Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 38 ยท Getting Started

How WebAssembly Runs

Follow a .wasm file from download to running code. Learn the decode, validate, compile and instantiate steps, the sandbox, hosts, and why validation matters.

A .wasm file is just a sequence of bytes. Before a single instruction runs, the engine takes it through several stages, and understanding them explains most of the API you will use later: why there are separate Module and Instance objects, why some functions are asynchronous, and why a module can never crash the browser.

This lesson walks through those stages, then shows the sandbox model that makes Wasm safe enough to run code from strangers.

The pipeline

flowchart TD
    A["Bytes (file or network)"] --> B["1. Decode: read sections"]
    B --> C["2. Validate: type check everything"]
    C --> D["3. Compile: machine code"]
    D --> E["WebAssembly.Module (shareable, stateless)"]
    E --> F["4. Instantiate: imports + memory"]
    F --> G["WebAssembly.Instance (runnable)"]
    G --> H["5. Run: call exports"]
  1. Decode. The engine reads the header and the sections (types, functions, memory, exports, code...). A malformed file is rejected here.
  2. Validate. Every function body is checked against the type rules. Does each instruction find the right types on the stack? Is every call target defined? A module that fails is never run, even partially.
  3. Compile. Validated code becomes machine code. Many engines compile quickly first with a simple compiler (so you can start running at once) and then recompile hot functions with an optimizing compiler in the background.
  4. Instantiate. The engine supplies the imports the module asked for, allocates its memory, tables and globals, runs initialization (data segments, an optional start function) and returns an instance.
  5. Run. You call the exported functions.

The result of step 3 is a WebAssembly.Module. It holds no memory and no state. You can create many instances from one module, or in a browser send the module to a Web Worker and instantiate it there.

Seeing the stages from JavaScript

The JavaScript API lets you perform each stage by hand. This example compiles the answer module from the previous lesson, inspects what the module declares, and only then instantiates it.

Node.js Compile first, instantiate later

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.

When you pass a Module to instantiate, you get an Instance back directly. When you pass raw bytes, you get an object { module, instance }, which is why earlier examples wrote const { instance } = await WebAssembly.instantiate(bytes).

Validation is the safety net

Validation is what makes Wasm trustworthy. The type rules are strict and checked once, ahead of time, so the engine does not need to check types while running. Try to damage the module: change the declared result type of the function to f64, while the body still pushes an i32.

Node.js A module the validator rejects

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 exact wording of the error message differs between engines, but the error type is always WebAssembly.CompileError.

The sandbox

A Wasm instance has exactly three kinds of things it can touch:

  • Its own linear memory, a block of bytes it owns. It cannot read or write anything outside that block. An out-of-bounds access traps (stops the program) instead of corrupting something else.
  • Its own stack, which the program cannot address. Return addresses are not stored in memory the code can overwrite, which removes a whole class of classic exploits.
  • Imports, the functions, memory, tables and globals the host passed in at instantiation.

There is no instruction for "open a file" or "send a packet". If you never import such a function, the module cannot do it. This is called capability-based security, and it is why runtimes can safely run plug-ins from users.

The sandbox protects the host from the module, not the module from itself. A C program compiled to Wasm can still have a buffer overflow that corrupts its own memory. The damage stays inside the module's memory, but the program's logic can still be attacked.

Hosts and embedders

The program that loads and runs the engine is the host or embedder. In a browser the host is the web page and its JavaScript. In Node.js it is the Node process. Other hosts are standalone runtimes such as Wasmtime, Wasmer and WasmEdge, which are used from the command line, from Rust, Go, Python and many other languages. The core specification is the same everywhere; what differs is the set of imports each host offers. Chapter 7 covers the standard system interface (WASI) that makes command-line modules portable.

Streaming and non-blocking compilation

Compiling a large module can take noticeable time, so the API is promise based. In browsers, WebAssembly.instantiateStreaming(fetch('app.wasm'), imports) compiles while the bytes are still downloading, so the work is mostly finished by the time the last byte arrives. The server must send the header Content-Type: application/wasm for this to work. Lesson 4 covers loading in detail.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In which order does an engine process a module?

    Bytes are decoded into sections, validated, compiled to machine code (a Module) and then instantiated with imports and memory (an Instance).
  2. 2. What does a WebAssembly.Module contain?

    A module is stateless. State (memory, tables, globals) lives in each instance.
  3. 3. What error type is thrown when the bytes fail validation?

    CompileError covers decoding and validation failures. LinkError is for bad imports and RuntimeError for traps.
  4. 4. How can a module read a file from disk?

    Wasm has no ambient authority. The host chooses which capabilities to import.

Summary

  • A module goes through decode, validate, compile and instantiate before any code runs.
  • WebAssembly.Module is stateless and reusable; each Instance has its own memory and state.
  • Validation checks every type up front and rejects bad modules with WebAssembly.CompileError.
  • The sandbox limits a module to its own memory, its own stack and the imports the host gives it.
  • Streaming compilation overlaps download and compile and needs the application/wasm MIME type.

Next: Your First Wasm Module