Files
unkernel/test/serial.test.ts

286 lines
13 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// kwserial end to end: the kernel's serial ports (/dev/ttyACM*,
// drivers/tty/serial/kwserial.c) on the SDK's device model (js/core/serial.ts)
// with its loopback backend (FakeSerialBackend). The guest program
// test/serial/ttyacm.c (built here with zig cc, static aarch64 musl, from a
// host directory mounted over 9p) drives the tty, and at each of its steps
// this side checks what reached the backend: the line settings (bauds up to
// 1500000 and 250000 through termios2, 8N1, 7E1, 8O2, CRTSCTS), DTR and RTS,
// a break, the bytes (256 KiB each way at once, tcdrain; 192 KiB left unread
// for a while, throttled without loss), the input signals
// (TIOCMIWAIT, TIOCMGET, TIOCGICOUNT), receive errors (INPCK with PARMRK,
// then IGNPAR and IGNBRK) and an unplug (EOF, EIO, ENODEV, a new port in the
// slot). On the UP kernel, and on the SMP kernel with the program on CPU 1,
// where the driver hands its work to CPU 0. Also: no ports without the
// serial option, ENODEV for an empty slot (root too), the kw layer's rc
// giving a user who is not in dialout the ports on Alpine, and a snapshot
// restored without the device hanging up a port that was open.
//
// node --test test/serial.test.ts
// UNKERNEL_TEST_KERNEL=path ... another bundle instead of vendor/build/bundle/unkernel.wasm
// UNKERNEL_TEST_DISTRO_DIR=dir ... where alpine.erofs is (default vendor/build/distro)
// ZIG=path ... zig for the guest program (default: zig on PATH)
import test, { after, before, describe } from "node:test";
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { FakeSerialBackend, bundledKernelUrl, createKernel, loadKernelModule, nodeFs, type SerialInputSignals } from "../js/node.ts";
type Instance = Awaited<ReturnType<typeof createKernel>>;
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const testKernel = process.env.UNKERNEL_TEST_KERNEL ? path.resolve(process.env.UNKERNEL_TEST_KERNEL) : undefined;
const kernelFile = testKernel ?? fileURLToPath(bundledKernelUrl);
const distroDir = path.resolve(process.env.UNKERNEL_TEST_DISTRO_DIR ?? path.join(root, "vendor/build/distro"));
const alpine = ["erofs", "ext4"].map((f) => path.join(distroDir, `alpine.${f}`)).find((f) => existsSync(f));
/** Kernel messages that must not appear. */
const KERNEL_TROUBLE = /WARNING|BUG|Oops|Call trace|INFO: rcu| stall|blocked for more/;
const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
/** Does the kernel under test have kwserial? */
const hasDriver = WebAssembly.Module.imports(await loadKernelModule(readFileSync(kernelFile))).some((i) => i.name === "wasm_driver_serial_init");
/** Can it run on 2 CPUs (the bundle carries the SMP patch, so the module derived with it imports wasm_cpu_start)? */
const hasSmp = WebAssembly.Module.imports(await loadKernelModule(readFileSync(kernelFile), { smp: true })).some((i) => i.name === "wasm_cpu_start");
const noDriver = !hasDriver && "the kernel has no kwserial";
const dir = mkdtempSync(path.join(tmpdir(), "kw-serial-test-"));
const mounts = { "/mnt/serial": { fs: nodeFs(dir), readOnly: true } };
const TTYACM = "/mnt/serial/ttyacm";
before(() => {
const cc = spawnSync(process.env.ZIG ?? "zig", ["cc", "-target", "aarch64-linux-musl", "-mcpu=generic", "-static", "-O2", "-s", "-o", path.join(dir, "ttyacm"), path.join(root, "test/serial/ttyacm.c")], { encoding: "utf8" });
assert.equal(cc.status, 0, `building ttyacm: ${cc.stderr}`);
});
after(() => rmSync(dir, { recursive: true, force: true }));
/** Lines of a stream as they come; next() waits for the next one (null at the end). */
function lines(stream: ReadableStream<Uint8Array>) {
const seen: (string | null)[] = [];
let buf = "";
let wake = () => {};
void (async () => {
const dec = new TextDecoder();
for await (const b of stream) {
buf += dec.decode(b, { stream: true });
let i;
while ((i = buf.indexOf("\n")) >= 0) {
seen.push(buf.slice(0, i));
buf = buf.slice(i + 1);
}
wake();
}
})()
.catch(() => {})
.finally(() => {
if (buf) seen.push(buf);
seen.push(null);
wake();
});
let at = 0;
return {
seen,
async next(ms = 180000): Promise<string | null> {
const end = Date.now() + ms;
while (at >= seen.length) {
if (Date.now() > end) throw new Error(`no line from the guest within ${ms} ms; so far:\n${seen.join("\n")}`);
await Promise.race([new Promise<void>((r) => (wake = r)), sleep(200)]);
}
return seen[at++]!;
},
};
}
/** Wait until cond() holds (or ms pass); returns whether it did. */
async function until(cond: () => boolean, ms = 3000): Promise<boolean> {
for (const end = Date.now() + ms; !cond(); ) {
if (Date.now() > end) return false;
await sleep(20);
}
return true;
}
const INPUTS: SerialInputSignals[] = [
{ clearToSend: true, dataSetReady: false, dataCarrierDetect: false, ringIndicator: false },
{ clearToSend: false, dataSetReady: true, dataCarrierDetect: true, ringIndicator: false },
{ clearToSend: false, dataSetReady: false, dataCarrierDetect: false, ringIndicator: true },
{ clearToSend: true, dataSetReady: true, dataCarrierDetect: true, ringIndicator: true },
{ clearToSend: false, dataSetReady: false, dataCarrierDetect: false, ringIndicator: false },
];
/** Run `ttyacm run /dev/ttyACM0 [cpu]` and answer its steps; returns the problems seen on either side. */
async function runSequence(vm: Instance, first: FakeSerialBackend, cpu?: number): Promise<{ problems: string[]; transcript: string }> {
const problems: string[] = [];
let fake = first;
const p = await vm.spawn(TTYACM, ["run", "/dev/ttyACM0", ...(cpu === undefined ? [] : [String(cpu)])], { pty: false });
void p.stderr.cancel();
const out = lines(p.stdout);
const stdin = p.stdin.getWriter();
const go = () => stdin.write("go\n");
let done = false;
while (!done) {
const l = await out.next();
if (l === null) {
problems.push("the guest program ended without its done line");
break;
}
let m: RegExpExecArray | null;
if (l.startsWith("FAIL")) problems.push(`guest: ${l}`);
else if ((m = /^step cfg (\d+) (\d) ([NEO]) (\d) (\d)$/.exec(l))) {
const want = {
baudRate: Number(m[1]),
dataBits: Number(m[2]),
parity: ({ N: "none", E: "even", O: "odd" } as const)[m[3] as "N" | "E" | "O"],
stopBits: Number(m[4]),
flowControl: m[5] === "1" ? "hardware" : "none",
};
// The host opens (or reopens) the port with the guest's settings after a short debounce.
const ok = await until(() => fake.isOpen && JSON.stringify(fake.config) === JSON.stringify({ ...fake.config, ...want }), 3000);
if (!ok) problems.push(`${l}: the port is ${fake.isOpen ? "open" : "closed"} with ${JSON.stringify(fake.config)}, want ${JSON.stringify(want)}`);
await go();
} else if ((m = /^step sig (\d) (\d)$/.exec(l))) {
const dtr = m[1] === "1", rts = m[2] === "1";
if (!(await until(() => fake.signals.dataTerminalReady === dtr && fake.signals.requestToSend === rts && !fake.signals.break)))
problems.push(`${l}: the port's signals are ${JSON.stringify(fake.signals)}`);
await go();
} else if (l === "step break") {
await until(() => !fake.signals.break);
const sig = fake.callsOf("setSignals");
const on = sig.findIndex((c) => c.signals.break);
const off = on >= 0 ? sig.findIndex((c, i) => i > on && !c.signals.break) : -1;
if (on < 0 || off < 0) problems.push(`${l}: no break on, then off, in ${JSON.stringify(sig.map((c) => c.signals))}`);
else if (sig[off]!.at - sig[on]!.at < 150) problems.push(`${l}: the break lasted ${(sig[off]!.at - sig[on]!.at).toFixed(0)} ms, want about 250`);
else if (!sig[on]!.signals.dataTerminalReady || !sig[on]!.signals.requestToSend) problems.push(`${l}: DTR or RTS dropped with the break: ${JSON.stringify(sig[on]!.signals)}`);
await go();
} else if ((m = /^step drained (\d+)$/.exec(l))) {
// tcdrain returned: everything the guest wrote has been written out to the port.
const n = fake.written().length;
if (n !== Number(m[1])) problems.push(`${l}: the port got ${n} bytes`);
await go();
} else if ((m = /^miwait (\d+)$/.exec(l))) {
// The guest blocks in TIOCMIWAIT; change the inputs once it surely does.
await sleep(300);
fake.setInputs(INPUTS[Number(m[1])]!);
} else if ((m = /^step errors ([A-Z])$/.exec(l))) {
for (const e of ["BreakError", "FramingError", "ParityError", "BufferOverrunError"]) {
fake.inject(e);
await sleep(60);
}
await sleep(200);
fake.feed(m[1]!);
await go();
} else if (l === "hangup-wait") {
await sleep(300);
fake.unplug();
} else if (l === "step reattach") {
if (vm.serial!.state(0).attached) problems.push(`${l}: slot 0 still attached after the unplug`);
fake = new FakeSerialBackend();
vm.serial!.attach(fake, 0);
await go();
} else if (/^done /.test(l)) done = true;
}
await stdin.close().catch(() => {});
const end = await p.ended;
if (end.type !== "exit" || end.code !== 0) problems.push(`ttyacm ended ${JSON.stringify(end)}`);
return { problems, transcript: out.seen.filter((x) => x !== null).join("\n") };
}
/** Kernel trouble in the guest's dmesg, if any. */
async function trouble(vm: Instance): Promise<string> {
const r = await vm.exec("dmesg", []);
return r.stdout.split("\n").filter((l) => KERNEL_TROUBLE.test(l)).join("\n");
}
describe("kwserial", { skip: noDriver }, () => {
for (const c of [
{ name: "UP", opts: {}, cpu: undefined },
{ name: "SMP, 2 CPUs, the program on CPU 1", opts: { cpus: 2, worker: true }, cpu: 1, skip: !hasSmp && "the bundle has no SMP patch" },
]) {
test(`ttyACM0 on a loopback port (${c.name})`, { skip: c.skip, timeout: 600000 }, async (t) => {
const fake = new FakeSerialBackend();
const vm = await createKernel({ kernel: testKernel, ...c.opts, serial: { attach: [fake] }, mounts, log: () => {} });
try {
const { problems, transcript } = await runSequence(vm, fake, c.cpu);
t.diagnostic(transcript);
assert.deepEqual(problems, [], transcript);
assert.equal(await trouble(vm), "");
} finally {
vm.stop();
}
});
}
test("no ports without the serial option; ENODEV for an empty slot", { timeout: 300000 }, async () => {
const vm = await createKernel({ kernel: testKernel, mounts, log: () => {} });
try {
const r = await vm.exec("sh", ["-c", "ls /dev/ttyACM* 2>&1; dmesg | grep -c kwserial"]);
assert.match(r.stdout, /No such file/);
assert.match(r.stdout, /^0$/m);
} finally {
vm.stop();
}
const vm2 = await createKernel({ kernel: testKernel, serial: 2, mounts, log: () => {} });
try {
const r = await vm2.exec("sh", ["-c", `ls /dev/ttyACM*; ${TTYACM} open-as 0 /dev/ttyACM1`]);
assert.match(r.stdout, /\/dev\/ttyACM0\n\/dev\/ttyACM1\n/);
assert.doesNotMatch(r.stdout, /ttyACM2/);
// serial_core would let root open it (EIO on every read and write); the driver refuses.
assert.match(r.stdout, /open-as 0: No such device/);
assert.equal(vm2.serial!.stats.ports, 2);
} finally {
vm2.stop();
}
});
test("the kw layer gives the ports to dialout, open to the image's user (Alpine)", { skip: !alpine && `no ${path.join(distroDir, "alpine.erofs")}`, timeout: 300000 }, async () => {
const fake = new FakeSerialBackend();
const vm = await createKernel({ kernel: testKernel, distro: alpine!, serial: { attach: [fake] }, mounts, log: () => {} });
try {
// exec() runs as the image's user there.
const r = await vm.exec("sh", ["-c", `ls -l /dev/ttyACM0; id user; ${TTYACM} open-as 1000 /dev/ttyACM0`]);
assert.match(r.stdout, /^crw-rw-rw-\s+\d+\s+root\s+dialout\s/m, r.stdout);
assert.doesNotMatch(r.stdout.split("\n")[1] ?? "", /dialout/, "the image's user is not in dialout (the rc's 0666 is for that)");
assert.match(r.stdout, /open-as 1000: ok/);
} finally {
vm.stop();
}
});
test("a snapshot restored without the device hangs up the open port", { timeout: 300000 }, async () => {
const fake = new FakeSerialBackend();
const vm = await createKernel({ kernel: testKernel, serial: { attach: [fake] }, mounts, log: () => {} });
let snap;
try {
// In its own session: the restore resets the vsock connection of a spawn(), and kwtty ends its programs then.
await vm.exec("sh", ["-c", `setsid ${TTYACM} park /dev/ttyACM0 /tmp/park.out > /tmp/park.log 2>&1 < /dev/null &`]);
let ready = false;
for (let i = 0; i < 100 && !ready; i++) {
ready = (await vm.exec("cat", ["/tmp/park.log"])).stdout === "ready\n";
if (!ready) await sleep(100);
}
assert.ok(ready, "ttyacm park said ready");
assert.ok(await until(() => fake.isOpen), "the port opened");
snap = await vm.snapshot({ stop: true });
} finally {
vm.stop();
}
// Without the serial option the host has no port at all: only the kernel's restore notifier hangs it up.
const vm2 = await createKernel({ kernel: testKernel, restore: snap, mounts, log: () => {} });
try {
let r;
for (let i = 0; i < 100; i++) {
r = await vm2.exec("cat", ["/tmp/park.out"]);
if (r.exitCode === 0) break;
await sleep(100);
}
assert.equal(r!.stdout, "read 0 -\nwrite -1 I/O error\n");
assert.equal(await trouble(vm2), "");
} finally {
vm2.stop();
}
});
});