1use self::error_contexts::GlobalErrorContextRefCount;
54use crate::component::func::{Func, call_post_return};
55use crate::component::{
56 HasData, HasSelf, Instance, Resource, ResourceTable, ResourceTableError, RuntimeInstance,
57};
58use crate::fiber::{self, StoreFiber, StoreFiberYield};
59use crate::hash_set::HashSet;
60#[cfg(feature = "gc")]
61use crate::module::ModuleRegistry;
62use crate::prelude::*;
63use crate::store::{Store, StoreId, StoreInner, StoreOpaque, StoreToken};
64#[cfg(feature = "gc")]
65use crate::vm::GcRootsList;
66use crate::vm::component::{
67 CallContext, ComponentInstance, CurrentScope, HandleCounter, InstanceState, Scope,
68};
69use crate::vm::{
70 AlwaysMut, SendSyncPtr, UncaughtException, VMFuncRef, VMLazyThread, VMMemoryDefinition, VMStore,
71};
72use crate::{AsContext, AsContextMut, Result, StoreContext, StoreContextMut, ValRaw, bail};
73use crate::{Instance as ModuleInstance, bail_bug};
74use alloc::borrow::ToOwned;
75use alloc::collections::btree_map::Entry;
76use alloc::collections::{BTreeMap, BTreeSet, VecDeque};
77use core::any::Any;
78use core::cell::UnsafeCell;
79use core::fmt;
80use core::future;
81use core::future::Future;
82use core::marker::PhantomData;
83use core::mem::{self, ManuallyDrop, MaybeUninit};
84use core::ops::DerefMut;
85use core::pin::{Pin, pin};
86use core::ptr::{self, NonNull};
87use core::task::{Context, Poll, Waker};
88use futures::channel::oneshot;
89use futures::stream::{FuturesUnordered, StreamExt};
90use futures_and_streams::{FlatAbi, ReturnCode, TransmitHandle, TransmitIndex};
91use table::{TableDebug, TableId};
92use wasmtime_environ::component::{
93 CanonicalAbiInfo, CanonicalOptions, CanonicalOptionsDataModel, MAX_FLAT_PARAMS,
94 MAX_FLAT_RESULTS, OptionsIndex, PREPARE_ASYNC_NO_RESULT, PREPARE_ASYNC_WITH_RESULT,
95 RuntimeComponentInstanceIndex, RuntimeTableIndex, StringEncoding,
96 TypeComponentGlobalErrorContextTableIndex, TypeComponentLocalErrorContextTableIndex,
97 TypeFutureTableIndex, TypeStreamTableIndex, TypeTupleIndex,
98};
99use wasmtime_environ::packed_option::ReservedValue;
100use wasmtime_environ::{ModuleInternedTypeIndex, NUM_COMPONENT_CONTEXT_SLOTS, Trap};
101#[cfg(feature = "gc")]
102use wasmtime_unwinder::Unwind;
103
104pub use abort::JoinHandle;
105pub use func::{FuncCallConcurrent, TypedFuncCallConcurrent};
106pub use future_stream_any::{FutureAny, StreamAny};
107pub use futures_and_streams::{
108 Destination, DirectDestination, DirectSource, ErrorContext, FutureConsumer, FutureProducer,
109 FutureReader, GuardedFutureReader, GuardedStreamReader, ReadBuffer, Source, StreamConsumer,
110 StreamProducer, StreamReader, StreamResult, VecBuffer, WriteBuffer,
111};
112pub(crate) use futures_and_streams::{ResourcePair, lower_error_context_to_index};
113#[cfg(feature = "task-group-hook")]
114pub use task_group_hook::TaskGroupHook;
115pub use task_group_hook::TaskGroupId;
116
117mod abort;
118mod error_contexts;
119mod func;
120mod future_stream_any;
121mod futures_and_streams;
122pub(crate) mod table;
123#[cfg(feature = "task-group-hook")]
124mod task_group_hook;
125#[cfg(not(feature = "task-group-hook"))]
126mod task_group_hook_disabled;
127#[cfg(not(feature = "task-group-hook"))]
128use task_group_hook_disabled as task_group_hook;
129pub(crate) mod tls;
130
131const BLOCKED: u32 = 0xffff_ffff;
134
135#[derive(Clone, Copy, Eq, PartialEq, Debug)]
137pub enum Status {
138 Starting = 0,
139 Started = 1,
140 Returned = 2,
141 StartCancelled = 3,
142 ReturnCancelled = 4,
143}
144
145impl Status {
146 pub fn pack(self, waitable: Option<u32>) -> u32 {
152 assert!(matches!(self, Status::Returned) == waitable.is_none());
153 let waitable = waitable.unwrap_or(0);
154 assert!(waitable < (1 << 28));
155 (waitable << 4) | (self as u32)
156 }
157}
158
159#[derive(Clone, Copy, Debug)]
162enum Event {
163 None,
164 Subtask {
165 status: Status,
166 },
167 StreamRead {
168 code: ReturnCode,
169 pending: Option<(TypeStreamTableIndex, u32)>,
170 },
171 StreamWrite {
172 code: ReturnCode,
173 pending: Option<(TypeStreamTableIndex, u32)>,
174 },
175 FutureRead {
176 code: ReturnCode,
177 pending: Option<(TypeFutureTableIndex, u32)>,
178 },
179 FutureWrite {
180 code: ReturnCode,
181 pending: Option<(TypeFutureTableIndex, u32)>,
182 },
183 Cancelled,
184}
185
186impl Event {
187 fn parts(self) -> (u32, u32) {
192 const EVENT_NONE: u32 = 0;
193 const EVENT_SUBTASK: u32 = 1;
194 const EVENT_STREAM_READ: u32 = 2;
195 const EVENT_STREAM_WRITE: u32 = 3;
196 const EVENT_FUTURE_READ: u32 = 4;
197 const EVENT_FUTURE_WRITE: u32 = 5;
198 const EVENT_CANCELLED: u32 = 6;
199 match self {
200 Event::None => (EVENT_NONE, 0),
201 Event::Cancelled => (EVENT_CANCELLED, 0),
202 Event::Subtask { status } => (EVENT_SUBTASK, status as u32),
203 Event::StreamRead { code, .. } => (EVENT_STREAM_READ, code.encode()),
204 Event::StreamWrite { code, .. } => (EVENT_STREAM_WRITE, code.encode()),
205 Event::FutureRead { code, .. } => (EVENT_FUTURE_READ, code.encode()),
206 Event::FutureWrite { code, .. } => (EVENT_FUTURE_WRITE, code.encode()),
207 }
208 }
209}
210
211mod callback_code {
213 pub const EXIT: u32 = 0;
214 pub const YIELD: u32 = 1;
215 pub const WAIT: u32 = 2;
216}
217
218const START_FLAG_ASYNC_CALLEE: u32 = wasmtime_environ::component::START_FLAG_ASYNC_CALLEE as u32;
220const START_FLAG_ASYNC_CALLER: u32 = wasmtime_environ::component::START_FLAG_ASYNC_CALLER as u32;
221
222pub struct Access<'a, T: 'static, D: HasData + ?Sized = HasSelf<T>> {
228 store: StoreContextMut<'a, T>,
229 get_data: fn(&mut T) -> D::Data<'_>,
230}
231
232impl<'a, T, D> Access<'a, T, D>
233where
234 D: HasData + ?Sized,
235 T: 'static,
236{
237 pub fn new(store: StoreContextMut<'a, T>, get_data: fn(&mut T) -> D::Data<'_>) -> Self {
239 Self { store, get_data }
240 }
241
242 pub fn data_mut(&mut self) -> &mut T {
244 self.store.data_mut()
245 }
246
247 pub fn get(&mut self) -> D::Data<'_> {
249 (self.get_data)(self.data_mut())
250 }
251
252 pub fn spawn(&mut self, task: impl for<'fut> AccessorTask<'fut, T, D>) -> Result<JoinHandle>
256 where
257 T: 'static,
258 {
259 let accessor = Accessor {
260 get_data: self.get_data,
261 token: StoreToken::new(self.store.as_context_mut()),
262 };
263 self.store
264 .as_context_mut()
265 .spawn_with_accessor(accessor, task)
266 }
267
268 pub fn getter(&self) -> fn(&mut T) -> D::Data<'_> {
271 self.get_data
272 }
273}
274
275impl<'a, T, D> AsContext for Access<'a, T, D>
276where
277 D: HasData + ?Sized,
278 T: 'static,
279{
280 type Data = T;
281
282 fn as_context(&self) -> StoreContext<'_, T> {
283 self.store.as_context()
284 }
285}
286
287impl<'a, T, D> AsContextMut for Access<'a, T, D>
288where
289 D: HasData + ?Sized,
290 T: 'static,
291{
292 fn as_context_mut(&mut self) -> StoreContextMut<'_, T> {
293 self.store.as_context_mut()
294 }
295}
296
297pub struct Accessor<T: 'static, D = HasSelf<T>>
357where
358 D: HasData + ?Sized,
359{
360 token: StoreToken<T>,
361 get_data: fn(&mut T) -> D::Data<'_>,
362}
363
364pub trait AsAccessor {
381 type Data: 'static;
383
384 type AccessorData: HasData + ?Sized;
387
388 fn as_accessor(&self) -> &Accessor<Self::Data, Self::AccessorData>;
390}
391
392impl<T: AsAccessor + ?Sized> AsAccessor for &T {
393 type Data = T::Data;
394 type AccessorData = T::AccessorData;
395
396 fn as_accessor(&self) -> &Accessor<Self::Data, Self::AccessorData> {
397 T::as_accessor(self)
398 }
399}
400
401impl<T, D: HasData + ?Sized> AsAccessor for Accessor<T, D> {
402 type Data = T;
403 type AccessorData = D;
404
405 fn as_accessor(&self) -> &Accessor<T, D> {
406 self
407 }
408}
409
410const _: () = {
433 const fn assert<T: Send + Sync>() {}
434 assert::<Accessor<UnsafeCell<u32>>>();
435};
436
437impl<T> Accessor<T> {
438 pub(crate) fn new(token: StoreToken<T>) -> Self {
447 Self {
448 token,
449 get_data: |x| x,
450 }
451 }
452}
453
454impl<T, D> Accessor<T, D>
455where
456 D: HasData + ?Sized,
457{
458 pub fn with<R>(&self, fun: impl FnOnce(Access<'_, T, D>) -> R) -> R {
476 tls::get(|vmstore| {
477 fun(Access {
478 store: self.token.as_context_mut(vmstore),
479 get_data: self.get_data,
480 })
481 })
482 }
483
484 pub fn getter(&self) -> fn(&mut T) -> D::Data<'_> {
487 self.get_data
488 }
489
490 pub fn with_getter<D2: HasData>(
507 &self,
508 get_data: fn(&mut T) -> D2::Data<'_>,
509 ) -> Accessor<T, D2> {
510 Accessor {
511 token: self.token,
512 get_data,
513 }
514 }
515
516 pub fn spawn(&self, task: impl for<'fut> AccessorTask<'fut, T, D>) -> Result<JoinHandle>
532 where
533 T: 'static,
534 {
535 let accessor = self.clone_for_spawn();
536 self.with(|mut access| access.as_context_mut().spawn_with_accessor(accessor, task))
537 }
538
539 fn clone_for_spawn(&self) -> Self {
540 Self {
541 token: self.token,
542 get_data: self.get_data,
543 }
544 }
545
546 pub fn poll_no_interesting_tasks(&self, cx: &mut Context<'_>) -> Poll<()> {
582 self.with(|mut access| {
583 let store = access.as_context_mut().0;
584 let state = store.concurrent_state_mut_without_forcing_current_thread();
585 if state.interesting_tasks == 0 {
586 Poll::Ready(())
587 } else {
588 state.interesting_tasks_empty_waker = Some(cx.waker().clone());
589 Poll::Pending
590 }
591 })
592 }
593
594 pub fn poll_ready_for_concurrent_call(&self, func: Func, cx: &mut Context<'_>) -> Poll<()> {
611 self.with(|mut access| {
612 let store = access.as_context_mut().0;
613 let (_, _, _, raw_options) = func.abi_info(store);
614 let instance = func.instance().runtime_instance(raw_options.instance);
615 let state = store.instance_state(instance).concurrent_state();
616 if state.backpressure == 0 {
617 Poll::Ready(())
618 } else {
619 store
620 .concurrent_state_mut_without_forcing_current_thread()
621 .ready_for_concurrent_call_waker = Some(cx.waker().clone());
622 Poll::Pending
623 }
624 })
625 }
626}
627
628pub trait AccessorTask<'fut, T, D = HasSelf<T>>:
650 AsyncFnOnce(&Accessor<T, D>) -> Result<()> + Send + 'static
651where
652 D: HasData + ?Sized,
653{
654 fn run(self, accessor: &'fut Accessor<T, D>) -> impl Future<Output = Result<()>> + Send + 'fut;
656}
657
658impl<'fut, F, Fut, T, D> AccessorTask<'fut, T, D> for F
659where
660 T: 'static,
661 F: AsyncFnOnce(&Accessor<T, D>) -> Result<()>,
662 F: FnOnce(&'fut Accessor<T, D>) -> Fut + Send + 'static,
663 Fut: Future<Output = Result<()>> + Send + 'fut,
664 D: HasData,
665{
666 fn run(self, accessor: &'fut Accessor<T, D>) -> impl Future<Output = Result<()>> + Send + 'fut {
667 (self)(accessor)
668 }
669}
670
671enum CallerInfo {
674 Async {
676 params: Vec<ValRaw>,
677 has_result: bool,
678 },
679 Sync {
681 params: Vec<ValRaw>,
682 result_count: u32,
683 },
684}
685
686enum WaitMode {
688 Fiber(StoreFiber<'static>),
690 Callback(Instance),
693}
694
695impl fmt::Debug for WaitMode {
696 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
697 match self {
698 Self::Fiber(_) => f.debug_tuple("Fiber").finish(),
699 Self::Callback(instance) => f.debug_tuple("Callback").field(instance).finish(),
700 }
701 }
702}
703
704#[derive(Debug)]
706enum SuspendReason {
707 Waiting {
710 set: TableId<WaitableSet>,
711 thread: QualifiedThreadId,
712 },
713 YieldingToSubtask { thread: QualifiedThreadId },
716 NeedWork,
719 Yielding { thread: QualifiedThreadId },
722 ExplicitlySuspending { thread: QualifiedThreadId },
725}
726
727enum GuestCallKind {
729 DeliverEvent {
732 instance: Instance,
734 set: Option<TableId<WaitableSet>>,
739 },
740 StartImplicit(Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send + Sync>),
743 StartExplicit(Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send + Sync>),
744}
745
746impl fmt::Debug for GuestCallKind {
747 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
748 match self {
749 Self::DeliverEvent { instance, set } => f
750 .debug_struct("DeliverEvent")
751 .field("instance", instance)
752 .field("set", set)
753 .finish(),
754 Self::StartImplicit(_) => f.debug_tuple("StartImplicit").finish(),
755 Self::StartExplicit(_) => f.debug_tuple("StartExplicit").finish(),
756 }
757 }
758}
759
760#[derive(Copy, Clone, Debug)]
762pub enum SuspensionTarget {
763 Resume(u32),
764 Promote(u32),
765 None,
766}
767
768#[derive(Copy, Clone, Debug)]
770pub enum ResumeThread {
771 Promote,
772 Resume,
773 ResumeLater,
774}
775
776#[derive(Debug)]
778struct GuestCall {
779 thread: QualifiedThreadId,
780 kind: GuestCallKind,
781}
782
783impl GuestCall {
784 fn is_ready(&self, store: &mut StoreOpaque) -> Result<bool> {
795 let task = store.concurrent_state_mut()?.get_mut(self.thread.task)?;
796 let async_typed = task.async_typed;
797 let async_lifted = task.async_lifted;
798 let has_callback = task.callback.is_some();
799 let instance = task.instance;
800 let state = store.instance_state(instance).concurrent_state();
801
802 let ready = match &self.kind {
803 GuestCallKind::DeliverEvent { .. } => !state.do_not_enter,
804 GuestCallKind::StartImplicit(_) => {
805 if async_typed {
806 let needs_exclusive = !async_lifted || has_callback;
809 !((needs_exclusive && state.do_not_enter) || state.backpressure > 0)
810 } else {
811 true
812 }
813 }
814 GuestCallKind::StartExplicit(_) => true,
815 };
816 log::trace!(
817 "call {self:?} ready? {ready} (do_not_enter: {}; backpressure: {})",
818 state.do_not_enter,
819 state.backpressure
820 );
821 Ok(ready)
822 }
823}
824
825enum WorkerItem {
827 GuestCall(GuestCall),
828 Function(AlwaysMut<Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send>>),
829}
830
831enum WorkItem {
834 PushFuture(AlwaysMut<HostTaskFuture>),
836 ResumeFiber {
838 instance: RuntimeInstance,
839 thread: QualifiedThreadId,
840 fiber: StoreFiber<'static>,
841 },
842 ResumeThread {
844 instance: RuntimeInstance,
845 thread: QualifiedThreadId,
846 },
847 GuestCall {
849 instance: RuntimeInstance,
850 call: GuestCall,
851 },
852 WorkerFunction(AlwaysMut<Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send>>),
854}
855
856struct ResumingFiber<'a> {
862 store: &'a mut StoreOpaque,
863 fiber: Option<StoreFiber<'static>>,
864}
865
866impl Drop for ResumingFiber<'_> {
867 fn drop(&mut self) {
868 if let Some(mut fiber) = self.fiber.take() {
869 fiber.dispose(self.store);
870 }
871 }
872}
873
874impl fmt::Debug for WorkItem {
875 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
876 match self {
877 Self::PushFuture(_) => f.debug_tuple("PushFuture").finish(),
878 Self::ResumeFiber {
879 instance, thread, ..
880 } => f
881 .debug_struct("ResumeFiber")
882 .field("instance", instance)
883 .field("thread", thread)
884 .finish(),
885 Self::ResumeThread { instance, thread } => f
886 .debug_struct("ResumeThread")
887 .field("instance", instance)
888 .field("thread", thread)
889 .finish(),
890 Self::GuestCall { instance, call } => f
891 .debug_struct("GuestCall")
892 .field("instance", instance)
893 .field("call", call)
894 .finish(),
895 Self::WorkerFunction(_) => f.debug_tuple("WorkerFunction").finish(),
896 }
897 }
898}
899
900#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
902pub(crate) enum WaitResult {
903 Cancelled,
904 Completed,
905}
906
907pub(crate) fn poll_and_block<R: Send + Sync + 'static>(
915 store: &mut dyn VMStore,
916 host_task: EnteredHostTask,
917 future: impl Future<Output = Result<R>> + Send + 'static,
918) -> Result<R> {
919 let mut future = Box::pin(future);
926 let poll = tls::set(store, || {
927 future
928 .as_mut()
929 .poll(&mut Context::from_waker(&Waker::noop()))
930 });
931
932 let caller = match host_task {
933 Some(caller) => caller,
934 None => bail_bug!("host task wasn't created but should have been"),
935 };
936
937 let task = match poll {
938 Poll::Ready(result) => return result,
940
941 Poll::Pending => {
946 let Some(task) = store.materialize_host_task_id()? else {
947 bail_bug!("current thread is not a host thread")
948 };
949
950 let future = Box::pin(async move {
953 let result = run_with_host_task_set(task, future).await??;
954 tls::get(move |store| {
955 let state = store.concurrent_state_mut()?;
956 let host_state = &mut state.get_mut(task)?.state;
957 assert!(matches!(host_state, HostTaskState::CalleeStarted));
958 *host_state = HostTaskState::CalleeFinished(Box::new(result));
959
960 Waitable::Host(task).set_event(
961 state,
962 Some(Event::Subtask {
963 status: Status::Returned,
964 }),
965 )?;
966
967 Ok(())
968 })
969 }) as HostTaskFuture;
970
971 let caller_instance = store.concurrent_state_mut()?.get_mut(caller.task)?.instance;
972 store.switch_or_trap_if_may_not_suspend(caller_instance)?;
973
974 let state = store.concurrent_state_mut()?;
975 state.push_future(future);
976
977 let set = state.get_mut(caller.thread)?.sync_call_set;
978 Waitable::Host(task).join(state, Some(set))?;
979
980 store.suspend(SuspendReason::Waiting {
981 set,
982 thread: caller,
983 })?;
984
985 Waitable::Host(task).join(store.concurrent_state_mut()?, None)?;
989 task
990 }
991 };
992
993 let host_state = &mut store.concurrent_state_mut()?.get_mut(task)?.state;
995 match mem::replace(host_state, HostTaskState::CalleeDone { cancelled: false }) {
996 HostTaskState::CalleeFinished(result) => Ok(match result.downcast() {
997 Ok(result) => *result,
998 Err(_) => bail_bug!("host task finished with wrong type of result"),
999 }),
1000 _ => bail_bug!("unexpected host task state after completion"),
1001 }
1002}
1003
1004fn handle_guest_call(store: &mut dyn VMStore, call: GuestCall) -> Result<()> {
1006 match call.kind {
1007 GuestCallKind::DeliverEvent { instance, set } => {
1008 if let Some(set) = set {
1011 store.concurrent_state_mut()?.get_mut(set)?.stop_waiting()?;
1012 }
1013 let (event, waitable) = match instance.get_event(store, call.thread.task, set, true)? {
1014 Some(pair) => pair,
1015 None => match set {
1016 Some(set) => {
1021 log::trace!(
1022 "event for {:?} on {set:?} no longer present; waiting again",
1023 call.thread
1024 );
1025 return instance.wait_with_callback(
1026 store.store_opaque_mut(),
1027 call.thread,
1028 set,
1029 );
1030 }
1031 None => (Event::None, None),
1036 },
1037 };
1038 let state = store.concurrent_state_mut()?;
1039 if let Some(set) = set
1044 && waitable.is_none()
1045 && !state.get_mut(set)?.ready.is_empty()
1046 {
1047 state.wake_waiter(set)?;
1048 }
1049 let task = state.get_mut(call.thread.task)?;
1050 let runtime_instance = task.instance;
1051 let handle = waitable.map(|(_, v)| v).unwrap_or(0);
1052
1053 log::trace!(
1054 "use callback to deliver event {event:?} to {:?} for {waitable:?}",
1055 call.thread,
1056 );
1057
1058 instance.handle_callback_code(store, call.thread, runtime_instance, |store| {
1059 invoke_callback(store, call.thread.task, event, handle)
1060 })?;
1061 }
1062 GuestCallKind::StartImplicit(fun) => {
1063 fun(store)?;
1064 }
1065 GuestCallKind::StartExplicit(fun) => {
1066 fun(store)?;
1067 }
1068 }
1069
1070 Ok(())
1071}
1072
1073fn invoke_callback(
1076 store: &mut dyn VMStore,
1077 task: TableId<GuestTask>,
1078 event: Event,
1079 handle: u32,
1080) -> Result<u32> {
1081 let Some(callback) = store.concurrent_state_mut()?.get_mut(task)?.callback.take() else {
1082 bail_bug!("guest task callback field not present")
1083 };
1084
1085 let code = callback(store, event, handle)?;
1086
1087 store.concurrent_state_mut()?.get_mut(task)?.callback = Some(callback);
1088
1089 Ok(code)
1090}
1091
1092impl<T> Store<T> {
1093 pub async fn run_concurrent<R>(&mut self, fun: impl AsyncFnOnce(&Accessor<T>) -> R) -> Result<R>
1095 where
1096 T: Send + 'static,
1097 {
1098 ensure!(
1099 self.as_context().0.concurrency_support(),
1100 "cannot use `run_concurrent` when Config::concurrency_support disabled",
1101 );
1102 self.as_context_mut().run_concurrent(fun).await
1103 }
1104
1105 #[doc(hidden)]
1106 pub fn assert_concurrent_state_empty(&mut self) {
1107 self.as_context_mut().assert_concurrent_state_empty();
1108 }
1109
1110 #[doc(hidden)]
1111 pub fn concurrent_state_table_size(&mut self) -> usize {
1112 self.as_context_mut().concurrent_state_table_size()
1113 }
1114
1115 pub fn spawn(
1117 &mut self,
1118 task: impl for<'fut> AccessorTask<'fut, T, HasSelf<T>>,
1119 ) -> Result<JoinHandle>
1120 where
1121 T: 'static,
1122 {
1123 self.as_context_mut().spawn(task)
1124 }
1125}
1126
1127impl<T> StoreContextMut<'_, T> {
1128 #[doc(hidden)]
1139 pub fn assert_concurrent_state_empty(self) {
1140 let store = self.0;
1141 store
1142 .store_data_mut()
1143 .components
1144 .assert_instance_states_empty();
1145 let state = store.concurrent_state_mut().unwrap();
1146 assert!(
1147 state.table.get_mut().is_empty(),
1148 "non-empty table: {:?}",
1149 state.table.get_mut()
1150 );
1151 assert!(state.switch_item.is_none());
1152 assert!(state.next_switch_item.is_none());
1153 assert!(state.high_priority.is_empty());
1154 assert!(state.low_priority.is_empty());
1155 assert!(state.saved_next_switch_items.is_empty());
1156 assert!(state.unforced_current_thread.is_none());
1157 assert!(state.deferred_host_call_context.is_none());
1158 assert!(state.futures_mut().unwrap().is_empty());
1159 assert!(state.global_error_context_ref_counts.is_empty());
1160 }
1161
1162 #[doc(hidden)]
1167 pub fn concurrent_state_table_size(&mut self) -> usize {
1168 self.0.concurrent_state_mut().unwrap().table.get_mut().len()
1169 }
1170
1171 pub fn spawn(mut self, task: impl for<'fut> AccessorTask<'fut, T>) -> Result<JoinHandle>
1181 where
1182 T: 'static,
1183 {
1184 let accessor = Accessor::new(StoreToken::new(self.as_context_mut()));
1185 self.spawn_with_accessor(accessor, task)
1186 }
1187
1188 fn spawn_with_accessor<D>(
1191 self,
1192 accessor: Accessor<T, D>,
1193 task: impl for<'fut> AccessorTask<'fut, T, D>,
1194 ) -> Result<JoinHandle>
1195 where
1196 T: 'static,
1197 D: HasData + ?Sized,
1198 {
1199 let (handle, future) = JoinHandle::run(async move { task.run(&accessor).await });
1203 self.0
1204 .concurrent_state_mut()?
1205 .push_future(Box::pin(async move { future.await.unwrap_or(Ok(())) }));
1206 Ok(handle)
1207 }
1208
1209 pub async fn run_concurrent<R>(self, fun: impl AsyncFnOnce(&Accessor<T>) -> R) -> Result<R>
1293 where
1294 T: Send + 'static,
1295 {
1296 ensure!(
1297 self.0.concurrency_support(),
1298 "cannot use `run_concurrent` when Config::concurrency_support disabled",
1299 );
1300 self.do_run_concurrent(fun, false).await
1301 }
1302
1303 pub(super) async fn run_concurrent_trap_on_idle<R>(
1304 self,
1305 fun: impl AsyncFnOnce(&Accessor<T>) -> R,
1306 ) -> Result<R> {
1307 self.do_run_concurrent(fun, true).await
1308 }
1309
1310 async fn do_run_concurrent<R>(
1311 mut self,
1312 fun: impl AsyncFnOnce(&Accessor<T>) -> R,
1313 trap_on_idle: bool,
1314 ) -> Result<R> {
1315 debug_assert!(self.0.concurrency_support());
1316 self.0.check_event_loop_not_running()?;
1317 let token = StoreToken::new(self.as_context_mut());
1318
1319 struct Dropper<'a, T: 'static, V> {
1320 store: StoreContextMut<'a, T>,
1321 value: ManuallyDrop<V>,
1322 }
1323
1324 impl<'a, T, V> Drop for Dropper<'a, T, V> {
1325 fn drop(&mut self) {
1326 self.store
1327 .0
1328 .concurrent_state_mut_already_forced_current_thread()
1329 .event_loop_running = false;
1330
1331 tls::set(self.store.0, || {
1332 unsafe { ManuallyDrop::drop(&mut self.value) }
1337 });
1338 }
1339 }
1340
1341 let accessor = &Accessor::new(token);
1342 self.0
1343 .concurrent_state_mut_already_forced_current_thread()
1344 .event_loop_running = true;
1345 let dropper = &mut Dropper {
1346 store: self,
1347 value: ManuallyDrop::new(fun(accessor)),
1348 };
1349 let future = unsafe { Pin::new_unchecked(dropper.value.deref_mut()) };
1351
1352 let result = dropper
1353 .store
1354 .as_context_mut()
1355 .poll_until(future, trap_on_idle)
1356 .await;
1357
1358 if result.is_err() {
1359 dropper.store.0.set_trapped();
1360 }
1361
1362 result
1363 }
1364
1365 async fn poll_until<R>(
1371 mut self,
1372 mut future: Pin<&mut impl Future<Output = R>>,
1373 trap_on_idle: bool,
1374 ) -> Result<R> {
1375 struct Reset<'a, T: 'static> {
1376 store: StoreContextMut<'a, T>,
1377 futures: Option<FuturesUnordered<HostTaskFuture>>,
1378 }
1379
1380 impl<'a, T> Drop for Reset<'a, T> {
1381 fn drop(&mut self) {
1382 if let Some(futures) = self.futures.take() {
1383 *self
1384 .store
1385 .0
1386 .concurrent_state_mut_already_forced_current_thread()
1387 .futures
1388 .get_mut() = Some(futures);
1389 }
1390 }
1391 }
1392
1393 const MAX_TURNS_WITHOUT_YIELD: usize = 128;
1397 let mut turns_without_yield = 0;
1398
1399 loop {
1400 let futures = self.0.concurrent_state_mut()?.futures.get_mut().take();
1404 let mut reset = Reset {
1405 store: self.as_context_mut(),
1406 futures,
1407 };
1408 let mut next = match reset.futures.as_mut() {
1409 Some(f) => pin!(f.next()),
1410 None => bail_bug!("concurrent state missing futures field"),
1411 };
1412
1413 enum PollResult<R> {
1414 Complete(R),
1415 ProcessWork {
1416 ready: Option<WorkItem>,
1417 low_priority: bool,
1418 },
1419 }
1420
1421 let result = future::poll_fn(|cx| {
1422 if let Poll::Ready(value) = tls::set(reset.store.0, || future.as_mut().poll(cx)) {
1425 return Poll::Ready(Ok(PollResult::Complete(value)));
1426 }
1427
1428 if reset.store.0.trapped() {
1437 return Poll::Ready(Err(Trap::CannotEnterComponent.into()));
1438 }
1439
1440 let next = match tls::set(reset.store.0, || next.as_mut().poll(cx)) {
1444 Poll::Ready(Some(output)) => {
1445 match output {
1446 Err(e) => return Poll::Ready(Err(e)),
1447 Ok(()) => {}
1448 }
1449 Poll::Ready(true)
1450 }
1451 Poll::Ready(None) => Poll::Ready(false),
1452 Poll::Pending => Poll::Pending,
1453 };
1454
1455 let state = reset.store.0.concurrent_state_mut()?;
1470 let mut ready = state.switch_item.take();
1471 let mut low_priority = false;
1472 if ready.is_none() {
1473 ready = state.high_priority.pop_back();
1474 if ready.is_none() {
1475 ready = state.low_priority.pop_back();
1476 low_priority = true;
1477 }
1478 }
1479 if ready.is_some() {
1480 return Poll::Ready(Ok(PollResult::ProcessWork {
1481 ready,
1482 low_priority,
1483 }));
1484 }
1485
1486 return match next {
1490 Poll::Ready(true) => {
1491 Poll::Ready(Ok(PollResult::ProcessWork {
1497 ready: None,
1498 low_priority: false,
1499 }))
1500 }
1501 Poll::Ready(false) => {
1502 if let Poll::Ready(value) =
1506 tls::set(reset.store.0, || future.as_mut().poll(cx))
1507 {
1508 Poll::Ready(Ok(PollResult::Complete(value)))
1509 } else {
1510 if trap_on_idle {
1516 Poll::Ready(Err(if reset.store.0.any_may_not_suspend()? {
1523 Trap::CannotBlockSyncTask.into()
1524 } else {
1525 Trap::AsyncDeadlock.into()
1527 }))
1528 } else {
1529 Poll::Pending
1533 }
1534 }
1535 }
1536 Poll::Pending => Poll::Pending,
1541 };
1542 })
1543 .await;
1544
1545 drop(reset);
1549
1550 match result? {
1551 PollResult::Complete(value) => break Ok(value),
1554 PollResult::ProcessWork {
1557 mut ready,
1558 low_priority,
1559 } => {
1560 if low_priority {
1588 if let Some(item) = ready.take() {
1589 self.0.concurrent_state_mut()?.low_priority.push_back(item);
1590 }
1591 self.0.yield_now().await;
1592 turns_without_yield = 0;
1593 ready = self.0.concurrent_state_mut()?.low_priority.pop_back();
1594 }
1595
1596 if let Some(item) = ready {
1597 self.as_context_mut().handle_work_item(item).await?;
1598 }
1599
1600 turns_without_yield += 1;
1601 if turns_without_yield == MAX_TURNS_WITHOUT_YIELD {
1602 turns_without_yield = 0;
1603 self.0.yield_now().await;
1604 }
1605 }
1606 }
1607 }
1608 }
1609
1610 fn handle_work_item(self, item: WorkItem) -> impl Future<Output = Result<()>> {
1612 let item = match item {
1616 WorkItem::ResumeFiber {
1617 instance,
1618 thread,
1619 fiber,
1620 } => {
1621 let future = self.0.resume_fiber(fiber);
1622 log::trace!(
1623 "handle work item ResumeFiber {{ instance: {instance:?}, thread: {thread:?} }}"
1624 );
1625 return futures::future::Either::Left(future);
1626 }
1627 item => item,
1628 };
1629 futures::future::Either::Right(async move {
1630 log::trace!("handle work item {item:?}");
1631 match item {
1632 WorkItem::PushFuture(future) => {
1633 self.0
1634 .concurrent_state_mut()?
1635 .futures_mut()?
1636 .push(future.into_inner());
1637 }
1638 WorkItem::ResumeFiber { .. } => unreachable!(),
1639 WorkItem::ResumeThread { thread, .. } => {
1640 let slot = &mut self.0.concurrent_state_mut()?.get_mut(thread.thread)?.state;
1641 if !matches!(slot, GuestThreadState::Ready { .. }) {
1642 bail_bug!("cannot resume non-pending thread {thread:?}");
1643 }
1644 let GuestThreadState::Ready { fiber } =
1645 mem::replace(slot, GuestThreadState::Running)
1646 else {
1647 unreachable!()
1648 };
1649 self.0.resume_fiber(fiber).await?;
1650 }
1651 WorkItem::GuestCall { call, .. } => {
1652 if call.is_ready(self.0)? {
1653 self.0
1654 .concurrent_state_mut()?
1655 .get_mut(call.thread.thread)?
1656 .wake_on_cancel = WakeOnCancel::None;
1657 self.run_on_worker(WorkerItem::GuestCall(call)).await?;
1658 } else {
1659 let state = self.0.concurrent_state_mut()?;
1660 let task = state.get_mut(call.thread.task)?;
1661 if !task.starting_sent {
1662 task.starting_sent = true;
1663 if let GuestCallKind::StartImplicit(_) = &call.kind {
1664 Waitable::Guest(call.thread.task).set_event(
1665 state,
1666 Some(Event::Subtask {
1667 status: Status::Starting,
1668 }),
1669 )?;
1670 }
1671 }
1672
1673 let instance = state.get_mut(call.thread.task)?.instance;
1674 if let GuestCallKind::DeliverEvent { set: Some(set), .. } = &call.kind {
1683 let state = self.0.concurrent_state_mut()?;
1684 if !state.get_mut(*set)?.ready.is_empty() {
1685 state.wake_waiter(*set)?;
1686 }
1687 }
1688 self.0
1689 .instance_state(instance)
1690 .concurrent_state()
1691 .pending
1692 .insert(call.thread, call.kind);
1693
1694 self.0.concurrent_state_mut()?.take_next_switch_item()?;
1698 }
1699 }
1700 WorkItem::WorkerFunction(fun) => {
1701 self.run_on_worker(WorkerItem::Function(fun)).await?;
1702 }
1703 }
1704
1705 Ok(())
1706 })
1707 }
1708
1709 async fn run_on_worker(self, item: WorkerItem) -> Result<()> {
1711 let state = self.0.concurrent_state_mut()?;
1712 if state.worker_item.is_some() {
1713 bail_bug!("worker item already set when taking worker fiber");
1714 }
1715 let worker = if let Some(fiber) = state.worker.take() {
1716 fiber
1717 } else {
1718 unsafe {
1737 fiber::make_fiber_unchecked(self.0, move |store| {
1738 loop {
1739 let Some(item) = store.concurrent_state_mut()?.worker_item.take() else {
1740 bail_bug!("worker_item not present when resuming fiber")
1741 };
1742 match item {
1743 WorkerItem::GuestCall(call) => handle_guest_call(store, call)?,
1744 WorkerItem::Function(fun) => fun.into_inner()(store)?,
1745 }
1746
1747 store.suspend(SuspendReason::NeedWork)?;
1748 }
1749 })?
1750 }
1751 };
1752
1753 self.0
1756 .concurrent_state_mut_already_forced_current_thread()
1757 .worker_item = Some(item);
1758
1759 self.0.resume_fiber(worker).await
1760 }
1761
1762 pub(crate) fn wrap_call<F, R>(self, closure: F) -> impl Future<Output = Result<R>> + 'static
1767 where
1768 T: 'static,
1769 F: FnOnce(&Accessor<T>) -> Pin<Box<dyn Future<Output = Result<R>> + Send + '_>>
1770 + Send
1771 + Sync
1772 + 'static,
1773 R: Send + Sync + 'static,
1774 {
1775 let token = StoreToken::new(self);
1776 async move {
1777 let mut accessor = Accessor::new(token);
1778 closure(&mut accessor).await
1779 }
1780 }
1781
1782 pub(crate) async fn start_instance(
1783 &mut self,
1784 instance: ModuleInstance,
1785 callee: Option<RuntimeInstance>,
1786 ) -> Result<ModuleInstance> {
1787 let (tx, rx) = oneshot::channel();
1788 let token = StoreToken::new(self.as_context_mut());
1789 self.0.queue_task(move |store| {
1790 _ = tx.send(
1791 super::instance::start_raw(&mut token.as_context_mut(store), instance, callee)
1792 .map(|()| instance),
1793 );
1794 Ok(())
1795 })?;
1796 self.as_context_mut()
1797 .run_concurrent_trap_on_idle(async |_| {
1798 rx.await
1799 .map_err(|_| format_err!("oneshot channel canceled"))
1800 })
1801 .await??
1802 }
1803}
1804
1805pub type EnteredHostTask = Option<QualifiedThreadId>;
1812
1813impl StoreOpaque {
1814 pub(crate) fn check_event_loop_not_running(&mut self) -> Result<()> {
1815 if self
1816 .concurrent_state_mut_already_forced_current_thread()
1817 .event_loop_running
1818 {
1819 bail!("Recursive `StoreContextMut::run_concurrent` calls not supported")
1820 }
1821 Ok(())
1822 }
1823
1824 #[inline]
1828 pub(crate) fn current_thread(&mut self) -> Result<CurrentThread> {
1829 if !self.concurrency_support() {
1831 return Ok(CurrentThread::None);
1832 }
1833
1834 if !self
1837 .vm_store_context_mut()
1838 .current_thread_mut()
1839 .is_deferred()
1840 {
1841 return Ok(self
1842 .concurrent_state_mut_already_forced_current_thread()
1843 .unforced_current_thread);
1844 }
1845
1846 self.force_deferred_current_thread()
1847 }
1848
1849 #[cold]
1852 fn force_deferred_current_thread(&mut self) -> Result<CurrentThread> {
1853 let state = self.concurrent_state_mut_without_forcing_current_thread();
1862 let id = match state.unforced_current_thread.guest_task() {
1863 Some(task) => state.get_mut(task)?.instance.instance,
1864 None => bail_bug!("deferred component-model thread with non-guest base"),
1865 };
1866
1867 let mut frames = Vec::new();
1870 let mut cur = *self.vm_store_context_mut().current_thread_mut();
1871 while let Some(ptr) = cur.as_deferred() {
1872 let deferred = unsafe { ptr.as_non_null().as_ref() };
1877 frames.push((
1878 deferred.callee_async != 0,
1879 deferred.callee_instance,
1880 deferred.saved_context,
1881 ));
1882 cur = deferred.parent;
1883 }
1884
1885 *self.vm_store_context_mut().current_thread_mut() = VMLazyThread::forced();
1889
1890 let current_context = *self.vm_store_context_mut().component_context_mut();
1893
1894 for (callee_async, callee_instance, saved_context) in frames.into_iter().rev() {
1898 *self.vm_store_context_mut().component_context_mut() = saved_context;
1902 let callee = RuntimeInstance {
1903 instance: id,
1904 index: RuntimeComponentInstanceIndex::from_u32(callee_instance),
1905 };
1906 self.enter_guest_sync_call(callee_async, callee)?;
1907 }
1908
1909 *self.vm_store_context_mut().component_context_mut() = current_context;
1911
1912 Ok(self
1913 .concurrent_state_mut_without_forcing_current_thread()
1914 .unforced_current_thread)
1915 }
1916
1917 fn current_guest_thread(&mut self) -> Result<QualifiedThreadId> {
1918 match self.current_thread()?.guest() {
1919 Some(id) => Ok(*id),
1920 None => bail_bug!("current thread is not a guest thread"),
1921 }
1922 }
1923
1924 pub(crate) fn current_materialized_host_task(&mut self) -> Result<Option<TableId<HostTask>>> {
1928 match self.current_thread()? {
1929 CurrentThread::Host(id) => Ok(Some(id)),
1930 CurrentThread::DeferredHost(_) | CurrentThread::None => Ok(None),
1931 _ => bail_bug!("current thread is not a host thread"),
1932 }
1933 }
1934
1935 fn materialize_host_task_id(&mut self) -> Result<Option<TableId<HostTask>>> {
1938 Ok(self
1939 .concurrent_state_mut()?
1940 .materialize_current_host_task_id()?)
1941 }
1942
1943 fn enter_sync_call(&mut self, callee: RuntimeInstance) -> Result<()> {
1944 log::trace!("enter sync-typed call {callee:?}");
1945 let state = self.instance_state(callee).concurrent_state();
1946 let old_do_not_suspend = state.do_not_suspend;
1947 state.do_not_suspend = true;
1948
1949 let thread = self.current_guest_thread()?;
1950 let thread = self.concurrent_state_mut()?.get_mut(thread.thread)?;
1951 if thread.old_do_not_suspend.is_some() {
1952 bail_bug!("current thread already has `old_do_not_suspend` value");
1953 }
1954
1955 thread.old_do_not_suspend = Some(old_do_not_suspend);
1956
1957 Ok(())
1958 }
1959
1960 fn exit_sync_call(&mut self, callee: RuntimeInstance) -> Result<()> {
1961 log::trace!("exit sync-typed call {callee:?}");
1962 let thread = self.current_guest_thread()?;
1963 let thread = self.concurrent_state_mut()?.get_mut(thread.thread)?;
1964 let Some(old_do_not_suspend) = thread.old_do_not_suspend.take() else {
1965 bail_bug!("current thread missing `old_do_not_suspend` value");
1966 };
1967 let state = self.instance_state(callee).concurrent_state();
1968 state.do_not_suspend = old_do_not_suspend;
1969 Ok(())
1970 }
1971
1972 pub(crate) fn enter_guest_sync_call(
1984 &mut self,
1985 callee_async_typed: bool,
1986 callee: RuntimeInstance,
1987 ) -> Result<()> {
1988 log::trace!("enter sync-lifted call {callee:?}");
1989 if !self.concurrency_support() {
1990 return self.enter_call_not_concurrent();
1991 }
1992
1993 let state = self.concurrent_state_mut()?;
1997 let item = state.next_switch_item.take();
1998 state.saved_next_switch_items.push(item);
1999
2000 let thread = self.current_thread()?;
2001 let caller = if let Some(thread) = thread.guest() {
2002 Caller::Guest { thread: *thread }
2003 } else {
2004 Caller::Host {
2005 tx: None,
2006 caller: self.materialize_host_task_id()?,
2007 }
2008 };
2009
2010 let state = self.concurrent_state_mut()?;
2011 let guest_thread = GuestTask::new(
2012 state,
2013 Box::new(move |_, _| bail_bug!("cannot lower params in sync call")),
2014 LiftResult {
2015 lift: Box::new(move |_, _| bail_bug!("cannot lift result in sync call")),
2016 ty: TypeTupleIndex::reserved_value(),
2017 memory: None,
2018 string_encoding: StringEncoding::Utf8,
2019 },
2020 caller,
2021 None,
2022 callee,
2023 callee_async_typed,
2024 false,
2025 )?;
2026
2027 Instance::from_wasmtime(self, callee.instance).add_guest_thread_to_instance_table(
2028 guest_thread.thread,
2029 self,
2030 callee.index,
2031 )?;
2032 self.set_thread(guest_thread)?;
2033
2034 if !callee_async_typed {
2035 self.enter_sync_call(callee)?;
2036 }
2037
2038 Ok(())
2039 }
2040
2041 pub(crate) fn exit_guest_sync_call(&mut self) -> Result<()> {
2049 if !self.concurrency_support() {
2050 return Ok(self.exit_call_not_concurrent());
2051 }
2052
2053 let thread = match self.current_thread()?.guest() {
2054 Some(t) => *t,
2055 None => bail_bug!("expected task when exiting"),
2056 };
2057 let task = self.concurrent_state_mut()?.get_mut(thread.task)?;
2058 let instance = task.instance;
2059
2060 let caller = match &task.caller {
2061 &Caller::Guest { thread } => thread.into(),
2062 &Caller::Host { caller, .. } => caller
2063 .map(CurrentThread::Host)
2064 .unwrap_or(CurrentThread::None),
2065 };
2066 task.lift_result = None;
2067 task.exited = true;
2068 let async_typed = task.async_typed;
2069
2070 if !async_typed {
2071 self.exit_sync_call(instance)?;
2072 }
2073
2074 self.set_thread(caller)?;
2075
2076 log::trace!("exit sync-lifted call {instance:?}");
2077
2078 if async_typed {
2079 self.switch_or_trap_if_may_not_suspend(instance)?;
2084 }
2085
2086 self.cleanup_thread(thread, instance)?;
2087
2088 self.concurrent_state_mut()?
2089 .decrement_task_ref_count(thread.task)?;
2090
2091 let state = self.concurrent_state_mut()?;
2092 let Some(item) = state.saved_next_switch_items.pop() else {
2093 bail_bug!("unable to pop from `saved_next_switch_items`");
2094 };
2095 if let Some(item) = mem::replace(&mut state.next_switch_item, item) {
2096 state.push_high_priority(item);
2099 bail_bug!("`next_switch_item` unexpectedly already set");
2100 }
2101
2102 Ok(())
2103 }
2104
2105 pub(crate) fn host_task_create(&mut self) -> Result<EnteredHostTask> {
2112 if !self.concurrency_support() {
2113 self.enter_call_not_concurrent()?;
2114 return Ok(None);
2115 }
2116 let caller = self.current_guest_thread()?;
2117 log::trace!("new deferred host task with caller {caller:?}");
2118
2119 self.set_thread(CurrentThread::DeferredHost(caller))?;
2120 let state = self.concurrent_state_mut()?;
2121 debug_assert!(state.deferred_host_call_context.is_none());
2122 state.deferred_host_call_context = Some(CallContext::default());
2123 state.debug_assert_deferred_host_invariant();
2124 Ok(Some(caller))
2125 }
2126
2127 pub(crate) fn host_task_delete(
2134 &mut self,
2135 original_task: EnteredHostTask,
2136 materialized_task: Option<TableId<HostTask>>,
2137 ) -> Result<()> {
2138 match original_task {
2139 Some(caller) => {
2140 self.set_thread(caller)?;
2141 if materialized_task.is_none() {
2142 let state = self.concurrent_state_mut()?;
2143 let context = state
2144 .deferred_host_call_context
2145 .take()
2146 .expect("deferred host call context should be present");
2147 debug_assert!(context.is_empty());
2148 state.debug_assert_deferred_host_invariant();
2149 }
2150 log::trace!(
2151 "delete host task with caller {original_task:?} and materialized as {materialized_task:?}"
2152 );
2153 if let Some(task) = materialized_task {
2154 self.concurrent_state_mut()?.delete_host_task(task)?;
2155 }
2156 }
2157 None => {
2158 debug_assert!(materialized_task.is_none());
2159 self.exit_call_not_concurrent();
2160 }
2161 }
2162 Ok(())
2163 }
2164
2165 fn instance_state(&mut self, instance: RuntimeInstance) -> &mut InstanceState {
2168 self.component_instance_mut(instance.instance)
2169 .instance_state(instance.index)
2170 }
2171
2172 fn instance_state_and_handle_counter(
2175 &mut self,
2176 instance: RuntimeInstance,
2177 ) -> (&mut InstanceState, &mut HandleCounter) {
2178 let (component, counter) = self
2179 .store_data_mut()
2180 .component_instance_and_handle_counter_mut(instance.instance);
2181 (component.instance_state(instance.index), counter)
2182 }
2183
2184 pub(crate) fn set_thread(&mut self, thread: impl Into<CurrentThread>) -> Result<CurrentThread> {
2190 let thread = thread.into();
2191 let state = self.concurrent_state_mut()?;
2192 state.debug_assert_deferred_host_invariant();
2193 let old_thread = mem::replace(&mut state.unforced_current_thread, thread);
2194
2195 state.handle_thread_switch(old_thread, thread)?;
2196
2197 if let Some(old_thread) = old_thread.guest() {
2205 let old_context = *self.vm_store_context_mut().component_context_mut();
2206 self.concurrent_state_mut()?
2207 .get_mut(old_thread.thread)?
2208 .context = old_context;
2209 }
2210 if cfg!(debug_assertions) {
2211 *self.vm_store_context_mut().component_context_mut() =
2212 [u32::MAX; NUM_COMPONENT_CONTEXT_SLOTS];
2213 }
2214 if let Some(thread) = thread.guest() {
2215 let thread = self.concurrent_state_mut()?.get_mut(thread.thread)?;
2216 let context = thread.context;
2217 if cfg!(debug_assertions) {
2218 thread.context = [u32::MAX; NUM_COMPONENT_CONTEXT_SLOTS];
2219 }
2220 *self.vm_store_context_mut().component_context_mut() = context;
2221 }
2222
2223 *self.vm_store_context_mut().current_thread_mut() = if thread.is_none() {
2225 VMLazyThread::none()
2226 } else {
2227 VMLazyThread::forced()
2228 };
2229
2230 Ok(old_thread)
2231 }
2232
2233 fn switch_or_trap_if_may_not_suspend(&mut self, instance: RuntimeInstance) -> Result<()> {
2235 if self.switch_if_may_not_suspend(instance)? {
2236 Ok(())
2237 } else {
2238 Err(Trap::CannotBlockSyncTask.into())
2239 }
2240 }
2241
2242 fn switch_if_may_not_suspend(&mut self, instance: RuntimeInstance) -> Result<bool> {
2246 self.concurrent_state_mut()?;
2250
2251 Ok(!self.concurrency_support()
2252 || !self
2253 .instance_state(instance)
2254 .concurrent_state()
2255 .do_not_suspend
2256 || self
2257 .concurrent_state_mut()?
2258 .promote_instance_local_thread_work_item(instance)?)
2259 }
2260
2261 fn enter_instance(&mut self, instance: RuntimeInstance) {
2265 log::trace!("enter {instance:?}");
2266 self.instance_state(instance)
2267 .concurrent_state()
2268 .do_not_enter = true;
2269 }
2270
2271 fn exit_instance(&mut self, instance: RuntimeInstance) -> Result<()> {
2275 log::trace!("exit {instance:?}");
2276 self.instance_state(instance)
2277 .concurrent_state()
2278 .do_not_enter = false;
2279 self.partition_pending(instance)
2280 }
2281
2282 fn partition_pending(&mut self, instance: RuntimeInstance) -> Result<()> {
2290 for (thread, kind) in
2291 mem::take(&mut self.instance_state(instance).concurrent_state().pending).into_iter()
2292 {
2293 let call = GuestCall { thread, kind };
2294 if call.is_ready(self)? {
2295 self.concurrent_state_mut()?
2296 .push_high_priority(WorkItem::GuestCall { instance, call });
2297 } else {
2298 self.instance_state(instance)
2299 .concurrent_state()
2300 .pending
2301 .insert(call.thread, call.kind);
2302 }
2303 }
2304
2305 if let Some(waker) = self
2306 .concurrent_state_mut()?
2307 .ready_for_concurrent_call_waker
2308 .take()
2309 {
2310 waker.wake();
2311 }
2312
2313 Ok(())
2314 }
2315
2316 pub(crate) fn backpressure_modify(
2318 &mut self,
2319 caller_instance: RuntimeInstance,
2320 modify: impl FnOnce(u16) -> Option<u16>,
2321 ) -> Result<()> {
2322 let state = self.instance_state(caller_instance).concurrent_state();
2323 let old = state.backpressure;
2324 let new = modify(old).ok_or_else(|| Trap::BackpressureOverflow)?;
2325 state.backpressure = new;
2326
2327 if old > 0 && new == 0 {
2328 self.partition_pending(caller_instance)?;
2331 }
2332
2333 Ok(())
2334 }
2335
2336 fn resume_fiber(
2339 &mut self,
2340 fiber: StoreFiber<'static>,
2341 ) -> impl Future<Output = Result<()>> + '_ {
2342 let mut resuming = ResumingFiber {
2343 store: self,
2344 fiber: Some(fiber),
2345 };
2346 async move {
2347 let old_thread = resuming.store.current_thread()?;
2348 log::trace!("resume_fiber: save current thread {old_thread:?}");
2349
2350 let fiber = resuming.fiber.take().unwrap();
2351 resuming.fiber = fiber::resolve_or_release(resuming.store, fiber).await?;
2352
2353 resuming.store.set_thread(old_thread)?;
2354
2355 let state = resuming.store.concurrent_state_mut()?;
2356
2357 if let Some(ot) = old_thread.guest() {
2358 state.set_thread_running(ot.thread)?;
2359 }
2360 log::trace!("resume_fiber: restore current thread {old_thread:?}");
2361
2362 if resuming.fiber.is_some() {
2363 log::trace!("resume_fiber: suspend reason {:?}", &state.suspend_reason);
2364 let reason = match state.suspend_reason.take() {
2366 Some(r) => r,
2367 None => bail_bug!("suspend reason missing when resuming fiber"),
2368 };
2369 match reason {
2370 SuspendReason::NeedWork => {
2371 if state.worker.is_none() {
2372 state.worker = resuming.fiber.take();
2373 }
2374 }
2375 SuspendReason::Yielding { thread } => {
2376 let slot = &mut state.get_mut(thread.thread)?.state;
2377 slot.check_no_fiber()?;
2378 *slot = GuestThreadState::Ready {
2379 fiber: resuming.fiber.take().unwrap(),
2380 };
2381 let instance = state.get_mut(thread.task)?.instance;
2382 state.push_low_priority(WorkItem::ResumeThread { instance, thread });
2383 }
2384 SuspendReason::ExplicitlySuspending { thread } => {
2385 let slot = &mut state.get_mut(thread.thread)?.state;
2386 slot.check_no_fiber()?;
2387 *slot = GuestThreadState::Suspended(resuming.fiber.take().unwrap());
2388 }
2389 SuspendReason::Waiting { set, thread } => {
2390 match state.get_mut(set)?.waiting.entry(thread) {
2391 Entry::Vacant(entry) => {
2392 entry.insert(WaitMode::Fiber(resuming.fiber.take().unwrap()));
2393 }
2394 Entry::Occupied(_) => {
2395 bail_bug!("entry unexpectedly already exists for {thread:?}");
2396 }
2397 }
2398 }
2399 SuspendReason::YieldingToSubtask { thread } => {
2400 let instance = state.get_mut(thread.task)?.instance;
2409 if state.next_switch_item.is_some() {
2410 bail_bug!(
2413 "`ConcurrentState::next_switch_item` was already `Some(_)` when \
2414 a thread wanted to wait on a subtask"
2415 );
2416 }
2417 let item = state.next_switch_item.insert(WorkItem::ResumeFiber {
2418 instance,
2419 thread,
2420 fiber: resuming.fiber.take().unwrap(),
2421 });
2422 log::trace!("set next switch item to {item:?}");
2423 }
2424 };
2425 } else {
2426 log::trace!("resume_fiber: fiber has exited");
2427 }
2428
2429 Ok(())
2430 }
2431 }
2432
2433 fn suspend(&mut self, reason: SuspendReason) -> Result<()> {
2439 log::trace!("suspend fiber: {reason:?}");
2440
2441 if !self.fiber_async_state_mut().can_block() {
2444 return Err(format_err!("future dropped"));
2445 }
2446
2447 let state = self.concurrent_state_mut()?;
2448
2449 let (save_and_restore_thread, save_and_restore_next_switch_item) = match &reason {
2456 SuspendReason::Yielding { .. }
2457 | SuspendReason::Waiting { .. }
2458 | SuspendReason::ExplicitlySuspending { .. } => {
2459 if state.switch_item.is_none() {
2462 state.take_next_switch_item()?;
2463 }
2464
2465 (true, false)
2466 }
2467 SuspendReason::YieldingToSubtask { .. } => (true, true),
2468 SuspendReason::NeedWork => (false, false),
2469 };
2470
2471 let old_next_switch_item = if save_and_restore_next_switch_item {
2472 Some(state.save_next_switch_item()?)
2473 } else {
2474 None
2475 };
2476
2477 let old_guest_thread = if save_and_restore_thread {
2478 self.current_thread()?
2479 } else {
2480 CurrentThread::None
2481 };
2482
2483 let waiting_set = match &reason {
2484 SuspendReason::Waiting { set, .. } => Some(*set),
2485 _ => None,
2486 };
2487
2488 let suspend_reason = &mut self.concurrent_state_mut()?.suspend_reason;
2489 if suspend_reason.is_some() {
2490 bail_bug!("suspend reason unexpectedly already set for store");
2491 }
2492 *suspend_reason = Some(reason);
2493
2494 if let Some(set) = waiting_set {
2497 self.concurrent_state_mut()?.get_mut(set)?.num_waiting += 1;
2498 }
2499
2500 self.with_blocking(|_, cx| cx.suspend(StoreFiberYield::ReleaseStore))?;
2501
2502 if let Some(set) = waiting_set {
2503 self.concurrent_state_mut()?.get_mut(set)?.stop_waiting()?;
2504 }
2505
2506 if save_and_restore_thread {
2507 self.set_thread(old_guest_thread)?;
2508 }
2509
2510 if let Some(item) = old_next_switch_item {
2511 let state = self.concurrent_state_mut()?;
2512 state.restore_next_switch_item(item)?;
2513 }
2514
2515 Ok(())
2516 }
2517
2518 fn wait_for_event(
2519 &mut self,
2520 caller_instance: RuntimeInstance,
2521 waitable: Waitable,
2522 ) -> Result<()> {
2523 let caller = self.current_guest_thread()?;
2524 let state = self.concurrent_state_mut()?;
2525
2526 waitable.trap_if_in_waitable_set(state)?;
2527
2528 let set = state.get_mut(caller.thread)?.sync_call_set;
2529 waitable.join(state, Some(set))?;
2530
2531 self.switch_or_trap_if_may_not_suspend(caller_instance)?;
2532
2533 self.suspend(SuspendReason::Waiting {
2534 set,
2535 thread: caller,
2536 })?;
2537 let state = self.concurrent_state_mut()?;
2538
2539 waitable.join(state, None)
2540 }
2541
2542 fn cleanup_thread(
2564 &mut self,
2565 guest_thread: QualifiedThreadId,
2566 runtime_instance: RuntimeInstance,
2567 ) -> Result<()> {
2568 let state = self.concurrent_state_mut()?;
2569 state.take_next_switch_item()?;
2572 let thread_data = state.get_mut(guest_thread.thread)?;
2573 let sync_call_set = thread_data.sync_call_set;
2574 if let Some(guest_id) = thread_data.instance_rep {
2575 let (state, counter) = self.instance_state_and_handle_counter(runtime_instance);
2576 state
2577 .thread_handle_table()
2578 .guest_thread_remove(counter, guest_id)?;
2579 }
2580 let state = self.concurrent_state_mut()?;
2581
2582 for waitable in mem::take(&mut state.get_mut(sync_call_set)?.ready) {
2584 if let Some(Event::Subtask {
2585 status: Status::Returned | Status::ReturnCancelled,
2586 }) = waitable.common(state)?.event
2587 {
2588 waitable.delete_from(state)?;
2589 }
2590 }
2591
2592 state.delete(guest_thread.thread)?;
2593 state.delete(sync_call_set)?;
2594 let task = state.get_mut(guest_thread.task)?;
2595 task.threads.remove(&guest_thread.thread);
2596
2597 if task.threads.is_empty() && !task.returned_or_cancelled() {
2598 bail!(Trap::NoAsyncResult);
2599 }
2600
2601 if !task.decremented_interesting_task_count && task.exited && task.returned_or_cancelled() {
2602 task.decremented_interesting_task_count = true;
2603
2604 debug_assert!(state.interesting_tasks > 0);
2605 state.interesting_tasks -= 1;
2606 if state.interesting_tasks == 0
2607 && let Some(waker) = state.interesting_tasks_empty_waker.take()
2608 {
2609 waker.wake();
2610 }
2611 }
2612
2613 state.decrement_task_ref_count(guest_thread.task)?;
2614
2615 Ok(())
2616 }
2617
2618 fn cancel_guest_subtask_without_lowered_parameters(
2627 &mut self,
2628 caller_instance: RuntimeInstance,
2629 guest_task: TableId<GuestTask>,
2630 ) -> Result<()> {
2631 let concurrent_state = self.concurrent_state_mut()?;
2632 let task = concurrent_state.get_mut(guest_task)?;
2633 assert!(!task.already_lowered_parameters());
2634 task.lower_params = None;
2638 task.lift_result = None;
2639 task.exited = true;
2640 let instance = task.instance;
2641
2642 assert_eq!(1, task.threads.len());
2649 let thread = *task.threads.iter().next().unwrap();
2650 let next_switch_item = concurrent_state.save_next_switch_item()?;
2651 self.cleanup_thread(
2652 QualifiedThreadId {
2653 task: guest_task,
2654 thread,
2655 },
2656 caller_instance,
2657 )?;
2658 self.concurrent_state_mut()?
2659 .restore_next_switch_item(next_switch_item)?;
2660
2661 let pending = &mut self.instance_state(instance).concurrent_state().pending;
2663 let pending_count = pending.len();
2664 pending.retain(|thread, _| thread.task != guest_task);
2665
2666 if pending.len() == pending_count {
2667 let matches = |item: &WorkItem| match item {
2670 WorkItem::ResumeThread { thread, .. }
2671 | WorkItem::GuestCall {
2672 call: GuestCall { thread, .. },
2673 ..
2674 } => thread.task == guest_task,
2675 _ => false,
2676 };
2677
2678 let remove = |queue: &mut VecDeque<WorkItem>| {
2679 let count = queue.len();
2680 queue.retain(|item| !matches(item));
2681 count != queue.len()
2682 };
2683
2684 let state = self.concurrent_state_mut()?;
2685 let mut found = remove(&mut state.high_priority);
2686 found |= remove(&mut state.low_priority);
2687
2688 for item in [&mut state.switch_item, &mut state.next_switch_item] {
2689 if matches!(item, Some(item) if matches(item)) {
2690 found = true;
2691 *item = None;
2692 }
2693 }
2694
2695 if !found {
2696 bail!(Trap::SubtaskCancelAfterTerminal);
2697 }
2698 }
2699 Ok(())
2700 }
2701
2702 pub(crate) fn current_scope(&mut self) -> Result<Option<CurrentScope>> {
2705 if !self.concurrency_support() {
2706 return Ok(self
2707 .current_scope_id_not_concurrent()?
2708 .map(|id| CurrentScope::Id(Scope::Id(id))));
2709 }
2710
2711 Ok(match self.current_thread()? {
2712 CurrentThread::Guest(id) => Some(CurrentScope::Id(Scope::Id(id.task.rep()))),
2713 CurrentThread::Host(id) => Some(CurrentScope::Id(Scope::HostId(id.rep()))),
2714 CurrentThread::DeferredHost(_) => Some(CurrentScope::DeferredHost),
2715 CurrentThread::None => return Ok(None),
2716 })
2717 }
2718
2719 pub(crate) fn queue_task(
2720 &mut self,
2721 task: impl FnOnce(&mut dyn VMStore) -> Result<()> + Send + 'static,
2722 ) -> Result<()> {
2723 self.concurrent_state_mut()?
2724 .push_high_priority(WorkItem::WorkerFunction(AlwaysMut::new(Box::new(task))));
2725 Ok(())
2726 }
2727
2728 fn any_may_not_suspend(&mut self) -> Result<bool> {
2737 Ok(self
2745 .concurrent_state_mut()?
2746 .table
2747 .get_mut()
2748 .iter_mut()
2749 .filter_map(|(_, entry)| {
2750 if let Some(task) = entry.downcast_ref::<GuestTask>() {
2751 Some(task.instance)
2752 } else {
2753 None
2754 }
2755 })
2756 .collect::<Vec<_>>()
2757 .into_iter()
2758 .any(|instance| {
2759 self.instance_state(instance)
2760 .concurrent_state()
2761 .do_not_suspend
2762 }))
2763 }
2764}
2765
2766impl Instance {
2767 fn get_event(
2770 self,
2771 store: &mut StoreOpaque,
2772 guest_task: TableId<GuestTask>,
2773 set: Option<TableId<WaitableSet>>,
2774 cancellable: bool,
2775 ) -> Result<Option<(Event, Option<(Waitable, u32)>)>> {
2776 let state = store.concurrent_state_mut()?;
2777
2778 let task = state.get_mut(guest_task)?;
2779 let event = &mut task.event;
2780 if let Some(ev) = event
2781 && (cancellable || !matches!(ev, Event::Cancelled))
2782 {
2783 log::trace!("deliver event {ev:?} to {guest_task:?}");
2784
2785 if matches!(ev, Event::Cancelled) {
2786 task.cancel_request_delivered = true;
2787 }
2788
2789 let ev = *ev;
2790 *event = None;
2791 return Ok(Some((ev, None)));
2792 }
2793
2794 let set = match set {
2795 Some(set) => set,
2796 None => return Ok(None),
2797 };
2798 let waitable = match state.get_mut(set)?.ready.pop_first() {
2799 Some(v) => v,
2800 None => return Ok(None),
2801 };
2802
2803 let common = waitable.common(state)?;
2804 let handle = match common.handle {
2805 Some(h) => h,
2806 None => bail_bug!("handle not set when delivering event"),
2807 };
2808 let event = match common.event.take() {
2809 Some(e) => e,
2810 None => bail_bug!("event not set when delivering event"),
2811 };
2812
2813 log::trace!(
2814 "deliver event {event:?} to {guest_task:?} for {waitable:?} (handle {handle}); set {set:?}"
2815 );
2816
2817 waitable.on_delivery(store, self, event)?;
2818
2819 Ok(Some((event, Some((waitable, handle)))))
2820 }
2821
2822 fn handle_callback_code(
2829 self,
2830 store: &mut dyn VMStore,
2831 guest_thread: QualifiedThreadId,
2832 runtime_instance: RuntimeInstance,
2833 call: impl FnOnce(&mut dyn VMStore) -> Result<u32>,
2834 ) -> Result<()> {
2835 let old_thread = store.set_thread(guest_thread)?;
2836 log::trace!(
2837 "callback-lifted call: replaced {old_thread:?} with {guest_thread:?} as current thread"
2838 );
2839
2840 store.enter_instance(runtime_instance);
2841
2842 let mut code = call(store)?;
2843
2844 if matches!(
2850 unpack_callback_code(code).0,
2851 callback_code::YIELD | callback_code::WAIT
2852 ) && let Some((event, _)) = self.get_event(store, guest_thread.task, None, true)?
2853 {
2854 let (unpacked, set) = unpack_callback_code(code);
2855 log::trace!(
2856 "{guest_thread:?} returned callback code {unpacked} (set: {set}) with a pending \
2857 cancellation; delivering it via callback"
2858 );
2859 code = invoke_callback(store, guest_thread.task, event, 0)?;
2860 }
2861
2862 store.exit_instance(runtime_instance)?;
2863
2864 store.set_thread(old_thread)?;
2865 log::trace!("callback-lifted call: restored {old_thread:?} as current thread");
2866
2867 let store = store.store_opaque_mut();
2868 let (code, set) = unpack_callback_code(code);
2869
2870 log::trace!("received callback code from {guest_thread:?}: {code} (set: {set})");
2871
2872 let state = store.concurrent_state_mut()?;
2873
2874 state.take_next_switch_item()?;
2875
2876 let get_set = |store: &mut StoreOpaque, handle| -> Result<_> {
2877 let set = store
2878 .instance_state(runtime_instance)
2879 .handle_table()
2880 .waitable_set_rep(handle)?;
2881
2882 Ok(TableId::<WaitableSet>::new(set))
2883 };
2884
2885 match code {
2886 callback_code::EXIT => {
2887 log::trace!("implicit thread {guest_thread:?} completed");
2888 let task = store.concurrent_state_mut()?.get_mut(guest_thread.task)?;
2889 task.exited = true;
2890 task.callback = None;
2891
2892 store.switch_or_trap_if_may_not_suspend(runtime_instance)?;
2897
2898 store.cleanup_thread(guest_thread, runtime_instance)?;
2899 }
2900 callback_code::YIELD => {
2901 let old = state
2904 .get_mut(guest_thread.thread)?
2905 .wake_on_cancel
2906 .replace(WakeOnCancel::Yielding);
2907 if !old.is_none() {
2908 bail_bug!("thread unexpectedly had wake_on_cancel set");
2909 }
2910
2911 let call = GuestCall {
2918 thread: guest_thread,
2919 kind: GuestCallKind::DeliverEvent {
2920 instance: self,
2921 set: None,
2922 },
2923 };
2924 state.push_low_priority(WorkItem::GuestCall {
2927 instance: runtime_instance,
2928 call,
2929 });
2930 }
2931 callback_code::WAIT => {
2932 let set = get_set(store, set)?;
2933 self.wait_with_callback(store, guest_thread, set)?;
2934 }
2935 _ => bail!(Trap::UnsupportedCallbackCode),
2936 }
2937
2938 Ok(())
2939 }
2940
2941 fn wait_with_callback(
2947 self,
2948 store: &mut StoreOpaque,
2949 guest_thread: QualifiedThreadId,
2950 set: TableId<WaitableSet>,
2951 ) -> Result<()> {
2952 let state = store.concurrent_state_mut()?;
2953 state.get_mut(set)?.num_waiting += 1;
2956
2957 if state.get_mut(guest_thread.task)?.event.is_some()
2958 || !state.get_mut(set)?.ready.is_empty()
2959 {
2960 let instance = state.get_mut(guest_thread.task)?.instance;
2962 state.push_high_priority(WorkItem::GuestCall {
2963 instance,
2964 call: GuestCall {
2965 thread: guest_thread,
2966 kind: GuestCallKind::DeliverEvent {
2967 instance: self,
2968 set: Some(set),
2969 },
2970 },
2971 });
2972 return Ok(());
2973 }
2974
2975 let instance = store
2981 .concurrent_state_mut()?
2982 .get_mut(guest_thread.task)?
2983 .instance;
2984 store.switch_or_trap_if_may_not_suspend(instance)?;
2985
2986 let state = store.concurrent_state_mut()?;
2992 let old = state
2993 .get_mut(guest_thread.thread)?
2994 .wake_on_cancel
2995 .replace(WakeOnCancel::Waiting(set));
2996 if !old.is_none() {
2997 bail_bug!("thread unexpectedly had wake_on_cancel set");
2998 }
2999 let old = state
3000 .get_mut(set)?
3001 .waiting
3002 .insert(guest_thread, WaitMode::Callback(self));
3003 if !old.is_none() {
3004 bail_bug!("set's waiting set already had this thread registered");
3005 }
3006 Ok(())
3007 }
3008
3009 unsafe fn stage_call<T: 'static>(
3016 self,
3017 mut store: StoreContextMut<T>,
3018 guest_thread: QualifiedThreadId,
3019 callee: SendSyncPtr<VMFuncRef>,
3020 param_count: usize,
3021 result_count: usize,
3022 async_: bool,
3023 callback: Option<SendSyncPtr<VMFuncRef>>,
3024 post_return: Option<SendSyncPtr<VMFuncRef>>,
3025 host_caller: bool,
3026 ) -> Result<()> {
3027 unsafe fn make_call<T: 'static>(
3042 store: StoreContextMut<T>,
3043 guest_thread: QualifiedThreadId,
3044 callee: SendSyncPtr<VMFuncRef>,
3045 param_count: usize,
3046 result_count: usize,
3047 ) -> impl FnOnce(&mut dyn VMStore) -> Result<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>
3048 + Send
3049 + Sync
3050 + 'static
3051 + use<T> {
3052 let token = StoreToken::new(store);
3053 move |store: &mut dyn VMStore| {
3054 let mut storage = [MaybeUninit::uninit(); MAX_FLAT_PARAMS];
3055
3056 store
3057 .concurrent_state_mut()?
3058 .set_thread_running(guest_thread.thread)?;
3059 let task = store.concurrent_state_mut()?.get_mut(guest_thread.task)?;
3060 let lower = match task.lower_params.take() {
3061 Some(l) => l,
3062 None => bail_bug!("lower_params missing"),
3063 };
3064
3065 lower(store, &mut storage[..param_count])?;
3066
3067 let mut store = token.as_context_mut(store);
3068
3069 unsafe {
3072 crate::Func::call_unchecked_raw(
3073 &mut store,
3074 callee.as_non_null(),
3075 NonNull::new(
3076 &mut storage[..param_count.max(result_count)]
3077 as *mut [MaybeUninit<ValRaw>] as _,
3078 )
3079 .unwrap(),
3080 UncaughtException::Trap,
3081 )?;
3082 }
3083
3084 Ok(storage)
3085 }
3086 }
3087
3088 let call = unsafe {
3092 make_call(
3093 store.as_context_mut(),
3094 guest_thread,
3095 callee,
3096 param_count,
3097 result_count,
3098 )
3099 };
3100
3101 let callee_instance = store
3102 .0
3103 .concurrent_state_mut()?
3104 .get_mut(guest_thread.task)?
3105 .instance;
3106
3107 let fun = if callback.is_some() {
3108 assert!(async_);
3109
3110 Box::new(move |store: &mut dyn VMStore| {
3111 self.add_guest_thread_to_instance_table(
3112 guest_thread.thread,
3113 store,
3114 callee_instance.index,
3115 )?;
3116 self.handle_callback_code(store, guest_thread, callee_instance, |store| {
3117 let storage = call(store)?;
3118
3119 Ok(unsafe { storage[0].assume_init() }.get_i32() as u32)
3122 })
3123 }) as Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send + Sync>
3124 } else {
3125 let token = StoreToken::new(store.as_context_mut());
3126 Box::new(move |store: &mut dyn VMStore| {
3127 self.add_guest_thread_to_instance_table(
3128 guest_thread.thread,
3129 store,
3130 callee_instance.index,
3131 )?;
3132 let old_thread = store.set_thread(guest_thread)?;
3133 log::trace!(
3134 "sync/async-stackful call: replaced {old_thread:?} with {guest_thread:?} as current thread",
3135 );
3136 let flags = self.id().get(store).instance_flags(callee_instance.index);
3137
3138 let callee_async_typed = store
3139 .concurrent_state_mut()?
3140 .get_mut(guest_thread.task)?
3141 .async_typed;
3142
3143 if !async_ && callee_async_typed {
3147 store.enter_instance(callee_instance);
3148 }
3149
3150 if !callee_async_typed {
3151 store.enter_sync_call(callee_instance)?;
3152 }
3153
3154 let storage = call(store)?;
3161
3162 if !callee_async_typed {
3163 store.exit_sync_call(callee_instance)?;
3164 }
3165
3166 if !async_ {
3167 if callee_async_typed {
3173 store.exit_instance(callee_instance)?;
3174 }
3175
3176 let lift = {
3177 let state = store.concurrent_state_mut()?;
3178 if !state.get_mut(guest_thread.task)?.result.is_none() {
3179 bail_bug!("task has already produced a result");
3180 }
3181
3182 match state.get_mut(guest_thread.task)?.lift_result.take() {
3183 Some(lift) => lift,
3184 None => bail_bug!("lift_result field is missing"),
3185 }
3186 };
3187
3188 let result = (lift.lift)(store, unsafe {
3191 mem::transmute::<&[MaybeUninit<ValRaw>], &[ValRaw]>(
3192 &storage[..result_count],
3193 )
3194 })?;
3195
3196 let post_return_arg = match result_count {
3197 0 => ValRaw::i32(0),
3198 1 => unsafe { storage[0].assume_init() },
3201 _ => unreachable!(),
3202 };
3203
3204 unsafe {
3205 call_post_return(
3206 token.as_context_mut(store),
3207 post_return.map(|v| v.as_non_null()),
3208 post_return_arg,
3209 flags,
3210 )?;
3211 }
3212
3213 self.task_complete(store, guest_thread.task, result, Status::Returned)?;
3214 }
3215
3216 store.set_thread(old_thread)?;
3217
3218 store
3219 .concurrent_state_mut()?
3220 .get_mut(guest_thread.task)?
3221 .exited = true;
3222
3223 log::trace!(
3224 "clean up thread; async lifted? {async_} async typed? {callee_async_typed}"
3225 );
3226
3227 if callee_async_typed {
3228 store.switch_or_trap_if_may_not_suspend(callee_instance)?;
3233 }
3234
3235 store.cleanup_thread(guest_thread, callee_instance)?;
3237 Ok(())
3238 })
3239 };
3240
3241 store.0.concurrent_state_mut()?.push_work_item(
3242 WorkItem::GuestCall {
3243 instance: callee_instance,
3244 call: GuestCall {
3245 thread: guest_thread,
3246 kind: GuestCallKind::StartImplicit(fun),
3247 },
3248 },
3249 if host_caller {
3250 Priority::High
3251 } else {
3252 Priority::Switch
3253 },
3254 )?;
3255
3256 Ok(())
3257 }
3258
3259 unsafe fn prepare_call<T: 'static>(
3272 self,
3273 mut store: StoreContextMut<T>,
3274 start: NonNull<VMFuncRef>,
3275 return_: NonNull<VMFuncRef>,
3276 caller_instance: RuntimeComponentInstanceIndex,
3277 callee_instance: RuntimeComponentInstanceIndex,
3278 task_return_type: TypeTupleIndex,
3279 callee_async_typed: bool,
3280 memory: *mut VMMemoryDefinition,
3281 string_encoding: StringEncoding,
3282 caller_info: CallerInfo,
3283 ) -> Result<()> {
3284 enum ResultInfo {
3285 Heap { results: u32 },
3286 Stack { result_count: u32 },
3287 }
3288
3289 let result_info = match &caller_info {
3290 CallerInfo::Async {
3291 has_result: true,
3292 params,
3293 } => ResultInfo::Heap {
3294 results: match params.last() {
3296 Some(r) => r.get_u32(),
3297 None => bail_bug!("retptr missing"),
3298 },
3299 },
3300 CallerInfo::Async {
3301 has_result: false, ..
3302 } => ResultInfo::Stack { result_count: 0 },
3303 CallerInfo::Sync {
3304 result_count,
3305 params,
3306 } if *result_count > u32::try_from(MAX_FLAT_RESULTS)? => ResultInfo::Heap {
3307 results: match params.last() {
3309 Some(r) => r.get_u32(),
3310 None => bail_bug!("arg ptr missing"),
3311 },
3312 },
3313 CallerInfo::Sync { result_count, .. } => ResultInfo::Stack {
3314 result_count: *result_count,
3315 },
3316 };
3317
3318 let sync_caller = matches!(caller_info, CallerInfo::Sync { .. });
3319
3320 let start = SendSyncPtr::new(start);
3324 let return_ = SendSyncPtr::new(return_);
3325 let token = StoreToken::new(store.as_context_mut());
3326 let old_thread = store.0.current_guest_thread()?;
3327
3328 let state = store.0.concurrent_state_mut()?;
3329
3330 debug_assert_eq!(
3331 state.get_mut(old_thread.task)?.instance,
3332 self.runtime_instance(caller_instance)
3333 );
3334
3335 let guest_thread = GuestTask::new(
3336 state,
3337 Box::new(move |store, dst| {
3338 let mut store = token.as_context_mut(store);
3339 assert!(dst.len() <= MAX_FLAT_PARAMS);
3340 let mut src = [MaybeUninit::uninit(); MAX_FLAT_PARAMS + 1];
3342 let count = match caller_info {
3343 CallerInfo::Async { params, has_result } => {
3347 let params = ¶ms[..params.len() - usize::from(has_result)];
3348 for (param, src) in params.iter().zip(&mut src) {
3349 src.write(*param);
3350 }
3351 params.len()
3352 }
3353
3354 CallerInfo::Sync { params, .. } => {
3356 for (param, src) in params.iter().zip(&mut src) {
3357 src.write(*param);
3358 }
3359 params.len()
3360 }
3361 };
3362 unsafe {
3369 crate::Func::call_unchecked_raw(
3370 &mut store,
3371 start.as_non_null(),
3372 NonNull::new(
3373 &mut src[..count.max(dst.len())] as *mut [MaybeUninit<ValRaw>] as _,
3374 )
3375 .unwrap(),
3376 UncaughtException::Trap,
3377 )?;
3378 }
3379 dst.copy_from_slice(&src[..dst.len()]);
3380 let task = store.0.current_guest_thread()?.task;
3381 let state = store.0.concurrent_state_mut()?;
3382 Waitable::Guest(task).set_event(
3383 state,
3384 Some(Event::Subtask {
3385 status: Status::Started,
3386 }),
3387 )?;
3388 Ok(())
3389 }),
3390 LiftResult {
3391 lift: Box::new(move |store, src| {
3392 let mut store = token.as_context_mut(store);
3395 let mut my_src = src.to_owned(); if let ResultInfo::Heap { results } = &result_info {
3397 my_src.push(ValRaw::u32(*results));
3398 }
3399
3400 unsafe {
3407 crate::Func::call_unchecked_raw(
3408 &mut store,
3409 return_.as_non_null(),
3410 my_src.as_mut_slice().into(),
3411 UncaughtException::Trap,
3412 )?;
3413 }
3414
3415 let thread = store.0.current_guest_thread()?;
3416 let state = store.0.concurrent_state_mut()?;
3417 if sync_caller {
3418 state.get_mut(thread.task)?.sync_result = SyncResult::Produced(
3419 if let ResultInfo::Stack { result_count } = &result_info {
3420 match result_count {
3421 0 => None,
3422 1 => Some(my_src[0]),
3423 _ => unreachable!(),
3424 }
3425 } else {
3426 None
3427 },
3428 );
3429 }
3430 Ok(Box::new(DummyResult) as Box<dyn Any + Send + Sync>)
3431 }),
3432 ty: task_return_type,
3433 memory: NonNull::new(memory).map(SendSyncPtr::new),
3434 string_encoding,
3435 },
3436 Caller::Guest { thread: old_thread },
3437 None,
3438 self.runtime_instance(callee_instance),
3439 callee_async_typed,
3440 false,
3443 )?;
3444
3445 store.0.set_thread(guest_thread)?;
3448 log::trace!("pushed {guest_thread:?} as current thread; old thread was {old_thread:?}");
3449
3450 Ok(())
3451 }
3452
3453 unsafe fn call_callback<T>(
3458 self,
3459 mut store: StoreContextMut<T>,
3460 function: SendSyncPtr<VMFuncRef>,
3461 event: Event,
3462 handle: u32,
3463 ) -> Result<u32> {
3464 let (ordinal, result) = event.parts();
3465 let params = &mut [
3466 ValRaw::u32(ordinal),
3467 ValRaw::u32(handle),
3468 ValRaw::u32(result),
3469 ];
3470 unsafe {
3475 crate::Func::call_unchecked_raw(
3476 &mut store,
3477 function.as_non_null(),
3478 params.as_mut_slice().into(),
3479 UncaughtException::Trap,
3480 )?;
3481 }
3482 Ok(params[0].get_u32())
3483 }
3484
3485 unsafe fn start_call<T: 'static>(
3503 self,
3504 mut store: StoreContextMut<T>,
3505 callback: *mut VMFuncRef,
3506 post_return: *mut VMFuncRef,
3507 callee: NonNull<VMFuncRef>,
3508 param_count: u32,
3509 result_count: u32,
3510 flags: u32,
3511 storage: &mut [MaybeUninit<ValRaw>],
3512 ) -> Result<()> {
3513 let token = StoreToken::new(store.as_context_mut());
3514 let async_caller = (flags & START_FLAG_ASYNC_CALLER) != 0;
3515 let guest_thread = store.0.current_guest_thread()?;
3516 let state = store.0.concurrent_state_mut()?;
3517
3518 if !state.event_loop_running {
3519 bail_bug!("Instance::start_call called without a running event loop");
3520 }
3521
3522 let callee = SendSyncPtr::new(callee);
3523 let param_count = usize::try_from(param_count)?;
3524 assert!(param_count <= MAX_FLAT_PARAMS);
3525 let result_count = usize::try_from(result_count)?;
3526 assert!(result_count <= MAX_FLAT_RESULTS);
3527
3528 let task = state.get_mut(guest_thread.task)?;
3529 let callee_async_typed = task.async_typed;
3530 let callee_instance = task.instance;
3531
3532 task.async_lifted = (flags & START_FLAG_ASYNC_CALLEE) != 0;
3533
3534 if let Some(callback) = NonNull::new(callback) {
3535 let callback = SendSyncPtr::new(callback);
3539 task.callback = Some(Box::new(move |store, event, handle| {
3540 let store = token.as_context_mut(store);
3541 unsafe { self.call_callback::<T>(store, callback, event, handle) }
3542 }));
3543 }
3544
3545 let Caller::Guest { thread: caller } = &task.caller else {
3546 bail_bug!("start_call unexpectedly invoked for host->guest call");
3549 };
3550 let caller = *caller;
3551 let caller_instance = state.get_mut(caller.task)?.instance;
3552
3553 unsafe {
3555 self.stage_call(
3556 store.as_context_mut(),
3557 guest_thread,
3558 callee,
3559 param_count,
3560 result_count,
3561 (flags & START_FLAG_ASYNC_CALLEE) != 0,
3562 NonNull::new(callback).map(SendSyncPtr::new),
3563 NonNull::new(post_return).map(SendSyncPtr::new),
3564 false,
3565 )?;
3566 }
3567
3568 let old_do_not_suspend = if callee_async_typed {
3569 let state = store.0.instance_state(callee_instance).concurrent_state();
3576 let old_do_not_suspend = state.do_not_suspend;
3577 state.do_not_suspend = false;
3578 Some(old_do_not_suspend)
3579 } else {
3580 None
3581 };
3582
3583 let state = store.0.concurrent_state_mut()?;
3584
3585 let guest_waitable = Waitable::Guest(guest_thread.task);
3588 let old_set = guest_waitable.common(state)?.set;
3589 let set = state.get_mut(caller.thread)?.sync_call_set;
3590 guest_waitable.join(state, Some(set))?;
3591
3592 store.0.set_thread(CurrentThread::None)?;
3593
3594 let mut yielded = false;
3610 let (status, waitable) = loop {
3611 store.0.suspend(if yielded {
3612 SuspendReason::Waiting {
3613 set,
3614 thread: caller,
3615 }
3616 } else {
3617 yielded = true;
3618 SuspendReason::YieldingToSubtask { thread: caller }
3619 })?;
3620
3621 if let Some(old_do_not_suspend) = old_do_not_suspend {
3622 store
3623 .0
3624 .instance_state(callee_instance)
3625 .concurrent_state()
3626 .do_not_suspend = old_do_not_suspend;
3627 }
3628
3629 let state = store.0.concurrent_state_mut()?;
3630
3631 log::trace!("taking event for {:?}", guest_thread.task);
3632 let event = guest_waitable.take_event(state)?;
3633 let Some(Event::Subtask { status }) = event else {
3634 bail_bug!("subtasks should only get subtask events, got {event:?}")
3635 };
3636
3637 log::trace!("status {status:?} for {:?}", guest_thread.task);
3638
3639 if status == Status::Returned {
3640 break (status, None);
3642 } else if async_caller {
3643 let (state, counter) = store.0.instance_state_and_handle_counter(caller_instance);
3647 let handle = state
3648 .handle_table()
3649 .subtask_insert_guest(counter, guest_thread.task.rep())?;
3650 store
3651 .0
3652 .concurrent_state_mut()?
3653 .get_mut(guest_thread.task)?
3654 .common
3655 .handle = Some(handle);
3656 break (status, Some(handle));
3657 } else {
3658 store.0.switch_or_trap_if_may_not_suspend(caller_instance)?;
3662 }
3663 };
3664
3665 guest_waitable.join(store.0.concurrent_state_mut()?, old_set)?;
3666
3667 store.0.set_thread(caller)?;
3669
3670 store
3671 .0
3672 .concurrent_state_mut()?
3673 .set_thread_running(caller.thread)?;
3674
3675 log::trace!("popped current thread {guest_thread:?}; new thread is {caller:?}");
3676
3677 if async_caller {
3678 let Some(slot) = storage.first_mut() else {
3679 bail_bug!("no storage for async call status");
3680 };
3681 *slot = MaybeUninit::new(ValRaw::u32(status.pack(waitable)));
3682 } else {
3683 let state = store.0.concurrent_state_mut()?;
3686 let task = state.get_mut(guest_thread.task)?;
3687 if let Some(Some(result)) = task.sync_result.take()? {
3688 storage[0] = MaybeUninit::new(result);
3689 }
3690 }
3691
3692 if status == Status::Returned {
3693 store
3694 .0
3695 .concurrent_state_mut()?
3696 .decrement_task_ref_count(guest_thread.task)?;
3697 }
3698
3699 Ok(())
3700 }
3701
3702 pub(crate) fn first_poll<T: 'static, R: Send + 'static>(
3718 self,
3719 mut store: StoreContextMut<'_, T>,
3720 host_task: EnteredHostTask,
3721 result_may_require_realloc: bool,
3722 future: impl Future<Output = Result<R>> + Send + 'static,
3723 lower: impl FnOnce(StoreContextMut<T>, Option<R>, bool, Option<TableId<HostTask>>) -> Result<()>
3724 + Send
3725 + 'static,
3726 ) -> Result<u32> {
3727 let token = StoreToken::new(store.as_context_mut());
3728
3729 let (join_handle, future) = JoinHandle::run(future);
3732 let mut future = Box::pin(future);
3733
3734 let poll = tls::set(store.0, || {
3739 future
3740 .as_mut()
3741 .poll(&mut Context::from_waker(&Waker::noop()))
3742 });
3743
3744 match poll {
3745 Poll::Ready(result) => {
3747 let result = result.transpose()?;
3748 let task = store.0.current_materialized_host_task()?;
3751 lower(store.as_context_mut(), result, true, task)?;
3752 return Ok(Status::Returned.pack(None));
3753 }
3754
3755 Poll::Pending => {}
3757 }
3758
3759 let Some(task) = store.0.materialize_host_task_id()? else {
3763 bail_bug!("current thread is not a host thread")
3764 };
3765 {
3766 let state = &mut store.0.concurrent_state_mut()?.get_mut(task)?.state;
3767 assert!(matches!(state, HostTaskState::CalleeStarted));
3768 *state = HostTaskState::CalleeRunning(join_handle);
3769 }
3770
3771 let future = Box::pin(async move {
3779 let result = match run_with_host_task_set(task, future).await? {
3780 Some(result) => Some(result?),
3781 None => None,
3782 };
3783 let on_complete = move |store: &mut dyn VMStore| {
3784 let mut store = token.as_context_mut(store);
3788 let old = store.0.set_thread(task)?;
3789
3790 let status = if result.is_some() {
3791 Status::Returned
3792 } else {
3793 Status::ReturnCancelled
3794 };
3795
3796 lower(store.as_context_mut(), result, false, Some(task))?;
3797 let state = store.0.concurrent_state_mut()?;
3798 match &mut state.get_mut(task)?.state {
3799 pending @ HostTaskState::CalleeCancelling => {
3802 *pending = HostTaskState::CalleeDone { cancelled: true };
3803 }
3804
3805 other => *other = HostTaskState::CalleeDone { cancelled: false },
3807 }
3808 Waitable::Host(task).set_event(state, Some(Event::Subtask { status }))?;
3809
3810 store.0.set_thread(old)?;
3811 Ok(())
3812 };
3813
3814 tls::get(move |store| {
3815 if result_may_require_realloc {
3816 store
3821 .concurrent_state_mut()?
3822 .push_high_priority(WorkItem::WorkerFunction(AlwaysMut::new(Box::new(
3823 on_complete,
3824 ))));
3825 Ok(())
3826 } else {
3827 on_complete(store)
3830 }
3831 })
3832 });
3833
3834 let caller = match host_task {
3837 Some(caller) => caller,
3838 None => bail_bug!("host task wasn't created but should have been"),
3839 };
3840 let state = store.0.concurrent_state_mut()?;
3841 state.push_future(future);
3842 let instance = state.get_mut(caller.task)?.instance;
3843 let (state, counter) = store.0.instance_state_and_handle_counter(instance);
3844 let handle = state
3845 .handle_table()
3846 .subtask_insert_host(counter, task.rep())?;
3847 store.0.concurrent_state_mut()?.get_mut(task)?.common.handle = Some(handle);
3848 log::trace!("assign {task:?} handle {handle} for {caller:?} instance {instance:?}");
3849
3850 store.0.set_thread(caller)?;
3854 Ok(Status::Started.pack(Some(handle)))
3855 }
3856
3857 pub(crate) fn task_return(
3860 self,
3861 store: &mut dyn VMStore,
3862 ty: TypeTupleIndex,
3863 options: OptionsIndex,
3864 storage: &[ValRaw],
3865 ) -> Result<()> {
3866 let guest_thread = store.current_guest_thread()?;
3867 let state = store.concurrent_state_mut()?;
3868 if !state.get_mut(guest_thread.task)?.async_lifted {
3869 bail!(Trap::TaskReturnOrCancelSyncLifted);
3870 }
3871 let lift = state
3872 .get_mut(guest_thread.task)?
3873 .lift_result
3874 .take()
3875 .ok_or_else(|| Trap::TaskCancelOrReturnTwice)?;
3876 if !state.get_mut(guest_thread.task)?.result.is_none() {
3877 bail_bug!("task result unexpectedly already set");
3878 }
3879
3880 let CanonicalOptions {
3881 string_encoding,
3882 data_model,
3883 ..
3884 } = &self.id().get(store).component().env_component().options[options];
3885
3886 let invalid = ty != lift.ty
3887 || string_encoding != &lift.string_encoding
3888 || match data_model {
3889 CanonicalOptionsDataModel::LinearMemory(opts) => match opts.memory {
3890 Some(memory) => {
3891 let expected = lift.memory.map(|v| v.as_ptr()).unwrap_or(ptr::null_mut());
3892 let actual = self.id().get(store).runtime_memory(memory);
3893 expected != actual.as_ptr()
3894 }
3895 None => false,
3898 },
3899 CanonicalOptionsDataModel::Gc { .. } => true,
3901 };
3902
3903 if invalid {
3904 bail!(Trap::TaskReturnInvalid);
3905 }
3906
3907 log::trace!("task.return for {guest_thread:?}");
3908
3909 let result = (lift.lift)(store, storage)?;
3910 self.task_complete(store, guest_thread.task, result, Status::Returned)
3911 }
3912
3913 pub(crate) fn task_cancel(self, store: &mut StoreOpaque) -> Result<()> {
3915 let guest_thread = store.current_guest_thread()?;
3916 let state = store.concurrent_state_mut()?;
3917 let task = state.get_mut(guest_thread.task)?;
3918 if !task.async_lifted {
3919 bail!(Trap::TaskReturnOrCancelSyncLifted);
3920 }
3921 if !task.cancel_request_delivered {
3922 bail!(Trap::TaskCancelNotCancelled);
3923 }
3924 _ = task
3925 .lift_result
3926 .take()
3927 .ok_or_else(|| Trap::TaskCancelOrReturnTwice)?;
3928
3929 if !task.result.is_none() {
3930 bail_bug!("task result should not bet set yet");
3931 }
3932
3933 log::trace!("task.cancel for {guest_thread:?}");
3934
3935 self.task_complete(
3936 store,
3937 guest_thread.task,
3938 Box::new(DummyResult),
3939 Status::ReturnCancelled,
3940 )
3941 }
3942
3943 fn task_complete(
3949 self,
3950 store: &mut StoreOpaque,
3951 guest_task: TableId<GuestTask>,
3952 result: Box<dyn Any + Send + Sync>,
3953 status: Status,
3954 ) -> Result<()> {
3955 store
3956 .component_resource_tables(Some(self))?
3957 .validate_scope_exit()?;
3958
3959 let state = store.concurrent_state_mut()?;
3960 let task = state.get_mut(guest_task)?;
3961
3962 task.event = None;
3966
3967 if let Caller::Host { tx, .. } = &mut task.caller {
3968 if let Some(tx) = tx.take() {
3969 _ = tx.send(result);
3970 }
3971 } else {
3972 task.result = Some(result);
3973 Waitable::Guest(guest_task).set_event(state, Some(Event::Subtask { status }))?;
3974 }
3975
3976 Ok(())
3977 }
3978
3979 pub(crate) fn waitable_set_new(
3981 self,
3982 store: &mut StoreOpaque,
3983 caller_instance: RuntimeComponentInstanceIndex,
3984 ) -> Result<u32> {
3985 let set = store.concurrent_state_mut()?.push(WaitableSet::default())?;
3986 let (state, counter) =
3987 store.instance_state_and_handle_counter(self.runtime_instance(caller_instance));
3988 let handle = state
3989 .handle_table()
3990 .waitable_set_insert(counter, set.rep())?;
3991 log::trace!("new waitable set {set:?} (handle {handle})");
3992 Ok(handle)
3993 }
3994
3995 pub(crate) fn waitable_set_drop(
3997 self,
3998 store: &mut StoreOpaque,
3999 caller_instance: RuntimeComponentInstanceIndex,
4000 set: u32,
4001 ) -> Result<()> {
4002 let (state, counter) =
4003 store.instance_state_and_handle_counter(self.runtime_instance(caller_instance));
4004 let rep = state.handle_table().waitable_set_remove(counter, set)?;
4005
4006 log::trace!("drop waitable set {rep} (handle {set})");
4007
4008 let set = store
4012 .concurrent_state_mut()?
4013 .get_mut(TableId::<WaitableSet>::new(rep))?;
4014 if set.num_waiting > 0 {
4015 bail!(Trap::WaitableSetDropHasWaiters);
4016 }
4017
4018 store
4019 .concurrent_state_mut()?
4020 .delete(TableId::<WaitableSet>::new(rep))?;
4021
4022 Ok(())
4023 }
4024
4025 pub(crate) fn waitable_join(
4027 self,
4028 store: &mut StoreOpaque,
4029 caller_instance: RuntimeComponentInstanceIndex,
4030 waitable_handle: u32,
4031 set_handle: u32,
4032 ) -> Result<()> {
4033 let mut instance = self.id().get_mut(store);
4034 let waitable =
4035 Waitable::from_instance(instance.as_mut(), caller_instance, waitable_handle)?;
4036
4037 let set = if set_handle == 0 {
4038 None
4039 } else {
4040 let set = instance.instance_states().0[caller_instance]
4041 .handle_table()
4042 .waitable_set_rep(set_handle)?;
4043
4044 Some(TableId::<WaitableSet>::new(set))
4045 };
4046
4047 waitable.trap_if_has_sync_waiter(store.concurrent_state_mut()?)?;
4048
4049 log::trace!(
4050 "waitable {waitable:?} (handle {waitable_handle}) join set {set:?} (handle {set_handle})",
4051 );
4052
4053 waitable.join(store.concurrent_state_mut()?, set)
4054 }
4055
4056 pub(crate) fn subtask_drop(
4058 self,
4059 store: &mut StoreOpaque,
4060 caller_instance: RuntimeComponentInstanceIndex,
4061 task_id: u32,
4062 ) -> Result<()> {
4063 self.waitable_join(store, caller_instance, task_id, 0)?;
4064
4065 let (state, counter) =
4066 store.instance_state_and_handle_counter(self.runtime_instance(caller_instance));
4067 let (rep, is_host) = state.handle_table().subtask_remove(counter, task_id)?;
4068
4069 let concurrent_state = store.concurrent_state_mut()?;
4070 let waitable = if is_host {
4071 let id = TableId::<HostTask>::new(rep);
4072 let task = concurrent_state.get_mut(id)?;
4073 match &task.state {
4074 HostTaskState::CalleeRunning(_) | HostTaskState::CalleeCancelling => {
4075 bail!(Trap::SubtaskDropNotResolved)
4076 }
4077 HostTaskState::CalleeDone { .. } => {}
4078 HostTaskState::CalleeStarted | HostTaskState::CalleeFinished(_) => {
4079 bail_bug!("invalid state for callee in `subtask.drop`")
4080 }
4081 }
4082
4083 Waitable::Host(id)
4084 } else {
4085 let id = TableId::<GuestTask>::new(rep);
4086 let task = concurrent_state.get_mut(id)?;
4087 if task.lift_result.is_some() {
4088 bail!(Trap::SubtaskDropNotResolved);
4089 }
4090 Waitable::Guest(id)
4091 };
4092
4093 waitable.common(concurrent_state)?.handle = None;
4094
4095 if waitable.take_event(concurrent_state)?.is_some() {
4098 bail!(Trap::SubtaskDropNotResolved);
4099 }
4100
4101 waitable.delete_from(concurrent_state)?;
4102
4103 log::trace!("subtask_drop {waitable:?} (handle {task_id})");
4104 Ok(())
4105 }
4106
4107 pub(crate) fn waitable_set_wait(
4109 self,
4110 store: &mut StoreOpaque,
4111 options: OptionsIndex,
4112 set: u32,
4113 payload: u32,
4114 ) -> Result<u32> {
4115 let &CanonicalOptions {
4116 instance: caller_instance,
4117 ..
4118 } = &self.id().get(store).component().env_component().options[options];
4119 let caller = self.runtime_instance(caller_instance);
4120 let rep = store
4121 .instance_state(self.runtime_instance(caller_instance))
4122 .handle_table()
4123 .waitable_set_rep(set)?;
4124
4125 self.waitable_check(
4126 store,
4127 caller,
4128 WaitableCheck::Wait,
4129 WaitableCheckParams {
4130 set: TableId::new(rep),
4131 options,
4132 payload,
4133 },
4134 )
4135 }
4136
4137 pub(crate) fn waitable_set_poll(
4139 self,
4140 store: &mut StoreOpaque,
4141 options: OptionsIndex,
4142 set: u32,
4143 payload: u32,
4144 ) -> Result<u32> {
4145 let &CanonicalOptions {
4146 instance: caller_instance,
4147 ..
4148 } = &self.id().get(store).component().env_component().options[options];
4149 let caller = self.runtime_instance(caller_instance);
4150 let rep = store
4151 .instance_state(caller)
4152 .handle_table()
4153 .waitable_set_rep(set)?;
4154
4155 self.waitable_check(
4156 store,
4157 caller,
4158 WaitableCheck::Poll,
4159 WaitableCheckParams {
4160 set: TableId::new(rep),
4161 options,
4162 payload,
4163 },
4164 )
4165 }
4166
4167 pub(crate) fn thread_index(&self, store: &mut dyn VMStore) -> Result<u32> {
4169 let thread_id = store.current_guest_thread()?.thread;
4170 match store
4171 .concurrent_state_mut()?
4172 .get_mut(thread_id)?
4173 .instance_rep
4174 {
4175 Some(r) => Ok(r),
4176 None => bail_bug!("thread should have instance_rep by now"),
4177 }
4178 }
4179
4180 pub(crate) fn thread_new_indirect<T: 'static>(
4182 self,
4183 mut store: StoreContextMut<T>,
4184 runtime_instance: RuntimeComponentInstanceIndex,
4185 start_func_ty: ModuleInternedTypeIndex,
4186 start_func_table_idx: RuntimeTableIndex,
4187 start_func_idx: u32,
4188 context: i32,
4189 ) -> Result<u32> {
4190 log::trace!("creating new thread");
4191
4192 let (instance, registry) = self.id().get_mut_and_registry(store.0);
4193 let Some(start_func_ty) = instance.component().signatures().shared_type(start_func_ty)
4194 else {
4195 bail_bug!("thread.new-indirect start function type should be registered");
4196 };
4197 let callee = instance
4198 .index_runtime_func_table(registry, start_func_table_idx, start_func_idx as u64)?
4199 .ok_or_else(|| Trap::ThreadNewIndirectUninitialized)?;
4200 if callee.type_index(store.0) != start_func_ty {
4201 bail!(Trap::ThreadNewIndirectInvalidType);
4202 }
4203
4204 let token = StoreToken::new(store.as_context_mut());
4205 let start_func = Box::new(
4206 move |store: &mut dyn VMStore, guest_thread: QualifiedThreadId| -> Result<()> {
4207 let old_thread = store.set_thread(guest_thread)?;
4208 log::trace!(
4209 "thread start: replaced {old_thread:?} with {guest_thread:?} as current thread"
4210 );
4211
4212 let mut store = token.as_context_mut(store);
4213 let mut params = [ValRaw::i32(context)];
4214 unsafe { callee.call_unchecked(store.as_context_mut(), &mut params)? };
4217
4218 store.0.set_thread(old_thread)?;
4219
4220 let runtime_instance = self.runtime_instance(runtime_instance);
4221
4222 store
4225 .0
4226 .switch_or_trap_if_may_not_suspend(runtime_instance)?;
4227
4228 store.0.cleanup_thread(guest_thread, runtime_instance)?;
4229
4230 log::trace!("explicit thread {guest_thread:?} completed");
4231 let state = store.0.concurrent_state_mut()?;
4232 if let Some(t) = old_thread.guest() {
4233 state.set_thread_running(t.thread)?;
4234 }
4235 log::trace!("thread start: restored {old_thread:?} as current thread");
4236
4237 Ok(())
4238 },
4239 );
4240
4241 let current_thread = store.0.current_guest_thread()?;
4242 let state = store.0.concurrent_state_mut()?;
4243 let parent_task = current_thread.task;
4244
4245 let new_thread = GuestThread::new_explicit(state, parent_task, start_func)?;
4246 let thread_id = state.push(new_thread)?;
4247 state.get_mut(parent_task)?.threads.insert(thread_id);
4248
4249 log::trace!("new thread with id {thread_id:?} created");
4250
4251 self.add_guest_thread_to_instance_table(thread_id, store.0, runtime_instance)
4252 }
4253
4254 pub(crate) fn resume_thread(
4255 self,
4256 store: &mut StoreOpaque,
4257 runtime_instance: RuntimeComponentInstanceIndex,
4258 thread_idx: u32,
4259 how: ResumeThread,
4260 ) -> Result<bool> {
4261 let thread_id =
4262 GuestThread::from_instance(self.id().get_mut(store), runtime_instance, thread_idx)?;
4263 let state = store.concurrent_state_mut()?;
4264 let guest_thread = QualifiedThreadId::qualify(state, thread_id)?;
4265
4266 if store.current_guest_thread()? == guest_thread {
4267 bail!(Trap::CannotResumeThread);
4268 }
4269
4270 let priority = match how {
4271 ResumeThread::Resume => Priority::Switch,
4272 ResumeThread::ResumeLater => Priority::Low,
4273
4274 ResumeThread::Promote => {
4277 let instance = self.runtime_instance(runtime_instance);
4278 let do_not_enter = store
4279 .instance_state(instance)
4280 .concurrent_state()
4281 .do_not_enter;
4282 return store.concurrent_state_mut()?.promote_work_item_matching(
4283 |item: &WorkItem| match item {
4284 WorkItem::ResumeThread { thread, .. }
4285 | WorkItem::ResumeFiber { thread, .. } => *thread == guest_thread,
4286
4287 WorkItem::GuestCall {
4288 call: GuestCall { thread, kind },
4289 ..
4290 } => {
4291 *thread == guest_thread
4292 && match kind {
4293 GuestCallKind::DeliverEvent { .. } => !do_not_enter,
4297
4298 GuestCallKind::StartExplicit(_) => true,
4301
4302 GuestCallKind::StartImplicit(_) => false,
4306 }
4307 }
4308
4309 WorkItem::PushFuture(_) | WorkItem::WorkerFunction(_) => false,
4310 },
4311 );
4312 }
4313 };
4314
4315 let state = store.concurrent_state_mut()?;
4316 let thread = state.get_mut(guest_thread.thread)?;
4317
4318 match &thread.state {
4321 GuestThreadState::NotStartedExplicit(_) => {}
4322 GuestThreadState::Suspended(_) => {
4323 log::trace!("resuming thread {thread_id:?} that was suspended");
4324 state.schedule_suspended_thread(
4325 guest_thread,
4326 self.runtime_instance(runtime_instance),
4327 priority,
4328 )?;
4329 return Ok(true);
4330 }
4331 _ => bail!(Trap::CannotResumeThread),
4332 }
4333 match mem::replace(&mut thread.state, GuestThreadState::Running) {
4334 GuestThreadState::NotStartedExplicit(start_func) => {
4335 log::trace!("starting thread {guest_thread:?}");
4336 let guest_call = WorkItem::GuestCall {
4337 instance: self.runtime_instance(runtime_instance),
4338 call: GuestCall {
4339 thread: guest_thread,
4340 kind: GuestCallKind::StartExplicit(Box::new(move |store| {
4341 start_func(store, guest_thread)
4342 })),
4343 },
4344 };
4345 state.push_work_item(guest_call, priority)?;
4346 }
4347 other => {
4348 thread.state = other;
4349 bail_bug!("thread state checked to be resumable above");
4350 }
4351 }
4352 Ok(true)
4353 }
4354
4355 fn add_guest_thread_to_instance_table(
4356 self,
4357 thread_id: TableId<GuestThread>,
4358 store: &mut StoreOpaque,
4359 runtime_instance: RuntimeComponentInstanceIndex,
4360 ) -> Result<u32> {
4361 let (state, counter) =
4362 store.instance_state_and_handle_counter(self.runtime_instance(runtime_instance));
4363 let guest_id = state
4364 .thread_handle_table()
4365 .guest_thread_insert(counter, thread_id.rep())?;
4366 store
4367 .concurrent_state_mut()?
4368 .get_mut(thread_id)?
4369 .instance_rep = Some(guest_id);
4370 Ok(guest_id)
4371 }
4372
4373 pub(crate) fn suspension_intrinsic(
4377 self,
4378 store: &mut StoreOpaque,
4379 caller: RuntimeComponentInstanceIndex,
4380 yielding: bool,
4381 to_thread: SuspensionTarget,
4382 ) -> Result<WaitResult> {
4383 let check_suspend = match to_thread {
4384 SuspensionTarget::Promote(thread) => {
4385 !self.resume_thread(store, caller, thread, ResumeThread::Promote)?
4386 }
4387 SuspensionTarget::Resume(thread) => {
4388 if !self.resume_thread(store, caller, thread, ResumeThread::Resume)? {
4389 bail_bug!(
4390 "`resume_thread` should only ever return false \
4391 when `ResumeThread::Promote` is passed to it"
4392 );
4393 }
4394 false
4395 }
4396 SuspensionTarget::None => true,
4397 };
4398
4399 if check_suspend && !store.switch_if_may_not_suspend(self.runtime_instance(caller))? {
4400 return if yielding {
4401 Ok(WaitResult::Completed)
4402 } else {
4403 Err(Trap::CannotBlockSyncTask.into())
4404 };
4405 }
4406
4407 let guest_thread = store.current_guest_thread()?;
4408
4409 let reason = if yielding {
4410 SuspendReason::Yielding {
4411 thread: guest_thread,
4412 }
4413 } else {
4414 SuspendReason::ExplicitlySuspending {
4415 thread: guest_thread,
4416 }
4417 };
4418
4419 store.suspend(reason)?;
4420
4421 Ok(WaitResult::Completed)
4422 }
4423
4424 fn waitable_check(
4426 self,
4427 store: &mut StoreOpaque,
4428 caller: RuntimeInstance,
4429 check: WaitableCheck,
4430 params: WaitableCheckParams,
4431 ) -> Result<u32> {
4432 let guest_thread = store.current_guest_thread()?;
4433
4434 log::trace!("waitable check for {guest_thread:?}; set {:?}", params.set);
4435
4436 match &check {
4439 WaitableCheck::Wait => {
4440 let set = params.set;
4441
4442 loop {
4447 let state = store.concurrent_state_mut()?;
4448 let task = state.get_mut(guest_thread.task)?;
4449 if !(task.event.is_none() || matches!(task.event, Some(Event::Cancelled)))
4450 || !state.get_mut(set)?.ready.is_empty()
4451 {
4452 break;
4453 }
4454
4455 store.switch_or_trap_if_may_not_suspend(caller)?;
4456
4457 store.suspend(SuspendReason::Waiting {
4458 set,
4459 thread: guest_thread,
4460 })?;
4461 }
4462 }
4463 WaitableCheck::Poll => {}
4464 }
4465
4466 log::trace!(
4467 "waitable check for {guest_thread:?}; set {:?}, part two",
4468 params.set
4469 );
4470
4471 let event = self.get_event(store, guest_thread.task, Some(params.set), false)?;
4473
4474 let (ordinal, handle, result) = match &check {
4475 WaitableCheck::Wait => {
4476 let (event, waitable) = match event {
4477 Some(p) => p,
4478 None => bail_bug!("event expected to be present"),
4479 };
4480 let handle = waitable.map(|(_, v)| v).unwrap_or(0);
4481 let (ordinal, result) = event.parts();
4482 (ordinal, handle, result)
4483 }
4484 WaitableCheck::Poll => {
4485 if let Some((event, waitable)) = event {
4486 let handle = waitable.map(|(_, v)| v).unwrap_or(0);
4487 let (ordinal, result) = event.parts();
4488 (ordinal, handle, result)
4489 } else {
4490 log::trace!(
4491 "no events ready to deliver via waitable-set.poll to {:?}; set {:?}",
4492 guest_thread.task,
4493 params.set
4494 );
4495 let (ordinal, result) = Event::None.parts();
4496 (ordinal, 0, result)
4497 }
4498 }
4499 };
4500 let memory = self.options_memory_mut(store, params.options);
4501 let ptr = crate::component::func::validate_inbounds_dynamic(
4502 &CanonicalAbiInfo::POINTER_PAIR,
4503 memory,
4504 &ValRaw::u32(params.payload),
4505 )?;
4506 memory[ptr + 0..][..4].copy_from_slice(&handle.to_le_bytes());
4507 memory[ptr + 4..][..4].copy_from_slice(&result.to_le_bytes());
4508 Ok(ordinal)
4509 }
4510
4511 pub(crate) fn subtask_cancel(
4513 self,
4514 store: &mut StoreOpaque,
4515 caller_instance: RuntimeComponentInstanceIndex,
4516 async_: bool,
4517 task_id: u32,
4518 ) -> Result<u32> {
4519 let (rep, is_host) = store
4520 .instance_state(self.runtime_instance(caller_instance))
4521 .handle_table()
4522 .subtask_rep(task_id)?;
4523 let waitable = if is_host {
4524 Waitable::Host(TableId::<HostTask>::new(rep))
4525 } else {
4526 Waitable::Guest(TableId::<GuestTask>::new(rep))
4527 };
4528 let concurrent_state = store.concurrent_state_mut()?;
4529
4530 log::trace!("subtask_cancel {waitable:?} (handle {task_id}; async {async_})");
4531
4532 waitable.trap_if_in_waitable_set(concurrent_state)?;
4533
4534 let needs_block;
4535 if let Waitable::Host(host_task) = waitable {
4536 let state = &mut concurrent_state.get_mut(host_task)?.state;
4537 match state {
4538 HostTaskState::CalleeRunning(handle) => {
4545 handle.abort();
4546 *state = HostTaskState::CalleeCancelling;
4547 needs_block = true;
4548 }
4549
4550 HostTaskState::CalleeCancelling | HostTaskState::CalleeDone { cancelled: true } => {
4553 bail!(Trap::SubtaskCancelAfterTerminal);
4554 }
4555 HostTaskState::CalleeDone { cancelled: false } => {
4556 *state = HostTaskState::CalleeDone { cancelled: true };
4559 needs_block = false;
4560 }
4561
4562 HostTaskState::CalleeStarted | HostTaskState::CalleeFinished(_) => {
4565 bail_bug!("invalid states for host callee")
4566 }
4567 }
4568 } else {
4569 let guest_task = TableId::<GuestTask>::new(rep);
4570 let task = concurrent_state.get_mut(guest_task)?;
4571
4572 if task.cancel_requested {
4575 bail!(Trap::SubtaskCancelAfterTerminal);
4576 }
4577
4578 if !task.already_lowered_parameters() {
4579 store.cancel_guest_subtask_without_lowered_parameters(
4580 self.runtime_instance(caller_instance),
4581 guest_task,
4582 )?;
4583 return Ok(Status::StartCancelled as u32);
4584 } else if !task.returned_or_cancelled() {
4585 task.cancel_requested = true;
4592 task.event = Some(Event::Cancelled);
4593 let runtime_instance = task.instance;
4594 for thread in task.threads.clone() {
4595 let thread = QualifiedThreadId {
4596 task: guest_task,
4597 thread,
4598 };
4599 let concurrent_state = store.concurrent_state_mut()?;
4600 let thread_mut = concurrent_state.get_mut(thread.thread)?;
4601
4602 let yield_ = |store: &mut StoreOpaque| {
4603 let state = store.instance_state(runtime_instance).concurrent_state();
4608 let old_do_not_suspend = state.do_not_suspend;
4609 state.do_not_suspend = false;
4610
4611 let caller = store.current_guest_thread()?;
4612
4613 let state = store.concurrent_state_mut()?;
4618 let set = state.get_mut(caller.thread)?.sync_call_set;
4619 waitable.join(state, Some(set))?;
4620
4621 store.suspend(SuspendReason::YieldingToSubtask { thread: caller })?;
4622
4623 let state = store.concurrent_state_mut()?;
4624 waitable.join(state, None)?;
4625
4626 store
4627 .instance_state(runtime_instance)
4628 .concurrent_state()
4629 .do_not_suspend = old_do_not_suspend;
4630
4631 Ok::<(), crate::Error>(())
4632 };
4633
4634 match thread_mut.wake_on_cancel.take() {
4635 WakeOnCancel::Waiting(set) => {
4636 let instance = concurrent_state.take_callback_waiter(set, thread)?;
4638 let item = WorkItem::GuestCall {
4639 instance: runtime_instance,
4640 call: GuestCall {
4641 thread,
4642 kind: GuestCallKind::DeliverEvent {
4643 instance,
4644 set: Some(set),
4645 },
4646 },
4647 };
4648 concurrent_state.set_switch_item(item)?;
4649
4650 yield_(store)?;
4651
4652 break;
4653 }
4654 WakeOnCancel::Yielding => {
4655 if concurrent_state.promote_thread_work_item(thread)? {
4656 yield_(store)?;
4657 break;
4658 } else if store
4659 .instance_state(runtime_instance)
4660 .concurrent_state()
4661 .pending
4662 .contains_key(&thread)
4663 {
4664 store
4674 .concurrent_state_mut()?
4675 .get_mut(thread.thread)?
4676 .wake_on_cancel = WakeOnCancel::Yielding;
4677 } else {
4678 bail_bug!("thread with `WakeOnCancel::Yielding` not promotable");
4679 }
4680 }
4681 WakeOnCancel::None => {}
4682 }
4683 }
4684
4685 needs_block = !store
4688 .concurrent_state_mut()?
4689 .get_mut(guest_task)?
4690 .returned_or_cancelled()
4691 } else {
4692 needs_block = false;
4693 }
4694 };
4695
4696 if needs_block {
4700 if async_ {
4701 return Ok(BLOCKED);
4702 }
4703
4704 let old_next_switch_item = if is_host {
4714 Some(store.concurrent_state_mut()?.save_next_switch_item()?)
4715 } else {
4716 None
4717 };
4718
4719 store.wait_for_event(self.runtime_instance(caller_instance), waitable)?;
4722
4723 if let Some(item) = old_next_switch_item {
4724 let state = store.concurrent_state_mut()?;
4725 state.restore_next_switch_item(item)?;
4726 }
4727
4728 }
4730
4731 let event = waitable.take_event(store.concurrent_state_mut()?)?;
4732 if let Some(Event::Subtask {
4733 status: status @ (Status::Returned | Status::ReturnCancelled),
4734 }) = event
4735 {
4736 Ok(status as u32)
4737 } else {
4738 bail!(Trap::SubtaskCancelAfterTerminal);
4739 }
4740 }
4741}
4742
4743pub trait VMComponentAsyncStore {
4751 unsafe fn prepare_call(
4757 &mut self,
4758 instance: Instance,
4759 memory: *mut VMMemoryDefinition,
4760 start: NonNull<VMFuncRef>,
4761 return_: NonNull<VMFuncRef>,
4762 caller_instance: RuntimeComponentInstanceIndex,
4763 callee_instance: RuntimeComponentInstanceIndex,
4764 task_return_type: TypeTupleIndex,
4765 callee_async: bool,
4766 string_encoding: StringEncoding,
4767 result_count: u32,
4768 storage: *mut ValRaw,
4769 storage_len: usize,
4770 ) -> Result<()>;
4771
4772 unsafe fn start_call(
4775 &mut self,
4776 instance: Instance,
4777 callback: *mut VMFuncRef,
4778 post_return: *mut VMFuncRef,
4779 callee: NonNull<VMFuncRef>,
4780 param_count: u32,
4781 result_count: u32,
4782 flags: u32,
4783 storage: *mut MaybeUninit<ValRaw>,
4784 storage_len: usize,
4785 ) -> Result<()>;
4786
4787 fn future_write(
4789 &mut self,
4790 instance: Instance,
4791 caller: RuntimeComponentInstanceIndex,
4792 ty: TypeFutureTableIndex,
4793 options: OptionsIndex,
4794 future: u32,
4795 address: u32,
4796 ) -> Result<u32>;
4797
4798 fn future_read(
4800 &mut self,
4801 instance: Instance,
4802 caller: RuntimeComponentInstanceIndex,
4803 ty: TypeFutureTableIndex,
4804 options: OptionsIndex,
4805 future: u32,
4806 address: u32,
4807 ) -> Result<u32>;
4808
4809 fn future_drop_writable(
4811 &mut self,
4812 instance: Instance,
4813 ty: TypeFutureTableIndex,
4814 writer: u32,
4815 ) -> Result<()>;
4816
4817 fn stream_write(
4819 &mut self,
4820 instance: Instance,
4821 caller: RuntimeComponentInstanceIndex,
4822 ty: TypeStreamTableIndex,
4823 options: OptionsIndex,
4824 stream: u32,
4825 address: u32,
4826 count: u32,
4827 ) -> Result<u32>;
4828
4829 fn stream_read(
4831 &mut self,
4832 instance: Instance,
4833 caller: RuntimeComponentInstanceIndex,
4834 ty: TypeStreamTableIndex,
4835 options: OptionsIndex,
4836 stream: u32,
4837 address: u32,
4838 count: u32,
4839 ) -> Result<u32>;
4840
4841 fn flat_stream_write(
4844 &mut self,
4845 instance: Instance,
4846 caller: RuntimeComponentInstanceIndex,
4847 ty: TypeStreamTableIndex,
4848 options: OptionsIndex,
4849 payload_size: u32,
4850 payload_align: u32,
4851 stream: u32,
4852 address: u32,
4853 count: u32,
4854 ) -> Result<u32>;
4855
4856 fn flat_stream_read(
4859 &mut self,
4860 instance: Instance,
4861 caller: RuntimeComponentInstanceIndex,
4862 ty: TypeStreamTableIndex,
4863 options: OptionsIndex,
4864 payload_size: u32,
4865 payload_align: u32,
4866 stream: u32,
4867 address: u32,
4868 count: u32,
4869 ) -> Result<u32>;
4870
4871 fn stream_drop_writable(
4873 &mut self,
4874 instance: Instance,
4875 ty: TypeStreamTableIndex,
4876 writer: u32,
4877 ) -> Result<()>;
4878
4879 fn error_context_debug_message(
4881 &mut self,
4882 instance: Instance,
4883 ty: TypeComponentLocalErrorContextTableIndex,
4884 options: OptionsIndex,
4885 err_ctx_handle: u32,
4886 debug_msg_address: u32,
4887 ) -> Result<()>;
4888
4889 fn thread_new_indirect(
4891 &mut self,
4892 instance: Instance,
4893 caller: RuntimeComponentInstanceIndex,
4894 func_ty_idx: ModuleInternedTypeIndex,
4895 start_func_table_idx: RuntimeTableIndex,
4896 start_func_idx: u32,
4897 context: i32,
4898 ) -> Result<u32>;
4899}
4900
4901impl<T: 'static> VMComponentAsyncStore for StoreInner<T> {
4903 unsafe fn prepare_call(
4904 &mut self,
4905 instance: Instance,
4906 memory: *mut VMMemoryDefinition,
4907 start: NonNull<VMFuncRef>,
4908 return_: NonNull<VMFuncRef>,
4909 caller_instance: RuntimeComponentInstanceIndex,
4910 callee_instance: RuntimeComponentInstanceIndex,
4911 task_return_type: TypeTupleIndex,
4912 callee_async: bool,
4913 string_encoding: StringEncoding,
4914 result_count_or_max_if_async: u32,
4915 storage: *mut ValRaw,
4916 storage_len: usize,
4917 ) -> Result<()> {
4918 let params = unsafe { core::slice::from_raw_parts(storage, storage_len) }.to_vec();
4922
4923 unsafe {
4924 instance.prepare_call(
4925 StoreContextMut(self),
4926 start,
4927 return_,
4928 caller_instance,
4929 callee_instance,
4930 task_return_type,
4931 callee_async,
4932 memory,
4933 string_encoding,
4934 match result_count_or_max_if_async {
4935 PREPARE_ASYNC_NO_RESULT => CallerInfo::Async {
4936 params,
4937 has_result: false,
4938 },
4939 PREPARE_ASYNC_WITH_RESULT => CallerInfo::Async {
4940 params,
4941 has_result: true,
4942 },
4943 result_count => CallerInfo::Sync {
4944 params,
4945 result_count,
4946 },
4947 },
4948 )
4949 }
4950 }
4951
4952 unsafe fn start_call(
4953 &mut self,
4954 instance: Instance,
4955 callback: *mut VMFuncRef,
4956 post_return: *mut VMFuncRef,
4957 callee: NonNull<VMFuncRef>,
4958 param_count: u32,
4959 result_count: u32,
4960 flags: u32,
4961 storage: *mut MaybeUninit<ValRaw>,
4962 storage_len: usize,
4963 ) -> Result<()> {
4964 unsafe {
4965 instance.start_call(
4966 StoreContextMut(self),
4967 callback,
4968 post_return,
4969 callee,
4970 param_count,
4971 result_count,
4972 flags,
4973 core::slice::from_raw_parts_mut(storage, storage_len),
4977 )
4978 }
4979 }
4980
4981 fn future_write(
4982 &mut self,
4983 instance: Instance,
4984 caller: RuntimeComponentInstanceIndex,
4985 ty: TypeFutureTableIndex,
4986 options: OptionsIndex,
4987 future: u32,
4988 address: u32,
4989 ) -> Result<u32> {
4990 instance
4991 .guest_write(
4992 StoreContextMut(self),
4993 caller,
4994 TransmitIndex::Future(ty),
4995 options,
4996 None,
4997 future,
4998 address,
4999 1,
5000 )
5001 .map(|result| result.encode())
5002 }
5003
5004 fn future_read(
5005 &mut self,
5006 instance: Instance,
5007 caller: RuntimeComponentInstanceIndex,
5008 ty: TypeFutureTableIndex,
5009 options: OptionsIndex,
5010 future: u32,
5011 address: u32,
5012 ) -> Result<u32> {
5013 instance
5014 .guest_read(
5015 StoreContextMut(self),
5016 caller,
5017 TransmitIndex::Future(ty),
5018 options,
5019 None,
5020 future,
5021 address,
5022 1,
5023 )
5024 .map(|result| result.encode())
5025 }
5026
5027 fn stream_write(
5028 &mut self,
5029 instance: Instance,
5030 caller: RuntimeComponentInstanceIndex,
5031 ty: TypeStreamTableIndex,
5032 options: OptionsIndex,
5033 stream: u32,
5034 address: u32,
5035 count: u32,
5036 ) -> Result<u32> {
5037 instance
5038 .guest_write(
5039 StoreContextMut(self),
5040 caller,
5041 TransmitIndex::Stream(ty),
5042 options,
5043 None,
5044 stream,
5045 address,
5046 count,
5047 )
5048 .map(|result| result.encode())
5049 }
5050
5051 fn stream_read(
5052 &mut self,
5053 instance: Instance,
5054 caller: RuntimeComponentInstanceIndex,
5055 ty: TypeStreamTableIndex,
5056 options: OptionsIndex,
5057 stream: u32,
5058 address: u32,
5059 count: u32,
5060 ) -> Result<u32> {
5061 instance
5062 .guest_read(
5063 StoreContextMut(self),
5064 caller,
5065 TransmitIndex::Stream(ty),
5066 options,
5067 None,
5068 stream,
5069 address,
5070 count,
5071 )
5072 .map(|result| result.encode())
5073 }
5074
5075 fn future_drop_writable(
5076 &mut self,
5077 instance: Instance,
5078 ty: TypeFutureTableIndex,
5079 writer: u32,
5080 ) -> Result<()> {
5081 instance.guest_drop_writable(self, TransmitIndex::Future(ty), writer)
5082 }
5083
5084 fn flat_stream_write(
5085 &mut self,
5086 instance: Instance,
5087 caller: RuntimeComponentInstanceIndex,
5088 ty: TypeStreamTableIndex,
5089 options: OptionsIndex,
5090 payload_size: u32,
5091 payload_align: u32,
5092 stream: u32,
5093 address: u32,
5094 count: u32,
5095 ) -> Result<u32> {
5096 instance
5097 .guest_write(
5098 StoreContextMut(self),
5099 caller,
5100 TransmitIndex::Stream(ty),
5101 options,
5102 Some(FlatAbi {
5103 size: payload_size,
5104 align: payload_align,
5105 }),
5106 stream,
5107 address,
5108 count,
5109 )
5110 .map(|result| result.encode())
5111 }
5112
5113 fn flat_stream_read(
5114 &mut self,
5115 instance: Instance,
5116 caller: RuntimeComponentInstanceIndex,
5117 ty: TypeStreamTableIndex,
5118 options: OptionsIndex,
5119 payload_size: u32,
5120 payload_align: u32,
5121 stream: u32,
5122 address: u32,
5123 count: u32,
5124 ) -> Result<u32> {
5125 instance
5126 .guest_read(
5127 StoreContextMut(self),
5128 caller,
5129 TransmitIndex::Stream(ty),
5130 options,
5131 Some(FlatAbi {
5132 size: payload_size,
5133 align: payload_align,
5134 }),
5135 stream,
5136 address,
5137 count,
5138 )
5139 .map(|result| result.encode())
5140 }
5141
5142 fn stream_drop_writable(
5143 &mut self,
5144 instance: Instance,
5145 ty: TypeStreamTableIndex,
5146 writer: u32,
5147 ) -> Result<()> {
5148 instance.guest_drop_writable(self, TransmitIndex::Stream(ty), writer)
5149 }
5150
5151 fn error_context_debug_message(
5152 &mut self,
5153 instance: Instance,
5154 ty: TypeComponentLocalErrorContextTableIndex,
5155 options: OptionsIndex,
5156 err_ctx_handle: u32,
5157 debug_msg_address: u32,
5158 ) -> Result<()> {
5159 instance.error_context_debug_message(
5160 StoreContextMut(self),
5161 ty,
5162 options,
5163 err_ctx_handle,
5164 debug_msg_address,
5165 )
5166 }
5167
5168 fn thread_new_indirect(
5169 &mut self,
5170 instance: Instance,
5171 caller: RuntimeComponentInstanceIndex,
5172 func_ty_idx: ModuleInternedTypeIndex,
5173 start_func_table_idx: RuntimeTableIndex,
5174 start_func_idx: u32,
5175 context: i32,
5176 ) -> Result<u32> {
5177 instance.thread_new_indirect(
5178 StoreContextMut(self),
5179 caller,
5180 func_ty_idx,
5181 start_func_table_idx,
5182 start_func_idx,
5183 context,
5184 )
5185 }
5186}
5187
5188type HostTaskFuture = Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>;
5189
5190async fn run_with_host_task_set<F>(task: TableId<HostTask>, future: F) -> Result<F::Output>
5193where
5194 F: Future,
5195{
5196 let mut future = pin!(future);
5197 future::poll_fn(|cx| {
5198 let old_thread = match tls::get(|store| store.set_thread(task)) {
5199 Ok(thread) => thread,
5200 Err(error) => return Poll::Ready(Err(error)),
5201 };
5202 let result = future.as_mut().poll(cx);
5203 match tls::get(|store| store.set_thread(old_thread)) {
5204 Ok(_) => result.map(Ok),
5205 Err(error) => Poll::Ready(Err(error)),
5206 }
5207 })
5208 .await
5209}
5210
5211pub(crate) struct HostTask {
5215 common: WaitableCommon,
5216
5217 call_context: CallContext,
5220
5221 state: HostTaskState,
5222
5223 group: TaskGroupId,
5224}
5225
5226enum HostTaskState {
5227 CalleeStarted,
5232
5233 CalleeRunning(JoinHandle),
5238
5239 CalleeCancelling,
5243
5244 CalleeFinished(LiftedResult),
5248
5249 CalleeDone { cancelled: bool },
5252}
5253
5254impl HostTask {
5255 fn new(
5256 concurrent_state: &mut ConcurrentState,
5257 state: HostTaskState,
5258 caller: QualifiedThreadId,
5259 ) -> Result<Self> {
5260 let group = concurrent_state.get_mut(caller.task)?.group;
5261 concurrent_state.increment_group_ref_count(group)?;
5262
5263 Ok(Self {
5264 common: WaitableCommon::default(),
5265 call_context: CallContext::default(),
5266 state,
5267 group,
5268 })
5269 }
5270}
5271
5272impl TableDebug for HostTask {
5273 fn type_name() -> &'static str {
5274 "HostTask"
5275 }
5276}
5277
5278type CallbackFn = Box<dyn Fn(&mut dyn VMStore, Event, u32) -> Result<u32> + Send + Sync + 'static>;
5279
5280enum Caller {
5282 Host {
5284 tx: Option<oneshot::Sender<LiftedResult>>,
5286 caller: Option<TableId<HostTask>>,
5290 },
5291 Guest {
5293 thread: QualifiedThreadId,
5295 },
5296}
5297
5298struct LiftResult {
5301 lift: RawLift,
5302 ty: TypeTupleIndex,
5303 memory: Option<SendSyncPtr<VMMemoryDefinition>>,
5304 string_encoding: StringEncoding,
5305}
5306
5307#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
5312pub(crate) struct QualifiedThreadId {
5313 task: TableId<GuestTask>,
5314 thread: TableId<GuestThread>,
5315}
5316
5317impl QualifiedThreadId {
5318 fn qualify(
5319 state: &mut ConcurrentState,
5320 thread: TableId<GuestThread>,
5321 ) -> Result<QualifiedThreadId> {
5322 Ok(QualifiedThreadId {
5323 task: state.get_mut(thread)?.parent_task,
5324 thread,
5325 })
5326 }
5327}
5328
5329impl fmt::Debug for QualifiedThreadId {
5330 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5331 f.debug_tuple("QualifiedThreadId")
5332 .field(&self.task.rep())
5333 .field(&self.thread.rep())
5334 .finish()
5335 }
5336}
5337
5338enum GuestThreadState {
5339 NotStartedImplicit,
5340 NotStartedExplicit(
5341 Box<dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync>,
5342 ),
5343 Running,
5344 Suspended(StoreFiber<'static>),
5345 Ready {
5346 fiber: StoreFiber<'static>,
5347 },
5348 Completed,
5349}
5350
5351impl GuestThreadState {
5352 fn check_no_fiber(&self) -> Result<()> {
5353 match self {
5354 Self::Suspended(_) | Self::Ready { .. } => bail_bug!("thread already owns a fiber"),
5355 Self::NotStartedImplicit
5356 | Self::NotStartedExplicit(_)
5357 | Self::Running
5358 | Self::Completed => Ok(()),
5359 }
5360 }
5361}
5362
5363impl fmt::Debug for GuestThreadState {
5364 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5365 match self {
5366 Self::NotStartedImplicit => f.debug_tuple("NotStartedImplicit").finish(),
5367 Self::NotStartedExplicit(_) => f.debug_tuple("NotStartedExplicit").finish(),
5368 Self::Running => f.debug_tuple("Running").finish(),
5369 Self::Suspended(_) => f.debug_tuple("Suspended").finish(),
5370 Self::Ready { .. } => f.debug_struct("Ready").finish(),
5371 Self::Completed => f.debug_tuple("Completed").finish(),
5372 }
5373 }
5374}
5375
5376#[derive(Copy, Clone, PartialEq, Eq, Debug)]
5377enum WakeOnCancel {
5378 None,
5379 Waiting(TableId<WaitableSet>),
5380 Yielding,
5381}
5382
5383impl WakeOnCancel {
5384 fn is_none(self) -> bool {
5385 matches!(self, WakeOnCancel::None)
5386 }
5387
5388 fn replace(&mut self, other: WakeOnCancel) -> Self {
5389 let old = *self;
5390 *self = other;
5391 old
5392 }
5393
5394 fn take(&mut self) -> Self {
5395 self.replace(WakeOnCancel::None)
5396 }
5397}
5398
5399pub struct GuestThread {
5400 context: [u32; NUM_COMPONENT_CONTEXT_SLOTS],
5403 parent_task: TableId<GuestTask>,
5405 wake_on_cancel: WakeOnCancel,
5408 state: GuestThreadState,
5410 instance_rep: Option<u32>,
5413 sync_call_set: TableId<WaitableSet>,
5415 old_do_not_suspend: Option<bool>,
5418}
5419
5420impl GuestThread {
5421 fn from_instance(
5424 state: Pin<&mut ComponentInstance>,
5425 caller_instance: RuntimeComponentInstanceIndex,
5426 guest_thread: u32,
5427 ) -> Result<TableId<Self>> {
5428 let rep = state.instance_states().0[caller_instance]
5429 .thread_handle_table()
5430 .guest_thread_rep(guest_thread)?;
5431 Ok(TableId::new(rep))
5432 }
5433
5434 fn new_implicit(state: &mut ConcurrentState, parent_task: TableId<GuestTask>) -> Result<Self> {
5435 let sync_call_set = state.push(WaitableSet {
5436 is_sync_call_set: true,
5437 ..WaitableSet::default()
5438 })?;
5439 Ok(Self {
5440 context: [0; NUM_COMPONENT_CONTEXT_SLOTS],
5441 parent_task,
5442 wake_on_cancel: WakeOnCancel::None,
5443 state: GuestThreadState::NotStartedImplicit,
5444 instance_rep: None,
5445 sync_call_set,
5446 old_do_not_suspend: None,
5447 })
5448 }
5449
5450 fn new_explicit(
5451 state: &mut ConcurrentState,
5452 parent_task: TableId<GuestTask>,
5453 start_func: Box<
5454 dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync,
5455 >,
5456 ) -> Result<Self> {
5457 state.increment_task_ref_count(parent_task)?;
5458 let sync_call_set = state.push(WaitableSet {
5459 is_sync_call_set: true,
5460 ..WaitableSet::default()
5461 })?;
5462 Ok(Self {
5463 context: [0; NUM_COMPONENT_CONTEXT_SLOTS],
5464 parent_task,
5465 wake_on_cancel: WakeOnCancel::None,
5466 state: GuestThreadState::NotStartedExplicit(start_func),
5467 instance_rep: None,
5468 sync_call_set,
5469 old_do_not_suspend: None,
5470 })
5471 }
5472}
5473
5474impl TableDebug for GuestThread {
5475 fn type_name() -> &'static str {
5476 "GuestThread"
5477 }
5478}
5479
5480enum SyncResult {
5481 NotProduced,
5482 Produced(Option<ValRaw>),
5483 Taken,
5484}
5485
5486impl SyncResult {
5487 fn take(&mut self) -> Result<Option<Option<ValRaw>>> {
5488 Ok(match mem::replace(self, SyncResult::Taken) {
5489 SyncResult::NotProduced => None,
5490 SyncResult::Produced(val) => Some(val),
5491 SyncResult::Taken => {
5492 bail_bug!("attempted to take a synchronous result that was already taken")
5493 }
5494 })
5495 }
5496}
5497
5498pub(crate) struct GuestTask {
5500 common: WaitableCommon,
5502 lower_params: Option<RawLower>,
5504 lift_result: Option<LiftResult>,
5506 result: Option<LiftedResult>,
5509 callback: Option<CallbackFn>,
5512 caller: Caller,
5514 call_context: CallContext,
5519 sync_result: SyncResult,
5522 cancel_request_delivered: bool,
5526 cancel_requested: bool,
5531 starting_sent: bool,
5534 instance: RuntimeInstance,
5541 event: Option<Event>,
5543 exited: bool,
5545 threads: HashSet<TableId<GuestThread>>,
5547 async_typed: bool,
5550 async_lifted: bool,
5553 decremented_interesting_task_count: bool,
5556 group: TaskGroupId,
5558 ref_count: usize,
5563}
5564
5565impl GuestTask {
5566 fn already_lowered_parameters(&self) -> bool {
5567 self.lower_params.is_none()
5569 }
5570
5571 fn returned_or_cancelled(&self) -> bool {
5572 self.lift_result.is_none()
5574 }
5575
5576 fn new(
5577 state: &mut ConcurrentState,
5578 lower_params: RawLower,
5579 lift_result: LiftResult,
5580 caller: Caller,
5581 callback: Option<CallbackFn>,
5582 instance: RuntimeInstance,
5583 async_typed: bool,
5584 async_lifted: bool,
5585 ) -> Result<QualifiedThreadId> {
5586 let group = match caller {
5587 Caller::Guest { thread } => {
5588 let group = state.get_mut(thread.task)?.group;
5589 state.increment_group_ref_count(group)?;
5590 group
5591 }
5592 Caller::Host { .. } => state.make_task_group()?,
5593 };
5594
5595 let task = state.push(Self {
5596 common: WaitableCommon::default(),
5597 lower_params: Some(lower_params),
5598 lift_result: Some(lift_result),
5599 result: None,
5600 callback,
5601 caller,
5602 call_context: CallContext::default(),
5603 sync_result: SyncResult::NotProduced,
5604 cancel_request_delivered: false,
5605 cancel_requested: false,
5606 starting_sent: false,
5607 instance,
5608 event: None,
5609 exited: false,
5610 threads: HashSet::new(),
5611 async_typed,
5612 async_lifted,
5613 decremented_interesting_task_count: false,
5614 group,
5615 ref_count: 2,
5618 })?;
5619 let new_thread = GuestThread::new_implicit(state, task)?;
5620 let thread = state.push(new_thread)?;
5621 state.get_mut(task)?.threads.insert(thread);
5622 state.interesting_tasks += 1;
5623 let thread = QualifiedThreadId { task, thread };
5624 log::trace!("new implicit thread {thread:?} for instance {instance:?}");
5625 Ok(thread)
5626 }
5627}
5628
5629impl TableDebug for GuestTask {
5630 fn type_name() -> &'static str {
5631 "GuestTask"
5632 }
5633}
5634
5635#[derive(Default)]
5637struct WaitableCommon {
5638 event: Option<Event>,
5640 set: Option<TableId<WaitableSet>>,
5642 handle: Option<u32>,
5644}
5645
5646#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
5648enum Waitable {
5649 Host(TableId<HostTask>),
5651 Guest(TableId<GuestTask>),
5653 Transmit(TableId<TransmitHandle>),
5655}
5656
5657impl Waitable {
5658 fn from_instance(
5661 state: Pin<&mut ComponentInstance>,
5662 caller_instance: RuntimeComponentInstanceIndex,
5663 waitable: u32,
5664 ) -> Result<Self> {
5665 use crate::runtime::vm::component::Waitable;
5666
5667 let (waitable, kind) = state.instance_states().0[caller_instance]
5668 .handle_table()
5669 .waitable_rep(waitable)?;
5670
5671 Ok(match kind {
5672 Waitable::Subtask { is_host: true } => Self::Host(TableId::new(waitable)),
5673 Waitable::Subtask { is_host: false } => Self::Guest(TableId::new(waitable)),
5674 Waitable::Stream | Waitable::Future => Self::Transmit(TableId::new(waitable)),
5675 })
5676 }
5677
5678 fn rep(&self) -> u32 {
5680 match self {
5681 Self::Host(id) => id.rep(),
5682 Self::Guest(id) => id.rep(),
5683 Self::Transmit(id) => id.rep(),
5684 }
5685 }
5686
5687 fn join(&self, state: &mut ConcurrentState, set: Option<TableId<WaitableSet>>) -> Result<()> {
5691 log::trace!("waitable {self:?} join set {set:?}");
5692
5693 let old = mem::replace(&mut self.common(state)?.set, set);
5694
5695 if let Some(old) = old {
5696 match *self {
5697 Waitable::Host(id) => state.remove_child(id, old),
5698 Waitable::Guest(id) => state.remove_child(id, old),
5699 Waitable::Transmit(id) => state.remove_child(id, old),
5700 }?;
5701
5702 state.get_mut(old)?.ready.remove(self);
5703 }
5704
5705 if let Some(set) = set {
5706 match *self {
5707 Waitable::Host(id) => state.add_child(id, set),
5708 Waitable::Guest(id) => state.add_child(id, set),
5709 Waitable::Transmit(id) => state.add_child(id, set),
5710 }?;
5711
5712 if self.common(state)?.event.is_some() {
5713 self.mark_ready(state)?;
5714 }
5715 }
5716
5717 Ok(())
5718 }
5719
5720 fn common<'a>(&self, state: &'a mut ConcurrentState) -> Result<&'a mut WaitableCommon> {
5722 Ok(match self {
5723 Self::Host(id) => &mut state.get_mut(*id)?.common,
5724 Self::Guest(id) => &mut state.get_mut(*id)?.common,
5725 Self::Transmit(id) => &mut state.get_mut(*id)?.common,
5726 })
5727 }
5728
5729 fn trap_if_in_waitable_set(&self, state: &mut ConcurrentState) -> Result<()> {
5735 if self.common(state)?.set.is_some() {
5736 bail!(Trap::WaitableSyncAndAsync);
5737 }
5738 Ok(())
5739 }
5740
5741 fn trap_if_has_sync_waiter(&self, state: &mut ConcurrentState) -> Result<()> {
5747 if let Some(set) = self.common(state)?.set
5748 && state.get_mut(set)?.is_sync_call_set
5749 {
5750 bail!(Trap::WaitableSyncAndAsync);
5751 }
5752 Ok(())
5753 }
5754
5755 fn set_event(&self, state: &mut ConcurrentState, event: Option<Event>) -> Result<()> {
5759 log::trace!("set event for {self:?}: {event:?}");
5760 self.common(state)?.event = event;
5761 self.mark_ready(state)
5762 }
5763
5764 fn take_event(&self, state: &mut ConcurrentState) -> Result<Option<Event>> {
5766 let common = self.common(state)?;
5767 let event = common.event.take();
5768 if let Some(set) = self.common(state)?.set {
5769 state.get_mut(set)?.ready.remove(self);
5770 }
5771
5772 Ok(event)
5773 }
5774
5775 fn mark_ready(&self, state: &mut ConcurrentState) -> Result<()> {
5779 if let Some(set) = self.common(state)?.set {
5780 state.get_mut(set)?.ready.insert(*self);
5781 state.wake_waiter(set)?;
5782 }
5783 Ok(())
5784 }
5785
5786 fn delete_from(&self, state: &mut ConcurrentState) -> Result<()> {
5789 match self {
5790 Self::Host(task) => state.delete_host_task(*task),
5791 Self::Guest(task) => state.decrement_task_ref_count(*task),
5792 Self::Transmit(task) => Ok(state.delete(*task).map(drop)?),
5793 }
5794 }
5795}
5796
5797impl fmt::Debug for Waitable {
5798 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5799 match self {
5800 Self::Host(id) => write!(f, "{id:?}"),
5801 Self::Guest(id) => write!(f, "{id:?}"),
5802 Self::Transmit(id) => write!(f, "{id:?}"),
5803 }
5804 }
5805}
5806
5807#[derive(Default)]
5809struct WaitableSet {
5810 ready: BTreeSet<Waitable>,
5812 waiting: BTreeMap<QualifiedThreadId, WaitMode>,
5814 num_waiting: usize,
5817 is_sync_call_set: bool,
5820}
5821
5822impl WaitableSet {
5823 fn stop_waiting(&mut self) -> Result<()> {
5825 self.num_waiting = match self.num_waiting.checked_sub(1) {
5826 Some(n) => n,
5827 None => bail_bug!("waiter not accounted for in waitable set"),
5828 };
5829 Ok(())
5830 }
5831}
5832
5833impl TableDebug for WaitableSet {
5834 fn type_name() -> &'static str {
5835 "WaitableSet"
5836 }
5837}
5838
5839type RawLower =
5841 Box<dyn FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync>;
5842
5843type RawLift = Box<
5845 dyn FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
5846>;
5847
5848type LiftedResult = Box<dyn Any + Send + Sync>;
5852
5853struct DummyResult;
5856
5857#[derive(Default)]
5859pub struct ConcurrentInstanceState {
5860 backpressure: u16,
5862 do_not_enter: bool,
5864 do_not_suspend: bool,
5867 pending: BTreeMap<QualifiedThreadId, GuestCallKind>,
5870}
5871
5872impl ConcurrentInstanceState {
5873 pub fn pending_is_empty(&self) -> bool {
5874 self.pending.is_empty()
5875 }
5876}
5877
5878#[derive(Debug, Copy, Clone)]
5879pub(crate) enum CurrentThread {
5880 Guest(QualifiedThreadId),
5883 Host(TableId<HostTask>),
5885 DeferredHost(QualifiedThreadId),
5888 None,
5891}
5892
5893impl CurrentThread {
5894 fn guest(&self) -> Option<&QualifiedThreadId> {
5895 match self {
5896 Self::Guest(id) => Some(id),
5897 _ => None,
5898 }
5899 }
5900
5901 fn guest_task(&self) -> Option<TableId<GuestTask>> {
5902 match self {
5903 Self::Guest(id) => Some(id.task),
5904 _ => None,
5905 }
5906 }
5907
5908 fn is_none(&self) -> bool {
5909 matches!(self, Self::None)
5910 }
5911}
5912
5913impl From<QualifiedThreadId> for CurrentThread {
5914 fn from(id: QualifiedThreadId) -> Self {
5915 Self::Guest(id)
5916 }
5917}
5918
5919impl From<TableId<HostTask>> for CurrentThread {
5920 fn from(id: TableId<HostTask>) -> Self {
5921 Self::Host(id)
5922 }
5923}
5924
5925enum Priority {
5926 Switch,
5927 High,
5928 Low,
5929}
5930
5931pub struct ConcurrentState {
5933 unforced_current_thread: CurrentThread,
5939
5940 deferred_host_call_context: Option<CallContext>,
5946
5947 futures: AlwaysMut<Option<FuturesUnordered<HostTaskFuture>>>,
5952 table: AlwaysMut<ResourceTable>,
5954 switch_item: Option<WorkItem>,
5962 next_switch_item: Option<WorkItem>,
5968 high_priority: VecDeque<WorkItem>,
5970 low_priority: VecDeque<WorkItem>,
5972 suspend_reason: Option<SuspendReason>,
5976 worker: Option<StoreFiber<'static>>,
5980 worker_item: Option<WorkerItem>,
5982
5983 global_error_context_ref_counts:
5996 BTreeMap<TypeComponentGlobalErrorContextTableIndex, GlobalErrorContextRefCount>,
5997
5998 interesting_tasks: usize,
6011
6012 interesting_tasks_empty_waker: Option<Waker>,
6016
6017 ready_for_concurrent_call_waker: Option<Waker>,
6022
6023 event_loop_running: bool,
6025
6026 saved_next_switch_items: Vec<Option<WorkItem>>,
6029
6030 #[cfg(feature = "task-group-hook")]
6032 task_group_hook: Option<Box<dyn TaskGroupHook>>,
6033}
6034
6035impl Default for ConcurrentState {
6036 fn default() -> Self {
6037 Self {
6038 unforced_current_thread: CurrentThread::None,
6039 deferred_host_call_context: None,
6040 table: AlwaysMut::new(ResourceTable::new()),
6041 futures: AlwaysMut::new(Some(FuturesUnordered::new())),
6042 switch_item: None,
6043 next_switch_item: None,
6044 high_priority: VecDeque::new(),
6045 low_priority: VecDeque::new(),
6046 suspend_reason: None,
6047 worker: None,
6048 worker_item: None,
6049 global_error_context_ref_counts: BTreeMap::new(),
6050 interesting_tasks: 0,
6051 interesting_tasks_empty_waker: None,
6052 ready_for_concurrent_call_waker: None,
6053 event_loop_running: false,
6054 saved_next_switch_items: Vec::new(),
6055 #[cfg(feature = "task-group-hook")]
6056 task_group_hook: None,
6057 }
6058 }
6059}
6060
6061impl ConcurrentState {
6062 pub(crate) fn take_fibers_and_futures(
6079 &mut self,
6080 fibers: &mut Vec<StoreFiber<'static>>,
6081 futures: &mut Vec<FuturesUnordered<HostTaskFuture>>,
6082 ) {
6083 let ConcurrentState {
6084 table,
6085 worker,
6086 switch_item,
6087 next_switch_item,
6088 high_priority,
6089 low_priority,
6090 saved_next_switch_items,
6091 futures: pending_futures,
6092 worker_item: _,
6093 unforced_current_thread: _,
6094 deferred_host_call_context: _,
6095 suspend_reason: _,
6096 global_error_context_ref_counts: _,
6097 interesting_tasks: _,
6098 interesting_tasks_empty_waker: _,
6099 ready_for_concurrent_call_waker: _,
6100 event_loop_running: _,
6101 #[cfg(feature = "task-group-hook")]
6102 task_group_hook: _,
6103 } = self;
6104
6105 let mut items = Vec::new();
6106 for (_, entry) in table.get_mut().iter_mut() {
6107 if let Some(set) = entry.downcast_mut::<WaitableSet>() {
6108 for mode in mem::take(&mut set.waiting).into_values() {
6109 match mode {
6110 WaitMode::Fiber(fiber) => {
6111 fibers.push(fiber);
6112 }
6113 WaitMode::Callback(_) => {}
6114 }
6115 }
6116 } else if let Some(thread) = entry.downcast_mut::<GuestThread>() {
6117 match mem::replace(&mut thread.state, GuestThreadState::Completed) {
6118 GuestThreadState::Suspended(fiber) | GuestThreadState::Ready { fiber } => {
6119 fibers.push(fiber);
6120 }
6121 GuestThreadState::NotStartedImplicit
6122 | GuestThreadState::NotStartedExplicit(_)
6123 | GuestThreadState::Running
6124 | GuestThreadState::Completed => {}
6125 }
6126 } else if let Some(item) = entry.downcast_mut::<Option<WorkItem>>() {
6127 if let Some(item) = item.take() {
6128 items.push(item);
6129 }
6130 }
6131 }
6132
6133 if let Some(fiber) = worker.take() {
6134 fibers.push(fiber);
6135 }
6136
6137 let mut handle_item = |item| match item {
6138 WorkItem::ResumeFiber { fiber, .. } => {
6139 fibers.push(fiber);
6140 }
6141 WorkItem::PushFuture(future) => {
6142 pending_futures
6143 .get_mut()
6144 .as_mut()
6145 .unwrap()
6146 .push(future.into_inner());
6147 }
6148 WorkItem::ResumeThread { .. }
6149 | WorkItem::GuestCall { .. }
6150 | WorkItem::WorkerFunction(_) => {}
6151 };
6152
6153 for item in items {
6154 handle_item(item);
6155 }
6156 if let Some(item) = switch_item.take() {
6157 handle_item(item);
6158 }
6159 if let Some(item) = next_switch_item.take() {
6160 handle_item(item);
6161 }
6162 for item in mem::take(high_priority) {
6163 handle_item(item);
6164 }
6165 for item in mem::take(low_priority) {
6166 handle_item(item);
6167 }
6168 for item in mem::take(saved_next_switch_items)
6169 .into_iter()
6170 .filter_map(|v| v)
6171 {
6172 handle_item(item);
6173 }
6174
6175 if let Some(them) = pending_futures.get_mut().take() {
6176 futures.push(them);
6177 }
6178 }
6179
6180 #[cfg(feature = "gc")]
6181 pub(crate) fn trace_fiber_roots(
6182 &mut self,
6183 modules: &ModuleRegistry,
6184 unwind: &dyn Unwind,
6185 gc_roots_list: &mut GcRootsList,
6186 ) {
6187 let ConcurrentState {
6188 table,
6189 worker,
6190 switch_item,
6191 next_switch_item,
6192 high_priority,
6193 low_priority,
6194 saved_next_switch_items,
6195
6196 futures: _,
6200
6201 worker_item: _,
6203 unforced_current_thread: _,
6204 deferred_host_call_context: _,
6205 suspend_reason: _,
6206 global_error_context_ref_counts: _,
6207 interesting_tasks: _,
6208 interesting_tasks_empty_waker: _,
6209 ready_for_concurrent_call_waker: _,
6210 event_loop_running: _,
6211 #[cfg(feature = "task-group-hook")]
6212 task_group_hook: _,
6213 } = self;
6214
6215 for (_, entry) in table.get_mut().iter_mut() {
6216 if let Some(set) = entry.downcast_mut::<WaitableSet>() {
6217 for mode in set.waiting.values_mut() {
6218 match mode {
6219 WaitMode::Fiber(fiber) => {
6220 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6221 }
6222 WaitMode::Callback(_) => {}
6223 }
6224 }
6225 } else if let Some(thread) = entry.downcast_mut::<GuestThread>() {
6226 match &mut thread.state {
6227 GuestThreadState::Suspended(fiber) | GuestThreadState::Ready { fiber } => {
6228 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6229 }
6230 GuestThreadState::NotStartedImplicit
6231 | GuestThreadState::NotStartedExplicit(_)
6232 | GuestThreadState::Running
6233 | GuestThreadState::Completed => {}
6234 }
6235 } else if let Some(Some(WorkItem::ResumeFiber { fiber, .. })) =
6236 entry.downcast_mut::<Option<WorkItem>>()
6237 {
6238 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6239 }
6240 }
6241
6242 if let Some(fiber) = worker {
6243 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6244 }
6245
6246 let mut handle_item = |item: &mut WorkItem| match item {
6247 WorkItem::ResumeFiber { fiber, .. } => {
6248 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6249 }
6250 WorkItem::PushFuture(_future) => {
6251 }
6254 WorkItem::ResumeThread { .. }
6255 | WorkItem::GuestCall { .. }
6256 | WorkItem::WorkerFunction(_) => {}
6257 };
6258
6259 if let Some(item) = switch_item {
6260 handle_item(item);
6261 }
6262 if let Some(item) = next_switch_item {
6263 handle_item(item);
6264 }
6265 for item in high_priority {
6266 handle_item(item);
6267 }
6268 for item in low_priority {
6269 handle_item(item);
6270 }
6271 for item in saved_next_switch_items
6272 .iter_mut()
6273 .filter_map(|v| v.as_mut())
6274 {
6275 handle_item(item);
6276 }
6277 }
6278
6279 fn schedule_suspended_thread(
6280 &mut self,
6281 thread: QualifiedThreadId,
6282 instance: RuntimeInstance,
6283 priority: Priority,
6284 ) -> Result<()> {
6285 if matches!(priority, Priority::Switch) && self.switch_item.is_some() {
6287 bail_bug!("switch item already set");
6288 }
6289 let slot = &mut self.get_mut(thread.thread)?.state;
6290 if !matches!(slot, GuestThreadState::Suspended(_)) {
6291 bail!(Trap::CannotResumeThread);
6292 }
6293 let GuestThreadState::Suspended(fiber) = mem::replace(slot, GuestThreadState::Running)
6294 else {
6295 unreachable!()
6296 };
6297 let item = WorkItem::ResumeFiber {
6298 instance,
6299 thread,
6300 fiber,
6301 };
6302 match priority {
6303 Priority::Switch => self.switch_item = Some(item),
6304 Priority::High => self.push_high_priority(item),
6305 Priority::Low => self.push_low_priority(item),
6306 }
6307 Ok(())
6308 }
6309
6310 fn set_thread_running(&mut self, thread: TableId<GuestThread>) -> Result<()> {
6311 let slot = &mut self.get_mut(thread)?.state;
6312 slot.check_no_fiber()?;
6313 *slot = GuestThreadState::Running;
6314 Ok(())
6315 }
6316
6317 fn save_next_switch_item(&mut self) -> Result<TableId<Option<WorkItem>>> {
6318 let saved = self.push(None::<WorkItem>)?;
6321 let slot = self.table.get_mut().get_mut(&Resource::from(saved))?;
6322 *slot = self.next_switch_item.take();
6323 Ok(saved)
6324 }
6325
6326 fn restore_next_switch_item(&mut self, saved: TableId<Option<WorkItem>>) -> Result<()> {
6327 if self.next_switch_item.is_some() {
6328 bail_bug!("next switch item already set when restoring");
6329 }
6330 self.next_switch_item = self.delete(saved)?;
6331 Ok(())
6332 }
6333
6334 fn take_callback_waiter(
6335 &mut self,
6336 set: TableId<WaitableSet>,
6337 thread: QualifiedThreadId,
6338 ) -> Result<Instance> {
6339 let waiting = &mut self.get_mut(set)?.waiting;
6340 let instance = match waiting.get(&thread) {
6341 Some(WaitMode::Callback(instance)) => *instance,
6342 other => bail_bug!("expected `Some(WaitMode::Callback(_))`; got `{other:?}`"),
6343 };
6344 waiting.remove(&thread);
6345 Ok(instance)
6346 }
6347
6348 fn push<V: Send + Sync + 'static>(
6349 &mut self,
6350 value: V,
6351 ) -> Result<TableId<V>, ResourceTableError> {
6352 self.table.get_mut().push(value).map(TableId::from)
6353 }
6354
6355 fn get_mut<V: 'static>(&mut self, id: TableId<V>) -> Result<&mut V, ResourceTableError> {
6356 self.table.get_mut().get_mut(&Resource::from(id))
6357 }
6358
6359 pub fn add_child<T: 'static, U: 'static>(
6360 &mut self,
6361 child: TableId<T>,
6362 parent: TableId<U>,
6363 ) -> Result<(), ResourceTableError> {
6364 self.table
6365 .get_mut()
6366 .add_child(Resource::from(child), Resource::from(parent))
6367 }
6368
6369 pub fn remove_child<T: 'static, U: 'static>(
6370 &mut self,
6371 child: TableId<T>,
6372 parent: TableId<U>,
6373 ) -> Result<(), ResourceTableError> {
6374 self.table
6375 .get_mut()
6376 .remove_child(Resource::from(child), Resource::from(parent))
6377 }
6378
6379 fn delete<V: 'static>(&mut self, id: TableId<V>) -> Result<V, ResourceTableError> {
6380 self.table.get_mut().delete(Resource::from(id))
6381 }
6382
6383 fn push_future(&mut self, future: HostTaskFuture) {
6384 self.push_high_priority(WorkItem::PushFuture(AlwaysMut::new(future)));
6391 }
6392
6393 fn set_switch_item(&mut self, item: WorkItem) -> Result<()> {
6394 if self.switch_item.is_some() {
6395 self.push_high_priority(item);
6398 bail_bug!("switch item already set");
6399 }
6400
6401 self.switch_item = Some(item);
6402 log::trace!("set switch item: {:?}", self.switch_item.as_ref().unwrap());
6403
6404 Ok(())
6405 }
6406
6407 fn take_next_switch_item(&mut self) -> Result<()> {
6408 if let Some(item) = self.next_switch_item.take() {
6409 self.set_switch_item(item)?;
6410 }
6411 Ok(())
6412 }
6413
6414 fn wake_waiter(&mut self, set: TableId<WaitableSet>) -> Result<()> {
6417 let Some((&thread, _)) = self.get_mut(set)?.waiting.first_key_value() else {
6420 return Ok(());
6421 };
6422 let wake_on_cancel = self.get_mut(thread.thread)?.wake_on_cancel;
6423 if wake_on_cancel != WakeOnCancel::None && wake_on_cancel != WakeOnCancel::Waiting(set) {
6424 bail_bug!("thread {thread:?} has unexpected wake_on_cancel value {wake_on_cancel:?}");
6425 }
6426 let instance = self.get_mut(thread.task)?.instance;
6427 self.get_mut(thread.thread)?.wake_on_cancel.take();
6428 let (_, mode) = self.get_mut(set)?.waiting.pop_first().unwrap();
6429
6430 let item = match mode {
6431 WaitMode::Fiber(fiber) => WorkItem::ResumeFiber {
6432 instance,
6433 thread,
6434 fiber,
6435 },
6436 WaitMode::Callback(callback_instance) => WorkItem::GuestCall {
6437 instance,
6438 call: GuestCall {
6439 thread,
6440 kind: GuestCallKind::DeliverEvent {
6441 instance: callback_instance,
6442 set: Some(set),
6443 },
6444 },
6445 },
6446 };
6447 self.push_high_priority(item);
6448 Ok(())
6449 }
6450
6451 fn push_high_priority(&mut self, item: WorkItem) {
6452 self.high_priority.push_front(item);
6453 log::trace!(
6454 "push high priority: {:?}",
6455 self.high_priority.front().unwrap()
6456 );
6457 }
6458
6459 fn push_low_priority(&mut self, item: WorkItem) {
6460 self.low_priority.push_front(item);
6461 log::trace!(
6462 "push low priority: {:?}",
6463 self.low_priority.front().unwrap()
6464 );
6465 }
6466
6467 fn push_work_item(&mut self, item: WorkItem, priority: Priority) -> Result<()> {
6468 match priority {
6469 Priority::Switch => self.set_switch_item(item)?,
6470 Priority::High => self.push_high_priority(item),
6471 Priority::Low => self.push_low_priority(item),
6472 }
6473
6474 Ok(())
6475 }
6476
6477 fn promote_instance_local_thread_work_item(
6478 &mut self,
6479 current_instance: RuntimeInstance,
6480 ) -> Result<bool> {
6481 log::trace!("promote thread work items for {current_instance:?}");
6482
6483 self.promote_work_item_matching(|item: &WorkItem| {
6484 let result = match item {
6485 WorkItem::ResumeThread { instance, .. }
6486 | WorkItem::ResumeFiber { instance, .. }
6487 | WorkItem::GuestCall { instance, .. } => *instance == current_instance,
6488 _ => false,
6489 };
6490
6491 log::trace!("candidate {item:?}: {result}");
6492 result
6493 })
6494 }
6495
6496 fn promote_thread_work_item(&mut self, thread: QualifiedThreadId) -> Result<bool> {
6497 self.promote_work_item_matching(|item: &WorkItem| match item {
6498 WorkItem::ResumeThread {
6499 thread: item_thread,
6500 ..
6501 }
6502 | WorkItem::GuestCall {
6503 call:
6504 GuestCall {
6505 thread: item_thread,
6506 ..
6507 },
6508 ..
6509 } => *item_thread == thread,
6510 _ => false,
6511 })
6512 }
6513
6514 fn promote_work_item_matching<F>(&mut self, mut predicate: F) -> Result<bool>
6515 where
6516 F: FnMut(&WorkItem) -> bool,
6517 {
6518 if self.switch_item.is_none() {
6525 if let Some(index) = self.high_priority.iter().rposition(&mut predicate) {
6526 self.switch_item = self.high_priority.remove(index);
6527 }
6528 }
6529 if self.switch_item.is_none() {
6530 if let Some(index) = self.low_priority.iter().rposition(predicate) {
6531 self.switch_item = self.low_priority.remove(index);
6532 }
6533 }
6534 Ok(self.switch_item.is_some())
6535 }
6536
6537 pub fn call_context(&mut self, task: Scope) -> Result<&mut CallContext> {
6540 match task {
6541 Scope::HostId(task) => {
6542 let task: TableId<HostTask> = TableId::new(task);
6543 Ok(&mut self.get_mut(task)?.call_context)
6544 }
6545 Scope::Id(task) => {
6546 let task: TableId<GuestTask> = TableId::new(task);
6547 Ok(&mut self.get_mut(task)?.call_context)
6548 }
6549 }
6550 }
6551
6552 pub(crate) fn deferred_host_call_context(&mut self) -> Option<&mut CallContext> {
6553 self.deferred_host_call_context.as_mut()
6554 }
6555
6556 fn futures_mut(&mut self) -> Result<&mut FuturesUnordered<HostTaskFuture>> {
6557 match self.futures.get_mut().as_mut() {
6558 Some(f) => Ok(f),
6559 None => bail_bug!("futures field of concurrent state is currently taken"),
6560 }
6561 }
6562
6563 pub(crate) fn table(&mut self) -> &mut ResourceTable {
6564 self.table.get_mut()
6565 }
6566
6567 fn debug_assert_deferred_host_invariant(&self) {
6568 debug_assert_eq!(
6569 self.deferred_host_call_context.is_some(),
6570 matches!(self.unforced_current_thread, CurrentThread::DeferredHost(_)),
6571 "a deferred host thread and call context must exist together",
6572 );
6573 }
6574
6575 fn materialize_host_task(&mut self) -> Result<CurrentThread> {
6576 self.debug_assert_deferred_host_invariant();
6577 let caller = match self.unforced_current_thread {
6578 CurrentThread::DeferredHost(caller) => caller,
6579 thread => return Ok(thread),
6580 };
6581
6582 let task = HostTask::new(self, HostTaskState::CalleeStarted, caller)?;
6584 let task = self.push(task)?;
6585 let call_context = self
6586 .deferred_host_call_context
6587 .take()
6588 .expect("deferred host call context should be present");
6589 self.get_mut(task)
6590 .expect("newly inserted host task should be present")
6591 .call_context = call_context;
6592 self.unforced_current_thread = CurrentThread::Host(task);
6593 self.debug_assert_deferred_host_invariant();
6594 log::trace!("new host task materialized {task:?}");
6595 Ok(CurrentThread::Host(task))
6596 }
6597
6598 fn materialize_current_host_task_id(&mut self) -> Result<Option<TableId<HostTask>>> {
6599 match self.materialize_host_task()? {
6600 CurrentThread::Host(id) => Ok(Some(id)),
6601 CurrentThread::None => Ok(None),
6602 CurrentThread::Guest(_) => {
6603 bail_bug!("tried to materialize a host task id from a guest thread")
6604 }
6605 CurrentThread::DeferredHost(_) => {
6606 bail_bug!(
6607 "current thread is a deferred host thread which should have been materialized"
6608 )
6609 }
6610 }
6611 }
6612
6613 pub(crate) fn materialize_current_scope(&mut self) -> Result<Scope> {
6614 match self.materialize_host_task()? {
6615 CurrentThread::Host(id) => Ok(Scope::HostId(id.rep())),
6616 _ => bail_bug!("current scope is not a deferred host scope"),
6617 }
6618 }
6619
6620 fn increment_task_ref_count(&mut self, task: TableId<GuestTask>) -> Result<()> {
6621 let count = &mut self.get_mut(task)?.ref_count;
6622 *count += 1;
6623 log::trace!("increment {task:?} to {count}");
6624 Ok(())
6625 }
6626
6627 fn decrement_task_ref_count(&mut self, task: TableId<GuestTask>) -> Result<()> {
6628 let count = &mut self.get_mut(task)?.ref_count;
6629 if *count == 0 {
6630 bail_bug!("can't decrement task ref count that's already zero");
6631 }
6632 *count -= 1;
6633 log::trace!("decrement {task:?} to {count}");
6634 if *count == 0 {
6635 let task = self.delete(task)?;
6636
6637 self.decrement_group_ref_count(task.group)?;
6638
6639 debug_assert!(task.decremented_interesting_task_count);
6646 }
6647 Ok(())
6648 }
6649
6650 fn delete_host_task(&mut self, task: TableId<HostTask>) -> Result<()> {
6651 log::trace!("delete host task {task:?}");
6652 let task = self.delete(task)?;
6653
6654 self.decrement_group_ref_count(task.group)
6655 }
6656}
6657
6658fn for_any_lower<
6661 F: FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync,
6662>(
6663 fun: F,
6664) -> F {
6665 fun
6666}
6667
6668fn for_any_lift<
6670 F: FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
6671>(
6672 fun: F,
6673) -> F {
6674 fun
6675}
6676
6677fn check_ambient_store(id: StoreId) {
6678 let message = "\
6679 `Future`s which depend on asynchronous component tasks, streams, or \
6680 futures to complete may only be polled from the event loop of the \
6681 store to which they belong. Please use \
6682 `StoreContextMut::{run_concurrent,spawn}` to poll or await them.\
6683 ";
6684 tls::try_get(|store| {
6685 let matched = match store {
6686 tls::TryGet::Some(store) => store.id() == id,
6687 tls::TryGet::Taken | tls::TryGet::None => false,
6688 };
6689
6690 if !matched {
6691 panic!("{message}")
6692 }
6693 });
6694}
6695
6696fn unpack_callback_code(code: u32) -> (u32, u32) {
6697 (code & 0xF, code >> 4)
6698}
6699
6700struct WaitableCheckParams {
6704 set: TableId<WaitableSet>,
6705 options: OptionsIndex,
6706 payload: u32,
6707}
6708
6709enum WaitableCheck {
6712 Wait,
6713 Poll,
6714}
6715
6716pub(crate) struct PreparedCall<R> {
6718 handle: Func,
6720 thread: QualifiedThreadId,
6722 param_count: usize,
6724 rx: oneshot::Receiver<LiftedResult>,
6727 _phantom: PhantomData<R>,
6728}
6729
6730impl<R> PreparedCall<R> {
6731 pub(crate) fn acquire_task_id(&self, store: &mut StoreOpaque) -> Result<TaskId> {
6738 store
6739 .concurrent_state_mut()?
6740 .increment_task_ref_count(self.thread.task)?;
6741
6742 Ok(TaskId {
6743 task: self.thread.task,
6744 })
6745 }
6746}
6747
6748pub(crate) struct TaskId {
6750 task: TableId<GuestTask>,
6751}
6752
6753impl TaskId {
6754 pub(crate) fn host_future_dropped(&self, store: &mut StoreOpaque) -> Result<()> {
6766 let task = store.concurrent_state_mut()?.get_mut(self.task)?;
6767 if !task.already_lowered_parameters() {
6768 task.lower_params = Some(Box::new(|store, _| {
6773 store.set_trapped();
6774 bail!("the host future for this call was dropped before it started")
6775 }));
6776 } else {
6777 _ = store
6782 .concurrent_state_mut()?
6783 .decrement_task_ref_count(self.task);
6784 }
6785
6786 Ok(())
6787 }
6788}
6789
6790pub(crate) fn prepare_call<T, R>(
6796 mut store: StoreContextMut<T>,
6797 handle: Func,
6798 param_count: usize,
6799 lower_params: impl FnOnce(StoreContextMut<T>, &mut [MaybeUninit<ValRaw>]) -> Result<()>
6800 + Send
6801 + Sync
6802 + 'static,
6803 lift_result: impl FnOnce(&mut StoreOpaque, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>>
6804 + Send
6805 + Sync
6806 + 'static,
6807) -> Result<PreparedCall<R>> {
6808 if !store.0.may_enter() {
6809 bail!(Trap::CannotEnterComponent);
6810 }
6811
6812 let (options, _flags, ty, raw_options) = handle.abi_info(store.0);
6813
6814 let instance = handle.instance().id().get(store.0);
6815 let options = &instance.component().env_component().options[options];
6816 let ty = &instance.component().types()[ty];
6817 let async_typed = ty.async_;
6818 let async_lifted = raw_options.async_;
6819 let task_return_type = ty.results;
6820 let component_instance = raw_options.instance;
6821 let callback = options.callback.map(|i| instance.runtime_callback(i));
6822 let memory = options
6823 .memory()
6824 .map(|i| instance.runtime_memory(i))
6825 .map(SendSyncPtr::new);
6826 let string_encoding = options.string_encoding;
6827 let token = StoreToken::new(store.as_context_mut());
6828 let caller = store.0.materialize_host_task_id()?;
6829 let state = store.0.concurrent_state_mut()?;
6830
6831 let (tx, rx) = oneshot::channel();
6832
6833 let instance = handle.instance().runtime_instance(component_instance);
6834 let thread = GuestTask::new(
6835 state,
6836 Box::new(for_any_lower(move |store, params| {
6837 lower_params(token.as_context_mut(store), params)
6838 })),
6839 LiftResult {
6840 lift: Box::new(for_any_lift(move |store, result| {
6841 lift_result(store, result)
6842 })),
6843 ty: task_return_type,
6844 memory,
6845 string_encoding,
6846 },
6847 Caller::Host {
6848 tx: Some(tx),
6849 caller,
6850 },
6851 callback.map(|callback| {
6852 let callback = SendSyncPtr::new(callback);
6853 let instance = handle.instance();
6854 Box::new(move |store: &mut dyn VMStore, event, handle| {
6855 let store = token.as_context_mut(store);
6856 unsafe { instance.call_callback(store, callback, event, handle) }
6859 }) as CallbackFn
6860 }),
6861 instance,
6862 async_typed,
6863 async_lifted,
6864 )?;
6865
6866 Ok(PreparedCall {
6867 handle,
6868 thread,
6869 param_count,
6870 rx,
6871 _phantom: PhantomData,
6872 })
6873}
6874
6875pub(crate) struct StagedCall<R> {
6876 store: StoreId,
6877 rx: oneshot::Receiver<LiftedResult>,
6878 _marker: PhantomData<fn() -> R>,
6879 group: TaskGroupId,
6887}
6888
6889impl<R> StagedCall<R> {
6890 pub(crate) fn new<T: 'static>(
6901 mut store: StoreContextMut<T>,
6902 prepared: PreparedCall<R>,
6903 ) -> Result<StagedCall<R>> {
6904 let PreparedCall {
6905 handle,
6906 thread,
6907 param_count,
6908 rx,
6909 ..
6910 } = prepared;
6911
6912 stage_call0(store.as_context_mut(), handle, thread, param_count)?;
6913
6914 let state = store.0.concurrent_state_mut()?;
6915 let group = state.get_mut(thread.task)?.group;
6916 state.decrement_task_ref_count(thread.task)?;
6917
6918 Ok(StagedCall {
6919 store: store.0.id(),
6920 rx,
6921 _marker: PhantomData,
6922 group,
6923 })
6924 }
6925}
6926
6927impl<R> Future for StagedCall<R>
6928where
6929 R: 'static,
6930{
6931 type Output = Result<R>;
6932
6933 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
6934 check_ambient_store(self.store);
6935 Pin::new(&mut self.rx).poll(cx).map(|result| match result {
6936 Ok(r) => match r.downcast() {
6937 Ok(r) => Ok(*r),
6938 Err(_) => bail_bug!("wrong type of value produced"),
6939 },
6940 Err(oneshot::Canceled) => bail_bug!("channel erroneously dropped"),
6941 })
6942 }
6943}
6944
6945fn stage_call0<T: 'static>(
6948 store: StoreContextMut<T>,
6949 handle: Func,
6950 guest_thread: QualifiedThreadId,
6951 param_count: usize,
6952) -> Result<()> {
6953 let (_options, _, _ty, raw_options) = handle.abi_info(store.0);
6954 let is_concurrent = raw_options.async_;
6955 let callback = raw_options.callback;
6956 let instance = handle.instance();
6957 let callee = handle.lifted_core_func(store.0);
6958 let post_return = raw_options
6959 .post_return
6960 .map(|i| instance.id().get(store.0).runtime_post_return(i));
6961 let callback = callback.map(|i| {
6962 let instance = instance.id().get(store.0);
6963 SendSyncPtr::new(instance.runtime_callback(i))
6964 });
6965
6966 log::trace!("queueing call {guest_thread:?}");
6967
6968 unsafe {
6972 instance.stage_call(
6973 store,
6974 guest_thread,
6975 SendSyncPtr::new(callee),
6976 param_count,
6977 1,
6978 is_concurrent,
6979 callback,
6980 post_return.map(SendSyncPtr::new),
6981 true,
6982 )
6983 }
6984}
6985
6986#[cfg(all(test, feature = "cranelift", feature = "wat"))]
6987mod tests {
6988 use super::*;
6989 use crate::component::{Component, Linker};
6990 use crate::store::AsStoreOpaque;
6991 use crate::{Config, Engine};
6992
6993 fn host_subtask(
6994 state: HostTaskState,
6995 event: Option<Event>,
6996 ) -> Result<(Store<()>, Instance, TableId<HostTask>, u32)> {
6997 let mut config = Config::new();
6998 config.wasm_component_model_async(true);
6999 let engine = Engine::new(&config)?;
7000 let component = Component::new(&engine, "(component)")?;
7001 let mut store = Store::new(&engine, ());
7002 let instance = Linker::new(&engine).instantiate(&mut store, &component)?;
7003 let store_opaque = store.as_store_opaque();
7004 let concurrent_state = store_opaque.concurrent_state_mut()?;
7005 let group = concurrent_state.make_task_group()?;
7008 let task = concurrent_state.push(HostTask {
7009 common: WaitableCommon::default(),
7010 call_context: CallContext::default(),
7011 state,
7012 group,
7013 })?;
7014 let (state, counter) = store_opaque.instance_state_and_handle_counter(
7015 instance.runtime_instance(RuntimeComponentInstanceIndex::from_u32(0)),
7016 );
7017 let handle = state
7018 .handle_table()
7019 .subtask_insert_host(counter, task.rep())?;
7020 let common = &mut store_opaque.concurrent_state_mut()?.get_mut(task)?.common;
7021 common.handle = Some(handle);
7022 common.event = event;
7023 Ok((store, instance, task, handle))
7024 }
7025
7026 #[test]
7027 fn host_subtask_drop_during_cancellation() -> Result<()> {
7028 for abort_completed in [false, true] {
7029 let (handle, future) = JoinHandle::run(future::pending::<()>());
7030 let mut future = pin!(future);
7031 let (mut store, instance, task, handle) =
7032 host_subtask(HostTaskState::CalleeRunning(handle), None)?;
7033 let store = store.as_store_opaque();
7034 let caller = RuntimeComponentInstanceIndex::from_u32(0);
7035 assert_eq!(
7036 instance.subtask_cancel(store, caller, true, handle)?,
7037 BLOCKED
7038 );
7039 if abort_completed {
7040 assert!(matches!(
7043 future
7044 .as_mut()
7045 .poll(&mut Context::from_waker(Waker::noop())),
7046 Poll::Ready(None),
7047 ));
7048 }
7049 for async_ in [false, true] {
7050 let err = instance
7051 .subtask_cancel(store, caller, async_, handle)
7052 .unwrap_err();
7053 assert_eq!(err.downcast::<Trap>()?, Trap::SubtaskCancelAfterTerminal);
7054 }
7055 let err = instance.subtask_drop(store, caller, handle).unwrap_err();
7056 assert_eq!(err.downcast::<Trap>()?, Trap::SubtaskDropNotResolved);
7057 assert!(store.concurrent_state_mut()?.get_mut(task).is_ok());
7058 }
7059 Ok(())
7060 }
7061
7062 #[test]
7063 fn host_subtask_cancel_after_completion() -> Result<()> {
7064 for async_ in [false, true] {
7065 let (mut store, instance, task, handle) = host_subtask(
7066 HostTaskState::CalleeDone { cancelled: false },
7067 Some(Event::Subtask {
7068 status: Status::Returned,
7069 }),
7070 )?;
7071 let store = store.as_store_opaque();
7072 let caller = RuntimeComponentInstanceIndex::from_u32(0);
7073 assert_eq!(
7074 instance.subtask_cancel(store, caller, async_, handle)?,
7075 Status::Returned as u32,
7076 );
7077 let err = instance
7078 .subtask_cancel(store, caller, async_, handle)
7079 .unwrap_err();
7080 assert_eq!(err.downcast::<Trap>()?, Trap::SubtaskCancelAfterTerminal);
7081 instance.subtask_drop(store, caller, handle)?;
7082 assert!(store.concurrent_state_mut()?.get_mut(task).is_err());
7083 }
7084 Ok(())
7085 }
7086
7087 #[test]
7088 fn host_subtask_drop_requires_terminal_event_delivery() -> Result<()> {
7089 for (cancelled, status) in [
7090 (false, Status::Returned),
7091 (true, Status::Returned),
7092 (true, Status::ReturnCancelled),
7093 ] {
7094 for delivered in [false, true] {
7095 let event = if delivered {
7096 None
7097 } else {
7098 Some(Event::Subtask { status })
7099 };
7100 let (mut store, instance, task, handle) =
7101 host_subtask(HostTaskState::CalleeDone { cancelled }, event)?;
7102 let store = store.as_store_opaque();
7103 let result = instance.subtask_drop(
7104 store,
7105 RuntimeComponentInstanceIndex::from_u32(0),
7106 handle,
7107 );
7108 if delivered {
7109 result?;
7110 assert!(store.concurrent_state_mut()?.get_mut(task).is_err());
7111 } else {
7112 let err = result.unwrap_err();
7113 assert_eq!(err.downcast::<Trap>()?, Trap::SubtaskDropNotResolved);
7114 assert!(store.concurrent_state_mut()?.get_mut(task).is_ok());
7115 }
7116 }
7117 }
7118 Ok(())
7119 }
7120}