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