Web and networkingDive 12 of 12

WebAssembly, top to bottom

Start with real C zlib compressing your text in this tab. Then go down through the JavaScript boundary, the module format and the stack machine to the guard pages and x86-64 an engine uses to run it fast and safely.

Levels
10
Reading
40 min
Depth
Idea to Machine
Published
add.wasm41 bytes
  1. 00000061736d01000000header\0asm, version 1
  2. 000801070160027f7f017ftypeone signature: (i32, i32) → i32
  3. 001103020100functionfunction 0 has signature 0
  4. 0015070701036164640000export"add" is function 0
  5. 001e0a09010700200020016a0bcodelocal.get 0 · local.get 1 · i32.add · end

Waiting for your browser to compile these bytes…

A complete, valid WebAssembly module, built byte by byte in this page's script and handed to WebAssembly.instantiate. By the bottom of the page you will be able to read every byte, and you will know what your CPU actually runs when it calls add.

Level 01/10Idea

Why the browser needed a second language

Say your web app lets people upload log files, and you want to compress them in the browser before they go over the network. The compression format everyone expects is DEFLATE in a zlib wrapper, and the reference implementation is zlib: several thousand lines of portable C, first released in 1995, tuned for three decades, and sitting under PNG, gzip, git, PDF and a large share of HTTP compression.

For most of the web's history you had two options. Port zlib to JavaScript by hand and own the bugs, or don't do it in the browser. The tool below is the third option. It is the original zlib C source, compiled once, running in this tab. Type in it, pick a sample or compress a file from your disk. Nothing leaves the page.

Loading zlib.wasm…zlib 1.3.1module 64.6 KBimports 0linear memory 6 pages, 384.0 KB
Input
Result of compress2()
Smaller by–
Original–
Compressed–
compress2–
uncompress–
  • Round trip through uncompress()
  • The browser's own DecompressionStream reads it
  • CRC-32 of the input
First bytes of the compressed stream

Every zlib stream (RFC 1950) starts with two header bytes. 0x78 means DEFLATE with a 32 KiB window. 0x9c records the default setting (level 6) and makes the 16-bit header a multiple of 31, a cheap integrity check.

The checks on the right are the interesting part. The output of C compress2() goes back through C uncompress(), and also through the browser's own DecompressionStream, which is a completely separate, native implementation of the same format. They agree byte for byte, because this is the same zlib that produces real .zz streams everywhere else.

The thing that made it possible is WebAssembly (Wasm): a compact binary instruction format for a virtual machine that every major browser has shipped since 2017. You don't usually write it by hand. You point a compiler for C, C++, Rust, Go, Zig, Kotlin, Dart or C# at it, and the browser compiles the result to native machine code for whatever CPU the visitor has.

Why not just JavaScript?

JavaScript engines are astonishing, but they are built for a dynamic language. A function like function add(a, b) { return a + b; } might add integers, add doubles, or concatenate strings, depending on what you pass it. The engine has to run the code, watch which types show up, compile a fast version that bets on those types, and throw the fast version away if the bet goes wrong. That works well for typical web code. It works less well when you want predictable performance from a codec, a physics engine or a database, and it does nothing for the millions of lines of existing C, C++ and Rust you'd like to reuse.

People tried to fix this several times before Wasm. The table shows why those attempts didn't stick.

ApproachWhat shippedWhy it wasn't the answer
Plugins: Java applets, Flash, ActiveXNative code or a separate VM bolted onto the browserTheir own security model, with a long history of exploits. Vendor-controlled, not part of the web platform. All gone.
Native Client (NaCl)Real x86 or ARM machine code, sandboxed by verifying it before it runsChrome only, and a separate binary per CPU architecture.
Portable Native Client (PNaCl)A frozen subset of LLVM bitcode, translated on the clientStill Chrome only. Google deprecated it in 2017 in favour of WebAssembly.
asm.js (2013)A strict subset of JavaScript with type hints like x|0Worked in every browser and was fast once compiled, but the engine still had to download and parse text JavaScript, and the subset couldn't grow features like 64-bit integers or threads easily.
WebAssembly (2017)A binary format designed jointly by all the browser vendorsThis is the one that stuck: a W3C standard, in every browser, with a design that later went far beyond the browser.

Wasm is asm.js's idea done properly. The browser vendors announced it together in 2015, shipped the first version (the Minimum viable product: the 2017 feature set, with four number types, one memory, one table and no GC.) in Chrome, Firefox, Safari and Edge during 2017, and the core specification became a W3C Recommendation in December 2019. Its design goals fit in one line: fast, safe, portable and compact.

  • Fast. Every value has a static type, so the engine can compile straight to machine code without watching the program first. Typical code runs somewhere between close to native speed and a small factor slower.
  • Safe. Code runs in a sandbox. It can touch its own memory and the functions it was explicitly given, and nothing else.
  • Portable. One .wasm file runs on every OS and CPU the engine supports: browsers, servers, edge platforms, plugins.
  • Compact. A dense binary encoding that the engine can decode, validate and compile while it is still downloading.

WebAssembly is a portable, sandboxed instruction set that lets existing native code run in the browser at close to native speed.

That raises the obvious question. What happens between zlib's C source and the 66 KB file this page just downloaded?

Level 02/10Interface

From C source to a .wasm file

