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