mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-05 23:10:07 +08:00
999 lines
48 KiB
Markdown
999 lines
48 KiB
Markdown
<h1 align="center"><img alt="unkernel" src="assets/logo-wordmark.svg" width="400"></h1>
|
|
|
|
**A real Linux kernel, compiled to WebAssembly. It boots to a shell in less than a second.**
|
|
|
|
<p align="center">
|
|
<a href="https://unkernel.dev/"><b>Try it</b></a> ·
|
|
<a href="#-performance">Performance</a> ·
|
|
<a href="#-a-real-kernel">Features</a> ·
|
|
<a href="#-run-it-from-the-terminal">CLI</a> ·
|
|
<a href="#-how-it-works">How it works</a> ·
|
|
<a href="#-benchmarks">Benchmarks</a> ·
|
|
<a href="#-use-it-from-javascript">JavaScript SDK</a>
|
|
</p>
|
|
|
|
unkernel is Linux 7.x built as a single wasm module with a real MMU. The
|
|
kernel (syscalls, scheduler, memory management, ext4, TCP/IP) is compiled
|
|
code, not emulated, so programs get Linux's own behavior down to the edge
|
|
cases. Only user programs are emulated: unmodified aarch64 (arm64) Linux
|
|
binaries, so Alpine and Debian packages run as they are.
|
|
|
|
[Open a page](#-try-it-in-the-browser) and you have a Linux machine with a
|
|
shell, a package manager, a persistent disk, internet access, and a screen
|
|
with sound. It runs entirely on your device, with nothing to install and no
|
|
server, and every layer is open source. [How it works](#-how-it-works)
|
|
explains the design.
|
|
|
|
<p align="center">
|
|
<img alt="Linux programs run on kwemu, an aarch64 CPU linked into the Linux kernel, built together into unkernel.wasm, which talks to the JavaScript SDK" src="assets/architecture.svg" width="760">
|
|
</p>
|
|
|
|
## ⚡ Performance
|
|
|
|
Much of what makes a system feel slow lives in the kernel: starting
|
|
processes, syscalls, page faults, file and network I/O. In unkernel that
|
|
path runs at wasm speed.
|
|
|
|
- **Boot**: the kernel reaches `/init` about 70 ms after it starts, and the Alpine
|
|
prompt appears 0.3 s after `node` launches. The page downloads about
|
|
10 MB, and Alpine boots in 48 MiB of guest memory.
|
|
- **Syscalls at close to native cost**: `getppid` takes about 170 ns (110
|
|
native, 1.7 µs under qemu-system), a 64-byte `read` about 170 ns (160
|
|
native).
|
|
- **fork at native speed**: fork + exit + wait takes about 60 µs, against
|
|
about 70 µs natively and 1.2 ms under qemu-system.
|
|
- **A JIT for user code**: hot aarch64 code, including the AES, PMULL and
|
|
SHA instructions OpenSSL uses, is compiled to wasm while it runs. With
|
|
it a shell loop runs 1.6 times and `sort` 2.3 times as fast as on the
|
|
interpreter alone, and OpenSSL in the guest does AES-128-GCM at about
|
|
100 MB/s and SHA-256 at about 160 MB/s.
|
|
|
|
The syscall and fork numbers were measured on 2026-11-14 (with the
|
|
riscv64 user space the project started with; the path through the kernel
|
|
is the same), the JIT numbers on 2026-11-18. CPU-heavy programs are well
|
|
behind native: `apk search` over the main index takes about 0.8 s, `apk
|
|
add python3` about 3.4 s. [Benchmarks](#-benchmarks) has the full numbers.
|
|
|
|
## 🐧 A real kernel
|
|
|
|
Anything a program relies on, from `/proc` and `epoll` to cgroups and
|
|
overlayfs, behaves as it does on a server, because it runs the same code.
|
|
|
|
- **A real MMU** (`arch/wasm` with Sv48 page tables): `fork`, `mmap`,
|
|
copy-on-write, shared memory, threads and signals behave as they do on
|
|
hardware. This is not a NOMMU port where programs are limited to `vfork`.
|
|
- **Linux's own file systems**: ext4, overlayfs, tmpfs, loop devices, FUSE,
|
|
and 9p, which [mounts file systems](#mount-host-files) your program serves
|
|
from the host. The root file system is an overlay: a read-only distro
|
|
image under your changes, which go to a persistent ext4 disk, so
|
|
everything you change survives a reload, and a safe mode recovers a
|
|
system you broke.
|
|
- **Linux's own TCP/IP stack**, with DHCP and DNS, reaching the internet
|
|
through your host's sockets or a Wisp proxy
|
|
([Add a network](#add-a-network)).
|
|
- **cgroups, namespaces, userfaultfd, fanotify and TUN**: enough for
|
|
systemd to boot Ubuntu 26.10 to `multi-user.target`.
|
|
- **Devices**: a [framebuffer (`/dev/fb0`), evdev keyboard, mouse and touch,
|
|
sound and a microphone through ALSA and `/dev/dsp`, a V4L2
|
|
camera](#display-input-and-sound), [AF_VSOCK](#talk-over-vsock),
|
|
[shared memory](#share-memory) with the host, a virtio-gpu with [guest
|
|
GL](#gl-in-the-guest-browsers) and [Vulkan](#vulkan-in-the-guest-browsers-with-webgpu)
|
|
on the page's WebGL2 and WebGPU, [VA-API video](#video-in-the-guest-browsers-with-webcodecs)
|
|
on WebCodecs, and [serial ports](#serial-ports), [Bluetooth](#bluetooth)
|
|
and [USB devices](#usb-devices) from Web Serial, Web Bluetooth and WebUSB.
|
|
- **aarch64 user space**: ARMv8.0-A with FP and AdvSIMD plus the AES,
|
|
PMULL, SHA1, SHA2, SHA512, SHA3, CRC32 and LSE atomics extensions, so
|
|
distribution binaries and
|
|
OpenSSL's hardware AES, GHASH and SHA paths run unchanged. aarch64 is a
|
|
first-class port of
|
|
every distribution, so their full, current package archives are
|
|
available.
|
|
|
|
[Known limits](#-known-limits) lists what is still missing.
|
|
|
|
## 🧰 What you can do with it
|
|
|
|
- **[Carry a Linux shell anywhere](#-try-it-in-the-browser).** Alpine Linux
|
|
3.24 runs in Chrome, Edge, Firefox and Safari, including on phones. Install
|
|
anything with `apk add` from Alpine's regular mirrors. Type a command that
|
|
isn't installed, such as `htop`, and its package is installed for you. apk
|
|
starts with only the `main` repository, because it is about 4x faster that
|
|
way; `community` is added the first time a command needs it.
|
|
- **Run real runtimes and tools**: Node and npm, Python, OpenSSL, curl and
|
|
`wget`, straight from the distribution. Debian 13 boots the same way as
|
|
Alpine (`--distro debian`), with apt. x86-64 and i386 binaries run too,
|
|
through box64 on Debian and qemu-user on Alpine.
|
|
- **Run desktop apps on the GPU** (Debian, in the browser): Wayland and X11
|
|
apps open as windows of the page, such as Firefox, Chromium, Zed and Xfce.
|
|
The guest's Mesa renders on the page's WebGL2 and its Vulkan on WebGPU,
|
|
enough for 3D games and for llama.cpp and Ollama, and video decodes in the
|
|
browser's own decoder through VA-API. The page's launcher installs and
|
|
starts each app.
|
|
- **Use real hardware from a page**: boards on [serial
|
|
ports](#serial-ports) (esptool, arduino-cli, MicroPython through Thonny),
|
|
BLE devices through BlueZ ([Bluetooth](#bluetooth)), and [USB
|
|
devices](#usb-devices) through libusb (`adb`, `fastboot`, `dfu-util`), in
|
|
Chromium-based browsers.
|
|
- **[Write graphics and sound programs](#display-input-and-sound)** against
|
|
`/dev/fb0`, evdev and ALSA. Try `glimmer`, a tiny game with sound.
|
|
- **[Embed Linux in your app](#-use-it-from-javascript)** with a
|
|
zero-dependency TypeScript SDK, published as
|
|
[`unkernel`](https://www.npmjs.com/package/unkernel). The same kernel file
|
|
runs in Node and in every supported browser, optionally [in a
|
|
worker](#run-it-in-a-worker). [Disks](#add-disks) can be local ext4 images,
|
|
http(s) images fetched by range, or a persistent disk in OPFS or
|
|
IndexedDB. [Save a running machine](#save-and-restore-a-machine) and resume it
|
|
later, and [join a tailnet](#join-a-tailnet) from Node or a page. The SDK
|
|
is MIT-licensed, and there is no closed engine or license key behind it, so
|
|
you can ship it in your product and host it wherever you like.
|
|
- **Talk to the guest** through [terminal sessions](#run-programs), each
|
|
with its own pty and shell, [host directories and in-memory file
|
|
systems](#mount-host-files) mounted in the guest, [vsock byte
|
|
streams](#talk-over-vsock) and [zero-copy shared memory](#share-memory),
|
|
with no network in between. Guest programs can call your JavaScript as
|
|
[host commands](#host-commands).
|
|
- **Script and test**: [the CLI](#-run-it-from-the-terminal) types input on a
|
|
schedule, stops on a timeout, and reports how the guest ended in its exit
|
|
code.
|
|
|
|
## 🌐 Try it in the browser
|
|
|
|
Open **[unkernel.dev](https://unkernel.dev/)**. A desktop appears after a
|
|
download of about 10 MB, with a shell in its Terminal window. Your changes
|
|
are saved in the browser. The Dock opens the apps (so do ⌘K on a Mac and
|
|
Ctrl-Shift-O elsewhere); Settings has the options and export or reset for
|
|
your disk, System the diagnostics. Ctrl-A n (⌘J n on a Mac) or `+` on
|
|
a Terminal window's tabs opens another terminal with its own shell, up to
|
|
9; Ctrl-A (⌘J) and a digit switches, and Ctrl-A ? lists every shortcut. The
|
|
wallpaper is a random photo from [Lorem Picsum](https://picsum.photos/)
|
|
by default, so the page fetches one from picsum.photos on every load;
|
|
the built-in wallpaper or a preset (Settings > Desktop) stops that.
|
|
|
|
The page takes a few URL parameters:
|
|
|
|
| Parameter | Does |
|
|
| --- | --- |
|
|
| `?mem=512` | Guest memory in MiB |
|
|
| `?append=...` | Extra kernel command line |
|
|
| `?net=0` | Boot without a network |
|
|
| `?wisp=wss://...` | Use your own [Wisp](https://github.com/MercuryWorkshop/wisp-protocol) proxy |
|
|
| `?jit=0` | Interpreter only |
|
|
| `?data=0` | No persistent disk, a fresh system every time |
|
|
| `?worker=0` | Run the kernel on the page's thread (default: in a Web Worker where the page is cross-origin isolated) |
|
|
| `?cpus=2` | Boot on that many CPUs, each in a Web Worker (default: half the device's threads, up to 4 on desktops and 2 in Firefox and on phones, where the page has the SMP kernel and is cross-origin isolated; `?cpus=1`: one CPU) |
|
|
| `?gl=0` | No guest GL (on by default on Debian: the guest's Mesa renders through your browser's WebGL2, see below) |
|
|
|
|
On Debian the guest gets a GPU (`/dev/dri`, Settings, Guest GL): Mesa's
|
|
virgl driver draws through your browser's WebGL2. The renderer behind it
|
|
is downloaded only when a guest program first uses GL; the Guest GL row
|
|
in System > Environment then names the GPU (a software renderer such as SwiftShader
|
|
is flagged). Mesa is installed in the guest, not shipped:
|
|
|
|
```sh
|
|
sudo apt-get install -y mesa-utils libegl-mesa0 libgles2 kmscube
|
|
eglinfo -B -p gbm # OpenGL ES renderer: virgl (<your GPU>)
|
|
kmscube # on the display (Enter ends it)
|
|
sudo apt-get install -y xvfb xauth glmark2-es2-x11
|
|
xvfb-run -a -s "-screen 0 640x480x24" glmark2-es2 # frame rates
|
|
```
|
|
|
|
Wayland apps show as windows on the page: `wland foot` (or the
|
|
launcher's foot tile) starts wland's relay in the guest and runs the app
|
|
against it; [wland](https://github.com/pithings/wland)'s compositor runs in
|
|
the page and reads the app's pixels straight from guest memory. Each app
|
|
window is a window of the page's desktop; Ctrl-A w (⌘J w on a Mac) switches between them
|
|
and the other windows.
|
|
|
|
```sh
|
|
sudo apt-get install -y foot fonts-dejavu-core
|
|
wland foot
|
|
```
|
|
|
|
Browsers can't open raw TCP sockets, so the page reaches the internet
|
|
through a Wisp proxy, unless `?wisp=` names
|
|
another. A guest's TCP connections go through it, and the proxy sees their
|
|
addresses and the bytes on the wire (an HTTPS stream is opaque to it, a plain
|
|
one is not). The default one accepts only known origins, so if you host the
|
|
page somewhere else, build it with `KW_WISP=wss://your-proxy/` (several,
|
|
comma-separated; a path such as `/wisp/` is on the page's own origin) or
|
|
point `?wisp=` at your own proxy.
|
|
|
|
| Browser | Status |
|
|
| --- | --- |
|
|
| Chrome / Edge 137+ (desktop and Android) | ✅ works |
|
|
| Firefox 153+ | ✅ works |
|
|
| Safari 27+ on macOS, any browser on iOS/iPadOS 27 | ✅ works |
|
|
| Anything without [JSPI](#-how-it-works) | the page tells you what's missing |
|
|
|
|
## 💻 Run it from the terminal
|
|
|
|
```sh
|
|
npx unkernel
|
|
```
|
|
|
|
This boots Alpine, with networking over your host's sockets. Press
|
|
**Ctrl-]** to quit. The package holds the kernel and a small base system;
|
|
the first run downloads the Alpine image (about 4 MB) from the GitHub
|
|
release of your version and keeps it in `~/.cache/unkernel`.
|
|
|
|
```sh
|
|
npx unkernel --distro debian # Debian 13 instead (about 57 MB, downloaded once)
|
|
npx unkernel --distro none # no distro: the base shell (busybox)
|
|
npx unkernel --data my-data.img # changes persist on a /data disk, created on first use
|
|
npx unkernel --display --sound # a framebuffer and a sound card
|
|
npx unkernel --mem 1024 --no-net # more memory, no network
|
|
npx unkernel --mount .:/work # this directory at /work in the guest (:ro for read-only)
|
|
npx unkernel --forward 8000:80 # host 127.0.0.1:8000 to port 80 in the guest
|
|
npx unkernel --timeout 60 --input '{8}uname -a\n{2}poweroff\n' # scripted: wait, type, wait, type
|
|
npx unkernel --help # everything else
|
|
```
|
|
|
|
Without `--data`, changes to the root file system are kept in memory and
|
|
gone at exit; with it, each distro keeps its own in `/data/distros/<name>/`.
|
|
`--distro` also takes an image file or an http(s) URL, and
|
|
`UNKERNEL_CACHE_DIR` moves the download cache.
|
|
|
|
Exit codes: 0 power off, 1 halt or boot failure, 2 restart, 124 timeout, 253
|
|
kernel panic, 254 wasm trap, 255 fatal error. The CLI is built on the
|
|
[JavaScript SDK](#-use-it-from-javascript): `--mount` uses its [host
|
|
mounts](#mount-host-files) and `--forward` its
|
|
[`vm.connect()`](#talk-over-vsock).
|
|
|
|
## 🔍 How it works
|
|
|
|
Most "Linux in the browser" projects take one of three approaches:
|
|
|
|
- **Emulate a whole PC**, kernel included. This is faithful but slow,
|
|
because every syscall and page fault goes through emulated hardware.
|
|
- **Emulate the CPU and reimplement the syscalls.** Programs run on an
|
|
emulated CPU, often with a JIT, and a runtime answers their syscalls, with
|
|
no Linux kernel at all. This is fast, but it covers only as much of Linux
|
|
as the runtime implements.
|
|
- **Compile programs to wasm**, and run them on a kernel without an MMU or
|
|
on a runtime that provides POSIX calls. This is fast, but native programs
|
|
have to be rebuilt, and `fork` and anything else that needs an MMU breaks
|
|
or is approximated.
|
|
|
|
unkernel keeps the best of each: the real Linux kernel, running at native
|
|
wasm speed, under unmodified binaries with a real MMU.
|
|
|
|
| Approach | Kernel | User space | MMU |
|
|
| --- | --- | --- | --- |
|
|
| Whole-machine emulators (v86, JSLinux, container2wasm, QEMU's wasm build) | Linux, emulated | unmodified, emulated | emulated |
|
|
| Syscall emulators | none: a runtime reimplements the syscalls | unmodified, emulated | the runtime's own |
|
|
| POSIX runtimes for wasm (Wasmer WASIX, WebContainers, BrowserPod) | none: a runtime provides the syscalls | rebuilt for wasm, or JavaScript | none |
|
|
| Linux without an MMU (linux-wasm, tombl/linux, WasmLinux (LKL)) | Linux, native wasm | rebuilt for wasm | none |
|
|
| **unkernel** | **Linux, native wasm** | **unmodified aarch64, emulated** | **real page tables** |
|
|
|
|
The kernel is compiled straight to WebAssembly. User programs run on
|
|
**kwemu**, an aarch64 CPU written in Zig and linked into the kernel. kwemu
|
|
walks the kernel's own page tables, so memory management is done by the
|
|
real Linux code.
|
|
|
|
When a program makes a syscall, kwemu returns to the kernel, which handles
|
|
it as native wasm. There is no emulated trap and no emulated kernel mode in
|
|
between. Task switches use JSPI (`WebAssembly.Suspending`), so the kernel
|
|
gets real stacks that it can suspend and resume.
|
|
|
|
kwemu runs blocks of guest code decoded once into compact ops (what has
|
|
no op runs through a reference interpreter), and hot user code goes
|
|
through a second tier: a JIT that compiles those blocks to wasm modules
|
|
at run time, with output that matches the interpreter bit for bit.
|
|
[Benchmarks](#-benchmarks) shows what each tier costs.
|
|
|
|
Devices are small paravirtual drivers that talk to the JavaScript host:
|
|
[block](#add-disks) (kwblk), [network](#add-a-network) (kwnet, with a
|
|
user-mode TCP/IP stack in JS), [display, input and
|
|
sound](#display-input-and-sound) (kwfb, kwinput, kwsnd), a
|
|
[camera](#display-input-and-sound) (kwcam, V4L2), a
|
|
[virtio-gpu](#gl-in-the-guest-browsers) (kwvirtio),
|
|
[vsock](#talk-over-vsock) (kwvsock), [shared memory](#share-memory)
|
|
(kwshm), [serial ports](#serial-ports) (kwserial),
|
|
[Bluetooth](#bluetooth) (kwbt, an HCI transport) and a [USB host
|
|
controller](#usb-devices) (kwusb).
|
|
|
|
### 📊 Benchmarks
|
|
|
|
The design helps most with syscalls. These were measured under Node:
|
|
|
|
<p align="center">
|
|
<img alt="Time per operation for native, qemu-user, qemu-system and unkernel: getppid 110, 320, 1662 and 172 ns; read 64 B from /dev/zero 161, 481, 2247 and 172 ns; pipe write + read 417, 1032, 7256 and 482 ns; fork + exit + wait 73, 537, 1178 and 57 µs" src="assets/performance.svg" width="760">
|
|
</p>
|
|
|
|
In this test (2026-11-14) fork is faster than native. Pure computation is
|
|
slower. kwemu's decoded-op interpreter runs integer code at about 250-300
|
|
million guest instructions per second under Node (2026-11-17), and the
|
|
JIT makes real Alpine work 1.6 to 2.3 times as fast as that (2026-11-18:
|
|
an ash loop 2.5 s against 4.0 s, `seq 100000 | sort -r` 3.1 s against
|
|
7.1 s, `seq 250000 | gzip | gunzip` 3.5 s against 6.5 s), which is still
|
|
well behind native.
|
|
|
|
### 🚧 Known limits
|
|
|
|
- The SDK and CLI boot one CPU by default; the page boots several where
|
|
it can (`?cpus=`). A snapshot of several CPUs (SMP), and so a session
|
|
suspended on the page, resumes only on as many.
|
|
- No IPv6, no ICMP beyond the gateway, no UDP on the page beyond DHCP and
|
|
DNS (its Wisp server carries none), no inbound network connections
|
|
([`vm.connect()`, `vm.fetch()`](#talk-over-vsock) and `--forward` reach
|
|
guest servers over vsock instead), except with tailnet peers when the
|
|
network spec has `tailscale` (`--tailscale-authkey`), and through its
|
|
exit node when one is chosen (`exitNode`, `--tailscale-exit-node`).
|
|
- Over `wispBackend()`, a guest's half-close (`shutdown(SHUT_WR)`) does
|
|
not reach the server, so a client that waits for the server to see
|
|
end of file before it answers hangs (`echo hi | nc HOST PORT` against
|
|
such a server, an HTTP/1.0 body without Content-Length). Names resolve
|
|
to placeholder addresses in 198.18.0.0/15: every name resolves, a bad
|
|
one fails at connect time, and one address stands for each name. Pass
|
|
`lookup` for real answers, or use a backend of your own
|
|
([Add a network](#add-a-network)).
|
|
- No hardware breakpoints or watchpoints: `gdb`'s watchpoints are
|
|
software ones, which single-step the program.
|
|
- Code that runs only a few times (a large program's startup, such as
|
|
`npm`'s) stays on the interpreter, and FP and AdvSIMD floating point
|
|
run through it even inside compiled code. Without wasm SIMD in the host
|
|
engine, OpenSSL's AES and SHA paths run on the interpreter too.
|
|
- A wasm trap in the kernel ends the session.
|
|
|
|
## 🧩 Use it from JavaScript
|
|
|
|
```sh
|
|
npm install unkernel
|
|
```
|
|
|
|
```js
|
|
import { createKernel, fetchDistro } from "unkernel";
|
|
|
|
const vm = await createKernel({ distro: await fetchDistro("alpine") }); // Alpine, no network
|
|
vm.onOutput((bytes) => process.stdout.write(bytes));
|
|
vm.write("uname -a; poweroff\n");
|
|
|
|
const { code, kind } = await vm.exited; // 0, "halt"
|
|
```
|
|
|
|
Importing `unkernel` picks the Node or browser entry automatically, and
|
|
`unkernel/node` or `unkernel/web` selects one explicitly. The kernel ships
|
|
in the package (`unkernel/unkernel.wasm`) and loads from next to the entry,
|
|
streamed and compiled while it downloads. It carries a small base system
|
|
that mounts a distro image read-only under an overlay root and runs its
|
|
init; `createKernel()` without `distro` boots the base shell
|
|
(busybox and unkernel's tools), which needs no download.
|
|
|
|
The distro images are not in the package. On Node, `fetchDistro("alpine")`
|
|
(or `"debian"`) downloads one once from the GitHub release of the
|
|
package's version, checks it against the release's `distros.json` (size and
|
|
SHA-256), keeps it in `~/.cache/unkernel` (`UNKERNEL_CACHE_DIR`) and
|
|
returns its path; nothing else in the SDK downloads anything. In the
|
|
browser, host the image yourself (it is read lazily with range requests)
|
|
and pass its URL:
|
|
|
|
```js
|
|
const vm = await createKernel({ distro: "/distros/alpine.erofs" });
|
|
```
|
|
|
|
Changes to the root file system stay in memory, unless a persistent data
|
|
disk (labelled `kwdata`) is attached: then each distro keeps them in
|
|
`/data/distros/<name>/` on it.
|
|
|
|
### Add a network
|
|
|
|
```js
|
|
import { createKernel, directBackend, wispBackend } from "unkernel";
|
|
|
|
await createKernel({ net: directBackend() }); // Node: host sockets
|
|
await createKernel({ net: wispBackend("wss://wisp.example/") }); // anywhere: your Wisp proxy
|
|
```
|
|
|
|
Networking is off unless you pass `net`. Any object with `connect` and
|
|
`lookup` methods can carry the guest's TCP and DNS (and with a `udp`
|
|
method its UDP), so you can write your own backend; `directBackend()` and
|
|
`wispBackend()` carry UDP too (Wisp where the server does). Wisp carries no DNS and
|
|
no half-close ([Known limits](#-known-limits)); `wispBackend(servers, {
|
|
lookup })` takes a resolver of your own, such as DNS over HTTPS, for real
|
|
addresses. With `hostLoopback` in the network spec, the guest reaches the
|
|
host's 127.0.0.1 at the gateway, 10.0.2.2.
|
|
|
|
```js
|
|
const net = fetchRoutes(wispBackend("wss://wisp.example/"), {
|
|
"deb.debian.org": "https://debian-mirror.example", // http://deb.debian.org/x → https://debian-mirror.example/x
|
|
"api.local": (req) => Response.json({ ok: true }), // your own handler
|
|
});
|
|
```
|
|
|
|
`fetchRoutes(inner, routes)` answers the guest's plain-HTTP requests to the
|
|
named hosts with the host's `fetch()` and passes everything else to `inner`
|
|
(`undefined`: nothing else). The page uses it to fetch Debian packages from
|
|
a CORS mirror instead of through its Wisp proxy.
|
|
|
|
### Join a tailnet
|
|
|
|
```js
|
|
let state = load(); // the node's keys from an earlier run, if any
|
|
const vm = await createKernel({
|
|
net: {
|
|
kind: "net",
|
|
backend: { kind: "direct" }, // or { kind: "wisp", servers: "wss://wisp.example/" }
|
|
tailscale: { authKey: "tskey-auth-...", state, hostname: "box", exitNode: "my-server" },
|
|
},
|
|
onTailscale(e) {
|
|
if (e.type === "state") save(e.state); // keep it secret: it is the node's identity
|
|
if (e.type === "authurl") console.log("log in at", e.url); // no auth key: interactive login
|
|
if (e.type === "status") console.log(e.status.state, e.status.addresses);
|
|
},
|
|
});
|
|
vm.tailscale.setExitNode(null); // back to the backend; a name picks another
|
|
```
|
|
|
|
With `tailscale` in the network spec the guest joins your
|
|
[Tailscale](https://tailscale.com) network (or a
|
|
[headscale](https://github.com/juanfont/headscale) one: `controlURL`) from
|
|
Node or a browser. The client is JavaScript inside the SDK, loaded only
|
|
when the option is used: it speaks to the coordination server over a
|
|
WebSocket and carries WireGuard over Tailscale's DERP relays, so it needs
|
|
no UDP and no helper on the host, and every packet is relayed. The guest
|
|
gets its 100.x address on a `tailscale0` interface, reaches the tailnet's
|
|
devices by address or MagicDNS name, and they reach servers in the guest.
|
|
Everything else keeps going through `backend`.
|
|
|
|
`exitNode` (a device's name or 100.x address) sends all the guest's other
|
|
IPv4 traffic and its DNS through that device instead of the backend. The
|
|
device has to advertise itself as an exit node, be approved, and the
|
|
tailnet's policy has to let this node use it; `status.exitNodes` lists
|
|
the devices that qualify and `status.exitNode` says whether the chosen
|
|
one is usable. While it is not (offline, not found, not approved) that
|
|
traffic is refused, never sent through the backend. `acceptRoutes` adds
|
|
the peers' subnet routes. There is no IPv6 and the tunnel's MTU is 1280.
|
|
|
|
From the terminal, `npx unkernel --tailscale-authkey KEY
|
|
--tailscale-state ts.json --tailscale-exit-node my-server` does the same
|
|
(`--help` lists the `--tailscale-*` options); on the page it is in
|
|
Settings, Network, Tailscale.
|
|
|
|
### Add disks
|
|
|
|
```js
|
|
import { createImageFromKwsparse, createKernel, bundledBoot, openDisk } from "unkernel/node";
|
|
|
|
const vm = await createKernel({
|
|
distro,
|
|
disks: [await openDisk("data.img")], // the data disk, or any ext4 image or https:// URL
|
|
});
|
|
```
|
|
|
|
`createImageFromKwsparse(file, template)` makes a new data disk from the
|
|
template the kernel carries (`bundledBoot(module).datadisk`). In the
|
|
browser, `openHttpDisk(url)` keeps your writes in IndexedDB and
|
|
`openDataDisk()` gives you the persistent data disk that
|
|
[the page](#-try-it-in-the-browser) uses, in IndexedDB or, several times
|
|
faster, in the origin private file system (`backend: "opfs"`, for a kernel
|
|
in a worker: `{ kind: "data", template: "bundled", backend: "opfs" }`);
|
|
`migrateDataDisk()` moves one from IndexedDB to OPFS. Anything that implements
|
|
`BlockDevice` works too, and a disk of your own can be the root:
|
|
`cmdline: "console=hvc0 root=/dev/wda rw"` with `initrd: null`.
|
|
|
|
### Console and lifecycle
|
|
|
|
```js
|
|
// vm.output: a ReadableStream, everything since boot and then live
|
|
vm.output.pipeTo(new WritableStream({ write: (b) => process.stdout.write(b) }));
|
|
vm.write("ls /\n"); // or write to vm.input, a WritableStream
|
|
vm.resize(120, 40); // the foreground program gets SIGWINCH
|
|
|
|
await vm.sync(); // flush the guest's disks
|
|
console.log(vm.stats()); // memory, disk, network and JIT counters
|
|
const { code, reason, kind } = await vm.exited; // stop() parks it at once
|
|
```
|
|
|
|
### Run programs
|
|
|
|
```js
|
|
const { stdout, exitCode } = await vm.exec("uname", ["-a"]);
|
|
const { stdout: sum } = await vm.exec("sha256sum", [], { input: "hello" });
|
|
```
|
|
|
|
`exec()` runs a program on pipes and resolves with `{ stdout, stderr,
|
|
exitCode, signal }`, also for a non-zero exit. Pass `encoding: "buffer"`
|
|
for bytes, and `cwd` or `env` as you would to `child_process`. On the
|
|
distro images programs run as the user `user` (uid 1000, in
|
|
`/home/user`), who has `sudo` without a password; pass `user: "root"` (or
|
|
another name or uid) to run as someone else. The base shell is root's.
|
|
|
|
```js
|
|
const sh = await vm.spawn(); // a login shell on its own pty
|
|
sh.output.pipeTo(new WritableStream({ write: (b) => process.stdout.write(b) }));
|
|
await sh.write("cat /etc/alpine-release; exit\n");
|
|
console.log(await sh.ended); // { type: "exit", code: 0 }
|
|
```
|
|
|
|
`spawn(file, args, { cols, rows })` runs a program on a pty, in the
|
|
zigpty / node-pty shape, with `resize()`, `kill(signal)` and `close()` (a
|
|
hangup). Run as many as you like. Keep reading `output`: the guest program
|
|
waits while nobody does.
|
|
|
|
```js
|
|
const gz = await vm.spawn("gzip", ["-c"], { pty: false });
|
|
gz.stderr.cancel(); // read both outputs, or cancel one
|
|
const zipped = new Response(gz.stdout).bytes();
|
|
await new Response("hello\n").body.pipeTo(gz.stdin); // then EOF
|
|
console.log((await zipped).length);
|
|
```
|
|
|
|
With `pty: false` the program gets pipes: `stdin`, `stdout` and `stderr`
|
|
web streams, byte for byte.
|
|
|
|
### Host commands
|
|
|
|
```js
|
|
const vm = await createKernel({
|
|
commands: {
|
|
hello: (c) => `hello ${c.args.join(" ")} from the host\n`,
|
|
upper: (c) => c.stdin.pipeThrough(new TextDecoderStream())
|
|
.pipeThrough(new TransformStream({ transform: (s, out) => out.enqueue(s.toUpperCase()) }))
|
|
.pipeTo(c.stdout),
|
|
fail: () => ({ exitCode: 3 }),
|
|
},
|
|
});
|
|
await vm.exec("sh", ["-c", "hello world | upper; fail; echo $?"]); // "HELLO WORLD FROM THE HOST\n3\n"
|
|
await vm.addCommand("notify", (c) => console.log(c.args)); // at any time; removeCommand() too
|
|
```
|
|
|
|
The reverse of `exec()`: each name becomes `/run/kw/bin/NAME` in the guest,
|
|
first on `PATH`, and a guest process that runs it is a real process whose
|
|
arguments, environment, working directory and stdio (web streams; stdin is
|
|
read only as you read it) the function gets, with a `signal` that aborts when
|
|
it is killed. What the function returns ends it: nothing or a number is
|
|
its exit status, a string or bytes go to its stdout, `{ signal: "TERM" }`
|
|
kills it, and a throw prints the message and exits 1.
|
|
|
|
### Mount host files
|
|
|
|
```js
|
|
import { createKernel, MemoryFs, nodeFs } from "unkernel";
|
|
|
|
const mem = new MemoryFs();
|
|
mem.onChange((c) => console.log(c.type, c.path)); // what the guest changed
|
|
|
|
const vm = await createKernel({
|
|
mounts: {
|
|
"/mnt/host": { "hello.txt": "hi", dir: { "a.bin": bytes }, "now.txt": () => Date() },
|
|
"/mnt/mem": mem,
|
|
},
|
|
});
|
|
await vm.exec("cp", ["/etc/os-release", "/mnt/mem/"]);
|
|
console.log(mem.readText("/os-release"));
|
|
|
|
const work = await vm.mount("/work", nodeFs("."), { readOnly: true }); // Node only
|
|
await work.unmount();
|
|
```
|
|
|
|
A file system is a plain object tree (a function is a computed file,
|
|
evaluated once per open), a `MemoryFs` you read and write from the host,
|
|
`nodeFs(dir)`, or your own `Fs`: `getattr`, `readdir` and `open` by path,
|
|
sync or async, plus whichever change methods you want. Mounts are served
|
|
over 9p on vsock. Each guest write reaches the host as it happens, and a
|
|
host change shows in the guest within a second.
|
|
|
|
### Talk over vsock
|
|
|
|
```js
|
|
const listener = vm.vsock.listen(5000); // guest programs connect to CID 2, port 5000
|
|
vm.write("echo hello | kwbox vsock connect 5000\n");
|
|
const conn = await listener.accept();
|
|
console.log(await new Response(conn.readable).text()); // "hello\n"
|
|
conn.close();
|
|
|
|
const c = await vm.vsock.connect(6000); // a guest program listening on port 6000
|
|
await c.writable.getWriter().write("ping");
|
|
```
|
|
|
|
These are byte streams with real flow control and no network in between.
|
|
vsock is on unless you pass `vsock: false`.
|
|
|
|
```js
|
|
const sock = await vm.connect(8000); // TCP to the guest's 127.0.0.1:8000
|
|
await new Response("hello\n").body.pipeTo(sock.writable); // then EOF (a half-close)
|
|
console.log(await new Response(sock.readable).text());
|
|
```
|
|
|
|
`vm.connect(port)` reaches a TCP server on the guest's loopback through
|
|
the guest's kwtty, over vsock, so it needs no network. It resolves once
|
|
the guest has connected (`PtyError` `ECONNREFUSED` if nothing listens) with
|
|
`readable` and `writable` byte streams, half-close included, `close()` and
|
|
`closed`. [The CLI's](#-run-it-from-the-terminal) `--forward
|
|
HOSTPORT:GUESTPORT` uses it.
|
|
|
|
`vm.fetch(url, init)` sends an HTTP/1.1 request to a server in the guest
|
|
and returns a `Response` whose body streams. It always connects to the
|
|
guest's 127.0.0.1 at the URL's port; the host name only goes into the
|
|
`Host` header, so `vm.fetch("http://localhost:8000/")` reaches a dev server
|
|
listening on port 8000. `fetchOver(connect, url, init)` is the same client
|
|
over any byte stream.
|
|
|
|
### Share memory
|
|
|
|
```js
|
|
const vm = await createKernel({ shm: true });
|
|
await vm.exec("sh", ["-c", "printf result > /dev/shm/output"]);
|
|
|
|
const output = await vm.shm.open("output"); // a file a guest program made
|
|
const data = await output.read();
|
|
const views = output.views(); // zero-copy, until the kernel runs again
|
|
|
|
const input = await vm.shm.create("input", 1 << 20); // /dev/shm/input in the guest
|
|
await input.write(0, bytes);
|
|
```
|
|
|
|
`/dev/shm` exists once the guest's init has mounted it, so wait for the
|
|
guest before `create()` (an `exec()` waits for it). `openId(id)` opens a
|
|
memfd that a guest program exported through `/dev/kwshm`. `views()` and
|
|
`readSync()` work where `vm.shm.inPlace` is true: inline, and in worker mode
|
|
with several CPUs and shared memory (cross-origin isolated pages, Node);
|
|
elsewhere `read()` crosses to the kernel's worker.
|
|
|
|
### Serial ports
|
|
|
|
```js
|
|
const vm = await createKernel({ serial: true }); // /dev/ttyACM0..3
|
|
const port = await navigator.serial.requestPort(); // Web Serial, in a click handler
|
|
vm.serial.attach(webSerialBackend(port)); // the first free port: /dev/ttyACM0
|
|
// in the guest: picocom -b 115200 /dev/ttyACM0, esptool, arduino-cli
|
|
```
|
|
|
|
The guest's tty settings, DTR, RTS and break go to the real port, in order
|
|
with its writes; a speed change while it is open reopens it (Web Serial
|
|
cannot change an open port). Unplugging or `vm.serial.detach(slot)` hangs
|
|
up the program using it. Web Serial is in Chromium-based desktop browsers;
|
|
`FakeSerialBackend` is a loopback for tests (the CLI's `--serial`). The page
|
|
has Connect… in Settings > Serial ports, and a Thonny app (Tools) for
|
|
MicroPython boards (ESP32, Raspberry Pi Pico) on those ports.
|
|
|
|
### Bluetooth
|
|
|
|
```js
|
|
import { createKernel, VirtualLeController, WebBluetoothCentral } from "unkernel";
|
|
|
|
const vm = await createKernel({ bluetooth: true }); // kwbt: hci0 while a controller is attached
|
|
const central = new WebBluetoothCentral();
|
|
await vm.bluetooth.attach(new VirtualLeController({ central })); // an emulated LE controller
|
|
button.onclick = () => central.requestDevice(); // Web Bluetooth's chooser, from a click
|
|
// in the guest: apt install bluez; bluetoothctl, then scan on, connect, menu gatt
|
|
```
|
|
|
|
The guest gets a real Linux Bluetooth adapter, so unmodified BlueZ
|
|
(`bluetoothctl`, `btmgmt`, D-Bus GATT clients such as bleak) scans for,
|
|
connects to and talks GATT with the BLE devices the page was allowed to use.
|
|
Web Bluetooth has no HCI, so `VirtualLeController` emulates an LE controller
|
|
and proxies each device's GATT database; pairing is left to the host's OS,
|
|
and there is no BR/EDR, advertising or L2CAP channel beyond ATT. The kernel
|
|
side is a plain HCI transport: `H4StreamController` passes a real
|
|
controller's H4 through instead, and attaching another controller replaces
|
|
hci0, as replugging a dongle does. Web Bluetooth is in Chromium-based
|
|
browsers; `FakeGattCentral` is a scriptable central for tests (the CLI's
|
|
`--bluetooth`). The page has Bluetooth in Settings, and a Bluetooth app (Tools) that walks a device with bluetoothctl.
|
|
### USB devices
|
|
|
|
```js
|
|
const vm = await createKernel({ usb: true }); // a USB root hub with 4 ports
|
|
const device = await navigator.usb.requestDevice({ filters: [] }); // WebUSB, in a click handler
|
|
await vm.usb.attach(webUsbBackend(device)); // the guest enumerates it
|
|
// in the guest: lsusb, adb, fastboot, dfu-util, openocd, /dev/ttyUSB0 (FTDI, CP210x, CH34x, PL2303)
|
|
```
|
|
|
|
The guest's kernel enumerates and configures the device itself; each URB
|
|
goes to WebUSB whole (control, bulk, interrupt and isochronous transfers),
|
|
so libusb programs work through usbfs. Interfaces WebUSB keeps from pages
|
|
(HID, mass storage, audio, video, smart cards) are hidden from the guest.
|
|
Unplugging or `vm.usb.detach(slot)` disconnects it. In worker mode the
|
|
kernel's worker opens the device itself where WebUSB works in workers, so
|
|
transfers stay off your thread.
|
|
`FakeUsbBackend` is a test device (the CLI's `--usb`). The page has no USB
|
|
controls yet.
|
|
|
|
### Display, input and sound
|
|
|
|
```js
|
|
import { createKernel, domCodeToLinux, pcmToFloat32 } from "unkernel";
|
|
|
|
const vm = await createKernel({
|
|
display: { width: 800, height: 600 }, // the guest gets /dev/fb0
|
|
onDisplay: (mode) => console.log(mode), // a program opened it (its mode) or closed it (null)
|
|
sound: { onChunk: ({ data, format }) => play(pcmToFloat32(data, format)) },
|
|
});
|
|
|
|
const frame = vm.frame(); // RGBA, or null while nothing draws
|
|
if (frame) ctx.putImageData(new ImageData(frame.data, frame.width, frame.height), 0, 0);
|
|
|
|
addEventListener("keydown", (e) => {
|
|
const key = domCodeToLinux(e.code);
|
|
if (key && vm.evdev.keyboardOpen) vm.evdev.key(key, true);
|
|
});
|
|
```
|
|
|
|
`evdev` also has `button()`, `move()`, `moveTo()` and `wheel()` for a
|
|
mouse or tablet. `onInput` tells you when a program opens the keyboard
|
|
and mouse; until then, send keys to the console. `readFrame()` waits for
|
|
a fresh frame.
|
|
|
|
In browsers, `createAudioOut()` plays the guest's sound with Web Audio:
|
|
|
|
```js
|
|
import { createAudioOut, createKernel } from "unkernel/web";
|
|
|
|
button.hidden = true;
|
|
const audio = createAudioOut({
|
|
onChange: (state) => { button.hidden = state !== "waiting"; }, // "click to play"
|
|
});
|
|
const vm = await createKernel({ sound: audio });
|
|
button.onclick = () => audio.resume(); // or any other click or key press on the page
|
|
```
|
|
|
|
Browsers start sound only after a click, tap or key press on the page.
|
|
Until then the latest `holdSeconds` (10) of what the guest plays are held:
|
|
a clip that has ended by then plays whole, a stream joins live.
|
|
`audio.muted = true` silences it. One sink serves one kernel at a time, and
|
|
outlives it: pass it to the next kernel, or `close()` it.
|
|
|
|
`soundIn` gives the card a capture substream (what `arecord` or a read of
|
|
`/dev/dsp` records): `createAudioIn()` from `unkernel/web` is the user's
|
|
microphone, asked for only when a guest program starts recording and let
|
|
go when it closes the device (silence until then); anywhere else, a
|
|
source's `read(out, rate)` fills `out` with mono samples in [-1, 1]:
|
|
|
|
```js
|
|
const vm = await createKernel({ sound: audio, soundIn: createAudioIn() });
|
|
```
|
|
|
|
`camera` gives the guest `/dev/video0` (V4L2: I420, NV12 and YUYV up to 1280x720
|
|
at 30 frames a second, for `v4l2-ctl`, ffmpeg, GStreamer or a browser in
|
|
the guest): `createCamera()` from `unkernel/web` is the user's camera,
|
|
asked for only when a guest program starts streaming and let go when it
|
|
stops (black frames until then); anywhere else, a source's `read(out,
|
|
format)` writes the current frame in the stream's format, and `true` gives
|
|
black frames. Where the browser's `VideoEncoder` makes H.264, the camera
|
|
offers it too, encoded on the host, so the guest copies the stream instead
|
|
of encoding it (`ffmpeg -f v4l2 -input_format h264 -i /dev/video0 -c:v
|
|
copy out.mkv`), as with a webcam that encodes. The CLI's `--camera` shows
|
|
a test pattern, `--camera=h264` also as H.264.
|
|
|
|
```js
|
|
const vm = await createKernel({ camera: createCamera() });
|
|
```
|
|
|
|
### GL in the guest (browsers)
|
|
|
|
```js
|
|
const vm = await createKernel({ distro: "/distros/debian.erofs", gl: true });
|
|
await vm.gl.ready; // the guest is linked; the renderer loads on its first GL use
|
|
await vm.exec("sudo", ["apt-get", "install", "-y", "mesa-utils", "libegl-mesa0", "libgles2"]);
|
|
const r = await vm.exec("sh", ["-c", "GALLIUM_DRIVER=virpipe LIBGL_ALWAYS_SOFTWARE=1 eglinfo -B -p surfaceless"]);
|
|
```
|
|
|
|
The guest's Mesa (Debian; its `virpipe` driver) renders through
|
|
virglrenderer compiled to wasm (`virgl.wasm`, fetched only with `gl`, and
|
|
only on the guest's first GL use; `vm.gl.status` tells, `vm.gl.load()`
|
|
starts it, and `gl: { eager: true }` loads it before the boot so that a
|
|
failure shows up front) on one WebGL2 context of the page, and gets its
|
|
frames back by readback: GL 2.1 and GLES 3.0, surfaceless or under Xvfb.
|
|
Node has no WebGL, so there `gl` is ignored with a log line.
|
|
|
|
With `gpu: true` as well (and a kernel with kwvirtio), the guest gets a
|
|
virtio-gpu device with 3D on the same renderer: stock Mesa finds
|
|
`/dev/dri/renderD128` and `card0` (driver `virtio_gpu`) and renders through
|
|
it with no variables set, and a KMS client's frames (kmscube,
|
|
`glmark2-es2-drm`, a Wayland compositor) come from the renderer's texture:
|
|
|
|
```js
|
|
const vm = await createKernel({ distro, gl: true, gpu: true, display: { width: 1280, height: 720 } });
|
|
// per animation frame: the scanout's latest frame, no readback (null: no GL client on it)
|
|
if (vm.gl.gpu.drawFrame(ctx) === null) { /* show vm.frame() as above */ }
|
|
// the window resized: a hotplug with a new preferred mode, which KMS clients may take
|
|
vm.updateDisplaySize({ width: 1600, height: 900 });
|
|
```
|
|
|
|
### Vulkan in the guest (browsers with WebGPU)
|
|
|
|
```js
|
|
const vm = await createKernel({ distro: "/distros/debian.erofs", vk: true });
|
|
await vm.exec("sudo", ["apt-get", "install", "-y", "libvulkan1", "vulkan-tools"]);
|
|
const r = await vm.exec("vulkaninfo", ["--summary"]); // deviceName = kwvk (WebGPU)
|
|
```
|
|
|
|
The base carries a Vulkan driver (an ICD the Vulkan loader finds by
|
|
itself) that sends the guest's Vulkan calls to a renderer on the page's
|
|
WebGPU device; SPIR-V shaders become WGSL through `kwvk-naga.wasm`.
|
|
Nothing loads before the guest's first Vulkan program (`vm.vk.status`).
|
|
Vulkan 1.2 with Wayland, X11 and headless presentation (frames come back
|
|
by readback); vkcube, vkmark, SDL's GPU API and GTK 4's Vulkan renderer run
|
|
on it. Node has no WebGPU, so there `vk` is ignored with a log line.
|
|
[vk/PROTOCOL.md](vk/PROTOCOL.md) has the design.
|
|
|
|
### Video in the guest (browsers with WebCodecs)
|
|
|
|
```js
|
|
const vm = await createKernel({ distro: "/distros/debian.erofs", gl: true, gpu: true, va: true });
|
|
await vm.exec("sudo", ["apt-get", "install", "-y", "vainfo"]);
|
|
const r = await vm.exec("vainfo"); // the kwva driver and the profiles it decodes
|
|
```
|
|
|
|
The base carries a VA-API driver that Debian's libva loads for the
|
|
virtio-gpu device by itself. It hands each picture to a WebCodecs
|
|
`VideoDecoder` on the page, so the guest's ffmpeg, mpv and Chromium decode
|
|
VP9, H.264, AV1 and HEVC in the browser's decoder (in hardware where it has
|
|
one), and ffmpeg's `vp9_vaapi` encodes on a `VideoEncoder`. Pictures come
|
|
back as NV12, or with `gl` as dmabufs filled on the GPU (mpv's
|
|
`--hwdec=vaapi --vo=dmabuf-wayland`). `vm.va.status` lists what is offered.
|
|
Node has no WebCodecs, so there `va` is ignored with a log line.
|
|
[va/PROTOCOL.md](va/PROTOCOL.md) has the design.
|
|
|
|
### Save and restore a machine
|
|
|
|
```js
|
|
import { createKernel, decodeSnapshot, encodeSnapshot } from "unkernel";
|
|
|
|
const sh = await vm.spawn("sh", [], { detachable: true }); // survives the restore
|
|
await vm.snapshot({ commit: (snap) => writeFile("vm.snap", encodeSnapshot(snap)) }); // stored, then stopped
|
|
|
|
const snap = decodeSnapshot(await readFile("vm.snap"));
|
|
const restored = await createKernel({ distro, restore: snap }); // same kernel, disks and devices
|
|
const again = await restored.attach(snap.ttys[0]);
|
|
```
|
|
|
|
The kernel parks every task, so a snapshot is the guest's memory (free
|
|
pages and, when it stops, the clean file cache left out: the idle base
|
|
shell in a 2 GiB guest saved to 46 MiB on 2026-11-30) plus a few host values. `snapshot()` alone lets
|
|
the machine run on, `{ stop: true }` stops it, and `{ commit }` stops it only
|
|
once the snapshot is stored, so a failed save never loses the machine.
|
|
Disks are not copied: a restore needs the same disks, unwritten since, and
|
|
the same devices and CPU count, or `createKernel()` rejects with the reason.
|
|
Host mounts and detachable sessions survive; other vsock sessions and TCP
|
|
connections are reset. The CLI's `--input '{save=FILE}'` and `--restore
|
|
FILE` use it, and the page suspends a session with it.
|
|
|
|
### Run it in a worker
|
|
|
|
```js
|
|
const vm = await createKernel({
|
|
worker: true,
|
|
distro, // a path or URL
|
|
net: { kind: "net", backend: { kind: "direct" } },
|
|
disks: [{ kind: "file", path: "data.img" }],
|
|
});
|
|
```
|
|
|
|
The kernel runs in a worker thread or Web Worker, with the same API. Disks
|
|
and the network are given as specs, which the worker builds: `{ kind:
|
|
"file", path }` on Node, `{ kind: "http", url }` and `{ kind: "data",
|
|
template: "bundled" }` in browsers. Input and frames go through shared
|
|
memory when it is available (`vm.transport` says). This mode is
|
|
experimental.
|
|
|
|
An SMP kernel (a bundle with the SMP patch) boots on several CPUs with
|
|
`cpus: 4`, each CPU in a thread of its own on one shared memory. In
|
|
browsers that needs a cross-origin isolated page and `worker: true`,
|
|
because a CPU blocks while it waits for another, which a page's main
|
|
thread may not; `webCpuBlocker()` says why it cannot, and
|
|
`vm.stats().cpus` how many CPUs the kernel got.
|
|
|
|
On a server, `worker: true` keeps the event loop free at no cost in speed,
|
|
and `cpus: 4` gets most of what more CPUs give (about 3x on parallel work;
|
|
8 or 16 add little, and each CPU adds to boot time and takes 9 MiB of
|
|
guest memory). `node test/profile.ts` measures your host, and the page's
|
|
`/profile.html` a browser.
|
|
|
|
### Boot options and helpers
|
|
|
|
```js
|
|
import { checkSupport, ConsoleRouter, createKernel } from "unkernel";
|
|
|
|
const support = await checkSupport(); // JSPI and the rest, before you boot
|
|
if (!support.ok) throw new Error(support.problems.join("\n"));
|
|
|
|
const vm = await createKernel({
|
|
kernel: "./my-kernel.wasm", // a URL, bytes, a Response or a WebAssembly.Module
|
|
initrd: "./initramfs.cpio.gz", // null: none
|
|
cmdline: "console=hvc0 rdinit=/init",
|
|
memoryMiB: 1024,
|
|
jit: false, // interpreter only
|
|
onProgress: (p) => console.log(p.stage),
|
|
});
|
|
|
|
const router = new ConsoleRouter({ // kernel log lines apart from program output
|
|
onKernelLine: (line, { important }) => important && console.warn(line),
|
|
onUserOutput: (text) => process.stdout.write(text),
|
|
});
|
|
vm.onOutput((bytes) => router.write(bytes));
|
|
```
|
|
|
|
The SDK has some limits, on top of the kernel's [known
|
|
limits](#-known-limits). There is no guest agent beyond terminal sessions, so
|
|
you drive the guest through a terminal or its console, or over vsock with your
|
|
own program. `stop()` doesn't shut the guest down cleanly, so prefer
|
|
`poweroff`. Only one kernel can run per thread. Types ship as `.d.mts` and use
|
|
the DOM's `WebAssembly` types, so a Node-only TypeScript project needs `"lib":
|
|
["dom"]` or `skipLibCheck`.
|
|
|
|
## 🛠️ Building from source
|
|
|
|
You need Linux (x86-64 or arm64), Zig 0.16, Node 24, clang 21+ with the
|
|
wasm target, and the usual build tools. `./setup.sh --check` lists what's
|
|
missing. The first build takes about 12 minutes, most of it spent on a
|
|
patched `wasm-ld`, and uses 5 GiB of disk.
|
|
|
|
```sh
|
|
./setup.sh # check, then build everything
|
|
node js/cli.ts # boot your build (Alpine from vendor/build/distro/)
|
|
pnpm install && pnpm dev # the web page at http://localhost:8080
|
|
zig build test # emulator tests
|
|
```
|
|
|
|
The build makes the kernel bundle `vendor/build/bundle/unkernel.wasm` and
|
|
the distro images `vendor/build/distro/{alpine,debian}.erofs` with their
|
|
index `distros.json`; a source checkout uses those and never downloads
|
|
them. [guest/README.md](guest/README.md) describes the base system and how
|
|
to add a distro.
|
|
|
|
[kernel/README.md](kernel/README.md) maps the kernel directory and its
|
|
build steps. [AGENTS.md](AGENTS.md) and [.agents/](.agents/) hold the
|
|
contributor notes: the kernel, its devices and the guest image, invariants,
|
|
workflows, which tests to run, and the [roadmap](.agents/status.md).
|
|
|
|
## 🙏 Credits
|
|
|
|
Made with ♥ by [Pooya Parsa](https://x.com/_pi0_) ([pi0](https://github.com/pi0)), sponsored by
|
|
[▲ Vercel](https://vercel.com/open-source-program).
|
|
|
|
Thanks to:
|
|
|
|
- [Kernarium](https://github.com/imxieyi/Kernarium), for the idea: a native
|
|
kernel with emulated user space behind a software MMU.
|
|
- [linux-wasm](https://github.com/joelseverin/linux-wasm) by Joel Severin,
|
|
for the `arch/wasm` port this kernel grew from, the wasm-ld linker-script
|
|
patches and the Kbuild toolchain wrapper.
|
|
- [iSH](https://github.com/ish-app/ish) and [v86](https://github.com/copy/v86),
|
|
for showing how to build a fast user-mode emulator and a wasm JIT.
|
|
- [virglrenderer](https://gitlab.freedesktop.org/virgl/virglrenderer) and
|
|
[Mesa](https://mesa3d.org/), for guest GL: Mesa's virgl driver in the
|
|
guest, and virglrenderer compiled to wasm with
|
|
[Emscripten](https://emscripten.org/), rendering on WebGL2 in the page.
|
|
- [Alpine Linux](https://alpinelinux.org/) and
|
|
[Debian](https://www.debian.org/), the distributions it boots, packed with
|
|
[erofs-utils](https://git.kernel.org/pub/scm/linux/kernel/git/xiang/erofs-utils.git),
|
|
[LZ4](https://github.com/lz4/lz4) and [Zstandard](https://github.com/facebook/zstd).
|
|
- [wland](https://github.com/pithings/wland), the Wayland compositor that
|
|
brings the guest's windows to the page, and [wterm](https://wterm.dev/),
|
|
the page's terminals.
|
|
- [Zig](https://ziglang.org/), [LLVM](https://llvm.org/) and
|
|
[Binaryen](https://github.com/WebAssembly/binaryen), which build it;
|
|
[React](https://react.dev/), [Tailwind CSS](https://tailwindcss.com/),
|
|
[Vite](https://vite.dev/), [Nitro](https://nitro.build/) and the
|
|
[Geist](https://vercel.com/font) fonts, which make the page.
|
|
- [Wisp](https://github.com/MercuryWorkshop/wisp-protocol), the protocol
|
|
behind the guest's network in the browser.
|
|
|
|
## 📄 License
|
|
|
|
Everything is open source: the kernel patches, the emulator and its JIT,
|
|
the patched linker, the SDK and the page. `./setup.sh` rebuilds the kernel
|
|
file from source.
|
|
|
|
The project is GPL-2.0-or-later ([LICENSE](LICENSE)) unless a file says
|
|
otherwise. The JavaScript SDK and page (`js/`, `web/`, SDK tests) are MIT
|
|
([LICENSE-MIT](LICENSE-MIT)), so you can embed them anywhere.
|
|
|
|
The npm package ships a Linux kernel (GPL-2.0) with a small base system
|
|
(Alpine's static busybox, GPL-2.0, and unkernel's own tools), so it is `MIT
|
|
AND GPL-2.0-only`. It also ships the guest GL renderer (`virgl.wasm`:
|
|
virglrenderer and Emscripten's runtime, MIT, with unkernel's glue,
|
|
GPL-2.0-or-later) and the guest Vulkan translator (`kwvk-naga.wasm`: naga
|
|
and its Rust dependencies, MIT or Apache-2.0, with unkernel's glue,
|
|
GPL-2.0-or-later). [THIRD-PARTY.md](THIRD-PARTY.md), in the package and on
|
|
the page at `/licenses.md`, lists what is not unkernel's, with the notices
|
|
its licenses ask for. The distro images it downloads hold the distributions'
|
|
packages, which keep their own licenses. The
|
|
kernel's source is Linux 7.3.4 plus
|
|
[kernel/patches/linux](kernel/patches/linux) (`arch/wasm` is based on
|
|
linux-wasm's). Those patches and
|
|
`kernel/tools/fake-llvm` are GPL-2.0-only, and the patches in
|
|
`kernel/patches/llvm` follow LLVM's license (Apache-2.0 WITH
|
|
LLVM-exception).
|