Two compilers are involved, and they run on different machines at different times. The first runs once, on the developer's machine, and produces a .wasm file. The second lives in the visitor's browser and turns that file into machine code for their specific CPU, every time the page loads (or once, if the engine caches the result).

  1. You writeC sourcezlib's deflate.c, inflate.c and friends
  2. On your machineclang + wasm-ldLLVM's wasm32 backend, then the linker
  3. Shippedzlib.wasm66 KB of portable bytecode
  4. In the browserThe engineV8, SpiderMonkey or JavaScriptCore
  5. On the CPUMachine codex86-64, ARM64, whatever the visitor has
The two halves of the pipeline. Everything left of the .wasm file happens once, at build time. Everything right of it happens in each visitor's browser.

Here is the build command that produced the zlib module in this page. It is plain clang, pointed at a different target.

Building zlib.wasm with clang from wasi-sdk
clang --target=wasm32-wasip1 -O3 -mexec-model=reactor \
  adler32.c compress.c crc32.c deflate.c inflate.c inftrees.c \
  inffast.c trees.c uncompr.c zutil.c \
  -Wl,--export=compress2,--export=uncompress,--export=compressBound \
  -Wl,--export=crc32,--export=zlibVersion,--export=malloc,--export=free \
  -o zlib.wasm

Each flag maps to a concept you'll meet further down.

  • --target=wasm32-wasip1 asks LLVM for 32-bit Wasm: pointers are 32-bit offsets into the module's memory. The wasip1 part says the C library underneath is wasi-libc, which supplies malloc, memcpy and friends.
  • -mexec-model=reactor builds a library rather than a program. There is no main. Instead the module exports _initialize, which runs C's static constructors once, and then sits there waiting to be called.
  • --export=… tells the linker which C functions should be visible from outside. Everything else stays private, and the linker is free to inline it or delete it.

The result needs no imports at all. zlib never reads a file, a clock or the console in the paths we call, so the module asks its host for nothing. Keep that in mind; it matters a lot in level 4 and again in level 8.

What the compiler actually emits

To see the output without 66 KB of noise, take one tiny C function. The tabs show the C and the Wasm text that clang -O2 produces for it. Wasm has a readable text format, called WAT, that maps one to one onto the binary.

sq_plus.c
int sq_plus(int x, int y) {
    return x * x + y;
}
clang --target=wasm32 -O2, shown as text
;; module boilerplate (memory, stack pointer, exports) omitted
(func $sq_plus (param i32 i32) (result i32)
  local.get 0
  local.get 0
  i32.mul
  local.get 1
  i32.add)

Notice what is missing. There are no registers, no calling convention and no stack frame. There are typed parameters, and instructions that push and pop values. That is the abstract machine, and the engine's job is to map it onto a real one. We'll step through exactly this function in level 6.

LanguageCommon toolchainNotes
C, C++Emscripten, wasi-sdk (clang)Emscripten also generates JavaScript glue that emulates POSIX and wraps web APIs. wasi-sdk produces plain modules like ours.
Rustrustc with wasm32-unknown-unknown or wasm32-wasip1/wasip2wasm-bindgen generates the JS side for rich types.
GoGo (GOOS=js or GOOS=wasip1), TinyGoShips Go's runtime and garbage collector inside the module, so binaries are larger.
Kotlin, Dart, Java, OCamlKotlin/Wasm, dart2wasm, J2Wasm, wasm_of_ocamlUse Wasm's built-in garbage collector (Wasm GC) instead of shipping their own.
C#.NET (Blazor)Runs the .NET runtime compiled to Wasm, with optional ahead-of-time compilation of your code.

Why it starts faster than JavaScript

On the browser side, the engine can begin working before the download finishes. The format is built for it: types come first, and every function body is prefixed with its length. Step through what happens in an engine that compiles eagerly, such as Firefox's SpiderMonkey, when a page calls WebAssembly.instantiateStreaming(fetch("zlib.wasm")).

  1. fetch() resolves as soon as the response headers arrive. WebAssembly.instantiateStreaming hands the still-downloading body to the engine, which checks the 8-byte header right away.
  2. The small sections come first: types, imports, the function list, exports. Now the engine knows the signature of every function before it has seen a single body.
  3. The code section arrives body by body. Each body starts with its own byte length, so an engine that compiles eagerly, such as Firefox's SpiderMonkey, can cut it out and hand it to a background thread while the download continues. V8, by default, only validates the body here and compiles it later, on its first call (level 10 shows why).
  4. More bodies arrive while the earlier ones are already compiled. Functions don't depend on each other's machine code, only on signatures, so an eager engine spreads the work over cores.
  5. The last bodies and the data section arrive. With a fast baseline compiler working eagerly, compilation ends moments after the last byte lands. A lazy engine finishes even sooner, because it has only validated the bodies.
  6. Instantiation: create or import the memory, copy the data segments into it, link imports, run the start function, hand back exports. Nothing here waited for a profiler to watch the code run.
1 / 6
JavaScriptWebAssembly
What arrivesSource textA binary that is already a compiler's output
Before runningParse, build an AST, generate bytecodeDecode and validate in one pass
TypesUnknown. Learned by watching the code run.Written in the binary. Checked before any code runs.
Optimized codeSpeculates on types. Thrown away (deoptimized) when a guess fails.Types are known, so there is nothing to speculate about there.
Parallel compilationLimitedPer function, on as many threads as the engine likes
Check yourselfWhy can the engine compile function 5 before it has received function 4's body?

Level 03/10Interface

Meeting JavaScript: imports, exports and pointers

