Files
unkernel/test/bluetooth.test.ts

246 lines
11 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// kwbt end to end: the kernel's Bluetooth transport
// (drivers/bluetooth/kwbt.c, hci0) on the SDK's device model
// (js/core/bluetooth.ts) with the emulated LE controller
// (js/core/bluetooth-le.ts) and FakeGattCentral's demo peripheral. The
// guest program test/bluetooth/kwbt.c (built here with zig cc, static
// aarch64 musl, from a host directory mounted over 9p) works on raw
// AF_BLUETOOTH sockets, without BlueZ: management to power on and discover,
// an L2CAP socket on ATT for GATT (discovery, read, write, notifications),
// and at its steps this side acts: a notification from the device, a
// remote disconnect, the controller detached while connected, a new one
// attached. On the UP kernel, and on the SMP kernel with the program on
// CPU 1 (worker mode), where the driver hands its work to CPU 0. Also: no
// adapter without the option (and none until a controller is attached),
// a kernel host without the bt imports (the unresolved probe answers
// -ENODEV), and a snapshot restored onto a machine with a new controller:
// the connection fails, hci0 is replaced and works.
//
// BlueZ itself (bluetoothd, bluetoothctl) in the Debian guest is checked by
// hand (.agents/kernel/devices.md, kwbt).
//
// node --test test/bluetooth.test.ts (pnpm test:bluetooth runs the host's unit tests too)
// UNKERNEL_TEST_KERNEL=path ... another bundle instead of vendor/build/bundle/unkernel.wasm
// 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 { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import {
BluetoothDevice, FAKE_LOOPBACK_CHAR, FakeGattCentral, VirtualLeController, bundledKernelUrl, createKernel, deviceAddress, fakeDemoPeripheral, formatAddress,
loadKernelModule, nodeFs,
} 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);
/** 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));
const kernelBytes = readFileSync(kernelFile);
const hasDriver = WebAssembly.Module.imports(await loadKernelModule(kernelBytes)).some((i) => i.name === "wasm_driver_bt_init");
const hasSmp = WebAssembly.Module.imports(await loadKernelModule(kernelBytes, { smp: true })).some((i) => i.name === "wasm_cpu_start");
const noDriver = !hasDriver && "the kernel has no kwbt";
const ID = fakeDemoPeripheral().id;
const ADDR = formatAddress(deviceAddress(ID));
const dir = mkdtempSync(path.join(tmpdir(), "kw-bt-test-"));
const mounts = { "/mnt/bt": { fs: nodeFs(dir), readOnly: true } };
const KWBT = "/mnt/bt/kwbt";
before(() => {
if (noDriver) return;
const cc = spawnSync(process.env.ZIG ?? "zig", ["cc", "-target", "aarch64-linux-musl", "-mcpu=generic", "-static", "-O2", "-s", "-o", path.join(dir, "kwbt"), path.join(root, "test/bluetooth/kwbt.c")], { encoding: "utf8" });
assert.equal(cc.status, 0, `building kwbt: ${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++]!;
},
};
}
function fakeController(log?: (m: string) => void) {
const central = new FakeGattCentral([fakeDemoPeripheral()]);
return { central, ctl: new VirtualLeController({ central, log: log ?? (() => {}) }) };
}
/** Run `kwbt run ADDR [cpu]` and answer its steps; returns the problems seen. */
async function runSequence(vm: Instance, first: ReturnType<typeof fakeController>, cpu?: number): Promise<{ problems: string[]; transcript: string }> {
const problems: string[] = [];
const p = await vm.spawn(KWBT, ["run", ADDR, ...(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");
for (;;) {
const l = await out.next();
if (l === null) {
problems.push("the guest program ended without its done line");
break;
}
if (l.startsWith("FAIL")) problems.push(`guest: ${l}`);
else if (l === "step notify") {
if (!first.central.notify(ID, FAKE_LOOPBACK_CHAR, new TextEncoder().encode("host"))) problems.push(`${l}: the device has no connection`);
await go();
} else if (l === "step remote-disconnect") {
first.central.disconnectRemote(ID);
await go();
} else if (l === "step detach") {
if (!first.central.connected(ID)) problems.push(`${l}: not connected before the detach`);
await vm.bluetooth!.detach();
if (first.central.connected(ID)) problems.push(`${l}: the detach left the device connected`);
await go();
} else if (l === "step attach") {
await vm.bluetooth!.attach(fakeController().ctl);
await go();
} else if (/^done /.test(l)) break;
}
await stdin.close().catch(() => {});
const end = await p.ended;
if (end.type !== "exit" || end.code !== 0) problems.push(`kwbt 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("kwbt", { 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(`hci0 on the emulated LE controller (${c.name})`, { skip: c.skip, timeout: 600000 }, async (t) => {
const fake = fakeController((m) => t.diagnostic(m));
const vm = await createKernel({ kernel: testKernel, ...c.opts, bluetooth: { attach: fake.ctl }, mounts, log: () => {} });
try {
const { problems, transcript } = await runSequence(vm, fake, c.cpu);
t.diagnostic(transcript);
assert.deepEqual(problems, [], transcript);
assert.equal(await trouble(vm), "");
assert.ok(fake.ctl.stats.attRequests >= 8, `${fake.ctl.stats.attRequests} ATT requests`);
} finally {
vm.stop();
}
});
}
test("no adapter without the option, none until a controller is attached; a host without the imports", { timeout: 300000 }, async () => {
const vm = await createKernel({ kernel: testKernel, mounts, log: () => {} });
try {
const r = await vm.exec("sh", ["-c", "ls /sys/class/bluetooth | wc -l; dmesg | grep -c kwbt"]);
assert.equal(r.stdout, "0\n0\n");
} finally {
vm.stop();
}
const vm2 = await createKernel({ kernel: testKernel, bluetooth: true, mounts, log: () => {} });
try {
let r = await vm2.exec("sh", ["-c", "ls /sys/class/bluetooth | wc -l; dmesg | grep kwbt"]);
assert.match(r.stdout, /^0\n.*kwbt: host Bluetooth/s);
assert.equal(vm2.bluetooth!.probed, true);
// A controller attached later: hci0 appears.
await vm2.bluetooth!.attach(fakeController().ctl);
r = await vm2.exec("sh", ["-c", `for i in $(seq 50); do [ -e /sys/class/bluetooth/hci0 ] && break; sleep 0.1; done; ${KWBT} find ${ADDR}`]);
assert.match(r.stdout, new RegExp(`found ${ADDR} unkernel fake`), r.stdout + r.stderr);
} finally {
vm2.stop();
}
// A host without kwbt's imports (an older SDK's): the unresolved probe gets -ENODEV, the boot goes on.
const logs: string[] = [];
const imports = BluetoothDevice.prototype.imports;
BluetoothDevice.prototype.imports = () => ({});
let vm3: Instance;
try {
vm3 = await createKernel({ kernel: testKernel, bluetooth: true, mounts, log: (m) => logs.push(m) });
} finally {
BluetoothDevice.prototype.imports = imports;
}
try {
const r = await vm3.exec("sh", ["-c", "ls /sys/class/bluetooth | wc -l; dmesg | grep -c kwbt"]);
assert.equal(r.stdout, "0\n0\n");
assert.ok(logs.some((l) => /unresolved imports: .*wasm_driver_bt_init/.test(l)), logs.join("\n"));
} finally {
vm3.stop();
}
});
test("a snapshot restored onto a new controller: the connection fails, hci0 is replaced and works", { timeout: 300000 }, async () => {
const fake = fakeController();
const vm = await createKernel({ kernel: testKernel, bluetooth: { attach: fake.ctl }, 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 ${KWBT} park ${ADDR} /tmp/park.out > /tmp/park.log 2>&1 < /dev/null &`]);
let ready = false;
for (let i = 0; i < 300 && !ready; i++) {
ready = /^ready$/m.test((await vm.exec("cat", ["/tmp/park.log"])).stdout);
if (!ready) await sleep(100);
}
assert.ok(ready, `kwbt park said ready: ${(await vm.exec("cat", ["/tmp/park.log"])).stdout}`);
assert.ok(fake.central.connected(ID));
snap = await vm.snapshot({ stop: true });
} finally {
vm.stop();
}
const next = fakeController();
const vm2 = await createKernel({ kernel: testKernel, restore: snap, bluetooth: { attach: next.ctl }, 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.match(r!.stdout, /^recv -1 /, "the old connection fails");
r = await vm2.exec("sh", ["-c", `for i in $(seq 50); do [ -e /sys/class/bluetooth/hci0 ] && break; sleep 0.1; done; dmesg | grep -c 'kwbt: controller attached'; ${KWBT} find ${ADDR}`]);
assert.match(r.stdout, /^2\n/, "attached again after the restore");
assert.match(r.stdout, new RegExp(`found ${ADDR}`), r.stdout + r.stderr);
assert.equal(await trouble(vm2), "");
} finally {
vm2.stop();
}
});
});