wasm_encode (wasm v0.16.0)
View SourceWebAssembly binary format encoder: a #module{} back to bytes.
Read this when you need a module's bytes, or when you change what bytes a
module gives. It is the decoder run backwards: wasm_decode reads the binary
format into the #module{} in include/wasm.hrl, and this writes that record
out again. wasm:encode/1 is the supported way to call it.
One encoding per module
The bytes are an identity. wasm:load/1 names a module by the SHA-256 of
its bytes, and an embedder may store a module under that digest. So the same
#module{} always gives the same bytes, and the rules below are fixed. A
change to any of them changes the digest of modules that are already stored,
which is a breaking change: it needs a changelog entry and an Upgrading note.
wasm_encode_SUITE holds golden vectors that fail when the output moves.
Where the binary format has more than one encoding for the same thing, this writes the one that decodes back to the same record:
- Sections in the specification's order: type, import, function, table, memory, tag, global, export, start, element, data count, code, data. A section with nothing in it is left out.
- Custom sections after the last known section, in the record's order. The decoder does not keep where a custom section stood among the others, so its position cannot be given back.
- LEB128 in its shortest form everywhere.
- Data count written exactly when
data_countis set. - Types: a recursive group of one type is written as that type alone,
since the decoder reads both the same; any other group, the empty one
included, as
rec. A final type with no supertypes is written bare, one with supertypes withsub final, and a non-final type withsub. Type indices, groups and the order of every index space are kept as the record holds them, never renumbered or merged. - Reference types: a nullable abstract type in its one-byte short form
(
funcrefis0x70), a nullable type index as0x63, a non-nullable type as0x64. - Limits: the flags byte has a bit for a maximum, for
sharedand for a 64-bit index, and nothing else. - Tables: the plain form when the table has no initialiser, the
0x40 0x00form when it has one. - Element segments: a segment of type
(ref func)whose every element is a singleref.funcis written with function indices, in the form for its mode (0for table 0,2for another table,1passive,3declarative). Every other segment is written with expressions: form4for afuncrefsegment on table 0, otherwise form6(active, with its table and type),5passive or7declarative. The decoder reads the index forms as(ref func)and form4asfuncref, which is why the type decides. - Data segments: form
0for memory 0, form2for another memory, form1passive. - Locals in runs of equal consecutive types, each run as long as it goes.
- Instructions: see
wasm_encode_code. A memory argument names its memory only when it is not memory 0, and anifwriteselseonly when the else branch has instructions.
A module built from WAT keeps no name section: its identifiers are not
written, so its bytes do not depend on what its author called things.
What cannot be encoded
A record that has no binary form is an error value, {error, #{class => invalid, kind => unencodable}}, with the field and the value in its context:
an index or a constant out of the range of its encoding, a name that is not
UTF-8, rec groups that do not cover the types, an instruction this runtime
does not know. So is a record whose bytes the decoder would refuse: a data
count that does not match the data segments, or memory.init or data.drop
in a module without a data count. A record whose fields do not even have
the types include/wasm.hrl gives them is an error value too, an internal
one, since there is nothing to say about it but where it stopped. Nothing
raises.
Where things are
| you want | look at |
|---|---|
| the entry point and the section order | module/1, sections/1 |
| types and recursive groups | %%% types |
| element and data segments | %%% segments |
| function bodies and locals | code/1 |
| the integer encodings and their range checks | %%% integers |
| instructions | wasm_encode_code, and wasm_encode_simd, wasm_encode_gc, wasm_encode_atomic for the prefixed spaces |
Summary
Functions
One raw byte, such as a SIMD lane index.
Encode a module. Takes a body as decoded or as validated: the validator's annotations are stripped first.
Encode, letting the internal throw escape. For use inside a capture.
A length-prefixed UTF-8 name, refused if it is not UTF-8.
A signed 32-bit LEB128.
A signed 33-bit LEB128: a type index where a block or heap type is expected.
A signed 64-bit LEB128.
An unsigned 32-bit LEB128.
An unsigned 64-bit LEB128, for limits and memory offsets.
Raise the encoder's error for a field whose value has no binary form.
wasm_encode_code and the prefixed-space encoders use it too.
A value type. A reference type takes the shortest form that reads back the same.
A vector: its length, then each element as Fun writes it.
Types
-type annotated() :: {Height :: non_neg_integer(), instr()} | {Height :: non_neg_integer(), Base :: non_neg_integer(), instr()}.
-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()}.
-type memidx() :: non_neg_integer().
-type mut() :: const | var.
-type numtype() :: i32 | i64 | f32 | f64.
-type reftype() :: {ref, null | nonull, heaptype()}.
-type tableidx() :: non_neg_integer().
-type typeidx() :: non_neg_integer().
-type vectype() :: v128.
Functions
One raw byte, such as a SIMD lane index.
-spec limits(#limits{min :: non_neg_integer(), max :: undefined | non_neg_integer(), shared :: boolean(), index_type :: i32 | i64}) -> iodata().
-spec 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()}]}) -> {ok, binary()} | {error, wasm_error:error()}.
Encode a module. Takes a body as decoded or as validated: the validator's annotations are stripped first.
-spec module_unchecked(#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()}]}) -> binary().
Encode, letting the internal throw escape. For use inside a capture.
A length-prefixed UTF-8 name, refused if it is not UTF-8.
A signed 32-bit LEB128.
A signed 33-bit LEB128: a type index where a block or heap type is expected.
A signed 64-bit LEB128.
-spec u32(non_neg_integer()) -> iodata() | byte().
An unsigned 32-bit LEB128.
-spec u64(non_neg_integer()) -> iodata() | byte().
An unsigned 64-bit LEB128, for limits and memory offsets.
Raise the encoder's error for a field whose value has no binary form.
wasm_encode_code and the prefixed-space encoders use it too.
A value type. A reference type takes the shortest form that reads back the same.
A vector: its length, then each element as Fun writes it.