wasm_encode (wasm v0.16.0)

View Source

WebAssembly 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_count is 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 with sub final, and a non-final type with sub. 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 (funcref is 0x70), a nullable type index as 0x63, a non-nullable type as 0x64.
  • Limits: the flags byte has a bit for a maximum, for shared and for a 64-bit index, and nothing else.
  • Tables: the plain form when the table has no initialiser, the 0x40 0x00 form when it has one.
  • Element segments: a segment of type (ref func) whose every element is a single ref.func is written with function indices, in the form for its mode (0 for table 0, 2 for another table, 1 passive, 3 declarative). Every other segment is written with expressions: form 4 for a funcref segment on table 0, otherwise form 6 (active, with its table and type), 5 passive or 7 declarative. The decoder reads the index forms as (ref func) and form 4 as funcref, which is why the type decides.
  • Data segments: form 0 for memory 0, form 2 for another memory, form 1 passive.
  • 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 an if writes else only 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 wantlook at
the entry point and the section ordermodule/1, sections/1
types and recursive groups%%% types
element and data segments%%% segments
function bodies and localscode/1
the integer encodings and their range checks%%% integers
instructionswasm_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

annotated()

-type annotated() ::
          {Height :: non_neg_integer(), instr()} |
          {Height :: non_neg_integer(), Base :: non_neg_integer(), instr()}.

externtype()

-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()}}.

funcidx()

-type funcidx() :: non_neg_integer().

heaptype()

-type heaptype() ::
          func | extern | exn | any | eq | i31 | struct | array | nofunc | noextern | noexn | none |
          {type, typeidx()}.

instr()

-type instr() :: atom() | tuple().

memidx()

-type memidx() :: non_neg_integer().

mut()

-type mut() :: const | var.

numtype()

-type numtype() :: i32 | i64 | f32 | f64.

reftype()

-type reftype() :: {ref, null | nonull, heaptype()}.

tableidx()

-type tableidx() :: non_neg_integer().

typeidx()

-type typeidx() :: non_neg_integer().

valtype()

-type valtype() :: numtype() | vectype() | reftype().

vectype()

-type vectype() :: v128.

Functions

byte/1

-spec byte(byte()) -> byte().

One raw byte, such as a SIMD lane index.

heaptype/1

-spec heaptype(heaptype()) -> iodata() | byte().

limits/1

-spec limits(#limits{min :: non_neg_integer(),
                     max :: undefined | non_neg_integer(),
                     shared :: boolean(),
                     index_type :: i32 | i64}) ->
                iodata().

module(M)

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

module_unchecked/1

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

name/1

-spec name(binary()) -> iodata().

A length-prefixed UTF-8 name, refused if it is not UTF-8.

reftype/1

-spec reftype(reftype()) -> iodata() | byte().

s32/1

-spec s32(integer()) -> iodata() | byte().

A signed 32-bit LEB128.

s33/1

-spec s33(integer()) -> iodata() | byte().

A signed 33-bit LEB128: a type index where a block or heap type is expected.

s64/1

-spec s64(integer()) -> iodata() | byte().

A signed 64-bit LEB128.

u32/1

-spec u32(non_neg_integer()) -> iodata() | byte().

An unsigned 32-bit LEB128.

u64/1

-spec u64(non_neg_integer()) -> iodata() | byte().

An unsigned 64-bit LEB128, for limits and memory offsets.

unencodable(What, Value)

-spec unencodable(atom(), term()) -> no_return().

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.

valtype/1

-spec valtype(valtype()) -> iodata() | byte().

A value type. A reference type takes the shortest form that reads back the same.

vec/2

-spec vec(list(), fun((term()) -> iodata() | byte())) -> iodata().

A vector: its length, then each element as Fun writes it.