1 //! Runtime support for the Component Model Async ABI.
2 //!
3 //! This module and its submodules provide host runtime support for Component
4 //! Model Async features such as async-lifted exports, async-lowered imports,
5 //! streams, futures, and related intrinsics.  See [the Async
6 //! Explainer](https://github.com/WebAssembly/component-model/blob/main/design/mvp/Concurrency.md)
7 //! for a high-level overview.
8 //!
9 //! At the core of this support is an event loop which schedules and switches
10 //! between guest tasks and any host tasks they create.  Each
11 //! `Store` will have at most one event loop running at any given
12 //! time, and that loop may be suspended and resumed by the host embedder using
13 //! e.g. `StoreContextMut::run_concurrent`.  The `StoreContextMut::poll_until`
14 //! function contains the loop itself, while the
15 //! `StoreOpaque::concurrent_state` field holds its state.
16 //!
17 //! # Public API Overview
18 //!
19 //! ## Top-level API (e.g. kicking off host->guest calls and driving the event loop)
20 //!
21 //! - `[Typed]Func::call_concurrent`: Start a host->guest call to an
22 //! async-lifted or sync-lifted import, creating a guest task.
23 //!
24 //! - `StoreContextMut::run_concurrent`: Run the event loop for the specified
25 //! instance, allowing any and all tasks belonging to that instance to make
26 //! progress.
27 //!
28 //! - `StoreContextMut::spawn`: Run a background task as part of the event loop
29 //! for the specified instance.
30 //!
31 //! - `{Future,Stream}Reader::new`: Create a new Component Model `future` or
32 //! `stream` which may be passed to the guest.  This takes a
33 //! `{Future,Stream}Producer` implementation which will be polled for items when
34 //! the consumer requests them.
35 //!
36 //! - `{Future,Stream}Reader::pipe`: Consume a `future` or `stream` by
37 //! connecting it to a `{Future,Stream}Consumer` which will consume any items
38 //! produced by the write end.
39 //!
40 //! ## Host Task API (e.g. implementing concurrent host functions and background tasks)
41 //!
42 //! - `LinkerInstance::func_wrap_concurrent`: Register a concurrent host
43 //! function with the linker.  That function will take an `Accessor` as its
44 //! first parameter, which provides access to the store between (but not across)
45 //! await points.
46 //!
47 //! - `Accessor::with`: Access the store and its associated data.
48 //!
49 //! - `Accessor::spawn`: Run a background task as part of the event loop for the
50 //! store.  This is equivalent to `StoreContextMut::spawn` but more convenient to use
51 //! in host functions.
52 
53 use crate::component::func::{self, Func, call_post_return};
54 use crate::component::{
55     HasData, HasSelf, Instance, Resource, ResourceTable, ResourceTableError, RuntimeInstance,
56 };
57 use crate::fiber::{self, StoreFiber, StoreFiberYield};
58 use crate::prelude::*;
59 use crate::store::{Store, StoreId, StoreInner, StoreOpaque, StoreToken};
60 use crate::vm::component::{CallContext, ComponentInstance, HandleTable, ResourceTables};
61 use crate::vm::{AlwaysMut, SendSyncPtr, VMFuncRef, VMMemoryDefinition, VMStore};
62 use crate::{
63     AsContext, AsContextMut, FuncType, Result, StoreContext, StoreContextMut, ValRaw, ValType,
64     bail,
65     error::{Context as _, format_err},
66 };
67 use error_contexts::GlobalErrorContextRefCount;
68 use futures::channel::oneshot;
69 use futures::future::{self, FutureExt};
70 use futures::stream::{FuturesUnordered, StreamExt};
71 use futures_and_streams::{FlatAbi, ReturnCode, TransmitHandle, TransmitIndex};
72 use std::any::Any;
73 use std::borrow::ToOwned;
74 use std::boxed::Box;
75 use std::cell::UnsafeCell;
76 use std::collections::{BTreeMap, BTreeSet, HashSet, VecDeque};
77 use std::fmt;
78 use std::future::Future;
79 use std::marker::PhantomData;
80 use std::mem::{self, ManuallyDrop, MaybeUninit};
81 use std::ops::DerefMut;
82 use std::pin::{Pin, pin};
83 use std::ptr::{self, NonNull};
84 use std::sync::Arc;
85 use std::task::{Context, Poll, Waker};
86 use std::vec::Vec;
87 use table::{TableDebug, TableId};
88 use wasmtime_environ::Trap;
89 use wasmtime_environ::component::{
90     CanonicalAbiInfo, CanonicalOptions, CanonicalOptionsDataModel, ExportIndex, 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 };
96 use wasmtime_environ::packed_option::ReservedValue;
97 
98 pub use abort::JoinHandle;
99 pub use future_stream_any::{FutureAny, StreamAny};
100 pub use futures_and_streams::{
101     Destination, DirectDestination, DirectSource, ErrorContext, FutureConsumer, FutureProducer,
102     FutureReader, GuardedFutureReader, GuardedStreamReader, ReadBuffer, Source, StreamConsumer,
103     StreamProducer, StreamReader, StreamResult, VecBuffer, WriteBuffer,
104 };
105 pub(crate) use futures_and_streams::{ResourcePair, lower_error_context_to_index};
106 
107 mod abort;
108 mod error_contexts;
109 mod future_stream_any;
110 mod futures_and_streams;
111 pub(crate) mod table;
112 pub(crate) mod tls;
113 
114 /// Constant defined in the Component Model spec to indicate that the async
115 /// intrinsic (e.g. `future.write`) has not yet completed.
116 const BLOCKED: u32 = 0xffff_ffff;
117 
118 /// Corresponds to `CallState` in the upstream spec.
119 #[derive(Clone, Copy, Eq, PartialEq, Debug)]
120 pub enum Status {
121     Starting = 0,
122     Started = 1,
123     Returned = 2,
124     StartCancelled = 3,
125     ReturnCancelled = 4,
126 }
127 
128 impl Status {
129     /// Packs this status and the optional `waitable` provided into a 32-bit
130     /// result that the canonical ABI requires.
131     ///
132     /// The low 4 bits are reserved for the status while the upper 28 bits are
133     /// the waitable, if present.
134     pub fn pack(self, waitable: Option<u32>) -> u32 {
135         assert!(matches!(self, Status::Returned) == waitable.is_none());
136         let waitable = waitable.unwrap_or(0);
137         assert!(waitable < (1 << 28));
138         (waitable << 4) | (self as u32)
139     }
140 }
141 
142 /// Corresponds to `EventCode` in the Component Model spec, plus related payload
143 /// data.
144 #[derive(Clone, Copy, Debug)]
145 enum Event {
146     None,
147     Cancelled,
148     Subtask {
149         status: Status,
150     },
151     StreamRead {
152         code: ReturnCode,
153         pending: Option<(TypeStreamTableIndex, u32)>,
154     },
155     StreamWrite {
156         code: ReturnCode,
157         pending: Option<(TypeStreamTableIndex, u32)>,
158     },
159     FutureRead {
160         code: ReturnCode,
161         pending: Option<(TypeFutureTableIndex, u32)>,
162     },
163     FutureWrite {
164         code: ReturnCode,
165         pending: Option<(TypeFutureTableIndex, u32)>,
166     },
167 }
168 
169 impl Event {
170     /// Lower this event to core Wasm integers for delivery to the guest.
171     ///
172     /// Note that the waitable handle, if any, is assumed to be lowered
173     /// separately.
174     fn parts(self) -> (u32, u32) {
175         const EVENT_NONE: u32 = 0;
176         const EVENT_SUBTASK: u32 = 1;
177         const EVENT_STREAM_READ: u32 = 2;
178         const EVENT_STREAM_WRITE: u32 = 3;
179         const EVENT_FUTURE_READ: u32 = 4;
180         const EVENT_FUTURE_WRITE: u32 = 5;
181         const EVENT_CANCELLED: u32 = 6;
182         match self {
183             Event::None => (EVENT_NONE, 0),
184             Event::Cancelled => (EVENT_CANCELLED, 0),
185             Event::Subtask { status } => (EVENT_SUBTASK, status as u32),
186             Event::StreamRead { code, .. } => (EVENT_STREAM_READ, code.encode()),
187             Event::StreamWrite { code, .. } => (EVENT_STREAM_WRITE, code.encode()),
188             Event::FutureRead { code, .. } => (EVENT_FUTURE_READ, code.encode()),
189             Event::FutureWrite { code, .. } => (EVENT_FUTURE_WRITE, code.encode()),
190         }
191     }
192 }
193 
194 /// Corresponds to `CallbackCode` in the spec.
195 mod callback_code {
196     pub const EXIT: u32 = 0;
197     pub const YIELD: u32 = 1;
198     pub const WAIT: u32 = 2;
199 }
200 
201 /// A flag indicating that the callee is an async-lowered export.
202 ///
203 /// This may be passed to the `async-start` intrinsic from a fused adapter.
204 const START_FLAG_ASYNC_CALLEE: u32 = wasmtime_environ::component::START_FLAG_ASYNC_CALLEE as u32;
205 
206 /// Provides access to either store data (via the `get` method) or the store
207 /// itself (via [`AsContext`]/[`AsContextMut`]), as well as the component
208 /// instance to which the current host task belongs.
209 ///
210 /// See [`Accessor::with`] for details.
211 pub struct Access<'a, T: 'static, D: HasData + ?Sized = HasSelf<T>> {
212     store: StoreContextMut<'a, T>,
213     get_data: fn(&mut T) -> D::Data<'_>,
214 }
215 
216 impl<'a, T, D> Access<'a, T, D>
217 where
218     D: HasData + ?Sized,
219     T: 'static,
220 {
221     /// Creates a new [`Access`] from its component parts.
222     pub fn new(store: StoreContextMut<'a, T>, get_data: fn(&mut T) -> D::Data<'_>) -> Self {
223         Self { store, get_data }
224     }
225 
226     /// Get mutable access to the store data.
227     pub fn data_mut(&mut self) -> &mut T {
228         self.store.data_mut()
229     }
230 
231     /// Get mutable access to the store data.
232     pub fn get(&mut self) -> D::Data<'_> {
233         (self.get_data)(self.data_mut())
234     }
235 
236     /// Spawn a background task.
237     ///
238     /// See [`Accessor::spawn`] for details.
239     pub fn spawn(&mut self, task: impl AccessorTask<T, D>) -> JoinHandle
240     where
241         T: 'static,
242     {
243         let accessor = Accessor {
244             get_data: self.get_data,
245             token: StoreToken::new(self.store.as_context_mut()),
246         };
247         self.store
248             .as_context_mut()
249             .spawn_with_accessor(accessor, task)
250     }
251 
252     /// Returns the getter this accessor is using to project from `T` into
253     /// `D::Data`.
254     pub fn getter(&self) -> fn(&mut T) -> D::Data<'_> {
255         self.get_data
256     }
257 }
258 
259 impl<'a, T, D> AsContext for Access<'a, T, D>
260 where
261     D: HasData + ?Sized,
262     T: 'static,
263 {
264     type Data = T;
265 
266     fn as_context(&self) -> StoreContext<'_, T> {
267         self.store.as_context()
268     }
269 }
270 
271 impl<'a, T, D> AsContextMut for Access<'a, T, D>
272 where
273     D: HasData + ?Sized,
274     T: 'static,
275 {
276     fn as_context_mut(&mut self) -> StoreContextMut<'_, T> {
277         self.store.as_context_mut()
278     }
279 }
280 
281 /// Provides scoped mutable access to store data in the context of a concurrent
282 /// host task future.
283 ///
284 /// This allows multiple host task futures to execute concurrently and access
285 /// the store between (but not across) `await` points.
286 ///
287 /// # Rationale
288 ///
289 /// This structure is sort of like `&mut T` plus a projection from `&mut T` to
290 /// `D::Data<'_>`. The problem this is solving, however, is that it does not
291 /// literally store these values. The basic problem is that when a concurrent
292 /// host future is being polled it has access to `&mut T` (and the whole
293 /// `Store`) but when it's not being polled it does not have access to these
294 /// values. This reflects how the store is only ever polling one future at a
295 /// time so the store is effectively being passed between futures.
296 ///
297 /// Rust's `Future` trait, however, has no means of passing a `Store`
298 /// temporarily between futures. The [`Context`](std::task::Context) type does
299 /// not have the ability to attach arbitrary information to it at this time.
300 /// This type, [`Accessor`], is used to bridge this expressivity gap.
301 ///
302 /// The [`Accessor`] type here represents the ability to acquire, temporarily in
303 /// a synchronous manner, the current store. The [`Accessor::with`] function
304 /// yields an [`Access`] which can be used to access [`StoreContextMut`], `&mut
305 /// T`, or `D::Data<'_>`. Note though that [`Accessor::with`] intentionally does
306 /// not take an `async` closure as its argument, instead it's a synchronous
307 /// closure which must complete during on run of `Future::poll`. This reflects
308 /// how the store is temporarily made available while a host future is being
309 /// polled.
310 ///
311 /// # Implementation
312 ///
313 /// This type does not actually store `&mut T` nor `StoreContextMut<T>`, and
314 /// this type additionally doesn't even have a lifetime parameter. This is
315 /// instead a representation of proof of the ability to acquire these while a
316 /// future is being polled. Wasmtime will, when it polls a host future,
317 /// configure ambient state such that the `Accessor` that a future closes over
318 /// will work and be able to access the store.
319 ///
320 /// This has a number of implications for users such as:
321 ///
322 /// * It's intentional that `Accessor` cannot be cloned, it needs to stay within
323 ///   the lifetime of a single future.
324 /// * A future is expected to, however, close over an `Accessor` and keep it
325 ///   alive probably for the duration of the entire future.
326 /// * Different host futures will be given different `Accessor`s, and that's
327 ///   intentional.
328 /// * The `Accessor` type is `Send` and `Sync` irrespective of `T` which
329 ///   alleviates some otherwise required bounds to be written down.
330 ///
331 /// # Using `Accessor` in `Drop`
332 ///
333 /// The methods on `Accessor` are only expected to work in the context of
334 /// `Future::poll` and are not guaranteed to work in `Drop`. This is because a
335 /// host future can be dropped at any time throughout the system and Wasmtime
336 /// store context is not necessarily available at that time. It's recommended to
337 /// not use `Accessor` methods in anything connected to a `Drop` implementation
338 /// as they will panic and have unintended results. If you run into this though
339 /// feel free to file an issue on the Wasmtime repository.
340 pub struct Accessor<T: 'static, D = HasSelf<T>>
341 where
342     D: HasData + ?Sized,
343 {
344     token: StoreToken<T>,
345     get_data: fn(&mut T) -> D::Data<'_>,
346 }
347 
348 /// A helper trait to take any type of accessor-with-data in functions.
349 ///
350 /// This trait is similar to [`AsContextMut`] except that it's used when
351 /// working with an [`Accessor`] instead of a [`StoreContextMut`]. The
352 /// [`Accessor`] is the main type used in concurrent settings and is passed to
353 /// functions such as [`Func::call_concurrent`].
354 ///
355 /// This trait is implemented for [`Accessor`] and `&T` where `T` implements
356 /// this trait. This effectively means that regardless of the `D` in
357 /// `Accessor<T, D>` it can still be passed to a function which just needs a
358 /// store accessor.
359 ///
360 /// Acquiring an [`Accessor`] can be done through
361 /// [`StoreContextMut::run_concurrent`] for example or in a host function
362 /// through
363 /// [`Linker::func_wrap_concurrent`](crate::component::LinkerInstance::func_wrap_concurrent).
364 pub trait AsAccessor {
365     /// The `T` in `Store<T>` that this accessor refers to.
366     type Data: 'static;
367 
368     /// The `D` in `Accessor<T, D>`, or the projection out of
369     /// `Self::Data`.
370     type AccessorData: HasData + ?Sized;
371 
372     /// Returns the accessor that this is referring to.
373     fn as_accessor(&self) -> &Accessor<Self::Data, Self::AccessorData>;
374 }
375 
376 impl<T: AsAccessor + ?Sized> AsAccessor for &T {
377     type Data = T::Data;
378     type AccessorData = T::AccessorData;
379 
380     fn as_accessor(&self) -> &Accessor<Self::Data, Self::AccessorData> {
381         T::as_accessor(self)
382     }
383 }
384 
385 impl<T, D: HasData + ?Sized> AsAccessor for Accessor<T, D> {
386     type Data = T;
387     type AccessorData = D;
388 
389     fn as_accessor(&self) -> &Accessor<T, D> {
390         self
391     }
392 }
393 
394 // Note that it is intentional at this time that `Accessor` does not actually
395 // store `&mut T` or anything similar. This distinctly enables the `Accessor`
396 // structure to be both `Send` and `Sync` regardless of what `T` is (or `D` for
397 // that matter). This is used to ergonomically simplify bindings where the
398 // majority of the time `Accessor` is closed over in a future which then needs
399 // to be `Send` and `Sync`. To avoid needing to write `T: Send` everywhere (as
400 // you already have to write `T: 'static`...) it helps to avoid this.
401 //
402 // Note as well that `Accessor` doesn't actually store its data at all. Instead
403 // it's more of a "proof" of what can be accessed from TLS. API design around
404 // `Accessor` and functions like `Linker::func_wrap_concurrent` are
405 // intentionally made to ensure that `Accessor` is ideally only used in the
406 // context that TLS variables are actually set. For example host functions are
407 // given `&Accessor`, not `Accessor`, and this prevents them from persisting
408 // the value outside of a future. Within the future the TLS variables are all
409 // guaranteed to be set while the future is being polled.
410 //
411 // Finally though this is not an ironclad guarantee, but nor does it need to be.
412 // The TLS APIs are designed to panic or otherwise model usage where they're
413 // called recursively or similar. It's hoped that code cannot be constructed to
414 // actually hit this at runtime but this is not a safety requirement at this
415 // time.
416 const _: () = {
417     const fn assert<T: Send + Sync>() {}
418     assert::<Accessor<UnsafeCell<u32>>>();
419 };
420 
421 impl<T> Accessor<T> {
422     /// Creates a new `Accessor` backed by the specified functions.
423     ///
424     /// - `get`: used to retrieve the store
425     ///
426     /// - `get_data`: used to "project" from the store's associated data to
427     /// another type (e.g. a field of that data or a wrapper around it).
428     ///
429     /// - `spawn`: used to queue spawned background tasks to be run later
430     pub(crate) fn new(token: StoreToken<T>) -> Self {
431         Self {
432             token,
433             get_data: |x| x,
434         }
435     }
436 }
437 
438 impl<T, D> Accessor<T, D>
439 where
440     D: HasData + ?Sized,
441 {
442     /// Run the specified closure, passing it mutable access to the store.
443     ///
444     /// This function is one of the main building blocks of the [`Accessor`]
445     /// type. This yields synchronous, blocking, access to the store via an
446     /// [`Access`]. The [`Access`] implements [`AsContextMut`] in addition to
447     /// providing the ability to access `D` via [`Access::get`]. Note that the
448     /// `fun` here is given only temporary access to the store and `T`/`D`
449     /// meaning that the return value `R` here is not allowed to capture borrows
450     /// into the two. If access is needed to data within `T` or `D` outside of
451     /// this closure then it must be `clone`d out, for example.
452     ///
453     /// # Panics
454     ///
455     /// This function will panic if it is call recursively with any other
456     /// accessor already in scope. For example if `with` is called within `fun`,
457     /// then this function will panic. It is up to the embedder to ensure that
458     /// this does not happen.
459     pub fn with<R>(&self, fun: impl FnOnce(Access<'_, T, D>) -> R) -> R {
460         tls::get(|vmstore| {
461             fun(Access {
462                 store: self.token.as_context_mut(vmstore),
463                 get_data: self.get_data,
464             })
465         })
466     }
467 
468     /// Returns the getter this accessor is using to project from `T` into
469     /// `D::Data`.
470     pub fn getter(&self) -> fn(&mut T) -> D::Data<'_> {
471         self.get_data
472     }
473 
474     /// Changes this accessor to access `D2` instead of the current type
475     /// parameter `D`.
476     ///
477     /// This changes the underlying data access from `T` to `D2::Data<'_>`.
478     ///
479     /// # Panics
480     ///
481     /// When using this API the returned value is disconnected from `&self` and
482     /// the lifetime binding the `self` argument. An `Accessor` only works
483     /// within the context of the closure or async closure that it was
484     /// originally given to, however. This means that due to the fact that the
485     /// returned value has no lifetime connection it's possible to use the
486     /// accessor outside of `&self`, the original accessor, and panic.
487     ///
488     /// The returned value should only be used within the scope of the original
489     /// `Accessor` that `self` refers to.
490     pub fn with_getter<D2: HasData>(
491         &self,
492         get_data: fn(&mut T) -> D2::Data<'_>,
493     ) -> Accessor<T, D2> {
494         Accessor {
495             token: self.token,
496             get_data,
497         }
498     }
499 
500     /// Spawn a background task which will receive an `&Accessor<T, D>` and
501     /// run concurrently with any other tasks in progress for the current
502     /// store.
503     ///
504     /// This is particularly useful for host functions which return a `stream`
505     /// or `future` such that the code to write to the write end of that
506     /// `stream` or `future` must run after the function returns.
507     ///
508     /// The returned [`JoinHandle`] may be used to cancel the task.
509     ///
510     /// # Panics
511     ///
512     /// Panics if called within a closure provided to the [`Accessor::with`]
513     /// function. This can only be called outside an active invocation of
514     /// [`Accessor::with`].
515     pub fn spawn(&self, task: impl AccessorTask<T, D>) -> JoinHandle
516     where
517         T: 'static,
518     {
519         let accessor = self.clone_for_spawn();
520         self.with(|mut access| access.as_context_mut().spawn_with_accessor(accessor, task))
521     }
522 
523     fn clone_for_spawn(&self) -> Self {
524         Self {
525             token: self.token,
526             get_data: self.get_data,
527         }
528     }
529 }
530 
531 /// Represents a task which may be provided to `Accessor::spawn`,
532 /// `Accessor::forward`, or `StorecContextMut::spawn`.
533 // TODO: Replace this with `std::ops::AsyncFnOnce` when that becomes a viable
534 // option.
535 //
536 // As of this writing, it's not possible to specify e.g. `Send` and `Sync`
537 // bounds on the `Future` type returned by an `AsyncFnOnce`.  Also, using `F:
538 // Future<Output = Result<()>> + Send + Sync, FN: FnOnce(&Accessor<T>) -> F +
539 // Send + Sync + 'static` fails with a type mismatch error when we try to pass
540 // it an async closure (e.g. `async move |_| { ... }`).  So this seems to be the
541 // best we can do for the time being.
542 pub trait AccessorTask<T, D = HasSelf<T>>: Send + 'static
543 where
544     D: HasData + ?Sized,
545 {
546     /// Run the task.
547     fn run(self, accessor: &Accessor<T, D>) -> impl Future<Output = Result<()>> + Send;
548 }
549 
550 /// Represents parameter and result metadata for the caller side of a
551 /// guest->guest call orchestrated by a fused adapter.
552 enum CallerInfo {
553     /// Metadata for a call to an async-lowered import
554     Async {
555         params: Vec<ValRaw>,
556         has_result: bool,
557     },
558     /// Metadata for a call to an sync-lowered import
559     Sync {
560         params: Vec<ValRaw>,
561         result_count: u32,
562     },
563 }
564 
565 /// Indicates how a guest task is waiting on a waitable set.
566 enum WaitMode {
567     /// The guest task is waiting using `task.wait`
568     Fiber(StoreFiber<'static>),
569     /// The guest task is waiting via a callback declared as part of an
570     /// async-lifted export.
571     Callback(Instance),
572 }
573 
574 /// Represents the reason a fiber is suspending itself.
575 #[derive(Debug)]
576 enum SuspendReason {
577     /// The fiber is waiting for an event to be delivered to the specified
578     /// waitable set or task.
579     Waiting {
580         set: TableId<WaitableSet>,
581         thread: QualifiedThreadId,
582         skip_may_block_check: bool,
583     },
584     /// The fiber has finished handling its most recent work item and is waiting
585     /// for another (or to be dropped if it is no longer needed).
586     NeedWork,
587     /// The fiber is yielding and should be resumed once other tasks have had a
588     /// chance to run.
589     Yielding {
590         thread: QualifiedThreadId,
591         skip_may_block_check: bool,
592     },
593     /// The fiber was explicitly suspended with a call to `thread.suspend` or `thread.switch-to`.
594     ExplicitlySuspending {
595         thread: QualifiedThreadId,
596         skip_may_block_check: bool,
597     },
598 }
599 
600 /// Represents a pending call into guest code for a given guest task.
601 enum GuestCallKind {
602     /// Indicates there's an event to deliver to the task, possibly related to a
603     /// waitable set the task has been waiting on or polling.
604     DeliverEvent {
605         /// The instance to which the task belongs.
606         instance: Instance,
607         /// The waitable set the event belongs to, if any.
608         ///
609         /// If this is `None` the event will be waiting in the
610         /// `GuestTask::event` field for the task.
611         set: Option<TableId<WaitableSet>>,
612     },
613     /// Indicates that a new guest task call is pending and may be executed
614     /// using the specified closure.
615     ///
616     /// If the closure returns `Ok(Some(call))`, the `call` should be run
617     /// immediately using `handle_guest_call`.
618     StartImplicit(Box<dyn FnOnce(&mut dyn VMStore) -> Result<Option<GuestCall>> + Send + Sync>),
619     StartExplicit(Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send + Sync>),
620 }
621 
622 impl fmt::Debug for GuestCallKind {
623     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
624         match self {
625             Self::DeliverEvent { instance, set } => f
626                 .debug_struct("DeliverEvent")
627                 .field("instance", instance)
628                 .field("set", set)
629                 .finish(),
630             Self::StartImplicit(_) => f.debug_tuple("StartImplicit").finish(),
631             Self::StartExplicit(_) => f.debug_tuple("StartExplicit").finish(),
632         }
633     }
634 }
635 
636 /// Represents a pending call into guest code for a given guest thread.
637 #[derive(Debug)]
638 struct GuestCall {
639     thread: QualifiedThreadId,
640     kind: GuestCallKind,
641 }
642 
643 impl GuestCall {
644     /// Returns whether or not the call is ready to run.
645     ///
646     /// A call will not be ready to run if either:
647     ///
648     /// - the (sub-)component instance to be called has already been entered and
649     /// cannot be reentered until an in-progress call completes
650     ///
651     /// - the call is for a not-yet started task and the (sub-)component
652     /// instance to be called has backpressure enabled
653     fn is_ready(&self, store: &mut StoreOpaque) -> Result<bool> {
654         let instance = store
655             .concurrent_state_mut()
656             .get_mut(self.thread.task)?
657             .instance;
658         let state = store.instance_state(instance);
659 
660         let ready = match &self.kind {
661             GuestCallKind::DeliverEvent { .. } => !state.do_not_enter,
662             GuestCallKind::StartImplicit(_) => !(state.do_not_enter || state.backpressure > 0),
663             GuestCallKind::StartExplicit(_) => true,
664         };
665         log::trace!(
666             "call {self:?} ready? {ready} (do_not_enter: {}; backpressure: {})",
667             state.do_not_enter,
668             state.backpressure
669         );
670         Ok(ready)
671     }
672 }
673 
674 /// Job to be run on a worker fiber.
675 enum WorkerItem {
676     GuestCall(GuestCall),
677     Function(AlwaysMut<Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send>>),
678 }
679 
680 /// Represents a pending work item to be handled by the event loop for a given
681 /// component instance.
682 enum WorkItem {
683     /// A host task to be pushed to `ConcurrentState::futures`.
684     PushFuture(AlwaysMut<HostTaskFuture>),
685     /// A fiber to resume.
686     ResumeFiber(StoreFiber<'static>),
687     /// A pending call into guest code for a given guest task.
688     GuestCall(GuestCall),
689     /// A job to run on a worker fiber.
690     WorkerFunction(AlwaysMut<Box<dyn FnOnce(&mut dyn VMStore) -> Result<()> + Send>>),
691 }
692 
693 impl fmt::Debug for WorkItem {
694     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
695         match self {
696             Self::PushFuture(_) => f.debug_tuple("PushFuture").finish(),
697             Self::ResumeFiber(_) => f.debug_tuple("ResumeFiber").finish(),
698             Self::GuestCall(call) => f.debug_tuple("GuestCall").field(call).finish(),
699             Self::WorkerFunction(_) => f.debug_tuple("WorkerFunction").finish(),
700         }
701     }
702 }
703 
704 /// Whether a suspension intrinsic was cancelled or completed
705 #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
706 pub(crate) enum WaitResult {
707     Cancelled,
708     Completed,
709 }
710 
711 /// Poll the specified future until it completes on behalf of a guest->host call
712 /// using a sync-lowered import.
713 ///
714 /// This is similar to `Instance::first_poll` except it's for sync-lowered
715 /// imports, meaning we don't need to handle cancellation and we can block the
716 /// caller until the task completes, at which point the caller can handle
717 /// lowering the result to the guest's stack and linear memory.
718 pub(crate) fn poll_and_block<R: Send + Sync + 'static>(
719     store: &mut dyn VMStore,
720     future: impl Future<Output = Result<R>> + Send + 'static,
721     caller_instance: RuntimeInstance,
722 ) -> Result<R> {
723     let state = store.concurrent_state_mut();
724 
725     let caller = state.guest_thread.unwrap();
726 
727     // Save any existing result stashed in `GuestTask::result` so we can replace
728     // it with the new result.
729     let old_result = state
730         .get_mut(caller.task)
731         .with_context(|| format!("bad handle: {caller:?}"))?
732         .result
733         .take();
734 
735     // Add a temporary host task into the table so we can track its progress.
736     // Note that we'll never allocate a waitable handle for the guest since
737     // we're being called synchronously.
738     let task = state.push(HostTask::new(caller_instance, None))?;
739 
740     log::trace!("new host task child of {caller:?}: {task:?}");
741 
742     // Wrap the future in a closure which will take care of stashing the result
743     // in `GuestTask::result` and resuming this fiber when the host task
744     // completes.
745     let mut future = Box::pin(async move {
746         let result = future.await?;
747         tls::get(move |store| {
748             let state = store.concurrent_state_mut();
749             state.get_mut(caller.task)?.result = Some(Box::new(result) as _);
750 
751             Waitable::Host(task).set_event(
752                 state,
753                 Some(Event::Subtask {
754                     status: Status::Returned,
755                 }),
756             )?;
757 
758             Ok(())
759         })
760     }) as HostTaskFuture;
761 
762     // Finally, poll the future.  We can use a dummy `Waker` here because we'll
763     // add the future to `ConcurrentState::futures` and poll it automatically
764     // from the event loop if it doesn't complete immediately here.
765     let poll = tls::set(store, || {
766         future
767             .as_mut()
768             .poll(&mut Context::from_waker(&Waker::noop()))
769     });
770 
771     match poll {
772         Poll::Ready(result) => {
773             // It completed immediately; check the result and delete the task.
774             result?;
775             log::trace!("delete host task {task:?} (already ready)");
776             store.concurrent_state_mut().delete(task)?;
777         }
778         Poll::Pending => {
779             // It did not complete immediately; add it to
780             // `ConcurrentState::futures` so it will be polled via the event
781             // loop; then use `GuestTask::sync_call_set` to wait for the task to
782             // complete, suspending the current fiber until it does so.
783             let state = store.concurrent_state_mut();
784             state.push_future(future);
785 
786             let set = state.get_mut(caller.task)?.sync_call_set;
787             Waitable::Host(task).join(state, Some(set))?;
788 
789             store.suspend(SuspendReason::Waiting {
790                 set,
791                 thread: caller,
792                 skip_may_block_check: false,
793             })?;
794         }
795     }
796 
797     // Retrieve and return the result.
798     Ok(*mem::replace(
799         &mut store.concurrent_state_mut().get_mut(caller.task)?.result,
800         old_result,
801     )
802     .unwrap()
803     .downcast()
804     .unwrap())
805 }
806 
807 /// Execute the specified guest call.
808 fn handle_guest_call(store: &mut dyn VMStore, call: GuestCall) -> Result<()> {
809     let mut next = Some(call);
810     while let Some(call) = next.take() {
811         match call.kind {
812             GuestCallKind::DeliverEvent { instance, set } => {
813                 let (event, waitable) = instance
814                     .get_event(store, call.thread.task, set, true)?
815                     .unwrap();
816                 let state = store.concurrent_state_mut();
817                 let task = state.get_mut(call.thread.task)?;
818                 let runtime_instance = task.instance;
819                 let handle = waitable.map(|(_, v)| v).unwrap_or(0);
820 
821                 log::trace!(
822                     "use callback to deliver event {event:?} to {:?} for {waitable:?}",
823                     call.thread,
824                 );
825 
826                 let old_thread = store.set_thread(Some(call.thread));
827                 log::trace!(
828                     "GuestCallKind::DeliverEvent: replaced {old_thread:?} with {:?} as current thread",
829                     call.thread
830                 );
831 
832                 store.maybe_push_call_context(call.thread.task)?;
833 
834                 store.enter_instance(runtime_instance);
835 
836                 let callback = store
837                     .concurrent_state_mut()
838                     .get_mut(call.thread.task)?
839                     .callback
840                     .take()
841                     .unwrap();
842 
843                 let code = callback(store, event, handle)?;
844 
845                 store
846                     .concurrent_state_mut()
847                     .get_mut(call.thread.task)?
848                     .callback = Some(callback);
849 
850                 store.exit_instance(runtime_instance)?;
851 
852                 store.maybe_pop_call_context(call.thread.task)?;
853 
854                 store.set_thread(old_thread);
855 
856                 next = instance.handle_callback_code(
857                     store,
858                     call.thread,
859                     runtime_instance.index,
860                     code,
861                 )?;
862 
863                 log::trace!(
864                     "GuestCallKind::DeliverEvent: restored {old_thread:?} as current thread"
865                 );
866             }
867             GuestCallKind::StartImplicit(fun) => {
868                 next = fun(store)?;
869             }
870             GuestCallKind::StartExplicit(fun) => {
871                 fun(store)?;
872             }
873         }
874     }
875 
876     Ok(())
877 }
878 
879 impl<T> Store<T> {
880     /// Convenience wrapper for [`StoreContextMut::run_concurrent`].
881     pub async fn run_concurrent<R>(&mut self, fun: impl AsyncFnOnce(&Accessor<T>) -> R) -> Result<R>
882     where
883         T: Send + 'static,
884     {
885         ensure!(
886             self.as_context().0.concurrency_support(),
887             "cannot use `run_concurrent` when Config::concurrency_support disabled",
888         );
889         self.as_context_mut().run_concurrent(fun).await
890     }
891 
892     #[doc(hidden)]
893     pub fn assert_concurrent_state_empty(&mut self) {
894         self.as_context_mut().assert_concurrent_state_empty();
895     }
896 
897     /// Convenience wrapper for [`StoreContextMut::spawn`].
898     pub fn spawn(&mut self, task: impl AccessorTask<T, HasSelf<T>>) -> JoinHandle
899     where
900         T: 'static,
901     {
902         self.as_context_mut().spawn(task)
903     }
904 }
905 
906 impl<T> StoreContextMut<'_, T> {
907     /// Assert that all the relevant tables and queues in the concurrent state
908     /// for this store are empty.
909     ///
910     /// This is for sanity checking in integration tests
911     /// (e.g. `component-async-tests`) that the relevant state has been cleared
912     /// after each test concludes.  This should help us catch leaks, e.g. guest
913     /// tasks which haven't been deleted despite having completed and having
914     /// been dropped by their supertasks.
915     #[doc(hidden)]
916     pub fn assert_concurrent_state_empty(self) {
917         let store = self.0;
918         store
919             .store_data_mut()
920             .components
921             .assert_instance_states_empty();
922         let state = store.concurrent_state_mut();
923         assert!(
924             state.table.get_mut().is_empty(),
925             "non-empty table: {:?}",
926             state.table.get_mut()
927         );
928         assert!(state.high_priority.is_empty());
929         assert!(state.low_priority.is_empty());
930         assert!(state.guest_thread.is_none());
931         assert!(state.futures.get_mut().as_ref().unwrap().is_empty());
932         assert!(state.global_error_context_ref_counts.is_empty());
933     }
934 
935     /// Spawn a background task to run as part of this instance's event loop.
936     ///
937     /// The task will receive an `&Accessor<U>` and run concurrently with
938     /// any other tasks in progress for the instance.
939     ///
940     /// Note that the task will only make progress if and when the event loop
941     /// for this instance is run.
942     ///
943     /// The returned [`JoinHandle`] may be used to cancel the task.
944     pub fn spawn(mut self, task: impl AccessorTask<T>) -> JoinHandle
945     where
946         T: 'static,
947     {
948         let accessor = Accessor::new(StoreToken::new(self.as_context_mut()));
949         self.spawn_with_accessor(accessor, task)
950     }
951 
952     /// Internal implementation of `spawn` functions where a `store` is
953     /// available along with an `Accessor`.
954     fn spawn_with_accessor<D>(
955         self,
956         accessor: Accessor<T, D>,
957         task: impl AccessorTask<T, D>,
958     ) -> JoinHandle
959     where
960         T: 'static,
961         D: HasData + ?Sized,
962     {
963         // Create an "abortable future" here where internally the future will
964         // hook calls to poll and possibly spawn more background tasks on each
965         // iteration.
966         let (handle, future) = JoinHandle::run(async move { task.run(&accessor).await });
967         self.0
968             .concurrent_state_mut()
969             .push_future(Box::pin(async move { future.await.unwrap_or(Ok(())) }));
970         handle
971     }
972 
973     /// Run the specified closure `fun` to completion as part of this store's
974     /// event loop.
975     ///
976     /// This will run `fun` as part of this store's event loop until it
977     /// yields a result.  `fun` is provided an [`Accessor`], which provides
978     /// controlled access to the store and its data.
979     ///
980     /// This function can be used to invoke [`Func::call_concurrent`] for
981     /// example within the async closure provided here.
982     ///
983     /// This function will unconditionally return an error if
984     /// [`Config::concurrency_support`] is disabled.
985     ///
986     /// [`Config::concurrency_support`]: crate::Config::concurrency_support
987     ///
988     /// # Store-blocking behavior
989     ///
990     /// At this time there are certain situations in which the `Future` returned
991     /// by the `AsyncFnOnce` passed to this function will not be polled for an
992     /// extended period of time, despite one or more `Waker::wake` events having
993     /// occurred for the task to which it belongs.  This can manifest as the
994     /// `Future` seeming to be "blocked" or "locked up", but is actually due to
995     /// the `Store` being held by e.g. a blocking host function, preventing the
996     /// `Future` from being polled. A canonical example of this is when the
997     /// `fun` provided to this function attempts to set a timeout for an
998     /// invocation of a wasm function. In this situation the async closure is
999     /// waiting both on (a) the wasm computation to finish, and (b) the timeout
1000     /// to elapse. At this time this setup will not always work and the timeout
1001     /// may not reliably fire.
1002     ///
1003     /// This function will not block the current thread and as such is always
1004     /// suitable to run in an `async` context, but the current implementation of
1005     /// Wasmtime can lead to situations where a certain wasm computation is
1006     /// required to make progress the closure to make progress. This is an
1007     /// artifact of Wasmtime's historical implementation of `async` functions
1008     /// and is the topic of [#11869] and [#11870]. In the timeout example from
1009     /// above it means that Wasmtime can get "wedged" for a bit where (a) must
1010     /// progress for a readiness notification of (b) to get delivered.
1011     ///
1012     /// This effectively means that it's not possible to reliably perform a
1013     /// "select" operation within the `fun` closure, which timeouts for example
1014     /// are based on. Fixing this requires some relatively major refactoring
1015     /// work within Wasmtime itself. This is a known pitfall otherwise and one
1016     /// that is intended to be fixed one day. In the meantime it's recommended
1017     /// to apply timeouts or such to the entire `run_concurrent` call itself
1018     /// rather than internally.
1019     ///
1020     /// [#11869]: https://github.com/bytecodealliance/wasmtime/issues/11869
1021     /// [#11870]: https://github.com/bytecodealliance/wasmtime/issues/11870
1022     ///
1023     /// # Example
1024     ///
1025     /// ```
1026     /// # use {
1027     /// #   wasmtime::{
1028     /// #     error::{Result},
1029     /// #     component::{ Component, Linker, Resource, ResourceTable},
1030     /// #     Config, Engine, Store
1031     /// #   },
1032     /// # };
1033     /// #
1034     /// # struct MyResource(u32);
1035     /// # struct Ctx { table: ResourceTable }
1036     /// #
1037     /// # async fn foo() -> Result<()> {
1038     /// # let mut config = Config::new();
1039     /// # let engine = Engine::new(&config)?;
1040     /// # let mut store = Store::new(&engine, Ctx { table: ResourceTable::new() });
1041     /// # let mut linker = Linker::new(&engine);
1042     /// # let component = Component::new(&engine, "")?;
1043     /// # let instance = linker.instantiate_async(&mut store, &component).await?;
1044     /// # let foo = instance.get_typed_func::<(Resource<MyResource>,), (Resource<MyResource>,)>(&mut store, "foo")?;
1045     /// # let bar = instance.get_typed_func::<(u32,), ()>(&mut store, "bar")?;
1046     /// store.run_concurrent(async |accessor| -> wasmtime::Result<_> {
1047     ///    let resource = accessor.with(|mut access| access.get().table.push(MyResource(42)))?;
1048     ///    let (another_resource,) = foo.call_concurrent(accessor, (resource,)).await?.0;
1049     ///    let value = accessor.with(|mut access| access.get().table.delete(another_resource))?;
1050     ///    bar.call_concurrent(accessor, (value.0,)).await?;
1051     ///    Ok(())
1052     /// }).await??;
1053     /// # Ok(())
1054     /// # }
1055     /// ```
1056     pub async fn run_concurrent<R>(self, fun: impl AsyncFnOnce(&Accessor<T>) -> R) -> Result<R>
1057     where
1058         T: Send + 'static,
1059     {
1060         ensure!(
1061             self.0.concurrency_support(),
1062             "cannot use `run_concurrent` when Config::concurrency_support disabled",
1063         );
1064         self.do_run_concurrent(fun, false).await
1065     }
1066 
1067     pub(super) async fn run_concurrent_trap_on_idle<R>(
1068         self,
1069         fun: impl AsyncFnOnce(&Accessor<T>) -> R,
1070     ) -> Result<R>
1071     where
1072         T: Send + 'static,
1073     {
1074         self.do_run_concurrent(fun, true).await
1075     }
1076 
1077     async fn do_run_concurrent<R>(
1078         mut self,
1079         fun: impl AsyncFnOnce(&Accessor<T>) -> R,
1080         trap_on_idle: bool,
1081     ) -> Result<R>
1082     where
1083         T: Send + 'static,
1084     {
1085         debug_assert!(self.0.concurrency_support());
1086         check_recursive_run();
1087         let token = StoreToken::new(self.as_context_mut());
1088 
1089         struct Dropper<'a, T: 'static, V> {
1090             store: StoreContextMut<'a, T>,
1091             value: ManuallyDrop<V>,
1092         }
1093 
1094         impl<'a, T, V> Drop for Dropper<'a, T, V> {
1095             fn drop(&mut self) {
1096                 tls::set(self.store.0, || {
1097                     // SAFETY: Here we drop the value without moving it for the
1098                     // first and only time -- per the contract for `Drop::drop`,
1099                     // this code won't run again, and the `value` field will no
1100                     // longer be accessible.
1101                     unsafe { ManuallyDrop::drop(&mut self.value) }
1102                 });
1103             }
1104         }
1105 
1106         let accessor = &Accessor::new(token);
1107         let dropper = &mut Dropper {
1108             store: self,
1109             value: ManuallyDrop::new(fun(accessor)),
1110         };
1111         // SAFETY: We never move `dropper` nor its `value` field.
1112         let future = unsafe { Pin::new_unchecked(dropper.value.deref_mut()) };
1113 
1114         dropper
1115             .store
1116             .as_context_mut()
1117             .poll_until(future, trap_on_idle)
1118             .await
1119     }
1120 
1121     /// Run this store's event loop.
1122     ///
1123     /// The returned future will resolve when the specified future completes or,
1124     /// if `trap_on_idle` is true, when the event loop can't make further
1125     /// progress.
1126     async fn poll_until<R>(
1127         mut self,
1128         mut future: Pin<&mut impl Future<Output = R>>,
1129         trap_on_idle: bool,
1130     ) -> Result<R>
1131     where
1132         T: Send + 'static,
1133     {
1134         struct Reset<'a, T: 'static> {
1135             store: StoreContextMut<'a, T>,
1136             futures: Option<FuturesUnordered<HostTaskFuture>>,
1137         }
1138 
1139         impl<'a, T> Drop for Reset<'a, T> {
1140             fn drop(&mut self) {
1141                 if let Some(futures) = self.futures.take() {
1142                     *self.store.0.concurrent_state_mut().futures.get_mut() = Some(futures);
1143                 }
1144             }
1145         }
1146 
1147         loop {
1148             // Take `ConcurrentState::futures` out of the store so we can poll
1149             // it while also safely giving any of the futures inside access to
1150             // `self`.
1151             let futures = self.0.concurrent_state_mut().futures.get_mut().take();
1152             let mut reset = Reset {
1153                 store: self.as_context_mut(),
1154                 futures,
1155             };
1156             let mut next = pin!(reset.futures.as_mut().unwrap().next());
1157 
1158             enum PollResult<R> {
1159                 Complete(R),
1160                 ProcessWork(Vec<WorkItem>),
1161             }
1162             let result = future::poll_fn(|cx| {
1163                 // First, poll the future we were passed as an argument and
1164                 // return immediately if it's ready.
1165                 if let Poll::Ready(value) = tls::set(reset.store.0, || future.as_mut().poll(cx)) {
1166                     return Poll::Ready(Ok(PollResult::Complete(value)));
1167                 }
1168 
1169                 // Next, poll `ConcurrentState::futures` (which includes any
1170                 // pending host tasks and/or background tasks), returning
1171                 // immediately if one of them fails.
1172                 let next = match tls::set(reset.store.0, || next.as_mut().poll(cx)) {
1173                     Poll::Ready(Some(output)) => {
1174                         match output {
1175                             Err(e) => return Poll::Ready(Err(e)),
1176                             Ok(()) => {}
1177                         }
1178                         Poll::Ready(true)
1179                     }
1180                     Poll::Ready(None) => Poll::Ready(false),
1181                     Poll::Pending => Poll::Pending,
1182                 };
1183 
1184                 // Next, collect the next batch of work items to process, if any.
1185                 // This will be either all of the high-priority work items, or if
1186                 // there are none, a single low-priority work item.
1187                 let state = reset.store.0.concurrent_state_mut();
1188                 let ready = state.collect_work_items_to_run();
1189                 if !ready.is_empty() {
1190                     return Poll::Ready(Ok(PollResult::ProcessWork(ready)));
1191                 }
1192 
1193                 // Finally, if we have nothing else to do right now, determine what to do
1194                 // based on whether there are any pending futures in
1195                 // `ConcurrentState::futures`.
1196                 return match next {
1197                     Poll::Ready(true) => {
1198                         // In this case, one of the futures in
1199                         // `ConcurrentState::futures` completed
1200                         // successfully, so we return now and continue
1201                         // the outer loop in case there is another one
1202                         // ready to complete.
1203                         Poll::Ready(Ok(PollResult::ProcessWork(Vec::new())))
1204                     }
1205                     Poll::Ready(false) => {
1206                         // Poll the future we were passed one last time
1207                         // in case one of `ConcurrentState::futures` had
1208                         // the side effect of unblocking it.
1209                         if let Poll::Ready(value) =
1210                             tls::set(reset.store.0, || future.as_mut().poll(cx))
1211                         {
1212                             Poll::Ready(Ok(PollResult::Complete(value)))
1213                         } else {
1214                             // In this case, there are no more pending
1215                             // futures in `ConcurrentState::futures`,
1216                             // there are no remaining work items, _and_
1217                             // the future we were passed as an argument
1218                             // still hasn't completed.
1219                             if trap_on_idle {
1220                                 // `trap_on_idle` is true, so we exit
1221                                 // immediately.
1222                                 Poll::Ready(Err(format_err!(crate::Trap::AsyncDeadlock)))
1223                             } else {
1224                                 // `trap_on_idle` is false, so we assume
1225                                 // that future will wake up and give us
1226                                 // more work to do when it's ready to.
1227                                 Poll::Pending
1228                             }
1229                         }
1230                     }
1231                     // There is at least one pending future in
1232                     // `ConcurrentState::futures` and we have nothing
1233                     // else to do but wait for now, so we return
1234                     // `Pending`.
1235                     Poll::Pending => Poll::Pending,
1236                 };
1237             })
1238             .await;
1239 
1240             // Put the `ConcurrentState::futures` back into the store before we
1241             // return or handle any work items since one or more of those items
1242             // might append more futures.
1243             drop(reset);
1244 
1245             match result? {
1246                 // The future we were passed as an argument completed, so we
1247                 // return the result.
1248                 PollResult::Complete(value) => break Ok(value),
1249                 // The future we were passed has not yet completed, so handle
1250                 // any work items and then loop again.
1251                 PollResult::ProcessWork(ready) => {
1252                     struct Dispose<'a, T: 'static, I: Iterator<Item = WorkItem>> {
1253                         store: StoreContextMut<'a, T>,
1254                         ready: I,
1255                     }
1256 
1257                     impl<'a, T, I: Iterator<Item = WorkItem>> Drop for Dispose<'a, T, I> {
1258                         fn drop(&mut self) {
1259                             while let Some(item) = self.ready.next() {
1260                                 match item {
1261                                     WorkItem::ResumeFiber(mut fiber) => fiber.dispose(self.store.0),
1262                                     WorkItem::PushFuture(future) => {
1263                                         tls::set(self.store.0, move || drop(future))
1264                                     }
1265                                     _ => {}
1266                                 }
1267                             }
1268                         }
1269                     }
1270 
1271                     let mut dispose = Dispose {
1272                         store: self.as_context_mut(),
1273                         ready: ready.into_iter(),
1274                     };
1275 
1276                     while let Some(item) = dispose.ready.next() {
1277                         dispose
1278                             .store
1279                             .as_context_mut()
1280                             .handle_work_item(item)
1281                             .await?;
1282                     }
1283                 }
1284             }
1285         }
1286     }
1287 
1288     /// Handle the specified work item, possibly resuming a fiber if applicable.
1289     async fn handle_work_item(self, item: WorkItem) -> Result<()>
1290     where
1291         T: Send,
1292     {
1293         log::trace!("handle work item {item:?}");
1294         match item {
1295             WorkItem::PushFuture(future) => {
1296                 self.0
1297                     .concurrent_state_mut()
1298                     .futures
1299                     .get_mut()
1300                     .as_mut()
1301                     .unwrap()
1302                     .push(future.into_inner());
1303             }
1304             WorkItem::ResumeFiber(fiber) => {
1305                 self.0.resume_fiber(fiber).await?;
1306             }
1307             WorkItem::GuestCall(call) => {
1308                 if call.is_ready(self.0)? {
1309                     self.run_on_worker(WorkerItem::GuestCall(call)).await?;
1310                 } else {
1311                     let state = self.0.concurrent_state_mut();
1312                     let task = state.get_mut(call.thread.task)?;
1313                     if !task.starting_sent {
1314                         task.starting_sent = true;
1315                         if let GuestCallKind::StartImplicit(_) = &call.kind {
1316                             Waitable::Guest(call.thread.task).set_event(
1317                                 state,
1318                                 Some(Event::Subtask {
1319                                     status: Status::Starting,
1320                                 }),
1321                             )?;
1322                         }
1323                     }
1324 
1325                     let instance = state.get_mut(call.thread.task)?.instance;
1326                     self.0
1327                         .instance_state(instance)
1328                         .pending
1329                         .insert(call.thread, call.kind);
1330                 }
1331             }
1332             WorkItem::WorkerFunction(fun) => {
1333                 self.run_on_worker(WorkerItem::Function(fun)).await?;
1334             }
1335         }
1336 
1337         Ok(())
1338     }
1339 
1340     /// Execute the specified guest call on a worker fiber.
1341     async fn run_on_worker(self, item: WorkerItem) -> Result<()>
1342     where
1343         T: Send,
1344     {
1345         let worker = if let Some(fiber) = self.0.concurrent_state_mut().worker.take() {
1346             fiber
1347         } else {
1348             fiber::make_fiber(self.0, move |store| {
1349                 loop {
1350                     match store.concurrent_state_mut().worker_item.take().unwrap() {
1351                         WorkerItem::GuestCall(call) => handle_guest_call(store, call)?,
1352                         WorkerItem::Function(fun) => fun.into_inner()(store)?,
1353                     }
1354 
1355                     store.suspend(SuspendReason::NeedWork)?;
1356                 }
1357             })?
1358         };
1359 
1360         let worker_item = &mut self.0.concurrent_state_mut().worker_item;
1361         assert!(worker_item.is_none());
1362         *worker_item = Some(item);
1363 
1364         self.0.resume_fiber(worker).await
1365     }
1366 
1367     /// Wrap the specified host function in a future which will call it, passing
1368     /// it an `&Accessor<T>`.
1369     ///
1370     /// See the `Accessor` documentation for details.
1371     pub(crate) fn wrap_call<F, R>(self, closure: F) -> impl Future<Output = Result<R>> + 'static
1372     where
1373         T: 'static,
1374         F: FnOnce(&Accessor<T>) -> Pin<Box<dyn Future<Output = Result<R>> + Send + '_>>
1375             + Send
1376             + Sync
1377             + 'static,
1378         R: Send + Sync + 'static,
1379     {
1380         let token = StoreToken::new(self);
1381         async move {
1382             let mut accessor = Accessor::new(token);
1383             closure(&mut accessor).await
1384         }
1385     }
1386 }
1387 
1388 impl StoreOpaque {
1389     /// Push a `GuestTask` onto the task stack for either a sync-to-sync,
1390     /// guest-to-guest call or a sync host-to-guest call.
1391     ///
1392     /// This task will only be used for the purpose of handling calls to
1393     /// intrinsic functions; both parameter lowering and result lifting are
1394     /// assumed to be taken care of elsewhere.
1395     pub(crate) fn enter_sync_call(
1396         &mut self,
1397         guest_caller: Option<RuntimeInstance>,
1398         callee_async: bool,
1399         callee: RuntimeInstance,
1400     ) -> Result<()> {
1401         log::trace!("enter sync call {callee:?}");
1402 
1403         let state = self.concurrent_state_mut();
1404         let thread = state.guest_thread;
1405         let instance = if let Some(thread) = thread {
1406             Some(state.get_mut(thread.task)?.instance)
1407         } else {
1408             None
1409         };
1410         let task = GuestTask::new(
1411             state,
1412             Box::new(move |_, _| unreachable!()),
1413             LiftResult {
1414                 lift: Box::new(move |_, _| unreachable!()),
1415                 ty: TypeTupleIndex::reserved_value(),
1416                 memory: None,
1417                 string_encoding: StringEncoding::Utf8,
1418             },
1419             if let Some(caller) = guest_caller {
1420                 assert_eq!(caller, instance.unwrap());
1421                 Caller::Guest {
1422                     thread: thread.unwrap(),
1423                 }
1424             } else {
1425                 Caller::Host {
1426                     tx: None,
1427                     exit_tx: Arc::new(oneshot::channel().0),
1428                     host_future_present: false,
1429                     caller: state.guest_thread,
1430                 }
1431             },
1432             None,
1433             callee,
1434             callee_async,
1435         )?;
1436 
1437         let guest_task = state.push(task)?;
1438         let new_thread = GuestThread::new_implicit(guest_task);
1439         let guest_thread = state.push(new_thread)?;
1440         Instance::from_wasmtime(self, callee.instance).add_guest_thread_to_instance_table(
1441             guest_thread,
1442             self,
1443             callee.index,
1444         )?;
1445 
1446         let state = self.concurrent_state_mut();
1447         state.get_mut(guest_task)?.threads.insert(guest_thread);
1448         if guest_caller.is_some() {
1449             let thread = state.guest_thread.unwrap();
1450             state.get_mut(thread.task)?.subtasks.insert(guest_task);
1451         }
1452 
1453         self.set_thread(Some(QualifiedThreadId {
1454             task: guest_task,
1455             thread: guest_thread,
1456         }));
1457 
1458         Ok(())
1459     }
1460 
1461     /// Pop a `GuestTask` previously pushed using `enter_sync_call`.
1462     pub(crate) fn exit_sync_call(&mut self, guest_caller: bool) -> Result<()> {
1463         let thread = self.set_thread(None).unwrap();
1464         let instance = self.concurrent_state_mut().get_mut(thread.task)?.instance;
1465         log::trace!("exit sync call {instance:?}");
1466         Instance::from_wasmtime(self, instance.instance).cleanup_thread(
1467             self,
1468             thread,
1469             instance.index,
1470         )?;
1471 
1472         let state = self.concurrent_state_mut();
1473         let task = state.get_mut(thread.task)?;
1474         let caller = match &task.caller {
1475             &Caller::Guest { thread } => {
1476                 assert!(guest_caller);
1477                 Some(thread)
1478             }
1479             &Caller::Host { caller, .. } => {
1480                 assert!(!guest_caller);
1481                 caller
1482             }
1483         };
1484         self.set_thread(caller);
1485 
1486         let state = self.concurrent_state_mut();
1487         let task = state.get_mut(thread.task)?;
1488         if task.ready_to_delete() {
1489             state.delete(thread.task)?.dispose(state, thread.task)?;
1490         }
1491 
1492         Ok(())
1493     }
1494 
1495     /// Determine whether the specified instance may be entered from the host.
1496     ///
1497     /// We return `true` here only if all of the following hold:
1498     ///
1499     /// - The top-level instance is not already on the current task's call stack.
1500     /// - The instance is not in need of a post-return function call.
1501     /// - `self` has not been poisoned due to a trap.
1502     pub(crate) fn may_enter(&mut self, instance: RuntimeInstance) -> bool {
1503         if !self.concurrency_support() {
1504             return !self.trapped();
1505         }
1506         let state = self.concurrent_state_mut();
1507         if let Some(caller) = state.guest_thread {
1508             instance != state.get_mut(caller.task).unwrap().instance
1509                 && self.may_enter_from_caller(caller.task, instance)
1510         } else {
1511             !self.trapped()
1512         }
1513     }
1514 
1515     /// Variation of `may_enter` which takes a `TableId<GuestTask>` representing
1516     /// the callee.
1517     fn may_enter_task(&mut self, task: TableId<GuestTask>) -> bool {
1518         let instance = self.concurrent_state_mut().get_mut(task).unwrap().instance;
1519         self.may_enter_from_caller(task, instance)
1520     }
1521 
1522     /// Variation of `may_enter` which takes a `TableId<GuestTask>` representing
1523     /// the caller, plus a `RuntimeInstance` representing the callee.
1524     fn may_enter_from_caller(
1525         &mut self,
1526         mut guest_task: TableId<GuestTask>,
1527         instance: RuntimeInstance,
1528     ) -> bool {
1529         !self.trapped() && {
1530             let state = self.concurrent_state_mut();
1531             let guest_instance = instance.instance;
1532             loop {
1533                 // Note that we only compare top-level instance IDs here.  The
1534                 // idea is that the host is not allowed to recursively enter a
1535                 // top-level instance even if the specific leaf instance is not
1536                 // on the stack.  This the behavior defined in the spec, and it
1537                 // allows us to elide runtime checks in guest-to-guest adapters.
1538                 let next_thread = match &state.get_mut(guest_task).unwrap().caller {
1539                     Caller::Host { caller: None, .. } => break true,
1540                     &Caller::Host {
1541                         caller: Some(caller),
1542                         ..
1543                     } => {
1544                         let instance = state.get_mut(caller.task).unwrap().instance;
1545                         if instance.instance == guest_instance {
1546                             break false;
1547                         } else {
1548                             caller
1549                         }
1550                     }
1551                     &Caller::Guest { thread } => {
1552                         if state.get_mut(thread.task).unwrap().instance.instance == guest_instance {
1553                             break false;
1554                         } else {
1555                             thread
1556                         }
1557                     }
1558                 };
1559                 guest_task = next_thread.task;
1560             }
1561         }
1562     }
1563 
1564     /// Helper function to retrieve the `ConcurrentInstanceState` for the
1565     /// specified instance.
1566     fn instance_state(&mut self, instance: RuntimeInstance) -> &mut ConcurrentInstanceState {
1567         self.component_instance_mut(instance.instance)
1568             .instance_state(instance.index)
1569             .concurrent_state()
1570     }
1571 
1572     /// Helper function to retrieve the `HandleTable` for the specified
1573     /// instance.
1574     fn handle_table(&mut self, instance: RuntimeInstance) -> &mut HandleTable {
1575         self.component_instance_mut(instance.instance)
1576             .instance_state(instance.index)
1577             .handle_table()
1578     }
1579 
1580     fn set_thread(&mut self, thread: Option<QualifiedThreadId>) -> Option<QualifiedThreadId> {
1581         // Each time we switch threads, we conservatively set `task_may_block`
1582         // to `false` for the component instance we're switching away from (if
1583         // any), meaning it will be `false` for any new thread created for that
1584         // instance unless explicitly set otherwise.
1585         let state = self.concurrent_state_mut();
1586         let old_thread = state.guest_thread.take();
1587         if let Some(old_thread) = old_thread {
1588             let instance = state.get_mut(old_thread.task).unwrap().instance.instance;
1589             self.component_instance_mut(instance)
1590                 .set_task_may_block(false)
1591         }
1592 
1593         self.concurrent_state_mut().guest_thread = thread;
1594 
1595         // If we're switching to a new thread, set its component instance's
1596         // `task_may_block` according to where it left off.
1597         if thread.is_some() {
1598             self.set_task_may_block();
1599         }
1600 
1601         old_thread
1602     }
1603 
1604     /// Set the global variable representing whether the current task may block
1605     /// prior to entering Wasm code.
1606     fn set_task_may_block(&mut self) {
1607         let state = self.concurrent_state_mut();
1608         let guest_thread = state.guest_thread.unwrap();
1609         let instance = state.get_mut(guest_thread.task).unwrap().instance.instance;
1610         let may_block = self.concurrent_state_mut().may_block(guest_thread.task);
1611         self.component_instance_mut(instance)
1612             .set_task_may_block(may_block)
1613     }
1614 
1615     pub(crate) fn check_blocking(&mut self) -> Result<()> {
1616         if !self.concurrency_support() {
1617             return Ok(());
1618         }
1619         let state = self.concurrent_state_mut();
1620         let task = state.guest_thread.unwrap().task;
1621         let instance = state.get_mut(task).unwrap().instance.instance;
1622         let task_may_block = self.component_instance(instance).get_task_may_block();
1623 
1624         if task_may_block {
1625             Ok(())
1626         } else {
1627             Err(Trap::CannotBlockSyncTask.into())
1628         }
1629     }
1630 
1631     /// Record that we're about to enter a (sub-)component instance which does
1632     /// not support more than one concurrent, stackful activation, meaning it
1633     /// cannot be entered again until the next call returns.
1634     fn enter_instance(&mut self, instance: RuntimeInstance) {
1635         log::trace!("enter {instance:?}");
1636         self.instance_state(instance).do_not_enter = true;
1637     }
1638 
1639     /// Record that we've exited a (sub-)component instance previously entered
1640     /// with `Self::enter_instance` and then calls `Self::partition_pending`.
1641     /// See the documentation for the latter for details.
1642     fn exit_instance(&mut self, instance: RuntimeInstance) -> Result<()> {
1643         log::trace!("exit {instance:?}");
1644         self.instance_state(instance).do_not_enter = false;
1645         self.partition_pending(instance)
1646     }
1647 
1648     /// Iterate over `InstanceState::pending`, moving any ready items into the
1649     /// "high priority" work item queue.
1650     ///
1651     /// See `GuestCall::is_ready` for details.
1652     fn partition_pending(&mut self, instance: RuntimeInstance) -> Result<()> {
1653         for (thread, kind) in mem::take(&mut self.instance_state(instance).pending).into_iter() {
1654             let call = GuestCall { thread, kind };
1655             if call.is_ready(self)? {
1656                 self.concurrent_state_mut()
1657                     .push_high_priority(WorkItem::GuestCall(call));
1658             } else {
1659                 self.instance_state(instance)
1660                     .pending
1661                     .insert(call.thread, call.kind);
1662             }
1663         }
1664 
1665         Ok(())
1666     }
1667 
1668     /// Implements the `backpressure.{inc,dec}` intrinsics.
1669     pub(crate) fn backpressure_modify(
1670         &mut self,
1671         caller_instance: RuntimeInstance,
1672         modify: impl FnOnce(u16) -> Option<u16>,
1673     ) -> Result<()> {
1674         let state = self.instance_state(caller_instance);
1675         let old = state.backpressure;
1676         let new = modify(old).ok_or_else(|| format_err!("backpressure counter overflow"))?;
1677         state.backpressure = new;
1678 
1679         if old > 0 && new == 0 {
1680             // Backpressure was previously enabled and is now disabled; move any
1681             // newly-eligible guest calls to the "high priority" queue.
1682             self.partition_pending(caller_instance)?;
1683         }
1684 
1685         Ok(())
1686     }
1687 
1688     /// Resume the specified fiber, giving it exclusive access to the specified
1689     /// store.
1690     async fn resume_fiber(&mut self, fiber: StoreFiber<'static>) -> Result<()> {
1691         let old_thread = self.concurrent_state_mut().guest_thread;
1692         log::trace!("resume_fiber: save current thread {old_thread:?}");
1693 
1694         let fiber = fiber::resolve_or_release(self, fiber).await?;
1695 
1696         self.set_thread(old_thread);
1697 
1698         let state = self.concurrent_state_mut();
1699 
1700         if let Some(ref ot) = old_thread {
1701             state.get_mut(ot.thread)?.state = GuestThreadState::Running;
1702         }
1703         log::trace!("resume_fiber: restore current thread {old_thread:?}");
1704 
1705         if let Some(mut fiber) = fiber {
1706             log::trace!("resume_fiber: suspend reason {:?}", &state.suspend_reason);
1707             // See the `SuspendReason` documentation for what each case means.
1708             match state.suspend_reason.take().unwrap() {
1709                 SuspendReason::NeedWork => {
1710                     if state.worker.is_none() {
1711                         state.worker = Some(fiber);
1712                     } else {
1713                         fiber.dispose(self);
1714                     }
1715                 }
1716                 SuspendReason::Yielding { thread, .. } => {
1717                     state.get_mut(thread.thread)?.state = GuestThreadState::Pending;
1718                     state.push_low_priority(WorkItem::ResumeFiber(fiber));
1719                 }
1720                 SuspendReason::ExplicitlySuspending { thread, .. } => {
1721                     state.get_mut(thread.thread)?.state = GuestThreadState::Suspended(fiber);
1722                 }
1723                 SuspendReason::Waiting { set, thread, .. } => {
1724                     let old = state
1725                         .get_mut(set)?
1726                         .waiting
1727                         .insert(thread, WaitMode::Fiber(fiber));
1728                     assert!(old.is_none());
1729                 }
1730             };
1731         } else {
1732             log::trace!("resume_fiber: fiber has exited");
1733         }
1734 
1735         Ok(())
1736     }
1737 
1738     /// Suspend the current fiber, storing the reason in
1739     /// `ConcurrentState::suspend_reason` to indicate the conditions under which
1740     /// it should be resumed.
1741     ///
1742     /// See the `SuspendReason` documentation for details.
1743     fn suspend(&mut self, reason: SuspendReason) -> Result<()> {
1744         log::trace!("suspend fiber: {reason:?}");
1745 
1746         // If we're yielding or waiting on behalf of a guest thread, we'll need to
1747         // pop the call context which manages resource borrows before suspending
1748         // and then push it again once we've resumed.
1749         let task = match &reason {
1750             SuspendReason::Yielding { thread, .. }
1751             | SuspendReason::Waiting { thread, .. }
1752             | SuspendReason::ExplicitlySuspending { thread, .. } => Some(thread.task),
1753             SuspendReason::NeedWork => None,
1754         };
1755 
1756         let old_guest_thread = if let Some(task) = task {
1757             self.maybe_pop_call_context(task)?;
1758             self.concurrent_state_mut().guest_thread
1759         } else {
1760             None
1761         };
1762 
1763         // We should not have reached here unless either there's no current
1764         // task, or the current task is permitted to block.  In addition, we
1765         // special-case `thread.switch-to` and waiting for a subtask to go from
1766         // `starting` to `started`, both of which we consider non-blocking
1767         // operations despite requiring a suspend.
1768         assert!(
1769             matches!(
1770                 reason,
1771                 SuspendReason::ExplicitlySuspending {
1772                     skip_may_block_check: true,
1773                     ..
1774                 } | SuspendReason::Waiting {
1775                     skip_may_block_check: true,
1776                     ..
1777                 } | SuspendReason::Yielding {
1778                     skip_may_block_check: true,
1779                     ..
1780                 }
1781             ) || old_guest_thread
1782                 .map(|thread| self.concurrent_state_mut().may_block(thread.task))
1783                 .unwrap_or(true)
1784         );
1785 
1786         let suspend_reason = &mut self.concurrent_state_mut().suspend_reason;
1787         assert!(suspend_reason.is_none());
1788         *suspend_reason = Some(reason);
1789 
1790         self.with_blocking(|_, cx| cx.suspend(StoreFiberYield::ReleaseStore))?;
1791 
1792         if let Some(task) = task {
1793             self.set_thread(old_guest_thread);
1794             self.maybe_push_call_context(task)?;
1795         }
1796 
1797         Ok(())
1798     }
1799 
1800     /// Push the call context for managing resource borrows for the specified
1801     /// guest task if it has not yet either returned a result or cancelled
1802     /// itself.
1803     fn maybe_push_call_context(&mut self, guest_task: TableId<GuestTask>) -> Result<()> {
1804         let task = self.concurrent_state_mut().get_mut(guest_task)?;
1805 
1806         if !task.returned_or_cancelled() {
1807             log::trace!("push call context for {guest_task:?}");
1808             let call_context = task.call_context.take().unwrap();
1809             self.component_resource_state().0.push(call_context);
1810         }
1811         Ok(())
1812     }
1813 
1814     /// Pop the call context for managing resource borrows for the specified
1815     /// guest task if it has not yet either returned a result or cancelled
1816     /// itself.
1817     fn maybe_pop_call_context(&mut self, guest_task: TableId<GuestTask>) -> Result<()> {
1818         if !self
1819             .concurrent_state_mut()
1820             .get_mut(guest_task)?
1821             .returned_or_cancelled()
1822         {
1823             log::trace!("pop call context for {guest_task:?}");
1824             let call_context = Some(self.component_resource_state().0.pop().unwrap());
1825             self.concurrent_state_mut()
1826                 .get_mut(guest_task)?
1827                 .call_context = call_context;
1828         }
1829         Ok(())
1830     }
1831 
1832     fn wait_for_event(&mut self, waitable: Waitable) -> Result<()> {
1833         let state = self.concurrent_state_mut();
1834         let caller = state.guest_thread.unwrap();
1835         let old_set = waitable.common(state)?.set;
1836         let set = state.get_mut(caller.task)?.sync_call_set;
1837         waitable.join(state, Some(set))?;
1838         self.suspend(SuspendReason::Waiting {
1839             set,
1840             thread: caller,
1841             skip_may_block_check: false,
1842         })?;
1843         let state = self.concurrent_state_mut();
1844         waitable.join(state, old_set)
1845     }
1846 }
1847 
1848 impl Instance {
1849     /// Get the next pending event for the specified task and (optional)
1850     /// waitable set, along with the waitable handle if applicable.
1851     fn get_event(
1852         self,
1853         store: &mut StoreOpaque,
1854         guest_task: TableId<GuestTask>,
1855         set: Option<TableId<WaitableSet>>,
1856         cancellable: bool,
1857     ) -> Result<Option<(Event, Option<(Waitable, u32)>)>> {
1858         let state = store.concurrent_state_mut();
1859 
1860         if let Some(event) = state.get_mut(guest_task)?.event.take() {
1861             log::trace!("deliver event {event:?} to {guest_task:?}");
1862 
1863             if cancellable || !matches!(event, Event::Cancelled) {
1864                 return Ok(Some((event, None)));
1865             } else {
1866                 state.get_mut(guest_task)?.event = Some(event);
1867             }
1868         }
1869 
1870         Ok(
1871             if let Some((set, waitable)) = set
1872                 .and_then(|set| {
1873                     state
1874                         .get_mut(set)
1875                         .map(|v| v.ready.pop_first().map(|v| (set, v)))
1876                         .transpose()
1877                 })
1878                 .transpose()?
1879             {
1880                 let common = waitable.common(state)?;
1881                 let handle = common.handle.unwrap();
1882                 let event = common.event.take().unwrap();
1883 
1884                 log::trace!(
1885                     "deliver event {event:?} to {guest_task:?} for {waitable:?} (handle {handle}); set {set:?}"
1886                 );
1887 
1888                 waitable.on_delivery(store, self, event);
1889 
1890                 Some((event, Some((waitable, handle))))
1891             } else {
1892                 None
1893             },
1894         )
1895     }
1896 
1897     /// Handle the `CallbackCode` returned from an async-lifted export or its
1898     /// callback.
1899     ///
1900     /// If this returns `Ok(Some(call))`, then `call` should be run immediately
1901     /// using `handle_guest_call`.
1902     fn handle_callback_code(
1903         self,
1904         store: &mut StoreOpaque,
1905         guest_thread: QualifiedThreadId,
1906         runtime_instance: RuntimeComponentInstanceIndex,
1907         code: u32,
1908     ) -> Result<Option<GuestCall>> {
1909         let (code, set) = unpack_callback_code(code);
1910 
1911         log::trace!("received callback code from {guest_thread:?}: {code} (set: {set})");
1912 
1913         let state = store.concurrent_state_mut();
1914 
1915         let get_set = |store: &mut StoreOpaque, handle| {
1916             if handle == 0 {
1917                 bail!("invalid waitable-set handle");
1918             }
1919 
1920             let set = store
1921                 .handle_table(RuntimeInstance {
1922                     instance: self.id().instance(),
1923                     index: runtime_instance,
1924                 })
1925                 .waitable_set_rep(handle)?;
1926 
1927             Ok(TableId::<WaitableSet>::new(set))
1928         };
1929 
1930         Ok(match code {
1931             callback_code::EXIT => {
1932                 log::trace!("implicit thread {guest_thread:?} completed");
1933                 self.cleanup_thread(store, guest_thread, runtime_instance)?;
1934                 let task = store.concurrent_state_mut().get_mut(guest_thread.task)?;
1935                 if task.threads.is_empty() && !task.returned_or_cancelled() {
1936                     bail!(Trap::NoAsyncResult);
1937                 }
1938                 match &task.caller {
1939                     Caller::Host { .. } => {
1940                         if task.ready_to_delete() {
1941                             Waitable::Guest(guest_thread.task)
1942                                 .delete_from(store.concurrent_state_mut())?;
1943                         }
1944                     }
1945                     Caller::Guest { .. } => {
1946                         task.exited = true;
1947                         task.callback = None;
1948                     }
1949                 }
1950                 None
1951             }
1952             callback_code::YIELD => {
1953                 let task = state.get_mut(guest_thread.task)?;
1954                 // If an `Event::Cancelled` is pending, we'll deliver that;
1955                 // otherwise, we'll deliver `Event::None`.  Note that
1956                 // `GuestTask::event` is only ever set to one of those two
1957                 // `Event` variants.
1958                 if let Some(event) = task.event {
1959                     assert!(matches!(event, Event::None | Event::Cancelled));
1960                 } else {
1961                     task.event = Some(Event::None);
1962                 }
1963                 let call = GuestCall {
1964                     thread: guest_thread,
1965                     kind: GuestCallKind::DeliverEvent {
1966                         instance: self,
1967                         set: None,
1968                     },
1969                 };
1970                 if state.may_block(guest_thread.task) {
1971                     // Push this thread onto the "low priority" queue so it runs
1972                     // after any other threads have had a chance to run.
1973                     state.push_low_priority(WorkItem::GuestCall(call));
1974                     None
1975                 } else {
1976                     // Yielding in a non-blocking context is defined as a no-op
1977                     // according to the spec, so we must run this thread
1978                     // immediately without allowing any others to run.
1979                     Some(call)
1980                 }
1981             }
1982             callback_code::WAIT => {
1983                 // The task may only return `WAIT` if it was created for a call
1984                 // to an async export).  Otherwise, we'll trap.
1985                 state.check_blocking_for(guest_thread.task)?;
1986 
1987                 let set = get_set(store, set)?;
1988                 let state = store.concurrent_state_mut();
1989 
1990                 if state.get_mut(guest_thread.task)?.event.is_some()
1991                     || !state.get_mut(set)?.ready.is_empty()
1992                 {
1993                     // An event is immediately available; deliver it ASAP.
1994                     state.push_high_priority(WorkItem::GuestCall(GuestCall {
1995                         thread: guest_thread,
1996                         kind: GuestCallKind::DeliverEvent {
1997                             instance: self,
1998                             set: Some(set),
1999                         },
2000                     }));
2001                 } else {
2002                     // No event is immediately available.
2003                     //
2004                     // We're waiting, so register to be woken up when an event
2005                     // is published for this waitable set.
2006                     //
2007                     // Here we also set `GuestTask::wake_on_cancel` which allows
2008                     // `subtask.cancel` to interrupt the wait.
2009                     let old = state
2010                         .get_mut(guest_thread.thread)?
2011                         .wake_on_cancel
2012                         .replace(set);
2013                     assert!(old.is_none());
2014                     let old = state
2015                         .get_mut(set)?
2016                         .waiting
2017                         .insert(guest_thread, WaitMode::Callback(self));
2018                     assert!(old.is_none());
2019                 }
2020                 None
2021             }
2022             _ => bail!("unsupported callback code: {code}"),
2023         })
2024     }
2025 
2026     fn cleanup_thread(
2027         self,
2028         store: &mut StoreOpaque,
2029         guest_thread: QualifiedThreadId,
2030         runtime_instance: RuntimeComponentInstanceIndex,
2031     ) -> Result<()> {
2032         let guest_id = store
2033             .concurrent_state_mut()
2034             .get_mut(guest_thread.thread)?
2035             .instance_rep;
2036         store
2037             .handle_table(RuntimeInstance {
2038                 instance: self.id().instance(),
2039                 index: runtime_instance,
2040             })
2041             .guest_thread_remove(guest_id.unwrap())?;
2042 
2043         store.concurrent_state_mut().delete(guest_thread.thread)?;
2044         let task = store.concurrent_state_mut().get_mut(guest_thread.task)?;
2045         task.threads.remove(&guest_thread.thread);
2046         Ok(())
2047     }
2048 
2049     /// Add the specified guest call to the "high priority" work item queue, to
2050     /// be started as soon as backpressure and/or reentrance rules allow.
2051     ///
2052     /// SAFETY: The raw pointer arguments must be valid references to guest
2053     /// functions (with the appropriate signatures) when the closures queued by
2054     /// this function are called.
2055     unsafe fn queue_call<T: 'static>(
2056         self,
2057         mut store: StoreContextMut<T>,
2058         guest_thread: QualifiedThreadId,
2059         callee: SendSyncPtr<VMFuncRef>,
2060         param_count: usize,
2061         result_count: usize,
2062         async_: bool,
2063         callback: Option<SendSyncPtr<VMFuncRef>>,
2064         post_return: Option<SendSyncPtr<VMFuncRef>>,
2065     ) -> Result<()> {
2066         /// Return a closure which will call the specified function in the scope
2067         /// of the specified task.
2068         ///
2069         /// This will use `GuestTask::lower_params` to lower the parameters, but
2070         /// will not lift the result; instead, it returns a
2071         /// `[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]` from which the result, if
2072         /// any, may be lifted.  Note that an async-lifted export will have
2073         /// returned its result using the `task.return` intrinsic (or not
2074         /// returned a result at all, in the case of `task.cancel`), in which
2075         /// case the "result" of this call will either be a callback code or
2076         /// nothing.
2077         ///
2078         /// SAFETY: `callee` must be a valid `*mut VMFuncRef` at the time when
2079         /// the returned closure is called.
2080         unsafe fn make_call<T: 'static>(
2081             store: StoreContextMut<T>,
2082             guest_thread: QualifiedThreadId,
2083             callee: SendSyncPtr<VMFuncRef>,
2084             param_count: usize,
2085             result_count: usize,
2086         ) -> impl FnOnce(&mut dyn VMStore) -> Result<[MaybeUninit<ValRaw>; MAX_FLAT_PARAMS]>
2087         + Send
2088         + Sync
2089         + 'static
2090         + use<T> {
2091             let token = StoreToken::new(store);
2092             move |store: &mut dyn VMStore| {
2093                 let mut storage = [MaybeUninit::uninit(); MAX_FLAT_PARAMS];
2094 
2095                 store
2096                     .concurrent_state_mut()
2097                     .get_mut(guest_thread.thread)?
2098                     .state = GuestThreadState::Running;
2099                 let task = store.concurrent_state_mut().get_mut(guest_thread.task)?;
2100                 let lower = task.lower_params.take().unwrap();
2101 
2102                 lower(store, &mut storage[..param_count])?;
2103 
2104                 let mut store = token.as_context_mut(store);
2105 
2106                 // SAFETY: Per the contract documented in `make_call's`
2107                 // documentation, `callee` must be a valid pointer.
2108                 unsafe {
2109                     crate::Func::call_unchecked_raw(
2110                         &mut store,
2111                         callee.as_non_null(),
2112                         NonNull::new(
2113                             &mut storage[..param_count.max(result_count)]
2114                                 as *mut [MaybeUninit<ValRaw>] as _,
2115                         )
2116                         .unwrap(),
2117                     )?;
2118                 }
2119 
2120                 Ok(storage)
2121             }
2122         }
2123 
2124         // SAFETY: Per the contract described in this function documentation,
2125         // the `callee` pointer which `call` closes over must be valid when
2126         // called by the closure we queue below.
2127         let call = unsafe {
2128             make_call(
2129                 store.as_context_mut(),
2130                 guest_thread,
2131                 callee,
2132                 param_count,
2133                 result_count,
2134             )
2135         };
2136 
2137         let callee_instance = store
2138             .0
2139             .concurrent_state_mut()
2140             .get_mut(guest_thread.task)?
2141             .instance;
2142 
2143         let fun = if callback.is_some() {
2144             assert!(async_);
2145 
2146             Box::new(move |store: &mut dyn VMStore| {
2147                 self.add_guest_thread_to_instance_table(
2148                     guest_thread.thread,
2149                     store,
2150                     callee_instance.index,
2151                 )?;
2152                 let old_thread = store.set_thread(Some(guest_thread));
2153                 log::trace!(
2154                     "stackless call: replaced {old_thread:?} with {guest_thread:?} as current thread"
2155                 );
2156 
2157                 store.maybe_push_call_context(guest_thread.task)?;
2158 
2159                 store.enter_instance(callee_instance);
2160 
2161                 // SAFETY: See the documentation for `make_call` to review the
2162                 // contract we must uphold for `call` here.
2163                 //
2164                 // Per the contract described in the `queue_call`
2165                 // documentation, the `callee` pointer which `call` closes
2166                 // over must be valid.
2167                 let storage = call(store)?;
2168 
2169                 store.exit_instance(callee_instance)?;
2170 
2171                 store.maybe_pop_call_context(guest_thread.task)?;
2172 
2173                 store.set_thread(old_thread);
2174                 let state = store.concurrent_state_mut();
2175                 old_thread
2176                     .map(|t| state.get_mut(t.thread).unwrap().state = GuestThreadState::Running);
2177                 log::trace!("stackless call: restored {old_thread:?} as current thread");
2178 
2179                 // SAFETY: `wasmparser` will have validated that the callback
2180                 // function returns a `i32` result.
2181                 let code = unsafe { storage[0].assume_init() }.get_i32() as u32;
2182 
2183                 self.handle_callback_code(store, guest_thread, callee_instance.index, code)
2184             })
2185                 as Box<dyn FnOnce(&mut dyn VMStore) -> Result<Option<GuestCall>> + Send + Sync>
2186         } else {
2187             let token = StoreToken::new(store.as_context_mut());
2188             Box::new(move |store: &mut dyn VMStore| {
2189                 self.add_guest_thread_to_instance_table(
2190                     guest_thread.thread,
2191                     store,
2192                     callee_instance.index,
2193                 )?;
2194                 let old_thread = store.set_thread(Some(guest_thread));
2195                 log::trace!(
2196                     "sync/async-stackful call: replaced {old_thread:?} with {guest_thread:?} as current thread",
2197                 );
2198                 let flags = self.id().get(store).instance_flags(callee_instance.index);
2199 
2200                 store.maybe_push_call_context(guest_thread.task)?;
2201 
2202                 // Unless this is a callback-less (i.e. stackful)
2203                 // async-lifted export, we need to record that the instance
2204                 // cannot be entered until the call returns.
2205                 if !async_ {
2206                     store.enter_instance(callee_instance);
2207                 }
2208 
2209                 // SAFETY: See the documentation for `make_call` to review the
2210                 // contract we must uphold for `call` here.
2211                 //
2212                 // Per the contract described in the `queue_call`
2213                 // documentation, the `callee` pointer which `call` closes
2214                 // over must be valid.
2215                 let storage = call(store)?;
2216 
2217                 if async_ {
2218                     let task = store.concurrent_state_mut().get_mut(guest_thread.task)?;
2219                     if task.threads.len() == 1 && !task.returned_or_cancelled() {
2220                         bail!(Trap::NoAsyncResult);
2221                     }
2222                 } else {
2223                     // This is a sync-lifted export, so now is when we lift the
2224                     // result, optionally call the post-return function, if any,
2225                     // and finally notify any current or future waiters that the
2226                     // subtask has returned.
2227 
2228                     let lift = {
2229                         store.exit_instance(callee_instance)?;
2230 
2231                         let state = store.concurrent_state_mut();
2232                         assert!(state.get_mut(guest_thread.task)?.result.is_none());
2233 
2234                         state
2235                             .get_mut(guest_thread.task)?
2236                             .lift_result
2237                             .take()
2238                             .unwrap()
2239                     };
2240 
2241                     // SAFETY: `result_count` represents the number of core Wasm
2242                     // results returned, per `wasmparser`.
2243                     let result = (lift.lift)(store, unsafe {
2244                         mem::transmute::<&[MaybeUninit<ValRaw>], &[ValRaw]>(
2245                             &storage[..result_count],
2246                         )
2247                     })?;
2248 
2249                     let post_return_arg = match result_count {
2250                         0 => ValRaw::i32(0),
2251                         // SAFETY: `result_count` represents the number of
2252                         // core Wasm results returned, per `wasmparser`.
2253                         1 => unsafe { storage[0].assume_init() },
2254                         _ => unreachable!(),
2255                     };
2256 
2257                     unsafe {
2258                         call_post_return(
2259                             token.as_context_mut(store),
2260                             post_return.map(|v| v.as_non_null()),
2261                             post_return_arg,
2262                             flags,
2263                         )?;
2264                     }
2265 
2266                     self.task_complete(store, guest_thread.task, result, Status::Returned)?;
2267                 }
2268 
2269                 // This is a callback-less call, so the implicit thread has now completed
2270                 self.cleanup_thread(store, guest_thread, callee_instance.index)?;
2271 
2272                 store.set_thread(old_thread);
2273 
2274                 store.maybe_pop_call_context(guest_thread.task)?;
2275 
2276                 let state = store.concurrent_state_mut();
2277                 let task = state.get_mut(guest_thread.task)?;
2278 
2279                 match &task.caller {
2280                     Caller::Host { .. } => {
2281                         if task.ready_to_delete() {
2282                             Waitable::Guest(guest_thread.task).delete_from(state)?;
2283                         }
2284                     }
2285                     Caller::Guest { .. } => {
2286                         task.exited = true;
2287                     }
2288                 }
2289 
2290                 Ok(None)
2291             })
2292         };
2293 
2294         store
2295             .0
2296             .concurrent_state_mut()
2297             .push_high_priority(WorkItem::GuestCall(GuestCall {
2298                 thread: guest_thread,
2299                 kind: GuestCallKind::StartImplicit(fun),
2300             }));
2301 
2302         Ok(())
2303     }
2304 
2305     /// Prepare (but do not start) a guest->guest call.
2306     ///
2307     /// This is called from fused adapter code generated in
2308     /// `wasmtime_environ::fact::trampoline::Compiler`.  `start` and `return_`
2309     /// are synthesized Wasm functions which move the parameters from the caller
2310     /// to the callee and the result from the callee to the caller,
2311     /// respectively.  The adapter will call `Self::start_call` immediately
2312     /// after calling this function.
2313     ///
2314     /// SAFETY: All the pointer arguments must be valid pointers to guest
2315     /// entities (and with the expected signatures for the function references
2316     /// -- see `wasmtime_environ::fact::trampoline::Compiler` for details).
2317     unsafe fn prepare_call<T: 'static>(
2318         self,
2319         mut store: StoreContextMut<T>,
2320         start: *mut VMFuncRef,
2321         return_: *mut VMFuncRef,
2322         caller_instance: RuntimeComponentInstanceIndex,
2323         callee_instance: RuntimeComponentInstanceIndex,
2324         task_return_type: TypeTupleIndex,
2325         callee_async: bool,
2326         memory: *mut VMMemoryDefinition,
2327         string_encoding: u8,
2328         caller_info: CallerInfo,
2329     ) -> Result<()> {
2330         if let (CallerInfo::Sync { .. }, true) = (&caller_info, callee_async) {
2331             // A task may only call an async-typed function via a sync lower if
2332             // it was created by a call to an async export.  Otherwise, we'll
2333             // trap.
2334             store.0.check_blocking()?;
2335         }
2336 
2337         enum ResultInfo {
2338             Heap { results: u32 },
2339             Stack { result_count: u32 },
2340         }
2341 
2342         let result_info = match &caller_info {
2343             CallerInfo::Async {
2344                 has_result: true,
2345                 params,
2346             } => ResultInfo::Heap {
2347                 results: params.last().unwrap().get_u32(),
2348             },
2349             CallerInfo::Async {
2350                 has_result: false, ..
2351             } => ResultInfo::Stack { result_count: 0 },
2352             CallerInfo::Sync {
2353                 result_count,
2354                 params,
2355             } if *result_count > u32::try_from(MAX_FLAT_RESULTS).unwrap() => ResultInfo::Heap {
2356                 results: params.last().unwrap().get_u32(),
2357             },
2358             CallerInfo::Sync { result_count, .. } => ResultInfo::Stack {
2359                 result_count: *result_count,
2360             },
2361         };
2362 
2363         let sync_caller = matches!(caller_info, CallerInfo::Sync { .. });
2364 
2365         // Create a new guest task for the call, closing over the `start` and
2366         // `return_` functions to lift the parameters and lower the result,
2367         // respectively.
2368         let start = SendSyncPtr::new(NonNull::new(start).unwrap());
2369         let return_ = SendSyncPtr::new(NonNull::new(return_).unwrap());
2370         let token = StoreToken::new(store.as_context_mut());
2371         let state = store.0.concurrent_state_mut();
2372         let old_thread = state.guest_thread.unwrap();
2373 
2374         assert_eq!(
2375             state.get_mut(old_thread.task)?.instance,
2376             RuntimeInstance {
2377                 instance: self.id().instance(),
2378                 index: caller_instance,
2379             }
2380         );
2381 
2382         let new_task = GuestTask::new(
2383             state,
2384             Box::new(move |store, dst| {
2385                 let mut store = token.as_context_mut(store);
2386                 assert!(dst.len() <= MAX_FLAT_PARAMS);
2387                 // The `+ 1` here accounts for the return pointer, if any:
2388                 let mut src = [MaybeUninit::uninit(); MAX_FLAT_PARAMS + 1];
2389                 let count = match caller_info {
2390                     // Async callers, if they have a result, use the last
2391                     // parameter as a return pointer so chop that off if
2392                     // relevant here.
2393                     CallerInfo::Async { params, has_result } => {
2394                         let params = &params[..params.len() - usize::from(has_result)];
2395                         for (param, src) in params.iter().zip(&mut src) {
2396                             src.write(*param);
2397                         }
2398                         params.len()
2399                     }
2400 
2401                     // Sync callers forward everything directly.
2402                     CallerInfo::Sync { params, .. } => {
2403                         for (param, src) in params.iter().zip(&mut src) {
2404                             src.write(*param);
2405                         }
2406                         params.len()
2407                     }
2408                 };
2409                 // SAFETY: `start` is a valid `*mut VMFuncRef` from
2410                 // `wasmtime-cranelift`-generated fused adapter code.  Based on
2411                 // how it was constructed (see
2412                 // `wasmtime_environ::fact::trampoline::Compiler::compile_async_start_adapter`
2413                 // for details) we know it takes count parameters and returns
2414                 // `dst.len()` results.
2415                 unsafe {
2416                     crate::Func::call_unchecked_raw(
2417                         &mut store,
2418                         start.as_non_null(),
2419                         NonNull::new(
2420                             &mut src[..count.max(dst.len())] as *mut [MaybeUninit<ValRaw>] as _,
2421                         )
2422                         .unwrap(),
2423                     )?;
2424                 }
2425                 dst.copy_from_slice(&src[..dst.len()]);
2426                 let state = store.0.concurrent_state_mut();
2427                 Waitable::Guest(state.guest_thread.unwrap().task).set_event(
2428                     state,
2429                     Some(Event::Subtask {
2430                         status: Status::Started,
2431                     }),
2432                 )?;
2433                 Ok(())
2434             }),
2435             LiftResult {
2436                 lift: Box::new(move |store, src| {
2437                     // SAFETY: See comment in closure passed as `lower_params`
2438                     // parameter above.
2439                     let mut store = token.as_context_mut(store);
2440                     let mut my_src = src.to_owned(); // TODO: use stack to avoid allocation?
2441                     if let ResultInfo::Heap { results } = &result_info {
2442                         my_src.push(ValRaw::u32(*results));
2443                     }
2444                     // SAFETY: `return_` is a valid `*mut VMFuncRef` from
2445                     // `wasmtime-cranelift`-generated fused adapter code.  Based
2446                     // on how it was constructed (see
2447                     // `wasmtime_environ::fact::trampoline::Compiler::compile_async_return_adapter`
2448                     // for details) we know it takes `src.len()` parameters and
2449                     // returns up to 1 result.
2450                     unsafe {
2451                         crate::Func::call_unchecked_raw(
2452                             &mut store,
2453                             return_.as_non_null(),
2454                             my_src.as_mut_slice().into(),
2455                         )?;
2456                     }
2457                     let state = store.0.concurrent_state_mut();
2458                     let thread = state.guest_thread.unwrap();
2459                     if sync_caller {
2460                         state.get_mut(thread.task)?.sync_result = SyncResult::Produced(
2461                             if let ResultInfo::Stack { result_count } = &result_info {
2462                                 match result_count {
2463                                     0 => None,
2464                                     1 => Some(my_src[0]),
2465                                     _ => unreachable!(),
2466                                 }
2467                             } else {
2468                                 None
2469                             },
2470                         );
2471                     }
2472                     Ok(Box::new(DummyResult) as Box<dyn Any + Send + Sync>)
2473                 }),
2474                 ty: task_return_type,
2475                 memory: NonNull::new(memory).map(SendSyncPtr::new),
2476                 string_encoding: StringEncoding::from_u8(string_encoding).unwrap(),
2477             },
2478             Caller::Guest { thread: old_thread },
2479             None,
2480             RuntimeInstance {
2481                 instance: self.id().instance(),
2482                 index: callee_instance,
2483             },
2484             callee_async,
2485         )?;
2486 
2487         let guest_task = state.push(new_task)?;
2488         let new_thread = GuestThread::new_implicit(guest_task);
2489         let guest_thread = state.push(new_thread)?;
2490         state.get_mut(guest_task)?.threads.insert(guest_thread);
2491 
2492         store
2493             .0
2494             .concurrent_state_mut()
2495             .get_mut(old_thread.task)?
2496             .subtasks
2497             .insert(guest_task);
2498 
2499         // Make the new thread the current one so that `Self::start_call` knows
2500         // which one to start.
2501         store.0.set_thread(Some(QualifiedThreadId {
2502             task: guest_task,
2503             thread: guest_thread,
2504         }));
2505         log::trace!(
2506             "pushed {guest_task:?}:{guest_thread:?} as current thread; old thread was {old_thread:?}"
2507         );
2508 
2509         Ok(())
2510     }
2511 
2512     /// Call the specified callback function for an async-lifted export.
2513     ///
2514     /// SAFETY: `function` must be a valid reference to a guest function of the
2515     /// correct signature for a callback.
2516     unsafe fn call_callback<T>(
2517         self,
2518         mut store: StoreContextMut<T>,
2519         function: SendSyncPtr<VMFuncRef>,
2520         event: Event,
2521         handle: u32,
2522     ) -> Result<u32> {
2523         let (ordinal, result) = event.parts();
2524         let params = &mut [
2525             ValRaw::u32(ordinal),
2526             ValRaw::u32(handle),
2527             ValRaw::u32(result),
2528         ];
2529         // SAFETY: `func` is a valid `*mut VMFuncRef` from either
2530         // `wasmtime-cranelift`-generated fused adapter code or
2531         // `component::Options`.  Per `wasmparser` callback signature
2532         // validation, we know it takes three parameters and returns one.
2533         unsafe {
2534             crate::Func::call_unchecked_raw(
2535                 &mut store,
2536                 function.as_non_null(),
2537                 params.as_mut_slice().into(),
2538             )?;
2539         }
2540         Ok(params[0].get_u32())
2541     }
2542 
2543     /// Start a guest->guest call previously prepared using
2544     /// `Self::prepare_call`.
2545     ///
2546     /// This is called from fused adapter code generated in
2547     /// `wasmtime_environ::fact::trampoline::Compiler`.  The adapter will call
2548     /// this function immediately after calling `Self::prepare_call`.
2549     ///
2550     /// SAFETY: The `*mut VMFuncRef` arguments must be valid pointers to guest
2551     /// functions with the appropriate signatures for the current guest task.
2552     /// If this is a call to an async-lowered import, the actual call may be
2553     /// deferred and run after this function returns, in which case the pointer
2554     /// arguments must also be valid when the call happens.
2555     unsafe fn start_call<T: 'static>(
2556         self,
2557         mut store: StoreContextMut<T>,
2558         callback: *mut VMFuncRef,
2559         post_return: *mut VMFuncRef,
2560         callee: *mut VMFuncRef,
2561         param_count: u32,
2562         result_count: u32,
2563         flags: u32,
2564         storage: Option<&mut [MaybeUninit<ValRaw>]>,
2565     ) -> Result<u32> {
2566         let token = StoreToken::new(store.as_context_mut());
2567         let async_caller = storage.is_none();
2568         let state = store.0.concurrent_state_mut();
2569         let guest_thread = state.guest_thread.unwrap();
2570         let callee_async = state.get_mut(guest_thread.task)?.async_function;
2571         let callee = SendSyncPtr::new(NonNull::new(callee).unwrap());
2572         let param_count = usize::try_from(param_count).unwrap();
2573         assert!(param_count <= MAX_FLAT_PARAMS);
2574         let result_count = usize::try_from(result_count).unwrap();
2575         assert!(result_count <= MAX_FLAT_RESULTS);
2576 
2577         let task = state.get_mut(guest_thread.task)?;
2578         if !callback.is_null() {
2579             // We're calling an async-lifted export with a callback, so store
2580             // the callback and related context as part of the task so we can
2581             // call it later when needed.
2582             let callback = SendSyncPtr::new(NonNull::new(callback).unwrap());
2583             task.callback = Some(Box::new(move |store, event, handle| {
2584                 let store = token.as_context_mut(store);
2585                 unsafe { self.call_callback::<T>(store, callback, event, handle) }
2586             }));
2587         }
2588 
2589         let Caller::Guest { thread: caller } = &task.caller else {
2590             // As of this writing, `start_call` is only used for guest->guest
2591             // calls.
2592             unreachable!()
2593         };
2594         let caller = *caller;
2595         let caller_instance = state.get_mut(caller.task)?.instance;
2596 
2597         // Queue the call as a "high priority" work item.
2598         unsafe {
2599             self.queue_call(
2600                 store.as_context_mut(),
2601                 guest_thread,
2602                 callee,
2603                 param_count,
2604                 result_count,
2605                 (flags & START_FLAG_ASYNC_CALLEE) != 0,
2606                 NonNull::new(callback).map(SendSyncPtr::new),
2607                 NonNull::new(post_return).map(SendSyncPtr::new),
2608             )?;
2609         }
2610 
2611         let state = store.0.concurrent_state_mut();
2612 
2613         // Use the caller's `GuestTask::sync_call_set` to register interest in
2614         // the subtask...
2615         let guest_waitable = Waitable::Guest(guest_thread.task);
2616         let old_set = guest_waitable.common(state)?.set;
2617         let set = state.get_mut(caller.task)?.sync_call_set;
2618         guest_waitable.join(state, Some(set))?;
2619 
2620         // ... and suspend this fiber temporarily while we wait for it to start.
2621         //
2622         // Note that we _could_ call the callee directly using the current fiber
2623         // rather than suspend this one, but that would make reasoning about the
2624         // event loop more complicated and is probably only worth doing if
2625         // there's a measurable performance benefit.  In addition, it would mean
2626         // blocking the caller if the callee calls a blocking sync-lowered
2627         // import, and as of this writing the spec says we must not do that.
2628         //
2629         // Alternatively, the fused adapter code could be modified to call the
2630         // callee directly without calling a host-provided intrinsic at all (in
2631         // which case it would need to do its own, inline backpressure checks,
2632         // etc.).  Again, we'd want to see a measurable performance benefit
2633         // before committing to such an optimization.  And again, we'd need to
2634         // update the spec to allow that.
2635         let (status, waitable) = loop {
2636             store.0.suspend(SuspendReason::Waiting {
2637                 set,
2638                 thread: caller,
2639                 // Normally, `StoreOpaque::suspend` would assert it's being
2640                 // called from a context where blocking is allowed.  However, if
2641                 // `async_caller` is `true`, we'll only "block" long enough for
2642                 // the callee to start, i.e. we won't repeat this loop, so we
2643                 // tell `suspend` it's okay even if we're not allowed to block.
2644                 // Alternatively, if the callee is not an async function, then
2645                 // we know it won't block anyway.
2646                 skip_may_block_check: async_caller || !callee_async,
2647             })?;
2648 
2649             let state = store.0.concurrent_state_mut();
2650 
2651             log::trace!("taking event for {:?}", guest_thread.task);
2652             let event = guest_waitable.take_event(state)?;
2653             let Some(Event::Subtask { status }) = event else {
2654                 unreachable!();
2655             };
2656 
2657             log::trace!("status {status:?} for {:?}", guest_thread.task);
2658 
2659             if status == Status::Returned {
2660                 // It returned, so we can stop waiting.
2661                 break (status, None);
2662             } else if async_caller {
2663                 // It hasn't returned yet, but the caller is calling via an
2664                 // async-lowered import, so we generate a handle for the task
2665                 // waitable and return the status.
2666                 let handle = store
2667                     .0
2668                     .handle_table(caller_instance)
2669                     .subtask_insert_guest(guest_thread.task.rep())?;
2670                 store
2671                     .0
2672                     .concurrent_state_mut()
2673                     .get_mut(guest_thread.task)?
2674                     .common
2675                     .handle = Some(handle);
2676                 break (status, Some(handle));
2677             } else {
2678                 // The callee hasn't returned yet, and the caller is calling via
2679                 // a sync-lowered import, so we loop and keep waiting until the
2680                 // callee returns.
2681             }
2682         };
2683 
2684         guest_waitable.join(store.0.concurrent_state_mut(), old_set)?;
2685 
2686         // Reset the current thread to point to the caller as it resumes control.
2687         store.0.set_thread(Some(caller));
2688         store.0.concurrent_state_mut().get_mut(caller.thread)?.state = GuestThreadState::Running;
2689         log::trace!("popped current thread {guest_thread:?}; new thread is {caller:?}");
2690 
2691         if let Some(storage) = storage {
2692             // The caller used a sync-lowered import to call an async-lifted
2693             // export, in which case the result, if any, has been stashed in
2694             // `GuestTask::sync_result`.
2695             let state = store.0.concurrent_state_mut();
2696             let task = state.get_mut(guest_thread.task)?;
2697             if let Some(result) = task.sync_result.take() {
2698                 if let Some(result) = result {
2699                     storage[0] = MaybeUninit::new(result);
2700                 }
2701 
2702                 if task.exited && task.ready_to_delete() {
2703                     Waitable::Guest(guest_thread.task).delete_from(state)?;
2704                 }
2705             }
2706         }
2707 
2708         Ok(status.pack(waitable))
2709     }
2710 
2711     /// Poll the specified future once on behalf of a guest->host call using an
2712     /// async-lowered import.
2713     ///
2714     /// If it returns `Ready`, return `Ok(None)`.  Otherwise, if it returns
2715     /// `Pending`, add it to the set of futures to be polled as part of this
2716     /// instance's event loop until it completes, and then return
2717     /// `Ok(Some(handle))` where `handle` is the waitable handle to return.
2718     ///
2719     /// Whether the future returns `Ready` immediately or later, the `lower`
2720     /// function will be used to lower the result, if any, into the guest caller's
2721     /// stack and linear memory unless the task has been cancelled.
2722     pub(crate) fn first_poll<T: 'static, R: Send + 'static>(
2723         self,
2724         mut store: StoreContextMut<'_, T>,
2725         future: impl Future<Output = Result<R>> + Send + 'static,
2726         caller_instance: RuntimeComponentInstanceIndex,
2727         lower: impl FnOnce(StoreContextMut<T>, R) -> Result<()> + Send + 'static,
2728     ) -> Result<Option<u32>> {
2729         let token = StoreToken::new(store.as_context_mut());
2730         let state = store.0.concurrent_state_mut();
2731         let caller = state.guest_thread.unwrap();
2732 
2733         // Create an abortable future which hooks calls to poll and manages call
2734         // context state for the future.
2735         let (join_handle, future) = JoinHandle::run(async move {
2736             let mut future = pin!(future);
2737             let mut call_context = None;
2738             future::poll_fn(move |cx| {
2739                 // Push the call context for managing any resource borrows
2740                 // for the task.
2741                 tls::get(|store| {
2742                     if let Some(call_context) = call_context.take() {
2743                         token
2744                             .as_context_mut(store)
2745                             .0
2746                             .component_resource_state()
2747                             .0
2748                             .push(call_context);
2749                     }
2750                 });
2751 
2752                 let result = future.as_mut().poll(cx);
2753 
2754                 if result.is_pending() {
2755                     // Pop the call context for managing any resource
2756                     // borrows for the task.
2757                     tls::get(|store| {
2758                         call_context = Some(
2759                             token
2760                                 .as_context_mut(store)
2761                                 .0
2762                                 .component_resource_state()
2763                                 .0
2764                                 .pop()
2765                                 .unwrap(),
2766                         );
2767                     });
2768                 }
2769                 result
2770             })
2771             .await
2772         });
2773 
2774         // We create a new host task even though it might complete immediately
2775         // (in which case we won't need to pass a waitable back to the guest).
2776         // If it does complete immediately, we'll remove it before we return.
2777         let task = state.push(HostTask::new(
2778             RuntimeInstance {
2779                 instance: self.id().instance(),
2780                 index: caller_instance,
2781             },
2782             Some(join_handle),
2783         ))?;
2784 
2785         log::trace!("new host task child of {caller:?}: {task:?}");
2786 
2787         let mut future = Box::pin(future);
2788 
2789         // Finally, poll the future.  We can use a dummy `Waker` here because
2790         // we'll add the future to `ConcurrentState::futures` and poll it
2791         // automatically from the event loop if it doesn't complete immediately
2792         // here.
2793         let poll = tls::set(store.0, || {
2794             future
2795                 .as_mut()
2796                 .poll(&mut Context::from_waker(&Waker::noop()))
2797         });
2798 
2799         Ok(match poll {
2800             Poll::Ready(None) => unreachable!(),
2801             Poll::Ready(Some(result)) => {
2802                 // It finished immediately; lower the result and delete the
2803                 // task.
2804                 lower(store.as_context_mut(), result?)?;
2805                 log::trace!("delete host task {task:?} (already ready)");
2806                 store.0.concurrent_state_mut().delete(task)?;
2807                 None
2808             }
2809             Poll::Pending => {
2810                 // It hasn't finished yet; add the future to
2811                 // `ConcurrentState::futures` so it will be polled by the event
2812                 // loop and allocate a waitable handle to return to the guest.
2813 
2814                 // Wrap the future in a closure responsible for lowering the result into
2815                 // the guest's stack and memory, as well as notifying any waiters that
2816                 // the task returned.
2817                 let future =
2818                     Box::pin(async move {
2819                         let result = match future.await {
2820                             Some(result) => result?,
2821                             // Task was cancelled; nothing left to do.
2822                             None => return Ok(()),
2823                         };
2824                         tls::get(move |store| {
2825                             // Here we schedule a task to run on a worker fiber to do
2826                             // the lowering since it may involve a call to the guest's
2827                             // realloc function.  This is necessary because calling the
2828                             // guest while there are host embedder frames on the stack
2829                             // is unsound.
2830                             store.concurrent_state_mut().push_high_priority(
2831                                 WorkItem::WorkerFunction(AlwaysMut::new(Box::new(move |store| {
2832                                     lower(token.as_context_mut(store), result)?;
2833                                     let state = store.concurrent_state_mut();
2834                                     state.get_mut(task)?.join_handle.take();
2835                                     Waitable::Host(task).set_event(
2836                                         state,
2837                                         Some(Event::Subtask {
2838                                             status: Status::Returned,
2839                                         }),
2840                                     )
2841                                 }))),
2842                             );
2843                             Ok(())
2844                         })
2845                     });
2846 
2847                 store.0.concurrent_state_mut().push_future(future);
2848                 let handle = store
2849                     .0
2850                     .handle_table(RuntimeInstance {
2851                         instance: self.id().instance(),
2852                         index: caller_instance,
2853                     })
2854                     .subtask_insert_host(task.rep())?;
2855                 store.0.concurrent_state_mut().get_mut(task)?.common.handle = Some(handle);
2856                 log::trace!(
2857                     "assign {task:?} handle {handle} for {caller:?} instance {caller_instance:?}"
2858                 );
2859                 Some(handle)
2860             }
2861         })
2862     }
2863 
2864     /// Implements the `task.return` intrinsic, lifting the result for the
2865     /// current guest task.
2866     pub(crate) fn task_return(
2867         self,
2868         store: &mut dyn VMStore,
2869         ty: TypeTupleIndex,
2870         options: OptionsIndex,
2871         storage: &[ValRaw],
2872     ) -> Result<()> {
2873         let state = store.concurrent_state_mut();
2874         let guest_thread = state.guest_thread.unwrap();
2875         let lift = state
2876             .get_mut(guest_thread.task)?
2877             .lift_result
2878             .take()
2879             .ok_or_else(|| {
2880                 format_err!("`task.return` or `task.cancel` called more than once for current task")
2881             })?;
2882         assert!(state.get_mut(guest_thread.task)?.result.is_none());
2883 
2884         let CanonicalOptions {
2885             string_encoding,
2886             data_model,
2887             ..
2888         } = &self.id().get(store).component().env_component().options[options];
2889 
2890         let invalid = ty != lift.ty
2891             || string_encoding != &lift.string_encoding
2892             || match data_model {
2893                 CanonicalOptionsDataModel::LinearMemory(opts) => match opts.memory {
2894                     Some(memory) => {
2895                         let expected = lift.memory.map(|v| v.as_ptr()).unwrap_or(ptr::null_mut());
2896                         let actual = self.id().get(store).runtime_memory(memory);
2897                         expected != actual.as_ptr()
2898                     }
2899                     // Memory not specified, meaning it didn't need to be
2900                     // specified per validation, so not invalid.
2901                     None => false,
2902                 },
2903                 // Always invalid as this isn't supported.
2904                 CanonicalOptionsDataModel::Gc { .. } => true,
2905             };
2906 
2907         if invalid {
2908             bail!("invalid `task.return` signature and/or options for current task");
2909         }
2910 
2911         log::trace!("task.return for {guest_thread:?}");
2912 
2913         let result = (lift.lift)(store, storage)?;
2914         self.task_complete(store, guest_thread.task, result, Status::Returned)
2915     }
2916 
2917     /// Implements the `task.cancel` intrinsic.
2918     pub(crate) fn task_cancel(self, store: &mut StoreOpaque) -> Result<()> {
2919         let state = store.concurrent_state_mut();
2920         let guest_thread = state.guest_thread.unwrap();
2921         let task = state.get_mut(guest_thread.task)?;
2922         if !task.cancel_sent {
2923             bail!("`task.cancel` called by task which has not been cancelled")
2924         }
2925         _ = task.lift_result.take().ok_or_else(|| {
2926             format_err!("`task.return` or `task.cancel` called more than once for current task")
2927         })?;
2928 
2929         assert!(task.result.is_none());
2930 
2931         log::trace!("task.cancel for {guest_thread:?}");
2932 
2933         self.task_complete(
2934             store,
2935             guest_thread.task,
2936             Box::new(DummyResult),
2937             Status::ReturnCancelled,
2938         )
2939     }
2940 
2941     /// Complete the specified guest task (i.e. indicate that it has either
2942     /// returned a (possibly empty) result or cancelled itself).
2943     ///
2944     /// This will return any resource borrows and notify any current or future
2945     /// waiters that the task has completed.
2946     fn task_complete(
2947         self,
2948         store: &mut StoreOpaque,
2949         guest_task: TableId<GuestTask>,
2950         result: Box<dyn Any + Send + Sync>,
2951         status: Status,
2952     ) -> Result<()> {
2953         let (calls, host_table, _, instance) = store.component_resource_state_with_instance(self);
2954         ResourceTables {
2955             calls,
2956             host_table: Some(host_table),
2957             guest: Some(instance.instance_states()),
2958         }
2959         .exit_call()?;
2960 
2961         let state = store.concurrent_state_mut();
2962         let task = state.get_mut(guest_task)?;
2963 
2964         if let Caller::Host { tx, .. } = &mut task.caller {
2965             if let Some(tx) = tx.take() {
2966                 _ = tx.send(result);
2967             }
2968         } else {
2969             task.result = Some(result);
2970             Waitable::Guest(guest_task).set_event(state, Some(Event::Subtask { status }))?;
2971         }
2972 
2973         Ok(())
2974     }
2975 
2976     /// Implements the `waitable-set.new` intrinsic.
2977     pub(crate) fn waitable_set_new(
2978         self,
2979         store: &mut StoreOpaque,
2980         caller_instance: RuntimeComponentInstanceIndex,
2981     ) -> Result<u32> {
2982         let set = store.concurrent_state_mut().push(WaitableSet::default())?;
2983         let handle = store
2984             .handle_table(RuntimeInstance {
2985                 instance: self.id().instance(),
2986                 index: caller_instance,
2987             })
2988             .waitable_set_insert(set.rep())?;
2989         log::trace!("new waitable set {set:?} (handle {handle})");
2990         Ok(handle)
2991     }
2992 
2993     /// Implements the `waitable-set.drop` intrinsic.
2994     pub(crate) fn waitable_set_drop(
2995         self,
2996         store: &mut StoreOpaque,
2997         caller_instance: RuntimeComponentInstanceIndex,
2998         set: u32,
2999     ) -> Result<()> {
3000         let rep = store
3001             .handle_table(RuntimeInstance {
3002                 instance: self.id().instance(),
3003                 index: caller_instance,
3004             })
3005             .waitable_set_remove(set)?;
3006 
3007         log::trace!("drop waitable set {rep} (handle {set})");
3008 
3009         let set = store
3010             .concurrent_state_mut()
3011             .delete(TableId::<WaitableSet>::new(rep))?;
3012 
3013         if !set.waiting.is_empty() {
3014             bail!("cannot drop waitable set with waiters");
3015         }
3016 
3017         Ok(())
3018     }
3019 
3020     /// Implements the `waitable.join` intrinsic.
3021     pub(crate) fn waitable_join(
3022         self,
3023         store: &mut StoreOpaque,
3024         caller_instance: RuntimeComponentInstanceIndex,
3025         waitable_handle: u32,
3026         set_handle: u32,
3027     ) -> Result<()> {
3028         let mut instance = self.id().get_mut(store);
3029         let waitable =
3030             Waitable::from_instance(instance.as_mut(), caller_instance, waitable_handle)?;
3031 
3032         let set = if set_handle == 0 {
3033             None
3034         } else {
3035             let set = instance.instance_states().0[caller_instance]
3036                 .handle_table()
3037                 .waitable_set_rep(set_handle)?;
3038 
3039             Some(TableId::<WaitableSet>::new(set))
3040         };
3041 
3042         log::trace!(
3043             "waitable {waitable:?} (handle {waitable_handle}) join set {set:?} (handle {set_handle})",
3044         );
3045 
3046         waitable.join(store.concurrent_state_mut(), set)
3047     }
3048 
3049     /// Implements the `subtask.drop` intrinsic.
3050     pub(crate) fn subtask_drop(
3051         self,
3052         store: &mut StoreOpaque,
3053         caller_instance: RuntimeComponentInstanceIndex,
3054         task_id: u32,
3055     ) -> Result<()> {
3056         self.waitable_join(store, caller_instance, task_id, 0)?;
3057 
3058         let (rep, is_host) = store
3059             .handle_table(RuntimeInstance {
3060                 instance: self.id().instance(),
3061                 index: caller_instance,
3062             })
3063             .subtask_remove(task_id)?;
3064 
3065         let concurrent_state = store.concurrent_state_mut();
3066         let (waitable, expected_caller_instance, delete) = if is_host {
3067             let id = TableId::<HostTask>::new(rep);
3068             let task = concurrent_state.get_mut(id)?;
3069             if task.join_handle.is_some() {
3070                 bail!("cannot drop a subtask which has not yet resolved");
3071             }
3072             (Waitable::Host(id), task.caller_instance, true)
3073         } else {
3074             let id = TableId::<GuestTask>::new(rep);
3075             let task = concurrent_state.get_mut(id)?;
3076             if task.lift_result.is_some() {
3077                 bail!("cannot drop a subtask which has not yet resolved");
3078             }
3079             if let &Caller::Guest { thread } = &task.caller {
3080                 (
3081                     Waitable::Guest(id),
3082                     concurrent_state.get_mut(thread.task)?.instance,
3083                     concurrent_state.get_mut(id)?.exited,
3084                 )
3085             } else {
3086                 unreachable!()
3087             }
3088         };
3089 
3090         waitable.common(concurrent_state)?.handle = None;
3091 
3092         if waitable.take_event(concurrent_state)?.is_some() {
3093             bail!("cannot drop a subtask with an undelivered event");
3094         }
3095 
3096         if delete {
3097             waitable.delete_from(concurrent_state)?;
3098         }
3099 
3100         // Since waitables can neither be passed between instances nor forged,
3101         // this should never fail unless there's a bug in Wasmtime, but we check
3102         // here to be sure:
3103         assert_eq!(
3104             expected_caller_instance,
3105             RuntimeInstance {
3106                 instance: self.id().instance(),
3107                 index: caller_instance
3108             }
3109         );
3110         log::trace!("subtask_drop {waitable:?} (handle {task_id})");
3111         Ok(())
3112     }
3113 
3114     /// Implements the `waitable-set.wait` intrinsic.
3115     pub(crate) fn waitable_set_wait(
3116         self,
3117         store: &mut StoreOpaque,
3118         options: OptionsIndex,
3119         set: u32,
3120         payload: u32,
3121     ) -> Result<u32> {
3122         if !self.options(store, options).async_ {
3123             // The caller may only call `waitable-set.wait` from an async task
3124             // (i.e. a task created via a call to an async export).
3125             // Otherwise, we'll trap.
3126             store.check_blocking()?;
3127         }
3128 
3129         let &CanonicalOptions {
3130             cancellable,
3131             instance: caller_instance,
3132             ..
3133         } = &self.id().get(store).component().env_component().options[options];
3134         let rep = store
3135             .handle_table(RuntimeInstance {
3136                 instance: self.id().instance(),
3137                 index: caller_instance,
3138             })
3139             .waitable_set_rep(set)?;
3140 
3141         self.waitable_check(
3142             store,
3143             cancellable,
3144             WaitableCheck::Wait,
3145             WaitableCheckParams {
3146                 set: TableId::new(rep),
3147                 options,
3148                 payload,
3149             },
3150         )
3151     }
3152 
3153     /// Implements the `waitable-set.poll` intrinsic.
3154     pub(crate) fn waitable_set_poll(
3155         self,
3156         store: &mut StoreOpaque,
3157         options: OptionsIndex,
3158         set: u32,
3159         payload: u32,
3160     ) -> Result<u32> {
3161         let &CanonicalOptions {
3162             cancellable,
3163             instance: caller_instance,
3164             ..
3165         } = &self.id().get(store).component().env_component().options[options];
3166         let rep = store
3167             .handle_table(RuntimeInstance {
3168                 instance: self.id().instance(),
3169                 index: caller_instance,
3170             })
3171             .waitable_set_rep(set)?;
3172 
3173         self.waitable_check(
3174             store,
3175             cancellable,
3176             WaitableCheck::Poll,
3177             WaitableCheckParams {
3178                 set: TableId::new(rep),
3179                 options,
3180                 payload,
3181             },
3182         )
3183     }
3184 
3185     /// Implements the `thread.index` intrinsic.
3186     pub(crate) fn thread_index(&self, store: &mut dyn VMStore) -> Result<u32> {
3187         let thread_id = store.concurrent_state_mut().guest_thread.unwrap().thread;
3188         // The unwrap is safe because `instance_rep` must be `Some` by this point
3189         Ok(store
3190             .concurrent_state_mut()
3191             .get_mut(thread_id)?
3192             .instance_rep
3193             .unwrap())
3194     }
3195 
3196     /// Implements the `thread.new-indirect` intrinsic.
3197     pub(crate) fn thread_new_indirect<T: 'static>(
3198         self,
3199         mut store: StoreContextMut<T>,
3200         runtime_instance: RuntimeComponentInstanceIndex,
3201         _func_ty_idx: TypeFuncIndex, // currently unused
3202         start_func_table_idx: RuntimeTableIndex,
3203         start_func_idx: u32,
3204         context: i32,
3205     ) -> Result<u32> {
3206         log::trace!("creating new thread");
3207 
3208         let start_func_ty = FuncType::new(store.engine(), [ValType::I32], []);
3209         let (instance, registry) = self.id().get_mut_and_registry(store.0);
3210         let callee = instance
3211             .index_runtime_func_table(registry, start_func_table_idx, start_func_idx as u64)?
3212             .ok_or_else(|| {
3213                 format_err!("the start function index points to an uninitialized function")
3214             })?;
3215         if callee.type_index(store.0) != start_func_ty.type_index() {
3216             bail!(
3217                 "start function does not match expected type (currently only `(i32) -> ()` is supported)"
3218             );
3219         }
3220 
3221         let token = StoreToken::new(store.as_context_mut());
3222         let start_func = Box::new(
3223             move |store: &mut dyn VMStore, guest_thread: QualifiedThreadId| -> Result<()> {
3224                 let old_thread = store.set_thread(Some(guest_thread));
3225                 log::trace!(
3226                     "thread start: replaced {old_thread:?} with {guest_thread:?} as current thread"
3227                 );
3228 
3229                 store.maybe_push_call_context(guest_thread.task)?;
3230 
3231                 let mut store = token.as_context_mut(store);
3232                 let mut params = [ValRaw::i32(context)];
3233                 // Use call_unchecked rather than call or call_async, as we don't want to run the function
3234                 // on a separate fiber if we're running in an async store.
3235                 unsafe { callee.call_unchecked(store.as_context_mut(), &mut params)? };
3236 
3237                 store.0.maybe_pop_call_context(guest_thread.task)?;
3238 
3239                 self.cleanup_thread(store.0, guest_thread, runtime_instance)?;
3240                 log::trace!("explicit thread {guest_thread:?} completed");
3241                 let state = store.0.concurrent_state_mut();
3242                 let task = state.get_mut(guest_thread.task)?;
3243                 if task.threads.is_empty() && !task.returned_or_cancelled() {
3244                     bail!(Trap::NoAsyncResult);
3245                 }
3246                 store.0.set_thread(old_thread);
3247                 let state = store.0.concurrent_state_mut();
3248                 old_thread
3249                     .map(|t| state.get_mut(t.thread).unwrap().state = GuestThreadState::Running);
3250                 if state.get_mut(guest_thread.task)?.ready_to_delete() {
3251                     Waitable::Guest(guest_thread.task).delete_from(state)?;
3252                 }
3253                 log::trace!("thread start: restored {old_thread:?} as current thread");
3254 
3255                 Ok(())
3256             },
3257         );
3258 
3259         let state = store.0.concurrent_state_mut();
3260         let current_thread = state.guest_thread.unwrap();
3261         let parent_task = current_thread.task;
3262 
3263         let new_thread = GuestThread::new_explicit(parent_task, start_func);
3264         let thread_id = state.push(new_thread)?;
3265         state.get_mut(parent_task)?.threads.insert(thread_id);
3266 
3267         log::trace!("new thread with id {thread_id:?} created");
3268 
3269         self.add_guest_thread_to_instance_table(thread_id, store.0, runtime_instance)
3270     }
3271 
3272     pub(crate) fn resume_suspended_thread(
3273         self,
3274         store: &mut StoreOpaque,
3275         runtime_instance: RuntimeComponentInstanceIndex,
3276         thread_idx: u32,
3277         high_priority: bool,
3278     ) -> Result<()> {
3279         let thread_id =
3280             GuestThread::from_instance(self.id().get_mut(store), runtime_instance, thread_idx)?;
3281         let state = store.concurrent_state_mut();
3282         let guest_thread = QualifiedThreadId::qualify(state, thread_id)?;
3283         let thread = state.get_mut(guest_thread.thread)?;
3284 
3285         match mem::replace(&mut thread.state, GuestThreadState::Running) {
3286             GuestThreadState::NotStartedExplicit(start_func) => {
3287                 log::trace!("starting thread {guest_thread:?}");
3288                 let guest_call = WorkItem::GuestCall(GuestCall {
3289                     thread: guest_thread,
3290                     kind: GuestCallKind::StartExplicit(Box::new(move |store| {
3291                         start_func(store, guest_thread)
3292                     })),
3293                 });
3294                 store
3295                     .concurrent_state_mut()
3296                     .push_work_item(guest_call, high_priority);
3297             }
3298             GuestThreadState::Suspended(fiber) => {
3299                 log::trace!("resuming thread {thread_id:?} that was suspended");
3300                 store
3301                     .concurrent_state_mut()
3302                     .push_work_item(WorkItem::ResumeFiber(fiber), high_priority);
3303             }
3304             _ => {
3305                 bail!("cannot resume thread which is not suspended");
3306             }
3307         }
3308         Ok(())
3309     }
3310 
3311     fn add_guest_thread_to_instance_table(
3312         self,
3313         thread_id: TableId<GuestThread>,
3314         store: &mut StoreOpaque,
3315         runtime_instance: RuntimeComponentInstanceIndex,
3316     ) -> Result<u32> {
3317         let guest_id = store
3318             .handle_table(RuntimeInstance {
3319                 instance: self.id().instance(),
3320                 index: runtime_instance,
3321             })
3322             .guest_thread_insert(thread_id.rep())?;
3323         store
3324             .concurrent_state_mut()
3325             .get_mut(thread_id)?
3326             .instance_rep = Some(guest_id);
3327         Ok(guest_id)
3328     }
3329 
3330     /// Helper function for the `thread.yield`, `thread.yield-to`, `thread.suspend`,
3331     /// and `thread.switch-to` intrinsics.
3332     pub(crate) fn suspension_intrinsic(
3333         self,
3334         store: &mut StoreOpaque,
3335         caller: RuntimeComponentInstanceIndex,
3336         cancellable: bool,
3337         yielding: bool,
3338         to_thread: Option<u32>,
3339     ) -> Result<WaitResult> {
3340         if to_thread.is_none() {
3341             let state = store.concurrent_state_mut();
3342             if yielding {
3343                 // This is a `thread.yield` call
3344                 if !state.may_block(state.guest_thread.unwrap().task) {
3345                     // The spec defines `thread.yield` to be a no-op in a
3346                     // non-blocking context, so we return immediately without giving
3347                     // any other thread a chance to run.
3348                     return Ok(WaitResult::Completed);
3349                 }
3350             } else {
3351                 // The caller may only call `thread.suspend` from an async task
3352                 // (i.e. a task created via a call to an async export).
3353                 // Otherwise, we'll trap.
3354                 store.check_blocking()?;
3355             }
3356         }
3357 
3358         // There could be a pending cancellation from a previous uncancellable wait
3359         if cancellable && store.concurrent_state_mut().take_pending_cancellation() {
3360             return Ok(WaitResult::Cancelled);
3361         }
3362 
3363         if let Some(thread) = to_thread {
3364             self.resume_suspended_thread(store, caller, thread, true)?;
3365         }
3366 
3367         let state = store.concurrent_state_mut();
3368         let guest_thread = state.guest_thread.unwrap();
3369         let reason = if yielding {
3370             SuspendReason::Yielding {
3371                 thread: guest_thread,
3372                 // Tell `StoreOpaque::suspend` it's okay to suspend here since
3373                 // we're handling a `thread.yield-to` call; otherwise it would
3374                 // panic if we called it in a non-blocking context.
3375                 skip_may_block_check: to_thread.is_some(),
3376             }
3377         } else {
3378             SuspendReason::ExplicitlySuspending {
3379                 thread: guest_thread,
3380                 // Tell `StoreOpaque::suspend` it's okay to suspend here since
3381                 // we're handling a `thread.switch-to` call; otherwise it would
3382                 // panic if we called it in a non-blocking context.
3383                 skip_may_block_check: to_thread.is_some(),
3384             }
3385         };
3386 
3387         store.suspend(reason)?;
3388 
3389         if cancellable && store.concurrent_state_mut().take_pending_cancellation() {
3390             Ok(WaitResult::Cancelled)
3391         } else {
3392             Ok(WaitResult::Completed)
3393         }
3394     }
3395 
3396     /// Helper function for the `waitable-set.wait` and `waitable-set.poll` intrinsics.
3397     fn waitable_check(
3398         self,
3399         store: &mut StoreOpaque,
3400         cancellable: bool,
3401         check: WaitableCheck,
3402         params: WaitableCheckParams,
3403     ) -> Result<u32> {
3404         let guest_thread = store.concurrent_state_mut().guest_thread.unwrap();
3405 
3406         log::trace!("waitable check for {guest_thread:?}; set {:?}", params.set);
3407 
3408         let state = store.concurrent_state_mut();
3409         let task = state.get_mut(guest_thread.task)?;
3410 
3411         // If we're waiting, and there are no events immediately available,
3412         // suspend the fiber until that changes.
3413         match &check {
3414             WaitableCheck::Wait => {
3415                 let set = params.set;
3416 
3417                 if (task.event.is_none()
3418                     || (matches!(task.event, Some(Event::Cancelled)) && !cancellable))
3419                     && state.get_mut(set)?.ready.is_empty()
3420                 {
3421                     if cancellable {
3422                         let old = state
3423                             .get_mut(guest_thread.thread)?
3424                             .wake_on_cancel
3425                             .replace(set);
3426                         assert!(old.is_none());
3427                     }
3428 
3429                     store.suspend(SuspendReason::Waiting {
3430                         set,
3431                         thread: guest_thread,
3432                         skip_may_block_check: false,
3433                     })?;
3434                 }
3435             }
3436             WaitableCheck::Poll => {}
3437         }
3438 
3439         log::trace!(
3440             "waitable check for {guest_thread:?}; set {:?}, part two",
3441             params.set
3442         );
3443 
3444         // Deliver any pending events to the guest and return.
3445         let event = self.get_event(store, guest_thread.task, Some(params.set), cancellable)?;
3446 
3447         let (ordinal, handle, result) = match &check {
3448             WaitableCheck::Wait => {
3449                 let (event, waitable) = event.unwrap();
3450                 let handle = waitable.map(|(_, v)| v).unwrap_or(0);
3451                 let (ordinal, result) = event.parts();
3452                 (ordinal, handle, result)
3453             }
3454             WaitableCheck::Poll => {
3455                 if let Some((event, waitable)) = event {
3456                     let handle = waitable.map(|(_, v)| v).unwrap_or(0);
3457                     let (ordinal, result) = event.parts();
3458                     (ordinal, handle, result)
3459                 } else {
3460                     log::trace!(
3461                         "no events ready to deliver via waitable-set.poll to {:?}; set {:?}",
3462                         guest_thread.task,
3463                         params.set
3464                     );
3465                     let (ordinal, result) = Event::None.parts();
3466                     (ordinal, 0, result)
3467                 }
3468             }
3469         };
3470         let memory = self.options_memory_mut(store, params.options);
3471         let ptr = func::validate_inbounds_dynamic(
3472             &CanonicalAbiInfo::POINTER_PAIR,
3473             memory,
3474             &ValRaw::u32(params.payload),
3475         )?;
3476         memory[ptr + 0..][..4].copy_from_slice(&handle.to_le_bytes());
3477         memory[ptr + 4..][..4].copy_from_slice(&result.to_le_bytes());
3478         Ok(ordinal)
3479     }
3480 
3481     /// Implements the `subtask.cancel` intrinsic.
3482     pub(crate) fn subtask_cancel(
3483         self,
3484         store: &mut StoreOpaque,
3485         caller_instance: RuntimeComponentInstanceIndex,
3486         async_: bool,
3487         task_id: u32,
3488     ) -> Result<u32> {
3489         if !async_ {
3490             // The caller may only sync call `subtask.cancel` from an async task
3491             // (i.e. a task created via a call to an async export).  Otherwise,
3492             // we'll trap.
3493             store.check_blocking()?;
3494         }
3495 
3496         let (rep, is_host) = store
3497             .handle_table(RuntimeInstance {
3498                 instance: self.id().instance(),
3499                 index: caller_instance,
3500             })
3501             .subtask_rep(task_id)?;
3502         let (waitable, expected_caller_instance) = if is_host {
3503             let id = TableId::<HostTask>::new(rep);
3504             (
3505                 Waitable::Host(id),
3506                 store.concurrent_state_mut().get_mut(id)?.caller_instance,
3507             )
3508         } else {
3509             let id = TableId::<GuestTask>::new(rep);
3510             if let &Caller::Guest { thread } = &store.concurrent_state_mut().get_mut(id)?.caller {
3511                 (
3512                     Waitable::Guest(id),
3513                     store.concurrent_state_mut().get_mut(thread.task)?.instance,
3514                 )
3515             } else {
3516                 unreachable!()
3517             }
3518         };
3519         // Since waitables can neither be passed between instances nor forged,
3520         // this should never fail unless there's a bug in Wasmtime, but we check
3521         // here to be sure:
3522         assert_eq!(
3523             expected_caller_instance,
3524             RuntimeInstance {
3525                 instance: self.id().instance(),
3526                 index: caller_instance
3527             }
3528         );
3529 
3530         log::trace!("subtask_cancel {waitable:?} (handle {task_id})");
3531 
3532         let concurrent_state = store.concurrent_state_mut();
3533         if let Waitable::Host(host_task) = waitable {
3534             if let Some(handle) = concurrent_state.get_mut(host_task)?.join_handle.take() {
3535                 handle.abort();
3536                 return Ok(Status::ReturnCancelled as u32);
3537             }
3538         } else {
3539             let caller = concurrent_state.guest_thread.unwrap();
3540             let guest_task = TableId::<GuestTask>::new(rep);
3541             let task = concurrent_state.get_mut(guest_task)?;
3542             if !task.already_lowered_parameters() {
3543                 // The task is in a `starting` state, meaning it hasn't run at
3544                 // all yet.  Here we update its fields to indicate that it is
3545                 // ready to delete immediately once `subtask.drop` is called.
3546                 task.lower_params = None;
3547                 task.lift_result = None;
3548                 task.exited = true;
3549 
3550                 let instance = task.instance;
3551 
3552                 assert_eq!(1, task.threads.len());
3553                 let thread = mem::take(&mut task.threads).into_iter().next().unwrap();
3554                 let concurrent_state = store.concurrent_state_mut();
3555                 concurrent_state.delete(thread)?;
3556                 assert!(concurrent_state.get_mut(guest_task)?.ready_to_delete());
3557 
3558                 // Not yet started; cancel and remove from pending
3559                 let pending = &mut store.instance_state(instance).pending;
3560                 let pending_count = pending.len();
3561                 pending.retain(|thread, _| thread.task != guest_task);
3562                 // If there were no pending threads for this task, we're in an error state
3563                 if pending.len() == pending_count {
3564                     bail!("`subtask.cancel` called after terminal status delivered");
3565                 }
3566                 return Ok(Status::StartCancelled as u32);
3567             } else if !task.returned_or_cancelled() {
3568                 // Started, but not yet returned or cancelled; send the
3569                 // `CANCELLED` event
3570                 task.cancel_sent = true;
3571                 // Note that this might overwrite an event that was set earlier
3572                 // (e.g. `Event::None` if the task is yielding, or
3573                 // `Event::Cancelled` if it was already cancelled), but that's
3574                 // okay -- this should supersede the previous state.
3575                 task.event = Some(Event::Cancelled);
3576                 for thread in task.threads.clone() {
3577                     let thread = QualifiedThreadId {
3578                         task: guest_task,
3579                         thread,
3580                     };
3581                     if let Some(set) = concurrent_state
3582                         .get_mut(thread.thread)
3583                         .unwrap()
3584                         .wake_on_cancel
3585                         .take()
3586                     {
3587                         let item = match concurrent_state
3588                             .get_mut(set)?
3589                             .waiting
3590                             .remove(&thread)
3591                             .unwrap()
3592                         {
3593                             WaitMode::Fiber(fiber) => WorkItem::ResumeFiber(fiber),
3594                             WaitMode::Callback(instance) => WorkItem::GuestCall(GuestCall {
3595                                 thread,
3596                                 kind: GuestCallKind::DeliverEvent {
3597                                     instance,
3598                                     set: None,
3599                                 },
3600                             }),
3601                         };
3602                         concurrent_state.push_high_priority(item);
3603 
3604                         store.suspend(SuspendReason::Yielding {
3605                             thread: caller,
3606                             // `subtask.cancel` is not allowed to be called in a
3607                             // sync context, so we cannot skip the may-block check.
3608                             skip_may_block_check: false,
3609                         })?;
3610                         break;
3611                     }
3612                 }
3613 
3614                 let concurrent_state = store.concurrent_state_mut();
3615                 let task = concurrent_state.get_mut(guest_task)?;
3616                 if !task.returned_or_cancelled() {
3617                     if async_ {
3618                         return Ok(BLOCKED);
3619                     } else {
3620                         store.wait_for_event(Waitable::Guest(guest_task))?;
3621                     }
3622                 }
3623             }
3624         }
3625 
3626         let event = waitable.take_event(store.concurrent_state_mut())?;
3627         if let Some(Event::Subtask {
3628             status: status @ (Status::Returned | Status::ReturnCancelled),
3629         }) = event
3630         {
3631             Ok(status as u32)
3632         } else {
3633             bail!("`subtask.cancel` called after terminal status delivered");
3634         }
3635     }
3636 
3637     pub(crate) fn context_get(self, store: &mut StoreOpaque, slot: u32) -> Result<u32> {
3638         store.concurrent_state_mut().context_get(slot)
3639     }
3640 
3641     pub(crate) fn context_set(self, store: &mut StoreOpaque, slot: u32, value: u32) -> Result<()> {
3642         store.concurrent_state_mut().context_set(slot, value)
3643     }
3644 }
3645 
3646 /// Trait representing component model ABI async intrinsics and fused adapter
3647 /// helper functions.
3648 ///
3649 /// SAFETY (callers): Most of the methods in this trait accept raw pointers,
3650 /// which must be valid for at least the duration of the call (and possibly for
3651 /// as long as the relevant guest task exists, in the case of `*mut VMFuncRef`
3652 /// pointers used for async calls).
3653 pub trait VMComponentAsyncStore {
3654     /// A helper function for fused adapter modules involving calls where the
3655     /// one of the caller or callee is async.
3656     ///
3657     /// This helper is not used when the caller and callee both use the sync
3658     /// ABI, only when at least one is async is this used.
3659     unsafe fn prepare_call(
3660         &mut self,
3661         instance: Instance,
3662         memory: *mut VMMemoryDefinition,
3663         start: *mut VMFuncRef,
3664         return_: *mut VMFuncRef,
3665         caller_instance: RuntimeComponentInstanceIndex,
3666         callee_instance: RuntimeComponentInstanceIndex,
3667         task_return_type: TypeTupleIndex,
3668         callee_async: bool,
3669         string_encoding: u8,
3670         result_count: u32,
3671         storage: *mut ValRaw,
3672         storage_len: usize,
3673     ) -> Result<()>;
3674 
3675     /// A helper function for fused adapter modules involving calls where the
3676     /// caller is sync-lowered but the callee is async-lifted.
3677     unsafe fn sync_start(
3678         &mut self,
3679         instance: Instance,
3680         callback: *mut VMFuncRef,
3681         callee: *mut VMFuncRef,
3682         param_count: u32,
3683         storage: *mut MaybeUninit<ValRaw>,
3684         storage_len: usize,
3685     ) -> Result<()>;
3686 
3687     /// A helper function for fused adapter modules involving calls where the
3688     /// caller is async-lowered.
3689     unsafe fn async_start(
3690         &mut self,
3691         instance: Instance,
3692         callback: *mut VMFuncRef,
3693         post_return: *mut VMFuncRef,
3694         callee: *mut VMFuncRef,
3695         param_count: u32,
3696         result_count: u32,
3697         flags: u32,
3698     ) -> Result<u32>;
3699 
3700     /// The `future.write` intrinsic.
3701     fn future_write(
3702         &mut self,
3703         instance: Instance,
3704         caller: RuntimeComponentInstanceIndex,
3705         ty: TypeFutureTableIndex,
3706         options: OptionsIndex,
3707         future: u32,
3708         address: u32,
3709     ) -> Result<u32>;
3710 
3711     /// The `future.read` intrinsic.
3712     fn future_read(
3713         &mut self,
3714         instance: Instance,
3715         caller: RuntimeComponentInstanceIndex,
3716         ty: TypeFutureTableIndex,
3717         options: OptionsIndex,
3718         future: u32,
3719         address: u32,
3720     ) -> Result<u32>;
3721 
3722     /// The `future.drop-writable` intrinsic.
3723     fn future_drop_writable(
3724         &mut self,
3725         instance: Instance,
3726         ty: TypeFutureTableIndex,
3727         writer: u32,
3728     ) -> Result<()>;
3729 
3730     /// The `stream.write` intrinsic.
3731     fn stream_write(
3732         &mut self,
3733         instance: Instance,
3734         caller: RuntimeComponentInstanceIndex,
3735         ty: TypeStreamTableIndex,
3736         options: OptionsIndex,
3737         stream: u32,
3738         address: u32,
3739         count: u32,
3740     ) -> Result<u32>;
3741 
3742     /// The `stream.read` intrinsic.
3743     fn stream_read(
3744         &mut self,
3745         instance: Instance,
3746         caller: RuntimeComponentInstanceIndex,
3747         ty: TypeStreamTableIndex,
3748         options: OptionsIndex,
3749         stream: u32,
3750         address: u32,
3751         count: u32,
3752     ) -> Result<u32>;
3753 
3754     /// The "fast-path" implementation of the `stream.write` intrinsic for
3755     /// "flat" (i.e. memcpy-able) payloads.
3756     fn flat_stream_write(
3757         &mut self,
3758         instance: Instance,
3759         caller: RuntimeComponentInstanceIndex,
3760         ty: TypeStreamTableIndex,
3761         options: OptionsIndex,
3762         payload_size: u32,
3763         payload_align: u32,
3764         stream: u32,
3765         address: u32,
3766         count: u32,
3767     ) -> Result<u32>;
3768 
3769     /// The "fast-path" implementation of the `stream.read` intrinsic for "flat"
3770     /// (i.e. memcpy-able) payloads.
3771     fn flat_stream_read(
3772         &mut self,
3773         instance: Instance,
3774         caller: RuntimeComponentInstanceIndex,
3775         ty: TypeStreamTableIndex,
3776         options: OptionsIndex,
3777         payload_size: u32,
3778         payload_align: u32,
3779         stream: u32,
3780         address: u32,
3781         count: u32,
3782     ) -> Result<u32>;
3783 
3784     /// The `stream.drop-writable` intrinsic.
3785     fn stream_drop_writable(
3786         &mut self,
3787         instance: Instance,
3788         ty: TypeStreamTableIndex,
3789         writer: u32,
3790     ) -> Result<()>;
3791 
3792     /// The `error-context.debug-message` intrinsic.
3793     fn error_context_debug_message(
3794         &mut self,
3795         instance: Instance,
3796         ty: TypeComponentLocalErrorContextTableIndex,
3797         options: OptionsIndex,
3798         err_ctx_handle: u32,
3799         debug_msg_address: u32,
3800     ) -> Result<()>;
3801 
3802     /// The `thread.new-indirect` intrinsic
3803     fn thread_new_indirect(
3804         &mut self,
3805         instance: Instance,
3806         caller: RuntimeComponentInstanceIndex,
3807         func_ty_idx: TypeFuncIndex,
3808         start_func_table_idx: RuntimeTableIndex,
3809         start_func_idx: u32,
3810         context: i32,
3811     ) -> Result<u32>;
3812 }
3813 
3814 /// SAFETY: See trait docs.
3815 impl<T: 'static> VMComponentAsyncStore for StoreInner<T> {
3816     unsafe fn prepare_call(
3817         &mut self,
3818         instance: Instance,
3819         memory: *mut VMMemoryDefinition,
3820         start: *mut VMFuncRef,
3821         return_: *mut VMFuncRef,
3822         caller_instance: RuntimeComponentInstanceIndex,
3823         callee_instance: RuntimeComponentInstanceIndex,
3824         task_return_type: TypeTupleIndex,
3825         callee_async: bool,
3826         string_encoding: u8,
3827         result_count_or_max_if_async: u32,
3828         storage: *mut ValRaw,
3829         storage_len: usize,
3830     ) -> Result<()> {
3831         // SAFETY: The `wasmtime_cranelift`-generated code that calls
3832         // this method will have ensured that `storage` is a valid
3833         // pointer containing at least `storage_len` items.
3834         let params = unsafe { std::slice::from_raw_parts(storage, storage_len) }.to_vec();
3835 
3836         unsafe {
3837             instance.prepare_call(
3838                 StoreContextMut(self),
3839                 start,
3840                 return_,
3841                 caller_instance,
3842                 callee_instance,
3843                 task_return_type,
3844                 callee_async,
3845                 memory,
3846                 string_encoding,
3847                 match result_count_or_max_if_async {
3848                     PREPARE_ASYNC_NO_RESULT => CallerInfo::Async {
3849                         params,
3850                         has_result: false,
3851                     },
3852                     PREPARE_ASYNC_WITH_RESULT => CallerInfo::Async {
3853                         params,
3854                         has_result: true,
3855                     },
3856                     result_count => CallerInfo::Sync {
3857                         params,
3858                         result_count,
3859                     },
3860                 },
3861             )
3862         }
3863     }
3864 
3865     unsafe fn sync_start(
3866         &mut self,
3867         instance: Instance,
3868         callback: *mut VMFuncRef,
3869         callee: *mut VMFuncRef,
3870         param_count: u32,
3871         storage: *mut MaybeUninit<ValRaw>,
3872         storage_len: usize,
3873     ) -> Result<()> {
3874         unsafe {
3875             instance
3876                 .start_call(
3877                     StoreContextMut(self),
3878                     callback,
3879                     ptr::null_mut(),
3880                     callee,
3881                     param_count,
3882                     1,
3883                     START_FLAG_ASYNC_CALLEE,
3884                     // SAFETY: The `wasmtime_cranelift`-generated code that calls
3885                     // this method will have ensured that `storage` is a valid
3886                     // pointer containing at least `storage_len` items.
3887                     Some(std::slice::from_raw_parts_mut(storage, storage_len)),
3888                 )
3889                 .map(drop)
3890         }
3891     }
3892 
3893     unsafe fn async_start(
3894         &mut self,
3895         instance: Instance,
3896         callback: *mut VMFuncRef,
3897         post_return: *mut VMFuncRef,
3898         callee: *mut VMFuncRef,
3899         param_count: u32,
3900         result_count: u32,
3901         flags: u32,
3902     ) -> Result<u32> {
3903         unsafe {
3904             instance.start_call(
3905                 StoreContextMut(self),
3906                 callback,
3907                 post_return,
3908                 callee,
3909                 param_count,
3910                 result_count,
3911                 flags,
3912                 None,
3913             )
3914         }
3915     }
3916 
3917     fn future_write(
3918         &mut self,
3919         instance: Instance,
3920         caller: RuntimeComponentInstanceIndex,
3921         ty: TypeFutureTableIndex,
3922         options: OptionsIndex,
3923         future: u32,
3924         address: u32,
3925     ) -> Result<u32> {
3926         instance
3927             .guest_write(
3928                 StoreContextMut(self),
3929                 caller,
3930                 TransmitIndex::Future(ty),
3931                 options,
3932                 None,
3933                 future,
3934                 address,
3935                 1,
3936             )
3937             .map(|result| result.encode())
3938     }
3939 
3940     fn future_read(
3941         &mut self,
3942         instance: Instance,
3943         caller: RuntimeComponentInstanceIndex,
3944         ty: TypeFutureTableIndex,
3945         options: OptionsIndex,
3946         future: u32,
3947         address: u32,
3948     ) -> Result<u32> {
3949         instance
3950             .guest_read(
3951                 StoreContextMut(self),
3952                 caller,
3953                 TransmitIndex::Future(ty),
3954                 options,
3955                 None,
3956                 future,
3957                 address,
3958                 1,
3959             )
3960             .map(|result| result.encode())
3961     }
3962 
3963     fn stream_write(
3964         &mut self,
3965         instance: Instance,
3966         caller: RuntimeComponentInstanceIndex,
3967         ty: TypeStreamTableIndex,
3968         options: OptionsIndex,
3969         stream: u32,
3970         address: u32,
3971         count: u32,
3972     ) -> Result<u32> {
3973         instance
3974             .guest_write(
3975                 StoreContextMut(self),
3976                 caller,
3977                 TransmitIndex::Stream(ty),
3978                 options,
3979                 None,
3980                 stream,
3981                 address,
3982                 count,
3983             )
3984             .map(|result| result.encode())
3985     }
3986 
3987     fn stream_read(
3988         &mut self,
3989         instance: Instance,
3990         caller: RuntimeComponentInstanceIndex,
3991         ty: TypeStreamTableIndex,
3992         options: OptionsIndex,
3993         stream: u32,
3994         address: u32,
3995         count: u32,
3996     ) -> Result<u32> {
3997         instance
3998             .guest_read(
3999                 StoreContextMut(self),
4000                 caller,
4001                 TransmitIndex::Stream(ty),
4002                 options,
4003                 None,
4004                 stream,
4005                 address,
4006                 count,
4007             )
4008             .map(|result| result.encode())
4009     }
4010 
4011     fn future_drop_writable(
4012         &mut self,
4013         instance: Instance,
4014         ty: TypeFutureTableIndex,
4015         writer: u32,
4016     ) -> Result<()> {
4017         instance.guest_drop_writable(self, TransmitIndex::Future(ty), writer)
4018     }
4019 
4020     fn flat_stream_write(
4021         &mut self,
4022         instance: Instance,
4023         caller: RuntimeComponentInstanceIndex,
4024         ty: TypeStreamTableIndex,
4025         options: OptionsIndex,
4026         payload_size: u32,
4027         payload_align: u32,
4028         stream: u32,
4029         address: u32,
4030         count: u32,
4031     ) -> Result<u32> {
4032         instance
4033             .guest_write(
4034                 StoreContextMut(self),
4035                 caller,
4036                 TransmitIndex::Stream(ty),
4037                 options,
4038                 Some(FlatAbi {
4039                     size: payload_size,
4040                     align: payload_align,
4041                 }),
4042                 stream,
4043                 address,
4044                 count,
4045             )
4046             .map(|result| result.encode())
4047     }
4048 
4049     fn flat_stream_read(
4050         &mut self,
4051         instance: Instance,
4052         caller: RuntimeComponentInstanceIndex,
4053         ty: TypeStreamTableIndex,
4054         options: OptionsIndex,
4055         payload_size: u32,
4056         payload_align: u32,
4057         stream: u32,
4058         address: u32,
4059         count: u32,
4060     ) -> Result<u32> {
4061         instance
4062             .guest_read(
4063                 StoreContextMut(self),
4064                 caller,
4065                 TransmitIndex::Stream(ty),
4066                 options,
4067                 Some(FlatAbi {
4068                     size: payload_size,
4069                     align: payload_align,
4070                 }),
4071                 stream,
4072                 address,
4073                 count,
4074             )
4075             .map(|result| result.encode())
4076     }
4077 
4078     fn stream_drop_writable(
4079         &mut self,
4080         instance: Instance,
4081         ty: TypeStreamTableIndex,
4082         writer: u32,
4083     ) -> Result<()> {
4084         instance.guest_drop_writable(self, TransmitIndex::Stream(ty), writer)
4085     }
4086 
4087     fn error_context_debug_message(
4088         &mut self,
4089         instance: Instance,
4090         ty: TypeComponentLocalErrorContextTableIndex,
4091         options: OptionsIndex,
4092         err_ctx_handle: u32,
4093         debug_msg_address: u32,
4094     ) -> Result<()> {
4095         instance.error_context_debug_message(
4096             StoreContextMut(self),
4097             ty,
4098             options,
4099             err_ctx_handle,
4100             debug_msg_address,
4101         )
4102     }
4103 
4104     fn thread_new_indirect(
4105         &mut self,
4106         instance: Instance,
4107         caller: RuntimeComponentInstanceIndex,
4108         func_ty_idx: TypeFuncIndex,
4109         start_func_table_idx: RuntimeTableIndex,
4110         start_func_idx: u32,
4111         context: i32,
4112     ) -> Result<u32> {
4113         instance.thread_new_indirect(
4114             StoreContextMut(self),
4115             caller,
4116             func_ty_idx,
4117             start_func_table_idx,
4118             start_func_idx,
4119             context,
4120         )
4121     }
4122 }
4123 
4124 type HostTaskFuture = Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>;
4125 
4126 /// Represents the state of a pending host task.
4127 struct HostTask {
4128     common: WaitableCommon,
4129     caller_instance: RuntimeInstance,
4130     join_handle: Option<JoinHandle>,
4131 }
4132 
4133 impl HostTask {
4134     fn new(caller_instance: RuntimeInstance, join_handle: Option<JoinHandle>) -> Self {
4135         Self {
4136             common: WaitableCommon::default(),
4137             caller_instance,
4138             join_handle,
4139         }
4140     }
4141 }
4142 
4143 impl TableDebug for HostTask {
4144     fn type_name() -> &'static str {
4145         "HostTask"
4146     }
4147 }
4148 
4149 type CallbackFn = Box<dyn Fn(&mut dyn VMStore, Event, u32) -> Result<u32> + Send + Sync + 'static>;
4150 
4151 /// Represents the caller of a given guest task.
4152 enum Caller {
4153     /// The host called the guest task.
4154     Host {
4155         /// If present, may be used to deliver the result.
4156         tx: Option<oneshot::Sender<LiftedResult>>,
4157         /// Channel to notify once all subtasks spawned by this caller have
4158         /// completed.
4159         ///
4160         /// Note that we'll never actually send anything to this channel;
4161         /// dropping it when the refcount goes to zero is sufficient to notify
4162         /// the receiver.
4163         exit_tx: Arc<oneshot::Sender<()>>,
4164         /// If true, there's a host future that must be dropped before the task
4165         /// can be deleted.
4166         host_future_present: bool,
4167         /// If `Some`, represents the `QualifiedThreadId` caller of the host
4168         /// function which called back into a guest.  Note that this thread
4169         /// could belong to an entirely unrelated top-level component instance
4170         /// than the one the host called into.
4171         caller: Option<QualifiedThreadId>,
4172     },
4173     /// Another guest thread called the guest task
4174     Guest {
4175         /// The id of the caller
4176         thread: QualifiedThreadId,
4177     },
4178 }
4179 
4180 /// Represents a closure and related canonical ABI parameters required to
4181 /// validate a `task.return` call at runtime and lift the result.
4182 struct LiftResult {
4183     lift: RawLift,
4184     ty: TypeTupleIndex,
4185     memory: Option<SendSyncPtr<VMMemoryDefinition>>,
4186     string_encoding: StringEncoding,
4187 }
4188 
4189 /// The table ID for a guest thread, qualified by the task to which it belongs.
4190 ///
4191 /// This exists to minimize table lookups and the necessity to pass stores around mutably
4192 /// for the common case of identifying the task to which a thread belongs.
4193 #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
4194 struct QualifiedThreadId {
4195     task: TableId<GuestTask>,
4196     thread: TableId<GuestThread>,
4197 }
4198 
4199 impl QualifiedThreadId {
4200     fn qualify(
4201         state: &mut ConcurrentState,
4202         thread: TableId<GuestThread>,
4203     ) -> Result<QualifiedThreadId> {
4204         Ok(QualifiedThreadId {
4205             task: state.get_mut(thread)?.parent_task,
4206             thread,
4207         })
4208     }
4209 }
4210 
4211 impl fmt::Debug for QualifiedThreadId {
4212     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4213         f.debug_tuple("QualifiedThreadId")
4214             .field(&self.task.rep())
4215             .field(&self.thread.rep())
4216             .finish()
4217     }
4218 }
4219 
4220 enum GuestThreadState {
4221     NotStartedImplicit,
4222     NotStartedExplicit(
4223         Box<dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync>,
4224     ),
4225     Running,
4226     Suspended(StoreFiber<'static>),
4227     Pending,
4228     Completed,
4229 }
4230 pub struct GuestThread {
4231     /// Context-local state used to implement the `context.{get,set}`
4232     /// intrinsics.
4233     context: [u32; 2],
4234     /// The owning guest task.
4235     parent_task: TableId<GuestTask>,
4236     /// If present, indicates that the thread is currently waiting on the
4237     /// specified set but may be cancelled and woken immediately.
4238     wake_on_cancel: Option<TableId<WaitableSet>>,
4239     /// The execution state of this guest thread
4240     state: GuestThreadState,
4241     /// The index of this thread in the component instance's handle table.
4242     /// This must always be `Some` after initialization.
4243     instance_rep: Option<u32>,
4244 }
4245 
4246 impl GuestThread {
4247     /// Retrieve the `GuestThread` corresponding to the specified guest-visible
4248     /// handle.
4249     fn from_instance(
4250         state: Pin<&mut ComponentInstance>,
4251         caller_instance: RuntimeComponentInstanceIndex,
4252         guest_thread: u32,
4253     ) -> Result<TableId<Self>> {
4254         let rep = state.instance_states().0[caller_instance]
4255             .handle_table()
4256             .guest_thread_rep(guest_thread)?;
4257         Ok(TableId::new(rep))
4258     }
4259 
4260     fn new_implicit(parent_task: TableId<GuestTask>) -> Self {
4261         Self {
4262             context: [0; 2],
4263             parent_task,
4264             wake_on_cancel: None,
4265             state: GuestThreadState::NotStartedImplicit,
4266             instance_rep: None,
4267         }
4268     }
4269 
4270     fn new_explicit(
4271         parent_task: TableId<GuestTask>,
4272         start_func: Box<
4273             dyn FnOnce(&mut dyn VMStore, QualifiedThreadId) -> Result<()> + Send + Sync,
4274         >,
4275     ) -> Self {
4276         Self {
4277             context: [0; 2],
4278             parent_task,
4279             wake_on_cancel: None,
4280             state: GuestThreadState::NotStartedExplicit(start_func),
4281             instance_rep: None,
4282         }
4283     }
4284 }
4285 
4286 impl TableDebug for GuestThread {
4287     fn type_name() -> &'static str {
4288         "GuestThread"
4289     }
4290 }
4291 
4292 enum SyncResult {
4293     NotProduced,
4294     Produced(Option<ValRaw>),
4295     Taken,
4296 }
4297 
4298 impl SyncResult {
4299     fn take(&mut self) -> Option<Option<ValRaw>> {
4300         match mem::replace(self, SyncResult::Taken) {
4301             SyncResult::NotProduced => None,
4302             SyncResult::Produced(val) => Some(val),
4303             SyncResult::Taken => {
4304                 panic!("attempted to take a synchronous result that was already taken")
4305             }
4306         }
4307     }
4308 }
4309 
4310 #[derive(Debug)]
4311 enum HostFutureState {
4312     NotApplicable,
4313     Live,
4314     Dropped,
4315 }
4316 
4317 /// Represents a pending guest task.
4318 pub(crate) struct GuestTask {
4319     /// See `WaitableCommon`
4320     common: WaitableCommon,
4321     /// Closure to lower the parameters passed to this task.
4322     lower_params: Option<RawLower>,
4323     /// See `LiftResult`
4324     lift_result: Option<LiftResult>,
4325     /// A place to stash the type-erased lifted result if it can't be delivered
4326     /// immediately.
4327     result: Option<LiftedResult>,
4328     /// Closure to call the callback function for an async-lifted export, if
4329     /// provided.
4330     callback: Option<CallbackFn>,
4331     /// See `Caller`
4332     caller: Caller,
4333     /// A place to stash the call context for managing resource borrows while
4334     /// switching between guest tasks.
4335     call_context: Option<CallContext>,
4336     /// A place to stash the lowered result for a sync-to-async call until it
4337     /// can be returned to the caller.
4338     sync_result: SyncResult,
4339     /// Whether or not the task has been cancelled (i.e. whether the task is
4340     /// permitted to call `task.cancel`).
4341     cancel_sent: bool,
4342     /// Whether or not we've sent a `Status::Starting` event to any current or
4343     /// future waiters for this waitable.
4344     starting_sent: bool,
4345     /// Pending guest subtasks created by this task (directly or indirectly).
4346     ///
4347     /// This is used to re-parent subtasks which are still running when their
4348     /// parent task is disposed.
4349     subtasks: HashSet<TableId<GuestTask>>,
4350     /// Scratch waitable set used to watch subtasks during synchronous calls.
4351     sync_call_set: TableId<WaitableSet>,
4352     /// The runtime instance to which the exported function for this guest task
4353     /// belongs.
4354     ///
4355     /// Note that the task may do a sync->sync call via a fused adapter which
4356     /// results in that task executing code in a different instance, and it may
4357     /// call host functions and intrinsics from that other instance.
4358     instance: RuntimeInstance,
4359     /// If present, a pending `Event::None` or `Event::Cancelled` to be
4360     /// delivered to this task.
4361     event: Option<Event>,
4362     /// The `ExportIndex` of the guest function being called, if known.
4363     function_index: Option<ExportIndex>,
4364     /// Whether or not the task has exited.
4365     exited: bool,
4366     /// Threads belonging to this task
4367     threads: HashSet<TableId<GuestThread>>,
4368     /// The state of the host future that represents an async task, which must
4369     /// be dropped before we can delete the task.
4370     host_future_state: HostFutureState,
4371     /// Indicates whether this task was created for a call to an async-lifted
4372     /// export.
4373     async_function: bool,
4374 }
4375 
4376 impl GuestTask {
4377     fn already_lowered_parameters(&self) -> bool {
4378         // We reset `lower_params` after we lower the parameters
4379         self.lower_params.is_none()
4380     }
4381 
4382     fn returned_or_cancelled(&self) -> bool {
4383         // We reset `lift_result` after we return or exit
4384         self.lift_result.is_none()
4385     }
4386 
4387     fn ready_to_delete(&self) -> bool {
4388         let threads_completed = self.threads.is_empty();
4389         let has_sync_result = matches!(self.sync_result, SyncResult::Produced(_));
4390         let pending_completion_event = matches!(
4391             self.common.event,
4392             Some(Event::Subtask {
4393                 status: Status::Returned | Status::ReturnCancelled
4394             })
4395         );
4396         let ready = threads_completed
4397             && !has_sync_result
4398             && !pending_completion_event
4399             && !matches!(self.host_future_state, HostFutureState::Live);
4400         log::trace!(
4401             "ready to delete? {ready} (threads_completed: {}, has_sync_result: {}, pending_completion_event: {}, host_future_state: {:?})",
4402             threads_completed,
4403             has_sync_result,
4404             pending_completion_event,
4405             self.host_future_state
4406         );
4407         ready
4408     }
4409 
4410     fn new(
4411         state: &mut ConcurrentState,
4412         lower_params: RawLower,
4413         lift_result: LiftResult,
4414         caller: Caller,
4415         callback: Option<CallbackFn>,
4416         instance: RuntimeInstance,
4417         async_function: bool,
4418     ) -> Result<Self> {
4419         let sync_call_set = state.push(WaitableSet::default())?;
4420         let host_future_state = match &caller {
4421             Caller::Guest { .. } => HostFutureState::NotApplicable,
4422             Caller::Host {
4423                 host_future_present,
4424                 ..
4425             } => {
4426                 if *host_future_present {
4427                     HostFutureState::Live
4428                 } else {
4429                     HostFutureState::NotApplicable
4430                 }
4431             }
4432         };
4433         Ok(Self {
4434             common: WaitableCommon::default(),
4435             lower_params: Some(lower_params),
4436             lift_result: Some(lift_result),
4437             result: None,
4438             callback,
4439             caller,
4440             call_context: Some(CallContext::default()),
4441             sync_result: SyncResult::NotProduced,
4442             cancel_sent: false,
4443             starting_sent: false,
4444             subtasks: HashSet::new(),
4445             sync_call_set,
4446             instance,
4447             event: None,
4448             function_index: None,
4449             exited: false,
4450             threads: HashSet::new(),
4451             host_future_state,
4452             async_function,
4453         })
4454     }
4455 
4456     /// Dispose of this guest task, reparenting any pending subtasks to the
4457     /// caller.
4458     fn dispose(self, state: &mut ConcurrentState, me: TableId<GuestTask>) -> Result<()> {
4459         // If there are not-yet-delivered completion events for subtasks in
4460         // `self.sync_call_set`, recursively dispose of those subtasks as well.
4461         for waitable in mem::take(&mut state.get_mut(self.sync_call_set)?.ready) {
4462             if let Some(Event::Subtask {
4463                 status: Status::Returned | Status::ReturnCancelled,
4464             }) = waitable.common(state)?.event
4465             {
4466                 waitable.delete_from(state)?;
4467             }
4468         }
4469 
4470         assert!(self.threads.is_empty());
4471 
4472         state.delete(self.sync_call_set)?;
4473 
4474         // Reparent any pending subtasks to the caller.
4475         match &self.caller {
4476             Caller::Guest { thread } => {
4477                 let task_mut = state.get_mut(thread.task)?;
4478                 let present = task_mut.subtasks.remove(&me);
4479                 assert!(present);
4480 
4481                 for subtask in &self.subtasks {
4482                     task_mut.subtasks.insert(*subtask);
4483                 }
4484 
4485                 for subtask in &self.subtasks {
4486                     state.get_mut(*subtask)?.caller = Caller::Guest { thread: *thread };
4487                 }
4488             }
4489             Caller::Host {
4490                 exit_tx, caller, ..
4491             } => {
4492                 for subtask in &self.subtasks {
4493                     state.get_mut(*subtask)?.caller = Caller::Host {
4494                         tx: None,
4495                         // Clone `exit_tx` to ensure that it is only dropped
4496                         // once all transitive subtasks of the host call have
4497                         // exited:
4498                         exit_tx: exit_tx.clone(),
4499                         host_future_present: false,
4500                         caller: *caller,
4501                     };
4502                 }
4503             }
4504         }
4505 
4506         for subtask in self.subtasks {
4507             let task = state.get_mut(subtask)?;
4508             if task.exited && task.ready_to_delete() {
4509                 Waitable::Guest(subtask).delete_from(state)?;
4510             }
4511         }
4512 
4513         Ok(())
4514     }
4515 }
4516 
4517 impl TableDebug for GuestTask {
4518     fn type_name() -> &'static str {
4519         "GuestTask"
4520     }
4521 }
4522 
4523 /// Represents state common to all kinds of waitables.
4524 #[derive(Default)]
4525 struct WaitableCommon {
4526     /// The currently pending event for this waitable, if any.
4527     event: Option<Event>,
4528     /// The set to which this waitable belongs, if any.
4529     set: Option<TableId<WaitableSet>>,
4530     /// The handle with which the guest refers to this waitable, if any.
4531     handle: Option<u32>,
4532 }
4533 
4534 /// Represents a Component Model Async `waitable`.
4535 #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
4536 enum Waitable {
4537     /// A host task
4538     Host(TableId<HostTask>),
4539     /// A guest task
4540     Guest(TableId<GuestTask>),
4541     /// The read or write end of a stream or future
4542     Transmit(TableId<TransmitHandle>),
4543 }
4544 
4545 impl Waitable {
4546     /// Retrieve the `Waitable` corresponding to the specified guest-visible
4547     /// handle.
4548     fn from_instance(
4549         state: Pin<&mut ComponentInstance>,
4550         caller_instance: RuntimeComponentInstanceIndex,
4551         waitable: u32,
4552     ) -> Result<Self> {
4553         use crate::runtime::vm::component::Waitable;
4554 
4555         let (waitable, kind) = state.instance_states().0[caller_instance]
4556             .handle_table()
4557             .waitable_rep(waitable)?;
4558 
4559         Ok(match kind {
4560             Waitable::Subtask { is_host: true } => Self::Host(TableId::new(waitable)),
4561             Waitable::Subtask { is_host: false } => Self::Guest(TableId::new(waitable)),
4562             Waitable::Stream | Waitable::Future => Self::Transmit(TableId::new(waitable)),
4563         })
4564     }
4565 
4566     /// Retrieve the host-visible identifier for this `Waitable`.
4567     fn rep(&self) -> u32 {
4568         match self {
4569             Self::Host(id) => id.rep(),
4570             Self::Guest(id) => id.rep(),
4571             Self::Transmit(id) => id.rep(),
4572         }
4573     }
4574 
4575     /// Move this `Waitable` to the specified set (when `set` is `Some(_)`) or
4576     /// remove it from any set it may currently belong to (when `set` is
4577     /// `None`).
4578     fn join(&self, state: &mut ConcurrentState, set: Option<TableId<WaitableSet>>) -> Result<()> {
4579         log::trace!("waitable {self:?} join set {set:?}",);
4580 
4581         let old = mem::replace(&mut self.common(state)?.set, set);
4582 
4583         if let Some(old) = old {
4584             match *self {
4585                 Waitable::Host(id) => state.remove_child(id, old),
4586                 Waitable::Guest(id) => state.remove_child(id, old),
4587                 Waitable::Transmit(id) => state.remove_child(id, old),
4588             }?;
4589 
4590             state.get_mut(old)?.ready.remove(self);
4591         }
4592 
4593         if let Some(set) = set {
4594             match *self {
4595                 Waitable::Host(id) => state.add_child(id, set),
4596                 Waitable::Guest(id) => state.add_child(id, set),
4597                 Waitable::Transmit(id) => state.add_child(id, set),
4598             }?;
4599 
4600             if self.common(state)?.event.is_some() {
4601                 self.mark_ready(state)?;
4602             }
4603         }
4604 
4605         Ok(())
4606     }
4607 
4608     /// Retrieve mutable access to the `WaitableCommon` for this `Waitable`.
4609     fn common<'a>(&self, state: &'a mut ConcurrentState) -> Result<&'a mut WaitableCommon> {
4610         Ok(match self {
4611             Self::Host(id) => &mut state.get_mut(*id)?.common,
4612             Self::Guest(id) => &mut state.get_mut(*id)?.common,
4613             Self::Transmit(id) => &mut state.get_mut(*id)?.common,
4614         })
4615     }
4616 
4617     /// Set or clear the pending event for this waitable and either deliver it
4618     /// to the first waiter, if any, or mark it as ready to be delivered to the
4619     /// next waiter that arrives.
4620     fn set_event(&self, state: &mut ConcurrentState, event: Option<Event>) -> Result<()> {
4621         log::trace!("set event for {self:?}: {event:?}");
4622         self.common(state)?.event = event;
4623         self.mark_ready(state)
4624     }
4625 
4626     /// Take the pending event from this waitable, leaving `None` in its place.
4627     fn take_event(&self, state: &mut ConcurrentState) -> Result<Option<Event>> {
4628         let common = self.common(state)?;
4629         let event = common.event.take();
4630         if let Some(set) = self.common(state)?.set {
4631             state.get_mut(set)?.ready.remove(self);
4632         }
4633 
4634         Ok(event)
4635     }
4636 
4637     /// Deliver the current event for this waitable to the first waiter, if any,
4638     /// or else mark it as ready to be delivered to the next waiter that
4639     /// arrives.
4640     fn mark_ready(&self, state: &mut ConcurrentState) -> Result<()> {
4641         if let Some(set) = self.common(state)?.set {
4642             state.get_mut(set)?.ready.insert(*self);
4643             if let Some((thread, mode)) = state.get_mut(set)?.waiting.pop_first() {
4644                 let wake_on_cancel = state.get_mut(thread.thread)?.wake_on_cancel.take();
4645                 assert!(wake_on_cancel.is_none() || wake_on_cancel == Some(set));
4646 
4647                 let item = match mode {
4648                     WaitMode::Fiber(fiber) => WorkItem::ResumeFiber(fiber),
4649                     WaitMode::Callback(instance) => WorkItem::GuestCall(GuestCall {
4650                         thread,
4651                         kind: GuestCallKind::DeliverEvent {
4652                             instance,
4653                             set: Some(set),
4654                         },
4655                     }),
4656                 };
4657                 state.push_high_priority(item);
4658             }
4659         }
4660         Ok(())
4661     }
4662 
4663     /// Remove this waitable from the instance's rep table.
4664     fn delete_from(&self, state: &mut ConcurrentState) -> Result<()> {
4665         match self {
4666             Self::Host(task) => {
4667                 log::trace!("delete host task {task:?}");
4668                 state.delete(*task)?;
4669             }
4670             Self::Guest(task) => {
4671                 log::trace!("delete guest task {task:?}");
4672                 state.delete(*task)?.dispose(state, *task)?;
4673             }
4674             Self::Transmit(task) => {
4675                 state.delete(*task)?;
4676             }
4677         }
4678 
4679         Ok(())
4680     }
4681 }
4682 
4683 impl fmt::Debug for Waitable {
4684     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4685         match self {
4686             Self::Host(id) => write!(f, "{id:?}"),
4687             Self::Guest(id) => write!(f, "{id:?}"),
4688             Self::Transmit(id) => write!(f, "{id:?}"),
4689         }
4690     }
4691 }
4692 
4693 /// Represents a Component Model Async `waitable-set`.
4694 #[derive(Default)]
4695 struct WaitableSet {
4696     /// Which waitables in this set have pending events, if any.
4697     ready: BTreeSet<Waitable>,
4698     /// Which guest threads are currently waiting on this set, if any.
4699     waiting: BTreeMap<QualifiedThreadId, WaitMode>,
4700 }
4701 
4702 impl TableDebug for WaitableSet {
4703     fn type_name() -> &'static str {
4704         "WaitableSet"
4705     }
4706 }
4707 
4708 /// Type-erased closure to lower the parameters for a guest task.
4709 type RawLower =
4710     Box<dyn FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync>;
4711 
4712 /// Type-erased closure to lift the result for a guest task.
4713 type RawLift = Box<
4714     dyn FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
4715 >;
4716 
4717 /// Type erased result of a guest task which may be downcast to the expected
4718 /// type by a host caller (or simply ignored in the case of a guest caller; see
4719 /// `DummyResult`).
4720 type LiftedResult = Box<dyn Any + Send + Sync>;
4721 
4722 /// Used to return a result from a `LiftFn` when the actual result has already
4723 /// been lowered to a guest task's stack and linear memory.
4724 struct DummyResult;
4725 
4726 /// Represents the Component Model Async state of a (sub-)component instance.
4727 #[derive(Default)]
4728 pub struct ConcurrentInstanceState {
4729     /// Whether backpressure is set for this instance (enabled if >0)
4730     backpressure: u16,
4731     /// Whether this instance can be entered
4732     do_not_enter: bool,
4733     /// Pending calls for this instance which require `Self::backpressure` to be
4734     /// `true` and/or `Self::do_not_enter` to be false before they can proceed.
4735     pending: BTreeMap<QualifiedThreadId, GuestCallKind>,
4736 }
4737 
4738 impl ConcurrentInstanceState {
4739     pub fn pending_is_empty(&self) -> bool {
4740         self.pending.is_empty()
4741     }
4742 }
4743 
4744 /// Represents the Component Model Async state of a store.
4745 pub struct ConcurrentState {
4746     /// The currently running guest thread, if any.
4747     guest_thread: Option<QualifiedThreadId>,
4748 
4749     /// The set of pending host and background tasks, if any.
4750     ///
4751     /// See `ComponentInstance::poll_until` for where we temporarily take this
4752     /// out, poll it, then put it back to avoid any mutable aliasing hazards.
4753     futures: AlwaysMut<Option<FuturesUnordered<HostTaskFuture>>>,
4754     /// The table of waitables, waitable sets, etc.
4755     table: AlwaysMut<ResourceTable>,
4756     /// The "high priority" work queue for this store's event loop.
4757     high_priority: Vec<WorkItem>,
4758     /// The "low priority" work queue for this store's event loop.
4759     low_priority: VecDeque<WorkItem>,
4760     /// A place to stash the reason a fiber is suspending so that the code which
4761     /// resumed it will know under what conditions the fiber should be resumed
4762     /// again.
4763     suspend_reason: Option<SuspendReason>,
4764     /// A cached fiber which is waiting for work to do.
4765     ///
4766     /// This helps us avoid creating a new fiber for each `GuestCall` work item.
4767     worker: Option<StoreFiber<'static>>,
4768     /// A place to stash the work item for which we're resuming a worker fiber.
4769     worker_item: Option<WorkerItem>,
4770 
4771     /// Reference counts for all component error contexts
4772     ///
4773     /// NOTE: it is possible the global ref count to be *greater* than the sum of
4774     /// (sub)component ref counts as tracked by `error_context_tables`, for
4775     /// example when the host holds one or more references to error contexts.
4776     ///
4777     /// The key of this primary map is often referred to as the "rep" (i.e. host-side
4778     /// component-wide representation) of the index into concurrent state for a given
4779     /// stored `ErrorContext`.
4780     ///
4781     /// Stated another way, `TypeComponentGlobalErrorContextTableIndex` is essentially the same
4782     /// as a `TableId<ErrorContextState>`.
4783     global_error_context_ref_counts:
4784         BTreeMap<TypeComponentGlobalErrorContextTableIndex, GlobalErrorContextRefCount>,
4785 }
4786 
4787 impl Default for ConcurrentState {
4788     fn default() -> Self {
4789         Self {
4790             guest_thread: None,
4791             table: AlwaysMut::new(ResourceTable::new()),
4792             futures: AlwaysMut::new(Some(FuturesUnordered::new())),
4793             high_priority: Vec::new(),
4794             low_priority: VecDeque::new(),
4795             suspend_reason: None,
4796             worker: None,
4797             worker_item: None,
4798             global_error_context_ref_counts: BTreeMap::new(),
4799         }
4800     }
4801 }
4802 
4803 impl ConcurrentState {
4804     /// Take ownership of any fibers and futures owned by this object.
4805     ///
4806     /// This should be used when disposing of the `Store` containing this object
4807     /// in order to gracefully resolve any and all fibers using
4808     /// `StoreFiber::dispose`.  This is necessary to avoid possible
4809     /// use-after-free bugs due to fibers which may still have access to the
4810     /// `Store`.
4811     ///
4812     /// Additionally, the futures collected with this function should be dropped
4813     /// within a `tls::set` call, which will ensure than any futures closing
4814     /// over an `&Accessor` will have access to the store when dropped, allowing
4815     /// e.g. `WithAccessor[AndValue]` instances to be disposed of without
4816     /// panicking.
4817     ///
4818     /// Note that this will leave the object in an inconsistent and unusable
4819     /// state, so it should only be used just prior to dropping it.
4820     pub(crate) fn take_fibers_and_futures(
4821         &mut self,
4822         fibers: &mut Vec<StoreFiber<'static>>,
4823         futures: &mut Vec<FuturesUnordered<HostTaskFuture>>,
4824     ) {
4825         for entry in self.table.get_mut().iter_mut() {
4826             if let Some(set) = entry.downcast_mut::<WaitableSet>() {
4827                 for mode in mem::take(&mut set.waiting).into_values() {
4828                     if let WaitMode::Fiber(fiber) = mode {
4829                         fibers.push(fiber);
4830                     }
4831                 }
4832             } else if let Some(thread) = entry.downcast_mut::<GuestThread>() {
4833                 if let GuestThreadState::Suspended(fiber) =
4834                     mem::replace(&mut thread.state, GuestThreadState::Completed)
4835                 {
4836                     fibers.push(fiber);
4837                 }
4838             }
4839         }
4840 
4841         if let Some(fiber) = self.worker.take() {
4842             fibers.push(fiber);
4843         }
4844 
4845         let mut handle_item = |item| match item {
4846             WorkItem::ResumeFiber(fiber) => {
4847                 fibers.push(fiber);
4848             }
4849             WorkItem::PushFuture(future) => {
4850                 self.futures
4851                     .get_mut()
4852                     .as_mut()
4853                     .unwrap()
4854                     .push(future.into_inner());
4855             }
4856             _ => {}
4857         };
4858 
4859         for item in mem::take(&mut self.high_priority) {
4860             handle_item(item);
4861         }
4862         for item in mem::take(&mut self.low_priority) {
4863             handle_item(item);
4864         }
4865 
4866         if let Some(them) = self.futures.get_mut().take() {
4867             futures.push(them);
4868         }
4869     }
4870 
4871     /// Collect the next set of work items to run. This will be either all
4872     /// high-priority items, or a single low-priority item if there are no
4873     /// high-priority items.
4874     fn collect_work_items_to_run(&mut self) -> Vec<WorkItem> {
4875         let mut ready = mem::take(&mut self.high_priority);
4876         if ready.is_empty() {
4877             if let Some(item) = self.low_priority.pop_back() {
4878                 ready.push(item);
4879             }
4880         }
4881         ready
4882     }
4883 
4884     fn push<V: Send + Sync + 'static>(
4885         &mut self,
4886         value: V,
4887     ) -> Result<TableId<V>, ResourceTableError> {
4888         self.table.get_mut().push(value).map(TableId::from)
4889     }
4890 
4891     fn get_mut<V: 'static>(&mut self, id: TableId<V>) -> Result<&mut V, ResourceTableError> {
4892         self.table.get_mut().get_mut(&Resource::from(id))
4893     }
4894 
4895     pub fn add_child<T: 'static, U: 'static>(
4896         &mut self,
4897         child: TableId<T>,
4898         parent: TableId<U>,
4899     ) -> Result<(), ResourceTableError> {
4900         self.table
4901             .get_mut()
4902             .add_child(Resource::from(child), Resource::from(parent))
4903     }
4904 
4905     pub fn remove_child<T: 'static, U: 'static>(
4906         &mut self,
4907         child: TableId<T>,
4908         parent: TableId<U>,
4909     ) -> Result<(), ResourceTableError> {
4910         self.table
4911             .get_mut()
4912             .remove_child(Resource::from(child), Resource::from(parent))
4913     }
4914 
4915     fn delete<V: 'static>(&mut self, id: TableId<V>) -> Result<V, ResourceTableError> {
4916         self.table.get_mut().delete(Resource::from(id))
4917     }
4918 
4919     fn push_future(&mut self, future: HostTaskFuture) {
4920         // Note that we can't directly push to `ConcurrentState::futures` here
4921         // since this may be called from a future that's being polled inside
4922         // `Self::poll_until`, which temporarily removes the `FuturesUnordered`
4923         // so it has exclusive access while polling it.  Therefore, we push a
4924         // work item to the "high priority" queue, which will actually push to
4925         // `ConcurrentState::futures` later.
4926         self.push_high_priority(WorkItem::PushFuture(AlwaysMut::new(future)));
4927     }
4928 
4929     fn push_high_priority(&mut self, item: WorkItem) {
4930         log::trace!("push high priority: {item:?}");
4931         self.high_priority.push(item);
4932     }
4933 
4934     fn push_low_priority(&mut self, item: WorkItem) {
4935         log::trace!("push low priority: {item:?}");
4936         self.low_priority.push_front(item);
4937     }
4938 
4939     fn push_work_item(&mut self, item: WorkItem, high_priority: bool) {
4940         if high_priority {
4941             self.push_high_priority(item);
4942         } else {
4943             self.push_low_priority(item);
4944         }
4945     }
4946 
4947     /// Implements the `context.get` intrinsic.
4948     pub(crate) fn context_get(&mut self, slot: u32) -> Result<u32> {
4949         let thread = self.guest_thread.unwrap();
4950         let val = self.get_mut(thread.thread)?.context[usize::try_from(slot).unwrap()];
4951         log::trace!("context_get {thread:?} slot {slot} val {val:#x}");
4952         Ok(val)
4953     }
4954 
4955     /// Implements the `context.set` intrinsic.
4956     pub(crate) fn context_set(&mut self, slot: u32, val: u32) -> Result<()> {
4957         let thread = self.guest_thread.unwrap();
4958         log::trace!("context_set {thread:?} slot {slot} val {val:#x}");
4959         self.get_mut(thread.thread)?.context[usize::try_from(slot).unwrap()] = val;
4960         Ok(())
4961     }
4962 
4963     /// Returns whether there's a pending cancellation on the current guest thread,
4964     /// consuming the event if so.
4965     fn take_pending_cancellation(&mut self) -> bool {
4966         let thread = self.guest_thread.unwrap();
4967         if let Some(event) = self.get_mut(thread.task).unwrap().event.take() {
4968             assert!(matches!(event, Event::Cancelled));
4969             true
4970         } else {
4971             false
4972         }
4973     }
4974 
4975     fn check_blocking_for(&mut self, task: TableId<GuestTask>) -> Result<()> {
4976         if self.may_block(task) {
4977             Ok(())
4978         } else {
4979             Err(Trap::CannotBlockSyncTask.into())
4980         }
4981     }
4982 
4983     fn may_block(&mut self, task: TableId<GuestTask>) -> bool {
4984         let task = self.get_mut(task).unwrap();
4985         task.async_function || task.returned_or_cancelled()
4986     }
4987 }
4988 
4989 /// Provide a type hint to compiler about the shape of a parameter lower
4990 /// closure.
4991 fn for_any_lower<
4992     F: FnOnce(&mut dyn VMStore, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync,
4993 >(
4994     fun: F,
4995 ) -> F {
4996     fun
4997 }
4998 
4999 /// Provide a type hint to compiler about the shape of a result lift closure.
5000 fn for_any_lift<
5001     F: FnOnce(&mut dyn VMStore, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>> + Send + Sync,
5002 >(
5003     fun: F,
5004 ) -> F {
5005     fun
5006 }
5007 
5008 /// Wrap the specified future in a `poll_fn` which asserts that the future is
5009 /// only polled from the event loop of the specified `Store`.
5010 ///
5011 /// See `StoreContextMut::run_concurrent` for details.
5012 fn checked<F: Future + Send + 'static>(
5013     id: StoreId,
5014     fut: F,
5015 ) -> impl Future<Output = F::Output> + Send + 'static {
5016     async move {
5017         let mut fut = pin!(fut);
5018         future::poll_fn(move |cx| {
5019             let message = "\
5020                 `Future`s which depend on asynchronous component tasks, streams, or \
5021                 futures to complete may only be polled from the event loop of the \
5022                 store to which they belong.  Please use \
5023                 `StoreContextMut::{run_concurrent,spawn}` to poll or await them.\
5024             ";
5025             tls::try_get(|store| {
5026                 let matched = match store {
5027                     tls::TryGet::Some(store) => store.id() == id,
5028                     tls::TryGet::Taken | tls::TryGet::None => false,
5029                 };
5030 
5031                 if !matched {
5032                     panic!("{message}")
5033                 }
5034             });
5035             fut.as_mut().poll(cx)
5036         })
5037         .await
5038     }
5039 }
5040 
5041 /// Assert that `StoreContextMut::run_concurrent` has not been called from
5042 /// within an store's event loop.
5043 fn check_recursive_run() {
5044     tls::try_get(|store| {
5045         if !matches!(store, tls::TryGet::None) {
5046             panic!("Recursive `StoreContextMut::run_concurrent` calls not supported")
5047         }
5048     });
5049 }
5050 
5051 fn unpack_callback_code(code: u32) -> (u32, u32) {
5052     (code & 0xF, code >> 4)
5053 }
5054 
5055 /// Helper struct for packaging parameters to be passed to
5056 /// `ComponentInstance::waitable_check` for calls to `waitable-set.wait` or
5057 /// `waitable-set.poll`.
5058 struct WaitableCheckParams {
5059     set: TableId<WaitableSet>,
5060     options: OptionsIndex,
5061     payload: u32,
5062 }
5063 
5064 /// Indicates whether `ComponentInstance::waitable_check` is being called for
5065 /// `waitable-set.wait` or `waitable-set.poll`.
5066 enum WaitableCheck {
5067     Wait,
5068     Poll,
5069 }
5070 
5071 /// Represents a guest task called from the host, prepared using `prepare_call`.
5072 pub(crate) struct PreparedCall<R> {
5073     /// The guest export to be called
5074     handle: Func,
5075     /// The guest thread created by `prepare_call`
5076     thread: QualifiedThreadId,
5077     /// The number of lowered core Wasm parameters to pass to the call.
5078     param_count: usize,
5079     /// The `oneshot::Receiver` to which the result of the call will be
5080     /// delivered when it is available.
5081     rx: oneshot::Receiver<LiftedResult>,
5082     /// The `oneshot::Receiver` which will resolve when the task -- and any
5083     /// transitive subtasks -- have all exited.
5084     exit_rx: oneshot::Receiver<()>,
5085     _phantom: PhantomData<R>,
5086 }
5087 
5088 impl<R> PreparedCall<R> {
5089     /// Get a copy of the `TaskId` for this `PreparedCall`.
5090     pub(crate) fn task_id(&self) -> TaskId {
5091         TaskId {
5092             task: self.thread.task,
5093         }
5094     }
5095 }
5096 
5097 /// Represents a task created by `prepare_call`.
5098 pub(crate) struct TaskId {
5099     task: TableId<GuestTask>,
5100 }
5101 
5102 impl TaskId {
5103     /// The host future for an async task was dropped. If the parameters have not been lowered yet,
5104     /// it is no longer valid to do so, as the lowering closure would see a dangling pointer. In this case,
5105     /// we delete the task eagerly. Otherwise, there may be running threads, or ones that are suspended
5106     /// and can be resumed by other tasks for this component, so we mark the future as dropped
5107     /// and delete the task when all threads are done.
5108     pub(crate) fn host_future_dropped<T>(&self, store: StoreContextMut<T>) -> Result<()> {
5109         let task = store.0.concurrent_state_mut().get_mut(self.task)?;
5110         if !task.already_lowered_parameters() {
5111             Waitable::Guest(self.task).delete_from(store.0.concurrent_state_mut())?
5112         } else {
5113             task.host_future_state = HostFutureState::Dropped;
5114             if task.ready_to_delete() {
5115                 Waitable::Guest(self.task).delete_from(store.0.concurrent_state_mut())?
5116             }
5117         }
5118         Ok(())
5119     }
5120 }
5121 
5122 /// Prepare a call to the specified exported Wasm function, providing functions
5123 /// for lowering the parameters and lifting the result.
5124 ///
5125 /// To enqueue the returned `PreparedCall` in the `ComponentInstance`'s event
5126 /// loop, use `queue_call`.
5127 pub(crate) fn prepare_call<T, R>(
5128     mut store: StoreContextMut<T>,
5129     handle: Func,
5130     param_count: usize,
5131     host_future_present: bool,
5132     lower_params: impl FnOnce(Func, StoreContextMut<T>, &mut [MaybeUninit<ValRaw>]) -> Result<()>
5133     + Send
5134     + Sync
5135     + 'static,
5136     lift_result: impl FnOnce(Func, &mut StoreOpaque, &[ValRaw]) -> Result<Box<dyn Any + Send + Sync>>
5137     + Send
5138     + Sync
5139     + 'static,
5140 ) -> Result<PreparedCall<R>> {
5141     let (options, _flags, ty, raw_options) = handle.abi_info(store.0);
5142 
5143     let instance = handle.instance().id().get(store.0);
5144     let options = &instance.component().env_component().options[options];
5145     let ty = &instance.component().types()[ty];
5146     let async_function = ty.async_;
5147     let task_return_type = ty.results;
5148     let component_instance = raw_options.instance;
5149     let callback = options.callback.map(|i| instance.runtime_callback(i));
5150     let memory = options
5151         .memory()
5152         .map(|i| instance.runtime_memory(i))
5153         .map(SendSyncPtr::new);
5154     let string_encoding = options.string_encoding;
5155     let token = StoreToken::new(store.as_context_mut());
5156     let state = store.0.concurrent_state_mut();
5157 
5158     let (tx, rx) = oneshot::channel();
5159     let (exit_tx, exit_rx) = oneshot::channel();
5160 
5161     let caller = state.guest_thread;
5162     let mut task = GuestTask::new(
5163         state,
5164         Box::new(for_any_lower(move |store, params| {
5165             lower_params(handle, token.as_context_mut(store), params)
5166         })),
5167         LiftResult {
5168             lift: Box::new(for_any_lift(move |store, result| {
5169                 lift_result(handle, store, result)
5170             })),
5171             ty: task_return_type,
5172             memory,
5173             string_encoding,
5174         },
5175         Caller::Host {
5176             tx: Some(tx),
5177             exit_tx: Arc::new(exit_tx),
5178             host_future_present,
5179             caller,
5180         },
5181         callback.map(|callback| {
5182             let callback = SendSyncPtr::new(callback);
5183             let instance = handle.instance();
5184             Box::new(move |store: &mut dyn VMStore, event, handle| {
5185                 let store = token.as_context_mut(store);
5186                 // SAFETY: Per the contract of `prepare_call`, the callback
5187                 // will remain valid at least as long is this task exists.
5188                 unsafe { instance.call_callback(store, callback, event, handle) }
5189             }) as CallbackFn
5190         }),
5191         RuntimeInstance {
5192             instance: handle.instance().id().instance(),
5193             index: component_instance,
5194         },
5195         async_function,
5196     )?;
5197     task.function_index = Some(handle.index());
5198 
5199     let task = state.push(task)?;
5200     let thread = state.push(GuestThread::new_implicit(task))?;
5201     state.get_mut(task)?.threads.insert(thread);
5202 
5203     if !store.0.may_enter_task(task) {
5204         bail!(crate::Trap::CannotEnterComponent);
5205     }
5206 
5207     Ok(PreparedCall {
5208         handle,
5209         thread: QualifiedThreadId { task, thread },
5210         param_count,
5211         rx,
5212         exit_rx,
5213         _phantom: PhantomData,
5214     })
5215 }
5216 
5217 /// Queue a call previously prepared using `prepare_call` to be run as part of
5218 /// the associated `ComponentInstance`'s event loop.
5219 ///
5220 /// The returned future will resolve to the result once it is available, but
5221 /// must only be polled via the instance's event loop. See
5222 /// `StoreContextMut::run_concurrent` for details.
5223 pub(crate) fn queue_call<T: 'static, R: Send + 'static>(
5224     mut store: StoreContextMut<T>,
5225     prepared: PreparedCall<R>,
5226 ) -> Result<impl Future<Output = Result<(R, oneshot::Receiver<()>)>> + Send + 'static + use<T, R>> {
5227     let PreparedCall {
5228         handle,
5229         thread,
5230         param_count,
5231         rx,
5232         exit_rx,
5233         ..
5234     } = prepared;
5235 
5236     queue_call0(store.as_context_mut(), handle, thread, param_count)?;
5237 
5238     Ok(checked(
5239         store.0.id(),
5240         rx.map(move |result| {
5241             result
5242                 .map(|v| (*v.downcast().unwrap(), exit_rx))
5243                 .map_err(crate::Error::from)
5244         }),
5245     ))
5246 }
5247 
5248 /// Queue a call previously prepared using `prepare_call` to be run as part of
5249 /// the associated `ComponentInstance`'s event loop.
5250 fn queue_call0<T: 'static>(
5251     store: StoreContextMut<T>,
5252     handle: Func,
5253     guest_thread: QualifiedThreadId,
5254     param_count: usize,
5255 ) -> Result<()> {
5256     let (_options, _, _ty, raw_options) = handle.abi_info(store.0);
5257     let is_concurrent = raw_options.async_;
5258     let callback = raw_options.callback;
5259     let instance = handle.instance();
5260     let callee = handle.lifted_core_func(store.0);
5261     let post_return = handle.post_return_core_func(store.0);
5262     let callback = callback.map(|i| {
5263         let instance = instance.id().get(store.0);
5264         SendSyncPtr::new(instance.runtime_callback(i))
5265     });
5266 
5267     log::trace!("queueing call {guest_thread:?}");
5268 
5269     // SAFETY: `callee`, `callback`, and `post_return` are valid pointers
5270     // (with signatures appropriate for this call) and will remain valid as
5271     // long as this instance is valid.
5272     unsafe {
5273         instance.queue_call(
5274             store,
5275             guest_thread,
5276             SendSyncPtr::new(callee),
5277             param_count,
5278             1,
5279             is_concurrent,
5280             callback,
5281             post_return.map(SendSyncPtr::new),
5282         )
5283     }
5284 }
5285