TExcelTAD
Home › WebAssembly › The Binary Format

The Binary Format

Engines never see the text format: they load .wasm binaries. The format is simple enough to read by hand, and knowing it helps you debug toolchains, understand file sizes, and write tools. In this lesson we'll take apart a real module with a few lines of JavaScript.

The header

Every module starts with 8 bytes:

text
00 61 73 6d     magic number: "\0asm"
01 00 00 00     version 1 (a little-endian u32)

Sections

After the header comes a sequence of sections. Each one is:

text
section id (1 byte) | content size (LEB128 unsigned) | content bytes

The size field lets a decoder skip sections it doesn't care about. Sizes and counts are written in LEB128, a variable-length integer encoding explained in the next lesson; for now it's enough to know that numbers below 128 take a single byte.

Id Section Contents
0 custom name + arbitrary bytes (debug names, DWARF, producers info)
1 type function signatures
2 import module name, field name, kind, type
3 function the type index of each function defined in the module
4 table table types
5 memory memory limits
6 global global types and initializers
7 export name, kind, index
8 start the start function index
9 element element segments for tables
10 code locals and bodies of the functions
11 data data segments
12 data count number of data segments (helps single-pass validation)
13 tag exception tags

Non-custom sections appear at most once, in a fixed order. Function signatures (section 3) and function bodies (section 10) are split so an engine can start compiling bodies in parallel as soon as they arrive.

Encodings you'll see everywhere

Bytes Meaning
0x7f 0x7e 0x7d 0x7c value types i32 i64 f32 f64
0x7b 0x70 0x6f v128, funcref, externref
0x60 "a function type follows"
0x00 0x01 0x02 0x03 0x04 import/export kinds: function, table, memory, global, tag
n then n bytes a name (UTF-8), or any vector: a count followed by the items

Walking the sections

This module exports add(a, b). The JavaScript below reads the header, walks every section and prints its id, name and size:

js · try it yourself
const bytes = new Uint8Array([
  0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
  0x01, 0x07, 0x01, 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f,
  0x03, 0x02, 0x01, 0x00,
  0x07, 0x07, 0x01, 0x03, 0x61, 0x64, 0x64, 0x00, 0x00,
  0x0a, 0x09, 0x01, 0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b,
]);

const NAMES = ['custom', 'type', 'import', 'function', 'table', 'memory', 'global',
               'export', 'start', 'element', 'code', 'data', 'data count', 'tag'];

// read an unsigned LEB128 number starting at pos; returns [value, nextPos]
function readU32(buf, pos) {
  let result = 0, shift = 0, byte;
  do {
    byte = buf[pos++];
    result |= (byte & 0x7f) << shift;
    shift += 7;
  } while (byte & 0x80);
  return [result >>> 0, pos];
}

const magic = String.fromCharCode(...bytes.slice(1, 4));
const version = new DataView(bytes.buffer).getUint32(4, true);
console.log(`magic: \\0${magic}, version ${version}, total ${bytes.length} bytes`);

let pos = 8;
while (pos < bytes.length) {
  const id = bytes[pos];
  const [size, start] = readU32(bytes, pos + 1);
  console.log(`section ${String(id).padStart(2)} ${NAMES[id].padEnd(9)} ${size} bytes at offset ${start}`);
  pos = start + size;
}
magic: \0asm, version 1, total 41 bytes
section  1 type      7 bytes at offset 10
section  3 function  2 bytes at offset 19
section  7 export    7 bytes at offset 23
section 10 code      9 bytes at offset 32

Decoding the type and export sections

Let's decode two sections fully. A type section is a vector of function types: 0x60, a vector of parameter types, a vector of result types. An export section is a vector of (name, kind, index):

