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 pub fn poll_ready_for_concurrent_call(&self, func: Func, cx: &mut Context<'_>) -> Poll<()> {
600 self.with(|mut access| {
601 let store = access.as_context_mut().0;
602 let (_, _, _, raw_options) = func.abi_info(store);
603 let instance = func.instance().runtime_instance(raw_options.instance);
604 let state = store.instance_state(instance).concurrent_state();
605 if state.backpressure == 0 {
606 Poll::Ready(())
607 } else {
608 store
609 .concurrent_state_mut_without_forcing_current_thread()
610 .ready_for_concurrent_call_waker = Some(cx.waker().clone());
611 Poll::Pending
612 }
613 })
614 }
615}
616
617pub trait AccessorTask<T, D = HasSelf<T>>: Send + 'static
629where
630 D: HasData + ?Sized,
631{
632 fn run(self, accessor: &Accessor<T, D>) -> impl Future<Output = Result<()>> + Send;
634}
635
636enum CallerInfo {
639 Async {
641 params: Vec<ValRaw>,
642 has_result: bool,
643 },
644 Sync {
646 params: Vec<ValRaw>,
647 result_count: u32,
648 },
649}
650
651enum WaitMode {
653 Fiber(StoreFiber<'static>),
655 Callback(Instance),
658}
659
660#[derive(Debug)]
662enum SuspendReason {
663 Waiting {
666 set: TableId<WaitableSet>,
667 thread: QualifiedThreadId,
668 skip_may_block_check: bool,
669 },
670 NeedWork,
673 Yielding {
676 thread: QualifiedThreadId,
677 cancellable: bool,
678 skip_may_block_check: bool,
679 },
680 ExplicitlySuspending {
682 thread: QualifiedThreadId,
683 skip_may_block_check: bool,
684 },
685}
686
687enum GuestCallKind {
689 DeliverEvent {
692 instance: Instance,
694 set: Option<TableId<WaitableSet>>,
699 },
700 StartImplicit(Box<dyn FnOnce(&mut dyn VMStore) -> Result<Option<GuestCall>> + Send + Sync>),
706 StartExplicit(Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send + Sync>),
707}
708
709impl fmt::Debug for GuestCallKind {
710 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
711 match self {
712 Self::DeliverEvent { instance, set } => f
713 .debug_struct("DeliverEvent")
714 .field("instance", instance)
715 .field("set", set)
716 .finish(),
717 Self::StartImplicit(_) => f.debug_tuple("StartImplicit").finish(),
718 Self::StartExplicit(_) => f.debug_tuple("StartExplicit").finish(),
719 }
720 }
721}
722
723#[derive(Copy, Clone, Debug)]
725pub enum SuspensionTarget {
726 SomeSuspended(u32),
727 Some(u32),
728 None,
729}
730
731impl SuspensionTarget {
732 fn is_none(&self) -> bool {
733 matches!(self, SuspensionTarget::None)
734 }
735 fn is_some(&self) -> bool {
736 !self.is_none()
737 }
738}
739
740#[derive(Debug)]
742struct GuestCall {
743 thread: QualifiedThreadId,
744 kind: GuestCallKind,
745}
746
747impl GuestCall {
748 fn is_ready(&self, store: &mut StoreOpaque) -> Result<bool> {
758 let instance = store
759 .concurrent_state_mut()?
760 .get_mut(self.thread.task)?
761 .instance;
762 let state = store.instance_state(instance).concurrent_state();
763
764 let ready = match &self.kind {
765 GuestCallKind::DeliverEvent { .. } => !state.do_not_enter,
766 GuestCallKind::StartImplicit(_) => !(state.do_not_enter || state.backpressure > 0),
767 GuestCallKind::StartExplicit(_) => true,
768 };
769 log::trace!(
770 "call {self:?} ready? {ready} (do_not_enter: {}; backpressure: {})",
771 state.do_not_enter,
772 state.backpressure
773 );
774 Ok(ready)
775 }
776}
777
778enum WorkerItem {
780 GuestCall(GuestCall),
781 Function(AlwaysMut<Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send>>),
782}
783
784enum WorkItem {
787 PushFuture(AlwaysMut<HostTaskFuture>),
789 ResumeFiber(StoreFiber<'static>),
791 ResumeThread(RuntimeComponentInstanceIndex, QualifiedThreadId),
793 GuestCall(RuntimeComponentInstanceIndex, GuestCall),
795 WorkerFunction(AlwaysMut<Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send>>),
797}
798
799impl fmt::Debug for WorkItem {
800 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
801 match self {
802 Self::PushFuture(_) => f.debug_tuple("PushFuture").finish(),
803 Self::ResumeFiber(_) => f.debug_tuple("ResumeFiber").finish(),
804 Self::ResumeThread(instance, thread) => f
805 .debug_tuple("ResumeThread")
806 .field(instance)
807 .field(thread)
808 .finish(),
809 Self::GuestCall(instance, call) => f
810 .debug_tuple("GuestCall")
811 .field(instance)
812 .field(call)
813 .finish(),
814 Self::WorkerFunction(_) => f.debug_tuple("WorkerFunction").finish(),
815 }
816 }
817}
818
819#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
821pub(crate) enum WaitResult {
822 Cancelled,
823 Completed,
824}
825
826pub(crate) fn poll_and_block<R: Send + Sync + 'static>(
834 store: &mut dyn VMStore,
835 host_task: EnteredHostTask,
836 future: impl Future<Output = Result<R>> + Send + 'static,
837) -> Result<R> {
838 let task = store.current_host_thread()?;
839
840 let mut future = Box::pin(async move {
844 let result = future.await?;
845 tls::get(move |store| {
846 let state = store.concurrent_state_mut()?;
847 let host_state = &mut state.get_mut(task)?.state;
848 assert!(matches!(host_state, HostTaskState::CalleeStarted));
849 *host_state = HostTaskState::CalleeFinished(Box::new(result));
850
851 Waitable::Host(task).set_event(
852 state,
853 Some(Event::Subtask {
854 status: Status::Returned,
855 }),
856 )?;
857
858 Ok(())
859 })
860 }) as HostTaskFuture;
861
862 let poll = tls::set(store, || {
866 future
867 .as_mut()
868 .poll(&mut Context::from_waker(&Waker::noop()))
869 });
870
871 let caller = match host_task {
872 Some(pair) => pair.1,
873 None => bail_bug!("host task wasn't created but should have been"),
874 };
875
876 match poll {
877 Poll::Ready(result) => result?,
879
880 Poll::Pending => {
885 let state = store.concurrent_state_mut()?;
886 state.push_future(future);
887
888 let set = state.get_mut(caller.thread)?.sync_call_set;
889 Waitable::Host(task).join(state, Some(set))?;
890
891 store.suspend(SuspendReason::Waiting {
892 set,
893 thread: caller,
894 skip_may_block_check: false,
895 })?;
896
897 Waitable::Host(task).join(store.concurrent_state_mut()?, None)?;
901 }
902 }
903
904 let host_state = &mut store.concurrent_state_mut()?.get_mut(task)?.state;
906 match mem::replace(host_state, HostTaskState::CalleeDone { cancelled: false }) {
907 HostTaskState::CalleeFinished(result) => Ok(match result.downcast() {
908 Ok(result) => *result,
909 Err(_) => bail_bug!("host task finished with wrong type of result"),
910 }),
911 _ => bail_bug!("unexpected host task state after completion"),
912 }
913}
914
915fn handle_guest_call(store: &mut dyn VMStore, call: GuestCall) -> Result<()> {
917 let mut next = Some(call);
918 while let Some(call) = next.take() {
919 match call.kind {
920 GuestCallKind::DeliverEvent { instance, set } => {
921 let (event, waitable) =
922 match instance.get_event(store, call.thread.task, set, true)? {
923 Some(pair) => pair,
924 None => bail_bug!("delivering non-present event"),
925 };
926 let state = store.concurrent_state_mut()?;
927 let task = state.get_mut(call.thread.task)?;
928 let runtime_instance = task.instance;
929 let handle = waitable.map(|(_, v)| v).unwrap_or(0);
930
931 log::trace!(
932 "use callback to deliver event {event:?} to {:?} for {waitable:?}",
933 call.thread,
934 );
935
936 let old_thread = store.set_thread(call.thread)?;
937 log::trace!(
938 "GuestCallKind::DeliverEvent: replaced {old_thread:?} with {:?} as current thread",
939 call.thread
940 );
941
942 store.enter_instance(runtime_instance);
943
944 let Some(callback) = store
945 .concurrent_state_mut()?
946 .get_mut(call.thread.task)?
947 .callback
948 .take()
949 else {
950 bail_bug!("guest task callback field not present")
951 };
952
953 let code = callback(store, event, handle)?;
954
955 store
956 .concurrent_state_mut()?
957 .get_mut(call.thread.task)?
958 .callback = Some(callback);
959
960 store.exit_instance(runtime_instance)?;
961
962 store.set_thread(old_thread)?;
963
964 next = instance.handle_callback_code(
965 store,
966 call.thread,
967 runtime_instance.index,
968 code,
969 )?;
970
971 log::trace!(
972 "GuestCallKind::DeliverEvent: restored {old_thread:?} as current thread"
973 );
974 }
975 GuestCallKind::StartImplicit(fun) => {
976 next = fun(store)?;
977 }
978 GuestCallKind::StartExplicit(fun) => {
979 fun(store)?;
980 }
981 }
982 }
983
984 Ok(())
985}
986
987impl<T> Store<T> {
988 pub async fn run_concurrent<R>(&mut self, fun: impl AsyncFnOnce(&Accessor<T>) -> R) -> Result<R>
990 where
991 T: Send + 'static,
992 {
993 ensure!(
994 self.as_context().0.concurrency_support(),
995 "cannot use `run_concurrent` when Config::concurrency_support disabled",
996 );
997 self.as_context_mut().run_concurrent(fun).await
998 }
999
1000 #[doc(hidden)]
1001 pub fn assert_concurrent_state_empty(&mut self) {
1002 self.as_context_mut().assert_concurrent_state_empty();
1003 }
1004
1005 #[doc(hidden)]
1006 pub fn concurrent_state_table_size(&mut self) -> usize {
1007 self.as_context_mut().concurrent_state_table_size()
1008 }
1009
1010 pub fn spawn(&mut self, task: impl AccessorTask<T, HasSelf<T>>) -> Result<JoinHandle>
1012 where
1013 T: 'static,
1014 {
1015 self.as_context_mut().spawn(task)
1016 }
1017}
1018
1019impl<T> StoreContextMut<'_, T> {
1020 #[doc(hidden)]
1031 pub fn assert_concurrent_state_empty(self) {
1032 let store = self.0;
1033 store
1034 .store_data_mut()
1035 .components
1036 .assert_instance_states_empty();
1037 let state = store.concurrent_state_mut().unwrap();
1038 assert!(
1039 state.table.get_mut().is_empty(),
1040 "non-empty table: {:?}",
1041 state.table.get_mut()
1042 );
1043 assert!(state.high_priority.is_empty());
1044 assert!(state.low_priority.is_empty());
1045 assert!(state.unforced_current_thread.is_none());
1046 assert!(state.futures_mut().unwrap().is_empty());
1047 assert!(state.global_error_context_ref_counts.is_empty());
1048 }
1049
1050 #[doc(hidden)]
1055 pub fn concurrent_state_table_size(&mut self) -> usize {
1056 self.0
1057 .concurrent_state_mut()
1058 .unwrap()
1059 .table
1060 .get_mut()
1061 .iter_mut()
1062 .count()
1063 }
1064
1065 pub fn spawn(mut self, task: impl AccessorTask<T>) -> Result<JoinHandle>
1075 where
1076 T: 'static,
1077 {
1078 let accessor = Accessor::new(StoreToken::new(self.as_context_mut()));
1079 self.spawn_with_accessor(accessor, task)
1080 }
1081
1082 fn spawn_with_accessor<D>(
1085 self,
1086 accessor: Accessor<T, D>,
1087 task: impl AccessorTask<T, D>,
1088 ) -> Result<JoinHandle>
1089 where
1090 T: 'static,
1091 D: HasData + ?Sized,
1092 {
1093 let (handle, future) = JoinHandle::run(async move { task.run(&accessor).await });
1097 self.0
1098 .concurrent_state_mut()?
1099 .push_future(Box::pin(async move { future.await.unwrap_or(Ok(())) }));
1100 Ok(handle)
1101 }
1102
1103 pub async fn run_concurrent<R>(self, fun: impl AsyncFnOnce(&Accessor<T>) -> R) -> Result<R>
1187 where
1188 T: Send + 'static,
1189 {
1190 ensure!(
1191 self.0.concurrency_support(),
1192 "cannot use `run_concurrent` when Config::concurrency_support disabled",
1193 );
1194 self.do_run_concurrent(fun, false).await
1195 }
1196
1197 pub(super) async fn run_concurrent_trap_on_idle<R>(
1198 self,
1199 fun: impl AsyncFnOnce(&Accessor<T>) -> R,
1200 ) -> Result<R>
1201 where
1202 T: Send + 'static,
1203 {
1204 self.do_run_concurrent(fun, true).await
1205 }
1206
1207 async fn do_run_concurrent<R>(
1208 mut self,
1209 fun: impl AsyncFnOnce(&Accessor<T>) -> R,
1210 trap_on_idle: bool,
1211 ) -> Result<R>
1212 where
1213 T: Send + 'static,
1214 {
1215 debug_assert!(self.0.concurrency_support());
1216 check_recursive_run();
1217 let token = StoreToken::new(self.as_context_mut());
1218
1219 struct Dropper<'a, T: 'static, V> {
1220 store: StoreContextMut<'a, T>,
1221 value: ManuallyDrop<V>,
1222 }
1223
1224 impl<'a, T, V> Drop for Dropper<'a, T, V> {
1225 fn drop(&mut self) {
1226 tls::set(self.store.0, || {
1227 unsafe { ManuallyDrop::drop(&mut self.value) }
1232 });
1233 }
1234 }
1235
1236 let accessor = &Accessor::new(token);
1237 let dropper = &mut Dropper {
1238 store: self,
1239 value: ManuallyDrop::new(fun(accessor)),
1240 };
1241 let future = unsafe { Pin::new_unchecked(dropper.value.deref_mut()) };
1243
1244 dropper
1245 .store
1246 .as_context_mut()
1247 .poll_until(future, trap_on_idle)
1248 .await
1249 }
1250
1251 async fn poll_until<R>(
1257 mut self,
1258 mut future: Pin<&mut impl Future<Output = R>>,
1259 trap_on_idle: bool,
1260 ) -> Result<R>
1261 where
1262 T: Send + 'static,
1263 {
1264 struct Reset<'a, T: 'static> {
1265 store: StoreContextMut<'a, T>,
1266 futures: Option<FuturesUnordered<HostTaskFuture>>,
1267 }
1268
1269 impl<'a, T> Drop for Reset<'a, T> {
1270 fn drop(&mut self) {
1271 if let Some(futures) = self.futures.take() {
1272 *self
1273 .store
1274 .0
1275 .concurrent_state_mut_already_forced_current_thread()
1276 .futures
1277 .get_mut() = Some(futures);
1278 }
1279 }
1280 }
1281
1282 loop {
1283 let futures = self.0.concurrent_state_mut()?.futures.get_mut().take();
1287 let mut reset = Reset {
1288 store: self.as_context_mut(),
1289 futures,
1290 };
1291 let mut next = match reset.futures.as_mut() {
1292 Some(f) => pin!(f.next()),
1293 None => bail_bug!("concurrent state missing futures field"),
1294 };
1295
1296 enum PollResult<R> {
1297 Complete(R),
1298 ProcessWork {
1299 ready: Vec<WorkItem>,
1300 low_priority: bool,
1301 },
1302 }
1303
1304 let result = future::poll_fn(|cx| {
1305 if let Poll::Ready(value) = tls::set(reset.store.0, || future.as_mut().poll(cx)) {
1308 return Poll::Ready(Ok(PollResult::Complete(value)));
1309 }
1310
1311 let next = match tls::set(reset.store.0, || next.as_mut().poll(cx)) {
1315 Poll::Ready(Some(output)) => {
1316 match output {
1317 Err(e) => return Poll::Ready(Err(e)),
1318 Ok(()) => {}
1319 }
1320 Poll::Ready(true)
1321 }
1322 Poll::Ready(None) => Poll::Ready(false),
1323 Poll::Pending => Poll::Pending,
1324 };
1325
1326 let state = reset.store.0.concurrent_state_mut()?;
1330 let mut ready = mem::take(&mut state.high_priority);
1331 let mut low_priority = false;
1332 if ready.is_empty() {
1333 if let Some(item) = state.low_priority.pop_back() {
1334 ready.push(item);
1335 low_priority = true;
1336 }
1337 }
1338 if !ready.is_empty() {
1339 return Poll::Ready(Ok(PollResult::ProcessWork {
1340 ready,
1341 low_priority,
1342 }));
1343 }
1344
1345 return match next {
1349 Poll::Ready(true) => {
1350 Poll::Ready(Ok(PollResult::ProcessWork {
1356 ready: Vec::new(),
1357 low_priority: false,
1358 }))
1359 }
1360 Poll::Ready(false) => {
1361 if let Poll::Ready(value) =
1365 tls::set(reset.store.0, || future.as_mut().poll(cx))
1366 {
1367 Poll::Ready(Ok(PollResult::Complete(value)))
1368 } else {
1369 if trap_on_idle {
1375 Poll::Ready(Err(Trap::AsyncDeadlock.into()))
1378 } else {
1379 Poll::Pending
1383 }
1384 }
1385 }
1386 Poll::Pending => Poll::Pending,
1391 };
1392 })
1393 .await;
1394
1395 drop(reset);
1399
1400 match result? {
1401 PollResult::Complete(value) => break Ok(value),
1404 PollResult::ProcessWork {
1407 ready,
1408 low_priority,
1409 } => {
1410 struct Dispose<'a, T: 'static, I: Iterator<Item = WorkItem>> {
1411 store: StoreContextMut<'a, T>,
1412 ready: I,
1413 }
1414
1415 impl<'a, T, I: Iterator<Item = WorkItem>> Drop for Dispose<'a, T, I> {
1416 fn drop(&mut self) {
1417 while let Some(item) = self.ready.next() {
1418 match item {
1419 WorkItem::ResumeFiber(mut fiber) => fiber.dispose(self.store.0),
1420 WorkItem::PushFuture(future) => {
1421 tls::set(self.store.0, move || drop(future))
1422 }
1423 _ => {}
1424 }
1425 }
1426 }
1427 }
1428
1429 let mut dispose = Dispose {
1430 store: self.as_context_mut(),
1431 ready: ready.into_iter(),
1432 };
1433
1434 if low_priority {
1456 dispose.store.0.yield_now().await
1457 }
1458
1459 while let Some(item) = dispose.ready.next() {
1460 dispose
1461 .store
1462 .as_context_mut()
1463 .handle_work_item(item)
1464 .await?;
1465 }
1466 }
1467 }
1468 }
1469 }
1470
1471 async fn handle_work_item(self, item: WorkItem) -> Result<()>
1473 where
1474 T: Send,
1475 {
1476 log::trace!("handle work item {item:?}");
1477 match item {
1478 WorkItem::PushFuture(future) => {
1479 self.0
1480 .concurrent_state_mut()?
1481 .futures_mut()?
1482 .push(future.into_inner());
1483 }
1484 WorkItem::ResumeFiber(fiber) => {
1485 self.0.resume_fiber(fiber).await?;
1486 }
1487 WorkItem::ResumeThread(_, thread) => {
1488 if let GuestThreadState::Ready { fiber, .. } = mem::replace(
1489 &mut self.0.concurrent_state_mut()?.get_mut(thread.thread)?.state,
1490 GuestThreadState::Running,
1491 ) {
1492 self.0.resume_fiber(fiber).await?;
1493 } else {
1494 bail_bug!("cannot resume non-pending thread {thread:?}");
1495 }
1496 }
1497 WorkItem::GuestCall(_, call) => {
1498 if call.is_ready(self.0)? {
1499 self.run_on_worker(WorkerItem::GuestCall(call)).await?;
1500 } else {
1501 let state = self.0.concurrent_state_mut()?;
1502 let task = state.get_mut(call.thread.task)?;
1503 if !task.starting_sent {
1504 task.starting_sent = true;
1505 if let GuestCallKind::StartImplicit(_) = &call.kind {
1506 Waitable::Guest(call.thread.task).set_event(
1507 state,
1508 Some(Event::Subtask {
1509 status: Status::Starting,
1510 }),
1511 )?;
1512 }
1513 }
1514
1515 let instance = state.get_mut(call.thread.task)?.instance;
1516 self.0
1517 .instance_state(instance)
1518 .concurrent_state()
1519 .pending
1520 .insert(call.thread, call.kind);
1521 }
1522 }
1523 WorkItem::WorkerFunction(fun) => {
1524 self.run_on_worker(WorkerItem::Function(fun)).await?;
1525 }
1526 }
1527
1528 Ok(())
1529 }
1530
1531 async fn run_on_worker(self, item: WorkerItem) -> Result<()>
1533 where
1534 T: Send,
1535 {
1536 let worker = if let Some(fiber) = self.0.concurrent_state_mut()?.worker.take() {
1537 fiber
1538 } else {
1539 fiber::make_fiber(self.0, move |store| {
1540 loop {
1541 let Some(item) = store.concurrent_state_mut()?.worker_item.take() else {
1542 bail_bug!("worker_item not present when resuming fiber")
1543 };
1544 match item {
1545 WorkerItem::GuestCall(call) => handle_guest_call(store, call)?,
1546 WorkerItem::Function(fun) => fun.into_inner()(store)?,
1547 }
1548
1549 store.suspend(SuspendReason::NeedWork)?;
1550 }
1551 })?
1552 };
1553
1554 let worker_item = &mut self.0.concurrent_state_mut()?.worker_item;
1555 assert!(worker_item.is_none());
1556 *worker_item = Some(item);
1557
1558 self.0.resume_fiber(worker).await
1559 }
1560
1561 pub(crate) fn wrap_call<F, R>(self, closure: F) -> impl Future<Output = Result<R>> + 'static
1566 where
1567 T: 'static,
1568 F: FnOnce(&Accessor<T>) -> Pin<Box<dyn Future<Output = Result<R>> + Send + '_>>
1569 + Send
1570 + Sync
1571 + 'static,
1572 R: Send + Sync + 'static,
1573 {
1574 let token = StoreToken::new(self);
1575 async move {
1576 let mut accessor = Accessor::new(token);
1577 closure(&mut accessor).await
1578 }
1579 }
1580
1581 pub fn async_call_stack(&mut self) -> Result<impl Iterator<Item = GuestTaskId>> {
1591 let mut cur = Some(self.0.current_thread()?);
1592 let state = self.0.concurrent_state_mut()?;
1593 Ok(core::iter::from_fn(move || {
1594 while let Some(t) = cur {
1595 cur = state.parent(t);
1596 if let Some(task) = t.guest_task() {
1597 return Some(GuestTaskId(task));
1598 }
1599 }
1600
1601 None
1602 }))
1603 }
1604}
1605
1606pub type EnteredHostTask = Option<(TableId<HostTask>, QualifiedThreadId)>;
1612
1613impl StoreOpaque {
1614 #[inline]
1617 pub(crate) fn current_thread(&mut self) -> Result<CurrentThread> {
1618 if !self.concurrency_support() {
1620 return Ok(CurrentThread::None);
1621 }
1622
1623 if !self
1626 .vm_store_context_mut()
1627 .current_thread_mut()
1628 .is_deferred()
1629 {
1630 return Ok(self
1631 .concurrent_state_mut_already_forced_current_thread()
1632 .unforced_current_thread);
1633 }
1634
1635 self.force_deferred_current_thread()
1636 }
1637
1638 #[cold]
1641 fn force_deferred_current_thread(&mut self) -> Result<CurrentThread> {
1642 let state = self.concurrent_state_mut_without_forcing_current_thread();
1651 let id = match state.unforced_current_thread.guest_task() {
1652 Some(task) => state.get_mut(task)?.instance.instance,
1653 None => bail_bug!("deferred component-model thread with non-guest base"),
1654 };
1655
1656 let mut frames = Vec::new();
1659 let mut cur = *self.vm_store_context_mut().current_thread_mut();
1660 while let Some(ptr) = cur.as_deferred() {
1661 let deferred = unsafe { ptr.as_non_null().as_ref() };
1666 frames.push((
1667 deferred.callee_async != 0,
1668 deferred.callee_instance,
1669 deferred.saved_context,
1670 ));
1671 cur = deferred.parent;
1672 }
1673
1674 *self.vm_store_context_mut().current_thread_mut() = VMLazyThread::forced();
1678
1679 let current_context = *self.vm_store_context_mut().component_context_mut();
1682
1683 for (callee_async, callee_instance, saved_context) in frames.into_iter().rev() {
1687 *self.vm_store_context_mut().component_context_mut() = saved_context;
1691 let callee = RuntimeInstance {
1692 instance: id,
1693 index: RuntimeComponentInstanceIndex::from_u32(callee_instance),
1694 };
1695 self.enter_guest_sync_call(None, callee_async, callee)?;
1696 }
1697
1698 *self.vm_store_context_mut().component_context_mut() = current_context;
1700
1701 Ok(self
1702 .concurrent_state_mut_without_forcing_current_thread()
1703 .unforced_current_thread)
1704 }
1705
1706 fn current_guest_thread(&mut self) -> Result<QualifiedThreadId> {
1707 match self.current_thread()?.guest() {
1708 Some(id) => Ok(*id),
1709 None => bail_bug!("current thread is not a guest thread"),
1710 }
1711 }
1712
1713 fn current_host_thread(&mut self) -> Result<TableId<HostTask>> {
1714 match self.current_thread()?.host() {
1715 Some(id) => Ok(id),
1716 None => bail_bug!("current thread is not a host thread"),
1717 }
1718 }
1719
1720 fn take_pending_cancellation(&mut self) -> Result<bool> {
1723 let thread = self.current_guest_thread()?;
1724 let task = self.concurrent_state_mut()?.get_mut(thread.task)?;
1725 if let Some(Event::Cancelled) = task.event {
1726 task.event.take();
1727 return Ok(true);
1728 }
1729 Ok(false)
1730 }
1731
1732 pub(crate) fn enter_guest_sync_call(
1744 &mut self,
1745 guest_caller: Option<RuntimeInstance>,
1746 callee_async: bool,
1747 callee: RuntimeInstance,
1748 ) -> Result<()> {
1749 log::trace!("enter sync call {callee:?}");
1750 if !self.concurrency_support() {
1751 return self.enter_call_not_concurrent();
1752 }
1753
1754 let thread = self.current_thread()?;
1755 let state = self.concurrent_state_mut()?;
1756 let instance = if let Some(task) = thread.guest_task() {
1757 Some(state.get_mut(task)?.instance)
1758 } else {
1759 None
1760 };
1761 if guest_caller.is_some() {
1762 debug_assert_eq!(instance, guest_caller);
1763 }
1764 let guest_thread = GuestTask::new(
1765 state,
1766 Box::new(move |_, _| bail_bug!("cannot lower params in sync call")),
1767 LiftResult {
1768 lift: Box::new(move |_, _| bail_bug!("cannot lift result in sync call")),
1769 ty: TypeTupleIndex::reserved_value(),
1770 memory: None,
1771 string_encoding: StringEncoding::Utf8,
1772 },
1773 if let Some(thread) = thread.guest() {
1774 Caller::Guest { thread: *thread }
1775 } else {
1776 Caller::Host {
1777 tx: None,
1778 host_future_present: false,
1779 caller: thread,
1780 }
1781 },
1782 None,
1783 callee,
1784 callee_async,
1785 )?;
1786
1787 Instance::from_wasmtime(self, callee.instance).add_guest_thread_to_instance_table(
1788 guest_thread.thread,
1789 self,
1790 callee.index,
1791 )?;
1792 self.set_thread(guest_thread)?;
1793
1794 Ok(())
1795 }
1796
1797 pub(crate) fn exit_guest_sync_call(&mut self) -> Result<()> {
1805 if !self.concurrency_support() {
1806 return Ok(self.exit_call_not_concurrent());
1807 }
1808 let thread = match self.set_thread(CurrentThread::None)?.guest() {
1809 Some(t) => *t,
1810 None => bail_bug!("expected task when exiting"),
1811 };
1812 let task = self.concurrent_state_mut()?.get_mut(thread.task)?;
1813 let instance = task.instance;
1814 let caller = match &task.caller {
1815 &Caller::Guest { thread } => thread.into(),
1816 &Caller::Host { caller, .. } => caller,
1817 };
1818 task.lift_result = None;
1819 task.exited = true;
1820 self.set_thread(caller)?;
1821
1822 log::trace!("exit sync call {instance:?}");
1823 self.cleanup_thread(thread, instance, CleanupTask::Yes)?;
1824
1825 Ok(())
1826 }
1827
1828 pub(crate) fn host_task_create(&mut self) -> Result<EnteredHostTask> {
1836 if !self.concurrency_support() {
1837 self.enter_call_not_concurrent()?;
1838 return Ok(None);
1839 }
1840 let caller = self.current_guest_thread()?;
1841 let state = self.concurrent_state_mut()?;
1842 let task = state.push(HostTask::new(caller.task, HostTaskState::CalleeStarted))?;
1843 log::trace!("new host task {task:?}");
1844 self.set_thread(task)?;
1845 Ok(Some((task, caller)))
1846 }
1847
1848 pub(crate) fn host_task_delete(&mut self, task: EnteredHostTask) -> Result<()> {
1855 match task {
1856 Some((task, caller)) => {
1857 self.set_thread(caller)?;
1858 log::trace!("delete host task {task:?}");
1859 self.concurrent_state_mut()?.delete(task)?;
1860 }
1861 None => {
1862 self.exit_call_not_concurrent();
1863 }
1864 }
1865 Ok(())
1866 }
1867
1868 pub(crate) fn may_enter(&mut self, instance: RuntimeInstance) -> Result<bool> {
1876 if self.trapped() {
1877 return Ok(false);
1878 }
1879 if !self.concurrency_support() {
1880 return Ok(true);
1881 }
1882 let mut cur = Some(self.current_thread()?);
1883 let state = self.concurrent_state_mut()?;
1884 while let Some(t) = cur {
1885 if let Some(task) = t.guest_task() {
1886 let task = state.get_mut(task)?;
1887 if task.instance.instance == instance.instance {
1894 return Ok(false);
1895 }
1896 }
1897 cur = state.parent(t);
1898 }
1899 Ok(true)
1900 }
1901
1902 fn instance_state(&mut self, instance: RuntimeInstance) -> &mut InstanceState {
1905 self.component_instance_mut(instance.instance)
1906 .instance_state(instance.index)
1907 }
1908
1909 fn set_thread(&mut self, thread: impl Into<CurrentThread>) -> Result<CurrentThread> {
1915 let thread = thread.into();
1916 let state = self.concurrent_state_mut()?;
1917 let old_thread = mem::replace(&mut state.unforced_current_thread, thread);
1918
1919 if let Some(old_thread) = old_thread.guest() {
1927 let old_context = *self.vm_store_context_mut().component_context_mut();
1928 self.concurrent_state_mut()?
1929 .get_mut(old_thread.thread)?
1930 .context = old_context;
1931 }
1932 if cfg!(debug_assertions) {
1933 *self.vm_store_context_mut().component_context_mut() =
1934 [u32::MAX; NUM_COMPONENT_CONTEXT_SLOTS];
1935 }
1936 if let Some(thread) = thread.guest() {
1937 let thread = self.concurrent_state_mut()?.get_mut(thread.thread)?;
1938 let context = thread.context;
1939 if cfg!(debug_assertions) {
1940 thread.context = [u32::MAX; NUM_COMPONENT_CONTEXT_SLOTS];
1941 }
1942 *self.vm_store_context_mut().component_context_mut() = context;
1943 }
1944
1945 let state = self.concurrent_state_mut()?;
1953 if let Some(old_task) = old_thread.guest_task() {
1954 let instance = state.get_mut(old_task)?.instance.instance;
1955 self.component_instance_mut(instance)
1956 .set_task_may_block(false)
1957 }
1958
1959 if thread.guest_task().is_some() {
1960 self.set_task_may_block()?;
1961 }
1962
1963 *self.vm_store_context_mut().current_thread_mut() = if thread.is_none() {
1965 VMLazyThread::none()
1966 } else {
1967 VMLazyThread::forced()
1968 };
1969
1970 Ok(old_thread)
1971 }
1972
1973 fn set_task_may_block(&mut self) -> Result<()> {
1976 let guest_thread = self.current_guest_thread()?;
1977 let state = self.concurrent_state_mut()?;
1978 let instance = state.get_mut(guest_thread.task)?.instance.instance;
1979 let may_block = self.concurrent_state_mut()?.may_block(guest_thread.task)?;
1980 self.component_instance_mut(instance)
1981 .set_task_may_block(may_block);
1982 Ok(())
1983 }
1984
1985 pub(crate) fn check_blocking(&mut self) -> Result<()> {
1986 if !self.concurrency_support() {
1987 return Ok(());
1988 }
1989 let task = self.current_guest_thread()?.task;
1990 let state = self.concurrent_state_mut()?;
1991 let instance = state.get_mut(task)?.instance.instance;
1992 let task_may_block = self.component_instance(instance).get_task_may_block();
1993
1994 if task_may_block {
1995 Ok(())
1996 } else {
1997 Err(Trap::CannotBlockSyncTask.into())
1998 }
1999 }
2000
2001 fn enter_instance(&mut self, instance: RuntimeInstance) {
2005 log::trace!("enter {instance:?}");
2006 self.instance_state(instance)
2007 .concurrent_state()
2008 .do_not_enter = true;
2009 }
2010
2011 fn exit_instance(&mut self, instance: RuntimeInstance) -> Result<()> {
2015 log::trace!("exit {instance:?}");
2016 self.instance_state(instance)
2017 .concurrent_state()
2018 .do_not_enter = false;
2019 self.partition_pending(instance)
2020 }
2021
2022 fn partition_pending(&mut self, instance: RuntimeInstance) -> Result<()> {
2030 for (thread, kind) in
2031 mem::take(&mut self.instance_state(instance).concurrent_state().pending).into_iter()
2032 {
2033 let call = GuestCall { thread, kind };
2034 if call.is_ready(self)? {
2035 self.concurrent_state_mut()?
2036 .push_high_priority(WorkItem::GuestCall(instance.index, call));
2037 } else {
2038 self.instance_state(instance)
2039 .concurrent_state()
2040 .pending
2041 .insert(call.thread, call.kind);
2042 }
2043 }
2044
2045 if let Some(waker) = self
2046 .concurrent_state_mut()?
2047 .ready_for_concurrent_call_waker
2048 .take()
2049 {
2050 waker.wake();
2051 }
2052
2053 Ok(())
2054 }
2055
2056 pub(crate) fn backpressure_modify(
2058 &mut self,
2059 caller_instance: RuntimeInstance,
2060 modify: impl FnOnce(u16) -> Option<u16>,
2061 ) -> Result<()> {
2062 let state = self.instance_state(caller_instance).concurrent_state();
2063 let old = state.backpressure;
2064 let new = modify(old).ok_or_else(|| Trap::BackpressureOverflow)?;
2065 state.backpressure = new;
2066
2067 if old > 0 && new == 0 {
2068 self.partition_pending(caller_instance)?;
2071 }
2072
2073 Ok(())
2074 }
2075
2076 async fn resume_fiber(&mut self, fiber: StoreFiber<'static>) -> Result<()> {
2079 let old_thread = self.current_thread()?;
2080 log::trace!("resume_fiber: save current thread {old_thread:?}");
2081
2082 let fiber = fiber::resolve_or_release(self, fiber).await?;
2083
2084 self.set_thread(old_thread)?;
2085
2086 let state = self.concurrent_state_mut()?;
2087
2088 if let Some(ot) = old_thread.guest() {
2089 state.get_mut(ot.thread)?.state = GuestThreadState::Running;
2090 }
2091 log::trace!("resume_fiber: restore current thread {old_thread:?}");
2092
2093 if let Some(mut fiber) = fiber {
2094 log::trace!("resume_fiber: suspend reason {:?}", &state.suspend_reason);
2095 let reason = match state.suspend_reason.take() {
2097 Some(r) => r,
2098 None => bail_bug!("suspend reason missing when resuming fiber"),
2099 };
2100 match reason {
2101 SuspendReason::NeedWork => {
2102 if state.worker.is_none() {
2103 state.worker = Some(fiber);
2104 } else {
2105 fiber.dispose(self);
2106 }
2107 }
2108 SuspendReason::Yielding {
2109 thread,
2110 cancellable,
2111 ..
2112 } => {
2113 state.get_mut(thread.thread)?.state =
2114 GuestThreadState::Ready { fiber, cancellable };
2115 let instance = state.get_mut(thread.task)?.instance.index;
2116 state.push_low_priority(WorkItem::ResumeThread(instance, thread));
2117 }
2118 SuspendReason::ExplicitlySuspending { thread, .. } => {
2119 state.get_mut(thread.thread)?.state = GuestThreadState::Suspended(fiber);
2120 }
2121 SuspendReason::Waiting { set, thread, .. } => {
2122 let old = state
2123 .get_mut(set)?
2124 .waiting
2125 .insert(thread, WaitMode::Fiber(fiber));
2126 assert!(old.is_none());
2127 }
2128 };
2129 } else {
2130 log::trace!("resume_fiber: fiber has exited");
2131 }
2132
2133 Ok(())
2134 }
2135
2136 fn suspend(&mut self, reason: SuspendReason) -> Result<()> {
2142 log::trace!("suspend fiber: {reason:?}");
2143
2144 let task = match &reason {
2148 SuspendReason::Yielding { thread, .. }
2149 | SuspendReason::Waiting { thread, .. }
2150 | SuspendReason::ExplicitlySuspending { thread, .. } => Some(thread.task),
2151 SuspendReason::NeedWork => None,
2152 };
2153
2154 let old_guest_thread = if task.is_some() {
2155 self.current_thread()?
2156 } else {
2157 CurrentThread::None
2158 };
2159
2160 debug_assert!(
2166 matches!(
2167 reason,
2168 SuspendReason::ExplicitlySuspending {
2169 skip_may_block_check: true,
2170 ..
2171 } | SuspendReason::Waiting {
2172 skip_may_block_check: true,
2173 ..
2174 } | SuspendReason::Yielding {
2175 skip_may_block_check: true,
2176 ..
2177 }
2178 ) || old_guest_thread
2179 .guest_task()
2180 .map(|task| self.concurrent_state_mut()?.may_block(task))
2181 .transpose()?
2182 .unwrap_or(true)
2183 );
2184
2185 let suspend_reason = &mut self.concurrent_state_mut()?.suspend_reason;
2186 assert!(suspend_reason.is_none());
2187 *suspend_reason = Some(reason);
2188
2189 self.with_blocking(|_, cx| cx.suspend(StoreFiberYield::ReleaseStore))?;
2190
2191 if task.is_some() {
2192 self.set_thread(old_guest_thread)?;
2193 }
2194
2195 Ok(())
2196 }
2197
2198 fn wait_for_event(&mut self, waitable: Waitable) -> Result<()> {
2199 let caller = self.current_guest_thread()?;
2200 let state = self.concurrent_state_mut()?;
2201
2202 waitable.trap_if_in_waitable_set(state)?;
2203
2204 let set = state.get_mut(caller.thread)?.sync_call_set;
2205 waitable.join(state, Some(set))?;
2206 self.suspend(SuspendReason::Waiting {
2207 set,
2208 thread: caller,
2209 skip_may_block_check: false,
2210 })?;
2211 let state = self.concurrent_state_mut()?;
2212 waitable.join(state, None)
2213 }
2214
2215 fn cleanup_thread(
2237 &mut self,
2238 guest_thread: QualifiedThreadId,
2239 runtime_instance: RuntimeInstance,
2240 cleanup_task: CleanupTask,
2241 ) -> Result<()> {
2242 let state = self.concurrent_state_mut()?;
2243 let thread_data = state.get_mut(guest_thread.thread)?;
2244 let sync_call_set = thread_data.sync_call_set;
2245 if let Some(guest_id) = thread_data.instance_rep {
2246 self.instance_state(runtime_instance)
2247 .thread_handle_table()
2248 .guest_thread_remove(guest_id)?;
2249 }
2250 let state = self.concurrent_state_mut()?;
2251
2252 for waitable in mem::take(&mut state.get_mut(sync_call_set)?.ready) {
2254 if let Some(Event::Subtask {
2255 status: Status::Returned | Status::ReturnCancelled,
2256 }) = waitable.common(state)?.event
2257 {
2258 waitable.delete_from(state)?;
2259 }
2260 }
2261
2262 state.delete(guest_thread.thread)?;
2263 state.delete(sync_call_set)?;
2264 let task = state.get_mut(guest_thread.task)?;
2265 task.threads.remove(&guest_thread.thread);
2266
2267 if task.threads.is_empty() && !task.returned_or_cancelled() {
2268 bail!(Trap::NoAsyncResult);
2269 }
2270 let ready_to_delete = task.ready_to_delete();
2271
2272 if !task.decremented_interesting_task_count && task.exited && task.returned_or_cancelled() {
2273 task.decremented_interesting_task_count = true;
2274
2275 debug_assert!(state.interesting_tasks > 0);
2276 state.interesting_tasks -= 1;
2277 if state.interesting_tasks == 0
2278 && let Some(waker) = state.interesting_tasks_empty_waker.take()
2279 {
2280 waker.wake();
2281 }
2282 }
2283
2284 match cleanup_task {
2285 CleanupTask::Yes => {
2286 if ready_to_delete {
2287 Waitable::Guest(guest_thread.task).delete_from(state)?;
2288 }
2289 }
2290 CleanupTask::No => {}
2291 }
2292
2293 Ok(())
2294 }
2295
2296 fn cancel_guest_subtask_without_lowered_parameters(
2309 &mut self,
2310 caller_instance: RuntimeInstance,
2311 guest_task: TableId<GuestTask>,
2312 ) -> Result<()> {
2313 let concurrent_state = self.concurrent_state_mut()?;
2314 let task = concurrent_state.get_mut(guest_task)?;
2315 assert!(!task.already_lowered_parameters());
2316 task.lower_params = None;
2320 task.lift_result = None;
2321 task.exited = true;
2322 let instance = task.instance;
2323
2324 assert_eq!(1, task.threads.len());
2327 let thread = *task.threads.iter().next().unwrap();
2328 self.cleanup_thread(
2329 QualifiedThreadId {
2330 task: guest_task,
2331 thread,
2332 },
2333 caller_instance,
2334 CleanupTask::No,
2335 )?;
2336
2337 let pending = &mut self.instance_state(instance).concurrent_state().pending;
2339 let pending_count = pending.len();
2340 pending.retain(|thread, _| thread.task != guest_task);
2341 if pending.len() == pending_count {
2343 bail!(Trap::SubtaskCancelAfterTerminal);
2344 }
2345 Ok(())
2346 }
2347
2348 pub(crate) fn current_scope_id(&mut self) -> Result<Option<u32>> {
2351 if !self.concurrency_support() {
2352 return self.current_scope_id_not_concurrent();
2353 }
2354 let (bits, is_host) = match self.current_thread()? {
2355 CurrentThread::Guest(id) => (id.task.rep(), false),
2356 CurrentThread::GuestTask(id) => (id.rep(), false),
2357 CurrentThread::Host(id) => (id.rep(), true),
2358 CurrentThread::None => return Ok(None),
2359 };
2360 assert_eq!((bits << 1) >> 1, bits);
2361 Ok(Some((bits << 1) | u32::from(is_host)))
2362 }
2363}
2364
2365enum CleanupTask {
2366 Yes,
2367 No,
2368}
2369
2370impl Instance {
2371 fn get_event(
2374 self,
2375 store: &mut StoreOpaque,
2376 guest_task: TableId<GuestTask>,
2377 set: Option<TableId<WaitableSet>>,
2378 cancellable: bool,
2379 ) -> Result<Option<(Event, Option<(Waitable, u32)>)>> {
2380 let state = store.concurrent_state_mut()?;
2381
2382 let event = &mut state.get_mut(guest_task)?.event;
2383 if let Some(ev) = event
2384 && (cancellable || !matches!(ev, Event::Cancelled))
2385 {
2386 log::trace!("deliver event {ev:?} to {guest_task:?}");
2387 let ev = *ev;
2388 *event = None;
2389 return Ok(Some((ev, None)));
2390 }
2391
2392 let set = match set {
2393 Some(set) => set,
2394 None => return Ok(None),
2395 };
2396 let waitable = match state.get_mut(set)?.ready.pop_first() {
2397 Some(v) => v,
2398 None => return Ok(None),
2399 };
2400
2401 let common = waitable.common(state)?;
2402 let handle = match common.handle {
2403 Some(h) => h,
2404 None => bail_bug!("handle not set when delivering event"),
2405 };
2406 let event = match common.event.take() {
2407 Some(e) => e,
2408 None => bail_bug!("event not set when delivering event"),
2409 };
2410
2411 log::trace!(
2412 "deliver event {event:?} to {guest_task:?} for {waitable:?} (handle {handle}); set {set:?}"
2413 );
2414
2415 waitable.on_delivery(store, self, event)?;
2416
2417 Ok(Some((event, Some((waitable, handle)))))
2418 }
2419
2420 fn handle_callback_code(
2426 self,
2427 store: &mut StoreOpaque,
2428 guest_thread: QualifiedThreadId,
2429 runtime_instance: RuntimeComponentInstanceIndex,
2430 code: u32,
2431 ) -> Result<Option<GuestCall>> {
2432 let (code, set) = unpack_callback_code(code);
2433
2434 log::trace!("received callback code from {guest_thread:?}: {code} (set: {set})");
2435
2436 let state = store.concurrent_state_mut()?;
2437
2438 let get_set = |store: &mut StoreOpaque, handle| -> Result<_> {
2439 let set = store
2440 .instance_state(self.runtime_instance(runtime_instance))
2441 .handle_table()
2442 .waitable_set_rep(handle)?;
2443
2444 Ok(TableId::<WaitableSet>::new(set))
2445 };
2446
2447 Ok(match code {
2448 callback_code::EXIT => {
2449 log::trace!("implicit thread {guest_thread:?} completed");
2450 let task = store.concurrent_state_mut()?.get_mut(guest_thread.task)?;
2451 task.exited = true;
2452 task.callback = None;
2453 store.cleanup_thread(
2454 guest_thread,
2455 self.runtime_instance(runtime_instance),
2456 CleanupTask::Yes,
2457 )?;
2458 None
2459 }
2460 callback_code::YIELD => {
2461 let task = state.get_mut(guest_thread.task)?;
2462 if let Some(event) = task.event {
2467 assert!(matches!(event, Event::None | Event::Cancelled));
2468 } else {
2469 task.event = Some(Event::None);
2470 }
2471 let call = GuestCall {
2472 thread: guest_thread,
2473 kind: GuestCallKind::DeliverEvent {
2474 instance: self,
2475 set: None,
2476 },
2477 };
2478 if state.may_block(guest_thread.task)? {
2479 state.push_low_priority(WorkItem::GuestCall(runtime_instance, call));
2482 None
2483 } else {
2484 Some(call)
2488 }
2489 }
2490 callback_code::WAIT => {
2491 state.check_blocking_for(guest_thread.task)?;
2494
2495 let set = get_set(store, set)?;
2496 let state = store.concurrent_state_mut()?;
2497
2498 if state.get_mut(guest_thread.task)?.event.is_some()
2499 || !state.get_mut(set)?.ready.is_empty()
2500 {
2501 state.push_high_priority(WorkItem::GuestCall(
2503 runtime_instance,
2504 GuestCall {
2505 thread: guest_thread,
2506 kind: GuestCallKind::DeliverEvent {
2507 instance: self,
2508 set: Some(set),
2509 },
2510 },
2511 ));
2512 } else {
2513 let old = state
2521 .get_mut(guest_thread.thread)?
2522 .wake_on_cancel
2523 .replace(set);
2524 if !old.is_none() {
2525 bail_bug!("thread unexpectedly had wake_on_cancel set");
2526 }
2527 let old = state
2528 .get_mut(set)?
2529 .waiting
2530 .insert(guest_thread, WaitMode::Callback(self));
2531 if !old.is_none() {
2532 bail_bug!("set's waiting set already had this thread registered");
2533 }
2534 }
2535 None
2536 }
2537 _ => bail!(Trap::UnsupportedCallbackCode),
2538 })
2539 }
2540
2541 unsafe fn queue_call<T: 'static>(
2548 self,
2549 mut store: StoreContextMut<T>,
2550 guest_thread: QualifiedThreadId,
2551 callee: SendSyncPtr<VMFuncRef>,
2552 param_count: usize,
2553 result_count: usize,
2554 async_: bool,
2555 callback: Option<SendSyncPtr<VMFuncRef>>,
2556 post_return: Option<SendSyncPtr<VMFuncRef>>,
2557 ) -> Result<()> {
2558 unsafe fn make_call<T: 'static>(
2573 store: StoreContextMut<T>,
2574 guest_thread: QualifiedThreadId,
2575 callee: SendSyncPtr<VMFuncRef>,
2576 param_count: usize,
2577 result_count: usize,
2578 ) -> impl FnOnce(&mut dyn VMStore) -> Result<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>
2579 + Send
2580 + Sync
2581 + 'static
2582 + use<T> {
2583 let token = StoreToken::new(store);
2584 move |store: &mut dyn VMStore| {
2585 let mut storage = [MaybeUninit::uninit(); MAX_FLAT_PARAMS];
2586
2587 store
2588 .concurrent_state_mut()?
2589 .get_mut(guest_thread.thread)?
2590 .state = GuestThreadState::Running;
2591 let task = store.concurrent_state_mut()?.get_mut(guest_thread.task)?;
2592 let lower = match task.lower_params.take() {
2593 Some(l) => l,
2594 None => bail_bug!("lower_params missing"),
2595 };
2596
2597 lower(store, &mut storage[..param_count])?;
2598
2599 let mut store = token.as_context_mut(store);
2600
2601 unsafe {
2604 crate::Func::call_unchecked_raw(
2605 &mut store,
2606 callee.as_non_null(),
2607 NonNull::new(
2608 &mut storage[..param_count.max(result_count)]
2609 as *mut [MaybeUninit<ValRaw>] as _,
2610 )
2611 .unwrap(),
2612 )?;
2613 }
2614
2615 Ok(storage)
2616 }
2617 }
2618
2619 let call = unsafe {
2623 make_call(
2624 store.as_context_mut(),
2625 guest_thread,
2626 callee,
2627 param_count,
2628 result_count,
2629 )
2630 };
2631
2632 let callee_instance = store
2633 .0
2634 .concurrent_state_mut()?
2635 .get_mut(guest_thread.task)?
2636 .instance;
2637
2638 let fun = if callback.is_some() {
2639 assert!(async_);
2640
2641 Box::new(move |store: &mut dyn VMStore| {
2642 self.add_guest_thread_to_instance_table(
2643 guest_thread.thread,
2644 store,
2645 callee_instance.index,
2646 )?;
2647 let old_thread = store.set_thread(guest_thread)?;
2648 log::trace!(
2649 "stackless call: replaced {old_thread:?} with {guest_thread:?} as current thread"
2650 );
2651
2652 store.enter_instance(callee_instance);
2653
2654 let storage = call(store)?;
2661
2662 store.exit_instance(callee_instance)?;
2663
2664 store.set_thread(old_thread)?;
2665 let state = store.concurrent_state_mut()?;
2666 if let Some(t) = old_thread.guest() {
2667 state.get_mut(t.thread)?.state = GuestThreadState::Running;
2668 }
2669 log::trace!("stackless call: restored {old_thread:?} as current thread");
2670
2671 let code = unsafe { storage[0].assume_init() }.get_i32() as u32;
2674
2675 self.handle_callback_code(store, guest_thread, callee_instance.index, code)
2676 })
2677 as Box<dyn FnOnce(&mut dyn VMStore) -> Result<Option<GuestCall>> + Send + Sync>
2678 } else {
2679 let token = StoreToken::new(store.as_context_mut());
2680 Box::new(move |store: &mut dyn VMStore| {
2681 self.add_guest_thread_to_instance_table(
2682 guest_thread.thread,
2683 store,
2684 callee_instance.index,
2685 )?;
2686 let old_thread = store.set_thread(guest_thread)?;
2687 log::trace!(
2688 "sync/async-stackful call: replaced {old_thread:?} with {guest_thread:?} as current thread",
2689 );
2690 let flags = self.id().get(store).instance_flags(callee_instance.index);
2691
2692 if !async_ {
2696 store.enter_instance(callee_instance);
2697 }
2698
2699 let storage = call(store)?;
2706
2707 if !async_ {
2708 let lift = {
2714 store.exit_instance(callee_instance)?;
2715
2716 let state = store.concurrent_state_mut()?;
2717 if !state.get_mut(guest_thread.task)?.result.is_none() {
2718 bail_bug!("task has already produced a result");
2719 }
2720
2721 match state.get_mut(guest_thread.task)?.lift_result.take() {
2722 Some(lift) => lift,
2723 None => bail_bug!("lift_result field is missing"),
2724 }
2725 };
2726
2727 let result = (lift.lift)(store, unsafe {
2730 mem::transmute::<&[MaybeUninit<ValRaw>], &[ValRaw]>(
2731 &storage[..result_count],
2732 )
2733 })?;
2734
2735 let post_return_arg = match result_count {
2736 0 => ValRaw::i32(0),
2737 1 => unsafe { storage[0].assume_init() },
2740 _ => unreachable!(),
2741 };
2742
2743 unsafe {
2744 call_post_return(
2745 token.as_context_mut(store),
2746 post_return.map(|v| v.as_non_null()),
2747 post_return_arg,
2748 flags,
2749 )?;
2750 }
2751
2752 self.task_complete(store, guest_thread.task, result, Status::Returned)?;
2753 }
2754
2755 store.set_thread(old_thread)?;
2756
2757 store
2758 .concurrent_state_mut()?
2759 .get_mut(guest_thread.task)?
2760 .exited = true;
2761
2762 store.cleanup_thread(guest_thread, callee_instance, CleanupTask::Yes)?;
2764 Ok(None)
2765 })
2766 };
2767
2768 store
2769 .0
2770 .concurrent_state_mut()?
2771 .push_high_priority(WorkItem::GuestCall(
2772 callee_instance.index,
2773 GuestCall {
2774 thread: guest_thread,
2775 kind: GuestCallKind::StartImplicit(fun),
2776 },
2777 ));
2778
2779 Ok(())
2780 }
2781
2782 unsafe fn prepare_call<T: 'static>(
2795 self,
2796 mut store: StoreContextMut<T>,
2797 start: NonNull<VMFuncRef>,
2798 return_: NonNull<VMFuncRef>,
2799 caller_instance: RuntimeComponentInstanceIndex,
2800 callee_instance: RuntimeComponentInstanceIndex,
2801 task_return_type: TypeTupleIndex,
2802 callee_async: bool,
2803 memory: *mut VMMemoryDefinition,
2804 string_encoding: StringEncoding,
2805 caller_info: CallerInfo,
2806 ) -> Result<()> {
2807 if let (CallerInfo::Sync { .. }, true) = (&caller_info, callee_async) {
2808 store.0.check_blocking()?;
2812 }
2813
2814 enum ResultInfo {
2815 Heap { results: u32 },
2816 Stack { result_count: u32 },
2817 }
2818
2819 let result_info = match &caller_info {
2820 CallerInfo::Async {
2821 has_result: true,
2822 params,
2823 } => ResultInfo::Heap {
2824 results: match params.last() {
2825 Some(r) => r.get_u32(),
2826 None => bail_bug!("retptr missing"),
2827 },
2828 },
2829 CallerInfo::Async {
2830 has_result: false, ..
2831 } => ResultInfo::Stack { result_count: 0 },
2832 CallerInfo::Sync {
2833 result_count,
2834 params,
2835 } if *result_count > u32::try_from(MAX_FLAT_RESULTS)? => ResultInfo::Heap {
2836 results: match params.last() {
2837 Some(r) => r.get_u32(),
2838 None => bail_bug!("arg ptr missing"),
2839 },
2840 },
2841 CallerInfo::Sync { result_count, .. } => ResultInfo::Stack {
2842 result_count: *result_count,
2843 },
2844 };
2845
2846 let sync_caller = matches!(caller_info, CallerInfo::Sync { .. });
2847
2848 let start = SendSyncPtr::new(start);
2852 let return_ = SendSyncPtr::new(return_);
2853 let token = StoreToken::new(store.as_context_mut());
2854 let old_thread = store.0.current_guest_thread()?;
2855 let state = store.0.concurrent_state_mut()?;
2856
2857 debug_assert_eq!(
2858 state.get_mut(old_thread.task)?.instance,
2859 self.runtime_instance(caller_instance)
2860 );
2861
2862 let guest_thread = GuestTask::new(
2863 state,
2864 Box::new(move |store, dst| {
2865 let mut store = token.as_context_mut(store);
2866 assert!(dst.len() <= MAX_FLAT_PARAMS);
2867 let mut src = [MaybeUninit::uninit(); MAX_FLAT_PARAMS + 1];
2869 let count = match caller_info {
2870 CallerInfo::Async { params, has_result } => {
2874 let params = ¶ms[..params.len() - usize::from(has_result)];
2875 for (param, src) in params.iter().zip(&mut src) {
2876 src.write(*param);
2877 }
2878 params.len()
2879 }
2880
2881 CallerInfo::Sync { params, .. } => {
2883 for (param, src) in params.iter().zip(&mut src) {
2884 src.write(*param);
2885 }
2886 params.len()
2887 }
2888 };
2889 unsafe {
2896 crate::Func::call_unchecked_raw(
2897 &mut store,
2898 start.as_non_null(),
2899 NonNull::new(
2900 &mut src[..count.max(dst.len())] as *mut [MaybeUninit<ValRaw>] as _,
2901 )
2902 .unwrap(),
2903 )?;
2904 }
2905 dst.copy_from_slice(&src[..dst.len()]);
2906 let task = store.0.current_guest_thread()?.task;
2907 let state = store.0.concurrent_state_mut()?;
2908 Waitable::Guest(task).set_event(
2909 state,
2910 Some(Event::Subtask {
2911 status: Status::Started,
2912 }),
2913 )?;
2914 Ok(())
2915 }),
2916 LiftResult {
2917 lift: Box::new(move |store, src| {
2918 let mut store = token.as_context_mut(store);
2921 let mut my_src = src.to_owned(); if let ResultInfo::Heap { results } = &result_info {
2923 my_src.push(ValRaw::u32(*results));
2924 }
2925
2926 let prev = store.0.set_thread(old_thread)?;
2932
2933 unsafe {
2940 crate::Func::call_unchecked_raw(
2941 &mut store,
2942 return_.as_non_null(),
2943 my_src.as_mut_slice().into(),
2944 )?;
2945 }
2946
2947 store.0.set_thread(prev)?;
2950
2951 let thread = store.0.current_guest_thread()?;
2952 let state = store.0.concurrent_state_mut()?;
2953 if sync_caller {
2954 state.get_mut(thread.task)?.sync_result = SyncResult::Produced(
2955 if let ResultInfo::Stack { result_count } = &result_info {
2956 match result_count {
2957 0 => None,
2958 1 => Some(my_src[0]),
2959 _ => unreachable!(),
2960 }
2961 } else {
2962 None
2963 },
2964 );
2965 }
2966 Ok(Box::new(DummyResult) as Box<dyn Any + Send + Sync>)
2967 }),
2968 ty: task_return_type,
2969 memory: NonNull::new(memory).map(SendSyncPtr::new),
2970 string_encoding,
2971 },
2972 Caller::Guest { thread: old_thread },
2973 None,
2974 self.runtime_instance(callee_instance),
2975 callee_async,
2976 )?;
2977
2978 store.0.set_thread(guest_thread)?;
2981 log::trace!("pushed {guest_thread:?} as current thread; old thread was {old_thread:?}");
2982
2983 Ok(())
2984 }
2985
2986 unsafe fn call_callback<T>(
2991 self,
2992 mut store: StoreContextMut<T>,
2993 function: SendSyncPtr<VMFuncRef>,
2994 event: Event,
2995 handle: u32,
2996 ) -> Result<u32> {
2997 let (ordinal, result) = event.parts();
2998 let params = &mut [
2999 ValRaw::u32(ordinal),
3000 ValRaw::u32(handle),
3001 ValRaw::u32(result),
3002 ];
3003 unsafe {
3008 crate::Func::call_unchecked_raw(
3009 &mut store,
3010 function.as_non_null(),
3011 params.as_mut_slice().into(),
3012 )?;
3013 }
3014 Ok(params[0].get_u32())
3015 }
3016
3017 unsafe fn start_call<T: 'static>(
3030 self,
3031 mut store: StoreContextMut<T>,
3032 callback: *mut VMFuncRef,
3033 post_return: *mut VMFuncRef,
3034 callee: NonNull<VMFuncRef>,
3035 param_count: u32,
3036 result_count: u32,
3037 flags: u32,
3038 storage: Option<&mut [MaybeUninit<ValRaw>]>,
3039 ) -> Result<u32> {
3040 let token = StoreToken::new(store.as_context_mut());
3041 let async_caller = storage.is_none();
3042 let guest_thread = store.0.current_guest_thread()?;
3043 let state = store.0.concurrent_state_mut()?;
3044 let callee_async = state.get_mut(guest_thread.task)?.async_function;
3045 let callee = SendSyncPtr::new(callee);
3046 let param_count = usize::try_from(param_count)?;
3047 assert!(param_count <= MAX_FLAT_PARAMS);
3048 let result_count = usize::try_from(result_count)?;
3049 assert!(result_count <= MAX_FLAT_RESULTS);
3050
3051 let task = state.get_mut(guest_thread.task)?;
3052 if let Some(callback) = NonNull::new(callback) {
3053 let callback = SendSyncPtr::new(callback);
3057 task.callback = Some(Box::new(move |store, event, handle| {
3058 let store = token.as_context_mut(store);
3059 unsafe { self.call_callback::<T>(store, callback, event, handle) }
3060 }));
3061 }
3062
3063 let Caller::Guest { thread: caller } = &task.caller else {
3064 bail_bug!("start_call unexpectedly invoked for host->guest call");
3067 };
3068 let caller = *caller;
3069 let caller_instance = state.get_mut(caller.task)?.instance;
3070
3071 unsafe {
3073 self.queue_call(
3074 store.as_context_mut(),
3075 guest_thread,
3076 callee,
3077 param_count,
3078 result_count,
3079 (flags & START_FLAG_ASYNC_CALLEE) != 0,
3080 NonNull::new(callback).map(SendSyncPtr::new),
3081 NonNull::new(post_return).map(SendSyncPtr::new),
3082 )?;
3083 }
3084
3085 let state = store.0.concurrent_state_mut()?;
3086
3087 let guest_waitable = Waitable::Guest(guest_thread.task);
3090 let old_set = guest_waitable.common(state)?.set;
3091 let set = state.get_mut(caller.thread)?.sync_call_set;
3092 guest_waitable.join(state, Some(set))?;
3093
3094 store.0.set_thread(CurrentThread::None)?;
3095
3096 let (status, waitable) = loop {
3112 store.0.suspend(SuspendReason::Waiting {
3113 set,
3114 thread: caller,
3115 skip_may_block_check: async_caller || !callee_async,
3123 })?;
3124
3125 let state = store.0.concurrent_state_mut()?;
3126
3127 log::trace!("taking event for {:?}", guest_thread.task);
3128 let event = guest_waitable.take_event(state)?;
3129 let Some(Event::Subtask { status }) = event else {
3130 bail_bug!("subtasks should only get subtask events, got {event:?}")
3131 };
3132
3133 log::trace!("status {status:?} for {:?}", guest_thread.task);
3134
3135 if status == Status::Returned {
3136 break (status, None);
3138 } else if async_caller {
3139 let handle = store
3143 .0
3144 .instance_state(caller_instance)
3145 .handle_table()
3146 .subtask_insert_guest(guest_thread.task.rep())?;
3147 store
3148 .0
3149 .concurrent_state_mut()?
3150 .get_mut(guest_thread.task)?
3151 .common
3152 .handle = Some(handle);
3153 break (status, Some(handle));
3154 } else {
3155 }
3159 };
3160
3161 guest_waitable.join(store.0.concurrent_state_mut()?, old_set)?;
3162
3163 store.0.set_thread(caller)?;
3165 store
3166 .0
3167 .concurrent_state_mut()?
3168 .get_mut(caller.thread)?
3169 .state = GuestThreadState::Running;
3170 log::trace!("popped current thread {guest_thread:?}; new thread is {caller:?}");
3171
3172 if let Some(storage) = storage {
3173 let state = store.0.concurrent_state_mut()?;
3177 let task = state.get_mut(guest_thread.task)?;
3178 if let Some(result) = task.sync_result.take()? {
3179 if let Some(result) = result {
3180 storage[0] = MaybeUninit::new(result);
3181 }
3182
3183 if task.exited && task.ready_to_delete() {
3184 Waitable::Guest(guest_thread.task).delete_from(state)?;
3185 }
3186 }
3187 }
3188
3189 Ok(status.pack(waitable))
3190 }
3191
3192 pub(crate) fn first_poll<T: 'static, R: Send + 'static>(
3205 self,
3206 mut store: StoreContextMut<'_, T>,
3207 host_task: EnteredHostTask,
3208 future: impl Future<Output = Result<R>> + Send + 'static,
3209 lower: impl FnOnce(StoreContextMut<T>, Option<R>, bool) -> Result<()> + Send + 'static,
3210 ) -> Result<u32> {
3211 let token = StoreToken::new(store.as_context_mut());
3212 let task = store.0.current_host_thread()?;
3213 let state = store.0.concurrent_state_mut()?;
3214
3215 let (join_handle, future) = JoinHandle::run(future);
3218 {
3219 let state = &mut state.get_mut(task)?.state;
3220 assert!(matches!(state, HostTaskState::CalleeStarted));
3221 *state = HostTaskState::CalleeRunning(join_handle);
3222 }
3223
3224 let mut future = Box::pin(future);
3225
3226 let poll = tls::set(store.0, || {
3231 future
3232 .as_mut()
3233 .poll(&mut Context::from_waker(&Waker::noop()))
3234 });
3235
3236 match poll {
3237 Poll::Ready(result) => {
3239 let result = result.transpose()?;
3240 lower(store.as_context_mut(), result, true)?;
3241 return Ok(Status::Returned.pack(None));
3242 }
3243
3244 Poll::Pending => {}
3246 }
3247
3248 let future = Box::pin(async move {
3256 let result = match future.await {
3257 Some(result) => Some(result?),
3258 None => None,
3259 };
3260 let on_complete = move |store: &mut dyn VMStore| {
3261 let mut store = token.as_context_mut(store);
3265 let old = store.0.set_thread(task)?;
3266
3267 let status = if result.is_some() {
3268 Status::Returned
3269 } else {
3270 Status::ReturnCancelled
3271 };
3272
3273 lower(store.as_context_mut(), result, false)?;
3274 let state = store.0.concurrent_state_mut()?;
3275 match &mut state.get_mut(task)?.state {
3276 HostTaskState::CalleeDone { .. } => {}
3279
3280 other => *other = HostTaskState::CalleeDone { cancelled: false },
3282 }
3283 Waitable::Host(task).set_event(state, Some(Event::Subtask { status }))?;
3284
3285 store.0.set_thread(old)?;
3286 Ok(())
3287 };
3288
3289 tls::get(move |store| {
3294 store
3295 .concurrent_state_mut()?
3296 .push_high_priority(WorkItem::WorkerFunction(AlwaysMut::new(Box::new(
3297 on_complete,
3298 ))));
3299 Ok(())
3300 })
3301 });
3302
3303 let caller = match host_task {
3306 Some(pair) => pair.1,
3307 None => bail_bug!("host task wasn't created but should have been"),
3308 };
3309 let state = store.0.concurrent_state_mut()?;
3310 state.push_future(future);
3311 let instance = state.get_mut(caller.task)?.instance;
3312 let handle = store
3313 .0
3314 .instance_state(instance)
3315 .handle_table()
3316 .subtask_insert_host(task.rep())?;
3317 store.0.concurrent_state_mut()?.get_mut(task)?.common.handle = Some(handle);
3318 log::trace!("assign {task:?} handle {handle} for {caller:?} instance {instance:?}");
3319
3320 store.0.set_thread(caller)?;
3324 Ok(Status::Started.pack(Some(handle)))
3325 }
3326
3327 pub(crate) fn task_return(
3330 self,
3331 store: &mut dyn VMStore,
3332 ty: TypeTupleIndex,
3333 options: OptionsIndex,
3334 storage: &[ValRaw],
3335 ) -> Result<()> {
3336 let guest_thread = store.current_guest_thread()?;
3337 let state = store.concurrent_state_mut()?;
3338 let lift = state
3339 .get_mut(guest_thread.task)?
3340 .lift_result
3341 .take()
3342 .ok_or_else(|| Trap::TaskCancelOrReturnTwice)?;
3343 if !state.get_mut(guest_thread.task)?.result.is_none() {
3344 bail_bug!("task result unexpectedly already set");
3345 }
3346
3347 let CanonicalOptions {
3348 string_encoding,
3349 data_model,
3350 ..
3351 } = &self.id().get(store).component().env_component().options[options];
3352
3353 let invalid = ty != lift.ty
3354 || string_encoding != &lift.string_encoding
3355 || match data_model {
3356 CanonicalOptionsDataModel::LinearMemory(opts) => match opts.memory {
3357 Some(memory) => {
3358 let expected = lift.memory.map(|v| v.as_ptr()).unwrap_or(ptr::null_mut());
3359 let actual = self.id().get(store).runtime_memory(memory);
3360 expected != actual.as_ptr()
3361 }
3362 None => false,
3365 },
3366 CanonicalOptionsDataModel::Gc { .. } => true,
3368 };
3369
3370 if invalid {
3371 bail!(Trap::TaskReturnInvalid);
3372 }
3373
3374 log::trace!("task.return for {guest_thread:?}");
3375
3376 let result = (lift.lift)(store, storage)?;
3377 self.task_complete(store, guest_thread.task, result, Status::Returned)
3378 }
3379
3380 pub(crate) fn task_cancel(self, store: &mut StoreOpaque) -> Result<()> {
3382 let guest_thread = store.current_guest_thread()?;
3383 let state = store.concurrent_state_mut()?;
3384 let task = state.get_mut(guest_thread.task)?;
3385 if !task.cancel_sent {
3386 bail!(Trap::TaskCancelNotCancelled);
3387 }
3388 _ = task
3389 .lift_result
3390 .take()
3391 .ok_or_else(|| Trap::TaskCancelOrReturnTwice)?;
3392
3393 if !task.result.is_none() {
3394 bail_bug!("task result should not bet set yet");
3395 }
3396
3397 log::trace!("task.cancel for {guest_thread:?}");
3398
3399 self.task_complete(
3400 store,
3401 guest_thread.task,
3402 Box::new(DummyResult),
3403 Status::ReturnCancelled,
3404 )
3405 }
3406
3407 fn task_complete(
3413 self,
3414 store: &mut StoreOpaque,
3415 guest_task: TableId<GuestTask>,
3416 result: Box<dyn Any + Send + Sync>,
3417 status: Status,
3418 ) -> Result<()> {
3419 store
3420 .component_resource_tables(Some(self))?
3421 .validate_scope_exit()?;
3422
3423 let state = store.concurrent_state_mut()?;
3424 let task = state.get_mut(guest_task)?;
3425
3426 if let Caller::Host { tx, .. } = &mut task.caller {
3427 if let Some(tx) = tx.take() {
3428 _ = tx.send(result);
3429 }
3430 } else {
3431 task.result = Some(result);
3432 Waitable::Guest(guest_task).set_event(state, Some(Event::Subtask { status }))?;
3433 }
3434
3435 Ok(())
3436 }
3437
3438 pub(crate) fn waitable_set_new(
3440 self,
3441 store: &mut StoreOpaque,
3442 caller_instance: RuntimeComponentInstanceIndex,
3443 ) -> Result<u32> {
3444 let set = store.concurrent_state_mut()?.push(WaitableSet::default())?;
3445 let handle = store
3446 .instance_state(self.runtime_instance(caller_instance))
3447 .handle_table()
3448 .waitable_set_insert(set.rep())?;
3449 log::trace!("new waitable set {set:?} (handle {handle})");
3450 Ok(handle)
3451 }
3452
3453 pub(crate) fn waitable_set_drop(
3455 self,
3456 store: &mut StoreOpaque,
3457 caller_instance: RuntimeComponentInstanceIndex,
3458 set: u32,
3459 ) -> Result<()> {
3460 let rep = store
3461 .instance_state(self.runtime_instance(caller_instance))
3462 .handle_table()
3463 .waitable_set_remove(set)?;
3464
3465 log::trace!("drop waitable set {rep} (handle {set})");
3466
3467 if !store
3471 .concurrent_state_mut()?
3472 .get_mut(TableId::<WaitableSet>::new(rep))?
3473 .waiting
3474 .is_empty()
3475 {
3476 bail!(Trap::WaitableSetDropHasWaiters);
3477 }
3478
3479 store
3480 .concurrent_state_mut()?
3481 .delete(TableId::<WaitableSet>::new(rep))?;
3482
3483 Ok(())
3484 }
3485
3486 pub(crate) fn waitable_join(
3488 self,
3489 store: &mut StoreOpaque,
3490 caller_instance: RuntimeComponentInstanceIndex,
3491 waitable_handle: u32,
3492 set_handle: u32,
3493 ) -> Result<()> {
3494 let mut instance = self.id().get_mut(store);
3495 let waitable =
3496 Waitable::from_instance(instance.as_mut(), caller_instance, waitable_handle)?;
3497
3498 let set = if set_handle == 0 {
3499 None
3500 } else {
3501 let set = instance.instance_states().0[caller_instance]
3502 .handle_table()
3503 .waitable_set_rep(set_handle)?;
3504
3505 let state = store.concurrent_state_mut()?;
3506 if let Some(old) = waitable.common(state)?.set
3507 && state.get_mut(old)?.is_sync_call_set
3508 {
3509 bail!(Trap::WaitableSyncAndAsync);
3510 }
3511
3512 Some(TableId::<WaitableSet>::new(set))
3513 };
3514
3515 log::trace!(
3516 "waitable {waitable:?} (handle {waitable_handle}) join set {set:?} (handle {set_handle})",
3517 );
3518
3519 waitable.join(store.concurrent_state_mut()?, set)
3520 }
3521
3522 pub(crate) fn subtask_drop(
3524 self,
3525 store: &mut StoreOpaque,
3526 caller_instance: RuntimeComponentInstanceIndex,
3527 task_id: u32,
3528 ) -> Result<()> {
3529 self.waitable_join(store, caller_instance, task_id, 0)?;
3530
3531 let (rep, is_host) = store
3532 .instance_state(self.runtime_instance(caller_instance))
3533 .handle_table()
3534 .subtask_remove(task_id)?;
3535
3536 let concurrent_state = store.concurrent_state_mut()?;
3537 let (waitable, delete) = if is_host {
3538 let id = TableId::<HostTask>::new(rep);
3539 let task = concurrent_state.get_mut(id)?;
3540 match &task.state {
3541 HostTaskState::CalleeRunning(_) => bail!(Trap::SubtaskDropNotResolved),
3542 HostTaskState::CalleeDone { .. } => {}
3543 HostTaskState::CalleeStarted | HostTaskState::CalleeFinished(_) => {
3544 bail_bug!("invalid state for callee in `subtask.drop`")
3545 }
3546 }
3547 (Waitable::Host(id), true)
3548 } else {
3549 let id = TableId::<GuestTask>::new(rep);
3550 let task = concurrent_state.get_mut(id)?;
3551 if task.lift_result.is_some() {
3552 bail!(Trap::SubtaskDropNotResolved);
3553 }
3554 (
3555 Waitable::Guest(id),
3556 concurrent_state.get_mut(id)?.ready_to_delete(),
3557 )
3558 };
3559
3560 waitable.common(concurrent_state)?.handle = None;
3561
3562 if waitable.take_event(concurrent_state)?.is_some() {
3565 bail!(Trap::SubtaskDropNotResolved);
3566 }
3567
3568 if delete {
3569 waitable.delete_from(concurrent_state)?;
3570 }
3571
3572 log::trace!("subtask_drop {waitable:?} (handle {task_id})");
3573 Ok(())
3574 }
3575
3576 pub(crate) fn waitable_set_wait(
3578 self,
3579 store: &mut StoreOpaque,
3580 options: OptionsIndex,
3581 set: u32,
3582 payload: u32,
3583 ) -> Result<u32> {
3584 if !self.options(store, options).async_ {
3585 store.check_blocking()?;
3589 }
3590
3591 let &CanonicalOptions {
3592 cancellable,
3593 instance: caller_instance,
3594 ..
3595 } = &self.id().get(store).component().env_component().options[options];
3596 let rep = store
3597 .instance_state(self.runtime_instance(caller_instance))
3598 .handle_table()
3599 .waitable_set_rep(set)?;
3600
3601 self.waitable_check(
3602 store,
3603 cancellable,
3604 WaitableCheck::Wait,
3605 WaitableCheckParams {
3606 set: TableId::new(rep),
3607 options,
3608 payload,
3609 },
3610 )
3611 }
3612
3613 pub(crate) fn waitable_set_poll(
3615 self,
3616 store: &mut StoreOpaque,
3617 options: OptionsIndex,
3618 set: u32,
3619 payload: u32,
3620 ) -> Result<u32> {
3621 let &CanonicalOptions {
3622 cancellable,
3623 instance: caller_instance,
3624 ..
3625 } = &self.id().get(store).component().env_component().options[options];
3626 let rep = store
3627 .instance_state(self.runtime_instance(caller_instance))
3628 .handle_table()
3629 .waitable_set_rep(set)?;
3630
3631 self.waitable_check(
3632 store,
3633 cancellable,
3634 WaitableCheck::Poll,
3635 WaitableCheckParams {
3636 set: TableId::new(rep),
3637 options,
3638 payload,
3639 },
3640 )
3641 }
3642
3643 pub(crate) fn thread_index(&self, store: &mut dyn VMStore) -> Result<u32> {
3645 let thread_id = store.current_guest_thread()?.thread;
3646 match store
3647 .concurrent_state_mut()?
3648 .get_mut(thread_id)?
3649 .instance_rep
3650 {
3651 Some(r) => Ok(r),
3652 None => bail_bug!("thread should have instance_rep by now"),
3653 }
3654 }
3655
3656 pub(crate) fn thread_new_indirect<T: 'static>(
3658 self,
3659 mut store: StoreContextMut<T>,
3660 runtime_instance: RuntimeComponentInstanceIndex,
3661 _func_ty_idx: TypeFuncIndex, start_func_table_idx: RuntimeTableIndex,
3663 start_func_idx: u32,
3664 context: i32,
3665 ) -> Result<u32> {
3666 log::trace!("creating new thread");
3667
3668 let start_func_ty = FuncType::new(store.engine(), [ValType::I32], []);
3669 let (instance, registry) = self.id().get_mut_and_registry(store.0);
3670 let callee = instance
3671 .index_runtime_func_table(registry, start_func_table_idx, start_func_idx as u64)?
3672 .ok_or_else(|| Trap::ThreadNewIndirectUninitialized)?;
3673 if callee.type_index(store.0) != start_func_ty.type_index() {
3674 bail!(Trap::ThreadNewIndirectInvalidType);
3675 }
3676
3677 let token = StoreToken::new(store.as_context_mut());
3678 let start_func = Box::new(
3679 move |store: &mut dyn VMStore, guest_thread: QualifiedThreadId| -> Result<()> {
3680 let old_thread = store.set_thread(guest_thread)?;
3681 log::trace!(
3682 "thread start: replaced {old_thread:?} with {guest_thread:?} as current thread"
3683 );
3684
3685 let mut store = token.as_context_mut(store);
3686 let mut params = [ValRaw::i32(context)];
3687 unsafe { callee.call_unchecked(store.as_context_mut(), &mut params)? };
3690
3691 store.0.set_thread(old_thread)?;
3692
3693 store.0.cleanup_thread(
3694 guest_thread,
3695 self.runtime_instance(runtime_instance),
3696 CleanupTask::Yes,
3697 )?;
3698 log::trace!("explicit thread {guest_thread:?} completed");
3699 let state = store.0.concurrent_state_mut()?;
3700 if let Some(t) = old_thread.guest() {
3701 state.get_mut(t.thread)?.state = GuestThreadState::Running;
3702 }
3703 log::trace!("thread start: restored {old_thread:?} as current thread");
3704
3705 Ok(())
3706 },
3707 );
3708
3709 let current_thread = store.0.current_guest_thread()?;
3710 let state = store.0.concurrent_state_mut()?;
3711 let parent_task = current_thread.task;
3712
3713 let new_thread = GuestThread::new_explicit(state, parent_task, start_func)?;
3714 let thread_id = state.push(new_thread)?;
3715 state.get_mut(parent_task)?.threads.insert(thread_id);
3716
3717 log::trace!("new thread with id {thread_id:?} created");
3718
3719 self.add_guest_thread_to_instance_table(thread_id, store.0, runtime_instance)
3720 }
3721
3722 pub(crate) fn resume_thread(
3723 self,
3724 store: &mut StoreOpaque,
3725 runtime_instance: RuntimeComponentInstanceIndex,
3726 thread_idx: u32,
3727 high_priority: bool,
3728 allow_ready: bool,
3729 ) -> Result<()> {
3730 let thread_id =
3731 GuestThread::from_instance(self.id().get_mut(store), runtime_instance, thread_idx)?;
3732 let state = store.concurrent_state_mut()?;
3733 let guest_thread = QualifiedThreadId::qualify(state, thread_id)?;
3734 let thread = state.get_mut(guest_thread.thread)?;
3735
3736 match mem::replace(&mut thread.state, GuestThreadState::Running) {
3737 GuestThreadState::NotStartedExplicit(start_func) => {
3738 log::trace!("starting thread {guest_thread:?}");
3739 let guest_call = WorkItem::GuestCall(
3740 runtime_instance,
3741 GuestCall {
3742 thread: guest_thread,
3743 kind: GuestCallKind::StartExplicit(Box::new(move |store| {
3744 start_func(store, guest_thread)
3745 })),
3746 },
3747 );
3748 store
3749 .concurrent_state_mut()?
3750 .push_work_item(guest_call, high_priority);
3751 }
3752 GuestThreadState::Suspended(fiber) => {
3753 log::trace!("resuming thread {thread_id:?} that was suspended");
3754 store
3755 .concurrent_state_mut()?
3756 .push_work_item(WorkItem::ResumeFiber(fiber), high_priority);
3757 }
3758 GuestThreadState::Ready { fiber, cancellable } if allow_ready => {
3759 log::trace!("resuming thread {thread_id:?} that was ready");
3760 thread.state = GuestThreadState::Ready { fiber, cancellable };
3761 store
3762 .concurrent_state_mut()?
3763 .promote_thread_work_item(guest_thread);
3764 }
3765 other => {
3766 thread.state = other;
3767 bail!(Trap::CannotResumeThread);
3768 }
3769 }
3770 Ok(())
3771 }
3772
3773 fn add_guest_thread_to_instance_table(
3774 self,
3775 thread_id: TableId<GuestThread>,
3776 store: &mut StoreOpaque,
3777 runtime_instance: RuntimeComponentInstanceIndex,
3778 ) -> Result<u32> {
3779 let guest_id = store
3780 .instance_state(self.runtime_instance(runtime_instance))
3781 .thread_handle_table()
3782 .guest_thread_insert(thread_id.rep())?;
3783 store
3784 .concurrent_state_mut()?
3785 .get_mut(thread_id)?
3786 .instance_rep = Some(guest_id);
3787 Ok(guest_id)
3788 }
3789
3790 pub(crate) fn suspension_intrinsic(
3793 self,
3794 store: &mut StoreOpaque,
3795 caller: RuntimeComponentInstanceIndex,
3796 cancellable: bool,
3797 yielding: bool,
3798 to_thread: SuspensionTarget,
3799 ) -> Result<WaitResult> {
3800 let guest_thread = store.current_guest_thread()?;
3801 if to_thread.is_none() {
3802 let state = store.concurrent_state_mut()?;
3803 if yielding {
3804 if !state.may_block(guest_thread.task)? {
3806 if !state.promote_instance_local_thread_work_item(caller) {
3809 return Ok(WaitResult::Completed);
3811 }
3812 }
3813 } else {
3814 store.check_blocking()?;
3818 }
3819 }
3820
3821 if cancellable && store.take_pending_cancellation()? {
3823 return Ok(WaitResult::Cancelled);
3824 }
3825
3826 match to_thread {
3827 SuspensionTarget::SomeSuspended(thread) => {
3828 self.resume_thread(store, caller, thread, true, false)?
3829 }
3830 SuspensionTarget::Some(thread) => {
3831 self.resume_thread(store, caller, thread, true, true)?
3832 }
3833 SuspensionTarget::None => { }
3834 }
3835
3836 let reason = if yielding {
3837 SuspendReason::Yielding {
3838 thread: guest_thread,
3839 cancellable,
3840 skip_may_block_check: to_thread.is_some(),
3844 }
3845 } else {
3846 SuspendReason::ExplicitlySuspending {
3847 thread: guest_thread,
3848 skip_may_block_check: to_thread.is_some(),
3852 }
3853 };
3854
3855 store.suspend(reason)?;
3856
3857 if cancellable && store.take_pending_cancellation()? {
3858 Ok(WaitResult::Cancelled)
3859 } else {
3860 Ok(WaitResult::Completed)
3861 }
3862 }
3863
3864 fn waitable_check(
3866 self,
3867 store: &mut StoreOpaque,
3868 cancellable: bool,
3869 check: WaitableCheck,
3870 params: WaitableCheckParams,
3871 ) -> Result<u32> {
3872 let guest_thread = store.current_guest_thread()?;
3873
3874 log::trace!("waitable check for {guest_thread:?}; set {:?}", params.set);
3875
3876 let state = store.concurrent_state_mut()?;
3877 let task = state.get_mut(guest_thread.task)?;
3878
3879 match &check {
3882 WaitableCheck::Wait => {
3883 let set = params.set;
3884
3885 if (task.event.is_none()
3886 || (matches!(task.event, Some(Event::Cancelled)) && !cancellable))
3887 && state.get_mut(set)?.ready.is_empty()
3888 {
3889 if cancellable {
3890 let old = state
3891 .get_mut(guest_thread.thread)?
3892 .wake_on_cancel
3893 .replace(set);
3894 if !old.is_none() {
3895 bail_bug!("thread unexpectedly in a prior wake_on_cancel set");
3896 }
3897 }
3898
3899 store.suspend(SuspendReason::Waiting {
3900 set,
3901 thread: guest_thread,
3902 skip_may_block_check: false,
3903 })?;
3904 }
3905 }
3906 WaitableCheck::Poll => {}
3907 }
3908
3909 log::trace!(
3910 "waitable check for {guest_thread:?}; set {:?}, part two",
3911 params.set
3912 );
3913
3914 let event = self.get_event(store, guest_thread.task, Some(params.set), cancellable)?;
3916
3917 let (ordinal, handle, result) = match &check {
3918 WaitableCheck::Wait => {
3919 let (event, waitable) = match event {
3920 Some(p) => p,
3921 None => bail_bug!("event expected to be present"),
3922 };
3923 let handle = waitable.map(|(_, v)| v).unwrap_or(0);
3924 let (ordinal, result) = event.parts();
3925 (ordinal, handle, result)
3926 }
3927 WaitableCheck::Poll => {
3928 if let Some((event, waitable)) = event {
3929 let handle = waitable.map(|(_, v)| v).unwrap_or(0);
3930 let (ordinal, result) = event.parts();
3931 (ordinal, handle, result)
3932 } else {
3933 log::trace!(
3934 "no events ready to deliver via waitable-set.poll to {:?}; set {:?}",
3935 guest_thread.task,
3936 params.set
3937 );
3938 let (ordinal, result) = Event::None.parts();
3939 (ordinal, 0, result)
3940 }
3941 }
3942 };
3943 let memory = self.options_memory_mut(store, params.options);
3944 let ptr = crate::component::func::validate_inbounds_dynamic(
3945 &CanonicalAbiInfo::POINTER_PAIR,
3946 memory,
3947 &ValRaw::u32(params.payload),
3948 )?;
3949 memory[ptr + 0..][..4].copy_from_slice(&handle.to_le_bytes());
3950 memory[ptr + 4..][..4].copy_from_slice(&result.to_le_bytes());
3951 Ok(ordinal)
3952 }
3953
3954 pub(crate) fn subtask_cancel(
3956 self,
3957 store: &mut StoreOpaque,
3958 caller_instance: RuntimeComponentInstanceIndex,
3959 async_: bool,
3960 task_id: u32,
3961 ) -> Result<u32> {
3962 if !async_ {
3963 store.check_blocking()?;
3967 }
3968
3969 let (rep, is_host) = store
3970 .instance_state(self.runtime_instance(caller_instance))
3971 .handle_table()
3972 .subtask_rep(task_id)?;
3973 let waitable = if is_host {
3974 Waitable::Host(TableId::<HostTask>::new(rep))
3975 } else {
3976 Waitable::Guest(TableId::<GuestTask>::new(rep))
3977 };
3978 let concurrent_state = store.concurrent_state_mut()?;
3979
3980 log::trace!("subtask_cancel {waitable:?} (handle {task_id})");
3981
3982 if !async_ {
3983 waitable.trap_if_in_waitable_set(concurrent_state)?;
3984 }
3985
3986 let needs_block;
3987 if let Waitable::Host(host_task) = waitable {
3988 let state = &mut concurrent_state.get_mut(host_task)?.state;
3989 match mem::replace(state, HostTaskState::CalleeDone { cancelled: true }) {
3990 HostTaskState::CalleeRunning(handle) => {
3997 handle.abort();
3998 needs_block = true;
3999 }
4000
4001 HostTaskState::CalleeDone { cancelled } => {
4004 if cancelled {
4005 bail!(Trap::SubtaskCancelAfterTerminal);
4006 } else {
4007 needs_block = false;
4010 }
4011 }
4012
4013 HostTaskState::CalleeStarted | HostTaskState::CalleeFinished(_) => {
4016 bail_bug!("invalid states for host callee")
4017 }
4018 }
4019 } else {
4020 let guest_task = TableId::<GuestTask>::new(rep);
4021 let task = concurrent_state.get_mut(guest_task)?;
4022 if !task.already_lowered_parameters() {
4023 store.cancel_guest_subtask_without_lowered_parameters(
4024 self.runtime_instance(caller_instance),
4025 guest_task,
4026 )?;
4027 return Ok(Status::StartCancelled as u32);
4028 } else if !task.returned_or_cancelled() {
4029 task.cancel_sent = true;
4032 task.event = Some(Event::Cancelled);
4037 let runtime_instance = task.instance.index;
4038 for thread in task.threads.clone() {
4039 let thread = QualifiedThreadId {
4040 task: guest_task,
4041 thread,
4042 };
4043 let thread_mut = concurrent_state.get_mut(thread.thread)?;
4044 if let Some(set) = thread_mut.wake_on_cancel.take() {
4045 let item = match concurrent_state.get_mut(set)?.waiting.remove(&thread) {
4047 Some(WaitMode::Fiber(fiber)) => WorkItem::ResumeFiber(fiber),
4048 Some(WaitMode::Callback(instance)) => WorkItem::GuestCall(
4049 runtime_instance,
4050 GuestCall {
4051 thread,
4052 kind: GuestCallKind::DeliverEvent {
4053 instance,
4054 set: None,
4055 },
4056 },
4057 ),
4058 None => bail_bug!("thread not present in wake_on_cancel set"),
4059 };
4060 concurrent_state.push_high_priority(item);
4061
4062 let caller = store.current_guest_thread()?;
4063 store.suspend(SuspendReason::Yielding {
4064 thread: caller,
4065 cancellable: false,
4066 skip_may_block_check: false,
4069 })?;
4070 break;
4071 } else if let GuestThreadState::Ready {
4072 cancellable: true, ..
4073 } = &thread_mut.state
4074 {
4075 concurrent_state.promote_thread_work_item(thread);
4078 let caller = store.current_guest_thread()?;
4079 store.suspend(SuspendReason::Yielding {
4080 thread: caller,
4081 cancellable: false,
4082 skip_may_block_check: false,
4083 })?;
4084 break;
4085 }
4086 }
4087
4088 needs_block = !store
4091 .concurrent_state_mut()?
4092 .get_mut(guest_task)?
4093 .returned_or_cancelled()
4094 } else {
4095 needs_block = false;
4096 }
4097 };
4098
4099 if needs_block {
4103 if async_ {
4104 return Ok(BLOCKED);
4105 }
4106
4107 store.wait_for_event(waitable)?;
4111
4112 }
4114
4115 let event = waitable.take_event(store.concurrent_state_mut()?)?;
4116 if let Some(Event::Subtask {
4117 status: status @ (Status::Returned | Status::ReturnCancelled),
4118 }) = event
4119 {
4120 Ok(status as u32)
4121 } else {
4122 bail!(Trap::SubtaskCancelAfterTerminal);
4123 }
4124 }
4125}
4126
4127pub trait VMComponentAsyncStore {
4135 unsafe fn prepare_call(
4141 &mut self,
4142 instance: Instance,
4143 memory: *mut VMMemoryDefinition,
4144 start: NonNull<VMFuncRef>,
4145 return_: NonNull<VMFuncRef>,
4146 caller_instance: RuntimeComponentInstanceIndex,
4147 callee_instance: RuntimeComponentInstanceIndex,
4148 task_return_type: TypeTupleIndex,
4149 callee_async: bool,
4150 string_encoding: StringEncoding,
4151 result_count: u32,
4152 storage: *mut ValRaw,
4153 storage_len: usize,
4154 ) -> Result<()>;
4155
4156 unsafe fn sync_start(
4159 &mut self,
4160 instance: Instance,
4161 callback: *mut VMFuncRef,
4162 callee: NonNull<VMFuncRef>,
4163 param_count: u32,
4164 storage: *mut MaybeUninit<ValRaw>,
4165 storage_len: usize,
4166 ) -> Result<()>;
4167
4168 unsafe fn async_start(
4171 &mut self,
4172 instance: Instance,
4173 callback: *mut VMFuncRef,
4174 post_return: *mut VMFuncRef,
4175 callee: NonNull<VMFuncRef>,
4176 param_count: u32,
4177 result_count: u32,
4178 flags: u32,
4179 ) -> Result<u32>;
4180
4181 fn future_write(
4183 &mut self,
4184 instance: Instance,
4185 caller: RuntimeComponentInstanceIndex,
4186 ty: TypeFutureTableIndex,
4187 options: OptionsIndex,
4188 future: u32,
4189 address: u32,
4190 ) -> Result<u32>;
4191
4192 fn future_read(
4194 &mut self,
4195 instance: Instance,
4196 caller: RuntimeComponentInstanceIndex,
4197 ty: TypeFutureTableIndex,
4198 options: OptionsIndex,
4199 future: u32,
4200 address: u32,
4201 ) -> Result<u32>;
4202
4203 fn future_drop_writable(
4205 &mut self,
4206 instance: Instance,
4207 ty: TypeFutureTableIndex,
4208 writer: u32,
4209 ) -> Result<()>;
4210
4211 fn stream_write(
4213 &mut self,
4214 instance: Instance,
4215 caller: RuntimeComponentInstanceIndex,
4216 ty: TypeStreamTableIndex,
4217 options: OptionsIndex,
4218 stream: u32,
4219 address: u32,
4220 count: u32,
4221 ) -> Result<u32>;
4222
4223 fn stream_read(
4225 &mut self,
4226 instance: Instance,
4227 caller: RuntimeComponentInstanceIndex,
4228 ty: TypeStreamTableIndex,
4229 options: OptionsIndex,
4230 stream: u32,
4231 address: u32,
4232 count: u32,
4233 ) -> Result<u32>;
4234
4235 fn flat_stream_write(
4238 &mut self,
4239 instance: Instance,
4240 caller: RuntimeComponentInstanceIndex,
4241 ty: TypeStreamTableIndex,
4242 options: OptionsIndex,
4243 payload_size: u32,
4244 payload_align: u32,
4245 stream: u32,
4246 address: u32,
4247 count: u32,
4248 ) -> Result<u32>;
4249
4250 fn flat_stream_read(
4253 &mut self,
4254 instance: Instance,
4255 caller: RuntimeComponentInstanceIndex,
4256 ty: TypeStreamTableIndex,
4257 options: OptionsIndex,
4258 payload_size: u32,
4259 payload_align: u32,
4260 stream: u32,
4261 address: u32,
4262 count: u32,
4263 ) -> Result<u32>;
4264
4265 fn stream_drop_writable(
4267 &mut self,
4268 instance: Instance,
4269 ty: TypeStreamTableIndex,
4270 writer: u32,
4271 ) -> Result<()>;
4272
4273 fn error_context_debug_message(
4275 &mut self,
4276 instance: Instance,
4277 ty: TypeComponentLocalErrorContextTableIndex,
4278 options: OptionsIndex,
4279 err_ctx_handle: u32,
4280 debug_msg_address: u32,
4281 ) -> Result<()>;
4282
4283 fn thread_new_indirect(
4285 &mut self,
4286 instance: Instance,
4287 caller: RuntimeComponentInstanceIndex,
4288 func_ty_idx: TypeFuncIndex,
4289 start_func_table_idx: RuntimeTableIndex,
4290 start_func_idx: u32,
4291 context: i32,
4292 ) -> Result<u32>;
4293}
4294
4295impl<T: 'static> VMComponentAsyncStore for StoreInner<T> {
4297 unsafe fn prepare_call(
4298 &mut self,
4299 instance: Instance,
4300 memory: *mut VMMemoryDefinition,
4301 start: NonNull<VMFuncRef>,
4302 return_: NonNull<VMFuncRef>,
4303 caller_instance: RuntimeComponentInstanceIndex,
4304 callee_instance: RuntimeComponentInstanceIndex,
4305 task_return_type: TypeTupleIndex,
4306 callee_async: bool,
4307 string_encoding: StringEncoding,
4308 result_count_or_max_if_async: u32,
4309 storage: *mut ValRaw,
4310 storage_len: usize,
4311 ) -> Result<()> {
4312 let params = unsafe { core::slice::from_raw_parts(storage, storage_len) }.to_vec();
4316
4317 unsafe {
4318 instance.prepare_call(
4319 StoreContextMut(self),
4320 start,
4321 return_,
4322 caller_instance,
4323 callee_instance,
4324 task_return_type,
4325 callee_async,
4326 memory,
4327 string_encoding,
4328 match result_count_or_max_if_async {
4329 PREPARE_ASYNC_NO_RESULT => CallerInfo::Async {
4330 params,
4331 has_result: false,
4332 },
4333 PREPARE_ASYNC_WITH_RESULT => CallerInfo::Async {
4334 params,
4335 has_result: true,
4336 },
4337 result_count => CallerInfo::Sync {
4338 params,
4339 result_count,
4340 },
4341 },
4342 )
4343 }
4344 }
4345
4346 unsafe fn sync_start(
4347 &mut self,
4348 instance: Instance,
4349 callback: *mut VMFuncRef,
4350 callee: NonNull<VMFuncRef>,
4351 param_count: u32,
4352 storage: *mut MaybeUninit<ValRaw>,
4353 storage_len: usize,
4354 ) -> Result<()> {
4355 unsafe {
4356 instance
4357 .start_call(
4358 StoreContextMut(self),
4359 callback,
4360 ptr::null_mut(),
4361 callee,
4362 param_count,
4363 1,
4364 START_FLAG_ASYNC_CALLEE,
4365 Some(core::slice::from_raw_parts_mut(storage, storage_len)),
4369 )
4370 .map(drop)
4371 }
4372 }
4373
4374 unsafe fn async_start(
4375 &mut self,
4376 instance: Instance,
4377 callback: *mut VMFuncRef,
4378 post_return: *mut VMFuncRef,
4379 callee: NonNull<VMFuncRef>,
4380 param_count: u32,
4381 result_count: u32,
4382 flags: u32,
4383 ) -> Result<u32> {
4384 unsafe {
4385 instance.start_call(
4386 StoreContextMut(self),
4387 callback,
4388 post_return,
4389 callee,
4390 param_count,
4391 result_count,
4392 flags,
4393 None,
4394 )
4395 }
4396 }
4397
4398 fn future_write(
4399 &mut self,
4400 instance: Instance,
4401 caller: RuntimeComponentInstanceIndex,
4402 ty: TypeFutureTableIndex,
4403 options: OptionsIndex,
4404 future: u32,
4405 address: u32,
4406 ) -> Result<u32> {
4407 instance
4408 .guest_write(
4409 StoreContextMut(self),
4410 caller,
4411 TransmitIndex::Future(ty),
4412 options,
4413 None,
4414 future,
4415 address,
4416 1,
4417 )
4418 .map(|result| result.encode())
4419 }
4420
4421 fn future_read(
4422 &mut self,
4423 instance: Instance,
4424 caller: RuntimeComponentInstanceIndex,
4425 ty: TypeFutureTableIndex,
4426 options: OptionsIndex,
4427 future: u32,
4428 address: u32,
4429 ) -> Result<u32> {
4430 instance
4431 .guest_read(
4432 StoreContextMut(self),
4433 caller,
4434 TransmitIndex::Future(ty),
4435 options,
4436 None,
4437 future,
4438 address,
4439 1,
4440 )
4441 .map(|result| result.encode())
4442 }
4443
4444 fn stream_write(
4445 &mut self,
4446 instance: Instance,
4447 caller: RuntimeComponentInstanceIndex,
4448 ty: TypeStreamTableIndex,
4449 options: OptionsIndex,
4450 stream: u32,
4451 address: u32,
4452 count: u32,
4453 ) -> Result<u32> {
4454 instance
4455 .guest_write(
4456 StoreContextMut(self),
4457 caller,
4458 TransmitIndex::Stream(ty),
4459 options,
4460 None,
4461 stream,
4462 address,
4463 count,
4464 )
4465 .map(|result| result.encode())
4466 }
4467
4468 fn stream_read(
4469 &mut self,
4470 instance: Instance,
4471 caller: RuntimeComponentInstanceIndex,
4472 ty: TypeStreamTableIndex,
4473 options: OptionsIndex,
4474 stream: u32,
4475 address: u32,
4476 count: u32,
4477 ) -> Result<u32> {
4478 instance
4479 .guest_read(
4480 StoreContextMut(self),
4481 caller,
4482 TransmitIndex::Stream(ty),
4483 options,
4484 None,
4485 stream,
4486 address,
4487 count,
4488 )
4489 .map(|result| result.encode())
4490 }
4491
4492 fn future_drop_writable(
4493 &mut self,
4494 instance: Instance,
4495 ty: TypeFutureTableIndex,
4496 writer: u32,
4497 ) -> Result<()> {
4498 instance.guest_drop_writable(self, TransmitIndex::Future(ty), writer)
4499 }
4500
4501 fn flat_stream_write(
4502 &mut self,
4503 instance: Instance,
4504 caller: RuntimeComponentInstanceIndex,
4505 ty: TypeStreamTableIndex,
4506 options: OptionsIndex,
4507 payload_size: u32,
4508 payload_align: u32,
4509 stream: u32,
4510 address: u32,
4511 count: u32,
4512 ) -> Result<u32> {
4513 instance
4514 .guest_write(
4515 StoreContextMut(self),
4516 caller,
4517 TransmitIndex::Stream(ty),
4518 options,
4519 Some(FlatAbi {
4520 size: payload_size,
4521 align: payload_align,
4522 }),
4523 stream,
4524 address,
4525 count,
4526 )
4527 .map(|result| result.encode())
4528 }
4529
4530 fn flat_stream_read(
4531 &mut self,
4532 instance: Instance,
4533 caller: RuntimeComponentInstanceIndex,
4534 ty: TypeStreamTableIndex,
4535 options: OptionsIndex,
4536 payload_size: u32,
4537 payload_align: u32,
4538 stream: u32,
4539 address: u32,
4540 count: u32,
4541 ) -> Result<u32> {
4542 instance
4543 .guest_read(
4544 StoreContextMut(self),
4545 caller,
4546 TransmitIndex::Stream(ty),
4547 options,
4548 Some(FlatAbi {
4549 size: payload_size,
4550 align: payload_align,
4551 }),
4552 stream,
4553 address,
4554 count,
4555 )
4556 .map(|result| result.encode())
4557 }
4558
4559 fn stream_drop_writable(
4560 &mut self,
4561 instance: Instance,
4562 ty: TypeStreamTableIndex,
4563 writer: u32,
4564 ) -> Result<()> {
4565 instance.guest_drop_writable(self, TransmitIndex::Stream(ty), writer)
4566 }
4567
4568 fn error_context_debug_message(
4569 &mut self,
4570 instance: Instance,
4571 ty: TypeComponentLocalErrorContextTableIndex,
4572 options: OptionsIndex,
4573 err_ctx_handle: u32,
4574 debug_msg_address: u32,
4575 ) -> Result<()> {
4576 instance.error_context_debug_message(
4577 StoreContextMut(self),
4578 ty,
4579 options,
4580 err_ctx_handle,
4581 debug_msg_address,
4582 )
4583 }
4584
4585 fn thread_new_indirect(
4586 &mut self,
4587 instance: Instance,
4588 caller: RuntimeComponentInstanceIndex,
4589 func_ty_idx: TypeFuncIndex,
4590 start_func_table_idx: RuntimeTableIndex,
4591 start_func_idx: u32,
4592 context: i32,
4593 ) -> Result<u32> {
4594 instance.thread_new_indirect(
4595 StoreContextMut(self),
4596 caller,
4597 func_ty_idx,
4598 start_func_table_idx,
4599 start_func_idx,
4600 context,
4601 )
4602 }
4603}
4604
4605type HostTaskFuture = Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>;
4606
4607pub(crate) struct HostTask {
4611 common: WaitableCommon,
4612
4613 caller: TableId<GuestTask>,
4620
4621 call_context: CallContext,
4624
4625 state: HostTaskState,
4626}
4627
4628enum HostTaskState {
4629 CalleeStarted,
4634
4635 CalleeRunning(JoinHandle),
4640
4641 CalleeFinished(LiftedResult),
4645
4646 CalleeDone { cancelled: bool },
4649}
4650
4651impl HostTask {
4652 fn new(caller: TableId<GuestTask>, state: HostTaskState) -> Self {
4653 Self {
4654 common: WaitableCommon::default(),
4655 call_context: CallContext::default(),
4656 caller,
4657 state,
4658 }
4659 }
4660}
4661
4662impl TableDebug for HostTask {
4663 fn type_name() -> &'static str {
4664 "HostTask"
4665 }
4666}
4667
4668type CallbackFn = Box<dyn Fn(&mut dyn VMStore, Event, u32) -> Result<u32> + Send + Sync + 'static>;
4669
4670enum Caller {
4672 Host {
4674 tx: Option<oneshot::Sender<LiftedResult>>,
4676 host_future_present: bool,
4679 caller: CurrentThread,
4683 },
4684 Guest {
4686 thread: QualifiedThreadId,
4688 },
4689}
4690
4691struct LiftResult {
4694 lift: RawLift,
4695 ty: TypeTupleIndex,
4696 memory: Option<SendSyncPtr<VMMemoryDefinition>>,
4697 string_encoding: StringEncoding,
4698}
4699
4700#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
4705pub(crate) struct QualifiedThreadId {
4706 task: TableId<GuestTask>,
4707 thread: TableId<GuestThread>,
4708}
4709
4710impl QualifiedThreadId {
4711 fn qualify(
4712 state: &mut ConcurrentState,
4713 thread: TableId<GuestThread>,
4714 ) -> Result<QualifiedThreadId> {
4715 Ok(QualifiedThreadId {
4716 task: state.get_mut(thread)?.parent_task,
4717 thread,
4718 })
4719 }
4720}
4721
4722impl fmt::Debug for QualifiedThreadId {
4723 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4724 f.debug_tuple("QualifiedThreadId")
4725 .field(&self.task.rep())
4726 .field(&self.thread.rep())
4727 .finish()
4728 }
4729}
4730
4731enum GuestThreadState {
4732 NotStartedImplicit,
4733 NotStartedExplicit(
4734 Box<dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync>,
4735 ),
4736 Running,
4737 Suspended(StoreFiber<'static>),
4738 Ready {
4739 fiber: StoreFiber<'static>,
4740 cancellable: bool,
4741 },
4742 Completed,
4743}
4744pub struct GuestThread {
4745 context: [u32; NUM_COMPONENT_CONTEXT_SLOTS],
4748 parent_task: TableId<GuestTask>,
4750 wake_on_cancel: Option<TableId<WaitableSet>>,
4753 state: GuestThreadState,
4755 instance_rep: Option<u32>,
4758 sync_call_set: TableId<WaitableSet>,
4760}
4761
4762impl GuestThread {
4763 fn from_instance(
4766 state: Pin<&mut ComponentInstance>,
4767 caller_instance: RuntimeComponentInstanceIndex,
4768 guest_thread: u32,
4769 ) -> Result<TableId<Self>> {
4770 let rep = state.instance_states().0[caller_instance]
4771 .thread_handle_table()
4772 .guest_thread_rep(guest_thread)?;
4773 Ok(TableId::new(rep))
4774 }
4775
4776 fn new_implicit(state: &mut ConcurrentState, parent_task: TableId<GuestTask>) -> Result<Self> {
4777 let sync_call_set = state.push(WaitableSet {
4778 is_sync_call_set: true,
4779 ..WaitableSet::default()
4780 })?;
4781 Ok(Self {
4782 context: [0; NUM_COMPONENT_CONTEXT_SLOTS],
4783 parent_task,
4784 wake_on_cancel: None,
4785 state: GuestThreadState::NotStartedImplicit,
4786 instance_rep: None,
4787 sync_call_set,
4788 })
4789 }
4790
4791 fn new_explicit(
4792 state: &mut ConcurrentState,
4793 parent_task: TableId<GuestTask>,
4794 start_func: Box<
4795 dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync,
4796 >,
4797 ) -> Result<Self> {
4798 let sync_call_set = state.push(WaitableSet {
4799 is_sync_call_set: true,
4800 ..WaitableSet::default()
4801 })?;
4802 Ok(Self {
4803 context: [0; NUM_COMPONENT_CONTEXT_SLOTS],
4804 parent_task,
4805 wake_on_cancel: None,
4806 state: GuestThreadState::NotStartedExplicit(start_func),
4807 instance_rep: None,
4808 sync_call_set,
4809 })
4810 }
4811}
4812
4813impl TableDebug for GuestThread {
4814 fn type_name() -> &'static str {
4815 "GuestThread"
4816 }
4817}
4818
4819enum SyncResult {
4820 NotProduced,
4821 Produced(Option<ValRaw>),
4822 Taken,
4823}
4824
4825impl SyncResult {
4826 fn take(&mut self) -> Result<Option<Option<ValRaw>>> {
4827 Ok(match mem::replace(self, SyncResult::Taken) {
4828 SyncResult::NotProduced => None,
4829 SyncResult::Produced(val) => Some(val),
4830 SyncResult::Taken => {
4831 bail_bug!("attempted to take a synchronous result that was already taken")
4832 }
4833 })
4834 }
4835}
4836
4837#[derive(Debug)]
4838enum HostFutureState {
4839 NotApplicable,
4840 Live,
4841 Dropped,
4842}
4843
4844pub(crate) struct GuestTask {
4846 common: WaitableCommon,
4848 lower_params: Option<RawLower>,
4850 lift_result: Option<LiftResult>,
4852 result: Option<LiftedResult>,
4855 callback: Option<CallbackFn>,
4858 caller: Caller,
4860 call_context: CallContext,
4865 sync_result: SyncResult,
4868 cancel_sent: bool,
4871 starting_sent: bool,
4874 instance: RuntimeInstance,
4881 event: Option<Event>,
4884 exited: bool,
4886 threads: HashSet<TableId<GuestThread>>,
4888 host_future_state: HostFutureState,
4891 async_function: bool,
4894
4895 decremented_interesting_task_count: bool,
4896}
4897
4898impl GuestTask {
4899 fn already_lowered_parameters(&self) -> bool {
4900 self.lower_params.is_none()
4902 }
4903
4904 fn returned_or_cancelled(&self) -> bool {
4905 self.lift_result.is_none()
4907 }
4908
4909 fn ready_to_delete(&self) -> bool {
4910 let threads_completed = self.threads.is_empty();
4911 let has_sync_result = matches!(self.sync_result, SyncResult::Produced(_));
4912 let pending_completion_event = matches!(
4913 self.common.event,
4914 Some(Event::Subtask {
4915 status: Status::Returned | Status::ReturnCancelled
4916 })
4917 );
4918 let ready = threads_completed
4919 && !has_sync_result
4920 && !pending_completion_event
4921 && !matches!(self.host_future_state, HostFutureState::Live);
4922 log::trace!(
4923 "ready to delete? {ready} (threads_completed: {}, has_sync_result: {}, pending_completion_event: {}, host_future_state: {:?})",
4924 threads_completed,
4925 has_sync_result,
4926 pending_completion_event,
4927 self.host_future_state
4928 );
4929 ready
4930 }
4931
4932 fn new(
4933 state: &mut ConcurrentState,
4934 lower_params: RawLower,
4935 lift_result: LiftResult,
4936 caller: Caller,
4937 callback: Option<CallbackFn>,
4938 instance: RuntimeInstance,
4939 async_function: bool,
4940 ) -> Result<QualifiedThreadId> {
4941 let host_future_state = match &caller {
4942 Caller::Guest { .. } => HostFutureState::NotApplicable,
4943 Caller::Host {
4944 host_future_present,
4945 ..
4946 } => {
4947 if *host_future_present {
4948 HostFutureState::Live
4949 } else {
4950 HostFutureState::NotApplicable
4951 }
4952 }
4953 };
4954 let task = state.push(Self {
4955 common: WaitableCommon::default(),
4956 lower_params: Some(lower_params),
4957 lift_result: Some(lift_result),
4958 result: None,
4959 callback,
4960 caller,
4961 call_context: CallContext::default(),
4962 sync_result: SyncResult::NotProduced,
4963 cancel_sent: false,
4964 starting_sent: false,
4965 instance,
4966 event: None,
4967 exited: false,
4968 threads: HashSet::new(),
4969 host_future_state,
4970 async_function,
4971 decremented_interesting_task_count: false,
4972 })?;
4973 let new_thread = GuestThread::new_implicit(state, task)?;
4974 let thread = state.push(new_thread)?;
4975 state.get_mut(task)?.threads.insert(thread);
4976 state.interesting_tasks += 1;
4977 Ok(QualifiedThreadId { task, thread })
4978 }
4979}
4980
4981impl TableDebug for GuestTask {
4982 fn type_name() -> &'static str {
4983 "GuestTask"
4984 }
4985}
4986
4987#[derive(Default)]
4989struct WaitableCommon {
4990 event: Option<Event>,
4992 set: Option<TableId<WaitableSet>>,
4994 handle: Option<u32>,
4996}
4997
4998#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
5000enum Waitable {
5001 Host(TableId<HostTask>),
5003 Guest(TableId<GuestTask>),
5005 Transmit(TableId<TransmitHandle>),
5007}
5008
5009impl Waitable {
5010 fn from_instance(
5013 state: Pin<&mut ComponentInstance>,
5014 caller_instance: RuntimeComponentInstanceIndex,
5015 waitable: u32,
5016 ) -> Result<Self> {
5017 use crate::runtime::vm::component::Waitable;
5018
5019 let (waitable, kind) = state.instance_states().0[caller_instance]
5020 .handle_table()
5021 .waitable_rep(waitable)?;
5022
5023 Ok(match kind {
5024 Waitable::Subtask { is_host: true } => Self::Host(TableId::new(waitable)),
5025 Waitable::Subtask { is_host: false } => Self::Guest(TableId::new(waitable)),
5026 Waitable::Stream | Waitable::Future => Self::Transmit(TableId::new(waitable)),
5027 })
5028 }
5029
5030 fn rep(&self) -> u32 {
5032 match self {
5033 Self::Host(id) => id.rep(),
5034 Self::Guest(id) => id.rep(),
5035 Self::Transmit(id) => id.rep(),
5036 }
5037 }
5038
5039 fn join(&self, state: &mut ConcurrentState, set: Option<TableId<WaitableSet>>) -> Result<()> {
5043 log::trace!("waitable {self:?} join set {set:?}");
5044
5045 let old = mem::replace(&mut self.common(state)?.set, set);
5046
5047 if let Some(old) = old {
5048 match *self {
5049 Waitable::Host(id) => state.remove_child(id, old),
5050 Waitable::Guest(id) => state.remove_child(id, old),
5051 Waitable::Transmit(id) => state.remove_child(id, old),
5052 }?;
5053
5054 state.get_mut(old)?.ready.remove(self);
5055 }
5056
5057 if let Some(set) = set {
5058 match *self {
5059 Waitable::Host(id) => state.add_child(id, set),
5060 Waitable::Guest(id) => state.add_child(id, set),
5061 Waitable::Transmit(id) => state.add_child(id, set),
5062 }?;
5063
5064 if self.common(state)?.event.is_some() {
5065 self.mark_ready(state)?;
5066 }
5067 }
5068
5069 Ok(())
5070 }
5071
5072 fn common<'a>(&self, state: &'a mut ConcurrentState) -> Result<&'a mut WaitableCommon> {
5074 Ok(match self {
5075 Self::Host(id) => &mut state.get_mut(*id)?.common,
5076 Self::Guest(id) => &mut state.get_mut(*id)?.common,
5077 Self::Transmit(id) => &mut state.get_mut(*id)?.common,
5078 })
5079 }
5080
5081 fn trap_if_in_waitable_set(&self, state: &mut ConcurrentState) -> Result<()> {
5087 if self.common(state)?.set.is_some() {
5088 bail!(Trap::WaitableSyncAndAsync);
5089 }
5090 Ok(())
5091 }
5092
5093 fn set_event(&self, state: &mut ConcurrentState, event: Option<Event>) -> Result<()> {
5097 log::trace!("set event for {self:?}: {event:?}");
5098 self.common(state)?.event = event;
5099 self.mark_ready(state)
5100 }
5101
5102 fn take_event(&self, state: &mut ConcurrentState) -> Result<Option<Event>> {
5104 let common = self.common(state)?;
5105 let event = common.event.take();
5106 if let Some(set) = self.common(state)?.set {
5107 state.get_mut(set)?.ready.remove(self);
5108 }
5109
5110 Ok(event)
5111 }
5112
5113 fn mark_ready(&self, state: &mut ConcurrentState) -> Result<()> {
5117 if let Some(set) = self.common(state)?.set {
5118 state.get_mut(set)?.ready.insert(*self);
5119 if let Some((thread, mode)) = state.get_mut(set)?.waiting.pop_first() {
5120 let wake_on_cancel = state.get_mut(thread.thread)?.wake_on_cancel.take();
5121 assert!(wake_on_cancel.is_none() || wake_on_cancel == Some(set));
5122
5123 let item = match mode {
5124 WaitMode::Fiber(fiber) => WorkItem::ResumeFiber(fiber),
5125 WaitMode::Callback(instance) => WorkItem::GuestCall(
5126 state.get_mut(thread.task)?.instance.index,
5127 GuestCall {
5128 thread,
5129 kind: GuestCallKind::DeliverEvent {
5130 instance,
5131 set: Some(set),
5132 },
5133 },
5134 ),
5135 };
5136 state.push_high_priority(item);
5137 }
5138 }
5139 Ok(())
5140 }
5141
5142 fn delete_from(&self, state: &mut ConcurrentState) -> Result<()> {
5144 match self {
5145 Self::Host(task) => {
5146 log::trace!("delete host task {task:?}");
5147 state.delete(*task)?;
5148 }
5149 Self::Guest(task) => {
5150 log::trace!("delete guest task {task:?}");
5151 let task = state.delete(*task)?;
5152
5153 debug_assert!(task.decremented_interesting_task_count);
5160 }
5161 Self::Transmit(task) => {
5162 state.delete(*task)?;
5163 }
5164 }
5165
5166 Ok(())
5167 }
5168}
5169
5170impl fmt::Debug for Waitable {
5171 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5172 match self {
5173 Self::Host(id) => write!(f, "{id:?}"),
5174 Self::Guest(id) => write!(f, "{id:?}"),
5175 Self::Transmit(id) => write!(f, "{id:?}"),
5176 }
5177 }
5178}
5179
5180#[derive(Default)]
5182struct WaitableSet {
5183 ready: BTreeSet<Waitable>,
5185 waiting: BTreeMap<QualifiedThreadId, WaitMode>,
5187 is_sync_call_set: bool,
5190}
5191
5192impl TableDebug for WaitableSet {
5193 fn type_name() -> &'static str {
5194 "WaitableSet"
5195 }
5196}
5197
5198type RawLower =
5200 Box<dyn FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync>;
5201
5202type RawLift = Box<
5204 dyn FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
5205>;
5206
5207type LiftedResult = Box<dyn Any + Send + Sync>;
5211
5212struct DummyResult;
5215
5216#[derive(Default)]
5218pub struct ConcurrentInstanceState {
5219 backpressure: u16,
5221 do_not_enter: bool,
5223 pending: BTreeMap<QualifiedThreadId, GuestCallKind>,
5226}
5227
5228impl ConcurrentInstanceState {
5229 pub fn pending_is_empty(&self) -> bool {
5230 self.pending.is_empty()
5231 }
5232}
5233
5234#[derive(Debug, Copy, Clone)]
5235pub(crate) enum CurrentThread {
5236 Guest(QualifiedThreadId),
5239 Host(TableId<HostTask>),
5241 GuestTask(TableId<GuestTask>),
5245 None,
5247}
5248
5249impl CurrentThread {
5250 fn guest(&self) -> Option<&QualifiedThreadId> {
5251 match self {
5252 Self::Guest(id) => Some(id),
5253 _ => None,
5254 }
5255 }
5256
5257 fn guest_task(&self) -> Option<TableId<GuestTask>> {
5258 match self {
5259 Self::Guest(id) => Some(id.task),
5260 Self::GuestTask(id) => Some(*id),
5261 _ => None,
5262 }
5263 }
5264
5265 fn host(&self) -> Option<TableId<HostTask>> {
5266 match self {
5267 Self::Host(id) => Some(*id),
5268 _ => None,
5269 }
5270 }
5271
5272 fn is_none(&self) -> bool {
5273 matches!(self, Self::None)
5274 }
5275}
5276
5277impl From<QualifiedThreadId> for CurrentThread {
5278 fn from(id: QualifiedThreadId) -> Self {
5279 Self::Guest(id)
5280 }
5281}
5282
5283impl From<TableId<HostTask>> for CurrentThread {
5284 fn from(id: TableId<HostTask>) -> Self {
5285 Self::Host(id)
5286 }
5287}
5288
5289pub struct ConcurrentState {
5291 unforced_current_thread: CurrentThread,
5297
5298 futures: AlwaysMut<Option<FuturesUnordered<HostTaskFuture>>>,
5303 table: AlwaysMut<ResourceTable>,
5305 high_priority: Vec<WorkItem>,
5307 low_priority: VecDeque<WorkItem>,
5309 suspend_reason: Option<SuspendReason>,
5313 worker: Option<StoreFiber<'static>>,
5317 worker_item: Option<WorkerItem>,
5319
5320 global_error_context_ref_counts:
5333 BTreeMap<TypeComponentGlobalErrorContextTableIndex, GlobalErrorContextRefCount>,
5334
5335 interesting_tasks: usize,
5348
5349 interesting_tasks_empty_waker: Option<Waker>,
5353
5354 ready_for_concurrent_call_waker: Option<Waker>,
5359}
5360
5361impl Default for ConcurrentState {
5362 fn default() -> Self {
5363 Self {
5364 unforced_current_thread: CurrentThread::None,
5365 table: AlwaysMut::new(ResourceTable::new()),
5366 futures: AlwaysMut::new(Some(FuturesUnordered::new())),
5367 high_priority: Vec::new(),
5368 low_priority: VecDeque::new(),
5369 suspend_reason: None,
5370 worker: None,
5371 worker_item: None,
5372 global_error_context_ref_counts: BTreeMap::new(),
5373 interesting_tasks: 0,
5374 interesting_tasks_empty_waker: None,
5375 ready_for_concurrent_call_waker: None,
5376 }
5377 }
5378}
5379
5380impl ConcurrentState {
5381 pub(crate) fn take_fibers_and_futures(
5398 &mut self,
5399 fibers: &mut Vec<StoreFiber<'static>>,
5400 futures: &mut Vec<FuturesUnordered<HostTaskFuture>>,
5401 ) {
5402 for entry in self.table.get_mut().iter_mut() {
5403 if let Some(set) = entry.downcast_mut::<WaitableSet>() {
5404 for mode in mem::take(&mut set.waiting).into_values() {
5405 if let WaitMode::Fiber(fiber) = mode {
5406 fibers.push(fiber);
5407 }
5408 }
5409 } else if let Some(thread) = entry.downcast_mut::<GuestThread>() {
5410 if let GuestThreadState::Suspended(fiber) | GuestThreadState::Ready { fiber, .. } =
5411 mem::replace(&mut thread.state, GuestThreadState::Completed)
5412 {
5413 fibers.push(fiber);
5414 }
5415 }
5416 }
5417
5418 if let Some(fiber) = self.worker.take() {
5419 fibers.push(fiber);
5420 }
5421
5422 let mut handle_item = |item| match item {
5423 WorkItem::ResumeFiber(fiber) => {
5424 fibers.push(fiber);
5425 }
5426 WorkItem::PushFuture(future) => {
5427 self.futures
5428 .get_mut()
5429 .as_mut()
5430 .unwrap()
5431 .push(future.into_inner());
5432 }
5433 WorkItem::ResumeThread(..) | WorkItem::GuestCall(..) | WorkItem::WorkerFunction(..) => {
5434 }
5435 };
5436
5437 for item in mem::take(&mut self.high_priority) {
5438 handle_item(item);
5439 }
5440 for item in mem::take(&mut self.low_priority) {
5441 handle_item(item);
5442 }
5443
5444 if let Some(them) = self.futures.get_mut().take() {
5445 futures.push(them);
5446 }
5447 }
5448
5449 #[cfg(feature = "gc")]
5450 pub(crate) fn trace_fiber_roots(
5451 &mut self,
5452 modules: &ModuleRegistry,
5453 unwind: &dyn Unwind,
5454 gc_roots_list: &mut GcRootsList,
5455 ) {
5456 let ConcurrentState {
5457 table,
5458 worker,
5459 high_priority,
5460 low_priority,
5461
5462 futures: _,
5466
5467 worker_item: _,
5469 unforced_current_thread: _,
5470 suspend_reason: _,
5471 global_error_context_ref_counts: _,
5472 interesting_tasks: _,
5473 interesting_tasks_empty_waker: _,
5474 ready_for_concurrent_call_waker: _,
5475 } = self;
5476
5477 for entry in table.get_mut().iter_mut() {
5478 if let Some(set) = entry.downcast_mut::<WaitableSet>() {
5479 for mode in set.waiting.values_mut() {
5480 if let WaitMode::Fiber(fiber) = mode {
5481 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
5482 }
5483 }
5484 } else if let Some(thread) = entry.downcast_mut::<GuestThread>() {
5485 if let GuestThreadState::Suspended(fiber) | GuestThreadState::Ready { fiber, .. } =
5486 &mut thread.state
5487 {
5488 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
5489 }
5490 }
5491 }
5492
5493 if let Some(fiber) = worker {
5494 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
5495 }
5496
5497 let mut handle_item = |item: &mut WorkItem| match item {
5498 WorkItem::ResumeFiber(fiber) => {
5499 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
5500 }
5501 WorkItem::PushFuture(_future) => {
5502 }
5505 WorkItem::ResumeThread(..) | WorkItem::GuestCall(..) | WorkItem::WorkerFunction(..) => {
5506 }
5507 };
5508
5509 for item in high_priority {
5510 handle_item(item);
5511 }
5512 for item in low_priority {
5513 handle_item(item);
5514 }
5515 }
5516
5517 fn push<V: Send + Sync + 'static>(
5518 &mut self,
5519 value: V,
5520 ) -> Result<TableId<V>, ResourceTableError> {
5521 self.table.get_mut().push(value).map(TableId::from)
5522 }
5523
5524 fn get_mut<V: 'static>(&mut self, id: TableId<V>) -> Result<&mut V, ResourceTableError> {
5525 self.table.get_mut().get_mut(&Resource::from(id))
5526 }
5527
5528 pub fn add_child<T: 'static, U: 'static>(
5529 &mut self,
5530 child: TableId<T>,
5531 parent: TableId<U>,
5532 ) -> Result<(), ResourceTableError> {
5533 self.table
5534 .get_mut()
5535 .add_child(Resource::from(child), Resource::from(parent))
5536 }
5537
5538 pub fn remove_child<T: 'static, U: 'static>(
5539 &mut self,
5540 child: TableId<T>,
5541 parent: TableId<U>,
5542 ) -> Result<(), ResourceTableError> {
5543 self.table
5544 .get_mut()
5545 .remove_child(Resource::from(child), Resource::from(parent))
5546 }
5547
5548 fn delete<V: 'static>(&mut self, id: TableId<V>) -> Result<V, ResourceTableError> {
5549 self.table.get_mut().delete(Resource::from(id))
5550 }
5551
5552 fn push_future(&mut self, future: HostTaskFuture) {
5553 self.push_high_priority(WorkItem::PushFuture(AlwaysMut::new(future)));
5560 }
5561
5562 fn push_high_priority(&mut self, item: WorkItem) {
5563 log::trace!("push high priority: {item:?}");
5564 self.high_priority.push(item);
5565 }
5566
5567 fn push_low_priority(&mut self, item: WorkItem) {
5568 log::trace!("push low priority: {item:?}");
5569 self.low_priority.push_front(item);
5570 }
5571
5572 fn push_work_item(&mut self, item: WorkItem, high_priority: bool) {
5573 if high_priority {
5574 self.push_high_priority(item);
5575 } else {
5576 self.push_low_priority(item);
5577 }
5578 }
5579
5580 fn promote_instance_local_thread_work_item(
5581 &mut self,
5582 current_instance: RuntimeComponentInstanceIndex,
5583 ) -> bool {
5584 self.promote_work_items_matching(|item: &WorkItem| match item {
5585 WorkItem::ResumeThread(instance, _) | WorkItem::GuestCall(instance, _) => {
5586 *instance == current_instance
5587 }
5588 _ => false,
5589 })
5590 }
5591
5592 fn promote_thread_work_item(&mut self, thread: QualifiedThreadId) -> bool {
5593 self.promote_work_items_matching(|item: &WorkItem| match item {
5594 WorkItem::ResumeThread(_, t) | WorkItem::GuestCall(_, GuestCall { thread: t, .. }) => {
5595 *t == thread
5596 }
5597 _ => false,
5598 })
5599 }
5600
5601 fn promote_work_items_matching<F>(&mut self, mut predicate: F) -> bool
5602 where
5603 F: FnMut(&WorkItem) -> bool,
5604 {
5605 if self.high_priority.iter().any(&mut predicate) {
5609 true
5610 }
5611 else if let Some(idx) = self.low_priority.iter().position(&mut predicate) {
5614 let item = self.low_priority.remove(idx).unwrap();
5615 self.push_high_priority(item);
5616 true
5617 } else {
5618 false
5619 }
5620 }
5621
5622 fn check_blocking_for(&mut self, task: TableId<GuestTask>) -> Result<()> {
5623 if self.may_block(task)? {
5624 Ok(())
5625 } else {
5626 Err(Trap::CannotBlockSyncTask.into())
5627 }
5628 }
5629
5630 fn may_block(&mut self, task: TableId<GuestTask>) -> Result<bool> {
5631 let task = self.get_mut(task)?;
5632 Ok(task.async_function || task.returned_or_cancelled())
5633 }
5634
5635 pub fn call_context(&mut self, task: u32) -> Result<&mut CallContext> {
5641 let (task, is_host) = (task >> 1, task & 1 == 1);
5642 if is_host {
5643 let task: TableId<HostTask> = TableId::new(task);
5644 Ok(&mut self.get_mut(task)?.call_context)
5645 } else {
5646 let task: TableId<GuestTask> = TableId::new(task);
5647 Ok(&mut self.get_mut(task)?.call_context)
5648 }
5649 }
5650
5651 fn futures_mut(&mut self) -> Result<&mut FuturesUnordered<HostTaskFuture>> {
5652 match self.futures.get_mut().as_mut() {
5653 Some(f) => Ok(f),
5654 None => bail_bug!("futures field of concurrent state is currently taken"),
5655 }
5656 }
5657
5658 pub(crate) fn table(&mut self) -> &mut ResourceTable {
5659 self.table.get_mut()
5660 }
5661
5662 fn parent(&mut self, cur: CurrentThread) -> Option<CurrentThread> {
5664 let task = match cur {
5665 CurrentThread::GuestTask(task) => task,
5666 CurrentThread::Guest(thread) => thread.task,
5667 CurrentThread::Host(id) => {
5668 return Some(CurrentThread::GuestTask(self.get_mut(id).ok()?.caller));
5669 }
5670 CurrentThread::None => return None,
5671 };
5672 let task = self.get_mut(task).ok()?;
5673 Some(match task.caller {
5674 Caller::Host { caller, .. } => caller,
5675 Caller::Guest { thread } => thread.into(),
5676 })
5677 }
5678}
5679
5680fn for_any_lower<
5683 F: FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync,
5684>(
5685 fun: F,
5686) -> F {
5687 fun
5688}
5689
5690fn for_any_lift<
5692 F: FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
5693>(
5694 fun: F,
5695) -> F {
5696 fun
5697}
5698
5699fn check_ambient_store(id: StoreId) {
5700 let message = "\
5701 `Future`s which depend on asynchronous component tasks, streams, or \
5702 futures to complete may only be polled from the event loop of the \
5703 store to which they belong. Please use \
5704 `StoreContextMut::{run_concurrent,spawn}` to poll or await them.\
5705 ";
5706 tls::try_get(|store| {
5707 let matched = match store {
5708 tls::TryGet::Some(store) => store.id() == id,
5709 tls::TryGet::Taken | tls::TryGet::None => false,
5710 };
5711
5712 if !matched {
5713 panic!("{message}")
5714 }
5715 });
5716}
5717
5718fn check_recursive_run() {
5721 tls::try_get(|store| {
5722 if !matches!(store, tls::TryGet::None) {
5723 panic!("Recursive `StoreContextMut::run_concurrent` calls not supported")
5724 }
5725 });
5726}
5727
5728fn unpack_callback_code(code: u32) -> (u32, u32) {
5729 (code & 0xF, code >> 4)
5730}
5731
5732struct WaitableCheckParams {
5736 set: TableId<WaitableSet>,
5737 options: OptionsIndex,
5738 payload: u32,
5739}
5740
5741enum WaitableCheck {
5744 Wait,
5745 Poll,
5746}
5747
5748#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
5757pub struct GuestTaskId(TableId<GuestTask>);
5758
5759pub(crate) struct PreparedCall<R> {
5761 handle: Func,
5763 thread: QualifiedThreadId,
5765 param_count: usize,
5767 rx: oneshot::Receiver<LiftedResult>,
5770 runtime_instance: RuntimeInstance,
5772 _phantom: PhantomData<R>,
5773}
5774
5775impl<R> PreparedCall<R> {
5776 pub(crate) fn task_id(&self) -> TaskId {
5778 TaskId {
5779 task: self.thread.task,
5780 runtime_instance: self.runtime_instance,
5781 }
5782 }
5783}
5784
5785pub(crate) struct TaskId {
5787 task: TableId<GuestTask>,
5788 runtime_instance: RuntimeInstance,
5789}
5790
5791impl TaskId {
5792 pub(crate) fn host_future_dropped(&self, store: &mut StoreOpaque) -> Result<()> {
5798 let task = store.concurrent_state_mut()?.get_mut(self.task)?;
5799 let delete = if !task.already_lowered_parameters() {
5800 store.cancel_guest_subtask_without_lowered_parameters(
5801 self.runtime_instance,
5802 self.task,
5803 )?;
5804 true
5805 } else {
5806 task.host_future_state = HostFutureState::Dropped;
5807 task.ready_to_delete()
5808 };
5809 if delete {
5810 Waitable::Guest(self.task).delete_from(store.concurrent_state_mut()?)?
5811 }
5812 Ok(())
5813 }
5814}
5815
5816pub(crate) fn prepare_call<T, R>(
5822 mut store: StoreContextMut<T>,
5823 handle: Func,
5824 param_count: usize,
5825 host_future_present: bool,
5826 lower_params: impl FnOnce(Func, StoreContextMut<T>, &mut [MaybeUninit<ValRaw>]) -> Result<()>
5827 + Send
5828 + Sync
5829 + 'static,
5830 lift_result: impl FnOnce(Func, &mut StoreOpaque, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>>
5831 + Send
5832 + Sync
5833 + 'static,
5834) -> Result<PreparedCall<R>> {
5835 let (options, _flags, ty, raw_options) = handle.abi_info(store.0);
5836
5837 let instance = handle.instance().id().get(store.0);
5838 let options = &instance.component().env_component().options[options];
5839 let ty = &instance.component().types()[ty];
5840 let async_function = ty.async_;
5841 let task_return_type = ty.results;
5842 let component_instance = raw_options.instance;
5843 let callback = options.callback.map(|i| instance.runtime_callback(i));
5844 let memory = options
5845 .memory()
5846 .map(|i| instance.runtime_memory(i))
5847 .map(SendSyncPtr::new);
5848 let string_encoding = options.string_encoding;
5849 let token = StoreToken::new(store.as_context_mut());
5850 let caller = store.0.current_thread()?;
5851 let state = store.0.concurrent_state_mut()?;
5852
5853 let (tx, rx) = oneshot::channel();
5854
5855 let instance = handle.instance().runtime_instance(component_instance);
5856 let thread = GuestTask::new(
5857 state,
5858 Box::new(for_any_lower(move |store, params| {
5859 lower_params(handle, token.as_context_mut(store), params)
5860 })),
5861 LiftResult {
5862 lift: Box::new(for_any_lift(move |store, result| {
5863 lift_result(handle, store, result)
5864 })),
5865 ty: task_return_type,
5866 memory,
5867 string_encoding,
5868 },
5869 Caller::Host {
5870 tx: Some(tx),
5871 host_future_present,
5872 caller,
5873 },
5874 callback.map(|callback| {
5875 let callback = SendSyncPtr::new(callback);
5876 let instance = handle.instance();
5877 Box::new(move |store: &mut dyn VMStore, event, handle| {
5878 let store = token.as_context_mut(store);
5879 unsafe { instance.call_callback(store, callback, event, handle) }
5882 }) as CallbackFn
5883 }),
5884 instance,
5885 async_function,
5886 )?;
5887
5888 if !store.0.may_enter(instance)? {
5889 bail!(Trap::CannotEnterComponent);
5890 }
5891
5892 Ok(PreparedCall {
5893 handle,
5894 thread,
5895 param_count,
5896 runtime_instance: instance,
5897 rx,
5898 _phantom: PhantomData,
5899 })
5900}
5901
5902pub(crate) struct QueuedCall<R> {
5903 store: StoreId,
5904 task: TableId<GuestTask>,
5905 rx: oneshot::Receiver<LiftedResult>,
5906 _marker: PhantomData<fn() -> R>,
5907}
5908
5909impl<R> QueuedCall<R> {
5910 pub(crate) fn new<T: 'static>(
5917 mut store: StoreContextMut<T>,
5918 prepared: PreparedCall<R>,
5919 ) -> Result<QueuedCall<R>> {
5920 let PreparedCall {
5921 handle,
5922 thread,
5923 param_count,
5924 rx,
5925 ..
5926 } = prepared;
5927
5928 queue_call0(store.as_context_mut(), handle, thread, param_count)?;
5929
5930 Ok(QueuedCall {
5931 store: store.0.id(),
5932 task: thread.task,
5933 rx,
5934 _marker: PhantomData,
5935 })
5936 }
5937
5938 fn task(&self) -> GuestTaskId {
5939 GuestTaskId(self.task)
5940 }
5941}
5942
5943impl<R> Future for QueuedCall<R>
5944where
5945 R: 'static,
5946{
5947 type Output = Result<R>;
5948
5949 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
5950 check_ambient_store(self.store);
5951 Pin::new(&mut self.rx).poll(cx).map(|result| match result {
5952 Ok(r) => match r.downcast() {
5953 Ok(r) => Ok(*r),
5954 Err(_) => bail_bug!("wrong type of value produced"),
5955 },
5956 Err(oneshot::Canceled) => bail_bug!("channel erroneously dropped"),
5957 })
5958 }
5959}
5960
5961fn queue_call0<T: 'static>(
5964 store: StoreContextMut<T>,
5965 handle: Func,
5966 guest_thread: QualifiedThreadId,
5967 param_count: usize,
5968) -> Result<()> {
5969 let (_options, _, _ty, raw_options) = handle.abi_info(store.0);
5970 let is_concurrent = raw_options.async_;
5971 let callback = raw_options.callback;
5972 let instance = handle.instance();
5973 let callee = handle.lifted_core_func(store.0);
5974 let post_return = handle.post_return_core_func(store.0);
5975 let callback = callback.map(|i| {
5976 let instance = instance.id().get(store.0);
5977 SendSyncPtr::new(instance.runtime_callback(i))
5978 });
5979
5980 log::trace!("queueing call {guest_thread:?}");
5981
5982 unsafe {
5986 instance.queue_call(
5987 store,
5988 guest_thread,
5989 SendSyncPtr::new(callee),
5990 param_count,
5991 1,
5992 is_concurrent,
5993 callback,
5994 post_return.map(SendSyncPtr::new),
5995 )
5996 }
5997}