Crate wasmer

source ·
Expand description

Wasmer is the most popular WebAssembly runtime for Rust. It supports JIT (Just In Time) and AOT (Ahead Of Time) compilation as well as pluggable compilers suited to your needs and interpreters.

It’s designed to be safe and secure, and runnable in any kind of environment.

§Usage

Here is a small example of using Wasmer to run a WebAssembly module written with its WAT format (textual format):

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)
        local.get $p0
        i32.const 1
        i32.add))
    "#;

    let mut 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(&mut store, &module, &import_object)?;

    let add_one = instance.exports.get_function("add_one")?;
    let result = add_one.call(&mut store, &[Value::I32(42)])?;
    assert_eq!(result[0], Value::I32(43));

    Ok(())
}

Discover the full collection of examples.

§Overview of the Features

Wasmer is not only fast, but also designed to be highly customizable:

  • Pluggable compilers — A compiler is used by the engine to transform WebAssembly into executable code:

  • Interpreters - Wasmer supports interpeters such as wamr and wasmi.

  • Other runtimes - Wasmer supports v8.

  • Headless mode — Once a WebAssembly module has been compiled, it is possible to serialize it in a file for example, and later execute it with Wasmer with headless mode turned on. Headless Wasmer has no compiler, which makes it more portable and faster to load. It’s ideal for constrainted environments.

  • Cross-compilation — Most compilers support cross-compilation. It means it possible to pre-compile a WebAssembly module targetting a different architecture or platform and serialize it, to then run it on the targetted architecture and platform later.

  • Run Wasmer in a JavaScript environment — With the js Cargo feature, it is possible to compile a Rust program using Wasmer to WebAssembly. In this context, the resulting WebAssembly module will expect to run in a JavaScript environment, like a browser, Node.js, Deno and so on. In this specific scenario, there is no engines or compilers available, it’s the one available in the JavaScript environment that will be used.

Wasmer ships by default with the Cranelift compiler as its great for development purposes. However, we strongly encourage to use the LLVM compiler in production as it performs about 50% faster, achieving near-native speeds.

Note: if one wants to use multiple compilers at the same time, it’s also possible! One will need to import them directly via each of the compiler crates.

§Table of Contents

