Skip to main content

wasmtime/runtime/component/
concurrent.rs

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