[−][src]Crate wasmer
This crate contains the wasmer
API. The wasmer
API facilitates the efficient,
sandboxed execution of WebAssembly (Wasm) modules.
Here's an example of the wasmer
API in action:
use wasmer::{Store, Module, Instance, Value, imports}; fn main() -> anyhow::Result<()> { let module_wat = r#" (module (type $t0 (func (param i32) (result i32))) (func $add_one (export "add_one") (type $t0) (param $p0 i32) (result i32) get_local $p0 i32.const 1 i32.add)) "#; let store = Store::default(); let module = Module::new(&store, &module_wat)?; // The module doesn't import anything, so we create an empty import object. let import_object = imports! {}; let instance = Instance::new(&module, &import_object)?; let add_one = instance.exports.get_function("add_one")?; let result = add_one.call(&[Value::I32(42)])?; assert_eq!(result[0], Value::I32(43)); Ok(()) }
For more examples of using the wasmer
API, check out the
wasmer examples.
Table of Contents
Wasm Primitives
In order to make use of the power of the wasmer
API, it's important
to understand the primitives around which the API is built.
Wasm only deals with a small number of core data types, these data
types can be found in the Value
type.
In addition to the core Wasm types, the core types of the API are referred to as "externs".
Externs
An Extern
is a type that can be imported or exported from a Wasm
module.
To import an extern, simply give it a namespace and a name with the
imports
macro:
let memory = Memory::new(&store, MemoryType::new(1, None, false)).unwrap(); imports! { "env" => { "my_function" => Function::new_native(store, || println!("Hello")), "memory" => memory, } }
And to access an exported extern, see the Exports
API, accessible
from any instance via instance.exports
:
let memory = instance.exports.get_memory("memory")?; let memory: &Memory = instance.exports.get("some_other_memory")?; let add: NativeFunc<(i32, i32), i32> = instance.exports.get_native_function("add")?; let result = add.call(5, 37)?; assert_eq!(result, 42);
These are the primary types that the wasmer
API uses.
Functions
There are 2 types of functions in wasmer
:
- Wasm functions
- Host functions
A Wasm function is a function defined in a WebAssembly module that can only perform computation without side effects and call other functions.
Wasm functions take 0 or more arguments and return 0 or more results.
Wasm functions can only deal with the primitive types defined in
Value
.
A Host function is any function implemented on the host, in this case in Rust.
Host functions can optionally be created with an environment that
implements WasmerEnv
. This environment is useful for maintaining
host state (for example the filesystem in WASI).
Thus WebAssembly modules by themselves cannot do anything but computation
on the core types in Value
. In order to make them more useful we
give them access to the outside world with imports
.
If you're looking for a sandboxed, POSIX-like environment to execute Wasm
in, check out the [wasmer-wasi
][] crate for our implementation of WASI,
the WebAssembly System Interface.
In the wasmer
API we support functions which take their arguments and
return their results dynamically, Function
, and functions which
take their arguments and return their results statically, NativeFunc
.
Memories
Memories store data.
In most Wasm programs, nearly all data will live in a Memory
.
This data can be shared between the host and guest to allow for more interesting programs.
Globals
A Global
is a type that may be either mutable or immutable, and
contains one of the core Wasm types defined in Value
.
Tables
A Table
is an indexed list of items.
Project Layout
The Wasmer project is divided into a number of crates, below is a dependency graph with transitive dependencies removed.
While this crate is the top level API, we also publish crates built on top of this API that you may be interested in using, including:
- wasmer-cache for caching compiled Wasm modules.
- wasmer-emscripten for running Wasm modules compiled to the Emscripten ABI.
- wasmer-wasi for running Wasm modules compiled to the WASI ABI.
The Wasmer project has two major abstractions:
These two abstractions have multiple options that can be enabled with features.
Engines
An engine is a system that uses a compiler to make a WebAssembly module executable.
Compilers
A compiler is a system that handles the details of making a Wasm module executable. For example, by generating native machine code for each Wasm function.
Features
This crate's features can be broken down into 2 kinds, features that enable new functionality and features that set defaults.
The features that enable new functionality are:
jit
- enable the JIT engine. (See wasmer-jit)native
- enable the native engine. (See wasmer-native)cranelift
- enable Wasmer's Cranelift compiler. (See wasmer-cranelift)llvm
- enable Wasmer's LLVM compiler. (See wasmer-llvm)singlepass
- enable Wasmer's Singlepass compiler. (See wasmer-singlepass)wat
- enablewasmer
to parse the WebAssembly text format.
The features that set defaults come in sets that are mutually exclusive.
The first set is the default compiler set:
default-cranelift
- set Wasmer's Cranelift compiler as the default.default-llvm
- set Wasmer's LLVM compiler as the default.default-singlepass
- set Wasmer's Singlepass compiler as the default.
The next set is the default engine set:
default-jit
- set the JIT engine as the default.default-native
- set the native engine as the default.
By default the wat
, default-cranelift
, and default-jit
features
are enabled.
Re-exports
pub use wasmer_compiler::wasmparser; |
Modules
vm | The vm module re-exports wasmer-vm types. |
Macros
imports | Generate an |
Structs
Array | The |
Atomically | Atomically. |
BaseTunables | Tunable parameters for WebAssembly compilation.
This is the reference implementation of the |
Bytes | Units of WebAssembly memory in terms of 8-bit bytes. |
Cranelift | Global configuration options used to create an
|
ExportType | A descriptor for an exported WebAssembly value. |
Exports | Exports is a special kind of map that allows easily unwrapping the types of instances. |
ExportsIterator | An iterator over exports. |
Features | Controls which experimental features will be enabled. Features usually have a corresponding WebAssembly proposal. |
FrameInfo | Description of a frame in a backtrace for a |
Function | A WebAssembly |
FunctionType | The signature of a function that is either implemented in a Wasm module or exposed to Wasm by the host. |
Global | A WebAssembly |
GlobalType | WebAssembly global. |
HostRef | Represents a piece of data located in the host environment. |
ImportObject | All of the import data used when instantiating. |
ImportObjectIterator | Iterator for an |
ImportType | A descriptor for an imported value into a wasm module. |
Instance | A WebAssembly Instance is a stateful, executable
instance of a WebAssembly |
Item | The |
JIT | The JIT builder |
JITArtifact | A compiled wasm module, ready to be instantiated. |
JITEngine | A WebAssembly |
LazyInit | Lazily init an item |
LocalFunctionIndex | Index type of a function defined locally inside the WebAssembly module. |
Memory | A WebAssembly |
MemoryType | A descriptor for a WebAssembly memory type. |
MemoryView | A view into a memory. |
MiddlewareError | A error in the middleware. |
MiddlewareReaderState | The state of the binary reader. Exposed to middlewares to push their outputs. |
Module | A WebAssembly Module contains stateless WebAssembly code that has already been compiled and can be instantiated multiple times. |
NamedResolverChain | A |
NativeFunc | A WebAssembly function that can be called natively (using the Native ABI). |
Pages | Units of WebAssembly pages (as specified to be 65,536 bytes). |
RuntimeError | A struct representing an aborted instruction execution, with a message indicating the cause. |
Store | The store represents all global state that can be manipulated by WebAssembly programs. It consists of the runtime representation of all instances of functions, tables, memories, and globals that have been allocated during the lifetime of the abstract machine. |
Table | A WebAssembly |
TableType | A descriptor for a table in a WebAssembly module. |
Target | This is the target that we will use for compiling the WebAssembly ModuleInfo, and then run it. |
Triple | A target "triple". Historically such things had three fields, though they've added additional fields over time. |
WasmPtr | A zero-cost type that represents a pointer to something in Wasm linear memory. |
Enums
Architecture | The "architecture" field, which in some cases also specifies a specific subarchitecture. |
CallingConvention | The calling convention, which specifies things like which registers are used for passing arguments, which registers are callee-saved, and so on. |
CompileError | The WebAssembly.CompileError object indicates an error during WebAssembly decoding or validation. |
CpuFeature | The nomenclature is inspired by the |
CraneliftOptLevel | Possible optimization levels for the Cranelift codegen backend. |
DeserializeError | The Deserialize error can occur when loading a compiled Module from a binary. |
Export | The value of an export passed from one instance to another. |
ExportError | The |
ExportIndex | An entity to export. |
Extern | An |
ExternRef | Represents an opaque reference to any data within WebAssembly. |
ExternType | A list of all possible types which can be externally referenced from a WebAssembly module. |
GlobalInit | Globals are initialized via the |
HostEnvInitError | An error while initializing the user supplied host env with the |
InstantiationError | An error while instantiating a module. |
LinkError | The WebAssembly.LinkError object indicates an error during module instantiation (besides traps from the start function). |
MemoryError | Error type describing things that can go wrong when operating on Wasm Memories. |
Mutability | Indicator of whether a global is mutable or not |
OperatingSystem | The "operating system" field, which sometimes implies an environment, and sometimes isn't an actual operating system. |
ParseCpuFeatureError | The error that can happen while parsing a |
SerializeError | The Serialize error can occur when serializing a compiled Module into a binary. |
Type | A list of all possible value types in WebAssembly. |
VMExport | The value of an export passed from one instance to another. |
ValType | A list of all possible value types in WebAssembly. |
WasmError | A WebAssembly translation error. |
Constants
HOST | The |
VERSION | Version number of this crate. |
WASM_MAX_PAGES | The number of pages we can have before we run out of byte index space. |
WASM_MIN_PAGES | The minimum number of pages allowed. |
WASM_PAGE_SIZE | WebAssembly page sizes are fixed to be 64KiB. Note: large page support may be added in an opt-in manner in the future. |
Traits
ChainableNamedResolver | A trait for chaining resolvers together. |
CompilerConfig | The compiler configuration options. |
Engine | A unimplemented Wasmer |
Exportable | This trait is used to mark types as gettable from an |
FromToNativeWasmType | A trait to convert a Rust value to a |
FunctionMiddleware | A function middleware specialized for a single function. |
HostFunction | The |
HostInfo | |
LikeNamespace | The |
ModuleMiddleware | A shared builder for function middlewares. |
NamedResolver | Import resolver connects imports with available exported values. |
Resolver | Import resolver connects imports with available exported values. |
StoreObject | A trait represinting any object that lives in the |
Tunables | An engine delegates the creation of memories, tables, and globals to a foreign implementor of this trait. |
ValueType | Trait for a Value type. A Value type is a type that is always valid and may be safely copied. |
WasmTypeList | The |
WasmerEnv | Trait for initializing the environments passed to host functions after instantiation but before execution. |
Functions
is_wasm | Check if the provided bytes are wasm-like |
raise_user_trap⚠ | Raises a user-defined trap immediately. |
wat2wasm | Parses in-memory bytes as either the WebAssembly Text format, or a binary WebAssembly module. |
Type Definitions
Val | WebAssembly computations manipulate values of basic value types: |
Value | WebAssembly computations manipulate values of basic value types: |
WasmResult | A convenient alias for a |
Derive Macros
WasmerEnv | Implement |