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