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