Skip to main content

wasmtime/runtime/component/
concurrent.rs

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