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
1529fn bump(slot: &mut usize, max: usize, amt: usize, desc: &str) -> Result<()> {
1530 let new = slot.saturating_add(amt);
1531 if new > max {
1532 bail!("resource limit exceeded: {desc} count too high at {new}");
1533 }
1534 *slot = new;
1535 Ok(())
1536}
1537
1538#[doc(hidden)]
1539impl StoreOpaque {
1540 pub fn id(&self) -> StoreId {
1541 self.store_data.id()
1542 }
1543
1544 pub fn bump_resource_counts(&mut self, module: &Module) -> Result<()> {
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 pub fn bump_memory_count(&mut self) -> Result<()> {
1562 bump(&mut self.memory_count, self.memory_limit, 1, "memory")
1563 }
1564
1565 pub fn bump_table_count(&mut self) -> Result<()> {
1566 bump(&mut self.table_count, self.table_limit, 1, "table")
1567 }
1568
1569 #[inline]
1570 pub fn engine(&self) -> &Engine {
1571 &self.engine
1572 }
1573
1574 #[inline]
1575 pub fn store_data(&self) -> &StoreData {
1576 &self.store_data
1577 }
1578
1579 #[inline]
1580 pub fn store_data_mut(&mut self) -> &mut StoreData {
1581 &mut self.store_data
1582 }
1583
1584 pub fn store_data_mut_and_registry(&mut self) -> (&mut StoreData, &ModuleRegistry) {
1585 (&mut self.store_data, &self.modules)
1586 }
1587
1588 #[cfg(feature = "debug")]
1589 pub(crate) fn breakpoints_and_registry_and_engine_mut(
1590 &mut self,
1591 ) -> (&mut BreakpointState, &mut ModuleRegistry, &Engine) {
1592 (&mut self.breakpoints, &mut self.modules, &self.engine)
1593 }
1594
1595 #[cfg(feature = "debug")]
1596 pub(crate) fn breakpoints_and_registry(&self) -> (&BreakpointState, &ModuleRegistry) {
1597 (&self.breakpoints, &self.modules)
1598 }
1599
1600 #[cfg(feature = "debug")]
1601 pub(crate) fn frame_data_cache_mut_and_registry(
1602 &mut self,
1603 ) -> (&mut FrameDataCache, &ModuleRegistry) {
1604 (&mut self.frame_data_cache, &self.modules)
1605 }
1606
1607 #[inline]
1608 pub(crate) fn modules(&self) -> &ModuleRegistry {
1609 &self.modules
1610 }
1611
1612 #[inline]
1613 pub(crate) fn modules_and_engine_and_breakpoints_mut(
1614 &mut self,
1615 ) -> (&mut ModuleRegistry, &Engine, RegisterBreakpointState<'_>) {
1616 #[cfg(feature = "debug")]
1617 let breakpoints = RegisterBreakpointState(&self.breakpoints);
1618 #[cfg(not(feature = "debug"))]
1619 let breakpoints = RegisterBreakpointState(core::marker::PhantomData);
1620
1621 (&mut self.modules, &self.engine, breakpoints)
1622 }
1623
1624 pub(crate) fn func_refs_and_modules(&mut self) -> (&mut FuncRefs, &ModuleRegistry) {
1625 (&mut self.func_refs, &self.modules)
1626 }
1627
1628 pub(crate) fn host_globals(
1629 &self,
1630 ) -> &TryPrimaryMap<DefinedGlobalIndex, StoreBox<VMHostGlobalContext>> {
1631 &self.host_globals
1632 }
1633
1634 pub(crate) fn host_globals_mut(
1635 &mut self,
1636 ) -> &mut TryPrimaryMap<DefinedGlobalIndex, StoreBox<VMHostGlobalContext>> {
1637 &mut self.host_globals
1638 }
1639
1640 pub fn module_for_instance(&self, instance: StoreInstanceId) -> Option<&'_ Module> {
1641 instance.store_id().assert_belongs_to(self.id());
1642 match self.instances[instance.instance()].kind {
1643 StoreInstanceKind::Dummy => None,
1644 StoreInstanceKind::Real { module_id } => {
1645 let module = self
1646 .modules()
1647 .module_by_id(module_id)
1648 .expect("should always have a registered module for real instances");
1649 Some(module)
1650 }
1651 }
1652 }
1653
1654 /// Accessor from `InstanceId` to `&vm::Instance`.
1655 ///
1656 /// Note that if you have a `StoreInstanceId` you should use
1657 /// `StoreInstanceId::get` instead. This assumes that `id` has been
1658 /// validated to already belong to this store.
1659 #[inline]
1660 pub fn instance(&self, id: InstanceId) -> &vm::Instance {
1661 self.instances[id].handle.get()
1662 }
1663
1664 /// Accessor from `InstanceId` to `&vm::Instance`, if `id` is actually an
1665 /// instance within this store.
1666 ///
1667 /// Unlike `instance`, this does not assume `id` has already been validated,
1668 /// and so suits ids from an untrusted source.
1669 #[inline]
1670 pub fn try_instance(&self, id: InstanceId) -> Option<&vm::Instance> {
1671 Some(self.instances.get(id)?.handle.get())
1672 }
1673
1674 /// Accessor from `InstanceId` to `Pin<&mut vm::Instance>`.
1675 ///
1676 /// Note that if you have a `StoreInstanceId` you should use
1677 /// `StoreInstanceId::get_mut` instead. This assumes that `id` has been
1678 /// validated to already belong to this store.
1679 #[inline]
1680 pub fn instance_mut(&mut self, id: InstanceId) -> Pin<&mut vm::Instance> {
1681 self.instances[id].handle.get_mut()
1682 }
1683
1684 /// Accessor from `InstanceId` to both `Pin<&mut vm::Instance>`
1685 /// and `&ModuleRegistry`.
1686 #[inline]
1687 pub fn instance_and_module_registry_mut(
1688 &mut self,
1689 id: InstanceId,
1690 ) -> (Pin<&mut vm::Instance>, &ModuleRegistry) {
1691 (self.instances[id].handle.get_mut(), &self.modules)
1692 }
1693
1694 /// Access multiple instances specified via `ids`.
1695 ///
1696 /// # Panics
1697 ///
1698 /// This method will panic if any indices in `ids` overlap.
1699 ///
1700 /// # Safety
1701 ///
1702 /// This method is not safe if the returned instances are used to traverse
1703 /// "laterally" between other instances. For example accessing imported
1704 /// items in an instance may traverse laterally to a sibling instance thus
1705 /// aliasing a returned value here. The caller must ensure that only defined
1706 /// items within the instances themselves are accessed.
1707 #[inline]
1708 pub unsafe fn optional_gc_store_and_instances_mut<const N: usize>(
1709 &mut self,
1710 ids: [InstanceId; N],
1711 ) -> (Option<&mut GcStore>, [Pin<&mut vm::Instance>; N]) {
1712 let instances = self
1713 .instances
1714 .get_disjoint_mut(ids)
1715 .unwrap()
1716 .map(|h| h.handle.get_mut());
1717 (self.gc_store.as_mut(), instances)
1718 }
1719
1720 /// Pair of `Self::optional_gc_store_mut` and `Self::instance_mut`
1721 pub fn optional_gc_store_and_instance_mut(
1722 &mut self,
1723 id: InstanceId,
1724 ) -> (Option<&mut GcStore>, Pin<&mut vm::Instance>) {
1725 (self.gc_store.as_mut(), self.instances[id].handle.get_mut())
1726 }
1727
1728 /// Tuple of `Self::optional_gc_store_mut`, `Self::modules`, and
1729 /// `Self::instance_mut`.
1730 pub fn optional_gc_store_and_registry_and_instance_mut(
1731 &mut self,
1732 id: InstanceId,
1733 ) -> (
1734 Option<&mut GcStore>,
1735 &ModuleRegistry,
1736 Pin<&mut vm::Instance>,
1737 ) {
1738 (
1739 self.gc_store.as_mut(),
1740 &self.modules,
1741 self.instances[id].handle.get_mut(),
1742 )
1743 }
1744
1745 /// Get all instances (ignoring dummy instances) within this store.
1746 pub fn all_instances<'a>(&'a mut self) -> impl ExactSizeIterator<Item = Instance> + 'a {
1747 let instances = self
1748 .instances
1749 .iter()
1750 .filter_map(|(id, inst)| {
1751 if let StoreInstanceKind::Dummy = inst.kind {
1752 None
1753 } else {
1754 Some(id)
1755 }
1756 })
1757 .collect::<Vec<_>>();
1758 instances
1759 .into_iter()
1760 .map(|i| Instance::from_wasmtime(i, self))
1761 }
1762
1763 /// Get all memories (host- or Wasm-defined) within this store.
1764 pub fn all_memories<'a>(&'a self) -> impl Iterator<Item = ExportMemory> + 'a {
1765 // NB: Host-created memories have dummy instances. Therefore, we can get
1766 // all memories in the store by iterating over all instances (including
1767 // dummy instances) and getting each of their defined memories.
1768 let id = self.id();
1769 self.instances
1770 .iter()
1771 .flat_map(move |(_, instance)| instance.handle.get().defined_memories(id))
1772 }
1773
1774 /// Iterate over all tables (host- or Wasm-defined) within this store.
1775 pub fn for_each_table(&mut self, mut f: impl FnMut(&mut Self, Table)) {
1776 // NB: Host-created tables have dummy instances. Therefore, we can get
1777 // all tables in the store by iterating over all instances (including
1778 // dummy instances) and getting each of their defined memories.
1779 for id in self.instances.keys() {
1780 let instance = StoreInstanceId::new(self.id(), id);
1781 for table in 0..self.instance(id).env_module().num_defined_tables() {
1782 let table = DefinedTableIndex::new(table);
1783 f(self, Table::from_raw(instance, table));
1784 }
1785 }
1786 }
1787
1788 /// Iterate over all globals (host- or Wasm-defined) within this store.
1789 pub fn for_each_global(&mut self, mut f: impl FnMut(&mut Self, Global)) {
1790 // First enumerate all the host-created globals.
1791 for global in self.host_globals.keys() {
1792 let global = Global::new_host(self, global);
1793 f(self, global);
1794 }
1795
1796 // Then enumerate all instances' defined globals.
1797 for id in self.instances.keys() {
1798 for index in 0..self.instance(id).env_module().num_defined_globals() {
1799 let index = DefinedGlobalIndex::new(index);
1800 let global = Global::new_instance(self, id, index);
1801 f(self, global);
1802 }
1803 }
1804 }
1805
1806 #[cfg(all(feature = "std", any(unix, windows)))]
1807 pub fn set_signal_handler(&mut self, handler: Option<SignalHandler>) {
1808 self.signal_handler = handler;
1809 }
1810
1811 #[inline]
1812 pub fn vm_store_context(&self) -> &VMStoreContext {
1813 &self.vm_store_context
1814 }
1815
1816 #[inline]
1817 pub fn vm_store_context_mut(&mut self) -> &mut VMStoreContext {
1818 &mut self.vm_store_context
1819 }
1820
1821 /// Attempts to access the GC store that has been previously allocated.
1822 ///
1823 /// This method will return `Some` if the GC store was previously allocated.
1824 /// A `None` return value means either that the GC heap hasn't yet been
1825 /// allocated or that it does not need to be allocated for this store. Note
1826 /// that to require a GC store in a particular situation it's recommended to
1827 /// use [`Self::require_gc_store_mut`] instead.
1828 #[inline]
1829 pub(crate) fn optional_gc_store_mut(&mut self) -> Option<&mut GcStore> {
1830 if cfg!(not(feature = "gc")) || !self.engine.features().gc_types() {
1831 debug_assert!(self.gc_store.is_none());
1832 None
1833 } else {
1834 self.gc_store.as_mut()
1835 }
1836 }
1837
1838 /// Helper to assert that a GC store was previously allocated and is
1839 /// present.
1840 ///
1841 /// # Panics
1842 ///
1843 /// This method will panic if the GC store has not yet been allocated. This
1844 /// should only be used in a context where there's an existing GC reference,
1845 /// for example, or if `ensure_gc_store` has already been called.
1846 #[inline]
1847 #[track_caller]
1848 pub(crate) fn unwrap_gc_store(&self) -> &GcStore {
1849 self.gc_store
1850 .as_ref()
1851 .expect("attempted to access the store's GC heap before it has been allocated")
1852 }
1853
1854 /// Same as [`Self::unwrap_gc_store`], but mutable.
1855 #[inline]
1856 #[track_caller]
1857 pub(crate) fn unwrap_gc_store_mut(&mut self) -> &mut GcStore {
1858 self.gc_store
1859 .as_mut()
1860 .expect("attempted to access the store's GC heap before it has been allocated")
1861 }
1862
1863 /// Returns a mutable reference to the GC store if it has been allocated.
1864 #[inline]
1865 #[cfg(any(feature = "gc-drc", feature = "gc-copying"))]
1866 pub(crate) fn try_gc_store_mut(&mut self) -> Option<&mut GcStore> {
1867 self.gc_store.as_mut()
1868 }
1869
1870 /// Helper function execute a `init_gc_ref` when placing `gc_ref` in `dest`.
1871 ///
1872 /// This avoids allocating `GcStore` where possible.
1873 pub(crate) fn init_gc_ref(
1874 &mut self,
1875 dest: &mut MaybeUninit<Option<VMGcRef>>,
1876 gc_ref: Option<&VMGcRef>,
1877 ) -> Result<()> {
1878 if GcStore::needs_init_barrier(gc_ref) {
1879 self.unwrap_gc_store_mut().init_gc_ref(dest, gc_ref)
1880 } else {
1881 dest.write(gc_ref.map(|r| r.copy_i31()));
1882 Ok(())
1883 }
1884 }
1885
1886 /// Helper function execute a write barrier when placing `gc_ref` in `dest`.
1887 ///
1888 /// This avoids allocating `GcStore` where possible.
1889 pub(crate) fn write_gc_ref(
1890 &mut self,
1891 dest: &mut Option<VMGcRef>,
1892 gc_ref: Option<&VMGcRef>,
1893 ) -> Result<()> {
1894 GcStore::write_gc_ref_optional_store(self.optional_gc_store_mut(), dest, gc_ref)
1895 }
1896
1897 /// Helper function to clone `gc_ref` notably avoiding allocating a
1898 /// `GcStore` where possible.
1899 pub(crate) fn clone_gc_ref(&mut self, gc_ref: &VMGcRef) -> VMGcRef {
1900 if gc_ref.is_i31() {
1901 gc_ref.copy_i31()
1902 } else {
1903 self.unwrap_gc_store_mut().clone_gc_ref(gc_ref)
1904 }
1905 }
1906
1907 pub fn get_fuel(&self) -> Result<u64> {
1908 crate::ensure!(
1909 self.engine().tunables().consume_fuel,
1910 "fuel is not configured in this store"
1911 );
1912 let injected_fuel = unsafe { *self.vm_store_context.fuel_consumed.get() };
1913 Ok(get_fuel(injected_fuel, self.fuel_reserve))
1914 }
1915
1916 pub(crate) fn refuel(&mut self) -> bool {
1917 let injected_fuel = unsafe { &mut *self.vm_store_context.fuel_consumed.get() };
1918 refuel(
1919 injected_fuel,
1920 &mut self.fuel_reserve,
1921 self.fuel_yield_interval,
1922 )
1923 }
1924
1925 pub fn set_fuel(&mut self, fuel: u64) -> Result<()> {
1926 crate::ensure!(
1927 self.engine().tunables().consume_fuel,
1928 "fuel is not configured in this store"
1929 );
1930 let injected_fuel = unsafe { &mut *self.vm_store_context.fuel_consumed.get() };
1931 set_fuel(
1932 injected_fuel,
1933 &mut self.fuel_reserve,
1934 self.fuel_yield_interval,
1935 fuel,
1936 );
1937 Ok(())
1938 }
1939
1940 #[cfg(feature = "async")]
1941 pub fn fuel_async_yield_interval(&mut self, interval: Option<u64>) -> Result<()> {
1942 crate::ensure!(
1943 self.engine().tunables().consume_fuel,
1944 "fuel is not configured in this store"
1945 );
1946 crate::ensure!(
1947 interval != Some(0),
1948 "fuel_async_yield_interval must not be 0"
1949 );
1950
1951 // All future entrypoints must be async to handle the case that fuel
1952 // runs out and an async yield is needed.
1953 self.set_async_required(Asyncness::Yes);
1954
1955 self.fuel_yield_interval = interval.and_then(|i| NonZeroU64::new(i));
1956 // Reset the fuel active + reserve states by resetting the amount.
1957 self.set_fuel(self.get_fuel()?)
1958 }
1959
1960 #[inline]
1961 pub fn signal_handler(&self) -> Option<*const SignalHandler> {
1962 let handler = self.signal_handler.as_ref()?;
1963 Some(handler)
1964 }
1965
1966 #[inline]
1967 pub fn vm_store_context_ptr(&self) -> NonNull<VMStoreContext> {
1968 NonNull::from(&self.vm_store_context)
1969 }
1970
1971 #[inline]
1972 pub fn default_caller(&self) -> NonNull<VMContext> {
1973 self.default_caller_vmctx.as_non_null()
1974 }
1975
1976 #[inline]
1977 pub fn traitobj(&self) -> NonNull<dyn VMStore> {
1978 self.traitobj.0.unwrap()
1979 }
1980
1981 /// Takes the cached `Vec<Val>` stored internally across hostcalls to get
1982 /// used as part of calling the host in a `Func::new` method invocation.
1983 #[inline]
1984 pub fn take_hostcall_val_storage(&mut self) -> Vec<Val> {
1985 mem::take(&mut self.hostcall_val_storage)
1986 }
1987
1988 /// Restores the vector previously taken by `take_hostcall_val_storage`
1989 /// above back into the store, allowing it to be used in the future for the
1990 /// next wasm->host call.
1991 #[inline]
1992 pub fn save_hostcall_val_storage(&mut self, storage: Vec<Val>) {
1993 if storage.capacity() > self.hostcall_val_storage.capacity() {
1994 self.hostcall_val_storage = storage;
1995 }
1996 }
1997
1998 /// Same as `take_hostcall_val_storage`, but for the direction of the host
1999 /// calling wasm.
2000 #[inline]
2001 pub fn take_wasm_val_raw_storage(&mut self) -> TryVec<ValRaw> {
2002 mem::take(&mut self.wasm_val_raw_storage)
2003 }
2004
2005 /// Same as `save_hostcall_val_storage`, but for the direction of the host
2006 /// calling wasm.
2007 #[inline]
2008 pub fn save_wasm_val_raw_storage(&mut self, storage: TryVec<ValRaw>) {
2009 if storage.capacity() > self.wasm_val_raw_storage.capacity() {
2010 self.wasm_val_raw_storage = storage;
2011 }
2012 }
2013
2014 /// Translates a WebAssembly fault at the native `pc` and native `addr` to a
2015 /// WebAssembly-relative fault.
2016 ///
2017 /// This function may abort the process if `addr` is not found to actually
2018 /// reside in any linear memory. In such a situation it means that the
2019 /// segfault was erroneously caught by Wasmtime and is possibly indicative
2020 /// of a code generator bug.
2021 ///
2022 /// This function returns `None` for dynamically-bounds-checked-memories
2023 /// with spectre mitigations enabled since the hardware fault address is
2024 /// always zero in these situations which means that the trapping context
2025 /// doesn't have enough information to report the fault address.
2026 pub(crate) fn wasm_fault(&self, pc: usize, addr: usize) -> Option<vm::WasmFault> {
2027 // There are a few instances where a "close to zero" pointer is loaded
2028 // and we expect that to happen:
2029 //
2030 // * Explicitly bounds-checked memories with spectre-guards enabled will
2031 // cause out-of-bounds accesses to get routed to address 0, so allow
2032 // wasm instructions to fault on the null address.
2033 // * `call_indirect` when invoking a null function pointer may load data
2034 // from the a `VMFuncRef` whose address is null, meaning any field of
2035 // `VMFuncRef` could be the address of the fault.
2036 //
2037 // In these situations where the address is so small it won't be in any
2038 // instance, so skip the checks below.
2039 if addr <= mem::size_of::<VMFuncRef>() {
2040 const _: () = {
2041 // static-assert that `VMFuncRef` isn't too big to ensure that
2042 // it lives solely within the first page as we currently only
2043 // have the guarantee that the first page of memory is unmapped,
2044 // no more.
2045 assert!(mem::size_of::<VMFuncRef>() <= 512);
2046 };
2047 return None;
2048 }
2049
2050 // Search all known instances in this store for this address. Note that
2051 // this is probably not the speediest way to do this. Traps, however,
2052 // are generally not expected to be super fast and additionally stores
2053 // probably don't have all that many instances or memories.
2054 //
2055 // If this loop becomes hot in the future, however, it should be
2056 // possible to precompute maps about linear memories in a store and have
2057 // a quicker lookup.
2058 //
2059 // A shared memory can be defined by more than one instance in a store,
2060 // for example when it's imported through the single-memory instance
2061 // that `SharedMemory::vmimport` creates. Each of those instances
2062 // reports the same fault, so only assert that the faulting address
2063 // doesn't belong to two different memories. The memory size isn't
2064 // compared because a shared memory can grow concurrently.
2065 let mut fault: Option<vm::WasmFault> = None;
2066 for (_, instance) in self.instances.iter() {
2067 if let Some(f) = instance.handle.get().wasm_fault(addr) {
2068 match &fault {
2069 Some(prev) => assert_eq!(prev.wasm_address, f.wasm_address),
2070 None => fault = Some(f),
2071 }
2072 }
2073 }
2074 if fault.is_some() {
2075 return fault;
2076 }
2077
2078 cfg_select! {
2079 feature = "std" => {
2080 // With the standard library a rich error can be printed here
2081 // to stderr and the native abort path is used.
2082 eprintln!(
2083 "\
2084Wasmtime caught a segfault for a wasm program because the faulting instruction
2085is allowed to segfault due to how linear memories are implemented. The address
2086that was accessed, however, is not known to any linear memory in use within this
2087Store. This may be indicative of a critical bug in Wasmtime's code generation
2088because all addresses which are known to be reachable from wasm won't reach this
2089message.
2090
2091 pc: 0x{pc:x}
2092 address: 0x{addr:x}
2093
2094This is a possible security issue because WebAssembly has accessed something it
2095shouldn't have been able to. Other accesses may have succeeded and this one just
2096happened to be caught. The process will now be aborted to prevent this damage
2097from going any further and to alert what's going on. If this is a security
2098issue please reach out to the Wasmtime team via its security policy
2099at https://bytecodealliance.org/security.
2100"
2101 );
2102 std::process::abort();
2103 }
2104 panic = "abort" => {
2105 // Without the standard library but with `panic=abort` then
2106 // it's safe to panic as that's known to halt execution. For
2107 // now avoid the above error message as well since without
2108 // `std` it's probably best to be a bit more size-conscious.
2109 let _ = pc;
2110 panic!("invalid fault");
2111 }
2112 _ => {
2113 // Without `std` and with `panic = "unwind"` there's no
2114 // dedicated API to abort the process portably, so manufacture
2115 // this with a double-panic.
2116 let _ = pc;
2117
2118 struct PanicAgainOnDrop;
2119
2120 impl Drop for PanicAgainOnDrop {
2121 fn drop(&mut self) {
2122 panic!("panicking again to trigger a process abort");
2123 }
2124
2125 }
2126
2127 let _bomb = PanicAgainOnDrop;
2128
2129 panic!("invalid fault");
2130 }
2131 }
2132 }
2133
2134 /// Retrieve the store's protection key.
2135 #[inline]
2136 #[cfg(feature = "pooling-allocator")]
2137 pub(crate) fn get_pkey(&self) -> Option<ProtectionKey> {
2138 self.pkey
2139 }
2140
2141 #[cfg(feature = "async")]
2142 pub(crate) fn fiber_async_state_mut(&mut self) -> &mut fiber::AsyncState {
2143 &mut self.async_state
2144 }
2145
2146 #[cfg(feature = "async")]
2147 pub(crate) fn has_pkey(&self) -> bool {
2148 self.pkey.is_some()
2149 }
2150
2151 pub(crate) fn executor(&mut self) -> ExecutorRef<'_> {
2152 match &mut self.executor {
2153 Executor::Interpreter(i) => ExecutorRef::Interpreter(i.as_interpreter_ref()),
2154 #[cfg(has_host_compiler_backend)]
2155 Executor::Native => ExecutorRef::Native,
2156 }
2157 }
2158
2159 #[cfg(feature = "async")]
2160 pub(crate) fn swap_executor(&mut self, executor: &mut Executor) {
2161 mem::swap(&mut self.executor, executor);
2162 }
2163
2164 pub(crate) fn unwinder(&self) -> &'static dyn Unwind {
2165 match &self.executor {
2166 Executor::Interpreter(i) => i.unwinder(),
2167 #[cfg(has_host_compiler_backend)]
2168 Executor::Native => &vm::UnwindHost,
2169 }
2170 }
2171
2172 /// Allocates a new continuation. Note that we currently don't support
2173 /// deallocating them. Instead, all continuations remain allocated
2174 /// throughout the store's lifetime.
2175 #[cfg(feature = "stack-switching")]
2176 pub fn allocate_continuation(&mut self) -> Result<*mut VMContRef> {
2177 // FIXME(frank-emrich) Do we need to pin this?
2178 let mut continuation = Box::new(VMContRef::empty());
2179 let stack_size = self.engine.config().async_stack_size;
2180 let stack = crate::vm::VMContinuationStack::new(stack_size)?;
2181 #[cfg(asan)]
2182 {
2183 let asan_range = stack
2184 .asan_range()
2185 .expect("supported continuation stacks have a usable range");
2186 continuation.common_stack_information.asan.stack_bottom = Some(vm::VmPtr::from(
2187 NonNull::new(asan_range.start as *mut u8)
2188 .expect("a continuation stack's ASan range must have a non-null bottom"),
2189 ));
2190 continuation.common_stack_information.asan.stack_size = asan_range.len();
2191 }
2192 continuation.stack = stack;
2193 let ptr = continuation.deref_mut() as *mut VMContRef;
2194 self.continuations.push(continuation);
2195 Ok(ptr)
2196 }
2197
2198 /// Constructs and executes an `InstanceAllocationRequest` and pushes the
2199 /// returned instance into the store.
2200 ///
2201 /// This is a helper method for invoking
2202 /// `InstanceAllocator::allocate_module` with the appropriate parameters
2203 /// from this store's own configuration. The `kind` provided is used to
2204 /// distinguish between "real" modules and dummy ones that are synthesized
2205 /// for embedder-created memories, globals, tables, etc. The `kind` will
2206 /// also use a different instance allocator by default, the one passed in,
2207 /// rather than the engine's default allocator.
2208 ///
2209 /// This method will push the instance within `StoreOpaque` onto the
2210 /// `instances` array and return the `InstanceId` which can be use to look
2211 /// it up within the store.
2212 ///
2213 /// # Safety
2214 ///
2215 /// The `imports` provided must be correctly sized/typed for the module
2216 /// being allocated.
2217 pub(crate) async unsafe fn allocate_instance(
2218 &mut self,
2219 limiter: Option<&mut StoreResourceLimiter<'_>>,
2220 kind: AllocateInstanceKind<'_>,
2221 runtime_info: &ModuleRuntimeInfo,
2222 imports: Imports<'_>,
2223 ) -> Result<InstanceId> {
2224 self.instances.reserve(1)?;
2225
2226 let id = self.instances.next_key();
2227
2228 let allocator = match kind {
2229 AllocateInstanceKind::Module(_) => self.engine().allocator(),
2230 AllocateInstanceKind::Dummy { allocator } => allocator,
2231 };
2232 // SAFETY: this function's own contract is the same as
2233 // `allocate_module`, namely the imports provided are valid.
2234 let handle = unsafe {
2235 allocator
2236 .allocate_module(InstanceAllocationRequest {
2237 id,
2238 runtime_info,
2239 imports,
2240 store: self,
2241 limiter,
2242 })
2243 .await?
2244 };
2245
2246 let actual = match kind {
2247 AllocateInstanceKind::Module(module_id) => {
2248 log::trace!(
2249 "Adding instance to store: store={:?}, module={module_id:?}, instance={id:?}",
2250 self.id()
2251 );
2252 self.instances
2253 .push(StoreInstance {
2254 handle,
2255 kind: StoreInstanceKind::Real { module_id },
2256 })
2257 .expect("capacity was reserved above")
2258 }
2259 AllocateInstanceKind::Dummy { .. } => {
2260 log::trace!(
2261 "Adding dummy instance to store: store={:?}, instance={id:?}",
2262 self.id()
2263 );
2264 self.instances
2265 .push(StoreInstance {
2266 handle,
2267 kind: StoreInstanceKind::Dummy,
2268 })
2269 .expect("capacity was reserved above")
2270 }
2271 };
2272
2273 // double-check we didn't accidentally allocate two instances and our
2274 // prediction of what the id would be is indeed the id it should be.
2275 assert_eq!(id, actual);
2276
2277 Ok(id)
2278 }
2279
2280 #[cfg(target_has_atomic = "64")]
2281 pub(crate) fn set_epoch_deadline(&mut self, delta: u64) {
2282 // Set a new deadline based on the "epoch deadline delta".
2283 //
2284 // Also, note that when this update is performed while Wasm is
2285 // on the stack, the Wasm will reload the new value once we
2286 // return into it.
2287 let current_epoch = self.engine().current_epoch();
2288 let epoch_deadline = self.vm_store_context.epoch_deadline.get_mut();
2289 *epoch_deadline = current_epoch.saturating_add(delta).min(u64::MAX - 1);
2290 }
2291
2292 pub(crate) fn get_epoch_deadline(&mut self) -> u64 {
2293 *self.vm_store_context.epoch_deadline.get_mut()
2294 }
2295
2296 #[inline]
2297 pub(crate) fn validate_sync_call(&mut self) -> Result<()> {
2298 #[cfg(feature = "async")]
2299 if self.async_state.async_required {
2300 bail!("store configuration requires that `*_async` functions are used instead");
2301 }
2302 // We disallow `[Typed]Func::call` from a fiber since it can lead to
2303 // e.g. GC or epoch interruption which suspends the fiber, potentially
2304 // returning control to the embedder and allowing it to poll a top-level
2305 // `call_async` future from another thread, effectively and unsoundly
2306 // sending `!Send` data across threads. In addition, allowing such
2307 // recursion risks panicking on stack overflow.
2308 if self.can_block() {
2309 bail!("cannot do blocking `call` from an async context");
2310 }
2311 Ok(())
2312 }
2313
2314 /// Returns whether this store is presently on a fiber and is allowed to
2315 /// block via `block_on` with fibers.
2316 pub(crate) fn can_block(&mut self) -> bool {
2317 #[cfg(feature = "async")]
2318 if true {
2319 return self.fiber_async_state_mut().can_block();
2320 }
2321
2322 false
2323 }
2324
2325 #[cfg(not(feature = "async"))]
2326 pub(crate) fn set_async_required(&mut self, asyncness: Asyncness) {
2327 match asyncness {
2328 Asyncness::No => {}
2329 }
2330 }
2331
2332 #[cfg(any(feature = "async", feature = "gc"))]
2333 pub(crate) async fn yield_now(&self) {
2334 // TODO: Once `Config` has an optional `AsyncFn` field for yielding to the
2335 // current async runtime (e.g. `tokio::task::yield_now`), use that if set;
2336 // otherwise fall back to the runtime-agnostic code.
2337 yield_now().await
2338 }
2339
2340 #[cfg(not(feature = "component-model"))]
2341 pub(crate) fn set_trapped(&mut self) {}
2342}
2343
2344#[cfg(any(feature = "async", feature = "gc"))]
2345async fn yield_now() {
2346 let mut yielded = false;
2347 future::poll_fn(move |cx| {
2348 if yielded {
2349 Poll::Ready(())
2350 } else {
2351 yielded = true;
2352 cx.waker().wake_by_ref();
2353 Poll::Pending
2354 }
2355 })
2356 .await;
2357}
2358
2359/// Helper parameter to [`StoreOpaque::allocate_instance`].
2360pub(crate) enum AllocateInstanceKind<'a> {
2361 /// An embedder-provided module is being allocated meaning that the default
2362 /// engine's allocator will be used.
2363 Module(RegisteredModuleId),
2364
2365 /// Add a dummy instance that to the store.
2366 ///
2367 /// These are instances that are just implementation details of something
2368 /// else (e.g. host-created memories that are not actually defined in any
2369 /// Wasm module) and therefore shouldn't show up in things like core dumps.
2370 ///
2371 /// A custom, typically OnDemand-flavored, allocator is provided to execute
2372 /// the allocation.
2373 Dummy {
2374 allocator: &'a dyn InstanceAllocator,
2375 },
2376}
2377
2378unsafe impl<T> VMStore for StoreInner<T> {
2379 #[cfg(feature = "component-model-async")]
2380 fn component_async_store(
2381 &mut self,
2382 ) -> &mut dyn crate::runtime::component::VMComponentAsyncStore {
2383 self
2384 }
2385
2386 fn store_opaque(&self) -> &StoreOpaque {
2387 &self.inner
2388 }
2389
2390 fn store_opaque_mut(&mut self) -> &mut StoreOpaque {
2391 &mut self.inner
2392 }
2393
2394 #[cfg(feature = "call-hook")]
2395 fn call_hook(&mut self, s: CallHook) -> Result<()> {
2396 StoreInner::call_hook(self, s)
2397 }
2398
2399 fn resource_limiter_and_store_opaque(
2400 &mut self,
2401 ) -> (Option<StoreResourceLimiter<'_>>, &mut StoreOpaque) {
2402 let (data, limiter, opaque) = self.data_limiter_and_opaque();
2403
2404 let limiter = limiter.map(|l| match l {
2405 ResourceLimiterInner::Sync(s) => StoreResourceLimiter::Sync(s(data)),
2406 #[cfg(feature = "async")]
2407 ResourceLimiterInner::Async(s) => StoreResourceLimiter::Async(s(data)),
2408 });
2409
2410 (limiter, opaque)
2411 }
2412
2413 #[cfg(target_has_atomic = "64")]
2414 fn new_epoch_updated_deadline(&mut self) -> Result<UpdateDeadline> {
2415 // Temporarily take the configured behavior to avoid mutably borrowing
2416 // multiple times.
2417 let mut behavior = self.epoch_deadline_behavior.take();
2418 let update = match &mut behavior {
2419 Some(callback) => callback(StoreHookState::new((&mut *self).as_context_mut())),
2420 None => Ok(UpdateDeadline::Interrupt),
2421 };
2422
2423 // Put back the original behavior which was replaced by `take`.
2424 self.epoch_deadline_behavior = behavior;
2425 update
2426 }
2427
2428 #[cfg(feature = "debug")]
2429 fn block_on_debug_handler(&mut self, event: crate::DebugEvent<'_>) -> crate::Result<()> {
2430 if let Some(handler) = self.debug_handler.take() {
2431 if !self.can_block() {
2432 bail!("could not invoke debug handler without async context");
2433 }
2434 log::trace!("about to raise debug event {event:?}");
2435 StoreContextMut(self).with_blocking(|store, cx| {
2436 cx.block_on(Pin::from(handler.handle(store, event)).as_mut())
2437 })
2438 } else {
2439 Ok(())
2440 }
2441 }
2442}
2443
2444impl<T> StoreInner<T> {
2445 #[cfg(target_has_atomic = "64")]
2446 fn epoch_deadline_trap(&mut self) {
2447 self.epoch_deadline_behavior = None;
2448 }
2449
2450 #[cfg(target_has_atomic = "64")]
2451 fn epoch_deadline_callback(
2452 &mut self,
2453 callback: Box<dyn FnMut(StoreHookState<T>) -> Result<UpdateDeadline> + Send + Sync>,
2454 ) {
2455 self.epoch_deadline_behavior = Some(callback);
2456 }
2457}
2458
2459impl<T: Default> Default for Store<T> {
2460 fn default() -> Store<T> {
2461 Store::new(&Engine::default(), T::default())
2462 }
2463}
2464
2465impl<T: fmt::Debug> fmt::Debug for Store<T> {
2466 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2467 let inner = &**self.inner as *const StoreInner<T>;
2468 f.debug_struct("Store")
2469 .field("inner", &inner)
2470 .field("data", self.inner.data())
2471 .finish()
2472 }
2473}
2474
2475impl<T> Drop for Store<T> {
2476 fn drop(&mut self) {
2477 self.run_manual_drop_routines();
2478
2479 // For documentation on this `unsafe`, see `into_data`.
2480 unsafe {
2481 ManuallyDrop::drop(&mut self.inner.data_no_provenance);
2482 ManuallyDrop::drop(&mut self.inner);
2483 }
2484 }
2485}
2486
2487impl Drop for StoreOpaque {
2488 fn drop(&mut self) {
2489 // NB it's important that this destructor does not access `self.data`.
2490 // That is deallocated by `Drop for Store<T>` above.
2491
2492 unsafe {
2493 let allocator = self.engine.allocator();
2494 let ondemand = OnDemandInstanceAllocator::default();
2495 let store_id = self.id();
2496
2497 #[cfg(feature = "gc")]
2498 if let Some(mut gc_store) = self.gc_store.take() {
2499 let gc_alloc_index = gc_store.allocation_index;
2500 log::trace!("store {store_id:?} is deallocating GC heap {gc_alloc_index:?}");
2501 debug_assert!(self.engine.features().gc_types());
2502 let mem = gc_store.gc_heap.detach();
2503 let mem_alloc_index =
2504 allocator.deallocate_gc_heap(gc_alloc_index, gc_store.gc_heap);
2505 allocator.deallocate_memory(None, mem_alloc_index, mem);
2506 }
2507
2508 for (id, instance) in self.instances.iter_mut() {
2509 log::trace!("store {store_id:?} is deallocating {id:?}");
2510 let allocator = match instance.kind {
2511 StoreInstanceKind::Dummy => &ondemand,
2512 _ => allocator,
2513 };
2514 allocator.deallocate_module(&mut instance.handle);
2515 }
2516
2517 self.store_data.decrement_allocator_resources(allocator);
2518 }
2519 }
2520}
2521
2522#[cfg_attr(
2523 not(any(feature = "gc", feature = "async")),
2524 // NB: Rust 1.89, current stable, does not fire this lint. Rust 1.90,
2525 // however, does, so use #[allow] until our MSRV is 1.90.
2526 allow(dead_code, reason = "don't want to put #[cfg] on all impls below too")
2527)]
2528pub(crate) trait AsStoreOpaque {
2529 fn as_store_opaque(&mut self) -> &mut StoreOpaque;
2530}
2531
2532impl AsStoreOpaque for StoreOpaque {
2533 fn as_store_opaque(&mut self) -> &mut StoreOpaque {
2534 self
2535 }
2536}
2537
2538impl AsStoreOpaque for dyn VMStore {
2539 fn as_store_opaque(&mut self) -> &mut StoreOpaque {
2540 self
2541 }
2542}
2543
2544impl<T: 'static> AsStoreOpaque for Store<T> {
2545 fn as_store_opaque(&mut self) -> &mut StoreOpaque {
2546 &mut self.inner.inner
2547 }
2548}
2549
2550impl<T: 'static> AsStoreOpaque for StoreInner<T> {
2551 fn as_store_opaque(&mut self) -> &mut StoreOpaque {
2552 self
2553 }
2554}
2555
2556impl<T: AsStoreOpaque + ?Sized> AsStoreOpaque for &mut T {
2557 fn as_store_opaque(&mut self) -> &mut StoreOpaque {
2558 T::as_store_opaque(self)
2559 }
2560}
2561
2562/// Helper enum to indicate, in some function contexts, whether `async` should
2563/// be taken advantage of or not.
2564///
2565/// This is used throughout Wasmtime where internal functions are all `async`
2566/// but external functions might be either sync or `async`. If the external
2567/// function is sync, then internally Wasmtime shouldn't yield as it won't do
2568/// anything. If the external function is `async`, however, yields are fine.
2569///
2570/// An example of this is GC. Right now GC will cooperatively yield after phases
2571/// of GC have passed, but this cooperative yielding is only enabled with
2572/// `Asyncness::Yes`.
2573///
2574/// This enum is additionally conditionally defined such that `Yes` is only
2575/// present in `async`-enabled builds. That ensures that this compiles down to a
2576/// zero-sized type in `async`-disabled builds in case that interests embedders.
2577#[derive(PartialEq, Eq, Copy, Clone)]
2578pub enum Asyncness {
2579 /// Don't do async things, don't yield, etc. It's ok to execute an `async`
2580 /// function, but it should be validated ahead of time that when doing so a
2581 /// yield isn't possible (e.g. `validate_sync_*` methods on Store.
2582 No,
2583
2584 /// Async things is OK. This should only be used when the API entrypoint is
2585 /// itself `async`.
2586 #[cfg(feature = "async")]
2587 Yes,
2588}
2589
2590impl core::ops::BitOr for Asyncness {
2591 type Output = Self;
2592
2593 fn bitor(self, rhs: Self) -> Self::Output {
2594 match (self, rhs) {
2595 (Asyncness::No, Asyncness::No) => Asyncness::No,
2596 #[cfg(feature = "async")]
2597 (Asyncness::Yes, _) | (_, Asyncness::Yes) => Asyncness::Yes,
2598 }
2599 }
2600}
2601
2602#[cfg(test)]
2603mod tests {
2604 use super::*;
2605
2606 struct FuelTank {
2607 pub consumed_fuel: i64,
2608 pub reserve_fuel: u64,
2609 pub yield_interval: Option<NonZeroU64>,
2610 }
2611
2612 impl FuelTank {
2613 fn new() -> Self {
2614 FuelTank {
2615 consumed_fuel: 0,
2616 reserve_fuel: 0,
2617 yield_interval: None,
2618 }
2619 }
2620 fn get_fuel(&self) -> u64 {
2621 get_fuel(self.consumed_fuel, self.reserve_fuel)
2622 }
2623 fn refuel(&mut self) -> bool {
2624 refuel(
2625 &mut self.consumed_fuel,
2626 &mut self.reserve_fuel,
2627 self.yield_interval,
2628 )
2629 }
2630 fn set_fuel(&mut self, fuel: u64) {
2631 set_fuel(
2632 &mut self.consumed_fuel,
2633 &mut self.reserve_fuel,
2634 self.yield_interval,
2635 fuel,
2636 );
2637 }
2638 }
2639
2640 #[test]
2641 fn smoke() {
2642 let mut tank = FuelTank::new();
2643 tank.set_fuel(10);
2644 assert_eq!(tank.consumed_fuel, -10);
2645 assert_eq!(tank.reserve_fuel, 0);
2646
2647 tank.yield_interval = NonZeroU64::new(10);
2648 tank.set_fuel(25);
2649 assert_eq!(tank.consumed_fuel, -10);
2650 assert_eq!(tank.reserve_fuel, 15);
2651 }
2652
2653 #[test]
2654 fn does_not_lose_precision() {
2655 let mut tank = FuelTank::new();
2656 tank.set_fuel(u64::MAX);
2657 assert_eq!(tank.get_fuel(), u64::MAX);
2658
2659 tank.set_fuel(i64::MAX as u64);
2660 assert_eq!(tank.get_fuel(), i64::MAX as u64);
2661
2662 tank.set_fuel(i64::MAX as u64 + 1);
2663 assert_eq!(tank.get_fuel(), i64::MAX as u64 + 1);
2664 }
2665
2666 #[test]
2667 fn yielding_does_not_lose_precision() {
2668 let mut tank = FuelTank::new();
2669
2670 tank.yield_interval = NonZeroU64::new(10);
2671 tank.set_fuel(u64::MAX);
2672 assert_eq!(tank.get_fuel(), u64::MAX);
2673 assert_eq!(tank.consumed_fuel, -10);
2674 assert_eq!(tank.reserve_fuel, u64::MAX - 10);
2675
2676 tank.yield_interval = NonZeroU64::new(u64::MAX);
2677 tank.set_fuel(u64::MAX);
2678 assert_eq!(tank.get_fuel(), u64::MAX);
2679 assert_eq!(tank.consumed_fuel, -i64::MAX);
2680 assert_eq!(tank.reserve_fuel, u64::MAX - (i64::MAX as u64));
2681
2682 tank.yield_interval = NonZeroU64::new((i64::MAX as u64) + 1);
2683 tank.set_fuel(u64::MAX);
2684 assert_eq!(tank.get_fuel(), u64::MAX);
2685 assert_eq!(tank.consumed_fuel, -i64::MAX);
2686 assert_eq!(tank.reserve_fuel, u64::MAX - (i64::MAX as u64));
2687 }
2688
2689 #[test]
2690 fn refueling() {
2691 // It's possible to fuel to have consumed over the limit as some instructions can consume
2692 // multiple units of fuel at once. Refueling should be strict in it's consumption and not
2693 // add more fuel than there is.
2694 let mut tank = FuelTank::new();
2695
2696 tank.yield_interval = NonZeroU64::new(10);
2697 tank.reserve_fuel = 42;
2698 tank.consumed_fuel = 4;
2699 assert!(tank.refuel());
2700 assert_eq!(tank.reserve_fuel, 28);
2701 assert_eq!(tank.consumed_fuel, -10);
2702
2703 tank.yield_interval = NonZeroU64::new(1);
2704 tank.reserve_fuel = 8;
2705 tank.consumed_fuel = 4;
2706 assert_eq!(tank.get_fuel(), 4);
2707 assert!(tank.refuel());
2708 assert_eq!(tank.reserve_fuel, 3);
2709 assert_eq!(tank.consumed_fuel, -1);
2710 assert_eq!(tank.get_fuel(), 4);
2711
2712 tank.yield_interval = NonZeroU64::new(10);
2713 tank.reserve_fuel = 3;
2714 tank.consumed_fuel = 4;
2715 assert_eq!(tank.get_fuel(), 0);
2716 assert!(!tank.refuel());
2717 assert_eq!(tank.reserve_fuel, 3);
2718 assert_eq!(tank.consumed_fuel, 4);
2719 assert_eq!(tank.get_fuel(), 0);
2720 }
2721
2722 #[test]
2723 fn store_data_provenance() {
2724 // Test that we juggle pointer provenance and all that correctly, and
2725 // miri is happy with everything, while allowing both Rust code and
2726 // "Wasm" to access and modify the store's `T` data. Note that this is
2727 // not actually Wasm mutating the store data here because compiling Wasm
2728 // under miri is way too slow.
2729
2730 unsafe fn run_wasm(store: &mut Store<u32>) {
2731 let ptr = store
2732 .inner
2733 .inner
2734 .vm_store_context
2735 .store_data
2736 .as_ptr()
2737 .cast::<u32>();
2738 unsafe { *ptr += 1 }
2739 }
2740
2741 let engine = Engine::default();
2742 let mut store = Store::new(&engine, 0_u32);
2743
2744 assert_eq!(*store.data(), 0);
2745 *store.data_mut() += 1;
2746 assert_eq!(*store.data(), 1);
2747 unsafe { run_wasm(&mut store) }
2748 assert_eq!(*store.data(), 2);
2749 *store.data_mut() += 1;
2750 assert_eq!(*store.data(), 3);
2751 }
2752}