Files
unkernel/test/usb-host.test.ts

499 lines
22 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// kwusb's host side (js/core/usb.ts) against FakeUsbBackend (usb-fake.ts):
// the imports driven directly on a memory of their own, as the kernel's
// driver calls them (struct kwusb_xfer written here, completions reaped
// here), with UsbDevice and UsbHost joined as createKernel joins them, and
// once with the backend behind the worker bridge across a MessageChannel
// (UsbRemote on one side, UsbWorkerSide on the other). No kernel is
// booted; test/usb.test.ts is the end-to-end test with the kernel.
//
// node --test test/usb-host.test.ts (pnpm test:usb-host; pnpm test:usb runs both)
import { afterEach, test } from "node:test";
import assert from "node:assert/strict";
import { MessageChannel } from "node:worker_threads";
import {
USB_DONE_SIZE, USB_OP_RESET, USB_PORT_CONNECTED, USB_PORT_EV_CHANGE, USB_PORT_EV_RESET, USB_SEG_SIZE, USB_XFER_BULK, USB_XFER_CONTROL,
USB_XFER_INT, USB_XFER_ISO, USB_XFER_SIZE, USB_X_ZERO_PACKET, UsbDevice, UsbHost, UsbRemote, UsbWorkerSide, deriveSpeed, filterConfig, parseConfig,
type UsbFromWorker, type UsbToWorker,
} from "../js/core/usb.ts";
import { FakeUsbBackend } from "../js/core/usb-fake.ts";
const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
async function until(what: string, cond: () => boolean, ms = 2000): Promise<void> {
const end = performance.now() + ms;
while (!cond()) {
if (performance.now() > end) throw new Error(`timed out waiting for ${what}`);
await sleep(1);
}
}
const EPIPE = 32, EOVERFLOW = 75, ENODEV = 19, ESHUTDOWN = 108;
type Imports = {
wasm_driver_usb_init(): number;
wasm_driver_usb_changed(): number;
wasm_driver_usb_port(slot: number): number;
wasm_driver_usb_port_op(slot: number, op: number): number;
wasm_driver_usb_submit(x: bigint): number;
wasm_driver_usb_cancel(id: number): void;
wasm_driver_usb_reap(done: bigint, max: number): number;
};
interface Done {
id: number;
status: number;
actual: number;
errors: number;
}
const hosts: UsbHost[] = [];
afterEach(() => {
for (const h of hosts.splice(0)) h.shutdown();
});
/** The kernel's side of kwusb on a memory of its own. */
function machine(ports = 4) {
const memory = new WebAssembly.Memory({ initial: 160 });
const u8 = new Uint8Array(memory.buffer);
const dv = new DataView(memory.buffer);
let irqs = 0;
const logs: string[] = [];
const dev = new UsbDevice({ ports, memory: () => memory, raise: () => irqs++ });
const host = new UsbHost({ ports, device: dev, log: (m) => logs.push(m) });
hosts.push(host);
const k = dev.imports() as unknown as Imports;
assert.equal(k.wasm_driver_usb_init(), ports);
let heap = 0x1000;
const alloc = (n: number) => {
const at = heap;
heap += (n + 15) & ~15;
assert.ok(heap < memory.buffer.byteLength, "test heap");
return at;
};
let nextId = 1;
const DONE = alloc(64 * USB_DONE_SIZE);
const reaped = new Map<number, Done>();
const m = {
dev, host, k, u8, logs, get irqs() { return irqs; },
alloc,
/** Write a struct kwusb_xfer and submit it: the id, or throws with the errno. */
submit(slot: number, ep: number, type: number, o: { length?: number; data?: Uint8Array; setup?: number[]; flags?: number; maxpacket?: number; segs?: number[]; packets?: number[] } = {}) {
const length = o.data?.length ?? o.length ?? 0;
const segLens = o.segs ?? (length ? [length] : []);
const segs = segLens.map((l) => ({ at: alloc(l), len: l }));
if (o.data) {
let off = 0;
for (const s of segs) {
u8.set(o.data.subarray(off, off + s.len), s.at);
off += s.len;
}
}
const x = alloc(USB_XFER_SIZE + segs.length * USB_SEG_SIZE);
const id = nextId++;
dv.setUint32(x, id, true);
dv.setUint8(x + 4, slot);
dv.setUint8(x + 5, ep);
dv.setUint8(x + 6, type);
dv.setUint8(x + 7, o.flags ?? 0);
dv.setUint32(x + 8, length, true);
dv.setUint32(x + 12, segs.length, true);
dv.setUint32(x + 16, o.maxpacket ?? 512, true);
if (o.setup) {
const sp = alloc(8);
u8.set(o.setup, sp);
dv.setBigUint64(x + 32, BigInt(sp), true);
}
if (o.packets) {
const iso = alloc(o.packets.length * 16);
let off = 0;
o.packets.forEach((l, i) => {
dv.setUint32(iso + i * 16, off, true);
dv.setUint32(iso + i * 16 + 4, l, true);
off += l;
});
dv.setUint32(x + 24, o.packets.length, true);
dv.setBigUint64(x + 40, BigInt(iso), true);
(m as { lastIso?: number }).lastIso = iso;
}
segs.forEach((s, i) => {
dv.setBigUint64(x + USB_XFER_SIZE + i * USB_SEG_SIZE, BigInt(s.at), true);
dv.setUint32(x + USB_XFER_SIZE + i * USB_SEG_SIZE + 8, s.len, true);
});
const r = k.wasm_driver_usb_submit(BigInt(x));
if (r) throw Object.assign(new Error(`submit: errno ${-r}`), { errno: -r });
bufs.set(id, segs);
return id;
},
/** The bytes of transfer `id`'s buffer (its segments joined). */
bytes(id: number, n?: number) {
const segs = bufs.get(id)!;
const out = new Uint8Array(segs.reduce((a, s) => a + s.len, 0));
let off = 0;
for (const s of segs) {
out.set(u8.subarray(s.at, s.at + s.len), off);
off += s.len;
}
return out.subarray(0, n ?? out.length);
},
reap() {
for (;;) {
const n = k.wasm_driver_usb_reap(BigInt(DONE), 64);
for (let i = 0; i < n; i++) {
const d: Done = { id: dv.getUint32(DONE + i * 16, true), status: dv.getInt32(DONE + i * 16 + 4, true), actual: dv.getUint32(DONE + i * 16 + 8, true), errors: dv.getUint32(DONE + i * 16 + 12, true) };
reaped.set(d.id, d);
}
if (n < 64) break;
}
},
async wait(id: number, ms = 2000): Promise<Done> {
await until(`transfer ${id}`, () => (m.reap(), reaped.has(id)), ms);
return reaped.get(id)!;
},
reaped,
control(slot: number, setup: number[], data?: Uint8Array, length?: number) {
const wLength = data?.length ?? length ?? 0;
const s = [...setup.slice(0, 6), wLength & 0xff, wLength >> 8];
return m.submit(slot, 0, USB_XFER_CONTROL, { setup: s, data, length: wLength, maxpacket: 64 });
},
/** The kernel's view of the ports after the IRQ: each changed slot's status word. */
ports() {
const changed = k.wasm_driver_usb_changed();
const out: Record<number, number> = {};
for (let i = 0; i < ports; i++) if (changed & (1 << i)) out[i] = k.wasm_driver_usb_port(i);
return out;
},
/** What usbcore does: reset (answered at once at first), GET_DESCRIPTOR, SET_ADDRESS, SET_CONFIGURATION 1. */
async enumerate(slot: number) {
assert.equal(k.wasm_driver_usb_port_op(slot, USB_OP_RESET), 1);
const d8 = await m.wait(m.control(slot, [0x80, 6, 0, 1, 0, 0], undefined, 64));
assert.equal(d8.status, 0);
assert.equal((await m.wait(m.control(slot, [0x00, 5, 2, 0, 0, 0]))).status, 0);
const conf = m.control(slot, [0x00, 9, 1, 0, 0, 0]);
assert.equal((await m.wait(conf)).status, 0);
},
};
const bufs = new Map<number, Array<{ at: number; len: number }>>();
return m;
}
const enc = (s: string) => new TextEncoder().encode(s);
const dec = (b: Uint8Array) => new TextDecoder().decode(b);
function pattern(n: number, seed = 1) {
const b = new Uint8Array(n);
let x = seed;
for (let i = 0; i < n; i++) {
x = (x * 1103515245 + 12345) >>> 0;
b[i] = x >>> 24;
}
return b;
}
test("descriptors: the speed from them, protected interfaces hidden", () => {
for (const speed of ["full", "high", "super"] as const) {
const f = new FakeUsbBackend({ speed });
assert.equal(deriveSpeed(f.device, [f.config]), speed, speed);
const { config, hidden } = filterConfig(f.config);
assert.deepEqual(hidden, [1]);
const info = parseConfig(config);
assert.deepEqual([...new Set(info.interfaces.map((i) => i.number))], [0]);
assert.equal(config[4], 1, "bNumInterfaces");
assert.equal(config[2]! | (config[3]! << 8), config.length, "wTotalLength");
assert.ok(!info.endpoints.some((e) => e.address === 0x84), "the HID endpoint goes with its interface");
assert.equal(info.endpoints.filter((e) => e.address === 0x81).length, 2, "both alternate settings stay");
}
// A USB 1.1 mouse-like device: 8-byte ep0, one small interrupt endpoint.
const ls = Uint8Array.from([18, 1, 0x10, 0x01, 0, 0, 0, 8, 1, 0, 2, 0, 0, 1, 0, 0, 0, 1]);
const lsConf = Uint8Array.from([9, 2, 25, 0, 1, 1, 0, 0x80, 50, 9, 4, 0, 0, 1, 0xff, 0, 0, 0, 7, 5, 0x81, 3, 8, 0, 10]);
assert.equal(deriveSpeed(ls, [lsConf]), "low");
// A USB 2.0 full-speed serial adapter (bcdUSB 2.0, 64-byte bulk).
const fs = Uint8Array.from([18, 1, 0x00, 0x02, 0, 0, 0, 64, 1, 0, 2, 0, 0, 1, 0, 0, 0, 1]);
const fsConf = Uint8Array.from([9, 2, 32, 0, 1, 1, 0, 0x80, 50, 9, 4, 0, 0, 2, 0xff, 0, 0, 0, 7, 5, 0x81, 2, 64, 0, 0, 7, 5, 0x02, 2, 64, 0, 0]);
assert.equal(deriveSpeed(fs, [fsConf]), "full");
// A USB 3 device on a USB 2 port reports bcdUSB 2.1 and a 64-byte ep0.
const hs3 = Uint8Array.from([18, 1, 0x10, 0x02, 0, 0, 0, 64, 1, 0, 2, 0, 0, 1, 0, 0, 0, 1]);
const hsConf = Uint8Array.from([9, 2, 32, 0, 1, 1, 0, 0x80, 50, 9, 4, 0, 0, 2, 0xff, 0, 0, 0, 7, 5, 0x81, 2, 0, 2, 0, 7, 5, 0x02, 2, 0, 2, 0]);
assert.equal(deriveSpeed(hs3, [hsConf]), "high");
});
test("attach: the port connects at the device's speed; enumeration is answered from the descriptors", async () => {
const m = machine();
const fake = new FakeUsbBackend();
assert.equal(await m.host.attach(fake), 0);
const p = m.ports();
assert.equal(p[0], USB_PORT_CONNECTED | (3 << 1) | USB_PORT_EV_CHANGE, "connected, high speed (3), a change");
assert.deepEqual(m.host.state(0).hidden, [1]);
assert.equal(m.host.state(0).speed, "high");
const reads = fake.callsOf("controlTransferIn").length;
// usbcore: reset (answered at once), 64-byte device descriptor, SET_ADDRESS, the 18 bytes, the configuration.
assert.equal(m.k.wasm_driver_usb_port_op(0, USB_OP_RESET), 1);
const d64 = await m.wait(m.control(0, [0x80, 6, 0, 1, 0, 0], undefined, 64));
assert.deepEqual({ s: d64.status, n: d64.actual }, { s: 0, n: 18 });
assert.equal((await m.wait(m.control(0, [0x00, 5, 7, 0, 0, 0]))).status, 0);
const c9 = m.control(0, [0x80, 6, 0, 2, 0, 0], undefined, 9);
assert.equal((await m.wait(c9)).actual, 9);
const total = m.bytes(c9)[2]! | (m.bytes(c9)[3]! << 8);
const cAll = m.control(0, [0x80, 6, 0, 2, 0, 0], undefined, total);
assert.equal((await m.wait(cAll)).actual, total);
assert.equal(m.bytes(cAll)[4], 1, "one interface shown");
assert.ok(total < fake.config.length);
assert.equal(fake.callsOf("controlTransferIn").length, reads, "answered here, not by the device");
// A string descriptor passes through.
const str = m.control(0, [0x80, 6, 2, 3, 0x09, 0x04], undefined, 255);
const sd = await m.wait(str);
assert.equal(sd.status, 0);
assert.equal(new TextDecoder("utf-16le").decode(m.bytes(str, sd.actual).subarray(2)), "kwusb test device");
// SET_CONFIGURATION: selectConfiguration and claims, without the hidden interface.
assert.equal((await m.wait(m.control(0, [0x00, 9, 1, 0, 0, 0]))).status, 0);
assert.deepEqual(fake.callsOf("claimInterface").map((c) => c.args[0]), [0]);
assert.deepEqual(m.host.state(0).claimed, [0]);
assert.equal(fake.callsOf("controlTransferOut").length, 0, "SET_ADDRESS and SET_CONFIGURATION never reach the device as requests");
const gc = m.control(0, [0x80, 8, 0, 0, 0, 0], undefined, 1);
await m.wait(gc);
assert.equal(m.bytes(gc)[0], 1);
// A request to the hidden interface stalls here.
const before = fake.calls.length;
assert.equal((await m.wait(m.control(0, [0xa1, 1, 0, 0, 1, 0], undefined, 8))).status, -EPIPE);
assert.equal(fake.calls.length, before);
// A port reset after the guest configured the device resets it, and its end is an event.
assert.equal(m.k.wasm_driver_usb_port_op(0, USB_OP_RESET), 0);
await until("the reset", () => fake.resets === 1);
await until("the reset's event", () => (m.ports()[0] ?? 0) & USB_PORT_EV_RESET ? true : false);
assert.equal(m.host.state(0).configuration, 0);
});
test("control: vendor requests in and out", async () => {
const m = machine();
const fake = new FakeUsbBackend();
await m.host.attach(fake);
await m.enumerate(0);
const out = m.control(0, [0x40, 0x02, 0, 0, 0, 0], enc("hello, device"));
assert.equal((await m.wait(out)).actual, 13);
const inn = m.control(0, [0xc0, 0x01, 0, 0, 0, 0], undefined, 64);
const r = await m.wait(inn);
assert.equal(dec(m.bytes(inn, r.actual)), "hello, device");
});
test("bulk: a large loopback over segments, ZLP, short reads and babble", async () => {
const m = machine();
const fake = new FakeUsbBackend();
await m.host.attach(fake);
await m.enumerate(0);
const big = pattern(1 << 20);
const segs = Array(64).fill(16384);
const o = m.submit(0, 0x01, USB_XFER_BULK, { data: big, segs });
const i = m.submit(0, 0x81, USB_XFER_BULK, { length: big.length, segs });
assert.equal((await m.wait(o)).actual, big.length);
const r = await m.wait(i);
assert.equal(r.actual, big.length);
assert.ok(Buffer.from(m.bytes(i)).equals(Buffer.from(big)), "the bytes came back");
// URB_ZERO_PACKET on a full last packet: a zero-length transfer follows; reads see 512 bytes, then 0.
const z = m.submit(0, 0x01, USB_XFER_BULK, { data: pattern(512), flags: USB_X_ZERO_PACKET });
await m.wait(z);
assert.deepEqual(fake.callsOf("transferOut").slice(-2).map((c) => c.args[1]), [512, 0]);
assert.equal((await m.wait(m.submit(0, 0x81, USB_XFER_BULK, { length: 4096 }))).actual, 512);
assert.equal((await m.wait(m.submit(0, 0x81, USB_XFER_BULK, { length: 4096 }))).actual, 0);
// A short read: 100 bytes into 4096.
await m.wait(m.submit(0, 0x01, USB_XFER_BULK, { data: pattern(100) }));
assert.equal((await m.wait(m.submit(0, 0x81, USB_XFER_BULK, { length: 4096 }))).actual, 100);
// Babble: 1000 bytes waiting, a 100-byte read (inside a packet).
await m.wait(m.submit(0, 0x01, USB_XFER_BULK, { data: pattern(1000) }));
assert.equal((await m.wait(m.submit(0, 0x81, USB_XFER_BULK, { length: 100 }))).status, -EOVERFLOW);
});
test("interrupt IN waits for data", async () => {
const m = machine();
const fake = new FakeUsbBackend();
await m.host.attach(fake);
await m.enumerate(0);
const id = m.submit(0, 0x82, USB_XFER_INT, { length: 64, maxpacket: 64 });
await sleep(20);
m.reap();
assert.ok(!m.reaped.has(id), "pending");
fake.interrupt("tick");
const r = await m.wait(id);
assert.equal(dec(m.bytes(id, r.actual)), "tick");
// Through vendor request 0x05 too.
const id2 = m.submit(0, 0x82, USB_XFER_INT, { length: 64, maxpacket: 64 });
await m.wait(m.control(0, [0x40, 0x05, 0, 0, 0, 0], enc("tock")));
assert.equal(dec(m.bytes(id2, (await m.wait(id2)).actual)), "tock");
});
test("an unlinked IN leaves its read pending; its data goes to the next URB", async () => {
const m = machine();
const fake = new FakeUsbBackend();
await m.host.attach(fake);
await m.enumerate(0);
const a = m.submit(0, 0x81, USB_XFER_BULK, { length: 4096 });
await until("the read", () => fake.pendingReads(0x81) === 1);
m.k.wasm_driver_usb_cancel(a);
const reads = fake.callsOf("transferIn").length;
// The next URB takes the spare read instead of a new one.
const b = m.submit(0, 0x81, USB_XFER_BULK, { length: 4096 });
assert.equal(fake.callsOf("transferIn").length, reads);
await m.wait(m.submit(0, 0x01, USB_XFER_BULK, { data: enc("parked bytes") }));
const r = await m.wait(b);
assert.equal(dec(m.bytes(b, r.actual)), "parked bytes");
assert.ok(!m.reaped.has(a), "nothing for the cancelled one");
// Data that comes while no URB waits is parked for the next.
const c = m.submit(0, 0x81, USB_XFER_BULK, { length: 4096 });
await until("the read", () => fake.pendingReads(0x81) === 1);
m.k.wasm_driver_usb_cancel(c);
await m.wait(m.submit(0, 0x01, USB_XFER_BULK, { data: enc("kept") }));
await sleep(5);
const d = m.submit(0, 0x81, USB_XFER_BULK, { length: 2 });
const e = m.submit(0, 0x81, USB_XFER_BULK, { length: 4096 });
assert.equal(dec(m.bytes(d, (await m.wait(d)).actual)), "ke", "a smaller URB takes what fits");
assert.equal(dec(m.bytes(e, (await m.wait(e)).actual)), "pt", "the rest goes to the next");
// A transfer that finished but was not reaped is dropped by the cancel.
const f = m.submit(0, 0x81, USB_XFER_BULK, { length: 64 });
m.submit(0, 0x01, USB_XFER_BULK, { data: enc("x") });
await until("the loopback", () => fake.looped > 0 && fake.pendingReads(0x81) === 0);
await sleep(5);
m.k.wasm_driver_usb_cancel(f);
m.reap();
assert.ok(!m.reaped.has(f));
});
test("stall and clear halt", async () => {
const m = machine();
const fake = new FakeUsbBackend();
await m.host.attach(fake);
await m.enumerate(0);
await m.wait(m.control(0, [0x40, 0x03, 0x81, 0, 0, 0]));
assert.equal((await m.wait(m.submit(0, 0x81, USB_XFER_BULK, { length: 64 }))).status, -EPIPE);
// CLEAR_FEATURE(ENDPOINT_HALT) on 0x81.
assert.equal((await m.wait(m.control(0, [0x02, 1, 0, 0, 0x81, 0]))).status, 0);
assert.deepEqual(fake.callsOf("clearHalt").map((c) => c.args), [["in", 1]]);
await m.wait(m.submit(0, 0x01, USB_XFER_BULK, { data: enc("after") }));
const r = m.submit(0, 0x81, USB_XFER_BULK, { length: 64 });
assert.equal(dec(m.bytes(r, (await m.wait(r)).actual)), "after");
// A rejected transfer is EPROTO.
fake.failNext(0x01);
assert.equal((await m.wait(m.submit(0, 0x01, USB_XFER_BULK, { data: enc("y") }))).status, -71);
});
test("isochronous IN in alternate setting 1", async () => {
const m = machine();
const fake = new FakeUsbBackend();
await m.host.attach(fake);
await m.enumerate(0);
assert.equal((await m.wait(m.control(0, [0x01, 11, 1, 0, 0, 0]))).status, 0);
assert.deepEqual(fake.callsOf("selectAlternateInterface").map((c) => c.args), [[0, 1]]);
const id = m.submit(0, 0x83, USB_XFER_ISO, { length: 4 * 64, packets: [64, 64, 64, 64], maxpacket: 512 });
const iso = (m as unknown as { lastIso: number }).lastIso;
const r = await m.wait(id);
assert.equal(r.status, 0);
assert.equal(r.errors, 0);
assert.equal(r.actual, 4 * 16);
const dv = new DataView(m.u8.buffer);
for (let p = 0; p < 4; p++) {
assert.equal(dv.getUint32(iso + p * 16 + 8, true), 16, `packet ${p} actual`);
assert.equal(dv.getInt32(iso + p * 16 + 12, true), 0);
assert.equal(m.bytes(id)[p * 64 + 1], (m.bytes(id)[p * 64]! + 1) & 0xff, "at the packet's offset");
}
});
test("disconnect with URBs pending, then a new device in the slot", async () => {
const m = machine();
const fake = new FakeUsbBackend();
await m.host.attach(fake);
await m.enumerate(0);
const a = m.submit(0, 0x81, USB_XFER_BULK, { length: 64 });
const b = m.submit(0, 0x82, USB_XFER_INT, { length: 64, maxpacket: 64 });
m.ports();
fake.unplug();
assert.equal((await m.wait(a)).status, -ESHUTDOWN);
assert.equal((await m.wait(b)).status, -ESHUTDOWN);
assert.equal(m.ports()[0], USB_PORT_EV_CHANGE, "disconnected");
assert.equal(m.host.state(0).attached, false);
assert.throws(() => m.submit(0, 0x81, USB_XFER_BULK, { length: 64 }), (e: { errno?: number }) => e.errno === ENODEV);
assert.equal(m.k.wasm_driver_usb_port_op(0, USB_OP_RESET), -ENODEV);
const again = new FakeUsbBackend({ speed: "super" });
assert.equal(await m.host.attach(again, { slot: 0 }), 0);
assert.equal(m.ports()[0], USB_PORT_CONNECTED | (5 << 1) | USB_PORT_EV_CHANGE, "SuperSpeed (5)");
await m.enumerate(0);
await m.wait(m.submit(0, 0x01, USB_XFER_BULK, { data: enc("hi"), maxpacket: 1024 }));
const r = m.submit(0, 0x81, USB_XFER_BULK, { length: 1024, maxpacket: 1024 });
assert.equal(dec(m.bytes(r, (await m.wait(r)).actual)), "hi");
// detach() closes the device.
await m.host.detach(0);
assert.equal(again.opened, false);
assert.equal(m.ports()[0], USB_PORT_EV_CHANGE);
});
test("snapshot state: slots with a device come back disconnected", async () => {
const m = machine(2);
await m.host.attach(new FakeUsbBackend());
assert.deepEqual(m.dev.saveState(), { ports: 2, connected: [0] });
const mem = new WebAssembly.Memory({ initial: 1 });
const fresh = new UsbDevice({ ports: 2, memory: () => mem, raise: () => {} });
fresh.restoreState({ ports: 2, connected: [0] });
const k = fresh.imports() as unknown as Imports;
assert.equal(k.wasm_driver_usb_changed(), 1);
assert.equal(k.wasm_driver_usb_port(0), USB_PORT_EV_CHANGE);
});
test("worker bridge: a backend on the other side of a MessageChannel", async () => {
const memory = new WebAssembly.Memory({ initial: 64 });
const dev = new UsbDevice({ ports: 2, memory: () => memory, raise: () => {} });
const host = new UsbHost({ ports: 2, device: dev, log: () => {} });
hosts.push(host);
(dev.imports() as unknown as Imports).wasm_driver_usb_init();
const ch = new MessageChannel();
const side = new UsbWorkerSide(host, { post: (m) => ch.port1.postMessage(m) });
ch.port1.on("message", (m: UsbToWorker) => side.receive(m));
const remote = new UsbRemote(2, (m) => ch.port2.postMessage(m));
ch.port2.on("message", (m: UsbFromWorker) => remote.receive(m));
try {
const fake = new FakeUsbBackend();
assert.equal(await remote.attach(fake), 0);
await until("the state", () => remote.state(0).phase === "connected");
assert.equal(remote.state(0).runs, "owner");
assert.equal(remote.slotOf(fake), 0);
assert.equal(fake.opened, true);
// The kernel's end drives it as inline.
const k = dev.imports() as unknown as Imports;
const dv = new DataView(memory.buffer);
const put = (x: number, id: number, ep: number, type: number, len: number, buf: number, setup = 0) => {
dv.setUint32(x, id, true);
dv.setUint8(x + 4, 0);
dv.setUint8(x + 5, ep);
dv.setUint8(x + 6, type);
dv.setUint32(x + 8, len, true);
dv.setUint32(x + 12, len ? 1 : 0, true);
dv.setUint32(x + 16, 512, true);
dv.setBigUint64(x + 32, BigInt(setup), true);
dv.setBigUint64(x + 48, BigInt(buf), true);
dv.setUint32(x + 56, len, true);
return k.wasm_driver_usb_submit(BigInt(x));
};
new Uint8Array(memory.buffer).set([0x00, 9, 1, 0, 0, 0, 0, 0], 0x100);
assert.equal(put(0x200, 1, 0, USB_XFER_CONTROL, 0, 0, 0x100), 0);
await until("SET_CONFIGURATION", () => k.wasm_driver_usb_reap(0x800n, 16) === 1);
assert.equal(dv.getInt32(0x804, true), 0);
new Uint8Array(memory.buffer).set(enc("across"), 0x1000);
assert.equal(put(0x300, 2, 0x01, USB_XFER_BULK, 6, 0x1000), 0);
assert.equal(put(0x400, 3, 0x81, USB_XFER_BULK, 64, 0x2000), 0);
const seen = new Set<number>();
await until("the transfers", () => {
const n = k.wasm_driver_usb_reap(0x800n, 16);
for (let i = 0; i < n; i++) {
seen.add(dv.getUint32(0x800 + i * 16, true));
assert.equal(dv.getInt32(0x800 + i * 16 + 4, true), 0);
}
return seen.size === 2;
});
assert.equal(dec(new Uint8Array(memory.buffer, 0x2000, 6)), "across");
// An unplug on the owner's side reaches the worker's host.
fake.unplug();
await until("the disconnect", () => !remote.state(0).attached);
assert.equal(remote.slotOf(fake), -1);
} finally {
ch.port1.close();
ch.port2.close();
}
});