1use self::error_contexts::GlobalErrorContextRefCount;
54use crate::component::func::{Func, call_post_return};
55use crate::component::store::ComponentInstanceId;
56use crate::component::{
57 HasData, HasSelf, Instance, Resource, ResourceTable, ResourceTableError, RuntimeInstance,
58};
59use crate::fiber::{self, StoreFiber, StoreFiberYield};
60use crate::hash_set::HashSet;
61#[cfg(feature = "gc")]
62use crate::module::ModuleRegistry;
63use crate::prelude::*;
64use crate::store::{Store, StoreId, StoreInner, StoreOpaque, StoreToken};
65#[cfg(feature = "gc")]
66use crate::vm::GcRootsList;
67use crate::vm::VMScope;
68use crate::vm::component::ScopeKind;
69use crate::vm::component::{
70 CallContext, ComponentInstance, CurrentScope, HandleCounter, HandleTableInsertion,
71 InstanceState,
72};
73use crate::vm::{
74 AlwaysMut, SendSyncPtr, UncaughtException, VMFuncRef, VMLazyThread, VMMemoryDefinition, VMStore,
75};
76use crate::{AsContext, AsContextMut, Result, StoreContext, StoreContextMut, ValRaw, bail};
77use crate::{Instance as ModuleInstance, bail_bug};
78use alloc::borrow::ToOwned;
79use alloc::collections::btree_map::Entry;
80use alloc::collections::{BTreeMap, BTreeSet, VecDeque};
81use core::any::Any;
82use core::cell::UnsafeCell;
83use core::fmt;
84use core::future;
85use core::future::Future;
86use core::marker::PhantomData;
87use core::mem::{self, ManuallyDrop, MaybeUninit};
88use core::ops::DerefMut;
89use core::pin::{Pin, pin};
90use core::ptr::{self, NonNull};
91use core::task::{Context, Poll, Waker};
92use futures::channel::oneshot;
93use futures::stream::{FuturesUnordered, StreamExt};
94use futures_and_streams::{FlatAbi, ReturnCode, TransmitHandle, TransmitIndex};
95use smallvec::SmallVec;
96use table::{TableDebug, TableId};
97use wasmtime_environ::component::{
98 CanonicalAbiInfo, CanonicalOptions, CanonicalOptionsDataModel, MAX_FLAT_PARAMS,
99 MAX_FLAT_RESULTS, OptionsIndex, PREPARE_ASYNC_NO_RESULT, PREPARE_ASYNC_WITH_RESULT,
100 RuntimeComponentInstanceIndex, RuntimeTableIndex, StringEncoding,
101 TypeComponentGlobalErrorContextTableIndex, TypeComponentLocalErrorContextTableIndex,
102 TypeFutureTableIndex, TypeStreamTableIndex, TypeTupleIndex,
103};
104use wasmtime_environ::packed_option::ReservedValue;
105use wasmtime_environ::{ModuleInternedTypeIndex, NUM_COMPONENT_CONTEXT_SLOTS, Trap};
106#[cfg(feature = "gc")]
107use wasmtime_unwinder::Unwind;
108
109pub use abort::JoinHandle;
110pub use func::{FuncCallConcurrent, TypedFuncCallConcurrent};
111pub use future_stream_any::{FutureAny, StreamAny};
112pub use futures_and_streams::{
113 Destination, DirectDestination, DirectSource, ErrorContext, FutureConsumer, FutureProducer,
114 FutureReader, GuardedFutureReader, GuardedStreamReader, ReadBuffer, Source, StreamConsumer,
115 StreamProducer, StreamReader, StreamResult, VecBuffer, WriteBuffer,
116};
117pub(crate) use futures_and_streams::{ResourcePair, lower_error_context_to_index};
118#[cfg(feature = "task-group-hook")]
119pub use task_group_hook::TaskGroupHook;
120pub use task_group_hook::TaskGroupId;
121
122mod abort;
123mod error_contexts;
124mod func;
125mod future_stream_any;
126mod futures_and_streams;
127pub(crate) mod table;
128#[cfg(feature = "task-group-hook")]
129mod task_group_hook;
130#[cfg(not(feature = "task-group-hook"))]
131mod task_group_hook_disabled;
132#[cfg(not(feature = "task-group-hook"))]
133use task_group_hook_disabled as task_group_hook;
134pub(crate) mod tls;
135
136const BLOCKED: u32 = 0xffff_ffff;
139
140#[derive(Clone, Copy, Eq, PartialEq, Debug)]
142pub enum Status {
143 Starting = 0,
144 Started = 1,
145 Returned = 2,
146 StartCancelled = 3,
147 ReturnCancelled = 4,
148}
149
150impl Status {
151 pub fn pack(self, waitable: Option<u32>) -> u32 {
157 assert!(matches!(self, Status::Returned) == waitable.is_none());
158 let waitable = waitable.unwrap_or(0);
159 assert!(waitable < (1 << 28));
160 (waitable << 4) | (self as u32)
161 }
162}
163
164#[derive(Clone, Copy, Debug)]
167enum Event {
168 None,
169 Subtask {
170 status: Status,
171 },
172 StreamRead {
173 code: ReturnCode,
174 pending: Option<(TypeStreamTableIndex, u32)>,
175 },
176 StreamWrite {
177 code: ReturnCode,
178 pending: Option<(TypeStreamTableIndex, u32)>,
179 },
180 FutureRead {
181 code: ReturnCode,
182 pending: Option<(TypeFutureTableIndex, u32)>,
183 },
184 FutureWrite {
185 code: ReturnCode,
186 pending: Option<(TypeFutureTableIndex, u32)>,
187 },
188 Cancelled,
189}
190
191impl Event {
192 fn parts(self) -> (u32, u32) {
197 const EVENT_NONE: u32 = 0;
198 const EVENT_SUBTASK: u32 = 1;
199 const EVENT_STREAM_READ: u32 = 2;
200 const EVENT_STREAM_WRITE: u32 = 3;
201 const EVENT_FUTURE_READ: u32 = 4;
202 const EVENT_FUTURE_WRITE: u32 = 5;
203 const EVENT_CANCELLED: u32 = 6;
204 match self {
205 Event::None => (EVENT_NONE, 0),
206 Event::Cancelled => (EVENT_CANCELLED, 0),
207 Event::Subtask { status } => (EVENT_SUBTASK, status as u32),
208 Event::StreamRead { code, .. } => (EVENT_STREAM_READ, code.encode()),
209 Event::StreamWrite { code, .. } => (EVENT_STREAM_WRITE, code.encode()),
210 Event::FutureRead { code, .. } => (EVENT_FUTURE_READ, code.encode()),
211 Event::FutureWrite { code, .. } => (EVENT_FUTURE_WRITE, code.encode()),
212 }
213 }
214}
215
216mod callback_code {
218 pub const EXIT: u32 = 0;
219 pub const YIELD: u32 = 1;
220 pub const WAIT: u32 = 2;
221}
222
223const START_FLAG_ASYNC_CALLEE: u32 = wasmtime_environ::component::START_FLAG_ASYNC_CALLEE as u32;
225const START_FLAG_ASYNC_CALLER: u32 = wasmtime_environ::component::START_FLAG_ASYNC_CALLER as u32;
226
227pub struct Access<'a, T: 'static, D: HasData + ?Sized = HasSelf<T>> {
233 store: StoreContextMut<'a, T>,
234 get_data: fn(&mut T) -> D::Data<'_>,
235}
236
237impl<'a, T, D> Access<'a, T, D>
238where
239 D: HasData + ?Sized,
240 T: 'static,
241{
242 pub fn new(store: StoreContextMut<'a, T>, get_data: fn(&mut T) -> D::Data<'_>) -> Self {
244 Self { store, get_data }
245 }
246
247 pub fn data_mut(&mut self) -> &mut T {
249 self.store.data_mut()
250 }
251
252 pub fn get(&mut self) -> D::Data<'_> {
254 (self.get_data)(self.data_mut())
255 }
256
257 pub fn spawn(&mut self, task: impl for<'fut> AccessorTask<'fut, T, D>) -> Result<JoinHandle>
261 where
262 T: 'static,
263 {
264 let accessor = Accessor {
265 get_data: self.get_data,
266 token: StoreToken::new(self.store.as_context_mut()),
267 };
268 self.store
269 .as_context_mut()
270 .spawn_with_accessor(accessor, task)
271 }
272
273 pub fn getter(&self) -> fn(&mut T) -> D::Data<'_> {
276 self.get_data
277 }
278}
279
280impl<'a, T, D> AsContext for Access<'a, T, D>
281where
282 D: HasData + ?Sized,
283 T: 'static,
284{
285 type Data = T;
286
287 fn as_context(&self) -> StoreContext<'_, T> {
288 self.store.as_context()
289 }
290}
291
292impl<'a, T, D> AsContextMut for Access<'a, T, D>
293where
294 D: HasData + ?Sized,
295 T: 'static,
296{
297 fn as_context_mut(&mut self) -> StoreContextMut<'_, T> {
298 self.store.as_context_mut()
299 }
300}
301
302pub struct Accessor<T: 'static, D = HasSelf<T>>
362where
363 D: HasData + ?Sized,
364{
365 token: StoreToken<T>,
366 get_data: fn(&mut T) -> D::Data<'_>,
367}
368
369pub trait AsAccessor {
386 type Data: 'static;
388
389 type AccessorData: HasData + ?Sized;
392
393 fn as_accessor(&self) -> &Accessor<Self::Data, Self::AccessorData>;
395}
396
397impl<T: AsAccessor + ?Sized> AsAccessor for &T {
398 type Data = T::Data;
399 type AccessorData = T::AccessorData;
400
401 fn as_accessor(&self) -> &Accessor<Self::Data, Self::AccessorData> {
402 T::as_accessor(self)
403 }
404}
405
406impl<T, D: HasData + ?Sized> AsAccessor for Accessor<T, D> {
407 type Data = T;
408 type AccessorData = D;
409
410 fn as_accessor(&self) -> &Accessor<T, D> {
411 self
412 }
413}
414
415const _: () = {
438 const fn assert<T: Send + Sync>() {}
439 assert::<Accessor<UnsafeCell<u32>>>();
440};
441
442impl<T> Accessor<T> {
443 pub(crate) fn new(token: StoreToken<T>) -> Self {
452 Self {
453 token,
454 get_data: |x| x,
455 }
456 }
457}
458
459impl<T, D> Accessor<T, D>
460where
461 D: HasData + ?Sized,
462{
463 pub fn with<R>(&self, fun: impl FnOnce(Access<'_, T, D>) -> R) -> R {
481 tls::get(|vmstore| {
482 fun(Access {
483 store: self.token.as_context_mut(vmstore),
484 get_data: self.get_data,
485 })
486 })
487 }
488
489 pub fn getter(&self) -> fn(&mut T) -> D::Data<'_> {
492 self.get_data
493 }
494
495 pub fn with_getter<D2: HasData>(
512 &self,
513 get_data: fn(&mut T) -> D2::Data<'_>,
514 ) -> Accessor<T, D2> {
515 Accessor {
516 token: self.token,
517 get_data,
518 }
519 }
520
521 pub fn spawn(&self, task: impl for<'fut> AccessorTask<'fut, T, D>) -> Result<JoinHandle>
537 where
538 T: 'static,
539 {
540 let accessor = self.clone_for_spawn();
541 self.with(|mut access| access.as_context_mut().spawn_with_accessor(accessor, task))
542 }
543
544 fn clone_for_spawn(&self) -> Self {
545 Self {
546 token: self.token,
547 get_data: self.get_data,
548 }
549 }
550
551 pub fn poll_no_interesting_tasks(&self, cx: &mut Context<'_>) -> Poll<()> {
587 self.with(|mut access| {
588 let store = access.as_context_mut().0;
589 let state = store.concurrent_state_mut_without_forcing_current_thread();
590 if state.interesting_tasks == 0 {
591 Poll::Ready(())
592 } else {
593 state.interesting_tasks_empty_waker = Some(cx.waker().clone());
594 Poll::Pending
595 }
596 })
597 }
598
599 pub fn poll_ready_for_concurrent_call(&self, func: Func, cx: &mut Context<'_>) -> Poll<()> {
623 self.with(|mut access| {
624 let store = access.as_context_mut().0;
625
626 {
627 let state = store.concurrent_state_mut_without_forcing_current_thread();
628 if state.switch_item.is_some()
629 || !state.high_priority.is_empty()
630 || !state.low_priority.is_empty()
631 {
632 state.idle_waker = Some(cx.waker().clone());
633 return Poll::Pending;
634 }
635 }
636
637 let (_, _, _, raw_options) = func.abi_info(store);
638 let instance = func.instance().runtime_instance(raw_options.instance);
639 let state = store.instance_state(instance).concurrent_state();
640 if state.backpressure == 0 {
641 Poll::Ready(())
642 } else {
643 store
644 .concurrent_state_mut_without_forcing_current_thread()
645 .backpressure_waker = Some(cx.waker().clone());
646 Poll::Pending
647 }
648 })
649 }
650}
651
652pub trait AccessorTask<'fut, T, D = HasSelf<T>>:
674 AsyncFnOnce(&Accessor<T, D>) -> Result<()> + Send + 'static
675where
676 D: HasData + ?Sized,
677{
678 fn run(self, accessor: &'fut Accessor<T, D>) -> impl Future<Output = Result<()>> + Send + 'fut;
680}
681
682impl<'fut, F, Fut, T, D> AccessorTask<'fut, T, D> for F
683where
684 T: 'static,
685 F: AsyncFnOnce(&Accessor<T, D>) -> Result<()>,
686 F: FnOnce(&'fut Accessor<T, D>) -> Fut + Send + 'static,
687 Fut: Future<Output = Result<()>> + Send + 'fut,
688 D: HasData,
689{
690 fn run(self, accessor: &'fut Accessor<T, D>) -> impl Future<Output = Result<()>> + Send + 'fut {
691 (self)(accessor)
692 }
693}
694
695enum CallerInfo {
698 Async {
700 params: Vec<ValRaw>,
701 has_result: bool,
702 },
703 Sync {
705 params: Vec<ValRaw>,
706 result_count: u32,
707 },
708}
709
710enum WaitMode {
712 Fiber(StoreFiber<'static>),
714 Callback(Instance),
717}
718
719impl fmt::Debug for WaitMode {
720 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
721 match self {
722 Self::Fiber(_) => f.debug_tuple("Fiber").finish(),
723 Self::Callback(instance) => f.debug_tuple("Callback").field(instance).finish(),
724 }
725 }
726}
727
728#[derive(Debug)]
730enum SuspendReason {
731 Waiting {
734 set: TableId<WaitableSet>,
735 thread: QualifiedThreadId,
736 },
737 YieldingToSubtask { thread: QualifiedThreadId },
740 NeedWork,
743 Yielding { thread: QualifiedThreadId },
746 ExplicitlySuspending { thread: QualifiedThreadId },
749}
750
751enum GuestCallKind {
753 DeliverEvent {
756 instance: Instance,
758 set: Option<TableId<WaitableSet>>,
763 },
764 StartImplicit {
767 closure: Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send + Sync>,
769 was_pending: bool,
771 },
772 StartExplicit(Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send + Sync>),
773}
774
775impl fmt::Debug for GuestCallKind {
776 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
777 match self {
778 Self::DeliverEvent { instance, set } => f
779 .debug_struct("DeliverEvent")
780 .field("instance", instance)
781 .field("set", set)
782 .finish(),
783 Self::StartImplicit { was_pending, .. } => f
784 .debug_struct("StartImplicit")
785 .field("was_pending", was_pending)
786 .finish(),
787 Self::StartExplicit(_) => f.debug_tuple("StartExplicit").finish(),
788 }
789 }
790}
791
792#[derive(Copy, Clone, Debug)]
794pub enum SuspensionTarget {
795 Resume(u32),
796 Promote(u32),
797 None,
798}
799
800#[derive(Copy, Clone, Debug)]
802pub enum ResumeThread {
803 Promote,
804 Resume,
805 ResumeLater,
806}
807
808#[derive(Debug)]
810struct GuestCall {
811 thread: QualifiedThreadId,
812 kind: GuestCallKind,
813}
814
815impl GuestCall {
816 fn is_ready(&self, store: &mut StoreOpaque) -> Result<bool> {
828 let task = store.concurrent_state_mut()?.get_mut(self.thread.task)?;
829 let async_typed = task.async_typed;
830 let async_lifted = task.async_lifted;
831 let has_callback = task.callback.is_some();
832 let instance = task.instance;
833 let state = store.instance_state(instance).concurrent_state();
834
835 let ready = match &self.kind {
836 GuestCallKind::DeliverEvent { .. } => !state.do_not_enter,
837 GuestCallKind::StartImplicit { was_pending, .. } => {
838 if async_typed {
839 let needs_exclusive = !async_lifted || has_callback;
842
843 let may_enter =
848 !((needs_exclusive && state.do_not_enter) || state.backpressure > 0);
849
850 let skip_wait = *was_pending || state.pending_start_count == 0;
857
858 may_enter && skip_wait
861 } else {
862 true
863 }
864 }
865 GuestCallKind::StartExplicit(_) => true,
866 };
867 log::trace!(
868 "call {self:?} ready? {ready} (do_not_enter: {}; backpressure: {}; pending_start_count: {})",
869 state.do_not_enter,
870 state.backpressure,
871 state.pending_start_count,
872 );
873 Ok(ready)
874 }
875}
876
877enum WorkerItem {
879 GuestCall(GuestCall),
880 Function(AlwaysMut<Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send>>),
881}
882
883enum WorkItem {
886 PushFuture(AlwaysMut<HostTaskFuture>),
888 ResumeFiber {
890 instance: RuntimeInstance,
891 thread: QualifiedThreadId,
892 fiber: StoreFiber<'static>,
893 },
894 ResumeThread {
896 instance: RuntimeInstance,
897 thread: QualifiedThreadId,
898 },
899 GuestCall {
901 instance: RuntimeInstance,
902 call: GuestCall,
903 },
904 WorkerFunction(AlwaysMut<Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send>>),
906}
907
908struct ResumingFiber<'a> {
914 store: &'a mut StoreOpaque,
915 fiber: Option<StoreFiber<'static>>,
916}
917
918impl Drop for ResumingFiber<'_> {
919 fn drop(&mut self) {
920 if let Some(mut fiber) = self.fiber.take() {
921 fiber.dispose(self.store);
922 }
923 }
924}
925
926impl fmt::Debug for WorkItem {
927 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
928 match self {
929 Self::PushFuture(_) => f.debug_tuple("PushFuture").finish(),
930 Self::ResumeFiber {
931 instance, thread, ..
932 } => f
933 .debug_struct("ResumeFiber")
934 .field("instance", instance)
935 .field("thread", thread)
936 .finish(),
937 Self::ResumeThread { instance, thread } => f
938 .debug_struct("ResumeThread")
939 .field("instance", instance)
940 .field("thread", thread)
941 .finish(),
942 Self::GuestCall { instance, call } => f
943 .debug_struct("GuestCall")
944 .field("instance", instance)
945 .field("call", call)
946 .finish(),
947 Self::WorkerFunction(_) => f.debug_tuple("WorkerFunction").finish(),
948 }
949 }
950}
951
952#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
954pub(crate) enum WaitResult {
955 Cancelled,
956 Completed,
957}
958
959pub(crate) fn poll_and_block<R: Send + Sync + 'static>(
967 store: &mut dyn VMStore,
968 host_task: EnteredHostTask,
969 future: impl Future<Output = Result<R>> + Send + 'static,
970) -> Result<R> {
971 let mut future = Box::pin(future);
978 let poll = tls::set(store, || {
979 future
980 .as_mut()
981 .poll(&mut Context::from_waker(&Waker::noop()))
982 });
983
984 let caller = match host_task {
985 Some(caller) => caller,
986 None => bail_bug!("host task wasn't created but should have been"),
987 };
988
989 let task = match poll {
990 Poll::Ready(result) => return result,
992
993 Poll::Pending => {
998 let Some(task) = store.materialize_host_task_id()? else {
999 bail_bug!("current thread is not a host thread")
1000 };
1001
1002 let future = Box::pin(async move {
1005 let result = run_with_host_task_set(task, future).await??;
1006 tls::get(move |store| {
1007 let state = store.concurrent_state_mut()?;
1008 let host_state = &mut state.get_mut(task)?.state;
1009 assert!(matches!(host_state, HostTaskState::CalleeStarted));
1010 *host_state = HostTaskState::CalleeFinished(Box::new(result));
1011
1012 Waitable::Host(task).set_event(
1013 state,
1014 Some(Event::Subtask {
1015 status: Status::Returned,
1016 }),
1017 )?;
1018
1019 Ok(())
1020 })
1021 }) as HostTaskFuture;
1022
1023 let caller_instance = store.concurrent_state_mut()?.get_mut(caller.task)?.instance;
1024 store.switch_or_trap_if_may_not_suspend(caller_instance)?;
1025
1026 let state = store.concurrent_state_mut()?;
1027 state.push_future(future);
1028
1029 let set = state.get_mut(caller.thread)?.sync_call_set;
1030 Waitable::Host(task).join(state, Some(set))?;
1031
1032 store.suspend(SuspendReason::Waiting {
1033 set,
1034 thread: caller,
1035 })?;
1036
1037 Waitable::Host(task).join(store.concurrent_state_mut()?, None)?;
1041 task
1042 }
1043 };
1044
1045 let host_state = &mut store.concurrent_state_mut()?.get_mut(task)?.state;
1047 match mem::replace(host_state, HostTaskState::CalleeDone { cancelled: false }) {
1048 HostTaskState::CalleeFinished(result) => Ok(match result.downcast() {
1049 Ok(result) => *result,
1050 Err(_) => bail_bug!("host task finished with wrong type of result"),
1051 }),
1052 _ => bail_bug!("unexpected host task state after completion"),
1053 }
1054}
1055
1056fn handle_guest_call(store: &mut dyn VMStore, call: GuestCall) -> Result<()> {
1058 match call.kind {
1059 GuestCallKind::DeliverEvent { instance, set } => {
1060 if let Some(set) = set {
1063 store.concurrent_state_mut()?.get_mut(set)?.stop_waiting()?;
1064 }
1065 let (event, waitable) = match instance.get_event(store, call.thread.task, set, true)? {
1066 Some(pair) => pair,
1067 None => match set {
1068 Some(set) => {
1073 log::trace!(
1074 "event for {:?} on {set:?} no longer present; waiting again",
1075 call.thread
1076 );
1077 return instance.wait_with_callback(&mut **store, call.thread, set);
1078 }
1079 None => (Event::None, None),
1084 },
1085 };
1086 let state = store.concurrent_state_mut()?;
1087 if let Some(set) = set
1092 && waitable.is_none()
1093 && !state.get_mut(set)?.ready.is_empty()
1094 {
1095 state.wake_waiter(set)?;
1096 }
1097 let task = state.get_mut(call.thread.task)?;
1098 let runtime_instance = task.instance;
1099 let handle = waitable.map(|(_, v)| v).unwrap_or(0);
1100
1101 log::trace!(
1102 "use callback to deliver event {event:?} to {:?} for {waitable:?}",
1103 call.thread,
1104 );
1105
1106 instance.handle_callback_code(store, call.thread, runtime_instance, |store| {
1107 invoke_callback(store, call.thread.task, event, handle)
1108 })?;
1109 }
1110 GuestCallKind::StartImplicit { closure, .. } => {
1111 closure(store)?;
1112 }
1113 GuestCallKind::StartExplicit(fun) => {
1114 fun(store)?;
1115 }
1116 }
1117
1118 Ok(())
1119}
1120
1121fn invoke_callback(
1124 store: &mut dyn VMStore,
1125 task: TableId<GuestTask>,
1126 event: Event,
1127 handle: u32,
1128) -> Result<u32> {
1129 let Some(callback) = store.concurrent_state_mut()?.get_mut(task)?.callback.take() else {
1130 bail_bug!("guest task callback field not present")
1131 };
1132
1133 let code = callback(store, event, handle)?;
1134
1135 store.concurrent_state_mut()?.get_mut(task)?.callback = Some(callback);
1136
1137 Ok(code)
1138}
1139
1140impl<T> Store<T> {
1141 pub async fn run_concurrent<R>(&mut self, fun: impl AsyncFnOnce(&Accessor<T>) -> R) -> Result<R>
1143 where
1144 T: Send + 'static,
1145 {
1146 ensure!(
1147 self.as_context().0.concurrency_support(),
1148 "cannot use `run_concurrent` when Config::concurrency_support disabled",
1149 );
1150 self.as_context_mut().run_concurrent(fun).await
1151 }
1152
1153 #[doc(hidden)]
1154 pub fn assert_concurrent_state_empty(&mut self) {
1155 self.as_context_mut().assert_concurrent_state_empty();
1156 }
1157
1158 #[doc(hidden)]
1159 pub fn concurrent_state_table_size(&mut self) -> usize {
1160 self.as_context_mut().concurrent_state_table_size()
1161 }
1162
1163 #[doc(hidden)]
1164 pub fn set_max_concurrent_state_table_capacity(&mut self, max: usize) {
1165 self.as_context_mut()
1166 .set_max_concurrent_state_table_capacity(max)
1167 }
1168
1169 pub fn spawn(
1171 &mut self,
1172 task: impl for<'fut> AccessorTask<'fut, T, HasSelf<T>>,
1173 ) -> Result<JoinHandle>
1174 where
1175 T: 'static,
1176 {
1177 self.as_context_mut().spawn(task)
1178 }
1179}
1180
1181impl<T> StoreContextMut<'_, T> {
1182 #[doc(hidden)]
1193 pub fn assert_concurrent_state_empty(self) {
1194 let store = self.0;
1195 store
1196 .store_data_mut()
1197 .components
1198 .assert_instance_states_empty();
1199 let state = store.concurrent_state_mut().unwrap();
1200 assert!(
1201 state.table.get_mut().is_empty(),
1202 "non-empty table: {:?}",
1203 state.table.get_mut()
1204 );
1205 assert!(state.switch_item.is_none());
1206 assert!(state.next_switch_item.is_none());
1207 assert!(state.high_priority.is_empty());
1208 assert!(state.low_priority.is_empty());
1209 assert!(state.saved_next_switch_items.is_empty());
1210 assert!(state.unforced_current_thread.is_none());
1211 assert!(state.deferred_host_call_context.is_none());
1212 assert!(state.futures_mut().unwrap().is_empty());
1213 assert!(state.global_error_context_ref_counts.is_empty());
1214 }
1215
1216 #[doc(hidden)]
1221 pub fn concurrent_state_table_size(&mut self) -> usize {
1222 self.0.concurrent_state_mut().unwrap().table.get_mut().len()
1223 }
1224
1225 #[doc(hidden)]
1231 pub fn set_max_concurrent_state_table_capacity(&mut self, max: usize) {
1232 self.0
1233 .concurrent_state_mut_without_forcing_current_thread()
1234 .table
1235 .get_mut()
1236 .set_max_capacity(max);
1237 }
1238
1239 pub fn spawn(mut self, task: impl for<'fut> AccessorTask<'fut, T>) -> Result<JoinHandle>
1249 where
1250 T: 'static,
1251 {
1252 let accessor = Accessor::new(StoreToken::new(self.as_context_mut()));
1253 self.spawn_with_accessor(accessor, task)
1254 }
1255
1256 fn spawn_with_accessor<D>(
1259 self,
1260 accessor: Accessor<T, D>,
1261 task: impl for<'fut> AccessorTask<'fut, T, D>,
1262 ) -> Result<JoinHandle>
1263 where
1264 T: 'static,
1265 D: HasData + ?Sized,
1266 {
1267 let (handle, future) = JoinHandle::run(async move { task.run(&accessor).await });
1271 self.0
1272 .concurrent_state_mut()?
1273 .push_future(Box::pin(async move { future.await.unwrap_or(Ok(())) }));
1274 Ok(handle)
1275 }
1276
1277 pub async fn run_concurrent<R>(self, fun: impl AsyncFnOnce(&Accessor<T>) -> R) -> Result<R>
1361 where
1362 T: Send + 'static,
1363 {
1364 ensure!(
1365 self.0.concurrency_support(),
1366 "cannot use `run_concurrent` when Config::concurrency_support disabled",
1367 );
1368 self.do_run_concurrent(fun, false).await
1369 }
1370
1371 pub(super) async fn run_concurrent_trap_on_idle<R>(
1372 self,
1373 fun: impl AsyncFnOnce(&Accessor<T>) -> R,
1374 ) -> Result<R> {
1375 self.do_run_concurrent(fun, true).await
1376 }
1377
1378 async fn do_run_concurrent<R>(
1379 mut self,
1380 fun: impl AsyncFnOnce(&Accessor<T>) -> R,
1381 trap_on_idle: bool,
1382 ) -> Result<R> {
1383 debug_assert!(self.0.concurrency_support());
1384 self.0.check_event_loop_not_running()?;
1385
1386 self.0.concurrent_state_mut()?.materialize_host_task()?;
1391
1392 let token = StoreToken::new(self.as_context_mut());
1393
1394 struct Dropper<'a, T: 'static, V> {
1395 store: StoreContextMut<'a, T>,
1396 value: ManuallyDrop<V>,
1397 }
1398
1399 impl<'a, T, V> Drop for Dropper<'a, T, V> {
1400 fn drop(&mut self) {
1401 self.store
1402 .0
1403 .concurrent_state_mut_already_forced_current_thread()
1404 .event_loop_running = false;
1405
1406 tls::set(self.store.0, || {
1407 unsafe { ManuallyDrop::drop(&mut self.value) }
1412 });
1413 }
1414 }
1415
1416 let accessor = &Accessor::new(token);
1417 self.0
1418 .concurrent_state_mut_already_forced_current_thread()
1419 .event_loop_running = true;
1420 let dropper = &mut Dropper {
1421 store: self,
1422 value: ManuallyDrop::new(fun(accessor)),
1423 };
1424 let future = unsafe { Pin::new_unchecked(dropper.value.deref_mut()) };
1426
1427 let result = dropper
1428 .store
1429 .as_context_mut()
1430 .poll_until(future, trap_on_idle)
1431 .await;
1432
1433 if result.is_err() {
1434 dropper.store.0.set_trapped();
1435 }
1436
1437 result
1438 }
1439
1440 async fn poll_until<R>(
1446 mut self,
1447 mut future: Pin<&mut impl Future<Output = R>>,
1448 trap_on_idle: bool,
1449 ) -> Result<R> {
1450 struct Reset<'a, T: 'static> {
1451 store: StoreContextMut<'a, T>,
1452 futures: Option<FuturesUnordered<HostTaskFuture>>,
1453 }
1454
1455 impl<'a, T> Drop for Reset<'a, T> {
1456 fn drop(&mut self) {
1457 if let Some(futures) = self.futures.take() {
1458 *self
1459 .store
1460 .0
1461 .concurrent_state_mut_already_forced_current_thread()
1462 .futures
1463 .get_mut() = Some(futures);
1464 }
1465 }
1466 }
1467
1468 const MAX_TURNS_WITHOUT_YIELD: usize = 128;
1472 let mut turns_without_yield = 0;
1473
1474 loop {
1475 let futures = self.0.concurrent_state_mut()?.futures.get_mut().take();
1479 let mut reset = Reset {
1480 store: self.as_context_mut(),
1481 futures,
1482 };
1483 let mut next = match reset.futures.as_mut() {
1484 Some(f) => pin!(f.next()),
1485 None => bail!(Trap::CannotEnterComponent),
1488 };
1489
1490 enum PollResult<R> {
1491 Complete(R),
1492 ProcessWork {
1493 ready: Option<WorkItem>,
1494 low_priority: bool,
1495 },
1496 }
1497
1498 let result = future::poll_fn(|cx| {
1499 if let Poll::Ready(value) = tls::set(reset.store.0, || future.as_mut().poll(cx)) {
1502 return Poll::Ready(Ok(PollResult::Complete(value)));
1503 }
1504
1505 if reset.store.0.component_trapped() {
1514 return Poll::Ready(Err(Trap::CannotEnterComponent.into()));
1515 }
1516
1517 let next = match tls::set(reset.store.0, || next.as_mut().poll(cx)) {
1521 Poll::Ready(Some(output)) => {
1522 match output {
1523 Err(e) => return Poll::Ready(Err(e)),
1524 Ok(()) => {}
1525 }
1526 Poll::Ready(true)
1527 }
1528 Poll::Ready(None) => Poll::Ready(false),
1529 Poll::Pending => Poll::Pending,
1530 };
1531
1532 let state = reset.store.0.concurrent_state_mut()?;
1547 let mut ready = state.switch_item.take();
1548 let mut low_priority = false;
1549 if ready.is_none() {
1550 ready = state.high_priority.pop_back();
1551 if ready.is_none() {
1552 ready = state.low_priority.pop_back();
1553 low_priority = true;
1554 }
1555 }
1556 if ready.is_some() {
1557 return Poll::Ready(Ok(PollResult::ProcessWork {
1558 ready,
1559 low_priority,
1560 }));
1561 }
1562
1563 if let Some(waker) = state.idle_waker.take() {
1564 waker.wake();
1565 }
1566
1567 return match next {
1571 Poll::Ready(true) => {
1572 Poll::Ready(Ok(PollResult::ProcessWork {
1578 ready: None,
1579 low_priority: false,
1580 }))
1581 }
1582 Poll::Ready(false) => {
1583 if let Poll::Ready(value) =
1587 tls::set(reset.store.0, || future.as_mut().poll(cx))
1588 {
1589 Poll::Ready(Ok(PollResult::Complete(value)))
1590 } else {
1591 if trap_on_idle {
1597 Poll::Ready(Err(if reset.store.0.any_may_not_suspend()? {
1604 Trap::CannotBlockSyncTask.into()
1605 } else {
1606 Trap::AsyncDeadlock.into()
1608 }))
1609 } else {
1610 Poll::Pending
1614 }
1615 }
1616 }
1617 Poll::Pending => Poll::Pending,
1622 };
1623 })
1624 .await;
1625
1626 drop(reset);
1630
1631 match result? {
1632 PollResult::Complete(value) => break Ok(value),
1635 PollResult::ProcessWork {
1638 mut ready,
1639 low_priority,
1640 } => {
1641 if low_priority {
1669 if let Some(item) = ready.take() {
1670 self.0.concurrent_state_mut()?.low_priority.push_back(item);
1671 }
1672 self.0.yield_now().await;
1673 turns_without_yield = 0;
1674 ready = self.0.concurrent_state_mut()?.low_priority.pop_back();
1675 }
1676
1677 if let Some(item) = ready {
1678 self.as_context_mut().handle_work_item(item).await?;
1679 }
1680
1681 turns_without_yield += 1;
1682 if turns_without_yield == MAX_TURNS_WITHOUT_YIELD {
1683 turns_without_yield = 0;
1684 self.0.yield_now().await;
1685 }
1686 }
1687 }
1688 }
1689 }
1690
1691 fn handle_work_item(self, item: WorkItem) -> impl Future<Output = Result<()>> {
1693 let item = match item {
1697 WorkItem::ResumeFiber {
1698 instance,
1699 thread,
1700 fiber,
1701 } => {
1702 let future = self.0.resume_fiber(fiber);
1703 log::trace!(
1704 "handle work item ResumeFiber {{ instance: {instance:?}, thread: {thread:?} }}"
1705 );
1706 return futures::future::Either::Left(future);
1707 }
1708 item => item,
1709 };
1710 futures::future::Either::Right(async move {
1711 log::trace!("handle work item {item:?}");
1712 match item {
1713 WorkItem::PushFuture(future) => {
1714 self.0
1715 .concurrent_state_mut()?
1716 .futures_mut()?
1717 .push(future.into_inner());
1718 }
1719 WorkItem::ResumeFiber { .. } => unreachable!(),
1720 WorkItem::ResumeThread { thread, .. } => {
1721 let slot = &mut self.0.concurrent_state_mut()?.get_mut(thread.thread)?.state;
1722 if !matches!(slot, GuestThreadState::Ready { .. }) {
1723 bail_bug!("cannot resume non-pending thread {thread:?}");
1724 }
1725 let GuestThreadState::Ready { fiber } =
1726 mem::replace(slot, GuestThreadState::Running)
1727 else {
1728 unreachable!()
1729 };
1730 self.0.resume_fiber(fiber).await?;
1731 }
1732 WorkItem::GuestCall { mut call, .. } => {
1733 if call.is_ready(self.0)? {
1734 if let GuestCallKind::StartImplicit {
1735 was_pending: true, ..
1736 } = &call.kind
1737 {
1738 let instance = self
1739 .0
1740 .concurrent_state_mut()?
1741 .get_mut(call.thread.task)?
1742 .instance;
1743
1744 self.0.decrement_pending_start_count(instance, 1)?;
1745 }
1746
1747 self.0
1748 .concurrent_state_mut()?
1749 .get_mut(call.thread.thread)?
1750 .wake_on_cancel = WakeOnCancel::None;
1751
1752 self.run_on_worker(WorkerItem::GuestCall(call)).await?;
1753 } else {
1754 let state = self.0.concurrent_state_mut()?;
1755 let task = state.get_mut(call.thread.task)?;
1756 if !task.starting_sent {
1757 task.starting_sent = true;
1758 if let GuestCallKind::StartImplicit { .. } = &call.kind {
1759 Waitable::Guest(call.thread.task).set_event(
1760 state,
1761 Some(Event::Subtask {
1762 status: Status::Starting,
1763 }),
1764 )?;
1765 }
1766 }
1767
1768 let increment = if let GuestCallKind::StartImplicit {
1769 was_pending, ..
1770 } = &mut call.kind
1771 {
1772 let increment = !*was_pending;
1773 *was_pending = true;
1774 increment
1775 } else {
1776 false
1777 };
1778
1779 let instance = state.get_mut(call.thread.task)?.instance;
1780 if let GuestCallKind::DeliverEvent { set: Some(set), .. } = &call.kind {
1789 if !state.get_mut(*set)?.ready.is_empty() {
1790 state.wake_waiter(*set)?;
1791 }
1792 }
1793
1794 state.take_next_switch_item()?;
1798
1799 let requeue = increment && call.is_ready(self.0)?;
1816
1817 if increment {
1818 self.0
1819 .instance_state(instance)
1820 .concurrent_state()
1821 .pending_start_count += 1;
1822 }
1823
1824 if requeue {
1825 self.0
1826 .concurrent_state_mut()?
1827 .push_high_priority(WorkItem::GuestCall { instance, call });
1828 } else {
1829 self.0
1830 .instance_state(instance)
1831 .concurrent_state()
1832 .pending
1833 .insert(call.thread, call.kind);
1834 }
1835 }
1836 }
1837 WorkItem::WorkerFunction(fun) => {
1838 self.run_on_worker(WorkerItem::Function(fun)).await?;
1839 }
1840 }
1841
1842 Ok(())
1843 })
1844 }
1845
1846 async fn run_on_worker(self, item: WorkerItem) -> Result<()> {
1848 let state = self.0.concurrent_state_mut()?;
1849 if state.worker_item.is_some() {
1850 bail_bug!("worker item already set when taking worker fiber");
1851 }
1852 let worker = if let Some(fiber) = state.worker.take() {
1853 fiber
1854 } else {
1855 unsafe {
1874 fiber::make_fiber_unchecked(self.0, move |store| {
1875 loop {
1876 let Some(item) = store.concurrent_state_mut()?.worker_item.take() else {
1877 bail_bug!("worker_item not present when resuming fiber")
1878 };
1879 match item {
1880 WorkerItem::GuestCall(call) => handle_guest_call(store, call)?,
1881 WorkerItem::Function(fun) => fun.into_inner()(store)?,
1882 }
1883
1884 store.suspend(SuspendReason::NeedWork)?;
1885 }
1886 })?
1887 }
1888 };
1889
1890 self.0
1893 .concurrent_state_mut_already_forced_current_thread()
1894 .worker_item = Some(item);
1895
1896 self.0.resume_fiber(worker).await
1897 }
1898
1899 pub(crate) fn wrap_call<F, R>(self, closure: F) -> impl Future<Output = Result<R>> + 'static
1904 where
1905 T: 'static,
1906 F: FnOnce(&Accessor<T>) -> Pin<Box<dyn Future<Output = Result<R>> + Send + '_>>
1907 + Send
1908 + Sync
1909 + 'static,
1910 R: Send + Sync + 'static,
1911 {
1912 let token = StoreToken::new(self);
1913 async move {
1914 let mut accessor = Accessor::new(token);
1915 closure(&mut accessor).await
1916 }
1917 }
1918
1919 pub(crate) async fn start_instance(
1920 &mut self,
1921 instance: ModuleInstance,
1922 callee: Option<RuntimeInstance>,
1923 ) -> Result<ModuleInstance> {
1924 self.0.check_event_loop_not_running()?;
1926 let (tx, rx) = oneshot::channel();
1927 let token = StoreToken::new(self.as_context_mut());
1928 self.0.queue_task(move |store| {
1929 _ = tx.send(
1930 super::instance::start_raw(&mut token.as_context_mut(store), instance, callee)
1931 .map(|()| instance),
1932 );
1933 Ok(())
1934 })?;
1935 self.as_context_mut()
1936 .run_concurrent_trap_on_idle(async |_| {
1937 rx.await
1938 .map_err(|_| format_err!("oneshot channel canceled"))
1939 })
1940 .await??
1941 }
1942}
1943
1944pub type EnteredHostTask = Option<QualifiedThreadId>;
1951
1952impl StoreOpaque {
1953 pub(crate) fn check_event_loop_not_running(&mut self) -> Result<()> {
1954 if self
1955 .concurrent_state_mut_already_forced_current_thread()
1956 .event_loop_running
1957 {
1958 bail!("Recursive `StoreContextMut::run_concurrent` calls not supported")
1959 }
1960 Ok(())
1961 }
1962
1963 #[inline]
1967 pub(crate) fn current_thread(&mut self) -> Result<CurrentThread> {
1968 if !self.concurrency_support() {
1970 return Ok(CurrentThread::None);
1971 }
1972
1973 if !self
1976 .vm_store_context_mut()
1977 .current_thread_mut()
1978 .is_deferred()
1979 {
1980 return Ok(self
1981 .concurrent_state_mut_already_forced_current_thread()
1982 .unforced_current_thread);
1983 }
1984
1985 self.force_deferred_current_thread()
1986 }
1987
1988 #[cold]
1991 fn force_deferred_current_thread(&mut self) -> Result<CurrentThread> {
1992 let state = self.concurrent_state_mut_without_forcing_current_thread();
2001 let id = match state.unforced_current_thread.guest_task() {
2002 Some(task) => state.get_mut(task)?.instance.instance,
2003 None => bail_bug!("deferred component-model thread with non-guest base"),
2004 };
2005
2006 let mut frames = SmallVec::<[_; 8]>::new();
2009 let mut cur = *self.vm_store_context_mut().current_thread_mut();
2010 while let Some(ptr) = cur.as_deferred() {
2011 let deferred = unsafe { ptr.as_non_null().as_ref() };
2016 frames.push((
2017 deferred.callee_async != 0,
2018 deferred.callee_instance,
2019 deferred.saved_context,
2020 deferred.lazy_lenders_start,
2021 ));
2022 cur = deferred.parent;
2023 }
2024
2025 *self.vm_store_context_mut().current_thread_mut() = VMLazyThread::forced();
2029
2030 let current_context = *self.vm_store_context_mut().component_context_mut();
2033
2034 let lazy_lenders_end = *self.vm_store_context_mut().lazy_lenders_len_mut();
2041 frames.reverse();
2042 let lazy_lenders_base = match frames.first() {
2043 Some((_, _, _, start)) => *start,
2044 None => bail_bug!("forcing a deferred thread with no deferred frames"),
2045 };
2046 let lazy_lender_ends = frames
2047 .iter()
2048 .skip(1)
2049 .map(|(_, _, _, start)| *start)
2050 .chain([lazy_lenders_end])
2051 .collect::<SmallVec<[_; 8]>>();
2052 for ((callee_async, callee_instance, saved_context, start), lenders_end) in
2053 frames.into_iter().zip(lazy_lender_ends)
2054 {
2055 *self.vm_store_context_mut().component_context_mut() = saved_context;
2059 let callee = RuntimeInstance {
2060 instance: id,
2061 index: RuntimeComponentInstanceIndex::from_u32(callee_instance),
2062 };
2063 self.enter_guest_sync_call(callee_async, callee)?;
2064
2065 self.promote_current_lazy_lends(id, start, lenders_end)?;
2068 }
2069
2070 debug_assert_eq!(
2073 *self.vm_store_context_mut().lazy_lenders_len_mut(),
2074 lazy_lenders_end
2075 );
2076 *self.vm_store_context_mut().lazy_lenders_len_mut() = lazy_lenders_base;
2077
2078 *self.vm_store_context_mut().component_context_mut() = current_context;
2080
2081 Ok(self
2082 .concurrent_state_mut_without_forcing_current_thread()
2083 .unforced_current_thread)
2084 }
2085
2086 fn promote_current_lazy_lends(
2092 &mut self,
2093 id: ComponentInstanceId,
2094 start: usize,
2095 end: usize,
2096 ) -> Result<()> {
2097 if start == end {
2098 return Ok(());
2099 }
2100
2101 let scope = match self
2102 .concurrent_state_mut_without_forcing_current_thread()
2103 .unforced_current_thread
2104 .guest_task()
2105 {
2106 Some(task) => VMScope::id(task.rep()),
2107 None => bail_bug!("replayed deferred frame is not a guest thread"),
2108 };
2109 let instance = Instance::from_wasmtime(self, id);
2110 self.promote_lazy_lends(instance, scope, start, end)
2111 }
2112
2113 fn current_guest_thread(&mut self) -> Result<QualifiedThreadId> {
2114 match self.current_thread()?.guest() {
2115 Some(id) => Ok(*id),
2116 None => bail_bug!("current thread is not a guest thread"),
2117 }
2118 }
2119
2120 pub(crate) fn current_materialized_host_task(&mut self) -> Result<Option<TableId<HostTask>>> {
2124 match self.current_thread()? {
2125 CurrentThread::Host(id) => Ok(Some(id)),
2126 CurrentThread::DeferredHost(_) | CurrentThread::None => Ok(None),
2127 _ => bail_bug!("current thread is not a host thread"),
2128 }
2129 }
2130
2131 fn materialize_host_task_id(&mut self) -> Result<Option<TableId<HostTask>>> {
2134 Ok(self
2135 .concurrent_state_mut()?
2136 .materialize_current_host_task_id()?)
2137 }
2138
2139 fn enter_sync_call(&mut self, callee: RuntimeInstance) -> Result<()> {
2140 log::trace!("enter sync-typed call {callee:?}");
2141 let state = self.instance_state(callee).concurrent_state();
2142 let old_do_not_suspend = state.do_not_suspend;
2143 state.do_not_suspend = true;
2144
2145 let thread = self.current_guest_thread()?;
2146 let thread = self.concurrent_state_mut()?.get_mut(thread.thread)?;
2147 if thread.old_do_not_suspend.is_some() {
2148 bail_bug!("current thread already has `old_do_not_suspend` value");
2149 }
2150
2151 thread.old_do_not_suspend = Some(old_do_not_suspend);
2152
2153 Ok(())
2154 }
2155
2156 fn exit_sync_call(&mut self, callee: RuntimeInstance) -> Result<()> {
2157 log::trace!("exit sync-typed call {callee:?}");
2158 let thread = self.current_guest_thread()?;
2159 let thread = self.concurrent_state_mut()?.get_mut(thread.thread)?;
2160 let Some(old_do_not_suspend) = thread.old_do_not_suspend.take() else {
2161 bail_bug!("current thread missing `old_do_not_suspend` value");
2162 };
2163 let state = self.instance_state(callee).concurrent_state();
2164 state.do_not_suspend = old_do_not_suspend;
2165 Ok(())
2166 }
2167
2168 pub(crate) fn enter_guest_sync_call(
2180 &mut self,
2181 callee_async_typed: bool,
2182 callee: RuntimeInstance,
2183 ) -> Result<()> {
2184 log::trace!("enter sync-lifted call {callee:?}");
2185 if !self.concurrency_support() {
2186 return self.enter_call_not_concurrent();
2187 }
2188
2189 let state = self.concurrent_state_mut()?;
2193 let item = state.next_switch_item.take();
2194 state.saved_next_switch_items.push(item);
2195
2196 let thread = self.current_thread()?;
2197 let caller = if let Some(thread) = thread.guest() {
2198 Caller::Guest { thread: *thread }
2199 } else {
2200 Caller::Host {
2201 tx: None,
2202 caller: self.materialize_host_task_id()?,
2203 }
2204 };
2205
2206 let state = self.concurrent_state_mut()?;
2207 let guest_thread = GuestTask::new(
2208 state,
2209 Box::new(move |_, _| bail_bug!("cannot lower params in sync call")),
2210 LiftResult {
2211 lift: Box::new(move |_, _| bail_bug!("cannot lift result in sync call")),
2212 ty: TypeTupleIndex::reserved_value(),
2213 memory: None,
2214 string_encoding: StringEncoding::Utf8,
2215 },
2216 caller,
2217 None,
2218 callee,
2219 callee_async_typed,
2220 false,
2221 )?;
2222
2223 Instance::from_wasmtime(self, callee.instance).add_guest_thread_to_instance_table(
2224 guest_thread.thread,
2225 self,
2226 callee.index,
2227 )?;
2228 self.set_thread(guest_thread)?;
2229
2230 if !callee_async_typed {
2231 self.enter_sync_call(callee)?;
2232 }
2233
2234 Ok(())
2235 }
2236
2237 pub(crate) fn exit_guest_sync_call(&mut self) -> Result<()> {
2245 if !self.concurrency_support() {
2246 return Ok(self.exit_call_not_concurrent());
2247 }
2248
2249 let thread = match self.current_thread()?.guest() {
2250 Some(t) => *t,
2251 None => bail_bug!("expected task when exiting"),
2252 };
2253 let task = self.concurrent_state_mut()?.get_mut(thread.task)?;
2254 let instance = task.instance;
2255
2256 let caller = match &task.caller {
2257 &Caller::Guest { thread } => thread.into(),
2258 &Caller::Host { caller, .. } => caller
2259 .map(CurrentThread::Host)
2260 .unwrap_or(CurrentThread::None),
2261 };
2262 task.lift_result = None;
2263 task.exited = true;
2264 let async_typed = task.async_typed;
2265
2266 if !async_typed {
2267 self.exit_sync_call(instance)?;
2268 }
2269
2270 self.set_thread(caller)?;
2271
2272 log::trace!("exit sync-lifted call {instance:?}");
2273
2274 if async_typed {
2275 self.switch_or_trap_if_may_not_suspend(instance)?;
2280 }
2281
2282 self.cleanup_thread(thread, instance)?;
2283
2284 self.concurrent_state_mut()?
2285 .decrement_task_ref_count(thread.task)?;
2286
2287 let state = self.concurrent_state_mut()?;
2288 let Some(item) = state.saved_next_switch_items.pop() else {
2289 bail_bug!("unable to pop from `saved_next_switch_items`");
2290 };
2291 if let Some(item) = mem::replace(&mut state.next_switch_item, item) {
2292 state.push_high_priority(item);
2295 bail_bug!("`next_switch_item` unexpectedly already set");
2296 }
2297
2298 Ok(())
2299 }
2300
2301 pub(crate) fn host_task_create(&mut self) -> Result<EnteredHostTask> {
2308 if !self.concurrency_support() {
2309 self.enter_call_not_concurrent()?;
2310 return Ok(None);
2311 }
2312 let caller = self.current_guest_thread()?;
2313 log::trace!("new deferred host task with caller {caller:?}");
2314
2315 self.set_thread(CurrentThread::DeferredHost(caller))?;
2316 let state = self.concurrent_state_mut()?;
2317 debug_assert!(state.deferred_host_call_context.is_none());
2318 state.deferred_host_call_context = Some(CallContext::default());
2319 state.debug_assert_deferred_host_invariant();
2320 Ok(Some(caller))
2321 }
2322
2323 pub(crate) fn host_task_delete(
2330 &mut self,
2331 original_task: EnteredHostTask,
2332 materialized_task: Option<TableId<HostTask>>,
2333 ) -> Result<()> {
2334 match original_task {
2335 Some(caller) => {
2336 self.set_thread(caller)?;
2337 if materialized_task.is_none() {
2338 let state = self.concurrent_state_mut()?;
2339 let context = state
2340 .deferred_host_call_context
2341 .take()
2342 .expect("deferred host call context should be present");
2343 debug_assert!(context.is_empty());
2344 state.debug_assert_deferred_host_invariant();
2345 }
2346 log::trace!(
2347 "delete host task with caller {original_task:?} and materialized as {materialized_task:?}"
2348 );
2349 if let Some(task) = materialized_task {
2350 self.concurrent_state_mut()?.delete_host_task(task)?;
2351 }
2352 }
2353 None => {
2354 debug_assert!(materialized_task.is_none());
2355 self.exit_call_not_concurrent();
2356 }
2357 }
2358 Ok(())
2359 }
2360
2361 fn instance_state(&mut self, instance: RuntimeInstance) -> &mut InstanceState {
2364 self.component_instance_mut(instance.instance)
2365 .instance_state(instance.index)
2366 }
2367
2368 fn instance_state_and_handle_counter(
2371 &mut self,
2372 instance: RuntimeInstance,
2373 ) -> (&mut InstanceState, &mut HandleCounter) {
2374 let (component, counter) = self
2375 .store_data_mut()
2376 .component_instance_and_handle_counter_mut(instance.instance);
2377 (component.instance_state(instance.index), counter)
2378 }
2379
2380 fn handle_table_insertion(&mut self, instance: RuntimeInstance) -> HandleTableInsertion<'_> {
2382 let (component, counter) = self
2383 .store_data_mut()
2384 .component_instance_and_handle_counter_mut(instance.instance);
2385 component.handle_table_insertion(instance.index, counter)
2386 }
2387
2388 pub(crate) fn set_thread(&mut self, thread: impl Into<CurrentThread>) -> Result<CurrentThread> {
2394 let thread = thread.into();
2395 let state = self.concurrent_state_mut()?;
2396 state.debug_assert_deferred_host_invariant();
2397 let old_thread = mem::replace(&mut state.unforced_current_thread, thread);
2398
2399 state.handle_thread_switch(old_thread, thread)?;
2400
2401 if let Some(old_thread) = old_thread.guest() {
2409 let old_context = *self.vm_store_context_mut().component_context_mut();
2410 self.concurrent_state_mut()?
2411 .get_mut(old_thread.thread)?
2412 .context = old_context;
2413 }
2414 if cfg!(debug_assertions) {
2415 *self.vm_store_context_mut().component_context_mut() =
2416 [u32::MAX; NUM_COMPONENT_CONTEXT_SLOTS];
2417 }
2418 if let Some(thread) = thread.guest() {
2419 let thread = self.concurrent_state_mut()?.get_mut(thread.thread)?;
2420 let context = thread.context;
2421 if cfg!(debug_assertions) {
2422 thread.context = [u32::MAX; NUM_COMPONENT_CONTEXT_SLOTS];
2423 }
2424 *self.vm_store_context_mut().component_context_mut() = context;
2425 }
2426
2427 *self.vm_store_context_mut().current_thread_mut() = if thread.is_none() {
2429 VMLazyThread::none()
2430 } else {
2431 VMLazyThread::forced()
2432 };
2433
2434 Ok(old_thread)
2435 }
2436
2437 fn switch_or_trap_if_may_not_suspend(&mut self, instance: RuntimeInstance) -> Result<()> {
2439 if self.switch_if_may_not_suspend(instance)? {
2440 Ok(())
2441 } else {
2442 Err(Trap::CannotBlockSyncTask.into())
2443 }
2444 }
2445
2446 fn switch_if_may_not_suspend(&mut self, instance: RuntimeInstance) -> Result<bool> {
2450 self.concurrent_state_mut()?;
2454
2455 Ok(!self.concurrency_support()
2456 || !self
2457 .instance_state(instance)
2458 .concurrent_state()
2459 .do_not_suspend
2460 || self
2461 .concurrent_state_mut()?
2462 .promote_instance_local_thread_work_item(instance)?)
2463 }
2464
2465 fn enter_instance(&mut self, instance: RuntimeInstance) {
2469 log::trace!("enter {instance:?}");
2470 self.instance_state(instance)
2471 .concurrent_state()
2472 .do_not_enter = true;
2473 }
2474
2475 fn exit_instance(&mut self, instance: RuntimeInstance) -> Result<()> {
2479 log::trace!("exit {instance:?}");
2480 self.instance_state(instance)
2481 .concurrent_state()
2482 .do_not_enter = false;
2483 self.partition_pending(instance)
2484 }
2485
2486 fn partition_pending(&mut self, instance: RuntimeInstance) -> Result<()> {
2493 let mut any_ready = false;
2494 for (thread, kind) in
2495 mem::take(&mut self.instance_state(instance).concurrent_state().pending)
2496 {
2497 let call = GuestCall { thread, kind };
2498 if call.is_ready(self)? {
2499 any_ready = true;
2500 self.concurrent_state_mut()?
2501 .push_high_priority(WorkItem::GuestCall { instance, call });
2502 } else {
2503 self.instance_state(instance)
2504 .concurrent_state()
2505 .pending
2506 .insert(call.thread, call.kind);
2507 }
2508 }
2509
2510 if any_ready {
2511 if let Some(waker) = self.concurrent_state_mut()?.backpressure_waker.take() {
2512 waker.wake();
2513 }
2514 }
2515
2516 Ok(())
2517 }
2518
2519 pub(crate) fn backpressure_modify(
2521 &mut self,
2522 caller_instance: RuntimeInstance,
2523 modify: impl FnOnce(u16) -> Option<u16>,
2524 ) -> Result<()> {
2525 let state = self.instance_state(caller_instance).concurrent_state();
2526 let old = state.backpressure;
2527 let new = modify(old).ok_or_else(|| Trap::BackpressureOverflow)?;
2528 state.backpressure = new;
2529
2530 log::trace!("backpressure update for {caller_instance:?} from {old} to {new}");
2531
2532 if old > 0 && new == 0 {
2533 self.partition_pending(caller_instance)?;
2536 }
2537
2538 Ok(())
2539 }
2540
2541 fn resume_fiber(
2544 &mut self,
2545 fiber: StoreFiber<'static>,
2546 ) -> impl Future<Output = Result<()>> + '_ {
2547 let mut resuming = ResumingFiber {
2548 store: self,
2549 fiber: Some(fiber),
2550 };
2551 async move {
2552 let old_thread = resuming.store.current_thread()?;
2553 log::trace!("resume_fiber: save current thread {old_thread:?}");
2554
2555 let fiber = resuming.fiber.take().unwrap();
2556 resuming.fiber = fiber::resolve_or_release(resuming.store, fiber).await?;
2557
2558 resuming.store.set_thread(old_thread)?;
2559
2560 let state = resuming.store.concurrent_state_mut()?;
2561
2562 if let Some(ot) = old_thread.guest() {
2563 state.set_thread_running(ot.thread)?;
2564 }
2565 log::trace!("resume_fiber: restore current thread {old_thread:?}");
2566
2567 if resuming.fiber.is_some() {
2568 log::trace!("resume_fiber: suspend reason {:?}", &state.suspend_reason);
2569 let reason = match state.suspend_reason.take() {
2571 Some(r) => r,
2572 None => bail_bug!("suspend reason missing when resuming fiber"),
2573 };
2574 match reason {
2575 SuspendReason::NeedWork => {
2576 if state.worker.is_none() {
2577 state.worker = resuming.fiber.take();
2578 }
2579 }
2580 SuspendReason::Yielding { thread } => {
2581 let slot = &mut state.get_mut(thread.thread)?.state;
2582 slot.check_no_fiber()?;
2583 *slot = GuestThreadState::Ready {
2584 fiber: resuming.fiber.take().unwrap(),
2585 };
2586 let instance = state.get_mut(thread.task)?.instance;
2587 state.push_low_priority(WorkItem::ResumeThread { instance, thread });
2588 }
2589 SuspendReason::ExplicitlySuspending { thread } => {
2590 let slot = &mut state.get_mut(thread.thread)?.state;
2591 slot.check_no_fiber()?;
2592 *slot = GuestThreadState::Suspended(resuming.fiber.take().unwrap());
2593 }
2594 SuspendReason::Waiting { set, thread } => {
2595 match state.get_mut(set)?.waiting.entry(thread) {
2596 Entry::Vacant(entry) => {
2597 entry.insert(WaitMode::Fiber(resuming.fiber.take().unwrap()));
2598 }
2599 Entry::Occupied(_) => {
2600 bail_bug!("entry unexpectedly already exists for {thread:?}");
2601 }
2602 }
2603 }
2604 SuspendReason::YieldingToSubtask { thread } => {
2605 let instance = state.get_mut(thread.task)?.instance;
2614 if state.next_switch_item.is_some() {
2615 bail_bug!(
2618 "`ConcurrentState::next_switch_item` was already `Some(_)` when \
2619 a thread wanted to wait on a subtask"
2620 );
2621 }
2622 let item = state.next_switch_item.insert(WorkItem::ResumeFiber {
2623 instance,
2624 thread,
2625 fiber: resuming.fiber.take().unwrap(),
2626 });
2627 log::trace!("set next switch item to {item:?}");
2628 }
2629 };
2630 } else {
2631 log::trace!("resume_fiber: fiber has exited");
2632 }
2633
2634 Ok(())
2635 }
2636 }
2637
2638 fn suspend(&mut self, reason: SuspendReason) -> Result<()> {
2644 log::trace!("suspend fiber: {reason:?}");
2645
2646 if !self.fiber_async_state_mut().can_block() {
2649 return Err(format_err!("future dropped"));
2650 }
2651
2652 let state = self.concurrent_state_mut()?;
2653
2654 let (save_and_restore_thread, save_and_restore_next_switch_item) = match &reason {
2661 SuspendReason::Yielding { .. }
2662 | SuspendReason::Waiting { .. }
2663 | SuspendReason::ExplicitlySuspending { .. } => {
2664 if state.switch_item.is_none() {
2667 state.take_next_switch_item()?;
2668 }
2669
2670 (true, false)
2671 }
2672 SuspendReason::YieldingToSubtask { .. } => (true, true),
2673 SuspendReason::NeedWork => (false, false),
2674 };
2675
2676 let old_next_switch_item = if save_and_restore_next_switch_item {
2677 Some(state.save_next_switch_item()?)
2678 } else {
2679 None
2680 };
2681
2682 let old_guest_thread = if save_and_restore_thread {
2683 self.current_thread()?
2684 } else {
2685 CurrentThread::None
2686 };
2687
2688 let waiting_set = match &reason {
2689 SuspendReason::Waiting { set, .. } => Some(*set),
2690 _ => None,
2691 };
2692
2693 let suspend_reason = &mut self.concurrent_state_mut()?.suspend_reason;
2694 if suspend_reason.is_some() {
2695 bail_bug!("suspend reason unexpectedly already set for store");
2696 }
2697 *suspend_reason = Some(reason);
2698
2699 if let Some(set) = waiting_set {
2702 self.concurrent_state_mut()?.get_mut(set)?.num_waiting += 1;
2703 }
2704
2705 self.with_blocking(|_, cx| cx.suspend(StoreFiberYield::ReleaseStore))?;
2706
2707 if let Some(set) = waiting_set {
2708 self.concurrent_state_mut()?.get_mut(set)?.stop_waiting()?;
2709 }
2710
2711 if save_and_restore_thread {
2712 self.set_thread(old_guest_thread)?;
2713 }
2714
2715 if let Some(item) = old_next_switch_item {
2716 let state = self.concurrent_state_mut()?;
2717 state.restore_next_switch_item(item)?;
2718 }
2719
2720 Ok(())
2721 }
2722
2723 fn wait_for_event(
2724 &mut self,
2725 caller_instance: RuntimeInstance,
2726 waitable: Waitable,
2727 ) -> Result<()> {
2728 let caller = self.current_guest_thread()?;
2729 let state = self.concurrent_state_mut()?;
2730
2731 waitable.trap_if_in_waitable_set(state)?;
2732
2733 let set = state.get_mut(caller.thread)?.sync_call_set;
2734 waitable.join(state, Some(set))?;
2735
2736 self.switch_or_trap_if_may_not_suspend(caller_instance)?;
2737
2738 self.suspend(SuspendReason::Waiting {
2739 set,
2740 thread: caller,
2741 })?;
2742 let state = self.concurrent_state_mut()?;
2743
2744 waitable.join(state, None)
2745 }
2746
2747 fn cleanup_thread(
2769 &mut self,
2770 guest_thread: QualifiedThreadId,
2771 runtime_instance: RuntimeInstance,
2772 ) -> Result<()> {
2773 let state = self.concurrent_state_mut()?;
2774 state.take_next_switch_item()?;
2777 let thread_data = state.get_mut(guest_thread.thread)?;
2778 let sync_call_set = thread_data.sync_call_set;
2779 if let Some(guest_id) = thread_data.instance_rep {
2780 self.instance_state(runtime_instance)
2781 .thread_handle_table()
2782 .guest_thread_remove(guest_id)?;
2783 }
2784 let state = self.concurrent_state_mut()?;
2785
2786 for waitable in mem::take(&mut state.get_mut(sync_call_set)?.ready) {
2788 if let Some(Event::Subtask {
2789 status: Status::Returned | Status::ReturnCancelled,
2790 }) = waitable.common(state)?.event
2791 {
2792 waitable.delete_from(state)?;
2793 }
2794 }
2795
2796 state.delete(guest_thread.thread)?;
2797 state.delete(sync_call_set)?;
2798 let task = state.get_mut(guest_thread.task)?;
2799 task.threads.remove(&guest_thread.thread);
2800
2801 if task.threads.is_empty() && !task.returned_or_cancelled() {
2802 bail!(Trap::NoAsyncResult);
2803 }
2804
2805 if !task.decremented_interesting_task_count && task.exited && task.returned_or_cancelled() {
2806 task.decremented_interesting_task_count = true;
2807
2808 debug_assert!(state.interesting_tasks > 0);
2809 state.interesting_tasks -= 1;
2810 if state.interesting_tasks == 0
2811 && let Some(waker) = state.interesting_tasks_empty_waker.take()
2812 {
2813 waker.wake();
2814 }
2815 }
2816
2817 state.decrement_task_ref_count(guest_thread.task)?;
2818
2819 Ok(())
2820 }
2821
2822 fn cancel_guest_subtask_without_lowered_parameters(
2831 &mut self,
2832 caller_instance: RuntimeInstance,
2833 guest_task: TableId<GuestTask>,
2834 ) -> Result<()> {
2835 let concurrent_state = self.concurrent_state_mut()?;
2836 let task = concurrent_state.get_mut(guest_task)?;
2837 assert!(!task.already_lowered_parameters());
2838 task.lower_params = None;
2842 task.lift_result = None;
2843 task.exited = true;
2844 let instance = task.instance;
2845
2846 assert_eq!(1, task.threads.len());
2853 let thread = *task.threads.iter().next().unwrap();
2854 let next_switch_item = concurrent_state.save_next_switch_item()?;
2855 self.cleanup_thread(
2856 QualifiedThreadId {
2857 task: guest_task,
2858 thread,
2859 },
2860 caller_instance,
2861 )?;
2862 self.concurrent_state_mut()?
2863 .restore_next_switch_item(next_switch_item)?;
2864
2865 let pending = &mut self.instance_state(instance).concurrent_state().pending;
2867 let pending_count = pending.len();
2868 let mut decrement = 0;
2869 let mut consume = |kind: &GuestCallKind| {
2870 if let GuestCallKind::StartImplicit {
2871 was_pending: true, ..
2872 } = kind
2873 {
2874 decrement += 1;
2875 }
2876 };
2877 pending.retain(|thread, kind| {
2878 if thread.task == guest_task {
2879 consume(kind);
2880 false
2881 } else {
2882 true
2883 }
2884 });
2885
2886 if pending.len() == pending_count {
2887 let mut matches = |item: &WorkItem| match item {
2890 WorkItem::ResumeThread { thread, .. } => thread.task == guest_task,
2891 WorkItem::GuestCall {
2892 call: GuestCall { thread, kind },
2893 ..
2894 } => {
2895 if thread.task == guest_task {
2896 consume(kind);
2897 true
2898 } else {
2899 false
2900 }
2901 }
2902 _ => false,
2903 };
2904
2905 let mut remove = |queue: &mut VecDeque<WorkItem>| {
2906 let count = queue.len();
2907 queue.retain(|item| !matches(item));
2908 count != queue.len()
2909 };
2910
2911 let state = self.concurrent_state_mut()?;
2912 let mut found = remove(&mut state.high_priority);
2913 found |= remove(&mut state.low_priority);
2914
2915 for item in [&mut state.switch_item, &mut state.next_switch_item] {
2916 if matches!(item, Some(item) if matches(item)) {
2917 found = true;
2918 *item = None;
2919 }
2920 }
2921
2922 if !found {
2923 bail!(Trap::SubtaskCancelAfterTerminal);
2924 }
2925 }
2926
2927 self.decrement_pending_start_count(instance, decrement)?;
2928
2929 Ok(())
2930 }
2931
2932 fn decrement_pending_start_count(
2933 &mut self,
2934 instance: RuntimeInstance,
2935 decrement: usize,
2936 ) -> Result<()> {
2937 if decrement > 0 {
2938 let count = &mut self
2939 .instance_state(instance)
2940 .concurrent_state()
2941 .pending_start_count;
2942
2943 if *count < decrement {
2944 bail_bug!("`ConcurrentInstantState::pending_start_count` underflow");
2945 }
2946
2947 *count -= decrement;
2948
2949 self.partition_pending(instance)?;
2951 }
2952
2953 Ok(())
2954 }
2955
2956 pub(crate) fn current_scope(&mut self) -> Result<Option<CurrentScope>> {
2959 if !self.concurrency_support() {
2960 return Ok(self
2961 .current_scope_id_not_concurrent()?
2962 .map(|id| CurrentScope::Id(VMScope::id(id))));
2963 }
2964
2965 Ok(match self.current_thread()? {
2966 CurrentThread::Guest(id) => Some(CurrentScope::Id(VMScope::id(id.task.rep()))),
2967 CurrentThread::Host(id) => Some(CurrentScope::Id(VMScope::host_id(id.rep()))),
2968 CurrentThread::DeferredHost(_) => Some(CurrentScope::DeferredHost),
2969 CurrentThread::None => return Ok(None),
2970 })
2971 }
2972
2973 pub(crate) fn queue_task(
2974 &mut self,
2975 task: impl FnOnce(&mut dyn VMStore) -> Result<()> + Send + 'static,
2976 ) -> Result<()> {
2977 self.concurrent_state_mut()?
2978 .push_high_priority(WorkItem::WorkerFunction(AlwaysMut::new(Box::new(task))));
2979 Ok(())
2980 }
2981
2982 fn any_may_not_suspend(&mut self) -> Result<bool> {
2991 Ok(self
2999 .concurrent_state_mut()?
3000 .table
3001 .get_mut()
3002 .iter_mut()
3003 .filter_map(|(_, entry)| {
3004 if let Some(task) = entry.entry().downcast_ref::<GuestTask>() {
3005 Some(task.instance)
3006 } else {
3007 None
3008 }
3009 })
3010 .collect::<Vec<_>>()
3011 .into_iter()
3012 .any(|instance| {
3013 self.instance_state(instance)
3014 .concurrent_state()
3015 .do_not_suspend
3016 }))
3017 }
3018}
3019
3020impl Instance {
3021 fn get_event(
3024 self,
3025 store: &mut StoreOpaque,
3026 guest_task: TableId<GuestTask>,
3027 set: Option<TableId<WaitableSet>>,
3028 cancellable: bool,
3029 ) -> Result<Option<(Event, Option<(Waitable, u32)>)>> {
3030 let state = store.concurrent_state_mut()?;
3031
3032 let task = state.get_mut(guest_task)?;
3033 let event = &mut task.event;
3034 if let Some(ev) = event
3035 && (cancellable || !matches!(ev, Event::Cancelled))
3036 {
3037 log::trace!("deliver event {ev:?} to {guest_task:?}");
3038
3039 if matches!(ev, Event::Cancelled) {
3040 task.cancel_request_delivered = true;
3041 }
3042
3043 let ev = *ev;
3044 *event = None;
3045 return Ok(Some((ev, None)));
3046 }
3047
3048 let set = match set {
3049 Some(set) => set,
3050 None => return Ok(None),
3051 };
3052 let waitable = match state.get_mut(set)?.ready.pop_first() {
3053 Some(v) => v,
3054 None => return Ok(None),
3055 };
3056
3057 let common = waitable.common(state)?;
3058 let handle = match common.handle {
3059 Some(h) => h,
3060 None => bail_bug!("handle not set when delivering event"),
3061 };
3062 let event = match common.event.take() {
3063 Some(e) => e,
3064 None => bail_bug!("event not set when delivering event"),
3065 };
3066
3067 log::trace!(
3068 "deliver event {event:?} to {guest_task:?} for {waitable:?} (handle {handle}); set {set:?}"
3069 );
3070
3071 waitable.on_delivery(store, self, event)?;
3072
3073 Ok(Some((event, Some((waitable, handle)))))
3074 }
3075
3076 fn handle_callback_code(
3083 self,
3084 store: &mut dyn VMStore,
3085 guest_thread: QualifiedThreadId,
3086 runtime_instance: RuntimeInstance,
3087 call: impl FnOnce(&mut dyn VMStore) -> Result<u32>,
3088 ) -> Result<()> {
3089 let old_thread = store.set_thread(guest_thread)?;
3090 log::trace!(
3091 "callback-lifted call: replaced {old_thread:?} with {guest_thread:?} as current thread"
3092 );
3093
3094 store.enter_instance(runtime_instance);
3095
3096 let mut code = call(store)?;
3097
3098 if matches!(
3104 unpack_callback_code(code).0,
3105 callback_code::YIELD | callback_code::WAIT
3106 ) && let Some((event, _)) = self.get_event(store, guest_thread.task, None, true)?
3107 {
3108 let (unpacked, set) = unpack_callback_code(code);
3109 log::trace!(
3110 "{guest_thread:?} returned callback code {unpacked} (set: {set}) with a pending \
3111 cancellation; delivering it via callback"
3112 );
3113 code = invoke_callback(store, guest_thread.task, event, 0)?;
3114 }
3115
3116 store.exit_instance(runtime_instance)?;
3117
3118 store.set_thread(old_thread)?;
3119 log::trace!("callback-lifted call: restored {old_thread:?} as current thread");
3120
3121 let store = &mut **store;
3122 let (code, set) = unpack_callback_code(code);
3123
3124 log::trace!("received callback code from {guest_thread:?}: {code} (set: {set})");
3125
3126 let state = store.concurrent_state_mut()?;
3127
3128 state.take_next_switch_item()?;
3129
3130 let get_set = |store: &mut StoreOpaque, handle| -> Result<_> {
3131 let set = store
3132 .instance_state(runtime_instance)
3133 .handle_table()
3134 .waitable_set_rep(handle)?;
3135
3136 Ok(TableId::<WaitableSet>::new(set))
3137 };
3138
3139 match code {
3140 callback_code::EXIT => {
3141 log::trace!("implicit thread {guest_thread:?} completed");
3142 let task = store.concurrent_state_mut()?.get_mut(guest_thread.task)?;
3143 task.exited = true;
3144 task.callback = None;
3145
3146 store.switch_or_trap_if_may_not_suspend(runtime_instance)?;
3151
3152 store.cleanup_thread(guest_thread, runtime_instance)?;
3153 }
3154 callback_code::YIELD => {
3155 let old = state
3158 .get_mut(guest_thread.thread)?
3159 .wake_on_cancel
3160 .replace(WakeOnCancel::Yielding);
3161 if !old.is_none() {
3162 bail_bug!("thread unexpectedly had wake_on_cancel set");
3163 }
3164
3165 let call = GuestCall {
3172 thread: guest_thread,
3173 kind: GuestCallKind::DeliverEvent {
3174 instance: self,
3175 set: None,
3176 },
3177 };
3178 state.push_low_priority(WorkItem::GuestCall {
3181 instance: runtime_instance,
3182 call,
3183 });
3184 }
3185 callback_code::WAIT => {
3186 let set = get_set(store, set)?;
3187 self.wait_with_callback(store, guest_thread, set)?;
3188 }
3189 _ => bail!(Trap::UnsupportedCallbackCode),
3190 }
3191
3192 Ok(())
3193 }
3194
3195 fn wait_with_callback(
3201 self,
3202 store: &mut StoreOpaque,
3203 guest_thread: QualifiedThreadId,
3204 set: TableId<WaitableSet>,
3205 ) -> Result<()> {
3206 let state = store.concurrent_state_mut()?;
3207 state.get_mut(set)?.num_waiting += 1;
3210
3211 if state.get_mut(guest_thread.task)?.event.is_some()
3212 || !state.get_mut(set)?.ready.is_empty()
3213 {
3214 let instance = state.get_mut(guest_thread.task)?.instance;
3216 state.push_high_priority(WorkItem::GuestCall {
3217 instance,
3218 call: GuestCall {
3219 thread: guest_thread,
3220 kind: GuestCallKind::DeliverEvent {
3221 instance: self,
3222 set: Some(set),
3223 },
3224 },
3225 });
3226 return Ok(());
3227 }
3228
3229 let instance = store
3235 .concurrent_state_mut()?
3236 .get_mut(guest_thread.task)?
3237 .instance;
3238 store.switch_or_trap_if_may_not_suspend(instance)?;
3239
3240 let state = store.concurrent_state_mut()?;
3246 let old = state
3247 .get_mut(guest_thread.thread)?
3248 .wake_on_cancel
3249 .replace(WakeOnCancel::Waiting(set));
3250 if !old.is_none() {
3251 bail_bug!("thread unexpectedly had wake_on_cancel set");
3252 }
3253 let old = state
3254 .get_mut(set)?
3255 .waiting
3256 .insert(guest_thread, WaitMode::Callback(self));
3257 if !old.is_none() {
3258 bail_bug!("set's waiting set already had this thread registered");
3259 }
3260 Ok(())
3261 }
3262
3263 unsafe fn stage_call<T: 'static>(
3270 self,
3271 mut store: StoreContextMut<T>,
3272 guest_thread: QualifiedThreadId,
3273 callee: SendSyncPtr<VMFuncRef>,
3274 param_count: usize,
3275 result_count: usize,
3276 async_: bool,
3277 callback: Option<SendSyncPtr<VMFuncRef>>,
3278 post_return: Option<SendSyncPtr<VMFuncRef>>,
3279 host_caller: bool,
3280 ) -> Result<()> {
3281 unsafe fn make_call<T: 'static>(
3296 store: StoreContextMut<T>,
3297 guest_thread: QualifiedThreadId,
3298 callee: SendSyncPtr<VMFuncRef>,
3299 param_count: usize,
3300 result_count: usize,
3301 ) -> impl FnOnce(&mut dyn VMStore) -> Result<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>
3302 + Send
3303 + Sync
3304 + 'static
3305 + use<T> {
3306 let token = StoreToken::new(store);
3307 move |store: &mut dyn VMStore| {
3308 let mut storage = [MaybeUninit::uninit(); MAX_FLAT_PARAMS];
3309
3310 store
3311 .concurrent_state_mut()?
3312 .set_thread_running(guest_thread.thread)?;
3313 let task = store.concurrent_state_mut()?.get_mut(guest_thread.task)?;
3314 let lower = match task.lower_params.take() {
3315 Some(l) => l,
3316 None => bail_bug!("lower_params missing"),
3317 };
3318
3319 lower(store, &mut storage[..param_count])?;
3320
3321 let mut store = token.as_context_mut(store);
3322
3323 unsafe {
3326 crate::Func::call_unchecked_raw(
3327 &mut store,
3328 callee.as_non_null(),
3329 NonNull::new(
3330 &mut storage[..param_count.max(result_count)]
3331 as *mut [MaybeUninit<ValRaw>] as _,
3332 )
3333 .unwrap(),
3334 UncaughtException::Trap,
3335 )?;
3336 }
3337
3338 Ok(storage)
3339 }
3340 }
3341
3342 let call = unsafe {
3346 make_call(
3347 store.as_context_mut(),
3348 guest_thread,
3349 callee,
3350 param_count,
3351 result_count,
3352 )
3353 };
3354
3355 let callee_instance = store
3356 .0
3357 .concurrent_state_mut()?
3358 .get_mut(guest_thread.task)?
3359 .instance;
3360
3361 let fun = if callback.is_some() {
3362 assert!(async_);
3363
3364 Box::new(move |store: &mut dyn VMStore| {
3365 self.add_guest_thread_to_instance_table(
3366 guest_thread.thread,
3367 store,
3368 callee_instance.index,
3369 )?;
3370 self.handle_callback_code(store, guest_thread, callee_instance, |store| {
3371 let storage = call(store)?;
3372
3373 Ok(unsafe { storage[0].assume_init() }.get_i32() as u32)
3376 })
3377 }) as Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send + Sync>
3378 } else {
3379 let token = StoreToken::new(store.as_context_mut());
3380 Box::new(move |store: &mut dyn VMStore| {
3381 self.add_guest_thread_to_instance_table(
3382 guest_thread.thread,
3383 store,
3384 callee_instance.index,
3385 )?;
3386 let old_thread = store.set_thread(guest_thread)?;
3387 log::trace!(
3388 "sync/async-stackful call: replaced {old_thread:?} with {guest_thread:?} as current thread",
3389 );
3390 let flags = self.id().get(store).instance_flags(callee_instance.index);
3391
3392 let callee_async_typed = store
3393 .concurrent_state_mut()?
3394 .get_mut(guest_thread.task)?
3395 .async_typed;
3396
3397 if !async_ && callee_async_typed {
3401 store.enter_instance(callee_instance);
3402 }
3403
3404 if !callee_async_typed {
3405 store.enter_sync_call(callee_instance)?;
3406 }
3407
3408 let storage = call(store)?;
3415
3416 if !callee_async_typed {
3417 store.exit_sync_call(callee_instance)?;
3418 }
3419
3420 if !async_ {
3421 if callee_async_typed {
3427 store.exit_instance(callee_instance)?;
3428 }
3429
3430 let lift = {
3431 let state = store.concurrent_state_mut()?;
3432 if !state.get_mut(guest_thread.task)?.result.is_none() {
3433 bail_bug!("task has already produced a result");
3434 }
3435
3436 match state.get_mut(guest_thread.task)?.lift_result.take() {
3437 Some(lift) => lift,
3438 None => bail_bug!("lift_result field is missing"),
3439 }
3440 };
3441
3442 let result = (lift.lift)(store, unsafe {
3445 mem::transmute::<&[MaybeUninit<ValRaw>], &[ValRaw]>(
3446 &storage[..result_count],
3447 )
3448 })?;
3449
3450 let post_return_arg = match result_count {
3451 0 => ValRaw::i32(0),
3452 1 => unsafe { storage[0].assume_init() },
3455 _ => unreachable!(),
3456 };
3457
3458 unsafe {
3459 call_post_return(
3460 token.as_context_mut(store),
3461 post_return.map(|v| v.as_non_null()),
3462 post_return_arg,
3463 flags,
3464 )?;
3465 }
3466
3467 self.task_complete(store, guest_thread.task, result, Status::Returned)?;
3468 }
3469
3470 store.set_thread(old_thread)?;
3471
3472 store
3473 .concurrent_state_mut()?
3474 .get_mut(guest_thread.task)?
3475 .exited = true;
3476
3477 log::trace!(
3478 "clean up thread; async lifted? {async_} async typed? {callee_async_typed}"
3479 );
3480
3481 if callee_async_typed {
3482 store.switch_or_trap_if_may_not_suspend(callee_instance)?;
3487 }
3488
3489 store.cleanup_thread(guest_thread, callee_instance)?;
3491 Ok(())
3492 })
3493 };
3494
3495 store.0.concurrent_state_mut()?.push_work_item(
3496 WorkItem::GuestCall {
3497 instance: callee_instance,
3498 call: GuestCall {
3499 thread: guest_thread,
3500 kind: GuestCallKind::StartImplicit {
3501 closure: fun,
3502 was_pending: false,
3503 },
3504 },
3505 },
3506 if host_caller {
3507 Priority::Low
3513 } else {
3514 Priority::Switch
3515 },
3516 )?;
3517
3518 Ok(())
3519 }
3520
3521 unsafe fn prepare_call<T: 'static>(
3534 self,
3535 mut store: StoreContextMut<T>,
3536 start: NonNull<VMFuncRef>,
3537 return_: NonNull<VMFuncRef>,
3538 caller_instance: RuntimeComponentInstanceIndex,
3539 callee_instance: RuntimeComponentInstanceIndex,
3540 task_return_type: TypeTupleIndex,
3541 callee_async_typed: bool,
3542 memory: *mut VMMemoryDefinition,
3543 string_encoding: StringEncoding,
3544 caller_info: CallerInfo,
3545 ) -> Result<()> {
3546 enum ResultInfo {
3547 Heap { results: u32 },
3548 Stack { result_count: u32 },
3549 }
3550
3551 let result_info = match &caller_info {
3552 CallerInfo::Async {
3553 has_result: true,
3554 params,
3555 } => ResultInfo::Heap {
3556 results: match params.last() {
3558 Some(r) => r.get_u32(),
3559 None => bail_bug!("retptr missing"),
3560 },
3561 },
3562 CallerInfo::Async {
3563 has_result: false, ..
3564 } => ResultInfo::Stack { result_count: 0 },
3565 CallerInfo::Sync {
3566 result_count,
3567 params,
3568 } if *result_count > u32::try_from(MAX_FLAT_RESULTS)? => ResultInfo::Heap {
3569 results: match params.last() {
3571 Some(r) => r.get_u32(),
3572 None => bail_bug!("arg ptr missing"),
3573 },
3574 },
3575 CallerInfo::Sync { result_count, .. } => ResultInfo::Stack {
3576 result_count: *result_count,
3577 },
3578 };
3579
3580 let sync_caller = matches!(caller_info, CallerInfo::Sync { .. });
3581
3582 let start = SendSyncPtr::new(start);
3586 let return_ = SendSyncPtr::new(return_);
3587 let token = StoreToken::new(store.as_context_mut());
3588 let old_thread = store.0.current_guest_thread()?;
3589
3590 let state = store.0.concurrent_state_mut()?;
3591
3592 debug_assert_eq!(
3593 state.get_mut(old_thread.task)?.instance,
3594 self.runtime_instance(caller_instance)
3595 );
3596
3597 let guest_thread = GuestTask::new(
3598 state,
3599 Box::new(move |store, dst| {
3600 let mut store = token.as_context_mut(store);
3601 assert!(dst.len() <= MAX_FLAT_PARAMS);
3602 let mut src = [MaybeUninit::uninit(); MAX_FLAT_PARAMS + 1];
3604 let count = match caller_info {
3605 CallerInfo::Async { params, has_result } => {
3609 let params = ¶ms[..params.len() - usize::from(has_result)];
3610 for (param, src) in params.iter().zip(&mut src) {
3611 src.write(*param);
3612 }
3613 params.len()
3614 }
3615
3616 CallerInfo::Sync { params, .. } => {
3618 for (param, src) in params.iter().zip(&mut src) {
3619 src.write(*param);
3620 }
3621 params.len()
3622 }
3623 };
3624 unsafe {
3631 crate::Func::call_unchecked_raw(
3632 &mut store,
3633 start.as_non_null(),
3634 NonNull::new(
3635 &mut src[..count.max(dst.len())] as *mut [MaybeUninit<ValRaw>] as _,
3636 )
3637 .unwrap(),
3638 UncaughtException::Trap,
3639 )?;
3640 }
3641 dst.copy_from_slice(&src[..dst.len()]);
3642 let task = store.0.current_guest_thread()?.task;
3643 let state = store.0.concurrent_state_mut()?;
3644 Waitable::Guest(task).set_event(
3645 state,
3646 Some(Event::Subtask {
3647 status: Status::Started,
3648 }),
3649 )?;
3650 Ok(())
3651 }),
3652 LiftResult {
3653 lift: Box::new(move |store, src| {
3654 let mut store = token.as_context_mut(store);
3657 let mut my_src = src.to_owned(); if let ResultInfo::Heap { results } = &result_info {
3659 my_src.push(ValRaw::u32(*results));
3660 }
3661
3662 unsafe {
3669 crate::Func::call_unchecked_raw(
3670 &mut store,
3671 return_.as_non_null(),
3672 my_src.as_mut_slice().into(),
3673 UncaughtException::Trap,
3674 )?;
3675 }
3676
3677 let thread = store.0.current_guest_thread()?;
3678 let state = store.0.concurrent_state_mut()?;
3679 if sync_caller {
3680 state.get_mut(thread.task)?.sync_result = SyncResult::Produced(
3681 if let ResultInfo::Stack { result_count } = &result_info {
3682 match result_count {
3683 0 => None,
3684 1 => Some(my_src[0]),
3685 _ => unreachable!(),
3686 }
3687 } else {
3688 None
3689 },
3690 );
3691 }
3692 Ok(Box::new(DummyResult) as Box<dyn Any + Send + Sync>)
3693 }),
3694 ty: task_return_type,
3695 memory: NonNull::new(memory).map(SendSyncPtr::new),
3696 string_encoding,
3697 },
3698 Caller::Guest { thread: old_thread },
3699 None,
3700 self.runtime_instance(callee_instance),
3701 callee_async_typed,
3702 false,
3705 )?;
3706
3707 store.0.set_thread(guest_thread)?;
3710 log::trace!("pushed {guest_thread:?} as current thread; old thread was {old_thread:?}");
3711
3712 Ok(())
3713 }
3714
3715 unsafe fn call_callback<T>(
3720 self,
3721 mut store: StoreContextMut<T>,
3722 function: SendSyncPtr<VMFuncRef>,
3723 event: Event,
3724 handle: u32,
3725 ) -> Result<u32> {
3726 let (ordinal, result) = event.parts();
3727 let params = &mut [
3728 ValRaw::u32(ordinal),
3729 ValRaw::u32(handle),
3730 ValRaw::u32(result),
3731 ];
3732 unsafe {
3737 crate::Func::call_unchecked_raw(
3738 &mut store,
3739 function.as_non_null(),
3740 params.as_mut_slice().into(),
3741 UncaughtException::Trap,
3742 )?;
3743 }
3744 Ok(params[0].get_u32())
3745 }
3746
3747 unsafe fn start_call<T: 'static>(
3765 self,
3766 mut store: StoreContextMut<T>,
3767 callback: *mut VMFuncRef,
3768 post_return: *mut VMFuncRef,
3769 callee: NonNull<VMFuncRef>,
3770 param_count: u32,
3771 result_count: u32,
3772 flags: u32,
3773 storage: &mut [MaybeUninit<ValRaw>],
3774 ) -> Result<()> {
3775 let token = StoreToken::new(store.as_context_mut());
3776 let async_caller = (flags & START_FLAG_ASYNC_CALLER) != 0;
3777 let guest_thread = store.0.current_guest_thread()?;
3778 let state = store.0.concurrent_state_mut()?;
3779
3780 if !state.event_loop_running {
3785 bail!(
3786 "async function started during an original synchronous \
3787 entrypoint; please use an async-style entrypoint instead"
3788 );
3789 }
3790
3791 let callee = SendSyncPtr::new(callee);
3792 let param_count = usize::try_from(param_count)?;
3793 assert!(param_count <= MAX_FLAT_PARAMS);
3794 let result_count = usize::try_from(result_count)?;
3795 assert!(result_count <= MAX_FLAT_RESULTS);
3796
3797 let task = state.get_mut(guest_thread.task)?;
3798 let callee_async_typed = task.async_typed;
3799 let callee_instance = task.instance;
3800
3801 task.async_lifted = (flags & START_FLAG_ASYNC_CALLEE) != 0;
3802
3803 if let Some(callback) = NonNull::new(callback) {
3804 let callback = SendSyncPtr::new(callback);
3808 task.callback = Some(Box::new(move |store, event, handle| {
3809 let store = token.as_context_mut(store);
3810 unsafe { self.call_callback::<T>(store, callback, event, handle) }
3811 }));
3812 }
3813
3814 let Caller::Guest { thread: caller } = &task.caller else {
3815 bail_bug!("start_call unexpectedly invoked for host->guest call");
3818 };
3819 let caller = *caller;
3820 let caller_instance = state.get_mut(caller.task)?.instance;
3821
3822 unsafe {
3824 self.stage_call(
3825 store.as_context_mut(),
3826 guest_thread,
3827 callee,
3828 param_count,
3829 result_count,
3830 (flags & START_FLAG_ASYNC_CALLEE) != 0,
3831 NonNull::new(callback).map(SendSyncPtr::new),
3832 NonNull::new(post_return).map(SendSyncPtr::new),
3833 false,
3834 )?;
3835 }
3836
3837 let old_do_not_suspend = if callee_async_typed {
3838 let state = store.0.instance_state(callee_instance).concurrent_state();
3845 let old_do_not_suspend = state.do_not_suspend;
3846 state.do_not_suspend = false;
3847 Some(old_do_not_suspend)
3848 } else {
3849 None
3850 };
3851
3852 let state = store.0.concurrent_state_mut()?;
3853
3854 let guest_waitable = Waitable::Guest(guest_thread.task);
3857 let old_set = guest_waitable.common(state)?.set;
3858 let set = state.get_mut(caller.thread)?.sync_call_set;
3859 guest_waitable.join(state, Some(set))?;
3860
3861 store.0.set_thread(CurrentThread::None)?;
3862
3863 let mut yielded = false;
3879 let (status, waitable) = loop {
3880 store.0.suspend(if yielded {
3881 SuspendReason::Waiting {
3882 set,
3883 thread: caller,
3884 }
3885 } else {
3886 yielded = true;
3887 SuspendReason::YieldingToSubtask { thread: caller }
3888 })?;
3889
3890 if let Some(old_do_not_suspend) = old_do_not_suspend {
3891 store
3892 .0
3893 .instance_state(callee_instance)
3894 .concurrent_state()
3895 .do_not_suspend = old_do_not_suspend;
3896 }
3897
3898 let state = store.0.concurrent_state_mut()?;
3899
3900 log::trace!("taking event for {:?}", guest_thread.task);
3901 let event = guest_waitable.take_event(state)?;
3902 let Some(Event::Subtask { status }) = event else {
3903 bail_bug!("subtasks should only get subtask events, got {event:?}")
3904 };
3905
3906 log::trace!("status {status:?} for {:?}", guest_thread.task);
3907
3908 if status == Status::Returned {
3909 break (status, None);
3911 } else if async_caller {
3912 let handle = store
3916 .0
3917 .handle_table_insertion(caller_instance)
3918 .subtask_guest(guest_thread.task.rep())?;
3919 store
3920 .0
3921 .concurrent_state_mut()?
3922 .get_mut(guest_thread.task)?
3923 .common
3924 .handle = Some(handle);
3925 break (status, Some(handle));
3926 } else {
3927 store.0.switch_or_trap_if_may_not_suspend(caller_instance)?;
3931 }
3932 };
3933
3934 guest_waitable.join(store.0.concurrent_state_mut()?, old_set)?;
3935
3936 store.0.set_thread(caller)?;
3938
3939 store
3940 .0
3941 .concurrent_state_mut()?
3942 .set_thread_running(caller.thread)?;
3943
3944 log::trace!("popped current thread {guest_thread:?}; new thread is {caller:?}");
3945
3946 if async_caller {
3947 let Some(slot) = storage.first_mut() else {
3948 bail_bug!("no storage for async call status");
3949 };
3950 *slot = MaybeUninit::new(ValRaw::u32(status.pack(waitable)));
3951 } else {
3952 let state = store.0.concurrent_state_mut()?;
3955 let task = state.get_mut(guest_thread.task)?;
3956 if let Some(Some(result)) = task.sync_result.take()? {
3957 storage[0] = MaybeUninit::new(result);
3958 }
3959 }
3960
3961 if status == Status::Returned {
3962 store
3963 .0
3964 .concurrent_state_mut()?
3965 .decrement_task_ref_count(guest_thread.task)?;
3966 }
3967
3968 Ok(())
3969 }
3970
3971 pub(crate) fn first_poll<T: 'static, R: Send + 'static>(
3987 self,
3988 mut store: StoreContextMut<'_, T>,
3989 host_task: EnteredHostTask,
3990 result_may_require_realloc: bool,
3991 future: impl Future<Output = Result<R>> + Send + 'static,
3992 lower: impl FnOnce(StoreContextMut<T>, Option<R>, bool, Option<TableId<HostTask>>) -> Result<()>
3993 + Send
3994 + 'static,
3995 ) -> Result<u32> {
3996 let token = StoreToken::new(store.as_context_mut());
3997
3998 let (join_handle, future) = JoinHandle::run(future);
4001 let mut future = Box::pin(future);
4002
4003 let poll = tls::set(store.0, || {
4008 future
4009 .as_mut()
4010 .poll(&mut Context::from_waker(&Waker::noop()))
4011 });
4012
4013 match poll {
4014 Poll::Ready(result) => {
4016 let result = result.transpose()?;
4017 let task = store.0.current_materialized_host_task()?;
4020 lower(store.as_context_mut(), result, true, task)?;
4021 return Ok(Status::Returned.pack(None));
4022 }
4023
4024 Poll::Pending => {}
4026 }
4027
4028 let Some(task) = store.0.materialize_host_task_id()? else {
4032 bail_bug!("current thread is not a host thread")
4033 };
4034 {
4035 let state = &mut store.0.concurrent_state_mut()?.get_mut(task)?.state;
4036 assert!(matches!(state, HostTaskState::CalleeStarted));
4037 *state = HostTaskState::CalleeRunning(join_handle);
4038 }
4039
4040 let future = Box::pin(async move {
4048 let result = match run_with_host_task_set(task, future).await? {
4049 Some(result) => Some(result?),
4050 None => None,
4051 };
4052 let on_complete = move |store: &mut dyn VMStore| {
4053 let mut store = token.as_context_mut(store);
4057 let old = store.0.set_thread(task)?;
4058
4059 let status = if result.is_some() {
4060 Status::Returned
4061 } else {
4062 Status::ReturnCancelled
4063 };
4064
4065 lower(store.as_context_mut(), result, false, Some(task))?;
4066 let state = store.0.concurrent_state_mut()?;
4067 match &mut state.get_mut(task)?.state {
4068 pending @ HostTaskState::CalleeCancelling => {
4071 *pending = HostTaskState::CalleeDone { cancelled: true };
4072 }
4073
4074 other => *other = HostTaskState::CalleeDone { cancelled: false },
4076 }
4077 Waitable::Host(task).set_event(state, Some(Event::Subtask { status }))?;
4078
4079 store.0.set_thread(old)?;
4080 Ok(())
4081 };
4082
4083 tls::get(move |store| {
4084 if result_may_require_realloc {
4085 store
4090 .concurrent_state_mut()?
4091 .push_high_priority(WorkItem::WorkerFunction(AlwaysMut::new(Box::new(
4092 on_complete,
4093 ))));
4094 Ok(())
4095 } else {
4096 on_complete(store)
4099 }
4100 })
4101 });
4102
4103 let caller = match host_task {
4106 Some(caller) => caller,
4107 None => bail_bug!("host task wasn't created but should have been"),
4108 };
4109 let state = store.0.concurrent_state_mut()?;
4110 state.push_future(future);
4111 let instance = state.get_mut(caller.task)?.instance;
4112 let handle = store
4113 .0
4114 .handle_table_insertion(instance)
4115 .subtask_host(task.rep())?;
4116 store.0.concurrent_state_mut()?.get_mut(task)?.common.handle = Some(handle);
4117 log::trace!("assign {task:?} handle {handle} for {caller:?} instance {instance:?}");
4118
4119 store.0.set_thread(caller)?;
4123 Ok(Status::Started.pack(Some(handle)))
4124 }
4125
4126 pub(crate) fn task_return(
4129 self,
4130 store: &mut dyn VMStore,
4131 ty: TypeTupleIndex,
4132 options: OptionsIndex,
4133 storage: &[ValRaw],
4134 ) -> Result<()> {
4135 let guest_thread = store.current_guest_thread()?;
4136 let state = store.concurrent_state_mut()?;
4137 if !state.get_mut(guest_thread.task)?.async_lifted {
4138 bail!(Trap::TaskReturnOrCancelSyncLifted);
4139 }
4140 let lift = state
4141 .get_mut(guest_thread.task)?
4142 .lift_result
4143 .take()
4144 .ok_or_else(|| Trap::TaskCancelOrReturnTwice)?;
4145 if !state.get_mut(guest_thread.task)?.result.is_none() {
4146 bail_bug!("task result unexpectedly already set");
4147 }
4148
4149 let CanonicalOptions {
4150 string_encoding,
4151 data_model,
4152 ..
4153 } = &self.id().get(store).component().env_component().options[options];
4154
4155 let invalid = ty != lift.ty
4156 || string_encoding != &lift.string_encoding
4157 || match data_model {
4158 CanonicalOptionsDataModel::LinearMemory(opts) => match opts.memory {
4159 Some(memory) => {
4160 let expected = lift.memory.map(|v| v.as_ptr()).unwrap_or(ptr::null_mut());
4161 let actual = self.id().get(store).runtime_memory(memory);
4162 expected != actual.as_ptr()
4163 }
4164 None => false,
4167 },
4168 CanonicalOptionsDataModel::Gc { .. } => true,
4170 };
4171
4172 if invalid {
4173 bail!(Trap::TaskReturnInvalid);
4174 }
4175
4176 log::trace!("task.return for {guest_thread:?}");
4177
4178 let result = (lift.lift)(store, storage)?;
4179 self.task_complete(store, guest_thread.task, result, Status::Returned)
4180 }
4181
4182 pub(crate) fn task_cancel(self, store: &mut StoreOpaque) -> Result<()> {
4184 let guest_thread = store.current_guest_thread()?;
4185 let state = store.concurrent_state_mut()?;
4186 let task = state.get_mut(guest_thread.task)?;
4187 if !task.async_lifted {
4188 bail!(Trap::TaskReturnOrCancelSyncLifted);
4189 }
4190 if !task.cancel_request_delivered {
4191 bail!(Trap::TaskCancelNotCancelled);
4192 }
4193 _ = task
4194 .lift_result
4195 .take()
4196 .ok_or_else(|| Trap::TaskCancelOrReturnTwice)?;
4197
4198 if !task.result.is_none() {
4199 bail_bug!("task result should not bet set yet");
4200 }
4201
4202 log::trace!("task.cancel for {guest_thread:?}");
4203
4204 self.task_complete(
4205 store,
4206 guest_thread.task,
4207 Box::new(DummyResult),
4208 Status::ReturnCancelled,
4209 )
4210 }
4211
4212 fn task_complete(
4218 self,
4219 store: &mut StoreOpaque,
4220 guest_task: TableId<GuestTask>,
4221 result: Box<dyn Any + Send + Sync>,
4222 status: Status,
4223 ) -> Result<()> {
4224 store
4225 .component_resource_tables(Some(self))?
4226 .validate_scope_exit()?;
4227
4228 let state = store.concurrent_state_mut()?;
4229 let task = state.get_mut(guest_task)?;
4230
4231 task.event = None;
4235
4236 if let Caller::Host { tx, .. } = &mut task.caller {
4237 if let Some(tx) = tx.take() {
4238 _ = tx.send(result);
4239 }
4240 } else {
4241 task.result = Some(result);
4242 Waitable::Guest(guest_task).set_event(state, Some(Event::Subtask { status }))?;
4243 }
4244
4245 Ok(())
4246 }
4247
4248 pub(crate) fn waitable_set_new(
4250 self,
4251 store: &mut StoreOpaque,
4252 caller_instance: RuntimeComponentInstanceIndex,
4253 ) -> Result<u32> {
4254 let set = store.concurrent_state_mut()?.push(WaitableSet::default())?;
4255 let handle = store
4256 .handle_table_insertion(self.runtime_instance(caller_instance))
4257 .waitable_set(set.rep())?;
4258 log::trace!("new waitable set {set:?} (handle {handle})");
4259 Ok(handle)
4260 }
4261
4262 pub(crate) fn waitable_set_drop(
4264 self,
4265 store: &mut StoreOpaque,
4266 caller_instance: RuntimeComponentInstanceIndex,
4267 set: u32,
4268 ) -> Result<()> {
4269 let rep = store
4270 .instance_state(self.runtime_instance(caller_instance))
4271 .handle_table()
4272 .waitable_set_remove(set)?;
4273
4274 log::trace!("drop waitable set {rep} (handle {set})");
4275
4276 let set = store
4280 .concurrent_state_mut()?
4281 .get_mut(TableId::<WaitableSet>::new(rep))?;
4282 if set.num_waiting > 0 {
4283 bail!(Trap::WaitableSetDropHasWaiters);
4284 }
4285
4286 store
4287 .concurrent_state_mut()?
4288 .delete(TableId::<WaitableSet>::new(rep))?;
4289
4290 Ok(())
4291 }
4292
4293 pub(crate) fn waitable_join(
4295 self,
4296 store: &mut StoreOpaque,
4297 caller_instance: RuntimeComponentInstanceIndex,
4298 waitable_handle: u32,
4299 set_handle: u32,
4300 ) -> Result<()> {
4301 let mut instance = self.id().get_mut(store);
4302 let waitable =
4303 Waitable::from_instance(instance.as_mut(), caller_instance, waitable_handle)?;
4304
4305 let set = if set_handle == 0 {
4306 None
4307 } else {
4308 let set = instance.instance_states().0[caller_instance]
4309 .handle_table()
4310 .waitable_set_rep(set_handle)?;
4311
4312 Some(TableId::<WaitableSet>::new(set))
4313 };
4314
4315 waitable.trap_if_has_sync_waiter(store.concurrent_state_mut()?)?;
4316
4317 log::trace!(
4318 "waitable {waitable:?} (handle {waitable_handle}) join set {set:?} (handle {set_handle})",
4319 );
4320
4321 waitable.join(store.concurrent_state_mut()?, set)
4322 }
4323
4324 pub(crate) fn subtask_drop(
4326 self,
4327 store: &mut StoreOpaque,
4328 caller_instance: RuntimeComponentInstanceIndex,
4329 task_id: u32,
4330 ) -> Result<()> {
4331 self.waitable_join(store, caller_instance, task_id, 0)?;
4332
4333 let (rep, is_host) = store
4334 .instance_state(self.runtime_instance(caller_instance))
4335 .handle_table()
4336 .subtask_remove(task_id)?;
4337
4338 let concurrent_state = store.concurrent_state_mut()?;
4339 let waitable = if is_host {
4340 let id = TableId::<HostTask>::new(rep);
4341 let task = concurrent_state.get_mut(id)?;
4342 match &task.state {
4343 HostTaskState::CalleeRunning(_) | HostTaskState::CalleeCancelling => {
4344 bail!(Trap::SubtaskDropNotResolved)
4345 }
4346 HostTaskState::CalleeDone { .. } => {}
4347 HostTaskState::CalleeStarted | HostTaskState::CalleeFinished(_) => {
4348 bail_bug!("invalid state for callee in `subtask.drop`")
4349 }
4350 }
4351
4352 Waitable::Host(id)
4353 } else {
4354 let id = TableId::<GuestTask>::new(rep);
4355 let task = concurrent_state.get_mut(id)?;
4356 if task.lift_result.is_some() {
4357 bail!(Trap::SubtaskDropNotResolved);
4358 }
4359 Waitable::Guest(id)
4360 };
4361
4362 waitable.common(concurrent_state)?.handle = None;
4363
4364 if waitable.take_event(concurrent_state)?.is_some() {
4367 bail!(Trap::SubtaskDropNotResolved);
4368 }
4369
4370 waitable.delete_from(concurrent_state)?;
4371
4372 log::trace!("subtask_drop {waitable:?} (handle {task_id})");
4373 Ok(())
4374 }
4375
4376 pub(crate) fn waitable_set_wait(
4378 self,
4379 store: &mut StoreOpaque,
4380 options: OptionsIndex,
4381 set: u32,
4382 payload: u32,
4383 ) -> Result<u32> {
4384 let &CanonicalOptions {
4385 instance: caller_instance,
4386 ..
4387 } = &self.id().get(store).component().env_component().options[options];
4388 let caller = self.runtime_instance(caller_instance);
4389 let rep = store
4390 .instance_state(self.runtime_instance(caller_instance))
4391 .handle_table()
4392 .waitable_set_rep(set)?;
4393
4394 self.waitable_check(
4395 store,
4396 caller,
4397 WaitableCheck::Wait,
4398 WaitableCheckParams {
4399 set: TableId::new(rep),
4400 options,
4401 payload,
4402 },
4403 )
4404 }
4405
4406 pub(crate) fn waitable_set_poll(
4408 self,
4409 store: &mut StoreOpaque,
4410 options: OptionsIndex,
4411 set: u32,
4412 payload: u32,
4413 ) -> Result<u32> {
4414 let &CanonicalOptions {
4415 instance: caller_instance,
4416 ..
4417 } = &self.id().get(store).component().env_component().options[options];
4418 let caller = self.runtime_instance(caller_instance);
4419 let rep = store
4420 .instance_state(caller)
4421 .handle_table()
4422 .waitable_set_rep(set)?;
4423
4424 self.waitable_check(
4425 store,
4426 caller,
4427 WaitableCheck::Poll,
4428 WaitableCheckParams {
4429 set: TableId::new(rep),
4430 options,
4431 payload,
4432 },
4433 )
4434 }
4435
4436 pub(crate) fn thread_index(&self, store: &mut dyn VMStore) -> Result<u32> {
4438 let thread_id = store.current_guest_thread()?.thread;
4439 match store
4440 .concurrent_state_mut()?
4441 .get_mut(thread_id)?
4442 .instance_rep
4443 {
4444 Some(r) => Ok(r),
4445 None => bail_bug!("thread should have instance_rep by now"),
4446 }
4447 }
4448
4449 pub(crate) fn thread_new_indirect<T: 'static>(
4451 self,
4452 mut store: StoreContextMut<T>,
4453 runtime_instance: RuntimeComponentInstanceIndex,
4454 start_func_ty: ModuleInternedTypeIndex,
4455 start_func_table_idx: RuntimeTableIndex,
4456 start_func_idx: u32,
4457 context: i32,
4458 ) -> Result<u32> {
4459 log::trace!("creating new thread");
4460
4461 let (instance, registry) = self.id().get_mut_and_registry(store.0);
4462 let Some(start_func_ty) = instance.component().signatures().shared_type(start_func_ty)
4463 else {
4464 bail_bug!("thread.new-indirect start function type should be registered");
4465 };
4466 let callee = instance
4467 .index_runtime_func_table(registry, start_func_table_idx, start_func_idx as u64)?
4468 .ok_or_else(|| Trap::ThreadNewIndirectUninitialized)?;
4469 if callee.type_index(store.0) != start_func_ty {
4470 bail!(Trap::ThreadNewIndirectInvalidType);
4471 }
4472
4473 let token = StoreToken::new(store.as_context_mut());
4474 let start_func = Box::new(
4475 move |store: &mut dyn VMStore, guest_thread: QualifiedThreadId| -> Result<()> {
4476 let old_thread = store.set_thread(guest_thread)?;
4477 log::trace!(
4478 "thread start: replaced {old_thread:?} with {guest_thread:?} as current thread"
4479 );
4480
4481 let mut store = token.as_context_mut(store);
4482 let mut params = [ValRaw::i32(context)];
4483 let func_ref = callee.vm_func_ref(store.0);
4487 unsafe {
4488 crate::Func::call_unchecked_raw(
4489 &mut store,
4490 func_ref,
4491 NonNull::from(&mut params[..]),
4492 UncaughtException::Trap,
4493 )?;
4494 }
4495
4496 store.0.set_thread(old_thread)?;
4497
4498 let runtime_instance = self.runtime_instance(runtime_instance);
4499
4500 store
4503 .0
4504 .switch_or_trap_if_may_not_suspend(runtime_instance)?;
4505
4506 store.0.cleanup_thread(guest_thread, runtime_instance)?;
4507
4508 log::trace!("explicit thread {guest_thread:?} completed");
4509 let state = store.0.concurrent_state_mut()?;
4510 if let Some(t) = old_thread.guest() {
4511 state.set_thread_running(t.thread)?;
4512 }
4513 log::trace!("thread start: restored {old_thread:?} as current thread");
4514
4515 Ok(())
4516 },
4517 );
4518
4519 let current_thread = store.0.current_guest_thread()?;
4520 let state = store.0.concurrent_state_mut()?;
4521 let parent_task = current_thread.task;
4522
4523 let new_thread = GuestThread::new_explicit(state, parent_task, start_func)?;
4524 let thread_id = state.push(new_thread)?;
4525 state.get_mut(parent_task)?.threads.insert(thread_id);
4526
4527 log::trace!("new thread with id {thread_id:?} created");
4528
4529 self.add_guest_thread_to_instance_table(thread_id, store.0, runtime_instance)
4530 }
4531
4532 pub(crate) fn resume_thread(
4533 self,
4534 store: &mut StoreOpaque,
4535 runtime_instance: RuntimeComponentInstanceIndex,
4536 thread_idx: u32,
4537 how: ResumeThread,
4538 ) -> Result<bool> {
4539 let thread_id =
4540 GuestThread::from_instance(self.id().get_mut(store), runtime_instance, thread_idx)?;
4541 let state = store.concurrent_state_mut()?;
4542 let guest_thread = QualifiedThreadId::qualify(state, thread_id)?;
4543
4544 if store.current_guest_thread()? == guest_thread {
4545 bail!(Trap::CannotResumeThread);
4546 }
4547
4548 let priority = match how {
4549 ResumeThread::Resume => Priority::Switch,
4550 ResumeThread::ResumeLater => Priority::Low,
4551
4552 ResumeThread::Promote => {
4555 let instance = self.runtime_instance(runtime_instance);
4556 let do_not_enter = store
4557 .instance_state(instance)
4558 .concurrent_state()
4559 .do_not_enter;
4560 return store.concurrent_state_mut()?.promote_work_item_matching(
4561 |item: &WorkItem| match item {
4562 WorkItem::ResumeThread { thread, .. }
4563 | WorkItem::ResumeFiber { thread, .. } => *thread == guest_thread,
4564
4565 WorkItem::GuestCall {
4566 call: GuestCall { thread, kind },
4567 ..
4568 } => {
4569 *thread == guest_thread
4570 && match kind {
4571 GuestCallKind::DeliverEvent { .. } => !do_not_enter,
4575
4576 GuestCallKind::StartExplicit(_) => true,
4579
4580 GuestCallKind::StartImplicit { .. } => false,
4584 }
4585 }
4586
4587 WorkItem::PushFuture(_) | WorkItem::WorkerFunction(_) => false,
4588 },
4589 );
4590 }
4591 };
4592
4593 let state = store.concurrent_state_mut()?;
4594 let thread = state.get_mut(guest_thread.thread)?;
4595
4596 match &thread.state {
4599 GuestThreadState::NotStartedExplicit(_) => {}
4600 GuestThreadState::Suspended(_) => {
4601 log::trace!("resuming thread {thread_id:?} that was suspended");
4602 state.schedule_suspended_thread(
4603 guest_thread,
4604 self.runtime_instance(runtime_instance),
4605 priority,
4606 )?;
4607 return Ok(true);
4608 }
4609 _ => bail!(Trap::CannotResumeThread),
4610 }
4611 match mem::replace(&mut thread.state, GuestThreadState::Running) {
4612 GuestThreadState::NotStartedExplicit(start_func) => {
4613 log::trace!("starting thread {guest_thread:?}");
4614 let guest_call = WorkItem::GuestCall {
4615 instance: self.runtime_instance(runtime_instance),
4616 call: GuestCall {
4617 thread: guest_thread,
4618 kind: GuestCallKind::StartExplicit(Box::new(move |store| {
4619 start_func(store, guest_thread)
4620 })),
4621 },
4622 };
4623 state.push_work_item(guest_call, priority)?;
4624 }
4625 other => {
4626 thread.state = other;
4627 bail_bug!("thread state checked to be resumable above");
4628 }
4629 }
4630 Ok(true)
4631 }
4632
4633 fn add_guest_thread_to_instance_table(
4634 self,
4635 thread_id: TableId<GuestThread>,
4636 store: &mut StoreOpaque,
4637 runtime_instance: RuntimeComponentInstanceIndex,
4638 ) -> Result<u32> {
4639 let (state, counter) =
4640 store.instance_state_and_handle_counter(self.runtime_instance(runtime_instance));
4641 let guest_id = state
4642 .thread_handle_table()
4643 .guest_thread_insert(counter, thread_id.rep())?;
4644 store
4645 .concurrent_state_mut()?
4646 .get_mut(thread_id)?
4647 .instance_rep = Some(guest_id);
4648 Ok(guest_id)
4649 }
4650
4651 pub(crate) fn suspension_intrinsic(
4655 self,
4656 store: &mut StoreOpaque,
4657 caller: RuntimeComponentInstanceIndex,
4658 yielding: bool,
4659 to_thread: SuspensionTarget,
4660 ) -> Result<WaitResult> {
4661 let check_suspend = match to_thread {
4662 SuspensionTarget::Promote(thread) => {
4663 !self.resume_thread(store, caller, thread, ResumeThread::Promote)?
4664 }
4665 SuspensionTarget::Resume(thread) => {
4666 if !self.resume_thread(store, caller, thread, ResumeThread::Resume)? {
4667 bail_bug!(
4668 "`resume_thread` should only ever return false \
4669 when `ResumeThread::Promote` is passed to it"
4670 );
4671 }
4672 false
4673 }
4674 SuspensionTarget::None => true,
4675 };
4676
4677 if check_suspend && !store.switch_if_may_not_suspend(self.runtime_instance(caller))? {
4678 return if yielding {
4679 Ok(WaitResult::Completed)
4680 } else {
4681 Err(Trap::CannotBlockSyncTask.into())
4682 };
4683 }
4684
4685 let guest_thread = store.current_guest_thread()?;
4686
4687 let reason = if yielding {
4688 SuspendReason::Yielding {
4689 thread: guest_thread,
4690 }
4691 } else {
4692 SuspendReason::ExplicitlySuspending {
4693 thread: guest_thread,
4694 }
4695 };
4696
4697 store.suspend(reason)?;
4698
4699 Ok(WaitResult::Completed)
4700 }
4701
4702 fn waitable_check(
4704 self,
4705 store: &mut StoreOpaque,
4706 caller: RuntimeInstance,
4707 check: WaitableCheck,
4708 params: WaitableCheckParams,
4709 ) -> Result<u32> {
4710 let guest_thread = store.current_guest_thread()?;
4711
4712 log::trace!("waitable check for {guest_thread:?}; set {:?}", params.set);
4713
4714 match &check {
4717 WaitableCheck::Wait => {
4718 let set = params.set;
4719
4720 loop {
4725 let state = store.concurrent_state_mut()?;
4726 let task = state.get_mut(guest_thread.task)?;
4727 if !(task.event.is_none() || matches!(task.event, Some(Event::Cancelled)))
4728 || !state.get_mut(set)?.ready.is_empty()
4729 {
4730 break;
4731 }
4732
4733 store.switch_or_trap_if_may_not_suspend(caller)?;
4734
4735 store.suspend(SuspendReason::Waiting {
4736 set,
4737 thread: guest_thread,
4738 })?;
4739 }
4740 }
4741 WaitableCheck::Poll => {}
4742 }
4743
4744 log::trace!(
4745 "waitable check for {guest_thread:?}; set {:?}, part two",
4746 params.set
4747 );
4748
4749 let event = self.get_event(store, guest_thread.task, Some(params.set), false)?;
4751
4752 let (ordinal, handle, result) = match &check {
4753 WaitableCheck::Wait => {
4754 let (event, waitable) = match event {
4755 Some(p) => p,
4756 None => bail_bug!("event expected to be present"),
4757 };
4758 let handle = waitable.map(|(_, v)| v).unwrap_or(0);
4759 let (ordinal, result) = event.parts();
4760 (ordinal, handle, result)
4761 }
4762 WaitableCheck::Poll => {
4763 if let Some((event, waitable)) = event {
4764 let handle = waitable.map(|(_, v)| v).unwrap_or(0);
4765 let (ordinal, result) = event.parts();
4766 (ordinal, handle, result)
4767 } else {
4768 log::trace!(
4769 "no events ready to deliver via waitable-set.poll to {:?}; set {:?}",
4770 guest_thread.task,
4771 params.set
4772 );
4773 let (ordinal, result) = Event::None.parts();
4774 (ordinal, 0, result)
4775 }
4776 }
4777 };
4778 let ptr = crate::component::func::validate_inbounds_dynamic(
4779 &CanonicalAbiInfo::POINTER_PAIR,
4780 self.options_memory(store, params.options),
4781 &ValRaw::u32(params.payload),
4782 )?;
4783 let memory = self
4784 .options_memory_range_mut(store, params.options, ptr, 8)
4785 .unwrap();
4786 memory[0..4].copy_from_slice(&handle.to_le_bytes());
4787 memory[4..8].copy_from_slice(&result.to_le_bytes());
4788 Ok(ordinal)
4789 }
4790
4791 pub(crate) fn subtask_cancel(
4793 self,
4794 store: &mut StoreOpaque,
4795 caller_instance: RuntimeComponentInstanceIndex,
4796 async_: bool,
4797 task_id: u32,
4798 ) -> Result<u32> {
4799 let (rep, is_host) = store
4800 .instance_state(self.runtime_instance(caller_instance))
4801 .handle_table()
4802 .subtask_rep(task_id)?;
4803 let waitable = if is_host {
4804 Waitable::Host(TableId::<HostTask>::new(rep))
4805 } else {
4806 Waitable::Guest(TableId::<GuestTask>::new(rep))
4807 };
4808 let concurrent_state = store.concurrent_state_mut()?;
4809
4810 log::trace!("subtask_cancel {waitable:?} (handle {task_id}; async {async_})");
4811
4812 waitable.trap_if_in_waitable_set(concurrent_state)?;
4813
4814 let needs_block;
4815 if let Waitable::Host(host_task) = waitable {
4816 let state = &mut concurrent_state.get_mut(host_task)?.state;
4817 match state {
4818 HostTaskState::CalleeRunning(handle) => {
4825 handle.abort();
4826 *state = HostTaskState::CalleeCancelling;
4827 needs_block = true;
4828 }
4829
4830 HostTaskState::CalleeCancelling | HostTaskState::CalleeDone { cancelled: true } => {
4833 bail!(Trap::SubtaskCancelAfterTerminal);
4834 }
4835 HostTaskState::CalleeDone { cancelled: false } => {
4836 *state = HostTaskState::CalleeDone { cancelled: true };
4839 needs_block = false;
4840 }
4841
4842 HostTaskState::CalleeStarted | HostTaskState::CalleeFinished(_) => {
4845 bail_bug!("invalid states for host callee")
4846 }
4847 }
4848 } else {
4849 let guest_task = TableId::<GuestTask>::new(rep);
4850 let task = concurrent_state.get_mut(guest_task)?;
4851
4852 if task.cancel_requested {
4855 bail!(Trap::SubtaskCancelAfterTerminal);
4856 }
4857
4858 if !task.already_lowered_parameters() {
4859 store.cancel_guest_subtask_without_lowered_parameters(
4860 self.runtime_instance(caller_instance),
4861 guest_task,
4862 )?;
4863 return Ok(Status::StartCancelled as u32);
4864 } else if !task.returned_or_cancelled() {
4865 task.cancel_requested = true;
4872 task.event = Some(Event::Cancelled);
4873 let runtime_instance = task.instance;
4874 for thread in task.threads.clone() {
4875 let thread = QualifiedThreadId {
4876 task: guest_task,
4877 thread,
4878 };
4879 let concurrent_state = store.concurrent_state_mut()?;
4880 let thread_mut = concurrent_state.get_mut(thread.thread)?;
4881
4882 let yield_ = |store: &mut StoreOpaque| {
4883 let state = store.instance_state(runtime_instance).concurrent_state();
4888 let old_do_not_suspend = state.do_not_suspend;
4889 state.do_not_suspend = false;
4890
4891 let caller = store.current_guest_thread()?;
4892
4893 let state = store.concurrent_state_mut()?;
4898 let set = state.get_mut(caller.thread)?.sync_call_set;
4899 waitable.join(state, Some(set))?;
4900
4901 store.suspend(SuspendReason::YieldingToSubtask { thread: caller })?;
4902
4903 let state = store.concurrent_state_mut()?;
4904 waitable.join(state, None)?;
4905
4906 store
4907 .instance_state(runtime_instance)
4908 .concurrent_state()
4909 .do_not_suspend = old_do_not_suspend;
4910
4911 Ok::<(), crate::Error>(())
4912 };
4913
4914 match thread_mut.wake_on_cancel.take() {
4915 WakeOnCancel::Waiting(set) => {
4916 let instance = concurrent_state.take_callback_waiter(set, thread)?;
4918 let item = WorkItem::GuestCall {
4919 instance: runtime_instance,
4920 call: GuestCall {
4921 thread,
4922 kind: GuestCallKind::DeliverEvent {
4923 instance,
4924 set: Some(set),
4925 },
4926 },
4927 };
4928 concurrent_state.set_switch_item(item)?;
4929
4930 yield_(store)?;
4931
4932 break;
4933 }
4934 WakeOnCancel::Yielding => {
4935 if concurrent_state.promote_thread_work_item(thread)? {
4936 yield_(store)?;
4937 break;
4938 } else if store
4939 .instance_state(runtime_instance)
4940 .concurrent_state()
4941 .pending
4942 .contains_key(&thread)
4943 {
4944 store
4954 .concurrent_state_mut()?
4955 .get_mut(thread.thread)?
4956 .wake_on_cancel = WakeOnCancel::Yielding;
4957 } else {
4958 bail_bug!("thread with `WakeOnCancel::Yielding` not promotable");
4959 }
4960 }
4961 WakeOnCancel::None => {}
4962 }
4963 }
4964
4965 needs_block = !store
4968 .concurrent_state_mut()?
4969 .get_mut(guest_task)?
4970 .returned_or_cancelled()
4971 } else {
4972 needs_block = false;
4973 }
4974 };
4975
4976 if needs_block {
4980 if async_ {
4981 return Ok(BLOCKED);
4982 }
4983
4984 let old_next_switch_item = if is_host {
4994 Some(store.concurrent_state_mut()?.save_next_switch_item()?)
4995 } else {
4996 None
4997 };
4998
4999 store.wait_for_event(self.runtime_instance(caller_instance), waitable)?;
5002
5003 if let Some(item) = old_next_switch_item {
5004 let state = store.concurrent_state_mut()?;
5005 state.restore_next_switch_item(item)?;
5006 }
5007
5008 }
5010
5011 let event = waitable.take_event(store.concurrent_state_mut()?)?;
5012 if let Some(Event::Subtask {
5013 status: status @ (Status::Returned | Status::ReturnCancelled),
5014 }) = event
5015 {
5016 Ok(status as u32)
5017 } else {
5018 bail!(Trap::SubtaskCancelAfterTerminal);
5019 }
5020 }
5021}
5022
5023pub trait VMComponentAsyncStore {
5031 unsafe fn prepare_call(
5037 &mut self,
5038 instance: Instance,
5039 memory: *mut VMMemoryDefinition,
5040 start: NonNull<VMFuncRef>,
5041 return_: NonNull<VMFuncRef>,
5042 caller_instance: RuntimeComponentInstanceIndex,
5043 callee_instance: RuntimeComponentInstanceIndex,
5044 task_return_type: TypeTupleIndex,
5045 callee_async: bool,
5046 string_encoding: StringEncoding,
5047 result_count: u32,
5048 storage: *mut ValRaw,
5049 storage_len: usize,
5050 ) -> Result<()>;
5051
5052 unsafe fn start_call(
5055 &mut self,
5056 instance: Instance,
5057 callback: *mut VMFuncRef,
5058 post_return: *mut VMFuncRef,
5059 callee: NonNull<VMFuncRef>,
5060 param_count: u32,
5061 result_count: u32,
5062 flags: u32,
5063 storage: *mut MaybeUninit<ValRaw>,
5064 storage_len: usize,
5065 ) -> Result<()>;
5066
5067 fn future_write(
5069 &mut self,
5070 instance: Instance,
5071 caller: RuntimeComponentInstanceIndex,
5072 ty: TypeFutureTableIndex,
5073 options: OptionsIndex,
5074 future: u32,
5075 address: u32,
5076 ) -> Result<u32>;
5077
5078 fn future_read(
5080 &mut self,
5081 instance: Instance,
5082 caller: RuntimeComponentInstanceIndex,
5083 ty: TypeFutureTableIndex,
5084 options: OptionsIndex,
5085 future: u32,
5086 address: u32,
5087 ) -> Result<u32>;
5088
5089 fn future_drop_writable(
5091 &mut self,
5092 instance: Instance,
5093 ty: TypeFutureTableIndex,
5094 writer: u32,
5095 ) -> Result<()>;
5096
5097 fn stream_write(
5099 &mut self,
5100 instance: Instance,
5101 caller: RuntimeComponentInstanceIndex,
5102 ty: TypeStreamTableIndex,
5103 options: OptionsIndex,
5104 stream: u32,
5105 address: u32,
5106 count: u32,
5107 ) -> Result<u32>;
5108
5109 fn stream_read(
5111 &mut self,
5112 instance: Instance,
5113 caller: RuntimeComponentInstanceIndex,
5114 ty: TypeStreamTableIndex,
5115 options: OptionsIndex,
5116 stream: u32,
5117 address: u32,
5118 count: u32,
5119 ) -> Result<u32>;
5120
5121 fn flat_stream_write(
5124 &mut self,
5125 instance: Instance,
5126 caller: RuntimeComponentInstanceIndex,
5127 ty: TypeStreamTableIndex,
5128 options: OptionsIndex,
5129 payload_size: u32,
5130 payload_align: u32,
5131 stream: u32,
5132 address: u32,
5133 count: u32,
5134 ) -> Result<u32>;
5135
5136 fn flat_stream_read(
5139 &mut self,
5140 instance: Instance,
5141 caller: RuntimeComponentInstanceIndex,
5142 ty: TypeStreamTableIndex,
5143 options: OptionsIndex,
5144 payload_size: u32,
5145 payload_align: u32,
5146 stream: u32,
5147 address: u32,
5148 count: u32,
5149 ) -> Result<u32>;
5150
5151 fn stream_drop_writable(
5153 &mut self,
5154 instance: Instance,
5155 ty: TypeStreamTableIndex,
5156 writer: u32,
5157 ) -> Result<()>;
5158
5159 fn error_context_debug_message(
5161 &mut self,
5162 instance: Instance,
5163 ty: TypeComponentLocalErrorContextTableIndex,
5164 options: OptionsIndex,
5165 err_ctx_handle: u32,
5166 debug_msg_address: u32,
5167 ) -> Result<()>;
5168
5169 fn thread_new_indirect(
5171 &mut self,
5172 instance: Instance,
5173 caller: RuntimeComponentInstanceIndex,
5174 func_ty_idx: ModuleInternedTypeIndex,
5175 start_func_table_idx: RuntimeTableIndex,
5176 start_func_idx: u32,
5177 context: i32,
5178 ) -> Result<u32>;
5179}
5180
5181impl<T: 'static> VMComponentAsyncStore for StoreInner<T> {
5183 unsafe fn prepare_call(
5184 &mut self,
5185 instance: Instance,
5186 memory: *mut VMMemoryDefinition,
5187 start: NonNull<VMFuncRef>,
5188 return_: NonNull<VMFuncRef>,
5189 caller_instance: RuntimeComponentInstanceIndex,
5190 callee_instance: RuntimeComponentInstanceIndex,
5191 task_return_type: TypeTupleIndex,
5192 callee_async: bool,
5193 string_encoding: StringEncoding,
5194 result_count_or_max_if_async: u32,
5195 storage: *mut ValRaw,
5196 storage_len: usize,
5197 ) -> Result<()> {
5198 let params = unsafe { core::slice::from_raw_parts(storage, storage_len) }.to_vec();
5202
5203 unsafe {
5204 instance.prepare_call(
5205 StoreContextMut(self),
5206 start,
5207 return_,
5208 caller_instance,
5209 callee_instance,
5210 task_return_type,
5211 callee_async,
5212 memory,
5213 string_encoding,
5214 match result_count_or_max_if_async {
5215 PREPARE_ASYNC_NO_RESULT => CallerInfo::Async {
5216 params,
5217 has_result: false,
5218 },
5219 PREPARE_ASYNC_WITH_RESULT => CallerInfo::Async {
5220 params,
5221 has_result: true,
5222 },
5223 result_count => CallerInfo::Sync {
5224 params,
5225 result_count,
5226 },
5227 },
5228 )
5229 }
5230 }
5231
5232 unsafe fn start_call(
5233 &mut self,
5234 instance: Instance,
5235 callback: *mut VMFuncRef,
5236 post_return: *mut VMFuncRef,
5237 callee: NonNull<VMFuncRef>,
5238 param_count: u32,
5239 result_count: u32,
5240 flags: u32,
5241 storage: *mut MaybeUninit<ValRaw>,
5242 storage_len: usize,
5243 ) -> Result<()> {
5244 unsafe {
5245 instance.start_call(
5246 StoreContextMut(self),
5247 callback,
5248 post_return,
5249 callee,
5250 param_count,
5251 result_count,
5252 flags,
5253 core::slice::from_raw_parts_mut(storage, storage_len),
5257 )
5258 }
5259 }
5260
5261 fn future_write(
5262 &mut self,
5263 instance: Instance,
5264 caller: RuntimeComponentInstanceIndex,
5265 ty: TypeFutureTableIndex,
5266 options: OptionsIndex,
5267 future: u32,
5268 address: u32,
5269 ) -> Result<u32> {
5270 instance
5271 .guest_write(
5272 StoreContextMut(self),
5273 caller,
5274 TransmitIndex::Future(ty),
5275 options,
5276 None,
5277 future,
5278 address,
5279 1,
5280 )
5281 .map(|result| result.encode())
5282 }
5283
5284 fn future_read(
5285 &mut self,
5286 instance: Instance,
5287 caller: RuntimeComponentInstanceIndex,
5288 ty: TypeFutureTableIndex,
5289 options: OptionsIndex,
5290 future: u32,
5291 address: u32,
5292 ) -> Result<u32> {
5293 instance
5294 .guest_read(
5295 StoreContextMut(self),
5296 caller,
5297 TransmitIndex::Future(ty),
5298 options,
5299 None,
5300 future,
5301 address,
5302 1,
5303 )
5304 .map(|result| result.encode())
5305 }
5306
5307 fn stream_write(
5308 &mut self,
5309 instance: Instance,
5310 caller: RuntimeComponentInstanceIndex,
5311 ty: TypeStreamTableIndex,
5312 options: OptionsIndex,
5313 stream: u32,
5314 address: u32,
5315 count: u32,
5316 ) -> Result<u32> {
5317 instance
5318 .guest_write(
5319 StoreContextMut(self),
5320 caller,
5321 TransmitIndex::Stream(ty),
5322 options,
5323 None,
5324 stream,
5325 address,
5326 count,
5327 )
5328 .map(|result| result.encode())
5329 }
5330
5331 fn stream_read(
5332 &mut self,
5333 instance: Instance,
5334 caller: RuntimeComponentInstanceIndex,
5335 ty: TypeStreamTableIndex,
5336 options: OptionsIndex,
5337 stream: u32,
5338 address: u32,
5339 count: u32,
5340 ) -> Result<u32> {
5341 instance
5342 .guest_read(
5343 StoreContextMut(self),
5344 caller,
5345 TransmitIndex::Stream(ty),
5346 options,
5347 None,
5348 stream,
5349 address,
5350 count,
5351 )
5352 .map(|result| result.encode())
5353 }
5354
5355 fn future_drop_writable(
5356 &mut self,
5357 instance: Instance,
5358 ty: TypeFutureTableIndex,
5359 writer: u32,
5360 ) -> Result<()> {
5361 instance.guest_drop_writable(self, TransmitIndex::Future(ty), writer)
5362 }
5363
5364 fn flat_stream_write(
5365 &mut self,
5366 instance: Instance,
5367 caller: RuntimeComponentInstanceIndex,
5368 ty: TypeStreamTableIndex,
5369 options: OptionsIndex,
5370 payload_size: u32,
5371 payload_align: u32,
5372 stream: u32,
5373 address: u32,
5374 count: u32,
5375 ) -> Result<u32> {
5376 instance
5377 .guest_write(
5378 StoreContextMut(self),
5379 caller,
5380 TransmitIndex::Stream(ty),
5381 options,
5382 Some(FlatAbi {
5383 size: payload_size,
5384 align: payload_align,
5385 }),
5386 stream,
5387 address,
5388 count,
5389 )
5390 .map(|result| result.encode())
5391 }
5392
5393 fn flat_stream_read(
5394 &mut self,
5395 instance: Instance,
5396 caller: RuntimeComponentInstanceIndex,
5397 ty: TypeStreamTableIndex,
5398 options: OptionsIndex,
5399 payload_size: u32,
5400 payload_align: u32,
5401 stream: u32,
5402 address: u32,
5403 count: u32,
5404 ) -> Result<u32> {
5405 instance
5406 .guest_read(
5407 StoreContextMut(self),
5408 caller,
5409 TransmitIndex::Stream(ty),
5410 options,
5411 Some(FlatAbi {
5412 size: payload_size,
5413 align: payload_align,
5414 }),
5415 stream,
5416 address,
5417 count,
5418 )
5419 .map(|result| result.encode())
5420 }
5421
5422 fn stream_drop_writable(
5423 &mut self,
5424 instance: Instance,
5425 ty: TypeStreamTableIndex,
5426 writer: u32,
5427 ) -> Result<()> {
5428 instance.guest_drop_writable(self, TransmitIndex::Stream(ty), writer)
5429 }
5430
5431 fn error_context_debug_message(
5432 &mut self,
5433 instance: Instance,
5434 ty: TypeComponentLocalErrorContextTableIndex,
5435 options: OptionsIndex,
5436 err_ctx_handle: u32,
5437 debug_msg_address: u32,
5438 ) -> Result<()> {
5439 instance.error_context_debug_message(
5440 StoreContextMut(self),
5441 ty,
5442 options,
5443 err_ctx_handle,
5444 debug_msg_address,
5445 )
5446 }
5447
5448 fn thread_new_indirect(
5449 &mut self,
5450 instance: Instance,
5451 caller: RuntimeComponentInstanceIndex,
5452 func_ty_idx: ModuleInternedTypeIndex,
5453 start_func_table_idx: RuntimeTableIndex,
5454 start_func_idx: u32,
5455 context: i32,
5456 ) -> Result<u32> {
5457 instance.thread_new_indirect(
5458 StoreContextMut(self),
5459 caller,
5460 func_ty_idx,
5461 start_func_table_idx,
5462 start_func_idx,
5463 context,
5464 )
5465 }
5466}
5467
5468type HostTaskFuture = Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>;
5469
5470async fn run_with_host_task_set<F>(task: TableId<HostTask>, future: F) -> Result<F::Output>
5473where
5474 F: Future,
5475{
5476 let mut future = pin!(future);
5477 future::poll_fn(|cx| {
5478 let old_thread = match tls::get(|store| store.set_thread(task)) {
5479 Ok(thread) => thread,
5480 Err(error) => return Poll::Ready(Err(error)),
5481 };
5482 let result = future.as_mut().poll(cx);
5483 match tls::get(|store| store.set_thread(old_thread)) {
5484 Ok(_) => result.map(Ok),
5485 Err(error) => Poll::Ready(Err(error)),
5486 }
5487 })
5488 .await
5489}
5490
5491pub(crate) struct HostTask {
5495 common: WaitableCommon,
5496
5497 call_context: CallContext,
5500
5501 state: HostTaskState,
5502
5503 group: TaskGroupId,
5504}
5505
5506enum HostTaskState {
5507 CalleeStarted,
5512
5513 CalleeRunning(JoinHandle),
5518
5519 CalleeCancelling,
5523
5524 CalleeFinished(LiftedResult),
5528
5529 CalleeDone { cancelled: bool },
5532}
5533
5534impl HostTask {
5535 fn new(
5536 concurrent_state: &mut ConcurrentState,
5537 state: HostTaskState,
5538 caller: QualifiedThreadId,
5539 ) -> Result<Self> {
5540 let group = concurrent_state.get_mut(caller.task)?.group;
5541 concurrent_state.increment_group_ref_count(group)?;
5542
5543 Ok(Self {
5544 common: WaitableCommon::default(),
5545 call_context: CallContext::default(),
5546 state,
5547 group,
5548 })
5549 }
5550}
5551
5552impl TableDebug for HostTask {
5553 fn type_name() -> &'static str {
5554 "HostTask"
5555 }
5556}
5557
5558type CallbackFn = Box<dyn Fn(&mut dyn VMStore, Event, u32) -> Result<u32> + Send + Sync + 'static>;
5559
5560enum Caller {
5562 Host {
5564 tx: Option<oneshot::Sender<LiftedResult>>,
5566 caller: Option<TableId<HostTask>>,
5570 },
5571 Guest {
5573 thread: QualifiedThreadId,
5575 },
5576}
5577
5578struct LiftResult {
5581 lift: RawLift,
5582 ty: TypeTupleIndex,
5583 memory: Option<SendSyncPtr<VMMemoryDefinition>>,
5584 string_encoding: StringEncoding,
5585}
5586
5587#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
5592pub(crate) struct QualifiedThreadId {
5593 task: TableId<GuestTask>,
5594 thread: TableId<GuestThread>,
5595}
5596
5597impl QualifiedThreadId {
5598 fn qualify(
5599 state: &mut ConcurrentState,
5600 thread: TableId<GuestThread>,
5601 ) -> Result<QualifiedThreadId> {
5602 Ok(QualifiedThreadId {
5603 task: state.get_mut(thread)?.parent_task,
5604 thread,
5605 })
5606 }
5607}
5608
5609impl fmt::Debug for QualifiedThreadId {
5610 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5611 f.debug_tuple("QualifiedThreadId")
5612 .field(&self.task.rep())
5613 .field(&self.thread.rep())
5614 .finish()
5615 }
5616}
5617
5618enum GuestThreadState {
5619 NotStartedImplicit,
5620 NotStartedExplicit(
5621 Box<dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync>,
5622 ),
5623 Running,
5624 Suspended(StoreFiber<'static>),
5625 Ready {
5626 fiber: StoreFiber<'static>,
5627 },
5628 Completed,
5629}
5630
5631impl GuestThreadState {
5632 fn check_no_fiber(&self) -> Result<()> {
5633 match self {
5634 Self::Suspended(_) | Self::Ready { .. } => bail_bug!("thread already owns a fiber"),
5635 Self::NotStartedImplicit
5636 | Self::NotStartedExplicit(_)
5637 | Self::Running
5638 | Self::Completed => Ok(()),
5639 }
5640 }
5641}
5642
5643impl fmt::Debug for GuestThreadState {
5644 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5645 match self {
5646 Self::NotStartedImplicit => f.debug_tuple("NotStartedImplicit").finish(),
5647 Self::NotStartedExplicit(_) => f.debug_tuple("NotStartedExplicit").finish(),
5648 Self::Running => f.debug_tuple("Running").finish(),
5649 Self::Suspended(_) => f.debug_tuple("Suspended").finish(),
5650 Self::Ready { .. } => f.debug_struct("Ready").finish(),
5651 Self::Completed => f.debug_tuple("Completed").finish(),
5652 }
5653 }
5654}
5655
5656#[derive(Copy, Clone, PartialEq, Eq, Debug)]
5657enum WakeOnCancel {
5658 None,
5659 Waiting(TableId<WaitableSet>),
5660 Yielding,
5661}
5662
5663impl WakeOnCancel {
5664 fn is_none(self) -> bool {
5665 matches!(self, WakeOnCancel::None)
5666 }
5667
5668 fn replace(&mut self, other: WakeOnCancel) -> Self {
5669 let old = *self;
5670 *self = other;
5671 old
5672 }
5673
5674 fn take(&mut self) -> Self {
5675 self.replace(WakeOnCancel::None)
5676 }
5677}
5678
5679pub struct GuestThread {
5680 context: [u32; NUM_COMPONENT_CONTEXT_SLOTS],
5683 parent_task: TableId<GuestTask>,
5685 wake_on_cancel: WakeOnCancel,
5688 state: GuestThreadState,
5690 instance_rep: Option<u32>,
5693 sync_call_set: TableId<WaitableSet>,
5695 old_do_not_suspend: Option<bool>,
5698}
5699
5700impl GuestThread {
5701 fn from_instance(
5704 state: Pin<&mut ComponentInstance>,
5705 caller_instance: RuntimeComponentInstanceIndex,
5706 guest_thread: u32,
5707 ) -> Result<TableId<Self>> {
5708 let rep = state.instance_states().0[caller_instance]
5709 .thread_handle_table()
5710 .guest_thread_rep(guest_thread)?;
5711 Ok(TableId::new(rep))
5712 }
5713
5714 fn new_implicit(state: &mut ConcurrentState, parent_task: TableId<GuestTask>) -> Result<Self> {
5715 let sync_call_set = state.push(WaitableSet {
5716 is_sync_call_set: true,
5717 ..WaitableSet::default()
5718 })?;
5719 Ok(Self {
5720 context: [0; NUM_COMPONENT_CONTEXT_SLOTS],
5721 parent_task,
5722 wake_on_cancel: WakeOnCancel::None,
5723 state: GuestThreadState::NotStartedImplicit,
5724 instance_rep: None,
5725 sync_call_set,
5726 old_do_not_suspend: None,
5727 })
5728 }
5729
5730 fn new_explicit(
5731 state: &mut ConcurrentState,
5732 parent_task: TableId<GuestTask>,
5733 start_func: Box<
5734 dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync,
5735 >,
5736 ) -> Result<Self> {
5737 state.increment_task_ref_count(parent_task)?;
5738 let sync_call_set = state.push(WaitableSet {
5739 is_sync_call_set: true,
5740 ..WaitableSet::default()
5741 })?;
5742 Ok(Self {
5743 context: [0; NUM_COMPONENT_CONTEXT_SLOTS],
5744 parent_task,
5745 wake_on_cancel: WakeOnCancel::None,
5746 state: GuestThreadState::NotStartedExplicit(start_func),
5747 instance_rep: None,
5748 sync_call_set,
5749 old_do_not_suspend: None,
5750 })
5751 }
5752}
5753
5754impl TableDebug for GuestThread {
5755 fn type_name() -> &'static str {
5756 "GuestThread"
5757 }
5758}
5759
5760enum SyncResult {
5761 NotProduced,
5762 Produced(Option<ValRaw>),
5763 Taken,
5764}
5765
5766impl SyncResult {
5767 fn take(&mut self) -> Result<Option<Option<ValRaw>>> {
5768 Ok(match mem::replace(self, SyncResult::Taken) {
5769 SyncResult::NotProduced => None,
5770 SyncResult::Produced(val) => Some(val),
5771 SyncResult::Taken => {
5772 bail_bug!("attempted to take a synchronous result that was already taken")
5773 }
5774 })
5775 }
5776}
5777
5778pub(crate) struct GuestTask {
5780 common: WaitableCommon,
5782 lower_params: Option<RawLower>,
5784 lift_result: Option<LiftResult>,
5786 result: Option<LiftedResult>,
5789 callback: Option<CallbackFn>,
5792 caller: Caller,
5794 call_context: CallContext,
5799 sync_result: SyncResult,
5802 cancel_request_delivered: bool,
5806 cancel_requested: bool,
5811 starting_sent: bool,
5814 instance: RuntimeInstance,
5821 event: Option<Event>,
5823 exited: bool,
5825 threads: HashSet<TableId<GuestThread>>,
5827 async_typed: bool,
5830 async_lifted: bool,
5833 decremented_interesting_task_count: bool,
5836 group: TaskGroupId,
5838 ref_count: usize,
5843}
5844
5845impl GuestTask {
5846 fn already_lowered_parameters(&self) -> bool {
5847 self.lower_params.is_none()
5849 }
5850
5851 fn returned_or_cancelled(&self) -> bool {
5852 self.lift_result.is_none()
5854 }
5855
5856 fn new(
5857 state: &mut ConcurrentState,
5858 lower_params: RawLower,
5859 lift_result: LiftResult,
5860 caller: Caller,
5861 callback: Option<CallbackFn>,
5862 instance: RuntimeInstance,
5863 async_typed: bool,
5864 async_lifted: bool,
5865 ) -> Result<QualifiedThreadId> {
5866 let group = match caller {
5867 Caller::Guest { thread } => {
5868 let group = state.get_mut(thread.task)?.group;
5869 state.increment_group_ref_count(group)?;
5870 group
5871 }
5872 Caller::Host { .. } => state.make_task_group()?,
5873 };
5874
5875 let task = state.push(Self {
5876 common: WaitableCommon::default(),
5877 lower_params: Some(lower_params),
5878 lift_result: Some(lift_result),
5879 result: None,
5880 callback,
5881 caller,
5882 call_context: CallContext::default(),
5883 sync_result: SyncResult::NotProduced,
5884 cancel_request_delivered: false,
5885 cancel_requested: false,
5886 starting_sent: false,
5887 instance,
5888 event: None,
5889 exited: false,
5890 threads: HashSet::new(),
5891 async_typed,
5892 async_lifted,
5893 decremented_interesting_task_count: false,
5894 group,
5895 ref_count: 2,
5898 })?;
5899 let new_thread = GuestThread::new_implicit(state, task)?;
5900 let thread = state.push(new_thread)?;
5901 state.get_mut(task)?.threads.insert(thread);
5902 state.interesting_tasks += 1;
5903 let thread = QualifiedThreadId { task, thread };
5904 log::trace!("new implicit thread {thread:?} for instance {instance:?}");
5905 Ok(thread)
5906 }
5907}
5908
5909impl TableDebug for GuestTask {
5910 fn type_name() -> &'static str {
5911 "GuestTask"
5912 }
5913}
5914
5915#[derive(Default)]
5917struct WaitableCommon {
5918 event: Option<Event>,
5920 set: Option<TableId<WaitableSet>>,
5922 handle: Option<u32>,
5924}
5925
5926#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
5928enum Waitable {
5929 Host(TableId<HostTask>),
5931 Guest(TableId<GuestTask>),
5933 Transmit(TableId<TransmitHandle>),
5935}
5936
5937impl Waitable {
5938 fn from_instance(
5941 state: Pin<&mut ComponentInstance>,
5942 caller_instance: RuntimeComponentInstanceIndex,
5943 waitable: u32,
5944 ) -> Result<Self> {
5945 use crate::runtime::vm::component::Waitable;
5946
5947 let (waitable, kind) = state.instance_states().0[caller_instance]
5948 .handle_table()
5949 .waitable_rep(waitable)?;
5950
5951 Ok(match kind {
5952 Waitable::Subtask { is_host: true } => Self::Host(TableId::new(waitable)),
5953 Waitable::Subtask { is_host: false } => Self::Guest(TableId::new(waitable)),
5954 Waitable::Stream | Waitable::Future => Self::Transmit(TableId::new(waitable)),
5955 })
5956 }
5957
5958 fn rep(&self) -> u32 {
5960 match self {
5961 Self::Host(id) => id.rep(),
5962 Self::Guest(id) => id.rep(),
5963 Self::Transmit(id) => id.rep(),
5964 }
5965 }
5966
5967 fn join(&self, state: &mut ConcurrentState, set: Option<TableId<WaitableSet>>) -> Result<()> {
5971 log::trace!("waitable {self:?} join set {set:?}");
5972
5973 let old = mem::replace(&mut self.common(state)?.set, set);
5974
5975 if let Some(old) = old {
5976 match *self {
5977 Waitable::Host(id) => state.remove_child(id, old),
5978 Waitable::Guest(id) => state.remove_child(id, old),
5979 Waitable::Transmit(id) => state.remove_child(id, old),
5980 }?;
5981
5982 state.get_mut(old)?.ready.remove(self);
5983 }
5984
5985 if let Some(set) = set {
5986 match *self {
5987 Waitable::Host(id) => state.add_child(id, set),
5988 Waitable::Guest(id) => state.add_child(id, set),
5989 Waitable::Transmit(id) => state.add_child(id, set),
5990 }?;
5991
5992 if self.common(state)?.event.is_some() {
5993 self.mark_ready(state)?;
5994 }
5995 }
5996
5997 Ok(())
5998 }
5999
6000 fn common<'a>(&self, state: &'a mut ConcurrentState) -> Result<&'a mut WaitableCommon> {
6002 Ok(match self {
6003 Self::Host(id) => &mut state.get_mut(*id)?.common,
6004 Self::Guest(id) => &mut state.get_mut(*id)?.common,
6005 Self::Transmit(id) => &mut state.get_mut(*id)?.common,
6006 })
6007 }
6008
6009 fn trap_if_in_waitable_set(&self, state: &mut ConcurrentState) -> Result<()> {
6015 if self.common(state)?.set.is_some() {
6016 bail!(Trap::WaitableSyncAndAsync);
6017 }
6018 Ok(())
6019 }
6020
6021 fn trap_if_has_sync_waiter(&self, state: &mut ConcurrentState) -> Result<()> {
6027 if let Some(set) = self.common(state)?.set
6028 && state.get_mut(set)?.is_sync_call_set
6029 {
6030 bail!(Trap::WaitableSyncAndAsync);
6031 }
6032 Ok(())
6033 }
6034
6035 fn set_event(&self, state: &mut ConcurrentState, event: Option<Event>) -> Result<()> {
6039 log::trace!("set event for {self:?}: {event:?}");
6040 self.common(state)?.event = event;
6041 self.mark_ready(state)
6042 }
6043
6044 fn take_event(&self, state: &mut ConcurrentState) -> Result<Option<Event>> {
6046 let common = self.common(state)?;
6047 let event = common.event.take();
6048 if let Some(set) = self.common(state)?.set {
6049 state.get_mut(set)?.ready.remove(self);
6050 }
6051
6052 Ok(event)
6053 }
6054
6055 fn mark_ready(&self, state: &mut ConcurrentState) -> Result<()> {
6059 if let Some(set) = self.common(state)?.set {
6060 state.get_mut(set)?.ready.insert(*self);
6061 state.wake_waiter(set)?;
6062 }
6063 Ok(())
6064 }
6065
6066 fn delete_from(&self, state: &mut ConcurrentState) -> Result<()> {
6069 match self {
6070 Self::Host(task) => state.delete_host_task(*task),
6071 Self::Guest(task) => state.decrement_task_ref_count(*task),
6072 Self::Transmit(task) => Ok(state.delete(*task).map(drop)?),
6073 }
6074 }
6075}
6076
6077impl fmt::Debug for Waitable {
6078 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6079 match self {
6080 Self::Host(id) => write!(f, "{id:?}"),
6081 Self::Guest(id) => write!(f, "{id:?}"),
6082 Self::Transmit(id) => write!(f, "{id:?}"),
6083 }
6084 }
6085}
6086
6087#[derive(Default)]
6089struct WaitableSet {
6090 ready: BTreeSet<Waitable>,
6092 waiting: BTreeMap<QualifiedThreadId, WaitMode>,
6094 num_waiting: usize,
6097 is_sync_call_set: bool,
6100}
6101
6102impl WaitableSet {
6103 fn stop_waiting(&mut self) -> Result<()> {
6105 self.num_waiting = match self.num_waiting.checked_sub(1) {
6106 Some(n) => n,
6107 None => bail_bug!("waiter not accounted for in waitable set"),
6108 };
6109 Ok(())
6110 }
6111}
6112
6113impl TableDebug for WaitableSet {
6114 fn type_name() -> &'static str {
6115 "WaitableSet"
6116 }
6117}
6118
6119type RawLower =
6121 Box<dyn FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync>;
6122
6123type RawLift = Box<
6125 dyn FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
6126>;
6127
6128type LiftedResult = Box<dyn Any + Send + Sync>;
6132
6133struct DummyResult;
6136
6137#[derive(Default)]
6139pub struct ConcurrentInstanceState {
6140 backpressure: u16,
6142 do_not_enter: bool,
6144 do_not_suspend: bool,
6147 pending: BTreeMap<QualifiedThreadId, GuestCallKind>,
6150 pending_start_count: usize,
6153}
6154
6155impl ConcurrentInstanceState {
6156 pub fn pending_is_empty(&self) -> bool {
6157 self.pending.is_empty()
6158 }
6159}
6160
6161#[derive(Debug, Copy, Clone)]
6162pub(crate) enum CurrentThread {
6163 Guest(QualifiedThreadId),
6166 Host(TableId<HostTask>),
6168 DeferredHost(QualifiedThreadId),
6171 None,
6174}
6175
6176impl CurrentThread {
6177 fn guest(&self) -> Option<&QualifiedThreadId> {
6178 match self {
6179 Self::Guest(id) => Some(id),
6180 _ => None,
6181 }
6182 }
6183
6184 fn guest_task(&self) -> Option<TableId<GuestTask>> {
6185 match self {
6186 Self::Guest(id) => Some(id.task),
6187 _ => None,
6188 }
6189 }
6190
6191 fn is_none(&self) -> bool {
6192 matches!(self, Self::None)
6193 }
6194}
6195
6196impl From<QualifiedThreadId> for CurrentThread {
6197 fn from(id: QualifiedThreadId) -> Self {
6198 Self::Guest(id)
6199 }
6200}
6201
6202impl From<TableId<HostTask>> for CurrentThread {
6203 fn from(id: TableId<HostTask>) -> Self {
6204 Self::Host(id)
6205 }
6206}
6207
6208enum Priority {
6209 Switch,
6210 #[expect(
6211 dead_code,
6212 reason = "Here for completeness and in case we need it later"
6213 )]
6214 High,
6215 Low,
6216}
6217
6218pub struct ConcurrentState {
6220 unforced_current_thread: CurrentThread,
6226
6227 deferred_host_call_context: Option<CallContext>,
6233
6234 futures: AlwaysMut<Option<FuturesUnordered<HostTaskFuture>>>,
6239 table: AlwaysMut<ResourceTable>,
6241 switch_item: Option<WorkItem>,
6249 next_switch_item: Option<WorkItem>,
6255 high_priority: VecDeque<WorkItem>,
6257 low_priority: VecDeque<WorkItem>,
6259 suspend_reason: Option<SuspendReason>,
6263 worker: Option<StoreFiber<'static>>,
6267 worker_item: Option<WorkerItem>,
6269
6270 global_error_context_ref_counts:
6283 BTreeMap<TypeComponentGlobalErrorContextTableIndex, GlobalErrorContextRefCount>,
6284
6285 interesting_tasks: usize,
6298
6299 interesting_tasks_empty_waker: Option<Waker>,
6303
6304 backpressure_waker: Option<Waker>,
6309
6310 idle_waker: Option<Waker>,
6315
6316 event_loop_running: bool,
6318
6319 saved_next_switch_items: Vec<Option<WorkItem>>,
6322
6323 #[cfg(feature = "task-group-hook")]
6325 task_group_hook: Option<Box<dyn TaskGroupHook>>,
6326}
6327
6328impl Default for ConcurrentState {
6329 fn default() -> Self {
6330 Self {
6331 unforced_current_thread: CurrentThread::None,
6332 deferred_host_call_context: None,
6333 table: AlwaysMut::new(ResourceTable::new()),
6334 futures: AlwaysMut::new(Some(FuturesUnordered::new())),
6335 switch_item: None,
6336 next_switch_item: None,
6337 high_priority: VecDeque::new(),
6338 low_priority: VecDeque::new(),
6339 suspend_reason: None,
6340 worker: None,
6341 worker_item: None,
6342 global_error_context_ref_counts: BTreeMap::new(),
6343 interesting_tasks: 0,
6344 interesting_tasks_empty_waker: None,
6345 backpressure_waker: None,
6346 idle_waker: None,
6347 event_loop_running: false,
6348 saved_next_switch_items: Vec::new(),
6349 #[cfg(feature = "task-group-hook")]
6350 task_group_hook: None,
6351 }
6352 }
6353}
6354
6355impl ConcurrentState {
6356 pub(crate) fn take_fibers_and_futures(
6373 &mut self,
6374 fibers: &mut Vec<StoreFiber<'static>>,
6375 futures: &mut Vec<FuturesUnordered<HostTaskFuture>>,
6376 ) {
6377 let ConcurrentState {
6378 table,
6379 worker,
6380 switch_item,
6381 next_switch_item,
6382 high_priority,
6383 low_priority,
6384 saved_next_switch_items,
6385 futures: pending_futures,
6386 worker_item: _,
6387 unforced_current_thread: _,
6388 deferred_host_call_context: _,
6389 suspend_reason: _,
6390 global_error_context_ref_counts: _,
6391 interesting_tasks: _,
6392 interesting_tasks_empty_waker: _,
6393 idle_waker: _,
6394 backpressure_waker: _,
6395 event_loop_running: _,
6396 #[cfg(feature = "task-group-hook")]
6397 task_group_hook: _,
6398 } = self;
6399
6400 let mut items = Vec::new();
6401 for (_, entry) in table.get_mut().iter_mut() {
6402 let entry = entry.into_entry_mut();
6403 if let Some(set) = entry.downcast_mut::<WaitableSet>() {
6404 for mode in mem::take(&mut set.waiting).into_values() {
6405 match mode {
6406 WaitMode::Fiber(fiber) => {
6407 fibers.push(fiber);
6408 }
6409 WaitMode::Callback(_) => {}
6410 }
6411 }
6412 } else if let Some(thread) = entry.downcast_mut::<GuestThread>() {
6413 match mem::replace(&mut thread.state, GuestThreadState::Completed) {
6414 GuestThreadState::Suspended(fiber) | GuestThreadState::Ready { fiber } => {
6415 fibers.push(fiber);
6416 }
6417 GuestThreadState::NotStartedImplicit
6418 | GuestThreadState::NotStartedExplicit(_)
6419 | GuestThreadState::Running
6420 | GuestThreadState::Completed => {}
6421 }
6422 } else if let Some(item) = entry.downcast_mut::<Option<WorkItem>>() {
6423 if let Some(item) = item.take() {
6424 items.push(item);
6425 }
6426 }
6427 }
6428
6429 if let Some(fiber) = worker.take() {
6430 fibers.push(fiber);
6431 }
6432
6433 let mut handle_item = |item| match item {
6434 WorkItem::ResumeFiber { fiber, .. } => {
6435 fibers.push(fiber);
6436 }
6437 WorkItem::PushFuture(future) => {
6438 pending_futures
6439 .get_mut()
6440 .as_mut()
6441 .unwrap()
6442 .push(future.into_inner());
6443 }
6444 WorkItem::ResumeThread { .. }
6445 | WorkItem::GuestCall { .. }
6446 | WorkItem::WorkerFunction(_) => {}
6447 };
6448
6449 for item in items {
6450 handle_item(item);
6451 }
6452 if let Some(item) = switch_item.take() {
6453 handle_item(item);
6454 }
6455 if let Some(item) = next_switch_item.take() {
6456 handle_item(item);
6457 }
6458 for item in mem::take(high_priority) {
6459 handle_item(item);
6460 }
6461 for item in mem::take(low_priority) {
6462 handle_item(item);
6463 }
6464 for item in mem::take(saved_next_switch_items)
6465 .into_iter()
6466 .filter_map(|v| v)
6467 {
6468 handle_item(item);
6469 }
6470
6471 if let Some(them) = pending_futures.get_mut().take() {
6472 futures.push(them);
6473 }
6474 }
6475
6476 #[cfg(feature = "gc")]
6477 pub(crate) fn trace_fiber_roots(
6478 &mut self,
6479 modules: &ModuleRegistry,
6480 unwind: &dyn Unwind,
6481 gc_roots_list: &mut GcRootsList,
6482 ) {
6483 let ConcurrentState {
6484 table,
6485 worker,
6486 switch_item,
6487 next_switch_item,
6488 high_priority,
6489 low_priority,
6490 saved_next_switch_items,
6491
6492 futures: _,
6496
6497 worker_item: _,
6499 unforced_current_thread: _,
6500 deferred_host_call_context: _,
6501 suspend_reason: _,
6502 global_error_context_ref_counts: _,
6503 interesting_tasks: _,
6504 interesting_tasks_empty_waker: _,
6505 idle_waker: _,
6506 backpressure_waker: _,
6507 event_loop_running: _,
6508 #[cfg(feature = "task-group-hook")]
6509 task_group_hook: _,
6510 } = self;
6511
6512 for (_, entry) in table.get_mut().iter_mut() {
6513 let entry = entry.into_entry_mut();
6514 if let Some(set) = entry.downcast_mut::<WaitableSet>() {
6515 for mode in set.waiting.values_mut() {
6516 match mode {
6517 WaitMode::Fiber(fiber) => {
6518 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6519 }
6520 WaitMode::Callback(_) => {}
6521 }
6522 }
6523 } else if let Some(thread) = entry.downcast_mut::<GuestThread>() {
6524 match &mut thread.state {
6525 GuestThreadState::Suspended(fiber) | GuestThreadState::Ready { fiber } => {
6526 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6527 }
6528 GuestThreadState::NotStartedImplicit
6529 | GuestThreadState::NotStartedExplicit(_)
6530 | GuestThreadState::Running
6531 | GuestThreadState::Completed => {}
6532 }
6533 } else if let Some(Some(WorkItem::ResumeFiber { fiber, .. })) =
6534 entry.downcast_mut::<Option<WorkItem>>()
6535 {
6536 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6537 }
6538 }
6539
6540 if let Some(fiber) = worker {
6541 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6542 }
6543
6544 let mut handle_item = |item: &mut WorkItem| match item {
6545 WorkItem::ResumeFiber { fiber, .. } => {
6546 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6547 }
6548 WorkItem::PushFuture(_future) => {
6549 }
6552 WorkItem::ResumeThread { .. }
6553 | WorkItem::GuestCall { .. }
6554 | WorkItem::WorkerFunction(_) => {}
6555 };
6556
6557 if let Some(item) = switch_item {
6558 handle_item(item);
6559 }
6560 if let Some(item) = next_switch_item {
6561 handle_item(item);
6562 }
6563 for item in high_priority {
6564 handle_item(item);
6565 }
6566 for item in low_priority {
6567 handle_item(item);
6568 }
6569 for item in saved_next_switch_items
6570 .iter_mut()
6571 .filter_map(|v| v.as_mut())
6572 {
6573 handle_item(item);
6574 }
6575 }
6576
6577 fn schedule_suspended_thread(
6578 &mut self,
6579 thread: QualifiedThreadId,
6580 instance: RuntimeInstance,
6581 priority: Priority,
6582 ) -> Result<()> {
6583 if matches!(priority, Priority::Switch) && self.switch_item.is_some() {
6585 bail_bug!("switch item already set");
6586 }
6587 let slot = &mut self.get_mut(thread.thread)?.state;
6588 if !matches!(slot, GuestThreadState::Suspended(_)) {
6589 bail!(Trap::CannotResumeThread);
6590 }
6591 let GuestThreadState::Suspended(fiber) = mem::replace(slot, GuestThreadState::Running)
6592 else {
6593 unreachable!()
6594 };
6595 let item = WorkItem::ResumeFiber {
6596 instance,
6597 thread,
6598 fiber,
6599 };
6600 match priority {
6601 Priority::Switch => self.switch_item = Some(item),
6602 Priority::High => self.push_high_priority(item),
6603 Priority::Low => self.push_low_priority(item),
6604 }
6605 Ok(())
6606 }
6607
6608 fn set_thread_running(&mut self, thread: TableId<GuestThread>) -> Result<()> {
6609 let slot = &mut self.get_mut(thread)?.state;
6610 slot.check_no_fiber()?;
6611 *slot = GuestThreadState::Running;
6612 Ok(())
6613 }
6614
6615 fn save_next_switch_item(&mut self) -> Result<TableId<Option<WorkItem>>> {
6616 let saved = self.push(None::<WorkItem>)?;
6619 let slot = self.table.get_mut().get_mut(&Resource::from(saved))?;
6620 *slot = self.next_switch_item.take();
6621 Ok(saved)
6622 }
6623
6624 fn restore_next_switch_item(&mut self, saved: TableId<Option<WorkItem>>) -> Result<()> {
6625 if self.next_switch_item.is_some() {
6626 bail_bug!("next switch item already set when restoring");
6627 }
6628 self.next_switch_item = self.delete(saved)?;
6629 Ok(())
6630 }
6631
6632 fn take_callback_waiter(
6633 &mut self,
6634 set: TableId<WaitableSet>,
6635 thread: QualifiedThreadId,
6636 ) -> Result<Instance> {
6637 let waiting = &mut self.get_mut(set)?.waiting;
6638 let instance = match waiting.get(&thread) {
6639 Some(WaitMode::Callback(instance)) => *instance,
6640 other => bail_bug!("expected `Some(WaitMode::Callback(_))`; got `{other:?}`"),
6641 };
6642 waiting.remove(&thread);
6643 Ok(instance)
6644 }
6645
6646 fn push<V: Send + Sync + 'static>(
6647 &mut self,
6648 value: V,
6649 ) -> Result<TableId<V>, ResourceTableError> {
6650 self.table.get_mut().push(value).map(TableId::from)
6651 }
6652
6653 fn get_mut<V: 'static>(&mut self, id: TableId<V>) -> Result<&mut V, ResourceTableError> {
6654 self.table.get_mut().get_mut(&Resource::from(id))
6655 }
6656
6657 pub fn add_child<T: 'static, U: 'static>(
6658 &mut self,
6659 child: TableId<T>,
6660 parent: TableId<U>,
6661 ) -> Result<(), ResourceTableError> {
6662 self.table
6663 .get_mut()
6664 .add_child(Resource::from(child), Resource::from(parent))
6665 }
6666
6667 pub fn remove_child<T: 'static, U: 'static>(
6668 &mut self,
6669 child: TableId<T>,
6670 parent: TableId<U>,
6671 ) -> Result<(), ResourceTableError> {
6672 self.table
6673 .get_mut()
6674 .remove_child(Resource::from(child), Resource::from(parent))
6675 }
6676
6677 fn delete<V: 'static>(&mut self, id: TableId<V>) -> Result<V, ResourceTableError> {
6678 self.table.get_mut().delete(Resource::from(id))
6679 }
6680
6681 fn push_future(&mut self, future: HostTaskFuture) {
6682 self.push_high_priority(WorkItem::PushFuture(AlwaysMut::new(future)));
6689 }
6690
6691 fn set_switch_item(&mut self, item: WorkItem) -> Result<()> {
6692 if self.switch_item.is_some() {
6693 self.push_high_priority(item);
6696 bail_bug!("switch item already set");
6697 }
6698
6699 self.switch_item = Some(item);
6700 log::trace!("set switch item: {:?}", self.switch_item.as_ref().unwrap());
6701
6702 Ok(())
6703 }
6704
6705 fn take_next_switch_item(&mut self) -> Result<()> {
6706 if let Some(item) = self.next_switch_item.take() {
6707 self.set_switch_item(item)?;
6708 }
6709 Ok(())
6710 }
6711
6712 fn wake_waiter(&mut self, set: TableId<WaitableSet>) -> Result<()> {
6715 let Some((&thread, _)) = self.get_mut(set)?.waiting.first_key_value() else {
6718 return Ok(());
6719 };
6720 let wake_on_cancel = self.get_mut(thread.thread)?.wake_on_cancel;
6721 if wake_on_cancel != WakeOnCancel::None && wake_on_cancel != WakeOnCancel::Waiting(set) {
6722 bail_bug!("thread {thread:?} has unexpected wake_on_cancel value {wake_on_cancel:?}");
6723 }
6724 let instance = self.get_mut(thread.task)?.instance;
6725 self.get_mut(thread.thread)?.wake_on_cancel.take();
6726 let (_, mode) = self.get_mut(set)?.waiting.pop_first().unwrap();
6727
6728 let item = match mode {
6729 WaitMode::Fiber(fiber) => WorkItem::ResumeFiber {
6730 instance,
6731 thread,
6732 fiber,
6733 },
6734 WaitMode::Callback(callback_instance) => WorkItem::GuestCall {
6735 instance,
6736 call: GuestCall {
6737 thread,
6738 kind: GuestCallKind::DeliverEvent {
6739 instance: callback_instance,
6740 set: Some(set),
6741 },
6742 },
6743 },
6744 };
6745 self.push_high_priority(item);
6746 Ok(())
6747 }
6748
6749 fn push_high_priority(&mut self, item: WorkItem) {
6750 self.high_priority.push_front(item);
6751 log::trace!(
6752 "push high priority: {:?}",
6753 self.high_priority.front().unwrap()
6754 );
6755 }
6756
6757 fn push_low_priority(&mut self, item: WorkItem) {
6758 self.low_priority.push_front(item);
6759 log::trace!(
6760 "push low priority: {:?}",
6761 self.low_priority.front().unwrap()
6762 );
6763 }
6764
6765 fn push_work_item(&mut self, item: WorkItem, priority: Priority) -> Result<()> {
6766 match priority {
6767 Priority::Switch => self.set_switch_item(item)?,
6768 Priority::High => self.push_high_priority(item),
6769 Priority::Low => self.push_low_priority(item),
6770 }
6771
6772 Ok(())
6773 }
6774
6775 fn promote_instance_local_thread_work_item(
6776 &mut self,
6777 current_instance: RuntimeInstance,
6778 ) -> Result<bool> {
6779 log::trace!("promote thread work items for {current_instance:?}");
6780
6781 self.promote_work_item_matching(|item: &WorkItem| {
6782 let result = match item {
6783 WorkItem::ResumeThread { instance, .. }
6784 | WorkItem::ResumeFiber { instance, .. }
6785 | WorkItem::GuestCall { instance, .. } => *instance == current_instance,
6786 _ => false,
6787 };
6788
6789 log::trace!("candidate {item:?}: {result}");
6790 result
6791 })
6792 }
6793
6794 fn promote_thread_work_item(&mut self, thread: QualifiedThreadId) -> Result<bool> {
6795 self.promote_work_item_matching(|item: &WorkItem| match item {
6796 WorkItem::ResumeThread {
6797 thread: item_thread,
6798 ..
6799 }
6800 | WorkItem::GuestCall {
6801 call:
6802 GuestCall {
6803 thread: item_thread,
6804 ..
6805 },
6806 ..
6807 } => *item_thread == thread,
6808 _ => false,
6809 })
6810 }
6811
6812 fn promote_work_item_matching<F>(&mut self, mut predicate: F) -> Result<bool>
6813 where
6814 F: FnMut(&WorkItem) -> bool,
6815 {
6816 if self.switch_item.is_none() {
6823 if let Some(index) = self.high_priority.iter().rposition(&mut predicate) {
6824 self.switch_item = self.high_priority.remove(index);
6825 }
6826 }
6827 if self.switch_item.is_none() {
6828 if let Some(index) = self.low_priority.iter().rposition(predicate) {
6829 self.switch_item = self.low_priority.remove(index);
6830 }
6831 }
6832 Ok(self.switch_item.is_some())
6833 }
6834
6835 pub fn call_context(&mut self, task: VMScope) -> Result<&mut CallContext> {
6838 match task.kind() {
6839 ScopeKind::HostId(task) => {
6840 let task: TableId<HostTask> = TableId::new(task);
6841 Ok(&mut self.get_mut(task)?.call_context)
6842 }
6843 ScopeKind::Id(task) => {
6844 let task: TableId<GuestTask> = TableId::new(task);
6845 Ok(&mut self.get_mut(task)?.call_context)
6846 }
6847 }
6848 }
6849
6850 pub(crate) fn deferred_host_call_context(&mut self) -> Option<&mut CallContext> {
6851 self.deferred_host_call_context.as_mut()
6852 }
6853
6854 fn futures_mut(&mut self) -> Result<&mut FuturesUnordered<HostTaskFuture>> {
6855 match self.futures.get_mut().as_mut() {
6856 Some(f) => Ok(f),
6857 None => bail_bug!("futures field of concurrent state is currently taken"),
6858 }
6859 }
6860
6861 pub(crate) fn table(&mut self) -> &mut ResourceTable {
6862 self.table.get_mut()
6863 }
6864
6865 fn debug_assert_deferred_host_invariant(&self) {
6866 debug_assert_eq!(
6867 self.deferred_host_call_context.is_some(),
6868 matches!(self.unforced_current_thread, CurrentThread::DeferredHost(_)),
6869 "a deferred host thread and call context must exist together",
6870 );
6871 }
6872
6873 fn materialize_host_task(&mut self) -> Result<CurrentThread> {
6874 self.debug_assert_deferred_host_invariant();
6875 let caller = match self.unforced_current_thread {
6876 CurrentThread::DeferredHost(caller) => caller,
6877 thread => return Ok(thread),
6878 };
6879
6880 let task = HostTask::new(self, HostTaskState::CalleeStarted, caller)?;
6882 let task = self.push(task)?;
6883 let call_context = self
6884 .deferred_host_call_context
6885 .take()
6886 .expect("deferred host call context should be present");
6887 self.get_mut(task)
6888 .expect("newly inserted host task should be present")
6889 .call_context = call_context;
6890 self.unforced_current_thread = CurrentThread::Host(task);
6891 self.debug_assert_deferred_host_invariant();
6892 log::trace!("new host task materialized {task:?}");
6893 Ok(CurrentThread::Host(task))
6894 }
6895
6896 fn materialize_current_host_task_id(&mut self) -> Result<Option<TableId<HostTask>>> {
6897 match self.materialize_host_task()? {
6898 CurrentThread::Host(id) => Ok(Some(id)),
6899 CurrentThread::None => Ok(None),
6900 CurrentThread::Guest(_) => {
6901 bail_bug!("tried to materialize a host task id from a guest thread")
6902 }
6903 CurrentThread::DeferredHost(_) => {
6904 bail_bug!(
6905 "current thread is a deferred host thread which should have been materialized"
6906 )
6907 }
6908 }
6909 }
6910
6911 pub(crate) fn materialize_current_scope(&mut self) -> Result<VMScope> {
6912 match self.materialize_host_task()? {
6913 CurrentThread::Host(id) => Ok(VMScope::host_id(id.rep())),
6914 _ => bail_bug!("current scope is not a deferred host scope"),
6915 }
6916 }
6917
6918 fn increment_task_ref_count(&mut self, task: TableId<GuestTask>) -> Result<()> {
6919 let count = &mut self.get_mut(task)?.ref_count;
6920 *count += 1;
6921 log::trace!("increment {task:?} to {count}");
6922 Ok(())
6923 }
6924
6925 fn decrement_task_ref_count(&mut self, task: TableId<GuestTask>) -> Result<()> {
6926 let count = &mut self.get_mut(task)?.ref_count;
6927 if *count == 0 {
6928 bail_bug!("can't decrement task ref count that's already zero");
6929 }
6930 *count -= 1;
6931 log::trace!("decrement {task:?} to {count}");
6932 if *count == 0 {
6933 let task = self.delete(task)?;
6934
6935 self.decrement_group_ref_count(task.group)?;
6936
6937 debug_assert!(task.decremented_interesting_task_count);
6944 }
6945 Ok(())
6946 }
6947
6948 fn delete_host_task(&mut self, task: TableId<HostTask>) -> Result<()> {
6949 log::trace!("delete host task {task:?}");
6950 let task = self.delete(task)?;
6951
6952 self.decrement_group_ref_count(task.group)
6953 }
6954}
6955
6956fn for_any_lower<
6959 F: FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync,
6960>(
6961 fun: F,
6962) -> F {
6963 fun
6964}
6965
6966fn for_any_lift<
6968 F: FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
6969>(
6970 fun: F,
6971) -> F {
6972 fun
6973}
6974
6975fn check_ambient_store(id: StoreId) {
6976 let message = "\
6977 `Future`s which depend on asynchronous component tasks, streams, or \
6978 futures to complete may only be polled from the event loop of the \
6979 store to which they belong. Please use \
6980 `StoreContextMut::{run_concurrent,spawn}` to poll or await them.\
6981 ";
6982 tls::try_get(|store| {
6983 let matched = match store {
6984 tls::TryGet::Some(store) => store.id() == id,
6985 tls::TryGet::Taken | tls::TryGet::None => false,
6986 };
6987
6988 if !matched {
6989 panic!("{message}")
6990 }
6991 });
6992}
6993
6994fn unpack_callback_code(code: u32) -> (u32, u32) {
6995 (code & 0xF, code >> 4)
6996}
6997
6998struct WaitableCheckParams {
7002 set: TableId<WaitableSet>,
7003 options: OptionsIndex,
7004 payload: u32,
7005}
7006
7007enum WaitableCheck {
7010 Wait,
7011 Poll,
7012}
7013
7014pub(crate) struct PreparedCall<R> {
7016 handle: Func,
7018 thread: QualifiedThreadId,
7020 param_count: usize,
7022 rx: oneshot::Receiver<LiftedResult>,
7025 _phantom: PhantomData<R>,
7026}
7027
7028impl<R> PreparedCall<R> {
7029 pub(crate) fn acquire_task_id(&self, store: &mut StoreOpaque) -> Result<TaskId> {
7036 store
7037 .concurrent_state_mut()?
7038 .increment_task_ref_count(self.thread.task)?;
7039
7040 Ok(TaskId {
7041 task: self.thread.task,
7042 })
7043 }
7044}
7045
7046pub(crate) struct TaskId {
7048 task: TableId<GuestTask>,
7049}
7050
7051impl TaskId {
7052 pub(crate) fn host_future_dropped(&self, store: &mut StoreOpaque) -> Result<()> {
7064 let task = store.concurrent_state_mut()?.get_mut(self.task)?;
7065 if !task.already_lowered_parameters() {
7066 task.lower_params = Some(Box::new(|store, _| {
7071 store.set_trapped();
7072 bail!("the host future for this call was dropped before it started")
7073 }));
7074 } else {
7075 _ = store
7080 .concurrent_state_mut()?
7081 .decrement_task_ref_count(self.task);
7082 }
7083
7084 Ok(())
7085 }
7086}
7087
7088pub(crate) fn prepare_call<T, R>(
7094 mut store: StoreContextMut<T>,
7095 handle: Func,
7096 param_count: usize,
7097 lower_params: impl FnOnce(StoreContextMut<T>, &mut [MaybeUninit<ValRaw>]) -> Result<()>
7098 + Send
7099 + Sync
7100 + 'static,
7101 lift_result: impl FnOnce(&mut StoreOpaque, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>>
7102 + Send
7103 + Sync
7104 + 'static,
7105) -> Result<PreparedCall<R>> {
7106 if !store.0.may_enter() {
7110 bail!(Trap::CannotEnterComponent);
7111 }
7112
7113 let (options, _flags, ty, raw_options) = handle.abi_info(store.0);
7114
7115 let instance = handle.instance().id().get(store.0);
7116 let options = &instance.component().env_component().options[options];
7117 let ty = &instance.component().types()[ty];
7118 let async_typed = ty.async_;
7119 let async_lifted = raw_options.async_;
7120 let task_return_type = ty.results;
7121 let component_instance = raw_options.instance;
7122 let callback = options.callback.map(|i| instance.runtime_callback(i));
7123 let memory = options
7124 .memory()
7125 .map(|i| instance.runtime_memory(i))
7126 .map(SendSyncPtr::new);
7127 let string_encoding = options.string_encoding;
7128 let token = StoreToken::new(store.as_context_mut());
7129 let caller = store.0.materialize_host_task_id()?;
7130 let state = store.0.concurrent_state_mut()?;
7131
7132 let (tx, rx) = oneshot::channel();
7133
7134 let instance = handle.instance().runtime_instance(component_instance);
7135 let thread = GuestTask::new(
7136 state,
7137 Box::new(for_any_lower(move |store, params| {
7138 lower_params(token.as_context_mut(store), params)
7139 })),
7140 LiftResult {
7141 lift: Box::new(for_any_lift(move |store, result| {
7142 lift_result(store, result)
7143 })),
7144 ty: task_return_type,
7145 memory,
7146 string_encoding,
7147 },
7148 Caller::Host {
7149 tx: Some(tx),
7150 caller,
7151 },
7152 callback.map(|callback| {
7153 let callback = SendSyncPtr::new(callback);
7154 let instance = handle.instance();
7155 Box::new(move |store: &mut dyn VMStore, event, handle| {
7156 let store = token.as_context_mut(store);
7157 unsafe { instance.call_callback(store, callback, event, handle) }
7160 }) as CallbackFn
7161 }),
7162 instance,
7163 async_typed,
7164 async_lifted,
7165 )?;
7166
7167 Ok(PreparedCall {
7168 handle,
7169 thread,
7170 param_count,
7171 rx,
7172 _phantom: PhantomData,
7173 })
7174}
7175
7176pub(crate) struct StagedCall<R> {
7177 store: StoreId,
7178 rx: oneshot::Receiver<LiftedResult>,
7179 _marker: PhantomData<fn() -> R>,
7180 group: TaskGroupId,
7188}
7189
7190impl<R> StagedCall<R> {
7191 pub(crate) fn new<T: 'static>(
7202 mut store: StoreContextMut<T>,
7203 prepared: PreparedCall<R>,
7204 ) -> Result<StagedCall<R>> {
7205 let PreparedCall {
7206 handle,
7207 thread,
7208 param_count,
7209 rx,
7210 ..
7211 } = prepared;
7212
7213 stage_call0(store.as_context_mut(), handle, thread, param_count)?;
7214
7215 let state = store.0.concurrent_state_mut()?;
7216 let group = state.get_mut(thread.task)?.group;
7217 state.decrement_task_ref_count(thread.task)?;
7218
7219 Ok(StagedCall {
7220 store: store.0.id(),
7221 rx,
7222 _marker: PhantomData,
7223 group,
7224 })
7225 }
7226}
7227
7228impl<R> Future for StagedCall<R>
7229where
7230 R: 'static,
7231{
7232 type Output = Result<R>;
7233
7234 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
7235 check_ambient_store(self.store);
7236 Pin::new(&mut self.rx).poll(cx).map(|result| match result {
7237 Ok(r) => match r.downcast() {
7238 Ok(r) => Ok(*r),
7239 Err(_) => bail_bug!("wrong type of value produced"),
7240 },
7241 Err(oneshot::Canceled) => bail_bug!("channel erroneously dropped"),
7242 })
7243 }
7244}
7245
7246fn stage_call0<T: 'static>(
7249 store: StoreContextMut<T>,
7250 handle: Func,
7251 guest_thread: QualifiedThreadId,
7252 param_count: usize,
7253) -> Result<()> {
7254 let (_options, _, _ty, raw_options) = handle.abi_info(store.0);
7255 let is_concurrent = raw_options.async_;
7256 let callback = raw_options.callback;
7257 let instance = handle.instance();
7258 let callee = handle.lifted_core_func(store.0);
7259 let post_return = raw_options
7260 .post_return
7261 .map(|i| instance.id().get(store.0).runtime_post_return(i));
7262 let callback = callback.map(|i| {
7263 let instance = instance.id().get(store.0);
7264 SendSyncPtr::new(instance.runtime_callback(i))
7265 });
7266
7267 log::trace!("queueing call {guest_thread:?}");
7268
7269 unsafe {
7273 instance.stage_call(
7274 store,
7275 guest_thread,
7276 SendSyncPtr::new(callee),
7277 param_count,
7278 1,
7279 is_concurrent,
7280 callback,
7281 post_return.map(SendSyncPtr::new),
7282 true,
7283 )
7284 }
7285}
7286
7287#[cfg(all(test, feature = "cranelift", feature = "wat"))]
7288mod tests {
7289 use super::*;
7290 use crate::component::{Component, Linker};
7291 use crate::store::AsStoreOpaque;
7292 use crate::{Config, Engine};
7293
7294 fn host_subtask(
7295 state: HostTaskState,
7296 event: Option<Event>,
7297 ) -> Result<(Store<()>, Instance, TableId<HostTask>, u32)> {
7298 let mut config = Config::new();
7299 config.wasm_component_model_async(true);
7300 let engine = Engine::new(&config)?;
7301 let component = Component::new(&engine, "(component)")?;
7302 let mut store = Store::new(&engine, ());
7303 let instance = Linker::new(&engine).instantiate(&mut store, &component)?;
7304 let store_opaque = store.as_store_opaque();
7305 let concurrent_state = store_opaque.concurrent_state_mut()?;
7306 let group = concurrent_state.make_task_group()?;
7309 let task = concurrent_state.push(HostTask {
7310 common: WaitableCommon::default(),
7311 call_context: CallContext::default(),
7312 state,
7313 group,
7314 })?;
7315 let handle = store_opaque
7316 .handle_table_insertion(
7317 instance.runtime_instance(RuntimeComponentInstanceIndex::from_u32(0)),
7318 )
7319 .subtask_host(task.rep())?;
7320 let common = &mut store_opaque.concurrent_state_mut()?.get_mut(task)?.common;
7321 common.handle = Some(handle);
7322 common.event = event;
7323 Ok((store, instance, task, handle))
7324 }
7325
7326 #[test]
7327 fn host_subtask_drop_during_cancellation() -> Result<()> {
7328 for abort_completed in [false, true] {
7329 let (handle, future) = JoinHandle::run(future::pending::<()>());
7330 let mut future = pin!(future);
7331 let (mut store, instance, task, handle) =
7332 host_subtask(HostTaskState::CalleeRunning(handle), None)?;
7333 let store = store.as_store_opaque();
7334 let caller = RuntimeComponentInstanceIndex::from_u32(0);
7335 assert_eq!(
7336 instance.subtask_cancel(store, caller, true, handle)?,
7337 BLOCKED
7338 );
7339 if abort_completed {
7340 assert!(matches!(
7343 future
7344 .as_mut()
7345 .poll(&mut Context::from_waker(Waker::noop())),
7346 Poll::Ready(None),
7347 ));
7348 }
7349 for async_ in [false, true] {
7350 let err = instance
7351 .subtask_cancel(store, caller, async_, handle)
7352 .unwrap_err();
7353 assert_eq!(err.downcast::<Trap>()?, Trap::SubtaskCancelAfterTerminal);
7354 }
7355 let err = instance.subtask_drop(store, caller, handle).unwrap_err();
7356 assert_eq!(err.downcast::<Trap>()?, Trap::SubtaskDropNotResolved);
7357 assert!(store.concurrent_state_mut()?.get_mut(task).is_ok());
7358 }
7359 Ok(())
7360 }
7361
7362 #[test]
7363 fn host_subtask_cancel_after_completion() -> Result<()> {
7364 for async_ in [false, true] {
7365 let (mut store, instance, task, handle) = host_subtask(
7366 HostTaskState::CalleeDone { cancelled: false },
7367 Some(Event::Subtask {
7368 status: Status::Returned,
7369 }),
7370 )?;
7371 let store = store.as_store_opaque();
7372 let caller = RuntimeComponentInstanceIndex::from_u32(0);
7373 assert_eq!(
7374 instance.subtask_cancel(store, caller, async_, handle)?,
7375 Status::Returned as u32,
7376 );
7377 let err = instance
7378 .subtask_cancel(store, caller, async_, handle)
7379 .unwrap_err();
7380 assert_eq!(err.downcast::<Trap>()?, Trap::SubtaskCancelAfterTerminal);
7381 instance.subtask_drop(store, caller, handle)?;
7382 assert!(store.concurrent_state_mut()?.get_mut(task).is_err());
7383 }
7384 Ok(())
7385 }
7386
7387 #[test]
7388 fn host_subtask_drop_requires_terminal_event_delivery() -> Result<()> {
7389 for (cancelled, status) in [
7390 (false, Status::Returned),
7391 (true, Status::Returned),
7392 (true, Status::ReturnCancelled),
7393 ] {
7394 for delivered in [false, true] {
7395 let event = if delivered {
7396 None
7397 } else {
7398 Some(Event::Subtask { status })
7399 };
7400 let (mut store, instance, task, handle) =
7401 host_subtask(HostTaskState::CalleeDone { cancelled }, event)?;
7402 let store = store.as_store_opaque();
7403 let result = instance.subtask_drop(
7404 store,
7405 RuntimeComponentInstanceIndex::from_u32(0),
7406 handle,
7407 );
7408 if delivered {
7409 result?;
7410 assert!(store.concurrent_state_mut()?.get_mut(task).is_err());
7411 } else {
7412 let err = result.unwrap_err();
7413 assert_eq!(err.downcast::<Trap>()?, Trap::SubtaskDropNotResolved);
7414 assert!(store.concurrent_state_mut()?.get_mut(task).is_ok());
7415 }
7416 }
7417 }
7418 Ok(())
7419 }
7420}