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