wasm (wasm v0.16.0)
View SourceA WebAssembly runtime for Erlang/OTP.
Start here when you are embedding the runtime. You load a module once, instantiate it as often as you need, call its exports, and destroy the instances when you are done.
{ok, Mod} = wasm:load(Binary), % compiled once, cached
{ok, Inst} = wasm:instantiate(Mod, Imports), % owned by this process
{ok, [R]} = wasm:call(Inst, ~"run", [42]),
ok = wasm:destroy(Inst).Where things are
The first column is the banner (%%% name) the code sits under; the banners
are in this order in the file.
| banner | you want | look at |
|---|---|---|
| lifecycle | a module from bytes or text, cached or not | load/1, load/2, load_file/1, compile/1, compile/2 |
| lifecycle | validation, and dropping a cached module | validate/1, compile_with/3, unload/1 |
| lifecycle | a new instance, and the limits it gets | instantiate/2, instantiate/3, check_limits/1, defaults/1 |
| lifecycle | checking a call's arguments | check_args/3 |
| lifecycle | the start function | run_start/3 |
| call protocol | calling an export | call/3, call/4 |
| call protocol | the lease, depth and limits around one invocation | invoke_with/5, leased_invoke/6, invoke_at/6 |
| call protocol | a wasm-to-wasm call through a link | call_nested/3 |
| call protocol | what a trap leaves in the store, and the call depth | settle/2, enter/0, leave/1 |
| gc roots | collection after a call, and its roots | maybe_collect/4, roots_of/1 |
| globals, exports and pins | reading a global, listing the exports | get_global/2, exports/1 |
| globals, exports and pins | keeping a reference alive outside the runtime | pin/2, release/2, release_all/1 |
| destroy | releasing an instance's claims | destroy/1, do_destroy/1, share_ir/1 |
| snapshots | capturing and restoring an image, and holding one | snapshot/1, snapshot/2, restore/3, acquire/1, release/1, snapshot_info/1 |
| snapshot files | images on disk | save_snapshot/2, load_snapshot/2 |
| compiled code ahead of time | a unit file built now and loaded at boot | precompile/2, preload/1, preload_app/1 |
| extern and export types | an export in the form another module imports | extern/2 |
| extern and export types | a function export's type, without instantiating | func_type_of/2, func_types_of/1 |
| host helpers | reading and writing linear memory from the host | read_memory/3, write_memory/3, memory_size/1 |
| errors | printing an error value | format_error/1 |
You get one execution path
Create an instance, call it, destroy it. That is the inline path and there is
no other. The library ships no process wrapper, because process architecture
belongs to your application; ets, counters and atomics do not impose one
either.
Build actors on this API rather than beside it. A worker is a process that
calls instantiate/3 in its init and call/3 in its handle_call. See
docs/worker.md and wasm_instance_worker, which is that worker, including
per-request isolation, timeouts, and killing runaway code.
You own the instance
An instance belongs to the process that created it and stays valid while that process lives, like a port or an ETS table. You may pass it to another process, but do not call the same instance from two processes at once: both read-modify-write the same mutable state and the last writer wins. Putting the instance inside a process is what serialises the calls.
Pages are released when the owner exits, however it exits, so forgetting
destroy/1 is untidy rather than a leak. Destroying an instance releases only
its claim on each memory: one it imported stays as long as anybody else holds
it, and destroying the same instance twice releases nothing the second time.
Every failure is a value
Nothing a guest supplies makes a call here raise, however hostile. A malformed
binary, an ill-typed module, a trap and a resource limit all come back as
{error, E}, where E carries the class (malformed, invalid, link,
trap, exhaustion), a machine-readable kind, the specification's message
text, and context to diagnose it. A wrong Erlang type in your own call, such
as an atom for the module bytes, raises as any Erlang function does;
wasm_error says how the promise is kept and where its exceptions are listed.
Summary
Types
An instance, owned by the process that created it.
A module: compiled inline, or a handle to a cached one.
An immutable image of an initialised instance. See wasm_snapshot.
Functions
Keep an image alive past the process that captured it.
Decode and validate a module without caching it.
Release an instance's memory pages and state.
Encode a module to the binary format.
Take an instance's export in the form another module can import it.
The type of a core function a module exports, read from the module bytes without instantiating it. Only the sections that type it are decoded: a module whose code is malformed still answers.
The type of every function a module exports, from one read of its bytes, without instantiating it. Only the type, import, function and export sections are decoded; the code is not, nor checked.
Instantiate, resolving imports and running the start function.
Decode, validate and cache a module, returning a handle.
Read a module file and load it.
Read an image back, for a module the caller names.
Keep a garbage-collected reference alive until you release it.
Compile a module's functions now, into the bytes of a unit file, so a node can load compiled code before its first call instead of compiling it in the background.
Load a unit file precompile/2 wrote, before the module's first call.
preload/1 for every module your application declares, as
{env, [{wasm_modules, [#{file => "priv/x.wasm"}, ...]}]} in its .app file.
Read a byte range from a host function's instance.
Drop this process's hold on an image. Always ok, and never blocks.
Release a reference, letting it be collected once nothing else holds it.
Release every pinned reference.
Build a fresh instance at a captured point.
Write an image to a file, so a later node need not run init() again.
Capture an initialised instance, so a later one can start where it left off.
As snapshot/1, with a version and a compatibility_key.
What an image holds: its size in bytes, its module and its version.
Drop your claim on a cached module.
Validate a module, as wasm:load/1 or wasm_decode:module/1 gives it.
Types
-type annotated() :: {Height :: non_neg_integer(), instr()} | {Height :: non_neg_integer(), Base :: non_neg_integer(), instr()}.
-nominal extern() :: {wasm_func, fun((term(), [term()]) -> {ok, [term()]}), term()} | {wasm_global, wasm_global:global(), #globaltype{valtype :: valtype(), mut :: mut()}} | {wasm_global_const, term(), #globaltype{valtype :: valtype(), mut :: mut()}} | {wasm_tag, reference(), term(), term()} | wasm_memory:mem() | wasm_table:table().
An export taken in the form another module imports it, as extern/2 hands it
back.
Named because an import map is built out of these, so anything describing one has to be able to spell the value. A function carries its type so a mismatched signature is a link error; a memory, table or mutable global is the handle itself, so the importer shares the thing rather than a copy of it.
-type externtype() :: {func, typeidx()} | {table, #tabletype{limits :: #limits{min :: non_neg_integer(), max :: undefined | non_neg_integer(), shared :: boolean(), index_type :: i32 | i64}, elemtype :: reftype(), init :: undefined | [instr()]}} | {mem, #memtype{limits :: #limits{min :: non_neg_integer(), max :: undefined | non_neg_integer(), shared :: boolean(), index_type :: i32 | i64}}} | {global, #globaltype{valtype :: valtype(), mut :: mut()}} | {tag, #tagtype{type :: typeidx()}}.
-type funcidx() :: non_neg_integer().
-type heaptype() :: func | extern | exn | any | eq | i31 | struct | array | nofunc | noextern | noexn | none | {type, typeidx()}.
-nominal instance() :: #inst{id :: reference(), ckpt :: reference(), entry_key :: undefined | reference(), types :: tuple(), funcs :: tuple(), exports :: #{binary() => {func | table | mem | global, non_neg_integer()}}, elems :: tuple(), datas :: tuple(), globaltypes :: tuple(), tags :: tuple(), canon :: tuple(), fields :: tuple(), kinds :: tuple(), supers :: tuple(), heap :: undefined | wasm_heap:heap(), identity :: undefined | {sha256, binary()} | reference(), module_handle :: undefined | wasm_module_cache:handle(), leases :: undefined | atomics:atomics_ref(), store :: term(), version :: term(), limits :: map(), ctx :: term(), shared_ir :: undefined | {wasm_ir_shared, binary(), term()}}.
An instance, owned by the process that created it.
-type memidx() :: non_neg_integer().
-nominal module_() :: #module{identity :: undefined | {sha256, binary()} | reference(), types :: [#subtype{final :: boolean(), supers :: [typeidx()], body :: #functype{params :: [valtype()], results :: [valtype()]} | #structtype{fields :: [#fieldtype{type :: valtype() | i8 | i16, mut :: mut()}]} | #arraytype{field :: #fieldtype{type :: valtype() | i8 | i16, mut :: mut()}}}], rec_groups :: [{non_neg_integer(), non_neg_integer()}], imports :: [#import{module :: binary(), name :: binary(), desc :: externtype()}], funcs :: [#func{type :: typeidx(), locals :: [valtype()], body :: [instr()] | {validated, [annotated()]}}], tables :: [#tabletype{limits :: #limits{min :: non_neg_integer(), max :: undefined | non_neg_integer(), shared :: boolean(), index_type :: i32 | i64}, elemtype :: reftype(), init :: undefined | [instr()]}], mems :: [#memtype{limits :: #limits{min :: non_neg_integer(), max :: undefined | non_neg_integer(), shared :: boolean(), index_type :: i32 | i64}}], tags :: [#tagtype{type :: typeidx()}], globals :: [#global{type :: #globaltype{valtype :: valtype(), mut :: mut()}, init :: [instr()]}], exports :: [#export{name :: binary(), desc :: {func | table | mem | global | tag, non_neg_integer()}}], start :: undefined | funcidx(), elems :: [#elem{type :: reftype(), init :: [[instr()]], mode :: passive | declarative | {active, tableidx(), [instr()]}}], datas :: [#data{init :: binary(), mode :: passive | {active, memidx(), [instr()]}}], data_count :: undefined | non_neg_integer(), customs :: [{binary(), binary()}]} | wasm_module_cache:handle().
A module: compiled inline, or a handle to a cached one.
-type mut() :: const | var.
-type numtype() :: i32 | i64 | f32 | f64.
-type reftype() :: {ref, null | nonull, heaptype()}.
-nominal snapshot() :: wasm_snapshot:snapshot().
An immutable image of an initialised instance. See wasm_snapshot.
What compile/1 and load/1 take: the binary format, or the text format.
-type tableidx() :: non_neg_integer().
-type typeidx() :: non_neg_integer().
-type vectype() :: v128.
Functions
-spec acquire(snapshot()) -> ok | {error, wasm_error:error()}.
Keep an image alive past the process that captured it.
A holder is dropped when its process dies, so "the capturing process exits and the image survives" is only true if another process acquired first. Do it in that order: the reverse is a race that would pass most of the time.
Not to be confused with release/2, which drops a pin on a garbage-collected
reference. Different subject, adjacent name; this pair is about images.
-spec call(instance(), binary(), [term()]) -> {ok, [term()]} | {error, wasm_error:error()}.
-spec compile(source()) -> {ok, module_()} | {error, wasm_error:error()}.
Decode and validate a module without caching it.
Takes the binary format, or {wat, Source} for the text format:
{ok, M} = wasm:compile({wat, ~"(module (func (export \"f\") (result i32) i32.const 7))"}).Use it for one-shot work. If you instantiate more than once, use load/1,
which takes text too. A module compiled from text here has no bytes, so it
takes a fresh identity every time and shares nothing; load/1 encodes the
text and names it by its bytes.
-spec compile(source(), map()) -> {ok, module_()} | {error, wasm_error:error()}.
As compile/1, with an identity for the module.
Pass one when you already know what names these bytes -- wasm_module_cache
passes the content hash it has just computed -- so that anything caching work
derived from the module shares it between two loads of the same bytes. Without
one the module gets a fresh reference, which is correct and simply does not
share. Nothing hashes on this path: five milliseconds on the 1.8 MB QuickJS
module is not worth paying to buy sharing the inline API does not promise.
-spec destroy(instance()) -> ok.
Release an instance's memory pages and state.
Idempotent, and optional: pages are released anyway when the owning process exits. Calling it returns them sooner, which matters when one process creates and discards many instances.
-spec encode(module_() | {wat, binary()}) -> {ok, binary()} | {error, wasm_error:error()}.
Encode a module to the binary format.
Takes a #module{}, as compile/1 or wasm_decode:module/1 gives it, a
handle from load/1, or {wat, Source}. Turn a text module into a .wasm
file:
{ok, Bin} = wasm:encode({wat, ~"(module (func (export \"f\") (result i32) i32.const 7))"}).The bytes are the same for the same module every time, and they are what
load/1 names the module by. The rules that make them so are in
wasm_encode. Encoding does not validate: an invalid module encodes, and
load/1 or validate/1 refuses it.
A module with no binary form, such as one built by hand with an index out of
range, is {error, #{kind := unencodable}}. Bytes larger than
max_module_bytes are {error, #{kind := module_too_large}}, as they would be
on the way in. A handle the node no longer holds is module_not_loaded.
-spec extern(instance(), binary()) -> {ok, extern()} | {error, wasm_error:error()}.
Take an instance's export in the form another module can import it.
Functions come back as host functions, so wasm-to-wasm linking reuses the same import mechanism as Erlang-implemented imports rather than needing a second path through the interpreter.
-spec format_error(wasm_error:error()) -> iolist().
The type of a core function a module exports, read from the module bytes without instantiating it. Only the sections that type it are decoded: a module whose code is malformed still answers.
For a static check that must run before any core start function does, e.g. the
Component Model verifying a canon lift's core function has the signature the
Canonical ABI derives from the declared component type. Returns the core
function's {Params, Results} value-type lists, or a named error if the module is
undecodable, the export is missing, or it is not a function export.
-spec func_types_of(binary()) -> {ok, #{binary() => {ok, {[valtype()], [valtype()]}} | {error, term()}}} | {error, term()}.
The type of every function a module exports, from one read of its bytes, without instantiating it. Only the type, import, function and export sections are decoded; the code is not, nor checked.
#{Name => {ok, {Params, Results}} | {error, Why}}, one entry per function
export: a caller checking several exports of one module, such as every
canon lift of a component naming the same core, decodes it once rather
than once per export. {error, {undecodable_core, _}} when the bytes do not
decode.
-spec get_global(instance(), binary()) -> {ok, [term()]} | {error, wasm_error:error()}.
-spec instantiate(module_(), map()) -> {ok, instance()} | {error, wasm_error:error()}.
-spec instantiate(module_(), map(), map()) -> {ok, instance()} | {error, wasm_error:error()}.
Instantiate, resolving imports and running the start function.
Opts is one flat map: the limits (fuel, max_depth, max_memory_pages,
max_host_calls, the keys wasm_limits lists) sit in it beside the other
options, such as link or compile. A limits => #{...} key is not read
here, so the limits inside it are not applied; that nested form is what
wasm_instance_worker and wasm_script_worker take. Pass
wasm_limits:untrusted() itself as Opts, or merge your options into it.
The limits default to permissive values, so a trusted embedder does not have to opt out of them. Set them yourself when the module is untrusted.
To link modules that exchange garbage-collected references, name the instance to share an object store with:
{ok, A} = wasm:instantiate(ModA, #{}),
{ok, T} = wasm:extern(A, ~"table"),
{ok, B} = wasm:instantiate(ModB, #{{~"env", ~"t"} => T}, #{link => A}).A reference is an id into a store, so an id from another store means nothing
here and reading one traps with foreign_reference. Link this way whenever two
modules pass structs or arrays between them, through a shared table, a shared
global or each other's exports. You do not need it for modules that exchange
only numbers, memories and functions.
You say it explicitly rather than having it inferred from Imports, because an
import is a bare handle that does not say which instance produced it: extern/2
hands out a table, a memory or a cell, none of which names its origin. Inferring
it would work for some import kinds and not others, which is worse than one rule
that always holds.
The instance you get back is scoped to your process. Its mutable state lives
in an ETS table this process owns, so the handle stops working when this process
exits, like a port or an ETS table would. Passing the handle to another process
works while the creator is alive. To give an instance a lifetime of its own, put
a process in charge of it; see docs/worker.md.
Decode, validate and cache a module, returning a handle.
Use this rather than compile/1. Compiling is the expensive step, roughly 20 ms
for a 100 KB Rust binary against 15 us to instantiate one, and loading the same
bytes twice hands you the cached artefact instead of repeating the work.
Takes the binary format, or {wat, Source} for the text format. Text is
encoded first, as encode/1 does, and the bytes are loaded: a module loaded
from text and the same module loaded from its .wasm share one cache entry
and one handle, named by the SHA-256 of those bytes.
-spec load_file(file:filename_all()) -> {ok, module_()} | {error, term()}.
Read a module file and load it.
A path ending in .wat is the text format, loaded as {wat, Source} is by
load/1: encoded first, so it gets the same handle as its .wasm. Any other
path is the binary format. The extension decides, not the contents, so a
damaged .wasm is still reported as one.
-spec load_snapshot(file:filename_all(), module_()) -> {ok, snapshot()} | {error, wasm_error:error()}.
Read an image back, for a module the caller names.
{ok, Handle} = wasm:load(Bytes),
{ok, Image} = wasm:load_snapshot("/var/cache/wasm/py.img", Handle).The module is an argument rather than something the file chooses, which is the
opposite of restore/3 and is the same protection from the other side: on the live
path taking the module from the image is what closes the forgery, and off disk
a file that picked its own module would open it again. An image whose recorded
hash is not this handle's is refused.
Everything else a file could lie about is bounded by the module too: the decompressed size is checked against what its memories may hold before a byte is allocated.
-spec memory_size(instance() | map()) -> {ok, non_neg_integer()} | {error, term()}.
Keep a garbage-collected reference alive until you release it.
References that leave the runtime are pinned for you: call results,
get_global/2 results, and the values carried by an uncaught exception. The
runtime cannot see what you are holding, so without a pin the next collection
frees it.
Pin by hand in one case: your host function keeps a reference it was passed. Its arguments are safe for the duration of the call, because collection does not run below a live frame, and not afterwards.
Fun = fun(_Ctx, [Ref]) ->
ok = wasm:pin(Inst, Ref), % keeping it past this call
ets:insert(mine, {last, Ref}),
{ok, []}
end.Reference counted, so a reference pinned twice needs releasing twice.
-spec precompile(module_(), #{functions => all | [non_neg_integer()], quality => full | baseline}) -> {ok, binary(), #{compiled := non_neg_integer(), left_out := non_neg_integer()}} | {error, wasm_error:error()}.
Compile a module's functions now, into the bytes of a unit file, so a node can load compiled code before its first call instead of compiling it in the background.
Write the bytes to a file you ship in your release and give it to preload/1
at boot. Takes a handle from load/1, because the file names the module by its
content hash. Opts:
functions:all, the default, or a list of function indexes, at most 4,096. A list is what a large guest needs;wasm_jit:compiled_functions/1andwasm_jit:executed/1give one.quality:full, the default, orbaseline.
A function the compiler refuses is left out, and Info says how many:
#{compiled := N, left_out := M}.
-spec preload(file:filename_all()) -> ok | {miss, atom()}.
Load a unit file precompile/2 wrote, before the module's first call.
Call it from your application's start/2 or your top supervisor's init/1:
the calling process holds the compiled code while it lives. An instance of the
module then runs compiled code from its first call when the tier is on for it
(compile => true), including a call that never returns. A miss is never an
error: the module interprets and the tier compiles it as it would have.
| answer | when |
|---|---|
ok | loaded, or already loaded |
{miss, not_started} | the wasm application is not running |
{miss, not_read} | the file could not be read |
{miss, corrupt} | the file is damaged, or larger than any unit |
{miss, format} | a unit-file format this runtime does not know |
{miss, abi}, {miss, otp_release}, {miss, emulator}, {miss, architecture} | built for another runtime |
{miss, loading} | the tier is compiling this module now |
{miss, slot_busy} | another module holds the slot it was built for |
{miss, load_failed} | the code server refused it |
Loading holds up other module loads on the node for as long as it takes, up to a few seconds for a large guest, so call it before taking traffic.
preload/1 for every module your application declares, as
{env, [{wasm_modules, [#{file => "priv/x.wasm"}, ...]}]} in its .app file.
Each unit file is the module's file with .unit added, in your application's
directory, where scripts/wasm-units.escript writes it at build time.
-spec read_memory(instance() | map(), non_neg_integer(), non_neg_integer()) -> {ok, binary()} | {error, wasm_error:error()}.
Read a byte range from a host function's instance.
Accepts either an instance or the context map a host function receives, so imports can be written without unpacking anything.
-spec release(snapshot()) -> ok.
Drop this process's hold on an image. Always ok, and never blocks.
Release a reference, letting it be collected once nothing else holds it.
Releasing something that was never pinned is not an error, so you can release everything you have seen without tracking which ones counted.
-spec release_all(instance()) -> ok.
Release every pinned reference.
Use this when you scope references to a request: run the request, take what you need out of the results, then drop the lot. Without it, pins accumulate for the life of the instance.
-spec restore(snapshot(), map(), map()) -> {ok, instance()} | {error, wasm_error:error()}.
Build a fresh instance at a captured point.
restore/3, not an option to instantiate/3, and the difference is a
security property rather than a spelling: the module comes from the image
rather than from the caller, so there is no module argument left to forge.
The imports are reconstructed, never restored. You build the WASI config and every host binding for this request; the image carries only guest-visible state.
It does not run the module's start function. Ordinary instantiation always does, and repeating arbitrary guest code against fresh imports would redo work the image already contains.
profile in Opts expands exactly as it does for instantiate/3.
-spec save_snapshot(snapshot(), file:filename_all()) -> ok | {error, wasm_error:error()}.
Write an image to a file, so a later node need not run init() again.
ok = wasm:save_snapshot(Image, "/var/cache/wasm/py.img").Written to a temporary name and renamed, so a reader never sees a half-written
file. That is BEAM-crash durability and not host-crash durability: there is no
fsync, and a machine that loses power mid-write leaves no file, which is a
miss.
The directory is as trusted as your release. The same words
wasm_code_cache uses, and here they carry more weight: an image is not code
but guest state laid into a live runtime, so anyone who can write the file can
choose what a restored instance believes. Every field is validated on the way
back in and a table slot may name only a function the module has, but that is
containment rather than authentication.
-spec snapshot(instance()) -> {ok, snapshot()} | {error, wasm_error:error()}.
Capture an initialised instance, so a later one can start where it left off.
{ok, M} = wasm:load(Bytes),
{ok, Init} = wasm:instantiate(M, Imports, #{}),
{ok, _} = wasm:call(Init, ~"init", []),
{ok, Image} = wasm:snapshot(Init),
ok = wasm:destroy(Init),
{ok, Fresh} = wasm:restore(Image, FreshImports, #{}),
{ok, _} = wasm:call(Fresh, ~"handle", []).The instance must have been built through load/1, must import no memory,
table or global, must have no shared memory and no live objects, and must hold
no reference to another instance. wasm_snapshot says why each of those is a
refusal rather than a special case.
An image is an in-memory optimisation and not durable state. It is a term: it lives as long as something holds it and it does not survive the node.
-spec snapshot(instance(), map()) -> {ok, snapshot()} | {error, wasm_error:error()}.
As snapshot/1, with a version and a compatibility_key.
What an image holds: its size in bytes, its module and its version.
-spec unload(module_()) -> ok.
Drop your claim on a cached module.
The module stays resident until every holder has released it, so you can call this safely even when another part of the system loaded the same bytes.
-spec validate(module_()) -> {ok, module_()} | {error, wasm_error:error()}.
Validate a module, as wasm:load/1 or wasm_decode:module/1 gives it.
A decoded module answers {ok, Module} when it is valid. A handle from
wasm:load/1 names the cache's copy, which is validated and answered as
{ok, Handle}; a handle the node no longer holds answers
module_not_loaded, as instantiate/3 does. Otherwise {error, Why}, the
reason the module is invalid.
-spec write_memory(instance() | map(), non_neg_integer(), binary()) -> ok | {error, wasm_error:error()}.