kwemu: chain compiled modules in desktop Safari, where it measures 10-16% faster on Perl, and add /jit-probe.html, which times guest work with chaining off and on in a browser (KW_JIT_TAIL=1 or 0 answers instead of the engine test) (#148)

This commit is contained in:
pi0x
2026-12-02 18:09:14 +09:00
committed by GitHub
parent bdcc90c51f
commit dd108fa943
5 changed files with 325 additions and 11 deletions

View File

@@ -278,7 +278,8 @@ names the member a region left from.
`State.slot_base + slot_off[i]`, the linker places the stubs in no
order). Anything else returns to `run`. Tail calls keep the wasm stack
flat, so the host stack does not grow with the guest's call depth;
without cheap tail calls (JavaScriptCore) there is no chaining. Growth
where tail calls do not pay (JavaScriptCore on a phone or in Bun:
`jitTail()`) there is no chaining. Growth
along exits goes on: `State.cur_slot` names the module that runs (set by
`enter` and by every chained entry), `chainOut` counts an exit from an
open region to another module's block in that block's `hits`, and the
@@ -387,7 +388,7 @@ These imports exist only with `-Dkwemu-jit`. The kernel host is
| Import | |
| --- | --- |
| `kw_host_jit_caps() -> u32` | Called once from `kw_cpu_init`, by each CPU on its own host. Bit 0 = JIT available (0: never compile). Bit 1 = 32-bit memory (lowered kernel: the code imports a 32-bit `env.memory` and wraps addresses). Bit 2 = eager. Bit 3 = shared memory (the code declares `env.memory` shared, with a maximum of 65536 pages for memory32 and 262144 for memory64, and reads `*irqp` atomically; set when the kernel's memory is a SharedArrayBuffer). Bit 4 = the host passes the kernel's function table as `env.table` (A64 calls its interpreter through it; `jit.ts` always sets it). Bit 5 = the engine compiles fixed-width SIMD (`jit.ts` sets it when `WebAssembly.validate` accepts a small SIMD module; the test host unless `KWEMU_JIT_SIMD=0`). Bit 6 (only with bit 5) = the engine compiles relaxed SIMD and its f32x4/f64x2 `relaxed_madd`/`relaxed_nmadd` are fused here (both hosts set it after a start-up probe whose operands give 2^-54 and 2^-24 fused and 0 unfused: V8 on an x86-64 without FMA3 is unfused, Safari 27.2 has no relaxed SIMD; the test host unless `KWEMU_JIT_FMA=0`). Bit 7 = the engine's tail calls are cheap (`jit.ts`: they validate and the engine is not JavaScriptCore; the test host unless `KWEMU_JIT_TAIL=0`). Bit 8 = regions in module format v2 (`jit.ts` with `KW_JIT_V2=1`, the test host with `KWEMU_JIT_V2=1`). Bit 9 = chaining, with bits 4 and 7 (`jit.ts` unless `KW_JIT_CHAIN=0`, the test host with `KWEMU_JIT_CHAIN=1`). |
| `kw_host_jit_caps() -> u32` | Called once from `kw_cpu_init`, by each CPU on its own host. Bit 0 = JIT available (0: never compile). Bit 1 = 32-bit memory (lowered kernel: the code imports a 32-bit `env.memory` and wraps addresses). Bit 2 = eager. Bit 3 = shared memory (the code declares `env.memory` shared, with a maximum of 65536 pages for memory32 and 262144 for memory64, and reads `*irqp` atomically; set when the kernel's memory is a SharedArrayBuffer). Bit 4 = the host passes the kernel's function table as `env.table` (A64 calls its interpreter through it; `jit.ts` always sets it). Bit 5 = the engine compiles fixed-width SIMD (`jit.ts` sets it when `WebAssembly.validate` accepts a small SIMD module; the test host unless `KWEMU_JIT_SIMD=0`). Bit 6 (only with bit 5) = the engine compiles relaxed SIMD and its f32x4/f64x2 `relaxed_madd`/`relaxed_nmadd` are fused here (both hosts set it after a start-up probe whose operands give 2^-54 and 2^-24 fused and 0 unfused: V8 on an x86-64 without FMA3 is unfused, Safari 27.2 has no relaxed SIMD; the test host unless `KWEMU_JIT_FMA=0`). Bit 7 = tail calls pay on the engine (`jit.ts` `jitTail()`: they validate and the engine is not JavaScriptCore on a phone or in Bun; `KW_JIT_TAIL=1` or `0` answers instead; the test host unless `KWEMU_JIT_TAIL=0`). Bit 8 = regions in module format v2 (`jit.ts` with `KW_JIT_V2=1`, the test host with `KWEMU_JIT_V2=1`). Bit 9 = chaining, with bits 4 and 7 (`jit.ts` unless `KW_JIT_CHAIN=0`, the test host with `KWEMU_JIT_CHAIN=1`). |
| `kw_host_jit_compile(ptr, len, slot, flags) -> i32` | Compile the module at `ptr` (imports `env.memory`, maybe `env.table`, exports `f`) synchronously with `new WebAssembly.Module` and `table.set` its `f` into `slot` (a BigInt for table64). 0 = installed, < 0 = failed (slot untouched, that block is never compiled), > 0 = installed, and the threshold of blocks decoded from now on is the built-in one times 2^(result - 1), at most one step up (`jit.ts`: 2 while its compiles are slow, else 1; kwemu.md When; the test host always 0). `flags` bit 0: `f(0, 0, 0, 0)` returns at once, and the host calls it once so V8 compiles it inside the compile window. |
| `kw_host_jit_free(slot)` | Put back the stub that was there before the first compile, and drop the module. |

View File

@@ -208,7 +208,7 @@ export function jitFma(): boolean {
return false;
}
}
/** The engine's tail calls are cheap (V8, SpiderMonkey; not JavaScriptCore): kwemu may tail-call between its functions and modules. */
/** Tail calls between kwemu's functions and modules pay on this engine (jitTail()). */
const CAP_TAIL = 128;
/** Regions in module format v2 (one function per cluster of members). */
const CAP_V2 = 256;
@@ -216,11 +216,22 @@ const CAP_V2 = 256;
const CAP_CHAIN = 512;
/** A module whose function is `return_call 0`: engines without tail calls do not validate it. */
const TAIL_PROBE = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 6, 1, 4, 0, 18, 0, 11]);
/** Whether this engine has cheap tail calls (cap bit 7): it validates them and is not JavaScriptCore (3-7.5 ns per hop there). */
/**
* Whether tail calls pay on this engine (cap bit 7): it validates them, and
* it is not JavaScriptCore on a phone or in Bun. Measured with
* /jit-probe.html on 2026-12-01 (chaining on against off, Perl kernels):
* Safari 27.2 on an M4 10-16% faster on five of six and none slower; Safari
* 27.3 on an iPhone 2-11% faster on five but the regex kernel 13% slower
* (a hop costs 7.5 ns there against 3.3 on the Mac), so phones stay off.
*/
export function jitTail(): boolean {
const g = globalThis as { Bun?: unknown; navigator?: { userAgent?: string } };
const ua = g.navigator?.userAgent ?? "";
if (g.Bun !== undefined || (/AppleWebKit/.test(ua) && !/Chrome\/|Chromium\/|Edg\/|Firefox\//.test(ua))) return false;
// KW_JIT_TAIL=1 or 0 (a host environment variable, or a global of the same name set before the boot:
// web/src/jit-probe.ts) answers instead of the engine test, to measure chaining on an engine.
const pin = (globalThis as { KW_JIT_TAIL?: string }).KW_JIT_TAIL ?? hostEnv("KW_JIT_TAIL");
if (pin === "0") return false;
if (pin !== "1" && (g.Bun !== undefined || (/AppleWebKit/.test(ua) && /Mobile\//.test(ua) && !/Chrome\/|Chromium\/|Edg\/|Firefox\//.test(ua)))) return false;
try {
return WebAssembly.validate(TAIL_PROBE);
} catch {

58
web/jit-probe.html Normal file
View File

@@ -0,0 +1,58 @@
<!doctype html>
<!-- SPDX-License-Identifier: MIT -->
<!-- Copyright (C) 2026 Pooya Parsa <pooya@pi0.io> -->
<!--
/jit-probe.html: is kwemu's chaining between compiled modules (tail calls)
a gain in this browser? Boots the page's kernel on the page's thread with
chaining off and on in turn, one boot per page load, and times the Perl
kernels of test/guest/work/work.pl, Perl's start-up and a shell loop in each
(src/jit-probe.ts).
-->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="dark">
<meta name="robots" content="noindex">
<title>unkernel: JIT probe</title>
<style>
body { margin: 0; padding: 1rem; background: #000; color: #ddd; font: 13px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; }
main { max-width: 60rem; margin: 0 auto; }
h1 { font-size: 1.1rem; color: #fff; margin: 0 0 .5rem; }
h2 { font-size: 1rem; color: #fff; margin: 1.25rem 0 .5rem; }
label { display: inline-flex; gap: .3rem; align-items: center; margin: .15rem .9rem .15rem 0; }
input[type=number], input[type=text] { font: inherit; background: #111; color: #ddd; border: 1px solid #444; border-radius: 3px; padding: .1rem .3rem; }
button { font: inherit; padding: .5rem 1.1rem; background: #222; color: #fff; border: 1px solid #555; border-radius: 4px; cursor: pointer; margin: .25rem .5rem .25rem 0; }
button:disabled { opacity: .5; cursor: default; }
pre { white-space: pre-wrap; word-break: break-word; background: #111; padding: .6rem; border-radius: 4px; margin: .5rem 0; }
#report { white-space: pre; overflow-x: auto; word-break: normal; }
#log { max-height: 14rem; overflow: auto; color: #999; }
#warn { color: #fc6; }
#warn:empty { display: none; }
.dim { color: #888; }
#status { color: #8cf; }
</style>
</head>
<body>
<main>
<h1>unkernel JIT probe</h1>
<p class="dim">Times guest work with chaining between compiled modules off and on, to decide the default for this browser. Press Run, keep this tab in front and the screen on (the page reloads itself between boots; a few minutes in all), then press Copy text and paste the result.</p>
<pre id="warn"></pre>
<pre id="env"></pre>
<div>
<label>rounds <input type="number" id="rounds" min="1" max="6" value="3" style="width:3rem"></label>
<label>runs <input type="number" id="runs" min="2" max="8" value="4" style="width:3rem"></label>
<label>size <input type="number" id="size" min="1" max="8" value="1" style="width:3rem"></label>
<label>memory MiB <input type="number" id="mem" min="128" step="64" value="512" style="width:5rem"></label>
<label>rows <input type="text" id="rows" style="width:20rem"></label>
</div>
<button id="run">Run</button><button id="stop" disabled>Stop</button><button id="copytext" disabled>Copy text</button><button id="copyjson" disabled>Copy JSON</button>
<span id="status">idle</span>
<h2>Report</h2>
<pre id="report" class="dim">Press Run.</pre>
<h2>Log</h2>
<pre id="log"></pre>
</main>
<script type="module" src="/src/jit-probe.ts"></script>
</body>
</html>

243
web/src/jit-probe.ts Normal file
View File

@@ -0,0 +1,243 @@
// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// /jit-probe.html: chaining between kwemu's compiled modules (tail calls,
// js/core/jit.ts jitTail()) off against on in this browser. One boot per
// page load, so a boot never shares the engine's heap or compiled code
// with the one before it: the plan and the results so far are in
// localStorage, and the page loads itself again for the next boot. The
// order of the two variants turns round each round. Each boot runs the
// kernel on the page's thread (the override is a global of that thread) on
// one CPU, with the Debian image, and times each row in the guest:
// test/guest/work/work.pl's six Perl kernels (code that stays hot), and
// Perl starting up with a few modules and a loop of short processes (much
// code run a few times).
//
// ?auto=1 start at once
// ?rounds=N boots per variant (default 3)
// ?runs=N runs of a row per boot; the first is reported apart (default 4)
// ?size=N the rows' size (default 1)
// ?mem=MiB guest memory (default 512)
// ?rows=a,b rows (default all: k1..k6, ps, sh)
// ?label=NAME a name for the report
// ?post=URL also POST the JSON report there when done
import workPl from "../../test/guest/work/work.pl?raw";
import { DEFAULT_DISTRO, DISTROS_OFFERED } from "./config.ts";
import { MemoryFs, createKernel, jitFma, jitSimd, jitTail, kernelUrl, loadKernelModule, type KernelHandle } from "./sdk.ts";
const $ = <T extends HTMLElement = HTMLElement>(id: string) => document.getElementById(id) as T;
const q = new URLSearchParams(location.search);
const KEY = "kw-jit-probe";
const ALL_ROWS = ["k1", "k2", "k3", "k4", "k5", "k6", "ps", "sh"];
const ROW_NAME: Record<string, string> = { k1: "perl 1 sieve", k2: "perl 2 hashes", k3: "perl 3 sort", k4: "perl 4 regex", k5: "perl 5 calls", k6: "perl 6 float", ps: "perl start-up", sh: "shell procs" };
type Variant = "off" | "on";
interface Run { row: string; ms: number; hostMs: number; rc: number; compiled: number; bytes: number; compileMs: number }
interface Boot { variant: Variant; round: number; bootMs: number; tail: boolean; runs: Run[]; jit: Record<string, number>; hidden: boolean }
interface Env { ua: string; label: string; origin: string; secure: boolean; isolated: boolean; threads: number; tailDefault: boolean; simd: boolean; fma: boolean; jspi: boolean }
interface State {
started: string; rounds: number; runs: number; size: number; mem: number; rows: string[]; post: string;
steps: { variant: Variant; round: number }[]; next: number; tries: number; boots: Boot[]; env: Env; done: boolean; error?: string;
}
const local = /^(localhost|127\.0\.0\.1|\[::1\])$/.test(location.hostname) || location.hostname.endsWith(".localhost");
const env: Env = {
ua: navigator.userAgent, label: q.get("label") ?? "", origin: location.protocol === "https:" ? "https" : local ? "http, localhost" : "plain http, not localhost",
secure: isSecureContext, isolated: crossOriginIsolated, threads: navigator.hardwareConcurrency || 1,
tailDefault: jitTail(), simd: jitSimd(), fma: jitFma(),
jspi: typeof (WebAssembly as { Suspending?: unknown }).Suspending === "function",
};
$("env").textContent = [
env.ua,
`origin: ${env.origin}, secure context: ${env.secure}, cross-origin isolated: ${env.isolated}, threads: ${env.threads}`,
`this browser's defaults: chaining ${env.tailDefault ? "on" : "off"}, SIMD ${env.simd}, fused multiply-add ${env.fma}, JSPI ${env.jspi}`,
].join("\n");
if (!env.secure) $("warn").textContent = "Not a secure context: Safari runs such a page without its JIT, so the numbers would say nothing. Open the page over https.";
const logEl = $("log");
function log(m: string) {
logEl.textContent += `${m}\n`;
logEl.scrollTop = logEl.scrollHeight;
console.log(`[jit-probe] ${m}`);
}
const status = (m: string) => { $("status").textContent = m; };
const load = (): State | null => { try { return JSON.parse(localStorage.getItem(KEY) ?? "null") as State | null; } catch { return null; } };
const save = (s: State) => localStorage.setItem(KEY, JSON.stringify(s));
for (const k of ["rounds", "runs", "size", "mem"]) if (q.has(k)) $<HTMLInputElement>(k).value = q.get(k)!;
$<HTMLInputElement>("rows").value = q.get("rows") ?? ALL_ROWS.join(",");
// --- the report -----------------------------------------------------------------
const median = (a: number[]) => { const s = [...a].sort((x, y) => x - y), n = s.length; return n ? (n % 2 ? s[(n - 1) / 2]! : (s[n / 2 - 1]! + s[n / 2]!) / 2) : NaN; };
const pad = (s: string, n: number) => s.padStart(n);
const pct = (a: number, b: number) => Number.isFinite(a) && Number.isFinite(b) && a > 0 ? `${b >= a ? "+" : ""}${((b / a - 1) * 100).toFixed(1)}%` : "-";
/** Per row: the medians of the first runs and of the later runs of each variant's boots. */
function table(s: State) {
return s.rows.map((row) => {
const of = (v: Variant, later: boolean) => s.boots.filter((b) => b.variant === v).flatMap((b) => b.runs.filter((r) => r.row === row && r.rc === 0).filter((_, i) => (i > 0) === later).map((r) => r.ms));
const range = (a: number[]) => a.length ? `${Math.min(...a)}-${Math.max(...a)}` : "-";
return { row, offFirst: median(of("off", false)), onFirst: median(of("on", false)), off: median(of("off", true)), on: median(of("on", true)), offRange: range(of("off", true)), onRange: range(of("on", true)) };
});
}
function reportText(s: State): string {
const L = [
`unkernel JIT probe${s.env.label ? ` (${s.env.label})` : ""}, ${s.started}`,
s.env.ua,
`origin ${s.env.origin}, isolated ${s.env.isolated}, threads ${s.env.threads}, default chaining ${s.env.tailDefault ? "on" : "off"}, fma ${s.env.fma}, simd ${s.env.simd}`,
`${s.boots.length} of ${s.steps.length} boots, ${s.runs} runs per row, size ${s.size}, ${s.mem} MiB, kernel on the page's thread, 1 CPU`,
"",
"guest ms, medians; later = every run but a boot's first; on against off (negative: chaining is faster)",
`${"row".padEnd(14)}${pad("off first", 10)}${pad("on first", 10)}${pad("diff", 8)}${pad("off later", 11)}${pad("on later", 10)}${pad("diff", 8)} ranges later (off | on)`,
];
const f = (x: number) => Number.isFinite(x) ? String(Math.round(x)) : "-";
for (const t of table(s)) L.push(`${(ROW_NAME[t.row] ?? t.row).padEnd(14)}${pad(f(t.offFirst), 10)}${pad(f(t.onFirst), 10)}${pad(pct(t.offFirst, t.onFirst), 8)}${pad(f(t.off), 11)}${pad(f(t.on), 10)}${pad(pct(t.off, t.on), 8)} ${t.offRange} | ${t.onRange}`);
L.push("", "boots:");
for (const b of s.boots) {
const c = b.runs.reduce((a, r) => ({ n: a.n + r.compiled, kb: a.kb + r.bytes / 1024, ms: a.ms + r.compileMs }), { n: 0, kb: 0, ms: 0 });
const bad = b.runs.filter((r) => r.rc !== 0).length;
L.push(` round ${b.round} ${b.variant.padEnd(3)} (tail calls ${b.tail}): shell after ${Math.round(b.bootMs)} ms; rows compiled ${c.n} modules, ${Math.round(c.kb)} KiB, ${Math.round(c.ms)} ms; failed ${b.jit.failed ?? 0}, refused ${b.jit.refused ?? 0}${bad ? `; ${bad} runs FAILED` : ""}${b.hidden ? "; TAB WAS HIDDEN" : ""}`);
}
if (s.error) L.push("", `ERROR: ${s.error}`);
return L.join("\n");
}
function render(s: State) {
const el = $("report");
el.textContent = reportText(s);
el.classList.remove("dim");
$<HTMLButtonElement>("copytext").disabled = $<HTMLButtonElement>("copyjson").disabled = false;
}
async function copy(text: string) {
try {
await navigator.clipboard.writeText(text);
status("copied");
} catch {
$("log").textContent = text;
status("clipboard unavailable: the log shows it to copy");
}
}
$("copytext").onclick = () => { const s = load(); if (s) void copy(reportText(s)); };
$("copyjson").onclick = () => { const s = load(); if (s) void copy(JSON.stringify(s)); };
// --- one boot ---------------------------------------------------------------------
const CMD: Record<string, (n: number) => string> = {
ps: (n) => `i=0; while [ $i -lt ${3 * n} ]; do i=$((i+1)); perl -MPOSIX -MGetopt::Long -MList::Util -MFile::Temp -MSocket -MIO::Handle -MText::ParseWords -MCwd -e 1 || exit 1; done`,
sh: (n) => `i=0; while [ $i -lt ${6 * n} ]; do i=$((i+1)); ls -l /usr/bin | grep -c x; sed -n "s/:.*//p" /etc/passwd | sort | uniq | wc -l; find /etc -maxdepth 1 -name "*.conf" | xargs cat | awk "{ n += NF } END { print n }"; basename /a/b/c; dirname /a/b/c; expr 3 + 4; date +%s; head -c 4096 /usr/bin/ls | md5sum; done`,
};
for (const k of [1, 2, 3, 4, 5, 6]) CMD[`k${k}`] = (n) => `perl /t/work.pl ${n} a ${k}`;
async function boot(s: State, step: { variant: Variant; round: number }): Promise<Boot> {
(globalThis as { KW_JIT_TAIL?: string }).KW_JIT_TAIL = step.variant === "on" ? "1" : "0";
let hidden = document.hidden;
const onHide = () => { if (document.hidden) { hidden = true; log("the tab was hidden: this boot's timings may be off"); } };
document.addEventListener("visibilitychange", onHide);
const what = `boot ${s.next + 1}/${s.steps.length} (chaining ${step.variant})`;
status(`${what}: loading the kernel`);
let vm: KernelHandle | undefined;
try {
const kernel = await loadKernelModule(kernelUrl.href, { what: "kernel" });
const distro = DISTROS_OFFERED.find((d) => d.name === DEFAULT_DISTRO)?.url;
if (!distro) throw new Error("this page has no distro image");
status(`${what}: booting`);
const t0 = performance.now();
vm = await createKernel({
kernel, memoryMiB: s.mem, jit: true, distro, vsock: true, worker: false, display: false, sound: false,
consoleSize: { cols: 80, rows: 24 }, log: (m: string) => console.log(m),
mounts: { "/t": { fs: new MemoryFs({ "work.pl": workPl }), readOnly: true } },
});
await vm.exec("true", [], { timeout: 300000 });
const bootMs = performance.now() - t0;
log(`${what}: shell after ${Math.round(bootMs)} ms`);
const jit = () => ({ ...(vm!.stats().jit as unknown as Record<string, number>) });
const runs: Run[] = [];
for (const row of s.rows) {
for (let i = 1; i <= s.runs; i++) {
if (load()?.done) throw new Error("stopped");
status(`${what}: ${ROW_NAME[row] ?? row}, run ${i}/${s.runs}`);
const a = jit(), h0 = performance.now();
const r = await vm.exec("sh", ["-c", `s=$(date +%s%N); ( ${CMD[row]!(s.size)} ) >/dev/null 2>/tmp/e; rc=$?; e=$(date +%s%N); echo "RES $(( (e - s) / 1000000 )) $rc"; [ $rc = 0 ] || tail -2 /tmp/e >&2`], { timeout: 600000 });
const hostMs = performance.now() - h0, b = jit();
const m = /^RES (\d+) (\d+)$/m.exec(r.stdout);
if (!m) throw new Error(`${row}: no result: ${r.stdout}${r.stderr}`.slice(0, 300));
const run: Run = { row, ms: Number(m[1]), hostMs: Math.round(hostMs), rc: Number(m[2]), compiled: b.compiled! - a.compiled!, bytes: b.bytes! - a.bytes!, compileMs: Math.round((b.compileMs! - a.compileMs!) * 10) / 10 };
if (run.rc) log(`${row}: exit ${run.rc}: ${r.stderr.trim().slice(-200)}`);
log(` ${(ROW_NAME[row] ?? row).padEnd(14)} ${String(run.ms).padStart(6)} ms${i === 1 ? ` (first; ${run.compiled} modules)` : ""}`);
runs.push(run);
}
}
return { variant: step.variant, round: step.round, bootMs, tail: jitTail(), runs, jit: jit(), hidden };
} finally {
document.removeEventListener("visibilitychange", onHide);
await vm?.stop().catch(() => {});
}
}
// --- the plan -----------------------------------------------------------------------
function finish(s: State, error?: string) {
s.done = true;
if (error) s.error = error;
save(s);
render(s);
status(error ? `stopped: ${error}` : "done: press Copy text");
$<HTMLButtonElement>("run").disabled = false;
$<HTMLButtonElement>("stop").disabled = true;
if (s.post) fetch(s.post, { method: "POST", mode: "cors", headers: { "content-type": "text/plain" }, body: JSON.stringify(s) }).then((r) => log(`posted: ${r.status}`), (e) => log(`post failed: ${e}`));
}
async function step(s: State) {
$<HTMLButtonElement>("run").disabled = true;
$<HTMLButtonElement>("stop").disabled = false;
if (s.boots.length) render(s);
// A load that did not get to the end of its boot (the browser reloaded the tab) is tried once more.
if (s.tries >= 2) return finish(s, `boot ${s.next + 1} did not finish twice (the browser reloaded the tab: try less memory)`);
s.tries++;
save(s);
// The screen stays on where the browser allows it.
try { await (navigator as Navigator & { wakeLock?: { request(t: string): Promise<unknown> } }).wakeLock?.request("screen"); } catch {}
try {
const b = await boot(s, s.steps[s.next]!);
const now = load();
if (now?.done) return finish(now, now.error ?? "stopped");
s.boots.push(b);
s.next++;
s.tries = 0;
save(s);
} catch (e) {
return finish(load()?.done ? load()! : s, e instanceof Error ? e.message : String(e));
}
if (s.next >= s.steps.length) return finish(s);
render(s);
status("loading the page again for the next boot");
const u = new URL(location.href);
u.searchParams.set("resume", "1");
u.searchParams.delete("auto");
setTimeout(() => location.replace(u.href), 300);
}
function start() {
const num = (id: string, lo: number, hi: number) => Math.max(lo, Math.min(hi, Math.round(Number($<HTMLInputElement>(id).value)) || lo));
const rounds = num("rounds", 1, 6);
const rows = $<HTMLInputElement>("rows").value.split(",").map((r) => r.trim()).filter((r) => r in CMD);
const steps: State["steps"] = [];
for (let r = 1; r <= rounds; r++) for (const v of (r % 2 ? ["off", "on"] : ["on", "off"]) as Variant[]) steps.push({ variant: v, round: r });
const s: State = {
started: new Date().toISOString(), rounds, runs: num("runs", 2, 8), size: num("size", 1, 8), mem: num("mem", 128, 4096),
rows: rows.length ? rows : ALL_ROWS, post: q.get("post") ?? "", steps, next: 0, tries: 0, boots: [], env, done: false,
};
logEl.textContent = "";
void step(s);
}
$("run").onclick = start;
$("stop").onclick = () => {
const s = load();
if (s && !s.done) { s.done = true; s.error = "stopped"; save(s); status("stopping after this run"); }
};
const prev = load();
if (prev && !prev.done && q.get("resume") === "1") void step(prev);
else if (q.get("auto") === "1") start();
else if (prev?.boots.length) { render(prev); status(prev.done ? "an earlier result (Run starts a new one)" : "an unfinished earlier run (Run starts a new one)"); }

View File

@@ -179,8 +179,9 @@ export default defineConfig({
watch: { ignored: ["**/.output/**", "**/.vercel/**", "**/kernel/page/**"] },
},
build: { target: "esnext" },
// profile.html: the defaults profiler (src/profile.ts), and smp-probe.html:
// the SMP slowdown probe (src/smp-probe.ts), pages of their own. Nitro
// profile.html: the defaults profiler (src/profile.ts), smp-probe.html: the
// SMP slowdown probe (src/smp-probe.ts), and jit-probe.html: chaining off
// against on (src/jit-probe.ts), pages of their own. Nitro
// builds the client environment from index.html alone (its renderer
// template), so they are a second client environment, which it builds
// into the same public directory.
@@ -188,7 +189,7 @@ export default defineConfig({
// the pages' bundles are a part of it).
environments: {
client: { build: { license: { fileName: BUNDLED_LICENSES } } },
pages: { consumer: "client", build: { rollupOptions: { input: { profile: path.join(import.meta.dirname, "profile.html"), "smp-probe": path.join(import.meta.dirname, "smp-probe.html") } } } },
pages: { consumer: "client", build: { rollupOptions: { input: { profile: path.join(import.meta.dirname, "profile.html"), "smp-probe": path.join(import.meta.dirname, "smp-probe.html"), "jit-probe": path.join(import.meta.dirname, "jit-probe.html") } } } },
},
// The SDK's worker mode (?worker=1): js/web/worker.ts starts a module worker.
worker: { format: "es" },
@@ -305,14 +306,14 @@ export default defineConfig({
},
},
{
// Nitro's dev renderer answers every page with index.html: profile.html
// and smp-probe.html here (a build emits them as pages of their own,
// Nitro's dev renderer answers every page with index.html: profile.html,
// smp-probe.html and jit-probe.html here (a build emits them as pages of their own,
// build.rollupOptions above).
name: "unkernel:profile-page",
configureServer(server) {
server.middlewares.use((req, res, next) => {
const url = (req.url ?? "").split("?")[0]!;
if (url !== "/profile.html" && url !== "/smp-probe.html") return next();
if (url !== "/profile.html" && url !== "/smp-probe.html" && url !== "/jit-probe.html") return next();
readFile(path.join(import.meta.dirname, url.slice(1)), "utf8")
.then((html) => server.transformIndexHtml(url, html))
.then((html) => {