Struct wiggle::wasmtime_crate::Store [−][src]
pub struct Store<T> { /* fields omitted */ }
Expand description
A Store
is a collection of WebAssembly instances and host-defined state.
All WebAssembly instances and items will be attached to and refer to a
Store
. For example instances, functions, globals, and tables are all
attached to a Store
. Instances are created by instantiating a
Module
within a Store
.
A Store
is intended to be a short-lived object in a program. No form
of GC is implemented at this time so once an instance is created within a
Store
it will not be deallocated until the Store
itself is dropped.
This makes Store
unsuitable for creating an unbounded number of
instances in it because Store
will never release this memory. It’s
recommended to have a Store
correspond roughly to the lifetime of a “main
instance” that an embedding is interested in executing.
Type parameter T
Each Store
has a type parameter T
associated with it. This T
represents state defined by the host. This state will be accessible through
the Caller
type that host-defined functions get access
to. This T
is suitable for storing Store
-specific information which
imported functions may want access to.
The data T
can be accessed through methods like Store::data
and
Store::data_mut
.
Stores, contexts, oh my
Most methods in Wasmtime take something of the form
AsContext
or AsContextMut
as
the first argument. These two traits allow ergonomically passing in the
context you currently have to any method. The primary two sources of
contexts are:
Store<T>
Caller<'_, T>
corresponding to what you create and what you have access to in a host
function. You can also explicitly acquire a StoreContext
or
StoreContextMut
and pass that around as well.
Note that all methods on Store
are mirrored onto StoreContext
,
StoreContextMut
, and Caller
. This way no matter what
form of context you have you can call various methods, create objects, etc.
Stores and Default
You can create a store with default configuration settings using
Store::default()
. This will create a brand new Engine
with default
configuration (see Config
for more information).
Implementations
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.
Consumes this Store
, destroying it, and returns the underlying data.
Configures the ResourceLimiter
used to limit
resource creation within this Store
.
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
.
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 propogates to the root call.
Creates an InterruptHandle
which can be used to interrupt the
execution of instances within this Store
.
An InterruptHandle
handle is a mechanism of ensuring that guest code
doesn’t execute for too long. For example it’s used to prevent wasm
programs for executing infinitely in infinite loops or recursive call
chains.
The InterruptHandle
type is sendable to other threads so you can
interact with it even while the thread with this Store
is executing
wasm code.
There’s one method on an interrupt handle:
InterruptHandle::interrupt
. This method is used to generate an
interrupt and cause wasm code to exit “soon”.
When are interrupts delivered?
The term “interrupt” here refers to one of two different behaviors that are interrupted in wasm:
- The head of every loop in wasm has a check to see if it’s interrupted.
- The prologue of every function has a check to see if it’s interrupted.
This interrupt mechanism makes no attempt to signal interrupts to native code. For example if a host function is blocked, then sending an interrupt will not interrupt that operation.
Interrupts are consumed as soon as possible when wasm itself starts executing. This means that if you interrupt wasm code then it basically guarantees that the next time wasm is executing on the target thread it will return quickly (either normally if it were already in the process of returning or with a trap from the interrupt). Once an interrupt trap is generated then an interrupt is consumed, and further execution will not be interrupted (unless another interrupt is set).
When implementing interrupts you’ll want to ensure that the delivery of interrupts into wasm code is also handled in your host imports and functionality. Host functions need to either execute for bounded amounts of time or you’ll need to arrange for them to be interrupted as well.
Return Value
This function returns a Result
since interrupts are not always
enabled. Interrupts are enabled via the
Config::interruptable
method, and if
this store’s Config
hasn’t been configured to enable
interrupts then an error is returned.
Examples
// Enable interruptable code via `Config` and then create an interrupt
// handle which we'll use later to interrupt running code.
let engine = Engine::new(Config::new().interruptable(true))?;
let mut store = Store::new(&engine, ());
let interrupt_handle = store.interrupt_handle()?;
// Compile and instantiate a small example with an infinite loop.
let module = Module::new(&engine, r#"
(func (export "run") (loop br 0))
"#)?;
let instance = Instance::new(&mut store, &module, &[])?;
let run = instance.get_typed_func::<(), (), _>(&mut store, "run")?;
// Spin up a thread to send us an interrupt in a second
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_secs(1));
interrupt_handle.interrupt();
});
let trap = run.call(&mut store, ()).unwrap_err();
assert!(trap.to_string().contains("wasm trap: interrupt"));
Perform garbage collection of ExternRef
s.
Note that it is not required to actively call this function. GC will automatically happen when internal buffers fill up. This is provided if fine-grained control over the GC is desired.
Returns the amount of fuel consumed by this store’s execution so far.
If fuel consumption is not enabled via
Config::consume_fuel
then this
function will return None
. Also note that fuel, if enabled, must be
originally configured via Store::add_fuel
.
Adds 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 at this time when fuel is entirely consumed it will cause wasm to trap. More usages of fuel are planned for the future.
Panics
This function will panic if the store’s Config
did
not have fuel consumption enabled.
Synthetically consumes fuel from this Store
.
For this method to work fuel consumption must be enabled via
Config::consume_fuel
.
WebAssembly execution will automatically consume fuel but if so desired the embedder can also consume fuel manually to account for relative costs of host functions, for example.
This function will attempt to consume fuel
units of fuel from within
this store. If the remaining amount of fuel allows this then Ok(N)
is
returned where N
is the amount of remaining fuel. Otherwise an error
is returned and no fuel is consumed.
Errors
This function will return an either either if fuel consumption via
Config
is disabled or if fuel
exceeds the amount
of remaining fuel within this store.
Configures a Store
to generate a Trap
whenever it runs out of
fuel.
When a Store
is configured to consume fuel with
Config::consume_fuel
this method will
configure what happens when fuel runs out. Specifically a WebAssembly
trap will be raised and the current execution of WebAssembly will be
aborted.
This is the default behavior for running out of fuel.
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 what happens when fuel runs out. Specifically executing
WebAssembly will be suspended and control will be yielded back to the
caller. 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 fuel_to_inject
parameter indicates how much fuel should be
automatically re-injected after fuel runs out. This is how much fuel
will be consumed between yields of an async future.
The injection_count
parameter indicates how many times this fuel will
be injected. Multiplying the two parameters is the total amount of fuel
this store is allowed before wasm traps.
Panics
This method will panic if it is not called on a store associated with an async config.
Trait Implementations
Returns the store context that this type provides access to.
Returns the store context that this type provides access to.
Auto Trait Implementations
impl<T> !RefUnwindSafe for Store<T>
impl<T> !UnwindSafe for Store<T>
Blanket Implementations
Mutably borrows from an owned value. Read more
Attaches the provided Subscriber
to this type, returning a
WithDispatch
wrapper. Read more
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more