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 self.instance_state(runtime_instance)
2576 .thread_handle_table()
2577 .guest_thread_remove(guest_id)?;
2578 }
2579 let state = self.concurrent_state_mut()?;
2580
2581 for waitable in mem::take(&mut state.get_mut(sync_call_set)?.ready) {
2583 if let Some(Event::Subtask {
2584 status: Status::Returned | Status::ReturnCancelled,
2585 }) = waitable.common(state)?.event
2586 {
2587 waitable.delete_from(state)?;
2588 }
2589 }
2590
2591 state.delete(guest_thread.thread)?;
2592 state.delete(sync_call_set)?;
2593 let task = state.get_mut(guest_thread.task)?;
2594 task.threads.remove(&guest_thread.thread);
2595
2596 if task.threads.is_empty() && !task.returned_or_cancelled() {
2597 bail!(Trap::NoAsyncResult);
2598 }
2599
2600 if !task.decremented_interesting_task_count && task.exited && task.returned_or_cancelled() {
2601 task.decremented_interesting_task_count = true;
2602
2603 debug_assert!(state.interesting_tasks > 0);
2604 state.interesting_tasks -= 1;
2605 if state.interesting_tasks == 0
2606 && let Some(waker) = state.interesting_tasks_empty_waker.take()
2607 {
2608 waker.wake();
2609 }
2610 }
2611
2612 state.decrement_task_ref_count(guest_thread.task)?;
2613
2614 Ok(())
2615 }
2616
2617 fn cancel_guest_subtask_without_lowered_parameters(
2626 &mut self,
2627 caller_instance: RuntimeInstance,
2628 guest_task: TableId<GuestTask>,
2629 ) -> Result<()> {
2630 let concurrent_state = self.concurrent_state_mut()?;
2631 let task = concurrent_state.get_mut(guest_task)?;
2632 assert!(!task.already_lowered_parameters());
2633 task.lower_params = None;
2637 task.lift_result = None;
2638 task.exited = true;
2639 let instance = task.instance;
2640
2641 assert_eq!(1, task.threads.len());
2648 let thread = *task.threads.iter().next().unwrap();
2649 let next_switch_item = concurrent_state.save_next_switch_item()?;
2650 self.cleanup_thread(
2651 QualifiedThreadId {
2652 task: guest_task,
2653 thread,
2654 },
2655 caller_instance,
2656 )?;
2657 self.concurrent_state_mut()?
2658 .restore_next_switch_item(next_switch_item)?;
2659
2660 let pending = &mut self.instance_state(instance).concurrent_state().pending;
2662 let pending_count = pending.len();
2663 pending.retain(|thread, _| thread.task != guest_task);
2664
2665 if pending.len() == pending_count {
2666 let matches = |item: &WorkItem| match item {
2669 WorkItem::ResumeThread { thread, .. }
2670 | WorkItem::GuestCall {
2671 call: GuestCall { thread, .. },
2672 ..
2673 } => thread.task == guest_task,
2674 _ => false,
2675 };
2676
2677 let remove = |queue: &mut VecDeque<WorkItem>| {
2678 let count = queue.len();
2679 queue.retain(|item| !matches(item));
2680 count != queue.len()
2681 };
2682
2683 let state = self.concurrent_state_mut()?;
2684 let mut found = remove(&mut state.high_priority);
2685 found |= remove(&mut state.low_priority);
2686
2687 for item in [&mut state.switch_item, &mut state.next_switch_item] {
2688 if matches!(item, Some(item) if matches(item)) {
2689 found = true;
2690 *item = None;
2691 }
2692 }
2693
2694 if !found {
2695 bail!(Trap::SubtaskCancelAfterTerminal);
2696 }
2697 }
2698 Ok(())
2699 }
2700
2701 pub(crate) fn current_scope(&mut self) -> Result<Option<CurrentScope>> {
2704 if !self.concurrency_support() {
2705 return Ok(self
2706 .current_scope_id_not_concurrent()?
2707 .map(|id| CurrentScope::Id(Scope::Id(id))));
2708 }
2709
2710 Ok(match self.current_thread()? {
2711 CurrentThread::Guest(id) => Some(CurrentScope::Id(Scope::Id(id.task.rep()))),
2712 CurrentThread::Host(id) => Some(CurrentScope::Id(Scope::HostId(id.rep()))),
2713 CurrentThread::DeferredHost(_) => Some(CurrentScope::DeferredHost),
2714 CurrentThread::None => return Ok(None),
2715 })
2716 }
2717
2718 pub(crate) fn queue_task(
2719 &mut self,
2720 task: impl FnOnce(&mut dyn VMStore) -> Result<()> + Send + 'static,
2721 ) -> Result<()> {
2722 self.concurrent_state_mut()?
2723 .push_high_priority(WorkItem::WorkerFunction(AlwaysMut::new(Box::new(task))));
2724 Ok(())
2725 }
2726
2727 fn any_may_not_suspend(&mut self) -> Result<bool> {
2736 Ok(self
2744 .concurrent_state_mut()?
2745 .table
2746 .get_mut()
2747 .iter_mut()
2748 .filter_map(|(_, entry)| {
2749 if let Some(task) = entry.downcast_ref::<GuestTask>() {
2750 Some(task.instance)
2751 } else {
2752 None
2753 }
2754 })
2755 .collect::<Vec<_>>()
2756 .into_iter()
2757 .any(|instance| {
2758 self.instance_state(instance)
2759 .concurrent_state()
2760 .do_not_suspend
2761 }))
2762 }
2763}
2764
2765impl Instance {
2766 fn get_event(
2769 self,
2770 store: &mut StoreOpaque,
2771 guest_task: TableId<GuestTask>,
2772 set: Option<TableId<WaitableSet>>,
2773 cancellable: bool,
2774 ) -> Result<Option<(Event, Option<(Waitable, u32)>)>> {
2775 let state = store.concurrent_state_mut()?;
2776
2777 let task = state.get_mut(guest_task)?;
2778 let event = &mut task.event;
2779 if let Some(ev) = event
2780 && (cancellable || !matches!(ev, Event::Cancelled))
2781 {
2782 log::trace!("deliver event {ev:?} to {guest_task:?}");
2783
2784 if matches!(ev, Event::Cancelled) {
2785 task.cancel_request_delivered = true;
2786 }
2787
2788 let ev = *ev;
2789 *event = None;
2790 return Ok(Some((ev, None)));
2791 }
2792
2793 let set = match set {
2794 Some(set) => set,
2795 None => return Ok(None),
2796 };
2797 let waitable = match state.get_mut(set)?.ready.pop_first() {
2798 Some(v) => v,
2799 None => return Ok(None),
2800 };
2801
2802 let common = waitable.common(state)?;
2803 let handle = match common.handle {
2804 Some(h) => h,
2805 None => bail_bug!("handle not set when delivering event"),
2806 };
2807 let event = match common.event.take() {
2808 Some(e) => e,
2809 None => bail_bug!("event not set when delivering event"),
2810 };
2811
2812 log::trace!(
2813 "deliver event {event:?} to {guest_task:?} for {waitable:?} (handle {handle}); set {set:?}"
2814 );
2815
2816 waitable.on_delivery(store, self, event)?;
2817
2818 Ok(Some((event, Some((waitable, handle)))))
2819 }
2820
2821 fn handle_callback_code(
2828 self,
2829 store: &mut dyn VMStore,
2830 guest_thread: QualifiedThreadId,
2831 runtime_instance: RuntimeInstance,
2832 call: impl FnOnce(&mut dyn VMStore) -> Result<u32>,
2833 ) -> Result<()> {
2834 let old_thread = store.set_thread(guest_thread)?;
2835 log::trace!(
2836 "callback-lifted call: replaced {old_thread:?} with {guest_thread:?} as current thread"
2837 );
2838
2839 store.enter_instance(runtime_instance);
2840
2841 let mut code = call(store)?;
2842
2843 if matches!(
2849 unpack_callback_code(code).0,
2850 callback_code::YIELD | callback_code::WAIT
2851 ) && let Some((event, _)) = self.get_event(store, guest_thread.task, None, true)?
2852 {
2853 let (unpacked, set) = unpack_callback_code(code);
2854 log::trace!(
2855 "{guest_thread:?} returned callback code {unpacked} (set: {set}) with a pending \
2856 cancellation; delivering it via callback"
2857 );
2858 code = invoke_callback(store, guest_thread.task, event, 0)?;
2859 }
2860
2861 store.exit_instance(runtime_instance)?;
2862
2863 store.set_thread(old_thread)?;
2864 log::trace!("callback-lifted call: restored {old_thread:?} as current thread");
2865
2866 let store = store.store_opaque_mut();
2867 let (code, set) = unpack_callback_code(code);
2868
2869 log::trace!("received callback code from {guest_thread:?}: {code} (set: {set})");
2870
2871 let state = store.concurrent_state_mut()?;
2872
2873 state.take_next_switch_item()?;
2874
2875 let get_set = |store: &mut StoreOpaque, handle| -> Result<_> {
2876 let set = store
2877 .instance_state(runtime_instance)
2878 .handle_table()
2879 .waitable_set_rep(handle)?;
2880
2881 Ok(TableId::<WaitableSet>::new(set))
2882 };
2883
2884 match code {
2885 callback_code::EXIT => {
2886 log::trace!("implicit thread {guest_thread:?} completed");
2887 let task = store.concurrent_state_mut()?.get_mut(guest_thread.task)?;
2888 task.exited = true;
2889 task.callback = None;
2890
2891 store.switch_or_trap_if_may_not_suspend(runtime_instance)?;
2896
2897 store.cleanup_thread(guest_thread, runtime_instance)?;
2898 }
2899 callback_code::YIELD => {
2900 let old = state
2903 .get_mut(guest_thread.thread)?
2904 .wake_on_cancel
2905 .replace(WakeOnCancel::Yielding);
2906 if !old.is_none() {
2907 bail_bug!("thread unexpectedly had wake_on_cancel set");
2908 }
2909
2910 let call = GuestCall {
2917 thread: guest_thread,
2918 kind: GuestCallKind::DeliverEvent {
2919 instance: self,
2920 set: None,
2921 },
2922 };
2923 state.push_low_priority(WorkItem::GuestCall {
2926 instance: runtime_instance,
2927 call,
2928 });
2929 }
2930 callback_code::WAIT => {
2931 let set = get_set(store, set)?;
2932 self.wait_with_callback(store, guest_thread, set)?;
2933 }
2934 _ => bail!(Trap::UnsupportedCallbackCode),
2935 }
2936
2937 Ok(())
2938 }
2939
2940 fn wait_with_callback(
2946 self,
2947 store: &mut StoreOpaque,
2948 guest_thread: QualifiedThreadId,
2949 set: TableId<WaitableSet>,
2950 ) -> Result<()> {
2951 let state = store.concurrent_state_mut()?;
2952 state.get_mut(set)?.num_waiting += 1;
2955
2956 if state.get_mut(guest_thread.task)?.event.is_some()
2957 || !state.get_mut(set)?.ready.is_empty()
2958 {
2959 let instance = state.get_mut(guest_thread.task)?.instance;
2961 state.push_high_priority(WorkItem::GuestCall {
2962 instance,
2963 call: GuestCall {
2964 thread: guest_thread,
2965 kind: GuestCallKind::DeliverEvent {
2966 instance: self,
2967 set: Some(set),
2968 },
2969 },
2970 });
2971 return Ok(());
2972 }
2973
2974 let instance = store
2980 .concurrent_state_mut()?
2981 .get_mut(guest_thread.task)?
2982 .instance;
2983 store.switch_or_trap_if_may_not_suspend(instance)?;
2984
2985 let state = store.concurrent_state_mut()?;
2991 let old = state
2992 .get_mut(guest_thread.thread)?
2993 .wake_on_cancel
2994 .replace(WakeOnCancel::Waiting(set));
2995 if !old.is_none() {
2996 bail_bug!("thread unexpectedly had wake_on_cancel set");
2997 }
2998 let old = state
2999 .get_mut(set)?
3000 .waiting
3001 .insert(guest_thread, WaitMode::Callback(self));
3002 if !old.is_none() {
3003 bail_bug!("set's waiting set already had this thread registered");
3004 }
3005 Ok(())
3006 }
3007
3008 unsafe fn stage_call<T: 'static>(
3015 self,
3016 mut store: StoreContextMut<T>,
3017 guest_thread: QualifiedThreadId,
3018 callee: SendSyncPtr<VMFuncRef>,
3019 param_count: usize,
3020 result_count: usize,
3021 async_: bool,
3022 callback: Option<SendSyncPtr<VMFuncRef>>,
3023 post_return: Option<SendSyncPtr<VMFuncRef>>,
3024 host_caller: bool,
3025 ) -> Result<()> {
3026 unsafe fn make_call<T: 'static>(
3041 store: StoreContextMut<T>,
3042 guest_thread: QualifiedThreadId,
3043 callee: SendSyncPtr<VMFuncRef>,
3044 param_count: usize,
3045 result_count: usize,
3046 ) -> impl FnOnce(&mut dyn VMStore) -> Result<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>
3047 + Send
3048 + Sync
3049 + 'static
3050 + use<T> {
3051 let token = StoreToken::new(store);
3052 move |store: &mut dyn VMStore| {
3053 let mut storage = [MaybeUninit::uninit(); MAX_FLAT_PARAMS];
3054
3055 store
3056 .concurrent_state_mut()?
3057 .set_thread_running(guest_thread.thread)?;
3058 let task = store.concurrent_state_mut()?.get_mut(guest_thread.task)?;
3059 let lower = match task.lower_params.take() {
3060 Some(l) => l,
3061 None => bail_bug!("lower_params missing"),
3062 };
3063
3064 lower(store, &mut storage[..param_count])?;
3065
3066 let mut store = token.as_context_mut(store);
3067
3068 unsafe {
3071 crate::Func::call_unchecked_raw(
3072 &mut store,
3073 callee.as_non_null(),
3074 NonNull::new(
3075 &mut storage[..param_count.max(result_count)]
3076 as *mut [MaybeUninit<ValRaw>] as _,
3077 )
3078 .unwrap(),
3079 UncaughtException::Trap,
3080 )?;
3081 }
3082
3083 Ok(storage)
3084 }
3085 }
3086
3087 let call = unsafe {
3091 make_call(
3092 store.as_context_mut(),
3093 guest_thread,
3094 callee,
3095 param_count,
3096 result_count,
3097 )
3098 };
3099
3100 let callee_instance = store
3101 .0
3102 .concurrent_state_mut()?
3103 .get_mut(guest_thread.task)?
3104 .instance;
3105
3106 let fun = if callback.is_some() {
3107 assert!(async_);
3108
3109 Box::new(move |store: &mut dyn VMStore| {
3110 self.add_guest_thread_to_instance_table(
3111 guest_thread.thread,
3112 store,
3113 callee_instance.index,
3114 )?;
3115 self.handle_callback_code(store, guest_thread, callee_instance, |store| {
3116 let storage = call(store)?;
3117
3118 Ok(unsafe { storage[0].assume_init() }.get_i32() as u32)
3121 })
3122 }) as Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send + Sync>
3123 } else {
3124 let token = StoreToken::new(store.as_context_mut());
3125 Box::new(move |store: &mut dyn VMStore| {
3126 self.add_guest_thread_to_instance_table(
3127 guest_thread.thread,
3128 store,
3129 callee_instance.index,
3130 )?;
3131 let old_thread = store.set_thread(guest_thread)?;
3132 log::trace!(
3133 "sync/async-stackful call: replaced {old_thread:?} with {guest_thread:?} as current thread",
3134 );
3135 let flags = self.id().get(store).instance_flags(callee_instance.index);
3136
3137 let callee_async_typed = store
3138 .concurrent_state_mut()?
3139 .get_mut(guest_thread.task)?
3140 .async_typed;
3141
3142 if !async_ && callee_async_typed {
3146 store.enter_instance(callee_instance);
3147 }
3148
3149 if !callee_async_typed {
3150 store.enter_sync_call(callee_instance)?;
3151 }
3152
3153 let storage = call(store)?;
3160
3161 if !callee_async_typed {
3162 store.exit_sync_call(callee_instance)?;
3163 }
3164
3165 if !async_ {
3166 if callee_async_typed {
3172 store.exit_instance(callee_instance)?;
3173 }
3174
3175 let lift = {
3176 let state = store.concurrent_state_mut()?;
3177 if !state.get_mut(guest_thread.task)?.result.is_none() {
3178 bail_bug!("task has already produced a result");
3179 }
3180
3181 match state.get_mut(guest_thread.task)?.lift_result.take() {
3182 Some(lift) => lift,
3183 None => bail_bug!("lift_result field is missing"),
3184 }
3185 };
3186
3187 let result = (lift.lift)(store, unsafe {
3190 mem::transmute::<&[MaybeUninit<ValRaw>], &[ValRaw]>(
3191 &storage[..result_count],
3192 )
3193 })?;
3194
3195 let post_return_arg = match result_count {
3196 0 => ValRaw::i32(0),
3197 1 => unsafe { storage[0].assume_init() },
3200 _ => unreachable!(),
3201 };
3202
3203 unsafe {
3204 call_post_return(
3205 token.as_context_mut(store),
3206 post_return.map(|v| v.as_non_null()),
3207 post_return_arg,
3208 flags,
3209 )?;
3210 }
3211
3212 self.task_complete(store, guest_thread.task, result, Status::Returned)?;
3213 }
3214
3215 store.set_thread(old_thread)?;
3216
3217 store
3218 .concurrent_state_mut()?
3219 .get_mut(guest_thread.task)?
3220 .exited = true;
3221
3222 log::trace!(
3223 "clean up thread; async lifted? {async_} async typed? {callee_async_typed}"
3224 );
3225
3226 if callee_async_typed {
3227 store.switch_or_trap_if_may_not_suspend(callee_instance)?;
3232 }
3233
3234 store.cleanup_thread(guest_thread, callee_instance)?;
3236 Ok(())
3237 })
3238 };
3239
3240 store.0.concurrent_state_mut()?.push_work_item(
3241 WorkItem::GuestCall {
3242 instance: callee_instance,
3243 call: GuestCall {
3244 thread: guest_thread,
3245 kind: GuestCallKind::StartImplicit(fun),
3246 },
3247 },
3248 if host_caller {
3249 Priority::High
3250 } else {
3251 Priority::Switch
3252 },
3253 )?;
3254
3255 Ok(())
3256 }
3257
3258 unsafe fn prepare_call<T: 'static>(
3271 self,
3272 mut store: StoreContextMut<T>,
3273 start: NonNull<VMFuncRef>,
3274 return_: NonNull<VMFuncRef>,
3275 caller_instance: RuntimeComponentInstanceIndex,
3276 callee_instance: RuntimeComponentInstanceIndex,
3277 task_return_type: TypeTupleIndex,
3278 callee_async_typed: bool,
3279 memory: *mut VMMemoryDefinition,
3280 string_encoding: StringEncoding,
3281 caller_info: CallerInfo,
3282 ) -> Result<()> {
3283 enum ResultInfo {
3284 Heap { results: u32 },
3285 Stack { result_count: u32 },
3286 }
3287
3288 let result_info = match &caller_info {
3289 CallerInfo::Async {
3290 has_result: true,
3291 params,
3292 } => ResultInfo::Heap {
3293 results: match params.last() {
3295 Some(r) => r.get_u32(),
3296 None => bail_bug!("retptr missing"),
3297 },
3298 },
3299 CallerInfo::Async {
3300 has_result: false, ..
3301 } => ResultInfo::Stack { result_count: 0 },
3302 CallerInfo::Sync {
3303 result_count,
3304 params,
3305 } if *result_count > u32::try_from(MAX_FLAT_RESULTS)? => ResultInfo::Heap {
3306 results: match params.last() {
3308 Some(r) => r.get_u32(),
3309 None => bail_bug!("arg ptr missing"),
3310 },
3311 },
3312 CallerInfo::Sync { result_count, .. } => ResultInfo::Stack {
3313 result_count: *result_count,
3314 },
3315 };
3316
3317 let sync_caller = matches!(caller_info, CallerInfo::Sync { .. });
3318
3319 let start = SendSyncPtr::new(start);
3323 let return_ = SendSyncPtr::new(return_);
3324 let token = StoreToken::new(store.as_context_mut());
3325 let old_thread = store.0.current_guest_thread()?;
3326
3327 let state = store.0.concurrent_state_mut()?;
3328
3329 debug_assert_eq!(
3330 state.get_mut(old_thread.task)?.instance,
3331 self.runtime_instance(caller_instance)
3332 );
3333
3334 let guest_thread = GuestTask::new(
3335 state,
3336 Box::new(move |store, dst| {
3337 let mut store = token.as_context_mut(store);
3338 assert!(dst.len() <= MAX_FLAT_PARAMS);
3339 let mut src = [MaybeUninit::uninit(); MAX_FLAT_PARAMS + 1];
3341 let count = match caller_info {
3342 CallerInfo::Async { params, has_result } => {
3346 let params = ¶ms[..params.len() - usize::from(has_result)];
3347 for (param, src) in params.iter().zip(&mut src) {
3348 src.write(*param);
3349 }
3350 params.len()
3351 }
3352
3353 CallerInfo::Sync { params, .. } => {
3355 for (param, src) in params.iter().zip(&mut src) {
3356 src.write(*param);
3357 }
3358 params.len()
3359 }
3360 };
3361 unsafe {
3368 crate::Func::call_unchecked_raw(
3369 &mut store,
3370 start.as_non_null(),
3371 NonNull::new(
3372 &mut src[..count.max(dst.len())] as *mut [MaybeUninit<ValRaw>] as _,
3373 )
3374 .unwrap(),
3375 UncaughtException::Trap,
3376 )?;
3377 }
3378 dst.copy_from_slice(&src[..dst.len()]);
3379 let task = store.0.current_guest_thread()?.task;
3380 let state = store.0.concurrent_state_mut()?;
3381 Waitable::Guest(task).set_event(
3382 state,
3383 Some(Event::Subtask {
3384 status: Status::Started,
3385 }),
3386 )?;
3387 Ok(())
3388 }),
3389 LiftResult {
3390 lift: Box::new(move |store, src| {
3391 let mut store = token.as_context_mut(store);
3394 let mut my_src = src.to_owned(); if let ResultInfo::Heap { results } = &result_info {
3396 my_src.push(ValRaw::u32(*results));
3397 }
3398
3399 unsafe {
3406 crate::Func::call_unchecked_raw(
3407 &mut store,
3408 return_.as_non_null(),
3409 my_src.as_mut_slice().into(),
3410 UncaughtException::Trap,
3411 )?;
3412 }
3413
3414 let thread = store.0.current_guest_thread()?;
3415 let state = store.0.concurrent_state_mut()?;
3416 if sync_caller {
3417 state.get_mut(thread.task)?.sync_result = SyncResult::Produced(
3418 if let ResultInfo::Stack { result_count } = &result_info {
3419 match result_count {
3420 0 => None,
3421 1 => Some(my_src[0]),
3422 _ => unreachable!(),
3423 }
3424 } else {
3425 None
3426 },
3427 );
3428 }
3429 Ok(Box::new(DummyResult) as Box<dyn Any + Send + Sync>)
3430 }),
3431 ty: task_return_type,
3432 memory: NonNull::new(memory).map(SendSyncPtr::new),
3433 string_encoding,
3434 },
3435 Caller::Guest { thread: old_thread },
3436 None,
3437 self.runtime_instance(callee_instance),
3438 callee_async_typed,
3439 false,
3442 )?;
3443
3444 store.0.set_thread(guest_thread)?;
3447 log::trace!("pushed {guest_thread:?} as current thread; old thread was {old_thread:?}");
3448
3449 Ok(())
3450 }
3451
3452 unsafe fn call_callback<T>(
3457 self,
3458 mut store: StoreContextMut<T>,
3459 function: SendSyncPtr<VMFuncRef>,
3460 event: Event,
3461 handle: u32,
3462 ) -> Result<u32> {
3463 let (ordinal, result) = event.parts();
3464 let params = &mut [
3465 ValRaw::u32(ordinal),
3466 ValRaw::u32(handle),
3467 ValRaw::u32(result),
3468 ];
3469 unsafe {
3474 crate::Func::call_unchecked_raw(
3475 &mut store,
3476 function.as_non_null(),
3477 params.as_mut_slice().into(),
3478 UncaughtException::Trap,
3479 )?;
3480 }
3481 Ok(params[0].get_u32())
3482 }
3483
3484 unsafe fn start_call<T: 'static>(
3502 self,
3503 mut store: StoreContextMut<T>,
3504 callback: *mut VMFuncRef,
3505 post_return: *mut VMFuncRef,
3506 callee: NonNull<VMFuncRef>,
3507 param_count: u32,
3508 result_count: u32,
3509 flags: u32,
3510 storage: &mut [MaybeUninit<ValRaw>],
3511 ) -> Result<()> {
3512 let token = StoreToken::new(store.as_context_mut());
3513 let async_caller = (flags & START_FLAG_ASYNC_CALLER) != 0;
3514 let guest_thread = store.0.current_guest_thread()?;
3515 let state = store.0.concurrent_state_mut()?;
3516
3517 if !state.event_loop_running {
3522 bail!(
3523 "async function started during an original synchronous \
3524 entrypoint; please use an async-style entrypoint instead"
3525 );
3526 }
3527
3528 let callee = SendSyncPtr::new(callee);
3529 let param_count = usize::try_from(param_count)?;
3530 assert!(param_count <= MAX_FLAT_PARAMS);
3531 let result_count = usize::try_from(result_count)?;
3532 assert!(result_count <= MAX_FLAT_RESULTS);
3533
3534 let task = state.get_mut(guest_thread.task)?;
3535 let callee_async_typed = task.async_typed;
3536 let callee_instance = task.instance;
3537
3538 task.async_lifted = (flags & START_FLAG_ASYNC_CALLEE) != 0;
3539
3540 if let Some(callback) = NonNull::new(callback) {
3541 let callback = SendSyncPtr::new(callback);
3545 task.callback = Some(Box::new(move |store, event, handle| {
3546 let store = token.as_context_mut(store);
3547 unsafe { self.call_callback::<T>(store, callback, event, handle) }
3548 }));
3549 }
3550
3551 let Caller::Guest { thread: caller } = &task.caller else {
3552 bail_bug!("start_call unexpectedly invoked for host->guest call");
3555 };
3556 let caller = *caller;
3557 let caller_instance = state.get_mut(caller.task)?.instance;
3558
3559 unsafe {
3561 self.stage_call(
3562 store.as_context_mut(),
3563 guest_thread,
3564 callee,
3565 param_count,
3566 result_count,
3567 (flags & START_FLAG_ASYNC_CALLEE) != 0,
3568 NonNull::new(callback).map(SendSyncPtr::new),
3569 NonNull::new(post_return).map(SendSyncPtr::new),
3570 false,
3571 )?;
3572 }
3573
3574 let old_do_not_suspend = if callee_async_typed {
3575 let state = store.0.instance_state(callee_instance).concurrent_state();
3582 let old_do_not_suspend = state.do_not_suspend;
3583 state.do_not_suspend = false;
3584 Some(old_do_not_suspend)
3585 } else {
3586 None
3587 };
3588
3589 let state = store.0.concurrent_state_mut()?;
3590
3591 let guest_waitable = Waitable::Guest(guest_thread.task);
3594 let old_set = guest_waitable.common(state)?.set;
3595 let set = state.get_mut(caller.thread)?.sync_call_set;
3596 guest_waitable.join(state, Some(set))?;
3597
3598 store.0.set_thread(CurrentThread::None)?;
3599
3600 let mut yielded = false;
3616 let (status, waitable) = loop {
3617 store.0.suspend(if yielded {
3618 SuspendReason::Waiting {
3619 set,
3620 thread: caller,
3621 }
3622 } else {
3623 yielded = true;
3624 SuspendReason::YieldingToSubtask { thread: caller }
3625 })?;
3626
3627 if let Some(old_do_not_suspend) = old_do_not_suspend {
3628 store
3629 .0
3630 .instance_state(callee_instance)
3631 .concurrent_state()
3632 .do_not_suspend = old_do_not_suspend;
3633 }
3634
3635 let state = store.0.concurrent_state_mut()?;
3636
3637 log::trace!("taking event for {:?}", guest_thread.task);
3638 let event = guest_waitable.take_event(state)?;
3639 let Some(Event::Subtask { status }) = event else {
3640 bail_bug!("subtasks should only get subtask events, got {event:?}")
3641 };
3642
3643 log::trace!("status {status:?} for {:?}", guest_thread.task);
3644
3645 if status == Status::Returned {
3646 break (status, None);
3648 } else if async_caller {
3649 let (state, counter) = store.0.instance_state_and_handle_counter(caller_instance);
3653 let handle = state
3654 .handle_table()
3655 .subtask_insert_guest(counter, guest_thread.task.rep())?;
3656 store
3657 .0
3658 .concurrent_state_mut()?
3659 .get_mut(guest_thread.task)?
3660 .common
3661 .handle = Some(handle);
3662 break (status, Some(handle));
3663 } else {
3664 store.0.switch_or_trap_if_may_not_suspend(caller_instance)?;
3668 }
3669 };
3670
3671 guest_waitable.join(store.0.concurrent_state_mut()?, old_set)?;
3672
3673 store.0.set_thread(caller)?;
3675
3676 store
3677 .0
3678 .concurrent_state_mut()?
3679 .set_thread_running(caller.thread)?;
3680
3681 log::trace!("popped current thread {guest_thread:?}; new thread is {caller:?}");
3682
3683 if async_caller {
3684 let Some(slot) = storage.first_mut() else {
3685 bail_bug!("no storage for async call status");
3686 };
3687 *slot = MaybeUninit::new(ValRaw::u32(status.pack(waitable)));
3688 } else {
3689 let state = store.0.concurrent_state_mut()?;
3692 let task = state.get_mut(guest_thread.task)?;
3693 if let Some(Some(result)) = task.sync_result.take()? {
3694 storage[0] = MaybeUninit::new(result);
3695 }
3696 }
3697
3698 if status == Status::Returned {
3699 store
3700 .0
3701 .concurrent_state_mut()?
3702 .decrement_task_ref_count(guest_thread.task)?;
3703 }
3704
3705 Ok(())
3706 }
3707
3708 pub(crate) fn first_poll<T: 'static, R: Send + 'static>(
3724 self,
3725 mut store: StoreContextMut<'_, T>,
3726 host_task: EnteredHostTask,
3727 result_may_require_realloc: bool,
3728 future: impl Future<Output = Result<R>> + Send + 'static,
3729 lower: impl FnOnce(StoreContextMut<T>, Option<R>, bool, Option<TableId<HostTask>>) -> Result<()>
3730 + Send
3731 + 'static,
3732 ) -> Result<u32> {
3733 let token = StoreToken::new(store.as_context_mut());
3734
3735 let (join_handle, future) = JoinHandle::run(future);
3738 let mut future = Box::pin(future);
3739
3740 let poll = tls::set(store.0, || {
3745 future
3746 .as_mut()
3747 .poll(&mut Context::from_waker(&Waker::noop()))
3748 });
3749
3750 match poll {
3751 Poll::Ready(result) => {
3753 let result = result.transpose()?;
3754 let task = store.0.current_materialized_host_task()?;
3757 lower(store.as_context_mut(), result, true, task)?;
3758 return Ok(Status::Returned.pack(None));
3759 }
3760
3761 Poll::Pending => {}
3763 }
3764
3765 let Some(task) = store.0.materialize_host_task_id()? else {
3769 bail_bug!("current thread is not a host thread")
3770 };
3771 {
3772 let state = &mut store.0.concurrent_state_mut()?.get_mut(task)?.state;
3773 assert!(matches!(state, HostTaskState::CalleeStarted));
3774 *state = HostTaskState::CalleeRunning(join_handle);
3775 }
3776
3777 let future = Box::pin(async move {
3785 let result = match run_with_host_task_set(task, future).await? {
3786 Some(result) => Some(result?),
3787 None => None,
3788 };
3789 let on_complete = move |store: &mut dyn VMStore| {
3790 let mut store = token.as_context_mut(store);
3794 let old = store.0.set_thread(task)?;
3795
3796 let status = if result.is_some() {
3797 Status::Returned
3798 } else {
3799 Status::ReturnCancelled
3800 };
3801
3802 lower(store.as_context_mut(), result, false, Some(task))?;
3803 let state = store.0.concurrent_state_mut()?;
3804 match &mut state.get_mut(task)?.state {
3805 pending @ HostTaskState::CalleeCancelling => {
3808 *pending = HostTaskState::CalleeDone { cancelled: true };
3809 }
3810
3811 other => *other = HostTaskState::CalleeDone { cancelled: false },
3813 }
3814 Waitable::Host(task).set_event(state, Some(Event::Subtask { status }))?;
3815
3816 store.0.set_thread(old)?;
3817 Ok(())
3818 };
3819
3820 tls::get(move |store| {
3821 if result_may_require_realloc {
3822 store
3827 .concurrent_state_mut()?
3828 .push_high_priority(WorkItem::WorkerFunction(AlwaysMut::new(Box::new(
3829 on_complete,
3830 ))));
3831 Ok(())
3832 } else {
3833 on_complete(store)
3836 }
3837 })
3838 });
3839
3840 let caller = match host_task {
3843 Some(caller) => caller,
3844 None => bail_bug!("host task wasn't created but should have been"),
3845 };
3846 let state = store.0.concurrent_state_mut()?;
3847 state.push_future(future);
3848 let instance = state.get_mut(caller.task)?.instance;
3849 let (state, counter) = store.0.instance_state_and_handle_counter(instance);
3850 let handle = state
3851 .handle_table()
3852 .subtask_insert_host(counter, task.rep())?;
3853 store.0.concurrent_state_mut()?.get_mut(task)?.common.handle = Some(handle);
3854 log::trace!("assign {task:?} handle {handle} for {caller:?} instance {instance:?}");
3855
3856 store.0.set_thread(caller)?;
3860 Ok(Status::Started.pack(Some(handle)))
3861 }
3862
3863 pub(crate) fn task_return(
3866 self,
3867 store: &mut dyn VMStore,
3868 ty: TypeTupleIndex,
3869 options: OptionsIndex,
3870 storage: &[ValRaw],
3871 ) -> Result<()> {
3872 let guest_thread = store.current_guest_thread()?;
3873 let state = store.concurrent_state_mut()?;
3874 if !state.get_mut(guest_thread.task)?.async_lifted {
3875 bail!(Trap::TaskReturnOrCancelSyncLifted);
3876 }
3877 let lift = state
3878 .get_mut(guest_thread.task)?
3879 .lift_result
3880 .take()
3881 .ok_or_else(|| Trap::TaskCancelOrReturnTwice)?;
3882 if !state.get_mut(guest_thread.task)?.result.is_none() {
3883 bail_bug!("task result unexpectedly already set");
3884 }
3885
3886 let CanonicalOptions {
3887 string_encoding,
3888 data_model,
3889 ..
3890 } = &self.id().get(store).component().env_component().options[options];
3891
3892 let invalid = ty != lift.ty
3893 || string_encoding != &lift.string_encoding
3894 || match data_model {
3895 CanonicalOptionsDataModel::LinearMemory(opts) => match opts.memory {
3896 Some(memory) => {
3897 let expected = lift.memory.map(|v| v.as_ptr()).unwrap_or(ptr::null_mut());
3898 let actual = self.id().get(store).runtime_memory(memory);
3899 expected != actual.as_ptr()
3900 }
3901 None => false,
3904 },
3905 CanonicalOptionsDataModel::Gc { .. } => true,
3907 };
3908
3909 if invalid {
3910 bail!(Trap::TaskReturnInvalid);
3911 }
3912
3913 log::trace!("task.return for {guest_thread:?}");
3914
3915 let result = (lift.lift)(store, storage)?;
3916 self.task_complete(store, guest_thread.task, result, Status::Returned)
3917 }
3918
3919 pub(crate) fn task_cancel(self, store: &mut StoreOpaque) -> Result<()> {
3921 let guest_thread = store.current_guest_thread()?;
3922 let state = store.concurrent_state_mut()?;
3923 let task = state.get_mut(guest_thread.task)?;
3924 if !task.async_lifted {
3925 bail!(Trap::TaskReturnOrCancelSyncLifted);
3926 }
3927 if !task.cancel_request_delivered {
3928 bail!(Trap::TaskCancelNotCancelled);
3929 }
3930 _ = task
3931 .lift_result
3932 .take()
3933 .ok_or_else(|| Trap::TaskCancelOrReturnTwice)?;
3934
3935 if !task.result.is_none() {
3936 bail_bug!("task result should not bet set yet");
3937 }
3938
3939 log::trace!("task.cancel for {guest_thread:?}");
3940
3941 self.task_complete(
3942 store,
3943 guest_thread.task,
3944 Box::new(DummyResult),
3945 Status::ReturnCancelled,
3946 )
3947 }
3948
3949 fn task_complete(
3955 self,
3956 store: &mut StoreOpaque,
3957 guest_task: TableId<GuestTask>,
3958 result: Box<dyn Any + Send + Sync>,
3959 status: Status,
3960 ) -> Result<()> {
3961 store
3962 .component_resource_tables(Some(self))?
3963 .validate_scope_exit()?;
3964
3965 let state = store.concurrent_state_mut()?;
3966 let task = state.get_mut(guest_task)?;
3967
3968 task.event = None;
3972
3973 if let Caller::Host { tx, .. } = &mut task.caller {
3974 if let Some(tx) = tx.take() {
3975 _ = tx.send(result);
3976 }
3977 } else {
3978 task.result = Some(result);
3979 Waitable::Guest(guest_task).set_event(state, Some(Event::Subtask { status }))?;
3980 }
3981
3982 Ok(())
3983 }
3984
3985 pub(crate) fn waitable_set_new(
3987 self,
3988 store: &mut StoreOpaque,
3989 caller_instance: RuntimeComponentInstanceIndex,
3990 ) -> Result<u32> {
3991 let set = store.concurrent_state_mut()?.push(WaitableSet::default())?;
3992 let (state, counter) =
3993 store.instance_state_and_handle_counter(self.runtime_instance(caller_instance));
3994 let handle = state
3995 .handle_table()
3996 .waitable_set_insert(counter, set.rep())?;
3997 log::trace!("new waitable set {set:?} (handle {handle})");
3998 Ok(handle)
3999 }
4000
4001 pub(crate) fn waitable_set_drop(
4003 self,
4004 store: &mut StoreOpaque,
4005 caller_instance: RuntimeComponentInstanceIndex,
4006 set: u32,
4007 ) -> Result<()> {
4008 let rep = store
4009 .instance_state(self.runtime_instance(caller_instance))
4010 .handle_table()
4011 .waitable_set_remove(set)?;
4012
4013 log::trace!("drop waitable set {rep} (handle {set})");
4014
4015 let set = store
4019 .concurrent_state_mut()?
4020 .get_mut(TableId::<WaitableSet>::new(rep))?;
4021 if set.num_waiting > 0 {
4022 bail!(Trap::WaitableSetDropHasWaiters);
4023 }
4024
4025 store
4026 .concurrent_state_mut()?
4027 .delete(TableId::<WaitableSet>::new(rep))?;
4028
4029 Ok(())
4030 }
4031
4032 pub(crate) fn waitable_join(
4034 self,
4035 store: &mut StoreOpaque,
4036 caller_instance: RuntimeComponentInstanceIndex,
4037 waitable_handle: u32,
4038 set_handle: u32,
4039 ) -> Result<()> {
4040 let mut instance = self.id().get_mut(store);
4041 let waitable =
4042 Waitable::from_instance(instance.as_mut(), caller_instance, waitable_handle)?;
4043
4044 let set = if set_handle == 0 {
4045 None
4046 } else {
4047 let set = instance.instance_states().0[caller_instance]
4048 .handle_table()
4049 .waitable_set_rep(set_handle)?;
4050
4051 Some(TableId::<WaitableSet>::new(set))
4052 };
4053
4054 waitable.trap_if_has_sync_waiter(store.concurrent_state_mut()?)?;
4055
4056 log::trace!(
4057 "waitable {waitable:?} (handle {waitable_handle}) join set {set:?} (handle {set_handle})",
4058 );
4059
4060 waitable.join(store.concurrent_state_mut()?, set)
4061 }
4062
4063 pub(crate) fn subtask_drop(
4065 self,
4066 store: &mut StoreOpaque,
4067 caller_instance: RuntimeComponentInstanceIndex,
4068 task_id: u32,
4069 ) -> Result<()> {
4070 self.waitable_join(store, caller_instance, task_id, 0)?;
4071
4072 let (rep, is_host) = store
4073 .instance_state(self.runtime_instance(caller_instance))
4074 .handle_table()
4075 .subtask_remove(task_id)?;
4076
4077 let concurrent_state = store.concurrent_state_mut()?;
4078 let waitable = if is_host {
4079 let id = TableId::<HostTask>::new(rep);
4080 let task = concurrent_state.get_mut(id)?;
4081 match &task.state {
4082 HostTaskState::CalleeRunning(_) | HostTaskState::CalleeCancelling => {
4083 bail!(Trap::SubtaskDropNotResolved)
4084 }
4085 HostTaskState::CalleeDone { .. } => {}
4086 HostTaskState::CalleeStarted | HostTaskState::CalleeFinished(_) => {
4087 bail_bug!("invalid state for callee in `subtask.drop`")
4088 }
4089 }
4090
4091 Waitable::Host(id)
4092 } else {
4093 let id = TableId::<GuestTask>::new(rep);
4094 let task = concurrent_state.get_mut(id)?;
4095 if task.lift_result.is_some() {
4096 bail!(Trap::SubtaskDropNotResolved);
4097 }
4098 Waitable::Guest(id)
4099 };
4100
4101 waitable.common(concurrent_state)?.handle = None;
4102
4103 if waitable.take_event(concurrent_state)?.is_some() {
4106 bail!(Trap::SubtaskDropNotResolved);
4107 }
4108
4109 waitable.delete_from(concurrent_state)?;
4110
4111 log::trace!("subtask_drop {waitable:?} (handle {task_id})");
4112 Ok(())
4113 }
4114
4115 pub(crate) fn waitable_set_wait(
4117 self,
4118 store: &mut StoreOpaque,
4119 options: OptionsIndex,
4120 set: u32,
4121 payload: u32,
4122 ) -> Result<u32> {
4123 let &CanonicalOptions {
4124 instance: caller_instance,
4125 ..
4126 } = &self.id().get(store).component().env_component().options[options];
4127 let caller = self.runtime_instance(caller_instance);
4128 let rep = store
4129 .instance_state(self.runtime_instance(caller_instance))
4130 .handle_table()
4131 .waitable_set_rep(set)?;
4132
4133 self.waitable_check(
4134 store,
4135 caller,
4136 WaitableCheck::Wait,
4137 WaitableCheckParams {
4138 set: TableId::new(rep),
4139 options,
4140 payload,
4141 },
4142 )
4143 }
4144
4145 pub(crate) fn waitable_set_poll(
4147 self,
4148 store: &mut StoreOpaque,
4149 options: OptionsIndex,
4150 set: u32,
4151 payload: u32,
4152 ) -> Result<u32> {
4153 let &CanonicalOptions {
4154 instance: caller_instance,
4155 ..
4156 } = &self.id().get(store).component().env_component().options[options];
4157 let caller = self.runtime_instance(caller_instance);
4158 let rep = store
4159 .instance_state(caller)
4160 .handle_table()
4161 .waitable_set_rep(set)?;
4162
4163 self.waitable_check(
4164 store,
4165 caller,
4166 WaitableCheck::Poll,
4167 WaitableCheckParams {
4168 set: TableId::new(rep),
4169 options,
4170 payload,
4171 },
4172 )
4173 }
4174
4175 pub(crate) fn thread_index(&self, store: &mut dyn VMStore) -> Result<u32> {
4177 let thread_id = store.current_guest_thread()?.thread;
4178 match store
4179 .concurrent_state_mut()?
4180 .get_mut(thread_id)?
4181 .instance_rep
4182 {
4183 Some(r) => Ok(r),
4184 None => bail_bug!("thread should have instance_rep by now"),
4185 }
4186 }
4187
4188 pub(crate) fn thread_new_indirect<T: 'static>(
4190 self,
4191 mut store: StoreContextMut<T>,
4192 runtime_instance: RuntimeComponentInstanceIndex,
4193 start_func_ty: ModuleInternedTypeIndex,
4194 start_func_table_idx: RuntimeTableIndex,
4195 start_func_idx: u32,
4196 context: i32,
4197 ) -> Result<u32> {
4198 log::trace!("creating new thread");
4199
4200 let (instance, registry) = self.id().get_mut_and_registry(store.0);
4201 let Some(start_func_ty) = instance.component().signatures().shared_type(start_func_ty)
4202 else {
4203 bail_bug!("thread.new-indirect start function type should be registered");
4204 };
4205 let callee = instance
4206 .index_runtime_func_table(registry, start_func_table_idx, start_func_idx as u64)?
4207 .ok_or_else(|| Trap::ThreadNewIndirectUninitialized)?;
4208 if callee.type_index(store.0) != start_func_ty {
4209 bail!(Trap::ThreadNewIndirectInvalidType);
4210 }
4211
4212 let token = StoreToken::new(store.as_context_mut());
4213 let start_func = Box::new(
4214 move |store: &mut dyn VMStore, guest_thread: QualifiedThreadId| -> Result<()> {
4215 let old_thread = store.set_thread(guest_thread)?;
4216 log::trace!(
4217 "thread start: replaced {old_thread:?} with {guest_thread:?} as current thread"
4218 );
4219
4220 let mut store = token.as_context_mut(store);
4221 let mut params = [ValRaw::i32(context)];
4222 unsafe { callee.call_unchecked(store.as_context_mut(), &mut params)? };
4225
4226 store.0.set_thread(old_thread)?;
4227
4228 let runtime_instance = self.runtime_instance(runtime_instance);
4229
4230 store
4233 .0
4234 .switch_or_trap_if_may_not_suspend(runtime_instance)?;
4235
4236 store.0.cleanup_thread(guest_thread, runtime_instance)?;
4237
4238 log::trace!("explicit thread {guest_thread:?} completed");
4239 let state = store.0.concurrent_state_mut()?;
4240 if let Some(t) = old_thread.guest() {
4241 state.set_thread_running(t.thread)?;
4242 }
4243 log::trace!("thread start: restored {old_thread:?} as current thread");
4244
4245 Ok(())
4246 },
4247 );
4248
4249 let current_thread = store.0.current_guest_thread()?;
4250 let state = store.0.concurrent_state_mut()?;
4251 let parent_task = current_thread.task;
4252
4253 let new_thread = GuestThread::new_explicit(state, parent_task, start_func)?;
4254 let thread_id = state.push(new_thread)?;
4255 state.get_mut(parent_task)?.threads.insert(thread_id);
4256
4257 log::trace!("new thread with id {thread_id:?} created");
4258
4259 self.add_guest_thread_to_instance_table(thread_id, store.0, runtime_instance)
4260 }
4261
4262 pub(crate) fn resume_thread(
4263 self,
4264 store: &mut StoreOpaque,
4265 runtime_instance: RuntimeComponentInstanceIndex,
4266 thread_idx: u32,
4267 how: ResumeThread,
4268 ) -> Result<bool> {
4269 let thread_id =
4270 GuestThread::from_instance(self.id().get_mut(store), runtime_instance, thread_idx)?;
4271 let state = store.concurrent_state_mut()?;
4272 let guest_thread = QualifiedThreadId::qualify(state, thread_id)?;
4273
4274 if store.current_guest_thread()? == guest_thread {
4275 bail!(Trap::CannotResumeThread);
4276 }
4277
4278 let priority = match how {
4279 ResumeThread::Resume => Priority::Switch,
4280 ResumeThread::ResumeLater => Priority::Low,
4281
4282 ResumeThread::Promote => {
4285 let instance = self.runtime_instance(runtime_instance);
4286 let do_not_enter = store
4287 .instance_state(instance)
4288 .concurrent_state()
4289 .do_not_enter;
4290 return store.concurrent_state_mut()?.promote_work_item_matching(
4291 |item: &WorkItem| match item {
4292 WorkItem::ResumeThread { thread, .. }
4293 | WorkItem::ResumeFiber { thread, .. } => *thread == guest_thread,
4294
4295 WorkItem::GuestCall {
4296 call: GuestCall { thread, kind },
4297 ..
4298 } => {
4299 *thread == guest_thread
4300 && match kind {
4301 GuestCallKind::DeliverEvent { .. } => !do_not_enter,
4305
4306 GuestCallKind::StartExplicit(_) => true,
4309
4310 GuestCallKind::StartImplicit(_) => false,
4314 }
4315 }
4316
4317 WorkItem::PushFuture(_) | WorkItem::WorkerFunction(_) => false,
4318 },
4319 );
4320 }
4321 };
4322
4323 let state = store.concurrent_state_mut()?;
4324 let thread = state.get_mut(guest_thread.thread)?;
4325
4326 match &thread.state {
4329 GuestThreadState::NotStartedExplicit(_) => {}
4330 GuestThreadState::Suspended(_) => {
4331 log::trace!("resuming thread {thread_id:?} that was suspended");
4332 state.schedule_suspended_thread(
4333 guest_thread,
4334 self.runtime_instance(runtime_instance),
4335 priority,
4336 )?;
4337 return Ok(true);
4338 }
4339 _ => bail!(Trap::CannotResumeThread),
4340 }
4341 match mem::replace(&mut thread.state, GuestThreadState::Running) {
4342 GuestThreadState::NotStartedExplicit(start_func) => {
4343 log::trace!("starting thread {guest_thread:?}");
4344 let guest_call = WorkItem::GuestCall {
4345 instance: self.runtime_instance(runtime_instance),
4346 call: GuestCall {
4347 thread: guest_thread,
4348 kind: GuestCallKind::StartExplicit(Box::new(move |store| {
4349 start_func(store, guest_thread)
4350 })),
4351 },
4352 };
4353 state.push_work_item(guest_call, priority)?;
4354 }
4355 other => {
4356 thread.state = other;
4357 bail_bug!("thread state checked to be resumable above");
4358 }
4359 }
4360 Ok(true)
4361 }
4362
4363 fn add_guest_thread_to_instance_table(
4364 self,
4365 thread_id: TableId<GuestThread>,
4366 store: &mut StoreOpaque,
4367 runtime_instance: RuntimeComponentInstanceIndex,
4368 ) -> Result<u32> {
4369 let (state, counter) =
4370 store.instance_state_and_handle_counter(self.runtime_instance(runtime_instance));
4371 let guest_id = state
4372 .thread_handle_table()
4373 .guest_thread_insert(counter, thread_id.rep())?;
4374 store
4375 .concurrent_state_mut()?
4376 .get_mut(thread_id)?
4377 .instance_rep = Some(guest_id);
4378 Ok(guest_id)
4379 }
4380
4381 pub(crate) fn suspension_intrinsic(
4385 self,
4386 store: &mut StoreOpaque,
4387 caller: RuntimeComponentInstanceIndex,
4388 yielding: bool,
4389 to_thread: SuspensionTarget,
4390 ) -> Result<WaitResult> {
4391 let check_suspend = match to_thread {
4392 SuspensionTarget::Promote(thread) => {
4393 !self.resume_thread(store, caller, thread, ResumeThread::Promote)?
4394 }
4395 SuspensionTarget::Resume(thread) => {
4396 if !self.resume_thread(store, caller, thread, ResumeThread::Resume)? {
4397 bail_bug!(
4398 "`resume_thread` should only ever return false \
4399 when `ResumeThread::Promote` is passed to it"
4400 );
4401 }
4402 false
4403 }
4404 SuspensionTarget::None => true,
4405 };
4406
4407 if check_suspend && !store.switch_if_may_not_suspend(self.runtime_instance(caller))? {
4408 return if yielding {
4409 Ok(WaitResult::Completed)
4410 } else {
4411 Err(Trap::CannotBlockSyncTask.into())
4412 };
4413 }
4414
4415 let guest_thread = store.current_guest_thread()?;
4416
4417 let reason = if yielding {
4418 SuspendReason::Yielding {
4419 thread: guest_thread,
4420 }
4421 } else {
4422 SuspendReason::ExplicitlySuspending {
4423 thread: guest_thread,
4424 }
4425 };
4426
4427 store.suspend(reason)?;
4428
4429 Ok(WaitResult::Completed)
4430 }
4431
4432 fn waitable_check(
4434 self,
4435 store: &mut StoreOpaque,
4436 caller: RuntimeInstance,
4437 check: WaitableCheck,
4438 params: WaitableCheckParams,
4439 ) -> Result<u32> {
4440 let guest_thread = store.current_guest_thread()?;
4441
4442 log::trace!("waitable check for {guest_thread:?}; set {:?}", params.set);
4443
4444 match &check {
4447 WaitableCheck::Wait => {
4448 let set = params.set;
4449
4450 loop {
4455 let state = store.concurrent_state_mut()?;
4456 let task = state.get_mut(guest_thread.task)?;
4457 if !(task.event.is_none() || matches!(task.event, Some(Event::Cancelled)))
4458 || !state.get_mut(set)?.ready.is_empty()
4459 {
4460 break;
4461 }
4462
4463 store.switch_or_trap_if_may_not_suspend(caller)?;
4464
4465 store.suspend(SuspendReason::Waiting {
4466 set,
4467 thread: guest_thread,
4468 })?;
4469 }
4470 }
4471 WaitableCheck::Poll => {}
4472 }
4473
4474 log::trace!(
4475 "waitable check for {guest_thread:?}; set {:?}, part two",
4476 params.set
4477 );
4478
4479 let event = self.get_event(store, guest_thread.task, Some(params.set), false)?;
4481
4482 let (ordinal, handle, result) = match &check {
4483 WaitableCheck::Wait => {
4484 let (event, waitable) = match event {
4485 Some(p) => p,
4486 None => bail_bug!("event expected to be present"),
4487 };
4488 let handle = waitable.map(|(_, v)| v).unwrap_or(0);
4489 let (ordinal, result) = event.parts();
4490 (ordinal, handle, result)
4491 }
4492 WaitableCheck::Poll => {
4493 if let Some((event, waitable)) = event {
4494 let handle = waitable.map(|(_, v)| v).unwrap_or(0);
4495 let (ordinal, result) = event.parts();
4496 (ordinal, handle, result)
4497 } else {
4498 log::trace!(
4499 "no events ready to deliver via waitable-set.poll to {:?}; set {:?}",
4500 guest_thread.task,
4501 params.set
4502 );
4503 let (ordinal, result) = Event::None.parts();
4504 (ordinal, 0, result)
4505 }
4506 }
4507 };
4508 let memory = self.options_memory_mut(store, params.options);
4509 let ptr = crate::component::func::validate_inbounds_dynamic(
4510 &CanonicalAbiInfo::POINTER_PAIR,
4511 memory,
4512 &ValRaw::u32(params.payload),
4513 )?;
4514 memory[ptr + 0..][..4].copy_from_slice(&handle.to_le_bytes());
4515 memory[ptr + 4..][..4].copy_from_slice(&result.to_le_bytes());
4516 Ok(ordinal)
4517 }
4518
4519 pub(crate) fn subtask_cancel(
4521 self,
4522 store: &mut StoreOpaque,
4523 caller_instance: RuntimeComponentInstanceIndex,
4524 async_: bool,
4525 task_id: u32,
4526 ) -> Result<u32> {
4527 let (rep, is_host) = store
4528 .instance_state(self.runtime_instance(caller_instance))
4529 .handle_table()
4530 .subtask_rep(task_id)?;
4531 let waitable = if is_host {
4532 Waitable::Host(TableId::<HostTask>::new(rep))
4533 } else {
4534 Waitable::Guest(TableId::<GuestTask>::new(rep))
4535 };
4536 let concurrent_state = store.concurrent_state_mut()?;
4537
4538 log::trace!("subtask_cancel {waitable:?} (handle {task_id}; async {async_})");
4539
4540 waitable.trap_if_in_waitable_set(concurrent_state)?;
4541
4542 let needs_block;
4543 if let Waitable::Host(host_task) = waitable {
4544 let state = &mut concurrent_state.get_mut(host_task)?.state;
4545 match state {
4546 HostTaskState::CalleeRunning(handle) => {
4553 handle.abort();
4554 *state = HostTaskState::CalleeCancelling;
4555 needs_block = true;
4556 }
4557
4558 HostTaskState::CalleeCancelling | HostTaskState::CalleeDone { cancelled: true } => {
4561 bail!(Trap::SubtaskCancelAfterTerminal);
4562 }
4563 HostTaskState::CalleeDone { cancelled: false } => {
4564 *state = HostTaskState::CalleeDone { cancelled: true };
4567 needs_block = false;
4568 }
4569
4570 HostTaskState::CalleeStarted | HostTaskState::CalleeFinished(_) => {
4573 bail_bug!("invalid states for host callee")
4574 }
4575 }
4576 } else {
4577 let guest_task = TableId::<GuestTask>::new(rep);
4578 let task = concurrent_state.get_mut(guest_task)?;
4579
4580 if task.cancel_requested {
4583 bail!(Trap::SubtaskCancelAfterTerminal);
4584 }
4585
4586 if !task.already_lowered_parameters() {
4587 store.cancel_guest_subtask_without_lowered_parameters(
4588 self.runtime_instance(caller_instance),
4589 guest_task,
4590 )?;
4591 return Ok(Status::StartCancelled as u32);
4592 } else if !task.returned_or_cancelled() {
4593 task.cancel_requested = true;
4600 task.event = Some(Event::Cancelled);
4601 let runtime_instance = task.instance;
4602 for thread in task.threads.clone() {
4603 let thread = QualifiedThreadId {
4604 task: guest_task,
4605 thread,
4606 };
4607 let concurrent_state = store.concurrent_state_mut()?;
4608 let thread_mut = concurrent_state.get_mut(thread.thread)?;
4609
4610 let yield_ = |store: &mut StoreOpaque| {
4611 let state = store.instance_state(runtime_instance).concurrent_state();
4616 let old_do_not_suspend = state.do_not_suspend;
4617 state.do_not_suspend = false;
4618
4619 let caller = store.current_guest_thread()?;
4620
4621 let state = store.concurrent_state_mut()?;
4626 let set = state.get_mut(caller.thread)?.sync_call_set;
4627 waitable.join(state, Some(set))?;
4628
4629 store.suspend(SuspendReason::YieldingToSubtask { thread: caller })?;
4630
4631 let state = store.concurrent_state_mut()?;
4632 waitable.join(state, None)?;
4633
4634 store
4635 .instance_state(runtime_instance)
4636 .concurrent_state()
4637 .do_not_suspend = old_do_not_suspend;
4638
4639 Ok::<(), crate::Error>(())
4640 };
4641
4642 match thread_mut.wake_on_cancel.take() {
4643 WakeOnCancel::Waiting(set) => {
4644 let instance = concurrent_state.take_callback_waiter(set, thread)?;
4646 let item = WorkItem::GuestCall {
4647 instance: runtime_instance,
4648 call: GuestCall {
4649 thread,
4650 kind: GuestCallKind::DeliverEvent {
4651 instance,
4652 set: Some(set),
4653 },
4654 },
4655 };
4656 concurrent_state.set_switch_item(item)?;
4657
4658 yield_(store)?;
4659
4660 break;
4661 }
4662 WakeOnCancel::Yielding => {
4663 if concurrent_state.promote_thread_work_item(thread)? {
4664 yield_(store)?;
4665 break;
4666 } else if store
4667 .instance_state(runtime_instance)
4668 .concurrent_state()
4669 .pending
4670 .contains_key(&thread)
4671 {
4672 store
4682 .concurrent_state_mut()?
4683 .get_mut(thread.thread)?
4684 .wake_on_cancel = WakeOnCancel::Yielding;
4685 } else {
4686 bail_bug!("thread with `WakeOnCancel::Yielding` not promotable");
4687 }
4688 }
4689 WakeOnCancel::None => {}
4690 }
4691 }
4692
4693 needs_block = !store
4696 .concurrent_state_mut()?
4697 .get_mut(guest_task)?
4698 .returned_or_cancelled()
4699 } else {
4700 needs_block = false;
4701 }
4702 };
4703
4704 if needs_block {
4708 if async_ {
4709 return Ok(BLOCKED);
4710 }
4711
4712 let old_next_switch_item = if is_host {
4722 Some(store.concurrent_state_mut()?.save_next_switch_item()?)
4723 } else {
4724 None
4725 };
4726
4727 store.wait_for_event(self.runtime_instance(caller_instance), waitable)?;
4730
4731 if let Some(item) = old_next_switch_item {
4732 let state = store.concurrent_state_mut()?;
4733 state.restore_next_switch_item(item)?;
4734 }
4735
4736 }
4738
4739 let event = waitable.take_event(store.concurrent_state_mut()?)?;
4740 if let Some(Event::Subtask {
4741 status: status @ (Status::Returned | Status::ReturnCancelled),
4742 }) = event
4743 {
4744 Ok(status as u32)
4745 } else {
4746 bail!(Trap::SubtaskCancelAfterTerminal);
4747 }
4748 }
4749}
4750
4751pub trait VMComponentAsyncStore {
4759 unsafe fn prepare_call(
4765 &mut self,
4766 instance: Instance,
4767 memory: *mut VMMemoryDefinition,
4768 start: NonNull<VMFuncRef>,
4769 return_: NonNull<VMFuncRef>,
4770 caller_instance: RuntimeComponentInstanceIndex,
4771 callee_instance: RuntimeComponentInstanceIndex,
4772 task_return_type: TypeTupleIndex,
4773 callee_async: bool,
4774 string_encoding: StringEncoding,
4775 result_count: u32,
4776 storage: *mut ValRaw,
4777 storage_len: usize,
4778 ) -> Result<()>;
4779
4780 unsafe fn start_call(
4783 &mut self,
4784 instance: Instance,
4785 callback: *mut VMFuncRef,
4786 post_return: *mut VMFuncRef,
4787 callee: NonNull<VMFuncRef>,
4788 param_count: u32,
4789 result_count: u32,
4790 flags: u32,
4791 storage: *mut MaybeUninit<ValRaw>,
4792 storage_len: usize,
4793 ) -> Result<()>;
4794
4795 fn future_write(
4797 &mut self,
4798 instance: Instance,
4799 caller: RuntimeComponentInstanceIndex,
4800 ty: TypeFutureTableIndex,
4801 options: OptionsIndex,
4802 future: u32,
4803 address: u32,
4804 ) -> Result<u32>;
4805
4806 fn future_read(
4808 &mut self,
4809 instance: Instance,
4810 caller: RuntimeComponentInstanceIndex,
4811 ty: TypeFutureTableIndex,
4812 options: OptionsIndex,
4813 future: u32,
4814 address: u32,
4815 ) -> Result<u32>;
4816
4817 fn future_drop_writable(
4819 &mut self,
4820 instance: Instance,
4821 ty: TypeFutureTableIndex,
4822 writer: u32,
4823 ) -> Result<()>;
4824
4825 fn stream_write(
4827 &mut self,
4828 instance: Instance,
4829 caller: RuntimeComponentInstanceIndex,
4830 ty: TypeStreamTableIndex,
4831 options: OptionsIndex,
4832 stream: u32,
4833 address: u32,
4834 count: u32,
4835 ) -> Result<u32>;
4836
4837 fn stream_read(
4839 &mut self,
4840 instance: Instance,
4841 caller: RuntimeComponentInstanceIndex,
4842 ty: TypeStreamTableIndex,
4843 options: OptionsIndex,
4844 stream: u32,
4845 address: u32,
4846 count: u32,
4847 ) -> Result<u32>;
4848
4849 fn flat_stream_write(
4852 &mut self,
4853 instance: Instance,
4854 caller: RuntimeComponentInstanceIndex,
4855 ty: TypeStreamTableIndex,
4856 options: OptionsIndex,
4857 payload_size: u32,
4858 payload_align: u32,
4859 stream: u32,
4860 address: u32,
4861 count: u32,
4862 ) -> Result<u32>;
4863
4864 fn flat_stream_read(
4867 &mut self,
4868 instance: Instance,
4869 caller: RuntimeComponentInstanceIndex,
4870 ty: TypeStreamTableIndex,
4871 options: OptionsIndex,
4872 payload_size: u32,
4873 payload_align: u32,
4874 stream: u32,
4875 address: u32,
4876 count: u32,
4877 ) -> Result<u32>;
4878
4879 fn stream_drop_writable(
4881 &mut self,
4882 instance: Instance,
4883 ty: TypeStreamTableIndex,
4884 writer: u32,
4885 ) -> Result<()>;
4886
4887 fn error_context_debug_message(
4889 &mut self,
4890 instance: Instance,
4891 ty: TypeComponentLocalErrorContextTableIndex,
4892 options: OptionsIndex,
4893 err_ctx_handle: u32,
4894 debug_msg_address: u32,
4895 ) -> Result<()>;
4896
4897 fn thread_new_indirect(
4899 &mut self,
4900 instance: Instance,
4901 caller: RuntimeComponentInstanceIndex,
4902 func_ty_idx: ModuleInternedTypeIndex,
4903 start_func_table_idx: RuntimeTableIndex,
4904 start_func_idx: u32,
4905 context: i32,
4906 ) -> Result<u32>;
4907}
4908
4909impl<T: 'static> VMComponentAsyncStore for StoreInner<T> {
4911 unsafe fn prepare_call(
4912 &mut self,
4913 instance: Instance,
4914 memory: *mut VMMemoryDefinition,
4915 start: NonNull<VMFuncRef>,
4916 return_: NonNull<VMFuncRef>,
4917 caller_instance: RuntimeComponentInstanceIndex,
4918 callee_instance: RuntimeComponentInstanceIndex,
4919 task_return_type: TypeTupleIndex,
4920 callee_async: bool,
4921 string_encoding: StringEncoding,
4922 result_count_or_max_if_async: u32,
4923 storage: *mut ValRaw,
4924 storage_len: usize,
4925 ) -> Result<()> {
4926 let params = unsafe { core::slice::from_raw_parts(storage, storage_len) }.to_vec();
4930
4931 unsafe {
4932 instance.prepare_call(
4933 StoreContextMut(self),
4934 start,
4935 return_,
4936 caller_instance,
4937 callee_instance,
4938 task_return_type,
4939 callee_async,
4940 memory,
4941 string_encoding,
4942 match result_count_or_max_if_async {
4943 PREPARE_ASYNC_NO_RESULT => CallerInfo::Async {
4944 params,
4945 has_result: false,
4946 },
4947 PREPARE_ASYNC_WITH_RESULT => CallerInfo::Async {
4948 params,
4949 has_result: true,
4950 },
4951 result_count => CallerInfo::Sync {
4952 params,
4953 result_count,
4954 },
4955 },
4956 )
4957 }
4958 }
4959
4960 unsafe fn start_call(
4961 &mut self,
4962 instance: Instance,
4963 callback: *mut VMFuncRef,
4964 post_return: *mut VMFuncRef,
4965 callee: NonNull<VMFuncRef>,
4966 param_count: u32,
4967 result_count: u32,
4968 flags: u32,
4969 storage: *mut MaybeUninit<ValRaw>,
4970 storage_len: usize,
4971 ) -> Result<()> {
4972 unsafe {
4973 instance.start_call(
4974 StoreContextMut(self),
4975 callback,
4976 post_return,
4977 callee,
4978 param_count,
4979 result_count,
4980 flags,
4981 core::slice::from_raw_parts_mut(storage, storage_len),
4985 )
4986 }
4987 }
4988
4989 fn future_write(
4990 &mut self,
4991 instance: Instance,
4992 caller: RuntimeComponentInstanceIndex,
4993 ty: TypeFutureTableIndex,
4994 options: OptionsIndex,
4995 future: u32,
4996 address: u32,
4997 ) -> Result<u32> {
4998 instance
4999 .guest_write(
5000 StoreContextMut(self),
5001 caller,
5002 TransmitIndex::Future(ty),
5003 options,
5004 None,
5005 future,
5006 address,
5007 1,
5008 )
5009 .map(|result| result.encode())
5010 }
5011
5012 fn future_read(
5013 &mut self,
5014 instance: Instance,
5015 caller: RuntimeComponentInstanceIndex,
5016 ty: TypeFutureTableIndex,
5017 options: OptionsIndex,
5018 future: u32,
5019 address: u32,
5020 ) -> Result<u32> {
5021 instance
5022 .guest_read(
5023 StoreContextMut(self),
5024 caller,
5025 TransmitIndex::Future(ty),
5026 options,
5027 None,
5028 future,
5029 address,
5030 1,
5031 )
5032 .map(|result| result.encode())
5033 }
5034
5035 fn stream_write(
5036 &mut self,
5037 instance: Instance,
5038 caller: RuntimeComponentInstanceIndex,
5039 ty: TypeStreamTableIndex,
5040 options: OptionsIndex,
5041 stream: u32,
5042 address: u32,
5043 count: u32,
5044 ) -> Result<u32> {
5045 instance
5046 .guest_write(
5047 StoreContextMut(self),
5048 caller,
5049 TransmitIndex::Stream(ty),
5050 options,
5051 None,
5052 stream,
5053 address,
5054 count,
5055 )
5056 .map(|result| result.encode())
5057 }
5058
5059 fn stream_read(
5060 &mut self,
5061 instance: Instance,
5062 caller: RuntimeComponentInstanceIndex,
5063 ty: TypeStreamTableIndex,
5064 options: OptionsIndex,
5065 stream: u32,
5066 address: u32,
5067 count: u32,
5068 ) -> Result<u32> {
5069 instance
5070 .guest_read(
5071 StoreContextMut(self),
5072 caller,
5073 TransmitIndex::Stream(ty),
5074 options,
5075 None,
5076 stream,
5077 address,
5078 count,
5079 )
5080 .map(|result| result.encode())
5081 }
5082
5083 fn future_drop_writable(
5084 &mut self,
5085 instance: Instance,
5086 ty: TypeFutureTableIndex,
5087 writer: u32,
5088 ) -> Result<()> {
5089 instance.guest_drop_writable(self, TransmitIndex::Future(ty), writer)
5090 }
5091
5092 fn flat_stream_write(
5093 &mut self,
5094 instance: Instance,
5095 caller: RuntimeComponentInstanceIndex,
5096 ty: TypeStreamTableIndex,
5097 options: OptionsIndex,
5098 payload_size: u32,
5099 payload_align: u32,
5100 stream: u32,
5101 address: u32,
5102 count: u32,
5103 ) -> Result<u32> {
5104 instance
5105 .guest_write(
5106 StoreContextMut(self),
5107 caller,
5108 TransmitIndex::Stream(ty),
5109 options,
5110 Some(FlatAbi {
5111 size: payload_size,
5112 align: payload_align,
5113 }),
5114 stream,
5115 address,
5116 count,
5117 )
5118 .map(|result| result.encode())
5119 }
5120
5121 fn flat_stream_read(
5122 &mut self,
5123 instance: Instance,
5124 caller: RuntimeComponentInstanceIndex,
5125 ty: TypeStreamTableIndex,
5126 options: OptionsIndex,
5127 payload_size: u32,
5128 payload_align: u32,
5129 stream: u32,
5130 address: u32,
5131 count: u32,
5132 ) -> Result<u32> {
5133 instance
5134 .guest_read(
5135 StoreContextMut(self),
5136 caller,
5137 TransmitIndex::Stream(ty),
5138 options,
5139 Some(FlatAbi {
5140 size: payload_size,
5141 align: payload_align,
5142 }),
5143 stream,
5144 address,
5145 count,
5146 )
5147 .map(|result| result.encode())
5148 }
5149
5150 fn stream_drop_writable(
5151 &mut self,
5152 instance: Instance,
5153 ty: TypeStreamTableIndex,
5154 writer: u32,
5155 ) -> Result<()> {
5156 instance.guest_drop_writable(self, TransmitIndex::Stream(ty), writer)
5157 }
5158
5159 fn error_context_debug_message(
5160 &mut self,
5161 instance: Instance,
5162 ty: TypeComponentLocalErrorContextTableIndex,
5163 options: OptionsIndex,
5164 err_ctx_handle: u32,
5165 debug_msg_address: u32,
5166 ) -> Result<()> {
5167 instance.error_context_debug_message(
5168 StoreContextMut(self),
5169 ty,
5170 options,
5171 err_ctx_handle,
5172 debug_msg_address,
5173 )
5174 }
5175
5176 fn thread_new_indirect(
5177 &mut self,
5178 instance: Instance,
5179 caller: RuntimeComponentInstanceIndex,
5180 func_ty_idx: ModuleInternedTypeIndex,
5181 start_func_table_idx: RuntimeTableIndex,
5182 start_func_idx: u32,
5183 context: i32,
5184 ) -> Result<u32> {
5185 instance.thread_new_indirect(
5186 StoreContextMut(self),
5187 caller,
5188 func_ty_idx,
5189 start_func_table_idx,
5190 start_func_idx,
5191 context,
5192 )
5193 }
5194}
5195
5196type HostTaskFuture = Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>;
5197
5198async fn run_with_host_task_set<F>(task: TableId<HostTask>, future: F) -> Result<F::Output>
5201where
5202 F: Future,
5203{
5204 let mut future = pin!(future);
5205 future::poll_fn(|cx| {
5206 let old_thread = match tls::get(|store| store.set_thread(task)) {
5207 Ok(thread) => thread,
5208 Err(error) => return Poll::Ready(Err(error)),
5209 };
5210 let result = future.as_mut().poll(cx);
5211 match tls::get(|store| store.set_thread(old_thread)) {
5212 Ok(_) => result.map(Ok),
5213 Err(error) => Poll::Ready(Err(error)),
5214 }
5215 })
5216 .await
5217}
5218
5219pub(crate) struct HostTask {
5223 common: WaitableCommon,
5224
5225 call_context: CallContext,
5228
5229 state: HostTaskState,
5230
5231 group: TaskGroupId,
5232}
5233
5234enum HostTaskState {
5235 CalleeStarted,
5240
5241 CalleeRunning(JoinHandle),
5246
5247 CalleeCancelling,
5251
5252 CalleeFinished(LiftedResult),
5256
5257 CalleeDone { cancelled: bool },
5260}
5261
5262impl HostTask {
5263 fn new(
5264 concurrent_state: &mut ConcurrentState,
5265 state: HostTaskState,
5266 caller: QualifiedThreadId,
5267 ) -> Result<Self> {
5268 let group = concurrent_state.get_mut(caller.task)?.group;
5269 concurrent_state.increment_group_ref_count(group)?;
5270
5271 Ok(Self {
5272 common: WaitableCommon::default(),
5273 call_context: CallContext::default(),
5274 state,
5275 group,
5276 })
5277 }
5278}
5279
5280impl TableDebug for HostTask {
5281 fn type_name() -> &'static str {
5282 "HostTask"
5283 }
5284}
5285
5286type CallbackFn = Box<dyn Fn(&mut dyn VMStore, Event, u32) -> Result<u32> + Send + Sync + 'static>;
5287
5288enum Caller {
5290 Host {
5292 tx: Option<oneshot::Sender<LiftedResult>>,
5294 caller: Option<TableId<HostTask>>,
5298 },
5299 Guest {
5301 thread: QualifiedThreadId,
5303 },
5304}
5305
5306struct LiftResult {
5309 lift: RawLift,
5310 ty: TypeTupleIndex,
5311 memory: Option<SendSyncPtr<VMMemoryDefinition>>,
5312 string_encoding: StringEncoding,
5313}
5314
5315#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
5320pub(crate) struct QualifiedThreadId {
5321 task: TableId<GuestTask>,
5322 thread: TableId<GuestThread>,
5323}
5324
5325impl QualifiedThreadId {
5326 fn qualify(
5327 state: &mut ConcurrentState,
5328 thread: TableId<GuestThread>,
5329 ) -> Result<QualifiedThreadId> {
5330 Ok(QualifiedThreadId {
5331 task: state.get_mut(thread)?.parent_task,
5332 thread,
5333 })
5334 }
5335}
5336
5337impl fmt::Debug for QualifiedThreadId {
5338 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5339 f.debug_tuple("QualifiedThreadId")
5340 .field(&self.task.rep())
5341 .field(&self.thread.rep())
5342 .finish()
5343 }
5344}
5345
5346enum GuestThreadState {
5347 NotStartedImplicit,
5348 NotStartedExplicit(
5349 Box<dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync>,
5350 ),
5351 Running,
5352 Suspended(StoreFiber<'static>),
5353 Ready {
5354 fiber: StoreFiber<'static>,
5355 },
5356 Completed,
5357}
5358
5359impl GuestThreadState {
5360 fn check_no_fiber(&self) -> Result<()> {
5361 match self {
5362 Self::Suspended(_) | Self::Ready { .. } => bail_bug!("thread already owns a fiber"),
5363 Self::NotStartedImplicit
5364 | Self::NotStartedExplicit(_)
5365 | Self::Running
5366 | Self::Completed => Ok(()),
5367 }
5368 }
5369}
5370
5371impl fmt::Debug for GuestThreadState {
5372 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5373 match self {
5374 Self::NotStartedImplicit => f.debug_tuple("NotStartedImplicit").finish(),
5375 Self::NotStartedExplicit(_) => f.debug_tuple("NotStartedExplicit").finish(),
5376 Self::Running => f.debug_tuple("Running").finish(),
5377 Self::Suspended(_) => f.debug_tuple("Suspended").finish(),
5378 Self::Ready { .. } => f.debug_struct("Ready").finish(),
5379 Self::Completed => f.debug_tuple("Completed").finish(),
5380 }
5381 }
5382}
5383
5384#[derive(Copy, Clone, PartialEq, Eq, Debug)]
5385enum WakeOnCancel {
5386 None,
5387 Waiting(TableId<WaitableSet>),
5388 Yielding,
5389}
5390
5391impl WakeOnCancel {
5392 fn is_none(self) -> bool {
5393 matches!(self, WakeOnCancel::None)
5394 }
5395
5396 fn replace(&mut self, other: WakeOnCancel) -> Self {
5397 let old = *self;
5398 *self = other;
5399 old
5400 }
5401
5402 fn take(&mut self) -> Self {
5403 self.replace(WakeOnCancel::None)
5404 }
5405}
5406
5407pub struct GuestThread {
5408 context: [u32; NUM_COMPONENT_CONTEXT_SLOTS],
5411 parent_task: TableId<GuestTask>,
5413 wake_on_cancel: WakeOnCancel,
5416 state: GuestThreadState,
5418 instance_rep: Option<u32>,
5421 sync_call_set: TableId<WaitableSet>,
5423 old_do_not_suspend: Option<bool>,
5426}
5427
5428impl GuestThread {
5429 fn from_instance(
5432 state: Pin<&mut ComponentInstance>,
5433 caller_instance: RuntimeComponentInstanceIndex,
5434 guest_thread: u32,
5435 ) -> Result<TableId<Self>> {
5436 let rep = state.instance_states().0[caller_instance]
5437 .thread_handle_table()
5438 .guest_thread_rep(guest_thread)?;
5439 Ok(TableId::new(rep))
5440 }
5441
5442 fn new_implicit(state: &mut ConcurrentState, parent_task: TableId<GuestTask>) -> Result<Self> {
5443 let sync_call_set = state.push(WaitableSet {
5444 is_sync_call_set: true,
5445 ..WaitableSet::default()
5446 })?;
5447 Ok(Self {
5448 context: [0; NUM_COMPONENT_CONTEXT_SLOTS],
5449 parent_task,
5450 wake_on_cancel: WakeOnCancel::None,
5451 state: GuestThreadState::NotStartedImplicit,
5452 instance_rep: None,
5453 sync_call_set,
5454 old_do_not_suspend: None,
5455 })
5456 }
5457
5458 fn new_explicit(
5459 state: &mut ConcurrentState,
5460 parent_task: TableId<GuestTask>,
5461 start_func: Box<
5462 dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync,
5463 >,
5464 ) -> Result<Self> {
5465 state.increment_task_ref_count(parent_task)?;
5466 let sync_call_set = state.push(WaitableSet {
5467 is_sync_call_set: true,
5468 ..WaitableSet::default()
5469 })?;
5470 Ok(Self {
5471 context: [0; NUM_COMPONENT_CONTEXT_SLOTS],
5472 parent_task,
5473 wake_on_cancel: WakeOnCancel::None,
5474 state: GuestThreadState::NotStartedExplicit(start_func),
5475 instance_rep: None,
5476 sync_call_set,
5477 old_do_not_suspend: None,
5478 })
5479 }
5480}
5481
5482impl TableDebug for GuestThread {
5483 fn type_name() -> &'static str {
5484 "GuestThread"
5485 }
5486}
5487
5488enum SyncResult {
5489 NotProduced,
5490 Produced(Option<ValRaw>),
5491 Taken,
5492}
5493
5494impl SyncResult {
5495 fn take(&mut self) -> Result<Option<Option<ValRaw>>> {
5496 Ok(match mem::replace(self, SyncResult::Taken) {
5497 SyncResult::NotProduced => None,
5498 SyncResult::Produced(val) => Some(val),
5499 SyncResult::Taken => {
5500 bail_bug!("attempted to take a synchronous result that was already taken")
5501 }
5502 })
5503 }
5504}
5505
5506pub(crate) struct GuestTask {
5508 common: WaitableCommon,
5510 lower_params: Option<RawLower>,
5512 lift_result: Option<LiftResult>,
5514 result: Option<LiftedResult>,
5517 callback: Option<CallbackFn>,
5520 caller: Caller,
5522 call_context: CallContext,
5527 sync_result: SyncResult,
5530 cancel_request_delivered: bool,
5534 cancel_requested: bool,
5539 starting_sent: bool,
5542 instance: RuntimeInstance,
5549 event: Option<Event>,
5551 exited: bool,
5553 threads: HashSet<TableId<GuestThread>>,
5555 async_typed: bool,
5558 async_lifted: bool,
5561 decremented_interesting_task_count: bool,
5564 group: TaskGroupId,
5566 ref_count: usize,
5571}
5572
5573impl GuestTask {
5574 fn already_lowered_parameters(&self) -> bool {
5575 self.lower_params.is_none()
5577 }
5578
5579 fn returned_or_cancelled(&self) -> bool {
5580 self.lift_result.is_none()
5582 }
5583
5584 fn new(
5585 state: &mut ConcurrentState,
5586 lower_params: RawLower,
5587 lift_result: LiftResult,
5588 caller: Caller,
5589 callback: Option<CallbackFn>,
5590 instance: RuntimeInstance,
5591 async_typed: bool,
5592 async_lifted: bool,
5593 ) -> Result<QualifiedThreadId> {
5594 let group = match caller {
5595 Caller::Guest { thread } => {
5596 let group = state.get_mut(thread.task)?.group;
5597 state.increment_group_ref_count(group)?;
5598 group
5599 }
5600 Caller::Host { .. } => state.make_task_group()?,
5601 };
5602
5603 let task = state.push(Self {
5604 common: WaitableCommon::default(),
5605 lower_params: Some(lower_params),
5606 lift_result: Some(lift_result),
5607 result: None,
5608 callback,
5609 caller,
5610 call_context: CallContext::default(),
5611 sync_result: SyncResult::NotProduced,
5612 cancel_request_delivered: false,
5613 cancel_requested: false,
5614 starting_sent: false,
5615 instance,
5616 event: None,
5617 exited: false,
5618 threads: HashSet::new(),
5619 async_typed,
5620 async_lifted,
5621 decremented_interesting_task_count: false,
5622 group,
5623 ref_count: 2,
5626 })?;
5627 let new_thread = GuestThread::new_implicit(state, task)?;
5628 let thread = state.push(new_thread)?;
5629 state.get_mut(task)?.threads.insert(thread);
5630 state.interesting_tasks += 1;
5631 let thread = QualifiedThreadId { task, thread };
5632 log::trace!("new implicit thread {thread:?} for instance {instance:?}");
5633 Ok(thread)
5634 }
5635}
5636
5637impl TableDebug for GuestTask {
5638 fn type_name() -> &'static str {
5639 "GuestTask"
5640 }
5641}
5642
5643#[derive(Default)]
5645struct WaitableCommon {
5646 event: Option<Event>,
5648 set: Option<TableId<WaitableSet>>,
5650 handle: Option<u32>,
5652}
5653
5654#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
5656enum Waitable {
5657 Host(TableId<HostTask>),
5659 Guest(TableId<GuestTask>),
5661 Transmit(TableId<TransmitHandle>),
5663}
5664
5665impl Waitable {
5666 fn from_instance(
5669 state: Pin<&mut ComponentInstance>,
5670 caller_instance: RuntimeComponentInstanceIndex,
5671 waitable: u32,
5672 ) -> Result<Self> {
5673 use crate::runtime::vm::component::Waitable;
5674
5675 let (waitable, kind) = state.instance_states().0[caller_instance]
5676 .handle_table()
5677 .waitable_rep(waitable)?;
5678
5679 Ok(match kind {
5680 Waitable::Subtask { is_host: true } => Self::Host(TableId::new(waitable)),
5681 Waitable::Subtask { is_host: false } => Self::Guest(TableId::new(waitable)),
5682 Waitable::Stream | Waitable::Future => Self::Transmit(TableId::new(waitable)),
5683 })
5684 }
5685
5686 fn rep(&self) -> u32 {
5688 match self {
5689 Self::Host(id) => id.rep(),
5690 Self::Guest(id) => id.rep(),
5691 Self::Transmit(id) => id.rep(),
5692 }
5693 }
5694
5695 fn join(&self, state: &mut ConcurrentState, set: Option<TableId<WaitableSet>>) -> Result<()> {
5699 log::trace!("waitable {self:?} join set {set:?}");
5700
5701 let old = mem::replace(&mut self.common(state)?.set, set);
5702
5703 if let Some(old) = old {
5704 match *self {
5705 Waitable::Host(id) => state.remove_child(id, old),
5706 Waitable::Guest(id) => state.remove_child(id, old),
5707 Waitable::Transmit(id) => state.remove_child(id, old),
5708 }?;
5709
5710 state.get_mut(old)?.ready.remove(self);
5711 }
5712
5713 if let Some(set) = set {
5714 match *self {
5715 Waitable::Host(id) => state.add_child(id, set),
5716 Waitable::Guest(id) => state.add_child(id, set),
5717 Waitable::Transmit(id) => state.add_child(id, set),
5718 }?;
5719
5720 if self.common(state)?.event.is_some() {
5721 self.mark_ready(state)?;
5722 }
5723 }
5724
5725 Ok(())
5726 }
5727
5728 fn common<'a>(&self, state: &'a mut ConcurrentState) -> Result<&'a mut WaitableCommon> {
5730 Ok(match self {
5731 Self::Host(id) => &mut state.get_mut(*id)?.common,
5732 Self::Guest(id) => &mut state.get_mut(*id)?.common,
5733 Self::Transmit(id) => &mut state.get_mut(*id)?.common,
5734 })
5735 }
5736
5737 fn trap_if_in_waitable_set(&self, state: &mut ConcurrentState) -> Result<()> {
5743 if self.common(state)?.set.is_some() {
5744 bail!(Trap::WaitableSyncAndAsync);
5745 }
5746 Ok(())
5747 }
5748
5749 fn trap_if_has_sync_waiter(&self, state: &mut ConcurrentState) -> Result<()> {
5755 if let Some(set) = self.common(state)?.set
5756 && state.get_mut(set)?.is_sync_call_set
5757 {
5758 bail!(Trap::WaitableSyncAndAsync);
5759 }
5760 Ok(())
5761 }
5762
5763 fn set_event(&self, state: &mut ConcurrentState, event: Option<Event>) -> Result<()> {
5767 log::trace!("set event for {self:?}: {event:?}");
5768 self.common(state)?.event = event;
5769 self.mark_ready(state)
5770 }
5771
5772 fn take_event(&self, state: &mut ConcurrentState) -> Result<Option<Event>> {
5774 let common = self.common(state)?;
5775 let event = common.event.take();
5776 if let Some(set) = self.common(state)?.set {
5777 state.get_mut(set)?.ready.remove(self);
5778 }
5779
5780 Ok(event)
5781 }
5782
5783 fn mark_ready(&self, state: &mut ConcurrentState) -> Result<()> {
5787 if let Some(set) = self.common(state)?.set {
5788 state.get_mut(set)?.ready.insert(*self);
5789 state.wake_waiter(set)?;
5790 }
5791 Ok(())
5792 }
5793
5794 fn delete_from(&self, state: &mut ConcurrentState) -> Result<()> {
5797 match self {
5798 Self::Host(task) => state.delete_host_task(*task),
5799 Self::Guest(task) => state.decrement_task_ref_count(*task),
5800 Self::Transmit(task) => Ok(state.delete(*task).map(drop)?),
5801 }
5802 }
5803}
5804
5805impl fmt::Debug for Waitable {
5806 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5807 match self {
5808 Self::Host(id) => write!(f, "{id:?}"),
5809 Self::Guest(id) => write!(f, "{id:?}"),
5810 Self::Transmit(id) => write!(f, "{id:?}"),
5811 }
5812 }
5813}
5814
5815#[derive(Default)]
5817struct WaitableSet {
5818 ready: BTreeSet<Waitable>,
5820 waiting: BTreeMap<QualifiedThreadId, WaitMode>,
5822 num_waiting: usize,
5825 is_sync_call_set: bool,
5828}
5829
5830impl WaitableSet {
5831 fn stop_waiting(&mut self) -> Result<()> {
5833 self.num_waiting = match self.num_waiting.checked_sub(1) {
5834 Some(n) => n,
5835 None => bail_bug!("waiter not accounted for in waitable set"),
5836 };
5837 Ok(())
5838 }
5839}
5840
5841impl TableDebug for WaitableSet {
5842 fn type_name() -> &'static str {
5843 "WaitableSet"
5844 }
5845}
5846
5847type RawLower =
5849 Box<dyn FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync>;
5850
5851type RawLift = Box<
5853 dyn FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
5854>;
5855
5856type LiftedResult = Box<dyn Any + Send + Sync>;
5860
5861struct DummyResult;
5864
5865#[derive(Default)]
5867pub struct ConcurrentInstanceState {
5868 backpressure: u16,
5870 do_not_enter: bool,
5872 do_not_suspend: bool,
5875 pending: BTreeMap<QualifiedThreadId, GuestCallKind>,
5878}
5879
5880impl ConcurrentInstanceState {
5881 pub fn pending_is_empty(&self) -> bool {
5882 self.pending.is_empty()
5883 }
5884}
5885
5886#[derive(Debug, Copy, Clone)]
5887pub(crate) enum CurrentThread {
5888 Guest(QualifiedThreadId),
5891 Host(TableId<HostTask>),
5893 DeferredHost(QualifiedThreadId),
5896 None,
5899}
5900
5901impl CurrentThread {
5902 fn guest(&self) -> Option<&QualifiedThreadId> {
5903 match self {
5904 Self::Guest(id) => Some(id),
5905 _ => None,
5906 }
5907 }
5908
5909 fn guest_task(&self) -> Option<TableId<GuestTask>> {
5910 match self {
5911 Self::Guest(id) => Some(id.task),
5912 _ => None,
5913 }
5914 }
5915
5916 fn is_none(&self) -> bool {
5917 matches!(self, Self::None)
5918 }
5919}
5920
5921impl From<QualifiedThreadId> for CurrentThread {
5922 fn from(id: QualifiedThreadId) -> Self {
5923 Self::Guest(id)
5924 }
5925}
5926
5927impl From<TableId<HostTask>> for CurrentThread {
5928 fn from(id: TableId<HostTask>) -> Self {
5929 Self::Host(id)
5930 }
5931}
5932
5933enum Priority {
5934 Switch,
5935 High,
5936 Low,
5937}
5938
5939pub struct ConcurrentState {
5941 unforced_current_thread: CurrentThread,
5947
5948 deferred_host_call_context: Option<CallContext>,
5954
5955 futures: AlwaysMut<Option<FuturesUnordered<HostTaskFuture>>>,
5960 table: AlwaysMut<ResourceTable>,
5962 switch_item: Option<WorkItem>,
5970 next_switch_item: Option<WorkItem>,
5976 high_priority: VecDeque<WorkItem>,
5978 low_priority: VecDeque<WorkItem>,
5980 suspend_reason: Option<SuspendReason>,
5984 worker: Option<StoreFiber<'static>>,
5988 worker_item: Option<WorkerItem>,
5990
5991 global_error_context_ref_counts:
6004 BTreeMap<TypeComponentGlobalErrorContextTableIndex, GlobalErrorContextRefCount>,
6005
6006 interesting_tasks: usize,
6019
6020 interesting_tasks_empty_waker: Option<Waker>,
6024
6025 ready_for_concurrent_call_waker: Option<Waker>,
6030
6031 event_loop_running: bool,
6033
6034 saved_next_switch_items: Vec<Option<WorkItem>>,
6037
6038 #[cfg(feature = "task-group-hook")]
6040 task_group_hook: Option<Box<dyn TaskGroupHook>>,
6041}
6042
6043impl Default for ConcurrentState {
6044 fn default() -> Self {
6045 Self {
6046 unforced_current_thread: CurrentThread::None,
6047 deferred_host_call_context: None,
6048 table: AlwaysMut::new(ResourceTable::new()),
6049 futures: AlwaysMut::new(Some(FuturesUnordered::new())),
6050 switch_item: None,
6051 next_switch_item: None,
6052 high_priority: VecDeque::new(),
6053 low_priority: VecDeque::new(),
6054 suspend_reason: None,
6055 worker: None,
6056 worker_item: None,
6057 global_error_context_ref_counts: BTreeMap::new(),
6058 interesting_tasks: 0,
6059 interesting_tasks_empty_waker: None,
6060 ready_for_concurrent_call_waker: None,
6061 event_loop_running: false,
6062 saved_next_switch_items: Vec::new(),
6063 #[cfg(feature = "task-group-hook")]
6064 task_group_hook: None,
6065 }
6066 }
6067}
6068
6069impl ConcurrentState {
6070 pub(crate) fn take_fibers_and_futures(
6087 &mut self,
6088 fibers: &mut Vec<StoreFiber<'static>>,
6089 futures: &mut Vec<FuturesUnordered<HostTaskFuture>>,
6090 ) {
6091 let ConcurrentState {
6092 table,
6093 worker,
6094 switch_item,
6095 next_switch_item,
6096 high_priority,
6097 low_priority,
6098 saved_next_switch_items,
6099 futures: pending_futures,
6100 worker_item: _,
6101 unforced_current_thread: _,
6102 deferred_host_call_context: _,
6103 suspend_reason: _,
6104 global_error_context_ref_counts: _,
6105 interesting_tasks: _,
6106 interesting_tasks_empty_waker: _,
6107 ready_for_concurrent_call_waker: _,
6108 event_loop_running: _,
6109 #[cfg(feature = "task-group-hook")]
6110 task_group_hook: _,
6111 } = self;
6112
6113 let mut items = Vec::new();
6114 for (_, entry) in table.get_mut().iter_mut() {
6115 if let Some(set) = entry.downcast_mut::<WaitableSet>() {
6116 for mode in mem::take(&mut set.waiting).into_values() {
6117 match mode {
6118 WaitMode::Fiber(fiber) => {
6119 fibers.push(fiber);
6120 }
6121 WaitMode::Callback(_) => {}
6122 }
6123 }
6124 } else if let Some(thread) = entry.downcast_mut::<GuestThread>() {
6125 match mem::replace(&mut thread.state, GuestThreadState::Completed) {
6126 GuestThreadState::Suspended(fiber) | GuestThreadState::Ready { fiber } => {
6127 fibers.push(fiber);
6128 }
6129 GuestThreadState::NotStartedImplicit
6130 | GuestThreadState::NotStartedExplicit(_)
6131 | GuestThreadState::Running
6132 | GuestThreadState::Completed => {}
6133 }
6134 } else if let Some(item) = entry.downcast_mut::<Option<WorkItem>>() {
6135 if let Some(item) = item.take() {
6136 items.push(item);
6137 }
6138 }
6139 }
6140
6141 if let Some(fiber) = worker.take() {
6142 fibers.push(fiber);
6143 }
6144
6145 let mut handle_item = |item| match item {
6146 WorkItem::ResumeFiber { fiber, .. } => {
6147 fibers.push(fiber);
6148 }
6149 WorkItem::PushFuture(future) => {
6150 pending_futures
6151 .get_mut()
6152 .as_mut()
6153 .unwrap()
6154 .push(future.into_inner());
6155 }
6156 WorkItem::ResumeThread { .. }
6157 | WorkItem::GuestCall { .. }
6158 | WorkItem::WorkerFunction(_) => {}
6159 };
6160
6161 for item in items {
6162 handle_item(item);
6163 }
6164 if let Some(item) = switch_item.take() {
6165 handle_item(item);
6166 }
6167 if let Some(item) = next_switch_item.take() {
6168 handle_item(item);
6169 }
6170 for item in mem::take(high_priority) {
6171 handle_item(item);
6172 }
6173 for item in mem::take(low_priority) {
6174 handle_item(item);
6175 }
6176 for item in mem::take(saved_next_switch_items)
6177 .into_iter()
6178 .filter_map(|v| v)
6179 {
6180 handle_item(item);
6181 }
6182
6183 if let Some(them) = pending_futures.get_mut().take() {
6184 futures.push(them);
6185 }
6186 }
6187
6188 #[cfg(feature = "gc")]
6189 pub(crate) fn trace_fiber_roots(
6190 &mut self,
6191 modules: &ModuleRegistry,
6192 unwind: &dyn Unwind,
6193 gc_roots_list: &mut GcRootsList,
6194 ) {
6195 let ConcurrentState {
6196 table,
6197 worker,
6198 switch_item,
6199 next_switch_item,
6200 high_priority,
6201 low_priority,
6202 saved_next_switch_items,
6203
6204 futures: _,
6208
6209 worker_item: _,
6211 unforced_current_thread: _,
6212 deferred_host_call_context: _,
6213 suspend_reason: _,
6214 global_error_context_ref_counts: _,
6215 interesting_tasks: _,
6216 interesting_tasks_empty_waker: _,
6217 ready_for_concurrent_call_waker: _,
6218 event_loop_running: _,
6219 #[cfg(feature = "task-group-hook")]
6220 task_group_hook: _,
6221 } = self;
6222
6223 for (_, entry) in table.get_mut().iter_mut() {
6224 if let Some(set) = entry.downcast_mut::<WaitableSet>() {
6225 for mode in set.waiting.values_mut() {
6226 match mode {
6227 WaitMode::Fiber(fiber) => {
6228 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6229 }
6230 WaitMode::Callback(_) => {}
6231 }
6232 }
6233 } else if let Some(thread) = entry.downcast_mut::<GuestThread>() {
6234 match &mut thread.state {
6235 GuestThreadState::Suspended(fiber) | GuestThreadState::Ready { fiber } => {
6236 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6237 }
6238 GuestThreadState::NotStartedImplicit
6239 | GuestThreadState::NotStartedExplicit(_)
6240 | GuestThreadState::Running
6241 | GuestThreadState::Completed => {}
6242 }
6243 } else if let Some(Some(WorkItem::ResumeFiber { fiber, .. })) =
6244 entry.downcast_mut::<Option<WorkItem>>()
6245 {
6246 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6247 }
6248 }
6249
6250 if let Some(fiber) = worker {
6251 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6252 }
6253
6254 let mut handle_item = |item: &mut WorkItem| match item {
6255 WorkItem::ResumeFiber { fiber, .. } => {
6256 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
6257 }
6258 WorkItem::PushFuture(_future) => {
6259 }
6262 WorkItem::ResumeThread { .. }
6263 | WorkItem::GuestCall { .. }
6264 | WorkItem::WorkerFunction(_) => {}
6265 };
6266
6267 if let Some(item) = switch_item {
6268 handle_item(item);
6269 }
6270 if let Some(item) = next_switch_item {
6271 handle_item(item);
6272 }
6273 for item in high_priority {
6274 handle_item(item);
6275 }
6276 for item in low_priority {
6277 handle_item(item);
6278 }
6279 for item in saved_next_switch_items
6280 .iter_mut()
6281 .filter_map(|v| v.as_mut())
6282 {
6283 handle_item(item);
6284 }
6285 }
6286
6287 fn schedule_suspended_thread(
6288 &mut self,
6289 thread: QualifiedThreadId,
6290 instance: RuntimeInstance,
6291 priority: Priority,
6292 ) -> Result<()> {
6293 if matches!(priority, Priority::Switch) && self.switch_item.is_some() {
6295 bail_bug!("switch item already set");
6296 }
6297 let slot = &mut self.get_mut(thread.thread)?.state;
6298 if !matches!(slot, GuestThreadState::Suspended(_)) {
6299 bail!(Trap::CannotResumeThread);
6300 }
6301 let GuestThreadState::Suspended(fiber) = mem::replace(slot, GuestThreadState::Running)
6302 else {
6303 unreachable!()
6304 };
6305 let item = WorkItem::ResumeFiber {
6306 instance,
6307 thread,
6308 fiber,
6309 };
6310 match priority {
6311 Priority::Switch => self.switch_item = Some(item),
6312 Priority::High => self.push_high_priority(item),
6313 Priority::Low => self.push_low_priority(item),
6314 }
6315 Ok(())
6316 }
6317
6318 fn set_thread_running(&mut self, thread: TableId<GuestThread>) -> Result<()> {
6319 let slot = &mut self.get_mut(thread)?.state;
6320 slot.check_no_fiber()?;
6321 *slot = GuestThreadState::Running;
6322 Ok(())
6323 }
6324
6325 fn save_next_switch_item(&mut self) -> Result<TableId<Option<WorkItem>>> {
6326 let saved = self.push(None::<WorkItem>)?;
6329 let slot = self.table.get_mut().get_mut(&Resource::from(saved))?;
6330 *slot = self.next_switch_item.take();
6331 Ok(saved)
6332 }
6333
6334 fn restore_next_switch_item(&mut self, saved: TableId<Option<WorkItem>>) -> Result<()> {
6335 if self.next_switch_item.is_some() {
6336 bail_bug!("next switch item already set when restoring");
6337 }
6338 self.next_switch_item = self.delete(saved)?;
6339 Ok(())
6340 }
6341
6342 fn take_callback_waiter(
6343 &mut self,
6344 set: TableId<WaitableSet>,
6345 thread: QualifiedThreadId,
6346 ) -> Result<Instance> {
6347 let waiting = &mut self.get_mut(set)?.waiting;
6348 let instance = match waiting.get(&thread) {
6349 Some(WaitMode::Callback(instance)) => *instance,
6350 other => bail_bug!("expected `Some(WaitMode::Callback(_))`; got `{other:?}`"),
6351 };
6352 waiting.remove(&thread);
6353 Ok(instance)
6354 }
6355
6356 fn push<V: Send + Sync + 'static>(
6357 &mut self,
6358 value: V,
6359 ) -> Result<TableId<V>, ResourceTableError> {
6360 self.table.get_mut().push(value).map(TableId::from)
6361 }
6362
6363 fn get_mut<V: 'static>(&mut self, id: TableId<V>) -> Result<&mut V, ResourceTableError> {
6364 self.table.get_mut().get_mut(&Resource::from(id))
6365 }
6366
6367 pub fn add_child<T: 'static, U: 'static>(
6368 &mut self,
6369 child: TableId<T>,
6370 parent: TableId<U>,
6371 ) -> Result<(), ResourceTableError> {
6372 self.table
6373 .get_mut()
6374 .add_child(Resource::from(child), Resource::from(parent))
6375 }
6376
6377 pub fn remove_child<T: 'static, U: 'static>(
6378 &mut self,
6379 child: TableId<T>,
6380 parent: TableId<U>,
6381 ) -> Result<(), ResourceTableError> {
6382 self.table
6383 .get_mut()
6384 .remove_child(Resource::from(child), Resource::from(parent))
6385 }
6386
6387 fn delete<V: 'static>(&mut self, id: TableId<V>) -> Result<V, ResourceTableError> {
6388 self.table.get_mut().delete(Resource::from(id))
6389 }
6390
6391 fn push_future(&mut self, future: HostTaskFuture) {
6392 self.push_high_priority(WorkItem::PushFuture(AlwaysMut::new(future)));
6399 }
6400
6401 fn set_switch_item(&mut self, item: WorkItem) -> Result<()> {
6402 if self.switch_item.is_some() {
6403 self.push_high_priority(item);
6406 bail_bug!("switch item already set");
6407 }
6408
6409 self.switch_item = Some(item);
6410 log::trace!("set switch item: {:?}", self.switch_item.as_ref().unwrap());
6411
6412 Ok(())
6413 }
6414
6415 fn take_next_switch_item(&mut self) -> Result<()> {
6416 if let Some(item) = self.next_switch_item.take() {
6417 self.set_switch_item(item)?;
6418 }
6419 Ok(())
6420 }
6421
6422 fn wake_waiter(&mut self, set: TableId<WaitableSet>) -> Result<()> {
6425 let Some((&thread, _)) = self.get_mut(set)?.waiting.first_key_value() else {
6428 return Ok(());
6429 };
6430 let wake_on_cancel = self.get_mut(thread.thread)?.wake_on_cancel;
6431 if wake_on_cancel != WakeOnCancel::None && wake_on_cancel != WakeOnCancel::Waiting(set) {
6432 bail_bug!("thread {thread:?} has unexpected wake_on_cancel value {wake_on_cancel:?}");
6433 }
6434 let instance = self.get_mut(thread.task)?.instance;
6435 self.get_mut(thread.thread)?.wake_on_cancel.take();
6436 let (_, mode) = self.get_mut(set)?.waiting.pop_first().unwrap();
6437
6438 let item = match mode {
6439 WaitMode::Fiber(fiber) => WorkItem::ResumeFiber {
6440 instance,
6441 thread,
6442 fiber,
6443 },
6444 WaitMode::Callback(callback_instance) => WorkItem::GuestCall {
6445 instance,
6446 call: GuestCall {
6447 thread,
6448 kind: GuestCallKind::DeliverEvent {
6449 instance: callback_instance,
6450 set: Some(set),
6451 },
6452 },
6453 },
6454 };
6455 self.push_high_priority(item);
6456 Ok(())
6457 }
6458
6459 fn push_high_priority(&mut self, item: WorkItem) {
6460 self.high_priority.push_front(item);
6461 log::trace!(
6462 "push high priority: {:?}",
6463 self.high_priority.front().unwrap()
6464 );
6465 }
6466
6467 fn push_low_priority(&mut self, item: WorkItem) {
6468 self.low_priority.push_front(item);
6469 log::trace!(
6470 "push low priority: {:?}",
6471 self.low_priority.front().unwrap()
6472 );
6473 }
6474
6475 fn push_work_item(&mut self, item: WorkItem, priority: Priority) -> Result<()> {
6476 match priority {
6477 Priority::Switch => self.set_switch_item(item)?,
6478 Priority::High => self.push_high_priority(item),
6479 Priority::Low => self.push_low_priority(item),
6480 }
6481
6482 Ok(())
6483 }
6484
6485 fn promote_instance_local_thread_work_item(
6486 &mut self,
6487 current_instance: RuntimeInstance,
6488 ) -> Result<bool> {
6489 log::trace!("promote thread work items for {current_instance:?}");
6490
6491 self.promote_work_item_matching(|item: &WorkItem| {
6492 let result = match item {
6493 WorkItem::ResumeThread { instance, .. }
6494 | WorkItem::ResumeFiber { instance, .. }
6495 | WorkItem::GuestCall { instance, .. } => *instance == current_instance,
6496 _ => false,
6497 };
6498
6499 log::trace!("candidate {item:?}: {result}");
6500 result
6501 })
6502 }
6503
6504 fn promote_thread_work_item(&mut self, thread: QualifiedThreadId) -> Result<bool> {
6505 self.promote_work_item_matching(|item: &WorkItem| match item {
6506 WorkItem::ResumeThread {
6507 thread: item_thread,
6508 ..
6509 }
6510 | WorkItem::GuestCall {
6511 call:
6512 GuestCall {
6513 thread: item_thread,
6514 ..
6515 },
6516 ..
6517 } => *item_thread == thread,
6518 _ => false,
6519 })
6520 }
6521
6522 fn promote_work_item_matching<F>(&mut self, mut predicate: F) -> Result<bool>
6523 where
6524 F: FnMut(&WorkItem) -> bool,
6525 {
6526 if self.switch_item.is_none() {
6533 if let Some(index) = self.high_priority.iter().rposition(&mut predicate) {
6534 self.switch_item = self.high_priority.remove(index);
6535 }
6536 }
6537 if self.switch_item.is_none() {
6538 if let Some(index) = self.low_priority.iter().rposition(predicate) {
6539 self.switch_item = self.low_priority.remove(index);
6540 }
6541 }
6542 Ok(self.switch_item.is_some())
6543 }
6544
6545 pub fn call_context(&mut self, task: Scope) -> Result<&mut CallContext> {
6548 match task {
6549 Scope::HostId(task) => {
6550 let task: TableId<HostTask> = TableId::new(task);
6551 Ok(&mut self.get_mut(task)?.call_context)
6552 }
6553 Scope::Id(task) => {
6554 let task: TableId<GuestTask> = TableId::new(task);
6555 Ok(&mut self.get_mut(task)?.call_context)
6556 }
6557 }
6558 }
6559
6560 pub(crate) fn deferred_host_call_context(&mut self) -> Option<&mut CallContext> {
6561 self.deferred_host_call_context.as_mut()
6562 }
6563
6564 fn futures_mut(&mut self) -> Result<&mut FuturesUnordered<HostTaskFuture>> {
6565 match self.futures.get_mut().as_mut() {
6566 Some(f) => Ok(f),
6567 None => bail_bug!("futures field of concurrent state is currently taken"),
6568 }
6569 }
6570
6571 pub(crate) fn table(&mut self) -> &mut ResourceTable {
6572 self.table.get_mut()
6573 }
6574
6575 fn debug_assert_deferred_host_invariant(&self) {
6576 debug_assert_eq!(
6577 self.deferred_host_call_context.is_some(),
6578 matches!(self.unforced_current_thread, CurrentThread::DeferredHost(_)),
6579 "a deferred host thread and call context must exist together",
6580 );
6581 }
6582
6583 fn materialize_host_task(&mut self) -> Result<CurrentThread> {
6584 self.debug_assert_deferred_host_invariant();
6585 let caller = match self.unforced_current_thread {
6586 CurrentThread::DeferredHost(caller) => caller,
6587 thread => return Ok(thread),
6588 };
6589
6590 let task = HostTask::new(self, HostTaskState::CalleeStarted, caller)?;
6592 let task = self.push(task)?;
6593 let call_context = self
6594 .deferred_host_call_context
6595 .take()
6596 .expect("deferred host call context should be present");
6597 self.get_mut(task)
6598 .expect("newly inserted host task should be present")
6599 .call_context = call_context;
6600 self.unforced_current_thread = CurrentThread::Host(task);
6601 self.debug_assert_deferred_host_invariant();
6602 log::trace!("new host task materialized {task:?}");
6603 Ok(CurrentThread::Host(task))
6604 }
6605
6606 fn materialize_current_host_task_id(&mut self) -> Result<Option<TableId<HostTask>>> {
6607 match self.materialize_host_task()? {
6608 CurrentThread::Host(id) => Ok(Some(id)),
6609 CurrentThread::None => Ok(None),
6610 CurrentThread::Guest(_) => {
6611 bail_bug!("tried to materialize a host task id from a guest thread")
6612 }
6613 CurrentThread::DeferredHost(_) => {
6614 bail_bug!(
6615 "current thread is a deferred host thread which should have been materialized"
6616 )
6617 }
6618 }
6619 }
6620
6621 pub(crate) fn materialize_current_scope(&mut self) -> Result<Scope> {
6622 match self.materialize_host_task()? {
6623 CurrentThread::Host(id) => Ok(Scope::HostId(id.rep())),
6624 _ => bail_bug!("current scope is not a deferred host scope"),
6625 }
6626 }
6627
6628 fn increment_task_ref_count(&mut self, task: TableId<GuestTask>) -> Result<()> {
6629 let count = &mut self.get_mut(task)?.ref_count;
6630 *count += 1;
6631 log::trace!("increment {task:?} to {count}");
6632 Ok(())
6633 }
6634
6635 fn decrement_task_ref_count(&mut self, task: TableId<GuestTask>) -> Result<()> {
6636 let count = &mut self.get_mut(task)?.ref_count;
6637 if *count == 0 {
6638 bail_bug!("can't decrement task ref count that's already zero");
6639 }
6640 *count -= 1;
6641 log::trace!("decrement {task:?} to {count}");
6642 if *count == 0 {
6643 let task = self.delete(task)?;
6644
6645 self.decrement_group_ref_count(task.group)?;
6646
6647 debug_assert!(task.decremented_interesting_task_count);
6654 }
6655 Ok(())
6656 }
6657
6658 fn delete_host_task(&mut self, task: TableId<HostTask>) -> Result<()> {
6659 log::trace!("delete host task {task:?}");
6660 let task = self.delete(task)?;
6661
6662 self.decrement_group_ref_count(task.group)
6663 }
6664}
6665
6666fn for_any_lower<
6669 F: FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync,
6670>(
6671 fun: F,
6672) -> F {
6673 fun
6674}
6675
6676fn for_any_lift<
6678 F: FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
6679>(
6680 fun: F,
6681) -> F {
6682 fun
6683}
6684
6685fn check_ambient_store(id: StoreId) {
6686 let message = "\
6687 `Future`s which depend on asynchronous component tasks, streams, or \
6688 futures to complete may only be polled from the event loop of the \
6689 store to which they belong. Please use \
6690 `StoreContextMut::{run_concurrent,spawn}` to poll or await them.\
6691 ";
6692 tls::try_get(|store| {
6693 let matched = match store {
6694 tls::TryGet::Some(store) => store.id() == id,
6695 tls::TryGet::Taken | tls::TryGet::None => false,
6696 };
6697
6698 if !matched {
6699 panic!("{message}")
6700 }
6701 });
6702}
6703
6704fn unpack_callback_code(code: u32) -> (u32, u32) {
6705 (code & 0xF, code >> 4)
6706}
6707
6708struct WaitableCheckParams {
6712 set: TableId<WaitableSet>,
6713 options: OptionsIndex,
6714 payload: u32,
6715}
6716
6717enum WaitableCheck {
6720 Wait,
6721 Poll,
6722}
6723
6724pub(crate) struct PreparedCall<R> {
6726 handle: Func,
6728 thread: QualifiedThreadId,
6730 param_count: usize,
6732 rx: oneshot::Receiver<LiftedResult>,
6735 _phantom: PhantomData<R>,
6736}
6737
6738impl<R> PreparedCall<R> {
6739 pub(crate) fn acquire_task_id(&self, store: &mut StoreOpaque) -> Result<TaskId> {
6746 store
6747 .concurrent_state_mut()?
6748 .increment_task_ref_count(self.thread.task)?;
6749
6750 Ok(TaskId {
6751 task: self.thread.task,
6752 })
6753 }
6754}
6755
6756pub(crate) struct TaskId {
6758 task: TableId<GuestTask>,
6759}
6760
6761impl TaskId {
6762 pub(crate) fn host_future_dropped(&self, store: &mut StoreOpaque) -> Result<()> {
6774 let task = store.concurrent_state_mut()?.get_mut(self.task)?;
6775 if !task.already_lowered_parameters() {
6776 task.lower_params = Some(Box::new(|store, _| {
6781 store.set_trapped();
6782 bail!("the host future for this call was dropped before it started")
6783 }));
6784 } else {
6785 _ = store
6790 .concurrent_state_mut()?
6791 .decrement_task_ref_count(self.task);
6792 }
6793
6794 Ok(())
6795 }
6796}
6797
6798pub(crate) fn prepare_call<T, R>(
6804 mut store: StoreContextMut<T>,
6805 handle: Func,
6806 param_count: usize,
6807 lower_params: impl FnOnce(StoreContextMut<T>, &mut [MaybeUninit<ValRaw>]) -> Result<()>
6808 + Send
6809 + Sync
6810 + 'static,
6811 lift_result: impl FnOnce(&mut StoreOpaque, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>>
6812 + Send
6813 + Sync
6814 + 'static,
6815) -> Result<PreparedCall<R>> {
6816 if !store.0.may_enter() {
6817 bail!(Trap::CannotEnterComponent);
6818 }
6819
6820 let (options, _flags, ty, raw_options) = handle.abi_info(store.0);
6821
6822 let instance = handle.instance().id().get(store.0);
6823 let options = &instance.component().env_component().options[options];
6824 let ty = &instance.component().types()[ty];
6825 let async_typed = ty.async_;
6826 let async_lifted = raw_options.async_;
6827 let task_return_type = ty.results;
6828 let component_instance = raw_options.instance;
6829 let callback = options.callback.map(|i| instance.runtime_callback(i));
6830 let memory = options
6831 .memory()
6832 .map(|i| instance.runtime_memory(i))
6833 .map(SendSyncPtr::new);
6834 let string_encoding = options.string_encoding;
6835 let token = StoreToken::new(store.as_context_mut());
6836 let caller = store.0.materialize_host_task_id()?;
6837 let state = store.0.concurrent_state_mut()?;
6838
6839 let (tx, rx) = oneshot::channel();
6840
6841 let instance = handle.instance().runtime_instance(component_instance);
6842 let thread = GuestTask::new(
6843 state,
6844 Box::new(for_any_lower(move |store, params| {
6845 lower_params(token.as_context_mut(store), params)
6846 })),
6847 LiftResult {
6848 lift: Box::new(for_any_lift(move |store, result| {
6849 lift_result(store, result)
6850 })),
6851 ty: task_return_type,
6852 memory,
6853 string_encoding,
6854 },
6855 Caller::Host {
6856 tx: Some(tx),
6857 caller,
6858 },
6859 callback.map(|callback| {
6860 let callback = SendSyncPtr::new(callback);
6861 let instance = handle.instance();
6862 Box::new(move |store: &mut dyn VMStore, event, handle| {
6863 let store = token.as_context_mut(store);
6864 unsafe { instance.call_callback(store, callback, event, handle) }
6867 }) as CallbackFn
6868 }),
6869 instance,
6870 async_typed,
6871 async_lifted,
6872 )?;
6873
6874 Ok(PreparedCall {
6875 handle,
6876 thread,
6877 param_count,
6878 rx,
6879 _phantom: PhantomData,
6880 })
6881}
6882
6883pub(crate) struct StagedCall<R> {
6884 store: StoreId,
6885 rx: oneshot::Receiver<LiftedResult>,
6886 _marker: PhantomData<fn() -> R>,
6887 group: TaskGroupId,
6895}
6896
6897impl<R> StagedCall<R> {
6898 pub(crate) fn new<T: 'static>(
6909 mut store: StoreContextMut<T>,
6910 prepared: PreparedCall<R>,
6911 ) -> Result<StagedCall<R>> {
6912 let PreparedCall {
6913 handle,
6914 thread,
6915 param_count,
6916 rx,
6917 ..
6918 } = prepared;
6919
6920 stage_call0(store.as_context_mut(), handle, thread, param_count)?;
6921
6922 let state = store.0.concurrent_state_mut()?;
6923 let group = state.get_mut(thread.task)?.group;
6924 state.decrement_task_ref_count(thread.task)?;
6925
6926 Ok(StagedCall {
6927 store: store.0.id(),
6928 rx,
6929 _marker: PhantomData,
6930 group,
6931 })
6932 }
6933}
6934
6935impl<R> Future for StagedCall<R>
6936where
6937 R: 'static,
6938{
6939 type Output = Result<R>;
6940
6941 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
6942 check_ambient_store(self.store);
6943 Pin::new(&mut self.rx).poll(cx).map(|result| match result {
6944 Ok(r) => match r.downcast() {
6945 Ok(r) => Ok(*r),
6946 Err(_) => bail_bug!("wrong type of value produced"),
6947 },
6948 Err(oneshot::Canceled) => bail_bug!("channel erroneously dropped"),
6949 })
6950 }
6951}
6952
6953fn stage_call0<T: 'static>(
6956 store: StoreContextMut<T>,
6957 handle: Func,
6958 guest_thread: QualifiedThreadId,
6959 param_count: usize,
6960) -> Result<()> {
6961 let (_options, _, _ty, raw_options) = handle.abi_info(store.0);
6962 let is_concurrent = raw_options.async_;
6963 let callback = raw_options.callback;
6964 let instance = handle.instance();
6965 let callee = handle.lifted_core_func(store.0);
6966 let post_return = raw_options
6967 .post_return
6968 .map(|i| instance.id().get(store.0).runtime_post_return(i));
6969 let callback = callback.map(|i| {
6970 let instance = instance.id().get(store.0);
6971 SendSyncPtr::new(instance.runtime_callback(i))
6972 });
6973
6974 log::trace!("queueing call {guest_thread:?}");
6975
6976 unsafe {
6980 instance.stage_call(
6981 store,
6982 guest_thread,
6983 SendSyncPtr::new(callee),
6984 param_count,
6985 1,
6986 is_concurrent,
6987 callback,
6988 post_return.map(SendSyncPtr::new),
6989 true,
6990 )
6991 }
6992}
6993
6994#[cfg(all(test, feature = "cranelift", feature = "wat"))]
6995mod tests {
6996 use super::*;
6997 use crate::component::{Component, Linker};
6998 use crate::store::AsStoreOpaque;
6999 use crate::{Config, Engine};
7000
7001 fn host_subtask(
7002 state: HostTaskState,
7003 event: Option<Event>,
7004 ) -> Result<(Store<()>, Instance, TableId<HostTask>, u32)> {
7005 let mut config = Config::new();
7006 config.wasm_component_model_async(true);
7007 let engine = Engine::new(&config)?;
7008 let component = Component::new(&engine, "(component)")?;
7009 let mut store = Store::new(&engine, ());
7010 let instance = Linker::new(&engine).instantiate(&mut store, &component)?;
7011 let store_opaque = store.as_store_opaque();
7012 let concurrent_state = store_opaque.concurrent_state_mut()?;
7013 let group = concurrent_state.make_task_group()?;
7016 let task = concurrent_state.push(HostTask {
7017 common: WaitableCommon::default(),
7018 call_context: CallContext::default(),
7019 state,
7020 group,
7021 })?;
7022 let (state, counter) = store_opaque.instance_state_and_handle_counter(
7023 instance.runtime_instance(RuntimeComponentInstanceIndex::from_u32(0)),
7024 );
7025 let handle = state
7026 .handle_table()
7027 .subtask_insert_host(counter, task.rep())?;
7028 let common = &mut store_opaque.concurrent_state_mut()?.get_mut(task)?.common;
7029 common.handle = Some(handle);
7030 common.event = event;
7031 Ok((store, instance, task, handle))
7032 }
7033
7034 #[test]
7035 fn host_subtask_drop_during_cancellation() -> Result<()> {
7036 for abort_completed in [false, true] {
7037 let (handle, future) = JoinHandle::run(future::pending::<()>());
7038 let mut future = pin!(future);
7039 let (mut store, instance, task, handle) =
7040 host_subtask(HostTaskState::CalleeRunning(handle), None)?;
7041 let store = store.as_store_opaque();
7042 let caller = RuntimeComponentInstanceIndex::from_u32(0);
7043 assert_eq!(
7044 instance.subtask_cancel(store, caller, true, handle)?,
7045 BLOCKED
7046 );
7047 if abort_completed {
7048 assert!(matches!(
7051 future
7052 .as_mut()
7053 .poll(&mut Context::from_waker(Waker::noop())),
7054 Poll::Ready(None),
7055 ));
7056 }
7057 for async_ in [false, true] {
7058 let err = instance
7059 .subtask_cancel(store, caller, async_, handle)
7060 .unwrap_err();
7061 assert_eq!(err.downcast::<Trap>()?, Trap::SubtaskCancelAfterTerminal);
7062 }
7063 let err = instance.subtask_drop(store, caller, handle).unwrap_err();
7064 assert_eq!(err.downcast::<Trap>()?, Trap::SubtaskDropNotResolved);
7065 assert!(store.concurrent_state_mut()?.get_mut(task).is_ok());
7066 }
7067 Ok(())
7068 }
7069
7070 #[test]
7071 fn host_subtask_cancel_after_completion() -> Result<()> {
7072 for async_ in [false, true] {
7073 let (mut store, instance, task, handle) = host_subtask(
7074 HostTaskState::CalleeDone { cancelled: false },
7075 Some(Event::Subtask {
7076 status: Status::Returned,
7077 }),
7078 )?;
7079 let store = store.as_store_opaque();
7080 let caller = RuntimeComponentInstanceIndex::from_u32(0);
7081 assert_eq!(
7082 instance.subtask_cancel(store, caller, async_, handle)?,
7083 Status::Returned as u32,
7084 );
7085 let err = instance
7086 .subtask_cancel(store, caller, async_, handle)
7087 .unwrap_err();
7088 assert_eq!(err.downcast::<Trap>()?, Trap::SubtaskCancelAfterTerminal);
7089 instance.subtask_drop(store, caller, handle)?;
7090 assert!(store.concurrent_state_mut()?.get_mut(task).is_err());
7091 }
7092 Ok(())
7093 }
7094
7095 #[test]
7096 fn host_subtask_drop_requires_terminal_event_delivery() -> Result<()> {
7097 for (cancelled, status) in [
7098 (false, Status::Returned),
7099 (true, Status::Returned),
7100 (true, Status::ReturnCancelled),
7101 ] {
7102 for delivered in [false, true] {
7103 let event = if delivered {
7104 None
7105 } else {
7106 Some(Event::Subtask { status })
7107 };
7108 let (mut store, instance, task, handle) =
7109 host_subtask(HostTaskState::CalleeDone { cancelled }, event)?;
7110 let store = store.as_store_opaque();
7111 let result = instance.subtask_drop(
7112 store,
7113 RuntimeComponentInstanceIndex::from_u32(0),
7114 handle,
7115 );
7116 if delivered {
7117 result?;
7118 assert!(store.concurrent_state_mut()?.get_mut(task).is_err());
7119 } else {
7120 let err = result.unwrap_err();
7121 assert_eq!(err.downcast::<Trap>()?, Trap::SubtaskDropNotResolved);
7122 assert!(store.concurrent_state_mut()?.get_mut(task).is_ok());
7123 }
7124 }
7125 }
7126 Ok(())
7127 }
7128}