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