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