Type Alias WasmStore

Source
pub type WasmStore = Store<WasmStoreData>;

Aliased Type§

struct WasmStore { /* private fields */ }

Implementations

§

impl<T> Store<T>

pub fn limiter_async( &mut self, limiter: impl FnMut(&mut T) -> &mut dyn ResourceLimiterAsync + Send + Sync + 'static, )

Configures the ResourceLimiterAsync used to limit resource creation within this [Store].

This method is an asynchronous variant of the [Store::limiter] method where the embedder can block the wasm request for more resources with host async execution of futures.

By using a ResourceLimiterAsync with a [Store], you can no longer use Memory::new, Memory::grow, Table::new, and Table::grow. Instead, you must use their async variants: Memory::new_async, Memory::grow_async, Table::new_async, and Table::grow_async.

Note that this limiter is only used to limit the creation/growth of resources in the future, this does not retroactively attempt to apply limits to the [Store]. Additionally this must be used with an async [Store] configured via Config::async_support.

pub fn call_hook_async( &mut self, hook: impl CallHookHandler<T> + Send + Sync + 'static, )

Configures an async function that runs on calls and returns between WebAssembly and host code. For the non-async equivalent of this method, see [Store::call_hook].

The function is passed a [CallHook] argument, which indicates which state transition the VM is making.

This function’s future may return a [Trap]. If a trap is returned when an import was called, it is immediately raised as-if the host import had returned the trap. If a trap is returned after wasm returns to the host then the wasm function’s result is ignored and this trap is returned instead.

After this function returns a trap, it may be called for subsequent returns to host or wasm code as the trap propagates to the root call.

pub async fn gc_async(&mut self)
where T: Send,

Perform garbage collection asynchronously.

Note that it is not required to actively call this function. GC will automatically happen according to various internal heuristics. This is provided if fine-grained control over the GC is desired.

This method is only available when the gc Cargo feature is enabled.

pub fn epoch_deadline_async_yield_and_update(&mut self, delta: u64)

Configures epoch-deadline expiration to yield to the async caller and the update the deadline.

When epoch-interruption-instrumented code is executed on this store and the epoch deadline is reached before completion, with the store configured in this way, execution will yield (the future will return Pending but re-awake itself for later execution) and, upon resuming, the store will be configured with an epoch deadline equal to the current epoch plus delta ticks.

This setting is intended to allow for cooperative timeslicing of multiple CPU-bound Wasm guests in different stores, all executing under the control of an async executor. To drive this, stores should be configured to “yield and update” automatically with this function, and some external driver (a thread that wakes up periodically, or a timer signal/interrupt) should call Engine::increment_epoch().

See documentation on Config::epoch_interruption() for an introduction to epoch-based interruption.

§

impl<T> Store<T>

pub fn new(engine: &Engine, data: T) -> Store<T>

Creates a new [Store] to be associated with the given [Engine] and data provided.

The created [Store] will place no additional limits on the size of linear memories or tables at runtime. Linear memories and tables will be allowed to grow to any upper limit specified in their definitions. The store will limit the number of instances, linear memories, and tables created to 10,000. This can be overridden with the [Store::limiter] configuration method.

pub fn data(&self) -> &T

Access the underlying data owned by this Store.

pub fn data_mut(&mut self) -> &mut T

Access the underlying data owned by this Store.

pub fn into_data(self) -> T

Consumes this [Store], destroying it, and returns the underlying data.

pub fn limiter( &mut self, limiter: impl FnMut(&mut T) -> &mut dyn ResourceLimiter + Send + Sync + 'static, )

Configures the ResourceLimiter used to limit resource creation within this [Store].

Whenever resources such as linear memory, tables, or instances are allocated the limiter specified here is invoked with the store’s data T and the returned ResourceLimiter is used to limit the operation being allocated. The returned ResourceLimiter is intended to live within the T itself, for example by storing a StoreLimits.

Note that this limiter is only used to limit the creation/growth of resources in the future, this does not retroactively attempt to apply limits to the [Store].

§Examples
use wasmtime::*;

struct MyApplicationState {
    my_state: u32,
    limits: StoreLimits,
}

let engine = Engine::default();
let my_state = MyApplicationState {
    my_state: 42,
    limits: StoreLimitsBuilder::new()
        .memory_size(1 << 20 /* 1 MB */)
        .instances(2)
        .build(),
};
let mut store = Store::new(&engine, my_state);
store.limiter(|state| &mut state.limits);

// Creation of smaller memories is allowed
Memory::new(&mut store, MemoryType::new(1, None)).unwrap();

// Creation of a larger memory, however, will exceed the 1MB limit we've
// configured
assert!(Memory::new(&mut store, MemoryType::new(1000, None)).is_err());

// The number of instances in this store is limited to 2, so the third
// instance here should fail.
let module = Module::new(&engine, "(module)").unwrap();
assert!(Instance::new(&mut store, &module, &[]).is_ok());
assert!(Instance::new(&mut store, &module, &[]).is_ok());
assert!(Instance::new(&mut store, &module, &[]).is_err());

pub fn call_hook( &mut self, hook: impl FnMut(StoreContextMut<'_, T>, CallHook) -> Result<(), Error> + Send + Sync + 'static, )

Configure a function that runs on calls and returns between WebAssembly and host code.

The function is passed a [CallHook] argument, which indicates which state transition the VM is making.

This function may return a [Trap]. If a trap is returned when an import was called, it is immediately raised as-if the host import had returned the trap. If a trap is returned after wasm returns to the host then the wasm function’s result is ignored and this trap is returned instead.

After this function returns a trap, it may be called for subsequent returns to host or wasm code as the trap propagates to the root call.

pub fn engine(&self) -> &Engine

Returns the [Engine] that this store is associated with.

pub fn gc(&mut self)

Perform garbage collection.

Note that it is not required to actively call this function. GC will automatically happen according to various internal heuristics. This is provided if fine-grained control over the GC is desired.

This method is only available when the gc Cargo feature is enabled.

pub fn get_fuel(&self) -> Result<u64, Error>

Returns the amount fuel in this [Store]. When fuel is enabled, it must be configured via [Store::set_fuel].

§Errors

This function will return an error if fuel consumption is not enabled via Config::consume_fuel.

pub fn set_fuel(&mut self, fuel: u64) -> Result<(), Error>

Set the fuel to this [Store] for wasm to consume while executing.

For this method to work fuel consumption must be enabled via Config::consume_fuel. By default a [Store] starts with 0 fuel for wasm to execute with (meaning it will immediately trap). This function must be called for the store to have some fuel to allow WebAssembly to execute.

Most WebAssembly instructions consume 1 unit of fuel. Some instructions, such as nop, drop, block, and loop, consume 0 units, as any execution cost associated with them involves other instructions which do consume fuel.

Note that when fuel is entirely consumed it will cause wasm to trap.

§Errors

This function will return an error if fuel consumption is not enabled via Config::consume_fuel.

pub fn fuel_async_yield_interval( &mut self, interval: Option<u64>, ) -> Result<(), Error>

Configures a [Store] to yield execution of async WebAssembly code periodically.

When a [Store] is configured to consume fuel with Config::consume_fuel this method will configure WebAssembly to be suspended and control will be yielded back to the caller every interval units of fuel consumed. This is only suitable with use of a store associated with an async config because only then are futures used and yields are possible.

The purpose of this behavior is to ensure that futures which represent execution of WebAssembly do not execute too long inside their Future::poll method. This allows for some form of cooperative multitasking where WebAssembly will voluntarily yield control periodically (based on fuel consumption) back to the running thread.

Note that futures returned by this crate will automatically flag themselves to get re-polled if a yield happens. This means that WebAssembly will continue to execute, just after giving the host an opportunity to do something else.

The interval parameter indicates how much fuel should be consumed between yields of an async future. When fuel runs out wasm will trap.

§Error

This method will error if it is not called on a store associated with an async config.

pub fn set_epoch_deadline(&mut self, ticks_beyond_current: u64)

Sets the epoch deadline to a certain number of ticks in the future.

When the Wasm guest code is compiled with epoch-interruption instrumentation (Config::epoch_interruption()), and when the Engine’s epoch is incremented (Engine::increment_epoch()) past a deadline, execution can be configured to either trap or yield and then continue.

This deadline is always set relative to the current epoch: ticks_beyond_current ticks in the future. The deadline can be set explicitly via this method, or refilled automatically on a yield if configured via epoch_deadline_async_yield_and_update(). After this method is invoked, the deadline is reached when [Engine::increment_epoch()] has been invoked at least ticks_beyond_current times.

By default a store will trap immediately with an epoch deadline of 0 (which has always “elapsed”). This method is required to be configured for stores with epochs enabled to some future epoch deadline.

See documentation on Config::epoch_interruption() for an introduction to epoch-based interruption.

pub fn epoch_deadline_trap(&mut self)

Configures epoch-deadline expiration to trap.

When epoch-interruption-instrumented code is executed on this store and the epoch deadline is reached before completion, with the store configured in this way, execution will terminate with a trap as soon as an epoch check in the instrumented code is reached.

This behavior is the default if the store is not otherwise configured via epoch_deadline_trap(), epoch_deadline_callback() or epoch_deadline_async_yield_and_update().

This setting is intended to allow for coarse-grained interruption, but not a deterministic deadline of a fixed, finite interval. For deterministic interruption, see the “fuel” mechanism instead.

Note that when this is used it’s required to call [Store::set_epoch_deadline] or otherwise wasm will always immediately trap.

See documentation on Config::epoch_interruption() for an introduction to epoch-based interruption.

pub fn epoch_deadline_callback( &mut self, callback: impl FnMut(StoreContextMut<'_, T>) -> Result<UpdateDeadline, Error> + Send + Sync + 'static, )

Configures epoch-deadline expiration to invoke a custom callback function.

When epoch-interruption-instrumented code is executed on this store and the epoch deadline is reached before completion, the provided callback function is invoked.

This callback should either return an [UpdateDeadline], or return an error, which will terminate execution with a trap.

The [UpdateDeadline] is a positive number of ticks to add to the epoch deadline, as well as indicating what to do after the callback returns. If the [Store] is configured with async support, then the callback may return [UpdateDeadline::Yield] to yield to the async executor before updating the epoch deadline. Alternatively, the callback may return [UpdateDeadline::Continue] to update the epoch deadline immediately.

This setting is intended to allow for coarse-grained interruption, but not a deterministic deadline of a fixed, finite interval. For deterministic interruption, see the “fuel” mechanism instead.

See documentation on Config::epoch_interruption() for an introduction to epoch-based interruption.

Trait Implementations

§

impl<T> AsContext for Store<T>

§

type Data = T

The host information associated with the [Store], aka the T in [Store<T>].
§

fn as_context(&self) -> StoreContext<'_, T>

Returns the store context that this type provides access to.
§

impl<T> AsContextMut for Store<T>

§

fn as_context_mut(&mut self) -> StoreContextMut<'_, T>

Returns the store context that this type provides access to.
§

impl<T> Debug for Store<T>
where T: Debug,

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<T> Default for Store<T>
where T: Default,

§

fn default() -> Store<T>

Returns the “default value” for a type. Read more
§

impl<T> Drop for Store<T>

§

fn drop(&mut self)

Executes the destructor for this type. Read more
§

impl<T> StoreExt for Store<T>

§

unsafe fn set_signal_handler<H>(&mut self, handler: H)
where H: 'static + Fn(i32, *const siginfo_t, *const c_void) -> bool + Send + Sync,

The signal handler must be async-signal-safe.