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.ready_for_concurrent_call_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 .ready_for_concurrent_call_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.ready_for_concurrent_call_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 state = self.0.instance_state(instance).concurrent_state();
1800
1801 state.pending.insert(call.thread, call.kind);
1802
1803 if increment {
1804 state.pending_start_count += 1;
1805 }
1806 }
1807 }
1808 WorkItem::WorkerFunction(fun) => {
1809 self.run_on_worker(WorkerItem::Function(fun)).await?;
1810 }
1811 }
1812
1813 Ok(())
1814 })
1815 }
1816
1817 async fn run_on_worker(self, item: WorkerItem) -> Result<()> {
1819 let state = self.0.concurrent_state_mut()?;
1820 if state.worker_item.is_some() {
1821 bail_bug!("worker item already set when taking worker fiber");
1822 }
1823 let worker = if let Some(fiber) = state.worker.take() {
1824 fiber
1825 } else {
1826 unsafe {
1845 fiber::make_fiber_unchecked(self.0, move |store| {
1846 loop {
1847 let Some(item) = store.concurrent_state_mut()?.worker_item.take() else {
1848 bail_bug!("worker_item not present when resuming fiber")
1849 };
1850 match item {
1851 WorkerItem::GuestCall(call) => handle_guest_call(store, call)?,
1852 WorkerItem::Function(fun) => fun.into_inner()(store)?,
1853 }
1854
1855 store.suspend(SuspendReason::NeedWork)?;
1856 }
1857 })?
1858 }
1859 };
1860
1861 self.0
1864 .concurrent_state_mut_already_forced_current_thread()
1865 .worker_item = Some(item);
1866
1867 self.0.resume_fiber(worker).await
1868 }
1869
1870 pub(crate) fn wrap_call<F, R>(self, closure: F) -> impl Future<Output = Result<R>> + 'static
1875 where
1876 T: 'static,
1877 F: FnOnce(&Accessor<T>) -> Pin<Box<dyn Future<Output = Result<R>> + Send + '_>>
1878 + Send
1879 + Sync
1880 + 'static,
1881 R: Send + Sync + 'static,
1882 {
1883 let token = StoreToken::new(self);
1884 async move {
1885 let mut accessor = Accessor::new(token);
1886 closure(&mut accessor).await
1887 }
1888 }
1889
1890 pub(crate) async fn start_instance(
1891 &mut self,
1892 instance: ModuleInstance,
1893 callee: Option<RuntimeInstance>,
1894 ) -> Result<ModuleInstance> {
1895 self.0.check_event_loop_not_running()?;
1897 let (tx, rx) = oneshot::channel();
1898 let token = StoreToken::new(self.as_context_mut());
1899 self.0.queue_task(move |store| {
1900 _ = tx.send(
1901 super::instance::start_raw(&mut token.as_context_mut(store), instance, callee)
1902 .map(|()| instance),
1903 );
1904 Ok(())
1905 })?;
1906 self.as_context_mut()
1907 .run_concurrent_trap_on_idle(async |_| {
1908 rx.await
1909 .map_err(|_| format_err!("oneshot channel canceled"))
1910 })
1911 .await??
1912 }
1913}
1914
1915pub type EnteredHostTask = Option<QualifiedThreadId>;
1922
1923impl StoreOpaque {
1924 pub(crate) fn check_event_loop_not_running(&mut self) -> Result<()> {
1925 if self
1926 .concurrent_state_mut_already_forced_current_thread()
1927 .event_loop_running
1928 {
1929 bail!("Recursive `StoreContextMut::run_concurrent` calls not supported")
1930 }
1931 Ok(())
1932 }
1933
1934 #[inline]
1938 pub(crate) fn current_thread(&mut self) -> Result<CurrentThread> {
1939 if !self.concurrency_support() {
1941 return Ok(CurrentThread::None);
1942 }
1943
1944 if !self
1947 .vm_store_context_mut()
1948 .current_thread_mut()
1949 .is_deferred()
1950 {
1951 return Ok(self
1952 .concurrent_state_mut_already_forced_current_thread()
1953 .unforced_current_thread);
1954 }
1955
1956 self.force_deferred_current_thread()
1957 }
1958
1959 #[cold]
1962 fn force_deferred_current_thread(&mut self) -> Result<CurrentThread> {
1963 let state = self.concurrent_state_mut_without_forcing_current_thread();
1972 let id = match state.unforced_current_thread.guest_task() {
1973 Some(task) => state.get_mut(task)?.instance.instance,
1974 None => bail_bug!("deferred component-model thread with non-guest base"),
1975 };
1976
1977 let mut frames = SmallVec::<[_; 8]>::new();
1980 let mut cur = *self.vm_store_context_mut().current_thread_mut();
1981 while let Some(ptr) = cur.as_deferred() {
1982 let deferred = unsafe { ptr.as_non_null().as_ref() };
1987 frames.push((
1988 deferred.callee_async != 0,
1989 deferred.callee_instance,
1990 deferred.saved_context,
1991 deferred.lazy_lenders_start,
1992 ));
1993 cur = deferred.parent;
1994 }
1995
1996 *self.vm_store_context_mut().current_thread_mut() = VMLazyThread::forced();
2000
2001 let current_context = *self.vm_store_context_mut().component_context_mut();
2004
2005 let lazy_lenders_end = *self.vm_store_context_mut().lazy_lenders_len_mut();
2012 frames.reverse();
2013 let lazy_lenders_base = match frames.first() {
2014 Some((_, _, _, start)) => *start,
2015 None => bail_bug!("forcing a deferred thread with no deferred frames"),
2016 };
2017 let lazy_lender_ends = frames
2018 .iter()
2019 .skip(1)
2020 .map(|(_, _, _, start)| *start)
2021 .chain([lazy_lenders_end])
2022 .collect::<SmallVec<[_; 8]>>();
2023 for ((callee_async, callee_instance, saved_context, start), lenders_end) in
2024 frames.into_iter().zip(lazy_lender_ends)
2025 {
2026 *self.vm_store_context_mut().component_context_mut() = saved_context;
2030 let callee = RuntimeInstance {
2031 instance: id,
2032 index: RuntimeComponentInstanceIndex::from_u32(callee_instance),
2033 };
2034 self.enter_guest_sync_call(callee_async, callee)?;
2035
2036 self.promote_current_lazy_lends(id, start, lenders_end)?;
2039 }
2040
2041 debug_assert_eq!(
2044 *self.vm_store_context_mut().lazy_lenders_len_mut(),
2045 lazy_lenders_end
2046 );
2047 *self.vm_store_context_mut().lazy_lenders_len_mut() = lazy_lenders_base;
2048
2049 *self.vm_store_context_mut().component_context_mut() = current_context;
2051
2052 Ok(self
2053 .concurrent_state_mut_without_forcing_current_thread()
2054 .unforced_current_thread)
2055 }
2056
2057 fn promote_current_lazy_lends(
2063 &mut self,
2064 id: ComponentInstanceId,
2065 start: usize,
2066 end: usize,
2067 ) -> Result<()> {
2068 if start == end {
2069 return Ok(());
2070 }
2071
2072 let scope = match self
2073 .concurrent_state_mut_without_forcing_current_thread()
2074 .unforced_current_thread
2075 .guest_task()
2076 {
2077 Some(task) => VMScope::id(task.rep()),
2078 None => bail_bug!("replayed deferred frame is not a guest thread"),
2079 };
2080 let instance = Instance::from_wasmtime(self, id);
2081 self.promote_lazy_lends(instance, scope, start, end)
2082 }
2083
2084 fn current_guest_thread(&mut self) -> Result<QualifiedThreadId> {
2085 match self.current_thread()?.guest() {
2086 Some(id) => Ok(*id),
2087 None => bail_bug!("current thread is not a guest thread"),
2088 }
2089 }
2090
2091 pub(crate) fn current_materialized_host_task(&mut self) -> Result<Option<TableId<HostTask>>> {
2095 match self.current_thread()? {
2096 CurrentThread::Host(id) => Ok(Some(id)),
2097 CurrentThread::DeferredHost(_) | CurrentThread::None => Ok(None),
2098 _ => bail_bug!("current thread is not a host thread"),
2099 }
2100 }
2101
2102 fn materialize_host_task_id(&mut self) -> Result<Option<TableId<HostTask>>> {
2105 Ok(self
2106 .concurrent_state_mut()?
2107 .materialize_current_host_task_id()?)
2108 }
2109
2110 fn enter_sync_call(&mut self, callee: RuntimeInstance) -> Result<()> {
2111 log::trace!("enter sync-typed call {callee:?}");
2112 let state = self.instance_state(callee).concurrent_state();
2113 let old_do_not_suspend = state.do_not_suspend;
2114 state.do_not_suspend = true;
2115
2116 let thread = self.current_guest_thread()?;
2117 let thread = self.concurrent_state_mut()?.get_mut(thread.thread)?;
2118 if thread.old_do_not_suspend.is_some() {
2119 bail_bug!("current thread already has `old_do_not_suspend` value");
2120 }
2121
2122 thread.old_do_not_suspend = Some(old_do_not_suspend);
2123
2124 Ok(())
2125 }
2126
2127 fn exit_sync_call(&mut self, callee: RuntimeInstance) -> Result<()> {
2128 log::trace!("exit sync-typed call {callee:?}");
2129 let thread = self.current_guest_thread()?;
2130 let thread = self.concurrent_state_mut()?.get_mut(thread.thread)?;
2131 let Some(old_do_not_suspend) = thread.old_do_not_suspend.take() else {
2132 bail_bug!("current thread missing `old_do_not_suspend` value");
2133 };
2134 let state = self.instance_state(callee).concurrent_state();
2135 state.do_not_suspend = old_do_not_suspend;
2136 Ok(())
2137 }
2138
2139 pub(crate) fn enter_guest_sync_call(
2151 &mut self,
2152 callee_async_typed: bool,
2153 callee: RuntimeInstance,
2154 ) -> Result<()> {
2155 log::trace!("enter sync-lifted call {callee:?}");
2156 if !self.concurrency_support() {
2157 return self.enter_call_not_concurrent();
2158 }
2159
2160 let state = self.concurrent_state_mut()?;
2164 let item = state.next_switch_item.take();
2165 state.saved_next_switch_items.push(item);
2166
2167 let thread = self.current_thread()?;
2168 let caller = if let Some(thread) = thread.guest() {
2169 Caller::Guest { thread: *thread }
2170 } else {
2171 Caller::Host {
2172 tx: None,
2173 caller: self.materialize_host_task_id()?,
2174 }
2175 };
2176
2177 let state = self.concurrent_state_mut()?;
2178 let guest_thread = GuestTask::new(
2179 state,
2180 Box::new(move |_, _| bail_bug!("cannot lower params in sync call")),
2181 LiftResult {
2182 lift: Box::new(move |_, _| bail_bug!("cannot lift result in sync call")),
2183 ty: TypeTupleIndex::reserved_value(),
2184 memory: None,
2185 string_encoding: StringEncoding::Utf8,
2186 },
2187 caller,
2188 None,
2189 callee,
2190 callee_async_typed,
2191 false,
2192 )?;
2193
2194 Instance::from_wasmtime(self, callee.instance).add_guest_thread_to_instance_table(
2195 guest_thread.thread,
2196 self,
2197 callee.index,
2198 )?;
2199 self.set_thread(guest_thread)?;
2200
2201 if !callee_async_typed {
2202 self.enter_sync_call(callee)?;
2203 }
2204
2205 Ok(())
2206 }
2207
2208 pub(crate) fn exit_guest_sync_call(&mut self) -> Result<()> {
2216 if !self.concurrency_support() {
2217 return Ok(self.exit_call_not_concurrent());
2218 }
2219
2220 let thread = match self.current_thread()?.guest() {
2221 Some(t) => *t,
2222 None => bail_bug!("expected task when exiting"),
2223 };
2224 let task = self.concurrent_state_mut()?.get_mut(thread.task)?;
2225 let instance = task.instance;
2226
2227 let caller = match &task.caller {
2228 &Caller::Guest { thread } => thread.into(),
2229 &Caller::Host { caller, .. } => caller
2230 .map(CurrentThread::Host)
2231 .unwrap_or(CurrentThread::None),
2232 };
2233 task.lift_result = None;
2234 task.exited = true;
2235 let async_typed = task.async_typed;
2236
2237 if !async_typed {
2238 self.exit_sync_call(instance)?;
2239 }
2240
2241 self.set_thread(caller)?;
2242
2243 log::trace!("exit sync-lifted call {instance:?}");
2244
2245 if async_typed {
2246 self.switch_or_trap_if_may_not_suspend(instance)?;
2251 }
2252
2253 self.cleanup_thread(thread, instance)?;
2254
2255 self.concurrent_state_mut()?
2256 .decrement_task_ref_count(thread.task)?;
2257
2258 let state = self.concurrent_state_mut()?;
2259 let Some(item) = state.saved_next_switch_items.pop() else {
2260 bail_bug!("unable to pop from `saved_next_switch_items`");
2261 };
2262 if let Some(item) = mem::replace(&mut state.next_switch_item, item) {
2263 state.push_high_priority(item);
2266 bail_bug!("`next_switch_item` unexpectedly already set");
2267 }
2268
2269 Ok(())
2270 }
2271
2272 pub(crate) fn host_task_create(&mut self) -> Result<EnteredHostTask> {
2279 if !self.concurrency_support() {
2280 self.enter_call_not_concurrent()?;
2281 return Ok(None);
2282 }
2283 let caller = self.current_guest_thread()?;
2284 log::trace!("new deferred host task with caller {caller:?}");
2285
2286 self.set_thread(CurrentThread::DeferredHost(caller))?;
2287 let state = self.concurrent_state_mut()?;
2288 debug_assert!(state.deferred_host_call_context.is_none());
2289 state.deferred_host_call_context = Some(CallContext::default());
2290 state.debug_assert_deferred_host_invariant();
2291 Ok(Some(caller))
2292 }
2293
2294 pub(crate) fn host_task_delete(
2301 &mut self,
2302 original_task: EnteredHostTask,
2303 materialized_task: Option<TableId<HostTask>>,
2304 ) -> Result<()> {
2305 match original_task {
2306 Some(caller) => {
2307 self.set_thread(caller)?;
2308 if materialized_task.is_none() {
2309 let state = self.concurrent_state_mut()?;
2310 let context = state
2311 .deferred_host_call_context
2312 .take()
2313 .expect("deferred host call context should be present");
2314 debug_assert!(context.is_empty());
2315 state.debug_assert_deferred_host_invariant();
2316 }
2317 log::trace!(
2318 "delete host task with caller {original_task:?} and materialized as {materialized_task:?}"
2319 );
2320 if let Some(task) = materialized_task {
2321 self.concurrent_state_mut()?.delete_host_task(task)?;
2322 }
2323 }
2324 None => {
2325 debug_assert!(materialized_task.is_none());
2326 self.exit_call_not_concurrent();
2327 }
2328 }
2329 Ok(())
2330 }
2331
2332 fn instance_state(&mut self, instance: RuntimeInstance) -> &mut InstanceState {
2335 self.component_instance_mut(instance.instance)
2336 .instance_state(instance.index)
2337 }
2338
2339 fn instance_state_and_handle_counter(
2342 &mut self,
2343 instance: RuntimeInstance,
2344 ) -> (&mut InstanceState, &mut HandleCounter) {
2345 let (component, counter) = self
2346 .store_data_mut()
2347 .component_instance_and_handle_counter_mut(instance.instance);
2348 (component.instance_state(instance.index), counter)
2349 }
2350
2351 fn handle_table_insertion(&mut self, instance: RuntimeInstance) -> HandleTableInsertion<'_> {
2353 let (component, counter) = self
2354 .store_data_mut()
2355 .component_instance_and_handle_counter_mut(instance.instance);
2356 component.handle_table_insertion(instance.index, counter)
2357 }
2358
2359 pub(crate) fn set_thread(&mut self, thread: impl Into<CurrentThread>) -> Result<CurrentThread> {
2365 let thread = thread.into();
2366 let state = self.concurrent_state_mut()?;
2367 state.debug_assert_deferred_host_invariant();
2368 let old_thread = mem::replace(&mut state.unforced_current_thread, thread);
2369
2370 state.handle_thread_switch(old_thread, thread)?;
2371
2372 if let Some(old_thread) = old_thread.guest() {
2380 let old_context = *self.vm_store_context_mut().component_context_mut();
2381 self.concurrent_state_mut()?
2382 .get_mut(old_thread.thread)?
2383 .context = old_context;
2384 }
2385 if cfg!(debug_assertions) {
2386 *self.vm_store_context_mut().component_context_mut() =
2387 [u32::MAX; NUM_COMPONENT_CONTEXT_SLOTS];
2388 }
2389 if let Some(thread) = thread.guest() {
2390 let thread = self.concurrent_state_mut()?.get_mut(thread.thread)?;
2391 let context = thread.context;
2392 if cfg!(debug_assertions) {
2393 thread.context = [u32::MAX; NUM_COMPONENT_CONTEXT_SLOTS];
2394 }
2395 *self.vm_store_context_mut().component_context_mut() = context;
2396 }
2397
2398 *self.vm_store_context_mut().current_thread_mut() = if thread.is_none() {
2400 VMLazyThread::none()
2401 } else {
2402 VMLazyThread::forced()
2403 };
2404
2405 Ok(old_thread)
2406 }
2407
2408 fn switch_or_trap_if_may_not_suspend(&mut self, instance: RuntimeInstance) -> Result<()> {
2410 if self.switch_if_may_not_suspend(instance)? {
2411 Ok(())
2412 } else {
2413 Err(Trap::CannotBlockSyncTask.into())
2414 }
2415 }
2416
2417 fn switch_if_may_not_suspend(&mut self, instance: RuntimeInstance) -> Result<bool> {
2421 self.concurrent_state_mut()?;
2425
2426 Ok(!self.concurrency_support()
2427 || !self
2428 .instance_state(instance)
2429 .concurrent_state()
2430 .do_not_suspend
2431 || self
2432 .concurrent_state_mut()?
2433 .promote_instance_local_thread_work_item(instance)?)
2434 }
2435
2436 fn enter_instance(&mut self, instance: RuntimeInstance) {
2440 log::trace!("enter {instance:?}");
2441 self.instance_state(instance)
2442 .concurrent_state()
2443 .do_not_enter = true;
2444 }
2445
2446 fn exit_instance(&mut self, instance: RuntimeInstance) -> Result<()> {
2450 log::trace!("exit {instance:?}");
2451 self.instance_state(instance)
2452 .concurrent_state()
2453 .do_not_enter = false;
2454 self.partition_pending(instance)
2455 }
2456
2457 fn partition_pending(&mut self, instance: RuntimeInstance) -> Result<()> {
2465 let mut any_ready = false;
2466 for (thread, kind) in
2467 mem::take(&mut self.instance_state(instance).concurrent_state().pending)
2468 {
2469 let call = GuestCall { thread, kind };
2470 if call.is_ready(self)? {
2471 any_ready = true;
2472 self.concurrent_state_mut()?
2473 .push_high_priority(WorkItem::GuestCall { instance, call });
2474 } else {
2475 self.instance_state(instance)
2476 .concurrent_state()
2477 .pending
2478 .insert(call.thread, call.kind);
2479 }
2480 }
2481
2482 if any_ready {
2483 if let Some(waker) = self
2484 .concurrent_state_mut()?
2485 .ready_for_concurrent_call_waker
2486 .take()
2487 {
2488 waker.wake();
2489 }
2490 }
2491
2492 Ok(())
2493 }
2494
2495 pub(crate) fn backpressure_modify(
2497 &mut self,
2498 caller_instance: RuntimeInstance,
2499 modify: impl FnOnce(u16) -> Option<u16>,
2500 ) -> Result<()> {
2501 let state = self.instance_state(caller_instance).concurrent_state();
2502 let old = state.backpressure;
2503 let new = modify(old).ok_or_else(|| Trap::BackpressureOverflow)?;
2504 state.backpressure = new;
2505
2506 log::trace!("backpressure update for {caller_instance:?} from {old} to {new}");
2507
2508 if old > 0 && new == 0 {
2509 self.partition_pending(caller_instance)?;
2512 }
2513
2514 Ok(())
2515 }
2516
2517 fn resume_fiber(
2520 &mut self,
2521 fiber: StoreFiber<'static>,
2522 ) -> impl Future<Output = Result<()>> + '_ {
2523 let mut resuming = ResumingFiber {
2524 store: self,
2525 fiber: Some(fiber),
2526 };
2527 async move {
2528 let old_thread = resuming.store.current_thread()?;
2529 log::trace!("resume_fiber: save current thread {old_thread:?}");
2530
2531 let fiber = resuming.fiber.take().unwrap();
2532 resuming.fiber = fiber::resolve_or_release(resuming.store, fiber).await?;
2533
2534 resuming.store.set_thread(old_thread)?;
2535
2536 let state = resuming.store.concurrent_state_mut()?;
2537
2538 if let Some(ot) = old_thread.guest() {
2539 state.set_thread_running(ot.thread)?;
2540 }
2541 log::trace!("resume_fiber: restore current thread {old_thread:?}");
2542
2543 if resuming.fiber.is_some() {
2544 log::trace!("resume_fiber: suspend reason {:?}", &state.suspend_reason);
2545 let reason = match state.suspend_reason.take() {
2547 Some(r) => r,
2548 None => bail_bug!("suspend reason missing when resuming fiber"),
2549 };
2550 match reason {
2551 SuspendReason::NeedWork => {
2552 if state.worker.is_none() {
2553 state.worker = resuming.fiber.take();
2554 }
2555 }
2556 SuspendReason::Yielding { thread } => {
2557 let slot = &mut state.get_mut(thread.thread)?.state;
2558 slot.check_no_fiber()?;
2559 *slot = GuestThreadState::Ready {
2560 fiber: resuming.fiber.take().unwrap(),
2561 };
2562 let instance = state.get_mut(thread.task)?.instance;
2563 state.push_low_priority(WorkItem::ResumeThread { instance, thread });
2564 }
2565 SuspendReason::ExplicitlySuspending { thread } => {
2566 let slot = &mut state.get_mut(thread.thread)?.state;
2567 slot.check_no_fiber()?;
2568 *slot = GuestThreadState::Suspended(resuming.fiber.take().unwrap());
2569 }
2570 SuspendReason::Waiting { set, thread } => {
2571 match state.get_mut(set)?.waiting.entry(thread) {
2572 Entry::Vacant(entry) => {
2573 entry.insert(WaitMode::Fiber(resuming.fiber.take().unwrap()));
2574 }
2575 Entry::Occupied(_) => {
2576 bail_bug!("entry unexpectedly already exists for {thread:?}");
2577 }
2578 }
2579 }
2580 SuspendReason::YieldingToSubtask { thread } => {
2581 let instance = state.get_mut(thread.task)?.instance;
2590 if state.next_switch_item.is_some() {
2591 bail_bug!(
2594 "`ConcurrentState::next_switch_item` was already `Some(_)` when \
2595 a thread wanted to wait on a subtask"
2596 );
2597 }
2598 let item = state.next_switch_item.insert(WorkItem::ResumeFiber {
2599 instance,
2600 thread,
2601 fiber: resuming.fiber.take().unwrap(),
2602 });
2603 log::trace!("set next switch item to {item:?}");
2604 }
2605 };
2606 } else {
2607 log::trace!("resume_fiber: fiber has exited");
2608 }
2609
2610 Ok(())
2611 }
2612 }
2613
2614 fn suspend(&mut self, reason: SuspendReason) -> Result<()> {
2620 log::trace!("suspend fiber: {reason:?}");
2621
2622 if !self.fiber_async_state_mut().can_block() {
2625 return Err(format_err!("future dropped"));
2626 }
2627
2628 let state = self.concurrent_state_mut()?;
2629
2630 let (save_and_restore_thread, save_and_restore_next_switch_item) = match &reason {
2637 SuspendReason::Yielding { .. }
2638 | SuspendReason::Waiting { .. }
2639 | SuspendReason::ExplicitlySuspending { .. } => {
2640 if state.switch_item.is_none() {
2643 state.take_next_switch_item()?;
2644 }
2645
2646 (true, false)
2647 }
2648 SuspendReason::YieldingToSubtask { .. } => (true, true),
2649 SuspendReason::NeedWork => (false, false),
2650 };
2651
2652 let old_next_switch_item = if save_and_restore_next_switch_item {
2653 Some(state.save_next_switch_item()?)
2654 } else {
2655 None
2656 };
2657
2658 let old_guest_thread = if save_and_restore_thread {
2659 self.current_thread()?
2660 } else {
2661 CurrentThread::None
2662 };
2663
2664 let waiting_set = match &reason {
2665 SuspendReason::Waiting { set, .. } => Some(*set),
2666 _ => None,
2667 };
2668
2669 let suspend_reason = &mut self.concurrent_state_mut()?.suspend_reason;
2670 if suspend_reason.is_some() {
2671 bail_bug!("suspend reason unexpectedly already set for store");
2672 }
2673 *suspend_reason = Some(reason);
2674
2675 if let Some(set) = waiting_set {
2678 self.concurrent_state_mut()?.get_mut(set)?.num_waiting += 1;
2679 }
2680
2681 self.with_blocking(|_, cx| cx.suspend(StoreFiberYield::ReleaseStore))?;
2682
2683 if let Some(set) = waiting_set {
2684 self.concurrent_state_mut()?.get_mut(set)?.stop_waiting()?;
2685 }
2686
2687 if save_and_restore_thread {
2688 self.set_thread(old_guest_thread)?;
2689 }
2690
2691 if let Some(item) = old_next_switch_item {
2692 let state = self.concurrent_state_mut()?;
2693 state.restore_next_switch_item(item)?;
2694 }
2695
2696 Ok(())
2697 }
2698
2699 fn wait_for_event(
2700 &mut self,
2701 caller_instance: RuntimeInstance,
2702 waitable: Waitable,
2703 ) -> Result<()> {
2704 let caller = self.current_guest_thread()?;
2705 let state = self.concurrent_state_mut()?;
2706
2707 waitable.trap_if_in_waitable_set(state)?;
2708
2709 let set = state.get_mut(caller.thread)?.sync_call_set;
2710 waitable.join(state, Some(set))?;
2711
2712 self.switch_or_trap_if_may_not_suspend(caller_instance)?;
2713
2714 self.suspend(SuspendReason::Waiting {
2715 set,
2716 thread: caller,
2717 })?;
2718 let state = self.concurrent_state_mut()?;
2719
2720 waitable.join(state, None)
2721 }
2722
2723 fn cleanup_thread(
2745 &mut self,
2746 guest_thread: QualifiedThreadId,
2747 runtime_instance: RuntimeInstance,
2748 ) -> Result<()> {
2749 let state = self.concurrent_state_mut()?;
2750 state.take_next_switch_item()?;
2753 let thread_data = state.get_mut(guest_thread.thread)?;
2754 let sync_call_set = thread_data.sync_call_set;
2755 if let Some(guest_id) = thread_data.instance_rep {
2756 self.instance_state(runtime_instance)
2757 .thread_handle_table()
2758 .guest_thread_remove(guest_id)?;
2759 }
2760 let state = self.concurrent_state_mut()?;
2761
2762 for waitable in mem::take(&mut state.get_mut(sync_call_set)?.ready) {
2764 if let Some(Event::Subtask {
2765 status: Status::Returned | Status::ReturnCancelled,
2766 }) = waitable.common(state)?.event
2767 {
2768 waitable.delete_from(state)?;
2769 }
2770 }
2771
2772 state.delete(guest_thread.thread)?;
2773 state.delete(sync_call_set)?;
2774 let task = state.get_mut(guest_thread.task)?;
2775 task.threads.remove(&guest_thread.thread);
2776
2777 if task.threads.is_empty() && !task.returned_or_cancelled() {
2778 bail!(Trap::NoAsyncResult);
2779 }
2780
2781 if !task.decremented_interesting_task_count && task.exited && task.returned_or_cancelled() {
2782 task.decremented_interesting_task_count = true;
2783
2784 debug_assert!(state.interesting_tasks > 0);
2785 state.interesting_tasks -= 1;
2786 if state.interesting_tasks == 0
2787 && let Some(waker) = state.interesting_tasks_empty_waker.take()
2788 {
2789 waker.wake();
2790 }
2791 }
2792
2793 state.decrement_task_ref_count(guest_thread.task)?;
2794
2795 Ok(())
2796 }
2797
2798 fn cancel_guest_subtask_without_lowered_parameters(
2807 &mut self,
2808 caller_instance: RuntimeInstance,
2809 guest_task: TableId<GuestTask>,
2810 ) -> Result<()> {
2811 let concurrent_state = self.concurrent_state_mut()?;
2812 let task = concurrent_state.get_mut(guest_task)?;
2813 assert!(!task.already_lowered_parameters());
2814 task.lower_params = None;
2818 task.lift_result = None;
2819 task.exited = true;
2820 let instance = task.instance;
2821
2822 assert_eq!(1, task.threads.len());
2829 let thread = *task.threads.iter().next().unwrap();
2830 let next_switch_item = concurrent_state.save_next_switch_item()?;
2831 self.cleanup_thread(
2832 QualifiedThreadId {
2833 task: guest_task,
2834 thread,
2835 },
2836 caller_instance,
2837 )?;
2838 self.concurrent_state_mut()?
2839 .restore_next_switch_item(next_switch_item)?;
2840
2841 let pending = &mut self.instance_state(instance).concurrent_state().pending;
2843 let pending_count = pending.len();
2844 let mut decrement = 0;
2845 let mut consume = |kind: &GuestCallKind| {
2846 if let GuestCallKind::StartImplicit {
2847 was_pending: true, ..
2848 } = kind
2849 {
2850 decrement += 1;
2851 }
2852 };
2853 pending.retain(|thread, kind| {
2854 if thread.task == guest_task {
2855 consume(kind);
2856 false
2857 } else {
2858 true
2859 }
2860 });
2861
2862 if pending.len() == pending_count {
2863 let mut matches = |item: &WorkItem| match item {
2866 WorkItem::ResumeThread { thread, .. } => thread.task == guest_task,
2867 WorkItem::GuestCall {
2868 call: GuestCall { thread, kind },
2869 ..
2870 } => {
2871 if thread.task == guest_task {
2872 consume(kind);
2873 true
2874 } else {
2875 false
2876 }
2877 }
2878 _ => false,
2879 };
2880
2881 let mut remove = |queue: &mut VecDeque<WorkItem>| {
2882 let count = queue.len();
2883 queue.retain(|item| !matches(item));
2884 count != queue.len()
2885 };
2886
2887 let state = self.concurrent_state_mut()?;
2888 let mut found = remove(&mut state.high_priority);
2889 found |= remove(&mut state.low_priority);
2890
2891 for item in [&mut state.switch_item, &mut state.next_switch_item] {
2892 if matches!(item, Some(item) if matches(item)) {
2893 found = true;
2894 *item = None;
2895 }
2896 }
2897
2898 if !found {
2899 bail!(Trap::SubtaskCancelAfterTerminal);
2900 }
2901 }
2902
2903 self.decrement_pending_start_count(instance, decrement)?;
2904
2905 Ok(())
2906 }
2907
2908 fn decrement_pending_start_count(
2909 &mut self,
2910 instance: RuntimeInstance,
2911 decrement: usize,
2912 ) -> Result<()> {
2913 if decrement > 0 {
2914 let count = &mut self
2915 .instance_state(instance)
2916 .concurrent_state()
2917 .pending_start_count;
2918
2919 if *count < decrement {
2920 bail_bug!("`ConcurrentInstantState::pending_start_count` underflow");
2921 }
2922
2923 *count -= decrement;
2924
2925 self.partition_pending(instance)?;
2927 }
2928
2929 Ok(())
2930 }
2931
2932 pub(crate) fn current_scope(&mut self) -> Result<Option<CurrentScope>> {
2935 if !self.concurrency_support() {
2936 return Ok(self
2937 .current_scope_id_not_concurrent()?
2938 .map(|id| CurrentScope::Id(VMScope::id(id))));
2939 }
2940
2941 Ok(match self.current_thread()? {
2942 CurrentThread::Guest(id) => Some(CurrentScope::Id(VMScope::id(id.task.rep()))),
2943 CurrentThread::Host(id) => Some(CurrentScope::Id(VMScope::host_id(id.rep()))),
2944 CurrentThread::DeferredHost(_) => Some(CurrentScope::DeferredHost),
2945 CurrentThread::None => return Ok(None),
2946 })
2947 }
2948
2949 pub(crate) fn queue_task(
2950 &mut self,
2951 task: impl FnOnce(&mut dyn VMStore) -> Result<()> + Send + 'static,
2952 ) -> Result<()> {
2953 self.concurrent_state_mut()?
2954 .push_high_priority(WorkItem::WorkerFunction(AlwaysMut::new(Box::new(task))));
2955 Ok(())
2956 }
2957
2958 fn any_may_not_suspend(&mut self) -> Result<bool> {
2967 Ok(self
2975 .concurrent_state_mut()?
2976 .table
2977 .get_mut()
2978 .iter_mut()
2979 .filter_map(|(_, entry)| {
2980 if let Some(task) = entry.entry().downcast_ref::<GuestTask>() {
2981 Some(task.instance)
2982 } else {
2983 None
2984 }
2985 })
2986 .collect::<Vec<_>>()
2987 .into_iter()
2988 .any(|instance| {
2989 self.instance_state(instance)
2990 .concurrent_state()
2991 .do_not_suspend
2992 }))
2993 }
2994}
2995
2996impl Instance {
2997 fn get_event(
3000 self,
3001 store: &mut StoreOpaque,
3002 guest_task: TableId<GuestTask>,
3003 set: Option<TableId<WaitableSet>>,
3004 cancellable: bool,
3005 ) -> Result<Option<(Event, Option<(Waitable, u32)>)>> {
3006 let state = store.concurrent_state_mut()?;
3007
3008 let task = state.get_mut(guest_task)?;
3009 let event = &mut task.event;
3010 if let Some(ev) = event
3011 && (cancellable || !matches!(ev, Event::Cancelled))
3012 {
3013 log::trace!("deliver event {ev:?} to {guest_task:?}");
3014
3015 if matches!(ev, Event::Cancelled) {
3016 task.cancel_request_delivered = true;
3017 }
3018
3019 let ev = *ev;
3020 *event = None;
3021 return Ok(Some((ev, None)));
3022 }
3023
3024 let set = match set {
3025 Some(set) => set,
3026 None => return Ok(None),
3027 };
3028 let waitable = match state.get_mut(set)?.ready.pop_first() {
3029 Some(v) => v,
3030 None => return Ok(None),
3031 };
3032
3033 let common = waitable.common(state)?;
3034 let handle = match common.handle {
3035 Some(h) => h,
3036 None => bail_bug!("handle not set when delivering event"),
3037 };
3038 let event = match common.event.take() {
3039 Some(e) => e,
3040 None => bail_bug!("event not set when delivering event"),
3041 };
3042
3043 log::trace!(
3044 "deliver event {event:?} to {guest_task:?} for {waitable:?} (handle {handle}); set {set:?}"
3045 );
3046
3047 waitable.on_delivery(store, self, event)?;
3048
3049 Ok(Some((event, Some((waitable, handle)))))
3050 }
3051
3052 fn handle_callback_code(
3059 self,
3060 store: &mut dyn VMStore,
3061 guest_thread: QualifiedThreadId,
3062 runtime_instance: RuntimeInstance,
3063 call: impl FnOnce(&mut dyn VMStore) -> Result<u32>,
3064 ) -> Result<()> {
3065 let old_thread = store.set_thread(guest_thread)?;
3066 log::trace!(
3067 "callback-lifted call: replaced {old_thread:?} with {guest_thread:?} as current thread"
3068 );
3069
3070 store.enter_instance(runtime_instance);
3071
3072 let mut code = call(store)?;
3073
3074 if matches!(
3080 unpack_callback_code(code).0,
3081 callback_code::YIELD | callback_code::WAIT
3082 ) && let Some((event, _)) = self.get_event(store, guest_thread.task, None, true)?
3083 {
3084 let (unpacked, set) = unpack_callback_code(code);
3085 log::trace!(
3086 "{guest_thread:?} returned callback code {unpacked} (set: {set}) with a pending \
3087 cancellation; delivering it via callback"
3088 );
3089 code = invoke_callback(store, guest_thread.task, event, 0)?;
3090 }
3091
3092 store.exit_instance(runtime_instance)?;
3093
3094 store.set_thread(old_thread)?;
3095 log::trace!("callback-lifted call: restored {old_thread:?} as current thread");
3096
3097 let store = &mut **store;
3098 let (code, set) = unpack_callback_code(code);
3099
3100 log::trace!("received callback code from {guest_thread:?}: {code} (set: {set})");
3101
3102 let state = store.concurrent_state_mut()?;
3103
3104 state.take_next_switch_item()?;
3105
3106 let get_set = |store: &mut StoreOpaque, handle| -> Result<_> {
3107 let set = store
3108 .instance_state(runtime_instance)
3109 .handle_table()
3110 .waitable_set_rep(handle)?;
3111
3112 Ok(TableId::<WaitableSet>::new(set))
3113 };
3114
3115 match code {
3116 callback_code::EXIT => {
3117 log::trace!("implicit thread {guest_thread:?} completed");
3118 let task = store.concurrent_state_mut()?.get_mut(guest_thread.task)?;
3119 task.exited = true;
3120 task.callback = None;
3121
3122 store.switch_or_trap_if_may_not_suspend(runtime_instance)?;
3127
3128 store.cleanup_thread(guest_thread, runtime_instance)?;
3129 }
3130 callback_code::YIELD => {
3131 let old = state
3134 .get_mut(guest_thread.thread)?
3135 .wake_on_cancel
3136 .replace(WakeOnCancel::Yielding);
3137 if !old.is_none() {
3138 bail_bug!("thread unexpectedly had wake_on_cancel set");
3139 }
3140
3141 let call = GuestCall {
3148 thread: guest_thread,
3149 kind: GuestCallKind::DeliverEvent {
3150 instance: self,
3151 set: None,
3152 },
3153 };
3154 state.push_low_priority(WorkItem::GuestCall {
3157 instance: runtime_instance,
3158 call,
3159 });
3160 }
3161 callback_code::WAIT => {
3162 let set = get_set(store, set)?;
3163 self.wait_with_callback(store, guest_thread, set)?;
3164 }
3165 _ => bail!(Trap::UnsupportedCallbackCode),
3166 }
3167
3168 Ok(())
3169 }
3170
3171 fn wait_with_callback(
3177 self,
3178 store: &mut StoreOpaque,
3179 guest_thread: QualifiedThreadId,
3180 set: TableId<WaitableSet>,
3181 ) -> Result<()> {
3182 let state = store.concurrent_state_mut()?;
3183 state.get_mut(set)?.num_waiting += 1;
3186
3187 if state.get_mut(guest_thread.task)?.event.is_some()
3188 || !state.get_mut(set)?.ready.is_empty()
3189 {
3190 let instance = state.get_mut(guest_thread.task)?.instance;
3192 state.push_high_priority(WorkItem::GuestCall {
3193 instance,
3194 call: GuestCall {
3195 thread: guest_thread,
3196 kind: GuestCallKind::DeliverEvent {
3197 instance: self,
3198 set: Some(set),
3199 },
3200 },
3201 });
3202 return Ok(());
3203 }
3204
3205 let instance = store
3211 .concurrent_state_mut()?
3212 .get_mut(guest_thread.task)?
3213 .instance;
3214 store.switch_or_trap_if_may_not_suspend(instance)?;
3215
3216 let state = store.concurrent_state_mut()?;
3222 let old = state
3223 .get_mut(guest_thread.thread)?
3224 .wake_on_cancel
3225 .replace(WakeOnCancel::Waiting(set));
3226 if !old.is_none() {
3227 bail_bug!("thread unexpectedly had wake_on_cancel set");
3228 }
3229 let old = state
3230 .get_mut(set)?
3231 .waiting
3232 .insert(guest_thread, WaitMode::Callback(self));
3233 if !old.is_none() {
3234 bail_bug!("set's waiting set already had this thread registered");
3235 }
3236 Ok(())
3237 }
3238
3239 unsafe fn stage_call<T: 'static>(
3246 self,
3247 mut store: StoreContextMut<T>,
3248 guest_thread: QualifiedThreadId,
3249 callee: SendSyncPtr<VMFuncRef>,
3250 param_count: usize,
3251 result_count: usize,
3252 async_: bool,
3253 callback: Option<SendSyncPtr<VMFuncRef>>,
3254 post_return: Option<SendSyncPtr<VMFuncRef>>,
3255 host_caller: bool,
3256 ) -> Result<()> {
3257 unsafe fn make_call<T: 'static>(
3272 store: StoreContextMut<T>,
3273 guest_thread: QualifiedThreadId,
3274 callee: SendSyncPtr<VMFuncRef>,
3275 param_count: usize,
3276 result_count: usize,
3277 ) -> impl FnOnce(&mut dyn VMStore) -> Result<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>
3278 + Send
3279 + Sync
3280 + 'static
3281 + use<T> {
3282 let token = StoreToken::new(store);
3283 move |store: &mut dyn VMStore| {
3284 let mut storage = [MaybeUninit::uninit(); MAX_FLAT_PARAMS];
3285
3286 store
3287 .concurrent_state_mut()?
3288 .set_thread_running(guest_thread.thread)?;
3289 let task = store.concurrent_state_mut()?.get_mut(guest_thread.task)?;
3290 let lower = match task.lower_params.take() {
3291 Some(l) => l,
3292 None => bail_bug!("lower_params missing"),
3293 };
3294
3295 lower(store, &mut storage[..param_count])?;
3296
3297 let mut store = token.as_context_mut(store);
3298
3299 unsafe {
3302 crate::Func::call_unchecked_raw(
3303 &mut store,
3304 callee.as_non_null(),
3305 NonNull::new(
3306 &mut storage[..param_count.max(result_count)]
3307 as *mut [MaybeUninit<ValRaw>] as _,
3308 )
3309 .unwrap(),
3310 UncaughtException::Trap,
3311 )?;
3312 }
3313
3314 Ok(storage)
3315 }
3316 }
3317
3318 let call = unsafe {
3322 make_call(
3323 store.as_context_mut(),
3324 guest_thread,
3325 callee,
3326 param_count,
3327 result_count,
3328 )
3329 };
3330
3331 let callee_instance = store
3332 .0
3333 .concurrent_state_mut()?
3334 .get_mut(guest_thread.task)?
3335 .instance;
3336
3337 let fun = if callback.is_some() {
3338 assert!(async_);
3339
3340 Box::new(move |store: &mut dyn VMStore| {
3341 self.add_guest_thread_to_instance_table(
3342 guest_thread.thread,
3343 store,
3344 callee_instance.index,
3345 )?;
3346 self.handle_callback_code(store, guest_thread, callee_instance, |store| {
3347 let storage = call(store)?;
3348
3349 Ok(unsafe { storage[0].assume_init() }.get_i32() as u32)
3352 })
3353 }) as Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send + Sync>
3354 } else {
3355 let token = StoreToken::new(store.as_context_mut());
3356 Box::new(move |store: &mut dyn VMStore| {
3357 self.add_guest_thread_to_instance_table(
3358 guest_thread.thread,
3359 store,
3360 callee_instance.index,
3361 )?;
3362 let old_thread = store.set_thread(guest_thread)?;
3363 log::trace!(
3364 "sync/async-stackful call: replaced {old_thread:?} with {guest_thread:?} as current thread",
3365 );
3366 let flags = self.id().get(store).instance_flags(callee_instance.index);
3367
3368 let callee_async_typed = store
3369 .concurrent_state_mut()?
3370 .get_mut(guest_thread.task)?
3371 .async_typed;
3372
3373 if !async_ && callee_async_typed {
3377 store.enter_instance(callee_instance);
3378 }
3379
3380 if !callee_async_typed {
3381 store.enter_sync_call(callee_instance)?;
3382 }
3383
3384 let storage = call(store)?;
3391
3392 if !callee_async_typed {
3393 store.exit_sync_call(callee_instance)?;
3394 }
3395
3396 if !async_ {
3397 if callee_async_typed {
3403 store.exit_instance(callee_instance)?;
3404 }
3405
3406 let lift = {
3407 let state = store.concurrent_state_mut()?;
3408 if !state.get_mut(guest_thread.task)?.result.is_none() {
3409 bail_bug!("task has already produced a result");
3410 }
3411
3412 match state.get_mut(guest_thread.task)?.lift_result.take() {
3413 Some(lift) => lift,
3414 None => bail_bug!("lift_result field is missing"),
3415 }
3416 };
3417
3418 let result = (lift.lift)(store, unsafe {
3421 mem::transmute::<&[MaybeUninit<ValRaw>], &[ValRaw]>(
3422 &storage[..result_count],
3423 )
3424 })?;
3425
3426 let post_return_arg = match result_count {
3427 0 => ValRaw::i32(0),
3428 1 => unsafe { storage[0].assume_init() },
3431 _ => unreachable!(),
3432 };
3433
3434 unsafe {
3435 call_post_return(
3436 token.as_context_mut(store),
3437 post_return.map(|v| v.as_non_null()),
3438 post_return_arg,
3439 flags,
3440 )?;
3441 }
3442
3443 self.task_complete(store, guest_thread.task, result, Status::Returned)?;
3444 }
3445
3446 store.set_thread(old_thread)?;
3447
3448 store
3449 .concurrent_state_mut()?
3450 .get_mut(guest_thread.task)?
3451 .exited = true;
3452
3453 log::trace!(
3454 "clean up thread; async lifted? {async_} async typed? {callee_async_typed}"
3455 );
3456
3457 if callee_async_typed {
3458 store.switch_or_trap_if_may_not_suspend(callee_instance)?;
3463 }
3464
3465 store.cleanup_thread(guest_thread, callee_instance)?;
3467 Ok(())
3468 })
3469 };
3470
3471 store.0.concurrent_state_mut()?.push_work_item(
3472 WorkItem::GuestCall {
3473 instance: callee_instance,
3474 call: GuestCall {
3475 thread: guest_thread,
3476 kind: GuestCallKind::StartImplicit {
3477 closure: fun,
3478 was_pending: false,
3479 },
3480 },
3481 },
3482 if host_caller {
3483 Priority::Low
3489 } else {
3490 Priority::Switch
3491 },
3492 )?;
3493
3494 Ok(())
3495 }
3496
3497 unsafe fn prepare_call<T: 'static>(
3510 self,
3511 mut store: StoreContextMut<T>,
3512 start: NonNull<VMFuncRef>,
3513 return_: NonNull<VMFuncRef>,
3514 caller_instance: RuntimeComponentInstanceIndex,
3515 callee_instance: RuntimeComponentInstanceIndex,
3516 task_return_type: TypeTupleIndex,
3517 callee_async_typed: bool,
3518 memory: *mut VMMemoryDefinition,
3519 string_encoding: StringEncoding,
3520 caller_info: CallerInfo,
3521 ) -> Result<()> {
3522 enum ResultInfo {
3523 Heap { results: u32 },
3524 Stack { result_count: u32 },
3525 }
3526
3527 let result_info = match &caller_info {
3528 CallerInfo::Async {
3529 has_result: true,
3530 params,
3531 } => ResultInfo::Heap {
3532 results: match params.last() {
3534 Some(r) => r.get_u32(),
3535 None => bail_bug!("retptr missing"),
3536 },
3537 },
3538 CallerInfo::Async {
3539 has_result: false, ..
3540 } => ResultInfo::Stack { result_count: 0 },
3541 CallerInfo::Sync {
3542 result_count,
3543 params,
3544 } if *result_count > u32::try_from(MAX_FLAT_RESULTS)? => ResultInfo::Heap {
3545 results: match params.last() {
3547 Some(r) => r.get_u32(),
3548 None => bail_bug!("arg ptr missing"),
3549 },
3550 },
3551 CallerInfo::Sync { result_count, .. } => ResultInfo::Stack {
3552 result_count: *result_count,
3553 },
3554 };
3555
3556 let sync_caller = matches!(caller_info, CallerInfo::Sync { .. });
3557
3558 let start = SendSyncPtr::new(start);
3562 let return_ = SendSyncPtr::new(return_);
3563 let token = StoreToken::new(store.as_context_mut());
3564 let old_thread = store.0.current_guest_thread()?;
3565
3566 let state = store.0.concurrent_state_mut()?;
3567
3568 debug_assert_eq!(
3569 state.get_mut(old_thread.task)?.instance,
3570 self.runtime_instance(caller_instance)
3571 );
3572
3573 let guest_thread = GuestTask::new(
3574 state,
3575 Box::new(move |store, dst| {
3576 let mut store = token.as_context_mut(store);
3577 assert!(dst.len() <= MAX_FLAT_PARAMS);
3578 let mut src = [MaybeUninit::uninit(); MAX_FLAT_PARAMS + 1];
3580 let count = match caller_info {
3581 CallerInfo::Async { params, has_result } => {
3585 let params = ¶ms[..params.len() - usize::from(has_result)];
3586 for (param, src) in params.iter().zip(&mut src) {
3587 src.write(*param);
3588 }
3589 params.len()
3590 }
3591
3592 CallerInfo::Sync { params, .. } => {
3594 for (param, src) in params.iter().zip(&mut src) {
3595 src.write(*param);
3596 }
3597 params.len()
3598 }
3599 };
3600 unsafe {
3607 crate::Func::call_unchecked_raw(
3608 &mut store,
3609 start.as_non_null(),
3610 NonNull::new(
3611 &mut src[..count.max(dst.len())] as *mut [MaybeUninit<ValRaw>] as _,
3612 )
3613 .unwrap(),
3614 UncaughtException::Trap,
3615 )?;
3616 }
3617 dst.copy_from_slice(&src[..dst.len()]);
3618 let task = store.0.current_guest_thread()?.task;
3619 let state = store.0.concurrent_state_mut()?;
3620 Waitable::Guest(task).set_event(
3621 state,
3622 Some(Event::Subtask {
3623 status: Status::Started,
3624 }),
3625 )?;
3626 Ok(())
3627 }),
3628 LiftResult {
3629 lift: Box::new(move |store, src| {
3630 let mut store = token.as_context_mut(store);
3633 let mut my_src = src.to_owned(); if let ResultInfo::Heap { results } = &result_info {
3635 my_src.push(ValRaw::u32(*results));
3636 }
3637
3638 unsafe {
3645 crate::Func::call_unchecked_raw(
3646 &mut store,
3647 return_.as_non_null(),
3648 my_src.as_mut_slice().into(),
3649 UncaughtException::Trap,
3650 )?;
3651 }
3652
3653 let thread = store.0.current_guest_thread()?;
3654 let state = store.0.concurrent_state_mut()?;
3655 if sync_caller {
3656 state.get_mut(thread.task)?.sync_result = SyncResult::Produced(
3657 if let ResultInfo::Stack { result_count } = &result_info {
3658 match result_count {
3659 0 => None,
3660 1 => Some(my_src[0]),
3661 _ => unreachable!(),
3662 }
3663 } else {
3664 None
3665 },
3666 );
3667 }
3668 Ok(Box::new(DummyResult) as Box<dyn Any + Send + Sync>)
3669 }),
3670 ty: task_return_type,
3671 memory: NonNull::new(memory).map(SendSyncPtr::new),
3672 string_encoding,
3673 },
3674 Caller::Guest { thread: old_thread },
3675 None,
3676 self.runtime_instance(callee_instance),
3677 callee_async_typed,
3678 false,
3681 )?;
3682
3683 store.0.set_thread(guest_thread)?;
3686 log::trace!("pushed {guest_thread:?} as current thread; old thread was {old_thread:?}");
3687
3688 Ok(())
3689 }
3690
3691 unsafe fn call_callback<T>(
3696 self,
3697 mut store: StoreContextMut<T>,
3698 function: SendSyncPtr<VMFuncRef>,
3699 event: Event,
3700 handle: u32,
3701 ) -> Result<u32> {
3702 let (ordinal, result) = event.parts();
3703 let params = &mut [
3704 ValRaw::u32(ordinal),
3705 ValRaw::u32(handle),
3706 ValRaw::u32(result),
3707 ];
3708 unsafe {
3713 crate::Func::call_unchecked_raw(
3714 &mut store,
3715 function.as_non_null(),
3716 params.as_mut_slice().into(),
3717 UncaughtException::Trap,
3718 )?;
3719 }
3720 Ok(params[0].get_u32())
3721 }
3722
3723 unsafe fn start_call<T: 'static>(
3741 self,
3742 mut store: StoreContextMut<T>,
3743 callback: *mut VMFuncRef,
3744 post_return: *mut VMFuncRef,
3745 callee: NonNull<VMFuncRef>,
3746 param_count: u32,
3747 result_count: u32,
3748 flags: u32,
3749 storage: &mut [MaybeUninit<ValRaw>],
3750 ) -> Result<()> {
3751 let token = StoreToken::new(store.as_context_mut());
3752 let async_caller = (flags & START_FLAG_ASYNC_CALLER) != 0;
3753 let guest_thread = store.0.current_guest_thread()?;
3754 let state = store.0.concurrent_state_mut()?;
3755
3756 if !state.event_loop_running {
3761 bail!(
3762 "async function started during an original synchronous \
3763 entrypoint; please use an async-style entrypoint instead"
3764 );
3765 }
3766
3767 let callee = SendSyncPtr::new(callee);
3768 let param_count = usize::try_from(param_count)?;
3769 assert!(param_count <= MAX_FLAT_PARAMS);
3770 let result_count = usize::try_from(result_count)?;
3771 assert!(result_count <= MAX_FLAT_RESULTS);
3772
3773 let task = state.get_mut(guest_thread.task)?;
3774 let callee_async_typed = task.async_typed;
3775 let callee_instance = task.instance;
3776
3777 task.async_lifted = (flags & START_FLAG_ASYNC_CALLEE) != 0;
3778
3779 if let Some(callback) = NonNull::new(callback) {
3780 let callback = SendSyncPtr::new(callback);
3784 task.callback = Some(Box::new(move |store, event, handle| {
3785 let store = token.as_context_mut(store);
3786 unsafe { self.call_callback::<T>(store, callback, event, handle) }
3787 }));
3788 }
3789
3790 let Caller::Guest { thread: caller } = &task.caller else {
3791 bail_bug!("start_call unexpectedly invoked for host->guest call");
3794 };
3795 let caller = *caller;
3796 let caller_instance = state.get_mut(caller.task)?.instance;
3797
3798 unsafe {
3800 self.stage_call(
3801 store.as_context_mut(),
3802 guest_thread,
3803 callee,
3804 param_count,
3805 result_count,
3806 (flags & START_FLAG_ASYNC_CALLEE) != 0,
3807 NonNull::new(callback).map(SendSyncPtr::new),
3808 NonNull::new(post_return).map(SendSyncPtr::new),
3809 false,
3810 )?;
3811 }
3812
3813 let old_do_not_suspend = if callee_async_typed {
3814 let state = store.0.instance_state(callee_instance).concurrent_state();
3821 let old_do_not_suspend = state.do_not_suspend;
3822 state.do_not_suspend = false;
3823 Some(old_do_not_suspend)
3824 } else {
3825 None
3826 };
3827
3828 let state = store.0.concurrent_state_mut()?;
3829
3830 let guest_waitable = Waitable::Guest(guest_thread.task);
3833 let old_set = guest_waitable.common(state)?.set;
3834 let set = state.get_mut(caller.thread)?.sync_call_set;
3835 guest_waitable.join(state, Some(set))?;
3836
3837 store.0.set_thread(CurrentThread::None)?;
3838
3839 let mut yielded = false;
3855 let (status, waitable) = loop {
3856 store.0.suspend(if yielded {
3857 SuspendReason::Waiting {
3858 set,
3859 thread: caller,
3860 }
3861 } else {
3862 yielded = true;
3863 SuspendReason::YieldingToSubtask { thread: caller }
3864 })?;
3865
3866 if let Some(old_do_not_suspend) = old_do_not_suspend {
3867 store
3868 .0
3869 .instance_state(callee_instance)
3870 .concurrent_state()
3871 .do_not_suspend = old_do_not_suspend;
3872 }
3873
3874 let state = store.0.concurrent_state_mut()?;
3875
3876 log::trace!("taking event for {:?}", guest_thread.task);
3877 let event = guest_waitable.take_event(state)?;
3878 let Some(Event::Subtask { status }) = event else {
3879 bail_bug!("subtasks should only get subtask events, got {event:?}")
3880 };
3881
3882 log::trace!("status {status:?} for {:?}", guest_thread.task);
3883
3884 if status == Status::Returned {
3885 break (status, None);
3887 } else if async_caller {
3888 let handle = store
3892 .0
3893 .handle_table_insertion(caller_instance)
3894 .subtask_guest(guest_thread.task.rep())?;
3895 store
3896 .0
3897 .concurrent_state_mut()?
3898 .get_mut(guest_thread.task)?
3899 .common
3900 .handle = Some(handle);
3901 break (status, Some(handle));
3902 } else {
3903 store.0.switch_or_trap_if_may_not_suspend(caller_instance)?;
3907 }
3908 };
3909
3910 guest_waitable.join(store.0.concurrent_state_mut()?, old_set)?;
3911
3912 store.0.set_thread(caller)?;
3914
3915 store
3916 .0
3917 .concurrent_state_mut()?
3918 .set_thread_running(caller.thread)?;
3919
3920 log::trace!("popped current thread {guest_thread:?}; new thread is {caller:?}");
3921
3922 if async_caller {
3923 let Some(slot) = storage.first_mut() else {
3924 bail_bug!("no storage for async call status");
3925 };
3926 *slot = MaybeUninit::new(ValRaw::u32(status.pack(waitable)));
3927 } else {
3928 let state = store.0.concurrent_state_mut()?;
3931 let task = state.get_mut(guest_thread.task)?;
3932 if let Some(Some(result)) = task.sync_result.take()? {
3933 storage[0] = MaybeUninit::new(result);
3934 }
3935 }
3936
3937 if status == Status::Returned {
3938 store
3939 .0
3940 .concurrent_state_mut()?
3941 .decrement_task_ref_count(guest_thread.task)?;
3942 }
3943
3944 Ok(())
3945 }
3946
3947 pub(crate) fn first_poll<T: 'static, R: Send + 'static>(
3963 self,
3964 mut store: StoreContextMut<'_, T>,
3965 host_task: EnteredHostTask,
3966 result_may_require_realloc: bool,
3967 future: impl Future<Output = Result<R>> + Send + 'static,
3968 lower: impl FnOnce(StoreContextMut<T>, Option<R>, bool, Option<TableId<HostTask>>) -> Result<()>
3969 + Send
3970 + 'static,
3971 ) -> Result<u32> {
3972 let token = StoreToken::new(store.as_context_mut());
3973
3974 let (join_handle, future) = JoinHandle::run(future);
3977 let mut future = Box::pin(future);
3978
3979 let poll = tls::set(store.0, || {
3984 future
3985 .as_mut()
3986 .poll(&mut Context::from_waker(&Waker::noop()))
3987 });
3988
3989 match poll {
3990 Poll::Ready(result) => {
3992 let result = result.transpose()?;
3993 let task = store.0.current_materialized_host_task()?;
3996 lower(store.as_context_mut(), result, true, task)?;
3997 return Ok(Status::Returned.pack(None));
3998 }
3999
4000 Poll::Pending => {}
4002 }
4003
4004 let Some(task) = store.0.materialize_host_task_id()? else {
4008 bail_bug!("current thread is not a host thread")
4009 };
4010 {
4011 let state = &mut store.0.concurrent_state_mut()?.get_mut(task)?.state;
4012 assert!(matches!(state, HostTaskState::CalleeStarted));
4013 *state = HostTaskState::CalleeRunning(join_handle);
4014 }
4015
4016 let future = Box::pin(async move {
4024 let result = match run_with_host_task_set(task, future).await? {
4025 Some(result) => Some(result?),
4026 None => None,
4027 };
4028 let on_complete = move |store: &mut dyn VMStore| {
4029 let mut store = token.as_context_mut(store);
4033 let old = store.0.set_thread(task)?;
4034
4035 let status = if result.is_some() {
4036 Status::Returned
4037 } else {
4038 Status::ReturnCancelled
4039 };
4040
4041 lower(store.as_context_mut(), result, false, Some(task))?;
4042 let state = store.0.concurrent_state_mut()?;
4043 match &mut state.get_mut(task)?.state {
4044 pending @ HostTaskState::CalleeCancelling => {
4047 *pending = HostTaskState::CalleeDone { cancelled: true };
4048 }
4049
4050 other => *other = HostTaskState::CalleeDone { cancelled: false },
4052 }
4053 Waitable::Host(task).set_event(state, Some(Event::Subtask { status }))?;
4054
4055 store.0.set_thread(old)?;
4056 Ok(())
4057 };
4058
4059 tls::get(move |store| {
4060 if result_may_require_realloc {
4061 store
4066 .concurrent_state_mut()?
4067 .push_high_priority(WorkItem::WorkerFunction(AlwaysMut::new(Box::new(
4068 on_complete,
4069 ))));
4070 Ok(())
4071 } else {
4072 on_complete(store)
4075 }
4076 })
4077 });
4078
4079 let caller = match host_task {
4082 Some(caller) => caller,
4083 None => bail_bug!("host task wasn't created but should have been"),
4084 };
4085 let state = store.0.concurrent_state_mut()?;
4086 state.push_future(future);
4087 let instance = state.get_mut(caller.task)?.instance;
4088 let handle = store
4089 .0
4090 .handle_table_insertion(instance)
4091 .subtask_host(task.rep())?;
4092 store.0.concurrent_state_mut()?.get_mut(task)?.common.handle = Some(handle);
4093 log::trace!("assign {task:?} handle {handle} for {caller:?} instance {instance:?}");
4094
4095 store.0.set_thread(caller)?;
4099 Ok(Status::Started.pack(Some(handle)))
4100 }
4101
4102 pub(crate) fn task_return(
4105 self,
4106 store: &mut dyn VMStore,
4107 ty: TypeTupleIndex,
4108 options: OptionsIndex,
4109 storage: &[ValRaw],
4110 ) -> Result<()> {
4111 let guest_thread = store.current_guest_thread()?;
4112 let state = store.concurrent_state_mut()?;
4113 if !state.get_mut(guest_thread.task)?.async_lifted {
4114 bail!(Trap::TaskReturnOrCancelSyncLifted);
4115 }
4116 let lift = state
4117 .get_mut(guest_thread.task)?
4118 .lift_result
4119 .take()
4120 .ok_or_else(|| Trap::TaskCancelOrReturnTwice)?;
4121 if !state.get_mut(guest_thread.task)?.result.is_none() {
4122 bail_bug!("task result unexpectedly already set");
4123 }
4124
4125 let CanonicalOptions {
4126 string_encoding,
4127 data_model,
4128 ..
4129 } = &self.id().get(store).component().env_component().options[options];
4130
4131 let invalid = ty != lift.ty
4132 || string_encoding != &lift.string_encoding
4133 || match data_model {
4134 CanonicalOptionsDataModel::LinearMemory(opts) => match opts.memory {
4135 Some(memory) => {
4136 let expected = lift.memory.map(|v| v.as_ptr()).unwrap_or(ptr::null_mut());
4137 let actual = self.id().get(store).runtime_memory(memory);
4138 expected != actual.as_ptr()
4139 }
4140 None => false,
4143 },
4144 CanonicalOptionsDataModel::Gc { .. } => true,
4146 };
4147
4148 if invalid {
4149 bail!(Trap::TaskReturnInvalid);
4150 }
4151
4152 log::trace!("task.return for {guest_thread:?}");
4153
4154 let result = (lift.lift)(store, storage)?;
4155 self.task_complete(store, guest_thread.task, result, Status::Returned)
4156 }
4157
4158 pub(crate) fn task_cancel(self, store: &mut StoreOpaque) -> Result<()> {
4160 let guest_thread = store.current_guest_thread()?;
4161 let state = store.concurrent_state_mut()?;
4162 let task = state.get_mut(guest_thread.task)?;
4163 if !task.async_lifted {
4164 bail!(Trap::TaskReturnOrCancelSyncLifted);
4165 }
4166 if !task.cancel_request_delivered {
4167 bail!(Trap::TaskCancelNotCancelled);
4168 }
4169 _ = task
4170 .lift_result
4171 .take()
4172 .ok_or_else(|| Trap::TaskCancelOrReturnTwice)?;
4173
4174 if !task.result.is_none() {
4175 bail_bug!("task result should not bet set yet");
4176 }
4177
4178 log::trace!("task.cancel for {guest_thread:?}");
4179
4180 self.task_complete(
4181 store,
4182 guest_thread.task,
4183 Box::new(DummyResult),
4184 Status::ReturnCancelled,
4185 )
4186 }
4187
4188 fn task_complete(
4194 self,
4195 store: &mut StoreOpaque,
4196 guest_task: TableId<GuestTask>,
4197 result: Box<dyn Any + Send + Sync>,
4198 status: Status,
4199 ) -> Result<()> {
4200 store
4201 .component_resource_tables(Some(self))?
4202 .validate_scope_exit()?;
4203
4204 let state = store.concurrent_state_mut()?;
4205 let task = state.get_mut(guest_task)?;
4206
4207 task.event = None;
4211
4212 if let Caller::Host { tx, .. } = &mut task.caller {
4213 if let Some(tx) = tx.take() {
4214 _ = tx.send(result);
4215 }
4216 } else {
4217 task.result = Some(result);
4218 Waitable::Guest(guest_task).set_event(state, Some(Event::Subtask { status }))?;
4219 }
4220
4221 Ok(())
4222 }
4223
4224 pub(crate) fn waitable_set_new(
4226 self,
4227 store: &mut StoreOpaque,
4228 caller_instance: RuntimeComponentInstanceIndex,
4229 ) -> Result<u32> {
4230 let set = store.concurrent_state_mut()?.push(WaitableSet::default())?;
4231 let handle = store
4232 .handle_table_insertion(self.runtime_instance(caller_instance))
4233 .waitable_set(set.rep())?;
4234 log::trace!("new waitable set {set:?} (handle {handle})");
4235 Ok(handle)
4236 }
4237
4238 pub(crate) fn waitable_set_drop(
4240 self,
4241 store: &mut StoreOpaque,
4242 caller_instance: RuntimeComponentInstanceIndex,
4243 set: u32,
4244 ) -> Result<()> {
4245 let rep = store
4246 .instance_state(self.runtime_instance(caller_instance))
4247 .handle_table()
4248 .waitable_set_remove(set)?;
4249
4250 log::trace!("drop waitable set {rep} (handle {set})");
4251
4252 let set = store
4256 .concurrent_state_mut()?
4257 .get_mut(TableId::<WaitableSet>::new(rep))?;
4258 if set.num_waiting > 0 {
4259 bail!(Trap::WaitableSetDropHasWaiters);
4260 }
4261
4262 store
4263 .concurrent_state_mut()?
4264 .delete(TableId::<WaitableSet>::new(rep))?;
4265
4266 Ok(())
4267 }
4268
4269 pub(crate) fn waitable_join(
4271 self,
4272 store: &mut StoreOpaque,
4273 caller_instance: RuntimeComponentInstanceIndex,
4274 waitable_handle: u32,
4275 set_handle: u32,
4276 ) -> Result<()> {
4277 let mut instance = self.id().get_mut(store);
4278 let waitable =
4279 Waitable::from_instance(instance.as_mut(), caller_instance, waitable_handle)?;
4280
4281 let set = if set_handle == 0 {
4282 None
4283 } else {
4284 let set = instance.instance_states().0[caller_instance]
4285 .handle_table()
4286 .waitable_set_rep(set_handle)?;
4287
4288 Some(TableId::<WaitableSet>::new(set))
4289 };
4290
4291 waitable.trap_if_has_sync_waiter(store.concurrent_state_mut()?)?;
4292
4293 log::trace!(
4294 "waitable {waitable:?} (handle {waitable_handle}) join set {set:?} (handle {set_handle})",
4295 );
4296
4297 waitable.join(store.concurrent_state_mut()?, set)
4298 }
4299
4300 pub(crate) fn subtask_drop(
4302 self,
4303 store: &mut StoreOpaque,
4304 caller_instance: RuntimeComponentInstanceIndex,
4305 task_id: u32,
4306 ) -> Result<()> {
4307 self.waitable_join(store, caller_instance, task_id, 0)?;
4308
4309 let (rep, is_host) = store
4310 .instance_state(self.runtime_instance(caller_instance))
4311 .handle_table()
4312 .subtask_remove(task_id)?;
4313
4314 let concurrent_state = store.concurrent_state_mut()?;
4315 let waitable = if is_host {
4316 let id = TableId::<HostTask>::new(rep);
4317 let task = concurrent_state.get_mut(id)?;
4318 match &task.state {
4319 HostTaskState::CalleeRunning(_) | HostTaskState::CalleeCancelling => {
4320 bail!(Trap::SubtaskDropNotResolved)
4321 }
4322 HostTaskState::CalleeDone { .. } => {}
4323 HostTaskState::CalleeStarted | HostTaskState::CalleeFinished(_) => {
4324 bail_bug!("invalid state for callee in `subtask.drop`")
4325 }
4326 }
4327
4328 Waitable::Host(id)
4329 } else {
4330 let id = TableId::<GuestTask>::new(rep);
4331 let task = concurrent_state.get_mut(id)?;
4332 if task.lift_result.is_some() {
4333 bail!(Trap::SubtaskDropNotResolved);
4334 }
4335 Waitable::Guest(id)
4336 };
4337
4338 waitable.common(concurrent_state)?.handle = None;
4339
4340 if waitable.take_event(concurrent_state)?.is_some() {
4343 bail!(Trap::SubtaskDropNotResolved);
4344 }
4345
4346 waitable.delete_from(concurrent_state)?;
4347
4348 log::trace!("subtask_drop {waitable:?} (handle {task_id})");
4349 Ok(())
4350 }
4351
4352 pub(crate) fn waitable_set_wait(
4354 self,
4355 store: &mut StoreOpaque,
4356 options: OptionsIndex,
4357 set: u32,
4358 payload: u32,
4359 ) -> Result<u32> {
4360 let &CanonicalOptions {
4361 instance: caller_instance,
4362 ..
4363 } = &self.id().get(store).component().env_component().options[options];
4364 let caller = self.runtime_instance(caller_instance);
4365 let rep = store
4366 .instance_state(self.runtime_instance(caller_instance))
4367 .handle_table()
4368 .waitable_set_rep(set)?;
4369
4370 self.waitable_check(
4371 store,
4372 caller,
4373 WaitableCheck::Wait,
4374 WaitableCheckParams {
4375 set: TableId::new(rep),
4376 options,
4377 payload,
4378 },
4379 )
4380 }
4381
4382 pub(crate) fn waitable_set_poll(
4384 self,
4385 store: &mut StoreOpaque,
4386 options: OptionsIndex,
4387 set: u32,
4388 payload: u32,
4389 ) -> Result<u32> {
4390 let &CanonicalOptions {
4391 instance: caller_instance,
4392 ..
4393 } = &self.id().get(store).component().env_component().options[options];
4394 let caller = self.runtime_instance(caller_instance);
4395 let rep = store
4396 .instance_state(caller)
4397 .handle_table()
4398 .waitable_set_rep(set)?;
4399
4400 self.waitable_check(
4401 store,
4402 caller,
4403 WaitableCheck::Poll,
4404 WaitableCheckParams {
4405 set: TableId::new(rep),
4406 options,
4407 payload,
4408 },
4409 )
4410 }
4411
4412 pub(crate) fn thread_index(&self, store: &mut dyn VMStore) -> Result<u32> {
4414 let thread_id = store.current_guest_thread()?.thread;
4415 match store
4416 .concurrent_state_mut()?
4417 .get_mut(thread_id)?
4418 .instance_rep
4419 {
4420 Some(r) => Ok(r),
4421 None => bail_bug!("thread should have instance_rep by now"),
4422 }
4423 }
4424
4425 pub(crate) fn thread_new_indirect<T: 'static>(
4427 self,
4428 mut store: StoreContextMut<T>,
4429 runtime_instance: RuntimeComponentInstanceIndex,
4430 start_func_ty: ModuleInternedTypeIndex,
4431 start_func_table_idx: RuntimeTableIndex,
4432 start_func_idx: u32,
4433 context: i32,
4434 ) -> Result<u32> {
4435 log::trace!("creating new thread");
4436
4437 let (instance, registry) = self.id().get_mut_and_registry(store.0);
4438 let Some(start_func_ty) = instance.component().signatures().shared_type(start_func_ty)
4439 else {
4440 bail_bug!("thread.new-indirect start function type should be registered");
4441 };
4442 let callee = instance
4443 .index_runtime_func_table(registry, start_func_table_idx, start_func_idx as u64)?
4444 .ok_or_else(|| Trap::ThreadNewIndirectUninitialized)?;
4445 if callee.type_index(store.0) != start_func_ty {
4446 bail!(Trap::ThreadNewIndirectInvalidType);
4447 }
4448
4449 let token = StoreToken::new(store.as_context_mut());
4450 let start_func = Box::new(
4451 move |store: &mut dyn VMStore, guest_thread: QualifiedThreadId| -> Result<()> {
4452 let old_thread = store.set_thread(guest_thread)?;
4453 log::trace!(
4454 "thread start: replaced {old_thread:?} with {guest_thread:?} as current thread"
4455 );
4456
4457 let mut store = token.as_context_mut(store);
4458 let mut params = [ValRaw::i32(context)];
4459 unsafe { callee.call_unchecked(store.as_context_mut(), &mut params)? };
4462
4463 store.0.set_thread(old_thread)?;
4464
4465 let runtime_instance = self.runtime_instance(runtime_instance);
4466
4467 store
4470 .0
4471 .switch_or_trap_if_may_not_suspend(runtime_instance)?;
4472
4473 store.0.cleanup_thread(guest_thread, runtime_instance)?;
4474
4475 log::trace!("explicit thread {guest_thread:?} completed");
4476 let state = store.0.concurrent_state_mut()?;
4477 if let Some(t) = old_thread.guest() {
4478 state.set_thread_running(t.thread)?;
4479 }
4480 log::trace!("thread start: restored {old_thread:?} as current thread");
4481
4482 Ok(())
4483 },
4484 );
4485
4486 let current_thread = store.0.current_guest_thread()?;
4487 let state = store.0.concurrent_state_mut()?;
4488 let parent_task = current_thread.task;
4489
4490 let new_thread = GuestThread::new_explicit(state, parent_task, start_func)?;
4491 let thread_id = state.push(new_thread)?;
4492 state.get_mut(parent_task)?.threads.insert(thread_id);
4493
4494 log::trace!("new thread with id {thread_id:?} created");
4495
4496 self.add_guest_thread_to_instance_table(thread_id, store.0, runtime_instance)
4497 }
4498
4499 pub(crate) fn resume_thread(
4500 self,
4501 store: &mut StoreOpaque,
4502 runtime_instance: RuntimeComponentInstanceIndex,
4503 thread_idx: u32,
4504 how: ResumeThread,
4505 ) -> Result<bool> {
4506 let thread_id =
4507 GuestThread::from_instance(self.id().get_mut(store), runtime_instance, thread_idx)?;
4508 let state = store.concurrent_state_mut()?;
4509 let guest_thread = QualifiedThreadId::qualify(state, thread_id)?;
4510
4511 if store.current_guest_thread()? == guest_thread {
4512 bail!(Trap::CannotResumeThread);
4513 }
4514
4515 let priority = match how {
4516 ResumeThread::Resume => Priority::Switch,
4517 ResumeThread::ResumeLater => Priority::Low,
4518
4519 ResumeThread::Promote => {
4522 let instance = self.runtime_instance(runtime_instance);
4523 let do_not_enter = store
4524 .instance_state(instance)
4525 .concurrent_state()
4526 .do_not_enter;
4527 return store.concurrent_state_mut()?.promote_work_item_matching(
4528 |item: &WorkItem| match item {
4529 WorkItem::ResumeThread { thread, .. }
4530 | WorkItem::ResumeFiber { thread, .. } => *thread == guest_thread,
4531
4532 WorkItem::GuestCall {
4533 call: GuestCall { thread, kind },
4534 ..
4535 } => {
4536 *thread == guest_thread
4537 && match kind {
4538 GuestCallKind::DeliverEvent { .. } => !do_not_enter,
4542
4543 GuestCallKind::StartExplicit(_) => true,
4546
4547 GuestCallKind::StartImplicit { .. } => false,
4551 }
4552 }
4553
4554 WorkItem::PushFuture(_) | WorkItem::WorkerFunction(_) => false,
4555 },
4556 );
4557 }
4558 };
4559
4560 let state = store.concurrent_state_mut()?;
4561 let thread = state.get_mut(guest_thread.thread)?;
4562
4563 match &thread.state {
4566 GuestThreadState::NotStartedExplicit(_) => {}
4567 GuestThreadState::Suspended(_) => {
4568 log::trace!("resuming thread {thread_id:?} that was suspended");
4569 state.schedule_suspended_thread(
4570 guest_thread,
4571 self.runtime_instance(runtime_instance),
4572 priority,
4573 )?;
4574 return Ok(true);
4575 }
4576 _ => bail!(Trap::CannotResumeThread),
4577 }
4578 match mem::replace(&mut thread.state, GuestThreadState::Running) {
4579 GuestThreadState::NotStartedExplicit(start_func) => {
4580 log::trace!("starting thread {guest_thread:?}");
4581 let guest_call = WorkItem::GuestCall {
4582 instance: self.runtime_instance(runtime_instance),
4583 call: GuestCall {
4584 thread: guest_thread,
4585 kind: GuestCallKind::StartExplicit(Box::new(move |store| {
4586 start_func(store, guest_thread)
4587 })),
4588 },
4589 };
4590 state.push_work_item(guest_call, priority)?;
4591 }
4592 other => {
4593 thread.state = other;
4594 bail_bug!("thread state checked to be resumable above");
4595 }
4596 }
4597 Ok(true)
4598 }
4599
4600 fn add_guest_thread_to_instance_table(
4601 self,
4602 thread_id: TableId<GuestThread>,
4603 store: &mut StoreOpaque,
4604 runtime_instance: RuntimeComponentInstanceIndex,
4605 ) -> Result<u32> {
4606 let (state, counter) =
4607 store.instance_state_and_handle_counter(self.runtime_instance(runtime_instance));
4608 let guest_id = state
4609 .thread_handle_table()
4610 .guest_thread_insert(counter, thread_id.rep())?;
4611 store
4612 .concurrent_state_mut()?
4613 .get_mut(thread_id)?
4614 .instance_rep = Some(guest_id);
4615 Ok(guest_id)
4616 }
4617
4618 pub(crate) fn suspension_intrinsic(
4622 self,
4623 store: &mut StoreOpaque,
4624 caller: RuntimeComponentInstanceIndex,
4625 yielding: bool,
4626 to_thread: SuspensionTarget,
4627 ) -> Result<WaitResult> {
4628 let check_suspend = match to_thread {
4629 SuspensionTarget::Promote(thread) => {
4630 !self.resume_thread(store, caller, thread, ResumeThread::Promote)?
4631 }
4632 SuspensionTarget::Resume(thread) => {
4633 if !self.resume_thread(store, caller, thread, ResumeThread::Resume)? {
4634 bail_bug!(
4635 "`resume_thread` should only ever return false \
4636 when `ResumeThread::Promote` is passed to it"
4637 );
4638 }
4639 false
4640 }
4641 SuspensionTarget::None => true,
4642 };
4643
4644 if check_suspend && !store.switch_if_may_not_suspend(self.runtime_instance(caller))? {
4645 return if yielding {
4646 Ok(WaitResult::Completed)
4647 } else {
4648 Err(Trap::CannotBlockSyncTask.into())
4649 };
4650 }
4651
4652 let guest_thread = store.current_guest_thread()?;
4653
4654 let reason = if yielding {
4655 SuspendReason::Yielding {
4656 thread: guest_thread,
4657 }
4658 } else {
4659 SuspendReason::ExplicitlySuspending {
4660 thread: guest_thread,
4661 }
4662 };
4663
4664 store.suspend(reason)?;
4665
4666 Ok(WaitResult::Completed)
4667 }
4668
4669 fn waitable_check(
4671 self,
4672 store: &mut StoreOpaque,
4673 caller: RuntimeInstance,
4674 check: WaitableCheck,
4675 params: WaitableCheckParams,
4676 ) -> Result<u32> {
4677 let guest_thread = store.current_guest_thread()?;
4678
4679 log::trace!("waitable check for {guest_thread:?}; set {:?}", params.set);
4680
4681 match &check {
4684 WaitableCheck::Wait => {
4685 let set = params.set;
4686
4687 loop {
4692 let state = store.concurrent_state_mut()?;
4693 let task = state.get_mut(guest_thread.task)?;
4694 if !(task.event.is_none() || matches!(task.event, Some(Event::Cancelled)))
4695 || !state.get_mut(set)?.ready.is_empty()
4696 {
4697 break;
4698 }
4699
4700 store.switch_or_trap_if_may_not_suspend(caller)?;
4701
4702 store.suspend(SuspendReason::Waiting {
4703 set,
4704 thread: guest_thread,
4705 })?;
4706 }
4707 }
4708 WaitableCheck::Poll => {}
4709 }
4710
4711 log::trace!(
4712 "waitable check for {guest_thread:?}; set {:?}, part two",
4713 params.set
4714 );
4715
4716 let event = self.get_event(store, guest_thread.task, Some(params.set), false)?;
4718
4719 let (ordinal, handle, result) = match &check {
4720 WaitableCheck::Wait => {
4721 let (event, waitable) = match event {
4722 Some(p) => p,
4723 None => bail_bug!("event expected to be present"),
4724 };
4725 let handle = waitable.map(|(_, v)| v).unwrap_or(0);
4726 let (ordinal, result) = event.parts();
4727 (ordinal, handle, result)
4728 }
4729 WaitableCheck::Poll => {
4730 if let Some((event, waitable)) = event {
4731 let handle = waitable.map(|(_, v)| v).unwrap_or(0);
4732 let (ordinal, result) = event.parts();
4733 (ordinal, handle, result)
4734 } else {
4735 log::trace!(
4736 "no events ready to deliver via waitable-set.poll to {:?}; set {:?}",
4737 guest_thread.task,
4738 params.set
4739 );
4740 let (ordinal, result) = Event::None.parts();
4741 (ordinal, 0, result)
4742 }
4743 }
4744 };
4745 let ptr = crate::component::func::validate_inbounds_dynamic(
4746 &CanonicalAbiInfo::POINTER_PAIR,
4747 self.options_memory(store, params.options),
4748 &ValRaw::u32(params.payload),
4749 )?;
4750 let memory = self
4751 .options_memory_range_mut(store, params.options, ptr, 8)
4752 .unwrap();
4753 memory[0..4].copy_from_slice(&handle.to_le_bytes());
4754 memory[4..8].copy_from_slice(&result.to_le_bytes());
4755 Ok(ordinal)
4756 }
4757
4758 pub(crate) fn subtask_cancel(
4760 self,
4761 store: &mut StoreOpaque,
4762 caller_instance: RuntimeComponentInstanceIndex,
4763 async_: bool,
4764 task_id: u32,
4765 ) -> Result<u32> {
4766 let (rep, is_host) = store
4767 .instance_state(self.runtime_instance(caller_instance))
4768 .handle_table()
4769 .subtask_rep(task_id)?;
4770 let waitable = if is_host {
4771 Waitable::Host(TableId::<HostTask>::new(rep))
4772 } else {
4773 Waitable::Guest(TableId::<GuestTask>::new(rep))
4774 };
4775 let concurrent_state = store.concurrent_state_mut()?;
4776
4777 log::trace!("subtask_cancel {waitable:?} (handle {task_id}; async {async_})");
4778
4779 waitable.trap_if_in_waitable_set(concurrent_state)?;
4780
4781 let needs_block;
4782 if let Waitable::Host(host_task) = waitable {
4783 let state = &mut concurrent_state.get_mut(host_task)?.state;
4784 match state {
4785 HostTaskState::CalleeRunning(handle) => {
4792 handle.abort();
4793 *state = HostTaskState::CalleeCancelling;
4794 needs_block = true;
4795 }
4796
4797 HostTaskState::CalleeCancelling | HostTaskState::CalleeDone { cancelled: true } => {
4800 bail!(Trap::SubtaskCancelAfterTerminal);
4801 }
4802 HostTaskState::CalleeDone { cancelled: false } => {
4803 *state = HostTaskState::CalleeDone { cancelled: true };
4806 needs_block = false;
4807 }
4808
4809 HostTaskState::CalleeStarted | HostTaskState::CalleeFinished(_) => {
4812 bail_bug!("invalid states for host callee")
4813 }
4814 }
4815 } else {
4816 let guest_task = TableId::<GuestTask>::new(rep);
4817 let task = concurrent_state.get_mut(guest_task)?;
4818
4819 if task.cancel_requested {
4822 bail!(Trap::SubtaskCancelAfterTerminal);
4823 }
4824
4825 if !task.already_lowered_parameters() {
4826 store.cancel_guest_subtask_without_lowered_parameters(
4827 self.runtime_instance(caller_instance),
4828 guest_task,
4829 )?;
4830 return Ok(Status::StartCancelled as u32);
4831 } else if !task.returned_or_cancelled() {
4832 task.cancel_requested = true;
4839 task.event = Some(Event::Cancelled);
4840 let runtime_instance = task.instance;
4841 for thread in task.threads.clone() {
4842 let thread = QualifiedThreadId {
4843 task: guest_task,
4844 thread,
4845 };
4846 let concurrent_state = store.concurrent_state_mut()?;
4847 let thread_mut = concurrent_state.get_mut(thread.thread)?;
4848
4849 let yield_ = |store: &mut StoreOpaque| {
4850 let state = store.instance_state(runtime_instance).concurrent_state();
4855 let old_do_not_suspend = state.do_not_suspend;
4856 state.do_not_suspend = false;
4857
4858 let caller = store.current_guest_thread()?;
4859
4860 let state = store.concurrent_state_mut()?;
4865 let set = state.get_mut(caller.thread)?.sync_call_set;
4866 waitable.join(state, Some(set))?;
4867
4868 store.suspend(SuspendReason::YieldingToSubtask { thread: caller })?;
4869
4870 let state = store.concurrent_state_mut()?;
4871 waitable.join(state, None)?;
4872
4873 store
4874 .instance_state(runtime_instance)
4875 .concurrent_state()
4876 .do_not_suspend = old_do_not_suspend;
4877
4878 Ok::<(), crate::Error>(())
4879 };
4880
4881 match thread_mut.wake_on_cancel.take() {
4882 WakeOnCancel::Waiting(set) => {
4883 let instance = concurrent_state.take_callback_waiter(set, thread)?;
4885 let item = WorkItem::GuestCall {
4886 instance: runtime_instance,
4887 call: GuestCall {
4888 thread,
4889 kind: GuestCallKind::DeliverEvent {
4890 instance,
4891 set: Some(set),
4892 },
4893 },
4894 };
4895 concurrent_state.set_switch_item(item)?;
4896
4897 yield_(store)?;
4898
4899 break;
4900 }
4901 WakeOnCancel::Yielding => {
4902 if concurrent_state.promote_thread_work_item(thread)? {
4903 yield_(store)?;
4904 break;
4905 } else if store
4906 .instance_state(runtime_instance)
4907 .concurrent_state()
4908 .pending
4909 .contains_key(&thread)
4910 {
4911 store
4921 .concurrent_state_mut()?
4922 .get_mut(thread.thread)?
4923 .wake_on_cancel = WakeOnCancel::Yielding;
4924 } else {
4925 bail_bug!("thread with `WakeOnCancel::Yielding` not promotable");
4926 }
4927 }
4928 WakeOnCancel::None => {}
4929 }
4930 }
4931
4932 needs_block = !store
4935 .concurrent_state_mut()?
4936 .get_mut(guest_task)?
4937 .returned_or_cancelled()
4938 } else {
4939 needs_block = false;
4940 }
4941 };
4942
4943 if needs_block {
4947 if async_ {
4948 return Ok(BLOCKED);
4949 }
4950
4951 let old_next_switch_item = if is_host {
4961 Some(store.concurrent_state_mut()?.save_next_switch_item()?)
4962 } else {
4963 None
4964 };
4965
4966 store.wait_for_event(self.runtime_instance(caller_instance), waitable)?;
4969
4970 if let Some(item) = old_next_switch_item {
4971 let state = store.concurrent_state_mut()?;
4972 state.restore_next_switch_item(item)?;
4973 }
4974
4975 }
4977
4978 let event = waitable.take_event(store.concurrent_state_mut()?)?;
4979 if let Some(Event::Subtask {
4980 status: status @ (Status::Returned | Status::ReturnCancelled),
4981 }) = event
4982 {
4983 Ok(status as u32)
4984 } else {
4985 bail!(Trap::SubtaskCancelAfterTerminal);
4986 }
4987 }
4988}
4989
4990pub trait VMComponentAsyncStore {
4998 unsafe fn prepare_call(
5004 &mut self,
5005 instance: Instance,
5006 memory: *mut VMMemoryDefinition,
5007 start: NonNull<VMFuncRef>,
5008 return_: NonNull<VMFuncRef>,
5009 caller_instance: RuntimeComponentInstanceIndex,
5010 callee_instance: RuntimeComponentInstanceIndex,
5011 task_return_type: TypeTupleIndex,
5012 callee_async: bool,
5013 string_encoding: StringEncoding,
5014 result_count: u32,
5015 storage: *mut ValRaw,
5016 storage_len: usize,
5017 ) -> Result<()>;
5018
5019 unsafe fn start_call(
5022 &mut self,
5023 instance: Instance,
5024 callback: *mut VMFuncRef,
5025 post_return: *mut VMFuncRef,
5026 callee: NonNull<VMFuncRef>,
5027 param_count: u32,
5028 result_count: u32,
5029 flags: u32,
5030 storage: *mut MaybeUninit<ValRaw>,
5031 storage_len: usize,
5032 ) -> Result<()>;
5033
5034 fn future_write(
5036 &mut self,
5037 instance: Instance,
5038 caller: RuntimeComponentInstanceIndex,
5039 ty: TypeFutureTableIndex,
5040 options: OptionsIndex,
5041 future: u32,
5042 address: u32,
5043 ) -> Result<u32>;
5044
5045 fn future_read(
5047 &mut self,
5048 instance: Instance,
5049 caller: RuntimeComponentInstanceIndex,
5050 ty: TypeFutureTableIndex,
5051 options: OptionsIndex,
5052 future: u32,
5053 address: u32,
5054 ) -> Result<u32>;
5055
5056 fn future_drop_writable(
5058 &mut self,
5059 instance: Instance,
5060 ty: TypeFutureTableIndex,
5061 writer: u32,
5062 ) -> Result<()>;
5063
5064 fn stream_write(
5066 &mut self,
5067 instance: Instance,
5068 caller: RuntimeComponentInstanceIndex,
5069 ty: TypeStreamTableIndex,
5070 options: OptionsIndex,
5071 stream: u32,
5072 address: u32,
5073 count: u32,
5074 ) -> Result<u32>;
5075
5076 fn stream_read(
5078 &mut self,
5079 instance: Instance,
5080 caller: RuntimeComponentInstanceIndex,
5081 ty: TypeStreamTableIndex,
5082 options: OptionsIndex,
5083 stream: u32,
5084 address: u32,
5085 count: u32,
5086 ) -> Result<u32>;
5087
5088 fn flat_stream_write(
5091 &mut self,
5092 instance: Instance,
5093 caller: RuntimeComponentInstanceIndex,
5094 ty: TypeStreamTableIndex,
5095 options: OptionsIndex,
5096 payload_size: u32,
5097 payload_align: u32,
5098 stream: u32,
5099 address: u32,
5100 count: u32,
5101 ) -> Result<u32>;
5102
5103 fn flat_stream_read(
5106 &mut self,
5107 instance: Instance,
5108 caller: RuntimeComponentInstanceIndex,
5109 ty: TypeStreamTableIndex,
5110 options: OptionsIndex,
5111 payload_size: u32,
5112 payload_align: u32,
5113 stream: u32,
5114 address: u32,
5115 count: u32,
5116 ) -> Result<u32>;
5117
5118 fn stream_drop_writable(
5120 &mut self,
5121 instance: Instance,
5122 ty: TypeStreamTableIndex,
5123 writer: u32,
5124 ) -> Result<()>;
5125
5126 fn error_context_debug_message(
5128 &mut self,
5129 instance: Instance,
5130 ty: TypeComponentLocalErrorContextTableIndex,
5131 options: OptionsIndex,
5132 err_ctx_handle: u32,
5133 debug_msg_address: u32,
5134 ) -> Result<()>;
5135
5136 fn thread_new_indirect(
5138 &mut self,
5139 instance: Instance,
5140 caller: RuntimeComponentInstanceIndex,
5141 func_ty_idx: ModuleInternedTypeIndex,
5142 start_func_table_idx: RuntimeTableIndex,
5143 start_func_idx: u32,
5144 context: i32,
5145 ) -> Result<u32>;
5146}
5147
5148impl<T: 'static> VMComponentAsyncStore for StoreInner<T> {
5150 unsafe fn prepare_call(
5151 &mut self,
5152 instance: Instance,
5153 memory: *mut VMMemoryDefinition,
5154 start: NonNull<VMFuncRef>,
5155 return_: NonNull<VMFuncRef>,
5156 caller_instance: RuntimeComponentInstanceIndex,
5157 callee_instance: RuntimeComponentInstanceIndex,
5158 task_return_type: TypeTupleIndex,
5159 callee_async: bool,
5160 string_encoding: StringEncoding,
5161 result_count_or_max_if_async: u32,
5162 storage: *mut ValRaw,
5163 storage_len: usize,
5164 ) -> Result<()> {
5165 let params = unsafe { core::slice::from_raw_parts(storage, storage_len) }.to_vec();
5169
5170 unsafe {
5171 instance.prepare_call(
5172 StoreContextMut(self),
5173 start,
5174 return_,
5175 caller_instance,
5176 callee_instance,
5177 task_return_type,
5178 callee_async,
5179 memory,
5180 string_encoding,
5181 match result_count_or_max_if_async {
5182 PREPARE_ASYNC_NO_RESULT => CallerInfo::Async {
5183 params,
5184 has_result: false,
5185 },
5186 PREPARE_ASYNC_WITH_RESULT => CallerInfo::Async {
5187 params,
5188 has_result: true,
5189 },
5190 result_count => CallerInfo::Sync {
5191 params,
5192 result_count,
5193 },
5194 },
5195 )
5196 }
5197 }
5198
5199 unsafe fn start_call(
5200 &mut self,
5201 instance: Instance,
5202 callback: *mut VMFuncRef,
5203 post_return: *mut VMFuncRef,
5204 callee: NonNull<VMFuncRef>,
5205 param_count: u32,
5206 result_count: u32,
5207 flags: u32,
5208 storage: *mut MaybeUninit<ValRaw>,
5209 storage_len: usize,
5210 ) -> Result<()> {
5211 unsafe {
5212 instance.start_call(
5213 StoreContextMut(self),
5214 callback,
5215 post_return,
5216 callee,
5217 param_count,
5218 result_count,
5219 flags,
5220 core::slice::from_raw_parts_mut(storage, storage_len),
5224 )
5225 }
5226 }
5227
5228 fn future_write(
5229 &mut self,
5230 instance: Instance,
5231 caller: RuntimeComponentInstanceIndex,
5232 ty: TypeFutureTableIndex,
5233 options: OptionsIndex,
5234 future: u32,
5235 address: u32,
5236 ) -> Result<u32> {
5237 instance
5238 .guest_write(
5239 StoreContextMut(self),
5240 caller,
5241 TransmitIndex::Future(ty),
5242 options,
5243 None,
5244 future,
5245 address,
5246 1,
5247 )
5248 .map(|result| result.encode())
5249 }
5250
5251 fn future_read(
5252 &mut self,
5253 instance: Instance,
5254 caller: RuntimeComponentInstanceIndex,
5255 ty: TypeFutureTableIndex,
5256 options: OptionsIndex,
5257 future: u32,
5258 address: u32,
5259 ) -> Result<u32> {
5260 instance
5261 .guest_read(
5262 StoreContextMut(self),
5263 caller,
5264 TransmitIndex::Future(ty),
5265 options,
5266 None,
5267 future,
5268 address,
5269 1,
5270 )
5271 .map(|result| result.encode())
5272 }
5273
5274 fn stream_write(
5275 &mut self,
5276 instance: Instance,
5277 caller: RuntimeComponentInstanceIndex,
5278 ty: TypeStreamTableIndex,
5279 options: OptionsIndex,
5280 stream: u32,
5281 address: u32,
5282 count: u32,
5283 ) -> Result<u32> {
5284 instance
5285 .guest_write(
5286 StoreContextMut(self),
5287 caller,
5288 TransmitIndex::Stream(ty),
5289 options,
5290 None,
5291 stream,
5292 address,
5293 count,
5294 )
5295 .map(|result| result.encode())
5296 }
5297
5298 fn stream_read(
5299 &mut self,
5300 instance: Instance,
5301 caller: RuntimeComponentInstanceIndex,
5302 ty: TypeStreamTableIndex,
5303 options: OptionsIndex,
5304 stream: u32,
5305 address: u32,
5306 count: u32,
5307 ) -> Result<u32> {
5308 instance
5309 .guest_read(
5310 StoreContextMut(self),
5311 caller,
5312 TransmitIndex::Stream(ty),
5313 options,
5314 None,
5315 stream,
5316 address,
5317 count,
5318 )
5319 .map(|result| result.encode())
5320 }
5321
5322 fn future_drop_writable(
5323 &mut self,
5324 instance: Instance,
5325 ty: TypeFutureTableIndex,
5326 writer: u32,
5327 ) -> Result<()> {
5328 instance.guest_drop_writable(self, TransmitIndex::Future(ty), writer)
5329 }
5330
5331 fn flat_stream_write(
5332 &mut self,
5333 instance: Instance,
5334 caller: RuntimeComponentInstanceIndex,
5335 ty: TypeStreamTableIndex,
5336 options: OptionsIndex,
5337 payload_size: u32,
5338 payload_align: u32,
5339 stream: u32,
5340 address: u32,
5341 count: u32,
5342 ) -> Result<u32> {
5343 instance
5344 .guest_write(
5345 StoreContextMut(self),
5346 caller,
5347 TransmitIndex::Stream(ty),
5348 options,
5349 Some(FlatAbi {
5350 size: payload_size,
5351 align: payload_align,
5352 }),
5353 stream,
5354 address,
5355 count,
5356 )
5357 .map(|result| result.encode())
5358 }
5359
5360 fn flat_stream_read(
5361 &mut self,
5362 instance: Instance,
5363 caller: RuntimeComponentInstanceIndex,
5364 ty: TypeStreamTableIndex,
5365 options: OptionsIndex,
5366 payload_size: u32,
5367 payload_align: u32,
5368 stream: u32,
5369 address: u32,
5370 count: u32,
5371 ) -> Result<u32> {
5372 instance
5373 .guest_read(
5374 StoreContextMut(self),
5375 caller,
5376 TransmitIndex::Stream(ty),
5377 options,
5378 Some(FlatAbi {
5379 size: payload_size,
5380 align: payload_align,
5381 }),
5382 stream,
5383 address,
5384 count,
5385 )
5386 .map(|result| result.encode())
5387 }
5388
5389 fn stream_drop_writable(
5390 &mut self,
5391 instance: Instance,
5392 ty: TypeStreamTableIndex,
5393 writer: u32,
5394 ) -> Result<()> {
5395 instance.guest_drop_writable(self, TransmitIndex::Stream(ty), writer)
5396 }
5397
5398 fn error_context_debug_message(
5399 &mut self,
5400 instance: Instance,
5401 ty: TypeComponentLocalErrorContextTableIndex,
5402 options: OptionsIndex,
5403 err_ctx_handle: u32,
5404 debug_msg_address: u32,
5405 ) -> Result<()> {
5406 instance.error_context_debug_message(
5407 StoreContextMut(self),
5408 ty,
5409 options,
5410 err_ctx_handle,
5411 debug_msg_address,
5412 )
5413 }
5414
5415 fn thread_new_indirect(
5416 &mut self,
5417 instance: Instance,
5418 caller: RuntimeComponentInstanceIndex,
5419 func_ty_idx: ModuleInternedTypeIndex,
5420 start_func_table_idx: RuntimeTableIndex,
5421 start_func_idx: u32,
5422 context: i32,
5423 ) -> Result<u32> {
5424 instance.thread_new_indirect(
5425 StoreContextMut(self),
5426 caller,
5427 func_ty_idx,
5428 start_func_table_idx,
5429 start_func_idx,
5430 context,
5431 )
5432 }
5433}
5434
5435type HostTaskFuture = Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>;
5436
5437async fn run_with_host_task_set<F>(task: TableId<HostTask>, future: F) -> Result<F::Output>
5440where
5441 F: Future,
5442{
5443 let mut future = pin!(future);
5444 future::poll_fn(|cx| {
5445 let old_thread = match tls::get(|store| store.set_thread(task)) {
5446 Ok(thread) => thread,
5447 Err(error) => return Poll::Ready(Err(error)),
5448 };
5449 let result = future.as_mut().poll(cx);
5450 match tls::get(|store| store.set_thread(old_thread)) {
5451 Ok(_) => result.map(Ok),
5452 Err(error) => Poll::Ready(Err(error)),
5453 }
5454 })
5455 .await
5456}
5457
5458pub(crate) struct HostTask {
5462 common: WaitableCommon,
5463
5464 call_context: CallContext,
5467
5468 state: HostTaskState,
5469
5470 group: TaskGroupId,
5471}
5472
5473enum HostTaskState {
5474 CalleeStarted,
5479
5480 CalleeRunning(JoinHandle),
5485
5486 CalleeCancelling,
5490
5491 CalleeFinished(LiftedResult),
5495
5496 CalleeDone { cancelled: bool },
5499}
5500
5501impl HostTask {
5502 fn new(
5503 concurrent_state: &mut ConcurrentState,
5504 state: HostTaskState,
5505 caller: QualifiedThreadId,
5506 ) -> Result<Self> {
5507 let group = concurrent_state.get_mut(caller.task)?.group;
5508 concurrent_state.increment_group_ref_count(group)?;
5509
5510 Ok(Self {
5511 common: WaitableCommon::default(),
5512 call_context: CallContext::default(),
5513 state,
5514 group,
5515 })
5516 }
5517}
5518
5519impl TableDebug for HostTask {
5520 fn type_name() -> &'static str {
5521 "HostTask"
5522 }
5523}
5524
5525type CallbackFn = Box<dyn Fn(&mut dyn VMStore, Event, u32) -> Result<u32> + Send + Sync + 'static>;
5526
5527enum Caller {
5529 Host {
5531 tx: Option<oneshot::Sender<LiftedResult>>,
5533 caller: Option<TableId<HostTask>>,
5537 },
5538 Guest {
5540 thread: QualifiedThreadId,
5542 },
5543}
5544
5545struct LiftResult {
5548 lift: RawLift,
5549 ty: TypeTupleIndex,
5550 memory: Option<SendSyncPtr<VMMemoryDefinition>>,
5551 string_encoding: StringEncoding,
5552}
5553
5554#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
5559pub(crate) struct QualifiedThreadId {
5560 task: TableId<GuestTask>,
5561 thread: TableId<GuestThread>,
5562}
5563
5564impl QualifiedThreadId {
5565 fn qualify(
5566 state: &mut ConcurrentState,
5567 thread: TableId<GuestThread>,
5568 ) -> Result<QualifiedThreadId> {
5569 Ok(QualifiedThreadId {
5570 task: state.get_mut(thread)?.parent_task,
5571 thread,
5572 })
5573 }
5574}
5575
5576impl fmt::Debug for QualifiedThreadId {
5577 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5578 f.debug_tuple("QualifiedThreadId")
5579 .field(&self.task.rep())
5580 .field(&self.thread.rep())
5581 .finish()
5582 }
5583}
5584
5585enum GuestThreadState {
5586 NotStartedImplicit,
5587 NotStartedExplicit(
5588 Box<dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync>,
5589 ),
5590 Running,
5591 Suspended(StoreFiber<'static>),
5592 Ready {
5593 fiber: StoreFiber<'static>,
5594 },
5595 Completed,
5596}
5597
5598impl GuestThreadState {
5599 fn check_no_fiber(&self) -> Result<()> {
5600 match self {
5601 Self::Suspended(_) | Self::Ready { .. } => bail_bug!("thread already owns a fiber"),
5602 Self::NotStartedImplicit
5603 | Self::NotStartedExplicit(_)
5604 | Self::Running
5605 | Self::Completed => Ok(()),
5606 }
5607 }
5608}
5609
5610impl fmt::Debug for GuestThreadState {
5611 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5612 match self {
5613 Self::NotStartedImplicit => f.debug_tuple("NotStartedImplicit").finish(),
5614 Self::NotStartedExplicit(_) => f.debug_tuple("NotStartedExplicit").finish(),
5615 Self::Running => f.debug_tuple("Running").finish(),
5616 Self::Suspended(_) => f.debug_tuple("Suspended").finish(),
5617 Self::Ready { .. } => f.debug_struct("Ready").finish(),
5618 Self::Completed => f.debug_tuple("Completed").finish(),
5619 }
5620 }
5621}
5622
5623#[derive(Copy, Clone, PartialEq, Eq, Debug)]
5624enum WakeOnCancel {
5625 None,
5626 Waiting(TableId<WaitableSet>),
5627 Yielding,
5628}
5629
5630impl WakeOnCancel {
5631 fn is_none(self) -> bool {
5632 matches!(self, WakeOnCancel::None)
5633 }
5634
5635 fn replace(&mut self, other: WakeOnCancel) -> Self {
5636 let old = *self;
5637 *self = other;
5638 old
5639 }
5640
5641 fn take(&mut self) -> Self {
5642 self.replace(WakeOnCancel::None)
5643 }
5644}
5645
5646pub struct GuestThread {
5647 context: [u32; NUM_COMPONENT_CONTEXT_SLOTS],
5650 parent_task: TableId<GuestTask>,
5652 wake_on_cancel: WakeOnCancel,
5655 state: GuestThreadState,
5657 instance_rep: Option<u32>,
5660 sync_call_set: TableId<WaitableSet>,
5662 old_do_not_suspend: Option<bool>,
5665}
5666
5667impl GuestThread {
5668 fn from_instance(
5671 state: Pin<&mut ComponentInstance>,
5672 caller_instance: RuntimeComponentInstanceIndex,
5673 guest_thread: u32,
5674 ) -> Result<TableId<Self>> {
5675 let rep = state.instance_states().0[caller_instance]
5676 .thread_handle_table()
5677 .guest_thread_rep(guest_thread)?;
5678 Ok(TableId::new(rep))
5679 }
5680
5681 fn new_implicit(state: &mut ConcurrentState, parent_task: TableId<GuestTask>) -> Result<Self> {
5682 let sync_call_set = state.push(WaitableSet {
5683 is_sync_call_set: true,
5684 ..WaitableSet::default()
5685 })?;
5686 Ok(Self {
5687 context: [0; NUM_COMPONENT_CONTEXT_SLOTS],
5688 parent_task,
5689 wake_on_cancel: WakeOnCancel::None,
5690 state: GuestThreadState::NotStartedImplicit,
5691 instance_rep: None,
5692 sync_call_set,
5693 old_do_not_suspend: None,
5694 })
5695 }
5696
5697 fn new_explicit(
5698 state: &mut ConcurrentState,
5699 parent_task: TableId<GuestTask>,
5700 start_func: Box<
5701 dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync,
5702 >,
5703 ) -> Result<Self> {
5704 state.increment_task_ref_count(parent_task)?;
5705 let sync_call_set = state.push(WaitableSet {
5706 is_sync_call_set: true,
5707 ..WaitableSet::default()
5708 })?;
5709 Ok(Self {
5710 context: [0; NUM_COMPONENT_CONTEXT_SLOTS],
5711 parent_task,
5712 wake_on_cancel: WakeOnCancel::None,
5713 state: GuestThreadState::NotStartedExplicit(start_func),
5714 instance_rep: None,
5715 sync_call_set,
5716 old_do_not_suspend: None,
5717 })
5718 }
5719}
5720
5721impl TableDebug for GuestThread {
5722 fn type_name() -> &'static str {
5723 "GuestThread"
5724 }
5725}
5726
5727enum SyncResult {
5728 NotProduced,
5729 Produced(Option<ValRaw>),
5730 Taken,
5731}
5732
5733impl SyncResult {
5734 fn take(&mut self) -> Result<Option<Option<ValRaw>>> {
5735 Ok(match mem::replace(self, SyncResult::Taken) {
5736 SyncResult::NotProduced => None,
5737 SyncResult::Produced(val) => Some(val),
5738 SyncResult::Taken => {
5739 bail_bug!("attempted to take a synchronous result that was already taken")
5740 }
5741 })
5742 }
5743}
5744
5745pub(crate) struct GuestTask {
5747 common: WaitableCommon,
5749 lower_params: Option<RawLower>,
5751 lift_result: Option<LiftResult>,
5753 result: Option<LiftedResult>,
5756 callback: Option<CallbackFn>,
5759 caller: Caller,
5761 call_context: CallContext,
5766 sync_result: SyncResult,
5769 cancel_request_delivered: bool,
5773 cancel_requested: bool,
5778 starting_sent: bool,
5781 instance: RuntimeInstance,
5788 event: Option<Event>,
5790 exited: bool,
5792 threads: HashSet<TableId<GuestThread>>,
5794 async_typed: bool,
5797 async_lifted: bool,
5800 decremented_interesting_task_count: bool,
5803 group: TaskGroupId,
5805 ref_count: usize,
5810}
5811
5812impl GuestTask {
5813 fn already_lowered_parameters(&self) -> bool {
5814 self.lower_params.is_none()
5816 }
5817
5818 fn returned_or_cancelled(&self) -> bool {
5819 self.lift_result.is_none()
5821 }
5822
5823 fn new(
5824 state: &mut ConcurrentState,
5825 lower_params: RawLower,
5826 lift_result: LiftResult,
5827 caller: Caller,
5828 callback: Option<CallbackFn>,
5829 instance: RuntimeInstance,
5830 async_typed: bool,
5831 async_lifted: bool,
5832 ) -> Result<QualifiedThreadId> {
5833 let group = match caller {
5834 Caller::Guest { thread } => {
5835 let group = state.get_mut(thread.task)?.group;
5836 state.increment_group_ref_count(group)?;
5837 group
5838 }
5839 Caller::Host { .. } => state.make_task_group()?,
5840 };
5841
5842 let task = state.push(Self {
5843 common: WaitableCommon::default(),
5844 lower_params: Some(lower_params),
5845 lift_result: Some(lift_result),
5846 result: None,
5847 callback,
5848 caller,
5849 call_context: CallContext::default(),
5850 sync_result: SyncResult::NotProduced,
5851 cancel_request_delivered: false,
5852 cancel_requested: false,
5853 starting_sent: false,
5854 instance,
5855 event: None,
5856 exited: false,
5857 threads: HashSet::new(),
5858 async_typed,
5859 async_lifted,
5860 decremented_interesting_task_count: false,
5861 group,
5862 ref_count: 2,
5865 })?;
5866 let new_thread = GuestThread::new_implicit(state, task)?;
5867 let thread = state.push(new_thread)?;
5868 state.get_mut(task)?.threads.insert(thread);
5869 state.interesting_tasks += 1;
5870 let thread = QualifiedThreadId { task, thread };
5871 log::trace!("new implicit thread {thread:?} for instance {instance:?}");
5872 Ok(thread)
5873 }
5874}
5875
5876impl TableDebug for GuestTask {
5877 fn type_name() -> &'static str {
5878 "GuestTask"
5879 }
5880}
5881
5882#[derive(Default)]
5884struct WaitableCommon {
5885 event: Option<Event>,
5887 set: Option<TableId<WaitableSet>>,
5889 handle: Option<u32>,
5891}
5892
5893#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
5895enum Waitable {
5896 Host(TableId<HostTask>),
5898 Guest(TableId<GuestTask>),
5900 Transmit(TableId<TransmitHandle>),
5902}
5903
5904impl Waitable {
5905 fn from_instance(
5908 state: Pin<&mut ComponentInstance>,
5909 caller_instance: RuntimeComponentInstanceIndex,
5910 waitable: u32,
5911 ) -> Result<Self> {
5912 use crate::runtime::vm::component::Waitable;
5913
5914 let (waitable, kind) = state.instance_states().0[caller_instance]
5915 .handle_table()
5916 .waitable_rep(waitable)?;
5917
5918 Ok(match kind {
5919 Waitable::Subtask { is_host: true } => Self::Host(TableId::new(waitable)),
5920 Waitable::Subtask { is_host: false } => Self::Guest(TableId::new(waitable)),
5921 Waitable::Stream | Waitable::Future => Self::Transmit(TableId::new(waitable)),
5922 })
5923 }
5924
5925 fn rep(&self) -> u32 {
5927 match self {
5928 Self::Host(id) => id.rep(),
5929 Self::Guest(id) => id.rep(),
5930 Self::Transmit(id) => id.rep(),
5931 }
5932 }
5933
5934 fn join(&self, state: &mut ConcurrentState, set: Option<TableId<WaitableSet>>) -> Result<()> {
5938 log::trace!("waitable {self:?} join set {set:?}");
5939
5940 let old = mem::replace(&mut self.common(state)?.set, set);
5941
5942 if let Some(old) = old {
5943 match *self {
5944 Waitable::Host(id) => state.remove_child(id, old),
5945 Waitable::Guest(id) => state.remove_child(id, old),
5946 Waitable::Transmit(id) => state.remove_child(id, old),
5947 }?;
5948
5949 state.get_mut(old)?.ready.remove(self);
5950 }
5951
5952 if let Some(set) = set {
5953 match *self {
5954 Waitable::Host(id) => state.add_child(id, set),
5955 Waitable::Guest(id) => state.add_child(id, set),
5956 Waitable::Transmit(id) => state.add_child(id, set),
5957 }?;
5958
5959 if self.common(state)?.event.is_some() {
5960 self.mark_ready(state)?;
5961 }
5962 }
5963
5964 Ok(())
5965 }
5966
5967 fn common<'a>(&self, state: &'a mut ConcurrentState) -> Result<&'a mut WaitableCommon> {
5969 Ok(match self {
5970 Self::Host(id) => &mut state.get_mut(*id)?.common,
5971 Self::Guest(id) => &mut state.get_mut(*id)?.common,
5972 Self::Transmit(id) => &mut state.get_mut(*id)?.common,
5973 })
5974 }
5975
5976 fn trap_if_in_waitable_set(&self, state: &mut ConcurrentState) -> Result<()> {
5982 if self.common(state)?.set.is_some() {
5983 bail!(Trap::WaitableSyncAndAsync);
5984 }
5985 Ok(())
5986 }
5987
5988 fn trap_if_has_sync_waiter(&self, state: &mut ConcurrentState) -> Result<()> {
5994 if let Some(set) = self.common(state)?.set
5995 && state.get_mut(set)?.is_sync_call_set
5996 {
5997 bail!(Trap::WaitableSyncAndAsync);
5998 }
5999 Ok(())
6000 }
6001
6002 fn set_event(&self, state: &mut ConcurrentState, event: Option<Event>) -> Result<()> {
6006 log::trace!("set event for {self:?}: {event:?}");
6007 self.common(state)?.event = event;
6008 self.mark_ready(state)
6009 }
6010
6011 fn take_event(&self, state: &mut ConcurrentState) -> Result<Option<Event>> {
6013 let common = self.common(state)?;
6014 let event = common.event.take();
6015 if let Some(set) = self.common(state)?.set {
6016 state.get_mut(set)?.ready.remove(self);
6017 }
6018
6019 Ok(event)
6020 }
6021
6022 fn mark_ready(&self, state: &mut ConcurrentState) -> Result<()> {
6026 if let Some(set) = self.common(state)?.set {
6027 state.get_mut(set)?.ready.insert(*self);
6028 state.wake_waiter(set)?;
6029 }
6030 Ok(())
6031 }
6032
6033 fn delete_from(&self, state: &mut ConcurrentState) -> Result<()> {
6036 match self {
6037 Self::Host(task) => state.delete_host_task(*task),
6038 Self::Guest(task) => state.decrement_task_ref_count(*task),
6039 Self::Transmit(task) => Ok(state.delete(*task).map(drop)?),
6040 }
6041 }
6042}
6043
6044impl fmt::Debug for Waitable {
6045 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6046 match self {
6047 Self::Host(id) => write!(f, "{id:?}"),
6048 Self::Guest(id) => write!(f, "{id:?}"),
6049 Self::Transmit(id) => write!(f, "{id:?}"),
6050 }
6051 }
6052}
6053
6054#[derive(Default)]
6056struct WaitableSet {
6057 ready: BTreeSet<Waitable>,
6059 waiting: BTreeMap<QualifiedThreadId, WaitMode>,
6061 num_waiting: usize,
6064 is_sync_call_set: bool,
6067}
6068
6069impl WaitableSet {
6070 fn stop_waiting(&mut self) -> Result<()> {
6072 self.num_waiting = match self.num_waiting.checked_sub(1) {
6073 Some(n) => n,
6074 None => bail_bug!("waiter not accounted for in waitable set"),
6075 };
6076 Ok(())
6077 }
6078}
6079
6080impl TableDebug for WaitableSet {
6081 fn type_name() -> &'static str {
6082 "WaitableSet"
6083 }
6084}
6085
6086type RawLower =
6088 Box<dyn FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync>;
6089
6090type RawLift = Box<
6092 dyn FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
6093>;
6094
6095type LiftedResult = Box<dyn Any + Send + Sync>;
6099
6100struct DummyResult;
6103
6104#[derive(Default)]
6106pub struct ConcurrentInstanceState {
6107 backpressure: u16,
6109 do_not_enter: bool,
6111 do_not_suspend: bool,
6114 pending: BTreeMap<QualifiedThreadId, GuestCallKind>,
6117 pending_start_count: usize,
6120}
6121
6122impl ConcurrentInstanceState {
6123 pub fn pending_is_empty(&self) -> bool {
6124 self.pending.is_empty()
6125 }
6126}
6127
6128#[derive(Debug, Copy, Clone)]
6129pub(crate) enum CurrentThread {
6130 Guest(QualifiedThreadId),
6133 Host(TableId<HostTask>),
6135 DeferredHost(QualifiedThreadId),
6138 None,
6141}
6142
6143impl CurrentThread {
6144 fn guest(&self) -> Option<&QualifiedThreadId> {
6145 match self {
6146 Self::Guest(id) => Some(id),
6147 _ => None,
6148 }
6149 }
6150
6151 fn guest_task(&self) -> Option<TableId<GuestTask>> {
6152 match self {
6153 Self::Guest(id) => Some(id.task),
6154 _ => None,
6155 }
6156 }
6157
6158 fn is_none(&self) -> bool {
6159 matches!(self, Self::None)
6160 }
6161}
6162
6163impl From<QualifiedThreadId> for CurrentThread {
6164 fn from(id: QualifiedThreadId) -> Self {
6165 Self::Guest(id)
6166 }
6167}
6168
6169impl From<TableId<HostTask>> for CurrentThread {
6170 fn from(id: TableId<HostTask>) -> Self {
6171 Self::Host(id)
6172 }
6173}
6174
6175enum Priority {
6176 Switch,
6177 #[expect(
6178 dead_code,
6179 reason = "Here for completeness and in case we need it later"
6180 )]
6181 High,
6182 Low,
6183}
6184
6185pub struct ConcurrentState {
6187 unforced_current_thread: CurrentThread,
6193
6194 deferred_host_call_context: Option<CallContext>,
6200
6201 futures: AlwaysMut<Option<FuturesUnordered<HostTaskFuture>>>,
6206 table: AlwaysMut<ResourceTable>,
6208 switch_item: Option<WorkItem>,
6216 next_switch_item: Option<WorkItem>,
6222 high_priority: VecDeque<WorkItem>,
6224 low_priority: VecDeque<WorkItem>,
6226 suspend_reason: Option<SuspendReason>,
6230 worker: Option<StoreFiber<'static>>,
6234 worker_item: Option<WorkerItem>,
6236
6237 global_error_context_ref_counts:
6250 BTreeMap<TypeComponentGlobalErrorContextTableIndex, GlobalErrorContextRefCount>,
6251
6252 interesting_tasks: usize,
6265
6266 interesting_tasks_empty_waker: Option<Waker>,
6270
6271 ready_for_concurrent_call_waker: Option<Waker>,
6276
6277 event_loop_running: bool,
6279
6280 saved_next_switch_items: Vec<Option<WorkItem>>,
6283
6284 #[cfg(feature = "task-group-hook")]
6286 task_group_hook: Option<Box<dyn TaskGroupHook>>,
6287}
6288
6289impl Default for ConcurrentState {
6290 fn default() -> Self {
6291 Self {
6292 unforced_current_thread: CurrentThread::None,
6293 deferred_host_call_context: None,
6294 table: AlwaysMut::new(ResourceTable::new()),
6295 futures: AlwaysMut::new(Some(FuturesUnordered::new())),
6296 switch_item: None,
6297 next_switch_item: None,
6298 high_priority: VecDeque::new(),
6299 low_priority: VecDeque::new(),
6300 suspend_reason: None,
6301 worker: None,
6302 worker_item: None,
6303 global_error_context_ref_counts: BTreeMap::new(),
6304 interesting_tasks: 0,
6305 interesting_tasks_empty_waker: None,
6306 ready_for_concurrent_call_waker: None,
6307 event_loop_running: false,
6308 saved_next_switch_items: Vec::new(),
6309 #[cfg(feature = "task-group-hook")]
6310 task_group_hook: None,
6311 }
6312 }
6313}
6314
6315impl ConcurrentState {
6316 pub(crate) fn take_fibers_and_futures(
6333 &mut self,
6334 fibers: &mut Vec<StoreFiber<'static>>,
6335 futures: &mut Vec<FuturesUnordered<HostTaskFuture>>,
6336 ) {
6337 let ConcurrentState {
6338 table,
6339 worker,
6340 switch_item,
6341 next_switch_item,
6342 high_priority,
6343 low_priority,
6344 saved_next_switch_items,
6345 futures: pending_futures,
6346 worker_item: _,
6347 unforced_current_thread: _,
6348 deferred_host_call_context: _,
6349 suspend_reason: _,
6350 global_error_context_ref_counts: _,
6351 interesting_tasks: _,
6352 interesting_tasks_empty_waker: _,
6353 ready_for_concurrent_call_waker: _,
6354 event_loop_running: _,
6355 #[cfg(feature = "task-group-hook")]
6356 task_group_hook: _,
6357 } = self;
6358
6359 let mut items = Vec::new();
6360 for (_, entry) in table.get_mut().iter_mut() {
6361 let entry = entry.into_entry_mut();
6362 if let Some(set) = entry.downcast_mut::<WaitableSet>() {
6363 for mode in mem::take(&mut set.waiting).into_values() {
6364 match mode {
6365 WaitMode::Fiber(fiber) => {
6366 fibers.push(fiber);
6367 }
6368 WaitMode::Callback(_) => {}
6369 }
6370 }
6371 } else if let Some(thread) = entry.downcast_mut::<GuestThread>() {
6372 match mem::replace(&mut thread.state, GuestThreadState::Completed) {
6373 GuestThreadState::Suspended(fiber) | GuestThreadState::Ready { fiber } => {
6374 fibers.push(fiber);
6375 }
6376 GuestThreadState::NotStartedImplicit
6377 | GuestThreadState::NotStartedExplicit(_)
6378 | GuestThreadState::Running
6379 | GuestThreadState::Completed => {}
6380 }
6381 } else if let Some(item) = entry.downcast_mut::<Option<WorkItem>>() {
6382 if let Some(item) = item.take() {
6383 items.push(item);
6384 }
6385 }
6386 }
6387
6388 if let Some(fiber) = worker.take() {
6389 fibers.push(fiber);
6390 }
6391
6392 let mut handle_item = |item| match item {
6393 WorkItem::ResumeFiber { fiber, .. } => {
6394 fibers.push(fiber);
6395 }
6396 WorkItem::PushFuture(future) => {
6397 pending_futures
6398 .get_mut()
6399 .as_mut()
6400 .unwrap()
6401 .push(future.into_inner());
6402 }
6403 WorkItem::ResumeThread { .. }
6404 | WorkItem::GuestCall { .. }
6405 | WorkItem::WorkerFunction(_) => {}
6406 };
6407
6408 for item in items {
6409 handle_item(item);
6410 }
6411 if let Some(item) = switch_item.take() {
6412 handle_item(item);
6413 }
6414 if let Some(item) = next_switch_item.take() {
6415 handle_item(item);
6416 }
6417 for item in mem::take(high_priority) {
6418 handle_item(item);
6419 }
6420 for item in mem::take(low_priority) {
6421 handle_item(item);
6422 }
6423 for item in mem::take(saved_next_switch_items)
6424 .into_iter()
6425 .filter_map(|v| v)
6426 {
6427 handle_item(item);
6428 }
6429
6430 if let Some(them) = pending_futures.get_mut().take() {
6431 futures.push(them);
6432 }
6433 }
6434
6435 #[cfg(feature = "gc")]
6436 pub(crate) fn trace_fiber_roots(
6437 &mut self,
6438 modules: &ModuleRegistry,
6439 unwind: &dyn Unwind,
6440 gc_roots_list: &mut GcRootsList,
6441 ) {
6442 let ConcurrentState {
6443 table,
6444 worker,
6445 switch_item,
6446 next_switch_item,
6447 high_priority,
6448 low_priority,
6449 saved_next_switch_items,
6450
6451 futures: _,
6455
6456 worker_item: _,
6458 unforced_current_thread: _,
6459 deferred_host_call_context: _,
6460 suspend_reason: _,
6461 global_error_context_ref_counts: _,
6462 interesting_tasks: _,
6463 interesting_tasks_empty_waker: _,
6464 ready_for_concurrent_call_waker: _,
6465 event_loop_running: _,
6466 #[cfg(feature = "task-group-hook")]
6467 task_group_hook: _,
6468 } = self;
6469
6470 for (_, entry) in table.get_mut().iter_mut() {
6471 let entry = entry.into_entry_mut();
6472 if let Some(set) = entry.downcast_mut::<WaitableSet>() {
6473 for mode in set.waiting.values_mut() {
6474 match mode {
6475 WaitMode::Fiber(fiber) => {
6476 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6477 }
6478 WaitMode::Callback(_) => {}
6479 }
6480 }
6481 } else if let Some(thread) = entry.downcast_mut::<GuestThread>() {
6482 match &mut thread.state {
6483 GuestThreadState::Suspended(fiber) | GuestThreadState::Ready { fiber } => {
6484 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6485 }
6486 GuestThreadState::NotStartedImplicit
6487 | GuestThreadState::NotStartedExplicit(_)
6488 | GuestThreadState::Running
6489 | GuestThreadState::Completed => {}
6490 }
6491 } else if let Some(Some(WorkItem::ResumeFiber { fiber, .. })) =
6492 entry.downcast_mut::<Option<WorkItem>>()
6493 {
6494 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6495 }
6496 }
6497
6498 if let Some(fiber) = worker {
6499 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6500 }
6501
6502 let mut handle_item = |item: &mut WorkItem| match item {
6503 WorkItem::ResumeFiber { fiber, .. } => {
6504 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6505 }
6506 WorkItem::PushFuture(_future) => {
6507 }
6510 WorkItem::ResumeThread { .. }
6511 | WorkItem::GuestCall { .. }
6512 | WorkItem::WorkerFunction(_) => {}
6513 };
6514
6515 if let Some(item) = switch_item {
6516 handle_item(item);
6517 }
6518 if let Some(item) = next_switch_item {
6519 handle_item(item);
6520 }
6521 for item in high_priority {
6522 handle_item(item);
6523 }
6524 for item in low_priority {
6525 handle_item(item);
6526 }
6527 for item in saved_next_switch_items
6528 .iter_mut()
6529 .filter_map(|v| v.as_mut())
6530 {
6531 handle_item(item);
6532 }
6533 }
6534
6535 fn schedule_suspended_thread(
6536 &mut self,
6537 thread: QualifiedThreadId,
6538 instance: RuntimeInstance,
6539 priority: Priority,
6540 ) -> Result<()> {
6541 if matches!(priority, Priority::Switch) && self.switch_item.is_some() {
6543 bail_bug!("switch item already set");
6544 }
6545 let slot = &mut self.get_mut(thread.thread)?.state;
6546 if !matches!(slot, GuestThreadState::Suspended(_)) {
6547 bail!(Trap::CannotResumeThread);
6548 }
6549 let GuestThreadState::Suspended(fiber) = mem::replace(slot, GuestThreadState::Running)
6550 else {
6551 unreachable!()
6552 };
6553 let item = WorkItem::ResumeFiber {
6554 instance,
6555 thread,
6556 fiber,
6557 };
6558 match priority {
6559 Priority::Switch => self.switch_item = Some(item),
6560 Priority::High => self.push_high_priority(item),
6561 Priority::Low => self.push_low_priority(item),
6562 }
6563 Ok(())
6564 }
6565
6566 fn set_thread_running(&mut self, thread: TableId<GuestThread>) -> Result<()> {
6567 let slot = &mut self.get_mut(thread)?.state;
6568 slot.check_no_fiber()?;
6569 *slot = GuestThreadState::Running;
6570 Ok(())
6571 }
6572
6573 fn save_next_switch_item(&mut self) -> Result<TableId<Option<WorkItem>>> {
6574 let saved = self.push(None::<WorkItem>)?;
6577 let slot = self.table.get_mut().get_mut(&Resource::from(saved))?;
6578 *slot = self.next_switch_item.take();
6579 Ok(saved)
6580 }
6581
6582 fn restore_next_switch_item(&mut self, saved: TableId<Option<WorkItem>>) -> Result<()> {
6583 if self.next_switch_item.is_some() {
6584 bail_bug!("next switch item already set when restoring");
6585 }
6586 self.next_switch_item = self.delete(saved)?;
6587 Ok(())
6588 }
6589
6590 fn take_callback_waiter(
6591 &mut self,
6592 set: TableId<WaitableSet>,
6593 thread: QualifiedThreadId,
6594 ) -> Result<Instance> {
6595 let waiting = &mut self.get_mut(set)?.waiting;
6596 let instance = match waiting.get(&thread) {
6597 Some(WaitMode::Callback(instance)) => *instance,
6598 other => bail_bug!("expected `Some(WaitMode::Callback(_))`; got `{other:?}`"),
6599 };
6600 waiting.remove(&thread);
6601 Ok(instance)
6602 }
6603
6604 fn push<V: Send + Sync + 'static>(
6605 &mut self,
6606 value: V,
6607 ) -> Result<TableId<V>, ResourceTableError> {
6608 self.table.get_mut().push(value).map(TableId::from)
6609 }
6610
6611 fn get_mut<V: 'static>(&mut self, id: TableId<V>) -> Result<&mut V, ResourceTableError> {
6612 self.table.get_mut().get_mut(&Resource::from(id))
6613 }
6614
6615 pub fn add_child<T: 'static, U: 'static>(
6616 &mut self,
6617 child: TableId<T>,
6618 parent: TableId<U>,
6619 ) -> Result<(), ResourceTableError> {
6620 self.table
6621 .get_mut()
6622 .add_child(Resource::from(child), Resource::from(parent))
6623 }
6624
6625 pub fn remove_child<T: 'static, U: 'static>(
6626 &mut self,
6627 child: TableId<T>,
6628 parent: TableId<U>,
6629 ) -> Result<(), ResourceTableError> {
6630 self.table
6631 .get_mut()
6632 .remove_child(Resource::from(child), Resource::from(parent))
6633 }
6634
6635 fn delete<V: 'static>(&mut self, id: TableId<V>) -> Result<V, ResourceTableError> {
6636 self.table.get_mut().delete(Resource::from(id))
6637 }
6638
6639 fn push_future(&mut self, future: HostTaskFuture) {
6640 self.push_high_priority(WorkItem::PushFuture(AlwaysMut::new(future)));
6647 }
6648
6649 fn set_switch_item(&mut self, item: WorkItem) -> Result<()> {
6650 if self.switch_item.is_some() {
6651 self.push_high_priority(item);
6654 bail_bug!("switch item already set");
6655 }
6656
6657 self.switch_item = Some(item);
6658 log::trace!("set switch item: {:?}", self.switch_item.as_ref().unwrap());
6659
6660 Ok(())
6661 }
6662
6663 fn take_next_switch_item(&mut self) -> Result<()> {
6664 if let Some(item) = self.next_switch_item.take() {
6665 self.set_switch_item(item)?;
6666 }
6667 Ok(())
6668 }
6669
6670 fn wake_waiter(&mut self, set: TableId<WaitableSet>) -> Result<()> {
6673 let Some((&thread, _)) = self.get_mut(set)?.waiting.first_key_value() else {
6676 return Ok(());
6677 };
6678 let wake_on_cancel = self.get_mut(thread.thread)?.wake_on_cancel;
6679 if wake_on_cancel != WakeOnCancel::None && wake_on_cancel != WakeOnCancel::Waiting(set) {
6680 bail_bug!("thread {thread:?} has unexpected wake_on_cancel value {wake_on_cancel:?}");
6681 }
6682 let instance = self.get_mut(thread.task)?.instance;
6683 self.get_mut(thread.thread)?.wake_on_cancel.take();
6684 let (_, mode) = self.get_mut(set)?.waiting.pop_first().unwrap();
6685
6686 let item = match mode {
6687 WaitMode::Fiber(fiber) => WorkItem::ResumeFiber {
6688 instance,
6689 thread,
6690 fiber,
6691 },
6692 WaitMode::Callback(callback_instance) => WorkItem::GuestCall {
6693 instance,
6694 call: GuestCall {
6695 thread,
6696 kind: GuestCallKind::DeliverEvent {
6697 instance: callback_instance,
6698 set: Some(set),
6699 },
6700 },
6701 },
6702 };
6703 self.push_high_priority(item);
6704 Ok(())
6705 }
6706
6707 fn push_high_priority(&mut self, item: WorkItem) {
6708 self.high_priority.push_front(item);
6709 log::trace!(
6710 "push high priority: {:?}",
6711 self.high_priority.front().unwrap()
6712 );
6713 }
6714
6715 fn push_low_priority(&mut self, item: WorkItem) {
6716 self.low_priority.push_front(item);
6717 log::trace!(
6718 "push low priority: {:?}",
6719 self.low_priority.front().unwrap()
6720 );
6721 }
6722
6723 fn push_work_item(&mut self, item: WorkItem, priority: Priority) -> Result<()> {
6724 match priority {
6725 Priority::Switch => self.set_switch_item(item)?,
6726 Priority::High => self.push_high_priority(item),
6727 Priority::Low => self.push_low_priority(item),
6728 }
6729
6730 Ok(())
6731 }
6732
6733 fn promote_instance_local_thread_work_item(
6734 &mut self,
6735 current_instance: RuntimeInstance,
6736 ) -> Result<bool> {
6737 log::trace!("promote thread work items for {current_instance:?}");
6738
6739 self.promote_work_item_matching(|item: &WorkItem| {
6740 let result = match item {
6741 WorkItem::ResumeThread { instance, .. }
6742 | WorkItem::ResumeFiber { instance, .. }
6743 | WorkItem::GuestCall { instance, .. } => *instance == current_instance,
6744 _ => false,
6745 };
6746
6747 log::trace!("candidate {item:?}: {result}");
6748 result
6749 })
6750 }
6751
6752 fn promote_thread_work_item(&mut self, thread: QualifiedThreadId) -> Result<bool> {
6753 self.promote_work_item_matching(|item: &WorkItem| match item {
6754 WorkItem::ResumeThread {
6755 thread: item_thread,
6756 ..
6757 }
6758 | WorkItem::GuestCall {
6759 call:
6760 GuestCall {
6761 thread: item_thread,
6762 ..
6763 },
6764 ..
6765 } => *item_thread == thread,
6766 _ => false,
6767 })
6768 }
6769
6770 fn promote_work_item_matching<F>(&mut self, mut predicate: F) -> Result<bool>
6771 where
6772 F: FnMut(&WorkItem) -> bool,
6773 {
6774 if self.switch_item.is_none() {
6781 if let Some(index) = self.high_priority.iter().rposition(&mut predicate) {
6782 self.switch_item = self.high_priority.remove(index);
6783 }
6784 }
6785 if self.switch_item.is_none() {
6786 if let Some(index) = self.low_priority.iter().rposition(predicate) {
6787 self.switch_item = self.low_priority.remove(index);
6788 }
6789 }
6790 Ok(self.switch_item.is_some())
6791 }
6792
6793 pub fn call_context(&mut self, task: VMScope) -> Result<&mut CallContext> {
6796 match task.kind() {
6797 ScopeKind::HostId(task) => {
6798 let task: TableId<HostTask> = TableId::new(task);
6799 Ok(&mut self.get_mut(task)?.call_context)
6800 }
6801 ScopeKind::Id(task) => {
6802 let task: TableId<GuestTask> = TableId::new(task);
6803 Ok(&mut self.get_mut(task)?.call_context)
6804 }
6805 }
6806 }
6807
6808 pub(crate) fn deferred_host_call_context(&mut self) -> Option<&mut CallContext> {
6809 self.deferred_host_call_context.as_mut()
6810 }
6811
6812 fn futures_mut(&mut self) -> Result<&mut FuturesUnordered<HostTaskFuture>> {
6813 match self.futures.get_mut().as_mut() {
6814 Some(f) => Ok(f),
6815 None => bail_bug!("futures field of concurrent state is currently taken"),
6816 }
6817 }
6818
6819 pub(crate) fn table(&mut self) -> &mut ResourceTable {
6820 self.table.get_mut()
6821 }
6822
6823 fn debug_assert_deferred_host_invariant(&self) {
6824 debug_assert_eq!(
6825 self.deferred_host_call_context.is_some(),
6826 matches!(self.unforced_current_thread, CurrentThread::DeferredHost(_)),
6827 "a deferred host thread and call context must exist together",
6828 );
6829 }
6830
6831 fn materialize_host_task(&mut self) -> Result<CurrentThread> {
6832 self.debug_assert_deferred_host_invariant();
6833 let caller = match self.unforced_current_thread {
6834 CurrentThread::DeferredHost(caller) => caller,
6835 thread => return Ok(thread),
6836 };
6837
6838 let task = HostTask::new(self, HostTaskState::CalleeStarted, caller)?;
6840 let task = self.push(task)?;
6841 let call_context = self
6842 .deferred_host_call_context
6843 .take()
6844 .expect("deferred host call context should be present");
6845 self.get_mut(task)
6846 .expect("newly inserted host task should be present")
6847 .call_context = call_context;
6848 self.unforced_current_thread = CurrentThread::Host(task);
6849 self.debug_assert_deferred_host_invariant();
6850 log::trace!("new host task materialized {task:?}");
6851 Ok(CurrentThread::Host(task))
6852 }
6853
6854 fn materialize_current_host_task_id(&mut self) -> Result<Option<TableId<HostTask>>> {
6855 match self.materialize_host_task()? {
6856 CurrentThread::Host(id) => Ok(Some(id)),
6857 CurrentThread::None => Ok(None),
6858 CurrentThread::Guest(_) => {
6859 bail_bug!("tried to materialize a host task id from a guest thread")
6860 }
6861 CurrentThread::DeferredHost(_) => {
6862 bail_bug!(
6863 "current thread is a deferred host thread which should have been materialized"
6864 )
6865 }
6866 }
6867 }
6868
6869 pub(crate) fn materialize_current_scope(&mut self) -> Result<VMScope> {
6870 match self.materialize_host_task()? {
6871 CurrentThread::Host(id) => Ok(VMScope::host_id(id.rep())),
6872 _ => bail_bug!("current scope is not a deferred host scope"),
6873 }
6874 }
6875
6876 fn increment_task_ref_count(&mut self, task: TableId<GuestTask>) -> Result<()> {
6877 let count = &mut self.get_mut(task)?.ref_count;
6878 *count += 1;
6879 log::trace!("increment {task:?} to {count}");
6880 Ok(())
6881 }
6882
6883 fn decrement_task_ref_count(&mut self, task: TableId<GuestTask>) -> Result<()> {
6884 let count = &mut self.get_mut(task)?.ref_count;
6885 if *count == 0 {
6886 bail_bug!("can't decrement task ref count that's already zero");
6887 }
6888 *count -= 1;
6889 log::trace!("decrement {task:?} to {count}");
6890 if *count == 0 {
6891 let task = self.delete(task)?;
6892
6893 self.decrement_group_ref_count(task.group)?;
6894
6895 debug_assert!(task.decremented_interesting_task_count);
6902 }
6903 Ok(())
6904 }
6905
6906 fn delete_host_task(&mut self, task: TableId<HostTask>) -> Result<()> {
6907 log::trace!("delete host task {task:?}");
6908 let task = self.delete(task)?;
6909
6910 self.decrement_group_ref_count(task.group)
6911 }
6912}
6913
6914fn for_any_lower<
6917 F: FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync,
6918>(
6919 fun: F,
6920) -> F {
6921 fun
6922}
6923
6924fn for_any_lift<
6926 F: FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
6927>(
6928 fun: F,
6929) -> F {
6930 fun
6931}
6932
6933fn check_ambient_store(id: StoreId) {
6934 let message = "\
6935 `Future`s which depend on asynchronous component tasks, streams, or \
6936 futures to complete may only be polled from the event loop of the \
6937 store to which they belong. Please use \
6938 `StoreContextMut::{run_concurrent,spawn}` to poll or await them.\
6939 ";
6940 tls::try_get(|store| {
6941 let matched = match store {
6942 tls::TryGet::Some(store) => store.id() == id,
6943 tls::TryGet::Taken | tls::TryGet::None => false,
6944 };
6945
6946 if !matched {
6947 panic!("{message}")
6948 }
6949 });
6950}
6951
6952fn unpack_callback_code(code: u32) -> (u32, u32) {
6953 (code & 0xF, code >> 4)
6954}
6955
6956struct WaitableCheckParams {
6960 set: TableId<WaitableSet>,
6961 options: OptionsIndex,
6962 payload: u32,
6963}
6964
6965enum WaitableCheck {
6968 Wait,
6969 Poll,
6970}
6971
6972pub(crate) struct PreparedCall<R> {
6974 handle: Func,
6976 thread: QualifiedThreadId,
6978 param_count: usize,
6980 rx: oneshot::Receiver<LiftedResult>,
6983 _phantom: PhantomData<R>,
6984}
6985
6986impl<R> PreparedCall<R> {
6987 pub(crate) fn acquire_task_id(&self, store: &mut StoreOpaque) -> Result<TaskId> {
6994 store
6995 .concurrent_state_mut()?
6996 .increment_task_ref_count(self.thread.task)?;
6997
6998 Ok(TaskId {
6999 task: self.thread.task,
7000 })
7001 }
7002}
7003
7004pub(crate) struct TaskId {
7006 task: TableId<GuestTask>,
7007}
7008
7009impl TaskId {
7010 pub(crate) fn host_future_dropped(&self, store: &mut StoreOpaque) -> Result<()> {
7022 let task = store.concurrent_state_mut()?.get_mut(self.task)?;
7023 if !task.already_lowered_parameters() {
7024 task.lower_params = Some(Box::new(|store, _| {
7029 store.set_trapped();
7030 bail!("the host future for this call was dropped before it started")
7031 }));
7032 } else {
7033 _ = store
7038 .concurrent_state_mut()?
7039 .decrement_task_ref_count(self.task);
7040 }
7041
7042 Ok(())
7043 }
7044}
7045
7046pub(crate) fn prepare_call<T, R>(
7052 mut store: StoreContextMut<T>,
7053 handle: Func,
7054 param_count: usize,
7055 lower_params: impl FnOnce(StoreContextMut<T>, &mut [MaybeUninit<ValRaw>]) -> Result<()>
7056 + Send
7057 + Sync
7058 + 'static,
7059 lift_result: impl FnOnce(&mut StoreOpaque, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>>
7060 + Send
7061 + Sync
7062 + 'static,
7063) -> Result<PreparedCall<R>> {
7064 if !store.0.may_enter() {
7068 bail!(Trap::CannotEnterComponent);
7069 }
7070
7071 let (options, _flags, ty, raw_options) = handle.abi_info(store.0);
7072
7073 let instance = handle.instance().id().get(store.0);
7074 let options = &instance.component().env_component().options[options];
7075 let ty = &instance.component().types()[ty];
7076 let async_typed = ty.async_;
7077 let async_lifted = raw_options.async_;
7078 let task_return_type = ty.results;
7079 let component_instance = raw_options.instance;
7080 let callback = options.callback.map(|i| instance.runtime_callback(i));
7081 let memory = options
7082 .memory()
7083 .map(|i| instance.runtime_memory(i))
7084 .map(SendSyncPtr::new);
7085 let string_encoding = options.string_encoding;
7086 let token = StoreToken::new(store.as_context_mut());
7087 let caller = store.0.materialize_host_task_id()?;
7088 let state = store.0.concurrent_state_mut()?;
7089
7090 let (tx, rx) = oneshot::channel();
7091
7092 let instance = handle.instance().runtime_instance(component_instance);
7093 let thread = GuestTask::new(
7094 state,
7095 Box::new(for_any_lower(move |store, params| {
7096 lower_params(token.as_context_mut(store), params)
7097 })),
7098 LiftResult {
7099 lift: Box::new(for_any_lift(move |store, result| {
7100 lift_result(store, result)
7101 })),
7102 ty: task_return_type,
7103 memory,
7104 string_encoding,
7105 },
7106 Caller::Host {
7107 tx: Some(tx),
7108 caller,
7109 },
7110 callback.map(|callback| {
7111 let callback = SendSyncPtr::new(callback);
7112 let instance = handle.instance();
7113 Box::new(move |store: &mut dyn VMStore, event, handle| {
7114 let store = token.as_context_mut(store);
7115 unsafe { instance.call_callback(store, callback, event, handle) }
7118 }) as CallbackFn
7119 }),
7120 instance,
7121 async_typed,
7122 async_lifted,
7123 )?;
7124
7125 Ok(PreparedCall {
7126 handle,
7127 thread,
7128 param_count,
7129 rx,
7130 _phantom: PhantomData,
7131 })
7132}
7133
7134pub(crate) struct StagedCall<R> {
7135 store: StoreId,
7136 rx: oneshot::Receiver<LiftedResult>,
7137 _marker: PhantomData<fn() -> R>,
7138 group: TaskGroupId,
7146}
7147
7148impl<R> StagedCall<R> {
7149 pub(crate) fn new<T: 'static>(
7160 mut store: StoreContextMut<T>,
7161 prepared: PreparedCall<R>,
7162 ) -> Result<StagedCall<R>> {
7163 let PreparedCall {
7164 handle,
7165 thread,
7166 param_count,
7167 rx,
7168 ..
7169 } = prepared;
7170
7171 stage_call0(store.as_context_mut(), handle, thread, param_count)?;
7172
7173 let state = store.0.concurrent_state_mut()?;
7174 let group = state.get_mut(thread.task)?.group;
7175 state.decrement_task_ref_count(thread.task)?;
7176
7177 Ok(StagedCall {
7178 store: store.0.id(),
7179 rx,
7180 _marker: PhantomData,
7181 group,
7182 })
7183 }
7184}
7185
7186impl<R> Future for StagedCall<R>
7187where
7188 R: 'static,
7189{
7190 type Output = Result<R>;
7191
7192 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
7193 check_ambient_store(self.store);
7194 Pin::new(&mut self.rx).poll(cx).map(|result| match result {
7195 Ok(r) => match r.downcast() {
7196 Ok(r) => Ok(*r),
7197 Err(_) => bail_bug!("wrong type of value produced"),
7198 },
7199 Err(oneshot::Canceled) => bail_bug!("channel erroneously dropped"),
7200 })
7201 }
7202}
7203
7204fn stage_call0<T: 'static>(
7207 store: StoreContextMut<T>,
7208 handle: Func,
7209 guest_thread: QualifiedThreadId,
7210 param_count: usize,
7211) -> Result<()> {
7212 let (_options, _, _ty, raw_options) = handle.abi_info(store.0);
7213 let is_concurrent = raw_options.async_;
7214 let callback = raw_options.callback;
7215 let instance = handle.instance();
7216 let callee = handle.lifted_core_func(store.0);
7217 let post_return = raw_options
7218 .post_return
7219 .map(|i| instance.id().get(store.0).runtime_post_return(i));
7220 let callback = callback.map(|i| {
7221 let instance = instance.id().get(store.0);
7222 SendSyncPtr::new(instance.runtime_callback(i))
7223 });
7224
7225 log::trace!("queueing call {guest_thread:?}");
7226
7227 unsafe {
7231 instance.stage_call(
7232 store,
7233 guest_thread,
7234 SendSyncPtr::new(callee),
7235 param_count,
7236 1,
7237 is_concurrent,
7238 callback,
7239 post_return.map(SendSyncPtr::new),
7240 true,
7241 )
7242 }
7243}
7244
7245#[cfg(all(test, feature = "cranelift", feature = "wat"))]
7246mod tests {
7247 use super::*;
7248 use crate::component::{Component, Linker};
7249 use crate::store::AsStoreOpaque;
7250 use crate::{Config, Engine};
7251
7252 fn host_subtask(
7253 state: HostTaskState,
7254 event: Option<Event>,
7255 ) -> Result<(Store<()>, Instance, TableId<HostTask>, u32)> {
7256 let mut config = Config::new();
7257 config.wasm_component_model_async(true);
7258 let engine = Engine::new(&config)?;
7259 let component = Component::new(&engine, "(component)")?;
7260 let mut store = Store::new(&engine, ());
7261 let instance = Linker::new(&engine).instantiate(&mut store, &component)?;
7262 let store_opaque = store.as_store_opaque();
7263 let concurrent_state = store_opaque.concurrent_state_mut()?;
7264 let group = concurrent_state.make_task_group()?;
7267 let task = concurrent_state.push(HostTask {
7268 common: WaitableCommon::default(),
7269 call_context: CallContext::default(),
7270 state,
7271 group,
7272 })?;
7273 let handle = store_opaque
7274 .handle_table_insertion(
7275 instance.runtime_instance(RuntimeComponentInstanceIndex::from_u32(0)),
7276 )
7277 .subtask_host(task.rep())?;
7278 let common = &mut store_opaque.concurrent_state_mut()?.get_mut(task)?.common;
7279 common.handle = Some(handle);
7280 common.event = event;
7281 Ok((store, instance, task, handle))
7282 }
7283
7284 #[test]
7285 fn host_subtask_drop_during_cancellation() -> Result<()> {
7286 for abort_completed in [false, true] {
7287 let (handle, future) = JoinHandle::run(future::pending::<()>());
7288 let mut future = pin!(future);
7289 let (mut store, instance, task, handle) =
7290 host_subtask(HostTaskState::CalleeRunning(handle), None)?;
7291 let store = store.as_store_opaque();
7292 let caller = RuntimeComponentInstanceIndex::from_u32(0);
7293 assert_eq!(
7294 instance.subtask_cancel(store, caller, true, handle)?,
7295 BLOCKED
7296 );
7297 if abort_completed {
7298 assert!(matches!(
7301 future
7302 .as_mut()
7303 .poll(&mut Context::from_waker(Waker::noop())),
7304 Poll::Ready(None),
7305 ));
7306 }
7307 for async_ in [false, true] {
7308 let err = instance
7309 .subtask_cancel(store, caller, async_, handle)
7310 .unwrap_err();
7311 assert_eq!(err.downcast::<Trap>()?, Trap::SubtaskCancelAfterTerminal);
7312 }
7313 let err = instance.subtask_drop(store, caller, handle).unwrap_err();
7314 assert_eq!(err.downcast::<Trap>()?, Trap::SubtaskDropNotResolved);
7315 assert!(store.concurrent_state_mut()?.get_mut(task).is_ok());
7316 }
7317 Ok(())
7318 }
7319
7320 #[test]
7321 fn host_subtask_cancel_after_completion() -> Result<()> {
7322 for async_ in [false, true] {
7323 let (mut store, instance, task, handle) = host_subtask(
7324 HostTaskState::CalleeDone { cancelled: false },
7325 Some(Event::Subtask {
7326 status: Status::Returned,
7327 }),
7328 )?;
7329 let store = store.as_store_opaque();
7330 let caller = RuntimeComponentInstanceIndex::from_u32(0);
7331 assert_eq!(
7332 instance.subtask_cancel(store, caller, async_, handle)?,
7333 Status::Returned as u32,
7334 );
7335 let err = instance
7336 .subtask_cancel(store, caller, async_, handle)
7337 .unwrap_err();
7338 assert_eq!(err.downcast::<Trap>()?, Trap::SubtaskCancelAfterTerminal);
7339 instance.subtask_drop(store, caller, handle)?;
7340 assert!(store.concurrent_state_mut()?.get_mut(task).is_err());
7341 }
7342 Ok(())
7343 }
7344
7345 #[test]
7346 fn host_subtask_drop_requires_terminal_event_delivery() -> Result<()> {
7347 for (cancelled, status) in [
7348 (false, Status::Returned),
7349 (true, Status::Returned),
7350 (true, Status::ReturnCancelled),
7351 ] {
7352 for delivered in [false, true] {
7353 let event = if delivered {
7354 None
7355 } else {
7356 Some(Event::Subtask { status })
7357 };
7358 let (mut store, instance, task, handle) =
7359 host_subtask(HostTaskState::CalleeDone { cancelled }, event)?;
7360 let store = store.as_store_opaque();
7361 let result = instance.subtask_drop(
7362 store,
7363 RuntimeComponentInstanceIndex::from_u32(0),
7364 handle,
7365 );
7366 if delivered {
7367 result?;
7368 assert!(store.concurrent_state_mut()?.get_mut(task).is_err());
7369 } else {
7370 let err = result.unwrap_err();
7371 assert_eq!(err.downcast::<Trap>()?, Trap::SubtaskDropNotResolved);
7372 assert!(store.concurrent_state_mut()?.get_mut(task).is_ok());
7373 }
7374 }
7375 }
7376 Ok(())
7377 }
7378}