Expand description
§Wasmtime’s embedding API
Wasmtime is a WebAssembly engine for JIT-compiled or ahead-of-time compiled
WebAssembly modules and components. More information about the Wasmtime
project as a whole can be found in the documentation
book whereas this documentation mostly focuses
on the API reference of the wasmtime crate itself.
This crate contains an API used to interact with WebAssembly modules or WebAssembly components. For example you can compile WebAssembly, create instances, call functions, etc. As an embedder of WebAssembly you can also provide guests functionality from the host by creating host-defined functions, memories, globals, etc, which can do things that WebAssembly cannot (such as print to the screen).
The wasmtime crate is designed to be safe, efficient, and ergonomic.
This enables executing WebAssembly without the embedder needing to use
unsafe code, meaning that you’re guaranteed there is no undefined behavior
or segfaults in either the WebAssembly guest or the host itself.
The wasmtime crate can roughly be thought of as being split into two
halves:
-
One half of the crate is similar to the JS WebAssembly API as well as the proposed C API and is intended for working with WebAssembly modules. This API resides in the root of the
wasmtimecrate’s namespace, for examplewasmtime::Module. -
The second half of the crate is for use with the WebAssembly Component Model. The implementation of the component model is present in
wasmtime::componentand roughly mirrors the structure for core WebAssembly, for examplecomponent::FuncmirrorsFunc.
An example of using Wasmtime to run a core WebAssembly module looks like:
use wasmtime::*;
fn main() -> wasmtime::Result<()> {
let engine = Engine::default();
// Modules can be compiled through either the text or binary format
let wat = r#"
(module
(import "host" "host_func" (func $host_hello (param i32)))
(func (export "hello")
i32.const 3
call $host_hello)
)
"#;
let module = Module::new(&engine, wat)?;
// Host functionality can be arbitrary Rust functions and is provided
// to guests through a `Linker`.
let mut linker = Linker::new(&engine);
linker.func_wrap("host", "host_func", |caller: Caller<'_, u32>, param: i32| {
println!("Got {} from WebAssembly", param);
println!("my host state is: {}", caller.data());
})?;
// All wasm objects operate within the context of a "store". Each
// `Store` has a type parameter to store host-specific data, which in
// this case we're using `4` for.
let mut store: Store<u32> = Store::new(&engine, 4);
// Instantiation of a module requires specifying its imports and then
// afterwards we can fetch exports by name, as well as asserting the
// type signature of the function with `get_typed_func`.
let instance = linker.instantiate(&mut store, &module)?;
let hello = instance.get_typed_func::<(), ()>(&mut store, "hello")?;
// And finally we can call the wasm!
hello.call(&mut store, ())?;
Ok(())
}§Core Concepts
There are a number of core types and concepts that are important to be aware
of when using the wasmtime crate:
-
Engine- a global compilation and runtime environment for WebAssembly. AnEngineis an object that can be shared concurrently across threads and is created with aConfigwith many knobs for configuring behavior. Compiling or executing any WebAssembly requires first configuring and creating anEngine. AllModules andComponents belong to anEngine, and typically there’s oneEngineper process. -
Store- container for all information related to WebAssembly objects such as functions, instances, memories, etc. AStore<T>allows customization of theTto store arbitrary host data within aStore. This host data can be accessed through host functions via theCallerfunction parameter in host-defined functions. AStoreis required for all WebAssembly operations, such as calling a wasm function. TheStoreis passed in as a “context” to methods likeFunc::call. Dropping aStorewill deallocate all memory associated with WebAssembly objects within theStore. AStoreis cheap to create and destroy and does not GC objects such as unused instances internally, so it’s intended to be short-lived (or no longer than the instances it contains). -
Linker(orcomponent::Linker) - host functions are defined within a linker to provide them a string-based name which can be looked up when instantiating a WebAssembly module or component. Linkers are traditionally populated at startup and then reused for all future instantiations of all instances, assuming the set of host functions does not change over time. Host functions areFn(..) + Send + Syncand typically do not close over mutable state. Instead it’s recommended to store mutable state in theTofStore<T>which is accessed throughCaller<'_, T>provided to host functions. -
Module(orComponent) - a compiled WebAssembly module or component. These structures contain compiled executable code from a WebAssembly binary which is ready to execute after being instantiated. These are expensive to create as they require compilation of the input WebAssembly. Modules and components are safe to share across threads, however. Modules and components can additionally be serialized into a list of bytes to later be deserialized quickly. This enables JIT-style compilation through constructors such asModule::newand AOT-style compilation by having the compilation process useModule::serializeand the execution process useModule::deserialize. -
Instance(orcomponent::Instance) - an instantiated WebAssembly module or component. An instance is where you can actually acquire aFunc(orcomponent::Func) from, for example, to call. -
Func(orcomponent::Func) - a WebAssembly function. This can be acquired as the export of anInstanceto call WebAssembly functions, or it can be created via functions likeFunc::wrapto wrap host-defined functionality and give it to WebAssembly. Functions also have typed views asTypedFuncorcomponent::TypedFuncfor a more efficient calling convention. -
Table,Global,Memory,component::Resource- other WebAssembly objects which can either be defined on the host or in wasm itself (via instances). These all have various ways of being interacted with likeFunc.
All “store-connected” types such as Func, Memory, etc, require the
store to be passed in as a context to each method. Methods in wasmtime
frequently have their first parameter as either impl AsContext or impl AsContextMut. These
traits are implemented for a variety of types, allowing you to, for example,
pass the following types into methods:
&Store<T>&mut Store<T>&Caller<'_, T>&mut Caller<'_, T>StoreContext<'_, T>StoreContextMut<'_, T>
A Store is the sole owner of all WebAssembly internals. Types like
Func point within the Store and require the Store to be provided
to actually access the internals of the WebAssembly function, for instance.
§WASI
The wasmtime crate does not natively provide support for WASI, but you can
use the wasmtime-wasi crate for that purpose. With wasmtime-wasi all
WASI functions can be added to a Linker and then used to instantiate
WASI-using modules. For more information see the WASI example in the
documentation.
§Crate Features
The wasmtime crate comes with a number of compile-time features that can
be used to customize what features it supports. Some of these features are
just internal details, but some affect the public API of the wasmtime
crate. Wasmtime APIs gated behind a Cargo feature should be indicated as
such in the documentation.
-
runtime- Enabled by default, this feature enables executing WebAssembly modules and components. If a compiler is not available (such ascranelift) thenModule::deserializemust be used, for example, to provide an ahead-of-time compiled artifact to execute WebAssembly. -
cranelift- Enabled by default, this features enables using Cranelift at runtime to compile a WebAssembly module to native code. This feature is required to process and compile new WebAssembly modules and components. -
cache- Enabled by default, this feature adds support for wasmtime to perform internal caching of modules in a global location. This must still be enabled explicitly throughConfig::cache_config_loadorConfig::cache_config_load_default. -
wat- Enabled by default, this feature adds support for accepting the text format of WebAssembly inModule::newandComponent::new. The text format will be automatically recognized and translated to binary when compiling a module. -
parallel-compilation- Enabled by default, this feature enables support for compiling functions in parallel withrayon. -
async- Enabled by default, this feature enables APIs and runtime support for defining asynchronous host functions and calling WebAssembly asynchronously. For more information seeConfig::async_support. -
profiling- Enabled by default, this feature compiles in support for profiling guest code via a number of possible strategies. SeeConfig::profilerfor more information. -
all-arch- Not enabled by default. This feature compiles in support for all architectures for both the JIT compiler and thewasmtime compileCLI command. This can be combined withConfig::targetto precompile modules for a different platform than the host. -
pooling-allocator- Enabled by default, this feature adds support forPoolingAllocationConfigto pass toConfig::allocation_strategy. The pooling allocator can enable efficient reuse of resources for high-concurrency and high-instantiation-count scenarios. -
demangle- Enabled by default, this will affect how backtraces are printed and whether symbol names from WebAssembly are attempted to be demangled. Rust and C++ demanglings are currently supported. -
coredump- Enabled by default, this will provide support for generating a core dump when a trap happens. This can be configured viaConfig::coredump_on_trap. -
addr2line- Enabled by default, this feature configures whether traps will attempt to parse DWARF debug information and convert WebAssembly addresses to source filenames and line numbers. -
debug-builtins- Enabled by default, this feature includes some built-in debugging utilities and symbols for native debuggers such as GDB and LLDB to attach to the process Wasmtime is used within. The intrinsics provided will enable debugging guest code compiled to WebAssembly. This must also be enabled viaConfig::debug_infoas well for guests. -
component-model- Enabled by default, this enables support for thewasmtime::componentAPI for working with components. -
gc- Enabled by default, this enables support for a number of WebAssembly proposals such asreference-types,function-references, andgc. Note that the implementation of thegcproposal itself is not yet complete at this time. -
threads- Enabled by default, this enables compile-time support for the WebAssemblythreadsproposal, notably shared memories. -
call-hook- Disabled by default, this enables support for theStore::call_hookAPI. This incurs a small overhead on all entries/exits from WebAssembly and may want to be disabled by some embedders. -
memory-protection-keys- Disabled by default, this enables support for thePoolingAllocationConfig::memory_protection_keysAPI. This feature currently only works on x64 Linux and can enable compacting the virtual memory allocation for linear memories in the pooling allocator. This comes with the same overhead as thecall-hookfeature where entries/exits into WebAssembly will have more overhead than before. -
signals-based-traps- Enabled by default, this enables support for using host signal handlers to implement WebAssembly traps. For example virtual memory is used to catch out-of-bounds accesses in WebAssembly that result in segfaults. This is implicitly enabled by thestdfeature and is the best way to get high-performance WebAssembly.
More crate features can be found in the manifest of Wasmtime itself for seeing what can be enabled and disabled.
Re-exports§
pub use anyhow::Error;pub use anyhow::Result;pub use wasmparser;reexport-wasmparser
Modules§
- component
runtimeandcomponent-model - Embedding API for the Component Model
- unix
runtime - Unix-specific extension for the
wasmtimecrate.
Structs§
- AnyRef
gcandruntime - An
anyrefGC reference. - Array
Ref gcandruntime - A reference to a GC-managed
arrayinstance. - Array
RefPre gcandruntime - An allocator for a particular Wasm GC array type.
- Array
Type runtime - The type of a WebAssembly array.
- Caller
runtime - A structure representing the caller’s context when creating a function
via
Func::wrap. - Code
Builder craneliftorwinch - Builder-style structure used to create a
Moduleor pre-compile a module to a serialized list of bytes. - Code
Memory runtime - Management of executable memory within a
MmapVec - Compiled
Module runtime - A compiled wasm module, ready to be instantiated.
- Config
- Global configuration options used to create an
Engineand customize its behavior. - Engine
- An
Enginewhich is a global context for compilation and management of wasm modules. - Engine
Weak - A weak reference to an
Engine. - EqRef
gcandruntime - A reference to a GC-managed object that can be tested for equality.
- Export
runtime - An exported WebAssembly value.
- Export
Type runtime - A descriptor for an exported WebAssembly value.
- Extern
Ref gcandruntime - An opaque, GC-managed reference to some host data that can be passed to WebAssembly.
- Field
Type runtime - The type of a
structfield or anarray’s elements. - Frame
Info runtime - Description of a frame in a backtrace for a
WasmBacktrace. - Frame
Symbol runtime - Debug information for a symbol that is attached to a
FrameInfo. - Func
runtime - A WebAssembly function which can be called.
- Func
Type runtime - The type of a WebAssembly function.
- GcHeap
OutOf Memory runtime - An error returned when attempting to allocate a GC-managed object, but the GC heap is out of memory.
- Global
runtime - A WebAssembly
globalvalue which can be read and written to. - Global
Type runtime - A WebAssembly global descriptor.
- Guest
Profiler profilingandruntime - Collects basic profiling data for a single WebAssembly guest.
- I31
gcandruntime - A 31-bit integer.
- Import
Type runtime - A descriptor for an imported value into a wasm module.
- Instance
runtime - An instantiated WebAssembly module.
- Instance
Pre runtime - An instance, pre-instantiation, that is ready to be instantiated.
- Linker
runtime - Structure used to link wasm modules/instances together.
- Manually
Rooted gcandruntime - A rooted reference to a garbage-collected
Twith arbitrary lifetime. - Memory
runtime - A WebAssembly linear memory.
- Memory
Access Error runtime - Error for out of bounds
Memoryaccess. - Memory
Type runtime - A descriptor for a WebAssembly memory type.
- Memory
Type Builder runtime - A builder for
MemoryTypes. - Module
runtime - A compiled WebAssembly module, ready to be instantiated.
- Module
Export runtime - Describes the location of an export in a module.
- NoExtern
runtime - A reference to the abstract
noexternheap value. - NoFunc
runtime - A reference to the abstract
nofuncheap value. - NoneRef
runtime - A reference to the abstract
noneheap value. - Pool
Concurrency Limit Error pooling-allocatorandruntime - An error returned when the pooling allocator cannot allocate a table, memory, etc… because the maximum number of concurrent allocations for that entity has been reached.
- Pooling
Allocation Config pooling-allocator - Configuration options used with
InstanceAllocationStrategy::Poolingto change the behavior of the pooling instance allocator. - RefType
runtime - Opaque references to data in the Wasm heap or to host data.
- Resources
Required runtime - A summary of the amount of resources required to instantiate a particular
ModuleorComponent. - Root
Scope gcandruntime - Nested rooting scopes.
- Rooted
gcandruntime - A scoped, rooted reference to a garbage-collected
T. - Shared
Memory runtime - A constructor for externally-created shared memory.
- Store
runtime - A
Storeis a collection of WebAssembly instances and host-defined state. - Store
Context runtime - A temporary handle to a
&Store<T>. - Store
Context Mut runtime - A temporary handle to a
&mut Store<T>. - Store
Limits runtime - Provides limits for a
Store. - Store
Limits Builder runtime - Used to build
StoreLimits. - Struct
Ref gcandruntime - A reference to a GC-managed
structinstance. - Struct
RefPre gcandruntime - An allocator for a particular Wasm GC struct type.
- Struct
Type runtime - The type of a WebAssembly struct.
- Table
runtime - A WebAssembly
table, or an array of values. - Table
Type runtime - A descriptor for a table in a WebAssembly module.
- Tag
runtime - A WebAssembly
tag. - TagType
runtime - A descriptor for a tag in a WebAssembly module.
- Typed
Func runtime - A statically typed WebAssembly function.
- Unknown
Import Error runtime - Error for an unresolvable import.
- V128
runtime - Representation of a 128-bit vector type,
v128, for WebAssembly. - Wasm
Backtrace runtime - Representation of a backtrace of function frames in a WebAssembly module for where an error happened.
- Wasm
Core Dump coredumpandruntime - Representation of a core dump of a WebAssembly module
Enums§
- Call
Hook runtime - Passed to the argument of
Store::call_hookto indicate a state transition in the WebAssembly VM. - Code
Hint craneliftorwinch - Return value of
CodeBuilder::hint - Collector
- Possible garbage collector implementations for Wasm.
- Extern
runtime - An external item to a WebAssembly module, or a list of what can possibly be exported from a wasm module.
- Extern
Type runtime - A list of all possible types which can be externally referenced from a WebAssembly module.
- Finality
runtime - Indicator of whether a type is final or not.
- Heap
Type runtime - The heap types that can Wasm can have references to.
- Instance
Allocation Strategy - Represents the module instance allocation strategy to use.
- Module
Version Strategy - Configure the strategy used for versioning in serializing and deserializing
crate::Module. - MpkEnabled
- Describe the tri-state configuration of memory protection keys (MPK).
- Mutability
runtime - Indicator of whether a global value, struct’s field, or array type’s elements are mutable or not.
- OptLevel
- Possible optimization levels for the Cranelift codegen backend.
- Precompiled
- Return value from the
Engine::detect_precompiledAPI. - Profiling
Strategy - Select which profiling technique to support.
- Ref
runtime - A reference.
- Regalloc
Algorithm - Possible register allocator algorithms for the Cranelift codegen backend.
- Storage
Type runtime - The storage type of a
structfield orarrayelement. - Strategy
- Possible Compilation strategies for a wasm module.
- Trap
- Representation of a WebAssembly trap and what caused it to occur.
- Update
Deadline runtime - What to do after returning from a callback when the engine epoch reaches the deadline for a Store during execution of a function using that store.
- Val
runtime - Possible runtime values that a WebAssembly module can either consume or produce.
- ValType
runtime - A list of all possible value types in WebAssembly.
- Wait
Result runtime - Result of
Memory::atomic_wait32andMemory::atomic_wait64 - Wasm
Backtrace Details - Select how wasm backtrace detailed information is handled.
Constants§
- DEFAULT_
INSTANCE_ LIMIT runtime - Value returned by
ResourceLimiter::instancesdefault method - DEFAULT_
MEMORY_ LIMIT runtime - Value returned by
ResourceLimiter::memoriesdefault method - DEFAULT_
TABLE_ LIMIT runtime - Value returned by
ResourceLimiter::tablesdefault method
Traits§
- AsContext
runtime - A trait used to get shared access to a
Storein Wasmtime. - AsContext
Mut runtime - A trait used to get exclusive mutable access to a
Storein Wasmtime. - Cache
Store incremental-cacheandcranelift - Implementation of an incremental compilation’s key/value cache store.
- Call
Hook Handler asyncandruntimeandcall-hook - An object that can take callbacks when the runtime enters or exits hostcalls.
- Custom
Code Memory runtime - Interface implemented by an embedder to provide custom implementations of code-memory protection and execute permissions.
- GcRef
runtime - A common trait implemented by all garbage-collected reference types.
- Into
Func runtime - Internal trait implemented for all arguments that can be passed to
Func::wrapandLinker::func_wrap. - Linear
Memory runtime - A linear memory. This trait provides an interface for raw memory buffers which are used by wasmtime, e.g. inside [‘Memory’]. Such buffers are in principle not thread safe. By implementing this trait together with MemoryCreator, one can supply wasmtime with custom allocated host managed memory.
- Memory
Creator runtime - A memory creator. Can be used to provide a memory creator to wasmtime which supplies host managed memory.
- Resource
Limiter runtime - Used by hosts to limit resource consumption of instances.
- Resource
Limiter Async runtimeandasync - Used by hosts to limit resource consumption of instances, blocking asynchronously if necessary.
- Rooted
GcRef runtime - A trait implemented for GC references that are guaranteed to be rooted:
- Stack
Creator asyncandruntime - A stack creator. Can be used to provide a stack creator to wasmtime which supplies stacks for async support.
- Stack
Memory asyncandruntime - A stack memory. This trait provides an interface for raw memory buffers which are used by wasmtime inside of stacks which wasmtime executes WebAssembly in for async support. By implementing this trait together with StackCreator, one can supply wasmtime with custom allocated host managed stacks.
- Wasm
Params runtime - A trait used for
Func::typedand withTypedFuncto represent the set of parameters for wasm functions. - Wasm
Results runtime - A trait used for
Func::typedand withTypedFuncto represent the set of results for wasm functions. - WasmRet
runtime - A trait implemented for types which can be returned from closures passed to
Func::wrapand friends. - WasmTy
runtime - A trait implemented for types which can be arguments and results for
closures passed to
Func::wrapas well as parameters toFunc::typed. - Wasm
TyList runtime - Trait implemented for various tuples made up of types which implement
WasmTythat can be passed toFunc::wrap_innerand [HostContext::from_closure].
Unions§
- ValRaw
runtime - A “raw” and unsafe representation of a WebAssembly value.