§WebAssembly 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(&mut store, MemoryType::new(1, None, false)).unwrap();
imports! {
    "env" => {
         "my_function" => Function::new_typed(&mut 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: TypedFunction<(i32, i32), i32> = instance.exports.get_typed_function(&mut store, "add")?;
let result = add.call(&mut store, 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:

  1. Wasm functions,
  2. 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.

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-wasix crate for our implementation of WASI, the WebAssembly System Interface, and WASIX, the Extended version of WASI.

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, TypedFunction.

§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:

The Wasmer project has two major abstractions:

  1. Engine,
  2. Compilers.

These two abstractions have multiple options that can be enabled with features.

§Engine

The engine is a system that uses a compiler to make a WebAssembly module executable.

§Runtimes

A runtime is a system that handles the details of making a Wasm module executable. We support multiple kinds of runtimes: compilers, which generate native machine code for each Wasm function and interpreter, in which no native machine code is generated and can be used on platforms where JIT compilation is not allowed, such as iOS.

§Cargo Features

  1. sys (enabled), where wasmer will be compiled to a native executable which provides compilers, engines, a full VM etc. By default, the singlepass and cranelift backends are enabled.

  2. v8 (disabled), where wasmer will be compiled to a native executable where the v8 runtime is used for execution.

  3. wamr (disabled), where wasmer will be compiled to a native executable where wamr (in interpreter mode) is used for execution.

  4. js (disabled), where wasmer will be compiled to WebAssembly to run in a JavaScript host (see Using Wasmer in a JavaScript environment).

§Features for the sys feature group (enabled)

The default features can be enabled with the sys-default feature.

The features for the sys feature group can be broken down into 2 kinds: features that enable new functionality and features that set defaults.

The features that enable new functionality are:

  • cranelift (enabled), enables Wasmer’s [Cranelift compiler][wasmer-compiler-cranelift],
  • llvm (enabled), enables Wasmer’s [LLVM compiler][wasmer-compiler-lvm],
  • singlepass (enabled), enables Wasmer’s [Singlepass compiler][wasmer-compiler-singlepass],
  • wat (enabled), enables wasmer to parse the WebAssembly text format,
  • compilation (enabled), enables compilation with the wasmer engine.

Notice that the sys, wamr and v8 features are composable together, so a single build of Wasmer using llvm, cranelift, singlepass, wamr, and v8 (or any combination of them) is possible.

§Features for the js feature group (disabled)

The default features can be enabled with the js-default feature.

Here are the detailed list of features:

  • wasm-types-polyfill (disabled), parses the Wasm file, allowing to do type reflection of the inner Wasm types. It adds 100kb to the Wasm bundle (28kb gzipped). It is possible to disable it and to use Module::set_type_hints manually instead for a lightweight alternative. This is needed until the Wasm JS introspection API proposal is adopted by browsers,
  • wat (enabled), allows to read a Wasm file in its text format. This feature is normally used only in development environments. It will add around 650kb to the Wasm bundle (120Kb gzipped).

§Using Wasmer in a JavaScript environment

Imagine a Rust program that uses this wasmer crate to execute a WebAssembly module. It is possible to compile this Rust progam to WebAssembly by turning on the js Cargo feature of this wasmer crate.

Here is a small example illustrating such a Rust program, and how to compile it with wasm-pack and wasm-bindgen:

use wasm_bindgen::prelude::*;
use wasmer::{imports, Instance, Module, Store, Value};

#[wasm_bindgen]
pub extern fn do_add_one_in_wasmer() -> i32 {
    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)
        local.get $p0
        i32.const 1
        i32.add))
    "#;
    let mut store = Store::default();
    let module = Module::new(&store, &module_wat).unwrap();
    // The module doesn't import anything, so we create an empty import object.
    let import_object = imports! {};
    let instance = Instance::new(&mut store, &module, &import_object).unwrap();

    let add_one = instance.exports.get_function("add_one").unwrap();
    let result = add_one.call(&mut store, &[Value::I32(42)]).unwrap();
    assert_eq!(result[0], Value::I32(43));

    result[0].unwrap_i32()
}

Note that it’s the same code as above with the former example. The API is the same!

Then, compile with wasm-pack build. Take care of using the js or js-default Cargo features.

Re-exports§

  • pub use wasmparser;

Modules§

  • backend 🔒
    This submodule has the concrete definitions for all the available implenters of the WebAssembly types needed to create a runtime.
  • entities 🔒
    This module defines data types, functions and traits used to describe and interact with various WebAssembly entities such as Value, Module and Store. It also describes entities related to the runtime, such as Engine.
  • error 🔒
  • Data types, functions and traits for the sys runtime.
  • utils 🔒
    Useful data types, functions and traits used throughout the crate to interact with WebAssembly entities such as crate::Memory and crate::Value.
  • vm 🔒
    This module defines traits to handle abstractions created by the runtimes.

Macros§

Structs§

  • Units of WebAssembly memory in terms of 8-bit bytes.
  • The Engine is the entrypoint type for the runtime. It defines the kind of steps the runtime must take to execute the WebAssembly module (compile, interpret..) and the place of execution (in-browser, host, ..).
  • An engine identifier.
  • A temporary handle to an Engine.
  • A WebAssembly exception instance.
  • An opaque reference to some data. This reference can be passed through Wasm.
  • A descriptor for an exported WebAssembly value.
  • Exports is a special kind of map that allows easily unwrapping the types of instances.
  • An iterator over exports.
  • An opaque reference to some data. This reference can be passed through Wasm.
  • Description of a frame in a backtrace.
  • A WebAssembly function instance.
  • An opaque reference to a function environment. The function environment data is owned by the Store.
  • A temporary handle to a FunctionEnv.
  • The signature of a function that is either implemented in a Wasm module or exposed to Wasm by the host.
  • A WebAssembly global instance.
  • WebAssembly global.
  • A descriptor for an imported value into a wasm module.
  • All of the import data used when instantiating.
  • An iterator over module imports.
  • A WebAssembly Instance is a stateful, executable instance of a WebAssembly Module.
  • Index type of a function defined locally inside the WebAssembly module.
  • A WebAssembly memory instance.
  • Marker trait for 32-bit memories.
  • Marker trait for 64-bit memories.
  • Location in a WebAssembly memory.
  • A descriptor for a WebAssembly memory type.
  • A WebAssembly memory view.
  • A WebAssembly Module contains stateless WebAssembly code that has already been compiled and can be instantiated multiple times.
  • Units of WebAssembly pages (as specified to be 65,536 bytes).
  • A struct representing an aborted instruction execution, with a message indicating the cause.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A structure with a C-compatible representation that can hold a set of Wasm values. This type is used by WasmTypeList::CStruct.
  • A handle that exposes operations only relevant for shared memories.
  • 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.
  • A temporary handle to a crate::Store.
  • A temporary handle to a crate::Store.
  • A WebAssembly table instance.
  • A descriptor for a table in a WebAssembly module.
  • A WebAssembly tag instance.
  • A WebAssembly function that can be called natively (using the Native ABI).
  • A zero-cost type that represents a pointer to something in Wasm linear memory.
  • Reference to a value in Wasm memory.
  • Reference to an array of values in Wasm memory.
  • Iterator over the elements of a WasmSlice.
  • An empty struct to help Rust typing to determine when a HostFunction does have an environment.
  • An empty struct to help Rust typing to determine when a HostFunction does not have an environment.

Enums§

  • Error that can occur during atomic operations. (notify/wait)
  • An enumeration over all the supported runtimes.
  • An enumeration of all the trap kinds supported by the runtimes.
  • The WebAssembly.CompileError object indicates an error during WebAssembly decoding or validation.
  • The Deserialize error can occur when loading a compiled Module from a binary.
  • The ExportError can happen when trying to get a specific export Extern from the Instance exports.
  • An entity to export.
  • An Extern is the runtime representation of an entity that can be imported or exported.
  • A list of all possible types which can be externally referenced from a WebAssembly module.
  • Globals are initialized via the const operators or by referring to another import.
  • An error while instantiating a module.
  • IO errors that can happen while compiling a Module.
  • The WebAssembly.LinkError object indicates an error during module instantiation (besides traps from the start function).
  • Error for invalid Memory access.
  • Error type describing things that can go wrong when operating on Wasm Memories.
  • Implementation styles for WebAssembly linear memory.
  • Indicator of whether a global is mutable or not
  • After the stack is unwound via asyncify what should the call loop do next
  • The error that can happen while parsing a str to retrieve a CpuFeature.
  • The Serialize error can occur when serializing a compiled Module into a binary.
  • Set of objects managed by a context.
  • Implementation styles for WebAssembly tables.
  • A list of all possible value types in WebAssembly.
  • WebAssembly computations manipulate values of basic value types:
  • A WebAssembly translation error.

Constants§

  • The number of pages we can have before we run out of byte index space.
  • The minimum number of pages allowed.
  • WebAssembly page sizes are fixed to be 64KiB. Note: large page support may be added in an opt-in manner in the future.

Traits§

  • Helper trait for a value that is convertible to a EngineRef.
  • Helper trait for a value that is convertible to a StoreMut.
  • Helper trait for a value that is convertible to a StoreRef.
  • This trait is used to mark types as gettable from an Instance.
  • A trait for accessing exports (like Exportable) but it takes generic Args and Rets parameters so that TypedFunction can be accessed directly as well.
  • A trait to convert a Rust value to a WasmNativeType value, or to convert WasmNativeType value to a Rust value.
  • The HostFunction trait represents the set of functions that can be used as host function. To uphold this statement, it is necessary for a function to be transformed into a VMFunctionCallback.
  • Convert binary data into [bytes::Bytes].
  • The IntoResult trait turns a WasmTypeList into a Result<WasmTypeList, Self::Error>.
  • Trait for the Memory32 and Memory64 marker types.
  • NativeWasmType represents a Wasm type that has a direct representation on the host (hence the “native” term).
  • NativeWasmTypeInto performs conversions from and into NativeWasmType types with a context.
  • Trait convert a VMExtern to a Extern
  • Trait for a Value type. A Value type is a type that is always valid and may be safely copied.
  • The WasmTypeList trait represents a tuple (list) of Wasm typed values. It is used to get low-level representation of such a tuple.

Functions§

Type Aliases§

  • Alias for `WasmPtr<T, Memory64>.
  • A convenient alias for a Result that uses WasmError as the error type.

Derive Macros§