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