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: true,
4073 })?;
4074 break;
4075 } else if let GuestThreadState::Ready {
4076 cancellable: true, ..
4077 } = &thread_mut.state
4078 {
4079 concurrent_state.promote_thread_work_item(thread);
4082 let caller = store.current_guest_thread()?;
4083 store.suspend(SuspendReason::Yielding {
4084 thread: caller,
4085 cancellable: false,
4086 skip_may_block_check: true,
4088 })?;
4089 break;
4090 }
4091 }
4092
4093 needs_block = !store
4096 .concurrent_state_mut()?
4097 .get_mut(guest_task)?
4098 .returned_or_cancelled()
4099 } else {
4100 needs_block = false;
4101 }
4102 };
4103
4104 if needs_block {
4108 if async_ {
4109 return Ok(BLOCKED);
4110 }
4111
4112 store.wait_for_event(waitable)?;
4116
4117 }
4119
4120 let event = waitable.take_event(store.concurrent_state_mut()?)?;
4121 if let Some(Event::Subtask {
4122 status: status @ (Status::Returned | Status::ReturnCancelled),
4123 }) = event
4124 {
4125 Ok(status as u32)
4126 } else {
4127 bail!(Trap::SubtaskCancelAfterTerminal);
4128 }
4129 }
4130}
4131
4132pub trait VMComponentAsyncStore {
4140 unsafe fn prepare_call(
4146 &mut self,
4147 instance: Instance,
4148 memory: *mut VMMemoryDefinition,
4149 start: NonNull<VMFuncRef>,
4150 return_: NonNull<VMFuncRef>,
4151 caller_instance: RuntimeComponentInstanceIndex,
4152 callee_instance: RuntimeComponentInstanceIndex,
4153 task_return_type: TypeTupleIndex,
4154 callee_async: bool,
4155 string_encoding: StringEncoding,
4156 result_count: u32,
4157 storage: *mut ValRaw,
4158 storage_len: usize,
4159 ) -> Result<()>;
4160
4161 unsafe fn sync_start(
4164 &mut self,
4165 instance: Instance,
4166 callback: *mut VMFuncRef,
4167 callee: NonNull<VMFuncRef>,
4168 param_count: u32,
4169 storage: *mut MaybeUninit<ValRaw>,
4170 storage_len: usize,
4171 ) -> Result<()>;
4172
4173 unsafe fn async_start(
4176 &mut self,
4177 instance: Instance,
4178 callback: *mut VMFuncRef,
4179 post_return: *mut VMFuncRef,
4180 callee: NonNull<VMFuncRef>,
4181 param_count: u32,
4182 result_count: u32,
4183 flags: u32,
4184 ) -> Result<u32>;
4185
4186 fn future_write(
4188 &mut self,
4189 instance: Instance,
4190 caller: RuntimeComponentInstanceIndex,
4191 ty: TypeFutureTableIndex,
4192 options: OptionsIndex,
4193 future: u32,
4194 address: u32,
4195 ) -> Result<u32>;
4196
4197 fn future_read(
4199 &mut self,
4200 instance: Instance,
4201 caller: RuntimeComponentInstanceIndex,
4202 ty: TypeFutureTableIndex,
4203 options: OptionsIndex,
4204 future: u32,
4205 address: u32,
4206 ) -> Result<u32>;
4207
4208 fn future_drop_writable(
4210 &mut self,
4211 instance: Instance,
4212 ty: TypeFutureTableIndex,
4213 writer: u32,
4214 ) -> Result<()>;
4215
4216 fn stream_write(
4218 &mut self,
4219 instance: Instance,
4220 caller: RuntimeComponentInstanceIndex,
4221 ty: TypeStreamTableIndex,
4222 options: OptionsIndex,
4223 stream: u32,
4224 address: u32,
4225 count: u32,
4226 ) -> Result<u32>;
4227
4228 fn stream_read(
4230 &mut self,
4231 instance: Instance,
4232 caller: RuntimeComponentInstanceIndex,
4233 ty: TypeStreamTableIndex,
4234 options: OptionsIndex,
4235 stream: u32,
4236 address: u32,
4237 count: u32,
4238 ) -> Result<u32>;
4239
4240 fn flat_stream_write(
4243 &mut self,
4244 instance: Instance,
4245 caller: RuntimeComponentInstanceIndex,
4246 ty: TypeStreamTableIndex,
4247 options: OptionsIndex,
4248 payload_size: u32,
4249 payload_align: u32,
4250 stream: u32,
4251 address: u32,
4252 count: u32,
4253 ) -> Result<u32>;
4254
4255 fn flat_stream_read(
4258 &mut self,
4259 instance: Instance,
4260 caller: RuntimeComponentInstanceIndex,
4261 ty: TypeStreamTableIndex,
4262 options: OptionsIndex,
4263 payload_size: u32,
4264 payload_align: u32,
4265 stream: u32,
4266 address: u32,
4267 count: u32,
4268 ) -> Result<u32>;
4269
4270 fn stream_drop_writable(
4272 &mut self,
4273 instance: Instance,
4274 ty: TypeStreamTableIndex,
4275 writer: u32,
4276 ) -> Result<()>;
4277
4278 fn error_context_debug_message(
4280 &mut self,
4281 instance: Instance,
4282 ty: TypeComponentLocalErrorContextTableIndex,
4283 options: OptionsIndex,
4284 err_ctx_handle: u32,
4285 debug_msg_address: u32,
4286 ) -> Result<()>;
4287
4288 fn thread_new_indirect(
4290 &mut self,
4291 instance: Instance,
4292 caller: RuntimeComponentInstanceIndex,
4293 func_ty_idx: TypeFuncIndex,
4294 start_func_table_idx: RuntimeTableIndex,
4295 start_func_idx: u32,
4296 context: i32,
4297 ) -> Result<u32>;
4298}
4299
4300impl<T: 'static> VMComponentAsyncStore for StoreInner<T> {
4302 unsafe fn prepare_call(
4303 &mut self,
4304 instance: Instance,
4305 memory: *mut VMMemoryDefinition,
4306 start: NonNull<VMFuncRef>,
4307 return_: NonNull<VMFuncRef>,
4308 caller_instance: RuntimeComponentInstanceIndex,
4309 callee_instance: RuntimeComponentInstanceIndex,
4310 task_return_type: TypeTupleIndex,
4311 callee_async: bool,
4312 string_encoding: StringEncoding,
4313 result_count_or_max_if_async: u32,
4314 storage: *mut ValRaw,
4315 storage_len: usize,
4316 ) -> Result<()> {
4317 let params = unsafe { core::slice::from_raw_parts(storage, storage_len) }.to_vec();
4321
4322 unsafe {
4323 instance.prepare_call(
4324 StoreContextMut(self),
4325 start,
4326 return_,
4327 caller_instance,
4328 callee_instance,
4329 task_return_type,
4330 callee_async,
4331 memory,
4332 string_encoding,
4333 match result_count_or_max_if_async {
4334 PREPARE_ASYNC_NO_RESULT => CallerInfo::Async {
4335 params,
4336 has_result: false,
4337 },
4338 PREPARE_ASYNC_WITH_RESULT => CallerInfo::Async {
4339 params,
4340 has_result: true,
4341 },
4342 result_count => CallerInfo::Sync {
4343 params,
4344 result_count,
4345 },
4346 },
4347 )
4348 }
4349 }
4350
4351 unsafe fn sync_start(
4352 &mut self,
4353 instance: Instance,
4354 callback: *mut VMFuncRef,
4355 callee: NonNull<VMFuncRef>,
4356 param_count: u32,
4357 storage: *mut MaybeUninit<ValRaw>,
4358 storage_len: usize,
4359 ) -> Result<()> {
4360 unsafe {
4361 instance
4362 .start_call(
4363 StoreContextMut(self),
4364 callback,
4365 ptr::null_mut(),
4366 callee,
4367 param_count,
4368 1,
4369 START_FLAG_ASYNC_CALLEE,
4370 Some(core::slice::from_raw_parts_mut(storage, storage_len)),
4374 )
4375 .map(drop)
4376 }
4377 }
4378
4379 unsafe fn async_start(
4380 &mut self,
4381 instance: Instance,
4382 callback: *mut VMFuncRef,
4383 post_return: *mut VMFuncRef,
4384 callee: NonNull<VMFuncRef>,
4385 param_count: u32,
4386 result_count: u32,
4387 flags: u32,
4388 ) -> Result<u32> {
4389 unsafe {
4390 instance.start_call(
4391 StoreContextMut(self),
4392 callback,
4393 post_return,
4394 callee,
4395 param_count,
4396 result_count,
4397 flags,
4398 None,
4399 )
4400 }
4401 }
4402
4403 fn future_write(
4404 &mut self,
4405 instance: Instance,
4406 caller: RuntimeComponentInstanceIndex,
4407 ty: TypeFutureTableIndex,
4408 options: OptionsIndex,
4409 future: u32,
4410 address: u32,
4411 ) -> Result<u32> {
4412 instance
4413 .guest_write(
4414 StoreContextMut(self),
4415 caller,
4416 TransmitIndex::Future(ty),
4417 options,
4418 None,
4419 future,
4420 address,
4421 1,
4422 )
4423 .map(|result| result.encode())
4424 }
4425
4426 fn future_read(
4427 &mut self,
4428 instance: Instance,
4429 caller: RuntimeComponentInstanceIndex,
4430 ty: TypeFutureTableIndex,
4431 options: OptionsIndex,
4432 future: u32,
4433 address: u32,
4434 ) -> Result<u32> {
4435 instance
4436 .guest_read(
4437 StoreContextMut(self),
4438 caller,
4439 TransmitIndex::Future(ty),
4440 options,
4441 None,
4442 future,
4443 address,
4444 1,
4445 )
4446 .map(|result| result.encode())
4447 }
4448
4449 fn stream_write(
4450 &mut self,
4451 instance: Instance,
4452 caller: RuntimeComponentInstanceIndex,
4453 ty: TypeStreamTableIndex,
4454 options: OptionsIndex,
4455 stream: u32,
4456 address: u32,
4457 count: u32,
4458 ) -> Result<u32> {
4459 instance
4460 .guest_write(
4461 StoreContextMut(self),
4462 caller,
4463 TransmitIndex::Stream(ty),
4464 options,
4465 None,
4466 stream,
4467 address,
4468 count,
4469 )
4470 .map(|result| result.encode())
4471 }
4472
4473 fn stream_read(
4474 &mut self,
4475 instance: Instance,
4476 caller: RuntimeComponentInstanceIndex,
4477 ty: TypeStreamTableIndex,
4478 options: OptionsIndex,
4479 stream: u32,
4480 address: u32,
4481 count: u32,
4482 ) -> Result<u32> {
4483 instance
4484 .guest_read(
4485 StoreContextMut(self),
4486 caller,
4487 TransmitIndex::Stream(ty),
4488 options,
4489 None,
4490 stream,
4491 address,
4492 count,
4493 )
4494 .map(|result| result.encode())
4495 }
4496
4497 fn future_drop_writable(
4498 &mut self,
4499 instance: Instance,
4500 ty: TypeFutureTableIndex,
4501 writer: u32,
4502 ) -> Result<()> {
4503 instance.guest_drop_writable(self, TransmitIndex::Future(ty), writer)
4504 }
4505
4506 fn flat_stream_write(
4507 &mut self,
4508 instance: Instance,
4509 caller: RuntimeComponentInstanceIndex,
4510 ty: TypeStreamTableIndex,
4511 options: OptionsIndex,
4512 payload_size: u32,
4513 payload_align: u32,
4514 stream: u32,
4515 address: u32,
4516 count: u32,
4517 ) -> Result<u32> {
4518 instance
4519 .guest_write(
4520 StoreContextMut(self),
4521 caller,
4522 TransmitIndex::Stream(ty),
4523 options,
4524 Some(FlatAbi {
4525 size: payload_size,
4526 align: payload_align,
4527 }),
4528 stream,
4529 address,
4530 count,
4531 )
4532 .map(|result| result.encode())
4533 }
4534
4535 fn flat_stream_read(
4536 &mut self,
4537 instance: Instance,
4538 caller: RuntimeComponentInstanceIndex,
4539 ty: TypeStreamTableIndex,
4540 options: OptionsIndex,
4541 payload_size: u32,
4542 payload_align: u32,
4543 stream: u32,
4544 address: u32,
4545 count: u32,
4546 ) -> Result<u32> {
4547 instance
4548 .guest_read(
4549 StoreContextMut(self),
4550 caller,
4551 TransmitIndex::Stream(ty),
4552 options,
4553 Some(FlatAbi {
4554 size: payload_size,
4555 align: payload_align,
4556 }),
4557 stream,
4558 address,
4559 count,
4560 )
4561 .map(|result| result.encode())
4562 }
4563
4564 fn stream_drop_writable(
4565 &mut self,
4566 instance: Instance,
4567 ty: TypeStreamTableIndex,
4568 writer: u32,
4569 ) -> Result<()> {
4570 instance.guest_drop_writable(self, TransmitIndex::Stream(ty), writer)
4571 }
4572
4573 fn error_context_debug_message(
4574 &mut self,
4575 instance: Instance,
4576 ty: TypeComponentLocalErrorContextTableIndex,
4577 options: OptionsIndex,
4578 err_ctx_handle: u32,
4579 debug_msg_address: u32,
4580 ) -> Result<()> {
4581 instance.error_context_debug_message(
4582 StoreContextMut(self),
4583 ty,
4584 options,
4585 err_ctx_handle,
4586 debug_msg_address,
4587 )
4588 }
4589
4590 fn thread_new_indirect(
4591 &mut self,
4592 instance: Instance,
4593 caller: RuntimeComponentInstanceIndex,
4594 func_ty_idx: TypeFuncIndex,
4595 start_func_table_idx: RuntimeTableIndex,
4596 start_func_idx: u32,
4597 context: i32,
4598 ) -> Result<u32> {
4599 instance.thread_new_indirect(
4600 StoreContextMut(self),
4601 caller,
4602 func_ty_idx,
4603 start_func_table_idx,
4604 start_func_idx,
4605 context,
4606 )
4607 }
4608}
4609
4610type HostTaskFuture = Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>;
4611
4612pub(crate) struct HostTask {
4616 common: WaitableCommon,
4617
4618 caller: TableId<GuestTask>,
4625
4626 call_context: CallContext,
4629
4630 state: HostTaskState,
4631}
4632
4633enum HostTaskState {
4634 CalleeStarted,
4639
4640 CalleeRunning(JoinHandle),
4645
4646 CalleeFinished(LiftedResult),
4650
4651 CalleeDone { cancelled: bool },
4654}
4655
4656impl HostTask {
4657 fn new(caller: TableId<GuestTask>, state: HostTaskState) -> Self {
4658 Self {
4659 common: WaitableCommon::default(),
4660 call_context: CallContext::default(),
4661 caller,
4662 state,
4663 }
4664 }
4665}
4666
4667impl TableDebug for HostTask {
4668 fn type_name() -> &'static str {
4669 "HostTask"
4670 }
4671}
4672
4673type CallbackFn = Box<dyn Fn(&mut dyn VMStore, Event, u32) -> Result<u32> + Send + Sync + 'static>;
4674
4675enum Caller {
4677 Host {
4679 tx: Option<oneshot::Sender<LiftedResult>>,
4681 host_future_present: bool,
4684 caller: CurrentThread,
4688 },
4689 Guest {
4691 thread: QualifiedThreadId,
4693 },
4694}
4695
4696struct LiftResult {
4699 lift: RawLift,
4700 ty: TypeTupleIndex,
4701 memory: Option<SendSyncPtr<VMMemoryDefinition>>,
4702 string_encoding: StringEncoding,
4703}
4704
4705#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
4710pub(crate) struct QualifiedThreadId {
4711 task: TableId<GuestTask>,
4712 thread: TableId<GuestThread>,
4713}
4714
4715impl QualifiedThreadId {
4716 fn qualify(
4717 state: &mut ConcurrentState,
4718 thread: TableId<GuestThread>,
4719 ) -> Result<QualifiedThreadId> {
4720 Ok(QualifiedThreadId {
4721 task: state.get_mut(thread)?.parent_task,
4722 thread,
4723 })
4724 }
4725}
4726
4727impl fmt::Debug for QualifiedThreadId {
4728 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4729 f.debug_tuple("QualifiedThreadId")
4730 .field(&self.task.rep())
4731 .field(&self.thread.rep())
4732 .finish()
4733 }
4734}
4735
4736enum GuestThreadState {
4737 NotStartedImplicit,
4738 NotStartedExplicit(
4739 Box<dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync>,
4740 ),
4741 Running,
4742 Suspended(StoreFiber<'static>),
4743 Ready {
4744 fiber: StoreFiber<'static>,
4745 cancellable: bool,
4746 },
4747 Completed,
4748}
4749pub struct GuestThread {
4750 context: [u32; NUM_COMPONENT_CONTEXT_SLOTS],
4753 parent_task: TableId<GuestTask>,
4755 wake_on_cancel: Option<TableId<WaitableSet>>,
4758 state: GuestThreadState,
4760 instance_rep: Option<u32>,
4763 sync_call_set: TableId<WaitableSet>,
4765}
4766
4767impl GuestThread {
4768 fn from_instance(
4771 state: Pin<&mut ComponentInstance>,
4772 caller_instance: RuntimeComponentInstanceIndex,
4773 guest_thread: u32,
4774 ) -> Result<TableId<Self>> {
4775 let rep = state.instance_states().0[caller_instance]
4776 .thread_handle_table()
4777 .guest_thread_rep(guest_thread)?;
4778 Ok(TableId::new(rep))
4779 }
4780
4781 fn new_implicit(state: &mut ConcurrentState, parent_task: TableId<GuestTask>) -> Result<Self> {
4782 let sync_call_set = state.push(WaitableSet {
4783 is_sync_call_set: true,
4784 ..WaitableSet::default()
4785 })?;
4786 Ok(Self {
4787 context: [0; NUM_COMPONENT_CONTEXT_SLOTS],
4788 parent_task,
4789 wake_on_cancel: None,
4790 state: GuestThreadState::NotStartedImplicit,
4791 instance_rep: None,
4792 sync_call_set,
4793 })
4794 }
4795
4796 fn new_explicit(
4797 state: &mut ConcurrentState,
4798 parent_task: TableId<GuestTask>,
4799 start_func: Box<
4800 dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync,
4801 >,
4802 ) -> Result<Self> {
4803 let sync_call_set = state.push(WaitableSet {
4804 is_sync_call_set: true,
4805 ..WaitableSet::default()
4806 })?;
4807 Ok(Self {
4808 context: [0; NUM_COMPONENT_CONTEXT_SLOTS],
4809 parent_task,
4810 wake_on_cancel: None,
4811 state: GuestThreadState::NotStartedExplicit(start_func),
4812 instance_rep: None,
4813 sync_call_set,
4814 })
4815 }
4816}
4817
4818impl TableDebug for GuestThread {
4819 fn type_name() -> &'static str {
4820 "GuestThread"
4821 }
4822}
4823
4824enum SyncResult {
4825 NotProduced,
4826 Produced(Option<ValRaw>),
4827 Taken,
4828}
4829
4830impl SyncResult {
4831 fn take(&mut self) -> Result<Option<Option<ValRaw>>> {
4832 Ok(match mem::replace(self, SyncResult::Taken) {
4833 SyncResult::NotProduced => None,
4834 SyncResult::Produced(val) => Some(val),
4835 SyncResult::Taken => {
4836 bail_bug!("attempted to take a synchronous result that was already taken")
4837 }
4838 })
4839 }
4840}
4841
4842#[derive(Debug)]
4843enum HostFutureState {
4844 NotApplicable,
4845 Live,
4846 Dropped,
4847}
4848
4849pub(crate) struct GuestTask {
4851 common: WaitableCommon,
4853 lower_params: Option<RawLower>,
4855 lift_result: Option<LiftResult>,
4857 result: Option<LiftedResult>,
4860 callback: Option<CallbackFn>,
4863 caller: Caller,
4865 call_context: CallContext,
4870 sync_result: SyncResult,
4873 cancel_sent: bool,
4876 starting_sent: bool,
4879 instance: RuntimeInstance,
4886 event: Option<Event>,
4889 exited: bool,
4891 threads: HashSet<TableId<GuestThread>>,
4893 host_future_state: HostFutureState,
4896 async_function: bool,
4899
4900 decremented_interesting_task_count: bool,
4901}
4902
4903impl GuestTask {
4904 fn already_lowered_parameters(&self) -> bool {
4905 self.lower_params.is_none()
4907 }
4908
4909 fn returned_or_cancelled(&self) -> bool {
4910 self.lift_result.is_none()
4912 }
4913
4914 fn ready_to_delete(&self) -> bool {
4915 let threads_completed = self.threads.is_empty();
4916 let has_sync_result = matches!(self.sync_result, SyncResult::Produced(_));
4917 let pending_completion_event = matches!(
4918 self.common.event,
4919 Some(Event::Subtask {
4920 status: Status::Returned | Status::ReturnCancelled
4921 })
4922 );
4923 let ready = threads_completed
4924 && !has_sync_result
4925 && !pending_completion_event
4926 && !matches!(self.host_future_state, HostFutureState::Live);
4927 log::trace!(
4928 "ready to delete? {ready} (threads_completed: {}, has_sync_result: {}, pending_completion_event: {}, host_future_state: {:?})",
4929 threads_completed,
4930 has_sync_result,
4931 pending_completion_event,
4932 self.host_future_state
4933 );
4934 ready
4935 }
4936
4937 fn new(
4938 state: &mut ConcurrentState,
4939 lower_params: RawLower,
4940 lift_result: LiftResult,
4941 caller: Caller,
4942 callback: Option<CallbackFn>,
4943 instance: RuntimeInstance,
4944 async_function: bool,
4945 ) -> Result<QualifiedThreadId> {
4946 let host_future_state = match &caller {
4947 Caller::Guest { .. } => HostFutureState::NotApplicable,
4948 Caller::Host {
4949 host_future_present,
4950 ..
4951 } => {
4952 if *host_future_present {
4953 HostFutureState::Live
4954 } else {
4955 HostFutureState::NotApplicable
4956 }
4957 }
4958 };
4959 let task = state.push(Self {
4960 common: WaitableCommon::default(),
4961 lower_params: Some(lower_params),
4962 lift_result: Some(lift_result),
4963 result: None,
4964 callback,
4965 caller,
4966 call_context: CallContext::default(),
4967 sync_result: SyncResult::NotProduced,
4968 cancel_sent: false,
4969 starting_sent: false,
4970 instance,
4971 event: None,
4972 exited: false,
4973 threads: HashSet::new(),
4974 host_future_state,
4975 async_function,
4976 decremented_interesting_task_count: false,
4977 })?;
4978 let new_thread = GuestThread::new_implicit(state, task)?;
4979 let thread = state.push(new_thread)?;
4980 state.get_mut(task)?.threads.insert(thread);
4981 state.interesting_tasks += 1;
4982 Ok(QualifiedThreadId { task, thread })
4983 }
4984}
4985
4986impl TableDebug for GuestTask {
4987 fn type_name() -> &'static str {
4988 "GuestTask"
4989 }
4990}
4991
4992#[derive(Default)]
4994struct WaitableCommon {
4995 event: Option<Event>,
4997 set: Option<TableId<WaitableSet>>,
4999 handle: Option<u32>,
5001}
5002
5003#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
5005enum Waitable {
5006 Host(TableId<HostTask>),
5008 Guest(TableId<GuestTask>),
5010 Transmit(TableId<TransmitHandle>),
5012}
5013
5014impl Waitable {
5015 fn from_instance(
5018 state: Pin<&mut ComponentInstance>,
5019 caller_instance: RuntimeComponentInstanceIndex,
5020 waitable: u32,
5021 ) -> Result<Self> {
5022 use crate::runtime::vm::component::Waitable;
5023
5024 let (waitable, kind) = state.instance_states().0[caller_instance]
5025 .handle_table()
5026 .waitable_rep(waitable)?;
5027
5028 Ok(match kind {
5029 Waitable::Subtask { is_host: true } => Self::Host(TableId::new(waitable)),
5030 Waitable::Subtask { is_host: false } => Self::Guest(TableId::new(waitable)),
5031 Waitable::Stream | Waitable::Future => Self::Transmit(TableId::new(waitable)),
5032 })
5033 }
5034
5035 fn rep(&self) -> u32 {
5037 match self {
5038 Self::Host(id) => id.rep(),
5039 Self::Guest(id) => id.rep(),
5040 Self::Transmit(id) => id.rep(),
5041 }
5042 }
5043
5044 fn join(&self, state: &mut ConcurrentState, set: Option<TableId<WaitableSet>>) -> Result<()> {
5048 log::trace!("waitable {self:?} join set {set:?}");
5049
5050 let old = mem::replace(&mut self.common(state)?.set, set);
5051
5052 if let Some(old) = old {
5053 match *self {
5054 Waitable::Host(id) => state.remove_child(id, old),
5055 Waitable::Guest(id) => state.remove_child(id, old),
5056 Waitable::Transmit(id) => state.remove_child(id, old),
5057 }?;
5058
5059 state.get_mut(old)?.ready.remove(self);
5060 }
5061
5062 if let Some(set) = set {
5063 match *self {
5064 Waitable::Host(id) => state.add_child(id, set),
5065 Waitable::Guest(id) => state.add_child(id, set),
5066 Waitable::Transmit(id) => state.add_child(id, set),
5067 }?;
5068
5069 if self.common(state)?.event.is_some() {
5070 self.mark_ready(state)?;
5071 }
5072 }
5073
5074 Ok(())
5075 }
5076
5077 fn common<'a>(&self, state: &'a mut ConcurrentState) -> Result<&'a mut WaitableCommon> {
5079 Ok(match self {
5080 Self::Host(id) => &mut state.get_mut(*id)?.common,
5081 Self::Guest(id) => &mut state.get_mut(*id)?.common,
5082 Self::Transmit(id) => &mut state.get_mut(*id)?.common,
5083 })
5084 }
5085
5086 fn trap_if_in_waitable_set(&self, state: &mut ConcurrentState) -> Result<()> {
5092 if self.common(state)?.set.is_some() {
5093 bail!(Trap::WaitableSyncAndAsync);
5094 }
5095 Ok(())
5096 }
5097
5098 fn set_event(&self, state: &mut ConcurrentState, event: Option<Event>) -> Result<()> {
5102 log::trace!("set event for {self:?}: {event:?}");
5103 self.common(state)?.event = event;
5104 self.mark_ready(state)
5105 }
5106
5107 fn take_event(&self, state: &mut ConcurrentState) -> Result<Option<Event>> {
5109 let common = self.common(state)?;
5110 let event = common.event.take();
5111 if let Some(set) = self.common(state)?.set {
5112 state.get_mut(set)?.ready.remove(self);
5113 }
5114
5115 Ok(event)
5116 }
5117
5118 fn mark_ready(&self, state: &mut ConcurrentState) -> Result<()> {
5122 if let Some(set) = self.common(state)?.set {
5123 state.get_mut(set)?.ready.insert(*self);
5124 if let Some((thread, mode)) = state.get_mut(set)?.waiting.pop_first() {
5125 let wake_on_cancel = state.get_mut(thread.thread)?.wake_on_cancel.take();
5126 assert!(wake_on_cancel.is_none() || wake_on_cancel == Some(set));
5127
5128 let item = match mode {
5129 WaitMode::Fiber(fiber) => WorkItem::ResumeFiber(fiber),
5130 WaitMode::Callback(instance) => WorkItem::GuestCall(
5131 state.get_mut(thread.task)?.instance.index,
5132 GuestCall {
5133 thread,
5134 kind: GuestCallKind::DeliverEvent {
5135 instance,
5136 set: Some(set),
5137 },
5138 },
5139 ),
5140 };
5141 state.push_high_priority(item);
5142 }
5143 }
5144 Ok(())
5145 }
5146
5147 fn delete_from(&self, state: &mut ConcurrentState) -> Result<()> {
5149 match self {
5150 Self::Host(task) => {
5151 log::trace!("delete host task {task:?}");
5152 state.delete(*task)?;
5153 }
5154 Self::Guest(task) => {
5155 log::trace!("delete guest task {task:?}");
5156 let task = state.delete(*task)?;
5157
5158 debug_assert!(task.decremented_interesting_task_count);
5165 }
5166 Self::Transmit(task) => {
5167 state.delete(*task)?;
5168 }
5169 }
5170
5171 Ok(())
5172 }
5173}
5174
5175impl fmt::Debug for Waitable {
5176 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5177 match self {
5178 Self::Host(id) => write!(f, "{id:?}"),
5179 Self::Guest(id) => write!(f, "{id:?}"),
5180 Self::Transmit(id) => write!(f, "{id:?}"),
5181 }
5182 }
5183}
5184
5185#[derive(Default)]
5187struct WaitableSet {
5188 ready: BTreeSet<Waitable>,
5190 waiting: BTreeMap<QualifiedThreadId, WaitMode>,
5192 is_sync_call_set: bool,
5195}
5196
5197impl TableDebug for WaitableSet {
5198 fn type_name() -> &'static str {
5199 "WaitableSet"
5200 }
5201}
5202
5203type RawLower =
5205 Box<dyn FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync>;
5206
5207type RawLift = Box<
5209 dyn FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
5210>;
5211
5212type LiftedResult = Box<dyn Any + Send + Sync>;
5216
5217struct DummyResult;
5220
5221#[derive(Default)]
5223pub struct ConcurrentInstanceState {
5224 backpressure: u16,
5226 do_not_enter: bool,
5228 pending: BTreeMap<QualifiedThreadId, GuestCallKind>,
5231}
5232
5233impl ConcurrentInstanceState {
5234 pub fn pending_is_empty(&self) -> bool {
5235 self.pending.is_empty()
5236 }
5237}
5238
5239#[derive(Debug, Copy, Clone)]
5240pub(crate) enum CurrentThread {
5241 Guest(QualifiedThreadId),
5244 Host(TableId<HostTask>),
5246 GuestTask(TableId<GuestTask>),
5250 None,
5252}
5253
5254impl CurrentThread {
5255 fn guest(&self) -> Option<&QualifiedThreadId> {
5256 match self {
5257 Self::Guest(id) => Some(id),
5258 _ => None,
5259 }
5260 }
5261
5262 fn guest_task(&self) -> Option<TableId<GuestTask>> {
5263 match self {
5264 Self::Guest(id) => Some(id.task),
5265 Self::GuestTask(id) => Some(*id),
5266 _ => None,
5267 }
5268 }
5269
5270 fn host(&self) -> Option<TableId<HostTask>> {
5271 match self {
5272 Self::Host(id) => Some(*id),
5273 _ => None,
5274 }
5275 }
5276
5277 fn is_none(&self) -> bool {
5278 matches!(self, Self::None)
5279 }
5280}
5281
5282impl From<QualifiedThreadId> for CurrentThread {
5283 fn from(id: QualifiedThreadId) -> Self {
5284 Self::Guest(id)
5285 }
5286}
5287
5288impl From<TableId<HostTask>> for CurrentThread {
5289 fn from(id: TableId<HostTask>) -> Self {
5290 Self::Host(id)
5291 }
5292}
5293
5294pub struct ConcurrentState {
5296 unforced_current_thread: CurrentThread,
5302
5303 futures: AlwaysMut<Option<FuturesUnordered<HostTaskFuture>>>,
5308 table: AlwaysMut<ResourceTable>,
5310 high_priority: Vec<WorkItem>,
5312 low_priority: VecDeque<WorkItem>,
5314 suspend_reason: Option<SuspendReason>,
5318 worker: Option<StoreFiber<'static>>,
5322 worker_item: Option<WorkerItem>,
5324
5325 global_error_context_ref_counts:
5338 BTreeMap<TypeComponentGlobalErrorContextTableIndex, GlobalErrorContextRefCount>,
5339
5340 interesting_tasks: usize,
5353
5354 interesting_tasks_empty_waker: Option<Waker>,
5358
5359 ready_for_concurrent_call_waker: Option<Waker>,
5364}
5365
5366impl Default for ConcurrentState {
5367 fn default() -> Self {
5368 Self {
5369 unforced_current_thread: CurrentThread::None,
5370 table: AlwaysMut::new(ResourceTable::new()),
5371 futures: AlwaysMut::new(Some(FuturesUnordered::new())),
5372 high_priority: Vec::new(),
5373 low_priority: VecDeque::new(),
5374 suspend_reason: None,
5375 worker: None,
5376 worker_item: None,
5377 global_error_context_ref_counts: BTreeMap::new(),
5378 interesting_tasks: 0,
5379 interesting_tasks_empty_waker: None,
5380 ready_for_concurrent_call_waker: None,
5381 }
5382 }
5383}
5384
5385impl ConcurrentState {
5386 pub(crate) fn take_fibers_and_futures(
5403 &mut self,
5404 fibers: &mut Vec<StoreFiber<'static>>,
5405 futures: &mut Vec<FuturesUnordered<HostTaskFuture>>,
5406 ) {
5407 for entry in self.table.get_mut().iter_mut() {
5408 if let Some(set) = entry.downcast_mut::<WaitableSet>() {
5409 for mode in mem::take(&mut set.waiting).into_values() {
5410 if let WaitMode::Fiber(fiber) = mode {
5411 fibers.push(fiber);
5412 }
5413 }
5414 } else if let Some(thread) = entry.downcast_mut::<GuestThread>() {
5415 if let GuestThreadState::Suspended(fiber) | GuestThreadState::Ready { fiber, .. } =
5416 mem::replace(&mut thread.state, GuestThreadState::Completed)
5417 {
5418 fibers.push(fiber);
5419 }
5420 }
5421 }
5422
5423 if let Some(fiber) = self.worker.take() {
5424 fibers.push(fiber);
5425 }
5426
5427 let mut handle_item = |item| match item {
5428 WorkItem::ResumeFiber(fiber) => {
5429 fibers.push(fiber);
5430 }
5431 WorkItem::PushFuture(future) => {
5432 self.futures
5433 .get_mut()
5434 .as_mut()
5435 .unwrap()
5436 .push(future.into_inner());
5437 }
5438 WorkItem::ResumeThread(..) | WorkItem::GuestCall(..) | WorkItem::WorkerFunction(..) => {
5439 }
5440 };
5441
5442 for item in mem::take(&mut self.high_priority) {
5443 handle_item(item);
5444 }
5445 for item in mem::take(&mut self.low_priority) {
5446 handle_item(item);
5447 }
5448
5449 if let Some(them) = self.futures.get_mut().take() {
5450 futures.push(them);
5451 }
5452 }
5453
5454 #[cfg(feature = "gc")]
5455 pub(crate) fn trace_fiber_roots(
5456 &mut self,
5457 modules: &ModuleRegistry,
5458 unwind: &dyn Unwind,
5459 gc_roots_list: &mut GcRootsList,
5460 ) {
5461 let ConcurrentState {
5462 table,
5463 worker,
5464 high_priority,
5465 low_priority,
5466
5467 futures: _,
5471
5472 worker_item: _,
5474 unforced_current_thread: _,
5475 suspend_reason: _,
5476 global_error_context_ref_counts: _,
5477 interesting_tasks: _,
5478 interesting_tasks_empty_waker: _,
5479 ready_for_concurrent_call_waker: _,
5480 } = self;
5481
5482 for entry in table.get_mut().iter_mut() {
5483 if let Some(set) = entry.downcast_mut::<WaitableSet>() {
5484 for mode in set.waiting.values_mut() {
5485 if let WaitMode::Fiber(fiber) = mode {
5486 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
5487 }
5488 }
5489 } else if let Some(thread) = entry.downcast_mut::<GuestThread>() {
5490 if let GuestThreadState::Suspended(fiber) | GuestThreadState::Ready { fiber, .. } =
5491 &mut thread.state
5492 {
5493 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
5494 }
5495 }
5496 }
5497
5498 if let Some(fiber) = worker {
5499 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
5500 }
5501
5502 let mut handle_item = |item: &mut WorkItem| match item {
5503 WorkItem::ResumeFiber(fiber) => {
5504 fiber.trace_gc_roots(modules, unwind, gc_roots_list);
5505 }
5506 WorkItem::PushFuture(_future) => {
5507 }
5510 WorkItem::ResumeThread(..) | WorkItem::GuestCall(..) | WorkItem::WorkerFunction(..) => {
5511 }
5512 };
5513
5514 for item in high_priority {
5515 handle_item(item);
5516 }
5517 for item in low_priority {
5518 handle_item(item);
5519 }
5520 }
5521
5522 fn push<V: Send + Sync + 'static>(
5523 &mut self,
5524 value: V,
5525 ) -> Result<TableId<V>, ResourceTableError> {
5526 self.table.get_mut().push(value).map(TableId::from)
5527 }
5528
5529 fn get_mut<V: 'static>(&mut self, id: TableId<V>) -> Result<&mut V, ResourceTableError> {
5530 self.table.get_mut().get_mut(&Resource::from(id))
5531 }
5532
5533 pub fn add_child<T: 'static, U: 'static>(
5534 &mut self,
5535 child: TableId<T>,
5536 parent: TableId<U>,
5537 ) -> Result<(), ResourceTableError> {
5538 self.table
5539 .get_mut()
5540 .add_child(Resource::from(child), Resource::from(parent))
5541 }
5542
5543 pub fn remove_child<T: 'static, U: 'static>(
5544 &mut self,
5545 child: TableId<T>,
5546 parent: TableId<U>,
5547 ) -> Result<(), ResourceTableError> {
5548 self.table
5549 .get_mut()
5550 .remove_child(Resource::from(child), Resource::from(parent))
5551 }
5552
5553 fn delete<V: 'static>(&mut self, id: TableId<V>) -> Result<V, ResourceTableError> {
5554 self.table.get_mut().delete(Resource::from(id))
5555 }
5556
5557 fn push_future(&mut self, future: HostTaskFuture) {
5558 self.push_high_priority(WorkItem::PushFuture(AlwaysMut::new(future)));
5565 }
5566
5567 fn push_high_priority(&mut self, item: WorkItem) {
5568 log::trace!("push high priority: {item:?}");
5569 self.high_priority.push(item);
5570 }
5571
5572 fn push_low_priority(&mut self, item: WorkItem) {
5573 log::trace!("push low priority: {item:?}");
5574 self.low_priority.push_front(item);
5575 }
5576
5577 fn push_work_item(&mut self, item: WorkItem, high_priority: bool) {
5578 if high_priority {
5579 self.push_high_priority(item);
5580 } else {
5581 self.push_low_priority(item);
5582 }
5583 }
5584
5585 fn promote_instance_local_thread_work_item(
5586 &mut self,
5587 current_instance: RuntimeComponentInstanceIndex,
5588 ) -> bool {
5589 self.promote_work_items_matching(|item: &WorkItem| match item {
5590 WorkItem::ResumeThread(instance, _) | WorkItem::GuestCall(instance, _) => {
5591 *instance == current_instance
5592 }
5593 _ => false,
5594 })
5595 }
5596
5597 fn promote_thread_work_item(&mut self, thread: QualifiedThreadId) -> bool {
5598 self.promote_work_items_matching(|item: &WorkItem| match item {
5599 WorkItem::ResumeThread(_, t) | WorkItem::GuestCall(_, GuestCall { thread: t, .. }) => {
5600 *t == thread
5601 }
5602 _ => false,
5603 })
5604 }
5605
5606 fn promote_work_items_matching<F>(&mut self, mut predicate: F) -> bool
5607 where
5608 F: FnMut(&WorkItem) -> bool,
5609 {
5610 if self.high_priority.iter().any(&mut predicate) {
5614 true
5615 }
5616 else if let Some(idx) = self.low_priority.iter().position(&mut predicate) {
5619 let item = self.low_priority.remove(idx).unwrap();
5620 self.push_high_priority(item);
5621 true
5622 } else {
5623 false
5624 }
5625 }
5626
5627 fn check_blocking_for(&mut self, task: TableId<GuestTask>) -> Result<()> {
5628 if self.may_block(task)? {
5629 Ok(())
5630 } else {
5631 Err(Trap::CannotBlockSyncTask.into())
5632 }
5633 }
5634
5635 fn may_block(&mut self, task: TableId<GuestTask>) -> Result<bool> {
5636 let task = self.get_mut(task)?;
5637 Ok(task.async_function || task.returned_or_cancelled())
5638 }
5639
5640 pub fn call_context(&mut self, task: u32) -> Result<&mut CallContext> {
5646 let (task, is_host) = (task >> 1, task & 1 == 1);
5647 if is_host {
5648 let task: TableId<HostTask> = TableId::new(task);
5649 Ok(&mut self.get_mut(task)?.call_context)
5650 } else {
5651 let task: TableId<GuestTask> = TableId::new(task);
5652 Ok(&mut self.get_mut(task)?.call_context)
5653 }
5654 }
5655
5656 fn futures_mut(&mut self) -> Result<&mut FuturesUnordered<HostTaskFuture>> {
5657 match self.futures.get_mut().as_mut() {
5658 Some(f) => Ok(f),
5659 None => bail_bug!("futures field of concurrent state is currently taken"),
5660 }
5661 }
5662
5663 pub(crate) fn table(&mut self) -> &mut ResourceTable {
5664 self.table.get_mut()
5665 }
5666
5667 fn parent(&mut self, cur: CurrentThread) -> Option<CurrentThread> {
5669 let task = match cur {
5670 CurrentThread::GuestTask(task) => task,
5671 CurrentThread::Guest(thread) => thread.task,
5672 CurrentThread::Host(id) => {
5673 return Some(CurrentThread::GuestTask(self.get_mut(id).ok()?.caller));
5674 }
5675 CurrentThread::None => return None,
5676 };
5677 let task = self.get_mut(task).ok()?;
5678 Some(match task.caller {
5679 Caller::Host { caller, .. } => caller,
5680 Caller::Guest { thread } => thread.into(),
5681 })
5682 }
5683}
5684
5685fn for_any_lower<
5688 F: FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync,
5689>(
5690 fun: F,
5691) -> F {
5692 fun
5693}
5694
5695fn for_any_lift<
5697 F: FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
5698>(
5699 fun: F,
5700) -> F {
5701 fun
5702}
5703
5704fn check_ambient_store(id: StoreId) {
5705 let message = "\
5706 `Future`s which depend on asynchronous component tasks, streams, or \
5707 futures to complete may only be polled from the event loop of the \
5708 store to which they belong. Please use \
5709 `StoreContextMut::{run_concurrent,spawn}` to poll or await them.\
5710 ";
5711 tls::try_get(|store| {
5712 let matched = match store {
5713 tls::TryGet::Some(store) => store.id() == id,
5714 tls::TryGet::Taken | tls::TryGet::None => false,
5715 };
5716
5717 if !matched {
5718 panic!("{message}")
5719 }
5720 });
5721}
5722
5723fn check_recursive_run() {
5726 tls::try_get(|store| {
5727 if !matches!(store, tls::TryGet::None) {
5728 panic!("Recursive `StoreContextMut::run_concurrent` calls not supported")
5729 }
5730 });
5731}
5732
5733fn unpack_callback_code(code: u32) -> (u32, u32) {
5734 (code & 0xF, code >> 4)
5735}
5736
5737struct WaitableCheckParams {
5741 set: TableId<WaitableSet>,
5742 options: OptionsIndex,
5743 payload: u32,
5744}
5745
5746enum WaitableCheck {
5749 Wait,
5750 Poll,
5751}
5752
5753#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
5762pub struct GuestTaskId(TableId<GuestTask>);
5763
5764pub(crate) struct PreparedCall<R> {
5766 handle: Func,
5768 thread: QualifiedThreadId,
5770 param_count: usize,
5772 rx: oneshot::Receiver<LiftedResult>,
5775 runtime_instance: RuntimeInstance,
5777 _phantom: PhantomData<R>,
5778}
5779
5780impl<R> PreparedCall<R> {
5781 pub(crate) fn task_id(&self) -> TaskId {
5783 TaskId {
5784 task: self.thread.task,
5785 runtime_instance: self.runtime_instance,
5786 }
5787 }
5788}
5789
5790pub(crate) struct TaskId {
5792 task: TableId<GuestTask>,
5793 runtime_instance: RuntimeInstance,
5794}
5795
5796impl TaskId {
5797 pub(crate) fn host_future_dropped(&self, store: &mut StoreOpaque) -> Result<()> {
5803 let task = store.concurrent_state_mut()?.get_mut(self.task)?;
5804 let delete = if !task.already_lowered_parameters() {
5805 store.cancel_guest_subtask_without_lowered_parameters(
5806 self.runtime_instance,
5807 self.task,
5808 )?;
5809 true
5810 } else {
5811 task.host_future_state = HostFutureState::Dropped;
5812 task.ready_to_delete()
5813 };
5814 if delete {
5815 Waitable::Guest(self.task).delete_from(store.concurrent_state_mut()?)?
5816 }
5817 Ok(())
5818 }
5819}
5820
5821pub(crate) fn prepare_call<T, R>(
5827 mut store: StoreContextMut<T>,
5828 handle: Func,
5829 param_count: usize,
5830 host_future_present: bool,
5831 lower_params: impl FnOnce(Func, StoreContextMut<T>, &mut [MaybeUninit<ValRaw>]) -> Result<()>
5832 + Send
5833 + Sync
5834 + 'static,
5835 lift_result: impl FnOnce(Func, &mut StoreOpaque, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>>
5836 + Send
5837 + Sync
5838 + 'static,
5839) -> Result<PreparedCall<R>> {
5840 let (options, _flags, ty, raw_options) = handle.abi_info(store.0);
5841
5842 let instance = handle.instance().id().get(store.0);
5843 let options = &instance.component().env_component().options[options];
5844 let ty = &instance.component().types()[ty];
5845 let async_function = ty.async_;
5846 let task_return_type = ty.results;
5847 let component_instance = raw_options.instance;
5848 let callback = options.callback.map(|i| instance.runtime_callback(i));
5849 let memory = options
5850 .memory()
5851 .map(|i| instance.runtime_memory(i))
5852 .map(SendSyncPtr::new);
5853 let string_encoding = options.string_encoding;
5854 let token = StoreToken::new(store.as_context_mut());
5855 let caller = store.0.current_thread()?;
5856 let state = store.0.concurrent_state_mut()?;
5857
5858 let (tx, rx) = oneshot::channel();
5859
5860 let instance = handle.instance().runtime_instance(component_instance);
5861 let thread = GuestTask::new(
5862 state,
5863 Box::new(for_any_lower(move |store, params| {
5864 lower_params(handle, token.as_context_mut(store), params)
5865 })),
5866 LiftResult {
5867 lift: Box::new(for_any_lift(move |store, result| {
5868 lift_result(handle, store, result)
5869 })),
5870 ty: task_return_type,
5871 memory,
5872 string_encoding,
5873 },
5874 Caller::Host {
5875 tx: Some(tx),
5876 host_future_present,
5877 caller,
5878 },
5879 callback.map(|callback| {
5880 let callback = SendSyncPtr::new(callback);
5881 let instance = handle.instance();
5882 Box::new(move |store: &mut dyn VMStore, event, handle| {
5883 let store = token.as_context_mut(store);
5884 unsafe { instance.call_callback(store, callback, event, handle) }
5887 }) as CallbackFn
5888 }),
5889 instance,
5890 async_function,
5891 )?;
5892
5893 if !store.0.may_enter(instance)? {
5894 bail!(Trap::CannotEnterComponent);
5895 }
5896
5897 Ok(PreparedCall {
5898 handle,
5899 thread,
5900 param_count,
5901 runtime_instance: instance,
5902 rx,
5903 _phantom: PhantomData,
5904 })
5905}
5906
5907pub(crate) struct QueuedCall<R> {
5908 store: StoreId,
5909 task: TableId<GuestTask>,
5910 rx: oneshot::Receiver<LiftedResult>,
5911 _marker: PhantomData<fn() -> R>,
5912}
5913
5914impl<R> QueuedCall<R> {
5915 pub(crate) fn new<T: 'static>(
5922 mut store: StoreContextMut<T>,
5923 prepared: PreparedCall<R>,
5924 ) -> Result<QueuedCall<R>> {
5925 let PreparedCall {
5926 handle,
5927 thread,
5928 param_count,
5929 rx,
5930 ..
5931 } = prepared;
5932
5933 queue_call0(store.as_context_mut(), handle, thread, param_count)?;
5934
5935 Ok(QueuedCall {
5936 store: store.0.id(),
5937 task: thread.task,
5938 rx,
5939 _marker: PhantomData,
5940 })
5941 }
5942
5943 fn task(&self) -> GuestTaskId {
5944 GuestTaskId(self.task)
5945 }
5946}
5947
5948impl<R> Future for QueuedCall<R>
5949where
5950 R: 'static,
5951{
5952 type Output = Result<R>;
5953
5954 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
5955 check_ambient_store(self.store);
5956 Pin::new(&mut self.rx).poll(cx).map(|result| match result {
5957 Ok(r) => match r.downcast() {
5958 Ok(r) => Ok(*r),
5959 Err(_) => bail_bug!("wrong type of value produced"),
5960 },
5961 Err(oneshot::Canceled) => bail_bug!("channel erroneously dropped"),
5962 })
5963 }
5964}
5965
5966fn queue_call0<T: 'static>(
5969 store: StoreContextMut<T>,
5970 handle: Func,
5971 guest_thread: QualifiedThreadId,
5972 param_count: usize,
5973) -> Result<()> {
5974 let (_options, _, _ty, raw_options) = handle.abi_info(store.0);
5975 let is_concurrent = raw_options.async_;
5976 let callback = raw_options.callback;
5977 let instance = handle.instance();
5978 let callee = handle.lifted_core_func(store.0);
5979 let post_return = handle.post_return_core_func(store.0);
5980 let callback = callback.map(|i| {
5981 let instance = instance.id().get(store.0);
5982 SendSyncPtr::new(instance.runtime_callback(i))
5983 });
5984
5985 log::trace!("queueing call {guest_thread:?}");
5986
5987 unsafe {
5991 instance.queue_call(
5992 store,
5993 guest_thread,
5994 SendSyncPtr::new(callee),
5995 param_count,
5996 1,
5997 is_concurrent,
5998 callback,
5999 post_return.map(SendSyncPtr::new),
6000 )
6001 }
6002}