TExcelTAD
Home › WebAssembly › WASI

WASI

In a browser, JavaScript provides a module's imports. But WebAssembly is also used outside the browser: on servers, in the cloud, in edge functions and as a plug-in format. There the module needs files, clocks, random numbers, environment variables and standard output. WASI, the WebAssembly System Interface, standardises these imports so one .wasm file runs on any compatible runtime.

Capabilities, not ambient authority

A native program can open any file the user can. A WASI module can only use what the runtime explicitly grants it:

bash
wasmtime run app.wasm                      # no file system access at all
wasmtime run --dir ./data app.wasm         # may access ./data, nothing else
wasmtime run --env API_URL=https://… app.wasm

This capability-based design makes WASI attractive for running untrusted code: a plug-in that wasn't given a directory simply can't name one.

WASI versions

Version What it is
Preview 1 (wasi_snapshot_preview1) POSIX-like functions imported from one module: fd_write, fd_read, path_open, clock_time_get, random_get, proc_exit, … Supported everywhere
Preview 2 (WASI 0.2) rebuilt on the component model with WIT interfaces (wasi:cli, wasi:filesystem, wasi:http, wasi:sockets)
Preview 3 (WASI 0.3) adds native async to the component model

Hello from WASI, by hand

Preview 1's fd_write(fd, iovs, iovs_len, nwritten) writes a list of buffers (iovecs: pairs of pointer and length in memory) to a file descriptor; 1 is standard output. Here is a complete WASI program in WAT:

wat
(module
  (import "wasi_snapshot_preview1" "fd_write"
    (func $fd_write (param i32 i32 i32 i32) (result i32)))
  (import "wasi_snapshot_preview1" "proc_exit" (func $proc_exit (param i32)))
  (memory (export "memory") 1)
  (data (i32.const 16) "Hello from WASI!\n")
  (func (export "_start")
    (i32.store (i32.const 0) (i32.const 16))     ;; iovec.buf     = 16
    (i32.store (i32.const 4) (i32.const 17))     ;; iovec.buf_len = 17
    (drop (call $fd_write (i32.const 1) (i32.const 0) (i32.const 1) (i32.const 8)))
    (call $proc_exit (i32.const 0))))
bash
wat2wasm hello.wat -o hello.wasm
wasmtime hello.wasm              # Hello from WASI!

It can't run in our wat playground (whose host has no WASI imports), but WASI is just a set of imports, so a few lines of JavaScript can implement the two functions it needs. This is what browser WASI shims do:

js · try it yourself
const bytes = new Uint8Array([
  0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
  // types: (i32 i32 i32 i32)->i32, (i32)->(), ()->()
  0x01, 0x10, 0x03, 0x60, 0x04, 0x7f, 0x7f, 0x7f, 0x7f, 0x01, 0x7f, 0x60, 0x01, 0x7f, 0x00, 0x60, 0x00, 0x00,
  // imports: "wasi_snapshot_preview1" "fd_write" (type 0) and "proc_exit" (type 1)
  0x02, 0x46, 0x02,
  0x16, 0x77, 0x61, 0x73, 0x69, 0x5f, 0x73, 0x6e, 0x61, 0x70, 0x73, 0x68, 0x6f, 0x74, 0x5f,
  0x70, 0x72, 0x65, 0x76, 0x69, 0x65, 0x77, 0x31, 0x08, 0x66, 0x64, 0x5f, 0x77, 0x72, 0x69, 0x74, 0x65, 0x00, 0x00,
  0x16, 0x77, 0x61, 0x73, 0x69, 0x5f, 0x73, 0x6e, 0x61, 0x70, 0x73, 0x68, 0x6f, 0x74, 0x5f,
  0x70, 0x72, 0x65, 0x76, 0x69, 0x65, 0x77, 0x31, 0x09, 0x70, 0x72, 0x6f, 0x63, 0x5f, 0x65, 0x78, 0x69, 0x74, 0x00, 0x01,
  0x03, 0x02, 0x01, 0x02,                                         // _start has type 2
  0x05, 0x03, 0x01, 0x00, 0x01,                                   // memory: 1 page
  0x07, 0x13, 0x02, 0x06, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x02, 0x00,   // export "memory"
  0x06, 0x5f, 0x73, 0x74, 0x61, 0x72, 0x74, 0x00, 0x02,                     // export "_start"
  0x0a, 0x21, 0x01, 0x1f, 0x00,
  0x41, 0x00, 0x41, 0x10, 0x36, 0x02, 0x00,                       // i32.store [0] = 16
  0x41, 0x04, 0x41, 0x11, 0x36, 0x02, 0x00,                       // i32.store [4] = 17
  0x41, 0x01, 0x41, 0x00, 0x41, 0x01, 0x41, 0x08, 0x10, 0x00, 0x1a,   // fd_write(1, 0, 1, 8); drop
  0x41, 0x00, 0x10, 0x01, 0x0b,                                   // proc_exit(0); end
  // data: "Hello from WASI!\n" at 16
  0x0b, 0x17, 0x01, 0x00, 0x41, 0x10, 0x0b, 0x11,
  0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x66, 0x72, 0x6f, 0x6d, 0x20, 0x57, 0x41, 0x53, 0x49, 0x21, 0x0a,
]);

