1use self::error_contexts::GlobalErrorContextRefCount;
54use crate::bail_bug;
55use crate::component::func::{Func, call_post_return};
56use crate::component::{
57 HasData, HasSelf, Instance, Resource, ResourceTable, ResourceTableError, RuntimeInstance,
58};
59use crate::fiber::{self, StoreFiber, StoreFiberYield};
60use crate::hash_set::HashSet;
61#[cfg(feature = "gc")]
62use crate::module::ModuleRegistry;
63use crate::prelude::*;
64use crate::store::{Store, StoreId, StoreInner, StoreOpaque, StoreToken};
65#[cfg(feature = "gc")]
66use crate::vm::GcRootsList;
67use crate::vm::component::{CallContext, ComponentInstance, InstanceState};
68use crate::vm::{AlwaysMut, SendSyncPtr, VMFuncRef, VMLazyThread, VMMemoryDefinition, VMStore};
69use crate::{
70 AsContext, AsContextMut, FuncType, Result, StoreContext, StoreContextMut, ValRaw, ValType, bail,
71};
72use alloc::borrow::ToOwned;
73use alloc::collections::{BTreeMap, BTreeSet, VecDeque};
74use core::any::Any;
75use core::cell::UnsafeCell;
76use core::fmt;
77use core::future;
78use core::future::Future;
79use core::marker::PhantomData;
80use core::mem::{self, ManuallyDrop, MaybeUninit};
81use core::ops::DerefMut;
82use core::pin::{Pin, pin};
83use core::ptr::{self, NonNull};
84use core::task::{Context, Poll, Waker};
85use futures::channel::oneshot;
86use futures::stream::{FuturesUnordered, StreamExt};
87use futures_and_streams::{FlatAbi, ReturnCode, TransmitHandle, TransmitIndex};
88use table::{TableDebug, TableId};
89use wasmtime_environ::component::{
90 CanonicalAbiInfo, CanonicalOptions, CanonicalOptionsDataModel, MAX_FLAT_PARAMS,
91 MAX_FLAT_RESULTS, OptionsIndex, PREPARE_ASYNC_NO_RESULT, PREPARE_ASYNC_WITH_RESULT,
92 RuntimeComponentInstanceIndex, RuntimeTableIndex, StringEncoding,
93 TypeComponentGlobalErrorContextTableIndex, TypeComponentLocalErrorContextTableIndex,
94 TypeFuncIndex, TypeFutureTableIndex, TypeStreamTableIndex, TypeTupleIndex,
95};
96use wasmtime_environ::packed_option::ReservedValue;
97use wasmtime_environ::{NUM_COMPONENT_CONTEXT_SLOTS, Trap};
98#[cfg(feature = "gc")]
99use wasmtime_unwinder::Unwind;
100
101pub use abort::JoinHandle;
102pub use func::{FuncCallConcurrent, TypedFuncCallConcurrent};
103pub use future_stream_any::{FutureAny, StreamAny};
104pub use futures_and_streams::{
105 Destination, DirectDestination, DirectSource, ErrorContext, FutureConsumer, FutureProducer,
106 FutureReader, GuardedFutureReader, GuardedStreamReader, ReadBuffer, Source, StreamConsumer,
107 StreamProducer, StreamReader, StreamResult, VecBuffer, WriteBuffer,
108};
109pub(crate) use futures_and_streams::{ResourcePair, lower_error_context_to_index};
110
111mod abort;
112mod error_contexts;
113mod func;
114mod future_stream_any;
115mod futures_and_streams;
116pub(crate) mod table;
117pub(crate) mod tls;
118
119const BLOCKED: u32 = 0xffff_ffff;
122
123#[derive(Clone, Copy, Eq, PartialEq, Debug)]
125pub enum Status {
126 Starting = 0,
127 Started = 1,
128 Returned = 2,
129 StartCancelled = 3,
130 ReturnCancelled = 4,
131}
132
133impl Status {
134 pub fn pack(self, waitable: Option<u32>) -> u32 {
140 assert!(matches!(self, Status::Returned) == waitable.is_none());
141 let waitable = waitable.unwrap_or(0);
142 assert!(waitable < (1 << 28));
143 (waitable << 4) | (self as u32)
144 }
145}
146
147#[derive(Clone, Copy, Debug)]
150enum Event {
151 None,
152 Subtask {
153 status: Status,
154 },
155 StreamRead {
156 code: ReturnCode,
157 pending: Option<(TypeStreamTableIndex, u32)>,
158 },
159 StreamWrite {
160 code: ReturnCode,
161 pending: Option<(TypeStreamTableIndex, u32)>,
162 },
163 FutureRead {
164 code: ReturnCode,
165 pending: Option<(TypeFutureTableIndex, u32)>,
166 },
167 FutureWrite {
168 code: ReturnCode,
169 pending: Option<(TypeFutureTableIndex, u32)>,
170 },
171 Cancelled,
172}
173
174impl Event {
175 fn parts(self) -> (u32, u32) {
180 const EVENT_NONE: u32 = 0;
181 const EVENT_SUBTASK: u32 = 1;
182 const EVENT_STREAM_READ: u32 = 2;
183 const EVENT_STREAM_WRITE: u32 = 3;
184 const EVENT_FUTURE_READ: u32 = 4;
185 const EVENT_FUTURE_WRITE: u32 = 5;
186 const EVENT_CANCELLED: u32 = 6;
187 match self {
188 Event::None => (EVENT_NONE, 0),
189 Event::Cancelled => (EVENT_CANCELLED, 0),
190 Event::Subtask { status } => (EVENT_SUBTASK, status as u32),
191 Event::StreamRead { code, .. } => (EVENT_STREAM_READ, code.encode()),
192 Event::StreamWrite { code, .. } => (EVENT_STREAM_WRITE, code.encode()),
193 Event::FutureRead { code, .. } => (EVENT_FUTURE_READ, code.encode()),
194 Event::FutureWrite { code, .. } => (EVENT_FUTURE_WRITE, code.encode()),
195 }
196 }
197}
198
199mod callback_code {
201 pub const EXIT: u32 = 0;
202 pub const YIELD: u32 = 1;
203 pub const WAIT: u32 = 2;
204}
205
206const START_FLAG_ASYNC_CALLEE: u32 = wasmtime_environ::component::START_FLAG_ASYNC_CALLEE as u32;
210
211pub struct Access<'a, T: 'static, D: HasData + ?Sized = HasSelf<T>> {
217 store: StoreContextMut<'a, T>,
218 get_data: fn(&mut T) -> D::Data<'_>,
219}
220
221impl<'a, T, D> Access<'a, T, D>
222where
223 D: HasData + ?Sized,
224 T: 'static,
225{
226 pub fn new(store: StoreContextMut<'a, T>, get_data: fn(&mut T) -> D::Data<'_>) -> Self {
228 Self { store, get_data }
229 }
230
231 pub fn data_mut(&mut self) -> &mut T {
233 self.store.data_mut()
234 }
235
236 pub fn get(&mut self) -> D::Data<'_> {
238 (self.get_data)(self.data_mut())
239 }
240
241 pub fn spawn(&mut self, task: impl AccessorTask<T, D>) -> Result<JoinHandle>
245 where
246 T: 'static,
247 {
248 let accessor = Accessor {
249 get_data: self.get_data,
250 token: StoreToken::new(self.store.as_context_mut()),
251 };
252 self.store
253 .as_context_mut()
254 .spawn_with_accessor(accessor, task)
255 }
256
257 pub fn getter(&self) -> fn(&mut T) -> D::Data<'_> {
260 self.get_data
261 }
262}
263
264impl<'a, T, D> AsContext for Access<'a, T, D>
265where
266 D: HasData + ?Sized,
267 T: 'static,
268{
269 type Data = T;
270
271 fn as_context(&self) -> StoreContext<'_, T> {
272 self.store.as_context()
273 }
274}
275
276impl<'a, T, D> AsContextMut for Access<'a, T, D>
277where
278 D: HasData + ?Sized,
279 T: 'static,
280{
281 fn as_context_mut(&mut self) -> StoreContextMut<'_, T> {
282 self.store.as_context_mut()
283 }
284}
285
286pub struct Accessor<T: 'static, D = HasSelf<T>>
346where
347 D: HasData + ?Sized,
348{
349 token: StoreToken<T>,
350 get_data: fn(&mut T) -> D::Data<'_>,
351}
352
353pub trait AsAccessor {
370 type Data: 'static;
372
373 type AccessorData: HasData + ?Sized;
376
377 fn as_accessor(&self) -> &Accessor<Self::Data, Self::AccessorData>;
379}
380
381impl<T: AsAccessor + ?Sized> AsAccessor for &T {
382 type Data = T::Data;
383 type AccessorData = T::AccessorData;
384
385 fn as_accessor(&self) -> &Accessor<Self::Data, Self::AccessorData> {
386 T::as_accessor(self)
387 }
388}
389
390impl<T, D: HasData + ?Sized> AsAccessor for Accessor<T, D> {
391 type Data = T;
392 type AccessorData = D;
393
394 fn as_accessor(&self) -> &Accessor<T, D> {
395 self
396 }
397}
398
399const _: () = {
422 const fn assert<T: Send + Sync>() {}
423 assert::<Accessor<UnsafeCell<u32>>>();
424};
425
426impl<T> Accessor<T> {
427 pub(crate) fn new(token: StoreToken<T>) -> Self {
436 Self {
437 token,
438 get_data: |x| x,
439 }
440 }
441}
442
443impl<T, D> Accessor<T, D>
444where
445 D: HasData + ?Sized,
446{
447 pub fn with<R>(&self, fun: impl FnOnce(Access<'_, T, D>) -> R) -> R {
465 tls::get(|vmstore| {
466 fun(Access {
467 store: self.token.as_context_mut(vmstore),
468 get_data: self.get_data,
469 })
470 })
471 }
472
473 pub fn getter(&self) -> fn(&mut T) -> D::Data<'_> {
476 self.get_data
477 }
478
479 pub fn with_getter<D2: HasData>(
496 &self,
497 get_data: fn(&mut T) -> D2::Data<'_>,
498 ) -> Accessor<T, D2> {
499 Accessor {
500 token: self.token,
501 get_data,
502 }
503 }
504
505 pub fn spawn(&self, task: impl AccessorTask<T, D>) -> Result<JoinHandle>
521 where
522 T: 'static,
523 {
524 let accessor = self.clone_for_spawn();
525 self.with(|mut access| access.as_context_mut().spawn_with_accessor(accessor, task))
526 }
527
528 fn clone_for_spawn(&self) -> Self {
529 Self {
530 token: self.token,
531 get_data: self.get_data,
532 }
533 }
534
535 pub fn poll_no_interesting_tasks(&self, cx: &mut Context<'_>) -> Poll<()> {
571 self.with(|mut access| {
572 let store = access.as_context_mut().0;
573 let state = store.concurrent_state_mut_without_forcing_current_thread();
574 if state.interesting_tasks == 0 {
575 Poll::Ready(())
576 } else {
577 state.interesting_tasks_empty_waker = Some(cx.waker().clone());
578 Poll::Pending
579 }
580 })
581 }
582}
583
584pub trait AccessorTask<T, D = HasSelf<T>>: Send + 'static
596where
597 D: HasData + ?Sized,
598{
599 fn run(self, accessor: &Accessor<T, D>) -> impl Future<Output = Result<()>> + Send;
601}
602
603enum CallerInfo {
606 Async {
608 params: Vec<ValRaw>,
609 has_result: bool,
610 },
611 Sync {
613 params: Vec<ValRaw>,
614 result_count: u32,
615 },
616}
617
618enum WaitMode {
620 Fiber(StoreFiber<'static>),
622 Callback(Instance),
625}
626
627#[derive(Debug)]
629enum SuspendReason {
630 Waiting {
633 set: TableId<WaitableSet>,
634 thread: QualifiedThreadId,
635 skip_may_block_check: bool,
636 },
637 NeedWork,
640 Yielding {
643 thread: QualifiedThreadId,
644 cancellable: bool,
645 skip_may_block_check: bool,
646 },
647 ExplicitlySuspending {
649 thread: QualifiedThreadId,
650 skip_may_block_check: bool,
651 },
652}
653
654enum GuestCallKind {
656 DeliverEvent {
659 instance: Instance,
661 set: Option<TableId<WaitableSet>>,
666 },
667 StartImplicit(Box<dyn FnOnce(&mut dyn VMStore) -> Result<Option<GuestCall>> + Send + Sync>),
673 StartExplicit(Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send + Sync>),
674}
675
676impl fmt::Debug for GuestCallKind {
677 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
678 match self {
679 Self::DeliverEvent { instance, set } => f
680 .debug_struct("DeliverEvent")
681 .field("instance", instance)
682 .field("set", set)
683 .finish(),
684 Self::StartImplicit(_) => f.debug_tuple("StartImplicit").finish(),
685 Self::StartExplicit(_) => f.debug_tuple("StartExplicit").finish(),
686 }
687 }
688}
689
690#[derive(Copy, Clone, Debug)]
692pub enum SuspensionTarget {
693 SomeSuspended(u32),
694 Some(u32),
695 None,
696}
697
698impl SuspensionTarget {
699 fn is_none(&self) -> bool {
700 matches!(self, SuspensionTarget::None)
701 }
702 fn is_some(&self) -> bool {
703 !self.is_none()
704 }
705}
706
707#[derive(Debug)]
709struct GuestCall {
710 thread: QualifiedThreadId,
711 kind: GuestCallKind,
712}
713
714impl GuestCall {
715 fn is_ready(&self, store: &mut StoreOpaque) -> Result<bool> {
725 let instance = store
726 .concurrent_state_mut()?
727 .get_mut(self.thread.task)?
728 .instance;
729 let state = store.instance_state(instance).concurrent_state();
730
731 let ready = match &self.kind {
732 GuestCallKind::DeliverEvent { .. } => !state.do_not_enter,
733 GuestCallKind::StartImplicit(_) => !(state.do_not_enter || state.backpressure > 0),
734 GuestCallKind::StartExplicit(_) => true,
735 };
736 log::trace!(
737 "call {self:?} ready? {ready} (do_not_enter: {}; backpressure: {})",
738 state.do_not_enter,
739 state.backpressure
740 );
741 Ok(ready)
742 }
743}
744
745enum WorkerItem {
747 GuestCall(GuestCall),
748 Function(AlwaysMut<Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send>>),
749}
750
751enum WorkItem {
754 PushFuture(AlwaysMut<HostTaskFuture>),
756 ResumeFiber(StoreFiber<'static>),
758 ResumeThread(RuntimeComponentInstanceIndex, QualifiedThreadId),
760 GuestCall(RuntimeComponentInstanceIndex, GuestCall),
762 WorkerFunction(AlwaysMut<Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send>>),
764}
765
766impl fmt::Debug for WorkItem {
767 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
768 match self {
769 Self::PushFuture(_) => f.debug_tuple("PushFuture").finish(),
770 Self::ResumeFiber(_) => f.debug_tuple("ResumeFiber").finish(),
771 Self::ResumeThread(instance, thread) => f
772 .debug_tuple("ResumeThread")
773 .field(instance)
774 .field(thread)
775 .finish(),
776 Self::GuestCall(instance, call) => f
777 .debug_tuple("GuestCall")
778 .field(instance)
779 .field(call)
780 .finish(),
781 Self::WorkerFunction(_) => f.debug_tuple("WorkerFunction").finish(),
782 }
783 }
784}
785
786#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
788pub(crate) enum WaitResult {
789 Cancelled,
790 Completed,
791}
792
793pub(crate) fn poll_and_block<R: Send + Sync + 'static>(
801 store: &mut dyn VMStore,
802 future: impl Future<Output = Result<R>> + Send + 'static,
803) -> Result<R> {
804 let task = store.current_host_thread()?;
805
806 let mut future = Box::pin(async move {
810 let result = future.await?;
811 tls::get(move |store| {
812 let state = store.concurrent_state_mut()?;
813 let host_state = &mut state.get_mut(task)?.state;
814 assert!(matches!(host_state, HostTaskState::CalleeStarted));
815 *host_state = HostTaskState::CalleeFinished(Box::new(result));
816
817 Waitable::Host(task).set_event(
818 state,
819 Some(Event::Subtask {
820 status: Status::Returned,
821 }),
822 )?;
823
824 Ok(())
825 })
826 }) as HostTaskFuture;
827
828 let poll = tls::set(store, || {
832 future
833 .as_mut()
834 .poll(&mut Context::from_waker(&Waker::noop()))
835 });
836
837 match poll {
838 Poll::Ready(result) => result?,
840
841 Poll::Pending => {
846 let state = store.concurrent_state_mut()?;
847 state.push_future(future);
848
849 let caller = state.get_mut(task)?.caller;
850 let set = state.get_mut(caller.thread)?.sync_call_set;
851 Waitable::Host(task).join(state, Some(set))?;
852
853 store.suspend(SuspendReason::Waiting {
854 set,
855 thread: caller,
856 skip_may_block_check: false,
857 })?;
858
859 Waitable::Host(task).join(store.concurrent_state_mut()?, None)?;
863 }
864 }
865
866 let host_state = &mut store.concurrent_state_mut()?.get_mut(task)?.state;
868 match mem::replace(host_state, HostTaskState::CalleeDone { cancelled: false }) {
869 HostTaskState::CalleeFinished(result) => Ok(match result.downcast() {
870 Ok(result) => *result,
871 Err(_) => bail_bug!("host task finished with wrong type of result"),
872 }),
873 _ => bail_bug!("unexpected host task state after completion"),
874 }
875}
876
877fn handle_guest_call(store: &mut dyn VMStore, call: GuestCall) -> Result<()> {
879 let mut next = Some(call);
880 while let Some(call) = next.take() {
881 match call.kind {
882 GuestCallKind::DeliverEvent { instance, set } => {
883 let (event, waitable) =
884 match instance.get_event(store, call.thread.task, set, true)? {
885 Some(pair) => pair,
886 None => bail_bug!("delivering non-present event"),
887 };
888 let state = store.concurrent_state_mut()?;
889 let task = state.get_mut(call.thread.task)?;
890 let runtime_instance = task.instance;
891 let handle = waitable.map(|(_, v)| v).unwrap_or(0);
892
893 log::trace!(
894 "use callback to deliver event {event:?} to {:?} for {waitable:?}",
895 call.thread,
896 );
897
898 let old_thread = store.set_thread(call.thread)?;
899 log::trace!(
900 "GuestCallKind::DeliverEvent: replaced {old_thread:?} with {:?} as current thread",
901 call.thread
902 );
903
904 store.enter_instance(runtime_instance);
905
906 let Some(callback) = store
907 .concurrent_state_mut()?
908 .get_mut(call.thread.task)?
909 .callback
910 .take()
911 else {
912 bail_bug!("guest task callback field not present")
913 };
914
915 let code = callback(store, event, handle)?;
916
917 store
918 .concurrent_state_mut()?
919 .get_mut(call.thread.task)?
920 .callback = Some(callback);
921
922 store.exit_instance(runtime_instance)?;
923
924 store.set_thread(old_thread)?;
925
926 next = instance.handle_callback_code(
927 store,
928 call.thread,
929 runtime_instance.index,
930 code,
931 )?;
932
933 log::trace!(
934 "GuestCallKind::DeliverEvent: restored {old_thread:?} as current thread"
935 );
936 }
937 GuestCallKind::StartImplicit(fun) => {
938 next = fun(store)?;
939 }
940 GuestCallKind::StartExplicit(fun) => {
941 fun(store)?;
942 }
943 }
944 }
945
946 Ok(())
947}
948
949impl<T> Store<T> {
950 pub async fn run_concurrent<R>(&mut self, fun: impl AsyncFnOnce(&Accessor<T>) -> R) -> Result<R>
952 where
953 T: Send + 'static,
954 {
955 ensure!(
956 self.as_context().0.concurrency_support(),
957 "cannot use `run_concurrent` when Config::concurrency_support disabled",
958 );
959 self.as_context_mut().run_concurrent(fun).await
960 }
961
962 #[doc(hidden)]
963 pub fn assert_concurrent_state_empty(&mut self) {
964 self.as_context_mut().assert_concurrent_state_empty();
965 }
966
967 #[doc(hidden)]
968 pub fn concurrent_state_table_size(&mut self) -> usize {
969 self.as_context_mut().concurrent_state_table_size()
970 }
971
972 pub fn spawn(&mut self, task: impl AccessorTask<T, HasSelf<T>>) -> Result<JoinHandle>
974 where
975 T: 'static,
976 {
977 self.as_context_mut().spawn(task)
978 }
979}
980
981impl<T> StoreContextMut<'_, T> {
982 #[doc(hidden)]
993 pub fn assert_concurrent_state_empty(self) {
994 let store = self.0;
995 store
996 .store_data_mut()
997 .components
998 .assert_instance_states_empty();
999 let state = store.concurrent_state_mut().unwrap();
1000 assert!(
1001 state.table.get_mut().is_empty(),
1002 "non-empty table: {:?}",
1003 state.table.get_mut()
1004 );
1005 assert!(state.high_priority.is_empty());
1006 assert!(state.low_priority.is_empty());
1007 assert!(state.unforced_current_thread.is_none());
1008 assert!(state.futures_mut().unwrap().is_empty());
1009 assert!(state.global_error_context_ref_counts.is_empty());
1010 }
1011
1012 #[doc(hidden)]
1017 pub fn concurrent_state_table_size(&mut self) -> usize {
1018 self.0
1019 .concurrent_state_mut()
1020 .unwrap()
1021 .table
1022 .get_mut()
1023 .iter_mut()
1024 .count()
1025 }
1026
1027 pub fn spawn(mut self, task: impl AccessorTask<T>) -> Result<JoinHandle>
1037 where
1038 T: 'static,
1039 {
1040 let accessor = Accessor::new(StoreToken::new(self.as_context_mut()));
1041 self.spawn_with_accessor(accessor, task)
1042 }
1043
1044 fn spawn_with_accessor<D>(
1047 self,
1048 accessor: Accessor<T, D>,
1049 task: impl AccessorTask<T, D>,
1050 ) -> Result<JoinHandle>
1051 where
1052 T: 'static,
1053 D: HasData + ?Sized,
1054 {
1055 let (handle, future) = JoinHandle::run(async move { task.run(&accessor).await });
1059 self.0
1060 .concurrent_state_mut()?
1061 .push_future(Box::pin(async move { future.await.unwrap_or(Ok(())) }));
1062 Ok(handle)
1063 }
1064
1065 pub async fn run_concurrent<R>(self, fun: impl AsyncFnOnce(&Accessor<T>) -> R) -> Result<R>
1149 where
1150 T: Send + 'static,
1151 {
1152 ensure!(
1153 self.0.concurrency_support(),
1154 "cannot use `run_concurrent` when Config::concurrency_support disabled",
1155 );
1156 self.do_run_concurrent(fun, false).await
1157 }
1158
1159 pub(super) async fn run_concurrent_trap_on_idle<R>(
1160 self,
1161 fun: impl AsyncFnOnce(&Accessor<T>) -> R,
1162 ) -> Result<R>
1163 where
1164 T: Send + 'static,
1165 {
1166 self.do_run_concurrent(fun, true).await
1167 }
1168
1169 async fn do_run_concurrent<R>(
1170 mut self,
1171 fun: impl AsyncFnOnce(&Accessor<T>) -> R,
1172 trap_on_idle: bool,
1173 ) -> Result<R>
1174 where
1175 T: Send + 'static,
1176 {
1177 debug_assert!(self.0.concurrency_support());
1178 check_recursive_run();
1179 let token = StoreToken::new(self.as_context_mut());
1180
1181 struct Dropper<'a, T: 'static, V> {
1182 store: StoreContextMut<'a, T>,
1183 value: ManuallyDrop<V>,
1184 }
1185
1186 impl<'a, T, V> Drop for Dropper<'a, T, V> {
1187 fn drop(&mut self) {
1188 tls::set(self.store.0, || {
1189 unsafe { ManuallyDrop::drop(&mut self.value) }
1194 });
1195 }
1196 }
1197
1198 let accessor = &Accessor::new(token);
1199 let dropper = &mut Dropper {
1200 store: self,
1201 value: ManuallyDrop::new(fun(accessor)),
1202 };
1203 let future = unsafe { Pin::new_unchecked(dropper.value.deref_mut()) };
1205
1206 dropper
1207 .store
1208 .as_context_mut()
1209 .poll_until(future, trap_on_idle)
1210 .await
1211 }
1212
1213 async fn poll_until<R>(
1219 mut self,
1220 mut future: Pin<&mut impl Future<Output = R>>,
1221 trap_on_idle: bool,
1222 ) -> Result<R>
1223 where
1224 T: Send + 'static,
1225 {
1226 struct Reset<'a, T: 'static> {
1227 store: StoreContextMut<'a, T>,
1228 futures: Option<FuturesUnordered<HostTaskFuture>>,
1229 }
1230
1231 impl<'a, T> Drop for Reset<'a, T> {
1232 fn drop(&mut self) {
1233 if let Some(futures) = self.futures.take() {
1234 *self
1235 .store
1236 .0
1237 .concurrent_state_mut_already_forced_current_thread()
1238 .futures
1239 .get_mut() = Some(futures);
1240 }
1241 }
1242 }
1243
1244 loop {
1245 let futures = self.0.concurrent_state_mut()?.futures.get_mut().take();
1249 let mut reset = Reset {
1250 store: self.as_context_mut(),
1251 futures,
1252 };
1253 let mut next = match reset.futures.as_mut() {
1254 Some(f) => pin!(f.next()),
1255 None => bail_bug!("concurrent state missing futures field"),
1256 };
1257
1258 enum PollResult<R> {
1259 Complete(R),
1260 ProcessWork {
1261 ready: Vec<WorkItem>,
1262 low_priority: bool,
1263 },
1264 }
1265
1266 let result = future::poll_fn(|cx| {
1267 if let Poll::Ready(value) = tls::set(reset.store.0, || future.as_mut().poll(cx)) {
1270 return Poll::Ready(Ok(PollResult::Complete(value)));
1271 }
1272
1273 let next = match tls::set(reset.store.0, || next.as_mut().poll(cx)) {
1277 Poll::Ready(Some(output)) => {
1278 match output {
1279 Err(e) => return Poll::Ready(Err(e)),
1280 Ok(()) => {}
1281 }
1282 Poll::Ready(true)
1283 }
1284 Poll::Ready(None) => Poll::Ready(false),
1285 Poll::Pending => Poll::Pending,
1286 };
1287
1288 let state = reset.store.0.concurrent_state_mut()?;
1292 let mut ready = mem::take(&mut state.high_priority);
1293 let mut low_priority = false;
1294 if ready.is_empty() {
1295 if let Some(item) = state.low_priority.pop_back() {
1296 ready.push(item);
1297 low_priority = true;
1298 }
1299 }
1300 if !ready.is_empty() {
1301 return Poll::Ready(Ok(PollResult::ProcessWork {
1302 ready,
1303 low_priority,
1304 }));
1305 }
1306
1307 return match next {
1311 Poll::Ready(true) => {
1312 Poll::Ready(Ok(PollResult::ProcessWork {
1318 ready: Vec::new(),
1319 low_priority: false,
1320 }))
1321 }
1322 Poll::Ready(false) => {
1323 if let Poll::Ready(value) =
1327 tls::set(reset.store.0, || future.as_mut().poll(cx))
1328 {
1329 Poll::Ready(Ok(PollResult::Complete(value)))
1330 } else {
1331 if trap_on_idle {
1337 Poll::Ready(Err(Trap::AsyncDeadlock.into()))
1340 } else {
1341 Poll::Pending
1345 }
1346 }
1347 }
1348 Poll::Pending => Poll::Pending,
1353 };
1354 })
1355 .await;
1356
1357 drop(reset);
1361
1362 match result? {
1363 PollResult::Complete(value) => break Ok(value),
1366 PollResult::ProcessWork {
1369 ready,
1370 low_priority,
1371 } => {
1372 struct Dispose<'a, T: 'static, I: Iterator<Item = WorkItem>> {
1373 store: StoreContextMut<'a, T>,
1374 ready: I,
1375 }
1376
1377 impl<'a, T, I: Iterator<Item = WorkItem>> Drop for Dispose<'a, T, I> {
1378 fn drop(&mut self) {
1379 while let Some(item) = self.ready.next() {
1380 match item {
1381 WorkItem::ResumeFiber(mut fiber) => fiber.dispose(self.store.0),
1382 WorkItem::PushFuture(future) => {
1383 tls::set(self.store.0, move || drop(future))
1384 }
1385 _ => {}
1386 }
1387 }
1388 }
1389 }
1390
1391 let mut dispose = Dispose {
1392 store: self.as_context_mut(),
1393 ready: ready.into_iter(),
1394 };
1395
1396 if low_priority {
1418 dispose.store.0.yield_now().await
1419 }
1420
1421 while let Some(item) = dispose.ready.next() {
1422 dispose
1423 .store
1424 .as_context_mut()
1425 .handle_work_item(item)
1426 .await?;
1427 }
1428 }
1429 }
1430 }
1431 }
1432
1433 async fn handle_work_item(self, item: WorkItem) -> Result<()>
1435 where
1436 T: Send,
1437 {
1438 log::trace!("handle work item {item:?}");
1439 match item {
1440 WorkItem::PushFuture(future) => {
1441 self.0
1442 .concurrent_state_mut()?
1443 .futures_mut()?
1444 .push(future.into_inner());
1445 }
1446 WorkItem::ResumeFiber(fiber) => {
1447 self.0.resume_fiber(fiber).await?;
1448 }
1449 WorkItem::ResumeThread(_, thread) => {
1450 if let GuestThreadState::Ready { fiber, .. } = mem::replace(
1451 &mut self.0.concurrent_state_mut()?.get_mut(thread.thread)?.state,
1452 GuestThreadState::Running,
1453 ) {
1454 self.0.resume_fiber(fiber).await?;
1455 } else {
1456 bail_bug!("cannot resume non-pending thread {thread:?}");
1457 }
1458 }
1459 WorkItem::GuestCall(_, call) => {
1460 if call.is_ready(self.0)? {
1461 self.run_on_worker(WorkerItem::GuestCall(call)).await?;
1462 } else {
1463 let state = self.0.concurrent_state_mut()?;
1464 let task = state.get_mut(call.thread.task)?;
1465 if !task.starting_sent {
1466 task.starting_sent = true;
1467 if let GuestCallKind::StartImplicit(_) = &call.kind {
1468 Waitable::Guest(call.thread.task).set_event(
1469 state,
1470 Some(Event::Subtask {
1471 status: Status::Starting,
1472 }),
1473 )?;
1474 }
1475 }
1476
1477 let instance = state.get_mut(call.thread.task)?.instance;
1478 self.0
1479 .instance_state(instance)
1480 .concurrent_state()
1481 .pending
1482 .insert(call.thread, call.kind);
1483 }
1484 }
1485 WorkItem::WorkerFunction(fun) => {
1486 self.run_on_worker(WorkerItem::Function(fun)).await?;
1487 }
1488 }
1489
1490 Ok(())
1491 }
1492
1493 async fn run_on_worker(self, item: WorkerItem) -> Result<()>
1495 where
1496 T: Send,
1497 {
1498 let worker = if let Some(fiber) = self.0.concurrent_state_mut()?.worker.take() {
1499 fiber
1500 } else {
1501 fiber::make_fiber(self.0, move |store| {
1502 loop {
1503 let Some(item) = store.concurrent_state_mut()?.worker_item.take() else {
1504 bail_bug!("worker_item not present when resuming fiber")
1505 };
1506 match item {
1507 WorkerItem::GuestCall(call) => handle_guest_call(store, call)?,
1508 WorkerItem::Function(fun) => fun.into_inner()(store)?,
1509 }
1510
1511 store.suspend(SuspendReason::NeedWork)?;
1512 }
1513 })?
1514 };
1515
1516 let worker_item = &mut self.0.concurrent_state_mut()?.worker_item;
1517 assert!(worker_item.is_none());
1518 *worker_item = Some(item);
1519
1520 self.0.resume_fiber(worker).await
1521 }
1522
1523 pub(crate) fn wrap_call<F, R>(self, closure: F) -> impl Future<Output = Result<R>> + 'static
1528 where
1529 T: 'static,
1530 F: FnOnce(&Accessor<T>) -> Pin<Box<dyn Future<Output = Result<R>> + Send + '_>>
1531 + Send
1532 + Sync
1533 + 'static,
1534 R: Send + Sync + 'static,
1535 {
1536 let token = StoreToken::new(self);
1537 async move {
1538 let mut accessor = Accessor::new(token);
1539 closure(&mut accessor).await
1540 }
1541 }
1542
1543 pub fn async_call_stack(&mut self) -> Result<impl Iterator<Item = GuestTaskId>> {
1553 let mut cur = Some(self.0.current_thread()?);
1554 let state = self.0.concurrent_state_mut()?;
1555 Ok(core::iter::from_fn(move || {
1556 while let Some(t) = cur {
1557 cur = state.parent(t);
1558 if let Some(thread) = t.guest() {
1559 return Some(GuestTaskId(thread.task));
1560 }
1561 }
1562
1563 None
1564 }))
1565 }
1566}
1567
1568impl StoreOpaque {
1569 pub(crate) fn current_thread(&mut self) -> Result<CurrentThread> {
1572 if !self.concurrency_support() {
1574 return Ok(CurrentThread::None);
1575 }
1576
1577 if !self
1580 .vm_store_context_mut()
1581 .current_thread_mut()
1582 .is_deferred()
1583 {
1584 return Ok(self
1585 .concurrent_state_mut_already_forced_current_thread()
1586 .unforced_current_thread);
1587 }
1588
1589 let state = self.concurrent_state_mut_without_forcing_current_thread();
1598 let id = match state.unforced_current_thread.guest().copied() {
1599 Some(thread) => state.get_mut(thread.task)?.instance.instance,
1600 None => bail_bug!("deferred component-model thread with non-guest base"),
1601 };
1602
1603 let mut frames = Vec::new();
1606 let mut cur = *self.vm_store_context_mut().current_thread_mut();
1607 while let Some(ptr) = cur.as_deferred() {
1608 let deferred = unsafe { ptr.as_non_null().as_ref() };
1613 frames.push((
1614 deferred.callee_async != 0,
1615 deferred.callee_instance,
1616 deferred.saved_context,
1617 ));
1618 cur = deferred.parent;
1619 }
1620
1621 *self.vm_store_context_mut().current_thread_mut() = VMLazyThread::forced();
1625
1626 let current_context = *self.vm_store_context_mut().component_context_mut();
1629
1630 for (callee_async, callee_instance, saved_context) in frames.into_iter().rev() {
1634 *self.vm_store_context_mut().component_context_mut() = saved_context;
1638 let callee = RuntimeInstance {
1639 instance: id,
1640 index: RuntimeComponentInstanceIndex::from_u32(callee_instance),
1641 };
1642 self.enter_guest_sync_call(None, callee_async, callee)?;
1643 }
1644
1645 *self.vm_store_context_mut().component_context_mut() = current_context;
1647
1648 Ok(self
1649 .concurrent_state_mut_without_forcing_current_thread()
1650 .unforced_current_thread)
1651 }
1652
1653 fn current_guest_thread(&mut self) -> Result<QualifiedThreadId> {
1654 match self.current_thread()?.guest() {
1655 Some(id) => Ok(*id),
1656 None => bail_bug!("current thread is not a guest thread"),
1657 }
1658 }
1659
1660 fn current_host_thread(&mut self) -> Result<TableId<HostTask>> {
1661 match self.current_thread()?.host() {
1662 Some(id) => Ok(id),
1663 None => bail_bug!("current thread is not a host thread"),
1664 }
1665 }
1666
1667 fn take_pending_cancellation(&mut self) -> Result<bool> {
1670 let thread = self.current_guest_thread()?;
1671 let task = self.concurrent_state_mut()?.get_mut(thread.task)?;
1672 if let Some(Event::Cancelled) = task.event {
1673 task.event.take();
1674 return Ok(true);
1675 }
1676 Ok(false)
1677 }
1678
1679 pub(crate) fn enter_guest_sync_call(
1691 &mut self,
1692 guest_caller: Option<RuntimeInstance>,
1693 callee_async: bool,
1694 callee: RuntimeInstance,
1695 ) -> Result<()> {
1696 log::trace!("enter sync call {callee:?}");
1697 if !self.concurrency_support() {
1698 return self.enter_call_not_concurrent();
1699 }
1700
1701 let thread = self.current_thread()?;
1702 let state = self.concurrent_state_mut()?;
1703 let instance = if let Some(thread) = thread.guest() {
1704 Some(state.get_mut(thread.task)?.instance)
1705 } else {
1706 None
1707 };
1708 if guest_caller.is_some() {
1709 debug_assert_eq!(instance, guest_caller);
1710 }
1711 let guest_thread = GuestTask::new(
1712 state,
1713 Box::new(move |_, _| bail_bug!("cannot lower params in sync call")),
1714 LiftResult {
1715 lift: Box::new(move |_, _| bail_bug!("cannot lift result in sync call")),
1716 ty: TypeTupleIndex::reserved_value(),
1717 memory: None,
1718 string_encoding: StringEncoding::Utf8,
1719 },
1720 if let Some(thread) = thread.guest() {
1721 Caller::Guest { thread: *thread }
1722 } else {
1723 Caller::Host {
1724 tx: None,
1725 host_future_present: false,
1726 caller: thread,
1727 }
1728 },
1729 None,
1730 callee,
1731 callee_async,
1732 )?;
1733
1734 Instance::from_wasmtime(self, callee.instance).add_guest_thread_to_instance_table(
1735 guest_thread.thread,
1736 self,
1737 callee.index,
1738 )?;
1739 self.set_thread(guest_thread)?;
1740
1741 Ok(())
1742 }
1743
1744 pub(crate) fn exit_guest_sync_call(&mut self) -> Result<()> {
1752 if !self.concurrency_support() {
1753 return Ok(self.exit_call_not_concurrent());
1754 }
1755 let thread = match self.set_thread(CurrentThread::None)?.guest() {
1756 Some(t) => *t,
1757 None => bail_bug!("expected task when exiting"),
1758 };
1759 let task = self.concurrent_state_mut()?.get_mut(thread.task)?;
1760 let instance = task.instance;
1761 let caller = match &task.caller {
1762 &Caller::Guest { thread } => thread.into(),
1763 &Caller::Host { caller, .. } => caller,
1764 };
1765 task.lift_result = None;
1766 task.exited = true;
1767 self.set_thread(caller)?;
1768
1769 log::trace!("exit sync call {instance:?}");
1770 self.cleanup_thread(thread, instance, CleanupTask::Yes)?;
1771
1772 Ok(())
1773 }
1774
1775 pub(crate) fn host_task_create(&mut self) -> Result<Option<TableId<HostTask>>> {
1783 if !self.concurrency_support() {
1784 self.enter_call_not_concurrent()?;
1785 return Ok(None);
1786 }
1787 let caller = self.current_guest_thread()?;
1788 let state = self.concurrent_state_mut()?;
1789 let task = state.push(HostTask::new(caller, HostTaskState::CalleeStarted))?;
1790 log::trace!("new host task {task:?}");
1791 self.set_thread(task)?;
1792 Ok(Some(task))
1793 }
1794
1795 pub fn host_task_reenter_caller(&mut self) -> Result<()> {
1801 if !self.concurrency_support() {
1802 return Ok(());
1803 }
1804 let task = self.current_host_thread()?;
1805 let caller = self.concurrent_state_mut()?.get_mut(task)?.caller;
1806 self.set_thread(caller)?;
1807 Ok(())
1808 }
1809
1810 pub(crate) fn host_task_delete(&mut self, task: Option<TableId<HostTask>>) -> Result<()> {
1817 match task {
1818 Some(task) => {
1819 log::trace!("delete host task {task:?}");
1820 self.concurrent_state_mut()?.delete(task)?;
1821 }
1822 None => {
1823 self.exit_call_not_concurrent();
1824 }
1825 }
1826 Ok(())
1827 }
1828
1829 pub(crate) fn may_enter(&mut self, instance: RuntimeInstance) -> Result<bool> {
1837 if self.trapped() {
1838 return Ok(false);
1839 }
1840 if !self.concurrency_support() {
1841 return Ok(true);
1842 }
1843 let mut cur = Some(self.current_thread()?);
1844 let state = self.concurrent_state_mut()?;
1845 while let Some(t) = cur {
1846 if let Some(thread) = t.guest() {
1847 let task = state.get_mut(thread.task)?;
1848 if task.instance.instance == instance.instance {
1855 return Ok(false);
1856 }
1857 }
1858 cur = state.parent(t);
1859 }
1860 Ok(true)
1861 }
1862
1863 fn instance_state(&mut self, instance: RuntimeInstance) -> &mut InstanceState {
1866 self.component_instance_mut(instance.instance)
1867 .instance_state(instance.index)
1868 }
1869
1870 fn set_thread(&mut self, thread: impl Into<CurrentThread>) -> Result<CurrentThread> {
1876 let thread = thread.into();
1877 let state = self.concurrent_state_mut()?;
1878 let old_thread = mem::replace(&mut state.unforced_current_thread, thread);
1879
1880 if let Some(old_thread) = old_thread.guest() {
1888 let old_context = *self.vm_store_context_mut().component_context_mut();
1889 self.concurrent_state_mut()?
1890 .get_mut(old_thread.thread)?
1891 .context = old_context;
1892 }
1893 if cfg!(debug_assertions) {
1894 *self.vm_store_context_mut().component_context_mut() =
1895 [u32::MAX; NUM_COMPONENT_CONTEXT_SLOTS];
1896 }
1897 if let Some(thread) = thread.guest() {
1898 let thread = self.concurrent_state_mut()?.get_mut(thread.thread)?;
1899 let context = thread.context;
1900 if cfg!(debug_assertions) {
1901 thread.context = [u32::MAX; NUM_COMPONENT_CONTEXT_SLOTS];
1902 }
1903 *self.vm_store_context_mut().component_context_mut() = context;
1904 }
1905
1906 let state = self.concurrent_state_mut()?;
1914 if let Some(old_thread) = old_thread.guest() {
1915 let instance = state.get_mut(old_thread.task)?.instance.instance;
1916 self.component_instance_mut(instance)
1917 .set_task_may_block(false)
1918 }
1919
1920 if thread.guest().is_some() {
1921 self.set_task_may_block()?;
1922 }
1923
1924 *self.vm_store_context_mut().current_thread_mut() = if thread.is_none() {
1926 VMLazyThread::none()
1927 } else {
1928 VMLazyThread::forced()
1929 };
1930
1931 Ok(old_thread)
1932 }
1933
1934 fn set_task_may_block(&mut self) -> Result<()> {
1937 let guest_thread = self.current_guest_thread()?;
1938 let state = self.concurrent_state_mut()?;
1939 let instance = state.get_mut(guest_thread.task)?.instance.instance;
1940 let may_block = self.concurrent_state_mut()?.may_block(guest_thread.task)?;
1941 self.component_instance_mut(instance)
1942 .set_task_may_block(may_block);
1943 Ok(())
1944 }
1945
1946 pub(crate) fn check_blocking(&mut self) -> Result<()> {
1947 if !self.concurrency_support() {
1948 return Ok(());
1949 }
1950 let task = self.current_guest_thread()?.task;
1951 let state = self.concurrent_state_mut()?;
1952 let instance = state.get_mut(task)?.instance.instance;
1953 let task_may_block = self.component_instance(instance).get_task_may_block();
1954
1955 if task_may_block {
1956 Ok(())
1957 } else {
1958 Err(Trap::CannotBlockSyncTask.into())
1959 }
1960 }
1961
1962 fn enter_instance(&mut self, instance: RuntimeInstance) {
1966 log::trace!("enter {instance:?}");
1967 self.instance_state(instance)
1968 .concurrent_state()
1969 .do_not_enter = true;
1970 }
1971
1972 fn exit_instance(&mut self, instance: RuntimeInstance) -> Result<()> {
1976 log::trace!("exit {instance:?}");
1977 self.instance_state(instance)
1978 .concurrent_state()
1979 .do_not_enter = false;
1980 self.partition_pending(instance)
1981 }
1982
1983 fn partition_pending(&mut self, instance: RuntimeInstance) -> Result<()> {
1988 for (thread, kind) in
1989 mem::take(&mut self.instance_state(instance).concurrent_state().pending).into_iter()
1990 {
1991 let call = GuestCall { thread, kind };
1992 if call.is_ready(self)? {
1993 self.concurrent_state_mut()?
1994 .push_high_priority(WorkItem::GuestCall(instance.index, call));
1995 } else {
1996 self.instance_state(instance)
1997 .concurrent_state()
1998 .pending
1999 .insert(call.thread, call.kind);
2000 }
2001 }
2002
2003 Ok(())
2004 }
2005
2006 pub(crate) fn backpressure_modify(
2008 &mut self,
2009 caller_instance: RuntimeInstance,
2010 modify: impl FnOnce(u16) -> Option<u16>,
2011 ) -> Result<()> {
2012 let state = self.instance_state(caller_instance).concurrent_state();
2013 let old = state.backpressure;
2014 let new = modify(old).ok_or_else(|| Trap::BackpressureOverflow)?;
2015 state.backpressure = new;
2016
2017 if old > 0 && new == 0 {
2018 self.partition_pending(caller_instance)?;
2021 }
2022
2023 Ok(())
2024 }
2025
2026 async fn resume_fiber(&mut self, fiber: StoreFiber<'static>) -> Result<()> {
2029 let old_thread = self.current_thread()?;
2030 log::trace!("resume_fiber: save current thread {old_thread:?}");
2031
2032 let fiber = fiber::resolve_or_release(self, fiber).await?;
2033
2034 self.set_thread(old_thread)?;
2035
2036 let state = self.concurrent_state_mut()?;
2037
2038 if let Some(ot) = old_thread.guest() {
2039 state.get_mut(ot.thread)?.state = GuestThreadState::Running;
2040 }
2041 log::trace!("resume_fiber: restore current thread {old_thread:?}");
2042
2043 if let Some(mut fiber) = fiber {
2044 log::trace!("resume_fiber: suspend reason {:?}", &state.suspend_reason);
2045 let reason = match state.suspend_reason.take() {
2047 Some(r) => r,
2048 None => bail_bug!("suspend reason missing when resuming fiber"),
2049 };
2050 match reason {
2051 SuspendReason::NeedWork => {
2052 if state.worker.is_none() {
2053 state.worker = Some(fiber);
2054 } else {
2055 fiber.dispose(self);
2056 }
2057 }
2058 SuspendReason::Yielding {
2059 thread,
2060 cancellable,
2061 ..
2062 } => {
2063 state.get_mut(thread.thread)?.state =
2064 GuestThreadState::Ready { fiber, cancellable };
2065 let instance = state.get_mut(thread.task)?.instance.index;
2066 state.push_low_priority(WorkItem::ResumeThread(instance, thread));
2067 }
2068 SuspendReason::ExplicitlySuspending { thread, .. } => {
2069 state.get_mut(thread.thread)?.state = GuestThreadState::Suspended(fiber);
2070 }
2071 SuspendReason::Waiting { set, thread, .. } => {
2072 let old = state
2073 .get_mut(set)?
2074 .waiting
2075 .insert(thread, WaitMode::Fiber(fiber));
2076 assert!(old.is_none());
2077 }
2078 };
2079 } else {
2080 log::trace!("resume_fiber: fiber has exited");
2081 }
2082
2083 Ok(())
2084 }
2085
2086 fn suspend(&mut self, reason: SuspendReason) -> Result<()> {
2092 log::trace!("suspend fiber: {reason:?}");
2093
2094 let task = match &reason {
2098 SuspendReason::Yielding { thread, .. }
2099 | SuspendReason::Waiting { thread, .. }
2100 | SuspendReason::ExplicitlySuspending { thread, .. } => Some(thread.task),
2101 SuspendReason::NeedWork => None,
2102 };
2103
2104 let old_guest_thread = if task.is_some() {
2105 self.current_thread()?
2106 } else {
2107 CurrentThread::None
2108 };
2109
2110 debug_assert!(
2116 matches!(
2117 reason,
2118 SuspendReason::ExplicitlySuspending {
2119 skip_may_block_check: true,
2120 ..
2121 } | SuspendReason::Waiting {
2122 skip_may_block_check: true,
2123 ..
2124 } | SuspendReason::Yielding {
2125 skip_may_block_check: true,
2126 ..
2127 }
2128 ) || old_guest_thread
2129 .guest()
2130 .map(|thread| self.concurrent_state_mut()?.may_block(thread.task))
2131 .transpose()?
2132 .unwrap_or(true)
2133 );
2134
2135 let suspend_reason = &mut self.concurrent_state_mut()?.suspend_reason;
2136 assert!(suspend_reason.is_none());
2137 *suspend_reason = Some(reason);
2138
2139 self.with_blocking(|_, cx| cx.suspend(StoreFiberYield::ReleaseStore))?;
2140
2141 if task.is_some() {
2142 self.set_thread(old_guest_thread)?;
2143 }
2144
2145 Ok(())
2146 }
2147
2148 fn wait_for_event(&mut self, waitable: Waitable) -> Result<()> {
2149 let caller = self.current_guest_thread()?;
2150 let state = self.concurrent_state_mut()?;
2151
2152 if waitable.common(state)?.set.is_some() {
2153 bail!(Trap::WaitableSyncAndAsync);
2154 }
2155
2156 let set = state.get_mut(caller.thread)?.sync_call_set;
2157 waitable.join(state, Some(set))?;
2158 self.suspend(SuspendReason::Waiting {
2159 set,
2160 thread: caller,
2161 skip_may_block_check: false,
2162 })?;
2163 let state = self.concurrent_state_mut()?;
2164 waitable.join(state, None)
2165 }
2166
2167 fn cleanup_thread(
2189 &mut self,
2190 guest_thread: QualifiedThreadId,
2191 runtime_instance: RuntimeInstance,
2192 cleanup_task: CleanupTask,
2193 ) -> Result<()> {
2194 let state = self.concurrent_state_mut()?;
2195 let thread_data = state.get_mut(guest_thread.thread)?;
2196 let sync_call_set = thread_data.sync_call_set;
2197 if let Some(guest_id) = thread_data.instance_rep {
2198 self.instance_state(runtime_instance)
2199 .thread_handle_table()
2200 .guest_thread_remove(guest_id)?;
2201 }
2202 let state = self.concurrent_state_mut()?;
2203
2204 for waitable in mem::take(&mut state.get_mut(sync_call_set)?.ready) {
2206 if let Some(Event::Subtask {
2207 status: Status::Returned | Status::ReturnCancelled,
2208 }) = waitable.common(state)?.event
2209 {
2210 waitable.delete_from(state)?;
2211 }
2212 }
2213
2214 state.delete(guest_thread.thread)?;
2215 state.delete(sync_call_set)?;
2216 let task = state.get_mut(guest_thread.task)?;
2217 task.threads.remove(&guest_thread.thread);
2218
2219 if task.threads.is_empty() && !task.returned_or_cancelled() {
2220 bail!(Trap::NoAsyncResult);
2221 }
2222 let ready_to_delete = task.ready_to_delete();
2223
2224 if !task.decremented_interesting_task_count && task.exited && task.returned_or_cancelled() {
2225 task.decremented_interesting_task_count = true;
2226
2227 debug_assert!(state.interesting_tasks > 0);
2228 state.interesting_tasks -= 1;
2229 if state.interesting_tasks == 0
2230 && let Some(waker) = state.interesting_tasks_empty_waker.take()
2231 {
2232 waker.wake();
2233 }
2234 }
2235
2236 match cleanup_task {
2237 CleanupTask::Yes => {
2238 if ready_to_delete {
2239 Waitable::Guest(guest_thread.task).delete_from(state)?;
2240 }
2241 }
2242 CleanupTask::No => {}
2243 }
2244
2245 Ok(())
2246 }
2247
2248 fn cancel_guest_subtask_without_lowered_parameters(
2261 &mut self,
2262 caller_instance: RuntimeInstance,
2263 guest_task: TableId<GuestTask>,
2264 ) -> Result<()> {
2265 let concurrent_state = self.concurrent_state_mut()?;
2266 let task = concurrent_state.get_mut(guest_task)?;
2267 assert!(!task.already_lowered_parameters());
2268 task.lower_params = None;
2272 task.lift_result = None;
2273 task.exited = true;
2274 let instance = task.instance;
2275
2276 assert_eq!(1, task.threads.len());
2279 let thread = *task.threads.iter().next().unwrap();
2280 self.cleanup_thread(
2281 QualifiedThreadId {
2282 task: guest_task,
2283 thread,
2284 },
2285 caller_instance,
2286 CleanupTask::No,
2287 )?;
2288
2289 let pending = &mut self.instance_state(instance).concurrent_state().pending;
2291 let pending_count = pending.len();
2292 pending.retain(|thread, _| thread.task != guest_task);
2293 if pending.len() == pending_count {
2295 bail!(Trap::SubtaskCancelAfterTerminal);
2296 }
2297 Ok(())
2298 }
2299}
2300
2301enum CleanupTask {
2302 Yes,
2303 No,
2304}
2305
2306impl Instance {
2307 fn get_event(
2310 self,
2311 store: &mut StoreOpaque,
2312 guest_task: TableId<GuestTask>,
2313 set: Option<TableId<WaitableSet>>,
2314 cancellable: bool,
2315 ) -> Result<Option<(Event, Option<(Waitable, u32)>)>> {
2316 let state = store.concurrent_state_mut()?;
2317
2318 let event = &mut state.get_mut(guest_task)?.event;
2319 if let Some(ev) = event
2320 && (cancellable || !matches!(ev, Event::Cancelled))
2321 {
2322 log::trace!("deliver event {ev:?} to {guest_task:?}");
2323 let ev = *ev;
2324 *event = None;
2325 return Ok(Some((ev, None)));
2326 }
2327
2328 let set = match set {
2329 Some(set) => set,
2330 None => return Ok(None),
2331 };
2332 let waitable = match state.get_mut(set)?.ready.pop_first() {
2333 Some(v) => v,
2334 None => return Ok(None),
2335 };
2336
2337 let common = waitable.common(state)?;
2338 let handle = match common.handle {
2339 Some(h) => h,
2340 None => bail_bug!("handle not set when delivering event"),
2341 };
2342 let event = match common.event.take() {
2343 Some(e) => e,
2344 None => bail_bug!("event not set when delivering event"),
2345 };
2346
2347 log::trace!(
2348 "deliver event {event:?} to {guest_task:?} for {waitable:?} (handle {handle}); set {set:?}"
2349 );
2350
2351 waitable.on_delivery(store, self, event)?;
2352
2353 Ok(Some((event, Some((waitable, handle)))))
2354 }
2355
2356 fn handle_callback_code(
2362 self,
2363 store: &mut StoreOpaque,
2364 guest_thread: QualifiedThreadId,
2365 runtime_instance: RuntimeComponentInstanceIndex,
2366 code: u32,
2367 ) -> Result<Option<GuestCall>> {
2368 let (code, set) = unpack_callback_code(code);
2369
2370 log::trace!("received callback code from {guest_thread:?}: {code} (set: {set})");
2371
2372 let state = store.concurrent_state_mut()?;
2373
2374 let get_set = |store: &mut StoreOpaque, handle| -> Result<_> {
2375 let set = store
2376 .instance_state(self.runtime_instance(runtime_instance))
2377 .handle_table()
2378 .waitable_set_rep(handle)?;
2379
2380 Ok(TableId::<WaitableSet>::new(set))
2381 };
2382
2383 Ok(match code {
2384 callback_code::EXIT => {
2385 log::trace!("implicit thread {guest_thread:?} completed");
2386 let task = store.concurrent_state_mut()?.get_mut(guest_thread.task)?;
2387 task.exited = true;
2388 task.callback = None;
2389 store.cleanup_thread(
2390 guest_thread,
2391 self.runtime_instance(runtime_instance),
2392 CleanupTask::Yes,
2393 )?;
2394 None
2395 }
2396 callback_code::YIELD => {
2397 let task = state.get_mut(guest_thread.task)?;
2398 if let Some(event) = task.event {
2403 assert!(matches!(event, Event::None | Event::Cancelled));
2404 } else {
2405 task.event = Some(Event::None);
2406 }
2407 let call = GuestCall {
2408 thread: guest_thread,
2409 kind: GuestCallKind::DeliverEvent {
2410 instance: self,
2411 set: None,
2412 },
2413 };
2414 if state.may_block(guest_thread.task)? {
2415 state.push_low_priority(WorkItem::GuestCall(runtime_instance, call));
2418 None
2419 } else {
2420 Some(call)
2424 }
2425 }
2426 callback_code::WAIT => {
2427 state.check_blocking_for(guest_thread.task)?;
2430
2431 let set = get_set(store, set)?;
2432 let state = store.concurrent_state_mut()?;
2433
2434 if state.get_mut(guest_thread.task)?.event.is_some()
2435 || !state.get_mut(set)?.ready.is_empty()
2436 {
2437 state.push_high_priority(WorkItem::GuestCall(
2439 runtime_instance,
2440 GuestCall {
2441 thread: guest_thread,
2442 kind: GuestCallKind::DeliverEvent {
2443 instance: self,
2444 set: Some(set),
2445 },
2446 },
2447 ));
2448 } else {
2449 let old = state
2457 .get_mut(guest_thread.thread)?
2458 .wake_on_cancel
2459 .replace(set);
2460 if !old.is_none() {
2461 bail_bug!("thread unexpectedly had wake_on_cancel set");
2462 }
2463 let old = state
2464 .get_mut(set)?
2465 .waiting
2466 .insert(guest_thread, WaitMode::Callback(self));
2467 if !old.is_none() {
2468 bail_bug!("set's waiting set already had this thread registered");
2469 }
2470 }
2471 None
2472 }
2473 _ => bail!(Trap::UnsupportedCallbackCode),
2474 })
2475 }
2476
2477 unsafe fn queue_call<T: 'static>(
2484 self,
2485 mut store: StoreContextMut<T>,
2486 guest_thread: QualifiedThreadId,
2487 callee: SendSyncPtr<VMFuncRef>,
2488 param_count: usize,
2489 result_count: usize,
2490 async_: bool,
2491 callback: Option<SendSyncPtr<VMFuncRef>>,
2492 post_return: Option<SendSyncPtr<VMFuncRef>>,
2493 ) -> Result<()> {
2494 unsafe fn make_call<T: 'static>(
2509 store: StoreContextMut<T>,
2510 guest_thread: QualifiedThreadId,
2511 callee: SendSyncPtr<VMFuncRef>,
2512 param_count: usize,
2513 result_count: usize,
2514 ) -> impl FnOnce(&mut dyn VMStore) -> Result<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>
2515 + Send
2516 + Sync
2517 + 'static
2518 + use<T> {
2519 let token = StoreToken::new(store);
2520 move |store: &mut dyn VMStore| {
2521 let mut storage = [MaybeUninit::uninit(); MAX_FLAT_PARAMS];
2522
2523 store
2524 .concurrent_state_mut()?
2525 .get_mut(guest_thread.thread)?
2526 .state = GuestThreadState::Running;
2527 let task = store.concurrent_state_mut()?.get_mut(guest_thread.task)?;
2528 let lower = match task.lower_params.take() {
2529 Some(l) => l,
2530 None => bail_bug!("lower_params missing"),
2531 };
2532
2533 lower(store, &mut storage[..param_count])?;
2534
2535 let mut store = token.as_context_mut(store);
2536
2537 unsafe {
2540 crate::Func::call_unchecked_raw(
2541 &mut store,
2542 callee.as_non_null(),
2543 NonNull::new(
2544 &mut storage[..param_count.max(result_count)]
2545 as *mut [MaybeUninit<ValRaw>] as _,
2546 )
2547 .unwrap(),
2548 )?;
2549 }
2550
2551 Ok(storage)
2552 }
2553 }
2554
2555 let call = unsafe {
2559 make_call(
2560 store.as_context_mut(),
2561 guest_thread,
2562 callee,
2563 param_count,
2564 result_count,
2565 )
2566 };
2567
2568 let callee_instance = store
2569 .0
2570 .concurrent_state_mut()?
2571 .get_mut(guest_thread.task)?
2572 .instance;
2573
2574 let fun = if callback.is_some() {
2575 assert!(async_);
2576
2577 Box::new(move |store: &mut dyn VMStore| {
2578 self.add_guest_thread_to_instance_table(
2579 guest_thread.thread,
2580 store,
2581 callee_instance.index,
2582 )?;
2583 let old_thread = store.set_thread(guest_thread)?;
2584 log::trace!(
2585 "stackless call: replaced {old_thread:?} with {guest_thread:?} as current thread"
2586 );
2587
2588 store.enter_instance(callee_instance);
2589
2590 let storage = call(store)?;
2597
2598 store.exit_instance(callee_instance)?;
2599
2600 store.set_thread(old_thread)?;
2601 let state = store.concurrent_state_mut()?;
2602 if let Some(t) = old_thread.guest() {
2603 state.get_mut(t.thread)?.state = GuestThreadState::Running;
2604 }
2605 log::trace!("stackless call: restored {old_thread:?} as current thread");
2606
2607 let code = unsafe { storage[0].assume_init() }.get_i32() as u32;
2610
2611 self.handle_callback_code(store, guest_thread, callee_instance.index, code)
2612 })
2613 as Box<dyn FnOnce(&mut dyn VMStore) -> Result<Option<GuestCall>> + Send + Sync>
2614 } else {
2615 let token = StoreToken::new(store.as_context_mut());
2616 Box::new(move |store: &mut dyn VMStore| {
2617 self.add_guest_thread_to_instance_table(
2618 guest_thread.thread,
2619 store,
2620 callee_instance.index,
2621 )?;
2622 let old_thread = store.set_thread(guest_thread)?;
2623 log::trace!(
2624 "sync/async-stackful call: replaced {old_thread:?} with {guest_thread:?} as current thread",
2625 );
2626 let flags = self.id().get(store).instance_flags(callee_instance.index);
2627
2628 if !async_ {
2632 store.enter_instance(callee_instance);
2633 }
2634
2635 let storage = call(store)?;
2642
2643 if !async_ {
2644 let lift = {
2650 store.exit_instance(callee_instance)?;
2651
2652 let state = store.concurrent_state_mut()?;
2653 if !state.get_mut(guest_thread.task)?.result.is_none() {
2654 bail_bug!("task has already produced a result");
2655 }
2656
2657 match state.get_mut(guest_thread.task)?.lift_result.take() {
2658 Some(lift) => lift,
2659 None => bail_bug!("lift_result field is missing"),
2660 }
2661 };
2662
2663 let result = (lift.lift)(store, unsafe {
2666 mem::transmute::<&[MaybeUninit<ValRaw>], &[ValRaw]>(
2667 &storage[..result_count],
2668 )
2669 })?;
2670
2671 let post_return_arg = match result_count {
2672 0 => ValRaw::i32(0),
2673 1 => unsafe { storage[0].assume_init() },
2676 _ => unreachable!(),
2677 };
2678
2679 unsafe {
2680 call_post_return(
2681 token.as_context_mut(store),
2682 post_return.map(|v| v.as_non_null()),
2683 post_return_arg,
2684 flags,
2685 )?;
2686 }
2687
2688 self.task_complete(store, guest_thread.task, result, Status::Returned)?;
2689 }
2690
2691 store.set_thread(old_thread)?;
2692
2693 store
2694 .concurrent_state_mut()?
2695 .get_mut(guest_thread.task)?
2696 .exited = true;
2697
2698 store.cleanup_thread(guest_thread, callee_instance, CleanupTask::Yes)?;
2700 Ok(None)
2701 })
2702 };
2703
2704 store
2705 .0
2706 .concurrent_state_mut()?
2707 .push_high_priority(WorkItem::GuestCall(
2708 callee_instance.index,
2709 GuestCall {
2710 thread: guest_thread,
2711 kind: GuestCallKind::StartImplicit(fun),
2712 },
2713 ));
2714
2715 Ok(())
2716 }
2717
2718 unsafe fn prepare_call<T: 'static>(
2731 self,
2732 mut store: StoreContextMut<T>,
2733 start: NonNull<VMFuncRef>,
2734 return_: NonNull<VMFuncRef>,
2735 caller_instance: RuntimeComponentInstanceIndex,
2736 callee_instance: RuntimeComponentInstanceIndex,
2737 task_return_type: TypeTupleIndex,
2738 callee_async: bool,
2739 memory: *mut VMMemoryDefinition,
2740 string_encoding: StringEncoding,
2741 caller_info: CallerInfo,
2742 ) -> Result<()> {
2743 if let (CallerInfo::Sync { .. }, true) = (&caller_info, callee_async) {
2744 store.0.check_blocking()?;
2748 }
2749
2750 enum ResultInfo {
2751 Heap { results: u32 },
2752 Stack { result_count: u32 },
2753 }
2754
2755 let result_info = match &caller_info {
2756 CallerInfo::Async {
2757 has_result: true,
2758 params,
2759 } => ResultInfo::Heap {
2760 results: match params.last() {
2761 Some(r) => r.get_u32(),
2762 None => bail_bug!("retptr missing"),
2763 },
2764 },
2765 CallerInfo::Async {
2766 has_result: false, ..
2767 } => ResultInfo::Stack { result_count: 0 },
2768 CallerInfo::Sync {
2769 result_count,
2770 params,
2771 } if *result_count > u32::try_from(MAX_FLAT_RESULTS)? => ResultInfo::Heap {
2772 results: match params.last() {
2773 Some(r) => r.get_u32(),
2774 None => bail_bug!("arg ptr missing"),
2775 },
2776 },
2777 CallerInfo::Sync { result_count, .. } => ResultInfo::Stack {
2778 result_count: *result_count,
2779 },
2780 };
2781
2782 let sync_caller = matches!(caller_info, CallerInfo::Sync { .. });
2783
2784 let start = SendSyncPtr::new(start);
2788 let return_ = SendSyncPtr::new(return_);
2789 let token = StoreToken::new(store.as_context_mut());
2790 let old_thread = store.0.current_guest_thread()?;
2791 let state = store.0.concurrent_state_mut()?;
2792
2793 debug_assert_eq!(
2794 state.get_mut(old_thread.task)?.instance,
2795 self.runtime_instance(caller_instance)
2796 );
2797
2798 let guest_thread = GuestTask::new(
2799 state,
2800 Box::new(move |store, dst| {
2801 let mut store = token.as_context_mut(store);
2802 assert!(dst.len() <= MAX_FLAT_PARAMS);
2803 let mut src = [MaybeUninit::uninit(); MAX_FLAT_PARAMS + 1];
2805 let count = match caller_info {
2806 CallerInfo::Async { params, has_result } => {
2810 let params = ¶ms[..params.len() - usize::from(has_result)];
2811 for (param, src) in params.iter().zip(&mut src) {
2812 src.write(*param);
2813 }
2814 params.len()
2815 }
2816
2817 CallerInfo::Sync { params, .. } => {
2819 for (param, src) in params.iter().zip(&mut src) {
2820 src.write(*param);
2821 }
2822 params.len()
2823 }
2824 };
2825 unsafe {
2832 crate::Func::call_unchecked_raw(
2833 &mut store,
2834 start.as_non_null(),
2835 NonNull::new(
2836 &mut src[..count.max(dst.len())] as *mut [MaybeUninit<ValRaw>] as _,
2837 )
2838 .unwrap(),
2839 )?;
2840 }
2841 dst.copy_from_slice(&src[..dst.len()]);
2842 let task = store.0.current_guest_thread()?.task;
2843 let state = store.0.concurrent_state_mut()?;
2844 Waitable::Guest(task).set_event(
2845 state,
2846 Some(Event::Subtask {
2847 status: Status::Started,
2848 }),
2849 )?;
2850 Ok(())
2851 }),
2852 LiftResult {
2853 lift: Box::new(move |store, src| {
2854 let mut store = token.as_context_mut(store);
2857 let mut my_src = src.to_owned(); if let ResultInfo::Heap { results } = &result_info {
2859 my_src.push(ValRaw::u32(*results));
2860 }
2861
2862 let prev = store.0.set_thread(old_thread)?;
2868
2869 unsafe {
2876 crate::Func::call_unchecked_raw(
2877 &mut store,
2878 return_.as_non_null(),
2879 my_src.as_mut_slice().into(),
2880 )?;
2881 }
2882
2883 store.0.set_thread(prev)?;
2886
2887 let thread = store.0.current_guest_thread()?;
2888 let state = store.0.concurrent_state_mut()?;
2889 if sync_caller {
2890 state.get_mut(thread.task)?.sync_result = SyncResult::Produced(
2891 if let ResultInfo::Stack { result_count } = &result_info {
2892 match result_count {
2893 0 => None,
2894 1 => Some(my_src[0]),
2895 _ => unreachable!(),
2896 }
2897 } else {
2898 None
2899 },
2900 );
2901 }
2902 Ok(Box::new(DummyResult) as Box<dyn Any + Send + Sync>)
2903 }),
2904 ty: task_return_type,
2905 memory: NonNull::new(memory).map(SendSyncPtr::new),
2906 string_encoding,
2907 },
2908 Caller::Guest { thread: old_thread },
2909 None,
2910 self.runtime_instance(callee_instance),
2911 callee_async,
2912 )?;
2913
2914 store.0.set_thread(guest_thread)?;
2917 log::trace!("pushed {guest_thread:?} as current thread; old thread was {old_thread:?}");
2918
2919 Ok(())
2920 }
2921
2922 unsafe fn call_callback<T>(
2927 self,
2928 mut store: StoreContextMut<T>,
2929 function: SendSyncPtr<VMFuncRef>,
2930 event: Event,
2931 handle: u32,
2932 ) -> Result<u32> {
2933 let (ordinal, result) = event.parts();
2934 let params = &mut [
2935 ValRaw::u32(ordinal),
2936 ValRaw::u32(handle),
2937 ValRaw::u32(result),
2938 ];
2939 unsafe {
2944 crate::Func::call_unchecked_raw(
2945 &mut store,
2946 function.as_non_null(),
2947 params.as_mut_slice().into(),
2948 )?;
2949 }
2950 Ok(params[0].get_u32())
2951 }
2952
2953 unsafe fn start_call<T: 'static>(
2966 self,
2967 mut store: StoreContextMut<T>,
2968 callback: *mut VMFuncRef,
2969 post_return: *mut VMFuncRef,
2970 callee: NonNull<VMFuncRef>,
2971 param_count: u32,
2972 result_count: u32,
2973 flags: u32,
2974 storage: Option<&mut [MaybeUninit<ValRaw>]>,
2975 ) -> Result<u32> {
2976 let token = StoreToken::new(store.as_context_mut());
2977 let async_caller = storage.is_none();
2978 let guest_thread = store.0.current_guest_thread()?;
2979 let state = store.0.concurrent_state_mut()?;
2980 let callee_async = state.get_mut(guest_thread.task)?.async_function;
2981 let callee = SendSyncPtr::new(callee);
2982 let param_count = usize::try_from(param_count)?;
2983 assert!(param_count <= MAX_FLAT_PARAMS);
2984 let result_count = usize::try_from(result_count)?;
2985 assert!(result_count <= MAX_FLAT_RESULTS);
2986
2987 let task = state.get_mut(guest_thread.task)?;
2988 if let Some(callback) = NonNull::new(callback) {
2989 let callback = SendSyncPtr::new(callback);
2993 task.callback = Some(Box::new(move |store, event, handle| {
2994 let store = token.as_context_mut(store);
2995 unsafe { self.call_callback::<T>(store, callback, event, handle) }
2996 }));
2997 }
2998
2999 let Caller::Guest { thread: caller } = &task.caller else {
3000 bail_bug!("start_call unexpectedly invoked for host->guest call");
3003 };
3004 let caller = *caller;
3005 let caller_instance = state.get_mut(caller.task)?.instance;
3006
3007 unsafe {
3009 self.queue_call(
3010 store.as_context_mut(),
3011 guest_thread,
3012 callee,
3013 param_count,
3014 result_count,
3015 (flags & START_FLAG_ASYNC_CALLEE) != 0,
3016 NonNull::new(callback).map(SendSyncPtr::new),
3017 NonNull::new(post_return).map(SendSyncPtr::new),
3018 )?;
3019 }
3020
3021 let state = store.0.concurrent_state_mut()?;
3022
3023 let guest_waitable = Waitable::Guest(guest_thread.task);
3026 let old_set = guest_waitable.common(state)?.set;
3027 let set = state.get_mut(caller.thread)?.sync_call_set;
3028 guest_waitable.join(state, Some(set))?;
3029
3030 store.0.set_thread(CurrentThread::None)?;
3031
3032 let (status, waitable) = loop {
3048 store.0.suspend(SuspendReason::Waiting {
3049 set,
3050 thread: caller,
3051 skip_may_block_check: async_caller || !callee_async,
3059 })?;
3060
3061 let state = store.0.concurrent_state_mut()?;
3062
3063 log::trace!("taking event for {:?}", guest_thread.task);
3064 let event = guest_waitable.take_event(state)?;
3065 let Some(Event::Subtask { status }) = event else {
3066 bail_bug!("subtasks should only get subtask events, got {event:?}")
3067 };
3068
3069 log::trace!("status {status:?} for {:?}", guest_thread.task);
3070
3071 if status == Status::Returned {
3072 break (status, None);
3074 } else if async_caller {
3075 let handle = store
3079 .0
3080 .instance_state(caller_instance)
3081 .handle_table()
3082 .subtask_insert_guest(guest_thread.task.rep())?;
3083 store
3084 .0
3085 .concurrent_state_mut()?
3086 .get_mut(guest_thread.task)?
3087 .common
3088 .handle = Some(handle);
3089 break (status, Some(handle));
3090 } else {
3091 }
3095 };
3096
3097 guest_waitable.join(store.0.concurrent_state_mut()?, old_set)?;
3098
3099 store.0.set_thread(caller)?;
3101 store
3102 .0
3103 .concurrent_state_mut()?
3104 .get_mut(caller.thread)?
3105 .state = GuestThreadState::Running;
3106 log::trace!("popped current thread {guest_thread:?}; new thread is {caller:?}");
3107
3108 if let Some(storage) = storage {
3109 let state = store.0.concurrent_state_mut()?;
3113 let task = state.get_mut(guest_thread.task)?;
3114 if let Some(result) = task.sync_result.take()? {
3115 if let Some(result) = result {
3116 storage[0] = MaybeUninit::new(result);
3117 }
3118
3119 if task.exited && task.ready_to_delete() {
3120 Waitable::Guest(guest_thread.task).delete_from(state)?;
3121 }
3122 }
3123 }
3124
3125 Ok(status.pack(waitable))
3126 }
3127
3128 pub(crate) fn first_poll<T: 'static, R: Send + 'static>(
3141 self,
3142 mut store: StoreContextMut<'_, T>,
3143 future: impl Future<Output = Result<R>> + Send + 'static,
3144 lower: impl FnOnce(StoreContextMut<T>, Option<R>) -> Result<()> + Send + 'static,
3145 ) -> Result<Option<u32>> {
3146 let token = StoreToken::new(store.as_context_mut());
3147 let task = store.0.current_host_thread()?;
3148 let state = store.0.concurrent_state_mut()?;
3149
3150 let (join_handle, future) = JoinHandle::run(future);
3153 {
3154 let state = &mut state.get_mut(task)?.state;
3155 assert!(matches!(state, HostTaskState::CalleeStarted));
3156 *state = HostTaskState::CalleeRunning(join_handle);
3157 }
3158
3159 let mut future = Box::pin(future);
3160
3161 let poll = tls::set(store.0, || {
3166 future
3167 .as_mut()
3168 .poll(&mut Context::from_waker(&Waker::noop()))
3169 });
3170
3171 match poll {
3172 Poll::Ready(result) => {
3174 let result = result.transpose()?;
3175 lower(store.as_context_mut(), result)?;
3176 return Ok(None);
3177 }
3178
3179 Poll::Pending => {}
3181 }
3182
3183 let future = Box::pin(async move {
3191 let result = match future.await {
3192 Some(result) => Some(result?),
3193 None => None,
3194 };
3195 let on_complete = move |store: &mut dyn VMStore| {
3196 let mut store = token.as_context_mut(store);
3200 let old = store.0.set_thread(task)?;
3201
3202 let status = if result.is_some() {
3203 Status::Returned
3204 } else {
3205 Status::ReturnCancelled
3206 };
3207
3208 lower(store.as_context_mut(), result)?;
3209 let state = store.0.concurrent_state_mut()?;
3210 match &mut state.get_mut(task)?.state {
3211 HostTaskState::CalleeDone { .. } => {}
3214
3215 other => *other = HostTaskState::CalleeDone { cancelled: false },
3217 }
3218 Waitable::Host(task).set_event(state, Some(Event::Subtask { status }))?;
3219
3220 store.0.set_thread(old)?;
3221 Ok(())
3222 };
3223
3224 tls::get(move |store| {
3229 store
3230 .concurrent_state_mut()?
3231 .push_high_priority(WorkItem::WorkerFunction(AlwaysMut::new(Box::new(
3232 on_complete,
3233 ))));
3234 Ok(())
3235 })
3236 });
3237
3238 let state = store.0.concurrent_state_mut()?;
3241 state.push_future(future);
3242 let caller = state.get_mut(task)?.caller;
3243 let instance = state.get_mut(caller.task)?.instance;
3244 let handle = store
3245 .0
3246 .instance_state(instance)
3247 .handle_table()
3248 .subtask_insert_host(task.rep())?;
3249 store.0.concurrent_state_mut()?.get_mut(task)?.common.handle = Some(handle);
3250 log::trace!("assign {task:?} handle {handle} for {caller:?} instance {instance:?}");
3251
3252 store.0.set_thread(caller)?;
3256 Ok(Some(handle))
3257 }
3258
3259 pub(crate) fn task_return(
3262 self,
3263 store: &mut dyn VMStore,
3264 ty: TypeTupleIndex,
3265 options: OptionsIndex,
3266 storage: &[ValRaw],
3267 ) -> Result<()> {
3268 let guest_thread = store.current_guest_thread()?;
3269 let state = store.concurrent_state_mut()?;
3270 let lift = state
3271 .get_mut(guest_thread.task)?
3272 .lift_result
3273 .take()
3274 .ok_or_else(|| Trap::TaskCancelOrReturnTwice)?;
3275 if !state.get_mut(guest_thread.task)?.result.is_none() {
3276 bail_bug!("task result unexpectedly already set");
3277 }
3278
3279 let CanonicalOptions {
3280 string_encoding,
3281 data_model,
3282 ..
3283 } = &self.id().get(store).component().env_component().options[options];
3284
3285 let invalid = ty != lift.ty
3286 || string_encoding != &lift.string_encoding
3287 || match data_model {
3288 CanonicalOptionsDataModel::LinearMemory(opts) => match opts.memory {
3289 Some(memory) => {
3290 let expected = lift.memory.map(|v| v.as_ptr()).unwrap_or(ptr::null_mut());
3291 let actual = self.id().get(store).runtime_memory(memory);
3292 expected != actual.as_ptr()
3293 }
3294 None => false,
3297 },
3298 CanonicalOptionsDataModel::Gc { .. } => true,
3300 };
3301
3302 if invalid {
3303 bail!(Trap::TaskReturnInvalid);
3304 }
3305
3306 log::trace!("task.return for {guest_thread:?}");
3307
3308 let result = (lift.lift)(store, storage)?;
3309 self.task_complete(store, guest_thread.task, result, Status::Returned)
3310 }
3311
3312 pub(crate) fn task_cancel(self, store: &mut StoreOpaque) -> Result<()> {
3314 let guest_thread = store.current_guest_thread()?;
3315 let state = store.concurrent_state_mut()?;
3316 let task = state.get_mut(guest_thread.task)?;
3317 if !task.cancel_sent {
3318 bail!(Trap::TaskCancelNotCancelled);
3319 }
3320 _ = task
3321 .lift_result
3322 .take()
3323 .ok_or_else(|| Trap::TaskCancelOrReturnTwice)?;
3324
3325 if !task.result.is_none() {
3326 bail_bug!("task result should not bet set yet");
3327 }
3328
3329 log::trace!("task.cancel for {guest_thread:?}");
3330
3331 self.task_complete(
3332 store,
3333 guest_thread.task,
3334 Box::new(DummyResult),
3335 Status::ReturnCancelled,
3336 )
3337 }
3338
3339 fn task_complete(
3345 self,
3346 store: &mut StoreOpaque,
3347 guest_task: TableId<GuestTask>,
3348 result: Box<dyn Any + Send + Sync>,
3349 status: Status,
3350 ) -> Result<()> {
3351 store
3352 .component_resource_tables(Some(self))?
3353 .validate_scope_exit()?;
3354
3355 let state = store.concurrent_state_mut()?;
3356 let task = state.get_mut(guest_task)?;
3357
3358 if let Caller::Host { tx, .. } = &mut task.caller {
3359 if let Some(tx) = tx.take() {
3360 _ = tx.send(result);
3361 }
3362 } else {
3363 task.result = Some(result);
3364 Waitable::Guest(guest_task).set_event(state, Some(Event::Subtask { status }))?;
3365 }
3366
3367 Ok(())
3368 }
3369
3370 pub(crate) fn waitable_set_new(
3372 self,
3373 store: &mut StoreOpaque,
3374 caller_instance: RuntimeComponentInstanceIndex,
3375 ) -> Result<u32> {
3376 let set = store.concurrent_state_mut()?.push(WaitableSet::default())?;
3377 let handle = store
3378 .instance_state(self.runtime_instance(caller_instance))
3379 .handle_table()
3380 .waitable_set_insert(set.rep())?;
3381 log::trace!("new waitable set {set:?} (handle {handle})");
3382 Ok(handle)
3383 }
3384
3385 pub(crate) fn waitable_set_drop(
3387 self,
3388 store: &mut StoreOpaque,
3389 caller_instance: RuntimeComponentInstanceIndex,
3390 set: u32,
3391 ) -> Result<()> {
3392 let rep = store
3393 .instance_state(self.runtime_instance(caller_instance))
3394 .handle_table()
3395 .waitable_set_remove(set)?;
3396
3397 log::trace!("drop waitable set {rep} (handle {set})");
3398
3399 if !store
3403 .concurrent_state_mut()?
3404 .get_mut(TableId::<WaitableSet>::new(rep))?
3405 .waiting
3406 .is_empty()
3407 {
3408 bail!(Trap::WaitableSetDropHasWaiters);
3409 }
3410
3411 store
3412 .concurrent_state_mut()?
3413 .delete(TableId::<WaitableSet>::new(rep))?;
3414
3415 Ok(())
3416 }
3417
3418 pub(crate) fn waitable_join(
3420 self,
3421 store: &mut StoreOpaque,
3422 caller_instance: RuntimeComponentInstanceIndex,
3423 waitable_handle: u32,
3424 set_handle: u32,
3425 ) -> Result<()> {
3426 let mut instance = self.id().get_mut(store);
3427 let waitable =
3428 Waitable::from_instance(instance.as_mut(), caller_instance, waitable_handle)?;
3429
3430 let set = if set_handle == 0 {
3431 None
3432 } else {
3433 let set = instance.instance_states().0[caller_instance]
3434 .handle_table()
3435 .waitable_set_rep(set_handle)?;
3436
3437 let state = store.concurrent_state_mut()?;
3438 if let Some(old) = waitable.common(state)?.set
3439 && state.get_mut(old)?.is_sync_call_set
3440 {
3441 bail!(Trap::WaitableSyncAndAsync);
3442 }
3443
3444 Some(TableId::<WaitableSet>::new(set))
3445 };
3446
3447 log::trace!(
3448 "waitable {waitable:?} (handle {waitable_handle}) join set {set:?} (handle {set_handle})",
3449 );
3450
3451 waitable.join(store.concurrent_state_mut()?, set)
3452 }
3453
3454 pub(crate) fn subtask_drop(
3456 self,
3457 store: &mut StoreOpaque,
3458 caller_instance: RuntimeComponentInstanceIndex,
3459 task_id: u32,
3460 ) -> Result<()> {
3461 self.waitable_join(store, caller_instance, task_id, 0)?;
3462
3463 let (rep, is_host) = store
3464 .instance_state(self.runtime_instance(caller_instance))
3465 .handle_table()
3466 .subtask_remove(task_id)?;
3467
3468 let concurrent_state = store.concurrent_state_mut()?;
3469 let (waitable, delete) = if is_host {
3470 let id = TableId::<HostTask>::new(rep);
3471 let task = concurrent_state.get_mut(id)?;
3472 match &task.state {
3473 HostTaskState::CalleeRunning(_) => bail!(Trap::SubtaskDropNotResolved),
3474 HostTaskState::CalleeDone { .. } => {}
3475 HostTaskState::CalleeStarted | HostTaskState::CalleeFinished(_) => {
3476 bail_bug!("invalid state for callee in `subtask.drop`")
3477 }
3478 }
3479 (Waitable::Host(id), true)
3480 } else {
3481 let id = TableId::<GuestTask>::new(rep);
3482 let task = concurrent_state.get_mut(id)?;
3483 if task.lift_result.is_some() {
3484 bail!(Trap::SubtaskDropNotResolved);
3485 }
3486 (
3487 Waitable::Guest(id),
3488 concurrent_state.get_mut(id)?.ready_to_delete(),
3489 )
3490 };
3491
3492 waitable.common(concurrent_state)?.handle = None;
3493
3494 if waitable.take_event(concurrent_state)?.is_some() {
3497 bail!(Trap::SubtaskDropNotResolved);
3498 }
3499
3500 if delete {
3501 waitable.delete_from(concurrent_state)?;
3502 }
3503
3504 log::trace!("subtask_drop {waitable:?} (handle {task_id})");
3505 Ok(())
3506 }
3507
3508 pub(crate) fn waitable_set_wait(
3510 self,
3511 store: &mut StoreOpaque,
3512 options: OptionsIndex,
3513 set: u32,
3514 payload: u32,
3515 ) -> Result<u32> {
3516 if !self.options(store, options).async_ {
3517 store.check_blocking()?;
3521 }
3522
3523 let &CanonicalOptions {
3524 cancellable,
3525 instance: caller_instance,
3526 ..
3527 } = &self.id().get(store).component().env_component().options[options];
3528 let rep = store
3529 .instance_state(self.runtime_instance(caller_instance))
3530 .handle_table()
3531 .waitable_set_rep(set)?;
3532
3533 self.waitable_check(
3534 store,
3535 cancellable,
3536 WaitableCheck::Wait,
3537 WaitableCheckParams {
3538 set: TableId::new(rep),
3539 options,
3540 payload,
3541 },
3542 )
3543 }
3544
3545 pub(crate) fn waitable_set_poll(
3547 self,
3548 store: &mut StoreOpaque,
3549 options: OptionsIndex,
3550 set: u32,
3551 payload: u32,
3552 ) -> Result<u32> {
3553 let &CanonicalOptions {
3554 cancellable,
3555 instance: caller_instance,
3556 ..
3557 } = &self.id().get(store).component().env_component().options[options];
3558 let rep = store
3559 .instance_state(self.runtime_instance(caller_instance))
3560 .handle_table()
3561 .waitable_set_rep(set)?;
3562
3563 self.waitable_check(
3564 store,
3565 cancellable,
3566 WaitableCheck::Poll,
3567 WaitableCheckParams {
3568 set: TableId::new(rep),
3569 options,
3570 payload,
3571 },
3572 )
3573 }
3574
3575 pub(crate) fn thread_index(&self, store: &mut dyn VMStore) -> Result<u32> {
3577 let thread_id = store.current_guest_thread()?.thread;
3578 match store
3579 .concurrent_state_mut()?
3580 .get_mut(thread_id)?
3581 .instance_rep
3582 {
3583 Some(r) => Ok(r),
3584 None => bail_bug!("thread should have instance_rep by now"),
3585 }
3586 }
3587
3588 pub(crate) fn thread_new_indirect<T: 'static>(
3590 self,
3591 mut store: StoreContextMut<T>,
3592 runtime_instance: RuntimeComponentInstanceIndex,
3593 _func_ty_idx: TypeFuncIndex, start_func_table_idx: RuntimeTableIndex,
3595 start_func_idx: u32,
3596 context: i32,
3597 ) -> Result<u32> {
3598 log::trace!("creating new thread");
3599
3600 let start_func_ty = FuncType::new(store.engine(), [ValType::I32], []);
3601 let (instance, registry) = self.id().get_mut_and_registry(store.0);
3602 let callee = instance
3603 .index_runtime_func_table(registry, start_func_table_idx, start_func_idx as u64)?
3604 .ok_or_else(|| Trap::ThreadNewIndirectUninitialized)?;
3605 if callee.type_index(store.0) != start_func_ty.type_index() {
3606 bail!(Trap::ThreadNewIndirectInvalidType);
3607 }
3608
3609 let token = StoreToken::new(store.as_context_mut());
3610 let start_func = Box::new(
3611 move |store: &mut dyn VMStore, guest_thread: QualifiedThreadId| -> Result<()> {
3612 let old_thread = store.set_thread(guest_thread)?;
3613 log::trace!(
3614 "thread start: replaced {old_thread:?} with {guest_thread:?} as current thread"
3615 );
3616
3617 let mut store = token.as_context_mut(store);
3618 let mut params = [ValRaw::i32(context)];
3619 unsafe { callee.call_unchecked(store.as_context_mut(), &mut params)? };
3622
3623 store.0.set_thread(old_thread)?;
3624
3625 store.0.cleanup_thread(
3626 guest_thread,
3627 self.runtime_instance(runtime_instance),
3628 CleanupTask::Yes,
3629 )?;
3630 log::trace!("explicit thread {guest_thread:?} completed");
3631 let state = store.0.concurrent_state_mut()?;
3632 if let Some(t) = old_thread.guest() {
3633 state.get_mut(t.thread)?.state = GuestThreadState::Running;
3634 }
3635 log::trace!("thread start: restored {old_thread:?} as current thread");
3636
3637 Ok(())
3638 },
3639 );
3640
3641 let current_thread = store.0.current_guest_thread()?;
3642 let state = store.0.concurrent_state_mut()?;
3643 let parent_task = current_thread.task;
3644
3645 let new_thread = GuestThread::new_explicit(state, parent_task, start_func)?;
3646 let thread_id = state.push(new_thread)?;
3647 state.get_mut(parent_task)?.threads.insert(thread_id);
3648
3649 log::trace!("new thread with id {thread_id:?} created");
3650
3651 self.add_guest_thread_to_instance_table(thread_id, store.0, runtime_instance)
3652 }
3653
3654 pub(crate) fn resume_thread(
3655 self,
3656 store: &mut StoreOpaque,
3657 runtime_instance: RuntimeComponentInstanceIndex,
3658 thread_idx: u32,
3659 high_priority: bool,
3660 allow_ready: bool,
3661 ) -> Result<()> {
3662 let thread_id =
3663 GuestThread::from_instance(self.id().get_mut(store), runtime_instance, thread_idx)?;
3664 let state = store.concurrent_state_mut()?;
3665 let guest_thread = QualifiedThreadId::qualify(state, thread_id)?;
3666 let thread = state.get_mut(guest_thread.thread)?;
3667
3668 match mem::replace(&mut thread.state, GuestThreadState::Running) {
3669 GuestThreadState::NotStartedExplicit(start_func) => {
3670 log::trace!("starting thread {guest_thread:?}");
3671 let guest_call = WorkItem::GuestCall(
3672 runtime_instance,
3673 GuestCall {
3674 thread: guest_thread,
3675 kind: GuestCallKind::StartExplicit(Box::new(move |store| {
3676 start_func(store, guest_thread)
3677 })),
3678 },
3679 );
3680 store
3681 .concurrent_state_mut()?
3682 .push_work_item(guest_call, high_priority);
3683 }
3684 GuestThreadState::Suspended(fiber) => {
3685 log::trace!("resuming thread {thread_id:?} that was suspended");
3686 store
3687 .concurrent_state_mut()?
3688 .push_work_item(WorkItem::ResumeFiber(fiber), high_priority);
3689 }
3690 GuestThreadState::Ready { fiber, cancellable } if allow_ready => {
3691 log::trace!("resuming thread {thread_id:?} that was ready");
3692 thread.state = GuestThreadState::Ready { fiber, cancellable };
3693 store
3694 .concurrent_state_mut()?
3695 .promote_thread_work_item(guest_thread);
3696 }
3697 other => {
3698 thread.state = other;
3699 bail!(Trap::CannotResumeThread);
3700 }
3701 }
3702 Ok(())
3703 }
3704
3705 fn add_guest_thread_to_instance_table(
3706 self,
3707 thread_id: TableId<GuestThread>,
3708 store: &mut StoreOpaque,
3709 runtime_instance: RuntimeComponentInstanceIndex,
3710 ) -> Result<u32> {
3711 let guest_id = store
3712 .instance_state(self.runtime_instance(runtime_instance))
3713 .thread_handle_table()
3714 .guest_thread_insert(thread_id.rep())?;
3715 store
3716 .concurrent_state_mut()?
3717 .get_mut(thread_id)?
3718 .instance_rep = Some(guest_id);
3719 Ok(guest_id)
3720 }
3721
3722 pub(crate) fn suspension_intrinsic(
3725 self,
3726 store: &mut StoreOpaque,
3727 caller: RuntimeComponentInstanceIndex,
3728 cancellable: bool,
3729 yielding: bool,
3730 to_thread: SuspensionTarget,
3731 ) -> Result<WaitResult> {
3732 let guest_thread = store.current_guest_thread()?;
3733 if to_thread.is_none() {
3734 let state = store.concurrent_state_mut()?;
3735 if yielding {
3736 if !state.may_block(guest_thread.task)? {
3738 if !state.promote_instance_local_thread_work_item(caller) {
3741 return Ok(WaitResult::Completed);
3743 }
3744 }
3745 } else {
3746 store.check_blocking()?;
3750 }
3751 }
3752
3753 if cancellable && store.take_pending_cancellation()? {
3755 return Ok(WaitResult::Cancelled);
3756 }
3757
3758 match to_thread {
3759 SuspensionTarget::SomeSuspended(thread) => {
3760 self.resume_thread(store, caller, thread, true, false)?
3761 }
3762 SuspensionTarget::Some(thread) => {
3763 self.resume_thread(store, caller, thread, true, true)?
3764 }
3765 SuspensionTarget::None => { }
3766 }
3767
3768 let reason = if yielding {
3769 SuspendReason::Yielding {
3770 thread: guest_thread,
3771 cancellable,
3772 skip_may_block_check: to_thread.is_some(),
3776 }
3777 } else {
3778 SuspendReason::ExplicitlySuspending {
3779 thread: guest_thread,
3780 skip_may_block_check: to_thread.is_some(),
3784 }
3785 };
3786
3787 store.suspend(reason)?;
3788
3789 if cancellable && store.take_pending_cancellation()? {
3790 Ok(WaitResult::Cancelled)
3791 } else {
3792 Ok(WaitResult::Completed)
3793 }
3794 }
3795
3796 fn waitable_check(
3798 self,
3799 store: &mut StoreOpaque,
3800 cancellable: bool,
3801 check: WaitableCheck,
3802 params: WaitableCheckParams,
3803 ) -> Result<u32> {
3804 let guest_thread = store.current_guest_thread()?;
3805
3806 log::trace!("waitable check for {guest_thread:?}; set {:?}", params.set);
3807
3808 let state = store.concurrent_state_mut()?;
3809 let task = state.get_mut(guest_thread.task)?;
3810
3811 match &check {
3814 WaitableCheck::Wait => {
3815 let set = params.set;
3816
3817 if (task.event.is_none()
3818 || (matches!(task.event, Some(Event::Cancelled)) && !cancellable))
3819 && state.get_mut(set)?.ready.is_empty()
3820 {
3821 if cancellable {
3822 let old = state
3823 .get_mut(guest_thread.thread)?
3824 .wake_on_cancel
3825 .replace(set);
3826 if !old.is_none() {
3827 bail_bug!("thread unexpectedly in a prior wake_on_cancel set");
3828 }
3829 }
3830
3831 store.suspend(SuspendReason::Waiting {
3832 set,
3833 thread: guest_thread,
3834 skip_may_block_check: false,
3835 })?;
3836 }
3837 }
3838 WaitableCheck::Poll => {}
3839 }
3840
3841 log::trace!(
3842 "waitable check for {guest_thread:?}; set {:?}, part two",
3843 params.set
3844 );
3845
3846 let event = self.get_event(store, guest_thread.task, Some(params.set), cancellable)?;
3848
3849 let (ordinal, handle, result) = match &check {
3850 WaitableCheck::Wait => {
3851 let (event, waitable) = match event {
3852 Some(p) => p,
3853 None => bail_bug!("event expected to be present"),
3854 };
3855 let handle = waitable.map(|(_, v)| v).unwrap_or(0);
3856 let (ordinal, result) = event.parts();
3857 (ordinal, handle, result)
3858 }
3859 WaitableCheck::Poll => {
3860 if let Some((event, waitable)) = event {
3861 let handle = waitable.map(|(_, v)| v).unwrap_or(0);
3862 let (ordinal, result) = event.parts();
3863 (ordinal, handle, result)
3864 } else {
3865 log::trace!(
3866 "no events ready to deliver via waitable-set.poll to {:?}; set {:?}",
3867 guest_thread.task,
3868 params.set
3869 );
3870 let (ordinal, result) = Event::None.parts();
3871 (ordinal, 0, result)
3872 }
3873 }
3874 };
3875 let memory = self.options_memory_mut(store, params.options);
3876 let ptr = crate::component::func::validate_inbounds_dynamic(
3877 &CanonicalAbiInfo::POINTER_PAIR,
3878 memory,
3879 &ValRaw::u32(params.payload),
3880 )?;
3881 memory[ptr + 0..][..4].copy_from_slice(&handle.to_le_bytes());
3882 memory[ptr + 4..][..4].copy_from_slice(&result.to_le_bytes());
3883 Ok(ordinal)
3884 }
3885
3886 pub(crate) fn subtask_cancel(
3888 self,
3889 store: &mut StoreOpaque,
3890 caller_instance: RuntimeComponentInstanceIndex,
3891 async_: bool,
3892 task_id: u32,
3893 ) -> Result<u32> {
3894 if !async_ {
3895 store.check_blocking()?;
3899 }
3900
3901 let (rep, is_host) = store
3902 .instance_state(self.runtime_instance(caller_instance))
3903 .handle_table()
3904 .subtask_rep(task_id)?;
3905 let waitable = if is_host {
3906 Waitable::Host(TableId::<HostTask>::new(rep))
3907 } else {
3908 Waitable::Guest(TableId::<GuestTask>::new(rep))
3909 };
3910 let concurrent_state = store.concurrent_state_mut()?;
3911
3912 log::trace!("subtask_cancel {waitable:?} (handle {task_id})");
3913
3914 let needs_block;
3915 if let Waitable::Host(host_task) = waitable {
3916 let state = &mut concurrent_state.get_mut(host_task)?.state;
3917 match mem::replace(state, HostTaskState::CalleeDone { cancelled: true }) {
3918 HostTaskState::CalleeRunning(handle) => {
3925 handle.abort();
3926 needs_block = true;
3927 }
3928
3929 HostTaskState::CalleeDone { cancelled } => {
3932 if cancelled {
3933 bail!(Trap::SubtaskCancelAfterTerminal);
3934 } else {
3935 needs_block = false;
3938 }
3939 }
3940
3941 HostTaskState::CalleeStarted | HostTaskState::CalleeFinished(_) => {
3944 bail_bug!("invalid states for host callee")
3945 }
3946 }
3947 } else {
3948 let guest_task = TableId::<GuestTask>::new(rep);
3949 let task = concurrent_state.get_mut(guest_task)?;
3950 if !task.already_lowered_parameters() {
3951 store.cancel_guest_subtask_without_lowered_parameters(
3952 self.runtime_instance(caller_instance),
3953 guest_task,
3954 )?;
3955 return Ok(Status::StartCancelled as u32);
3956 } else if !task.returned_or_cancelled() {
3957 task.cancel_sent = true;
3960 task.event = Some(Event::Cancelled);
3965 let runtime_instance = task.instance.index;
3966 for thread in task.threads.clone() {
3967 let thread = QualifiedThreadId {
3968 task: guest_task,
3969 thread,
3970 };
3971 let thread_mut = concurrent_state.get_mut(thread.thread)?;
3972 if let Some(set) = thread_mut.wake_on_cancel.take() {
3973 let item = match concurrent_state.get_mut(set)?.waiting.remove(&thread) {
3975 Some(WaitMode::Fiber(fiber)) => WorkItem::ResumeFiber(fiber),
3976 Some(WaitMode::Callback(instance)) => WorkItem::GuestCall(
3977 runtime_instance,
3978 GuestCall {
3979 thread,
3980 kind: GuestCallKind::DeliverEvent {
3981 instance,
3982 set: None,
3983 },
3984 },
3985 ),
3986 None => bail_bug!("thread not present in wake_on_cancel set"),
3987 };
3988 concurrent_state.push_high_priority(item);
3989
3990 let caller = store.current_guest_thread()?;
3991 store.suspend(SuspendReason::Yielding {
3992 thread: caller,
3993 cancellable: false,
3994 skip_may_block_check: false,
3997 })?;
3998 break;
3999 } else if let GuestThreadState::Ready {
4000 cancellable: true, ..
4001 } = &thread_mut.state
4002 {
4003 concurrent_state.promote_thread_work_item(thread);
4006 let caller = store.current_guest_thread()?;
4007 store.suspend(SuspendReason::Yielding {
4008 thread: caller,
4009 cancellable: false,
4010 skip_may_block_check: false,
4011 })?;
4012 break;
4013 }
4014 }
4015
4016 needs_block = !store
4019 .concurrent_state_mut()?
4020 .get_mut(guest_task)?
4021 .returned_or_cancelled()
4022 } else {
4023 needs_block = false;
4024 }
4025 };
4026
4027 if needs_block {
4031 if async_ {
4032 return Ok(BLOCKED);
4033 }
4034
4035 store.wait_for_event(waitable)?;
4039
4040 }
4042
4043 let event = waitable.take_event(store.concurrent_state_mut()?)?;
4044 if let Some(Event::Subtask {
4045 status: status @ (Status::Returned | Status::ReturnCancelled),
4046 }) = event
4047 {
4048 Ok(status as u32)
4049 } else {
4050 bail!(Trap::SubtaskCancelAfterTerminal);
4051 }
4052 }
4053}
4054
4055pub trait VMComponentAsyncStore {
4063 unsafe fn prepare_call(
4069 &mut self,
4070 instance: Instance,
4071 memory: *mut VMMemoryDefinition,
4072 start: NonNull<VMFuncRef>,
4073 return_: NonNull<VMFuncRef>,
4074 caller_instance: RuntimeComponentInstanceIndex,
4075 callee_instance: RuntimeComponentInstanceIndex,
4076 task_return_type: TypeTupleIndex,
4077 callee_async: bool,
4078 string_encoding: StringEncoding,
4079 result_count: u32,
4080 storage: *mut ValRaw,
4081 storage_len: usize,
4082 ) -> Result<()>;
4083
4084 unsafe fn sync_start(
4087 &mut self,
4088 instance: Instance,
4089 callback: *mut VMFuncRef,
4090 callee: NonNull<VMFuncRef>,
4091 param_count: u32,
4092 storage: *mut MaybeUninit<ValRaw>,
4093 storage_len: usize,
4094 ) -> Result<()>;
4095
4096 unsafe fn async_start(
4099 &mut self,
4100 instance: Instance,
4101 callback: *mut VMFuncRef,
4102 post_return: *mut VMFuncRef,
4103 callee: NonNull<VMFuncRef>,
4104 param_count: u32,
4105 result_count: u32,
4106 flags: u32,
4107 ) -> Result<u32>;
4108
4109 fn future_write(
4111 &mut self,
4112 instance: Instance,
4113 caller: RuntimeComponentInstanceIndex,
4114 ty: TypeFutureTableIndex,
4115 options: OptionsIndex,
4116 future: u32,
4117 address: u32,
4118 ) -> Result<u32>;
4119
4120 fn future_read(
4122 &mut self,
4123 instance: Instance,
4124 caller: RuntimeComponentInstanceIndex,
4125 ty: TypeFutureTableIndex,
4126 options: OptionsIndex,
4127 future: u32,
4128 address: u32,
4129 ) -> Result<u32>;
4130
4131 fn future_drop_writable(
4133 &mut self,
4134 instance: Instance,
4135 ty: TypeFutureTableIndex,
4136 writer: u32,
4137 ) -> Result<()>;
4138
4139 fn stream_write(
4141 &mut self,
4142 instance: Instance,
4143 caller: RuntimeComponentInstanceIndex,
4144 ty: TypeStreamTableIndex,
4145 options: OptionsIndex,
4146 stream: u32,
4147 address: u32,
4148 count: u32,
4149 ) -> Result<u32>;
4150
4151 fn stream_read(
4153 &mut self,
4154 instance: Instance,
4155 caller: RuntimeComponentInstanceIndex,
4156 ty: TypeStreamTableIndex,
4157 options: OptionsIndex,
4158 stream: u32,
4159 address: u32,
4160 count: u32,
4161 ) -> Result<u32>;
4162
4163 fn flat_stream_write(
4166 &mut self,
4167 instance: Instance,
4168 caller: RuntimeComponentInstanceIndex,
4169 ty: TypeStreamTableIndex,
4170 options: OptionsIndex,
4171 payload_size: u32,
4172 payload_align: u32,
4173 stream: u32,
4174 address: u32,
4175 count: u32,
4176 ) -> Result<u32>;
4177
4178 fn flat_stream_read(
4181 &mut self,
4182 instance: Instance,
4183 caller: RuntimeComponentInstanceIndex,
4184 ty: TypeStreamTableIndex,
4185 options: OptionsIndex,
4186 payload_size: u32,
4187 payload_align: u32,
4188 stream: u32,
4189 address: u32,
4190 count: u32,
4191 ) -> Result<u32>;
4192
4193 fn stream_drop_writable(
4195 &mut self,
4196 instance: Instance,
4197 ty: TypeStreamTableIndex,
4198 writer: u32,
4199 ) -> Result<()>;
4200
4201 fn error_context_debug_message(
4203 &mut self,
4204 instance: Instance,
4205 ty: TypeComponentLocalErrorContextTableIndex,
4206 options: OptionsIndex,
4207 err_ctx_handle: u32,
4208 debug_msg_address: u32,
4209 ) -> Result<()>;
4210
4211 fn thread_new_indirect(
4213 &mut self,
4214 instance: Instance,
4215 caller: RuntimeComponentInstanceIndex,
4216 func_ty_idx: TypeFuncIndex,
4217 start_func_table_idx: RuntimeTableIndex,
4218 start_func_idx: u32,
4219 context: i32,
4220 ) -> Result<u32>;
4221}
4222
4223impl<T: 'static> VMComponentAsyncStore for StoreInner<T> {
4225 unsafe fn prepare_call(
4226 &mut self,
4227 instance: Instance,
4228 memory: *mut VMMemoryDefinition,
4229 start: NonNull<VMFuncRef>,
4230 return_: NonNull<VMFuncRef>,
4231 caller_instance: RuntimeComponentInstanceIndex,
4232 callee_instance: RuntimeComponentInstanceIndex,
4233 task_return_type: TypeTupleIndex,
4234 callee_async: bool,
4235 string_encoding: StringEncoding,
4236 result_count_or_max_if_async: u32,
4237 storage: *mut ValRaw,
4238 storage_len: usize,
4239 ) -> Result<()> {
4240 let params = unsafe { core::slice::from_raw_parts(storage, storage_len) }.to_vec();
4244
4245 unsafe {
4246 instance.prepare_call(
4247 StoreContextMut(self),
4248 start,
4249 return_,
4250 caller_instance,
4251 callee_instance,
4252 task_return_type,
4253 callee_async,
4254 memory,
4255 string_encoding,
4256 match result_count_or_max_if_async {
4257 PREPARE_ASYNC_NO_RESULT => CallerInfo::Async {
4258 params,
4259 has_result: false,
4260 },
4261 PREPARE_ASYNC_WITH_RESULT => CallerInfo::Async {
4262 params,
4263 has_result: true,
4264 },
4265 result_count => CallerInfo::Sync {
4266 params,
4267 result_count,
4268 },
4269 },
4270 )
4271 }
4272 }
4273
4274 unsafe fn sync_start(
4275 &mut self,
4276 instance: Instance,
4277 callback: *mut VMFuncRef,
4278 callee: NonNull<VMFuncRef>,
4279 param_count: u32,
4280 storage: *mut MaybeUninit<ValRaw>,
4281 storage_len: usize,
4282 ) -> Result<()> {
4283 unsafe {
4284 instance
4285 .start_call(
4286 StoreContextMut(self),
4287 callback,
4288 ptr::null_mut(),
4289 callee,
4290 param_count,
4291 1,
4292 START_FLAG_ASYNC_CALLEE,
4293 Some(core::slice::from_raw_parts_mut(storage, storage_len)),
4297 )
4298 .map(drop)
4299 }
4300 }
4301
4302 unsafe fn async_start(
4303 &mut self,
4304 instance: Instance,
4305 callback: *mut VMFuncRef,
4306 post_return: *mut VMFuncRef,
4307 callee: NonNull<VMFuncRef>,
4308 param_count: u32,
4309 result_count: u32,
4310 flags: u32,
4311 ) -> Result<u32> {
4312 unsafe {
4313 instance.start_call(
4314 StoreContextMut(self),
4315 callback,
4316 post_return,
4317 callee,
4318 param_count,
4319 result_count,
4320 flags,
4321 None,
4322 )
4323 }
4324 }
4325
4326 fn future_write(
4327 &mut self,
4328 instance: Instance,
4329 caller: RuntimeComponentInstanceIndex,
4330 ty: TypeFutureTableIndex,
4331 options: OptionsIndex,
4332 future: u32,
4333 address: u32,
4334 ) -> Result<u32> {
4335 instance
4336 .guest_write(
4337 StoreContextMut(self),
4338 caller,
4339 TransmitIndex::Future(ty),
4340 options,
4341 None,
4342 future,
4343 address,
4344 1,
4345 )
4346 .map(|result| result.encode())
4347 }
4348
4349 fn future_read(
4350 &mut self,
4351 instance: Instance,
4352 caller: RuntimeComponentInstanceIndex,
4353 ty: TypeFutureTableIndex,
4354 options: OptionsIndex,
4355 future: u32,
4356 address: u32,
4357 ) -> Result<u32> {
4358 instance
4359 .guest_read(
4360 StoreContextMut(self),
4361 caller,
4362 TransmitIndex::Future(ty),
4363 options,
4364 None,
4365 future,
4366 address,
4367 1,
4368 )
4369 .map(|result| result.encode())
4370 }
4371
4372 fn stream_write(
4373 &mut self,
4374 instance: Instance,
4375 caller: RuntimeComponentInstanceIndex,
4376 ty: TypeStreamTableIndex,
4377 options: OptionsIndex,
4378 stream: u32,
4379 address: u32,
4380 count: u32,
4381 ) -> Result<u32> {
4382 instance
4383 .guest_write(
4384 StoreContextMut(self),
4385 caller,
4386 TransmitIndex::Stream(ty),
4387 options,
4388 None,
4389 stream,
4390 address,
4391 count,
4392 )
4393 .map(|result| result.encode())
4394 }
4395
4396 fn stream_read(
4397 &mut self,
4398 instance: Instance,
4399 caller: RuntimeComponentInstanceIndex,
4400 ty: TypeStreamTableIndex,
4401 options: OptionsIndex,
4402 stream: u32,
4403 address: u32,
4404 count: u32,
4405 ) -> Result<u32> {
4406 instance
4407 .guest_read(
4408 StoreContextMut(self),
4409 caller,
4410 TransmitIndex::Stream(ty),
4411 options,
4412 None,
4413 stream,
4414 address,
4415 count,
4416 )
4417 .map(|result| result.encode())
4418 }
4419
4420 fn future_drop_writable(
4421 &mut self,
4422 instance: Instance,
4423 ty: TypeFutureTableIndex,
4424 writer: u32,
4425 ) -> Result<()> {
4426 instance.guest_drop_writable(self, TransmitIndex::Future(ty), writer)
4427 }
4428
4429 fn flat_stream_write(
4430 &mut self,
4431 instance: Instance,
4432 caller: RuntimeComponentInstanceIndex,
4433 ty: TypeStreamTableIndex,
4434 options: OptionsIndex,
4435 payload_size: u32,
4436 payload_align: u32,
4437 stream: u32,
4438 address: u32,
4439 count: u32,
4440 ) -> Result<u32> {
4441 instance
4442 .guest_write(
4443 StoreContextMut(self),
4444 caller,
4445 TransmitIndex::Stream(ty),
4446 options,
4447 Some(FlatAbi {
4448 size: payload_size,
4449 align: payload_align,
4450 }),
4451 stream,
4452 address,
4453 count,
4454 )
4455 .map(|result| result.encode())
4456 }
4457
4458 fn flat_stream_read(
4459 &mut self,
4460 instance: Instance,
4461 caller: RuntimeComponentInstanceIndex,
4462 ty: TypeStreamTableIndex,
4463 options: OptionsIndex,
4464 payload_size: u32,
4465 payload_align: u32,
4466 stream: u32,
4467 address: u32,
4468 count: u32,
4469 ) -> Result<u32> {
4470 instance
4471 .guest_read(
4472 StoreContextMut(self),
4473 caller,
4474 TransmitIndex::Stream(ty),
4475 options,
4476 Some(FlatAbi {
4477 size: payload_size,
4478 align: payload_align,
4479 }),
4480 stream,
4481 address,
4482 count,
4483 )
4484 .map(|result| result.encode())
4485 }
4486
4487 fn stream_drop_writable(
4488 &mut self,
4489 instance: Instance,
4490 ty: TypeStreamTableIndex,
4491 writer: u32,
4492 ) -> Result<()> {
4493 instance.guest_drop_writable(self, TransmitIndex::Stream(ty), writer)
4494 }
4495
4496 fn error_context_debug_message(
4497 &mut self,
4498 instance: Instance,
4499 ty: TypeComponentLocalErrorContextTableIndex,
4500 options: OptionsIndex,
4501 err_ctx_handle: u32,
4502 debug_msg_address: u32,
4503 ) -> Result<()> {
4504 instance.error_context_debug_message(
4505 StoreContextMut(self),
4506 ty,
4507 options,
4508 err_ctx_handle,
4509 debug_msg_address,
4510 )
4511 }
4512
4513 fn thread_new_indirect(
4514 &mut self,
4515 instance: Instance,
4516 caller: RuntimeComponentInstanceIndex,
4517 func_ty_idx: TypeFuncIndex,
4518 start_func_table_idx: RuntimeTableIndex,
4519 start_func_idx: u32,
4520 context: i32,
4521 ) -> Result<u32> {
4522 instance.thread_new_indirect(
4523 StoreContextMut(self),
4524 caller,
4525 func_ty_idx,
4526 start_func_table_idx,
4527 start_func_idx,
4528 context,
4529 )
4530 }
4531}
4532
4533type HostTaskFuture = Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>;
4534
4535pub(crate) struct HostTask {
4539 common: WaitableCommon,
4540
4541 caller: QualifiedThreadId,
4543
4544 call_context: CallContext,
4547
4548 state: HostTaskState,
4549}
4550
4551enum HostTaskState {
4552 CalleeStarted,
4557
4558 CalleeRunning(JoinHandle),
4563
4564 CalleeFinished(LiftedResult),
4568
4569 CalleeDone { cancelled: bool },
4572}
4573
4574impl HostTask {
4575 fn new(caller: QualifiedThreadId, state: HostTaskState) -> Self {
4576 Self {
4577 common: WaitableCommon::default(),
4578 call_context: CallContext::default(),
4579 caller,
4580 state,
4581 }
4582 }
4583}
4584
4585impl TableDebug for HostTask {
4586 fn type_name() -> &'static str {
4587 "HostTask"
4588 }
4589}
4590
4591type CallbackFn = Box<dyn Fn(&mut dyn VMStore, Event, u32) -> Result<u32> + Send + Sync + 'static>;
4592
4593enum Caller {
4595 Host {
4597 tx: Option<oneshot::Sender<LiftedResult>>,
4599 host_future_present: bool,
4602 caller: CurrentThread,
4606 },
4607 Guest {
4609 thread: QualifiedThreadId,
4611 },
4612}
4613
4614struct LiftResult {
4617 lift: RawLift,
4618 ty: TypeTupleIndex,
4619 memory: Option<SendSyncPtr<VMMemoryDefinition>>,
4620 string_encoding: StringEncoding,
4621}
4622
4623#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
4628pub(crate) struct QualifiedThreadId {
4629 task: TableId<GuestTask>,
4630 thread: TableId<GuestThread>,
4631}
4632
4633impl QualifiedThreadId {
4634 fn qualify(
4635 state: &mut ConcurrentState,
4636 thread: TableId<GuestThread>,
4637 ) -> Result<QualifiedThreadId> {
4638 Ok(QualifiedThreadId {
4639 task: state.get_mut(thread)?.parent_task,
4640 thread,
4641 })
4642 }
4643}
4644
4645impl fmt::Debug for QualifiedThreadId {
4646 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4647 f.debug_tuple("QualifiedThreadId")
4648 .field(&self.task.rep())
4649 .field(&self.thread.rep())
4650 .finish()
4651 }
4652}
4653
4654enum GuestThreadState {
4655 NotStartedImplicit,
4656 NotStartedExplicit(
4657 Box<dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync>,
4658 ),
4659 Running,
4660 Suspended(StoreFiber<'static>),
4661 Ready {
4662 fiber: StoreFiber<'static>,
4663 cancellable: bool,
4664 },
4665 Completed,
4666}
4667pub struct GuestThread {
4668 context: [u32; NUM_COMPONENT_CONTEXT_SLOTS],
4671 parent_task: TableId<GuestTask>,
4673 wake_on_cancel: Option<TableId<WaitableSet>>,
4676 state: GuestThreadState,
4678 instance_rep: Option<u32>,
4681 sync_call_set: TableId<WaitableSet>,
4683}
4684
4685impl GuestThread {
4686 fn from_instance(
4689 state: Pin<&mut ComponentInstance>,
4690 caller_instance: RuntimeComponentInstanceIndex,
4691 guest_thread: u32,
4692 ) -> Result<TableId<Self>> {
4693 let rep = state.instance_states().0[caller_instance]
4694 .thread_handle_table()
4695 .guest_thread_rep(guest_thread)?;
4696 Ok(TableId::new(rep))
4697 }
4698
4699 fn new_implicit(state: &mut ConcurrentState, parent_task: TableId<GuestTask>) -> Result<Self> {
4700 let sync_call_set = state.push(WaitableSet {
4701 is_sync_call_set: true,
4702 ..WaitableSet::default()
4703 })?;
4704 Ok(Self {
4705 context: [0; NUM_COMPONENT_CONTEXT_SLOTS],
4706 parent_task,
4707 wake_on_cancel: None,
4708 state: GuestThreadState::NotStartedImplicit,
4709 instance_rep: None,
4710 sync_call_set,
4711 })
4712 }
4713
4714 fn new_explicit(
4715 state: &mut ConcurrentState,
4716 parent_task: TableId<GuestTask>,
4717 start_func: Box<
4718 dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync,
4719 >,
4720 ) -> Result<Self> {
4721 let sync_call_set = state.push(WaitableSet {
4722 is_sync_call_set: true,
4723 ..WaitableSet::default()
4724 })?;
4725 Ok(Self {
4726 context: [0; NUM_COMPONENT_CONTEXT_SLOTS],
4727 parent_task,
4728 wake_on_cancel: None,
4729 state: GuestThreadState::NotStartedExplicit(start_func),
4730 instance_rep: None,
4731 sync_call_set,
4732 })
4733 }
4734}
4735
4736impl TableDebug for GuestThread {
4737 fn type_name() -> &'static str {
4738 "GuestThread"
4739 }
4740}
4741
4742enum SyncResult {
4743 NotProduced,
4744 Produced(Option<ValRaw>),
4745 Taken,
4746}
4747
4748impl SyncResult {
4749 fn take(&mut self) -> Result<Option<Option<ValRaw>>> {
4750 Ok(match mem::replace(self, SyncResult::Taken) {
4751 SyncResult::NotProduced => None,
4752 SyncResult::Produced(val) => Some(val),
4753 SyncResult::Taken => {
4754 bail_bug!("attempted to take a synchronous result that was already taken")
4755 }
4756 })
4757 }
4758}
4759
4760#[derive(Debug)]
4761enum HostFutureState {
4762 NotApplicable,
4763 Live,
4764 Dropped,
4765}
4766
4767pub(crate) struct GuestTask {
4769 common: WaitableCommon,
4771 lower_params: Option<RawLower>,
4773 lift_result: Option<LiftResult>,
4775 result: Option<LiftedResult>,
4778 callback: Option<CallbackFn>,
4781 caller: Caller,
4783 call_context: CallContext,
4788 sync_result: SyncResult,
4791 cancel_sent: bool,
4794 starting_sent: bool,
4797 instance: RuntimeInstance,
4804 event: Option<Event>,
4807 exited: bool,
4809 threads: HashSet<TableId<GuestThread>>,
4811 host_future_state: HostFutureState,
4814 async_function: bool,
4817
4818 decremented_interesting_task_count: bool,
4819}
4820
4821impl GuestTask {
4822 fn already_lowered_parameters(&self) -> bool {
4823 self.lower_params.is_none()
4825 }
4826
4827 fn returned_or_cancelled(&self) -> bool {
4828 self.lift_result.is_none()
4830 }
4831
4832 fn ready_to_delete(&self) -> bool {
4833 let threads_completed = self.threads.is_empty();
4834 let has_sync_result = matches!(self.sync_result, SyncResult::Produced(_));
4835 let pending_completion_event = matches!(
4836 self.common.event,
4837 Some(Event::Subtask {
4838 status: Status::Returned | Status::ReturnCancelled
4839 })
4840 );
4841 let ready = threads_completed
4842 && !has_sync_result
4843 && !pending_completion_event
4844 && !matches!(self.host_future_state, HostFutureState::Live);
4845 log::trace!(
4846 "ready to delete? {ready} (threads_completed: {}, has_sync_result: {}, pending_completion_event: {}, host_future_state: {:?})",
4847 threads_completed,
4848 has_sync_result,
4849 pending_completion_event,
4850 self.host_future_state
4851 );
4852 ready
4853 }
4854
4855 fn new(
4856 state: &mut ConcurrentState,
4857 lower_params: RawLower,
4858 lift_result: LiftResult,
4859 caller: Caller,
4860 callback: Option<CallbackFn>,
4861 instance: RuntimeInstance,
4862 async_function: bool,
4863 ) -> Result<QualifiedThreadId> {
4864 let host_future_state = match &caller {
4865 Caller::Guest { .. } => HostFutureState::NotApplicable,
4866 Caller::Host {
4867 host_future_present,
4868 ..
4869 } => {
4870 if *host_future_present {
4871 HostFutureState::Live
4872 } else {
4873 HostFutureState::NotApplicable
4874 }
4875 }
4876 };
4877 let task = state.push(Self {
4878 common: WaitableCommon::default(),
4879 lower_params: Some(lower_params),
4880 lift_result: Some(lift_result),
4881 result: None,
4882 callback,
4883 caller,
4884 call_context: CallContext::default(),
4885 sync_result: SyncResult::NotProduced,
4886 cancel_sent: false,
4887 starting_sent: false,
4888 instance,
4889 event: None,
4890 exited: false,
4891 threads: HashSet::new(),
4892 host_future_state,
4893 async_function,
4894 decremented_interesting_task_count: false,
4895 })?;
4896 let new_thread = GuestThread::new_implicit(state, task)?;
4897 let thread = state.push(new_thread)?;
4898 state.get_mut(task)?.threads.insert(thread);
4899 state.interesting_tasks += 1;
4900 Ok(QualifiedThreadId { task, thread })
4901 }
4902}
4903
4904impl TableDebug for GuestTask {
4905 fn type_name() -> &'static str {
4906 "GuestTask"
4907 }
4908}
4909
4910#[derive(Default)]
4912struct WaitableCommon {
4913 event: Option<Event>,
4915 set: Option<TableId<WaitableSet>>,
4917 handle: Option<u32>,
4919}
4920
4921#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
4923enum Waitable {
4924 Host(TableId<HostTask>),
4926 Guest(TableId<GuestTask>),
4928 Transmit(TableId<TransmitHandle>),
4930}
4931
4932impl Waitable {
4933 fn from_instance(
4936 state: Pin<&mut ComponentInstance>,
4937 caller_instance: RuntimeComponentInstanceIndex,
4938 waitable: u32,
4939 ) -> Result<Self> {
4940 use crate::runtime::vm::component::Waitable;
4941
4942 let (waitable, kind) = state.instance_states().0[caller_instance]
4943 .handle_table()
4944 .waitable_rep(waitable)?;
4945
4946 Ok(match kind {
4947 Waitable::Subtask { is_host: true } => Self::Host(TableId::new(waitable)),
4948 Waitable::Subtask { is_host: false } => Self::Guest(TableId::new(waitable)),
4949 Waitable::Stream | Waitable::Future => Self::Transmit(TableId::new(waitable)),
4950 })
4951 }
4952
4953 fn rep(&self) -> u32 {
4955 match self {
4956 Self::Host(id) => id.rep(),
4957 Self::Guest(id) => id.rep(),
4958 Self::Transmit(id) => id.rep(),
4959 }
4960 }
4961
4962 fn join(&self, state: &mut ConcurrentState, set: Option<TableId<WaitableSet>>) -> Result<()> {
4966 log::trace!("waitable {self:?} join set {set:?}");
4967
4968 let old = mem::replace(&mut self.common(state)?.set, set);
4969
4970 if let Some(old) = old {
4971 match *self {
4972 Waitable::Host(id) => state.remove_child(id, old),
4973 Waitable::Guest(id) => state.remove_child(id, old),
4974 Waitable::Transmit(id) => state.remove_child(id, old),
4975 }?;
4976
4977 state.get_mut(old)?.ready.remove(self);
4978 }
4979
4980 if let Some(set) = set {
4981 match *self {
4982 Waitable::Host(id) => state.add_child(id, set),
4983 Waitable::Guest(id) => state.add_child(id, set),
4984 Waitable::Transmit(id) => state.add_child(id, set),
4985 }?;
4986
4987 if self.common(state)?.event.is_some() {
4988 self.mark_ready(state)?;
4989 }
4990 }
4991
4992 Ok(())
4993 }
4994
4995 fn common<'a>(&self, state: &'a mut ConcurrentState) -> Result<&'a mut WaitableCommon> {
4997 Ok(match self {
4998 Self::Host(id) => &mut state.get_mut(*id)?.common,
4999 Self::Guest(id) => &mut state.get_mut(*id)?.common,
5000 Self::Transmit(id) => &mut state.get_mut(*id)?.common,
5001 })
5002 }
5003
5004 fn set_event(&self, state: &mut ConcurrentState, event: Option<Event>) -> Result<()> {
5008 log::trace!("set event for {self:?}: {event:?}");
5009 self.common(state)?.event = event;
5010 self.mark_ready(state)
5011 }
5012
5013 fn take_event(&self, state: &mut ConcurrentState) -> Result<Option<Event>> {
5015 let common = self.common(state)?;
5016 let event = common.event.take();
5017 if let Some(set) = self.common(state)?.set {
5018 state.get_mut(set)?.ready.remove(self);
5019 }
5020
5021 Ok(event)
5022 }
5023
5024 fn mark_ready(&self, state: &mut ConcurrentState) -> Result<()> {
5028 if let Some(set) = self.common(state)?.set {
5029 state.get_mut(set)?.ready.insert(*self);
5030 if let Some((thread, mode)) = state.get_mut(set)?.waiting.pop_first() {
5031 let wake_on_cancel = state.get_mut(thread.thread)?.wake_on_cancel.take();
5032 assert!(wake_on_cancel.is_none() || wake_on_cancel == Some(set));
5033
5034 let item = match mode {
5035 WaitMode::Fiber(fiber) => WorkItem::ResumeFiber(fiber),
5036 WaitMode::Callback(instance) => WorkItem::GuestCall(
5037 state.get_mut(thread.task)?.instance.index,
5038 GuestCall {
5039 thread,
5040 kind: GuestCallKind::DeliverEvent {
5041 instance,
5042 set: Some(set),
5043 },
5044 },
5045 ),
5046 };
5047 state.push_high_priority(item);
5048 }
5049 }
5050 Ok(())
5051 }
5052
5053 fn delete_from(&self, state: &mut ConcurrentState) -> Result<()> {
5055 match self {
5056 Self::Host(task) => {
5057 log::trace!("delete host task {task:?}");
5058 state.delete(*task)?;
5059 }
5060 Self::Guest(task) => {
5061 log::trace!("delete guest task {task:?}");
5062 let task = state.delete(*task)?;
5063
5064 debug_assert!(task.decremented_interesting_task_count);
5071 }
5072 Self::Transmit(task) => {
5073 state.delete(*task)?;
5074 }
5075 }
5076
5077 Ok(())
5078 }
5079}
5080
5081impl fmt::Debug for Waitable {
5082 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5083 match self {
5084 Self::Host(id) => write!(f, "{id:?}"),
5085 Self::Guest(id) => write!(f, "{id:?}"),
5086 Self::Transmit(id) => write!(f, "{id:?}"),
5087 }
5088 }
5089}
5090
5091#[derive(Default)]
5093struct WaitableSet {
5094 ready: BTreeSet<Waitable>,
5096 waiting: BTreeMap<QualifiedThreadId, WaitMode>,
5098 is_sync_call_set: bool,
5101}
5102
5103impl TableDebug for WaitableSet {
5104 fn type_name() -> &'static str {
5105 "WaitableSet"
5106 }
5107}
5108
5109type RawLower =
5111 Box<dyn FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync>;
5112
5113type RawLift = Box<
5115 dyn FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
5116>;
5117
5118type LiftedResult = Box<dyn Any + Send + Sync>;
5122
5123struct DummyResult;
5126
5127#[derive(Default)]
5129pub struct ConcurrentInstanceState {
5130 backpressure: u16,
5132 do_not_enter: bool,
5134 pending: BTreeMap<QualifiedThreadId, GuestCallKind>,
5137}
5138
5139impl ConcurrentInstanceState {
5140 pub fn pending_is_empty(&self) -> bool {
5141 self.pending.is_empty()
5142 }
5143}
5144
5145#[derive(Debug, Copy, Clone)]
5146pub(crate) enum CurrentThread {
5147 Guest(QualifiedThreadId),
5148 Host(TableId<HostTask>),
5149 None,
5150}
5151
5152impl CurrentThread {
5153 fn guest(&self) -> Option<&QualifiedThreadId> {
5154 match self {
5155 Self::Guest(id) => Some(id),
5156 _ => None,
5157 }
5158 }
5159
5160 fn host(&self) -> Option<TableId<HostTask>> {
5161 match self {
5162 Self::Host(id) => Some(*id),
5163 _ => None,
5164 }
5165 }
5166
5167 fn is_none(&self) -> bool {
5168 matches!(self, Self::None)
5169 }
5170}
5171
5172impl From<QualifiedThreadId> for CurrentThread {
5173 fn from(id: QualifiedThreadId) -> Self {
5174 Self::Guest(id)
5175 }
5176}
5177
5178impl From<TableId<HostTask>> for CurrentThread {
5179 fn from(id: TableId<HostTask>) -> Self {
5180 Self::Host(id)
5181 }
5182}
5183
5184pub struct ConcurrentState {
5186 unforced_current_thread: CurrentThread,
5192
5193 futures: AlwaysMut<Option<FuturesUnordered<HostTaskFuture>>>,
5198 table: AlwaysMut<ResourceTable>,
5200 high_priority: Vec<WorkItem>,
5202 low_priority: VecDeque<WorkItem>,
5204 suspend_reason: Option<SuspendReason>,
5208 worker: Option<StoreFiber<'static>>,
5212 worker_item: Option<WorkerItem>,
5214
5215 global_error_context_ref_counts:
5228 BTreeMap<TypeComponentGlobalErrorContextTableIndex, GlobalErrorContextRefCount>,
5229
5230 interesting_tasks: usize,
5243
5244 interesting_tasks_empty_waker: Option<Waker>,
5248}
5249
5250impl Default for ConcurrentState {
5251 fn default() -> Self {
5252 Self {
5253 unforced_current_thread: CurrentThread::None,
5254 table: AlwaysMut::new(ResourceTable::new()),
5255 futures: AlwaysMut::new(Some(FuturesUnordered::new())),
5256 high_priority: Vec::new(),
5257 low_priority: VecDeque::new(),
5258 suspend_reason: None,
5259 worker: None,
5260 worker_item: None,
5261 global_error_context_ref_counts: BTreeMap::new(),
5262 interesting_tasks: 0,
5263 interesting_tasks_empty_waker: None,
5264 }
5265 }
5266}
5267
5268impl ConcurrentState {
5269 pub(crate) fn take_fibers_and_futures(
5286 &mut self,
5287 fibers: &mut Vec<StoreFiber<'static>>,
5288 futures: &mut Vec<FuturesUnordered<HostTaskFuture>>,
5289 ) {
5290 for entry in self.table.get_mut().iter_mut() {
5291 if let Some(set) = entry.downcast_mut::<WaitableSet>() {
5292 for mode in mem::take(&mut set.waiting).into_values() {
5293 if let WaitMode::Fiber(fiber) = mode {
5294 fibers.push(fiber);
5295 }
5296 }
5297 } else if let Some(thread) = entry.downcast_mut::<GuestThread>() {
5298 if let GuestThreadState::Suspended(fiber) | GuestThreadState::Ready { fiber, .. } =
5299 mem::replace(&mut thread.state, GuestThreadState::Completed)
5300 {
5301 fibers.push(fiber);
5302 }
5303 }
5304 }
5305
5306 if let Some(fiber) = self.worker.take() {
5307 fibers.push(fiber);
5308 }
5309
5310 let mut handle_item = |item| match item {
5311 WorkItem::ResumeFiber(fiber) => {
5312 fibers.push(fiber);
5313 }
5314 WorkItem::PushFuture(future) => {
5315 self.futures
5316 .get_mut()
5317 .as_mut()
5318 .unwrap()
5319 .push(future.into_inner());
5320 }
5321 WorkItem::ResumeThread(..) | WorkItem::GuestCall(..) | WorkItem::WorkerFunction(..) => {
5322 }
5323 };
5324
5325 for item in mem::take(&mut self.high_priority) {
5326 handle_item(item);
5327 }
5328 for item in mem::take(&mut self.low_priority) {
5329 handle_item(item);
5330 }
5331
5332 if let Some(them) = self.futures.get_mut().take() {
5333 futures.push(them);
5334 }
5335 }
5336
5337 #[cfg(feature = "gc")]
5338 pub(crate) fn trace_fiber_roots(
5339 &mut self,
5340 modules: &ModuleRegistry,
5341 unwind: &dyn Unwind,
5342 gc_roots_list: &mut GcRootsList,
5343 ) {
5344 let ConcurrentState {
5345 table,
5346 worker,
5347 high_priority,
5348 low_priority,
5349
5350 futures: _,
5354
5355 worker_item: _,
5357 unforced_current_thread: _,
5358 suspend_reason: _,
5359 global_error_context_ref_counts: _,
5360 interesting_tasks: _,
5361 interesting_tasks_empty_waker: _,
5362 } = self;
5363
5364 for entry in table.get_mut().iter_mut() {
5365 if let Some(set) = entry.downcast_mut::<WaitableSet>() {
5366 for mode in set.waiting.values_mut() {
5367 if let WaitMode::Fiber(fiber) = mode {
5368 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
5369 }
5370 }
5371 } else if let Some(thread) = entry.downcast_mut::<GuestThread>() {
5372 if let GuestThreadState::Suspended(fiber) | GuestThreadState::Ready { fiber, .. } =
5373 &mut thread.state
5374 {
5375 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
5376 }
5377 }
5378 }
5379
5380 if let Some(fiber) = worker {
5381 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
5382 }
5383
5384 let mut handle_item = |item: &mut WorkItem| match item {
5385 WorkItem::ResumeFiber(fiber) => {
5386 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
5387 }
5388 WorkItem::PushFuture(_future) => {
5389 }
5392 WorkItem::ResumeThread(..) | WorkItem::GuestCall(..) | WorkItem::WorkerFunction(..) => {
5393 }
5394 };
5395
5396 for item in high_priority {
5397 handle_item(item);
5398 }
5399 for item in low_priority {
5400 handle_item(item);
5401 }
5402 }
5403
5404 fn push<V: Send + Sync + 'static>(
5405 &mut self,
5406 value: V,
5407 ) -> Result<TableId<V>, ResourceTableError> {
5408 self.table.get_mut().push(value).map(TableId::from)
5409 }
5410
5411 fn get_mut<V: 'static>(&mut self, id: TableId<V>) -> Result<&mut V, ResourceTableError> {
5412 self.table.get_mut().get_mut(&Resource::from(id))
5413 }
5414
5415 pub fn add_child<T: 'static, U: 'static>(
5416 &mut self,
5417 child: TableId<T>,
5418 parent: TableId<U>,
5419 ) -> Result<(), ResourceTableError> {
5420 self.table
5421 .get_mut()
5422 .add_child(Resource::from(child), Resource::from(parent))
5423 }
5424
5425 pub fn remove_child<T: 'static, U: 'static>(
5426 &mut self,
5427 child: TableId<T>,
5428 parent: TableId<U>,
5429 ) -> Result<(), ResourceTableError> {
5430 self.table
5431 .get_mut()
5432 .remove_child(Resource::from(child), Resource::from(parent))
5433 }
5434
5435 fn delete<V: 'static>(&mut self, id: TableId<V>) -> Result<V, ResourceTableError> {
5436 self.table.get_mut().delete(Resource::from(id))
5437 }
5438
5439 fn push_future(&mut self, future: HostTaskFuture) {
5440 self.push_high_priority(WorkItem::PushFuture(AlwaysMut::new(future)));
5447 }
5448
5449 fn push_high_priority(&mut self, item: WorkItem) {
5450 log::trace!("push high priority: {item:?}");
5451 self.high_priority.push(item);
5452 }
5453
5454 fn push_low_priority(&mut self, item: WorkItem) {
5455 log::trace!("push low priority: {item:?}");
5456 self.low_priority.push_front(item);
5457 }
5458
5459 fn push_work_item(&mut self, item: WorkItem, high_priority: bool) {
5460 if high_priority {
5461 self.push_high_priority(item);
5462 } else {
5463 self.push_low_priority(item);
5464 }
5465 }
5466
5467 fn promote_instance_local_thread_work_item(
5468 &mut self,
5469 current_instance: RuntimeComponentInstanceIndex,
5470 ) -> bool {
5471 self.promote_work_items_matching(|item: &WorkItem| match item {
5472 WorkItem::ResumeThread(instance, _) | WorkItem::GuestCall(instance, _) => {
5473 *instance == current_instance
5474 }
5475 _ => false,
5476 })
5477 }
5478
5479 fn promote_thread_work_item(&mut self, thread: QualifiedThreadId) -> bool {
5480 self.promote_work_items_matching(|item: &WorkItem| match item {
5481 WorkItem::ResumeThread(_, t) | WorkItem::GuestCall(_, GuestCall { thread: t, .. }) => {
5482 *t == thread
5483 }
5484 _ => false,
5485 })
5486 }
5487
5488 fn promote_work_items_matching<F>(&mut self, mut predicate: F) -> bool
5489 where
5490 F: FnMut(&WorkItem) -> bool,
5491 {
5492 if self.high_priority.iter().any(&mut predicate) {
5496 true
5497 }
5498 else if let Some(idx) = self.low_priority.iter().position(&mut predicate) {
5501 let item = self.low_priority.remove(idx).unwrap();
5502 self.push_high_priority(item);
5503 true
5504 } else {
5505 false
5506 }
5507 }
5508
5509 fn check_blocking_for(&mut self, task: TableId<GuestTask>) -> Result<()> {
5510 if self.may_block(task)? {
5511 Ok(())
5512 } else {
5513 Err(Trap::CannotBlockSyncTask.into())
5514 }
5515 }
5516
5517 fn may_block(&mut self, task: TableId<GuestTask>) -> Result<bool> {
5518 let task = self.get_mut(task)?;
5519 Ok(task.async_function || task.returned_or_cancelled())
5520 }
5521
5522 pub fn call_context(&mut self, task: u32) -> Result<&mut CallContext> {
5528 let (task, is_host) = (task >> 1, task & 1 == 1);
5529 if is_host {
5530 let task: TableId<HostTask> = TableId::new(task);
5531 Ok(&mut self.get_mut(task)?.call_context)
5532 } else {
5533 let task: TableId<GuestTask> = TableId::new(task);
5534 Ok(&mut self.get_mut(task)?.call_context)
5535 }
5536 }
5537
5538 pub fn current_call_context_scope_id(&self) -> Result<u32> {
5541 let (bits, is_host) = match self.unforced_current_thread {
5542 CurrentThread::Guest(id) => (id.task.rep(), false),
5543 CurrentThread::Host(id) => (id.rep(), true),
5544 CurrentThread::None => bail_bug!("current thread is not set"),
5545 };
5546 assert_eq!((bits << 1) >> 1, bits);
5547 Ok((bits << 1) | u32::from(is_host))
5548 }
5549
5550 fn futures_mut(&mut self) -> Result<&mut FuturesUnordered<HostTaskFuture>> {
5551 match self.futures.get_mut().as_mut() {
5552 Some(f) => Ok(f),
5553 None => bail_bug!("futures field of concurrent state is currently taken"),
5554 }
5555 }
5556
5557 pub(crate) fn table(&mut self) -> &mut ResourceTable {
5558 self.table.get_mut()
5559 }
5560
5561 fn parent(&mut self, cur: CurrentThread) -> Option<CurrentThread> {
5563 match cur {
5564 CurrentThread::Guest(thread) => {
5565 let task = self.get_mut(thread.task).ok()?;
5566 Some(match task.caller {
5567 Caller::Host { caller, .. } => caller,
5568 Caller::Guest { thread } => thread.into(),
5569 })
5570 }
5571 CurrentThread::Host(id) => Some(self.get_mut(id).ok()?.caller.into()),
5572 CurrentThread::None => None,
5573 }
5574 }
5575}
5576
5577fn for_any_lower<
5580 F: FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync,
5581>(
5582 fun: F,
5583) -> F {
5584 fun
5585}
5586
5587fn for_any_lift<
5589 F: FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
5590>(
5591 fun: F,
5592) -> F {
5593 fun
5594}
5595
5596fn check_ambient_store(id: StoreId) {
5597 let message = "\
5598 `Future`s which depend on asynchronous component tasks, streams, or \
5599 futures to complete may only be polled from the event loop of the \
5600 store to which they belong. Please use \
5601 `StoreContextMut::{run_concurrent,spawn}` to poll or await them.\
5602 ";
5603 tls::try_get(|store| {
5604 let matched = match store {
5605 tls::TryGet::Some(store) => store.id() == id,
5606 tls::TryGet::Taken | tls::TryGet::None => false,
5607 };
5608
5609 if !matched {
5610 panic!("{message}")
5611 }
5612 });
5613}
5614
5615fn check_recursive_run() {
5618 tls::try_get(|store| {
5619 if !matches!(store, tls::TryGet::None) {
5620 panic!("Recursive `StoreContextMut::run_concurrent` calls not supported")
5621 }
5622 });
5623}
5624
5625fn unpack_callback_code(code: u32) -> (u32, u32) {
5626 (code & 0xF, code >> 4)
5627}
5628
5629struct WaitableCheckParams {
5633 set: TableId<WaitableSet>,
5634 options: OptionsIndex,
5635 payload: u32,
5636}
5637
5638enum WaitableCheck {
5641 Wait,
5642 Poll,
5643}
5644
5645#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
5654pub struct GuestTaskId(TableId<GuestTask>);
5655
5656pub(crate) struct PreparedCall<R> {
5658 handle: Func,
5660 thread: QualifiedThreadId,
5662 param_count: usize,
5664 rx: oneshot::Receiver<LiftedResult>,
5667 runtime_instance: RuntimeInstance,
5669 _phantom: PhantomData<R>,
5670}
5671
5672impl<R> PreparedCall<R> {
5673 pub(crate) fn task_id(&self) -> TaskId {
5675 TaskId {
5676 task: self.thread.task,
5677 runtime_instance: self.runtime_instance,
5678 }
5679 }
5680}
5681
5682pub(crate) struct TaskId {
5684 task: TableId<GuestTask>,
5685 runtime_instance: RuntimeInstance,
5686}
5687
5688impl TaskId {
5689 pub(crate) fn host_future_dropped(&self, store: &mut StoreOpaque) -> Result<()> {
5695 let task = store.concurrent_state_mut()?.get_mut(self.task)?;
5696 let delete = if !task.already_lowered_parameters() {
5697 store.cancel_guest_subtask_without_lowered_parameters(
5698 self.runtime_instance,
5699 self.task,
5700 )?;
5701 true
5702 } else {
5703 task.host_future_state = HostFutureState::Dropped;
5704 task.ready_to_delete()
5705 };
5706 if delete {
5707 Waitable::Guest(self.task).delete_from(store.concurrent_state_mut()?)?
5708 }
5709 Ok(())
5710 }
5711}
5712
5713pub(crate) fn prepare_call<T, R>(
5719 mut store: StoreContextMut<T>,
5720 handle: Func,
5721 param_count: usize,
5722 host_future_present: bool,
5723 lower_params: impl FnOnce(Func, StoreContextMut<T>, &mut [MaybeUninit<ValRaw>]) -> Result<()>
5724 + Send
5725 + Sync
5726 + 'static,
5727 lift_result: impl FnOnce(Func, &mut StoreOpaque, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>>
5728 + Send
5729 + Sync
5730 + 'static,
5731) -> Result<PreparedCall<R>> {
5732 let (options, _flags, ty, raw_options) = handle.abi_info(store.0);
5733
5734 let instance = handle.instance().id().get(store.0);
5735 let options = &instance.component().env_component().options[options];
5736 let ty = &instance.component().types()[ty];
5737 let async_function = ty.async_;
5738 let task_return_type = ty.results;
5739 let component_instance = raw_options.instance;
5740 let callback = options.callback.map(|i| instance.runtime_callback(i));
5741 let memory = options
5742 .memory()
5743 .map(|i| instance.runtime_memory(i))
5744 .map(SendSyncPtr::new);
5745 let string_encoding = options.string_encoding;
5746 let token = StoreToken::new(store.as_context_mut());
5747 let caller = store.0.current_thread()?;
5748 let state = store.0.concurrent_state_mut()?;
5749
5750 let (tx, rx) = oneshot::channel();
5751
5752 let instance = handle.instance().runtime_instance(component_instance);
5753 let thread = GuestTask::new(
5754 state,
5755 Box::new(for_any_lower(move |store, params| {
5756 lower_params(handle, token.as_context_mut(store), params)
5757 })),
5758 LiftResult {
5759 lift: Box::new(for_any_lift(move |store, result| {
5760 lift_result(handle, store, result)
5761 })),
5762 ty: task_return_type,
5763 memory,
5764 string_encoding,
5765 },
5766 Caller::Host {
5767 tx: Some(tx),
5768 host_future_present,
5769 caller,
5770 },
5771 callback.map(|callback| {
5772 let callback = SendSyncPtr::new(callback);
5773 let instance = handle.instance();
5774 Box::new(move |store: &mut dyn VMStore, event, handle| {
5775 let store = token.as_context_mut(store);
5776 unsafe { instance.call_callback(store, callback, event, handle) }
5779 }) as CallbackFn
5780 }),
5781 instance,
5782 async_function,
5783 )?;
5784
5785 if !store.0.may_enter(instance)? {
5786 bail!(Trap::CannotEnterComponent);
5787 }
5788
5789 Ok(PreparedCall {
5790 handle,
5791 thread,
5792 param_count,
5793 runtime_instance: instance,
5794 rx,
5795 _phantom: PhantomData,
5796 })
5797}
5798
5799pub(crate) struct QueuedCall<R> {
5800 store: StoreId,
5801 task: TableId<GuestTask>,
5802 rx: oneshot::Receiver<LiftedResult>,
5803 _marker: PhantomData<fn() -> R>,
5804}
5805
5806impl<R> QueuedCall<R> {
5807 pub(crate) fn new<T: 'static>(
5814 mut store: StoreContextMut<T>,
5815 prepared: PreparedCall<R>,
5816 ) -> Result<QueuedCall<R>> {
5817 let PreparedCall {
5818 handle,
5819 thread,
5820 param_count,
5821 rx,
5822 ..
5823 } = prepared;
5824
5825 queue_call0(store.as_context_mut(), handle, thread, param_count)?;
5826
5827 Ok(QueuedCall {
5828 store: store.0.id(),
5829 task: thread.task,
5830 rx,
5831 _marker: PhantomData,
5832 })
5833 }
5834
5835 fn task(&self) -> GuestTaskId {
5836 GuestTaskId(self.task)
5837 }
5838}
5839
5840impl<R> Future for QueuedCall<R>
5841where
5842 R: 'static,
5843{
5844 type Output = Result<R>;
5845
5846 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
5847 check_ambient_store(self.store);
5848 Pin::new(&mut self.rx).poll(cx).map(|result| match result {
5849 Ok(r) => match r.downcast() {
5850 Ok(r) => Ok(*r),
5851 Err(_) => bail_bug!("wrong type of value produced"),
5852 },
5853 Err(oneshot::Canceled) => bail_bug!("channel erroneously dropped"),
5854 })
5855 }
5856}
5857
5858fn queue_call0<T: 'static>(
5861 store: StoreContextMut<T>,
5862 handle: Func,
5863 guest_thread: QualifiedThreadId,
5864 param_count: usize,
5865) -> Result<()> {
5866 let (_options, _, _ty, raw_options) = handle.abi_info(store.0);
5867 let is_concurrent = raw_options.async_;
5868 let callback = raw_options.callback;
5869 let instance = handle.instance();
5870 let callee = handle.lifted_core_func(store.0);
5871 let post_return = handle.post_return_core_func(store.0);
5872 let callback = callback.map(|i| {
5873 let instance = instance.id().get(store.0);
5874 SendSyncPtr::new(instance.runtime_callback(i))
5875 });
5876
5877 log::trace!("queueing call {guest_thread:?}");
5878
5879 unsafe {
5883 instance.queue_call(
5884 store,
5885 guest_thread,
5886 SendSyncPtr::new(callee),
5887 param_count,
5888 1,
5889 is_concurrent,
5890 callback,
5891 post_return.map(SendSyncPtr::new),
5892 )
5893 }
5894}