// ../../linux-in-the-browser/hardwarejs/src/uaccessBoundary.mjs var UACCESS_LEAF_IMPORTS = Object.freeze([ "raw_copy_to_user", "raw_copy_from_user", "raw_clear_user" ]); var PARKING_IMPORT_NAMESPACE = "hwjs_suspend"; function auditVmlinuxSingleMemory(module) { const problems = []; let memoryImports = 0; for (const imp of WebAssembly.Module.imports(module)) { if (imp.kind === "memory") { memoryImports++; if (!(imp.module === "env" && imp.name === "kernel_memory")) { problems.push( `vmlinux imports memory ${imp.module}.${imp.name} \u2014 the kernel is a SINGLE-memory module now (only env.kernel_memory). A stale multi-memory vmlinux.wasm (the deleted env.user_memory splice) cannot boot on this host: rebuild the kernel (uaccess is host-serviced via linux.raw_copy_*_user; multi-memory is also what WebKit/iPadOS rejects \u2014 litb#68).` ); } } if (imp.module === PARKING_IMPORT_NAMESPACE && UACCESS_LEAF_IMPORTS.includes(imp.name)) { problems.push( `vmlinux declares kernel-memory service import '${imp.name}' in parking namespace '${PARKING_IMPORT_NAMESPACE}' \u2014 the uaccess crossing would be a coroutine suspend boundary by construction, which is the silently-catastrophic wiring the leaf witness exists to refuse (PLAN-THREADS-SINGLE-MEMORY \xA75 R1).` ); } } if (memoryImports > 1) { problems.push( `vmlinux imports ${memoryImports} memories \u2014 exactly one (env.kernel_memory) is the single-memory contract.` ); } return problems; } function makeUaccessLeafBoundary(opts) { const { userMemory, kernelMemory, refuse, context, redPark } = opts; if (typeof refuse !== "function") { throw new Error("makeUaccessLeafBoundary: refuse() is required"); } let leafDepth = 0; let parkedSlotReader = null; let guardedPark = null; const guardPark = (parkFn) => { const wrapped = (...args) => { if (leafDepth > 0) { refuse( `uaccess-leaf-witness REFUSAL [${context}]: park signal raised while a kernel-memory leaf crossing is live (depth=${leafDepth}). A park across the uaccess crossing is silently catastrophic (R1 spike: poison propagation with a clean DONE exit) \u2014 the crossing MUST be a leaf host memcpy. Refusing loudly instead.` ); throw new Error("uaccess-leaf-witness: park during leaf crossing"); } return parkFn(...args); }; guardedPark = wrapped; return wrapped; }; const setParkedSlotReader = (fn) => { parkedSlotReader = fn; }; const inLeafCrossing = () => leafDepth > 0; if (!userMemory) { const kthreadBug = (name) => (...args) => { refuse( `uaccess-leaf-witness REFUSAL [${context}]: linux.${name}(${args.map((a) => "0x" + (a >>> 0).toString(16)).join(", ")}) called from kthread context \u2014 the standalone vmlinux Worker has no user pages; kernel code must never uaccess outside a process context. This is a kernel bug (the old 1-page sentinel's trap, now named).` ); throw new Error(`kthread uaccess: linux.${name}`); }; return { imports: { raw_copy_to_user: kthreadBug("raw_copy_to_user"), raw_copy_from_user: kthreadBug("raw_copy_from_user"), raw_clear_user: kthreadBug("raw_clear_user") }, guardPark, setParkedSlotReader, inLeafCrossing }; } let uBuf = null, uU8 = null; const userU8 = () => { const b = userMemory.buffer; if (b !== uBuf) { uBuf = b; uU8 = new Uint8Array(b); } return uU8; }; let kBuf = null, kU8 = null; const kernU8 = () => { const b = kernelMemory.buffer; if (b !== kBuf) { kBuf = b; kU8 = new Uint8Array(b); } return kU8; }; const SMALL_N = 32; const copyBytes = (dst, dstOff, src, srcOff, n) => { if (n <= SMALL_N) { for (let i = 0; i < n; i++) dst[dstOff + i] = src[srcOff + i]; } else { dst.set(src.subarray(srcOff, srcOff + n), dstOff); } }; const kernelBug = (name, msg) => { refuse(`uaccess-leaf-witness REFUSAL [${context}]: linux.${name}: ${msg}`); throw new Error(`uaccess kernel-side bug: linux.${name}`); }; const leaf = (name, body) => (a0, a1, a2) => { const slotBefore = parkedSlotReader ? parkedSlotReader() : 0; leafDepth++; try { if (redPark) { if (!guardedPark) { refuse( `uaccess-leaf-witness REFUSAL [${context}]: RED park arm requested but no park binding was guarded (guardPark never called) \u2014 the witness would be vacuous. Wire guardPark.` ); } guardedPark(); } return body(a0, a1, a2); } finally { leafDepth--; if (parkedSlotReader) { const slotAfter = parkedSlotReader(); if (slotAfter !== slotBefore) { refuse( `uaccess-leaf-witness REFUSAL [${context}]: parked slot changed across linux.${name} (0x${(slotBefore >>> 0).toString(16)} -> 0x${(slotAfter >>> 0).toString(16)}) \u2014 the kernel-memory crossing suspended. The crossing MUST be a leaf.` ); } } } }; const imports = { /* (to_user, from_kernel, n) -> bytes NOT copied */ raw_copy_to_user: leaf("raw_copy_to_user", (to, from, n) => { to >>>= 0; from >>>= 0; n >>>= 0; if (n === 0) return 0; const u = userU8(); if (to + n > u.length) return n; const k = kernU8(); if (from + n > k.length) { kernelBug( "raw_copy_to_user", `kernel-side source out of range (from=0x${from.toString(16)} n=${n} kernel_len=0x${k.length.toString(16)}) \u2014 kernel bug` ); } copyBytes(u, to, k, from, n); return 0; }), /* (to_kernel, from_user, n) -> bytes NOT copied */ raw_copy_from_user: leaf("raw_copy_from_user", (to, from, n) => { to >>>= 0; from >>>= 0; n >>>= 0; if (n === 0) return 0; const u = userU8(); if (from + n > u.length) return n; const k = kernU8(); if (to + n > k.length) { kernelBug( "raw_copy_from_user", `kernel-side destination out of range (to=0x${to.toString(16)} n=${n} kernel_len=0x${k.length.toString(16)}) \u2014 kernel bug` ); } copyBytes(k, to, u, from, n); return 0; }), /* (to_user, n) -> bytes NOT cleared */ raw_clear_user: leaf("raw_clear_user", (to, n) => { to >>>= 0; n >>>= 0; if (n === 0) return 0; const u = userU8(); if (to + n > u.length) return n; u.fill(0, to, to + n); return 0; }) }; return { imports, guardPark, setParkedSlotReader, inLeafCrossing }; } // ../../linux-in-the-browser/hardwarejs/src/macrotask.mjs var HAVE_SET_IMMEDIATE = typeof setImmediate === "function"; var HAVE_MESSAGE_CHANNEL = typeof MessageChannel === "function"; var MACROTASK_TURN_KIND = HAVE_SET_IMMEDIATE ? "setImmediate" : HAVE_MESSAGE_CHANNEL ? "MessageChannel" : "setTimeout"; var MACROTASK_FAIRNESS_MS = 100; var fairnessLastMs = 0; var beltTurns = 0; var turns = 0; var macrotaskChannel = null; var macrotaskWaiters = []; var macrotaskPortRef = (p) => { if (typeof p.ref === "function") p.ref(); }; var macrotaskPortUnref = (p) => { if (typeof p.unref === "function") p.unref(); }; function portTurn() { if (macrotaskChannel === null) { const ch = new MessageChannel(); ch.port1.onmessage = () => { const resolve = macrotaskWaiters.shift(); if (resolve) resolve(); if (macrotaskWaiters.length === 0) macrotaskPortUnref(ch.port1); }; macrotaskPortUnref(ch.port1); macrotaskPortUnref(ch.port2); macrotaskChannel = ch; } return new Promise((resolve) => { if (macrotaskWaiters.length === 0) macrotaskPortRef(macrotaskChannel.port1); macrotaskWaiters.push(resolve); macrotaskChannel.port2.postMessage(0); }); } function macrotaskTurn() { turns++; if (MACROTASK_TURN_KIND === "setImmediate") { return new Promise((resolve) => { setImmediate(resolve); }); } if (MACROTASK_TURN_KIND !== "MessageChannel") { return new Promise((resolve) => { setTimeout(resolve, 0); }); } const turn = portTurn(); const now = Date.now(); if (now - fairnessLastMs < MACROTASK_FAIRNESS_MS) return turn; fairnessLastMs = now; beltTurns++; return turn.then(() => new Promise((resolve) => { setTimeout(resolve, 0); })); } // ../../linux-in-the-browser/hardwarejs/src/pause.mjs var WAIT_BOUND_MS = 200; var TIMER_FALLBACK_MS = 50; function isPaused(word) { return word !== null && Atomics.load(word, 0) === 1; } async function waitOutPause(word) { while (isPaused(word)) { if (typeof Atomics.waitAsync === "function") { const r = Atomics.waitAsync(word, 0, 1, WAIT_BOUND_MS); if (r.async) await r.value; } else { await new Promise((resolve) => setTimeout(resolve, TIMER_FALLBACK_MS)); } } } // ../../linux-in-the-browser/hardwarejs/src/kernelWorker.mjs var kernelInstanceCount = 0; var kernelMemoriesInstantiated = /* @__PURE__ */ new WeakSet(); function bindKernelWorker({ post, onMessage, onTerminate, callHostSync }) { const stop = { requested: false }; onTerminate?.(() => { stop.requested = true; }); let devicesReady = null; let devicesReadyWake = null; onMessage(async (msg) => { try { if (msg?.kind === "devices-ready") { devicesReady = msg; if (devicesReadyWake) { const w = devicesReadyWake; devicesReadyWake = null; w(); } return; } if (msg?.kind !== "boot") { post({ kind: "error", message: `unknown msg ${msg?.kind}` }); return; } await boot(msg, post, stop, callHostSync, { get: () => devicesReady, wait: () => new Promise((res) => { devicesReadyWake = res; }) }); } catch (e) { const message = e instanceof Error ? `${e.message} ${e.stack ?? ""}` : String(e); post({ kind: "error", message }); } }); } async function boot(init, post, stop = { requested: false }, callHostSync = void 0, devicesReadySignal = void 0) { if (Object.prototype.hasOwnProperty.call(init, "initramfs")) { post({ kind: "error", message: "kernelWorker: initramfs is unsupported; no fallback root." }); return; } const td = new TextDecoder("utf-8", { fatal: false }); const pauseArr = init.pauseBuffer ? new Int32Array(init.pauseBuffer) : null; function dmesg(level, buf, len) { const view = new Uint8Array(init.kernelMemory.buffer, buf, len); const bytes = new Uint8Array(len); bytes.set(view); const text = td.decode(bytes); post({ kind: "dmesg", level: level | 0, text }); } const MERGED_DRAIN_MSG = Object.freeze({ kind: "virtio-drain-sync" }); const MERGED_SPIN_FATAL_MS = 1e4; const MERGED_SPIN_FATAL_CALLS = 1e6; const MERGED_SPIN_SAMPLE_MASK = 65535; const MERGED_SPIN_GAP_MS = 2e3; const MERGED_SPIN_WARN_MS = 1e3; let mergedSpinArmed = false; let mergedSpinCalls = 0; let mergedSpinT0 = 0; let mergedSpinLast = 0; let mergedSpinKicks = 0; let mergedSpinWarned = false; let mergedSpinWarnings = 0; function noteHostThreadTurn() { mergedSpinCalls = 0; mergedSpinT0 = 0; mergedSpinLast = 0; mergedSpinKicks = 0; mergedSpinWarned = false; } function mergedSpinGuestFrames() { const prev = Error.stackTraceLimit; let raw = ""; try { Error.stackTraceLimit = 200; raw = new Error().stack || ""; } catch { } finally { try { Error.stackTraceLimit = prev; } catch { } } const frames = []; for (const line of raw.split("\n")) { const m = /at\s+(?:([^\s(]+)\s+\()?wasm:\/\/wasm\/[^\s)]*\)?/.exec(line); if (!m) continue; const name = (m[1] || "").trim(); frames.push(name || ""); if (frames.length >= 24) break; } return frames; } function mergedSpinCheck(site) { if (!mergedSpinArmed) return; if ((++mergedSpinCalls & MERGED_SPIN_SAMPLE_MASK) !== 0) return; const t = Date.now(); if (mergedSpinT0 === 0) { mergedSpinT0 = mergedSpinLast = t; return; } const gap = t - mergedSpinLast; if (gap > MERGED_SPIN_GAP_MS) mergedSpinT0 += gap; mergedSpinLast = t; const heldMs = t - mergedSpinT0; if (!mergedSpinWarned && heldMs >= MERGED_SPIN_WARN_MS) { mergedSpinWarned = true; const n = ++mergedSpinWarnings; if ((n & n - 1) === 0) { const frames2 = mergedSpinGuestFrames(); post({ kind: "dmesg", level: 4, text: `hwjs-merged SPIN #${n} \u2014 CPU 0 has held the merged JS thread for ${heldMs} ms across ${mergedSpinCalls} linux.${site} calls with no return to the drive loop (${mergedSpinKicks} unserviced doorbell(s)). Not fatal yet \u2014 the deadlock verdict needs ${MERGED_SPIN_FATAL_MS} ms \u2014 but every co-resident and every device backend on this thread was starved for that whole time. ` + (frames2.length > 0 ? `THE LOOP IS: ${frames2.join(" <- ")}` : `THE LOOP COULD NOT BE NAMED (no wasm frames in Error.stack on this runtime).`) }); } } if (heldMs < MERGED_SPIN_FATAL_MS) return; if (mergedSpinCalls < MERGED_SPIN_FATAL_CALLS) return; const calls = mergedSpinCalls; const kicks = mergedSpinKicks; const frames = mergedSpinGuestFrames(); noteHostThreadTurn(); throw new Error( `hwjs-merged DEADLOCK: CPU 0 has held the merged JS thread for ${heldMs} ms across ${calls} linux.${site} calls without one return to the host drive loop. The guest is in an in-kernel BUSY-WAIT (on this arch cpu_relax() IS linux.cpu_relax_host \u2014 asm/barrier.h \u2014 and it is not a suspend point), and ${kicks} virtio doorbell(s) were rung during that run and NOT ONE was serviced, because the backend that would service them is on this same thread. CPU 0's only handback is the IDLE park, which a runnable busy-waiting task never reaches, and the drive loop's quantum is measured between hwjs_resume returns, which never happen. The host cannot close this from inside a synchronous import: it can neither turn the event loop nor resolve a promise, and every FUSE reply and every virtio-net reply is a promise. WHAT ENDS IT is a kernel-side yield on wasm_merged_cpu0 that is not the idle park. WHICH LEVER depends on WHERE the loop below is, and this sentence used to name a door that is already open: wasm32_park_allowed() does NOT refuse a merged CPU 0 \u2014 park.c's kernel-Worker clause reads \`coop_sched && !merged_cpu0\` and park.c's consumer switch substitutes CONSUMER_HOST for it, so a CPU-0 chain may park and park_suspend() brackets it with wasm32_cpu0_handback_park_*. What is missing is a CALLER: no in-kernel busy-wait asks. If the loop is in arch/wasm32, give that leaf a wasm32_cooperative_park() and it will be taken. If it is in a DRIVER \u2014 as this one is \u2014 that is not available: cpu_relax() may not become a suspend point, because it is inlined into native scheduler internals under rq->lock (arch/wasm32/Kconfig states it), and this tree forks no file outside arch/wasm32. For a driver loop the only lever is CONFIG_WASM32_CORO_SAFEPOINTS, which places a budgeted checkpoint on the back-edge \u2014 default n, and the reason is written at the line that would turn it on (distros/common/linux-6.12/config/common.fragment). ` + (frames.length > 0 ? `THE LOOP IS: ${frames.join(" <- ")}` : `THE LOOP COULD NOT BE NAMED: this runtime put no wasm frames in Error.stack, so the guest call path above linux.${site} is not readable from here \u2014 read it from the kernel side instead.`) ); } const MERGED_DRAIN_EVERY = 255; let mergedRelaxTick = 0; function cpu_relax_host() { if (mergedSpinArmed && callHostSync !== void 0 && (++mergedRelaxTick & MERGED_DRAIN_EVERY) === 0) { callHostSync(MERGED_DRAIN_MSG); } mergedSpinCheck("cpu_relax_host"); } function now_ns() { if (typeof performance !== "undefined" && performance.now && typeof performance.timeOrigin === "number") { return BigInt(Math.round((performance.timeOrigin + performance.now()) * 1e6)); } return BigInt(Date.now()) * 1000000n; } function atomic_wait_i32(_addr, _expected, _timeoutNs) { if (mergedSpinArmed && callHostSync !== void 0) { callHostSync(MERGED_DRAIN_MSG); } mergedSpinCheck("atomic_wait_i32"); return 0; } function atomic_notify(_addr, _count) { return 0; } const stubHost = (name) => (..._args) => { post({ kind: "unimplemented-host-call", name }); return 0; }; const uaccessBoundary = makeUaccessLeafBoundary({ userMemory: null, kernelMemory: init.kernelMemory, refuse: (msg) => { post({ kind: "kernel-trap", message: msg }); throw new Error(msg); }, context: "standalone vmlinux Worker (kthread context)", redPark: false }); const WASM_PAGE_BYTES = 65536; const GUEST_PAGE_BYTES = 4096; let committedPagesIdx = -1; const publishCommittedPages = () => { if (committedPagesIdx < 0) return; const i32 = new Int32Array(init.kernelMemory.buffer); Atomics.store( i32, committedPagesIdx, init.kernelMemory.buffer.byteLength / GUEST_PAGE_BYTES | 0 ); }; const growKernelMemory = (wantBytes) => { const mem = init.kernelMemory; const have = mem.buffer.byteLength; if (wantBytes <= have) return have; const deltaPages = Math.ceil((wantBytes - have) / WASM_PAGE_BYTES); try { mem.grow(deltaPages); } catch { } const now = mem.buffer.byteLength; if (now !== have) { publishCommittedPages(); post({ kind: "kernel-mem-grown", bytes: now }); } return now; }; const mem_commit = (wantPages) => { const want = (wantPages >>> 0) * GUEST_PAGE_BYTES; return growKernelMemory(want) / GUEST_PAGE_BYTES >>> 0; }; const linux = { dmesg, cpu_relax_host, now_ns, mem_commit, atomic_wait_i32, atomic_notify, ...uaccessBoundary.imports, console_write: stubHost("console_write"), console_read_nonblock: stubHost("console_read_nonblock"), hlt: stubHost("hlt"), mmap_user_page: stubHost("mmap_user_page"), munmap_user_page: stubHost("munmap_user_page"), spawn_worker: stubHost("spawn_worker"), /* pid 0 names no task: the kernel asking to end the machine (reboot(2), * or a kthread's kernel_restart / kernel_power_off), with the reboot * command as the code. The process Worker's import does the same. */ terminate_worker: (pid, code) => { if ((pid | 0) === 0) { post({ kind: "machine-power", cmd: code >>> 0, pid: 0 }); return 0; } return stubHost("terminate_worker")(); }, signal_inject: stubHost("signal_inject"), /* * HWJS-A-1: QUEUE_NOTIFY doorbell. arch/wasm32/kernel/virtio_wasm.c * calls this from the writel hook when the guest virtio_mmio driver * notifies a queue. Forward to the main thread, which reads the vring * out of shared kernel memory, answers FUSE from @brintos/storage, and * injects the completion IRQ. Returns immediately (the guest task then * blocks waiting for that interrupt). */ virtio_kick: (devid, qidx) => { mergedSpinKicks++; post({ kind: "virtio-kick", devid: devid >>> 0, qidx: qidx >>> 0 }); } }; const env = { kernel_memory: init.kernelMemory, /* env.user_memory is GONE: vmlinux is a single-memory module (the * uaccess crossing is the linux.raw_copy_*_user leaf imports; the * 1-page kthread sentinel that used to satisfy this import is * deleted from physRam.ts). A module still importing it is a stale * multi-memory build — refused with attribution below. */ /* * Any remaining function imports the kernel ships with that we * have not provided. The kernelImports object is K1's ephemeral * §15 debt — it shrinks per K-phase as real arch implementations * land, and is empty by K5. For K1 we expect it to be empty * already (real impls for __wasm32_get_current, irq flag ops, * __sw_hweight32 via lib/hweight.c; stubs for show_regs, * show_stack, machine_restart inside arch/wasm32/kernel/traps.c) * but the slot exists so K2 can drop more in without re-shaping * this file. */ ...init.kernelImports?.env ?? {} }; let hwjsParkedAddr = 0; let hwjsKernelU32 = null; const hwjsParkedCheck = (importName) => { if (!hwjsParkedAddr || !hwjsKernelU32) return; const h = hwjsKernelU32[hwjsParkedAddr >> 2]; if (h !== 0) { const msg = `hwjs runtime gate (host leg): parked slot NOT EMPTY at host import '${importName}' (handle=0x${h.toString(16)}) \u2014 a leaked slice crossed the host boundary`; post({ kind: "kernel-trap", message: msg }); throw new Error(msg); } }; const hwjsGuard = (name, fn) => (...args) => { hwjsParkedCheck(name); return fn(...args); }; const hwjsGuardDmesgLast = (name, fn) => (...args) => { const r = fn(...args); hwjsParkedCheck(name); return r; }; for (const k of Object.keys(linux)) { linux[k] = (k === "dmesg" ? hwjsGuardDmesgLast : hwjsGuard)(`linux.${k}`, linux[k]); } const hwjs_suspend = { park: uaccessBoundary.guardPark(hwjsGuard("hwjs_suspend.park", () => { })) }; const imports = { env, linux, hwjs_suspend }; const module = init.vmlinuxModule; if (!(module instanceof WebAssembly.Module)) { post({ kind: "instantiate-error", message: init.vmlinuxCompileError ? `vmlinux did not compile on the posting thread: ${init.vmlinuxCompileError}` : "boot message carried no compiled vmlinux Module (kernelWorker expects init.vmlinuxModule \u2014 see bootKernel.ts)." }); return; } const boundaryProblems = auditVmlinuxSingleMemory(module); if (boundaryProblems.length > 0) { post({ kind: "instantiate-error", message: "uaccess-leaf-witness: refusing to boot this vmlinux.wasm:\n - " + boundaryProblems.join("\n - ") }); return; } const needed = WebAssembly.Module.imports(module); const missing = []; for (const imp of needed) { const ns = Object.hasOwn(imports, imp.module) ? imports[imp.module] : void 0; if (!ns || !Object.hasOwn(ns, imp.name)) { missing.push(`${imp.module}.${imp.name} (${imp.kind})`); } } if (missing.length > 0) { post({ kind: "link-error", missing }); return; } let instance; try { if (init.kernelMemory && kernelMemoriesInstantiated.has(init.kernelMemory)) { post({ kind: "instantiate-error", message: `K10-A4 R-K10-W1 invariant violated: vmlinux.wasm has already been instantiated against THIS env.kernel_memory (this realm has instantiated ${kernelInstanceCount} kernel(s) in total). The K10-B active-segment overlay assumes single-instance vmlinux per env.kernel_memory; re-instantiation would re-write the .initcall_anchor.* active overlays into shared kernel memory and corrupt the running kernel's initcall arrays. See docs/ARCHITECTURE.md \xA715.3 R-K10-W1 (migration path: switch to strategy A, keeping .initcall*.init segments passive with --defsym anchors). NOTE: a power cycle is NOT this \u2014 each boot builds a fresh PhysRam and therefore a fresh memory \u2014 so if you are seeing this on a restart, the memory was reused and that is the defect to chase, not this refusal.` }); return; } instance = await WebAssembly.instantiate(module, imports); kernelInstanceCount += 1; if (init.kernelMemory) kernelMemoriesInstantiated.add(init.kernelMemory); } catch (e) { const message = e instanceof Error ? e.message : String(e); post({ kind: "instantiate-error", message }); return; } const exp = instance.exports; if (exp.__hwjs_parked && typeof exp.__hwjs_parked.value === "number") { hwjsParkedAddr = exp.__hwjs_parked.value >>> 0; hwjsKernelU32 = new Uint32Array(init.kernelMemory.buffer); post({ kind: "hwjs-parked-offset", offset: hwjsParkedAddr }); } const hwjsDataOffset = (name) => exp[name] && typeof exp[name].value === "number" ? exp[name].value >>> 0 : 0; const hwjsArenaAddrs = { highWater: hwjsDataOffset("__hwjs_frame_high_water") }; const hwjsArenaStats = () => { if (!hwjsKernelU32 || !hwjsArenaAddrs.highWater) return null; return { highWater: hwjsKernelU32[hwjsArenaAddrs.highWater >> 2], live: exp.__hwjs_arena_total(0) >>> 0, allocs: exp.__hwjs_arena_total(1) >>> 0 }; }; const hwjsArenaSuffix = () => { const s = hwjsArenaStats(); return s ? ` [hwjs arena: high-water=${s.highWater} live=${s.live} allocs=${s.allocs}]` : ""; }; const HWJS_INITIAL_BUDGET = 1 << 20; if (typeof exp.__hwjs_budget_set === "function") { exp.__hwjs_budget_set(HWJS_INITIAL_BUDGET | 0); } if (typeof exp.__wasm_call_ctors === "function") { try { exp.__wasm_call_ctors(); } catch (e) { const message = e instanceof Error ? e.message : String(e); post({ kind: "ctors-trap", message }); return; } } if (typeof exp.wasm_start_kernel !== "function") { post({ kind: "no-entry", message: "vmlinux.wasm has no wasm_start_kernel export" }); return; } const heapBaseExport = exp.__heap_base; if (typeof heapBaseExport !== "object" || heapBaseExport === null || typeof heapBaseExport.value !== "number") { post({ kind: "no-entry", message: "vmlinux.wasm has no __heap_base i32 global export" }); return; } const heapBase = heapBaseExport.value >>> 0; const committedPagesExport = exp.wasm32_committed_pages; const kernelDoesDemandCommit = !!(committedPagesExport && typeof committedPagesExport.value === "number"); if (kernelDoesDemandCommit) committedPagesIdx = committedPagesExport.value >>> 0 >> 2; const align16 = (n) => n + 15 & ~15; let bootInfoOffset = align16(heapBase); const VIRTIO_WIN_SIZE = 4096; const VIRTIO_IRQ = 1; const VIRTINPUT_WIN_SIZE = 4096; const VIRTINPUT_IRQ = 2; const VIRTNET_WIN_SIZE = 4096; const VIRTNET_IRQ = 3; const VIRTCON_WIN_SIZE = 4096; const VIRTCON_IRQ = 5; const VIRTFSCACHE_WIN_SIZE = 4096; const VIRTFSCACHE_IRQ = 6; const HOSTTRANS_WIN_SIZE = 4096; const HOSTTRANS_IRQ = 7; const spanBytes = Number(init.kernelMaxBytes) || init.kernelMemory.buffer.byteLength; let effectiveCmdline = init.cmdline ?? ""; const MERGED_CPU0_ABI = 1; const mergedCpu0 = true; const cpu0ParkExport = exp.wasm32_cpu0_park; const cpu0ParkAddr = cpu0ParkExport && typeof cpu0ParkExport.value === "number" ? cpu0ParkExport.value >>> 0 : 0; const kernU32 = new Uint32Array(init.kernelMemory.buffer); const kernI32 = new Int32Array(init.kernelMemory.buffer); const CPU0_PARK_NONE = 0; const CPU0_PARK_IDLE = 1; const CPU0_PARK_RESUME = 2; if (mergedCpu0) { if (!cpu0ParkAddr) { post({ kind: "error", message: `COLLAPSED CPU 0: this vmlinux.wasm exports no wasm32_cpu0_park \u2014 it has no merged dispatcher, so its idle path is still memory.atomic.wait32 on __sched_wakeup_word and it would block the one JS thread this machine has (kernel\u2194host lockstep: hardwarejs and packages/modified/linux ship together; deploy order is host first, then machine images). Refusing to boot rather than starting a machine that wedges at its first idle. THERE IS NO OTHER TOPOLOGY TO PUT THIS IMAGE ON \u2014 mergedCpuHost:'separate' was deleted when the merged path booted the appliance end to end \u2014 so the fix is to rebuild the kernel from a tree carrying PLAN-COLLAPSED-CPU0 \xA73.1.` }); return; } const abi = kernU32[(cpu0ParkAddr >> 2) + 1] >>> 0; if (abi !== MERGED_CPU0_ABI) { post({ kind: "error", message: `COLLAPSED CPU 0: this vmlinux.wasm publishes merged-CPU0 ABI version ${abi}; this host speaks version ${MERGED_CPU0_ABI}. The park block's layout is the contract between the two halves and a mismatch reads one half's fields at the other's offsets. Refusing.` }); return; } effectiveCmdline = `${effectiveCmdline}${effectiveCmdline ? " " : ""}wasm_merged_cpu0`; post({ kind: "dmesg", level: 6, text: `hwjs-merged: CPU 0 shares this JS thread with pool lane 1 (wasm32_cpu0_park @0x${cpu0ParkAddr.toString(16)}, abi ${abi}) ` }); mergedSpinArmed = true; } const alignPage = (n) => n + 4095 & ~4095; const deviceRegionBase = alignPage(heapBase); let deviceRegionTop = deviceRegionBase; const carveDevice = (size) => { const base = deviceRegionTop; deviceRegionTop = alignPage(base + size); return base; }; let virtblkWindowBase = 0; if (init.virtioBlk) { virtblkWindowBase = carveDevice(4096); effectiveCmdline = (effectiveCmdline + ` wasm_virtblk=0x${virtblkWindowBase.toString(16)},0x1000,8,${init.virtioBlk.size / 512},${init.virtioBlk.readOnly ? 1 : 0}`).trim(); } let virtsndWindowBase = 0; if (init.virtioSound) { virtsndWindowBase = carveDevice(4096); effectiveCmdline = (effectiveCmdline + ` wasm_virtsnd=0x${virtsndWindowBase.toString(16)},0x1000,9,${init.virtioSound.streams},${init.virtioSound.chmaps}`).trim(); } let virtioWindowBase = 0; let virtfscacheWindowBase = 0; if (init.virtioFs) { virtioWindowBase = carveDevice(VIRTIO_WIN_SIZE); effectiveCmdline = (effectiveCmdline + ` wasm_virtiofs=0x${virtioWindowBase.toString(16)},0x${VIRTIO_WIN_SIZE.toString(16)},${VIRTIO_IRQ}`).trim(); } if (init.virtioFsCache) { virtfscacheWindowBase = carveDevice(VIRTFSCACHE_WIN_SIZE); effectiveCmdline = (effectiveCmdline + ` wasm_virtiofs_cache=0x${virtfscacheWindowBase.toString(16)},0x${VIRTFSCACHE_WIN_SIZE.toString(16)},${VIRTFSCACHE_IRQ}`).trim(); } const FB_FORMAT = "a8b8g8r8"; const FB_DEFAULT_MAX_W = 1920; const FB_DEFAULT_MAX_H = 1080; const FB_CEIL_W = 3840; const FB_CEIL_H = 2160; let fbBase = 0, fbWidth = 0, fbHeight = 0, fbStride = 0, fbSize = 0; let fbMaxW = 0, fbMaxH = 0; if (init.framebuffer) { fbMaxW = Math.max( FB_DEFAULT_MAX_W, Math.min(FB_CEIL_W, init.framebuffer.maxWidth | 0 || FB_DEFAULT_MAX_W) ); fbMaxH = Math.max( FB_DEFAULT_MAX_H, Math.min(FB_CEIL_H, init.framebuffer.maxHeight | 0 || FB_DEFAULT_MAX_H) ); fbWidth = init.framebuffer.width | 0 || 640; fbHeight = init.framebuffer.height | 0 || 480; fbWidth = Math.max(16, Math.min(fbMaxW, fbWidth)); fbHeight = Math.max(16, Math.min(fbMaxH, fbHeight)); fbStride = fbMaxW * 4; fbSize = fbStride * fbMaxH + 4095 & ~4095; fbBase = carveDevice(fbSize); const fbParams = `0x${fbBase.toString(16)},${fbWidth},${fbHeight},${fbStride},${FB_FORMAT},${fbMaxW},${fbMaxH}`; effectiveCmdline = (effectiveCmdline + ` wasm_drmfb=${fbParams}`).trim(); if (init.framebuffer.suppressHotplug) { effectiveCmdline = (effectiveCmdline + " wasm_drmfb_nohotplug").trim(); } if (init.framebuffer.resizeGateTimeoutMs) { effectiveCmdline = (effectiveCmdline + ` wasm_drmfb_resize_gate=${init.framebuffer.resizeGateTimeoutMs | 0}`).trim(); } } let virtinputWindowBase = 0; if (init.virtioInput) { virtinputWindowBase = carveDevice(VIRTINPUT_WIN_SIZE); const WASM_VINPUT_F_ABS = 1; const flags = init.virtioInput.absolutePointer ? WASM_VINPUT_F_ABS : 0; effectiveCmdline = (effectiveCmdline + ` wasm_virtinput=0x${virtinputWindowBase.toString(16)},0x${VIRTINPUT_WIN_SIZE.toString(16)},${VIRTINPUT_IRQ}${flags ? `,${flags}` : ""}`).trim(); } let virtnetWindowBase = 0; if (init.virtioNet) { virtnetWindowBase = carveDevice(VIRTNET_WIN_SIZE); const WASM_VIRTNET_FLAG_MRG_RXBUF = 1; const mtu = init.virtioNet.mtu | 0; const flags = init.virtioNet.mergeRxBuf ? WASM_VIRTNET_FLAG_MRG_RXBUF : 0; const wantMtu = mtu > 0 && mtu !== 1500; const tail = wantMtu ? flags ? `,${mtu},${flags}` : `,${mtu}` : ""; if (flags && !wantMtu) { post({ kind: "error", message: "virtioNet.mergeRxBuf was requested with no mtu (or mtu 1500); the flags field of wasm_virtnet= is positional and cannot be written without an mtu field before it. Set virtioNet.mtu." }); } effectiveCmdline = (effectiveCmdline + ` wasm_virtnet=0x${virtnetWindowBase.toString(16)},0x${VIRTNET_WIN_SIZE.toString(16)},${VIRTNET_IRQ}${tail}`).trim(); } const USB_WIN_SIZE = 8192; const USB_IRQ = 4; let usbWindowBase = 0; if (init.usbHcd) { usbWindowBase = carveDevice(USB_WIN_SIZE); effectiveCmdline = (effectiveCmdline + ` wasm_usb=0x${usbWindowBase.toString(16)},0x${USB_WIN_SIZE.toString(16)},${USB_IRQ}`).trim(); } let virtconWindowBase = 0; if (init.virtioConsole) { virtconWindowBase = carveDevice(VIRTCON_WIN_SIZE); const maxNrPorts = init.virtioConsole.maxNrPorts | 0 || 2; effectiveCmdline = (effectiveCmdline + ` wasm_virtcon=0x${virtconWindowBase.toString(16)},0x${VIRTCON_WIN_SIZE.toString(16)},${VIRTCON_IRQ},${maxNrPorts}`).trim(); } let hosttransWindowBase = 0; if (init.hostTransport) { hosttransWindowBase = carveDevice(HOSTTRANS_WIN_SIZE); effectiveCmdline = (effectiveCmdline + ` wasm_hosttrans=0x${hosttransWindowBase.toString(16)},0x${HOSTTRANS_WIN_SIZE.toString(16)},${HOSTTRANS_IRQ}`).trim(); } bootInfoOffset = align16(deviceRegionTop); const cmdlineBytes = new TextEncoder().encode(effectiveCmdline); const BOOT_INFO_SIZE = 104; const cmdlineOffset = align16(bootInfoOffset + BOOT_INFO_SIZE); const postCmdline = align16(cmdlineOffset + cmdlineBytes.length + 1); const RNG_SEED_BYTES = 64; const rngSeedBytes = new Uint8Array(RNG_SEED_BYTES); let haveRngSeed = false; try { if (globalThis.crypto && typeof globalThis.crypto.getRandomValues === "function") { globalThis.crypto.getRandomValues(rngSeedBytes); haveRngSeed = true; } } catch { } const rngSeedOffset = haveRngSeed ? postCmdline : 0; const rngSeedLength = haveRngSeed ? RNG_SEED_BYTES : 0; const postSeed = haveRngSeed ? align16(rngSeedOffset + RNG_SEED_BYTES) : postCmdline; const usableStart = postSeed; const totalMemory = spanBytes; if (usableStart >= totalMemory) { post({ kind: "error", message: `kernel memory too small for image + device regions + prologue: heap_base=0x${heapBase.toString(16)} device_block=[0x${deviceRegionBase.toString(16)},0x${deviceRegionTop.toString(16)}) usable_start=0x${usableStart.toString(16)} total=0x${totalMemory.toString(16)}` }); return; } const commitNeeded = kernelDoesDemandCommit ? usableStart : totalMemory; if (growKernelMemory(commitNeeded) < commitNeeded) { post({ kind: "error", message: `kernel memory could not be grown to ${kernelDoesDemandCommit ? "hold the boot prologue" : "the full span this pre-demand-commit kernel requires"}: need 0x${commitNeeded.toString(16)} bytes, env.kernel_memory stopped at 0x${init.kernelMemory.buffer.byteLength.toString(16)} (maximum 0x${totalMemory.toString(16)})` }); return; } if (!kernelDoesDemandCommit) { post({ kind: "dmesg", level: 4, text: `hardwarejs: this vmlinux.wasm exports no wasm32_committed_pages \u2014 it cannot ask the host to grow env.kernel_memory, so the full ${(totalMemory / (1024 * 1024)).toFixed(0)} MiB span was committed at boot. A demand-commit kernel would have started at ${(init.kernelMemory.buffer.byteLength / (1024 * 1024)).toFixed(0)} MiB.` }); } const kview = new Uint8Array(init.kernelMemory.buffer); if (init.bootInfoOverride) { if (init.bootInfoOverride.length !== BOOT_INFO_SIZE) { post({ kind: "error", message: `bootInfoOverride must be exactly ${BOOT_INFO_SIZE} bytes, got ${init.bootInfoOverride.length}` }); return; } kview.set(init.bootInfoOverride, bootInfoOffset); } else { const scratch = new ArrayBuffer(BOOT_INFO_SIZE); const dv = new DataView(scratch); dv.setUint32(0, 826884695, true); dv.setUint32(4, 4, true); dv.setUint32(8, BOOT_INFO_SIZE, true); dv.setUint32(12, 0, true); dv.setBigUint64(16, BigInt(totalMemory), true); dv.setBigUint64(24, BigInt(usableStart), true); dv.setBigUint64(32, BigInt(totalMemory), true); dv.setBigUint64(40, 0n, true); dv.setBigUint64(48, BigInt(heapBase), true); dv.setUint32(56, cmdlineOffset, true); dv.setUint32(60, cmdlineBytes.length, true); dv.setUint32(64, init.numCpus | 0 || 1, true); dv.setUint32(68, 0, true); dv.setBigUint64(72, 1000000000n, true); dv.setUint32(80, 0, true); dv.setUint32(84, 0, true); dv.setUint32(88, rngSeedOffset >>> 0, true); dv.setUint32(92, rngSeedLength >>> 0, true); dv.setBigUint64(96, BigInt(init.declaredMemoryBytes ?? totalMemory), true); kview.set(new Uint8Array(scratch), bootInfoOffset); } kview.set(cmdlineBytes, cmdlineOffset); kview[cmdlineOffset + cmdlineBytes.length] = 0; if (haveRngSeed) { kview.set(rngSeedBytes, rngSeedOffset); rngSeedBytes.fill(0); } let sched_wakeup_word_offset = -1; const wakeupExport = exp.__sched_wakeup_word; if (wakeupExport && typeof wakeupExport.value === "number") { sched_wakeup_word_offset = wakeupExport.value >>> 0; post({ kind: "sched-wakeup-word-offset", offset: sched_wakeup_word_offset }); } const spawnRingExport = exp.wasm32_spawn_ring; if (spawnRingExport && typeof spawnRingExport.value === "number") { post({ kind: "spawn-ring-offset", offset: spawnRingExport.value >>> 0 }); } const signalRingExport = exp.wasm32_signal_ring; if (signalRingExport && typeof signalRingExport.value === "number") { post({ kind: "signal-ring-offset", offset: signalRingExport.value >>> 0 }); } const tickReqExport = exp.wasm32_tick_req; if (tickReqExport && typeof tickReqExport.value === "number") { post({ kind: "tick-req-offset", offset: tickReqExport.value >>> 0 }); } const userSabPagesExport = exp.wasm32_user_sab_pages; if (userSabPagesExport && typeof userSabPagesExport.value === "number") { post({ kind: "user-sab-pages-offset", offset: userSabPagesExport.value >>> 0 }); } const pidPagesExport = exp.wasm32_user_sab_pid_pages; const pidSlotsExport = exp.wasm32_user_sab_pid_slots; const pidMaxExport = exp.wasm32_user_sab_pid_max; if (pidPagesExport && typeof pidPagesExport.value === "number" && pidSlotsExport && typeof pidSlotsExport.value === "number") { post({ kind: "user-sab-pid-table-offset", offset: pidPagesExport.value >>> 0, slotsOffset: pidSlotsExport.value >>> 0, ...pidMaxExport && typeof pidMaxExport.value === "number" ? { maxOffset: pidMaxExport.value >>> 0 } : {} }); } if (kernelDoesDemandCommit) { publishCommittedPages(); post({ kind: "committed-pages-offset", offset: committedPagesExport.value >>> 0 }); } if (init.virtioBlk) { post({ kind: "virtio-blk-window", base: virtblkWindowBase >>> 0 }); const irq = exp.wasm32_virtio_irq_pending; if (!irq || typeof irq.value !== "number") throw new Error("virtio-blk requires wasm32_virtio_irq_pending"); post({ kind: "virtio-irq-pending-offset", offset: irq.value >>> 0 }); } if (init.virtioSound) { post({ kind: "virtio-snd-window", base: virtsndWindowBase >>> 0 }); const irq = exp.wasm32_virtio_irq_pending; if (!irq || typeof irq.value !== "number") throw new Error("virtio-snd requires wasm32_virtio_irq_pending"); post({ kind: "virtio-irq-pending-offset", offset: irq.value >>> 0 }); } if (init.virtioFsCache) { post({ kind: "virtio-fs-cache-window", base: virtfscacheWindowBase >>> 0 }); } if (init.virtioFs) { post({ kind: "virtio-window", base: virtioWindowBase >>> 0, size: VIRTIO_WIN_SIZE, irq: VIRTIO_IRQ }); const virtioIrqExport = exp.wasm32_virtio_irq_pending; if (virtioIrqExport && typeof virtioIrqExport.value === "number") { post({ kind: "virtio-irq-pending-offset", offset: virtioIrqExport.value >>> 0 }); } else { post({ kind: "error", message: "virtioFs requested but vmlinux.wasm has no wasm32_virtio_irq_pending export" }); } } if (init.virtioInput) { post({ kind: "virtio-input-window", base: virtinputWindowBase >>> 0, size: VIRTINPUT_WIN_SIZE, irq: VIRTINPUT_IRQ }); const virtioIrqExport = exp.wasm32_virtio_irq_pending; if (virtioIrqExport && typeof virtioIrqExport.value === "number") { post({ kind: "virtio-irq-pending-offset", offset: virtioIrqExport.value >>> 0 }); } else { post({ kind: "error", message: "virtioInput requested but vmlinux.wasm has no wasm32_virtio_irq_pending export" }); } } if (init.virtioNet) { post({ kind: "virtio-net-window", base: virtnetWindowBase >>> 0, size: VIRTNET_WIN_SIZE, irq: VIRTNET_IRQ }); const virtioIrqExport = exp.wasm32_virtio_irq_pending; if (virtioIrqExport && typeof virtioIrqExport.value === "number") { post({ kind: "virtio-irq-pending-offset", offset: virtioIrqExport.value >>> 0 }); } else { post({ kind: "error", message: "virtioNet requested but vmlinux.wasm has no wasm32_virtio_irq_pending export" }); } } if (init.usbHcd) { post({ kind: "usb-window", base: usbWindowBase >>> 0, size: USB_WIN_SIZE, irq: USB_IRQ }); const virtioIrqExport = exp.wasm32_virtio_irq_pending; if (virtioIrqExport && typeof virtioIrqExport.value === "number") { post({ kind: "virtio-irq-pending-offset", offset: virtioIrqExport.value >>> 0 }); } else { post({ kind: "error", message: "usbHcd requested but vmlinux.wasm has no wasm32_virtio_irq_pending export" }); } } if (init.virtioConsole) { post({ kind: "virtio-console-window", base: virtconWindowBase >>> 0, size: VIRTCON_WIN_SIZE, irq: VIRTCON_IRQ }); const virtioIrqExport = exp.wasm32_virtio_irq_pending; if (virtioIrqExport && typeof virtioIrqExport.value === "number") { post({ kind: "virtio-irq-pending-offset", offset: virtioIrqExport.value >>> 0 }); } else { post({ kind: "error", message: "virtioConsole requested but vmlinux.wasm has no wasm32_virtio_irq_pending export" }); } } if (init.hostTransport) { post({ kind: "hosttrans-window", base: hosttransWindowBase >>> 0, size: HOSTTRANS_WIN_SIZE, irq: HOSTTRANS_IRQ }); const virtioIrqExport = exp.wasm32_virtio_irq_pending; if (virtioIrqExport && typeof virtioIrqExport.value === "number") { post({ kind: "virtio-irq-pending-offset", offset: virtioIrqExport.value >>> 0 }); } else { post({ kind: "error", message: "hostTransport requested but vmlinux.wasm has no wasm32_virtio_irq_pending export" }); } } if (init.framebuffer) { const displayCtrlExport = exp.wasm32_display_ctrl; const ctrlOffset = displayCtrlExport && typeof displayCtrlExport.value === "number" ? displayCtrlExport.value >>> 0 : 0; const slotsExport = exp.wasm32_display_slots; const slotsOffset = slotsExport && typeof slotsExport.value === "number" ? slotsExport.value >>> 0 : 0; post({ kind: "fb-window", base: fbBase >>> 0, width: fbWidth, height: fbHeight, stride: fbStride, size: fbSize, format: FB_FORMAT, maxWidth: fbMaxW, maxHeight: fbMaxH, ctrlOffset, slotsOffset }); } const ptyBridgeRingExport = exp.wasm32_pty_bridge_ring; if (ptyBridgeRingExport && typeof ptyBridgeRingExport.value === "number") { const table = exp.wasm32_pty_bridge_rings; post({ kind: "pty-bridge-ring-offset", offset: ptyBridgeRingExport.value >>> 0, tableOffset: table && typeof table.value === "number" ? table.value >>> 0 : void 0 }); } const serialBridgeRingExport = exp.wasm32_serial_bridge_ring; if (serialBridgeRingExport && typeof serialBridgeRingExport.value === "number") { post({ kind: "serial-bridge-ring-offset", offset: serialBridgeRingExport.value >>> 0 }); } const MERGED_QUANTUM_MS = 2; const MERGED_IDLE_POLL_MS = 4; const HAVE_WAIT_ASYNC = typeof Atomics.waitAsync === "function"; if (mergedCpu0 && !HAVE_WAIT_ASYNC) { post({ kind: "dmesg", level: 4, text: `hwjs-merged: this runtime has no Atomics.waitAsync \u2014 CPU 0's idle wait falls back to a ${MERGED_IDLE_POLL_MS}ms macrotask poll of __sched_wakeup_word. Correct (the word is the same, and a missed notify self-heals within one poll) but a wake costs up to ${MERGED_IDLE_POLL_MS}ms of latency it would not otherwise cost. ` }); } const cpu0ParkDeadlineMs = () => { const lo = kernU32[(cpu0ParkAddr >> 2) + 2] >>> 0; const hi = kernU32[(cpu0ParkAddr >> 2) + 3] >>> 0; if (lo === 4294967295 && hi === 4294967295) return Infinity; const ns = hi * 4294967296 + lo; return Math.max(1, Math.ceil(ns / 1e6)); }; async function waitForKernelWake() { const timeoutMs = cpu0ParkDeadlineMs(); if (sched_wakeup_word_offset < 0) { post({ kind: "dmesg", level: 3, text: `hwjs-merged: CPU 0 idle-parked but __sched_wakeup_word was never published, so its wake has no address. Falling back to a ${MERGED_IDLE_POLL_MS}ms turn; this machine's idle costs CPU. ` }); await macrotaskTurn(); return; } const idx = sched_wakeup_word_offset >> 2; if (HAVE_WAIT_ASYNC) { const r = Atomics.waitAsync(kernI32, idx, 0, timeoutMs); if (r.async) await r.value; else await macrotaskTurn(); return; } const deadline = Date.now() + (timeoutMs === Infinity ? 1e9 : timeoutMs); for (; ; ) { await macrotaskTurn(); if ((Atomics.load(kernI32, idx) | 0) !== 0) return; if (Date.now() >= deadline) return; if (stop.requested) return; await new Promise((res) => setTimeout(res, MERGED_IDLE_POLL_MS)); } } post({ kind: "pre-start" }); if (mergedCpu0) { const DEVICES_READY_TIMEOUT_MS = 1e4; const t0 = Date.now(); let ready = devicesReadySignal?.get?.() ?? null; while (ready === null && !stop.requested) { await macrotaskTurn(); ready = devicesReadySignal?.get?.() ?? null; if (ready !== null) break; if (Date.now() - t0 >= DEVICES_READY_TIMEOUT_MS) break; await new Promise((res) => setTimeout(res, 1)); } if (ready === null) { const why = devicesReadySignal === void 0 ? `this realm was bound by a transport that cannot deliver one (no inbound path after 'boot')` : `the host never posted one in ${Date.now() - t0} ms`; post({ kind: "error", message: `hwjs-merged: REFUSING to start the kernel \u2014 no 'devices-ready' from the host: ${why}. Merged, CPU 0 and the device backends share one JS thread, and a guest that reaches an in-kernel busy-wait on a device whose backend does not yet exist holds that thread forever (the virtcons_probe deadlock). Starting anyway would trade a named refusal for a machine that boots to silence.` }); return; } post({ kind: "dmesg", level: 6, text: `hwjs-merged: devices ready after ${Date.now() - t0} ms (${ready.built ?? "unnamed"}) ` }); } try { exp.wasm_start_kernel(bootInfoOffset); const canDrive = hwjsParkedAddr && hwjsKernelU32 && typeof exp.hwjs_resume === "function" && typeof exp.hwjs_done === "function" && typeof exp.hwjs_destroy === "function" && typeof exp.__hwjs_take_parked === "function"; const hwjsOwnerAddr = hwjsParkedAddr ? hwjsParkedAddr + 4 : 0; if (canDrive && hwjsKernelU32[hwjsParkedAddr >> 2] !== 0) { const owner = hwjsOwnerAddr ? hwjsKernelU32[hwjsOwnerAddr >> 2] : 0; const h = exp.__hwjs_take_parked(0, 0) >>> 0; post({ kind: "hwjs-host-drive", handle: h, owner }); let slices = 0; let spBreaths = 0; let idleParks = 0; let resumeNowParks = 0; let quantumYields = 0; let quantumT0 = Date.now(); while (!exp.hwjs_done(h)) { if (isPaused(pauseArr)) await waitOutPause(pauseArr); if (mergedCpu0) { const parkState = Atomics.load(kernI32, cpu0ParkAddr >> 2) | 0; if (parkState === CPU0_PARK_RESUME) { resumeNowParks++; Atomics.store(kernI32, cpu0ParkAddr >> 2, CPU0_PARK_NONE); } else if (parkState === CPU0_PARK_IDLE) { idleParks++; await waitForKernelWake(); noteHostThreadTurn(); Atomics.store(kernI32, cpu0ParkAddr >> 2, CPU0_PARK_NONE); quantumT0 = Date.now(); } else if (Date.now() - quantumT0 >= MERGED_QUANTUM_MS) { quantumYields++; await macrotaskTurn(); noteHostThreadTurn(); quantumT0 = Date.now(); } if (stop.requested) { post({ kind: "dmesg", level: 6, text: `hwjs-merged: cooperative stop honoured after ${slices} slice(s); the kernel chain is left PARKED (not destroyed) \u2014 nothing else may resume it, and the frame goes with the realm. ` }); break; } } if (typeof exp.__hwjs_budget_get === "function" && (exp.__hwjs_budget_get() | 0) === 0) { spBreaths++; exp.__hwjs_budget_set(HWJS_INITIAL_BUDGET | 0); await macrotaskTurn(); noteHostThreadTurn(); } exp.hwjs_resume(h); slices++; exp.__hwjs_take_parked(owner, h); } const stopped = stop.requested && !exp.hwjs_done(h); if (!stopped) exp.hwjs_destroy(h); post({ kind: "returned", message: `hwjs host drive loop: top frame 0x${h.toString(16)} (owner 0x${owner.toString(16)}) ` + (stopped ? `STOPPED cooperatively after ${slices} slice(s) \u2014 still parked, NOT destroyed` : `driven to done in ${slices} slice(s)`) + ` (${spBreaths} budget-expiry breath(es) refilled+yielded` + (mergedCpu0 ? `; merged CPU 0: ${idleParks} idle park(s) waited on __sched_wakeup_word, ${resumeNowParks} resume-now park(s), ${quantumYields} quantum yield(s) at ${MERGED_QUANTUM_MS}ms` : ``) + `); wasm_start_kernel never re-enters \u2014 boot ends here by construction.${hwjsArenaSuffix()}` }); } else { post({ kind: "returned", message: `wasm_start_kernel returned (should not happen)${hwjsArenaSuffix()}` }); } } catch (e) { const message = e instanceof Error ? `${e.message} ${e.stack ?? ""}` : String(e); post({ kind: "kernel-trap", message: message + hwjsArenaSuffix() }); } } // ../../linux-in-the-browser/hardwarejs/src/kernelWorker-browser.mjs bindKernelWorker({ post: (m) => self.postMessage(m), onMessage: (cb) => { self.onmessage = (ev) => cb(ev.data); } });