mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-04 11:10:11 +08:00
Add the x64 single-tier Wasm SIMD JIT implementing jitcore.Jit across alu, mem, branch, vec, and emit modules, wire lazy RFLAGS, data-TLB fast paths, cross-page regions, SMP epoch polling, AES-NI/SHA-256 Wasm codegen, and KWEMU_JIT_SIMD=0 scalar fallback, and pass all native, wasm64+jit, nosimd, guest lockstep, and upstream A64 regression gates.
169 lines
7.4 KiB
JavaScript
169 lines
7.4 KiB
JavaScript
import { readFile, mkdtemp, rm } from "node:fs/promises";
|
|
import { existsSync } from "node:fs";
|
|
import { spawnSync } from "node:child_process";
|
|
import { join, resolve } from "node:path";
|
|
import { tmpdir } from "node:os";
|
|
import { fileURLToPath } from "node:url";
|
|
import { createJitHost } from "./kwemu-jit-host.mjs";
|
|
|
|
const prefix = resolve(process.argv[2] ?? "zig-out");
|
|
const dec = new TextDecoder();
|
|
|
|
const cases = [
|
|
{ dir: "x64", guest: "hello", args: ["x", "y z"], status: 42 },
|
|
{ dir: "x64", guest: "inttest", args: [], status: 0 },
|
|
{ dir: "x64", guest: "x87test", args: [], status: 0 },
|
|
{ dir: "x64", guest: "ssetest", args: [], status: 0 },
|
|
{ dir: "x64", guest: "avxtest", args: [], status: 0 },
|
|
{ dir: "x64", guest: "cryptotest", args: [], status: 0 },
|
|
{ dir: "x64", guest: "atomictest", args: [], status: 0 },
|
|
{ dir: "x64", guest: "edgetest", args: [], status: 0 },
|
|
{ dir: "i386", guest: "hello32", args: ["a", "b c"], status: 7 },
|
|
{ dir: "i386", guest: "ia32test", args: [], status: 0 },
|
|
];
|
|
|
|
let failed = 0;
|
|
|
|
for (const name of ["kwemu.o", "kwemu-jit.o"]) {
|
|
const obj = await WebAssembly.compile(await readFile(join(prefix, "lib", name)));
|
|
const bad = WebAssembly.Module.imports(obj).filter((i) => i.kind === "function" && !i.name.startsWith("kw_host_jit_"));
|
|
if (bad.length) {
|
|
failed++;
|
|
console.log(`FAIL x64 ${name} imports functions: ${bad.map((i) => i.name).join(", ")}`);
|
|
} else {
|
|
console.log(`ok x64 ${name} imports no functions`);
|
|
}
|
|
}
|
|
|
|
const env = { HOME: "/", PATH: "/bin", TERM: "dumb" };
|
|
|
|
function runHost(elf, args) {
|
|
const p = spawnSync(elf, args, { encoding: "utf8", env, timeout: 30000 });
|
|
return { status: p.status, out: p.stdout ?? "", err: p.stderr ?? "" };
|
|
}
|
|
|
|
function runNative(elf, args) {
|
|
const p = spawnSync(join(prefix, "bin", "kwemu-harness"), ["--stats", elf, ...args], { encoding: "utf8", timeout: 30000 });
|
|
return { status: p.status, out: p.stdout ?? "", err: p.stderr ?? "" };
|
|
}
|
|
|
|
function runLockstep(elf, args) {
|
|
const p = spawnSync(join(prefix, "bin", "kwemu-harness"), ["--stats", "--lockstep", "1", elf, ...args], { encoding: "utf8", timeout: 30000 });
|
|
return { status: p.status, out: p.stdout ?? "", err: p.stderr ?? "" };
|
|
}
|
|
|
|
const wasmModule = await WebAssembly.compile(await readFile(join(prefix, "bin", "kwemu-harness.wasm")));
|
|
const jitPath = join(prefix, "bin", "kwemu-harness-jit.wasm");
|
|
const jitModule = await WebAssembly.compile(await readFile(jitPath));
|
|
|
|
let jit32Module = null, jit32Note = "";
|
|
{
|
|
const wasmOpt = process.env.WASM_OPT ?? fileURLToPath(new URL("../vendor/toolchain/binaryen/bin/wasm-opt", import.meta.url));
|
|
if (!existsSync(wasmOpt)) jit32Note = `skipped x64 wasm32+jit: ${wasmOpt} not found (set WASM_OPT)`;
|
|
else {
|
|
const dir = await mkdtemp(join(tmpdir(), "kwemu-x64-jit32-"));
|
|
const out = join(dir, "kwemu-harness-jit32.wasm");
|
|
const p = spawnSync(wasmOpt, ["-g", "--enable-memory64", "--enable-bulk-memory", "--enable-sign-ext", "--enable-nontrapping-float-to-int", "--enable-mutable-globals", "--enable-threads", "--memory64-lowering", "--table64-lowering", jitPath, "-o", out], { encoding: "utf8" });
|
|
if (p.status !== 0) jit32Note = `FAIL x64 wasm-opt lowering: ${p.stderr}`;
|
|
else jit32Module = await WebAssembly.compile(await readFile(out));
|
|
await rm(dir, { recursive: true, force: true });
|
|
}
|
|
}
|
|
|
|
async function runWasm(elf, args, module = wasmModule, jit = null, eagerRequired = false) {
|
|
let out = "", err = "", mem;
|
|
if (!jit && WebAssembly.Module.imports(module).some((i) => i.module === "unkernel")) jit = createJitHost({ available: false });
|
|
const imports = {
|
|
env: {
|
|
host_write: (fd, ptr, len) => {
|
|
const s = dec.decode(new Uint8Array(mem.buffer, Number(ptr), Number(len)));
|
|
if (fd === 2) err += s; else out += s;
|
|
},
|
|
host_now_ns: () => Number(process.hrtime.bigint()),
|
|
},
|
|
};
|
|
if (jit) imports.unkernel = jit.imports;
|
|
const inst = await WebAssembly.instantiate(module, imports);
|
|
const ex = inst.exports;
|
|
mem = ex.memory;
|
|
jit?.attach(ex);
|
|
const image = await readFile(elf);
|
|
const argBytes = new TextEncoder().encode([elf, ...args].join("\0") + "\0");
|
|
const total = image.length + argBytes.length;
|
|
const ptr = Number(ex.kwh_buf(BigInt(total)));
|
|
if (!ptr) throw new Error("image too large");
|
|
new Uint8Array(mem.buffer, ptr, total).set(image);
|
|
new Uint8Array(mem.buffer, ptr + image.length, argBytes.length).set(argBytes);
|
|
const status = ex.kwh_run(BigInt(image.length), BigInt(argBytes.length), 1);
|
|
if (jit) {
|
|
const s = jit.stats;
|
|
if (s.errors.length || s.failures > 0 || (eagerRequired && s.compiles === 0)) {
|
|
if (s.failures > 0) err += `jit host: failures=${s.failures}\n`;
|
|
if (eagerRequired && s.compiles === 0) err += `jit host: zero compiles in eager mode\n`;
|
|
err += s.errors.map((e) => `jit host: ${e}\n`).join("");
|
|
return { status: -1, out, err };
|
|
}
|
|
if (s.compiles) return { status, out, err, jit: `${s.compiles} compiled, ${(s.bytes / 1024).toFixed(0)} KiB, ${(Number(s.compileNs) / 1e6).toFixed(0)} ms` };
|
|
}
|
|
return { status, out, err };
|
|
}
|
|
|
|
function firstDiff(a, b) {
|
|
const x = a.split("\n"), y = b.split("\n");
|
|
for (let i = 0; i < Math.max(x.length, y.length); i++) {
|
|
if (x[i] !== y[i]) return `line ${i + 1}: host ${JSON.stringify(x[i])}, kwemu ${JSON.stringify(y[i])}`;
|
|
}
|
|
return "";
|
|
}
|
|
|
|
function stats(r) {
|
|
const m = /instret=(\d+).*MIPS=([\d.]+)/.exec(r.err);
|
|
return (m ? `${(Number(m[1]) / 1e6).toFixed(2)}M insns, ${m[2]} MIPS` : "") + (r.jit ? `; jit: ${r.jit}` : "");
|
|
}
|
|
|
|
const modes = [
|
|
["native", runNative],
|
|
["wasm64", (elf, args) => runWasm(elf, args)],
|
|
["wasm64+jit", (elf, args) => runWasm(elf, args, jitModule, createJitHost({ eager: true, strict: true }), true)],
|
|
["wasm64+jit/thr", (elf, args) => runWasm(elf, args, jitModule, createJitHost({ strict: true }), false)],
|
|
["wasm64+jit/nosimd", (elf, args) => runWasm(elf, args, jitModule, createJitHost({ eager: true, strict: true, simd: false }), true)],
|
|
["lockstep", runLockstep],
|
|
];
|
|
if (jit32Module) modes.splice(4, 0, ["wasm32+jit", (elf, args) => runWasm(elf, args, jit32Module, createJitHost({ eager: true, mem32: true, strict: true }), true)]);
|
|
const width = Math.max(...modes.map(([m]) => m.length));
|
|
|
|
for (const c of cases) {
|
|
const elf = join(prefix, "guest", c.dir, `${c.guest}.elf`);
|
|
const ref = runHost(elf, c.args);
|
|
if (ref.status !== c.status) {
|
|
failed++;
|
|
console.log(`FAIL x64 host ${c.guest}: status ${ref.status}, want ${c.status}\n${ref.err}`);
|
|
continue;
|
|
}
|
|
let instret = null;
|
|
for (const [mode, fn] of modes) {
|
|
const r = await fn(elf, c.args);
|
|
const n = /instret=(\d+)/.exec(r.err)?.[1];
|
|
if (mode === "wasm64") instret = n;
|
|
let why = "";
|
|
if (r.status !== c.status) why = `status ${r.status}, want ${c.status}`;
|
|
else if (r.out !== ref.out) why = `stdout differs from physical CPU (${firstDiff(ref.out, r.out)})`;
|
|
else if (mode.includes("jit") && n !== instret) why = `instret ${n}, the wasm64 interpreter retired ${instret}`;
|
|
if (why) {
|
|
failed++;
|
|
console.log(`FAIL x64 ${mode.padEnd(width)} ${c.guest}: ${why}\n--- stdout ---\n${r.out}--- stderr ---\n${r.err}`);
|
|
} else {
|
|
console.log(`ok x64 ${mode.padEnd(width)} ${c.guest.padEnd(11)} = physical CPU (${stats(r)})`);
|
|
}
|
|
}
|
|
}
|
|
if (jit32Note) {
|
|
console.log(jit32Note);
|
|
if (jit32Note.startsWith("FAIL")) failed++;
|
|
}
|
|
|
|
if (failed) {
|
|
console.log(`${failed} x64 test(s) failed`);
|
|
process.exit(1);
|
|
}
|