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