A compiled module is inert. To run it you instantiate it: you supply everything it imports, and you get back an instance holding everything it exports. The JavaScript API has a small set of objects for this.

  • WebAssembly.Module: compiled, stateless code. You can cache it, send it to a worker and instantiate it many times.
  • WebAssembly.Instance: a module plus its state (memory, globals, tables) plus the imports it was linked against.
  • WebAssembly.Memory, Table and Global: the pieces of state, which can be created in JavaScript and imported, or created by the module and exported.
The usual way to load a module
const { module, instance } = await WebAssembly.instantiateStreaming(
  fetch("/dives/webassembly/zlib.wasm"),
  {}, // the import object: zlib needs nothing from us
);
const z = instance.exports;
z._initialize(); // run C's static constructors once

WebAssembly.Module.exports(module).map((e) => e.name);
// ["memory", "_initialize", "compress2", "compressBound", "crc32",
//  "uncompress", "zlibVersion", "malloc", "free"]

The 41-byte module from the top of the page, called from JavaScript as you type:

exports.add(,) =…

Try . JavaScript converts each argument with ToInt32, the Wasm i32.add wraps around like a CPU register, and the result comes back as a JavaScript number.

The calculator above shows the defining limit of the boundary. Wasm functions take and return numbers. The JS API converts between the two worlds with fixed rules:

Wasm typeArrives in JavaScript asGoing in, JavaScript converts with
i32Number (signed)ToInt32: wraps modulo 2³²
i64BigIntToBigInt64. Passing a plain Number throws a TypeError.
f32, f64NumberToNumber, rounded to single precision for f32
externrefThe same JS value you passed inNothing. The module can hold it and pass it back but can't look inside.
v128Not allowedCalling such a function from JavaScript throws a TypeError.

So how did a whole text box get into zlib?

Through memory. The module exports its linear memory, a single resizable block of bytes, and JavaScript sees it as an ordinary ArrayBuffer. To pass a buffer, JavaScript asks the module's own malloc for space, copies the bytes in, and passes the resulting address. That address is just an i32: an offset into the buffer.

  • JavaScriptz.compress2(dst, lenPtr, src, n, 6)A plain JS function call with five numbers
    export: instance → host
    zlib instancecompress2, uncompress, compressBound, crc32, malloc, free, zlibVersion, _initializeFunctions: typed, and callable only through their export
  • JavaScriptnew Uint8Array(z.memory.buffer)An ordinary ArrayBuffer over the same bytes
    export: instance → host
    zlib instancememory: 2 pages (128 KiB) at start, growing on demandLinear memory: every pointer in the C code is an offset into this
  • JavaScriptWebAssembly.instantiate(bytes, {})The import object: here, empty
    import: host → instance
    zlib instanceno importszlib needs no clock, files or console, so it asks for nothing

Inside the instance, out of everyone's reach

The call stack with its return addresses, the values on the operand stack, globals and tables that aren't exported, and the compiled machine code. JavaScript cannot name any of them, and neither can another module.

Everything that crosses between JavaScript and the zlib instance in the demo at the top. Functions and memory go out as exports. The import object is empty. Everything else stays sealed inside.

This is the actual code driving the demo at the top of the page, trimmed to the essentials. Read it as C written from the outside: every pointer is an integer, and every out-parameter is a 4-byte slot you allocate and read back yourself.

Calling C compress2() from JavaScript
function compress(z, input, level) {
  const src = z.malloc(input.length);
  const cap = z.compressBound(input.length);
  new Uint8Array(z.memory.buffer).set(input, src);
  const dst = z.malloc(cap);
  const lenPtr = z.malloc(4); // room for C's uLongf destLen, 32 bits on wasm32
  new DataView(z.memory.buffer).setUint32(lenPtr, cap, true);

  const rc = z.compress2(dst, lenPtr, src, input.length, level);

  const outLen = new DataView(z.memory.buffer).getUint32(lenPtr, true);
  const out = new Uint8Array(z.memory.buffer, dst, outLen).slice();
  z.free(src);
  z.free(dst);
  z.free(lenPtr);
  if (rc !== 0) throw new Error(`compress2 failed with ${rc}`);
  return out;
}