js · try it yourself
const bytes = new Uint8Array([
  0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
  0x01, 0x07, 0x01, 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f,
  0x03, 0x02, 0x01, 0x00,
  0x07, 0x07, 0x01, 0x03, 0x61, 0x64, 0x64, 0x00, 0x00,
  0x0a, 0x09, 0x01, 0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b,
]);
const TYPES = { 0x7f: 'i32', 0x7e: 'i64', 0x7d: 'f32', 0x7c: 'f64' };
const KINDS = ['func', 'table', 'memory', 'global', 'tag'];

let pos = 8;
const byte = () => bytes[pos++];          // all numbers in this module are < 128: one byte each
const vec = (readItem) => Array.from({ length: byte() }, readItem);
const name = () => {
  const length = byte();
  const text = new TextDecoder().decode(bytes.slice(pos, pos + length));
  pos += length;
  return text;
};

while (pos < bytes.length) {
  const id = byte();
  const size = byte();
  const end = pos + size;
  if (id === 1) {
    const types = vec(() => {
      if (byte() !== 0x60) throw new Error('expected a function type');
      const params = vec(() => TYPES[byte()]);
      const results = vec(() => TYPES[byte()]);
      return `(${params.join(', ')}) -> (${results.join(', ')})`;
    });
    console.log('types:', types);
  } else if (id === 7) {
    const exports = vec(() => ({ name: name(), kind: KINDS[byte()], index: byte() }));
    console.log('exports:', exports);
  } else if (id === 10) {
    const body = bytes.slice(pos + 2, end);      // skip count and body size
    console.log('code bytes:', [...body].map((b) => b.toString(16).padStart(2, '0')).join(' '));
  }
  pos = end;
}
types: [ '(i32, i32) -> (i32)' ]
exports: [ { name: 'add', kind: 'func', index: 0 } ]
code bytes: 00 20 00 20 01 6a 0b

The code body 00 20 00 20 01 6a 0b reads: 0 local declarations, local.get 0, local.get 1, i32.add, end. Every function body ends with 0x0b.

Validation in action

The engine checks everything. Change one byte, say the i32.add opcode 0x6a to 0x7c (i64.add), and the module no longer validates, because the operands are i32s:

js · try it yourself
const good = new Uint8Array([
  0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
  0x01, 0x07, 0x01, 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f,
  0x03, 0x02, 0x01, 0x00,
  0x07, 0x07, 0x01, 0x03, 0x61, 0x64, 0x64, 0x00, 0x00,
  0x0a, 0x09, 0x01, 0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b,
]);
const bad = good.slice();
bad[39] = 0x7c;                                   // i32.add -> i64.add
const notWasm = new Uint8Array([0x7f, 0x45, 0x4c, 0x46, 1, 0, 0, 0]);   // an ELF header

console.log(WebAssembly.validate(good), WebAssembly.validate(bad), WebAssembly.validate(notWasm));
try {
  new WebAssembly.Module(bad);
} catch (err) {
  console.log(err.constructor.name);
}
true false false
CompileError

WebAssembly.validate returns a boolean; compiling an invalid module throws WebAssembly.CompileError, with a message that names the byte offset (the exact wording differs between engines).

Custom sections

Section id 0 holds named, uninterpreted data. Engines ignore it, tools use it: the name section stores function and local names for stack traces, producers records which compiler made the file, and DWARF debug info lives in .debug_* sections. Strip them for production (wasm-strip, wasm-opt --strip-debug) to save bytes. JavaScript can read them with WebAssembly.Module.customSections(module, 'name').

Test yourself

What are the first four bytes of every Wasm module?

  1. 7f 45 4c 46
  2. 00 61 73 6d ("\0asm")
  3. ca fe ba be
  4. 01 00 00 00

Why are function signatures (section 3) separate from function bodies (section 10)?

  1. Historical accident
  2. So the engine knows all signatures before the bodies arrive and can compile bodies in parallel while streaming
  3. To make files bigger
  4. Because bodies are optional

Which byte stands for the value type i32?

  1. 0x60
  2. 0x7f
  3. 0x6a
  4. 0x0b