Files
unkernel/js/node/wasi.ts
Pooya Parsa b5b75b53de Run WASI programs from the guest on the host's wasm engine (prototype)
binfmt_misc hands a wasm module to kwwasi (kernel/guest/kwwasi.c), which
connects to the host over AF_VSOCK port 1021 and serves the program's
file I/O with its own descriptors, cwd and credentials. The host
(js/core/wasi-exec.ts, serveWasiPrograms(), the CLI's --wasi) compiles
the module once and runs each program in a worker of its own
(js/core/wasi-program.ts) with WASI preview 1, or preview 0 adapted.
Requests cross through a SharedArrayBuffer where one can be used, else
with JSPI and messages. kwwasi sends a module only when the host has not
compiled it for that file, resolves paths against the cwd or / by what
exists, and maps open flags from their asm-generic values to the
guest's.

alpine.sh builds kwwasi and kw-binfmt.sh registers it; no image with
them has been built yet, so test/wasi-binfmt.ts brings kwwasi in through
a mount.
2026-11-19 07:08:32 +00:00

37 lines
1.7 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// The guest's WASI programs on Node (core/wasi-exec.ts): each in a
// worker_threads Worker running wasi-entry.ts, started by the owner of
// vm.vsock. serveWasiPrograms() is core's with this spawner.
//
// From source, Node starts the worker from wasi-entry.ts itself. `pnpm
// build` (build.config.ts, WORKERS) replaces the URL below (it must appear
// exactly once in this file) with the bundled entry as a string literal.
import { Worker } from "node:worker_threads";
import type { Vsock } from "../core/vsock.ts";
import { serveWasiProgramsWith, type WasiExecOptions, type WasiExecServer } from "../core/wasi-exec.ts";
import type { WasiFromProgram, WasiProgramEndpoint } from "../core/wasi-program.ts";
export function spawnNodeWasi(): WasiProgramEndpoint {
const entry: URL | string = new URL("./wasi-entry.ts", import.meta.url);
const opts = { name: "unkernel-wasi" };
const w = typeof entry === "string" ? new Worker(entry, { ...opts, eval: true }) : new Worker(entry, opts);
// A program never keeps the process alive: it belongs to the machine, whose end ends it.
w.unref();
return {
post: (msg, transfer) => w.postMessage(msg, transfer),
listen(h) {
w.on("message", (m: WasiFromProgram) => h.message(m));
w.on("error", h.error);
w.on("exit", () => h.exit());
},
terminate: () => void w.terminate(),
};
}
/** Run the guest's WASI programs (kwwasi, vsock port 1021) on this host, each in a worker thread. */
export function serveWasiPrograms(vsock: Vsock, opts: WasiExecOptions = {}): WasiExecServer {
return serveWasiProgramsWith(vsock, { ...opts, spawn: spawnNodeWasi });
}