TExcelTAD
Home › WebAssembly › LEB128 & Instruction Encoding

LEB128 & Instruction Encoding

Wasm binaries are small partly because integers are stored in LEB128 ("Little Endian Base 128"): a variable-length encoding where small numbers take one byte and large numbers take more. Every count, size, index and integer constant in a module uses it.

Unsigned LEB128

Split the number into groups of 7 bits, lowest group first. Each group becomes a byte; the high bit (0x80) is set on every byte except the last, meaning "more bytes follow".

text
624485 = 0b 100110 0001110 1100101
groups (low first): 1100101  0001110  0100110
bytes:              0xE5     0x8E     0x26        (0x80 added to all but the last)
js · try it yourself
function encodeU(n) {
  const out = [];
  do {
    let byte = n & 0x7f;
    n >>>= 7;
    if (n !== 0) byte |= 0x80;      // more to come
    out.push(byte);
  } while (n !== 0);
  return out;
}

function decodeU(bytes) {
  let result = 0, shift = 0;
  for (const byte of bytes) {
    result |= (byte & 0x7f) << shift;
    shift += 7;
    if ((byte & 0x80) === 0) break;
  }
  return result >>> 0;
}

const hex = (arr) => arr.map((b) => b.toString(16).padStart(2, '0')).join(' ');
for (const n of [0, 5, 127, 128, 300, 624485, 4294967295]) {
  const enc = encodeU(n);
  console.log(String(n).padStart(10), '->', hex(enc).padEnd(15), '->', decodeU(enc));
}
         0 -> 00              -> 0
         5 -> 05              -> 5
       127 -> 7f              -> 127
       128 -> 80 01           -> 128
       300 -> ac 02           -> 300
    624485 -> e5 8e 26        -> 624485
4294967295 -> ff ff ff ff 0f  -> 4294967295

127 still fits in one byte, 128 needs two. A 32-bit value never needs more than 5 bytes.

Signed LEB128

Constants such as i32.const -1 use the signed variant: the same 7-bit groups of the two's-complement value, and the encoder stops when the remaining bits are all copies of the sign bit, and bit 6 of the last byte already has that sign.

js · try it yourself
function encodeS(n) {
  const out = [];
  while (true) {
    const byte = n & 0x7f;
    n >>= 7;                                     // arithmetic shift keeps the sign
    const signBitSet = (byte & 0x40) !== 0;
    if ((n === 0 && !signBitSet) || (n === -1 && signBitSet)) {
      out.push(byte);
      return out;
    }
    out.push(byte | 0x80);
  }
}

function decodeS(bytes) {
  let result = 0, shift = 0, byte;
  let i = 0;
  do {
    byte = bytes[i++];
    result |= (byte & 0x7f) << shift;
    shift += 7;
  } while (byte & 0x80);
  if (shift < 32 && (byte & 0x40)) result |= -1 << shift;   // sign-extend
  return result;
}

const hex = (arr) => arr.map((b) => b.toString(16).padStart(2, '0')).join(' ');
for (const n of [0, 1, -1, 63, 64, -64, -65, 42, -123456]) {
  const enc = encodeS(n);
  console.log(String(n).padStart(8), '->', hex(enc).padEnd(9), '->', decodeS(enc));
}
       0 -> 00        -> 0
       1 -> 01        -> 1
      -1 -> 7f        -> -1
      63 -> 3f        -> 63
      64 -> c0 00     -> 64
     -64 -> 40        -> -64
     -65 -> bf 7f     -> -65
      42 -> 2a        -> 42
 -123456 -> c0 bb 78  -> -123456

Notice that 64 needs two bytes in signed form (its bit 6 would otherwise look like a minus sign), while -64 fits in one.

How instructions are encoded

Each instruction is an opcode byte followed by its immediates:

