How WebAssembly Runs
Before writing bigger modules, it helps to know what happens between "here are some bytes" and "the function returned 42". Every engine goes through the same four stages.
.wasm bytes ──► decode ──► validate ──► compile ──► instantiate ──► call exports
(parse (type-check (to native (link imports,
sections) everything) machine allocate memory,
code) run start function)1. Decoding
A module is a sequence of sections (types, imports, functions, memory, exports, code, data …). The engine reads
them in a single pass. Because the format is designed for streaming, browsers can start decoding and even compiling
while the file is still downloading (WebAssembly.compileStreaming).
2. Validation
Before a single instruction runs, the engine validates the entire module. Validation checks, among other things:
- every instruction gets operands of the right type from the stack,
- every branch targets an enclosing block, and the stack has the right shape there,
- every function, local, global, memory and table index exists,
- each function leaves exactly its declared result types on the stack.
If anything is wrong, the module is rejected with a CompileError and nothing runs. Here the function promises an
i32 result but leaves nothing on the stack:
(module
(func (export "main") (result i32)
nop))main.wat:3:5: error: type mismatch in implicit return, expected [i32] but got []
nop))
^^^
Validation is fast (linear in the size of the code) and it is what makes Wasm safe to compile ahead of time: the compiler never has to guess types or handle "impossible" stack states.
3. Compilation
Engines translate each function to native machine code. Browsers typically use tiers: a quick baseline compiler so the code can start immediately, and an optimising compiler that recompiles hot functions in the background. In V8 (Chrome, Node.js) these are called Liftoff and TurboFan. Compiled modules can be cached, so a returning visitor skips most of the work.
Note: Unlike JavaScript, Wasm is never "deoptimised" because a type changed: types are fixed at validation time. This is why its performance is so predictable.
4. Instantiation
A compiled Module is just code. To run it, you create an instance, which:
- resolves every import against an object provided by the host (functions, memories, tables, globals),
- allocates the module's own memories, tables and globals,
- copies data segments into memory and element segments into tables,
- runs the optional start function.
The same module can be instantiated many times, and each instance gets its own fresh memory and globals.
The sandbox
An instance lives in a tightly sealed box:
| It can | It cannot |
|---|---|
| Compute with numbers in its own locals, globals and stack | Read or write the host's memory or other instances' memory |
| Read and write its own linear memory (bounds-checked) | Jump to arbitrary addresses: control flow is structured |
| Call its own functions and functions in its tables | Make system calls or access files, network, DOM |
| Call imported host functions | Inspect the call stack or return addresses |
Every memory access is checked against the memory's current size. An out-of-bounds access does not corrupt
anything: it traps, immediately aborting the call with a RuntimeError:
(module
(memory 1) ;; one 64 KiB page: valid addresses are 0 to 65535
(func (export "main") (result i32)
(i32.store (i32.const 100) (i32.const 7))
(i32.load (i32.const 100))))7
Now read from an address beyond the end of the page:
(module
(memory 1)
(func (export "main") (result i32)
(i32.load (i32.const 65535)))) ;; needs bytes 65535..65538RuntimeError: memory access out of bounds
The load needs four bytes, but only one of them (65535) is inside the memory, so the engine traps.
Linear memory in one paragraph
Linear memory is a contiguous, byte-addressable array that starts at address 0 and grows in units of pages
(64 KiB each). Wasm code addresses it with plain i32 offsets. The host can see the same bytes as an
ArrayBuffer, which is how JavaScript and Wasm share strings, images and arrays. You'll explore it in depth in the
Memory section.
The host
The host is whatever embeds the engine: a web page, Node.js, a Wasmtime command line. It decides what the module
may import. In this course's playground the host provides console.log (print numbers), console.str (print a
string from memory) and js.mem (a memory). A browser page would provide its own functions, typically wrappers
around DOM or Web APIs.
Test yourself
When does validation happen?
- After the first call
- Before the module can be compiled and instantiated
- Only in debug builds
- Only when a trap occurs
What happens when Wasm code loads from an address outside its linear memory?
- It reads zeros
- It reads the host's memory
- It traps with a RuntimeError
- The address wraps around to 0
Which step links a module's imports to real host functions?
- Decoding
- Validation
- Compilation
- Instantiation