class ExitSignal { constructor(code) { this.code = code; } }
let memory;
const stdout = [];

const wasi = {
  fd_write(fd, iovs, iovsLen, nwrittenPtr) {
    const view = new DataView(memory.buffer);
    let written = 0;
    for (let i = 0; i < iovsLen; i++) {
      const ptr = view.getUint32(iovs + i * 8, true);
      const len = view.getUint32(iovs + i * 8 + 4, true);
      const chunk = new TextDecoder().decode(new Uint8Array(memory.buffer, ptr, len));
      if (fd === 1) stdout.push(chunk);
      written += len;
    }
    view.setUint32(nwrittenPtr, written, true);
    return 0;                                   // errno 0 = success
  },
  proc_exit(code) { throw new ExitSignal(code); },   // unwind out of Wasm
};

const { instance } = await WebAssembly.instantiate(bytes, { wasi_snapshot_preview1: wasi });
memory = instance.exports.memory;
try {
  instance.exports._start();
} catch (e) {
  if (!(e instanceof ExitSignal)) throw e;
  console.log('exit code:', e.code);
}
console.log('stdout:', JSON.stringify(stdout.join('')));
console.log('bytes written:', new DataView(memory.buffer).getUint32(8, true));
exit code: 0
stdout: "Hello from WASI!\n"
bytes written: 17

The shim reads the iovec at address 0, decodes the 17 bytes at address 16, and stores the count at address 8. Node.js ships a full implementation as node:wasi, and browser libraries such as @bjorn3/browser_wasi_shim do the same.

The iovec layout

An iovec array is just structs in memory. Here two buffers are written with a single call: our playground's console.str stands in for the fd_write loop:

wat · try it yourself
(module
  (import "console" "str" (func $print (param i32 i32)))
  (memory (export "memory") 1)
  (data (i32.const 100) "first chunk")
  (data (i32.const 200) "second chunk")

  ;; a mini fd_write: walk $count iovecs at $iovs, print each, return total bytes
  (func $write_all (param $iovs i32) (param $count i32) (result i32)
    (local $total i32)
    (block $done (loop $next
      (br_if $done (i32.eqz (local.get $count)))
      (call $print (i32.load (local.get $iovs)) (i32.load offset=4 (local.get $iovs)))
      (local.set $total (i32.add (local.get $total) (i32.load offset=4 (local.get $iovs))))
      (local.set $iovs (i32.add (local.get $iovs) (i32.const 8)))
      (local.set $count (i32.sub (local.get $count) (i32.const 1)))
      (br $next)))
    (local.get $total))

  (func (export "main") (result i32)
    (i32.store (i32.const 0) (i32.const 100))  (i32.store (i32.const 4) (i32.const 11))
    (i32.store (i32.const 8) (i32.const 200))  (i32.store (i32.const 12) (i32.const 12))
    (call $write_all (i32.const 0) (i32.const 2))))
first chunk
second chunk
23

Compiling for WASI

You rarely write WASI calls by hand; the language's standard library does it:

bash
# Rust
rustup target add wasm32-wasip1
cargo build --target wasm32-wasip1 --release
wasmtime target/wasm32-wasip1/release/app.wasm

# C with wasi-sdk
$WASI_SDK/bin/clang -O2 hello.c -o hello.wasm
wasmtime hello.wasm

# Go
GOOS=wasip1 GOARCH=wasm go build -o app.wasm

println!, printf and fmt.Println all end up calling fd_write.

Test yourself

What is WASI?

  1. A browser API
  2. A standard set of system-interface imports (files, clocks, stdout…) for running Wasm outside the browser
  3. A new instruction set
  4. A JavaScript framework

Why can't a WASI module read /etc/passwd by default in Wasmtime?

  1. Wasm can't do I/O
  2. Access is capability-based: only directories granted with --dir are visible
  3. The file is encrypted
  4. WASI only supports network access

What does fd_write take to describe the data to write?

  1. A JS string
  2. A pointer to an array of iovecs (pointer + length pairs) in linear memory
  3. A file name
  4. An externref