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 let next = match tls::set(reset.store.0, || next.as_mut().poll(cx)) {
1509 Poll::Ready(Some(output)) => {
1510 match output {
1511 Err(e) => return Poll::Ready(Err(e)),
1512 Ok(()) => {}
1513 }
1514 Poll::Ready(true)
1515 }
1516 Poll::Ready(None) => Poll::Ready(false),
1517 Poll::Pending => Poll::Pending,
1518 };
1519
1520 let state = reset.store.0.concurrent_state_mut()?;
1535 let mut ready = state.switch_item.take();
1536 let mut low_priority = false;
1537 if ready.is_none() {
1538 ready = state.high_priority.pop_back();
1539 if ready.is_none() {
1540 ready = state.low_priority.pop_back();
1541 low_priority = true;
1542 }
1543 }
1544 if ready.is_some() {
1545 return Poll::Ready(Ok(PollResult::ProcessWork {
1546 ready,
1547 low_priority,
1548 }));
1549 }
1550
1551 if let Some(waker) = state.idle_waker.take() {
1552 waker.wake();
1553 }
1554
1555 return match next {
1559 Poll::Ready(true) => {
1560 Poll::Ready(Ok(PollResult::ProcessWork {
1566 ready: None,
1567 low_priority: false,
1568 }))
1569 }
1570 Poll::Ready(false) => {
1571 if let Poll::Ready(value) =
1575 tls::set(reset.store.0, || future.as_mut().poll(cx))
1576 {
1577 Poll::Ready(Ok(PollResult::Complete(value)))
1578 } else {
1579 if trap_on_idle {
1585 Poll::Ready(Err(if reset.store.0.any_may_not_suspend()? {
1592 Trap::CannotBlockSyncTask.into()
1593 } else {
1594 Trap::AsyncDeadlock.into()
1596 }))
1597 } else {
1598 Poll::Pending
1602 }
1603 }
1604 }
1605 Poll::Pending => Poll::Pending,
1610 };
1611 })
1612 .await;
1613
1614 drop(reset);
1618
1619 match result? {
1620 PollResult::Complete(value) => break Ok(value),
1623 PollResult::ProcessWork {
1626 mut ready,
1627 low_priority,
1628 } => {
1629 if low_priority {
1657 if let Some(item) = ready.take() {
1658 self.0.concurrent_state_mut()?.low_priority.push_back(item);
1659 }
1660 self.0.yield_now().await;
1661 turns_without_yield = 0;
1662 ready = self.0.concurrent_state_mut()?.low_priority.pop_back();
1663 }
1664
1665 if let Some(item) = ready {
1666 self.as_context_mut().handle_work_item(item).await?;
1667 }
1668
1669 turns_without_yield += 1;
1670 if turns_without_yield == MAX_TURNS_WITHOUT_YIELD {
1671 turns_without_yield = 0;
1672 self.0.yield_now().await;
1673 }
1674 }
1675 }
1676 }
1677 }
1678
1679 fn handle_work_item(self, item: WorkItem) -> impl Future<Output = Result<()>> {
1681 let item = match item {
1685 WorkItem::ResumeFiber {
1686 instance,
1687 thread,
1688 fiber,
1689 } => {
1690 let future = self.0.resume_fiber(fiber);
1691 log::trace!(
1692 "handle work item ResumeFiber {{ instance: {instance:?}, thread: {thread:?} }}"
1693 );
1694 return futures::future::Either::Left(future);
1695 }
1696 item => item,
1697 };
1698 futures::future::Either::Right(async move {
1699 log::trace!("handle work item {item:?}");
1700 match item {
1701 WorkItem::PushFuture(future) => {
1702 self.0
1703 .concurrent_state_mut()?
1704 .futures_mut()?
1705 .push(future.into_inner());
1706 }
1707 WorkItem::ResumeFiber { .. } => unreachable!(),
1708 WorkItem::ResumeThread { thread, .. } => {
1709 let slot = &mut self.0.concurrent_state_mut()?.get_mut(thread.thread)?.state;
1710 if !matches!(slot, GuestThreadState::Ready { .. }) {
1711 bail_bug!("cannot resume non-pending thread {thread:?}");
1712 }
1713 let GuestThreadState::Ready { fiber } =
1714 mem::replace(slot, GuestThreadState::Running)
1715 else {
1716 unreachable!()
1717 };
1718 self.0.resume_fiber(fiber).await?;
1719 }
1720 WorkItem::GuestCall { mut call, .. } => {
1721 if call.is_ready(self.0)? {
1722 if let GuestCallKind::StartImplicit {
1723 was_pending: true, ..
1724 } = &call.kind
1725 {
1726 let instance = self
1727 .0
1728 .concurrent_state_mut()?
1729 .get_mut(call.thread.task)?
1730 .instance;
1731
1732 self.0.decrement_pending_start_count(instance, 1)?;
1733 }
1734
1735 self.0
1736 .concurrent_state_mut()?
1737 .get_mut(call.thread.thread)?
1738 .wake_on_cancel = WakeOnCancel::None;
1739
1740 self.run_on_worker(WorkerItem::GuestCall(call)).await?;
1741 } else {
1742 let state = self.0.concurrent_state_mut()?;
1743 let task = state.get_mut(call.thread.task)?;
1744 if !task.starting_sent {
1745 task.starting_sent = true;
1746 if let GuestCallKind::StartImplicit { .. } = &call.kind {
1747 Waitable::Guest(call.thread.task).set_event(
1748 state,
1749 Some(Event::Subtask {
1750 status: Status::Starting,
1751 }),
1752 )?;
1753 }
1754 }
1755
1756 let increment = if let GuestCallKind::StartImplicit {
1757 was_pending, ..
1758 } = &mut call.kind
1759 {
1760 let increment = !*was_pending;
1761 *was_pending = true;
1762 increment
1763 } else {
1764 false
1765 };
1766
1767 let instance = state.get_mut(call.thread.task)?.instance;
1768 if let GuestCallKind::DeliverEvent { set: Some(set), .. } = &call.kind {
1777 if !state.get_mut(*set)?.ready.is_empty() {
1778 state.wake_waiter(*set)?;
1779 }
1780 }
1781
1782 state.take_next_switch_item()?;
1786
1787 let requeue = increment && call.is_ready(self.0)?;
1804
1805 if increment {
1806 self.0
1807 .instance_state(instance)
1808 .concurrent_state()
1809 .pending_start_count += 1;
1810 }
1811
1812 if requeue {
1813 self.0
1814 .concurrent_state_mut()?
1815 .push_high_priority(WorkItem::GuestCall { instance, call });
1816 } else {
1817 self.0
1818 .instance_state(instance)
1819 .concurrent_state()
1820 .pending
1821 .insert(call.thread, call.kind);
1822 }
1823 }
1824 }
1825 WorkItem::WorkerFunction(fun) => {
1826 self.run_on_worker(WorkerItem::Function(fun)).await?;
1827 }
1828 }
1829
1830 Ok(())
1831 })
1832 }
1833
1834 async fn run_on_worker(self, item: WorkerItem) -> Result<()> {
1836 let state = self.0.concurrent_state_mut()?;
1837 if state.worker_item.is_some() {
1838 bail_bug!("worker item already set when taking worker fiber");
1839 }
1840 let worker = if let Some(fiber) = state.worker.take() {
1841 fiber
1842 } else {
1843 unsafe {
1862 fiber::make_fiber_unchecked(self.0, move |store| {
1863 loop {
1864 let Some(item) = store.concurrent_state_mut()?.worker_item.take() else {
1865 bail_bug!("worker_item not present when resuming fiber")
1866 };
1867 match item {
1868 WorkerItem::GuestCall(call) => handle_guest_call(store, call)?,
1869 WorkerItem::Function(fun) => fun.into_inner()(store)?,
1870 }
1871
1872 store.suspend(SuspendReason::NeedWork)?;
1873 }
1874 })?
1875 }
1876 };
1877
1878 self.0
1881 .concurrent_state_mut_already_forced_current_thread()
1882 .worker_item = Some(item);
1883
1884 self.0.resume_fiber(worker).await
1885 }
1886
1887 pub(crate) fn wrap_call<F, R>(self, closure: F) -> impl Future<Output = Result<R>> + 'static
1892 where
1893 T: 'static,
1894 F: FnOnce(&Accessor<T>) -> Pin<Box<dyn Future<Output = Result<R>> + Send + '_>>
1895 + Send
1896 + Sync
1897 + 'static,
1898 R: Send + Sync + 'static,
1899 {
1900 let token = StoreToken::new(self);
1901 async move {
1902 let mut accessor = Accessor::new(token);
1903 closure(&mut accessor).await
1904 }
1905 }
1906
1907 pub(crate) async fn start_instance(
1908 &mut self,
1909 instance: ModuleInstance,
1910 callee: Option<RuntimeInstance>,
1911 ) -> Result<ModuleInstance> {
1912 self.0.check_event_loop_not_running()?;
1914 let (tx, rx) = oneshot::channel();
1915 let token = StoreToken::new(self.as_context_mut());
1916 self.0.queue_task(move |store| {
1917 _ = tx.send(
1918 super::instance::start_raw(&mut token.as_context_mut(store), instance, callee)
1919 .map(|()| instance),
1920 );
1921 Ok(())
1922 })?;
1923 self.as_context_mut()
1924 .run_concurrent_trap_on_idle(async |_| {
1925 rx.await
1926 .map_err(|_| format_err!("oneshot channel canceled"))
1927 })
1928 .await??
1929 }
1930}
1931
1932pub type EnteredHostTask = Option<QualifiedThreadId>;
1939
1940impl StoreOpaque {
1941 pub(crate) fn check_event_loop_not_running(&mut self) -> Result<()> {
1942 if self
1943 .concurrent_state_mut_already_forced_current_thread()
1944 .event_loop_running
1945 {
1946 bail!("Recursive `StoreContextMut::run_concurrent` calls not supported")
1947 }
1948 Ok(())
1949 }
1950
1951 #[inline]
1955 pub(crate) fn current_thread(&mut self) -> Result<CurrentThread> {
1956 if !self.concurrency_support() {
1958 return Ok(CurrentThread::None);
1959 }
1960
1961 if !self
1964 .vm_store_context_mut()
1965 .current_thread_mut()
1966 .is_deferred()
1967 {
1968 return Ok(self
1969 .concurrent_state_mut_already_forced_current_thread()
1970 .unforced_current_thread);
1971 }
1972
1973 self.force_deferred_current_thread()
1974 }
1975
1976 #[cold]
1979 fn force_deferred_current_thread(&mut self) -> Result<CurrentThread> {
1980 let state = self.concurrent_state_mut_without_forcing_current_thread();
1989 let id = match state.unforced_current_thread.guest_task() {
1990 Some(task) => state.get_mut(task)?.instance.instance,
1991 None => bail_bug!("deferred component-model thread with non-guest base"),
1992 };
1993
1994 let mut frames = SmallVec::<[_; 8]>::new();
1997 let mut cur = *self.vm_store_context_mut().current_thread_mut();
1998 while let Some(ptr) = cur.as_deferred() {
1999 let deferred = unsafe { ptr.as_non_null().as_ref() };
2004 frames.push((
2005 deferred.callee_async != 0,
2006 deferred.callee_instance,
2007 deferred.saved_context,
2008 deferred.lazy_lenders_start,
2009 ));
2010 cur = deferred.parent;
2011 }
2012
2013 *self.vm_store_context_mut().current_thread_mut() = VMLazyThread::forced();
2017
2018 let current_context = *self.vm_store_context_mut().component_context_mut();
2021
2022 let lazy_lenders_end = *self.vm_store_context_mut().lazy_lenders_len_mut();
2029 frames.reverse();
2030 let lazy_lenders_base = match frames.first() {
2031 Some((_, _, _, start)) => *start,
2032 None => bail_bug!("forcing a deferred thread with no deferred frames"),
2033 };
2034 let lazy_lender_ends = frames
2035 .iter()
2036 .skip(1)
2037 .map(|(_, _, _, start)| *start)
2038 .chain([lazy_lenders_end])
2039 .collect::<SmallVec<[_; 8]>>();
2040 for ((callee_async, callee_instance, saved_context, start), lenders_end) in
2041 frames.into_iter().zip(lazy_lender_ends)
2042 {
2043 *self.vm_store_context_mut().component_context_mut() = saved_context;
2047 let callee = RuntimeInstance {
2048 instance: id,
2049 index: RuntimeComponentInstanceIndex::from_u32(callee_instance),
2050 };
2051 self.enter_guest_sync_call(callee_async, callee)?;
2052
2053 self.promote_current_lazy_lends(id, start, lenders_end)?;
2056 }
2057
2058 debug_assert_eq!(
2061 *self.vm_store_context_mut().lazy_lenders_len_mut(),
2062 lazy_lenders_end
2063 );
2064 *self.vm_store_context_mut().lazy_lenders_len_mut() = lazy_lenders_base;
2065
2066 *self.vm_store_context_mut().component_context_mut() = current_context;
2068
2069 Ok(self
2070 .concurrent_state_mut_without_forcing_current_thread()
2071 .unforced_current_thread)
2072 }
2073
2074 fn promote_current_lazy_lends(
2080 &mut self,
2081 id: ComponentInstanceId,
2082 start: usize,
2083 end: usize,
2084 ) -> Result<()> {
2085 if start == end {
2086 return Ok(());
2087 }
2088
2089 let scope = match self
2090 .concurrent_state_mut_without_forcing_current_thread()
2091 .unforced_current_thread
2092 .guest_task()
2093 {
2094 Some(task) => VMScope::id(task.rep()),
2095 None => bail_bug!("replayed deferred frame is not a guest thread"),
2096 };
2097 let instance = Instance::from_wasmtime(self, id);
2098 self.promote_lazy_lends(instance, scope, start, end)
2099 }
2100
2101 fn current_guest_thread(&mut self) -> Result<QualifiedThreadId> {
2102 match self.current_thread()?.guest() {
2103 Some(id) => Ok(*id),
2104 None => bail_bug!("current thread is not a guest thread"),
2105 }
2106 }
2107
2108 pub(crate) fn current_materialized_host_task(&mut self) -> Result<Option<TableId<HostTask>>> {
2112 match self.current_thread()? {
2113 CurrentThread::Host(id) => Ok(Some(id)),
2114 CurrentThread::DeferredHost(_) | CurrentThread::None => Ok(None),
2115 CurrentThread::Guest(_) => {
2116 if self.component_trapped() {
2120 bail!(Trap::CannotEnterComponent)
2121 } else {
2122 bail_bug!("current thread is not a host thread")
2123 }
2124 }
2125 }
2126 }
2127
2128 fn materialize_host_task_id(&mut self) -> Result<Option<TableId<HostTask>>> {
2131 Ok(self
2132 .concurrent_state_mut()?
2133 .materialize_current_host_task_id()?)
2134 }
2135
2136 fn enter_sync_call(&mut self, callee: RuntimeInstance) -> Result<()> {
2137 log::trace!("enter sync-typed call {callee:?}");
2138 let state = self.instance_state(callee).concurrent_state();
2139 let old_do_not_suspend = state.do_not_suspend;
2140 state.do_not_suspend = true;
2141
2142 let thread = self.current_guest_thread()?;
2143 let thread = self.concurrent_state_mut()?.get_mut(thread.thread)?;
2144 if thread.old_do_not_suspend.is_some() {
2145 bail_bug!("current thread already has `old_do_not_suspend` value");
2146 }
2147
2148 thread.old_do_not_suspend = Some(old_do_not_suspend);
2149
2150 Ok(())
2151 }
2152
2153 fn exit_sync_call(&mut self, callee: RuntimeInstance) -> Result<()> {
2154 log::trace!("exit sync-typed call {callee:?}");
2155 let thread = self.current_guest_thread()?;
2156 let thread = self.concurrent_state_mut()?.get_mut(thread.thread)?;
2157 let Some(old_do_not_suspend) = thread.old_do_not_suspend.take() else {
2158 bail_bug!("current thread missing `old_do_not_suspend` value");
2159 };
2160 let state = self.instance_state(callee).concurrent_state();
2161 state.do_not_suspend = old_do_not_suspend;
2162 Ok(())
2163 }
2164
2165 pub(crate) fn enter_guest_sync_call(
2177 &mut self,
2178 callee_async_typed: bool,
2179 callee: RuntimeInstance,
2180 ) -> Result<()> {
2181 log::trace!("enter sync-lifted call {callee:?}");
2182 if !self.concurrency_support() {
2183 return self.enter_call_not_concurrent();
2184 }
2185
2186 let state = self.concurrent_state_mut()?;
2190 let item = state.next_switch_item.take();
2191 state.saved_next_switch_items.push(item);
2192
2193 let thread = self.current_thread()?;
2194 let caller = if let Some(thread) = thread.guest() {
2195 Caller::Guest { thread: *thread }
2196 } else {
2197 Caller::Host {
2198 tx: None,
2199 caller: self.materialize_host_task_id()?,
2200 }
2201 };
2202
2203 let state = self.concurrent_state_mut()?;
2204 let guest_thread = GuestTask::new(
2205 state,
2206 Box::new(move |_, _| bail_bug!("cannot lower params in sync call")),
2207 LiftResult {
2208 lift: Box::new(move |_, _| bail_bug!("cannot lift result in sync call")),
2209 ty: TypeTupleIndex::reserved_value(),
2210 memory: None,
2211 string_encoding: StringEncoding::Utf8,
2212 },
2213 caller,
2214 None,
2215 callee,
2216 callee_async_typed,
2217 false,
2218 )?;
2219
2220 Instance::from_wasmtime(self, callee.instance).add_guest_thread_to_instance_table(
2221 guest_thread.thread,
2222 self,
2223 callee.index,
2224 )?;
2225 self.set_thread(guest_thread)?;
2226
2227 if !callee_async_typed {
2228 self.enter_sync_call(callee)?;
2229 }
2230
2231 Ok(())
2232 }
2233
2234 pub(crate) fn exit_guest_sync_call(&mut self) -> Result<()> {
2242 if !self.concurrency_support() {
2243 return Ok(self.exit_call_not_concurrent());
2244 }
2245
2246 let thread = match self.current_thread()?.guest() {
2247 Some(t) => *t,
2248 None => bail_bug!("expected task when exiting"),
2249 };
2250 let task = self.concurrent_state_mut()?.get_mut(thread.task)?;
2251 let instance = task.instance;
2252
2253 let caller = match &task.caller {
2254 &Caller::Guest { thread } => thread.into(),
2255 &Caller::Host { caller, .. } => caller
2256 .map(CurrentThread::Host)
2257 .unwrap_or(CurrentThread::None),
2258 };
2259 task.lift_result = None;
2260 task.exited = true;
2261 let async_typed = task.async_typed;
2262
2263 if !async_typed {
2264 self.exit_sync_call(instance)?;
2265 }
2266
2267 self.set_thread(caller)?;
2268
2269 log::trace!("exit sync-lifted call {instance:?}");
2270
2271 if async_typed {
2272 self.switch_or_trap_if_may_not_suspend(instance)?;
2277 }
2278
2279 self.cleanup_thread(thread, instance)?;
2280
2281 self.concurrent_state_mut()?
2282 .decrement_task_ref_count(thread.task)?;
2283
2284 let state = self.concurrent_state_mut()?;
2285 let Some(item) = state.saved_next_switch_items.pop() else {
2286 bail_bug!("unable to pop from `saved_next_switch_items`");
2287 };
2288 if let Some(item) = mem::replace(&mut state.next_switch_item, item) {
2289 state.push_high_priority(item);
2292 bail_bug!("`next_switch_item` unexpectedly already set");
2293 }
2294
2295 Ok(())
2296 }
2297
2298 pub(crate) fn host_task_create(&mut self) -> Result<EnteredHostTask> {
2305 if !self.concurrency_support() {
2306 self.enter_call_not_concurrent()?;
2307 return Ok(None);
2308 }
2309 let caller = self.current_guest_thread()?;
2310 log::trace!("new deferred host task with caller {caller:?}");
2311
2312 self.set_thread(CurrentThread::DeferredHost(caller))?;
2313 let state = self.concurrent_state_mut()?;
2314 debug_assert!(state.deferred_host_call_context.is_none());
2315 state.deferred_host_call_context = Some(CallContext::default());
2316 state.debug_assert_deferred_host_invariant();
2317 Ok(Some(caller))
2318 }
2319
2320 pub(crate) fn host_task_delete(
2327 &mut self,
2328 original_task: EnteredHostTask,
2329 materialized_task: Option<TableId<HostTask>>,
2330 ) -> Result<()> {
2331 match original_task {
2332 Some(caller) => {
2333 self.set_thread(caller)?;
2334 if materialized_task.is_none() {
2335 let state = self.concurrent_state_mut()?;
2336 let context = state
2337 .deferred_host_call_context
2338 .take()
2339 .expect("deferred host call context should be present");
2340 debug_assert!(context.is_empty());
2341 state.debug_assert_deferred_host_invariant();
2342 }
2343 log::trace!(
2344 "delete host task with caller {original_task:?} and materialized as {materialized_task:?}"
2345 );
2346 if let Some(task) = materialized_task {
2347 self.concurrent_state_mut()?.delete_host_task(task)?;
2348 }
2349 }
2350 None => {
2351 debug_assert!(materialized_task.is_none());
2352 self.exit_call_not_concurrent();
2353 }
2354 }
2355 Ok(())
2356 }
2357
2358 fn instance_state(&mut self, instance: RuntimeInstance) -> &mut InstanceState {
2361 self.component_instance_mut(instance.instance)
2362 .instance_state(instance.index)
2363 }
2364
2365 fn instance_state_and_handle_counter(
2368 &mut self,
2369 instance: RuntimeInstance,
2370 ) -> (&mut InstanceState, &mut HandleCounter) {
2371 let (component, counter) = self
2372 .store_data_mut()
2373 .component_instance_and_handle_counter_mut(instance.instance);
2374 (component.instance_state(instance.index), counter)
2375 }
2376
2377 fn handle_table_insertion(&mut self, instance: RuntimeInstance) -> HandleTableInsertion<'_> {
2379 let (component, counter) = self
2380 .store_data_mut()
2381 .component_instance_and_handle_counter_mut(instance.instance);
2382 component.handle_table_insertion(instance.index, counter)
2383 }
2384
2385 pub(crate) fn set_thread(&mut self, thread: impl Into<CurrentThread>) -> Result<CurrentThread> {
2391 let thread = thread.into();
2392 let state = self.concurrent_state_mut()?;
2393 state.debug_assert_deferred_host_invariant();
2394 let old_thread = mem::replace(&mut state.unforced_current_thread, thread);
2395
2396 state.handle_thread_switch(old_thread, thread)?;
2397
2398 if let Some(old_thread) = old_thread.guest() {
2406 let old_context = *self.vm_store_context_mut().component_context_mut();
2407 self.concurrent_state_mut()?
2408 .get_mut(old_thread.thread)?
2409 .context = old_context;
2410 }
2411 if cfg!(debug_assertions) {
2412 *self.vm_store_context_mut().component_context_mut() =
2413 [u32::MAX; NUM_COMPONENT_CONTEXT_SLOTS];
2414 }
2415 if let Some(thread) = thread.guest() {
2416 let thread = self.concurrent_state_mut()?.get_mut(thread.thread)?;
2417 let context = thread.context;
2418 if cfg!(debug_assertions) {
2419 thread.context = [u32::MAX; NUM_COMPONENT_CONTEXT_SLOTS];
2420 }
2421 *self.vm_store_context_mut().component_context_mut() = context;
2422 }
2423
2424 *self.vm_store_context_mut().current_thread_mut() = if thread.is_none() {
2426 VMLazyThread::none()
2427 } else {
2428 VMLazyThread::forced()
2429 };
2430
2431 Ok(old_thread)
2432 }
2433
2434 fn switch_or_trap_if_may_not_suspend(&mut self, instance: RuntimeInstance) -> Result<()> {
2436 if self.switch_if_may_not_suspend(instance)? {
2437 Ok(())
2438 } else {
2439 Err(Trap::CannotBlockSyncTask.into())
2440 }
2441 }
2442
2443 fn switch_if_may_not_suspend(&mut self, instance: RuntimeInstance) -> Result<bool> {
2447 self.concurrent_state_mut()?;
2451
2452 Ok(!self.concurrency_support()
2453 || !self
2454 .instance_state(instance)
2455 .concurrent_state()
2456 .do_not_suspend
2457 || self
2458 .concurrent_state_mut()?
2459 .promote_instance_local_thread_work_item(instance)?)
2460 }
2461
2462 fn enter_instance(&mut self, instance: RuntimeInstance) {
2466 log::trace!("enter {instance:?}");
2467 self.instance_state(instance)
2468 .concurrent_state()
2469 .do_not_enter = true;
2470 }
2471
2472 fn exit_instance(&mut self, instance: RuntimeInstance) -> Result<()> {
2476 log::trace!("exit {instance:?}");
2477 self.instance_state(instance)
2478 .concurrent_state()
2479 .do_not_enter = false;
2480 self.partition_pending(instance)
2481 }
2482
2483 fn partition_pending(&mut self, instance: RuntimeInstance) -> Result<()> {
2490 let mut any_ready = false;
2491 for (thread, kind) in
2492 mem::take(&mut self.instance_state(instance).concurrent_state().pending)
2493 {
2494 let call = GuestCall { thread, kind };
2495 if call.is_ready(self)? {
2496 any_ready = true;
2497 self.concurrent_state_mut()?
2498 .push_high_priority(WorkItem::GuestCall { instance, call });
2499 } else {
2500 self.instance_state(instance)
2501 .concurrent_state()
2502 .pending
2503 .insert(call.thread, call.kind);
2504 }
2505 }
2506
2507 if any_ready {
2508 if let Some(waker) = self.concurrent_state_mut()?.backpressure_waker.take() {
2509 waker.wake();
2510 }
2511 }
2512
2513 Ok(())
2514 }
2515
2516 pub(crate) fn backpressure_modify(
2518 &mut self,
2519 caller_instance: RuntimeInstance,
2520 modify: impl FnOnce(u16) -> Option<u16>,
2521 ) -> Result<()> {
2522 let state = self.instance_state(caller_instance).concurrent_state();
2523 let old = state.backpressure;
2524 let new = modify(old).ok_or_else(|| Trap::BackpressureOverflow)?;
2525 state.backpressure = new;
2526
2527 log::trace!("backpressure update for {caller_instance:?} from {old} to {new}");
2528
2529 if old > 0 && new == 0 {
2530 self.partition_pending(caller_instance)?;
2533 }
2534
2535 Ok(())
2536 }
2537
2538 fn resume_fiber(
2541 &mut self,
2542 fiber: StoreFiber<'static>,
2543 ) -> impl Future<Output = Result<()>> + '_ {
2544 let mut resuming = ResumingFiber {
2545 store: self,
2546 fiber: Some(fiber),
2547 };
2548 async move {
2549 let old_thread = resuming.store.current_thread()?;
2550 log::trace!("resume_fiber: save current thread {old_thread:?}");
2551
2552 let fiber = resuming.fiber.take().unwrap();
2553 resuming.fiber = fiber::resolve_or_release(resuming.store, fiber).await?;
2554
2555 resuming.store.set_thread(old_thread)?;
2556
2557 let state = resuming.store.concurrent_state_mut()?;
2558
2559 if let Some(ot) = old_thread.guest() {
2560 state.set_thread_running(ot.thread)?;
2561 }
2562 log::trace!("resume_fiber: restore current thread {old_thread:?}");
2563
2564 if resuming.fiber.is_some() {
2565 log::trace!("resume_fiber: suspend reason {:?}", &state.suspend_reason);
2566 let reason = match state.suspend_reason.take() {
2568 Some(r) => r,
2569 None => bail_bug!("suspend reason missing when resuming fiber"),
2570 };
2571 match reason {
2572 SuspendReason::NeedWork => {
2573 if state.worker.is_none() {
2574 state.worker = resuming.fiber.take();
2575 }
2576 }
2577 SuspendReason::Yielding { thread } => {
2578 let slot = &mut state.get_mut(thread.thread)?.state;
2579 slot.check_no_fiber()?;
2580 *slot = GuestThreadState::Ready {
2581 fiber: resuming.fiber.take().unwrap(),
2582 };
2583 let instance = state.get_mut(thread.task)?.instance;
2584 state.push_low_priority(WorkItem::ResumeThread { instance, thread });
2585 }
2586 SuspendReason::ExplicitlySuspending { thread } => {
2587 let slot = &mut state.get_mut(thread.thread)?.state;
2588 slot.check_no_fiber()?;
2589 *slot = GuestThreadState::Suspended(resuming.fiber.take().unwrap());
2590 }
2591 SuspendReason::Waiting { set, thread } => {
2592 match state.get_mut(set)?.waiting.entry(thread) {
2593 Entry::Vacant(entry) => {
2594 entry.insert(WaitMode::Fiber(resuming.fiber.take().unwrap()));
2595 }
2596 Entry::Occupied(_) => {
2597 bail_bug!("entry unexpectedly already exists for {thread:?}");
2598 }
2599 }
2600 }
2601 SuspendReason::YieldingToSubtask { thread } => {
2602 let instance = state.get_mut(thread.task)?.instance;
2611 if state.next_switch_item.is_some() {
2612 bail_bug!(
2615 "`ConcurrentState::next_switch_item` was already `Some(_)` when \
2616 a thread wanted to wait on a subtask"
2617 );
2618 }
2619 let item = state.next_switch_item.insert(WorkItem::ResumeFiber {
2620 instance,
2621 thread,
2622 fiber: resuming.fiber.take().unwrap(),
2623 });
2624 log::trace!("set next switch item to {item:?}");
2625 }
2626 };
2627 } else {
2628 log::trace!("resume_fiber: fiber has exited");
2629 }
2630
2631 Ok(())
2632 }
2633 }
2634
2635 fn suspend(&mut self, reason: SuspendReason) -> Result<()> {
2641 log::trace!("suspend fiber: {reason:?}");
2642
2643 if !self.fiber_async_state_mut().can_block() {
2646 return Err(format_err!("future dropped"));
2647 }
2648
2649 let state = self.concurrent_state_mut()?;
2650
2651 let (save_and_restore_thread, save_and_restore_next_switch_item) = match &reason {
2658 SuspendReason::Yielding { .. }
2659 | SuspendReason::Waiting { .. }
2660 | SuspendReason::ExplicitlySuspending { .. } => {
2661 if state.switch_item.is_none() {
2664 state.take_next_switch_item()?;
2665 }
2666
2667 (true, false)
2668 }
2669 SuspendReason::YieldingToSubtask { .. } => (true, true),
2670 SuspendReason::NeedWork => (false, false),
2671 };
2672
2673 let old_next_switch_item = if save_and_restore_next_switch_item {
2674 Some(state.save_next_switch_item()?)
2675 } else {
2676 None
2677 };
2678
2679 let old_guest_thread = if save_and_restore_thread {
2680 self.current_thread()?
2681 } else {
2682 CurrentThread::None
2683 };
2684
2685 let waiting_set = match &reason {
2686 SuspendReason::Waiting { set, .. } => Some(*set),
2687 _ => None,
2688 };
2689
2690 let suspend_reason = &mut self.concurrent_state_mut()?.suspend_reason;
2691 if suspend_reason.is_some() {
2692 bail_bug!("suspend reason unexpectedly already set for store");
2693 }
2694 *suspend_reason = Some(reason);
2695
2696 if let Some(set) = waiting_set {
2699 self.concurrent_state_mut()?.get_mut(set)?.num_waiting += 1;
2700 }
2701
2702 self.with_blocking(|_, cx| cx.suspend(StoreFiberYield::ReleaseStore))?;
2703
2704 if let Some(set) = waiting_set {
2705 self.concurrent_state_mut()?.get_mut(set)?.stop_waiting()?;
2706 }
2707
2708 if save_and_restore_thread {
2709 self.set_thread(old_guest_thread)?;
2710 }
2711
2712 if let Some(item) = old_next_switch_item {
2713 let state = self.concurrent_state_mut()?;
2714 state.restore_next_switch_item(item)?;
2715 }
2716
2717 Ok(())
2718 }
2719
2720 fn wait_for_event(
2721 &mut self,
2722 caller_instance: RuntimeInstance,
2723 waitable: Waitable,
2724 ) -> Result<()> {
2725 let caller = self.current_guest_thread()?;
2726 let state = self.concurrent_state_mut()?;
2727
2728 waitable.trap_if_in_waitable_set(state)?;
2729
2730 let set = state.get_mut(caller.thread)?.sync_call_set;
2731 waitable.join(state, Some(set))?;
2732
2733 self.switch_or_trap_if_may_not_suspend(caller_instance)?;
2734
2735 self.suspend(SuspendReason::Waiting {
2736 set,
2737 thread: caller,
2738 })?;
2739 let state = self.concurrent_state_mut()?;
2740
2741 waitable.join(state, None)
2742 }
2743
2744 fn cleanup_thread(
2766 &mut self,
2767 guest_thread: QualifiedThreadId,
2768 runtime_instance: RuntimeInstance,
2769 ) -> Result<()> {
2770 let state = self.concurrent_state_mut()?;
2771 state.take_next_switch_item()?;
2774 let thread_data = state.get_mut(guest_thread.thread)?;
2775 let sync_call_set = thread_data.sync_call_set;
2776 if let Some(guest_id) = thread_data.instance_rep {
2777 self.instance_state(runtime_instance)
2778 .thread_handle_table()
2779 .guest_thread_remove(guest_id)?;
2780 }
2781 let state = self.concurrent_state_mut()?;
2782
2783 for waitable in mem::take(&mut state.get_mut(sync_call_set)?.ready) {
2785 if let Some(Event::Subtask {
2786 status: Status::Returned | Status::ReturnCancelled,
2787 }) = waitable.common(state)?.event
2788 {
2789 waitable.delete_from(state)?;
2790 }
2791 }
2792
2793 state.delete(guest_thread.thread)?;
2794 state.delete(sync_call_set)?;
2795 let task = state.get_mut(guest_thread.task)?;
2796 task.threads.remove(&guest_thread.thread);
2797
2798 if task.threads.is_empty() && !task.returned_or_cancelled() {
2799 bail!(Trap::NoAsyncResult);
2800 }
2801
2802 if !task.decremented_interesting_task_count && task.exited && task.returned_or_cancelled() {
2803 task.decremented_interesting_task_count = true;
2804
2805 debug_assert!(state.interesting_tasks > 0);
2806 state.interesting_tasks -= 1;
2807 if state.interesting_tasks == 0
2808 && let Some(waker) = state.interesting_tasks_empty_waker.take()
2809 {
2810 waker.wake();
2811 }
2812 }
2813
2814 state.decrement_task_ref_count(guest_thread.task)?;
2815
2816 Ok(())
2817 }
2818
2819 fn cancel_guest_subtask_without_lowered_parameters(
2828 &mut self,
2829 caller_instance: RuntimeInstance,
2830 guest_task: TableId<GuestTask>,
2831 ) -> Result<()> {
2832 let concurrent_state = self.concurrent_state_mut()?;
2833 let task = concurrent_state.get_mut(guest_task)?;
2834 assert!(!task.already_lowered_parameters());
2835 task.lower_params = None;
2839 task.lift_result = None;
2840 task.exited = true;
2841 let instance = task.instance;
2842
2843 assert_eq!(1, task.threads.len());
2850 let thread = *task.threads.iter().next().unwrap();
2851 let next_switch_item = concurrent_state.save_next_switch_item()?;
2852 self.cleanup_thread(
2853 QualifiedThreadId {
2854 task: guest_task,
2855 thread,
2856 },
2857 caller_instance,
2858 )?;
2859 self.concurrent_state_mut()?
2860 .restore_next_switch_item(next_switch_item)?;
2861
2862 let pending = &mut self.instance_state(instance).concurrent_state().pending;
2864 let pending_count = pending.len();
2865 let mut decrement = 0;
2866 let mut consume = |kind: &GuestCallKind| {
2867 if let GuestCallKind::StartImplicit {
2868 was_pending: true, ..
2869 } = kind
2870 {
2871 decrement += 1;
2872 }
2873 };
2874 pending.retain(|thread, kind| {
2875 if thread.task == guest_task {
2876 consume(kind);
2877 false
2878 } else {
2879 true
2880 }
2881 });
2882
2883 if pending.len() == pending_count {
2884 let mut matches = |item: &WorkItem| match item {
2887 WorkItem::ResumeThread { thread, .. } => thread.task == guest_task,
2888 WorkItem::GuestCall {
2889 call: GuestCall { thread, kind },
2890 ..
2891 } => {
2892 if thread.task == guest_task {
2893 consume(kind);
2894 true
2895 } else {
2896 false
2897 }
2898 }
2899 _ => false,
2900 };
2901
2902 let mut remove = |queue: &mut VecDeque<WorkItem>| {
2903 let count = queue.len();
2904 queue.retain(|item| !matches(item));
2905 count != queue.len()
2906 };
2907
2908 let state = self.concurrent_state_mut()?;
2909 let mut found = remove(&mut state.high_priority);
2910 found |= remove(&mut state.low_priority);
2911
2912 for item in [&mut state.switch_item, &mut state.next_switch_item] {
2913 if matches!(item, Some(item) if matches(item)) {
2914 found = true;
2915 *item = None;
2916 }
2917 }
2918
2919 if !found {
2920 bail!(Trap::SubtaskCancelAfterTerminal);
2921 }
2922 }
2923
2924 self.decrement_pending_start_count(instance, decrement)?;
2925
2926 Ok(())
2927 }
2928
2929 fn decrement_pending_start_count(
2930 &mut self,
2931 instance: RuntimeInstance,
2932 decrement: usize,
2933 ) -> Result<()> {
2934 if decrement > 0 {
2935 let count = &mut self
2936 .instance_state(instance)
2937 .concurrent_state()
2938 .pending_start_count;
2939
2940 if *count < decrement {
2941 bail_bug!("`ConcurrentInstantState::pending_start_count` underflow");
2942 }
2943
2944 *count -= decrement;
2945
2946 self.partition_pending(instance)?;
2948 }
2949
2950 Ok(())
2951 }
2952
2953 pub(crate) fn current_scope(&mut self) -> Result<Option<CurrentScope>> {
2956 if !self.concurrency_support() {
2957 return Ok(self
2958 .current_scope_id_not_concurrent()?
2959 .map(|id| CurrentScope::Id(VMScope::id(id))));
2960 }
2961
2962 Ok(match self.current_thread()? {
2963 CurrentThread::Guest(id) => Some(CurrentScope::Id(VMScope::id(id.task.rep()))),
2964 CurrentThread::Host(id) => Some(CurrentScope::Id(VMScope::host_id(id.rep()))),
2965 CurrentThread::DeferredHost(_) => Some(CurrentScope::DeferredHost),
2966 CurrentThread::None => return Ok(None),
2967 })
2968 }
2969
2970 pub(crate) fn queue_task(
2971 &mut self,
2972 task: impl FnOnce(&mut dyn VMStore) -> Result<()> + Send + 'static,
2973 ) -> Result<()> {
2974 self.concurrent_state_mut()?
2975 .push_high_priority(WorkItem::WorkerFunction(AlwaysMut::new(Box::new(task))));
2976 Ok(())
2977 }
2978
2979 fn any_may_not_suspend(&mut self) -> Result<bool> {
2988 Ok(self
2996 .concurrent_state_mut()?
2997 .table
2998 .get_mut()
2999 .iter_mut()
3000 .filter_map(|(_, entry)| {
3001 if let Some(task) = entry.entry().downcast_ref::<GuestTask>() {
3002 Some(task.instance)
3003 } else {
3004 None
3005 }
3006 })
3007 .collect::<Vec<_>>()
3008 .into_iter()
3009 .any(|instance| {
3010 self.instance_state(instance)
3011 .concurrent_state()
3012 .do_not_suspend
3013 }))
3014 }
3015}
3016
3017impl Instance {
3018 fn get_event(
3021 self,
3022 store: &mut StoreOpaque,
3023 guest_task: TableId<GuestTask>,
3024 set: Option<TableId<WaitableSet>>,
3025 cancellable: bool,
3026 ) -> Result<Option<(Event, Option<(Waitable, u32)>)>> {
3027 let state = store.concurrent_state_mut()?;
3028
3029 let task = state.get_mut(guest_task)?;
3030 let event = &mut task.event;
3031 if let Some(ev) = event
3032 && (cancellable || !matches!(ev, Event::Cancelled))
3033 {
3034 log::trace!("deliver event {ev:?} to {guest_task:?}");
3035
3036 if matches!(ev, Event::Cancelled) {
3037 task.cancel_request_delivered = true;
3038 }
3039
3040 let ev = *ev;
3041 *event = None;
3042 return Ok(Some((ev, None)));
3043 }
3044
3045 let set = match set {
3046 Some(set) => set,
3047 None => return Ok(None),
3048 };
3049 let waitable = match state.get_mut(set)?.ready.pop_first() {
3050 Some(v) => v,
3051 None => return Ok(None),
3052 };
3053
3054 let common = waitable.common(state)?;
3055 let handle = match common.handle {
3056 Some(h) => h,
3057 None => bail_bug!("handle not set when delivering event"),
3058 };
3059 let event = match common.event.take() {
3060 Some(e) => e,
3061 None => bail_bug!("event not set when delivering event"),
3062 };
3063
3064 log::trace!(
3065 "deliver event {event:?} to {guest_task:?} for {waitable:?} (handle {handle}); set {set:?}"
3066 );
3067
3068 waitable.on_delivery(store, self, event)?;
3069
3070 Ok(Some((event, Some((waitable, handle)))))
3071 }
3072
3073 fn handle_callback_code(
3080 self,
3081 store: &mut dyn VMStore,
3082 guest_thread: QualifiedThreadId,
3083 runtime_instance: RuntimeInstance,
3084 call: impl FnOnce(&mut dyn VMStore) -> Result<u32>,
3085 ) -> Result<()> {
3086 let old_thread = store.set_thread(guest_thread)?;
3087 log::trace!(
3088 "callback-lifted call: replaced {old_thread:?} with {guest_thread:?} as current thread"
3089 );
3090
3091 store.enter_instance(runtime_instance);
3092
3093 let mut code = call(store)?;
3094
3095 if matches!(
3101 unpack_callback_code(code).0,
3102 callback_code::YIELD | callback_code::WAIT
3103 ) && let Some((event, _)) = self.get_event(store, guest_thread.task, None, true)?
3104 {
3105 let (unpacked, set) = unpack_callback_code(code);
3106 log::trace!(
3107 "{guest_thread:?} returned callback code {unpacked} (set: {set}) with a pending \
3108 cancellation; delivering it via callback"
3109 );
3110 code = invoke_callback(store, guest_thread.task, event, 0)?;
3111 }
3112
3113 store.exit_instance(runtime_instance)?;
3114
3115 store.set_thread(old_thread)?;
3116 log::trace!("callback-lifted call: restored {old_thread:?} as current thread");
3117
3118 let store = &mut **store;
3119 let (code, set) = unpack_callback_code(code);
3120
3121 log::trace!("received callback code from {guest_thread:?}: {code} (set: {set})");
3122
3123 let state = store.concurrent_state_mut()?;
3124
3125 state.take_next_switch_item()?;
3126
3127 let get_set = |store: &mut StoreOpaque, handle| -> Result<_> {
3128 let set = store
3129 .instance_state(runtime_instance)
3130 .handle_table()
3131 .waitable_set_rep(handle)?;
3132
3133 Ok(TableId::<WaitableSet>::new(set))
3134 };
3135
3136 match code {
3137 callback_code::EXIT => {
3138 log::trace!("implicit thread {guest_thread:?} completed");
3139 let task = store.concurrent_state_mut()?.get_mut(guest_thread.task)?;
3140 task.exited = true;
3141 task.callback = None;
3142
3143 store.switch_or_trap_if_may_not_suspend(runtime_instance)?;
3148
3149 store.cleanup_thread(guest_thread, runtime_instance)?;
3150 }
3151 callback_code::YIELD => {
3152 let old = state
3155 .get_mut(guest_thread.thread)?
3156 .wake_on_cancel
3157 .replace(WakeOnCancel::Yielding);
3158 if !old.is_none() {
3159 bail_bug!("thread unexpectedly had wake_on_cancel set");
3160 }
3161
3162 let call = GuestCall {
3169 thread: guest_thread,
3170 kind: GuestCallKind::DeliverEvent {
3171 instance: self,
3172 set: None,
3173 },
3174 };
3175 state.push_low_priority(WorkItem::GuestCall {
3178 instance: runtime_instance,
3179 call,
3180 });
3181 }
3182 callback_code::WAIT => {
3183 let set = get_set(store, set)?;
3184 self.wait_with_callback(store, guest_thread, set)?;
3185 }
3186 _ => bail!(Trap::UnsupportedCallbackCode),
3187 }
3188
3189 Ok(())
3190 }
3191
3192 fn wait_with_callback(
3198 self,
3199 store: &mut StoreOpaque,
3200 guest_thread: QualifiedThreadId,
3201 set: TableId<WaitableSet>,
3202 ) -> Result<()> {
3203 let state = store.concurrent_state_mut()?;
3204 state.get_mut(set)?.num_waiting += 1;
3207
3208 if state.get_mut(guest_thread.task)?.event.is_some()
3209 || !state.get_mut(set)?.ready.is_empty()
3210 {
3211 let instance = state.get_mut(guest_thread.task)?.instance;
3213 state.push_high_priority(WorkItem::GuestCall {
3214 instance,
3215 call: GuestCall {
3216 thread: guest_thread,
3217 kind: GuestCallKind::DeliverEvent {
3218 instance: self,
3219 set: Some(set),
3220 },
3221 },
3222 });
3223 return Ok(());
3224 }
3225
3226 let instance = store
3232 .concurrent_state_mut()?
3233 .get_mut(guest_thread.task)?
3234 .instance;
3235 store.switch_or_trap_if_may_not_suspend(instance)?;
3236
3237 let state = store.concurrent_state_mut()?;
3243 let old = state
3244 .get_mut(guest_thread.thread)?
3245 .wake_on_cancel
3246 .replace(WakeOnCancel::Waiting(set));
3247 if !old.is_none() {
3248 bail_bug!("thread unexpectedly had wake_on_cancel set");
3249 }
3250 let old = state
3251 .get_mut(set)?
3252 .waiting
3253 .insert(guest_thread, WaitMode::Callback(self));
3254 if !old.is_none() {
3255 bail_bug!("set's waiting set already had this thread registered");
3256 }
3257 Ok(())
3258 }
3259
3260 unsafe fn stage_call<T: 'static>(
3267 self,
3268 mut store: StoreContextMut<T>,
3269 guest_thread: QualifiedThreadId,
3270 callee: SendSyncPtr<VMFuncRef>,
3271 param_count: usize,
3272 result_count: usize,
3273 async_: bool,
3274 callback: Option<SendSyncPtr<VMFuncRef>>,
3275 post_return: Option<SendSyncPtr<VMFuncRef>>,
3276 host_caller: bool,
3277 ) -> Result<()> {
3278 unsafe fn make_call<T: 'static>(
3293 store: StoreContextMut<T>,
3294 guest_thread: QualifiedThreadId,
3295 callee: SendSyncPtr<VMFuncRef>,
3296 param_count: usize,
3297 result_count: usize,
3298 ) -> impl FnOnce(&mut dyn VMStore) -> Result<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>
3299 + Send
3300 + Sync
3301 + 'static
3302 + use<T> {
3303 let token = StoreToken::new(store);
3304 move |store: &mut dyn VMStore| {
3305 let mut storage = [MaybeUninit::uninit(); MAX_FLAT_PARAMS];
3306
3307 store
3308 .concurrent_state_mut()?
3309 .set_thread_running(guest_thread.thread)?;
3310 let task = store.concurrent_state_mut()?.get_mut(guest_thread.task)?;
3311 let lower = match task.lower_params.take() {
3312 Some(l) => l,
3313 None => bail_bug!("lower_params missing"),
3314 };
3315
3316 lower(store, &mut storage[..param_count])?;
3317
3318 let mut store = token.as_context_mut(store);
3319
3320 unsafe {
3323 crate::Func::call_unchecked_raw(
3324 &mut store,
3325 callee.as_non_null(),
3326 NonNull::new(
3327 &mut storage[..param_count.max(result_count)]
3328 as *mut [MaybeUninit<ValRaw>] as _,
3329 )
3330 .unwrap(),
3331 UncaughtException::Trap,
3332 )?;
3333 }
3334
3335 Ok(storage)
3336 }
3337 }
3338
3339 let call = unsafe {
3343 make_call(
3344 store.as_context_mut(),
3345 guest_thread,
3346 callee,
3347 param_count,
3348 result_count,
3349 )
3350 };
3351
3352 let callee_instance = store
3353 .0
3354 .concurrent_state_mut()?
3355 .get_mut(guest_thread.task)?
3356 .instance;
3357
3358 let fun = if callback.is_some() {
3359 assert!(async_);
3360
3361 Box::new(move |store: &mut dyn VMStore| {
3362 self.add_guest_thread_to_instance_table(
3363 guest_thread.thread,
3364 store,
3365 callee_instance.index,
3366 )?;
3367 self.handle_callback_code(store, guest_thread, callee_instance, |store| {
3368 let storage = call(store)?;
3369
3370 Ok(unsafe { storage[0].assume_init() }.get_i32() as u32)
3373 })
3374 }) as Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send + Sync>
3375 } else {
3376 let token = StoreToken::new(store.as_context_mut());
3377 Box::new(move |store: &mut dyn VMStore| {
3378 self.add_guest_thread_to_instance_table(
3379 guest_thread.thread,
3380 store,
3381 callee_instance.index,
3382 )?;
3383 let old_thread = store.set_thread(guest_thread)?;
3384 log::trace!(
3385 "sync/async-stackful call: replaced {old_thread:?} with {guest_thread:?} as current thread",
3386 );
3387 let flags = self.id().get(store).instance_flags(callee_instance.index);
3388
3389 let callee_async_typed = store
3390 .concurrent_state_mut()?
3391 .get_mut(guest_thread.task)?
3392 .async_typed;
3393
3394 if !async_ && callee_async_typed {
3398 store.enter_instance(callee_instance);
3399 }
3400
3401 if !callee_async_typed {
3402 store.enter_sync_call(callee_instance)?;
3403 }
3404
3405 let storage = call(store)?;
3412
3413 if !callee_async_typed {
3414 store.exit_sync_call(callee_instance)?;
3415 }
3416
3417 if !async_ {
3418 if callee_async_typed {
3424 store.exit_instance(callee_instance)?;
3425 }
3426
3427 let lift = {
3428 let state = store.concurrent_state_mut()?;
3429 if !state.get_mut(guest_thread.task)?.result.is_none() {
3430 bail_bug!("task has already produced a result");
3431 }
3432
3433 match state.get_mut(guest_thread.task)?.lift_result.take() {
3434 Some(lift) => lift,
3435 None => bail_bug!("lift_result field is missing"),
3436 }
3437 };
3438
3439 let result = (lift.lift)(store, unsafe {
3442 mem::transmute::<&[MaybeUninit<ValRaw>], &[ValRaw]>(
3443 &storage[..result_count],
3444 )
3445 })?;
3446
3447 let post_return_arg = match result_count {
3448 0 => ValRaw::i32(0),
3449 1 => unsafe { storage[0].assume_init() },
3452 _ => unreachable!(),
3453 };
3454
3455 unsafe {
3456 call_post_return(
3457 token.as_context_mut(store),
3458 post_return.map(|v| v.as_non_null()),
3459 post_return_arg,
3460 flags,
3461 )?;
3462 }
3463
3464 self.task_complete(store, guest_thread.task, result, Status::Returned)?;
3465 }
3466
3467 store.set_thread(old_thread)?;
3468
3469 store
3470 .concurrent_state_mut()?
3471 .get_mut(guest_thread.task)?
3472 .exited = true;
3473
3474 log::trace!(
3475 "clean up thread; async lifted? {async_} async typed? {callee_async_typed}"
3476 );
3477
3478 if callee_async_typed {
3479 store.switch_or_trap_if_may_not_suspend(callee_instance)?;
3484 }
3485
3486 store.cleanup_thread(guest_thread, callee_instance)?;
3488 Ok(())
3489 })
3490 };
3491
3492 store.0.concurrent_state_mut()?.push_work_item(
3493 WorkItem::GuestCall {
3494 instance: callee_instance,
3495 call: GuestCall {
3496 thread: guest_thread,
3497 kind: GuestCallKind::StartImplicit {
3498 closure: fun,
3499 was_pending: false,
3500 },
3501 },
3502 },
3503 if host_caller {
3504 Priority::Low
3510 } else {
3511 Priority::Switch
3512 },
3513 )?;
3514
3515 Ok(())
3516 }
3517
3518 unsafe fn prepare_call<T: 'static>(
3531 self,
3532 mut store: StoreContextMut<T>,
3533 start: NonNull<VMFuncRef>,
3534 return_: NonNull<VMFuncRef>,
3535 caller_instance: RuntimeComponentInstanceIndex,
3536 callee_instance: RuntimeComponentInstanceIndex,
3537 task_return_type: TypeTupleIndex,
3538 callee_async_typed: bool,
3539 memory: *mut VMMemoryDefinition,
3540 string_encoding: StringEncoding,
3541 caller_info: CallerInfo,
3542 ) -> Result<()> {
3543 enum ResultInfo {
3544 Heap { results: u32 },
3545 Stack { result_count: u32 },
3546 }
3547
3548 let result_info = match &caller_info {
3549 CallerInfo::Async {
3550 has_result: true,
3551 params,
3552 } => ResultInfo::Heap {
3553 results: match params.last() {
3555 Some(r) => r.get_u32(),
3556 None => bail_bug!("retptr missing"),
3557 },
3558 },
3559 CallerInfo::Async {
3560 has_result: false, ..
3561 } => ResultInfo::Stack { result_count: 0 },
3562 CallerInfo::Sync {
3563 result_count,
3564 params,
3565 } if *result_count > u32::try_from(MAX_FLAT_RESULTS)? => ResultInfo::Heap {
3566 results: match params.last() {
3568 Some(r) => r.get_u32(),
3569 None => bail_bug!("arg ptr missing"),
3570 },
3571 },
3572 CallerInfo::Sync { result_count, .. } => ResultInfo::Stack {
3573 result_count: *result_count,
3574 },
3575 };
3576
3577 let sync_caller = matches!(caller_info, CallerInfo::Sync { .. });
3578
3579 let start = SendSyncPtr::new(start);
3583 let return_ = SendSyncPtr::new(return_);
3584 let token = StoreToken::new(store.as_context_mut());
3585 let old_thread = store.0.current_guest_thread()?;
3586
3587 let state = store.0.concurrent_state_mut()?;
3588
3589 debug_assert_eq!(
3590 state.get_mut(old_thread.task)?.instance,
3591 self.runtime_instance(caller_instance)
3592 );
3593
3594 let guest_thread = GuestTask::new(
3595 state,
3596 Box::new(move |store, dst| {
3597 let mut store = token.as_context_mut(store);
3598 assert!(dst.len() <= MAX_FLAT_PARAMS);
3599 let mut src = [MaybeUninit::uninit(); MAX_FLAT_PARAMS + 1];
3601 let count = match caller_info {
3602 CallerInfo::Async { params, has_result } => {
3606 let params = ¶ms[..params.len() - usize::from(has_result)];
3607 for (param, src) in params.iter().zip(&mut src) {
3608 src.write(*param);
3609 }
3610 params.len()
3611 }
3612
3613 CallerInfo::Sync { params, .. } => {
3615 for (param, src) in params.iter().zip(&mut src) {
3616 src.write(*param);
3617 }
3618 params.len()
3619 }
3620 };
3621 unsafe {
3628 crate::Func::call_unchecked_raw(
3629 &mut store,
3630 start.as_non_null(),
3631 NonNull::new(
3632 &mut src[..count.max(dst.len())] as *mut [MaybeUninit<ValRaw>] as _,
3633 )
3634 .unwrap(),
3635 UncaughtException::Trap,
3636 )?;
3637 }
3638 dst.copy_from_slice(&src[..dst.len()]);
3639 let task = store.0.current_guest_thread()?.task;
3640 let state = store.0.concurrent_state_mut()?;
3641 Waitable::Guest(task).set_event(
3642 state,
3643 Some(Event::Subtask {
3644 status: Status::Started,
3645 }),
3646 )?;
3647 Ok(())
3648 }),
3649 LiftResult {
3650 lift: Box::new(move |store, src| {
3651 let mut store = token.as_context_mut(store);
3654 let mut my_src = src.to_owned(); if let ResultInfo::Heap { results } = &result_info {
3656 my_src.push(ValRaw::u32(*results));
3657 }
3658
3659 unsafe {
3666 crate::Func::call_unchecked_raw(
3667 &mut store,
3668 return_.as_non_null(),
3669 my_src.as_mut_slice().into(),
3670 UncaughtException::Trap,
3671 )?;
3672 }
3673
3674 let thread = store.0.current_guest_thread()?;
3675 let state = store.0.concurrent_state_mut()?;
3676 if sync_caller {
3677 state.get_mut(thread.task)?.sync_result = SyncResult::Produced(
3678 if let ResultInfo::Stack { result_count } = &result_info {
3679 match result_count {
3680 0 => None,
3681 1 => Some(my_src[0]),
3682 _ => unreachable!(),
3683 }
3684 } else {
3685 None
3686 },
3687 );
3688 }
3689 Ok(Box::new(DummyResult) as Box<dyn Any + Send + Sync>)
3690 }),
3691 ty: task_return_type,
3692 memory: NonNull::new(memory).map(SendSyncPtr::new),
3693 string_encoding,
3694 },
3695 Caller::Guest { thread: old_thread },
3696 None,
3697 self.runtime_instance(callee_instance),
3698 callee_async_typed,
3699 false,
3702 )?;
3703
3704 store.0.set_thread(guest_thread)?;
3707 log::trace!("pushed {guest_thread:?} as current thread; old thread was {old_thread:?}");
3708
3709 Ok(())
3710 }
3711
3712 unsafe fn call_callback<T>(
3717 self,
3718 mut store: StoreContextMut<T>,
3719 function: SendSyncPtr<VMFuncRef>,
3720 event: Event,
3721 handle: u32,
3722 ) -> Result<u32> {
3723 let (ordinal, result) = event.parts();
3724 let params = &mut [
3725 ValRaw::u32(ordinal),
3726 ValRaw::u32(handle),
3727 ValRaw::u32(result),
3728 ];
3729 unsafe {
3734 crate::Func::call_unchecked_raw(
3735 &mut store,
3736 function.as_non_null(),
3737 params.as_mut_slice().into(),
3738 UncaughtException::Trap,
3739 )?;
3740 }
3741 Ok(params[0].get_u32())
3742 }
3743
3744 unsafe fn start_call<T: 'static>(
3762 self,
3763 mut store: StoreContextMut<T>,
3764 callback: *mut VMFuncRef,
3765 post_return: *mut VMFuncRef,
3766 callee: NonNull<VMFuncRef>,
3767 param_count: u32,
3768 result_count: u32,
3769 flags: u32,
3770 storage: &mut [MaybeUninit<ValRaw>],
3771 ) -> Result<()> {
3772 let token = StoreToken::new(store.as_context_mut());
3773 let async_caller = (flags & START_FLAG_ASYNC_CALLER) != 0;
3774 let guest_thread = store.0.current_guest_thread()?;
3775 let state = store.0.concurrent_state_mut()?;
3776
3777 if !state.event_loop_running {
3782 bail!(
3783 "async function started during an original synchronous \
3784 entrypoint; please use an async-style entrypoint instead"
3785 );
3786 }
3787
3788 let callee = SendSyncPtr::new(callee);
3789 let param_count = usize::try_from(param_count)?;
3790 assert!(param_count <= MAX_FLAT_PARAMS);
3791 let result_count = usize::try_from(result_count)?;
3792 assert!(result_count <= MAX_FLAT_RESULTS);
3793
3794 let task = state.get_mut(guest_thread.task)?;
3795 let callee_async_typed = task.async_typed;
3796 let callee_instance = task.instance;
3797
3798 task.async_lifted = (flags & START_FLAG_ASYNC_CALLEE) != 0;
3799
3800 if let Some(callback) = NonNull::new(callback) {
3801 let callback = SendSyncPtr::new(callback);
3805 task.callback = Some(Box::new(move |store, event, handle| {
3806 let store = token.as_context_mut(store);
3807 unsafe { self.call_callback::<T>(store, callback, event, handle) }
3808 }));
3809 }
3810
3811 let Caller::Guest { thread: caller } = &task.caller else {
3812 bail_bug!("start_call unexpectedly invoked for host->guest call");
3815 };
3816 let caller = *caller;
3817 let caller_instance = state.get_mut(caller.task)?.instance;
3818
3819 unsafe {
3821 self.stage_call(
3822 store.as_context_mut(),
3823 guest_thread,
3824 callee,
3825 param_count,
3826 result_count,
3827 (flags & START_FLAG_ASYNC_CALLEE) != 0,
3828 NonNull::new(callback).map(SendSyncPtr::new),
3829 NonNull::new(post_return).map(SendSyncPtr::new),
3830 false,
3831 )?;
3832 }
3833
3834 let old_do_not_suspend = if callee_async_typed {
3835 let state = store.0.instance_state(callee_instance).concurrent_state();
3842 let old_do_not_suspend = state.do_not_suspend;
3843 state.do_not_suspend = false;
3844 Some(old_do_not_suspend)
3845 } else {
3846 None
3847 };
3848
3849 let state = store.0.concurrent_state_mut()?;
3850
3851 let guest_waitable = Waitable::Guest(guest_thread.task);
3854 let old_set = guest_waitable.common(state)?.set;
3855 let set = state.get_mut(caller.thread)?.sync_call_set;
3856 guest_waitable.join(state, Some(set))?;
3857
3858 store.0.set_thread(CurrentThread::None)?;
3859
3860 let mut yielded = false;
3876 let (status, waitable) = loop {
3877 store.0.suspend(if yielded {
3878 SuspendReason::Waiting {
3879 set,
3880 thread: caller,
3881 }
3882 } else {
3883 yielded = true;
3884 SuspendReason::YieldingToSubtask { thread: caller }
3885 })?;
3886
3887 if let Some(old_do_not_suspend) = old_do_not_suspend {
3888 store
3889 .0
3890 .instance_state(callee_instance)
3891 .concurrent_state()
3892 .do_not_suspend = old_do_not_suspend;
3893 }
3894
3895 let state = store.0.concurrent_state_mut()?;
3896
3897 log::trace!("taking event for {:?}", guest_thread.task);
3898 let event = guest_waitable.take_event(state)?;
3899 let Some(Event::Subtask { status }) = event else {
3900 bail_bug!("subtasks should only get subtask events, got {event:?}")
3901 };
3902
3903 log::trace!("status {status:?} for {:?}", guest_thread.task);
3904
3905 if status == Status::Returned {
3906 break (status, None);
3908 } else if async_caller {
3909 let handle = store
3913 .0
3914 .handle_table_insertion(caller_instance)
3915 .subtask_guest(guest_thread.task.rep())?;
3916 store
3917 .0
3918 .concurrent_state_mut()?
3919 .get_mut(guest_thread.task)?
3920 .common
3921 .handle = Some(handle);
3922 break (status, Some(handle));
3923 } else {
3924 store.0.switch_or_trap_if_may_not_suspend(caller_instance)?;
3928 }
3929 };
3930
3931 guest_waitable.join(store.0.concurrent_state_mut()?, old_set)?;
3932
3933 store.0.set_thread(caller)?;
3935
3936 store
3937 .0
3938 .concurrent_state_mut()?
3939 .set_thread_running(caller.thread)?;
3940
3941 log::trace!("popped current thread {guest_thread:?}; new thread is {caller:?}");
3942
3943 if async_caller {
3944 let Some(slot) = storage.first_mut() else {
3945 bail_bug!("no storage for async call status");
3946 };
3947 *slot = MaybeUninit::new(ValRaw::u32(status.pack(waitable)));
3948 } else {
3949 let state = store.0.concurrent_state_mut()?;
3952 let task = state.get_mut(guest_thread.task)?;
3953 if let Some(Some(result)) = task.sync_result.take()? {
3954 storage[0] = MaybeUninit::new(result);
3955 }
3956 }
3957
3958 if status == Status::Returned {
3959 store
3960 .0
3961 .concurrent_state_mut()?
3962 .decrement_task_ref_count(guest_thread.task)?;
3963 }
3964
3965 Ok(())
3966 }
3967
3968 pub(crate) fn first_poll<T: 'static, R: Send + 'static>(
3984 self,
3985 mut store: StoreContextMut<'_, T>,
3986 host_task: EnteredHostTask,
3987 result_may_require_realloc: bool,
3988 future: impl Future<Output = Result<R>> + Send + 'static,
3989 lower: impl FnOnce(StoreContextMut<T>, Option<R>, bool, Option<TableId<HostTask>>) -> Result<()>
3990 + Send
3991 + 'static,
3992 ) -> Result<u32> {
3993 let token = StoreToken::new(store.as_context_mut());
3994
3995 let (join_handle, future) = JoinHandle::run(future);
3998 let mut future = Box::pin(future);
3999
4000 let poll = tls::set(store.0, || {
4005 future
4006 .as_mut()
4007 .poll(&mut Context::from_waker(&Waker::noop()))
4008 });
4009
4010 match poll {
4011 Poll::Ready(result) => {
4013 let result = result.transpose()?;
4014 let task = store.0.current_materialized_host_task()?;
4017 lower(store.as_context_mut(), result, true, task)?;
4018 return Ok(Status::Returned.pack(None));
4019 }
4020
4021 Poll::Pending => {}
4023 }
4024
4025 let Some(task) = store.0.materialize_host_task_id()? else {
4029 bail_bug!("current thread is not a host thread")
4030 };
4031 {
4032 let state = &mut store.0.concurrent_state_mut()?.get_mut(task)?.state;
4033 assert!(matches!(state, HostTaskState::CalleeStarted));
4034 *state = HostTaskState::CalleeRunning(join_handle);
4035 }
4036
4037 let future = Box::pin(async move {
4045 let result = match run_with_host_task_set(task, future).await? {
4046 Some(result) => Some(result?),
4047 None => None,
4048 };
4049 let on_complete = move |store: &mut dyn VMStore| {
4050 let mut store = token.as_context_mut(store);
4054 let old = store.0.set_thread(task)?;
4055
4056 let status = if result.is_some() {
4057 Status::Returned
4058 } else {
4059 Status::ReturnCancelled
4060 };
4061
4062 lower(store.as_context_mut(), result, false, Some(task))?;
4063 let state = store.0.concurrent_state_mut()?;
4064 match &mut state.get_mut(task)?.state {
4065 pending @ HostTaskState::CalleeCancelling => {
4068 *pending = HostTaskState::CalleeDone { cancelled: true };
4069 }
4070
4071 other => *other = HostTaskState::CalleeDone { cancelled: false },
4073 }
4074 Waitable::Host(task).set_event(state, Some(Event::Subtask { status }))?;
4075
4076 store.0.set_thread(old)?;
4077 Ok(())
4078 };
4079
4080 tls::get(move |store| {
4081 if result_may_require_realloc {
4082 store
4087 .concurrent_state_mut()?
4088 .push_high_priority(WorkItem::WorkerFunction(AlwaysMut::new(Box::new(
4089 on_complete,
4090 ))));
4091 Ok(())
4092 } else {
4093 on_complete(store)
4096 }
4097 })
4098 });
4099
4100 let caller = match host_task {
4103 Some(caller) => caller,
4104 None => bail_bug!("host task wasn't created but should have been"),
4105 };
4106 let state = store.0.concurrent_state_mut()?;
4107 state.push_future(future);
4108 let instance = state.get_mut(caller.task)?.instance;
4109 let handle = store
4110 .0
4111 .handle_table_insertion(instance)
4112 .subtask_host(task.rep())?;
4113 store.0.concurrent_state_mut()?.get_mut(task)?.common.handle = Some(handle);
4114 log::trace!("assign {task:?} handle {handle} for {caller:?} instance {instance:?}");
4115
4116 store.0.set_thread(caller)?;
4120 Ok(Status::Started.pack(Some(handle)))
4121 }
4122
4123 pub(crate) fn task_return(
4126 self,
4127 store: &mut dyn VMStore,
4128 ty: TypeTupleIndex,
4129 options: OptionsIndex,
4130 storage: &[ValRaw],
4131 ) -> Result<()> {
4132 let guest_thread = store.current_guest_thread()?;
4133 let state = store.concurrent_state_mut()?;
4134 if !state.get_mut(guest_thread.task)?.async_lifted {
4135 bail!(Trap::TaskReturnOrCancelSyncLifted);
4136 }
4137 let lift = state
4138 .get_mut(guest_thread.task)?
4139 .lift_result
4140 .take()
4141 .ok_or_else(|| Trap::TaskCancelOrReturnTwice)?;
4142 if !state.get_mut(guest_thread.task)?.result.is_none() {
4143 bail_bug!("task result unexpectedly already set");
4144 }
4145
4146 let CanonicalOptions {
4147 string_encoding,
4148 data_model,
4149 ..
4150 } = &self.id().get(store).component().env_component().options[options];
4151
4152 let invalid = ty != lift.ty
4153 || string_encoding != &lift.string_encoding
4154 || match data_model {
4155 CanonicalOptionsDataModel::LinearMemory(opts) => match opts.memory {
4156 Some(memory) => {
4157 let expected = lift.memory.map(|v| v.as_ptr()).unwrap_or(ptr::null_mut());
4158 let actual = self.id().get(store).runtime_memory(memory);
4159 expected != actual.as_ptr()
4160 }
4161 None => false,
4164 },
4165 CanonicalOptionsDataModel::Gc { .. } => true,
4167 };
4168
4169 if invalid {
4170 bail!(Trap::TaskReturnInvalid);
4171 }
4172
4173 log::trace!("task.return for {guest_thread:?}");
4174
4175 let result = (lift.lift)(store, storage)?;
4176 self.task_complete(store, guest_thread.task, result, Status::Returned)
4177 }
4178
4179 pub(crate) fn task_cancel(self, store: &mut StoreOpaque) -> Result<()> {
4181 let guest_thread = store.current_guest_thread()?;
4182 let state = store.concurrent_state_mut()?;
4183 let task = state.get_mut(guest_thread.task)?;
4184 if !task.async_lifted {
4185 bail!(Trap::TaskReturnOrCancelSyncLifted);
4186 }
4187 if !task.cancel_request_delivered {
4188 bail!(Trap::TaskCancelNotCancelled);
4189 }
4190 _ = task
4191 .lift_result
4192 .take()
4193 .ok_or_else(|| Trap::TaskCancelOrReturnTwice)?;
4194
4195 if !task.result.is_none() {
4196 bail_bug!("task result should not bet set yet");
4197 }
4198
4199 log::trace!("task.cancel for {guest_thread:?}");
4200
4201 self.task_complete(
4202 store,
4203 guest_thread.task,
4204 Box::new(DummyResult),
4205 Status::ReturnCancelled,
4206 )
4207 }
4208
4209 fn task_complete(
4215 self,
4216 store: &mut StoreOpaque,
4217 guest_task: TableId<GuestTask>,
4218 result: Box<dyn Any + Send + Sync>,
4219 status: Status,
4220 ) -> Result<()> {
4221 store
4222 .component_resource_tables(Some(self))?
4223 .validate_scope_exit()?;
4224
4225 let state = store.concurrent_state_mut()?;
4226 let task = state.get_mut(guest_task)?;
4227
4228 task.event = None;
4232
4233 if let Caller::Host { tx, .. } = &mut task.caller {
4234 if let Some(tx) = tx.take() {
4235 _ = tx.send(result);
4236 }
4237 } else {
4238 task.result = Some(result);
4239 Waitable::Guest(guest_task).set_event(state, Some(Event::Subtask { status }))?;
4240 }
4241
4242 Ok(())
4243 }
4244
4245 pub(crate) fn waitable_set_new(
4247 self,
4248 store: &mut StoreOpaque,
4249 caller_instance: RuntimeComponentInstanceIndex,
4250 ) -> Result<u32> {
4251 let set = store.concurrent_state_mut()?.push(WaitableSet::default())?;
4252 let handle = store
4253 .handle_table_insertion(self.runtime_instance(caller_instance))
4254 .waitable_set(set.rep())?;
4255 log::trace!("new waitable set {set:?} (handle {handle})");
4256 Ok(handle)
4257 }
4258
4259 pub(crate) fn waitable_set_drop(
4261 self,
4262 store: &mut StoreOpaque,
4263 caller_instance: RuntimeComponentInstanceIndex,
4264 set: u32,
4265 ) -> Result<()> {
4266 let rep = store
4267 .instance_state(self.runtime_instance(caller_instance))
4268 .handle_table()
4269 .waitable_set_remove(set)?;
4270
4271 log::trace!("drop waitable set {rep} (handle {set})");
4272
4273 let set = store
4277 .concurrent_state_mut()?
4278 .get_mut(TableId::<WaitableSet>::new(rep))?;
4279 if set.num_waiting > 0 {
4280 bail!(Trap::WaitableSetDropHasWaiters);
4281 }
4282
4283 store
4284 .concurrent_state_mut()?
4285 .delete(TableId::<WaitableSet>::new(rep))?;
4286
4287 Ok(())
4288 }
4289
4290 pub(crate) fn waitable_join(
4292 self,
4293 store: &mut StoreOpaque,
4294 caller_instance: RuntimeComponentInstanceIndex,
4295 waitable_handle: u32,
4296 set_handle: u32,
4297 ) -> Result<()> {
4298 let mut instance = self.id().get_mut(store);
4299 let waitable =
4300 Waitable::from_instance(instance.as_mut(), caller_instance, waitable_handle)?;
4301
4302 let set = if set_handle == 0 {
4303 None
4304 } else {
4305 let set = instance.instance_states().0[caller_instance]
4306 .handle_table()
4307 .waitable_set_rep(set_handle)?;
4308
4309 Some(TableId::<WaitableSet>::new(set))
4310 };
4311
4312 waitable.trap_if_has_sync_waiter(store.concurrent_state_mut()?)?;
4313
4314 log::trace!(
4315 "waitable {waitable:?} (handle {waitable_handle}) join set {set:?} (handle {set_handle})",
4316 );
4317
4318 waitable.join(store.concurrent_state_mut()?, set)
4319 }
4320
4321 pub(crate) fn subtask_drop(
4323 self,
4324 store: &mut StoreOpaque,
4325 caller_instance: RuntimeComponentInstanceIndex,
4326 task_id: u32,
4327 ) -> Result<()> {
4328 self.waitable_join(store, caller_instance, task_id, 0)?;
4329
4330 let (rep, is_host) = store
4331 .instance_state(self.runtime_instance(caller_instance))
4332 .handle_table()
4333 .subtask_remove(task_id)?;
4334
4335 let concurrent_state = store.concurrent_state_mut()?;
4336 let waitable = if is_host {
4337 let id = TableId::<HostTask>::new(rep);
4338 let task = concurrent_state.get_mut(id)?;
4339 match &task.state {
4340 HostTaskState::CalleeRunning(_) | HostTaskState::CalleeCancelling => {
4341 bail!(Trap::SubtaskDropNotResolved)
4342 }
4343 HostTaskState::CalleeDone { .. } => {}
4344 HostTaskState::CalleeStarted | HostTaskState::CalleeFinished(_) => {
4345 bail_bug!("invalid state for callee in `subtask.drop`")
4346 }
4347 }
4348
4349 Waitable::Host(id)
4350 } else {
4351 let id = TableId::<GuestTask>::new(rep);
4352 let task = concurrent_state.get_mut(id)?;
4353 if task.lift_result.is_some() {
4354 bail!(Trap::SubtaskDropNotResolved);
4355 }
4356 Waitable::Guest(id)
4357 };
4358
4359 waitable.common(concurrent_state)?.handle = None;
4360
4361 if waitable.take_event(concurrent_state)?.is_some() {
4364 bail!(Trap::SubtaskDropNotResolved);
4365 }
4366
4367 waitable.delete_from(concurrent_state)?;
4368
4369 log::trace!("subtask_drop {waitable:?} (handle {task_id})");
4370 Ok(())
4371 }
4372
4373 pub(crate) fn waitable_set_wait(
4375 self,
4376 store: &mut StoreOpaque,
4377 options: OptionsIndex,
4378 set: u32,
4379 payload: u32,
4380 ) -> Result<u32> {
4381 let &CanonicalOptions {
4382 instance: caller_instance,
4383 ..
4384 } = &self.id().get(store).component().env_component().options[options];
4385 let caller = self.runtime_instance(caller_instance);
4386 let rep = store
4387 .instance_state(self.runtime_instance(caller_instance))
4388 .handle_table()
4389 .waitable_set_rep(set)?;
4390
4391 self.waitable_check(
4392 store,
4393 caller,
4394 WaitableCheck::Wait,
4395 WaitableCheckParams {
4396 set: TableId::new(rep),
4397 options,
4398 payload,
4399 },
4400 )
4401 }
4402
4403 pub(crate) fn waitable_set_poll(
4405 self,
4406 store: &mut StoreOpaque,
4407 options: OptionsIndex,
4408 set: u32,
4409 payload: u32,
4410 ) -> Result<u32> {
4411 let &CanonicalOptions {
4412 instance: caller_instance,
4413 ..
4414 } = &self.id().get(store).component().env_component().options[options];
4415 let caller = self.runtime_instance(caller_instance);
4416 let rep = store
4417 .instance_state(caller)
4418 .handle_table()
4419 .waitable_set_rep(set)?;
4420
4421 self.waitable_check(
4422 store,
4423 caller,
4424 WaitableCheck::Poll,
4425 WaitableCheckParams {
4426 set: TableId::new(rep),
4427 options,
4428 payload,
4429 },
4430 )
4431 }
4432
4433 pub(crate) fn thread_index(&self, store: &mut dyn VMStore) -> Result<u32> {
4435 let thread_id = store.current_guest_thread()?.thread;
4436 match store
4437 .concurrent_state_mut()?
4438 .get_mut(thread_id)?
4439 .instance_rep
4440 {
4441 Some(r) => Ok(r),
4442 None => bail_bug!("thread should have instance_rep by now"),
4443 }
4444 }
4445
4446 pub(crate) fn thread_new_indirect<T: 'static>(
4448 self,
4449 mut store: StoreContextMut<T>,
4450 runtime_instance: RuntimeComponentInstanceIndex,
4451 start_func_ty: ModuleInternedTypeIndex,
4452 start_func_table_idx: RuntimeTableIndex,
4453 start_func_idx: u32,
4454 context: i32,
4455 ) -> Result<u32> {
4456 log::trace!("creating new thread");
4457
4458 let (instance, registry) = self.id().get_mut_and_registry(store.0);
4459 let Some(start_func_ty) = instance.component().signatures().shared_type(start_func_ty)
4460 else {
4461 bail_bug!("thread.new-indirect start function type should be registered");
4462 };
4463 let callee = instance
4464 .index_runtime_func_table(registry, start_func_table_idx, start_func_idx as u64)?
4465 .ok_or_else(|| Trap::ThreadNewIndirectUninitialized)?;
4466 if callee.type_index(store.0) != start_func_ty {
4467 bail!(Trap::ThreadNewIndirectInvalidType);
4468 }
4469
4470 let token = StoreToken::new(store.as_context_mut());
4471 let start_func = Box::new(
4472 move |store: &mut dyn VMStore, guest_thread: QualifiedThreadId| -> Result<()> {
4473 let old_thread = store.set_thread(guest_thread)?;
4474 log::trace!(
4475 "thread start: replaced {old_thread:?} with {guest_thread:?} as current thread"
4476 );
4477
4478 let mut store = token.as_context_mut(store);
4479 let mut params = [ValRaw::i32(context)];
4480 let func_ref = callee.vm_func_ref(store.0);
4484 unsafe {
4485 crate::Func::call_unchecked_raw(
4486 &mut store,
4487 func_ref,
4488 NonNull::from(&mut params[..]),
4489 UncaughtException::Trap,
4490 )?;
4491 }
4492
4493 store.0.set_thread(old_thread)?;
4494
4495 let runtime_instance = self.runtime_instance(runtime_instance);
4496
4497 store
4500 .0
4501 .switch_or_trap_if_may_not_suspend(runtime_instance)?;
4502
4503 store.0.cleanup_thread(guest_thread, runtime_instance)?;
4504
4505 log::trace!("explicit thread {guest_thread:?} completed");
4506 let state = store.0.concurrent_state_mut()?;
4507 if let Some(t) = old_thread.guest() {
4508 state.set_thread_running(t.thread)?;
4509 }
4510 log::trace!("thread start: restored {old_thread:?} as current thread");
4511
4512 Ok(())
4513 },
4514 );
4515
4516 let current_thread = store.0.current_guest_thread()?;
4517 let state = store.0.concurrent_state_mut()?;
4518 let parent_task = current_thread.task;
4519
4520 let new_thread = GuestThread::new_explicit(state, parent_task, start_func)?;
4521 let thread_id = state.push(new_thread)?;
4522 state.get_mut(parent_task)?.threads.insert(thread_id);
4523
4524 log::trace!("new thread with id {thread_id:?} created");
4525
4526 self.add_guest_thread_to_instance_table(thread_id, store.0, runtime_instance)
4527 }
4528
4529 pub(crate) fn resume_thread(
4530 self,
4531 store: &mut StoreOpaque,
4532 runtime_instance: RuntimeComponentInstanceIndex,
4533 thread_idx: u32,
4534 how: ResumeThread,
4535 ) -> Result<bool> {
4536 let thread_id =
4537 GuestThread::from_instance(self.id().get_mut(store), runtime_instance, thread_idx)?;
4538 let state = store.concurrent_state_mut()?;
4539 let guest_thread = QualifiedThreadId::qualify(state, thread_id)?;
4540
4541 if store.current_guest_thread()? == guest_thread {
4542 bail!(Trap::CannotResumeThread);
4543 }
4544
4545 let priority = match how {
4546 ResumeThread::Resume => Priority::Switch,
4547 ResumeThread::ResumeLater => Priority::Low,
4548
4549 ResumeThread::Promote => {
4552 let instance = self.runtime_instance(runtime_instance);
4553 let do_not_enter = store
4554 .instance_state(instance)
4555 .concurrent_state()
4556 .do_not_enter;
4557 return store.concurrent_state_mut()?.promote_work_item_matching(
4558 |item: &WorkItem| match item {
4559 WorkItem::ResumeThread { thread, .. }
4560 | WorkItem::ResumeFiber { thread, .. } => *thread == guest_thread,
4561
4562 WorkItem::GuestCall {
4563 call: GuestCall { thread, kind },
4564 ..
4565 } => {
4566 *thread == guest_thread
4567 && match kind {
4568 GuestCallKind::DeliverEvent { .. } => !do_not_enter,
4572
4573 GuestCallKind::StartExplicit(_) => true,
4576
4577 GuestCallKind::StartImplicit { .. } => false,
4581 }
4582 }
4583
4584 WorkItem::PushFuture(_) | WorkItem::WorkerFunction(_) => false,
4585 },
4586 );
4587 }
4588 };
4589
4590 let state = store.concurrent_state_mut()?;
4591 let thread = state.get_mut(guest_thread.thread)?;
4592
4593 match &thread.state {
4596 GuestThreadState::NotStartedExplicit(_) => {}
4597 GuestThreadState::Suspended(_) => {
4598 log::trace!("resuming thread {thread_id:?} that was suspended");
4599 state.schedule_suspended_thread(
4600 guest_thread,
4601 self.runtime_instance(runtime_instance),
4602 priority,
4603 )?;
4604 return Ok(true);
4605 }
4606 _ => bail!(Trap::CannotResumeThread),
4607 }
4608 match mem::replace(&mut thread.state, GuestThreadState::Running) {
4609 GuestThreadState::NotStartedExplicit(start_func) => {
4610 log::trace!("starting thread {guest_thread:?}");
4611 let guest_call = WorkItem::GuestCall {
4612 instance: self.runtime_instance(runtime_instance),
4613 call: GuestCall {
4614 thread: guest_thread,
4615 kind: GuestCallKind::StartExplicit(Box::new(move |store| {
4616 start_func(store, guest_thread)
4617 })),
4618 },
4619 };
4620 state.push_work_item(guest_call, priority)?;
4621 }
4622 other => {
4623 thread.state = other;
4624 bail_bug!("thread state checked to be resumable above");
4625 }
4626 }
4627 Ok(true)
4628 }
4629
4630 fn add_guest_thread_to_instance_table(
4631 self,
4632 thread_id: TableId<GuestThread>,
4633 store: &mut StoreOpaque,
4634 runtime_instance: RuntimeComponentInstanceIndex,
4635 ) -> Result<u32> {
4636 let (state, counter) =
4637 store.instance_state_and_handle_counter(self.runtime_instance(runtime_instance));
4638 let guest_id = state
4639 .thread_handle_table()
4640 .guest_thread_insert(counter, thread_id.rep())?;
4641 store
4642 .concurrent_state_mut()?
4643 .get_mut(thread_id)?
4644 .instance_rep = Some(guest_id);
4645 Ok(guest_id)
4646 }
4647
4648 pub(crate) fn suspension_intrinsic(
4652 self,
4653 store: &mut StoreOpaque,
4654 caller: RuntimeComponentInstanceIndex,
4655 yielding: bool,
4656 to_thread: SuspensionTarget,
4657 ) -> Result<WaitResult> {
4658 let check_suspend = match to_thread {
4659 SuspensionTarget::Promote(thread) => {
4660 !self.resume_thread(store, caller, thread, ResumeThread::Promote)?
4661 }
4662 SuspensionTarget::Resume(thread) => {
4663 if !self.resume_thread(store, caller, thread, ResumeThread::Resume)? {
4664 bail_bug!(
4665 "`resume_thread` should only ever return false \
4666 when `ResumeThread::Promote` is passed to it"
4667 );
4668 }
4669 false
4670 }
4671 SuspensionTarget::None => true,
4672 };
4673
4674 if check_suspend && !store.switch_if_may_not_suspend(self.runtime_instance(caller))? {
4675 return if yielding {
4676 Ok(WaitResult::Completed)
4677 } else {
4678 Err(Trap::CannotBlockSyncTask.into())
4679 };
4680 }
4681
4682 let guest_thread = store.current_guest_thread()?;
4683
4684 let reason = if yielding {
4685 SuspendReason::Yielding {
4686 thread: guest_thread,
4687 }
4688 } else {
4689 SuspendReason::ExplicitlySuspending {
4690 thread: guest_thread,
4691 }
4692 };
4693
4694 store.suspend(reason)?;
4695
4696 Ok(WaitResult::Completed)
4697 }
4698
4699 fn waitable_check(
4701 self,
4702 store: &mut StoreOpaque,
4703 caller: RuntimeInstance,
4704 check: WaitableCheck,
4705 params: WaitableCheckParams,
4706 ) -> Result<u32> {
4707 let guest_thread = store.current_guest_thread()?;
4708
4709 log::trace!("waitable check for {guest_thread:?}; set {:?}", params.set);
4710
4711 match &check {
4714 WaitableCheck::Wait => {
4715 let set = params.set;
4716
4717 loop {
4722 let state = store.concurrent_state_mut()?;
4723 let task = state.get_mut(guest_thread.task)?;
4724 if !(task.event.is_none() || matches!(task.event, Some(Event::Cancelled)))
4725 || !state.get_mut(set)?.ready.is_empty()
4726 {
4727 break;
4728 }
4729
4730 store.switch_or_trap_if_may_not_suspend(caller)?;
4731
4732 store.suspend(SuspendReason::Waiting {
4733 set,
4734 thread: guest_thread,
4735 })?;
4736 }
4737 }
4738 WaitableCheck::Poll => {}
4739 }
4740
4741 log::trace!(
4742 "waitable check for {guest_thread:?}; set {:?}, part two",
4743 params.set
4744 );
4745
4746 let event = self.get_event(store, guest_thread.task, Some(params.set), false)?;
4748
4749 let (ordinal, handle, result) = match &check {
4750 WaitableCheck::Wait => {
4751 let (event, waitable) = match event {
4752 Some(p) => p,
4753 None => bail_bug!("event expected to be present"),
4754 };
4755 let handle = waitable.map(|(_, v)| v).unwrap_or(0);
4756 let (ordinal, result) = event.parts();
4757 (ordinal, handle, result)
4758 }
4759 WaitableCheck::Poll => {
4760 if let Some((event, waitable)) = event {
4761 let handle = waitable.map(|(_, v)| v).unwrap_or(0);
4762 let (ordinal, result) = event.parts();
4763 (ordinal, handle, result)
4764 } else {
4765 log::trace!(
4766 "no events ready to deliver via waitable-set.poll to {:?}; set {:?}",
4767 guest_thread.task,
4768 params.set
4769 );
4770 let (ordinal, result) = Event::None.parts();
4771 (ordinal, 0, result)
4772 }
4773 }
4774 };
4775 let ptr = crate::component::func::validate_inbounds_dynamic(
4776 &CanonicalAbiInfo::POINTER_PAIR,
4777 self.options_memory(store, params.options),
4778 &ValRaw::u32(params.payload),
4779 )?;
4780 let memory = self
4781 .options_memory_range_mut(store, params.options, ptr, 8)
4782 .unwrap();
4783 memory[0..4].copy_from_slice(&handle.to_le_bytes());
4784 memory[4..8].copy_from_slice(&result.to_le_bytes());
4785 Ok(ordinal)
4786 }
4787
4788 pub(crate) fn subtask_cancel(
4790 self,
4791 store: &mut StoreOpaque,
4792 caller_instance: RuntimeComponentInstanceIndex,
4793 async_: bool,
4794 task_id: u32,
4795 ) -> Result<u32> {
4796 let (rep, is_host) = store
4797 .instance_state(self.runtime_instance(caller_instance))
4798 .handle_table()
4799 .subtask_rep(task_id)?;
4800 let waitable = if is_host {
4801 Waitable::Host(TableId::<HostTask>::new(rep))
4802 } else {
4803 Waitable::Guest(TableId::<GuestTask>::new(rep))
4804 };
4805 let concurrent_state = store.concurrent_state_mut()?;
4806
4807 log::trace!("subtask_cancel {waitable:?} (handle {task_id}; async {async_})");
4808
4809 waitable.trap_if_in_waitable_set(concurrent_state)?;
4810
4811 let needs_block;
4812 if let Waitable::Host(host_task) = waitable {
4813 let state = &mut concurrent_state.get_mut(host_task)?.state;
4814 match state {
4815 HostTaskState::CalleeRunning(handle) => {
4822 handle.abort();
4823 *state = HostTaskState::CalleeCancelling;
4824 needs_block = true;
4825 }
4826
4827 HostTaskState::CalleeCancelling | HostTaskState::CalleeDone { cancelled: true } => {
4830 bail!(Trap::SubtaskCancelAfterTerminal);
4831 }
4832 HostTaskState::CalleeDone { cancelled: false } => {
4833 *state = HostTaskState::CalleeDone { cancelled: true };
4836 needs_block = false;
4837 }
4838
4839 HostTaskState::CalleeStarted | HostTaskState::CalleeFinished(_) => {
4842 bail_bug!("invalid states for host callee")
4843 }
4844 }
4845 } else {
4846 let guest_task = TableId::<GuestTask>::new(rep);
4847 let task = concurrent_state.get_mut(guest_task)?;
4848
4849 if task.cancel_requested {
4852 bail!(Trap::SubtaskCancelAfterTerminal);
4853 }
4854
4855 if !task.already_lowered_parameters() {
4856 store.cancel_guest_subtask_without_lowered_parameters(
4857 self.runtime_instance(caller_instance),
4858 guest_task,
4859 )?;
4860 return Ok(Status::StartCancelled as u32);
4861 } else if !task.returned_or_cancelled() {
4862 task.cancel_requested = true;
4869 task.event = Some(Event::Cancelled);
4870 let runtime_instance = task.instance;
4871 for thread in task.threads.clone() {
4872 let thread = QualifiedThreadId {
4873 task: guest_task,
4874 thread,
4875 };
4876 let concurrent_state = store.concurrent_state_mut()?;
4877 let thread_mut = concurrent_state.get_mut(thread.thread)?;
4878
4879 let yield_ = |store: &mut StoreOpaque| {
4880 let state = store.instance_state(runtime_instance).concurrent_state();
4885 let old_do_not_suspend = state.do_not_suspend;
4886 state.do_not_suspend = false;
4887
4888 let caller = store.current_guest_thread()?;
4889
4890 let state = store.concurrent_state_mut()?;
4895 let set = state.get_mut(caller.thread)?.sync_call_set;
4896 waitable.join(state, Some(set))?;
4897
4898 store.suspend(SuspendReason::YieldingToSubtask { thread: caller })?;
4899
4900 let state = store.concurrent_state_mut()?;
4901 waitable.join(state, None)?;
4902
4903 store
4904 .instance_state(runtime_instance)
4905 .concurrent_state()
4906 .do_not_suspend = old_do_not_suspend;
4907
4908 Ok::<(), crate::Error>(())
4909 };
4910
4911 match thread_mut.wake_on_cancel.take() {
4912 WakeOnCancel::Waiting(set) => {
4913 let instance = concurrent_state.take_callback_waiter(set, thread)?;
4915 let item = WorkItem::GuestCall {
4916 instance: runtime_instance,
4917 call: GuestCall {
4918 thread,
4919 kind: GuestCallKind::DeliverEvent {
4920 instance,
4921 set: Some(set),
4922 },
4923 },
4924 };
4925 concurrent_state.set_switch_item(item)?;
4926
4927 yield_(store)?;
4928
4929 break;
4930 }
4931 WakeOnCancel::Yielding => {
4932 if concurrent_state.promote_thread_work_item(thread)? {
4933 yield_(store)?;
4934 break;
4935 } else if store
4936 .instance_state(runtime_instance)
4937 .concurrent_state()
4938 .pending
4939 .contains_key(&thread)
4940 {
4941 store
4951 .concurrent_state_mut()?
4952 .get_mut(thread.thread)?
4953 .wake_on_cancel = WakeOnCancel::Yielding;
4954 } else {
4955 bail_bug!("thread with `WakeOnCancel::Yielding` not promotable");
4956 }
4957 }
4958 WakeOnCancel::None => {}
4959 }
4960 }
4961
4962 needs_block = !store
4965 .concurrent_state_mut()?
4966 .get_mut(guest_task)?
4967 .returned_or_cancelled()
4968 } else {
4969 needs_block = false;
4970 }
4971 };
4972
4973 if needs_block {
4977 if async_ {
4978 return Ok(BLOCKED);
4979 }
4980
4981 let old_next_switch_item = if is_host {
4991 Some(store.concurrent_state_mut()?.save_next_switch_item()?)
4992 } else {
4993 None
4994 };
4995
4996 store.wait_for_event(self.runtime_instance(caller_instance), waitable)?;
4999
5000 if let Some(item) = old_next_switch_item {
5001 let state = store.concurrent_state_mut()?;
5002 state.restore_next_switch_item(item)?;
5003 }
5004
5005 }
5007
5008 let event = waitable.take_event(store.concurrent_state_mut()?)?;
5009 if let Some(Event::Subtask {
5010 status: status @ (Status::Returned | Status::ReturnCancelled),
5011 }) = event
5012 {
5013 Ok(status as u32)
5014 } else {
5015 bail!(Trap::SubtaskCancelAfterTerminal);
5016 }
5017 }
5018}
5019
5020pub trait VMComponentAsyncStore {
5028 unsafe fn prepare_call(
5034 &mut self,
5035 instance: Instance,
5036 memory: *mut VMMemoryDefinition,
5037 start: NonNull<VMFuncRef>,
5038 return_: NonNull<VMFuncRef>,
5039 caller_instance: RuntimeComponentInstanceIndex,
5040 callee_instance: RuntimeComponentInstanceIndex,
5041 task_return_type: TypeTupleIndex,
5042 callee_async: bool,
5043 string_encoding: StringEncoding,
5044 result_count: u32,
5045 storage: *mut ValRaw,
5046 storage_len: usize,
5047 ) -> Result<()>;
5048
5049 unsafe fn start_call(
5052 &mut self,
5053 instance: Instance,
5054 callback: *mut VMFuncRef,
5055 post_return: *mut VMFuncRef,
5056 callee: NonNull<VMFuncRef>,
5057 param_count: u32,
5058 result_count: u32,
5059 flags: u32,
5060 storage: *mut MaybeUninit<ValRaw>,
5061 storage_len: usize,
5062 ) -> Result<()>;
5063
5064 fn future_write(
5066 &mut self,
5067 instance: Instance,
5068 caller: RuntimeComponentInstanceIndex,
5069 ty: TypeFutureTableIndex,
5070 options: OptionsIndex,
5071 future: u32,
5072 address: u32,
5073 ) -> Result<u32>;
5074
5075 fn future_read(
5077 &mut self,
5078 instance: Instance,
5079 caller: RuntimeComponentInstanceIndex,
5080 ty: TypeFutureTableIndex,
5081 options: OptionsIndex,
5082 future: u32,
5083 address: u32,
5084 ) -> Result<u32>;
5085
5086 fn future_drop_writable(
5088 &mut self,
5089 instance: Instance,
5090 ty: TypeFutureTableIndex,
5091 writer: u32,
5092 ) -> Result<()>;
5093
5094 fn stream_write(
5096 &mut self,
5097 instance: Instance,
5098 caller: RuntimeComponentInstanceIndex,
5099 ty: TypeStreamTableIndex,
5100 options: OptionsIndex,
5101 stream: u32,
5102 address: u32,
5103 count: u32,
5104 ) -> Result<u32>;
5105
5106 fn stream_read(
5108 &mut self,
5109 instance: Instance,
5110 caller: RuntimeComponentInstanceIndex,
5111 ty: TypeStreamTableIndex,
5112 options: OptionsIndex,
5113 stream: u32,
5114 address: u32,
5115 count: u32,
5116 ) -> Result<u32>;
5117
5118 fn flat_stream_write(
5121 &mut self,
5122 instance: Instance,
5123 caller: RuntimeComponentInstanceIndex,
5124 ty: TypeStreamTableIndex,
5125 options: OptionsIndex,
5126 payload_size: u32,
5127 payload_align: u32,
5128 stream: u32,
5129 address: u32,
5130 count: u32,
5131 ) -> Result<u32>;
5132
5133 fn flat_stream_read(
5136 &mut self,
5137 instance: Instance,
5138 caller: RuntimeComponentInstanceIndex,
5139 ty: TypeStreamTableIndex,
5140 options: OptionsIndex,
5141 payload_size: u32,
5142 payload_align: u32,
5143 stream: u32,
5144 address: u32,
5145 count: u32,
5146 ) -> Result<u32>;
5147
5148 fn stream_drop_writable(
5150 &mut self,
5151 instance: Instance,
5152 ty: TypeStreamTableIndex,
5153 writer: u32,
5154 ) -> Result<()>;
5155
5156 fn error_context_debug_message(
5158 &mut self,
5159 instance: Instance,
5160 ty: TypeComponentLocalErrorContextTableIndex,
5161 options: OptionsIndex,
5162 err_ctx_handle: u32,
5163 debug_msg_address: u32,
5164 ) -> Result<()>;
5165
5166 fn thread_new_indirect(
5168 &mut self,
5169 instance: Instance,
5170 caller: RuntimeComponentInstanceIndex,
5171 func_ty_idx: ModuleInternedTypeIndex,
5172 start_func_table_idx: RuntimeTableIndex,
5173 start_func_idx: u32,
5174 context: i32,
5175 ) -> Result<u32>;
5176}
5177
5178impl<T: 'static> VMComponentAsyncStore for StoreInner<T> {
5180 unsafe fn prepare_call(
5181 &mut self,
5182 instance: Instance,
5183 memory: *mut VMMemoryDefinition,
5184 start: NonNull<VMFuncRef>,
5185 return_: NonNull<VMFuncRef>,
5186 caller_instance: RuntimeComponentInstanceIndex,
5187 callee_instance: RuntimeComponentInstanceIndex,
5188 task_return_type: TypeTupleIndex,
5189 callee_async: bool,
5190 string_encoding: StringEncoding,
5191 result_count_or_max_if_async: u32,
5192 storage: *mut ValRaw,
5193 storage_len: usize,
5194 ) -> Result<()> {
5195 let params = unsafe { core::slice::from_raw_parts(storage, storage_len) }.to_vec();
5199
5200 unsafe {
5201 instance.prepare_call(
5202 StoreContextMut(self),
5203 start,
5204 return_,
5205 caller_instance,
5206 callee_instance,
5207 task_return_type,
5208 callee_async,
5209 memory,
5210 string_encoding,
5211 match result_count_or_max_if_async {
5212 PREPARE_ASYNC_NO_RESULT => CallerInfo::Async {
5213 params,
5214 has_result: false,
5215 },
5216 PREPARE_ASYNC_WITH_RESULT => CallerInfo::Async {
5217 params,
5218 has_result: true,
5219 },
5220 result_count => CallerInfo::Sync {
5221 params,
5222 result_count,
5223 },
5224 },
5225 )
5226 }
5227 }
5228
5229 unsafe fn start_call(
5230 &mut self,
5231 instance: Instance,
5232 callback: *mut VMFuncRef,
5233 post_return: *mut VMFuncRef,
5234 callee: NonNull<VMFuncRef>,
5235 param_count: u32,
5236 result_count: u32,
5237 flags: u32,
5238 storage: *mut MaybeUninit<ValRaw>,
5239 storage_len: usize,
5240 ) -> Result<()> {
5241 unsafe {
5242 instance.start_call(
5243 StoreContextMut(self),
5244 callback,
5245 post_return,
5246 callee,
5247 param_count,
5248 result_count,
5249 flags,
5250 core::slice::from_raw_parts_mut(storage, storage_len),
5254 )
5255 }
5256 }
5257
5258 fn future_write(
5259 &mut self,
5260 instance: Instance,
5261 caller: RuntimeComponentInstanceIndex,
5262 ty: TypeFutureTableIndex,
5263 options: OptionsIndex,
5264 future: u32,
5265 address: u32,
5266 ) -> Result<u32> {
5267 instance
5268 .guest_write(
5269 StoreContextMut(self),
5270 caller,
5271 TransmitIndex::Future(ty),
5272 options,
5273 None,
5274 future,
5275 address,
5276 1,
5277 )
5278 .map(|result| result.encode())
5279 }
5280
5281 fn future_read(
5282 &mut self,
5283 instance: Instance,
5284 caller: RuntimeComponentInstanceIndex,
5285 ty: TypeFutureTableIndex,
5286 options: OptionsIndex,
5287 future: u32,
5288 address: u32,
5289 ) -> Result<u32> {
5290 instance
5291 .guest_read(
5292 StoreContextMut(self),
5293 caller,
5294 TransmitIndex::Future(ty),
5295 options,
5296 None,
5297 future,
5298 address,
5299 1,
5300 )
5301 .map(|result| result.encode())
5302 }
5303
5304 fn stream_write(
5305 &mut self,
5306 instance: Instance,
5307 caller: RuntimeComponentInstanceIndex,
5308 ty: TypeStreamTableIndex,
5309 options: OptionsIndex,
5310 stream: u32,
5311 address: u32,
5312 count: u32,
5313 ) -> Result<u32> {
5314 instance
5315 .guest_write(
5316 StoreContextMut(self),
5317 caller,
5318 TransmitIndex::Stream(ty),
5319 options,
5320 None,
5321 stream,
5322 address,
5323 count,
5324 )
5325 .map(|result| result.encode())
5326 }
5327
5328 fn stream_read(
5329 &mut self,
5330 instance: Instance,
5331 caller: RuntimeComponentInstanceIndex,
5332 ty: TypeStreamTableIndex,
5333 options: OptionsIndex,
5334 stream: u32,
5335 address: u32,
5336 count: u32,
5337 ) -> Result<u32> {
5338 instance
5339 .guest_read(
5340 StoreContextMut(self),
5341 caller,
5342 TransmitIndex::Stream(ty),
5343 options,
5344 None,
5345 stream,
5346 address,
5347 count,
5348 )
5349 .map(|result| result.encode())
5350 }
5351
5352 fn future_drop_writable(
5353 &mut self,
5354 instance: Instance,
5355 ty: TypeFutureTableIndex,
5356 writer: u32,
5357 ) -> Result<()> {
5358 instance.guest_drop_writable(self, TransmitIndex::Future(ty), writer)
5359 }
5360
5361 fn flat_stream_write(
5362 &mut self,
5363 instance: Instance,
5364 caller: RuntimeComponentInstanceIndex,
5365 ty: TypeStreamTableIndex,
5366 options: OptionsIndex,
5367 payload_size: u32,
5368 payload_align: u32,
5369 stream: u32,
5370 address: u32,
5371 count: u32,
5372 ) -> Result<u32> {
5373 instance
5374 .guest_write(
5375 StoreContextMut(self),
5376 caller,
5377 TransmitIndex::Stream(ty),
5378 options,
5379 Some(FlatAbi {
5380 size: payload_size,
5381 align: payload_align,
5382 }),
5383 stream,
5384 address,
5385 count,
5386 )
5387 .map(|result| result.encode())
5388 }
5389
5390 fn flat_stream_read(
5391 &mut self,
5392 instance: Instance,
5393 caller: RuntimeComponentInstanceIndex,
5394 ty: TypeStreamTableIndex,
5395 options: OptionsIndex,
5396 payload_size: u32,
5397 payload_align: u32,
5398 stream: u32,
5399 address: u32,
5400 count: u32,
5401 ) -> Result<u32> {
5402 instance
5403 .guest_read(
5404 StoreContextMut(self),
5405 caller,
5406 TransmitIndex::Stream(ty),
5407 options,
5408 Some(FlatAbi {
5409 size: payload_size,
5410 align: payload_align,
5411 }),
5412 stream,
5413 address,
5414 count,
5415 )
5416 .map(|result| result.encode())
5417 }
5418
5419 fn stream_drop_writable(
5420 &mut self,
5421 instance: Instance,
5422 ty: TypeStreamTableIndex,
5423 writer: u32,
5424 ) -> Result<()> {
5425 instance.guest_drop_writable(self, TransmitIndex::Stream(ty), writer)
5426 }
5427
5428 fn error_context_debug_message(
5429 &mut self,
5430 instance: Instance,
5431 ty: TypeComponentLocalErrorContextTableIndex,
5432 options: OptionsIndex,
5433 err_ctx_handle: u32,
5434 debug_msg_address: u32,
5435 ) -> Result<()> {
5436 instance.error_context_debug_message(
5437 StoreContextMut(self),
5438 ty,
5439 options,
5440 err_ctx_handle,
5441 debug_msg_address,
5442 )
5443 }
5444
5445 fn thread_new_indirect(
5446 &mut self,
5447 instance: Instance,
5448 caller: RuntimeComponentInstanceIndex,
5449 func_ty_idx: ModuleInternedTypeIndex,
5450 start_func_table_idx: RuntimeTableIndex,
5451 start_func_idx: u32,
5452 context: i32,
5453 ) -> Result<u32> {
5454 instance.thread_new_indirect(
5455 StoreContextMut(self),
5456 caller,
5457 func_ty_idx,
5458 start_func_table_idx,
5459 start_func_idx,
5460 context,
5461 )
5462 }
5463}
5464
5465type HostTaskFuture = Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>;
5466
5467async fn run_with_host_task_set<F>(task: TableId<HostTask>, future: F) -> Result<F::Output>
5470where
5471 F: Future,
5472{
5473 let mut future = pin!(future);
5474 future::poll_fn(|cx| {
5475 let old_thread = match tls::get(|store| store.set_thread(task)) {
5476 Ok(thread) => thread,
5477 Err(error) => return Poll::Ready(Err(error)),
5478 };
5479 let result = future.as_mut().poll(cx);
5480 match tls::get(|store| store.set_thread(old_thread)) {
5481 Ok(_) => result.map(Ok),
5482 Err(error) => Poll::Ready(Err(error)),
5483 }
5484 })
5485 .await
5486}
5487
5488pub(crate) struct HostTask {
5492 common: WaitableCommon,
5493
5494 call_context: CallContext,
5497
5498 state: HostTaskState,
5499
5500 group: TaskGroupId,
5501}
5502
5503enum HostTaskState {
5504 CalleeStarted,
5509
5510 CalleeRunning(JoinHandle),
5515
5516 CalleeCancelling,
5520
5521 CalleeFinished(LiftedResult),
5525
5526 CalleeDone { cancelled: bool },
5529}
5530
5531impl HostTask {
5532 fn new(
5533 concurrent_state: &mut ConcurrentState,
5534 state: HostTaskState,
5535 caller: QualifiedThreadId,
5536 ) -> Result<Self> {
5537 let group = concurrent_state.get_mut(caller.task)?.group;
5538 concurrent_state.increment_group_ref_count(group)?;
5539
5540 Ok(Self {
5541 common: WaitableCommon::default(),
5542 call_context: CallContext::default(),
5543 state,
5544 group,
5545 })
5546 }
5547}
5548
5549impl TableDebug for HostTask {
5550 fn type_name() -> &'static str {
5551 "HostTask"
5552 }
5553}
5554
5555type CallbackFn = Box<dyn Fn(&mut dyn VMStore, Event, u32) -> Result<u32> + Send + Sync + 'static>;
5556
5557enum Caller {
5559 Host {
5561 tx: Option<oneshot::Sender<LiftedResult>>,
5563 caller: Option<TableId<HostTask>>,
5567 },
5568 Guest {
5570 thread: QualifiedThreadId,
5572 },
5573}
5574
5575struct LiftResult {
5578 lift: RawLift,
5579 ty: TypeTupleIndex,
5580 memory: Option<SendSyncPtr<VMMemoryDefinition>>,
5581 string_encoding: StringEncoding,
5582}
5583
5584#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
5589pub(crate) struct QualifiedThreadId {
5590 task: TableId<GuestTask>,
5591 thread: TableId<GuestThread>,
5592}
5593
5594impl QualifiedThreadId {
5595 fn qualify(
5596 state: &mut ConcurrentState,
5597 thread: TableId<GuestThread>,
5598 ) -> Result<QualifiedThreadId> {
5599 Ok(QualifiedThreadId {
5600 task: state.get_mut(thread)?.parent_task,
5601 thread,
5602 })
5603 }
5604}
5605
5606impl fmt::Debug for QualifiedThreadId {
5607 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5608 f.debug_tuple("QualifiedThreadId")
5609 .field(&self.task.rep())
5610 .field(&self.thread.rep())
5611 .finish()
5612 }
5613}
5614
5615enum GuestThreadState {
5616 NotStartedImplicit,
5617 NotStartedExplicit(
5618 Box<dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync>,
5619 ),
5620 Running,
5621 Suspended(StoreFiber<'static>),
5622 Ready {
5623 fiber: StoreFiber<'static>,
5624 },
5625 Completed,
5626}
5627
5628impl GuestThreadState {
5629 fn check_no_fiber(&self) -> Result<()> {
5630 match self {
5631 Self::Suspended(_) | Self::Ready { .. } => bail_bug!("thread already owns a fiber"),
5632 Self::NotStartedImplicit
5633 | Self::NotStartedExplicit(_)
5634 | Self::Running
5635 | Self::Completed => Ok(()),
5636 }
5637 }
5638}
5639
5640impl fmt::Debug for GuestThreadState {
5641 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5642 match self {
5643 Self::NotStartedImplicit => f.debug_tuple("NotStartedImplicit").finish(),
5644 Self::NotStartedExplicit(_) => f.debug_tuple("NotStartedExplicit").finish(),
5645 Self::Running => f.debug_tuple("Running").finish(),
5646 Self::Suspended(_) => f.debug_tuple("Suspended").finish(),
5647 Self::Ready { .. } => f.debug_struct("Ready").finish(),
5648 Self::Completed => f.debug_tuple("Completed").finish(),
5649 }
5650 }
5651}
5652
5653#[derive(Copy, Clone, PartialEq, Eq, Debug)]
5654enum WakeOnCancel {
5655 None,
5656 Waiting(TableId<WaitableSet>),
5657 Yielding,
5658}
5659
5660impl WakeOnCancel {
5661 fn is_none(self) -> bool {
5662 matches!(self, WakeOnCancel::None)
5663 }
5664
5665 fn replace(&mut self, other: WakeOnCancel) -> Self {
5666 let old = *self;
5667 *self = other;
5668 old
5669 }
5670
5671 fn take(&mut self) -> Self {
5672 self.replace(WakeOnCancel::None)
5673 }
5674}
5675
5676pub struct GuestThread {
5677 context: [u32; NUM_COMPONENT_CONTEXT_SLOTS],
5680 parent_task: TableId<GuestTask>,
5682 wake_on_cancel: WakeOnCancel,
5685 state: GuestThreadState,
5687 instance_rep: Option<u32>,
5690 sync_call_set: TableId<WaitableSet>,
5692 old_do_not_suspend: Option<bool>,
5695}
5696
5697impl GuestThread {
5698 fn from_instance(
5701 state: Pin<&mut ComponentInstance>,
5702 caller_instance: RuntimeComponentInstanceIndex,
5703 guest_thread: u32,
5704 ) -> Result<TableId<Self>> {
5705 let rep = state.instance_states().0[caller_instance]
5706 .thread_handle_table()
5707 .guest_thread_rep(guest_thread)?;
5708 Ok(TableId::new(rep))
5709 }
5710
5711 fn new_implicit(state: &mut ConcurrentState, parent_task: TableId<GuestTask>) -> Result<Self> {
5712 let sync_call_set = state.push(WaitableSet {
5713 is_sync_call_set: true,
5714 ..WaitableSet::default()
5715 })?;
5716 Ok(Self {
5717 context: [0; NUM_COMPONENT_CONTEXT_SLOTS],
5718 parent_task,
5719 wake_on_cancel: WakeOnCancel::None,
5720 state: GuestThreadState::NotStartedImplicit,
5721 instance_rep: None,
5722 sync_call_set,
5723 old_do_not_suspend: None,
5724 })
5725 }
5726
5727 fn new_explicit(
5728 state: &mut ConcurrentState,
5729 parent_task: TableId<GuestTask>,
5730 start_func: Box<
5731 dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync,
5732 >,
5733 ) -> Result<Self> {
5734 state.increment_task_ref_count(parent_task)?;
5735 let sync_call_set = state.push(WaitableSet {
5736 is_sync_call_set: true,
5737 ..WaitableSet::default()
5738 })?;
5739 Ok(Self {
5740 context: [0; NUM_COMPONENT_CONTEXT_SLOTS],
5741 parent_task,
5742 wake_on_cancel: WakeOnCancel::None,
5743 state: GuestThreadState::NotStartedExplicit(start_func),
5744 instance_rep: None,
5745 sync_call_set,
5746 old_do_not_suspend: None,
5747 })
5748 }
5749}
5750
5751impl TableDebug for GuestThread {
5752 fn type_name() -> &'static str {
5753 "GuestThread"
5754 }
5755}
5756
5757enum SyncResult {
5758 NotProduced,
5759 Produced(Option<ValRaw>),
5760 Taken,
5761}
5762
5763impl SyncResult {
5764 fn take(&mut self) -> Result<Option<Option<ValRaw>>> {
5765 Ok(match mem::replace(self, SyncResult::Taken) {
5766 SyncResult::NotProduced => None,
5767 SyncResult::Produced(val) => Some(val),
5768 SyncResult::Taken => {
5769 bail_bug!("attempted to take a synchronous result that was already taken")
5770 }
5771 })
5772 }
5773}
5774
5775pub(crate) struct GuestTask {
5777 common: WaitableCommon,
5779 lower_params: Option<RawLower>,
5781 lift_result: Option<LiftResult>,
5783 result: Option<LiftedResult>,
5786 callback: Option<CallbackFn>,
5789 caller: Caller,
5791 call_context: CallContext,
5796 sync_result: SyncResult,
5799 cancel_request_delivered: bool,
5803 cancel_requested: bool,
5808 starting_sent: bool,
5811 instance: RuntimeInstance,
5818 event: Option<Event>,
5820 exited: bool,
5822 threads: HashSet<TableId<GuestThread>>,
5824 async_typed: bool,
5827 async_lifted: bool,
5830 decremented_interesting_task_count: bool,
5833 group: TaskGroupId,
5835 ref_count: usize,
5840}
5841
5842impl GuestTask {
5843 fn already_lowered_parameters(&self) -> bool {
5844 self.lower_params.is_none()
5846 }
5847
5848 fn returned_or_cancelled(&self) -> bool {
5849 self.lift_result.is_none()
5851 }
5852
5853 fn new(
5854 state: &mut ConcurrentState,
5855 lower_params: RawLower,
5856 lift_result: LiftResult,
5857 caller: Caller,
5858 callback: Option<CallbackFn>,
5859 instance: RuntimeInstance,
5860 async_typed: bool,
5861 async_lifted: bool,
5862 ) -> Result<QualifiedThreadId> {
5863 let group = match caller {
5864 Caller::Guest { thread } => {
5865 let group = state.get_mut(thread.task)?.group;
5866 state.increment_group_ref_count(group)?;
5867 group
5868 }
5869 Caller::Host { .. } => state.make_task_group()?,
5870 };
5871
5872 let task = state.push(Self {
5873 common: WaitableCommon::default(),
5874 lower_params: Some(lower_params),
5875 lift_result: Some(lift_result),
5876 result: None,
5877 callback,
5878 caller,
5879 call_context: CallContext::default(),
5880 sync_result: SyncResult::NotProduced,
5881 cancel_request_delivered: false,
5882 cancel_requested: false,
5883 starting_sent: false,
5884 instance,
5885 event: None,
5886 exited: false,
5887 threads: HashSet::new(),
5888 async_typed,
5889 async_lifted,
5890 decremented_interesting_task_count: false,
5891 group,
5892 ref_count: 2,
5895 })?;
5896 let new_thread = GuestThread::new_implicit(state, task)?;
5897 let thread = state.push(new_thread)?;
5898 state.get_mut(task)?.threads.insert(thread);
5899 state.interesting_tasks += 1;
5900 let thread = QualifiedThreadId { task, thread };
5901 log::trace!("new implicit thread {thread:?} for instance {instance:?}");
5902 Ok(thread)
5903 }
5904}
5905
5906impl TableDebug for GuestTask {
5907 fn type_name() -> &'static str {
5908 "GuestTask"
5909 }
5910}
5911
5912#[derive(Default)]
5914struct WaitableCommon {
5915 event: Option<Event>,
5917 set: Option<TableId<WaitableSet>>,
5919 handle: Option<u32>,
5921}
5922
5923#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
5925enum Waitable {
5926 Host(TableId<HostTask>),
5928 Guest(TableId<GuestTask>),
5930 Transmit(TableId<TransmitHandle>),
5932}
5933
5934impl Waitable {
5935 fn from_instance(
5938 state: Pin<&mut ComponentInstance>,
5939 caller_instance: RuntimeComponentInstanceIndex,
5940 waitable: u32,
5941 ) -> Result<Self> {
5942 use crate::runtime::vm::component::Waitable;
5943
5944 let (waitable, kind) = state.instance_states().0[caller_instance]
5945 .handle_table()
5946 .waitable_rep(waitable)?;
5947
5948 Ok(match kind {
5949 Waitable::Subtask { is_host: true } => Self::Host(TableId::new(waitable)),
5950 Waitable::Subtask { is_host: false } => Self::Guest(TableId::new(waitable)),
5951 Waitable::Stream | Waitable::Future => Self::Transmit(TableId::new(waitable)),
5952 })
5953 }
5954
5955 fn rep(&self) -> u32 {
5957 match self {
5958 Self::Host(id) => id.rep(),
5959 Self::Guest(id) => id.rep(),
5960 Self::Transmit(id) => id.rep(),
5961 }
5962 }
5963
5964 fn join(&self, state: &mut ConcurrentState, set: Option<TableId<WaitableSet>>) -> Result<()> {
5968 log::trace!("waitable {self:?} join set {set:?}");
5969
5970 let old = mem::replace(&mut self.common(state)?.set, set);
5971
5972 if let Some(old) = old {
5973 match *self {
5974 Waitable::Host(id) => state.remove_child(id, old),
5975 Waitable::Guest(id) => state.remove_child(id, old),
5976 Waitable::Transmit(id) => state.remove_child(id, old),
5977 }?;
5978
5979 state.get_mut(old)?.ready.remove(self);
5980 }
5981
5982 if let Some(set) = set {
5983 match *self {
5984 Waitable::Host(id) => state.add_child(id, set),
5985 Waitable::Guest(id) => state.add_child(id, set),
5986 Waitable::Transmit(id) => state.add_child(id, set),
5987 }?;
5988
5989 if self.common(state)?.event.is_some() {
5990 self.mark_ready(state)?;
5991 }
5992 }
5993
5994 Ok(())
5995 }
5996
5997 fn common<'a>(&self, state: &'a mut ConcurrentState) -> Result<&'a mut WaitableCommon> {
5999 Ok(match self {
6000 Self::Host(id) => &mut state.get_mut(*id)?.common,
6001 Self::Guest(id) => &mut state.get_mut(*id)?.common,
6002 Self::Transmit(id) => &mut state.get_mut(*id)?.common,
6003 })
6004 }
6005
6006 fn trap_if_in_waitable_set(&self, state: &mut ConcurrentState) -> Result<()> {
6012 if self.common(state)?.set.is_some() {
6013 bail!(Trap::WaitableSyncAndAsync);
6014 }
6015 Ok(())
6016 }
6017
6018 fn trap_if_has_sync_waiter(&self, state: &mut ConcurrentState) -> Result<()> {
6024 if let Some(set) = self.common(state)?.set
6025 && state.get_mut(set)?.is_sync_call_set
6026 {
6027 bail!(Trap::WaitableSyncAndAsync);
6028 }
6029 Ok(())
6030 }
6031
6032 fn set_event(&self, state: &mut ConcurrentState, event: Option<Event>) -> Result<()> {
6036 log::trace!("set event for {self:?}: {event:?}");
6037 self.common(state)?.event = event;
6038 self.mark_ready(state)
6039 }
6040
6041 fn take_event(&self, state: &mut ConcurrentState) -> Result<Option<Event>> {
6043 let common = self.common(state)?;
6044 let event = common.event.take();
6045 if let Some(set) = self.common(state)?.set {
6046 state.get_mut(set)?.ready.remove(self);
6047 }
6048
6049 Ok(event)
6050 }
6051
6052 fn mark_ready(&self, state: &mut ConcurrentState) -> Result<()> {
6056 if let Some(set) = self.common(state)?.set {
6057 state.get_mut(set)?.ready.insert(*self);
6058 state.wake_waiter(set)?;
6059 }
6060 Ok(())
6061 }
6062
6063 fn delete_from(&self, state: &mut ConcurrentState) -> Result<()> {
6066 match self {
6067 Self::Host(task) => state.delete_host_task(*task),
6068 Self::Guest(task) => state.decrement_task_ref_count(*task),
6069 Self::Transmit(task) => Ok(state.delete(*task).map(drop)?),
6070 }
6071 }
6072}
6073
6074impl fmt::Debug for Waitable {
6075 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6076 match self {
6077 Self::Host(id) => write!(f, "{id:?}"),
6078 Self::Guest(id) => write!(f, "{id:?}"),
6079 Self::Transmit(id) => write!(f, "{id:?}"),
6080 }
6081 }
6082}
6083
6084#[derive(Default)]
6086struct WaitableSet {
6087 ready: BTreeSet<Waitable>,
6089 waiting: BTreeMap<QualifiedThreadId, WaitMode>,
6091 num_waiting: usize,
6094 is_sync_call_set: bool,
6097}
6098
6099impl WaitableSet {
6100 fn stop_waiting(&mut self) -> Result<()> {
6102 self.num_waiting = match self.num_waiting.checked_sub(1) {
6103 Some(n) => n,
6104 None => bail_bug!("waiter not accounted for in waitable set"),
6105 };
6106 Ok(())
6107 }
6108}
6109
6110impl TableDebug for WaitableSet {
6111 fn type_name() -> &'static str {
6112 "WaitableSet"
6113 }
6114}
6115
6116type RawLower =
6118 Box<dyn FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync>;
6119
6120type RawLift = Box<
6122 dyn FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
6123>;
6124
6125type LiftedResult = Box<dyn Any + Send + Sync>;
6129
6130struct DummyResult;
6133
6134#[derive(Default)]
6136pub struct ConcurrentInstanceState {
6137 backpressure: u16,
6139 do_not_enter: bool,
6141 do_not_suspend: bool,
6144 pending: BTreeMap<QualifiedThreadId, GuestCallKind>,
6147 pending_start_count: usize,
6150}
6151
6152impl ConcurrentInstanceState {
6153 pub fn pending_is_empty(&self) -> bool {
6154 self.pending.is_empty()
6155 }
6156}
6157
6158#[derive(Debug, Copy, Clone)]
6159pub(crate) enum CurrentThread {
6160 Guest(QualifiedThreadId),
6163 Host(TableId<HostTask>),
6165 DeferredHost(QualifiedThreadId),
6168 None,
6171}
6172
6173impl CurrentThread {
6174 fn guest(&self) -> Option<&QualifiedThreadId> {
6175 match self {
6176 Self::Guest(id) => Some(id),
6177 _ => None,
6178 }
6179 }
6180
6181 fn guest_task(&self) -> Option<TableId<GuestTask>> {
6182 match self {
6183 Self::Guest(id) => Some(id.task),
6184 _ => None,
6185 }
6186 }
6187
6188 fn is_none(&self) -> bool {
6189 matches!(self, Self::None)
6190 }
6191}
6192
6193impl From<QualifiedThreadId> for CurrentThread {
6194 fn from(id: QualifiedThreadId) -> Self {
6195 Self::Guest(id)
6196 }
6197}
6198
6199impl From<TableId<HostTask>> for CurrentThread {
6200 fn from(id: TableId<HostTask>) -> Self {
6201 Self::Host(id)
6202 }
6203}
6204
6205enum Priority {
6206 Switch,
6207 #[expect(
6208 dead_code,
6209 reason = "Here for completeness and in case we need it later"
6210 )]
6211 High,
6212 Low,
6213}
6214
6215pub struct ConcurrentState {
6217 trapped: bool,
6220
6221 unforced_current_thread: CurrentThread,
6227
6228 deferred_host_call_context: Option<CallContext>,
6234
6235 futures: AlwaysMut<Option<FuturesUnordered<HostTaskFuture>>>,
6240 table: AlwaysMut<ResourceTable>,
6242 switch_item: Option<WorkItem>,
6250 next_switch_item: Option<WorkItem>,
6256 high_priority: VecDeque<WorkItem>,
6258 low_priority: VecDeque<WorkItem>,
6260 suspend_reason: Option<SuspendReason>,
6264 worker: Option<StoreFiber<'static>>,
6268 worker_item: Option<WorkerItem>,
6270
6271 global_error_context_ref_counts:
6284 BTreeMap<TypeComponentGlobalErrorContextTableIndex, GlobalErrorContextRefCount>,
6285
6286 interesting_tasks: usize,
6299
6300 interesting_tasks_empty_waker: Option<Waker>,
6304
6305 backpressure_waker: Option<Waker>,
6310
6311 idle_waker: Option<Waker>,
6316
6317 event_loop_running: bool,
6319
6320 saved_next_switch_items: Vec<Option<WorkItem>>,
6323
6324 #[cfg(feature = "task-group-hook")]
6326 task_group_hook: Option<Box<dyn TaskGroupHook>>,
6327}
6328
6329impl Default for ConcurrentState {
6330 fn default() -> Self {
6331 Self {
6332 trapped: false,
6333 unforced_current_thread: CurrentThread::None,
6334 deferred_host_call_context: None,
6335 table: AlwaysMut::new(ResourceTable::new()),
6336 futures: AlwaysMut::new(Some(FuturesUnordered::new())),
6337 switch_item: None,
6338 next_switch_item: None,
6339 high_priority: VecDeque::new(),
6340 low_priority: VecDeque::new(),
6341 suspend_reason: None,
6342 worker: None,
6343 worker_item: None,
6344 global_error_context_ref_counts: BTreeMap::new(),
6345 interesting_tasks: 0,
6346 interesting_tasks_empty_waker: None,
6347 backpressure_waker: None,
6348 idle_waker: None,
6349 event_loop_running: false,
6350 saved_next_switch_items: Vec::new(),
6351 #[cfg(feature = "task-group-hook")]
6352 task_group_hook: None,
6353 }
6354 }
6355}
6356
6357impl ConcurrentState {
6358 pub(crate) fn take_fibers_and_futures(
6375 &mut self,
6376 fibers: &mut Vec<StoreFiber<'static>>,
6377 futures: &mut Vec<FuturesUnordered<HostTaskFuture>>,
6378 ) {
6379 let ConcurrentState {
6380 table,
6381 worker,
6382 switch_item,
6383 next_switch_item,
6384 high_priority,
6385 low_priority,
6386 saved_next_switch_items,
6387 futures: pending_futures,
6388 worker_item: _,
6389 trapped: _,
6390 unforced_current_thread: _,
6391 deferred_host_call_context: _,
6392 suspend_reason: _,
6393 global_error_context_ref_counts: _,
6394 interesting_tasks: _,
6395 interesting_tasks_empty_waker: _,
6396 idle_waker: _,
6397 backpressure_waker: _,
6398 event_loop_running: _,
6399 #[cfg(feature = "task-group-hook")]
6400 task_group_hook: _,
6401 } = self;
6402
6403 let mut items = Vec::new();
6404 for (_, entry) in table.get_mut().iter_mut() {
6405 let entry = entry.into_entry_mut();
6406 if let Some(set) = entry.downcast_mut::<WaitableSet>() {
6407 for mode in mem::take(&mut set.waiting).into_values() {
6408 match mode {
6409 WaitMode::Fiber(fiber) => {
6410 fibers.push(fiber);
6411 }
6412 WaitMode::Callback(_) => {}
6413 }
6414 }
6415 } else if let Some(thread) = entry.downcast_mut::<GuestThread>() {
6416 match mem::replace(&mut thread.state, GuestThreadState::Completed) {
6417 GuestThreadState::Suspended(fiber) | GuestThreadState::Ready { fiber } => {
6418 fibers.push(fiber);
6419 }
6420 GuestThreadState::NotStartedImplicit
6421 | GuestThreadState::NotStartedExplicit(_)
6422 | GuestThreadState::Running
6423 | GuestThreadState::Completed => {}
6424 }
6425 } else if let Some(item) = entry.downcast_mut::<Option<WorkItem>>() {
6426 if let Some(item) = item.take() {
6427 items.push(item);
6428 }
6429 }
6430 }
6431
6432 if let Some(fiber) = worker.take() {
6433 fibers.push(fiber);
6434 }
6435
6436 let mut handle_item = |item| match item {
6437 WorkItem::ResumeFiber { fiber, .. } => {
6438 fibers.push(fiber);
6439 }
6440 WorkItem::PushFuture(future) => {
6441 pending_futures
6442 .get_mut()
6443 .as_mut()
6444 .unwrap()
6445 .push(future.into_inner());
6446 }
6447 WorkItem::ResumeThread { .. }
6448 | WorkItem::GuestCall { .. }
6449 | WorkItem::WorkerFunction(_) => {}
6450 };
6451
6452 for item in items {
6453 handle_item(item);
6454 }
6455 if let Some(item) = switch_item.take() {
6456 handle_item(item);
6457 }
6458 if let Some(item) = next_switch_item.take() {
6459 handle_item(item);
6460 }
6461 for item in mem::take(high_priority) {
6462 handle_item(item);
6463 }
6464 for item in mem::take(low_priority) {
6465 handle_item(item);
6466 }
6467 for item in mem::take(saved_next_switch_items)
6468 .into_iter()
6469 .filter_map(|v| v)
6470 {
6471 handle_item(item);
6472 }
6473
6474 if let Some(them) = pending_futures.get_mut().take() {
6475 futures.push(them);
6476 }
6477 }
6478
6479 #[cfg(feature = "gc")]
6480 pub(crate) fn trace_fiber_roots(
6481 &mut self,
6482 modules: &ModuleRegistry,
6483 unwind: &dyn Unwind,
6484 gc_roots_list: &mut GcRootsList,
6485 ) {
6486 let ConcurrentState {
6487 table,
6488 worker,
6489 switch_item,
6490 next_switch_item,
6491 high_priority,
6492 low_priority,
6493 saved_next_switch_items,
6494
6495 futures: _,
6499
6500 worker_item: _,
6502 trapped: _,
6503 unforced_current_thread: _,
6504 deferred_host_call_context: _,
6505 suspend_reason: _,
6506 global_error_context_ref_counts: _,
6507 interesting_tasks: _,
6508 interesting_tasks_empty_waker: _,
6509 idle_waker: _,
6510 backpressure_waker: _,
6511 event_loop_running: _,
6512 #[cfg(feature = "task-group-hook")]
6513 task_group_hook: _,
6514 } = self;
6515
6516 for (_, entry) in table.get_mut().iter_mut() {
6517 let entry = entry.into_entry_mut();
6518 if let Some(set) = entry.downcast_mut::<WaitableSet>() {
6519 for mode in set.waiting.values_mut() {
6520 match mode {
6521 WaitMode::Fiber(fiber) => {
6522 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6523 }
6524 WaitMode::Callback(_) => {}
6525 }
6526 }
6527 } else if let Some(thread) = entry.downcast_mut::<GuestThread>() {
6528 match &mut thread.state {
6529 GuestThreadState::Suspended(fiber) | GuestThreadState::Ready { fiber } => {
6530 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6531 }
6532 GuestThreadState::NotStartedImplicit
6533 | GuestThreadState::NotStartedExplicit(_)
6534 | GuestThreadState::Running
6535 | GuestThreadState::Completed => {}
6536 }
6537 } else if let Some(Some(WorkItem::ResumeFiber { fiber, .. })) =
6538 entry.downcast_mut::<Option<WorkItem>>()
6539 {
6540 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6541 }
6542 }
6543
6544 if let Some(fiber) = worker {
6545 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6546 }
6547
6548 let mut handle_item = |item: &mut WorkItem| match item {
6549 WorkItem::ResumeFiber { fiber, .. } => {
6550 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6551 }
6552 WorkItem::PushFuture(_future) => {
6553 }
6556 WorkItem::ResumeThread { .. }
6557 | WorkItem::GuestCall { .. }
6558 | WorkItem::WorkerFunction(_) => {}
6559 };
6560
6561 if let Some(item) = switch_item {
6562 handle_item(item);
6563 }
6564 if let Some(item) = next_switch_item {
6565 handle_item(item);
6566 }
6567 for item in high_priority {
6568 handle_item(item);
6569 }
6570 for item in low_priority {
6571 handle_item(item);
6572 }
6573 for item in saved_next_switch_items
6574 .iter_mut()
6575 .filter_map(|v| v.as_mut())
6576 {
6577 handle_item(item);
6578 }
6579 }
6580
6581 fn schedule_suspended_thread(
6582 &mut self,
6583 thread: QualifiedThreadId,
6584 instance: RuntimeInstance,
6585 priority: Priority,
6586 ) -> Result<()> {
6587 if matches!(priority, Priority::Switch) && self.switch_item.is_some() {
6589 bail_bug!("switch item already set");
6590 }
6591 let slot = &mut self.get_mut(thread.thread)?.state;
6592 if !matches!(slot, GuestThreadState::Suspended(_)) {
6593 bail!(Trap::CannotResumeThread);
6594 }
6595 let GuestThreadState::Suspended(fiber) = mem::replace(slot, GuestThreadState::Running)
6596 else {
6597 unreachable!()
6598 };
6599 let item = WorkItem::ResumeFiber {
6600 instance,
6601 thread,
6602 fiber,
6603 };
6604 match priority {
6605 Priority::Switch => self.switch_item = Some(item),
6606 Priority::High => self.push_high_priority(item),
6607 Priority::Low => self.push_low_priority(item),
6608 }
6609 Ok(())
6610 }
6611
6612 fn set_thread_running(&mut self, thread: TableId<GuestThread>) -> Result<()> {
6613 let slot = &mut self.get_mut(thread)?.state;
6614 slot.check_no_fiber()?;
6615 *slot = GuestThreadState::Running;
6616 Ok(())
6617 }
6618
6619 fn save_next_switch_item(&mut self) -> Result<TableId<Option<WorkItem>>> {
6620 let saved = self.push(None::<WorkItem>)?;
6623 let slot = self.table.get_mut().get_mut(&Resource::from(saved))?;
6624 *slot = self.next_switch_item.take();
6625 Ok(saved)
6626 }
6627
6628 fn restore_next_switch_item(&mut self, saved: TableId<Option<WorkItem>>) -> Result<()> {
6629 if self.next_switch_item.is_some() {
6630 bail_bug!("next switch item already set when restoring");
6631 }
6632 self.next_switch_item = self.delete(saved)?;
6633 Ok(())
6634 }
6635
6636 fn take_callback_waiter(
6637 &mut self,
6638 set: TableId<WaitableSet>,
6639 thread: QualifiedThreadId,
6640 ) -> Result<Instance> {
6641 let waiting = &mut self.get_mut(set)?.waiting;
6642 let instance = match waiting.get(&thread) {
6643 Some(WaitMode::Callback(instance)) => *instance,
6644 other => bail_bug!("expected `Some(WaitMode::Callback(_))`; got `{other:?}`"),
6645 };
6646 waiting.remove(&thread);
6647 Ok(instance)
6648 }
6649
6650 fn push<V: Send + Sync + 'static>(
6651 &mut self,
6652 value: V,
6653 ) -> Result<TableId<V>, ResourceTableError> {
6654 self.table.get_mut().push(value).map(TableId::from)
6655 }
6656
6657 fn get_mut<V: 'static>(&mut self, id: TableId<V>) -> Result<&mut V, ResourceTableError> {
6658 self.table.get_mut().get_mut(&Resource::from(id))
6659 }
6660
6661 pub fn add_child<T: 'static, U: 'static>(
6662 &mut self,
6663 child: TableId<T>,
6664 parent: TableId<U>,
6665 ) -> Result<(), ResourceTableError> {
6666 self.table
6667 .get_mut()
6668 .add_child(Resource::from(child), Resource::from(parent))
6669 }
6670
6671 pub fn remove_child<T: 'static, U: 'static>(
6672 &mut self,
6673 child: TableId<T>,
6674 parent: TableId<U>,
6675 ) -> Result<(), ResourceTableError> {
6676 self.table
6677 .get_mut()
6678 .remove_child(Resource::from(child), Resource::from(parent))
6679 }
6680
6681 fn delete<V: 'static>(&mut self, id: TableId<V>) -> Result<V, ResourceTableError> {
6682 self.table.get_mut().delete(Resource::from(id))
6683 }
6684
6685 fn push_future(&mut self, future: HostTaskFuture) {
6686 self.push_high_priority(WorkItem::PushFuture(AlwaysMut::new(future)));
6693 }
6694
6695 fn set_switch_item(&mut self, item: WorkItem) -> Result<()> {
6696 if self.switch_item.is_some() {
6697 self.push_high_priority(item);
6700 bail_bug!("switch item already set");
6701 }
6702
6703 self.switch_item = Some(item);
6704 log::trace!("set switch item: {:?}", self.switch_item.as_ref().unwrap());
6705
6706 Ok(())
6707 }
6708
6709 fn take_next_switch_item(&mut self) -> Result<()> {
6710 if let Some(item) = self.next_switch_item.take() {
6711 self.set_switch_item(item)?;
6712 }
6713 Ok(())
6714 }
6715
6716 fn wake_waiter(&mut self, set: TableId<WaitableSet>) -> Result<()> {
6719 let Some((&thread, _)) = self.get_mut(set)?.waiting.first_key_value() else {
6722 return Ok(());
6723 };
6724 let wake_on_cancel = self.get_mut(thread.thread)?.wake_on_cancel;
6725 if wake_on_cancel != WakeOnCancel::None && wake_on_cancel != WakeOnCancel::Waiting(set) {
6726 bail_bug!("thread {thread:?} has unexpected wake_on_cancel value {wake_on_cancel:?}");
6727 }
6728 let instance = self.get_mut(thread.task)?.instance;
6729 self.get_mut(thread.thread)?.wake_on_cancel.take();
6730 let (_, mode) = self.get_mut(set)?.waiting.pop_first().unwrap();
6731
6732 let item = match mode {
6733 WaitMode::Fiber(fiber) => WorkItem::ResumeFiber {
6734 instance,
6735 thread,
6736 fiber,
6737 },
6738 WaitMode::Callback(callback_instance) => WorkItem::GuestCall {
6739 instance,
6740 call: GuestCall {
6741 thread,
6742 kind: GuestCallKind::DeliverEvent {
6743 instance: callback_instance,
6744 set: Some(set),
6745 },
6746 },
6747 },
6748 };
6749 self.push_high_priority(item);
6750 Ok(())
6751 }
6752
6753 fn push_high_priority(&mut self, item: WorkItem) {
6754 self.high_priority.push_front(item);
6755 log::trace!(
6756 "push high priority: {:?}",
6757 self.high_priority.front().unwrap()
6758 );
6759 }
6760
6761 fn push_low_priority(&mut self, item: WorkItem) {
6762 self.low_priority.push_front(item);
6763 log::trace!(
6764 "push low priority: {:?}",
6765 self.low_priority.front().unwrap()
6766 );
6767 }
6768
6769 fn push_work_item(&mut self, item: WorkItem, priority: Priority) -> Result<()> {
6770 match priority {
6771 Priority::Switch => self.set_switch_item(item)?,
6772 Priority::High => self.push_high_priority(item),
6773 Priority::Low => self.push_low_priority(item),
6774 }
6775
6776 Ok(())
6777 }
6778
6779 fn promote_instance_local_thread_work_item(
6780 &mut self,
6781 current_instance: RuntimeInstance,
6782 ) -> Result<bool> {
6783 log::trace!("promote thread work items for {current_instance:?}");
6784
6785 self.promote_work_item_matching(|item: &WorkItem| {
6786 let result = match item {
6787 WorkItem::ResumeThread { instance, .. }
6788 | WorkItem::ResumeFiber { instance, .. }
6789 | WorkItem::GuestCall { instance, .. } => *instance == current_instance,
6790 _ => false,
6791 };
6792
6793 log::trace!("candidate {item:?}: {result}");
6794 result
6795 })
6796 }
6797
6798 fn promote_thread_work_item(&mut self, thread: QualifiedThreadId) -> Result<bool> {
6799 self.promote_work_item_matching(|item: &WorkItem| match item {
6800 WorkItem::ResumeThread {
6801 thread: item_thread,
6802 ..
6803 }
6804 | WorkItem::GuestCall {
6805 call:
6806 GuestCall {
6807 thread: item_thread,
6808 ..
6809 },
6810 ..
6811 } => *item_thread == thread,
6812 _ => false,
6813 })
6814 }
6815
6816 fn promote_work_item_matching<F>(&mut self, mut predicate: F) -> Result<bool>
6817 where
6818 F: FnMut(&WorkItem) -> bool,
6819 {
6820 if self.switch_item.is_none() {
6827 if let Some(index) = self.high_priority.iter().rposition(&mut predicate) {
6828 self.switch_item = self.high_priority.remove(index);
6829 }
6830 }
6831 if self.switch_item.is_none() {
6832 if let Some(index) = self.low_priority.iter().rposition(predicate) {
6833 self.switch_item = self.low_priority.remove(index);
6834 }
6835 }
6836 Ok(self.switch_item.is_some())
6837 }
6838
6839 pub fn call_context(&mut self, task: VMScope) -> Result<&mut CallContext> {
6842 match task.kind() {
6843 ScopeKind::HostId(task) => {
6844 let task: TableId<HostTask> = TableId::new(task);
6845 Ok(&mut self.get_mut(task)?.call_context)
6846 }
6847 ScopeKind::Id(task) => {
6848 let task: TableId<GuestTask> = TableId::new(task);
6849 Ok(&mut self.get_mut(task)?.call_context)
6850 }
6851 }
6852 }
6853
6854 pub(crate) fn deferred_host_call_context(&mut self) -> Option<&mut CallContext> {
6855 self.deferred_host_call_context.as_mut()
6856 }
6857
6858 fn futures_mut(&mut self) -> Result<&mut FuturesUnordered<HostTaskFuture>> {
6859 match self.futures.get_mut().as_mut() {
6860 Some(f) => Ok(f),
6861 None => bail_bug!("futures field of concurrent state is currently taken"),
6862 }
6863 }
6864
6865 pub(crate) fn table(&mut self) -> &mut ResourceTable {
6866 self.table.get_mut()
6867 }
6868
6869 fn debug_assert_deferred_host_invariant(&self) {
6870 debug_assert_eq!(
6871 self.deferred_host_call_context.is_some(),
6872 matches!(self.unforced_current_thread, CurrentThread::DeferredHost(_)),
6873 "a deferred host thread and call context must exist together",
6874 );
6875 }
6876
6877 fn materialize_host_task(&mut self) -> Result<CurrentThread> {
6878 self.debug_assert_deferred_host_invariant();
6879 let caller = match self.unforced_current_thread {
6880 CurrentThread::DeferredHost(caller) => caller,
6881 thread => return Ok(thread),
6882 };
6883
6884 let task = HostTask::new(self, HostTaskState::CalleeStarted, caller)?;
6886 let task = self.push(task)?;
6887 let call_context = self
6888 .deferred_host_call_context
6889 .take()
6890 .expect("deferred host call context should be present");
6891 self.get_mut(task)
6892 .expect("newly inserted host task should be present")
6893 .call_context = call_context;
6894 self.unforced_current_thread = CurrentThread::Host(task);
6895 self.debug_assert_deferred_host_invariant();
6896 log::trace!("new host task materialized {task:?}");
6897 Ok(CurrentThread::Host(task))
6898 }
6899
6900 #[inline]
6901 pub(crate) fn trapped(&self) -> bool {
6902 self.trapped
6903 }
6904
6905 #[inline]
6906 pub(crate) fn set_trapped(&mut self) {
6907 self.trapped = true;
6908 }
6909
6910 fn materialize_current_host_task_id(&mut self) -> Result<Option<TableId<HostTask>>> {
6911 match self.materialize_host_task()? {
6912 CurrentThread::Host(id) => Ok(Some(id)),
6913 CurrentThread::None => Ok(None),
6914 CurrentThread::Guest(_) => {
6915 if self.trapped {
6918 bail!(Trap::CannotEnterComponent)
6919 } else {
6920 bail_bug!("tried to materialize a host task id from a guest thread")
6921 }
6922 }
6923 CurrentThread::DeferredHost(_) => {
6924 bail_bug!(
6925 "current thread is a deferred host thread which should have been materialized"
6926 )
6927 }
6928 }
6929 }
6930
6931 pub(crate) fn materialize_current_scope(&mut self) -> Result<VMScope> {
6932 match self.materialize_host_task()? {
6933 CurrentThread::Host(id) => Ok(VMScope::host_id(id.rep())),
6934 _ => bail_bug!("current scope is not a deferred host scope"),
6935 }
6936 }
6937
6938 fn increment_task_ref_count(&mut self, task: TableId<GuestTask>) -> Result<()> {
6939 let count = &mut self.get_mut(task)?.ref_count;
6940 *count += 1;
6941 log::trace!("increment {task:?} to {count}");
6942 Ok(())
6943 }
6944
6945 fn decrement_task_ref_count(&mut self, task: TableId<GuestTask>) -> Result<()> {
6946 let count = &mut self.get_mut(task)?.ref_count;
6947 if *count == 0 {
6948 bail_bug!("can't decrement task ref count that's already zero");
6949 }
6950 *count -= 1;
6951 log::trace!("decrement {task:?} to {count}");
6952 if *count == 0 {
6953 let task = self.delete(task)?;
6954
6955 self.decrement_group_ref_count(task.group)?;
6956
6957 debug_assert!(task.decremented_interesting_task_count);
6964 }
6965 Ok(())
6966 }
6967
6968 fn delete_host_task(&mut self, task: TableId<HostTask>) -> Result<()> {
6969 log::trace!("delete host task {task:?}");
6970 let task = self.delete(task)?;
6971
6972 self.decrement_group_ref_count(task.group)
6973 }
6974}
6975
6976fn for_any_lower<
6979 F: FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync,
6980>(
6981 fun: F,
6982) -> F {
6983 fun
6984}
6985
6986fn for_any_lift<
6988 F: FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
6989>(
6990 fun: F,
6991) -> F {
6992 fun
6993}
6994
6995fn check_ambient_store(id: StoreId) {
6996 let message = "\
6997 `Future`s which depend on asynchronous component tasks, streams, or \
6998 futures to complete may only be polled from the event loop of the \
6999 store to which they belong. Please use \
7000 `StoreContextMut::{run_concurrent,spawn}` to poll or await them.\
7001 ";
7002 tls::try_get(|store| {
7003 let matched = match store {
7004 tls::TryGet::Some(store) => store.id() == id,
7005 tls::TryGet::Taken | tls::TryGet::None => false,
7006 };
7007
7008 if !matched {
7009 panic!("{message}")
7010 }
7011 });
7012}
7013
7014fn unpack_callback_code(code: u32) -> (u32, u32) {
7015 (code & 0xF, code >> 4)
7016}
7017
7018struct WaitableCheckParams {
7022 set: TableId<WaitableSet>,
7023 options: OptionsIndex,
7024 payload: u32,
7025}
7026
7027enum WaitableCheck {
7030 Wait,
7031 Poll,
7032}
7033
7034pub(crate) struct PreparedCall<R> {
7036 handle: Func,
7038 thread: QualifiedThreadId,
7040 param_count: usize,
7042 rx: oneshot::Receiver<LiftedResult>,
7045 _phantom: PhantomData<R>,
7046}
7047
7048impl<R> PreparedCall<R> {
7049 pub(crate) fn acquire_task_id(&self, store: &mut StoreOpaque) -> Result<TaskId> {
7056 store
7057 .concurrent_state_mut()?
7058 .increment_task_ref_count(self.thread.task)?;
7059
7060 Ok(TaskId {
7061 task: self.thread.task,
7062 })
7063 }
7064}
7065
7066pub(crate) struct TaskId {
7068 task: TableId<GuestTask>,
7069}
7070
7071impl TaskId {
7072 pub(crate) fn host_future_dropped(&self, store: &mut StoreOpaque) -> Result<()> {
7084 let task = store.concurrent_state_mut()?.get_mut(self.task)?;
7085 if !task.already_lowered_parameters() {
7086 task.lower_params = Some(Box::new(|store, _| {
7091 store.set_trapped();
7092 bail!("the host future for this call was dropped before it started")
7093 }));
7094 } else {
7095 _ = store
7100 .concurrent_state_mut()?
7101 .decrement_task_ref_count(self.task);
7102 }
7103
7104 Ok(())
7105 }
7106}
7107
7108pub(crate) fn prepare_call<T, R>(
7114 mut store: StoreContextMut<T>,
7115 handle: Func,
7116 param_count: usize,
7117 lower_params: impl FnOnce(StoreContextMut<T>, &mut [MaybeUninit<ValRaw>]) -> Result<()>
7118 + Send
7119 + Sync
7120 + 'static,
7121 lift_result: impl FnOnce(&mut StoreOpaque, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>>
7122 + Send
7123 + Sync
7124 + 'static,
7125) -> Result<PreparedCall<R>> {
7126 let (options, _flags, ty, raw_options) = handle.abi_info(store.0);
7127
7128 let instance = handle.instance().id().get(store.0);
7129 let options = &instance.component().env_component().options[options];
7130 let ty = &instance.component().types()[ty];
7131 let async_typed = ty.async_;
7132 let async_lifted = raw_options.async_;
7133 let task_return_type = ty.results;
7134 let component_instance = raw_options.instance;
7135 let callback = options.callback.map(|i| instance.runtime_callback(i));
7136 let memory = options
7137 .memory()
7138 .map(|i| instance.runtime_memory(i))
7139 .map(SendSyncPtr::new);
7140 let string_encoding = options.string_encoding;
7141 let token = StoreToken::new(store.as_context_mut());
7142 let caller = store.0.materialize_host_task_id()?;
7143 let state = store.0.concurrent_state_mut()?;
7144
7145 let (tx, rx) = oneshot::channel();
7146
7147 let instance = handle.instance().runtime_instance(component_instance);
7148 let thread = GuestTask::new(
7149 state,
7150 Box::new(for_any_lower(move |store, params| {
7151 lower_params(token.as_context_mut(store), params)
7152 })),
7153 LiftResult {
7154 lift: Box::new(for_any_lift(move |store, result| {
7155 lift_result(store, result)
7156 })),
7157 ty: task_return_type,
7158 memory,
7159 string_encoding,
7160 },
7161 Caller::Host {
7162 tx: Some(tx),
7163 caller,
7164 },
7165 callback.map(|callback| {
7166 let callback = SendSyncPtr::new(callback);
7167 let instance = handle.instance();
7168 Box::new(move |store: &mut dyn VMStore, event, handle| {
7169 let store = token.as_context_mut(store);
7170 unsafe { instance.call_callback(store, callback, event, handle) }
7173 }) as CallbackFn
7174 }),
7175 instance,
7176 async_typed,
7177 async_lifted,
7178 )?;
7179
7180 Ok(PreparedCall {
7181 handle,
7182 thread,
7183 param_count,
7184 rx,
7185 _phantom: PhantomData,
7186 })
7187}
7188
7189pub(crate) struct StagedCall<R> {
7190 store: StoreId,
7191 rx: oneshot::Receiver<LiftedResult>,
7192 _marker: PhantomData<fn() -> R>,
7193 group: TaskGroupId,
7201}
7202
7203impl<R> StagedCall<R> {
7204 pub(crate) fn new<T: 'static>(
7215 mut store: StoreContextMut<T>,
7216 prepared: PreparedCall<R>,
7217 ) -> Result<StagedCall<R>> {
7218 let PreparedCall {
7219 handle,
7220 thread,
7221 param_count,
7222 rx,
7223 ..
7224 } = prepared;
7225
7226 stage_call0(store.as_context_mut(), handle, thread, param_count)?;
7227
7228 let state = store.0.concurrent_state_mut()?;
7229 let group = state.get_mut(thread.task)?.group;
7230 state.decrement_task_ref_count(thread.task)?;
7231
7232 Ok(StagedCall {
7233 store: store.0.id(),
7234 rx,
7235 _marker: PhantomData,
7236 group,
7237 })
7238 }
7239}
7240
7241impl<R> Future for StagedCall<R>
7242where
7243 R: 'static,
7244{
7245 type Output = Result<R>;
7246
7247 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
7248 check_ambient_store(self.store);
7249 Pin::new(&mut self.rx).poll(cx).map(|result| match result {
7250 Ok(r) => match r.downcast() {
7251 Ok(r) => Ok(*r),
7252 Err(_) => bail_bug!("wrong type of value produced"),
7253 },
7254 Err(oneshot::Canceled) => bail_bug!("channel erroneously dropped"),
7255 })
7256 }
7257}
7258
7259fn stage_call0<T: 'static>(
7262 store: StoreContextMut<T>,
7263 handle: Func,
7264 guest_thread: QualifiedThreadId,
7265 param_count: usize,
7266) -> Result<()> {
7267 let (_options, _, _ty, raw_options) = handle.abi_info(store.0);
7268 let is_concurrent = raw_options.async_;
7269 let callback = raw_options.callback;
7270 let instance = handle.instance();
7271 let callee = handle.lifted_core_func(store.0);
7272 let post_return = raw_options
7273 .post_return
7274 .map(|i| instance.id().get(store.0).runtime_post_return(i));
7275 let callback = callback.map(|i| {
7276 let instance = instance.id().get(store.0);
7277 SendSyncPtr::new(instance.runtime_callback(i))
7278 });
7279
7280 log::trace!("queueing call {guest_thread:?}");
7281
7282 unsafe {
7286 instance.stage_call(
7287 store,
7288 guest_thread,
7289 SendSyncPtr::new(callee),
7290 param_count,
7291 1,
7292 is_concurrent,
7293 callback,
7294 post_return.map(SendSyncPtr::new),
7295 true,
7296 )
7297 }
7298}
7299
7300#[cfg(all(test, feature = "cranelift", feature = "wat"))]
7301mod tests {
7302 use super::*;
7303 use crate::component::{Component, Linker};
7304 use crate::store::AsStoreOpaque;
7305 use crate::{Config, Engine};
7306
7307 fn host_subtask(
7308 state: HostTaskState,
7309 event: Option<Event>,
7310 ) -> Result<(Store<()>, Instance, TableId<HostTask>, u32)> {
7311 let mut config = Config::new();
7312 config.wasm_component_model_async(true);
7313 let engine = Engine::new(&config)?;
7314 let component = Component::new(&engine, "(component)")?;
7315 let mut store = Store::new(&engine, ());
7316 let instance = Linker::new(&engine).instantiate(&mut store, &component)?;
7317 let store_opaque = store.as_store_opaque();
7318 let concurrent_state = store_opaque.concurrent_state_mut()?;
7319 let group = concurrent_state.make_task_group()?;
7322 let task = concurrent_state.push(HostTask {
7323 common: WaitableCommon::default(),
7324 call_context: CallContext::default(),
7325 state,
7326 group,
7327 })?;
7328 let handle = store_opaque
7329 .handle_table_insertion(
7330 instance.runtime_instance(RuntimeComponentInstanceIndex::from_u32(0)),
7331 )
7332 .subtask_host(task.rep())?;
7333 let common = &mut store_opaque.concurrent_state_mut()?.get_mut(task)?.common;
7334 common.handle = Some(handle);
7335 common.event = event;
7336 Ok((store, instance, task, handle))
7337 }
7338
7339 #[test]
7340 fn host_subtask_drop_during_cancellation() -> Result<()> {
7341 for abort_completed in [false, true] {
7342 let (handle, future) = JoinHandle::run(future::pending::<()>());
7343 let mut future = pin!(future);
7344 let (mut store, instance, task, handle) =
7345 host_subtask(HostTaskState::CalleeRunning(handle), None)?;
7346 let store = store.as_store_opaque();
7347 let caller = RuntimeComponentInstanceIndex::from_u32(0);
7348 assert_eq!(
7349 instance.subtask_cancel(store, caller, true, handle)?,
7350 BLOCKED
7351 );
7352 if abort_completed {
7353 assert!(matches!(
7356 future
7357 .as_mut()
7358 .poll(&mut Context::from_waker(Waker::noop())),
7359 Poll::Ready(None),
7360 ));
7361 }
7362 for async_ in [false, true] {
7363 let err = instance
7364 .subtask_cancel(store, caller, async_, handle)
7365 .unwrap_err();
7366 assert_eq!(err.downcast::<Trap>()?, Trap::SubtaskCancelAfterTerminal);
7367 }
7368 let err = instance.subtask_drop(store, caller, handle).unwrap_err();
7369 assert_eq!(err.downcast::<Trap>()?, Trap::SubtaskDropNotResolved);
7370 assert!(store.concurrent_state_mut()?.get_mut(task).is_ok());
7371 }
7372 Ok(())
7373 }
7374
7375 #[test]
7376 fn host_subtask_cancel_after_completion() -> Result<()> {
7377 for async_ in [false, true] {
7378 let (mut store, instance, task, handle) = host_subtask(
7379 HostTaskState::CalleeDone { cancelled: false },
7380 Some(Event::Subtask {
7381 status: Status::Returned,
7382 }),
7383 )?;
7384 let store = store.as_store_opaque();
7385 let caller = RuntimeComponentInstanceIndex::from_u32(0);
7386 assert_eq!(
7387 instance.subtask_cancel(store, caller, async_, handle)?,
7388 Status::Returned as u32,
7389 );
7390 let err = instance
7391 .subtask_cancel(store, caller, async_, handle)
7392 .unwrap_err();
7393 assert_eq!(err.downcast::<Trap>()?, Trap::SubtaskCancelAfterTerminal);
7394 instance.subtask_drop(store, caller, handle)?;
7395 assert!(store.concurrent_state_mut()?.get_mut(task).is_err());
7396 }
7397 Ok(())
7398 }
7399
7400 #[test]
7401 fn host_subtask_drop_requires_terminal_event_delivery() -> Result<()> {
7402 for (cancelled, status) in [
7403 (false, Status::Returned),
7404 (true, Status::Returned),
7405 (true, Status::ReturnCancelled),
7406 ] {
7407 for delivered in [false, true] {
7408 let event = if delivered {
7409 None
7410 } else {
7411 Some(Event::Subtask { status })
7412 };
7413 let (mut store, instance, task, handle) =
7414 host_subtask(HostTaskState::CalleeDone { cancelled }, event)?;
7415 let store = store.as_store_opaque();
7416 let result = instance.subtask_drop(
7417 store,
7418 RuntimeComponentInstanceIndex::from_u32(0),
7419 handle,
7420 );
7421 if delivered {
7422 result?;
7423 assert!(store.concurrent_state_mut()?.get_mut(task).is_err());
7424 } else {
7425 let err = result.unwrap_err();
7426 assert_eq!(err.downcast::<Trap>()?, Trap::SubtaskDropNotResolved);
7427 assert!(store.concurrent_state_mut()?.get_mut(task).is_ok());
7428 }
7429 }
7430 }
7431 Ok(())
7432 }
7433}