Hosts
What the platform provides to a machine: its WebAssembly modules, files, disks, sockets, display and sound. Node and the browser each have a ready-made host.
What QEMU gets from the computer it runs on, Warm64 gets from a host: a plain object you pass to WARM.launch(). The two ready-made hosts cover the common cases, and you can extend either one by spreading it into a new object.
const host = {
...nodeWARMHost(),
display: { refreshHz: 30, frame: (width, height, pixels) => draw(width, height, pixels) },
};When a host lacks something the command line needs, the machine responds as QEMU does on a computer without it, or names the member that would provide it: this platform has no sockets for a tap netdev (WARMHost.netSockets).
nodeWARMHost()
The host for Node. It provides everything QEMU gets from a computer, using Node's files, sockets, terminal and processes.
import { nodeWARMHost } from "@warm-virtual/warm64/warm-node";
nodeWARMHost(options?): WARMHostNodeWARMHostOptions:
| Option | Type | Default | Description |
|---|---|---|---|
wasmDir | string or URL | the package's wasm/ | Where the .wasm modules are. |
snapshotDir | string | none | Keeps savevm's states there as NAME.warm64snap files, instead of in the disks. See Snapshots. |
warn | (line) => void | writes to stderr | Where warnings go. |
log | (text) => void | writes to stderr | Where the -d log goes, as QEMU writes it. |
It provides nearly every WARMHost member. The exceptions are display, audio, browserWindow and webSocket (Node's global WebSocket serves -netdev socket,connect=ws://), and it only provides snapshots when you give snapshotDir. Images are opened in place, in any format. warm-system-aarch64 adds the rest: -display cocoa as a page in the default browser, and -audiodev coreaudio on a Mac.
browserWARMHost()
The host for a web page or worker. It fetches everything by URL.
import { browserWARMHost } from "@warm-virtual/warm64";
browserWARMHost(options?): WARMHostBrowserWARMHostOptions:
| Option | Type | Default | Description |
|---|---|---|---|
base | string or URL | the page's URL | What relative paths are resolved against. The cores are fetched from ${base}wasm/${kind}.wasm. |
relay | string | none | A relay for the user network, ws://host:port/ or wss://…/?token=…. Each of the guest's TCP connections becomes a WebSocket to it, and each DNS lookup a GET /dns request to it. See Networking. |
audio | boolean or WebAudio | true where the page has Web Audio | The sound output, through Web Audio. false leaves the sound card silent. Pass your own WebAudio to call its unlock() or read its stats. See Sound. |
warn | (line) => void | console.warn | Where warnings go. |
It provides wasm, readFile, asset and warn; with relay, a connector and resolve; and on a page with Web Audio, an audio. Paths on the command line can be relative to base, absolute URLs, or blob: URLs of local files:
const url = URL.createObjectURL(fileInput.files[0]);
await WARM.launch(`-cpu cortex-a76 -kernel ${url} -display none`, browserWARMHost());Images are fetched whole, and the guest's writes are kept in memory. Add the rest yourself: openDisk for disks that persist, display, audio in a worker (Web Audio only exists on a page's main thread), snapshots, and a connector if you don't pass relay.
WARMHost
Every member except wasm and readFile is optional. These are the ones an embedder usually sets or replaces:
| Member | Type | Description |
|---|---|---|
wasm | (kind) => WasmSource | Returns the WebAssembly module Warm64 asks for: a WebAssembly.Module, bytes, a Response, or a URL string to fetch. See Core modules. |
readFile | (path) => Promise<Uint8Array> | Reads what the command line names: -kernel, -initrd, -bios, and images when there's neither openFile nor openDisk. |
asset | (name) => Promise<Uint8Array or null> | Reads a file that ships with the package, next to the cores: the wision installer (wision/wision.img, wision/wision, wision/musl, wision/gnu). Returns null when the package doesn't have it, which leaves the installer out. Both hosts provide it. |
openDisk | (path, readOnly, format) => WARMDiskFile | Opens an image in place. See openDisk. |
writeFile | (path, data, options?) => Promise<void> | Writes files for screendump, migrate file:, dumpdtb, dump-guest-memory and -audiodev wav. options.mode is the new file's mode. |
connector | Connector | Opens the user network's connections. See connector. |
resolve | (name) => Promise<string or null> | Answers the guest's DNS lookups with an IPv4 address, when there's no nameserver. Without either, every name is unknown. |
webSocket | a WebSocket-like constructor | Used by -netdev socket,connect=ws://. Defaults to the global WebSocket. |
snapshots | WARMSnapshotStore | Keeps savevm's states in place of the disks. See snapshots. |
display | WARMDisplay | The screen. See display. |
audio | WARMAudio | The sound output. See audio. |
warn | (line) => void | Warnings, as QEMU prints them. Defaults to console.warn. |
log | (text) => void | The -d log, as QEMU writes it. Defaults to warn. |
The other members
The rest of WARMHost provides what a QEMU process gets from its operating system. nodeWARMHost() provides them all except browserWindow, which warm-system-aarch64 adds, and a page rarely needs any of them. Here are the WARMHost members, grouped by what they serve:
| Serves | Members |
|---|---|
Files and images (the block layer, image locks, -mem-path, vvfat) | openFile (a file as QEMU's file protocol reads it: Warm64 reads the formats itself), createFile, createTempFile, removeFile, statFile, allocatedSize, access, createWriter, listDir, tmpDir, makeTempDir, removeTree, fileLocks, backingStore, vvfat, zstdCompress |
Sockets (the user network's hostfwd, guestfwd and smb, the other netdevs, the block layer's nbd, http and ssh, migration) | nameserver (the host's resolver the guest's DNS goes to), connectSync, listenTcp, listenUdp, listenUnix, netSockets, commandService, migrationChannel, migrationIncoming |
| Character devices and terminals | chardev (a -chardev's host side: stdio, files, pipes, sockets, a pty), chardevLog, curses (-display curses), semihost |
| Credentials and devices | tlsCreds, sasl, ssh, tpmEmulator (-tpmdev emulator over swtpm) |
| The process | inheritedFd, fdFlags, fdMode, closeFd (-add-fd and fd= options), exit, abort, print, pageSize, uid, userName, machineId, parseHooks |
| A window of the host's | browserWindow (-display cocoa) |
| Diagnostics | dumpVmstate (-dump-vmstate), diagnostics (Warm64's own QMP commands offered to monitor clients too) |
Core modules
Warm64 picks the module from the command line and asks the host for it by name, as a WARMCoreKind. The file is ${kind}.wasm.
| Kind | When |
|---|---|
warm64 | One core, while the RAM and about 34 MiB fit in 1.5 GiB. |
warm64-memory64 | One core and more RAM: 64-bit WebAssembly memory. |
warm64-threads | More than one core, while the RAM and about 34 MiB a core fit in 1.5 GiB: one host thread per guest core. |
warm64-memory64-threads | More than one core and more RAM. |
warm64-gpu-threads | The GPU worker for a virtio-gpu device, where shared memory is available (Node, or a cross-origin-isolated page). |
warm64-gpu | The GPU worker, where shared memory isn't. |
Note The threads modules need SharedArrayBuffer. Browsers only give it to cross-origin-isolated pages, which are served with the Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp headers. Node has no such requirement.
openDisk
openDisk(path: string, readOnly: boolean, format: string): WARMDiskFile | Promise<WARMDiskFile>Opens an image so the guest can read and write it in place. A host with openFile reads every format through that, and openDisk isn't used; without openFile, openDisk serves the image's guest-visible bytes. format is the drive's format, raw unless the command line names another, and a host that can't serve a format should throw. Return a WARMDiskFile:
{ size: number, backing: DiskBacking, close?(): void, flush?(): void, truncate?(size): void, punch?(offset, length): void, allocated?(): number }flush makes what was written durable, truncate serves block_resize, punch returns a discarded range to the host as a hole, and allocated reports how much space the file takes. A DiskBacking has these synchronous methods, which are called while the guest runs:
| Method | Description |
|---|---|
read(offset, into) | Fill the Uint8Array into from the disk at offset. |
write(offset, data) | Write data at offset. |
discard(offset, length) | Optional. Free a range; called only for drives with discard=unmap. |
io(write, offset, data), flush(), writeZeroes(offset, length, unmap), pdiscard(offset, length) | Optional: a request in the form QEMU's block layer makes it, answering 0 or an errno. Without them, the methods above are used, and a failure is EIO. |
errorAction(isRead, errno), acct(kind, phase, bytes), setWriteCache(on), stats(), blockStatus(offset, bytes) | Optional: the error policy, statistics, write-cache state and allocation status QEMU's block layer keeps. Warm64's own block layer fills these in for the images it opens. |
Returning false or throwing gives the guest an I/O error. opfsDiskBacking() builds a DiskBacking from an OPFS handle.
In a browser, disks that persist come from the Origin Private File System. Its synchronous access handles only exist in workers, so run Warm64 in a worker:
import { opfsDiskBacking } from "@warm-virtual/warm64";
const root = await navigator.storage.getDirectory();
const host = {
...browserWARMHost(),
async openDisk(path) {
const file = await root.getFileHandle(path);
const handle = await file.createSyncAccessHandle();
return { size: handle.getSize(), backing: opfsDiskBacking(handle), close: () => handle.close() };
},
};connector
-netdev user is QEMU's user network. The guest gets DHCP, DNS and ping from it, and its TCP connections go out through the host's connector. Without one, the guest's connections are refused.
interface Connector {
connect(host: string, port: number, handlers: SocketHandlers): Promise<StackSocket>;
udp?(onMessage: (host: string, port: number, data: Uint8Array) => void): UdpFlow;
ping?(host: string): Promise<boolean>;
icmp?(dst: Uint8Array, packet: Uint8Array, handlers): Promise<{ fd: number; close(): void }>;
readFile?(path: string): Promise<Uint8Array | null>;
}
interface SocketHandlers { onData(bytes: Uint8Array): void; onEnd(unclean?: boolean): void; onError(error: Error): void }
interface StackSocket {
write(bytes: Uint8Array): void;
end(): void; // half-close: no more data from the guest
destroy(): void;
reset?(): void; // a reset, where the host can
startTlsServer?(...): void; // the NBD server's STARTTLS; absent where the host has no TLS
}Only connect is required. udp carries the guest's UDP beyond DHCP and DNS, ping and icmp carry its pings to the outside, and readFile serves tftp=. Node's host has them all, using real sockets. A browser can't open sockets, so webSocketConnector() carries each TCP connection over a WebSocket to a relay you run, such as examples/net/tcp-relay.mjs in the Warm64 repository:
import { webSocketConnector } from "@warm-virtual/warm64";
const host = { ...browserWARMHost(), connector: webSocketConnector("wss://relay.example.com/") };webSocketResolver() answers the guest's DNS lookups through the same relay, as GET /dns requests, and browserWARMHost({ relay }) sets up both:
import { browserWARMHost, webSocketConnector, webSocketResolver } from "@warm-virtual/warm64";
const url = "wss://relay.example.com/";
const host = browserWARMHost({ relay: url });
// the same as
const same = { ...browserWARMHost(), connector: webSocketConnector(url), resolve: webSocketResolver(url) };See Networking.
display
interface WARMDisplay {
canvas?: OffscreenCanvas;
gl?: "auto" | "software" | "webgpu" | "webgl2"; // default "auto"
frame?(width: number, height: number, pixels: Uint8Array): void;
refreshHz?: number; // default 60
cursor?(cursor: WARMCursor | null): void;
}
interface WARMCursor {
width: number; height: number;
hotX: number; hotY: number; // the hot spot, from the image's top-left
pixels: Uint8Array; // straight-alpha RGBA
png: Blob | null; // the same image as a PNG (null in Node)
url: string | null; // an object URL of the PNG, the same for the same image
}canvas: anOffscreenCanvasfromcanvas.transferControlToOffscreen(). The GPU worker draws on it with WebGPU or WebGL2, or in software when neither is available. The host's GPU is used for 3D under-accel wapi(-device virtio-gpu-gl-pciwith-display …,gl=on); under-accel tcg, and for 2Dvirtio-gpu-pci, it renders in software.gl: the OpenGL this display offers to a machine that asks for it under-accel wapi, as a computer's graphics driver does for QEMU."auto"offers the best available, WebGPU before WebGL2."webgpu"or"webgl2"offers that one, falling back to the next one down when the browser doesn't have it (WebGPU to WebGL2, either to software)."software"draws in software whatever the command line asks. A renderer that-wapileaves out is never used.frame: called with each changed frame, at mostrefreshHztimes a second.pixelsis a8r8g8b8 (bytes B, G, R, X) and is valid only during the call.cursor: optional. With a tablet, the display doesn't draw the guest's cursor, because the page's own pointer is the cursor, so leave it visible over the canvas. Givecursorto show the guest's cursor image on that pointer instead, as QEMU's GTK display does. It's called with aWARMCursoron each change, or withnullwhen the guest hides its cursor.
const el = document.querySelector("canvas");
const display = {
canvas: el.transferControlToOffscreen(),
cursor(c) {
el.style.cursor = c ? `url(${c.url}) ${c.hotX} ${c.hotY}, default` : "none";
},
};Don't revoke url. A browser shows its default arrow until a new cursor image is decoded, so on a page, WARM decodes each image before calling cursor. When WARM runs in a worker, decode the image on the page before applying it (new Image(), set src to the URL, await img.decode()), and keep only the latest one, or the arrow flashes between an animated cursor's frames.
The display is used unless the command line says -display none or -nographic. See Display and input.
audio
interface WARMAudio {
play(samples: Int16Array, rate: number, channels: number): void;
record?(): Int16Array | null;
open?(location: string): void;
}Used for any -audiodev other than none and wav. play receives what the guest plays, as signed 16-bit interleaved samples. record is polled regularly and supplies what the guest captures, or null when there's nothing yet. open, if present, is called when the first sound card opens its voices, with the option that named the audiodev. Without a host audio, Warm64 warns and drops the sound.
WebAudio
The browser's sound output, and what browserWARMHost() uses by default on a page:
import { WebAudio } from "@warm-virtual/warm64";
new WebAudio(warn?: (line: string) => void)It implements WARMAudio, playing the samples through an AudioWorklet at their own rate and channel count. On a cross-origin-isolated page it uses shared memory, and on any other page, posted chunks. It doesn't record.
| Member | Description |
|---|---|
play(samples, rate, channels) | Plays what the guest played. Your code may call it too, with samples posted from a machine in a worker. |
unlock() | Starts the sound that a browser holds back until the user interacts with the page. The page's first click, key press or touch calls it; call it from your own handler to start sooner. Returns a promise. |
state | "none" before the first samples, "suspended" until the page's first gesture, then "running", or "closed". |
time | The output's clock in seconds: it advances only while sound is playing. |
stats | { played, underrun }: frames played, and frames filled with silence because no samples had arrived. |
close() | Stops the output. |
snapshots
interface WARMSnapshotStore {
load(name: string): Promise<Uint8Array | null>;
save(name: string, state: Uint8Array): Promise<void>;
delete(name: string): Promise<boolean>;
list(): Promise<string[]>;
}With a store, savevm, loadvm, delvm, info snapshots and -loadvm keep the machine's states in it by name, instead of in the qcow2 disks as QEMU does. In Node, fileSnapshots(dir) keeps them as files. See Snapshots.