Instruction Bytes
unreachable / nop 00 / 01
block / loop / if blocktype 02 / 03 / 04, then 40 (no result) or a value type
else / end 05 / 0b
br l / br_if l 0c l / 0d l
return / call f 0f / 10 f
local.get i / local.set i / local.tee i 20 i / 21 i / 22 i
global.get i / global.set i 23 i / 24 i
i32.load align offset / i32.store … 28 a o / 36 a o (align as a power of two: 2 = 4 bytes)
i32.const n / i64.const n 41 n / 42 n (signed LEB128)
f64.const x 44 + 8 bytes IEEE 754 little-endian
i32.eqz i32.eq i32.lt_s 45 46 48
i32.add i32.sub i32.mul 6a 6b 6c
SIMD, bulk memory, … a prefix byte (fd, fc) and a LEB128 sub-opcode

Assembling a module by hand

With LEB128 and the opcode table you can generate a module without any toolchain. This builds (func (export "f") (param i32) (result i32) local.get 0 i32.const 300 i32.mul i32.const -1 i32.add), that is f(x) = x * 300 - 1, from scratch:

js · try it yourself
const u = (n) => { const o = []; do { let b = n & 0x7f; n >>>= 7; if (n) b |= 0x80; o.push(b); } while (n); return o; };
const s = (n) => { const o = []; for (;;) { const b = n & 0x7f; n >>= 7;
  if ((n === 0 && !(b & 0x40)) || (n === -1 && (b & 0x40))) { o.push(b); return o; } o.push(b | 0x80); } };
const vec = (items) => [...u(items.length), ...items.flat()];
const section = (id, content) => [id, ...u(content.length), ...content];
const str = (text) => vec([...new TextEncoder().encode(text)]);

const I32 = 0x7f;
const body = [
  0x00,                    // no extra locals
  0x20, ...u(0),           // local.get 0
  0x41, ...s(300),         // i32.const 300  (signed LEB128: ac 02)
  0x6c,                    // i32.mul
  0x41, ...s(-1),          // i32.const -1   (7f)
  0x6a,                    // i32.add
  0x0b,                    // end
];

const bytes = new Uint8Array([
  0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
  ...section(1, vec([[0x60, ...vec([I32]), ...vec([I32])]])),     // type 0: (i32) -> i32
  ...section(3, vec([u(0)])),                                     // function 0 has type 0
  ...section(7, vec([[...str('f'), 0x00, ...u(0)]])),             // export "f" = func 0
  ...section(10, vec([[...u(body.length), ...body]])),            // the body
]);

console.log([...bytes].map((b) => b.toString(16).padStart(2, '0')).join(' '));
const { instance } = await WebAssembly.instantiate(bytes);
console.log(instance.exports.f(1), instance.exports.f(10), instance.exports.f(-2));
00 61 73 6d 01 00 00 00 01 06 01 60 01 7f 01 7f 03 02 01 00 07 05 01 01 66 00 00 0a 0d 01 0b 00 20 00 41 ac 02 6c 41 7f 6a 0b
299 2999 -601

This is, in miniature, exactly what a compiler backend does: emit opcodes and LEB128 immediates, then wrap them in sections with their sizes.

Tip: Because sizes are LEB128, a backend often doesn't know how many bytes a section's size field needs until it has written the section. Some tools write sizes as padded 5-byte LEB128 (0x80 0x80 0x80 0x80 0x00 = 0) and patch them later; that is valid but wastes bytes, and wasm-opt removes the padding.

Test yourself

How is the number 300 encoded in unsigned LEB128?

  1. 2c 01
  2. ac 02
  3. 01 2c
  4. ff 2c

What does the high bit (0x80) of a LEB128 byte mean?

  1. The number is negative
  2. More bytes follow
  3. The byte is padding
  4. It is an opcode

Why does i32.const 64 take two bytes of immediate but i32.const -64 only one?

  1. Positive numbers are always longer
  2. In signed LEB128, bit 6 of the last byte is the sign; 64 has bit 6 set, so it needs another byte to show it's positive
  3. It's a wabt optimisation
  4. -64 is stored as an unsigned number