The Wasm Component Model — WebAssembly

The Component Model wraps core modules into components with a WIT contract: package, interface, world, and rich types (list, string, record, result, option…

How does a Wasm module from Rust call a module from Go, when only numbers can cross the border? The Component Model is a standard that wraps a Wasm module into a component: a module that states clearly what it needs and what it provides, with rich data types like list<u8>, string, record and result, not only numbers.

Mrs. Sri once ordered photo editing from different craftsmen: one from a nearby town, one from a big city, one from the other side of the country. Each used to take orders his own way: one wanted a shelf number and a photo count, another wanted the photos left in a particular box. Every pairing needed its own agreement. Now there is a standard order form that says what is handed over and what comes back, plus fixed rules for packing the goods. Any craftsman who can read the form can start working straight away. The form is WIT, the packing rules are the canonical ABI, and the craftsmen are components written in Rust, Go, C or JavaScript.

Core modules and components

Every .wasm in the earlier lessons is a core module. Only numbers cross its boundary: i32, i64, f32, f64, plus references. Text and photos have to be written into linear memory and passed as a pointer and a length, and every pair of languages needs its own glue code (wasm-bindgen for Rust and JS, syscall/js for Go). If a Rust module is to be used by a Go module, both sides have to agree by hand on the memory layout. The idea that solves this used to be called interface types; it is now part of the Component Model.

Core module Component
What crosses the boundary i32, i64, f32, f64, references also string, list, record, variant, option, result, resource
Memory can be exported and shared hidden inside the component, not shared
Contract a list of functions with numeric types WIT: interfaces and worlds
Bytes 5 to 8 01 00 00 00 0d 00 01 00

A component is a wrapper: inside it are one or more core modules, plus types written in WIT and the instructions that turn rich types into numbers. Browsers and Node only know core modules. Chromium 147 rejects a component with CompileError: WebAssembly.compile(): expected version 01 00 00 00, found 0d 00 01 00 @+4, WebKit 26.4 with CompileError: WebAssembly.Module doesn't parse at byte 0: unexpected version number 65549 expected 1.

WIT: the contract for Mrs. Sri's photo tool

WIT (Wasm Interface Type) is the language you write the contract in. This is wit/photolab.wit:

package homestay:[email protected];

/// Room photos of Mist Homestay: RGBA, 4 bytes per pixel.
interface photo {
    record size {
        width: u32,
        height: u32,
    }

    /// gray = (r × 77 + g × 150 + b × 29) >> 8, alpha unchanged.
    grayscale: func(pixels: list<u8>) -> list<u8>;

    /// Area-average thumbnail. Fails when the byte count does not match the size.
    thumbnail: func(pixels: list<u8>, source: size, target: size) -> result<list<u8>, string>;
}

world photolab {
    export photo;
}

Building the component from Rust

The project is a plain Rust crate (photolab-component) with crate-type = ["cdylib"] and one dependency, wit-bindgen = "0.62". The WIT file sits in the wit/ folder.

wit_bindgen::generate!({ world: "photolab", path: "wit" });

use exports::homestay::mist::photo::{Guest, Size};

struct Photolab;

impl Guest for Photolab {
    fn grayscale(mut pixels: Vec<u8>) -> Vec<u8> {
        for p in pixels.chunks_exact_mut(4) {
            let gray = ((p[0] as u32 * 77 + p[1] as u32 * 150 + p[2] as u32 * 29) >> 8) as u8;
            (p[0], p[1], p[2]) = (gray, gray, gray);
        }
        pixels
    }

    fn thumbnail(pixels: Vec<u8>, source: Size, target: Size) -> Result<Vec<u8>, String> {
        let needed = (source.width * source.height * 4) as usize;
        if pixels.len() != needed {
            return Err(format!("pixels must be {} bytes, got {}", needed, pixels.len()));
        }
        if target.width == 0 || target.height == 0 || target.width > source.width || target.height > source.height {
            return Err(format!("target size {} × {} cannot come from {} × {}", target.width, target.height, source.width, source.height));
        }
        Ok(area_average(&pixels, source, target))
    }
}

export!(Photolab);
$ cargo build --release --target wasm32-wasip2
$ wasm-tools component wit target/wasm32-wasip2/release/photolab_component.wasm
world root {
  import wasi:io/[email protected];
  import wasi:cli/[email protected];
  ...                       (14 wasi imports, cut short)
  export homestay:mist/[email protected];
}

Canonical ABI: from list to numbers

Inside a component, the function is still a core Wasm function that only knows numbers. The canonical ABI is the fixed set of rules for "lowering" rich values into numbers and bytes in linear memory, and "lifting" the results back: lists and strings become a pointer plus a length, records are split into their fields, a result becomes a tag byte plus its contents. Because the rules are the same for every language, Rust and Go can call each other with no extra agreement. These are the exports of the core module inside photolab.wasm:

memory
homestay:mist/[email protected]#grayscale        (i32, i32) -> i32
homestay:mist/[email protected]#thumbnail        (i32, i32, i32, i32, i32, i32) -> i32
cabi_realloc                               (i32, i32, i32, i32) -> i32
cabi_post_homestay:mist/[email protected]#grayscale   (i32)

In WIT, grayscale takes a list<u8>, but its core function receives two i32 numbers, a pointer and a length, and the result is one i32: the address of a "return area" holding the result's pointer and length. This is the order of one grayscale([200, 120, 40, 255]) call, with the numbers from the Lab:

Step What happens
1 cabi_realloc(0, 0, 1, 4) gives 1114112: room for 4 bytes in the component's memory
2 the glue copies the 4 bytes to address 1114112
3 homestay:mist/[email protected]#grayscale(1114112, 4) returns 1048912
4 read 8 bytes at 1048912: ptr 1114112, len 4
5 copy 4 bytes out: [135, 135, 135, 255]
6 cabi_post_...#grayscale(1048912): the component frees its result

Running it: Wasmtime and jco

$ wasmtime run --invoke 'grayscale([200, 120, 40, 255])' photolab.wasm
[135, 135, 135, 255]
$ wasmtime run --invoke 'thumbnail([1, 2, 3, 4], {width: 1200, height: 800}, {width: 400, height: 267})' photolab.wasm
err("pixels must be 3840000 bytes, got 4")

Wasmtime 49.0.2 runs components directly, with no JavaScript. In browsers and Node, use jco (1.37.0) from the Bytecode Alliance. jco transpile photolab.wasm -o photolab turns the no_std component above into a plain core module (photolab.core.wasm, 7,139 bytes) plus a JavaScript ES module (photolab.js, 98.2 KiB before minifying) that holds the canonical ABI described above:

import { photo } from './photolab/photolab.js';

photo.grayscale(new Uint8Array([200, 120, 40, 255])); // Uint8Array [135, 135, 135, 255]
try {
  photo.thumbnail(new Uint8Array(16), { width: 1200, height: 800 }, { width: 400, height: 267 });
} catch (e) {
  console.log(e.message); // pixels must be 3840000 bytes, got 16
}

📌 WASI 0.2, 0.3, and runtime support

⚠️ Components that get refused, copied, or misnamed

TL;DR: The Component Model wraps core modules into components with a WIT contract: package, interface, world, and rich types (list, string, record, result, option, variant, resource), so modules from different languages can call each other without laying out memory by hand. The canonical ABI is the fixed rule set: a list<u8> becomes two i32s (pointer and length) copied in through cabi_realloc, the result is read from a return area and then freed with cabi_post_*; records are split into their fields. From Rust: wit-bindgen 0.62 with cargo build --target wasm32-wasip2 (50,511 bytes, WASI imports included), or wasm32-unknown-unknown plus wasm-tools component new (21,924 bytes). Inspect it with wasm-tools component wit. Wasmtime runs it directly (--invoke); browsers and Node don't know components (expected version 01 00 00 00), so jco 1.37.0 turns them into a core module plus JS. WASI 0.2 and 0.3 are built on components: wasi:cli/command, wasi:http/proxy, wasi:http/service.

⚡ Core modules only know numbers

Meaning: Only i32, i64, f32, f64 and references cross a core module's boundary. The Component Model wraps it into a component with a WIT contract and rich types (string, list, record, result), so modules from different languages can call each other without laying out memory by hand.

⚡ WIT: the contract

Write:

interface photo {
    record size {
        width: u32,
        height: u32,
    }

    grayscale: func(pixels: list<u8>) -> list<u8>;
}

world photolab {
    export photo;
}

Meaning: An interface groups functions and types, a record is an object with fixed fields, and a world states what the component exports and imports.

⚡ Canonical ABI: a list becomes two numbers

Guess first: in WIT, grayscale takes one list<u8>. What does its core function take?

Two i32s: a pointer and a length. Its result is one i32, the address of a return area holding the result's pointer and length.

Meaning: The canonical ABI rules are the same for every language: lists and strings are copied in through cabi_realloc, records are split into their fields, and the result is freed with cabi_post_*.

⚡ Browsers don't know components yet

Meaning: WebAssembly.compile rejects a component at byte 4: expected version 01 00 00 00, found 0d 00 01 00. Wasmtime runs it directly, and for browsers and Node, jco turns it into a core module plus JavaScript.

What you will learn