Line 4 is the copy in. Line 9 is the call: five integers go in, one integer comes back (0 is zlib's Z_OK). Line 12 is the copy out, and the .slice() matters: it copies the bytes into a fresh JavaScript-owned buffer before free lets C reuse that memory. There is no garbage collector on the C side, so every malloc needs a free.

Writing this glue by hand is fine for five functions. For real applications, tools generate it. Emscripten emits a JavaScript file that wraps every export, and Rust's wasm-bindgen generates bindings that copy strings and structs across. Newer Wasm features shrink the glue further: externref lets a module hold JavaScript objects directly, and the JS string builtins added in Wasm 3.0 let it work with JavaScript strings without copying them into linear memory.

Check yourselfJavaScript holds a Uint8Array over memory.buffer. Then a Wasm call grows the memory. What does the old Uint8Array see?

Level 04/10Interface

Outside the browser, and what comes next

Look at the boundary again. A module can do nothing except compute and call what it was given. In a browser, "what it was given" is a handful of JavaScript functions. But nothing in the design requires a browser, or JavaScript. A sandboxed, portable, fast-starting binary is useful anywhere you want to run code you don't fully trust: a server running customers' functions, a proxy running filters, an editor running plugins.

Outside the browser the host is a standalone runtime such as Wasmtime, WasmEdge, Wasmer or WAMR. The missing piece was a standard set of imports, so a module compiled once could ask any runtime for a file or a clock in the same way. That is WASI, the WebAssembly System Interface.

How a WASI preview 1 program asks to write to stdout
(import "wasi_snapshot_preview1" "fd_write"
  (func $fd_write (param i32 i32 i32 i32) (result i32)))

;; fd_write(fd, iovs, iovs_len, nwritten_ptr) -> errno
;; fd 1 is stdout. iovs points at (pointer, length) pairs in linear memory,
;; so even here, data crosses the boundary as offsets into memory.

WASI preview 1 looks a lot like POSIX: file descriptors, fd_write, clock_time_get. The difference is that it is A design where code can only reach a resource it was explicitly handed a reference to, instead of everything its user account can reach.. A WASI program can't open /etc/passwd just because the process can. The runtime hands it specific directories when it starts (wasmtime run --dir ./data app.wasm), and it can only reach paths under those.

The component model

The JavaScript boundary we just crossed has one big flaw: only numbers go through. Every language pair needs hand-written glue to agree on how a string or a list is laid out in memory. The component model fixes this one level up. You describe an interface in WIT, a small interface language, and the toolchain generates code on both sides that moves rich values through a standard memory layout, the canonical ABI.

A WIT interface for our compressor
package example:compress;

interface codec {
  compress: func(data: list<u8>, level: u8) -> result<list<u8>, string>;
  uncompress: func(data: list<u8>) -> result<list<u8>, string>;
}

world compressor {
  export codec;
}

A Rust component exporting this world can be called from a Python or JavaScript host with a real byte list and a real result, and neither side sees a pointer. WASI 0.2, released in January 2024, was rebuilt on top of components, and WASI 0.3, ratified in June 2026, adds native async functions, streams and futures to the component model. In the browser, components still need a translation step (tools like jco turn them into a core module plus JavaScript glue).

What's in the standard, and what's coming

Wasm grows through proposals that move through phases 0 to 5 in the WebAssembly Community Group. Finished proposals are rolled into numbered versions. Version 2.0 was published as a W3C Candidate Recommendation in December 2024, years after its features had shipped in browsers. Version 3.0 was announced complete in September 2025, and the specification is now maintained as a living Candidate Recommendation rather than moving to a frozen Recommendation. Here is where the larger features stand as of November 2026.

FeatureWhat it addsStatus
Fixed-width SIMDThe v128 type and over 200 vector instructionsIn 2.0. In all major browsers.
Reference types, bulk memory, multi-valueexternref, fast memory.copy/fill, functions with several resultsIn 2.0. In all major browsers.
Garbage collectionStructs and arrays managed by the engine's GC, so Kotlin, Dart and Java don't ship their ownIn 3.0. Chrome 119, Firefox 120, Safari 18.2.
Exception handlingtry_table, throw and the exnref type for C++ exceptions and language-level errorsIn 3.0. In all major browsers.
Tail calls, typed function referencesFunctional languages, faster indirect callsIn 3.0. In all major browsers.
Relaxed SIMD, multiple memoriesFaster but less deterministic vector ops, more than one memory per moduleIn 3.0. In Chrome and Firefox, not yet in Safari at the time of writing.
Memory6464-bit addresses, so memories past 4 GiBIn 3.0. Chrome 133, Firefox 134. In Safari behind a flag at the time of writing. Level 10 explains why it can be slower.
ThreadsShared memories and atomic instructionsPhase 4 and shipped in all major browsers for years, but not yet in a numbered spec version. Browsers require the page to be cross-origin isolated.
JS Promise Integration (JSPI)Lets synchronous Wasm code call an async JavaScript API and wait for itPhase 5. In Chrome since 137, and in recent Firefox and Safari releases.
Stack switchingFirst-class coroutines for green threads, generators and effect handlersPhase 3.
Component modelInterfaces, rich types and linking between modulesPhase 1 in the Community Group. Shipped by WASI runtimes ahead of browser standardization.

Wasm's only door to the outside world is its imports. WASI standardizes that door for servers, and the component model makes it wide enough for strings and lists.

We have used the word module a lot. Time to open one up.

Level 05/10Runtime

Anatomy of a module

A .wasm file is an 8-byte header followed by a sequence of sections. Each section starts with a one-byte id and its length in bytes, so an engine, or a tool, can skip any section without understanding it. Most sections are lists: a count followed by that many entries.

The map below is not a diagram drawn for the article. It is this page reading the real zlib.wasm it downloaded for the demo, section by section, and comparing it with the full list of section kinds the format defines.

Sections of the real zlib.wasm running at the top of this page

Reading the module…

IdSectionWhat it holdsIn zlib.wasm
0customAnything with a name: debug info, source maps, producer metadata. Engines skip sections they don't understand.not present
1typeFunction signatures, such as (i32, i32) → i32. Since 3.0 also struct and array types for GC.87 B · 13 entries
2importWhat the host must supply: functions, memories, tables, globals, tags.not present
3functionFor each function defined here, the index of its signature. Bodies come later.53 B · 52 entries
4tableTables of references, used for indirect calls (C function pointers).5 B · 1 entry
5memoryLinear memories: initial and maximum size in 64 KiB pages.3 B · 1 entry
13tagException tags for exception handling. Placed between memory and global despite its id.not present
6globalGlobal variables with their types and initial values, such as the C stack pointer.13 B · 2 entries
7exportNames the host can see, each pointing at a function, memory, table, global or tag.103 B · 9 entries
8startA function to run automatically when the module is instantiated.not present
9elementInitial contents of tables: which functions sit in which slots.11 B · 1 entry
12data countHow many data segments follow, so code can be validated in one pass.not present
10codeFunction bodies: local declarations and instructions, each prefixed with its size.54,771 B · 52 entries
11dataBytes to copy into linear memory at start-up: string literals, lookup tables, static data.11,104 B · 1 entry

A few things stand out. More than four fifths of the file is the code section: 52 function bodies. The data section is the next biggest: zlib's lookup tables and error strings, copied into memory at start-up. The table and element sections exist because zlib uses C function pointers, which become indexes into a table (more on that in level 8). There is no custom section, so no debug names or toolchain metadata ship with it, and no import section, because zlib imports nothing.

Signatures, declarations and bodies live apart

A function is split across three sections. Its signature lives in the type section, shared by every function with the same shape. The function section lists, for each function, which signature it has. The code section holds the bodies, in the same order. This looks fussy, but it is what made the streaming compilation in level 2 possible: by the time the first body arrives, the engine knows every function's type, so it can validate and compile each body on its own.

Sections must appear in a fixed order (custom sections can go anywhere), and each kind appears at most once. That lets a decoder be a single forward pass with no backtracking.

Index spaces

Inside a module nothing has a name, only an index. Functions, tables, memories, globals, types and a few other kinds of thing each have their own index space, numbered from zero. Imports come first in each space, then the module's own definitions. Export names are the only strings the engine cares about, and the optional name custom section exists purely so debuggers can show $deflate_slow instead of func[23].

Here is the smallest module we'll keep coming back to, the 41-byte add from the top of the page, in text form.

add.wat
(module
  (func $add (param $a i32) (param $b i32) (result i32)
    local.get $a   ;; push a
    local.get $b   ;; push b
    i32.add)       ;; pop both, push a + b
  (export "add" (func $add)))

;; The $names are for humans. In the binary, $a is local 0,
;; $b is local 1 and $add is function 0.

The text format is a convenience, not what the engine reads. Each line maps onto a field in one of the sections: the func line becomes an entry in the type section (its signature), the function section (its type index) and the code section (its body). The export line becomes the export section. In level 9 you'll assemble these bytes yourself and watch every size field update.

A module is a list of length-prefixed sections, with types up front, so engines can skip, stream and compile in parallel.

Level 06/10Runtime

A stack machine you can step through

Wasm code has no registers. Every instruction takes its inputs from an implicit operand stack and pushes its result back onto it. i32.add pops two 32-bit integers and pushes their sum, which is why it fits in a single byte, 0x6a: there are no operands to name.

There are only a handful of value types, and signedness lives in the instruction, not the type. i32.div_s and i32.div_u read the same 32 bits as signed or unsigned.

  • i3232-bit integer. Also pointers, booleans and C int.0x7f
  • i6464-bit integer. Crosses into JavaScript as a BigInt.0x7e
  • f32IEEE 754 single precision.0x7d
  • f64IEEE 754 double precision, like a JS number.0x7c
  • v128128-bit SIMD vector: 16 × i8, 4 × i32, 2 × f64…0x7b
  • funcref / externrefOpaque references to functions and host objects.0x70 / 0x6f

Below is a small interpreter for a slice of the instruction set. The first program is sq_plus from level 2, exactly as clang compiled it. The second is a loop that sums n + (n − 1) + … + 1, which shows how Wasm does control flow. Step through each one, change the arguments, and watch the stack, the locals and the open blocks. When it finishes, the page compiles the same instructions into a real module and runs them on your browser's engine as a cross-check.

Instructions and their bytes

    Operand stack top is up

    Locals

    Control stack open blocks and loops

    Cross-check: the same instructions, assembled into a 42-byte module and run by your browser's engine, return f(7, 5) = 54, the same answer the stepper reaches.

    Structured control flow

    There is no goto and no jump to an address. Control flow uses three nested constructs, block, loop and if, each closed by an end. A branch names its target by how many constructs out it is, not where it is: br 0 means the innermost enclosing one, br 1 the one around that. Branching to a block jumps forward past its end. Branching to a loop jumps back to its start. That's the whole trick in the sum program: br_if 1 leaves the outer block when n reaches zero, and br 0 goes round again.

    Switch-style jump tables are still possible (br_table picks one of several enclosing labels), but irreducible control flow, such as a loop that can be entered in two places, can't be expressed directly, and toolchains restructure it (LLVM does this automatically). The payoff is that every branch target is known statically. Nothing can jump into the middle of an instruction, or into the middle of another function.

    Validation: types are checked before anything runs

    Before an engine compiles a function, it validates it in a single linear pass. The validator simulates the stack with types instead of values. It knows that after local.get 0 the stack holds one i32, that i32.add needs two, and that the function must end with exactly the results its signature promises. A module that would pop an empty stack, add a float to an integer, or branch to a label that doesn't exist is rejected as a whole, before a single instruction runs. Try it:

    Validation is what lets the rest of the system trust the code. Once a function has validated, the engine knows the exact type and height of the stack at every instruction. That is also why the stack can disappear entirely when the code is compiled, as you'll see at the bottom.

    Check yourselfIn the sum program, the loop sits inside a block. Inside the loop, where does br_if 1 jump when its condition is non-zero?

    Level 07/10Runtime

    Linear memory: one big byte array

    Values on the stack and in locals are typed and private. Everything else, every C array, struct, string and malloced buffer, lives in linear memory: one contiguous, resizable array of bytes, addressed by plain integers starting at zero. A C pointer compiled to wasm32 is nothing more than an i32 index into it.

    Memory is sized in pages of 64 KiB. It starts at the size the module declares, can grow with memory.grow, and never shrinks. A 32-bit memory can reach 65,536 pages, which is 4 GiB. Multi-byte values are always little-endian, regardless of the host CPU, so a module behaves identically on every machine.

    Below is a real WebAssembly.Memory of one page, created by this page and imported into a module assembled in the browser. The module exports three functions: store(addr, value) runs i32.store, load(addr) runs i32.load, and grow(n) runs memory.grow. The grid shows the first 64 bytes of memory.buffer, read through an ordinary Uint8Array.

    Wasm

    JavaScript

    Wasm

    memory.buffer, bytes 0 to 631 page · 65,536 bytes
    1. Wasmstore(4, 305419896)0x12345678 lands as 78 56 34 12: least significant byte first.

    Try three things. Store 305419896, which is 0x12345678, and see it land as 78 56 34 12. Write some text from the JavaScript side and load it back from Wasm as an integer, to see that both sides really share the same bytes. Then press "Load past the end": the engine stops the access with a trap instead of reading whatever happens to sit next to the buffer in the browser's memory. Level 8 is about how that check costs almost nothing.

    How C lays out its memory

    Wasm gives a C program one flat array and nothing else. The compiler and linker decide what goes where. Here is the layout of the zlib module from the demo, read straight from its bytes.

    unused 0 – 1,023
    wasm-ld starts static data at 1024 by default. Address 0 is still readable.
    data 1,024 – 12,119
    The data segment: string constants and lookup tables copied in at instantiation.
    bss + stack 12,120 – 78,159
    Zero-initialized statics, then 64 KiB of shadow stack growing down from 78,160.
    heap 78,160 →
    malloc's territory. When it runs out, malloc calls memory.grow.

    Read from the module's own bytes: the data segment's offset is i32.const 1024, it is 11,096 bytes long, and the mutable global the C code uses as its stack pointer starts at i32.const 78160. Not to scale.

    zlib.wasm's linear memory at start-up, as wasm-ld laid it out. The engine knows nothing about these regions; to Wasm it is all just bytes.

    The stack in that picture is a shadow stack. Wasm's real call stack, with return addresses and spilled locals, lives in the engine where the module can't reach it. But C lets you take the address of a local variable (&len), and an address must point into linear memory. So the compiler keeps a second, software-managed stack in linear memory for exactly those variables, and tracks its top in a mutable global. In zlib, that global starts at 78,160 and moves down as functions need space.

    Two more facts complete the picture. With the threads proposal, a memory can be declared shared, backed by a SharedArrayBuffer, and used from several Web Workers at once with atomic instructions. And since Wasm 3.0 a module can have several memories and 64-bit memories, though most code still uses exactly one 32-bit memory.

    Linear memory is a single bounds-checked byte array that JavaScript and Wasm both see. Every pointer is just an index into it.

    Level 08/10System

    The sandbox: guard pages, signals and traps

    Every load and store in Wasm must stay inside the memory, and every call must go to a function of the right type. Those two guarantees, enforced on every instruction, are most of what makes it safe to run code from any website. The rest comes from what the module simply has no way to express.

    A module canA module cannot
    Compute with values on its stack and in its locals and globalsName a raw machine address. Addresses are indexes into its own memory.
    Read and write its own linear memory, within boundsRead the browser's memory, another module's memory, or its own machine code
    Call its own functions and the functions it importsMake a system call, open a socket or touch the DOM, unless an import does it on its behalf
    Branch to the end of an enclosing block or the start of an enclosing loopJump to an arbitrary address or overwrite a return address. The call stack is outside linear memory.
    Call through a table with call_indirectCall a table entry with the wrong signature. The engine checks the type at runtime and traps.

    The bounds check is the interesting one. Checking every memory access against the memory's size sounds expensive, and on a tight loop like zlib's longest-match search it would be: a compare and a branch around every load. On 64-bit machines, engines make the check essentially free by getting the hardware to do it.

    Reserve 8 GiB, commit what you use

    A 32-bit memory is addressed by an i32 index plus a constant offset baked into the instruction, also 32 bits. The sum can never exceed about 8 GiB. A 64-bit process has address space to spare (at least 128 TiB on typical x86-64 Linux), so when V8 creates a 32-bit memory it reserves a full 8 GiB of virtual address space, maps only the pages the memory actually uses as readable and writable, and leaves the rest with no access rights at all. Growing the memory just changes the protection on more pages.

    Now no access can ever leave the reservation, and any access past the end of the memory hits a page the CPU refuses to touch. The compiled code doesn't need to compare anything. Try some addresses against zlib's initial 128 KiB (2 pages). The demo at the top has grown it since, but the reservation doesn't care how big the memory is:

    The trap still has to get from the CPU back to JavaScript as a clean exception. That trip goes through the kernel, and it only works because the engine set it up in advance.

    1. The engine compiled i32.load offset=8 into one ordinary mov. There is no comparison before it. This time the index is far past the end of memory.
    2. The address falls inside the engine's reservation, on a page mapped with no access rights. The MMU refuses the translation and the CPU raises a page fault, an exception in the hardware sense.
    3. The kernel's fault handler finds that the page's mapping forbids all access (the engine mapped it PROT_NONE), so it delivers SIGSEGV to the thread. Windows raises an access-violation exception instead, and the engine catches it with a vectored exception handler.
    4. The engine installed its own handler at start-up. It checks two things: was the thread running Wasm code, and is the faulting instruction in the table of memory accesses the compiler recorded? If not, it's a genuine crash and the handler passes the signal on.
    5. Both match. The handler rewrites the saved register state so that, when the signal returns, the thread resumes at a trap stub instead of retrying the load.
    6. The stub unwinds the Wasm frames and throws a WebAssembly.RuntimeError into the JavaScript that called the export. The page keeps running. Nothing outside the module's memory was read.
    1 / 6

    This trick is why the zlib demo can run at close to native speed. It has limits, though. It needs a 64-bit address space, so on 32-bit platforms and in some embeddings engines fall back to explicit checks. Memory64 breaks it too: a 64-bit index can point anywhere, and you can't reserve the whole 64-bit space. Engines generally fall back to explicit checks there, though V8 has started applying the guard-region trick to memory64 too, by reserving the largest memory the JavaScript API allows (16 GiB).

    Check yourselfA C program compiled to Wasm has a heap buffer overflow that an attacker controls. What can the attacker reach?

    Wasm's sandbox is enforced by validation and by the page tables: the engine reserves more address space than a module can name and lets the CPU fault on everything it hasn't granted.

    Level 09/10Machine

    Bytes on disk

    Time to read the bytes from the top of the page. The builder below assembles a complete module in TypeScript, field by field, the way a linker does: the magic number and version, then each section with its id, its size, and its contents. Pick a function body, rename the export, and watch the offsets and every size field change. The page validates the result with WebAssembly.validate, instantiates it and calls the export. If you'd like, download the file and open it in any Wasm tool.

    exports["add"](40, 2) = 42
    OffsetBytesMeaning

    A few things are worth noticing as you play with it.

    • Rename the export to something longer and two numbers change: the name's own length byte, and the export section's size. Nothing else moves except the offsets, because sections are self-contained.
    • The code section has two size fields: one for the whole section and one for each body. The second is what lets an engine hand bodies to compile threads without decoding them.
    • Switch to "Sum loop" and the code section gains a local declaration, 01 01 7f: one group of one local of type i32. Locals are declared as run-length groups, so a function with 50 i32 locals still spends only three bytes declaring them.
    • Every count, size and index is encoded with LEB128, never with a fixed-width integer.

    LEB128: small numbers stay small

    Little Endian Base 128, a variable-length integer encoding from the DWARF debugging format. stores a number seven bits at a time, lowest bits first. The high bit of each byte is a continuation flag: 1 means another byte follows, 0 means this is the last one. Most numbers in a module are tiny (section ids, local indexes, type indexes), so they take a single byte instead of four. Signed values, like the operand of i32.const, use a variant where the top bit of the last group acts as the sign.

      Put the two together and you can decode any instruction. Here is i32.const -123456, from the "Return a constant" preset above, with its bits.

      4101000001C011000000BB101110117801111000
      1. Opcodei32.const
      2. Low 7 bits1 + 1000000: more follows
      3. Next 7 bits1 + 0111011: more follows
      4. Last 7 bits0 + 1111000: last byte, sign bit set
      i32.const -123456. One opcode byte, then three bytes of signed LEB128. The last byte's top bit is 0, so the number ends there, and its next bit (bit 6) is 1, so the value is negative.

      The opcode space

      The MVP fit every instruction into a single opcode byte, from 0x00 (unreachable) up to 0xbf. Later features needed more room, so they live behind prefix bytes followed by a LEB128 sub-opcode: 0xfc for saturating conversions and bulk memory, 0xfd for SIMD, 0xfb for GC, 0xfe for atomics. Common operations stay one byte, and the space never runs out.

      Check yourselfAn export section has size byte 0x07. You rename its only export from 'add' to 'add_two'. What is the new size byte?

      Level 10/10Machine

      Inside the engine: from bytecode to x86-64

      The engine now has validated bytes. The last step is turning them into instructions the CPU can execute, and every engine makes the same trade-off: compile quickly so the page starts now, or compile carefully so the hot code runs fast. The answer is to do both, in tiers.

      EngineFirst tierOptimizing tier
      V8 (Chrome, Edge, Node.js, Deno)Liftoff, a one-pass baseline compilerTurboFan, whose Wasm pipeline now runs on the newer Turboshaft IR
      SpiderMonkey (Firefox)Wasm-Baseline (RabaldrMonkey)Ion (BaldrMonkey)
      JavaScriptCore (Safari)IPInt, an in-place interpreter, then BBQ, a fast compilerOMG
      Wasmtime (servers)One tier per module, chosen by the embedder: Cranelift (optimizing), Winch (baseline) or the Pulley interpreter. There is no automatic tier-up.

      V8 is a good concrete example. Since Chrome 101 it uses dynamic tiering, and by default it also compiles lazily: while the module streams in, V8 decodes and validates it but compiles nothing, and each function is compiled by Liftoff the first time it is called. Functions that never run are never compiled. Liftoff works in a single pass over the bytecode, with no intermediate representation: it walks the instructions, keeps track of which value of the abstract stack lives in which register, and emits machine code as it goes. It's fast enough that compiling on first call costs little. TurboFan builds a full graph of the function, optimizes it and allocates registers properly, which takes much longer, so it is only spent on functions that turn out to be hot.

      1. While the module streams in, V8 decodes and validates every function but, by default, compiles none of them yet.
      2. The first call to a function makes Liftoff compile it in one fast pass, and it then runs as baseline code that counts down a tier-up budget. Functions that are never called are never compiled.
      3. A hot function runs out of budget. It is queued for TurboFan, which compiles it on a background thread while baseline code keeps running.
      4. Other hot functions follow. Cold ones stay on baseline code forever, which is fine.
      5. The next call to a hot function jumps to the optimized code. It made no guesses about value types, so it never has to fall back because of one.

      The crucial difference from JavaScript is the last note. A JIT for JavaScript optimizes on assumptions ("this variable has always been a small integer") and must keep a way to bail out when an assumption fails. A Wasm function's types are fixed by the binary, so the optimizing tier never speculates on types and its code is never thrown away because a type turned out different.

      One function, two compilers

      Here is sq_plus, the function you stepped through in level 6, as each tier might compile it for x86-64. The listings are illustrative: we use the System V calling convention (arguments in edi and esi, result in eax) so they read like ordinary C output, while V8 actually uses its own internal convention with an extra register pointing at the instance. The shape is what matters.

      sq_plus: a 10-byte body (1 byte of local declarations, 9 of instructions)
      ;; (func $sq_plus (param i32 i32) (result i32)
      local.get 0   ;; 20 00
      local.get 0   ;; 20 00
      i32.mul       ;; 6c
      local.get 1   ;; 20 01
      i32.add       ;; 6a
      end           ;; 0b
      x86-64, one pass, illustrative
      ; baseline: one pass over the bytecode
      push rbp
      mov  rbp, rsp
      sub  rsp, 16
      cmp  rsp, qword ptr [r13 + 0x20]   ; stack limit check
      jbe  .Lstack_overflow
      mov  eax, edi                      ; local.get 0
      mov  ecx, edi                      ; local.get 0
      imul eax, ecx                      ; i32.mul
      mov  ecx, esi                      ; local.get 1
      add  eax, ecx                      ; i32.add
      sub  dword ptr [r13 + 0x48], 23    ; spend this function's tier-up budget
      js   .Ltier_up                     ; budget gone: queue it for TurboFan
      mov  rsp, rbp
      pop  rbp
      ret                                ; end: the result is in eax
      x86-64, optimized, illustrative
      ; optimizing: the operand stack is gone
      ; (a real engine may still keep an entry stack check)
      imul edi, edi          ; x * x
      lea  eax, [rdi + rsi]  ; + y, result in eax
      ret
      ARM64, optimized, illustrative
      ; one integer multiply-add
      madd w0, w0, w0, w1    ; w0 = w1 + w0 * w0
      ret

      The baseline code is a faithful, almost literal translation: each stack slot gets a register, each instruction becomes one or two machine instructions, and the function is wrapped in a frame, a stack-overflow check and a tier-up counter. The optimized code is what a C compiler would produce, and the operand stack has vanished completely. On ARM64 the whole function is one integer multiply-add instruction.

      Follow a single operation all the way down and the descent of this whole page fits in five lines.

      1. Cint add(int a, int b) { return a + b; }
      2. Wasm textlocal.get 0 · local.get 1 · i32.add · end
      3. Wasm bytes20 00 20 01 6a 0b
      4. x86-64lea eax, [rdi + rsi] · ret
      5. ARM64add w0, w0, w1 · ret
      The add function at every level of this dive. Three Wasm instructions become one CPU instruction, plus the return.

      What a memory access compiles to

      Finally, the payoff from level 8. Here is a load with a constant offset, i32.load offset=8, compiled with and without guard pages. The base address of linear memory sits in a register (rbx here); the index is zero-extended into rcx.

      x86-64, illustrative
      ; i32.load offset=8, guard pages do the checking
      ; rbx = start of linear memory, rcx = the i32 index, zero-extended
      mov  eax, dword ptr [rbx + rcx + 8]
      x86-64, illustrative
      ; i32.load offset=8, no guard pages
      lea  rdx, [rcx + 12]               ; one past the last byte: index + 8 + 4
      cmp  rdx, qword ptr [r13 + 0x18]   ; current memory size in bytes
      ja   .Ltrap_oob                    ; past the end: jump to the trap stub
      mov  eax, dword ptr [rbx + rcx + 8]

      One instruction against four, and the extra three include a compare and a branch on every single access. In a compression loop that does little but load bytes, that difference is measurable. Mozilla measured memory64 code running anywhere from about 10% to over 100% slower than the same code as memory32 in early 2025, largely because of explicit checks. That is why memory64 is something you choose when you need more than 4 GiB, not a free upgrade.

      Not compiling at all

      The cheapest compile is the one you skip. Chrome, for example, caches optimized machine code (for modules above a size threshold) loaded with compileStreaming or instantiateStreaming, keyed on the response, so a returning visitor's engine can load it from disk instead of recompiling. That's another reason to prefer the streaming APIs over fetching an ArrayBuffer and calling instantiate yourself, which is what the demos on this page do only because they also need the raw bytes.

      Check yourselfWhy does an optimizing Wasm compiler never need to deoptimize because of a wrong type guess, while a JavaScript JIT does?

      An engine turns Wasm's typed stack code into ordinary register code, first quickly and then well, and leans on the virtual memory hardware so bounds checks cost nothing.

      That's the whole descent. A C library in a browser tab is a list of typed sections, validated in one pass, holding stack-machine code that an engine turns into the same kind of machine code a C compiler would emit, inside an address-space reservation the CPU itself polices. The next time a page decodes video, edits a photo or compresses your upload without a server, you know what's underneath.

      End of WebAssembly · 10 levels, Idea to Machine

      Where to next

      Browse all 34 divesAll topics