Skip to main content

wasmtime/runtime/
store.rs

1//! Wasmtime's "store" type
2//!
3//! This module, and its submodules, contain the `Store` type and various types
4//! used to interact with it. At first glance this is a pretty confusing module
5//! where you need to know the difference between:
6//!
7//! * `Store<T>`
8//! * `StoreContext<T>`
9//! * `StoreContextMut<T>`
10//! * `AsContext`
11//! * `AsContextMut`
12//! * `StoreInner<T>`
13//! * `StoreOpaque`
14//! * `StoreData`
15//!
16//! There's... quite a lot going on here, and it's easy to be confused. This
17//! comment is ideally going to serve the purpose of clarifying what all these
18//! types are for and why they're motivated.
19//!
20//! First it's important to know what's "internal" and what's "external". Almost
21//! everything above is defined as `pub`, but only some of the items are
22//! reexported to the outside world to be usable from this crate. Otherwise all
23//! items are `pub` within this `store` module, and the `store` module is
24//! private to the `wasmtime` crate. Notably `Store<T>`, `StoreContext<T>`,
25//! `StoreContextMut<T>`, `AsContext`, and `AsContextMut` are all public
26//! interfaces to the `wasmtime` crate. You can think of these as:
27//!
28//! * `Store<T>` - an owned reference to a store, the "root of everything"
29//! * `StoreContext<T>` - basically `&StoreInner<T>`
30//! * `StoreContextMut<T>` - more-or-less `&mut StoreInner<T>` with caveats.
31//!   Explained later.
32//! * `AsContext` - similar to `AsRef`, but produces `StoreContext<T>`
33//! * `AsContextMut` - similar to `AsMut`, but produces `StoreContextMut<T>`
34//!
35//! Next comes the internal structure of the `Store<T>` itself. This looks like:
36//!
37//! * `Store<T>` - this type is just a pointer large. It's primarily just
38//!   intended to be consumed by the outside world. Note that the "just a
39//!   pointer large" is a load-bearing implementation detail in Wasmtime. This
40//!   enables it to store a pointer to its own trait object which doesn't need
41//!   to change over time.
42//!
43//! * `StoreInner<T>` - the first layer of the contents of a `Store<T>`, what's
44//!   stored inside the `Box`. This is the general Rust pattern when one struct
45//!   is a layer over another. The surprising part, though, is that this is
46//!   further subdivided. This structure only contains things which actually
47//!   need `T` itself. The downside of this structure is that it's always
48//!   generic and means that code is monomorphized into consumer crates. We
49//!   strive to have things be as monomorphic as possible in `wasmtime` so this
50//!   type is not heavily used.
51//!
52//! * `StoreOpaque` - this is the primary contents of the `StoreInner<T>` type.
53//!   Stored inline in the outer type the "opaque" here means that it's a
54//!   "store" but it doesn't have access to the `T`. This is the primary
55//!   "internal" reference that Wasmtime uses since `T` is rarely needed by the
56//!   internals of Wasmtime.
57//!
58//! * `StoreData` - this is a final helper struct stored within `StoreOpaque`.
59//!   All references of Wasm items into a `Store` are actually indices into a
60//!   table in this structure, and the `StoreData` being separate makes it a bit
61//!   easier to manage/define/work with. There's no real fundamental reason this
62//!   is split out, although sometimes it's useful to have separate borrows into
63//!   these tables than the `StoreOpaque`.
64//!
65//! A major caveat with these representations is that the internal `&mut
66//! StoreInner<T>` is never handed out publicly to consumers of this crate, only
67//! through a wrapper of `StoreContextMut<'_, T>`. The reason for this is that
68//! we want to provide mutable, but not destructive, access to the contents of a
69//! `Store`. For example if a `StoreInner<T>` were replaced with some other
70//! `StoreInner<T>` then that would drop live instances, possibly those
71//! currently executing beneath the current stack frame. This would not be a
72//! safe operation.
73//!
74//! This means, though, that the `wasmtime` crate, which liberally uses `&mut
75//! StoreOpaque` internally, has to be careful to never actually destroy the
76//! contents of `StoreOpaque`. This is an invariant that we, as the authors of
77//! `wasmtime`, must uphold for the public interface to be safe.
78
79use crate::error::OutOfMemory;
80#[cfg(feature = "async")]
81use crate::fiber;
82use crate::hash_map::HashMap;
83use crate::module::{RegisterBreakpointState, RegisteredModuleId};
84use crate::prelude::*;
85use crate::runtime::epoch_state::EpochState;
86#[cfg(feature = "stack-switching")]
87use crate::runtime::vm::VMContRef;
88use crate::runtime::vm::mpk::ProtectionKey;
89use crate::runtime::vm::{
90    self, ExportMemory, GcStore, Imports, InstanceAllocationRequest, InstanceAllocator,
91    InstanceHandle, Interpreter, InterpreterRef, ModuleRuntimeInfo, OnDemandInstanceAllocator,
92    SendSyncPtr, SignalHandler, StoreBox, Unwind, VMContext, VMFuncRef, VMGcRef, VMStore,
93    VMStoreContext,
94};
95use crate::trampoline::VMHostGlobalContext;
96#[cfg(feature = "debug")]
97use crate::{Breakpoints, DebugHandler, FrameDataCache};
98use crate::{Engine, Module, Val, ValRaw, module::ModuleRegistry};
99use crate::{Global, Instance, Table};
100use core::convert::Infallible;
101use core::fmt;
102#[cfg(any(feature = "async", feature = "gc"))]
103use core::future;
104use core::marker;
105use core::mem::{self, ManuallyDrop, MaybeUninit};
106use core::num::NonZeroU64;
107use core::ops::{Deref, DerefMut};
108use core::pin::Pin;
109use core::ptr::NonNull;
110#[cfg(any(feature = "async", feature = "gc"))]
111use core::task::Poll;
112use wasmtime_core::undo::Undo;
113use wasmtime_environ::{
114    DefinedGlobalIndex, DefinedTableIndex, EntityRef, TripleExt, VMSharedTypeIndex,
115};
116
117mod context;
118pub use self::context::*;
119mod data;
120pub use self::data::*;
121mod func_refs;
122use func_refs::FuncRefs;
123#[cfg(feature = "component-model-async")]
124mod token;
125#[cfg(feature = "component-model-async")]
126pub(crate) use token::StoreToken;
127#[cfg(feature = "async")]
128mod async_;
129#[cfg(all(feature = "async", feature = "call-hook"))]
130pub use self::async_::CallHookHandler;
131
132#[cfg(feature = "gc")]
133mod gc;
134#[cfg(not(feature = "gc"))]
135mod gc_disabled;
136
137/// A [`Store`] is a collection of WebAssembly instances and host-defined state.
138///
139/// All WebAssembly instances and items will be attached to and refer to a
140/// [`Store`]. For example instances, functions, globals, and tables are all
141/// attached to a [`Store`]. Instances are created by instantiating a
142/// [`Module`](crate::Module) within a [`Store`].
143///
144/// A [`Store`] is intended to be a short-lived object in a program. No form
145/// of GC is implemented at this time so once an instance is created within a
146/// [`Store`] it will not be deallocated until the [`Store`] itself is dropped.
147/// This makes [`Store`] unsuitable for creating an unbounded number of
148/// instances in it because [`Store`] will never release this memory. It's
149/// recommended to have a [`Store`] correspond roughly to the lifetime of a
150/// "main instance" that an embedding is interested in executing.
151///
152/// ## Type parameter `T`
153///
154/// Each [`Store`] has a type parameter `T` associated with it. This `T`
155/// represents state defined by the host. This state will be accessible through
156/// the [`Caller`](crate::Caller) type that host-defined functions get access
157/// to. This `T` is suitable for storing `Store`-specific information which
158/// imported functions may want access to.
159///
160/// The data `T` can be accessed through methods like [`Store::data`] and
161/// [`Store::data_mut`].
162///
163/// ## Stores, contexts, oh my
164///
165/// Most methods in Wasmtime take something of the form
166/// [`AsContext`](crate::AsContext) or [`AsContextMut`](crate::AsContextMut) as
167/// the first argument. These two traits allow ergonomically passing in the
168/// context you currently have to any method. The primary two sources of
169/// contexts are:
170///
171/// * `Store<T>`
172/// * `Caller<'_, T>`
173///
174/// corresponding to what you create and what you have access to in a host
175/// function. You can also explicitly acquire a [`StoreContext`] or
176/// [`StoreContextMut`] and pass that around as well.
177///
178/// Note that all methods on [`Store`] are mirrored onto [`StoreContext`],
179/// [`StoreContextMut`], and [`Caller`](crate::Caller). This way no matter what
180/// form of context you have you can call various methods, create objects, etc.
181///
182/// ## Stores and `Default`
183///
184/// You can create a store with default configuration settings using
185/// `Store::default()`. This will create a brand new [`Engine`] with default
186/// configuration (see [`Config`](crate::Config) for more information).
187///
188/// ## Cross-store usage of items
189///
190/// In `wasmtime` wasm items such as [`Global`] and [`Memory`] "belong" to a
191/// [`Store`]. The store they belong to is the one they were created with
192/// (passed in as a parameter) or instantiated with. This store is the only
193/// store that can be used to interact with wasm items after they're created.
194///
195/// The `wasmtime` crate will panic if the [`Store`] argument passed in to these
196/// operations is incorrect. In other words it's considered a programmer error
197/// rather than a recoverable error for the wrong [`Store`] to be used when
198/// calling APIs.
199///
200/// [`Memory`]: crate::Memory
201pub struct Store<T: 'static> {
202    // for comments about `ManuallyDrop`, see `Store::into_data`
203    inner: ManuallyDrop<Box<StoreInner<T>>>,
204}
205
206#[derive(Copy, Clone, Debug)]
207/// Passed to the argument of [`Store::call_hook`] to indicate a state transition in
208/// the WebAssembly VM.
209pub enum CallHook {
210    /// Indicates the VM is calling a WebAssembly function, from the host.
211    CallingWasm,
212    /// Indicates the VM is returning from a WebAssembly function, to the host.
213    ReturningFromWasm,
214    /// Indicates the VM is calling a host function, from WebAssembly.
215    CallingHost,
216    /// Indicates the VM is returning from a host function, to WebAssembly.
217    ReturningFromHost,
218}
219
220impl CallHook {
221    /// Indicates the VM is entering host code (exiting WebAssembly code)
222    pub fn entering_host(&self) -> bool {
223        match self {
224            CallHook::ReturningFromWasm | CallHook::CallingHost => true,
225            _ => false,
226        }
227    }
228    /// Indicates the VM is exiting host code (entering WebAssembly code)
229    pub fn exiting_host(&self) -> bool {
230        match self {
231            CallHook::ReturningFromHost | CallHook::CallingWasm => true,
232            _ => false,
233        }
234    }
235}
236
237/// Internal contents of a `Store<T>` that live on the heap.
238///
239/// The members of this struct are those that need to be generic over `T`, the
240/// store's internal type storage. Otherwise all things that don't rely on `T`
241/// should go into `StoreOpaque`.
242///
243/// This is `#[repr(C)]` with `inner` as its first field so that a `dyn VMStore`
244/// (which is always a `StoreInner<T>`) can be cast directly to its
245/// `StoreOpaque` without a virtual call; see the `Deref` impl for `dyn VMStore`.
246#[repr(C)]
247pub struct StoreInner<T: 'static> {
248    /// Generic metadata about the store that doesn't need access to `T`.
249    ///
250    /// This must remain the first field; see above.
251    inner: StoreOpaque,
252
253    limiter: Option<ResourceLimiterInner<T>>,
254    call_hook: Option<CallHookInner<T>>,
255    #[cfg(target_has_atomic = "64")]
256    epoch_deadline_behavior:
257        Option<Box<dyn FnMut(StoreHookState<T>) -> Result<UpdateDeadline> + Send + Sync>>,
258
259    /// The user's `T` data.
260    ///
261    /// Don't actually access it via this field, however! Use the
262    /// `Store{,Inner,Context,ContextMut}::data[_mut]` methods instead, to
263    /// preserve stacked borrows and provenance in the face of potential
264    /// direct-access of `T` from Wasm code (via unsafe intrinsics).
265    ///
266    /// The only exception to the above is when taking ownership of the value,
267    /// e.g. in `Store::into_data`, after which nothing can access this field
268    /// via raw pointers anymore so there is no more provenance to preserve.
269    ///
270    /// For comments about `ManuallyDrop`, see `Store::into_data`.
271    data_no_provenance: ManuallyDrop<T>,
272
273    /// The user's debug handler, if any. See [`crate::DebugHandler`]
274    /// for more documentation.
275    ///
276    /// We need this to be an `Arc` because the handler itself takes
277    /// `&self` and also the whole Store mutably (via
278    /// `StoreContextMut`); so we need to hold a separate reference to
279    /// it while invoking it.
280    #[cfg(feature = "debug")]
281    debug_handler: Option<Box<dyn StoreDebugHandler<T>>>,
282}
283
284/// Adapter around `DebugHandler` that gets monomorphized into an
285/// object-safe dyn trait to place in `store.debug_handler`.
286#[cfg(feature = "debug")]
287trait StoreDebugHandler<T: 'static>: Send + Sync {
288    fn handle<'a>(
289        self: Box<Self>,
290        store: StoreContextMut<'a, T>,
291        event: crate::DebugEvent<'a>,
292    ) -> Box<dyn Future<Output = ()> + Send + 'a>;
293}
294
295#[cfg(feature = "debug")]
296impl<D> StoreDebugHandler<D::Data> for D
297where
298    D: DebugHandler,
299    D::Data: Send,
300{
301    fn handle<'a>(
302        self: Box<Self>,
303        store: StoreContextMut<'a, D::Data>,
304        event: crate::DebugEvent<'a>,
305    ) -> Box<dyn Future<Output = ()> + Send + 'a> {
306        // Clone the underlying `DebugHandler` (the trait requires
307        // Clone as a supertrait), not the Box. The clone happens here
308        // rather than at the callsite because `Clone::clone` is not
309        // object-safe so needs to be in a monomorphized context.
310        let handler: D = (*self).clone();
311        // Since we temporarily took `self` off the store at the
312        // callsite, put it back now that we've cloned it.
313        store.0.debug_handler = Some(self);
314        Box::new(async move { handler.handle(store, event).await })
315    }
316}
317
318enum ResourceLimiterInner<T> {
319    Sync(Box<dyn (FnMut(&mut T) -> &mut dyn crate::ResourceLimiter) + Send + Sync>),
320    #[cfg(feature = "async")]
321    Async(Box<dyn (FnMut(&mut T) -> &mut dyn crate::ResourceLimiterAsync) + Send + Sync>),
322}
323
324/// Representation of a configured resource limiter for a store.
325///
326/// This is acquired with `resource_limiter_and_store_opaque` for example and is
327/// threaded through to growth operations on tables/memories. Note that this is
328/// passed around as `Option<&mut StoreResourceLimiter<'_>>` to make it
329/// efficient to pass around (nullable pointer) and it's also notably passed
330/// around as an `Option` to represent how this is optionally specified within a
331/// store.
332pub enum StoreResourceLimiter<'a> {
333    Sync(&'a mut dyn crate::ResourceLimiter),
334    #[cfg(feature = "async")]
335    Async(&'a mut dyn crate::ResourceLimiterAsync),
336}
337
338impl StoreResourceLimiter<'_> {
339    pub(crate) async fn memory_growing(
340        &mut self,
341        current: usize,
342        desired: usize,
343        maximum: Option<usize>,
344    ) -> Result<bool, Error> {
345        match self {
346            Self::Sync(s) => s.memory_growing(current, desired, maximum),
347            #[cfg(feature = "async")]
348            Self::Async(s) => s.memory_growing(current, desired, maximum).await,
349        }
350    }
351
352    pub(crate) fn memory_grow_failed(&mut self, error: crate::Error) -> Result<()> {
353        match self {
354            Self::Sync(s) => s.memory_grow_failed(error),
355            #[cfg(feature = "async")]
356            Self::Async(s) => s.memory_grow_failed(error),
357        }
358    }
359
360    pub(crate) async fn table_growing(
361        &mut self,
362        current: usize,
363        desired: usize,
364        maximum: Option<usize>,
365    ) -> Result<bool, Error> {
366        match self {
367            Self::Sync(s) => s.table_growing(current, desired, maximum),
368            #[cfg(feature = "async")]
369            Self::Async(s) => s.table_growing(current, desired, maximum).await,
370        }
371    }
372
373    pub(crate) fn table_grow_failed(&mut self, error: crate::Error) -> Result<()> {
374        match self {
375            Self::Sync(s) => s.table_grow_failed(error),
376            #[cfg(feature = "async")]
377            Self::Async(s) => s.table_grow_failed(error),
378        }
379    }
380}
381
382enum CallHookInner<T: 'static> {
383    #[cfg(feature = "call-hook")]
384    Sync(Box<dyn FnMut(StoreHookState<'_, T>, CallHook) -> Result<()> + Send + Sync>),
385    #[cfg(all(feature = "async", feature = "call-hook"))]
386    Async(Box<dyn CallHookHandler<T> + Send + Sync>),
387    #[expect(
388        dead_code,
389        reason = "forcing, regardless of cfg, the type param to be used"
390    )]
391    ForceTypeParameterToBeUsed {
392        uninhabited: Infallible,
393        _marker: marker::PhantomData<T>,
394    },
395}
396
397/// What to do after returning from a callback when the engine epoch reaches
398/// the deadline for a Store during execution of a function using that store.
399#[non_exhaustive]
400pub enum UpdateDeadline {
401    /// Halt execution of WebAssembly, don't update the epoch deadline, and
402    /// raise a trap.
403    Interrupt,
404    /// Extend the deadline by the specified number of ticks.
405    Continue(u64),
406    /// Extend the deadline by the specified number of ticks after yielding to
407    /// the async executor loop.
408    ///
409    /// This can only be used when WebAssembly is invoked with `*_async`
410    /// methods. If WebAssembly was invoked with a synchronous method then
411    /// returning this variant will raise a trap.
412    #[cfg(feature = "async")]
413    Yield(u64),
414    /// Extend the deadline by the specified number of ticks after yielding to
415    /// the async executor loop.
416    ///
417    /// This can only be used when WebAssembly is invoked with `*_async`
418    /// methods. If WebAssembly was invoked with a synchronous method then
419    /// returning this variant will raise a trap.
420    ///
421    /// The yield will be performed by the future provided; when using `tokio`
422    /// it is recommended to provide [`tokio::task::yield_now`](https://docs.rs/tokio/latest/tokio/task/fn.yield_now.html)
423    /// here.
424    #[cfg(feature = "async")]
425    YieldCustom(
426        u64,
427        ::core::pin::Pin<Box<dyn ::core::future::Future<Output = ()> + Send>>,
428    ),
429}
430
431// Forward methods on `StoreOpaque` to also being on `StoreInner<T>`
432impl<T> Deref for StoreInner<T> {
433    type Target = StoreOpaque;
434    fn deref(&self) -> &Self::Target {
435        &self.inner
436    }
437}
438
439impl<T> DerefMut for StoreInner<T> {
440    fn deref_mut(&mut self) -> &mut Self::Target {
441        &mut self.inner
442    }
443}
444
445/// Monomorphic storage for a `Store<T>`.
446///
447/// This structure contains the bulk of the metadata about a `Store`. This is
448/// used internally in Wasmtime when dependence on the `T` of `Store<T>` isn't
449/// necessary, allowing code to be monomorphic and compiled into the `wasmtime`
450/// crate itself.
451pub struct StoreOpaque {
452    // This `StoreOpaque` structure has references to itself. These aren't
453    // immediately evident, however, so we need to tell the compiler that it
454    // contains self-references. This notably suppresses `noalias` annotations
455    // when this shows up in compiled code because types of this structure do
456    // indeed alias itself. An example of this is `default_callee` holds a
457    // `*mut dyn Store` to the address of this `StoreOpaque` itself, indeed
458    // aliasing!
459    //
460    // It's somewhat unclear to me at this time if this is 100% sufficient to
461    // get all the right codegen in all the right places. For example does
462    // `Store` need to internally contain a `Pin<Box<StoreInner<T>>>`? Do the
463    // contexts need to contain `Pin<&mut StoreInner<T>>`? I'm not familiar
464    // enough with `Pin` to understand if it's appropriate here (we do, for
465    // example want to allow movement in and out of `data: T`, just not movement
466    // of most of the other members). It's also not clear if using `Pin` in a
467    // few places buys us much other than a bunch of `unsafe` that we already
468    // sort of hand-wave away.
469    //
470    // In any case this seems like a good mid-ground for now where we're at
471    // least telling the compiler something about all the aliasing happening
472    // within a `Store`.
473    _marker: marker::PhantomPinned,
474
475    engine: Engine,
476    vm_store_context: VMStoreContext,
477
478    /// A stand-in for all state that Wasm execution can mutate in this
479    /// store (e.g. its stack frames); see `WasmState`.
480    ///
481    /// Invariant: this is mutated (and its epoch is thus bumped)
482    /// whenever Wasm executes, after it runs and before host code can
483    /// observe what it did. We ensure this by mutating it on every
484    /// transfer of control from Wasm to the host; see
485    /// `StoreOpaque::on_wasm_to_host_transition`.
486    wasm_state: EpochState<WasmState>,
487
488    // Contains all continuations ever allocated throughout the lifetime of this
489    // store.
490    #[cfg(feature = "stack-switching")]
491    continuations: Vec<Box<VMContRef>>,
492
493    instances: TryPrimaryMap<InstanceId, StoreInstance>,
494
495    signal_handler: Option<SignalHandler>,
496    modules: ModuleRegistry,
497    func_refs: FuncRefs,
498    host_globals: TryPrimaryMap<DefinedGlobalIndex, StoreBox<VMHostGlobalContext>>,
499    // GC-related fields.
500    gc_store: Option<GcStore>,
501    #[cfg(feature = "gc")]
502    gc_data: gc::StoreGcData,
503
504    /// A store-local cache of engine-level subtype checks.
505    ///
506    /// Dynamic subtype checks (e.g. for `ref.cast` instructions) consult the
507    /// engine's type registry, which is protected by a read-write lock.
508    /// Testing locally shows that parallel readers take a significant
509    /// performance hit when using this lock (as measured with `wasmtime
510    /// serve`). Thus this cache is intended to serve as a fast path where the
511    /// lock need not be hit at all.
512    ///
513    /// Note that the size of this cache is currently bounded to a fixed size.
514    /// Once this cache is full then all future consultations which aren't in
515    /// the cache go upstream to the engine itself (slow). In the future
516    /// this'll either be removed entirely (see #13484) or will have some sort
517    /// of LRU-like behavior.
518    ///
519    /// FIXME(#13484) this field is a temporary workaround for a "true
520    /// solution" where supertypes are stored inline in a compiled-code-visible
521    /// location which means that a libcall isn't needed at all (nor
522    /// synchronization) to determine subtype/supertype relationships.
523    subtype_check_cache:
524        HashMap<(VMSharedTypeIndex, VMSharedTypeIndex), bool, foldhash::fast::FixedState>,
525
526    // Numbers of resources instantiated in this store, and their limits
527    instance_count: usize,
528    instance_limit: usize,
529    memory_count: usize,
530    memory_limit: usize,
531    table_count: usize,
532    table_limit: usize,
533    #[cfg(feature = "async")]
534    async_state: fiber::AsyncState,
535
536    // If fuel_yield_interval is enabled, then we store the remaining fuel (that isn't in
537    // runtime_limits) here. The total amount of fuel is the runtime limits and reserve added
538    // together. Then when we run out of gas, we inject the yield amount from the reserve
539    // until the reserve is empty.
540    fuel_reserve: u64,
541    pub(crate) fuel_yield_interval: Option<NonZeroU64>,
542    /// Indexed data within this `Store`, used to store information about
543    /// globals, functions, memories, etc.
544    store_data: StoreData,
545    traitobj: StorePtr,
546    default_caller_vmctx: SendSyncPtr<VMContext>,
547
548    /// Used to optimized wasm->host calls when the host function is defined with
549    /// `Func::new` to avoid allocating a new vector each time a function is
550    /// called.
551    hostcall_val_storage: Vec<Val>,
552    /// Same as `hostcall_val_storage`, but for the direction of the host
553    /// calling wasm.
554    wasm_val_raw_storage: TryVec<ValRaw>,
555
556    /// Keep track of what protection key is being used during allocation so
557    /// that the right memory pages can be enabled when entering WebAssembly
558    /// guest code.
559    pkey: Option<ProtectionKey>,
560
561    /// State related to the executor of wasm code.
562    ///
563    /// For example if Pulley is enabled and configured then this will store a
564    /// Pulley interpreter.
565    executor: Executor,
566
567    /// The debug breakpoint state for this store.
568    ///
569    /// When guest debugging is enabled, a given store may have a set
570    /// of breakpoints defined, denoted by module and Wasm PC within
571    /// that module. Or alternately, it may be in "single-step" mode,
572    /// where every possible breakpoint is logically enabled.
573    ///
574    /// When execution of any instance in this store hits any defined
575    /// breakpoint, a `Breakpoint` debug event is emitted and the
576    /// handler defined above, if any, has a chance to perform some
577    /// logic before returning to allow execution to resume.
578    #[cfg(feature = "debug")]
579    breakpoints: Breakpoints,
580
581    /// The debug PC-to-FrameData cache for this store.
582    ///
583    /// When guest debugging is enabled, we parse compiler metadata
584    /// and pass out `FrameHandle`s that represent Wasm guest
585    /// frames. These handles represent a specific frame within a
586    /// frozen stack and are invalidated upon further execution. In
587    /// order to keep these handles lightweight, and to avoid
588    /// redundant work when passing out *new* handles after further
589    /// execution, we cache the mapping from store-specific PCs to
590    /// parsed frame data. (This cache needs to be store-specific
591    /// rather than e.g. engine-specific because each store has its
592    /// own privately mapped copy of guest code when debugging is
593    /// enabled, so the key-space is unique for each store.)
594    #[cfg(feature = "debug")]
595    frame_data_cache: FrameDataCache,
596}
597
598/// A stand-in for the state that Wasm execution mutates in a store.
599///
600/// The actual state that Wasm mutates (e.g. its stack frames on the
601/// machine stack) can't be placed inside an `EpochState`, so instead
602/// we keep this unit type in an `EpochState` and mutate it whenever
603/// Wasm executes (see `StoreOpaque::wasm_state` for how this is
604/// ensured). Mutation of this value is thus a proxy for any mutation
605/// that actual Wasm code performs.
606///
607/// We use epoch handles (whose validity we can check, and which are
608/// invalidated by subsequent mutations) to guard other kinds of
609/// Wasm-mutated state, such as `FrameHandle`s in the debug API that
610/// refer to live (and frozen) Wasm stack frames.
611#[derive(Clone, Copy, Debug, PartialEq, Eq)]
612pub(crate) struct WasmState;
613
614/// Self-pointer to `StoreInner<T>` from within a `StoreOpaque` which is chiefly
615/// used to copy into instances during instantiation.
616///
617/// FIXME: ideally this type would get deleted and Wasmtime's reliance on it
618/// would go away.
619struct StorePtr(Option<NonNull<dyn VMStore>>);
620
621// We can't make `VMStore: Send + Sync` because that requires making all of
622// Wastime's internals generic over the `Store`'s `T`. So instead, we take care
623// in the whole VM layer to only use the `VMStore` in ways that are `Send`- and
624// `Sync`-safe and we have to have these unsafe impls.
625unsafe impl Send for StorePtr {}
626unsafe impl Sync for StorePtr {}
627
628/// Executor state within `StoreOpaque`.
629///
630/// Effectively stores Pulley interpreter state and handles conditional support
631/// for Cranelift at compile time.
632pub(crate) enum Executor {
633    Interpreter(Interpreter),
634    #[cfg(has_host_compiler_backend)]
635    Native,
636}
637
638impl Executor {
639    pub(crate) fn new(engine: &Engine) -> Result<Self, OutOfMemory> {
640        #[cfg(has_host_compiler_backend)]
641        if cfg!(feature = "pulley") && engine.target().is_pulley() {
642            Ok(Executor::Interpreter(Interpreter::new(engine)?))
643        } else {
644            Ok(Executor::Native)
645        }
646        #[cfg(not(has_host_compiler_backend))]
647        {
648            debug_assert!(engine.target().is_pulley());
649            Ok(Executor::Interpreter(Interpreter::new(engine)?))
650        }
651    }
652}
653
654/// A borrowed reference to `Executor` above.
655pub(crate) enum ExecutorRef<'a> {
656    Interpreter(InterpreterRef<'a>),
657    #[cfg(has_host_compiler_backend)]
658    Native,
659}
660
661/// An RAII type to automatically mark a region of code as unsafe for GC.
662#[doc(hidden)]
663pub struct AutoAssertNoGc<'a> {
664    store: &'a mut StoreOpaque,
665    entered: bool,
666}
667
668impl<'a> AutoAssertNoGc<'a> {
669    #[inline]
670    pub fn new(store: &'a mut StoreOpaque) -> Self {
671        let entered = if !cfg!(feature = "gc") {
672            false
673        } else if let Some(gc_store) = store.gc_store.as_mut() {
674            gc_store.gc_heap.get_mut().enter_no_gc_scope();
675            true
676        } else {
677            false
678        };
679
680        AutoAssertNoGc { store, entered }
681    }
682
683    /// Creates an `AutoAssertNoGc` value which is forcibly "not entered" and
684    /// disables checks for no GC happening for the duration of this value.
685    ///
686    /// This is used when it is statically otherwise known that a GC doesn't
687    /// happen for the various types involved.
688    ///
689    /// # Unsafety
690    ///
691    /// This method is `unsafe` as it does not provide the same safety
692    /// guarantees as `AutoAssertNoGc::new`. It must be guaranteed by the
693    /// caller that a GC doesn't happen.
694    #[inline]
695    pub unsafe fn disabled(store: &'a mut StoreOpaque) -> Self {
696        if cfg!(debug_assertions) {
697            AutoAssertNoGc::new(store)
698        } else {
699            AutoAssertNoGc {
700                store,
701                entered: false,
702            }
703        }
704    }
705}
706
707impl core::ops::Deref for AutoAssertNoGc<'_> {
708    type Target = StoreOpaque;
709
710    #[inline]
711    fn deref(&self) -> &Self::Target {
712        &*self.store
713    }
714}
715
716impl core::ops::DerefMut for AutoAssertNoGc<'_> {
717    #[inline]
718    fn deref_mut(&mut self) -> &mut Self::Target {
719        &mut *self.store
720    }
721}
722
723impl Drop for AutoAssertNoGc<'_> {
724    #[inline]
725    fn drop(&mut self) {
726        if self.entered {
727            self.store
728                .unwrap_gc_store_mut()
729                .gc_heap
730                .get_mut()
731                .exit_no_gc_scope();
732        }
733    }
734}
735
736/// Used to associate instances with the store.
737///
738/// This is needed to track if the instance was allocated explicitly with the on-demand
739/// instance allocator.
740struct StoreInstance {
741    handle: InstanceHandle,
742    kind: StoreInstanceKind,
743}
744
745enum StoreInstanceKind {
746    /// An actual, non-dummy instance.
747    Real {
748        /// The id of this instance's module inside our owning store's
749        /// `ModuleRegistry`.
750        module_id: RegisteredModuleId,
751    },
752
753    /// This is a dummy instance that is just an implementation detail for
754    /// something else. For example, host-created memories internally create a
755    /// dummy instance.
756    ///
757    /// Regardless of the configured instance allocator for the engine, dummy
758    /// instances always use the on-demand allocator to deallocate the instance.
759    Dummy,
760}
761
762impl<T> Store<T> {
763    /// Creates a new [`Store`] to be associated with the given [`Engine`] and
764    /// `data` provided.
765    ///
766    /// The created [`Store`] will place no additional limits on the size of
767    /// linear memories or tables at runtime. Linear memories and tables will
768    /// be allowed to grow to any upper limit specified in their definitions.
769    /// The store will limit the number of instances, linear memories, and
770    /// tables created to 10,000. This can be overridden with the
771    /// [`Store::limiter`] configuration method.
772    pub fn new(engine: &Engine, data: T) -> Self {
773        Self::try_new(engine, data).expect(
774            "allocation failure during `Store::new` (use `Store::try_new` to handle such errors)",
775        )
776    }
777
778    /// Like `Store::new` but returns an error on allocation failure.
779    ///
780    /// # Errors
781    ///
782    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
783    /// memory allocation fails. See the `OutOfMemory` type's documentation for
784    /// details on Wasmtime's out-of-memory handling.
785    pub fn try_new(engine: &Engine, data: T) -> Result<Self> {
786        let store_data = StoreData::new(engine)?;
787        log::trace!("creating new store {:?}", store_data.id());
788
789        let pkey = engine.allocator().next_available_pkey();
790        let wasm_state = EpochState::new(store_data.id(), WasmState);
791
792        let inner = StoreOpaque {
793            _marker: marker::PhantomPinned,
794            engine: engine.clone(),
795            vm_store_context: Default::default(),
796            wasm_state,
797            #[cfg(feature = "stack-switching")]
798            continuations: Vec::new(),
799            instances: TryPrimaryMap::new(),
800            signal_handler: None,
801            gc_store: None,
802            #[cfg(feature = "gc")]
803            gc_data: Default::default(),
804            subtype_check_cache: Default::default(),
805            modules: ModuleRegistry::default(),
806            func_refs: FuncRefs::default(),
807            host_globals: TryPrimaryMap::new(),
808            instance_count: 0,
809            instance_limit: crate::DEFAULT_INSTANCE_LIMIT,
810            memory_count: 0,
811            memory_limit: crate::DEFAULT_MEMORY_LIMIT,
812            table_count: 0,
813            table_limit: crate::DEFAULT_TABLE_LIMIT,
814            #[cfg(feature = "async")]
815            async_state: Default::default(),
816            fuel_reserve: 0,
817            fuel_yield_interval: None,
818            store_data,
819            traitobj: StorePtr(None),
820            default_caller_vmctx: SendSyncPtr::new(NonNull::dangling()),
821            hostcall_val_storage: Vec::new(),
822            wasm_val_raw_storage: TryVec::new(),
823            pkey,
824            executor: Executor::new(engine)?,
825            #[cfg(feature = "debug")]
826            breakpoints: Default::default(),
827            #[cfg(feature = "debug")]
828            frame_data_cache: FrameDataCache::new(),
829        };
830        let mut inner = try_new::<Box<_>>(StoreInner {
831            inner,
832            limiter: None,
833            call_hook: None,
834            #[cfg(target_has_atomic = "64")]
835            epoch_deadline_behavior: None,
836            data_no_provenance: ManuallyDrop::new(data),
837            #[cfg(feature = "debug")]
838            debug_handler: None,
839        })?;
840
841        let store_data =
842            <NonNull<ManuallyDrop<T>>>::from(&mut inner.data_no_provenance).cast::<()>();
843        inner.inner.vm_store_context.store_data = store_data.into();
844
845        // SAFETY: `store_data` and the `VMStoreContext` beside it live in the
846        // same boxed `StoreInner`, so neither outlives nor moves out from under
847        // the other.
848        unsafe {
849            let StoreOpaque {
850                store_data,
851                vm_store_context,
852                ..
853            } = &mut inner.inner;
854            store_data.publish_to_vm_store_context(vm_store_context);
855        }
856
857        inner.traitobj = StorePtr(Some(NonNull::from(&mut *inner)));
858
859        // Wasmtime uses the callee argument to host functions to learn about
860        // the original pointer to the `Store` itself, allowing it to
861        // reconstruct a `StoreContextMut<T>`. When we initially call a `Func`,
862        // however, there's no "callee" to provide. To fix this we allocate a
863        // single "default callee" for the entire `Store`. This is then used as
864        // part of `Func::call` to guarantee that the `callee: *mut VMContext`
865        // is never null.
866        let allocator = OnDemandInstanceAllocator::default();
867        let info = engine.empty_module_runtime_info();
868        allocator
869            .validate_module(info.env_module(), info.offsets())
870            .unwrap();
871
872        unsafe {
873            // Note that this dummy instance doesn't allocate tables or memories
874            // (also no limiter is passed in) so it won't have an async await
875            // point meaning that it should be ok to assert the future is
876            // always ready.
877            let result = vm::assert_ready(inner.allocate_instance(
878                None,
879                AllocateInstanceKind::Dummy {
880                    allocator: &allocator,
881                },
882                info,
883                Default::default(),
884            ));
885            let id = match result {
886                Ok(id) => id,
887                Err(e) => {
888                    if e.is::<OutOfMemory>() {
889                        return Err(e);
890                    }
891                    panic!("instance allocator failed to allocate default callee")
892                }
893            };
894            let default_caller_vmctx = inner.instance(id).vmctx();
895            inner.default_caller_vmctx = default_caller_vmctx.into();
896        }
897
898        Ok(Self {
899            inner: ManuallyDrop::new(inner),
900        })
901    }
902
903    /// Access the underlying `T` data owned by this `Store`.
904    #[inline]
905    pub fn data(&self) -> &T {
906        self.inner.data()
907    }
908
909    /// Access the underlying `T` data owned by this `Store`.
910    #[inline]
911    pub fn data_mut(&mut self) -> &mut T {
912        self.inner.data_mut()
913    }
914
915    fn run_manual_drop_routines(&mut self) {
916        StoreData::run_manual_drop_routines(StoreContextMut(&mut self.inner));
917
918        // Ensure all fiber stacks, even cached ones, are all flushed out to the
919        // instance allocator.
920        self.inner.flush_fiber_stack();
921    }
922
923    /// Consumes this [`Store`], destroying it, and returns the underlying data.
924    pub fn into_data(mut self) -> T {
925        self.run_manual_drop_routines();
926
927        // This is an unsafe operation because we want to avoid having a runtime
928        // check or boolean for whether the data is actually contained within a
929        // `Store`. The data itself is stored as `ManuallyDrop` since we're
930        // manually managing the memory here, and there's also a `ManuallyDrop`
931        // around the `Box<StoreInner<T>>`. The way this works though is a bit
932        // tricky, so here's how things get dropped appropriately:
933        //
934        // * When a `Store<T>` is normally dropped, the custom destructor for
935        //   `Store<T>` will drop `T`, then the `self.inner` field. The
936        //   rustc-glue destructor runs for `Box<StoreInner<T>>` which drops
937        //   `StoreInner<T>`. This cleans up all internal fields and doesn't
938        //   touch `T` because it's wrapped in `ManuallyDrop`.
939        //
940        // * When calling this method we skip the top-level destructor for
941        //   `Store<T>` with `mem::forget`. This skips both the destructor for
942        //   `T` and the destructor for `StoreInner<T>`. We do, however, run the
943        //   destructor for `Box<StoreInner<T>>` which, like above, will skip
944        //   the destructor for `T` since it's `ManuallyDrop`.
945        //
946        // In both cases all the other fields of `StoreInner<T>` should all get
947        // dropped, and the manual management of destructors is basically
948        // between this method and `Drop for Store<T>`. Note that this also
949        // means that `Drop for StoreInner<T>` cannot access `self.data`, so
950        // there is a comment indicating this as well.
951        unsafe {
952            let mut inner = ManuallyDrop::take(&mut self.inner);
953            core::mem::forget(self);
954            ManuallyDrop::take(&mut inner.data_no_provenance)
955        }
956    }
957
958    /// Configures the [`ResourceLimiter`] used to limit resource creation
959    /// within this [`Store`].
960    ///
961    /// Whenever resources such as linear memory, tables, or instances are
962    /// allocated the `limiter` specified here is invoked with the store's data
963    /// `T` and the returned [`ResourceLimiter`] is used to limit the operation
964    /// being allocated. The returned [`ResourceLimiter`] is intended to live
965    /// within the `T` itself, for example by storing a
966    /// [`StoreLimits`](crate::StoreLimits).
967    ///
968    /// Note that this limiter is only used to limit the creation/growth of
969    /// resources in the future, this does not retroactively attempt to apply
970    /// limits to the [`Store`].
971    ///
972    /// # Examples
973    ///
974    /// ```
975    /// use wasmtime::*;
976    ///
977    /// struct MyApplicationState {
978    ///     my_state: u32,
979    ///     limits: StoreLimits,
980    /// }
981    ///
982    /// # fn main() -> Result<()> {
983    /// let engine = Engine::default();
984    /// let my_state = MyApplicationState {
985    ///     my_state: 42,
986    ///     limits: StoreLimitsBuilder::new()
987    ///         .memory_size(1 << 20 /* 1 MB */)
988    ///         .instances(2)
989    ///         .build(),
990    /// };
991    /// let mut store = Store::new(&engine, my_state);
992    /// store.limiter(|state| &mut state.limits);
993    ///
994    /// // Creation of smaller memories is allowed
995    /// Memory::new(&mut store, MemoryType::new(1, None)?)?;
996    ///
997    /// // Creation of a larger memory, however, will exceed the 1MB limit we've
998    /// // configured
999    /// assert!(Memory::new(&mut store, MemoryType::new(1000, None)?).is_err());
1000    ///
1001    /// // The number of instances in this store is limited to 2, so the third
1002    /// // instance here should fail.
1003    /// let module = Module::new(&engine, "(module)")?;
1004    /// Instance::new(&mut store, &module, &[])?;
1005    /// Instance::new(&mut store, &module, &[])?;
1006    /// assert!(Instance::new(&mut store, &module, &[]).is_err());
1007    /// # Ok(())
1008    /// # }
1009    /// ```
1010    ///
1011    /// [`ResourceLimiter`]: crate::ResourceLimiter
1012    pub fn limiter(
1013        &mut self,
1014        mut limiter: impl (FnMut(&mut T) -> &mut dyn crate::ResourceLimiter) + Send + Sync + 'static,
1015    ) {
1016        // Apply the limits on instances, tables, and memory given by the limiter:
1017        let inner = &mut self.inner;
1018        let (instance_limit, table_limit, memory_limit) = {
1019            let l = limiter(inner.data_mut());
1020            (l.instances(), l.tables(), l.memories())
1021        };
1022        let innermost = &mut inner.inner;
1023        innermost.instance_limit = instance_limit;
1024        innermost.table_limit = table_limit;
1025        innermost.memory_limit = memory_limit;
1026
1027        // Save the limiter accessor function:
1028        inner.limiter = Some(ResourceLimiterInner::Sync(Box::new(limiter)));
1029    }
1030
1031    /// Configure a function that runs on calls and returns between WebAssembly
1032    /// and host code.
1033    ///
1034    /// The function is passed a [`CallHook`] argument, which indicates which
1035    /// state transition the VM is making.
1036    ///
1037    /// This function may return a [`Trap`]. If a trap is returned when an
1038    /// import was called, it is immediately raised as-if the host import had
1039    /// returned the trap. If a trap is returned after wasm returns to the host
1040    /// then the wasm function's result is ignored and this trap is returned
1041    /// instead.
1042    ///
1043    /// After this function returns a trap, it may be called for subsequent returns
1044    /// to host or wasm code as the trap propagates to the root call.
1045    ///
1046    /// [`Trap`]: crate::Trap
1047    #[cfg(feature = "call-hook")]
1048    pub fn call_hook(
1049        &mut self,
1050        hook: impl FnMut(StoreHookState<'_, T>, CallHook) -> Result<()> + Send + Sync + 'static,
1051    ) {
1052        self.inner.call_hook = Some(CallHookInner::Sync(Box::new(hook)));
1053    }
1054
1055    /// Returns the [`Engine`] that this store is associated with.
1056    pub fn engine(&self) -> &Engine {
1057        self.inner.engine()
1058    }
1059
1060    /// Returns the amount fuel in this [`Store`]. When fuel is enabled, it must
1061    /// be configured via [`Store::set_fuel`].
1062    ///
1063    /// # Errors
1064    ///
1065    /// This function will return an error if fuel consumption is not enabled
1066    /// via [`Config::consume_fuel`](crate::Config::consume_fuel).
1067    ///
1068    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
1069    /// memory allocation fails. See the `OutOfMemory` type's documentation for
1070    /// details on Wasmtime's out-of-memory handling.
1071    pub fn get_fuel(&self) -> Result<u64> {
1072        self.inner.get_fuel()
1073    }
1074
1075    /// Set the fuel to this [`Store`] for wasm to consume while executing.
1076    ///
1077    /// For this method to work fuel consumption must be enabled via
1078    /// [`Config::consume_fuel`](crate::Config::consume_fuel). By default a
1079    /// [`Store`] starts with 0 fuel for wasm to execute with (meaning it will
1080    /// immediately trap). This function must be called for the store to have
1081    /// some fuel to allow WebAssembly to execute.
1082    ///
1083    /// Most WebAssembly instructions consume 1 unit of fuel. Some
1084    /// instructions, such as `nop`, `drop`, `block`, and `loop`, consume 0
1085    /// units, as any execution cost associated with them involves other
1086    /// instructions which do consume fuel.
1087    ///
1088    /// Note that when fuel is entirely consumed it will cause wasm to trap.
1089    ///
1090    /// # Errors
1091    ///
1092    /// This function will return an error if fuel consumption is not enabled via
1093    /// [`Config::consume_fuel`](crate::Config::consume_fuel).
1094    ///
1095    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
1096    /// memory allocation fails. See the `OutOfMemory` type's documentation for
1097    /// details on Wasmtime's out-of-memory handling.
1098    pub fn set_fuel(&mut self, fuel: u64) -> Result<()> {
1099        self.inner.set_fuel(fuel)
1100    }
1101
1102    /// Configures a [`Store`] to yield execution of async WebAssembly code
1103    /// periodically.
1104    ///
1105    /// When a [`Store`] is configured to consume fuel with
1106    /// [`Config::consume_fuel`](crate::Config::consume_fuel) this method will
1107    /// configure WebAssembly to be suspended and control will be yielded back
1108    /// to the caller every `interval` units of fuel consumed. When using this
1109    /// method it requires further invocations of WebAssembly to use `*_async`
1110    /// entrypoints.
1111    ///
1112    /// The purpose of this behavior is to ensure that futures which represent
1113    /// execution of WebAssembly do not execute too long inside their
1114    /// `Future::poll` method. This allows for some form of cooperative
1115    /// multitasking where WebAssembly will voluntarily yield control
1116    /// periodically (based on fuel consumption) back to the running thread.
1117    ///
1118    /// Note that futures returned by this crate will automatically flag
1119    /// themselves to get re-polled if a yield happens. This means that
1120    /// WebAssembly will continue to execute, just after giving the host an
1121    /// opportunity to do something else.
1122    ///
1123    /// The `interval` parameter indicates how much fuel should be
1124    /// consumed between yields of an async future. When fuel runs out wasm will trap.
1125    ///
1126    /// For limitations related to consumption of fuel and when yield points are
1127    /// injected, see the discussion in
1128    /// [`Config::epoch_interruption`](crate::Config::epoch_interruption).
1129    ///
1130    /// # Error
1131    ///
1132    /// This method will error if fuel is not enabled or `interval` is
1133    /// `Some(0)`.
1134    #[cfg(feature = "async")]
1135    pub fn fuel_async_yield_interval(&mut self, interval: Option<u64>) -> Result<()> {
1136        self.inner.fuel_async_yield_interval(interval)
1137    }
1138
1139    /// Sets the epoch deadline to a certain number of ticks in the future.
1140    ///
1141    /// When the Wasm guest code is compiled with epoch-interruption
1142    /// instrumentation
1143    /// ([`Config::epoch_interruption()`](crate::Config::epoch_interruption)),
1144    /// and when the `Engine`'s epoch is incremented
1145    /// ([`Engine::increment_epoch()`](crate::Engine::increment_epoch))
1146    /// past a deadline, execution can be configured to either trap or
1147    /// yield and then continue.
1148    ///
1149    /// This deadline is always set relative to the current epoch:
1150    /// `ticks_beyond_current` ticks in the future. The deadline can
1151    /// be set explicitly via this method, or refilled automatically
1152    /// on a yield if configured via
1153    /// [`epoch_deadline_async_yield_and_update()`](Store::epoch_deadline_async_yield_and_update). After
1154    /// this method is invoked, the deadline is reached when
1155    /// [`Engine::increment_epoch()`] has been invoked at least
1156    /// `ticks_beyond_current` times.
1157    ///
1158    /// Note that when this method is called while WebAssembly is already
1159    /// executing, for example from within a host function called by wasm,
1160    /// raising the deadline takes effect immediately but lowering it is
1161    /// unsupported. Lowering the deadline does not affect WebAssembly frames
1162    /// already executing and only takes effect for new WebAssembly stack frames
1163    /// made after this function was called.
1164    ///
1165    /// By default a store will trap immediately with an epoch deadline of 0
1166    /// (which has always "elapsed"). This method is required to be configured
1167    /// for stores with epochs enabled to some future epoch deadline.
1168    ///
1169    /// See documentation on
1170    /// [`Config::epoch_interruption()`](crate::Config::epoch_interruption)
1171    /// for an introduction to epoch-based interruption.
1172    #[cfg(target_has_atomic = "64")]
1173    pub fn set_epoch_deadline(&mut self, ticks_beyond_current: u64) {
1174        self.inner.set_epoch_deadline(ticks_beyond_current);
1175    }
1176
1177    /// Configures epoch-deadline expiration to trap.
1178    ///
1179    /// When epoch-interruption-instrumented code is executed on this
1180    /// store and the epoch deadline is reached before completion,
1181    /// with the store configured in this way, execution will
1182    /// terminate with a trap as soon as an epoch check in the
1183    /// instrumented code is reached.
1184    ///
1185    /// This behavior is the default if the store is not otherwise
1186    /// configured via
1187    /// [`epoch_deadline_trap()`](Store::epoch_deadline_trap),
1188    /// [`epoch_deadline_callback()`](Store::epoch_deadline_callback) or
1189    /// [`epoch_deadline_async_yield_and_update()`](Store::epoch_deadline_async_yield_and_update).
1190    ///
1191    /// This setting is intended to allow for coarse-grained
1192    /// interruption, but not a deterministic deadline of a fixed,
1193    /// finite interval. For deterministic interruption, see the
1194    /// "fuel" mechanism instead.
1195    ///
1196    /// Note that when this is used it's required to call
1197    /// [`Store::set_epoch_deadline`] or otherwise wasm will always immediately
1198    /// trap.
1199    ///
1200    /// See documentation on
1201    /// [`Config::epoch_interruption()`](crate::Config::epoch_interruption)
1202    /// for an introduction to epoch-based interruption.
1203    #[cfg(target_has_atomic = "64")]
1204    pub fn epoch_deadline_trap(&mut self) {
1205        self.inner.epoch_deadline_trap();
1206    }
1207
1208    /// Configures epoch-deadline expiration to invoke a custom callback
1209    /// function.
1210    ///
1211    /// When epoch-interruption-instrumented code is executed on this
1212    /// store and the epoch deadline is reached before completion, the
1213    /// provided callback function is invoked.
1214    ///
1215    /// This callback should either return an [`UpdateDeadline`], or
1216    /// return an error, which will terminate execution with a trap.
1217    ///
1218    /// The [`UpdateDeadline`] is a positive number of ticks to
1219    /// add to the epoch deadline, as well as indicating what
1220    /// to do after the callback returns. If the [`Store`] is
1221    /// configured with async support, then the callback may return
1222    /// [`UpdateDeadline::Yield`] or [`UpdateDeadline::YieldCustom`]
1223    /// to yield to the async executor before updating the epoch deadline.
1224    /// Alternatively, the callback may return [`UpdateDeadline::Continue`] to
1225    /// update the epoch deadline immediately.
1226    ///
1227    /// This setting is intended to allow for coarse-grained
1228    /// interruption, but not a deterministic deadline of a fixed,
1229    /// finite interval. For deterministic interruption, see the
1230    /// "fuel" mechanism instead.
1231    ///
1232    /// See documentation on
1233    /// [`Config::epoch_interruption()`](crate::Config::epoch_interruption)
1234    /// for an introduction to epoch-based interruption.
1235    #[cfg(target_has_atomic = "64")]
1236    pub fn epoch_deadline_callback(
1237        &mut self,
1238        callback: impl FnMut(StoreHookState<T>) -> Result<UpdateDeadline> + Send + Sync + 'static,
1239    ) {
1240        self.inner.epoch_deadline_callback(Box::new(callback));
1241    }
1242
1243    /// Tests whether there is a pending exception.
1244    ///
1245    /// Ordinarily, a pending exception will be set on a store if and
1246    /// only if a host-side callstack is propagating a
1247    /// [`crate::ThrownException`] error. The final consumer that
1248    /// catches the exception takes it; it may re-place it to re-throw
1249    /// (using [`Self::throw`]) if it chooses not to actually handle the
1250    /// exception.
1251    ///
1252    /// This method is useful to tell whether a store is in this
1253    /// state, but should not be used as part of the ordinary
1254    /// exception-handling flow. For the most idiomatic handling, see
1255    /// [`StoreContextMut::throw`].
1256    pub fn has_pending_exception(&self) -> bool {
1257        self.inner.has_pending_exception()
1258    }
1259
1260    /// Return all breakpoints.
1261    #[cfg(feature = "debug")]
1262    pub fn breakpoints(&self) -> Option<impl Iterator<Item = crate::Breakpoint> + '_> {
1263        self.as_context().breakpoints()
1264    }
1265
1266    /// Indicate whether single-step mode is enabled.
1267    #[cfg(feature = "debug")]
1268    pub fn is_single_step(&self) -> bool {
1269        self.as_context().is_single_step()
1270    }
1271
1272    /// Set the debug callback on this store.
1273    ///
1274    /// See [`crate::DebugHandler`] for more documentation.
1275    ///
1276    /// # Panics
1277    ///
1278    /// - Will panic if guest-debug support was not enabled via
1279    ///   [`crate::Config::guest_debug`].
1280    #[cfg(feature = "debug")]
1281    pub fn set_debug_handler(&mut self, handler: impl DebugHandler<Data = T>)
1282    where
1283        // We require `Send` here because the debug handler becomes
1284        // referenced from a future: when `DebugHandler::handle` is
1285        // invoked, its `self` references the `handler` with the
1286        // user's state. Note that we are careful to keep this bound
1287        // constrained to debug-handler-related code only and not
1288        // propagate it outward to the store in general. The presence
1289        // of the trait implementation serves as a witness that `T:
1290        // Send`. This is required in particular because we will have
1291        // a `&mut dyn VMStore` on the stack when we pause a fiber
1292        // with `block_on` to run a debugger hook; that `VMStore` must
1293        // be a `Store<T> where T: Send`.
1294        T: Send,
1295    {
1296        // Debug hooks rely on async support, so async entrypoints are required.
1297        self.inner.set_async_required(Asyncness::Yes);
1298
1299        assert!(
1300            self.engine().tunables().debug_guest,
1301            "debug hooks require guest debugging to be enabled"
1302        );
1303        self.inner.debug_handler = Some(Box::new(handler));
1304    }
1305
1306    /// Clear the debug handler on this store. If any existed, it will
1307    /// be dropped.
1308    #[cfg(feature = "debug")]
1309    pub fn clear_debug_handler(&mut self) {
1310        self.inner.debug_handler = None;
1311    }
1312
1313    /// Register a [`Module`] with this store's module registry for
1314    /// debugging, without instantiating it.
1315    ///
1316    /// This makes the module visible to debuggers (via
1317    /// `debug_all_modules`) before the module is actually
1318    /// instantiated. This is useful for guest-debug workflows where
1319    /// the debugger needs to see modules to set breakpoints before
1320    /// the first Wasm instruction executes.
1321    ///
1322    /// # Errors
1323    ///
1324    /// Returns an error if `module` was not compiled by this store's
1325    /// [`Engine`].
1326    #[cfg(feature = "debug")]
1327    pub fn debug_register_module(&mut self, module: &crate::Module) -> crate::Result<()> {
1328        let (modules, engine, breakpoints) = self.inner.modules_and_engine_and_breakpoints_mut();
1329        modules.register_module(module, engine, breakpoints)?;
1330        Ok(())
1331    }
1332
1333    /// Register all inner modules of a [`Component`](crate::component::Component)
1334    /// with this store's module registry for debugging, without instantiating
1335    /// the component.
1336    ///
1337    /// # Errors
1338    ///
1339    /// Returns an error if `component` was not compiled by this store's
1340    /// [`Engine`].
1341    #[cfg(all(feature = "debug", feature = "component-model"))]
1342    pub fn debug_register_component(
1343        &mut self,
1344        component: &crate::component::Component,
1345    ) -> crate::Result<()> {
1346        let (modules, engine, breakpoints) = self.inner.modules_and_engine_and_breakpoints_mut();
1347        modules.register_component(component, engine, breakpoints)?;
1348        for module in component.static_modules() {
1349            self.debug_register_module(module)?;
1350        }
1351        Ok(())
1352    }
1353}
1354
1355impl<'a, T> StoreContext<'a, T> {
1356    /// Returns the underlying [`Engine`] this store is connected to.
1357    pub fn engine(&self) -> &Engine {
1358        self.0.engine()
1359    }
1360
1361    /// Access the underlying data owned by this `Store`.
1362    ///
1363    /// Same as [`Store::data`].
1364    pub fn data(&self) -> &'a T {
1365        self.0.data()
1366    }
1367
1368    /// Returns the remaining fuel in this store.
1369    ///
1370    /// For more information see [`Store::get_fuel`].
1371    pub fn get_fuel(&self) -> Result<u64> {
1372        self.0.get_fuel()
1373    }
1374}
1375
1376impl<'a, T> StoreContextMut<'a, T> {
1377    /// Access the underlying data owned by this `Store`.
1378    ///
1379    /// Same as [`Store::data`].
1380    pub fn data(&self) -> &T {
1381        self.0.data()
1382    }
1383
1384    /// Access the underlying data owned by this `Store`.
1385    ///
1386    /// Same as [`Store::data_mut`].
1387    pub fn data_mut(&mut self) -> &mut T {
1388        self.0.data_mut()
1389    }
1390
1391    /// Returns the underlying [`Engine`] this store is connected to.
1392    pub fn engine(&self) -> &Engine {
1393        self.0.engine()
1394    }
1395
1396    /// Returns remaining fuel in this store.
1397    ///
1398    /// For more information see [`Store::get_fuel`]
1399    pub fn get_fuel(&self) -> Result<u64> {
1400        self.0.get_fuel()
1401    }
1402
1403    /// Set the amount of fuel in this store.
1404    ///
1405    /// For more information see [`Store::set_fuel`]
1406    pub fn set_fuel(&mut self, fuel: u64) -> Result<()> {
1407        self.0.set_fuel(fuel)
1408    }
1409
1410    /// Configures this `Store` to periodically yield while executing futures.
1411    ///
1412    /// For more information see [`Store::fuel_async_yield_interval`]
1413    #[cfg(feature = "async")]
1414    pub fn fuel_async_yield_interval(&mut self, interval: Option<u64>) -> Result<()> {
1415        self.0.fuel_async_yield_interval(interval)
1416    }
1417
1418    /// Sets the epoch deadline to a certain number of ticks in the future.
1419    ///
1420    /// For more information see [`Store::set_epoch_deadline`].
1421    #[cfg(target_has_atomic = "64")]
1422    pub fn set_epoch_deadline(&mut self, ticks_beyond_current: u64) {
1423        self.0.set_epoch_deadline(ticks_beyond_current);
1424    }
1425
1426    /// Configures epoch-deadline expiration to trap.
1427    ///
1428    /// For more information see [`Store::epoch_deadline_trap`].
1429    #[cfg(target_has_atomic = "64")]
1430    pub fn epoch_deadline_trap(&mut self) {
1431        self.0.epoch_deadline_trap();
1432    }
1433
1434    /// Tests whether there is a pending exception.
1435    ///
1436    /// See [`Store::has_pending_exception`] for more details.
1437    pub fn has_pending_exception(&self) -> bool {
1438        self.0.inner.has_pending_exception()
1439    }
1440}
1441
1442impl<T> StoreInner<T> {
1443    #[inline]
1444    fn data(&self) -> &T {
1445        // We are actually just accessing `&self.data_no_provenance` but we must
1446        // do so with the `VMStoreContext::store_data` pointer's provenance. If
1447        // we did otherwise, i.e. directly accessed the field, we would
1448        // invalidate that pointer, which would in turn invalidate any direct
1449        // `T` accesses that Wasm code makes via unsafe intrinsics.
1450        let data: *const ManuallyDrop<T> = &raw const self.data_no_provenance;
1451        let provenance = self.inner.vm_store_context.store_data.as_ptr().cast::<T>();
1452        let ptr = provenance.with_addr(data.addr());
1453
1454        // SAFETY: The pointer is non-null, points to our `T` data, and is valid
1455        // to access because of our `&self` borrow.
1456        debug_assert_ne!(ptr, core::ptr::null_mut());
1457        debug_assert_eq!(ptr.addr(), (&raw const self.data_no_provenance).addr());
1458        unsafe { &*ptr }
1459    }
1460
1461    #[inline]
1462    fn data_limiter_and_opaque(
1463        &mut self,
1464    ) -> (
1465        &mut T,
1466        Option<&mut ResourceLimiterInner<T>>,
1467        &mut StoreOpaque,
1468    ) {
1469        // See the comments about provenance in `StoreInner::data` above.
1470        let data: *mut ManuallyDrop<T> = &raw mut self.data_no_provenance;
1471        let provenance = self.inner.vm_store_context.store_data.as_ptr().cast::<T>();
1472        let ptr = provenance.with_addr(data.addr());
1473
1474        // SAFETY: The pointer is non-null, points to our `T` data, and is valid
1475        // to access because of our `&mut self` borrow.
1476        debug_assert_ne!(ptr, core::ptr::null_mut());
1477        debug_assert_eq!(ptr.addr(), (&raw const self.data_no_provenance).addr());
1478        let data = unsafe { &mut *ptr };
1479
1480        let limiter = self.limiter.as_mut();
1481
1482        (data, limiter, &mut self.inner)
1483    }
1484
1485    /// Borrows the store's `T` and the rest of the store, which are
1486    /// disjoint, mutably at the same time.
1487    #[inline]
1488    pub(crate) fn data_and_opaque_mut(&mut self) -> (&mut T, &mut StoreOpaque) {
1489        let (data, _limiter, opaque) = self.data_limiter_and_opaque();
1490        (data, opaque)
1491    }
1492
1493    #[inline]
1494    fn data_mut(&mut self) -> &mut T {
1495        self.data_limiter_and_opaque().0
1496    }
1497
1498    #[inline]
1499    pub fn call_hook(&mut self, s: CallHook) -> Result<()> {
1500        if self.inner.pkey.is_none() && self.call_hook.is_none() {
1501            Ok(())
1502        } else {
1503            self.call_hook_slow_path(s)
1504        }
1505    }
1506
1507    fn call_hook_slow_path(&mut self, s: CallHook) -> Result<()> {
1508        if let Some(pkey) = &self.inner.pkey {
1509            let allocator = self.engine().allocator();
1510            match s {
1511                CallHook::CallingWasm | CallHook::ReturningFromHost => {
1512                    allocator.restrict_to_pkey(*pkey)
1513                }
1514                CallHook::ReturningFromWasm | CallHook::CallingHost => allocator.allow_all_pkeys(),
1515            }
1516        }
1517
1518        // Temporarily take the configured behavior to avoid mutably borrowing
1519        // multiple times, and put it back when done, even if the hook panics.
1520        let call_hook = self.call_hook.take();
1521        let mut undo = Undo::new((self, call_hook), |(store, call_hook)| {
1522            store.call_hook = call_hook;
1523        });
1524        let (store, call_hook) = &mut *undo;
1525        match call_hook {
1526            Some(call_hook) => store.invoke_call_hook(call_hook, s),
1527            None => Ok(()),
1528        }
1529    }
1530
1531    fn invoke_call_hook(&mut self, call_hook: &mut CallHookInner<T>, s: CallHook) -> Result<()> {
1532        match call_hook {
1533            #[cfg(feature = "call-hook")]
1534            CallHookInner::Sync(hook) => {
1535                hook(StoreHookState::new((&mut *self).as_context_mut()), s)
1536            }
1537
1538            #[cfg(all(feature = "async", feature = "call-hook"))]
1539            CallHookInner::Async(handler) => {
1540                if !self.can_block() {
1541                    bail!("couldn't grab async_cx for call hook")
1542                }
1543                return (&mut *self).as_context_mut().with_blocking(|store, cx| {
1544                    cx.block_on(handler.handle_call_event(StoreHookState::new(store), s))
1545                })?;
1546            }
1547
1548            CallHookInner::ForceTypeParameterToBeUsed { uninhabited, .. } => {
1549                let _ = s;
1550                match *uninhabited {}
1551            }
1552        }
1553    }
1554
1555    #[cfg(not(feature = "async"))]
1556    fn flush_fiber_stack(&mut self) {
1557        // noop shim so code can assume this always exists.
1558    }
1559
1560    /// Splits this `StoreInner<T>` into a `limiter`/`StoreOpaque` borrow while
1561    /// validating that an async limiter is not configured.
1562    ///
1563    /// This is used for sync entrypoints which need to fail if an async limiter
1564    /// is configured as otherwise the async entrypoint must be used instead.
1565    pub(crate) fn validate_sync_resource_limiter_and_store_opaque(
1566        &mut self,
1567    ) -> Result<(Option<StoreResourceLimiter<'_>>, &mut StoreOpaque)> {
1568        let (limiter, store) = self.resource_limiter_and_store_opaque();
1569        if !matches!(limiter, None | Some(StoreResourceLimiter::Sync(_))) {
1570            bail!(
1571                "when using an async resource limiter `*_async` functions must \
1572             be used instead"
1573            );
1574        }
1575        Ok((limiter, store))
1576    }
1577}
1578
1579fn get_fuel(injected_fuel: i64, fuel_reserve: u64) -> u64 {
1580    fuel_reserve.saturating_add_signed(-injected_fuel)
1581}
1582
1583// Add remaining fuel from the reserve into the active fuel if there is any left.
1584fn refuel(
1585    injected_fuel: &mut i64,
1586    fuel_reserve: &mut u64,
1587    yield_interval: Option<NonZeroU64>,
1588) -> bool {
1589    let fuel = get_fuel(*injected_fuel, *fuel_reserve);
1590    if fuel > 0 {
1591        set_fuel(injected_fuel, fuel_reserve, yield_interval, fuel);
1592        true
1593    } else {
1594        false
1595    }
1596}
1597
1598fn set_fuel(
1599    injected_fuel: &mut i64,
1600    fuel_reserve: &mut u64,
1601    yield_interval: Option<NonZeroU64>,
1602    new_fuel_amount: u64,
1603) {
1604    let interval = yield_interval.unwrap_or(NonZeroU64::MAX).get();
1605    // If we're yielding periodically we only store the "active" amount of fuel into consumed_ptr
1606    // for the VM to use.
1607    let injected = core::cmp::min(interval, new_fuel_amount);
1608    // Fuel in the VM is stored as an i64, so we have to cap the amount of fuel we inject into the
1609    // VM at once to be i64 range.
1610    let injected = core::cmp::min(injected, i64::MAX as u64);
1611    // Add whatever is left over after injection to the reserve for later use.
1612    *fuel_reserve = new_fuel_amount - injected;
1613    // Within the VM we increment to count fuel, so inject a negative amount. The VM will halt when
1614    // this counter is positive.
1615    *injected_fuel = -(injected as i64);
1616}
1617
1618fn bump(slot: &mut usize, max: usize, amt: usize, desc: &str) -> Result<()> {
1619    let new = slot.saturating_add(amt);
1620    if new > max {
1621        bail!("resource limit exceeded: {desc} count too high at {new}");
1622    }
1623    *slot = new;
1624    Ok(())
1625}
1626
1627#[doc(hidden)]
1628impl StoreOpaque {
1629    /// Is type `sub` a subtype of `sup`?
1630    ///
1631    /// Equivalent to `self.engine().signatures().is_subtype(sub, sup)` but
1632    /// caches results store-locally to avoid contention on the engine's type
1633    /// registry lock. See the documentation of the `subtype_check_cache` field
1634    /// for details.
1635    pub(crate) fn is_subtype_cached(
1636        &mut self,
1637        sub: VMSharedTypeIndex,
1638        sup: VMSharedTypeIndex,
1639    ) -> bool {
1640        const MAX_SIZE: usize = 1 << 16; // 64k entries
1641
1642        let key = (sub, sup);
1643        let engine_answer = || self.engine.signatures().is_subtype(sub, sup);
1644        if self.subtype_check_cache.len() < MAX_SIZE {
1645            *self
1646                .subtype_check_cache
1647                .entry(key)
1648                .or_insert_with(engine_answer)
1649        } else {
1650            self.subtype_check_cache
1651                .get(&key)
1652                .copied()
1653                .unwrap_or_else(engine_answer)
1654        }
1655    }
1656
1657    pub fn id(&self) -> StoreId {
1658        self.store_data.id()
1659    }
1660
1661    pub fn bump_resource_counts(&mut self, module: &Module) -> Result<()> {
1662        let module = module.env_module();
1663        let memories = module.num_defined_memories();
1664        let tables = module.num_defined_tables();
1665
1666        bump(&mut self.instance_count, self.instance_limit, 1, "instance")?;
1667        bump(
1668            &mut self.memory_count,
1669            self.memory_limit,
1670            memories,
1671            "memory",
1672        )?;
1673        bump(&mut self.table_count, self.table_limit, tables, "table")?;
1674
1675        Ok(())
1676    }
1677
1678    pub fn bump_memory_count(&mut self) -> Result<()> {
1679        bump(&mut self.memory_count, self.memory_limit, 1, "memory")
1680    }
1681
1682    pub fn bump_table_count(&mut self) -> Result<()> {
1683        bump(&mut self.table_count, self.table_limit, 1, "table")
1684    }
1685
1686    #[inline]
1687    pub fn engine(&self) -> &Engine {
1688        &self.engine
1689    }
1690
1691    #[inline]
1692    pub fn store_data(&self) -> &StoreData {
1693        &self.store_data
1694    }
1695
1696    #[inline]
1697    pub fn store_data_mut(&mut self) -> &mut StoreData {
1698        &mut self.store_data
1699    }
1700
1701    pub fn store_data_mut_and_registry(&mut self) -> (&mut StoreData, &ModuleRegistry) {
1702        (&mut self.store_data, &self.modules)
1703    }
1704
1705    /// Borrows the `VMStoreContext` and the store's data at the same time.
1706    ///
1707    /// These are disjoint fields, so JIT-visible state can be reached alongside
1708    /// the tables in `StoreData` without a whole-store borrow in between.
1709    #[cfg(feature = "component-model")]
1710    pub(crate) fn vm_store_context_and_store_data_mut(
1711        &mut self,
1712    ) -> (&mut VMStoreContext, &mut StoreData) {
1713        (&mut self.vm_store_context, &mut self.store_data)
1714    }
1715
1716    #[cfg(feature = "debug")]
1717    pub(crate) fn breakpoints_and_registry_and_engine_mut(
1718        &mut self,
1719    ) -> (&mut Breakpoints, &mut ModuleRegistry, &Engine) {
1720        (&mut self.breakpoints, &mut self.modules, &self.engine)
1721    }
1722
1723    #[cfg(feature = "debug")]
1724    pub(crate) fn breakpoints_and_registry(&self) -> (&Breakpoints, &ModuleRegistry) {
1725        (&self.breakpoints, &self.modules)
1726    }
1727
1728    #[cfg(feature = "debug")]
1729    pub(crate) fn frame_data_cache(&self) -> &FrameDataCache {
1730        &self.frame_data_cache
1731    }
1732
1733    #[inline]
1734    pub(crate) fn modules(&self) -> &ModuleRegistry {
1735        &self.modules
1736    }
1737
1738    #[inline]
1739    pub(crate) fn modules_and_engine_and_breakpoints_mut(
1740        &mut self,
1741    ) -> (&mut ModuleRegistry, &Engine, RegisterBreakpointState<'_>) {
1742        #[cfg(feature = "debug")]
1743        let breakpoints = RegisterBreakpointState(&self.breakpoints);
1744        #[cfg(not(feature = "debug"))]
1745        let breakpoints = RegisterBreakpointState(core::marker::PhantomData);
1746
1747        (&mut self.modules, &self.engine, breakpoints)
1748    }
1749
1750    pub(crate) fn func_refs_and_modules(&mut self) -> (&mut FuncRefs, &ModuleRegistry) {
1751        (&mut self.func_refs, &self.modules)
1752    }
1753
1754    pub(crate) fn host_globals(
1755        &self,
1756    ) -> &TryPrimaryMap<DefinedGlobalIndex, StoreBox<VMHostGlobalContext>> {
1757        &self.host_globals
1758    }
1759
1760    pub(crate) fn host_globals_mut(
1761        &mut self,
1762    ) -> &mut TryPrimaryMap<DefinedGlobalIndex, StoreBox<VMHostGlobalContext>> {
1763        &mut self.host_globals
1764    }
1765
1766    pub fn module_for_instance(&self, instance: StoreInstanceId) -> Option<&'_ Module> {
1767        instance.store_id().assert_belongs_to(self.id());
1768        match self.instances[instance.instance()].kind {
1769            StoreInstanceKind::Dummy => None,
1770            StoreInstanceKind::Real { module_id } => {
1771                let module = self
1772                    .modules()
1773                    .module_by_id(module_id)
1774                    .expect("should always have a registered module for real instances");
1775                Some(module)
1776            }
1777        }
1778    }
1779
1780    /// Accessor from `InstanceId` to `&vm::Instance`.
1781    ///
1782    /// Note that if you have a `StoreInstanceId` you should use
1783    /// `StoreInstanceId::get` instead. This assumes that `id` has been
1784    /// validated to already belong to this store.
1785    #[inline]
1786    pub fn instance(&self, id: InstanceId) -> &vm::Instance {
1787        self.instances[id].handle.get()
1788    }
1789
1790    /// Accessor from `InstanceId` to `&vm::Instance`, if `id` is actually an
1791    /// instance within this store.
1792    ///
1793    /// Unlike `instance`, this does not assume `id` has already been validated,
1794    /// and so suits ids from an untrusted source.
1795    #[inline]
1796    pub fn try_instance(&self, id: InstanceId) -> Option<&vm::Instance> {
1797        Some(self.instances.get(id)?.handle.get())
1798    }
1799
1800    /// Accessor from `InstanceId` to `Pin<&mut vm::Instance>`.
1801    ///
1802    /// Note that if you have a `StoreInstanceId` you should use
1803    /// `StoreInstanceId::get_mut` instead. This assumes that `id` has been
1804    /// validated to already belong to this store.
1805    #[inline]
1806    pub fn instance_mut(&mut self, id: InstanceId) -> Pin<&mut vm::Instance> {
1807        self.instances[id].handle.get_mut()
1808    }
1809
1810    /// Accessor from `InstanceId` to both `Pin<&mut vm::Instance>`
1811    /// and `&ModuleRegistry`.
1812    #[inline]
1813    pub fn instance_and_module_registry_mut(
1814        &mut self,
1815        id: InstanceId,
1816    ) -> (Pin<&mut vm::Instance>, &ModuleRegistry) {
1817        (self.instances[id].handle.get_mut(), &self.modules)
1818    }
1819
1820    /// Access multiple instances specified via `ids`.
1821    ///
1822    /// # Panics
1823    ///
1824    /// This method will panic if any indices in `ids` overlap.
1825    ///
1826    /// # Safety
1827    ///
1828    /// This method is not safe if the returned instances are used to traverse
1829    /// "laterally" between other instances. For example accessing imported
1830    /// items in an instance may traverse laterally to a sibling instance thus
1831    /// aliasing a returned value here. The caller must ensure that only defined
1832    /// items within the instances themselves are accessed.
1833    #[inline]
1834    pub unsafe fn optional_gc_store_and_instances_mut<const N: usize>(
1835        &mut self,
1836        ids: [InstanceId; N],
1837    ) -> (Option<&mut GcStore>, [Pin<&mut vm::Instance>; N]) {
1838        let instances = self
1839            .instances
1840            .get_disjoint_mut(ids)
1841            .unwrap()
1842            .map(|h| h.handle.get_mut());
1843        (self.gc_store.as_mut(), instances)
1844    }
1845
1846    /// Pair of `Self::optional_gc_store_mut` and `Self::instance_mut`
1847    pub fn optional_gc_store_and_instance_mut(
1848        &mut self,
1849        id: InstanceId,
1850    ) -> (Option<&mut GcStore>, Pin<&mut vm::Instance>) {
1851        (self.gc_store.as_mut(), self.instances[id].handle.get_mut())
1852    }
1853
1854    /// Tuple of `Self::optional_gc_store_mut`, `Self::modules`, and
1855    /// `Self::instance_mut`.
1856    pub fn optional_gc_store_and_registry_and_instance_mut(
1857        &mut self,
1858        id: InstanceId,
1859    ) -> (
1860        Option<&mut GcStore>,
1861        &ModuleRegistry,
1862        Pin<&mut vm::Instance>,
1863    ) {
1864        (
1865            self.gc_store.as_mut(),
1866            &self.modules,
1867            self.instances[id].handle.get_mut(),
1868        )
1869    }
1870
1871    /// Get all instances (ignoring dummy instances) within this store.
1872    pub fn all_instances<'a>(&'a self) -> impl ExactSizeIterator<Item = Instance> + 'a {
1873        let instances = self
1874            .instances
1875            .iter()
1876            .filter_map(|(id, inst)| {
1877                if let StoreInstanceKind::Dummy = inst.kind {
1878                    None
1879                } else {
1880                    Some(id)
1881                }
1882            })
1883            .collect::<Vec<_>>();
1884        instances
1885            .into_iter()
1886            .map(|i| Instance::from_wasmtime(i, self))
1887    }
1888
1889    /// Get all memories (host- or Wasm-defined) within this store.
1890    pub fn all_memories<'a>(&'a self) -> impl Iterator<Item = ExportMemory> + 'a {
1891        // NB: Host-created memories have dummy instances. Therefore, we can get
1892        // all memories in the store by iterating over all instances (including
1893        // dummy instances) and getting each of their defined memories.
1894        let id = self.id();
1895        self.instances
1896            .iter()
1897            .flat_map(move |(_, instance)| instance.handle.get().defined_memories(id))
1898    }
1899
1900    /// Iterate over all tables (host- or Wasm-defined) within this store.
1901    pub fn for_each_table(&mut self, mut f: impl FnMut(&mut Self, Table)) {
1902        // NB: Host-created tables have dummy instances. Therefore, we can get
1903        // all tables in the store by iterating over all instances (including
1904        // dummy instances) and getting each of their defined memories.
1905        for id in self.instances.keys() {
1906            let instance = StoreInstanceId::new(self.id(), id);
1907            for table in 0..self.instance(id).env_module().num_defined_tables() {
1908                let table = DefinedTableIndex::new(table);
1909                f(self, Table::from_raw(instance, table));
1910            }
1911        }
1912    }
1913
1914    /// Iterate over all globals (host- or Wasm-defined) within this store.
1915    pub fn for_each_global(&mut self, mut f: impl FnMut(&mut Self, Global)) {
1916        // First enumerate all the host-created globals.
1917        for global in self.host_globals.keys() {
1918            let global = Global::new_host(self, global);
1919            f(self, global);
1920        }
1921
1922        // Then enumerate all instances' defined globals.
1923        for id in self.instances.keys() {
1924            for index in 0..self.instance(id).env_module().num_defined_globals() {
1925                let index = DefinedGlobalIndex::new(index);
1926                let global = Global::new_instance(self, id, index);
1927                f(self, global);
1928            }
1929        }
1930    }
1931
1932    #[cfg(all(feature = "std", any(unix, windows)))]
1933    pub fn set_signal_handler(&mut self, handler: Option<SignalHandler>) {
1934        self.signal_handler = handler;
1935    }
1936
1937    #[inline]
1938    pub fn vm_store_context(&self) -> &VMStoreContext {
1939        &self.vm_store_context
1940    }
1941
1942    #[inline]
1943    pub fn vm_store_context_mut(&mut self) -> &mut VMStoreContext {
1944        &mut self.vm_store_context
1945    }
1946
1947    /// Hook invoked on every transfer of control from Wasm to the host,
1948    /// before any host code can observe what Wasm did: when a
1949    /// host-to-Wasm call returns (normally, or by unwinding or trapping)
1950    /// back to the host, and when Wasm calls out to the host (via a host
1951    /// function or libcall).
1952    ///
1953    /// Wasm may have mutated state in this store without going through
1954    /// the `EpochState`s that guard it, so we treat invalidation of
1955    /// handles to that state as a deferred effect of running Wasm,
1956    /// performed here. Specifically, we:
1957    ///
1958    /// - bump `wasm_state`'s epoch, invalidating handles to Wasm
1959    ///   execution state, such as debugger `FrameHandle`s; and
1960    /// - invalidate every [`Unrooted`](crate::Unrooted) reference into
1961    ///   this store's GC heap, since compiled Wasm mutates the GC heap
1962    ///   directly; see `GcStore::invalidate_unrooted_refs`. (The GC heap
1963    ///   has its own `EpochState`, separate from `wasm_state`, because
1964    ///   the host API can also mutate it.)
1965    ///
1966    /// NB: there is intentionally no corresponding hook for transfers
1967    /// of control from the host to Wasm (calls into Wasm, returns from
1968    /// host functions or libcalls back to Wasm, or resumption of Wasm at
1969    /// an exception handler). Wasm has not run yet at that point, so
1970    /// there is nothing to invalidate: host code cannot observe anything
1971    /// Wasm does until control next transfers back to the host, which
1972    /// comes through here. Avoiding work after host functions and
1973    /// libcalls return is also important for performance: it would keep
1974    /// state live across those calls and defeat tail calls in libcall
1975    /// wrappers.
1976    #[inline(always)]
1977    pub(crate) fn on_wasm_to_host_transition(&mut self) {
1978        let _ = self.wasm_state.get_mut();
1979        if let Some(gc_store) = &mut self.gc_store {
1980            gc_store.invalidate_unrooted_refs();
1981        }
1982    }
1983
1984    /// The state standing in for all Wasm-mutated state in this store.
1985    ///
1986    /// The point of this is to allow taking handles from this
1987    /// `EpochState`, and later checking if they are still valid. If an
1988    /// epoch handle is still valid, that means that Wasm has not run in
1989    /// this store since the handle was created. That allows us to make
1990    /// certain assumptions, such as that observed Wasm stack frames are
1991    /// still present, and build higher-level safe primitives for
1992    /// observing these kinds of Wasm state.
1993    #[cfg(feature = "debug")]
1994    pub(crate) fn wasm_state(&self) -> &EpochState<WasmState> {
1995        &self.wasm_state
1996    }
1997
1998    /// Like `Self::optional_gc_store_mut`, but shared.
1999    #[inline]
2000    #[cfg(feature = "gc")]
2001    pub(crate) fn optional_gc_store(&self) -> Option<&GcStore> {
2002        self.gc_store.as_ref()
2003    }
2004
2005    /// Attempts to access the GC store that has been previously allocated.
2006    ///
2007    /// This method will return `Some` if the GC store was previously allocated.
2008    /// A `None` return value means either that the GC heap hasn't yet been
2009    /// allocated or that it does not need to be allocated for this store. Note
2010    /// that to require a GC store in a particular situation it's recommended to
2011    /// use [`Self::require_gc_store_mut`] instead.
2012    #[inline]
2013    pub(crate) fn optional_gc_store_mut(&mut self) -> Option<&mut GcStore> {
2014        if cfg!(not(feature = "gc")) || !self.engine.features().gc_types() {
2015            debug_assert!(self.gc_store.is_none());
2016            None
2017        } else {
2018            self.gc_store.as_mut()
2019        }
2020    }
2021
2022    /// Helper to assert that a GC store was previously allocated and is
2023    /// present.
2024    ///
2025    /// # Panics
2026    ///
2027    /// This method will panic if the GC store has not yet been allocated. This
2028    /// should only be used in a context where there's an existing GC reference,
2029    /// for example, or if `ensure_gc_store` has already been called.
2030    #[inline]
2031    #[track_caller]
2032    pub(crate) fn unwrap_gc_store(&self) -> &GcStore {
2033        self.gc_store
2034            .as_ref()
2035            .expect("attempted to access the store's GC heap before it has been allocated")
2036    }
2037
2038    /// Same as [`Self::unwrap_gc_store`], but mutable.
2039    #[inline]
2040    #[track_caller]
2041    pub(crate) fn unwrap_gc_store_mut(&mut self) -> &mut GcStore {
2042        self.gc_store
2043            .as_mut()
2044            .expect("attempted to access the store's GC heap before it has been allocated")
2045    }
2046
2047    /// Returns a mutable reference to the GC store if it has been allocated.
2048    #[inline]
2049    #[cfg(any(feature = "gc-drc", feature = "gc-copying"))]
2050    pub(crate) fn try_gc_store_mut(&mut self) -> Option<&mut GcStore> {
2051        self.gc_store.as_mut()
2052    }
2053
2054    /// Helper function execute a `init_gc_ref` when placing `gc_ref` in `dest`.
2055    ///
2056    /// This avoids allocating `GcStore` where possible.
2057    pub(crate) fn init_gc_ref(
2058        &mut self,
2059        dest: &mut MaybeUninit<Option<VMGcRef>>,
2060        gc_ref: Option<&VMGcRef>,
2061    ) -> Result<()> {
2062        if GcStore::needs_init_barrier(gc_ref) {
2063            self.unwrap_gc_store_mut().init_gc_ref(dest, gc_ref)
2064        } else {
2065            dest.write(gc_ref.map(|r| r.copy_i31()));
2066            Ok(())
2067        }
2068    }
2069
2070    /// Helper function execute a write barrier when placing `gc_ref` in `dest`.
2071    ///
2072    /// This avoids allocating `GcStore` where possible.
2073    pub(crate) fn write_gc_ref(
2074        &mut self,
2075        dest: &mut Option<VMGcRef>,
2076        gc_ref: Option<&VMGcRef>,
2077    ) -> Result<()> {
2078        GcStore::write_gc_ref_optional_store(self.optional_gc_store_mut(), dest, gc_ref)
2079    }
2080
2081    /// Helper function to clone `gc_ref` notably avoiding allocating a
2082    /// `GcStore` where possible.
2083    #[cfg(feature = "gc")]
2084    pub(crate) fn clone_gc_ref(&mut self, gc_ref: &VMGcRef) -> VMGcRef {
2085        if gc_ref.is_i31() {
2086            gc_ref.copy_i31()
2087        } else {
2088            self.unwrap_gc_store_mut().clone_gc_ref(gc_ref)
2089        }
2090    }
2091
2092    pub fn get_fuel(&self) -> Result<u64> {
2093        crate::ensure!(
2094            self.engine().tunables().consume_fuel,
2095            "fuel is not configured in this store"
2096        );
2097        let injected_fuel = unsafe { *self.vm_store_context.fuel_consumed.get() };
2098        Ok(get_fuel(injected_fuel, self.fuel_reserve))
2099    }
2100
2101    pub(crate) fn refuel(&mut self) -> bool {
2102        let injected_fuel = unsafe { &mut *self.vm_store_context.fuel_consumed.get() };
2103        refuel(
2104            injected_fuel,
2105            &mut self.fuel_reserve,
2106            self.fuel_yield_interval,
2107        )
2108    }
2109
2110    pub fn set_fuel(&mut self, fuel: u64) -> Result<()> {
2111        crate::ensure!(
2112            self.engine().tunables().consume_fuel,
2113            "fuel is not configured in this store"
2114        );
2115        let injected_fuel = unsafe { &mut *self.vm_store_context.fuel_consumed.get() };
2116        set_fuel(
2117            injected_fuel,
2118            &mut self.fuel_reserve,
2119            self.fuel_yield_interval,
2120            fuel,
2121        );
2122        Ok(())
2123    }
2124
2125    #[cfg(feature = "async")]
2126    pub fn fuel_async_yield_interval(&mut self, interval: Option<u64>) -> Result<()> {
2127        crate::ensure!(
2128            self.engine().tunables().consume_fuel,
2129            "fuel is not configured in this store"
2130        );
2131        crate::ensure!(
2132            interval != Some(0),
2133            "fuel_async_yield_interval must not be 0"
2134        );
2135
2136        // All future entrypoints must be async to handle the case that fuel
2137        // runs out and an async yield is needed.
2138        self.set_async_required(Asyncness::Yes);
2139
2140        self.fuel_yield_interval = interval.and_then(|i| NonZeroU64::new(i));
2141        // Reset the fuel active + reserve states by resetting the amount.
2142        self.set_fuel(self.get_fuel()?)
2143    }
2144
2145    #[inline]
2146    pub fn signal_handler(&self) -> Option<*const SignalHandler> {
2147        let handler = self.signal_handler.as_ref()?;
2148        Some(handler)
2149    }
2150
2151    #[inline]
2152    pub fn vm_store_context_ptr(&self) -> NonNull<VMStoreContext> {
2153        NonNull::from(&self.vm_store_context)
2154    }
2155
2156    #[inline]
2157    pub fn default_caller(&self) -> NonNull<VMContext> {
2158        self.default_caller_vmctx.as_non_null()
2159    }
2160
2161    #[inline]
2162    pub fn traitobj(&self) -> NonNull<dyn VMStore> {
2163        self.traitobj.0.unwrap()
2164    }
2165
2166    /// Takes the cached `Vec<Val>` stored internally across hostcalls to get
2167    /// used as part of calling the host in a `Func::new` method invocation.
2168    #[inline]
2169    pub fn take_hostcall_val_storage(&mut self) -> Vec<Val> {
2170        mem::take(&mut self.hostcall_val_storage)
2171    }
2172
2173    /// Restores the vector previously taken by `take_hostcall_val_storage`
2174    /// above back into the store, allowing it to be used in the future for the
2175    /// next wasm->host call.
2176    #[inline]
2177    pub fn save_hostcall_val_storage(&mut self, storage: Vec<Val>) {
2178        if storage.capacity() > self.hostcall_val_storage.capacity() {
2179            self.hostcall_val_storage = storage;
2180        }
2181    }
2182
2183    /// Same as `take_hostcall_val_storage`, but for the direction of the host
2184    /// calling wasm.
2185    #[inline]
2186    pub fn take_wasm_val_raw_storage(&mut self) -> TryVec<ValRaw> {
2187        mem::take(&mut self.wasm_val_raw_storage)
2188    }
2189
2190    /// Same as `save_hostcall_val_storage`, but for the direction of the host
2191    /// calling wasm.
2192    #[inline]
2193    pub fn save_wasm_val_raw_storage(&mut self, storage: TryVec<ValRaw>) {
2194        if storage.capacity() > self.wasm_val_raw_storage.capacity() {
2195            self.wasm_val_raw_storage = storage;
2196        }
2197    }
2198
2199    /// Translates a WebAssembly fault at the native `pc` and native `addr` to a
2200    /// WebAssembly-relative fault.
2201    ///
2202    /// This function may abort the process if `addr` is not found to actually
2203    /// reside in any linear memory. In such a situation it means that the
2204    /// segfault was erroneously caught by Wasmtime and is possibly indicative
2205    /// of a code generator bug.
2206    ///
2207    /// This function returns `None` for dynamically-bounds-checked-memories
2208    /// with spectre mitigations enabled since the hardware fault address is
2209    /// always zero in these situations which means that the trapping context
2210    /// doesn't have enough information to report the fault address.
2211    pub(crate) fn wasm_fault(&self, pc: usize, addr: usize) -> Option<vm::WasmFault> {
2212        // There are a few instances where a "close to zero" pointer is loaded
2213        // and we expect that to happen:
2214        //
2215        // * Explicitly bounds-checked memories with spectre-guards enabled will
2216        //   cause out-of-bounds accesses to get routed to address 0, so allow
2217        //   wasm instructions to fault on the null address.
2218        // * `call_indirect` when invoking a null function pointer may load data
2219        //   from the a `VMFuncRef` whose address is null, meaning any field of
2220        //   `VMFuncRef` could be the address of the fault.
2221        //
2222        // In these situations where the address is so small it won't be in any
2223        // instance, so skip the checks below.
2224        if addr <= mem::size_of::<VMFuncRef>() {
2225            const _: () = {
2226                // static-assert that `VMFuncRef` isn't too big to ensure that
2227                // it lives solely within the first page as we currently only
2228                // have the guarantee that the first page of memory is unmapped,
2229                // no more.
2230                assert!(mem::size_of::<VMFuncRef>() <= 512);
2231            };
2232            return None;
2233        }
2234
2235        // Search all known instances in this store for this address. Note that
2236        // this is probably not the speediest way to do this. Traps, however,
2237        // are generally not expected to be super fast and additionally stores
2238        // probably don't have all that many instances or memories.
2239        //
2240        // If this loop becomes hot in the future, however, it should be
2241        // possible to precompute maps about linear memories in a store and have
2242        // a quicker lookup.
2243        //
2244        // A shared memory can be defined by more than one instance in a store,
2245        // for example when it's imported through the single-memory instance
2246        // that `SharedMemory::vmimport` creates. Each of those instances
2247        // reports the same fault, so only assert that the faulting address
2248        // doesn't belong to two different memories. The memory size isn't
2249        // compared because a shared memory can grow concurrently.
2250        let mut fault: Option<vm::WasmFault> = None;
2251        for (_, instance) in self.instances.iter() {
2252            if let Some(f) = instance.handle.get().wasm_fault(addr) {
2253                match &fault {
2254                    Some(prev) => assert_eq!(prev.wasm_address, f.wasm_address),
2255                    None => fault = Some(f),
2256                }
2257            }
2258        }
2259        if fault.is_some() {
2260            return fault;
2261        }
2262
2263        cfg_select! {
2264            feature = "std" => {
2265                // With the standard library a rich error can be printed here
2266                // to stderr and the native abort path is used.
2267                eprintln!(
2268                    "\
2269Wasmtime caught a segfault for a wasm program because the faulting instruction
2270is allowed to segfault due to how linear memories are implemented. The address
2271that was accessed, however, is not known to any linear memory in use within this
2272Store. This may be indicative of a critical bug in Wasmtime's code generation
2273because all addresses which are known to be reachable from wasm won't reach this
2274message.
2275
2276    pc:      0x{pc:x}
2277    address: 0x{addr:x}
2278
2279This is a possible security issue because WebAssembly has accessed something it
2280shouldn't have been able to. Other accesses may have succeeded and this one just
2281happened to be caught. The process will now be aborted to prevent this damage
2282from going any further and to alert what's going on. If this is a security
2283issue please reach out to the Wasmtime team via its security policy
2284at https://bytecodealliance.org/security.
2285"
2286                );
2287                std::process::abort();
2288            }
2289            panic = "abort" => {
2290                // Without the standard library but with `panic=abort` then
2291                // it's safe to panic as that's known to halt execution. For
2292                // now avoid the above error message as well since without
2293                // `std` it's probably best to be a bit more size-conscious.
2294                let _ = pc;
2295                panic!("invalid fault");
2296            }
2297            _ => {
2298                // Without `std` and with `panic = "unwind"` there's no
2299                // dedicated API to abort the process portably, so manufacture
2300                // this with a double-panic.
2301                let _ = pc;
2302
2303                struct PanicAgainOnDrop;
2304
2305                impl Drop for PanicAgainOnDrop {
2306                    fn drop(&mut self) {
2307                        panic!("panicking again to trigger a process abort");
2308                    }
2309
2310                }
2311
2312                let _bomb = PanicAgainOnDrop;
2313
2314                panic!("invalid fault");
2315            }
2316        }
2317    }
2318
2319    /// Retrieve the store's protection key.
2320    #[inline]
2321    #[cfg(feature = "pooling-allocator")]
2322    pub(crate) fn get_pkey(&self) -> Option<ProtectionKey> {
2323        self.pkey
2324    }
2325
2326    #[cfg(feature = "async")]
2327    pub(crate) fn fiber_async_state_mut(&mut self) -> &mut fiber::AsyncState {
2328        &mut self.async_state
2329    }
2330
2331    #[cfg(feature = "async")]
2332    pub(crate) fn has_pkey(&self) -> bool {
2333        self.pkey.is_some()
2334    }
2335
2336    pub(crate) fn executor(&mut self) -> ExecutorRef<'_> {
2337        match &mut self.executor {
2338            Executor::Interpreter(i) => ExecutorRef::Interpreter(i.as_interpreter_ref()),
2339            #[cfg(has_host_compiler_backend)]
2340            Executor::Native => ExecutorRef::Native,
2341        }
2342    }
2343
2344    #[cfg(feature = "async")]
2345    pub(crate) fn swap_executor(&mut self, executor: &mut Executor) {
2346        mem::swap(&mut self.executor, executor);
2347    }
2348
2349    pub(crate) fn unwinder(&self) -> &'static dyn Unwind {
2350        match &self.executor {
2351            Executor::Interpreter(i) => i.unwinder(),
2352            #[cfg(has_host_compiler_backend)]
2353            Executor::Native => &vm::UnwindHost,
2354        }
2355    }
2356
2357    /// Allocates a new continuation. Note that we currently don't support
2358    /// deallocating them. Instead, all continuations remain allocated
2359    /// throughout the store's lifetime.
2360    #[cfg(feature = "stack-switching")]
2361    pub fn allocate_continuation(&mut self) -> Result<*mut VMContRef> {
2362        // FIXME(frank-emrich) Do we need to pin this?
2363        let mut continuation = Box::new(VMContRef::empty());
2364        let stack_size = self.engine.config().async_stack_size;
2365        let stack = crate::vm::VMContinuationStack::new(stack_size)?;
2366        #[cfg(asan)]
2367        {
2368            let asan_range = stack
2369                .asan_range()
2370                .expect("supported continuation stacks have a usable range");
2371            continuation.common_stack_information.asan.stack_bottom = Some(vm::VmPtr::from(
2372                NonNull::new(asan_range.start as *mut u8)
2373                    .expect("a continuation stack's ASan range must have a non-null bottom"),
2374            ));
2375            continuation.common_stack_information.asan.stack_size = asan_range.len();
2376        }
2377        continuation.stack = stack;
2378        let ptr = continuation.deref_mut() as *mut VMContRef;
2379        self.continuations.push(continuation);
2380        Ok(ptr)
2381    }
2382
2383    /// Constructs and executes an `InstanceAllocationRequest` and pushes the
2384    /// returned instance into the store.
2385    ///
2386    /// This is a helper method for invoking
2387    /// `InstanceAllocator::allocate_module` with the appropriate parameters
2388    /// from this store's own configuration. The `kind` provided is used to
2389    /// distinguish between "real" modules and dummy ones that are synthesized
2390    /// for embedder-created memories, globals, tables, etc. The `kind` will
2391    /// also use a different instance allocator by default, the one passed in,
2392    /// rather than the engine's default allocator.
2393    ///
2394    /// This method will push the instance within `StoreOpaque` onto the
2395    /// `instances` array and return the `InstanceId` which can be use to look
2396    /// it up within the store.
2397    ///
2398    /// # Safety
2399    ///
2400    /// The `imports` provided must be correctly sized/typed for the module
2401    /// being allocated.
2402    pub(crate) async unsafe fn allocate_instance(
2403        &mut self,
2404        limiter: Option<&mut StoreResourceLimiter<'_>>,
2405        kind: AllocateInstanceKind<'_>,
2406        runtime_info: &ModuleRuntimeInfo,
2407        imports: Imports<'_>,
2408    ) -> Result<InstanceId> {
2409        self.instances.reserve(1)?;
2410
2411        let id = self.instances.next_key();
2412
2413        let allocator = match kind {
2414            AllocateInstanceKind::Module(_) => self.engine().allocator(),
2415            AllocateInstanceKind::Dummy { allocator } => allocator,
2416        };
2417        // SAFETY: this function's own contract is the same as
2418        // `allocate_module`, namely the imports provided are valid.
2419        let handle = unsafe {
2420            allocator
2421                .allocate_module(InstanceAllocationRequest {
2422                    id,
2423                    runtime_info,
2424                    imports,
2425                    store: self,
2426                    limiter,
2427                })
2428                .await?
2429        };
2430
2431        let actual = match kind {
2432            AllocateInstanceKind::Module(module_id) => {
2433                log::trace!(
2434                    "Adding instance to store: store={:?}, module={module_id:?}, instance={id:?}",
2435                    self.id()
2436                );
2437                self.instances
2438                    .push(StoreInstance {
2439                        handle,
2440                        kind: StoreInstanceKind::Real { module_id },
2441                    })
2442                    .expect("capacity was reserved above")
2443            }
2444            AllocateInstanceKind::Dummy { .. } => {
2445                log::trace!(
2446                    "Adding dummy instance to store: store={:?}, instance={id:?}",
2447                    self.id()
2448                );
2449                self.instances
2450                    .push(StoreInstance {
2451                        handle,
2452                        kind: StoreInstanceKind::Dummy,
2453                    })
2454                    .expect("capacity was reserved above")
2455            }
2456        };
2457
2458        // double-check we didn't accidentally allocate two instances and our
2459        // prediction of what the id would be is indeed the id it should be.
2460        assert_eq!(id, actual);
2461
2462        Ok(id)
2463    }
2464
2465    #[cfg(target_has_atomic = "64")]
2466    pub(crate) fn set_epoch_deadline(&mut self, delta: u64) {
2467        // Set a new deadline based on the "epoch deadline delta".
2468        //
2469        // Also, note that when this update is performed while Wasm is
2470        // on the stack, the Wasm will reload the new value once we
2471        // return into it.
2472        let current_epoch = self.engine().current_epoch();
2473        let epoch_deadline = self.vm_store_context.epoch_deadline.get_mut();
2474        *epoch_deadline = current_epoch.saturating_add(delta).min(u64::MAX - 1);
2475    }
2476
2477    pub(crate) fn get_epoch_deadline(&mut self) -> u64 {
2478        *self.vm_store_context.epoch_deadline.get_mut()
2479    }
2480
2481    #[inline]
2482    pub(crate) fn validate_sync_call(&mut self) -> Result<()> {
2483        #[cfg(feature = "async")]
2484        if self.async_state.async_required {
2485            bail!("store configuration requires that `*_async` functions are used instead");
2486        }
2487        // We disallow `[Typed]Func::call` from a fiber since it can lead to
2488        // e.g. GC or epoch interruption which suspends the fiber, potentially
2489        // returning control to the embedder and allowing it to poll a top-level
2490        // `call_async` future from another thread, effectively and unsoundly
2491        // sending `!Send` data across threads.  In addition, allowing such
2492        // recursion risks panicking on stack overflow.
2493        if self.can_block() {
2494            bail!("cannot do blocking `call` from an async context");
2495        }
2496        Ok(())
2497    }
2498
2499    /// Returns whether this store is presently on a fiber and is allowed to
2500    /// block via `block_on` with fibers.
2501    pub(crate) fn can_block(&mut self) -> bool {
2502        #[cfg(feature = "async")]
2503        if true {
2504            return self.fiber_async_state_mut().can_block();
2505        }
2506
2507        false
2508    }
2509
2510    #[cfg(not(feature = "async"))]
2511    pub(crate) fn set_async_required(&mut self, asyncness: Asyncness) {
2512        match asyncness {
2513            Asyncness::No => {}
2514        }
2515    }
2516
2517    #[cfg(any(feature = "async", feature = "gc"))]
2518    pub(crate) async fn yield_now(&self) {
2519        // TODO: Once `Config` has an optional `AsyncFn` field for yielding to the
2520        // current async runtime (e.g. `tokio::task::yield_now`), use that if set;
2521        // otherwise fall back to the runtime-agnostic code.
2522        yield_now().await
2523    }
2524
2525    #[cfg(not(feature = "component-model"))]
2526    pub(crate) fn set_trapped(&mut self) {}
2527}
2528
2529#[cfg(any(feature = "async", feature = "gc"))]
2530async fn yield_now() {
2531    let mut yielded = false;
2532    future::poll_fn(move |cx| {
2533        if yielded {
2534            Poll::Ready(())
2535        } else {
2536            yielded = true;
2537            cx.waker().wake_by_ref();
2538            Poll::Pending
2539        }
2540    })
2541    .await;
2542}
2543
2544/// Helper parameter to [`StoreOpaque::allocate_instance`].
2545pub(crate) enum AllocateInstanceKind<'a> {
2546    /// An embedder-provided module is being allocated meaning that the default
2547    /// engine's allocator will be used.
2548    Module(RegisteredModuleId),
2549
2550    /// Add a dummy instance that to the store.
2551    ///
2552    /// These are instances that are just implementation details of something
2553    /// else (e.g. host-created memories that are not actually defined in any
2554    /// Wasm module) and therefore shouldn't show up in things like core dumps.
2555    ///
2556    /// A custom, typically OnDemand-flavored, allocator is provided to execute
2557    /// the allocation.
2558    Dummy {
2559        allocator: &'a dyn InstanceAllocator,
2560    },
2561}
2562
2563unsafe impl<T> VMStore for StoreInner<T> {
2564    #[cfg(feature = "component-model-async")]
2565    fn component_async_store(
2566        &mut self,
2567    ) -> &mut dyn crate::runtime::component::VMComponentAsyncStore {
2568        self
2569    }
2570
2571    #[cfg(feature = "call-hook")]
2572    fn call_hook(&mut self, s: CallHook) -> Result<()> {
2573        StoreInner::call_hook(self, s)
2574    }
2575
2576    fn resource_limiter_and_store_opaque(
2577        &mut self,
2578    ) -> (Option<StoreResourceLimiter<'_>>, &mut StoreOpaque) {
2579        let (data, limiter, opaque) = self.data_limiter_and_opaque();
2580
2581        let limiter = limiter.map(|l| match l {
2582            ResourceLimiterInner::Sync(s) => StoreResourceLimiter::Sync(s(data)),
2583            #[cfg(feature = "async")]
2584            ResourceLimiterInner::Async(s) => StoreResourceLimiter::Async(s(data)),
2585        });
2586
2587        (limiter, opaque)
2588    }
2589
2590    #[cfg(target_has_atomic = "64")]
2591    fn new_epoch_updated_deadline(&mut self) -> Result<UpdateDeadline> {
2592        // Temporarily take the configured behavior to avoid mutably borrowing
2593        // multiple times.
2594        let behavior = self.epoch_deadline_behavior.take();
2595        let mut undo = Undo::new((self, behavior), |(store, behavior)| {
2596            store.epoch_deadline_behavior = behavior;
2597        });
2598        let (store, behavior) = &mut *undo;
2599        match behavior {
2600            Some(callback) => callback(StoreHookState::new((&mut **store).as_context_mut())),
2601            None => Ok(UpdateDeadline::Interrupt),
2602        }
2603    }
2604
2605    #[cfg(feature = "debug")]
2606    fn block_on_debug_handler(&mut self, event: crate::DebugEvent<'_>) -> crate::Result<()> {
2607        if let Some(handler) = self.debug_handler.take() {
2608            if !self.can_block() {
2609                bail!("could not invoke debug handler without async context");
2610            }
2611            log::trace!("about to raise debug event {event:?}");
2612            StoreContextMut(self).with_blocking(|store, cx| {
2613                cx.block_on(Pin::from(handler.handle(store, event)).as_mut())
2614            })
2615        } else {
2616            Ok(())
2617        }
2618    }
2619}
2620
2621impl<T> StoreInner<T> {
2622    #[cfg(target_has_atomic = "64")]
2623    fn epoch_deadline_trap(&mut self) {
2624        self.epoch_deadline_behavior = None;
2625    }
2626
2627    #[cfg(target_has_atomic = "64")]
2628    fn epoch_deadline_callback(
2629        &mut self,
2630        callback: Box<dyn FnMut(StoreHookState<T>) -> Result<UpdateDeadline> + Send + Sync>,
2631    ) {
2632        self.epoch_deadline_behavior = Some(callback);
2633    }
2634}
2635
2636impl<T: Default> Default for Store<T> {
2637    fn default() -> Store<T> {
2638        Store::new(&Engine::default(), T::default())
2639    }
2640}
2641
2642impl<T: fmt::Debug> fmt::Debug for Store<T> {
2643    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2644        let inner = &**self.inner as *const StoreInner<T>;
2645        f.debug_struct("Store")
2646            .field("inner", &inner)
2647            .field("data", self.inner.data())
2648            .finish()
2649    }
2650}
2651
2652impl<T> Drop for Store<T> {
2653    fn drop(&mut self) {
2654        self.run_manual_drop_routines();
2655
2656        // For documentation on this `unsafe`, see `into_data`.
2657        unsafe {
2658            ManuallyDrop::drop(&mut self.inner.data_no_provenance);
2659            ManuallyDrop::drop(&mut self.inner);
2660        }
2661    }
2662}
2663
2664impl Drop for StoreOpaque {
2665    fn drop(&mut self) {
2666        // NB it's important that this destructor does not access `self.data`.
2667        // That is deallocated by `Drop for Store<T>` above.
2668
2669        unsafe {
2670            let allocator = self.engine.allocator();
2671            let ondemand = OnDemandInstanceAllocator::default();
2672            let store_id = self.id();
2673
2674            #[cfg(feature = "gc")]
2675            if let Some(mut gc_store) = self.gc_store.take() {
2676                let gc_alloc_index = gc_store.allocation_index;
2677                log::trace!("store {store_id:?} is deallocating GC heap {gc_alloc_index:?}");
2678                debug_assert!(self.engine.features().gc_types());
2679                let mem = gc_store.gc_heap.get_mut().detach();
2680                let mem_alloc_index =
2681                    allocator.deallocate_gc_heap(gc_alloc_index, gc_store.gc_heap.into_inner());
2682                allocator.deallocate_memory(None, mem_alloc_index, mem);
2683            }
2684
2685            for (id, instance) in self.instances.iter_mut() {
2686                log::trace!("store {store_id:?} is deallocating {id:?}");
2687                let allocator = match instance.kind {
2688                    StoreInstanceKind::Dummy => &ondemand,
2689                    _ => allocator,
2690                };
2691                allocator.deallocate_module(&mut instance.handle);
2692            }
2693
2694            self.store_data.decrement_allocator_resources(allocator);
2695        }
2696    }
2697}
2698
2699#[cfg_attr(
2700    not(any(feature = "gc", feature = "async")),
2701    // NB: Rust 1.89, current stable, does not fire this lint. Rust 1.90,
2702    // however, does, so use #[allow] until our MSRV is 1.90.
2703    allow(dead_code, reason = "don't want to put #[cfg] on all impls below too")
2704)]
2705pub(crate) trait AsStoreOpaque {
2706    fn as_store_opaque(&mut self) -> &mut StoreOpaque;
2707}
2708
2709impl AsStoreOpaque for StoreOpaque {
2710    fn as_store_opaque(&mut self) -> &mut StoreOpaque {
2711        self
2712    }
2713}
2714
2715impl AsStoreOpaque for dyn VMStore {
2716    fn as_store_opaque(&mut self) -> &mut StoreOpaque {
2717        self
2718    }
2719}
2720
2721impl<T: 'static> AsStoreOpaque for Store<T> {
2722    fn as_store_opaque(&mut self) -> &mut StoreOpaque {
2723        &mut self.inner.inner
2724    }
2725}
2726
2727impl<T: 'static> AsStoreOpaque for StoreInner<T> {
2728    fn as_store_opaque(&mut self) -> &mut StoreOpaque {
2729        self
2730    }
2731}
2732
2733impl<T: AsStoreOpaque + ?Sized> AsStoreOpaque for &mut T {
2734    fn as_store_opaque(&mut self) -> &mut StoreOpaque {
2735        T::as_store_opaque(self)
2736    }
2737}
2738
2739/// Helper enum to indicate, in some function contexts, whether `async` should
2740/// be taken advantage of or not.
2741///
2742/// This is used throughout Wasmtime where internal functions are all `async`
2743/// but external functions might be either sync or `async`. If the external
2744/// function is sync, then internally Wasmtime shouldn't yield as it won't do
2745/// anything. If the external function is `async`, however, yields are fine.
2746///
2747/// An example of this is GC. Right now GC will cooperatively yield after phases
2748/// of GC have passed, but this cooperative yielding is only enabled with
2749/// `Asyncness::Yes`.
2750///
2751/// This enum is additionally conditionally defined such that `Yes` is only
2752/// present in `async`-enabled builds. That ensures that this compiles down to a
2753/// zero-sized type in `async`-disabled builds in case that interests embedders.
2754#[derive(PartialEq, Eq, Copy, Clone)]
2755pub enum Asyncness {
2756    /// Don't do async things, don't yield, etc. It's ok to execute an `async`
2757    /// function, but it should be validated ahead of time that when doing so a
2758    /// yield isn't possible (e.g. `validate_sync_*` methods on Store.
2759    No,
2760
2761    /// Async things is OK. This should only be used when the API entrypoint is
2762    /// itself `async`.
2763    #[cfg(feature = "async")]
2764    Yes,
2765}
2766
2767impl core::ops::BitOr for Asyncness {
2768    type Output = Self;
2769
2770    fn bitor(self, rhs: Self) -> Self::Output {
2771        match (self, rhs) {
2772            (Asyncness::No, Asyncness::No) => Asyncness::No,
2773            #[cfg(feature = "async")]
2774            (Asyncness::Yes, _) | (_, Asyncness::Yes) => Asyncness::Yes,
2775        }
2776    }
2777}
2778
2779#[cfg(test)]
2780mod tests {
2781    use super::*;
2782
2783    struct FuelTank {
2784        pub consumed_fuel: i64,
2785        pub reserve_fuel: u64,
2786        pub yield_interval: Option<NonZeroU64>,
2787    }
2788
2789    impl FuelTank {
2790        fn new() -> Self {
2791            FuelTank {
2792                consumed_fuel: 0,
2793                reserve_fuel: 0,
2794                yield_interval: None,
2795            }
2796        }
2797        fn get_fuel(&self) -> u64 {
2798            get_fuel(self.consumed_fuel, self.reserve_fuel)
2799        }
2800        fn refuel(&mut self) -> bool {
2801            refuel(
2802                &mut self.consumed_fuel,
2803                &mut self.reserve_fuel,
2804                self.yield_interval,
2805            )
2806        }
2807        fn set_fuel(&mut self, fuel: u64) {
2808            set_fuel(
2809                &mut self.consumed_fuel,
2810                &mut self.reserve_fuel,
2811                self.yield_interval,
2812                fuel,
2813            );
2814        }
2815    }
2816
2817    #[test]
2818    fn smoke() {
2819        let mut tank = FuelTank::new();
2820        tank.set_fuel(10);
2821        assert_eq!(tank.consumed_fuel, -10);
2822        assert_eq!(tank.reserve_fuel, 0);
2823
2824        tank.yield_interval = NonZeroU64::new(10);
2825        tank.set_fuel(25);
2826        assert_eq!(tank.consumed_fuel, -10);
2827        assert_eq!(tank.reserve_fuel, 15);
2828    }
2829
2830    #[test]
2831    fn does_not_lose_precision() {
2832        let mut tank = FuelTank::new();
2833        tank.set_fuel(u64::MAX);
2834        assert_eq!(tank.get_fuel(), u64::MAX);
2835
2836        tank.set_fuel(i64::MAX as u64);
2837        assert_eq!(tank.get_fuel(), i64::MAX as u64);
2838
2839        tank.set_fuel(i64::MAX as u64 + 1);
2840        assert_eq!(tank.get_fuel(), i64::MAX as u64 + 1);
2841    }
2842
2843    #[test]
2844    fn yielding_does_not_lose_precision() {
2845        let mut tank = FuelTank::new();
2846
2847        tank.yield_interval = NonZeroU64::new(10);
2848        tank.set_fuel(u64::MAX);
2849        assert_eq!(tank.get_fuel(), u64::MAX);
2850        assert_eq!(tank.consumed_fuel, -10);
2851        assert_eq!(tank.reserve_fuel, u64::MAX - 10);
2852
2853        tank.yield_interval = NonZeroU64::new(u64::MAX);
2854        tank.set_fuel(u64::MAX);
2855        assert_eq!(tank.get_fuel(), u64::MAX);
2856        assert_eq!(tank.consumed_fuel, -i64::MAX);
2857        assert_eq!(tank.reserve_fuel, u64::MAX - (i64::MAX as u64));
2858
2859        tank.yield_interval = NonZeroU64::new((i64::MAX as u64) + 1);
2860        tank.set_fuel(u64::MAX);
2861        assert_eq!(tank.get_fuel(), u64::MAX);
2862        assert_eq!(tank.consumed_fuel, -i64::MAX);
2863        assert_eq!(tank.reserve_fuel, u64::MAX - (i64::MAX as u64));
2864    }
2865
2866    #[test]
2867    fn refueling() {
2868        // It's possible to fuel to have consumed over the limit as some instructions can consume
2869        // multiple units of fuel at once. Refueling should be strict in it's consumption and not
2870        // add more fuel than there is.
2871        let mut tank = FuelTank::new();
2872
2873        tank.yield_interval = NonZeroU64::new(10);
2874        tank.reserve_fuel = 42;
2875        tank.consumed_fuel = 4;
2876        assert!(tank.refuel());
2877        assert_eq!(tank.reserve_fuel, 28);
2878        assert_eq!(tank.consumed_fuel, -10);
2879
2880        tank.yield_interval = NonZeroU64::new(1);
2881        tank.reserve_fuel = 8;
2882        tank.consumed_fuel = 4;
2883        assert_eq!(tank.get_fuel(), 4);
2884        assert!(tank.refuel());
2885        assert_eq!(tank.reserve_fuel, 3);
2886        assert_eq!(tank.consumed_fuel, -1);
2887        assert_eq!(tank.get_fuel(), 4);
2888
2889        tank.yield_interval = NonZeroU64::new(10);
2890        tank.reserve_fuel = 3;
2891        tank.consumed_fuel = 4;
2892        assert_eq!(tank.get_fuel(), 0);
2893        assert!(!tank.refuel());
2894        assert_eq!(tank.reserve_fuel, 3);
2895        assert_eq!(tank.consumed_fuel, 4);
2896        assert_eq!(tank.get_fuel(), 0);
2897    }
2898
2899    #[test]
2900    fn store_data_provenance() {
2901        // Test that we juggle pointer provenance and all that correctly, and
2902        // miri is happy with everything, while allowing both Rust code and
2903        // "Wasm" to access and modify the store's `T` data. Note that this is
2904        // not actually Wasm mutating the store data here because compiling Wasm
2905        // under miri is way too slow.
2906
2907        unsafe fn run_wasm(store: &mut Store<u32>) {
2908            let ptr = store
2909                .inner
2910                .inner
2911                .vm_store_context
2912                .store_data
2913                .as_ptr()
2914                .cast::<u32>();
2915            unsafe { *ptr += 1 }
2916        }
2917
2918        let engine = Engine::default();
2919        let mut store = Store::new(&engine, 0_u32);
2920
2921        assert_eq!(*store.data(), 0);
2922        *store.data_mut() += 1;
2923        assert_eq!(*store.data(), 1);
2924        unsafe { run_wasm(&mut store) }
2925        assert_eq!(*store.data(), 2);
2926        *store.data_mut() += 1;
2927        assert_eq!(*store.data(), 3);
2928    }
2929}