Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 38 ยท Getting Started

Your First Wasm Module

Build and run a real WebAssembly module from scratch. Learn the type, function, export and code sections, plus a tiny JavaScript byte builder used in this course.

Most people meet WebAssembly through a compiler and never see a single byte. We will do the opposite on purpose. In this lesson you build a module that adds two numbers, byte by byte, and then you write a tiny helper so that building bigger modules is easy. Seeing the real structure makes every later topic (memory, tables, imports) much simpler, because you know what the compiler is producing for you.

Everything here runs in plain JavaScript. There is no compiler to install.

The shape of a module

A module is the 8-byte header followed by sections. Each section is id, size in bytes, then its content. The ones we need now:

Id Section What it holds
1 Type Function signatures, like (i32, i32) -> i32
3 Function For each function, the index of its signature
7 Export Names visible to the host, and what they point at
10 Code The bodies of the functions

Numbers such as sizes and counts use LEB128, a variable-length encoding: values below 128 take one byte, so for small modules you can write them as plain numbers.

Strings are a length followed by UTF-8 bytes. Lists (called vectors) are a count followed by the items.

Add, by hand

The function we want, written in the text format you will learn in chapter 3:

WAT
(func (param i32 i32) (result i32)
  local.get 0
  local.get 1
  i32.add)

Read it as a stack machine: push parameter 0, push parameter 1, then i32.add pops both and pushes their sum. The result left on the stack is returned. Here is the complete binary with every section labelled.

Node.js add() written as raw bytes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the last two lines. The sum of the largest 32-bit integer and one wraps around to the smallest, because the arithmetic is genuinely 32-bit. And an exported function is a JavaScript function whose name is its function index (here 0), not the export name.

A small byte builder

Counting section sizes by hand is error-prone. Here is a ten-line helper that does the arithmetic for you. The rest of the course reuses it, so read it once and it will look familiar.

JavaScript
const leb = n => { const o = []; do { let b = n & 127; n >>>= 7; if (n) b |= 128; o.push(b); } while (n); return o; };
const vec = a => [...leb(a.length), ...a.flat()];            // count + items
const str = s => vec([...new TextEncoder().encode(s)]);      // length + UTF-8
const sec = (id, items) => { const b = vec(items); return [id, ...leb(b.length), ...b]; };
const mod = (...s) => new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, ...s.flat()]);
const fn = (params, results) => [0x60, ...vec(params), ...vec(results)];
const body = (locals, code) => { const b = [...vec(locals), ...code, 0x0b]; return [...leb(b.length), ...b]; };
const I32 = 0x7f, I64 = 0x7e, F32 = 0x7d, F64 = 0x7c;
  • leb encodes an unsigned integer in LEB128.
  • vec writes a count then the items, so sec(1, [fn(...)]) is a whole type section.
  • str writes a name.
  • fn builds a function type and body builds one function body, adding the closing end byte (0x0b) and the byte length.

Now we can describe four functions in a few lines. Opcodes are written as numbers with a comment, since in Wasm every instruction is one byte (some take immediate operands after it).

Node.js Four functions with the byte builder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The select instruction takes three values from the stack: two candidates and a condition. It keeps the first candidate when the condition is not zero. That is how max works without a branch; chapter 3 covers real control flow.

What the engine sees

flowchart LR
    T["Type section: signatures"] --> F["Function section: which signature each function has"]
    F --> C["Code section: one body per function"]
    F --> E["Export section: names pointing at function indexes"]

The function section and code section are parallel lists: entry 0 of each describes function 0. Function indexes also count imported functions first, which matters in the imports lessons.

When a module will not load, check the sizes first. A section whose declared size is wrong is the most common beginner mistake, and the reason the builder helper exists.

Common mistakes

  • Forgetting the closing end (0x0b). Every function body, block and loop ends with it.
  • Mixing up counts and sizes. A vector's count is the number of items; a section's size is the number of bytes.
  • Returning the wrong number of values. If the type says one result, exactly one value must be on the stack at the end.
  • Treating the export name as the function's name property. It is only the key on instance.exports.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the Function section store?

    Signatures live in the Type section, bodies in the Code section, and the Function section links each function to its signature.
  2. 2. What does i32.add do?

    It is a stack instruction. Overflow does not throw; it wraps around modulo 2^32.
  3. 3. In the builder, what does body([], code) append that you must not forget by hand?

    Each body is encoded as its byte length, the local declarations, the instructions and a final end opcode.
  4. 4. What does add(2147483647, 1) return for an i32 function?

    i32 arithmetic wraps modulo 2^32, and the result is read back as a signed 32-bit number.

Summary

  • A module is a header plus sections; Type, Function, Export and Code are enough for a working function.
  • Wasm functions are stack-based: instructions pop their inputs and push results.
  • Counts and sizes use LEB128; names are a length plus UTF-8; lists are a count plus items.
  • The tiny leb, vec, str, sec, mod, fn, body helpers remove the size arithmetic and are reused throughout this course.
  • i32 arithmetic wraps around at 32 bits.

Next: The WebAssembly JavaScript API