var __defProp = Object.defineProperty; var __getOwnPropNames = Object.getOwnPropertyNames; var __esm = (fn2, res) => function __init() { return fn2 && (res = (0, fn2[__getOwnPropNames(fn2)[0]])(fn2 = 0)), res; }; var __export = (target, all) => { for (var name2 in all) __defProp(target, name2, { get: all[name2], enumerable: true }); }; // ../../linux-in-the-browser/hardwarejs/src/uaccessCopies.mjs function zeroMemory(memory, addr, len) { let fill = fillByMemory.get(memory); if (fill === void 0) { if (fillModule === void 0) { fillModule = typeof WebAssembly !== "undefined" && WebAssembly.validate(FILL_BYTES) ? new WebAssembly.Module(FILL_BYTES) : null; } try { fill = fillModule ? new WebAssembly.Instance(fillModule, { m: { m: memory } }).exports.fill : null; } catch (_e) { fill = null; } fillByMemory.set(memory, fill); } if (fill !== null) fill(addr, len); else new Uint8Array(memory.buffer, addr, len).fill(0); } function zeroMemoryExcept(memory, addr, len, keepOff, keepLen) { const keep = keepLen > 0 && keepOff >= addr && keepOff + keepLen <= addr + len ? new Uint8Array(memory.buffer, keepOff, keepLen).slice() : null; zeroMemory(memory, addr, len); if (keep) new Uint8Array(memory.buffer, keepOff, keepLen).set(keep); } function modules() { if (copiesModule === void 0) { const ok = typeof WebAssembly !== "undefined" && WebAssembly.validate(COPIES_BYTES); copiesModule = ok ? new WebAssembly.Module(COPIES_BYTES) : null; doorModule = ok ? new WebAssembly.Module(DOOR_BYTES) : null; } return copiesModule; } function uaccessCopiesFor(userMemory, kernelMemory) { if (!modules() || !userMemory || !kernelMemory) return null; let byKernel = copiesByUser.get(userMemory); if (!byKernel) copiesByUser.set(userMemory, byKernel = /* @__PURE__ */ new WeakMap()); let c = byKernel.get(kernelMemory); if (c === void 0) { try { c = new WebAssembly.Instance(copiesModule, { m: { u: userMemory, k: kernelMemory } }).exports; } catch (_e) { c = null; } byKernel.set(kernelMemory, c); } return c; } function makeUaccessDoor() { if (!modules()) return null; const table = new WebAssembly.Table({ element: "anyfunc", initial: 3 }); const imports = new WebAssembly.Instance(doorModule, { m: { t: table } }).exports; return { imports, bind(copies) { table.set(0, copies.to_user); table.set(1, copies.from_user); table.set(2, copies.clear_user); } }; } var leb, name, section, vec, code, header, I32, fn, T_COPY, T_CLEAR, T_PAGES, TYPES, get, MEM_USER, MEM_KERNEL, past, orNotCopied, COPIES_BYTES, door, DOOR_BYTES, FILL_BYTES, fillModule, fillByMemory, copiesModule, doorModule, copiesByUser; var init_uaccessCopies = __esm({ "../../linux-in-the-browser/hardwarejs/src/uaccessCopies.mjs"() { "use strict"; leb = (n) => { const o = []; do { let b = n & 127; n >>>= 7; if (n) b |= 128; o.push(b); } while (n); return o; }; name = (s) => [...leb(s.length), ...[...s].map((c) => c.charCodeAt(0))]; section = (id, body) => [id, ...leb(body.length), ...body]; vec = (items) => [...leb(items.length), ...items.flat()]; code = (ops) => [...leb(ops.length + 2), 0, ...ops, 11]; header = [0, 97, 115, 109, 1, 0, 0, 0]; I32 = 127; fn = (params, results) => [96, ...vec(params.map((t) => [t])), ...vec(results.map((t) => [t]))]; T_COPY = 0; T_CLEAR = 1; T_PAGES = 2; TYPES = section(1, vec([fn([I32, I32, I32], [I32]), fn([I32, I32], [I32]), fn([], [I32])])); get = (i) => [32, i]; MEM_USER = 0; MEM_KERNEL = 1; past = (addr, n, mem) => [ ...get(addr), 173, ...get(n), 173, 124, /* i64.extend_i32_u, i64.add */ 63, mem, 173, 66, 16, 134, /* memory.size, extend, i64.const 16, i64.shl */ 86 /* i64.gt_u */ ]; orNotCopied = (n, body) => [4, I32, ...get(n), 5, ...body, 65, 0, 11]; COPIES_BYTES = new Uint8Array([ ...header, ...TYPES, ...section(2, vec(["u", "k"].map((m) => [...name("m"), ...name(m), 2, 3, 0, ...leb(65536)]))), ...section(3, vec([[T_COPY], [T_COPY], [T_CLEAR], [T_PAGES], [T_PAGES]])), ...section(7, vec([ [...name("to_user"), 0, 0], [...name("from_user"), 0, 1], [...name("clear_user"), 0, 2], [...name("user_pages"), 0, 3], [...name("kernel_pages"), 0, 4] ])), ...section(10, vec([ code([...past(0, 2, MEM_USER), ...orNotCopied(2, [...get(0), ...get(1), ...get(2), 252, 10, MEM_USER, MEM_KERNEL])]), code([...past(1, 2, MEM_USER), ...orNotCopied(2, [...get(0), ...get(1), ...get(2), 252, 10, MEM_KERNEL, MEM_USER])]), code([...past(0, 1, MEM_USER), ...orNotCopied(1, [...get(0), 65, 0, ...get(1), 252, 11, MEM_USER])]), code([63, MEM_USER]), code([63, MEM_KERNEL]) ])) ]); door = (i, type, args) => code([...args.flatMap((a) => get(a)), 65, i, 17, type, 0]); DOOR_BYTES = new Uint8Array([ ...header, ...TYPES, ...section(2, vec([[...name("m"), ...name("t"), 1, 112, 0, 3]])), ...section(3, vec([[T_COPY], [T_COPY], [T_CLEAR]])), ...section(7, vec([ [...name("raw_copy_to_user"), 0, 0], [...name("raw_copy_from_user"), 0, 1], [...name("raw_clear_user"), 0, 2] ])), ...section(10, vec([door(0, T_COPY, [0, 1, 2]), door(1, T_COPY, [0, 1, 2]), door(2, T_CLEAR, [0, 1])])) ]); FILL_BYTES = new Uint8Array([ ...header, ...section(1, vec([fn([I32, I32], [])])), ...section(2, vec([[...name("m"), ...name("m"), 2, 3, 0, ...leb(65536)]])), ...section(3, vec([[0]])), ...section(7, vec([[...name("fill"), 0, 0]])), ...section(10, vec([code([...get(0), 65, 0, ...get(1), 252, 11, 0])])) ]); fillByMemory = /* @__PURE__ */ new WeakMap(); copiesByUser = /* @__PURE__ */ new WeakMap(); } }); // ../../linux-in-the-browser/hardwarejs/src/macrotask.mjs 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); })); } var HAVE_SET_IMMEDIATE, HAVE_MESSAGE_CHANNEL, MACROTASK_TURN_KIND, MACROTASK_FAIRNESS_MS, fairnessLastMs, beltTurns, turns, macrotaskChannel, macrotaskWaiters, macrotaskPortRef, macrotaskPortUnref; var init_macrotask = __esm({ "../../linux-in-the-browser/hardwarejs/src/macrotask.mjs"() { "use strict"; HAVE_SET_IMMEDIATE = typeof setImmediate === "function"; HAVE_MESSAGE_CHANNEL = typeof MessageChannel === "function"; MACROTASK_TURN_KIND = HAVE_SET_IMMEDIATE ? "setImmediate" : HAVE_MESSAGE_CHANNEL ? "MessageChannel" : "setTimeout"; MACROTASK_FAIRNESS_MS = 100; fairnessLastMs = 0; beltTurns = 0; turns = 0; macrotaskChannel = null; macrotaskWaiters = []; macrotaskPortRef = (p) => { if (typeof p.ref === "function") p.ref(); }; macrotaskPortUnref = (p) => { if (typeof p.unref === "function") p.unref(); }; } }); // ../../linux-in-the-browser/hardwarejs/src/preemptTimer.mjs function preemptPortMessage(views, m) { if (m?.t === "reg") views.set(m.token, { i32: new Int32Array(m.sab), idx: m.idx >>> 0 }); else if (m?.t === "unreg") views.delete(m.token); } function preemptSweep(ctl, views, state, nowMs2) { let fired = 0; for (let s = 0; s < PT_SLOTS; s++) { const b = PT.HEADER + s * PT.STRIDE; const gen = Atomics.load(ctl, b + PT.GEN); if (gen !== state.gen[s]) { state.gen[s] = gen; state.start[s] = nowMs2; state.fired[s] = 0; } if (state.fired[s]) continue; const token = Atomics.load(ctl, b + PT.TOKEN); if (token === 0) continue; if ((nowMs2 - state.start[s]) * 1e3 < Atomics.load(ctl, b + PT.SLICE_US)) continue; const v = views.get(token); if (v === void 0) continue; if (Atomics.load(ctl, b + PT.TOKEN) !== token) continue; Atomics.store(v.i32, v.idx, 1); state.fired[s] = 1; fired++; } return fired; } function newPreemptState() { return { gen: new Int32Array(PT_SLOTS), start: new Float64Array(PT_SLOTS), fired: new Uint8Array(PT_SLOTS) }; } async function runPreemptTimer(ctlSab) { const ctl = new Int32Array(ctlSab); const clock = new Float64Array(ctlSab); const origin = performance.timeOrigin; const sleep = new Int32Array(new SharedArrayBuffer(4)); const state = newPreemptState(); for (let n = 0; ; n++) { if (Atomics.load(ctl, PT.ACTIVE) <= 0) { Atomics.wait(ctl, PT.ACTIVE, 0, IDLE_WAIT_MS); await macrotaskTurn(); continue; } Atomics.wait(sleep, 0, 0, TICK_MS); const now = performance.now(); clock[PT_CLOCK_F64] = origin + now; preemptSweep(ctl, preemptViews, state, now); if (n % TICKS_PER_TURN === 0) await macrotaskTurn(); } } function preemptAddPort(port) { port.onmessage = (ev) => preemptPortMessage(preemptViews, ev.data); } var PREEMPT_WORD_BYTES, PT, PT_CLOCK_F64, PT_SLOTS, preemptCtlBytes, TICK_MS, TICKS_PER_TURN, IDLE_WAIT_MS, preemptViews; var init_preemptTimer = __esm({ "../../linux-in-the-browser/hardwarejs/src/preemptTimer.mjs"() { "use strict"; init_macrotask(); PREEMPT_WORD_BYTES = 12; PT = Object.freeze({ ACTIVE: 0, HEADER: 4, STRIDE: 4, TOKEN: 0, SLICE_US: 1, GEN: 2 }); PT_CLOCK_F64 = 1; PT_SLOTS = 512; preemptCtlBytes = () => (PT.HEADER + PT.STRIDE * PT_SLOTS) * 4; TICK_MS = 1; TICKS_PER_TURN = 8; IDLE_WAIT_MS = 1e3; preemptViews = /* @__PURE__ */ new Map(); } }); // ../../linux-in-the-browser/hardwarejs/src/inlineRealm.ts var inlineRealm_exports = {}; __export(inlineRealm_exports, { createInlineRealm: () => createInlineRealm }); function createInlineRealm(bind, origin) { let stopped = false; const terminateHooks = []; let inbound = null; const pendingToHost = []; const pendingErrors = []; let onmessageCb = null; let onerrorCb = null; const pendingToRealm = []; let hostSyncCall = null; const handle = { postMessage: (m, transfer) => { toRealm(m, transfer); }, get onmessage() { return onmessageCb; }, set onmessage(cb) { onmessageCb = cb; if (cb === null || stopped) return; const q = pendingToHost.splice(0, pendingToHost.length); if (browserPortSemantics) { for (const m of q) { toHostQueue.push(m); toHostCh.port2.postMessage(0); } return; } for (const m of q) { try { cb({ data: m }); } catch (e) { reportError(e); } } }, get onerror() { return onerrorCb; }, set onerror(cb) { onerrorCb = cb; if (cb === null || stopped) return; const q = pendingErrors.splice(0, pendingErrors.length); for (const e of q) { try { cb(e); } catch { } } }, setHostSyncCall: (fn2) => { hostSyncCall = fn2; }, terminate: () => { if (stopped) return; stopped = true; hostSyncCall = null; for (const h of terminateHooks) { try { h(); } catch { } } closePorts(); reportUndelivered(); }, get stopped() { return stopped; }, get origin() { return origin; } }; const toRealmCh = new MessageChannel(); const toHostCh = new MessageChannel(); const unref = (p) => { const q = p; if (typeof q.unref === "function") q.unref(); }; unref(toRealmCh.port1); unref(toRealmCh.port2); unref(toHostCh.port1); unref(toHostCh.port2); function reportError(e) { const msg = e instanceof Error ? e.stack ?? e.message : String(e); if (onerrorCb) onerrorCb(msg); else if (!stopped) pendingErrors.push(msg); else queueMicrotask(() => { throw new Error(`inline realm [${origin}]: ${msg}`); }); } function reportUndelivered() { if (pendingToHost.length > 0) { const kinds = pendingToHost.map(kindOf).join(", "); queueMicrotask(() => { throw new Error( `inline realm [${origin}]: torn down with ${pendingToHost.length} message(s) the host NEVER READ \u2014 kinds: ${kinds}. They were posted by the realm before anything attached an onmessage handler; the host saw a machine that produced nothing.` ); }); } if (pendingErrors.length > 0) { const first = pendingErrors[0]; queueMicrotask(() => { throw new Error( `inline realm [${origin}]: torn down with ${pendingErrors.length} unread error(s); the first was: ${String(first)}` ); }); } if (pendingToRealm.length > 0) { const kinds = pendingToRealm.map(kindOf).join(", "); queueMicrotask(() => { throw new Error( `inline realm [${origin}]: torn down with ${pendingToRealm.length} message(s) the REALM never read \u2014 kinds: ${kinds}.` ); }); } } toRealmCh.port1.onmessage = (ev) => { if (stopped) return; if (!inbound) { pendingToRealm.push(ev.data); return; } deliverToRealm(ev.data); }; function deliverToRealm(data) { try { const r = inbound(data); if (r && typeof r.catch === "function") { r.catch(reportError); } } catch (e) { reportError(e); } } const browserPortSemantics = !!(globalThis.process?.env?.HWJS_INLINE_REALM_BROWSER_PORT || globalThis.HWJS_INLINE_REALM_BROWSER_PORT); const toHostQueue = []; toHostCh.port1.onmessage = (ev) => { if (stopped) return; const data = browserPortSemantics ? toHostQueue.length > 0 ? toHostQueue.shift() : void 0 : ev.data; if (browserPortSemantics && data === void 0) return; if (!onmessageCb) { pendingToHost.push(data); return; } try { onmessageCb({ data }); } catch (e) { reportError(e); } }; const kindOf = (m) => m && typeof m === "object" && typeof m.kind === "string" ? m.kind : ""; toRealmCh.port1.onmessageerror = () => reportError( `inline realm [${origin}]: a message to the realm arrived but could not be DESERIALISED (messageerror). It is lost, and the realm is waiting for it.` ); toHostCh.port1.onmessageerror = () => reportError( `inline realm [${origin}]: a message from the realm could not be DESERIALISED (messageerror). It is lost, and the host is waiting for it.` ); function toRealm(m, transfer) { if (stopped) return; try { toRealmCh.port2.postMessage(m, transfer ?? []); } catch (e) { reportError( `inline realm [${origin}]: postMessage(kind=${kindOf(m)}) to the realm threw \u2014 the value is not structured-cloneable, which a real Worker would also refuse: ${e instanceof Error ? e.message : String(e)}` ); } } function toHost(m) { if (stopped) return; if (browserPortSemantics) { toHostQueue.push(m); try { toHostCh.port2.postMessage(0); } catch (e) { reportError(e); } return; } try { toHostCh.port2.postMessage(m); } catch (e) { reportError( `inline realm [${origin}]: postMessage(kind=${kindOf(m)}) to the host threw \u2014 the value is not structured-cloneable, which a real Worker would also refuse: ${e instanceof Error ? e.message : String(e)}` ); } } function closePorts() { for (const p of [toRealmCh.port1, toRealmCh.port2, toHostCh.port1, toHostCh.port2]) { try { p.close(); } catch { } } } bind({ post: toHost, onMessage: (cb) => { inbound = cb; if (stopped) return; const q = pendingToRealm.splice(0, pendingToRealm.length); for (const m of q) deliverToRealm(m); }, onTerminate: (cb) => { terminateHooks.push(cb); }, /* NOT the host handler itself — a stable forwarder, so the realm can hold * this one reference for its whole life while the host installs and * removes handlers underneath it. A throw here is REPORTED and swallowed: * the caller is a guest busy-wait inside a wasm frame, and letting a host * device error trap the kernel would turn a serviceable doorbell into a * dead machine. */ callHostSync: (m) => { if (stopped || hostSyncCall === null) return void 0; try { return hostSyncCall(m); } catch (e) { reportError(e); return void 0; } } }); return handle; } var init_inlineRealm = __esm({ "../../linux-in-the-browser/hardwarejs/src/inlineRealm.ts"() { "use strict"; } }); // ../../linux-in-the-browser/hardwarejs/src/dynLoader.mjs function readU32LEB(b, p) { let result = 0, shift = 0, byte = 0; do { if (p >= b.length) throw new Error("hwjs-dlopen: truncated LEB in dylink.0"); byte = b[p++]; result |= (byte & 127) << shift; shift += 7; } while (byte & 128); return [result >>> 0, p]; } function wasmSource2(bytes) { if (!(bytes && bytes.buffer instanceof SharedArrayBuffer)) return bytes; if (__sharedWasmSourceOk === void 0) { try { const probe = new Uint8Array(new SharedArrayBuffer(8)); probe.set([0, 97, 115, 109, 1, 0, 0, 0]); new WebAssembly.Module(probe); __sharedWasmSourceOk = true; } catch (_e) { __sharedWasmSourceOk = false; } } return __sharedWasmSourceOk ? bytes : bytes.slice(); } function decodeMaybeShared2(view) { const shared = typeof SharedArrayBuffer !== "undefined" && view.buffer instanceof SharedArrayBuffer; return __dynLoaderDecoder.decode(shared ? view.slice() : view); } function parseDylink0(bytes) { const b = bytes; if (b.length < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) { throw new Error("hwjs-dlopen: not a wasm module (bad magic)"); } let p = 8; while (p < b.length) { const id = b[p++]; let size; [size, p] = readU32LEB(b, p); const sectionEnd = p + size; if (id === 0) { let nameLen, np = p; [nameLen, np] = readU32LEB(b, np); const name2 = decodeMaybeShared2(b.subarray(np, np + nameLen)); np += nameLen; if (name2 === "dylink.0") { const info = { memorySize: 0, memoryAlign: 1, tableSize: 0, tableAlign: 1, needed: [], tlsExports: [], /* hardwarejs#46: symbol name -> import module, for each import * wasm-ld marked WEAK. Its GOT.func/GOT.mem entries carry the same * name. */ weakImports: /* @__PURE__ */ new Map() }; let sp = np; while (sp < sectionEnd) { const subId = b[sp++]; let subSize; [subSize, sp] = readU32LEB(b, sp); const subEnd = sp + subSize; if (subId === WASM_DYLINK_MEM_INFO) { let memSize, memAlignLog2, tblSize, tblAlignLog2; [memSize, sp] = readU32LEB(b, sp); [memAlignLog2, sp] = readU32LEB(b, sp); [tblSize, sp] = readU32LEB(b, sp); [tblAlignLog2, sp] = readU32LEB(b, sp); info.memorySize = memSize; info.memoryAlign = 1 << memAlignLog2; info.tableSize = tblSize; info.tableAlign = 1 << tblAlignLog2; } else if (subId === WASM_DYLINK_NEEDED) { let count; [count, sp] = readU32LEB(b, sp); for (let i = 0; i < count; i++) { let len; [len, sp] = readU32LEB(b, sp); info.needed.push(decodeMaybeShared2(b.subarray(sp, sp + len))); sp += len; } } else if (subId === WASM_DYLINK_EXPORT_INFO) { let count; [count, sp] = readU32LEB(b, sp); for (let i = 0; i < count; i++) { let len, flags; [len, sp] = readU32LEB(b, sp); const nm2 = decodeMaybeShared2(b.subarray(sp, sp + len)); sp += len; [flags, sp] = readU32LEB(b, sp); if (flags & WASM_SYMBOL_TLS) info.tlsExports.push(nm2); } } else if (subId === WASM_DYLINK_IMPORT_INFO) { let count; [count, sp] = readU32LEB(b, sp); for (let i = 0; i < count; i++) { let len, flags; [len, sp] = readU32LEB(b, sp); const mod = decodeMaybeShared2(b.subarray(sp, sp + len)); sp += len; [len, sp] = readU32LEB(b, sp); const nm2 = decodeMaybeShared2(b.subarray(sp, sp + len)); sp += len; [flags, sp] = readU32LEB(b, sp); if ((flags & WASM_SYMBOL_BINDING_MASK) === WASM_SYMBOL_BINDING_WEAK) { info.weakImports.set(nm2, mod); } } } sp = subEnd; } return info; } } p = sectionEnd; } return null; } function parseImportedTableType(bytes) { const b = bytes; if (b.length < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) { throw new Error("hwjs-dlopen: not a wasm module (bad magic)"); } let p = 8; while (p < b.length) { const id = b[p++]; let size; [size, p] = readU32LEB(b, p); const sectionEnd = p + size; if (id === 2) { let count; [count, p] = readU32LEB(b, p); for (let i = 0; i < count; i++) { let len; [len, p] = readU32LEB(b, p); p += len; [len, p] = readU32LEB(b, p); p += len; const kind = b[p++]; if (kind === 0) { [, p] = readU32LEB(b, p); } else if (kind === 1) { p += 1; const flags = b[p++]; let min, max; [min, p] = readU32LEB(b, p); if (flags & 1) { [max, p] = readU32LEB(b, p); } return { min, max }; } else if (kind === 2) { const flags = b[p++]; [, p] = readU32LEB(b, p); if (flags & 1) { [, p] = readU32LEB(b, p); } } else if (kind === 3) { p += 2; } } } p = sectionEnd; } return null; } function parseImportedMemoryMinPages(bytes) { const b = bytes; if (b.length < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) { throw new Error("hwjs-exec: not a wasm module (bad magic; cannot read memory-import min)"); } let firstMemMin = null; let p = 8; while (p < b.length) { const id = b[p++]; let size; [size, p] = readU32LEB(b, p); const sectionEnd = p + size; if (id === 2) { let count; [count, p] = readU32LEB(b, p); for (let i = 0; i < count; i++) { let len; [len, p] = readU32LEB(b, p); const mod = decodeMaybeShared2(b.subarray(p, p + len)); p += len; [len, p] = readU32LEB(b, p); const fld = decodeMaybeShared2(b.subarray(p, p + len)); p += len; const kind = b[p++]; if (kind === 0) { [, p] = readU32LEB(b, p); } else if (kind === 1) { p += 1; const flags = b[p++]; [, p] = readU32LEB(b, p); if (flags & 1) { [, p] = readU32LEB(b, p); } } else if (kind === 2) { const flags = b[p++]; let min; [min, p] = readU32LEB(b, p); if (flags & 1) { [, p] = readU32LEB(b, p); } if (mod === "env" && fld === "user_memory") return min; if (firstMemMin === null) firstMemMin = min; } else if (kind === 3) { p += 2; } } return firstMemMin; } p = sectionEnd; } return firstMemMin; } function parseImportedFunctionNames(bytes) { const b = bytes; const importedFns = []; const fnNameSubsections = []; let p = 8; while (p < b.length) { const id = b[p++]; let size; [size, p] = readU32LEB(b, p); const sectionEnd = p + size; if (id === 2) { let count; [count, p] = readU32LEB(b, p); for (let i = 0; i < count; i++) { let len, mod, fld; [len, p] = readU32LEB(b, p); mod = decodeMaybeShared2(b.subarray(p, p + len)); p += len; [len, p] = readU32LEB(b, p); fld = decodeMaybeShared2(b.subarray(p, p + len)); p += len; const kind = b[p++]; if (kind === 0) { [, p] = readU32LEB(b, p); importedFns.push({ module: mod, field: fld }); } else if (kind === 1) { p += 1; const f = b[p++]; [, p] = readU32LEB(b, p); if (f & 1) { [, p] = readU32LEB(b, p); } } else if (kind === 2) { const f = b[p++]; [, p] = readU32LEB(b, p); if (f & 1) { [, p] = readU32LEB(b, p); } } else if (kind === 3) { p += 2; } } } else if (id === 0) { let nameLen, np = p; [nameLen, np] = readU32LEB(b, np); const cname = decodeMaybeShared2(b.subarray(np, np + nameLen)); np += nameLen; if (cname === "name") { let sp = np; while (sp < sectionEnd) { const subId = b[sp++]; let subSize; [subSize, sp] = readU32LEB(b, sp); const subEnd = sp + subSize; if (subId === 1) fnNameSubsections.push(sp); sp = subEnd; } } } p = sectionEnd; } const nameByFuncIdx = /* @__PURE__ */ new Map(); for (let sp of fnNameSubsections) { let c; [c, sp] = readU32LEB(b, sp); for (let i = 0; i < c; i++) { let fi, nl; [fi, sp] = readU32LEB(b, sp); [nl, sp] = readU32LEB(b, sp); if (fi < importedFns.length) { nameByFuncIdx.set(fi, decodeMaybeShared2(b.subarray(sp, sp + nl))); } sp += nl; } } const out = /* @__PURE__ */ new Map(); for (let i = 0; i < importedFns.length; i++) { const nm2 = nameByFuncIdx.get(i); if (nm2) out.set(nm2, importedFns[i]); } return out; } function importedFunctionNamesOf(module, bytes) { let names = importedFunctionNamesByModule.get(module); if (names === void 0) { names = parseImportedFunctionNames(bytes); importedFunctionNamesByModule.set(module, names); } return names; } function moduleFactsOf(module) { let f = moduleFactsByModule.get(module); if (f === void 0) { f = /* @__PURE__ */ Object.create(null); moduleFactsByModule.set(module, f); } return f; } function moduleKeptOf(module) { let k = moduleKeptByModule.get(module); if (k === void 0) { k = /* @__PURE__ */ Object.create(null); moduleKeptByModule.set(module, k); } return k; } function moduleFactsDrop() { moduleFactsByModule = /* @__PURE__ */ new WeakMap(); neededExportersRoot = { next: /* @__PURE__ */ new WeakMap(), maps: null }; } function packEntries(list, withModule) { const parts = []; const lengths = new Uint32Array(withModule ? list.length * 2 : list.length); const kinds = new Uint8Array(list.length); let j = 0; for (let i = 0; i < list.length; i++) { const e = list[i]; if (withModule) { parts.push(e.module); lengths[j++] = e.module.length; } parts.push(e.name); lengths[j++] = e.name.length; const k = PACKED_KINDS.indexOf(e.kind); if (k < 0) return null; kinds[i] = k; } return { text: parts.join(""), lengths, kinds }; } function unpackEntries(packed, withModule) { const { text, lengths, kinds } = packed; const out = new Array(kinds.length); let at = 0; let j = 0; for (let i = 0; i < kinds.length; i++) { let module; if (withModule) { module = text.slice(at, at + lengths[j]); at += lengths[j++]; } const name2 = text.slice(at, at + lengths[j]); at += lengths[j++]; out[i] = withModule ? { module, name: name2, kind: PACKED_KINDS[kinds[i]] } : { name: name2, kind: PACKED_KINDS[kinds[i]] }; } return out; } function listedEntries(module, key, withModule, list) { const f = moduleFactsOf(module); if (f[key] !== void 0) return f[key]; const k = moduleKeptOf(module); let out; if (k[key] !== void 0) { out = unpackEntries(k[key], withModule); } else { out = list(module); const packed = packEntries(out, withModule); if (packed !== null) k[key] = packed; } return f[key] = Object.freeze(out); } function moduleImportsOf(module) { return listedEntries(module, "imports", true, WebAssembly.Module.imports); } function moduleExportsOf(module) { return listedEntries(module, "exports", false, WebAssembly.Module.exports); } function functionExportNamesOf(module) { const f = moduleFactsOf(module); if (f.fnExportNames === void 0) { const s = /* @__PURE__ */ new Set(); for (const e of moduleExportsOf(module)) { if (e.kind === "function") s.add(e.name); } f.fnExportNames = s; } return f.fnExportNames; } function neededFirstExporters(modules2) { let node = neededExportersRoot; for (const m of modules2) { let next = node.next.get(m); if (next === void 0) { next = { next: /* @__PURE__ */ new WeakMap(), maps: null }; node.next.set(m, next); } node = next; } if (node.maps === null) { const fn2 = /* @__PURE__ */ new Map(); const data = /* @__PURE__ */ new Map(); for (let pos = 0; pos < modules2.length; pos++) { for (const e of moduleExportsOf(modules2[pos])) { const m = e.kind === "function" ? fn2 : e.kind === "global" ? data : null; if (m && !m.has(e.name)) m.set(e.name, pos); } } node.maps = { fn: fn2, data }; } return node.maps; } function neededSiblingTiers(wants, moduleOf) { const first = neededFirstExporters(wants.map(moduleOf)); const indexAt = wants.map((w) => w.index); const view = (m) => ({ get: (n) => { const pos = m.get(n); return pos === void 0 ? void 0 : indexAt[pos]; } }); return { fn: view(first.fn), data: view(first.data) }; } function activeElemEnd(bytes) { const b = bytes; let end = 0; let p = 8; while (p < b.length) { const id = b[p++]; let size; [size, p] = readU32LEB(b, p); const sectionEnd = p + size; if (id === 9) { let count; [count, p] = readU32LEB(b, p); for (let s = 0; s < count; s++) { let flags; [flags, p] = readU32LEB(b, p); if (flags === 3) { p += 1; let n2; [n2, p] = readU32LEB(b, p); for (let i = 0; i < n2; i++) { [, p] = readU32LEB(b, p); } continue; } if (flags !== 0 && flags !== 2) return Infinity; if (flags === 2) { let tableIdx; [tableIdx, p] = readU32LEB(b, p); if (tableIdx !== 0) return Infinity; } if (b[p++] !== 65) return Infinity; let off; [off, p] = readS32LEB(b, p, sectionEnd); if (b[p++] !== 11 || off < 0) return Infinity; if (flags === 2 && b[p++] !== 0) return Infinity; let n; [n, p] = readU32LEB(b, p); for (let i = 0; i < n; i++) { [, p] = readU32LEB(b, p); } if (off + n > end) end = off + n; } return end; } p = sectionEnd; } return end; } function activeElemEndOf(module, bytes) { const f = moduleKeptOf(module); return f.activeElemEnd ?? (f.activeElemEnd = activeElemEnd(bytes)); } function parseExportedFunctionIndices(bytes) { const b = bytes; const out = /* @__PURE__ */ new Map(); let p = 8; while (p < b.length) { const id = b[p++]; let size; [size, p] = readU32LEB(b, p); const sectionEnd = p + size; if (id === 7) { let count; [count, p] = readU32LEB(b, p); for (let i = 0; i < count; i++) { let len, idx; [len, p] = readU32LEB(b, p); const nm2 = decodeMaybeShared2(b.subarray(p, p + len)); p += len; const kind = b[p++]; [idx, p] = readU32LEB(b, p); if (kind === 0) out.set(nm2, idx); } break; } p = sectionEnd; } return out; } function setLinkFactsStore(store) { linkFactsStore = store && typeof store.get === "function" && typeof store.put === "function" ? store : null; } function noteModuleContentId(module, id) { if (module instanceof WebAssembly.Module && typeof id === "string" && id !== "") { moduleKeptOf(module).contentId = id; } } function moduleContentId(module) { return module instanceof WebAssembly.Module ? moduleKeptOf(module).contentId : void 0; } function sharedFactsOf(module, key) { const id = moduleContentId(module); if (id === void 0 || linkFactsStore === null) return void 0; const f = linkFactsStore.get(`${key}:${id}`); return f && f.v === LINK_FACTS_FORMAT ? f : void 0; } function publishFacts(module, key, facts) { const id = moduleContentId(module); if (id === void 0 || linkFactsStore === null) return; try { linkFactsStore.put(`${key}:${id}`, { v: LINK_FACTS_FORMAT, ...facts }); } catch (_e) { } } function exportedFunctionIndicesOf(module, bytes) { if (!(module instanceof WebAssembly.Module)) return parseExportedFunctionIndices(bytes); const k = moduleKeptOf(module); if (k.exportFnIndices !== void 0) return k.exportFnIndices; let m; const shared = sharedFactsOf(module, "xfi"); if (shared && Array.isArray(shared.names) && shared.idx instanceof Uint32Array && shared.names.length === shared.idx.length) { m = /* @__PURE__ */ new Map(); for (let i = 0; i < shared.names.length; i++) m.set(shared.names[i], shared.idx[i]); } else { m = parseExportedFunctionIndices(bytes); publishFacts(module, "xfi", { names: [...m.keys()], idx: Uint32Array.from(m.values()) }); } return k.exportFnIndices = m; } function dlopenSiblingExport(name2, modules2) { if (name2.startsWith("__hwjs_") || name2.startsWith("__wasm_")) return void 0; for (const mod of modules2) { const f = mod && mod.handle && mod.handle.exports ? mod.handle.exports[name2] : void 0; if (typeof f === "function") return f; } return void 0; } function dlopenScopeExport(name2, ownDefined, needed, dlopened) { if (ownDefined) return void 0; return dlopenSiblingExport(name2, needed) ?? dlopenSiblingExport(name2, dlopened); } function mainScopeFunction(name2, mainExports, needed, order) { const fn2 = mainExports ? mainExports[name2] : void 0; if (typeof fn2 === "function") { if (!order) return fn2; const own = fn2 !== (order.libcExports ? order.libcExports[name2] : void 0) && fn2 !== (order.rtExports ? order.rtExports[name2] : void 0); if (own || !mainNeededBeforeLibc( name2, order.rtExports || null, order.mainGotFunc || null )) return fn2; return dlopenSiblingExport(name2, scopeWithoutBarredPreloads(name2, needed)) ?? fn2; } return dlopenSiblingExport(name2, order ? scopeWithoutBarredPreloads(name2, needed) : needed); } function scopeWithoutBarredPreloads(name2, needed) { const barred = PRELOAD_LIBC_ALLOCATOR.has(name2) || name2.startsWith("__hwjs_") || name2.startsWith("__wasm_"); const out = []; for (const h of needed) { if (h && h.preload && barred) continue; out.push(h); } return out; } function dlsymCallerImport(name2, fn2, libcExports, caller, box) { if (typeof fn2 !== "function" || !DLSYM_CALLER_IMPORTS.has(name2)) return fn2; if (!libcExports || fn2 !== libcExports[name2]) return fn2; const bound = (...a) => { box.caller = caller; return fn2(...a); }; bound.tableTarget = fn2; return bound; } function rtldNextHandles(caller, name2, scope) { if (!caller || typeof caller !== "object") return null; let after; if (caller.kind === "main") { after = scopeWithoutBarredPreloads(name2, scope.needed); } else if (caller.kind === "needed") { const i = scope.needed.findIndex((h) => h && h.index === caller.index); if (i < 0) return null; after = scopeWithoutBarredPreloads(name2, scope.needed.slice(i + 1)); } else if (caller.kind === "dlopen") { const list = [...scope.dlopened].filter((e) => e && !e.mainScope && e.handle); const i = list.findIndex((e) => e.dlsymCaller === caller); after = i < 0 ? [] : list.slice(i + 1); } else { return null; } const out = []; for (const h of after) if (h && h.handle) out.push(h.handle); if (scope.libc) out.push(scope.libc); return out; } function lateTableEntries(live2, recorded) { const seen = new Set((recorded || []).map(([n]) => n)); return live2.filter(([n]) => !seen.has(n)); } function mainNeededBeforeLibc(name2, rtExports, mainGotFunc) { if (name2.startsWith("__hwjs_") || name2.startsWith("__wasm_")) return false; if (rtExports && typeof rtExports[name2] === "function") return false; return !!mainGotFunc && mainGotFunc.has(name2); } function mainImportProviders(name2, rtExports, libcExports, needed, mainGotFunc) { const rt = [], libc = [], libs = []; if (rtExports && typeof rtExports[name2] === "function") { rt.push({ from: "rt", fn: rtExports[name2] }); } if (libcExports && typeof libcExports[name2] === "function") { libc.push({ from: "libc", fn: libcExports[name2] }); } for (const h of needed) { const f = h && h.exports ? h.exports[name2] : void 0; if (typeof f === "function") libs.push({ from: h, fn: f }); } return mainNeededBeforeLibc(name2, rtExports, mainGotFunc) ? [...rt, ...libs, ...libc] : [...rt, ...libc, ...libs]; } function ldPreloadEntries(envp) { if (!Array.isArray(envp)) return []; const kv = envp.find((s) => typeof s === "string" && s.startsWith("LD_PRELOAD=")); if (!kv) return []; return kv.slice("LD_PRELOAD=".length).split(/[ :\t\n]+/).filter((s) => s.length > 0); } function ldPreloadCandidates(item) { return item.includes("/") ? [item] : [`/usr/lib/${item}`, `/lib/${item}`]; } function ldLibraryPathDirs(envp) { if (!Array.isArray(envp)) return []; const kv = envp.find((s) => typeof s === "string" && s.startsWith("LD_LIBRARY_PATH=")); if (!kv || kv.length === "LD_LIBRARY_PATH=".length) return []; const dirs = kv.slice("LD_LIBRARY_PATH=".length).split(/[:;]/).map((d) => d.length === 0 ? "." : d.replace(/\/+$/, "")); return [...new Set(dirs)]; } function ldLibraryPathCandidates(dirs, name2) { const plain = neededSoname(name2); return dirs.flatMap((d) => [`${d}/${name2}`, `${d}/${plain}`]); } function dirOfPath(path) { const p = String(path).replace(/\/+$/, ""); const at = p.lastIndexOf("/"); if (at < 0) return "."; return p.slice(0, at).replace(/\/+$/, ""); } function runPathDirs(runpath, origin) { const out = []; for (const entry of runpath || []) { let d = entry; if (d.includes("$")) { if (typeof origin !== "string") continue; d = d.replace(/\$\{ORIGIN\}|\$ORIGIN(?![0-9A-Za-z_])/g, () => origin); if (d.includes("$")) continue; } out.push(d.replace(/\/+$/, "")); } return [...new Set(out)]; } function neededRecordRunPath(record, who) { if (!("runpath" in record)) return []; const rp = record.runpath; if (!Array.isArray(rp) || rp.some((d) => typeof d !== "string" || d.length === 0 || d.length >= 4096 || d.includes("\0"))) { throw new Error(`${who} wasm.linux.needed "runpath" is not a list of directories (never-silent)`); } return [...rp]; } function neededLoadErrorLine(prog, name2, kernelErrno, mismatched) { const ELIBBAD = -80; const found = [...mismatched]; if (kernelErrno === ELIBBAD) found.push("the copy in /lib, /usr/lib or /usr/local/lib (see dmesg)"); let why; if (found.length) { why = `not the build this program was linked against: ${found.join(", ")}; relink the program`; } else if (kernelErrno === -2) { why = "cannot open shared object file: No such file or directory"; } else { why = `cannot read shared object file: error ${-kernelErrno}`; } return `${prog}: error while loading shared libraries: ${neededSoname(name2)}: ${why}`; } function preloadProvider(name2, preloads) { if (name2.startsWith("__hwjs_") || name2.startsWith("__wasm_")) return void 0; if (PRELOAD_LIBC_ALLOCATOR.has(name2)) return void 0; for (const p of preloads) { if (p && p.exports && typeof p.exports[name2] === "function") return p; } return void 0; } function neededScopeFor(name2, needed) { return needed.filter((h) => !h || !h.preload || preloadProvider(name2, [h])); } function ldPreloadRefusal(bytes, digest, mainNeeded) { if (mainNeeded.some((n) => neededDigest(n) === digest)) { return { reason: "the program loads it already", already: true }; } try { if (!parseDylink0(bytes)) return { reason: "not a shared object" }; parseSideModuleNeeded(bytes); } catch (e) { return { reason: `not a shared object (${e instanceof Error ? e.message : e})` }; } return null; } function ldPreloadNeeds(bytes, mainNeeded) { const have = new Set(mainNeeded.map((n) => neededDigest(n))); return parseSideModuleNeeded(bytes).filter((n) => !have.has(neededDigest(n))); } function ldPreloadDependencies(preloads, mainNeeded, needsOf) { const placed = new Set([...mainNeeded, ...preloads.map((p) => p.name)].map((n) => neededDigest(n))); const order = []; const queue = preloads.map((p) => p.name); for (let i = 0; i < queue.length; i++) { for (const n of needsOf(queue[i]) || []) { const d = neededDigest(n); if (placed.has(d)) continue; placed.add(d); order.push(n); queue.push(n); } } return order; } function mainScopeDataAddress(name2, mainExports, needed) { if (name2.startsWith("__hwjs_") || name2.startsWith("__wasm_") || DLOPEN_SIBLING_DATA_RESERVED.has(name2)) return 0; const g = mainExports ? mainExports[name2] : void 0; if (g instanceof WebAssembly.Global) { let mutable = true; try { g.value = g.value; } catch (_e) { mutable = false; } if (!mutable) return g.value >>> 0; return 0; } return dlopenSiblingDataAddress(name2, needed) || 0; } function dlopenOpenModule(modules2, digest, digestOf) { for (const [cookie, m] of modules2) { if (!m || m.mainScope || !m.bytes) continue; if (m.digest === void 0) m.digest = digestOf(m.bytes); if (m.digest === digest) return [cookie, m]; } return null; } function wasmLinuxSoname(bytes) { const b = bytes; if (!b || b.length < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) return null; try { let p = 8; while (p < b.length) { const id = b[p++]; let size; [size, p] = readU32LEB(b, p); const end = p + size; if (end > b.length) return null; if (id === 0) { let len, q; [len, q] = readU32LEB(b, p); if (q + len <= end && decodeMaybeShared2(b.subarray(q, q + len)) === "wasm.linux.soname") { return decodeMaybeShared2(b.subarray(q + len, end)); } } p = end; } } catch (_e) { } return null; } function dlopenLoadedBySoname(name2, placements, modules2, bytesOf) { if (!name2 || name2.includes("/")) return null; for (const np of placements) { if (!np || typeof np.name !== "string") continue; if (neededSoname(np.name) === name2) return { needed: np }; const bytes = bytesOf(np); if (bytes && wasmLinuxSoname(bytes) === name2) return { needed: np }; } for (const [cookie, m] of modules2) { if (!m || m.mainScope || !m.bytes) continue; if (m.name && neededSoname(m.name) === name2) return { cookie, module: m }; if (wasmLinuxSoname(m.bytes) === name2) return { cookie, module: m }; } return null; } function dlopenNeededEntry(placements, digest) { for (const np of placements) { if (np && np.digest === digest) return np; } return null; } function dlopenLibraryPresentIn(name2, placements, modules2, digestOf, sameSonameOk = null) { const digest = neededDigest(name2); const soname = neededSoname(name2); for (const np of placements) { if (np.name === name2 || np.digest === digest) return true; if (neededSoname(np.name) === soname) { if (sameSonameOk && sameSonameOk(np)) return true; return `this process loaded ${soname} ${np.digest.slice(0, 16)}\u2026 as a needed entry of its main, not ${digest.slice(0, 16)}\u2026` + (sameSonameOk ? ", and its interface as the needing module uses it differs" : ""); } } for (const m of modules2) { if (!m || m.mainScope || !m.bytes) continue; if (m.name === name2) return true; if (m.name && neededSoname(m.name) === soname) { if (sameSonameOk && sameSonameOk(m)) { m.boundByDependent = true; return true; } return `this process already loaded ${m.name} for another module` + (sameSonameOk ? ", and its interface as the needing module uses it differs" : ""); } if (!m.name) { if (m.digest === void 0) m.digest = digestOf(m.bytes); if (m.digest === digest) { m.boundByDependent = true; return true; } } } return false; } function dlopenRefs(m) { return m.refs !== void 0 ? m.refs >>> 0 : m.internal ? 0 : 1; } function dlopenTakeRef(m) { m.refs = dlopenRefs(m) + 1; } function dlcloseDropRef(m) { const n = dlopenRefs(m); if (n > 1 || m.internal && n === 1) { m.refs = n - 1; return true; } return false; } function neededPreemptible(name2) { if (name2.startsWith("__")) return false; return !NEEDED_STD_NAME.test(name2); } function neededEarlierProvider(name2, firstProvider, wantIndex, order) { if (firstProvider === void 0 || firstProvider === wantIndex) return void 0; if (!neededPreemptible(name2)) return void 0; const pj = order.get(firstProvider); const pw = order.get(wantIndex); return pj !== void 0 && pw !== void 0 && pj < pw ? firstProvider : void 0; } function neededGotPatchProvider(name2, o) { const fnOf = (x) => x && typeof x[name2] === "function" ? x[name2] : void 0; if (o.provider !== void 0) { const se = o.siblings.find((s) => s.index === o.provider); const f = se ? fnOf(se.exports) : void 0; return f ? { f, sibling: se } : null; } const m = fnOf(o.exp); if (m) return { f: m, sibling: null }; const own = fnOf(o.ownExp); if (own) return { f: own, sibling: null }; for (const se of o.siblings) { if (se.exports === o.ownExp) continue; const f = fnOf(se.exports); if (f) return { f, sibling: se }; } return null; } function dladdrObject(addr, objects, slot = () => null) { const list = [...objects]; for (const o of list) { if (addr >= o.memoryBase && addr < o.memoryBase + o.memorySize) return o; } for (const o of list) { if (addr >= o.tableBase && addr < o.tableBase + o.tableSize) return o; } for (const o of list) { if (o.tableIndices().includes(addr)) return o; } const fn2 = slot(addr); if (typeof fn2 === "function") { for (const o of list) { if (o.owns(fn2)) return o; } } return null; } function dladdrLibraryPaths(name2, known) { const paths = [ ...known ? [known] : [], ...neededLibraryPaths(name2), `/usr/local/lib/${neededSoname(name2)}` ]; return [...new Set(paths)]; } function neededLibraryPaths(name2) { const soname = neededSoname(name2); return [`/usr/lib/${name2}`, `/lib/${name2}`, `/usr/lib/${soname}`, `/lib/${soname}`]; } function dlopenSiblingDataAddress(name2, modules2) { if (name2.startsWith("__hwjs_") || name2.startsWith("__wasm_") || DLOPEN_SIBLING_DATA_RESERVED.has(name2)) return void 0; for (const mod of modules2) { const h = mod && mod.handle; if (!h || !h.exports || typeof h.dlsym !== "function") continue; if (!(h.exports[name2] instanceof WebAssembly.Global)) continue; const addr = h.dlsym(name2) >>> 0; if (addr !== 0) return addr; } return void 0; } function mainDataExportAddresses(bytes) { const b = bytes; const out = /* @__PURE__ */ new Map(); if (!b || b.length < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) { throw new Error("hwjs-libc: mainDataExportAddresses: not a wasm module (bad magic)"); } let p = 8; let numImportedGlobals = 0; const exportedGlobals = /* @__PURE__ */ new Map(); let gOff = -1, gEnd = -1; while (p < b.length) { const id = b[p++]; let size; [size, p] = readU32LEB(b, p); const end = p + size; if (id === 2) { let count; [count, p] = readU32LEB(b, p); for (let i = 0; i < count; i++) { let len; [len, p] = readU32LEB(b, p); p += len; [len, p] = readU32LEB(b, p); p += len; const kind = b[p++]; if (kind === 0) { [, p] = readU32LEB(b, p); } else if (kind === 1) { p += 1; p = skipLimits(b, p); } else if (kind === 2) { p = skipLimits(b, p); } else if (kind === 3) { p += 2; numImportedGlobals++; } else if (kind === 4) { p += 1; [, p] = readU32LEB(b, p); } } } else if (id === 7) { let count; [count, p] = readU32LEB(b, p); for (let i = 0; i < count; i++) { let len; [len, p] = readU32LEB(b, p); const nm2 = decodeMaybeShared2(b.subarray(p, p + len)); p += len; const kind = b[p++]; let idx; [idx, p] = readU32LEB(b, p); if (kind === 3) { const names = exportedGlobals.get(idx); if (names) names.push(nm2); else exportedGlobals.set(idx, [nm2]); } } } else if (id === 6) { gOff = p; gEnd = end; } p = end; } if (gOff < 0 || exportedGlobals.size === 0) return out; let gp = gOff; let gcount; [gcount, gp] = readU32LEB(b, gp); for (let i = 0; i < gcount && gp < gEnd; i++) { const valType = b[gp]; const mutable = b[gp + 1] !== 0; gp += 2; let value; if (b[gp] === 65 && valType === 127) { [value, gp] = readS32LEB(b, gp + 1, gEnd); if (b[gp] !== 11) value = void 0; } while (gp < gEnd && b[gp] !== 11) { const op = b[gp++]; if (op === 65 || op === 66) { [, gp] = readS32LEB(b, gp, gEnd); } else if (op === 67) { gp += 4; } else if (op === 68) { gp += 8; } else if (op === 35) { [, gp] = readU32LEB(b, gp); } } gp++; const names = exportedGlobals.get(numImportedGlobals + i); if (!names || mutable || value === void 0 || value >>> 0 === 0) continue; for (const nm2 of names) out.set(nm2, value >>> 0); } return out; } function interposingDataAddress(name2, mainData) { if (name2.startsWith("__hwjs_") || name2.startsWith("hwjs_") || name2.startsWith("__wasm") || DLOPEN_SIBLING_DATA_RESERVED.has(name2)) { return void 0; } const a = mainData ? mainData.get(name2) : void 0; return typeof a === "number" && a > 0 ? a : void 0; } function stripStartSection(bytes) { const b = bytes; if (b.length < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) { throw new Error("hwjs-dlopen: stripStartSection: not a wasm module (bad magic)"); } let p = 8; while (p < b.length) { const secStart = p; const id = b[p++]; let size; [size, p] = readU32LEB(b, p); const secEnd = p + size; if (id === 8) { const out = new Uint8Array(b.length - (secEnd - secStart)); out.set(b.subarray(0, secStart), 0); out.set(b.subarray(secEnd), secStart); return out; } p = secEnd; } return b; } function readS32LEB(b, p, end) { let result = 0, shift = 0, byte = 0; do { if (p >= end) throw new Error("hwjs-dlopen: truncated signed LEB in global init expr"); byte = b[p++]; result |= (byte & 127) << shift; shift += 7; } while (byte & 128); if (shift < 32 && byte & 64) result |= -1 << shift; return [result | 0, p]; } function skipLimits(b, p) { const flags = b[p++]; [, p] = readU32LEB(b, p); if (flags & 1) { [, p] = readU32LEB(b, p); } return p; } function findExportedI32Global(b, name2) { let p = 8; let numImportedGlobals = 0; let exportGlobalIndex = -1; let globalSectionOff = -1, globalSectionEnd = -1; while (p < b.length) { const id = b[p++]; let size; [size, p] = readU32LEB(b, p); const sectionStart = p; const sectionEnd = p + size; if (id === 2) { let count; [count, p] = readU32LEB(b, p); for (let i = 0; i < count; i++) { let len; [len, p] = readU32LEB(b, p); p += len; [len, p] = readU32LEB(b, p); p += len; const kind = b[p++]; if (kind === 0) { [, p] = readU32LEB(b, p); } else if (kind === 1) { p += 1; p = skipLimits(b, p); } else if (kind === 2) { p = skipLimits(b, p); } else if (kind === 3) { p += 2; numImportedGlobals++; } } } else if (id === 7) { let count; [count, p] = readU32LEB(b, p); for (let i = 0; i < count; i++) { let len; [len, p] = readU32LEB(b, p); const nm2 = decodeMaybeShared2(b.subarray(p, p + len)); p += len; const kind = b[p++]; let idx; [idx, p] = readU32LEB(b, p); if (kind === 3 && nm2 === name2) exportGlobalIndex = idx; } } else if (id === 6) { globalSectionOff = sectionStart; globalSectionEnd = sectionEnd; } p = sectionEnd; } if (exportGlobalIndex < 0) return { ok: false, why: "no-export" }; if (globalSectionOff < 0) return { ok: false, why: "no-global-section" }; const definedIndex = exportGlobalIndex - numImportedGlobals; let gp = globalSectionOff; let gcount; [gcount, gp] = readU32LEB(b, gp); if (definedIndex < 0 || definedIndex >= gcount) { return { ok: false, why: "out-of-range", exportGlobalIndex, definedIndex, gcount }; } for (let i = 0; i < gcount; i++) { const mutable = b[gp + 1] !== 0; gp += 2; if (i === definedIndex) { const op = b[gp++]; if (op !== 65) return { ok: false, why: "not-i32-const", op }; let val; [val, gp] = readS32LEB(b, gp, globalSectionEnd); return { ok: true, value: val >>> 0, mutable }; } while (gp < globalSectionEnd && b[gp] !== 11) { const op = b[gp++]; if (op === 65 || op === 66) { [, gp] = readS32LEB(b, gp, globalSectionEnd); } else if (op === 67) { gp += 4; } else if (op === 68) { gp += 8; } else if (op === 35) { [, gp] = readU32LEB(b, gp); } } gp++; } return { ok: false, why: "unreached" }; } function readExportedI32Global(wasmBytes, name2, who) { const b = wasmBytes; if (b.length < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) { throw new Error( `hwjs-dlopen: readExportedI32Global(${name2}) for ${who}: not a wasm module (bad magic)` ); } const r = findExportedI32Global(b, name2); if (r.ok) return r.value; throw new Error( `hwjs-dlopen: ${who} does not publish a readable i32 data offset for "${name2}" (${r.why}) -- a sibling GOT.mem binding needs the PROVIDER's link-time offset, and a defined -shared data export is an immutable i32 global with an i32.const init by construction (never-silent).` ); } function readHeapBase(wasmBytes) { const b = wasmBytes; if (b.length < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) { throw new Error("hwjs-rt: readHeapBase: not a wasm module (bad magic)"); } const r = findExportedI32Global(b, "__heap_base"); if (r.ok) return r.value; if (r.why === "no-export") { throw new Error("hwjs-rt: image does not export __heap_base (cannot derive the reserved rt window)"); } if (r.why === "no-global-section") { throw new Error("hwjs-rt: image has no global section (cannot read __heap_base)"); } if (r.why === "out-of-range") { throw new Error(`hwjs-rt: __heap_base global index ${r.exportGlobalIndex} (defined ${r.definedIndex}) out of range (${r.gcount} defined globals)`); } if (r.why === "not-i32-const") { throw new Error(`hwjs-rt: __heap_base init is opcode 0x${r.op.toString(16)}, expected i32.const (0x41)`); } throw new Error("hwjs-rt: __heap_base global not reached while walking the global section"); } function deriveHwjsRtWindowBase(wasmBytes) { return alignUp(readHeapBase(wasmBytes) + HWJS_RT_BRK_RESERVE, HWJS_RT_PAGE) >>> 0; } function readMainRootLayout(wasmBytes, initialSp = 0) { const b = wasmBytes; if (!b || b.length < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) { return { dataLo: 0, dataHi: 0, stackHi: 0 }; } const read = (n) => { const r = findExportedI32Global(b, n); return r.ok ? r.value >>> 0 : 0; }; const stackHi = read("__stack_pointer") || initialSp >>> 0; const dataHi = read("__data_end") || read("__heap_base"); const dataLo = stackHi && dataHi && stackHi <= dataHi ? stackHi : 0; return { dataLo, dataHi, stackHi }; } function initialStackPointer(exports) { const get2 = exports ? exports.__wasm32_get_stack_pointer : void 0; return typeof get2 === "function" ? get2() >>> 0 : 0; } function callerStackRegion(layout, threadStackTop = 0) { const top = threadStackTop >>> 0; if (top) return { hi: top, limit: 0 }; const hi = layout ? layout.stackHi >>> 0 : 0; return hi ? { hi, limit: 0 } : null; } function buildRootMap({ main = null, modules: modules2 = [], stacks = [], arena = [] }) { const out = []; if (main && main.dataHi > main.dataLo) { out.push({ kind: HWJS_ROOT_DATA, lo: main.dataLo >>> 0, hi: main.dataHi >>> 0, limit: 0 }); } for (const m of modules2) { const lo = m.memoryBase >>> 0, sz = m.memorySize >>> 0; if (lo && sz) out.push({ kind: HWJS_ROOT_DATA, lo, hi: lo + sz >>> 0, limit: 0 }); } const data = out.slice(); for (const s of stacks) { const hi = s.hi >>> 0, limit = s.limit >>> 0; if (!(hi > limit)) continue; const sp = s.sp >>> 0; const lo = sp >= limit && sp <= hi ? sp : limit; out.push({ kind: HWJS_ROOT_STACK, lo, hi, limit }); } for (const [base, end] of arena) { const lo = base >>> 0, hi = end >>> 0; if (!(hi > lo)) continue; if (data.some((d) => lo >= d.lo && hi <= d.hi)) continue; out.push({ kind: HWJS_ROOT_ARENA, lo, hi, limit: 0 }); } return out; } function writeRootMap(memoryBuffer, buf, cap, records) { const n = Math.max(0, Math.min(cap | 0, records.length)); const addr = buf >>> 0; if (n > 0) { if (addr === 0 || addr + n * HWJS_ROOT_RECORD_BYTES > memoryBuffer.byteLength) return -14; const dv = new DataView(memoryBuffer); for (let i = 0; i < n; i++) { const r = records[i], p = addr + i * HWJS_ROOT_RECORD_BYTES; dv.setUint32(p, r.kind >>> 0, true); dv.setUint32(p + 4, r.lo >>> 0, true); dv.setUint32(p + 8, r.hi >>> 0, true); dv.setUint32(p + 12, r.limit >>> 0, true); } } return records.length; } function skipDataOffsetExpr(b, p, end) { for (; ; ) { if (p >= end) throw new Error("hwjs-dlopen: readDataSegmentBytes: unterminated offset expression"); const op = b[p++]; if (op === 11) return p; if (op === 65 || op === 66) [, p] = readS32LEB(b, p, end); else if (op === 35) [, p] = readU32LEB(b, p); else if (!(op >= 106 && op <= 108 || op >= 124 && op <= 126)) { throw new Error( `hwjs-dlopen: readDataSegmentBytes: opcode 0x${op.toString(16)} in a data segment's offset expression (never-silent)` ); } } } function dataSectionSegmentBytes2(b, p, end) { let count, total = 0; [count, p] = readU32LEB(b, p); for (let i = 0; i < count; i++) { let flags, len; [flags, p] = readU32LEB(b, p); if (flags === 2) [, p] = readU32LEB(b, p); if (flags === 0 || flags === 2) p = skipDataOffsetExpr(b, p, end); else if (flags !== 1) { throw new Error(`hwjs-dlopen: readDataSegmentBytes: segment ${i} has flags ${flags} (never-silent)`); } [len, p] = readU32LEB(b, p); p += len; if (p > end) throw new Error(`hwjs-dlopen: readDataSegmentBytes: segment ${i} runs past the data section`); total += len; } return total; } function readDataSegmentBytes(bytes) { const b = bytes, end = b.length; if (end < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) { throw new Error("hwjs-dlopen: readDataSegmentBytes: not a wasm module (bad magic)"); } const retained = retainedLibraryInfo2(b) !== null; let p = 8; while (p < end) { const id = b[p++]; let size; [size, p] = readU32LEB(b, p); const secEnd = p + size; if (secEnd > end) throw new Error("hwjs-dlopen: readDataSegmentBytes: a section runs past the module"); if (id === 11) return dataSectionSegmentBytes2(b, p, secEnd); if (id === 0 && retained && size === RETAINED_DATA_BYTES2 - 2 && b[p] === RETAINED_DATA_NAME2.length) { let q = p + 1, named = true; for (let i = 0; i < RETAINED_DATA_NAME2.length; i++) { if (b[q + i] !== RETAINED_DATA_NAME2.charCodeAt(i)) { named = false; break; } } q += RETAINED_DATA_NAME2.length; if (named) return (b[q] | b[q + 1] << 8 | b[q + 2] << 16 | b[q + 3] << 24) >>> 0; } p = secEnd; } return 0; } function deriveHwjsLibcWindowBase(wasmBytes) { return deriveHwjsRtWindowBase(wasmBytes) + HWJS_RT_WINDOW_SIZE >>> 0; } function sha256HexJs(data) { const H = new Uint32Array([ 1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225 ]); const len = data.length; const bitLenHi = Math.floor(len / 536870912); const bitLenLo = len << 3 >>> 0; const whole = len - len % 64; const tail = new Uint8Array((len - whole + 8 >> 6) + 1 << 6); tail.set(data.subarray(whole)); tail[len - whole] = 128; const tailDv = new DataView(tail.buffer); tailDv.setUint32(tail.length - 8, bitLenHi, false); tailDv.setUint32(tail.length - 4, bitLenLo, false); const dataDv = new DataView(data.buffer, data.byteOffset, data.byteLength); const w = new Uint32Array(64); for (let at = 0; at < whole + tail.length; at += 64) { const dv = at < whole ? dataDv : tailDv; const off = at < whole ? at : at - whole; for (let i = 0; i < 16; i++) w[i] = dv.getUint32(off + i * 4, false); for (let i = 16; i < 64; i++) { const x = w[i - 15], y = w[i - 2]; const s0 = (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ x >>> 3; const s1 = (y >>> 17 | y << 15) ^ (y >>> 19 | y << 13) ^ y >>> 10; w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0; } let a = H[0], b2 = H[1], c = H[2], d = H[3]; let e = H[4], f = H[5], g = H[6], h = H[7]; for (let i = 0; i < 64; i++) { const S1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7); const ch = e & f ^ ~e & g; const t1 = h + S1 + ch + SHA256_K[i] + w[i] >>> 0; const S0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10); const maj = a & b2 ^ a & c ^ b2 & c; const t2 = S0 + maj >>> 0; h = g; g = f; f = e; e = d + t1 >>> 0; d = c; c = b2; b2 = a; a = t1 + t2 >>> 0; } H[0] = H[0] + a >>> 0; H[1] = H[1] + b2 >>> 0; H[2] = H[2] + c >>> 0; H[3] = H[3] + d >>> 0; H[4] = H[4] + e >>> 0; H[5] = H[5] + f >>> 0; H[6] = H[6] + g >>> 0; H[7] = H[7] + h >>> 0; } let out = ""; for (let i = 0; i < 8; i++) out += H[i].toString(16).padStart(8, "0"); return out; } function sha256WasmBytes() { const N = 0, P = 1, END = 2, T1 = 3, T2 = 4, TMP = 5; const V = 6, H = 14, W = 22; const NLOCALS = W + 16 - 1; const code2 = []; const leb2 = (out, v2) => { for (; ; ) { const byte = v2 & 127; v2 >>= 7; if (v2 === 0 && !(byte & 64) || v2 === -1 && byte & 64) { out.push(byte); return; } out.push(byte | 128); } }; const uleb = (out, v2) => { do { let byte = v2 & 127; v2 >>>= 7; if (v2) byte |= 128; out.push(byte); } while (v2); }; const get2 = (l) => { code2.push(32); uleb(code2, l); }; const set = (l) => { code2.push(33); uleb(code2, l); }; const tee = (l) => { code2.push(34); uleb(code2, l); }; const k = (v2) => { code2.push(65); leb2(code2, v2 | 0); }; const op = (...o) => code2.push(...o); const ADD = 106, AND = 113, OR = 114, XOR = 115, SHL = 116, SHRU = 118, ROTL = 119, ROTR = 120, GEU = 79; const LOAD = (off) => { op(40, 2); uleb(code2, off); }; const STORE = (off) => { op(54, 2); uleb(code2, off); }; const rotr = (l, n) => { get2(l); k(n); op(ROTR); }; const shr = (l, n) => { get2(l); k(n); op(SHRU); }; const sig = (l, a, b, c, last) => { rotr(l, a); rotr(l, b); op(XOR); (last ? shr : rotr)(l, c); op(XOR); }; get2(N); k(6); op(SHL); set(END); for (let i = 0; i < 8; i++) { k(0); LOAD(SHA256_WASM_CHUNK + 4 * i); set(H + i); } op(2, 64, 3, 64); get2(P); get2(END); op(GEU, 13, 1); for (let i = 0; i < 8; i++) { get2(H + i); set(V + i); } let v = [0, 1, 2, 3, 4, 5, 6, 7].map((i) => V + i); for (let t = 0; t < 64; t++) { const w = W + (t & 15); if (t < 16) { get2(P); LOAD(4 * t); tee(TMP); k(8); op(ROTR); k(4278255360); op(AND); get2(TMP); k(8); op(ROTL); k(16711935); op(AND, OR); set(w); } else { get2(w); sig(W + (t - 15 & 15), 7, 18, 3, true); op(ADD); get2(W + (t - 7 & 15)); op(ADD); sig(W + (t - 2 & 15), 17, 19, 10, true); op(ADD); set(w); } const [a, b, c, d, e, f, g, h] = v; get2(h); sig(e, 6, 11, 25, false); op(ADD); get2(g); get2(e); get2(f); get2(g); op(XOR, AND, XOR, ADD); k(SHA256_K[t]); op(ADD); get2(w); op(ADD); set(T1); sig(a, 2, 13, 22, false); get2(a); get2(b); op(AND); get2(c); get2(a); get2(b); op(OR, AND, OR, ADD); set(T2); get2(d); get2(T1); op(ADD); set(d); get2(T1); get2(T2); op(ADD); set(h); v = [h, a, b, c, d, e, f, g]; } for (let i = 0; i < 8; i++) { get2(H + i); get2(V + i); op(ADD); set(H + i); } get2(P); k(64); op(ADD); set(P); op(12, 0, 11, 11); for (let i = 0; i < 8; i++) { k(0); get2(H + i); STORE(SHA256_WASM_CHUNK + 4 * i); } op(11); const body = [1]; uleb(body, NLOCALS); body.push(127, ...code2); const section2 = (id, bytes) => { const out = [id]; uleb(out, bytes.length); out.push(...bytes); return out; }; const codeSec = [1]; uleb(codeSec, body.length); codeSec.push(...body); const pages2 = SHA256_WASM_CHUNK + 32 + 65535 >>> 16; return new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, ...section2(1, [1, 96, 1, 127, 0]), ...section2(3, [1, 0]), ...section2(5, [1, 0, pages2]), ...section2(7, [2, 1, 109, 2, 0, 1, 98, 0, 0]), ...section2(10, codeSec) ]); } function sha256WasmInstance() { if (wasmSha256 !== void 0) return wasmSha256; wasmSha256 = null; try { const inst = new WebAssembly.Instance( new WebAssembly.Module(sha256WasmBytes()), {} ); wasmSha256 = { mem: inst.exports.m, b: inst.exports.b }; if (sha256HexWasm(new Uint8Array([97, 98, 99])) !== SHA256_ABC) { wasmSha256 = null; } } catch (_e) { wasmSha256 = null; } return wasmSha256; } function sha256HexWasm(data) { const run2 = sha256WasmInstance(); if (!run2) return null; const mem = new Uint8Array(run2.mem.buffer); const state = new DataView(run2.mem.buffer, SHA256_WASM_CHUNK, 32); const IV = [ 1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225 ]; for (let i = 0; i < 8; i++) state.setUint32(4 * i, IV[i], true); const len = data.length; const whole = len - len % 64; for (let at = 0; at < whole; at += SHA256_WASM_CHUNK) { const n = Math.min(SHA256_WASM_CHUNK, whole - at); mem.set(data.subarray(at, at + n), 0); run2.b(n >>> 6); } const tailLen = (len - whole + 8 >> 6) + 1 << 6; mem.fill(0, 0, tailLen); mem.set(data.subarray(whole), 0); mem[len - whole] = 128; const tail = new DataView(run2.mem.buffer, 0, tailLen); tail.setUint32(tailLen - 8, Math.floor(len / 536870912), false); tail.setUint32(tailLen - 4, len << 3 >>> 0, false); run2.b(tailLen >>> 6); let out = ""; for (let i = 0; i < 8; i++) { out += state.getUint32(4 * i, true).toString(16).padStart(8, "0"); } return out; } function hostSha256Hex() { if (hostSha256 !== void 0) return hostSha256; hostSha256 = null; try { const crypto = globalThis.process?.getBuiltinModule?.("node:crypto"); if (crypto && typeof crypto.createHash === "function") { const hash = (data) => crypto.createHash("sha256").update(data).digest("hex"); const abc = new Uint8Array(typeof SharedArrayBuffer === "function" ? new SharedArrayBuffer(3) : 3); abc.set([97, 98, 99]); if (hash(abc) === SHA256_ABC) hostSha256 = hash; } } catch (_e) { } return hostSha256; } function sha256Hex(data) { const host = hostSha256Hex(); if (host) return host(data); return sha256HexWasm(data) ?? sha256HexJs(data); } function retainedLibraryInfo2(bytes) { const n = bytes ? bytes.length : 0; if (n < 8 + RETAINED_MARKER_BYTES2) return null; let p = n - RETAINED_MARKER_BYTES2; if (bytes[p] !== 0 || bytes[p + 1] !== RETAINED_MARKER_BYTES2 - 2 || bytes[p + 2] !== RETAINED_NAME2.length) return null; p += 3; for (let i = 0; i < RETAINED_NAME2.length; i++) { if (bytes[p + i] !== RETAINED_NAME2.charCodeAt(i)) return null; } p += RETAINED_NAME2.length; const wireLength = (bytes[p] | bytes[p + 1] << 8 | bytes[p + 2] << 16 | bytes[p + 3] << 24) >>> 0; let digest = ""; for (let i = 0; i < 32; i++) digest += bytes[p + 4 + i].toString(16).padStart(2, "0"); return { wireLength, digest }; } function scanTableWrites2(b, detail = null) { const n = b.length; const stop = (verdict, op, at) => { if (detail) { detail.op = op; detail.at = at; } return verdict; }; if (n < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) return stop("unknown", "not wasm", 0); let p = 8; const u = () => { let r = 0, s = 0, x; do { if (p >= n) throw new RangeError("truncated"); x = b[p++]; r += (x & 127) * 2 ** s; s += 7; } while (x & 128); return r; }; const skip = () => { for (; ; ) { if (p >= n) throw new RangeError("truncated"); if (!(b[p++] & 128)) return; } }; const memarg = () => { const a = u(); if (a & 64) skip(); skip(); }; const valtype = () => { const x = b[p++]; if (x === 99 || x === 100) skip(); }; const blocktype = () => { const x = b[p]; if (x === 99 || x === 100) { p++; skip(); return; } if (x >= 64 && x <= 127) { p++; return; } skip(); }; try { let codeStart = -1, codeEnd = -1; while (p < n) { const id = b[p++]; const size = u(); const end = p + size; if (end > n) return stop("unknown", "section past the end", p); if (id === 10) { codeStart = p; codeEnd = end; break; } p = end; } if (codeStart < 0) return "none"; p = codeStart; const count = u(); for (let f = 0; f < count; f++) { const size = u(); const bodyEnd = p + size; if (bodyEnd > codeEnd) return stop("unknown", "body past the code", p); const groups = u(); for (let g = 0; g < groups; g++) { skip(); valtype(); } let depth = 1; while (p < bodyEnd) { const at = p; const op = b[p++]; if (op === 11) { if (--depth === 0) break; continue; } if (op <= 1 || op === 5 || op === 10 || op === 15 || op === 25 || op === 26 || op === 27 || op >= 69 && op <= 196 || op === 209 || op === 211 || op === 212) continue; if (op === 2 || op === 3 || op === 4 || op === 6) { blocktype(); depth++; continue; } if (op === 31) { blocktype(); depth++; const c = u(); for (let i = 0; i < c; i++) { const k = b[p++]; if (k === 0 || k === 1) skip(); skip(); } continue; } if (op === 24) { skip(); depth--; continue; } if (op === 7 || op === 8 || op === 9 || op === 12 || op === 13 || op === 16 || op === 18 || op === 20 || op === 21 || op >= 32 && op <= 37 || op === 210 || op === 213 || op === 214 || op === 63 || op === 64 || op === 65 || op === 66) { skip(); continue; } if (op === 14) { const c = u(); for (let i = 0; i <= c; i++) skip(); continue; } if (op === 17 || op === 19) { skip(); skip(); continue; } if (op === 28) { const c = u(); for (let i = 0; i < c; i++) valtype(); continue; } if (op === 38) return stop("writes", "0x26", at); if (op >= 40 && op <= 62) { memarg(); continue; } if (op === 67) { p += 4; continue; } if (op === 68) { p += 8; continue; } if (op === 208) { const x = b[p]; if (x >= 64 && x <= 127) p++; else skip(); continue; } if (op === 251) { const s = u(); if (s <= 1 || s === 6 || s === 7 || s >= 11 && s <= 14 || s === 16) { skip(); continue; } if (s >= 2 && s <= 5 || s >= 8 && s <= 10 || s >= 17 && s <= 19) { skip(); skip(); continue; } if (s === 15 || s >= 26 && s <= 30) continue; if (s >= 20 && s <= 23) { skip(); continue; } if (s === 24 || s === 25) { p += 1; skip(); skip(); skip(); continue; } return stop("unknown", `0xfb ${s}`, at); } if (op === 252) { const s = u(); if (s <= 7) continue; if (s === 8 || s === 10) { skip(); skip(); continue; } if (s === 9 || s === 11 || s === 13 || s === 16) { skip(); continue; } if (s === 12 || s === 14 || s === 15 || s === 17) return stop("writes", `0xfc ${s}`, at); return stop("unknown", `0xfc ${s}`, at); } if (op === 253) { const s = u(); if (s <= 11 || s === 92 || s === 93) { memarg(); continue; } if (s === 12 || s === 13) { p += 16; continue; } if (s >= 21 && s <= 34) { p += 1; continue; } if (s >= 84 && s <= 91) { memarg(); p += 1; continue; } if (s <= 275) continue; return stop("unknown", `0xfd ${s}`, at); } if (op === 254) { const s = u(); if (s === 3) { p += 1; continue; } if (s <= 78) { memarg(); continue; } return stop("unknown", `0xfe ${s}`, at); } return stop("unknown", `0x${op.toString(16)}`, at); } if (depth !== 0 || p !== bodyEnd) return stop("unknown", "body end", p); } return p === codeEnd ? "none" : stop("unknown", "code end", p); } catch (_e) { return stop("unknown", "truncated", p); } } function tableWritesOfBytes(bytes) { if (!retainedLibraryInfo2(bytes) || hasCodeSection(bytes)) return scanTableWrites2(bytes); const p = bytes.length - RETAINED_MARKER_BYTES2 - TABLE_WRITES_BYTES2; if (p < 8 || bytes[p] !== 0 || bytes[p + 1] !== TABLE_WRITES_BYTES2 - 2 || bytes[p + 2] !== TABLE_WRITES_NAME2.length) return "unknown"; for (let i = 0; i < TABLE_WRITES_NAME2.length; i++) { if (bytes[p + 3 + i] !== TABLE_WRITES_NAME2.charCodeAt(i)) return "unknown"; } return TABLE_WRITES_CODES2[bytes[p + 3 + TABLE_WRITES_NAME2.length]] ?? "unknown"; } function segmentsAtTableBase(b) { let importedFns = 0; let importedGlobals = 0; let tableBaseGlobal = -1; let p = 8; try { while (p < b.length) { const id = b[p++]; let size; [size, p] = readU32LEB(b, p); const sectionEnd = p + size; if (id === 2) { let count; [count, p] = readU32LEB(b, p); for (let i = 0; i < count; i++) { let len; [len, p] = readU32LEB(b, p); const mod = decodeMaybeShared2(b.subarray(p, p + len)); p += len; [len, p] = readU32LEB(b, p); const fld = decodeMaybeShared2(b.subarray(p, p + len)); p += len; const kind = b[p++]; if (kind === 0) { [, p] = readU32LEB(b, p); importedFns++; } else if (kind === 1) { p += 1; const f = b[p++]; [, p] = readU32LEB(b, p); if (f & 1) { [, p] = readU32LEB(b, p); } } else if (kind === 2) { const f = b[p++]; [, p] = readU32LEB(b, p); if (f & 1) { [, p] = readU32LEB(b, p); } } else if (kind === 3) { if (mod === "env" && fld === "__table_base") tableBaseGlobal = importedGlobals; importedGlobals++; p += 2; } else return false; } } else if (id === 9) { let count; [count, p] = readU32LEB(b, p); for (let s = 0; s < count; s++) { let flags; [flags, p] = readU32LEB(b, p); if (flags !== 0 && flags !== 2) return false; if (flags === 2) { let t; [t, p] = readU32LEB(b, p); if (t !== 0) return false; } if (b[p++] !== 35) return false; let g; [g, p] = readU32LEB(b, p); if (tableBaseGlobal < 0 || g !== tableBaseGlobal) return false; if (b[p++] !== 11) return false; if (flags === 2 && b[p++] !== 0) return false; let n; [n, p] = readU32LEB(b, p); for (let i = 0; i < n; i++) { let fi; [fi, p] = readU32LEB(b, p); if (fi < importedFns) return false; } } return true; } p = sectionEnd; } return true; } catch (_e) { return false; } } function segmentsAtTableBaseOf(module, bytes) { const f = moduleKeptOf(module); return f.segmentsAtTableBase ?? (f.segmentsAtTableBase = segmentsAtTableBase(bytes)); } function tableWritesOf(module, bytes) { const f = moduleKeptOf(module); return f.tableWrites ?? (f.tableWrites = tableWritesOfBytes(bytes)); } function hasCodeSection(b) { let p = 8; while (p < b.length) { const id = b[p++]; let size = 0, mul = 1, x; do { if (p >= b.length) return true; x = b[p++]; size += (x & 127) * mul; mul *= 128; } while (x & 128); if (id === 10) return true; p += size; } return false; } function isCustomSectionNamed2(bytes, p, end, name2) { if (bytes[p] !== 0) return false; let q = p + 1; while (q < end && bytes[q] & 128) q++; q++; if (q >= end || bytes[q] !== name2.length) return false; for (let i = 0; i < name2.length; i++) { if (bytes[q + 1 + i] !== name2.charCodeAt(i)) return false; } return true; } function retainedLibraryBytes2(bytes, digest, walkStop = null) { if (!/^[0-9a-f]{64}$/.test(digest)) { throw new Error(`hwjs-libc: retained copy: ${JSON.stringify(String(digest).slice(0, 80))} is not a SHA-256 (never-silent)`); } const n = bytes.length; if (n < 8 || bytes[0] !== 0 || bytes[1] !== 97 || bytes[2] !== 115 || bytes[3] !== 109) { throw new Error(`hwjs-libc: retained copy: ${digest.slice(0, 16)}\u2026 is not a wasm module (never-silent)`); } if (retainedLibraryInfo2(bytes)) { throw new Error(`hwjs-libc: retained copy: ${digest.slice(0, 16)}\u2026 is a retained copy already (never-silent)`); } const keep = [[0, 8]]; let kept = 8; let dropped = 0; let dataBytes = null; let p = 8; while (p < n) { const id = bytes[p]; let q = p + 1; let size = 0; let mul = 1; for (; ; ) { if (q >= n) { throw new Error(`hwjs-libc: retained copy: ${digest.slice(0, 16)}\u2026: the section header at ${p} runs past the module (never-silent)`); } const b = bytes[q++]; size += (b & 127) * mul; mul *= 128; if (!(b & 128)) break; } const end = q + size; if (end > n) { throw new Error(`hwjs-libc: retained copy: ${digest.slice(0, 16)}\u2026: section ${id} at ${p} declares ${size}B, past the module's ${n}B (never-silent)`); } if (id === 11) dataBytes = dataSectionSegmentBytes2(bytes, q, end); if (id === 10 || id === 11) { dropped += end - p; } else if (isCustomSectionNamed2(bytes, p, end, TABLE_WRITES_NAME2)) { } else { keep.push([p, end]); kept += end - p; } p = end; } if (dropped === 0) { const whole = new Uint8Array(new SharedArrayBuffer(n)); whole.set(bytes); return whole; } const dataRecord = dataBytes === null ? 0 : RETAINED_DATA_BYTES2; const out = new Uint8Array(new SharedArrayBuffer( kept + dataRecord + TABLE_WRITES_BYTES2 + RETAINED_MARKER_BYTES2 )); let at = 0; for (const [from, to] of keep) { out.set(bytes.subarray(from, to), at); at += to - from; } if (dataBytes !== null) { out[at++] = 0; out[at++] = RETAINED_DATA_BYTES2 - 2; out[at++] = RETAINED_DATA_NAME2.length; for (let i = 0; i < RETAINED_DATA_NAME2.length; i++) out[at++] = RETAINED_DATA_NAME2.charCodeAt(i); out[at++] = dataBytes & 255; out[at++] = dataBytes >>> 8 & 255; out[at++] = dataBytes >>> 16 & 255; out[at++] = dataBytes >>> 24 & 255; } out[at++] = 0; out[at++] = TABLE_WRITES_BYTES2 - 2; out[at++] = TABLE_WRITES_NAME2.length; for (let i = 0; i < TABLE_WRITES_NAME2.length; i++) out[at++] = TABLE_WRITES_NAME2.charCodeAt(i); const walked = scanTableWrites2(bytes, walkStop); if (walkStop) walkStop.verdict = walked; out[at++] = TABLE_WRITES_CODES2.indexOf(walked); out[at++] = 0; out[at++] = RETAINED_MARKER_BYTES2 - 2; out[at++] = RETAINED_NAME2.length; for (let i = 0; i < RETAINED_NAME2.length; i++) out[at++] = RETAINED_NAME2.charCodeAt(i); out[at++] = n & 255; out[at++] = n >>> 8 & 255; out[at++] = n >>> 16 & 255; out[at++] = n >>> 24 & 255; for (let i = 0; i < 32; i++) out[at++] = parseInt(digest.slice(i * 2, i * 2 + 2), 16); return out; } function sharedLibWireLength(bytes) { const kept = retainedLibraryInfo2(bytes); return kept ? kept.wireLength : bytes.length; } function mergeSharedLib(prev, e) { const bytes = e.bytes instanceof Uint8Array ? e.bytes : new Uint8Array(e.bytes); const kept = retainedLibraryInfo2(bytes); if (kept && kept.digest !== e.digest) { throw new Error( `hwjs-libc: shared-lib delivery for digest ${e.digest} carries the retained copy of ${kept.digest} (never-silent)` ); } if (kept && !e.module && !(prev && prev.module)) { throw new Error( `hwjs-libc: shared-lib delivery for digest ${e.digest} is a retained copy (${bytes.length}B of ${kept.wireLength}B) with no Module \u2014 a retained copy holds no code and is only kept beside its Module (never-silent)` ); } if (!prev) return { bytes, ...e.module ? { module: e.module } : {} }; const prevLen = sharedLibWireLength(prev.bytes); const len = kept ? kept.wireLength : bytes.length; if (prevLen !== len) { throw new Error( `hwjs-libc: shared-lib re-delivery for digest ${e.digest} with DIFFERENT bytes (${prevLen} vs ${len}) \u2014 content-addressed delivery can never disagree (never-silent)` ); } if (!prev.module && e.module) prev.module = e.module; if (kept && !retainedLibraryInfo2(prev.bytes)) prev.bytes = bytes; return prev; } function threadBlockPlan(init, firstImage) { const mode = init ? init.mode : void 0; if (mode === "thread") return { kind: "attach" }; if (firstImage && mode === "migrate-resume" && init.tcb >>> 0 !== 0) { return { kind: "bind", tcb: init.tcb >>> 0 }; } if (firstImage && mode === "fork-resume" && init.forkTcb >>> 0 !== 0) { return { kind: "bind", tcb: init.forkTcb >>> 0 }; } return { kind: "initial" }; } function refillExpiredBudgets(globals, mainExports, value) { let n = 0; for (const g of globals) { try { if ((g.value | 0) === 0) { g.value = value | 0; n++; } } catch (_e) { } } if (mainExports && typeof mainExports.__hwjs_budget_get === "function" && typeof mainExports.__hwjs_budget_set === "function" && (mainExports.__hwjs_budget_get() | 0) === 0) { mainExports.__hwjs_budget_set(value | 0); n++; } return n; } function driveEntryImport(n, f, refill) { if (typeof f !== "function" || !RT_DRIVE_ENTRY_OPS.has(n)) return f; return (...a) => { refill(); return f(...a); }; } function terminusHookImport(mainExports, rtFn) { return (exc) => { const m = mainExports(); const f = m ? m[TERMINUS_HOOK] : void 0; return (typeof f === "function" ? f : rtFn)(exc); }; } function checkLibcReplayRecord(replay, neededDigest2) { if (replay && typeof replay === "object" && "bytes" in replay) { throw new Error( "hwjs-libc: the fork payload carries libc.so BYTES \u2014 the D4 fork rule is placement-record-only (a bash fork storm would clone GBs; PLAN-DYNAMIC-LIBC \xA73.4). Corrupt payload; refusing (never-silent)." ); } if (String(replay.digest) !== neededDigest2) { throw new Error( `hwjs-libc: fork-replay digest ${String(replay.digest).slice(0, 16)}\u2026 != the boot image's needed digest ${neededDigest2.slice(0, 16)}\u2026 \u2014 the recorded placement is for a different libc.so generation (never-silent).` ); } } function parseSideModuleNeeded(bytes) { const b = bytes; if (b.length < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) { throw new Error("hwjs-dlopen: parseSideModuleNeeded: not a wasm module (bad magic)"); } let payload = null; let count = 0; let p = 8; while (p < b.length) { const id = b[p++]; let size; [size, p] = readU32LEB(b, p); const sectionEnd = p + size; if (id === 0) { let nameLen, np = p; [nameLen, np] = readU32LEB(b, np); if (decodeMaybeShared2(b.subarray(np, np + nameLen)) === "wasm.linux.needed") { count++; payload = b.subarray(np + nameLen, sectionEnd); } } p = sectionEnd; } if (count === 0) return []; if (count > 1) { throw new Error(`hwjs-dlopen: ${count} wasm.linux.needed sections on a side module \u2014 one needed list per module (never-silent)`); } let parsed; try { parsed = JSON.parse(decodeMaybeShared2(payload)); } catch (e) { throw new Error("hwjs-dlopen: malformed side-module wasm.linux.needed (not JSON): " + (e instanceof Error ? e.message : String(e)) + " (never-silent)"); } if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.needed)) { throw new Error('hwjs-dlopen: side-module wasm.linux.needed shape mismatch \u2014 want {"needed":[...]} (never-silent)'); } const names = neededRecordNames(parsed, "hwjs-dlopen: side-module", false); const seen = /* @__PURE__ */ new Set(); names.forEach((n, i) => { if (n.length > 127 || /^libc\.so\./.test(n) || seen.has(n)) { throw new Error(`hwjs-dlopen: side-module wasm.linux.needed entry ${i} ${JSON.stringify(n)} is not a distinct digest-qualified library name other than libc.so (never-silent)`); } seen.add(n); }); const out = [...names]; if (Array.isArray(parsed.view) && Array.isArray(parsed.sha256)) { out.views = new Map(names.map((n, i) => [n, parsed.view[i]])); } const runpath = neededRecordRunPath(parsed, "hwjs-dlopen: side-module"); if (runpath.length) out.runpath = runpath; return out; } function neededRecordNames(parsed, who, main) { const v2 = Array.isArray(parsed.sha256); if (!v2) { parsed.needed.forEach((n, i) => { if (typeof n !== "string" || !/^[0-9A-Za-z._+-]+\.[0-9a-f]{64}$/.test(n)) { throw new Error( `${who} wasm.linux.needed entry ${i} ${JSON.stringify(n)} is not a digest-qualified library name (want . over [0-9A-Za-z._+-]; never-silent refuse)` ); } }); return [...parsed.needed]; } if (parsed.v !== 2 || parsed.sha256.length !== parsed.needed.length || !Array.isArray(parsed.view) || parsed.view.length !== parsed.needed.length) { throw new Error( `${who} wasm.linux.needed version-2 record is malformed \u2014 want "v":2 and needed, sha256 and view arrays of one length (never-silent refuse)` ); } return parsed.needed.map((n, i) => { const h = parsed.sha256[i], v = parsed.view[i]; if (typeof h !== "string" || !/^[0-9a-f]{64}$/.test(h)) { throw new Error(`${who} wasm.linux.needed sha256[${i}] ${JSON.stringify(h)} is not a sha256 hex digest (never-silent refuse)`); } if (typeof n === "string" && n.endsWith("." + h) && /^[0-9A-Za-z._+-]+\.[0-9a-f]{64}$/.test(n)) { if (typeof v !== "string" || v !== "" && !/^[0-9a-f]{64}$/.test(v)) { throw new Error(`${who} wasm.linux.needed view[${i}] is not empty or a sha256 hex digest (never-silent refuse)`); } return n; } if (typeof n !== "string" || !/^[0-9A-Za-z_+-][0-9A-Za-z._+-]*$/.test(n) || /\.[0-9a-f]{64}$/.test(n)) { throw new Error( `${who} wasm.linux.needed entry ${i} ${JSON.stringify(n)} is not a soname (want one path component over [0-9A-Za-z._+-], not starting with '.', without a digest tail; never-silent refuse)` ); } if (typeof v !== "string" || !/^[0-9a-f]{64}$/.test(v) || main && i === 0) { throw new Error(`${who} wasm.linux.needed view[${i}] of ${JSON.stringify(n)} is not a sha256 hex digest (never-silent refuse)`); } return `${n}.${h}`; }); } function neededViewReader(b, p, end) { const r = { p, byte() { if (r.p >= end) throw new Error("truncated module"); return b[r.p++]; }, leb() { let v = 0, m = 1, x; do { x = r.byte(); v += (x & 127) * m; m *= 128; } while (x & 128); return v; }, raw() { const s = r.p; let x; do { x = r.byte(); } while (x & 128); let h = ""; for (let i = s; i < r.p; i++) h += b[i].toString(16).padStart(2, "0"); return h; }, str() { const n = r.leb(); if (r.p + n > end) throw new Error("truncated name"); let s = ""; for (let i = r.p; i < r.p + n; i++) s += String.fromCharCode(b[i]); r.p += n; return s; }, valtype() { const t = r.byte(); if (t === 99 || t === 100) return t.toString(16) + ":" + r.raw(); return t.toString(16); }, limits() { const f = r.leb(); r.leb(); if (f & 1) r.leb(); } }; return r; } function neededViewSections(b) { if (b.length < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) { throw new Error("not a wasm module (bad magic)"); } const out = []; const r = neededViewReader(b, 8, b.length); while (r.p < b.length) { const id = r.byte(); const size = r.leb(); const start = r.p, end = start + size; if (end > b.length) throw new Error("a section runs past the end of the module"); let name2 = null, body = start; if (id === 0) { const c = neededViewReader(b, start, end); name2 = c.str(); body = c.p; } out.push({ id, name: name2, body, end }); r.p = end; } return out; } function neededViewImports(b) { const names = /* @__PURE__ */ new Set(); for (const s of neededViewSections(b)) { if (s.id !== 2) continue; const r = neededViewReader(b, s.body, s.end); for (let n = r.leb(); n > 0; n--) { const mod = r.str(), field = r.str(), kind = r.byte(); if (kind === 0) r.leb(); else if (kind === 1) { r.valtype(); r.limits(); } else if (kind === 2) r.limits(); else if (kind === 3) { r.valtype(); r.byte(); } else if (kind === 4) { r.byte(); r.leb(); } else throw new Error("unknown import kind " + kind); if (NEEDED_VIEW_IMPORT_MODULES.has(mod)) names.add(field); } } return names; } function neededViewSurface(b) { let types = [], fnNames = null; const funcTypes = [], exports = []; for (const s of neededViewSections(b)) { const r = neededViewReader(b, s.body, s.end); if (s.id === 1) { for (let n = r.leb(); n > 0 && types; n--) { if (r.byte() !== 96) { types = null; break; } const ps = [], rs = []; for (let k = r.leb(); k > 0; k--) ps.push(r.valtype()); for (let k = r.leb(); k > 0; k--) rs.push(r.valtype()); types.push("(" + ps.join(",") + ")->(" + rs.join(",") + ")"); } } else if (s.id === 2) { for (let n = r.leb(); n > 0; n--) { r.str(); r.str(); const kind = r.byte(); if (kind === 0) funcTypes.push(r.leb()); else if (kind === 1) { r.valtype(); r.limits(); } else if (kind === 2) r.limits(); else if (kind === 3) { r.valtype(); r.byte(); } else if (kind === 4) { r.byte(); r.leb(); } else throw new Error("unknown import kind " + kind); } } else if (s.id === 3) { for (let n = r.leb(); n > 0; n--) funcTypes.push(r.leb()); } else if (s.id === 7) { for (let n = r.leb(); n > 0; n--) { const name2 = r.str(), kind = r.byte(), index = r.leb(); exports.push({ name: name2, kind, index }); } } else if (s.id === 0 && s.name === "name") { fnNames = /* @__PURE__ */ new Map(); while (r.p < s.end) { const sub = r.byte(), size = r.leb(), se = r.p + size; if (sub === 1) { for (let n = r.leb(); n > 0; n--) { const i = r.leb(); fnNames.set(i, r.str()); } } r.p = se; } } } const globalTypes = []; for (const s of neededViewSections(b)) { if (s.id === 2) { const r = neededViewReader(b, s.body, s.end); for (let n = r.leb(); n > 0; n--) { r.str(); r.str(); const kind = r.byte(); if (kind === 0) r.leb(); else if (kind === 1) { r.valtype(); r.limits(); } else if (kind === 2) r.limits(); else if (kind === 3) globalTypes.push(r.valtype() + (r.byte() ? "m" : "c")); else if (kind === 4) { r.byte(); r.leb(); } } } } for (const s of neededViewSections(b)) { if (s.id === 6) { const r = neededViewReader(b, s.body, s.end); for (let n = r.leb(); n > 0; n--) { globalTypes.push(r.valtype() + (r.byte() ? "m" : "c")); for (; ; ) { const op = r.byte(); if (op === 11) break; if (op === 65 || op === 66 || op === 35 || op === 210 || op === 208) r.raw(); else if (op === 67) r.p += 4; else if (op === 68) r.p += 8; else if (op === 253) { r.raw(); r.p += 16; } } } } } const have = fnNames ? new Set(fnNames.values()) : null; const coro = (f) => have.has(f + ".resume") || have.has(f + " (.resume)"); const surface = /* @__PURE__ */ new Map(); for (const e of exports) { let d; if (e.kind === 0) { const t = types && funcTypes[e.index] !== void 0 ? types[funcTypes[e.index]] : void 0; let cls = "?"; if (have) { const inner = fnNames.get(e.index); cls = inner && coro(inner) || coro(e.name) ? "C" : "N"; } d = "f" + (t === void 0 ? "?" : t) + ":" + cls; } else if (e.kind === 3) { const g = globalTypes[e.index]; d = "g" + (g === void 0 ? "?" : g); } else if (e.kind === 1) d = "t"; else if (e.kind === 2) d = "m"; else d = "x" + e.kind; surface.set(e.name, d); } return surface; } function neededViewLines(consumer, lib) { const used = neededViewImports(consumer); const surface = lib instanceof Map ? lib : neededViewSurface(lib); const lines = []; for (const [name2, d] of surface) { if (used.has(name2)) lines.push(name2 + " " + d); } return lines.sort(); } function neededView(consumer, lib) { const lines = neededViewLines(consumer, lib); const text = lines.length ? lines.join("\n") + "\n" : ""; const u8 = new Uint8Array(text.length); for (let i = 0; i < text.length; i++) u8[i] = text.charCodeAt(i) & 255; return sha256Hex(u8); } function neededConstructionOrder(entries, needsOf) { const byDigest = /* @__PURE__ */ new Map(); const bySoname = /* @__PURE__ */ new Map(); for (const e of entries) { if (!byDigest.has(e.digest)) byDigest.set(e.digest, e); const so = e.soname !== void 0 ? e.soname : e.name ? neededSoname(e.name) : void 0; if (so !== void 0 && !bySoname.has(so)) bySoname.set(so, e); } const seen = /* @__PURE__ */ new Set(); const order = []; const visit = (e) => { if (seen.has(e.index)) return; seen.add(e.index); for (const n of needsOf(e)) { const dep = byDigest.get(neededDigest(n)) || bySoname.get(neededSoname(n)); if (dep) visit(dep); } order.push(e.index); }; for (const e of entries) visit(e); return order; } function neededDigest(name2) { return name2.slice(-64); } function neededSoname(name2) { return name2.slice(0, -65); } function parseWasmLinuxNeeded(bytes) { const b = bytes; if (b.length < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) { throw new Error("hwjs-libc: parseWasmLinuxNeeded: not a wasm module (bad magic)"); } let payload = null; let count = 0; let p = 8; while (p < b.length) { const id = b[p++]; let size; [size, p] = readU32LEB(b, p); const sectionEnd = p + size; if (id === 0) { let nameLen, np = p; [nameLen, np] = readU32LEB(b, np); const name2 = decodeMaybeShared2(b.subarray(np, np + nameLen)); np += nameLen; if (name2 === "wasm.linux.needed") { count++; payload = b.subarray(np, sectionEnd); } } p = sectionEnd; } if (count === 0) return null; if (count > 1) { throw new Error( `hwjs-libc: ${count} wasm.linux.needed sections on the image \u2014 exactly ONE needed-list carrier is legal (a concatenated/tampered artifact; never-silent refuse)` ); } let parsed; try { parsed = JSON.parse(decodeMaybeShared2(payload)); } catch (e) { throw new Error( `hwjs-libc: malformed wasm.linux.needed payload (not JSON): ` + (e instanceof Error ? e.message : String(e)) + " (never-silent refuse)" ); } if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.needed) || typeof parsed.suspenders_sha256 !== "string" || !/^[0-9a-f]{64}$/.test(parsed.suspenders_sha256)) { throw new Error( 'hwjs-libc: wasm.linux.needed payload shape mismatch \u2014 want {"needed":[...],"suspenders_sha256":""} (never-silent refuse)' ); } const v2 = Array.isArray(parsed.sha256); const recorded = parsed.needed; const names = neededRecordNames(parsed, "hwjs-libc:", true); const bySoname = names.map((n, i) => v2 && n !== recorded[i]); const views = names.map((_n, i) => v2 ? parsed.view[i] : ""); const runpath = neededRecordRunPath(parsed, "hwjs-libc:"); parsed = { needed: names, suspenders_sha256: parsed.suspenders_sha256 }; const NEEDED_ENTRY_MAX = 127; parsed.needed.forEach((n, i) => { if (typeof n !== "string" || !/^[0-9A-Za-z._+-]+\.[0-9a-f]{64}$/.test(n)) { throw new Error( `hwjs-libc: wasm.linux.needed entry ${i} ${JSON.stringify(n)} is not a digest-qualified library name (want . over [0-9A-Za-z._+-]; never-silent refuse)` ); } if (n.length > NEEDED_ENTRY_MAX) { throw new Error( `hwjs-libc: wasm.linux.needed entry ${i} is ${n.length} bytes, over the ${NEEDED_ENTRY_MAX} the kernel's parser accepts (WASM32_NEEDED_NAME_MAX) \u2014 the exec would fail there with no entry named (never-silent refuse)` ); } if (i === 0 && !/^libc\.so\.[0-9a-f]{64}$/.test(n)) { throw new Error( `hwjs-libc: wasm.linux.needed entry 0 is ${JSON.stringify(n)}, not a digest-qualified libc.so \u2014 entry 0 is libc.so by construction (never-silent refuse)` ); } }); const seen = /* @__PURE__ */ new Set(); for (const n of parsed.needed) { if (seen.has(n)) { throw new Error( `hwjs-libc: wasm.linux.needed names ${JSON.stringify(n)} more than once \u2014 one entry per library (never-silent refuse)` ); } seen.add(n); } return { needed: [...parsed.needed], suspendersSha256: parsed.suspenders_sha256, version: v2 ? 2 : 1, bySoname, views, runpath }; } function parseHwjsAbi(bytes) { const b = bytes; if (b.length < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) { throw new Error("hwjs-dlopen: parseHwjsAbi: not a wasm module (bad magic)"); } let found = null; let p = 8; while (p < b.length) { const id = b[p++]; let size; [size, p] = readU32LEB(b, p); const sectionEnd = p + size; if (id === 0) { let nameLen, np = p; [nameLen, np] = readU32LEB(b, np); const name2 = decodeMaybeShared2(b.subarray(np, np + nameLen)); np += nameLen; if (name2 === "hwjs.abi") { if (found) { throw new Error( "hwjs-dlopen: multiple hwjs.abi sections in the .so \u2014 exactly ONE manifest is legal (concatenated / multi-record artifact; never-silent refuse)" ); } const readField = (label) => { let result = 0, shift = 0, byte = 0; do { if (np >= sectionEnd) { throw new Error( `hwjs-dlopen: malformed hwjs.abi manifest \u2014 truncated LEB reading ${label} (never-silent refuse)` ); } byte = b[np++]; result |= (byte & 127) << shift; shift += 7; } while (byte & 128); return result >>> 0; }; const readField64Hex = (label) => { let result = 0n, shift = 0n, byte = 0; do { if (np >= sectionEnd) { throw new Error( `hwjs-dlopen: malformed hwjs.abi manifest \u2014 truncated LEB reading ${label} (never-silent refuse)` ); } byte = b[np++]; result |= BigInt(byte & 127) << shift; shift += 7n; } while (byte & 128); return result.toString(16).padStart(16, "0"); }; const manifestVersion = readField("manifest_version"); const driveAbi = readField("drive_abi"); const parkedAbi = readField("parked_abi"); const dsRegionAbi = readField("ds_region_abi"); const suspendAbiVersion = readField("suspend_abi_version"); const capregVersion = readField("capreg_version"); const fpcastVersion = readField("fpcast_version"); const flagsRaw = readField("flags"); const suspenderDigestLo64 = manifestVersion >= 2 ? readField64Hex("suspender_partition_digest") : null; const refusedExports = manifestVersion >= 2 ? readField("refused_exports") : 0; if (np !== sectionEnd) { throw new Error( `hwjs-dlopen: malformed hwjs.abi manifest \u2014 ${sectionEnd - np} trailing byte(s) after the ${manifestVersion >= 2 ? "10 v2 fields" : "8 fields"} (concatenated multi-record manifest? never-silent refuse)` ); } found = { manifestVersion, driveAbi, parkedAbi, dsRegionAbi, suspendAbiVersion, capregVersion, fpcastVersion, flagsRaw, suspenderDigestLo64, refusedExports, flags: { usesShadowStack: (flagsRaw & 1) !== 0, usesTls: (flagsRaw & 2) !== 0, safepoints: (flagsRaw & 4) !== 0, dynamicModule: (flagsRaw & 8) !== 0, checkEmitting: (flagsRaw & 16) !== 0, laneAddressed: (flagsRaw & 32) !== 0, /* bit6 with bit2 = the THREE-VALUED preemptibility fact. bit2 alone * says checkpoints were ARMED, which a module with three of them and * a module with one on every loop both satisfy; bit6 says the whole * image was censused and no function was left with a loop carrying * neither a checkpoint nor a proof. Only the latter supports "this * module will always reach a slice boundary". */ preemptTotal: (flagsRaw & 64) !== 0 }, preemptibility: (flagsRaw & 64) !== 0 ? "whole-program" : (flagsRaw & 4) !== 0 ? "scoped" : "none" }; } } p = sectionEnd; } return found; } function keptSurfaceOf(module) { const kept = moduleKeptOf(module).policy; if (kept === void 0) return null; return { importsEnvStackPointer: kept.importsEnvStackPointer, importedEnvFuncNames: moduleImportsOf(module).filter((e) => e.module === "env" && e.kind === "function").map((e) => e.name), importsHwjsSuspendPark: kept.importsHwjsSuspendPark, importsXmodConsultGen: moduleImportsOf(module).some((e) => e.module === "env" && e.name === XMOD_CONSULT_GEN_IMPORT && e.kind === "global"), exportNames: moduleExportsOf(module).map((e) => e.name), definedMutableGlobals: kept.definedMutableGlobals }; } function scanModuleSurface(bytes) { const b = bytes; if (b.length < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) { throw new Error("hwjs-dlopen: scanModuleSurface: not a wasm module (bad magic)"); } const out = { importsEnvStackPointer: false, importedEnvFuncNames: [], importsHwjsSuspendPark: false, importsXmodConsultGen: false, exportNames: [], definedMutableGlobals: [] }; let importedGlobalCount = 0; const globalNames = /* @__PURE__ */ new Map(); let p = 8; while (p < b.length) { const id = b[p++]; let size; [size, p] = readU32LEB(b, p); const sectionEnd = p + size; if (id === 2) { let count; [count, p] = readU32LEB(b, p); for (let i = 0; i < count; i++) { let len, mod, fld; [len, p] = readU32LEB(b, p); mod = decodeMaybeShared2(b.subarray(p, p + len)); p += len; [len, p] = readU32LEB(b, p); fld = decodeMaybeShared2(b.subarray(p, p + len)); p += len; const kind = b[p++]; if (kind === 0) { [, p] = readU32LEB(b, p); if (mod === "env") out.importedEnvFuncNames.push(fld); if (mod === "hwjs_suspend" && fld === "park") out.importsHwjsSuspendPark = true; } else if (kind === 1) { p += 1; const f = b[p++]; [, p] = readU32LEB(b, p); if (f & 1) { [, p] = readU32LEB(b, p); } } else if (kind === 2) { const f = b[p++]; [, p] = readU32LEB(b, p); if (f & 1) { [, p] = readU32LEB(b, p); } } else if (kind === 3) { const valtype = b[p++]; const mut = b[p++]; importedGlobalCount++; if (mod === "env" && fld === "__stack_pointer" && valtype === 127 && mut === 1) { out.importsEnvStackPointer = true; } if (mod === "env" && fld === XMOD_CONSULT_GEN_IMPORT && valtype === 126) { out.importsXmodConsultGen = true; } } else { throw new Error( `hwjs-dlopen: scanModuleSurface: unknown import kind 0x${kind.toString(16)} (malformed .so; never-silent)` ); } } } else if (id === 6) { let count; [count, p] = readU32LEB(b, p); for (let i = 0; i < count; i++) { const valtype = b[p++]; const mut = b[p++]; let initIsI32Const0 = false; let initIsI32Const = false; let initIsI64Const0 = false; const op = b[p++]; if (op === 65) { let v; [v, p] = readS32LEB(b, p, sectionEnd); initIsI32Const0 = v === 0; initIsI32Const = true; } else if (op === 66) { let v; [v, p] = readS32LEB(b, p, sectionEnd); initIsI64Const0 = v === 0; } else if (op === 67) { p += 4; } else if (op === 68) { p += 8; } else if (op === 35) { [, p] = readU32LEB(b, p); } else if (op === 208) { p += 1; } else if (op === 210) { [, p] = readU32LEB(b, p); } else { throw new Error( `hwjs-dlopen: scanModuleSurface: unsupported global init opcode 0x${op.toString(16)} (not an lld -shared artifact; never-silent)` ); } if (b[p++] !== 11) { throw new Error( "hwjs-dlopen: scanModuleSurface: global init expr not terminated by end (malformed .so; never-silent)" ); } if (mut === 1) { out.definedMutableGlobals.push({ valtype, initIsI32Const0, initIsI32Const, initIsI64Const0, definedIndex: i }); } } } else if (id === 7) { let count; [count, p] = readU32LEB(b, p); for (let i = 0; i < count; i++) { let len; [len, p] = readU32LEB(b, p); out.exportNames.push(decodeMaybeShared2(b.subarray(p, p + len))); p += len; p += 1; [, p] = readU32LEB(b, p); } } else if (id === 0) { let len; [len, p] = readU32LEB(b, p); const secName = decodeMaybeShared2(b.subarray(p, p + len)); p += len; if (secName === "name") { while (p < sectionEnd) { const subId = b[p++]; let subLen; [subLen, p] = readU32LEB(b, p); const subEnd = p + subLen; if (subId === 7) { let count; [count, p] = readU32LEB(b, p); for (let i = 0; i < count; i++) { let idx, nlen; [idx, p] = readU32LEB(b, p); [nlen, p] = readU32LEB(b, p); globalNames.set(idx, decodeMaybeShared2(b.subarray(p, p + nlen))); p += nlen; } } p = subEnd; } } } p = sectionEnd; } for (const g of out.definedMutableGlobals) { g.name = globalNames.get(importedGlobalCount + g.definedIndex); } return out; } function unsanctionedMutableGlobals(surface, manifest) { const isInternalGotShape = (g) => typeof g.name === "string" && (g.name.startsWith("GOT.data.internal.") || g.name.startsWith("GOT.func.internal.")) && g.valtype === 127 && g.initIsI32Const; const isBudgetShape = (g) => g.name === "__hwjs_budget" && g.valtype === 127 && g.initIsI32Const0 && manifest.flags.safepoints === true; const isTcbPointerShape = (g) => g.name === "__hwjs_tcb" && g.valtype === 127 && g.initIsI32Const0 && surface.exportNames.includes("__hwjs_tcb_bind"); const isXmcSiteShape = (g) => surface.importsXmodConsultGen === true && typeof g.name === "string" && (/^hwjs\.xmc\.fp(\.\d+)?$/.test(g.name) && g.valtype === 127 && g.initIsI32Const0 || /^hwjs\.xmc\.gen(\.\d+)?$/.test(g.name) && g.valtype === 126 && g.initIsI64Const0 === true); return surface.definedMutableGlobals.filter((g) => !isInternalGotShape(g) && !isBudgetShape(g) && !isTcbPointerShape(g) && !isXmcSiteShape(g)); } function checkLoadPolicy(wasmBytes, opts, known = null, fresh = null) { const kf = known ? moduleFactsOf(known) : null; let manifest, surface; const kept = known ? moduleKeptOf(known).policy : void 0; if (kf && kf.policyRead === true) { manifest = kf.manifest; surface = kf.surface; } else if (kept !== void 0) { manifest = kept.manifest; surface = keptSurfaceOf(known); if (fresh) { fresh.manifest = manifest; fresh.surface = surface; } } else { manifest = parseHwjsAbi(wasmBytes); surface = scanModuleSurface(wasmBytes); if (fresh) { fresh.manifest = manifest; fresh.surface = surface; } } const mut = unsanctionedMutableGlobals(surface, manifest); const isTlsBaseShape = (g) => g.valtype === 127 && g.initIsI32Const0; if (mut.length > 1 || mut.length === 1 && !isTlsBaseShape(mut[0])) { throw new Error( `hwjs-dlopen: private mutable global state in a .so \u2014 not an lld -shared artifact (found ${mut.length} defined mutable global(s) beyond the sanctioned lld GOT.data.internal.* internal-GOT shape; at most ONE other is legal and only the lld __tls_base shape: i32, init i32.const 0; unnamed mutable globals stay refused \u2014 the name section is the sanction carrier). Refusing to instantiate (never-silent).` ); } if (surface.importsEnvStackPointer && !(opts.stackPointer instanceof WebAssembly.Global)) { throw new Error( "hwjs-dlopen: the .so imports env.__stack_pointer (mutable i32 \u2014 the shared shadow-stack pointer) but no opts.stackPointer WebAssembly.Global was provided. The loader REFUSES to fabricate a private sp global (a shadow-stack-using .so descending on a private sp=0 corrupts linear memory); pass the main image's exported __stack_pointer so main + .so share ONE sp (never-silent)." ); } if (manifest) { if (manifest.manifestVersion !== 1 && manifest.manifestVersion !== 2) { throw new Error( `hwjs-dlopen: hwjs.abi manifest_version ${manifest.manifestVersion} is not a known version (want 1 or 2) \u2014 ABI-skewed / foreign .so, refusing to instantiate (never-silent).` ); } let wantDriveAbi = 3; if (opts.mainDriveAbi !== void 0) { if (opts.mainDriveAbi !== 3 && opts.mainDriveAbi !== 4) { throw new Error( `hwjs-dlopen: opts.mainDriveAbi=${opts.mainDriveAbi} is not a dlopen-capable drive abi (want 3 flat or 4 status-channel) \u2014 refusing to guess (never-silent).` ); } wantDriveAbi = opts.mainDriveAbi; } const want = [ ["drive_abi", manifest.driveAbi, wantDriveAbi], ["parked_abi", manifest.parkedAbi, 2], ["ds_region_abi", manifest.dsRegionAbi, 2], ["suspend_abi_version", manifest.suspendAbiVersion, 1], ["capreg_version", manifest.capregVersion, 1], ["fpcast_version", manifest.fpcastVersion, 1], /* flags.uses_tls is handled by the G2 single-owner rule below (it is * NOT a fixed-value field: the ONE sanctioned owner may carry 1). * * PREEMPTIBILITY is checked just below rather than here, because it is * three-valued and this table compares numbers for equality. * * What used to be on this line: ['flags.safepoints', got, laneAddressed * ? 1 : 0] — an EQUALITY, so a lane-unaware .so was required to have * safepoints OFF. That pinned the DEFAULT of the day, not a property: * checkpoints were the exception, so "lane-unaware" and "unsafepointed" * happened to coincide. They no longer do — checkpoints are on by * default — and left alone this line would refuse every correctly built * module in the tree. It is replaced, not deleted: the half that was * load-bearing (a lane-addressed module must be preemptible) is kept and * strengthened from a bit to the whole-image value. */ ["flags.dynamic_module", manifest.flags.dynamicModule ? 1 : 0, 1] ]; for (const [field, got, expected] of want) { if (got !== expected) { throw new Error( `hwjs-dlopen: hwjs.abi manifest ${field} mismatch: got ${got}, want ${expected} \u2014 ABI-skewed / foreign .so, refusing to instantiate (never-silent).` ); } } if (manifest.flags.laneAddressed === true && manifest.preemptibility !== "whole-program") { throw new Error( `hwjs-dlopen: hwjs.abi manifest preemptibility=${manifest.preemptibility} on a LANE-ADDRESSED .so (flags bit5) \u2014 want whole-program. Sibling lanes run concurrently in one process, so a lane of this module inside a syscall-free unbounded loop reaches no slice boundary: fork() would return EAGAIN on the acquire deadline and no lane's pending signals would be dispatched. ${manifest.preemptibility === "scoped" ? "scoped means SOME checkpoints exist and is not a whole-image statement." : "This module was built with checkpoints disarmed."} Refusing to instantiate (never-silent).` ); } const procLaneAddressed = opts.mainLaneAddressed === true; const soLaneAddressed = manifest.flags.laneAddressed === true; if (soLaneAddressed !== procLaneAddressed) { throw new Error( `hwjs-dlopen: LANE-ADDRESSED MISMATCH \u2014 this .so attests hwjs.abi flags bit5 lane_addressed=${soLaneAddressed ? 1 : 0} but the process (main) attests lane_addressed=${procLaneAddressed ? 1 : 0}. Mixing a lane-addressed module with a lane-unaware one lets the lane-unaware side read the INITIAL thread's status word from ANY thread \u2014 silent transit under threads (I3-2; PLAN-THREADS-SINGLE-MEMORY \xA74 step 2). Rebuild the pair in lockstep (both HWJS_RT_LANES>1 or neither); refusing to instantiate (never-silent).` ); } if ((manifest.flags.usesTls ? 1 : 0) === 1 && opts.tlsOwner !== true) { if (!(opts.sideTls && typeof opts.sideTls === "object")) { throw new Error( `hwjs-dlopen: hwjs.abi manifest flags.uses_tls=1 on a load that binds no TLS for it \u2014 neither the libc.so thread-pointer owner (opts.tlsOwner) nor a side-module load (opts.sideTls). Its private __tls_base would be unbound on every Instance after the first. Refusing to instantiate (never-silent).` ); } const missing = SIDE_TLS_EXPORTS.filter( (n) => !surface.exportNames.includes(n) ); if (missing.length) { throw new Error( `hwjs-dlopen: side module owns TLS (hwjs.abi uses_tls=1) but does not export ${missing.join(", ")} \u2014 the loader cannot bind its per-thread block without them. Relink it with a brintld that emits the side-module TLS surface (brintos/hwjs-cc#106). Refusing to instantiate (never-silent).` ); } } return manifest; } const suspendSurface = surface.importsHwjsSuspendPark || surface.importedEnvFuncNames.some( (n) => n.startsWith("__hwjs_") || n.startsWith("hwjs_") ) || surface.exportNames.includes("__hwjs_drive_abi"); if (suspendSurface) { throw new Error( "hwjs-dlopen: suspend-capable .so without hwjs.abi manifest \u2014 the module imports/exports hwjs suspend-ABI surface but carries no hwjs.abi attestation (a pre-manifest or nested-built artifact). Rebuild it with the manifest-emitting linker, brintld (never-silent refuse)." ); } throw new Error( "hwjs-dlopen: .so has no hwjs.abi manifest \u2014 every dlopen-able module must attest its ABI lineage (the STEP-2 manifest-less PURE grandfather is retired). Rebuild it with the manifest-emitting linker, brintld (never-silent refuse)." ); } function classifyDlopenFailure(e) { const message = e instanceof Error ? e.message : String(e); const mk = (errno, errnoName, cls) => ({ errno, errnoName, cls, message }); if (typeof RangeError === "function" && e instanceof RangeError || /never-silent OOM|out of memory|Cannot allocate memory|failed to grow the shared table|could not grow the shared table/i.test(message)) { return mk(-12, "ENOMEM", "alloc"); } if (e instanceof WebAssembly.CompileError || /not a wasm module \(bad magic\)/.test(message)) { return mk(-8, "ENOEXEC", "compile"); } if (e instanceof WebAssembly.LinkError) { return mk(-80, "ELIBBAD", "link"); } if (message.startsWith("hwjs-dlopen:")) { return mk(-80, "ELIBBAD", "policy"); } return mk(-22, "EINVAL", "unknown"); } function sideTlsLayout(exports) { const size = exports.__tls_size.value >>> 0; const align = Math.max(exports.__tls_align.value >>> 0, 16); return { size, align, stride: Math.ceil(Math.max(size, 1) / align) * align }; } function mainTlsSlot(heapBase, size, align) { const al = Math.max(align >>> 0, 16); const stride = Math.ceil((size >>> 0) / al) * al + al; const top = Math.floor(((heapBase >>> 0) + MAIN_TLS_BRK_BYTES) / al) * al; const floor = (heapBase >>> 0) + MAIN_TLS_CARVE_BYTES; const addr = top - stride >= floor ? top - stride : 0; return { addr: addr >>> 0, stride, align: al }; } function sideTlsReplayMode(mode, entry, alloc) { if (mode === "thread") return { mode: "materialise", alloc }; if (mode === "fork-resume") return { mode: "fork", base: entry.tlsBase >>> 0 }; return { mode: "rebind", base: entry.tlsBase >>> 0 }; } function sideTlsRecordFields(handle) { return { tlsBase: handle && handle.tls ? handle.tls.base() : 0 }; } function materialiseSideModuleTls(handle, alloc, soPath) { if (!handle || !handle.tls) { throw new Error( `hwjs-dlopen: materialiseSideModuleTls on a module that owns no TLS${soPath ? ` ("${soPath}")` : ""} (never-silent)` ); } return bindSideModuleTls( handle.exports, null, { mode: "materialise", alloc }, soPath ); } function bindSideModuleTls(exports, memory, sideTls, soPath) { const tlsBase = exports.__tls_base; const where = soPath ? ` "${soPath}"` : ""; const requireBase = (base, what) => { if (base >>> 0 === 0) { throw new Error( `hwjs-dlopen: side module${where} owns TLS but ${what} \u2014 binding 0 would put its thread_local state at address 0 (never-silent).` ); } }; const initInto = (base) => { exports.__wasm_init_tls(base | 0); if (tlsBase.value >>> 0 !== base >>> 0) { throw new Error( `hwjs-dlopen: side module${where} __wasm_init_tls(${base >>> 0}) left __tls_base at ${tlsBase.value >>> 0} (never-silent).` ); } return base >>> 0; }; switch (sideTls.mode) { case "fresh": { const base = tlsBase.value >>> 0; requireBase(base, "its first Instance left __tls_base at 0 (lld's start function did not bind the loading thread's block)"); return initInto(base); } case "rebind": { requireBase(sideTls.base, "the replay record carries no live __tls_base for it"); tlsBase.value = sideTls.base | 0; return sideTls.base >>> 0; } case "fork": { requireBase(sideTls.base, "the fork record carries no live __tls_base for it"); tlsBase.value = sideTls.base | 0; return sideTls.base >>> 0; } case "materialise": { if (typeof sideTls.alloc !== "function") { throw new Error( `hwjs-dlopen: side module${where} owns TLS but this thread has no TLS arena to take a block from \u2014 its thread_local state has nowhere to live (never-silent).` ); } const { size, align } = sideTlsLayout(exports); const block = sideTls.alloc(Math.max(size, 1), align) >>> 0; if (block === 0) return 0; return initInto(block); } default: throw new Error( `hwjs-dlopen: unknown side-module TLS bind mode ${JSON.stringify(sideTls.mode)} (never-silent)` ); } } function tableLedgerOpen(table) { if (!(table instanceof WebAssembly.Table)) return; for (let i = 0; i < table.length; i++) { if (table.get(i) !== null) return; } tableLedgers.set(table, { slotOf: /* @__PURE__ */ new Map() }); } function tableLedgerDrop(table, why) { if (!tableLedgers.delete(table)) return; const ix = tableIndexes.get(table); if (ix !== void 0 && ix.byLedger) ix.exact = false; linkPlanTell( "ledger", `hwjs-link-plan: the shared table's ledger is given up (${why}); its identity lookups scan the table from here (slower, not wrong)` ); } function tableLedgerNoteSet(table, slot, fn2) { const l = tableLedgers.get(table); if (!l || typeof fn2 !== "function") return; const prev = l.slotOf.get(fn2); if (prev === void 0 || slot < prev) l.slotOf.set(fn2, slot >>> 0); } function parseActiveElemSegments(bytes) { const b = bytes; let p = 8; while (p < b.length) { const id = b[p++]; let size; [size, p] = readU32LEB(b, p); const end = p + size; if (id === 9) { const segs = []; let count; [count, p] = readU32LEB(b, p); for (let s = 0; s < count; s++) { let flags; [flags, p] = readU32LEB(b, p); if (flags !== 0 && flags !== 2 && flags !== 4) return null; if (flags === 2) { let tidx; [tidx, p] = readU32LEB(b, p); if (tidx !== 0) return null; } let offset; const op = b[p++]; if (op === 65) { let v = 0, shift = 0, byte; do { byte = b[p++]; v |= (byte & 127) << shift; shift += 7; } while (byte & 128); if (shift < 32 && byte & 64) v |= ~0 << shift; offset = { const: v | 0 }; } else if (op === 35) { let g; [g, p] = readU32LEB(b, p); offset = { global: g }; } else { return null; } if (b[p++] !== 11) return null; if (flags === 2 && b[p++] !== 0) return null; let n; [n, p] = readU32LEB(b, p); const funcs = new Uint32Array(n); for (let i = 0; i < n; i++) { if (flags === 4) { if (b[p++] !== 210) return null; [funcs[i], p] = readU32LEB(b, p); if (b[p++] !== 11) return null; } else { [funcs[i], p] = readU32LEB(b, p); } } segs.push({ offset, funcs }); } return segs; } p = end; } return []; } function ledgerFactsOf(module, bytes) { const k = moduleKeptOf(module); if (k.ledgerFacts !== void 0) return k.ledgerFacts; let segs; const shared = sharedFactsOf(module, "elem"); if (shared && (shared.segs === null || Array.isArray(shared.segs))) { segs = shared.segs; } else { segs = parseActiveElemSegments(bytes); publishFacts(module, "elem", { segs }); } const funcImports = []; const globalImports = []; for (const i of moduleImportsOf(module)) { if (i.kind === "function") funcImports.push(i); else if (i.kind === "global") globalImports.push(i); } const exportByFunc = /* @__PURE__ */ new Map(); for (const [name2, idx] of exportedFunctionIndicesOf(module, bytes)) { if (!exportByFunc.has(idx)) exportByFunc.set(idx, name2); } return k.ledgerFacts = Object.freeze({ segs, funcImports, globalImports, exportByFunc }); } function tableLedgerNoteInstance(table, instance, module, bytes, imports) { const l = tableLedgers.get(table); if (!l) return; const walked = tableWritesOf(module, bytes); if (walked !== "none") { tableLedgerDrop(table, `a module's code walk found ${walked} table writes`); return; } const facts = ledgerFactsOf(module, bytes); const segs = facts.segs; if (segs === null) { tableLedgers.delete(table); return; } const { funcImports, globalImports, exportByFunc } = facts; for (const seg of segs) { let base; if (seg.offset.const !== void 0) { base = seg.offset.const; } else { const gi = globalImports[seg.offset.global]; const gv = gi ? imports?.[gi.module]?.[gi.name] : void 0; if (!(gv instanceof WebAssembly.Global)) { tableLedgers.delete(table); return; } base = gv.value | 0; } for (let k = 0; k < seg.funcs.length; k++) { const f = seg.funcs[k]; let fn2; if (f < funcImports.length) { const im = funcImports[f]; fn2 = imports?.[im.module]?.[im.name]; } else { const name2 = exportByFunc.get(f); fn2 = name2 !== void 0 ? instance.exports[name2] : void 0; } if (typeof fn2 === "function") tableLedgerNoteSet(table, base + k, fn2); } } } function tableLedgerSlot(table, fn2, from) { const l = tableLedgers.get(table); if (!l) return void 0; const s = l.slotOf.get(fn2); const ans = s === void 0 || s < from || s >= table.length ? -1 : s; if (TABLE_LEDGER_VERIFY) { let scan = -1; for (let i = from; i < table.length; i++) { if (table.get(i) === fn2) { scan = i; break; } } if (scan !== ans) { throw new Error(`hwjs-dlopen: TABLE LEDGER DISAGREES with the table: it answers slot ${ans} where a scan finds ${scan} \u2014 a table writer did not record its write (never-silent; HWJS_TABLE_LEDGER_VERIFY)`); } } return ans; } function tableSlotOf(table, fn2, from = 0) { const l = tableLedgerSlot(table, fn2, from); if (l !== void 0) return l; for (let i = from; i < table.length; i++) { if (table.get(i) === fn2) return i; } return -1; } function tableIndexOf(table, fn2) { return tableSlotOf(table, fn2, 0); } function alignUp(x, a) { if (a <= 1) return x; return x + (a - 1) & ~(a - 1); } function wireImports(module, opts, memoryBase, tableBase, weakImports) { const out = /* @__PURE__ */ Object.create(null); const put = (m, n, v) => { (out[m] ??= /* @__PURE__ */ Object.create(null))[n] = v; }; const gotFunc = /* @__PURE__ */ new Map(); const gotMem = /* @__PURE__ */ new Map(); let budgetGlobal = null; const ensureBudgetGlobal = () => budgetGlobal ??= opts.budgetGlobal instanceof WebAssembly.Global ? opts.budgetGlobal : new WebAssembly.Global({ value: "i32", mutable: true }, 0); const mbGlobal = new WebAssembly.Global({ value: "i32", mutable: false }, memoryBase | 0); const tbGlobal = new WebAssembly.Global({ value: "i32", mutable: false }, tableBase | 0); const selfBox = { exports: null }; const ownBound = []; let ownFns = null; const ownDefines = (n) => (ownFns ??= new Set( WebAssembly.Module.exports(module).filter((e) => e.kind === "function").map((e) => e.name) )).has(n); const weakUnbound = []; for (const imp of moduleImportsOf(module)) { const { module: m, name: n, kind } = imp; if (kind === "memory") { put(m, n, opts.memory); continue; } if (kind === "table") { put(m, n, opts.table); continue; } if (kind === "global" && n === "__memory_base") { put(m, n, mbGlobal); continue; } if (kind === "global" && n === "__table_base") { put(m, n, tbGlobal); continue; } if (kind === "global" && n === "__stack_pointer" && opts.stackPointer instanceof WebAssembly.Global) { put(m, n, opts.stackPointer); continue; } if (kind === "global" && m === "env" && n === XMOD_CONSULT_GEN_IMPORT) { put(m, n, xmodConsultGenerationGlobal()); continue; } if (kind === "global" && m === "env" && n === "__hwjs_status_channel_addr") { if (opts.statusChannelGlobal !== void 0) { const g = opts.statusChannelGlobal; if (!(g instanceof WebAssembly.Global)) { throw new Error("hwjs-dlopen: opts.statusChannelGlobal is not a WebAssembly.Global \u2014 refusing to bind the status-channel address import to anything else (never-silent)."); } put(m, n, g); continue; } const addr = opts.statusChannelAddr; if (typeof addr !== "number" || !Number.isInteger(addr) || addr <= 0) { throw new Error( "hwjs-dlopen: the .so imports env.__hwjs_status_channel_addr (lane-addressed module) but the caller supplied no opts.statusChannelAddr \u2014 refusing to fabricate a channel base (address 0 would silently read wrong memory as the status word; never-silent; PLAN-THREADS-SINGLE-MEMORY \xA74 step 2)." ); } put(m, n, new WebAssembly.Global({ value: "i32", mutable: true }, addr | 0)); continue; } if (kind === "global" && m === "env" && n === "__hwjs_budget") { put(m, n, ensureBudgetGlobal()); continue; } if (kind === "function" && m === "env" && (n === "__hwjs_budget_set" || n === "__hwjs_budget_get")) { const g = ensureBudgetGlobal(); put(m, n, n === "__hwjs_budget_set" ? (v) => { g.value = v | 0; } : () => g.value | 0); continue; } if (kind === "global" && m === "GOT.func") { const g = new WebAssembly.Global({ value: "i32", mutable: true }, 0); gotFunc.set(n, g); put(m, n, g); continue; } if (kind === "global" && m === "GOT.mem") { const g = new WebAssembly.Global({ value: "i32", mutable: true }, 0); gotMem.set(n, g); put(m, n, g); continue; } if (m === "hwjs_suspend" && n === "park") { put(m, n, opts.parkImport ?? (() => { })); continue; } const own = !!opts.bindOwnDefinitions && m === "env" && kind === "function" && ownDefines(n); const resolved = opts.resolveImport ? opts.resolveImport(m, n, kind, own) : void 0; if ((resolved === void 0 || resolved === null) && own) { put(m, n, ownDefinitionTrampoline(n, selfBox, opts.soPath)); ownBound.push(n); continue; } if ((resolved === void 0 || resolved === null) && kind === "function" && weakImports && weakImports.get(n) === m) { put(m, n, weakUndefinedCall(m, n, opts.soPath)); weakUnbound.push(n); continue; } if (resolved === void 0 || resolved === null) { const soName = opts.soPath ? `"${opts.soPath}"` : "the shared object"; let defined = ""; try { defined = moduleExportsOf(module).some((e) => e.name === n && e.kind === kind) ? ` NOTE: ${soName} ITSELF exports ${n} (${kind}) \u2014 this is a PREEMPTIBLE symbol (a -shared module routes its own weak/default-visibility definitions through env so the loader may interpose one), and nothing in this process provides it.` : ""; } catch (_e) { } throw new Error( `hwjs-dlopen: unresolved import ${m}.${n} (${kind}) in ${soName} \u2014 the loader has no binding and resolveImport returned nothing (never-silent; a mis-wired dynamic module must fail loudly, not run with a hole).${defined}` ); } put(m, n, resolved); } return { imports: out, gotFunc, gotMem, budgetGlobal, selfBox, ownBound, weakUnbound }; } function ownDefinitionTrampoline(n, selfBox, soPath) { let bound = null; const provider = () => { const f = selfBox.exports ? selfBox.exports[n] : void 0; if (typeof f !== "function") { const soName = soPath ? `"${soPath}"` : "the shared object"; throw new Error( `hwjs-dlopen: env.${n} in ${soName} is bound to the module's own definition, but ${selfBox.exports ? `the instance exports no function "${n}"` : "it was called before the module was instantiated (from its start section)"} (never-silent).` ); } return f; }; return function(a, b, c, d, e, g, h) { const f = bound || (bound = provider()); switch (arguments.length) { case 0: return f(); case 1: return f(a); case 2: return f(a, b); case 3: return f(a, b, c); case 4: return f(a, b, c, d); case 5: return f(a, b, c, d, e); case 6: return f(a, b, c, d, e, g); case 7: return f(a, b, c, d, e, g, h); default: return f.apply(null, arguments); } }; } function weakUndefinedCall(m, n, soPath) { const soName = soPath ? `"${soPath}"` : "the shared object"; return () => { throw new Error( `hwjs-dlopen: call to ${m}.${n} in ${soName}, a WEAK undefined function that no loaded module defines, so its address is null (never-silent; ELF would fault on the same call).` ); }; } function tableSet(table, idx, fn2) { tableProtoSet.call(table, idx, fn2); } function tableGrow(table, delta) { return tableProtoGrow.call(table, delta); } function setTableAllocator(table, alloc) { if (typeof alloc === "function") slotAllocators.set(table, alloc); else slotAllocators.delete(table); } function makeCellTableAllocator(cell, word2) { return (len, n) => { for (; ; ) { const cur = Atomics.load(cell, word2) >>> 0; const base = Math.max(cur, len >>> 0); if (Atomics.compareExchange(cell, word2, cur | 0, base + n | 0) === (cur | 0)) return base; } }; } function appendCountOf(table) { return appendCounts.get(table) ?? 0; } function tableReserve(table, n) { appendCounts.set(table, appendCountOf(table) + 1); const r = planRegions.get(table); if (r !== void 0) { if (r.next + (n >>> 0) <= r.end) { const base = r.next; r.next += n >>> 0; return base; } r.next = r.end; r.overflow = true; } const alloc = slotAllocators.get(table); if (alloc) return alloc(table.length >>> 0, n >>> 0) >>> 0; return table.length >>> 0; } function tableAppend(table, n) { const base = tableReserve(table, n); if (table.length >>> 0 < base + n) tableGrow(table, base + n - (table.length >>> 0)); return base; } function tableIndexGuard(table) { if (Object.prototype.hasOwnProperty.call(table, "set")) return; Object.defineProperty(table, "set", { configurable: true, writable: true, value: function set(idx, fn2) { tableIndexEnd(this, "set"); return tableProtoSet.apply(this, arguments); } }); Object.defineProperty(table, "grow", { configurable: true, writable: true, value: function grow(delta, fn2) { if (arguments.length > 1 && fn2 !== null && fn2 !== void 0) tableIndexEnd(this, "grow"); return tableProtoGrow.apply(this, arguments); } }); } function tableIndexEnd(table, how) { const ix = tableIndexes.get(table); if (ix === void 0 || !ix.exact) return; ix.exact = false; linkPlanStats.forgotten++; tableLedgerDrop(table, `a ${how}() from outside the loader`); const tell = linkPlanReport !== null && !linkPlanTold.has("caught"); if (tell || linkPlanStats.traceForget && linkPlanStats.forgottenBy === "") { const at = (new Error().stack || "").split("\n").slice(2, 4).map((l) => l.trim()).join(" < "); if (linkPlanStats.traceForget && linkPlanStats.forgottenBy === "") linkPlanStats.forgottenBy = `${how}: ${at}`; linkPlanTell( "caught", `hwjs-link-plan: a ${how}() on a shared table from outside the loader ended the table's index; its loads read the whole table from here (slower, not wrong): ${at}` ); } } function setLinkPlanReport(fn2) { linkPlanReport = typeof fn2 === "function" ? fn2 : null; } function linkPlanTell(kind, text) { if (linkPlanReport === null || linkPlanTold.has(kind)) return; try { linkPlanReport(text); linkPlanTold.add(kind); } catch (_e) { } } function tableIndexFor(table, lengthBefore, covered) { let ix = tableIndexes.get(table); if (ix === void 0) { ix = { exact: covered, slots: /* @__PURE__ */ new Map(), readTo: 0, firstBase: lengthBefore }; tableIndexes.set(table, ix); for (let i = 0; covered && i < lengthBefore && i < table.length; i++) { if (table.get(i) !== null) { ix.exact = false; break; } } if (ix.exact) tableIndexGuard(table); } if (!covered) ix.exact = false; return ix; } function tableIndexForget(table) { const ix = tableIndexes.get(table); if (ix !== void 0) ix.exact = false; } function tableIndexRead(ix, table) { const len = table.length; if (tableLedgers.has(table)) { ix.readTo = len; ix.byLedger = true; return; } for (let i = ix.readTo; i < len; i++) { const f = table.get(i); if (f !== null && !ix.slots.has(f)) ix.slots.set(f, i); } ix.readTo = len; } function tableIndexNote(ix, fn2, idx) { const prev = ix.slots.get(fn2); if (prev === void 0 || idx < prev) ix.slots.set(fn2, idx); } function loadSharedObject(opts) { const table = opts.table; const plan = opts.tablePlan; const lengthAtEntry = table ? table.length >>> 0 : 0; let region = null; if (plan && table && typeof opts.fixedTableBase !== "number" && !planRegions.has(table) && plan.base >>> 0 === lengthAtEntry && plan.growth >>> 0 > 0) { const growth = plan.growth >>> 0; const alloc = slotAllocators.get(table); const start = alloc ? alloc(lengthAtEntry, growth) >>> 0 : lengthAtEntry; try { if (table.length >>> 0 < start + growth) tableGrow(table, start + growth - (table.length >>> 0)); region = { next: start, end: start + growth, overflow: false }; planRegions.set(table, region); } catch (_e) { region = null; } } let handle; try { handle = loadSharedObjectPlaced(opts); } finally { if (region !== null) planRegions.delete(table); } if (table && typeof opts.fixedTableBase !== "number") { const end = region !== null && !region.overflow && table.length >>> 0 === region.end ? region.next : table.length >>> 0; handle.tableGrowth = { base: lengthAtEntry, used: end - lengthAtEntry, planned: region !== null ? plan.growth >>> 0 : null }; } return handle; } function loadSharedObjectPlaced(opts) { const { wasmBytes, memory, table } = opts; const known = opts.knownModule instanceof WebAssembly.Module ? opts.knownModule : null; const freshFacts = known ? /* @__PURE__ */ Object.create(null) : null; const manifest = checkLoadPolicy(wasmBytes, opts, known, freshFacts); const knownFacts = known ? moduleFactsOf(known) : null; let dylink; if (knownFacts && knownFacts.dylinkRead === true) { dylink = knownFacts.dylink; } else { dylink = parseDylink0(wasmBytes); } const memorySize = dylink ? dylink.memorySize : 0; const memoryAlign = dylink ? dylink.memoryAlign : 1; const tableSize = dylink ? dylink.tableSize : 0; const memoryBase = typeof opts.fixedMemoryBase === "number" ? opts.fixedMemoryBase >>> 0 : memorySize > 0 ? opts.allocMemory(alignUp(memorySize, memoryAlign), memoryAlign) : 0; if (memorySize > 0 && !(memoryBase > 0)) { throw new Error( `hwjs-dlopen: allocMemory returned ${memoryBase} for a ${memorySize}B .so data region (never-silent OOM / bad bump)` ); } const hasFixedTableBase = typeof opts.fixedTableBase === "number"; const tableBase = hasFixedTableBase ? opts.fixedTableBase >>> 0 : tableSize > 0 ? tableReserve(table, tableSize) : table.length; if (hasFixedTableBase) { if (tableBase + tableSize > table.length) { throw new Error( `hwjs-dlopen: fixedTableBase placement [${tableBase}, ${tableBase + tableSize}) exceeds the shared table length ${table.length} \u2014 the replay payload places a module past the parent's declared table extent (corrupt placement; never-silent)` ); } for (let i = tableBase; i < tableBase + tableSize; i++) { if (table.get(i) !== null) { throw new Error( `hwjs-dlopen: fixedTableBase placement [${tableBase}, ${tableBase + tableSize}) collides with an occupied slot ${i} \u2014 two modules' recorded windows overlap (corrupt placement; never-silent, the elem write would clobber another module's identities)` ); } } } else if (tableSize > 0 && tableBase + tableSize > table.length) { try { tableGrow(table, tableBase + tableSize - table.length); } catch (e) { throw new Error( `hwjs-dlopen: failed to grow the shared table by ${tableSize} slots for the .so (table max reached?): ` + (e instanceof Error ? e.message : String(e)) ); } } const module = typeof opts.compileModule === "function" ? opts.compileModule(wasmBytes) : new WebAssembly.Module(wasmSource2(wasmBytes)); if (!(module instanceof WebAssembly.Module)) { throw new Error( "hwjs-dlopen: opts.compileModule returned a non-Module \u2014 the caller must hand back a WebAssembly.Module compiled from exactly the load bytes (never-silent)" ); } const dataBytes = readDataSegmentBytes(wasmBytes); if (known && module !== known) { throw new Error( "hwjs-dlopen: opts.knownModule is not the Module opts.compileModule returned \u2014 what was read from one must not be used for the other (never-silent)" ); } if (knownFacts) { if (knownFacts.policyRead !== true && "surface" in freshFacts) { knownFacts.manifest = freshFacts.manifest; knownFacts.surface = freshFacts.surface; knownFacts.policyRead = true; const kept = moduleKeptOf(known); if (kept.policy === void 0) { const sv = freshFacts.surface; kept.policy = { manifest: freshFacts.manifest, importsEnvStackPointer: sv.importsEnvStackPointer, importsHwjsSuspendPark: sv.importsHwjsSuspendPark, definedMutableGlobals: sv.definedMutableGlobals }; } } if (knownFacts.dylinkRead !== true) { knownFacts.dylink = dylink; knownFacts.dylinkRead = true; } } const weakImports = dylink ? dylink.weakImports : null; const { imports, gotFunc, gotMem, budgetGlobal, selfBox, ownBound, weakUnbound } = wireImports(module, opts, memoryBase, tableBase, weakImports); const instance = new WebAssembly.Instance(module, imports); heapChargeInstance(instance, module); tableLedgerNoteInstance(table, instance, module, wasmBytes, imports); const exports = instance.exports; selfBox.exports = exports; const indexedLoad = !!known && opts.preMain === true && !hasFixedTableBase && tableBase > 0 && !opts.skipDataRelocs && !opts.seedSymbolIndices && !(opts.reservedSymbolIndices && opts.reservedSymbolIndices.length); const ix = tableIndexFor( table, tableBase, indexedLoad && segmentsAtTableBaseOf(known, wasmBytes) && tableWritesOf(known, wasmBytes) === "none" ); let indexed = ix.exact; if (indexed) tableIndexRead(ix, table); let indexOwnAsked = false; const planCheck = opts.linkPlanCheck === true; if (indexed) linkPlanStats.indexedLoads++; else linkPlanStats.snapshotLoads++; function indexedSlotOf(fn2) { const ledgered = tableLedgerSlot(table, fn2, 0); if (ledgered === void 0 && ix.byLedger) { ix.exact = false; indexed = false; residentIdx = null; return null; } const i = ledgered !== void 0 ? ledgered < 0 ? void 0 : ledgered : ix.slots.get(fn2); if (i === void 0) return -1; if (table.get(i) === fn2) return i; linkPlanStats.readBackFailed++; linkPlanTell( "readback", `hwjs-link-plan: slot ${i} of a shared table no longer held the function the table's index named for ${opts.soPath || "a module"}: something outside the loader wrote it; its loads read the whole table from here (slower, not wrong)` ); ix.exact = false; indexed = false; residentIdx = null; return null; } function lowestSlotFrom(fn2, from) { for (let i = from; i < table.length; i++) if (table.get(i) === fn2) return i; return -1; } function checked(what, got, want) { if (planCheck && got !== want) { throw new Error( `hwjs-link-plan: ${what} of ${opts.soPath || "a module"} is at table slot ${want} by a scan and ${got} by the table's index (never-silent)` ); } return got; } if (manifest && typeof exports.__hwjs_drive_abi === "function") { const live2 = exports.__hwjs_drive_abi() | 0; if (live2 !== manifest.driveAbi) { throw new Error( `hwjs-dlopen: lying hwjs.abi manifest \u2014 manifest drive_abi=${manifest.driveAbi} but exports.__hwjs_drive_abi() returned ${live2} (a manifest that contradicts the live probe is a build error; never-silent refuse).` ); } } let ctorsRun = false; let unloaded = false; let exportSigKeys = null; let exportNames = null; const dlsymCache = new XmodInputMap(); if (opts.seedSymbolIndices) { for (const [name2, rawIdx] of opts.seedSymbolIndices) { const idx = rawIdx >>> 0; const sym = exports[name2]; if (typeof sym !== "function") { throw new Error( `hwjs-dlopen: seedSymbolIndices["${name2}"] = ${idx} but the replayed module exports no such function \u2014 the parent recorded an appended slot this artifact cannot back (never-silent)` ); } if (!(idx > 0) || idx >= table.length) { throw new Error( `hwjs-dlopen: seedSymbolIndices["${name2}"] = ${idx} is outside the shared table (length ${table.length}) \u2014 corrupt placement payload (never-silent)` ); } const cur = table.get(idx); if (cur !== null && cur !== sym) { throw new Error( `hwjs-dlopen: seedSymbolIndices["${name2}"] = ${idx} collides with an occupied slot holding a DIFFERENT function \u2014 two recorded appends overlap (never-silent)` ); } tableSet(table, idx, sym); tableLedgerNoteSet(table, idx, sym); tableIndexNote(ix, sym, idx); dlsymCache.set(name2, idx); } } let residentIdx = null; function residentIndexOf(sym) { const ledgered = tableLedgerSlot(table, sym, 1); if (ledgered !== void 0) return ledgered; if (residentIdx === null) { residentIdx = /* @__PURE__ */ new Map(); for (let i = table.length - 1; i >= 1; i--) { const f = table.get(i); if (f !== null) residentIdx.set(f, i); } } const idx = residentIdx.get(sym); return idx === void 0 ? -1 : idx; } function symbolIndex(name2) { const cached = dlsymCache.get(name2); if (cached !== void 0) return cached; const sym = exports[name2]; if (typeof sym !== "function") { dlsymCache.set(name2, 0); return 0; } let resident; if (indexed) { indexOwnAsked = true; const i = indexedSlotOf(sym); resident = i === null ? residentIndexOf(sym) : i > 0 ? i : -1; if (i !== null) { if (resident > 0) linkPlanStats.ownSlot++; else linkPlanStats.ownAbsent++; if (planCheck && ix.exact) { const snap = residentIndexOf(sym); checked(`"${name2}"`, resident, snap === resident ? snap : lowestSlotFrom(sym, Math.max(1, ix.firstBase))); } } } else { resident = residentIndexOf(sym); } if (resident > 0) { dlsymCache.set(name2, resident); return resident; } let idx; try { idx = tableAppend(table, 1); } catch (e) { throw new Error( `hwjs-dlopen: could not grow the shared table for "${name2}" (max reached): ` + (e instanceof Error ? e.message : String(e)) ); } tableSet(table, idx, sym); tableLedgerNoteSet(table, idx, sym); if (residentIdx !== null) residentIdx.set(sym, idx); tableIndexNote(ix, sym, idx); gotPassRecord(sym, idx); dlsymCache.set(name2, idx); return idx; } if (opts.reservedSymbolIndices) { for (const [name2, rawIdx] of opts.reservedSymbolIndices) { const idx = rawIdx >>> 0; const sym = exports[name2]; if (typeof sym !== "function") { throw new Error( `hwjs-dlopen: a sibling reserved shared-table slot ${idx} for "${name2}", but ${opts.soPath || "this module"} exports no such function (never-silent)` ); } if (!(idx > 0) || idx >= table.length || table.get(idx) !== null && table.get(idx) !== sym) { throw new Error( `hwjs-dlopen: the slot ${idx} reserved for "${name2}" is outside the shared table (length ${table.length}) or already occupied (never-silent)` ); } const resident = residentIndexOf(sym); if (resident > 0 && resident !== idx) { throw new Error( `hwjs-dlopen: "${name2}" in ${opts.soPath || "this module"} is already table-resident at ${resident}, but a sibling has baked the reserved slot ${idx} into its data -- one function would have two addresses (never-silent)` ); } tableSet(table, idx, sym); tableLedgerNoteSet(table, idx, sym); if (residentIdx !== null) residentIdx.set(sym, idx); tableIndexNote(ix, sym, idx); dlsymCache.set(name2, idx); } } let dataAddrCache = null; function dataSymbolAddress(name2) { if (dataAddrCache === null) dataAddrCache = /* @__PURE__ */ new Map(); const cached = dataAddrCache.get(name2); if (cached !== void 0) return cached; let addr = 0; const r = findExportedI32Global(wasmBytes, name2); if (r.ok && !r.mutable && !DLOPEN_SIBLING_DATA_RESERVED.has(name2) && !(dylink && dylink.tlsExports.includes(name2)) && r.value <= memorySize) { addr = (memoryBase >>> 0) + r.value >>> 0; } dataAddrCache.set(name2, addr); return addr; } let gotPassActive = false; let gotPassIdx = null; let gotPassLen = 0; let gotPassAppends = 0; function gotPassResidentIndexOf(fn2) { const ledgered = tableLedgerSlot(table, fn2, 0); if (ledgered !== void 0) return ledgered; if (gotPassIdx === null || gotPassLen !== table.length || gotPassAppends !== appendCountOf(table)) { gotPassIdx = /* @__PURE__ */ new Map(); for (let i = table.length - 1; i >= 0; i--) { const f = table.get(i); if (f !== null) gotPassIdx.set(f, i); } gotPassLen = table.length; gotPassAppends = appendCountOf(table); } const idx = gotPassIdx.get(fn2); return idx === void 0 ? -1 : idx; } function gotPassRecord(fn2, idx) { if (gotPassIdx === null) return; const prev = gotPassIdx.get(fn2); if (prev === void 0 || idx < prev) gotPassIdx.set(fn2, idx); gotPassLen = table.length; gotPassAppends = appendCountOf(table); } function patchedSlotOf(fn2) { tableIndexRead(ix, table); for (let i2 = 0; i2 < ix.firstBase; i2++) { if (table.get(i2) === fn2) { linkPlanStats.patchMain++; return i2; } } const i = indexedSlotOf(fn2); if (i === null) return tableIndexOf(table, fn2); if (i >= 0) linkPlanStats.patchSlot++; else linkPlanStats.patchAbsent++; return i; } function mainFunctionTableIndex(name2, fn2, post) { if (typeof fn2 === "function" && typeof fn2.tableTarget === "function") { fn2 = fn2.tableTarget; } let resident; if (gotPassActive) { const i = indexed ? indexedSlotOf(fn2) : null; if (i === null) { resident = gotPassResidentIndexOf(fn2); } else { resident = i; if (i >= 0) linkPlanStats.foreignSlot++; else linkPlanStats.foreignAbsent++; if (planCheck) checked(`the function bound to "${name2}"`, resident, gotPassResidentIndexOf(fn2)); } } else if (indexedLoad && ix.exact && post && post.mainClean === true && post.mainWindowEnd === ix.firstBase) { resident = patchedSlotOf(fn2); if (planCheck) checked(`the function patched into "${name2}"`, resident, tableIndexOf(table, fn2)); } else { ix.exact = false; resident = tableIndexOf(table, fn2); } if (resident >= 0) return resident; const cache = opts.gotFuncIndex; if (!(cache instanceof Map)) { throw new Error( `hwjs-dlopen: GOT.func.${name2} resolves to a MAIN function that is not table-resident, and no PROCESS-wide opts.gotFuncIndex Map was provided \u2014 refusing to append per-handle (two .so's address-taking the same symbol would diverge on its table index, breaking the cross-module coroutine identity; never-silent)` ); } const cached = cache.get(name2); if (cached !== void 0) { if (cached >= table.length) { try { tableGrow(table, cached + 1 - table.length); } catch (e) { throw new Error( `hwjs-dlopen: could not grow the shared table to the seeded GOT.func.${name2} index ${cached} (max reached): ` + (e instanceof Error ? e.message : String(e)) ); } } const cur = table.get(cached); if (cur === null) { tableSet(table, cached, fn2); tableLedgerNoteSet(table, cached, fn2); tableIndexNote(ix, fn2, cached); gotPassRecord(fn2, cached); return cached; } if (cur !== fn2) { throw new Error( `hwjs-dlopen: GOT.func.${name2} identity drift \u2014 the process-wide cache holds shared-table index ${cached} but the resolver now returns a DIFFERENT function object (a per-module wrapped closure?). One symbol must keep ONE table identity across modules (never-silent)` ); } return cached; } let idx; try { idx = tableAppend(table, 1); } catch (e) { throw new Error( `hwjs-dlopen: could not grow the shared table for GOT.func.${name2} (max reached): ` + (e instanceof Error ? e.message : String(e)) ); } tableSet(table, idx, fn2); tableLedgerNoteSet(table, idx, fn2); tableIndexNote(ix, fn2, idx); gotPassRecord(fn2, idx); cache.set(name2, idx); return idx; } let importedFnNames = null; const pendingGotFunc = /* @__PURE__ */ new Map(); gotPassActive = true; for (const [name2, g] of gotFunc) { if (opts.presetGotFunc && opts.presetGotFunc.has(name2)) { g.value = opts.presetGotFunc.get(name2) >>> 0; continue; } if (opts.deferGotFunc && opts.deferGotFunc.has(name2)) { pendingGotFunc.set(name2, g); continue; } if (typeof exports[name2] === "function") { const idx = symbolIndex(name2); if (!(idx > 0)) { throw new Error( `hwjs-dlopen: GOT.func.${name2} resolved to table index ${idx} (never-silent PIC hole)` ); } g.value = idx; continue; } if (!importedFnNames) importedFnNames = importedFunctionNamesOf(module, wasmBytes); const binding = importedFnNames.get(name2); if (binding) { const fn3 = opts.resolveImport ? opts.resolveImport(binding.module, binding.field, "function") : void 0; if (fn3 == null && weakImports && weakImports.has(name2)) { g.value = 0; weakUnbound.push(name2); continue; } if (typeof fn3 !== "function") { throw new Error( `hwjs-dlopen: GOT.func.${name2} -> import ${binding.module}.${binding.field} did not resolve to a function (never-silent)` ); } g.value = mainFunctionTableIndex(name2, fn3); continue; } const fn2 = opts.resolveImport ? opts.resolveImport("env", name2, "function") : void 0; if (fn2 == null && weakImports && weakImports.has(name2)) { g.value = 0; weakUnbound.push(name2); continue; } if (typeof fn2 !== "function") { throw new Error( `hwjs-dlopen: GOT.func.${name2} unresolved \u2014 not a .so export, no imported-function symbol of that name, and the MAIN resolveImport chain provides no env.${name2} function (never-silent PIC hole)` ); } g.value = mainFunctionTableIndex(name2, fn2); } gotPassActive = false; gotPassIdx = null; if (indexed && !indexOwnAsked) indexed = false; let moduleIdAddr = 0; const interposedData = []; for (const [name2, g] of gotMem) { const mainIp = opts.interposeDataAddress ? opts.interposeDataAddress(name2) : void 0; if (!(typeof mainIp === "number" && mainIp >>> 0 > 0) && opts.preemptsData && opts.preemptsData(name2)) { const pre = opts.resolveDataAddress ? opts.resolveDataAddress(name2) : void 0; if (typeof pre !== "number" || !(pre >>> 0 > 0)) { throw new Error( `hwjs-dlopen: GOT.mem.${name2} \u2014 an earlier needed entry exports it, but its address did not resolve (resolveDataAddress -> ${pre}). Refusing rather than binding this module's own copy beside it (never-silent).` ); } g.value = pre | 0; continue; } const sym = exports[name2]; if (sym instanceof WebAssembly.Global) { const ip = opts.interposeDataAddress ? opts.interposeDataAddress(name2) : void 0; if (typeof ip === "number" && ip >>> 0 > 0) { g.value = ip | 0; interposedData.push(name2); continue; } const addr2 = (memoryBase | 0) + (sym.value | 0); if (name2 === "__hwjs_status_channel") { const procAddr = opts.resolveDataAddress ? opts.resolveDataAddress(name2) : void 0; if (typeof procAddr === "number" && procAddr >>> 0 > 0 && procAddr >>> 0 !== addr2 >>> 0) { throw new Error( `hwjs-dlopen: GOT.mem.${name2} LOCKSTEP VIOLATION \u2014 this .so DEFINES its own ${name2} (memoryBase+offset = ${addr2 >>> 0}) while the process already owns one at ${procAddr >>> 0} (contract \xA71: ONE channel block per process, MAIN/rt-owned). The .so was linked with the RT merged in; link it against the RT-import surface instead. Refusing the silent split-brain (two channel blocks = raises invisible to the other side's checks).` ); } } g.value = addr2; if (name2 === "__hwjs_module_id") { if (!(addr2 > 0)) { throw new Error( `hwjs-dlopen: GOT.mem.__hwjs_module_id resolved to addr ${addr2} (memoryBase=${memoryBase}) \u2014 cannot bind the module id into the NULL page (never-silent; the .so must declare data for it)` ); } moduleIdAddr = addr2; } continue; } const addr = opts.resolveDataAddress ? opts.resolveDataAddress(name2) : void 0; if (!(typeof addr === "number" && addr >>> 0 > 0) && weakImports && weakImports.has(name2)) { g.value = 0; weakUnbound.push(name2); continue; } if (typeof addr !== "number" || !(addr >>> 0 > 0)) { throw new Error( `hwjs-dlopen: GOT.mem.${name2} unresolved \u2014 the .so does not define it and the MAIN provides no address-bearing data export of that name (resolveDataAddress -> ${addr}). Refusing the old silent memoryBase+0 resolution (never-silent PIC hole; export the symbol from the dynamic main, e.g. WASMLD_DYN_EXPORT_LIBC)` ); } g.value = addr | 0; } let dataRelocsApplied = false; if (!opts.skipDataRelocs && typeof exports.__wasm_apply_data_relocs === "function") { exports.__wasm_apply_data_relocs(); dataRelocsApplied = true; } const ownsSideTls = !!(manifest && manifest.flags.usesTls && opts.tlsOwner !== true && exports.__tls_size.value >>> 0 > 0); const sideTlsBound = ownsSideTls ? bindSideModuleTls(exports, memory, opts.sideTls, opts.soPath) : 0; if (moduleIdAddr > 0) { new DataView(memory.buffer).setInt32(moduleIdAddr, opts.moduleId | 0, true); } return { module, instance, exports, memoryBase, tableBase, dylink, /* What the module's data segments filled from its file; the process * Worker reports it as file-backed pages. */ dataBytes, /* F86 side-module budget: the per-instance env.__hwjs_budget Global * bound above (null when the .so carries no safepoints) — the driver * refills it alongside the main's accessor at every slice refill. */ budgetGlobal, /* hardwarejs#46: the weak imports bound to null because nothing * provides them, one entry per import or GOT slot. */ weakUnboundImports: weakUnbound, /* bindOwnDefinitions: the env function imports bound to the module's * own export because nothing earlier in the search order provides them. */ ownBoundImports: ownBound, /* Side-module TLS (null when the module owns none, or is libc.so): the * layout, and the live base this Instance's thread uses — what a fork or * migrate record must carry for the next Instance of the same thread. */ tls: ownsSideTls ? { ...sideTlsLayout(exports), base: () => exports.__tls_base.value >>> 0, /* true only for a thread whose TLS arena could not grow: the caller * must refuse the thread before any of its code runs. */ unbound: sideTlsBound === 0 } : null, /* Deferred GOT.func entries (see the deferGotFunc block above): * name -> the live mutable GOT global, still 0. The caller patches * each once the providing module exists; pendingGotFuncNames() is the * never-silent audit surface. */ pendingGotFuncNames() { return [...pendingGotFunc.keys()]; }, patchGotFunc(name2, fn2, post) { const g = pendingGotFunc.get(name2); if (!g) { throw new Error( `hwjs-dlopen: patchGotFunc("${name2}") \u2014 no deferred GOT.func of that name (never deferred, or already patched)` ); } const idx = mainFunctionTableIndex(name2, fn2, post); g.value = idx; pendingGotFunc.delete(name2); return idx; }, /* issue #45 gap 1 witness: whether THIS load ran the .so's * __wasm_apply_data_relocs (false when absent or skipDataRelocs). */ dataRelocsApplied, interposedData, runCtors() { if (ctorsRun) return false; ctorsRun = true; const ctor = exports.__wasm_call_ctors; if (typeof ctor === "function") { ctor(); return true; } return false; }, dlsym(name2) { if (unloaded) { throw new Error(`hwjs-dlopen: dlsym("${name2}") on an unloaded module`); } if (exports[name2] instanceof WebAssembly.Global) { return dataSymbolAddress(name2); } return symbolIndex(name2); }, /* hardwarejs#49: the function half of dlsym alone -- 0 for a data * export -- for the callers that mint a table identity from it. */ dlsymFunction(name2) { if (unloaded) { throw new Error(`hwjs-dlopen: dlsymFunction("${name2}") on an unloaded module`); } if (exports[name2] instanceof WebAssembly.Global) return 0; return symbolIndex(name2); }, /* M2 dlclose census (suspend-across-module dlopen M2): the shared-table * indices this module APPENDED via symbolIndex (dlsym + GOT.func) — the * union with [tableBase, tableBase + dylink.tableSize) is the module's * full table footprint, which the dlclose anomaly guard checks the * parked owner word against. dlsymCache is closure-private; this is the * read-only accessor. */ tableIndices() { const out = []; for (const idx of dlsymCache.values()) { if (idx > 0) out.push(idx); } return out; }, /* Issue #43 placement-aware fork replay: the NAMED appended slots * ([name, index] pairs — the same set tableIndices() reports), shipped * on the fork payload so the child reproduces each append AT its * recorded index (seedSymbolIndices) instead of by append order. */ tableEntries() { const out = []; for (const [name2, idx] of dlsymCache) { if (idx > 0) out.push([name2, idx]); } return out; }, /* A fork child's copy of a slot the parent appended at run time, after * the placement record this module was replayed from (lateTableEntries): * bound at the parent's index once the table has the parent's length. */ adoptSymbolIndex(name2, rawIdx) { const idx = rawIdx >>> 0; const sym = exports[name2]; if (typeof sym !== "function" || !(idx > 0) || idx >= table.length) { throw new Error( `hwjs-dlopen: adoptSymbolIndex("${name2}", ${idx}): the module exports no such function, or the index is outside the shared table (length ${table.length}) (never-silent)` ); } const cur = table.get(idx); if (cur !== null && cur !== sym) { throw new Error( `hwjs-dlopen: adoptSymbolIndex("${name2}", ${idx}): the slot holds a different function (never-silent)` ); } tableSet(table, idx, sym); tableLedgerNoteSet(table, idx, sym); if (residentIdx !== null && !residentIdx.has(sym)) residentIdx.set(sym, idx); tableIndexNote(ix, sym, idx); dlsymCache.set(name2, idx); }, /* The fpcast census sig hash of one of this module's function exports, * from its own type section (0: none) -- xmodExportSigOf. */ exportFpcastSig(name2) { if (exportSigKeys === null) exportSigKeys = exportFpcastSigKeys(wasmBytes); const k = exportSigKeys.get(name2); return k === void 0 ? 0 : fpcastSigHash(k); }, /* The export name a function object of this module is exported under * (undefined: not one of its function exports). */ exportNameOf(fn2) { if (exportNames === null) { exportNames = /* @__PURE__ */ new Map(); for (const [n, v] of Object.entries(exports)) { if (typeof v === "function" && !exportNames.has(v)) exportNames.set(v, n); } } return exportNames.get(fn2); }, unload() { unloaded = true; } }; } function xmodConsultClassify(siteSig, fp, deadRanges, modules2, ownSigOf) { siteSig = siteSig >>> 0; fp = fp >>> 0; for (const d of deadRanges) { if (fp >= d.tableBase && fp < d.tableBase + d.tableSize || Array.isArray(d.appended) && d.appended.includes(fp)) { return { dead: d, live: null, inElem: false, hasRec: false, recOtherSig: false, recAny: false, regRan: false }; } } for (const m of modules2) { const ts = m.handle && m.handle.dylink ? m.handle.dylink.tableSize >>> 0 : 0; const tb = m.tableBase >>> 0; const appended = m.handle && typeof m.handle.tableIndices === "function" ? m.handle.tableIndices() : []; const inElem = fp >= tb && fp < tb + ts; if (!(inElem || appended.includes(fp))) continue; const own2 = typeof ownSigOf === "function" ? ownSigOf(fp) : void 0; const recAny2 = own2 !== void 0 && own2 !== 0; const regRan = !!(m.xmodRecs && m.xmodRecs.size > 0) || !!(m.xmodRegistrar && m.xmodRegistrar.imported === false); return { dead: null, live: m, inElem, hasRec: !!(m.xmodRecs && m.xmodRecs.has(siteSig + ":" + fp)), recOtherSig: recAny2 && own2 >>> 0 !== siteSig, recAny: recAny2, regRan }; } const own = typeof ownSigOf === "function" ? ownSigOf(fp) : void 0; const recAny = own !== void 0 && own !== 0; return { dead: null, live: null, inElem: false, hasRec: false, recOtherSig: recAny && own >>> 0 !== siteSig, recAny, regRan: false }; } function exportFpcastSigKeys(b) { const cls = { "7f": "i", "7e": "j", "7d": "f", "7c": "d" }; const types = [], funcTypes = [], keys = /* @__PURE__ */ new Map(); for (const s of neededViewSections(b)) { if (s.id !== 1 && s.id !== 2 && s.id !== 3 && s.id !== 7) continue; const r = neededViewReader(b, s.body, s.end); if (s.id === 1) { for (let n = r.leb(); n > 0; n--) { if (r.byte() !== 96) return /* @__PURE__ */ new Map(); let ok = true, ps = "", ret = "v"; for (let k = r.leb(); k > 0; k--) { const c = cls[r.valtype()]; if (c) ps += c; else ok = false; } const nr = r.leb(); for (let k = 0; k < nr; k++) { const c = cls[r.valtype()]; if (c) ret = c; else ok = false; } types.push(ok && nr <= 1 ? "F" + ret + ps : null); } } else if (s.id === 2) { for (let n = r.leb(); n > 0; n--) { r.str(); r.str(); const kind = r.byte(); if (kind === 0) funcTypes.push(r.leb()); else if (kind === 1) { r.valtype(); r.limits(); } else if (kind === 2) r.limits(); else if (kind === 3) { r.valtype(); r.byte(); } else if (kind === 4) { r.byte(); r.leb(); } else throw new Error("unknown import kind " + kind); } } else if (s.id === 3) { for (let n = r.leb(); n > 0; n--) funcTypes.push(r.leb()); } else { for (let n = r.leb(); n > 0; n--) { const name2 = r.str(), kind = r.byte(), index = r.leb(); if (kind !== 0) continue; const t = funcTypes[index]; const k = t === void 0 ? null : types[t]; if (k) keys.set(name2, k); } } } return keys; } function fpcastSigHash(key) { let h = 2166136261; for (let i = 0; i < key.length; i++) { h ^= key.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0; } function xmodExportSigOf(fp, table, handles) { fp = fp >>> 0; const hit = xmodDerivedSigs.get(fp); if (hit !== void 0) return hit; let sig = 0; let fn2 = null; try { fn2 = table && fp < table.length ? table.get(fp) : null; } catch (_e) { fn2 = null; } if (typeof fn2 === "function") { for (const h of handles) { if (!h || typeof h.exportNameOf !== "function") continue; const name2 = h.exportNameOf(fn2); if (name2 === void 0) continue; const tb = h.tableBase >>> 0; const ts = h.dylink ? h.dylink.tableSize >>> 0 : 0; if (fp < tb || fp >= tb + ts) sig = h.exportFpcastSig(name2) >>> 0; break; } } xmodDerivedSigs.set(fp, sig); return sig; } function xmodMarshalArmed(module) { return WebAssembly.Module.customSections(module, XMOD_MARSHAL_SECTION).length > 0; } function xmodConsultVerdict(c) { if (c.inDead) return 0; if (!c.inFootprint) { return c.marshal && !c.fromRt && c.recOtherSig ? 2 : 1; } if (c.hasRec) return 1; if (c.fromRt) return 1; if (c.fromMain && !c.inElem) return 1; if (!c.inElem && !c.recAny && c.regRan) return 1; if (c.marshal && c.recOtherSig) return 2; return 0; } function xmodConsultInvalidate() { if (xmodDerivedSigs.size > 0) xmodDerivedSigs.clear(); if (!xmodConsultMissed || !xmodConsultGeneration) return; xmodConsultMissed = false; xmodConsultGenerationValue += 1n; xmodConsultGeneration.value = xmodConsultGenerationValue; } function xmodConsultGenerationGlobal() { if (!xmodConsultGeneration) { xmodConsultGeneration = new WebAssembly.Global( { value: "i64", mutable: true }, xmodConsultGenerationValue ); } return xmodConsultGeneration; } function xmodConsultUncached(miss) { const gen = xmodConsultGenerationGlobal(); return (sig, fp) => { xmodConsultGenerationValue += 1n; gen.value = xmodConsultGenerationValue; return miss(sig, fp); }; } function xmodConsultOwner() { xmodConsultLastOwner = xmodConsultLastOwner + 1 & 536870911; return xmodConsultLastOwner << 3; } function makeXmodConsultCache(miss, id, counted = false) { if (!xmodConsultCacheMemory) { xmodConsultCacheMemory = new WebAssembly.Memory({ initial: XMOD_CONSULT_CACHE_PAGES, maximum: XMOD_CONSULT_CACHE_PAGES }); } const bytes = counted ? XMOD_CONSULT_CACHE_COUNTED_BYTES : XMOD_CONSULT_CACHE_BYTES; let mod = xmodConsultCacheModules.get(bytes); if (!mod) { mod = new WebAssembly.Module(bytes); xmodConsultCacheModules.set(bytes, mod); } const m = (sig, fp) => { xmodConsultMissed = true; return miss(sig, fp); }; const inst = new WebAssembly.Instance(mod, { e: { m, g: xmodConsultGenerationGlobal(), i: id | 0, k: xmodConsultCacheMemory } }); const hits = inst.exports.hits; return { check: inst.exports.check, hits: hits ? () => Number(hits.value) : () => 0 }; } function drivenCtorHandles(exports) { const set = exports ? exports.__hwjs_ctors_defer_set : void 0; const get2 = exports ? exports.__hwjs_ctors_runner : void 0; if (typeof set !== "function" || typeof get2 !== "function") return {}; const runner = get2() >>> 0; return runner === 0 ? {} : { deferSet: set, runner }; } function runDlopenModuleCtors({ exports, runCtors, runners, soname }) { const driven = Array.isArray(runners) ? drivenCtorHandles(exports) : {}; if (!driven.runner) { runCtors(); return false; } driven.deferSet(1); try { runCtors(); } finally { driven.deferSet(0); } runners.push({ runner: driven.runner, soname }); return true; } async function driveCtorRunner({ soname, start, resume, breath, clearReason, wait, dlopen, reason, progress }) { let st = await start() >>> 0; for (; ; ) { if (st === DRIVE_DONE) return; if (st === PARK_PREEMPT && reason && reason() >>> 0 !== 0) { throw new Error( `hwjs-dlopen: a constructor of "${soname}" parked with reason 6 (PREEMPT) and the reason slot still latched (${reason() >>> 0}): the image's user runtime predates HWJS_PARK_PREEMPT (never-silent).` ); } if (st === PARK_NONE || st === PARK_PREEMPT) { await breath(); } else if (st === PARK_RESCHED) { clearReason(); await wait(); } else if (st === PARK_DLOPEN) { await dlopen(); } else { throw new Error( `hwjs-dlopen: a constructor of "${soname}" ` + (st === DRIVE_DONE_LIVE ? "completed with an exception or longjmp still in flight" : `parked with reason ${st}, which a constructor run by dlopen is not serviced for (breaths, preemptions, blocking waits and dlopen are)`) + " (never-silent)." ); } if (progress) progress(); st = await resume() >>> 0; } } function publishNeededCtorsInStart({ table, memory, slotAddr, list }) { const addr = slotAddr >>> 0; const dv = new DataView(memory.buffer); const cap = dv.getUint32(addr, true); if (list.length > cap) { throw new Error( `hwjs-libc: ${list.length} needed libraries defer their ctors to _start but the main's __wasm32_needed_ctors_in_start slot holds ${cap} \u2014 refusing to drop any (never-silent).` ); } if (list.length === 0) return []; const isDriven = (d) => typeof d.deferSet === "function" && d.runner >>> 0 !== 0; const driven = list.length + list.filter(isDriven).length <= cap; const base = table.length >>> 0; tableGrow(table, list.length); let n = 0; const indices = list.map((d, i) => { const run2 = driven && isDriven(d); const fn2 = neededCtorTrampoline(d.ctor, run2 ? d.deferSet : null); tableSet(table, base + i, fn2); tableLedgerNoteSet(table, base + i, fn2); dv.setUint32(addr + 8 + 4 * n++, base + i >>> 0, true); if (run2) dv.setUint32(addr + 8 + 4 * n++, d.runner >>> 0, true); return base + i; }); dv.setUint32(addr + 4, n >>> 0, true); Object.defineProperty(indices, "driven", { value: driven }); return indices; } function neededCtorTrampoline(ctor, deferSet) { if (!neededCtorTrampolineModule) { neededCtorTrampolineModule = new WebAssembly.Module(NEEDED_CTOR_TRAMPOLINE_BYTES); } return new WebAssembly.Instance(neededCtorTrampolineModule, { e: { s: () => { if (deferSet) deferSet(1); }, c: ctor, z: () => { if (deferSet) deferSet(0); } } }).exports.r; } function replaceNeededCtorTrampolines({ table, records, resolve }) { if (!Array.isArray(records) || records.length === 0) return 0; const top = Math.max(...records.map((r) => (r.index >>> 0) + 1)); if (table.length >>> 0 < top) tableGrow(table, top - (table.length >>> 0)); for (const r of records) { const index = r.index >>> 0; const what = `needed ctor trampoline of ${r.soname} (entry ${r.entry}) at table ${index}`; if (table.get(index) !== null) { throw new Error(`hwjs-libc: ${what}: the slot is already taken on this Worker -- the rebuilt table diverged from the publisher's (never-silent).`); } const exports = resolve(r.entry >>> 0); const ctor = exports ? exports.__wasm_call_ctors : void 0; if (typeof ctor !== "function") { throw new Error(`hwjs-libc: ${what}: the library is not loaded here or exports no __wasm_call_ctors (never-silent).`); } let deferSet = null; if (r.run) { deferSet = drivenCtorHandles(exports).deferSet; if (typeof deferSet !== "function") { throw new Error(`hwjs-libc: ${what}: published driven but the library here has no __hwjs_ctors_defer_set (never-silent).`); } } const fn2 = neededCtorTrampoline(ctor, deferSet); tableSet(table, index, fn2); tableLedgerNoteSet(table, index, fn2); } return records.length; } function heapChargePublish() { if (heapChargeWords === null) return; Atomics.store(heapChargeWords, heapChargeSlot, HEAP_REALM_BASE_KIB + Math.max(0, heapInstancesKiB)); } function heapChargeBind(sab, slot) { if (!(sab instanceof SharedArrayBuffer) || !Number.isInteger(slot)) return; if (slot < 0 || slot << 2 >= sab.byteLength) return; heapChargeWords = new Int32Array(sab); heapChargeSlot = slot; heapChargePublish(); } function heapChargeInstance(instance, module) { if (heapInstanceFinalizer === null || instance === null || typeof instance !== "object") return; let kib = heapInstanceCosts.get(module); if (kib === void 0) { let n = 0; try { n = moduleImportsOf(module).length + moduleExportsOf(module).length; } catch (_e) { n = 0; } kib = HEAP_INSTANCE_BASE_KIB + Math.ceil(n / 2); heapInstanceCosts.set(module, kib); } heapInstancesKiB += kib; heapInstanceFinalizer.register(instance, kib); heapChargePublish(); } function collectGarbageNow() { const g = globalThis.gc; if (typeof g === "function") { try { g(); } catch (_e) { } return true; } if (heapIsNode) return false; try { new ArrayBuffer(HEAP_COLLECT_PROBE_BYTES); } catch (_e) { } return true; } var WASM_DYLINK_MEM_INFO, WASM_DYLINK_NEEDED, WASM_DYLINK_EXPORT_INFO, WASM_DYLINK_IMPORT_INFO, WASM_SYMBOL_BINDING_MASK, WASM_SYMBOL_BINDING_WEAK, WASM_SYMBOL_TLS, __sharedWasmSourceOk, __dynLoaderDecoder, importedFunctionNamesByModule, moduleFactsByModule, moduleKeptByModule, PACKED_KINDS, neededExportersRoot, LINK_FACTS_FORMAT, linkFactsStore, DLSYM_RTLD_DEFAULT, DLSYM_RTLD_NEXT, DLSYM_CALLER_IMPORTS, PRELOAD_LIBC_ALLOCATOR, DLOPEN_SIBLING_DATA_RESERVED, NEEDED_STD_NAME, HWJS_RT_BRK_RESERVE, HWJS_RT_WINDOW_SIZE, HWJS_RT_PAGE, HWJS_RT_STACK_CARVE, HWJS_ROOT_DATA, HWJS_ROOT_STACK, HWJS_ROOT_ARENA, HWJS_ROOT_RECORD_BYTES, HWJS_LIBC_WINDOW_SIZE, FILL_MODULE_BYTES, SHA256_K, SHA256_WASM_CHUNK, wasmSha256, SHA256_ABC, hostSha256, RETAINED_NAME2, RETAINED_MARKER_BYTES2, RETAINED_DATA_NAME2, RETAINED_DATA_BYTES2, TABLE_WRITES_NAME2, TABLE_WRITES_BYTES2, TABLE_WRITES_CODES2, SoModuleCache, RT_DRIVE_ENTRY_OPS, TERMINUS_HOOK, NEEDED_VIEW_IMPORT_MODULES, SIDE_TLS_EXPORTS, MAIN_TLS_BRK_BYTES, MAIN_TLS_CARVE_BYTES, tableLedgers, TABLE_LEDGER_VERIFY, tableIndexes, tableProtoSet, tableProtoGrow, slotAllocators, planRegions, appendCounts, linkPlanReport, linkPlanTold, linkPlanStats, xmodDerivedSigs, XMOD_MARSHAL_SECTION, XMOD_CONSULT_CACHE_PAGES, XMOD_CONSULT_CACHE_BYTES, XMOD_CONSULT_CACHE_COUNTED_BYTES, xmodConsultCacheModules, xmodConsultCacheMemory, xmodConsultGeneration, xmodConsultGenerationValue, xmodConsultMissed, xmodConsultLastOwner, XMOD_CONSULT_GEN_IMPORT, XmodInputMap, XmodInputSet, NEEDED_CTOR_TRAMPOLINE_BYTES, neededCtorTrampolineModule, DRIVE_DONE, DRIVE_DONE_LIVE, PARK_NONE, PARK_DLOPEN, PARK_RESCHED, PARK_PREEMPT, HEAP_REALM_BASE_KIB, HEAP_INSTANCE_BASE_KIB, heapChargeWords, heapChargeSlot, heapInstancesKiB, heapInstanceCosts, heapInstanceFinalizer, HEAP_COLLECT_PROBE_BYTES, heapIsNode; var init_dynLoader = __esm({ "../../linux-in-the-browser/hardwarejs/src/dynLoader.mjs"() { "use strict"; WASM_DYLINK_MEM_INFO = 1; WASM_DYLINK_NEEDED = 2; WASM_DYLINK_EXPORT_INFO = 3; WASM_DYLINK_IMPORT_INFO = 4; WASM_SYMBOL_BINDING_MASK = 3; WASM_SYMBOL_BINDING_WEAK = 1; WASM_SYMBOL_TLS = 1024; __dynLoaderDecoder = new TextDecoder(); importedFunctionNamesByModule = /* @__PURE__ */ new WeakMap(); moduleFactsByModule = /* @__PURE__ */ new WeakMap(); moduleKeptByModule = /* @__PURE__ */ new WeakMap(); PACKED_KINDS = ["function", "table", "memory", "global", "tag"]; neededExportersRoot = { next: /* @__PURE__ */ new WeakMap(), maps: null }; LINK_FACTS_FORMAT = 1; linkFactsStore = null; DLSYM_RTLD_DEFAULT = 0; DLSYM_RTLD_NEXT = 4294967295; DLSYM_CALLER_IMPORTS = /* @__PURE__ */ new Set(["dlsym", "dlvsym"]); PRELOAD_LIBC_ALLOCATOR = /* @__PURE__ */ new Set([ "malloc", "free", "calloc", "realloc", "reallocarray", "posix_memalign", "aligned_alloc", "memalign", "valloc", "pvalloc", "malloc_usable_size", "free_sized", "free_aligned_sized", "cfree" ]); DLOPEN_SIBLING_DATA_RESERVED = /* @__PURE__ */ new Set([ "__stack_pointer", "__tls_base", "__tls_size", "__tls_align", "__memory_base", "__table_base", "__heap_base", "__heap_end", "__data_end", "__dso_handle", "__global_base" ]); NEEDED_STD_NAME = /^_Z(T[IVSTC]|G[VR]|Z|T[hv](n?[0-9]+_)+)?N?K?St/; HWJS_RT_BRK_RESERVE = 1 * 1024 * 1024; HWJS_RT_WINDOW_SIZE = 8 * 1024 * 1024; HWJS_RT_PAGE = 4096; HWJS_RT_STACK_CARVE = 64 * 1024; HWJS_ROOT_DATA = 1; HWJS_ROOT_STACK = 2; HWJS_ROOT_ARENA = 3; HWJS_ROOT_RECORD_BYTES = 16; HWJS_LIBC_WINDOW_SIZE = 16 * 1024 * 1024; FILL_MODULE_BYTES = new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 6, 1, 96, 2, 127, 127, 0, 2, 11, 1, 1, 101, 1, 109, 2, 3, 0, 128, 128, 4, 3, 2, 1, 0, 7, 5, 1, 1, 122, 0, 0, 10, 13, 1, 11, 0, 32, 0, 65, 0, 32, 1, 252, 11, 0, 11 ]); SHA256_K = new Uint32Array([ 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298 ]); SHA256_WASM_CHUNK = 1 << 18; SHA256_ABC = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; RETAINED_NAME2 = "hwjs.retained"; RETAINED_MARKER_BYTES2 = 2 + 1 + RETAINED_NAME2.length + 4 + 32; RETAINED_DATA_NAME2 = "hwjs.retained.data"; RETAINED_DATA_BYTES2 = 2 + 1 + RETAINED_DATA_NAME2.length + 4; TABLE_WRITES_NAME2 = "hwjs.tablewrites"; TABLE_WRITES_BYTES2 = 2 + 1 + TABLE_WRITES_NAME2.length + 1; TABLE_WRITES_CODES2 = ["none", "writes", "unknown"]; SoModuleCache = class { /** * @param {number} max entries kept; the least recently used goes first * @param {(bytes: Uint8Array) => string} contentKey must cover the length * @param {(bytes: Uint8Array) => string} [digestOf] SHA-256, lowercase hex */ constructor(max, contentKey, digestOf = sha256Hex) { this.max = max; this.contentKey = contentKey; this.digestOf = digestOf; this.entries = []; } get size() { return this.entries.length; } /** * @param {Uint8Array} bytes * @param {string} [digest] the SHA-256 these bytes are held under * @returns {string} the key these bytes are logged and looked up under */ keyOf(bytes, digest) { return digest !== void 0 ? `sha256:${digest}` : this.contentKey(bytes); } /** * @param {Uint8Array} bytes * @param {string} [digest] the SHA-256 these bytes are held under * @returns {{ key: string, module?: WebAssembly.Module, id: object }} * `module` on a hit. On a miss, compile and hand `id` to add(). */ find(bytes, digest) { const len = bytes.length; const id = { len, digest, content: void 0 }; let e; if (digest !== void 0) { e = this.entries.find((x) => x.digest === digest); if (!e) { const byContent = this.entries.filter( (x) => x.digest === void 0 && x.len === len ); if (byContent.length > 0) { id.content = this.contentKey(bytes); e = byContent.find((x) => x.content === id.content); if (e) e.digest = digest; } } } else { id.content = this.contentKey(bytes); e = this.entries.find((x) => x.content === id.content); if (!e) { const byDigest = this.entries.filter( (x) => x.content === void 0 && x.len === len ); if (byDigest.length > 0) { id.digest = this.digestOf(bytes); e = byDigest.find((x) => x.digest === id.digest); if (e) e.content = id.content; } } } const key = digest !== void 0 ? `sha256:${digest}` : id.content; if (!e) return { key, id }; this.entries.splice(this.entries.indexOf(e), 1); this.entries.push(e); return { key, module: e.module, id }; } /** * @param {object} id what find() returned for the bytes just compiled * @param {WebAssembly.Module} module */ add(id, module) { this.entries.push({ len: id.len, digest: id.digest, content: id.content, module }); if (this.entries.length > this.max) this.entries.shift(); } }; RT_DRIVE_ENTRY_OPS = /* @__PURE__ */ new Set(["__hwjs_drive", "__hwjs_drive_resume"]); TERMINUS_HOOK = "__hwjs_uncaught_unwinding"; NEEDED_VIEW_IMPORT_MODULES = /* @__PURE__ */ new Set(["env", "GOT.func", "GOT.mem"]); SIDE_TLS_EXPORTS = Object.freeze( ["__tls_base", "__tls_size", "__tls_align", "__wasm_init_tls"] ); MAIN_TLS_BRK_BYTES = 1 * 1024 * 1024; MAIN_TLS_CARVE_BYTES = MAIN_TLS_BRK_BYTES >>> 1; tableLedgers = /* @__PURE__ */ new WeakMap(); TABLE_LEDGER_VERIFY = (globalThis.process?.env?.HWJS_TABLE_LEDGER_VERIFY || "") === "1"; tableIndexes = /* @__PURE__ */ new WeakMap(); tableProtoSet = typeof WebAssembly === "object" ? WebAssembly.Table.prototype.set : void 0; tableProtoGrow = typeof WebAssembly === "object" ? WebAssembly.Table.prototype.grow : void 0; slotAllocators = /* @__PURE__ */ new WeakMap(); planRegions = /* @__PURE__ */ new WeakMap(); appendCounts = /* @__PURE__ */ new WeakMap(); linkPlanReport = null; linkPlanTold = /* @__PURE__ */ new Set(); linkPlanStats = { indexedLoads: 0, snapshotLoads: 0, ownSlot: 0, ownAbsent: 0, foreignSlot: 0, foreignAbsent: 0, patchMain: 0, patchSlot: 0, patchAbsent: 0, readBackFailed: 0, /* An index ended by a write the table's own set()/grow() caught (not * by a tableIndexForget), and, when traceForget is set, where the * first one came from. */ forgotten: 0, traceForget: false, forgottenBy: "" }; xmodDerivedSigs = /* @__PURE__ */ new Map(); XMOD_MARSHAL_SECTION = "hwjs.xmod_marshal"; XMOD_CONSULT_CACHE_PAGES = 4; XMOD_CONSULT_CACHE_BYTES = new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 7, 1, 96, 2, 127, 127, 1, 127, 2, 29, 4, 1, 101, 1, 109, 0, 0, 1, 101, 1, 103, 3, 126, 1, 1, 101, 1, 105, 3, 127, 0, 1, 101, 1, 107, 2, 1, 4, 4, 3, 2, 1, 0, 7, 9, 1, 5, 99, 104, 101, 99, 107, 0, 1, 10, 125, 1, 123, 2, 2, 127, 1, 126, 35, 0, 33, 4, 32, 0, 32, 1, 115, 35, 1, 115, 65, 177, 243, 221, 241, 121, 108, 65, 19, 118, 65, 5, 116, 34, 2, 40, 2, 0, 32, 0, 70, 32, 2, 40, 2, 4, 32, 1, 70, 113, 32, 2, 40, 2, 8, 35, 1, 70, 113, 32, 2, 41, 3, 16, 32, 4, 81, 113, 4, 64, 32, 2, 40, 2, 12, 15, 11, 32, 0, 32, 1, 16, 0, 34, 3, 4, 64, 32, 2, 32, 0, 54, 2, 0, 32, 2, 32, 1, 54, 2, 4, 32, 2, 35, 1, 54, 2, 8, 32, 2, 32, 3, 54, 2, 12, 32, 2, 32, 4, 55, 3, 16, 11, 32, 3, 11 ]); XMOD_CONSULT_CACHE_COUNTED_BYTES = new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 7, 1, 96, 2, 127, 127, 1, 127, 2, 29, 4, 1, 101, 1, 109, 0, 0, 1, 101, 1, 103, 3, 126, 1, 1, 101, 1, 105, 3, 127, 0, 1, 101, 1, 107, 2, 1, 4, 4, 3, 2, 1, 0, 6, 6, 1, 126, 1, 66, 0, 11, 7, 16, 2, 5, 99, 104, 101, 99, 107, 0, 1, 4, 104, 105, 116, 115, 3, 2, 10, 133, 1, 1, 130, 1, 2, 2, 127, 1, 126, 35, 0, 33, 4, 32, 0, 32, 1, 115, 35, 1, 115, 65, 177, 243, 221, 241, 121, 108, 65, 19, 118, 65, 5, 116, 34, 2, 40, 2, 0, 32, 0, 70, 32, 2, 40, 2, 4, 32, 1, 70, 113, 32, 2, 40, 2, 8, 35, 1, 70, 113, 32, 2, 41, 3, 16, 32, 4, 81, 113, 4, 64, 35, 2, 66, 1, 124, 36, 2, 32, 2, 40, 2, 12, 15, 11, 32, 0, 32, 1, 16, 0, 34, 3, 4, 64, 32, 2, 32, 0, 54, 2, 0, 32, 2, 32, 1, 54, 2, 4, 32, 2, 35, 1, 54, 2, 8, 32, 2, 32, 3, 54, 2, 12, 32, 2, 32, 4, 55, 3, 16, 11, 32, 3, 11 ]); xmodConsultCacheModules = /* @__PURE__ */ new Map(); xmodConsultCacheMemory = null; xmodConsultGeneration = null; xmodConsultGenerationValue = 1n; xmodConsultMissed = false; xmodConsultLastOwner = 0; XMOD_CONSULT_GEN_IMPORT = "__hwjs_xmod_consult_gen"; XmodInputMap = class extends Map { constructor(entries) { super(entries); xmodConsultInvalidate(); } set(k, v) { xmodConsultInvalidate(); return super.set(k, v); } delete(k) { xmodConsultInvalidate(); return super.delete(k); } clear() { xmodConsultInvalidate(); super.clear(); } }; XmodInputSet = class extends Set { constructor(values) { super(values); xmodConsultInvalidate(); } add(v) { xmodConsultInvalidate(); return super.add(v); } delete(v) { xmodConsultInvalidate(); return super.delete(v); } clear() { xmodConsultInvalidate(); super.clear(); } }; NEEDED_CTOR_TRAMPOLINE_BYTES = new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 2, 19, 3, 1, 101, 1, 115, 0, 0, 1, 101, 1, 99, 0, 0, 1, 101, 1, 122, 0, 0, 3, 2, 1, 0, 7, 5, 1, 1, 114, 0, 3, 10, 10, 1, 8, 0, 16, 0, 16, 1, 16, 2, 11 ]); neededCtorTrampolineModule = null; DRIVE_DONE = 53406; DRIVE_DONE_LIVE = 53407; PARK_NONE = 0; PARK_DLOPEN = 3; PARK_RESCHED = 4; PARK_PREEMPT = 6; HEAP_REALM_BASE_KIB = 24 * 1024; HEAP_INSTANCE_BASE_KIB = 16; heapChargeWords = null; heapChargeSlot = -1; heapInstancesKiB = 0; heapInstanceCosts = /* @__PURE__ */ new WeakMap(); heapInstanceFinalizer = typeof FinalizationRegistry === "function" ? new FinalizationRegistry((kib) => { heapInstancesKiB -= kib; heapChargePublish(); }) : null; HEAP_COLLECT_PROBE_BYTES = 2 ** 35 - 65536; heapIsNode = typeof process !== "undefined" && !!(process.versions && process.versions.node); } }); // ../../linux-in-the-browser/hardwarejs/src/hwjsTcb.mjs function hasTcbRuntime(exports) { return !!exports && typeof exports.__hwjs_tcb_field === "function" && typeof exports.__hwjs_tcb_bind === "function" && typeof exports.__hwjs_thread_attach === "function"; } function imageRuntimeRefusal(names) { if (names.has("asyncify_start_unwind")) { return "the image is Asyncify-instrumented (exports asyncify_start_unwind): the Asyncify substrate is retired and this runtime cannot drive it; relink the program with the current toolchain"; } if (names.has("__hwjs_take_parked") && !(names.has("__hwjs_tcb_field") && names.has("__hwjs_tcb_bind") && names.has("__hwjs_thread_attach"))) { return NO_TCB_RUNTIME_WHY; } return ""; } function readTcbLayout(exports) { const abi = exports.__hwjs_tcb_field(TCBF.ABI) >>> 0; if (abi !== HWJS_TCB_ABI) { throw new Error( `hwjs-tcb: the image's user runtime answers thread-block ABI ${abi}, this host reads ABI ${HWJS_TCB_ABI} \u2014 a kernel/host pair from different builds (the runtime ships inside the kernel; deploy them together). Refusing to read thread state at guessed offsets.` ); } const layout = { size: exports.__hwjs_tcb_field(TCBF.SIZE) >>> 0 }; for (const [name2, id] of Object.entries(TCBF)) { if (name2 === "ABI" || name2 === "SIZE") continue; const off = exports.__hwjs_tcb_field(id) >>> 0; if (off === 4294967295) { throw new Error( `hwjs-tcb: the image's user runtime does not know thread-block field ${name2} (id ${id}) at ABI ${abi} \u2014 a runtime older than its ABI word says. Refusing.` ); } layout[name2] = off; } return Object.freeze(layout); } function tcbResult(rc) { const s = rc | 0; if (s < 0 && s >= -4095) return { errno: -s, addr: 0 }; return { errno: 0, addr: rc >>> 0 }; } function listThreadBlocks(exports) { const out = []; if (typeof exports.__hwjs_thread_first !== "function") return out; const bound = (typeof exports.__hwjs_thread_count === "function" ? exports.__hwjs_thread_count() >>> 0 : 0) + 1 | 0; for (let a = exports.__hwjs_thread_first() >>> 0; a !== 0 && out.length <= bound; a = exports.__hwjs_thread_next(a) >>> 0) { out.push(a); } return out; } var HWJS_TCB_ABI, TCBF, TCB_STATE, NO_TCB_RUNTIME_WHY, TCB_EBUSY, TCB_ERESTART, tcbRetryable; var init_hwjsTcb = __esm({ "../../linux-in-the-browser/hardwarejs/src/hwjsTcb.mjs"() { "use strict"; HWJS_TCB_ABI = 1; TCBF = Object.freeze({ ABI: 0, SIZE: 1, CHANNEL: 2, ID: 3, STATE: 4, PARKED: 5, PARKED_OWNER: 6, PARK_REASON: 7, PARK_RESULT: 8, STW_ACK: 9, STW_INSLICE: 10, FRAME_LIVE: 11, FRAME_HIGH_WATER: 12, FRAME_ALLOCS: 13, VIOLATION_PENDING: 14, VIOLATION_BUF: 15, USER_INSLICE: 16, PROGRESS_VIOLATIONS: 17, NEXT: 18, MAGIC: 19 }); TCB_STATE = Object.freeze({ FREE: 0, LIVE: 1 }); NO_TCB_RUNTIME_WHY = "the image carries a user runtime that keeps no per-thread blocks (no __hwjs_tcb_field / __hwjs_thread_attach) \u2014 it was linked against a runtime from before 2026-10-10, whose per-lane arrays this host no longer binds. Relink the image against the current runtime."; TCB_EBUSY = 16; TCB_ERESTART = 517; tcbRetryable = (errno) => errno === TCB_EBUSY || errno === TCB_ERESTART; } }); // ../../linux-in-the-browser/hardwarejs/src/uaccessBoundary.mjs 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: refuse3, context, redPark } = opts; if (typeof refuse3 !== "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) { refuse3( `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 = (fn2) => { parkedSlotReader = fn2; }; const inLeafCrossing = () => leafDepth > 0; if (!userMemory) { const kthreadBug = (name2) => (...args) => { refuse3( `uaccess-leaf-witness REFUSAL [${context}]: linux.${name2}(${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.${name2}`); }; 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 = (name2, msg) => { refuse3(`uaccess-leaf-witness REFUSAL [${context}]: linux.${name2}: ${msg}`); throw new Error(`uaccess kernel-side bug: linux.${name2}`); }; const leaf = (name2, body) => (a0, a1, a2) => { const slotBefore = parkedSlotReader ? parkedSlotReader() : 0; leafDepth++; try { if (redPark) { if (!guardedPark) { refuse3( `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) { refuse3( `uaccess-leaf-witness REFUSAL [${context}]: parked slot changed across linux.${name2} (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 }; } var UACCESS_LEAF_IMPORTS, PARKING_IMPORT_NAMESPACE; var init_uaccessBoundary = __esm({ "../../linux-in-the-browser/hardwarejs/src/uaccessBoundary.mjs"() { "use strict"; UACCESS_LEAF_IMPORTS = Object.freeze([ "raw_copy_to_user", "raw_copy_from_user", "raw_clear_user" ]); PARKING_IMPORT_NAMESPACE = "hwjs_suspend"; } }); // ../../linux-in-the-browser/hardwarejs/src/wasmJit.mjs function randomBelow(n) { const u = new Uint32Array(1); try { globalThis.crypto.getRandomValues(u); } catch (_e) { u[0] = Math.floor(Math.random() * 2 ** 32); } return u[0] % n; } function nextEpoch(cpuId) { if (epochTag < 0) { epochTag = Number.isInteger(cpuId) && cpuId >= 0 && cpuId <= 128 ? cpuId : 129 + randomBelow(127); epochSeq = randomBelow(EPOCH_SEQ_LIMIT >>> 1); } let reseeded = false; if (epochSeq + 1 >= EPOCH_SEQ_LIMIT) { epochSeq = randomBelow(EPOCH_SEQ_LIMIT >>> 1); reseeded = true; } epochSeq++; return { epoch: (epochSeq << 8 | epochTag) >>> 0, reseeded }; } function wasmJitFeatures() { if (featureBits >= 0) return featureBits; let f = 0; try { if (WebAssembly.validate(RETURN_CALL_PROBE)) f |= WASM_JIT_FEATURE_RETURN_CALL; } catch (_e) { } try { if (WebAssembly.validate(SIMD128_PROBE)) f |= WASM_JIT_FEATURE_SIMD128; } catch (_e) { } return featureBits = f; } function nm(s) { return /^[\x21-\x7e]{1,64}$/.test(s) ? s : JSON.stringify(s.length > 64 ? s.slice(0, 64) + "\u2026" : s); } function wasmJitCleanText(s, cap = ENGINE_TEXT_CAP) { let t = String(s); if (t.length > cap) t = t.slice(0, cap) + "\u2026"; return t.replace(UNSAFE_CHARS, (c) => { const u = c.charCodeAt(0); return u > 255 ? `\\u${u.toString(16).padStart(4, "0")}` : `\\x${u.toString(16).padStart(2, "0")}`; }); } function sigIndex(b, at, end, allowed) { outer: for (let k = 0; k < allowed.length; k++) { const s = allowed[k]; if (at + s.length > end) continue; for (let j = 0; j < s.length; j++) if (b[at + j] !== s[j]) continue outer; return k; } return -1; } function typeText(b, at, end, note = null) { if (at >= end) return "(truncated)"; if (b[at] !== 96) return `(form 0x${b[at].toString(16)})`; let p = at + 1; const sides = []; for (let side = 0; side < 2; side++) { const n = rdU32(b, p, end); if (n < 0) return "(truncated)"; const count = RV; if (note && n - p > lebLen(count)) note.overlong = true; p = n; if (count > 16) return `(a function type of ${count} ${side ? "results" : "params"})`; const vts = []; for (let k = 0; k < count; k++) { if (p >= end) return "(truncated)"; const vt = b[p++]; if (vt !== 99 && vt !== 100) { vts.push(VALTYPE_NAME[vt] ?? `0x${vt.toString(16)}`); continue; } if (p >= end) return "(truncated)"; let ht; if (b[p] < 128 && b[p] & 64) { ht = HEAPTYPE_NAME[b[p]] ?? `heap type 0x${b[p].toString(16)}`; p++; } else { const q = rdU32(b, p, end); if (q < 0) return "(truncated)"; ht = `type ${RV}`; p = q; } vts.push(`(ref ${vt === 99 ? "null " : ""}${ht})`); } sides.push(vts); } return `(${sides[0].join(",")})->${sides[1].length === 1 ? sides[1][0] : `(${sides[1].join(",")})`}`; } function typeRefusal(i, b, at, end, allowed) { const note = { overlong: false }; const text = typeText(b, at, end, note); if (note.overlong) { for (const s of allowed) { if (typeText(s, 0, s.length) === text) { return `type ${i} ${text} is encoded non-canonically (a count in a longer LEB128 than its value needs); allowed signatures are matched byte for byte, in their shortest encoding`; } } } return `type ${i} ${text} is not an allowed signature${note.overlong ? " (and is encoded non-canonically)" : ""}: only ${WASM_JIT_ENTRY_SIG}, ()->() and the ${allowed.length - 2} registered helper signature(s) (a signature the engine has not seen is canonicalized process-wide and never freed)`; } function walkModule(b, allowed) { const st = { p: 0 }; const byte = (end) => { if (st.p >= end) throw new Malformed(`truncated at byte ${st.p}`); return b[st.p++]; }; const u32 = (end) => { let r = 0; for (let shift = 0; ; shift += 7) { if (st.p >= end) throw new Malformed(`truncated at byte ${st.p}`); const x = b[st.p++]; if (shift === 28 && (x & 240) !== 0) throw new Malformed(`u32 LEB128 out of range at byte ${st.p - 1}`); r |= (x & 127) << shift; if ((x & 128) === 0) return r >>> 0; } }; const name2 = (end) => { const n = u32(end); if (st.p + n > end) throw new Malformed(`name of ${n} bytes runs past its section at byte ${st.p}`); const s = UTF8.decode(b.subarray(st.p, st.p + n)); st.p += n; return s; }; const limits = (end, maxFlags, what, whose) => { const flags = byte(end); if (flags > maxFlags) { throw new Refused(EPERM, `import ${what} declares limits flags 0x${flags.toString(16)}; only a 32-bit ${whose} can bind the process ${whose}`); } u32(end); if (flags & 1) u32(end); }; if (b.length < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) { throw new Malformed("no \\0asm magic"); } if (b[4] !== 1 || b[5] !== 0 || b[6] !== 0 || b[7] !== 0) { throw new Malformed(`binary version ${b[4] | b[5] << 8 | b[6] << 16 | b[7] << 24} (only 1)`); } const typeAt = []; const typeIsEntry = []; const funcTypes = []; const exports = []; let sawMemory = false, sawTable = false; let codeAt = -1, codeEnd = -1; let lastId = 0; st.p = 8; while (st.p < b.length) { const id = byte(b.length); const size = u32(b.length); const start = st.p, end = start + size; if (end > b.length) throw new Malformed(`section id ${id} declares ${size} bytes, ${b.length - start} remain`); if (!ALLOWED_SECTIONS.has(id)) { throw new Refused(EPERM, `section id ${id} (${SECTION_NAME[id] ?? "unknown"}) is not allowed; only {0,1,2,3,7,10} (custom, type, import, function, export, code)`); } if (id !== 0) { if (id <= lastId) { throw new Malformed(`section id ${id} (${SECTION_NAME[id]}) follows section id ${lastId}: out of order or repeated`); } lastId = id; } if (id === 1) { const count = u32(end); if (count > WASM_JIT_MAX_TYPES) { throw new Refused(E2BIG, `the module declares ${count} types > ${WASM_JIT_MAX_TYPES} per INSTALL`); } for (let i = 0; i < count; i++) { const at = st.p; const k = sigIndex(b, at, end, allowed); if (k < 0) throw new Refused(EPERM, typeRefusal(i, b, at, end, allowed)); typeAt.push(at); typeIsEntry.push(k === 0); st.p = at + allowed[k].length; } } else if (id === 2) { const count = u32(end); for (let i = 0; i < count; i++) { const mod = name2(end), field = name2(end), kind = byte(end); const what = `${nm(mod)}.${nm(field)} (${KIND_NAME[kind] ?? `kind 0x${kind.toString(16)}`})`; if (mod === "env" && field === "user_memory" && kind === 2) { limits(end, 3, what, "memory"); if (sawMemory) throw new Refused(EPERM, `import ${what} appears twice`); sawMemory = true; } else if (mod === "env" && field === WASM_JIT_TABLE_IMPORT && kind === 1) { const ref = byte(end); if (ref !== 112) { throw new Refused(EPERM, `import ${what} has element type 0x${ref.toString(16)}; only funcref (0x70)`); } limits(end, 1, what, "table"); if (sawTable) throw new Refused(EPERM, `import ${what} appears twice`); sawTable = true; } else if (mod === "env" && field === "__indirect_function_table") { throw new Refused(EPERM, `import ${what} is not allowed: generated code never binds the process table (every function of the image would be one call_indirect away); import env.${WASM_JIT_TABLE_IMPORT}, which holds the registered helpers and this record's regions`); } else { throw new Refused(EPERM, `import ${what} is not allowed; only env.user_memory (memory) and env.${WASM_JIT_TABLE_IMPORT} (funcref table)`); } } } else if (id === 3) { const count = u32(end); if (count > WASM_JIT_MAX_FUNCS) { throw new Refused(E2BIG, `the module defines ${count} functions > ${WASM_JIT_MAX_FUNCS} per INSTALL`); } for (let i = 0; i < count; i++) funcTypes.push(u32(end)); } else if (id === 7) { const count = u32(end); if (count > WASM_JIT_MAX_FUNCS) { throw new Refused(E2BIG, `the module declares ${count} exports > ${WASM_JIT_MAX_FUNCS} per INSTALL`); } for (let i = 0; i < count; i++) { const len = u32(end), at = st.p; if (at + len > end) throw new Malformed(`name of ${len} bytes runs past its section at byte ${at}`); st.p += len; const kind = byte(end), index = u32(end); exports.push({ at, len, fi: fIndexOf(b, at, len), kind, index }); } } else if (id === 10) { const count = u32(end); if (count !== funcTypes.length) { throw new Malformed(`the code section holds ${count} bodies for ${funcTypes.length} functions`); } codeAt = start; codeEnd = end; } st.p = end; } if (funcTypes.length > 0 && codeAt < 0) { throw new Malformed(`${funcTypes.length} functions and no code section`); } return { typeAt, typeIsEntry, funcTypes, exports, codeAt, codeEnd }; } function fIndexOf(b, at, len) { if (len < 2 || len > 10 || b[at] !== 102 || b[at + 1] === 48 && len > 2) return -1; let v = 0; for (let k = at + 1; k < at + len; k++) { const d = b[k] - 48; if (d < 0 || d > 9) return -1; v = v * 10 + d; } return v; } function rdU32(b, p, lim) { let r = 0; for (let shift = 0; shift < 35; shift += 7) { if (p >= lim) return -1; const x = b[p++]; if (shift === 28 && (x & 240) !== 0) return -1; r |= (x & 127) << shift; if (x < 128) { RV = r >>> 0; return p; } } return -1; } function skLeb(b, p, lim) { for (let k = 0; k < 10; k++) { if (p >= lim) return -1; if (b[p++] < 128) return p; } return -1; } function skMemarg(b, p, lim) { if (p >= lim) return -1; let align = b[p]; if (align < 128) p++; else { p = rdU32(b, p, lim); if (p < 0) return -1; align = RV; } if (align & 64) { p = skLeb(b, p, lim); if (p < 0) return -1; } return skLeb(b, p, lim); } function isNumType(vt) { return vt === 127 || vt === 126 || vt === 125 || vt === 124 || vt === 123; } function skBlockType(b, p, lim, fn2, at) { if (p >= lim) return -1; const x = b[p]; if (x === 64 || isNumType(x)) return p + 1; if (x >= 64 && x < 128) { throw new Refused(EPERM, `function ${fn2}, byte ${at}: block type 0x${x.toString(16)} is not allowed (only empty, a number/vector type or a type index)`); } for (let k = 0; k < 5; k++) { if (p >= lim) return -1; const y = b[p++]; if (y < 128) { if (y & 64) { throw new Refused(EPERM, `function ${fn2}, byte ${at}: block type is a negative s33`); } return p; } } return -1; } function skDenied(b, p, lim, kinds, fn2, at) { for (const k of kinds) { if (p < 0) return -1; if (k === K_NONE) continue; if (k === K_BLOCK) p = skBlockType(b, p, lim, fn2, at); else if (k === K_MEMARG) p = skMemarg(b, p, lim); else if (k === K_TRYTABLE) { p = skBlockType(b, p, lim, fn2, at); if (p < 0) return -1; p = rdU32(b, p, lim); const n = RV; for (let i = 0; i < n && p >= 0; i++) { if (p >= lim) return -1; const c = b[p++]; if (c < 2) p = skLeb(b, p, lim); if (p >= 0) p = skLeb(b, p, lim); } } else p = skLeb(b, p, lim); } return p; } function openBlock(max) { return ++DEPTH > max; } function brTable(b, p, lim, n, max, fn2, pos) { p = rdU32(b, p, lim); const targets = RV + 1; TARGETS += targets; if (p >= 0 && n + TARGETS > max) throw tooLong(fn2, pos, n + TARGETS, max); for (let k = targets; k > 0 && p >= 0; k--) p = skLeb(b, p, lim); return p; } function scanBody(b, p, lim, fn2, deny, maxDepth, maxInstrs) { DEPTH = 0; TARGETS = 0; let n = 0; while (p < lim) { const pos = p; const op = b[p++]; if (++n > maxInstrs) throw tooLong(fn2, pos, n + TARGETS, maxInstrs); switch (OP1[op]) { case K_NONE: continue; case K_END: if (--DEPTH < 0 && p !== lim) throw pastEnd(fn2, p); continue; case K_U32: case K_MEMIDX: case K_LEB: if (p < lim && b[p] < 128) { p++; continue; } p = skLeb(b, p, lim); break; case K_MEMARG: if (p + 1 < lim && b[p] < 64 && b[p + 1] < 128) { p += 2; continue; } p = skMemarg(b, p, lim); break; case K_BLOCK: if (openBlock(maxDepth)) throw tooDeep(fn2, pos, DEPTH, maxDepth); p = skBlockType(b, p, lim, fn2, pos); break; case K_F32: p = p + 4 <= lim ? p + 4 : -1; break; case K_F64: p = p + 8 <= lim ? p + 8 : -1; break; case K_BRTABLE: p = brTable(b, p, lim, n, maxInstrs, fn2, pos); break; case K_CALLIND: { p = skLeb(b, p, lim); if (p >= 0) p = rdU32(b, p, lim); if (p >= 0 && RV !== 0) { deny( fn2, pos, `${op === 17 ? "call_indirect" : "return_call_indirect"} on table ${RV}`, `only table 0, env.${WASM_JIT_TABLE_IMPORT}` ); } break; } case K_SELT: { p = rdU32(b, p, lim); if (p >= 0 && (RV !== 1 || p >= lim || !isNumType(b[p]))) { throw new Refused(EPERM, `function ${fn2}, byte ${pos}: a typed select is allowed only over one number/vector type`); } if (p >= 0) p++; break; } case K_FD: { let sub; if (p < lim && b[p] < 128) sub = b[p++]; else { p = rdU32(b, p, lim); sub = RV; if (p < 0) break; } if (sub <= 11 || sub === 92 || sub === 93) p = skMemarg(b, p, lim); else if (sub === 12 || sub === 13) p = p + 16 <= lim ? p + 16 : -1; else if (sub >= 21 && sub <= 34) p = p + 1 <= lim ? p + 1 : -1; else if (sub >= 84 && sub <= 91) { p = skMemarg(b, p, lim); if (p >= 0) p = p + 1 <= lim ? p + 1 : -1; } else if (sub >= 256 && sub <= 275) { deny(fn2, pos, `relaxed SIMD (0xfd ${sub})`, "relaxed SIMD results are engine-defined"); } else if (sub > 255 || SIMD_RESERVED.has(sub)) { throw unknownOp(fn2, pos, `0xfd ${sub}`); } break; } case K_FE: { p = rdU32(b, p, lim); if (p < 0) break; const sub = RV; if (sub === 3) { p = p + 1 <= lim ? p + 1 : -1; break; } if (sub >= 16 && sub <= 78) { p = skMemarg(b, p, lim); break; } const d = DENYFE.get(sub); if (!d) throw unknownOp(fn2, pos, `0xfe ${sub}`); p = skMemarg(b, p, lim); if (p >= 0) deny(fn2, pos, `${d[0]} (0xfe ${sub})`, d[1]); break; } case K_FC: { p = rdU32(b, p, lim); if (p < 0) break; const sub = RV; if (sub <= 7) break; if (sub === 10) { p = skLeb(b, p, lim); if (p >= 0) p = skLeb(b, p, lim); break; } if (sub === 11) { p = skLeb(b, p, lim); break; } const d = DENYFC.get(sub); if (!d) throw unknownOp(fn2, pos, `0xfc ${sub}`); p = skDenied(b, p, lim, d[1], fn2, pos); if (p >= 0) deny(fn2, pos, `${d[0]} (0xfc ${sub})`, d[2]); break; } default: { const d = DENY1.get(op); if (!d) throw unknownOp(fn2, pos, `0x${op.toString(16)}`); if (d[1] === K_BAD) { throw new Refused(EPERM, `function ${fn2}, byte ${pos}: ${d[0]} is not allowed (${d[2]})`); } p = skDenied(b, p, lim, [d[1]], fn2, pos); if (p >= 0) deny(fn2, pos, `${d[0]} (0x${op.toString(16)})`, d[2]); if (op === 6 || op === 31) DEPTH++; else if (op === 24) DEPTH--; } } if (p < 0) throw malformed(fn2, pos); } if (n + TARGETS > maxInstrs) throw tooLong(fn2, lim, n + TARGETS, maxInstrs); INSTRS = n + TARGETS; return p; } function scanWasmJitCode(b, at, end, onDeny, fnBase = 0, maxDepth = WASM_JIT_MAX_NESTING, maxLocals = WASM_JIT_MAX_LOCALS, maxFuncInstrs = WASM_JIT_MAX_FUNC_INSTRS, maxInstrs = Infinity) { const deny = onDeny ?? defaultDeny; let p = rdU32(b, at, end); if (p < 0) throw new Malformed(`code section count at byte ${at}`); const count = RV; let total = 0; for (let f = 0; f < count; f++) { const fn2 = fnBase + f; p = rdU32(b, p, end); if (p < 0) throw new Malformed(`function ${fn2}'s body size`); const lim = p + RV; if (lim > end) throw new Malformed(`function ${fn2}'s body runs past the code section`); const localsAt = p; p = rdU32(b, p, lim); if (p < 0) throw new Malformed(`function ${fn2}: its local-group count at byte ${localsAt} runs past its body`); const groups = RV; let locals = 0; for (let g = 0; g < groups; g++) { const groupAt = p; p = rdU32(b, p, lim); if (p < 0 || p >= lim) { throw new Malformed(`function ${fn2}: local group ${g} of ${groups} at byte ${groupAt} runs past its body`); } locals += RV; const vt = b[p]; if (!isNumType(vt)) { throw new Refused(EPERM, `function ${fn2}, byte ${p}: a local of type 0x${vt.toString(16)} is not allowed (only i32/i64/f32/f64/v128)`); } p++; } if (locals > maxLocals) { throw new Refused(E2BIG, `function ${fn2}, byte ${localsAt}: declares ${locals} locals in ${groups} group(s) > ${maxLocals} per function`); } p = scanBody(b, p, lim, fn2, deny, maxDepth, maxFuncInstrs); if (p !== lim) throw new Malformed(`function ${fn2}'s last instruction runs past its body`); total += INSTRS; if (total > maxInstrs) throw new OverBudget(fn2, total, maxInstrs); } if (p !== end) throw new Malformed(`the code section has ${end - p} bytes after its last body`); return total; } function uleb32(n) { const out = []; do { let x = n & 127; n >>>= 7; if (n) x |= 128; out.push(x); } while (n); return out; } function warmScanner() { scanWarm = true; for (let i = 0; i < 2; i++) scanWasmJitCode(WARM_CODE, 0, WARM_CODE.length); } function asU8(x) { if (x instanceof Uint8Array) return x; if (ArrayBuffer.isView(x)) return new Uint8Array(x.buffer, x.byteOffset, x.byteLength); if (x instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && x instanceof SharedArrayBuffer) { return new Uint8Array(x); } return null; } function wasmJitImageFacts(module, bytes) { let f = imageFactsCache.get(module); if (f) return f; f = { error: null, native: /* @__PURE__ */ new Set(), slots: /* @__PURE__ */ new Map(), slotSig: /* @__PURE__ */ new Map(), segmentsUnread: 0, importedFns: [] }; try { for (const i of WebAssembly.Module.imports(module)) { if (i.kind === "function") f.importedFns.push(`${i.module}.${i.name}`); } const secs = WebAssembly.Module.customSections(module, WASM_JIT_NATIVE_SECTION); if (secs.length === 0) { f.error = `the image carries no ${WASM_JIT_NATIVE_SECTION} section, so no function of it is known not to park`; } for (const s of secs) { if (s.byteLength % 4 !== 0) { f.error = `the image's ${WASM_JIT_NATIVE_SECTION} section is ${s.byteLength} bytes, not a whole number of u32 function indices`; break; } const dv = new DataView(s); for (let i = 0; i < s.byteLength; i += 4) { const fi = dv.getUint32(i, true); if (fi !== 4294967295) f.native.add(fi); } } const b = asU8(bytes); if (!f.error && !b) f.error = "the host kept no bytes of the image to read its element segments from"; if (!f.error) readImageSections(b, f); } catch (e) { f.error = `the image could not be read: ${errText(e)}`; } imageFactsCache.set(module, f); return f; } function readImageSections(b, f) { let p = 8; const u32 = () => { let r = 0; for (let shift = 0; ; shift += 7) { const x = b[p++]; if (x === void 0) throw new Error("truncated section"); r |= (x & 127) << shift; if ((x & 128) === 0) return r >>> 0; } }; const s32 = () => { let r = 0, shift = 0, x; do { x = b[p++]; if (x === void 0) throw new Error("truncated element section"); r |= (x & 127) << shift; shift += 7; } while (x & 128); return shift < 32 && x & 64 ? r | -1 << shift : r; }; const typeSpan = []; const funcType = []; const slotFn = /* @__PURE__ */ new Map(); let start = -1, codeAt = -1, codeEnd = -1; while (p < b.length) { const id = b[p++]; const size = u32(); const end = p + size; if (id === 1) { const count = u32(); for (let i = 0; i < count; i++) { const at = p; if (b[p++] !== 96) break; let ok = true; for (let side = 0; side < 2 && ok; side++) { const n = u32(); for (let k = 0; k < n; k++) if (!isNumType(b[p++])) { ok = false; break; } } if (!ok || p > end) break; typeSpan.push([at, p]); } } else if (id === 3) { const count = u32(); for (let i = 0; i < count; i++) funcType.push(u32()); } else if (id === 9) { const count = u32(); for (let s = 0; s < count; s++) { const flags = u32(); if (flags === 1 || flags === 3) { p++; const n2 = u32(); for (let i = 0; i < n2; i++) u32(); continue; } if (flags !== 0 && flags !== 2) { f.segmentsUnread++; break; } const table = flags === 2 ? u32() : 0; if (b[p++] !== 65) { f.segmentsUnread++; break; } const off = s32(); if (b[p++] !== 11) { f.segmentsUnread++; break; } if (flags === 2 && b[p++] !== 0) { f.segmentsUnread++; break; } const n = u32(); for (let i = 0; i < n; i++) { const fi = u32(); if (table !== 0 || off < 0) continue; if (f.native.has(fi) && fi >= f.importedFns.length) slotFn.set(off + i, fi); else slotFn.delete(off + i); } } } else if (id === 8) { start = u32(); } else if (id === 10) { codeAt = p; codeEnd = end; } p = end; } if (start >= 0) { const why = startFunctionHazard(b, codeAt, codeEnd, start, f.importedFns.length); if (why) { f.error = `the image's start function (function ${start}) ${why}: a start function runs inside instantiation, before the host can snapshot the table, so it could have left any function in a native's slot \u2014 another module's among them, which the name check cannot tell from the native \u2014 and no slot is known to hold what the element segments put there`; slotFn.clear(); } } if (f.segmentsUnread > 0) slotFn.clear(); for (const [slot, fi] of slotFn) { f.slots.set(slot, fi); const t = funcType[fi - f.importedFns.length]; const span = t === void 0 ? void 0 : typeSpan[t]; f.slotSig.set(slot, span ? b.slice(span[0], span[1]) : null); } } function startFunctionHazard(b, codeAt, codeEnd, start, nImported) { if (start < nImported) return "is an import, so host code ran inside instantiation"; if (codeAt < 0) return "has no body"; let p = rdU32(b, codeAt, codeEnd); if (p < 0) return "could not be read (the code section count)"; const k = start - nImported; if (k >= RV) return "has no body"; for (let i = 0; i < k; i++) { p = rdU32(b, p, codeEnd); if (p < 0 || p + RV > codeEnd) return "could not be read (a body before it)"; p += RV; } p = rdU32(b, p, codeEnd); if (p < 0 || p + RV > codeEnd) return "could not be read (its body size)"; const lim = p + RV; p = rdU32(b, p, lim); if (p < 0) return "could not be read (its locals)"; for (let g = RV; g > 0; g--) { p = skLeb(b, p, lim); if (p < 0 || p >= lim || !isNumType(b[p])) return "could not be read (a local of a type it does not read)"; p++; } try { while (p < lim) { const at = p, op = b[p++]; if (op === 16 || op === 18) { p = rdU32(b, p, lim); return `calls function ${p < 0 ? "?" : RV} (byte ${at} of the image)`; } if (op === 17 || op === 19 || op === 20 || op === 21) { return `makes an indirect call (opcode 0x${op.toString(16)}, byte ${at} of the image)`; } if (op === 38) return `writes a table (table.set, byte ${at} of the image)`; if (op === 37) { p = skLeb(b, p, lim); if (p < 0) return "could not be read"; continue; } switch (OP1[op]) { case K_NONE: case K_END: break; case K_U32: case K_MEMIDX: case K_LEB: p = skLeb(b, p, lim); break; case K_MEMARG: p = skMemarg(b, p, lim); break; case K_BLOCK: p = skBlockType(b, p, lim, start, at); break; case K_F32: p = p + 4 <= lim ? p + 4 : -1; break; case K_F64: p = p + 8 <= lim ? p + 8 : -1; break; case K_BRTABLE: p = rdU32(b, p, lim); for (let n = RV; n >= 0 && p >= 0; n--) p = skLeb(b, p, lim); break; case K_FC: { p = rdU32(b, p, lim); if (p < 0) break; const sub = RV; if (sub === 12 || sub === 14 || sub === 15 || sub === 17) { return `writes a table (0xfc ${sub}, byte ${at} of the image)`; } if (sub <= 7) break; if (sub === 8 || sub === 10) { p = skLeb(b, p, lim); if (p >= 0) p = skLeb(b, p, lim); break; } if (sub === 9 || sub === 11 || sub === 13 || sub === 16) { p = skLeb(b, p, lim); break; } return `uses opcode 0xfc ${sub} (byte ${at} of the image), which this check does not read`; } case K_FE: { p = rdU32(b, p, lim); if (p < 0) break; const sub = RV; if (sub === 3) { p = p + 1 <= lim ? p + 1 : -1; break; } if (sub <= 2 || sub >= 16 && sub <= 78) { p = skMemarg(b, p, lim); break; } return `uses opcode 0xfe ${sub} (byte ${at} of the image), which this check does not read`; } default: return `uses opcode 0x${op.toString(16)} (byte ${at} of the image), which this check does not read`; } if (p < 0) return `could not be read (the instruction at byte ${at} of the image runs past its body)`; } } catch (e) { return `could not be read (${e instanceof Error ? e.message : String(e)})`; } return null; } function wasmJitBindImage(instance, module, bytes) { if (instance && !imageSnapshots.has(instance)) { const t = instance.exports && instance.exports.__indirect_function_table; if (t instanceof WebAssembly.Table) { const snap = /* @__PURE__ */ new Map(); const facts = wasmJitImageFacts(module, bytes); if (!facts.error) { for (const [slot, fi] of facts.slots) { if (slot < t.length) { const fn2 = t.get(slot); if (typeof fn2 === "function" && fn2.name === String(fi)) snap.set(slot, fn2); } } } imageSnapshots.set(instance, snap); } } return { module, bytes }; } function helperSigWhy(sig) { let p = rdU32(sig, 1, sig.length); if (p < 0) return "its parameter count could not be read"; const np = RV; if (np > WASM_JIT_MAX_HELPER_PARAMS) return `${np} parameters > ${WASM_JIT_MAX_HELPER_PARAMS}`; for (let k = 0; k < np; k++, p++) if (sig[p] === 123) return "a v128 parameter (only i32/i64/f32/f64)"; p = rdU32(sig, p, sig.length); if (p < 0) return "its result count could not be read"; const nr = RV; if (nr > 1) return `${nr} results > 1`; if (nr === 1 && sig[p] === 123) return "a v128 result (only i32/i64/f32/f64)"; return ""; } function poolOf(table) { let p = slotPools.get(table); if (!p) slotPools.set(table, p = { free: [], head: 0, high: 0, floor: 0 }); return p; } function poolTake(pool, n) { const k = Math.min(n, pool.free.length - pool.head); const out = pool.free.slice(pool.head, pool.head + k); pool.head += k; return out; } function poolGive(pool, slots) { if (pool.head > 1024 && pool.head * 2 > pool.free.length) { pool.free = pool.free.slice(pool.head); pool.head = 0; } for (const s of slots) pool.free.push(s); } function makeWasmJitMemoryLedger() { const holders = /* @__PURE__ */ new Map(); return { add(memoryId, token) { if (typeof memoryId !== "number") return; let s = holders.get(memoryId); if (!s) holders.set(memoryId, s = /* @__PURE__ */ new Set()); s.add(token); }, release(memoryId, token) { const s = holders.get(memoryId); if (s && s.delete(token) && s.size === 0) holders.delete(memoryId); }, has(memoryId) { return holders.has(memoryId); }, get size() { return holders.size; } }; } function makeWasmJitHost({ memory, instance, image, cpuId, log: log2, onInstall, slotFloor = 0 }) { const records = /* @__PURE__ */ new WeakMap(); let lastError = ""; let logged = /* @__PURE__ */ new Set(); let capNoted = false; let inherited = Number.isInteger(slotFloor) && slotFloor > 0 && slotFloor < 268435456 ? slotFloor : 0; function say(line) { try { log2(line); } catch (_e) { } } function refuse3(op, errno, text, keepLast = false) { const line = wasmJitCleanText(`wasm_jit ${OP_NAME[op] ?? `op ${op}`}: -${ERRNO_NAME[errno] ?? errno}: ${text}`, 1024); if (!keepLast) lastError = line; if (!logged.has(line)) { if (logged.size < WASM_JIT_LOG_CAP) { logged.add(line); say(line); } else if (!capNoted) { capNoted = true; say(`wasm_jit: ${WASM_JIT_LOG_CAP} distinct refusals logged for this image; further ones are kept for the ERROR op but not logged`); } } return -errno; } function newRecord(table) { return { table, jit: new WebAssembly.Table({ element: "anyfunc", initial: 0 }), epoch: 0, installs: [], /* { instance, module, slots, bytes, funcs, instrs } */ owner: /* @__PURE__ */ new Map(), /* live slot -> its install (EVICT's lookup) */ liveSlots: 0, liveFuncs: 0, /* defined functions of the live installs */ liveInstrs: 0, /* the live installs' charged instructions */ bytes: 0, quarantine: [], /* retired by the last RESET that retired anything */ helpers: [], /* registered helper slots, ascending */ /* The signatures a generated module may declare: [entry, empty, * each distinct registered helper signature]. */ allowed: [SIG_ENTRY, SIG_EMPTY] }; } function recordFor(inst, table) { let rec = records.get(inst); if (!rec) records.set(inst, rec = newRecord(table)); return rec; } function tableOf(inst) { const t = inst && inst.exports && inst.exports.__indirect_function_table; return t instanceof WebAssembly.Table ? t : null; } function noTable(op, inst) { return refuse3(op, ENOTSUP, inst ? "the calling instance exports no __indirect_function_table (link the image with -Wl,--export-table -Wl,--growable-table)" : "no user instance is bound to this task yet"); } function inMemory(ptr, len) { return ptr !== 0 && ptr + len <= memory.buffer.byteLength; } function takeEpoch(op) { const { epoch, reseeded } = nextEpoch(cpuId); if (reseeded) { say(`wasm_jit ${OP_NAME[op]}: this Worker's epoch sequence was spent and reseeded at random; an epoch may now recur within one record (improbably)`); } return epoch; } function poolFor(table) { const p = poolOf(table); if (inherited > p.floor) p.floor = inherited; return p; } function jitCover(rec, max) { if (rec.jit.length <= max) rec.jit.grow(max + 1 - rec.jit.length, null); } function growSlots(table, need) { const fl = poolFor(table).floor; const over = tableCapText(table, need); if (over) throw new RangeError(over); if (table.length < fl) table.grow(fl - table.length, null); return table.grow(need, null); } function tableCapText(table, need) { const fl = poolFor(table).floor; const to = Math.max(table.length, fl) + need; return to > WASM_JIT_MAX_TABLE ? `the table would reach ${to} entries > ${WASM_JIT_MAX_TABLE}, the host's cap on a table the JIT grows (fork floor ${fl})` : ""; } function refusedBy(op, e) { if (e instanceof Refused) return refuse3(op, e.errno, e.message); if (e instanceof Malformed) return refuse3(op, ENOEXEC, `malformed module: ${e.message}`); return refuse3(op, ENOEXEC, `malformed module: ${errText(e)}`); } function allowedFor(sigs) { const out = [SIG_ENTRY, SIG_EMPTY]; for (const sig of sigs) if (sigIndex(sig, 0, sig.length, out) < 0) out.push(sig); return out; } function probe(info, len) { const inst = instance(); const table = tableOf(inst); if (!table) return noTable(WASM_JIT_PROBE, inst); if (len < WASM_JIT_PROBE_INFO_BYTES) { return refuse3(WASM_JIT_PROBE, EINVAL, `info len ${len} < ${WASM_JIT_PROBE_INFO_BYTES}`); } if (!inMemory(info, WASM_JIT_PROBE_INFO_BYTES)) { return refuse3(WASM_JIT_PROBE, EFAULT, `info 0x${info.toString(16)}+${WASM_JIT_PROBE_INFO_BYTES} is outside user memory (${memory.buffer.byteLength} bytes)`); } const rec = recordFor(inst, table); if (rec.epoch === 0) rec.epoch = takeEpoch(WASM_JIT_PROBE); const dv = new DataView(memory.buffer); dv.setUint32(info, WASM_JIT_ABI, true); dv.setUint32(info + 4, wasmJitFeatures() | WASM_JIT_FEATURE_EVICT, true); dv.setUint32(info + 8, rec.epoch, true); dv.setUint32(info + 12, WASM_JIT_MAX_MODULE_BYTES, true); dv.setUint32(info + 16, WASM_JIT_MAX_LIVE_SLOTS, true); dv.setUint32(info + 20, WASM_JIT_MAX_LIVE_BYTES, true); dv.setUint32(info + 24, WASM_JIT_MAX_FUNCS, true); dv.setUint32(info + 28, WASM_JIT_MAX_HELPERS, true); dv.setUint32(info + 32, WASM_JIT_MAX_LIVE_INSTALLS, true); dv.setUint32(info + 36, WASM_JIT_MAX_TYPES, true); dv.setUint32(info + 40, WASM_JIT_MAX_NESTING, true); dv.setUint32(info + 44, WASM_JIT_MAX_LOCALS, true); dv.setUint32(info + 48, WASM_JIT_MAX_LIVE_INSTRS, true); dv.setUint32(info + 52, WASM_JIT_MAX_FUNC_INSTRS, true); return 0; } function reset() { const inst = instance(); const table = tableOf(inst); if (!table) return noTable(WASM_JIT_RESET, inst); const rec = recordFor(inst, table); if (rec.epoch !== 0 && rec.installs.length === 0) { if (rec.quarantine.length && tableCapText(table, WASM_JIT_MAX_FUNCS)) { poolGive(poolFor(table), rec.quarantine); rec.quarantine = []; } return rec.epoch; } const e = takeEpoch(WASM_JIT_RESET); if (rec.installs.length) { poolGive(poolFor(table), rec.quarantine); const q = []; for (const { slots } of rec.installs) { for (const s of slots) { table.set(s, null); rec.jit.set(s, null); q.push(s); } } rec.quarantine = q; rec.installs = []; rec.owner.clear(); rec.liveSlots = 0; rec.liveFuncs = 0; rec.liveInstrs = 0; rec.bytes = 0; } rec.epoch = e; return e; } function checkHelpers(inst, table, idxs) { const img = image ? image() : null; if (!img || !(img.module instanceof WebAssembly.Module)) { throw new Refused(ENOTSUP, "the host holds no Module for the calling image"); } const facts = wasmJitImageFacts(img.module, img.bytes); if (facts.error) throw new Refused(ENOTSUP, facts.error); const snap = imageSnapshots.get(inst); if (!snap) { throw new Refused(ENOTSUP, "the host took no snapshot of the image's table at instantiation (wasmJitBindImage), so no slot is known to hold what the element segment put there"); } const fns = [], sigs = []; for (const idx of idxs) { if (idx >= table.length) { throw new Refused(EINVAL, `helper slot ${idx} is outside the table (length ${table.length})`); } const fi = facts.slots.get(idx); if (fi === void 0) { throw new Refused(EPERM, `helper slot ${idx} was not filled by the image's element segments with a function marked hwjs.native.v1 (${facts.native.size} functions are marked, ${facts.slots.size} of them in the table)`); } const orig = snap.get(idx); if (!orig) { throw new Refused(EPERM, `helper slot ${idx} did not hold the image's function ${fi} when the image was bound at instantiation (the snapshot has nothing for it)`); } const fn2 = table.get(idx); if (fn2 !== orig) { throw new Refused(EPERM, `helper slot ${idx} no longer holds the function the image's element segment put there (function ${fi}); it holds ${typeof fn2 === "function" ? `function ${nm(fn2.name || "?")} (a different object)` : "null"}`); } const sig = facts.slotSig.get(idx); if (!sig) { throw new Refused(EPERM, `helper slot ${idx} (function ${fi}) has a type this host cannot reproduce byte for byte (not a plain function type of number/vector types), so no generated module could declare it`); } const why = helperSigWhy(sig); if (why) { throw new Refused(EPERM, `helper slot ${idx} (function ${fi}) has signature ${typeText(sig, 0, sig.length)}: ${why} (a registered helper's signature becomes declarable by generated code, and 1,000 v128 parameters per call took one record to 1.48 GB)`); } fns.push(orig); sigs.push(sig); } return { fns, sigs }; } function registerHelpers(ptr, n) { const op = WASM_JIT_REGISTER_HELPERS; const inst = instance(); const table = tableOf(inst); if (!table) return noTable(op, inst); if (n === 0) return refuse3(op, EINVAL, "n = 0 helpers"); if (n > WASM_JIT_MAX_HELPERS) return refuse3(op, E2BIG, `n = ${n} helpers > ${WASM_JIT_MAX_HELPERS}`); if (!inMemory(ptr, n * 4)) { return refuse3(op, EFAULT, `idx 0x${ptr.toString(16)}+${n}*4 is outside user memory (${memory.buffer.byteLength} bytes)`); } const dv = new DataView(memory.buffer); const idxs = []; for (let i = 0; i < n; i++) idxs.push(dv.getUint32(ptr + 4 * i, true)); let checked; try { checked = checkHelpers(inst, table, idxs); } catch (e) { if (e instanceof Refused) return refuse3(op, e.errno, e.message); throw e; } const rec = recordFor(inst, table); const all = /* @__PURE__ */ new Set([...rec.helpers, ...idxs]); if (all.size > WASM_JIT_MAX_HELPERS) { return refuse3(op, E2BIG, `${all.size} distinct helpers for this record > ${WASM_JIT_MAX_HELPERS}`); } let max = 0; for (const x of idxs) if (x > max) max = x; try { jitCover(rec, max); } catch (e) { return refuse3(op, ENOMEM, `JIT table grow to ${max + 1}: ${errText(e)}`); } for (let i = 0; i < n; i++) rec.jit.set(idxs[i], checked.fns[i]); rec.helpers = [...all].sort((x, y) => x - y); rec.allowed = allowedFor([...rec.allowed.slice(2), ...checked.sigs]); return n; } function install(epoch, ptr, len, slotsPtr, cap) { const op = WASM_JIT_INSTALL; const memBytes = memory.buffer.byteLength; if (!inMemory(ptr, len)) { return refuse3(op, EFAULT, `module 0x${ptr.toString(16)}+${len} is outside user memory (${memBytes} bytes)`); } if (!inMemory(slotsPtr, cap * 4)) { return refuse3(op, EFAULT, `slots 0x${slotsPtr.toString(16)}+${cap}*4 is outside user memory (${memBytes} bytes)`); } if (len > WASM_JIT_MAX_MODULE_BYTES) { return refuse3(op, E2BIG, `module of ${len} bytes > ${WASM_JIT_MAX_MODULE_BYTES}`); } const inst = instance(); const rec = inst ? records.get(inst) : void 0; if (!rec || rec.epoch === 0 || rec.epoch !== epoch) { return refuse3(op, ESTALE, `epoch ${epoch} is not this instance's (` + (rec && rec.epoch ? `current ${rec.epoch}` : "none yet: PROBE or RESET first") + ")"); } const bytes = new Uint8Array(memory.buffer, ptr, len).slice(); let walk; try { walk = walkModule(bytes, rec.allowed); } catch (e) { return refusedBy(op, e); } const n = walk.exports.length; const nDef = walk.funcTypes.length; if (n === 0) return refuse3(op, EINVAL, "the module exports nothing; INSTALL needs f0..f(n-1)"); if (n > cap) return refuse3(op, EINVAL, `the module exports ${n} functions; slots[] holds cap=${cap}`); if (rec.liveSlots + n > WASM_JIT_MAX_LIVE_SLOTS) { return refuse3(op, ENOSPC, `${rec.liveSlots} live slots + ${n} > ${WASM_JIT_MAX_LIVE_SLOTS}; RESET to reclaim`); } if (rec.liveFuncs + nDef > WASM_JIT_MAX_LIVE_FUNCS) { return refuse3(op, ENOSPC, `${rec.liveFuncs} live functions + ${nDef} defined by this module > ${WASM_JIT_MAX_LIVE_FUNCS}; RESET to reclaim (every defined function costs the engine memory, exported or not)`); } if (rec.installs.length >= WASM_JIT_MAX_LIVE_INSTALLS) { return refuse3(op, ENOSPC, `${rec.installs.length} live installs = ${WASM_JIT_MAX_LIVE_INSTALLS}; RESET to reclaim (each compiled module costs the engine ~21 KiB whatever its size)`); } if (rec.bytes + len > WASM_JIT_MAX_LIVE_BYTES) { return refuse3(op, ENOSPC, `${rec.bytes} live bytes + ${len} > ${WASM_JIT_MAX_LIVE_BYTES}; RESET to reclaim`); } const fixed = WASM_JIT_INSTALL_INSTRS + nDef * WASM_JIT_FUNC_INSTRS + Math.ceil(len / WASM_JIT_BYTES_PER_INSTR); const budgetText = (more) => `${rec.liveInstrs} live instructions + ${more} for this module > ${WASM_JIT_MAX_LIVE_INSTRS}; RESET to reclaim (the module is charged its instructions, br_table targets one each, + ${WASM_JIT_INSTALL_INSTRS} for the install, ${WASM_JIT_FUNC_INSTRS} per defined function and 1 per ${WASM_JIT_BYTES_PER_INSTR} bytes)`; if (rec.liveInstrs + fixed + nDef > WASM_JIT_MAX_LIVE_INSTRS) { return refuse3(op, ENOSPC, budgetText(`at least ${fixed + nDef}`)); } const table = rec.table; const pool = poolFor(table); const grow = n - Math.min(n, pool.free.length - pool.head); if (grow > 0) { const over = tableCapText(table, grow); if (over) return refuse3(op, ENOMEM, `table.grow(${grow}) at length ${table.length}: ${over}`); } let instrs = 0; if (walk.codeAt >= 0) { try { if (!scanWarm) warmScanner(); instrs = scanWasmJitCode( bytes, walk.codeAt, walk.codeEnd, null, 0, WASM_JIT_MAX_NESTING, WASM_JIT_MAX_LOCALS, WASM_JIT_MAX_FUNC_INSTRS, WASM_JIT_MAX_LIVE_INSTRS - rec.liveInstrs - fixed ); } catch (e) { if (e instanceof OverBudget) { return refuse3(op, ENOSPC, budgetText(`at least ${fixed + e.total} (counted through function ${e.fn})`)); } return refusedBy(op, e); } } const charge = fixed + instrs; let mod; try { mod = new WebAssembly.Module(bytes); } catch (e) { return e instanceof WebAssembly.CompileError ? refuse3(op, ENOEXEC, `CompileError: ${errText(e)}`) : refuse3(op, ENOMEM, `compile failed: ${errText(e)}`); } const ex = walk.exports; const exportName = (e) => nm(UTF8.decode(bytes.subarray(e.at, e.at + e.len))); const fnIndex = new Array(n); for (const e of ex) { if (e.kind !== 0) { return refuse3(op, EINVAL, `export ${exportName(e)} is a ${KIND_NAME[e.kind] ?? `kind ${e.kind}`}; only functions f0..f${n - 1}`); } const i = e.fi; if (i < 0 || i >= n || fnIndex[i] !== void 0) { return refuse3(op, EINVAL, `export ${exportName(e)} is not one of f0..f${n - 1}`); } const t = walk.funcTypes[e.index]; if (t === void 0 || !walk.typeIsEntry[t]) { const sig = t === void 0 || walk.typeAt[t] === void 0 ? "unknown" : typeText(bytes, walk.typeAt[t], bytes.length); return refuse3(op, EINVAL, `export f${i} has type ${sig}; every export must be ${WASM_JIT_ENTRY_SIG}`); } fnIndex[i] = e.index; } let gen; try { gen = new WebAssembly.Instance(mod, { env: { user_memory: memory, [WASM_JIT_TABLE_IMPORT]: rec.jit } }); } catch (e) { return e instanceof WebAssembly.LinkError ? refuse3(op, ENOEXEC, `LinkError: ${errText(e)}`) : refuse3(op, ENOMEM, `instantiate failed: ${errText(e)}`); } const fns = new Array(n); for (let i = 0; i < n; i++) { fns[i] = gen.exports[`f${i}`]; if (typeof fns[i] !== "function") { return refuse3(op, EINVAL, `export f${i} is not a function of the instance (the section walk and the engine disagree)`); } } const slots = poolTake(pool, n); const taken = slots.length; const need = n - taken; if (need > 0) { let base; try { base = growSlots(table, need); } catch (e) { pool.head -= taken; return refuse3(op, ENOMEM, `table.grow(${need}) at length ${table.length}: ${errText(e)}`); } for (let j = 0; j < need; j++) slots.push(base + j); } let max = 0; for (const s of slots) if (s > max) max = s; try { jitCover(rec, max); } catch (e) { pool.head -= taken; poolGive(pool, slots.slice(taken)); return refuse3(op, ENOMEM, `JIT table grow to ${max + 1}: ${errText(e)}`); } for (let i = 0; i < n; i++) { table.set(slots[i], fns[i]); rec.jit.set(slots[i], fns[i]); } if (max + 1 > pool.high) pool.high = max + 1; const placed = { instance: gen, module: mod, slots, bytes: len, funcs: nDef, instrs: charge }; rec.installs.push(placed); for (const s of slots) rec.owner.set(s, placed); rec.liveSlots += n; rec.liveFuncs += nDef; rec.liveInstrs += charge; const dv = new DataView(memory.buffer); for (let i = 0; i < n; i++) dv.setUint32(slotsPtr + 4 * i, slots[i], true); rec.bytes += len; try { onInstall(); } catch (_e) { } return n; } function evict(epoch, slot) { const op = WASM_JIT_EVICT; const inst = instance(); const rec = inst ? records.get(inst) : void 0; if (!rec || rec.epoch === 0 || rec.epoch !== epoch) { return refuse3(op, ESTALE, `epoch ${epoch} is not this instance's (` + (rec && rec.epoch ? `current ${rec.epoch}` : "none yet: PROBE or RESET first") + ")"); } const ins = rec.owner.get(slot); if (!ins) { return refuse3(op, EINVAL, `slot ${slot} is not a slot of a live install of this record (${rec.installs.length} live installs, ${rec.liveSlots} live slots` + (rec.helpers.includes(slot) ? "; it is a registered helper's" : "") + ")"); } const at = rec.installs.indexOf(ins); if (at >= 0) rec.installs.splice(at, 1); const table = rec.table; for (const s of ins.slots) { table.set(s, null); rec.jit.set(s, null); rec.owner.delete(s); rec.quarantine.push(s); } rec.liveSlots -= ins.slots.length; rec.liveFuncs -= ins.funcs; rec.liveInstrs -= ins.instrs; rec.bytes -= ins.bytes; const keep = Math.max(rec.liveSlots, WASM_JIT_MAX_FUNCS); if (rec.quarantine.length > keep) { poolGive(poolFor(table), rec.quarantine.slice(0, rec.quarantine.length - keep)); rec.quarantine = rec.quarantine.slice(rec.quarantine.length - keep); } return ins.instrs; } function error(buf, len) { const text = new TextEncoder().encode(lastError); if (len === 0) return text.length; const n = Math.min(text.length, len - 1); if (!inMemory(buf, n + 1)) { return refuse3(WASM_JIT_ERROR, EFAULT, `buf 0x${buf.toString(16)}+${len} is outside user memory (${memory.buffer.byteLength} bytes)`, true); } const u8 = new Uint8Array(memory.buffer); u8.set(text.subarray(0, n), buf); u8[buf + n] = 0; return text.length; } { const t = tableOf(instance()); if (t) poolFor(t); } return { /* syscall(1031, op, a1..a5): the arguments arrive as the import's i32s. */ syscall(op, a1, a2, a3, a4, a5) { switch (op | 0) { case WASM_JIT_PROBE: return probe(a1 >>> 0, a2 >>> 0); case WASM_JIT_INSTALL: return install(a1 >>> 0, a2 >>> 0, a3 >>> 0, a4 >>> 0, a5 >>> 0); case WASM_JIT_RESET: return reset(); case WASM_JIT_ERROR: return error(a1 >>> 0, a2 >>> 0); case WASM_JIT_REGISTER_HELPERS: return registerHelpers(a1 >>> 0, a2 >>> 0); case WASM_JIT_EVICT: return evict(a1 >>> 0, a2 >>> 0); default: return refuse3(op | 0, EINVAL, `unknown op ${op | 0} (PROBE=0 INSTALL=1 RESET=2 ERROR=3 REGISTER_HELPERS=4 EVICT=5)`); } }, /* * Exec / thread or process end / migrated away: null this record's * slots in both tables, hand every slot it held (live and quarantined) * to the table's pool, and drop the record. At exec the table dies with * the image anyway; a thread leaving a SHARED image leaves the table to * the others, whose installs now reuse its slots. The refusal log * starts over: its cap is per image, not per run() (review #8). So does * the fork floor: an exec'd image's memory holds no inherited number. */ drop() { const inst = instance(); const rec = inst ? records.get(inst) : void 0; if (rec) { const back = rec.quarantine.slice(); for (const { slots } of rec.installs) { for (const s of slots) { rec.table.set(s, null); rec.jit.set(s, null); back.push(s); } } poolGive(poolFor(rec.table), back); records.delete(inst); } lastError = ""; logged = /* @__PURE__ */ new Set(); capNoted = false; inherited = 0; }, /* * Right after the caller's Instance is bound (worker.mjs, after * wasmJitBindImage): put the inherited floor on its table's pool NOW, * so a thread that joins the image before this one makes its first JIT * call — and any fork made from such a thread — finds it. A no-op with * no Instance; the host also seats itself when it is made after one. */ seat() { const table = tableOf(instance()); if (table) poolFor(table); }, /* * FORK, the parent half: the floor its child's JIT must never grow * below — one past the highest slot number this image's JIT ever * placed, or the floor this image inherited, whichever is higher; 0 * when neither exists (nothing to carry). The child's memory is a copy * of this one, so every number the emulator ever cached is below it. */ forkFloor() { const table = tableOf(instance()); if (!table) return inherited; const pool = poolFor(table); return Math.max(pool.floor, pool.high); }, /* * CPU MIGRATION, the source half: everything the destination needs to * rebuild this record on its own Instance — the epoch, the helper * slots, each live install's compiled Module (a Module structured- * clones to another Worker of the same agent cluster) with its slots, * the slots that are quarantined or free, and the fork floor — or null * when there is nothing to carry. Read-only: the source keeps its * record until the destination commits. */ migrateOut() { const inst = instance(); const table = tableOf(inst); const rec = inst ? records.get(inst) : void 0; const fl = table ? Math.max(poolFor(table).floor, poolFor(table).high) : inherited; const empty = !rec || rec.epoch === 0 && rec.helpers.length === 0 && rec.installs.length === 0; if (empty && fl === 0) return null; const pool = table ? poolFor(table) : null; return { abi: WASM_JIT_ABI, floor: fl, record: !empty, epoch: rec ? rec.epoch : 0, helpers: rec ? rec.helpers.slice() : [], installs: rec ? rec.installs.map(({ module, slots, bytes, funcs, instrs }) => ({ module, slots: slots.slice(), bytes, funcs, instrs })) : [], quarantine: rec ? rec.quarantine.slice() : [], free: rec && pool ? pool.free.slice(pool.head) : [] }; }, /* * CPU MIGRATION, the destination half, run BEFORE the commit: rebuild * the record on this Worker's fresh Instance with every slot at the * index it had on the source, so the slot numbers the emulator holds * stay valid. Throws (and changes nothing the guest can reach) when it * cannot — a slot the destination's table already uses, a helper that * no longer checks out, a Module that did not survive the message — so * the offer aborts and the source, which never released the task, * keeps driving it with its record intact. Returns a one-line summary. * The caller drops its reference to `state` afterwards: the carried * Modules live on in the record's installs only while they are live * (re-review #5). */ migrateIn(state) { const inst = instance(); const table = tableOf(inst); if (!table) throw new Error("wasm_jit migrate-in: the destination instance exports no table"); if (!state || typeof state !== "object" || state.abi !== WASM_JIT_ABI || !Array.isArray(state.installs) || !Array.isArray(state.helpers) || !Array.isArray(state.quarantine) || !Array.isArray(state.free)) { throw new Error(`wasm_jit migrate-in: the carried record is not an abi ${WASM_JIT_ABI} record`); } if (records.get(inst)) throw new Error("wasm_jit migrate-in: the destination instance already has a record"); const isSlot = (s) => Number.isInteger(s) && s > 0 && s < 268435456; const fl = state.floor === void 0 ? 0 : state.floor; if (fl !== 0 && !isSlot(fl)) throw new Error(`wasm_jit migrate-in: the carried floor ${fl} is malformed`); if (state.record === false) { if (fl > inherited) inherited = fl; return `no record; floor ${poolFor(table).floor}`; } const live2 = []; let carried = 0; for (const ins of state.installs) { if (!(ins && ins.module instanceof WebAssembly.Module) || !Array.isArray(ins.slots) || !ins.slots.every(isSlot) || !Number.isInteger(ins.bytes) || !Number.isInteger(ins.funcs) || ins.funcs < 1 || ins.funcs > WASM_JIT_MAX_FUNCS || !Number.isInteger(ins.instrs) || ins.instrs > WASM_JIT_MAX_LIVE_INSTRS || ins.instrs < WASM_JIT_INSTALL_INSTRS + ins.funcs * (WASM_JIT_FUNC_INSTRS + 1) + Math.ceil(ins.bytes / WASM_JIT_BYTES_PER_INSTR)) { throw new Error("wasm_jit migrate-in: a carried install has no Module, a malformed slot list or a malformed function or instruction count (the message transport did not clone a WebAssembly.Module?)"); } carried += ins.instrs; for (const s of ins.slots) live2.push(s); } if (carried > WASM_JIT_MAX_LIVE_INSTRS) { throw new Error(`wasm_jit migrate-in: the carried installs hold ${carried} instructions > ${WASM_JIT_MAX_LIVE_INSTRS}`); } const all = live2; for (const s of state.quarantine) all.push(s); for (const s of state.free) all.push(s); let max = 0; for (const s of all) { if (!isSlot(s)) throw new Error("wasm_jit migrate-in: a carried slot number is malformed"); if (s > max) max = s; } for (const s of state.helpers) { if (!isSlot(s)) throw new Error("wasm_jit migrate-in: a carried helper slot number is malformed"); if (s > max) max = s; } if (new Set(all).size !== all.length) throw new Error("wasm_jit migrate-in: a carried slot appears twice"); const tableLen = table.length; for (const s of all) { if (s < tableLen && table.get(s) !== null) { throw new Error(`wasm_jit migrate-in: slot ${s} is already in use on the destination (its table was not rebuilt to the source's layout)`); } } const rec = newRecord(table); const checked = state.helpers.length ? checkHelpersOrThrow(inst, table, state.helpers) : { fns: [], sigs: [] }; const placed = []; for (const ins of state.installs) { const gen = new WebAssembly.Instance( ins.module, { env: { user_memory: memory, [WASM_JIT_TABLE_IMPORT]: rec.jit } } ); const fns = ins.slots.map((_, i) => gen.exports[`f${i}`]); if (!fns.every((f) => typeof f === "function") || Object.keys(gen.exports).length !== fns.length) { throw new Error(`wasm_jit migrate-in: a carried Module does not export exactly f0..f${fns.length - 1}`); } placed.push({ instance: gen, module: ins.module, slots: ins.slots.slice(), bytes: ins.bytes, funcs: ins.funcs, instrs: ins.instrs, fns }); } if (table.length <= max) table.grow(max + 1 - table.length, null); rec.jit.grow(max + 1, null); state.helpers.forEach((idx, i) => rec.jit.set(idx, checked.fns[i])); for (const p of placed) { p.slots.forEach((s, i) => { table.set(s, p.fns[i]); rec.jit.set(s, p.fns[i]); }); const ins = { instance: p.instance, module: p.module, slots: p.slots, bytes: p.bytes, funcs: p.funcs, instrs: p.instrs }; rec.installs.push(ins); for (const s of p.slots) rec.owner.set(s, ins); rec.liveSlots += p.slots.length; rec.liveFuncs += p.funcs; rec.liveInstrs += p.instrs; rec.bytes += p.bytes; } rec.helpers = state.helpers.slice().sort((x, y) => x - y); rec.allowed = allowedFor(checked.sigs); rec.quarantine = state.quarantine.slice(); rec.epoch = state.epoch >>> 0; if (fl > inherited) inherited = fl; const pool = poolFor(table); poolGive(pool, state.free); if (max + 1 > pool.high) pool.high = max + 1; records.set(inst, rec); return `epoch ${rec.epoch}, ${placed.length} install(s) / ${rec.liveSlots} slot(s) re-placed at their source indices, ${rec.helpers.length} helper(s), ${rec.quarantine.length} quarantined, ${state.free.length} free, floor ${pool.floor}`; } }; function checkHelpersOrThrow(inst, table, idxs) { try { return checkHelpers(inst, table, idxs); } catch (e) { throw new Error(`wasm_jit migrate-in: a carried helper no longer checks out: ${e.message}`); } } } var SYS_WASM_JIT, WASM_JIT_PROBE, WASM_JIT_INSTALL, WASM_JIT_RESET, WASM_JIT_ERROR, WASM_JIT_REGISTER_HELPERS, WASM_JIT_EVICT, WASM_JIT_ABI, WASM_JIT_MAX_MODULE_BYTES, WASM_JIT_MAX_LIVE_SLOTS, WASM_JIT_MAX_LIVE_BYTES, WASM_JIT_MAX_FUNCS, WASM_JIT_MAX_HELPERS, WASM_JIT_MAX_LIVE_INSTALLS, WASM_JIT_MAX_LIVE_FUNCS, WASM_JIT_MAX_TABLE, WASM_JIT_MAX_TYPES, WASM_JIT_MAX_NESTING, WASM_JIT_MAX_LOCALS, WASM_JIT_MAX_LIVE_INSTRS, WASM_JIT_INSTALL_INSTRS, WASM_JIT_FUNC_INSTRS, WASM_JIT_BYTES_PER_INSTR, WASM_JIT_MAX_FUNC_INSTRS, WASM_JIT_MAX_HELPER_PARAMS, WASM_JIT_PROBE_INFO_BYTES, WASM_JIT_FEATURE_RETURN_CALL, WASM_JIT_FEATURE_SIMD128, WASM_JIT_FEATURE_EVICT, WASM_JIT_LOG_CAP, WASM_JIT_ENTRY_SIG, SIG_ENTRY, SIG_EMPTY, WASM_JIT_TABLE_IMPORT, WASM_JIT_NATIVE_SECTION, EPERM, E2BIG, ENOEXEC, ENOMEM, EFAULT, EINVAL, ENOSPC, ENOTSUP, ESTALE, ERRNO_NAME, OP_NAME, ALLOWED_SECTIONS, SECTION_NAME, KIND_NAME, VALTYPE_NAME, HEAPTYPE_NAME, EPOCH_SEQ_LIMIT, epochTag, epochSeq, RETURN_CALL_PROBE, SIMD128_PROBE, featureBits, ENGINE_TEXT_CAP, UNSAFE_CHARS, errText, UTF8, Malformed, Refused, OverBudget, lebLen, K_BAD, K_NONE, K_BLOCK, K_U32, K_BRTABLE, K_CALLIND, K_MEMARG, K_MEMIDX, K_LEB, K_F32, K_F64, K_SELT, K_FC, K_FD, K_FE, K_HEAPTYPE, K_TRYTABLE, K_END, OP1, R_EH, R_TABLE, R_REF, DENY1, R_SEG, DENYFC, SIMD_RESERVED, R_ATOMIC_WAIT, DENYFE, RV, malformed, tooDeep, pastEnd, DEPTH, TARGETS, tooLong, unknownOp, defaultDeny, INSTRS, WARM_BODY, WARM_CODE, scanWarm, imageFactsCache, imageSnapshots, slotPools; var init_wasmJit = __esm({ "../../linux-in-the-browser/hardwarejs/src/wasmJit.mjs"() { "use strict"; SYS_WASM_JIT = 1031; WASM_JIT_PROBE = 0; WASM_JIT_INSTALL = 1; WASM_JIT_RESET = 2; WASM_JIT_ERROR = 3; WASM_JIT_REGISTER_HELPERS = 4; WASM_JIT_EVICT = 5; WASM_JIT_ABI = 2; WASM_JIT_MAX_MODULE_BYTES = 4 << 20; WASM_JIT_MAX_LIVE_SLOTS = 65536; WASM_JIT_MAX_LIVE_BYTES = 64 << 20; WASM_JIT_MAX_FUNCS = 256; WASM_JIT_MAX_HELPERS = 64; WASM_JIT_MAX_LIVE_INSTALLS = 4096; WASM_JIT_MAX_LIVE_FUNCS = WASM_JIT_MAX_LIVE_SLOTS; WASM_JIT_MAX_TABLE = 1 << 20; WASM_JIT_MAX_TYPES = 16; WASM_JIT_MAX_NESTING = 1024; WASM_JIT_MAX_LOCALS = 256; WASM_JIT_MAX_LIVE_INSTRS = 20 << 16; WASM_JIT_INSTALL_INSTRS = 112; WASM_JIT_FUNC_INSTRS = 6; WASM_JIT_BYTES_PER_INSTR = 112; WASM_JIT_MAX_FUNC_INSTRS = 1024; WASM_JIT_MAX_HELPER_PARAMS = 8; WASM_JIT_PROBE_INFO_BYTES = 56; WASM_JIT_FEATURE_RETURN_CALL = 1; WASM_JIT_FEATURE_SIMD128 = 2; WASM_JIT_FEATURE_EVICT = 4; WASM_JIT_LOG_CAP = 16; WASM_JIT_ENTRY_SIG = "(i32,i32,f32)->i32"; SIG_ENTRY = Uint8Array.of(96, 3, 127, 127, 125, 1, 127); SIG_EMPTY = Uint8Array.of(96, 0, 0); WASM_JIT_TABLE_IMPORT = "__wasm_jit_table"; WASM_JIT_NATIVE_SECTION = "llvm.func_attr.annotate.hwjs.native.v1"; EPERM = 1; E2BIG = 7; ENOEXEC = 8; ENOMEM = 12; EFAULT = 14; EINVAL = 22; ENOSPC = 28; ENOTSUP = 95; ESTALE = 116; ERRNO_NAME = { [EPERM]: "EPERM", [E2BIG]: "E2BIG", [ENOEXEC]: "ENOEXEC", [ENOMEM]: "ENOMEM", [EFAULT]: "EFAULT", [EINVAL]: "EINVAL", [ENOSPC]: "ENOSPC", [ENOTSUP]: "ENOTSUP", [ESTALE]: "ESTALE" }; OP_NAME = ["PROBE", "INSTALL", "RESET", "ERROR", "REGISTER_HELPERS", "EVICT"]; ALLOWED_SECTIONS = /* @__PURE__ */ new Set([0, 1, 2, 3, 7, 10]); SECTION_NAME = [ "custom", "type", "import", "function", "table", "memory", "global", "export", "start", "element", "code", "data", "datacount", "tag" ]; KIND_NAME = ["function", "table", "memory", "global", "tag"]; VALTYPE_NAME = { 127: "i32", 126: "i64", 125: "f32", 124: "f64", 123: "v128", 112: "funcref", 111: "externref", 110: "anyref", 109: "eqref", 108: "i31ref", 107: "structref", 106: "arrayref", 105: "exnref", 113: "nullref", 114: "nullexternref", 115: "nullfuncref", 116: "nullexnref" }; HEAPTYPE_NAME = { 112: "func", 111: "extern", 110: "any", 109: "eq", 108: "i31", 107: "struct", 106: "array", 105: "exn", 113: "none", 114: "noextern", 115: "nofunc", 116: "noexn" }; EPOCH_SEQ_LIMIT = 1 << 23; epochTag = -1; epochSeq = 0; RETURN_CALL_PROBE = Uint8Array.of( 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 ); SIMD128_PROBE = Uint8Array.of( 0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 23, 1, 21, 0, 253, 12, ...new Array(16).fill(0), 26, 11 ); featureBits = -1; ENGINE_TEXT_CAP = 240; UNSAFE_CHARS = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/g; errText = (e) => wasmJitCleanText(e instanceof Error ? e.message : String(e)); UTF8 = new TextDecoder("utf-8", { fatal: true }); Malformed = class extends Error { }; Refused = class extends Error { constructor(errno, text) { super(text); this.errno = errno; } }; OverBudget = class extends Error { constructor(fn2, total, max) { super(`the module's instructions reach ${total} by the end of function ${fn2} > ${max}`); this.fn = fn2; this.total = total; } }; lebLen = (v) => v < 128 ? 1 : v < 16384 ? 2 : v < 2097152 ? 3 : v < 268435456 ? 4 : 5; K_BAD = 0; K_NONE = 1; K_BLOCK = 2; K_U32 = 3; K_BRTABLE = 4; K_CALLIND = 5; K_MEMARG = 6; K_MEMIDX = 7; K_LEB = 8; K_F32 = 9; K_F64 = 10; K_SELT = 11; K_FC = 12; K_FD = 13; K_FE = 14; K_HEAPTYPE = 15; K_TRYTABLE = 16; K_END = 17; OP1 = new Uint8Array(256); for (const op of [0, 1, 5, 15, 26, 27]) OP1[op] = K_NONE; OP1[11] = K_END; for (const op of [2, 3, 4]) OP1[op] = K_BLOCK; for (const op of [12, 13, 16, 18, 32, 33, 34, 35, 36]) OP1[op] = K_U32; OP1[14] = K_BRTABLE; OP1[17] = K_CALLIND; OP1[19] = K_CALLIND; OP1[28] = K_SELT; for (let op = 40; op <= 62; op++) OP1[op] = K_MEMARG; OP1[63] = K_MEMIDX; OP1[65] = K_LEB; OP1[66] = K_LEB; OP1[67] = K_F32; OP1[68] = K_F64; for (let op = 69; op <= 196; op++) OP1[op] = K_NONE; OP1[252] = K_FC; OP1[253] = K_FD; OP1[254] = K_FE; R_EH = "exception handling: a catch would swallow the host's unwind exception, a throw would unwind the emulator's frames from outside the coroutine protocol"; R_TABLE = "table access: the process table and the JIT table are written by the host only"; R_REF = "function references: generated code calls only through call_indirect on the JIT table"; DENY1 = /* @__PURE__ */ new Map([ [6, ["try", K_BLOCK, R_EH]], [7, ["catch", K_U32, R_EH]], [8, ["throw", K_U32, R_EH]], [9, ["rethrow", K_U32, R_EH]], [10, ["throw_ref", K_NONE, R_EH]], [24, ["delegate", K_U32, R_EH]], [25, ["catch_all", K_NONE, R_EH]], [31, ["try_table", K_TRYTABLE, R_EH]], [20, ["call_ref", K_U32, R_REF]], [21, ["return_call_ref", K_U32, R_REF]], [37, ["table.get", K_U32, R_TABLE]], [38, ["table.set", K_U32, R_TABLE]], [64, ["memory.grow", K_MEMIDX, "memory.grow: the size of the address space is the kernel's"]], [208, ["ref.null", K_HEAPTYPE, R_REF]], [209, ["ref.is_null", K_NONE, R_REF]], [210, ["ref.func", K_U32, R_REF]], [211, ["ref.eq", K_NONE, R_REF]], [212, ["ref.as_non_null", K_NONE, R_REF]], [213, ["br_on_null", K_U32, R_REF]], [214, ["br_on_non_null", K_U32, R_REF]], [251, ["0xfb (GC prefix)", K_BAD, "the GC proposal is not part of the generated-code ABI"]] ]); R_SEG = "segment ops: generated modules carry no data or element segments"; DENYFC = /* @__PURE__ */ new Map([ [8, ["memory.init", [K_U32, K_U32], R_SEG]], [9, ["data.drop", [K_U32], R_SEG]], [12, ["table.init", [K_U32, K_U32], R_TABLE]], [13, ["elem.drop", [K_U32], R_TABLE]], [14, ["table.copy", [K_U32, K_U32], R_TABLE]], [15, ["table.grow", [K_U32], R_TABLE]], [16, ["table.size", [K_U32], R_TABLE]], [17, ["table.fill", [K_U32], R_TABLE]] ]); SIMD_RESERVED = /* @__PURE__ */ new Set([ 154, 162, 165, 166, 175, 176, 178, 179, 180, 187, 194, 197, 198, 207, 208, 210, 211, 212, 226, 238 ]); R_ATOMIC_WAIT = "blocks the OS thread outside the coroutine protocol: every task on this Worker stalls"; DENYFE = /* @__PURE__ */ new Map([ [0, ["memory.atomic.notify", "wakes waiters on the shared memory outside the kernel's futex protocol"]], [1, ["memory.atomic.wait32", R_ATOMIC_WAIT]], [2, ["memory.atomic.wait64", R_ATOMIC_WAIT]] ]); RV = 0; malformed = (fn2, pos) => new Malformed(`function ${fn2}: instruction at byte ${pos} runs past its body`); tooDeep = (fn2, pos, depth, max) => new Refused(E2BIG, `function ${fn2}, byte ${pos}: blocks nest ${depth} deep > ${max}`); pastEnd = (fn2, pos) => new Malformed(`function ${fn2}: instruction at byte ${pos} follows the body's final end`); DEPTH = 0; TARGETS = 0; tooLong = (fn2, pos, n, max) => new Refused(E2BIG, `function ${fn2}, byte ${pos}: ${n} instructions > ${max} per function (br_table targets count one each)`); unknownOp = (fn2, at, what) => new Refused(EPERM, `function ${fn2}, byte ${at}: unknown opcode ${what} (the scan refuses what it does not know)`); defaultDeny = (fn2, at, name2, why) => { throw new Refused(EPERM, `function ${fn2}, byte ${at}: ${name2} is not allowed (${why})`); }; INSTRS = 0; WARM_BODY = [ 2, 64, 2, 127, 2, 0, 3, 64, 4, 64, 5, 11, 11, /* block types: empty, value, index */ 65, 5, 65, 232, 7, 65, 128, 128, 128, 128, 120, /* i32.const, 1/2/5-byte LEB */ 66, 128, 128, 4, 66, 1, /* i64.const */ 67, 0, 0, 128, 63, 68, 0, 0, 0, 0, 0, 0, 240, 63, /* f32/f64.const */ 32, 0, 32, 129, 1, 33, 1, 34, 2, 35, 0, 36, 0, /* locals/globals */ 40, 2, 0, 40, 2, 128, 8, 54, 2, 4, 63, 0, /* load, load off=1024, store, memory.size */ 14, 2, 0, 1, 0, 12, 0, 13, 128, 1, /* br_table, br, br_if (2-byte) */ 16, 129, 1, 17, 0, 0, 18, 0, 19, 1, 0, /* call, call_indirect, return_call(_indirect) */ 28, 1, 127, 27, 26, 106, 69, /* typed select, select, drop, numeric */ 252, 0, 252, 10, 0, 0, 252, 11, 0, /* trunc_sat, memory.copy, memory.fill */ 253, 0, 4, 0, 253, 12, ...new Array(16).fill(0), /* v128.load, v128.const */ 253, 21, 0, 253, 84, 0, 0, 0, 253, 98, 253, 213, 1, /* lane, load lane, popcnt, i64x2.mul */ 254, 3, 0, 254, 16, 2, 0, 254, 72, 2, 128, 1, /* atomic.fence, load, cmpxchg off=128 */ 11, 11, 11, 11 /* the three blocks, then the body */ ]; WARM_CODE = Uint8Array.from([1, ...uleb32(WARM_BODY.length + 3), 1, 2, 123, ...WARM_BODY]); scanWarm = false; imageFactsCache = /* @__PURE__ */ new WeakMap(); imageSnapshots = /* @__PURE__ */ new WeakMap(); slotPools = /* @__PURE__ */ new WeakMap(); } }); // ../../linux-in-the-browser/hardwarejs/src/capsummaryRegistry.mjs function refuse(reason) { throw new Error(`hwjs-capsummary: ${reason}`); } function word(value, label) { if (!Number.isInteger(value) || value < -2147483648 || value > 4294967295) refuse(`invalid ${label}`); return value >>> 0; } function snapshotWord(x) { if (!Number.isInteger(x) || x < 0 || x > 4294967295) refuse("invalid snapshot word"); return x; } function version(v) { if (word(v, "version") !== CAPSUMMARY_RECORD_VERSION) refuse(`unknown record version ${v >>> 0} (expected ${CAPSUMMARY_RECORD_VERSION})`); } function mask64(mask) { if (typeof mask !== "bigint") refuse("invalid i64 nocapture mask"); return BigInt.asUintN(64, mask); } function createCapsummaryRegistry(snapshot = { records: [], targets: [] }) { const modules2 = /* @__PURE__ */ new Map(); const targets = /* @__PURE__ */ new Map(); const interposed = /* @__PURE__ */ new Map(); let size = 0; function meet(mid, sig, bits) { let entries = modules2.get(mid); const previous = entries?.get(sig); if (previous === void 0 && size === CAPSUMMARY_MAX_RECORDS) refuse(`per-image record capacity ${CAPSUMMARY_MAX_RECORDS} exhausted`); if (!entries) modules2.set(mid, entries = /* @__PURE__ */ new Map()); entries.set(sig, previous === void 0 ? bits : previous & bits); if (previous === void 0) size++; } function meetTarget(fn2, sig, bits, mid) { const previous = targets.get(fn2); if (previous === void 0) { if (targets.size === CAPSUMMARY_MAX_TARGETS) refuse(`per-image target capacity ${CAPSUMMARY_MAX_TARGETS} exhausted`); targets.set(fn2, { sig, bits, mid }); return; } if (previous.sig !== sig || previous.mid !== mid) refuse(`function pointer ${fn2} registered as signature ${previous.sig} of module ${previous.mid} and again as signature ${sig} of module ${mid}`); previous.bits &= bits; } function rows(list, width, what) { if (list instanceof Uint32Array) { if (list.length % width !== 0) refuse(`invalid snapshot ${what}`); const out = []; for (let i = 0; i < list.length; i += width) out.push(Array.from(list.subarray(i, i + width))); return out; } if (!Array.isArray(list)) refuse("invalid snapshot"); return list.map((row) => { if (!Array.isArray(row) || row.length !== width) refuse(`invalid snapshot ${what}`); return row.map(snapshotWord); }); } function parse(snap) { if (!snap) refuse("invalid snapshot"); const recs = rows(snap.records, 4, "record").map(([mid, sig, low, high]) => [mid, sig, BigInt(low) | BigInt(high) << 32n]); const tgts = rows(snap.targets, 5, "target").map(([fn2, sig, mid, low, high]) => [fn2, sig, mid, BigInt(low) | BigInt(high) << 32n]); return { recs, tgts }; } { const { recs, tgts } = parse(snapshot); for (const [mid, sig, bits] of recs) { if (modules2.get(mid)?.has(sig)) refuse("duplicate snapshot record"); meet(mid, sig, bits); } for (const [fn2, sig, mid, bits] of tgts) { if (targets.has(fn2)) refuse("duplicate snapshot target"); meetTarget(fn2, sig, bits, mid); } } function lookup(signature, argument) { const sig = word(signature, "signature"), arg = word(argument, "argument"); if (arg >= 64) return 0; let acc = MASK64, found = false; for (const entries of modules2.values()) { const bits = entries.get(sig); if (bits !== void 0) { found = true; acc &= bits; } } return found && bit(acc, arg) ? 1 : 0; } return { /* Records and targets: what a carrier has to ship. */ get size() { return size + targets.size; }, register(v, signature, mask, moduleId) { version(v); const sig = word(signature, "signature"), mid = word(moduleId, "module id"); meet(mid, sig, mask64(mask)); return 1; }, registerTarget(v, signature, mask, fn2, moduleId) { version(v); const sig = word(signature, "signature"), mid = word(moduleId, "module id"); const ptr = word(fn2, "function pointer"), bits = mask64(mask); if (interposed.get(mid)?.has(ptr)) return 1; meetTarget(ptr, sig, bits, mid); return 1; }, /* Module `moduleId`'s GOT entry for a function it defines holds `fn`, * another module's copy: its target registration of `fn` is dropped. */ interpose(moduleId, fn2) { const mid = word(moduleId, "module id"), ptr = word(fn2, "function pointer"); let ptrs = interposed.get(mid); if (!ptrs) interposed.set(mid, ptrs = /* @__PURE__ */ new Set()); ptrs.add(ptr); }, lookup, /* The callee's own record when it has one of the site's signature, else * the per-signature AND. */ lookupCallee(signature, argument, callee) { const sig = word(signature, "signature"), arg = word(argument, "argument"); const t = targets.get(word(callee, "callee")); if (t !== void 0 && t.sig === sig) return arg < 64 && bit(t.bits, arg) ? 1 : 0; return lookup(sig, arg); }, /* Every module's record of one signature, [moduleId, mask], and a callee's * own record, for a refusal to name which of them cleared the argument. */ records(signature) { const sig = word(signature, "signature"); const out = []; for (const [mid, entries] of modules2) { const bits = entries.get(sig); if (bits !== void 0) out.push([mid, bits]); } return out; }, target(callee) { const t = targets.get(word(callee, "callee")); return t === void 0 ? void 0 : { sig: t.sig, bits: t.bits, mid: t.mid }; }, /* Another carrier's snapshot of the same image: add what is missing and * meet what is shared. */ merge(snap) { const { recs, tgts } = parse(snap); let added = 0; for (const [mid, sig, bits] of recs) { if (!modules2.get(mid)?.has(sig)) added++; meet(mid, sig, bits); } for (const [fn2, sig, mid, bits] of tgts) { if (!targets.has(fn2)) added++; meetTarget(fn2, sig, bits, mid); } return added; }, removeModule(moduleId) { const mid = word(moduleId, "module id"); let removed = 0; const entries = modules2.get(mid); if (entries) { size -= entries.size; removed += entries.size; modules2.delete(mid); } for (const [fn2, t] of targets) { if (t.mid === mid) { targets.delete(fn2); removed++; } } interposed.delete(mid); return removed; }, /* Flat words, so all 64 mask bits survive structured clone. A snapshot * rides every placement record, and the host keeps those: as arrays of * rows, a large image's targets cost the host hundreds of MiB of JS heap. */ snapshot() { const records = new Uint32Array(size * 4); let r = 0; for (const [mid, entries] of modules2) { for (const [sig, bits] of entries) { records[r++] = mid; records[r++] = sig; records[r++] = Number(bits & 0xffffffffn); records[r++] = Number(bits >> 32n); } } const tgts = new Uint32Array(targets.size * 5); let t5 = 0; for (const [fn2, t] of targets) { tgts[t5++] = fn2; tgts[t5++] = t.sig; tgts[t5++] = t.mid; tgts[t5++] = Number(t.bits & 0xffffffffn); tgts[t5++] = Number(t.bits >> 32n); } return { records, targets: tgts }; } }; } var CAPSUMMARY_RECORD_VERSION, CAPSUMMARY_MAX_RECORDS, CAPSUMMARY_MAX_TARGETS, MASK64, bit; var init_capsummaryRegistry = __esm({ "../../linux-in-the-browser/hardwarejs/src/capsummaryRegistry.mjs"() { "use strict"; CAPSUMMARY_RECORD_VERSION = 1; CAPSUMMARY_MAX_RECORDS = 16384; CAPSUMMARY_MAX_TARGETS = 1 << 20; MASK64 = (1n << 64n) - 1n; bit = (bits, arg) => (bits & 1n << BigInt(arg)) !== 0n; } }); // ../../linux-in-the-browser/hardwarejs/src/pause.mjs function isPaused(word2) { return word2 !== null && Atomics.load(word2, 0) === 1; } async function waitOutPause(word2) { while (isPaused(word2)) { if (typeof Atomics.waitAsync === "function") { const r = Atomics.waitAsync(word2, 0, 1, WAIT_BOUND_MS); if (r.async) await r.value; } else { await new Promise((resolve) => setTimeout(resolve, TIMER_FALLBACK_MS)); } } } var WAIT_BOUND_MS, TIMER_FALLBACK_MS; var init_pause = __esm({ "../../linux-in-the-browser/hardwarejs/src/pause.mjs"() { "use strict"; WAIT_BOUND_MS = 200; TIMER_FALLBACK_MS = 50; } }); // ../../linux-in-the-browser/hardwarejs/src/violationWitness.mjs function globalAddr(exports, name2) { const g = exports?.[name2]; if (!g || typeof g.value !== "number") return -1; return g.value >>> 0; } function readCString(bytes, at, cap) { let end = at; const limit = Math.min(at + cap, bytes.length); while (end < limit && bytes[end] !== 0) end++; if (end <= at) return ""; return new TextDecoder("utf-8", { fatal: false }).decode(bytes.slice(at, end)); } function readViolationWitness(exports, memory) { if (hasTcbRuntime(exports)) return readBlockWitness(exports, memory); const pendingLanes = globalAddr(exports, "__hwjs_violation_pending_lanes"); const bufLanes = globalAddr(exports, "__hwjs_violation_buf_lanes"); const pendingFlat = globalAddr(exports, "__hwjs_violation_pending"); const bufFlat = globalAddr(exports, "__hwjs_violation_buf"); const laned = pendingLanes >= 0 && bufLanes >= 0; const flat = pendingFlat >= 0 && bufFlat >= 0; if (!laned && !flat) { return { readable: false, why: "this image exports neither __hwjs_violation_pending_lanes/__hwjs_violation_buf_lanes nor the non-laned __hwjs_violation_pending/__hwjs_violation_buf, so its undelivered violations cannot be read. Absence of a witness line here is NOT evidence that no violation fired \u2014 it is evidence that nobody could look. The link has to name them: the user-image export list lives in brintium (brintld --export-if-defined + the DCE roots), the kernel one in scripts/link-vmlinux.sh.", found: [] }; } let bytes; try { bytes = new Uint8Array(memory.buffer); } catch (e) { return { readable: false, why: `the image's memory could not be viewed: ${e instanceof Error ? e.message : String(e)}`, found: [] }; } const i32 = (() => { try { return new Int32Array(memory.buffer); } catch { return null; } })(); if (i32 === null) return { readable: false, why: "no i32 view of the image memory", found: [] }; const found = []; const consider = (laneIdx, pendingAddr, bufAddr) => { if (pendingAddr + 4 > bytes.length || bufAddr >= bytes.length) return; if ((Atomics.load(i32, pendingAddr >> 2) | 0) !== 1) return; const text = readCString(bytes, bufAddr, VIOLATION_BUF_STRIDE); if (!VIOLATION_PREFIXES.some((p) => text.startsWith(p))) return; found.push({ lane: laneIdx, text: text.replace(/\n+$/, "") }); }; if (laned) { let cap = VIOLATION_LANE_CEILING; try { if (typeof exports.__hwjs_lane_cap === "function") { const n = exports.__hwjs_lane_cap() | 0; if (n > 0 && n < cap) cap = n; } } catch (_e) { } for (let l = 0; l < cap; l++) { consider(l, pendingLanes + 4 * l, bufLanes + VIOLATION_BUF_STRIDE * l); } } if (flat) consider(-1, pendingFlat, bufFlat); return { readable: true, why: "", found }; } function readBlockWitness(exports, memory) { let bytes, i32; try { bytes = new Uint8Array(memory.buffer); i32 = new Int32Array(memory.buffer); } catch (e) { return { readable: false, why: `the image's memory could not be viewed: ${e instanceof Error ? e.message : String(e)}`, found: [] }; } let off; try { off = { pending: exports.__hwjs_tcb_field(TCBF.VIOLATION_PENDING) >>> 0, buf: exports.__hwjs_tcb_field(TCBF.VIOLATION_BUF) >>> 0, id: exports.__hwjs_tcb_field(TCBF.ID) >>> 0 }; } catch (e) { return { readable: false, why: `the runtime's block layout could not be read (__hwjs_tcb_field threw: ${e instanceof Error ? e.message : String(e)})`, found: [] }; } const blocks = new Set(listThreadBlocks(exports)); try { if (typeof exports.__hwjs_tcb_initial === "function") blocks.add(exports.__hwjs_tcb_initial() >>> 0); } catch (_e) { } const found = []; for (const b of blocks) { const p = b + off.pending; if (!b || p + 4 > bytes.length || b + off.buf >= bytes.length) continue; if ((Atomics.load(i32, p >> 2) | 0) !== 1) continue; const text = readCString(bytes, b + off.buf, VIOLATION_BUF_STRIDE); if (!VIOLATION_PREFIXES.some((x) => text.startsWith(x))) continue; const id = b + off.id + 4 <= bytes.length ? i32[b + off.id >> 2] >>> 0 : -1; found.push({ lane: -1, thread: id, text: text.replace(/\n+$/, "") }); } return { readable: true, why: "", found }; } function formatViolationWitness(witness, where) { if (!witness.readable) { return `hwjs-witness ${where}: the undelivered-violation witness could not be read \u2014 ${witness.why}`; } if (witness.found.length === 0) return null; const lines = witness.found.map((f) => ` ${f.thread !== void 0 ? `[thread ${f.thread}]` : f.lane < 0 ? "(unlaned)" : `[lane ${f.lane}]`} ${f.text}`); return `hwjs-witness ${where}: ${witness.found.length} violation sentence(s) were formatted and NEVER DELIVERED \u2014 the runtime set its pending word, tried to write(2) them to fd 2, and the write did not report every byte gone. They say what the trap does not: ${lines.join("\n")}`; } var VIOLATION_BUF_STRIDE, VIOLATION_LANE_CEILING, VIOLATION_PREFIXES; var init_violationWitness = __esm({ "../../linux-in-the-browser/hardwarejs/src/violationWitness.mjs"() { "use strict"; init_hwjsTcb(); VIOLATION_BUF_STRIDE = 512; VIOLATION_LANE_CEILING = 2048; VIOLATION_PREFIXES = ["hwjs-user-rt VIOLATION", "hwjs-rt VIOLATION"]; } }); // ../../linux-in-the-browser/hardwarejs/src/worker.mjs function decodeExecArgvPrefix(bytes, argc, flags, requested) { const dec2 = new TextDecoder(); const argv = []; let start = 0; for (let i = 0; i < bytes.length; i++) { if (bytes[i] === 0) { argv.push(dec2.decode(bytes.subarray(start, i))); start = i + 1; } } if (argv.length !== argc || start !== bytes.length) { throw new Error( `#75 shebang: argv-prefix blob decodes to ${argv.length} strings (tail=${bytes.length - start}B) but the kernel reports argc=${argc} \u2014 refusing to exec with torn argv (never-silent)` ); } const f = flags >>> 0; if (f & ~WASM_EXEC_PREFIX_KEEPS_ARGV0) { throw new Error( `exec argv prefix: the kernel reports shape bits 0x${f.toString(16)}, of which 0x${(f & ~WASM_EXEC_PREFIX_KEEPS_ARGV0).toString(16)} this host does not know \u2014 refusing to splice [${argv.join(", ")}] in a shape it cannot apply (never-silent)` ); } const keepArgv0 = (f & WASM_EXEC_PREFIX_KEEPS_ARGV0) !== 0; if (keepArgv0 && !(requested >>> 0 & WASM_EXEC_HOST_KEEPS_ARGV0)) { throw new Error( `exec argv prefix: the kernel built the keep-argv[0] shape [${argv.join(", ")}] for a load whose begin did not request it (host flags 0x${(requested >>> 0).toString(16)}) \u2014 kernel/host argv handshake broken, refusing to guess which argv[0] survives (never-silent)` ); } return { argv, keepArgv0 }; } function spliceExecArgvPrefix(prefix, argv) { const caller = Array.isArray(argv) ? argv : []; if (!prefix) return caller; if (prefix.keepArgv0) { return [...prefix.argv, ...caller.length ? caller : [""]]; } return [...prefix.argv, ...caller.slice(1)]; } function migAbort(mig, code2) { for (; ; ) { const s = Atomics.load(mig, 0) | 0; if (s === MIG_BOUND || s === MIG_ABORTED) return false; if (Atomics.compareExchange(mig, 0, s, MIG_ABORTED) === s) { Atomics.store(mig, 2, code2 | 0); Atomics.notify(mig, 0); return true; } } } function setExecImageResolver(fn2) { execImageResolver = fn2; } function readKernelScatterImage(kernelBuffer, sglistOffset, nsegs, totalSize, what, privateOut = false) { const cap = kernelBuffer.byteLength; const off = sglistOffset >>> 0; const n = nsegs >>> 0; const total = totalSize >>> 0; if (n === 0) { throw new Error( `hwjs-scatter: ${what} declares 0 segments (sglist 0x${off.toString(16)}, total ${total}B) \u2014 a staged image always has at least one segment; kernel/host ABI skew (never-silent)` ); } if (n > 65536) { throw new Error( `hwjs-scatter: ${what} declares ${n} segments, far past the kernel's WASM32_IMG_MAX_SEGS cap \u2014 REFUSED as a torn or misread request (never-silent)` ); } const listBytes = n * SGSEG_SIZE2; if (off === 0 || off > cap || listBytes > cap - off) { throw new Error( `hwjs-scatter: ${what} segment list [0x${off.toString(16)}, +${listBytes}B) (${n} segments) is outside kernel memory (${cap}B) \u2014 REFUSED (never-silent)` ); } const dv = new DataView(kernelBuffer, off, listBytes); const segs = []; let sum = 0; for (let i = 0; i < n; i++) { const sOff = dv.getUint32(i * SGSEG_SIZE2, true) >>> 0; const sLen = dv.getUint32(i * SGSEG_SIZE2 + 4, true) >>> 0; if (sLen === 0) { throw new Error( `hwjs-scatter: ${what} segment ${i}/${n} has length 0 (offset 0x${sOff.toString(16)}) \u2014 the kernel never emits empty segments; REFUSED (never-silent)` ); } if (sOff === 0 || sOff > cap || sLen > cap - sOff) { throw new Error( `hwjs-scatter: ${what} segment ${i}/${n} is [0x${sOff.toString(16)}, +${sLen}B) which runs past kernel memory (${cap}B) \u2014 REFUSED (never-silent)` ); } sum += sLen; if (sum > total) { throw new Error( `hwjs-scatter: ${what} segments through ${i}/${n} already sum to ${sum}B but the kernel declares ${total}B total \u2014 REFUSED (never-silent)` ); } segs.push([sOff, sLen]); } if (sum !== total) { throw new Error( `hwjs-scatter: ${what} segment lengths sum to ${sum}B but the kernel declares ${total}B total \u2014 REFUSED (never-silent)` ); } const out = new Uint8Array(privateOut ? new ArrayBuffer(total) : new SharedArrayBuffer(total)); let at = 0; for (const [sOff, sLen] of segs) { out.set(new Uint8Array(kernelBuffer, sOff, sLen), at); at += sLen; } return out; } function wasmSource3(bytes) { if (!(bytes && bytes.buffer instanceof SharedArrayBuffer)) return bytes; if (sharedWasmSourceOk2 === void 0) { try { const probe = new Uint8Array(new SharedArrayBuffer(8)); probe.set([0, 97, 115, 109, 1, 0, 0, 0]); new WebAssembly.Module(probe); sharedWasmSourceOk2 = true; } catch (_e) { sharedWasmSourceOk2 = false; } } return sharedWasmSourceOk2 ? bytes : bytes.slice(); } function readKernelStagedImage(exp, kernelBuffer, prefix, what, privateOut = false) { const sglistFn = exp[`${prefix}_sglist_addr`]; const nsegsFn = exp[`${prefix}_nsegs`]; const sizeFn = exp[`${prefix}_image_size`]; if (typeof sglistFn !== "function" || typeof nsegsFn !== "function" || typeof sizeFn !== "function") { throw new Error( `hwjs-scatter: this vmlinux does not export ${prefix}_sglist_addr/${prefix}_nsegs \u2014 it predates the segment-list staging ABI (memory-contract Part C) and this host has no flat-image path. Rebuild the kernel and the host together (never-silent).` ); } return readKernelScatterImage( kernelBuffer, sglistFn() >>> 0, nsegsFn() >>> 0, sizeFn() >>> 0, what, privateOut ); } function decodeMaybeShared3(view) { const shared = typeof SharedArrayBuffer !== "undefined" && view.buffer instanceof SharedArrayBuffer; return __utf8Decoder.decode(shared ? view.slice() : view); } async function runA4bCoexistProbe(init, post) { const report = (text) => post({ kind: "dmesg", level: 6, text: `[a4b] ${text}` }); const SYS_getpid = 39; const result = { ok: false, instances: [], notes: [] }; const mkInit = (memory, tidSentinel) => ({ kind: "init", mode: "fork", pid: 0, tid: tidSentinel, ppid: 0, cpuId: init.cpuId | 0, vmlinuxModule: init.vmlinuxModule, kernelMemory: init.kernelMemory, kernelMemoryWasm: init.kernelMemoryWasm, memory }); try { report(`instantiating vmlinux instance #1 cpu_id=${init.cpuId | 0}`); const r1 = await instantiateProcessWorkerVmlinux(mkInit(init.userMemoryA, 1001), post); if (!r1) { report("instance #1 FAILED to instantiate"); post({ kind: "a4b-result", result }); return; } const pidA1 = r1.instance.exports.wasm_syscall(SYS_getpid, 0, 0, 0, 0, 0, 0) | 0; result.instances.push({ idx: 1, kernelPid: r1.kernelPid | 0, taskAddr: r1.perProcessTaskAddr >>> 0, getpid: pidA1 }); report(`instance #1: kernelPid=${r1.kernelPid | 0} task=0x${(r1.perProcessTaskAddr >>> 0).toString(16)} getpid=${pidA1}`); report("resetting processVmlinuxInstanceCount (BYPASS R-K10-W1) for instance #2"); processVmlinuxInstanceCount = 0; report(`instantiating vmlinux instance #2 cpu_id=${init.cpuId | 0} (same lane)`); let r2 = null; try { r2 = await instantiateProcessWorkerVmlinux(mkInit(init.userMemoryB, 1002), post); } catch (e) { report(`instance #2 instantiate THREW: ${e instanceof Error ? e.message : String(e)}`); } if (!r2) { report("instance #2 FAILED \u2014 2nd same-Worker vmlinux instantiation is a HARD blocker for Approach A"); result.notes.push("second-instance-instantiate-failed"); post({ kind: "a4b-result", result }); return; } const pidB = r2.instance.exports.wasm_syscall(SYS_getpid, 0, 0, 0, 0, 0, 0) | 0; result.instances.push({ idx: 2, kernelPid: r2.kernelPid | 0, taskAddr: r2.perProcessTaskAddr >>> 0, getpid: pidB }); report(`instance #2: kernelPid=${r2.kernelPid | 0} task=0x${(r2.perProcessTaskAddr >>> 0).toString(16)} getpid=${pidB}`); const pidA2 = r1.instance.exports.wasm_syscall(SYS_getpid, 0, 0, 0, 0, 0, 0) | 0; result.instances.push({ idx: 1, phase: "after-2", getpid: pidA2 }); report(`instance #1 re-getpid after #2: getpid=${pidA2} (expect == ${pidA1})`); const distinctTasks = r1.perProcessTaskAddr >>> 0 !== r2.perProcessTaskAddr >>> 0; const distinctPids = pidA1 !== pidB; const inst1Intact = pidA1 === pidA2; result.distinctTasks = distinctTasks; result.distinctPids = distinctPids; result.inst1Intact = inst1Intact; result.ok = distinctTasks && distinctPids && inst1Intact; report(`COEXIST: distinctTasks=${distinctTasks} distinctPids=${distinctPids} inst1Intact=${inst1Intact} => ${result.ok ? "OK" : "BROKEN"}`); } catch (e) { result.error = e instanceof Error ? `${e.message} ${e.stack}` : String(e); report(`PROBE THREW: ${result.error}`); } post({ kind: "a4b-result", result }); } function laneInboxPending() { return laneInboxI32 !== null && Atomics.load(laneInboxI32, 0) > 0; } function laneInboxReceived() { if (laneInboxI32 === null) return; if (Atomics.sub(laneInboxI32, 0, 1) <= 0) Atomics.add(laneInboxI32, 0, 1); } function othersRunnableIn(residents, self2, inboxPending = false) { if (inboxPending) return true; for (const r of residents) { if (r === self2) continue; const p = r.probe; if (p === null) return true; try { if (p()) return true; } catch (_e) { return true; } } return false; } function laneOthersRunnable(self2) { return othersRunnableIn(laneResidents, self2, laneInboxPending()); } function preemptAdopt(init) { if (!(init?.preemptCtl instanceof SharedArrayBuffer) || !init.preemptPort) return; preemptCtlI32 = new Int32Array(init.preemptCtl); preemptClock = new Float64Array(init.preemptCtl); preemptPort = init.preemptPort; preemptSlot = init.preemptSlot | 0; preemptSlotBase = PT.HEADER + preemptSlot * PT.STRIDE; preemptSliceMax = init.mergedCpu0Lane === true ? PREEMPT_SLICE_MERGED_US : PREEMPT_SLICE_ALONE_US; } function preemptUnregister(token) { if (token !== 0 && preemptPort !== null) { try { preemptPort.postMessage({ t: "unreg", token }); } catch (_e) { } } } async function heapTrace(post, cpuId, residents, mode) { await heapStatsReady; if (!heapStatsFn) return; try { if (typeof globalThis.gc === "function") globalThis.gc(); } catch (_e) { } const { used } = heapStatsFn(); let more = ""; try { const v8 = await import("node:v8"); const h = v8.getHeapStatistics(); const mb = (n) => (n / 1048576).toFixed(2); more = ` heap-physical=${mb(h.total_physical_size)} malloced=${mb(h.malloced_memory)} external=${mb(h.external_memory ?? 0)} rss=${mb(globalThis.process?.memoryUsage?.rss?.() ?? 0)}`; } catch (_e) { } try { post({ kind: "dmesg", level: 6, text: `hwjs-heap cpu=${cpuId} residents=${residents} adding=${mode || "fork"} live-heap=${(used / 1048576).toFixed(2)} MiB${more}` }); } catch (_e) { } const at = parseInt(globalThis.process?.env?.HWJS_HEAP_SNAPSHOT_AT ?? "", 10); const dir = globalThis.process?.env?.HWJS_HEAP_SNAPSHOT_DIR; if (!heapSnapshotTaken && Number.isFinite(at) && residents >= at && dir) { heapSnapshotTaken = true; try { const v8 = await import("node:v8"); const f = v8.writeHeapSnapshot(`${dir}/cpu${cpuId}-residents${residents}.heapsnapshot`); post({ kind: "dmesg", level: 6, text: `hwjs-heap cpu=${cpuId} snapshot ${f}` }); } catch (e) { try { post({ kind: "dmesg", level: 4, text: `hwjs-heap cpu=${cpuId} snapshot failed: ${e?.message ?? e}` }); } catch (_e) { } } } } async function threadHeapRefusal(post) { await heapStatsReady; if (!heapStatsFn) { if (!heapGuardNoted) { heapGuardNoted = true; try { post({ kind: "dmesg", level: 4, text: "hwjs-heap-guard: this realm exposes no JS heap statistics, so a pool Worker cannot refuse threads before its heap runs out here (the guard is INACTIVE, not passing)" }); } catch (_e) { } } return ""; } const { used, limit } = heapStatsFn(); if (!(limit > 0)) return ""; const margin = Math.min(HEAP_GUARD_MAX_MARGIN, limit / 8); if (limit - used >= margin) return ""; const mb = (n) => `${Math.round(n / (1024 * 1024))} MiB`; return `thread refused by this CPU Worker's heap guard: its JS heap is at ${mb(used)} of a ${mb(limit)} limit (${mb(limit - used)} left; the guard keeps ${mb(margin)}) \u2014 one more resident would risk the Worker and every task on it`; } function neededViewCheckIn(mainBytes, name2, digest, want, post) { let surface = neededSurfaces.get(digest); if (!surface) { const lib = workerSharedLibs.get(digest); const b = lib.bytes instanceof Uint8Array ? lib.bytes : new Uint8Array(lib.bytes); surface = neededViewSurface(b); neededSurfaces.set(digest, surface); } const have = neededView(mainBytes, surface); if (have !== want) { throw new Error( `hwjs-libc: ${neededSoname(name2)} on this machine is another build (${digest.slice(0, 16)}\u2026) than the ${neededDigest(name2).slice(0, 16)}\u2026 this image was linked against, and its interface as this image uses it differs (view ${have.slice(0, 16)}\u2026, recorded ${want.slice(0, 16)}\u2026) \u2014 relink the image, or install the build it names (never-silent refuse)` ); } const key = `${name2} ${digest}`; if (!neededSubstituteNoted.has(key)) { neededSubstituteNoted.add(key); try { if (post) post({ kind: "dmesg", level: 5, text: `hwjs-libc: ${neededSoname(name2)}: bound build ${digest.slice(0, 16)}\u2026 in place of ${neededDigest(name2).slice(0, 16)}\u2026 by soname; the interface the image uses is the one it was linked against (view ${want.slice(0, 16)}\u2026)` }); } catch (_e) { } } } function sharedLibsMerge(entries, post) { if (!Array.isArray(entries)) return; for (const e of entries) { if (!e || typeof e.digest !== "string" || !e.bytes) continue; const prev = workerSharedLibs.get(e.digest); const entry = mergeSharedLib(prev, e); if (typeof e.path === "string" && e.path.startsWith("/") && !sharedLibPaths.has(e.digest)) { sharedLibPaths.set(e.digest, e.path); } if (prev) continue; workerSharedLibs.set(e.digest, entry); try { if (post) post({ kind: "dmesg", level: 7, text: `hwjs-libc: shared-lib store gained digest ${e.digest.slice(0, 16)}\u2026 (${e.bytes.length}B; store size ${workerSharedLibs.size})` }); } catch (_e) { } } } function heapCollectSoon(delayMs = HEAP_COLLECT_DELAY_MS) { if (heapCollectTimer !== null) return; const wait = Math.max(delayMs, heapCollectLast + HEAP_COLLECT_MIN_GAP_MS - Date.now()); heapCollectTimer = setTimeout(() => { heapCollectTimer = null; heapCollectLast = Date.now(); collectGarbageNow(); }, wait); try { heapCollectTimer?.unref?.(); } catch (_e) { } } function hostRpcWait({ ctrl, sliceMs, onSlice, red, wait = Atomics.wait }) { const ignoreReaped = !!(red && red.ignoreReaped); for (; ; ) { if (Atomics.load(ctrl, C.STATE) === RESPONSE) return "response"; if (!ignoreReaped && Atomics.load(ctrl, CTRL_I32_REAPED) !== 0) return "reaped"; wait(ctrl, C.STATE, REQUEST, sliceMs); if (Atomics.load(ctrl, C.STATE) === RESPONSE) return "response"; onSlice(); } } function isDesignedUnwind(e) { return e === HWJS_EXIT_UNWIND || e === HWJS_EXEC_UNWIND || e === HWJS_REAPED_UNWIND || e === HWJS_TASK_REAPED; } function startCpuWorker(init, post) { const CPU_WORKER_YIELD_MS = 3; const cpuId = init.cpuId | 0; preemptAdopt(init); if (init.laneInbox instanceof SharedArrayBuffer && init.laneInbox.byteLength >= 4) { laneInboxI32 = new Int32Array(init.laneInbox, 0, 1); } heapChargeBind(init.heapCharge, cpuId); sharedLibsMerge(init.sharedLibs, post); userImagesMerge(init.userImages); linkFactsMerge(init.linkFacts); const residentTasks = /* @__PURE__ */ new Map(); const execResolvers = /* @__PURE__ */ new Map(); const stats = { blocks: 0, switches: 0, byTid: {}, adds: 0, dones: 0 }; const dbg = (s) => { try { post({ kind: "dmesg", level: 6, text: `[cpu-worker cpu=${cpuId}] ${s}` }); } catch (_e) { } }; const sched = { cpuId, residentTasks, /* RESCHED park hook (run()'s flat/nested RESCHED branch). This task is * blocked on its in-flight syscall; yield the JS event loop a bounded slice * so a PEER resident task drives + the kernel Worker/backend land the * completion, then return so the caller re-drives (re-issue -> resume * preserved chain -> re-check). Strictly serial: the wasm drive between * yields is synchronous, so only one instance is ever resumed at a time. */ async blockYield(tid, _reason) { const t = residentTasks.get(tid); if (t && t.status !== "done") t.status = "blocked"; stats.blocks++; stats.byTid[tid] = (stats.byTid[tid] | 0) + 1; const y0 = SCHED_TRACE ? schedNow() : 0; schedTrace(post, `YIELD cpu=${cpuId} tid=${tid} reason=${_reason ?? "blockYield"} site=sched.blockYield slice=${CPU_WORKER_YIELD_MS}ms`); await new Promise((r) => setTimeout(r, CPU_WORKER_YIELD_MS)); if (SCHED_TRACE) { schedTrace(post, `RESUME cpu=${cpuId} tid=${tid} site=sched.blockYield waited=${(schedNow() - y0).toFixed(1)}ms`); } if (t && t.status !== "done") t.status = "runnable"; stats.switches++; } }; const loopMonitor = makeWorkerLoopMonitor({ cpuId, residents: () => residentTasks.values(), emit: (level, text) => post({ kind: "dmesg", level, text }), /* * WHOSE THREAD THIS ACTUALLY IS. On the merged lane it is not this lane's * alone — CPU 0 and pool lane 1 share the thread that called bootKernel * (PLAN-COLLAPSED-CPU0 §2.1) — and the monitor can only see the residents * of ITS OWN lane. That gap is not academic: a stall line reading * `cpu=1 loop unavailable 10104.3ms … residents=[none]` was read for a * night as "a lane with nothing on it froze", which is a mystery, when the * true statement is "the kernel's own drive held the shared thread and * this lane happened to be empty", which is a place to look. */ mergedCpu0Lane: init.mergedCpu0Lane === true }); const addTask = (spec) => { const tid = spec.tid; if (spec.claim) { const claim = new Int32Array(spec.claim); const prev = Atomics.compareExchange(claim, 0, 0, 2); if (prev !== 0) { dbg(`hwjs#3: add-task routeKey=${spec.routeKey} tid=${tid} DECLINED (claim=${prev}: host canceled after lane-starvation timeout and re-placed the task; this stale placement is dropped)`); return; } Atomics.notify(claim, 0); } if (spec.mode === "migrate-resume") { if (!(spec.mig instanceof SharedArrayBuffer)) { post({ kind: "error", routeKey: spec.routeKey, tid, message: `add-task REFUSED: mode='migrate-resume' for tid=${tid} carries no migration protocol word. A migration hand-off is a two-phase commit and the word IS the commit; without it this lane would start driving a task the source still believes it owns (never-silent).` }); return; } const mig = new Int32Array(spec.mig); Atomics.store(mig, 3, 1); if (Atomics.compareExchange(mig, 0, MIG_OFFERED, MIG_CLAIMED) !== MIG_OFFERED) { dbg(`hwjs-migrate: add-task routeKey=${spec.routeKey} tid=${tid} DECLINED (offer already terminal: state=${Atomics.load(mig, 0) | 0}); the source kept the task`); return; } Atomics.notify(mig, 0); try { if (typeof process !== "undefined" && process.env && process.env.HWJS_MIGRATE_RED_DROP === "1") { post({ kind: "dmesg", level: 4, text: `hwjs-migrate RED_DROP: cpu=${cpuId} CLAIMED tid=${tid} and is abandoning it without binding \u2014 simulating a destination that dies inside the commit window (test knob)` }); return; } } catch (_e) { } } if ((spec.mode || "fork") === "thread") { const missing = [ "argRegionOffset", "stackPointerOffset", "tlsPointerOffset" ].filter((k) => typeof spec[k] !== "number"); if (missing.length > 0 || spec.rtThread !== true) { const why = missing.length > 0 ? `missing/non-numeric field(s): ${missing.join(", ")}` : `rtThread=${spec.rtThread} (a co-resident thread MUST be a user-runtime thread that attaches its own block; the legacy shape shares the process main's block and cannot co-reside)`; post({ kind: "error", routeKey: spec.routeKey, tid, message: `add-task REFUSED: mode='thread' spec for tid=${tid} routeKey=${spec.routeKey} is incomplete \u2014 ${why}. A thread task init is only well-formed with rtThread + argRegionOffset + stackPointerOffset + tlsPointerOffset; defaulting any of them would run the thread over a garbage arg region on the process main's block (never-silent).` }); return; } } if (stopped) { post({ kind: "error", routeKey: spec.routeKey, tid, message: `add-task REFUSED: this CPU-Worker realm (cpu=${cpuId}) has been cooperatively STOPPED (the machine is tearing down and this lane has no Worker to terminate \u2014 PLAN-COLLAPSED-CPU0 \xA75). The task would never be driven; refusing it is what makes that visible to the placer instead of presenting as a task that was placed and never ran.` }); return; } stats.adds++; if (HEAP_TRACE) heapTrace(post, cpuId, stats.adds - 1 - stats.dones, spec.mode); try { if (typeof process !== "undefined" && process.env.A4C_DBG) console.error(`[a4c-w] addTask tid=${tid} routeKey=${spec.routeKey} mode=${spec.mode} cpu=${cpuId}`); } catch (_e) { } try { if (typeof process !== "undefined" && process.env.A4C_FORKDBG) post({ kind: "dmesg", level: 6, text: `[a4c-fork] addTask tid=${tid} routeKey=${spec.routeKey} mode=${spec.mode} cpu=${cpuId} (run() will instantiate+drive)` }); } catch (_e) { } residentTasks.set(tid, { tid, status: "runnable", argv: spec.argv }); schedTrace(post, `ADD cpu=${cpuId} tid=${tid} pid=${spec.pid != null ? spec.pid : tid} mode=${spec.mode || "fork"} rt=${spec.rtThread ? 1 : 0} routeKey=${spec.routeKey} residents=${residentTasks.size}`); const routeKey = spec.routeKey; const taskPost = (m) => { try { post(routeKey != null ? { ...m, routeKey } : { ...m, tid }); } catch (_e) { } }; const taskInit = { kind: "init", mode: spec.mode || "fork", pid: spec.pid != null ? spec.pid : tid, tid, ppid: spec.ppid | 0, cpuId, /* the POOL Worker's id, SHARED by residents */ wasmBytes: spec.wasmBytes, ...typeof spec.imgKey === "string" ? { imgKey: spec.imgKey } : {}, memory: spec.memory, ...spec.memoryId !== void 0 ? { memoryId: spec.memoryId } : {}, ctrl: spec.ctrl, ...spec.userDirtyCell instanceof SharedArrayBuffer ? { userDirtyCell: spec.userDirtyCell } : {}, ...spec.placementCell instanceof SharedArrayBuffer ? { placementCell: spec.placementCell } : {}, ...spec.threadImageEpoch !== void 0 ? { threadImageEpoch: spec.threadImageEpoch } : {}, vmlinuxModule: init.vmlinuxModule, hwjsRtModule: init.hwjsRtModule, hwjsRtBytes: init.hwjsRtBytes, hwjsRtProvenance: init.hwjsRtProvenance, kernelMemory: init.kernelMemory, kernelMemoryWasm: init.kernelMemoryWasm, /* PLAN-THREADS §4 step 6: the machine-wide kernel-lane mutex SAB * (a SHARED bit like kernelMemoryWasm — every resident of this * pool Worker locks the same lane words). */ ...init.kernelLaneLocks !== void 0 ? { kernelLaneLocks: init.kernelLaneLocks } : {}, ...init.fileMapGen instanceof SharedArrayBuffer ? { fileMapGen: init.fileMapGen } : {}, /* The host's per-lane busy words: the drive bracket marks this lane * busy, so the host places new processes elsewhere while it is. */ ...init.laneBusy instanceof SharedArrayBuffer ? { laneBusy: init.laneBusy } : {}, /* COLLAPSED CPU 0 (PLAN-COLLAPSED-CPU0): does this lane share its JS * thread with CPU 0? Carried per TASK because every site that must * refuse rather than block — the unbounded in-kernel atomic wait, the * lane mutex, the host-RPC wait — is inside the task's own closure. */ ...init.mergedCpu0Lane === true ? { mergedCpu0Lane: true } : {}, /* The demux key this task's messages already carry (taskPost above). * The merged lane's SYNCHRONOUS syscall door is a direct function call * rather than a message, so it cannot be tagged on the way out — it has * to NAME its asker, and a pool lane can hold several residents. Same * key, same map, so a door and a post can never disagree about which * task they are about. */ ...routeKey != null ? { routeKey } : {}, allowMultiInstance: true, /* N user tasks over this Worker's one kernel instance */ /* forceWasmSyscall only when the spec asks (e.g. the direct A-4.b proof * harness, which has no SAB-RPC responder). Spawn-ring-placed tasks DO * have a per-process SAB-RPC responder (the kernelSpawnHandler per-task * handler), so they keep the SAME syscall routing as the single-task * path — preserving the green gate behaviour. */ ...spec.forceWasmSyscall ? { forceWasmSyscall: true } : {}, ...spec.mode ? { mode: spec.mode } : {}, ...Array.isArray(spec.argv) ? { argv: spec.argv } : {}, ...Array.isArray(spec.envp) ? { envp: spec.envp } : {}, ...Array.isArray(spec.lowFdRoutes) ? { lowFdRoutes: spec.lowFdRoutes } : {}, ...spec.sharedFileMaps && typeof spec.sharedFileMaps === "object" ? { sharedFileMaps: spec.sharedFileMaps } : {}, ...spec.signalPendingOffset !== void 0 ? { signalPendingOffset: spec.signalPendingOffset } : {}, /* The spawn handler answers 'leader-hold' (leaderHoldUntilGroupEmpty). * Whitelisted like every other rider: a field this copy drops is a * capability the task silently does not have. */ ...spec.leaderHold === 1 ? { leaderHold: 1 } : {}, ...spec.inheritFiles !== void 0 ? { inheritFiles: spec.inheritFiles } : {}, ...Array.isArray(spec.fdActions) ? { fdActions: spec.fdActions } : {}, ...spec.tlsBase !== void 0 ? { tlsBase: spec.tlsBase } : {}, ...spec.forkHandle !== void 0 ? { forkHandle: spec.forkHandle } : {}, ...spec.forkOwner !== void 0 ? { forkOwner: spec.forkOwner } : {}, ...spec.parentSp !== void 0 ? { parentSp: spec.parentSp } : {}, /* Step 7 (fork under threads): the caller's kept lane index. */ ...spec.forkTcb !== void 0 ? { forkTcb: spec.forkTcb } : {}, ...spec.mainTlsBase !== void 0 ? { mainTlsBase: spec.mainTlsBase } : {}, /* CPU MIGRATION riders. Every one of them already has a twin on the * fork or thread path — the two globals ride fork's tlsBase/parentSp, * the runtime block rides fork's forkTcb, the routing cache and the * placement record ride both — with two exceptions that are new * because migration is the only path that binds rather than * allocates: migrateTaskAddr (which task) and migratePid (the check * that it is that task). `mig` is the commit word. */ ...spec.mig !== void 0 ? { mig: spec.mig } : {}, ...spec.migrateTaskAddr !== void 0 ? { migrateTaskAddr: spec.migrateTaskAddr } : {}, ...spec.migratePid !== void 0 ? { migratePid: spec.migratePid } : {}, /* The vfork shape: the child (a thread-shaped resident that is a * process of its own) and the exec of one, which binds its task. */ ...spec.vforkChild === true ? { vforkChild: true } : {}, ...spec.bindTaskAddr !== void 0 ? { bindTaskAddr: spec.bindTaskAddr >>> 0, bindTaskPid: spec.bindTaskPid | 0 } : {}, ...spec.migrateSrcCpu !== void 0 ? { migrateSrcCpu: spec.migrateSrcCpu | 0 } : {}, ...spec.sp !== void 0 ? { sp: spec.sp } : {}, ...spec.sideSpTop !== void 0 ? { sideSp: spec.sideSp >>> 0, sideSpTop: spec.sideSpTop >>> 0 } : {}, ...spec.mode === "migrate-resume" && spec.tcb !== void 0 ? { tcb: spec.tcb >>> 0 } : {}, ...spec.dlopenFork && typeof spec.dlopenFork === "object" ? { dlopenFork: spec.dlopenFork } : {}, /* SYS_wasm_jit's record of a MIGRATING task (wasmJit.mjs migrateOut): * its compiled Modules and the slots they sit at, re-placed at the * same indices before the commit. */ ...spec.mode === "migrate-resume" && spec.wasmJit && typeof spec.wasmJit === "object" ? { wasmJit: spec.wasmJit } : {}, /* SYS_wasm_jit's fork floor (wasmJit.mjs forkFloor): the child's JIT * never hands out a slot number its parent's could have used. */ ...spec.mode === "fork-resume" && Number.isInteger(spec.wasmJitFloor) && spec.wasmJitFloor > 0 ? { wasmJitFloor: spec.wasmJitFloor } : {}, /* §6.4: the host-reserved libhwjs-rt window rides the add-task spec * (perTaskInit) exactly like the dedicated-Worker init. */ ...spec.hwjsRtWindowBase !== void 0 ? { hwjsRtWindowBase: spec.hwjsRtWindowBase, hwjsRtWindowSize: spec.hwjsRtWindowSize } : {}, /* The host-reserved libc.so window (twin of the rt window). */ ...spec.hwjsLibcWindowBase !== void 0 ? { hwjsLibcWindowBase: spec.hwjsLibcWindowBase, hwjsLibcWindowSize: spec.hwjsLibcWindowSize } : {}, /* THREAD RESIDENCY (PLAN-THREAD-POOL-RESIDENCY step A): the per-thread fields, validated * above — the co-resident twin of the dedicated thread Worker's * init. */ ...(spec.mode || "fork") === "thread" ? { rtThread: true, argRegionOffset: spec.argRegionOffset | 0, stackPointerOffset: spec.stackPointerOffset | 0, tlsPointerOffset: spec.tlsPointerOffset | 0 } : {}, ...init.pauseBuffer !== void 0 ? { pauseBuffer: init.pauseBuffer } : {} }; if (spec.dlopenFork) spec.dlopenFork = void 0; if (spec.wasmJit) spec.wasmJit = void 0; const releaseOffer = (code2) => { if (spec.mode !== "migrate-resume") return; if (!(spec.mig instanceof SharedArrayBuffer)) return; const mig = new Int32Array(spec.mig); if (migAbort(mig, code2)) { post({ kind: "dmesg", level: 3, text: `hwjs-migrate: cpu=${cpuId} tid=${tid} FAILED to bind the migrated task and released the offer (abort code ${code2}) \u2014 the source never released it and resumes driving it (loud, attributed)` }); } }; const laneRec = { probe: null, quiet: false, due: Infinity }; laneResidents.add(laneRec); laneRecByInit.set(taskInit, laneRec); if (routeKey != null) reapableTasks.set(routeKey, taskInit); const unreapable = () => { if (routeKey != null && reapableTasks.get(routeKey) === taskInit) reapableTasks.delete(routeKey); }; run(taskInit, taskPost, sched).then( () => { preemptUnregister(laneRec.preemptToken ?? 0); unreapable(); laneResidents.delete(laneRec); releaseOffer(MIG_ABORT_BIND); const t = residentTasks.get(tid); if (t) t.status = "done"; residentTasks.delete(tid); execResolvers.delete(tid); threadPlacementProviders.delete(taskInit); stats.dones++; schedTrace(post, `DONE cpu=${cpuId} tid=${tid} residents=${residentTasks.size}`); heapCollectSoon(); }, (e) => { preemptUnregister(laneRec.preemptToken ?? 0); unreapable(); laneResidents.delete(laneRec); releaseOffer(MIG_ABORT_BIND); const t = residentTasks.get(tid); if (t) t.status = "error"; residentTasks.delete(tid); execResolvers.delete(tid); threadPlacementProviders.delete(taskInit); schedTrace(post, `DONE cpu=${cpuId} tid=${tid} status=error residents=${residentTasks.size}`); heapCollectSoon(); taskPost({ kind: "error", message: `cpu-worker task tid=${tid}: ${e instanceof Error ? `${e.message} ${e.stack}` : String(e)}` }); } ); }; let stopped = false; const stopCpuWorker = () => { if (stopped) return; stopped = true; try { clearInterval(beatTimer); } catch (_e) { } try { clearInterval(heapCollectTick); } catch (_e) { } dbg(`cooperative stop: ${residentTasks.size} resident(s) keep running to their own exit; no further placement is accepted on this lane`); }; cpuWorker = { cpuId, residentTasks, sched, addTask, execResolvers, stats, dbg, stop: stopCpuWorker, isStopped: () => stopped }; const laneBusyBeat = init.laneBusy instanceof SharedArrayBuffer && cpuId << 2 < init.laneBusy.byteLength ? new Int32Array(init.laneBusy) : null; const beatTimer = setInterval(() => { if (laneBusyBeat) Atomics.store(laneBusyBeat, cpuId, 0); const gap = loopMonitor.beat(); if (SCHED_TRACE) { const who = [...residentTasks.values()].map((t) => `${t.tid}:${t.status}`).join(",") || "none"; schedTrace(post, `BEAT cpu=${cpuId} #${loopMonitor.stats().beats} gap=${gap.toFixed(1)}ms period=${WORKER_BEAT_MS}ms residents=[${who}] adds=${stats.adds} dones=${stats.dones} blocks=${stats.blocks} switches=${stats.switches}`); } }, WORKER_BEAT_MS); try { beatTimer?.unref?.(); } catch (_e) { } const heapCollectTick = setInterval(() => { if (residentTasks.size > 0) heapCollectSoon(0); }, HEAP_COLLECT_PERIOD_MS); try { heapCollectTick?.unref?.(); } catch (_e) { } try { if (typeof process !== "undefined" && process.env.A4C_DBG) console.error(`[a4c-w] startCpuWorker cpu=${cpuId} ready`); } catch (_e) { } dbg(`pool Worker ready (cpu_id=${cpuId}); awaiting add-task`); for (const spec of Array.isArray(init.tasks) ? init.tasks : []) addTask(spec); } function bindWorker({ post, onMessage: onMessage3, onTerminate, callHostSync }) { workerHostPost = post; workerHostSyncCall = typeof callHostSync === "function" ? callHostSync : null; onTerminate?.(() => { cpuWorker?.stop?.(); }); onMessage3(async (msg) => { if (msg?.kind === "add-task" || msg?.kind === "thread-placement-request") laneInboxReceived(); try { if (msg?.kind === "exec-image") { if (cpuWorker && msg.tid != null && cpuWorker.execResolvers.has(msg.tid)) { const r2 = cpuWorker.execResolvers.get(msg.tid); cpuWorker.execResolvers.delete(msg.tid); if (r2) r2(msg); return; } const r = execImageResolver; execImageResolver = null; if (r) r(msg); return; } if (msg?.kind === "a4b-coexist") { await runA4bCoexistProbe(msg, post); return; } if (msg?.kind === "preempt-timer") { void runPreemptTimer(msg.ctl); return; } if (msg?.kind === "preempt-port") { preemptAddPort(msg.port); return; } if (msg?.kind === "preempt-adopt") { preemptAdopt(msg); return; } if (msg?.kind === "cpu-worker") { startCpuWorker(msg, post); return; } if (msg?.kind === "heap-collect") { heapCollectSoon(0); return; } if (msg?.kind === "add-task") { if (!cpuWorker) { post({ kind: "error", pid: -1, message: "add-task before cpu-worker init" }); return; } cpuWorker.addTask(msg.spec || msg); return; } if (msg?.kind === "dl-placement-deltas") { const done = dlPlacementPulls.get(msg.seq | 0); if (done) { dlPlacementPulls.delete(msg.seq | 0); done(msg); } return; } if (msg?.kind === "task-reap") { const ti = reapableTasks.get(msg.routeKey); if (ti) { ti.reapedBy = String(msg.why ?? "group-death reap"); try { Atomics.notify(new Int32Array(ti.ctrl, 0, 16), C.STATE); } catch (_e) { } } return; } if (msg?.kind === "shared-lib") { sharedLibsMerge(msg.sharedLibs, post); return; } if (msg?.kind === "user-image") { userImagesMerge(msg.userImages); return; } if (msg?.kind === "link-facts") { linkFactsMerge(msg.entries); return; } if (msg?.kind === "thread-image-drop-idle") { const n = threadImagesDropIdle(msg.memoryId | 0); if (n > 0) { post({ kind: "dmesg", level: 6, text: `hwjs-thread-image DROPPED ${n} idle process image(s) of memory ${msg.memoryId | 0} on cpu=${msg.cpuId | 0}` }); } return; } if (msg?.kind === "thread-image-release") { const n = threadImagesRelease(msg.memoryId | 0, msg.beforeEpoch); if (n > 0) { post({ kind: "dmesg", level: 6, text: `hwjs-thread-image RELEASED ${n} process image(s) of memory ${msg.memoryId | 0} on cpu=${msg.cpuId | 0}` }); } return; } if (msg?.kind === "thread-placement-request") { const want = msg.pid | 0; const seq = msg.seq | 0; const rk = msg.routeKey !== void 0 ? { routeKey: msg.routeKey } : {}; let prov = null; for (const p of threadPlacementProviders.values()) { if ((p.getPid() | 0) === want) { prov = p; break; } } if (!prov) { post({ kind: "thread-placement", seq, pid: want, ...rk, error: `no resident task with kernel pid ${want} in this Worker \u2014 thread-placement-request cannot be served (never-silent)` }); return; } try { post({ kind: "thread-placement", seq, pid: want, ...rk, dlopenFork: prov.build() }); } catch (e) { post({ kind: "thread-placement", seq, pid: want, ...rk, error: `thread-placement snapshot failed: ` + (e instanceof Error ? e.message : String(e)) }); } return; } if (msg?.kind === "task-probe") { const seq = msg.seq | 0; const tasks = []; for (const p of threadPlacementProviders.values()) { const pid = p.getPid() | 0; if (typeof p.probe !== "function") { tasks.push({ pid, probeReady: false }); continue; } try { tasks.push({ ...p.probe(), probeReady: true }); } catch (e) { tasks.push({ pid, probeReady: false, error: e instanceof Error ? e.message : String(e) }); } } post({ kind: "task-probe-reply", seq, cpuId: cpuWorker ? cpuWorker.cpuId : null, residents: cpuWorker ? [...cpuWorker.residentTasks.values()].map((t) => ({ tid: t.tid | 0, status: String(t.status) })) : null, schedStats: cpuWorker ? { ...cpuWorker.stats } : null, /* An ISOLATE property, reported per realm so it outlives the * residents that caused it — see isolateModuleCacheCensus. */ isolateModuleCaches: isolateModuleCacheCensus(), tasks }); return; } if (msg?.kind !== "init") { post({ kind: "error", pid: -1, message: `unknown msg ${msg?.kind}` }); return; } try { await run(msg, post); } finally { threadPlacementProviders.delete(msg); } } catch (e) { post({ kind: "error", pid: msg?.pid ?? -1, message: e instanceof Error ? `${e.message} ${e.stack ?? ""}` : String(e) }); } }); } function nextBreathCost(hi, prevSample, sample, dtMs, halfMs) { const s = sample < prevSample ? sample : prevSample; const kept = hi > 0 ? hi * Math.pow(2, -(dtMs > 0 ? dtMs : 0) / halfMs) : 0; return s > kept ? s : kept; } function breathRefillFor(costMs, horizonMs, base, max) { if (!(costMs > 0) || !(horizonMs > 0)) return base; const u = horizonMs / costMs; return u <= base ? base : u >= max ? max : Math.floor(u); } function othersSliceHorizonIn(residents, self2, nowMs2, targetMs, frac, beside = true) { let h = targetMs; for (const r of residents) { if (r === self2) continue; if (!beside || r.probe === null || r.quiet !== true) return 0; const d = (r.due - nowMs2) * frac; if (!(d > 0)) return 0; if (d < h) h = d; } return h; } function flatBreathOf(status, reasonSlot) { if (status === 0) return { preempt: false }; if (status !== HWJS_PARK_PREEMPT) return null; if (reasonSlot >>> 0 !== 0) { throw new Error( `M-FLATDRIVE: PREEMPT park (status 6) with the reason slot still latched (${reasonSlot >>> 0}) \u2014 this image's user runtime predates HWJS_PARK_PREEMPT, whose in-wasm driver clears the slot as it returns 6; refusing before the next park trips the stale-reason violation (never-silent)` ); } return { preempt: true }; } function breathTakesLegacyDispatch(breath, signalPending, trampoline) { return !breath.preempt && trampoline !== null && signalPending(); } function unknownFlatDriveStatus(status) { return new Error( "M-FLATDRIVE: unexpected in-wasm driver status 0x" + (status >>> 0).toString(16) + " \u2014 not a PARK reason (0 NONE / 1 FORK / 2 EXEC / 3 DLOPEN / 4 RESCHED / 5 THREAD_EXIT / 6 PREEMPT) and not HWJS_DRIVE_DONE (0xD09E) / HWJS_DRIVE_DONE_LIVE (0xD09F). The _start()/__hwjs_drive_resume() return contract diverged; stop-and-report, do not loop." ); } function schedTrace(post, text) { if (!SCHED_TRACE) return; try { post({ kind: "dmesg", level: 6, text: `hwjs-schedtrace t=${schedNow().toFixed(1)} ${text}` }); } catch (_e) { } } function makeWorkerLoopMonitor({ cpuId, emit, residents, now = schedNow, thresholdMs = WORKER_STALL_THRESHOLD_MS, mergedCpu0Lane = false } = {}) { let beats = 0, maxGap = 0, stalls = 0; let last = now(); const emitLine = (level, text) => { try { emit(level, text); } catch (_e) { } }; const roster = () => { const r = typeof residents === "function" ? residents() : residents; return r ? [...r] : []; }; return { /* ONE turn of this Worker's event loop. `atMs` is the turn's timestamp — * defaulted from the clock, passed explicitly by a replay. Returns the * gap so a caller can narrate it without re-reading the clock. */ beat(atMs = now()) { const gap = atMs - last; last = atMs; beats++; if (gap > maxGap) maxGap = gap; const who = roster(); if (gap >= thresholdMs) { stalls++; if ((stalls & stalls - 1) === 0) { emitLine( 4, `hwjs-worker-stall cpu=${cpuId} loop unavailable ${gap.toFixed(1)}ms (threshold ${thresholdMs}ms) residents=[${who.map((t) => `${t.tid}:${t.status}`).join(",") || "none"}] occurrences=${stalls}` + (mergedCpu0Lane ? ` thread=MERGED \u2014 this lane shares its JS thread with CPU 0 (the kernel Worker and the inline device backends), and this monitor can only see LANE ${cpuId}'s residents. ${who.length === 0 ? "An empty roster here does NOT mean nothing was running: with no resident of its own, the only thing that can have held this thread is CPU 0 \u2014 look at what the kernel was doing, not for a lane that froze idle." : "CPU 0 was also on this thread and is not in the roster above, so the residents named are a lower bound on what could have held it."}` : ` thread=DEDICATED \u2014 this lane owns its JS thread, so the roster above is the complete list of what could have held it`) ); } } return gap; }, stats: () => ({ beats, maxGap, stalls }) }; } function holdReport(post, { cpu, pid, tid, site, label, fields, announce }) { const t0 = schedNow(); let next = t0 + SCHED_TRACE_HOLD_MS; let holds = 0; let announced = !!announce; const head = `cpu=${cpu ?? "?"} pid=${pid ?? "?"} tid=${tid ?? "?"} site=${site} label=${label}`; if (announced) schedTrace(post, `DRIVE-ENTER ${head}`); const extra = (n) => fields ? ` ${fields(n)}` : ""; return { holds: () => holds, /* Re-report while ONE hold is still running, so a hold that never ends is * still attributed. Cheap to call in a leg loop: one clock read and a * compare below the threshold. */ tick(n) { const nowMs2 = schedNow(); if (nowMs2 < next) return; next = nowMs2 + SCHED_TRACE_HOLD_MS; holds++; if (!announced) { announced = true; schedTrace(post, `DRIVE-ENTER ${head}`); } schedTrace(post, `HOLD ${head} #${holds} held=${(nowMs2 - t0).toFixed(1)}ms${extra(n)}`); }, /* Silent for a deferred reporter that never crossed the threshold — a * short bracket is not news, and this is what keeps the per-syscall sites * affordable. */ end(n) { if (!announced) return; schedTrace(post, `HOLD-END ${head} held=${(schedNow() - t0).toFixed(1)}ms${extra(n)} holds=${holds}`); } }; } function makeHwjsKernelLane(vmlinuxInstance, cpuId, kernelMemoryWasm, post, pid, kernelLaneLocks, tid, mergedCpu0Lane = false) { const exp = vmlinuxInstance.exports; const dataAddr = (name2) => { const g = exp[name2]; return g instanceof WebAssembly.Global ? g.value >>> 0 : 0; }; let violationWitnessReported = false; const reportUndeliveredViolations = (where) => { if (violationWitnessReported) return; violationWitnessReported = true; try { const w = readViolationWitness(exp, kernelMemoryWasm); const line = formatViolationWitness(w, where); if (line) post({ kind: "dmesg", level: 3, text: `${line} ` }); } catch (_e) { } }; const lanesBase = dataAddr("__hwjs_lane_hot"); const laneStrideAddr = dataAddr("__hwjs_lane_stride"); if (!lanesBase || !laneStrideAddr || typeof exp.hwjs_resume !== "function" || typeof exp.hwjs_done !== "function" || typeof exp.hwjs_destroy !== "function" || typeof exp.__hwjs_take_parked !== "function" || typeof exp.__hwjs_slice_enter !== "function" || typeof exp.__hwjs_slice_exit !== "function") { return null; } const lane = cpuId | 0; const ku32View = new Uint32Array(kernelMemoryWasm.buffer); const ku32 = () => ku32View; const laneWords = ku32()[laneStrideAddr >> 2] >>> 2; const slotIdx = (lanesBase >> 2) + lane * laneWords | 0; const ownerIdx = slotIdx + 1 | 0; const liveIdx = slotIdx + 5 | 0; const sliceIdx = slotIdx + 4 | 0; const laneLockI32 = kernelLaneLocks instanceof SharedArrayBuffer && lane >= 0 && lane << 2 < kernelLaneLocks.byteLength ? new Int32Array(kernelLaneLocks) : null; let laneLockDepth = 0; const LANE_LOCK_DEADLINE_MS = 18e4; const laneOwnerIdx = 32 + lane; let laneLockContended = false; function laneLockAcquire(label) { if (!laneLockI32) return; if (laneLockDepth++ > 0) return; if (Atomics.compareExchange(laneLockI32, lane, 0, 1) === 0) { if (laneOwnerIdx < laneLockI32.length) laneLockI32[laneOwnerIdx] = (pid ?? 0) | 0; laneLockContended = false; return; } const t0 = Date.now(); const dl = t0 + LANE_LOCK_DEADLINE_MS; let spun = true; let nextReport = t0 + LANE_WAIT_REPORT_MS; for (; ; ) { if (Atomics.compareExchange(laneLockI32, lane, 0, 2) === 0) { if (laneOwnerIdx < laneLockI32.length) laneLockI32[laneOwnerIdx] = (pid ?? 0) | 0; laneLockContended = spun; if (LANE_WAIT_REPORT_MS > 0 && Date.now() - t0 >= LANE_WAIT_REPORT_MS) { try { post({ kind: "dmesg", level: 4, text: `hwjs-lane[${lane}] WAIT-END ${label} (pid=${pid}) after ${Date.now() - t0}ms ` }); } catch (_e) { } } return; } spun = true; if (LANE_WAIT_REPORT_MS > 0 && Date.now() >= nextReport) { nextReport = Date.now() + LANE_WAIT_REPORT_MS; const holder = laneOwnerIdx < laneLockI32.length ? Atomics.load(laneLockI32, laneOwnerIdx) | 0 : 0; try { post({ kind: "dmesg", level: 4, text: `hwjs-lane[${lane}] WAIT ${label} (pid=${pid}) blocked ${Date.now() - t0}ms on holder tid=${holder} ` }); } catch (_e) { } } if (mergedCpu0Lane) { laneLockDepth--; const holder = laneOwnerIdx < laneLockI32.length ? Atomics.load(laneLockI32, laneOwnerIdx) | 0 : 0; throw new Error( `hwjs-lane[${lane}] FATAL (merged CPU 0): the lane mutex is HELD by tid=${holder} while this realm \u2014 the one that shares its JS thread with CPU 0 \u2014 tried to take it for ${label} (pid=${pid}). Exactly one realm may own the merged lane: the host's cpu-id allocator excludes lane ${lane} from every dedicated-Worker placement, so a second owner means that exclusion was broken. Refusing rather than waiting: an Atomics.wait here would block the kernel dispatcher, every kthread and (inline) the device backends on a peer this thread cannot schedule.` ); } if (Date.now() > dl) { laneLockDepth--; const holder = laneOwnerIdx < laneLockI32.length ? Atomics.load(laneLockI32, laneOwnerIdx) | 0 : 0; throw new Error( `hwjs-lane[${lane}] FATAL: cross-Worker lane mutex not acquired within ${LANE_LOCK_DEADLINE_MS}ms for ${label} (pid=${pid}) \u2014 a peer Worker (holder tid=${holder}) is wedged INSIDE a lane bracket (every hold is one bounded drive slice by construction). Refusing to drive a torn lane; never-silent.` ); } if (Atomics.compareExchange(laneLockI32, lane, 1, 2) !== 0) Atomics.wait(laneLockI32, lane, 2, 50); } } function laneLockRelease() { if (!laneLockI32) return; if (--laneLockDepth > 0) return; if (laneOwnerIdx < laneLockI32.length) laneLockI32[laneOwnerIdx] = 0; if (Atomics.exchange(laneLockI32, lane, 0) === 2) Atomics.notify(laneLockI32, lane); } const liveAtCreate = liveIdx >= 0 ? ku32()[liveIdx] >>> 0 : 0; const framesAtCreate = typeof exp.__hwjs_task_frames === "function" ? exp.__hwjs_task_frames() >>> 0 : 0; const hasTaskFrames = typeof exp.__hwjs_task_frames === "function"; const census = { lane, deferral: "F87c3-amended", /* lift condition: see block comment */ brackets: 0, /* bracketed export calls issued */ drives: 0, /* brackets that consumed + drove a park */ slices: 0, /* total resume legs across all drives */ frameResidue: 0, /* cumulative lane frame-live delta */ poisoned: null /* label of the first bracket call that trapped */ }; const HWJS_LANE_DBG = typeof process !== "undefined" && !!process.env.HWJS_LANE_DBG; function driveToDone(label, h, owner, hold = HOLD_REPORT_OFF) { let slices = 0; while (!exp.hwjs_done(h)) { if (HWJS_LANE_DBG && slices < 40) { try { post({ kind: "dmesg", level: 6, text: `hwjs-lane[${lane}] DBG drive ${label} slice=${slices} h=0x${(h >>> 0).toString(16)} owner=0x${(ku32()[ownerIdx] >>> 0).toString(16)}` }); } catch (_e) { } } exp.hwjs_resume(h); slices++; exp.__hwjs_take_parked(owner, h); if (SCHED_TRACE) hold.tick(slices); } const pAddr = typeof exp.__hwjs_promise_i32 === "function" ? exp.__hwjs_promise_i32(h) >>> 0 : 0; const value = pAddr ? ku32()[pAddr >> 2] | 0 : 0; exp.hwjs_destroy(h); census.drives++; census.slices += slices; return { value, slices }; } function bracketCensus(liveBefore) { if (liveIdx < 0) return; const d = (ku32()[liveIdx] >>> 0) - liveBefore | 0; if (d !== 0) { census.frameResidue += d; if (census.frameResidue > HWJS_LANE_RESIDUE_CEILING) { throw new Error( `hwjs-lane[${lane}] FATAL: frame residue ${census.frameResidue} crossed the never-silent ceiling ${HWJS_LANE_RESIDUE_CEILING} (F87 conf (3): the interim reported-not-fatal deferral does not cover unexplained unbounded growth)` ); } } } function bracket(label, call) { census.brackets++; laneLockAcquire(label); try { return bracketLocked(label, call); } finally { laneLockRelease(); } } function bracketLocked(label, call) { const liveBefore = liveIdx >= 0 ? ku32()[liveIdx] >>> 0 : 0; const hold = SCHED_TRACE ? holdReport(post, { cpu: lane, pid, tid, site: "bracket", label, announce: false, fields: (n) => `slices=${n}` }) : HOLD_REPORT_OFF; exp.__hwjs_slice_enter(); let ret; try { ret = call(); } catch (e) { if (!census.poisoned && !isDesignedUnwind(e)) census.poisoned = label; try { if (typeof exp.__hwjs_dump_park_trace === "function") { exp.__hwjs_dump_park_trace(); } } catch (_e2) { } reportUndeliveredViolations(`kernel lane ${lane} ${label}`); exp.__hwjs_slice_exit(); throw e; } const parked = ku32()[slotIdx] >>> 0; let drivenSlices = 0; if (parked !== 0) { const owner = ku32()[ownerIdx] >>> 0; const h = exp.__hwjs_take_parked(0, 0) >>> 0; let drive; try { drive = driveToDone(label, h, owner, hold); } catch (e) { if (!census.poisoned && !isDesignedUnwind(e)) census.poisoned = label; try { if (typeof exp.__hwjs_dump_park_trace === "function") { exp.__hwjs_dump_park_trace(); } } catch (_e2) { } reportUndeliveredViolations(`kernel lane ${lane} ${label} (mid-drive)`); exp.__hwjs_slice_exit(); throw e; } const { value, slices } = drive; drivenSlices = slices; post({ kind: "hwjs-lane-drive", pid, lane, label, handle: h, owner, slices }); ret = value; } exp.__hwjs_slice_exit(); bracketCensus(liveBefore); if (SCHED_TRACE) hold.end(drivenSlices); return ret; } const yieldWaitWord = new Int32Array(new SharedArrayBuffer(4)); const YIELD_SLEEP_MS = 2; const YIELD_SPIN_LEGS = 512; function bracketYielding(label, call) { census.brackets++; let backoffs = 0, parkedFlag = 0; const hold = SCHED_TRACE ? holdReport(post, { cpu: lane, pid, tid, site: "bracketYielding", label, announce: true, fields: (n) => `slices=${n} backoffs=${backoffs} parked=${parkedFlag} contended=${laneLockContended ? 1 : 0}` }) : HOLD_REPORT_OFF; laneLockAcquire(label); let ret; let h = 0, owner = 0; { const liveBefore = liveIdx >= 0 ? ku32()[liveIdx] >>> 0 : 0; exp.__hwjs_slice_enter(); try { ret = call(); } catch (e) { if (!census.poisoned && !isDesignedUnwind(e)) census.poisoned = label; try { if (typeof exp.__hwjs_dump_park_trace === "function") exp.__hwjs_dump_park_trace(); reportUndeliveredViolations(`kernel lane ${lane}`); } catch (_e2) { } exp.__hwjs_slice_exit(); laneLockRelease(); throw e; } const parked = ku32()[slotIdx] >>> 0; if (parked === 0) { exp.__hwjs_slice_exit(); bracketCensus(liveBefore); laneLockRelease(); if (SCHED_TRACE) hold.end(0); return ret; } owner = ku32()[ownerIdx] >>> 0; h = exp.__hwjs_take_parked(0, 0) >>> 0; parkedFlag = 1; exp.__hwjs_slice_exit(); laneLockRelease(); } let slices = 0; for (; ; ) { laneLockAcquire(label); exp.__hwjs_slice_enter(); let done, value = 0; try { done = !!exp.hwjs_done(h); if (!done) { exp.hwjs_resume(h); slices++; exp.__hwjs_take_parked(owner, h); done = !!exp.hwjs_done(h); } if (done) { const pAddr = typeof exp.__hwjs_promise_i32 === "function" ? exp.__hwjs_promise_i32(h) >>> 0 : 0; value = pAddr ? ku32()[pAddr >> 2] | 0 : 0; exp.hwjs_destroy(h); } } catch (e) { if (!census.poisoned && !isDesignedUnwind(e)) census.poisoned = label; try { if (typeof exp.__hwjs_dump_park_trace === "function") exp.__hwjs_dump_park_trace(); reportUndeliveredViolations(`kernel lane ${lane}`); } catch (_e2) { } exp.__hwjs_slice_exit(); laneLockRelease(); throw e; } exp.__hwjs_slice_exit(); laneLockRelease(); if (done) { census.drives++; census.slices += slices; post({ kind: "hwjs-lane-drive", pid, lane, label, handle: h, owner, slices }); if (SCHED_TRACE) hold.end(slices); return value; } if (SCHED_TRACE) hold.tick(slices); if (laneLockContended || slices % YIELD_SPIN_LEGS === 0) { if (SCHED_TRACE) backoffs++; Atomics.wait(yieldWaitWord, 0, 0, YIELD_SLEEP_MS); } } } const hasParkConsumer = typeof exp.__wasm32_set_park_consumer === "function"; const declareParkConsumerHost = () => hasParkConsumer ? exp.__wasm32_set_park_consumer(WASM32_PARK_CONSUMER_HOST) >>> 0 : WASM32_PARK_CONSUMER_NONE; const restoreParkConsumer = (prev) => { if (hasParkConsumer) exp.__wasm32_set_park_consumer(prev >>> 0); }; const hasTakeWouldBlock = typeof exp.__wasm32_take_syscall_would_block === "function"; let wouldBlockTakeNoted = false; function takeSyscallWouldBlock(label) { if (hasTakeWouldBlock) return (exp.__wasm32_take_syscall_would_block() | 0) !== 0; if (!wouldBlockTakeNoted) { wouldBlockTakeNoted = true; try { post({ kind: "dmesg", level: 4, text: `hwjs-lane[${lane}] this vmlinux exports no __wasm32_take_syscall_would_block, so a host drive (${label}) cannot tell a BLOCK park from a safepoint/budget park at a resume leg it owns; it drives such legs to completion exactly as before. The wasm_syscall route is unaffected (the kernel clears the flag and answers -517). Never-silent.` }); } catch (_e) { } } return false; } function driveWouldBlock(label, call, chain) { census.brackets++; const prevConsumer = declareParkConsumerHost(); try { return driveWouldBlockInner(label, call, chain); } finally { restoreParkConsumer(prevConsumer); } } function driveWouldBlockInner(label, call, chain) { let backoffs = 0, parkedFlag = chain.h ? 1 : 0, slices = 0; const hold = SCHED_TRACE ? holdReport(post, { cpu: lane, pid, tid, site: "driveWouldBlock", label, announce: true, fields: (n) => `slices=${n} backoffs=${backoffs} parked=${parkedFlag} contended=${laneLockContended ? 1 : 0}` }) : HOLD_REPORT_OFF; if (chain.h === 0) { laneLockAcquire(label); const liveBefore = liveIdx >= 0 ? ku32()[liveIdx] >>> 0 : 0; exp.__hwjs_slice_enter(); let ret; try { ret = call() | 0; } catch (e) { if (!census.poisoned && !isDesignedUnwind(e)) census.poisoned = label; try { if (typeof exp.__hwjs_dump_park_trace === "function") exp.__hwjs_dump_park_trace(); reportUndeliveredViolations(`kernel lane ${lane}`); } catch (_e2) { } exp.__hwjs_slice_exit(); laneLockRelease(); throw e; } const parked = ku32()[slotIdx] >>> 0; if (parked === 0) { const blocked = takeSyscallWouldBlock(label); exp.__hwjs_slice_exit(); bracketCensus(liveBefore); laneLockRelease(); if (SCHED_TRACE) hold.end(0); return { wouldBlock: ret === HWJS_LANE_WOULD_BLOCK || blocked, value: ret, slices: 0 }; } chain.owner = ku32()[ownerIdx] >>> 0; chain.h = exp.__hwjs_take_parked(0, 0) >>> 0; parkedFlag = 1; exp.__hwjs_slice_exit(); laneLockRelease(); } for (; ; ) { laneLockAcquire(label); exp.__hwjs_slice_enter(); let done, blocked = false, value = 0; const h = chain.h; try { done = !!exp.hwjs_done(h); if (!done) { exp.hwjs_resume(h); slices++; exp.__hwjs_take_parked(chain.owner, h); done = !!exp.hwjs_done(h); blocked = takeSyscallWouldBlock(label); } if (done) { const pAddr = typeof exp.__hwjs_promise_i32 === "function" ? exp.__hwjs_promise_i32(h) >>> 0 : 0; value = pAddr ? ku32()[pAddr >> 2] | 0 : 0; exp.hwjs_destroy(h); } } catch (e) { if (!census.poisoned && !isDesignedUnwind(e)) census.poisoned = label; try { if (typeof exp.__hwjs_dump_park_trace === "function") exp.__hwjs_dump_park_trace(); reportUndeliveredViolations(`kernel lane ${lane}`); } catch (_e2) { } exp.__hwjs_slice_exit(); laneLockRelease(); throw e; } exp.__hwjs_slice_exit(); laneLockRelease(); if (done) { const owner = chain.owner; chain.h = 0; chain.owner = 0; census.drives++; census.slices += slices; post({ kind: "hwjs-lane-drive", pid, lane, label, handle: h, owner, slices }); if (SCHED_TRACE) hold.end(slices); return { wouldBlock: false, value, slices }; } if (blocked) { census.slices += slices; if (SCHED_TRACE) hold.end(slices); return { wouldBlock: true, value: HWJS_LANE_WOULD_BLOCK, slices }; } if (SCHED_TRACE) hold.tick(slices); if (laneLockContended || slices % YIELD_SPIN_LEGS === 0) { if (SCHED_TRACE) backoffs++; Atomics.wait(yieldWaitWord, 0, 0, YIELD_SLEEP_MS); } } } function dispatchSyscall2(nr, call) { census.brackets++; laneLockAcquire(`wasm_syscall:${nr | 0}`); try { return dispatchSyscallLocked(nr, call); } finally { laneLockRelease(); } } function dispatchSyscallLocked(nr, call) { const liveBefore = liveIdx >= 0 ? ku32()[liveIdx] >>> 0 : 0; const hold = SCHED_TRACE ? holdReport(post, { cpu: lane, pid, tid, site: "dispatchSyscall", label: `wasm_syscall:${nr | 0}`, announce: false, fields: (n) => `slices=${n}` }) : HOLD_REPORT_OFF; const hot = ku32(); if (hot[slotIdx] !== 0) exp.__hwjs_slice_enter(); else hot[sliceIdx] = 1; let ret; try { ret = call(); } catch (e) { if (!census.poisoned && !isDesignedUnwind(e)) census.poisoned = `wasm_syscall:${nr | 0}`; exp.__hwjs_slice_exit(); throw e; } const parked = ku32()[slotIdx] >>> 0; let drivenSlices = 0; if (parked !== 0) { const owner = ku32()[ownerIdx] >>> 0; const h = exp.__hwjs_take_parked(0, 0) >>> 0; const label = `wasm_syscall:${nr | 0}`; const { value, slices } = driveToDone(label, h, owner, hold); drivenSlices = slices; post({ kind: "hwjs-lane-drive", pid, lane, label, handle: h, owner, slices }); ret = value; } ku32()[sliceIdx] = 0; bracketCensus(liveBefore); if (SCHED_TRACE) hold.end(drivenSlices); return ret; } function reconcile() { const liveAtExit = liveIdx >= 0 ? ku32()[liveIdx] >>> 0 : 0; const framesAtExit = hasTaskFrames ? exp.__hwjs_task_frames() >>> 0 : 0; const residue = hasTaskFrames ? framesAtExit - framesAtCreate | 0 : liveAtExit - liveAtCreate | 0 || census.frameResidue; const snapshot = { ...census, liveAtCreate, liveAtExit, residue, framesAtCreate, framesAtExit, perTask: hasTaskFrames }; if (residue !== 0 && !census.poisoned) { if (pid === 1) { post({ kind: "dmesg", level: 6, text: `hwjs-lane[${lane}] pid 1 reconcile: boot-continuation residue ${residue} frames ` + (hasTaskFrames ? `(per-task frames ${framesAtCreate} -> ${framesAtExit}) ` : `(lane-sum live ${liveAtCreate} -> ${liveAtExit}) `) + `\u2014 EXPECTED (reused kernel_init's by-design parked boot frames, baselined as 0 before its final schedule() attributed them); non-fatal (HWJS-A-4.c residual-2 carve-out, pid 1 only)` }); return { ...snapshot, explained: "pid1-boot-continuation" }; } post({ kind: "error", pid, lane, message: `hwjs-lane[${lane}] FATAL (quiesce reconciliation): end-of-process residue ${residue} frames ` + (hasTaskFrames ? `(per-task frames ${framesAtCreate} -> ${framesAtExit}) ` : `(lane-sum live ${liveAtCreate} -> ${liveAtExit}) `) + `with NO witnessed bracket trap \u2014 an unexplained leak the F87c3 deferral does not cover (amended form, manager 2026-06-11)` }); throw new Error( `hwjs-lane[${lane}] unexplained end-of-process frame residue ${residue} (reconciliation fatal)` ); } return snapshot; } return { lane, bracket, bracketYielding, driveWouldBlock, dispatchSyscall: dispatchSyscall2, census, reconcile }; } function thrTrace(init, post, phase) { if (!THR_TRACE) return; try { post({ kind: "dmesg", level: 6, text: `[thr-trace tid=${init?.tid ?? "?"} mode=${init?.mode ?? "?"} rt=${init?.rtThread ? 1 : 0} cpu=${init?.cpuId ?? "?"}] ${phase} t=${Date.now()} ` }); } catch (_e) { } } function workerKernelsOf(init) { const k = init.kernelMemoryWasm && typeof init.kernelMemoryWasm === "object" ? init.kernelMemoryWasm : workerKernelsNoMemory; let lanes = workerKernels.get(k); if (!lanes) { lanes = /* @__PURE__ */ new Map(); workerKernels.set(k, lanes); } return lanes; } function kernelEnter(cpu, t) { const prev = cpu.entered; if (prev !== t) { cpu.entered = t; if (cpu.door !== null) cpu.door.bind(t.uaccessCopies); } cpu.depth++; if (cpu.bound !== t.cur) { cpu.setCurrent(t.cur | 0); cpu.bound = t.cur; } return prev; } function kernelLeave(cpu, t, prev) { if (--cpu.depth > 0 && prev !== t && prev !== null) { cpu.entered = prev; if (cpu.door !== null) cpu.door.bind(prev.uaccessCopies); if (cpu.bound !== prev.cur) { cpu.setCurrent(prev.cur | 0); cpu.bound = prev.cur; } } } function kernelExportWrapper(cpu, t, f) { switch (f.length) { case 0: return function() { const p = kernelEnter(cpu, t); try { return f(); } finally { kernelLeave(cpu, t, p); } }; case 1: return function(a) { const p = kernelEnter(cpu, t); try { return f(a); } finally { kernelLeave(cpu, t, p); } }; case 2: return function(a, b) { const p = kernelEnter(cpu, t); try { return f(a, b); } finally { kernelLeave(cpu, t, p); } }; case 3: return function(a, b, c) { const p = kernelEnter(cpu, t); try { return f(a, b, c); } finally { kernelLeave(cpu, t, p); } }; case 4: return function(a, b, c, d) { const p = kernelEnter(cpu, t); try { return f(a, b, c, d); } finally { kernelLeave(cpu, t, p); } }; case 5: return function(a, b, c, d, e) { const p = kernelEnter(cpu, t); try { return f(a, b, c, d, e); } finally { kernelLeave(cpu, t, p); } }; case 6: return function(a, b, c, d, e, g) { const p = kernelEnter(cpu, t); try { return f(a, b, c, d, e, g); } finally { kernelLeave(cpu, t, p); } }; case 7: return function(a, b, c, d, e, g, h) { const p = kernelEnter(cpu, t); try { return f(a, b, c, d, e, g, h); } finally { kernelLeave(cpu, t, p); } }; default: return function(...args) { const p = kernelEnter(cpu, t); try { return f(...args); } finally { kernelLeave(cpu, t, p); } }; } } function makeTaskKernelView(cpu, t) { const real = cpu.instance.exports; const exports = {}; for (const name2 of Object.keys(real)) { const v = real[name2]; if (typeof v !== "function") { exports[name2] = v; continue; } if (name2 === "__wasm32_set_current") { exports[name2] = (task) => { t.cur = (task | 0) >>> 0; if (cpu.entered !== t) { cpu.entered = t; if (cpu.door !== null) cpu.door.bind(t.uaccessCopies); } cpu.setCurrent(task | 0); cpu.bound = t.cur; }; continue; } exports[name2] = kernelExportWrapper(cpu, t, v); } return { exports, cpu, task: t }; } async function instantiateWorkerKernel(key, init, post, first) { const cpu = { key, module: init.vmlinuxModule, memory: init.kernelMemoryWasm, instance: null, setCurrent: null, entered: first, bound: -1, depth: 0, syscallTable: void 0, tasks: 0, /* The first task decides: a Worker's knobs and engine are every task's. */ door: first.uaccessCopies ? makeUaccessDoor() : null }; if (cpu.door !== null) cpu.door.bind(first.uaccessCopies); const imports = {}; const kernelImportNames = []; const bindKernelImportFns = (t) => t.importFns = kernelImportNames.map(([m, n]) => t.imports[m][n]); for (const imp of moduleImportsOf(init.vmlinuxModule)) { const ns = imports[imp.module] ??= {}; if (imp.kind !== "function") { ns[imp.name] = first.imports[imp.module][imp.name]; continue; } if (cpu.door !== null && Object.hasOwn(cpu.door.imports, imp.name)) { ns[imp.name] = cpu.door.imports[imp.name]; continue; } const m = imp.module, n = imp.name, i = kernelImportNames.length; kernelImportNames.push([m, n]); ns[n] = (a, b, c, d, e, f) => { const t = cpu.entered; return (t.importFns ?? bindKernelImportFns(t))[i](a, b, c, d, e, f); }; } void KERNEL_IMPORT_ARGS_MAX; let inst; try { thrTrace(init, post, "vmlinux-instantiate-begin"); inst = await WebAssembly.instantiate(init.vmlinuxModule, imports); heapChargeInstance(inst, init.vmlinuxModule); thrTrace(init, post, "vmlinux-instantiate-end"); processVmlinuxInstanceCount += 1; } catch (e) { post({ kind: "vmlinux-error", pid: init.pid, message: "K11-B2a: vmlinux WebAssembly.instantiate trapped: " + (e instanceof Error ? e.message : String(e)) }); return null; } const exp = inst.exports; if (typeof exp.__wasm32_set_current !== "function") { post({ kind: "vmlinux-error", pid: init.pid, message: "shared kernel instance: this vmlinux exports no __wasm32_set_current, so one instance cannot serve more than one task (never-silent)" }); return null; } cpu.instance = inst; cpu.setCurrent = exp.__wasm32_set_current; if (typeof exp.__wasm32_set_coop_sched === "function") exp.__wasm32_set_coop_sched(0); 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) { post({ kind: "vmlinux-error", pid: init.pid, message: "K11-B2a: vmlinux __wasm_call_ctors trapped (likely a second-instance __wasm_init_memory or active-overlay invariant violation): " + (e instanceof Error ? e.message : String(e)) }); return null; } } if (typeof init.cpuId === "number" && typeof exp.__wasm32_set_cpu_id === "function") { try { exp.__wasm32_set_cpu_id(init.cpuId | 0); } catch (e) { post({ kind: "vmlinux-error", pid: init.pid, message: "K11-B2b: vmlinux __wasm32_set_cpu_id trapped: " + (e instanceof Error ? e.message : String(e)) }); return null; } } if (typeof init.cpuId === "number" && (init.cpuId | 0) >= 1 && typeof exp.__wasm32_lane_stack_init === "function") { try { const top = exp.__wasm32_lane_stack_init() >>> 0; if (top === 0) { post({ kind: "dmesg", level: 4, text: `hwjs #61 RED arm (wasm_shared_lane_stack): lane ${init.cpuId | 0} keeps the SHARED module shadow stack \u2014 cross-Worker stack corruption is reproducible by design` }); } } catch (e) { post({ kind: "vmlinux-error", pid: init.pid, message: "#61: vmlinux __wasm32_lane_stack_init trapped: " + (e instanceof Error ? e.message : String(e)) }); return null; } } else if (typeof init.cpuId === "number" && (init.cpuId | 0) >= 1) { post({ kind: "dmesg", level: 4, text: `hwjs #61: vmlinux lacks __wasm32_lane_stack_init (older build) \u2014 lane ${init.cpuId | 0} runs direct kernel calls on the SHARED module shadow stack (cross-Worker corruption window open)` }); } post({ kind: "dmesg", level: 6, text: `hwjs-kernel cpu=${init.cpuId ?? "?"}: one vmlinux instance serves every task resident on this Worker (instances in this realm: ${processVmlinuxInstanceCount})` }); return cpu; } async function acquireWorkerKernel(init, post, task) { const key = typeof init.cpuId === "number" ? init.cpuId | 0 : -1; const lanes = workerKernelsOf(init); let pending2 = lanes.get(key); if (!pending2) { if (!init.allowMultiInstance && processVmlinuxInstanceCount !== 0) { post({ kind: "vmlinux-error", pid: init.pid, message: `K11-B2a per-Worker vmlinux invariant violated: vmlinux.wasm has already been instantiated ${processVmlinuxInstanceCount} time(s) in this Worker. Each Worker (kernel or process) must instantiate vmlinux exactly once; re-instantiation re-runs the K10-A3 active- overlay against shared kernel memory and corrupts the running kernel's initcall arrays. See docs/ARCHITECTURE.md \xA715.3 R-K10-W1.` }); return null; } pending2 = instantiateWorkerKernel(key, init, post, task); lanes.set(key, pending2); pending2.then((c) => { if (!c && lanes.get(key) === pending2) lanes.delete(key); }); } const cpu = await pending2; if (!cpu) return null; if (cpu.door !== null && !task.uaccessCopies) { post({ kind: "vmlinux-error", pid: init.pid, message: `shared kernel instance: lane ${key}'s instance copies to user memory through the wasm door and this task's memory has no copies, so its uaccess would reach another task's pages (never-silent)` }); return null; } if (cpu.module !== init.vmlinuxModule || cpu.memory !== init.kernelMemoryWasm) { post({ kind: "vmlinux-error", pid: init.pid, message: `shared kernel instance: lane ${key}'s instance was made from a different vmlinux Module or kernel memory than this task carries \u2014 refusing to run a task against a kernel it was not spawned for (never-silent)` }); return null; } cpu.tasks++; return cpu; } function threadImageShape(imgKey, init) { const rec = init.dlopenFork; if (!rec || typeof rec !== "object") return String(imgKey); const shape = JSON.stringify(rec, (k, v) => THREAD_SHAPE_PER_THREAD_FIELDS.has(k) ? void 0 : typeof v === "bigint" ? `${v}n` : v instanceof ArrayBuffer || ArrayBuffer.isView(v) ? `#${v.byteLength}` : v); return `${imgKey}|${shape}`; } function threadCtxForImage(memoryId, imgKey, init, create) { const shape = threadImageShape(imgKey, init); const key = `${fnv1aHex(shape)}:${shape.length}`; const ctx = threadCtxFor(memoryId, key, false); if (ctx && ctx.shape === shape) return ctx; if (!create) return threadCtxCovering(memoryId, imgKey, init); if (ctx) threadCtxDrop(memoryId, ctx); const made = threadCtxFor(memoryId, key, true); made.shape = shape; made.imgKey = String(imgKey); return made; } function threadCtxCovering(memoryId, imgKey, init) { const rec = init.dlopenFork; const byKey = threadImageContexts.get(memoryId); if (!byKey || !rec || typeof rec !== "object") return null; for (const ctx of byKey.values()) { if (!ctx.ready || ctx.failed || ctx.imgKey !== String(imgKey)) continue; const base = ctx.placementRecord; if (base && typeof base === "object" && (base.placementGen | 0) <= (rec.placementGen | 0)) return ctx; } return null; } function fnv1aHex(str) { let h = 2166136261; for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 16777619); } return (h >>> 0).toString(16).padStart(8, "0"); } function threadCtxFor(memory, key, create) { let byKey = threadImageContexts.get(memory); if (!byKey) { if (!create) return null; byKey = /* @__PURE__ */ new Map(); threadImageContexts.set(memory, byKey); } let ctx = byKey.get(key); if (!ctx && create) { let resolveReady; const readyPromise = new Promise((r) => { resolveReady = r; }); ctx = { key, ready: false, failed: false, readyPromise, resolveReady, table: null, handles: /* @__PURE__ */ new Map(), mainInstance: null, userExports: null, gotFuncIndex: null, mainScopeIndex: null, spGlobal: null, budgetGlobal: null, chanGlobal: new WebAssembly.Global({ value: "i32", mutable: true }, 0), tlsGlobals: [], members: /* @__PURE__ */ new Set(), entered: null, depth: 0, regs: null, syscallDispatch: null }; ctx.syscallDispatch = (nr, a0, a1, a2, a3, a4, a5) => { const t = ctx.entered; if (ctx.depth === 0 || !t) { throw new Error( `hwjs-thread-image: syscall ${nr} arrived with no thread entered on a shared process image (depth=${ctx.depth}, entered=${t ? t.tid : "none"}) \u2014 an outermost wasm entry bypassed the thread view, so it ran on whichever thread was entered last. Refusing rather than attribute the call to the wrong task (never-silent; HWJS_THREAD_IMAGE_PRIVATE=1 is the private-graph arm).` ); } return t.syscall(nr, a0, a1, a2, a3, a4, a5); }; byKey.set(key, ctx); } return ctx || null; } function threadCtxDrop(memory, ctx) { const byKey = threadImageContexts.get(memory); if (byKey && byKey.get(ctx.key) === ctx) byKey.delete(ctx.key); } function threadCtxLeave(memoryId, ctx, rec, abnormal) { ctx.members.delete(rec); if (ctx.entered === rec) ctx.entered = null; if (!ctx.ready && !ctx.failed) { ctx.failed = true; ctx.resolveReady(); } if (ctx.failed || (abnormal || ctx.dropWhenIdle) && ctx.members.size === 0) { threadCtxDrop(memoryId, ctx); } } function threadImagesDropIdle(memoryId) { const byKey = threadImageContexts.get(memoryId); if (!byKey) return 0; let n = 0; for (const ctx of [...byKey.values()]) { if (ctx.ready && ctx.members.size === 0) { byKey.delete(ctx.key); n++; } else { ctx.dropWhenIdle = true; } } if (byKey.size === 0) threadImageContexts.delete(memoryId); return n; } function threadImagesRelease(memoryId, beforeEpoch) { const byKey = threadImageContexts.get(memoryId); if (!byKey) return 0; let n = 0; for (const ctx of [...byKey.values()]) { if (beforeEpoch !== void 0 && (ctx.imageEpoch | 0) >= (beforeEpoch | 0)) continue; byKey.delete(ctx.key); n++; } if (byKey.size === 0) threadImageContexts.delete(memoryId); return n; } function threadCtxEnter(ctx, t) { if (ctx.entered === t) return; if (ctx.regs) { if (ctx.entered) ctx.entered.saved = ctx.regs.read(); if (t.saved) ctx.regs.write(t.saved); else ctx.regs.unbind(t.stackTop); } ctx.entered = t; } function threadCtxCall(ctx, t, fn2) { if (ctx.depth === 0) threadCtxEnter(ctx, t); ctx.depth++; try { return fn2(); } finally { ctx.depth--; } } function threadViewWrap(ctx, t, f) { const w = (...args) => { if (ctx.depth === 0) threadCtxEnter(ctx, t); ctx.depth++; try { return f(...args); } finally { ctx.depth--; } }; threadViewRaw.set(w, f); return w; } function makeThreadExportView(ctx, t, raw) { const wrapped = /* @__PURE__ */ new Map(); const get2 = (k) => { const v = raw[k]; if (typeof v !== "function") return v; let w = wrapped.get(v); if (!w) { w = threadViewWrap(ctx, t, v); wrapped.set(v, w); } return w; }; return new Proxy(/* @__PURE__ */ Object.create(null), { get: (_t, k) => get2(k), has: (_t, k) => k in raw, ownKeys: () => Reflect.ownKeys(raw), getOwnPropertyDescriptor: (_t, k) => k in raw ? { value: get2(k), writable: false, enumerable: true, configurable: true } : void 0 }); } function unwrapThreadExport(f) { return typeof f === "function" && threadViewRaw.get(f) || f; } function threadCtxNoteTls(ctx, handle) { if (!ctx || !handle || !handle.tls) return; const g = handle.exports && handle.exports.__tls_base; if (g instanceof WebAssembly.Global && !ctx.tlsGlobals.includes(g)) ctx.tlsGlobals.push(g); } function makeThreadRegs({ spGlobal, mainExports, rtExports, tlsGlobals, chanGlobal, budgetExports, budgetGlobals }) { const tcbOps = rtExports && typeof rtExports.__hwjs_tcb_self === "function" ? rtExports : mainExports && typeof mainExports.__hwjs_tcb_self === "function" ? mainExports : null; const spGet = spGlobal ? () => spGlobal.value | 0 : typeof mainExports.__wasm32_get_stack_pointer === "function" ? () => mainExports.__wasm32_get_stack_pointer() | 0 : null; const spSet = spGlobal ? (v) => { spGlobal.value = v | 0; } : typeof mainExports.__wasm32_set_stack_pointer === "function" ? (v) => { mainExports.__wasm32_set_stack_pointer(v | 0); } : null; const tlsGet = typeof mainExports.__wasm32_get_tls_base === "function" ? () => mainExports.__wasm32_get_tls_base() | 0 : null; const switchThreadTls = (mainTls, sideTls) => { if (tlsGet) mainExports.__wasm32_set_tls_base(mainTls | 0); for (let i = 0; i < tlsGlobals.length; i++) tlsGlobals[i].value = sideTls[i] | 0; }; if (!spGet || !spSet || !tcbOps) { throw new Error( "hwjs-thread-image: this image does not expose the register file a shared image needs (stack pointer get/set and the runtime block ops) \u2014 refusing to share it (never-silent)" ); } const budgetHasGet = !!budgetExports && typeof budgetExports.__hwjs_budget_get === "function"; const budgetHasSet = !!budgetExports && typeof budgetExports.__hwjs_budget_set === "function"; if (budgetHasGet !== budgetHasSet) { throw new Error( `hwjs-thread-image: this image exports __hwjs_budget_${budgetHasGet ? "get" : "set"} without __hwjs_budget_${budgetHasGet ? "set" : "get"} \u2014 its safepoint budget cannot be kept per thread, so co-resident threads would share one counter and resume each other's budget parks on it \u2014 refusing to share it (never-silent)` ); } const sideBudgets = Array.from(budgetGlobals || []); return { read() { return [ spGet(), tlsGet ? tlsGet() : 0, tcbOps.__hwjs_tcb_self() | 0, chanGlobal.value | 0, tlsGlobals.map((g) => g.value | 0), budgetHasGet ? budgetExports.__hwjs_budget_get() | 0 : 0, sideBudgets.map((g) => g.value | 0) ]; }, /* The budget is left as it is: a thread being set up binds its own * initial budget (the F86 bind before ctors) before it drives, and the * value it finds was already saved with the thread that left it. */ unbind(stackTop) { tcbOps.__hwjs_tcb_bind(0); if (stackTop) spSet(stackTop); switchThreadTls(0, []); chanGlobal.value = 0; }, write(r) { spSet(r[0]); switchThreadTls(r[1], r[4]); tcbOps.__hwjs_tcb_bind(r[2] >>> 0); chanGlobal.value = r[3] | 0; if (budgetHasSet) budgetExports.__hwjs_budget_set(r[5] | 0); for (let i = 0; i < sideBudgets.length; i++) { try { sideBudgets[i].value = r[6][i] | 0; } catch (_e) { } } } }; } async function instantiateProcessWorkerVmlinux(init, post) { if (!init.kernelMemoryWasm) { post({ kind: "vmlinux-error", pid: init.pid, message: "K11-B2a: cannot instantiate per-Worker vmlinux without a WebAssembly.Memory backing env.kernel_memory; spawn handler must pass kernelMemoryWasm in the init message (see KernelSpawnHandlerOptions.kernelMemoryWasm)." }); return null; } const td3 = new TextDecoder("utf-8", { fatal: false }); function dmesg(level, buf, len) { const view = new Uint8Array(init.kernelMemoryWasm.buffer, buf, len); const bytes = new Uint8Array(len); bytes.set(view); const text = td3.decode(bytes); dmesgDeliver(post, init.routeKey, init.pid, level, text); } const LANE_DRAIN_EVERY = 255; const LANE_SPIN_FATAL_MS = 1e4; const LANE_SPIN_FATAL_CALLS = 1e6; const LANE_SPIN_SAMPLE_MASK = 65535; const laneMerged = init.mergedCpu0Lane === true; let laneRelaxTick = 0; let laneSpinCalls = 0; let laneSpinT0 = 0; let laneSpinLast = 0; const LANE_SPIN_GAP_MS = 2e3; function cpu_relax_host() { if (!laneMerged) return; if (workerHostSyncCall !== null && (++laneRelaxTick & LANE_DRAIN_EVERY) === 0) { workerHostSyncCall(LANE_DRAIN_MSG); } if ((++laneSpinCalls & LANE_SPIN_SAMPLE_MASK) !== 0) return; const t = Date.now(); if (laneSpinT0 === 0) { laneSpinT0 = laneSpinLast = t; return; } const gap = t - laneSpinLast; if (gap > LANE_SPIN_GAP_MS) laneSpinT0 += gap; laneSpinLast = t; const heldMs = t - laneSpinT0; if (heldMs < LANE_SPIN_FATAL_MS) return; if (laneSpinCalls < LANE_SPIN_FATAL_CALLS) return; const calls = laneSpinCalls; laneSpinCalls = 0; laneSpinT0 = 0; throw new Error( `hwjs-merged LANE DEADLOCK: pool lane ${init.cpuId | 0} (tid=${init.tid | 0}) has held the merged JS thread for ${heldMs} ms across ${calls} linux.cpu_relax_host calls without progress. The guest is in an in-kernel BUSY-WAIT \u2014 on this arch cpu_relax() IS this host call (asm/barrier.h) and it is not a suspend point \u2014 and the host backend it is waiting on is on THIS thread. ${workerHostSyncCall === null ? "No synchronous doorbell is installed on this realm, so nothing was drained at all." : "The synchronous doorbell was drained every " + (LANE_DRAIN_EVERY + 1) + " calls and did not satisfy it, so the backend it needs is one that AWAITS (virtio-fs, virtio-net) or is not registered in this realm."} A synchronous import can neither turn the event loop nor resolve a promise, so this cannot be closed from here: the guest wait has to become a cooperative park.` ); } const LANE_DRAIN_MSG = Object.freeze({ kind: "virtio-drain-sync" }); function now_ns() { if (HOST_TIME_ORIGIN !== null) { return BigInt(Math.round((HOST_TIME_ORIGIN + HOST_PERF.now()) * 1e6)); } return BigInt(Date.now()) * 1000000n; } let kernI32Buf = init.kernelMemoryWasm.buffer; let kernI32View = new Int32Array(kernI32Buf); const kernPagesOf = uaccessCopiesFor(init.memory, init.kernelMemoryWasm)?.kernel_pages ?? null; let kernI32Pages = kernPagesOf !== null ? kernPagesOf() : -1; const kernI32 = () => { if (kernPagesOf !== null) { const pages2 = kernPagesOf(); if (pages2 === kernI32Pages) return kernI32View; kernI32Pages = pages2; } const b = init.kernelMemoryWasm.buffer; if (b !== kernI32Buf) { kernI32Buf = b; kernI32View = new Int32Array(b); } return kernI32View; }; const T67W = !!globalThis.process?.env?.HWJS_67_TRACE; const STALL_TRACE_W = !!globalThis.process?.env?.HWJS_STALL_TRACE; const STALL_TRACE_MS = (() => { const raw = parseInt(globalThis.process?.env?.HWJS_STALL_TRACE ?? "", 10); return Number.isFinite(raw) && raw >= 100 ? raw : 15e3; })(); const STALL_STACK_W = !!globalThis.process?.env?.HWJS_STALL_STACK; if (STALL_STACK_W) Error.stackTraceLimit = 200; let stallWaitCount = 0, stallWaitLastEmit = 0; let mergedUnboundedWaitRefusals = 0; function atomic_wait_i32(addr, expected, timeoutNs) { const idx = (addr | 0) >>> 2; if (typeof timeoutNs === "bigint" && timeoutNs >= 0n) { const ms = Number(timeoutNs / 1000000n); if (STALL_TRACE_W) { stallWaitCount++; const now = Date.now(); if (now - stallWaitLastEmit > STALL_TRACE_MS) { stallWaitLastEmit = now; let where = ""; if (STALL_STACK_W) { try { where = " at " + String(new Error().stack ?? "").split("\n").slice(1, 40).map((l) => l.trim()).filter((l) => !/\.hwjs_resume \(/.test(l)).join(" <- "); } catch (_e) { } } dmesgDeliver( post, init.routeKey, init.pid, 5, `STALL-TRACE pid=${init.pid ?? "?"} tid=${init.tid | 0} rt=${init.rtThread ? 1 : 0} kern-wait addr=0x${(addr >>> 0).toString(16)} expected=${expected | 0} cur=${Atomics.load(kernI32(), idx) | 0} timeoutMs=${ms} waits=${stallWaitCount}${where}` ); } } const r2 = Atomics.wait(kernI32(), idx, expected | 0, ms); return r2 === "ok" ? 0 : r2 === "not-equal" ? 1 : 2; } if (T67W) { try { post({ kind: "dmesg", level: 6, text: `t67 tid=${init.tid | 0} KERN-ATOMIC-WAIT-INF addr=0x${(addr >>> 0).toString(16)} expected=${expected | 0} cur=${Atomics.load(kernI32(), idx) | 0}` }); } catch (_e) { } } if (init.mergedCpu0Lane === true) { mergedUnboundedWaitRefusals++; if ((mergedUnboundedWaitRefusals & mergedUnboundedWaitRefusals - 1) === 0) { dmesgDeliver( post, init.routeKey, init.pid, 3, `hwjs-merged REFUSED an UNBOUNDED in-kernel wait on the merged CPU-0 lane: pid=${init.pid ?? "?"} tid=${init.tid | 0} addr=0x${(addr >>> 0).toString(16)} expected=${expected | 0}. This lane shares its JS thread with CPU 0 (and, inline, with the device backends that would deliver the wake), so blocking here stops the machine, not just this task. Answering 'timed out' instead \u2014 the caller re-checks and returns. Occurrence ${mergedUnboundedWaitRefusals}. A merged machine runs only images whose libc absorbs the -517 park; if this fires, that assumption is false for this image. There is no other topology to move it to \u2014 every machine is merged \u2014 so what has to change is the image's libc, or the kernel path that reached an unbounded wait from a call graph the libc's nomination list does not cover.` ); } return 2; } const r = Atomics.wait(kernI32(), idx, expected | 0); if (T67W) { try { post({ kind: "dmesg", level: 6, text: `t67 tid=${init.tid | 0} KERN-ATOMIC-WAIT-INF WOKE addr=0x${(addr >>> 0).toString(16)} r=${r}` }); } catch (_e) { } } return r === "ok" ? 0 : r === "not-equal" ? 1 : 2; } function atomic_notify(addr, count) { return Atomics.notify(kernI32(), (addr | 0) >>> 2, count | 0); } const stubHost = (name2) => (..._args) => { post({ kind: "unimplemented-host-call", name: name2, pid: init.pid }); return 0; }; const uaccessRefuse = (msg) => { post({ kind: "vmlinux-error", pid: init.pid, message: msg }); throw new Error(msg); }; const uaccessBoundary = makeUaccessLeafBoundary({ userMemory: init.memory, kernelMemory: init.kernelMemoryWasm, refuse: uaccessRefuse, context: `pid=${init.pid} process Worker`, redPark: !!globalThis.process?.env?.HWJS_RED_UACCESS_PARK }); let committedPagesIdx = -1; const mem_commit = (wantPages) => { const mem = init.kernelMemoryWasm; const want = (wantPages >>> 0) * 4096; const have = mem.buffer.byteLength; if (want > have) { try { mem.grow(Math.ceil((want - have) / 65536)); } catch { } const now = mem.buffer.byteLength; if (now !== have && committedPagesIdx >= 0) { Atomics.store( new Int32Array(mem.buffer), committedPagesIdx, now / 4096 | 0 ); } } return mem.buffer.byteLength / 4096 >>> 0; }; const linuxImports = { 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's reboot(2) asking to end the machine, * with the reboot command (RESTART, HALT, POWER_OFF) as the code. */ terminate_worker: (pid, code2) => { if ((pid | 0) === 0) { post({ kind: "machine-power", cmd: code2 >>> 0, pid: init.pid }); return 0; } return stubHost("terminate_worker")(); }, signal_inject: stubHost("signal_inject"), virtio_kick: stubHost("virtio_kick") }; const envImports = { kernel_memory: init.kernelMemoryWasm }; const imports = { env: envImports, linux: linuxImports, hwjs_suspend: { park: uaccessBoundary.guardPark(() => { }) } }; const boundaryProblems = auditVmlinuxSingleMemory(init.vmlinuxModule); if (boundaryProblems.length > 0) { post({ kind: "vmlinux-error", pid: init.pid, message: "uaccess-leaf-witness: refusing to instantiate vmlinux in the process Worker:\n - " + boundaryProblems.join("\n - ") }); return null; } const needed = moduleImportsOf(init.vmlinuxModule); 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: "vmlinux-error", pid: init.pid, message: "K11-B2a: vmlinux import-resolution failure in process Worker; missing: " + missing.join(", ") }); return null; } const taskKernel = { imports, cur: 0, /* The park witness has to see a JavaScript crossing to prove anything. */ uaccessCopies: globalThis.process?.env?.HWJS_RED_UACCESS_PARK ? null : uaccessCopiesFor(init.memory, init.kernelMemoryWasm) }; const kernelCpu = await acquireWorkerKernel(init, post, taskKernel); if (!kernelCpu) return null; const vmlinuxInstance = makeTaskKernelView(kernelCpu, taskKernel); { const cp = vmlinuxInstance.exports.wasm32_committed_pages; if (cp && typeof cp.value === "number") committedPagesIdx = cp.value >>> 0 >> 2; } { const g = vmlinuxInstance.exports.__hwjs_lane_hot; const base = g instanceof WebAssembly.Global ? g.value >>> 0 : 0; const strideG = vmlinuxInstance.exports.__hwjs_lane_stride; if (base && strideG instanceof WebAssembly.Global) { const laneOff = (init.cpuId | 0) * new Uint32Array(init.kernelMemoryWasm.buffer)[strideG.value >>> 0 >> 2]; const idx = base + laneOff >> 2; const parkedView = new Uint32Array(init.kernelMemoryWasm.buffer); uaccessBoundary.setParkedSlotReader(() => parkedView[idx] >>> 0); } } const hwjsLane = makeHwjsKernelLane( vmlinuxInstance, typeof init.cpuId === "number" ? init.cpuId | 0 : 0, init.kernelMemoryWasm, post, init.pid, init.kernelLaneLocks, init.tid, init.mergedCpu0Lane === true ); let initTaskAddr = 0; let perProcessTaskAddr = 0; let kernelPid = init.pid | 0; if (typeof vmlinuxInstance.exports.__wasm32_get_init_task_addr === "function" && typeof vmlinuxInstance.exports.__wasm32_set_current === "function") { try { initTaskAddr = (vmlinuxInstance.exports.__wasm32_get_init_task_addr() | 0) >>> 0; vmlinuxInstance.exports.__wasm32_set_current(initTaskAddr | 0); } catch (e) { post({ kind: "vmlinux-error", pid: init.pid, message: "K11-B5: vmlinux __wasm32_set_current(&init_task) trapped: " + (e instanceof Error ? e.message : String(e)) }); return null; } if (init.mode === "migrate-resume" || init.bindTaskAddr !== void 0) { const bindAddr = ((init.migrateTaskAddr ?? init.bindTaskAddr) | 0) >>> 0; if (bindAddr === 0) { post({ kind: "vmlinux-error", pid: init.pid, message: "migrate-resume without a migrateTaskAddr \u2014 a migration binds an EXISTING task and there is nothing to bind (never-silent; the source still holds the task and will resume it)" }); return null; } let boundPid = 0; try { vmlinuxInstance.exports.__wasm32_set_current(bindAddr | 0); if (typeof vmlinuxInstance.exports.__wasm32_task_pid === "function") boundPid = vmlinuxInstance.exports.__wasm32_task_pid(bindAddr | 0) | 0; } catch (e) { post({ kind: "vmlinux-error", pid: init.pid, message: "migrate-resume bind of task 0x" + bindAddr.toString(16) + " trapped: " + (e instanceof Error ? e.message : String(e)) }); return null; } const wantPid = (init.migratePid ?? init.bindTaskPid) | 0; if (wantPid > 0 && boundPid !== wantPid) { post({ kind: "vmlinux-error", pid: init.pid, message: `migrate-resume bind REFUSED: task address 0x${bindAddr.toString(16)} reports pid ${boundPid}, the source said ${wantPid}. Refusing to drive a task that is not the one being migrated (never-silent).` }); return null; } perProcessTaskAddr = bindAddr; if (boundPid > 0) kernelPid = boundPid; } else if (typeof vmlinuxInstance.exports.__wasm32_alloc_process_task === "function") { try { const ppid = (init.ppid | 0) >>> 0; const inheritFiles = init.inheritFiles === 2 ? 2 : init.inheritFiles ? 1 : 0; const cloneTid = init.mode === "thread" && !init.vforkChild ? init.tid | 0 : 0; const rawAllocCall = () => vmlinuxInstance.exports.__wasm32_alloc_process_task( init.pid | 0, ppid | 0, inheritFiles | 0, cloneTid | 0 ) | 0; thrTrace(init, post, "alloc-process-task-begin"); const allocAddr = ((hwjsLane ? hwjsLane.bracket("__wasm32_alloc_process_task", rawAllocCall) : rawAllocCall()) | 0) >>> 0; thrTrace(init, post, `alloc-process-task-end addr=${allocAddr}`); if (allocAddr === 0) { post({ kind: "vmlinux-error", pid: init.pid, message: "linux#7: vmlinux __wasm32_alloc_process_task(" + (init.pid | 0) + ", " + (init.ppid | 0) + ") returned 0 (alloc_pid failure) \u2014 spawn refused (hwjs#65: parent gets -EAGAIN, the machine keeps running)" }); return null; } { vmlinuxInstance.exports.__wasm32_set_current(allocAddr | 0); perProcessTaskAddr = allocAddr; if (typeof vmlinuxInstance.exports.__wasm32_task_pid === "function") { const kp = vmlinuxInstance.exports.__wasm32_task_pid(allocAddr | 0) | 0; if (kp > 0) kernelPid = kp; } if (init.mode === "thread" && !init.vforkChild && typeof vmlinuxInstance.exports.__wasm32_task_set_thread_worker === "function") { vmlinuxInstance.exports.__wasm32_task_set_thread_worker(allocAddr | 0); } const fdActions = Array.isArray(init.fdActions) ? init.fdActions : null; if (fdActions && typeof vmlinuxInstance.exports.wasm_syscall === "function") { const SYS_DUP2 = 33; const SYS_CLOSE = 3; for (let i = 0; i < fdActions.length; i++) { const act = fdActions[i]; const op = act[0] | 0; const f1 = act[1] | 0; const f2 = act[2] | 0; let r; if (op === 0) { const call = () => vmlinuxInstance.exports.wasm_syscall( SYS_DUP2, f1, f2, 0, 0, 0, 0 ) | 0; r = (hwjsLane ? hwjsLane.dispatchSyscall(SYS_DUP2, call) : call()) | 0; } else if (op === 1) { const call = () => vmlinuxInstance.exports.wasm_syscall( SYS_CLOSE, f1, 0, 0, 0, 0, 0 ) | 0; r = (hwjsLane ? hwjsLane.dispatchSyscall(SYS_CLOSE, call) : call()) | 0; } else { r = -22; } if (r < 0) { post({ kind: "vmlinux-error", pid: init.pid, message: "K13-A: spawn fd-action " + i + " (op=" + op + ", fd1=" + f1 + ", fd2=" + f2 + ") failed rc=" + r }); return null; } } } } } catch (e) { try { if (typeof vmlinuxInstance.exports.__hwjs_lane_contain === "function") { const dirty = vmlinuxInstance.exports.__hwjs_lane_contain() | 0; if (dirty !== 0) { post({ kind: "dmesg", level: 3, text: `hwjs #85 CONTAINMENT pid=${init.pid} (alloc-task trap): kernel lane state reclaimed (dirty mask=${dirty}) \u2014 this spawn degrades -EAGAIN, the next spawn on this lane works` }); } } } catch (_e2) { } post({ kind: "vmlinux-error", pid: init.pid, message: "K11-C1.a: vmlinux __wasm32_alloc_process_task(" + (init.pid | 0) + ", " + (init.ppid | 0) + ") trapped: " + (e instanceof Error ? e.message : String(e)) + (e instanceof Error && e.stack ? "\nALLOC-TASK-STACK: " + e.stack.split("\n").slice(0, 12).join(" | ") : "") }); return null; } } } if (typeof init.signalPendingOffset === "number" && typeof vmlinuxInstance.exports.__wasm32_kernel_set_signal_region === "function") { try { vmlinuxInstance.exports.__wasm32_kernel_set_signal_region( init.signalPendingOffset >>> 0 ); } catch (_e) { } } const hasWasmSyscall = typeof vmlinuxInstance.exports.wasm_syscall === "function"; let perProcessTaskWakeAddr = 0; if (typeof vmlinuxInstance.exports.__hwjs_task_wake_addr === "function") { try { perProcessTaskWakeAddr = vmlinuxInstance.exports.__hwjs_task_wake_addr() >>> 0; } catch (_e) { } } if (init.mergedCpu0Lane === true && init.mode !== "migrate-resume" && workerHostSyncCall !== null && init.routeKey != null) { let ack; try { ack = workerHostSyncCall({ kind: "task-register-sync", routeKey: init.routeKey, pid: kernelPid }); } catch (_e) { ack = void 0; } if (ack !== "registered") { try { post({ kind: "dmesg", level: 4, text: `hwjs-merged REGISTER-SYNC DECLINED pid=${kernelPid | 0} tid=${init.tid | 0} routeKey=${init.routeKey}: the host did not register this task through the synchronous door (answer=${ack === void 0 ? "declined" : String(ack)}), so its kernel pid arrives only with the vmlinux-ready MESSAGE \u2014 which this thread cannot deliver while the guest holds it. Every host-answered syscall until then takes the deferred -517 route and depends on this libc re-issuing it.` }); } catch (_e) { } } } post({ /* * A migration REBINDS a task that is already registered; it does not * introduce one. Everything 'vmlinux-ready' triggers host-side — * registerProcessMaps under a freshly-allocated kernel pid, draining * the pre-registration syscall hold, resolving the parent's blocked * wasm_spawn_image — has already happened once for this task and must * not happen twice. So the destination announces itself with its own * kind, and the host's handler for it does exactly the bookkeeping a * move needs (which Worker replies go to, which cpu the task is on) * and nothing else. A boolean rider on 'vmlinux-ready' would have put * the "skip almost all of this" decision inside a handler whose whole * body is first-registration work. */ kind: init.mode === "migrate-resume" ? "vmlinux-rebound" : "vmlinux-ready", /* K11.6: the real kernel-assigned pid (HardwareJS keys its maps by * this, NOT by the sentinel init.pid). */ pid: kernelPid, tid: init.tid, hasWasmSyscall, initTaskAddr, perProcessTaskAddr, perProcessTaskWakeAddr, ...init.mode === "migrate-resume" ? { cpuId: init.cpuId | 0 } : {} }); return { instance: vmlinuxInstance, initTaskAddr, perProcessTaskAddr, kernelPid, hwjsLane }; } function makeExecImageLoader({ getExports, getLane, post }) { const st = { phase: "idle", pathPtr: 0, remaining: 0, chunks: 0, blocks: 0, chain: { h: 0, owner: 0 } }; let blocksLast = 0; function execLoadPhaseReset() { blocksLast = st.blocks; st.phase = "idle"; st.pathPtr = 0; st.remaining = 0; st.chunks = 0; st.blocks = 0; st.chain.h = 0; st.chain.owner = 0; } let execLoadViaSyscall = null; function load(pathPtr, yieldWouldBlock = false) { const ex = getExports(); const lane = getLane(); if (typeof ex.wasm32_user_exec_load_begin !== "function" || typeof ex.wasm32_user_exec_load_step !== "function") { const loadCall = () => ex.wasm32_user_exec_load(pathPtr >>> 0) | 0; return (lane ? lane.bracket("wasm32_user_exec_load", loadCall) : loadCall()) | 0; } if (st.phase === "idle") { if (typeof ex.wasm32_user_exec_defer_commit === "function") { ex.wasm32_user_exec_defer_commit(); } st.phase = "begin"; st.pathPtr = pathPtr >>> 0; st.remaining = Infinity; st.chunks = 0; st.blocks = 0; } else if (st.pathPtr !== pathPtr >>> 0) { throw new Error( `execLoadKernelChunked: a load for pathPtr=0x${(pathPtr >>> 0).toString(16)} entered while a load for 0x${st.pathPtr.toString(16)} is in flight (phase=${st.phase}, chunks=${st.chunks}, chain=0x${st.chain.h.toString(16)}) \u2014 refusing to abandon a live chain (never-silent)` ); } for (; ; ) { const begin = st.phase === "begin"; const nr = begin ? SYS_WASM_EXEC_LOAD_BEGIN : SYS_WASM_EXEC_LOAD_STEP; let r; try { r = execLoadIssue(nr, pathPtr) | 0; } catch (e) { execLoadPhaseReset(); throw e; } if (r === HWJS_ERESTART_RESCHED) { st.blocks++; if (yieldWouldBlock) return HWJS_ERESTART_RESCHED; continue; } if (r === HWJS_ERESTARTNOINTR) { return r | 0; } if (r < 0) { execLoadPhaseReset(); return r | 0; } if (r === 0) { execLoadPhaseReset(); return 0; } if (!(r < st.remaining)) { const was = st.remaining === Infinity ? "\u221E" : st.remaining; const chunks = st.chunks; execLoadPhaseReset(); throw new Error( `execLoadKernelChunked: ${begin ? "begin" : "step"} left ${r} bytes remaining, no fewer than the ${was} before it (${chunks} real chunks so far) \u2014 the chunked loader is not progressing; refusing to spin (never-silent)` ); } st.remaining = r; st.chunks++; st.phase = "step"; } } function execLoadIssue(nr, pathPtr) { const ex = getExports(); const lane = getLane(); const begin = nr === SYS_WASM_EXEC_LOAD_BEGIN; const hostFlags = begin ? EXEC_LOAD_HOST_FLAGS : 0; if (!lane) { return (begin ? ex.wasm32_user_exec_load_begin(pathPtr >>> 0, hostFlags) : ex.wasm32_user_exec_load_step()) | 0; } if (execLoadViaSyscall !== false && typeof ex.wasm_syscall === "function") { const r = lane.driveWouldBlock( `wasm_syscall:${nr}`, () => ex.wasm_syscall(nr, pathPtr >>> 0, hostFlags, 0, 0, 0, 0) | 0, st.chain ); if (r.wouldBlock) { execLoadViaSyscall = true; return HWJS_ERESTART_RESCHED; } if (r.value !== -38) { execLoadViaSyscall = true; return r.value | 0; } if (execLoadViaSyscall === null) { execLoadViaSyscall = false; try { post({ kind: "dmesg", level: 6, text: `hwjs-exec: this vmlinux answers no __NR_wasm_exec_load_begin/_step (${SYS_WASM_EXEC_LOAD_BEGIN}/${SYS_WASM_EXEC_LOAD_STEP}); driving the chunked load through the bare exports, which get no park preservation. Never-silent.` }); } catch (_e) { } } else { return -38; } } return lane.bracketYielding( begin ? "wasm32_user_exec_load_begin" : "wasm32_user_exec_load_step", () => (begin ? ex.wasm32_user_exec_load_begin(pathPtr >>> 0, hostFlags) : ex.wasm32_user_exec_load_step()) | 0 ) | 0; } return { load, /** Phase state, for diagnostics and for a test that has to see that a * would-block did NOT abandon the chain. Read-only by convention. */ phase: st, /** Would-blocks in the load currently in flight (0 when idle). */ blocks: () => st.blocks, /** Would-blocks in the load that most recently finished. THE witness * input: a load that returned -ENOENT with blocksLast>0 proves the * failure return survived a real would-block, not a quiet fast path. */ blocksLast: () => blocksLast }; } function makeParkYieldWithTurn(wait) { return async function parkYieldWithTurn(where) { const turn = macrotaskTurn(); await wait(where); await turn; }; } async function driveExecLoadWithYield({ load, yieldTurn, onYield }) { for (; ; ) { const rc = load() | 0; if (rc !== HWJS_ERESTART_RESCHED) return rc; if (onYield) onYield(); await yieldTurn(); } } function execStageRefusalErrno(err2) { const e = err2 !== null && typeof err2 === "object" ? err2.errno : void 0; return Number.isInteger(e) && e < 0 && e > -512 ? e : -14; } function populateFileMapping({ len, from = 0, read, wait = null, restartCap = Infinity, held = null }) { let done = from, streak = 0, restarts = 0; const out = (err2, parked, lost) => ({ done, err: err2, parked, lost, restarts }); while (done < len) { const r = read(done) | 0; if (held !== null && held()) return out(-4, false, true); if (isRestartValue(r)) { restarts++; if (!wait) return out(0, true, false); if (++streak > restartCap) return out(-4, false, true); wait(); continue; } if (r === 0) break; if (r < 0) return out(r, false, false); done += r; streak = 0; } return out(0, false, false); } function makeFileMapper({ alloc, free, read, guestResumes, canWait, wait, epoch, restartCap, held = () => false }) { let kept = null, busy = false; const none = (o) => ({ addr: 0, done: 0, err: 0, parked: false, lost: false, restarts: 0, ...o }); const keep = (req, addr, done) => { kept = { mfd: req.mfd, len: req.len, prot: req.prot, flags: req.flags, off: req.off, addr, done, epoch: epoch() }; }; const finish = (w) => { const k = kept; for (let streak = 0; ; ) { const r = read(k, k.addr, k.done) | 0; if (held()) return -4; if (!isRestartValue(r)) break; if (w === null) return r; if (++streak > restartCap) return -4; w(); } kept = null; free(k.addr, k.len); return 0; }; const map = (req) => { let from = 0, addr = -1; const coop = guestResumes(); if (kept !== null) { const k = kept; const same2 = k.mfd === req.mfd && k.len === req.len && k.prot === req.prot && k.flags === req.flags && k.off === req.off && k.epoch === epoch(); if (same2) { kept = null; addr = k.addr; from = k.done; } else { const v = finish(!coop && canWait() ? wait : null); if (v !== 0) { return coop && isRestartValue(v) ? none({ parked: true, restarts: 1 }) : none({ addr: v, err: v }); } } } if (addr < 0) { addr = alloc(req) | 0; if (addr < 0) return none({ addr, err: addr }); } let raw = 0; const r = populateFileMapping({ len: req.len, from, read: (done) => raw = read(req, addr, done) | 0, wait: !coop && canWait() ? wait : null, restartCap, held }); if (r.parked || r.lost) keep(req, addr, r.done); if (r.parked && !coop) return { addr, ...r, parked: false, err: raw }; return { addr, ...r }; }; return { map(req) { busy = true; try { return map(req); } finally { busy = false; } }, settle() { if (busy || kept === null) return 0; busy = true; try { return finish(null); } finally { busy = false; } }, /** A new image: the address a kept population was filling is gone. */ reset() { kept = null; } }; } function fileMapGenBucket(words, devMajor, devMinor, inoLo, inoHi) { let h = 2166136261; for (const v of [devMajor, devMinor, inoLo, inoHi]) { h = Math.imul(h ^ v & 65535, 16777619); h = Math.imul(h ^ v >>> 16, 16777619); } return 2 + (h >>> 0) % (words - 2); } function shmapPublishesAt(nr, a2, a3) { if (SHMAP_PRIVATE_SYSCALLS.has(nr)) return false; if (nr === 9) return (a3 & 32) === 0; if (nr === 7) return (a2 | 0) !== 0; if (nr === 232 || nr === 281) return (a3 | 0) !== 0; return true; } function makeSharedFileMaps({ sys, mem, gen, canWait, wait, restartCap = Infinity, epoch, answer = (_nr, r) => r, reissues = () => true, log: log2 = () => { } }) { let maps = []; let scratch = 0; let fdKeys = /* @__PURE__ */ new Map(), fdKeysEpoch = -1; const bucketWords = Math.min(gen.length, FMG_BUCKET_END); const logOn = gen.length >= FILE_MAP_GEN_WORDS; let localIds = 0; const newId = () => (logOn ? Atomics.add(gen, FMG_LOG_IDS, 1) + 1 | 0 : ++localIds) || 1; const logHead = () => logOn ? Atomics.load(gen, FMG_LOG_HEAD) : 0; const countLive = (bucket, d) => { Atomics.add(gen, FMG_LIVE, d); if (logOn) Atomics.add(gen, FMG_WATCH_BASE + bucket - 2, d); }; const watched = (bucket) => logOn && Atomics.load(gen, FMG_WATCH_BASE + bucket - 2) > 0; let held = null, heldCount = 0; const HELD = /* @__PURE__ */ Symbol("held"); let closeLater = []; let exposed = -1; let admission = null; let answered = false; let keepAdmission = false; let passedCount = 0; const call = (nr, a0 = 0, a1 = 0, a2 = 0, a3 = 0, a4 = 0, a5 = 0, info = null) => { if (held !== null) throw HELD; for (let streak = 0; ; ) { const r = sys(nr, a0, a1, a2, a3, a4, a5) | 0; if (!isRestartValue(r)) return r; if (canWait() && ++streak <= restartCap) { wait(); continue; } held = { nr, a: [a0, a1, a2, a3, a4, a5], r, ...info }; if (held.read) held.read.after = mem().slice(held.read.addr, held.read.addr + held.read.len); heldCount++; if ((heldCount & heldCount - 1) === 0) log2(6, `syscall nr=${nr} of the keeper's parked (${r}); held and issued again at the next syscall entry (${heldCount} so far)`); throw HELD; } }; const noteStores = (rd) => { const cur = mem().subarray(rd.addr, rd.addr + rd.len), was = rd.after; for (let i = 0; i < rd.len; i++) { if (cur[i] === was[i]) continue; if (rd.mask === void 0) { rd.mask = new Uint8Array(rd.len); rd.vals = new Uint8Array(rd.len); } rd.mask[i] = 1; rd.vals[i] = cur[i]; } }; const settle = () => { while (held !== null) { const h = held, rd = h.read; if (rd) noteStores(rd); const r = sys(h.nr, ...h.a) | 0; if (isRestartValue(r)) { h.r = r; if (rd) rd.after = mem().slice(rd.addr, rd.addr + rd.len); return r; } held = null; if (rd) { const u8 = mem(); const got = h.nr === 16 ? r < 0 ? 0 : rd.len : Math.max(r, 0); if (got > 0 && maps.includes(rd.e)) rd.e.shadow.set(u8.subarray(rd.addr, rd.addr + got), rd.addr - rd.e.addr); if (rd.mask !== void 0) { for (let i = 0; i < rd.len; i++) if (rd.mask[i]) u8[rd.addr + i] = rd.vals[i]; } } if (h.wrote && r >= 0 && maps.includes(h.wrote.e)) { const { e, pos, len } = h.wrote; const p = Math.floor(pos / 4096); logChanges(e.bucket, e.id, [[p, Math.ceil((pos + len) / 4096) - p]]); Atomics.add(gen, e.bucket, 1); } try { if (h.done) h.done(r); while (closeLater.length > 0) { call(3, closeLater[0]); closeLater.shift(); } } catch (x) { if (x !== HELD) throw x; } } return 0; }; const park = (nr, r0 = 0) => { for (let n = 0; ; n++) { const r = n === 0 && r0 !== 0 ? r0 : settle(); if (r === 0) return 0; const a = answer(nr, r); if (a !== null) { if (a !== 0) answered = true; return a; } if (n >= restartCap) return -4; wait(); } }; const unmapsHeld = (nr, addr, len) => { if (nr !== 11 && nr !== 25 || held === null) return false; let s, n; if (held.read) { s = held.read.addr; n = held.read.len; } else if (held.wrote) { s = held.wrote.e.addr + held.wrote.pos - held.wrote.e.off; n = held.wrote.len; } else return false; return addr < s + n && s < addr + Math.max(len, 1); }; const genOf = (b) => Atomics.load(gen, FMG_ALL) + Atomics.load(gen, b) | 0; const ensureScratch = () => { if (scratch !== 0) return true; const a = sys(9, 0, 4096, 3, 34, -1, 0) | 0; if (a < 0 && a > -4096) return false; scratch = a; return true; }; const statFd = (fd, info = null) => { if (!ensureScratch()) return -12; mem()[scratch] = 0; const r = call(332, fd, scratch, 4096, 2047, scratch + 256, 0, info); return r < 0 ? r : readStat(); }; const readStat = () => { const u8 = mem(); const dv = new DataView(u8.buffer, u8.byteOffset); const b = scratch + 256; const sizeLo = dv.getUint32(b + 40, true), sizeHi = dv.getUint32(b + 44, true); return { mode: dv.getUint16(b + 28, true), inoLo: dv.getUint32(b + 32, true), inoHi: dv.getUint32(b + 36, true), size: sizeHi > 0 ? Number.MAX_SAFE_INTEGER : sizeLo, rdevMajor: dv.getUint32(b + 128, true), rdevMinor: dv.getUint32(b + 132, true), devMajor: dv.getUint32(b + 136, true), devMinor: dv.getUint32(b + 140, true) }; }; const isDrm = (st) => (st.mode & 61440) === 8192 && st.rdevMajor === DRM_MAJOR; const gemCopy = (fd, write, addr, len, pos, info = null) => { if (!ensureScratch()) return -12; const a = scratch + 1024; const dv = new DataView(mem().buffer, mem().byteOffset); dv.setUint32(a, pos >>> 0, true); dv.setUint32(a + 4, 0, true); dv.setUint32(a + 8, len >>> 0, true); dv.setUint32(a + 12, 0, true); dv.setUint32(a + 16, addr >>> 0, true); dv.setUint32(a + 20, 0, true); const r = call( 16, fd, write ? WASMDRM_GEM_PWRITE : WASMDRM_GEM_PREAD, a, 0, 0, 0, info ); return r < 0 ? r : len; }; const fsTypeOf = (fd, info = null) => { if (!ensureScratch()) return -12; const r = call(138, fd, scratch + 256, 0, 0, 0, 0, info); return r < 0 ? r : readFsType(); }; const readFsType = () => { const u8 = mem(); return new DataView(u8.buffer, u8.byteOffset).getUint32(scratch + 256, true); }; const sameFile = (st, e) => st.inoLo === e.inoLo && st.inoHi === e.inoHi && st.devMajor === e.devMajor && st.devMinor === e.devMinor; const transfer = (nr, fd, addr, len, pos, info) => { let done = 0; while (done < len) { const r = call( nr, fd, addr + done | 0, len - done | 0, pos + done | 0, 0, 0, info(done) ); if (r === 0) break; if (r < 0) return done > 0 ? done : r; done += r; } return done; }; const release = (e) => { countLive(e.bucket, -1); if (--e.file.refs !== 0) return; if (held !== null) { closeLater.push(e.file.fd); return; } try { call(3, e.file.fd); } catch (x) { if (x !== HELD) throw x; } }; const detach = (e, why) => { log2(4, `writable MAP_SHARED mapping at 0x${(e.addr >>> 0).toString(16)} len=0x${e.len.toString(16)} detached from its file (${why}); later stores stay private`); maps = maps.filter((m) => m !== e); release(e); }; const dirtyRuns = (e, u8, from = 0, to = e.len) => { const runs = []; const view = u8.subarray(e.addr, e.addr + e.len), sh = e.shadow; let i = from, start = -1, lastDiff = -1; const n = to; const aligned = (u8.byteOffset + e.addr & 3) === 0; const w = aligned ? new Uint32Array(u8.buffer, u8.byteOffset + e.addr, e.len >>> 2) : null; const sw = aligned ? new Uint32Array(sh.buffer, sh.byteOffset, e.len >>> 2) : null; while (i < n) { if (w !== null && (i & 3) === 0 && i + 4 <= n && start < 0) { let k = i >>> 2; const kn = n >>> 2; while (k < kn && w[k] === sw[k]) k++; i = k << 2; if (i >= n) break; } if (view[i] !== sh[i]) { if (start < 0) start = i; else if (i - lastDiff > 64) { runs.push([start, lastDiff + 1]); start = i; } lastDiff = i; } else if (start >= 0 && i - lastDiff > 64) { runs.push([start, lastDiff + 1]); start = -1; } i++; } if (start >= 0) runs.push([start, lastDiff + 1]); return runs; }; const mergeRanges = (rs) => { rs.sort((x, y) => x[0] - y[0]); const out = []; for (const [s, t] of rs) { const last = out[out.length - 1]; if (last !== void 0 && s <= last[1]) last[1] = Math.max(last[1], t); else out.push([s, t]); } return out; }; const logChanges = (bucket, owner, pages2) => { if (!logOn || pages2.length === 0) return; const i0 = Atomics.add(gen, FMG_LOG_HEAD, pages2.length); for (let j = 0; j < pages2.length; j++) { const i = i0 + j | 0; const b = FMG_LOG_BASE + (i & FMG_LOG_SLOTS - 1) * FMG_LOG_STRIDE; Atomics.store(gen, b, 0); Atomics.store(gen, b + 1, bucket); Atomics.store(gen, b + 2, owner); Atomics.store(gen, b + 3, pages2[j][0]); Atomics.store(gen, b + 4, pages2[j][1]); Atomics.store(gen, b, i + 1 | 0); } }; const changesSince = (e, head) => { if (!logOn) return { ranges: null, next: head }; let from = e.logSeen, ranges = e.full ? null : []; const behind = head - from | 0; if (behind < 0 || behind > FMG_LOG_SLOTS) { ranges = null; from = head - FMG_LOG_SLOTS | 0; } let next = head; for (let i = from; i !== head; i = i + 1 | 0) { const b = FMG_LOG_BASE + (i & FMG_LOG_SLOTS - 1) * FMG_LOG_STRIDE; const tag = i + 1 | 0; if (Atomics.load(gen, b) !== tag) { if (next === head) next = i; continue; } if (ranges === null) continue; const bucket = Atomics.load(gen, b + 1), owner = Atomics.load(gen, b + 2); const p0 = Atomics.load(gen, b + 3) >>> 0, n = Atomics.load(gen, b + 4) >>> 0; if (Atomics.load(gen, b) !== tag) { if (next === head) next = i; continue; } if (bucket !== e.bucket || owner === e.id) continue; if (n === 0) { ranges = null; continue; } const s = Math.max(p0 * 4096 - e.off, 0); const t = Math.min((p0 + n) * 4096 - e.off, e.len); if (s < t) ranges.push([s, t]); } return { ranges: ranges === null ? null : mergeRanges(ranges), next }; }; const publish = (e, ranges = null) => { if (e.readOnly) return; const u8 = mem(); const runs = ranges === null ? dirtyRuns(e, u8) : ranges.flatMap(([s, t]) => dirtyRuns(e, u8, s, t)); if (runs.length === 0) return; const st = statFd(e.file.fd); if (typeof st !== "object" || !sameFile(st, e)) { detach(e, typeof st === "object" ? "its descriptor now names another file" : `statx errno ${-st}`); return; } const before = genOf(e.bucket); const size = e.device ? e.off + e.len : st.size; const pages2 = []; try { for (const [s, t] of runs) { e.shadow.set(u8.subarray(e.addr + s, e.addr + t), s); const pos = e.off + s; if (pos >= size) continue; const len = Math.min(t, size - e.off) - s; let r; try { r = e.device ? gemCopy(e.file.fd, true, e.addr + s, len, pos, { wrote: { e, pos, len } }) : transfer( 18, e.file.fd, e.addr + s, len, pos, (d) => ({ wrote: { e, pos: pos + d, len: len - d } }) ); } catch (x) { if (x === HELD) for (let i = s; i < t; i++) e.shadow[i] = ~u8[e.addr + i]; throw x; } if (e.device && (r === -2 || r === -22)) { detach(e, `its GEM object is gone (errno ${-r})`); return; } if (r < 0) { if (!e.warned) { e.warned = true; log2(3, `writable MAP_SHARED publish to fd=${e.file.fd} at 0x${pos.toString(16)} failed: errno ${-r}`); } continue; } pages2.push([Math.floor(pos / 4096), Math.ceil((pos + len) / 4096)]); } } finally { if (pages2.length > 0) { let rs = mergeRanges(pages2); if (rs.length > FMG_LOG_MAX_PER_PUBLISH) rs = [[rs[0][0], rs[rs.length - 1][1]]]; logChanges(e.bucket, e.id, rs.map(([p, q]) => [p, q - p])); Atomics.add(gen, e.bucket, 1); if (before === e.seen) e.seen = before + 1 | 0; } } }; const load = (e, ranges = null) => { const st = statFd(e.file.fd); if (typeof st !== "object" || !sameFile(st, e)) { detach(e, typeof st === "object" ? "its descriptor now names another file" : `statx errno ${-st}`); return false; } for (const [s, t] of ranges ?? [[0, e.len]]) { let got; if (e.device) { got = gemCopy( e.file.fd, false, e.addr + s, t - s, e.off + s, { read: { e, addr: e.addr + s, len: t - s } } ); if (got === -2 || got === -22) { detach(e, `its GEM object is gone (errno ${-got})`); return false; } } else { const want = Math.max(0, Math.min(t, st.size - e.off) - s); got = want > 0 ? transfer( 17, e.file.fd, e.addr + s, want, e.off + s, (d) => ({ read: { e, addr: e.addr + s + d, len: want - d } }) ) : 0; } if (got < 0) return false; const u8 = mem(); if (got < t - s) u8.fill(0, e.addr + s + got, e.addr + t); e.shadow.set(u8.subarray(e.addr + s, e.addr + t), s); } return true; }; const refresh = (e) => { const g = genOf(e.bucket); if (g === e.seen) return; const all = Atomics.load(gen, FMG_ALL); const { ranges: changed, next } = changesSince(e, logHead()); const ranges = all === e.seenAll ? changed : null; const was = { seen: e.seen, seenAll: e.seenAll, logSeen: e.logSeen, full: e.full }; e.seen = g; e.seenAll = all; e.logSeen = next; e.full = false; try { publish(e, ranges); if (!maps.includes(e)) return; if (ranges !== null && ranges.length === 0) return; if (!load(e, ranges) && maps.includes(e)) { e.seen = g - 1 | 0; e.full = true; } } catch (x) { if (x === HELD) Object.assign(e, was); throw x; } }; const bucketOfFd = (fd) => { const ep = epoch(); if (ep !== fdKeysEpoch) { fdKeys = /* @__PURE__ */ new Map(); fdKeysEpoch = ep; } let b = fdKeys.get(fd); if (b === void 0) { const st = statFd(fd); b = typeof st === "object" && (st.mode & 61440) === 32768 ? fileMapGenBucket(bucketWords, st.devMajor, st.devMinor, st.inoLo, st.inoHi) : -1; fdKeys.set(fd, b); } return b; }; const overlapping = (addr, len) => { const end = addr + len; return maps.filter((e) => e.addr < end && addr < e.addr + e.len); }; return { /** Has this task a mapping to keep, or a call of the keeper's held? */ active() { return maps.length > 0 || held !== null; }, /** The number of the keeper's held call, or 0. */ heldCall() { return held === null ? 0 : held.nr; }, /** * May `fd` be mapped shared and kept in step with the file? 0, or the * errno and reason of the refusal. A read-only mapping (`write` false) * needs no write access to the descriptor. With `held` set, `err` is what * the mmap returns so that the guest issues it again. */ admit(fd, write = true, off = 0) { for (; ; ) { if (held !== null) { const a = park( 9 /* mmap */ ); if (a !== 0) return { err: a, held: true, why: "a call of the keeper is held" }; } try { return this.admitOnce(fd, write, off); } catch (x) { if (x !== HELD) throw x; } } }, admitOnce(fd, write, off) { const ep = epoch(); let a = admission; if (a === null || a.fd !== fd || a.write !== write || a.off !== off || a.epoch !== ep) a = admission = { fd, write, off, epoch: ep }; const ask = (k, issue, read) => { if (!(k in a)) a[k] = issue({ done: (r) => { a[k] = r < 0 ? r : read(r); } }); return a[k]; }; const fl = ask( "fl", (info) => call(72, fd, 3, 0, 0, 0, 0, info), (r) => r ); if (fl < 0) return { err: -9, why: "bad descriptor" }; if (write && (fl & 3) !== 2) return { err: -13, why: "descriptor not open read-write" }; if (write && (fl & 1024) !== 0) return { err: -19, why: "O_APPEND descriptor: a positioned write would append" }; const st = ask("st", (info) => statFd(fd, info), readStat); if (typeof st !== "object") return { err: -19, why: `statx errno ${-st}` }; if (isDrm(st)) { const r = ask("gem", (info) => gemCopy(fd, false, 0, 0, off, info), () => 0); if (r < 0) return { err: -19, why: `no GEM object at this offset the kernel copies (GEM_PREAD errno ${-r})` }; return { err: 0, st, device: true }; } if ((st.mode & 61440) !== 32768) return { err: -19, why: "not a regular file (device mappings are not shared)" }; if (!write) { const fsType = ask("fs", (info) => fsTypeOf(fd, info), readFsType); if (fsType !== TMPFS_MAGIC && fsType !== RAMFS_MAGIC && !canWait()) return { err: -19, why: `file on fs 0x${(fsType >>> 0).toString(16)} may park, and this task cannot wait in place to refresh it` }; } return { err: 0, st }; }, /** Is `fd` a DRM device, whose mappings are copied with GEM ioctls? */ isDevice(fd) { try { const st = statFd(fd); return typeof st === "object" && isDrm(st); } catch (x) { if (x !== HELD) throw x; return false; } }, /** Populate a mapping of a DRM device: `len` bytes, or a negative errno, * or, while the copy is held, what the mmap returns so that the guest * issues it again (the allocation is then the held copy's to fill). */ populateDevice(fd, addr, len, off) { try { return gemCopy(fd, false, addr, len, off); } catch (x) { if (x !== HELD) throw x; const a = park( 9 /* mmap */ ); return a !== 0 ? a : len; } }, /** * Track a populated mapping. 0, or a negative errno when no descriptor * could be kept for it. */ track({ addr, len, off, fd, st, readOnly = false, device = false }) { const closeIt = { done: (r) => { if (r >= 0) closeLater.push(r); } }; let dup; for (; ; ) { if (held !== null) { const a = park( 9 /* mmap */ ); if (a !== 0) return a; } try { dup = call(72, fd, 1030, 512, 0, 0, 0, closeIt); if (dup < 0) dup = call(72, fd, 1030, 3, 0, 0, 0, closeIt); break; } catch (x) { if (x !== HELD) throw x; } } if (dup < 0) return dup; const bucket = device ? fileMapGenBucket(bucketWords, st.rdevMajor, st.rdevMinor, off, 4294967295) : fileMapGenBucket(bucketWords, st.devMajor, st.devMinor, st.inoLo, st.inoHi); const u8 = mem(); maps.push({ addr: addr >>> 0, len, off, file: { fd: dup, refs: 1 }, devMajor: st.devMajor, devMinor: st.devMinor, inoLo: st.inoLo, inoHi: st.inoHi, bucket, seen: genOf(bucket), warned: false, readOnly, device, id: newId(), seenAll: Atomics.load(gen, FMG_ALL), logSeen: logHead(), full: false, shadow: u8.slice(addr >>> 0, (addr >>> 0) + len) }); countLive(bucket, 1); return 0; }, /** * Syscall entry: issue a held call again, publish every mapping if the * call is one that publishes, then apply what the call does to the * mappings themselves. 0, or, while a call is held, what a syscall the * libc issues again returns without being issued. Any other syscall * goes to the kernel as it is: an answer it does not issue again would * be its result. */ enter(nr, a0, a1, a2, a3) { answered = false; keepAdmission = held !== null && !((nr | 0) === 9 && ((a3 | 0) & 32) === 0); if (nr === 1028 && held !== null) return 0; if (nr === 231 || nr === 60 || nr === 1027) { held = null; closeLater = []; } for (; ; ) { if (held !== null && exposed === -1) { let r = settle(); const fileMmap = (nr | 0) === 9 && ((a3 | 0) & 32) === 0; if (r !== 0 && !reissues(nr | 0) && !fileMmap) { if ((nr | 0) !== held.nr && !unmapsHeld(nr | 0, a0 >>> 0, a1 >>> 0)) { passedCount++; if ((passedCount & passedCount - 1) === 0) log2(6, `syscall nr=${nr} issued over the keeper's held nr=${held.nr} (${passedCount} so far)`); break; } for (let n = 0; r !== 0; n++) { if (n >= restartCap) return -4; wait(); r = settle(); } } if (r !== 0) { const a = park(nr, r); if (a !== 0) return a; } } if (maps.length === 0 || exposed !== -1 || held !== null) break; try { if (shmapPublishesAt(nr, a2, a3)) for (const e of maps.slice()) publish(e); break; } catch (x) { if (x !== HELD) throw x; } } if (nr === 11) this.unmap(a0 >>> 0, a1 >>> 0); else if (nr === 231) this.reset(); return 0; }, /** * Syscall exit: record a file change the call made, then refresh every * mapping whose file changed. A call answered with a restart value has * not returned: it is issued again, and its chain may be on top of the * park stack, so nothing of the keeper's is issued over it. */ leave(nr, a0, a1, a2, r) { if (isRestartValue(r | 0) || (r | 0) === HWJS_EMMAP_PARKED) { if (!answered) exposed = nr | 0; answered = false; return; } answered = false; exposed = -1; if (!keepAdmission) admission = null; keepAdmission = false; try { if (gen[FMG_LIVE] > 0 && (r | 0) >= 0) { const arg = FILE_WRITE_FD_ARG.get(nr); if (arg !== void 0 && (r > 0 || nr === 77 || nr === 285)) { let b; try { b = held === null ? bucketOfFd(arg === 0 ? a0 | 0 : a2 | 0) : -2; } catch (x) { if (x !== HELD) throw x; b = -2; } if (b === -2) { Atomics.add(gen, FMG_ALL, 1); } else if (b >= 0) { if (watched(b)) logChanges(b, 0, [[0, 0]]); Atomics.add(gen, b, 1); } } else if (nr === 76 || nr === 85 || nr === 2 && (a1 & 512) !== 0 || nr === 257 && (a2 & 512) !== 0) { Atomics.add(gen, FMG_ALL, 1); } } if (maps.length === 0 || held !== null) return; for (const e of maps.slice()) refresh(e); } catch (x) { if (x !== HELD) throw x; } }, /** * mremap of a tracked mapping, published already at this call's entry: * the new address or a negative errno, or null when no tracked mapping * starts at `old` or the call is one not served here (the mapping then * detaches, and the caller goes on as it would without one). */ remap(old, oldSize, newSize, flags) { const e = maps.find((m) => m.addr === old); if (e === void 0) return null; const pg = (n) => Math.ceil(n / 4096) * 4096; if ((flags & ~1) !== 0 || pg(oldSize) !== pg(e.len) || oldSize === 0) { detach(e, `mremap not served (flags=0x${(flags >>> 0).toString(16)} old_size=0x${(oldSize >>> 0).toString(16)})`); return null; } if (newSize === 0) return -22; let addr = e.addr; if (pg(newSize) > pg(e.len)) { if ((flags & 1) === 0) return -12; const na = sys( 9, 0, newSize, 3, 34, -1, 0 ) | 0; if (na < 0 && na > -4096) return na; addr = na >>> 0; mem().copyWithin(addr, e.addr, e.addr + e.len); sys(11, e.addr, pg(e.len), 0, 0, 0, 0); } else if (pg(newSize) < pg(e.len)) { sys(11, e.addr + pg(newSize), pg(e.len) - pg(newSize), 0, 0, 0, 0); } const shadow = new Uint8Array(newSize); shadow.set(e.shadow.subarray(0, Math.min(newSize, e.len))); e.addr = addr; e.len = newSize; e.shadow = shadow; e.seen = genOf(e.bucket); e.seenAll = Atomics.load(gen, FMG_ALL); e.logSeen = logHead(); e.full = false; try { load(e); } catch (x) { if (x !== HELD) throw x; e.seen = e.seen - 1 | 0; e.full = true; } return addr | 0; }, /** msync: validate; MS_INVALIDATE re-reads the range. Publishing already * happened at entry. */ msync(addr, len, flags) { if ((addr & 4095) !== 0) return -22; if ((flags & ~7) !== 0 || (flags & 1) !== 0 && (flags & 4) !== 0) return -22; if ((flags & 2) !== 0) for (const e of overlapping(addr >>> 0, len >>> 0)) { e.seen = e.seen - 1 | 0; e.full = true; } return 0; }, /** munmap of [addr, addr+len): drop or trim the mappings it covers. */ unmap(addr, len) { len = len + 4095 & ~4095; const end = addr + len; for (const e of overlapping(addr, len)) { const eEnd = e.addr + e.len; const keep = []; if (e.addr < addr) keep.push([e.addr, addr]); if (end < eEnd) keep.push([end, eEnd]); maps = maps.filter((m) => m !== e); for (const [s, t] of keep) { e.file.refs++; countLive(e.bucket, 1); maps.push({ ...e, addr: s, len: t - s, off: e.off + (s - e.addr), id: newId(), shadow: e.shadow.slice(s - e.addr, t - e.addr) }); } release(e); } }, /** What a fork child adopts: every mapping, published, with its shadow. */ forkRecord() { try { if (held === null) for (const e of maps.slice()) publish(e); } catch (x) { if (x !== HELD) throw x; } if (maps.length === 0) return null; return { scratch, maps: maps.map((e) => ({ addr: e.addr, len: e.len, off: e.off, fd: e.file.fd, devMajor: e.devMajor, devMinor: e.devMinor, inoLo: e.inoLo, inoHi: e.inoHi, bucket: e.bucket, seen: e.seen, readOnly: e.readOnly, device: e.device, seenAll: e.seenAll, logSeen: e.logSeen, full: e.full, shadow: e.shadow.slice() })) }; }, /** A fork child (or a migrated task) takes over a forkRecord. */ adopt(rec) { if (!rec || !Array.isArray(rec.maps)) return; if (typeof rec.scratch === "number") scratch = rec.scratch | 0; const files = /* @__PURE__ */ new Map(); for (const m of rec.maps) { let file = files.get(m.fd); if (!file) { file = { fd: m.fd | 0, refs: 0 }; files.set(m.fd, file); } file.refs++; maps.push({ addr: m.addr >>> 0, len: m.len | 0, off: m.off | 0, file, devMajor: m.devMajor, devMinor: m.devMinor, inoLo: m.inoLo, inoHi: m.inoHi, bucket: m.bucket | 0, seen: m.seen | 0, warned: false, readOnly: m.readOnly === true, device: m.device === true, id: newId(), seenAll: m.seenAll | 0, logSeen: m.logSeen | 0, full: m.full !== false, shadow: m.shadow instanceof Uint8Array ? m.shadow : new Uint8Array(m.shadow) }); countLive(m.bucket | 0, 1); } }, /** A new image or the end of the process: the mappings are gone. Their * descriptors close with the image (close-on-exec) or the process. */ reset() { for (const e of maps) countLive(e.bucket, -1); maps = []; scratch = 0; admission = null; fdKeys = /* @__PURE__ */ new Map(); held = null; closeLater = []; exposed = -1; }, /** Test and diagnostic view. */ list() { return maps.map((e) => ({ addr: e.addr, len: e.len, off: e.off, fd: e.file.fd })); } }; } function wasmSignalPendingIn(i32, idx) { if (idx < 0) return false; const lo = Atomics.load(i32, idx) | 0; const hi = Atomics.load(i32, idx + 1) | 0; return lo !== 0 || hi !== 0; } function taskStateSleeping(s) { return (s & 3) !== 0 && (s & ~9475) === 0; } function waitTaskRunnable(i32, wakeIdx, seq, stateIdx, timeoutMs) { const st = stateIdx >= 0 ? Atomics.load(i32, stateIdx) | 0 : 0; const w = Atomics.waitAsync(i32, wakeIdx, seq, timeoutMs); if (!w.async) return Promise.resolve(w.value); if (stateIdx < 0 || !taskStateSleeping(st)) return w.value; const s = Atomics.waitAsync(i32, stateIdx, st, timeoutMs); if (!s.async) { Atomics.notify(i32, wakeIdx, 1); return Promise.resolve(s.value); } return Promise.race([ w.value.then((r) => [stateIdx, r]), s.value.then((r) => [wakeIdx, r]) ]).then(([loser, r]) => { Atomics.notify(i32, loser, 1); return r; }); } function makeSigchldReassert({ getI32, getIdx, inExecWindow, askKernel, red }) { const redHostWritesBit = !!(red && red.hostWritesBit); function pendingNow() { const idx = getIdx(); if (idx < 0) return false; return (Atomics.load(getI32(), idx + SIGPEND_I32_PENDING_LO) & SIGCHLD_PENDING_BIT_LO) !== 0; } function deliverySeq() { const idx = getIdx(); if (idx < 0) return 0; return Atomics.load(getI32(), idx + SIGPEND_I32_SIGCHLD_DELIVERY_SEQ) >>> 0; } function wake() { const idx = getIdx(); if (idx < 0) return; const wakeIdx = idx + SIGPEND_I32_WAKE_WORD; Atomics.add(getI32(), wakeIdx, 1); Atomics.notify(getI32(), wakeIdx, Infinity); } function republish() { const idx = getIdx(); if (idx < 0) return false; if (redHostWritesBit) { Atomics.or( getI32(), idx + SIGPEND_I32_PENDING_LO, SIGCHLD_PENDING_BIT_LO ); wake(); return true; } const n = askKernel(); if (!(n > 0)) return false; wake(); return true; } function maybeReassert(armed) { if (!armed) return false; if (inExecWindow()) return false; if (pendingNow()) return false; return republish(); } return { pendingNow, deliverySeq, maybeReassert, /** The raw re-assert, exported for the callers that already had it. */ republish }; } function makeHostWaitSignals({ getI32, getIdx, getWakeSeq, askKernel, red }) { const redNoAsk = !!(red && red.noAsk); let askedAtSeq = null; let asked = false; function refresh() { if (redNoAsk || getIdx() < 0) return false; const seq = getWakeSeq(); if (seq !== null && asked && seq === askedAtSeq) return false; askedAtSeq = seq; asked = true; return askKernel() > 0; } function sigkillPending() { const idx = getIdx(); if (idx < 0) return false; return (Atomics.load(getI32(), idx + SIGPEND_I32_PENDING_LO) & SIGKILL_PENDING_BIT_LO) !== 0; } return { refresh, sigkillPending }; } function futexWaitSliced({ getI32, i32idx, val, timeoutMs, sliceMs, interrupted, between, wait = Atomics.wait }) { let remainingMs = timeoutMs; let result; for (; ; ) { const slice = Math.min(remainingMs, sliceMs); result = wait(getI32(), i32idx, val | 0, slice); if (result !== "timed-out") break; if (remainingMs !== Infinity) { remainingMs -= slice; if (remainingMs <= 0) break; } if (interrupted()) break; if (Atomics.load(getI32(), i32idx) !== (val | 0)) { result = "ok"; break; } between(); } return result; } function sysEnvKnobs() { const out = {}; if (typeof process === "undefined" || !process.env) return out; for (const k of Object.keys(process.env)) { if (SYS_ENV_KNOB.test(k)) out[k] = process.env[k]; } return out; } async function run(init, post, sched) { let hostTerminal = false; { const postToHost = post; post = (m) => { if (m !== null && typeof m === "object" && m.kind === "error") hostTerminal = true; return postToHost(m); }; } setLinkPlanReport((text) => post({ kind: "dmesg", level: 4, text })); thrTrace(init, post, "run-entry"); schedTrace(post, `RUN cpu=${init.cpuId ?? "?"} tid=${init.tid} pid=${init.pid} mode=${init.mode ?? "fork"} rt=${init.rtThread ? 1 : 0} resident=${sched ? 1 : 0}`); const ctrl = new Int32Array(init.ctrl, 0, 16); ctrl[C.PID] = init.pid; ctrl[C.TID] = init.tid; sharedLibsMerge(init.sharedLibs, post); threadPlacementProviders.set(init, { getPid: () => ctrl[C.PID] | 0, build: () => buildDlopenForkRecord() }); const pauseArr = init.pauseBuffer ? new Int32Array(init.pauseBuffer) : null; const pauseMayBlock = init.mergedCpu0Lane !== true; const maybePause = () => { if (!pauseArr || !pauseMayBlock) return; if (pauseArr[0] !== 1) return; while (Atomics.load(pauseArr, 0) === 1) { Atomics.wait(pauseArr, 0, 1, 200); } }; const slicePause = async () => { if (!isPaused(pauseArr)) return; if (pauseMayBlock) maybePause(); else await waitOutPause(pauseArr); }; let exitPosted = false; let exitCode = 0; let mainClearTid = 0; let pendingExitTerminus = null; let migratedAway = false; let childExitNotified = false; let exitDrainStepNoted = false; async function notifyChildExitOnce(code2, signaled) { if (childExitNotified) return; if (!vmlinuxInstance || perProcessTaskAddr === 0 || typeof vmlinuxInstance.exports.__wasm32_notify_child_exit !== "function") { return; } childExitNotified = true; if (D1_TRACE_FD) { try { post({ kind: "dmesg", level: 6, text: `hwjs-fd pid=${ctrl[C.PID] | 0} NOTIFY-CHILD-EXIT ptask=0x${(perProcessTaskAddr >>> 0).toString(16)} code=${code2 | 0} signaled=${signaled | 0}` }); } catch (_e) { } } try { const exp = vmlinuxInstance.exports; if (typeof exp.wasm32_exit_drain_step === "function" && hwjsLane) { const drainChain = { h: 0, owner: 0 }; const step = () => exp.wasm32_exit_drain_step() | 0; let legs = 0; await driveExecLoadWithYield({ load: () => hwjsLane.driveWouldBlock( "wasm32_exit_drain_step", step, drainChain ).wouldBlock ? HWJS_ERESTART_RESCHED : 0, yieldTurn: () => coopWaitParkYield("exit-drain park"), onYield: () => { legs++; if (legs === 1) { try { post({ kind: "dmesg", level: 6, text: `hwjs-exit pid=${init.pid} tid=${init.tid | 0} wasm32_exit_drain_step would-block \u2014 handing the CPU Worker back across a real event-loop turn before resuming the preserved syscall chain (the device backends and the in-flight fetch continuations run in that turn; this is the turn the native in-wasm drain could not take)` }); } catch (_e) { } } if (SCHED_TRACE) { schedTrace(post, `YIELD cpu=${init.cpuId ?? "?"} tid=${init.tid} reason=EXIT-DRAIN-park site=wasm32-exit-drain-step via=wake-word`); } } }); } else if (!exitDrainStepNoted) { exitDrainStepNoted = true; try { post({ kind: "dmesg", level: 4, text: `hwjs-exit pid=${init.pid} ` + (typeof exp.wasm32_exit_drain_step === "function" ? `has no hwjs lane bracket, so ` : `this vmlinux exports no wasm32_exit_drain_step, so `) + `the exit drain is NOT driven from JS: a preserved block-parked syscall is drained by entry.c's native in-wasm spin inside task_exit_cleanup, which cannot hand a would-block back. On a merged lane that spin holds the JS thread the backend it is waiting on runs on, and the wait ends only at fs/fuse/dev.c's deadline (wasm_fuse_timeout, 120 s). Never-silent.` }); } catch (_e) { } } if (typeof exp.task_exit_cleanup === "function") { const cleanup = () => { exp.task_exit_cleanup(perProcessTaskAddr | 0); return 0; }; if (hwjsLane) { const chain = { h: 0, owner: 0 }; let blocks = 0; await driveExecLoadWithYield({ load: () => hwjsLane.driveWouldBlock( "task_exit_cleanup", cleanup, chain ).wouldBlock ? HWJS_ERESTART_RESCHED : 0, yieldTurn: () => coopWaitParkYield("task-exit-cleanup park"), onYield: () => { blocks++; if (blocks === 1) { try { post({ kind: "dmesg", level: 6, text: `hwjs-exit pid=${init.pid} tid=${init.tid | 0} task_exit_cleanup would-block \u2014 handing the CPU Worker back across a real event-loop turn before resuming the preserved cleanup chain (contract 3, site 4)` }); } catch (_e) { } } if (SCHED_TRACE) { schedTrace(post, `YIELD cpu=${init.cpuId ?? "?"} tid=${init.tid} reason=EXIT-CLEANUP-park site=task-exit-cleanup via=wake-word`); } } }); } else cleanup(); } const call = () => { exp.__wasm32_notify_child_exit( perProcessTaskAddr | 0, code2 | 0, signaled | 0 ); return 0; }; if (hwjsLane) hwjsLane.bracket("__wasm32_notify_child_exit", call); else call(); if (typeof exp.task_exit_notify_parent === "function") { const notifyParent = () => { exp.task_exit_notify_parent(perProcessTaskAddr | 0); return 0; }; if (hwjsLane) hwjsLane.bracket("task_exit_notify_parent", notifyParent); else notifyParent(); } } catch (e) { post({ kind: "error", pid: init.pid, message: "F112 child-exit (task_exit_cleanup / __wasm32_notify_child_exit) trapped: " + (e instanceof Error ? e.message : String(e)) }); } } async function runExitTerminus() { const t = pendingExitTerminus; if (!t) return; pendingExitTerminus = null; await notifyChildExitOnce(t.codeArg, t.signaled); postExitMessage(t); } function postExitMessage({ codeArg, signaled, grpExit }) { if (exitPosted) return; xmodConsultStatsReport("exit"); exitPosted = true; post({ kind: "exit", pid: init.pid, code: exitCode, /* K11-C2: explicit signaled-vs-exit kind so the * spawnHandler / onUserExit consumers know whether the * Worker died by signal. Default kind="exit" preserves * pre-K11-C2 behaviour. */ kind_exit: signaled ? "exit-by-signal" : "exit", /* The EFFECTIVE signal, not a0: a thread that abort()s into a group * already dying of something else reports the group's signal, which * is what the parent's wait4 will say. */ signal: signaled ? codeArg & 127 : 0, /* * THE GROUP IS DYING, AND THE KERNEL SAID SO. Carried on the exit * post so the spawn handler can run the unwind MECHANISM it already * owns (threadContain.killGroup: force-clear the mask bit, stamp the * SIGKILL the kernel already made pending, and schedule the bounded * group-death reap for a signal-blind survivor). `zapped` is the * kernel's count, not a host guess — zero means the kernel condemned * nobody and the host must unwind nobody, which is what keeps the * wasm_grpexit_red / wasm_sigfatal_red arms real measurements * instead of decisions the host quietly makes anyway. * * PRESENT WHENEVER THE KERNEL WAS ASKED, INCLUDING WITH zapped == 0, * and that distinction is load-bearing. "The kernel condemned nobody" * and "the kernel was never consulted" are different facts and the * spawn handler acts differently on them: on the first it unwinds * nobody, on the second it keeps the belt it has always had for * terminal shapes the kernel never sees (a Worker trap, a vmlinux * skew). An absent field used to mean both. */ ...grpExit ? { groupExit: { wstatus: grpExit.wstatus, zapped: grpExit.zapped } } : {}, wasmSyscallStats: wasmSyscallStatsObject(), ...coopWaitViolations > 0 ? { coopWaitViolations } : {}, ...syncRestartViolations > 0 ? { syncRestartViolations } : {}, /* F87 conf (3) AMENDED: the COUNTED, lane-attributed census * line carries the end-of-process RECONCILIATION (fatal on * unexplained residue — reconcile() posts + throws; the * exit message still goes out with the raw census so the * harness sees both the exit and the refusal). */ ...hwjsLane ? { hwjsLaneCensus: reconcileOrFlag(hwjsLane) } : {} }); } function containTrappedLane(where) { try { if (vmlinuxInstance && typeof vmlinuxInstance.exports.__hwjs_lane_contain === "function") { try { if (typeof vmlinuxInstance.exports.__hwjs_dump_park_trace === "function") vmlinuxInstance.exports.__hwjs_dump_park_trace(); } catch (_e) { } const dirty = vmlinuxInstance.exports.__hwjs_lane_contain() | 0; if (dirty !== 0) { post({ kind: "dmesg", level: 3, text: `hwjs #85 CONTAINMENT pid=${init.pid} tid=${init.tid | 0} (${where}): kernel lane state reclaimed after a terminal trap (dirty mask=${dirty}: 1=orphaned parked slot, 2=in-violation latch, 4=stale slice marker) \u2014 identities in the hwjs-rt containment lines above` }); } return dirty; } } catch (e) { post({ kind: "dmesg", level: 3, text: `hwjs #85 CONTAINMENT pid=${init.pid}: __hwjs_lane_contain itself trapped (${e instanceof Error ? e.message : String(e)}) \u2014 lane state NOT reclaimed; a same-lane bystander may still trap` }); } return 0; } let groupExitAsked = false; let groupExitArity = 0; function decideGroupExit(code2, bySignal) { if (groupExitAsked) return null; if (!vmlinuxInstance || perProcessTaskAddr === 0) return null; groupExitAsked = true; const what = bySignal ? `a fatal terminus by signal ${code2 & 127}` : `exit_group(${code2 & 255})`; const exp = vmlinuxInstance.exports; if (typeof exp.__wasm32_group_exit !== "function") { post({ kind: "dmesg", level: 3, text: `hwjs-groupexit pid=${init.pid} tid=${init.tid | 0}: this vmlinux has no __wasm32_group_exit export \u2014 ${what} cannot be decided by the kernel, so do_group_exit/zap_other_threads do not run and only the calling task ends. KERNEL/HOST SKEW: rebuild vmlinux` }); return null; } if (groupExitArity === 0) { try { groupExitArity = (exp.__wasm32_group_exit.length | 0) >= 2 ? 2 : 1; } catch (_e) { groupExitArity = 1; } } if (bySignal && groupExitArity < 2) { post({ kind: "dmesg", level: 3, text: `hwjs-groupexit pid=${init.pid} tid=${init.tid | 0}: this vmlinux's __wasm32_group_exit takes no by_signal argument \u2014 ${what} cannot be decided by the kernel, so the group is NOT condemned by it and this process may outlive a fatal signal on one of its threads. KERNEL/HOST SKEW: rebuild vmlinux` }); return null; } try { const arg0 = bySignal ? code2 & 127 : code2 & 255; const call = () => exp.__wasm32_group_exit(arg0, bySignal ? 1 : 0) | 0; const packed = (hwjsLane ? hwjsLane.bracket("__wasm32_group_exit", call) : call()) | 0; if (packed < 0) return null; return { wstatus: packed & 65535, zapped: packed >>> 16 & 32767 }; } catch (e) { post({ kind: "dmesg", level: 3, text: `hwjs-groupexit pid=${init.pid} tid=${init.tid | 0}: __wasm32_group_exit trapped (${e instanceof Error ? e.message : String(e)}) \u2014 the group's other threads were NOT condemned; this process may outlive ${what}` }); return null; } } function containThreadGroupAfterTrap(sig = 9, why = "thread trap") { try { const exp = vmlinuxInstance ? vmlinuxInstance.exports : null; if (!exp || perProcessTaskAddr === 0 || typeof exp.__wasm32_thread_trap_contain !== "function") { post({ kind: "dmesg", level: 3, text: `hwjs #85 CONTAINMENT pid=${init.pid} tid=${init.tid | 0}: ${why} group-kill UNAVAILABLE (vmlinux export/task missing) \u2014 the host-side spawn-handler belt still delivers SIGKILL to the group` }); return; } const call = () => { exp.__wasm32_thread_trap_contain(sig | 0); return 0; }; if (hwjsLane) hwjsLane.bracket("__wasm32_thread_trap_contain", call); else call(); } catch (e) { post({ kind: "dmesg", level: 3, text: `hwjs #85 CONTAINMENT pid=${init.pid} tid=${init.tid | 0}: __wasm32_thread_trap_contain trapped (${e instanceof Error ? e.message : String(e)}) \u2014 kernel-side group kill incomplete; the host-side spawn-handler belt still delivers SIGKILL to the group` }); } } let syscallTrapContainments = 0; const SYSCALL_TRAP_CONTAIN_CAP = 16; const SYS_FORK = 57; const SYS_EXECVE = 59; let userExports = null; let wasmJitInstance = null; let wasmJitImage = null; const wasmJitToken = {}; const wasmJit = makeWasmJitHost({ memory: init.memory, instance: () => wasmJitInstance, image: () => wasmJitImage, cpuId: init.cpuId, log: (text) => { try { post({ kind: "dmesg", level: 4, text: `pid=${ctrl[C.PID] | 0} ${text}` }); } catch (_e) { } }, onInstall: () => { wasmJitMemories.add(init.memoryId, wasmJitToken); }, /* A fork child's memory is its parent's copy: the emulator's cache in * it names the parent's slots, so the child's JIT starts past them. */ slotFloor: init.mode === "fork-resume" ? init.wasmJitFloor : 0 }); const wasmJitRelease = () => { wasmJit.drop(); wasmJitInstance = null; wasmJitImage = null; wasmJitMemories.release(init.memoryId, wasmJitToken); }; let hwjsRtInstance = null; let hwjsRtPlacement = null; let hwjsRtHandle = null; let hwjsRtStackPointer = null; let threadSideSpTop = 0; let hwjsLaneBudget = null; let hwjsRtChannelGlobal = null; let threadCtx = null; let threadCtxJoin = false; let threadRec = null; let libcSoHandle = null; let libcSoPath = ""; let libcSoPlacement = null; let neededPlacements = []; let neededSoHandles = []; const dladdrKnownPaths = /* @__PURE__ */ new Map(); function libraryReadPath(digest) { return dladdrKnownPaths.get(digest) || sharedLibPaths.get(digest); } let mainGotFuncNames = null; const dlsymCallerBox = { caller: null }; const MAIN_DLSYM_CALLER = Object.freeze({ kind: "main" }); let deferredNeededCtors = []; let neededCtorTrampolines = []; let mainCheckEmitting = false; let mainLaneAddressed = false; let mainManifestDriveAbi = 0; let moduleBudgetGlobals = []; const armModuleBudget = (h) => { if (!h) return; const cands = []; if (h.budgetGlobal instanceof WebAssembly.Global) cands.push(h.budgetGlobal); const exG = h.exports ? h.exports.__hwjs_budget : void 0; if (exG instanceof WebAssembly.Global) cands.push(exG); for (const g of cands) { try { g.value = HWJS_USER_INITIAL_BUDGET | 0; } catch (_e) { continue; } moduleBudgetGlobals.push(g); } }; const setModuleBudgets = (v) => { for (const g of moduleBudgetGlobals) { try { g.value = v | 0; } catch (_e) { } } }; const laneRec = laneRecByInit.get(init) ?? { probe: null, quiet: false, due: Infinity }; let breathDispatchActive = false; let breathRefill = HWJS_SP_REFILL; let breathCostHi = 0, breathCostPrev = Infinity, breathCostT = 0; let breathCutSeq = 0, breathSyscallCuts = 0; let breathCutLeft = -1; let breathSampleUnits = 0, breathSampleSeq = 0, breathSampleCut = 0; function cutBreathBudget() { const left = typeof userExports.__hwjs_budget_get === "function" ? userExports.__hwjs_budget_get() | 0 : 0; if (left > 0 && breathCutLeft < 0) breathCutLeft = left; userExports.__hwjs_budget_set(0); setModuleBudgets(0); if (preemptI32 !== null) Atomics.store(preemptI32, preemptIdx, 1); breathCutSeq++; } let schedYieldEnded = 0, schedYieldInPlace = 0; function schedYield() { if (!breathDispatchActive && userExports && typeof userExports.__hwjs_budget_set === "function") { if (HWJS_SCHED_YIELD_ALWAYS || laneOthersRunnable(laneRec)) { cutBreathBudget(); if (HWJS_BREATH_CENSUS) schedYieldEnded++; } else if (HWJS_BREATH_CENSUS) schedYieldInPlace++; } return 0; } function aloneBreathRefill(nowMs2) { return breathRefillFor( breathCostHi > breathCostPrev ? breathCostHi : breathCostPrev, othersSliceHorizonIn( laneResidents, laneRec, nowMs2, BREATH_TARGET_MS, BREATH_SHARE_FRAC, HWJS_BREATH_BESIDE ), HWJS_SP_REFILL, HWJS_SP_REFILL_MAX ); } const driveImport = (n, f) => driveEntryImport( n, f, () => refillExpiredBudgets(moduleBudgetGlobals, userExports, HWJS_SP_REFILL) ); const terminusHook = (rtFn) => terminusHookImport(() => userExports, rtFn); let libcCtorsDeferred = false; const setLibcTlsBase = (v) => { if (!libcSoHandle) return; const g = (libcSoHandle.instance ?? libcSoHandle).exports.__tls_base; if (!(g instanceof WebAssembly.Global)) { throw new Error( "hwjs-libc: libc.so does not export the mutable __tls_base global the S2 \xA73.3 dual-write contract requires (producer must link --export=__tls_base; never-silent)." ); } g.value = v | 0; }; let hwjsSliceProgressed = false; let hwjsDrive = false; let hwjsFlat = false; let libcParksAnySyscall = false; let libcParkAbiPushed = false; let libcResumesMmap = false; const coopParkCapableFor = (nr) => !!sched || init.mode === "thread" && init.rtThread === true && hwjsDrive && hwjsFlat || (nr | 0) === SYS_SCHED_SETAFFINITY && libcParksAnySyscall && hwjsDrive && hwjsFlat; const blockParkGoesToGuest = (nr) => coopParkCapableFor(nr) && (libcParksAnySyscall || HWJS_CANCELLABLE_SYSCALLS.has(nr | 0)); let flatCensusEmit = null; let hwjsForkLatched = false; let hwjsVforkLatched = null; let hwjsExecLatched = false; let stwCtl = null; let currentTcb = 0; const preMainLoadOpts = () => ({ ...mainManifestDriveAbi === 3 || mainManifestDriveAbi === 4 ? { mainDriveAbi: mainManifestDriveAbi } : {}, ...threadCtx ? { statusChannelGlobal: threadCtx.chanGlobal } : { statusChannelAddr: currentTcb ? currentTcb >>> 0 : void 0 } }); let currentMainTlsBase = 0; let tcbLayout = null; let runtimeExports = null; const threadTlsAlloc = (size, align) => { if (!runtimeExports || typeof runtimeExports.__hwjs_thread_tls_alloc !== "function") return 0; const alloc = () => runtimeExports.__hwjs_thread_tls_alloc(size >>> 0, align >>> 0) >>> 0; return threadCtx ? threadCtxCall(threadCtx, threadRec, alloc) : alloc(); }; let threadSideTlsUnbound = false; const adoptSideTls = (handle, what, late) => { if (!handle || !handle.tls) return; const block = threadCtxCall(threadCtx, threadRec, () => materialiseSideModuleTls(handle, threadTlsAlloc, what)); if (block !== 0) return; if (late) { throw new Error(`hwjs-thread-image: this thread's TLS arena could not grow for "${what}", which another thread of the process loaded \u2014 its thread_local state has nowhere to live (never-silent).`); } threadSideTlsUnbound = true; }; const tcbFieldAddr = (name2) => currentTcb && tcbLayout ? currentTcb + tcbLayout[name2] >>> 0 : 0; function stwHoldSyncIfRequested() { if (!stwCtl) return; const c = stwCtl; if ((Atomics.load(uI32(), c.stwIdx) | 0) !== 0) { try { post({ kind: "dmesg", level: 7, text: `hwjs-fork-stw pid=${ctrl[C.PID] | 0} block=0x${(c.tcb >>> 0).toString(16)}: in-syscall HOLD entered (gen=${Atomics.load(uI32(), c.stwIdx) | 0})` }); } catch (_e) { } } let held = false; let holdT0 = 0; for (; ; ) { const g = Atomics.load(uI32(), c.stwIdx) | 0; if (g === 0) break; if (!held) { held = true; holdT0 = Date.now(); } Atomics.store(uI32(), c.ackIdx, g); Atomics.wait(uI32(), c.stwIdx, g, 250); if (Date.now() - holdT0 > 1e4) { holdT0 = Date.now(); const msg = `hwjs-fork-stw pid=${ctrl[C.PID] | 0} block=0x${(c.tcb >>> 0).toString(16)}: held at an in-syscall quiesce point for >10s under generation ${Atomics.load(uI32(), c.stwIdx) | 0} \u2014 the forking lane's servicer has not released; still holding (loud witness, never a silent wedge)`; try { post({ kind: "dmesg", level: 3, text: msg }); } catch (_e) { } try { console.error(msg); } catch (_e) { } } } if (held) Atomics.store(uI32(), c.ackIdx, 0); } const HWJS_PARK_NONE = 0, HWJS_PARK_FORK = 1, HWJS_PARK_EXEC = 2; const HWJS_PARK_DLOPEN = 3; const HWJS_PARK_RESCHED = 4; const HWJS_PARK_THREAD_EXIT = 5; const HWJS_RESCHED_RESTART_CAP = 1e5; const dlopenModules = new XmodInputMap(); let dlopenNextCookie = 1; const placementCell = init.placementCell instanceof SharedArrayBuffer ? new Int32Array(init.placementCell, 0, 6) : null; const PC_GEN = 0, PC_LOCK = 1, PC_THREADS = 2, PC_TLEN = 3, PC_COOKIE = 4, PC_IMAGE = 5; const dlopenCookieAlloc = placementCell ? makeCellTableAllocator(placementCell, PC_COOKIE) : null; let placementApplied = 0; let placementPullFails = 0; const placementOwnGens = /* @__PURE__ */ new Set(); const placementShipped = /* @__PURE__ */ new Set(); const xmodConsultClasses = /* @__PURE__ */ new Map(); const xmodConsultIdBase = xmodConsultOwner(); const dlopenDeadRanges = []; let sharedTable = null; let sharedTableInitial = 0; let dlopenGotFuncIndex = null; let dlopenMainScopeIndex = null; let fpcastProcessRecs = new XmodInputMap(); let capsummaryProcessRecs = createCapsummaryRegistry(); function leaveThreadImage(abnormal = false) { if (!threadCtx) return false; const imageGone = !!placementCell && (Atomics.load(placementCell, PC_IMAGE) | 0) !== (threadCtx.imageEpoch | 0); threadCtxLeave(init.memoryId, threadCtx, threadRec, abnormal || imageGone); return true; } function releaseProcessRunState(why) { wasmJitRelease(); if (leaveThreadImage(why === "error" || why === "thread refused" || why === "reaped")) return; try { if (dlopenModules.size > 0 && D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 7, text: `hwjs-70 pid=${init.pid} RELEASE(${why}): dropping ${dlopenModules.size} dlopen handle(s) + per-process dlopen state at process end` }); } catch (_e) { } } dlopenModules.clear(); dlopenDeadRanges.length = 0; xmodConsultInvalidate(); dlopenGotFuncIndex = null; dlopenMainScopeIndex = null; fpcastProcessRecs = new XmodInputMap(); capsummaryProcessRecs = createCapsummaryRegistry(); sharedTable = null; userExports = null; hwjsRtInstance = null; hwjsRtPlacement = null; hwjsRtHandle = null; hwjsRtStackPointer = null; hwjsLaneBudget = null; } catch (_e) { } } let execPendingPath = null; let execPendingPathPtr = 0; let execPendingArgv = null; let execPendingEnvp = null; let execResumeResult = 0; let execInlineReinstantiateBytes = null; const execImageLoader = makeExecImageLoader({ getExports: () => vmlinuxInstance.exports, getLane: () => hwjsLane, post }); const execWindowOpen = () => execImageLoader.phase.phase !== "idle" || execStage.phase !== "idle"; const execLoadKernelChunked = (pathPtr, yieldWouldBlock) => execImageLoader.load(pathPtr, yieldWouldBlock); const coopWaitParkYield = makeParkYieldWithTurn(coopWaitRunnable); const coopFutexParkYield = makeParkYieldWithTurn(coopFutexWait); let dlopenPendingPathPtr = 0; let dlopenLatched = false; let dlopenPendingReissue = false; let dlopenPendingLoaded = false; let dlopenCtorRunners = null; let dlopenLastError = ""; const HWJS_EXEC_VEC_CAP = 4096; const HWJS_EXEC_STR_CAP = 1 << 20; function decodeUserStringVector(vecPtr, label) { const p0 = vecPtr >>> 0; if (p0 === 0) return []; const buf = init.memory.buffer; const u8 = new Uint8Array(buf); const dv = new DataView(buf); const out = []; let p = p0; for (; ; ) { if (out.length > HWJS_EXEC_VEC_CAP) { throw new Error( `d1-fork-exec: ${label} vector exceeds ${HWJS_EXEC_VEC_CAP} entries (no NULL terminator? ptr=0x${p0.toString(16)}) \u2014 refusing (never-silent)` ); } if (p + 4 > u8.length) { throw new Error( `d1-fork-exec: ${label} vector pointer 0x${p.toString(16)} out of bounds (mem ${u8.length}B) \u2014 malformed vector, refusing` ); } const sptr = dv.getUint32(p, true) >>> 0; p += 4; if (sptr === 0) break; if (sptr >= u8.length) { throw new Error( `d1-fork-exec: ${label}[${out.length}] string pointer 0x${sptr.toString(16)} out of bounds (mem ${u8.length}B) \u2014 refusing` ); } let e = sptr; const lim = Math.min(u8.length, sptr + HWJS_EXEC_STR_CAP); while (e < lim && u8[e] !== 0) e++; if (e >= lim && (e >= u8.length || u8[e] !== 0)) { throw new Error( `d1-fork-exec: ${label}[${out.length}] string at 0x${sptr.toString(16)} unterminated within ${HWJS_EXEC_STR_CAP}B \u2014 refusing` ); } out.push(decodeMaybeShared3(u8.subarray(sptr, e))); } return out; } function buildDlopenForkRecord() { const dlopenReplay = []; const mainScope = []; for (const [cookie, m] of dlopenModules) { if (m && m.mainScope) { mainScope.push(cookie >>> 0); continue; } if (!m || !m.bytes) continue; dlopenReplay.push({ cookie: cookie >>> 0, moduleId: m.moduleId | 0, memoryBase: m.memoryBase >>> 0, tableBase: m.tableBase >>> 0, /* #43: the dylink elem window extent + the named appended slots * ([name, index]: dlsym + GOT.func.) — the module's placement. */ tableSize: m.handle && m.handle.dylink ? m.handle.dylink.tableSize >>> 0 : 0, appended: m.handle && typeof m.handle.tableEntries === "function" ? m.handle.tableEntries() : [], path: m.path || "", bytes: m.bytes, /* `module`: a library taken from the shared-lib store. Its bytes may * be the retained copy, so the Module travels with them (a handle on * compiled code the realms share, not a copy of it). */ ...m.internal ? { internal: true, name: m.name, digest: m.digest, ...m.module ? { module: m.module } : {} } : {}, ...m.boundByDependent ? { boundByDependent: true } : {}, /* hardwarejs#67: the guest opens the child inherits with the handle. */ ...m.refs !== void 0 ? { refs: m.refs >>> 0 } : {}, /* M2 dlclose census: the parent's live-frame count per cookie seeds * the child's counter (delta=0 copies the frames byte-identically; * replayForkDlopens consumes these). */ live: m.census ? m.census.live >>> 0 : 0, poisoned: m.census ? !!m.census.poisoned : false, /* F152: the parent's registration census seeds the child's (the * replay never re-runs ctors). */ xmodRecs: m.xmodRecs ? [...m.xmodRecs] : [], /* hwjs-cc#106 side-module TLS: the base THIS task's Instance is * using (the next Instance of the same thread — a fork child, a * migrated task — must bind exactly it), and the module's per-thread * slot array (a new thread materialises its own slot there). A * thread-spawn record carries the cloning task's base too; the * thread arm ignores it. */ ...sideTlsRecordFields(m.handle) }); } dlopenReplay.sort((a, b) => a.cookie - b.cookie); const mainScopeNames = dlopenMainScopeIndex instanceof Map ? [...dlopenMainScopeIndex] : []; return dlopenReplay.length || dlopenDeadRanges.length || mainScope.length || mainScopeNames.length || hwjsRtPlacement || libcSoPlacement || neededPlacements.length || fpcastProcessRecs.size || capsummaryProcessRecs.size ? { replay: dlopenReplay, /* dlopen(NULL) handles and every slot they handed out: the child has no * module to replay for them, so it re-creates the handles and re-binds * the slots (a pointer resolved before fork is called after it). */ mainScope, mainScopeNames, /* The per-process fpcast registration census (table index -> own-sig * hash) — fork/thread children consult the SAME table layout the * delta copy / live memory preserves, so the parent's census is * exactly theirs at spawn time. */ fpcastRecs: [...fpcastProcessRecs], /* The capsummary registry, as plain words so all 64 mask bits survive * structured clone (see capsummaryProcessRecs). */ capsummaryRecs: capsummaryProcessRecs.snapshot(), /* #43: the tombstoned footprints — the child's #52 census must see * the SAME holes (a stale open-world dispatch refuses attributedly * in the child exactly as in the parent). */ deadRanges: dlopenDeadRanges.map((d) => ({ tableBase: d.tableBase >>> 0, tableSize: d.tableSize >>> 0, appended: Array.isArray(d.appended) ? [...d.appended] : [], path: d.path || "", moduleId: d.moduleId | 0 })), /* #43: the process-wide GOT.func append cache (name -> shared-table * index of an APPENDED main function) — placement-seeded so two * post-fork .so's keep the parent's identities. */ gotFunc: dlopenGotFuncIndex instanceof Map ? [...dlopenGotFuncIndex] : [], /* A sibling's handle in the copied memory may name a library this thread * has not applied, so the child starts past the process's count. */ nextCookie: Math.max( dlopenNextCookie >>> 0, placementCell ? Atomics.load(placementCell, PC_COOKIE) >>> 0 : 0 ), /* hardwarejs#115: the journal generation this layout includes. */ placementGen: placementApplied, tableLen: sharedTable instanceof WebAssembly.Table ? sharedTable.length >>> 0 : 0, /* The kernel-provided runtime's reserved window — the consumer's * preamble re-instantiates rt FIRST at these exact bases (module #0; * state rides the delta copy / the live shared memory, no ctors * re-run). */ ...hwjsRtPlacement ? { hwjsRt: { ...hwjsRtPlacement, /* Slots a dlsym appended after the record was taken: the main's * GOT.func of a runtime op (__hwjs_user_park) is minted here, after * rt's placement. */ late: hwjsRtHandle ? lateTableEntries( hwjsRtHandle.tableEntries(), hwjsRtPlacement.appended ) : [] } } : {}, /* libc.so's placement record (module #1) — digest + bases * ONLY, never bytes (the D4 fork rule: a bash fork storm — and a * thread-spawn storm — must not clone MBs; the consumer * re-instantiates from its worker-init shared-lib store). Replay * order in the consumer is rt → libc.so → dlopen'd .so's (the * preamble replays #0 then #1; replayForkDlopens runs after the * main instantiates). */ ...libcSoPlacement ? { libcSo: { ...libcSoPlacement, /* Slots a dlsym appended after the record was taken: the child * adopts them in replayForkDlopens, once its table is full length. */ late: libcSoHandle ? lateTableEntries( libcSoHandle.tableEntries(), libcSoPlacement.appended ) : [] } } : {}, /* The needed-graph tail (modules #2..#N), same rule as libcSo: digest + * bases only, replayed by NAME in the consumer's preamble right after * libc.so and BEFORE the main, because the main's imports bind from * them. */ ...neededPlacements.length ? { neededLibs: neededPlacements.map((r) => ({ ...r, late: lateNeededEntries(r), /* A fork, thread or move names the library where its execve found it. */ ...libraryReadPath(r.digest) ? { knownPath: libraryReadPath(r.digest) } : {}, /* The base THIS task is using, read live like a dlopen record's. */ ...sideTlsRecordFields( (neededSoHandles.find((h) => h.index === r.index) || {}).handle ) })) } : {}, /* The needed-ctor trampolines crt1 may still be walking: a fork from a * constructor, or a move at a constructor's park, resumes that walk * over the destination's table. */ ...neededCtorTrampolines.length ? { neededCtorTrampolines: neededCtorTrampolines.map((r) => ({ ...r })) } : {} } : null; } async function requestVforkChild(vreq) { if (hostTerminal) return -11; if (dlPlacementBehind()) await dlPlacementCatchUp(); const tlsBase = (() => { if (libcSoHandle) { const g = (libcSoHandle.instance ?? libcSoHandle).exports.__tls_base; if (g instanceof WebAssembly.Global) return g.value >>> 0; } return userExports && typeof userExports.__wasm32_get_tls_base === "function" ? userExports.__wasm32_get_tls_base() >>> 0 : 0; })(); const dlopenFork = buildDlopenForkRecord(); const lowFdRoutes = [...kernelRoutedLowFds]; Atomics.store( ctrl, C.NR, 56 /* SYS_clone */ ); Atomics.store(ctrl, C.STATE, REQUEST); post({ kind: "vfork", pid: ctrl[C.PID] | 0, flags: vreq.flags, stack: vreq.stack, fn: vreq.fn, arg: vreq.arg, tlsBase, ...currentMainTlsBase ? { mainTlsBase: currentMainTlsBase >>> 0 } : {}, ...lowFdRoutes.length ? { lowFdRoutes } : {}, ...dlopenFork ? { dlopenFork } : {} }); while (Atomics.load(ctrl, C.STATE) !== RESPONSE) { if (init.reapedBy) throw HWJS_TASK_REAPED; const w = Atomics.waitAsync(ctrl, C.STATE, REQUEST, 5e3); if (w.async) { try { await w.value; } catch (_e) { } } } const r = ctrl[C.RET_LO] | 0; Atomics.store(ctrl, C.STATE, IDLE); return r; } async function requestForkChild(extra) { if (hostTerminal) { throw new Error( `fork after this task reported a terminal error to the host (pid=${ctrl[C.PID] | 0} tid=${init.tid | 0}): the host has stopped routing its messages, so the request would never be answered` ); } if (dlPlacementBehind()) await dlPlacementCatchUp(); Atomics.store(ctrl, C.NR, SYS_FORK | 0); Atomics.store(ctrl, C.STATE, REQUEST); const tlsBase = (() => { if (libcSoHandle) { const g = (libcSoHandle.instance ?? libcSoHandle).exports.__tls_base; if (g instanceof WebAssembly.Global) return g.value >>> 0; } return userExports && typeof userExports.__wasm32_get_tls_base === "function" ? userExports.__wasm32_get_tls_base() >>> 0 : 0; })(); const coro = extra && typeof extra === "object" ? extra : null; const parentSp = coro && userExports && typeof userExports.__wasm32_get_stack_pointer === "function" ? userExports.__wasm32_get_stack_pointer() >>> 0 : 0; const dlopenFork = buildDlopenForkRecord(); const lowFdRoutes = [...kernelRoutedLowFds]; post({ kind: "fork", pid: ctrl[C.PID] | 0, tlsBase, /* Step 7 (fork under threads): the child keeps the CALLER's runtime * block and main-image TLS — ride them to the spawn handler * (init.forkTcb / init.mainTlsBase). */ ...currentTcb ? { tcb: currentTcb >>> 0 } : {}, ...currentMainTlsBase ? { mainTlsBase: currentMainTlsBase >>> 0 } : {}, ...lowFdRoutes.length ? { lowFdRoutes } : {}, ...dlopenFork ? { dlopenFork } : {}, ...(() => { const m = sharedMaps.forkRecord(); return m ? { sharedFileMaps: m } : {}; })(), /* SYS_wasm_jit: the child's copied memory holds every slot number * this image's JIT handed out; its own JIT must start past them, or * its first install got the parent's number and that number ran the * child's code (re-review #8). */ ...(() => { const f = wasmJit.forkFloor(); return f > 0 ? { wasmJitFloor: f } : {}; })(), ...coro ? { parentSp, forkHandle: coro.handle >>> 0, forkOwner: coro.owner >>> 0 } : {} }); while (Atomics.load(ctrl, C.STATE) !== RESPONSE) { if (init.reapedBy) throw HWJS_TASK_REAPED; const w = Atomics.waitAsync(ctrl, C.STATE, REQUEST, 5e3); if (w.async) { try { await w.value; } catch (_e) { } } } const childPid = ctrl[C.RET_LO] | 0; Atomics.store(ctrl, C.STATE, IDLE); return childPid; } const migWord = init.mode === "migrate-resume" && init.mig instanceof SharedArrayBuffer ? new Int32Array(init.mig) : null; const migrateRetag = (srcCpu, destCpu) => { const pid = ctrl[C.PID] | 0; if (typeof srcCpu !== "number") { post({ kind: "user-report", pid, message: `hwjs-migrate pid=${pid}: the add-task carried no source cpu, so this task's live kernel frames keep the source lane's tag and their teardown will trip the cross-lane free guard (skewed host/worker; loud, attributed)` }); return -1; } if (!(vmlinuxInstance && typeof vmlinuxInstance.exports.__hwjs_frame_migrate_lane === "function")) { post({ kind: "user-report", pid, message: `hwjs-migrate pid=${pid}: this vmlinux exports no __hwjs_frame_migrate_lane \u2014 the migration proceeds, but the task's live kernel frames keep the source lane's tag and their teardown will trip the cross-lane free guard (stale kernel; loud, attributed)` }); return -1; } const retagged = vmlinuxInstance.exports.__hwjs_frame_migrate_lane( perProcessTaskAddr >>> 0, srcCpu | 0, destCpu | 0 ) | 0; if (retagged < 0) { post({ kind: "user-report", pid, message: `hwjs-migrate pid=${pid}: arena retag ${srcCpu}->${destCpu} was refused (bad lane index) \u2014 this task's live kernel frames still carry the source lane's tag, so their teardown WILL trip the cross-lane free guard (loud, attributed)` }); } try { post({ kind: "dmesg", level: 6, text: `hwjs-migrate pid=${pid}: arena retag cpu=${srcCpu}->${destCpu} moved ${retagged} live chunk(s) at the destination, before its first drive` }); } catch (_e) { } return retagged; }; const migrateCommit = () => { if (!migWord) return true; return Atomics.compareExchange(migWord, 0, MIG_CLAIMED, MIG_BOUND) === MIG_CLAIMED ? (Atomics.notify(migWord, 0), true) : false; }; async function requestMigrate(destCpu) { const srcCpu = init.cpuId | 0; const pid = ctrl[C.PID] | 0; const migSab = new SharedArrayBuffer(16); const mig = new Int32Array(migSab); Atomics.store(mig, 0, MIG_OFFERED); Atomics.store(mig, 1, destCpu | 0); if (threadCtx && threadCtx.depth === 0) threadCtxEnter(threadCtx, threadRec); const tlsBase = (() => { if (libcSoHandle) { const g = (libcSoHandle.instance ?? libcSoHandle).exports.__tls_base; if (g instanceof WebAssembly.Global) return g.value >>> 0; } return userExports && typeof userExports.__wasm32_get_tls_base === "function" ? userExports.__wasm32_get_tls_base() >>> 0 : 0; })(); const sp = userExports && typeof userExports.__wasm32_get_stack_pointer === "function" ? userExports.__wasm32_get_stack_pointer() >>> 0 : 0; const frames = vmlinuxInstance && typeof vmlinuxInstance.exports.__hwjs_task_frames === "function" ? vmlinuxInstance.exports.__hwjs_task_frames() >>> 0 : 0; post({ kind: "migrate", pid, srcCpu, destCpu: destCpu | 0, mig: migSab, taskAddr: perProcessTaskAddr >>> 0, tcb: currentTcb >>> 0, ...currentMainTlsBase ? { mainTlsBase: currentMainTlsBase >>> 0 } : {}, tlsBase, sp, ...threadSideSpTop && hwjsRtStackPointer ? { sideSp: hwjsRtStackPointer.value >>> 0, sideSpTop: threadSideSpTop } : {}, frames, lowFdRoutes: [...kernelRoutedLowFds], ...(() => { const d = buildDlopenForkRecord(); return d ? { dlopenFork: d } : {}; })(), ...(() => { const m2 = sharedMaps.forkRecord(); return m2 ? { sharedFileMaps: m2 } : {}; })(), /* SYS_wasm_jit: the slots the emulator holds are table indices, and * the destination's Instance starts with the image's initial table — * a region call after the move was out of bounds, a trap that killed * the process (review #2; a guest's sched_setaffinity or an external * taskset -p, which the emulator cannot see). The record rides the * offer: compiled Modules (a Module structured-clones between Workers * of one agent cluster) and their slots, re-placed at the same * indices before the destination commits. The source keeps its own * record until the commit, so a refused move changes nothing. */ ...(() => { const j = wasmJit.migrateOut(); return j ? { wasmJit: j } : {}; })() }); const t0 = Date.now(); for (; ; ) { const s = Atomics.load(mig, 0) | 0; if (s === MIG_BOUND || s === MIG_ABORTED) break; const budget = s === MIG_CLAIMED ? MIG_COMMIT_MS : MIG_PLACE_MS; const left = t0 + budget - Date.now(); if (left <= 0) { migAbort(mig, s === MIG_CLAIMED ? MIG_ABORT_TIMEOUT : MIG_ABORT_UNCLAIMED); break; } const w = Atomics.waitAsync(mig, 0, s, left); if (w.async) { try { await w.value; } catch (_e) { } } } if ((Atomics.load(mig, 0) | 0) === MIG_BOUND) { schedTrace(post, `MIGRATE-OUT cpu=${srcCpu} tid=${init.tid} pid=${pid} -> cpu=${destCpu} tcb=0x${(currentTcb >>> 0).toString(16)} taskFrames=${frames}`); sharedMaps.reset(); return true; } const code2 = Atomics.load(mig, 2) | 0; if (code2 === MIG_ABORT_NO_LANE && vmlinuxInstance && typeof vmlinuxInstance.exports.__wasm32_migrate_refuse === "function") { try { vmlinuxInstance.exports.__wasm32_migrate_refuse(); } catch (_e) { } } const why = code2 === MIG_ABORT_TIMEOUT ? `a lane CLAIMED the task and did not commit within ${MIG_COMMIT_MS} ms \u2014 it stalled or died inside the commit window` : code2 === MIG_ABORT_NO_LANE ? "no live pool Worker holds that cpu" : code2 === MIG_ABORT_UNCLAIMED ? `no lane claimed the offer within ${MIG_PLACE_MS} ms \u2014 the destination lane is starved, or nothing on this machine services migration requests at all` : code2 === MIG_ABORT_BIND ? "the destination refused to bind the task" : code2 === MIG_ABORT_HOST ? "the host refused the placement" : `abort code ${code2}`; const m = `hwjs-migrate pid=${pid} cpu=${srcCpu}: migration to cpu=${destCpu} REFUSED \u2014 ${why}. The task was never released and keeps running here; sched_setaffinity will answer -EAGAIN once its attempt bound is spent (loud, attributed, guest-survivable).`; try { post({ kind: "dmesg", level: 3, text: m }); } catch (_e) { } try { post({ kind: "user-report", pid, message: m }); } catch (_e) { } return false; } function tryGrowUserMemoryTo(minPages) { const cur = Math.floor(init.memory.buffer.byteLength / 65536); if (cur >= minPages) return cur; if (HWJS_TEST_GROW_FAIL_MINPAGES > 0 && minPages >= HWJS_TEST_GROW_FAIL_MINPAGES && hwjsTestGrowFailsLeft > 0) { hwjsTestGrowFailsLeft--; throw new Error( `hardwarejs#7 TEST INJECTION: simulated commit refusal for grow(+${minPages - cur}) (${hwjsTestGrowFailsLeft} injected failure(s) left in this Worker realm)` ); } init.memory.grow(minPages - cur); return minPages; } function requestHostUserMemReclaim(needPages) { const RECLAIM_WAIT_MS = 5e3; const sab = new SharedArrayBuffer(32); const rec = new Int32Array(sab); try { post({ kind: "usermem-reclaim", pid: init.pid, needPages: needPages | 0, sab }); } catch (_e) { return null; } const deadline = Date.now() + RECLAIM_WAIT_MS; while (Atomics.load(rec, 0) === 0 && Date.now() < deadline) { Atomics.wait(rec, 0, 0, Math.max(1, deadline - Date.now())); } if (Atomics.load(rec, 0) !== 1) return null; return { liveCount: rec[1], livePages: rec[2], zombieCount: rec[3], zombiePages: rec[4], recycledWorkers: rec[5], userMaxPages: rec[6], kernelPages: rec[7] }; } function settleWaitMs(ms) { if (!(ms > 0)) return; const cell = new Int32Array(new SharedArrayBuffer(4)); Atomics.wait(cell, 0, 0, ms); } function execImageFormatCheck(bytes, label) { let why; try { why = imageRuntimeRefusal(parseExportedFunctionIndices(bytes)); } catch (e) { why = `the export section does not parse (${e instanceof Error ? e.message : String(e)})`; } if (!why) return 0; try { post({ kind: "user-report", pid: init.pid, message: `hwjs-exec: ${label}: execve(${JSON.stringify(execPendingPath ?? "")}) refused with -ENOEXEC before the point of no return: ${why}` }); } catch (_e) { } return -8; } function ensureUserMemoryFitsImage(bytes, label) { let minPages; try { minPages = parseImportedMemoryMinPages(bytes); } catch (e) { post({ kind: "user-report", pid: init.pid, message: `hardwarejs#6 ${label}: cannot read the exec image's declared memory-import minimum (${e instanceof Error ? e.message : String(e)}) \u2014 refusing exec with -ENOEXEC (never-silent)` }); return -8; } if (minPages === null) return 0; const curPages = Math.floor(init.memory.buffer.byteLength / 65536); if (curPages >= minPages) return 0; const mib2 = (p) => (p * 65536 / (1024 * 1024)).toFixed(1); let firstErr = null; try { tryGrowUserMemoryTo(minPages); } catch (e) { firstErr = e; } if (firstErr === null) { try { post({ kind: "dmesg", level: 6, text: `hwjs exec pid=${ctrl[C.PID] | 0} ${label}: grew user_memory ${curPages} -> ${minPages} pages for the exec image's declared minimum (hardwarejs#6)` }); } catch (_e) { } return 0; } let declaredMaxPages = null; try { if (typeof init.memory.type === "function") { const t = init.memory.type(); if (t && typeof t.maximum === "number") declaredMaxPages = t.maximum >>> 0; } } catch (_e) { } const overCeiling = declaredMaxPages !== null && minPages > declaredMaxPages; let reclaimStats = null; let retried = false; let retryErr = null; let rounds = 0; let recycledTotal = 0; if (!HWJS_NO_RECLAIM_RETRY && !overCeiling) { retried = true; for (let round = 0; round < HWJS_RECLAIM_RETRY_ROUNDS; round++) { rounds++; const st = requestHostUserMemReclaim(minPages - curPages); if (st !== null) { reclaimStats = st; recycledTotal += st.recycledWorkers | 0; } settleWaitMs(HWJS_RECLAIM_SETTLE_MS[Math.min(round, HWJS_RECLAIM_SETTLE_MS.length - 1)]); try { tryGrowUserMemoryTo(minPages); retryErr = null; break; } catch (e) { retryErr = e; } } if (retryErr === null) { try { post({ kind: "dmesg", level: 6, text: `hwjs exec pid=${ctrl[C.PID] | 0} ${label}: grow(+${minPages - curPages}) was refused (${firstErr instanceof Error ? firstErr.message : String(firstErr)}) but succeeded after host reclaim (${rounds} round(s), recycled ${recycledTotal} idle pool Worker(s) total); user_memory ${curPages} -> ${minPages} pages (hardwarejs#7 rescue)` }); } catch (_e) { } return 0; } } const knownMaxPages = declaredMaxPages !== null ? declaredMaxPages : reclaimStats && reclaimStats.userMaxPages > 0 ? reclaimStats.userMaxPages : null; const maxSrc = declaredMaxPages !== null ? "this Memory\u2019s declared maximum" : "the machine default userMaxBytes"; const ceilingVerdict = knownMaxPages !== null ? minPages > knownMaxPages ? `the declared minimum EXCEEDS ${maxSrc} of ${knownMaxPages} pages (${mib2(knownMaxPages)} MiB) \u2014 raising userMaxBytes is the only remedy for THIS image` : `the userMaxBytes ceiling is NOT the limiting factor (${minPages} <= ${knownMaxPages} pages) \u2014 the engine refused to commit the pages` : `the Memory's maximum is not introspectable in this engine; if ${minPages} pages exceeds userMaxBytes that is the cause, otherwise the engine refused to commit the pages`; const reclaimVerdict = !retried ? overCeiling ? `reclaim-retry skipped (pointless below an exceeded ceiling)` : `reclaim-retry DISABLED (HWJS_NO_RECLAIM_RETRY)` : reclaimStats === null ? `host reclaim was requested (${rounds} round(s)) but never answered within the 5s/round cap (no kernelSpawnHandler route?); the blind retries also failed (${retryErr instanceof Error ? retryErr.message : String(retryErr)})` : `host reclaim ran ${rounds} round(s) with settle waits (recycled ${recycledTotal} idle pool Worker(s) total; ledger: ${reclaimStats.liveCount} live process SAB(s) ~${mib2(reclaimStats.livePages)} MiB in size, ${reclaimStats.zombieCount} exited-but-uncollected SAB(s) ~${mib2(reclaimStats.zombiePages)} MiB awaiting GC, kernel SAB ${mib2(reclaimStats.kernelPages)} MiB eagerly committed) and the last retry still failed (${retryErr instanceof Error ? retryErr.message : String(retryErr)})`; post({ kind: "user-report", pid: init.pid, message: `hardwarejs#7 ${label}: exec image declares a ${minPages}-page (${mib2(minPages)} MiB) user_memory minimum but this process's Memory holds ${curPages} pages (${mib2(curPages)} MiB) and grow(+${minPages - curPages}) was refused (${firstErr instanceof Error ? firstErr.message : String(firstErr)}). ${ceilingVerdict}; ${reclaimVerdict}. Failing execve with -ENOMEM (never-silent).` }); return -12; } function readExecShebangPrefix() { const ex = vmlinuxInstance && vmlinuxInstance.exports; if (!ex || typeof ex.wasm32_user_exec_shebang_argc !== "function") { return null; } const argc = ex.wasm32_user_exec_shebang_argc() >>> 0; if (argc === 0) return null; const addr = ex.wasm32_user_exec_shebang_addr() >>> 0; const size = ex.wasm32_user_exec_shebang_size() >>> 0; if (addr === 0 || size === 0) { throw new Error( `#75 shebang: kernel reports argc=${argc} but addr=0x${addr.toString(16)} size=${size} \u2014 kernel/host argv-prefix contract broken (never-silent)` ); } const flags = typeof ex.wasm32_user_exec_shebang_flags === "function" ? ex.wasm32_user_exec_shebang_flags() >>> 0 : 0; const requested = typeof ex.wasm32_user_exec_load_begin === "function" && typeof ex.wasm32_user_exec_load_step === "function" ? EXEC_LOAD_HOST_FLAGS : 0; const bytes = new Uint8Array(size); bytes.set(new Uint8Array(init.kernelMemoryWasm.buffer, addr, size)); return decodeExecArgvPrefix(bytes, argc, flags, requested); } function execOriginDir() { const ex = vmlinuxInstance && vmlinuxInstance.exports; if (ex && typeof ex.wasm32_user_exec_origin_size === "function") { const size = ex.wasm32_user_exec_origin_size() >>> 0; const addr = size ? ex.wasm32_user_exec_origin_addr() >>> 0 : 0; if (!size || !addr) return null; const dir = new TextDecoder().decode( new Uint8Array(init.kernelMemoryWasm.buffer, addr, size).slice() ); return dir.replace(/\/+$/, ""); } return typeof execPendingPath === "string" && execPendingPath ? dirOfPath(execPendingPath) : null; } function applyExecShebangPrefix(prefix) { if (!prefix) return; execPendingArgv = spliceExecArgvPrefix(prefix, execPendingArgv); if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} EXEC-SHEBANG argv respliced (${prefix.keepArgv0 ? "argv[0] kept" : "argv[0] replaced"}): [${execPendingArgv.map((s) => JSON.stringify(s)).join(",")}]` }); } catch (_e) { } } } function driveWholeFileRead(what, nr, issue, bareCall, latch, chain, yieldWouldBlock = false) { const exp = vmlinuxInstance ? vmlinuxInstance.exports : null; if (latch.v !== false && hwjsLane && exp && typeof exp.wasm_syscall === "function") { for (; ; ) { let r; try { r = hwjsLane.driveWouldBlock(`wasm_syscall:${nr}`, issue, chain); } catch (e) { chain.h = 0; chain.owner = 0; throw e; } if (r.wouldBlock) { latch.v = true; if (yieldWouldBlock) return HWJS_ERESTART_RESCHED; continue; } if (r.value !== -38) { latch.v = true; return r.value | 0; } if (latch.v === null) { latch.v = false; try { post({ kind: "dmesg", level: 6, text: `hwjs-${what}: this vmlinux answers no ${nr}; driving ${what} through the bare export, which holds the kernel lane across the whole file and gets no park preservation. Never-silent.` }); } catch (_e) { } break; } return -38; } } return bareCall() | 0; } const libcStageRoute = { v: null }; const dlopenLoadRoute = { v: null }; const libcStageChain = { h: 0, owner: 0 }; const dlopenLoadChain = { h: 0, owner: 0 }; const libcStagePark = { name: null }; let libPathStage = null; const dlopenLoadPark = { path: null, orphan: false }; let dlopenPending = null; let preloadStage = null; let execPreloads = null; function servicePreloadStage(imageBytes, mainNeeded, context, yieldWouldBlock) { let s = preloadStage; if (!s || s.image !== imageBytes) { if (s) preloadStageDrop(); execPreloads = null; const items = ldPreloadEntries(execPendingEnvp); if (items.length === 0) return void 0; s = preloadStage = { image: imageBytes, items, i: 0, cand: 0, scratch: 0, scratchFor: "", staged: [], needs: /* @__PURE__ */ new Map(), cur: null, fetching: null, done: false, restart: false }; } if (s.done) return void 0; const exp = vmlinuxInstance ? vmlinuxInstance.exports : null; const ignore = (item, why) => { const message = `ERROR: ld.so: object '${item}' from LD_PRELOAD cannot be preloaded (${why}): ignored.`; if (s.scratch) { try { const enc2 = new TextEncoder().encode(`${message} `).subarray(0, 4096); new Uint8Array(init.memory.buffer).set(enc2, s.scratch); s.scratchFor = ""; syscall(1, 2, s.scratch, enc2.length, 0, 0, 0); } catch (_e) { } } try { post({ kind: "user-report", pid: init.pid, message }); } catch (_e) { } try { post({ kind: "dmesg", level: 4, text: `hwjs-preload: pid=${ctrl[C.PID] | 0} ${message} [${context}]` }); } catch (_e) { } }; const stageFirst = (cands) => { let rc = -2; let path = ""; for (; s.cand < cands.length; s.cand++) { path = cands[s.cand]; const enc2 = new TextEncoder().encode(path); if (enc2.length >= 4096) { rc = -36; break; } if (s.scratchFor !== path) { const u8 = new Uint8Array(init.memory.buffer); u8.set(enc2, s.scratch); u8[s.scratch + enc2.length] = 0; s.scratchFor = path; } rc = dlopenStagingRead(s.scratch, path, yieldWouldBlock, s.restart); s.restart = false; if (rc === HWJS_ERESTART_RESCHED) return rc; if (rc === HWJS_ERESTARTNOINTR) { s.restart = true; return rc; } if (rc === -2 && s.cand + 1 < cands.length) continue; break; } s.cand = 0; if (rc < 0) return rc; const bytes = readKernelStagedImage( exp, init.kernelMemoryWasm.buffer, "wasm32_user_dlopen", `LD_PRELOAD "${path}"` ); const releaseCall = () => { exp.wasm32_user_dlopen_release(); return 0; }; if (hwjsLane) hwjsLane.bracket("wasm32_user_dlopen_release", releaseCall); else releaseCall(); return { bytes, path }; }; const store = (bytes, digest, path) => { if (path) dladdrKnownPaths.set(digest, path); if (workerSharedLibs.has(digest)) return; const r = compileSoModule(bytes, digest); const walkStop = {}; const kept = retainedLibraryBytes2(bytes, digest, walkStop); const walked = walkStop.verdict ?? "none"; const where = path ? { path } : {}; sharedLibsMerge([{ digest, bytes: kept, module: r.module, ...where }], post); try { post({ kind: "libc-so-staged", digest, bytes: kept, module: r.module, ...where }); } catch (_e) { } if (walked !== "none") { try { post({ kind: "dmesg", level: 5, text: `hwjs-preload: ${path} code walk: ${walked} (${walkStop.op ?? "?"} at byte ${walkStop.at ?? "?"}); its loads find table slots by reading the whole table, not from the table's index (slower, not wrong) (once per boot per digest)` }); } catch (_e) { } } }; if (!s.scratch) { const canStage = !!(exp && typeof exp.wasm32_user_dlopen_load === "function" && init.kernelMemoryWasm); const a = canStage ? syscall( 9, 0, 4096, 3, 34, -1, 0 ) | 0 : -38; if (a <= 0) { for (const item of s.items) { ignore(item, canStage ? `no page for the path: ${a}` : "no dlopen staging on this kernel"); } s.done = true; return void 0; } s.scratch = a >>> 0; } const mainDigests = new Set(mainNeeded.map((n) => neededDigest(n))); for (; s.i < s.items.length; s.i++) { const item = s.items[s.i]; if (!s.cur) { const got = stageFirst(ldPreloadCandidates(item)); if (isRestartValue(got)) return got; if (typeof got === "number") { ignore(item, got === -2 ? "cannot open shared object file" : got === -8 ? "not a shared object" : `cannot read shared object file: ${got}`); continue; } const { bytes, path } = got; const digest = sha256Hex(bytes); const no = ldPreloadRefusal(bytes, digest, mainNeeded); if (no) { if (!no.already) ignore(item, no.reason); continue; } if (s.staged.some((p) => p.digest === digest)) continue; const needs = ldPreloadNeeds(bytes, mainNeeded); s.cur = { bytes, digest, path, needs, got: /* @__PURE__ */ new Map(), queue: needs.map((n) => ({ name: n, by: path })) }; } const c = s.cur; let why = null; while (c.queue.length) { const { name: name3, by } = c.queue[0]; const digest = neededDigest(name3); if (mainDigests.has(digest) || c.got.has(name3) || s.needs.has(name3) || s.staged.some((p) => p.digest === digest) || digest === c.digest) { c.queue.shift(); continue; } let bytes, path, fromStore = false; const stored = s.fetching === name3 ? null : workerSharedLibs.get(digest); if (stored && stored.bytes) { fromStore = true; bytes = stored.bytes instanceof Uint8Array ? stored.bytes : new Uint8Array(stored.bytes); path = `/usr/lib/${name3}`; const kept = retainedLibraryInfo2(bytes); if ((kept ? kept.digest : sha256Hex(bytes)) !== digest) { why = `${by} needs ${neededSoname(name3)}, but the copy this process holds does not hash to its digest`; break; } } else { const got = stageFirst([`/usr/lib/${name3}`, `/lib/${name3}`]); s.fetching = isRestartValue(got) ? name3 : null; if (isRestartValue(got)) return got; if (typeof got === "number") { why = got === -2 ? `${by} needs ${neededSoname(name3)}, which is in neither /usr/lib nor /lib` : `${by} needs ${neededSoname(name3)}; reading it returned ${got}`; break; } ({ bytes, path } = got); if (sha256Hex(bytes) !== digest) { why = `${by} needs ${neededSoname(name3)}, but ${path} does not hash to its digest`; break; } let side = null; try { side = parseDylink0(bytes); } catch (_e) { side = null; } if (!side) { why = `${by} needs ${neededSoname(name3)}, but ${path} is not a shared object`; break; } } let needs; try { needs = parseSideModuleNeeded(bytes); } catch (e) { why = `${by} needs ${neededSoname(name3)}, but ${path}: ${e instanceof Error ? e.message : e}`; break; } c.got.set(name3, { bytes, digest, path, needs, fromStore }); c.queue.shift(); for (const n of needs) c.queue.push({ name: n, by: path }); } s.cur = null; if (why) { ignore(item, why); continue; } store(c.bytes, c.digest, c.path); for (const [name3, g] of c.got) { if (!g.fromStore) store(g.bytes, g.digest, g.path); s.needs.set(name3, g.needs); try { post({ kind: "dmesg", level: 6, text: `hwjs-preload: pid=${ctrl[C.PID] | 0} staged ${g.path}, needed by LD_PRELOAD "${c.path}" (digest ${g.digest.slice(0, 16)}\u2026) [${context}]` }); } catch (_e) { } } const soname = c.path.slice(c.path.lastIndexOf("/") + 1); const name2 = `${soname}.${c.digest}`; s.needs.set(name2, c.needs); s.staged.push({ name: name2, soname, digest: c.digest, path: c.path }); try { post({ kind: "dmesg", level: 6, text: `hwjs-preload: pid=${ctrl[C.PID] | 0} staged LD_PRELOAD "${c.path}" (digest ${c.digest.slice(0, 16)}\u2026, ${c.bytes.length}B) [${context}]` }); } catch (_e) { } } s.done = true; const deps = ldPreloadDependencies(s.staged, mainNeeded, (n) => s.needs.get(n)).map((n) => ({ name: n, soname: neededSoname(n), digest: neededDigest(n), dep: true })); execPreloads = [...s.staged, ...deps]; preloadStageDrop(); preloadStage = s; return void 0; } function preloadStageDrop() { const s = preloadStage; preloadStage = null; if (s && s.scratch) { try { syscallInner(11, s.scratch, 4096, 0, 0, 0, 0); } catch (_e) { } s.scratch = 0; } } function serviceLibcStageForExecImage(imageBytes, context, yieldWouldBlock = false) { const info = parseWasmLinuxNeeded(imageBytes); if (!info || info.needed.length === 0) return; if (libPathStage && libPathStage.image === imageBytes) { return finishNeededStage( imageBytes, libPathStage.name, libPathStage.index, libPathStage.kernelRc, context, yieldWouldBlock ); } let name2 = libcStagePark.name; if (name2 === null) { const pending2 = info.needed.filter((n, i) => { if (workerSharedLibs.has(neededDigest(n))) return false; const sub = info.bySoname && info.bySoname[i] ? neededSubstitutes.get(n) : void 0; return !(sub && workerSharedLibs.has(sub)); }); if (pending2.length === 0) { return servicePreloadStage(imageBytes, info.needed, context, yieldWouldBlock); } name2 = pending2[0]; } const index = info.needed.indexOf(name2); const digest = neededDigest(name2); const exp = vmlinuxInstance ? vmlinuxInstance.exports : null; if (!exp || typeof exp.wasm32_user_libc_stage !== "function" || !init.kernelMemoryWasm) { try { post({ kind: "user-report", pid: init.pid, message: `hwjs-libc: image needs libc.so.${digest.slice(0, 16)}\u2026 but this kernel exports no wasm32_user_libc_stage (a vmlinux without the libc-stage ops) \u2014 the exec preamble will refuse the image (never-silent) [${context}]` }); } catch (_e) { } return; } const byIndex = typeof exp.wasm32_user_needed_stage === "function"; if (!byIndex && index > 0) { try { post({ kind: "user-report", pid: init.pid, message: `hwjs-libc: the image needs ${name2.slice(0, 24)}\u2026 (needed entry ${index}) but this kernel exports no wasm32_user_needed_stage \u2014 a vmlinux without the needed-graph ops can stage entry 0 only; the exec preamble will refuse the image (never-silent) [${context}]` }); } catch (_e) { } return; } const nr = byIndex ? SYS_WASM_NEEDED_STAGE : SYS_WASM_LIBC_STAGE; const opName = byIndex ? "wasm32_user_needed_stage" : "wasm32_user_libc_stage"; const stageCall = () => byIndex ? exp.wasm32_user_needed_stage(Math.max(index, 0) >>> 0, 1) | 0 : exp.wasm32_user_libc_stage(1) | 0; let rc; try { rc = driveWholeFileRead( "libc-stage", nr, () => byIndex ? exp.wasm_syscall(nr, Math.max(index, 0) >>> 0, 1, 0, 0, 0, 0) | 0 : exp.wasm_syscall(nr, 1, 0, 0, 0, 0, 0) | 0, () => hwjsLane ? hwjsLane.bracket(opName, stageCall) : stageCall(), libcStageRoute, libcStageChain, yieldWouldBlock ) | 0; } catch (e) { libcStagePark.name = null; throw e; } libcStagePark.name = rc === HWJS_ERESTART_RESCHED || rc === HWJS_ERESTARTNOINTR ? name2 : null; if (rc === HWJS_ERESTART_RESCHED) return HWJS_ERESTART_RESCHED; if (rc === HWJS_ERESTARTNOINTR) return HWJS_ERESTARTNOINTR; if (rc < 0) { return finishNeededStage( imageBytes, name2, index, rc, context, yieldWouldBlock ); } if (rc !== 2) { throw new Error( `hwjs-libc: kernel NEEDED_STAGE(${index}, force=1) returned ${rc}, want 2 (staged) \u2014 kernel/host protocol skew (${context}; never-silent).` ); } const bytes = readKernelStagedImage( exp, init.kernelMemoryWasm.buffer, "wasm32_user_libc", `staged ${name2.slice(0, 24)}\u2026 (${context})`, true /* a buffer of its own */ ); const size = bytes.length; const dOff = exp.wasm32_user_libc_digest_addr() >>> 0; const kd = new Uint8Array(64); kd.set(new Uint8Array(init.kernelMemoryWasm.buffer, dOff, 64)); const kernelDigest = decodeMaybeShared3(kd); let kernelName = null; if (typeof exp.wasm32_user_libc_name_addr === "function") { const nOff = exp.wasm32_user_libc_name_addr() >>> 0; if (nOff) { const mem = new Uint8Array(init.kernelMemoryWasm.buffer); let end = nOff; while (end < mem.length && mem[end] !== 0) end++; kernelName = decodeMaybeShared3(mem.slice(nOff, end)); } } const releaseCall = () => { exp.wasm32_user_libc_release(); return 0; }; if (hwjsLane) hwjsLane.bracket("wasm32_user_libc_release", releaseCall); else releaseCall(); if (kernelDigest !== digest) { throw new Error( `hwjs-libc: kernel staged digest ${kernelDigest.slice(0, 16)}\u2026 but needed entry ${index} (${name2.slice(0, 24)}\u2026) wants ${digest.slice(0, 16)}\u2026 \u2014 needed-list parser skew between kernel and host (never-silent).` ); } if (kernelName !== null && kernelName !== name2) { throw new Error( `hwjs-libc: kernel staged ${JSON.stringify(kernelName.slice(0, 32))} for needed index ${index}, but the host's entry ${index} is ${JSON.stringify(name2.slice(0, 32))} \u2014 the two parsers disagree about what this index names (never-silent).` ); } if (workerSharedLibs.has(digest)) { if (typeof bytes.buffer.transfer === "function") bytes.buffer.transfer(0); try { post({ kind: "dmesg", level: 6, text: `hwjs-libc: ${name2.slice(0, 24)}\u2026 (needed entry ${index}) reached the store while this task's own read of it was parked; the read was finished and released, and its ${size}B dropped (${context})` }); } catch (_e) { } return serviceLibcStageForExecImage(imageBytes, context, yieldWouldBlock); } const got = sha256Hex(bytes); let storeDigest = digest; if (got !== digest) { if (!(index > 0 && info.bySoname && info.bySoname[index])) { throw new Error( `hwjs-libc: CONTENT SKEW \u2014 ${name2.slice(0, 24)}\u2026 on the needed search path hashes to ${got.slice(0, 16)}\u2026 (${size}B); the digest-qualified name lies about its content. Refusing delivery (never-silent).` ); } neededSubstitutes.set(name2, got); try { if (!neededSurfaces.has(got)) neededSurfaces.set(got, neededViewSurface(bytes)); } catch (_e) { } try { post({ kind: "dmesg", level: 6, text: `hwjs-libc: ${neededSoname(name2)} (needed entry ${index}) was staged by soname: ${got.slice(0, 16)}\u2026, not the ${digest.slice(0, 16)}\u2026 the image was linked against (${context})` }); } catch (_e) { } if (workerSharedLibs.has(got)) { if (typeof bytes.buffer.transfer === "function") bytes.buffer.transfer(0); return serviceLibcStageForExecImage(imageBytes, context, yieldWouldBlock); } storeDigest = got; } storeNeededLibrary( bytes, storeDigest, name2, index, `kernel ${byIndex ? "NEEDED_STAGE" : "LIBC_STAGE"}`, context ); return serviceLibcStageForExecImage(imageBytes, context, yieldWouldBlock); } function storeNeededLibrary(bytes, digest, name2, index, via, context, path) { const size = bytes.length; const r = compileSoModule(bytes, digest); const walkStop = {}; const kept = retainedLibraryBytes2(bytes, digest, walkStop); const walked = walkStop.verdict ?? "none"; if (typeof bytes.buffer.transfer === "function") bytes.buffer.transfer(0); const where = path ? { path } : {}; sharedLibsMerge([{ digest, bytes: kept, module: r.module, ...where }], post); try { post({ kind: "libc-so-staged", digest, bytes: kept, module: r.module, ...where }); } catch (_e) { } try { post({ kind: "dmesg", level: 6, text: `hwjs-libc: staged ${name2.slice(0, 24)}\u2026 (needed entry ${index}, ${size}B, compile ${r.cached ? "HIT" : "FRESH"}, ${kept.length}B kept) via ${via} (${context}; once per boot per digest)` }); } catch (_e) { } if (walked !== "none") { try { post({ kind: "dmesg", level: 5, text: `hwjs-libc: ${name2.slice(0, 24)}\u2026 code walk: ${walked} (${walkStop.op ?? "?"} at byte ${walkStop.at ?? "?"}); its loads find table slots by reading the whole table, not from the table's index (slower, not wrong) (once per boot per digest)` }); } catch (_e) { } } } function finishNeededStage(imageBytes, name2, index, kernelRc, context, yieldWouldBlock) { let found = { errno: kernelRc, mismatched: [], tried: 0 }; if (kernelRc === -2 || kernelRc === -80) { found = serviceLibraryPathStage( imageBytes, name2, index, kernelRc, context, yieldWouldBlock ); if (typeof found === "number") return found; if (found === true) { return serviceLibcStageForExecImage(imageBytes, context, yieldWouldBlock); } } writeNeededLoadError(name2, kernelRc, found.mismatched); throw Object.assign(new Error( `hwjs-libc: kernel NEEDED_STAGE for ${name2.slice(0, 24)}\u2026 (entry ${index}) failed rc=${kernelRc} (${context}) \u2014 not found on the needed search path (/lib, /usr/lib, /usr/local/lib) with the bytes it was linked against, or over the staging ceiling; LD_LIBRARY_PATH and run path: ${found.tried} file(s) tried, ${found.mismatched.length} with other bytes (never-silent).` ), { errno: found.errno }); } function serviceLibraryPathStage(imageBytes, name2, index, kernelRc, context, yieldWouldBlock) { let s = libPathStage; if (!s || s.image !== imageBytes || s.name !== name2) { libPathStageDrop(); const envDirs = ldLibraryPathDirs(execPendingEnvp); const runpath = (parseWasmLinuxNeeded(imageBytes) || {}).runpath || []; const runDirs = runpath.length ? runPathDirs(runpath, execOriginDir()).filter((d) => !envDirs.includes(d)) : []; const envCands = ldLibraryPathCandidates(envDirs, name2); s = libPathStage = { image: imageBytes, name: name2, index, kernelRc, cands: [...envCands, ...ldLibraryPathCandidates(runDirs, name2)], envCands: envCands.length, cand: 0, tried: 0, scratch: 0, scratchFor: "", restart: false, mismatched: [] }; } const exp = vmlinuxInstance ? vmlinuxInstance.exports : null; const digest = neededDigest(name2); if (s.cands.length && !s.scratch && exp && typeof exp.wasm32_user_dlopen_load === "function" && init.kernelMemoryWasm) { const a = syscall( 9, 0, 4096, 3, 34, -1, 0 ) | 0; if (a > 0) s.scratch = a >>> 0; else { try { post({ kind: "dmesg", level: 4, text: `hwjs-libc: pid=${ctrl[C.PID] | 0} LD_LIBRARY_PATH not searched for ${neededSoname(name2)}: no page for the path (${a}) [${context}]` }); } catch (_e) { } } } try { for (; s.scratch && s.cand < s.cands.length; s.cand++) { const path = s.cands[s.cand]; const enc2 = new TextEncoder().encode(path); if (enc2.length >= 4096) continue; if (s.scratchFor !== path) { const u8 = new Uint8Array(init.memory.buffer); u8.set(enc2, s.scratch); u8[s.scratch + enc2.length] = 0; s.scratchFor = path; } const rc = dlopenStagingRead(s.scratch, path, yieldWouldBlock, s.restart); s.restart = false; if (rc === HWJS_ERESTART_RESCHED) return rc; if (rc === HWJS_ERESTARTNOINTR) { s.restart = true; return rc; } s.tried++; if (rc < 0) continue; const via = `${s.cand < s.envCands ? "LD_LIBRARY_PATH" : "run path"} "${path}"`; const bytes = readKernelStagedImage( exp, init.kernelMemoryWasm.buffer, "wasm32_user_dlopen", via, true /* a buffer of its own */ ); const releaseCall = () => { exp.wasm32_user_dlopen_release(); return 0; }; if (hwjsLane) hwjsLane.bracket("wasm32_user_dlopen_release", releaseCall); else releaseCall(); if (!workerSharedLibs.has(digest)) { if (sha256Hex(bytes) !== digest) { s.mismatched.push(path); if (typeof bytes.buffer.transfer === "function") bytes.buffer.transfer(0); continue; } storeNeededLibrary(bytes, digest, name2, index, via, context, path); dladdrKnownPaths.set(digest, path); } else { if (sha256Hex(bytes) === digest) dladdrKnownPaths.set(digest, path); if (typeof bytes.buffer.transfer === "function") bytes.buffer.transfer(0); } libPathStageDrop(); return true; } } catch (e) { libPathStageDrop(); throw e; } const out = { errno: s.kernelRc, mismatched: s.mismatched, tried: s.tried }; libPathStageDrop(); return out; } function libPathStageDrop() { const s = libPathStage; libPathStage = null; if (s && s.scratch) { try { syscallInner(11, s.scratch, 4096, 0, 0, 0, 0); } catch (_e) { } s.scratch = 0; } } function writeNeededLoadError(name2, kernelRc, mismatched) { if (!Array.isArray(execPendingArgv)) return; const line = neededLoadErrorLine( execPendingArgv[0] || execPendingPath || "", name2, kernelRc, mismatched ); try { post({ kind: "dmesg", level: 4, text: `hwjs-libc: pid=${ctrl[C.PID] | 0} ${line}` }); } catch (_e) { } const a = syscall( 9, 0, 4096, 3, 34, -1, 0 ) | 0; if (a <= 0) return; try { const enc2 = new TextEncoder().encode(`${line} `).subarray(0, 4096); new Uint8Array(init.memory.buffer).set(enc2, a >>> 0); syscall(1, 2, a >>> 0, enc2.length, 0, 0, 0); } catch (_e) { } try { syscallInner(11, a >>> 0, 4096, 0, 0, 0, 0); } catch (_e) { } } async function requestExecImage(path, pathPtr) { if (vmlinuxInstance && perProcessTaskAddr !== 0 && typeof vmlinuxInstance.exports.wasm32_user_exec_load === "function" && init.kernelMemoryWasm) { try { const resumed = execStageResuming(pathPtr) ? execStage.bytes : null; execStageReset(); if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `EXEC-LOAD-DIAG: calling wasm32_user_exec_load path="${path}"` }); } catch (_e) { } } const rc = resumed ? 0 : await driveExecLoadWithYield({ load: () => execLoadKernelChunked( pathPtr, /* yieldWouldBlock */ true ), yieldTurn: () => coopWaitParkYield("EXEC-LOAD park service"), onYield: () => { announceExecLoadYield("exec park service", path); if (SCHED_TRACE) { schedTrace(post, `YIELD cpu=${init.cpuId ?? "?"} tid=${init.tid} reason=EXEC-LOAD-park site=exec-park-service via=wake-word`); } } }); if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `EXEC-LOAD-DIAG: wasm32_user_exec_load RETURNED rc=${rc | 0}` }); } catch (_e) { } } if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} EXEC-LOAD rc=${rc | 0}` }); } catch (_e) { } } if (rc < 0) { return { ok: false, errno: rc }; } const bytes = resumed || readKernelStagedImage( vmlinuxInstance.exports, init.kernelMemoryWasm.buffer, "wasm32_user_exec", "staged exec image (park service)" ); if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `EXEC-LOAD-DIAG: staged image ${bytes.length}B in ${vmlinuxInstance.exports.wasm32_user_exec_nsegs() >>> 0} segment(s); re-instantiating` }); } catch (_e) { } } try { const stageRc = await driveExecLoadWithYield({ load: () => { const r = serviceLibcStageForExecImage( bytes, "exec-load (park service)", /* yieldWouldBlock */ true ); return r === HWJS_ERESTART_RESCHED || r === HWJS_ERESTARTNOINTR ? r : 0; }, yieldTurn: () => coopWaitParkYield("LIBC-STAGE park service"), onYield: () => { if (SCHED_TRACE) { schedTrace(post, `YIELD cpu=${init.cpuId ?? "?"} tid=${init.tid} reason=LIBC-STAGE-park site=exec-park-service via=wake-word`); } } }); if (stageRc === HWJS_ERESTARTNOINTR) { execStage.phase = "staged"; execStage.pathPtr = pathPtr >>> 0; execStage.bytes = bytes; return { ok: false, errno: HWJS_ERESTARTNOINTR }; } } catch (stageErr) { try { post({ kind: "user-report", pid: init.pid, message: "hwjs-libc exec-load refusal (clean POSIX exec failure): " + (stageErr instanceof Error ? stageErr.message : String(stageErr)) }); } catch (_e) { } return Promise.resolve({ ok: false, errno: execStageRefusalErrno(stageErr) }); } const shebangPrefix = readExecShebangPrefix(); const releaseCall = () => { vmlinuxInstance.exports.wasm32_user_exec_release(); return 0; }; if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `EXEC-LOAD-DIAG: pre-release` }); } catch (_e) { } } if (hwjsLane) hwjsLane.bracket("wasm32_user_exec_release", releaseCall); else releaseCall(); if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `EXEC-LOAD-DIAG: post-release; returning ${bytes.length}B to EXEC service` }); } catch (_e) { } } { const fmtErr = execImageFormatCheck(bytes, "exec-load (park service)"); if (fmtErr < 0) return Promise.resolve({ ok: false, errno: fmtErr }); } { const fitErr = init.vforkChild ? 0 : ensureUserMemoryFitsImage(bytes, "exec-load (park service)"); if (fitErr < 0) return Promise.resolve({ ok: false, errno: fitErr }); } while (!execCommitStep()) await coopWaitParkYield("EXEC-COMMIT park service"); applyExecShebangPrefix(shebangPrefix); return Promise.resolve({ ok: true, wasmBytes: bytes }); } catch (e) { containTrappedLane("wasm32_user_exec_load (park service)"); post({ kind: "error", pid: init.pid, message: "D1-FORK exec-in-place: kernel-routed wasm32_user_exec_load trapped: " + (e instanceof Error ? e.message : String(e)) + (e instanceof Error && e.stack ? "\nEXEC-LOAD-STACK: " + e.stack.split("\n").slice(0, 12).join(" | ") : "") }); return Promise.resolve({ ok: false, errno: -14 /* EFAULT */ }); } } return new Promise((resolve) => { setExecImageResolver(resolve); post({ kind: "execve", pid: ctrl[C.PID] | 0, path }); }); } const execStage = { phase: "idle", pathPtr: 0, bytes: null, shebang: null }; const execCommitChain = { h: 0, owner: 0 }; function execCommitStep() { const exp = vmlinuxInstance ? vmlinuxInstance.exports : null; if (!exp || typeof exp.wasm32_user_exec_commit !== "function") return true; const commitCall = () => { exp.wasm32_user_exec_commit(); return 0; }; if (!hwjsLane) { commitCall(); return true; } return !hwjsLane.driveWouldBlock( "wasm32_user_exec_commit", commitCall, execCommitChain ).wouldBlock; } function execStageReset() { execStage.phase = "idle"; execStage.pathPtr = 0; execStage.bytes = null; execStage.shebang = null; } function execStageResuming(pathPtr) { if (execStage.phase === "idle") return false; if (execStage.pathPtr === pathPtr >>> 0) return true; const was = execStage.pathPtr; execStageReset(); throw new Error( `loadExecImageKernelSync: an exec for pathPtr=0x${(pathPtr >>> 0).toString(16)} entered while the image for 0x${was.toString(16)} is STAGED and unreleased (its libc stage is mid-flight) \u2014 refusing to abandon a live kernel staging slot (never-silent)` ); } function execStageDrainOnExit() { if (execStage.phase === "committing") { execStageReset(); try { while (!execCommitStep()) { } } catch (_e) { } return; } if (execStage.phase !== "staged") return; const held = execStage.bytes ? execStage.bytes.length : 0; execStageReset(); try { const exp = vmlinuxInstance ? vmlinuxInstance.exports : null; if (!exp || typeof exp.wasm32_user_exec_release !== "function") return; const releaseCall = () => { exp.wasm32_user_exec_release(); return 0; }; if (hwjsLane) hwjsLane.bracket("wasm32_user_exec_release", releaseCall); else releaseCall(); try { post({ kind: "dmesg", level: 4, text: `hwjs-exec: pid=${ctrl[C.PID] | 0} terminated with a ${held}B exec image still STAGED (its libc stage never finished) \u2014 released the kernel staging slot on the way out. Never-silent: nothing else would have, and the allocation would have outlived the machine.` }); } catch (_e) { } } catch (_e) { } } function loadExecImageKernelSync(pathPtr, yieldWouldBlock = false) { if (!(vmlinuxInstance && perProcessTaskAddr !== 0 && typeof vmlinuxInstance.exports.wasm32_user_exec_load === "function" && init.kernelMemoryWasm)) { return { unavailable: true }; } try { let bytes; if (execStageResuming(pathPtr) && execStage.phase === "committing") { if (!execCommitStep()) return { wouldBlock: true }; bytes = execStage.bytes; const shebang = execStage.shebang; execStageReset(); applyExecShebangPrefix(shebang); return { ok: true, wasmBytes: bytes }; } if (execStage.phase === "staged") { bytes = execStage.bytes; } else { const rc = execLoadKernelChunked(pathPtr, yieldWouldBlock) | 0; if (rc === HWJS_ERESTART_RESCHED) return { wouldBlock: true }; if (rc < 0) return { ok: false, errno: rc }; bytes = readKernelStagedImage( vmlinuxInstance.exports, init.kernelMemoryWasm.buffer, "wasm32_user_exec", "staged exec image (inline)" ); execStage.phase = "staged"; execStage.pathPtr = pathPtr >>> 0; execStage.bytes = bytes; } try { const stageRc = serviceLibcStageForExecImage( bytes, "exec-load (inline)", yieldWouldBlock ); if (stageRc === HWJS_ERESTART_RESCHED) return { wouldBlock: true }; if (stageRc === HWJS_ERESTARTNOINTR) { return { ok: false, errno: HWJS_ERESTARTNOINTR }; } } catch (stageErr) { execStageReset(); try { post({ kind: "user-report", pid: init.pid, message: "hwjs-libc exec-load refusal (clean POSIX exec failure): " + (stageErr instanceof Error ? stageErr.message : String(stageErr)) }); } catch (_e) { } return { ok: false, errno: execStageRefusalErrno(stageErr) }; } const shebangPrefix = readExecShebangPrefix(); const releaseCall = () => { vmlinuxInstance.exports.wasm32_user_exec_release(); return 0; }; if (hwjsLane) hwjsLane.bracket("wasm32_user_exec_release", releaseCall); else releaseCall(); execStageReset(); { const fmtErr = execImageFormatCheck(bytes, "exec-load (inline)"); if (fmtErr < 0) return { ok: false, errno: fmtErr }; } { const fitErr = init.vforkChild ? 0 : ensureUserMemoryFitsImage(bytes, "exec-load (inline)"); if (fitErr < 0) return { ok: false, errno: fitErr }; } if (!execCommitStep()) { if (yieldWouldBlock) { execStage.phase = "committing"; execStage.pathPtr = pathPtr >>> 0; execStage.bytes = bytes; execStage.shebang = shebangPrefix; return { wouldBlock: true }; } while (!execCommitStep()) { } } applyExecShebangPrefix(shebangPrefix); return { ok: true, wasmBytes: bytes }; } catch (e) { execStageReset(); containTrappedLane("wasm32_user_exec_load (inline)"); post({ kind: "error", pid: init.pid, message: "HWJS-B-2 exec: kernel-routed wasm32_user_exec_load trapped: " + (e instanceof Error ? e.message : String(e)) + (e instanceof Error && e.stack ? "\nEXEC-LOAD-STACK: " + e.stack.split("\n").slice(0, 12).join(" | ") : "") }); return { ok: false, errno: -14 /* EFAULT */ }; } } function readUserCString(ptr, cap = 4096) { const p = ptr >>> 0; if (p === 0) return ""; const u8 = new Uint8Array(init.memory.buffer); let e = p; const lim = Math.min(u8.length, p + cap); while (e < lim && u8[e] !== 0) e++; return decodeMaybeShared3(u8.subarray(p, e)); } const HWJS_BUDGET_LOUD_OPS = /* @__PURE__ */ new Set([ "__hwjs_budget_uninitialized", "__hwjs_budget_not_refilled" ]); function makeBudgetLoudHandler(op, owner) { if (op === "__hwjs_budget_not_refilled") { return (namePtr) => { const fn2 = readUserCString(namePtr >>> 0, 256) || ""; const msg = `hwjs-budget: DRIVER CONTRACT BREACH in "${owner}" \u2014 the M6 safepoint in ${fn2}() parked on an expired @__hwjs_budget and the driver RESUMED it without rebinding one. Every following back-edge crossing takes the expiry arm, so the module spends its life in park/resume round trips at loop-iteration granularity while every instrument still reports it preemptible. Refill the budget of EVERY module instance on resume (the handle's budgetGlobal / __hwjs_budget_set), not just the main's. The module traps at the \`unreachable\` immediately after this call \u2014 that trap is in the image and is identical in the static and -shared builds; this report only names the site.`; try { post({ kind: "user-report", pid: init.pid, message: msg }); } catch (_e) { } throw new Error(msg); }; } return () => { const msg = `hwjs-budget: UNINITIALIZED BUDGET in "${owner}" \u2014 the module's startup sanity constructor found @__hwjs_budget still at the weak-0 default, i.e. nothing bound this instance's initial safepoint budget BEFORE its constructors ran. A zero budget is correctness-safe (every safepoint parks) but perf-fatal, which is why it is refused rather than tolerated. The loader arms a freshly loaded module's budget before ctors (armModuleBudget); reaching this handler means that arming did not happen for this module. The module traps at the \`unreachable\` immediately after this call \u2014 that trap is in the image and is identical in the static and -shared builds; this report only names the module.`; try { post({ kind: "user-report", pid: init.pid, message: msg }); } catch (_e) { } throw new Error(msg); }; } const DLOPEN_MAIN_OWNED_OPS = /* @__PURE__ */ new Set([ "__hwjs_frame_alloc", "__hwjs_frame_free", "__hwjs_frame_publish", "__hwjs_set_parked", "__hwjs_clear_parked", "__hwjs_take_parked", "__hwjs_noreturn_completed", "__hwjs_xfer_descend", "__hwjs_xfer_park", "__hwjs_xfer_return", "__hwjs_xfer_take", "hwjs_sj_record", "hwjs_lj_arm_from", "hwjs_lj_match", "hwjs_lj_selector", "hwjs_lj_value", "hwjs_lj_clear", "hwjs_lj_unwound", "hwjs_trap", "hwjs_resume", "hwjs_done", "hwjs_destroy", "__hwjs_drive_abi", "__hwjs_register_suspends", "__hwjs_ds_region_abi_v2", "__hwjs_region_alloc", "__hwjs_region_save", "__hwjs_region_restore", "__hwjs_freea", /* drive_abi=4 status-channel op roster (STATUS-CHANNEL-CONTRACT §10: * "New ops join DLOPEN_MAIN_OWNED_OPS and the export whitelists"). * MAIN-owned by §1: every module in a process addresses the MAIN's one * channel block, so a .so's env.__hwjs_status_* import must bind the * main's op set — never the kernel namesake. No-op until an abi-4 .so * actually imports one (today none do); then the binding is contractual * and a main missing the export refuses loudly below. */ "__hwjs_status_park_exit", "__hwjs_status_baton", "__hwjs_status_clear", "__hwjs_status_adopt_top", "__hwjs_drive_adopt_parked", "__hwjs_status_raise_unwind", "__hwjs_status_raise_longjmp", "__hwjs_status_sj_register", "__hwjs_status_violation", "__hwjs_status_longjmp_lost", /* §4 terminus hook (2026-07-21, the uncaught-exit-0 fix): the EH * pre-lowering's process-exit-sink checks call it. MAIN-owned by the * same §1 rule: the main's definition (libc++abi's strong * std::terminate route in a C++ image; the RT weak fallback otherwise) * is the one every module in the process must reach. */ "__hwjs_uncaught_unwinding" ]); const DLOPEN_KERNEL_OWNED_OPS = /* @__PURE__ */ new Set([ "__hwjs_capsummary_lookup", "__hwjs_e8_refuse", "__hwjs_fpcast_adapter_lookup", "__hwjs_fpcast_target_sig_lookup", "__hwjs_register_capsummary", "__hwjs_register_fpcast_adapter" ]); function withDlsymCaller(resolve, dlsymCaller) { return (m, n, kind, ownDefined) => { const f = resolve(m, n, kind, ownDefined); return m === "env" && kind === "function" ? dlsymCallerImport(n, f, libcExportsNow(), dlsymCaller, dlsymCallerBox) : f; }; } function makeDlopenResolveImport(owner) { const kexp = vmlinuxInstance ? vmlinuxInstance.exports : null; return (m, n, kind, ownDefined) => { if (kind !== "function" || m !== "env") return void 0; if (HWJS_BUDGET_LOUD_OPS.has(n)) { if ((globalThis.process?.env?.HWJS_RED_NO_BUDGET_HANDLER_BIND || "") === "1") { return void 0; } return makeBudgetLoudHandler(n, owner || "a dlopen'd module"); } if (n === "fork") { const f = userExports && (userExports._Fork || userExports.fork); if (typeof f === "function") return f; throw new Error( "hwjs-dlopen: env.fork unresolved \u2014 the dynamic-main exports no musl _Fork/fork PARK LEAF for the loaded module to suspend through. The host cannot synthesize a wasm park leaf from JS (the fork dynamic-main must export + keep its _Fork park leaf)." ); } if (DLOPEN_MAIN_OWNED_OPS.has(n) || n.startsWith("__hwjs_promise_")) { const f = userExports ? userExports[n] : void 0; if (typeof f === "function") return f; throw new Error( `hwjs-dlopen: env.${n} is a MAIN-owned hwjs runtime op but the main image does not export "${n}" \u2014 refusing the kernel's namesake (cross-address-space misdispatch; the dynamic-main must carry its own hwjs_user_rt op set; never-silent).` ); } if (CAPSUMMARY_SCOPED_OPS[n]) return CAPSUMMARY_SCOPED_OPS[n]; if (DLOPEN_KERNEL_OWNED_OPS.has(n)) { if (FPCAST_SCOPED_OPS[n]) return FPCAST_SCOPED_OPS[n]; const f = kexp ? kexp[n] : void 0; if (typeof f === "function") return f; throw new Error( `hwjs-dlopen: env.${n} is a KERNEL-owned registry op but vmlinux does not export "${n}" \u2014 refusing to bind elsewhere (never-silent).` ); } if (userExports && typeof userExports[n] === "function") return driveImport(n, userExports[n]); const scoped = dlopenScopeExport( n, !!ownDefined, neededSoHandles, dlopenModules.values() ); if (scoped) return driveImport(n, scoped); return void 0; }; } function makeDlopenResolveDataAddress() { return (name2) => { const g = userExports ? userExports[name2] : void 0; if (g instanceof WebAssembly.Global) return g.value >>> 0; const needed = dlopenSiblingDataAddress(name2, neededSoHandles); if (needed !== void 0) return needed; const sib = dlopenSiblingDataAddress(name2, dlopenModules.values()); if (sib !== void 0) return sib; return void 0; }; } function makeFrameCensusResolveImport(base, census, path) { return (m, n, kind, ownDefined) => { const f = base(m, n, kind, ownDefined); if (kind !== "function" || m !== "env" || typeof f !== "function") return f; if (n === "__hwjs_frame_alloc") { return (sz) => { const p = f(sz); if ((p | 0) !== 0) census.live++; return p; }; } if (n === "__hwjs_frame_free") { return (p) => { f(p); if ((p | 0) === 0) return; if (census.live <= 0) { census.poisoned = true; post({ kind: "user-report", pid: init.pid, message: `HWJS-5 M2 dlclose census UNDERFLOW for "${path}": __hwjs_frame_free(0x${(p >>> 0).toString(16)}) with live=0 \u2014 the per-module frame census lost an alloc; module POISONED (its dlclose will refuse; never-silent, non-terminal).` }); return; } census.live--; }; } return f; }; } const xmodMarshalNoted = /* @__PURE__ */ new Set(); function xmodDispatchCheck(siteSig, fp, fromMain, fromRt, marshal) { siteSig = siteSig >>> 0; fp = fp >>> 0; if (HWJS_XMOD_CONSULT_TRACE) { const mods = [...dlopenModules.values()].map((m) => `${m.path}@[${m.tableBase},${m.tableBase + (m.handle && m.handle.dylink ? m.handle.dylink.tableSize >>> 0 : 0)})recs=${m.xmodRecs ? m.xmodRecs.size : -1}`).join(" "); post({ kind: "dmesg", level: 7, text: `hwjs-xmod-consult TRACE sig=0x${siteSig.toString(16)} fp=${fp} mods: ${mods}` }); } if (fromRt && dlopenDeadRanges.length === 0) return 1; const c = xmodConsultClassify( siteSig, fp, dlopenDeadRanges, dlopenModules.values(), (t) => fpcastProcessRecs.get(t >>> 0) ); const dead = c.dead, live2 = c.live; const verdict = xmodConsultVerdict({ inDead: !!dead, inFootprint: !!live2, inElem: c.inElem, hasRec: c.hasRec, recOtherSig: c.recOtherSig, recAny: c.recAny, regRan: c.regRan, fromMain, fromRt, marshal }); if (verdict === 2) { const where = live2 ? `"${live2.path}" (moduleId=${live2.moduleId})` : "the main image"; const key = siteSig + ":" + fp + ":" + where; if (!xmodMarshalNoted.has(key)) { xmodMarshalNoted.add(key); const own = fpcastProcessRecs.get(fp) >>> 0; post({ kind: "dmesg", level: 5, text: `HWJS F173 xmod-consult MARSHAL: table index ${fp} (site_sig=0x${siteSig.toString(16)}) targets ${where}, registered under own sig 0x${own.toString(16)} \u2014 the site's arm calls it if that is a parameter prefix of the site signature and traps otherwise (issue linux-in-the-browser#186).` }); } } if (verdict) return verdict; post({ kind: "user-report", pid: init.pid, message: dead ? `HWJS F152 xmod-consult E8-REFUSE (dead-module): sig-compatible open-world dispatch of table index ${fp} (site_sig=0x${siteSig.toString(16)}) targets dlclosed module "${dead.path}" (moduleId=${dead.moduleId}) \u2014 refusing loudly; the caller traps (never-silent; issue linux-in-the-browser#40).` : `HWJS F152 xmod-consult E8-REFUSE (unregistered-target): sig-compatible open-world dispatch of table index ${fp} (site_sig=0x${siteSig.toString(16)}) targets "${live2.path}" (moduleId=${live2.moduleId}) but that module has NO live __hwjs_register_fpcast_adapter record for (sig, target) \u2014 its F117 registration ctors under-ran (stripped start / partial registration) or the record's wasm signature is inconsistent with this site \u2014 refusing loudly; the caller traps (never-silent; issue linux-in-the-browser#40).` }); return 0; } function xmodConsultImport(fromMain, fromRt, marshal) { const key = (fromMain ? 1 : 0) | (fromRt ? 2 : 0) | (marshal ? 4 : 0); let k = xmodConsultClasses.get(key); if (!k) { k = { fromMain: !!fromMain, fromRt: !!fromRt, marshal: !!marshal, cache: null, check: null, js: 0, hitsBefore: 0 }; const slow = (sig, fp) => xmodDispatchCheck(sig, fp, fromMain, fromRt, marshal); const miss = HWJS_XMOD_CONSULT_STATS ? (sig, fp) => { k.js++; return slow(sig, fp); } : slow; if (HWJS_XMOD_CONSULT_CACHE && !HWJS_XMOD_CONSULT_TRACE) { k.cache = makeXmodConsultCache(miss, xmodConsultIdBase | key, HWJS_XMOD_CONSULT_STATS); } k.check = k.cache ? k.cache.check : xmodConsultUncached(miss); xmodConsultClasses.set(key, k); } return k.check; } function xmodConsultStatsReport(why) { if (!HWJS_XMOD_CONSULT_STATS) return; for (const k of xmodConsultClasses.values()) { const hits = k.cache ? k.cache.hits() : 0; const consults = hits - k.hitsBefore + k.js; post({ kind: "dmesg", level: 6, text: `hwjs-xmod-consult STATS pid=${ctrl[C.PID] | 0} at=${why} fromMain=${+k.fromMain} fromRt=${+k.fromRt} marshal=${+k.marshal} cache=${k.cache ? 1 : 0} consults=${consults} js=${k.js}` }); k.hitsBefore = hits; k.js = 0; } } function makeXmodConsultResolveImport(base, recs, registrar, arm) { return (m, n, kind, ownDefined) => { if (kind === "function" && m === "env" && n === "__hwjs_xmod_dispatch_check") { return xmodConsultImport(false, false, !!(arm && arm.marshal)); } const f = base(m, n, kind, ownDefined); if (kind !== "function" || m !== "env" || typeof f !== "function") return f; if (n === "__hwjs_register_fpcast_adapter") { if (registrar) registrar.imported = true; xmodConsultInvalidate(); return (ver, sig, fid, tgt, mid) => { recs.add((sig >>> 0) + ":" + (tgt >>> 0)); return f(ver, sig, fid, tgt, mid); }; } return f; }; } function fpcastRegisterScoped(ver, sig, fid, tgt, mid) { fpcastProcessRecs.set(tgt >>> 0, sig >>> 0); if (!HWJS_FPCAST_TRACE && ver >>> 0 === HWJS_FPCAST_VERSION) return 1; const kexp = vmlinuxInstance ? vmlinuxInstance.exports : null; const f = kexp ? kexp.__hwjs_register_fpcast_adapter : void 0; const rc = typeof f === "function" ? f(ver, sig, fid, tgt, mid) | 0 : 0; if (HWJS_FPCAST_TRACE) { let rb = "n/a"; try { const o = kexp ? kexp.__hwjs_fpcast_target_sig_lookup : void 0; if (typeof o === "function") rb = "0x" + (o(tgt) >>> 0).toString(16); } catch (_e) { } try { post({ kind: "dmesg", level: 7, text: `FPCAST-REGISTER(scoped) sig=0x${(sig >>> 0).toString(16)} fid=0x${(fid >>> 0).toString(16)} tgt=${tgt >>> 0} mid=${mid >>> 0} census=${fpcastProcessRecs.size} kernel-rc=${rc} kernel-readback=${rb}` }); } catch (_e) { } } return rc; } function fpcastAdapterLookupScoped(sig, tgt) { const own = fpcastProcessRecs.get(tgt >>> 0); const r = own !== void 0 && own === sig >>> 0 ? tgt | 0 : 0; if (HWJS_FPCAST_TRACE) { try { post({ kind: "dmesg", level: 7, text: `FPCAST-LOOKUP(scoped) site_sig=0x${(sig >>> 0).toString(16)} tgt=${tgt >>> 0} own=${own === void 0 ? "MISS" : "0x" + own.toString(16)} -> ${r}` }); } catch (_e) { } } return r; } function* fpcastExportOwners() { yield libcSoHandle; for (const r of neededSoHandles) yield r ? r.handle : null; for (const m of dlopenModules.values()) yield m ? m.handle : null; } function fpcastTargetSigLookupScoped(tgt) { const own = fpcastProcessRecs.get(tgt >>> 0); const derived = own === void 0 ? xmodExportSigOf(tgt, sharedTable, fpcastExportOwners()) : 0; const r = own === void 0 ? derived | 0 : own | 0; if (HWJS_FPCAST_TRACE) { try { post({ kind: "dmesg", level: 7, text: `FPCAST-TSIG(scoped) tgt=${tgt >>> 0} -> ${own !== void 0 ? "0x" + own.toString(16) : derived ? "EXPORT 0x" + derived.toString(16) : "MISS(0)"}` }); } catch (_e) { } } return r; } const FPCAST_SCOPED_OPS = { __hwjs_register_fpcast_adapter: fpcastRegisterScoped, __hwjs_fpcast_adapter_lookup: fpcastAdapterLookupScoped, __hwjs_fpcast_target_sig_lookup: fpcastTargetSigLookupScoped }; const CAPSUMMARY_SCOPED_OPS = { __proto__: null, __hwjs_register_capsummary: (ver, sig, mask, mid) => capsummaryProcessRecs.register(ver, sig, mask, mid), __hwjs_register_capsummary_target: (ver, sig, mask, fn2, mid) => capsummaryProcessRecs.registerTarget(ver, sig, mask, fn2, mid), __hwjs_capsummary_lookup: (sig, arg) => { const ok = capsummaryProcessRecs.lookup(sig, arg); if (!ok) capsummaryRefusalReport(sig, arg, void 0); return ok; }, __hwjs_capsummary_lookup_callee: (sig, arg, callee) => { const ok = capsummaryProcessRecs.lookupCallee(sig, arg, callee); if (!ok) capsummaryRefusalReport(sig, arg, callee); return ok; } }; const capsummaryRefusalsReported = /* @__PURE__ */ new Set(); function capsummaryModuleName(mid) { if (mid === 0) return "the main"; if (hwjsRtPlacement && hwjsRtPlacement.moduleId >>> 0 === mid) return "rt (#0)"; if (libcSoPlacement && libcSoPlacement.moduleId >>> 0 === mid) return "libc.so (#1)"; const n = neededPlacements.find((p) => p.moduleId >>> 0 === mid); if (n) return n.name || `needed #${n.index}`; for (const e of dlopenModules.values()) { if (e && !e.mainScope && e.moduleId >>> 0 === mid) return e.path || `dlopen module ${mid}`; } return `module ${mid}`; } function capsummaryRefusalReport(sig, arg, callee) { const key = `${sig >>> 0}:${arg >>> 0}:${callee === void 0 ? "" : callee >>> 0}`; if (capsummaryRefusalsReported.has(key)) return; capsummaryRefusalsReported.add(key); const recs = capsummaryProcessRecs.records(sig); const bit2 = 1n << BigInt(arg >>> 0); const named = recs.map(([mid, bits]) => `${capsummaryModuleName(mid)}=0x${bits.toString(16)}${bits & bit2 ? "" : " (clears it)"}`); let own = ""; if (callee !== void 0) { const t = capsummaryProcessRecs.target(callee); own = t === void 0 ? `callee ${callee >>> 0} has no record of its own, so the signature's records answer; ` : t.sig !== sig >>> 0 ? `callee ${callee >>> 0}'s own record is for signature ${t.sig}, so the signature's records answer; ` : `callee ${callee >>> 0} (${capsummaryModuleName(t.mid)}) keeps it: its own record is 0x${t.bits.toString(16)}; `; } try { post({ kind: "dmesg", level: 3, text: `hwjs-capsummary pid=${ctrl[C.PID] | 0} lookup sig_hash=${sig >>> 0} arg=${arg >>> 0} -> 0: ` + own + (recs.length ? `this image's records for the signature: ${named.join(", ")}` : "no module of this image registered a record for the signature") }); } catch (_e) { } } function adoptSharedDlopens(state, replay, deadRanges, mainScope) { const shared = threadCtx.dlEntries || /* @__PURE__ */ new Map(); let maxCookie = 0; for (const e of replay) { const c = e.cookie >>> 0; const m = shared.get(c); if (!m) { throw new Error(`hwjs-thread-image: the shared image has no module for "${e.path}" (cookie=${c}) that this thread's placement record names \u2014 the context does not match the record (never-silent).`); } dlopenModules.set(c, m); armModuleBudget(m.handle); adoptSideTls(m.handle, e.path || m.path || `cookie ${c}`, false); if (c > maxCookie) maxCookie = c; } for (const d of deadRanges) { dlopenDeadRanges.push({ tableBase: d.tableBase >>> 0, tableSize: d.tableSize >>> 0, appended: Array.isArray(d.appended) ? [...d.appended] : [], path: d.path || "", moduleId: d.moduleId | 0 }); } xmodConsultInvalidate(); for (const c of mainScope) { dlopenModules.set(c >>> 0, makeMainScopeEntry()); if (c >>> 0 > maxCookie) maxCookie = c >>> 0; } dlopenNextCookie = Math.max( dlopenNextCookie, maxCookie + 1, state.nextCookie >>> 0 ); } function replayForkDlopens(state, incremental = false) { if (!state || typeof state !== "object") return; const appendOnly = !incremental && (globalThis.process?.env?.HWJS_FORK_REPLAY_APPEND_ONLY || "") === "1"; const replay = Array.isArray(state.replay) ? state.replay : []; const deadRanges = Array.isArray(state.deadRanges) ? state.deadRanges : []; const mainScope = Array.isArray(state.mainScope) ? state.mainScope : []; const mainScopeNames = Array.isArray(state.mainScopeNames) ? state.mainScopeNames : []; const hasLate = !!(state.libcSo && Array.isArray(state.libcSo.late) && state.libcSo.late.length || Array.isArray(state.neededLibs) && state.neededLibs.some((r) => Array.isArray(r.late) && r.late.length)); if (replay.length === 0 && deadRanges.length === 0 && mainScope.length === 0 && mainScopeNames.length === 0 && !hasLate) return; const table = sharedTable; if (!(table instanceof WebAssembly.Table)) { throw new Error( "HWJS-5 fork\xD7dlopen: child has a dlopenFork payload but no shared table \u2014 the fork-resume main image is not a dynamic-main (never-silent)." ); } if (threadCtxJoin && !incremental) { adoptSharedDlopens(state, replay, deadRanges, mainScope); return; } const preGrowLen = table.length >>> 0; if (!appendOnly) { const parentLen = state.tableLen >>> 0 || 0; if (parentLen < preGrowLen && !incremental) { throw new Error( `HWJS-5 fork\xD7dlopen: parent fork-time table length ${parentLen} < child main-elem table length ${preGrowLen} \u2014 the child's main image diverged from the parent's (never-silent, the recorded placements would overlap main's elem).` ); } if (parentLen > preGrowLen) { try { table.grow(parentLen - preGrowLen); } catch (e) { throw new Error( `HWJS-5 fork\xD7dlopen: could not grow the child table ${preGrowLen} -> ${parentLen} (max reached?): ` + (e instanceof Error ? e.message : String(e)) ); } } adoptLateTableEntries(state); if (incremental) { for (const [k, v] of Array.isArray(state.fpcastRecs) ? state.fpcastRecs : []) { if (!fpcastProcessRecs.has(k >>> 0)) fpcastProcessRecs.set(k >>> 0, v >>> 0); } if (state.capsummaryRecs) capsummaryProcessRecs.merge(state.capsummaryRecs); } for (const d of deadRanges) { if (incremental) { if (dlopenDeadRanges.some((o) => o.tableBase >>> 0 === d.tableBase >>> 0)) continue; for (const [c, m] of dlopenModules) { if (m && !m.mainScope && m.tableBase >>> 0 === d.tableBase >>> 0) { dlopenModules.delete(c); } } if ((d.moduleId | 0) !== 0) capsummaryProcessRecs.removeModule(d.moduleId | 0); } dlopenDeadRanges.push({ tableBase: d.tableBase >>> 0, tableSize: d.tableSize >>> 0, appended: Array.isArray(d.appended) ? [...d.appended] : [], path: d.path || "", moduleId: d.moduleId | 0 }); } xmodConsultInvalidate(); if (dlopenGotFuncIndex instanceof Map) { for (const [name2, idx] of Array.isArray(state.gotFunc) ? state.gotFunc : []) { if (incremental && dlopenGotFuncIndex.has(String(name2))) continue; dlopenGotFuncIndex.set(String(name2), idx >>> 0); } } } let maxCookie = 0; let placed = 0; for (const e of replay) { if (incremental) { const c = e.cookie >>> 0; if (c > maxCookie) maxCookie = c; const have = dlopenModules.get(c); if (have) { if (have.handle && typeof have.handle.adoptSymbolIndex === "function") { for (const [name2, idx] of Array.isArray(e.appended) ? e.appended : []) { have.handle.adoptSymbolIndex(String(name2), idx); } } if (e.refs !== void 0) have.refs = e.refs >>> 0; continue; } const tb = e.tableBase >>> 0; if (dlopenDeadRanges.some((d) => tb >= d.tableBase >>> 0 && tb < (d.tableBase >>> 0) + Math.max(1, d.tableSize >>> 0))) continue; const twin = threadCtx && threadCtx.dlEntries ? threadCtx.dlEntries.get(c) : null; if (twin) { dlopenModules.set(c, twin); armModuleBudget(twin.handle); adoptSideTls(twin.handle, e.path || twin.path || `cookie ${c}`, true); continue; } if (!(e.bytes instanceof Uint8Array) && !(e.bytes instanceof ArrayBuffer)) { throw new Error(`hardwarejs#115: placement record for "${e.path}" (cookie=${c}) carries no module bytes (never-silent)`); } } placed++; const census = { live: e.live >>> 0 || 0, poisoned: !!e.poisoned }; const xmodRecs = new XmodInputSet(Array.isArray(e.xmodRecs) ? e.xmodRecs : []); const xmodRegistrar = { imported: false }; const dlsymCaller = { kind: "dlopen" }; const xmodArm = { marshal: false }; const resolveImport = makeXmodConsultResolveImport( makeFrameCensusResolveImport( withDlsymCaller(makeDlopenResolveImport(e.path || ""), dlsymCaller), census, e.path || "" ), xmodRecs, xmodRegistrar, xmodArm ); const want = e.tableBase >>> 0; if (appendOnly) { if (table.length >>> 0 !== want) { throw new Error( `HWJS-5 fork\xD7dlopen: child table length ${table.length} != parent tableBase ${want} for "${e.path}" (cookie=${e.cookie}) \u2014 the child's table layout diverged from the parent (replay order / main elem mismatch; never-silent, the cross-module identities would not match).` ); } } else if (want < preGrowLen && !incremental) { throw new Error( `HWJS-5 fork\xD7dlopen: recorded tableBase ${want} for "${e.path}" (cookie=${e.cookie}) falls inside the child main image's elem region [0, ${preGrowLen}) \u2014 corrupt placement payload (never-silent, the elem write would clobber main's identities).` ); } const h = loadSharedObject({ wasmBytes: e.bytes instanceof Uint8Array ? e.bytes : new Uint8Array(e.bytes), memory: init.memory, table, /* #70: the replay reuses the per-Worker compiled Module for identical * bytes too — a fork of a dlopen-carrying process must not add a * fresh compiled copy per child (same census line, replay-tagged). */ compileModule: (b) => { const r = e.module ? storedSoModule(e.module, e.digest) : compileSoModule(b); xmodArm.marshal = xmodMarshalArmed(r.module); try { post({ kind: "dmesg", level: 7, text: `HWJS70-SOCACHE pid=${ctrl[C.PID] | 0} ${r.cached ? "HIT " : "COMPILE"} path="${e.path || ""}" (fork-replay) len=${b.length} key=${r.key} ` + soModuleCacheStats() }); } catch (_e) { } return r.module; }, fixedMemoryBase: e.memoryBase >>> 0, /* hwjs-cc#106: a TLS-owning module's private __tls_base is 0 on this * Instance. A thread gets its own block from its runtime block's TLS * arena; fork-resume and migrate-resume continue the recording thread * and bind the base it was using. */ sideTls: sideTlsReplayMode(init.mode, e, threadTlsAlloc), /* #43 step 2: place at the recorded __table_base + re-seed the * recorded appended slots (placement, not append order). The * append-only RED arm keeps the historical end-append path. */ ...appendOnly ? {} : { fixedTableBase: want, seedSymbolIndices: Array.isArray(e.appended) ? e.appended : [] }, moduleId: e.moduleId | 0, soPath: e.path || "", resolveImport, bindOwnDefinitions: true, resolveDataAddress: makeDlopenResolveDataAddress(), /* issue #45 gap 3: the process-wide GOT.func append cache — under * #43 it is placement-SEEDED above; the loader adopts the recorded * indices instead of appending. */ gotFuncIndex: dlopenGotFuncIndex, /* issue #45 gap 1: do NOT re-apply __wasm_apply_data_relocs — the * patched (and possibly runtime-mutated) data rode the delta=0 copy; * re-applying would clobber runtime mutations of the patched slots * (same rationale as the skipped ctors below). */ skipDataRelocs: true, /* Share the MAIN's exported __stack_pointer with the .so (SEMANTICS * INV-3: one sp across parks). May be undefined for a main that does * not export it — the loader only requires it if the .so IMPORTS sp. */ stackPointer: userExports ? userExports.__stack_pointer : void 0, /* The lane's budget; undefined (a module budget of its own) only * when no lane budget was made for this image. */ budgetGlobal: hwjsLaneBudget || void 0, /* STATUS-CHANNEL-CONTRACT §10 loader acceptance: the .so's drive_abi * must equal the RUNNING MAIN's (3 flat | 4 status-channel); the * loader refuses a mix. Undefined (no sentinel) keeps the loader's * historical flat pin. */ mainDriveAbi: userExports && typeof userExports.__hwjs_drive_abi === "function" ? userExports.__hwjs_drive_abi() | 0 : void 0, /* PLAN-THREADS-SINGLE-MEMORY §4 step 2: the process lane posture * (checkLoadPolicy refuses a bit5 disagreement — I3-2), and the * per-instance channel base for a lane-addressed .so's * env.__hwjs_status_channel_addr import: THIS thread's runtime block * (its channel is the block's first member). undefined before a * block is bound — the loader then refuses a .so that imports the * global (loud, never a fabricated address-0 binding). */ mainLaneAddressed: libcSoPlacement ? !!libcSoPlacement.laneAddressed : mainLaneAddressed, /* On a shared process image the context's channel Global, which the * register file switches: the module is entered by every thread. */ ...threadCtx ? { statusChannelGlobal: threadCtx.chanGlobal } : { statusChannelAddr: currentTcb ? currentTcb >>> 0 : void 0 }, /* The no-op park import is CORRECT BY DESIGN: it matches the main's * own hwjs_suspend.park no-op boundary — suspension happens IN WASM * (the transform parks by returning through __hwjs_xfer_park), the * import is only the marker boundary. Do not "fix" it. */ parkImport: () => { } }); armModuleBudget(h); if (incremental && h.tls && h.tls.unbound) { throw new Error(`hwjs-thread-image: this thread's TLS arena could not grow for "${e.path}", which another thread of the process loaded \u2014 its thread_local state has nowhere to live (never-silent).`); } if (h.tableBase >>> 0 !== want) { throw new Error( `HWJS-5 fork\xD7dlopen: replayed "${e.path}" (cookie=${e.cookie}) landed at tableBase ${h.tableBase}, parent recorded ${want} (never-silent, the cross-module identities would not match).` ); } const placedEntry = { handle: h, moduleId: e.moduleId | 0, bytes: e.bytes, path: e.path || "", memoryBase: h.memoryBase >>> 0, tableBase: h.tableBase >>> 0, census, xmodRecs, xmodRegistrar, dlsymCaller, ...e.internal ? { internal: true, name: e.name, digest: e.digest, ...e.module ? { module: e.module } : {} } : {}, ...e.boundByDependent ? { boundByDependent: true } : {}, ...e.refs !== void 0 ? { refs: e.refs >>> 0 } : {} }; dlopenModules.set(e.cookie >>> 0, placedEntry); if (threadCtx) { (threadCtx.dlEntries ||= /* @__PURE__ */ new Map()).set(e.cookie >>> 0, placedEntry); threadCtxNoteTls(threadCtx, h); } if (incremental) placementShipped.add(e.cookie >>> 0); if (e.cookie >>> 0 > maxCookie) maxCookie = e.cookie >>> 0; if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} FORK-DLOPEN-REPLAY "${e.path}" cookie=${e.cookie} moduleId=${e.moduleId} memBase=0x${(h.memoryBase >>> 0).toString(16)} tableBase=${h.tableBase}` }); } catch (_e) { } } } for (const c of mainScope) { if (incremental && dlopenModules.has(c >>> 0)) continue; dlopenModules.set(c >>> 0, makeMainScopeEntry()); if (c >>> 0 > maxCookie) maxCookie = c >>> 0; } for (const [name2, idx] of mainScopeNames) { const fn2 = mainScopeFunction(name2, userExports, neededSoHandles, mainScopeOrder()); if (incremental && dlopenMainScopeIndex instanceof Map && dlopenMainScopeIndex.get(String(name2)) === idx >>> 0) continue; if (typeof fn2 !== "function" || idx >>> 0 >= table.length) { throw new Error(`HWJS-5 fork\xD7dlopen: dlsym(main, "${name2}") slot ${idx} cannot be re-bound in the child (never-silent)`); } const cur = table.get(idx >>> 0); if (cur === null) { tableIndexForget(table); table.set(idx >>> 0, fn2); tableLedgerNoteSet(table, idx >>> 0, fn2); } else if (cur !== fn2) { throw new Error(`HWJS-5 fork\xD7dlopen: dlsym(main, "${name2}") slot ${idx} holds a different function in the child than in the parent (never-silent)`); } if (dlopenMainScopeIndex instanceof Map) dlopenMainScopeIndex.set(String(name2), idx >>> 0); } if (maxCookie >= dlopenNextCookie) dlopenNextCookie = maxCookie + 1; if (!appendOnly) { if (state.nextCookie >>> 0 > dlopenNextCookie) { dlopenNextCookie = state.nextCookie >>> 0; } const parentLen = state.tableLen >>> 0; if (incremental) { try { post({ kind: "dmesg", level: 7, text: `hwjs-dl-placement-catchup pid=${ctrl[C.PID] | 0} tid=${init.tid | 0} placed=${placed} grew=${(table.length >>> 0) - preGrowLen} tableLen=${table.length} nextCookie=${dlopenNextCookie}` }); } catch (_e) { } return; } if (table.length >>> 0 !== parentLen) { throw new Error( `HWJS-5 fork\xD7dlopen: child table length ${table.length} != parent fork-time length ${parentLen} after placement replay \u2014 an append escaped the recorded placements (never-silent).` ); } try { post({ kind: "dmesg", level: 7, text: `hwjs-fork-dlopen-replay pid=${ctrl[C.PID] | 0} placed=${replay.length} deadRanges=${deadRanges.length} tableLen=${table.length} nextCookie=${dlopenNextCookie}` }); } catch (_e) { } } } function dlPlacementPublish(why) { if (!placementCell || (Atomics.load(placementCell, PC_THREADS) | 0) === 0) return 0; const rec = buildDlopenForkRecord(); if (!rec) return 0; trimPublication(rec); rec.replay = rec.replay.map((e) => { if (!placementShipped.has(e.cookie >>> 0)) return e; const { bytes: _b, module: _m, ...rest } = e; return rest; }); if (threadCtx) { const shared = threadCtx.dlEntries ||= /* @__PURE__ */ new Map(); for (const [c, m] of dlopenModules) { if (m && m.handle && !m.mainScope) { shared.set(c >>> 0, m); threadCtxNoteTls(threadCtx, m.handle); } } } const gen = Atomics.add(placementCell, PC_GEN, 1) + 1; placementOwnGens.add(gen); if (gen === placementApplied + 1) placementApplied = gen; for (const e of rec.replay) placementShipped.add(e.cookie >>> 0); post({ kind: "dl-placement-publish", memoryId: init.memoryId | 0, gen, tid: init.tid | 0, why, record: rec }); return gen; } const placementJournaled = /* @__PURE__ */ new WeakMap(); function trimPublication(rec) { rec.fpcastRecs = journalDelta(fpcastProcessRecs, rec.fpcastRecs); if (Array.isArray(rec.neededLibs)) { rec.neededLibs = rec.neededLibs.filter((r) => Array.isArray(r.late) && r.late.length).map((r) => ({ index: r.index, late: r.late })); } delete rec.neededCtorTrampolines; } function journalDelta(census, entries) { if (!census || !Array.isArray(entries)) return entries; const seen = placementJournaled.get(census); if (!seen) { placementJournaled.set(census, new Map(entries)); return entries; } const out = entries.filter(([k, v]) => seen.get(k) !== v); for (const [k, v] of out) seen.set(k, v); return out; } function dlPlacementBehind() { return !!placementCell && (Atomics.load(placementCell, PC_GEN) | 0) > placementApplied; } function dlPlacementLoud(text) { try { post({ kind: "dmesg", level: 3, text }); } catch (_e) { } try { console.error(text); } catch (_e) { } } async function dlPlacementCatchUp() { let pulls = 8 + Math.max(0, (Atomics.load(placementCell, PC_GEN) | 0) - placementApplied); for (; pulls > 0 && dlPlacementBehind(); pulls--) { const gen = Atomics.load(placementCell, PC_GEN) | 0; while (placementApplied < gen && placementOwnGens.has(placementApplied + 1)) placementApplied++; if (placementApplied >= gen) continue; const want = placementApplied + 1; const since = placementApplied; const seq = dlPlacementPullSeq++; const reply = await new Promise((resolve) => { const timer = setTimeout(() => { if (dlPlacementPulls.delete(seq)) resolve({ error: "no reply from the host in 15 s" }); }, 15e3); dlPlacementPulls.set(seq, (m) => { clearTimeout(timer); resolve(m); }); post({ kind: "dl-placement-pull", memoryId: init.memoryId | 0, seq, since, want, have: [...dlopenModules.keys()].map((c) => c >>> 0) }); }); if (!reply || reply.error || !Array.isArray(reply.pubs)) { const why = reply && reply.error || "malformed reply"; if (++placementPullFails < DL_PLACEMENT_PULL_TRIES) { try { post({ kind: "dmesg", level: 4, text: `hwjs-dl-placement pid=${ctrl[C.PID] | 0} tid=${init.tid | 0}: pull ${placementPullFails} of ${DL_PLACEMENT_PULL_TRIES} for generation ${want} failed: ${why}; retrying` }); } catch (_e) { } if (placementLockDepth > 0) return; continue; } placementPullFails = 0; placementApplied = Math.max(placementApplied, want); dlPlacementLoud(`hwjs-dl-placement pid=${ctrl[C.PID] | 0} tid=${init.tid | 0}: could not catch up from generation ${since} to ${want} in ${DL_PLACEMENT_PULL_TRIES} pulls: ${why}; a library another thread loaded is not callable from this thread`); return; } placementApplied = Math.max(placementApplied, want); if (placementPullFails) { try { post({ kind: "dmesg", level: 4, text: `hwjs-dl-placement pid=${ctrl[C.PID] | 0} tid=${init.tid | 0}: generation ${want} applied on pull ${placementPullFails + 1}` }); } catch (_e) { } placementPullFails = 0; } for (const p of reply.pubs) { if (placementOwnGens.has(p.gen | 0)) continue; try { replayForkDlopens(p.record, true); } catch (e) { if (e === HWJS_REAPED_UNWIND) throw e; dlPlacementLoud(`hwjs-dl-placement pid=${ctrl[C.PID] | 0} tid=${init.tid | 0}: generation ${p.gen | 0} from tid ${p.tid | 0} did not apply: ` + (e instanceof Error ? e.message : String(e))); } } } } let placementLockDepth = 0; async function dlPlacementLock() { const me = init.tid | 0 || -1; if (placementLockDepth > 0) { placementLockDepth++; return; } const t0 = Date.now(); for (; ; ) { const cur = Atomics.compareExchange(placementCell, PC_LOCK, 0, me); if (cur === 0) break; if (Date.now() - t0 > 3e4) { dlPlacementLoud(`hwjs-dl-placement pid=${ctrl[C.PID] | 0} tid=${init.tid | 0}: the placement lock is still held by tid ${cur} after 30 s; taking it`); Atomics.store(placementCell, PC_LOCK, me); break; } const w = Atomics.waitAsync(placementCell, PC_LOCK, cur, 50); if (w.async) { try { await w.value; } catch (_e) { } } } placementLockDepth = 1; } function dlPlacementUnlock() { if (--placementLockDepth > 0) return; placementLockDepth = 0; Atomics.store(placementCell, PC_LOCK, 0); Atomics.notify(placementCell, PC_LOCK); } function dlPlacementSignature() { const t = sharedTable instanceof WebAssembly.Table ? sharedTable.length : 0; return `${dlopenModules.size}:${dlopenNextCookie}:${t}:${dlopenDeadRanges.length}`; } async function dlPlacementBegin() { if (!placementCell || (Atomics.load(placementCell, PC_THREADS) | 0) === 0) return null; await dlPlacementLock(); try { await dlPlacementCatchUp(); } catch (e) { dlPlacementUnlock(); throw e; } return { sig: dlPlacementSignature() }; } function dlPlacementEnd(tok, why) { if (!tok) return 0; try { return dlPlacementSignature() !== tok.sig ? dlPlacementPublish(why) : 0; } finally { dlPlacementUnlock(); } } function dlopenCookieNew() { const cookie = dlopenCookieAlloc ? dlopenCookieAlloc(dlopenNextCookie, 1) : dlopenNextCookie; dlopenNextCookie = cookie + 1; return cookie; } function makeMainScopeEntry() { return { mainScope: true, handle: { dylink: { tableSize: 0 }, dlsym: (name2) => mainScopeDlsym(name2), tableIndices: () => [], tableEntries: () => [], unload: () => { } }, moduleId: 0, bytes: null, path: "", memoryBase: 0, tableBase: 0, census: { live: 0, poisoned: false }, xmodRecs: new XmodInputSet() }; } function dladdrObjects() { const record = (paths, h, cookie = 0) => ({ paths, cookie, memoryBase: h.memoryBase >>> 0, memorySize: h.dylink ? h.dylink.memorySize >>> 0 : 0, tableBase: h.tableBase >>> 0, tableSize: h.dylink ? h.dylink.tableSize >>> 0 : 0, tableIndices: () => h.tableIndices(), owns: (fn2) => dladdrExportedFunctions(h).has(fn2) }); const out = []; if (libcSoHandle) out.push(record([libcSoPath], libcSoHandle)); for (const n of neededSoHandles) { if (n && n.handle) { out.push(record(dladdrLibraryPaths(n.name, libraryReadPath(n.digest)), n.handle)); } } for (const [cookie, m] of dlopenModules) { if (!m || m.mainScope || !m.handle) continue; out.push(record( m.internal && m.name ? [m.path, ...dladdrLibraryPaths(m.name)] : [m.path], m.handle, cookie >>> 0 )); } return out; } const dladdrExports = /* @__PURE__ */ new WeakMap(); function dladdrExportedFunctions(h) { const exp = (h.instance ?? h).exports; let fns = dladdrExports.get(exp); if (!fns) { fns = new Set(Object.values(exp).filter((v) => typeof v === "function")); dladdrExports.set(exp, fns); } return fns; } function openMainScope() { const cookie = dlopenCookieNew(); dlopenModules.set(cookie >>> 0, makeMainScopeEntry()); hwjsSliceProgressed = true; if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} DLOPEN-MAIN-SCOPE cookie=${cookie}` }); } catch (_e) { } } return cookie >>> 0; } function openResidentLibc(path) { const cookie = dlopenCookieNew(); const entry = makeMainScopeEntry(); entry.path = path; entry.handle.dlsym = (name2) => libcSoHandle.dlsym(name2); dlopenModules.set(cookie >>> 0, entry); hwjsSliceProgressed = true; if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} DLOPEN-RESIDENT-LIBC cookie=${cookie} path="${path}"` }); } catch (_e) { } } return cookie >>> 0; } function openNeededEntry(path, np) { const rec = neededSoHandles.find((h) => h && h.index === np.index); if (!rec || !rec.handle) return 0; const own = [rec]; const cookie = dlopenCookieNew(); const entry = makeMainScopeEntry(); entry.path = path; entry.handle.dlsym = (name2) => { const fn2 = dlopenSiblingExport(name2, own); if (typeof fn2 !== "function") return dlopenSiblingDataAddress(name2, own) || 0; return mainScopeFunction(name2, userExports, neededSoHandles, mainScopeOrder()) === fn2 ? mainScopeDlsym(name2) : rec.handle.dlsym(name2); }; dlopenModules.set(cookie >>> 0, entry); hwjsSliceProgressed = true; if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} DLOPEN-NEEDED-ENTRY cookie=${cookie} index=${np.index} path="${path}"` }); } catch (_e) { } } return cookie >>> 0; } function openLoadedBySoname(name2) { const hit = dlopenLoadedBySoname( name2, neededPlacements, dlopenModules, (np) => { const sub = neededSubstitutes.get(np.name); const lib = workerSharedLibs.get(np.digest) || (sub ? workerSharedLibs.get(sub) : void 0); if (!lib || !lib.bytes) return null; return lib.bytes instanceof Uint8Array ? lib.bytes : new Uint8Array(lib.bytes); } ); let cookie = 0; if (hit && hit.needed) cookie = openNeededEntry(name2, hit.needed); else if (hit) cookie = reopenDlopenModule(hit.cookie, hit.module, name2); if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} DLOPEN-LOADED name="${name2}" -> ${cookie}` }); } catch (_e) { } } return cookie > 0 ? cookie : -2; } function reopenDlopenModule(cookie, entry, path) { dlopenTakeRef(entry); hwjsSliceProgressed = true; if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} DLOPEN-REOPEN path="${path}" cookie=${cookie} refs=${entry.refs}` }); } catch (_e) { } } return cookie >>> 0; } function lateNeededEntries(r) { const rec = neededSoHandles.find((h) => h && h.index === r.index); return rec && rec.handle ? lateTableEntries(rec.handle.tableEntries(), r.appended) : []; } function adoptLateTableEntries(state, grow = false) { const rtLate = state.hwjsRt && Array.isArray(state.hwjsRt.late) ? state.hwjsRt.late : []; const libcLate = state.libcSo && Array.isArray(state.libcSo.late) ? state.libcSo.late : []; if (grow) { let top = 0; for (const l of [ rtLate, libcLate, ...(Array.isArray(state.neededLibs) ? state.neededLibs : []).map((r) => Array.isArray(r.late) ? r.late : []) ]) { for (const [, idx] of l) top = Math.max(top, (idx >>> 0) + 1); } if (top > sharedTable.length) sharedTable.grow(top - sharedTable.length); } if (rtLate.length && !hwjsRtHandle) { throw new Error("HWJS-5 fork\xD7dlopen: the parent recorded late runtime table slots but the child has no runtime module (never-silent)"); } for (const [name2, idx] of rtLate) hwjsRtHandle.adoptSymbolIndex(String(name2), idx); if (libcLate.length && !libcSoHandle) { throw new Error("HWJS-5 fork\xD7dlopen: the parent recorded late libc.so table slots but the child has no libc.so (never-silent)"); } for (const [name2, idx] of libcLate) libcSoHandle.adoptSymbolIndex(String(name2), idx); for (const r of Array.isArray(state.neededLibs) ? state.neededLibs : []) { const late = Array.isArray(r.late) ? r.late : []; if (!late.length) continue; const rec = neededSoHandles.find((h) => h && h.index === r.index); if (!rec || !rec.handle) { throw new Error(`HWJS-5 fork\xD7dlopen: the parent recorded late table slots for needed entry ${r.index}, which the child did not place (never-silent)`); } for (const [name2, idx] of late) rec.handle.adoptSymbolIndex(String(name2), idx); } } function libcExportsNow() { return libcSoHandle ? (libcSoHandle.instance ?? libcSoHandle).exports : null; } function mainScopeOrder() { return { rtExports: hwjsRtHandle ? (hwjsRtHandle.instance ?? hwjsRtHandle).exports : null, libcExports: libcExportsNow(), mainGotFunc: mainGotFuncNames }; } function rtldNextDlsym(name2, caller) { const handles = rtldNextHandles(caller, name2, { needed: neededSoHandles, libc: libcSoHandle, dlopened: dlopenModules.values() }); if (!handles) { dlopenLastError = `dlsym(RTLD_NEXT, "${name2}"): the calling module is unknown -- dlsym was not called through a module's own dlsym import`; try { post({ kind: "dmesg", level: 4, text: `hwjs-dlsym pid=${ctrl[C.PID] | 0} ${dlopenLastError}` }); } catch (_e) { } return 0; } if (name2.startsWith("__hwjs_") || name2.startsWith("__wasm_")) return 0; for (const h of handles) { const v = h.dlsym(name2) | 0; if (v !== 0) return v; } return 0; } function mainScopeDlsym(name2) { const fn2 = mainScopeFunction(name2, userExports, neededSoHandles, mainScopeOrder()); if (typeof fn2 !== "function") { return mainScopeDataAddress(name2, userExports, neededSoHandles); } const table = sharedTable; if (!(table instanceof WebAssembly.Table) || !(dlopenMainScopeIndex instanceof Map) || !(dlopenGotFuncIndex instanceof Map)) return 0; const mine = dlopenMainScopeIndex.get(name2); if (mine !== void 0 && mine < table.length) { const cur = table.get(mine); if (cur === fn2) return mine; if (cur !== null) { throw new Error(`hwjs-dlopen: dlsym(main, "${name2}") identity drift -- slot ${mine} it was handed out at holds a different function (never-silent)`); } tableIndexForget(table); table.set(mine, fn2); tableLedgerNoteSet(table, mine, fn2); return mine; } { const i = tableSlotOf(table, fn2); if (i >= 0) { dlopenMainScopeIndex.set(name2, i); return i; } } const cached = dlopenGotFuncIndex.get(name2); if (cached !== void 0 && cached < table.length) { const cur = table.get(cached); if (cur !== null && cur !== fn2) { throw new Error(`hwjs-dlopen: dlsym(main, "${name2}") identity drift -- slot ${cached} holds a different function (never-silent)`); } if (cur === null) { tableIndexForget(table); table.set(cached, fn2); tableLedgerNoteSet(table, cached, fn2); } dlopenMainScopeIndex.set(name2, cached); return cached; } const idx = tableReserve(table, 1); tableIndexForget(table); table.grow(idx + 1 - table.length); table.set(idx, fn2); tableLedgerNoteSet(table, idx, fn2); dlopenGotFuncIndex.set(name2, idx); dlopenMainScopeIndex.set(name2, idx); return idx; } function serviceDlopen(pathPtr, yieldWouldBlock = false, reissue = false, loadedOnly = false) { const exp = vmlinuxInstance ? vmlinuxInstance.exports : null; if (!exp || typeof exp.wasm32_user_dlopen_load !== "function" || !init.kernelMemoryWasm) { dlopenLastError = "dlopen refused (ENOSYS): no kernel dlopen staging on this Worker (no vmlinux instance / wasm32_user_dlopen_load)"; return -38; } const table = sharedTable; if (!(table instanceof WebAssembly.Table)) { dlopenLastError = "dlopen refused (ENOSYS): this process is not a dynamic main (no shared __indirect_function_table to load a .so into \u2014 a static image cannot dlopen)"; return -38; } if (loadedOnly) return openLoadedBySoname(readUserCString(pathPtr)); if (readUserCString(pathPtr) === "") return openMainScope(); if (dlopenPending && (dlopenPending.pathPtr !== pathPtr >>> 0 || dlopenPending.path !== readUserCString(pathPtr) || dlopenPending.left && !reissue)) { dlopenPendingDrop(); } let bytes; if (dlopenPending) { bytes = dlopenPending.bytes; } else { const rc = dlopenStagingRead( pathPtr >>> 0, readUserCString(pathPtr), yieldWouldBlock, reissue ); if (rc === HWJS_ERESTART_RESCHED) return HWJS_ERESTART_RESCHED; if (rc < 0) { const left = dlopenLoadPark.orphan && dlopenLoadPark.path !== readUserCString(pathPtr) ? ` while finishing the read of "${dlopenLoadPark.path}" an earlier dlopen left parked` : ""; dlopenLastError = `kernel dlopen staging wasm32_user_dlopen_load("${readUserCString(pathPtr)}") returned ${rc}${left} (the .so could not be resolved/read from the VFS)`; return rc; } bytes = readKernelStagedImage( exp, init.kernelMemoryWasm.buffer, "wasm32_user_dlopen", `staged .so "${readUserCString(pathPtr)}"` ); const releaseCall = () => { exp.wasm32_user_dlopen_release(); return 0; }; if (hwjsLane) hwjsLane.bracket("wasm32_user_dlopen_release", releaseCall); else releaseCall(); } const loadedPath = readUserCString(pathPtr); const digest = sha256Hex(bytes); if (libcSoHandle && libcSoPlacement && libcSoPlacement.digest && digest === libcSoPlacement.digest) { dlopenPendingDrop(); return openResidentLibc(loadedPath); } const np = dlopenNeededEntry(neededPlacements, digest); if (np) { const c = openNeededEntry(loadedPath, np); if (c > 0) { dlopenPendingDrop(); return c; } } const open = dlopenOpenModule(dlopenModules, digest, sha256Hex); if (open) { dlopenPendingDrop(); return reopenDlopenModule(open[0], open[1], loadedPath); } let deps; try { deps = dlopenNeededClosure( pathPtr >>> 0, bytes, loadedPath, yieldWouldBlock, reissue ); } catch (e) { dlopenPendingDrop(); throw e; } if (!Array.isArray(deps)) return deps; for (const dep of deps) { const c = instantiateDlopenModule( dep.bytes, dep.path, { internal: true, name: dep.name, digest: dep.digest || neededDigest(dep.name), ...dep.module ? { module: dep.module } : {} } ); if (c < 0) { dlopenLastError = `while loading ${dep.name.slice(0, -65)}, needed by "${dep.by}": ${dlopenLastError}`; return c; } } const cookie = instantiateDlopenModule(bytes, loadedPath, null); const loaded = cookie > 0 ? dlopenModules.get(cookie >>> 0) : null; if (loaded) loaded.digest = digest; return cookie; } function dlopenPendingDrop() { const p = dlopenPending; dlopenPending = null; if (p && p.scratch) { try { syscallInner(11, p.scratch, 4096, 0, 0, 0, 0); } catch (_e) { } } } function dlopenNeededClosure(pathPtr, bytes, path, yieldWouldBlock, reissue) { const fail = (msg) => { dlopenLastError = `hwjs-dlopen: ${msg} (never-silent)`; dlopenPendingDrop(); try { post({ kind: "user-report", pid: init.pid, message: dlopenLastError }); } catch (_e) { } return -80; }; let p = dlopenPending; if (!p) { let top, topViews; try { top = parseSideModuleNeeded(bytes); topViews = top.views || /* @__PURE__ */ new Map(); } catch (e) { return fail(`"${path}": ${e instanceof Error ? e.message : e}`); } if (top.length === 0) return []; const topRunDirs = top.runpath ? runPathDirs(top.runpath, dirOfPath(path)) : []; p = dlopenPending = { pathPtr, path, bytes, top, queue: top.map((n) => ({ name: n, by: path, byBytes: bytes, view: topViews.get(n), runDirs: topRunDirs })), fetched: /* @__PURE__ */ new Map(), scratch: 0, cand: 0, fetching: null }; } while (p.queue.length) { const { name: name2, by, byBytes, view, runDirs } = p.queue[0]; if (p.fetched.has(name2)) { p.queue.shift(); continue; } const sameSonameOk = view === void 0 ? null : (libBytes) => { try { return neededView(byBytes, libBytes) === view; } catch (_e) { return false; } }; const present = dlopenLibraryPresent(name2, sameSonameOk); if (typeof present === "string") return fail(`"${by}" needs ${name2}, but ${present}`); if (present) { p.queue.shift(); continue; } let got = null; const sub = view !== void 0 ? neededSubstitutes.get(name2) : void 0; const stored = workerSharedLibs.get(neededDigest(name2)) || (sub ? workerSharedLibs.get(sub) : void 0); if (p.fetching !== name2 && stored && stored.bytes) { got = { bytes: stored.bytes instanceof Uint8Array ? stored.bytes : new Uint8Array(stored.bytes), path: libraryReadPath(neededDigest(name2)) || `/usr/lib/${name2}`, stored: true, module: stored.module }; } else { const r = dlopenFetchLibrary( p, name2, yieldWouldBlock, reissue, view !== void 0, runDirs ); p.fetching = isRestartValue(r) ? name2 : null; if (r === HWJS_ERESTART_RESCHED) return r; if (isRestartValue(r)) { p.left = true; dlopenLastError = `hwjs-dlopen: "${by}" needs ${name2}; reading it returned ${r}`; return r; } if (r === -2) { return fail(`"${by}" needs ${name2}, which is in neither /usr/lib nor /lib` + (view !== void 0 ? `, nor is ${neededSoname(name2)}` : "") + (runDirs && runDirs.length ? `, nor in its run path ${runDirs.join(":")}` : "")); } if (typeof r === "number") { dlopenLastError = `hwjs-dlopen: "${by}" needs ${name2}; reading it returned ${r} (never-silent)`; dlopenPendingDrop(); return r; } got = r; } const kept = got.stored ? retainedLibraryInfo2(got.bytes) : null; const gotDigest = kept ? kept.digest : sha256Hex(got.bytes); if (gotDigest !== neededDigest(name2)) { if (view === void 0) { return fail(`"${by}" needs ${name2}, but ${got.path} does not hash to that digest -- a content-addressed library was replaced in place`); } let have; try { have = neededView(byBytes, got.bytes); } catch (e) { return fail(`${got.path}: ${e instanceof Error ? e.message : e}`); } if (have !== view) { return fail(`"${by}" needs ${neededSoname(name2)} ${neededDigest(name2).slice(0, 16)}\u2026, but ${got.path} is another build (${gotDigest.slice(0, 16)}\u2026) whose interface, as "${by}" uses it, differs (view ${have.slice(0, 16)}\u2026, recorded ${view.slice(0, 16)}\u2026)`); } try { post({ kind: "dmesg", level: 5, text: `hwjs-dlopen: "${by}" needs ${neededSoname(name2)} ${neededDigest(name2).slice(0, 16)}\u2026; bound ${got.path}, build ${gotDigest.slice(0, 16)}\u2026, whose interface as "${by}" uses it is the recorded one` }); } catch (_e) { } } let needs, needViews; try { needs = parseSideModuleNeeded(got.bytes); needViews = needs.views || /* @__PURE__ */ new Map(); } catch (e) { return fail(`${got.path}: ${e instanceof Error ? e.message : e}`); } p.fetched.set(name2, { name: name2, by, bytes: got.bytes, path: got.path, needs, digest: gotDigest, ...got.module ? { module: got.module } : {} }); p.queue.shift(); const needRunDirs = needs.runpath ? runPathDirs(needs.runpath, dirOfPath(got.path)) : []; for (const n of needs) { p.queue.push({ name: n, by: got.path, byBytes: got.bytes, view: needViews.get(n), runDirs: needRunDirs }); } } const order = []; const done = /* @__PURE__ */ new Set(); const visit = (n) => { if (done.has(n) || !p.fetched.has(n)) return; done.add(n); const f = p.fetched.get(n); for (const c of f.needs) visit(c); order.push(f); }; for (const n of p.top) visit(n); dlopenPendingDrop(); return order; } function dlopenLibraryPresent(name2, sameSonameOk = null) { return dlopenLibraryPresentIn( name2, neededPlacements, dlopenModules.values(), sha256Hex, sameSonameOk && ((entry) => { const lib = entry.bytes ? entry : workerSharedLibs.get(entry.digest); if (!lib || !lib.bytes) return false; return sameSonameOk(lib.bytes instanceof Uint8Array ? lib.bytes : new Uint8Array(lib.bytes)); }) ); } function dlopenStagingRead(ptr, path, yieldWouldBlock, reissue = false) { const exp = vmlinuxInstance.exports; const loadCall = () => exp.wasm32_user_dlopen_load(ptr) | 0; const issue = () => { try { return driveWholeFileRead( "dlopen-load", SYS_WASM_DLOPEN_LOAD, () => exp.wasm_syscall(SYS_WASM_DLOPEN_LOAD, ptr, 0, 0, 0, 0, 0) | 0, () => hwjsLane ? hwjsLane.bracket("wasm32_user_dlopen_load", loadCall) : loadCall(), dlopenLoadRoute, dlopenLoadChain, yieldWouldBlock ) | 0; } catch (e) { dlopenLoadPark.path = null; dlopenLoadPark.orphan = false; throw e; } }; while (dlopenLoadPark.path !== null && (dlopenLoadPark.orphan && !reissue || dlopenLoadPark.path !== path)) { const rc2 = issue(); if (isRestartValue(rc2)) { if (rc2 !== HWJS_ERESTART_RESCHED) dlopenLoadPark.orphan = true; return rc2; } const left = dlopenLoadPark.path; dlopenLoadPark.path = null; dlopenLoadPark.orphan = false; if (rc2 >= 0) { const releaseCall = () => { exp.wasm32_user_dlopen_release(); return 0; }; if (hwjsLane) hwjsLane.bracket("wasm32_user_dlopen_release", releaseCall); else releaseCall(); } try { post({ kind: "dmesg", level: 6, text: `hwjs-dlopen: pid=${init.pid} finished the parked staging read of "${left}" (rc=${rc2}) and dropped it before reading "${path}"` }); } catch (_e) { } } const rc = issue(); dlopenLoadPark.path = isRestartValue(rc) ? path : null; dlopenLoadPark.orphan = isRestartValue(rc) && rc !== HWJS_ERESTART_RESCHED; return rc; } function dlopenFetchLibrary(p, name2, yieldWouldBlock, reissue, bySoname = false, runDirs = []) { const exp = vmlinuxInstance.exports; const fixed = bySoname ? neededLibraryPaths(name2) : neededLibraryPaths(name2).slice(0, 2); const cands = runDirs.length ? [...fixed, ...ldLibraryPathCandidates(runDirs, name2)] : fixed; if (!p.scratch) { const a = syscall( 9, 0, 4096, 3, 34, -1, 0 ) | 0; if (a <= 0) return -12; p.scratch = a >>> 0; p.cand = 0; p.scratchFor = ""; } for (; p.cand < cands.length; p.cand++) { const path = cands[p.cand]; if (p.scratchFor !== path) { const enc2 = new TextEncoder().encode(path); const u8 = new Uint8Array(init.memory.buffer); u8.set(enc2, p.scratch); u8[p.scratch + enc2.length] = 0; p.scratchFor = path; } const rc = dlopenStagingRead(p.scratch, path, yieldWouldBlock, reissue); if (isRestartValue(rc)) return rc; const viaRunPath = p.cand >= fixed.length; if ((rc === -2 || rc < 0 && viaRunPath) && p.cand + 1 < cands.length) continue; if (rc < 0) { p.cand = 0; p.scratchFor = ""; return viaRunPath ? -2 : rc; } const bytes = readKernelStagedImage( exp, init.kernelMemoryWasm.buffer, "wasm32_user_dlopen", `staged .so "${path}"` ); const releaseCall = () => { exp.wasm32_user_dlopen_release(); return 0; }; if (hwjsLane) hwjsLane.bracket("wasm32_user_dlopen_release", releaseCall); else releaseCall(); p.cand = 0; p.scratchFor = ""; return { bytes, path }; } p.cand = 0; p.scratchFor = ""; return -2; } function instantiateDlopenModule(bytes, loadedPath, extra) { const exp = vmlinuxInstance.exports; const table = sharedTable; const allocMemory = (sz, _align) => { const redOom = (globalThis.process?.env?.HWJS_RED_DLOPEN_OOM || "") === "1"; const a = redOom ? 0 : syscall( 9, 0, sz | 0, 3, 34, -1, 0 ) | 0; if (a <= 0) { throw new Error( `hwjs-dlopen: SYS_mmap for the .so data region (${sz}B) returned ${a} (never-silent OOM)` ); } return a >>> 0; }; const id = typeof exp.__hwjs_alloc_module_id === "function" ? exp.__hwjs_alloc_module_id() | 0 : 0; const census = { live: 0, poisoned: false }; const xmodRecs = new XmodInputSet(); const xmodRegistrar = { imported: false }; const dlsymCaller = { kind: "dlopen" }; const xmodArm = { marshal: false }; const resolveImport = makeXmodConsultResolveImport( makeFrameCensusResolveImport( withDlsymCaller(makeDlopenResolveImport(loadedPath), dlsymCaller), census, loadedPath ), xmodRecs, xmodRegistrar, xmodArm ); const redFlag = globalThis.process?.env?.HWJS_RED_NO_CTORS || ""; const redNoCtors = redFlag === "1" || redFlag.startsWith("/") && redFlag === loadedPath; const loadBytes = redNoCtors ? stripStartSection(bytes) : bytes; { const dylinkInfo = parseDylink0(loadBytes); const soNeeded = dylinkInfo && Array.isArray(dylinkInfo.needed) ? dylinkInfo.needed.filter((n) => /^libc\.so\./.test(String(n))) : []; for (const n of soNeeded) { if (!libcSoPlacement) { dlopenLastError = `hwjs-libc: "${loadedPath}" needs ${n} but this process runs NO shared libc.so \u2014 a shared-libc .so cannot load into a static-libc process (never-silent).`; post({ kind: "user-report", pid: init.pid, message: dlopenLastError }); return -80; } if (n !== `libc.so.${libcSoPlacement.digest}`) { dlopenLastError = `hwjs-libc: DIGEST SKEW \u2014 "${loadedPath}" needs ${String(n).slice(0, 24)}\u2026 but this process loaded libc.so.${libcSoPlacement.digest.slice(0, 16)}\u2026 (a .so of a different libc generation; PLAN-DYNAMIC-LIBC \xA73.2; never-silent).`; post({ kind: "user-report", pid: init.pid, message: dlopenLastError }); return -80; } } const soManifest = parseHwjsAbi(loadBytes); if (soManifest && soManifest.manifestVersion >= 2 && soManifest.suspenderDigestLo64 && soManifest.suspenderDigestLo64 !== "0000000000000000") { const procLo64 = libcSoPlacement ? libcSoPlacement.suspenderDigestLo64 : null; if (soManifest.suspenderDigestLo64 !== procLo64) { dlopenLastError = `hwjs-libc: SUSPENDER-PARTITION DIGEST SKEW \u2014 "${loadedPath}" was linked against partition ${soManifest.suspenderDigestLo64}\u2026 but this process's libc.so records ${procLo64 ?? ""}\u2026 (PLAN-DYNAMIC-LIBC \xA73.2; never-silent).`; post({ kind: "user-report", pid: init.pid, message: dlopenLastError }); return -80; } } if (soManifest) { const soCheckEmitting = !!(soManifest.flags && soManifest.flags.checkEmitting); const procCheckEmitting = libcSoPlacement ? !!libcSoPlacement.checkEmitting : mainCheckEmitting; if (soCheckEmitting !== procCheckEmitting) { dlopenLastError = `hwjs-dlopen: CHECK-EMITTING MISMATCH \u2014 "${loadedPath}" attests check_emitting=${soCheckEmitting ? 1 : 0} (hwjs.abi flags bit4) but this process (${libcSoPlacement ? "libc.so " + libcSoPlacement.digest.slice(0, 16) + "\u2026" : "main image"}) attests check_emitting=${procCheckEmitting ? 1 : 0}. Mixing check-emitting and non-check-emitting modules lets a status-channel throw/longjmp transit an uninstrumented frame SILENTLY (PLAN-CXX-STATUS-CHANNEL \xA77, I3). Rebuild the .so and the process images in lockstep (never-silent).`; post({ kind: "user-report", pid: init.pid, message: dlopenLastError }); return -80; } const soLaneAddressed = !!(soManifest.flags && soManifest.flags.laneAddressed); const procLaneAddressed = libcSoPlacement ? !!libcSoPlacement.laneAddressed : mainLaneAddressed; if (soLaneAddressed !== procLaneAddressed) { dlopenLastError = `hwjs-dlopen: LANE-ADDRESSED MISMATCH \u2014 "${loadedPath}" attests lane_addressed=${soLaneAddressed ? 1 : 0} (hwjs.abi flags bit5) but this process (${libcSoPlacement ? "libc.so " + libcSoPlacement.digest.slice(0, 16) + "\u2026" : "main image"}) attests lane_addressed=${procLaneAddressed ? 1 : 0}. Mixing a lane-addressed module with a lane-unaware one lets the lane-unaware side read the INITIAL thread's status word from ANY thread \u2014 silent transit under threads (I3-2; PLAN-THREADS-SINGLE-MEMORY \xA74 step 2). Rebuild the .so and the process images in lockstep (never-silent).`; post({ kind: "user-report", pid: init.pid, message: dlopenLastError }); return -80; } } } const held = extra ? workerSharedLibs.get(extra.digest) : void 0; const compileModule = (b) => { const r = extra && extra.module && b === bytes ? storedSoModule(extra.module, extra.digest) : compileSoModule( b, held && held.bytes === b ? extra.digest : void 0 ); xmodArm.marshal = xmodMarshalArmed(r.module); try { post({ kind: "dmesg", level: 6, text: `HWJS70-SOCACHE pid=${ctrl[C.PID] | 0} ${r.cached ? "HIT " : "COMPILE"} path="${loadedPath}" len=${b.length} key=${r.key} ` + soModuleCacheStats() }); } catch (_e) { } return r.module; }; let h; { h = loadSharedObject({ wasmBytes: loadBytes, memory: init.memory, table, allocMemory, moduleId: id, soPath: loadedPath, compileModule, resolveImport, /* hardwarejs#34: after the main, its needed entries and the modules * already dlopen'd, a preemptible name binds to the module's own * definition -- the end of ELF's search order for this object. */ bindOwnDefinitions: true, /* issue #45 gap 2: main-owned GOT.mem data (environ/stdout/...) — * resolved against the main's address-bearing data exports. */ resolveDataAddress: makeDlopenResolveDataAddress(), /* issue #45 gap 3: process-wide GOT.func append cache (one table * identity per main function across all dlopen'd modules). */ gotFuncIndex: dlopenGotFuncIndex, /* Share the MAIN's exported __stack_pointer with the .so (SEMANTICS * INV-3: one sp across parks). May be undefined for a main that does * not export it — the loader only requires it if the .so IMPORTS sp. */ stackPointer: userExports ? userExports.__stack_pointer : void 0, /* The lane's budget; undefined (a module budget of its own) only * when no lane budget was made for this image. */ budgetGlobal: hwjsLaneBudget || void 0, /* STATUS-CHANNEL-CONTRACT §10 loader acceptance: the .so's drive_abi * must equal the RUNNING MAIN's (3 flat | 4 status-channel); the * loader refuses a mix. Undefined (no sentinel) keeps the loader's * historical flat pin. */ mainDriveAbi: userExports && typeof userExports.__hwjs_drive_abi === "function" ? userExports.__hwjs_drive_abi() | 0 : void 0, /* PLAN-THREADS-SINGLE-MEMORY §4 step 2: the process lane posture * (checkLoadPolicy refuses a bit5 disagreement — I3-2), and the * per-instance channel base for a lane-addressed .so's * env.__hwjs_status_channel_addr import: THIS thread's runtime block * (its channel is the block's first member). undefined before a * block is bound — the loader then refuses a .so that imports the * global (loud, never a fabricated address-0 binding). */ mainLaneAddressed: libcSoPlacement ? !!libcSoPlacement.laneAddressed : mainLaneAddressed, /* On a shared process image the context's channel Global, which the * register file switches: the module is entered by every thread. */ ...threadCtx ? { statusChannelGlobal: threadCtx.chanGlobal } : { statusChannelAddr: currentTcb ? currentTcb >>> 0 : void 0 }, /* The no-op park import is CORRECT BY DESIGN: it matches the main's * own hwjs_suspend.park no-op boundary — suspension happens IN WASM * (the transform parks by returning through __hwjs_xfer_park), the * import is only the marker boundary. Do not "fix" it. */ parkImport: () => { }, /* hwjs-cc#106: this Instance first initialises the module's memory, * so lld's start function chose the loading thread's TLS block; the * loader re-runs __wasm_init_tls over it to apply the TLS relocations * the start function does not. */ sideTls: { mode: "fresh" } }); armModuleBudget(h); if (redNoCtors) { if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} RED-NO-CTORS: stripped start + skipped runCtors for "${loadedPath}" moduleId=${id} (its \xA7E8 register ctors did NOT run \u2192 its targets stay UNREGISTERED \u2192 consult UNRESOLVED \u2192 e8_refuse)` }); } catch (_e) { } } } else { runDlopenModuleCtors({ exports: (h.instance ?? h).exports, /* __wasm_call_ctors -> its records, under @__hwjs_module_id */ runCtors: () => threadCtx ? threadCtxCall(threadCtx, threadRec, () => h.runCtors()) : h.runCtors(), runners: dlopenCtorRunners, soname: loadedPath }); } } const cookie = dlopenCookieNew(); dlopenModules.set(cookie >>> 0, { handle: h, moduleId: id, bytes, path: loadedPath, memoryBase: h.memoryBase >>> 0, tableBase: h.tableBase >>> 0, census, xmodRecs, xmodRegistrar, dlsymCaller, ...extra || {} }); hwjsSliceProgressed = true; if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} DLOPEN-OK path="${loadedPath}" cookie=${cookie} moduleId=${id} memBase=0x${(h.memoryBase >>> 0).toString(16)} tableBase=${h.tableBase}` }); } catch (_e) { } } return cookie >>> 0; } const wasmSyscallStats = new Int32Array(WASM_SYSCALL_NR_MAX); const wasmSyscallStatsObject = () => { const o = {}; for (let i = 0; i < wasmSyscallStats.length; i++) if (wasmSyscallStats[i] !== 0) o[i] = wasmSyscallStats[i]; return o; }; let coopWaitViolations = 0; let coopEintrParkReported = false; let coopFutexParkReported = false; let syncRestartViolations = 0; let mergedHostRpcRefusals = 0; let mergedRpcPending = null; let mergedRpcCompleted = 0; let mergedRpcParks = 0; let mergedRpcInPlace = 0; let mergedRpcDoorAsync = 0; const MERGED_SYSCALL_SYNC_MSG = Object.freeze({ kind: "syscall-sync", routeKey: init.routeKey }); const MERGED_RPC_PARK_CAP = 2e4; let veneerParkReported = false; function announceExecLoadYield(site, path) { if (execImageLoader.blocks() !== 1) return; try { post({ kind: "dmesg", level: 6, text: `hwjs-exec EXEC-LOAD-YIELD pid=${ctrl[C.PID] | 0} tid=${init.tid | 0} rt=${init.rtThread ? 1 : 0} mode=${init.mode} cpu=${init.cpuId ?? "?"} site=${site}: the exec load of "${path ?? "?"}" block-parked (-517) with its chain preserved, and this Worker's JS event loop was HANDED BACK before the re-issue \u2014 a co-resident (canonically the single-threaded FUSE server this load is waiting on) gets real turns instead of being starved to the deadline` }); } catch (_e) { } } function announceExecLoadInline(path, blocks) { try { post({ kind: "dmesg", level: 4, text: `hwjs-exec EXEC-LOAD-INLINE pid=${ctrl[C.PID] | 0} tid=${init.tid | 0} rt=${init.rtThread ? 1 : 0} mode=${init.mode} cpu=${init.cpuId ?? "?"}: the exec load of "${path ?? "?"}" block-parked ${blocks | 0} time(s), but this image does not absorb the sentinel at raw syscalls (__hwjs_libc_syscall_park_abi ${libcParksAnySyscall ? "=1" : "absent"}), so execve cannot be told to retry and the host drove the load IN PLACE \u2014 this Worker's event loop, and every co-resident task with it, was frozen for the duration. Loud, attributed, and expected until this libc nominates the veneer.` }); } catch (_e) { } } const T67 = !!globalThis.process?.env?.HWJS_67_TRACE; const t67 = T67 ? { ring: [], /* last 48 completed syscalls {nr, ret} */ inSysNr: -1, inSysT: 0, statuses: /* @__PURE__ */ Object.create(null), lastStatus: -1, lastStatusT: 0, inWasm: false, lastDriveEnterT: 0, lastDriveRetT: 0, coopWaits: 0, reschedRestarts: 0, futex: null, /* in-flight synchronous FUTEX_WAIT {uaddr, val, ms, t} */ futexWaits: 0, reasonAddr: 0, resultAddr: 0, timer: null } : null; const t67RecordSys = (nr, ret) => { t67.ring.push(((nr | 0) << 0) + ":" + (ret | 0)); if (t67.ring.length > 48) t67.ring.shift(); t67.inSysNr = -1; }; const t67Sample = (tag) => { if (!t67) return; const now = Date.now(); const st = Object.entries(t67.statuses).map(([k, v]) => `${k}=${v}`).join(","); try { post({ kind: "dmesg", level: 6, text: `t67 pid=${ctrl[C.PID] | 0} ${tag} inWasm=${t67.inWasm ? 1 : 0} lastStatus=0x${(t67.lastStatus >>> 0).toString(16)}@-${now - t67.lastStatusT}ms driveEnter@-${now - t67.lastDriveEnterT}ms driveRet@-${now - t67.lastDriveRetT}ms statuses{${st}} coopWaits=${t67.coopWaits} reschedRestarts=${t67.reschedRestarts} inSys=${t67.inSysNr}@-${t67.inSysNr >= 0 ? now - t67.inSysT : 0}ms futexWaits=${t67.futexWaits} inFutex=${t67.futex ? JSON.stringify(t67.futex) : 0} reason=${t67.reasonAddr ? uU32()[t67.reasonAddr >> 2] >>> 0 : -1} result=${t67.resultAddr ? uU32()[t67.resultAddr >> 2] | 0 : -1} sysRing=[${t67.ring.slice(-24).join(" ")}]` }); } catch (_e) { } }; const kernelRoutedLowFds = /* @__PURE__ */ new Set(); let hwjsMmapSharedSnapshotWarned = false; let syncRestartGaveUp = -1; const fileMapper = makeFileMapper({ alloc: (req) => syscallInner( 9, 0, req.len, req.prot, 34, -1, 0 ), free: (addr, len) => { syscallInner(11, addr, len, 0, 0, 0, 0); }, /* off+done < 2^32 (off/len are u32 and user_memory <= 1 GiB), so pos_hi * is always 0 on this substrate. */ read: (req, addr, done) => { syncRestartGaveUp = -1; return syscallInner( 17, req.mfd, addr + done | 0, req.len - done | 0, req.off + done | 0, 0, 0 ); }, held: () => syncRestartGaveUp === 17, guestResumes: () => libcResumesMmap && coopParkCapableFor( 9 /* __NR_mmap */ ), /* A pool resident or laned thread shares its event loop with other * tasks, one of which may be what produces the reply, and on the merged * lane the device backends share its thread. Blocking there is what the * cooperative park exists to avoid, so only a Worker of its own waits. */ canWait: () => !coopParkCapableFor( 9 /* __NR_mmap */ ), wait: () => { awaitTaskWakeSlice(); stwHoldSyncIfRequested(); }, /* close, dup2, dup3, close_range, as this task issued them: the calls * after which an fd may name another file. */ epoch: () => (wasmSyscallStats[3] | 0) + (wasmSyscallStats[33] | 0) + (wasmSyscallStats[292] | 0) + (wasmSyscallStats[436] | 0), restartCap: HWJS_RESCHED_RESTART_CAP }); let sharedMapsImageInstalled = false; const sharedMaps = makeSharedFileMaps({ sys: (nr, a0, a1, a2, a3, a4, a5) => syscallInner(nr, a0, a1, a2, a3, a4, a5), mem: () => uU8(), gen: new Int32Array(init.fileMapGen instanceof SharedArrayBuffer && init.fileMapGen.byteLength >= 12 ? init.fileMapGen : new SharedArrayBuffer(FILE_MAP_GEN_WORDS * 4)), canWait: () => !coopParkCapableFor( 17 /* __NR_pread64 */ ), wait: () => { awaitTaskWakeSlice(); stwHoldSyncIfRequested(); }, restartCap: HWJS_RESCHED_RESTART_CAP, /* A signal restart is answered the guest's way whatever the call; a * park only where this libc parks at that call, and an mmap the way a * held population read answers it. */ answer: (nr, r) => { if ((r | 0) !== HWJS_ERESTART_RESCHED) return r; if ((nr | 0) === 9 && libcResumesMmap && coopParkCapableFor(9)) return HWJS_EMMAP_PARKED; return blockParkGoesToGuest(nr) ? r : null; }, /* The park ABI export does not mean glibc parks at every site: its * synchronous INTERNAL_SYSCALL and .S stubs (clock_gettime, ioctl, ...) * return a restart value as an error. Only the cancellable calls are * issued again by both libcs. Not mmap: the user runtime grows its * frame arena with a raw anonymous mmap that takes any answer as out of * memory. */ reissues: (nr) => coopParkCapableFor(nr) && HWJS_CANCELLABLE_SYSCALLS.has(nr), epoch: () => (wasmSyscallStats[3] | 0) + (wasmSyscallStats[33] | 0) + (wasmSyscallStats[292] | 0) + (wasmSyscallStats[436] | 0), log: (level, text) => { try { post({ kind: "dmesg", level, text: `hwjs-mmap pid=${ctrl[C.PID] | 0} ${text}` }); } catch (_e) { } } }); const D1_TRACE_FD = !!globalThis.process?.env?.D1_TRACE_FD; const D1_TRACE_SYS = !!globalThis.process?.env?.D1_TRACE_SYS; const d1SysPath = (nr, a0, a1) => { if (!D1_TRACE_SYS) return ""; const aAt = /* @__PURE__ */ new Set([ 257, 262, 267, 269, 439, 322, 332, 280 /*utimensat*/ ]); const a0p = /* @__PURE__ */ new Set([ 4, 6, 21, 89, 79, 59, 80, 2, 87, 161 /*chroot*/ ]); let p = -1; if (aAt.has(nr)) p = a1 >>> 0; else if (a0p.has(nr)) p = a0 >>> 0; if (p <= 0) return ""; try { const u8 = new Uint8Array(init.memory.buffer); let e = p; while (e < u8.length && e < p + 256 && u8[e] !== 0) e++; return decodeMaybeShared3(u8.subarray(p, e)); } catch (_e) { return ""; } }; { const bootFdActions = Array.isArray(init.fdActions) ? init.fdActions : null; if (bootFdActions) { for (let i = 0; i < bootFdActions.length; i++) { const act = bootFdActions[i]; if ((act[0] | 0) === 0) { const newfd = act[2] | 0; if (newfd >= 0 && newfd <= 2) kernelRoutedLowFds.add(newfd); } } } if (Array.isArray(init.lowFdRoutes)) { for (const fd of init.lowFdRoutes) { const n = fd | 0; if (n >= 0 && n <= 2) kernelRoutedLowFds.add(n); } } if (init.sharedFileMaps && typeof init.sharedFileMaps === "object") sharedMaps.adopt(init.sharedFileMaps); } const SYS_FUTEX = 202; const SYS_SCHED_YIELD = 24; const FUTEX_WAIT = 0; const FUTEX_WAKE = 1; const FUTEX_REQUEUE = 3; const FUTEX_CMP_REQUEUE = 4; const FUTEX_WAIT_BITSET = 9; const FUTEX_WAKE_BITSET = 10; const FUTEX_PRIVATE_FLAG = 128; const FUTEX_CLOCK_REALTIME = 256; const FUTEX_OP_MASK = ~(FUTEX_PRIVATE_FLAG | FUTEX_CLOCK_REALTIME) & 255; const FUTEX_COOP_WAIT = 1073741824; let pendingCoopFutex = null; let coopProgressSeq = 0; const RED_FUTEX_TIMED_LEG = !!globalThis.process?.env?.HWJS_RED_FUTEX_TIMED_LEG; const E_INTR = -4; const E_AGAIN = -11; const E_TIMEDOUT = -110; const E_INVAL = -22; const E_NOSYS = -38; let _uBuf = null, _uI32 = null, _uU32 = null, _uU8 = null; let _uPages = -1, _uPagesOf = void 0, _uPagesMem = null; const refreshUserViews = () => { if (_uPagesMem !== init.memory) { _uPagesMem = init.memory; _uPagesOf = uaccessCopiesFor(init.memory, init.kernelMemoryWasm)?.user_pages ?? null; _uPages = -1; } if (_uPagesOf !== null) { const pages2 = _uPagesOf(); if (pages2 === _uPages) return; _uPages = pages2; } const b = init.memory.buffer; if (b !== _uBuf) { _uBuf = b; _uI32 = new Int32Array(b); _uU32 = new Uint32Array(b); _uU8 = new Uint8Array(b); } }; const uI32 = () => { refreshUserViews(); return _uI32; }; const uU32 = () => { refreshUserViews(); return _uU32; }; const uU8 = () => { refreshUserViews(); return _uU8; }; const kernelI32 = init.kernelMemoryWasm ?? null; let kernelI32Buf = kernelI32 ? kernelI32.buffer : null; let kernelI32View = kernelI32Buf ? new Int32Array(kernelI32Buf) : null; const kernelI32Live = () => { if (kernelI32 === null) return null; const b = kernelI32.buffer; if (b !== kernelI32Buf) { kernelI32Buf = b; kernelI32View = new Int32Array(b); } return kernelI32View; }; const signalPendingIdx = typeof init.signalPendingOffset === "number" && (init.signalPendingOffset & 3) === 0 ? init.signalPendingOffset >>> 2 : -1; function signalPending() { return wasmSignalPendingIn(uI32(), signalPendingIdx); } function deliverableSignalPending() { if (signalPendingIdx < 0) return false; const lo = Atomics.load(uI32(), signalPendingIdx) | 0; const hi = Atomics.load(uI32(), signalPendingIdx + 1) | 0; if (lo === 0 && hi === 0) return false; const mlo = Atomics.load(uI32(), signalPendingIdx + 4) | 0; const mhi = Atomics.load(uI32(), signalPendingIdx + 5) | 0; return (lo & ~mlo | hi & ~mhi) !== 0; } let futexEintrStreak = 0; let futexEintrUaddr = 0; const FUTEX_EINTR_STORM_THRESHOLD = 5e3; function futexEintr(uaddr) { if (uaddr >>> 0 === futexEintrUaddr) futexEintrStreak++; else { futexEintrUaddr = uaddr >>> 0; futexEintrStreak = 1; } if (futexEintrStreak === FUTEX_EINTR_STORM_THRESHOLD || futexEintrStreak % (FUTEX_EINTR_STORM_THRESHOLD * 40) === 0) { const lo = signalPendingIdx >= 0 ? Atomics.load(uI32(), signalPendingIdx) >>> 0 : 0; const hi = signalPendingIdx >= 0 ? Atomics.load(uI32(), signalPendingIdx + 1) >>> 0 : 0; const mlo = signalPendingIdx >= 0 ? Atomics.load(uI32(), signalPendingIdx + 4) >>> 0 : 0; const mhi = signalPendingIdx >= 0 ? Atomics.load(uI32(), signalPendingIdx + 5) >>> 0 : 0; const msg = `hwjs-futex EINTR-STORM pid=${ctrl[C.PID] | 0} tid=${init.tid}: ${futexEintrStreak} consecutive FUTEX_WAIT -EINTRs at uaddr=0x${(uaddr >>> 0).toString(16)} \u2014 a pending signal (pending=0x${hi.toString(16)}:${lo.toString(16)} mask=0x${mhi.toString(16)}:${mlo.toString(16)}) is not being dispatched/cleared by the guest between waits: signal-delivery livelock (the caller loops on EINTR without crossing a dispatch point). Loud witness, not a behavior change.`; try { post({ kind: "user-report", pid: init.pid, message: msg }); } catch (_e) { } try { console.error(`[hwjs-futex pid=${ctrl[C.PID] | 0}] ${msg}`); } catch (_e) { } } return E_INTR; } let sigchldArmed = false; const RED_SIGCHLD_ARM_WNOHANG = !!globalThis.process?.env?.HWJS_RED_SIGCHLD_ARM_WNOHANG; const RED_SIGCHLD_REGION_WRITE = !!globalThis.process?.env?.HWJS_RED_SIGCHLD_REGION_WRITE; function askKernelRepublish() { const ex = vmlinuxInstance && vmlinuxInstance.exports; if (!ex || typeof ex.__wasm32_kernel_signal_pending_republish !== "function") return -1; try { return ex.__wasm32_kernel_signal_pending_republish() | 0; } catch (_e) { return -1; } } const sigchldMark = makeSigchldReassert({ getI32: () => uI32(), getIdx: () => signalPendingIdx, inExecWindow: () => execWindowOpen(), askKernel: askKernelRepublish, red: { hostWritesBit: RED_SIGCHLD_REGION_WRITE } }); const RED_HOSTWAIT_NO_REPUBLISH = !!globalThis.process?.env?.HWJS_RED_HOSTWAIT_NO_REPUBLISH; const hostWaitSignals = makeHostWaitSignals({ getI32: () => uI32(), getIdx: () => signalPendingIdx, getWakeSeq: () => { const idx = taskWakeIdx(); return idx < 0 ? null : Atomics.load(kernelI32Live(), idx) | 0; }, askKernel: askKernelRepublish, red: { noAsk: RED_HOSTWAIT_NO_REPUBLISH } }); function hostWaitDieOfSigkill() { return syscallInner(SYS_WASM_EXIT_BY_SIGNAL, 9, 0, 0, 0, 0, 0); } function sigchldPendingNow() { return sigchldMark.pendingNow(); } function maybeReassertSigchldOnWake() { sigchldMark.maybeReassert(sigchldArmed); } function readGuestTimespec64Ns(tp) { const idx = tp >>> 2; const secLo = uU32()[idx] >>> 0; const secHi = uU32()[idx + 1] | 0; const nsec = uU32()[idx + 2] >>> 0; const sec = BigInt(secHi) * 4294967296n + BigInt(secLo); if (sec < 0n || nsec >= 1e9) return null; return sec * 1000000000n + BigInt(nsec); } function guestClockNowNs(clockid, scratchPtr) { if (vmlinuxInstance && typeof vmlinuxInstance.exports.wasm_syscall === "function" && perProcessTaskAddr !== 0) { const idx = scratchPtr >>> 2; const s0 = uU32()[idx], s1 = uU32()[idx + 1], s2 = uU32()[idx + 2], s3 = uU32()[idx + 3]; try { const call = () => vmlinuxInstance.exports.wasm_syscall( 228, clockid | 0, scratchPtr | 0, 0, 0, 0, 0 ); const r = (hwjsLane ? hwjsLane.dispatchSyscall(228, call) : call()) | 0; if (r === 0) { const lo = uU32()[idx] >>> 0, hi = uU32()[idx + 1] | 0, ns = uU32()[idx + 2] >>> 0; return (BigInt(hi) * 4294967296n + BigInt(lo)) * 1000000000n + BigInt(ns); } } catch (_e) { } finally { uU32()[idx] = s0; uU32()[idx + 1] = s1; uU32()[idx + 2] = s2; uU32()[idx + 3] = s3; } } if (clockid === 0) { if (typeof performance !== "undefined" && performance.now && typeof performance.timeOrigin === "number") { return BigInt(Math.round( (performance.timeOrigin + performance.now()) * 1e6 )); } return BigInt(Date.now()) * 1000000n; } return null; } function handleFutex(uaddr, futex_op, val, timeout_ptr, _uaddr2, _val3) { const op = futex_op & FUTEX_OP_MASK; if (pendingCoopFutex && !((op === FUTEX_WAIT || op === FUTEX_WAIT_BITSET) && (futex_op & FUTEX_COOP_WAIT) !== 0)) { pendingCoopFutex = null; } if (globalThis.process?.env?.HWJS_DBG_FUTEX) { try { const tp = timeout_ptr >>> 0; let ts = "null"; if (tp) { const w0 = uU32()[tp >>> 2], w1 = uU32()[(tp >>> 2) + 1], w2 = uU32()[(tp >>> 2) + 2], w3 = uU32()[(tp >>> 2) + 3]; ts = `[${w0},${w1},${w2},${w3}]`; } const sIdx = signalPendingIdx; const sl = sIdx >= 0 ? (Atomics.load(uI32(), sIdx) >>> 0).toString(16) : "n/a"; const sm = sIdx >= 0 ? (Atomics.load(uI32(), sIdx + 4) >>> 0).toString(16) : "n/a"; console.error(`[FUTEX-DBG pid=${ctrl[C.PID] | 0}] raw_op=0x${(futex_op >>> 0).toString(16)} op=${op} uaddr=0x${(uaddr >>> 0).toString(16)} val=${val | 0} tp=0x${(timeout_ptr >>> 0).toString(16)} ts32words=${ts} sigRegionOff=0x${sIdx >= 0 ? (sIdx << 2).toString(16) : "-"} lo=0x${sl} mlo=0x${sm} deliverable=${deliverableSignalPending() ? 1 : 0}`); } catch (_e) { } } if ((uaddr & 3) !== 0) return E_INVAL; const i32_idx = uaddr >>> 2; if (op === FUTEX_WAIT || op === FUTEX_WAIT_BITSET && !RED_FUTEX_TIMED_LEG) { if (op === FUTEX_WAIT_BITSET && (_val3 | 0) === 0) return E_INVAL; hostWaitSignals.refresh(); if (sched && hostWaitSignals.sigkillPending()) { pendingCoopFutex = null; return hostWaitDieOfSigkill(); } if (deliverableSignalPending()) { const streakAtUaddr = uaddr >>> 0 === futexEintrUaddr ? futexEintrStreak : 0; if (sched && hwjsDrive && (futex_op & FUTEX_COOP_WAIT) !== 0 && streakAtUaddr >= FUTEX_EINTR_STORM_THRESHOLD) { if (!coopEintrParkReported) { coopEintrParkReported = true; const m = `hwjs-coopwait EINTR-STORM PARK pid=${ctrl[C.PID] | 0} tid=${init.tid | 0} rt=${init.rtThread ? 1 : 0}: ${streakAtUaddr} consecutive FUTEX_WAIT -EINTRs at uaddr=0x${(uaddr >>> 0).toString(16)} proved this caller discards EINTR. As a POOL RESIDENT that loop runs entirely inside the wasm drive and FREEZES the shared CPU Worker \u2014 every co-resident task and its onmessage. Converting to the cooperative park so the pump can yield. The underlying defect is upstream: a deliverable signal is pending and the guest never crosses a dispatch point (loud, attributed).`; try { post({ kind: "dmesg", level: 3, text: m }); } catch (_e) { } try { post({ kind: "user-report", pid: ctrl[C.PID] | 0, message: m }); } catch (_e) { } } coopWaitViolations++; pendingCoopFutex = null; return HWJS_ERESTART_RESCHED; } pendingCoopFutex = null; return futexEintr(uaddr); } let timeout_ms = Infinity; if (timeout_ptr !== 0) { if ((timeout_ptr & 3) !== 0) return E_INVAL; if (RED_FUTEX_TIMED_LEG) { const tv_sec = uU32()[timeout_ptr >>> 2]; const tv_nsec = uU32()[(timeout_ptr >>> 2) + 1]; timeout_ms = tv_sec * 1e3 + tv_nsec / 1e6; if (timeout_ms < 0) return E_INVAL; } else { const tsNs = readGuestTimespec64Ns(timeout_ptr >>> 0); if (tsNs === null) return E_INVAL; if (op === FUTEX_WAIT_BITSET) { const clockid = futex_op & FUTEX_CLOCK_REALTIME ? 0 : 1; const nowNs = guestClockNowNs(clockid, timeout_ptr >>> 0); if (nowNs === null) { try { post({ kind: "dmesg", level: 3, text: `wasm32: FUTEX_WAIT_BITSET pid=${ctrl[C.PID] | 0} clockid=${clockid} \u2014 guest clock unreachable (no in-Worker vmlinux); refusing the absolute-deadline wait with ENOSYS rather than waiting against the wrong clock` }); } catch (_e) { } return E_NOSYS; } const relNs = tsNs - nowNs; timeout_ms = relNs <= 0n ? 0 : Math.ceil(Number(relNs) / 1e6) + 1; } else { timeout_ms = Math.ceil(Number(tsNs) / 1e6) + 1; } } } if ((futex_op & FUTEX_COOP_WAIT) !== 0 && hwjsDrive) { const cur = Atomics.load(uI32(), i32_idx) | 0; const rec = pendingCoopFutex && pendingCoopFutex.uaddr === uaddr >>> 0 && pendingCoopFutex.val === (val | 0) ? pendingCoopFutex : null; if (cur !== (val | 0)) { pendingCoopFutex = null; futexEintrStreak = 0; return rec ? 0 : E_AGAIN; } const nowMs2 = Date.now(); const deadlineMs = rec ? rec.deadlineMs : timeout_ms === Infinity ? Infinity : nowMs2 + timeout_ms; if (nowMs2 >= deadlineMs) { pendingCoopFutex = null; futexEintrStreak = 0; return E_TIMEDOUT; } pendingCoopFutex = { uaddr: uaddr >>> 0, i32idx: i32_idx, val: val | 0, deadlineMs }; if (t67) t67.futexWaits++; if (!coopFutexParkReported) { coopFutexParkReported = true; try { post({ kind: "dmesg", level: 6, text: `hwjs-coopwait ACTIVE pid=${ctrl[C.PID] | 0} tid=${init.tid | 0} rt=${init.rtThread ? 1 : 0} mode=${init.mode}: this guest's libc sets HWJS_FUTEX_COOP_WAIT \u2014 blocking futex waits park cooperatively and never freeze a shared CPU Worker` }); } catch (_e) { } } return HWJS_ERESTART_RESCHED; } if (t67) { t67.futexWaits++; t67.futex = { uaddr: uaddr >>> 0, val: val | 0, ms: timeout_ms === Infinity ? -1 : Math.round(timeout_ms), t: Date.now() }; if (timeout_ms === Infinity) { try { post({ kind: "dmesg", level: 6, text: `t67 pid=${ctrl[C.PID] | 0} USER-FUTEX-WAIT-INF uaddr=0x${(uaddr >>> 0).toString(16)} val=${val | 0} cur=${Atomics.load(uI32(), i32_idx) | 0}` }); } catch (_e) { } } } if (sched && timeout_ms === Infinity) { coopWaitViolations++; if ((coopWaitViolations & coopWaitViolations - 1) === 0) { const m = `hwjs-coopwait VIOLATION pid=${ctrl[C.PID] | 0} tid=${init.tid | 0} rt=${init.rtThread ? 1 : 0} mode=${init.mode}: a POOL RESIDENT entered an UNBOUNDED raw FUTEX_WAIT (uaddr=0x${(uaddr >>> 0).toString(16)}) without HWJS_FUTEX_COOP_WAIT. This freezes the shared CPU Worker \u2014 every co-resident task and the Worker's own message loop (add-task claims, thread-placement requests) stall for the duration. The libc must set the cooperative bit on every indefinitely-blocking wait (PLAN-THREAD-POOL-RESIDENCY contract 3). Occurrences so far: ${coopWaitViolations} (loud, attributed, never-silent).`; try { post({ kind: "dmesg", level: 3, text: m }); } catch (_e) { } try { post({ kind: "user-report", pid: ctrl[C.PID] | 0, message: m }); } catch (_e) { } } } const FUTEX_SLICE_MS = 250; const result = futexWaitSliced({ wait: hostWait, getI32: () => uI32(), i32idx: i32_idx, val: val | 0, timeoutMs: timeout_ms, sliceMs: FUTEX_SLICE_MS, /* post-check below -> -EINTR, or the SIGKILL terminus */ interrupted: () => { hostWaitSignals.refresh(); return deliverableSignalPending(); }, /* Fork STW (step 7): a raw-futex-blocked lane is MID-SLICE and can * be waiting on a lock the FORKING lane itself holds across its * fork park (musl fork() takes the malloc/atfork locks first) — it * can never reach a slice boundary until the fork completes. Hold * HERE, between wait slices (no wasm running, no stores), with the * lane's ack published so the all-lanes barrier counts it * quiescent. Returns when the servicer releases; the futex wait * then resumes unchanged (hold time is stopped-world time and is * NOT charged against the caller's timeout). */ between: () => { stwHoldSyncIfRequested(); maybePause(); } }); if (t67) { if (t67.futex && t67.futex.ms === -1) { try { post({ kind: "dmesg", level: 6, text: `t67 pid=${ctrl[C.PID] | 0} USER-FUTEX-WAIT-INF WOKE r=${result}` }); } catch (_e) { } } t67.futex = null; } if (sched && hostWaitSignals.sigkillPending()) return hostWaitDieOfSigkill(); if (deliverableSignalPending()) return futexEintr(uaddr); futexEintrStreak = 0; if (result === "ok") return 0; if (result === "not-equal") return E_AGAIN; if (result === "timed-out") return E_TIMEDOUT; return E_INVAL; } if (op === FUTEX_WAKE || op === FUTEX_WAKE_BITSET && !RED_FUTEX_TIMED_LEG) { if (op === FUTEX_WAKE_BITSET && (_val3 | 0) === 0) return E_INVAL; const count = val < 0 ? 2147483647 : val | 0; const woken = Atomics.notify(uI32(), i32_idx, count); return woken | 0; } if (op === FUTEX_REQUEUE || op === FUTEX_CMP_REQUEUE) { if (op === FUTEX_CMP_REQUEUE && (Atomics.load(uI32(), i32_idx) | 0) !== (_val3 | 0)) { return E_AGAIN; } const nWake = (val | 0) < 0 ? 2147483647 : val | 0; const nReq = (timeout_ptr | 0) < 0 ? 2147483647 : timeout_ptr | 0; const count = Math.min(2147483647, nWake + nReq); return Atomics.notify(uI32(), i32_idx, count) | 0; } return E_NOSYS; } const DEBUG_K7_U4F = typeof process !== "undefined" && process.env?.HARDWAREJS_DEBUG_K7_U4F; let syscallSeq = 0; let debugFs = null; let debugFd = -1; if (DEBUG_K7_U4F) { try { debugFs = await import("node:fs"); const path = process.env?.HARDWAREJS_DEBUG_LOG ?? "/tmp/k7-u4f-trace.log"; debugFd = debugFs.openSync(path, "a"); } catch (_) { } } function writeDebug(line) { if (debugFs && debugFd >= 0) { try { debugFs.writeSync(debugFd, line); } catch (_) { } } } const acctNow = HOST_PERF !== null ? () => HOST_PERF.now() : () => Date.now(); const acctSysNow = () => preemptClock !== null && HOST_TIME_ORIGIN !== null && preemptClock[PT_CLOCK_F64] !== 0 ? preemptClock[PT_CLOCK_F64] - HOST_TIME_ORIGIN : acctNow(); const laneBusyIdx = init.cpuId | 0; const laneBusyI32 = init.laneBusy instanceof SharedArrayBuffer && laneBusyIdx >= 0 && laneBusyIdx << 2 < init.laneBusy.byteLength ? new Int32Array(init.laneBusy) : null; let acctSliceT0 = 0; let acctSliceLive = false; let acctSliceSyscallMs = 0; let acctSettledMs = 0; let acctLastSliceMs = 0; let acctLastSliceEnd = 0; const ACCT_SETTLE_MS = 2; function acctReportUser(userMs) { if (!(userMs > 0)) return; try { if (vmlinuxInstance && typeof vmlinuxInstance.exports.wasm32_account_user_ns === "function") { vmlinuxInstance.exports.wasm32_account_user_ns( BigInt(Math.round(userMs * 1e6)) ); } } catch (_e) { } } let acctSysPendingMs = 0; let acctHostWaitMs = 0; const hostWait = (i32, idx, v, t) => { const t0 = acctNow(); const r = Atomics.wait(i32, idx, v, t); acctHostWaitMs += acctNow() - t0; return r; }; function acctReportSystem() { const ms = acctSysPendingMs; acctSysPendingMs = 0; if (!(ms > 0)) return; try { if (vmlinuxInstance && typeof vmlinuxInstance.exports.wasm32_account_system_ns === "function") { vmlinuxInstance.exports.wasm32_account_system_ns(BigInt(Math.round(ms * 1e6))); } } catch (_e) { } } let acctSliceSeq = 0; let preemptToken = 0, preemptI32 = null, preemptIdx = -1, preemptMem = null, preemptDriving = false; function preemptSliceBegin(nowMs2) { if (preemptCtlI32 === null) { if (!preemptWarned) { preemptWarned = true; try { post({ kind: "dmesg", level: 4, text: "hwjs-preempt: this realm has no preemption timer; its loop checkpoints will never fire" }); } catch (_e) { } } return; } if (currentTcb === 0) return; const idx = (currentTcb >>> 0) + PREEMPT_WORD_BYTES >>> 2; if (idx !== preemptIdx || init.memory !== preemptMem) { preemptUnregister(preemptToken); preemptToken = (preemptSlot & 511) << 21 | ++preemptTokenSeq & 2097151 | 1 << 30; preemptMem = init.memory; preemptIdx = idx; const buf = init.memory.buffer; preemptI32 = new Int32Array(buf); laneRec.preemptToken = preemptToken; preemptPort.postMessage({ t: "reg", token: preemptToken, sab: buf, idx }); } Atomics.store(preemptI32, preemptIdx, 0); if (HOST_TIME_ORIGIN !== null && preemptClock[PT_CLOCK_F64] < HOST_TIME_ORIGIN + nowMs2) preemptClock[PT_CLOCK_F64] = HOST_TIME_ORIGIN + nowMs2; if (breathDispatchActive) return; const b = preemptSlotBase; Atomics.store(preemptCtlI32, b + PT.SLICE_US, preemptSliceUs()); Atomics.store(preemptCtlI32, b + PT.TOKEN, preemptToken); Atomics.add(preemptCtlI32, b + PT.GEN, 1); if (!preemptDriving) { preemptDriving = true; if (Atomics.add(preemptCtlI32, PT.ACTIVE, 1) === 0) Atomics.notify(preemptCtlI32, PT.ACTIVE); } } function preemptSliceEnd() { if (!preemptDriving) return; preemptDriving = false; Atomics.store(preemptCtlI32, preemptSlotBase + PT.TOKEN, 0); Atomics.sub(preemptCtlI32, PT.ACTIVE, 1); } function preemptSliceUs() { if (laneOthersRunnable(laneRec)) return Math.min(PREEMPT_SLICE_BESIDE_US, preemptSliceMax); const h = othersSliceHorizonIn( laneResidents, laneRec, acctNow(), preemptSliceMax / 1e3, BREATH_SHARE_FRAC, HWJS_BREATH_BESIDE ); if (!(h > 0)) return Math.min(PREEMPT_SLICE_BESIDE_US, preemptSliceMax); return Math.round(h * 1e3); } function acctBeginSlice() { acctSliceSeq++; if (laneBusyI32) Atomics.store(laneBusyI32, laneBusyIdx, 1); acctSliceSyscallMs = 0; acctSettledMs = 0; acctSliceT0 = acctNow(); preemptSliceBegin(acctSliceT0); acctSliceLive = true; return acctSliceT0; } function acctEndSlice(t0) { const t1 = acctNow(); acctLastSliceEnd = t1; acctLastSliceMs = t1 - t0; const userMs = t1 - t0 - acctSliceSyscallMs - acctSettledMs; acctSliceLive = false; if (laneBusyI32) Atomics.store(laneBusyI32, laneBusyIdx, 0); preemptSliceEnd(); if (HWJS_ACCT_DBG) { try { console.error(`[acct-dbg pid=${init.pid}] slice wall=${(acctNow() - t0).toFixed(3)}ms sys=${acctSliceSyscallMs.toFixed(3)}ms settled=${acctSettledMs.toFixed(3)}ms user-tail=${userMs.toFixed(3)}ms export=${!!(vmlinuxInstance && vmlinuxInstance.exports.wasm32_account_user_ns)}`); } catch (_e) { } } acctReportUser(userMs); acctReportSystem(); } let kcNr = 0, kcA0 = 0, kcA1 = 0, kcA2 = 0, kcA3 = 0, kcA4 = 0, kcA5 = 0; const kernelCall = () => vmlinuxInstance.exports.wasm_syscall( kcNr, kcA0, kcA1, kcA2, kcA3, kcA4, kcA5 ); function kernelDispatch(nr, a0, a1, a2, a3, a4, a5) { kcNr = nr | 0; kcA0 = a0 | 0; kcA1 = a1 | 0; kcA2 = a2 | 0; kcA3 = a3 | 0; kcA4 = a4 | 0; kcA5 = a5 | 0; return hwjsLane ? hwjsLane.dispatchSyscall(kcNr, kernelCall) : kernelCall(); } let clonePushOutstanding = false; function syscall(nr, a0, a1, a2, a3, a4, a5) { if (sched && Atomics.load(ctrl, CTRL_I32_REAPED) !== 0) throw HWJS_REAPED_UNWIND; if (filePagesWord >= 0) publishFilePages(); if (HEAP_AUDIT_CTX) heapAudit(`sys-entry nr=${nr}`); const acctT0 = acctSysNow(); const acctW0 = acctHostWaitMs; if (breathRefill !== HWJS_SP_REFILL && acctSliceLive && !breathDispatchActive && acctT0 - acctSliceT0 > BREATH_LONG_MS && userExports && typeof userExports.__hwjs_budget_set === "function") { cutBreathBudget(); } if (acctSliceLive) { const pending2 = acctT0 - acctSliceT0 - acctSliceSyscallMs - acctSettledMs; if (pending2 >= ACCT_SETTLE_MS) { acctReportUser(pending2); acctSettledMs += pending2; } } try { if (t67) { t67.inSysNr = nr | 0; t67.inSysT = Date.now(); } if (sharedMaps.active()) { const again = sharedMaps.enter(nr, a0, a1, a2, a3); if (again !== 0) return again; } const r67 = syscallInner(nr, a0, a1, a2, a3, a4, a5); sharedMaps.leave(nr, a0, a1, a2, r67); if (t67) t67RecordSys(nr, r67); if (nr === 56 && (r67 | 0) !== HWJS_ERESTART_RESCHED) clonePushOutstanding = false; if ((r67 | 0) !== HWJS_ERESTART_RESCHED && (r67 | 0) !== HWJS_EMMAP_PARKED) coopProgressSeq++; if (breathRefill !== HWJS_SP_REFILL && acctSliceLive && !breathDispatchActive && userExports && typeof userExports.__hwjs_budget_set === "function" && laneOthersRunnable(laneRec)) { cutBreathBudget(); breathSyscallCuts++; } return r67; } finally { const sysMs = acctSysNow() - acctT0; acctSliceSyscallMs += sysMs; acctSysPendingMs += Math.max(0, sysMs - (acctHostWaitMs - acctW0)); if (acctSysPendingMs >= ACCT_SETTLE_MS) acctReportSystem(); if (HEAP_AUDIT_CTX) heapAudit(`sys-exit nr=${nr}`); } } const HEAP_AUDIT_CTX = typeof process !== "undefined" && process.env?.HWJS_HEAP_AUDIT ? parseInt(process.env.HWJS_HEAP_AUDIT, 16) >>> 0 : 0; let heapAuditDisarmed = false; let heapAuditLastGood = "never"; let heapAuditArmedLogged = false; let heapAuditGateOpenLogged = false; const HEAP_AUDIT_SC = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 18, 20, 25, 31, 36, 42, 50, 63, 72, 84, 102, 127, 146, 170, 204, 255, 292, 340, 409, 511, 584, 682, 818, 1023, 1169, 1364, 1637, 2047, 2340, 2730, 3276, 4095, 4680, 5460, 6552, 8191 ]; const HEAP_AUDIT_LEN = typeof process !== "undefined" && process.env?.HWJS_HEAP_AUDIT_LEN ? parseInt(process.env.HWJS_HEAP_AUDIT_LEN, 10) >>> 0 : 0; const HEAP_AUDIT_META = typeof process !== "undefined" && !!process.env?.HWJS_HEAP_AUDIT_META; const ALIMIT_SIG = [1e9, 1e9, 2e3, 1e3, 500, 25e7, 1e3, 10, 5e4, 32766, 1e3]; let alimitAddr = 0, alimitDisarmed = false, alimitScans = 0; function heapAudit(where) { if (heapAuditDisarmed) return; if (HEAP_AUDIT_LEN && (!curWasmBytes || curWasmBytes.length !== HEAP_AUDIT_LEN)) return; const u8 = uU8(); const dv = new DataView(u8.buffer); const ctx = HEAP_AUDIT_CTX; if (!heapAuditArmedLogged) { heapAuditArmedLogged = true; try { post({ kind: "dmesg", level: 5, text: `HEAP-AUDIT ARMED pid=${init.pid} rt=${init.rtThread ? 1 : 0} ctx=0x${ctx.toString(16)} init_done@+12=${dv.getUint32(ctx + 12, true)} pagesize@+8=${dv.getUint32(ctx + 8, true)}` }); } catch (_e) { } } const n = u8.length; const fail = (msg) => { heapAuditDisarmed = true; const full = `HEAP-AUDIT pid=${init.pid} rt=${init.rtThread ? 1 : 0} FIRST VIOLATION at [${where}] (last good: [${heapAuditLastGood}]): ${msg}`; try { post({ kind: "dmesg", level: 3, text: full }); } catch (_e) { } try { post({ kind: "user-report", pid: init.pid, message: full }); } catch (_e) { } const trapDumpDir = typeof process !== "undefined" ? process.env?.HWJS_TRAP_DUMP : void 0; if (trapDumpDir) { try { import("node:fs").then((fsMod) => { const copy = new Uint8Array(u8.length); copy.set(new Uint8Array(init.memory.buffer)); const tag = `auditdump-tid${init.tid | 0}-${Date.now()}`; fsMod.writeFileSync(`${trapDumpDir}/${tag}.bin`, copy); fsMod.writeFileSync(`${trapDumpDir}/${tag}.txt`, full + "\n"); }).catch(() => { }); } catch (_e) { } } }; try { if (dv.getUint32(ctx + 8, true) === 0) { heapAuditLastGood = where; return; } if (!heapAuditGateOpenLogged) { heapAuditGateOpenLogged = true; try { post({ kind: "dmesg", level: 5, text: `HEAP-AUDIT GATE-OPEN pid=${ctrl ? ctrl[C.PID] | 0 : "?"} rt=${init.rtThread ? 1 : 0} ctx=0x${ctx.toString(16)} init_done=${dv.getUint32(ctx + 8, true)} secret=0x${dv.getUint32(ctx + 4, true).toString(16)}${dv.getUint32(ctx, true).toString(16)} area_head=0x${(dv.getUint32(ctx + 36, true) >>> 0).toString(16)} \u2014 walker LIVE` }); } catch (_e) { } } const secretLo = dv.getUint32(ctx, true), secretHi = dv.getUint32(ctx + 4, true); let area = dv.getUint32(ctx + 36, true) >>> 0; let areaCount = 0; const areaRanges = []; while (area !== 0 && areaCount < 64) { if (area + 16 > n) return fail(`meta_area 0x${area.toString(16)} out of range`); if (dv.getUint32(area, true) !== secretLo || dv.getUint32(area + 4, true) !== secretHi) { return fail(`meta_area 0x${area.toString(16)} check != secret (0x${dv.getUint32(area + 4, true).toString(16)}${dv.getUint32(area, true).toString(16)})`); } const nslots = dv.getUint32(area + 12, true); if (nslots === 0 || nslots > 4096) return fail(`meta_area 0x${area.toString(16)} nslots=${nslots}`); areaRanges.push([area + 16, area + 16 + 24 * nslots]); area = dv.getUint32(area + 8, true) >>> 0; areaCount++; } for (let sc = 0; sc < 48; sc++) { const m = dv.getUint32(ctx + 48 + 4 * sc, true) >>> 0; if (m === 0) continue; if (!areaRanges.some(([lo, hi]) => m >= lo && m + 24 <= hi)) { return fail(`active[${sc}] meta 0x${m.toString(16)} not inside any meta area`); } const bf = dv.getUint32(m + 20, true); const msc = bf >>> 6 & 63; if (msc !== sc) return fail(`active[${sc}] meta 0x${m.toString(16)} has sizeclass ${msc}`); const memp = dv.getUint32(m + 8, true) >>> 0; if (memp === 0 || memp + 16 > n) return fail(`active[${sc}] group mem 0x${memp.toString(16)} bad`); if (dv.getUint32(memp, true) >>> 0 !== m) { return fail(`active[${sc}] group 0x${memp.toString(16)} backptr 0x${dv.getUint32(memp, true).toString(16)} != meta 0x${m.toString(16)}`); } const avail = dv.getUint32(m + 12, true) >>> 0, freed = dv.getUint32(m + 16, true) >>> 0; if ((avail & freed) !== 0) { return fail(`active[${sc}] avail 0x${avail.toString(16)} \u2229 freed 0x${freed.toString(16)} != 0 (meta 0x${m.toString(16)})`); } if (sc <= 10 && !HEAP_AUDIT_META) { const stride = HEAP_AUDIT_SC[sc] * 16; const last = bf & 31; const storage = memp + 16; for (let idx = 0; idx <= last; idx++) { if (avail >>> idx & 1) { const p = storage + stride * idx; if (p - 4 >= 0 && p <= n && u8[p - 4] !== 0) { return fail(`active[${sc}] AVAIL slot ${idx} p=0x${p.toString(16)} in-band p[-4]=0x${u8[p - 4].toString(16)} != 0 (group 0x${memp.toString(16)} meta 0x${m.toString(16)} avail=0x${avail.toString(16)} freed=0x${freed.toString(16)}; bytes ${Array.from(u8.subarray(Math.max(0, p - 16), p + 16)).map((x) => x.toString(16).padStart(2, "0")).join(" ")})`); } } } } } if (!alimitDisarmed) { if (alimitAddr === 0) { alimitScans++; if (alimitScans > 128 * 24) { alimitDisarmed = true; heapAuditLastGood = where; return; } if ((alimitScans & 127) !== 1) { heapAuditLastGood = where; return; } const limit = Math.min(n - 44, 67108864); for (let a = 4194304; a <= limit; a += 16) { if (dv.getUint32(a, true) === 1e9 && dv.getUint32(a + 4, true) === 1e9 && dv.getUint32(a + 8, true) === 2e3 && dv.getUint32(a + 12, true) === 1e3 && dv.getUint32(a + 16, true) === 500 && dv.getUint32(a + 20, true) === 25e7) { alimitAddr = a; try { post({ kind: "dmesg", level: 5, text: `HEAP-AUDIT ALIMIT pinned @0x${a.toString(16)} rt=${init.rtThread ? 1 : 0} [${where}] \u2014 watching the sqlite3 connection aLimit signature for wild writes` }); } catch (_e) { } break; } } } else { for (let i = 0; i < ALIMIT_SIG.length; i++) { if (dv.getUint32(alimitAddr + 4 * i, true) >>> 0 !== ALIMIT_SIG[i] >>> 0) { alimitDisarmed = true; return fail(`sqlite3 connection aLimit[${i}] @0x${(alimitAddr + 4 * i).toString(16)} = 0x${dv.getUint32(alimitAddr + 4 * i, true).toString(16)} (expected 0x${(ALIMIT_SIG[i] >>> 0).toString(16)}) \u2014 WILD WRITE into the sqlite3 connection struct (the whereLoop T2 victim); bytes@aLimit-64 ${Array.from(u8.subarray(alimitAddr - 64, alimitAddr + 8)).map((x) => x.toString(16).padStart(2, "0")).join(" ")}`); } } } } heapAuditLastGood = where; } catch (e) { heapAuditDisarmed = true; try { post({ kind: "dmesg", level: 3, text: `HEAP-AUDIT pid=${init.pid} rt=${init.rtThread ? 1 : 0} walker threw at [${where}]: ${e instanceof Error ? e.message : String(e)}` }); } catch (_e) { } } } const STALL_TRACE = typeof process !== "undefined" && !!process.env?.HWJS_STALL_TRACE; const SYS_ENV = Object.freeze(sysEnvKnobs()); let stallLastNr = -1, stallLastT = 0, stallSyscalls = 0, stallLastEmitT = 0; const stallLine = (how) => `STALL-TRACE pid=${ctrl ? ctrl[C.PID] | 0 : init.pid ?? "?"} rt=${init.rtThread ? 1 : 0} ${how}; syscalls=${stallSyscalls} last nr=${stallLastNr} age=${stallLastT ? ((Date.now() - stallLastT) / 1e3).toFixed(1) : "?"}s`; if (STALL_TRACE && typeof setInterval === "function") { const iv = setInterval(() => { try { post({ kind: "dmesg", level: 5, text: stallLine("loop-alive") }); } catch (_e) { } }, 2e4); if (typeof iv === "object" && iv && typeof iv.unref === "function") iv.unref(); } let rootMapLayout = null, rootMapLayoutBytes = null, rootMapInitialSp = 0; function serviceRootMap(buf, cap) { if (rootMapLayoutBytes !== curWasmBytes) { rootMapLayout = readMainRootLayout(curWasmBytes, rootMapInitialSp); rootMapLayoutBytes = curWasmBytes; } const ue = userExports; const sizeOf = (h) => h && h.dylink ? h.dylink.memorySize >>> 0 : 0; const modules2 = []; if (hwjsRtHandle && hwjsRtPlacement) { modules2.push({ memoryBase: hwjsRtPlacement.memoryBase, memorySize: sizeOf(hwjsRtHandle) }); } if (libcSoHandle && libcSoPlacement) { modules2.push({ memoryBase: libcSoPlacement.memoryBase, memorySize: sizeOf(libcSoHandle) }); } for (const n of neededSoHandles) { if (n && n.handle) modules2.push({ memoryBase: n.handle.memoryBase, memorySize: sizeOf(n.handle) }); } for (const m of dlopenModules.values()) { if (m && !m.mainScope && m.handle) { modules2.push({ memoryBase: m.memoryBase, memorySize: sizeOf(m.handle) }); } } const stacks = []; const own = callerStackRegion( rootMapLayout, init.mode === "thread" ? init.stackPointerOffset >>> 0 : 0 ); if (own && ue && typeof ue.__wasm32_get_stack_pointer === "function") { stacks.push({ sp: ue.__wasm32_get_stack_pointer() >>> 0, ...own }); } if (hwjsRtPlacement && hwjsRtStackPointer) { const top = (threadSideSpTop || hwjsRtPlacement.spTop) >>> 0; stacks.push({ sp: hwjsRtStackPointer.value >>> 0, hi: top, limit: top - HWJS_RT_STACK_CARVE >>> 0 }); } const arena = []; if (ue && typeof ue.__hwjs_arena_seg_count === "function") { const tcb = currentTcb >>> 0; const n = Math.min(ue.__hwjs_arena_seg_count(tcb) >>> 0, 1024); for (let i = 0; i < n; i++) { arena.push([ ue.__hwjs_arena_seg_base(tcb, i) >>> 0, ue.__hwjs_arena_seg_end(tcb, i) >>> 0 ]); } } const records = buildRootMap({ main: rootMapLayout, modules: modules2, stacks, arena }); return writeRootMap(init.memory.buffer, buf, cap, records); } let filePagesWord = -1, filePagesPublished = 0, filePagesKey = null; let filePagesMainBytes = null, filePagesMain = 0; const filePagesOf = (n) => Math.ceil((n >>> 0) / 4096); function armFilePages(tgid) { const ex = vmlinuxInstance ? vmlinuxInstance.exports : null; const word2 = ex ? ex.wasm32_user_sab_pid_file_pages : null; const slots = ex ? ex.wasm32_user_sab_pid_slots : null; const kmem = kernelI32Live(); if (!kmem || !word2 || typeof word2.value !== "number" || !slots || typeof slots.value !== "number") return; const off = word2.value >>> 0; const n = Atomics.load(kmem, slots.value >>> 0 >> 2) >>> 0; if (off === 0 || (off & 3) !== 0 || off + 4 * n > kmem.byteLength || !(tgid > 0 && tgid < n)) { post({ kind: "dmesg", level: 4, text: `hwjs pid=${tgid} wasm32_user_sab_pid_file_pages at ${off} with ${n} slots does not fit kernel memory or this tgid; this process's file-backed pages read 0` }); return; } filePagesWord = (off >> 2) + tgid; filePagesPublished = 0; filePagesKey = null; Atomics.store(kmem, filePagesWord, 0); } function publishFilePages() { const k = filePagesKey; if (k && k[0] === curWasmBytes && k[1] === hwjsRtHandle && k[2] === libcSoHandle && k[3] === neededSoHandles && k[4] === dlopenModules.size && k[5] === dlopenNextCookie) return; filePagesKey = [ curWasmBytes, hwjsRtHandle, libcSoHandle, neededSoHandles, dlopenModules.size, dlopenNextCookie ]; try { if (filePagesMainBytes !== curWasmBytes) { filePagesMain = curWasmBytes ? filePagesOf(readDataSegmentBytes(curWasmBytes)) : 0; filePagesMainBytes = curWasmBytes; } const of = (h) => h && typeof h.dataBytes === "number" ? filePagesOf(h.dataBytes) : 0; let pages2 = filePagesMain + of(hwjsRtHandle) + of(libcSoHandle); for (const e of neededSoHandles) if (e) pages2 += of(e.handle); for (const m of dlopenModules.values()) if (m && !m.mainScope) pages2 += of(m.handle); if (pages2 !== filePagesPublished) { Atomics.store(kernelI32Live(), filePagesWord, pages2); filePagesPublished = pages2; } } catch (e) { filePagesWord = -1; post({ kind: "dmesg", level: 4, text: `hwjs pid=${ctrl[C.PID] | 0} file-backed pages not published: ${e instanceof Error ? e.message : String(e)}` }); } } function syscallInner(nr, a0, a1, a2, a3, a4, a5) { if (STALL_TRACE) { stallLastNr = nr | 0; stallLastT = Date.now(); stallSyscalls++; if (stallLastT - stallLastEmitT > 15e3) { stallLastEmitT = stallLastT; try { post({ kind: "dmesg", level: 5, text: stallLine("in-syscall") }); } catch (_e) { } } } maybePause(); hwjsSliceProgressed = true; if (pendingCoopFutex !== null && (nr | 0) !== SYS_FUTEX) { pendingCoopFutex = null; } if (futexEintrStreak !== 0 && (nr | 0) !== SYS_FUTEX) { futexEintrStreak = 0; } if (DEBUG_K7_U4F) { const seq = ++syscallSeq; writeDebug( `[K7-U4f worker pid=${init.pid} tid=${init.tid} seq=${seq}] nr=${nr} args=[0x${(a0 >>> 0).toString(16)},0x${(a1 >>> 0).toString(16)},0x${(a2 >>> 0).toString(16)},0x${(a3 >>> 0).toString(16)},0x${(a4 >>> 0).toString(16)},0x${(a5 >>> 0).toString(16)}] ` ); } if (D1_TRACE_SYS) { const pth = d1SysPath(nr, a0, a1); try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} ENTER nr=${nr | 0}` + (pth ? ` path="${pth}"` : "") + ` a0=0x${(a0 >>> 0).toString(16)} a1=0x${(a1 >>> 0).toString(16)} a2=0x${(a2 >>> 0).toString(16)}` }); } catch (_e) { } } if ((nr | 0) === SYS_SCHED_YIELD) return schedYield(); if (nr === 56 && hwjsDrive && (a0 >>> 0 & (256 | 16384 | 65536)) === (256 | 16384) && mainLaneAddressed && !!userExports && typeof userExports.__hwjs_thread_attach === "function" && globalThis.process?.env?.HWJS_VFORK !== "0") { const blk = a5 >>> 0; if (blk === 0 || blk + 8 > init.memory.buffer.byteLength) return -22; hwjsVforkLatched = { flags: a0 >>> 0, stack: a1 >>> 0, fn: uU32()[blk >>> 2] >>> 0, arg: uU32()[(blk >>> 2) + 1] >>> 0 }; return 0; } if (nr === 56 && a0 >>> 0 & 256 && hwjsDrive) { const laneSubstrate = mainLaneAddressed && !!userExports && typeof userExports.__hwjs_thread_attach === "function"; if (!laneSubstrate && globalThis.process?.env?.HWJS_EXPERIMENTAL_THREAD_CLONE !== "1") { try { post({ kind: "dmesg", level: 4, text: `wasm32: REFUSING thread-mode clone (CLONE_VM, pid=${ctrl[C.PID] | 0}, flags=0x${(a0 >>> 0).toString(16)}) with EAGAIN \u2014 the coro substrate's runtime protocol state is single-lane per process; a second Worker lane over the same user_memory is a structural protocol violation, not a schedulable thread. pthread_create() gets EAGAIN (catchable std::system_error). Opt-in: HWJS_EXPERIMENTAL_THREAD_CLONE=1.` }); } catch (_e) { } return -11; } } if (nr === 56 && a0 >>> 0 & 256 && a0 >>> 0 & 65536 && !(a0 >>> 0 & 16384)) { try { if (!clonePushOutstanding) { clonePushOutstanding = true; post({ kind: "thread-placement", pid: ctrl[C.PID] | 0, seq: 0, unsolicited: true, clone: { flags: a0 >>> 0, ptid: a2 >>> 0, ctid: a4 >>> 0 }, /* * WHETHER THIS WORKER STAYS AVAILABLE FOR THE CLONE, answered by * the caller because only the caller knows. The kernel's * spawn_ring_wait_result block-parks (arch/wasm32/kernel/spawn.c, * "THE ONE COOPERATIVE PARK"), so this clone's -517 goes wherever * blockParkGoesToGuest sends every other one: to the guest libc, * which parks reason 4 and yields a real event-loop turn — or to * the in-place restart loop, which freezes this Worker until the * clone returns. * * The host uses it to decide whether the new thread may be placed * on THIS lane. Asked through the shared predicate, not restated: * a placement decision made from a transcription of the -517 * routing rule is a deadlock the moment the two disagree. */ callerYieldsDuringClone: blockParkGoesToGuest(SYS_CLONE), /* Step 7 residual fix: the thread Worker shares the process's * kernel fd table but not this JS-side KERNEL-vs-host-RPC * routing cache — without it a thread lane's fd1=pts writes * fall back to host-RPC stdio and never reach the tty. */ lowFdRoutes: [...kernelRoutedLowFds], dlopenFork: buildDlopenForkRecord() }); } } catch (_e) { } } if (nr === SYS_FORK) { if (hwjsDrive) { hwjsForkLatched = true; return 0; } return E_NOSYS; } if (nr === SYS_EXECVE) { if (hwjsDrive) { const execReissue = execImageLoader.phase.phase !== "idle" && execImageLoader.phase.pathPtr === a0 >>> 0 || /* ...or the load is DONE for this path and the LIBC STAGE is the * thing mid-flight (execStage). Same execve, same argv, one phase * later — omitting this arm would re-walk argv/envp out of user * memory on every libc-stage resume and emit a LATCH line for each, * which is the waste the predicate exists to avoid. */ execStage.phase !== "idle" && execStage.pathPtr === a0 >>> 0; hwjsExecLatched = true; if (!execReissue) { execPendingPathPtr = a0 >>> 0; const u8h = new Uint8Array(init.memory.buffer); let e = a0 >>> 0; while (e < u8h.length && u8h[e] !== 0) e++; execPendingPath = decodeMaybeShared3(u8h.subarray(a0 >>> 0, e)); execPendingArgv = decodeUserStringVector(a1 >>> 0, "execve argv"); execPendingEnvp = decodeUserStringVector(a2 >>> 0, "execve envp"); if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} EXECVE-LATCH path="${execPendingPath}" argv=[${execPendingArgv.map((s) => JSON.stringify(s)).join(",")}] (${execPendingEnvp.length} env)` }); } catch (_e) { } } } { const r = loadExecImageKernelSync(a0 >>> 0, libcParksAnySyscall); if (r.wouldBlock) { announceExecLoadYield("execve intercept", execPendingPath); if (SCHED_TRACE) { schedTrace(post, `YIELD cpu=${init.cpuId ?? "?"} tid=${init.tid} reason=EXEC-LOAD-park site=execve-intercept via=guest-restart`); } return HWJS_ERESTART_RESCHED; } if (r.unavailable) { return 0; } if (!libcParksAnySyscall && execImageLoader.blocksLast() > 0) { announceExecLoadInline(execPendingPath, execImageLoader.blocksLast()); } if (!r.ok) { execResumeResult = typeof r.errno === "number" && r.errno < 0 ? r.errno | 0 : -2; if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} EXECVE-INLINE FAIL path="${execPendingPath}" errno=${execResumeResult}` }); } catch (_e) { } } return execResumeResult | 0; } execInlineReinstantiateBytes = r.wasmBytes; if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} EXECVE-INLINE OK path="${execPendingPath}" ${r.wasmBytes.length}B \u2014 unwinding to re-instantiate` }); } catch (_e) { } } hwjsExecLatched = false; throw HWJS_EXEC_UNWIND; } } return E_NOSYS; } if (nr === SYS_WASM_SETJMP) { if (hwjsDrive) { throw new Error( "HWJS-3: SYS_WASM_SETJMP from a coro-substrate image \u2014 sjlj is lowered in-module; this syscall is retired. A stale Asyncify-era setjmp override is linked into the binary." ); } return E_NOSYS; } if (nr === SYS_WASM_LONGJMP) { if (hwjsDrive) { throw new Error( "HWJS-3: SYS_WASM_LONGJMP from a coro-substrate image \u2014 sjlj is lowered in-module; this syscall is retired. A stale Asyncify-era setjmp override is linked into the binary." ); } return E_NOSYS; } if (nr === SYS_FUTEX) { return handleFutex(a0 | 0, a1 | 0, a2 | 0, a3 | 0, a4 | 0, a5 | 0); } if (nr === SYS_WASM_DLOPEN) { dlopenLatched = true; dlopenPendingPathPtr = a0 >>> 0; dlopenPendingReissue = (a1 & HWJS_DLOPEN_REISSUE) !== 0; dlopenPendingLoaded = false; dlopenLastError = ""; if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} DLOPEN-LATCH path="${readUserCString(a0 >>> 0)}" (HWJS_PARK_DLOPEN armed)` }); } catch (_e) { } } return 0; } if (nr === SYS_WASM_DLOPEN_LOADED) { dlopenLatched = true; dlopenPendingPathPtr = a0 >>> 0; dlopenPendingReissue = false; dlopenPendingLoaded = true; dlopenLastError = ""; if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} DLOPEN-LOADED-LATCH name="${readUserCString(a0 >>> 0)}" (HWJS_PARK_DLOPEN armed)` }); } catch (_e) { } } return 0; } if (nr === SYS_WASM_DLERROR) { const buf = a0 >>> 0; const cap = a1 | 0; if (!dlopenLastError || buf === 0 || cap <= 1) return 0; const bytes = new TextEncoder().encode(dlopenLastError); const n = Math.min(bytes.length, cap - 1); const u8 = new Uint8Array(init.memory.buffer); if (buf + n + 1 > u8.length) return 0; u8.set(bytes.subarray(0, n), buf); u8[buf + n] = 0; return n; } if (nr === SYS_WASM_ROOT_MAP) { return serviceRootMap(a0 >>> 0, a1 | 0); } if (nr === SYS_WASM_DLADDR) { const slot = (i) => sharedTable instanceof WebAssembly.Table && i < sharedTable.length ? sharedTable.get(i) : null; const o = dladdrObject(a0 >>> 0, dladdrObjects(), slot); if (!o) return 0; const bytes = new TextEncoder().encode(o.paths.map((p) => `${p}\0`).join("")); const buf = a1 >>> 0, base = a3 >>> 0, cookie = a4 >>> 0; const u8 = new Uint8Array(init.memory.buffer); if (bytes.length > a2 >>> 0 || buf + bytes.length > u8.length || base + 4 > u8.length || cookie && cookie + 4 > u8.length) return 0; u8.set(bytes, buf); const dv = new DataView(init.memory.buffer); dv.setUint32(base, o.memoryBase, true); if (cookie) dv.setUint32(cookie, o.cookie, true); return bytes.length; } if (nr === SYS_WASM_DLSYM) { const cookie = a0 >>> 0; const pseudo = cookie === DLSYM_RTLD_DEFAULT || cookie === DLSYM_RTLD_NEXT; const entry = pseudo ? null : dlopenModules.get(cookie); if (!pseudo && !entry) { dlsymCallerBox.caller = null; return 0; } const name2 = readUserCString(a1 >>> 0); const caller = dlsymCallerBox.caller; dlsymCallerBox.caller = null; let idx = 0; const lenBefore = sharedTable instanceof WebAssembly.Table ? sharedTable.length : 0; try { idx = (cookie === DLSYM_RTLD_DEFAULT ? mainScopeDlsym(name2) : cookie === DLSYM_RTLD_NEXT ? rtldNextDlsym(name2, caller) : entry.handle.dlsym(name2)) | 0; } catch (e) { post({ kind: "error", pid: init.pid, message: "HWJS-5 dlsym trapped: " + (e instanceof Error ? e.message : String(e)) }); return 0; } if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} DLSYM cookie=${a0 >>> 0} name="${name2}" -> ${idx >>> 0}` }); } catch (_e) { } } if (sharedTable instanceof WebAssembly.Table && sharedTable.length !== lenBefore) { dlPlacementPublish("dlsym"); } return idx; } if (nr === SYS_WASM_JIT) { return wasmJit.syscall(a0, a1, a2, a3, a4, a5); } if (nr === SYS_WASM_DLCLOSE) { const cookie = a0 >>> 0; const entry = dlopenModules.get(cookie); if (!entry) return -22; if (entry.mainScope) { dlopenModules.delete(cookie); return 0; } if (dlcloseDropRef(entry)) return 0; if (entry.internal) return -22; if (entry.boundByDependent) { entry.internal = true; entry.refs = 0; return 0; } const noCensus = (globalThis.process?.env?.HWJS_DLCLOSE_NO_CENSUS || "") === "1"; const census = entry.census || { live: 0, poisoned: false }; const pGlob = userExports ? userExports.__hwjs_parked : void 0; const parkedAddr = pGlob instanceof WebAssembly.Global ? pGlob.value >>> 0 : 0; const parkedVal = parkedAddr ? uU32()[parkedAddr >> 2] >>> 0 : 0; const oGlob = userExports ? userExports.__hwjs_parked_owner : void 0; const ownerAddr = oGlob instanceof WebAssembly.Global ? oGlob.value >>> 0 : 0; const ownerVal = ownerAddr ? uU32()[ownerAddr >> 2] >>> 0 : 0; const tb = entry.tableBase >>> 0; const ts = entry.handle && entry.handle.dylink ? entry.handle.dylink.tableSize >>> 0 : 0; const appended = entry.handle && typeof entry.handle.tableIndices === "function" ? entry.handle.tableIndices() : []; const ownerInModule = ownerVal >= tb && ownerVal < tb + ts || appended.includes(ownerVal); try { post({ kind: "dmesg", level: 7, text: `hwjs-dlclose-census pid=${ctrl[C.PID] | 0} cookie=${cookie} moduleId=${entry.moduleId} path="${entry.path || ""}" live=${census.live} poisoned=${census.poisoned ? 1 : 0} parked=0x${parkedVal.toString(16)} owner=0x${ownerVal.toString(16)} noCensus=${noCensus ? 1 : 0}` }); } catch (_e) { } if (!noCensus) { let refuseReason = null; if (census.live > 0) { refuseReason = `${census.live} live coroutine frame(s) allocated by the module are not yet freed`; } else if (census.poisoned) { refuseReason = "the module frame census is POISONED (a frame_free underflow was observed; the count is untrustworthy)"; } if (parkedVal !== 0) { post({ kind: "user-report", pid: init.pid, message: `HWJS-5 M2 dlclose ANOMALY: __hwjs_parked=0x${parkedVal.toString(16)} (owner=0x${ownerVal.toString(16)}) non-zero at dlclose service of cookie=${cookie} "${entry.path || ""}" \u2014 a park is in flight while dlclose runs${ownerInModule ? "; the owner word falls in the closing module's table footprint \u2014 REFUSING" : ""}.` }); if (ownerInModule && !refuseReason) { refuseReason = `a parked chain's owner word 0x${ownerVal.toString(16)} targets the closing module's table slots`; } } if (refuseReason) { post({ kind: "user-report", pid: init.pid, message: `HWJS-5 M2 dlclose REFUSED (EBUSY): path="${entry.path || ""}" cookie=${cookie} moduleId=${entry.moduleId} live=${census.live} \u2014 ` + refuseReason + `. The handle stays open; retry after the module's coroutines complete (never-silent, non-terminal).` }); return -16; } } dlopenDeadRanges.push({ tableBase: entry.tableBase >>> 0, tableSize: ts >>> 0, appended: appended.slice(), path: entry.path || "", moduleId: entry.moduleId | 0 }); xmodConsultInvalidate(); { const tb2 = entry.tableBase >>> 0; for (const k of [...fpcastProcessRecs.keys()]) { if (k >= tb2 && k < tb2 + (ts >>> 0) || appended.includes(k)) { fpcastProcessRecs.delete(k); } } } if ((entry.moduleId | 0) !== 0) capsummaryProcessRecs.removeModule(entry.moduleId | 0); try { entry.handle.unload(); } catch (_e) { } if (vmlinuxInstance && typeof vmlinuxInstance.exports.__hwjs_deregister_module === "function") { try { vmlinuxInstance.exports.__hwjs_deregister_module(entry.moduleId | 0); } catch (e) { post({ kind: "error", pid: init.pid, message: "HWJS-5 __hwjs_deregister_module trapped: " + (e instanceof Error ? e.message : String(e)) }); } } dlopenModules.delete(cookie); dlPlacementPublish("dlclose"); if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} DLCLOSE cookie=${cookie} moduleId=${entry.moduleId}` }); } catch (_e) { } } return 0; } if (nr === SYS_WASM_SIGCONSUME) { if (vmlinuxInstance && perProcessTaskAddr !== 0 && typeof vmlinuxInstance.exports.wasm32_sigconsume === "function") { try { const call = () => vmlinuxInstance.exports.wasm32_sigconsume(a0 | 0, a1 >>> 0) | 0; return (hwjsLane ? hwjsLane.bracket("wasm32_sigconsume", call) : call()) | 0; } catch (e) { post({ kind: "error", pid: init.pid, message: "K12-W4: vmlinux wasm32_sigconsume trapped: " + (e instanceof Error ? e.message : String(e)) }); return 0; } } return 0; } if (nr === SYS_EXIT || nr === SYS_EXIT_GROUP || nr === SYS_WASM_EXIT_BY_SIGNAL) { execStageDrainOnExit(); let signaled = nr === SYS_WASM_EXIT_BY_SIGNAL ? 1 : 0; let codeArg = signaled ? a0 & 127 : a0 & 255; const grpExit = nr === SYS_EXIT_GROUP ? decideGroupExit(a0 & 255, 0) : nr === SYS_WASM_EXIT_BY_SIGNAL ? decideGroupExit(a0 & 127, 1) : null; if (grpExit) { if ((grpExit.wstatus & 127) === 0) { codeArg = grpExit.wstatus >> 8 & 255; signaled = 0; } else { codeArg = grpExit.wstatus & 127; signaled = 1; } } exitCode = codeArg; if (grpExit && grpExit.zapped > 0) { post({ kind: "dmesg", level: 5, text: `hwjs-groupexit pid=${init.pid} tid=${init.tid | 0} mode=${init.mode ?? "fork"}: ` + (nr === SYS_EXIT_GROUP ? `exit_group(${a0 & 255})` : `fatal terminus by signal ${a0 & 127}`) + ` \u2014 the kernel condemned ${grpExit.zapped} other thread(s) of this process and set the group's exit code to 0x${grpExit.wstatus.toString(16)} (${grpExit.wstatus & 127 ? `WIFSIGNALED WTERMSIG=${grpExit.wstatus & 127}` : `WIFEXITED WEXITSTATUS=${grpExit.wstatus >> 8 & 255}`}); the host now unwinds their Workers (the kernel's decision, this host's mechanism)` }); } else if (nr === SYS_WASM_EXIT_BY_SIGNAL && !grpExit) { post({ kind: "dmesg", level: 3, text: `hwjs-groupexit pid=${init.pid} tid=${init.tid | 0} mode=${init.mode ?? "fork"}: fatal terminus by signal ${a0 & 127} was NOT decided by the kernel \u2014 this process's other threads are not condemned by it and the host unwinds none of them. On Linux a fatal signal on any thread ends the whole process` }); } pendingExitTerminus = { codeArg, signaled, grpExit }; if (!exitPosted && flatCensusEmit) flatCensusEmit("exit-syscall"); if (sched) throw HWJS_EXIT_UNWIND; pendingExitTerminus = null; if (vmlinuxInstance && perProcessTaskAddr !== 0) { throw new Error( `exit terminus: a legacy (non-pool) Worker reached SYS_exit_group with a live vmlinux task (ptask=0x${(perProcessTaskAddr >>> 0).toString(16)}) \u2014 the child-exit cleanup yields the event loop on a would-block (contract 3, site 4) and this arm has no async frame to yield into. Refusing to drop the cleanup (never-silent).` ); } postExitMessage({ codeArg, signaled, grpExit }); } const __NR_RT_SIGACTION = 13; const __NR_KILL = 62; const __NR_WAIT4 = 61; const __NR_TKILL = 200; const __NR_TGKILL = 234; const __NR_CLOSE = 3; const __NR_DUP = 32; const __NR_DUP2 = 33; const __NR_PIPE = 22; const __NR_DUP3 = 292; const __NR_PIPE2 = 293; const __NR_SETPGID = 109; const __NR_GETPGRP = 111; const __NR_SETSID = 112; const __NR_GETPGID = 121; const __NR_GETSID = 124; const __NR_GETPID = 39; const __NR_GETPPID = 110; const __NR_SET_TID_ADDRESS = 218; const __NR_READ = 0; const __NR_WRITE = 1; const __NR_LSEEK = 8; const __NR_READV = 19; const __NR_WRITEV = 20; const __NR_IOCTL = 16; const __NR_OPEN = 2; const __NR_OPENAT = 257; const __NR_CREAT = 85; const __NR_CHDIR = 80; const __NR_FCHDIR = 81; const __NR_GETCWD = 79; const __NR_FCNTL = 72; const __NR_FLOCK = 73; const __NR_STAT = 4; const __NR_FSTAT = 5; const __NR_LSTAT = 6; const __NR_GETDENTS64 = 217; const __NR_NEWFSTATAT = 262; const __NR_STATX = 332; const __NR_CLOCK_GETTIME = 228; const __NR_CLOCK_GETRES = 229; const __NR_NANOSLEEP = 35; const __NR_CLOCK_NANOSLEEP = 230; const __NR_RESTART_SYSCALL = 219; const __NR_GETTIMEOFDAY = 96; const __NR_TIME = 201; const __NR_GETITIMER = 36; const __NR_SETITIMER = 38; const __NR_SCHED_SETAFFINITY = SYS_SCHED_SETAFFINITY; const __NR_SCHED_GETAFFINITY = 204; const __NR_GETCPU = 309; const __NR_SIGALTSTACK = 131; const __NR_GETUID = 102; const __NR_GETGID = 104; const __NR_GETEUID = 107; const __NR_GETEGID = 108; const __NR_UTIMENSAT = 280; const __NR_UNLINKAT = 263; const __NR_ACCESS = 21; const __NR_FACCESSAT = 269; const __NR_FACCESSAT2 = 439; const __NR_READLINK = 89; const __NR_READLINKAT = 267; const __NR_FSYNC = 74; const __NR_FDATASYNC = 75; const __NR_SYNC = 162; const __NR_SYNCFS = 306; const __NR_RENAME = 82; const __NR_MKDIR = 83; const __NR_RMDIR = 84; const __NR_UNLINK = 87; const __NR_CHMOD = 90; const __NR_MKDIRAT = 258; const __NR_RENAMEAT = 264; const __NR_FCHMODAT = 268; const __NR_RENAMEAT2 = 316; const __NR_FCHMODAT2 = 452; const __NR_MOUNT = 165; const __NR_UMOUNT2 = 166; const __NR_PIVOT_ROOT = 155; const __NR_UNSHARE = 272; const __NR_POLL = 7; const __NR_SELECT = 23; const __NR_PSELECT6 = 270; const __NR_PPOLL = 271; const __NR_SOCKET = 41; const __NR_GETSOCKOPT = 55; const __NR_ACCEPT4 = 288; const __NR_MMAP_72 = 9; const __NR_PREAD64 = 17; const __NR_PWRITE64 = 18; const __NR_UNAME = 63; const __NR_TRUNCATE = 76; const __NR_FTRUNCATE = 77; const __NR_GETRANDOM = 318; const __NR_SYSLOG = 103; const __NR_LINK = 86; const __NR_SYMLINK = 88; const __NR_FCHMOD = 91; const __NR_CHOWN = 92; const __NR_FCHOWN = 93; const __NR_LCHOWN = 94; const __NR_MKNOD = 133; const __NR_MKNODAT = 259; const __NR_FCHOWNAT = 260; const __NR_LINKAT = 265; const __NR_SYMLINKAT = 266; const __NR_CAPGET = 125; const __NR_CAPSET = 126; const __NR_GETTID = 186; const __NR_SENDFILE = 40; const __NR_STATFS = 137; const __NR_FSTATFS = 138; const __NR_COPY_FILE_RANGE = 326; const mmapFileRed = !!SYS_ENV.HWJS_RED_MMAP_FILE_UNPOPULATED; if (nr === __NR_MMAP_72 && !mmapFileRed && ((a3 | 0) & 32) === 0) { const flags = a3 | 0, prot = a2 | 0, mfd = a4 | 0; const len = a1 >>> 0, off = a5 >>> 0; const mtype = flags & 15; const refuse3 = (err2, why) => { try { post({ kind: "dmesg", level: 3, text: `hwjs-mmap pid=${ctrl[C.PID] | 0} file-backed mmap REFUSED (${why}): fd=${mfd} len=0x${len.toString(16)} prot=0x${(prot >>> 0).toString(16)} flags=0x${(flags >>> 0).toString(16)} off=0x${off.toString(16)} -> errno ${-err2} (linux-in-the-browser#72)` }); } catch (_e) { } return err2 | 0; }; if (mfd === -1) return refuse3(-9, "no MAP_ANONYMOUS and fd == -1"); if (len === 0) return -22; if ((off & 4095) !== 0) return -22; if (mtype !== 1 && mtype !== 2 && mtype !== 3) return -22; if (!(vmlinuxInstance && perProcessTaskAddr !== 0 && typeof vmlinuxInstance.exports.wasm_syscall === "function")) return refuse3( -19, "no in-Worker kernel context to populate from the file" ); if ((flags & 16) !== 0) return refuse3( -19, "MAP_FIXED file mapping unsupported (the host bump allocator owns placement)" ); const writeShared = mtype !== 2 && (prot & 2) !== 0; let admitted = null; if (writeShared) { admitted = sharedMaps.admit(mfd, true, off); if (admitted.held) return admitted.err; if (admitted.err !== 0) { if (admitted.err === -9) return -9; return refuse3(admitted.err, `writable MAP_SHARED: ${admitted.why}`); } } else if (mtype !== 2) { admitted = sharedMaps.admit(mfd, false, off); if (admitted.held) return admitted.err; if (admitted.err !== 0) admitted = null; } const device = admitted !== null && admitted.device === true; const mapDevice = () => { const a = syscallInner( 9, 0, len, prot, 34, -1, 0 ) | 0; if (a < 0) return { addr: a, done: 0, err: 0, parked: false, lost: false, restarts: 0 }; const r = sharedMaps.populateDevice(mfd, a, len, off); if (isRestartValue(r) || r === HWJS_EMMAP_PARKED) return { addr: a, done: 0, err: 0, parked: false, lost: false, restarts: 0, again: r }; return { addr: a, done: r < 0 ? 0 : r, err: r < 0 ? r : 0, parked: false, lost: false, restarts: 0 }; }; const { addr, done, err: preadErr, parked, lost, restarts: preadRestarts, again } = device ? mapDevice() : fileMapper.map({ mfd, len, prot, flags, off }); if (parked) return HWJS_EMMAP_PARKED; if (again !== void 0) return again; if (addr < 0) return addr; if (preadErr !== 0) { if (!lost && !isRestartValue(preadErr)) syscallInner(11, addr, len, 0, 0, 0, 0); if (device) return refuse3( -19, `GEM_PREAD population failed (errno ${-preadErr})` ); if (preadErr === -38) return refuse3( -19, "kernel pread64 unwired \u2014 this vmlinux predates the #72 kernel half" ); if (preadErr === -9) { const fl = syscallInner( 72, mfd, 3, 0, 0, 0, 0 ) | 0; return fl < 0 ? -9 : refuse3(-13, "fd not open for reading"); } if (preadErr === -29 || preadErr === -21 || preadErr === -22) return refuse3( -19, `fd does not support positioned read (pread errno ${-preadErr})` ); return refuse3(preadErr, "pread64 population failed"); } if (writeShared) { const terr = sharedMaps.track({ addr, len, off, fd: mfd, st: admitted.st, device }); if (terr < 0) { syscallInner(11, addr, len, 0, 0, 0, 0); if (terr === HWJS_EMMAP_PARKED || isRestartValue(terr)) return terr; return refuse3(terr, "writable MAP_SHARED: no descriptor left to keep for it"); } } else if (admitted !== null && sharedMaps.track({ addr, len, off, fd: mfd, st: admitted.st, readOnly: true, device }) === 0) { } else if (mtype !== 2 && !hwjsMmapSharedSnapshotWarned) { hwjsMmapSharedSnapshotWarned = true; try { post({ kind: "dmesg", level: 4, text: `hwjs-mmap pid=${ctrl[C.PID] | 0} MAP_SHARED read-only file mapping is an eager snapshot on wasm32 (no faults -> no coherence with later file writes; linux-in-the-browser#72)` }); } catch (_e) { } } if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} MMAP-FILE fd=${mfd} off=0x${off.toString(16)} len=0x${len.toString(16)} populated=${done}B restarts=${preadRestarts} -> 0x${(addr >>> 0).toString(16)}` }); } catch (_e) { } } return addr | 0; } if (nr === 26 && !mmapFileRed) return sharedMaps.msync(a0 >>> 0, a1 >>> 0, a2 | 0); if (nr === 25 && !mmapFileRed) { const r = sharedMaps.remap(a0 >>> 0, a1 >>> 0, a2 >>> 0, a3 | 0); if (r !== null) return r; } if (nr === __NR_PREAD64 && !mmapFileRed) { const held = fileMapper.settle(); if (held !== 0) return held; } let routeToWasmSyscall = false; if (kernelImplements !== null && perProcessTaskAddr !== 0 && vmlinuxInstance && typeof vmlinuxInstance.exports.wasm_syscall === "function" && (nr | 0) >= 0 && (nr | 0) < kernelImplements.length && kernelImplements[nr | 0] === 1 && HOST_ANSWERS_NR[nr | 0] === 0) { routeToWasmSyscall = true; } if (init.forceWasmSyscall && vmlinuxInstance && perProcessTaskAddr !== 0 && typeof vmlinuxInstance.exports.wasm_syscall === "function") { routeToWasmSyscall = true; } if (kernelImplements !== null && nr === __NR_RT_SIGACTION && vmlinuxInstance && typeof vmlinuxInstance.exports.wasm_syscall === "function") { routeToWasmSyscall = true; } if (kernelImplements === null && vmlinuxInstance && typeof vmlinuxInstance.exports.wasm_syscall === "function") { if (nr === __NR_RT_SIGACTION) { routeToWasmSyscall = true; } else if (nr === 56 && a0 >>> 0 & 256) { if (perProcessTaskAddr !== 0 && mainLaneAddressed && userExports && typeof userExports.__hwjs_thread_attach === "function" && globalThis.process?.env?.HWJS_EXPERIMENTAL_THREAD_CLONE !== "1") { routeToWasmSyscall = true; } } else if (nr === __NR_TKILL || nr === __NR_TGKILL) { routeToWasmSyscall = true; } else if (nr === __NR_KILL) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_WAIT4) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_PIPE || nr === __NR_PIPE2 || nr === __NR_DUP || nr === __NR_DUP2 || nr === __NR_DUP3 || nr === __NR_CLOSE) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_SETPGID || nr === __NR_GETPGID || nr === __NR_SETSID || nr === __NR_GETSID || nr === __NR_GETPGRP) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_GETPID) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_GETCWD) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_SET_TID_ADDRESS && init.mode === "fork-resume") { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_CLOCK_GETTIME || nr === __NR_CLOCK_GETRES || nr === __NR_GETTIMEOFDAY || nr === __NR_TIME) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_NANOSLEEP || nr === __NR_CLOCK_NANOSLEEP) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_RESTART_SYSCALL) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_SETITIMER || nr === __NR_GETITIMER) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_SCHED_SETAFFINITY || nr === __NR_SCHED_GETAFFINITY || nr === __NR_GETCPU) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_SIGALTSTACK) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_STAT || nr === __NR_FSTAT || nr === __NR_LSTAT || nr === __NR_NEWFSTATAT || nr === __NR_STATX || nr === __NR_GETDENTS64) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_CHDIR || nr === __NR_FCHDIR) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_OPEN || nr === __NR_OPENAT || nr === __NR_CREAT) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_IOCTL) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_FCNTL) { const fcntlRed = !!SYS_ENV.HWJS_RED_FCNTL_FDGATE; if (perProcessTaskAddr !== 0 && (!fcntlRed || (a0 | 0) >= 3 || kernelRoutedLowFds.has(a0 | 0))) routeToWasmSyscall = true; } else if (nr === __NR_FLOCK) { const flockRed = !!SYS_ENV.HWJS_RED_FLOCK_UNROUTED; if (perProcessTaskAddr !== 0 && !flockRed) routeToWasmSyscall = true; } else if (nr === __NR_READ || nr === __NR_READV) { if (perProcessTaskAddr !== 0 && ((a0 | 0) === 0 || (a0 | 0) >= 3 || kernelRoutedLowFds.has(a0 | 0))) routeToWasmSyscall = true; } else if (nr === __NR_WRITE || nr === __NR_WRITEV) { if (perProcessTaskAddr !== 0 && ((a0 | 0) >= 3 || kernelRoutedLowFds.has(a0 | 0))) routeToWasmSyscall = true; } else if (nr === __NR_LSEEK) { if (perProcessTaskAddr !== 0 && ((a0 | 0) >= 3 || kernelRoutedLowFds.has(a0 | 0))) routeToWasmSyscall = true; } else if (nr === __NR_GETPPID) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_GETUID || nr === __NR_GETGID || nr === __NR_GETEUID || nr === __NR_GETEGID) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_POLL || nr === __NR_SELECT || nr === __NR_PSELECT6 || nr === __NR_PPOLL) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_MOUNT || nr === __NR_UMOUNT2 || nr === __NR_PIVOT_ROOT || nr === __NR_UNSHARE) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr >= __NR_SOCKET && nr <= __NR_GETSOCKOPT || nr === __NR_ACCEPT4) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_UTIMENSAT || nr === __NR_UNLINKAT) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_ACCESS || nr === __NR_FACCESSAT || nr === __NR_FACCESSAT2) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_READLINK || nr === __NR_READLINKAT) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_MKDIR || nr === __NR_MKDIRAT || nr === __NR_RMDIR || nr === __NR_UNLINK || nr === __NR_RENAME || nr === __NR_RENAMEAT || nr === __NR_RENAMEAT2 || nr === __NR_CHMOD || nr === __NR_FCHMODAT || nr === __NR_FCHMODAT2) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_PREAD64 || nr === __NR_PWRITE64) { if (perProcessTaskAddr !== 0 && !mmapFileRed) routeToWasmSyscall = true; } else if (nr === __NR_SYNC || nr === __NR_FSYNC || nr === __NR_FDATASYNC || nr === __NR_SYNCFS) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_UNAME || nr === __NR_TRUNCATE || nr === __NR_FTRUNCATE || nr === __NR_GETRANDOM) { const red788081 = !!SYS_ENV.HWJS_RED_788081_UNROUTED; if (perProcessTaskAddr !== 0 && !red788081) routeToWasmSyscall = true; } else if (nr === __NR_SYSLOG) { const red88syslog = !!SYS_ENV.HWJS_RED_88_SYSLOG_UNROUTED; if (perProcessTaskAddr !== 0 && !red88syslog) routeToWasmSyscall = true; } else if (nr === __NR_LINK || nr === __NR_LINKAT || nr === __NR_SYMLINK || nr === __NR_SYMLINKAT || nr === __NR_MKNOD || nr === __NR_MKNODAT || nr === __NR_FCHMOD || nr === __NR_CHOWN || nr === __NR_FCHOWN || nr === __NR_LCHOWN || nr === __NR_FCHOWNAT) { const red58vfsmut = !!SYS_ENV.HWJS_RED_58_VFSMUT_UNROUTED; if (perProcessTaskAddr !== 0 && !red58vfsmut) routeToWasmSyscall = true; } else if (nr === __NR_CAPGET || nr === __NR_CAPSET || nr === __NR_GETTID) { if (perProcessTaskAddr !== 0) routeToWasmSyscall = true; } else if (nr === __NR_STATFS || nr === __NR_FSTATFS || nr === __NR_SENDFILE || nr === __NR_COPY_FILE_RANGE) { const red104fsgap = !!SYS_ENV.HWJS_RED_104_FSGAP_UNROUTED; if (perProcessTaskAddr !== 0 && !red104fsgap) routeToWasmSyscall = true; } } if (routeToWasmSyscall && kernelImplements !== null) { const env = SYS_ENV; const fd = a0 | 0; const lowFdIsKernel = fd >= 3 || kernelRoutedLowFds.has(fd); if ((nr === __NR_READ || nr === __NR_READV) && !(fd === 0 || lowFdIsKernel)) routeToWasmSyscall = false; if ((nr === __NR_WRITE || nr === __NR_WRITEV || nr === __NR_LSEEK) && !lowFdIsKernel) routeToWasmSyscall = false; if (nr === 56 && !(a0 >>> 0 & 256 && mainLaneAddressed && userExports && typeof userExports.__hwjs_thread_attach === "function" && env.HWJS_EXPERIMENTAL_THREAD_CLONE !== "1")) routeToWasmSyscall = false; if (nr === __NR_SET_TID_ADDRESS) { mainClearTid = a0 >>> 0; if (init.mode !== "fork-resume") routeToWasmSyscall = false; } if (env.HWJS_RED_FCNTL_FDGATE && nr === __NR_FCNTL && !lowFdIsKernel) routeToWasmSyscall = false; if (env.HWJS_RED_FLOCK_UNROUTED && nr === __NR_FLOCK) routeToWasmSyscall = false; if (env.HWJS_RED_MMAP_FILE_UNPOPULATED && (nr === __NR_PREAD64 || nr === __NR_PWRITE64)) routeToWasmSyscall = false; if (env.HWJS_RED_788081_UNROUTED && (nr === __NR_UNAME || nr === __NR_TRUNCATE || nr === __NR_FTRUNCATE || nr === __NR_GETRANDOM)) routeToWasmSyscall = false; if (env.HWJS_RED_88_SYSLOG_UNROUTED && nr === __NR_SYSLOG) routeToWasmSyscall = false; if (env.HWJS_RED_58_VFSMUT_UNROUTED && (nr === __NR_LINK || nr === __NR_LINKAT || nr === __NR_SYMLINK || nr === __NR_SYMLINKAT || nr === __NR_MKNOD || nr === __NR_MKNODAT || nr === __NR_FCHMOD || nr === __NR_CHOWN || nr === __NR_FCHOWN || nr === __NR_LCHOWN || nr === __NR_FCHOWNAT)) routeToWasmSyscall = false; if (env.HWJS_RED_104_FSGAP_UNROUTED && (nr === __NR_STATFS || nr === __NR_FSTATFS || nr === __NR_SENDFILE || nr === __NR_COPY_FILE_RANGE)) routeToWasmSyscall = false; } if (D1_TRACE_FD && (nr === __NR_PIPE || nr === __NR_PIPE2 || nr === __NR_DUP2 || nr === __NR_DUP3 || nr === __NR_CLOSE || nr === __NR_WRITE || nr === __NR_READ || nr === __NR_WRITEV || nr === __NR_READV || nr === __NR_GETCWD)) { post({ kind: "dmesg", level: 6, text: `hwjs-fd pid=${ctrl[C.PID] | 0} mode=${init.mode} PRE nr=${nr | 0}(a0=${a0 | 0},a1=${a1 | 0},a2=${a2 | 0}) route=${routeToWasmSyscall ? "KERNEL" : "js-direct"} ptask=0x${(perProcessTaskAddr >>> 0).toString(16)} lowfds={${[...kernelRoutedLowFds].join(",")}}` }); } if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `SYSTRACE pid=${ctrl[C.PID] | 0} PRE nr=${nr | 0} route=${routeToWasmSyscall ? "K" : "js"} a0=0x${(a0 >>> 0).toString(16)} a1=0x${(a1 >>> 0).toString(16)}` }); } catch (_e) { } } if (routeToWasmSyscall) { let isSelfTarget = false; if (nr === __NR_TKILL || nr === __NR_TGKILL) { const targetTid = nr === __NR_TGKILL ? a1 | 0 : a0 | 0; isSelfTarget = targetTid === (init.tid | 0); } else if (nr === __NR_KILL) { isSelfTarget = (a0 | 0) === (init.pid | 0); } try { if (!libcParkAbiPushed && vmlinuxInstance && typeof vmlinuxInstance.exports.__wasm32_set_libc_park_abi === "function") { try { vmlinuxInstance.exports.__wasm32_set_libc_park_abi( libcParksAnySyscall ? 1 : 0 ); libcParkAbiPushed = true; } catch (_e) { } } if (SYS_ENV.A4C_FORKDBG) { try { post({ kind: "dmesg", level: 6, text: `[a4c-sys tid=${init.tid}] PRE nr=${nr | 0}` }); } catch (_e) { } } let r = kernelDispatch(nr, a0, a1, a2, a3, a4, a5); wasmSyscallStats[nr | 0]++; if (SYS_ENV.A4C_FORKDBG) { try { post({ kind: "dmesg", level: 6, text: `[a4c-sys tid=${init.tid}] nr=${nr | 0} -> ${r | 0}` }); } catch (_e) { } } const coopParkCapable = coopParkCapableFor(nr); if ((r | 0) === HWJS_ERESTART_RESCHED && blockParkGoesToGuest(nr)) { if (!veneerParkReported && libcParksAnySyscall && !HWJS_CANCELLABLE_SYSCALLS.has(nr | 0)) { veneerParkReported = true; try { post({ kind: "dmesg", level: 6, text: `hwjs-coopwait VENEER-PARK pid=${ctrl[C.PID] | 0} tid=${init.tid | 0} rt=${init.rtThread ? 1 : 0} mode=${init.mode}: syscall nr=${nr | 0} block-parked and this image absorbs -517 at raw veneers (__hwjs_libc_syscall_park_abi=1) \u2014 the CPU Worker was handed back instead of spun on synchronously` }); } catch (_e) { } } return HWJS_ERESTART_RESCHED; } if ((r | 0) === HWJS_ERESTART_RESCHED) { if (coopParkCapable) { syncRestartViolations++; if ((syncRestartViolations & syncRestartViolations - 1) === 0) { const m = `hwjs-coopwait SYNC-RESTART pid=${ctrl[C.PID] | 0} tid=${init.tid | 0} rt=${init.rtThread ? 1 : 0} mode=${init.mode}: syscall nr=${nr | 0} block-parked (-517) but this image's libc does not absorb the sentinel at raw syscalls (__hwjs_libc_syscall_park_abi ${libcParksAnySyscall ? "=1" : "absent"}, hwjsDrive=${hwjsDrive ? 1 : 0}), so the host must restart it in place on a SYNCHRONOUS wait \u2014 freezing this CPU Worker's event loop, and with it every co-resident task, for the duration. Occurrences so far: ${syncRestartViolations} (PLAN-THREAD-POOL-RESIDENCY contract 3; loud, attributed).`; try { post({ kind: "dmesg", level: 4, text: m }); } catch (_e) { } } } if (perProcessTaskAddr === 0 || kernelI32 === null) { post({ kind: "error", pid: init.pid, message: `HWJS-A-4: syscall nr=${nr | 0} returned -ERESTART_RESCHED but no kernel task_struct is reachable (perProcessTaskAddr=0x${(perProcessTaskAddr >>> 0).toString(16)}, kernelMem=${kernelI32 ? "present" : "absent"}) \u2014 cannot yield for the in-flight completion; refusing to spin.` }); return -38; } let reschedRestarts = 0; const hold = SCHED_TRACE ? holdReport(post, { cpu: init.cpuId, pid: ctrl[C.PID] | 0, tid: init.tid, site: "sync-restart", label: `wasm_syscall:${nr | 0}`, announce: false, fields: (n) => `restarts=${n}` }) : HOLD_REPORT_OFF; while ((r | 0) === HWJS_ERESTART_RESCHED) { if (++reschedRestarts > HWJS_RESCHED_RESTART_CAP) { post({ kind: "error", pid: init.pid, message: `HWJS-A-4: syscall nr=${nr | 0} restarted ${reschedRestarts} times still returning -ERESTART_RESCHED \u2014 the task never became runnable (FUSE/blocking completion never landed). Aborting the restart loop loudly rather than hanging.` }); syncRestartGaveUp = nr | 0; return -4; } awaitReschedRunnable(`wasm_syscall nr=${nr | 0}`); if (SCHED_TRACE) hold.tick(reschedRestarts); stwHoldSyncIfRequested(); r = kernelDispatch(nr, a0, a1, a2, a3, a4, a5); } if (SCHED_TRACE) hold.end(reschedRestarts); } if ((nr | 0) === __NR_WAIT4) { const wr = r | 0; if (RED_SIGCHLD_ARM_WNOHANG) { if (wr === -10) sigchldArmed = false; else if (wr >= 0) sigchldArmed = true; } else if (wr === -10 || wr === 0) { sigchldArmed = false; } else if (wr > 0) { sigchldArmed = true; } } const rInt = r | 0; if (rInt >= 0) { if (nr === __NR_DUP2 || nr === __NR_DUP3) { const oldfd = a0 | 0; const newfd = a1 | 0; if (newfd >= 0 && newfd <= 2) { const oldIsKernelFile = oldfd >= 3 || kernelRoutedLowFds.has(oldfd); if (oldIsKernelFile) kernelRoutedLowFds.add(newfd); else kernelRoutedLowFds.delete(newfd); } } else if (nr === __NR_DUP) { const oldfd = a0 | 0; const newfd = rInt; if (newfd >= 0 && newfd <= 2) { const oldIsKernelFile = oldfd >= 3 || kernelRoutedLowFds.has(oldfd); if (oldIsKernelFile) kernelRoutedLowFds.add(newfd); else kernelRoutedLowFds.delete(newfd); } } else if (nr === __NR_CLOSE) { const fd = a0 | 0; if (fd >= 0 && fd <= 2) kernelRoutedLowFds.delete(fd); } else if (nr === __NR_OPEN || nr === __NR_OPENAT || nr === __NR_CREAT || nr === __NR_FCNTL) { const isDupFcntl = nr === __NR_FCNTL && ((a1 | 0) === 0 || (a1 | 0) === 1030); const lowFdRed = !!SYS_ENV.HWJS_RED_LOWFD_OPEN; if (!lowFdRed && (nr !== __NR_FCNTL || isDupFcntl) && rInt >= 0 && rInt <= 2) { kernelRoutedLowFds.add(rInt); } } } if (D1_TRACE_FD && (nr === __NR_PIPE || nr === __NR_PIPE2 || nr === __NR_DUP2 || nr === __NR_DUP3 || nr === __NR_CLOSE || nr === __NR_WRITE || nr === __NR_WRITEV || nr === __NR_READV || nr === __NR_READ)) { post({ kind: "dmesg", level: 6, text: `hwjs-fd pid=${ctrl[C.PID] | 0} POST nr=${nr | 0} -> ret=${r | 0} lowfds={${[...kernelRoutedLowFds].join(",")}}` }); } const isRestartSentinel = rInt <= -512 && rInt >= -516; const waitForUserBit = isSelfTarget && rInt === 0 || isRestartSentinel; if (waitForUserBit && signalPendingIdx >= 0) { const wakeIdx = signalPendingIdx + 2; const startWake = Atomics.load(uI32(), wakeIdx) | 0; if (!signalPending()) { hostWait(uI32(), wakeIdx, startWake, 100); } } if (DEBUG_K7_U4F) writeDebug(` -> [kern] nr=${nr} ret=${r | 0} `); if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} RET nr=${nr | 0} route=KERNEL ret=${r | 0}` }); } catch (_e) { } } return r | 0; } catch (e) { const m = e instanceof Error ? e.message : String(e); const stk = e instanceof Error && e.stack ? "\nWASM-SYSCALL-STACK: " + e.stack.split("\n").slice(0, 32).join(" | ") : ""; const laneDirty = containTrappedLane(`wasm_syscall nr=${nr | 0}`); if (laneDirty !== 0 && ++syscallTrapContainments <= SYSCALL_TRAP_CONTAIN_CAP) { const frames = e instanceof Error && e.stack ? e.stack.split("\n").slice(0, 16).map((l) => l.trim()).join(" | ") : m.split("\n")[0]; post({ kind: "dmesg", level: 3, text: `hwjs #85 CONTAINMENT pid=${init.pid}: wasm_syscall nr=${nr | 0} trapped on a POISONED LANE; lane reclaimed (mask=${laneDirty}), returning -EINTR to the caller (containment ${syscallTrapContainments}/${SYSCALL_TRAP_CONTAIN_CAP} for this Worker) \u2014 the trapped in-flight chain's frames are leaked, attributed. The dirt is USUALLY a thread Worker that died mid-protocol on this lane (#85), but it is equally a coroutinized callee published under a NATIVE caller, and only the stack tells them apart: ${frames}` }); return -4; } post({ kind: "error", pid: init.pid, message: "K11-B5/B6: vmlinux.wasm_syscall trapped at nr=" + (nr | 0) + ": " + m + stk }); throw e; } } if (mergedRpcPending !== null) { const p = mergedRpcPending; const same2 = p.nr === (nr | 0) && p.a0 === (a0 | 0) && p.a1 === (a1 | 0) && p.a2 === (a2 | 0) && p.a3 === (a3 | 0) && p.a4 === (a4 | 0) && p.a5 === (a5 | 0); if (!same2) { mergedRpcPending = null; Atomics.store(ctrl, C.STATE, IDLE); try { post({ kind: "dmesg", level: 3, text: `hwjs-merged DEFERRED-RPC MISMATCH pid=${ctrl[C.PID] | 0} tid=${init.tid | 0}: nr=${p.nr} was in flight on the merged lane and the guest came back asking nr=${nr | 0} instead. A -517 park is only correct if the libc RE-ISSUES THE SAME CALL; this libc did not, so the answer in the control SAB belongs to a question nobody is asking any more. Refusing with -ENOSYS rather than handing it over.` }); } catch (_e) { } return -38; } if (Atomics.load(ctrl, C.STATE) === RESPONSE) { const lo0 = ctrl[C.RET_LO] | 0; Atomics.store(ctrl, C.STATE, IDLE); mergedRpcPending = null; mergedRpcCompleted++; if (DEBUG_K7_U4F) writeDebug(` -> [sab/merged] nr=${nr} ret=${lo0} `); if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} RET nr=${nr | 0} route=host-RPC/deferred ret=${lo0 | 0} parks=${p.parks}` }); } catch (_e) { } } return lo0; } if (++p.parks > MERGED_RPC_PARK_CAP) { mergedRpcPending = null; Atomics.store(ctrl, C.STATE, IDLE); post({ kind: "error", pid: init.pid, message: `hwjs-merged DEFERRED-RPC UNANSWERED pid=${ctrl[C.PID] | 0} tid=${init.tid | 0}: host-RPC nr=${nr | 0} was issued on the merged CPU-0 lane and re-checked across ${MERGED_RPC_PARK_CAP} cooperative parks without the responder ever writing an answer. The thread WAS handed back on every one of them, so this is not the merged deadlock \u2014 the responder itself never ran or never answered. Returning -EINTR rather than parking forever.` }); return -4; } mergedRpcParks++; if ((p.parks & p.parks - 1) === 0 && p.parks >= 64) { try { post({ kind: "dmesg", level: 4, text: `hwjs-merged DEFERRED-RPC SLOW pid=${ctrl[C.PID] | 0} tid=${init.tid | 0}: host-RPC nr=${nr | 0} still unanswered after ${p.parks} cooperative parks (${Date.now() - p.t0}ms). The thread was handed back on every one of them, so the responder had its turn and did not answer.` }); } catch (_e) { } } return HWJS_ERESTART_RESCHED; } Atomics.store(ctrl, C.NR, nr | 0); Atomics.store(ctrl, C.A0, a0 | 0); Atomics.store(ctrl, C.A1, a1 | 0); Atomics.store(ctrl, C.A2, a2 | 0); Atomics.store(ctrl, C.A3, a3 | 0); Atomics.store(ctrl, C.A4, a4 | 0); Atomics.store(ctrl, C.A5, a5 | 0); Atomics.store(ctrl, C.STATE, REQUEST); let doorTookRequest = false; if (init.mergedCpu0Lane === true && workerHostSyncCall !== null) { let door2; try { door2 = workerHostSyncCall(MERGED_SYSCALL_SYNC_MSG); } catch (_e) { door2 = void 0; } if (door2 === "sync" && Atomics.load(ctrl, C.STATE) === RESPONSE) { const lo2 = ctrl[C.RET_LO] | 0; Atomics.store(ctrl, C.STATE, IDLE); mergedRpcInPlace++; if (DEBUG_K7_U4F) writeDebug(` -> [sab/merged-sync] nr=${nr} ret=${lo2} `); if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} RET nr=${nr | 0} route=host-RPC/in-place ret=${lo2 | 0}` }); } catch (_e) { } } return lo2; } if (door2 === "async") { doorTookRequest = true; mergedRpcDoorAsync++; } } if (!doorTookRequest) post({ kind: "syscall", pid: init.pid }); if (init.mergedCpu0Lane === true) { if (!blockParkGoesToGuest(nr)) { mergedHostRpcRefusals++; if ((mergedHostRpcRefusals & mergedHostRpcRefusals - 1) === 0) { try { post({ kind: "dmesg", level: 3, text: `hwjs-merged REFUSED a host-RPC syscall on the merged CPU-0 lane: nr=${nr | 0} pid=${ctrl[C.PID] | 0} tid=${init.tid | 0}. The responder runs on the launching thread and this lane shares it, so the answer can only be produced by a thread this lane would be holding. The merged route out of that is the cooperative -517 park, and THIS IMAGE CANNOT TAKE ONE at this veneer (__hwjs_libc_syscall_park_abi ${libcParksAnySyscall ? "=1" : "absent"}, hwjsDrive=${hwjsDrive ? 1 : 0}, cancellable=${HWJS_CANCELLABLE_SYSCALLS.has(nr | 0) ? "yes" : "no"}) \u2014 so it would fall into the in-place restart loop, whose wait is a thread-blocking Atomics.wait. Returning -ENOSYS instead of a livelock (occurrence ${mergedHostRpcRefusals}). What fixes this is the libc absorbing -517 at raw veneers, not a change here.` }); } catch (_e) { } } Atomics.store(ctrl, C.STATE, IDLE); return -38; } mergedRpcPending = { nr: nr | 0, a0: a0 | 0, a1: a1 | 0, a2: a2 | 0, a3: a3 | 0, a4: a4 | 0, a5: a5 | 0, parks: 0, t0: Date.now() }; mergedRpcParks++; return HWJS_ERESTART_RESCHED; } { const RPC_SLICE_MS = 250; const RPC_REPORT_MS = 1e4; const rpcT0 = Date.now(); let rpcNextReport = rpcT0 + RPC_REPORT_MS; const rpc = hostRpcWait({ ctrl, sliceMs: RPC_SLICE_MS, wait: hostWait, onSlice: () => { if (Date.now() >= rpcNextReport) { rpcNextReport = Date.now() + RPC_REPORT_MS; const m = `hwjs-hostrpc STALL pid=${ctrl[C.PID] | 0} tid=${init.tid | 0} rt=${init.rtThread ? 1 : 0} mode=${init.mode}: host-RPC syscall nr=${nr | 0} unanswered after ${Date.now() - rpcT0}ms. This lane is blocked in the control SAB, which no signal, pause or fork servicer can wake \u2014 only the host's answer can. On a pool Worker that blocks every co-resident task and the message loop for the duration (loud, attributed, never a silent wedge).`; try { post({ kind: "dmesg", level: 4, text: m }); } catch (_e) { } } } }); if (rpc === "reaped" && sched) { Atomics.store(ctrl, C.STATE, IDLE); throw HWJS_REAPED_UNWIND; } } const lo = ctrl[C.RET_LO] | 0; Atomics.store(ctrl, C.STATE, IDLE); if (DEBUG_K7_U4F) writeDebug(` -> [sab] nr=${nr} ret=${lo} `); if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} RET nr=${nr | 0} route=host-RPC ret=${lo | 0}` }); } catch (_e) { } } return lo; } let vmlinuxInstance = null; let perProcessTaskAddr = 0; const republishSignals = () => { const f = vmlinuxInstance?.exports?.__wasm32_signal_republish; if (typeof f !== "function") return; try { f(); } catch (_e) { } }; let wakeWordOff = null; let parkDeadlineOff = null; let hwjsLane = null; let kernelImplements = null; if (init.vmlinuxModule) { const r = await instantiateProcessWorkerVmlinux(init, post); if (!r) { post({ kind: "dmesg", level: 3, text: `hwjs#65: spawn refused \u2014 per-Worker vmlinux/task-alloc failed (tid=${init.tid | 0} ppid=${init.ppid | 0} cpu=${init.cpuId | 0}); the user binary will NOT run (a task with no registered kernel pid must never issue syscalls \u2014 R-K11.6-W1 closed structurally)` }); return; } { vmlinuxInstance = r.instance; perProcessTaskAddr = r.perProcessTaskAddr | 0; hwjsLane = r.hwjsLane || null; if (vmlinuxInstance.cpu && vmlinuxInstance.cpu.syscallTable) { kernelImplements = vmlinuxInstance.cpu.syscallTable; } else if (typeof vmlinuxInstance.exports.wasm32_syscall_implemented === "function" && typeof vmlinuxInstance.exports.wasm32_syscall_table_size === "function") { try { const n = vmlinuxInstance.exports.wasm32_syscall_table_size() | 0; if (n > 0 && n <= 4096) { const t = new Uint8Array(n); let wired = 0; for (let i = 0; i < n; i++) { const v = vmlinuxInstance.exports.wasm32_syscall_implemented(i) | 0; t[i] = v ? 1 : 0; wired += t[i]; } kernelImplements = t; if (vmlinuxInstance.cpu) vmlinuxInstance.cpu.syscallTable = t; post({ kind: "dmesg", level: 6, text: `hwjs-route pid=${ctrl[C.PID] | 0} kernel syscall table: ${wired}/${n} implemented \u2014 the kernel's table is the routing rule; host exceptions are named in HOST_ANSWERED` }); } } catch (_e) { kernelImplements = null; } } if (kernelImplements === null) { post({ kind: "dmesg", level: 4, text: `hwjs-route pid=${ctrl[C.PID] | 0} this vmlinux exports no wasm32_syscall_implemented \u2014 falling back to the host-side per-nr allowlist. Syscalls the kernel implements but the list omits will be answered by the host responder without consulting the kernel.` }); } if (typeof vmlinuxInstance.exports.__hwjs_task_wake_addr === "function" && perProcessTaskAddr !== 0 && kernelI32 !== null) { try { const wa = vmlinuxInstance.exports.__hwjs_task_wake_addr() >>> 0; if (wa !== 0) wakeWordOff = wa - (perProcessTaskAddr >>> 0) | 0; } catch (_e) { } } if (typeof vmlinuxInstance.exports.__hwjs_task_park_deadline_addr === "function" && perProcessTaskAddr !== 0 && kernelI32 !== null) { try { const da = vmlinuxInstance.exports.__hwjs_task_park_deadline_addr() >>> 0; if (da !== 0 && (da & 3) === 0) parkDeadlineOff = da - (perProcessTaskAddr >>> 0) | 0; } catch (_e) { } } if (typeof r.kernelPid === "number" && r.kernelPid > 0) { ctrl[C.PID] = r.kernelPid | 0; if (init.mode !== "thread" || init.vforkChild) ctrl[C.TID] = r.kernelPid | 0; if (init.mode !== "thread" && init.mode !== "migrate-resume") armFilePages(r.kernelPid | 0); } } } void vmlinuxInstance; const RESCHED_YIELD_MS = 4; const COOP_WAIT_MS = 15; const COOP_WAIT_FIRST_MS = 1; const COOP_WAIT_QUIET_MS = 8; let coopWaitMs = COOP_WAIT_FIRST_MS; let coopWaitProgressMark = -1; const coopWaitDecay = (ms) => Math.max(COOP_WAIT_FIRST_MS, ms / 2); const coopWaitEpisodeReset = () => { coopWaitMs = COOP_WAIT_FIRST_MS; }; const taskWakeIdx = () => wakeWordOff === null || perProcessTaskAddr === 0 || kernelI32 === null ? -1 : (perProcessTaskAddr >>> 0) + wakeWordOff >>> 2; const stateWakeOff = !!(globalThis.process?.env?.HWJS_NO_STATE_WAKE || globalThis.HWJS_NO_STATE_WAKE); const taskStateIdx = () => stateWakeOff || perProcessTaskAddr === 0 || kernelI32 === null ? -1 : (perProcessTaskAddr >>> 0) + TASK_STATE_OFF >>> 2; const parkDeadlineOffEnv = !!(globalThis.process?.env?.HWJS_NO_PARK_DEADLINE || globalThis.HWJS_NO_PARK_DEADLINE); const taskParkDeadlineMs = (kmem) => { if (parkDeadlineOffEnv || parkDeadlineOff === null || perProcessTaskAddr === 0) return 0; const i = (perProcessTaskAddr >>> 0) + parkDeadlineOff >>> 2; const lo = Atomics.load(kmem, i) >>> 0; const hi = Atomics.load(kmem, i + 1) >>> 0; return (hi * 4294967296 + lo) / 1e6; }; const hostNowMs = () => performance.timeOrigin + performance.now(); async function coopWaitRunnable(where) { if (t67) t67.coopWaits++; const idx = taskWakeIdx(); if (sigchldPendingNow()) sigchldArmed = true; republishSignals(); if (deliverableSignalPending()) return; if (idx < 0) { if (perProcessTaskAddr === 0 || kernelI32 === null) { throw new Error( `${where}: -ERESTARTRESCHED but no kernel task_struct/wake word is reachable (perProcessTaskAddr=0x${(perProcessTaskAddr >>> 0).toString(16)}, kernelMem=${kernelI32 ? "present" : "absent"}) \u2014 refusing to spin.` ); } await new Promise((res) => setTimeout(res, coopWaitMs)); coopWaitMs = Math.min(COOP_WAIT_MS, coopWaitMs * 2); maybeReassertSigchldOnWake(); return; } if (coopProgressSeq !== coopWaitProgressMark) coopWaitMs = coopWaitDecay(coopWaitMs); const kmem = kernelI32Live(); const seq = Atomics.load(kmem, idx) | 0; const deadlineMs = taskParkDeadlineMs(kmem); const remainMs = deadlineMs > 0 ? deadlineMs - hostNowMs() : Infinity; const byDeadline = remainMs < coopWaitMs; const stIdx = taskStateIdx(); const probeSt = stIdx >= 0 ? Atomics.load(kmem, stIdx) | 0 : 0; const probeEnd = performance.now() + (byDeadline ? Math.max(0, remainMs) : coopWaitMs); laneRec.probe = () => (Atomics.load(kmem, idx) | 0) !== seq || stIdx >= 0 && (Atomics.load(kmem, stIdx) | 0) !== probeSt || performance.now() >= probeEnd || deliverableSignalPending(); laneRec.due = probeEnd; laneRec.quiet = deadlineMs > 0 || coopWaitMs >= COOP_WAIT_QUIET_MS; let outcome = "timed-out"; try { if (!byDeadline) { outcome = await waitTaskRunnable(kmem, idx, seq, stIdx, coopWaitMs); } else if (remainMs >= 1) { outcome = await waitTaskRunnable(kmem, idx, seq, stIdx, Math.floor(remainMs)); } if (byDeadline && outcome === "timed-out") { const st = stIdx >= 0 ? Atomics.load(kmem, stIdx) | 0 : 0; while (hostNowMs() < deadlineMs) { if ((Atomics.load(kmem, idx) | 0) !== seq || stIdx >= 0 && (Atomics.load(kmem, stIdx) | 0) !== st || deliverableSignalPending()) { outcome = "ok"; break; } await macrotaskTurn(); } } } catch (_e) { outcome = "ok"; } finally { laneRec.probe = null; laneRec.quiet = false; laneRec.due = Infinity; } if (!byDeadline || outcome !== "timed-out") { coopWaitMs = outcome === "timed-out" ? Math.min(COOP_WAIT_MS, coopWaitMs * 2) : coopWaitDecay(coopWaitMs); } coopWaitProgressMark = coopProgressSeq; maybeReassertSigchldOnWake(); } const FUTEX_COOP_SLICE_MS = 250; const FUTEX_COOP_SLICE_WOKEN_MS = 2e3; const FUTEX_SLICE_TRACE = !!globalThis.process?.env?.HWJS_FUTEX_SLICE_TRACE; async function coopFutexWait() { const f = pendingCoopFutex; if (!f) return; republishSignals(); if (deliverableSignalPending()) return; const widx = taskWakeIdx(); const cap = widx >= 0 ? FUTEX_COOP_SLICE_WOKEN_MS : FUTEX_COOP_SLICE_MS; const remainMs = f.deadlineMs === Infinity ? cap : Math.max(1, f.deadlineMs - Date.now()); const slice = Math.min(remainMs, cap); const kmem = widx >= 0 ? kernelI32Live() : null; const seq = kmem ? Atomics.load(kmem, widx) | 0 : 0; if (kmem && deliverableSignalPending()) return; const view = uI32(); if (Atomics.load(view, f.i32idx) !== f.val) return; const w = Atomics.waitAsync(view, f.i32idx, f.val, slice); if (!w.async) return; const probeEnd = performance.now() + slice; laneRec.probe = () => Atomics.load(uI32(), f.i32idx) !== f.val || kmem !== null && (Atomics.load(kmem, widx) | 0) !== seq || performance.now() >= probeEnd || deliverableSignalPending(); laneRec.due = probeEnd; laneRec.quiet = false; try { if (!kmem) { try { await w.value; } catch (_e) { } return; } const k = Atomics.waitAsync(kmem, widx, seq, slice); if (!k.async) return; let outcome; try { outcome = await Promise.race([w.value, k.value]); } catch (_e) { } if (outcome === "timed-out" && FUTEX_SLICE_TRACE) { try { post({ kind: "dmesg", level: 6, text: `hwjs-futex SLICE-TIMEOUT tid=${init.tid | 0} addr=0x${(f.i32idx << 2 >>> 0).toString(16)} waited-for=${f.val} now=${Atomics.load(uI32(), f.i32idx)} slice=${slice}ms` }); } catch (_e) { } } } finally { laneRec.probe = null; laneRec.quiet = false; laneRec.due = Infinity; } } function awaitReschedRunnable(where) { if (t67) t67.reschedRestarts++; if (perProcessTaskAddr === 0 || kernelI32 === null) { throw new Error( `${where}: -ERESTARTRESCHED but no kernel task_struct is reachable (perProcessTaskAddr=0x${(perProcessTaskAddr >>> 0).toString(16)}, kernelMem=${kernelI32 ? "present" : "absent"}).` ); } if (sigchldPendingNow()) sigchldArmed = true; if (deliverableSignalPending()) return; const idx = taskWakeIdx(); if (idx >= 0) { const kmem = kernelI32Live(); const seq = Atomics.load(kmem, idx) | 0; Atomics.wait(kmem, idx, seq, RESCHED_YIELD_MS); maybeReassertSigchldOnWake(); return; } const stateIdx = perProcessTaskAddr >>> 0 >>> 2; const kmem2 = kernelI32Live(); const cur = Atomics.load(kmem2, stateIdx) | 0; Atomics.wait(kmem2, stateIdx, cur, RESCHED_YIELD_MS); maybeReassertSigchldOnWake(); } function awaitTaskWakeSlice() { if (perProcessTaskAddr === 0 || kernelI32 === null) return; const idx = taskWakeIdx(); const at = idx >= 0 ? idx : perProcessTaskAddr >>> 0 >>> 2; const kmem = kernelI32Live(); Atomics.wait(kmem, at, Atomics.load(kmem, at) | 0, RESCHED_YIELD_MS); } const imports = { env: { user_memory: init.memory, /* * Issue linux-in-the-browser#52 (F152-MAIN): a dlopen-capable DYNAMIC * MAIN now carries the F152 sig-compatible open-world dispatch consult * too — a .so hands its callback fp to a main-side libc API (qsort/ * bsearch/atexit/signal) and the MAIN's open-world fp dispatch then * holds a .so-side target, which the consult must bless against module * liveness + the .so's F117 registration census (a main-side dispatch * of a live registered .so target is exactly the verdict logic * xmodDispatchCheck already implements — plus the fromMain=true * loader-vouched-append nuance, see the function header). Static * mains never import it (filterImports drops unused names; wasmld's * dynamic-main witness refuses it on a static image). */ __hwjs_xmod_dispatch_check: xmodConsultImport(true, false, true), /* brintium#87: the generation the main's consult sites keep a 1 in. */ [XMOD_CONSULT_GEN_IMPORT]: xmodConsultGenerationGlobal(), /* * F163 — the MAIN's fpcast registry seam. A dynamic MAIN no longer * self-satisfies these with weak no-op stubs (hwjs-cc F163: the stub * swallowed every main-owned F117 record, so a libc.so consult could * never resolve a main-side qsort comparator); they are env imports * now. They must be pre-bound HERE: the generic main-import bind loop * falls through to libc.so's exports, and libc.so exports its OWN * weak stub under the same names — binding there would silently * re-lose the records. Registration + lookups now route through the * PROCESS-SCOPED census (fpcastProcessRecs — the cross-process * table-index-collision fix; registration still forwards to the * kernel registry for diagnostics). filterImports drops these for * images that do not import them (pre-F163 artifacts). */ __hwjs_register_fpcast_adapter: (ver, sig, fid, tgt, mid) => fpcastRegisterScoped(ver, sig, fid, tgt, mid), __hwjs_fpcast_adapter_lookup: (sig, tgt) => fpcastAdapterLookupScoped(sig, tgt), /* * brintium#74 — the MAIN's capsummary seam, pre-bound HERE for the * same reason as the fpcast ops above: a dynamic main imports the * registrar and lookup instead of defining weak stubs, and the generic * bind loop would fall through to libc.so's own weak stub. Its records * and lookups then meet the rest of this process's modules in * capsummaryProcessRecs. filterImports drops these for images that do * not import them (every main built before the fix). */ __hwjs_register_capsummary: CAPSUMMARY_SCOPED_OPS.__hwjs_register_capsummary, __hwjs_register_capsummary_target: CAPSUMMARY_SCOPED_OPS.__hwjs_register_capsummary_target, __hwjs_capsummary_lookup: CAPSUMMARY_SCOPED_OPS.__hwjs_capsummary_lookup, __hwjs_capsummary_lookup_callee: CAPSUMMARY_SCOPED_OPS.__hwjs_capsummary_lookup_callee, __hwjs_fpcast_target_sig_lookup: (tgt) => fpcastTargetSigLookupScoped(tgt) }, linux: { syscall }, /* * HWJS-3: the coro substrate's boundary import (design §2) — the ONE * suspend seed in userland. A host NO-OP by design: the suspension * happens IN WASM (the coroutinize pass parks the calling frame right * after this call returns); the import exists only as the pass's * boundary seed. Harmless on images that do not import it * (filterImports drops namespaces the module does not declare). The kernelWorker host-leg * parked-empty guard is NOT replicated on the userland syscall import: * the userland violation reporter (hwjs_user_rt.c RULE 2) writes its * witness through raw linux.syscall WHILE the slot is — by definition * of what it reports — non-empty, and the syscall import is also the * synchronous hot path for every read/write; the in-module v2.2 * witnesses (set-over-set, orphan-at-clear, owner-validated takes) * carry the never-silent burden here. */ hwjs_suspend: { park: () => { } } }; { const km = init.kernelMemoryWasm ?? init.kernelMemory; if (km) imports.env.kernel_memory = km; } const baseEnvNames = new Set(Object.keys(imports.env)); let curWasmBytes = init.wasmBytes; let execInstalledPath = null; const buildTaskProbe = () => ({ pid: ctrl[C.PID] | 0, tid: init.tid | 0, mode: init.mode === "thread" ? "thread" : "fork", cpuId: init.cpuId | 0, tcb: currentTcb >>> 0, poolResident: !!sched, image: { byteLength: curWasmBytes ? curWasmBytes.length : 0, /* null == the image this task was SPAWNED with. See execInstalledPath. */ path: execInstalledPath }, /* * WHERE THIS IMAGE'S BLOCK-PARKS GO. `libcParksAnySyscall` is the image's * own __hwjs_libc_syscall_park_abi export, not a host knob; with it false * a -517 is spun on IN THIS WORKER and every co-resident stops for the * duration. It is the single most load-bearing per-image fact on the * machine and it had no reader outside this file. */ drive: { hwjsDrive, hwjsFlat, libcParksAnySyscall }, /* * MODULE #0 — the kernel-provided runtime. Non-null means libhwjs-rt WAS * INSTANTIATED into this process at the recorded window. It does NOT mean * any of its functions ran: rt exports are reached by direct wasm calls * and through the shared table, so the host counts none of them. See the * snapshot's hwjs-rt note. */ hwjsRt: hwjsRtPlacement ? { moduleId: hwjsRtPlacement.moduleId | 0, memoryBase: hwjsRtPlacement.memoryBase >>> 0, tableBase: hwjsRtPlacement.tableBase >>> 0, tableSize: hwjsRtPlacement.tableSize >>> 0 } : null, /* Module #1 — the shared libc this process bound, by digest. */ libcSo: libcSoPlacement ? { digest: libcSoPlacement.digest, checkEmitting: !!libcSoPlacement.checkEmitting, laneAddressed: !!libcSoPlacement.laneAddressed } : null, /* Everything this PROCESS dlopen'd, live. Per-process by construction: * the map is in this run()'s closure and is cleared across execve. */ dlopen: { open: [...dlopenModules].map(([cookie, m]) => ({ cookie: cookie >>> 0, moduleId: m.moduleId | 0, path: m.path || "", byteLength: m.bytes ? m.bytes.length : 0, memoryBase: m.memoryBase >>> 0, tableBase: m.tableBase >>> 0 })), deadRanges: dlopenDeadRanges.length, nextCookie: dlopenNextCookie >>> 0, tableLen: sharedTable instanceof WebAssembly.Table ? sharedTable.length >>> 0 : 0 }, /* The in-Worker wasm_syscall tally, keyed by x86_64 syscall number. Only * routings through vmlinuxInstance.exports.wasm_syscall appear. */ wasmSyscallStats: wasmSyscallStatsObject(), coopWaitViolations: coopWaitViolations | 0, syncRestartViolations: syncRestartViolations | 0, /* The kernel-lane driver's running census (brackets/drives/slices/frame * residue/poison label) — not a reconcile, which is end-of-process only. */ lane: hwjsLane ? { ...hwjsLane.census } : null, /* * ISOLATE-WIDE, NOT PER-PROCESS, AND THE DIFFERENCE MATTERS. Both caches * are module scope: they are shared by every resident of this Worker, so * a hit here may have been paid for by a co-resident. */ isolateModuleCaches: isolateModuleCacheCensus() }); { const prov = threadPlacementProviders.get(init); if (prov) prov.probe = buildTaskProbe; } let firstImage = true; imageLoop: for (; ; ) { let runtimeBlockBound = false; let threadBlockRefusal = ""; const bindRuntimeBlock = async (rt, where) => { if (!hasTcbRuntime(rt)) { if (typeof rt.__hwjs_take_parked === "function") { return { ok: false, tcb: 0, errno: 0, why: `${where}: ${NO_TCB_RUNTIME_WHY}` }; } runtimeBlockBound = true; return { ok: true, tcb: 0, errno: 0, why: "" }; } const asThread = (fn2) => threadCtx ? threadCtxCall(threadCtx, threadRec, fn2) : fn2(); tcbLayout = asThread(() => readTcbLayout(rt)); runtimeExports = rt; const plan = threadBlockPlan(init, firstImage); if (plan.kind === "bind") { asThread(() => rt.__hwjs_tcb_bind(plan.tcb >>> 0)); currentTcb = plan.tcb >>> 0; runtimeBlockBound = true; return { ok: true, tcb: currentTcb, errno: 0, why: "" }; } const op = plan.kind === "attach" ? rt.__hwjs_thread_attach : rt.__hwjs_thread_attach_initial; const deadline = Date.now() + 1e4; for (; ; ) { const { errno, addr } = tcbResult(asThread(() => op())); if (errno === 0) { currentTcb = addr; runtimeBlockBound = true; return { ok: true, tcb: addr, errno: 0, why: "" }; } if (!tcbRetryable(errno) || Date.now() > deadline) { return { ok: false, tcb: 0, errno, why: `${where}: ${plan.kind === "attach" ? "thread" : "initial-thread"} block attach returned -${errno} ` + (errno === TCB_EBUSY ? "(the registry lock stayed held for 10 s \u2014 a fork copy or an attach/detach that never finished)" : errno === 517 ? "(the block's SYS_mmap kept coming back as a -517 cooperative-park handback for 10 s \u2014 the kernel never served it)" : errno === 12 ? "(out of MEMORY: the block's SYS_mmap was refused; the runtime wrote the syscall's own answer to stderr)" : errno === 11 ? "(16M thread blocks exist at once \u2014 the 24-bit block-id space)" : "(unexpected)") }; } await new Promise((res) => setTimeout(res, 1)); } }; const vforkBlockToRest = () => { if (!init.vforkChild || !currentTcb) return; const rx = runtimeExports || userExports; const inRt = (fn2) => threadCtx ? threadCtxCall(threadCtx, threadRec, fn2) : fn2(); const userIn = tcbFieldAddr("USER_INSLICE"); if (userIn && uU32()[userIn >> 2] >>> 0 !== 0 && rx && typeof rx.__hwjs_slice_exit === "function") { try { inRt(() => rx.__hwjs_slice_exit()); } catch (_e) { } } const mirror = tcbFieldAddr("STW_INSLICE"); if (mirror) Atomics.store(uI32(), mirror >> 2, 0); if (userIn && uU32()[userIn >> 2] >>> 0 !== 0) return; if (rx && typeof rx.__hwjs_thread_arena_reset === "function") { try { inRt(() => rx.__hwjs_thread_arena_reset()); } catch (e) { try { post({ kind: "user-report", pid: init.pid, message: `vfork child block 0x${(currentTcb >>> 0).toString(16)} arena reset refused (${e instanceof Error ? e.message : String(e)})` }); } catch (_e) { } } } }; const releaseThreadBlock = async (why) => { vforkBlockToRest(); if (!currentTcb || !runtimeExports || typeof runtimeExports.__hwjs_thread_detach !== "function") return true; const deadline = Date.now() + 1e4; for (; ; ) { const { errno } = tcbResult(threadCtx ? threadCtxCall(threadCtx, threadRec, () => runtimeExports.__hwjs_thread_detach()) : runtimeExports.__hwjs_thread_detach()); if (errno === 0) { currentTcb = 0; return true; } if (errno !== TCB_EBUSY || Date.now() > deadline) { try { post({ kind: "dmesg", level: 3, text: `hwjs-tcb: thread tid=${init.tid | 0} block 0x${(currentTcb >>> 0).toString(16)} detach (${why}) returned -${errno}${errno === TCB_EBUSY ? " for 10 s (registry lock held)" : ""} \u2014 the block stays attached (never-silent) ` }); } catch (_e) { } return false; } await new Promise((res) => setTimeout(res, 1)); } }; if (init.mode !== "thread" || !firstImage) moduleFactsDrop(); if (!firstImage) { for (const k of Object.keys(imports.env)) { if (!baseEnvNames.has(k)) delete imports.env[k]; } delete imports["GOT.mem"]; delete imports["GOT.func"]; sharedTable = null; dlopenGotFuncIndex = null; dlopenMainScopeIndex = null; fpcastProcessRecs = new XmodInputMap(); capsummaryProcessRecs = createCapsummaryRegistry(); } let imageFatal = null; let execWipedBytes = 0; let execRtWindow = null; if (!firstImage && init.vforkChild) { let rested = false; try { rested = await releaseThreadBlock("vfork child exec"); } catch (e) { try { post({ kind: "user-report", pid: init.pid, message: `vfork child: block detach at exec failed: ${e instanceof Error ? e.message : String(e)}` }); } catch (_e) { } } Atomics.store(ctrl, C.NR, SYS_EXECVE); Atomics.store(ctrl, C.STATE, REQUEST); post({ kind: "vfork-exec", pid: init.pid, taskAddr: perProcessTaskAddr >>> 0, wasmBytes: curWasmBytes, argv: Array.isArray(execPendingArgv) ? execPendingArgv : [], envp: Array.isArray(execPendingEnvp) ? execPendingEnvp : [], lowFdRoutes: [...kernelRoutedLowFds] }); while (Atomics.load(ctrl, C.STATE) !== RESPONSE) { if (init.reapedBy) break; const w = Atomics.waitAsync(ctrl, C.STATE, REQUEST, 5e3); if (w.async) { try { await w.value; } catch (_e) { } } } const handOff = Atomics.load(ctrl, C.STATE) === RESPONSE ? ctrl[C.RET_LO] | 0 : -11; Atomics.store(ctrl, C.STATE, IDLE); if (handOff === 0) { releaseProcessRunState(rested ? "vfork child exec" : "error"); return; } post({ kind: "user-report", pid: init.pid, message: `vfork child pid ${ctrl[C.PID] | 0}: the exec hand-off was refused (errno ${-handOff}); the task exits 127` }); exitCode = 127; break imageLoop; } if (!firstImage) { const fitErr = ensureUserMemoryFitsImage(curWasmBytes, "exec re-instantiate"); if (fitErr < 0) { imageFatal = `user_memory cannot fit the exec image (errno ${fitErr})`; } else { const dirtyCell = init.userDirtyCell instanceof SharedArrayBuffer ? new Int32Array(init.userDirtyCell, 0, 1) : null; const memBytes = init.memory.buffer.byteLength; const imageMinPages = parseImportedMemoryMinPages(curWasmBytes); const imageFloor = imageMinPages === null ? memBytes : imageMinPages * 65536; const wipeBytes = dirtyCell ? Math.min(memBytes, Math.max(Atomics.load(dirtyCell, 0) >>> 0, imageFloor)) : memBytes; if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `EXEC-WIPE: pid=${init.pid} mode=${init.mode} rt=${init.rtThread ? 1 : 0} wiping ${wipeBytes}B of user_memory (${memBytes}B) for exec re-instantiate of ${curWasmBytes.length}B image` }); } catch (_e) { } } const sigOff = typeof init.signalPendingOffset === "number" ? init.signalPendingOffset >>> 0 : -1; zeroMemoryExcept(init.memory, 0, wipeBytes, sigOff, SIGNAL_REGION_BYTES); execWipedBytes = wipeBytes; if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `EXEC-LOAD-DIAG: imageLoop re-instantiate; compiling ${curWasmBytes.length}B` }); } catch (_e) { } } } } const execRefusalToStderr = (text) => { try { const who = Array.isArray(execPendingArgv) && execPendingArgv.length > 0 ? String(execPendingArgv[0]) : "exec"; const msg = new TextEncoder().encode(`${who}: ${text} `); const at = 65536; const mem = new Uint8Array(init.memory.buffer); if (mem.length < at + msg.length) return; mem.set(msg, at); syscall(1, 2, at, msg.length, 0, 0, 0); } catch (_e) { } }; if (imageFatal) { execRefusalToStderr(imageFatal); post({ kind: "user-report", pid: init.pid, message: `hardwarejs#6: exec-in-place FAILED past the point of no return \u2014 ${imageFatal}; killing pid ${init.pid} with exit 127 (guest reaps; never a silent hang)` }); exitCode = 127; break imageLoop; } const imageStageFatal = async (stage, e, sig = 0) => { const detail = `hardwarejs#6: user image ${firstImage ? "spawn" : "exec"} ${stage} failed (${curWasmBytes.length}B image, user_memory ${Math.floor(init.memory.buffer.byteLength / 65536)} pages): ${e instanceof Error ? e.message : String(e)}`; if (firstImage) { await notifyChildExitOnce(127, 0); post({ kind: "error", pid: init.pid, message: detail }); return "return"; } execRefusalToStderr(detail); post({ kind: "user-report", pid: init.pid, message: `${detail} \u2014 killing pid ${init.pid} with ${sig ? `signal ${sig}` : "exit 127"} (guest reaps; never a silent hang)` }); exitCode = 127; if (sig) { await notifyChildExitOnce(sig, 1); exitCode = 128 + sig; } return "break"; }; try { let module, imgCacheKey, imgCached; try { thrTrace(init, post, `image-compile-begin bytes=${curWasmBytes.length}`); ({ module, key: imgCacheKey, cached: imgCached } = await compileUserModule( curWasmBytes, placedImageKey(init, curWasmBytes) )); noteModuleContentId(module, `img:${imgCacheKey}`); thrTrace(init, post, `image-compile-end cached=${imgCached ? 1 : 0}`); } catch (e) { if (await imageStageFatal("COMPILE", e) === "return") { releaseProcessRunState("error"); return; } break imageLoop; } if (WebAssembly.Module.exports(module).some((x) => x.kind === "function" && x.name === "asyncify_start_unwind")) { if (await imageStageFatal("SUBSTRATE", new Error( "Asyncify-instrumented user image (exports asyncify_start_unwind): the Asyncify substrate is retired and this runtime cannot drive it; relink the program with the current toolchain" )) === "return") { releaseProcessRunState("error"); return; } break imageLoop; } if (!firstImage && D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `EXEC-LOAD-DIAG: re-instantiate compiled; instantiating` }); } catch (_e) { } } if (THREAD_IMAGE_SHARING && init.mode === "thread" && init.rtThread === true && firstImage && typeof init.memoryId === "number" && !wasmJitMemories.has(init.memoryId)) { const imageEpoch = init.threadImageEpoch | 0; const threadImageKey = `${imgCacheKey}@${imageEpoch}`; let ctx = threadCtxForImage(init.memoryId, threadImageKey, init, false); if (ctx && !ctx.ready && !ctx.failed) { await Promise.race([ ctx.readyPromise, new Promise((r) => setTimeout(r, 3e4)) ]); } if (ctx && ctx.ready && !ctx.failed) { threadCtxJoin = true; } else { if (ctx) threadCtxDrop(init.memoryId, ctx); ctx = threadCtxForImage(init.memoryId, threadImageKey, init, true); ctx.imageEpoch = imageEpoch; } threadCtx = ctx; if (ctx.placementRecord && init.dlopenFork) init.dlopenFork = ctx.placementRecord; else if (!ctx.placementRecord && init.dlopenFork) ctx.placementRecord = init.dlopenFork; threadRec = { tid: init.tid | 0, syscall, saved: null, stackTop: init.stackPointerOffset | 0 }; ctx.members.add(threadRec); imports.linux.syscall = ctx.syscallDispatch; try { post({ kind: "dmesg", level: 6, text: `hwjs-thread-image tid=${init.tid | 0} ${threadCtxJoin ? "JOINED" : "FOUNDED"} its process image on cpu=${init.cpuId | 0} (threads sharing it: ${ctx.members.size}; key ${ctx.key})` }); } catch (_e) { } threadCtxEnter(ctx, threadRec); thrTrace(init, post, threadCtxJoin ? "image-joined" : "image-founded"); } { const tableImp = moduleImportsOf(module).find((i) => i.kind === "table"); if (tableImp && threadCtxJoin) { sharedTable = threadCtx.table; dlopenGotFuncIndex = threadCtx.gotFuncIndex; dlopenMainScopeIndex = threadCtx.mainScopeIndex; (imports[tableImp.module] ??= {})[tableImp.name] = sharedTable; if (threadCtx.spGlobal) (imports.env ??= {}).__stack_pointer = threadCtx.spGlobal; if (threadCtx.budgetGlobal) (imports.env ??= {}).__hwjs_budget = threadCtx.budgetGlobal; } else if (tableImp) { const tt = parseImportedTableType(curWasmBytes) || { min: 0, max: void 0 }; sharedTableInitial = tt.min >>> 0; sharedTable = new WebAssembly.Table({ initial: tt.min >>> 0, ...tt.max !== void 0 ? { maximum: tt.max >>> 0 } : { maximum: 1 << 20 }, element: "anyfunc" }); tableLedgerOpen(sharedTable); if (placementCell) setTableAllocator(sharedTable, makeCellTableAllocator(placementCell, PC_TLEN)); dlopenGotFuncIndex = /* @__PURE__ */ new Map(); dlopenMainScopeIndex = /* @__PURE__ */ new Map(); if (replaysModuleGraph(init.mode) && firstImage && init.dlopenFork && Array.isArray(init.dlopenFork.gotFunc)) { for (const [name2, idx] of init.dlopenFork.gotFunc) { dlopenGotFuncIndex.set(String(name2), idx >>> 0); } } (imports[tableImp.module] ??= {})[tableImp.name] = sharedTable; for (const g of moduleImportsOf(module)) { if (g.kind !== "global") continue; if (g.name === "__memory_base") { (imports[g.module] ??= {})[g.name] = new WebAssembly.Global({ value: "i32", mutable: false }, 0); } else if (g.name === "__table_base") { (imports[g.module] ??= {})[g.name] = new WebAssembly.Global({ value: "i32", mutable: false }, 0); } else if (g.name === "__stack_pointer") { (imports[g.module] ??= {})[g.name] = new WebAssembly.Global({ value: "i32", mutable: true }, 0); } } } } hwjsRtInstance = null; hwjsRtPlacement = null; hwjsRtHandle = null; hwjsRtStackPointer = null; hwjsRtChannelGlobal = null; hwjsLaneBudget = threadCtxJoin && threadCtx.budgetGlobal || null; libcSoHandle = null; libcSoPlacement = null; neededPlacements = []; neededSoHandles = []; mainGotFuncNames = null; deferredNeededCtors = []; neededCtorTrampolines = []; userExports = null; wasmJitRelease(); mainCheckEmitting = false; mainManifestDriveAbi = 0; moduleBudgetGlobals = []; let libcNeeded = null; let neededLibs = []; let closurePlan = null; { let neededInfo; try { neededInfo = parseWasmLinuxNeeded(curWasmBytes); } catch (e) { if (await imageStageFatal("NEEDED-PARSE", e) === "return") { releaseProcessRunState("error"); return; } break imageLoop; } if (neededInfo && neededInfo.needed.length > 0) { try { const name2 = neededInfo.needed[0]; const digest = neededDigest(name2); if (!workerSharedLibs.has(digest)) { throw new Error( `hwjs-libc: the image needs /lib/${name2.slice(0, 24)}\u2026 but no shared library of that digest was delivered to this Worker (store has ${workerSharedLibs.size} digest(s)) \u2014 the kernel LIBC_STAGE hand-off did not run or delivered a different generation (never-silent loud exec failure).` ); } libcNeeded = { name: name2, digest, suspendersSha256: neededInfo.suspendersSha256 }; for (let i = 1; i < neededInfo.needed.length; i++) { const n = neededInfo.needed[i]; let d = neededDigest(n); if (!workerSharedLibs.has(d) && neededInfo.bySoname && neededInfo.bySoname[i]) { const rec = replaysModuleGraph(init.mode) && firstImage && init.dlopenFork && Array.isArray(init.dlopenFork.neededLibs) ? init.dlopenFork.neededLibs.find((r) => r && r.name === n) : null; const sub = rec ? rec.digest : neededSubstitutes.get(n); if (sub && workerSharedLibs.has(sub)) { neededViewCheckIn(curWasmBytes, n, sub, neededInfo.views[i], post); d = sub; } } if (!workerSharedLibs.has(d)) { throw new Error( `hwjs-libc: the image needs ${n.slice(0, 32)}\u2026 (needed entry ${i}) but no shared library of that digest was delivered to this Worker (store has ${workerSharedLibs.size} digest(s)) \u2014 the kernel NEEDED_STAGE hand-off did not run for this entry or delivered a different generation (never-silent loud exec failure).` ); } neededLibs.push({ name: n, soname: neededSoname(n), digest: d, index: i }); } if (replaysModuleGraph(init.mode) && firstImage && init.dlopenFork && Array.isArray(init.dlopenFork.neededLibs)) { for (const r of init.dlopenFork.neededLibs) if (r && r.knownPath) dladdrKnownPaths.set(r.digest, r.knownPath); } const staged = replaysModuleGraph(init.mode) && firstImage ? init.dlopenFork && Array.isArray(init.dlopenFork.neededLibs) ? init.dlopenFork.neededLibs.filter((r) => r && (r.preload || r.preloadDep)).map((r) => ({ name: r.name, digest: r.digest, dep: !!r.preloadDep })) : [] : !firstImage && execPreloads ? execPreloads : []; const pre = staged.filter((p) => !p.dep); const preDeps = staged.filter((p) => p.dep); execPreloads = null; if (firstImage && !replaysModuleGraph(init.mode) && ldPreloadEntries(init.envp).length) { try { post({ kind: "dmesg", level: 4, text: `hwjs-preload: pid=${init.pid} LD_PRELOAD is not read for a host-spawned first image; it takes effect at the next execve` }); } catch (_e) { } } for (let k = pre.length - 1; k >= 0; k--) { const { name: n, digest: d } = pre[k]; if (!workerSharedLibs.has(d)) { throw new Error( `hwjs-preload: the image preloads ${neededSoname(n)} (${d.slice(0, 16)}\u2026) but this Worker's store does not hold it (never-silent).` ); } neededLibs.unshift({ name: n, soname: neededSoname(n), digest: d, index: neededInfo.needed.length + k, preload: true }); } for (let k = 0; k < preDeps.length; k++) { const { name: n, digest: d } = preDeps[k]; if (!workerSharedLibs.has(d)) { throw new Error( `hwjs-preload: the image's preloads need ${neededSoname(n)} (${d.slice(0, 16)}\u2026) but this Worker's store does not hold it (never-silent).` ); } neededLibs.push({ name: n, soname: neededSoname(n), digest: d, index: neededInfo.needed.length + pre.length + k, preloadDep: true }); } } catch (e) { if (await imageStageFatal("LIBC-NEEDED", e) === "return") { releaseProcessRunState("error"); return; } break imageLoop; } } } try { const mainManifest = parseHwjsAbi(curWasmBytes); mainCheckEmitting = !!(mainManifest && mainManifest.flags.checkEmitting); mainLaneAddressed = !!(mainManifest && mainManifest.flags.laneAddressed); mainManifestDriveAbi = mainManifest ? mainManifest.driveAbi | 0 : 0; } catch (e) { if (await imageStageFatal("MAIN-MANIFEST", e) === "return") { releaseProcessRunState("error"); return; } break imageLoop; } { const mainImps = moduleImportsOf(module); const wantsRt = mainImps.some((i) => i.module === "env" && i.kind === "function" && i.name === "__hwjs_frame_alloc"); if (libcNeeded && !wantsRt) { throw new Error( "hwjs-libc: the image carries wasm.linux.needed but does not import the hwjs runtime (env.__hwjs_frame_alloc) \u2014 a dynamic-libc main is rt-importing by construction; refusing a foreign shape (never-silent)." ); } if (wantsRt) { if (moduleExportsOf(module).some((e) => e.name === "__hwjs_frame_alloc")) { throw new Error( "hwjs-rt: DOUBLE PROVISION refused \u2014 the main both LINKS its own hwjs runtime (exports __hwjs_frame_alloc) and IMPORTS the kernel-provided one. One runtime provider per process (PLAN-HWJS-RT-PSABI); relink the main." ); } if (libcNeeded) { const mainExpNames = functionExportNamesOf(module); for (const anchor of ["__libc_start_main", "malloc"]) { if (mainExpNames.has(anchor)) { throw new Error( `hwjs-libc: DOUBLE PROVISION refused \u2014 the main names ${libcNeeded.name.slice(0, 24)}\u2026 in wasm.linux.needed but also EXPORTS the libc anchor "${anchor}" (a statically linked libc). One libc provider per process (PLAN-DYNAMIC-LIBC \xA73.4); relink the main.` ); } } } if (!init.hwjsRtModule || !init.hwjsRtBytes) { throw new Error( "hwjs-rt: the main imports the hwjs runtime ops but this kernel ships no libhwjs-rt (no verified hwjs.rt.so section) \u2014 a runtime-importing dynamic main cannot run on a kernel image with no embedded rt (never-silent)." ); } let rtSoBytes = init.hwjsRtBytes; let rtSoModule = init.hwjsRtModule; const rt4Cached = mainManifestDriveAbi === 4 && init.vmlinuxModule ? rt4ByKernel.get(init.vmlinuxModule) : void 0; if (rt4Cached) { rtSoBytes = rt4Cached.bytes; rtSoModule = rt4Cached.module; } else if (mainManifestDriveAbi === 4) { const s4 = init.vmlinuxModule ? WebAssembly.Module.customSections(init.vmlinuxModule, "hwjs.rt4.so") : []; if (s4.length !== 1) { throw new Error( `hwjs-rt: this main is drive_abi=4 (status channel) but the kernel ships ${s4.length}x hwjs.rt4.so section(s) \u2014 an abi-4 dynamic main cannot run against the flat runtime (its leaf parks would silently transit; I3). Rebuild the kernel packaging (scripts/build-hwjs-rt.sh status-channel twin); never-silent.` ); } rtSoBytes = new Uint8Array(s4[0]); rtSoModule = compileSoModule(rtSoBytes).module; const p4 = WebAssembly.Module.customSections( rtSoModule, "hwjs.rt.provenance" ); const p4raw = p4.length === 1 ? new TextDecoder().decode(p4[0]).trim() : null; const want = typeof init.hwjsRtProvenance === "string" ? init.hwjsRtProvenance.trim() : null; if (!p4raw || !want || p4raw !== want) { throw new Error( "hwjs-rt: the status-channel runtime twin's embedded RT-PROVENANCE does not match the boot-verified attestation (mixed/stale kernel packaging) \u2014 refusing the runtime (never-silent)." ); } rt4ByKernel.set(init.vmlinuxModule, { bytes: rtSoBytes, module: rtSoModule }); } if (!sharedTable) { throw new Error( "hwjs-rt: the runtime-importing main does not import the shared table \u2014 not a dynamic main; refusing." ); } const envImp = imports.env ??= {}; if (!(envImp.__stack_pointer instanceof WebAssembly.Global)) { envImp.__stack_pointer = new WebAssembly.Global({ value: "i32", mutable: true }, 0); } if (!(envImp.__hwjs_budget instanceof WebAssembly.Global)) { envImp.__hwjs_budget = new WebAssembly.Global({ value: "i32", mutable: true }, 0); } hwjsLaneBudget = envImp.__hwjs_budget; const kexp = vmlinuxInstance ? vmlinuxInstance.exports : null; const lateGeneric = (n, who) => (...a) => { const f = userExports && userExports[n]; if (typeof f !== "function") { throw new Error( `hwjs-rt: ${who || "rt"} import env.${n} is unresolved \u2014 ` + (userExports ? `the main image is instantiated and exports no function "${n}", which is a link defect in the main image itself` : `the main image is NOT INSTANTIATED YET, so this call came from a load-time constructor of the runtime, libc.so or a needed library, and the main's export table is not the fault`) + ` (never-silent).` ); } return f(...a); }; const late = (n, who) => lateGeneric(n, who); const rtResolveImport = (m, n, kind) => { if (kind === "function" && m === "linux" && n === "syscall") { const f = imports.linux && imports.linux.syscall; if (typeof f !== "function") { throw new Error( "hwjs-rt: rt imports linux.syscall but the process import object carries none (never-silent)." ); } return f; } if (kind !== "function" || m !== "env") return void 0; if (n === "__hwjs_xmod_dispatch_check") { return xmodConsultImport(true, true, false); } if (CAPSUMMARY_SCOPED_OPS[n]) return CAPSUMMARY_SCOPED_OPS[n]; if (DLOPEN_KERNEL_OWNED_OPS.has(n)) { if (FPCAST_SCOPED_OPS[n]) return FPCAST_SCOPED_OPS[n]; const f = kexp ? kexp[n] : void 0; if (typeof f === "function") return f; throw new Error( `hwjs-rt: rt import env.${n} is KERNEL-owned but vmlinux does not export it (never-silent).` ); } if (HWJS_BUDGET_LOUD_OPS.has(n)) { return makeBudgetLoudHandler(n, "the hwjs runtime module (#0)"); } return late(n, "the hwjs runtime module (#0)"); }; const rtReplay = replaysModuleGraph(init.mode) && firstImage && init.dlopenFork && init.dlopenFork.hwjsRt || null; if (rtReplay) { const need = (rtReplay.tableBase >>> 0) + (rtReplay.tableSize >>> 0); if (sharedTable.length < need) { sharedTable.grow(need - sharedTable.length); } } let rtWinBase = 0, rtWinCur = 0, rtWinDataEnd = 0, rtWinEnd = 0; if (!rtReplay) { if (init.mode === "fork-resume" && firstImage) { throw new Error( "hwjs-rt (\xA76.4): fork-resume child of a runtime-importing main carries no dlopenFork.hwjsRt placement \u2014 refusing a fresh carve over the copied address space (never-silent)." ); } if (init.mode === "migrate-resume") { throw new Error( "hwjs-rt (\xA76.4): migrate-resume of a runtime-importing main carries no dlopenFork.hwjsRt placement record \u2014 refusing a fresh carve over the LIVE address space of a task that has not been released yet (never-silent; the source keeps it)." ); } if (init.mode === "thread") { throw new Error( "hwjs-rt (\xA76.4): thread-mode Worker of a runtime-importing main carries no dlopenFork.hwjsRt placement record \u2014 refusing a fresh carve over the process's LIVE shared address space (the thread-spawn placement round-trip did not deliver; never-silent)." ); } rtWinBase = deriveHwjsRtWindowBase(curWasmBytes); if (firstImage) { if (typeof init.hwjsRtWindowBase !== "number") { throw new Error( "hwjs-rt (\xA76.4): the main imports the hwjs runtime but this init carries no hwjsRtWindowBase \u2014 the host spawn handler did not reserve the rt window (host/worker version skew?); refusing (never-silent)." ); } if (init.hwjsRtWindowBase >>> 0 !== rtWinBase || init.hwjsRtWindowSize >>> 0 !== HWJS_RT_WINDOW_SIZE) { throw new Error( `hwjs-rt (\xA76.4): reserved-window DIVERGENCE \u2014 host computed base=0x${(init.hwjsRtWindowBase >>> 0).toString(16)} size=0x${(init.hwjsRtWindowSize >>> 0).toString(16)}, worker derived base=0x${rtWinBase.toString(16)} size=0x${HWJS_RT_WINDOW_SIZE.toString(16)} \u2014 the duplicated constants (BRK_RESERVE / HWJS_RT_WINDOW_SIZE / page size) drifted between kernelSpawnHandler.ts and dynLoader.mjs (never-silent).` ); } } rtWinEnd = rtWinBase + HWJS_RT_WINDOW_SIZE >>> 0; rtWinDataEnd = rtWinEnd - HWJS_RT_STACK_CARVE >>> 0; rtWinCur = rtWinBase; if (init.memory.buffer.byteLength < rtWinEnd) { tryGrowUserMemoryTo(Math.ceil(rtWinEnd / 65536)); } if (rtWinEnd > execWipedBytes) { zeroMemory(init.memory, rtWinBase, HWJS_RT_WINDOW_SIZE); } execRtWindow = { base: rtWinBase, end: rtWinEnd }; } const rtWinAlloc = (sz, align) => { const a = Math.max(align >>> 0 || 1, 16); const base = rtWinCur + (a - 1) & ~(a - 1); const need = sz >>> 0; if (!(base >= rtWinBase) || base + need > rtWinDataEnd) { throw new Error( `hwjs-rt (\xA76.4): rt data region does NOT fit the reserved window \u2014 need ${need}B (align ${a}) at 0x${base.toString(16)}, window [0x${rtWinBase.toString(16)}, 0x${rtWinEnd.toString(16)}) minus the top 65536B rt shadow-stack carve (usable end 0x${rtWinDataEnd.toString(16)}). Raise HWJS_RT_WINDOW_SIZE (src/dynLoader.mjs + src/kernelSpawnHandler.ts, in lockstep) (never-silent fit check).` ); } rtWinCur = base + need; return base >>> 0; }; const rtSpTop = rtReplay ? rtReplay.spTop >>> 0 : rtWinEnd >>> 0; if (!threadCtxJoin) envImp.__stack_pointer.value = rtSpTop | 0; hwjsRtStackPointer = envImp.__stack_pointer; const rtTableBase = rtReplay ? rtReplay.tableBase : sharedTable.length; const rtId = rtReplay ? rtReplay.moduleId | 0 : kexp && typeof kexp.__hwjs_alloc_module_id === "function" ? kexp.__hwjs_alloc_module_id() | 0 : 0; let rtHandle; closurePlan = closurePlanBegin({ imageKey: imgCacheKey, rtKey: `rt${mainManifestDriveAbi}:${rtSoBytes ? rtSoBytes.length : 0}`, libcDigest: libcNeeded ? libcNeeded.digest : null, needed: neededLibs, replay: replaysModuleGraph(init.mode) && firstImage, join: !!threadCtxJoin, envp: execPendingEnvp }); const rtWantsChannel = moduleImportsOf(rtSoModule).some( (i) => i.kind === "global" && i.module === "env" && i.name === "__hwjs_status_channel_addr" ); if (rtWantsChannel) { hwjsRtChannelGlobal = threadCtx ? threadCtx.chanGlobal : new WebAssembly.Global({ value: "i32", mutable: true }, 0); } try { rtHandle = threadCtxJoin ? threadCtx.handles.get("rt") : loadSharedObject({ wasmBytes: rtSoBytes, memory: init.memory, table: sharedTable, moduleId: rtId, soPath: "the hwjs runtime module (#0)", ...hwjsRtChannelGlobal ? { statusChannelGlobal: hwjsRtChannelGlobal } : {}, compileModule: () => rtSoModule, knownModule: rtSoModule, ...linkPlanOpts(), ...closurePlanOpts(closurePlan, "rt"), /* PLAN-THREADS §4 step 2 note: the FLAT rt module's lane * posture is deliberately NOT judged here — it is a * HOST-shipped artifact (extracted from vmlinux) and this * stage has no imageStageFatal bracket (a refusal thrown here * kills the worker and wedges the foreground tty — witnessed * by the lanes-mixing gate's post-red liveness arm). * checkLoadPolicy's unstated-posture default (0) refuses a * lane-STAMPED artifact fail-closed on the flat path. * §4 step 8: the STATUS-CHANNEL twin IS judged — it attests * drive_abi=4 + bit5 + safepoints, so the load states the * main's real abi/lane posture (the selection above already * pinned drive_abi=4). */ ...mainManifestDriveAbi === 4 ? { mainDriveAbi: 4, mainLaneAddressed } : {}, resolveImport: rtResolveImport, resolveDataAddress: () => void 0, gotFuncIndex: dlopenGotFuncIndex, stackPointer: envImp.__stack_pointer, budgetGlobal: hwjsLaneBudget, parkImport: () => { }, /* Main-glue names rt may take the ADDRESS of (GOT.func) — a * table slot needs a real wasm function, which exists only * after the main instantiates; deferred + patched below. * __hwjs_user_park is rt-DEFINED but deferred anyway: its GOT * value is the owner word rt's leaf coroutine PUBLISHES at a * park (set_parked), and the main's F83 balance take compares * it against the main's OWN identity for the imported leaf — * its link-baked elem slot. Resolving at rt-load would mint a * second (rt-side) slot for the same function and every * park through the leaf would die "adoption: take owner * mismatch". Post-main patching unifies on the main's slot * (patchGotFunc -> tableIndexOf finds the resident elem). */ /* 'freea' is deliberately NOT here: rt references it strongly * now, so there is no GOT.func.freea to defer. */ deferGotFunc: /* @__PURE__ */ new Set( [ "hwjs_resume", "hwjs_done", "hwjs_destroy", "__hwjs_drive_abi", "__hwjs_user_park" ] ), ...rtReplay ? { fixedMemoryBase: rtReplay.memoryBase >>> 0, fixedTableBase: rtReplay.tableBase >>> 0, skipDataRelocs: true, /* #43 placement contract applies to module #0 too: re-seed * the parent's NAMED appended slots (GOT.func., e.g. * __hwjs_user_park) AT their recorded indices — otherwise * the child re-appends at the table end, leaving the * parent-recorded slot a NULL hole, drifting tableSize +1 * per fork generation, and breaking every later dlopen * placement (replayForkDlopens' tableBase-inside-elem * refusal). */ seedSymbolIndices: Array.isArray(rtReplay.appended) ? rtReplay.appended : [] } : { allocMemory: rtWinAlloc } }); if (threadCtx && !threadCtxJoin) threadCtx.handles.set("rt", rtHandle); if (!threadCtxJoin) closurePlanNote(closurePlan, "rt", rtHandle); if (threadCtxJoin && !rtHandle) { throw new Error("hwjs-thread-image: the shared image has no runtime module to join (never-silent)"); } if (hwjsRtChannelGlobal && !threadCtxJoin) { const rx = (rtHandle.instance ?? rtHandle).exports; const t0 = typeof rx.__hwjs_tcb_initial === "function" ? rx.__hwjs_tcb_initial() >>> 0 : 0; if (t0 === 0) { throw new Error( "hwjs-rt: the status-channel runtime imports a channel address but exports no initial block (__hwjs_tcb_initial) to point it at \u2014 refusing to run it reading address 0 (never-silent)." ); } hwjsRtChannelGlobal.value = t0 | 0; } armModuleBudget(rtHandle); if (!rtReplay) rtHandle.runCtors(); } catch (e) { if (await imageStageFatal("RUNTIME-LOAD", e) === "return") { releaseProcessRunState("error"); return; } break imageLoop; } hwjsRtInstance = rtHandle.instance ?? rtHandle; hwjsRtHandle = rtHandle; hwjsRtPlacement = threadCtxJoin && threadCtx.rtPlacement ? threadCtx.rtPlacement : { memoryBase: rtHandle.memoryBase >>> 0, tableBase: rtTableBase >>> 0, tableSize: sharedTable.length - rtTableBase >>> 0, moduleId: rtId | 0, spTop: rtSpTop >>> 0, /* #43 for module #0: the NAMED appended slots ([name, index] — * rt's GOT.func. appends, e.g. __hwjs_user_park) so a fork * child seeds them at the recorded indices instead of appending * anew. The deferred GOT.func patches go through the PROCESS-wide * gotFuncIndex cache, which rides the fork payload separately; a * slot a later dlsym appends (the main's GOT.func of a runtime * op) rides the record's `late` list. In the replay * child tableEntries() returns the SEEDED entries, so grandchild * forks inherit the same layout (no drift). */ appended: rtHandle.tableEntries() }; const rtExports = (rtHandle.instance ?? rtHandle).exports; { const bound = await bindRuntimeBlock(rtExports, "pre-main (rt #0)"); if (threadCtx) threadCtxEnter(threadCtx, threadRec); if (!bound.ok) { if (init.mode === "thread") { threadBlockRefusal = bound.why; } else { throw new Error(`hwjs-tcb: ${bound.why} Refusing to drive (never-silent).`); } } else if (hwjsRtChannelGlobal && currentTcb) { hwjsRtChannelGlobal.value = currentTcb | 0; } } if (libcNeeded) { const lib = workerSharedLibs.get(libcNeeded.digest); if (!lib.module) lib.module = compileSoModule(lib.bytes, libcNeeded.digest).module; noteModuleContentId(lib.module, `lib:${libcNeeded.digest}`); let libcManifest; try { libcManifest = parseHwjsAbi(lib.bytes); if (!libcManifest || libcManifest.manifestVersion < 2 || !libcManifest.suspenderDigestLo64) { throw new Error( `hwjs-libc: staged libc.so (digest ${libcNeeded.digest.slice(0, 16)}\u2026) carries no v2 hwjs.abi suspender-partition digest \u2014 an older or foreign artifact cannot back a needed-main (never-silent).` ); } const wantLo64 = libcNeeded.suspendersSha256.slice(0, 16); if (libcManifest.suspenderDigestLo64 !== wantLo64) { throw new Error( `hwjs-libc: SUSPENDER-PARTITION DIGEST SKEW \u2014 the main was linked against partition ${wantLo64}\u2026 but the staged libc.so's hwjs.abi records ${libcManifest.suspenderDigestLo64}\u2026 (a main linked against partition N running against libc.so M; PLAN-DYNAMIC-LIBC \xA73.2). Refusing to instantiate (never-silent).` ); } const libcCheckEmitting = !!(libcManifest.flags && libcManifest.flags.checkEmitting); if (libcCheckEmitting !== mainCheckEmitting) { throw new Error( `hwjs-libc: CHECK-EMITTING MISMATCH \u2014 the main attests check_emitting=${mainCheckEmitting ? 1 : 0} but the staged libc.so (digest ${libcNeeded.digest.slice(0, 16)}\u2026) attests check_emitting=${libcCheckEmitting ? 1 : 0} (hwjs.abi flags bit4). Mixing check-emitting and non-check-emitting modules lets a status-channel raise transit an uninstrumented frame SILENTLY (PLAN-CXX-STATUS-CHANNEL \xA77, I3). Relink the pair in lockstep (never-silent).` ); } const libcLaneAddressed = !!(libcManifest.flags && libcManifest.flags.laneAddressed); if (libcLaneAddressed !== mainLaneAddressed) { throw new Error( `hwjs-libc: LANE-ADDRESSED MISMATCH \u2014 the main attests lane_addressed=${mainLaneAddressed ? 1 : 0} but the staged libc.so (digest ${libcNeeded.digest.slice(0, 16)}\u2026) attests lane_addressed=${libcLaneAddressed ? 1 : 0} (hwjs.abi flags bit5). Mixing a lane-addressed module with a lane-unaware one lets the lane-unaware side read the INITIAL thread's status word from ANY thread \u2014 silent transit under threads (I3-2; PLAN-THREADS-SINGLE-MEMORY \xA74 step 2). Relink the pair in lockstep (never-silent).` ); } } catch (e) { if (await imageStageFatal("LIBC-STAGE", e) === "return") { releaseProcessRunState("error"); return; } break imageLoop; } const libcReplay = replaysModuleGraph(init.mode) && firstImage && init.dlopenFork && init.dlopenFork.libcSo || null; if (libcReplay) checkLibcReplayRecord(libcReplay, libcNeeded.digest); let libcWinBase = 0, libcWinCur = 0, libcWinEnd = 0; if (!libcReplay) { if (init.mode === "fork-resume" && firstImage) { throw new Error( "hwjs-libc: fork-resume child of a libc.so-needing main carries no dlopenFork.libcSo placement \u2014 refusing a fresh carve over the copied address space (the delta copy holds live libc.so data; never-silent)." ); } if (init.mode === "migrate-resume") { throw new Error( "hwjs-libc: migrate-resume of a libc.so-needing main carries no dlopenFork.libcSo placement record \u2014 refusing a fresh carve over the LIVE address space of a task that has not been released yet (never-silent)." ); } if (init.mode === "thread") { throw new Error( "hwjs-libc: thread-mode Worker of a libc.so-needing main carries no dlopenFork.libcSo placement record \u2014 refusing a fresh carve over the process's LIVE shared address space (never-silent)." ); } libcWinBase = deriveHwjsLibcWindowBase(curWasmBytes); if (firstImage) { if (typeof init.hwjsLibcWindowBase !== "number") { throw new Error( "hwjs-libc: the main needs libc.so but this init carries no hwjsLibcWindowBase \u2014 the host spawn handler did not reserve the libc window (host/worker version skew?); refusing (never-silent)." ); } if (init.hwjsLibcWindowBase >>> 0 !== libcWinBase || init.hwjsLibcWindowSize >>> 0 !== HWJS_LIBC_WINDOW_SIZE) { throw new Error( `hwjs-libc: reserved-window DIVERGENCE \u2014 host computed base=0x${(init.hwjsLibcWindowBase >>> 0).toString(16)} size=0x${(init.hwjsLibcWindowSize >>> 0).toString(16)}, worker derived base=0x${libcWinBase.toString(16)} size=0x${HWJS_LIBC_WINDOW_SIZE.toString(16)} \u2014 the duplicated constants drifted between kernelSpawnHandler.ts and dynLoader.mjs (never-silent).` ); } } libcWinEnd = libcWinBase + HWJS_LIBC_WINDOW_SIZE >>> 0; libcWinCur = libcWinBase; if (init.memory.buffer.byteLength < libcWinEnd) { tryGrowUserMemoryTo(Math.ceil(libcWinEnd / 65536)); } const libcWinWritten = execRtWindow !== null && execRtWindow.base < libcWinEnd && libcWinBase < execRtWindow.end; if (libcWinEnd > execWipedBytes || libcWinWritten) { zeroMemory(init.memory, libcWinBase, HWJS_LIBC_WINDOW_SIZE); } } else { const need = (libcReplay.tableBase >>> 0) + (libcReplay.tableSize >>> 0); if (sharedTable.length < need) { sharedTable.grow(need - sharedTable.length); } } const libcWinAlloc = (sz, align) => { const a = Math.max(align >>> 0 || 1, 16); const base = libcWinCur + (a - 1) & ~(a - 1); const need = sz >>> 0; if (!(base >= libcWinBase) || base + need > libcWinEnd) { throw new Error( `hwjs-libc: libc.so data region does NOT fit the reserved window \u2014 need ${need}B (align ${a}) at 0x${base.toString(16)}, window [0x${libcWinBase.toString(16)}, 0x${libcWinEnd.toString(16)}). Raise HWJS_LIBC_WINDOW_SIZE (src/dynLoader.mjs + src/kernelSpawnHandler.ts, in lockstep) (never-silent fit check).` ); } libcWinCur = base + need; return base >>> 0; }; const libcSelfExportNames = functionExportNamesOf(lib.module); const libcMarshal = xmodMarshalArmed(lib.module); const mainExportNames = functionExportNamesOf(module); let libcWeak = null; const libcPreemptibleProvider = (n) => { const tier = mainExportNames.has(n) ? "main" : libcSelfExportNames.has(n) ? "self" : null; if (!tier) { libcWeak ??= (parseDylink0(lib.bytes) || {}).weakImports || /* @__PURE__ */ new Map(); if (libcWeak.get(n) === "env") return void 0; throw new Error( `hwjs-libc: unresolved import env.${n} (function) in libc.so (module #1) \u2014 the runtime (module #0) does not export it, the main image does not export it, and libc.so does not define it either, so NOTHING in this process can ever provide it. Refusing the load (never-silent): the alternative is a binding that throws at whatever guest call site reaches it first, which is where this class used to surface.` ); } let bound = null; const provider = () => { const src = tier === "main" ? userExports || null : libcSoHandle ? (libcSoHandle.instance ?? libcSoHandle).exports : null; const f = src ? src[n] : void 0; if (typeof f !== "function") { throw new Error( `hwjs-libc: libc.so's preemptible import env.${n} was resolved at load to the ${tier === "main" ? "MAIN image" : "libc.so self-definition"} (ELF search order), but that provider has no function export "${n}" now that it exists \u2014 the load-time census and the live instance disagree (never-silent).` ); } return f; }; return function(a, b, c, d, e, g, h) { const f = bound || (bound = provider()); switch (arguments.length) { case 0: return f(); case 1: return f(a); case 2: return f(a, b); case 3: return f(a, b, c); case 4: return f(a, b, c, d); case 5: return f(a, b, c, d, e); case 6: return f(a, b, c, d, e, g); case 7: return f(a, b, c, d, e, g, h); default: return f.apply(null, arguments); } }; }; const libcResolveImport = (m, n, kind) => { if (kind === "function" && m === "linux" && n === "syscall") { const f = imports.linux && imports.linux.syscall; if (typeof f !== "function") { throw new Error( "hwjs-libc: libc.so imports linux.syscall but the process import object carries none (never-silent)." ); } return f; } if (kind !== "function" || m !== "env") return void 0; if (CAPSUMMARY_SCOPED_OPS[n]) return CAPSUMMARY_SCOPED_OPS[n]; if (DLOPEN_KERNEL_OWNED_OPS.has(n)) { if (FPCAST_SCOPED_OPS[n]) return FPCAST_SCOPED_OPS[n]; const f = kexp ? kexp[n] : void 0; if (typeof f === "function") return f; throw new Error( `hwjs-libc: libc.so import env.${n} is KERNEL-owned but vmlinux does not export it (never-silent).` ); } if (n === "__hwjs_xmod_dispatch_check") { return xmodConsultImport(true, false, libcMarshal); } if (HWJS_BUDGET_LOUD_OPS.has(n)) { return makeBudgetLoudHandler(n, "libc.so (module #1)"); } if (n === TERMINUS_HOOK && mainExportNames.has(n) && typeof rtExports[n] === "function") { return terminusHook(rtExports[n]); } if (typeof rtExports[n] === "function") return driveImport(n, rtExports[n]); return libcPreemptibleProvider(n); }; const libcTableBase = libcReplay ? libcReplay.tableBase >>> 0 : sharedTable.length; const libcId = libcReplay ? libcReplay.moduleId | 0 : kexp && typeof kexp.__hwjs_alloc_module_id === "function" ? kexp.__hwjs_alloc_module_id() | 0 : 0; let libcHandle; { libcHandle = threadCtxJoin ? threadCtx.handles.get("libc") : loadSharedObject({ wasmBytes: lib.bytes, memory: init.memory, table: sharedTable, moduleId: libcId, soPath: "libc.so (module #1)", compileModule: () => lib.module, knownModule: lib.module, ...linkPlanOpts(), ...closurePlanOpts(closurePlan, "libc"), /* PLAN-THREADS §4 step 2: process lane posture (the LIBC-STAGE * bit5 lockstep above already required agreement with the * main; checkLoadPolicy re-judges at this vantage — the * digest-lockstep two-vantage pattern). */ mainLaneAddressed, /* §4 step 8: drive abi and channel address — see * preMainLoadOpts. */ ...preMainLoadOpts(), resolveImport: libcResolveImport, /* libc.so loads BEFORE the main exists, so there is no main * data-export surface yet — but module #0 (rt) is live, and a * check-emitting libc.so legitimately references RT-owned * DATA (GOT.mem.__hwjs_status_channel — every module in a * process addresses the SAME channel block, STATUS-CHANNEL- * CONTRACT §1; witnessed live: the check-emitting * libc-glibc.so refused to load here, 2026-07-21). Resolve * rt data exports REBASED by the module-#0 placement (the * same memoryBase+offset convention as the merged provider * view); everything else stays undefined -> the loader's * loud attributed throw. */ resolveDataAddress: (name2) => { const g = rtExports ? rtExports[name2] : void 0; if (g instanceof WebAssembly.Global && hwjsRtPlacement) { return ((hwjsRtPlacement.memoryBase >>> 0) + (g.value | 0) | 0) >>> 0; } return void 0; }, /* ELF search order for the data libc.so reads through its GOT: * the main's definition, then libc.so's own. A program defines * argp_program_version_hook for libc's argp to read; the main * is not instantiated yet, so the addresses come from its * bytes. The same rule holds on the fork/thread replay. */ interposeDataAddress: /* @__PURE__ */ (() => { let mainData = null; return (name2) => { if (!mainData) mainData = mainDataExportAddresses(curWasmBytes); return interposingDataAddress(name2, mainData); }; })(), gotFuncIndex: dlopenGotFuncIndex, stackPointer: envImp.__stack_pointer, budgetGlobal: hwjsLaneBudget, parkImport: () => { }, /* G2: libc.so (module #1) is the sanctioned single owner of the * __tls_base segment — the ONLY .so the load policy admits with * uses_tls=1 (glibc's REAL TLS; musl's is 0 and needs no flag). */ tlsOwner: true, /* Main-provided names libc.so may take the ADDRESS of — * deferred + patched post-main (the rt set plus the S2 * late-bound TLS surface). Names not in libc.so's GOT are * simply never recorded (defer is per-present-import). */ deferGotFunc: /* @__PURE__ */ new Set( [ "freea", "hwjs_resume", "hwjs_done", "hwjs_destroy", "__hwjs_drive_abi", "__hwjs_user_park", "__wasm32_set_tls_base", "__wasm_init_tls", "__wasm32_get_tls_size", "__wasm32_get_tls_align", /* wasm32 __unmapself port (threads step 6): the detached- * thread self-exit address-checks the weak crt sp setter — * main-exported; defer + patch post-main like the TLS set. */ "__wasm32_set_stack_pointer", /* The §4 terminus hook: an abi-3 exit sink passes its address * to the noreturn pump, and the slot must hold the main's * strong definition, not the closure libcResolveImport binds * for the call. */ TERMINUS_HOOK ] ), ...libcReplay ? { fixedMemoryBase: libcReplay.memoryBase >>> 0, fixedTableBase: libcReplay.tableBase >>> 0, skipDataRelocs: true, seedSymbolIndices: Array.isArray(libcReplay.appended) ? libcReplay.appended : [] } : { allocMemory: libcWinAlloc } }); armModuleBudget(libcHandle); if (!libcReplay) { if (libcManifest && libcManifest.flags && libcManifest.flags.usesTls) { libcCtorsDeferred = true; } else { libcHandle.runCtors(); } } } if (threadCtx && !threadCtxJoin) threadCtx.handles.set("libc", libcHandle); if (!threadCtxJoin) closurePlanNote(closurePlan, "libc", libcHandle); if (threadCtxJoin && !libcHandle) { throw new Error("hwjs-thread-image: the shared image has no libc.so module to join (never-silent)"); } libcSoHandle = libcHandle; libcSoPath = `/lib/${libcNeeded.name}`; libcSoPlacement = threadCtxJoin && threadCtx.libcPlacement ? threadCtx.libcPlacement : { digest: libcNeeded.digest, /* The staged libc.so's own hwjs.abi suspender-partition digest * (lo64 hex) — the dlopen path's §3.2 skew-refusal reference * (a third .so linked against partition N dlopen'd into a * process running libc.so M refuses on this). */ suspenderDigestLo64: libcManifest.suspenderDigestLo64, /* Track M: the process's check_emitting posture (== the main's, * by the lockstep refusal above) — the dlopen-time mixing * refusal's reference in libc.so processes. */ checkEmitting: !!(libcManifest.flags && libcManifest.flags.checkEmitting), /* PLAN-THREADS §4 step 2: the process lane posture the dlopen * mixing refusal consults in shared-libc processes (already * lockstepped with the main at the LIBC-STAGE check above). */ laneAddressed: !!(libcManifest.flags && libcManifest.flags.laneAddressed), memoryBase: libcHandle.memoryBase >>> 0, tableBase: libcTableBase >>> 0, tableSize: sharedTable.length - libcTableBase >>> 0, moduleId: libcId | 0, appended: libcHandle.tableEntries() }; try { post({ kind: "dmesg", level: 6, text: `hwjs-libc: module #1 instantiated (libc.so.${libcNeeded.digest.slice(0, 16)}\u2026 moduleId=${libcId} memoryBase=0x${libcSoPlacement.memoryBase.toString(16)} tableBase=${libcTableBase}${libcReplay ? " fork-replay" : ""}) \u2014 libc provider is the shared module` }); } catch (_e) { } if (libcHandle.interposedData && libcHandle.interposedData.length) { try { post({ kind: "dmesg", level: 6, text: `hwjs-libc: libc.so reads the main's ${libcHandle.interposedData.join(", ")}` }); } catch (_e) { } } } const libcExports = libcSoHandle ? (libcSoHandle.instance ?? libcSoHandle).exports : null; const neededHandles = []; let stagingWant = null; let stagingPhase = ""; if (neededLibs.length) { try { const neededCtorsInStart = moduleExportsOf(module).some((e) => e.kind === "function" && e.name === "__wasm32_needed_ctors_in_start"); const neededMainExportNames = functionExportNamesOf(module); const neededSelfExportNames = /* @__PURE__ */ new Map(); for (const want of neededLibs) { const lib = workerSharedLibs.get(want.digest); if (!lib.module) lib.module = compileSoModule(lib.bytes, want.digest).module; neededSelfExportNames.set( want.index, functionExportNamesOf(lib.module) ); } const ctorOrder = neededConstructionOrder(neededLibs, (w) => { const lib = workerSharedLibs.get(w.digest); return parseSideModuleNeeded(lib.bytes instanceof Uint8Array ? lib.bytes : new Uint8Array(lib.bytes)); }); const ctorPos = new Map(ctorOrder.map((ix, i) => [ix, i])); const ctorPlaced = /* @__PURE__ */ new Set(); let ctorNext = 0; const runReadyNeededCtors = () => { while (ctorNext < ctorOrder.length && ctorPlaced.has(ctorOrder[ctorNext])) { const ix = ctorOrder[ctorNext++]; stagingWant = neededByIndex.get(ix); stagingPhase = "runCtors"; handleBox.get(ix).runCtors(); } }; const { fn: neededSiblingFn, data: neededSiblingData } = ( /* name -> want.index */ neededSiblingTiers(neededLibs, (w) => workerSharedLibs.get(w.digest).module) ); const neededByIndex = new Map(neededLibs.map((w) => [w.index, w])); const neededPos = new Map(neededLibs.map((w, i) => [w.index, i])); const soEarlier = (map, want, n) => neededEarlierProvider(n, map.get(n), want.index, neededPos); const handleBox = /* @__PURE__ */ new Map(); const soMmapWindow = (label, sz) => { const a = syscall( 9, 0, sz | 0, 3, 34, -1, 0 ) | 0; if (a <= 0) { throw new Error( `hwjs-libc: SYS_mmap for ${label}'s data region (${sz}B) returned ${a} \u2014 the needed library cannot be placed (never-silent OOM).` ); } return a >>> 0; }; const preallocBase = /* @__PURE__ */ new Map(); const soPreallocBase = (j) => { if (preallocBase.has(j)) return preallocBase.get(j); const w = neededByIndex.get(j); const lib = w ? workerSharedLibs.get(w.digest) : null; if (!lib) return 0; const dyl = parseDylink0(lib.bytes); const size = dyl ? dyl.memorySize | 0 : 0; const align = dyl ? dyl.memoryAlign | 0 : 1; const a = align > 0 ? align : 1; const base = size > 0 ? soMmapWindow(w.soname, (size + a - 1 & ~(a - 1)) >>> 0) : 0; preallocBase.set(j, base); try { post({ kind: "dmesg", level: 6, text: `hwjs-libc: pre-placed needed entry ${j} (${w.soname}) at memoryBase=0x${base.toString(16)} \u2014 a sibling's GOT.mem names its data and a data address cannot be bound late` }); } catch (_e) { } return base; }; const reservedFnSlots = /* @__PURE__ */ new Map(); const reservedFnByFunc = /* @__PURE__ */ new Map(); const exportFnIndexCache = /* @__PURE__ */ new Map(); const soExportFnIndex = (j, n) => { let m = exportFnIndexCache.get(j); if (!m) { const w = neededByIndex.get(j); const lib = w ? workerSharedLibs.get(w.digest) : null; m = lib ? lib.module ? exportedFunctionIndicesOf(lib.module, lib.bytes) : parseExportedFunctionIndices(lib.bytes) : /* @__PURE__ */ new Map(); exportFnIndexCache.set(j, m); } return m.get(n); }; const soSiblingFnSlot = (want, j, n) => { const placed = handleBox.get(j); if (placed) { const idx2 = placed.dlsymFunction(n) >>> 0; if (!(idx2 > 0)) { throw new Error( `hwjs-dlopen: ${want.soname} (needed entry ${want.index}) takes the address of "${n}", which needed entry ${j} exports, but it has no table slot for it (never-silent).` ); } return idx2; } let slots = reservedFnSlots.get(j); if (!slots) reservedFnSlots.set(j, slots = /* @__PURE__ */ new Map()); if (slots.has(n)) return slots.get(n); let byFunc = reservedFnByFunc.get(j); if (!byFunc) reservedFnByFunc.set(j, byFunc = /* @__PURE__ */ new Map()); const fi = soExportFnIndex(j, n); if (fi !== void 0 && byFunc.has(fi)) { const alias = byFunc.get(fi); slots.set(n, alias); return alias; } const idx = sharedTable.length; sharedTable.grow(1); slots.set(n, idx); if (fi !== void 0) byFunc.set(fi, idx); try { post({ kind: "dmesg", level: 6, text: `hwjs-libc: reserved table slot ${idx} for "${n}" of needed entry ${j} \u2014 ${want.soname} (needed entry ${want.index}) takes its address before it is placed` }); } catch (_e) { } return idx; }; const soLateBind = (want, n, tier) => { let bound = null; const provider = () => { const from = typeof tier === "number" ? tier : want.index; if (typeof tier === "number" && !handleBox.has(from)) { throw new Error( `hwjs-dlopen: ${want.soname} (needed entry ${want.index}) called env.${n} from a CONSTRUCTOR, but its provider (needed entry ${from}) is not instantiated yet -- a sibling binding is late by construction and cannot be completed before the entry that owns it is placed. Refusing rather than binding a hole (never-silent).` ); } const src = tier === "main" ? userExports || null : (() => { const h = handleBox.get(from); return h ? (h.instance ?? h).exports : null; })(); const f = src ? src[n] : void 0; if (typeof f !== "function") { throw new Error( `hwjs-dlopen: ${want.soname} (needed entry ${want.index}) imported env.${n}, resolved at load to ${tier === "main" ? "the MAIN image" : typeof tier === "number" ? `needed entry ${tier}` : "the library's own definition"} (ELF search order), but that provider exports no function "${n}" now that it is called (never-silent).` ); } return f; }; return function(a, b, c, d, e, g, h) { const f = bound || (bound = provider()); switch (arguments.length) { case 0: return f(); case 1: return f(a); case 2: return f(a, b); case 3: return f(a, b, c); case 4: return f(a, b, c, d); case 5: return f(a, b, c, d, e); case 6: return f(a, b, c, d, e, g); case 7: return f(a, b, c, d, e, g, h); default: return f.apply(null, arguments); } }; }; const soTierFor = (want, n) => { if (neededMainExportNames.has(n)) return "main"; const early = soEarlier(neededSiblingFn, want, n); if (early !== void 0) return early; const self2 = neededSelfExportNames.get(want.index); if (self2 && self2.has(n)) return "self"; const sib = neededSiblingFn.get(n); if (sib !== void 0 && sib !== want.index) return sib; return null; }; const soWeakByIndex = /* @__PURE__ */ new Map(); const soPreemptibleProvider = (want, n) => { const tier = soTierFor(want, n); if (!tier) { let weak = soWeakByIndex.get(want.index); if (!weak) { const lib = workerSharedLibs.get(want.digest); weak = lib && (parseDylink0(lib.bytes) || {}).weakImports || /* @__PURE__ */ new Map(); soWeakByIndex.set(want.index, weak); } if (weak.get(n) === "env") return void 0; throw new Error( `hwjs-dlopen: unresolved import env.${n} (function) in "${want.soname} (needed entry ${want.index})" -- the runtime (module #0) does not export it, libc.so (module #1) does not export it, the main image does not export it, ${want.soname} does not define it either, and no OTHER needed entry of this main exports it, so NOTHING in this process can ever provide it. Refusing the load (never-silent): the alternative is a binding that throws at whatever guest call site reaches it first, which is where this class used to surface.` ); } return soLateBind(want, n, tier); }; for (const want of neededLibs) { stagingWant = want; stagingPhase = "instantiate"; const lib = workerSharedLibs.get(want.digest); if (!lib.module) lib.module = compileSoModule(lib.bytes, want.digest).module; noteModuleContentId(lib.module, `lib:${want.digest}`); const replay = replaysModuleGraph(init.mode) && firstImage && init.dlopenFork && Array.isArray(init.dlopenFork.neededLibs) ? init.dlopenFork.neededLibs.find((r) => r.name === want.name) : null; if (!replay && replaysModuleGraph(init.mode) && firstImage && init.dlopenFork) { throw new Error( `hwjs-libc: fork-resume child of a main needing ${want.name.slice(0, 32)}\u2026 carries no dlopenFork placement for it \u2014 refusing a fresh carve over the copied address space (the delta copy holds this library's live data; never-silent).` ); } if (replay && replay.digest !== want.digest) { throw new Error( `hwjs-libc: GENERATION SKEW \u2014 the parent's placement for ${want.soname} records digest ${String(replay.digest).slice(0, 16)}\u2026 but this image needs ${want.digest.slice(0, 16)}\u2026 (never-silent).` ); } if (replay) { const need = (replay.tableBase >>> 0) + (replay.tableSize >>> 0); if (sharedTable.length < need) { sharedTable.grow(need - sharedTable.length); } } const soAllocMemory = (sz, _align) => soMmapWindow(want.soname, sz); const soMarshal = xmodMarshalArmed(lib.module); let soGotFuncNames = null; const soDlsymCaller = Object.freeze({ kind: "needed", index: want.index }); const soResolveImport = (m, n, kind) => { if (kind === "function" && m === "linux" && n === "syscall") { const f = imports.linux && imports.linux.syscall; if (typeof f !== "function") { throw new Error( `hwjs-libc: ${want.soname} imports linux.syscall but the process import object carries none (never-silent).` ); } return f; } if (kind !== "function" || m !== "env") return void 0; if (CAPSUMMARY_SCOPED_OPS[n]) return CAPSUMMARY_SCOPED_OPS[n]; if (DLOPEN_KERNEL_OWNED_OPS.has(n)) { if (FPCAST_SCOPED_OPS[n]) return FPCAST_SCOPED_OPS[n]; const f = kexp ? kexp[n] : void 0; if (typeof f === "function") return f; throw new Error( `hwjs-libc: ${want.soname} import env.${n} is KERNEL-owned but vmlinux does not export it (never-silent).` ); } if (n === "__hwjs_xmod_dispatch_check") { return xmodConsultImport(false, false, soMarshal); } if (HWJS_BUDGET_LOUD_OPS.has(n)) { return makeBudgetLoudHandler( n, `${want.soname} (needed entry ${want.index})` ); } if (n === TERMINUS_HOOK && neededMainExportNames.has(n) && typeof rtExports[n] === "function") { return terminusHook(rtExports[n]); } if (typeof rtExports[n] === "function") return driveImport(n, rtExports[n]); if (!want.preload && mainNeededBeforeLibc( n, rtExports, soGotFuncNames || (soGotFuncNames = new Set( WebAssembly.Module.imports(lib.module).filter((x) => x.module === "GOT.func").map((x) => x.name) )) )) { const preN = preloadProvider(n, neededHandles.filter((h) => h.preload)); if (preN) return preN.exports[n]; } if (libcExports && typeof libcExports[n] === "function") { return dlsymCallerImport( n, libcExports[n], libcExports, soDlsymCaller, dlsymCallerBox ); } if (n === "fork") return void 0; return soPreemptibleProvider(want, n); }; const soDeferGot = /* @__PURE__ */ new Set(); const soPresetGot = /* @__PURE__ */ new Map(); const soGotProvider = /* @__PURE__ */ new Map(); const soInterposed = []; let soImportedFns = null; const soSelfSet = neededSelfExportNames.get(want.index); for (const imp of moduleImportsOf(lib.module)) { if (imp.module !== "GOT.func") continue; const gn = imp.name; if (soSelfSet && soSelfSet.has(gn) && soEarlier(neededSiblingFn, want, gn) === void 0) continue; if (!soImportedFns) { soImportedFns = importedFunctionNamesOf(lib.module, lib.bytes); } const b = soImportedFns.get(gn); const fmod = b ? b.module : "env"; const fld = b ? b.field : gn; if (fmod === "linux" && fld === "syscall" || fmod === "env" && (fld === "__hwjs_xmod_dispatch_check" || FPCAST_SCOPED_OPS[fld] || CAPSUMMARY_SCOPED_OPS[fld] || HWJS_BUDGET_LOUD_OPS.has(fld))) { throw new Error( `hwjs-dlopen: ${want.soname} (needed entry ${want.index}) takes the address of "${gn}", which resolves to ${fmod}.${fld} -- a host binding, not a wasm export, so it can occupy no table slot. Refusing the load (never-silent).` ); } if (fmod !== "env") continue; if (DLOPEN_KERNEL_OWNED_OPS.has(fld)) continue; if (HWJS_BUDGET_LOUD_OPS.has(fld)) continue; const mainOwned = fld === TERMINUS_HOOK && neededMainExportNames.has(fld); if (!mainOwned) { if (typeof rtExports[fld] === "function") continue; if (libcExports && typeof libcExports[fld] === "function") continue; } if (fld === "fork") continue; const tier = soTierFor(want, fld); if (tier === null) continue; if (fld !== gn) { throw new Error( `hwjs-dlopen: ${want.soname} (needed entry ${want.index}) takes the address of "${gn}", which resolves through env.${fld} -- a name provided only by the main, ${want.soname} itself, or a sibling needed entry, so the slot would need a late binding the post-main patch cannot complete under an aliased name. Refusing the load (never-silent).` ); } if (typeof tier === "number" && !replay) { soPresetGot.set(gn, soSiblingFnSlot(want, tier, gn)); if (soSelfSet && soSelfSet.has(gn)) soInterposed.push(soPresetGot.get(gn)); continue; } if (typeof tier === "number") soGotProvider.set(gn, tier); soDeferGot.add(gn); } const soTableBase = replay ? replay.tableBase >>> 0 : sharedTable.length; const soId = replay ? replay.moduleId | 0 : kexp && typeof kexp.__hwjs_alloc_module_id === "function" ? kexp.__hwjs_alloc_module_id() | 0 : 0; for (const slot of soInterposed) capsummaryProcessRecs.interpose(soId, slot); let soHandle; { soHandle = threadCtxJoin ? threadCtx.handles.get(`needed:${want.index}`) : loadSharedObject({ ...preMainLoadOpts(), wasmBytes: lib.bytes, memory: init.memory, table: sharedTable, moduleId: soId, soPath: `${want.soname} (needed entry ${want.index})`, compileModule: () => lib.module, knownModule: lib.module, ...linkPlanOpts(), ...closurePlanOpts(closurePlan, `needed:${want.digest}`), mainLaneAddressed: libcSoPlacement ? !!libcSoPlacement.laneAddressed : mainLaneAddressed, resolveImport: soResolveImport, /* Data addresses resolve from the two modules already * placed — rt and libc.so — rebased by their placements, * the same merged-provider convention libc.so gets. */ preemptsData: (n) => soEarlier(neededSiblingData, want, n) !== void 0, resolveDataAddress: (n) => { const lg = libcExports ? libcExports[n] : void 0; if (lg instanceof WebAssembly.Global && libcSoPlacement) { return ((libcSoPlacement.memoryBase >>> 0) + (lg.value | 0) | 0) >>> 0; } const rg = rtExports ? rtExports[n] : void 0; if (rg instanceof WebAssembly.Global && hwjsRtPlacement) { return ((hwjsRtPlacement.memoryBase >>> 0) + (rg.value | 0) | 0) >>> 0; } const j = neededSiblingData.get(n); if (j === void 0 || j === want.index) return void 0; const placed = handleBox.get(j); if (placed) { const g = ((placed.instance ?? placed).exports || {})[n]; if (g instanceof WebAssembly.Global) { return ((placed.memoryBase >>> 0) + (g.value | 0) | 0) >>> 0; } return void 0; } const jw = neededByIndex.get(j); if (!jw) return void 0; const jlib = workerSharedLibs.get(jw.digest); if (!jlib) return void 0; const onReplay = replaysModuleGraph(init.mode) && firstImage && init.dlopenFork && Array.isArray(init.dlopenFork.neededLibs); const jreplay = onReplay ? init.dlopenFork.neededLibs.find( (r) => r.name === jw.name ) : null; if (onReplay && !jreplay) { throw new Error( `hwjs-libc: ${want.soname} (needed entry ${want.index}) GOT.mem.${n} is owned by sibling needed entry ${j} (${jw.soname}), but this fork-resume child has no placement record for it \u2014 refusing to re-place it at a fresh base the parent's relocated data does not point at (never-silent).` ); } const jbase = jreplay ? jreplay.memoryBase >>> 0 : soPreallocBase(j); if (!(jbase > 0)) return void 0; const off = readExportedI32Global( jlib.bytes, n, `${jw.soname} (needed entry ${j})` ); return ((jbase >>> 0) + (off | 0) | 0) >>> 0; }, gotFuncIndex: dlopenGotFuncIndex, stackPointer: envImp.__stack_pointer, budgetGlobal: hwjsLaneBudget, parkImport: () => { }, /* A uses_tls=1 needed entry owns a private TLS block the * same way a dlopen'd module does (hardwarejs#52); the * loader ignores this for a module that owns none. */ sideTls: replay ? sideTlsReplayMode(init.mode, replay, threadTlsAlloc) : { mode: "fresh" }, ...soDeferGot.size ? { deferGotFunc: soDeferGot } : {}, ...soPresetGot.size ? { presetGotFunc: soPresetGot } : {}, ...!replay && reservedFnSlots.has(want.index) ? { reservedSymbolIndices: [...reservedFnSlots.get(want.index)] } : {}, ...replay ? { fixedMemoryBase: replay.memoryBase >>> 0, fixedTableBase: replay.tableBase >>> 0, skipDataRelocs: true, seedSymbolIndices: Array.isArray(replay.appended) ? replay.appended : [] } : preallocBase.has(want.index) ? { fixedMemoryBase: preallocBase.get(want.index) >>> 0 } : { allocMemory: soAllocMemory } }); if (threadCtxJoin && !soHandle) { throw new Error(`hwjs-thread-image: the shared image has no needed entry ${want.index} (${want.soname}) to join (never-silent)`); } if (threadCtx && !threadCtxJoin) { threadCtx.handles.set(`needed:${want.index}`, soHandle); } if (threadCtxJoin) { adoptSideTls( soHandle, `${want.soname} (needed entry ${want.index})`, false ); } handleBox.set(want.index, soHandle); if (!threadCtxJoin) closurePlanNote(closurePlan, `needed:${want.digest}`, soHandle); stagingPhase = "armModuleBudget"; armModuleBudget(soHandle); stagingPhase = "runCtors"; if (!replay && neededCtorsInStart) { const soExports = (soHandle.instance ?? soHandle).exports; const ctor = soExports.__wasm_call_ctors; if (typeof ctor === "function") { deferredNeededCtors.push({ ctor, moduleId: soId | 0, soname: want.soname, entry: want.index, ...drivenCtorHandles(soExports) }); } } else if (!replay) { ctorPlaced.add(want.index); runReadyNeededCtors(); } } neededHandles.push({ name: want.name, soname: want.soname, digest: want.digest, index: want.index, handle: soHandle, ...want.preload ? { preload: true } : {}, ...want.preloadDep ? { preloadDep: true } : {}, exports: (soHandle.instance ?? soHandle).exports, memoryBase: soHandle.memoryBase >>> 0, tableBase: soTableBase >>> 0, moduleId: soId | 0, appended: soHandle.tableEntries(), gotProviders: soGotProvider }); try { post({ kind: "dmesg", level: 6, text: `hwjs-libc: module #${1 + want.index} instantiated (${want.soname}, digest ${want.digest.slice(0, 16)}\u2026 moduleId=${soId} memoryBase=0x${(soHandle.memoryBase >>> 0).toString(16)} tableBase=${soTableBase}${replay ? " fork-replay" : ""}) \u2014 needed entry ${want.index}` }); } catch (_e) { } stagingWant = null; stagingPhase = ""; } if (ctorPlaced.size && ctorNext !== ctorOrder.length) { throw new Error( `hwjs-libc: ${ctorOrder.length - ctorNext} of ${ctorOrder.length} needed libraries were placed but not constructed (never-silent).` ); } if (deferredNeededCtors.length > 1) { deferredNeededCtors.sort((a, b) => ctorPos.get(a.entry) - ctorPos.get(b.entry)); } } catch (e) { if (stagingWant) { const w = stagingWant; let detail = ""; try { const base = e instanceof Error ? e.message : String(e); const frames = e && e.stack ? String(e.stack).split("\n").slice(1, 5).map((x) => x.trim()).filter(Boolean).join(" | ") : ""; detail = base + (frames ? ` [${frames}]` : ""); } catch (_e) { detail = "(unreportable throw value)"; } e = new Error( `hwjs-libc: needed entry ${w.index} (${w.soname}, digest ${String(w.digest).slice(0, 16)}) failed at ${stagingPhase}: ${detail}`, { cause: e } ); } if (await imageStageFatal("NEEDED-LOAD", e) === "return") { releaseProcessRunState("error"); return; } break imageLoop; } neededSoHandles = neededHandles.map((h) => ({ handle: h.handle, soname: h.soname, name: h.name, digest: h.digest, index: h.index, ...h.preload ? { preload: true } : {}, gotProviders: h.gotProviders, moduleId: h.moduleId })); neededPlacements = neededHandles.map((h) => ({ name: h.name, digest: h.digest, index: h.index, ...h.preload ? { preload: true } : {}, ...h.preloadDep ? { preloadDep: true } : {}, memoryBase: h.memoryBase, tableBase: h.tableBase, tableSize: sharedTable.length - h.tableBase >>> 0, /* Read now, not at the entry's own load: a later sibling's * address-take (soSiblingFnSlot) can append to it. */ moduleId: h.moduleId, appended: h.handle.tableEntries() })); if (threadCtxJoin && threadCtx.neededPlacements) { neededPlacements = threadCtx.neededPlacements; } } const mainGotFunc = threadCtxJoin ? /* @__PURE__ */ new Set() : new Set(mainImps.filter((i) => i.module === "GOT.func").map((i) => i.name)); for (const i of threadCtxJoin ? [] : mainImps) { if (i.module !== "env" || i.kind !== "function") continue; if (envImp[i.name] !== void 0) continue; if (typeof rtExports[i.name] === "function") { envImp[i.name] = driveImport(i.name, rtExports[i.name]); continue; } const [first] = mainImportProviders( i.name, rtExports, libcExports, neededScopeFor(i.name, neededHandles), mainGotFunc ); if (first) { envImp[i.name] = dlsymCallerImport( i.name, first.fn, libcExports, MAIN_DLSYM_CALLER, dlsymCallerBox ); } } mainGotFuncNames = mainGotFunc; for (const i of neededHandles.length && !threadCtxJoin ? mainImps : []) { if (i.module !== "env" || i.kind !== "function") continue; if (baseEnvNames.has(i.name)) continue; const providers = mainImportProviders( i.name, rtExports, libcExports, neededScopeFor(i.name, neededHandles), mainGotFunc ).map((p) => p.from === "rt" ? "rt (#0)" : p.from === "libc" ? "libc.so (#1)" : p.from.preload ? `${p.from.soname} (LD_PRELOAD)` : `${p.from.soname} (#${1 + p.from.index})`); if (providers.length > 1) { try { post({ kind: "dmesg", level: 6, text: `hwjs-libc: ${i.name} is exported by ${providers.length} placed modules (${providers.join(", ")}) \u2014 bound from ${providers[0]} by global-scope order` }); } catch (_e) { } } } try { if (libcSoHandle && !threadCtxJoin) { if (replaysModuleGraph(init.mode) && firstImage && init.dlopenFork) { adoptLateTableEntries(init.dlopenFork, true); } const libcBase = libcSoPlacement.memoryBase >>> 0; for (const i of mainImps) { if (i.kind !== "global") continue; if (i.module === "GOT.mem") { const g = libcExports[i.name]; if (g instanceof WebAssembly.Global) { (imports["GOT.mem"] ??= {})[i.name] = new WebAssembly.Global( { value: "i32", mutable: true }, libcBase + (g.value | 0) | 0 ); continue; } const rg = rtExports ? rtExports[i.name] : void 0; if (rg instanceof WebAssembly.Global && hwjsRtPlacement) { (imports["GOT.mem"] ??= {})[i.name] = new WebAssembly.Global( { value: "i32", mutable: true }, (hwjsRtPlacement.memoryBase >>> 0) + (rg.value | 0) | 0 ); continue; } let neededProviders = 0; let neededAddr = 0; for (const h of neededHandles) { const ng = h.exports[i.name]; if (!(ng instanceof WebAssembly.Global)) continue; if (neededProviders++ === 0) { neededAddr = (h.memoryBase >>> 0) + (ng.value | 0) | 0; } } if (neededProviders > 0) { (imports["GOT.mem"] ??= {})[i.name] = new WebAssembly.Global( { value: "i32", mutable: true }, neededAddr ); if (neededProviders > 1) { try { post({ kind: "dmesg", level: 6, text: `hwjs-libc: GOT.mem.${i.name} is exported as data by ${neededProviders} needed libraries \u2014 bound from the first in needed-list order` }); } catch (_e) { } } continue; } throw new Error( `hwjs-libc: main GOT.mem.${i.name} names no libc.so data export, no runtime (module #0) data export, and no data export of any needed library either \u2014 the by-name witness should have made this link-fatal; a skewed/foreign artifact pair (never-silent).` ); } else if (i.module === "GOT.func") { let idx = 0; if (mainNeededBeforeLibc(i.name, rtExports, mainGotFunc)) { for (const h of neededScopeFor(i.name, neededHandles)) { idx = h.handle.dlsymFunction(i.name); if (idx > 0) break; } } if (!(idx > 0)) idx = libcSoHandle.dlsymFunction(i.name); if (!(idx > 0) && hwjsRtHandle) idx = hwjsRtHandle.dlsymFunction(i.name); if (!(idx > 0)) { for (const h of neededHandles) { idx = h.handle.dlsymFunction(i.name); if (idx > 0) break; } } if (!(idx > 0)) { throw new Error( `hwjs-libc: main GOT.func.${i.name} names no libc.so function export, no runtime op, and no export of any needed library of that name \u2014 cannot mint a table identity (never-silent).` ); } (imports["GOT.func"] ??= {})[i.name] = new WebAssembly.Global({ value: "i32", mutable: true }, idx); } } } } catch (e) { if (await imageStageFatal("LIBC-GOT-MINT", e) === "return") { releaseProcessRunState("error"); return; } break imageLoop; } try { post({ kind: "dmesg", level: 6, text: `hwjs-rt: module #0 instantiated (moduleId=${rtId} memoryBase=0x${hwjsRtPlacement.memoryBase.toString(16)} tableBase=${rtTableBase}) \u2014 runtime provider is the kernel` }); } catch (_e) { } } } let statusChannelAddrGlobal = null; for (const i of moduleImportsOf(module)) { if (i.kind === "global" && i.module === "env" && i.name === "__hwjs_status_channel_addr") { statusChannelAddrGlobal = threadCtx ? threadCtx.chanGlobal : new WebAssembly.Global({ value: "i32", mutable: true }, 0); (imports.env ??= {}).__hwjs_status_channel_addr = statusChannelAddrGlobal; mainLaneAddressed = true; break; } } if (!threadCtxJoin && moduleImportsOf(module).some((i) => i.kind === "global" && i.module === "env" && i.name === "__hwjs_budget")) { if (!((imports.env ??= {}).__hwjs_budget instanceof WebAssembly.Global)) { imports.env.__hwjs_budget = new WebAssembly.Global({ value: "i32", mutable: true }, 0); } hwjsLaneBudget = imports.env.__hwjs_budget; } let instance; try { if (threadCtxJoin) { instance = threadCtx.mainInstance; if (!instance) { throw new Error("hwjs-thread-image: the shared image has no main instance to join (never-silent)"); } } else { closurePlanEnd(closurePlan, post); closurePlan = null; const filtered = filterImports(module, imports); instance = await WebAssembly.instantiate(module, filtered); heapChargeInstance(instance, module); if (sharedTable) { tableLedgerNoteInstance(sharedTable, instance, module, curWasmBytes, filtered); } if (threadCtx) threadCtxEnter(threadCtx, threadRec); } } catch (e) { if (await imageStageFatal("INSTANTIATE", e) === "return") { releaseProcessRunState("error"); return; } break imageLoop; } wasmJitInstance = instance; wasmJitImage = wasmJitBindImage(instance, module, curWasmBytes); wasmJit.seat(); { const mainExp = instance.exports; let rtExp = hwjsRtInstance && !threadCtxJoin ? hwjsRtInstance.exports : null; if (rtExp && hwjsRtPlacement) { const rtBase = hwjsRtPlacement.memoryBase >>> 0; const rebased = /* @__PURE__ */ Object.create(null); for (const k of Object.keys(rtExp)) { const v = rtExp[k]; rebased[k] = v instanceof WebAssembly.Global ? new WebAssembly.Global( { value: "i32" }, rtBase + (v.value | 0) | 0 ) : v; } rtExp = rebased; } let libcExp = libcSoHandle && !threadCtxJoin ? (libcSoHandle.instance ?? libcSoHandle).exports : null; if (libcExp && libcSoPlacement) { const libcBase = libcSoPlacement.memoryBase >>> 0; const rebased = /* @__PURE__ */ Object.create(null); for (const k of Object.keys(libcExp)) { const v = libcExp[k]; rebased[k] = v instanceof WebAssembly.Global && k !== "__tls_base" ? new WebAssembly.Global( { value: "i32" }, libcBase + (v.value | 0) | 0 ) : v; } libcExp = rebased; } userExports = threadCtxJoin ? threadCtx.userExports : rtExp || libcExp ? Object.assign( /* @__PURE__ */ Object.create(null), rtExp ?? {}, libcExp ?? {}, mainExp, mainExp.__stack_pointer === void 0 && imports.env && imports.env.__stack_pointer instanceof WebAssembly.Global ? { __stack_pointer: imports.env.__stack_pointer } : {} ) : mainExp; } const exp = threadCtx ? makeThreadExportView(threadCtx, threadRec, userExports) : userExports; rootMapInitialSp = initialStackPointer(exp); rootMapLayoutBytes = null; if (!runtimeBlockBound) { const bound = await bindRuntimeBlock(exp, "post-main"); if (threadCtx) threadCtxEnter(threadCtx, threadRec); if (!bound.ok) { if (init.mode === "thread") { threadBlockRefusal = bound.why; } else { throw new Error(`hwjs-tcb: ${bound.why} Refusing to drive (never-silent).`); } } } if (statusChannelAddrGlobal && !threadBlockRefusal) { if (!currentTcb) { throw new Error( "lane-addressed main imports env.__hwjs_status_channel_addr but no user-runtime block is bound for this thread \u2014 refusing a 0 bind (the R1-glibc phantom address-0 class; never-silent)." ); } if (threadCtx) threadCtxEnter(threadCtx, threadRec); statusChannelAddrGlobal.value = currentTcb | 0; if (DEBUG_K7_U4F) { try { post({ kind: "dmesg", level: 6, text: `[chan-addr main] mode=${init.mode} block=0x${(currentTcb >>> 0).toString(16)}` }); } catch (_e) { } } } if (!firstImage && D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `EXEC-LOAD-DIAG: re-instantiate DONE; entering drive (bash _start)` }); } catch (_e) { } } if (D1_TRACE_SYS && sharedTable) { try { const probe = (i) => { try { return typeof sharedTable.get(i); } catch (_e) { return "oob"; } }; post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} DYNMAIN-TABLE len=${sharedTable.length} get(0)=${probe(0)} get(1)=${probe(1)} get(85)=${probe(85)} exportsTable=${exp.__indirect_function_table instanceof WebAssembly.Table ? "yes" : "no"} sameAsExport=${exp.__indirect_function_table === sharedTable}` }); } catch (_e) { } } try { if (hwjsRtHandle || libcSoHandle || neededSoHandles.length) { const gotPatchTargets = [ ...hwjsRtHandle ? [{ handle: hwjsRtHandle, who: "rt" }] : [], ...libcSoHandle ? [{ handle: libcSoHandle, who: "libc.so" }] : [], ...neededSoHandles.map((r) => ({ handle: r.handle, who: `${r.soname} (needed entry ${r.index})`, gotProviders: r.gotProviders, moduleId: r.moduleId })) ]; const siblingExp = neededSoHandles.map((r) => ({ index: r.index, soname: r.soname, exports: (r.handle.instance ?? r.handle).exports ?? r.handle.exports })); const patchPost = LINK_PLAN_ON && sharedTable && activeElemEndOf(module, curWasmBytes) <= sharedTableInitial && tableWritesOf(module, curWasmBytes) === "none" ? { mainWindowEnd: sharedTableInitial, mainClean: true } : void 0; for (const t of gotPatchTargets) { const h = t.handle; if (!h) continue; const who = t.who; const ownExp = (h.instance ?? h).exports ?? h.exports; for (const name2 of h.pendingGotFuncNames()) { const pick = neededGotPatchProvider(name2, { exp, ownExp, siblings: siblingExp, provider: t.gotProviders ? t.gotProviders.get(name2) : void 0 }); const fn2 = pick ? pick.f : void 0; if (pick && pick.sibling) { try { post({ kind: "dmesg", level: 6, text: `hwjs-rt: ${who} took the address of "${name2}" (GOT.func); patched from sibling needed entry ${pick.sibling.index} (${pick.sibling.soname})` }); } catch (_e) { } } if (typeof fn2 !== "function") { throw new Error( `hwjs-rt: ${who} took the address of "${name2}" (GOT.func) but no provider (main/rt/libc.so own exports, or any needed entry of this main) supplies such a function \u2014 cannot patch the deferred slot (never-silent).` ); } const slot = h.patchGotFunc(name2, unwrapThreadExport(fn2), patchPost); if (t.moduleId !== void 0 && typeof ownExp[name2] === "function" && unwrapThreadExport(ownExp[name2]) !== unwrapThreadExport(fn2)) { capsummaryProcessRecs.interpose(t.moduleId, slot); } } } if (!patchPost && sharedTable) tableIndexForget(sharedTable); moduleFactsDrop(); } } catch (e) { if (await imageStageFatal("GOT-PATCH", e) === "return") { releaseProcessRunState("error"); return; } break imageLoop; } if (LINK_PLAN_TRACE && (hwjsRtHandle || libcSoHandle)) { try { post({ kind: "dmesg", level: 6, text: `hwjs-link-plan pid=${ctrl[C.PID] | 0} ${JSON.stringify(linkPlanStats)}` }); } catch (_e) { } } if (replaysModuleGraph(init.mode) && firstImage && init.dlopenFork && typeof init.dlopenFork === "object") { if (threadCtxJoin && threadCtx.fpcastRecs) { fpcastProcessRecs = threadCtx.fpcastRecs; } else if (Array.isArray(init.dlopenFork.fpcastRecs)) { fpcastProcessRecs = new XmodInputMap( init.dlopenFork.fpcastRecs.map(([k, v]) => [k >>> 0, v >>> 0]) ); } if (threadCtxJoin && threadCtx.capsummaryRecs) { capsummaryProcessRecs = threadCtx.capsummaryRecs; } else if (init.dlopenFork.capsummaryRecs) { capsummaryProcessRecs = createCapsummaryRegistry(init.dlopenFork.capsummaryRecs); } replayForkDlopens(init.dlopenFork); const tramps = Array.isArray(init.dlopenFork.neededCtorTrampolines) ? init.dlopenFork.neededCtorTrampolines : []; if (tramps.length && init.mode !== "thread") { replaceNeededCtorTrampolines({ table: sharedTable, records: tramps, resolve: (entry) => { const h = neededSoHandles.find((r) => r.index === entry); return h ? (h.handle.instance ?? h.handle).exports : null; } }); try { post({ kind: "dmesg", level: 6, text: `hwjs-libc: ${tramps.length} needed ctor trampoline(s) placed again (${init.mode}, table ${tramps.map((r) => r.index).join(",")})` }); } catch (_e) { } } neededCtorTrampolines = tramps.map((r) => ({ ...r })); if (init.mode === "thread" || init.migratePid !== void 0) { placementApplied = init.dlopenFork.placementGen | 0; } } const hwjsData = (name2) => { const g = userExports[name2]; return g instanceof WebAssembly.Global ? g.value >>> 0 : 0; }; stwCtl = null; hwjsDrive = typeof userExports.hwjs_resume === "function" && typeof userExports.hwjs_done === "function" && typeof userExports.hwjs_destroy === "function" && typeof userExports.__hwjs_take_parked === "function" && tcbFieldAddr("PARKED") !== 0 && tcbFieldAddr("PARK_REASON") !== 0; { const _driveAbi = hwjsDrive && typeof userExports.__hwjs_drive_abi === "function" ? userExports.__hwjs_drive_abi() | 0 : 0; hwjsFlat = _driveAbi === 3 || _driveAbi === 4; } libcParksAnySyscall = hwjsDrive && typeof userExports.__hwjs_libc_syscall_park_abi === "function" && (userExports.__hwjs_libc_syscall_park_abi() | 0) === 1; libcResumesMmap = hwjsDrive && typeof userExports.__hwjs_libc_mmap_park_abi === "function" && (userExports.__hwjs_libc_mmap_park_abi() | 0) === 1; if (init.mergedCpu0Lane === true && !libcParksAnySyscall) { const who = Array.isArray(init.argv) && init.argv.length > 0 ? String(init.argv[0]) : `pid ${init.pid ?? "?"}`; const msg = `hwjs-merged REFUSED image ${who} on the merged CPU-0 lane: it does not export __hwjs_libc_syscall_park_abi()==1 (hwjsDrive=${hwjsDrive ? 1 : 0}), so nothing in it can absorb a -517 cooperative park at all and every blocking read falls through to an UNBOUNDED in-kernel wait. (An image that DOES export 1 is admitted, and that is not the same as proven: glibc's port documents its export as an over-approximation over its nominated TUs. Host-answered syscalls no longer rely on it \u2014 they are answered in place through the merged lane's synchronous door \u2014 but a kernel-route block-park still does, and a libc that does not re-issue is caught there by measurement, at the DEFERRED-RPC MISMATCH arm, not here.) This lane shares its JS thread with CPU 0 \u2014 the dispatcher, every kthread, the timer tick, the virtio IRQ bottom half, and inline the PtyBridge that delivers the keystroke this image would be waiting for \u2014 so that wait stops the machine, at the first prompt, with nothing to see. PLAN-COLLAPSED-CPU0 \xA73.5 used to send this image to mergedCpuHost:'separate' (linux-6.12-glibc-bash-coreutils today); that topology is deleted, so there is nowhere to send it. Run an image whose libc parks, or widen this one's park nomination until it does.`; post({ kind: "error", pid: init.pid, message: msg }); throw new Error(msg); } libcParkAbiPushed = false; fileMapper.reset(); if (sharedMapsImageInstalled) sharedMaps.reset(); sharedMapsImageInstalled = true; hwjsForkLatched = false; hwjsExecLatched = false; if (typeof process !== "undefined" && process.env && process.env.HWJS_RED_LANE_RECYCLE_STALE === "1" && typeof exp.__hwjs_red_lane_recycle_stale === "function") { exp.__hwjs_red_lane_recycle_stale(1); } const skipCtors = init.mode === "fork-resume" && firstImage || /* A migration re-instantiates a module over memory whose ctors ran * long ago, in this same process, on another Worker. Running them * again would re-zero live .data and re-register live objects — * unconditionally, with no dlopenFork/lane qualification, because * unlike a thread there is no "fresh world" variant of a migration: * every migrate-resume is by definition a re-entry into a running * process. */ init.mode === "migrate-resume" && firstImage || init.mode === "thread" && firstImage && (!!init.dlopenFork || init.rtThread === true); if (typeof exp.__hwjs_budget_set === "function") { exp.__hwjs_budget_set(HWJS_USER_INITIAL_BUDGET | 0); setModuleBudgets(HWJS_USER_INITIAL_BUDGET); } if (typeof exp.__hwjs_set_stall_bound === "function") { const sbEnv = typeof process !== "undefined" && process.env.HWJS_F93_STALL_BOUND || ""; const sb = parseInt(sbEnv, 10); if (Number.isFinite(sb) && sb > 0) exp.__hwjs_set_stall_bound(sb | 0); } const libcOwnerExports = libcSoHandle ? (libcSoHandle.instance ?? libcSoHandle).exports : null; const bindBootstrapTls = (prov, libcOwner, block) => { prov.__wasm_init_tls(block); if (prov === libcOwner && typeof setLibcTlsBase === "function") { try { setLibcTlsBase(block >>> 0); } catch (_e) { } } }; const tlsProv = libcOwnerExports && typeof libcOwnerExports.__wasm_init_tls === "function" && typeof libcOwnerExports.__wasm32_get_tls_size === "function" && typeof libcOwnerExports.__wasm32_get_tls_align === "function" ? libcOwnerExports : exp; if (!skipCtors && init.mode !== "thread" && typeof tlsProv.__wasm_init_tls === "function" && typeof tlsProv.__wasm32_get_tls_size === "function" && typeof tlsProv.__wasm32_get_tls_align === "function") { const tlsSize = tlsProv.__wasm32_get_tls_size() >>> 0; if (tlsSize !== 0) { const tlsAlign = Math.max(tlsProv.__wasm32_get_tls_align() >>> 0, 16); const hb = exp.__heap_base; const heapBase = hb instanceof WebAssembly.Global ? hb.value >>> 0 : typeof hb === "number" ? hb >>> 0 : 0; if (heapBase === 0) { throw new Error( `HWJS bootstrap-TLS: image exports __wasm_init_tls and a non-zero __tls_size (${tlsSize}) but no usable __heap_base global \u2014 cannot place the pre-ctor TLS block. Refusing to run glibc ctors against a zero __tls_base (the ctor malloc would smash heap metadata).` ); } const block = heapBase + (tlsAlign - 1) & ~(tlsAlign - 1); const BOOTSTRAP_TLS_BRK_RESERVE = 1 * 1024 * 1024; if (block - heapBase + tlsSize > BOOTSTRAP_TLS_BRK_RESERVE) { throw new Error( `HWJS bootstrap-TLS: TLS block (size=${tlsSize}, align=${tlsAlign}) does not fit the ${BOOTSTRAP_TLS_BRK_RESERVE}-byte brk window at __heap_base=0x${heapBase.toString(16)} \u2014 raise BRK_RESERVE (kernelSpawnHandler) or shrink TLS. Refusing a colliding bootstrap block.` ); } bindBootstrapTls(tlsProv, libcOwnerExports, block); if (libcCtorsDeferred && libcSoHandle && typeof libcSoHandle.runCtors === "function") { libcCtorsDeferred = false; libcSoHandle.runCtors(); } } } const mainImageOwnsTlsBesideLibc = (() => { try { if (!libcOwnerExports || typeof libcOwnerExports.__wasm32_get_tls_size !== "function" || libcOwnerExports.__wasm32_get_tls_size() >>> 0 === 0) { return false; } const mex = instance.exports; return typeof mex.__wasm_init_tls === "function" && typeof mex.__wasm32_get_tls_size === "function" && typeof mex.__wasm32_get_tls_align === "function" && mex.__wasm32_get_tls_size() >>> 0 !== 0; } catch (_e) { return false; } })(); const mainImageTlsSlot = () => { const mex = instance.exports; const hb = mex.__heap_base; const heapBase = hb instanceof WebAssembly.Global ? hb.value >>> 0 : typeof hb === "number" ? hb >>> 0 : 0; if (heapBase === 0) { throw new Error( "HWJS main-image TLS: the main carries thread_local state beside a TLS-owning libc.so but exports no usable __heap_base \u2014 cannot place the initial thread's main-TLS block (never-silent)." ); } return mainTlsSlot( heapBase, mex.__wasm32_get_tls_size() >>> 0, mex.__wasm32_get_tls_align() >>> 0 ); }; const initialMainTlsBlock = () => { const slot = mainImageTlsSlot(); if (slot.addr === 0) { throw new Error( `HWJS main-image TLS: one ${slot.stride}B block for a ${instance.exports.__wasm32_get_tls_size() >>> 0}B/${slot.align}-aligned main TLS image does not fit half the ${MAIN_TLS_BRK_BYTES}B brk window \u2014 refusing a colliding carve (never-silent).` ); } return slot.addr; }; const threadMainTlsBlock = () => { const slot = mainImageTlsSlot(); return threadTlsAlloc(slot.stride, slot.align); }; const bindMainImageTls = (addr, materialise) => { if (materialise) instance.exports.__wasm_init_tls(addr | 0); else instance.exports.__wasm32_set_tls_base(addr | 0); currentMainTlsBase = addr >>> 0; return addr >>> 0; }; const bindTaskTlsBase = (tp, mainTls, materialise) => { if (!mainImageOwnsTlsBesideLibc) { exp.__wasm32_set_tls_base(tp | 0); setLibcTlsBase(tp | 0); return true; } setLibcTlsBase(tp | 0); if (mainTls >>> 0 === 0) return false; bindMainImageTls(mainTls >>> 0, !!materialise); return true; }; const continuingMainTlsBlock = () => mainImageOwnsTlsBesideLibc ? init.mainTlsBase >>> 0 || initialMainTlsBlock() : 0; if (!skipCtors && init.mode !== "thread" && mainImageOwnsTlsBesideLibc) { try { bindMainImageTls(initialMainTlsBlock(), true); } catch (e) { if (await imageStageFatal("MAIN-TLS", e) === "return") { releaseProcessRunState("error"); return; } break imageLoop; } } if (!skipCtors && typeof instance.exports.__wasm_apply_data_relocs === "function") { instance.exports.__wasm_apply_data_relocs(); } const ctorsRunInStart = typeof exp.__wasm32_ctors_run_in_start !== "undefined"; if (!skipCtors && deferredNeededCtors.length) { const idx = publishNeededCtorsInStart({ table: sharedTable, memory: init.memory, list: deferredNeededCtors, slotAddr: exp.__wasm32_needed_ctors_in_start() }); neededCtorTrampolines = deferredNeededCtors.map((d, i) => ({ index: idx[i] >>> 0, entry: d.entry | 0, soname: d.soname, run: !!(idx.driven && d.runner && typeof d.deferSet === "function") })); deferredNeededCtors.forEach((d, i) => { try { post({ kind: "dmesg", level: 6, text: `hwjs-libc: ${d.soname} ctors deferred to _start (moduleId=${d.moduleId}, table ${idx[i]}${idx.driven && d.runner ? `, runner ${d.runner}` : ""})` }); } catch (_e) { } }); deferredNeededCtors = []; } if (!skipCtors && !ctorsRunInStart && typeof exp.__wasm_call_ctors === "function") { exp.__wasm_call_ctors(); } if (!threadBlockRefusal && typeof init.signalPendingOffset === "number" && typeof exp.__wasm32_set_signal_region === "function") { exp.__wasm32_set_signal_region(init.signalPendingOffset >>> 0); } if (threadCtx && !threadCtxJoin && !threadCtx.ready) { threadCtx.table = sharedTable; threadCtx.gotFuncIndex = dlopenGotFuncIndex; threadCtx.mainScopeIndex = dlopenMainScopeIndex; threadCtx.spGlobal = imports.env && imports.env.__stack_pointer instanceof WebAssembly.Global ? imports.env.__stack_pointer : null; threadCtx.budgetGlobal = hwjsLaneBudget; threadCtx.mainInstance = instance; threadCtx.userExports = userExports; threadCtx.rtPlacement = hwjsRtPlacement; threadCtx.fpcastRecs = fpcastProcessRecs; threadCtx.capsummaryRecs = capsummaryProcessRecs; threadCtx.libcPlacement = libcSoPlacement; threadCtx.neededPlacements = neededPlacements; const tlsGlobals = threadCtx.tlsGlobals; if (libcSoHandle) { const g = (libcSoHandle.instance ?? libcSoHandle).exports.__tls_base; if (g instanceof WebAssembly.Global && !tlsGlobals.includes(g)) tlsGlobals.push(g); } for (const n of neededSoHandles) threadCtxNoteTls(threadCtx, n && n.handle); for (const m of (threadCtx.dlEntries || /* @__PURE__ */ new Map()).values()) { threadCtxNoteTls(threadCtx, m && m.handle); } try { threadCtx.regs = makeThreadRegs({ spGlobal: threadCtx.spGlobal, mainExports: instance.exports, rtExports: hwjsRtInstance ? hwjsRtInstance.exports : null, tlsGlobals, chanGlobal: threadCtx.chanGlobal, /* Exactly the budgets serviceCooperativeBreath refills: the * merged view's accessor and every armed side-module Global, taken * at publish. A module bound to the lane's budget (budgetGlobal) * reads the main's, which the accessor covers. NOT covered: a module * with a budget Global of its own that a member dlopens AFTER * publish arms it in that member's run() only, so co-residents * would share that one counter. Recorded, not fixed. */ budgetExports: userExports, budgetGlobals: moduleBudgetGlobals.slice() }); threadCtx.ready = true; try { post({ kind: "dmesg", level: 6, text: `hwjs-thread-image tid=${init.tid | 0} PUBLISHED its process image (key ${threadCtx.key})` }); } catch (_e) { } } catch (e) { threadCtx.failed = true; threadCtxDrop(init.memoryId, threadCtx); try { post({ kind: "dmesg", level: 4, text: `hwjs-thread-image tid=${init.tid | 0}: ${e.message}` }); } catch (_e) { } } threadCtx.resolveReady(); } const mode = init.mode === "thread" ? "thread" : "fork"; let execNextBytes = null; let threadLanePending = false; try { if (mode === "thread") { const refuseThread = async (message) => { await releaseThreadBlock("thread refused"); await notifyChildExitOnce(0, 0); if (threadCtx) releaseProcessRunState("thread refused"); post({ kind: "thread-refused", pid: init.pid, tid: init.tid, message: `${message}. pthread_create returns EAGAIN (loud, contained, never silent).` }); }; if (threadBlockRefusal) { await refuseThread(threadBlockRefusal); return; } { const heapWhy = await threadHeapRefusal(post); if (heapWhy) { await refuseThread(heapWhy); return; } } if (typeof exp.__wasm32_user_entry !== "function") { post({ kind: "error", pid: init.pid, message: "thread-mode Worker missing __wasm32_user_entry export \u2014 link wasm_thread.S into the binary" }); return; } if (init.rtThread === true) { const tdbg = (s) => { if (DEBUG_K7_U4F) { try { post({ kind: "dmesg", level: 6, text: `[thr tid=${init.tid} block=0x${(currentTcb >>> 0).toString(16)}] ${s}` }); } catch (_e) { } } }; tdbg("thread arm entered"); thrTrace(init, post, "thread-arm-entered"); const threadReady = mainLaneAddressed && hwjsDrive && hwjsFlat && currentTcb !== 0 && typeof exp.__hwjs_thread_detach === "function" && statusChannelAddrGlobal !== null; if (!threadReady) { await refuseThread( `thread-mode spawn cannot run on this image: lane_addressed=${mainLaneAddressed ? 1 : 0} block_runtime=${typeof exp.__hwjs_thread_detach === "function" ? 1 : 0} block=0x${(currentTcb >>> 0).toString(16)} flat_drive=${hwjsFlat ? 1 : 0} chan_addr_global=${statusChannelAddrGlobal !== null ? 1 : 0} \u2014 rebuild the image with lane-aware channel addressing (HWJS_LANE_ADDRESSED=1) against the current runtime` ); return; } } if (threadSideTlsUnbound || !threadCtxJoin && [...dlopenModules.values(), ...neededSoHandles].some((m) => m && m.handle && m.handle.tls && m.handle.tls.unbound)) { await refuseThread( "side-module TLS: this thread's TLS arena could not grow for a TLS-owning side module (SYS_mmap refused \u2014 out of memory; the runtime wrote the syscall's own answer to stderr)" ); return; } if (typeof exp.__wasm32_set_stack_pointer === "function") { exp.__wasm32_set_stack_pointer(init.stackPointerOffset | 0); } if (hwjsRtStackPointer) { const side = threadCtx && threadRec ? threadCtxCall(threadCtx, threadRec, () => threadTlsAlloc(HWJS_RT_STACK_CARVE, 16)) : threadTlsAlloc(HWJS_RT_STACK_CARVE, 16); if (!side) { await refuseThread( `side-module stack: this thread's TLS arena could not grow for its ${HWJS_RT_STACK_CARVE}B libc.so/rt stack (SYS_mmap refused \u2014 out of memory; the runtime wrote the syscall's own answer to stderr)` ); return; } threadSideSpTop = side + HWJS_RT_STACK_CARVE >>> 0; hwjsRtStackPointer.value = threadSideSpTop | 0; } if (typeof exp.__wasm32_set_tls_base === "function") { const mainTls = !mainImageOwnsTlsBesideLibc ? 0 : init.vforkChild ? continuingMainTlsBlock() : threadMainTlsBlock(); if (!bindTaskTlsBase(init.tlsPointerOffset, mainTls, !init.vforkChild)) { await refuseThread( `main-image TLS: this thread's TLS arena could not grow for a ${instance.exports.__wasm32_get_tls_size() >>> 0}B main TLS image (SYS_mmap refused \u2014 out of memory; the runtime wrote the syscall's own answer to stderr)` ); return; } } if (init.rtThread === true) { const tdbg = (s) => { if (DEBUG_K7_U4F) { try { post({ kind: "dmesg", level: 6, text: `[thr tid=${init.tid} block=0x${(currentTcb >>> 0).toString(16)}] ${s}` }); } catch (_e) { } } }; tdbg("block bound; TLS bound"); thrTrace(init, post, "thread-adopted-post"); post({ kind: "thread-adopted", pid: init.pid, tid: init.tid }); threadLanePending = true; } else if (hwjsDrive && (hwjsRtHandle || libcSoHandle)) { const parkedAddr = tcbFieldAddr("PARKED"); const ownerAddr = tcbFieldAddr("PARKED_OWNER"); if (!parkedAddr || !ownerAddr) { throw new Error( "thread arm: coro image without the parked-slot surface (__hwjs_parked/_owner exports) \u2014 cannot adopt the thread chain (never-silent)." ); } exp.__wasm32_user_entry(init.argRegionOffset | 0); if (uU32()[parkedAddr >> 2] === 0) { if (!exitPosted) { throw new Error( "thread arm: __wasm32_user_entry returned with an EMPTY parked slot and no exit \u2014 the thread chain neither parked for adoption nor terminated (never-silent)." ); } } else { const th = exp.__hwjs_take_parked(0, 0) >>> 0; try { exp.hwjs_destroy(th); } catch (e) { try { post({ kind: "dmesg", level: 3, text: `thread arm: hwjs_destroy of the refused thread chain trapped (${e instanceof Error ? e.message : String(e)}) \u2014 one chain's frames leak in the arena (bounded, loud)` }); } catch (_e2) { } } await notifyChildExitOnce(0, 0); post({ kind: "thread-refused", pid: init.pid, tid: init.tid, message: "thread-mode placement replay is LIVE (rt #0 + libc.so #1 replayed at the recorded bases in this thread Worker) but thread EXECUTION on the coro substrate needs the K7+ per-thread-park lift \u2014 the user-rt drive surface (parked slot / xfer verdict / drive leaf / frame arena) is single-driver-per-process shared state. pthread_create is refused with -EAGAIN (loud, contained; the thread's kernel task is reaped to a plain zombie before refusal \u2014 never a silent hang, a torn park slot, or a live-task leak)." }); return; } } else { post({ kind: "thread-adopted", pid: init.pid, tid: init.tid }); const rc = exp.__wasm32_user_entry(init.argRegionOffset | 0); if (typeof rc === "number" && !exitPosted) exitCode = rc & 255; } } if (threadLanePending || mode !== "thread" && typeof exp._start === "function") { const execImage = !firstImage && execPendingArgv !== null; const srcArgv = execImage ? execPendingArgv : init.mode !== "fork-resume" ? init.argv : null; const srcEnvp = execImage ? execPendingEnvp || [] : init.mode !== "fork-resume" ? init.envp : []; if (Array.isArray(srcArgv) && srcArgv.length > 0 && typeof exp.__wasm32_args_buf_addr === "function") { const argvArr = srcArgv.map((s) => String(s)); const envpArr = Array.isArray(srcEnvp) ? srcEnvp.map((s) => String(s)) : []; const base = exp.__wasm32_args_buf_addr() >>> 0; const cap = typeof exp.__wasm32_args_buf_size === "function" ? exp.__wasm32_args_buf_size() | 0 : 0; const enc2 = new TextEncoder(); const strBufs = [...argvArr, ...envpArr].map((s) => enc2.encode(s)); const redNoAuxv = typeof process !== "undefined" && process.env?.HWJS_RED_NO_AUXV === "1"; const AT_PAGESZ = 6; const AT_RANDOM = 25; const auxvWords = redNoAuxv ? [] : [AT_PAGESZ, 4096, AT_RANDOM, 0, 0, 0]; const nptrs = argvArr.length + 1 + envpArr.length + 1; const tableOff = 8; let strOff = tableOff + (nptrs + auxvWords.length) * 4; const strEnd = strBufs.reduce((n, b) => n + b.length + 1, strOff); const randOff = strEnd + 3 & ~3; const total = redNoAuxv ? strEnd : randOff + 16; if (total > cap) { post({ kind: "error", pid: init.pid, message: `argv block (${total}B) exceeds __wasm32_args_buf (${cap}B)` }); return; } const dv = new DataView(init.memory.buffer); const u8 = new Uint8Array(init.memory.buffer); let p = tableOff; let si = 0; const writeVec = (arr) => { for (const _s of arr) { const bytes = strBufs[si++]; const addr = base + strOff; u8.set(bytes, base + strOff); u8[base + strOff + bytes.length] = 0; strOff += bytes.length + 1; dv.setUint32(base + p, addr >>> 0, true); p += 4; } dv.setUint32(base + p, 0, true); p += 4; }; writeVec(argvArr); writeVec(envpArr); if (!redNoAuxv) { const rnd = new Uint8Array(16); globalThis.crypto.getRandomValues(rnd); u8.set(rnd, base + randOff); auxvWords[3] = base + randOff >>> 0; } for (const w of auxvWords) { dv.setUint32(base + p, w >>> 0, true); p += 4; } dv.setUint32(base + 0, argvArr.length >>> 0, true); dv.setUint32(base + 4, envpArr.length >>> 0, true); const kexp = vmlinuxInstance ? vmlinuxInstance.exports : null; if (kexp && typeof kexp.wasm32_user_args_set === "function") { const argsCall = () => kexp.wasm32_user_args_set(base >>> 0, total >>> 0) | 0; const argsRc = hwjsLane ? hwjsLane.bracket("wasm32_user_args_set", argsCall) | 0 : argsCall(); if (argsRc < 0) { try { post({ kind: "dmesg", level: 4, text: `hwjs-args: pid=${init.pid} the kernel refused the ${total}B argument block (errno ${-argsRc}); /proc/${init.pid}/cmdline, environ and auxv keep their previous contents` }); } catch (_e) { } } } if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `ARGS-BLOCK pid=${init.pid} ${execImage ? "exec" : "boot"} base=0x${base.toString(16)} argc=${argvArr.length} envc=${envpArr.length} auxv=[${auxvWords.join(",")}] auxv@0x${(base + tableOff + nptrs * 4).toString(16)}` }); } catch (_e) { } } } if (hwjsDrive) { const refillBreathBudget = () => { exp.__hwjs_budget_set(breathRefill | 0); setModuleBudgets(breathRefill); breathSampleUnits = breathRefill; breathSampleSeq = acctSliceSeq; breathSampleCut = breathCutSeq; breathCutLeft = -1; }; const serviceCooperativeBreath = async () => { if (typeof exp.__hwjs_budget_set !== "function") return false; refillBreathBudget(); if (!HWJS_NO_SP_YIELD) await macrotaskTurn(); return true; }; if (hwjsFlat) { const reasonAddr = tcbFieldAddr("PARK_REASON"); const resultAddr = tcbFieldAddr("PARK_RESULT"); if (!reasonAddr || !resultAddr) { throw new Error( "M-FLATDRIVE: flat image with no user-runtime block bound for this thread \u2014 the park reason/result slots have no address. Refusing to drive blind (never-silent)." ); } const HWJS_DRIVE_DONE = 53406; const HWJS_DRIVE_DONE_LIVE = 53407; let hwjsCoopBreaths = 0; let threadChainTop = 0; const flatCensusOn = typeof process !== "undefined" && process.env.HWJS_FLAT_CENSUS === "1"; const censusNow = typeof performance !== "undefined" && typeof performance.now === "function" ? () => performance.now() : () => Date.now(); const flatCensus = { NONE: 0, FORK: 0, EXEC: 0, RESCHED: 0, PREEMPT: 0, DONE: 0, other: 0, wasmCalls: 0, tWasmMs: 0, tHostMs: 0 }; let flatCensusEmitted = false; const emitFlatCensus = (where) => { if (!flatCensusOn || flatCensusEmitted) return; flatCensusEmitted = true; const reentries = flatCensus.NONE + flatCensus.FORK + flatCensus.EXEC + flatCensus.RESCHED + flatCensus.PREEMPT; const line = `hwjs-flat-census pid=${ctrl[C.PID] | 0} (${where}): host-reentries=${reentries} [NONE=${flatCensus.NONE} FORK=${flatCensus.FORK} EXEC=${flatCensus.EXEC} RESCHED=${flatCensus.RESCHED} PREEMPT=${flatCensus.PREEMPT}] DONE=${flatCensus.DONE} other=${flatCensus.other}; wasmCalls=${flatCensus.wasmCalls} tWasm=${flatCensus.tWasmMs.toFixed(1)}ms tHost=${flatCensus.tHostMs.toFixed(1)}ms (avg/crossing: wasm=${(flatCensus.tWasmMs / Math.max(1, flatCensus.wasmCalls)).toFixed(3)}ms host=${(flatCensus.tHostMs / Math.max(1, reentries)).toFixed(3)}ms)`; post({ kind: "dmesg", level: 6, text: line }); try { console.error(line); } catch (_e) { } }; flatCensusEmit = emitFlatCensus; let flatDriveEnters = 0; const breathCensus = HWJS_BREATH_CENSUS ? { breaths: 0, sync: 0, sliceMs: 0, hostMs: 0, tRet: 0, lastSliceMs: 0, pending: false, emitted: false, refillSum: 0, refillPeak: 0, sliceMaxMs: 0, over1ms: 0, over5ms: 0, hzAlone: 0, hzQuiet: 0, hzHeld: 0 } : null; const emitBreathCensus = () => { if (!breathCensus || breathCensus.emitted) return; breathCensus.emitted = true; const b = breathCensus, n = Math.max(1, b.breaths); const line = `hwjs-breath-census pid=${ctrl[C.PID] | 0} tid=${init.tid} cpu=${init.cpuId} merged=${init.mergedCpu0Lane === true ? 1 : 0}: breaths=${b.breaths} sync=${b.sync} slow=${b.breaths - b.sync} slice_us=${(b.sliceMs * 1e3 / n).toFixed(1)} host_us=${(b.hostMs * 1e3 / n).toFixed(2)} sched_yield ended=${schedYieldEnded} in_place=${schedYieldInPlace} turn_ms=${HWJS_BREATH_TURN_MS} refill_mean=${Math.round(b.refillSum / n)} refill_peak=${b.refillPeak} slice_target_us=${HWJS_BREATH_ADAPT ? HWJS_BREATH_SLICE_US : 0} beside=${HWJS_BREATH_BESIDE ? 1 : 0} slice_max_us=${Math.round(b.sliceMaxMs * 1e3)} over_1ms=${b.over1ms} over_5ms=${b.over5ms} syscall_cuts=${breathSyscallCuts} sized_alone=${b.hzAlone} sized_beside_quiet=${b.hzQuiet} held_by_neighbour=${b.hzHeld} unit_ns=${(breathCostHi * 1e6).toFixed(3)} refill_max=${HWJS_SP_REFILL_MAX}`; post({ kind: "dmesg", level: 6, text: line }); try { console.error(line); } catch (_e) { } }; const driveCallBare = (fn2) => { const acctT0 = acctBeginSlice(); if (t67) { t67.inWasm = true; t67.lastDriveEnterT = Date.now(); } try { if (!flatCensusOn) { if (!t67) return fn2() >>> 0; const r67 = fn2() >>> 0; t67.inWasm = false; t67.lastDriveRetT = Date.now(); t67.lastStatus = r67; t67.lastStatusT = t67.lastDriveRetT; const key = "0x" + r67.toString(16); t67.statuses[key] = (t67.statuses[key] | 0) + 1; return r67; } const seq = ++flatDriveEnters; try { console.error(`hwjs-flat-drivecall #${seq} ENTER pid=${ctrl[C.PID] | 0} t=${censusNow().toFixed(0)}`); } catch (_e) { } const t0 = censusNow(); const r = fn2() >>> 0; flatCensus.tWasmMs += censusNow() - t0; flatCensus.wasmCalls++; try { console.error(`hwjs-flat-drivecall #${seq} RETURN status=0x${(r >>> 0).toString(16)} dt=${(censusNow() - t0).toFixed(0)}ms`); } catch (_e) { } return r; } finally { acctEndSlice(acctT0); } }; const driveCall = breathCensus === null ? driveCallBare : (fn2) => { const b = breathCensus, t0 = acctNow(); if (b.pending) { b.hostMs += t0 - b.tRet; b.pending = false; } const r = driveCallBare(fn2); b.tRet = acctNow(); b.lastSliceMs = b.tRet - t0; return r; }; if (typeof exp.__hwjs_drive_resume !== "function") { throw new Error( "M-FLATDRIVE: flat image (__hwjs_drive_abi()===3) without the __hwjs_drive_resume re-entry export \u2014 the F107 in-wasm driver contract is incomplete; refusing to drive blind." ); } const stwA = hwjsData("__hwjs_fork_stw"); const stwSeqA = hwjsData("__hwjs_fork_stw_seq"); const stwAckA = tcbFieldAddr("STW_ACK"); const stwMirA = tcbFieldAddr("STW_INSLICE"); const stwCapable = !!(stwA && stwSeqA && stwAckA && stwMirA && typeof exp.__hwjs_fork_barrier_ok === "function"); if (stwCapable) { stwCtl = { stwIdx: stwA >> 2, seqIdx: stwSeqA >> 2, ackIdx: stwAckA >> 2, mirIdx: stwMirA >> 2, tcb: currentTcb >>> 0 }; } else { stwCtl = null; } try { post({ kind: "dmesg", level: 7, text: `hwjs-fork-stw pid=${ctrl[C.PID] | 0} tid=${init.tid} block=0x${(currentTcb >>> 0).toString(16)} ${stwCapable ? "ARMED" : "absent"} (stw=0x${stwA.toString(16)} ack=0x${stwAckA.toString(16)} mir=0x${stwMirA.toString(16)})` }); } catch (_e) { } const stwGate = async () => { if (!stwCtl) return; const c = stwCtl; let holdT0 = 0; for (; ; ) { if (init.reapedBy) throw HWJS_TASK_REAPED; if ((Atomics.load(uI32(), c.stwIdx) | 0) === 0) { Atomics.store(uI32(), c.mirIdx, 1); if ((Atomics.load(uI32(), c.stwIdx) | 0) === 0) return; Atomics.store(uI32(), c.mirIdx, 0); } const g = Atomics.load(uI32(), c.stwIdx) | 0; if (g !== 0) { if (!holdT0) { holdT0 = Date.now(); try { post({ kind: "dmesg", level: 7, text: `hwjs-fork-stw pid=${ctrl[C.PID] | 0} block=0x${(c.tcb >>> 0).toString(16)}: slice-entry gate HELD (gen=${g})` }); } catch (_e) { } } const w = Atomics.waitAsync(uI32(), c.stwIdx, g, 250); if (w.async) { try { await w.value; } catch (_e) { } } if (holdT0 && Date.now() - holdT0 > 1e4) { holdT0 = Date.now(); const msg = `hwjs-fork-stw pid=${ctrl[C.PID] | 0} block=0x${(c.tcb >>> 0).toString(16)}: held at the slice-entry gate for >10s under generation ${g} \u2014 the forking lane's servicer has not released; still holding (loud, never silent)`; try { post({ kind: "dmesg", level: 3, text: msg }); } catch (_e) { } try { console.error(msg); } catch (_e) { } } } } }; const stwEnterSync = () => { if (!stwCtl) return true; const c = stwCtl; if ((Atomics.load(uI32(), c.stwIdx) | 0) !== 0) return false; Atomics.store(uI32(), c.mirIdx, 1); if ((Atomics.load(uI32(), c.stwIdx) | 0) === 0) return true; Atomics.store(uI32(), c.mirIdx, 0); return false; }; const stwEnterCurrent = () => { if (!stwEnterSync()) return false; if (!dlPlacementBehind()) return true; if (stwCtl) Atomics.store(uI32(), stwCtl.mirIdx, 0); return false; }; const driveSlice = (fn2) => { if (init.reapedBy) throw HWJS_TASK_REAPED; if (!stwEnterCurrent()) return driveSliceHeld(fn2); try { return driveCall(fn2); } finally { if (stwCtl) Atomics.store(uI32(), stwCtl.mirIdx, 0); } }; const driveSliceHeld = async (fn2) => { await stwGate(); if (dlPlacementBehind()) { if (stwCtl) Atomics.store(uI32(), stwCtl.mirIdx, 0); await dlPlacementCatchUp(); await stwGate(); } try { return driveCall(fn2); } finally { if (stwCtl) Atomics.store(uI32(), stwCtl.mirIdx, 0); } }; const driveDlopenCtorRunner = ({ runner, soname }) => { const fn2 = sharedTable ? sharedTable.get(runner >>> 0) : null; if (typeof fn2 !== "function" || typeof exp.__hwjs_take_parked !== "function" || typeof exp.__hwjs_drive !== "function" || typeof exp.hwjs_done !== "function") { throw new Error( `hwjs-dlopen: the constructor runner of "${soname}" (table ${runner >>> 0}) cannot be driven: ` + (typeof fn2 !== "function" ? "the slot holds no function" : "the runtime exports no __hwjs_take_parked/__hwjs_drive/hwjs_done") + " (never-silent)." ); } const chA = tcbFieldAddr("CHANNEL"); const statusChannel = !!chA && typeof exp.__hwjs_status_adopt_top === "function" && typeof exp.__hwjs_drive_adopt_parked === "function"; const start = () => driveSlice(() => { if (threadCtx) threadCtxCall(threadCtx, threadRec, () => fn2()); else fn2(); if (statusChannel) { const ch = uU32()[chA >> 2] >>> 0; if (ch === 0) return HWJS_DRIVE_DONE; if (ch !== 1) return HWJS_DRIVE_DONE_LIVE; const top2 = exp.__hwjs_status_adopt_top() >>> 0; if (exp.hwjs_done(top2) | 0) { throw new Error(`hwjs-dlopen: the constructor runner of "${soname}" parked but its adopted top is DONE (park protocol breach; never-silent).`); } return exp.__hwjs_drive_adopt_parked(); } const top = exp.__hwjs_take_parked(0, 0) >>> 0; if (top === 0 || exp.hwjs_done(top) | 0) return HWJS_DRIVE_DONE; return exp.__hwjs_drive(top); }); return driveCtorRunner({ soname, start, resume: () => driveSlice(exp.__hwjs_drive_resume), breath: serviceCooperativeBreath, clearReason: () => { uU32()[reasonAddr >> 2] = HWJS_PARK_NONE; }, wait: () => pendingCoopFutex !== null ? coopFutexParkYield("DLOPEN-CTOR") : coopWaitParkYield("DLOPEN-CTOR"), dlopen: () => serviceDlopenPark(), reason: () => uU32()[reasonAddr >> 2], progress: () => { if (typeof exp.__hwjs_progress_note === "function") exp.__hwjs_progress_note(); } }); }; const serviceDlopenPark = async () => { if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} FLAT-DLOPEN-SERVICE status=HWJS_PARK_DLOPEN pathPtr=0x${(dlopenPendingPathPtr >>> 0).toString(16)}` }); } catch (_e) { } } if (!dlopenLatched) { throw new Error( "HWJS-5: DLOPEN park without a latched SYS_wasm_dlopen \u2014 the park leaf fired outside the musl dlopen protocol" ); } dlopenLatched = false; uU32()[reasonAddr >> 2] = HWJS_PARK_NONE; const nestDepth = typeof exp.__hwjs_drive_nest_depth === "function" ? exp.__hwjs_drive_nest_depth() >>> 0 : -1; const dlPlacement = await dlPlacementBegin(); let dlret; dlopenCtorRunners = []; try { dlret = await driveExecLoadWithYield({ load: () => serviceDlopen( dlopenPendingPathPtr | 0, /* yieldWouldBlock */ true, dlopenPendingReissue, dlopenPendingLoaded ), yieldTurn: () => coopWaitParkYield("DLOPEN-LOAD park service"), onYield: () => { if (SCHED_TRACE) { schedTrace(post, `YIELD cpu=${init.cpuId ?? "?"} tid=${init.tid} reason=DLOPEN-LOAD-park site=dlopen-park-service via=wake-word`); } } }); } catch (e) { const cls = classifyDlopenFailure(e); const allocAttribution = cls.cls === "alloc" ? ` | #70 per-Worker so-module accounting: ` + soModuleCacheStats() : ""; dlopenLastError = `[${cls.cls} -> ${cls.errnoName}] ${cls.message}` + allocAttribution; const report = `HWJS-5 dlopen service failed (${cls.cls} -> ${cls.errnoName} ${cls.errno}): ${cls.message}` + allocAttribution; post({ kind: "user-report", pid: init.pid, message: report }); try { console.error(`[hwjs-dlopen pid=${init.pid}] ${report}`); } catch (_e2) { } dlret = cls.errno | 0; if (nestDepth >= 0) exp.__hwjs_drive_nest_unwind_to(nestDepth); uU32()[reasonAddr >> 2] = HWJS_PARK_NONE; } const ctorRunners = dlopenCtorRunners; dlopenCtorRunners = null; const dlPlacementGen = dlPlacementEnd(dlPlacement, "dlopen"); dlopenPendingPathPtr = 0; dlopenPendingReissue = false; dlopenPendingLoaded = false; hwjsSliceProgressed = true; await dlPlacementBarrier(dlPlacementGen); for (const r of ctorRunners) await driveDlopenCtorRunner(r); uU32()[resultAddr >> 2] = dlret | 0; }; const dlPlacementBarrier = async (gen) => { if (!gen || !stwCtl || !tcbLayout) return; const rtx = runtimeExports || exp; const waiting = /* @__PURE__ */ new Set(); for (const t of listThreadBlocks(rtx)) { if (t >>> 0 !== currentTcb >>> 0) waiting.add(t >>> 0); } const t0 = Date.now(); while (waiting.size) { for (const t of waiting) { if ((Atomics.load(uI32(), t + tcbLayout.STW_INSLICE >> 2) | 0) === 0) { waiting.delete(t); } } if (!waiting.size) break; if (Date.now() - t0 > 2e3) { const ids = [...waiting].map((t) => uU32()[t + tcbLayout.ID >> 2] >>> 0); try { post({ kind: "dmesg", level: 4, text: `hwjs-dl-placement pid=${ctrl[C.PID] | 0} tid=${init.tid | 0}: dlopen generation ${gen} returns while thread(s) ${ids.join(",")} are still inside one slice; each catches up at its next slice entry` }); } catch (_e) { } break; } await new Promise((r) => setTimeout(r, 2)); } }; const stwGateSync = () => { if (!stwCtl) return; const c = stwCtl; for (; ; ) { if ((Atomics.load(uI32(), c.stwIdx) | 0) === 0) { Atomics.store(uI32(), c.mirIdx, 1); if ((Atomics.load(uI32(), c.stwIdx) | 0) === 0) return; Atomics.store(uI32(), c.mirIdx, 0); } const g = Atomics.load(uI32(), c.stwIdx) | 0; if (g !== 0) Atomics.wait(uI32(), c.stwIdx, g, 250); } }; const stwMirrorClear = () => { if (stwCtl) Atomics.store(uI32(), stwCtl.mirIdx, 0); }; const doneTerminusDispatchOff = typeof process !== "undefined" && process.env && process.env.HWJS_NO_DONE_TERMINUS_DISPATCH === "1"; const dispatchDoneLive = () => { stwGateSync(); try { return dispatchDoneLiveInner(); } finally { stwMirrorClear(); } }; const dispatchDoneLiveInner = () => { const chA = tcbFieldAddr("CHANNEL"); const chSt = chA ? uU32()[chA >> 2] >>> 0 : 0; const refuse3 = (why) => { const line = `drive DONE_TOP with live status ${chSt} \u2014 ${why}`; try { post({ kind: "dmesg", level: 3, text: `[hwjs-\xA74-terminus pid=${ctrl[C.PID] | 0}] ${line}` }); } catch (_e) { } throw new Error(`M-FLATDRIVE \xA74 terminus: ${line}`); }; if (!chA) refuse3("the driver returned HWJS_DRIVE_DONE_LIVE but no user-runtime block is bound for this thread \u2014 drive-status/channel contract skew"); if (chSt === 2) { if (doneTerminusDispatchOff) refuse3("an uncaught exception completed under the driver and the \xA74 dispatch is DISABLED (HWJS_NO_DONE_TERMINUS_DISPATCH=1, RED arm) \u2014 refusing rather than reporting a clean DONE"); if (typeof exp.__hwjs_uncaught_unwinding !== "function") refuse3("no __hwjs_uncaught_unwinding export to consume it (the RT weak fallback is part of the abi-4 export surface \u2014 its absence is a link/manifest defect)"); const exc = uU32()[chA + 8 >> 2] >>> 0; exp.__hwjs_uncaught_unwinding(exc); const chSt2 = uU32()[chA >> 2] >>> 0; if (chSt2 === 1 && typeof exp.__hwjs_status_adopt_top === "function" && typeof exp.__hwjs_drive_adopt_parked === "function") { const top = exp.__hwjs_status_adopt_top() >>> 0; if (exp.hwjs_done(top) | 0) refuse3("the terminus chain parked but its adopted top is DONE (park protocol breach)"); return exp.__hwjs_drive_adopt_parked() >>> 0; } refuse3(`__hwjs_uncaught_unwinding RETURNED without terminating the process and without a parked channel \u2014 the hook must terminate or park (channel now ${chSt2})`); } if (chSt === 3) { if (typeof exp.__hwjs_status_longjmp_lost === "function") exp.__hwjs_status_longjmp_lost(); refuse3("longjmp target not found (dead, stale, or foreign jmp_buf) and no __hwjs_status_longjmp_lost export to report it faithfully"); } refuse3("not a \xA74 terminus row (NORMAL/PARKED/corrupt channel word arrived with HWJS_DRIVE_DONE_LIVE \u2014 the RT consumes PARKED on its PARK leg and violates in-loop on a parked DONE, so this is drive-protocol skew)"); }; const threadLaneTeardown = () => { stwGateSync(); try { threadLaneTeardownInner(); } finally { stwMirrorClear(); } }; const threadLaneTeardownInner = () => { threadChainTop = 0; uU32()[reasonAddr >> 2] = HWJS_PARK_NONE; if (typeof exp.__hwjs_thread_arena_reset === "function") { try { exp.__hwjs_thread_arena_reset(); } catch (e) { post({ kind: "user-report", pid: init.pid, message: `thread block 0x${(currentTcb >>> 0).toString(16)} arena reset REFUSED at terminus (${e instanceof Error ? e.message : String(e)}) \u2014 the chain was mid-flight, not at a clean terminus (never silent)` }); } } const liveA = tcbFieldAddr("FRAME_LIVE"); const live2 = liveA ? uU32()[liveA >> 2] >>> 0 : 0; if (typeof process !== "undefined" && process.env && process.env.HWJS_ARENA_CENSUS) { const hwA = tcbFieldAddr("FRAME_HIGH_WATER"); const allocA = tcbFieldAddr("FRAME_ALLOCS"); post({ kind: "user-report", pid: init.pid, message: `hwjs-arena-census block 0x${(currentTcb >>> 0).toString(16)} peak bump-committed ${hwA ? uU32()[hwA >> 2] >>> 0 : 0} B in ${allocA ? uU32()[allocA >> 2] >>> 0 : 0} allocs (this thread's whole life; the bootstrap slice is what has to cover it before the first mmap)` }); } if (live2 !== 0) { post({ kind: "user-report", pid: init.pid, message: `thread block 0x${(currentTcb >>> 0).toString(16)} terminus with ${live2} live arena frame(s) after reclaim \u2014 a genuine per-thread leak (the detach below refuses; the block stays attached, loudly; never silent)` }); } try { const { errno } = tcbResult(exp.__hwjs_thread_detach()); if (errno === 0) { currentTcb = 0; } else if (errno === TCB_EBUSY) { void releaseThreadBlock("thread exit (registry busy at terminus)"); } else { post({ kind: "user-report", pid: init.pid, message: `thread block detach at terminus returned -${errno} (loud, attributed)` }); } } catch (e) { post({ kind: "user-report", pid: init.pid, message: `thread block 0x${(currentTcb >>> 0).toString(16)} detach REFUSED at terminus (${e instanceof Error ? e.message : String(e)}) \u2014 the block stays attached (loud, attributed)` }); } }; const leaderHoldUntilGroupEmpty = async () => { Atomics.store(ctrl, C.LEADER_HOLD, 0); uU32()[reasonAddr >> 2] = HWJS_PARK_NONE; if (typeof exp.__hwjs_thread_arena_reset === "function") { stwGateSync(); try { exp.__hwjs_thread_arena_reset(); } catch (e) { try { post({ kind: "dmesg", level: 3, text: `hwjs-threads pid=${ctrl[C.PID] | 0}: the held leader's block 0x${(currentTcb >>> 0).toString(16)} arena reset REFUSED (${e instanceof Error ? e.message : String(e)}) \u2014 a sibling's fork may be refused EAGAIN while it is held` }); } catch (_e) { } } finally { stwMirrorClear(); } } if (mainClearTid !== 0 && (mainClearTid & 3) === 0) { try { Atomics.store(uI32(), mainClearTid >>> 2, 0); Atomics.notify(uI32(), mainClearTid >>> 2); } catch (e) { try { post({ kind: "dmesg", level: 3, text: `hwjs-threads pid=${ctrl[C.PID] | 0}: the held leader's clear_child_tid 0x${mainClearTid.toString(16)} could not be cleared (${e instanceof Error ? e.message : String(e)}) \u2014 a thread waiting on it stays waiting` }); } catch (_e) { } } } const t0 = Date.now(); post({ kind: "leader-hold", pid: init.pid }); let said = false; const LEADER_HOLD_KILL_GRACE_MS = 1e3; const leaderKillPending = () => signalPendingIdx >= 0 && ((Atomics.load(uI32(), signalPendingIdx) | 0) & 1 << 9 - 1) !== 0; let killSeen = 0; let killEnded = false; while (Atomics.load(ctrl, C.LEADER_HOLD) === 0) { if (init.reapedBy) throw HWJS_TASK_REAPED; if (leaderKillPending()) { if (killSeen === 0) killSeen = Date.now(); else if (Date.now() - killSeen >= LEADER_HOLD_KILL_GRACE_MS) { killEnded = true; try { post({ kind: "dmesg", level: 4, text: `hwjs-threads pid=${ctrl[C.PID] | 0}: the held leader has had SIGKILL pending ${Date.now() - killSeen} ms and its group is not empty \u2014 ending the hold; the process completes as before the hold (its other threads are killed by the host)` }); } catch (_e) { } break; } } const w = Atomics.waitAsync(ctrl, C.LEADER_HOLD, 0, killSeen ? 100 : 1e3); if (w.async) await w.value; if (!said && Date.now() - t0 >= 1e4) { said = true; try { post({ kind: "dmesg", level: 6, text: `hwjs-threads pid=${ctrl[C.PID] | 0}: main thread exited 10 s ago and the process is still held for its other threads (Linux keeps it alive until the last one ends)` }); } catch (_e) { } } } const g = decideGroupExit(0, 0); let codeArg = 0; let signaled = 0; if (g) { if ((g.wstatus & 127) === 0) codeArg = g.wstatus >> 8 & 255; else { codeArg = g.wstatus & 127; signaled = 1; } } exitCode = codeArg; if (Date.now() - t0 >= 1e4 || codeArg !== 0 || killEnded) { try { post({ kind: "dmesg", level: 6, text: `hwjs-threads pid=${ctrl[C.PID] | 0}: held leader released after ${Date.now() - t0} ms, ${killEnded ? "on its SIGKILL" : "the group empty"}; status ${signaled ? `WIFSIGNALED ${codeArg}` : `WIFEXITED ${codeArg}`}${g ? "" : " (the kernel was not asked)"}` }); } catch (_e) { } } pendingExitTerminus = { codeArg, signaled, grpExit: g }; await runExitTerminus(); }; if (t67) { t67.reasonAddr = reasonAddr; t67.resultAddr = resultAddr; if (t67.timer) clearInterval(t67.timer); t67.timer = setInterval(() => { if (exitPosted) { clearInterval(t67.timer); t67.timer = null; return; } t67Sample("SAMPLE"); }, 1e4); if (typeof t67.timer.unref === "function") t67.timer.unref(); } let status; const A4CDBG = typeof process !== "undefined" && process.env && process.env.A4C_FORKDBG; const fdbg = (s) => { if (A4CDBG) { try { post({ kind: "dmesg", level: 6, text: `[a4c-fork tid=${init.tid} mode=${init.mode}] ${s}` }); } catch (_e) { } } }; try { if (init.mode === "migrate-resume" && firstImage) { fdbg(`FLAT migrate-resume entry: binding tls/sp on cpu=${init.cpuId | 0} (block=0x${(currentTcb >>> 0).toString(16)} task=0x${(init.migrateTaskAddr >>> 0).toString(16)})`); if (typeof init.tlsBase === "number" && typeof exp.__wasm32_set_tls_base === "function") { if (!bindTaskTlsBase(init.tlsBase, continuingMainTlsBlock(), false)) { throw new Error( `migrate-resume: no main-image TLS block for this task \u2014 refusing to resume with the main's __tls_base unbound (never-silent).` ); } } if (typeof init.sp === "number" && init.sp !== 0 && typeof exp.__wasm32_set_stack_pointer === "function") { exp.__wasm32_set_stack_pointer(init.sp >>> 0); } if (hwjsRtStackPointer && typeof init.sideSpTop === "number" && init.sideSpTop !== 0) { threadSideSpTop = init.sideSpTop >>> 0; hwjsRtStackPointer.value = init.sideSp >>> 0 | 0; } const staleReason = uU32()[reasonAddr >> 2] >>> 0; if (staleReason !== HWJS_PARK_NONE) { throw new Error( `migrate-resume: arrived with a PENDING park reason ${staleReason} \u2014 the source offers only from a serviced park, where the slot is already clear (never-silent)` ); } if (init.wasmJit) { const carried = init.wasmJit; init.wasmJit = void 0; const placed = wasmJit.migrateIn(carried); try { post({ kind: "dmesg", level: 6, text: `hwjs-migrate pid=${ctrl[C.PID] | 0}: wasm_jit record re-placed on cpu=${init.cpuId | 0}: ${placed}` }); } catch (_e) { } } if (!migrateCommit()) { throw new Error( "migrate-resume: the offer was already terminal when this destination finished binding (the source or the host aborted it first) \u2014 dropping the placement without driving; the task is the source's" ); } migrateRetag(init.migrateSrcCpu, init.cpuId | 0); schedTrace(post, `MIGRATE-IN cpu=${init.cpuId | 0} tid=${init.tid} pid=${ctrl[C.PID] | 0} block=0x${(currentTcb >>> 0).toString(16)}`); status = await driveSlice(exp.__hwjs_drive_resume); fdbg(`AFTER driveCall(__hwjs_drive_resume) [migrate] status=0x${(status >>> 0).toString(16)}`); } else if (init.mode === "fork-resume" && firstImage) { fdbg(`FLAT fork-resume entry: setting tls/sp, result=0 (block=0x${(currentTcb >>> 0).toString(16)} stwCapable=${stwCapable ? 1 : 0})`); if (typeof init.tlsBase === "number" && typeof exp.__wasm32_set_tls_base === "function") { bindTaskTlsBase(init.tlsBase, continuingMainTlsBlock(), false); } if (typeof init.parentSp === "number" && init.parentSp !== 0 && typeof exp.__wasm32_set_stack_pointer === "function") { exp.__wasm32_set_stack_pointer(init.parentSp >>> 0); } const staleReason = uU32()[reasonAddr >> 2] >>> 0; if (staleReason !== HWJS_PARK_NONE) { throw new Error( `M-FLATDRIVE: fork-resume child copied a PENDING park reason ${staleReason} \u2014 the parent clears the reason before the delta=0 copy by contract` ); } if (currentTcb) { const rtx = runtimeExports || exp; if (typeof rtx.__hwjs_fork_child_collapse !== "function") { throw new Error( "fork-resume child: image with per-thread runtime blocks but without __hwjs_fork_child_collapse \u2014 skewed RT/artifact pair; refusing to resume over ghost threads and a registry lock the parent held across the copy (never-silent)." ); } rtx.__hwjs_fork_child_collapse(); } uU32()[resultAddr >> 2] = 0; fdbg("BEFORE driveCall(__hwjs_drive_resume) [fork-resume initial]"); status = await driveSlice(exp.__hwjs_drive_resume); fdbg(`AFTER driveCall(__hwjs_drive_resume) RETURNED status=0x${(status >>> 0).toString(16)}`); } else if (threadLanePending) { fdbg(`THREAD block=0x${(currentTcb >>> 0).toString(16)} entry: __wasm32_user_entry ramp`); if (DEBUG_K7_U4F) { try { post({ kind: "dmesg", level: 6, text: `[thr tid=${init.tid} block=0x${(currentTcb >>> 0).toString(16)}] pump entry: calling __wasm32_user_entry(0x${(init.argRegionOffset >>> 0).toString(16)})` }); } catch (_e) { } } await driveSlice(() => { exp.__wasm32_user_entry(init.argRegionOffset | 0); return 0; }); if (DEBUG_K7_U4F) { try { post({ kind: "dmesg", level: 6, text: `[thr-lane tid=${init.tid}] entry returned; exitPosted=${exitPosted}` }); } catch (_e) { } } if (exitPosted) { threadLaneTeardown(); return; } const thrChA = tcbFieldAddr("CHANNEL"); const thrChSt = uU32()[thrChA >> 2] >>> 0; fdbg(`THREAD entry channel status=${thrChSt}`); if (thrChSt === 0) { threadLaneTeardown(); break; } if (thrChSt !== 1) { throw new Error( `thread lane entry: channel status ${thrChSt} after entry (not NORMAL/PARKED) \u2014 drive-status protocol skew.` ); } if (typeof exp.__hwjs_status_adopt_top !== "function") { throw new Error( "thread lane entry: parked channel but no __hwjs_status_adopt_top export (abi4 surface defect)." ); } const thrTop = exp.__hwjs_status_adopt_top() >>> 0; if (exp.hwjs_done(thrTop) | 0) { throw new Error( "thread lane entry: parked channel but the adopted top is DONE (park protocol breach; never-silent)." ); } threadChainTop = thrTop; status = await driveSlice(exp.__hwjs_drive_adopt_parked); fdbg(`THREAD adopt status=0x${(status >>> 0).toString(16)}`); } else { fdbg("BEFORE driveCall(_start) [fresh]"); status = await driveSlice(exp._start); fdbg(`AFTER driveCall(_start) RETURNED status=0x${(status >>> 0).toString(16)}`); } post({ kind: "hwjs-host-drive-flat", pid: init.pid }); const breathSyncCapable = typeof exp.__hwjs_budget_set === "function" && !HWJS_NO_SP_YIELD && HWJS_BREATH_TURN_MS > 0 && init.mergedCpu0Lane !== true && !flatCensusOn; let breathTurnT = acctNow(); breathRefill = HWJS_SP_REFILL; breathCostHi = 0; breathCostPrev = Infinity; breathSampleUnits = 0; for (; ; ) { if (exitPosted) { emitFlatCensus("exit_group"); return; } if (status === HWJS_DRIVE_DONE_LIVE) { status = dispatchDoneLive() >>> 0; } if (status !== HWJS_PARK_RESCHED) coopWaitEpisodeReset(); if (status === HWJS_DRIVE_DONE) { flatCensus.DONE++; if (threadLanePending) threadLaneTeardown(); break; } if (status === HWJS_PARK_THREAD_EXIT) { if (!threadLanePending && !init.rtThread) { if (init.leaderHold === 1 && vmlinuxInstance && perProcessTaskAddr !== 0) { await leaderHoldUntilGroupEmpty(); break; } try { post({ kind: "dmesg", level: 4, text: `hwjs-threads pid=${ctrl[C.PID] | 0}: pthread_exit from the MAIN thread on a host that cannot hold the leader (no leaderHold in the spawn, or no kernel task) \u2014 treating as process completion; siblings are NOT awaited` }); } catch (_e) { } } if (threadLanePending) threadLaneTeardown(); exitCode = 0; break; } const flatHostT0 = flatCensusOn ? censusNow() : 0; if (status === HWJS_PARK_FORK && hwjsVforkLatched) { flatCensus.FORK++; const vreq = hwjsVforkLatched; hwjsVforkLatched = null; uU32()[reasonAddr >> 2] = HWJS_PARK_NONE; uU32()[resultAddr >> 2] = await requestVforkChild(vreq) | 0; hwjsSliceProgressed = true; } else if (status === HWJS_PARK_FORK) { flatCensus.FORK++; if (!hwjsForkLatched) { throw new Error( "M-FLATDRIVE: FORK park without a latched SYS_fork \u2014 the park leaf fired outside the musl _Fork protocol" ); } hwjsForkLatched = false; if (typeof exp.__hwjs_fork_barrier_ok !== "function") { throw new Error( "M-FLATDRIVE fork latch: coro image lacks __hwjs_fork_barrier_ok \u2014 refusing the delta=0 copy without the structural barrier predicate (ADR-0004 F87 conf (4))" ); } uU32()[reasonAddr >> 2] = HWJS_PARK_NONE; const redNoQuiesce = stwCapable && typeof process !== "undefined" && process.env && process.env.HWJS_RED_FORK_NO_ALLLANE_QUIESCE === "1"; let stwHeld = false; let barrierHeld = false; const barrierRelease = () => { if (!barrierHeld) return; barrierHeld = false; exp.__hwjs_fork_barrier_release(); }; const stwRelease = () => { if (!stwHeld) return; stwHeld = false; Atomics.store(uI32(), stwCtl.stwIdx, 0); Atomics.notify(uI32(), stwCtl.stwIdx); }; const rtx = runtimeExports || exp; const tcbById = (id) => { for (const t of listThreadBlocks(rtx)) { if (uU32()[t + tcbLayout.ID >> 2] >>> 0 === id >>> 0) return t; } return 0; }; const tcbState = (t) => { if (!t) return "{gone}"; const at = (f) => t + tcbLayout[f] >> 2; return `{mir=${Atomics.load(uI32(), at("STW_INSLICE")) | 0} ack=${Atomics.load(uI32(), at("STW_ACK")) | 0} rsn=${uU32()[at("PARK_REASON")] >>> 0} pk=0x${(uU32()[at("PARKED")] >>> 0).toString(16)} st=${uU32()[at("CHANNEL")] >>> 0}}`; }; const forkRefuseEagain = (why) => { let dump = ""; try { const parts = []; let more = 0; for (const t of listThreadBlocks(rtx)) { const at = (f) => t + tcbLayout[f] >> 2; const busy = Atomics.load(uI32(), at("STW_INSLICE")) | 0 || Atomics.load(uI32(), at("STW_ACK")) | 0 || uU32()[at("PARK_REASON")] >>> 0 || uU32()[at("PARKED")] >>> 0 || uU32()[at("CHANNEL")] >>> 0; if (!busy) continue; if (parts.length >= 16) { more++; continue; } parts.push(`T${uU32()[at("ID")] >>> 0}${tcbState(t)}`); } if (more) parts.push(`(+${more} more)`); dump = parts.length ? ` [${parts.join(" ")}]` : " [all-clear]"; if (typeof rtx.__hwjs_fork_barrier_why === "function") { const w = rtx.__hwjs_fork_barrier_why() >>> 0; const CL = [ "quiesced", "mid-drive-unmirrored", "mid-drive-no-ack", "parked-slot", "lj-active", "park-reason", "xfer-pending", "status-non-normal", "registry-busy" ]; dump += ` why=thread${w >>> 8}:${CL[w & 255] ?? w & 255}`; } } catch (_e) { dump = " [dump-failed]"; } const msg = `hwjs-fork-stw pid=${ctrl[C.PID] | 0} tid=${init.tid | 0}: fork REFUSED with EAGAIN \u2014 ${why}${dump} (loud, attributed, POSIX-legal; the guest's fork() observes -EAGAIN and lives \u2014 plan \xA73 I1)`; try { post({ kind: "dmesg", level: 3, text: msg }); } catch (_e) { } try { post({ kind: "user-report", pid: init.pid, message: msg }); } catch (_e) { } try { console.error(msg); } catch (_e) { } uU32()[resultAddr >> 2] = -11 | 0; }; let forkProceed = true; if (redNoQuiesce) { try { post({ kind: "dmesg", level: 4, text: `hwjs-fork-stw pid=${ctrl[C.PID] | 0} tid=${init.tid | 0}: RED_NOQUIESCE \u2014 calling-thread-only fork barrier; the delta=0 copy will race live sibling threads (test knob)` }); } catch (_e) { } } else if (stwCapable) { const STW_ACQUIRE_MS = 1e4; const stwAcquire = async (deadline) => { for (; ; ) { const g = Atomics.add(uI32(), stwCtl.seqIdx, 1) + 1 | 0; if (Atomics.compareExchange(uI32(), stwCtl.stwIdx, 0, g === 0 ? 1 : g) === 0) { stwHeld = true; return true; } if (Date.now() > deadline) return false; const cur = Atomics.load(uI32(), stwCtl.stwIdx) | 0; if (cur !== 0) { const w = Atomics.waitAsync(uI32(), stwCtl.stwIdx, cur, 100); if (w.async) { try { await w.value; } catch (_e) { } } } } }; await stwAcquire(Date.now() + STW_ACQUIRE_MS); if (!stwHeld) { forkRefuseEagain( `could not acquire the fork stop-the-world word within ${STW_ACQUIRE_MS} ms (another thread's fork service is holding it)` ); forkProceed = false; } else { let barrier = 0; let whyTrail = ""; const whyNow = () => typeof exp.__hwjs_fork_barrier_why === "function" ? exp.__hwjs_fork_barrier_why() >>> 0 : 65535; const dl = Date.now() + STW_ACQUIRE_MS; let polls = 0; const FORK_BACKOFF_MS = HWJS_FORK_BACKOFF_MS; let stuckWhy = 0; let stuckSince = 0; let backoffs = 0; for (; ; ) { barrier = exp.__hwjs_fork_barrier_ok() | 0; if (barrier === 1) { barrierHeld = true; break; } if (polls === 0 || polls % 500 === 250) { const w = whyNow(); whyTrail += ` @${polls}:0x${w.toString(16)}` + ((w & 255) === 8 ? "{registry-busy}" : tcbState(tcbById(w >>> 8))); } polls++; if (Date.now() > dl) break; const why = whyNow(); if (FORK_BACKOFF_MS > 0 && (why & 255) === 3) { if (why !== stuckWhy) { stuckWhy = why; stuckSince = Date.now(); } else if (Date.now() - stuckSince >= FORK_BACKOFF_MS) { const t = tcbById(why >>> 8); stwRelease(); const letIn = Math.min(dl, Date.now() + FORK_BACKOFF_MS); while (t && Date.now() < letIn && uU32()[t + tcbLayout.PARKED >> 2] >>> 0 !== 0 && (Atomics.load(uI32(), t + tcbLayout.STW_INSLICE >> 2) | 0) === 0) { await new Promise((res) => setTimeout(res, 1)); } backoffs++; stuckWhy = 0; if (!await stwAcquire(dl)) break; continue; } } else { stuckWhy = 0; } await new Promise((res) => setTimeout(res, 2)); } if (barrier === 1 && backoffs > 0) { try { post({ kind: "dmesg", level: 6, text: `hwjs-fork-stw pid=${ctrl[C.PID] | 0} tid=${init.tid | 0}: quiesced after ${backoffs} back-off(s) for a parked-slot thread` }); } catch (_e) { } } if (barrier !== 1) { whyTrail += ` @final:0x${whyNow().toString(16)}(b=${barrier}) backoffs=${backoffs}`; stwRelease(); forkRefuseEagain( `the all-lanes fork barrier did not reach quiesce within ${STW_ACQUIRE_MS} ms whyTrail[thread:clause]:${whyTrail} (__hwjs_fork_barrier_ok=${barrier}: ${barrier === -1 ? "a thread is mid-slice and not host-held" : "a thread holds in-flight protocol state, or an attach/detach held the registry"})` ); forkProceed = false; } } } else { const barrier = exp.__hwjs_fork_barrier_ok() | 0; if (barrier === 1) barrierHeld = true; if (barrier !== 1) { throw new Error( `M-FLATDRIVE fork latch ${barrier === -1 ? "REFUSED" : "not quiesced"}: __hwjs_fork_barrier_ok=${barrier} \u2014 the delta=0 whole-memory copy is a whole-arena predicate, legal at barrier-quiesce only (ADR-0004 F87 conf (4))` ); } } if (forkProceed) { try { const childPid = await requestForkChild({ handle: 0, owner: 0 }); uU32()[resultAddr >> 2] = childPid | 0; } catch (e) { if (e === HWJS_TASK_REAPED) throw e; if (!stwCapable) { barrierRelease(); stwRelease(); throw e; } forkRefuseEagain( `fork service failed: ${e instanceof Error ? e.message : String(e)}` ); } finally { barrierRelease(); stwRelease(); } } hwjsSliceProgressed = true; } else if (status === HWJS_PARK_EXEC) { flatCensus.EXEC++; if (D1_TRACE_SYS) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${ctrl[C.PID] | 0} FLAT-EXEC-SERVICE status=HWJS_PARK_EXEC path="${execPendingPath}"` }); } catch (_e) { } } if (!hwjsExecLatched) { throw new Error( "M-FLATDRIVE: EXEC park without a latched SYS_execve \u2014 the park leaf fired outside the musl execve protocol" ); } hwjsExecLatched = false; const res = await requestExecImage( execPendingPath, execPendingPathPtr ); const execRequestedPath = execPendingPath; execPendingPath = null; execPendingPathPtr = 0; if (res && res.ok && res.wasmBytes) { if (flatCensusOn) flatCensus.tHostMs += censusNow() - flatHostT0; emitFlatCensus("execve"); execNextBytes = res.wasmBytes; execInstalledPath = execRequestedPath; break; } uU32()[reasonAddr >> 2] = HWJS_PARK_NONE; uU32()[resultAddr >> 2] = res && typeof res.errno === "number" ? res.errno | 0 : -2; hwjsSliceProgressed = true; } else if (status === HWJS_PARK_DLOPEN) { await serviceDlopenPark(); } else if (status === HWJS_PARK_NONE || status === HWJS_PARK_PREEMPT) { const breath = flatBreathOf(status, uU32()[reasonAddr >> 2] >>> 0); const preempt = breath.preempt; if (preempt) flatCensus.PREEMPT++; else flatCensus.NONE++; hwjsCoopBreaths++; if (breathCensus) { breathCensus.breaths++; breathCensus.sliceMs += breathCensus.lastSliceMs; breathCensus.pending = true; breathCensus.refillSum += breathRefill; if (breathRefill > breathCensus.refillPeak) breathCensus.refillPeak = breathRefill; const lm = breathCensus.lastSliceMs; if (lm > breathCensus.sliceMaxMs) breathCensus.sliceMaxMs = lm; if (lm > 1) breathCensus.over1ms++; if (lm > 5) breathCensus.over5ms++; } republishSignals(); if (breathSampleUnits > 0) { if (HWJS_BREATH_ADAPT && acctSliceSeq === breathSampleSeq + 1 && acctLastSliceMs > 0) { const units = breathSampleUnits; const spent = breathCutSeq !== breathSampleCut && breathCutLeft > 0 && breathCutLeft < units ? units - breathCutLeft : units; const sample = acctLastSliceMs / spent; breathCostHi = nextBreathCost( breathCostHi, breathCostPrev, sample, acctLastSliceEnd - breathCostT, BREATH_COST_HALF_MS ); breathCostPrev = sample; breathCostT = acctLastSliceEnd; } breathSampleUnits = 0; } const breathAlone = breathSyncCapable && (preempt || !deliverableSignalPending()) && !isPaused(pauseArr) && !laneOthersRunnable(laneRec); breathRefill = breathAlone && HWJS_BREATH_ADAPT ? aloneBreathRefill(acctLastSliceEnd) : HWJS_SP_REFILL; if (breathCensus && breathAlone && HWJS_BREATH_ADAPT) { if (laneResidents.size <= 1) breathCensus.hzAlone++; else if (othersSliceHorizonIn( laneResidents, laneRec, acctLastSliceEnd, BREATH_TARGET_MS, BREATH_SHARE_FRAC, HWJS_BREATH_BESIDE ) > 0) breathCensus.hzQuiet++; else breathCensus.hzHeld++; } if (breathAlone && acctLastSliceEnd - breathTurnT < HWJS_BREATH_TURN_MS && stwEnterCurrent()) { try { refillBreathBudget(); if (typeof exp.__hwjs_progress_note === "function") exp.__hwjs_progress_note(); if (breathCensus) breathCensus.sync++; status = driveCall(exp.__hwjs_drive_resume); } finally { stwMirrorClear(); } continue; } if (await serviceCooperativeBreath()) hwjsSliceProgressed = true; breathTurnT = acctNow(); if (breathRefill !== HWJS_SP_REFILL) { const r = laneOthersRunnable(laneRec) ? HWJS_SP_REFILL : aloneBreathRefill(breathTurnT); if (r < breathRefill) { breathRefill = r; refillBreathBudget(); } } const breathDispatch = typeof exp.__wasm_signal_dispatch_pending === "function" ? (() => exp.__wasm_signal_dispatch_pending()) : typeof exp.__wasm32_signal_dispatch_restart === "function" ? (() => exp.__wasm32_signal_dispatch_restart(0)) : null; if (breathTakesLegacyDispatch(breath, signalPending, breathDispatch) && typeof exp.__hwjs_take_parked === "function" && typeof exp.__hwjs_drive === "function") { const sigParkedA = tcbFieldAddr("PARKED"); breathDispatchActive = true; try { await driveSlice(() => { let st = HWJS_DRIVE_DONE; try { breathDispatch(); const sigTop = sigParkedA ? uU32()[sigParkedA >> 2] >>> 0 : 0; if (sigTop !== 0) { const adopted = exp.__hwjs_take_parked(0, 0) >>> 0; st = exp.__hwjs_drive(adopted) >>> 0; } } finally { breathDispatchActive = false; } if (st !== HWJS_DRIVE_DONE) { throw new Error( "M-FLATDRIVE breath-dispatch: the libc signal-dispatch trampoline PARKED (status 0x" + st.toString(16) + ") instead of completing \u2014 a signal handler blocked at the breath delivery point, which would corrupt the parked main chain. Refusing to continue this task." ); } return 0; }); } finally { breathDispatchActive = false; } hwjsSliceProgressed = true; } } else if (status === HWJS_PARK_RESCHED) { flatCensus.RESCHED++; uU32()[reasonAddr >> 2] = HWJS_PARK_NONE; if (vmlinuxInstance && typeof vmlinuxInstance.exports.__wasm32_migrate_pending === "function") { let want = 0; try { want = vmlinuxInstance.exports.__wasm32_migrate_pending() >>> 0; } catch (_e) { want = 0; } if (want > 0) { const destCpu = want - 1 | 0; if (destCpu === (init.cpuId | 0)) { } else if (await requestMigrate(destCpu)) { migratedAway = true; break; } } } const yT0 = SCHED_TRACE ? schedNow() : 0; schedTrace(post, `YIELD cpu=${init.cpuId ?? "?"} tid=${init.tid} reason=RESCHED-park site=flat-drive via=${pendingCoopFutex !== null ? "coop-futex" : "wake-word"}`); if (pendingCoopFutex !== null) await coopFutexParkYield("M-FLATDRIVE"); else await coopWaitParkYield("M-FLATDRIVE"); breathTurnT = acctNow(); if (SCHED_TRACE) { schedTrace(post, `RESUME cpu=${init.cpuId ?? "?"} tid=${init.tid} site=flat-drive waited=${(schedNow() - yT0).toFixed(1)}ms`); } hwjsSliceProgressed = true; } else { flatCensus.other++; try { const parkedA = tcbFieldAddr("PARKED"); post({ kind: "dmesg", level: 6, text: `[a4d-diag] unexpected status=0x${(status >>> 0).toString(16)} reasonSlot=0x${(uU32()[reasonAddr >> 2] >>> 0).toString(16)} resultSlot=0x${(uU32()[resultAddr >> 2] >>> 0).toString(16)} parked=0x${(parkedA ? uU32()[parkedA >> 2] >>> 0 : 0).toString(16)} budget=${typeof exp.__hwjs_budget_get === "function" ? exp.__hwjs_budget_get() : "n/a"}` }); } catch (_e) { } throw unknownFlatDriveStatus(status); } if (hwjsSliceProgressed) { if (typeof exp.__hwjs_progress_note === "function") exp.__hwjs_progress_note(); hwjsSliceProgressed = false; } if (flatCensusOn) flatCensus.tHostMs += censusNow() - flatHostT0; if (isPaused(pauseArr)) await slicePause(); if (A4CDBG) fdbg(`BEFORE re-drive driveCall(__hwjs_drive_resume) [loop]`); status = await driveSlice(exp.__hwjs_drive_resume); if (A4CDBG) fdbg(`AFTER re-drive RETURNED status=0x${(status >>> 0).toString(16)}`); } } finally { emitFlatCensus("flat-drive-end"); emitBreathCensus(); breathRefill = HWJS_SP_REFILL; } if (migratedAway) { wasmJitRelease(); try { post({ kind: "dmesg", level: 6, text: `hwjs-migrate pid=${ctrl[C.PID] | 0}: released by cpu=${init.cpuId | 0} after the destination committed \u2014 this Worker stops driving the task and runs NO exit path (the process is alive on another lane)` }); } catch (_e) { } return; } } else { const parkedAddr = tcbFieldAddr("PARKED"); const ownerAddr = tcbFieldAddr("PARKED_OWNER"); const reasonAddr = tcbFieldAddr("PARK_REASON"); const resultAddr = tcbFieldAddr("PARK_RESULT"); let h = 0, owner = 0; let pendingService = true; let hwjsCoopBreaths = 0; const sliceEnter = typeof exp.__hwjs_slice_enter === "function" ? exp.__hwjs_slice_enter : null; const sliceExit = typeof exp.__hwjs_slice_exit === "function" ? exp.__hwjs_slice_exit : null; if (init.mode === "fork-resume" && firstImage) { h = typeof init.forkHandle === "number" ? init.forkHandle >>> 0 : 0; owner = typeof init.forkOwner === "number" ? init.forkOwner >>> 0 : 0; if (!h) { throw new Error( "HWJS-3: fork-resume child without a forkHandle rider \u2014 the parent pump must pass the adopted (handle, owner) on the fork message (the taken slot is empty by design)" ); } if (typeof init.tlsBase === "number" && typeof exp.__wasm32_set_tls_base === "function") { bindTaskTlsBase(init.tlsBase, continuingMainTlsBlock(), false); } if (typeof init.parentSp === "number" && init.parentSp !== 0 && typeof exp.__wasm32_set_stack_pointer === "function") { exp.__wasm32_set_stack_pointer(init.parentSp >>> 0); } const staleReason = uU32()[reasonAddr >> 2] >>> 0; if (staleReason !== HWJS_PARK_NONE) { throw new Error( `HWJS-3: fork-resume child copied a PENDING park reason ${staleReason} \u2014 the parent pump clears the reason before the delta=0 copy by contract` ); } uU32()[resultAddr >> 2] = 0; pendingService = false; } else { const acctT0 = acctBeginSlice(); if (sliceEnter) sliceEnter(); exp._start(); if (sliceExit) sliceExit(); acctEndSlice(acctT0); if (uU32()[parkedAddr >> 2] === 0) { throw new Error( "HWJS-3: _start returned with an EMPTY parked slot \u2014 the program chain neither parked nor exited; __libc_start_main completed (noreturn contract breach)" ); } owner = uU32()[ownerAddr >> 2] >>> 0; h = exp.__hwjs_take_parked(0, 0) >>> 0; post({ kind: "hwjs-host-drive", pid: init.pid, handle: h, owner }); } for (; ; ) { if (pendingService) { const reason = uU32()[reasonAddr >> 2] >>> 0; uU32()[reasonAddr >> 2] = HWJS_PARK_NONE; if (reason === HWJS_PARK_FORK && hwjsVforkLatched) { const vreq = hwjsVforkLatched; hwjsVforkLatched = null; uU32()[resultAddr >> 2] = await requestVforkChild(vreq) | 0; hwjsSliceProgressed = true; } else if (reason === HWJS_PARK_FORK) { if (!hwjsForkLatched) { throw new Error( "HWJS-3: FORK park without a latched SYS_fork \u2014 the park leaf fired outside the musl _Fork protocol" ); } hwjsForkLatched = false; if (typeof exp.__hwjs_fork_barrier_ok !== "function") { throw new Error( "HWJS-3 fork latch: coro image lacks __hwjs_fork_barrier_ok \u2014 refusing the delta=0 copy without the structural barrier predicate (ADR-0004 F87 conf (4))" ); } const barrier = exp.__hwjs_fork_barrier_ok() | 0; if (barrier !== 1) { throw new Error( `HWJS-3 fork latch ${barrier === -1 ? "REFUSED" : "not quiesced"}: __hwjs_fork_barrier_ok=${barrier} \u2014 the delta=0 whole-memory copy is a whole-arena predicate, legal at barrier-quiesce only (ADR-0004 F87 conf (4))` ); } const childPid = await requestForkChild({ handle: h, owner }); uU32()[resultAddr >> 2] = childPid | 0; hwjsSliceProgressed = true; } else if (reason === HWJS_PARK_EXEC) { if (!hwjsExecLatched) { throw new Error( "HWJS-3: EXEC park without a latched SYS_execve \u2014 the park leaf fired outside the musl execve protocol" ); } hwjsExecLatched = false; const res = await requestExecImage( execPendingPath, execPendingPathPtr ); const execRequestedPath = execPendingPath; execPendingPath = null; execPendingPathPtr = 0; if (res && res.ok && res.wasmBytes) { execNextBytes = res.wasmBytes; execInstalledPath = execRequestedPath; break; } uU32()[resultAddr >> 2] = res && typeof res.errno === "number" ? res.errno | 0 : -2; hwjsSliceProgressed = true; } else if (reason === HWJS_PARK_NONE) { coopWaitEpisodeReset(); hwjsCoopBreaths++; if (await serviceCooperativeBreath()) hwjsSliceProgressed = true; } else if (reason === HWJS_PARK_RESCHED) { const yT0 = SCHED_TRACE ? schedNow() : 0; schedTrace(post, `YIELD cpu=${init.cpuId ?? "?"} tid=${init.tid} reason=RESCHED-park site=nested-pump via=${pendingCoopFutex !== null ? "coop-futex" : "wake-word"}`); if (pendingCoopFutex !== null) await coopFutexParkYield("HWJS-3 nested pump"); else await coopWaitParkYield("HWJS-3 nested pump"); if (SCHED_TRACE) { schedTrace(post, `RESUME cpu=${init.cpuId ?? "?"} tid=${init.tid} site=nested-pump waited=${(schedNow() - yT0).toFixed(1)}ms`); } hwjsSliceProgressed = true; } else { throw new Error( `HWJS-3: parked chain with UNKNOWN park reason=${reason} \u2014 not a service request (FORK/EXEC/RESCHED) and not a cooperative breath (0); ` + (reason === 6 ? "6 (PREEMPT, libc's __wasm_preempt: a checkpoint, or a mutex release that woke a waiter) has no arm in the nested pump, which only drive_abi<=2 user images use" : "the reason contract has a value this pump does not know") ); } } pendingService = true; await slicePause(); const acctT0 = acctBeginSlice(); if (sliceEnter) sliceEnter(); exp.hwjs_resume(h); if (exp.hwjs_done(h)) { if (sliceExit) sliceExit(); exp.hwjs_destroy(h); throw new Error( "HWJS-3: program chain ran to DONE \u2014 __libc_start_main completed without exit (noreturn contract breach; the in-module __hwjs_noreturn_completed witness should have fired first)" ); } exp.__hwjs_take_parked(owner, h); if (sliceExit) sliceExit(); acctEndSlice(acctT0); if (hwjsSliceProgressed) { if (typeof exp.__hwjs_progress_note === "function") exp.__hwjs_progress_note(); hwjsSliceProgressed = false; } if (typeof exp.__hwjs_drive_watch === "function" && (exp.__hwjs_drive_watch(h) | 0) === 1) { throw new Error( "HWJS-3 F93: drive-loop PROGRESS backstop tripped \u2014 the chain made stall_bound consecutive zero-progress resume slices (wedged handle 0x" + (h >>> 0).toString(16) + "). The attributed __hwjs_progress_violation was written to fd 2. This is the F18 chained-unwind / reason-0 spin failing loud+attributed; stop-and-report with the handle, do not iterate." ); } } } } else { if (init.mode === "fork-resume" && firstImage) { throw new Error( "fork-resume of a user image without the coro drive surface: such an image cannot fork, so there is no continuation to resume" ); } const rc = exp._start(); if (typeof rc === "number" && !exitPosted) exitCode = rc & 255; } } } catch (e) { if (e === HWJS_TASK_REAPED) { try { post({ kind: "dmesg", level: 4, text: `hwjs group-death REAP pid=${init.pid} tid=${init.tid | 0}: the resident stopped on its Worker (${init.reapedBy})` }); } catch (_e) { } await notifyChildExitOnce( 9, 1 /* signaled */ ); releaseProcessRunState("reaped"); return; } if (e === HWJS_EXEC_UNWIND) { execNextBytes = execInlineReinstantiateBytes; execInstalledPath = execPendingPath; execInlineReinstantiateBytes = null; } else if (e === HWJS_REAPED_UNWIND) { try { (workerHostPost || post)({ kind: "dmesg", level: 4, text: `hwjs-reaped tid=${init.tid | 0} pid=${init.pid ?? "?"}: the host reaped this resident at group death; it stopped running on cpu=${sched.cpuId} at its next host call, and the Worker serves its other residents again` }); } catch (_e) { } releaseProcessRunState("reaped"); return; } else { if (pendingExitTerminus) { if (init.vforkChild) { let rested = false; try { rested = await releaseThreadBlock("vfork child exit"); } catch (_e) { } if (!rested) leaveThreadImage(true); } await runExitTerminus(); } if (exitPosted) { releaseProcessRunState("exit-unwind"); return; } const message = e instanceof Error ? `${e.message} ${e.stack ?? ""}` : String(e); try { const w = readViolationWitness(userExports, init.memory); const line = formatViolationWitness( w, `pid=${init.pid ?? "?"} tid=${init.tid | 0} terminal trap` ); if (line) post({ kind: "dmesg", level: 3, text: `${line} ` }); } catch (_wErr) { } if (typeof process !== "undefined" && process.env?.HWJS_TRAP_DUMP) { try { const fsMod = await import("node:fs"); const dir = process.env.HWJS_TRAP_DUMP; const tag = `trapdump-pid${init.pid}-tid${init.tid ?? "?"}-${Date.now()}`; const memBytes = new Uint8Array(init.memory.buffer); const copy = new Uint8Array(memBytes.length); copy.set(memBytes); fsMod.writeFileSync(`${dir}/${tag}.bin`, copy); let sp = null; try { const g = userExports && userExports.__stack_pointer; if (g instanceof WebAssembly.Global) sp = g.value >>> 0; } catch (_e2) { } fsMod.writeFileSync(`${dir}/${tag}.json`, JSON.stringify({ pid: init.pid, tid: init.tid ?? null, mode: init.mode, block: currentTcb >>> 0, memLen: memBytes.length, stackPointer: sp, message }, null, 2)); post({ kind: "dmesg", level: 3, text: `HWJS_TRAP_DUMP: wrote ${tag}.bin (${memBytes.length}B) sp=${sp === null ? "?" : "0x" + sp.toString(16)}` }); } catch (dumpErr) { post({ kind: "dmesg", level: 3, text: `HWJS_TRAP_DUMP FAILED: ${dumpErr instanceof Error ? dumpErr.message : String(dumpErr)}` }); } } containTrappedLane("run-terminal-trap"); if (init.mode === "thread") containThreadGroupAfterTrap(); await notifyChildExitOnce( 4, 1 /* signaled */ ); post({ kind: "error", pid: init.pid, message }); releaseProcessRunState("error"); return; } } if (execNextBytes) { curWasmBytes = execNextBytes; firstImage = false; if (init.vforkChild) continue imageLoop; if (dlopenModules.size > 0) { try { post({ kind: "dmesg", level: 6, text: `hwjs-sys pid=${init.pid} EXEC-DLOPEN-TEARDOWN: dropping ${dlopenModules.size} dlopen handle(s) across execve (dl handles do not survive exec; the .so instances died with the replaced address space)` }); } catch (_e) { } dlopenModules.clear(); } if (placementCell) { const everThreaded = (Atomics.load(placementCell, PC_THREADS) | 0) !== 0; Atomics.store(placementCell, PC_GEN, 0); Atomics.store(placementCell, PC_LOCK, 0); Atomics.store(placementCell, PC_THREADS, 0); Atomics.store(placementCell, PC_TLEN, 0); const imageEpoch = Atomics.add(placementCell, PC_IMAGE, 1) + 1; post({ kind: "dl-placement-reset", memoryId: init.memoryId | 0, ...everThreaded ? { releaseThreadImagesBefore: imageEpoch } : {} }); } placementApplied = 0; placementPullFails = 0; placementOwnGens.clear(); placementShipped.clear(); if (dlopenDeadRanges.length > 0) dlopenDeadRanges.length = 0; xmodConsultInvalidate(); xmodConsultStatsReport("exec"); if (init.mergedCpu0Lane === true && workerHostSyncCall !== null && init.routeKey != null) { let ack; try { ack = workerHostSyncCall({ kind: "exec-install-sync", routeKey: init.routeKey, wasmBytes: curWasmBytes }); } catch (_e) { ack = void 0; } if (ack !== "installed") { try { post({ kind: "dmesg", level: 4, text: `hwjs-merged EXEC-SYNC DECLINED pid=${init.pid} routeKey=${init.routeKey}: the host did not re-derive the mmap partition through the synchronous door (answer=${ack === void 0 ? "declined" : String(ack)}), so the new image's first mmaps are served from the pre-exec floor until the exec-image-installed message is delivered.` }); } catch (_e) { } } } heapCollectSoon(); post({ kind: "exec-image-installed", pid: init.pid, wasmBytes: curWasmBytes, ...execInstalledPath ? { path: execInstalledPath } : {} }); continue imageLoop; } } catch (e) { if (firstImage || exitPosted) { leaveThreadImage(true); throw e; } if (e instanceof WebAssembly.RuntimeError) containTrappedLane("exec image load"); await imageStageFatal( "LOAD", e, 11 /* SIGSEGV */ ); break imageLoop; } break imageLoop; } if (!exitPosted) { await notifyChildExitOnce(exitCode & 255, 0); xmodConsultStatsReport("exit"); post({ kind: "exit", pid: init.pid, code: exitCode, wasmSyscallStats: wasmSyscallStatsObject(), ...coopWaitViolations > 0 ? { coopWaitViolations } : {}, ...syncRestartViolations > 0 ? { syncRestartViolations } : {}, /* F87 conf (3) AMENDED: census with end-of-process * reconciliation (fatal on unexplained residue). */ ...hwjsLane ? { hwjsLaneCensus: reconcileOrFlag(hwjsLane) } : {} }); } releaseProcessRunState("completed"); } function reconcileOrFlag(hwjsLane) { try { return hwjsLane.reconcile(); } catch (e) { return { ...hwjsLane.census, reconcileFatal: e instanceof Error ? e.message : String(e) }; } } function dmesgLoopStalledMs() { const now = Date.now(); if (!dmesgTurnPending) { dmesgTurnPending = true; dmesgTurnArmedMs = now; try { const t = setTimeout(() => { dmesgTurnPending = false; }, 0); t?.unref?.(); } catch (_e) { dmesgTurnPending = false; } return 0; } return now - dmesgTurnArmedMs; } function dmesgDeliver(post, routeKey, pid, level, text) { const stalled = dmesgLoopStalledMs(); if (stalled >= MERGED_DMESG_STALL_MS && workerHostSyncCall !== null && routeKey != null) { const door2 = (lvl, s) => { try { return workerHostSyncCall({ kind: "dmesg-sync", routeKey, pid: pid | 0, level: lvl | 0, text: String(s) }); } catch (_e) { return void 0; } }; if (!dmesgSyncNoted) { const ok = door2( 4, `hwjs-merged: this realm has not reached its event loop for ${stalled} ms, so kernel records cannot be POSTED \u2014 the port that carries them (inlineRealm.ts) is drained by the turn this thread is not taking. Every record from here on is delivered through the SYNCHRONOUS door instead, byte-for-byte, on the stalled thread's own stack. They are OUT OF ORDER with respect to records still queued from before this line, which arrive if and when the stall ends. Never-silent: without this the log stops at the last record posted before the wedge and reads as the machine stopping there. ` ); if (ok !== "delivered") { try { post({ kind: "dmesg", level: level | 0, text }); } catch (_e) { } return; } dmesgSyncNoted = true; } if (door2(level, text) === "delivered") return; } try { post({ kind: "dmesg", level: level | 0, text }); } catch (_e) { } } function userImagesMerge(entries) { if (!Array.isArray(entries)) return; for (const e of entries) { if (!e || typeof e.key !== "string" || !(e.module instanceof WebAssembly.Module)) continue; if (hostUserModules.has(e.key)) continue; hostUserModules.set(e.key, e.module); if (hostUserModules.size > USER_MODULE_CACHE_MAX) { hostUserModules.delete(hostUserModules.keys().next().value); } } } function fnv1a32(bytes, start, end, basis = 2166136261) { let h = basis >>> 0; for (let i = start; i < end; i++) { h ^= bytes[i]; h = Math.imul(h, 16777619); } return h >>> 0; } function userImageCacheKey(bytes) { const n = bytes.length; const dv = new DataView(bytes.buffer, bytes.byteOffset, n); let a = 0; let b = 2654435769 | 0; const words = n & ~3; let i = 0; for (; i < words; i += 4) { let k = dv.getUint32(i, true); k = Math.imul(k, 3432918353); k = k << 15 | k >>> 17; k = Math.imul(k, 461845907); a ^= k; a = a << 13 | a >>> 19; a = Math.imul(a, 5) + 3864292196 | 0; b = Math.imul(b ^ k, 2246822507); b ^= b >>> 13; } if (i < n) { let k = 0; for (let s = 0; i < n; i++, s += 8) k |= bytes[i] << s; k = Math.imul(k, 3432918353); k = k << 15 | k >>> 17; k = Math.imul(k, 461845907); a ^= k; b = Math.imul(b ^ k, 2246822507); b ^= b >>> 13; } const fmix = (h) => { h ^= n; h ^= h >>> 16; h = Math.imul(h, 2246822507); h ^= h >>> 13; h = Math.imul(h, 3266489909); h ^= h >>> 16; return h >>> 0; }; return `${n}:${fmix(a).toString(16)}:${fmix(b).toString(16)}`; } function placedImageKey(init, bytes) { const key = init && init.imgKey; if (typeof key !== "string" || !bytes || bytes !== init.wasmBytes) return void 0; return key.startsWith(`${bytes.length}:`) ? key : void 0; } async function compileUserModule(bytes, knownKey) { const key = knownKey === void 0 ? userImageCacheKey(bytes) : knownKey; const hit = userModuleCache.get(key); if (hit !== void 0) { userModuleCacheHits++; userModuleCache.delete(key); userModuleCache.set(key, hit); return { module: hit, key, cached: true }; } const shared = hostUserModules.get(key); if (shared !== void 0) { userModuleCacheHits++; userModuleHostAdopted++; hostUserModules.delete(key); hostUserModules.set(key, shared); userModuleCache.set(key, shared); if (userModuleCache.size > USER_MODULE_CACHE_MAX) { userModuleCache.delete(userModuleCache.keys().next().value); } return { module: shared, key, cached: true }; } const module = await WebAssembly.compile(wasmSource3(bytes)); userModuleCompiles++; userModuleCache.set(key, module); if (userModuleCache.size > USER_MODULE_CACHE_MAX) { const oldest = userModuleCache.keys().next().value; userModuleCache.delete(oldest); } hostUserModules.set(key, module); if (hostUserModules.size > USER_MODULE_CACHE_MAX) { hostUserModules.delete(hostUserModules.keys().next().value); } try { workerHostPost?.({ kind: "user-image-compiled", key, module, byteLength: bytes.length }); } catch (_e) { } return { module, key, cached: false }; } function soModuleCacheKey(bytes) { const h1 = fnv1a32(bytes, 0, bytes.length); const h2 = fnv1a32(bytes, 0, bytes.length, 3421674724); return `${bytes.length}:${h1.toString(16)}:${h2.toString(16)}`; } function soModuleCacheStats() { return `soCompiles=${soModuleCompiles} soHits=${soModuleCacheHits} soCacheSize=${soModuleCache.size} liveSoModules=${soModulesLive} soCompiledWireBytes=${soModuleCompiledWireBytes}`; } function isolateModuleCacheCensus() { return { userCompiles: userModuleCompiles, userHits: userModuleCacheHits, userCacheSize: userModuleCache.size, /* Modules the HOST compiled once and broadcast that this isolate * adopted instead of compiling. `userHits` counts both kinds of reuse; * this names the machine-wide half. */ userHostAdopted: userModuleHostAdopted, userHostMirrorSize: hostUserModules.size, soCompiles: soModuleCompiles, soHits: soModuleCacheHits, soCacheSize: soModuleCache.size, soModulesLive }; } function storedSoModule(module, digest) { soModuleCacheHits++; return { module, key: `sha256:${digest}`, cached: true }; } function compileSoModule(bytes, digest) { const kept = retainedLibraryInfo2(bytes); if (kept) { throw new Error( `hwjs-libc: the retained copy of library ${kept.digest.slice(0, 16)}\u2026 (${bytes.length}B of ${kept.wireLength}B) was handed to a compile \u2014 it holds no code; the library's Module is kept beside it and must be used instead (never-silent)` ); } const red = (globalThis.process?.env?.HWJS_70_RED_NOCACHE || "") === "1"; const found = red ? null : soModuleCache.find(bytes, digest); const key = found ? found.key : soModuleCache.keyOf(bytes, digest); if (found && found.module !== void 0) { soModuleCacheHits++; return { module: found.module, key, cached: true }; } const module = new WebAssembly.Module(wasmSource3(bytes)); soModuleCompiles++; soModuleCompiledWireBytes += bytes.length; if (soModuleFinalizer) { soModulesLive++; soModuleFinalizer.register(module, key); } if (found) soModuleCache.add(found.id, module); return { module, key, cached: false }; } function linkPlanOpts() { if (!LINK_PLAN_ON) return {}; return { preMain: true, ...LINK_PLAN_CHECK ? { linkPlanCheck: true } : {} }; } function linkFactsSet(id, facts) { linkFacts.delete(id); linkFacts.set(id, facts); if (linkFacts.size > LINK_FACTS_MAX) linkFacts.delete(linkFacts.keys().next().value); } function linkFactsMerge(entries) { if (!Array.isArray(entries)) return; for (const e of entries) { if (e && typeof e.id === "string" && e.facts && e.facts.v === LINK_FACTS_FORMAT) { linkFactsSet(e.id, e.facts); } } } function closurePlanBegin({ imageKey, rtKey, libcDigest, needed, replay, join, envp }) { if (!CLOSURE_PLAN_ON || replay || join || typeof imageKey !== "string") { closurePlanStats.off++; return null; } if (needed.some((w) => w.preload || w.preloadDep) || ldPreloadEntries(envp || []).length > 0 || ldLibraryPathDirs(envp || []).length > 0) { closurePlanStats.off++; return null; } const key = [imageKey, rtKey, libcDigest || "-", ...needed.map((w) => w.digest)].join("|"); const got = linkFacts.get(`plan:${key}`); const plan = got && got.v === LINK_FACTS_FORMAT && got.steps ? got : null; return { key, plan, steps: /* @__PURE__ */ Object.create(null), complete: true, differs: false }; } function closurePlanOpts(cp, step) { const st = cp && cp.plan ? cp.plan.steps[step] : void 0; return st ? { tablePlan: { base: st.base, growth: st.growth } } : {}; } function closurePlanNote(cp, step, handle) { if (!cp) return; const g = handle && handle.tableGrowth; if (!g) { cp.complete = false; return; } cp.steps[step] = { base: g.base >>> 0, growth: g.used >>> 0 }; if (cp.plan) { const st = cp.plan.steps[step]; if (!st || st.base !== g.base >>> 0 || st.growth !== g.used >>> 0 || g.planned === null) { if (!cp.differs && CLOSURE_PLAN_TRACE) { cp.why = `${step}: plan ${st ? `${st.base}+${st.growth}` : "none"}, load ${g.base}+${g.used} (planned ${g.planned})`; } cp.differs = true; } } } function closurePlanEnd(cp, post) { if (!cp) return; let verdict; if (!cp.complete) { verdict = "incomplete"; } else if (cp.plan && !cp.differs) { closurePlanStats.hit++; verdict = "hit"; } else { if (cp.plan) closurePlanStats.miss++; closurePlanStats.recorded++; verdict = cp.plan ? "replaced" : "recorded"; const facts = { v: LINK_FACTS_FORMAT, steps: cp.steps }; linkFactsSet(`plan:${cp.key}`, facts); try { workerHostPost?.({ kind: "link-facts", entries: [{ id: `plan:${cp.key}`, facts }] }); } catch (_e) { } } if (CLOSURE_PLAN_TRACE) { try { post({ kind: "dmesg", level: 4, text: `hwjs-closure-plan: ${verdict}${cp.why ? ` [${cp.why}]` : ""} (${Object.keys(cp.steps).length} loads; hit ${closurePlanStats.hit} miss ${closurePlanStats.miss} recorded ${closurePlanStats.recorded} off ${closurePlanStats.off})` }); } catch (_e) { } } } function filterImports(module, imports) { const needed = moduleImportsOf(module); const out = /* @__PURE__ */ Object.create(null); for (const imp of needed) { const ns = Object.hasOwn(imports, imp.module) ? imports[imp.module] : void 0; if (!ns || !Object.hasOwn(ns, imp.name)) { throw new Error(`missing import ${imp.module}.${imp.name} (${imp.kind})`); } out[imp.module] = out[imp.module] ?? /* @__PURE__ */ Object.create(null); out[imp.module][imp.name] = ns[imp.name]; } return out; } var SIGNAL_REGION_BYTES, C, REQUEST, RESPONSE, IDLE, CTRL_I32_REAPED, SYS_EXIT, SYS_EXIT_GROUP, SYS_CLONE, SYS_SCHED_SETAFFINITY, SYS_WASM_DLOPEN, SYS_WASM_DLSYM, SYS_WASM_DLCLOSE, HWJS_DLOPEN_REISSUE, SYS_WASM_DLERROR, SYS_WASM_DLOPEN_LOADED, SYS_WASM_DLADDR, SYS_WASM_EXEC_LOAD_BEGIN, SYS_WASM_EXEC_LOAD_STEP, WASM_EXEC_HOST_KEEPS_ARGV0, WASM_EXEC_PREFIX_KEEPS_ARGV0, EXEC_LOAD_HOST_FLAGS, SYS_WASM_LIBC_STAGE, SYS_WASM_DLOPEN_LOAD, SYS_WASM_NEEDED_STAGE, SYS_WASM_ROOT_MAP, HWJS_ERESTART_RESCHED, HWJS_ERESTARTNOINTR, replaysModuleGraph, MIG_OFFERED, MIG_CLAIMED, MIG_BOUND, MIG_ABORTED, MIG_COMMIT_MS, MIG_PLACE_MS, MIG_ABORT_TIMEOUT, MIG_ABORT_NO_LANE, MIG_ABORT_BIND, MIG_ABORT_HOST, MIG_ABORT_UNCLAIMED, SYS_WASM_EXIT_BY_SIGNAL, SYS_WASM_SIGCONSUME, SYS_WASM_SETJMP, SYS_WASM_LONGJMP, execImageResolver, __utf8Decoder, SGSEG_SIZE2, sharedWasmSourceOk2, cpuWorker, laneResidents, laneRecByInit, laneInboxI32, preemptCtlI32, preemptPort, preemptSlotBase, preemptSliceMax, preemptClock, preemptTokenSeq, preemptSlot, preemptWarned, PREEMPT_SLICE_BESIDE_US, PREEMPT_SLICE_ALONE_US, PREEMPT_SLICE_MERGED_US, workerSharedLibs, sharedLibPaths, neededSubstitutes, neededSurfaces, neededSubstituteNoted, threadPlacementProviders, dlPlacementPulls, dlPlacementPullSeq, DL_PLACEMENT_PULL_TRIES, heapStatsFn, heapGuardNoted, heapStatsReady, HEAP_TRACE, heapSnapshotTaken, HEAP_GUARD_MAX_MARGIN, HEAP_COLLECT_DELAY_MS, HEAP_COLLECT_MIN_GAP_MS, HEAP_COLLECT_PERIOD_MS, heapCollectTimer, heapCollectLast, HWJS_EXIT_UNWIND, HWJS_REAPED_UNWIND, HWJS_EXEC_UNWIND, HWJS_TASK_REAPED, reapableTasks, processVmlinuxInstanceCount, HWJS_INITIAL_BUDGET, HWJS_USER_INITIAL_BUDGET, HWJS_SP_REFILL, HWJS_BREATH_SLICE_US, HWJS_SP_REFILL_MAX, HWJS_BREATH_ADAPT, HWJS_BREATH_BESIDE, BREATH_TARGET_MS, BREATH_LONG_MS, BREATH_SHARE_FRAC, BREATH_COST_HALF_MS, HWJS_PARK_PREEMPT, HWJS_NO_SP_YIELD, HWJS_BREATH_TURN_MS, HWJS_FORK_BACKOFF_MS, HWJS_BREATH_CENSUS, HWJS_SCHED_YIELD_ALWAYS, HWJS_ACCT_DBG, HWJS_XMOD_CONSULT_TRACE, HWJS_XMOD_CONSULT_CACHE, HWJS_XMOD_CONSULT_STATS, HWJS_FPCAST_TRACE, HWJS_FPCAST_VERSION, HWJS_NO_RECLAIM_RETRY, HWJS_RECLAIM_RETRY_ROUNDS, HWJS_RECLAIM_SETTLE_MS, HWJS_TEST_GROW_FAIL_MINPAGES, hwjsTestGrowFailsLeft, LANE_WAIT_REPORT_MS, THR_TRACE, SCHED_TRACE, WORKER_BEAT_MS, SCHED_TRACE_HOLD_MS, HOST_PERF, HOST_TIME_ORIGIN, schedNow, WORKER_STALL_THRESHOLD_MS, HOLD_REPORT_OFF, HWJS_LANE_WOULD_BLOCK, WASM32_PARK_CONSUMER_NONE, WASM32_PARK_CONSUMER_HOST, HWJS_LANE_RESIDUE_CEILING, rt4ByKernel, workerKernels, workerKernelsNoMemory, KERNEL_IMPORT_ARGS_MAX, threadImageContexts, wasmJitMemories, THREAD_IMAGE_SHARING, threadViewRaw, THREAD_SHAPE_PER_THREAD_FIELDS, HWJS_EMMAP_PARKED, isRestartValue, FMG_BUCKET_END, FMG_LOG_HEAD, FMG_LOG_IDS, FMG_LOG_BASE, FMG_LOG_SLOTS, FMG_LOG_STRIDE, FMG_WATCH_BASE, FILE_MAP_GEN_WORDS, FMG_LIVE, FMG_ALL, FMG_LOG_MAX_PER_PUBLISH, TMPFS_MAGIC, RAMFS_MAGIC, DRM_MAJOR, WASMDRM_GEM_PWRITE, WASMDRM_GEM_PREAD, FILE_WRITE_FD_ARG, SHMAP_PRIVATE_SYSCALLS, TASK_STATE_OFF, SIGPEND_I32_PENDING_LO, SIGPEND_I32_WAKE_WORD, SIGPEND_I32_SIGCHLD_DELIVERY_SEQ, SIGCHLD_PENDING_BIT_LO, SIGKILL_PENDING_BIT_LO, HOST_ANSWERED, WASM_SYSCALL_NR_MAX, HOST_ANSWERS_NR, HWJS_CANCELLABLE_SYSCALLS, SYS_ENV_KNOB, USER_MODULE_CACHE_MAX, userModuleCache, userModuleCompiles, userModuleCacheHits, userModuleHostAdopted, hostUserModules, workerHostPost, workerHostSyncCall, MERGED_DMESG_STALL_MS, dmesgTurnPending, dmesgTurnArmedMs, dmesgSyncNoted, SO_MODULE_CACHE_MAX, soModuleCompiles, soModuleCacheHits, soModuleCompiledWireBytes, soModulesLive, soModuleFinalizer, soModuleCache, LINK_PLAN_ENV, LINK_PLAN_ON, LINK_PLAN_CHECK, LINK_PLAN_TRACE, CLOSURE_PLAN_ON, CLOSURE_PLAN_TRACE, LINK_FACTS_MAX, linkFacts, closurePlanStats; var init_worker = __esm({ "../../linux-in-the-browser/hardwarejs/src/worker.mjs"() { "use strict"; init_dynLoader(); init_dynLoader(); init_preemptTimer(); init_dynLoader(); init_dynLoader(); init_hwjsTcb(); init_dynLoader(); init_dynLoader(); init_dynLoader(); init_dynLoader(); init_dynLoader(); init_dynLoader(); init_dynLoader(); init_uaccessBoundary(); init_uaccessCopies(); init_wasmJit(); init_dynLoader(); init_dynLoader(); init_capsummaryRegistry(); init_dynLoader(); init_macrotask(); init_macrotask(); init_pause(); init_violationWitness(); SIGNAL_REGION_BYTES = 40; C = { STATE: 0, NR: 1, A0: 2, A1: 3, A2: 4, A3: 5, A4: 6, A5: 7, RET_LO: 9, RET_HI: 10, PID: 12, TID: 13, /* The leader hold's release word: 0 while a main thread that called * pthread_exit waits for its process's other threads, 1 once the host has * seen the group's last thread go (see leaderHoldUntilGroupEmpty). */ LEADER_HOLD: 14 }; REQUEST = 1; RESPONSE = 2; IDLE = 0; CTRL_I32_REAPED = 15; SYS_EXIT = 60; SYS_EXIT_GROUP = 231; SYS_CLONE = 56; SYS_SCHED_SETAFFINITY = 203; SYS_WASM_DLOPEN = 1040; SYS_WASM_DLSYM = 1041; SYS_WASM_DLCLOSE = 1042; HWJS_DLOPEN_REISSUE = 1; SYS_WASM_DLERROR = 1043; SYS_WASM_DLOPEN_LOADED = 1050; SYS_WASM_DLADDR = 1051; SYS_WASM_EXEC_LOAD_BEGIN = 1044; SYS_WASM_EXEC_LOAD_STEP = 1045; WASM_EXEC_HOST_KEEPS_ARGV0 = 1; WASM_EXEC_PREFIX_KEEPS_ARGV0 = 1; EXEC_LOAD_HOST_FLAGS = WASM_EXEC_HOST_KEEPS_ARGV0; SYS_WASM_LIBC_STAGE = 1046; SYS_WASM_DLOPEN_LOAD = 1047; SYS_WASM_NEEDED_STAGE = 1048; SYS_WASM_ROOT_MAP = 1049; HWJS_ERESTART_RESCHED = -517; HWJS_ERESTARTNOINTR = -513; replaysModuleGraph = (mode) => mode === "fork-resume" || mode === "thread" || mode === "migrate-resume"; MIG_OFFERED = 0; MIG_CLAIMED = 1; MIG_BOUND = 2; MIG_ABORTED = 3; MIG_COMMIT_MS = 1e4; MIG_PLACE_MS = 3e3; MIG_ABORT_TIMEOUT = 1; MIG_ABORT_NO_LANE = 2; MIG_ABORT_BIND = 3; MIG_ABORT_HOST = 4; MIG_ABORT_UNCLAIMED = 5; SYS_WASM_EXIT_BY_SIGNAL = 1027; SYS_WASM_SIGCONSUME = 1028; SYS_WASM_SETJMP = 1029; SYS_WASM_LONGJMP = 1030; execImageResolver = null; __utf8Decoder = new TextDecoder("utf-8", { fatal: false }); SGSEG_SIZE2 = 8; cpuWorker = null; laneResidents = /* @__PURE__ */ new Set(); laneRecByInit = /* @__PURE__ */ new WeakMap(); laneInboxI32 = null; preemptCtlI32 = null; preemptPort = null; preemptSlotBase = 0; preemptSliceMax = 0; preemptClock = null; preemptTokenSeq = 0; preemptSlot = 0; preemptWarned = false; PREEMPT_SLICE_BESIDE_US = (() => { const e = typeof process !== "undefined" && process.env.HWJS_PREEMPT_BESIDE_US || ""; const v = parseInt(e, 10); return Number.isFinite(v) && v > 0 ? v : 2e3; })(); PREEMPT_SLICE_ALONE_US = (() => { const e = typeof process !== "undefined" && process.env.HWJS_PREEMPT_ALONE_US || ""; const v = parseInt(e, 10); return Number.isFinite(v) && v > 0 ? v : 1e4; })(); PREEMPT_SLICE_MERGED_US = 1e3; workerSharedLibs = /* @__PURE__ */ new Map(); sharedLibPaths = /* @__PURE__ */ new Map(); neededSubstitutes = /* @__PURE__ */ new Map(); neededSurfaces = /* @__PURE__ */ new Map(); neededSubstituteNoted = /* @__PURE__ */ new Set(); threadPlacementProviders = /* @__PURE__ */ new Map(); dlPlacementPulls = /* @__PURE__ */ new Map(); dlPlacementPullSeq = 1; DL_PLACEMENT_PULL_TRIES = 3; heapStatsFn = null; heapGuardNoted = false; heapStatsReady = (async () => { try { if (typeof process !== "undefined" && process.versions && process.versions.node) { const v8 = await import("node:v8"); heapStatsFn = () => { const h = v8.getHeapStatistics(); return { used: h.used_heap_size, limit: h.heap_size_limit }; }; return; } } catch (_e) { } try { const pm = globalThis.performance && globalThis.performance.memory; if (pm && typeof pm.jsHeapSizeLimit === "number") { heapStatsFn = () => ({ used: globalThis.performance.memory.usedJSHeapSize, limit: globalThis.performance.memory.jsHeapSizeLimit }); } } catch (_e) { } })(); HEAP_TRACE = !!globalThis.process?.env?.HWJS_HEAP_TRACE; heapSnapshotTaken = false; HEAP_GUARD_MAX_MARGIN = 512 * 1024 * 1024; HEAP_COLLECT_DELAY_MS = 200; HEAP_COLLECT_MIN_GAP_MS = 1e3; HEAP_COLLECT_PERIOD_MS = 5e3; heapCollectTimer = null; heapCollectLast = 0; HWJS_EXIT_UNWIND = { hwjsExitUnwind: true }; HWJS_REAPED_UNWIND = { hwjsReapedUnwind: true }; HWJS_EXEC_UNWIND = { hwjsExecUnwind: true }; HWJS_TASK_REAPED = { hwjsTaskReaped: true }; reapableTasks = /* @__PURE__ */ new Map(); processVmlinuxInstanceCount = 0; HWJS_INITIAL_BUDGET = (() => { const e = typeof process !== "undefined" && process.env.HWJS_INITIAL_BUDGET || ""; const v = parseInt(e, 10); return Number.isFinite(v) && v > 0 ? v : 1 << 20; })(); HWJS_USER_INITIAL_BUDGET = (() => { const e = typeof process !== "undefined" && process.env.HWJS_INITIAL_BUDGET || ""; const v = parseInt(e, 10); return Number.isFinite(v) && v > 0 ? v : 1 << 20; })(); HWJS_SP_REFILL = (() => { const e = typeof process !== "undefined" && process.env.HWJS_SP_REFILL || ""; const v = parseInt(e, 10); return Number.isFinite(v) && v > 0 ? v : HWJS_USER_INITIAL_BUDGET; })(); HWJS_BREATH_SLICE_US = (() => { const e = typeof process !== "undefined" && process.env.HWJS_BREATH_SLICE_US || ""; const v = parseFloat(e); return e !== "" && Number.isFinite(v) && v >= 0 ? v : 0; })(); HWJS_SP_REFILL_MAX = (() => { const e = typeof process !== "undefined" && process.env.HWJS_SP_REFILL_MAX || ""; const v = parseInt(e, 10); return Number.isFinite(v) && v > 0 ? Math.min(v, 1 << 30) : Math.min(HWJS_SP_REFILL * 4, 1 << 30); })(); HWJS_BREATH_ADAPT = HWJS_BREATH_SLICE_US > 0 && HWJS_SP_REFILL_MAX > HWJS_SP_REFILL; HWJS_BREATH_BESIDE = !(typeof process !== "undefined" && process.env.HWJS_BREATH_BESIDE === "0"); BREATH_TARGET_MS = HWJS_BREATH_SLICE_US / 1e3; BREATH_LONG_MS = BREATH_TARGET_MS * 2.5; BREATH_SHARE_FRAC = 0.5; BREATH_COST_HALF_MS = 50; HWJS_PARK_PREEMPT = 6; HWJS_NO_SP_YIELD = typeof process !== "undefined" && !!process.env.HWJS_NO_SP_YIELD; HWJS_BREATH_TURN_MS = (() => { const e = typeof process !== "undefined" && process.env.HWJS_BREATH_TURN_MS || ""; const v = parseFloat(e); return e !== "" && Number.isFinite(v) && v >= 0 ? v : 1; })(); HWJS_FORK_BACKOFF_MS = (() => { const e = typeof process !== "undefined" && process.env.HWJS_FORK_BACKOFF_MS || ""; const v = parseFloat(e); return e !== "" && Number.isFinite(v) && v >= 0 ? v : 50; })(); HWJS_BREATH_CENSUS = typeof process !== "undefined" && process.env.HWJS_BREATH_CENSUS === "1"; HWJS_SCHED_YIELD_ALWAYS = typeof process !== "undefined" && process.env.HWJS_SCHED_YIELD_ALWAYS === "1"; HWJS_ACCT_DBG = typeof process !== "undefined" && !!process.env.HWJS_ACCT_DBG; HWJS_XMOD_CONSULT_TRACE = globalThis.process?.env?.HWJS_XMOD_CONSULT_TRACE === "1"; HWJS_XMOD_CONSULT_CACHE = globalThis.process?.env?.HWJS_XMOD_CONSULT_CACHE !== "0"; HWJS_XMOD_CONSULT_STATS = globalThis.process?.env?.HWJS_XMOD_CONSULT_STATS === "1"; HWJS_FPCAST_TRACE = globalThis.process?.env?.HWJS_FPCAST_TRACE === "1"; HWJS_FPCAST_VERSION = 1; HWJS_NO_RECLAIM_RETRY = typeof process !== "undefined" && !!process.env.HWJS_NO_RECLAIM_RETRY; HWJS_RECLAIM_RETRY_ROUNDS = (() => { const raw = typeof process !== "undefined" && process.env.HWJS_RECLAIM_RETRY_ROUNDS ? parseInt(process.env.HWJS_RECLAIM_RETRY_ROUNDS, 10) : NaN; return Number.isFinite(raw) && raw >= 1 && raw <= 10 ? raw : 3; })(); HWJS_RECLAIM_SETTLE_MS = [50, 500, 2e3]; HWJS_TEST_GROW_FAIL_MINPAGES = typeof process !== "undefined" && process.env.HWJS_TEST_GROW_FAIL_MINPAGES ? parseInt(process.env.HWJS_TEST_GROW_FAIL_MINPAGES, 10) >>> 0 : 0; hwjsTestGrowFailsLeft = typeof process !== "undefined" && process.env.HWJS_TEST_GROW_FAIL_N ? parseInt(process.env.HWJS_TEST_GROW_FAIL_N, 10) | 0 : HWJS_TEST_GROW_FAIL_MINPAGES > 0 ? 1 : 0; LANE_WAIT_REPORT_MS = (() => { const raw = typeof process !== "undefined" && process.env.HWJS_LANE_WAIT_REPORT_MS ? parseInt(process.env.HWJS_LANE_WAIT_REPORT_MS, 10) : NaN; return Number.isFinite(raw) ? raw | 0 : 2e3; })(); THR_TRACE = typeof process !== "undefined" && !!process.env.HWJS_THR_TRACE; SCHED_TRACE = typeof process !== "undefined" && !!process.env?.HWJS_WORKER_SCHED_TRACE; WORKER_BEAT_MS = (() => { const raw = parseInt(typeof process !== "undefined" && process.env?.HWJS_WORKER_SCHED_TRACE || "", 10); return Number.isFinite(raw) && raw >= 10 ? raw | 0 : 250; })(); SCHED_TRACE_HOLD_MS = (() => { const raw = parseInt(typeof process !== "undefined" && process.env?.HWJS_WORKER_SCHED_TRACE_HOLD_MS || "", 10); return Number.isFinite(raw) && raw >= 10 ? raw | 0 : 1e3; })(); HOST_PERF = typeof performance !== "undefined" && typeof performance.now === "function" ? performance : null; HOST_TIME_ORIGIN = HOST_PERF !== null && typeof HOST_PERF.timeOrigin === "number" ? HOST_PERF.timeOrigin : null; schedNow = HOST_PERF !== null ? () => HOST_PERF.now() : () => Date.now(); WORKER_STALL_THRESHOLD_MS = 1e3; HOLD_REPORT_OFF = { tick() { }, end() { }, holds: () => 0 }; HWJS_LANE_WOULD_BLOCK = -517; WASM32_PARK_CONSUMER_NONE = 0; WASM32_PARK_CONSUMER_HOST = 2; HWJS_LANE_RESIDUE_CEILING = 65536; rt4ByKernel = /* @__PURE__ */ new WeakMap(); workerKernels = /* @__PURE__ */ new WeakMap(); workerKernelsNoMemory = {}; KERNEL_IMPORT_ARGS_MAX = 6; threadImageContexts = /* @__PURE__ */ new Map(); wasmJitMemories = makeWasmJitMemoryLedger(); THREAD_IMAGE_SHARING = (globalThis.process?.env?.HWJS_THREAD_IMAGE_PRIVATE || "") !== "1"; threadViewRaw = /* @__PURE__ */ new WeakMap(); THREAD_SHAPE_PER_THREAD_FIELDS = /* @__PURE__ */ new Set(["tlsBase", "live"]); HWJS_EMMAP_PARKED = -540; isRestartValue = (r) => r <= -512 && r >= -517 && r !== -515; FMG_BUCKET_END = 2 + 1024; FMG_LOG_HEAD = FMG_BUCKET_END; FMG_LOG_IDS = FMG_BUCKET_END + 1; FMG_LOG_BASE = FMG_BUCKET_END + 2; FMG_LOG_SLOTS = 512; FMG_LOG_STRIDE = 8; FMG_WATCH_BASE = FMG_LOG_BASE + FMG_LOG_SLOTS * FMG_LOG_STRIDE; FILE_MAP_GEN_WORDS = FMG_WATCH_BASE + (FMG_BUCKET_END - 2); FMG_LIVE = 0; FMG_ALL = 1; FMG_LOG_MAX_PER_PUBLISH = 16; TMPFS_MAGIC = 16914836; RAMFS_MAGIC = 2240043254; DRM_MAJOR = 226; WASMDRM_GEM_PWRITE = 1075340352; WASMDRM_GEM_PREAD = 1075340353; FILE_WRITE_FD_ARG = /* @__PURE__ */ new Map([ [1, 0], [18, 0], [20, 0], [296, 0], [328, 0], [77, 0], [285, 0], [40, 0], [326, 2], [275, 2] ]); SHMAP_PRIVATE_SYSCALLS = /* @__PURE__ */ new Set([ 4, 5, 6, 262, 332, 8, 10, 12, 27, 149, 150, 13, 14, 15, 127, 131, 21, 269, 439, 89, 267, 78, 217, 79, 80, 81, 95, 137, 138, 191, 192, 193, 194, 195, 196, 39, 110, 186, 102, 104, 107, 108, 115, 118, 120, 111, 121, 124, 96, 201, 228, 229, 36, 287, 224, 225, 37, 38, 222, 223, 226, 286, 97, 98, 99, 100, 302, 63, 125, 140, 252, 143, 145, 204, 309, 157, 158, 218, 273, 274, 334, 318, 22, 293, 32, 41, 53, 51, 52, 55, 213, 291, 233, 284, 290, 283, 282, 289, 253, 294, 254, 255 ]); TASK_STATE_OFF = 12; SIGPEND_I32_PENDING_LO = 0; SIGPEND_I32_WAKE_WORD = 2; SIGPEND_I32_SIGCHLD_DELIVERY_SEQ = 6; SIGCHLD_PENDING_BIT_LO = 1 << 17 - 1; SIGKILL_PENDING_BIT_LO = 1 << 9 - 1; HOST_ANSWERED = /* @__PURE__ */ new Set([ 9, 10, 11, 12, 24, 26, 60, 231 ]); WASM_SYSCALL_NR_MAX = 1200; HOST_ANSWERS_NR = new Uint8Array(WASM_SYSCALL_NR_MAX); for (const nr of HOST_ANSWERED) HOST_ANSWERS_NR[nr] = 1; HWJS_CANCELLABLE_SYSCALLS = /* @__PURE__ */ new Set([ 0, /* read */ 1, /* write */ 17, /* pread64 */ 18, /* pwrite64 */ 19, /* readv */ 20, /* writev */ 23, /* select */ 7, /* poll */ 61, /* wait4 */ 247, /* waitid */ 35, /* nanosleep */ 230, /* clock_nanosleep */ 257, /* openat */ 3, /* close */ 270, /* pselect6 */ 271, /* ppoll */ 42, /* connect */ 43, /* accept */ 44, /* sendto */ 45, /* recvfrom */ 46, /* sendmsg */ 47, /* recvmsg */ 74, /* fsync */ 75, /* fdatasync */ /* The signal waits, added when the mask became the kernel's and these * three started reaching it. All park in-kernel for an unbounded time — * rt_sigsuspend and pause until a signal is deliverable, rt_sigtimedwait * until one arrives or the timeout expires — so a -517 from them MUST * propagate to libc and park the user coroutine. The alternative branch * is the in-place block-restart loop, a synchronous spin that would hold * the Worker for the whole of a sigsuspend. Both libcs issue all three * through their cancellable path (musl __syscall_cp, glibc * SYSCALL_CANCEL -> the C INTERNAL_SYSCALL resched wrapper), which is * the precondition for membership. */ 34, /* pause */ 128, /* rt_sigtimedwait */ 130 /* rt_sigsuspend */ /* NOT futex(202) — and it must STAY out (PLAN-THREAD-POOL-RESIDENCY contract 3). * * The original reason ("musl issues futex via raw __syscall, not * __syscall_cp, so a -517 there does not park reason 4") is now STALE: * musl 233328dc made every indefinitely-blocking futex wait set * HWJS_FUTEX_COOP_WAIT, and those calls DO park cooperatively. They do it * WITHOUT this list, because handleFutex answers -517 itself and returns * from syscallInner before this gate is ever consulted. * * Membership is what matters, and adding 202 would be a regression, not a * cleanup: this list feeds the `coopParkCapable` branch, whose ALTERNATIVE * is the in-place block-restart loop below — a synchronous spin that * blocks the lane. Routing futex -517 there would reintroduce exactly the * shared-Worker freeze the cooperative bit removes. Correct the wording * here if it drifts; do not change the set. */ ]); SYS_ENV_KNOB = /^(HWJS_RED_|HWJS_EXPERIMENTAL_|A4C_)/; USER_MODULE_CACHE_MAX = 8; userModuleCache = /* @__PURE__ */ new Map(); userModuleCompiles = 0; userModuleCacheHits = 0; userModuleHostAdopted = 0; hostUserModules = /* @__PURE__ */ new Map(); workerHostPost = null; workerHostSyncCall = null; MERGED_DMESG_STALL_MS = 1e3; dmesgTurnPending = false; dmesgTurnArmedMs = 0; dmesgSyncNoted = false; SO_MODULE_CACHE_MAX = 8; soModuleCompiles = 0; soModuleCacheHits = 0; soModuleCompiledWireBytes = 0; soModulesLive = 0; soModuleFinalizer = typeof FinalizationRegistry === "function" ? new FinalizationRegistry(() => { soModulesLive = Math.max(0, soModulesLive - 1); }) : null; soModuleCache = new SoModuleCache(SO_MODULE_CACHE_MAX, soModuleCacheKey); LINK_PLAN_ENV = typeof process !== "undefined" && process.env || {}; LINK_PLAN_ON = LINK_PLAN_ENV.HWJS_LINK_PLAN !== "0"; LINK_PLAN_CHECK = LINK_PLAN_ENV.HWJS_LINK_PLAN_CHECK === "1"; LINK_PLAN_TRACE = LINK_PLAN_ENV.HWJS_LINK_PLAN_TRACE === "1"; if (LINK_PLAN_TRACE) linkPlanStats.traceForget = true; CLOSURE_PLAN_ON = LINK_PLAN_ENV.HWJS_CLOSURE_PLAN !== "0"; CLOSURE_PLAN_TRACE = LINK_PLAN_ENV.HWJS_CLOSURE_PLAN_TRACE === "1"; LINK_FACTS_MAX = 4096; linkFacts = /* @__PURE__ */ new Map(); if (CLOSURE_PLAN_ON) { setLinkFactsStore({ get: (id) => linkFacts.get(id), put: (id, facts) => { linkFactsSet(id, facts); try { workerHostPost?.({ kind: "link-facts", entries: [{ id, facts }] }); } catch (_e) { } } }); } closurePlanStats = { hit: 0, miss: 0, recorded: 0, off: 0 }; } }); // ../../linux-in-the-browser/hardwarejs/src/worker-inline.mjs var worker_inline_exports = {}; __export(worker_inline_exports, { bindInlineWorker: () => bindInlineWorker }); function bindInlineWorker(transport) { bindWorker(transport); } var init_worker_inline = __esm({ "../../linux-in-the-browser/hardwarejs/src/worker-inline.mjs"() { "use strict"; init_worker(); } }); // src/worker-threads-stub.mjs var worker_threads_stub_exports = {}; __export(worker_threads_stub_exports, { BroadcastChannel: () => BroadcastChannel, MessageChannel: () => MessageChannel2, MessagePort: () => MessagePort, Worker: () => Worker2, default: () => worker_threads_stub_default, isMainThread: () => isMainThread, parentPort: () => parentPort, threadId: () => threadId, workerData: () => workerData }); var Worker2, parentPort, isMainThread, workerData, MessageChannel2, MessagePort, threadId, BroadcastChannel, worker_threads_stub_default; var init_worker_threads_stub = __esm({ "src/worker-threads-stub.mjs"() { Worker2 = void 0; parentPort = null; isMainThread = true; workerData = void 0; MessageChannel2 = void 0; MessagePort = void 0; threadId = 0; BroadcastChannel = void 0; worker_threads_stub_default = {}; } }); // ../../linux-in-the-browser/hardwarejs/src/kernelWorker.mjs var kernelWorker_exports = {}; __export(kernelWorker_exports, { bindKernelWorker: () => bindKernelWorker }); function bindKernelWorker({ post, onMessage: onMessage3, onTerminate, callHostSync }) { const stop = { requested: false }; onTerminate?.(() => { stop.requested = true; }); let devicesReady = null; let devicesReadyWake = null; onMessage3(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 td3 = 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 = td3.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 name2 = (m[1] || "").trim(); frames.push(name2 || ""); 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 = (name2) => (..._args) => { post({ kind: "unimplemented-host-call", name: name2 }); 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, code2) => { if ((pid | 0) === 0) { post({ kind: "machine-power", cmd: code2 >>> 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 = (name2, fn2) => (...args) => { hwjsParkedCheck(name2); return fn2(...args); }; const hwjsGuardDmesgLast = (name2, fn2) => (...args) => { const r = fn2(...args); hwjsParkedCheck(name2); 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 = (name2) => exp[name2] && typeof exp[name2].value === "number" ? exp[name2].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_BUDGET2 = 1 << 20; if (typeof exp.__hwjs_budget_set === "function") { exp.__hwjs_budget_set(HWJS_INITIAL_BUDGET2 | 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_SIZE2 = 104; const cmdlineOffset = align16(bootInfoOffset + BOOT_INFO_SIZE2); 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_SIZE2) { post({ kind: "error", message: `bootInfoOverride must be exactly ${BOOT_INFO_SIZE2} bytes, got ${init.bootInfoOverride.length}` }); return; } kview.set(init.bootInfoOverride, bootInfoOffset); } else { const scratch = new ArrayBuffer(BOOT_INFO_SIZE2); const dv = new DataView(scratch); dv.setUint32(0, 826884695, true); dv.setUint32(4, 4, true); dv.setUint32(8, BOOT_INFO_SIZE2, 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_BUDGET2 | 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() }); } } var kernelInstanceCount, kernelMemoriesInstantiated; var init_kernelWorker = __esm({ "../../linux-in-the-browser/hardwarejs/src/kernelWorker.mjs"() { "use strict"; init_uaccessBoundary(); init_macrotask(); init_pause(); kernelInstanceCount = 0; kernelMemoriesInstantiated = /* @__PURE__ */ new WeakSet(); } }); // ../../linux-in-the-browser/hardwarejs/src/physRam.ts init_uaccessCopies(); var PAGE_SIZE = 65536; var USER_MEM_POOL_COUNT = 8; var USER_MEM_POOL_BYTES_PER_ENTRY = 128 * 1024 * 1024; var USER_MAX_FLOOR_BYTES = 256 * 1024 * 1024; var WASM32_MEMORY_MAX_BYTES = 4 * 1024 * 1024 * 1024; function reflectUserMemoryMaximumBytes(mem) { try { const t = mem.type; if (typeof t !== "function") return null; const mt = t.call(mem); if (!mt || typeof mt.maximum !== "number") return null; return mt.maximum * PAGE_SIZE; } catch { return null; } } function classifyUserMemoryGrowBound(requestedBytes, maximumBytes) { if (requestedBytes > WASM32_MEMORY_MAX_BYTES) return "wasm32-address-space"; if (maximumBytes !== null && requestedBytes > maximumBytes) return "user-max"; return "host-commit"; } var KERNEL_SAB_INITIAL_BYTES = 64 * 1024 * 1024; var mib = (b) => (b / (1024 * 1024)).toFixed(1); function describeUserMemoryGrowRefusal(r) { const head = `user_memory grow REFUSED for pid ${r.pid} (${r.what}): needs ${mib(r.requestedBytes)} MiB (${r.requestedBytes} B), has ${mib(r.currentBytes)} MiB (${r.currentBytes} B)`; const notTheMachine = `This is a PER-PROCESS limit on a wasm32 single WebAssembly.Memory, NOT the machine running out of RAM: the machine's RAM is an aggregate spread over the kernel SAB plus one SAB per process, and the other processes are unaffected. The guest sees ENOMEM from this one process.`; switch (r.boundBy) { case "wasm32-address-space": return `${head}, bounded by the WASM32 ADDRESS SPACE. One WebAssembly.Memory is at most ${mib(WASM32_MEMORY_MAX_BYTES)} MiB (4 GiB, the entire i32 address space) and no setting raises it \u2014 a 64-bit memory would. ${notTheMachine} Fix: split the work across processes, or lower this process's peak footprint.`; case "user-max": return `${head}, bounded by THIS MEMORY'S DECLARED MAXIMUM of ${r.maximumBytes === null ? "(unknown)" : `${mib(r.maximumBytes)} MiB`} (PhysRam userMaxBytes). That is a configured per-process cap, well under the ${mib(WASM32_MEMORY_MAX_BYTES)} MiB wasm32 ceiling. ${notTheMachine} Fix: raise userMaxBytes for this machine.`; case "host-commit": return `${head}, and it was NOT a declared cap: the request fits this Memory's maximum (${r.maximumBytes === null ? "not introspectable here" : `${mib(r.maximumBytes)} MiB`}) and fits the ${mib(WASM32_MEMORY_MAX_BYTES)} MiB wasm32 ceiling, so the HOST refused to commit the pages. This one IS an out-of-memory condition, but of the browser tab / Node process, not of the guest's declared RAM. Fix: free memory on the host, or run a smaller machine.`; } } var PhysRam = class { opts; /** * Shared kernel memory. Imported by every wasm module as * `env.kernel_memory`. Backed by a SharedArrayBuffer so the main * thread + every Worker can memcpy into it directly without going * through a wasm export. */ kernelMemory; constructor(opts) { if (!Number.isFinite(opts.kernelBytes) || opts.kernelBytes <= 0) throw new Error( `PhysRam: kernelBytes must be a positive byte count (got ${String(opts.kernelBytes)}). This is the machine's physical RAM \u2014 there is no default, because a default is how a machine ends up booting 256 MiB while its spec says otherwise.` ); if (opts.kernelMaxBytes !== opts.kernelBytes) throw new Error( `PhysRam: kernelMaxBytes (${opts.kernelMaxBytes}) must equal kernelBytes (${opts.kernelBytes}); both name the kernel SAB's SPAN. The initial commit is kernelInitBytes, which is a different, smaller number.` ); const kernelInitBytes = Math.min( opts.kernelInitBytes ?? KERNEL_SAB_INITIAL_BYTES, opts.kernelBytes ); if (!Number.isFinite(kernelInitBytes) || kernelInitBytes <= 0) throw new Error( `PhysRam: kernelInitBytes must be a positive byte count (got ${String(opts.kernelInitBytes)}).` ); const declaredMemoryBytes = opts.declaredMemoryBytes ?? opts.kernelBytes; if (!Number.isFinite(declaredMemoryBytes) || declaredMemoryBytes < opts.kernelBytes) throw new Error( `PhysRam: declaredMemoryBytes (${String(opts.declaredMemoryBytes)}) is not a machine size at or above kernelBytes (${opts.kernelBytes}). The declared figure is the AGGREGATE \u2014 the kernel SAB plus the per-process user SABs \u2014 so it cannot be smaller than the kernel SAB alone. Omit it entirely to mean "this machine is exactly its kernel SAB".` ); this.opts = { /* * INITIAL < MAXIMUM, AND THAT IS THE WHOLE POINT. * * WHAT THIS REPLACED, AND WHY. Until 2026-08-09 the two were pinned * equal and the note here gave three reasons. The measured cost of * that pinning, in Chrome on a 2048 MiB machine: `system / * JSArrayBufferData` ~2.4 GB and ~3 GB for the tab against a ~240 MB * JS heap — i.e. the SharedArrayBuffer backing store, genuinely * allocated, for memory the guest had never touched. V8 marks exactly * `initial` rw-p and leaves `maximum - initial` at PROT_NONE, so * lowering `initial` is what removes the charge (and on Chrome for * Windows, where wasm memory's initial goes through * VirtualAlloc(MEM_COMMIT), it is charged against the system commit * limit before first touch — there it is not even lazy). * * All three old reasons are now retired, each by a change, not by a * shrug: * * (a) THE CARVE IS ONE-SHOT — it still is, but it no longer sits at * the TOP. kernelWorker.mjs carves the device MMIO windows and * the DRM scanout UP from a fixed LOW base immediately above * the kernel image, below usable_start. Those addresses do not * move when the memory grows, because growth only ever adds * pages at the top. * * (b) grow() HANDS BACK A NEW SharedArrayBuffer OBJECT — it does, * and MEASURED (Node v24 / V8): the OLD buffer is NOT detached. * It still aliases the same physical bytes, for plain writes and * for Atomics alike; only its byteLength is frozen at the old * value. So a stale snapshot reads and writes CORRECT bytes and * can only fail by addressing PAST what it captured. Everything * the host addresses at a FIXED offset (boot_info, the device * windows, the scheduler/tick/irq words, the spawn and signal * rings) is in the low prefix and is unaffected. The consumers * that address ARBITRARY guest physical pages — the virtio * backends, which follow descriptors into page-cache frames — * re-derive their views from the WebAssembly.Memory when the * buffer identity changes; see `kernelMemoryWasm` on each * backend and the `kernel-mem-grown` message in bootKernel.ts. * * (c) FLATMEM SIZES mem_map ONCE — it does, and it is now sized for * the FULL SPAN, not for the committed prefix. boot_info's * total_memory carries the span; the kernel memblock_add()s all * of it (so pfn_valid / pfn_to_page / max_mapnr are right for * every frame the memory can ever hold) and memblock_reserve()s * the not-yet-committed tail so the buddy allocator can never * hand out a frame the host has not committed. mem_map costs * 0.78% of the span (32-byte struct page / 4 KiB page): 16 MiB * on a 2 GiB machine, against the 2 GiB it saves. * * WHY THE KERNEL AND NOT THE HOST DRIVES GROWTH: wasm has no * recoverable memory fault. An out-of-bounds access traps the module * unresumably — there is no trap-and-grow. So the commit must happen * BEFORE anything touches the page, which only the guest's allocator * is in a position to know. arch/wasm32/mm/memcommit.c watches the * buddy free count and calls linux.mem_commit() when it drops below a * watermark; kernelWorker.mjs services that with kernelMemory.grow(). * When the grow is refused at the maximum the guest gets a normal * -ENOMEM / OOM kill, which is what a real machine out of RAM does. */ kernelBytes: opts.kernelBytes, kernelMaxBytes: opts.kernelMaxBytes, kernelInitBytes, /* A-5.a: small-initial per-process user_memory. The SAB grows on * demand (mmap grow-on-demand + spawn-time grow-to-fit in * kernelSpawnHandler), so 2 MiB initial is enough to boot+nest bash; * per-process footprint collapses to ~(image footprint + actual use) * instead of a fixed 64 MiB. * userMaxBytes: a per-process user SAB reserves its `maximum` of address * space up front (shared memory cannot grow-reallocate, so the max is the * reservation); 1 GiB x N processes is a huge reservation and no demo * allocates >256 MiB/proc (nested bash ~12 MiB each). 256 MiB ceiling is * ample and the grow-to-fit + mmap-grow paths only -ENOMEM if a partition * exceeds it (won't for these workloads). Was 1 GiB. */ userInitBytes: opts.userInitBytes ?? 2 * 1024 * 1024, userMaxBytes: opts.userMaxBytes ?? 256 * 1024 * 1024, declaredMemoryBytes }; this.kernelMemory = new WebAssembly.Memory({ initial: pages(this.opts.kernelInitBytes), maximum: pages(this.opts.kernelMaxBytes), shared: true }); } /* * THE LIVE USER-SAB TOTAL, PUBLISHED TO THE KERNEL. * * The guest reports the machine's AGGREGATE RAM as MemTotal, so MemFree has * to move with it or an idle 8 GB machine reads ~5 GB used and `free -m` * lies worse than it did when MemTotal was just the kernel SAB. The used * figure the kernel needs is kernel-SAB used PLUS the live per-process * user-SAB bytes — and only the host knows the second half, because the * kernel never maps a user SAB (asm/pgtable.h). * * The transport is the port's existing host->kernel scalar convention, not * a new one: the kernel defines a word in .data, `--export=` in * scripts/link-vmlinux.sh turns it into an immutable i32 global holding the * word's kernel_memory offset, kernelWorker.mjs reads `.value` once and * posts it here, and from then on this is an `Atomics.store` into the * kernel SAB. Identical in shape to wasm32_tick_req and * wasm32_virtio_irq_pending. * * UNITS ARE 4 KiB GUEST PAGES, not bytes and not 64 KiB wasm pages. One u32 * of 4 KiB pages covers 16 TiB, four times the kernel's accounting ceiling, * and it fits a single atomic store — a 64-bit byte count written as two * words could tear, and the kernel reads this without a lock. */ userSabPagesWord = null; userSabPagesIndex = 0; /** * Point the publisher at the kernel's exported `wasm32_user_sab_pages` word. * `offset` is the byte offset the kernel export reported. Called once, from * the `user-sab-pages-offset` message bootKernel.ts receives at instantiate. * * A kernel built before boot ABI v4 has no such export and never sends the * message, so the publisher stays null and every call below is a no-op — * which is exactly right: that kernel also reports no aggregate. */ attachUserSabPagesWord(buffer, offset) { if (!Number.isInteger(offset) || offset <= 0 || offset % 4 !== 0) throw new Error( `PhysRam: wasm32_user_sab_pages offset ${String(offset)} is not a positive 4-byte-aligned kernel_memory offset; refusing to publish the machine's live user-SAB total into an address the kernel did not name.` ); this.userSabPagesWord = new Int32Array(buffer); this.userSabPagesIndex = offset >> 2; this.publishUserSabPages(); } /** * Recompute the live per-process user-SAB commitment and publish it. * * Cheap by construction (a ledger sweep of live WeakRefs) and called from * both directions: eagerly at every ledger mutation below, and on the * main thread's existing ~12 ms scheduler-nudge interval, which is what * catches a plain `userMem.grow()` — a grow changes `buffer.byteLength` * without notifying this class, so an event-only publisher would go stale * exactly when a process is allocating hardest. */ publishUserSabPages() { const w = this.userSabPagesWord; const t = this.userSabPidTable; if (w === null && t === null) return; let bytes = 0; const perPid = t === null ? null : /* @__PURE__ */ new Map(); for (const e of this.userMemLedger) { const m = e.ref.deref(); if (m === void 0) continue; if (e.state !== "live") continue; const len = m.buffer.byteLength; bytes += len; if (perPid !== null && e.pid > 0 && e.pid < this.userSabPidSlots) { const inUse = this.userMemoryInUse?.(m) ?? len - e.heldFreeBytes; perPid.set(e.pid, { size: Math.floor(len / 4096), resident: Math.floor(Math.min(len, Math.max(0, inUse)) / 4096), max: Math.floor(e.maxBytes / 4096) }); } } if (w !== null) { const guestPages = Math.floor(bytes / 4096); Atomics.store(w, this.userSabPagesIndex, guestPages | 0); } if (t !== null && perPid !== null) this.publishUserSabPidFigures(t, perPid); } /* * THE SAME FIGURE PER PROCESS, for /proc//{statm,status,stat}. * * No process task has an mm describing its user SAB, so these are the only * per-process memory figures the kernel has. The kernel exports a table of * u32 pairs indexed by tgid (`wasm32_user_sab_pid_pages`) and its slot count * (`wasm32_user_sab_pid_slots`). A pair is [size, resident] in 4 KiB pages: * size is the SAB's byteLength; resident is what the process holds in it, * from the spawn handler's allocator (its bump less its free lists), so it * follows each mmap and munmap while the SAB, which cannot shrink, only * grows. Without that resolver resident is the byteLength less * `heldFreeBytes`. Only labelled live entries are published, and a slot * whose process is gone is zeroed. A kernel without the exports never sends * the offsets, and the table stays null. */ userSabPidTable = null; userSabPidTableIndex = 0; /* The kernel reports this table as RLIMIT_AS; -1 when it has none. */ userSabPidMaxIndex = -1; userSabPidSlots = 0; userSabPidPublished = /* @__PURE__ */ new Map(); userMemoryInUse = null; /** Where the per-process resident figure comes from; see above. */ setUserMemoryInUseResolver(f) { this.userMemoryInUse = f; this.publishUserSabPages(); } /** * Point the per-process publisher at the kernel's exported table. * `offset` and `slotsOffset` are the byte offsets of * `wasm32_user_sab_pid_pages` and `wasm32_user_sab_pid_slots`, from the * `user-sab-pid-table-offset` message bootKernel.ts receives at instantiate. */ attachUserSabPidTable(buffer, offset, slotsOffset, maxOffset) { const named = [ ["wasm32_user_sab_pid_pages", offset], ["wasm32_user_sab_pid_slots", slotsOffset] ]; if (maxOffset !== void 0) named.push(["wasm32_user_sab_pid_max", maxOffset]); for (const [name2, off] of named) if (!Number.isInteger(off) || off <= 0 || off % 4 !== 0) throw new Error( `PhysRam: ${name2} offset ${String(off)} is not a positive 4-byte-aligned kernel_memory offset; refusing to publish per-process user-SAB figures into an address the kernel did not name.` ); const w = new Int32Array(buffer); const slots = Atomics.load(w, slotsOffset >> 2) >>> 0; if (slots === 0 || offset + slots * 8 > w.byteLength || maxOffset !== void 0 && maxOffset + slots * 4 > w.byteLength) throw new Error( `PhysRam: wasm32_user_sab_pid_slots reads ${String(slots)}, which does not fit a table at ${String(offset)}` + (maxOffset !== void 0 ? ` and one at ${String(maxOffset)}` : ``) + ` in a ${String(w.byteLength)}-byte kernel_memory; refusing to publish per-process user-SAB figures past it.` ); this.userSabPidTable = w; this.userSabPidTableIndex = offset >> 2; this.userSabPidMaxIndex = maxOffset === void 0 ? -1 : maxOffset >> 2; this.userSabPidSlots = slots; this.publishUserSabPages(); } /* Size before resident, and size alone to clear: the kernel reads size * first, treats 0 as "nothing published", and clamps resident to size. */ publishUserSabPidFigures(t, now) { const base = this.userSabPidTableIndex; const maxBase = this.userSabPidMaxIndex; for (const pid of this.userSabPidPublished.keys()) if (!now.has(pid)) { Atomics.store(t, base + 2 * pid, 0); Atomics.store(t, base + 2 * pid + 1, 0); if (maxBase >= 0) Atomics.store(t, maxBase + pid, 0); } for (const [pid, f] of now) { const was = this.userSabPidPublished.get(pid); if (maxBase >= 0 && was?.max !== f.max) Atomics.store(t, maxBase + pid, f.max | 0); if (was !== void 0 && was.size === f.size && was.resident === f.resident) continue; Atomics.store(t, base + 2 * pid, f.size | 0); Atomics.store(t, base + 2 * pid + 1, f.resident | 0); } this.userSabPidPublished = now; } /* hardwarejs#7: the user-memory ledger (WeakRefs only — never retains). */ userMemLedger = /* @__PURE__ */ new Set(); userMemEntryByMem = /* @__PURE__ */ new WeakMap(); userMemCollected = 0; /* * Exited processes' user memories, kept for the next allocation of the same * maximum. A SAB's backing store is released only when every realm that * saw it has run a GC, which a fork-heavy guest outpaces by gigabytes; * reusing the exited memory means the next fork allocates nothing. */ userMemPool = []; userMemPoolBytes = 0; userMemReused = 0; userMemPoolLimits() { const raw = globalThis.process?.env?.HWJS_USER_MEM_POOL; const v = raw !== void 0 ? parseInt(raw, 10) : NaN; const count = Number.isFinite(v) && v >= 0 ? v : USER_MEM_POOL_COUNT; return { count, bytes: count * USER_MEM_POOL_BYTES_PER_ENTRY }; } /** * Allocate a per-process user memory (env.user_memory), zero-filled. * `overwriteBytes` is a prefix the caller overwrites at once (a fork copy); * a reused memory is then zeroed only above it, and only as far as its last * owner can have written it (`recycleUserMemory`'s `dirtyBytes`). Without a * prefix, a reused memory is zeroed whole. */ allocUserMemory(initBytes = this.opts.userInitBytes, maxBytesArg, overwriteBytes = 0) { let maxBytes = maxBytesArg ?? this.opts.userMaxBytes; const reused = this.takePooledUserMemory(initBytes, maxBytes, overwriteBytes); if (reused) return reused; let mem; for (; ; ) { try { mem = new WebAssembly.Memory({ initial: pages(initBytes), maximum: pages(maxBytes), shared: true }); break; } catch (e) { const lower = Math.max(maxBytes / 2, USER_MAX_FLOOR_BYTES); if (maxBytesArg !== void 0 || !(e instanceof RangeError) || maxBytes <= USER_MAX_FLOOR_BYTES || pages(initBytes) > pages(lower)) throw e; console.warn( `PhysRam: the host refused a ${mib(maxBytes)} MiB per-process memory (${e.message}); trying ${mib(lower)} MiB.` ); maxBytes = lower; } } if (maxBytesArg === void 0 && maxBytes !== this.opts.userMaxBytes) { console.warn(`PhysRam: new processes get ${mib(maxBytes)} MiB from now on.`); this.lowerUserMax(maxBytes); } const entry = { ref: new WeakRef(mem), state: "live", pid: 0, heldFreeBytes: 0, freedBytes: 0, maxBytes }; this.userMemLedger.add(entry); this.userMemEntryByMem.set(mem, entry); this.publishUserSabPages(); return mem; } /* Pooled memories keep their old, larger reservations: drop them so the * address space that ran short can be released. */ lowerUserMax(maxBytes) { this.opts.userMaxBytes = maxBytes; for (let i = this.userMemPool.length - 1; i >= 0; i--) { const mem = this.userMemPool[i]; const e = this.userMemEntryByMem.get(mem); if (e && e.maxBytes === maxBytes) continue; this.userMemPool.splice(i, 1); this.userMemPoolBytes -= mem.buffer.byteLength; if (e) e.state = "exited"; } } /** * A fork child's user memory: the parent's maximum, so the child keeps the * parent's cap, and never smaller than what the parent already uses. When * the host refuses the parent's maximum, the default serves if the parent * fits it; otherwise this throws and the fork answers ENOMEM. */ allocForkUserMemory(parent, overwriteBytes) { const need = parent.buffer.byteLength; const parentMax = this.userMemoryMaximumBytes(parent) ?? this.opts.userMaxBytes; let mem; if (parentMax !== this.opts.userMaxBytes) { try { mem = this.allocUserMemory(void 0, parentMax, overwriteBytes); } catch (e) { if (!(e instanceof RangeError)) throw e; } } mem ??= this.allocUserMemory(void 0, void 0, overwriteBytes); const max = this.userMemoryMaximumBytes(mem); if (max !== null && max < need) { const e = this.userMemEntryByMem.get(mem); if (e) e.state = "exited"; throw new RangeError( `PhysRam: a fork child needs ${mib(need)} MiB, its parent's size, but the host gives at most ${mib(max)} MiB per process` ); } return mem; } takePooledUserMemory(initBytes, maxBytes, overwriteBytes) { const want = pages(initBytes) * PAGE_SIZE; for (let i = this.userMemPool.length - 1; i >= 0; i--) { const mem = this.userMemPool[i]; const e = this.userMemEntryByMem.get(mem); if (!e || e.maxBytes !== maxBytes || mem.buffer.byteLength < want) continue; this.userMemPool.splice(i, 1); this.userMemPoolBytes -= mem.buffer.byteLength; const buf = mem.buffer; const from = Math.min(Math.max(0, overwriteBytes), buf.byteLength); const to = from > 0 ? Math.min(e.dirtyBytes ?? buf.byteLength, buf.byteLength) : buf.byteLength; if (to > from) zeroMemory(mem, from, to - from); if (to > from && globalThis.process?.env?.D1_TRACE_MEM) { globalThis.process.stderr.write( `[D1_TRACE_MEM] zero pool-reuse ${to - from} B ` ); } e.dirtyBytes = void 0; e.state = "live"; e.pid = 0; e.heldFreeBytes = 0; this.userMemReused++; this.publishUserSabPages(); return mem; } return null; } /** * Offer an EXITED process's user memory for reuse. The caller guarantees * nothing will touch it again: every host-side record keyed by it has been * dropped and no thread of the process can still be running on it. * Returns false when the pool is full or the memory is not ours to reuse, * in which case the memory is left to engine GC exactly as before. * `dirtyBytes` is how far the process can have written it (the spawn * handler's bump high-water); without it the whole memory is zeroed on reuse. */ recycleUserMemory(mem, dirtyBytes) { const e = this.userMemEntryByMem.get(mem); if (!e || e.state !== "exited" || e.maxBytes !== this.opts.userMaxBytes) return false; const lim = this.userMemPoolLimits(); const size = mem.buffer.byteLength; if (this.userMemPool.length >= lim.count || this.userMemPoolBytes + size > lim.bytes) return false; e.state = "pooled"; e.dirtyBytes = dirtyBytes === void 0 || !(dirtyBytes >= 0) ? void 0 : Math.min(dirtyBytes, size); this.userMemPool.push(mem); this.userMemPoolBytes += size; return true; } /** * The declared `maximum`, in bytes, of a per-process user memory — the * ceiling a grow refusal must name. Answers from the ledger (recorded at * construction, always exact), then from engine type reflection for a * Memory this PhysRam did not allocate (a fork-copy child), then null. */ userMemoryMaximumBytes(mem) { const e = this.userMemEntryByMem.get(mem); if (e) return e.maxBytes; return reflectUserMemoryMaximumBytes(mem); } /** hardwarejs#7: label a user memory with its kernel pid once known. */ noteUserMemoryOwner(mem, pid) { const e = this.userMemEntryByMem.get(mem); if (e) e.pid = pid | 0; this.publishUserSabPages(); } /** * hardwarejs#7: mark a user memory's owning process EXITED. Purely * observational (the actual reclaim is the reference drops in * kernelSpawnHandler's exit teardown + the owning Worker realm); an * entry still deref-able while 'exited' is a zombie SAB whose size * still counts against the tab — exactly the arithmetic a failing * late-session grow() needs to report. */ noteUserMemoryExited(mem) { const e = this.userMemEntryByMem.get(mem); if (e && e.state === "live") e.state = "exited"; this.publishUserSabPages(); } /** * A guest process freed `bytes` THROUGH THE KERNEL (munmap, brk step down, * exit). The host cannot return them — SABs do not shrink — so record them * as committed-but-unused. See UserMemoryStats' freed-but-unreclaimable * block for why this is accounting and not a reclaim. * * Callers pass the NET new free bytes (after the free list's overlap merge), * never the raw munmap length: a double-unmap is a POSIX no-op and must not * inflate the ledger into claiming memory that was already free. */ noteUserMemoryFreed(mem, bytes) { if (!(bytes > 0)) return; const e = this.userMemEntryByMem.get(mem); if (!e) return; e.heldFreeBytes += bytes; e.freedBytes += bytes; } /** * The process took `bytes` back out of its own free list (a later mmap * recycled a munmap'd range). Those bytes are live again, so they stop * being a shrink candidate — without this the ledger would ratchet and * every long-running process would look permanently reclaimable. */ noteUserMemoryReused(mem, bytes) { if (!(bytes > 0)) return; const e = this.userMemEntryByMem.get(mem); if (!e) return; e.heldFreeBytes = Math.max(0, e.heldFreeBytes - bytes); } /** hardwarejs#7: sweep the ledger and report the honest arithmetic. */ userMemoryStats() { let liveCount = 0, livePages = 0; let exitedUncollectedCount = 0, exitedUncollectedPages = 0; let pooledCount = 0, pooledPages = 0; let heldFreeBytes = 0, cumulativeFreedBytes = 0; const reclaimCandidates = []; for (const e of this.userMemLedger) { const m = e.ref.deref(); if (m === void 0) { this.userMemLedger.delete(e); this.userMemCollected++; continue; } const p = Math.floor(m.buffer.byteLength / PAGE_SIZE); cumulativeFreedBytes += e.freedBytes; if (e.state === "live") { liveCount++; livePages += p; heldFreeBytes += e.heldFreeBytes; if (e.heldFreeBytes > 0) reclaimCandidates.push({ pid: e.pid, sizeBytes: m.buffer.byteLength, heldFreeBytes: e.heldFreeBytes }); } else if (e.state === "pooled") { pooledCount++; pooledPages += p; } else { exitedUncollectedCount++; exitedUncollectedPages += p; } } reclaimCandidates.sort((a, b) => b.heldFreeBytes - a.heldFreeBytes); this.publishUserSabPages(); return { liveCount, livePages, exitedUncollectedCount, exitedUncollectedPages, collectedCount: this.userMemCollected, pooledCount, pooledPages, reusedCount: this.userMemReused, kernelPages: Math.floor(this.kernelMemory.buffer.byteLength / PAGE_SIZE), userMaxPages: pages(this.opts.userMaxBytes), userInitPages: pages(this.opts.userInitBytes), heldFreeBytes, cumulativeFreedBytes, reclaimCandidates }; } /** * The kernel SAB's CURRENTLY COMMITTED size in bytes — what the tab is * paying for right now, which since demand commit landed is NOT the * machine's kernel RAM. That is `opts.kernelBytes`, the span the memory may * grow to; this is how much of it the host has actually committed. Read * live from the Memory every call, because the agent that grows it (the * kernel Worker, or any process Worker running kernel code) never tells * this object. */ get kernelSize() { return this.kernelMemory.buffer.byteLength; } }; function pages(bytes) { return Math.ceil(bytes / PAGE_SIZE); } // ../../linux-in-the-browser/hardwarejs/src/ipc.ts var CTRL_WORDS = 16; var CTRL_BYTES = CTRL_WORDS * 4; // ../../linux-in-the-browser/hardwarejs/src/syscall-nr.ts var SYS = { read: 0, write: 1, open: 2, close: 3, stat: 4, fstat: 5, lstat: 6, poll: 7, lseek: 8, mmap: 9, mprotect: 10, munmap: 11, brk: 12, rt_sigaction: 13, rt_sigprocmask: 14, rt_sigreturn: 15, ioctl: 16, pread64: 17, pwrite64: 18, readv: 19, writev: 20, access: 21, pipe: 22, select: 23, sched_yield: 24, dup: 32, dup2: 33, nanosleep: 35, getpid: 39, clone: 56, fork: 57, vfork: 58, execve: 59, exit: 60, wait4: 61, kill: 62, uname: 63, fcntl: 72, getcwd: 79, chdir: 80, mkdir: 83, rmdir: 84, link: 86, unlink: 87, symlink: 88, readlink: 89, chmod: 90, fchmod: 91, chown: 92, fchown: 93, lchown: 94, getuid: 102, getgid: 104, geteuid: 107, getegid: 108, arch_prctl: 158, gettid: 186, set_tid_address: 218, clock_gettime: 228, clock_nanosleep: 230, exit_group: 231, mknod: 133, newfstatat: 262, openat: 257, mkdirat: 258, mknodat: 259, fchownat: 260, unlinkat: 263, linkat: 265, symlinkat: 266 }; var SYSCALL_NAME = Object.fromEntries( Object.entries(SYS).map(([k, v]) => [v, k]) ); // ../../linux-in-the-browser/hardwarejs/src/spawn.ts var __ctrlState = 0 /* IDLE */ | 1 /* REQUEST */ | 2 /* RESPONSE */ | 0 /* STATE */; // ../../linux-in-the-browser/hardwarejs/src/wasmBootPreflight.ts var HDR = [0, 97, 115, 109, 1, 0, 0, 0]; var WASM_BOOT_FEATURE_PROBES = [ { id: "shared-memory (threads)", why: "env.kernel_memory is one shared Memory attached by the kernel Worker and every process Worker", supportNote: "requires the wasm threads proposal (universal since ~2021; needs crossOriginIsolated)", /* (module (memory 1 1 shared)) — memory section, limits flags 0x03 = * has-max | shared. */ bytes: new Uint8Array([...HDR, 5, 4, 1, 3, 1, 1]) }, { id: "bulk-memory", why: "kernel memcpy/memset lower to memory.copy/memory.fill", supportNote: "universal since ~2021", /* (module (memory 1) (func (memory.copy (i32.const 0) (i32.const 0) * (i32.const 0)))) */ bytes: new Uint8Array([ ...HDR, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 3, 1, 0, 1, 10, 14, 1, 12, 0, 65, 0, 65, 0, 65, 0, 252, 10, 0, 0, 11 ]) }, { id: "simd128", why: "user programs are compiled with fixed-width SIMD; without it every exec fails", supportNote: "Chrome 91+, Firefox 89+, Safari 16.4+", /* (module (func (drop (v128.const i32x4 0 0 0 0)))) */ bytes: new Uint8Array([ ...HDR, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 23, 1, 21, 0, 253, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 26, 11 ]) } /* (RETIRED) "multi-memory": vmlinux.wasm used to import TWO memories * (env.kernel_memory + env.user_memory) and copy across them — the * shape WebKit/Safari rejects (the original #68 iPadOS silent boot * death). The single-memory boundary collapse removed the second * memory, so the probe is gone: WebKit engines now pass preflight. */ ]; function preflightWasmBootSupport(validate = (b) => WebAssembly.validate(b)) { const missing = []; for (const probe of WASM_BOOT_FEATURE_PROBES) { let pass = false; try { pass = validate(probe.bytes); } catch { pass = false; } if (!pass) missing.push({ id: probe.id, why: probe.why, supportNote: probe.supportNote }); } if (missing.length === 0) return { ok: true, missing, message: "" }; const lines = [ `REFUSING to boot: this browser's WebAssembly engine lacks ${missing.length} feature(s) vmlinux.wasm or its programs require \u2014 nothing was started (linux-in-the-browser#68).`, ...missing.map((m) => ` - ${m.id}: ${m.why}. [${m.supportNote}]`), `Without these the engine rejects the kernel image or its programs at WebAssembly.compile, before any Worker or console exists. Use a browser whose engine supports the listed features (desktop/Android Chrome 120+, Edge 120+, Firefox 125+).` ]; return { ok: false, missing, message: lines.join("\n") }; } // ../../linux-in-the-browser/hardwarejs/src/display-slot-abi.ts var WASM32_DISPLAY_SLOTS = 8; var DISPLAY_SLOT_BYTES = 48; var DS = { /** host: (maxh << 16) | maxw to plug; 0 to unplug */ PLUG_REQ: 0, /** host: bumped after each PLUG_REQ store */ PLUG_SEQ: 4, /** guest: PLUG_SEQ last carried out */ PLUG_ACK: 8, /** guest: 1 plugged, 0 absent, -errno: the last plug failed */ STATE: 12, /** guest: scanout byte offset in kernel memory, or 0 */ BASE: 16, /** guest: bytes per scanout row */ STRIDE: 20, /** guest: (maxh << 16) | maxw allocated */ MAXDIM: 24, /** guest: (drm card << 16) | fb; 0xffffffff when absent */ MINORS: 28, /** the display's mode protocol: wasm32_display_ctrl_words {req, applied, seq, ack} */ CTRL: 32 }; var DISPLAY_SLOT_FORMAT = "a8b8g8r8"; // ../../linux-in-the-browser/hardwarejs/src/workerRealms.ts var created = 0; var terminated = 0; var live = 0; var peakLive = 0; var createdByOrigin = /* @__PURE__ */ Object.create(null); var liveByOrigin = /* @__PURE__ */ Object.create(null); var originOf = /* @__PURE__ */ new WeakMap(); function noteWorkerRealmCreated(worker, origin) { if (!worker || typeof worker !== "object") return; if (originOf.has(worker)) return; originOf.set(worker, origin); created++; live++; if (live > peakLive) peakLive = live; createdByOrigin[origin] = (createdByOrigin[origin] ?? 0) + 1; liveByOrigin[origin] = (liveByOrigin[origin] ?? 0) + 1; } function workerRealmOrigin(worker) { if (!worker || typeof worker !== "object") return void 0; return originOf.get(worker); } function noteWorkerRealmTerminated(worker) { if (!worker || typeof worker !== "object") return; const origin = originOf.get(worker); if (origin === void 0) return; originOf.delete(worker); terminated++; live = Math.max(0, live - 1); liveByOrigin[origin] = Math.max(0, (liveByOrigin[origin] ?? 0) - 1); } function workerRealmCensus() { return { live, created, terminated, peakLive, createdByOrigin: { ...createdByOrigin }, liveByOrigin: { ...liveByOrigin } }; } // ../../linux-in-the-browser/hardwarejs/src/mergedDoorbell.ts var drains = /* @__PURE__ */ new Set(); function registerSyncDeviceDrain(fn2) { drains.add(fn2); return () => { drains.delete(fn2); }; } function runSyncDeviceDrain() { if (drains.size === 0) return; for (const fn2 of drains) { try { fn2(); } catch { } } } // ../../linux-in-the-browser/hardwarejs/src/spawn-ring-abi.ts var WASM_SPAWN_FORK = 0; var WASM_SPAWN_THREAD = 1; var WASM_SPAWN_NEEDED_LIB = 2; var WASM_SPAWN_FLAG_SCATTER_IMAGE = 1 << 0; var SGSEG_SIZE = 8; var SGSEG_OFF_OFF = 0; var SGSEG_OFF_LEN = 4; function privateImageCopy(bytes) { return bytes.buffer instanceof SharedArrayBuffer ? bytes.slice() : bytes; } var sharedWasmSourceOk; function wasmSource(bytes) { if (!(bytes.buffer instanceof SharedArrayBuffer)) return bytes; if (sharedWasmSourceOk === void 0) { try { const probe = new Uint8Array(new SharedArrayBuffer(8)); probe.set([0, 97, 115, 109, 1, 0, 0, 0]); new WebAssembly.Module(probe); sharedWasmSourceOk = true; } catch { sharedWasmSourceOk = false; } } return sharedWasmSourceOk ? bytes : bytes.slice(); } var RETAINED_NAME = "hwjs.retained"; var RETAINED_MARKER_BYTES = 2 + 1 + RETAINED_NAME.length + 4 + 32; var RETAINED_DATA_NAME = "hwjs.retained.data"; var RETAINED_DATA_BYTES = 2 + 1 + RETAINED_DATA_NAME.length + 4; var TABLE_WRITES_NAME = "hwjs.tablewrites"; var TABLE_WRITES_BYTES = 2 + 1 + TABLE_WRITES_NAME.length + 1; var TABLE_WRITES_CODES = ["none", "writes", "unknown"]; function dataSectionSegmentBytes(b, p, end) { const u32 = () => { let r = 0, shift = 0, byte = 0; do { if (p >= end) throw new Error("hwjs-libc: retained copy: a data section LEB runs past the section (never-silent)"); byte = b[p++]; r |= (byte & 127) << shift; shift += 7; } while (byte & 128); return r >>> 0; }; const count = u32(); let total = 0; for (let i = 0; i < count; i++) { const flags = u32(); if (flags === 2) u32(); if (flags === 0 || flags === 2) { for (; ; ) { if (p >= end) throw new Error("hwjs-libc: retained copy: an unterminated data offset expression (never-silent)"); const op = b[p++]; if (op === 11) break; if (op === 65 || op === 66 || op === 35) u32(); else if (!(op >= 106 && op <= 108 || op >= 124 && op <= 126)) { throw new Error(`hwjs-libc: retained copy: opcode 0x${op.toString(16)} in a data segment's offset expression (never-silent)`); } } } else if (flags !== 1) { throw new Error(`hwjs-libc: retained copy: data segment ${i} has flags ${flags} (never-silent)`); } const len = u32(); p += len; if (p > end) throw new Error(`hwjs-libc: retained copy: data segment ${i} runs past the data section (never-silent)`); total += len; } return total; } function scanTableWrites(b, detail = null) { const n = b.length; const stop = (verdict, op, at) => { if (detail) { detail.op = op; detail.at = at; } return verdict; }; if (n < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) return stop("unknown", "not wasm", 0); let p = 8; const u = () => { let r = 0, s = 0, x; do { if (p >= n) throw new RangeError("truncated"); x = b[p++]; r += (x & 127) * 2 ** s; s += 7; } while (x & 128); return r; }; const skip = () => { for (; ; ) { if (p >= n) throw new RangeError("truncated"); if (!(b[p++] & 128)) return; } }; const memarg = () => { const a = u(); if (a & 64) skip(); skip(); }; const valtype = () => { const x = b[p++]; if (x === 99 || x === 100) skip(); }; const blocktype = () => { const x = b[p]; if (x === 99 || x === 100) { p++; skip(); return; } if (x >= 64 && x <= 127) { p++; return; } skip(); }; try { let codeStart = -1, codeEnd = -1; while (p < n) { const id = b[p++]; const size = u(); const end = p + size; if (end > n) return stop("unknown", "section past the end", p); if (id === 10) { codeStart = p; codeEnd = end; break; } p = end; } if (codeStart < 0) return "none"; p = codeStart; const count = u(); for (let f = 0; f < count; f++) { const size = u(); const bodyEnd = p + size; if (bodyEnd > codeEnd) return stop("unknown", "body past the code", p); const groups = u(); for (let g = 0; g < groups; g++) { skip(); valtype(); } let depth = 1; while (p < bodyEnd) { const at = p; const op = b[p++]; if (op === 11) { if (--depth === 0) break; continue; } if (op <= 1 || op === 5 || op === 10 || op === 15 || op === 25 || op === 26 || op === 27 || op >= 69 && op <= 196 || op === 209 || op === 211 || op === 212) continue; if (op === 2 || op === 3 || op === 4 || op === 6) { blocktype(); depth++; continue; } if (op === 31) { blocktype(); depth++; const c = u(); for (let i = 0; i < c; i++) { const k = b[p++]; if (k === 0 || k === 1) skip(); skip(); } continue; } if (op === 24) { skip(); depth--; continue; } if (op === 7 || op === 8 || op === 9 || op === 12 || op === 13 || op === 16 || op === 18 || op === 20 || op === 21 || op >= 32 && op <= 37 || op === 210 || op === 213 || op === 214 || op === 63 || op === 64 || op === 65 || op === 66) { skip(); continue; } if (op === 14) { const c = u(); for (let i = 0; i <= c; i++) skip(); continue; } if (op === 17 || op === 19) { skip(); skip(); continue; } if (op === 28) { const c = u(); for (let i = 0; i < c; i++) valtype(); continue; } if (op === 38) return stop("writes", "0x26", at); if (op >= 40 && op <= 62) { memarg(); continue; } if (op === 67) { p += 4; continue; } if (op === 68) { p += 8; continue; } if (op === 208) { const x = b[p]; if (x >= 64 && x <= 127) p++; else skip(); continue; } if (op === 251) { const s = u(); if (s <= 1 || s === 6 || s === 7 || s >= 11 && s <= 14 || s === 16) { skip(); continue; } if (s >= 2 && s <= 5 || s >= 8 && s <= 10 || s >= 17 && s <= 19) { skip(); skip(); continue; } if (s === 15 || s >= 26 && s <= 30) continue; if (s >= 20 && s <= 23) { skip(); continue; } if (s === 24 || s === 25) { p += 1; skip(); skip(); skip(); continue; } return stop("unknown", `0xfb ${s}`, at); } if (op === 252) { const s = u(); if (s <= 7) continue; if (s === 8 || s === 10) { skip(); skip(); continue; } if (s === 9 || s === 11 || s === 13 || s === 16) { skip(); continue; } if (s === 12 || s === 14 || s === 15 || s === 17) return stop("writes", `0xfc ${s}`, at); return stop("unknown", `0xfc ${s}`, at); } if (op === 253) { const s = u(); if (s <= 11 || s === 92 || s === 93) { memarg(); continue; } if (s === 12 || s === 13) { p += 16; continue; } if (s >= 21 && s <= 34) { p += 1; continue; } if (s >= 84 && s <= 91) { memarg(); p += 1; continue; } if (s <= 275) continue; return stop("unknown", `0xfd ${s}`, at); } if (op === 254) { const s = u(); if (s === 3) { p += 1; continue; } if (s <= 78) { memarg(); continue; } return stop("unknown", `0xfe ${s}`, at); } return stop("unknown", `0x${op.toString(16)}`, at); } if (depth !== 0 || p !== bodyEnd) return stop("unknown", "body end", p); } return p === codeEnd ? "none" : stop("unknown", "code end", p); } catch (_e) { return stop("unknown", "truncated", p); } } function isCustomSectionNamed(bytes, p, end, name2) { if (bytes[p] !== 0) return false; let q = p + 1; while (q < end && bytes[q] & 128) q++; q++; if (q >= end || bytes[q] !== name2.length) return false; for (let i = 0; i < name2.length; i++) { if (bytes[q + 1 + i] !== name2.charCodeAt(i)) return false; } return true; } function retainedLibraryInfo(bytes) { const n = bytes ? bytes.length : 0; if (n < 8 + RETAINED_MARKER_BYTES) return null; let p = n - RETAINED_MARKER_BYTES; if (bytes[p] !== 0 || bytes[p + 1] !== RETAINED_MARKER_BYTES - 2 || bytes[p + 2] !== RETAINED_NAME.length) return null; p += 3; for (let i = 0; i < RETAINED_NAME.length; i++) { if (bytes[p + i] !== RETAINED_NAME.charCodeAt(i)) return null; } p += RETAINED_NAME.length; const wireLength = (bytes[p] | bytes[p + 1] << 8 | bytes[p + 2] << 16 | bytes[p + 3] << 24) >>> 0; let digest = ""; for (let i = 0; i < 32; i++) digest += bytes[p + 4 + i].toString(16).padStart(2, "0"); return { wireLength, digest }; } function retainedLibraryBytes(bytes, digest, walkStop = null) { if (!/^[0-9a-f]{64}$/.test(digest)) { throw new Error(`hwjs-libc: retained copy: ${JSON.stringify(String(digest).slice(0, 80))} is not a SHA-256 (never-silent)`); } const n = bytes.length; if (n < 8 || bytes[0] !== 0 || bytes[1] !== 97 || bytes[2] !== 115 || bytes[3] !== 109) { throw new Error(`hwjs-libc: retained copy: ${digest.slice(0, 16)}\u2026 is not a wasm module (never-silent)`); } if (retainedLibraryInfo(bytes)) { throw new Error(`hwjs-libc: retained copy: ${digest.slice(0, 16)}\u2026 is a retained copy already (never-silent)`); } const keep = [[0, 8]]; let kept = 8; let dropped = 0; let dataBytes = null; let p = 8; while (p < n) { const id = bytes[p]; let q = p + 1; let size = 0; let mul = 1; for (; ; ) { if (q >= n) { throw new Error(`hwjs-libc: retained copy: ${digest.slice(0, 16)}\u2026: the section header at ${p} runs past the module (never-silent)`); } const b = bytes[q++]; size += (b & 127) * mul; mul *= 128; if (!(b & 128)) break; } const end = q + size; if (end > n) { throw new Error(`hwjs-libc: retained copy: ${digest.slice(0, 16)}\u2026: section ${id} at ${p} declares ${size}B, past the module's ${n}B (never-silent)`); } if (id === 11) dataBytes = dataSectionSegmentBytes(bytes, q, end); if (id === 10 || id === 11) { dropped += end - p; } else if (isCustomSectionNamed(bytes, p, end, TABLE_WRITES_NAME)) { } else { keep.push([p, end]); kept += end - p; } p = end; } if (dropped === 0) { const whole = new Uint8Array(new SharedArrayBuffer(n)); whole.set(bytes); return whole; } const dataRecord = dataBytes === null ? 0 : RETAINED_DATA_BYTES; const out = new Uint8Array(new SharedArrayBuffer( kept + dataRecord + TABLE_WRITES_BYTES + RETAINED_MARKER_BYTES )); let at = 0; for (const [from, to] of keep) { out.set(bytes.subarray(from, to), at); at += to - from; } if (dataBytes !== null) { out[at++] = 0; out[at++] = RETAINED_DATA_BYTES - 2; out[at++] = RETAINED_DATA_NAME.length; for (let i = 0; i < RETAINED_DATA_NAME.length; i++) out[at++] = RETAINED_DATA_NAME.charCodeAt(i); out[at++] = dataBytes & 255; out[at++] = dataBytes >>> 8 & 255; out[at++] = dataBytes >>> 16 & 255; out[at++] = dataBytes >>> 24 & 255; } out[at++] = 0; out[at++] = TABLE_WRITES_BYTES - 2; out[at++] = TABLE_WRITES_NAME.length; for (let i = 0; i < TABLE_WRITES_NAME.length; i++) out[at++] = TABLE_WRITES_NAME.charCodeAt(i); const walked = scanTableWrites(bytes, walkStop); if (walkStop) walkStop.verdict = walked; out[at++] = TABLE_WRITES_CODES.indexOf(walked); out[at++] = 0; out[at++] = RETAINED_MARKER_BYTES - 2; out[at++] = RETAINED_NAME.length; for (let i = 0; i < RETAINED_NAME.length; i++) out[at++] = RETAINED_NAME.charCodeAt(i); out[at++] = n & 255; out[at++] = n >>> 8 & 255; out[at++] = n >>> 16 & 255; out[at++] = n >>> 24 & 255; for (let i = 0; i < 32; i++) out[at++] = parseInt(digest.slice(i * 2, i * 2 + 2), 16); return out; } var __imageDecoder = new TextDecoder(); function decodeMaybeShared(view) { const shared = typeof SharedArrayBuffer !== "undefined" && view.buffer instanceof SharedArrayBuffer; return __imageDecoder.decode( shared ? view.slice() : view ); } function readScatterImage(kernelMemory, sglistOffset, nsegs, totalSize, what) { const cap = kernelMemory.byteLength; const off = sglistOffset >>> 0; const n = nsegs >>> 0; const total = totalSize >>> 0; if (n === 0) { throw new Error( `hwjs-scatter: ${what} declares 0 segments (sglist 0x${off.toString(16)}, total ${total}B) \u2014 a staged image always has at least one segment; kernel/host ABI skew (never-silent)` ); } if (n > 65536) { throw new Error( `hwjs-scatter: ${what} declares ${n} segments, far past anything the kernel's WASM32_IMG_MAX_SEGS cap can produce \u2014 REFUSED as a torn or misread request (never-silent)` ); } const listBytes = n * SGSEG_SIZE; if (off === 0 || off > cap || listBytes > cap - off) { throw new Error( `hwjs-scatter: ${what} segment list [0x${off.toString(16)}, +${listBytes}B) (${n} segments) is outside kernel memory (${cap}B) \u2014 REFUSED (never-silent)` ); } const dv = new DataView(kernelMemory, off, listBytes); const segs = []; let sum = 0; for (let i = 0; i < n; i++) { const sOff = dv.getUint32(i * SGSEG_SIZE + SGSEG_OFF_OFF, true) >>> 0; const sLen = dv.getUint32(i * SGSEG_SIZE + SGSEG_OFF_LEN, true) >>> 0; if (sLen === 0) { throw new Error( `hwjs-scatter: ${what} segment ${i}/${n} has length 0 (offset 0x${sOff.toString(16)}) \u2014 the kernel never emits empty segments; REFUSED (never-silent)` ); } if (sOff === 0 || sOff > cap || sLen > cap - sOff) { throw new Error( `hwjs-scatter: ${what} segment ${i}/${n} is [0x${sOff.toString(16)}, +${sLen}B) which runs past kernel memory (${cap}B) \u2014 REFUSED (never-silent)` ); } sum += sLen; if (sum > total) { throw new Error( `hwjs-scatter: ${what} segments through ${i}/${n} already sum to ${sum}B but the request declares ${total}B total \u2014 REFUSED (never-silent)` ); } segs.push({ off: sOff, len: sLen }); } if (sum !== total) { throw new Error( `hwjs-scatter: ${what} segment lengths sum to ${sum}B but the request declares ${total}B total \u2014 REFUSED (never-silent)` ); } const out = new Uint8Array(new SharedArrayBuffer(total)); let at = 0; for (const s of segs) { out.set(new Uint8Array(kernelMemory, s.off, s.len), at); at += s.len; } return out; } var WASM_SPAWN_RING_SLOTS = 16; var SR_OFF_MODE = 0; var SR_OFF_FLAGS = 4; var SR_OFF_TID = 8; var SR_OFF_PARENT_TID = 12; var SR_OFF_EXEC_IMAGE_OFFSET = 16; var SR_OFF_EXEC_IMAGE_SIZE = 20; var SR_OFF_ARG_REGION_OFFSET = 24; var SR_OFF_STACK_POINTER_OFFSET = 28; var SR_OFF_TLS_POINTER_OFFSET = 32; var SR_OFF_RESULT = 36; var SR_OFF_LIBC_IMAGE_OFFSET = 40; var SR_OFF_LIBC_IMAGE_SIZE = 44; var SR_OFF_LIBC_DIGEST_OFFSET = 48; var SR_OFF_RT_THREAD = 52; var SR_RT_THREAD_BIT = 1; var SR_THREADS_MAX_SHIFT = 1; var SR_OFF_EXEC_IMAGE_NSEGS = 56; var SR_OFF_LIBC_IMAGE_NSEGS = 60; var WASM_SPAWN_REQUEST_V1_SIZE = 64; var RING_OFF_HEAD = 0; var RING_OFF_TAIL = 4; var RING_OFF_SPAWN_NOTIFY_WORD = 8; var RING_OFF_RESULT_NOTIFY_WORD = 12; var RING_OFF_SLOTS = 32; var WASM_SPAWN_RING_HEADER_V1_SIZE = 32; var WASM_SPAWN_RING_V1_SIZE = WASM_SPAWN_RING_HEADER_V1_SIZE + WASM_SPAWN_RING_SLOTS * WASM_SPAWN_REQUEST_V1_SIZE; function ringSlotOffset(ringBase, slotIdx) { return ringBase + RING_OFF_SLOTS + slotIdx % WASM_SPAWN_RING_SLOTS * WASM_SPAWN_REQUEST_V1_SIZE; } // ../../linux-in-the-browser/hardwarejs/src/spawnRingConsumer.ts var SpawnRingConsumer = class { kernelMemory; ringOffset; handler; onProcessed; onError; i32; dv; running = false; stopped = false; loopDone = null; /** * Last value of spawn_notify_word the consumer observed. * Atomics.waitAsync compares the current value against this; * if it has already moved (producer raced past), waitAsync * returns "not-equal" immediately and we drain. */ lastSpawnNotifyValue = 0; constructor(opts) { if ((opts.ringOffset & 3) !== 0) { throw new Error( `SpawnRingConsumer: ringOffset 0x${opts.ringOffset.toString(16)} not 4-byte aligned` ); } this.kernelMemory = opts.kernelMemory; this.ringOffset = opts.ringOffset; this.handler = opts.handler; this.onProcessed = opts.onProcessed; this.onError = opts.onError; this.i32 = new Int32Array(this.kernelMemory); this.dv = new DataView(this.kernelMemory); } /** * Begin the consumer loop. Returns a promise that resolves when * the loop exits (after stop() or a fatal error). Idempotent — * calling start() twice is a no-op on the second call. */ start() { if (this.running || this.stopped) { return this.loopDone ?? Promise.resolve(); } this.running = true; this.lastSpawnNotifyValue = Atomics.load( this.i32, this.spawnNotifyIdx() ); this.loopDone = this.runLoop(); return this.loopDone; } /** * Request loop termination. Sets the stopped flag and notifies * the spawn_notify_word so any pending Atomics.waitAsync wakes * immediately. The loop exits at the top of the next iteration. * * Returns the promise the loop resolves on completion (same * promise start() returned). */ async stop() { if (this.stopped) return; this.stopped = true; Atomics.notify(this.i32, this.spawnNotifyIdx(), Infinity); await this.loopDone; } spawnNotifyIdx() { return this.ringOffset + RING_OFF_SPAWN_NOTIFY_WORD >>> 2; } resultNotifyIdx() { return this.ringOffset + RING_OFF_RESULT_NOTIFY_WORD >>> 2; } headIdx() { return this.ringOffset + RING_OFF_HEAD >>> 2; } tailIdx() { return this.ringOffset + RING_OFF_TAIL >>> 2; } /** * Decode one slot. The slot is read non-atomically — the kernel * has finished writing all fields before incrementing the notify * word, and our load of head happens AFTER an observed notify * increment (acquire-release on the notify word's atomic * add+notify on the kernel side). So the fields are stable by * the time we read them. */ readSlot(slotIdx) { const base = ringSlotOffset(this.ringOffset, slotIdx); return { mode: this.dv.getUint32(base + SR_OFF_MODE, true), flags: this.dv.getUint32(base + SR_OFF_FLAGS, true), tid: this.dv.getUint32(base + SR_OFF_TID, true), parentTid: this.dv.getUint32(base + SR_OFF_PARENT_TID, true), execImageOffset: this.dv.getUint32(base + SR_OFF_EXEC_IMAGE_OFFSET, true), execImageSize: this.dv.getUint32(base + SR_OFF_EXEC_IMAGE_SIZE, true), execImageNsegs: this.dv.getUint32(base + SR_OFF_EXEC_IMAGE_NSEGS, true), argRegionOffset: this.dv.getUint32(base + SR_OFF_ARG_REGION_OFFSET, true), stackPointerOffset: this.dv.getUint32( base + SR_OFF_STACK_POINTER_OFFSET, true ), tlsPointerOffset: this.dv.getUint32(base + SR_OFF_TLS_POINTER_OFFSET, true), libcImageOffset: this.dv.getUint32(base + SR_OFF_LIBC_IMAGE_OFFSET, true), libcImageSize: this.dv.getUint32(base + SR_OFF_LIBC_IMAGE_SIZE, true), libcDigestOffset: this.dv.getUint32(base + SR_OFF_LIBC_DIGEST_OFFSET, true), libcImageNsegs: this.dv.getUint32(base + SR_OFF_LIBC_IMAGE_NSEGS, true), rtThread: (this.dv.getUint32(base + SR_OFF_RT_THREAD, true) & SR_RT_THREAD_BIT) !== 0, threadsMax: this.dv.getUint32(base + SR_OFF_RT_THREAD, true) >>> SR_THREADS_MAX_SHIFT }; } /** * Write the result back into the slot and notify the kernel. * * Order matters: * 1. Write result field (plain store; ordering guaranteed by * the subsequent atomic add+notify) * 2. Advance tail (atomic store; consumer-side bookkeeping) * 3. Atomic-add the result_notify_word (release) * 4. Atomics.notify * * The kernel-side producer is doing: * - reads slot.result (after seeing result_notify_word change) * * So our store of result must be observable BEFORE the kernel * observes the notify-word change. The atomic add provides a * release fence on the result_notify_word store; that release * fence orders before all prior writes including our plain * result store. Good enough for V8/spec. */ /** * @param tail current monotonic tail index (NOT the slot * index; the new tail is `tail + 1`). * @param result kernel-visible result code (0 on success or * negative errno). */ writeResultAndNotify(tail, result) { const base = ringSlotOffset(this.ringOffset, tail); this.dv.setInt32(base + SR_OFF_RESULT, result | 0, true); Atomics.store(this.i32, this.tailIdx(), tail + 1 >>> 0); Atomics.add(this.i32, this.resultNotifyIdx(), 1); Atomics.notify(this.i32, this.resultNotifyIdx(), Infinity); } async runLoop() { try { while (!this.stopped) { const cur = Atomics.load(this.i32, this.spawnNotifyIdx()); if (cur === this.lastSpawnNotifyValue) { const r = Atomics.waitAsync( this.i32, this.spawnNotifyIdx(), this.lastSpawnNotifyValue, 5e3 ); if (r.async) { const outcome = await r.value; void outcome; } } if (this.stopped) break; this.lastSpawnNotifyValue = Atomics.load( this.i32, this.spawnNotifyIdx() ); await this.drain(); } } catch (err2) { this.onError?.(err2); throw err2; } finally { this.running = false; } } /** * Drain all pending slots: process [tail, head). * * Indices are monotonic u32. Wrap-around for u32 subtraction is * well-defined: `(head - tail) >>> 0` gives the count of pending * slots even when head has wrapped past 2^32. */ async drain() { const head = Atomics.load(this.i32, this.headIdx()) >>> 0; let tail = Atomics.load(this.i32, this.tailIdx()) >>> 0; while (head - tail >>> 0 > 0) { const slotIdx = tail % WASM_SPAWN_RING_SLOTS; const req = this.readSlot(slotIdx); let result = 0; try { result = await this.handler(req) | 0; } catch (err2) { this.onError?.(err2); result = -22; } this.writeResultAndNotify(tail, result); this.onProcessed?.(req, result); tail = tail + 1 >>> 0; } } }; // ../../linux-in-the-browser/hardwarejs/src/signal-ring-abi.ts var WASM_SIGNAL_OFF_PENDING_LO = 0; var WASM_SIGNAL_OFF_PENDING_HI = 4; var WASM_SIGNAL_OFF_WAKE_WORD = 8; var WASM_SIGNAL_OFF_SIGCHLD_DELIVERY_SEQ = 24; var WASM_SIGNAL_OFF_FEATURES = 28; var WASM_SIGNAL_FEAT_KERNEL_PUBLISHES_PENDING = 1; var WASM_SIGNAL_PENDING_REGION_SIZE = 40; var SIG_REQ_OFF_TID = 0; var SIG_REQ_OFF_SIG = 4; var SIG_REQ_OFF_SENDER_PID = 8; var WASM_SIGNAL_REQUEST_V1_SIZE = 32; var SIG_RING_OFF_HEAD = 0; var SIG_RING_OFF_TAIL = 4; var SIG_RING_OFF_SIGNAL_NOTIFY_WORD = 8; var SIG_RING_OFF_SLOTS = 32; var WASM_SIGNAL_RING_HEADER_V1_SIZE = 32; var WASM_SIGNAL_RING_SLOTS = 16; var WASM_SIGNAL_RING_V1_SIZE = WASM_SIGNAL_RING_HEADER_V1_SIZE + WASM_SIGNAL_RING_SLOTS * WASM_SIGNAL_REQUEST_V1_SIZE; function signalRingSlotOffset(ringBase, slotIdx) { return ringBase + SIG_RING_OFF_SLOTS + slotIdx % WASM_SIGNAL_RING_SLOTS * WASM_SIGNAL_REQUEST_V1_SIZE; } // ../../linux-in-the-browser/hardwarejs/src/signalHandler.ts var hostStampRedCached = null; function hostStampsPendingBitRed() { if (hostStampRedCached === null) { hostStampRedCached = typeof process !== "undefined" && !!(typeof process === "undefined" ? void 0 : process)?.env?.HWJS_RED_SIGNAL_HOST_STAMP; } return hostStampRedCached; } var SIGCHLD = 17; function createSignalTargetRegistry() { const m = /* @__PURE__ */ new Map(); return { register(tid, rec) { m.set(tid, rec); }, unregister(tid) { m.delete(tid); }, has(tid) { return m.has(tid); }, size() { return m.size; }, lookup(tid) { return m.get(tid); } }; } function deliverSignalToTarget(registry2, req) { if (req.sig < 1 || req.sig > 64) { return { kind: "bad-signal" }; } const rec = registry2.lookup(req.tid); if (!rec) { return { kind: "no-target" }; } const buf = rec.userMemory.buffer; const userI32 = new Int32Array(buf); if (rec.signalPendingOffset < 0 || (rec.signalPendingOffset & 3) !== 0 || rec.signalPendingOffset + WASM_SIGNAL_PENDING_REGION_SIZE > buf.byteLength) { return { kind: "bad-region" }; } const pendingLoIdx = rec.signalPendingOffset + WASM_SIGNAL_OFF_PENDING_LO >>> 2; const pendingHiIdx = rec.signalPendingOffset + WASM_SIGNAL_OFF_PENDING_HI >>> 2; const wakeIdx = rec.signalPendingOffset + WASM_SIGNAL_OFF_WAKE_WORD >>> 2; if (req.sig === SIGCHLD) { const seqIdx = rec.signalPendingOffset + WASM_SIGNAL_OFF_SIGCHLD_DELIVERY_SEQ >>> 2; Atomics.add(userI32, seqIdx, 1); } const featIdx = rec.signalPendingOffset + WASM_SIGNAL_OFF_FEATURES >>> 2; const feats = Atomics.load(userI32, featIdx) >>> 0; const kernelPublishes = (feats & WASM_SIGNAL_FEAT_KERNEL_PUBLISHES_PENDING) !== 0 && !hostStampsPendingBitRed(); if (!kernelPublishes) { if (req.sig <= 32) { const mask = 1 << req.sig - 1; Atomics.or(userI32, pendingLoIdx, mask); } else { const mask = 1 << req.sig - 33; Atomics.or(userI32, pendingHiIdx, mask); } } Atomics.add(userI32, wakeIdx, 1); Atomics.notify(userI32, wakeIdx, Infinity); return { kind: "delivered", rec, stamped: !kernelPublishes }; } function makeSignalHandler(opts) { const { registry: registry2, onUnregisteredTarget, onDelivered } = opts; return (req) => { const out = deliverSignalToTarget(registry2, req); switch (out.kind) { case "delivered": onDelivered?.(req, out.rec); return; default: onUnregisteredTarget?.(req); return; } }; } // ../../linux-in-the-browser/hardwarejs/src/vcpuPolicy.ts var WASM32_NR_CPUS = 129; var WASM32_DEFAULT_VCPU_CAP = 8; function resolveNumVcpu(requested) { if (requested !== void 0) { if (!Number.isFinite(requested) || (requested | 0) !== requested) { throw new Error( `bootKernel({ num_vcpu }): expected an integer, got ${String(requested)}.` ); } if (requested < 2) { throw new Error( `bootKernel({ num_vcpu }): num_vcpu must be >= 2. It counts the KERNEL's CPUs, not the host's threads: CPU 0 is the kthread CPU (the only cpu_online one) and CPU 1 is the first lane a guest task can be placed on, so a machine has at least two even when CPU 0 and lane 1 share ONE JS thread. Got ${requested}.` ); } if (requested > WASM32_NR_CPUS) { throw new Error( `bootKernel({ num_vcpu }): num_vcpu must be <= ${WASM32_NR_CPUS} (CONFIG_NR_CPUS compile-time ceiling: 128 pool Workers + CPU 0). Got ${requested}.` ); } return requested | 0; } const hwc = globalThis.navigator?.hardwareConcurrency ?? 4; return Math.max(2, Math.min(WASM32_DEFAULT_VCPU_CAP, hwc | 0)); } function defaultPoolMaxCpuId() { return resolveNumVcpu(void 0) - 1; } function expectedWorkerRealms(numVcpu) { const n = resolveNumVcpu(numVcpu); return n - 1; } // ../../linux-in-the-browser/hardwarejs/src/kernelSpawnHandler.ts init_preemptTimer(); init_uaccessCopies(); // ../../linux-in-the-browser/hardwarejs/src/taskLedger.ts var EXITED_RING = 64; var nowMs = () => typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now(); function makeTaskLedger() { let nextSeq = 1; const live2 = /* @__PURE__ */ new Set(); const exited = []; let reapedBeyondRing = 0; const retire = (e) => { live2.delete(e); exited.push(e); while (exited.length > EXITED_RING) { exited.shift(); reapedBeyondRing++; } }; return { open(init) { const t = nowMs(); const e = { rec: { seq: nextSeq++, kind: init.kind, state: "placing", pid: null, tgid: init.tgid, parentPid: init.parentPid, spawnTid: init.spawnTid, residency: init.residency, cpuId: init.cpuId, routeKey: init.routeKey, placements: [{ cpuId: init.cpuId, atMs: t, why: "spawn" }], image: init.image, execCount: 0, sabSharedWithGroup: init.sabSharedWithGroup, signalPendingOffset: null, createdAtMs: t, pidAtMs: null, exitedAtMs: null, exit: null, degradedReason: null }, mem: init.userMemory ? new WeakRef(init.userMemory) : null }; live2.add(e); return { seq: e.rec.seq, notePid(pid, tgid) { if (e.rec.pid !== null) return; e.rec.pid = pid | 0; e.rec.tgid = tgid | 0; e.rec.pidAtMs = nowMs(); if (e.rec.state === "placing") e.rec.state = "running"; }, notePlacement(cpuId, why) { e.rec.cpuId = cpuId | 0; e.rec.placements.push({ cpuId: cpuId | 0, atMs: nowMs(), why }); }, noteRouteKey(routeKey) { e.rec.routeKey = routeKey; }, noteExec(image) { e.rec.image = image; e.rec.execCount++; }, noteSignalPendingOffset(off) { e.rec.signalPendingOffset = off === void 0 ? null : off >>> 0; }, noteDegraded(reason) { if (e.rec.state === "exited") return; e.rec.state = "degraded"; e.rec.degradedReason = reason; }, noteExit(code2, note) { if (e.rec.state === "exited") return; e.rec.state = "exited"; e.rec.exit = { code: code2 | 0, note }; e.rec.exitedAtMs = nowMs(); retire(e); } }; }, tasks() { const out = []; const add = (e) => { const m = e.mem === null ? void 0 : e.mem.deref(); out.push({ ...e.rec, /* Copy the arrays: the caller may serialise this while the machine * keeps running, and a shared array would tear across the JSON. */ placements: e.rec.placements.slice(), image: { ...e.rec.image }, exit: e.rec.exit === null ? null : { ...e.rec.exit }, sabCommittedBytes: e.mem === null ? null : m === void 0 ? null : m.buffer.byteLength }); }; for (const e of live2) add(e); for (const e of exited) add(e); out.sort((a, b) => a.seq - b.seq); return out; }, reapedBeyondRing: () => reapedBeyondRing }; } // ../../linux-in-the-browser/hardwarejs/src/kernelSpawnHandler.ts function threadFilesShareDisabled() { try { return typeof process !== "undefined" && process.env?.HWJS_THREAD_FILES_DUP === "1"; } catch { return false; } } function threadResidencyDisabled() { try { return typeof process !== "undefined" && process.env?.HWJS_THREAD_DEDICATED_WORKERS === "1"; } catch { return false; } } function threadParentRegistrationDisabled() { try { return typeof process !== "undefined" && process.env?.HWJS_THREAD_NO_PARENT_REGISTRATION === "1"; } catch { return false; } } function threadPlacementPinRaw() { try { if (typeof process === "undefined") return null; const v = process.env?.HWJS_THREAD_PLACEMENT_PIN; return typeof v === "string" && v.trim() !== "" ? v : null; } catch { return null; } } function resolveThreadPlacementPin(threadOrdinal, maxCpuId) { const raw = threadPlacementPinRaw(); if (raw === null) return { kind: "none" }; const pins = /* @__PURE__ */ new Map(); for (const entry of raw.split(",")) { const t = entry.trim(); if (t === "") continue; const m = /^(-?\d+)\s*:\s*(-?\d+)$/.exec(t); if (!m) { return { kind: "error", message: `HWJS_THREAD_PLACEMENT_PIN entry ${JSON.stringify(t)} is not : (whole table: ${JSON.stringify(raw)}; grammar: comma-separated thread:cpu pairs, e.g. "5:1,2:3", where thread N is the process's Nth created thread)` }; } const nth = Number(m[1]) | 0; const cpu = Number(m[2]) | 0; if (pins.has(nth) && pins.get(nth) !== cpu) { return { kind: "error", message: `HWJS_THREAD_PLACEMENT_PIN names thread ${nth} twice, with conflicting cpus ${pins.get(nth)} and ${cpu} (whole table: ${JSON.stringify(raw)}) \u2014 refusing to pick one, because guessing which the experiment meant is how a pin produces a fake result` }; } pins.set(nth, cpu); } const want = pins.get(threadOrdinal | 0); if (want === void 0) return { kind: "none" }; if (want < 1 || want > maxCpuId) { return { kind: "error", message: `HWJS_THREAD_PLACEMENT_PIN pins thread ${threadOrdinal | 0} to cpu ${want}, which is outside this machine's pool cpu range 1..${maxCpuId} (maxCpuId=${maxCpuId}; cpu 0 is the kernel Worker and is never a pool lane). NOT clamped \u2014 a clamped pin would run the experiment on a cpu nobody chose and report it as the one that was asked for. Raise num_vcpu or name a cpu in range` }; } return { kind: "pin", cpuId: want, raw }; } var __NR_read = 0; var __NR_write = 1; var __NR_mmap = 9; var __NR_mprotect = 10; var __NR_munmap = 11; var __NR_brk = 12; var __NR_ioctl = 16; var __NR_writev = 20; var __NR_madvise = 28; var __NR_clone = 56; var __NR_exit = 60; var __NR_getpid = 39; var __NR_pause = 34; var __NR_set_tid_address = 218; var __NR_clock_gettime = 228; var __NR_nanosleep = 35; var __NR_clock_nanosleep = 230; var __NR_exit_group = 231; var __NR_set_robust_list = 273; var __NR_wasm_spawn_image = 1024; var __NR_wasm_spawn_image_actions = 1025; var WASM_SPAWN_ACTION_DUP2 = 0; var WASM_SPAWN_ACTION_CLOSE = 1; var CLONE_VM = 256; var CLONE_VFORK = 16384; var CLONE_THREAD = 65536; var CLONE_CHILD_CLEARTID = 2097152; var WASM_THREAD_ARG_REGION_SIZE = 112; var WASM_THREAD_ARG_MAGIC_LO = 1380471895; var WASM_THREAD_ARG_MAGIC_HI = 1145128274; var WASM_THREAD_ARG_VERSION = 1; var ENOSYS = -38; var ENOMEM2 = -12; var EIO = -5; var EAGAIN = -11; var JS_HEAP_BUDGET_DEFAULT_MIB = 2560; function jsHeapBudgetMiBFor(platform, option, envRaw) { const fromEnv = envRaw !== void 0 && /^[0-9]+$/.test(envRaw) ? parseInt(envRaw, 10) : void 0; return option ?? fromEnv ?? (platform === "browser" ? JS_HEAP_BUDGET_DEFAULT_MIB : 0); } var JS_HEAP_REALM_BASE_KIB = 24 * 1024; var JS_HEAP_COLLECT_SHARE = 0.75; var JS_HEAP_HOME_SHARE = 0.5; function threadPrefersHomeLane(accountedKiB, budgetKiB) { return budgetKiB > 0 && accountedKiB >= budgetKiB * JS_HEAP_HOME_SHARE; } var JS_HEAP_COLLECT_GAP_MS = 2e3; function jsHeapBudgetFromCmdline(cmdline) { const prefix = "hwjs.js_heap_budget="; const tokens = (cmdline ?? "").split(/\s+/).filter((t) => t.startsWith(prefix)); const raw = tokens.length > 0 ? tokens[tokens.length - 1].slice(prefix.length) : ""; return /^[0-9]+$/.test(raw) ? parseInt(raw, 10) : void 0; } var ECHILD = -10; var WASM_MMAP_BASE = 4 * 1024 * 1024; var WASM_PAGE_SIZE = 4096; var BRK_RESERVE = 1 * 1024 * 1024; var HWJS_RT_WINDOW_SIZE2 = 8 * 1024 * 1024; var HWJS_LIBC_WINDOW_SIZE2 = 16 * 1024 * 1024; var MMAP_MIN_HEADROOM = 4 * 1024 * 1024; var HWJS_NO_USERMEM_GROW = !!globalThis.process?.env?.HWJS_NO_USERMEM_GROW; var HWJS_NO_SAB_RECLAIM = () => !!globalThis.process?.env?.HWJS_NO_SAB_RECLAIM; var userMemoryBumpPointers = /* @__PURE__ */ new WeakMap(); var userMemoryIds = /* @__PURE__ */ new WeakMap(); var userMemoryIdNext = 1; function userMemoryId(mem) { let id = userMemoryIds.get(mem); if (id === void 0) { id = userMemoryIdNext++; userMemoryIds.set(mem, id); } return id; } var userMemoryDirtyCells = /* @__PURE__ */ new WeakMap(); var DIRTY_ALL = -1; function setUserBump(userMem, bump) { userMemoryBumpPointers.set(userMem, bump); const cell = userMemoryDirtyCells.get(userMem); if (!cell) { const fresh = new Int32Array(new SharedArrayBuffer(4)); fresh[0] = bump | 0; userMemoryDirtyCells.set(userMem, fresh); return; } const cur = Atomics.load(cell, 0); if (cur !== DIRTY_ALL && bump >>> 0 > cur >>> 0) Atomics.store(cell, 0, bump | 0); } function markUserMemoryDirty(userMem) { const cell = userMemoryDirtyCells.get(userMem); if (cell) Atomics.store(cell, 0, DIRTY_ALL); } function userMemoryDirtyBytes(userMem) { const len = userMem.buffer.byteLength; const cell = userMemoryDirtyCells.get(userMem); return cell ? Math.min(len, Atomics.load(cell, 0) >>> 0) : len; } function userDirtyCellInit(userMem) { const cell = userMemoryDirtyCells.get(userMem); return cell ? { userDirtyCell: cell.buffer } : {}; } var DL_PLACEMENT_THREADS = 2; var DL_PLACEMENT_IMAGE = 5; var DL_PLACEMENT_PULL_MS = 1e4; var userPlacementCells = /* @__PURE__ */ new WeakMap(); var dlPlacementJournals = /* @__PURE__ */ new Map(); function placementCellInit(userMem, fresh) { const memoryId = userMemoryId(userMem); let cell = userPlacementCells.get(userMem); if (!cell || fresh) { cell = new SharedArrayBuffer(24); userPlacementCells.set(userMem, cell); dlPlacementJournalDrop(memoryId); } return { placementCell: cell, memoryId }; } function placementCellForThread(userMem, vforkChild = false) { const { placementCell } = placementCellInit(userMem, false); const words = new Int32Array(placementCell); if (!vforkChild) Atomics.add(words, DL_PLACEMENT_THREADS, 1); return { placementCell, threadImageEpoch: Atomics.load(words, DL_PLACEMENT_IMAGE) }; } function dlPlacementJournalDrop(memoryId) { const j = dlPlacementJournals.get(memoryId); if (!j) return; for (const p of j.pulls.values()) clearTimeout(p.timer); dlPlacementJournals.delete(memoryId); } function dlPlacementJournal(memoryId) { let j = dlPlacementJournals.get(memoryId); if (!j) { j = { pubs: /* @__PURE__ */ new Map(), mods: /* @__PURE__ */ new Map(), pulls: /* @__PURE__ */ new Set() }; dlPlacementJournals.set(memoryId, j); } return j; } function dlPlacementDeltas(j, since, want, have) { const out = []; for (let g = since + 1; g <= want; g++) { const p = j.pubs.get(g); if (!p) return null; const rec = p.record && typeof p.record === "object" ? p.record : {}; const replay = Array.isArray(rec.replay) ? rec.replay.map((e) => { const c = e?.cookie >>> 0; if (have.has(c)) { const { bytes: _b, module: _m, ...rest } = e; return rest; } if (e?.bytes !== void 0) return e; const m = j.mods.get(c); return m ? { ...e, ...m } : e; }) : []; out.push({ gen: p.gen, tid: p.tid, record: { ...rec, replay } }); } return out; } function dlPlacementServe(j, p) { const pubs = dlPlacementDeltas(j, p.since, p.want, p.have); if (!pubs) return; clearTimeout(p.timer); j.pulls.delete(p); p.reply({ kind: "dl-placement-deltas", seq: p.seq, pubs }); } function dlPlacementMessage(msg, reply, releaseThreadImages) { const kind = msg?.kind; if (kind !== "dl-placement-publish" && kind !== "dl-placement-pull" && kind !== "dl-placement-reset") return false; const memoryId = msg.memoryId | 0; if (kind === "dl-placement-reset") { dlPlacementJournalDrop(memoryId); if (msg.releaseThreadImagesBefore !== void 0) { releaseThreadImages?.(memoryId, msg.releaseThreadImagesBefore | 0); } return true; } const j = dlPlacementJournal(memoryId); if (kind === "dl-placement-publish") { const gen = msg.gen | 0; const record = msg.record && typeof msg.record === "object" ? msg.record : {}; for (const e of Array.isArray(record.replay) ? record.replay : []) { const c = e?.cookie >>> 0; if (e?.bytes !== void 0 && !j.mods.has(c)) { j.mods.set(c, { bytes: e.bytes, ...e.module !== void 0 ? { module: e.module } : {} }); } } j.pubs.set(gen, { gen, tid: msg.tid | 0, record }); for (const p of [...j.pulls]) dlPlacementServe(j, p); return true; } const seq = msg.seq | 0; const have = new Set((Array.isArray(msg.have) ? msg.have : []).map((c) => c >>> 0)); const pull = { seq, since: msg.since | 0, want: msg.want | 0, have, reply, timer: setTimeout(() => { if (!j.pulls.delete(pull)) return; reply({ kind: "dl-placement-deltas", seq, error: `no placement record up to generation ${msg.want | 0} arrived within ${DL_PLACEMENT_PULL_MS} ms (memory ${memoryId}, since ${msg.since | 0})` }); }, DL_PLACEMENT_PULL_MS) }; j.pulls.add(pull); dlPlacementServe(j, pull); return true; } function makeThreadImageLedger(dropIdle) { const live2 = /* @__PURE__ */ new Map(); const at = (memoryId, cpuId) => `${memoryId}:${cpuId}`; let idle = null; const giveUp = () => { if (idle) dropIdle(idle.cpuId, idle.memoryId); idle = null; }; return { threadPlaced(memoryId, cpuId) { const n = live2.get(at(memoryId, cpuId)) ?? 0; if (idle?.memoryId === memoryId && idle.cpuId === cpuId) idle = null; else if (n === 0) giveUp(); live2.set(at(memoryId, cpuId), n + 1); }, threadLeft(memoryId, cpuId) { const n = live2.get(at(memoryId, cpuId)); if (n === void 0) return; if (n > 1) { live2.set(at(memoryId, cpuId), n - 1); return; } live2.delete(at(memoryId, cpuId)); giveUp(); idle = { memoryId, cpuId }; }, /* An exec: threads of the new image can already be counted, and the old * image's still leaving are counted with them. */ imageReplaced(memoryId) { if (idle?.memoryId === memoryId) idle = null; }, imageGone(memoryId) { if (idle?.memoryId === memoryId) idle = null; for (const k of [...live2.keys()]) if (k.startsWith(`${memoryId}:`)) live2.delete(k); }, idleLane(memoryId) { return idle?.memoryId === memoryId ? idle.cpuId : void 0; } }; } function traceForkCopy(pid, copied, total) { if (!globalThis.process?.env?.D1_TRACE_MEM) return; globalThis.process.stderr.write( `[D1_TRACE_MEM pid=${pid}] fork COPIED 0x${copied.toString(16)} of 0x${total.toString(16)} bytes of user_memory ` ); } var userMemoryMmapFreeLists = /* @__PURE__ */ new WeakMap(); var userMemorySignalPageFreeLists = /* @__PURE__ */ new WeakMap(); function getMmapFreeList(userMem) { let l = userMemoryMmapFreeLists.get(userMem); if (!l) { l = []; userMemoryMmapFreeLists.set(userMem, l); } return l; } function userMemoryInUseBytes(userMem) { const bump = userMemoryBumpPointers.get(userMem); if (bump === void 0) return void 0; let free = (userMemorySignalPageFreeLists.get(userMem)?.length ?? 0) * WASM_PAGE_SIZE; for (const r of userMemoryMmapFreeLists.get(userMem) ?? []) free += r.end - r.start; return Math.max(0, bump - free); } function mmapFreeListTake(userMem, len) { const l = getMmapFreeList(userMem); for (let i = 0; i < l.length; i++) { const r = l[i]; if (r.end - r.start >= len) { const start = r.start; r.start += len; if (r.start === r.end) l.splice(i, 1); return start; } } return -1; } function mmapFreeListInsert(userMem, start, end) { if (end <= start) return 0; const l = getMmapFreeList(userMem); let i = 0; while (i < l.length && l[i].end < start) i++; let s = start, e = end; let absorbed = 0; while (i < l.length && l[i].start <= e) { s = Math.min(s, l[i].start); e = Math.max(e, l[i].end); absorbed += l[i].end - l[i].start; l.splice(i, 1); } l.splice(i, 0, { start: s, end: e }); return e - s - absorbed; } function userMemoryGrowRefusal(ram, userMem, pid, what, requestedBytes) { const maximumBytes = ram.userMemoryMaximumBytes(userMem); return describeUserMemoryGrowRefusal({ pid, what, requestedBytes, currentBytes: userMem.buffer.byteLength, maximumBytes, boundBy: classifyUserMemoryGrowBound(requestedBytes, maximumBytes) }); } var userMemoryPartitions = /* @__PURE__ */ new WeakMap(); var partitionReports = []; function alignUp2(x, a) { return Math.ceil(x / a) * a; } function readUnsignedLEB(b, p) { let result = 0, shift = 0, byte = 0; do { byte = b[p++]; result |= (byte & 127) << shift; shift += 7; } while (byte & 128); return [result >>> 0, p]; } function readSignedLEB(b, p) { let result = 0, shift = 0, byte = 0; do { byte = b[p++]; result |= (byte & 127) << shift; shift += 7; } while (byte & 128); if (shift < 32 && byte & 64) result |= -(1 << shift); return [result | 0, p]; } function readHeapBase2(wasmBytes) { const b = wasmBytes; if (b.length < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) { throw new Error("hwjs port BUG: exec image is not a wasm module (F30 partition cannot read __heap_base)"); } let p = 8; let numImportedGlobals = 0; let exportGlobalIndex = -1; let globalSectionOff = -1, globalSectionEnd = -1; while (p < b.length) { const id = b[p++]; let size; [size, p] = readUnsignedLEB(b, p); const sectionStart = p; const sectionEnd = p + size; if (id === 2) { let count; [count, p] = readUnsignedLEB(b, p); for (let i = 0; i < count; i++) { let len; [len, p] = readUnsignedLEB(b, p); p += len; [len, p] = readUnsignedLEB(b, p); p += len; const kind = b[p++]; if (kind === 0) { [, p] = readUnsignedLEB(b, p); } else if (kind === 1) { p += 1; p = skipLimits2(b, p); } else if (kind === 2) { p = skipLimits2(b, p); } else if (kind === 3) { p += 2; numImportedGlobals++; } } } else if (id === 7) { let count; [count, p] = readUnsignedLEB(b, p); for (let i = 0; i < count; i++) { let len; [len, p] = readUnsignedLEB(b, p); const name2 = decodeMaybeShared(b.subarray(p, p + len)); p += len; const kind = b[p++]; let idx; [idx, p] = readUnsignedLEB(b, p); if (kind === 3 && name2 === "__heap_base") exportGlobalIndex = idx; } } else if (id === 6) { globalSectionOff = sectionStart; globalSectionEnd = sectionEnd; } p = sectionEnd; } if (exportGlobalIndex < 0) { throw new Error("hwjs port BUG: exec image does not export __heap_base (F30 partition requires it)"); } if (globalSectionOff < 0) { throw new Error("hwjs port BUG: exec image has no global section (cannot read __heap_base)"); } const definedIndex = exportGlobalIndex - numImportedGlobals; let gp = globalSectionOff; let gcount; [gcount, gp] = readUnsignedLEB(b, gp); if (definedIndex < 0 || definedIndex >= gcount) { throw new Error(`hwjs port BUG: __heap_base global index ${exportGlobalIndex} (defined ${definedIndex}) out of range (${gcount} defined globals)`); } for (let i = 0; i < gcount; i++) { gp += 2; if (i === definedIndex) { const op = b[gp++]; if (op !== 65) { throw new Error(`hwjs port BUG: __heap_base init is opcode 0x${op.toString(16)}, expected i32.const (0x41)`); } let val; [val, gp] = readSignedLEB(b, gp); return val >>> 0; } while (gp < globalSectionEnd && b[gp] !== 11) { const op = b[gp++]; if (op === 65 || op === 66) { [, gp] = readSignedLEB(b, gp); } else if (op === 67) { gp += 4; } else if (op === 68) { gp += 8; } else if (op === 35) { [, gp] = readUnsignedLEB(b, gp); } } gp++; } throw new Error("hwjs port BUG: __heap_base global not reached while walking the global section"); } function skipLimits2(b, p) { const flags = b[p++]; [, p] = readUnsignedLEB(b, p); if (flags & 1) { [, p] = readUnsignedLEB(b, p); } return p; } function readMemImportMinBytes(wasmBytes) { const b = wasmBytes; if (b.length < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) { throw new Error("hwjs port BUG: exec image is not a wasm module (A-5.a cannot read memory-import min)"); } let p = 8; while (p < b.length) { const id = b[p++]; let size; [size, p] = readUnsignedLEB(b, p); const sectionEnd = p + size; if (id === 2) { let count; [count, p] = readUnsignedLEB(b, p); for (let i = 0; i < count; i++) { let len; [len, p] = readUnsignedLEB(b, p); p += len; [len, p] = readUnsignedLEB(b, p); p += len; const kind = b[p++]; if (kind === 0) { [, p] = readUnsignedLEB(b, p); } else if (kind === 1) { p += 1; p = skipLimits2(b, p); } else if (kind === 2) { const flags = b[p++]; let min; [min, p] = readUnsignedLEB(b, p); if (flags & 1) { [, p] = readUnsignedLEB(b, p); } return min * 65536; } else if (kind === 3) { p += 2; } } return 0; } p = sectionEnd; } return 0; } function imageImportsHwjsRt(wasmBytes) { const b = wasmBytes; if (b.length < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) { throw new Error("hwjs port BUG: exec image is not a wasm module (cannot walk the import section)"); } let p = 8; while (p < b.length) { const id = b[p++]; let size; [size, p] = readUnsignedLEB(b, p); const sectionEnd = p + size; if (id === 2) { let count; [count, p] = readUnsignedLEB(b, p); for (let i = 0; i < count; i++) { let len; [len, p] = readUnsignedLEB(b, p); const mod = decodeMaybeShared(b.subarray(p, p + len)); p += len; [len, p] = readUnsignedLEB(b, p); const field = decodeMaybeShared(b.subarray(p, p + len)); p += len; const kind = b[p++]; if (kind === 0) { [, p] = readUnsignedLEB(b, p); if (mod === "env" && field === "__hwjs_frame_alloc") return true; } else if (kind === 1) { p += 1; p = skipLimits2(b, p); } else if (kind === 2) { p = skipLimits2(b, p); } else if (kind === 3) { p += 2; } } return false; } p = sectionEnd; } return false; } function imageNeededLibcDigest(wasmBytes) { const b = wasmBytes; if (b.length < 8 || b[0] !== 0 || b[1] !== 97 || b[2] !== 115 || b[3] !== 109) { throw new Error("hwjs-libc BUG: exec image is not a wasm module (cannot walk custom sections)"); } let payload = null; let count = 0; let p = 8; while (p < b.length) { const id = b[p++]; let size; [size, p] = readUnsignedLEB(b, p); const sectionEnd = p + size; if (id === 0) { let nameLen, np = p; [nameLen, np] = readUnsignedLEB(b, np); const name2 = decodeMaybeShared(b.subarray(np, np + nameLen)); np += nameLen; if (name2 === "wasm.linux.needed") { count++; payload = b.subarray(np, sectionEnd); } } p = sectionEnd; } if (count === 0) return null; if (count > 1) { throw new Error(`hwjs-libc: ${count} wasm.linux.needed sections on the image \u2014 exactly ONE carrier is legal (never-silent refuse)`); } let parsed; try { parsed = JSON.parse(decodeMaybeShared(payload)); } catch (e) { throw new Error(`hwjs-libc: malformed wasm.linux.needed payload (not JSON): ${e instanceof Error ? e.message : String(e)} (never-silent refuse)`); } const needed = Array.isArray(parsed?.needed) ? parsed.needed : null; if (!needed || typeof parsed.suspenders_sha256 !== "string") { throw new Error("hwjs-libc: wasm.linux.needed payload shape mismatch (never-silent refuse)"); } if (needed.length === 0) return null; const n = String(needed[0]); const m = /^libc\.so\.([0-9a-f]{64})$/.exec(n); if (!m) { throw new Error(`hwjs-libc: wasm.linux.needed entry ${JSON.stringify(n)} is not a digest-qualified libc.so name (never-silent refuse)`); } return m[1]; } function userImageKey(bytes) { const n = bytes.length; const dv = new DataView(bytes.buffer, bytes.byteOffset, n); let a = 0; let b = 2654435769 | 0; const words = n & ~3; let i = 0; for (; i < words; i += 4) { let k = dv.getUint32(i, true); k = Math.imul(k, 3432918353); k = k << 15 | k >>> 17; k = Math.imul(k, 461845907); a ^= k; a = a << 13 | a >>> 19; a = Math.imul(a, 5) + 3864292196 | 0; b = Math.imul(b ^ k, 2246822507); b ^= b >>> 13; } if (i < n) { let k = 0; for (let s = 0; i < n; i++, s += 8) k |= bytes[i] << s; k = Math.imul(k, 3432918353); k = k << 15 | k >>> 17; k = Math.imul(k, 461845907); a ^= k; b = Math.imul(b ^ k, 2246822507); b ^= b >>> 13; } const fmix = (h) => { h ^= n; h ^= h >>> 16; h = Math.imul(h, 2246822507); h ^= h >>> 13; h = Math.imul(h, 3266489909); h ^= h >>> 16; return h >>> 0; }; return `${n}:${fmix(a).toString(16)}:${fmix(b).toString(16)}`; } function makeUserImageKeyMemo(hash = userImageKey) { const staged = /* @__PURE__ */ new WeakSet(); const keys = /* @__PURE__ */ new WeakMap(); const known = (bytes) => { const e = keys.get(bytes); if (!e || e.buffer !== bytes.buffer || e.byteOffset !== bytes.byteOffset || e.byteLength !== bytes.byteLength) return void 0; return e.key; }; return { known, keyOf(bytes) { const have = known(bytes); if (have !== void 0) return have; const key = hash(bytes); if (staged.has(bytes) && bytes.byteLength > 0) { keys.set(bytes, { key, buffer: bytes.buffer, byteOffset: bytes.byteOffset, byteLength: bytes.byteLength }); } return key; }, noteStaged(bytes) { if (bytes instanceof Uint8Array) staged.add(bytes); } }; } var userImageKeys = makeUserImageKeyMemo(); function placementImageKey(bytes, memo = userImageKeys) { const key = memo.known(bytes); return key === void 0 ? {} : { imgKey: key }; } function imageFactsOf(wasmBytes, path) { let importsHwjsRt = false; try { importsHwjsRt = imageImportsHwjsRt(wasmBytes); } catch { } let neededLibcDigest = null; try { neededLibcDigest = imageNeededLibcDigest(wasmBytes); } catch { } return { byteLength: wasmBytes.length, path, importsHwjsRt, neededLibcDigest }; } function initUserMemoryPartition(userMem, wasmBytes, attribution) { const pid = attribution.pid; const heapBase = readHeapBase2(wasmBytes); const mmapFloor = alignUp2(heapBase + BRK_RESERVE, WASM_PAGE_SIZE); const rtWindowSize = imageImportsHwjsRt(wasmBytes) ? HWJS_RT_WINDOW_SIZE2 : 0; const libcDigest = imageNeededLibcDigest(wasmBytes); if (libcDigest !== null && rtWindowSize === 0) { throw new Error( "hwjs-libc: the image carries wasm.linux.needed but does not import the hwjs runtime (env.__hwjs_frame_alloc) \u2014 a dynamic-libc main is rt-importing by construction; refusing a foreign shape (never-silent)" ); } const libcWindowSize = libcDigest !== null ? HWJS_LIBC_WINDOW_SIZE2 : 0; const bumpStart = mmapFloor + rtWindowSize + libcWindowSize; let memBytes = userMem.buffer.byteLength; if (!(mmapFloor >= alignUp2(heapBase, WASM_PAGE_SIZE))) { throw new Error(`hwjs port BUG: mmap_floor 0x${mmapFloor.toString(16)} < aligned __heap_base 0x${alignUp2(heapBase, WASM_PAGE_SIZE).toString(16)} (F30 partition inverted)`); } const moduleMinBytes = readMemImportMinBytes(wasmBytes); const needBytes = Math.max(bumpStart + MMAP_MIN_HEADROOM, moduleMinBytes); if (needBytes > memBytes) { if (HWJS_NO_USERMEM_GROW) { throw new Error(`hwjs A-5.a RED arm (HWJS_NO_USERMEM_GROW): need 0x${needBytes.toString(16)} (mmap_floor 0x${mmapFloor.toString(16)} + headroom 0x${MMAP_MIN_HEADROOM.toString(16)}, module-min 0x${moduleMinBytes.toString(16)}) exceeds user_memory 0x${memBytes.toString(16)} and grow-to-fit is disabled (small-initial exec needs grow)`); } const growPages = Math.ceil((needBytes - memBytes) / 65536); try { userMem.grow(growPages); } catch (_e) { throw new Error( userMemoryGrowRefusal(attribution.ram, userMem, pid, "exec grow-to-fit", needBytes) + ` [partition detail: mmap_floor 0x${mmapFloor.toString(16)} + headroom 0x${MMAP_MIN_HEADROOM.toString(16)}, module-declared minimum 0x${moduleMinBytes.toString(16)}, grow-to-fit needed ${growPages} pages; lowering BRK_RESERVE also shrinks the requirement]` ); } memBytes = userMem.buffer.byteLength; if (needBytes > memBytes) { throw new Error(`hwjs port BUG: grow-to-fit by ${growPages} pages did not satisfy need 0x${needBytes.toString(16)} (now 0x${memBytes.toString(16)}; F30 partition does not fit)`); } } if (bumpStart < WASM_MMAP_BASE) { throw new Error(`hwjs port BUG: mmap bump start 0x${bumpStart.toString(16)} (mmap_floor 0x${mmapFloor.toString(16)} + rt window 0x${rtWindowSize.toString(16)} + libc window 0x${libcWindowSize.toString(16)}) below the 4 MiB assert-min (image __heap_base 0x${heapBase.toString(16)} implausibly low)`); } setUserBump(userMem, bumpStart); userMemoryMmapFreeLists.set(userMem, []); userMemorySignalPageFreeLists.set(userMem, []); const part = { heapBase, mmapFloor, brk: heapBase, brkHighWater: heapBase, rtWindowBase: rtWindowSize > 0 ? mmapFloor : 0, rtWindowSize, libcWindowBase: libcWindowSize > 0 ? mmapFloor + rtWindowSize : 0, libcWindowSize }; userMemoryPartitions.set(userMem, part); partitionReports.push({ memBytes, heapBase, mmapFloor, brkHighWater: heapBase }); return part; } function getUserBump(userMem) { const b = userMemoryBumpPointers.get(userMem); if (b === void 0) { throw new Error( "hwjs port BUG: user_memory mmap floor not initialized before mmap/region alloc \u2014 the F30 partition for this Memory is absent (retired WASM_MMAP_BASE default must never be hit). Either it was never set at instance-creation, or it was RECLAIMED by a process exit while a task still dispatching against this Memory was alive \u2014 a thread of that group is the case that has actually happened" ); } return b; } function allocSignalPendingRegion(userMem) { const freed = userMemorySignalPageFreeLists.get(userMem); let offset; if (freed && freed.length > 0) { offset = freed.pop(); } else { let bump = getUserBump(userMem); bump = alignUp2(bump, WASM_PAGE_SIZE); let memBytes = userMem.buffer.byteLength; if (bump + WASM_PAGE_SIZE > memBytes) { if (HWJS_NO_USERMEM_GROW) return -1; const deficitPages = Math.ceil((bump + WASM_PAGE_SIZE - memBytes) / 65536); try { userMem.grow(deficitPages); } catch (_e) { return -1; } memBytes = userMem.buffer.byteLength; if (bump + WASM_PAGE_SIZE > memBytes) return -1; } offset = bump; setUserBump(userMem, bump + WASM_PAGE_SIZE); } const zeroBuf = userMem.buffer; const v = new Uint8Array(zeroBuf, offset, WASM_SIGNAL_PENDING_REGION_SIZE); v.fill(0); return offset; } function freeSignalPendingRegion(userMem, offset) { if (typeof offset !== "number" || offset <= 0) return; let l = userMemorySignalPageFreeLists.get(userMem); if (!l) { l = []; userMemorySignalPageFreeLists.set(userMem, l); } l.push(offset); } function userExitInfo(msg) { return { signal: msg.kind_exit === "exit-by-signal" ? Number(msg.signal) | 0 : 0 }; } function placementCandidates(list, mergedLane, usable) { return list.some((p) => p.cpuId !== mergedLane && usable(p)) ? list.filter((p) => p.cpuId !== mergedLane) : [...list]; } function leastLoadedLane(list, busy, home) { return list.reduce((a, b) => { const ab = busy(a.cpuId), bb = busy(b.cpuId); if (ab !== bb) return ab ? b : a; if (b.residentCount !== a.residentCount) { return b.residentCount < a.residentCount ? b : a; } const aHome = !!home?.has(a.cpuId), bHome = !!home?.has(b.cpuId); return bHome && !aHome ? b : a; }); } function forkPlacementView(ownedByOthers, parentCpuId) { const avoid = parentCpuId !== void 0 && !ownedByOthers.has(parentCpuId) ? parentCpuId : void 0; return { foreign: ownedByOthers, avoid }; } function makeKernelSpawnHandler(opts) { const parents = /* @__PURE__ */ new Map(); const taskLedger = makeTaskLedger(); opts.ram.setUserMemoryInUseResolver?.(userMemoryInUseBytes); const cloneCleartidMap = /* @__PURE__ */ new Map(); const kernelLaneLocks = new SharedArrayBuffer(64 * 4); const fileMapGen = new SharedArrayBuffer((2 + 1024 + 2 + 512 * 8 + 1024) * 4); const maxCpuId = Math.max(1, opts.maxCpuId ?? defaultPoolMaxCpuId()); const MERGED_LANE = 1; const laneIsMerged = (cpuId) => cpuId === MERGED_LANE; let laneCeiling = Math.max(maxCpuId, (opts.laneCeiling ?? maxCpuId) | 0); let hostSyncCall = null; const syscallSyncDoors = /* @__PURE__ */ new Map(); const registerSyncDoors = /* @__PURE__ */ new Map(); const execInstallSyncDoors = /* @__PURE__ */ new Map(); const mergedSyscallDoor = (m) => { const msg = m; if (typeof msg?.routeKey !== "number") return void 0; if (msg.kind === "syscall-sync") { const door2 = syscallSyncDoors.get(msg.routeKey); return door2 ? door2() : void 0; } if (msg.kind === "dmesg-sync") { if (!opts.onDmesg) return void 0; const m2 = msg; opts.onDmesg( (Number(m2.level) | 0) >>> 0, String(m2.text ?? ""), typeof m2.pid === "number" ? m2.pid | 0 : -1 ); return "delivered"; } if (msg.kind === "task-register-sync") { const reg = registerSyncDoors.get(msg.routeKey); if (!reg) return void 0; const pid = typeof msg.pid === "number" ? msg.pid | 0 : 0; return pid > 0 ? reg(pid) : void 0; } if (msg.kind === "exec-install-sync") { const door2 = execInstallSyncDoors.get(msg.routeKey); const img = msg.wasmBytes; if (!door2 || !(img instanceof Uint8Array) || img.length === 0) return void 0; return door2(img); } return void 0; }; const mergedRealmDoor = (m) => { const r = mergedSyscallDoor(m); if (r !== void 0) return r; return hostSyncCall !== null ? hostSyncCall(m) : void 0; }; const setHostSyncCall = (fn2) => { hostSyncCall = fn2; for (const p of mergedInlineRealms) p.setHostSyncCall?.(mergedRealmDoor); }; const mergedInlineRealms = []; const setLaneCeiling = (n) => { if (!Number.isFinite(n)) return; const v = Math.max(maxCpuId, n | 0); if (v === laneCeiling) return; laneCeiling = v; opts.onDmesg?.( 6, `hwjs-lanes: dedicated-Worker lane band = ${maxCpuId + 1}..${laneCeiling} (pool holds 1..${maxCpuId}); thread Workers are kernel-lane disjoint from pool residents by construction `, -1 ); }; const poolLaneBusy = (c) => { for (const pw of poolWorkers) if (pw.cpuId === c) return pw.residentCount > 0; return false; }; const inUseCpuIds = /* @__PURE__ */ new Set(); const cpuIdByTid = /* @__PURE__ */ new Map(); const allocateCpuId = (tid, avoidCpuId) => { for (let c = laneCeiling; c > maxCpuId; c--) { if (!inUseCpuIds.has(c)) { inUseCpuIds.add(c); cpuIdByTid.set(tid, c); return c; } } for (let pass = 0; pass < 2; pass++) { for (let c = maxCpuId; c >= 1; c--) { if (avoidCpuId !== void 0 && c === avoidCpuId && maxCpuId > 1) continue; if (laneIsMerged(c)) continue; if (inUseCpuIds.has(c)) continue; if (pass === 0 && poolLaneBusy(c)) continue; inUseCpuIds.add(c); cpuIdByTid.set(tid, c); if (poolLaneBusy(c)) { opts.onDmesg?.( 4, `hwjs-lanes: dedicated Worker tid=${tid} placed on kernel lane ${c}, which a POOL Worker with live residents also uses \u2014 the lane mutex is now shared with an independently-scheduled peer (a peer parked in an unbounded in-kernel wait will stall this Worker). Raise num_vcpu so the dedicated band (${maxCpuId + 1}..) has room. `, tid ); } return c; } } if (avoidCpuId !== void 0 && avoidCpuId >= 1 && avoidCpuId <= maxCpuId && !laneIsMerged(avoidCpuId) && !inUseCpuIds.has(avoidCpuId)) { inUseCpuIds.add(avoidCpuId); cpuIdByTid.set(tid, avoidCpuId); return avoidCpuId; } return 0; }; const releaseCpuId = (tid) => { const c = cpuIdByTid.get(tid); if (c !== void 0) { inUseCpuIds.delete(c); cpuIdByTid.delete(tid); } }; const reclaimDedicatedLane = (cpuId, tid, why) => { if (!(cpuId > maxCpuId) || cpuId < 1) return; const i32 = new Int32Array(kernelLaneLocks); if (cpuId >= i32.length) return; if (Atomics.load(i32, cpuId) === 0) return; const ownerIdx = 32 + cpuId; if (ownerIdx < i32.length) Atomics.store(i32, ownerIdx, 0); Atomics.store(i32, cpuId, 0); Atomics.notify(i32, cpuId, Infinity); opts.onUserError?.( tid, `hwjs-lanes: kernel lane ${cpuId} was still HELD by the terminated dedicated Worker tid=${tid} (${why}) \u2014 the mutex word has been reclaimed by the host. Without this the lane stays locked for the life of the machine and the next Worker on it starves the full lane deadline (loud, attributed, never silent).` ); }; const allocateCpuIdValue = () => { for (let c = laneCeiling; c > maxCpuId; c--) { if (!inUseCpuIds.has(c)) { inUseCpuIds.add(c); return c; } } for (let pass = 0; pass < 2; pass++) { for (let c = maxCpuId; c >= 1; c--) { if (laneIsMerged(c)) continue; if (inUseCpuIds.has(c)) continue; if (pass === 0 && poolLaneBusy(c)) continue; inUseCpuIds.add(c); return c; } } return 0; }; const releaseCpuIdValue = (c) => { inUseCpuIds.delete(c); }; const platformForPool = opts.platform ?? detectPlatform(); const POOL_SIZE = maxCpuId; const poolEnabled = opts.vmlinuxModule !== void 0; const poolWorkers = []; const preemptCtl = new SharedArrayBuffer(preemptCtlBytes()); let preemptTimer = null; let preemptTimerStarting = null; let preemptNextSlot = POOL_SIZE + 1; const preemptRealmInit = async (slot) => { preemptTimerStarting ??= createWorker(opts.workerEntry, platformForPool, "preempt-timer", "preemption timer").then((w) => { preemptTimer = w; postToWorker(w, { kind: "preempt-timer", ctl: preemptCtl }); return w; }); const timer = await preemptTimerStarting; const ch = new globalThis.MessageChannel(); postToWorker(timer, { kind: "preempt-port", port: ch.port1 }, [ch.port1]); return { fields: { preemptCtl, preemptSlot: slot, preemptPort: ch.port2 }, transfer: [ch.port2] }; }; const heapChargeSab = new SharedArrayBuffer(4 * (POOL_SIZE + 1)); const heapChargeWords2 = new Int32Array(heapChargeSab); const jsHeapBudgetKiB = (() => { const raw = globalThis.process?.env?.HWJS_JS_HEAP_BUDGET_MIB; const mib2 = jsHeapBudgetMiBFor(platformForPool, opts.jsHeapBudgetMiB, raw); return Number.isFinite(mib2) && mib2 > 0 ? Math.floor(mib2) * 1024 : 0; })(); let heapCollectAskedAt = 0; let heapRefusalNotedAt = 0; let heapNotedStep = 0; const heapAccountedKiB = () => { let kib = 0; for (let i = 0; i < heapChargeWords2.length; i++) kib += Atomics.load(heapChargeWords2, i); kib += (legacyWorkers.size + (preemptTimer ? 1 : 0)) * JS_HEAP_REALM_BASE_KIB; return kib; }; const heapAskCollect = () => { const now = Date.now(); if (now - heapCollectAskedAt < JS_HEAP_COLLECT_GAP_MS) return; heapCollectAskedAt = now; for (const pw of poolWorkers) { try { postToWorker(pw.worker, { kind: "heap-collect" }); } catch { } } }; const heapBudgetRefusal = (what) => { const kib = heapAccountedKiB(); const step = Math.floor(kib / (256 * 1024)); if (step !== heapNotedStep) { heapNotedStep = step; const lanes = []; for (let i = 1; i < heapChargeWords2.length; i++) lanes.push(String(Math.round(Atomics.load(heapChargeWords2, i) / 1024))); opts.onDmesg?.(6, `hwjs-heap-budget: ${Math.round(kib / 1024)} MiB accounted (budget ${jsHeapBudgetKiB === 0 ? "off" : `${Math.round(jsHeapBudgetKiB / 1024)} MiB`}); lanes 1.. ${lanes.join(" ")} MiB `, -1); } if (jsHeapBudgetKiB === 0) return ""; if (kib >= jsHeapBudgetKiB * JS_HEAP_COLLECT_SHARE) heapAskCollect(); if (kib < jsHeapBudgetKiB) return ""; const why = `${what} refused: the machine's Workers account ${Math.round(kib / 1024)} MiB of JS heap against a budget of ${Math.round(jsHeapBudgetKiB / 1024)} MiB (hwjs.js_heap_budget); one more risks the whole tab. Every realm was asked to collect; retry later`; const now = Date.now(); if (now - heapRefusalNotedAt >= 1e3) { heapRefusalNotedAt = now; opts.onDmesg?.(4, `hwjs-heap-budget: ${why} `, -1); } return why; }; const laneBusySab = new SharedArrayBuffer(4 * (POOL_SIZE + 1)); const laneBusyWords = new Int32Array(laneBusySab); const laneIsBusy = (cpuId) => cpuId >= 0 && cpuId < laneBusyWords.length && Atomics.load(laneBusyWords, cpuId) !== 0; const laneInboxByRealm = /* @__PURE__ */ new WeakMap(); const laneInboxPost = (realm) => { const w = realm !== null && typeof realm === "object" ? laneInboxByRealm.get(realm) : void 0; if (w !== void 0) Atomics.add(w, 0, 1); }; const poolHandlers = /* @__PURE__ */ new Map(); let nextRouteKey = 1; let liveResidents = 0; let peakResidents = 0; const noteResidentDelta = (d) => { liveResidents = Math.max(0, liveResidents + d); if (liveResidents > peakResidents) peakResidents = liveResidents; }; const laneOwners = /* @__PURE__ */ new Map(); let unknownGroupSeq = 0; const newLaneOwner = (group) => ({ group: group === void 0 ? --unknownGroupSeq : group }); const laneOccupy = (cpuId, owner) => { let s = laneOwners.get(cpuId); if (!s) { s = /* @__PURE__ */ new Set(); laneOwners.set(cpuId, s); } s.add(owner); }; const laneRelease = (cpuId, owner) => { const s = laneOwners.get(cpuId); if (!s) return; s.delete(owner); if (s.size === 0) laneOwners.delete(cpuId); }; const lanesOwnedByGroup = (group) => { const out = /* @__PURE__ */ new Set(); for (const [cpu, owners] of laneOwners) { for (const o of owners) { if (o.group === group) { out.add(cpu); break; } } } return out; }; const lanesOwnedByOthers = (group) => { const out = /* @__PURE__ */ new Set(); for (const [cpu, owners] of laneOwners) { for (const o of owners) { if (o.group !== group) { out.add(cpu); break; } } } return out; }; const lanesCarryingAnyOwner = () => { const out = /* @__PURE__ */ new Set(); for (const [cpu, owners] of laneOwners) if (owners.size > 0) out.add(cpu); return out; }; const laneOwnerText = (cpuId) => { const s = laneOwners.get(cpuId); return s && s.size > 0 ? [...s].map((o) => o.group).sort((a, b) => a - b).join(",") : "none"; }; const taskWakeAddrByPid = /* @__PURE__ */ new Map(); let kernelWakeBuf = opts.kernelMemory; let kernelWakeI32 = new Int32Array(kernelWakeBuf); let wakeRefused = false; const wakeTaskByPid = (pid) => { const wakeAddr = taskWakeAddrByPid.get(pid >>> 0); if (!wakeAddr) return; const liveBuf = opts.kernelMemoryWasm?.buffer; if (liveBuf !== void 0 && liveBuf !== kernelWakeBuf) { kernelWakeBuf = liveBuf; kernelWakeI32 = new Int32Array(liveBuf); } const idx = wakeAddr >>> 0 >>> 2; if ((wakeAddr & 3) !== 0 || idx >= kernelWakeI32.length) { if (!wakeRefused) { wakeRefused = true; console.error( `kernelSpawnHandler: REFUSING the task wake for pid ${pid} \u2014 published address ${wakeAddr >>> 0} (index ${idx}) is not addressable in guest RAM: the view is ${kernelWakeI32.length} words / ${kernelWakeI32.length * 4} bytes, live kernel_memory is ${kernelWakeBuf.byteLength} bytes. The view is LIVE, so this is not a stale snapshot \u2014 that address is not a task_struct field. The parent will fall back to its cooperative timeout, so forks still complete but pay the wait. Reported once.` ); } return; } Atomics.add(kernelWakeI32, idx, 1); Atomics.notify(kernelWakeI32, idx, Infinity); }; const legacyWorkers = /* @__PURE__ */ new Set(); let disposed = false; const taskProbePending = /* @__PURE__ */ new Map(); let taskProbeSeq = 1; const deliverTaskProbeReply = (m) => { const r = taskProbePending.get((m?.seq | 0) >>> 0); if (r) r(m); }; const sharedLibs = /* @__PURE__ */ new Map(); const sharedLibsForInit = () => [...sharedLibs].map(([digest, e]) => ({ digest, bytes: e.bytes, ...e.module ? { module: e.module } : {}, ...e.path ? { path: e.path } : {} })); const deliverSharedLib = (digest, bytesIn, from, moduleIn, pathIn) => { if (!/^[0-9a-f]{64}$/.test(digest)) { opts.onUserError?.(-1, `hwjs-libc: shared-lib delivery (${from}) with a malformed digest ${JSON.stringify(digest.slice(0, 80))} \u2014 REFUSED (never-silent)`); return Promise.resolve(false); } if (sharedLibs.has(digest)) return Promise.resolve(true); const bytes = bytesIn instanceof Uint8Array ? bytesIn : new Uint8Array(bytesIn); const kept = retainedLibraryInfo(bytes); if (kept && (kept.digest !== digest || !(moduleIn instanceof WebAssembly.Module))) { opts.onUserError?.(-1, `hwjs-libc: shared-lib delivery (${from}) for libc.so.${digest.slice(0, 16)}\u2026 is the retained copy of ${kept.digest.slice(0, 16)}\u2026 ${moduleIn instanceof WebAssembly.Module ? "under another digest" : "with no Module"} \u2014 REFUSED (never-silent)`); return Promise.resolve(false); } if (!kept && moduleIn instanceof WebAssembly.Module) { let why = ""; try { if (retainedLibraryInfo(retainedLibraryBytes(bytes, digest))) { why = `brings a Module with the whole file (${bytes.length}B), not its retained copy`; } } catch (e) { why = `brings a Module with bytes that are no module: ${e instanceof Error ? e.message : String(e)}`; } if (why) { opts.onUserError?.(-1, `hwjs-libc: shared-lib delivery (${from}) for libc.so.${digest.slice(0, 16)}\u2026 ${why} \u2014 REFUSED (never-silent)`); return Promise.resolve(false); } } const entry = { bytes }; const where = typeof pathIn === "string" && pathIn.startsWith("/") ? { path: pathIn } : {}; if (where.path) entry.path = where.path; sharedLibs.set(digest, entry); if (moduleIn instanceof WebAssembly.Module) { entry.module = moduleIn; for (const pw of poolWorkers) { try { postToWorker(pw.worker, { kind: "shared-lib", sharedLibs: [{ digest, bytes, module: moduleIn, ...where }] }); } catch { } } opts.onDmesg?.(6, `hwjs-libc: host retained libc.so.${digest.slice(0, 16)}\u2026 (${bytes.length}B of ${kept ? kept.wireLength : bytes.length}B, ${from}); took the Module compiled there; broadcast to ${poolWorkers.length} pool worker(s) `, -1); return Promise.resolve(true); } const p = (async () => { try { const priv = privateImageCopy(bytes); const subtle = globalThis.crypto?.subtle; if (subtle) { const buf = await subtle.digest("SHA-256", priv); const hex = [...new Uint8Array(buf)].map((x) => x.toString(16).padStart(2, "0")).join(""); if (hex !== digest) { sharedLibs.delete(digest); opts.onUserError?.(-1, `hwjs-libc: HOST CONTENT SKEW \u2014 delivered libc.so.${digest.slice(0, 16)}\u2026 (${from}) hashes to ${hex.slice(0, 16)}\u2026; delivery REFUSED machine-wide (never-silent)`); return false; } } const module = await WebAssembly.compile(priv); const walkStop = {}; const keptBytes = retainedLibraryBytes(bytes, digest, walkStop); const e = sharedLibs.get(digest); if (e) { e.module = module; e.bytes = keptBytes; } for (const pw of poolWorkers) { try { postToWorker(pw.worker, { kind: "shared-lib", sharedLibs: [{ digest, bytes: keptBytes, module, ...where }] }); } catch { } } opts.onDmesg?.(6, `hwjs-libc: host retained libc.so.${digest.slice(0, 16)}\u2026 (${keptBytes.length}B of ${bytes.length}B, ${from}); compiled once; broadcast to ${poolWorkers.length} pool worker(s) `, -1); if ((walkStop.verdict ?? "none") !== "none") { opts.onDmesg?.(5, `hwjs-libc: libc.so.${digest.slice(0, 16)}\u2026 code walk: ${walkStop.verdict} (${walkStop.op ?? "?"} at byte ${walkStop.at ?? "?"}); its loads find table slots by reading the whole table, not from the table's index (slower, not wrong) (once per boot per digest) `, -1); } return true; } catch (e) { sharedLibs.delete(digest); opts.onUserError?.(-1, `hwjs-libc: host retention of libc.so.${digest.slice(0, 16)}\u2026 (${from}) FAILED: ${e instanceof Error ? e.message : String(e)} (never-silent)`); return false; } })(); entry.pending = p; void p.then( () => { if (entry.pending === p) delete entry.pending; }, () => { if (entry.pending === p) delete entry.pending; } ); return p; }; const sharedLibDeliveryPending = (digest) => sharedLibs.get(digest)?.pending; const USER_IMAGE_REGISTRY_MAX = 8; const userImages = /* @__PURE__ */ new Map(); const userImagesBump = (key) => { const e = userImages.get(key); if (e) { userImages.delete(key); userImages.set(key, e); } }; const userImagesEvict = () => { while (userImages.size > USER_IMAGE_REGISTRY_MAX) { const oldest = userImages.keys().next().value; if (oldest === void 0) break; userImages.delete(oldest); } }; const userImagesForInit = () => { const out = []; for (const [key, e] of userImages) if (e.module) out.push({ key, module: e.module }); return out; }; const threadImages = makeThreadImageLedger((cpuId, memoryId) => { const pw = poolWorkers.find((p) => p.cpuId === cpuId); try { if (pw) postToWorker(pw.worker, { kind: "thread-image-drop-idle", memoryId, cpuId }); } catch { } }); const releaseThreadImages = (memoryId, beforeEpoch) => { if (beforeEpoch === void 0) threadImages.imageGone(memoryId); else threadImages.imageReplaced(memoryId); for (const pw of poolWorkers) { try { postToWorker(pw.worker, { kind: "thread-image-release", memoryId, cpuId: pw.cpuId, ...beforeEpoch !== void 0 ? { beforeEpoch } : {} }); } catch { } } }; const broadcastUserImage = (key, module, exceptWorker) => { let n = 0; for (const pw of poolWorkers) { if (exceptWorker !== void 0 && pw.worker === exceptWorker) continue; try { postToWorker(pw.worker, { kind: "user-image", userImages: [{ key, module }] }); n++; } catch { } } return n; }; const userImageModule = (bytes) => { if (!(bytes instanceof Uint8Array) || bytes.length === 0) return Promise.resolve(null); const key = userImageKeys.keyOf(bytes); const have = userImages.get(key); if (have) { userImagesBump(key); if (have.module) return Promise.resolve(have.module); if (have.pending) return have.pending; } const entry = { byteLength: bytes.length }; userImages.set(key, entry); userImagesEvict(); const p = (async () => { try { const module = await WebAssembly.compile( wasmSource(bytes) ); const e = userImages.get(key); if (e === entry) e.module = module; const n = broadcastUserImage(key, module); opts.onDmesg?.( 6, `hwjs-image: host compiled user image ${key} (${bytes.length}B) ONCE; broadcast to ${n} pool worker(s) `, -1 ); return module; } catch (e) { userImages.delete(key); opts.onUserError?.( -1, `hwjs-image: host compile of user image ${key} (${bytes.length}B) FAILED: ${e instanceof Error ? e.message : String(e)} \u2014 the placing Worker will compile it locally (slower, not wrong) (never-silent)` ); return null; } })(); entry.pending = p; void p.then( () => { if (entry.pending === p) delete entry.pending; }, () => { if (entry.pending === p) delete entry.pending; } ); return p; }; const noteWorkerCompiledUserImage = (msg, fromWorker) => { const m = msg; if (typeof m.key !== "string" || !(m.module instanceof WebAssembly.Module)) return; const existing = userImages.get(m.key); if (existing?.module) { userImagesBump(m.key); return; } userImages.set(m.key, { module: m.module, byteLength: typeof m.byteLength === "number" ? m.byteLength : 0 }); userImagesEvict(); const n = broadcastUserImage(m.key, m.module, fromWorker); opts.onDmesg?.( 6, `hwjs-image: adopted a pool-compiled user image ${m.key} (${typeof m.byteLength === "number" ? m.byteLength : "?"}B); broadcast to ${n} other pool worker(s) `, -1 ); }; const LINK_FACTS_REGISTRY_MAX = 4096; const linkFacts2 = /* @__PURE__ */ new Map(); const linkFactsForInit = () => { const out = []; for (const [id, facts] of linkFacts2) out.push({ id, facts }); return out; }; const noteWorkerLinkFacts = (msg, fromWorker) => { const m = msg; if (!Array.isArray(m.entries)) return; const fresh = []; for (const e of m.entries) { if (!e || typeof e.id !== "string" || e.facts === null || typeof e.facts !== "object") continue; linkFacts2.delete(e.id); linkFacts2.set(e.id, e.facts); fresh.push({ id: e.id, facts: e.facts }); } while (linkFacts2.size > LINK_FACTS_REGISTRY_MAX) { const oldest = linkFacts2.keys().next().value; if (oldest === void 0) break; linkFacts2.delete(oldest); } if (fresh.length === 0) return; for (const pw of poolWorkers) { if (pw.worker === fromWorker) continue; try { postToWorker(pw.worker, { kind: "link-facts", entries: fresh }); } catch { } } }; const createPoolWorker = async (cpuId, origin = "pool") => { if (laneIsMerged(cpuId)) { const [{ createInlineRealm: createInlineRealm2 }, { bindInlineWorker: bindInlineWorker2 }] = await Promise.all([ Promise.resolve().then(() => (init_inlineRealm(), inlineRealm_exports)), Promise.resolve().then(() => (init_worker_inline(), worker_inline_exports)) ]); const inline = createInlineRealm2(bindInlineWorker2, `pool-inline-cpu${cpuId}`); const tookARealm = workerRealmOrigin(inline) !== void 0; mergedInlineRealms.push(inline); inline.setHostSyncCall(mergedRealmDoor); opts.onDmesg?.( tookARealm ? 3 : 6, `hwjs-merged: pool lane ${cpuId} is INLINE \u2014 it shares this thread with CPU 0, and every other lane keeps its Worker. MEASURED: the realm census ${tookARealm ? "COUNTS this lane's realm, so it DID take a host Worker and the merge did not happen here" : "does not hold it, so this lane has no host Worker realm"}. `, -1 ); return initPoolWorker(inline, cpuId); } const worker = await createWorker(opts.workerEntry, platformForPool, origin, `vcpu${cpuId}`); return initPoolWorker(worker, cpuId); }; const initPoolWorker = async (worker, cpuId) => { const pw = { worker, cpuId, residentCount: 0 }; onMessage(worker, (msg) => { const rk = msg?.routeKey; if (rk != null) { const h = poolHandlers.get(rk); if (h) { void h(msg); return; } return; } if (msg?.kind === "dmesg") opts.onDmesg?.((msg.level | 0) >>> 0, String(msg.text), -1); else if (msg?.kind === "task-probe-reply") deliverTaskProbeReply(msg); else if (msg?.kind === "error") opts.onUserError?.(-1, String(msg.message ?? "")); else if (msg?.kind === "user-report") opts.onUserError?.(-1, String(msg.message ?? "")); else if (msg?.kind === "machine-power") opts.onMachinePower?.((msg.cmd | 0) >>> 0); else if (msg?.kind === "user-image-compiled") noteWorkerCompiledUserImage(msg, worker); else if (msg?.kind === "link-facts") noteWorkerLinkFacts(msg, worker); }); onError(worker, (e) => { opts.onUserError?.(-1, `pool CPU-Worker cpu_id=${cpuId} crashed: ${e instanceof Error ? `${e.message} ${e.stack}` : String(e)}`); }); const preemptInit = await preemptRealmInit(cpuId); const laneInbox = new SharedArrayBuffer(4); laneInboxByRealm.set(worker, new Int32Array(laneInbox)); postToWorker(worker, { kind: "cpu-worker", cpuId, ...preemptInit.fields, /* * COLLAPSED CPU 0: is THIS lane the one sharing its JS thread with * CPU 0 (PLAN-COLLAPSED-CPU0 §2.1)? The lane has to know, because * three things it is otherwise allowed to do stop being allowed: * an unbounded in-kernel atomic wait (§3.5 — it would freeze CPU 0 * and, inline, the device backends that produce the very wake it is * waiting for), the cross-Worker lane mutex's Atomics.wait (§5 — two * same-thread lanes self-deadlock on it), and the host-RPC wait * (§3.4 — inline, the responder is this same thread). Each refuses * loudly instead, naming this flag. */ ...laneIsMerged(cpuId) ? { mergedCpu0Lane: true } : {}, ...opts.vmlinuxModule !== void 0 ? { vmlinuxModule: opts.vmlinuxModule } : {}, ...opts.hwjsRtModule !== void 0 ? { hwjsRtModule: opts.hwjsRtModule, hwjsRtBytes: opts.hwjsRtBytes, hwjsRtProvenance: opts.hwjsRtProvenance } : {}, /* The machine-wide shared-lib map at pool-Worker creation * (usually empty — the eager pool warms up before any exec; later * digests arrive via the 'shared-lib' broadcast). */ ...sharedLibs.size > 0 ? { sharedLibs: sharedLibsForInit() } : {}, /* The machine-wide COMPILED user-image registry at realm creation. * A BOOT-time realm normally finds this empty; a `pool-recycle` realm * does NOT, and that is the point — it is born holding what the realm * it replaced compiled, so a recycle costs a structured clone instead * of a fresh compile of every image the machine is running. */ ...userImages.size > 0 ? { userImages: userImagesForInit() } : {}, ...linkFacts2.size > 0 ? { linkFacts: linkFactsForInit() } : {}, /* * THE RAW SAB IS POSTED ONLY WHEN THERE IS NO `WebAssembly.Memory` TO * DERIVE IT FROM (a pre-`kernelMemoryWasm` embedder). Every machine * this codebase boots supplies both, and posting both put TWO distinct * SharedArrayBuffer objects over ONE backing store into every realm — * confirmed in a heap snapshot, and V8 charges `GetByteLength()` per * reachable ArrayBuffer per realm, so the kernel memory counted twice * in the reported figure for nothing. * * It was also a live STALE-BUFFER HAZARD of the class that cost eight * gate boots last round: `opts.kernelMemory` is the buffer captured at * PhysRam construction, frozen at KERNEL_SAB_INITIAL_BYTES * (physRam.ts), while the kernel grows its Memory on demand * (arch/wasm32/mm/memcommit.c). After the first growth the two objects * disagree about how big the kernel's RAM is, and only one of them is * right. Nothing in a Worker should be able to reach the wrong one. */ ...opts.kernelMemoryWasm === void 0 ? { kernelMemory: opts.kernelMemory } : {}, ...opts.kernelMemoryWasm !== void 0 ? { kernelMemoryWasm: opts.kernelMemoryWasm } : {}, kernelLaneLocks, fileMapGen, laneBusy: laneBusySab, heapCharge: heapChargeSab, laneInbox, ...opts.pauseBuffer !== void 0 ? { pauseBuffer: opts.pauseBuffer } : {} }, preemptInit.transfer); if (disposed) { void terminateWorker(worker); return null; } poolWorkers.push(pw); return pw; }; let poolReady = Promise.resolve(); if (poolEnabled) { poolReady = (async () => { const tasks = []; for (let cpuId = 1; cpuId <= POOL_SIZE; cpuId++) tasks.push(createPoolWorker(cpuId)); await Promise.all(tasks); })(); poolReady.catch(() => { }); } const laneSuspectUntil = /* @__PURE__ */ new Map(); const LANE_SUSPECT_COOLDOWN_MS = 3e4; const getPoolWorker = async (avoidCpuId, excludeCpuIds, pinCpuId, foreignCpuIds, homeCpuIds, mergedLast) => { await poolReady; if (disposed || poolWorkers.length === 0) { throw new Error("kernelSpawnHandler: spawn after dispose() / empty pool"); } if (pinCpuId !== void 0) { const pinned = poolWorkers.find((p) => p.cpuId === pinCpuId); if (pinned) return pinned; throw new Error( `HWJS_THREAD_PLACEMENT_PIN names pool cpu=${pinCpuId}, which is in range but has NO LIVE pool Worker right now (live lanes: ${poolWorkers.map((p) => p.cpuId).join(",") || "none"}) \u2014 refusing to substitute another lane, because a substituted pin reports a placement the experiment never ran` ); } const now = Date.now(); const suspect = (cpuId) => (laneSuspectUntil.get(cpuId) ?? 0) > now; const leastLoaded = (all) => { const unmerged = mergedLast ? all.filter((p) => !laneIsMerged(p.cpuId)) : all; return leastLoadedLane(unmerged.length > 0 ? unmerged : all, laneIsBusy, homeCpuIds); }; const usable = (p) => !excludeCpuIds?.has(p.cpuId) && !suspect(p.cpuId); const notExcluded = placementCandidates(poolWorkers, MERGED_LANE, usable).filter( (p) => !excludeCpuIds?.has(p.cpuId) ); const notSuspect = notExcluded.filter((p) => !suspect(p.cpuId)); const friendly = notSuspect.filter((p) => !foreignCpuIds?.has(p.cpuId)); const tierOne = friendly.filter((p) => p.cpuId !== avoidCpuId); if (mergedLast) { if (homeCpuIds && homeCpuIds.size > 0 && threadPrefersHomeLane(heapAccountedKiB(), jsHeapBudgetKiB)) { const home = notSuspect.filter((p) => homeCpuIds.has(p.cpuId) && !laneIsMerged(p.cpuId)); const homeAway = home.filter((p) => p.cpuId !== avoidCpuId); if (homeAway.length > 0) return leastLoaded(homeAway); if (home.length > 0) return leastLoaded(home); } const free = (p) => p.cpuId !== avoidCpuId && !laneIsMerged(p.cpuId) && !laneIsBusy(p.cpuId) && !homeCpuIds?.has(p.cpuId); const freeFriendly = tierOne.filter(free); if (freeFriendly.length > 0) return leastLoaded(freeFriendly); const freeStranger = notSuspect.filter(free); if (freeStranger.length > 0) return leastLoaded(freeStranger); const unmerged = notSuspect.filter((p) => !laneIsMerged(p.cpuId)); if (unmerged.length > 0) return leastLoaded(unmerged); } if (tierOne.length > 0) return leastLoaded(tierOne); if (friendly.length > 0) return leastLoaded(friendly); const tierThree = notSuspect.filter((p) => p.cpuId !== avoidCpuId); if (tierThree.length > 0) return leastLoaded(tierThree); if (notSuspect.length > 0) return leastLoaded(notSuspect); if (notExcluded.length > 0) return leastLoaded(notExcluded); return leastLoaded(poolWorkers); }; const markLaneSuspect = (cpuId) => { laneSuspectUntil.set(cpuId, Date.now() + LANE_SUSPECT_COOLDOWN_MS); }; const markLaneLive = (cpuId) => { laneSuspectUntil.delete(cpuId); }; let reclaimInFlight = null; const reclaimUserMemorySweep = async (reason) => { let recycled = 0; if (poolEnabled && !disposed) { try { await poolReady; } catch { } const candidates = poolWorkers.filter( (p) => p.residentCount === 0 && !laneIsMerged(p.cpuId) ); let collected = 0; for (const pw of poolWorkers) { if (candidates.includes(pw)) continue; try { postToWorker(pw.worker, { kind: "heap-collect" }); collected++; } catch { } } opts.onDmesg?.( 6, `hardwarejs#7 reclaim(${reason}): ${collected} lane(s) with residents (lane ${MERGED_LANE}, the merged CPU-0 lane, among them) were asked to collect in place; ${candidates.length} idle lane(s) recycle. `, -1 ); for (const pw of candidates) { if (disposed) break; if (pw.residentCount !== 0 || !poolWorkers.includes(pw)) continue; let fresh = null; try { fresh = await createPoolWorker(pw.cpuId, "pool-recycle"); } catch (e) { opts.onDmesg?.( 3, `hardwarejs#7 reclaim(${reason}): replacement pool Worker for lane cpu=${pw.cpuId} failed to spawn (${e instanceof Error ? e.message : String(e)}) \u2014 keeping the old Worker `, -1 ); continue; } if (fresh === null) break; if (pw.residentCount === 0) { const i = poolWorkers.indexOf(pw); if (i >= 0) poolWorkers.splice(i, 1); try { await terminateWorker(pw.worker); } catch { } recycled++; } else { const i = poolWorkers.indexOf(fresh); if (i >= 0) poolWorkers.splice(i, 1); try { await terminateWorker(fresh.worker); } catch { } } } } const g = globalThis.gc; if (typeof g === "function") { try { g(); } catch { } } if (recycled > 0) { opts.onDmesg?.( 6, `hardwarejs#7 reclaim(${reason}): recycled ${recycled} idle pool Worker(s) (fresh realm per lane; exited processes' user SAB backing stores drop with the old realms) `, -1 ); } return { recycledWorkers: recycled }; }; const reclaimUserMemory = (reason) => { if (reclaimInFlight) return reclaimInFlight; const p = reclaimUserMemorySweep(reason).finally(() => { if (reclaimInFlight === p) reclaimInFlight = null; }); reclaimInFlight = p; return p; }; const PROACTIVE_RECLAIM_DEBOUNCE_MS = 250; const proactiveReclaimThresholdPages = () => { const raw = globalThis.process?.env?.HWJS_PROACTIVE_RECLAIM_PAGES; const v = raw !== void 0 ? parseInt(raw, 10) : NaN; return Number.isFinite(v) && v >= 0 ? v : 512; }; let proactiveReclaimTimer = null; const noteProcessExitForReclaim = () => { if (disposed) return; if (proactiveReclaimThresholdPages() === 0) return; if (proactiveReclaimTimer !== null) return; proactiveReclaimTimer = setTimeout(() => { proactiveReclaimTimer = null; if (disposed) return; const thr = proactiveReclaimThresholdPages(); if (thr === 0) return; const st = opts.ram.userMemoryStats?.(); if (!st || st.exitedUncollectedPages < thr) return; void reclaimUserMemory( `proactive-exit: ${st.exitedUncollectedCount} exited-but-uncollected SAB(s) ~${(st.exitedUncollectedPages * 65536 / (1024 * 1024)).toFixed(1)} MiB >= ${thr}-page threshold` ).catch(() => { }); }, PROACTIVE_RECLAIM_DEBOUNCE_MS); proactiveReclaimTimer.unref?.(); }; const dispose = async () => { if (disposed) return; disposed = true; if (proactiveReclaimTimer !== null) { clearTimeout(proactiveReclaimTimer); proactiveReclaimTimer = null; } try { await poolReady; } catch { } const toKill = [ ...poolWorkers.map((p) => p.worker), ...legacyWorkers, ...preemptTimer !== null ? [preemptTimer] : [] ]; preemptTimer = null; preemptTimerStarting = null; poolWorkers.length = 0; legacyWorkers.clear(); for (const w of toKill) { try { await terminateWorker(w); } catch { } } poolHandlers.clear(); parents.clear(); cloneCleartidMap.clear(); inUseCpuIds.clear(); cpuIdByTid.clear(); taskWakeAddrByPid.clear(); liveResidents = 0; peakResidents = 0; }; const threadTidsByParent = /* @__PURE__ */ new Map(); const threadSpawnsInFlight = /* @__PURE__ */ new Map(); const threadOrdinalByGroup = /* @__PURE__ */ new Map(); const threadOrdinals = { next(groupPid) { const n = (threadOrdinalByGroup.get(groupPid) ?? 0) + 1; threadOrdinalByGroup.set(groupPid, n); return n; }, dropParent(parentPid) { threadOrdinalByGroup.delete(parentPid); } }; const threadReapersByTid = /* @__PURE__ */ new Map(); const REAP_GRACE_MS = 2e3; const groupEmptyHooks = /* @__PURE__ */ new Map(); const everThreadedGroups = /* @__PURE__ */ new Set(); const runGroupEmpty = (parentPid) => { const q = groupEmptyHooks.get(parentPid); if (!q) return; groupEmptyHooks.delete(parentPid); for (const fn2 of q) { try { fn2(); } catch (e) { opts.onDmesg?.( 3, `hwjs group-empty hook for pid=${parentPid} threw: ${e instanceof Error ? e.message : String(e)} (loud; whatever it was going to release stays held) `, parentPid ); } } }; const threadContain = { note(parentPid, tid) { everThreadedGroups.add(parentPid); let s = threadTidsByParent.get(parentPid); if (!s) { s = /* @__PURE__ */ new Set(); threadTidsByParent.set(parentPid, s); } s.add(tid); }, /* A vfork child is a member while it runs over its caller's memory, so * the group's death ends it and the memory waits for it. It does not make * the memory unreusable: it is gone before its caller runs again, unless * it is reaped, which marks the group then. */ noteVfork(parentPid, tid) { let s = threadTidsByParent.get(parentPid); if (!s) { s = /* @__PURE__ */ new Set(); threadTidsByParent.set(parentPid, s); } s.add(tid); }, markEverThreaded(parentPid) { everThreadedGroups.add(parentPid); }, drop(parentPid, tid) { const s = threadTidsByParent.get(parentPid); if (!s) return; s.delete(tid); if (s.size === 0) { threadTidsByParent.delete(parentPid); runGroupEmpty(parentPid); } }, /* * RUN THIS WHEN THE GROUP'S LAST THREAD IS GONE, AND NOT BEFORE. * * THE INCIDENT (2026-08-24, the appliance's first mount teardown). The * leader's terminal event runs cleanupProcessWorker, which — since * HWJS-A-5.b — RECLAIMS the process's user_memory bookkeeping: the F30 * brk/mmap partition, the bump pointer and the mmap free list. Its comment * claims "it cannot free a live task's SAB" because it only fires on a * real terminal event. That reasoning holds for PROCESSES and is wrong for * THREADS: a thread of the group shares the leader's Memory, and the group * kill six lines above is a PENDING BIT, not a join. So the siblings were * still unwinding — and a thread unwinding is a thread calling munmap(2) * on its own stack — when the partition they dispatch against was deleted. * * What that produced, verbatim, and it named the wrong cause: * * hwjs port BUG: user_memory mmap floor not initialized before * mmap/region alloc — the F30 partition was not set at * instance-creation * * It WAS set at instance-creation. It was deleted at the leader's exit * while a thread of that process was still running. Worse than the wrong * sentence: nothing answered the munmap, so the thread parked on its ctrl * word forever (16,384 cooperative parks, 16,915 ms, still going). * * So the reclaim is DEFERRED to the moment the group is actually empty. * If it is already empty the callback runs synchronously, which is the * ordinary single-threaded process and is byte-identical to the old * behaviour. If a sibling never drops, the callback never runs and the SAB * is simply not reclaimed — the pre-A-5.b posture, a leak rather than a * corruption. In practice the group-death reaper closes that: it * terminates any survivor after REAP_GRACE_MS and its reap path calls * drop(), which is what fires this. */ consumeEverThreaded(parentPid) { return everThreadedGroups.delete(parentPid); }, whenGroupEmpty(parentPid, fn2) { if ((threadTidsByParent.get(parentPid)?.size ?? 0) === 0) { fn2(); return; } let q = groupEmptyHooks.get(parentPid); if (!q) { q = []; groupEmptyHooks.set(parentPid, q); } q.push(fn2); }, registerReaper(tid, reap) { threadReapersByTid.set(tid, reap); }, dropReaper(tid) { threadReapersByTid.delete(tid); }, liveThreads(parentPid) { return threadTidsByParent.get(parentPid)?.size ?? 0; }, /* Live threads plus admitted-but-unregistered spawns, each tid once. */ admittedThreads(parentPid) { const live2 = threadTidsByParent.get(parentPid); const pending2 = threadSpawnsInFlight.get(parentPid); if (!pending2) return live2?.size ?? 0; let n = live2?.size ?? 0; for (const t of pending2) if (!live2?.has(t)) n++; return n; }, admit(parentPid, tid) { let s = threadSpawnsInFlight.get(parentPid); if (!s) { s = /* @__PURE__ */ new Set(); threadSpawnsInFlight.set(parentPid, s); } s.add(tid); }, settle(parentPid, tid) { const s = threadSpawnsInFlight.get(parentPid); if (!s) return; s.delete(tid); if (s.size === 0) threadSpawnsInFlight.delete(parentPid); }, reapGroupAfter(parentPid, trappedTid, why) { const targets = [...threadTidsByParent.get(parentPid) ?? []].filter((t) => t !== trappedTid); if (targets.length === 0) return; const timer = setTimeout(() => { for (const t of targets) { const reap = threadReapersByTid.get(t); if (!reap) continue; opts.onDmesg?.( 3, `hwjs group-death REAP: thread tid=${t} of pid=${parentPid} survived the group's death ${REAP_GRACE_MS} ms after the stamp (${why}) \u2014 a signal-blind park (e.g. a cooperative wait on a dead holder's lock). Reaping: Worker terminated, cpu lane + cleartid + signal page + registrations released (native SIGKILL is not refusable; a wedged sibling must not leak machine thread capacity) `, t ); try { reap(why); } catch (e) { opts.onDmesg?.(3, `hwjs group-death REAP tid=${t} FAILED: ${e instanceof Error ? e.message : String(e)} (loud; the lane may stay leaked \u2014 report it) `, t); } } }, REAP_GRACE_MS); timer.unref?.(); }, killGroup(parentPid, trappedTid, sig = 9, why = "trapped terminally") { let delivered = 0; const targets = [parentPid, ...threadTidsByParent.get(parentPid) ?? []].filter((t) => t !== trappedTid); if (opts.signalRegistry) { for (const t of targets) { const req = { tid: t, sig: sig | 0, senderPid: trappedTid }; const frec = opts.signalRegistry.lookup(t); if (frec) { const fv = new Int32Array( frec.userMemory.buffer ); const s0 = sig | 0; if (s0 >= 1 && s0 <= 32) { Atomics.and( fv, frec.signalPendingOffset + 16 >>> 2, ~(1 << s0 - 1) ); } else if (s0 >= 33 && s0 <= 64) { Atomics.and( fv, frec.signalPendingOffset + 20 >>> 2, ~(1 << s0 - 33) ); } } const out = deliverSignalToTarget(opts.signalRegistry, req); if ((typeof process === "undefined" ? void 0 : process)?.env?.HWJS_DBG_KILLGROUP) { let words = ""; if (out.kind === "delivered") { const v = new Int32Array(out.rec.userMemory.buffer); const i = out.rec.signalPendingOffset >>> 2; words = ` off=0x${out.rec.signalPendingOffset.toString(16)} lo=0x${(v[i] >>> 0).toString(16)} hi=0x${(v[i + 1] >>> 0).toString(16)} mlo=0x${(v[i + 4] >>> 0).toString(16)} mhi=0x${(v[i + 5] >>> 0).toString(16)}`; } opts.onDmesg?.(3, `hwjs-killgroup DBG target=${t} outcome=${out.kind}${words} `, trappedTid); } if (out.kind === "delivered") { delivered++; } } } opts.onDmesg?.( 3, `hwjs #85 CONTAINMENT (host belt): thread tid=${trappedTid} of process pid=${parentPid} ${why} \u2014 sig=${sig | 0} stamped for the group (leader + ${targets.length - 1} sibling thread(s); ${delivered} delivered, missing targets already exited) so the process dies and the parent's wait4 resolves `, trappedTid ); this.reapGroupAfter( parentPid, trappedTid, `group death (sig=${sig | 0}: ${why})` ); } }; const optsWithCpuHooks = Object.assign({}, opts, { /* #85: thread-group membership + host-side group-kill belt. */ __threadContain: threadContain, __heapBudget: { refusal: heapBudgetRefusal }, /* per-process thread ordinals (see above). */ __threadOrdinals: threadOrdinals, __cpuIdHooks: { allocateCpuId, releaseCpuId, allocateCpuIdValue, releaseCpuIdValue, reclaimDedicatedLane }, /* PLAN-THREADS §4 step 6: the machine-wide kernel-lane mutex SAB, * threaded into the spawn helpers like the cpu_id allocator. */ __kernelLaneLocks: kernelLaneLocks, __fileMapGen: fileMapGen, __pool: poolEnabled ? { getPoolWorker, poolHandlers, syscallSyncDoors, registerSyncDoors, execInstallSyncDoors, releaseThreadImages, threadImages, allocRouteKey: () => nextRouteKey++, liveWorkerCount: () => poolWorkers.length, noteResidentDelta, markLaneSuspect, markLaneLive, laneInboxPost, /* Lane ownership (see the ledger above): the spawn helpers record * WHOSE task each lane carries as they place and reap it, and both * placement paths read it back to PREFER a lane no other thread * group carries (getPoolWorker's `foreignCpuIds` — a ranking, never * a ban: nothing here may mint a Worker). */ newLaneOwner, laneOccupy, laneRelease, lanesOwnedByOthers, lanesOwnedByGroup, lanesCarryingAnyOwner, laneIsBusy, laneOwnerText, liveCpuIds: () => poolWorkers.map((p) => p.cpuId), /* The pool's TOP cpu id (POOL_SIZE === maxCpuId). Threaded through * so spawnThreadWorker can range-check a HWJS_THREAD_PLACEMENT_PIN * against the machine's real ceiling — `liveWorkerCount()` is the * wrong number for that (a lane whose Worker failed to spawn is * still a legal id, and a pin naming it must fail as "no live * Worker", not as "out of range"). */ maxCpuId } : void 0, __taskWakeAddrByPid: taskWakeAddrByPid, /* Spike S4-exec-staging arm C: the machine-wide shared-lib map, threaded into the * spawn helpers the same way as the cpu_id allocator. */ __sharedLibs: { list: sharedLibsForInit, deliver: deliverSharedLib, deliveryPending: sharedLibDeliveryPending }, /* The machine-wide compile-once user-image registry, threaded into the * spawn helpers the same way. They are the only code that holds an * image's bytes at placement time. */ __userImageModule: userImageModule, __noteWorkerCompiledUserImage: noteWorkerCompiledUserImage, __noteWorkerLinkFacts: noteWorkerLinkFacts, /* hardwarejs#7: the per-process handler answers 'usermem-reclaim' * SAB-RPCs (a Worker whose exec grow-to-fit failed) with this sweep. */ __reclaimUserMemory: reclaimUserMemory, /* hardwarejs#7 (reopen): exit teardown pings this so zombie SABs are * swept PROACTIVELY (debounced + threshold-gated) — decommit gets wall * time long before the next large exec needs the headroom. */ __noteProcessExitForReclaim: noteProcessExitForReclaim, /* The per-task record. Threaded into the spawn helpers exactly like the * cpu_id allocator: they are the only code that ever knows a placement, * a kernel-pid handshake, an in-place exec or a teardown. */ __taskLedger: taskLedger, /* A DEDICATED Worker has one message callback — its task's own handler — * so the probe reply arrives there and is forwarded back here. */ __taskProbeReply: deliverTaskProbeReply, /* HWJS lifecycle (#2): legacy (non-pool) spawn helpers register the * Workers they create here so dispose() can terminate them too. */ __trackWorker: (w) => { if (!disposed) legacyWorkers.add(w); }, __preemptRealmInit: () => { const slot = preemptNextSlot; preemptNextSlot = preemptNextSlot + 1 >= PT_SLOTS ? POOL_SIZE + 1 : preemptNextSlot + 1; return preemptRealmInit(slot); }, __untrackWorker: (w) => { legacyWorkers.delete(w); } }); for (const e of opts.sharedLibs ?? []) { void deliverSharedLib(e.digest, e.bytes, "preload"); } optsWithCpuHooks.__poolStats = () => ({ workers: poolWorkers.length, residents: poolWorkers.map((p) => ({ cpuId: p.cpuId, residentCount: p.residentCount })) }); const takeLibraryHandoff = async (req, liveKernelMemory, from) => { const libcOff = (req.libcImageOffset ?? 0) >>> 0; const libcSize = (req.libcImageSize ?? 0) >>> 0; const libcDigOff = (req.libcDigestOffset ?? 0) >>> 0; if (libcSize === 0 || libcOff === 0) return 0; const km = new Uint8Array(liveKernelMemory); if (libcDigOff === 0 || libcDigOff + 64 > liveKernelMemory.byteLength) { opts.onUserError?.( req.tid, `hwjs-scatter: libc.so digest string at 0x${libcDigOff.toString(16)} (+64B) is outside kernel memory (${liveKernelMemory.byteLength}B) \u2014 REFUSED (never-silent)` ); return -22; } const digest = new TextDecoder().decode( km.slice(libcDigOff, libcDigOff + 64) ); let libcBytes; try { libcBytes = readScatterImage( liveKernelMemory, libcOff, req.libcImageNsegs ?? 0, libcSize, `library ${digest.slice(0, 16)}\u2026 hand-off for tid=${req.tid}` ); } catch (e) { opts.onUserError?.(req.tid, e instanceof Error ? e.message : String(e)); return -22; } const ok = await deliverSharedLib(digest, libcBytes, from); return ok ? 0 : -8; }; const handler = (async (req) => { if (req.mode === WASM_SPAWN_THREAD) { return spawnThreadWorker(req, parents, cloneCleartidMap, optsWithCpuHooks); } if (req.mode === WASM_SPAWN_NEEDED_LIB) { if ((req.flags & WASM_SPAWN_FLAG_SCATTER_IMAGE) === 0 || (req.libcImageSize ?? 0) === 0 || req.execImageSize !== 0) { opts.onUserError?.( req.tid, `hwjs-libc: NEEDED_LIB request tid=${req.tid} is malformed (flags=0x${(req.flags >>> 0).toString(16)}, library ${req.libcImageSize ?? 0}B, exec image ${req.execImageSize}B) \u2014 REFUSED -EINVAL (never-silent)` ); return -22; } return takeLibraryHandoff( req, opts.kernelMemoryWasm?.buffer ?? opts.kernelMemory, "spawn-ring needed" ); } if (req.mode !== WASM_SPAWN_FORK) { return -22; } if (req.execImageSize === 0) { return -22; } if ((req.flags & WASM_SPAWN_FLAG_SCATTER_IMAGE) === 0) { opts.onUserError?.( req.tid, `hwjs-scatter: FORK spawn request tid=${req.tid} carries a ${req.execImageSize}-byte exec image but NOT WASM_SPAWN_FLAG_SCATTER_IMAGE (flags=0x${(req.flags >>> 0).toString(16)}). This host only speaks the segment-list ABI; reading exec_image_offset as a byte offset would compile the segment list. REFUSED -EINVAL (never-silent) \u2014 the kernel and host are out of step and must be rebuilt together.` ); return -22; } const liveKernelMemory = opts.kernelMemoryWasm?.buffer ?? opts.kernelMemory; let wasmBytes; try { wasmBytes = readScatterImage( liveKernelMemory, req.execImageOffset, req.execImageNsegs ?? 0, req.execImageSize, `exec image for tid=${req.tid}` ); } catch (e) { opts.onUserError?.(req.tid, e instanceof Error ? e.message : String(e)); return -22; } userImageKeys.noteStaged(wasmBytes); { const lrc = await takeLibraryHandoff(req, liveKernelMemory, "spawn-ring"); if (lrc < 0) return lrc; } const rc = await spawnForkWorker( wasmBytes, req.tid, 0, parents, cloneCleartidMap, optsWithCpuHooks ); return rc < 0 ? rc : 0; }); handler.registerParent = (tid, record) => { parents.set(tid, record); }; handler.hasParent = (tid) => parents.has(tid); handler.parentCount = () => parents.size; handler.partitionReport = () => partitionReports.slice(); handler.carriesHwjsRt = opts.hwjsRtModule !== void 0; handler.__setLaneCeiling = setLaneCeiling; handler.__setHostSyncCall = setHostSyncCall; handler.poolStats = () => ({ enabled: poolEnabled, poolSize: POOL_SIZE, laneCeiling, workers: poolWorkers.length, liveResidents, peakResidents, residents: poolWorkers.map((p) => ({ cpuId: p.cpuId, residentCount: p.residentCount })) }); handler.taskCensus = () => ({ tasks: taskLedger.tasks(), reapedBeyondRing: taskLedger.reapedBeyondRing() }); handler.laneCensus = () => { const locks = new Int32Array(kernelLaneLocks); const now = Date.now(); const out = []; for (let c = 1; c <= laneCeiling; c++) { const pw = poolWorkers.find((p) => p.cpuId === c); const owners = laneOwners.get(c); const suspectUntil = laneSuspectUntil.get(c); out.push({ cpuId: c, band: c <= maxCpuId ? "pool" : "dedicated", poolWorkerLive: pw !== void 0, residentCount: pw ? pw.residentCount : 0, /* The thread groups this lane carries. A NEGATIVE id is a task placed * but not yet through its vmlinux-ready handshake — it has no kernel * pid to name, and the ledger deliberately treats it as foreign. */ ownerGroups: owners ? [...owners].map((o) => o.group).sort((a, b) => a - b) : [], /* A dedicated Worker holds this id exclusively. Pool ids are never in * this set: pool residents SHARE their Worker's id. */ heldByDedicatedWorker: inUseCpuIds.has(c), /* The cross-Worker lane mutex word, read now. Non-zero means some * Worker is inside a bracket/dispatch drive on this lane at this * instant — which is exactly what a starvation report needs, and the * one number that was previously only visible from inside a Worker. */ mutexHeld: c < locks.length ? Atomics.load(locks, c) !== 0 : false, suspectForMs: suspectUntil !== void 0 && suspectUntil > now ? suspectUntil - now : 0 }); } return out; }; handler.probeWorkers = async (timeoutMs = 250) => { const targets = [ ...poolWorkers.map((p) => ({ realm: "pool", cpuId: p.cpuId, worker: p.worker })), ...[...legacyWorkers].map((w) => ({ realm: "dedicated", cpuId: null, worker: w })) ]; const t0 = Date.now(); return Promise.all(targets.map((t) => new Promise((resolve) => { const seq = taskProbeSeq++; let settled = false; const finish = (r) => { if (settled) return; settled = true; taskProbePending.delete(seq); resolve(r); }; const timer = setTimeout(() => finish({ realm: t.realm, cpuId: t.cpuId, answered: false, waitedMs: Date.now() - t0, residents: null, schedStats: null, isolateModuleCaches: null, tasks: [] }), timeoutMs); taskProbePending.set(seq, (m) => { clearTimeout(timer); finish({ realm: t.realm, cpuId: typeof m.cpuId === "number" ? m.cpuId : t.cpuId, answered: true, waitedMs: Date.now() - t0, residents: Array.isArray(m.residents) ? m.residents : null, schedStats: m.schedStats ?? null, isolateModuleCaches: m.isolateModuleCaches ?? null, tasks: Array.isArray(m.tasks) ? m.tasks : [] }); }); try { postToWorker(t.worker, { kind: "task-probe", seq }); } catch (e) { clearTimeout(timer); finish({ realm: t.realm, cpuId: t.cpuId, answered: false, waitedMs: Date.now() - t0, postError: e instanceof Error ? e.message : String(e), residents: null, schedStats: null, isolateModuleCaches: null, tasks: [] }); } }))); }; handler.deliverSharedLib = deliverSharedLib; handler.sharedLibCensus = () => [...sharedLibs].map(([digest, e]) => ({ digest, byteLength: e.bytes.length, wireByteLength: retainedLibraryInfo(e.bytes)?.wireLength ?? e.bytes.length, compiled: e.module !== void 0, deliveryInFlight: e.pending !== void 0, ...e.path ? { path: e.path } : {} })); handler.__placementProbe = async (probe = {}) => { const pin = resolveThreadPlacementPin(probe.thread ?? 0, maxCpuId); const excl = new Set(probe.excludeCpuIds ?? []); const natural = await getPoolWorker(probe.avoidCpuId, excl); const chosen = pin.kind === "pin" ? await getPoolWorker(probe.avoidCpuId, excl, pin.cpuId) : natural; return { pin, maxCpuId, naturalCpuId: natural.cpuId, chosenCpuId: chosen.cpuId }; }; handler.wakeTaskByPid = wakeTaskByPid; handler.reclaimUserMemory = reclaimUserMemory; handler.userMemoryStats = () => opts.ram.userMemoryStats?.(); handler.dispose = dispose; return handler; } function makeUserMemPoolGate(dedicatedWorker, offer) { let own = false, reclaimed = false, gone = !dedicatedWorker, done = false; let inFlight = 0; const tryOffer = () => { if (done || !own || !reclaimed || inFlight > 0 || !gone) return; done = true; offer(); }; return { ownExit() { own = true; tryOffer(); }, reclaimed() { reclaimed = true; tryOffer(); }, workerGone() { gone = true; tryOffer(); }, syscallBegin() { inFlight++; }, syscallEnd() { inFlight--; tryOffer(); } }; } async function spawnForkWorker(initialWasmBytes, tid, ppid, parents, cloneCleartidMap, opts, inheritSpec, forkResume, execFrom) { let wasmBytes = initialWasmBytes; let userMem; if (forkResume) { userMem = forkResume.userMem; if (userMemoryBumpPointers.get(userMem) === void 0) { initUserMemoryPartition(userMem, wasmBytes, { ram: opts.ram, pid: -1 }); markUserMemoryDirty(userMem); } } else { const heapWhy = opts.__heapBudget?.refusal("process spawn") ?? ""; if (heapWhy) { opts.onUserError?.(-1, `spawn REFUSED: ${heapWhy}. The guest sees ENOMEM from fork/exec.`); return ENOMEM2; } try { userMem = opts.ram.allocUserMemory(); } catch (e) { const st = opts.ram.userMemoryStats(); opts.onUserError?.( -1, `spawn REFUSED: could not allocate a per-process user_memory (initial ${opts.ram.opts.userInitBytes} B, maximum ${opts.ram.opts.userMaxBytes} B): ${e instanceof Error ? e.message : String(e)}. This is the HOST declining a new WebAssembly.Memory, not the guest machine running out of its declared RAM. Live user SABs: ${st.liveCount} (${st.livePages} pages in size); exited-but-uncollected: ${st.exitedUncollectedCount} (${st.exitedUncollectedPages} pages in size). The guest sees ENOMEM from fork/exec.` ); return ENOMEM2; } initUserMemoryPartition(userMem, wasmBytes, { ram: opts.ram, pid: -1 }); } let signalPendingOffset; if (forkResume) { signalPendingOffset = forkResume.signalPendingOffset; } else if (opts.signalRegistry) { const off = allocSignalPendingRegion(userMem); if (off < 0) { opts.onUserError?.( -1, userMemoryGrowRefusal( opts.ram, userMem, -1, "signal-pending page at process spawn", userMem.buffer.byteLength + WASM_PAGE_SIZE ) + ` The process cannot be started; the guest sees ENOMEM from fork/exec.` ); return ENOMEM2; } signalPendingOffset = off; } const cpuIdHooks = opts.__cpuIdHooks; const pool = opts.__pool; { const shl = opts.__sharedLibs; if (shl?.deliveryPending) { let neededDigest2 = null; try { neededDigest2 = imageNeededLibcDigest(wasmBytes); } catch { } if (neededDigest2 !== null) { const w = shl.deliveryPending(neededDigest2); if (w) await w; } } } { const uim = opts.__userImageModule; if (uim) { try { await uim(wasmBytes); } catch { } } } let poolWorkerRec = null; let routeKey = 0; let cpuId; const laneOwner = pool ? pool.newLaneOwner() : null; const parentCpuId = forkResume && typeof forkResume.parentCpuId === "number" ? forkResume.parentCpuId : void 0; const forkPlacement = () => forkPlacementView(pool.lanesOwnedByOthers(ppid), parentCpuId); if (pool) { const fp = forkPlacement(); if (execFrom?.cpuId !== void 0) { try { poolWorkerRec = await pool.getPoolWorker(void 0, void 0, execFrom.cpuId); } catch { poolWorkerRec = null; } } poolWorkerRec ??= await pool.getPoolWorker(fp.avoid, void 0, void 0, fp.foreign); cpuId = poolWorkerRec.cpuId; routeKey = pool.allocRouteKey(); poolWorkerRec.residentCount++; pool.laneOccupy(cpuId, laneOwner); pool.noteResidentDelta(1); if (globalThis.process?.env?.A4C_DBG) globalThis.process.stderr.write(`[a4c] place tid=${tid} ppid=${ppid} -> pool cpu=${cpuId} routeKey=${routeKey} residents=${poolWorkerRec.residentCount} parentCpu=${parentCpuId} parentBusy=${parentCpuId !== void 0 && pool.laneIsBusy(parentCpuId)} forkResume=${!!forkResume} `); } else { cpuId = cpuIdHooks ? cpuIdHooks.allocateCpuIdValue() : 1; if (cpuId === 0) { return EAGAIN; } } const ledgerTask = opts.__taskLedger?.open({ kind: "process", spawnTid: tid, parentPid: ppid, tgid: null, cpuId, residency: pool ? "pool-resident" : "dedicated-worker", routeKey: pool ? routeKey : null, image: imageFactsOf(wasmBytes, null), userMemory: userMem, sabSharedWithGroup: false }) ?? null; ledgerTask?.noteSignalPendingOffset(signalPendingOffset); const ctrlSab = new SharedArrayBuffer( 64 /* 16 * i32 */ ); const ctrl = new Int32Array(ctrlSab); let routePid = tid; let mapsRegistered = false; const preRegHeldSyscalls = []; let spawnDegraded = false; const threadPlacementPending = /* @__PURE__ */ new Map(); let threadPlacementSeq = 0; let threadPlacementUnsolicited = null; const threadPlacementWaiters = []; const peekThreadPlacement = () => { if (!threadPlacementUnsolicited) return null; const env = threadPlacementUnsolicited.envelope; threadPlacementUnsolicited = null; return env; }; const requestThreadPlacement = (timeoutMs = 5e3) => { const peeked = peekThreadPlacement(); if (peeked) return Promise.resolve(peeked); return new Promise((resolve, reject) => { const seq = ++threadPlacementSeq; let settled = false; const unwait = (fn2) => { const i = threadPlacementWaiters.indexOf(fn2); if (i >= 0) threadPlacementWaiters.splice(i, 1); }; const settle = (v) => { if (settled) return; settled = true; clearTimeout(timer); threadPlacementPending.delete(seq); unwait(settle); resolve(v); }; const fail = (e) => { if (settled) return; settled = true; clearTimeout(timer); threadPlacementPending.delete(seq); unwait(settle); reject(e); }; const timer = setTimeout(() => { fail(new Error( `hwjs-libc: thread-placement fetch pid=${routePid} seq=${seq} timed out after ${timeoutMs}ms \u2014 no clone-time pre-push arrived and the parent Worker's event loop did not serve the request (starved lane / torn Worker / pre-push-less worker build); the thread spawn must be refused (never-silent)` )); }, timeoutMs); threadPlacementWaiters.push(settle); threadPlacementPending.set(seq, { resolve: settle, reject: fail }); try { if (pool) pool.laneInboxPost?.(worker); postReply({ kind: "thread-placement-request", seq, pid: routePid }); } catch (e) { fail(e instanceof Error ? e : new Error(String(e))); } }); }; const registerProcessMaps = (p) => { if (mapsRegistered) return; mapsRegistered = true; routePid = p; if (laneOwner) laneOwner.group = p; ledgerTask?.notePid(p, p); if (opts.signalRegistry && signalPendingOffset !== void 0) { opts.signalRegistry.register(p, { userMemory: userMem, signalPendingOffset }); } parents.set(p, { wasmBytes, userMemory: userMem, requestThreadPlacement, peekThreadPlacement, getCpuId: () => cpuId, /* A process record IS its own thread-group leader. */ leaderPid: p }); opts.ram.noteUserMemoryOwner?.(userMem, p); }; let recycleDirtyBytes; const poolGate = makeUserMemPoolGate(!pool, () => { opts.ram.recycleUserMemory?.(userMem, recycleDirtyBytes); }); const trackSyscall = (p) => { poolGate.syscallBegin(); return p.finally(() => poolGate.syscallEnd()); }; const cleanupProcessWorker = (kernelVerdict) => { opts.ram.noteUserMemoryExited?.(userMem); if (mapsRegistered) { const contain = opts.__threadContain; if (contain && kernelVerdict) { if ((kernelVerdict.zapped | 0) > 0) { const w = kernelVerdict.wstatus | 0; contain.killGroup( routePid, routePid, 9, `process leader terminus: the kernel condemned ${kernelVerdict.zapped} other thread(s) of this process and set the group's exit code to 0x${w.toString(16)} (` + (w & 127 ? `WIFSIGNALED WTERMSIG=${w & 127}` : `WIFEXITED WEXITSTATUS=${w >> 8 & 255}`) + `) \u2014 unwinding their Workers` ); } else if (contain.liveThreads(routePid) > 0) { opts.onDmesg?.( 4, `hwjs group-death: process leader pid=${routePid} reached a terminus and the kernel condemned NO other thread, while ${contain.liveThreads(routePid)} sibling Worker(s) are still up. The host unwinds none of them \u2014 the kernel owns which tasks die `, routePid ); } } else if (contain && contain.liveThreads(routePid) > 0) { contain.killGroup( routePid, routePid, 9, "process leader terminus the kernel never saw (trap / spawn failure) with live sibling threads \u2014 host containment belt, so a sibling parked on the dead leader's lock cannot leak a cpu lane" ); } performCleartid(cloneCleartidMap, routePid); opts.__threadOrdinals?.dropParent(routePid); opts.signalRegistry?.unregister(routePid); opts.stdinChannel?.dropTid(routePid); opts.__taskWakeAddrByPid?.delete(routePid >>> 0); if (!HWJS_NO_SAB_RECLAIM()) { const reusable = contain?.consumeEverThreaded !== void 0 && !contain.consumeEverThreaded(routePid); const reclaim = () => { recycleDirtyBytes = userMemoryDirtyBytes(userMem); parents.delete(routePid); userMemoryBumpPointers.delete(userMem); userMemoryDirtyCells.delete(userMem); dlPlacementJournalDrop(userMemoryId(userMem)); if (!reusable) pool?.releaseThreadImages?.(userMemoryId(userMem)); const cell = userPlacementCells.get(userMem); if (cell) Atomics.store(new Int32Array(cell), DL_PLACEMENT_IMAGE, -1); userPlacementCells.delete(userMem); userMemoryPartitions.delete(userMem); userMemoryMmapFreeLists.delete(userMem); userMemorySignalPageFreeLists.delete(userMem); if (reusable) poolGate.reclaimed(); }; if (contain?.whenGroupEmpty) contain.whenGroupEmpty(routePid, reclaim); else reclaim(); } } if (pool) { pool.poolHandlers.delete(routeKey); pool.syscallSyncDoors.delete(routeKey); pool.registerSyncDoors.delete(routeKey); pool.execInstallSyncDoors.delete(routeKey); if (poolWorkerRec) { poolWorkerRec.residentCount = Math.max(0, poolWorkerRec.residentCount - 1); if (laneOwner) pool.laneRelease(poolWorkerRec.cpuId, laneOwner); } pool.noteResidentDelta(-1); } else if (cpuIdHooks) { cpuIdHooks.releaseCpuIdValue(cpuId); } opts.__noteProcessExitForReclaim?.(); }; const platform = opts.platform ?? detectPlatform(); let worker = pool ? poolWorkerRec.worker : await createWorker(opts.workerEntry, platform, "fork-dedicated", `process (pid ${tid})`); if (!pool) opts.__trackWorker?.(worker); const postReply = (m) => postToWorker(worker, pool ? { ...m, routeKey } : m); let exitFired = false; const threadCtx = { parents, spawnThread: (r) => spawnThreadWorker(r, parents, cloneCleartidMap, opts), cloneCleartidMap }; let resolveVmlinuxAllocated = () => { }; const vmlinuxAllocated = opts.vmlinuxModule !== void 0 ? new Promise((r) => { resolveVmlinuxAllocated = r; }) : Promise.resolve(tid); let execPartitionsBySyncDoor = 0; const rederiveExecPartition = (img) => { const oldBump = userMemoryBumpPointers.get(userMem); initUserMemoryPartition(userMem, img, { ram: opts.ram, pid: routePid }); const newFloor = userMemoryBumpPointers.get(userMem); if (oldBump !== void 0 && newFloor !== void 0 && oldBump > newFloor) { setUserBump(userMem, oldBump); } }; const exited = new Promise((resolve) => { const handleMsg = async (msg) => { if (dlPlacementMessage(msg, postReply, pool?.releaseThreadImages)) return; if (msg?.kind === "user-image-compiled") { opts.__noteWorkerCompiledUserImage?.(msg, worker); return; } if (msg?.kind === "link-facts") { opts.__noteWorkerLinkFacts?.(msg, worker); return; } if (msg?.kind === "syscall") { if (opts.vmlinuxModule !== void 0 && !mapsRegistered) { if (spawnDegraded) { opts.onUserError?.( tid, "hwjs#65: syscall from a DEGRADED spawn (vmlinux-error, no kernel pid) answered -EAGAIN \u2014 the task should not be running user code at all (worker-side refusal bypassed?)" ); Atomics.store(ctrl, C2.RET_LO, EAGAIN | 0); Atomics.store(ctrl, C2.RET_HI, -1); Atomics.store(ctrl, C2.STATE, RESPONSE2); Atomics.notify(ctrl, C2.STATE); return; } opts.onDmesg?.( 4, `hwjs#65: R-K11.6-W1 early-signal HOLD \u2014 syscall from tid=${tid} (routeKey=${routeKey}) arrived before the vmlinux-ready handshake registered its kernel pid; deferring dispatch until registration (held=${preRegHeldSyscalls.length + 1}) `, tid ); preRegHeldSyscalls.push(msg); return; } await trackSyscall(dispatchSyscall(ctrl, userMem, routePid, opts, threadCtx)); return; } if (msg?.kind === "libc-so-staged") { const shl = opts.__sharedLibs; if (shl) { void shl.deliver( String(msg.digest ?? ""), msg.bytes instanceof Uint8Array ? msg.bytes : new Uint8Array(msg.bytes ?? []), `worker tid=${tid}`, msg.module instanceof WebAssembly.Module ? msg.module : void 0, typeof msg.path === "string" ? msg.path : void 0 ); } else { opts.onUserError?.( tid, "hwjs-libc: 'libc-so-staged' arrived but this spawn handler has no shared-lib hooks (harness without makeKernelSpawnHandler?) \u2014 machine-wide retention SKIPPED (never-silent)" ); } return; } if (msg?.kind === "thread-placement") { if (msg.unsolicited) { const envelope = { dlopenFork: msg.dlopenFork && typeof msg.dlopenFork === "object" ? msg.dlopenFork : null, ...msg.clone && typeof msg.clone === "object" ? { clone: { flags: (msg.clone.flags ?? 0) >>> 0, ptid: (msg.clone.ptid ?? 0) >>> 0, ctid: (msg.clone.ctid ?? 0) >>> 0 } } : {}, ...Array.isArray(msg.lowFdRoutes) ? { lowFdRoutes: msg.lowFdRoutes.map((n) => n | 0) } : {}, /* STRICT === true: absent (an older worker bundle) and any * non-boolean read as UNKNOWN, and unknown keeps the caller-lane * exclusion. A truthy coercion here would turn a missing field * into a placement that deadlocks. */ callerYieldsDuringClone: msg.callerYieldsDuringClone === true }; const w = threadPlacementWaiters.shift(); if (w) w(envelope); else threadPlacementUnsolicited = { envelope }; return; } const p = threadPlacementPending.get(msg.seq | 0); if (p) { threadPlacementPending.delete(msg.seq | 0); if (msg.error) p.reject(new Error(String(msg.error))); else p.resolve({ dlopenFork: msg.dlopenFork && typeof msg.dlopenFork === "object" ? msg.dlopenFork : null }); } return; } if (msg?.kind === "vfork") { await serveVforkRequest(msg, ctrl, routePid, parents, cloneCleartidMap, opts); return; } if (msg?.kind === "fork") { const st = Atomics.load(ctrl, C2.STATE); if (st !== REQUEST2) { throw new Error( "D1-FORK: 'fork' message arrived with ctrl STATE=" + st + " (expected REQUEST=" + REQUEST2 + "); refusing to snapshot a non-quiesced parent address space." ); } const copyBytes = userMemoryDirtyBytes(userMem); let childMem; const parentBytes = userMem.buffer.byteLength; try { const heapWhy = opts.__heapBudget?.refusal("fork") ?? ""; if (heapWhy) throw new Error(heapWhy); childMem = opts.ram.allocForkUserMemory(userMem, copyBytes); const deficitPages = Math.ceil((parentBytes - childMem.buffer.byteLength) / 65536); if (deficitPages > 0) childMem.grow(deficitPages); } catch { Atomics.store(ctrl, C2.RET_LO, ENOMEM2 | 0); Atomics.store(ctrl, C2.RET_HI, -1); Atomics.store(ctrl, C2.STATE, RESPONSE2); Atomics.notify(ctrl, C2.STATE); return; } new Uint8Array(childMem.buffer).set( new Uint8Array(userMem.buffer, 0, copyBytes) ); traceForkCopy(routePid, copyBytes, parentBytes); const parentBump = userMemoryBumpPointers.get(userMem); const parentPart = userMemoryPartitions.get(userMem); if (parentBump !== void 0 && parentPart) { setUserBump(childMem, parentBump); if (copyBytes > parentBump) markUserMemoryDirty(childMem); userMemoryPartitions.set(childMem, { ...parentPart }); userMemoryMmapFreeLists.set( childMem, getMmapFreeList(userMem).map((r) => ({ ...r })) ); } else { initUserMemoryPartition(childMem, wasmBytes, { ram: opts.ram, pid: -1 }); markUserMemoryDirty(childMem); } if (signalPendingOffset !== void 0) { new Int32Array(childMem.buffer, signalPendingOffset >>> 0, 3).fill(0); } const childPid = await spawnForkWorker( wasmBytes, /* tid sentinel: 0 = natural alloc_pid (shape-ii, same as * wasm_spawn_image children). */ 0, routePid, parents, cloneCleartidMap, opts, void 0, { userMem: childMem, signalPendingOffset, /* HWJS-A-4.c: place the child off the parent's pool Worker. */ ...pool ? { parentCpuId: cpuId } : {}, ...typeof msg.tlsBase === "number" ? { tlsBase: msg.tlsBase >>> 0 } : {}, /* HWJS-3 coro riders (worker.mjs requestForkChild, coro arm). */ ...typeof msg.forkHandle === "number" ? { forkHandle: msg.forkHandle >>> 0 } : {}, ...typeof msg.forkOwner === "number" ? { forkOwner: msg.forkOwner >>> 0 } : {}, /* Step 7 (fork under threads): the child keeps the CALLER's * runtime block and main-image TLS (plan §3 I1 keep-caller). */ ...typeof msg.tcb === "number" && msg.tcb >>> 0 !== 0 ? { forkTcb: msg.tcb >>> 0 } : {}, ...typeof msg.mainTlsBase === "number" && msg.mainTlsBase >>> 0 !== 0 ? { mainTlsBase: msg.mainTlsBase >>> 0 } : {}, ...typeof msg.parentSp === "number" ? { parentSp: msg.parentSp >>> 0 } : {}, /* HWJS-5 fork×dlopen (issue #43): the parent's dlopen LAYOUT to * reconstruct in the child's fresh per-Worker table (the table * can't cross Workers; the .so data is already in the * delta=0-copied memory). */ ...typeof msg.dlopenFork === "object" && msg.dlopenFork !== null ? { dlopenFork: msg.dlopenFork } : {}, /* D1-FORK fd routing: carry the parent's low-fd routing cache so * the child's inherited fds (e.g. fd1=pts) route KERNEL-side. */ ...Array.isArray(msg.lowFdRoutes) ? { lowFdRoutes: msg.lowFdRoutes } : {}, /* The parent's writable shared file mappings, shadows included. */ ...typeof msg.sharedFileMaps === "object" && msg.sharedFileMaps !== null ? { sharedFileMaps: msg.sharedFileMaps } : {}, /* SYS_wasm_jit's fork floor (worker.mjs forkFloor). */ ...Number.isInteger(msg.wasmJitFloor) && msg.wasmJitFloor > 0 ? { wasmJitFloor: msg.wasmJitFloor } : {} } ); Atomics.store(ctrl, C2.RET_LO, childPid | 0); Atomics.store(ctrl, C2.RET_HI, childPid < 0 ? -1 : 0); Atomics.store(ctrl, C2.STATE, RESPONSE2); Atomics.notify(ctrl, C2.STATE); return; } if (msg?.kind === "migrate") { const mig = msg.mig; if (!(mig instanceof SharedArrayBuffer) || mig.byteLength < 16) { opts.onDmesg?.( 3, `hwjs-migrate pid=${routePid}: 'migrate' message without a valid protocol word \u2014 ignoring (the source's own deadline releases it) `, routePid ); return; } const migW = new Int32Array(mig); const destCpu = msg.destCpu | 0; const srcCpu = msg.srcCpu | 0; const abortMig = (code2) => { for (; ; ) { const s = Atomics.load(migW, 0) | 0; if (s === 2 || s === 3) return false; if (Atomics.compareExchange(migW, 0, s, 3) === s) { Atomics.store(migW, 2, code2 | 0); Atomics.notify(migW, 0); return true; } } }; if (!pool) { abortMig( 4 /* HOST */ ); opts.onDmesg?.( 3, `hwjs-migrate pid=${routePid}: migration requires the CPU-Worker pool (this task runs on a dedicated Worker, whose cpu id is not a pool lane) \u2014 REFUSED `, routePid ); return; } let destRec; try { destRec = await pool.getPoolWorker(void 0, void 0, destCpu); } catch (e) { abortMig( 2 /* NO_LANE */ ); opts.onDmesg?.( 3, `hwjs-migrate pid=${routePid}: cpu=${destCpu} has no live pool Worker (${e instanceof Error ? e.message : String(e)}) \u2014 REFUSED; the task keeps running on cpu=${srcCpu} `, routePid ); return; } const prevWorker = worker; const prevCpu = cpuId; const prevRec = poolWorkerRec; worker = destRec.worker; cpuId = destRec.cpuId; poolWorkerRec = destRec; destRec.residentCount++; if (laneOwner) pool.laneOccupy(destRec.cpuId, laneOwner); pool.laneInboxPost?.(destRec.worker); postToWorker(destRec.worker, { kind: "add-task", routeKey, spec: { routeKey, mode: "migrate-resume", mig, /* Identity of the task being moved. */ pid: routePid, tid, ppid, migratePid: msg.pid | 0, migrateTaskAddr: msg.taskAddr | 0, /* The lane the task's kernel arena chunks carry now; the * destination retags them before its first drive. */ migrateSrcCpu: srcCpu, /* THE SAME objects, not copies. This is the whole mechanism: * hand over identity, not content. */ memory: userMem, ctrl: ctrlSab, leaderHold: 1, ...userDirtyCellInit(userMem), ...placementCellInit(userMem, false), wasmBytes, ...placementImageKey(wasmBytes), ...signalPendingOffset !== void 0 ? { signalPendingOffset } : {}, /* The two per-Instance globals, and the runtime block (and * main-image TLS block) the task keeps. */ tlsBase: msg.tlsBase | 0, sp: msg.sp | 0, ...typeof msg.sideSpTop === "number" ? { sideSp: msg.sideSp >>> 0, sideSpTop: msg.sideSpTop >>> 0 } : {}, tcb: msg.tcb >>> 0, ...typeof msg.mainTlsBase === "number" ? { mainTlsBase: msg.mainTlsBase >>> 0 } : {}, /* Rides the same paths the fork child's do. */ ...Array.isArray(msg.lowFdRoutes) ? { lowFdRoutes: msg.lowFdRoutes } : {}, ...typeof msg.sharedFileMaps === "object" && msg.sharedFileMaps !== null ? { sharedFileMaps: msg.sharedFileMaps } : {}, ...typeof msg.dlopenFork === "object" && msg.dlopenFork !== null ? { dlopenFork: msg.dlopenFork } : {}, /* SYS_wasm_jit's record (worker.mjs requestMigrate -> * wasmJit.mjs migrateOut): compiled Modules and the slot indices * the emulator holds, re-placed by the destination before it * commits. Passed through untouched. */ ...typeof msg.wasmJit === "object" && msg.wasmJit !== null ? { wasmJit: msg.wasmJit } : {}, /* The rt / libc.so reserved windows, re-derived from this * process's live partition exactly as the fork path does. */ ...(() => { const part = userMemoryPartitions.get(userMem); return part ? { ...part.rtWindowSize > 0 ? { hwjsRtWindowBase: part.rtWindowBase, hwjsRtWindowSize: part.rtWindowSize } : {}, ...part.libcWindowSize > 0 ? { hwjsLibcWindowBase: part.libcWindowBase, hwjsLibcWindowSize: part.libcWindowSize } : {} } : {}; })() } }); const MIGRATE_ACK_MS = 4e3; const dl = Date.now() + MIGRATE_ACK_MS; while (Date.now() < dl) { const s = Atomics.load(migW, 0) | 0; if (s === 2 || s === 3) break; const w = Atomics.waitAsync(migW, 0, s, Math.max(1, dl - Date.now())); if (w.async) { try { await w.value; } catch { } } } const final = Atomics.load(migW, 0) | 0; if (final === 2) { pool.markLaneLive(destCpu); if (prevRec) { prevRec.residentCount = Math.max(0, prevRec.residentCount - 1); if (laneOwner) pool.laneRelease(prevRec.cpuId, laneOwner); } opts.onDmesg?.( 6, `hwjs-migrate pid=${routePid}: cpu=${srcCpu} -> cpu=${destCpu} COMMITTED (routeKey=${routeKey}; same user_memory, same ctrl, same task_struct) `, routePid ); return; } const claimed = Atomics.load(migW, 3) | 0; abortMig( claimed ? 1 : 4 /* HOST */ ); worker = prevWorker; cpuId = prevCpu; poolWorkerRec = prevRec; destRec.residentCount = Math.max(0, destRec.residentCount - 1); if (laneOwner) pool.laneRelease(destRec.cpuId, laneOwner); if (!claimed) pool.markLaneSuspect(destCpu); opts.onDmesg?.( 3, `hwjs-migrate pid=${routePid}: cpu=${srcCpu} -> cpu=${destCpu} REFUSED after ${MIGRATE_ACK_MS} ms \u2014 ` + (claimed ? `the destination lane CLAIMED the task but never committed (it stalled or died between claiming and binding); this is the half-migrated case, and it is DETECTED here rather than lost: the source never released the task and resumes driving it` : `the destination lane never claimed the add-task (its event loop is starved by a resident that does not yield); lane marked suspect`) + `. Host bookkeeping rolled back to cpu=${srcCpu} `, routePid ); return; } if (msg?.kind === "vmlinux-rebound") { const wakeAddr = typeof msg.perProcessTaskWakeAddr === "number" ? msg.perProcessTaskWakeAddr >>> 0 : 0; const wakeMap = opts.__taskWakeAddrByPid; if (wakeAddr && wakeMap) wakeMap.set(routePid >>> 0, wakeAddr); opts.onDmesg?.( 6, `hwjs-migrate pid=${routePid}: bound on cpu=${msg.cpuId ?? cpuId} (task=0x${(msg.perProcessTaskAddr >>> 0).toString(16)}) `, routePid ); return; } if (msg?.kind === "execve") { const execPath = String(msg.path ?? ""); const ENOENT2 = -2; let reply; const execBytes = opts.childImageRegistry?.lookup(execPath); if (!opts.childImageRegistry) { reply = { kind: "exec-image", ok: false, errno: ENOSYS }; } else if (!execBytes) { reply = { kind: "exec-image", ok: false, errno: ENOENT2 }; } else { reply = { kind: "exec-image", ok: true, wasmBytes: execBytes }; } postReply(reply); return; } if (msg?.kind === "leader-hold") { const release = () => { Atomics.store(ctrl, C2.LEADER_HOLD, 1); Atomics.notify(ctrl, C2.LEADER_HOLD); }; const contain = opts.__threadContain; if (!contain || !mapsRegistered) { opts.onDmesg?.( 4, `hwjs-threads pid=${routePid}: main thread pthread_exit with no thread-group view on this host (${contain ? "pid not registered" : "no threadContain"}) \u2014 releasing the leader at once; any other thread is not awaited `, routePid ); release(); return; } const live2 = contain.liveThreads(routePid); if (live2 > 0) { opts.onDmesg?.( 6, `hwjs-threads pid=${routePid}: main thread pthread_exit with ${live2} other thread(s) live \u2014 the process stays until the last one ends or one calls exit_group (Linux's delay_group_leader) `, routePid ); } contain.whenGroupEmpty(routePid, release); return; } if (msg?.kind === "exit") { if (!exitFired) { exitFired = true; poolGate.ownExit(); const code2 = msg.code | 0; cleanupProcessWorker(msg.groupExit ?? null); if (msg.wasmSyscallStats && opts.onWasmSyscallStats) { opts.onWasmSyscallStats(routePid, msg.wasmSyscallStats); } ledgerTask?.noteExit(code2, "exit message from the Worker"); opts.onUserExit?.(routePid, code2, userExitInfo(msg)); if (!pool) { await terminateWorker(worker); poolGate.workerGone(); } resolve(code2); } return; } if (msg?.kind === "error") { if (!exitFired) { exitFired = true; cleanupProcessWorker(); ledgerTask?.noteExit(-1, `terminal error from the Worker: ${String(msg.message ?? "")}`); opts.onUserError?.(routePid, String(msg.message ?? "")); opts.onUserExit?.(routePid, -1); if (!pool) await terminateWorker(worker); resolve(-1); } return; } if (msg?.kind === "task-probe-reply") { opts.__taskProbeReply?.(msg); return; } if (msg?.kind === "machine-power") { opts.onMachinePower?.((msg.cmd | 0) >>> 0); return; } if (msg?.kind === "user-report") { opts.onUserError?.(routePid, String(msg.message ?? "")); return; } if (msg?.kind === "vmlinux-ready") { const kernelPid = typeof msg.pid === "number" && msg.pid > 0 ? msg.pid | 0 : tid; if (globalThis.process?.env?.A4C_DBG) globalThis.process.stderr.write(`[a4c] tid=${tid} routeKey=${routeKey} VMLINUX-READY kernelPid=${kernelPid} cpu=${cpuId} `); { const wakeAddr = typeof msg.perProcessTaskWakeAddr === "number" ? msg.perProcessTaskWakeAddr >>> 0 : 0; const wakeMap = opts.__taskWakeAddrByPid; if (wakeAddr && wakeMap) wakeMap.set(kernelPid >>> 0, wakeAddr); } registerProcessMaps(kernelPid); if (preRegHeldSyscalls.length > 0) { const held = preRegHeldSyscalls.splice(0, preRegHeldSyscalls.length); opts.onDmesg?.( 4, `hwjs#65: draining ${held.length} held pre-registration syscall(s) for kernel pid=${kernelPid} `, kernelPid ); for (const m of held) void handleMsg(m); } opts.onVmlinuxReady?.(routePid, { hasWasmSyscall: !!msg.hasWasmSyscall, cpuId, initTaskAddr: typeof msg.initTaskAddr === "number" ? msg.initTaskAddr : 0, perProcessTaskAddr: typeof msg.perProcessTaskAddr === "number" ? msg.perProcessTaskAddr : 0 }); resolveVmlinuxAllocated(routePid); return; } if (msg?.kind === "vmlinux-error") { spawnDegraded = true; opts.onUserError?.( tid, `vmlinux instantiation failed in Worker: ${String(msg.message ?? "")} \u2014 spawn refused with -EAGAIN (hwjs#65; the machine keeps running)` ); if (preRegHeldSyscalls.length > 0) { preRegHeldSyscalls.length = 0; Atomics.store(ctrl, C2.RET_LO, EAGAIN | 0); Atomics.store(ctrl, C2.RET_HI, -1); Atomics.store(ctrl, C2.STATE, RESPONSE2); Atomics.notify(ctrl, C2.STATE); } if (!exitFired) { exitFired = true; cleanupProcessWorker(); ledgerTask?.noteDegraded(String(msg.message ?? "")); ledgerTask?.noteExit(-1, "vmlinux-error: the spawn degraded and this task never ran user code"); opts.onUserExit?.(routePid, -1); if (!pool) await terminateWorker(worker); resolve(-1); } resolveVmlinuxAllocated(EAGAIN); return; } if (msg?.kind === "usermem-reclaim") { const sab = msg.sab; if (!(sab instanceof SharedArrayBuffer) || sab.byteLength < 32) { opts.onUserError?.( routePid, "hardwarejs#7: malformed 'usermem-reclaim' request (missing/short reply SAB) \u2014 the requesting Worker will time out its bounded wait" ); return; } const rec = new Int32Array(sab); const reclaim = opts.__reclaimUserMemory; void (async () => { let recycledWorkers = 0; try { if (reclaim) { recycledWorkers = (await reclaim( `execve grow-to-fit pid=${routePid} need=+${(msg.needPages ?? 0) | 0}p` )).recycledWorkers; } } catch (e) { opts.onUserError?.( routePid, `hardwarejs#7: reclaim sweep threw (${e instanceof Error ? e.message : String(e)}) \u2014 answering the Worker with the ledger stats anyway` ); } const st = opts.ram.userMemoryStats?.(); rec[1] = st ? st.liveCount : -1; rec[2] = st ? st.livePages : -1; rec[3] = st ? st.exitedUncollectedCount : -1; rec[4] = st ? st.exitedUncollectedPages : -1; rec[5] = recycledWorkers; rec[6] = st ? st.userMaxPages : -1; rec[7] = st ? st.kernelPages : -1; Atomics.store(rec, 0, 1); Atomics.notify(rec, 0); })(); return; } if (msg?.kind === "exec-image-installed") { const img = msg.wasmBytes; if (!(img instanceof Uint8Array) || img.length === 0) { throw new Error( `D1-FORK: 'exec-image-installed' without valid wasmBytes \u2014 refusing to track an empty/invalid post-exec image (pid=${routePid}).` ); } userImageKeys.noteStaged(img); wasmBytes = img; if (execPartitionsBySyncDoor > 0) execPartitionsBySyncDoor--; else rederiveExecPartition(img); if (mapsRegistered) { const rec = parents.get(routePid); if (rec) parents.set(routePid, { ...rec, wasmBytes: img }); } ledgerTask?.noteExec(imageFactsOf( img, typeof msg.path === "string" ? msg.path : null )); return; } if (msg?.kind === "dmesg") { opts.onDmesg?.((msg.level | 0) >>> 0, String(msg.text), routePid); return; } }; if (pool) { pool.poolHandlers.set(routeKey, (m) => { void handleMsg(m); }); pool.registerSyncDoors.set(routeKey, (pid) => { try { registerProcessMaps(pid | 0); } catch (e) { opts.onUserError?.( pid | 0, `hwjs-merged: the SYNCHRONOUS registration door threw for pid=${pid | 0} routeKey=${routeKey} \u2014 ${e instanceof Error ? e.message : String(e)}. Declining, so the vmlinux-ready MESSAGE registers this task instead and its first syscalls take the deferred route (the worker says so out loud).` ); return void 0; } return "registered"; }); pool.execInstallSyncDoors.set(routeKey, (img) => { try { rederiveExecPartition(img); } catch (e) { opts.onUserError?.( routePid, `hwjs-merged: the SYNCHRONOUS exec door threw for pid=${routePid} routeKey=${routeKey} \u2014 ${e instanceof Error ? e.message : String(e)}. Declining, so the exec-image-installed MESSAGE re-derives the partition instead.` ); return void 0; } execPartitionsBySyncDoor++; return "installed"; }); pool.syscallSyncDoors.set(routeKey, () => { if (opts.vmlinuxModule !== void 0 && !mapsRegistered) return void 0; let p; try { p = trackSyscall(dispatchSyscall(ctrl, userMem, routePid, opts, threadCtx)); } catch (e) { opts.onUserError?.( routePid, `hwjs-merged: the SYNCHRONOUS syscall door threw for nr=${ctrl[C2.NR] | 0} \u2014 ${e instanceof Error ? e.message : String(e)}. Declining: nothing was written, so the caller must take the message route and get whatever answer THAT produces, including its refusal.` ); return void 0; } p?.catch?.((e) => { opts.onUserError?.( routePid, `hwjs-merged: a syscall dispatched through the SYNCHRONOUS door rejected after awaiting (nr=${ctrl[C2.NR] | 0}) \u2014 ${e instanceof Error ? e.message : String(e)}` ); }); return Atomics.load(ctrl, C2.STATE) === RESPONSE2 ? "sync" : "async"; }); } else { onMessage(worker, handleMsg); onError(worker, async (err2) => { if (!exitFired) { exitFired = true; cleanupProcessWorker(); ledgerTask?.noteExit(-1, `Worker-level error event: ${err2 instanceof Error ? err2.message : String(err2)}`); opts.onUserError?.(routePid, err2 instanceof Error ? err2.message : String(err2)); opts.onUserExit?.(routePid, -1); await terminateWorker(worker); resolve(-1); } }); } }); void exited; const effInheritSpec = inheritSpec ?? (forkResume ? { inheritFiles: true, fdActions: [] } : void 0); const rtPart = userMemoryPartitions.get(userMem); const perTaskInit = { ...rtPart && rtPart.rtWindowSize > 0 ? { hwjsRtWindowBase: rtPart.rtWindowBase, hwjsRtWindowSize: rtPart.rtWindowSize } : {}, /* The reserved libc.so window (set for a needed-list image; * absent otherwise). Same stale-across-exec / worker re-derivation + * divergence-check contract as the rt window above. */ ...rtPart && rtPart.libcWindowSize > 0 ? { hwjsLibcWindowBase: rtPart.libcWindowBase, hwjsLibcWindowSize: rtPart.libcWindowSize } : {}, mode: forkResume ? "fork-resume" : "fork", pid: tid, tid, ppid, wasmBytes, ...placementImageKey(wasmBytes), memory: userMem, ctrl: ctrlSab, /* This handler answers 'leader-hold' (worker.mjs leaderHoldUntilGroupEmpty). */ leaderHold: 1, ...userDirtyCellInit(userMem), ...placementCellInit(userMem, true), ...signalPendingOffset !== void 0 ? { signalPendingOffset } : {}, ...effInheritSpec !== void 0 ? { inheritFiles: effInheritSpec.inheritFiles, fdActions: effInheritSpec.fdActions } : {}, ...forkResume && forkResume.tlsBase !== void 0 ? { tlsBase: forkResume.tlsBase } : {}, ...forkResume && forkResume.forkHandle !== void 0 ? { forkHandle: forkResume.forkHandle } : {}, ...forkResume && forkResume.forkOwner !== void 0 ? { forkOwner: forkResume.forkOwner } : {}, ...forkResume && forkResume.parentSp !== void 0 ? { parentSp: forkResume.parentSp } : {}, ...forkResume && forkResume.forkTcb !== void 0 ? { forkTcb: forkResume.forkTcb } : {}, ...forkResume && forkResume.mainTlsBase !== void 0 ? { mainTlsBase: forkResume.mainTlsBase } : {}, ...forkResume && forkResume.dlopenFork && typeof forkResume.dlopenFork === "object" ? { dlopenFork: forkResume.dlopenFork } : {}, ...forkResume && Array.isArray(forkResume.lowFdRoutes) && forkResume.lowFdRoutes.length ? { lowFdRoutes: forkResume.lowFdRoutes } : {}, ...forkResume && forkResume.sharedFileMaps && typeof forkResume.sharedFileMaps === "object" ? { sharedFileMaps: forkResume.sharedFileMaps } : {}, ...forkResume && forkResume.wasmJitFloor !== void 0 && forkResume.wasmJitFloor > 0 ? { wasmJitFloor: forkResume.wasmJitFloor } : {}, ...!forkResume && tid === 1 && Array.isArray(opts.initArgv) && opts.initArgv.length > 0 ? { argv: opts.initArgv, envp: Array.isArray(opts.initEnvp) ? opts.initEnvp : [] } : {}, ...!forkResume && tid === 1 && Array.isArray(opts.initLowFdRoutes) && opts.initLowFdRoutes.length > 0 ? { lowFdRoutes: opts.initLowFdRoutes } : {}, ...execFrom ? { bindTaskAddr: execFrom.taskAddr >>> 0, bindTaskPid: execFrom.pid | 0, argv: execFrom.argv, envp: execFrom.envp, ...Array.isArray(execFrom.lowFdRoutes) && execFrom.lowFdRoutes.length ? { lowFdRoutes: execFrom.lowFdRoutes } : {} } : {} }; if (pool) { const ACK_MS = 250; const a4cDbg = (s) => { if (globalThis.process?.env?.A4C_DBG) globalThis.process.stderr.write(`[a4c] ${s} `); }; const starvedLanes = /* @__PURE__ */ new Set(); let placeCycles = 0; for (; ; ) { const claimSab = new SharedArrayBuffer(4); const claim = new Int32Array(claimSab); pool.laneInboxPost?.(worker); postToWorker(worker, { kind: "add-task", routeKey, spec: { routeKey, claim: claimSab, ...perTaskInit } }); const deadline = Date.now() + ACK_MS; while (Atomics.load(claim, 0) === 0 && Date.now() < deadline) { const w = Atomics.waitAsync(claim, 0, 0, Math.max(1, deadline - Date.now())); if (w.async) { try { await w.value; } catch { } } } if (Atomics.load(claim, 0) === 2) { pool.markLaneLive(cpuId); break; } if (Atomics.compareExchange(claim, 0, 0, 1) === 2) { pool.markLaneLive(cpuId); break; } pool.markLaneSuspect(cpuId); starvedLanes.add(cpuId); const from = cpuId; if (poolWorkerRec) { poolWorkerRec.residentCount = Math.max(0, poolWorkerRec.residentCount - 1); if (laneOwner) pool.laneRelease(poolWorkerRec.cpuId, laneOwner); } let next; try { const fp = forkPlacement(); next = await pool.getPoolWorker(fp.avoid, starvedLanes, void 0, fp.foreign); } catch (e) { a4cDbg(`re-place tid=${tid} routeKey=${routeKey} aborted: ${e.message}`); opts.onDmesg?.( 4, `hwjs#3: add-task tid=${tid} routeKey=${routeKey} re-placement aborted (${e.message}) \u2014 refusing spawn with -EAGAIN `, tid ); return EAGAIN; } if (starvedLanes.has(next.cpuId)) { starvedLanes.clear(); placeCycles++; opts.onDmesg?.( 3, `hwjs#3: add-task tid=${tid} routeKey=${routeKey} found EVERY pool lane starved (cycle ${placeCycles}) \u2014 all residents are spinning without yielding; continuing to probe lanes `, tid ); } poolWorkerRec = next; cpuId = poolWorkerRec.cpuId; poolWorkerRec.residentCount++; if (laneOwner) pool.laneOccupy(cpuId, laneOwner); worker = poolWorkerRec.worker; ledgerTask?.notePlacement(cpuId, `re-placed: lane ${from} claim timed out (starved)`); opts.onDmesg?.( 4, `hwjs#3: add-task tid=${tid} routeKey=${routeKey} claim timed out on starved pool lane cpu=${from} (resident spinning without a yield); re-placing on cpu=${cpuId} `, tid ); a4cDbg(`re-place tid=${tid} routeKey=${routeKey} cpu=${from} -> cpu=${cpuId} (lane starved)`); } } else { await adoptPreemptTimer(opts, worker); postToWorker(worker, { kind: "init", /* The raw SAB only for an embedder that supplies no * `WebAssembly.Memory` — see the createPoolWorker init for why posting * both is a duplicate alias AND a stale-buffer hazard. */ ...opts.kernelMemoryWasm === void 0 ? { kernelMemory: opts.kernelMemory } : {}, ...opts.vmlinuxModule !== void 0 ? { vmlinuxModule: opts.vmlinuxModule } : {}, ...opts.hwjsRtModule !== void 0 ? { hwjsRtModule: opts.hwjsRtModule, hwjsRtBytes: opts.hwjsRtBytes, hwjsRtProvenance: opts.hwjsRtProvenance } : {}, /* The machine-wide shared-lib map rides the dedicated-Worker * init (the rt-fields precedent grown into a digest-keyed map). */ ...(() => { const shl = opts.__sharedLibs; const l = shl ? shl.list() : []; return l.length > 0 ? { sharedLibs: l } : {}; })(), ...opts.kernelMemoryWasm !== void 0 ? { kernelMemoryWasm: opts.kernelMemoryWasm } : {}, ...opts.__kernelLaneLocks !== void 0 ? { kernelLaneLocks: opts.__kernelLaneLocks } : {}, ...opts.__fileMapGen !== void 0 ? { fileMapGen: opts.__fileMapGen } : {}, ...opts.pauseBuffer !== void 0 ? { pauseBuffer: opts.pauseBuffer } : {}, cpuId, ...perTaskInit }); } if (opts.vmlinuxModule === void 0) { registerProcessMaps(tid); } const finalPid = await vmlinuxAllocated; return finalPid; } var adoptionTimeoutLeakedKernelTasks = 0; var nextVforkRoutingId = 1073741824; var vforkTraceOn = typeof process !== "undefined" && process?.env?.HWJS_VFORK_TRACE === "1"; var vforkTrace = (opts, who, what) => { if (vforkTraceOn) opts.onDmesg?.(4, `hwjs-vfork t=${(performance.timeOrigin + performance.now()).toFixed(1)} ${who} ${what} `, who); }; async function serveVforkRequest(msg, ctrl, callerPid, parents, cloneCleartidMap, opts) { const answer = (v) => { Atomics.store(ctrl, C2.RET_LO, v | 0); Atomics.store(ctrl, C2.RET_HI, v < 0 ? -1 : 0); Atomics.store(ctrl, C2.STATE, RESPONSE2); Atomics.notify(ctrl, C2.STATE); }; const st = Atomics.load(ctrl, C2.STATE); if (st !== REQUEST2) { throw new Error( `vfork: 'vfork' message from pid ${callerPid} arrived with ctrl STATE=${st} (expected REQUEST=${REQUEST2}); refusing to run a child over a caller that is not parked.` ); } vforkTrace(opts, callerPid, "request"); const parent = parents.get(callerPid); if (!parent) { opts.onUserError?.( callerPid, `vfork: no parent record for pid ${callerPid}; the clone is refused with -EAGAIN and libc falls back to fork.` ); answer(EAGAIN); return; } const mem = parent.userMemory; const top = (msg.stack >>> 0 & ~15) >>> 0; const region = (top - WASM_THREAD_ARG_REGION_SIZE & ~15) >>> 0; if (top < WASM_PAGE_SIZE || top > mem.buffer.byteLength || typeof msg.fn !== "number") { answer( -22 /* -EINVAL */ ); return; } new Uint8Array(mem.buffer, region, WASM_THREAD_ARG_REGION_SIZE).fill(0); const dv = new DataView(mem.buffer, region, WASM_THREAD_ARG_REGION_SIZE); dv.setUint32(0, WASM_THREAD_ARG_MAGIC_LO, true); dv.setUint32(4, WASM_THREAD_ARG_MAGIC_HI, true); dv.setUint32(8, WASM_THREAD_ARG_VERSION, true); dv.setUint32(12, msg.flags >>> 0, true); dv.setUint32(16, msg.fn >>> 0, true); dv.setUint32(24, msg.arg >>> 0, true); dv.setUint32(32, callerPid >>> 0, true); dv.setUint32(48, (msg.tlsBase ?? 0) >>> 0, true); dv.setUint32(56, top, true); const req = { mode: WASM_SPAWN_THREAD, flags: 0, tid: nextVforkRoutingId++, parentTid: callerPid, execImageOffset: 0, execImageSize: 0, argRegionOffset: region, stackPointerOffset: region, tlsPointerOffset: (msg.tlsBase ?? 0) >>> 0, rtThread: true, threadsMax: 0, vfork: { envelope: { dlopenFork: msg.dlopenFork && typeof msg.dlopenFork === "object" ? msg.dlopenFork : null, ...Array.isArray(msg.lowFdRoutes) ? { lowFdRoutes: msg.lowFdRoutes } : {}, /* The caller waits in its pump, not in the syscall: its lane runs * other residents meanwhile and may take the child. */ callerYieldsDuringClone: true }, ...typeof msg.mainTlsBase === "number" && msg.mainTlsBase > 0 ? { mainTlsBase: msg.mainTlsBase >>> 0 } : {} } }; let r; try { r = await spawnThreadWorkerPlaced(req, parents, cloneCleartidMap, opts); } catch (e) { opts.onUserError?.( callerPid, `vfork: the child of pid ${callerPid} could not be started: ${e instanceof Error ? e.message : String(e)}; -EAGAIN.` ); r = EAGAIN; } vforkTrace(opts, callerPid, `answer ${r}`); answer(r); } async function spawnThreadWorker(req, parents, cloneCleartidMap, opts) { const heapWhy = opts.__heapBudget?.refusal(`thread spawn tid=${req.tid}`) ?? ""; if (heapWhy) { opts.onUserError?.(req.tid, `${heapWhy}. pthread_create returns EAGAIN and the process lives.`); opts.signalRegistry?.unregister(req.tid); return EAGAIN; } const limit = req.rtThread === true ? (req.threadsMax ?? 0) >>> 0 : 0; const contain = opts.__threadContain; const parent = parents.get(req.parentTid); if (limit === 0 || !parent || !contain) { return spawnThreadWorkerPlaced(req, parents, cloneCleartidMap, opts); } const groupPid = parent.leaderPid ?? req.parentTid; const have = contain.admittedThreads(groupPid) + 1; if (have >= limit) { opts.onUserError?.( req.tid, `thread spawn tid=${req.tid} (group ${groupPid}): the process has ${have} thread(s), its main included, and this machine was booted with wasm32.threads_max=${limit}. Refusing the clone with -EAGAIN \u2014 pthread_create returns EAGAIN and the process lives.` ); opts.signalRegistry?.unregister(req.tid); return EAGAIN; } contain.admit(groupPid, req.tid); try { return await spawnThreadWorkerPlaced(req, parents, cloneCleartidMap, opts); } finally { contain.settle(groupPid, req.tid); } } async function spawnThreadWorkerPlaced(req, parents, cloneCleartidMap, opts) { const parent = parents.get(req.parentTid); if (!parent) { return ECHILD; } const groupPid = parent.leaderPid ?? req.parentTid; const vfork = req.vfork ?? null; if ((typeof process === "undefined" ? void 0 : process)?.env?.HARDWAREJS_DEBUG_K7_U4F) { process.stderr.write( `[K7-U4f spawnThreadWorker] tid=${req.tid} parentTid=${req.parentTid} argRegion=0x${(req.argRegionOffset >>> 0).toString(16)} stack=0x${(req.stackPointerOffset >>> 0).toString(16)} tls=0x${(req.tlsPointerOffset >>> 0).toString(16)} ` ); } const shl = opts.__sharedLibs; const testNoPlacement = globalThis.process?.env?.HWJS_TEST_THREAD_NO_PLACEMENT === "1"; const testNoSharedLibs = globalThis.process?.env?.HWJS_TEST_THREAD_NO_SHAREDLIBS === "1"; let neededDigest2 = null; try { neededDigest2 = imageNeededLibcDigest(parent.wasmBytes); } catch { } const dynamicMain = neededDigest2 !== null; const rtThread = req.rtThread === true; const threadOrdinal = rtThread ? opts.__threadOrdinals?.next(groupPid) ?? 0 : 0; { const uim = opts.__userImageModule; if (uim) { try { await uim(parent.wasmBytes); } catch { } } } let envelope = null; if (vfork) { envelope = { ...vfork.envelope }; } else if (neededDigest2 !== null && !testNoPlacement) { if (shl?.deliveryPending) { const w = shl.deliveryPending(neededDigest2); if (w) await w; } if (typeof parent.requestThreadPlacement !== "function") { opts.onUserError?.( req.tid, `hwjs-libc: WASM_SPAWN_THREAD of a libc.so-needing main (pid ${req.parentTid}) but its parent record carries no placement channel (registerParent-installed synthetic record?) \u2014 refusing the thread spawn with -EAGAIN (never-silent)` ); return EAGAIN; } try { envelope = await parent.requestThreadPlacement(); } catch (e) { opts.onUserError?.( req.tid, `hwjs-libc: thread-placement fetch for pid ${req.parentTid} FAILED \u2014 ${e instanceof Error ? e.message : String(e)} \u2014 refusing the thread spawn with -EAGAIN (never-silent)` ); return EAGAIN; } if (!envelope || !envelope.dlopenFork || !envelope.dlopenFork.libcSo) { opts.onUserError?.( req.tid, `hwjs-libc: thread-placement record for the libc.so-needing pid ${req.parentTid} carries no libcSo placement (module #1 was never instantiated in the parent?) \u2014 refusing the thread spawn with -EAGAIN (never-silent)` ); return EAGAIN; } } else { envelope = parent.peekThreadPlacement?.() ?? null; if (rtThread && !envelope?.clone && typeof parent.requestThreadPlacement === "function") { try { envelope = await parent.requestThreadPlacement(); } catch (e) { opts.onUserError?.( req.tid, `hwjs-threads: clone-args fetch for runtime static thread (pid ${req.parentTid} tid ${req.tid}) FAILED \u2014 ${e instanceof Error ? e.message : String(e)} \u2014 refusing the thread spawn with -EAGAIN (a missing CLEARTID registration would wedge pthread_join; never-silent)` ); return EAGAIN; } } if (rtThread && !envelope?.clone) { opts.onUserError?.( req.tid, `hwjs-threads: runtime static thread spawn (pid ${req.parentTid} tid ${req.tid}) has no clone-args envelope (no pre-push, no reply) \u2014 refusing with -EAGAIN (never a settid/cleartid-less thread; pthread_join would wedge silently)` ); return EAGAIN; } } const threadDlopenFork = dynamicMain && !testNoPlacement ? envelope?.dlopenFork ?? null : null; if ((dynamicMain || rtThread) && envelope?.clone) { const CLONE_PARENT_SETTID = 1048576; const CLONE_CHILD_CLEARTID2 = 2097152; const { flags, ptid, ctid } = envelope.clone; const memBytes = parent.userMemory.buffer.byteLength; if (flags & CLONE_PARENT_SETTID && ptid !== 0 && (ptid & 3) === 0 && ptid + 4 <= memBytes) { new Uint32Array(parent.userMemory.buffer)[ptid >>> 2] = req.tid >>> 0; } if (flags & CLONE_CHILD_CLEARTID2 && ctid !== 0 && (ctid & 3) === 0 && ctid + 4 <= memBytes) { cloneCleartidMap.set(req.tid, { ctid, userMemory: parent.userMemory }); } } const ctrlSab = new SharedArrayBuffer( 64 /* 16 * i32 */ ); const ctrl = new Int32Array(ctrlSab); let signalPendingOffset; if (opts.signalRegistry) { const off = allocSignalPendingRegion(parent.userMemory); if (off < 0) { opts.onUserError?.( req.tid, `thread spawn tid=${req.tid}: signal-pending page allocation FAILED. ` + userMemoryGrowRefusal( opts.ram, parent.userMemory, req.tid, "signal-pending page for a new thread", parent.userMemory.buffer.byteLength + WASM_PAGE_SIZE ) + ` pthread_create observes EAGAIN (loud, attributed).` ); return ENOMEM2; } signalPendingOffset = off; opts.signalRegistry.register(req.tid, { userMemory: parent.userMemory, signalPendingOffset: off }); } const cpuIdHooks = opts.__cpuIdHooks; const pool = opts.__pool; const laneOwner = pool ? pool.newLaneOwner(groupPid) : null; const threadMemoryId = userMemoryId(parent.userMemory); const homeLanes = () => { const home = pool.lanesOwnedByGroup(groupPid); const idle = pool.threadImages?.idleLane(threadMemoryId); if (idle !== void 0) home.add(idle); return home; }; const callerCpuId = dynamicMain || rtThread ? parent.getCpuId?.() : void 0; const poolLanes = pool ? pool.liveWorkerCount() : 0; const callerYieldsDuringClone = envelope?.callerYieldsDuringClone === true; const foreignLanes = () => pool ? pool.lanesOwnedByOthers(groupPid) : /* @__PURE__ */ new Set(); const eligibleLanes = () => { if (!pool) return []; if (callerYieldsDuringClone) return pool.liveCpuIds(); return pool.liveCpuIds().filter((c) => c !== callerCpuId); }; const poolHasEligibleLane = eligibleLanes().length > 0; const pinRawIfSet = threadPlacementPinRaw(); const pin = pool && rtThread && !vfork ? resolveThreadPlacementPin(threadOrdinal, pool.maxCpuId) : { kind: "none" }; if (pin.kind === "error") { opts.onUserError?.( req.tid, `thread spawn tid=${req.tid} (group ${groupPid}, thread ${threadOrdinal}): ${pin.message}. Refusing the clone with -EAGAIN (loud, attributed) \u2014 every thread spawn on this machine is refused while the pin table is unusable, so a broken table can never be mistaken for an unpinned run.` ); opts.signalRegistry?.unregister(req.tid); return EAGAIN; } const pinnedCpuId = pin.kind === "pin" ? pin.cpuId : void 0; if (pinnedCpuId !== void 0 && !(pool && rtThread && !threadResidencyDisabled())) { opts.onUserError?.( req.tid, `thread spawn tid=${req.tid} (group ${groupPid}): HWJS_THREAD_PLACEMENT_PIN=${pinRawIfSet} pins thread ${threadOrdinal} to cpu ${pinnedCpuId}, but this spawn can never be a pool resident (${!pool ? "this machine has no CPU-Worker pool (no vmlinuxModule)" : !rtThread ? "it is a legacy-arm spawn with no runtime thread (wasm32.experimental_thread_clone=1)" : "HWJS_THREAD_DEDICATED_WORKERS=1 has thread residency disabled machine-wide"}). Refusing the clone with -EAGAIN rather than running an UNPINNED spawn under a pinned transcript.` ); opts.signalRegistry?.unregister(req.tid); return EAGAIN; } const poolResidentNatural = !!pool && rtThread && !threadResidencyDisabled() && poolHasEligibleLane; const poolResident = poolResidentNatural || pinnedCpuId !== void 0; if (pool && rtThread && !threadResidencyDisabled() && !poolHasEligibleLane && pinnedCpuId === void 0) { const owned = foreignLanes(); const lanes = pool.liveCpuIds().sort((a, b) => a - b); opts.onDmesg?.( 4, `hwjs-threads: thread spawn tid=${req.tid} (group ${groupPid}) cannot be a pool resident \u2014 NO lane qualifies. Lanes: ${lanes.map((c) => `cpu${c}=${c === callerCpuId ? "CALLER" : "free"}[carries ${pool.laneOwnerText(c)}${owned.has(c) ? ", incl. other groups" : ""}]`).join(" ") || ""}. The CALLER's lane is the only excluded lane, and it is excluded because THIS caller pins that Worker for the whole clone(2): its image did not declare callerYieldsDuringClone, so the kernel's spawn-ring -517 is answered by the host's SYNCHRONOUS in-place restart loop instead of being handed to a libc that parks. Its onmessage therefore cannot claim an add-task until the clone returns, and the clone cannot return until the thread adopts. A caller whose libc absorbs the sentinel at raw veneers (musl) is NOT excluded \u2014 its lane is an ordinary lane, which is what makes cpu=1 expressible. Nor is a lane another THREAD GROUP carries: one JS thread is one scheduler, and that is what "cpu=N" means. So this is a machine with ${poolLanes} CPU Worker(s) whose only lane belongs to a caller that holds it. Falling back to a DEDICATED Worker realm for this thread: the "no host Worker after boot" invariant does NOT hold on such a machine. Raise num_vcpu, or build the caller against a libc that parks at raw syscalls. `, req.tid ); } let poolWorkerRec = null; let routeKey = 0; let cpuId; const bannedLanes = () => new Set(callerCpuId !== void 0 && !callerYieldsDuringClone ? [callerCpuId] : []); if (poolResident) { try { if (pinnedCpuId !== void 0) { let would; if (!poolResidentNatural) { would = "dedicated-Worker"; } else { try { would = `cpu=${(await pool.getPoolWorker(callerCpuId, bannedLanes(), void 0, foreignLanes())).cpuId}`; } catch { would = "unknown (unpinned probe failed)"; } } poolWorkerRec = await pool.getPoolWorker( callerCpuId, bannedLanes(), pinnedCpuId, foreignLanes(), homeLanes(), true ); opts.onDmesg?.( 4, `hwjs-thread-placement-pin: APPLIED thread=${threadOrdinal} cpu=${poolWorkerRec.cpuId} would-have-been=${would} tid=${req.tid} group=${groupPid} callerCpu=${callerCpuId ?? "-"} poolLanes=${poolLanes} maxCpuId=${pool.maxCpuId} overrode=${callerCpuId === pinnedCpuId ? "avoidCpuId+callerLaneExclusion" : "avoidCpuId"} table=HWJS_THREAD_PLACEMENT_PIN=${pinRawIfSet} `, req.tid ); } else { const vforkLane = vfork ? pool.threadImages?.idleLane(threadMemoryId) : void 0; if (vforkLane !== void 0 && !bannedLanes().has(vforkLane)) { try { poolWorkerRec = await pool.getPoolWorker(void 0, bannedLanes(), vforkLane); } catch { poolWorkerRec = null; } } poolWorkerRec ??= await pool.getPoolWorker( callerCpuId, bannedLanes(), void 0, foreignLanes(), homeLanes(), true ); } } catch (e) { opts.onUserError?.( req.tid, `thread spawn tid=${req.tid}: pool placement failed (${e instanceof Error ? e.message : String(e)}) \u2014 the machine is tearing down or the pool is empty; refusing the clone with -EAGAIN (loud, attributed).` ); opts.signalRegistry?.unregister(req.tid); return EAGAIN; } cpuId = poolWorkerRec.cpuId; routeKey = pool.allocRouteKey(); poolWorkerRec.residentCount++; pool.laneOccupy(cpuId, laneOwner); pool.threadImages?.threadPlaced(threadMemoryId, cpuId); pool.noteResidentDelta(1); } else { cpuId = cpuIdHooks ? cpuIdHooks.allocateCpuId(req.tid, callerCpuId) : 1; if (cpuId === 0) { opts.onUserError?.( req.tid, `thread spawn tid=${req.tid}: cpu-lane pool SATURATED (machine-wide thread-Worker lane keys all in flight) \u2014 pthread_create observes EAGAIN (loud, attributed). If this machine is not actually running that many threads, a lane has leaked (a thread Worker outliving its group) \u2014 report it.` ); opts.signalRegistry?.unregister(req.tid); return EAGAIN; } } const ledgerTask = opts.__taskLedger?.open({ kind: "thread", spawnTid: req.tid, parentPid: req.parentTid, tgid: groupPid, cpuId, residency: poolResident ? "pool-resident" : "dedicated-worker", routeKey: poolResident ? routeKey : null, image: imageFactsOf(parent.wasmBytes, null), userMemory: parent.userMemory, sabSharedWithGroup: true }) ?? null; ledgerTask?.noteSignalPendingOffset(signalPendingOffset); opts.onDmesg?.( 6, `hwjs-thread-spawn tid=${req.tid} parentTid=${req.parentTid} group=${groupPid} thread=${threadOrdinal} cpu=${cpuId} resident=${poolResident ? `pool(routeKey=${routeKey})` : "dedicated-Worker"} avoidCpu=${callerCpuId ?? "-"}${poolResident && callerCpuId !== void 0 && cpuId === callerCpuId ? ` callerLane=shared(callerYields=${callerYieldsDuringClone ? 1 : 0})` : ""}${pinnedCpuId !== void 0 ? ` pin=${pinnedCpuId}` : ""} `, req.tid ); const platform = opts.platform ?? detectPlatform(); let worker = poolResident ? poolWorkerRec.worker : await createWorker(opts.workerEntry, platform, "thread-dedicated", `thread (tid ${req.tid})`); if (!poolResident) opts.__trackWorker?.(worker); const postReply = (m) => postToWorker(worker, poolResident ? { ...m, routeKey } : m); if (vfork) vforkTrace(opts, req.parentTid, `child placed cpu=${cpuId} resident=${poolResident ? 1 : 0}`); let threadKernelPid = 0; const threadPlacementPending = /* @__PURE__ */ new Map(); let threadPlacementSeq = 0; let threadPlacementUnsolicited = null; const threadPlacementWaiters = []; const peekThreadPlacement = () => { if (!threadPlacementUnsolicited) return null; const env = threadPlacementUnsolicited.envelope; threadPlacementUnsolicited = null; return env; }; const requestThreadPlacement = (timeoutMs = 5e3) => { const peeked = peekThreadPlacement(); if (peeked) return Promise.resolve(peeked); return new Promise((resolve, reject) => { const seq = ++threadPlacementSeq; let settled = false; const unwait = (fn2) => { const i = threadPlacementWaiters.indexOf(fn2); if (i >= 0) threadPlacementWaiters.splice(i, 1); }; const settle = (v) => { if (settled) return; settled = true; clearTimeout(timer); threadPlacementPending.delete(seq); unwait(settle); resolve(v); }; const fail = (e) => { if (settled) return; settled = true; clearTimeout(timer); threadPlacementPending.delete(seq); unwait(settle); reject(e); }; const timer = setTimeout(() => { fail(new Error( `hwjs-threads: thread-placement fetch from THREAD pid=${threadKernelPid || req.tid} seq=${seq} timed out after ${timeoutMs}ms \u2014 no clone-time pre-push arrived and the calling thread's Worker did not serve the request (starved lane / torn Worker); the nested thread spawn must be refused (never-silent)` )); }, timeoutMs); threadPlacementWaiters.push(settle); threadPlacementPending.set(seq, { resolve: settle, reject: fail }); try { if (poolResident) pool.laneInboxPost?.(worker); postReply({ kind: "thread-placement-request", seq, pid: threadKernelPid || req.tid }); } catch (e) { fail(e instanceof Error ? e : new Error(String(e))); } }); }; const threadContain = opts.__threadContain; if (vfork && threadContain?.noteVfork) threadContain.noteVfork(groupPid, req.tid); else threadContain?.note(groupPid, req.tid); const dropThreadRegistrations = () => { threadContain?.drop(groupPid, req.tid); threadContain?.dropReaper?.(req.tid); if (threadKernelPid > 0) { opts.signalRegistry?.unregister(threadKernelPid); parents.delete(threadKernelPid); threadKernelPid = 0; } }; const releaseThreadWorker = async () => { if (poolResident) { pool.poolHandlers.delete(routeKey); pool.syscallSyncDoors.delete(routeKey); if (poolWorkerRec) { poolWorkerRec.residentCount = Math.max(0, poolWorkerRec.residentCount - 1); if (laneOwner) pool.laneRelease(poolWorkerRec.cpuId, laneOwner); pool.threadImages?.threadLeft(threadMemoryId, poolWorkerRec.cpuId); poolWorkerRec = null; pool.noteResidentDelta(-1); } return; } await terminateWorker(worker); }; const releaseThreadCpuId = () => { if (!poolResident) cpuIdHooks?.releaseCpuId(req.tid); }; const reclaimThreadLane = (why) => { if (!poolResident) cpuIdHooks?.reclaimDedicatedLane?.(cpuId, req.tid, why); }; let exitFired = false; let releaseAdoptionGate = () => { }; const adoptionGate = new Promise((r) => { releaseAdoptionGate = r; }); let releaseVforkGate = () => { }; const vforkGate = new Promise((r) => { releaseVforkGate = r; }); let vforkPid = 0; const vforkAnswer = () => vforkPid > 0 ? vforkPid : EAGAIN; const threadCtx = { parents, spawnThread: (r) => spawnThreadWorker(r, parents, cloneCleartidMap, opts), cloneCleartidMap }; const exited = new Promise((resolve) => { threadContain?.registerReaper?.(req.tid, (why) => { releaseAdoptionGate("failed"); if (vfork) { threadContain?.markEverThreaded?.(groupPid); releaseVforkGate(vforkAnswer()); } if (exitFired) return; exitFired = true; if (poolResident) markCtrlReaped(ctrl); performCleartid(cloneCleartidMap, req.tid); opts.signalRegistry?.unregister(req.tid); dropThreadRegistrations(); releaseThreadCpuId(); opts.onUserError?.( req.tid, `thread tid=${req.tid} REAPED at group death (${why}): ${poolResident ? `the resident survived the stamp past the grace window \u2014 reaped from pool cpu=${cpuId} (routeKey=${routeKey}); the shared CPU Worker keeps serving its peers` : `the Worker survived the stamp past the grace window \u2014 terminated; cpu lane released`}; cleartid, signal page and registrations released (loud, attributed)` ); ledgerTask?.noteExit(-1, `reaped at group death: ${why}`); opts.onUserExit?.(req.tid, -1); if (poolResident) { try { postToWorker(worker, { kind: "task-reap", routeKey, why }); } catch { } } void releaseThreadWorker().then(() => { reclaimThreadLane(`group-death reap: ${why}`); freeSignalPendingRegion(parent.userMemory, signalPendingOffset); signalPendingOffset = void 0; }); resolve(-1); }); const handleThreadMsg = async (msg) => { if (dlPlacementMessage(msg, postReply, pool?.releaseThreadImages)) return; if (msg?.kind === "thread-adopted") { if (vfork) vforkTrace(opts, req.parentTid, "child adopted"); releaseAdoptionGate("adopted"); return; } if (msg?.kind === "thread-refused") { opts.onUserError?.(req.tid, String(msg.message ?? "thread refused (no message)")); releaseAdoptionGate("failed"); if (vfork) releaseVforkGate(EAGAIN); return; } if (msg?.kind === "thread-placement") { if (msg.unsolicited) { const envelope2 = { dlopenFork: msg.dlopenFork && typeof msg.dlopenFork === "object" ? msg.dlopenFork : null, ...msg.clone && typeof msg.clone === "object" ? { clone: { flags: (msg.clone.flags ?? 0) >>> 0, ptid: (msg.clone.ptid ?? 0) >>> 0, ctid: (msg.clone.ctid ?? 0) >>> 0 } } : {}, ...Array.isArray(msg.lowFdRoutes) ? { lowFdRoutes: msg.lowFdRoutes.map((n) => n | 0) } : {}, /* STRICT === true: absent (an older worker bundle) and any * non-boolean read as UNKNOWN, and unknown keeps the caller-lane * exclusion. A truthy coercion here would turn a missing field * into a placement that deadlocks. */ callerYieldsDuringClone: msg.callerYieldsDuringClone === true }; const w = threadPlacementWaiters.shift(); if (w) w(envelope2); else threadPlacementUnsolicited = { envelope: envelope2 }; return; } const p = threadPlacementPending.get(msg.seq | 0); if (p) { threadPlacementPending.delete(msg.seq | 0); if (msg.error) p.reject(new Error(String(msg.error))); else p.resolve({ dlopenFork: msg.dlopenFork && typeof msg.dlopenFork === "object" ? msg.dlopenFork : null }); } return; } if (msg?.kind === "vfork") { await serveVforkRequest( msg, ctrl, threadKernelPid || req.tid, parents, cloneCleartidMap, opts ); return; } if (msg?.kind === "vfork-exec" && vfork) { const pid = vforkPid; let r = EAGAIN; vforkTrace(opts, req.parentTid, `child exec hand-off pid=${pid}`); if (!exitFired && pid > 0) { opts.signalRegistry?.unregister(req.tid); dropThreadRegistrations(); try { r = await spawnForkWorker( msg.wasmBytes, 0, groupPid, parents, cloneCleartidMap, opts, void 0, void 0, { taskAddr: msg.taskAddr >>> 0, pid, argv: Array.isArray(msg.argv) ? msg.argv : [], envp: Array.isArray(msg.envp) ? msg.envp : [], ...Array.isArray(msg.lowFdRoutes) ? { lowFdRoutes: msg.lowFdRoutes } : {}, ...poolResident ? { cpuId } : {} } ); } catch (e) { opts.onUserError?.( req.tid, `vfork: the exec hand-off of pid ${pid} failed: ${e instanceof Error ? e.message : String(e)}` ); r = EAGAIN; } } vforkTrace(opts, req.parentTid, `child exec resident up r=${r}`); Atomics.store(ctrl, C2.RET_LO, r < 0 ? r : 0); Atomics.store(ctrl, C2.RET_HI, r < 0 ? -1 : 0); Atomics.store(ctrl, C2.STATE, RESPONSE2); Atomics.notify(ctrl, C2.STATE); if (r < 0) return; exitFired = true; releaseAdoptionGate("adopted"); releaseVforkGate(pid); releaseThreadCpuId(); ledgerTask?.noteExit(0, `vfork child pid ${pid} exec'ed into a memory of its own`); await releaseThreadWorker(); reclaimThreadLane("vfork child exec"); freeSignalPendingRegion(parent.userMemory, signalPendingOffset); signalPendingOffset = void 0; resolve(0); return; } if (msg?.kind === "fork") { const userMem = parent.userMemory; opts.onDmesg?.( 6, `hwjs-fork(thread): fork from thread tid=${req.tid} block 0x${((msg.tcb ?? 0) >>> 0).toString(16)} `, req.tid ); const st = Atomics.load(ctrl, C2.STATE); if (st !== REQUEST2) { throw new Error( "D1-FORK(thread): 'fork' message arrived with ctrl STATE=" + st + " (expected REQUEST=" + REQUEST2 + "); refusing to snapshot a non-quiesced parent address space." ); } const copyBytes = userMemoryDirtyBytes(userMem); let childMem; const parentBytes = userMem.buffer.byteLength; try { const heapWhy = opts.__heapBudget?.refusal("fork") ?? ""; if (heapWhy) throw new Error(heapWhy); childMem = opts.ram.allocForkUserMemory(userMem, copyBytes); const deficitPages = Math.ceil((parentBytes - childMem.buffer.byteLength) / 65536); if (deficitPages > 0) childMem.grow(deficitPages); } catch { Atomics.store(ctrl, C2.RET_LO, ENOMEM2 | 0); Atomics.store(ctrl, C2.RET_HI, -1); Atomics.store(ctrl, C2.STATE, RESPONSE2); Atomics.notify(ctrl, C2.STATE); return; } new Uint8Array(childMem.buffer).set( new Uint8Array(userMem.buffer, 0, copyBytes) ); traceForkCopy(groupPid, copyBytes, parentBytes); const parentBump = userMemoryBumpPointers.get(userMem); const parentPart = userMemoryPartitions.get(userMem); if (parentBump !== void 0 && parentPart) { setUserBump(childMem, parentBump); if (copyBytes > parentBump) markUserMemoryDirty(childMem); userMemoryPartitions.set(childMem, { ...parentPart }); userMemoryMmapFreeLists.set( childMem, getMmapFreeList(userMem).map((r) => ({ ...r })) ); } else { initUserMemoryPartition(childMem, parent.wasmBytes, { ram: opts.ram, pid: -1 }); markUserMemoryDirty(childMem); } if (signalPendingOffset !== void 0) { new Int32Array(childMem.buffer, signalPendingOffset >>> 0, 3).fill(0); } const childPid = await spawnForkWorker( parent.wasmBytes, 0, /* kernel parent = the PROCESS, not the calling thread; a vfork * child is a process of its own */ vfork ? threadKernelPid || groupPid : groupPid, parents, cloneCleartidMap, opts, void 0, { userMem: childMem, signalPendingOffset, parentCpuId: cpuId, ...typeof msg.tlsBase === "number" ? { tlsBase: msg.tlsBase >>> 0 } : {}, ...typeof msg.forkHandle === "number" ? { forkHandle: msg.forkHandle >>> 0 } : {}, ...typeof msg.forkOwner === "number" ? { forkOwner: msg.forkOwner >>> 0 } : {}, ...typeof msg.parentSp === "number" ? { parentSp: msg.parentSp >>> 0 } : {}, /* Step 7: the child keeps the CALLER's block and main TLS. */ ...typeof msg.tcb === "number" && msg.tcb >>> 0 !== 0 ? { forkTcb: msg.tcb >>> 0 } : {}, ...typeof msg.mainTlsBase === "number" && msg.mainTlsBase >>> 0 !== 0 ? { mainTlsBase: msg.mainTlsBase >>> 0 } : {}, ...typeof msg.dlopenFork === "object" && msg.dlopenFork !== null ? { dlopenFork: msg.dlopenFork } : {}, ...Array.isArray(msg.lowFdRoutes) ? { lowFdRoutes: msg.lowFdRoutes } : {}, /* The parent's writable shared file mappings, shadows included. */ ...typeof msg.sharedFileMaps === "object" && msg.sharedFileMaps !== null ? { sharedFileMaps: msg.sharedFileMaps } : {}, /* SYS_wasm_jit's fork floor (worker.mjs forkFloor). */ ...Number.isInteger(msg.wasmJitFloor) && msg.wasmJitFloor > 0 ? { wasmJitFloor: msg.wasmJitFloor } : {} } ); Atomics.store(ctrl, C2.RET_LO, childPid | 0); Atomics.store(ctrl, C2.RET_HI, childPid < 0 ? -1 : 0); Atomics.store(ctrl, C2.STATE, RESPONSE2); Atomics.notify(ctrl, C2.STATE); return; } if (msg?.kind === "syscall") { try { await dispatchSyscall(ctrl, parent.userMemory, req.tid, opts, threadCtx); } catch (e) { opts.onUserError?.( req.tid, `thread tid=${req.tid} syscall dispatch failed after group teardown (contained; -ESRCH): ${e instanceof Error ? e.message : String(e)}` ); Atomics.store( ctrl, C2.RET_LO, -3 /* -ESRCH */ ); Atomics.store(ctrl, C2.RET_HI, -1); Atomics.store(ctrl, C2.STATE, RESPONSE2); Atomics.notify(ctrl, C2.STATE); } return; } if (msg?.kind === "exit") { releaseAdoptionGate("adopted"); if (vfork) releaseVforkGate(vforkAnswer()); if (!exitFired) { exitFired = true; const code2 = msg.code | 0; if ((typeof process === "undefined" ? void 0 : process)?.env?.HARDWAREJS_DEBUG_K7_U4F) { process.stderr.write(`[K7-U4f thread] tid=${req.tid} exit code=${code2} `); } const ge = msg.groupExit; if (ge && (ge.zapped | 0) > 0) { const w = ge.wstatus | 0; threadContain?.killGroup( groupPid, req.tid, 9, `a group terminus in a thread: the kernel condemned ${ge.zapped} other thread(s) of pid=${groupPid} and set the group's exit code to 0x${w.toString(16)} (` + (w & 127 ? `WIFSIGNALED WTERMSIG=${w & 127} \u2014 complete_signal's fatal block` : `WIFEXITED WEXITSTATUS=${w >> 8 & 255} \u2014 do_group_exit`) + ` / zap_other_threads) \u2014 unwinding their Workers` ); } else if (msg.kind_exit === "exit-by-signal" && !ge) { opts.onDmesg?.( 3, `hwjs group-death: thread tid=${req.tid} of pid=${groupPid} died by a fatal signal, but no kernel verdict came with the exit \u2014 the group is NOT condemned and its other threads keep running. KERNEL/HOST SKEW (rebuild vmlinux); on Linux this process would be dead `, req.tid ); } performCleartid(cloneCleartidMap, req.tid); opts.signalRegistry?.unregister(req.tid); dropThreadRegistrations(); releaseThreadCpuId(); if (msg.wasmSyscallStats && opts.onWasmSyscallStats) { opts.onWasmSyscallStats(req.tid, msg.wasmSyscallStats); } const cwv = (msg.coopWaitViolations ?? 0) | 0; if (cwv > 0) { opts.onUserError?.( req.tid, `hwjs-coopwait: thread tid=${req.tid} (pid ${threadKernelPid || "?"}, thread ${threadOrdinal}) blocked its shared CPU Worker in an unbounded raw FUTEX_WAIT ${cwv} time(s) \u2014 the libc did not set HWJS_FUTEX_COOP_WAIT (PLAN-THREAD-POOL-RESIDENCY contract 3). Every co-resident task stalled for the duration.` ); } const srv = (msg.syncRestartViolations ?? 0) | 0; if (srv > 0) { opts.onUserError?.( req.tid, `hwjs-coopwait: thread tid=${req.tid} (pid ${threadKernelPid || "?"}, thread ${threadOrdinal}) took the SYNCHRONOUS in-place -517 block-restart ${srv} time(s) \u2014 its libc does not absorb the sentinel at raw syscalls (__hwjs_libc_syscall_park_abi absent), so the shared CPU Worker's event loop froze for the duration (PLAN-THREAD-POOL-RESIDENCY contract 3).` ); } ledgerTask?.noteExit(code2, "exit message from the thread Worker"); opts.onUserExit?.(req.tid, code2, userExitInfo(msg)); await releaseThreadWorker(); reclaimThreadLane("thread exit"); freeSignalPendingRegion(parent.userMemory, signalPendingOffset); signalPendingOffset = void 0; resolve(code2); } return; } if (msg?.kind === "error") { releaseAdoptionGate("failed"); if (vfork) releaseVforkGate(vforkAnswer()); if (!exitFired) { exitFired = true; if ((typeof process === "undefined" ? void 0 : process)?.env?.HARDWAREJS_DEBUG_K7_U4F) { process.stderr.write(`[K7-U4f thread] tid=${req.tid} error: ${msg.message} `); } performCleartid(cloneCleartidMap, req.tid); opts.signalRegistry?.unregister(req.tid); dropThreadRegistrations(); if (!vfork) threadContain?.killGroup(groupPid, req.tid); releaseThreadCpuId(); ledgerTask?.noteExit(-1, `terminal trap in the thread Worker: ${String(msg.message ?? "")}`); opts.onUserError?.(req.tid, String(msg.message ?? "")); opts.onUserExit?.(req.tid, -1); await releaseThreadWorker(); reclaimThreadLane("terminal thread trap"); freeSignalPendingRegion(parent.userMemory, signalPendingOffset); signalPendingOffset = void 0; resolve(-1); } return; } if (msg?.kind === "task-probe-reply") { opts.__taskProbeReply?.(msg); return; } if (msg?.kind === "machine-power") { opts.onMachinePower?.((msg.cmd | 0) >>> 0); return; } if (msg?.kind === "user-report") { opts.onUserError?.(req.tid, String(msg.message ?? "")); return; } if (msg?.kind === "vmlinux-ready") { const kp = msg.pid | 0; if (kp > 0) ledgerTask?.notePid(kp, groupPid); if (kp > 0 && !exitFired) threadKernelPid = kp; if (vfork && kp > 0 && !exitFired) vforkPid = kp; if (vfork) vforkTrace(opts, req.parentTid, `child vmlinux-ready pid=${kp}`); if (threadKernelPid > 0 && threadKernelPid !== req.tid && signalPendingOffset !== void 0 && opts.signalRegistry) { opts.signalRegistry.register(threadKernelPid, { userMemory: parent.userMemory, signalPendingOffset }); } if (threadKernelPid > 0 && !exitFired && !threadParentRegistrationDisabled()) { parents.set(threadKernelPid, { wasmBytes: parent.wasmBytes, userMemory: parent.userMemory, requestThreadPlacement, peekThreadPlacement, getCpuId: () => cpuId, leaderPid: vfork ? threadKernelPid : groupPid }); } opts.onVmlinuxReady?.(req.tid, { hasWasmSyscall: !!msg.hasWasmSyscall, cpuId, initTaskAddr: typeof msg.initTaskAddr === "number" ? msg.initTaskAddr : 0, perProcessTaskAddr: typeof msg.perProcessTaskAddr === "number" ? msg.perProcessTaskAddr : 0 }); return; } if (msg?.kind === "vmlinux-error") { opts.onUserError?.( req.tid, `vmlinux instantiation failed in Worker: ${String(msg.message ?? "")}` ); if (vfork) releaseVforkGate(EAGAIN); return; } if (msg?.kind === "dmesg") { opts.onDmesg?.((msg.level | 0) >>> 0, String(msg.text), req.tid); return; } }; if (poolResident) { pool.poolHandlers.set(routeKey, (m) => { void handleThreadMsg(m); }); pool.syscallSyncDoors.set(routeKey, () => { let p; try { p = dispatchSyscall(ctrl, parent.userMemory, req.tid, opts, threadCtx); } catch (e) { opts.onUserError?.( req.tid, `hwjs-merged: the SYNCHRONOUS syscall door threw for thread tid=${req.tid} nr=${ctrl[C2.NR] | 0} \u2014 ${e instanceof Error ? e.message : String(e)}. Declining, so the caller takes the message route: nothing was written here.` ); return void 0; } p?.catch?.((e) => { opts.onUserError?.( req.tid, `hwjs-merged: a thread syscall dispatched through the SYNCHRONOUS door rejected after awaiting (tid=${req.tid} nr=${ctrl[C2.NR] | 0}) \u2014 ${e instanceof Error ? e.message : String(e)}` ); }); return Atomics.load(ctrl, C2.STATE) === RESPONSE2 ? "sync" : "async"; }); } else { onMessage(worker, handleThreadMsg); onError(worker, async (err2) => { releaseAdoptionGate("failed"); if (vfork) releaseVforkGate(vforkAnswer()); if (!exitFired) { exitFired = true; if ((typeof process === "undefined" ? void 0 : process)?.env?.HARDWAREJS_DEBUG_K7_U4F) { process.stderr.write(`[K7-U4f thread] tid=${req.tid} onError: ${err2 instanceof Error ? err2.message : String(err2)} `); } performCleartid(cloneCleartidMap, req.tid); opts.signalRegistry?.unregister(req.tid); dropThreadRegistrations(); if (!vfork) threadContain?.killGroup(groupPid, req.tid); releaseThreadCpuId(); ledgerTask?.noteExit(-1, `Worker-level error event: ${err2 instanceof Error ? err2.message : String(err2)}`); opts.onUserError?.(req.tid, err2 instanceof Error ? err2.message : String(err2)); opts.onUserExit?.(req.tid, -1); await releaseThreadWorker(); freeSignalPendingRegion(parent.userMemory, signalPendingOffset); signalPendingOffset = void 0; resolve(-1); } }); } }); void exited; const perThreadInit = { mode: "thread", /* Thread-spawn fix (vmlinux path, DYNAMIC mains only — scope boundary * above): the pid field is the WORKER-SIDE TASK ALLOCATOR SENTINEL * (1 → kernel_init REUSE; 0 → natural alloc_pid). * Passing req.parentTid here made a pid-1 parent's thread Worker * REUSE pid 1's task_struct — the thread's SYS_exit then ran * do_exit on the PROCESS's task (observed: "session leader pid=1 * exit" while pid 1 was still running, and pthread_join wedged). * A vmlinux-backed DYNAMIC thread task must be its OWN * (thread-marked, #85) child task: sentinel 0. Static mains (and * the no-vmlinux legacy path) keep the historical "threads share * their parent's pid" routing value byte-for-byte — the hw85 * containment gate pins that world (the pid-1 REUSE defect for a * hypothetical pid-1 STATIC threaded main remains the pre-existing * historical behavior, unexercised by any staged static image). */ pid: opts.vmlinuxModule !== void 0 && (dynamicMain || rtThread) ? 0 : req.parentTid, tid: req.tid, /* JS routing tid (the kernel's clone-counter tid musl sees) */ /* PLAN-THREADS §4 step 5: a user-runtime thread. Its Worker attaches * a runtime block of its own (__hwjs_thread_attach) and binds it * before driving the thread. */ rtThread, /* K11-C1.a: ppid forwarded to vmlinux's per-process task_struct * allocator. Thread-mode Workers inherit their parent's ppid; * the K11-C1.a allocator treats ppid as informational (parent * pointer goes to init_task in the flat hierarchy until the * fork path lands). */ ppid: vfork ? groupPid : req.parentTid, wasmBytes: parent.wasmBytes, ...placementImageKey(parent.wasmBytes), memory: parent.userMemory, /* SHARED — defining property of WASM_SPAWN_THREAD */ memoryId: threadMemoryId, ctrl: ctrlSab, ...userDirtyCellInit(parent.userMemory), ...placementCellForThread(parent.userMemory, !!vfork), argRegionOffset: req.argRegionOffset, stackPointerOffset: req.stackPointerOffset, tlsPointerOffset: req.tlsPointerOffset, /* Thread placement (spike S6 §3a): the parent's placement record — the thread Worker's * preamble replays rt (#0) → libc.so (#1) → dlopen'd .so's at the * recorded bases against the LIVE shared memory (no ctors, no data * relocs, no window zero/carve). */ ...threadDlopenFork ? { dlopenFork: threadDlopenFork } : {}, /* Step 7: seed the thread Worker's kernel-routed low-fd cache from * the cloning Worker's (pre-push rider) so the thread lane's stdio * writes reach the pts, not host-RPC. */ ...Array.isArray(envelope?.lowFdRoutes) && envelope.lowFdRoutes.length ? { lowFdRoutes: envelope.lowFdRoutes } : {}, /* Step 7 / AO-1: a lane thread's kernel task must see the PROCESS's * fds — CLONE_FILES, which POSIX requires of every thread. * * inheritFiles=2 (WASM32_FILES_SHARE, task_alloc.c) takes a * REFERENCE on the parent's files_struct. It replaces the Step 7 * stopgap, inheritFiles=true (=1, dup_fd(parent->files)), which was * a SNAPSHOT: it fixed the original symptom (an EMPTY thread table, * where a lane thread's printf died -EBADF and silently lost its * stdout) but only for descriptors already open at spawn. After * that the tables diverge permanently — an fd opened by a thread * does not exist in the process, a close() in one thread is * invisible in the other, and each private table hands out its own * lowest free slot, so the same integer names different objects in * different threads. That last one is a remote fd-corruption * primitive for correct POSIX code that passes an int between * threads; guest-root T9 was it, with the machine's root * filesystem as the victim (a prefetch thread's socket and the * mount thread's /dev/fuse both on fd 9, the HTTP pool's staleness * eviction closing the FUSE session). ao/ptfd.c is the contract as * five executable assertions; ao/run-ptfd.mjs is its gate. * * HWJS_THREAD_FILES_DUP=1 restores the pre-AO-1 snapshot (=1) at * runtime with no rebuild: the RED arm for ptfd, and the one-knob * back-out if sharing ever needs to be disarmed in the field. * * THAT KNOB NOW GIVES UP MORE THAN THE FD TABLE, and it is said here * because this is the line that decides it. inheritFiles === 2 is the * kernel's CLONE_THREAD discriminator as well as its CLONE_FILES one * (arch/wasm32/kernel/task_alloc.c: arm 2 carries CLONE_FILES, * CLONE_SIGHAND and CLONE_THREAD, which is what a pthread clone carries), * so a spawn that sends 1 gets a task that is its OWN thread group: * getpid() in it answers its own pid where Linux answers the process's, * and a cross-thread tgkill/pthread_kill naming the process answers * -ESRCH. That is not silent — the kernel's * __wasm32_task_set_thread_worker cross-checks the host's OTHER * statement of thread-ness (init.mode === 'thread') against the group it * actually built, and prints an attributed KERN_ERR line per task when * the two disagree. The knob is still a knob; it is now a knob that * announces its full cost. * * Laned threads only; the legacy lane-0 shape is pinned. */ ...vfork ? { inheritFiles: true, fdActions: [], vforkChild: true, ...vfork.mainTlsBase ? { mainTlsBase: vfork.mainTlsBase } : {} } : rtThread ? { inheritFiles: threadFilesShareDisabled() ? true : 2, fdActions: [] } : {}, ...signalPendingOffset !== void 0 ? { signalPendingOffset } : {} }; if (poolResident) { const ACK_MS = 250; const starvedLanes = /* @__PURE__ */ new Set(); let placeCycles = 0; const THREAD_PIN_STARVE_ATTEMPTS = 8; let pinStarveAttempts = 0; for (; ; ) { const claimSab = new SharedArrayBuffer(4); const claim = new Int32Array(claimSab); pool.laneInboxPost?.(worker); postToWorker(worker, { kind: "add-task", routeKey, spec: { routeKey, claim: claimSab, ...perThreadInit } }); const deadline = Date.now() + ACK_MS; while (Atomics.load(claim, 0) === 0 && Date.now() < deadline) { const w = Atomics.waitAsync(claim, 0, 0, Math.max(1, deadline - Date.now())); if (w.async) { try { await w.value; } catch { } } } if (Atomics.load(claim, 0) === 2) { pool.markLaneLive(cpuId); break; } if (Atomics.compareExchange(claim, 0, 0, 1) === 2) { pool.markLaneLive(cpuId); break; } pool.markLaneSuspect(cpuId); starvedLanes.add(cpuId); const from = cpuId; if (poolWorkerRec) { poolWorkerRec.residentCount = Math.max(0, poolWorkerRec.residentCount - 1); if (laneOwner) pool.laneRelease(poolWorkerRec.cpuId, laneOwner); pool.threadImages?.threadLeft(threadMemoryId, poolWorkerRec.cpuId); } if (pinnedCpuId !== void 0 && ++pinStarveAttempts > THREAD_PIN_STARVE_ATTEMPTS) { pool.poolHandlers.delete(routeKey); pool.syscallSyncDoors.delete(routeKey); pool.noteResidentDelta(-1); poolWorkerRec = null; opts.onUserError?.( req.tid, `hwjs-thread-placement-pin: UNSATISFIABLE thread=${threadOrdinal} cpu=${pinnedCpuId} tid=${req.tid} group=${groupPid} \u2014 the pinned lane did not claim the add-task in ${THREAD_PIN_STARVE_ATTEMPTS} attempts of ${ACK_MS}ms` + (callerCpuId === pinnedCpuId ? ` (expected: cpu=${pinnedCpuId} is the CALLING task's own lane, which it pins in a synchronous kernel ring wait for the whole clone(2) \u2014 this is the deadlock the caller-lane exclusion normally prevents, and the pin deliberately overrode it)` : ` (that lane's resident is spinning without yielding)`) + `. Refusing the clone with -EAGAIN rather than re-placing on another cpu: a migrated pin would report a co-residency the run never had. Unset HWJS_THREAD_PLACEMENT_PIN or pin another cpu.` ); opts.signalRegistry?.unregister(req.tid); cloneCleartidMap.delete(req.tid); dropThreadRegistrations(); freeSignalPendingRegion(parent.userMemory, signalPendingOffset); signalPendingOffset = void 0; return EAGAIN; } let next; try { const exclude = new Set(starvedLanes); for (const c of bannedLanes()) exclude.add(c); next = await pool.getPoolWorker(callerCpuId, exclude, pinnedCpuId); } catch (e) { pool.poolHandlers.delete(routeKey); pool.syscallSyncDoors.delete(routeKey); pool.noteResidentDelta(-1); poolWorkerRec = null; opts.onDmesg?.( 4, `hwjs#3: thread add-task tid=${req.tid} routeKey=${routeKey} re-placement aborted (${e.message}) \u2014 refusing the clone with -EAGAIN `, req.tid ); opts.signalRegistry?.unregister(req.tid); cloneCleartidMap.delete(req.tid); dropThreadRegistrations(); freeSignalPendingRegion(parent.userMemory, signalPendingOffset); signalPendingOffset = void 0; return EAGAIN; } if (pinnedCpuId === void 0 && starvedLanes.has(next.cpuId)) { starvedLanes.clear(); placeCycles++; opts.onDmesg?.( 3, `hwjs#3: thread add-task tid=${req.tid} routeKey=${routeKey} found EVERY pool lane starved (cycle ${placeCycles}) \u2014 all residents are spinning without yielding; continuing to probe lanes `, req.tid ); } poolWorkerRec = next; cpuId = poolWorkerRec.cpuId; poolWorkerRec.residentCount++; pool.laneOccupy(cpuId, laneOwner); pool.threadImages?.threadPlaced(threadMemoryId, cpuId); worker = poolWorkerRec.worker; opts.onDmesg?.( 4, `hwjs#3: thread add-task tid=${req.tid} routeKey=${routeKey} claim timed out on starved pool lane cpu=${from}; re-placing on cpu=${cpuId} `, req.tid ); } } else { await adoptPreemptTimer(opts, worker); postToWorker(worker, { kind: "init", /* The raw SAB only for an embedder that supplies no * `WebAssembly.Memory` — see the createPoolWorker init for why posting * both is a duplicate alias AND a stale-buffer hazard. */ ...opts.kernelMemoryWasm === void 0 ? { kernelMemory: opts.kernelMemory } : {}, /* Thread placement (spike S6 §3a): the machine-wide shared-lib store snapshot (the * dedicated-Worker init precedent) — libc.so bytes resolve from here * by digest, NEVER from the placement record. A pool Worker already * has the store (cpu-worker init + the 'shared-lib' broadcast). */ ...(() => { if (testNoSharedLibs || !shl) return {}; const l = shl.list(); return l.length > 0 ? { sharedLibs: l } : {}; })(), /* K11-B2a: per-Worker vmlinux for thread-mode spawns too. */ ...opts.vmlinuxModule !== void 0 ? { vmlinuxModule: opts.vmlinuxModule } : {}, ...opts.hwjsRtModule !== void 0 ? { hwjsRtModule: opts.hwjsRtModule, hwjsRtBytes: opts.hwjsRtBytes, hwjsRtProvenance: opts.hwjsRtProvenance } : {}, ...opts.kernelMemoryWasm !== void 0 ? { kernelMemoryWasm: opts.kernelMemoryWasm } : {}, ...opts.__kernelLaneLocks !== void 0 ? { kernelLaneLocks: opts.__kernelLaneLocks } : {}, ...opts.__fileMapGen !== void 0 ? { fileMapGen: opts.__fileMapGen } : {}, /* Cooperative pause word for thread-mode Workers too. */ ...opts.pauseBuffer !== void 0 ? { pauseBuffer: opts.pauseBuffer } : {}, /* K11-B2b: this DEDICATED thread Worker's own cpu_id. A pool * resident instead inherits its Worker's id (addTask supplies it). */ cpuId, ...perThreadInit }); } if (!dynamicMain && !rtThread) return 0; const ADOPTION_TIMEOUT_MS = 3e4; const gateResult = await Promise.race([ adoptionGate, new Promise((r) => setTimeout(() => r("timeout"), ADOPTION_TIMEOUT_MS)) ]); if (gateResult === "adopted") return vfork ? await vforkGate : 0; const failureErrno = EAGAIN; if (!exitFired) { exitFired = true; cloneCleartidMap.delete(req.tid); const strandedKernelPid = threadKernelPid; opts.signalRegistry?.unregister(req.tid); dropThreadRegistrations(); releaseThreadCpuId(); if (gateResult === "timeout") { adoptionTimeoutLeakedKernelTasks += 1; let laneDump = ""; try { const lk = opts.__kernelLaneLocks; if (lk) { const i32 = new Int32Array(lk); const parts = []; for (let l = 1; l < Math.min(32, i32.length); l++) { const held = Atomics.load(i32, l) | 0; if (held !== 0) { const owner = 32 + l < i32.length ? Atomics.load(i32, 32 + l) | 0 : 0; parts.push(`${l}:held(holder=${owner})`); } } laneDump = ` LANE-STATE cpu=${cpuId} held=[${parts.join(" ")}]`; } } catch { } opts.onUserError?.( req.tid, `hwjs-libc: thread Worker tid=${req.tid}${laneDump} did not adopt its chain within ${ADOPTION_TIMEOUT_MS}ms \u2014 refusing the clone with -EAGAIN and tearing the Worker down (never-silent). The wedged Worker's kernel task${strandedKernelPid > 0 ? ` (pid ${strandedKernelPid})` : ""} is stranded LIVE in the shared pid hash \u2014 it cannot be reaped from the host (the Worker holds the only current-bound instance and is unresponsive by hypothesis). Leaked live kernel tasks via this path so far: ${adoptionTimeoutLeakedKernelTasks} (bounded by Worker wedges; the deterministic thread-refused path reaps).` + (poolResident ? ` RESIDENCY NOTE: this task is a POOL RESIDENT, so \u2014 unlike the dedicated-Worker path \u2014 the host CANNOT terminate its realm without killing every co-resident task on cpu ${cpuId}. It is de-routed and its thread group is SIGKILLed instead, so a task whose pthread stack musl has already reclaimed cannot keep running over the live address space.` : "") ); if (poolResident) { threadContain?.killGroup( groupPid, req.tid, 9, `adoption gate TIMED OUT for a POOL RESIDENT \u2014 the host cannot terminate a shared CPU Worker, so the group is ended instead` ); } } await releaseThreadWorker(); reclaimThreadLane(`adoption gate ${gateResult}`); freeSignalPendingRegion(parent.userMemory, signalPendingOffset); signalPendingOffset = void 0; } return failureErrno; } function performCleartid(cloneCleartidMap, tid) { const rec = cloneCleartidMap.get(tid); if (!rec) return; cloneCleartidMap.delete(tid); const { ctid, userMemory } = rec; const i32 = new Int32Array(userMemory.buffer); const idx = ctid >>> 2; if (globalThis.process?.env?.HWJS_CLEARTID_TRACE) { const before = Atomics.load(i32, idx) | 0; if (before !== 0 && before !== (tid | 0)) { const w = globalThis.process?.stderr; w?.write(`[HWJS_CLEARTID_TRACE] SPURIOUS clear: tid=${tid} clears ctid=0x${ctid.toString(16)} holding tid=${before} (a DIFFERENT live holder) \u2014 double-clear race on __thread_list_lock `); } else if (before === 0) { const w = globalThis.process?.stderr; w?.write(`[HWJS_CLEARTID_TRACE] redundant clear: tid=${tid} ctid=0x${ctid.toString(16)} already 0 (kernel mm_release cleared first) \u2014 benign this instant, but proves the double-clear `); } } Atomics.store(i32, idx, 0); Atomics.notify(i32, idx, 2147483647); } var C2 = { STATE: 0, NR: 1, A0: 2, A1: 3, A2: 4, A3: 5, A4: 6, A5: 7, RET_LO: 9, RET_HI: 10, PID: 12, TID: 13, /* worker.mjs C.LEADER_HOLD: the held leader's release word. */ LEADER_HOLD: 14, /* worker.mjs CTRL_I32_REAPED: the reaped task's mark. */ REAPED: 15 }; function markCtrlReaped(ctrl) { Atomics.store(ctrl, C2.REAPED, 1); Atomics.notify(ctrl, C2.STATE); } var REQUEST2 = 1; var RESPONSE2 = 2; var nextLegacyRoutingId = 2; function allocLegacyRoutingId() { return nextLegacyRoutingId++; } function writeToFd(opts, pid, fd, bytes) { if (fd !== 1 && fd !== 2) return -9; if (globalThis.process?.env?.D1_TRACE_FD && (fd === 1 || fd === 2)) { try { const peek = decodeMaybeShared(bytes.subarray(0, 48)).replace(/\n/g, "\\n"); globalThis.process.stderr.write( `[D1_FD-MAIN pid=${pid}] write(fd=${fd}, ${bytes.byteLength}B "${peek}") -> onUserOutput (SAB-RPC js-direct leak surface) ` ); } catch (_e) { } } opts.onUserOutput?.(fd, bytes, pid); return bytes.byteLength; } async function dispatchSyscall(ctrl, userMem, pid, opts, threadCtx) { try { await dispatchSyscallBody(ctrl, userMem, pid, opts, threadCtx); } catch (e) { const nr = ctrl[C2.NR] | 0; if (Atomics.load(ctrl, C2.STATE) !== RESPONSE2) { Atomics.store(ctrl, C2.RET_LO, EIO); Atomics.store(ctrl, C2.RET_HI, -1); Atomics.store(ctrl, C2.STATE, RESPONSE2); Atomics.notify(ctrl, C2.STATE); } opts.onUserError?.( pid, `hwjs port BUG: the host syscall dispatcher THREW for nr=${nr} (pid/tid ${pid}) \u2014 ${e instanceof Error ? e.message : String(e)}. The caller was answered -EIO (${EIO}) rather than left parked on a reply that would never arrive; the errno is this belt's, not the kernel's, and the defect above is the thing to fix.` ); } } async function dispatchSyscallBody(ctrl, userMem, pid, opts, threadCtx) { const nr = ctrl[C2.NR] | 0; const a0 = ctrl[C2.A0] | 0; const a1 = ctrl[C2.A1] | 0; const a2 = ctrl[C2.A2] | 0; const a3 = ctrl[C2.A3] | 0; const a4 = ctrl[C2.A4] | 0; const a5 = ctrl[C2.A5] | 0; let ret = 0; switch (nr) { case __NR_write: { const fd = a0; const buf = a1 >>> 0; const len = a2 >>> 0; const view = new Uint8Array(userMem.buffer, buf, len); const bytes = new Uint8Array(len); bytes.set(view); const wr = writeToFd(opts, pid, fd, bytes); ret = wr; break; } case __NR_writev: { const fd = a0; const iov = a1 >>> 0; const iovcnt = a2 >>> 0; const u32 = new Uint32Array(userMem.buffer); let total = 0; for (let i = 0; i < iovcnt; i++) { const baseIdx = (iov >>> 2) + i * 2; const ptr = u32[baseIdx + 0] >>> 0; const ln = u32[baseIdx + 1] >>> 0; if (ln === 0) continue; const view = new Uint8Array(userMem.buffer, ptr, ln); const bytes = new Uint8Array(ln); bytes.set(view); const wr = writeToFd(opts, pid, fd, bytes); if (wr < 0) { ret = total > 0 ? total : wr; total = -1; break; } total += wr; } if (total >= 0) ret = total; break; } case __NR_ioctl: { ret = -25; break; } case __NR_set_tid_address: { ret = 1; break; } case __NR_read: { const fd = a0; const buf = a1 >>> 0; const len = a2 >>> 0; if (fd === 0) { if (opts.stdinChannel) { const r = await opts.stdinChannel.read(pid, len); const n = r.bytes.byteLength; if (n > 0) { new Uint8Array(userMem.buffer, buf, n).set(r.bytes); } ret = n; } else { ret = 0; } break; } ret = -9; break; } case __NR_nanosleep: case __NR_clock_nanosleep: { const isClock = nr === __NR_clock_nanosleep; const flags = isClock ? a1 : 0; const reqPtr = (isClock ? a2 : a0) >>> 0; const remPtr = (isClock ? a3 : a1) >>> 0; if (!reqPtr) { ret = -14; break; } const dv = new DataView(userMem.buffer); const reqSec = Number(dv.getBigInt64(reqPtr, true)); const reqNsec = dv.getUint32(reqPtr + 8, true); let ms = reqSec * 1e3 + reqNsec / 1e6; if (flags & 1) ms -= Date.now(); const deadline = Date.now() + ms; const rec = opts.signalRegistry?.lookup(pid); const sigPending = () => { if (!rec) return false; const i32 = new Int32Array(rec.userMemory.buffer); const idx = rec.signalPendingOffset >> 2; return (Atomics.load(i32, idx) | Atomics.load(i32, idx + 1)) !== 0; }; ret = 0; while (Date.now() < deadline) { if (sigPending()) { if (remPtr && !(flags & 1)) { const remMs = Math.max(0, deadline - Date.now()); dv.setBigInt64(remPtr, BigInt(Math.floor(remMs / 1e3)), true); dv.setUint32(remPtr + 8, Math.floor(remMs % 1e3 * 1e6), true); } ret = -4; break; } const chunk = Math.min(100, deadline - Date.now()); if (chunk > 0) await new Promise((r) => setTimeout(r, chunk)); } break; } case __NR_exit: case __NR_exit_group: { ret = 0; break; } case __NR_mmap: { const len = alignUp2(a1 >>> 0, WASM_PAGE_SIZE); if (len === 0) { ret = -22; break; } if ((a4 | 0) !== -1 && ((a3 | 0) & 32) === 0 && !globalThis.process?.env?.HWJS_RED_MMAP_FILE_UNPOPULATED) { opts.onUnknownSyscall?.(pid, nr, [a0, a1, a2, a3, a4, a5]); ret = -19; break; } { const reused = mmapFreeListTake(userMem, len); if (reused >= 0) { opts.ram.noteUserMemoryReused(userMem, len); zeroMemory(userMem, reused, len); if (globalThis.process?.env?.D1_TRACE_MEM) { globalThis.process.stderr.write( `[D1_TRACE_MEM pid=${pid}] zero mmap-reuse ${len} B [D1_TRACE_MEM pid=${pid}] mmap REUSED 0x${reused.toString(16)}+0x${len.toString(16)} from the free list ` ); } ret = reused; break; } } let bump = getUserBump(userMem); bump = alignUp2(bump, WASM_PAGE_SIZE); let memBytes = userMem.buffer.byteLength; if (bump + len > memBytes) { if (HWJS_NO_USERMEM_GROW) { opts.onUnknownSyscall?.(pid, nr, [a0, a1, a2, a3, a4, a5]); ret = ENOMEM2; break; } const deficitPages = Math.ceil((bump + len - memBytes) / 65536); try { userMem.grow(deficitPages); if (globalThis.process?.env?.D1_TRACE_MEM) { globalThis.process.stderr.write( `[D1_TRACE_MEM pid=${pid}] mmap GREW user_memory +${deficitPages} pages (0x${memBytes.toString(16)} -> 0x${userMem.buffer.byteLength.toString(16)}) for len=0x${len.toString(16)} at bump=0x${bump.toString(16)} ` ); } } catch (_e) { opts.onUserError?.( pid, userMemoryGrowRefusal(opts.ram, userMem, pid, `mmap ${len} B`, bump + len) ); opts.onUnknownSyscall?.(pid, nr, [a0, a1, a2, a3, a4, a5]); ret = ENOMEM2; break; } memBytes = userMem.buffer.byteLength; if (bump + len > memBytes) { opts.onUserError?.( pid, `hwjs port BUG: mmap grow of ${deficitPages} pages for pid ${pid} reported SUCCESS yet user_memory is still ${memBytes} B, short of the ${bump + len} B needed. Refusing rather than returning an out-of-bounds address. (This one really is an internal defect, not a memory ceiling.)` ); opts.onUnknownSyscall?.(pid, nr, [a0, a1, a2, a3, a4, a5]); ret = ENOMEM2; break; } } const addr = bump; setUserBump(userMem, bump + len); zeroMemory(userMem, addr, len); if (globalThis.process?.env?.D1_TRACE_MEM) { globalThis.process.stderr.write( `[D1_TRACE_MEM pid=${pid}] zero mmap-bump ${len} B ` ); } ret = addr; break; } case __NR_munmap: { const addr = a0 >>> 0; const rawLen = a1 >>> 0; if ((addr & WASM_PAGE_SIZE - 1) !== 0 || rawLen === 0) { ret = -22; break; } const len = alignUp2(rawLen, WASM_PAGE_SIZE); const munmapPart = userMemoryPartitions.get(userMem); const floor = munmapPart ? munmapPart.mmapFloor + (munmapPart.rtWindowSize ?? 0) : 0; const bumpTop = getUserBump(userMem); const s = Math.max(addr, floor); const e = Math.min(addr + len, bumpTop); const newlyFree = mmapFreeListInsert(userMem, s, e); opts.ram.noteUserMemoryFreed(userMem, newlyFree); if (globalThis.process?.env?.D1_TRACE_MEM) { globalThis.process.stderr.write( `[D1_TRACE_MEM pid=${pid}] munmap 0x${addr.toString(16)}+0x${len.toString(16)} -> freed [0x${s.toString(16)},0x${e.toString(16)}) net +${newlyFree} B unreclaimable-but-free ` ); } ret = 0; break; } case __NR_mprotect: { const mpStart = a0 >>> 0; const mpProt = a2 | 0; const PROT_KNOWN = 1 | 2 | 4 | 8 | 16777216 | 33554432; if (mpStart & 4095) { ret = -22; break; } if (mpProt & ~PROT_KNOWN) { ret = -22; break; } if (mpProt & 16777216 && mpProt & 33554432) { ret = -22; break; } ret = 0; break; } case __NR_brk: { const part = userMemoryPartitions.get(userMem); const reqBrk = a0 >>> 0; if (!part || !globalThis.process?.env?.D1_BRK_ENABLE) { ret = 0; break; } if (reqBrk === 0) { ret = part.brk; break; } if (reqBrk < part.heapBase) { ret = part.brk; break; } if (reqBrk > part.mmapFloor) { opts.onUnknownSyscall?.(pid, nr, [a0, a1, a2, a3, a4, a5]); ret = ENOMEM2; break; } if (reqBrk < part.brk) opts.ram.noteUserMemoryFreed(userMem, part.brk - reqBrk); part.brk = reqBrk; if (reqBrk > part.brkHighWater) part.brkHighWater = reqBrk; ret = reqBrk; break; } case __NR_madvise: { ret = 0; break; } /* * nr 14 (rt_sigprocmask) USED TO BE ANSWERED HERE, with `ret = 0` and * nothing recorded. It is deleted, deliberately, and this note is what * replaces it — because the case was not a stub, it was a LIE, and the * shape is worth naming so it is not written again. * * The comment said "signals are not yet implemented ... we just accept * it and return 0 success without recording state". Every caller was * therefore told its mask had been installed when nothing had. * current->blocked stayed empty for the life of every process, so the * kernel generated, queued and INTERRUPTED for signals the guest had * blocked. Measured on both libcs: a raw clock_nanosleep(2s) under a * blocked SIGALRM came back at ~700ms — as EINTR on musl, as the * kernel-internal errno 516 on glibc — where Linux returns 0 after * 2000ms. [14] had been wired in the kernel's sys_call_table the whole * time; only the host's per-nr allowlist kept the call from reaching it. * * A stub that returns an error is a stub. A stub that returns SUCCESS * for something it did not do is unfalsifiable from the guest side — * there is no observation that distinguishes it from a working * implementation until something downstream behaves impossibly. If a * syscall must be refused here, refuse it: the `default:` arm below * answers -ENOSYS and calls onUnknownSyscall, which is loud and true. * * nr 14 now routes to the kernel (worker.mjs: the kernel's table is the * routing rule), so this responder should never see it. If it does — * a Worker with no per-process task, an older vmlinux — it falls to * `default:` and says so, instead of quietly agreeing. */ case __NR_set_robust_list: { ret = 0; break; } case __NR_clock_gettime: { const tsPtr = a1 >>> 0; if (tsPtr === 0 || (tsPtr & 3) !== 0) { ret = -22; break; } const now = Date.now(); const sec = Math.floor(now / 1e3); const nsec = Math.round((now - sec * 1e3) * 1e6); const u32 = new Uint32Array(userMem.buffer); const idx = tsPtr >>> 2; u32[idx] = sec >>> 0; u32[idx + 1] = Math.floor(sec / 4294967296) >>> 0; u32[idx + 2] = nsec >>> 0; u32[idx + 3] = 0; ret = 0; break; } case __NR_clone: { const flags = a0 >>> 0; const stack = a1 >>> 0; const ptid = a2 >>> 0; const tls = a3 >>> 0; const ctid = a4 >>> 0; const fnArgBlockPtr = a5 >>> 0; if (!(flags & CLONE_VM)) { ret = ENOSYS; break; } const cloneLaxRed = typeof process !== "undefined" && !!process.env?.HWJS_RED_CLONE_LAX; if (!cloneLaxRed && (!(flags & CLONE_THREAD) || flags & CLONE_VFORK)) { opts.onDmesg?.( 4, `hwjs-spawn: SYS_clone pid=${pid} flags=0x${flags.toString(16)} REFUSED (-ENOSYS): CLONE_VM without CLONE_THREAD` + (flags & CLONE_VFORK ? " (+CLONE_VFORK \u2014 vfork/posix_spawn shape)" : "") + " \u2014 process-semantics clone cannot be serviced as a thread; use fork()+exec (musl _Fork park protocol)", pid ); ret = ENOSYS; break; } if (!threadCtx) { ret = ENOSYS; break; } if (fnArgBlockPtr === 0) { ret = -22; break; } const u32 = new Uint32Array(userMem.buffer); const fn2 = u32[fnArgBlockPtr >>> 2] >>> 0; const arg = u32[(fnArgBlockPtr >>> 2) + 1] >>> 0; const newTid = allocLegacyRoutingId(); if ((typeof process === "undefined" ? void 0 : process)?.env?.HARDWAREJS_DEBUG_K7_U4F) { process.stderr.write( `[K7-U4f SYS_clone] pid=${pid} newTid=${newTid} flags=0x${flags.toString(16)} stack=0x${stack.toString(16)} ptid=0x${ptid.toString(16)} tls=0x${tls.toString(16)} ctid=0x${ctid.toString(16)} fn_arg_block=0x${fnArgBlockPtr.toString(16)} (fn=0x${fn2.toString(16)} arg=0x${arg.toString(16)}) ` ); } const argRegionLen = alignUp2(WASM_THREAD_ARG_REGION_SIZE, WASM_PAGE_SIZE); let bump = getUserBump(userMem); bump = alignUp2(bump, WASM_PAGE_SIZE); const memBytes = userMem.buffer.byteLength; if (bump + argRegionLen > memBytes) { ret = ENOMEM2; break; } const argRegionOffset = bump; setUserBump(userMem, bump + argRegionLen); new Uint8Array(userMem.buffer, argRegionOffset, argRegionLen).fill(0); const dv = new DataView(userMem.buffer, argRegionOffset, WASM_THREAD_ARG_REGION_SIZE); dv.setUint32(0, WASM_THREAD_ARG_MAGIC_LO, true); dv.setUint32(4, WASM_THREAD_ARG_MAGIC_HI, true); dv.setUint32(8, WASM_THREAD_ARG_VERSION, true); dv.setUint32(12, flags, true); dv.setUint32(16, fn2, true); dv.setUint32(20, 0, true); dv.setUint32(24, arg, true); dv.setUint32(28, 0, true); dv.setUint32(32, pid, true); dv.setUint32(36, 0, true); dv.setUint32(40, newTid, true); dv.setUint32(44, 0, true); dv.setUint32(48, tls, true); dv.setUint32(52, 0, true); dv.setUint32(56, stack, true); dv.setUint32(60, 0, true); if (ptid !== 0 && (ptid & 3) === 0 && ptid + 4 <= memBytes) { u32[ptid >>> 2] = newTid >>> 0; } if (flags & CLONE_CHILD_CLEARTID && ctid !== 0 && (ctid & 3) === 0 && ctid + 4 <= memBytes) { threadCtx.cloneCleartidMap.set(newTid, { ctid, userMemory: userMem }); } const cloneReq = { mode: WASM_SPAWN_THREAD, flags: 0, tid: newTid, parentTid: pid, execImageOffset: 0, execImageSize: 0, execImageNsegs: 0, argRegionOffset, stackPointerOffset: stack, tlsPointerOffset: tls, libcImageOffset: 0, libcImageSize: 0, libcImageNsegs: 0, libcDigestOffset: 0 }; const r = await threadCtx.spawnThread(cloneReq); if (r < 0) { ret = r; break; } ret = newTid; break; } case __NR_wasm_spawn_image: { if (!opts.childImageRegistry) { ret = ENOSYS; break; } const pathPtr = a0 >>> 0; if (pathPtr === 0) { ret = -22; break; } const memU8 = new Uint8Array(userMem.buffer); const pathMaxLen = 4096; let pathLen = 0; const memBytes = userMem.buffer.byteLength; while (pathPtr + pathLen < memBytes && pathLen < pathMaxLen && memU8[pathPtr + pathLen] !== 0) { pathLen++; } if (pathLen === pathMaxLen) { ret = -36; break; } const pathBytes = new Uint8Array(pathLen); pathBytes.set(memU8.subarray(pathPtr, pathPtr + pathLen)); const path = new TextDecoder("utf-8").decode(pathBytes); const childBytes = opts.childImageRegistry.lookup(path); if (!childBytes) { ret = -2; break; } if (!threadCtx) { ret = ENOSYS; break; } const childSentinel = opts.vmlinuxModule !== void 0 ? 0 : allocLegacyRoutingId(); const spawnRc = await spawnForkWorker( childBytes, childSentinel, pid, threadCtx.parents, threadCtx.cloneCleartidMap, opts ); ret = spawnRc; break; } case __NR_wasm_spawn_image_actions: { if (!opts.childImageRegistry) { ret = ENOSYS; break; } const pathPtr = a0 >>> 0; const actionsPtr = a1 >>> 0; const nActions = a2 >>> 0; if (pathPtr === 0) { ret = -22; break; } const memU8 = new Uint8Array(userMem.buffer); const pathMaxLen = 4096; let pathLen = 0; const memBytes = userMem.buffer.byteLength; while (pathPtr + pathLen < memBytes && pathLen < pathMaxLen && memU8[pathPtr + pathLen] !== 0) { pathLen++; } if (pathLen === pathMaxLen) { ret = -36; break; } const pathBytes = new Uint8Array(pathLen); pathBytes.set(memU8.subarray(pathPtr, pathPtr + pathLen)); const path = new TextDecoder("utf-8").decode(pathBytes); const childBytes = opts.childImageRegistry.lookup(path); if (!childBytes) { ret = -2; break; } if (!threadCtx) { ret = ENOSYS; break; } const fdActions = []; let actionErr = 0; if (nActions > 0) { if (actionsPtr === 0 || (actionsPtr & 3) !== 0 || actionsPtr + nActions * 12 > memBytes) { actionErr = -14; } else { const u32 = new Uint32Array(userMem.buffer); for (let i = 0; i < nActions; i++) { const base = (actionsPtr >>> 2) + i * 3; const op = u32[base + 0] | 0; const f1 = u32[base + 1] | 0; const f2 = u32[base + 2] | 0; if (op !== WASM_SPAWN_ACTION_DUP2 && op !== WASM_SPAWN_ACTION_CLOSE) { actionErr = -22; break; } fdActions.push([op, f1, f2]); } } } if (actionErr < 0) { ret = actionErr; break; } const childSentinel = opts.vmlinuxModule !== void 0 ? 0 : allocLegacyRoutingId(); const spawnRc = await spawnForkWorker( childBytes, childSentinel, pid, /* ppid — the fork() fd-inheritance + pgrp parent */ threadCtx.parents, threadCtx.cloneCleartidMap, opts, { inheritFiles: true, fdActions } ); ret = spawnRc; break; } case __NR_getpid: { ret = pid; break; } case __NR_pause: { ret = ENOSYS; break; } default: { opts.onUnknownSyscall?.(pid, nr, [a0, a1, a2, a3, a4, a5]); ret = ENOSYS; break; } } if (globalThis.process?.env?.D1_TRACE_MEM && (nr === 9 || nr === 10 || nr === 11 || nr === 12)) { const part = userMemoryPartitions.get(userMem); const name2 = nr === 9 ? "mmap" : nr === 10 ? "mprotect" : nr === 11 ? "munmap" : "brk"; globalThis.process.stderr.write( `[D1_TRACE_MEM pid=${pid}] ${name2}(a0=0x${(a0 >>> 0).toString(16)},len=0x${(a1 >>> 0).toString(16)}) -> 0x${(ret >>> 0).toString(16)} (ret=${ret}) [floor=0x${(part?.mmapFloor ?? 0).toString(16)} brk=0x${(part?.brk ?? 0).toString(16)}] ` ); } Atomics.store(ctrl, C2.RET_LO, ret | 0); Atomics.store(ctrl, C2.RET_HI, ret < 0 ? -1 : 0); Atomics.store(ctrl, C2.STATE, RESPONSE2); Atomics.notify(ctrl, C2.STATE); } function detectPlatform() { const g = globalThis; if (typeof g.process !== "undefined" && g.process?.versions?.node) return "node"; return "browser"; } var NODE_WORKER_HEAP_DEFAULT_MB = 4096; var NODE_WORKER_HEAP_MAX_MB = 16384; function nodeWorkerResourceLimits(availableBytes) { const mb = Math.min(NODE_WORKER_HEAP_MAX_MB, Math.floor(availableBytes / 2 / (1024 * 1024))); return mb > NODE_WORKER_HEAP_DEFAULT_MB ? { maxOldGenerationSizeMb: mb } : void 0; } async function createWorker(entry, platform, origin = "unknown", name2 = origin) { const w = platform === "node" ? new (await Promise.resolve().then(() => (init_worker_threads_stub(), worker_threads_stub_exports))).Worker(entry, { type: "module", name: name2, resourceLimits: nodeWorkerResourceLimits(globalThis.process.availableMemory()) }) : new globalThis.Worker(entry, { type: "module", name: name2 }); noteWorkerRealmCreated(w, origin); return w; } async function adoptPreemptTimer(opts, worker) { const init = await opts.__preemptRealmInit?.(); if (init) postToWorker(worker, { kind: "preempt-adopt", ...init.fields }, init.transfer); } function postToWorker(worker, msg, transfer) { if (transfer !== void 0) worker.postMessage(msg, transfer); else worker.postMessage(msg); } function onMessage(worker, cb) { if (typeof worker.on === "function") worker.on("message", cb); else worker.onmessage = (ev) => cb(ev.data); } function onError(worker, cb) { if (typeof worker.on === "function") { worker.on("error", (e) => cb(describeWorkerError(e))); } else { worker.onerror = (ev) => cb(describeWorkerError(ev)); } } function describeWorkerError(ev) { if (ev instanceof Error) { return ev.stack ? `${ev.message} ${ev.stack}` : ev.message; } if (ev && typeof ev === "object") { const e = ev; const parts = []; if (e.message) parts.push(String(e.message)); if (e.filename) { parts.push(`at ${String(e.filename)}:${e.lineno ?? "?"}:${e.colno ?? "?"}`); } if (e.error instanceof Error) { parts.push(e.error.stack ? `${e.error.message} ${e.error.stack}` : e.error.message); } else if (e.error != null) { parts.push(String(e.error)); } if (parts.length > 0) return parts.join(" | "); return `Worker emitted a content-free "error" event (no message/error/filename). In the browser this is the signature of a module Worker that failed to LOAD or PARSE. Which cause to look at depends on where the entry came from. A blob: URL has no directory, so ANY surviving relative import in the bundle (e.g. ./dynLoader.mjs) resolves to nothing \u2014 the entry must be bundled self-contained before it is turned into a Blob. A served URL fails the same way when a sibling the entry imports is not served beside it. Otherwise: a syntax error, or a cross-origin entry the embedder's COEP will not admit.`; } return ev === void 0 ? "" : String(ev); } async function terminateWorker(worker) { noteWorkerRealmTerminated(worker); try { if (typeof worker.terminate === "function") { const t = worker.terminate(); if (t && typeof t.then === "function") await t; } } catch { } } // ../../linux-in-the-browser/hardwarejs/src/hwjsRt.ts var PROV_RE = /^RT-PROVENANCE commit=([0-9a-f]{40}) dirty=([01]) src=([0-9a-f]{64})(?: srckey=([0-9a-f]{64}))?$/; function parseProvenance(bytes, from) { const raw = new TextDecoder().decode(bytes).trim(); const m = PROV_RE.exec(raw); if (!m) { throw new Error( `hwjs-rt: ${from} carries an unparseable RT-PROVENANCE ("${raw.slice(0, 160)}") \u2014 refusing the kernel-provided runtime` ); } return { commit: m[1], dirty: m[2] === "1", srcSha256: m[3], srcKey: m[4], raw }; } async function extractHwjsRt(vmlinuxModule) { const so = WebAssembly.Module.customSections(vmlinuxModule, "hwjs.rt.so"); const prov = WebAssembly.Module.customSections(vmlinuxModule, "hwjs.rt.provenance"); if (so.length === 0 && prov.length === 0) return void 0; if (so.length !== 1 || prov.length !== 1) { throw new Error( `hwjs-rt: vmlinux carries ${so.length}x hwjs.rt.so / ${prov.length}x hwjs.rt.provenance (want exactly 1 of each, or neither) \u2014 a half-embedded runtime is a build defect, refusing` ); } const provenance = parseProvenance(prov[0], "vmlinux"); if (provenance.dirty) { throw new Error( `hwjs-rt: the kernel-provided runtime attests a DIRTY tree (${provenance.raw}) \u2014 refusing (never-silent; rebuild from a clean linux tree)` ); } let module; try { module = await WebAssembly.compile(so[0]); } catch (e) { throw new Error( `hwjs-rt: embedded libhwjs-rt.so does not compile: ${e instanceof Error ? e.message : String(e)}` ); } for (const name2 of ["dylink.0", "hwjs.abi"]) { if (WebAssembly.Module.customSections(module, name2).length !== 1) { throw new Error( `hwjs-rt: embedded libhwjs-rt.so lacks a (single) ${name2} custom section \u2014 not a conformant dynamic module, refusing` ); } } const soProv = WebAssembly.Module.customSections(module, "hwjs.rt.provenance"); if (soProv.length !== 1) { throw new Error( `hwjs-rt: embedded libhwjs-rt.so carries ${soProv.length} internal hwjs.rt.provenance sections (want exactly 1), refusing` ); } const soProvParsed = parseProvenance(soProv[0], "libhwjs-rt.so"); if (soProvParsed.raw !== provenance.raw) { throw new Error( `hwjs-rt: provenance mismatch between vmlinux ("${provenance.raw}") and the .so's internal section ("${soProvParsed.raw}") \u2014 mix-and-match runtime, refusing` ); } return { module, provenance, byteLength: so[0].byteLength, bytes: new Uint8Array(so[0].slice(0)) }; } // ../../linux-in-the-browser/hardwarejs/src/signalRingConsumer.ts var SignalRingConsumer = class { kernelMemory; ringOffset; handler; onProcessed; onError; i32; dv; running = false; stopped = false; loopDone = null; /** * Last value of signal_notify_word the consumer observed. * Atomics.waitAsync compares the current value against this; if * it has already moved (producer raced past), waitAsync returns * "not-equal" immediately and we drain. */ lastSignalNotifyValue = 0; constructor(opts) { if ((opts.ringOffset & 3) !== 0) { throw new Error( `SignalRingConsumer: ringOffset 0x${opts.ringOffset.toString(16)} not 4-byte aligned` ); } this.kernelMemory = opts.kernelMemory; this.ringOffset = opts.ringOffset; this.handler = opts.handler; this.onProcessed = opts.onProcessed; this.onError = opts.onError; this.i32 = new Int32Array(this.kernelMemory); this.dv = new DataView(this.kernelMemory); } /** * Begin the consumer loop. Returns a promise that resolves when * the loop exits (after stop() or a fatal error). Idempotent — * calling start() twice is a no-op on the second call. */ start() { if (this.running || this.stopped) { return this.loopDone ?? Promise.resolve(); } this.running = true; this.lastSignalNotifyValue = Atomics.load( this.i32, this.signalNotifyIdx() ); this.loopDone = this.runLoop(); return this.loopDone; } /** * Request loop termination. Sets the stopped flag and notifies * the signal_notify_word so any pending Atomics.waitAsync wakes * immediately. Returns the promise the loop resolves on completion. */ async stop() { if (this.stopped) return; this.stopped = true; Atomics.notify(this.i32, this.signalNotifyIdx(), Infinity); await this.loopDone; } signalNotifyIdx() { return this.ringOffset + SIG_RING_OFF_SIGNAL_NOTIFY_WORD >>> 2; } headIdx() { return this.ringOffset + SIG_RING_OFF_HEAD >>> 2; } tailIdx() { return this.ringOffset + SIG_RING_OFF_TAIL >>> 2; } /** * Decode one slot. Read non-atomically — the kernel finishes * writing all fields before incrementing the notify word, and our * load of head happens AFTER an observed notify increment, so the * fields are stable by the time we read them. */ readSlot(slotIdx) { const base = signalRingSlotOffset(this.ringOffset, slotIdx); return { tid: this.dv.getUint32(base + SIG_REQ_OFF_TID, true), sig: this.dv.getUint32(base + SIG_REQ_OFF_SIG, true), senderPid: this.dv.getUint32(base + SIG_REQ_OFF_SENDER_PID, true) }; } async runLoop() { try { await this.drain(); while (!this.stopped) { const cur = Atomics.load(this.i32, this.signalNotifyIdx()); if (cur === this.lastSignalNotifyValue) { const r = Atomics.waitAsync( this.i32, this.signalNotifyIdx(), this.lastSignalNotifyValue, 5e3 ); if (r.async) { const outcome = await r.value; void outcome; } } if (this.stopped) break; this.lastSignalNotifyValue = Atomics.load( this.i32, this.signalNotifyIdx() ); await this.drain(); } } catch (err2) { this.onError?.(err2); throw err2; } finally { this.running = false; } } /** * Drain all pending slots: process [tail, head). Indices are * monotonic u32; `(head - tail) >>> 0` gives the count even when * head wraps past 2^32. */ async drain() { const head = Atomics.load(this.i32, this.headIdx()) >>> 0; let tail = Atomics.load(this.i32, this.tailIdx()) >>> 0; while (head - tail >>> 0 > 0) { const slotIdx = tail % WASM_SIGNAL_RING_SLOTS; const req = this.readSlot(slotIdx); try { const r = this.handler(req); if (r && typeof r.then === "function") { await r; } } catch (err2) { this.onError?.(err2); } tail = tail + 1 >>> 0; Atomics.store(this.i32, this.tailIdx(), tail); this.onProcessed?.(req); } } }; // ../../linux-in-the-browser/hardwarejs/src/devices/guest_memory.ts var GuestMemory = class _GuestMemory { wasm; buf; /* Typed over ArrayBuffer, not ArrayBufferLike: guest RAM is a * SharedArrayBuffer, and TS's ArrayBufferLike views do not satisfy the * BufferSource parameters (WebUSB, fetch, ...) these bytes get handed to. */ view; bytesView; words; /** How many times a grow was observed. Diagnostics; the gates read it. */ rederives = 0; constructor(src) { this.wasm = src.kernelMemoryWasm; this.buf = this.wasm?.buffer ?? src.kernelMemory; this.view = new DataView(this.buf); this.bytesView = new Uint8Array(this.buf); this.words = new Int32Array(this.buf); } /** * A GuestMemory over a fixed buffer that cannot grow (tests, and any rig * that owns a plain SharedArrayBuffer). Named so that "no Memory object" * is a deliberate statement rather than an omission. */ static overFixedBuffer(buf) { return new _GuestMemory({ kernelMemory: buf }); } /** * A GuestMemory over the buffer behind `u8`. The array must start at * offset 0 and span its whole buffer: guest addresses are absolute byte * offsets into the memory, so a windowed view would silently shift every * address the guest hands us. */ static overFixedBytes(u8) { if (u8.byteOffset !== 0 || u8.byteLength !== u8.buffer.byteLength) throw new RangeError( `GuestMemory.overFixedBytes: the array must cover its whole buffer (byteOffset=${u8.byteOffset}, byteLength=${u8.byteLength}, buffer=${u8.buffer.byteLength}) \u2014 guest addresses are absolute, so a windowed view would shift every one of them` ); return new _GuestMemory({ kernelMemory: u8.buffer }); } /** * Re-derive the views if the memory grew. One property read and a * not-taken branch in the steady state; see the cost note at the top. */ live() { const b = this.wasm?.buffer; if (b === void 0 || b === this.buf) return; this.buf = b; this.view = new DataView(b); this.bytesView = new Uint8Array(b); this.words = new Int32Array(b); this.rederives++; } /** The live DataView over ALL of guest RAM. Keep it in a local, not a field. */ get dv() { this.live(); return this.view; } /** The live Uint8Array over ALL of guest RAM. Local-only, same as `dv`. */ get u8() { this.live(); return this.bytesView; } /** The live Int32Array over ALL of guest RAM (Atomics). Local-only. */ get i32() { this.live(); return this.words; } /** Size of the LIVE guest RAM in bytes. */ get byteLength() { this.live(); return this.bytesView.length; } /** Times a grow has been observed through this handle. Diagnostics. */ get growsObserved() { this.live(); return this.rederives; } /** * Refuse an out-of-range guest address LOUDLY and by name. The bare * `RangeError: Invalid typed array length: 66` this replaces named the * frame size and nothing else — not the address, not the device, not the * live size — which is why the failure took a gate matrix to localize. */ checkRange(addr, len, what) { const size = this.bytesView.length; if (!Number.isInteger(addr) || !Number.isInteger(len) || addr < 0 || len < 0 || addr + len > size) throw new RangeError( `guest memory ${what}: [${addr}, ${addr + len}) is outside the live guest RAM (${size}B committed, ${this.rederives} grow(s) observed). A guest-supplied address past the end is a corrupt descriptor, not a stale view \u2014 this handle re-derives from the live memory.` ); } /** * A view of `[addr, addr+len)` in the LIVE guest RAM. * * Use it when a caller needs a Uint8Array shape (a `.set` target, a * decoder's input). It allocates; the copy helpers below do not, so prefer * those on the packet paths. */ bytes(addr, len) { this.live(); this.checkRange(addr, len, "bytes"); return this.bytesView.subarray(addr, addr + len); } /** A detached COPY of `[addr, addr+len)`. Safe to hold; the view is not. */ read(addr, len) { this.live(); this.checkRange(addr, len, "read"); return this.bytesView.slice(addr, addr + len); } /** Copy `[addr, addr+len)` into `dst` at `dstOff`. No view allocated. */ copyOut(addr, len, dst, dstOff = 0) { this.live(); this.checkRange(addr, len, "copyOut"); if (dstOff + len > dst.length) throw new RangeError( `guest memory copyOut: destination too small (need ${dstOff + len}B, have ${dst.length}B)` ); dst.set(this.bytesView.subarray(addr, addr + len), dstOff); } /** Copy `src` into guest RAM at `addr`. No view allocated. */ write(addr, src) { this.live(); this.checkRange(addr, src.length, "write"); this.bytesView.set(src, addr); } /** Fill `[addr, addr+len)` with `value` (default 0). No view allocated. */ fill(addr, len, value = 0) { this.live(); this.checkRange(addr, len, "fill"); this.bytesView.fill(value, addr, addr + len); } }; // ../../linux-in-the-browser/hardwarejs/src/devices/virtio_mmio.ts var VIRTIO_MMIO_DRIVER_FEATURES = 32; var VIRTIO_MMIO_DRIVER_FEATURES_SEL = 36; var VIRTIO_MMIO_INTERRUPT_STATUS = 96; var VIRTIO_MMIO_STATUS = 112; var VIRTIO_MMIO_INT_VRING = 1; var VIRTIO_CONFIG_S_DRIVER_OK = 4; function readAcceptedFeaturesWord0(mem, windowBase) { const dv = mem.dv; const status = dv.getUint32(windowBase + VIRTIO_MMIO_STATUS, true); if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) { return { readable: false, word0: 0, why: `STATUS=0x${status.toString(16)} has no DRIVER_OK yet \u2014 negotiation is not finished` }; } const sel = dv.getUint32(windowBase + VIRTIO_MMIO_DRIVER_FEATURES_SEL, true); if (sel !== 0) { return { readable: false, word0: 0, why: `DRIVER_FEATURES_SEL reads back ${sel}, not 0 \u2014 the register does not hold word 0 and this readback assumption no longer holds` }; } return { readable: true, word0: dv.getUint32(windowBase + VIRTIO_MMIO_DRIVER_FEATURES, true) >>> 0, why: "" }; } var WASM_VIRTIO_SHADOW_OFF = 768; var WASM_VIRTIO_SHADOW_STRIDE = 32; var VRING_DESC_F_NEXT = 1; var VRING_DESC_F_WRITE = 2; var VRING_DESC_F_INDIRECT = 4; var DESC_SIZE = 16; var VirtQueue = class { /** * `mem` is the LIVE guest memory, not a view of it. * * This used to be a DataView, which a grow silently froze — every device * then needed a `retarget()` call to swap in a rebuilt one, and forgetting * it produced "requests.N:id M is not a head!" and -EIO on every request. * A GuestMemory re-derives on access, so there is nothing to remember and * nothing to forget. The queue itself must still never be REBUILT across a * grow: `lastAvailIdx` is the consumed-avail cursor, and resetting it makes * the device re-take chains the driver considers done. */ constructor(mem, geom) { this.mem = mem; this.geom = geom; } mem; geom; lastAvailIdx = 0; get ready() { return this.geom.ready; } get size() { return this.geom.num; } /** * Pull every newly-available descriptor chain since the last call, * invoking `handle` for each. `handle` returns the number of bytes it * wrote into the writable segments (used-ring `len`). */ async drainAvail(handle, shouldContinue) { if (!this.geom.ready || this.geom.num === 0) return 0; let processed = 0; const availIdx = this.mem.dv.getUint16(this.geom.avail + 2, true); while (this.lastAvailIdx !== availIdx) { if (shouldContinue && !shouldContinue()) break; const slot = this.lastAvailIdx % this.geom.num; const head = this.mem.dv.getUint16(this.geom.avail + 4 + slot * 2, true); const req = this.pullChain(head); const written = await handle(req); this.publishUsed(head, written >>> 0); this.lastAvailIdx = this.lastAvailIdx + 1 & 65535; processed++; } return processed; } /** * Pull the NEXT single available descriptor chain (or null if none), and * advance the consumed cursor. Unlike drainAvail (which drains every * pending chain), this consumes exactly one — for device->driver queues * like the virtio-input eventq, where the device fills one guest-provided * buffer per event rather than servicing a batch. Byte-identical to the * per-chain step drainAvail takes, just one at a time and without invoking * a handler or auto-publishing the used ring (the caller writes the buffer * then calls {@link complete}). */ takeAvail() { if (!this.geom.ready || this.geom.num === 0) return null; const dv = this.mem.dv; const availIdx = dv.getUint16(this.geom.avail + 2, true); if (this.lastAvailIdx === availIdx) return null; const slot = this.lastAvailIdx % this.geom.num; const head = dv.getUint16(this.geom.avail + 4 + slot * 2, true); const req = this.pullChain(head); this.lastAvailIdx = this.lastAvailIdx + 1 & 65535; return req; } /** Publish a completed buffer (head + bytes written) to the used ring. */ complete(head, len) { this.publishUsed(head, len >>> 0); } /** * Give `n` chains taken by {@link takeAvail} back to the avail ring. * * ONLY legal for chains whose used entry has NOT been published, and only in * reverse order of taking. That is the whole safety argument: the avail ring * is the guest's and is untouched; `lastAvailIdx` is this device's private * cursor into it; nothing else consumes this queue. Moving the cursor back * over chains nobody was told about is therefore indistinguishable, from the * guest's side, from never having looked. * * It exists for VIRTIO_NET_F_MRG_RXBUF: a merged rx frame needs however many * buffers its length demands, and the count is only known by taking them. If * the ring runs dry halfway, the alternative to rewinding is to hand the * guest a run of zero-length used entries — which it charges to * rx_length_errors and which loses the frame. Rewinding stalls instead, and * a stall is recoverable. */ rewind(n) { if (n <= 0) return; this.lastAvailIdx = this.lastAvailIdx - n & 65535; } /** Chains the guest has made available and this device has not yet taken. */ get availPending() { if (!this.geom.ready || this.geom.num === 0) return 0; const availIdx = this.mem.dv.getUint16(this.geom.avail + 2, true); return availIdx - this.lastAvailIdx & 65535; } /** Walk a descriptor chain from `head` into readable/writable segments. */ pullChain(head) { const readable = []; const writable = []; let i = head; const dv = this.mem.dv; for (let guard = 0; guard <= this.geom.num; guard++) { const d = this.geom.desc + i * DESC_SIZE; const addrLo = dv.getUint32(d, true); const addrHi = dv.getUint32(d + 4, true); const len = dv.getUint32(d + 8, true); const flags = dv.getUint16(d + 12, true); const next = dv.getUint16(d + 14, true); const addr = addrHi * 4294967296 + addrLo; if (flags & VRING_DESC_F_INDIRECT) { throw new Error( "virtio_mmio: INDIRECT descriptor not supported (VERSION_1-only device)" ); } (flags & VRING_DESC_F_WRITE ? writable : readable).push({ addr, len }); if (!(flags & VRING_DESC_F_NEXT)) return { head, readable, writable }; i = next; } throw new Error("virtio_mmio: descriptor chain exceeds queue size (corrupt)"); } /** Publish a completed buffer to the used ring. */ publishUsed(id, len) { const dv = this.mem.dv; const usedIdx = dv.getUint16(this.geom.used + 2, true); const slot = usedIdx % this.geom.num; const elem = this.geom.used + 4 + slot * 8; dv.setUint32(elem, id >>> 0, true); dv.setUint32(elem + 4, len >>> 0, true); Atomics.store( this.mem.i32, this.geom.used + 0 >> 2, packU16Pair( dv.getUint16(this.geom.used, true), // flags (unchanged) usedIdx + 1 & 65535 ) ); } }; function readQueueGeom(mem, windowBase, q) { const sh = windowBase + WASM_VIRTIO_SHADOW_OFF + q * WASM_VIRTIO_SHADOW_STRIDE; const dv = mem.dv; const num = dv.getUint32(sh + 0, true); const ready = Atomics.load(mem.i32, sh + 4 >> 2) === 1; const descLo = dv.getUint32(sh + 8, true); const descHi = dv.getUint32(sh + 12, true); const availLo = dv.getUint32(sh + 16, true); const availHi = dv.getUint32(sh + 20, true); const usedLo = dv.getUint32(sh + 24, true); const usedHi = dv.getUint32(sh + 28, true); return { num, ready, desc: descHi * 4294967296 + descLo, avail: availHi * 4294967296 + availLo, used: usedHi * 4294967296 + usedLo }; } function packU16Pair(lo, hi) { return (hi & 65535) << 16 | lo & 65535; } // ../../linux-in-the-browser/hardwarejs/src/devices/virtio_blk.ts var VirtioBlkBackend = class { constructor(opts) { this.opts = opts; this.mem = new GuestMemory(opts); } opts; mem; queue; onKick(index) { try { if (index !== 0) throw new Error(`virtio-blk: invalid queue ${index}`); if (!this.queue?.ready) { const geom = readQueueGeom(this.mem, this.opts.windowBase, 0); if (!geom.ready || !geom.num) return; this.queue = new VirtQueue(this.mem, geom); } for (let request; request = this.queue.takeAvail(); ) { const length = this.serve(request); this.queue.complete(request.head, length); const words = this.mem.i32; Atomics.or(words, this.opts.windowBase + VIRTIO_MMIO_INTERRUPT_STATUS >> 2, 1); if (!this.opts.suppressIrq) { Atomics.or(words, this.opts.irqPendingOffset >> 2, 1 << 7); Atomics.add(words, this.opts.schedWakeupOffset >> 2, 1); Atomics.notify(words, this.opts.schedWakeupOffset >> 2); } } } catch (error) { this.opts.onError?.(error); } } gather(segments) { const length = segments.reduce((n, segment) => n + segment.len, 0); if (length > 16 * 1024 * 1024) throw new Error("virtio-blk: oversized request"); const bytes = new Uint8Array(length); let offset = 0; for (const segment of segments) { bytes.set(this.mem.bytes(segment.addr, segment.len), offset); offset += segment.len; } return bytes; } serve(request) { const status = request.writable.at(-1); if (!status || status.len !== 1) throw new Error("virtio-blk: missing one-byte status descriptor"); let code2 = 0, written = 1; try { const input = this.gather(request.readable); if (input.length < 16) throw new Error("virtio-blk: truncated header"); const header2 = new DataView(input.buffer); const type = header2.getUint32(0, true); const sector = header2.getBigUint64(8, true); const output = request.writable.slice(0, -1); const length = type === 1 ? input.length - 16 : output.reduce((n, part) => n + part.len, 0); if (type === 0 || type === 1) { if (length % 512 || length > 16 * 1024 * 1024 || sector * 512n + BigInt(length) > BigInt(this.opts.disk.size)) throw new Error("virtio-blk: sector range exceeds selected image"); if (type === 0) { if (input.length !== 16) throw new Error("virtio-blk: unexpected read payload"); const bytes = this.opts.disk.read(Number(sector * 512n), length); if (bytes.length !== length) throw new Error("virtio-blk: short disk read"); let offset = 0; for (const part of output) { this.mem.bytes(part.addr, part.len).set(bytes.subarray(offset, offset + part.len)); offset += part.len; } written += length; } else { if (this.opts.disk.readOnly || output.length) throw new Error("virtio-blk: write refused"); this.opts.disk.write(Number(sector * 512n), input.subarray(16)); } } else if (type === 4) { if (input.length !== 16 || output.length) throw new Error("virtio-blk: malformed flush"); this.opts.disk.flush(); } else code2 = 2; } catch (error) { code2 = 1; this.opts.onError?.(error); } this.mem.bytes(status.addr, 1)[0] = code2; return written; } }; // ../../linux-in-the-browser/hardwarejs/src/mount-provider.mjs var REGISTRY_SLOT = /* @__PURE__ */ Symbol.for("hardwarejs.mountProvider.registry.v1"); var registry = globalThis[REGISTRY_SLOT] ?? (globalThis[REGISTRY_SLOT] = { brand: /* @__PURE__ */ Symbol("hardwarejs.mountProvider.v1") }); var MOUNT_PROVIDER = registry.brand; function defineMountProvider(view, record) { if (view === null || typeof view !== "object") { throw new TypeError( "defineMountProvider: a mount provider must be an object" ); } if (typeof record?.kind !== "string" || record.kind === "") { throw new TypeError("defineMountProvider: record.kind is required"); } if (typeof record?.origin !== "string" || record.origin === "") { throw new TypeError("defineMountProvider: record.origin is required"); } Object.defineProperty(view, MOUNT_PROVIDER, { value: Object.freeze({ ...record }), enumerable: false, writable: false, configurable: false }); return view; } function mountProviderOf(view) { if (view === null || typeof view !== "object") return void 0; return ( /** @type {any} */ view[MOUNT_PROVIDER] ); } function cmdlineDeclaresVirtiofsRoot(cmdline) { if (typeof cmdline !== "string" || cmdline === "") return false; return cmdline.split(/\s+/).some((tok) => tok === "prestrike.rootfs=virtiofs"); } function requireRegisteredGuestRoot(boot3) { if (!cmdlineDeclaresVirtiofsRoot(boot3.cmdline)) return void 0; const how = ` Get a root from a provider: Node tests/gates \u2014 hardwarejs/src/guest-root.mjs createTempGuestRoot({ "/bin/sh": bytes, ... }) builds a rootfs in a temp directory at test time and removes it afterwards; or openHostDirGuestRoot("/path/to/rootfs") mounts a directory that already exists (a distro build/cloud-rootfs, say). Browser \u2014 the guest root arrives as a capability port, not as a client in the image: frame/machine/fs-capability.ts turns the granted MessagePort into a TunnelFsView, which src/devices/ fs-tunnel.ts brands with this very provider record. NOT prestrike.rootfs=brintosfs. That spelling was here until 2026-08-30 and never named a root this kernel could mount: wasm32_rootfs_kind() (arch/wasm32/kernel/init.c) accepts exactly 'virtiofs', 'nfs' and 'ext4' and refuses everything else BY NAME, so a reader who followed this text landed on a kernel refusal one layer further down than the one they started with. It described an in-guest brintos-fs that no longer exists either: the client moved to the app origin because a filesystem client baked into an image can never be updated. Rationale and the divergences this mount does NOT reproduce: docs/hwjs/HOST-DIRECTORY-GUEST-ROOT.md`; if (boot3.fsView === void 0 || boot3.fsView === null) { throw new Error( `bootKernel: the cmdline declares a virtio-fs guest root (prestrike.rootfs=virtiofs) but no virtioFs was supplied, so the guest would panic mounting a device that does not exist. ` + how ); } const record = mountProviderOf(boot3.fsView); if (record === void 0) { throw new Error( `bootKernel: refusing to boot a virtio-fs guest ROOT off an unregistered filesystem. The object passed as virtioFs.fs was not minted by a mount provider \u2014 it is a filesystem this tree has invented on the spot, and a guest booted on one proves nothing about a guest booted on a real root: it cannot hold a dynamic libc, a symlink, an executable image tree, or anything execve() has to open. ` + how ); } return record; } // ../../linux-in-the-browser/hardwarejs/src/devices/fs-meta-memo.ts var META_MEMO_MAX_INOS = 1 << 15; var META_MEMO_MAX_ABSENT = 1 << 15; // ../../linux-in-the-browser/hardwarejs/src/devices/fs-tunnel.ts var FS_TUNNEL_IMAGE_INO_BASE = 4026531840; var DEFAULT_MAX_ISSUED_INOS = 1 << 17; var DEFAULT_MAX_READ_BYTES = 1 << 20; var DEFAULT_MAX_WRITE_BYTES = 1 << 20; var DEFAULT_CLIENT_MAX_RESIDENT_BYTES = 4 << 20; // ../../linux-in-the-browser/hardwarejs/src/devices/special-nodes.ts var S_IFMT = 61440; var S_IFDIR = 16384; var S_IFIFO = 4096; var S_IFSOCK = 49152; var EPERM2 = 1; var EEXIST = 17; var EISDIR = 21; var ENOSYS2 = 38; var ENOTEMPTY = 39; var EOPNOTSUPP = 95; var FIRST_INO = FS_TUNNEL_IMAGE_INO_BASE + 134217728; function then(v, fn2) { return v !== null && typeof v === "object" && typeof v.then === "function" ? v.then(fn2) : fn2(v); } function unlessRefused(fn2, fallback) { const refused = (e) => { const errno = e?.errno; const n = typeof errno === "number" ? Math.abs(errno) : 0; if (n === EPERM2 || n === ENOSYS2 || n === EOPNOTSUPP) return fallback(); throw e; }; let v; try { v = fn2(); } catch (e) { return refused(e); } return v !== null && typeof v === "object" && typeof v.then === "function" ? v.catch(refused) : v; } var refuse2 = (errno, why) => Object.assign(new Error(why), { errno }); var isKept = (mode) => (mode & S_IFMT) === S_IFIFO || (mode & S_IFMT) === S_IFSOCK; function withSpecialNodes(inner) { const attrs = /* @__PURE__ */ new Map(); const names = /* @__PURE__ */ new Map(); let next = FIRST_INO; const key = (parent, name2) => `${parent}/${name2}`; const copy = (a) => ({ ...a }); function childrenOf(dir) { const out = []; const prefix = `${dir}/`; for (const [k, ino] of names) { if (!k.startsWith(prefix)) continue; out.push({ name: k.slice(prefix.length), ino, type: (attrs.get(ino).mode & S_IFMT) >> 12 }); } return out; } function dropName(k) { const ino = names.get(k); if (ino === void 0) return; names.delete(k); const a = attrs.get(ino); a.nlink = Math.max(0, a.nlink - 1); } function keep(parent, name2, mode, rdev) { if (names.has(key(parent, name2))) throw refuse2(EEXIST, `mknod: ${name2} exists`); return then(inner.lookup(parent, name2), (existing) => { if (existing) throw refuse2(EEXIST, `mknod: ${name2} exists`); const ino = next++; const a = { ino, size: 0, mode, nlink: 1, uid: 0, gid: 0, mtimeSec: Math.floor(Date.now() / 1e3), rdev }; attrs.set(ino, a); names.set(key(parent, name2), ino); return copy(a); }); } const over = { getattr(ino) { const a = attrs.get(ino); return a ? copy(a) : inner.getattr(ino); }, lookup(parent, name2) { const ino = names.get(key(parent, name2)); return ino !== void 0 ? copy(attrs.get(ino)) : inner.lookup(parent, name2); }, readdir(ino) { const listed = inner.readdir(ino); if (names.size === 0) return listed; return then(listed, (entries) => { const kept = childrenOf(ino); if (kept.length === 0) return entries; const shadowed = new Set(kept.map((e) => e.name)); return [...entries.filter((e) => !shadowed.has(e.name)), ...kept]; }); }, mknod(parent, name2, mode, rdev) { if (!isKept(mode)) { if (!inner.mknod) throw refuse2(EPERM2, "mknod: not supported by this store"); return inner.mknod(parent, name2, mode, rdev); } if (!inner.mknod) return keep(parent, name2, mode, rdev); return unlessRefused( () => inner.mknod(parent, name2, mode, rdev), () => keep(parent, name2, mode, rdev) ); }, link(parent, name2, targetIno) { const a = attrs.get(targetIno); if (!a) { if (!inner.link) throw refuse2(EPERM2, "link: not supported by this store"); return inner.link(parent, name2, targetIno); } if (names.has(key(parent, name2))) throw refuse2(EEXIST, `link: ${name2} exists`); return then(inner.lookup(parent, name2), (existing) => { if (existing) throw refuse2(EEXIST, `link: ${name2} exists`); names.set(key(parent, name2), targetIno); a.nlink += 1; return copy(a); }); }, unlink(parent, name2, isDir) { const k = key(parent, name2); if (!isDir && names.has(k)) { dropName(k); return 0; } if (!inner.unlink) return ENOSYS2; if (!isDir || names.size === 0) return inner.unlink(parent, name2, isDir); return then( inner.lookup(parent, name2), (dir) => dir && childrenOf(dir.ino).length > 0 ? ENOTEMPTY : inner.unlink(parent, name2, isDir) ); }, rename(parent, name2, newParent, newName) { const from = key(parent, name2); const to = key(newParent, newName); const ino = names.get(from); if (ino === void 0) { if (!inner.rename) return ENOSYS2; return then(inner.rename(parent, name2, newParent, newName), (rc) => { if (!(typeof rc === "number" && rc > 0)) dropName(to); return rc; }); } if (from === to || names.get(to) === ino) return 0; const move = () => { dropName(to); names.delete(from); names.set(to, ino); return 0; }; if (names.has(to)) return move(); return then(inner.lookup(newParent, newName), (target) => { if (!target) return move(); if ((target.mode & S_IFMT) === S_IFDIR) return EISDIR; if (!inner.unlink) return ENOSYS2; return then( inner.unlink(newParent, newName, false), (rc) => typeof rc === "number" && rc > 0 ? rc : move() ); }); }, setattr(ino, changes) { const a = attrs.get(ino); if (!a) return inner.setattr ? inner.setattr(ino, changes) : then(inner.getattr(ino), (g) => g); if (changes.mode !== void 0) a.mode = a.mode & S_IFMT | changes.mode & 4095; if (changes.uid !== void 0) a.uid = changes.uid; if (changes.gid !== void 0) a.gid = changes.gid; if (changes.mtimeSec !== void 0) a.mtimeSec = changes.mtimeSec; return copy(a); }, forget(ino, nlookup) { const a = attrs.get(ino); if (!a) return inner.forget?.(ino, nlookup); if (a.nlink === 0) attrs.delete(ino); } }; return new Proxy(inner, { get(target, prop) { if (Object.prototype.hasOwnProperty.call(over, prop)) return over[prop]; const v = Reflect.get(target, prop, target); return typeof v === "function" ? v.bind(target) : v; }, has(target, prop) { return Object.prototype.hasOwnProperty.call(over, prop) || Reflect.has(target, prop); } }); } // ../../linux-in-the-browser/hardwarejs/src/devices/virtio_fs.ts var S_IFMT2 = 61440; var S_IFDIR2 = 16384; var S_IFREG = 32768; var S_IFLNK = 40960; var FUSE_KERNEL_VERSION = 7; var FUSE_KERNEL_MINOR_VERSION = 41; var FUSE_LK_FLOCK = 1 << 0; var FUSE_RELEASE_FLOCK_UNLOCK = 1 << 1; var F_RDLCK = 0; var F_WRLCK = 1; var F_UNLCK = 2; var FUSE_POSIX_LOCKS = 1 << 1; var FUSE_BIG_WRITES = 1 << 5; var FUSE_FLOCK_LOCKS = 1 << 10; var FUSE_AUTO_INVAL_DATA = 1 << 12; var FUSE_MAX_PAGES = 1 << 22; var FOPEN_KEEP_CACHE = 1 << 1; var MTIME_RETENTION_FLOOR_SEC = 946684800; var EPERM3 = 1; var ENOENT = 2; var EIO2 = 5; var EACCES = 13; var EBUSY = 16; var EEXIST2 = 17; var EXDEV = 18; var ENOTDIR = 20; var EISDIR2 = 21; var EINVAL2 = 22; var ENOSPC2 = 28; var EROFS = 30; var ENAMETOOLONG = 36; var ENOLCK = 37; var ENOSYS3 = 38; var ENOTEMPTY2 = 39; var ENOTSUP2 = 95; var ETIMEDOUT = 110; var RETRY_ON_TIMEOUT_OPS = /* @__PURE__ */ new Set([ 1 /* LOOKUP */, 3 /* GETATTR */, 5 /* READLINK */, 15 /* READ */, 28 /* READDIR */, 44 /* READDIRPLUS */ ]); var READ_TIMEOUT_RETRIES = 2; var CODE_TO_ERRNO = { EPERM: EPERM3, ENOENT, EIO: EIO2, EACCES, EBUSY, EEXIST: EEXIST2, EXDEV, ENOTDIR, EISDIR: EISDIR2, EINVAL: EINVAL2, ENOSPC: ENOSPC2, EROFS, ENAMETOOLONG, ENOSYS: ENOSYS3, ENOTEMPTY: ENOTEMPTY2, ENOTSUP: ENOTSUP2, EOPNOTSUPP: ENOTSUP2 }; function attributedErrno(e) { const err2 = e; const errno = err2?.errno; if (typeof errno === "number" && Number.isInteger(errno) && errno > 0 && errno <= 4095) { return errno; } const code2 = err2?.code; if (typeof code2 === "string" && Object.prototype.hasOwnProperty.call(CODE_TO_ERRNO, code2)) { return CODE_TO_ERRNO[code2]; } return null; } var FUSE_IN_HEADER_SIZE = 40; var FUSE_OUT_HEADER_SIZE = 16; function isThenable(v) { return v !== null && (typeof v === "object" || typeof v === "function") && typeof v.then === "function"; } function maybeThen(v, fn2) { return isThenable(v) ? v.then(fn2) : fn2(v); } function gather(mem, segs) { const total = segs.reduce((n, s) => n + s.len, 0); const out = new Uint8Array(total); let off = 0; for (const s of segs) { mem.copyOut(s.addr, s.len, out, off); off += s.len; } return out; } function scatter(mem, segs, data) { let off = 0; for (const s of segs) { if (off >= data.length) break; const n = Math.min(s.len, data.length - off); mem.write(s.addr, data.subarray(off, off + n)); off += n; } return off; } function cstr(buf, start) { let end = start; while (end < buf.length && buf[end] !== 0) end++; return new TextDecoder().decode(buf.subarray(start, end)); } function writeFuseAttr(dv, off, a) { dv.setBigUint64(off + 0, BigInt(a.ino), true); dv.setBigUint64(off + 8, BigInt(a.size), true); dv.setBigUint64(off + 16, BigInt(Math.ceil(a.size / 512)), true); dv.setBigUint64(off + 24, BigInt(a.mtimeSec), true); dv.setBigUint64(off + 32, BigInt(a.mtimeSec), true); dv.setBigUint64(off + 40, BigInt(a.mtimeSec), true); dv.setUint32(off + 48, 0, true); dv.setUint32(off + 52, 0, true); dv.setUint32(off + 56, 0, true); dv.setUint32(off + 60, a.mode, true); dv.setUint32(off + 64, a.nlink, true); dv.setUint32(off + 68, a.uid, true); dv.setUint32(off + 72, a.gid, true); dv.setUint32(off + 76, a.rdev ?? 0, true); dv.setUint32(off + 80, 4096, true); dv.setUint32(off + 84, 0, true); } var FUSE_ATTR_SIZE = 88; function buildInitOut(majorOut, flockLocks, autoInvalData) { const buf = new Uint8Array(64); const dv = new DataView(buf.buffer); dv.setUint32(0, FUSE_KERNEL_VERSION, true); dv.setUint32(4, Math.min(FUSE_KERNEL_MINOR_VERSION, 31), true); dv.setUint32(8, 1 << 20, true); dv.setUint32( 12, FUSE_MAX_PAGES | FUSE_BIG_WRITES | (flockLocks ? FUSE_FLOCK_LOCKS : 0) | (autoInvalData ? FUSE_AUTO_INVAL_DATA : 0), true ); dv.setUint16(16, 0, true); dv.setUint16(18, 0, true); dv.setUint32(20, 1 << 20, true); dv.setUint32(24, 0, true); dv.setUint16(28, 256, true); return buf; } var FuseServer = class _FuseServer { fs; constructor(fs) { this.fs = withSpecialNodes(fs); } /** * Per-directory listing snapshot, held for the duration of a multi-call * READDIR sequence. The kernel pages a large directory across several * READDIR requests (offset cookies); without this cache every call would * re-invoke `fs.readdir` and re-walk the whole directory — O(n^2) over a * big dir. We snapshot on the first call of a sequence (offset 0) and * reuse it for the continuation calls, invalidating on any mutation of * the directory so a fresh `ls` after a create/unlink/rename re-reads. */ readdirCache = /* @__PURE__ */ new Map(); /** * Every namespace mutation this server has performed. * * Requests are served concurrently now, which turns the invalidation below * into a lost update: a READDIR that is awaiting `fs.readdir` has already * passed the point where `invalidateDir` could reach it, so a create or * unlink landing during that await clears an empty cache and the readdir * then INSTALLS its pre-mutation snapshot on top. The listing that * continuation pages serve is stale from that moment until the next * mutation happens to clear it again — a directory that has been written to * and still lists as it was. * * A counter read before the await and re-read after is enough to catch it: * a snapshot is only cached if nothing changed while it was being taken. * It is deliberately GLOBAL rather than per-directory so it cannot grow * without bound; the cost of the coarseness is that a mutation anywhere * makes one concurrent readdir elsewhere re-read on its next page, which is * the direction to be wrong in. */ mutations = 0; /** Drop a directory's cached listing (called on a mutating op). */ invalidateDir(ino) { this.readdirCache.delete(ino); this.mutations++; } /** * The guest has let go of this nodeid, so everything memoised against it is * dead weight. Called from the FORGET dispatch. * * WHY THIS IS NOT HOUSEKEEPING. `readdirCache` had exactly one eviction * path: a MUTATION of the directory it belongs to. A guest that walks a tree * read-only therefore never evicted anything, and the listing of every * directory it ever opened stayed in this server's memory for the life of * the machine. Under an initramfs root that was a ten-entry archive and the * question never came up. Under a virtio-fs root it is the whole repository, * held twice — once by the kernel's dentry cache, which at least has a * shrinker, and once here, which had nothing. * * There is no version of this that can be fixed later. This server ships * inside the image; a leak baked into one is a leak that machine has * forever. FORGET is the signal that was already arriving and was already * being dropped on the floor. * * Not a correctness change: a nodeid the guest has forgotten cannot be the * subject of a later request without a fresh LOOKUP, which repopulates. */ forgetMemos(ino) { this.readdirCache.delete(ino); this.regularMtime.delete(ino); } /** * Did THIS kernel offer FUSE_AUTO_INVAL_DATA on INIT? * * Set from fuse_init_in.flags on every INIT, both ways, so a re-mount * re-decides rather than inheriting. It gates FOPEN_KEEP_CACHE: the two * are one change and half of it is the stale-bytes bug. */ autoInvalData = false; /** Whether the missing-invalidator refusal has already been said once. */ saidNoAutoInval = false; /** * The last mtime this server REPORTED for a regular file, by nodeid. * * Retention is decided per file rather than per mount, because the thing * that makes it safe is a property of the file's attributes and not of the * view: see MTIME_RETENTION_FLOOR_SEC. The kernel walks a path before it * opens anything at the end of it, so the LOOKUP or GETATTR that seeds this * entry has already happened by the time OPEN arrives — no extra round trip * is taken to decide, and an inode this server has never described gets no * retention, which is today's behaviour. * * Bounded, and a MISS IS THE SAFE ANSWER: eviction costs one re-read of one * file, never a stale byte. 4096 is far above any path walk's working set * and far below the inode count of a real root, so the bound is what keeps * a long-lived mount from accumulating one entry per file ever touched. */ regularMtime = /* @__PURE__ */ new Map(); static MTIME_MEMO_MAX = 4096; /** * Remember what we just told the kernel about a file, at the one choke * point every FsAttr passes through on its way to the wire. * * Non-regular files are ERASED rather than skipped: a view is free to * reuse a nodeid whose file became a directory, and a memo that outlived * the file type it was taken for would claim retention for a mapping the * kernel fills from somewhere else. */ noteAttr(a) { if ((a.mode & S_IFMT2) !== S_IFREG) { this.regularMtime.delete(a.ino); return; } this.regularMtime.delete(a.ino); this.regularMtime.set(a.ino, a.mtimeSec); if (this.regularMtime.size > _FuseServer.MTIME_MEMO_MAX) { const oldest = this.regularMtime.keys().next(); if (!oldest.done) this.regularMtime.delete(oldest.value); } } /** * May this open keep the pages the kernel already has for `nodeid`? * * Both halves must hold: the kernel armed the invalidator (INIT), and this * file's mtime can actually discriminate a same-size rewrite. Anything else * — an unknown inode, a directory, a placeholder mtime, a kernel that did * not offer the flag — answers no and pays the re-read. */ mayKeepCache(nodeid) { if (!this.autoInvalData) return false; const mtime = this.regularMtime.get(nodeid); return mtime !== void 0 && mtime >= MTIME_RETENTION_FLOOR_SEC; } /** * Handle one virtqueue request. `readable`/`writable` are byte segments * (guest addresses in `mem`). Returns the number of bytes written into the * writable segments (the used-ring `len`). * * `mem` is a {@link GuestMemory}, NOT a view: this gathers the request * before its await and scatters the reply after it, and env.kernel_memory * can grow in between — which would freeze any Uint8Array handed in here. */ async handle(mem, readable, writable) { return this.handleMaybeSync(mem, readable, writable); } /** * The same request, answered SYNCHRONOUSLY when nothing had to suspend. * * Returns a `number` — the used-ring length, exactly what {@link handle} * resolves to — whenever the view answered without a promise, and a * `Promise` otherwise. There is no second protocol engine behind * this: it is the identical `dispatch`, and the only difference is that the * result is not laundered through an `await` that could not have been * skipped by a caller who is holding the only thread. * * `VirtioFsBackend.serve` is the caller that needs it, so that a device * drain running inside a guest `cpu_relax()` can complete a FUSE request * rather than start one it cannot finish. */ handleMaybeSync(mem, readable, writable) { const inbuf = gather(mem, readable); if (inbuf.length < FUSE_IN_HEADER_SIZE) return 0; const idv = new DataView(inbuf.buffer, inbuf.byteOffset, inbuf.byteLength); const opcode = idv.getUint32(4, true); const unique = idv.getBigUint64(8, true); const nodeid = Number(idv.getBigUint64(16, true)); const body = FUSE_IN_HEADER_SIZE; const fail = (e) => { const errno = attributedErrno(e); if (errno === null) { console.error("virtio_fs: backend error -> EIO:", e.message); } else { console.debug(`virtio_fs: backend refusal -> errno ${errno}:`, e.message); } return this.reply(mem, writable, unique, -(errno ?? EIO2), new Uint8Array(0)); }; const finish = (payload) => { try { if (payload === FORGET_NO_REPLY) return 0; if (typeof payload === "number") return this.reply(mem, writable, unique, -payload, new Uint8Array(0)); return this.reply(mem, writable, unique, 0, payload); } catch (e) { return fail(e); } }; const attempt = (retriesLeft) => { let payload; try { payload = this.dispatch(opcode, nodeid, idv, inbuf, body); } catch (e) { return fail(e); } if (!isThenable(payload)) return finish(payload); return payload.then(finish, (e) => { if (retriesLeft > 0 && RETRY_ON_TIMEOUT_OPS.has(opcode) && attributedErrno(e) === ETIMEDOUT) { console.warn( `virtio_fs: opcode ${opcode} timed out in the backend; asking again (${retriesLeft} left)` ); return attempt(retriesLeft - 1); } return fail(e); }); }; return attempt(READ_TIMEOUT_RETRIES); } /** * Returns a payload buffer, or a positive errno, or FORGET_NO_REPLY — * DIRECTLY when the view answered directly, wrapped in a promise when it * did not. * * Not `async` any more, and that is the whole of the synchronous fast path. * Every case that used to `await` now goes through {@link maybeThen}, which * is the same control flow with the promise made optional rather than * mandatory. There is no second dispatch and no opcode allow-list: a * shortcut for "the hot four" would have to be kept correct twice, and the * op most likely to change (READDIRPLUS, which is the only one that calls * back into the view in a loop) is the one it would have left behind. */ dispatch(opcode, nodeid, idv, inbuf, body) { switch (opcode) { case 26 /* INIT */: { const major = idv.getUint32(body + 0, true); const kernelFlags = inbuf.length >= body + 16 ? idv.getUint32(body + 12, true) : 0; this.autoInvalData = (kernelFlags & FUSE_AUTO_INVAL_DATA) !== 0; if (!this.autoInvalData && !this.saidNoAutoInval) { this.saidNoAutoInval = true; console.warn( `virtio_fs: kernel offered no FUSE_AUTO_INVAL_DATA in INIT (flags=0x${kernelFlags.toString(16)}); page-cache retention stays OFF and every open(2) re-reads the whole file` ); } return buildInitOut( major, typeof this.fs.setlk === "function" && this.fs.crossContextLocks === true, this.autoInvalData ); } case 38 /* DESTROY */: return new Uint8Array(0); /* * FORGET is delivered and NEVER awaited — see `FsView.forget`. The * reply value is FORGET_NO_REPLY either way, because that is what the * kernel is owed: it has already dropped the reference. * * A view that does not implement `forget` is the historical behaviour * exactly (drop it on the floor), which is what keeps this additive. */ case 2 /* FORGET */: { if (inbuf.length >= body + 8) { this.forgetMemos(nodeid); this.fs.forget?.(nodeid, Number(idv.getBigUint64(body, true))); } return FORGET_NO_REPLY; } case 42 /* BATCH_FORGET */: { const count = idv.getUint32(body, true); const first = body + 8; const have = Math.floor((inbuf.length - first) / 16); if (count > have) { console.warn( `virtio_fs: BATCH_FORGET claims ${count} entries but the descriptor holds ${have}; forgetting the ${have} that are there rather than reading past the frame` ); } const n = Math.min(count, have); for (let i = 0; i < n; i++) { const at = first + i * 16; const ino = Number(idv.getBigUint64(at, true)); this.forgetMemos(ino); this.fs.forget?.(ino, Number(idv.getBigUint64(at + 8, true))); } return FORGET_NO_REPLY; } case 3 /* GETATTR */: return maybeThen( this.fs.getattr(nodeid), (a) => a ? this.attrOut(a) : ENOENT ); case 1 /* LOOKUP */: { const name2 = cstr(inbuf, body); return maybeThen( this.fs.lookup(nodeid, name2), (a) => a ? this.entryOut(a) : ENOENT ); } case 14 /* OPEN */: return this.openOut(this.mayKeepCache(nodeid)); case 27 /* OPENDIR */: return this.openOut(false); // see openOut: nothing reads a dir mapping case 29 /* RELEASEDIR */: case 25 /* FLUSH */: return new Uint8Array(0); case 18 /* RELEASE */: { if (this.fs.releaselk) { const releaseFlags = idv.getUint32(body + 12, true); if (releaseFlags & FUSE_RELEASE_FLOCK_UNLOCK) { return maybeThen( this.fs.releaselk(nodeid, idv.getBigUint64(body + 16, true)), () => new Uint8Array(0) ); } } return new Uint8Array(0); } case 32 /* SETLK */: case 33 /* SETLKW */: { if (!this.fs.setlk) return ENOSYS3; const owner = idv.getBigUint64(body + 8, true); const type = idv.getUint32(body + 32, true); const lkFlags = idv.getUint32(body + 40, true); if ((lkFlags & FUSE_LK_FLOCK) === 0) { return ENOSYS3; } if (opcode === 33 /* SETLKW */) { return ENOLCK; } if (type !== F_RDLCK && type !== F_WRLCK && type !== F_UNLCK) { return EINVAL2; } return maybeThen( this.fs.setlk(nodeid, owner, type), (rc) => ( /* e.g. EAGAIN for a LOCK_NB that would have blocked. */ typeof rc === "number" && rc > 0 ? rc : new Uint8Array(0) ) ); } case 20 /* FSYNC */: { if (!this.fs.fsync) return new Uint8Array(0); const flags = idv.getUint32(body + 8, true); return maybeThen( this.fs.fsync(nodeid, (flags & 1) !== 0), () => new Uint8Array(0) ); } case 15 /* READ */: { const off = Number(idv.getBigUint64(body + 8, true)); const size = idv.getUint32(body + 16, true); return maybeThen( this.fs.read(nodeid, off, size), (b) => new Uint8Array(b) ); } case 28 /* READDIR */: case 44 /* READDIRPLUS */: { const off = Number(idv.getBigUint64(body + 8, true)); const size = idv.getUint32(body + 16, true); return this.readdirOut( nodeid, off, size, opcode === 44 /* READDIRPLUS */ ); } case 5 /* READLINK */: { if (!this.fs.readlink) return ENOSYS3; return maybeThen( this.fs.readlink(nodeid), (target) => new TextEncoder().encode(target) ); } case 17 /* STATFS */: return this.statfsOut(); case 22 /* GETXATTR */: return ENOSYS3; case 16 /* WRITE */: { if (!this.fs.write) return ENOSYS3; const off = Number(idv.getBigUint64(body + 8, true)); const size = idv.getUint32(body + 16, true); const dataStart = body + 40; const data = inbuf.subarray(dataStart, dataStart + size); return maybeThen(this.fs.write(nodeid, off, data), (n) => { const out = new Uint8Array(8); new DataView(out.buffer).setUint32(0, n >>> 0, true); return out; }); } case 4 /* SETATTR */: return maybeThen(this.fs.getattr(nodeid), (a) => { if (!a) return ENOENT; if (this.fs.setattr) { const valid = idv.getUint32(body + 0, true); const FATTR_MODE = 1 << 0; const FATTR_UID = 1 << 1; const FATTR_GID = 1 << 2; const FATTR_SIZE = 1 << 3; const FATTR_MTIME = 1 << 5; const FATTR_MTIME_NOW = 1 << 8; const changes = {}; if (valid & FATTR_SIZE) changes.size = Number(idv.getBigUint64(body + 16, true)); if (valid & FATTR_MODE) changes.mode = idv.getUint32(body + 68, true); if (valid & FATTR_UID) changes.uid = idv.getUint32(body + 76, true); if (valid & FATTR_GID) changes.gid = idv.getUint32(body + 80, true); if (valid & FATTR_MTIME_NOW) changes.mtimeSec = Math.floor(Date.now() / 1e3); else if (valid & FATTR_MTIME) changes.mtimeSec = Number(idv.getBigUint64(body + 40, true)); return maybeThen( this.fs.setattr(nodeid, changes), (updated) => this.attrOut(updated) ); } return this.attrOut(a); }); case 10 /* UNLINK */: case 11 /* RMDIR */: { if (!this.fs.unlink) return ENOSYS3; const name2 = cstr(inbuf, body); return maybeThen( this.fs.unlink(nodeid, name2, opcode === 11 /* RMDIR */), (rc) => { if (typeof rc === "number" && rc > 0) return rc; this.invalidateDir(nodeid); return new Uint8Array(0); } ); } case 12 /* RENAME */: { if (!this.fs.rename) return ENOSYS3; const newParent = Number(idv.getBigUint64(body + 0, true)); const oldName = cstr(inbuf, body + 8); const newName = cstr(inbuf, body + 8 + oldName.length + 1); return maybeThen( this.fs.rename(nodeid, oldName, newParent, newName), (rc) => { if (typeof rc === "number" && rc > 0) return rc; this.invalidateDir(nodeid); this.invalidateDir(newParent); return new Uint8Array(0); } ); } case 35 /* CREATE */: { if (!this.fs.create) return ENOSYS3; const mode = idv.getUint32(body + 4, true); const name2 = cstr(inbuf, body + 16); return maybeThen(this.fs.create(nodeid, name2, mode), (a) => { this.invalidateDir(nodeid); const entry = this.entryOut(a); const open = this.openOut(false); const out = new Uint8Array(entry.length + open.length); out.set(entry, 0); out.set(open, entry.length); return out; }); } case 9 /* MKDIR */: { if (!this.fs.mkdir) return ENOSYS3; const mode = idv.getUint32(body + 0, true); const name2 = cstr(inbuf, body + 8); return maybeThen(this.fs.mkdir(nodeid, name2, mode), (a) => { this.invalidateDir(nodeid); return this.entryOut(a); }); } /* * brintos/linux#5: SYMLINK / LINK / MKNOD — the namespace-creation * remainder. A view that does not provide the op gets EPERM, not * ENOSYS: the syscall IS implemented end-to-end now, and EPERM is * what a real filesystem that cannot host hardlinks/symlinks/nodes * answers (POSIX link(2)/symlink(2) "the file system ... does not * support" case). ENOSYS from an implemented syscall would send * callers down "kernel missing" diagnoses (exactly ticket #5), and * fuse_link would additionally latch it into a misleading state. */ case 6 /* SYMLINK */: { if (!this.fs.symlink) return EPERM3; const name2 = cstr(inbuf, body); const target = cstr(inbuf, body + name2.length + 1); return maybeThen(this.fs.symlink(nodeid, name2, target), (a) => { this.invalidateDir(nodeid); return this.entryOut(a); }); } case 13 /* LINK */: { if (!this.fs.link) return EPERM3; const oldNodeid = Number(idv.getBigUint64(body + 0, true)); const name2 = cstr(inbuf, body + 8); return maybeThen(this.fs.link(nodeid, name2, oldNodeid), (a) => { this.invalidateDir(nodeid); return this.entryOut(a); }); } case 8 /* MKNOD */: { if (!this.fs.mknod) return EPERM3; const mode = idv.getUint32(body + 0, true); const rdev = idv.getUint32(body + 4, true); const name2 = cstr(inbuf, body + 16); return maybeThen(this.fs.mknod(nodeid, name2, mode, rdev), (a) => { this.invalidateDir(nodeid); return this.entryOut(a); }); } default: return ENOSYS3; } } // ---- reply builders ---- reply(mem, writable, unique, error, payload) { const out = new Uint8Array(FUSE_OUT_HEADER_SIZE + payload.length); const dv = new DataView(out.buffer); dv.setUint32(0, out.length, true); dv.setInt32(4, error, true); dv.setBigUint64(8, unique, true); out.set(payload, FUSE_OUT_HEADER_SIZE); return scatter(mem, writable, out); } /** struct fuse_attr_out: attr_valid(8) attr_valid_nsec(4) dummy(4) fuse_attr. */ attrOut(a) { const buf = new Uint8Array(16 + FUSE_ATTR_SIZE); const dv = new DataView(buf.buffer); dv.setBigUint64(0, 1n, true); writeFuseAttr(dv, 16, a); this.noteAttr(a); return buf; } /** struct fuse_entry_out: nodeid(8) generation(8) entry_valid(8) * attr_valid(8) entry_valid_nsec(4) attr_valid_nsec(4) fuse_attr. */ entryOut(a) { const buf = new Uint8Array(40 + FUSE_ATTR_SIZE); const dv = new DataView(buf.buffer); dv.setBigUint64(0, BigInt(a.ino), true); dv.setBigUint64(8, 0n, true); dv.setBigUint64(16, 1n, true); dv.setBigUint64(24, 1n, true); writeFuseAttr(dv, 40, a); this.noteAttr(a); return buf; } /** * struct fuse_open_out: fh(8) open_flags(4) backing_id(4). * * open_flags WAS ZERO, AND THAT COST A WHOLE RE-READ PER open(2). * fs/fuse/file.c fuse_open_common ends with * * else if (!(ff->open_flags & FOPEN_KEEP_CACHE)) * invalidate_inode_pages2(inode->i_mapping); * * so with no FOPEN_KEEP_CACHE the kernel throws away every cached page of * the file on each open, and the next read pulls the whole thing across * this seam again. Measured on a real boot: six execs of one 3 213 373-byte * /bin/ip cost 1.4-1.9 s apiece, 16 230 ms in total, for a file that was * already resident after the first. * * The flag ALONE would be a worse defect than the one it removes — it tells * the kernel to trust cached pages, and this view serves a tree the far * side can write. So it is never claimed alone: `mayKeepCache` requires * FUSE_AUTO_INVAL_DATA to have been negotiated on INIT (the invalidator) * AND this file's mtime to be a real clock reading rather than a * placeholder (MTIME_RETENTION_FLOOR_SEC). What the kernel then does with a * file that changed under a retained mapping, all of it on the revalidating * LOOKUP/GETATTR: * * size differs invalidate_inode_pages2 after truncate_pagecache — * ALWAYS, auto-inval or not (fs/fuse/inode.c:349). * size same, mtime invalidate, and ONLY because auto_inval_data compares * differs the mtime (fs/fuse/inode.c:353). This is the arm that * the INIT negotiation pays for. * nodeid differs the DENTRY goes first (fs/fuse/dir.c:252) — a name * re-pointed at another inode resolves to a different * inode with its own empty mapping, and the retained * pages stay with the file they belong to. * * WHAT IT COSTS, said plainly because it is a real narrowing: data is now * exactly as fresh as attributes, and no fresher. entry_valid and * attr_valid are 1 s (see entryOut/attrOut), so two opens inside one second * revalidate nothing and the second serves the first's pages; and this * server reports whole-second mtimes (writeFuseAttr zeroes mtimensec), so * an out-of-band writer that rewrites a file to the SAME SIZE twice inside * one second is not discriminable by mtime at all. That window is the * attribute cache's own, which every FUSE mount already lives with; what * changed is that data now shares it instead of being re-read every time. * * DIRECTORIES ARE EXCLUDED. A directory's page cache is only ever READ * under FOPEN_CACHE_DIR (fs/fuse/readdir.c:119), which this server does not * send, so retention there would preserve pages nothing consults while * putting a second, invisible copy of the listing behind `readdirCache`. */ openOut(keepCache) { const buf = new Uint8Array(16); if (keepCache) { new DataView(buf.buffer).setUint32(8, FOPEN_KEEP_CACHE, true); } return buf; } /** * struct fuse_statfs_out: kstatfs(80). * * Track O: when the view knows its real capacity it is asked, and the * guest's `statvfs` reflects the actual backing store. This is load-bearing * — brintos-fs sizes its blob pool from `total/4` (bfs_cache.c:237) and its * eviction reserve from a fraction of `total` (bfs_content.c:1246), so the * old unconditional 4 GiB/2 GiB answer was feeding cache-sizing decisions a * number nobody had measured. * * Views without `statfs()` keep exactly the previous placeholder, so every * existing gate and the HTTP-backed view are byte-for-byte unchanged. */ statfsOut() { if (this.fs.statfs) return maybeThen(this.fs.statfs(), (s) => { const total = Math.max(0, Math.floor(s.totalBytes)); const free = Math.max(0, Math.min(Math.floor(s.freeBytes), total)); return this.buildStatfs( BigInt(Math.ceil(total / 4096)), BigInt(Math.floor(free / 4096)), BigInt(s.files ?? 1 << 20), BigInt(s.ffree ?? 1 << 19) ); }); return this.buildStatfs(1n << 20n, 1n << 19n, 1n << 16n, 1n << 15n); } buildStatfs(blocks, bfree, files, ffree) { const buf = new Uint8Array(80); const dv = new DataView(buf.buffer); const BSIZE = 4096; dv.setBigUint64(0, blocks, true); dv.setBigUint64(8, bfree, true); dv.setBigUint64(16, bfree, true); dv.setBigUint64(24, files, true); dv.setBigUint64(32, ffree, true); dv.setUint32(40, BSIZE, true); dv.setUint32(44, 255, true); dv.setUint32(48, BSIZE, true); return buf; } /** * Build a READDIR(PLUS) payload of fuse_dirent[(+entry)] entries. * * THE PAGE IS SIZED BEFORE ANY ATTRIBUTE IS FETCHED, which is what lets * this stay one implementation on both the synchronous and the promised * path. A record's length is `entryPre + 24 + pad8(namelen)` and every term * of that is known from the dirent alone — `entryPre` is the constant * `40 + FUSE_ATTR_SIZE` — so the set of entries that fits in `maxSize` can * be decided first and the READDIRPLUS attrs fetched for exactly those. * The old shape interleaved `await this.fs.getattr` with the size * accounting, which meant the loop could not run at all without * suspending; it also serialised one round trip per entry, so this is * faster on the promised path as well. */ readdirOut(ino, offset, maxSize, plus) { const cached = offset === 0 ? void 0 : this.readdirCache.get(ino); if (cached) return this.readdirPage(cached, offset, maxSize, plus); const at = this.mutations; return maybeThen(this.fs.readdir(ino), (entries) => { if (this.mutations === at) this.readdirCache.set(ino, entries); return this.readdirPage(entries, offset, maxSize, plus); }); } /** The entries that fit, then the bytes for them. */ readdirPage(entries, offset, maxSize, plus) { const direntHdr = 24; const entryPre = plus ? 40 + FUSE_ATTR_SIZE : 0; const page = []; let total = 0; const enc2 = new TextEncoder(); for (let i = offset; i < entries.length; i++) { const e = entries[i]; const nameBytes = enc2.encode(e.name); const recLen = entryPre + direntHdr + (nameBytes.length + 7 & ~7); if (total + recLen > maxSize) break; page.push({ e, nameBytes, cookie: i + 1, recLen }); total += recLen; } if (!plus) return this.readdirBytes(page, total, null); const attrs = page.map((p) => this.fs.getattr(p.e.ino)); if (!attrs.some(isThenable)) return this.readdirBytes(page, total, attrs); return Promise.all(attrs).then( (settled) => this.readdirBytes(page, total, settled) ); } readdirBytes(page, total, attrs) { const out = new Uint8Array(total); const dv = new DataView(out.buffer); let off = 0; for (let k = 0; k < page.length; k++) { const { e, nameBytes, cookie, recLen } = page[k]; let p = off; if (attrs !== null) { const a = attrs[k] ?? { ino: e.ino, size: 0, mode: e.type << 12 | 493, nlink: 1, uid: 0, gid: 0, mtimeSec: 0 }; const eo = this.entryOut(a); out.set(eo, p); p += eo.length; } dv.setBigUint64(p + 0, BigInt(e.ino), true); dv.setBigUint64(p + 8, BigInt(cookie), true); dv.setUint32(p + 16, nameBytes.length, true); dv.setUint32(p + 20, e.type, true); out.set(nameBytes, p + 24); off += recLen; } return out; } }; var FORGET_NO_REPLY = /* @__PURE__ */ Symbol("fuse-forget-no-reply"); function modeOf(kind, perms) { const ifmt = kind === "dir" ? S_IFDIR2 : kind === "symlink" ? S_IFLNK : S_IFREG; return ifmt | perms & 4095; } // ../../linux-in-the-browser/hardwarejs/src/devices/virtio_fs_backend.ts var VirtioFsBackend = class { constructor(opts) { this.opts = opts; this.mem = new GuestMemory(opts); this.server = new FuseServer(opts.fs); } opts; /** The ONE way this device addresses guest RAM. See guest_memory.ts. */ mem; server; queues = /* @__PURE__ */ new Map(); /** Requests dispatched and not yet completed. Diagnostics only. */ inFlight = 0; /** Handle a QUEUE_NOTIFY doorbell for queue `qidx`. Fire-and-forget. */ onKick(qidx) { try { this.process(qidx); } catch (e) { this.opts.onError?.(e); } } /** Requests currently being served. */ get outstanding() { return this.inFlight; } getQueue(qidx) { let vq = this.queues.get(qidx); if (vq && vq.ready) return vq; const geom = readQueueGeom(this.mem, this.opts.windowBase, qidx); if (!geom.ready || geom.num === 0) return null; vq = new VirtQueue(this.mem, geom); this.queues.set(qidx, vq); return vq; } dbg(s) { this.opts.onDebug?.(s); } /** * Pull every available chain and dispatch each one CONCURRENTLY. * * The device used to `await` each request inside `drainAvail`, so a * virtio-fs queue served exactly one FUSE request at a time no matter how * many the guest had outstanding. That is not a protocol requirement, it * was an implementation shortcut: FUSE correlates replies by `unique` and * the guest's split-ring driver looks its request up by the used element's * ID (`virtqueue_get_buf`, fs/fuse/virtio_fs.c:822), so out-of-order * completion is exactly what both layers already expect. Meanwhile * `fuse_readahead` (fs/fuse/file.c:985) issues up to `fc->max_background` * = 12 background READs without waiting for any of them, so the in-order * drain was collapsing a 12-deep pipeline into a single file of requests. * * Nothing here needs a FIFO assumption unwound: `takeAvail` consumes one * chain and `publishUsed` already writes an explicit ID, with the element * stored before the index is published with release. * * The pull loop is SYNCHRONOUS, which is what makes overlapping kicks safe * without a chain: `takeAvail` reads the avail index and advances the * consumed cursor with no suspension point inside, so two doorbells racing * can only split the work between them — never hand the same chain out * twice, and never skip one. * * A SYNCHRONOUSLY-ANSWERED REQUEST NOW COMPLETES INSIDE THIS LOOP, which is * a new interleaving and is safe for the reason above rather than by luck: * `takeAvail` walks the AVAIL ring and `publish` writes the USED ring, so * the completion of chain N touches nothing the pull of chain N+1 reads. * `raiseInterrupt` is atomics and a notify — it runs no JS and cannot * re-enter this loop. What it does change is `inFlight` at the bottom of * this method: on a synchronous view it now reads as the requests still * outstanding rather than as the number dispatched, which is what the name * says and what the debug line should have printed all along. */ process(qidx) { const vq = this.getQueue(qidx); if (!vq) { this.dbg(`kick q${qidx}: queue not ready`); return; } this.dbg(`process q${qidx} start`); let dispatched = 0; for (; ; ) { const req = vq.takeAvail(); if (!req) break; dispatched++; this.dbg( `q${qidx} req head=${req.head} rd=${req.readable.length} wr=${req.writable.length} serving...` ); this.serve(qidx, vq, req); } this.dbg(`kick q${qidx}: dispatched=${dispatched} inFlight=${this.inFlight}`); } /** * Serve one chain and publish its completion as soon as it is ready — * WITHOUT AN EVENT-LOOP TURN when the filesystem answered synchronously. * * A request whose service throws is deliberately NOT completed. Every * ordinary filesystem failure is already caught inside `FuseServer.handle` * and answered with a real negative errno, so reaching here means the * transport itself failed (a corrupt descriptor chain). Returning the * buffer with len=0 would hand the guest an out-header it never wrote — * `error` reads back as 0 — and a silent bogus success on a shared * persistent store is the one outcome worse than a hang. It stays * outstanding and the guest's FUSE waiter blocks loudly, which is what the * in-order drain did too. * * WHY THIS IS NOT MERELY FASTER, AND WHAT IT UNLOCKS. `serve` used to be * `async` and to `await` unconditionally, so completing a request always * cost at least one microtask turn. A merged CPU 0 spinning in * `cpu_relax()` holds the only JS thread and cannot give that turn, which * is exactly why bootKernel's synchronous device drain EXCLUDED virtio-fs * by name: a drain that took chains off the ring and started work it could * not finish would race the ordinary asynchronous path for them. With * `handleMaybeSync`, a view that answers synchronously is completed inside * the drain, so virtio-fs is on that list for real. A view that does NOT * answer synchronously takes the promise arm below and behaves exactly as it * always did. * * WHICH VIEWS ARE WHICH, STATED BECAUSE IT IS EASY TO ASSUME WRONGLY. Every * in-memory view answers synchronously. THE OPFS ENGINE DOES NOT — every * `OpfsFsCore` method is declared `async`, so `/cache` takes the promise arm * today even though it is in-thread and even though its handles are * synchronous underneath (test/machine-cache-device.test.ts measures this * and PLAN-CLOUD-FS-CACHE-TIERS §4.1 states the opposite). The capability * tunnel is asynchronous by construction and always will be. * * NO PER-OPERATION SAVING IS CLAIMED. `bench/fuse-sync-path.mjs` measured * one — 3 microtask turns per FUSE op, deterministically — but its timing * arms came back INCONCLUSIVE on a shared host whose samples swung 2.2x for * identical work, and a rate this tree cannot reproduce is a rate it does * not quote (bench/results/2026-08-27-fuse-sync-path.txt). The reason for * this change is the paragraph above, which is a capability rather than a * percentage. */ serve(qidx, vq, req) { this.inFlight++; let n; try { n = this.server.handleMaybeSync(this.mem, req.readable, req.writable); } catch (e) { this.inFlight--; this.opts.onError?.(e); return; } if (typeof n === "number") { this.publish(qidx, vq, req, n); return; } n.then( (len) => this.publish(qidx, vq, req, len), (e) => { this.inFlight--; this.opts.onError?.(e); } ); } /** Publish one completed request's used element and ring the doorbell. */ publish(qidx, vq, req, n) { try { this.dbg(`q${qidx} req head=${req.head} -> ${n}B`); vq.complete(req.head, n); this.raiseInterrupt(); } catch (e) { this.opts.onError?.(e); } finally { this.inFlight--; } } /** Set INTERRUPT_STATUS, mark the IRQ pending, and wake the idle CPU. */ raiseInterrupt() { const i32 = this.mem.i32; const isOff = this.opts.windowBase + VIRTIO_MMIO_INTERRUPT_STATUS; Atomics.or(i32, isOff >> 2, VIRTIO_MMIO_INT_VRING); if (this.opts.suppressIrq) return; const bit2 = 1 << (this.opts.irqBit ?? 0); Atomics.or(i32, this.opts.irqPendingOffset >> 2, bit2); Atomics.add(i32, this.opts.schedWakeupOffset >> 2, 1); const woke = Atomics.notify(i32, this.opts.schedWakeupOffset >> 2, 1); this.dbg(`raiseInterrupt: pending|=${bit2} schedWakeup notify woke=${woke}`); } }; // ../../linux-in-the-browser/hardwarejs/src/devices/virtio_input.ts var VIRTIO_INPUT_EVENTQ = 0; var VIRTIO_INPUT_STATUSQ = 1; var VIRTIO_INPUT_EVENT_BYTES = 8; var VirtioInputBackend = class { constructor(opts) { this.opts = opts; this.mem = new GuestMemory(opts); } opts; /** The ONE way this device addresses guest RAM. See guest_memory.ts. */ mem; queues = /* @__PURE__ */ new Map(); /** Events awaiting a guest-provided eventq buffer. */ pending = []; /** Handle a QUEUE_NOTIFY doorbell for queue `qidx`. */ onKick(qidx) { if (qidx === VIRTIO_INPUT_EVENTQ) { this.dbg(`onKick eventq (guest refilled buffers; pending=${this.pending.length})`); this.pump(); } else if (qidx === VIRTIO_INPUT_STATUSQ) { this.drainStatus(); } } /** * Inject an evdev event { type, code, value } into the guest. The page's * raw input capture translates DOM key/pointer events to Linux evdev codes * and calls this (including the EV_SYN/SYN_REPORT terminator per group). * Events queued before the eventq is ready are held and flushed on the * first eventq kick. */ injectEvent(type, code2, value) { this.pending.push({ type: type & 65535, code: code2 & 65535, value: value | 0 }); this.pump(); } getQueue(qidx) { let vq = this.queues.get(qidx); if (vq && vq.ready) return vq; const geom = readQueueGeom(this.mem, this.opts.windowBase, qidx); if (!geom.ready || geom.num === 0) return null; vq = new VirtQueue(this.mem, geom); this.queues.set(qidx, vq); return vq; } dbg(s) { this.opts.onDebug?.(s); } /** Drain pending events into available eventq buffers, one buffer each. */ pump() { const vq = this.getQueue(VIRTIO_INPUT_EVENTQ); if (!vq) { this.dbg(`inject: eventq not ready (${this.pending.length} pending)`); return; } let wrote = 0; while (this.pending.length > 0) { const req = vq.takeAvail(); if (!req) break; const seg = req.writable[0]; if (!seg || seg.len < VIRTIO_INPUT_EVENT_BYTES) { this.opts.onError?.( new Error( `virtio-input: eventq buffer too small (len=${seg ? seg.len : 0})` ) ); vq.complete(req.head, 0); this.pending.shift(); continue; } const ev = this.pending.shift(); const dv = this.mem.dv; dv.setUint16(seg.addr + 0, ev.type, true); dv.setUint16(seg.addr + 2, ev.code, true); dv.setUint32(seg.addr + 4, ev.value >>> 0, true); vq.complete(req.head, VIRTIO_INPUT_EVENT_BYTES); wrote++; } if (wrote > 0) { this.dbg(`inject: filled ${wrote} eventq buffer(s)`); this.raiseInterrupt(); } } /* * HWJS-C-1 TRAILING-EVENT RE-RAISE — RETIRED (2026-07-02). * * A bounded-backoff IRQ re-raise (an empty EV_SYN through the full * delivery path, 7 shots over ~120ms..15s) used to live here as a * COMPENSATING fix for what looked like an edge-triggered lost wake: a * completed input line sat undelivered for 50+ s until unrelated device * activity woke the kernel Worker. The kernel-side root cause has been * found and fixed (arch/wasm32/kernel/sched.c idle-quiesce): the kernel * Worker idled with the last-parked task's finish_task_switch never run * (on_cpu stuck 1, CPU0 rq->lock held), so any pool CPU-Worker * try_to_wake_up() of a kernel kthread — the tty1 delivery/echo path's * queue_work — HOT-SPUN until the next IRQ dispatched something. The * re-raise's periodic empty IRQ was exactly such a dispatch, which is * why it "fixed" the symptom. With the idle-quiesce in place the whole * dual-console stress (48+ interleaved commands, cpu=1) runs with zero * timeouts and NO re-raise; keeping it would only mask regressions of * the real fix (the dualcon gate's noquiesce RED arm relies on the * defect being reproducible). */ /** Teardown hook (idempotent; no timers since the re-raise retirement). */ dispose() { } /** Ack any driver->device status buffers so the guest reclaims them. */ drainStatus() { const vq = this.getQueue(VIRTIO_INPUT_STATUSQ); if (!vq) return; let n = 0; for (; ; ) { const req = vq.takeAvail(); if (!req) break; vq.complete(req.head, 0); n++; } if (n > 0) this.raiseInterrupt(); } /** Set INTERRUPT_STATUS, mark the IRQ pending, and wake the idle CPU. */ raiseInterrupt() { const i32 = this.mem.i32; const isOff = this.opts.windowBase + VIRTIO_MMIO_INTERRUPT_STATUS; Atomics.or(i32, isOff >> 2, VIRTIO_MMIO_INT_VRING); if (this.opts.suppressIrq) return; const bit2 = 1 << (this.opts.irqBit ?? 1); const before = Atomics.or(i32, this.opts.irqPendingOffset >> 2, bit2); Atomics.add(i32, this.opts.schedWakeupOffset >> 2, 1); const woke = Atomics.notify(i32, this.opts.schedWakeupOffset >> 2, 1); this.dbg( `raiseInterrupt: pending ${before.toString(2)}|=${bit2} woke=${woke} sched=${Atomics.load(i32, this.opts.schedWakeupOffset >> 2)}` ); } }; // ../../linux-in-the-browser/hardwarejs/src/devices/virtio_snd.ts var VIRTIO_SND_STREAMS = 1; var VIRTIO_SND_CHMAPS = 2; var VIRTIO_SND_DEVID = 8; var QUEUE_CONTROL = 0; var QUEUE_TX = 2; var R_JACK_INFO = 1; var R_PCM_INFO = 256; var R_PCM_SET_PARAMS = 257; var R_PCM_PREPARE = 258; var R_PCM_RELEASE = 259; var R_PCM_START = 260; var R_PCM_STOP = 261; var R_CHMAP_INFO = 512; var S_OK = 32768; var S_BAD_MSG = 32769; var S_NOT_SUPP = 32770; var S_IO_ERR = 32771; var PCM_INFO_BYTES = 32; var CHMAP_INFO_BYTES = 24; var CHMAP_MONO = 2; var CHMAP_FL = 3; var CHMAP_FR = 4; var STATUS_BYTES = 8; var FMT_U8 = 4; var FMT_S16 = 5; var FMT_S32 = 17; var FMT_FLOAT = 19; var FORMATS = 1n << BigInt(FMT_U8) | 1n << BigInt(FMT_S16) | 1n << BigInt(FMT_S32) | 1n << BigInt(FMT_FLOAT); var RATES = /* @__PURE__ */ new Map([ [1, 8e3], [2, 11025], [3, 16e3], [4, 22050], [5, 32e3], [6, 44100], [7, 48e3], [8, 64e3], [9, 88200], [10, 96e3] ]); var RATE_BITS = [...RATES.keys()].reduce((bits, index) => bits | 1n << BigInt(index), 0n); var BYTES_PER_SAMPLE = /* @__PURE__ */ new Map([[FMT_U8, 1], [FMT_S16, 2], [FMT_S32, 4], [FMT_FLOAT, 4]]); var VirtioSndBackend = class { constructor(opts) { this.opts = opts; this.mem = new GuestMemory(opts); } opts; mem; queues = /* @__PURE__ */ new Map(); params = null; running = false; /** Tx chains taken while the stream is stopped, played on START. */ held = []; /** Tx chains the sink holds, by head; a chain leaves on done or on RELEASE. */ inFlight = /* @__PURE__ */ new Set(); statusOf = /* @__PURE__ */ new Map(); /** Bumped by RELEASE: a sink's late `done` must not complete a reused head. */ generation = 0; onKick(index) { try { if (index === QUEUE_CONTROL) this.drainControl(); else if (index === QUEUE_TX) this.drainTx(); } catch (error) { this.opts.onError?.(error); } } queue(index) { const known = this.queues.get(index); if (known?.ready) return known; const geom = readQueueGeom(this.mem, this.opts.windowBase, index); if (!geom.ready || !geom.num) return null; const queue = new VirtQueue(this.mem, geom); this.queues.set(index, queue); return queue; } interrupt() { const words = this.mem.i32; Atomics.or(words, this.opts.windowBase + VIRTIO_MMIO_INTERRUPT_STATUS >> 2, 1); if (this.opts.suppressIrq) return; Atomics.or(words, this.opts.irqPendingOffset >> 2, 1 << VIRTIO_SND_DEVID); Atomics.add(words, this.opts.schedWakeupOffset >> 2, 1); Atomics.notify(words, this.opts.schedWakeupOffset >> 2); } gather(segments) { const bytes = new Uint8Array(segments.reduce((n, segment) => n + segment.len, 0)); let offset = 0; for (const segment of segments) { bytes.set(this.mem.bytes(segment.addr, segment.len), offset); offset += segment.len; } return bytes; } scatter(segments, bytes) { let offset = 0; for (const segment of segments) { const part = bytes.subarray(offset, offset + segment.len); this.mem.bytes(segment.addr, part.length).set(part); offset += part.length; } return offset; } drainControl() { const queue = this.queue(QUEUE_CONTROL); if (!queue) return; let served = 0; for (let request; request = queue.takeAvail(); ) { const reply = this.control(this.gather(request.readable)); queue.complete(request.head, this.scatter(request.writable, reply)); served++; } if (served) this.interrupt(); } /** The reply: a virtio_snd_hdr, then any item data the request asked for. */ control(request) { const status = (code3) => { const bytes = new Uint8Array(4); new DataView(bytes.buffer).setUint32(0, code3, true); return bytes; }; if (request.length < 4) return status(S_BAD_MSG); const view = new DataView(request.buffer, request.byteOffset, request.length); const code2 = view.getUint32(0, true); switch (code2) { case R_PCM_INFO: return this.queryInfo(view, VIRTIO_SND_STREAMS, PCM_INFO_BYTES, this.writePcmInfo); case R_CHMAP_INFO: return this.queryInfo(view, VIRTIO_SND_CHMAPS, CHMAP_INFO_BYTES, this.writeChmapInfo); case R_JACK_INFO: return status(S_NOT_SUPP); case R_PCM_SET_PARAMS: return status(this.setParams(view)); case R_PCM_PREPARE: case R_PCM_RELEASE: case R_PCM_START: case R_PCM_STOP: { if (request.length < 8 || view.getUint32(4, true) >= VIRTIO_SND_STREAMS) return status(S_BAD_MSG); return status(this.transition(code2)); } default: return status(S_NOT_SUPP); } } queryInfo(view, items, itemBytes, write) { const reply = (code2, length) => { const bytes2 = new Uint8Array(4 + length); new DataView(bytes2.buffer).setUint32(0, code2, true); return bytes2; }; if (view.byteLength < 16) return reply(S_BAD_MSG, 0); const start = view.getUint32(4, true), count = view.getUint32(8, true), size = view.getUint32(12, true); if (size !== itemBytes || start + count > items) return reply(S_BAD_MSG, 0); const bytes = reply(S_OK, count * size); const out = new DataView(bytes.buffer); for (let i = 0; i < count; i++) write(out, 4 + i * size, start + i); return bytes; } writePcmInfo = (out, at) => { out.setBigUint64(at + 8, FORMATS, true); out.setBigUint64(at + 16, RATE_BITS, true); out.setUint8(at + 24, 0); out.setUint8(at + 25, 1); out.setUint8(at + 26, 2); }; writeChmapInfo = (out, at, id) => { const positions = id === 0 ? [CHMAP_MONO] : [CHMAP_FL, CHMAP_FR]; out.setUint8(at + 4, 0); out.setUint8(at + 5, positions.length); positions.forEach((position, i) => out.setUint8(at + 6 + i, position)); }; setParams(view) { if (view.byteLength < 24 || view.getUint32(4, true) >= VIRTIO_SND_STREAMS) return S_BAD_MSG; const channels = view.getUint8(20), format = view.getUint8(21), rate = view.getUint8(22); if (channels < 1 || channels > 2 || !BYTES_PER_SAMPLE.has(format) || !RATES.has(rate)) return S_NOT_SUPP; this.params = { channels, format, rate: RATES.get(rate) }; return S_OK; } transition(code2) { switch (code2) { case R_PCM_PREPARE: return this.params ? S_OK : S_BAD_MSG; case R_PCM_START: if (!this.params) return S_BAD_MSG; this.running = true; this.playHeld(); return S_OK; case R_PCM_STOP: this.running = false; return S_OK; default: this.running = false; this.generation++; this.opts.sink.flush(); this.completeOutstanding(); return S_OK; } } drainTx() { const queue = this.queue(QUEUE_TX); if (!queue) return; for (let request; request = queue.takeAvail(); ) this.held.push(request); if (this.running) this.playHeld(); } playHeld() { const held = this.held; this.held = []; for (const request of held) { try { this.play(request); } catch (error) { this.fail(request, error); } } } /** A chain that cannot play still goes back, or the driver waits on it forever. */ fail(request, error) { this.inFlight.delete(request.head); this.statusOf.delete(request.head); const status = request.writable[0]; if (status && status.len >= STATUS_BYTES) this.finish(request.head, status, S_IO_ERR); else { this.queues.get(QUEUE_TX)?.complete(request.head, 0); this.interrupt(); } this.opts.onError?.(error); } play(request) { const status = request.writable[0]; if (!status || status.len < STATUS_BYTES || request.readable.length < 2) throw new Error("virtio-snd: malformed tx chain"); const params = this.params; if (!params) return this.finish(request.head, status, S_BAD_MSG); this.inFlight.add(request.head); this.statusOf.set(request.head, status); const pcm = this.gather(request.readable.slice(1)); const generation = this.generation; this.opts.sink.write(toBlock(pcm, params), () => { if (generation !== this.generation || !this.inFlight.delete(request.head)) return; this.statusOf.delete(request.head); try { this.finish(request.head, status, S_OK); } catch (error) { this.opts.onError?.(error); } }); } completeOutstanding() { for (const request of this.held) { const status = request.writable[0]; if (status) this.finish(request.head, status, S_OK); } this.held = []; for (const head of this.inFlight) this.finish(head, this.statusOf.get(head), S_OK); this.inFlight.clear(); this.statusOf.clear(); } finish(head, status, code2) { const out = new DataView(new ArrayBuffer(STATUS_BYTES)); out.setUint32(0, code2, true); this.mem.bytes(status.addr, STATUS_BYTES).set(new Uint8Array(out.buffer)); this.queues.get(QUEUE_TX)?.complete(head, STATUS_BYTES); this.interrupt(); } }; function toBlock(pcm, params) { const width = BYTES_PER_SAMPLE.get(params.format); const frames = Math.floor(pcm.length / (width * params.channels)); const channels = Array.from({ length: params.channels }, () => new Float32Array(frames)); const view = new DataView(pcm.buffer, pcm.byteOffset, pcm.length); let at = 0; for (let frame = 0; frame < frames; frame++) { for (let channel = 0; channel < params.channels; channel++, at += width) { channels[channel][frame] = params.format === FMT_S16 ? view.getInt16(at, true) / 32768 : params.format === FMT_S32 ? view.getInt32(at, true) / 2147483648 : params.format === FMT_FLOAT ? view.getFloat32(at, true) : (view.getUint8(at) - 128) / 128; } } return { rate: params.rate, frames, channels }; } // ../../linux-in-the-browser/hardwarejs/src/devices/net_shim.ts var DEFAULT_GATEWAY_IP = [10, 0, 2, 2]; var DEFAULT_GATEWAY_MAC = [82, 85, 10, 0, 2, 2]; var DEFAULT_DNS_IP = [10, 0, 2, 3]; var DEFAULT_DNS_MAC = [82, 85, 10, 0, 2, 3]; var DEFAULT_NET_KEY_PATH = "/etc/brintos/net-key"; var GW_LOG_MAX = 512; var DEFAULT_GATEWAY_PORT = 3128; var TCP_MSS = 1400; var RX_WINDOW = 64240; var TCP_MAX_WSCALE = 14; var OUR_WSCALE = 0; var OUR_MSS = TCP_MSS; var TCPOPT_EOL = 0; var TCPOPT_NOP = 1; var TCPOPT_MSS = 2; var TCPOPT_WSCALE = 3; var TCPOPT_SACK_PERM = 4; var TCP_MAX_INFLIGHT = 1024 * 1024; var PROXY_HEAD_MAX = 64 * 1024; var PROXY_BODY_BUFFER_MAX = 8 * 1024 * 1024; var PROXY_BODY_STREAM_HWM = 1024 * 1024; var PROXY_RESP_LOWAT = 256 * 1024; var PROXY_MAX_CONCURRENT = 32; var PROXY_BUFFERED_BODY_MAX = 32 * 1024 * 1024; var HOP_BY_HOP = /* @__PURE__ */ new Set([ "connection", "proxy-connection", "keep-alive", "te", "trailer", "transfer-encoding", "upgrade", "proxy-authorization", "proxy-authenticate" ]); var StubNaasUplink = class { constructor(opts) { this.opts = opts; } opts; count = 0; canRelay = false; /** The classified sessions seen (bounded log; newest last). */ seen = []; open(session) { this.count++; if (this.seen.length < 64) this.seen.push(session); this.opts.onEvent( `NaaS-FORWARD-REFUSED: ${session.proto} ${session.host}:${session.port} reached the forward boundary but no egress relay is enabled (turn on VPN in the Network tab, and check your plan); REFUSED. forward-count=${this.count}` ); let closeCb = () => { }; queueMicrotask( () => closeCb(1, "network relay not enabled (enable VPN / upgrade plan)") ); return { send: () => false, onData: () => { }, onClose: (cb) => { closeCb = cb; }, onWritable: () => { }, ack: () => { }, close: () => { } }; } }; function newProxyState() { return { buf: [], bufLen: 0, phase: "head", req: null, respActive: false, activeHeld: false, respHeadWritten: false, respReader: null, respChunked: false, respBytesExpected: -1, respBytesSent: 0, reading: false, closing: false, guestFin: false, pendingRec: null, requests: 0 }; } var NetShim = class { constructor(opts) { this.opts = opts; this.tcpOpt = { wscale: opts.tcpOptions?.wscale ?? false, mss: opts.tcpOptions?.mss ?? true, sackOk: opts.tcpOptions?.sackOk ?? false }; if (opts.packetUplink) this.attachPacketUplink(opts.packetUplink, "this machine booted with it"); this.gateway = opts.gateway; if (this.gateway) { for (const o of this.gateway.origins) { const norm = normalizeOrigin(o); if (norm === null) { throw new Error(`NetShim gateway: malformed allowlist origin "${o}"`); } this.gatewayOrigins.add(norm); } const rawAppOrigin = this.gateway.appOrigin ?? this.gateway.checkout?.appOrigin; if (rawAppOrigin !== void 0) { const norm = normalizeOrigin(rawAppOrigin); if (norm === null) { throw new Error(`NetShim gateway: malformed appOrigin "${rawAppOrigin}"`); } this.gatewayAppOrigin = norm; } if (this.gateway.checkout) { const co = normalizeOrigin(this.gateway.checkout.appOrigin); if (co === null) { throw new Error( `NetShim gateway: malformed checkout appOrigin "${this.gateway.checkout.appOrigin}"` ); } if (this.gatewayAppOrigin !== co) { throw new Error( `NetShim gateway: checkout appOrigin "${co}" disagrees with appOrigin "${this.gatewayAppOrigin}"` ); } } if (this.gateway.readOnly && this.gatewayAppOrigin === null) { this.opts.info( `GATEWAY: read-only with NO appOrigin \u2014 this gateway cannot recognise its own fs API, so brintos-fs blob reads (POST /fs/blobs/presign, presign-batch, batch-get) will be refused. This door is for a guest that reaches the fs API for itself; the ROOT does not come through it any more. Supply gateway.appOrigin.` ); } if (this.gateway.appOriginDoorOpens !== void 0) { if (typeof this.gateway.appOriginDoorOpens !== "function") { throw new Error( `NetShim gateway: appOriginDoorOpens is ${typeof this.gateway.appOriginDoorOpens}, not a function. It is DOOR 1's route table (frame/machine/fsapi-capability.ts, fsApiRouteOf) injected as a predicate; pass a (pathname) => boolean or omit it.` ); } if (this.gatewayAppOrigin === null) { throw new Error( `NetShim gateway: appOriginDoorOpens was supplied with no appOrigin (and no checkout.appOrigin), so the filesystem-API door could never be consulted \u2014 every app-origin /fs request would be refused 403 origin-not-allowlisted by the allowlist gate instead. Supply gateway.appOrigin, or omit the door.` ); } this.appOriginDoorOpens = this.gateway.appOriginDoorOpens; } } this.gwIp = Uint8Array.from(opts.gatewayIp ?? DEFAULT_GATEWAY_IP); this.gwMac = Uint8Array.from(opts.gatewayMac ?? DEFAULT_GATEWAY_MAC); this.dnsIp = Uint8Array.from(opts.dnsIp ?? DEFAULT_DNS_IP); this.dnsMac = Uint8Array.from(opts.dnsMac ?? DEFAULT_DNS_MAC); this.httpPortMapping = opts.httpPortMapping === true; if (this.httpPortMapping) { this.opts.info( `NET: guest TCP :80 is mapped onto this host's own fetch (httpPortMapping). No origin allowlist applies to that path; the embedder asked for it.` ); } const hostFetch = globalThis.fetch; this.fetchImpl = opts.fetchImpl ?? (typeof hostFetch === "function" ? hostFetch.bind(globalThis) : (() => { throw new Error( "NetShim: no fetch implementation available (pass fetchImpl)" ); })); } opts; gwIp; gwMac; dnsIp; dnsMac; fetchImpl; /** Whether guest :80 maps onto this host's `fetch`. Off unless asked. */ httpPortMapping; flows = /* @__PURE__ */ new Map(); /** Relayed UDP 4-tuples (connectionless; no handshake/window). */ udpFlows = /* @__PURE__ */ new Map(); /** Fabricated DNS answers: hostname -> ip, and ip-string -> hostname. */ nameToIp = /* @__PURE__ */ new Map(); ipToName = /* @__PURE__ */ new Map(); dnsNext = 1; /* 198.51.100. allocation cursor (TEST-NET-2). */ /** Memoized key check (per shim/boot). undefined until first read. */ keyOk; /** Resolved SYN-ACK option gates (see TcpOptionGates). */ tcpOpt; /** * Full-access L3 uplink (set => packet-forward mode). * * NOT `readonly`, and the reason is the whole of why turning the VPN on used * to need a reboot. The guest's network DEVICE is unconditional — `eth0` is * probed, addressed and routed on every boot, VPN or no VPN, and the kernel * driver offers no VIRTIO_NET_F_STATUS, so there is no link state for a * carrier change to travel on. The only thing the switch ever changed was * whether this field held an uplink, and it was fixed at construction inside * `bootKernel`. So "enable the VPN" was "build another kernel", for a field. * * It is written only by {@link attachPacketUplink}/{@link detachPacketUplink}, * which are the two halves of one mode change and keep `guestMacL3` and the * inbound callback in step with it. */ l3; /** Guest MAC, learned from its frames — needed to inject L3 return packets. */ guestMacL3 = null; /** * The guest's MAC as of the last frame it sent, in ANY mode. * * Recorded outside L3 mode as well, because a hot attach must be able to * inject a relay→guest packet before the guest has transmitted anything since * the switch was flipped. `guestMacL3` used to be learned only inside * `handleL3`, and `injectIpPacket` returns early while it is null — SILENTLY, * the one drop in this shim with no line — so an uplink attached mid-run * black-holed everything inbound until the guest happened to speak first. * That is precisely the window a VPN is enabled in: the person turns it on * and then expects the reply to the request they already sent. */ lastGuestMac = null; /* ---- egress gateway (Track N) ---- */ gateway; /** Normalized allowed origins (via `new URL(o).origin`). */ gatewayOrigins = /* @__PURE__ */ new Set(); /** Normalized checkout app origin (lease-injection comparisons). */ gatewayAppOrigin = null; /** DOOR 1's route table, injected by the embedder. See * {@link NetGatewayOptions.appOriginDoorOpens} for the incident. */ appOriginDoorOpens = null; /** One line the first time the door actually claims a request, so a boot * transcript shows the split RAN rather than leaving a reader to infer it * from the absence of a refusal. See `noteRootFsRefusal` for the same * once-only shape and the two debugging sessions that motivated it. */ doorRouteNoted = false; /** Concurrent proxied fetches (ceiling: gateway.maxConcurrent). */ gatewayActive = 0; /** Sum of request-body bytes currently BUFFERED (pre-dispatch) across all * proxy flows; bounded by PROXY_BUFFERED_BODY_MAX (N2 host-memory invariant). */ gatewayBufferedBytes = 0; /** Gate-visible counters. */ gatewayRequests = 0; gatewayRefusals = 0; /* ---- gateway telemetry (the Storage panel's byte-accurate vantage) ---- * `gwActive` holds in-flight records by id; `gwRing` retains the last * GW_LOG_MAX completions. A fixed ring rather than an unbounded log: this * runs for the life of a machine and an unbounded one would be a slow leak * dressed as a feature. `gwDropped` is published so a reader says "history * truncated" instead of implying it saw everything. */ gwActive = /* @__PURE__ */ new Map(); gwRing = []; gwRingHead = 0; gwDropped = 0; gwNextId = 1; gwTotalDown = 0; gwTotalUp = 0; /** * A snapshot of gateway egress: totals, in-flight requests with live byte * counts, and the recent completions. Plain data, safe to postMessage. * * Records are COPIED, so a caller cannot mutate live bookkeeping and a * caller that holds the snapshot across ticks sees a consistent instant * rather than fields drifting under it. */ gatewayTelemetry() { const records = []; for (const r of this.gwActive.values()) records.push({ ...r }); records.sort((a, b) => a.startedMs - b.startedMs); for (let i = 0; i < this.gwRing.length; i++) { const idx = (this.gwRingHead - 1 - i + this.gwRing.length * 2) % this.gwRing.length; const r = this.gwRing[idx]; if (r) records.push({ ...r }); } return { nowMs: Date.now(), configured: this.gateway !== void 0, readOnly: this.gateway?.readOnly === true, origins: [...this.gatewayOrigins], requests: this.gatewayRequests, refusals: this.gatewayRefusals, active: this.gatewayActive, maxConcurrent: this.gateway?.maxConcurrent ?? PROXY_MAX_CONCURRENT, bufferedBodyBytes: this.gatewayBufferedBytes, totalDown: this.gwTotalDown, totalUp: this.gwTotalUp, records, dropped: this.gwDropped }; } /** Open a record. Called once per parsed request line — BEFORE the * allowlist and read-only gates, so a refusal is recorded as the request * it was rather than vanishing. */ gwBegin(flow, method, target) { const rec = { id: this.gwNextId++, fetchId: "", method, /* Empty until the target parses as an absolute URL. A record whose * origin is "" is a request that never got far enough to have one — * which is information, not a gap to paper over. */ origin: "", path: target, flow: flow.key, startedMs: Date.now(), headMs: 0, endedMs: 0, status: 0, contentLength: -1, down: 0, up: 0, state: "pending", error: "" }; this.gwActive.set(rec.id, rec); return rec; } /** Close a record and retire it into the ring. Idempotent: several teardown * paths can reach the same request and the FIRST verdict is the true one * (a refusal followed by a connection close is a refusal, not a close). */ gwEnd(rec, state, error = "") { if (!rec || !this.gwActive.has(rec.id)) return; this.gwActive.delete(rec.id); rec.state = state; rec.endedMs = Date.now(); if (error && !rec.error) rec.error = error; if (this.gwRing.length < GW_LOG_MAX) { this.gwRing.push(rec); this.gwRingHead = this.gwRing.length % GW_LOG_MAX; } else { if (this.gwRing[this.gwRingHead]) this.gwDropped++; this.gwRing[this.gwRingHead] = rec; this.gwRingHead = (this.gwRingHead + 1) % GW_LOG_MAX; } } /** Diagnostic (N2 gate): bytes queued guest-bound but not yet segmented onto * the wire for a flow — the host memory the response pump is holding. With * window-honoring backpressure this stays ≤ PROXY_RESP_LOWAT + one chunk; * the RED arm (redDisableBackpressure) lets it grow without bound. */ peekQueuedBytes(flowKey) { return this.flows.get(flowKey)?.outLen ?? 0; } /** Diagnostic/test seam: is a TCP flow still tracked? Used to assert flows * are torn down (no map leak) after teardown/FIN. */ hasFlow(flowKey) { return this.flows.has(flowKey); } /** Gate-visible NaaS forward counter passthrough (best-effort). */ get naasForwardCount() { return this.opts.naas.count ?? 0; } /** Whether this shim is currently in full-access packet-forward mode. */ get packetForwarding() { return this.l3 !== void 0; } /** * Put this shim into packet-forward mode NOW, on a running machine. * * WHAT THIS COSTS THE GUEST: nothing. `eth0` is already up, already carries * 10.0.2.15/24 and already has a default route — the rc that configures it is * guarded on the interface existing and never on the relay — and the driver * has no link state to raise, so there is no carrier event for the guest to * miss and nothing inside it to poke. The change is one classifier branch in * `handleGuestFrame`, and it takes effect on the very next frame. * * WHAT IT COSTS IN FLIGHT: also nothing, and that is not luck. With no uplink * every flow that is not gateway-local is already refused and reset by * StubNaasUplink, so there is no established connection to migrate — the * switch has no in-flight state on either side of it. * * `reason` goes in the transcript. A mode change with no line is the "why did * my machine start reaching the internet" question with no answer in the log. */ attachPacketUplink(uplink, reason) { if (this.l3 === uplink) return; if (this.l3) this.detachPacketUplink("it is being replaced by another uplink"); this.l3 = uplink; uplink.onPacket((ip) => { if (this.l3 !== uplink) return; this.injectIpPacket(ip); }); if (this.guestMacL3 === null && this.lastGuestMac !== null) { this.guestMacL3 = Uint8Array.from(this.lastGuestMac); } this.opts.info( `NET: full-access packet forwarding is ON (${reason}). Every IPv4 packet not addressed to the local gateway now leaves over the relay, from the next frame. eth0 needed no reconfiguration: its address, route and resolver were set at boot and are unchanged` + (this.guestMacL3 === null ? `. The guest MAC is not known yet, so inbound packets are dropped until it transmits.` : `.`) + ` Names resolved BEFORE this point may still be held by a running process; those answers were this shim's own and do not exist on the far side of the relay.` ); } /** * Leave packet-forward mode NOW. The caller still owns the uplink's socket. * * Deliberately does NOT close the uplink: this shim was handed one and does * not own its lifetime, and the caller has to end the relay SESSION as well * as the socket — closing a socket is worth about ten milliseconds against a * credential that still verifies. */ detachPacketUplink(reason) { if (!this.l3) return; this.l3 = void 0; this.guestMacL3 = null; this.opts.info( `NET: full-access packet forwarding is OFF (${reason}). eth0 stays up with the same address and route \u2014 what changed is that packets it cannot serve locally are refused here, loudly and by name, instead of leaving over the relay.` ); } /* ------------------------------- classify ------------------------------- */ handleGuestFrame(frame) { if (frame.length < 14) { this.opts.info(`FWD/drop: runt frame (${frame.length}B)`); return; } const src = frame.subarray(6, 12); if (this.lastGuestMac === null || !macEq(this.lastGuestMac, src)) { this.lastGuestMac = Uint8Array.from(src); } if (this.l3) { this.handleL3(frame); return; } const et = frame[12] << 8 | frame[13]; if (et === 2054) { this.handleArp(frame); return; } if (et === 2048) { this.handleIpv4(frame); return; } this.refuseUnsupported(`l3:0x${et.toString(16)}`, "raw"); } /** Refuse a classification the relay does not carry (raw L3/ICMP, and UDP * until M4). Loud + attributed + counted; never a silent drop. Option P * (raw-L3 relay) is deferred, so these have no uplink to hand off to. */ unsupportedRefuseCount = 0; refuseUnsupported(kind, dst) { this.unsupportedRefuseCount++; this.opts.info( `FWD-REFUSE: ${kind} -> ${dst}: the egress relay carries TCP and UDP, not raw ICMP/L3 (e.g. ping) \u2014 use a TCP or UDP connection instead. REFUSED. unsupported-refuse-count=${this.unsupportedRefuseCount}` ); } /* ------------------------------- L3 mode -------------------------------- */ /** Full-access packet-forward path (PLAN docs/naas/L3-DESIGN.md). ARP is * answered locally (the guest must learn the gateway/DNS MACs); the gateway * liveness echo stays local; EVERY other IPv4 packet — any protocol, any * port, including ICMP to real hosts — is forwarded verbatim to the VPN * relay, which NATs it to the internet. Non-IPv4 (e.g. IPv6) is dropped: the * guest is IPv4-only. */ handleL3(frame) { this.guestMacL3 = this.lastGuestMac; const et = frame[12] << 8 | frame[13]; if (et === 2054) { this.handleArp(frame); return; } if (et !== 2048 || frame.length < 34) { return; } const ip = 14; const dst = frame.subarray(ip + 16, ip + 20); if (ipEq(dst, this.gwIp)) { this.handleIpv4(frame); return; } this.l3.send(frame.subarray(14)); } /** Inject a relay→guest IPv4 packet: wrap it in Ethernet (from the gateway * MAC to the guest) and hand it to the rx queue. */ injectIpPacket(ipPacket) { if (!this.guestMacL3 || ipPacket.length < 20) return; const frame = new Uint8Array(14 + ipPacket.length); frame.set(this.guestMacL3, 0); frame.set(this.gwMac, 6); frame[12] = 8; frame[13] = 0; frame.set(ipPacket, 14); this.opts.transmit(frame); } /* --------------------------------- ARP ---------------------------------- */ handleArp(frame) { const a = 14; if (frame.length < a + 28) { this.opts.info(`FWD/drop: short ARP (${frame.length}B)`); return; } const op = frame[a + 6] << 8 | frame[a + 7]; if (op !== 1) return; const tpa = frame.subarray(a + 24, a + 28); let mac = null; let ip = null; if (ipEq(tpa, this.gwIp)) { mac = this.gwMac; ip = this.gwIp; } else if (ipEq(tpa, this.dnsIp)) { mac = this.dnsMac; ip = this.dnsIp; } if (!mac || !ip) { return; } const reply = new Uint8Array(a + 28); reply.set(frame.subarray(a + 8, a + 14), 0); reply.set(mac, 6); reply[12] = 8; reply[13] = 6; reply.set(frame.subarray(a, a + 6), a); reply[a + 6] = 0; reply[a + 7] = 2; reply.set(mac, a + 8); reply.set(ip, a + 14); reply.set(frame.subarray(a + 8, a + 14), a + 18); reply.set(frame.subarray(a + 14, a + 18), a + 24); this.opts.info(`ARP: answered who-has ${fmtIp(ip)} (is-at ${fmtMac(mac)})`); this.opts.transmit(reply); } /* -------------------------------- IPv4 ---------------------------------- */ handleIpv4(frame) { const ip = 14; if (frame.length < ip + 20 || frame[ip] >> 4 !== 4) { this.opts.info("FWD/drop: malformed IPv4"); return; } const ihl = (frame[ip] & 15) * 4; const proto = frame[ip + 9]; const dst = frame.subarray(ip + 16, ip + 20); if (proto === 6) { this.handleTcp(frame, ip, ihl); return; } if (proto === 17) { const l4 = ip + ihl; const dport = frame[l4 + 2] << 8 | frame[l4 + 3]; if (ipEq(dst, this.dnsIp) && dport === 53) { this.handleDns(frame, ip, ihl); } else if (ipEq(dst, this.gwIp)) { this.udpEchoToGateway(frame, ip, ihl); } else { this.handleUdpRelay(frame, ip, ihl); } return; } if (proto === 1) { if (ipEq(dst, this.gwIp)) { this.icmpEchoToGateway(frame, ip, ihl); } else { this.refuseUnsupported("icmp", fmtIp(dst)); } return; } this.refuseUnsupported(`ip-proto:${proto}`, fmtIp(dst)); } /* ----------------------- gateway ICMP / UDP echo ------------------------ */ icmpEchoToGateway(frame, ip, ihl) { const icmp = ip + ihl; if (frame.length < icmp + 8 || frame[icmp] !== 8 || frame[icmp + 1] !== 0) { this.refuseUnsupported("icmp", fmtIp(frame.subarray(ip + 16, ip + 20))); return; } const reply = frame.slice(); swapEth(reply); swapIp(reply, ip); reply[icmp] = 0; reply[icmp + 2] = 0; reply[icmp + 3] = 0; const c = inetChecksum(reply.subarray(icmp)); reply[icmp + 2] = c >> 8; reply[icmp + 3] = c & 255; this.opts.info(`ICMP: echoed ping (${frame.length - icmp - 8}B payload)`); this.opts.transmit(reply); } udpEchoToGateway(frame, ip, ihl) { const udp = ip + ihl; if (frame.length < udp + 8) { this.opts.info("FWD/drop: short UDP to gateway"); return; } const reply = frame.slice(); swapEth(reply); swapIp(reply, ip); for (let i = 0; i < 2; i++) { const t = reply[udp + i]; reply[udp + i] = reply[udp + 2 + i]; reply[udp + 2 + i] = t; } const dport = frame[udp + 2] << 8 | frame[udp + 3]; this.opts.info( `UDP: echoed datagram to port ${dport} (${frame.length - udp - 8}B payload)` ); this.opts.transmit(reply); } /* --------------------------------- DNS ---------------------------------- */ handleDns(frame, ip, ihl) { const udp = ip + ihl; const dnsOff = udp + 8; if (frame.length < dnsOff + 12) { this.opts.info("FWD/drop: short DNS"); return; } const id = frame[dnsOff] << 8 | frame[dnsOff + 1]; const qd = frame[dnsOff + 4] << 8 | frame[dnsOff + 5]; if (qd < 1) return; let p = dnsOff + 12; const labels = []; while (p < frame.length) { const len = frame[p]; if (len === 0) { p++; break; } if ((len & 192) !== 0) return; const s = p + 1; if (s + len > frame.length) return; labels.push( String.fromCharCode(...Array.from(frame.subarray(s, s + len))) ); p += 1 + len; } if (p + 4 > frame.length) return; const qtype = frame[p] << 8 | frame[p + 1]; const qname = labels.join("."); const qnameEnd = p + 4; if (qtype !== 1) { this.opts.info(`DNS: ${qname} qtype=${qtype} -> empty answer`); this.sendDnsResponse(frame, ip, ihl, dnsOff, id, qnameEnd, null); return; } const answerIp = this.fabricateIp(qname); this.opts.info(`DNS: ${qname} A -> ${fmtIp(answerIp)} (fabricated)`); this.sendDnsResponse(frame, ip, ihl, dnsOff, id, qnameEnd, answerIp); } fabricateIp(hostname) { const existing = this.nameToIp.get(hostname); if (existing) return existing; const last = (this.dnsNext++ - 1) % 253 + 1; const ip = Uint8Array.from([198, 51, 100, last]); this.nameToIp.set(hostname, ip); this.ipToName.set(fmtIp(ip), hostname); return ip; } sendDnsResponse(reqFrame, ip, ihl, dnsOff, id, qnameEnd, answerIp) { const question = reqFrame.subarray(dnsOff + 12, qnameEnd); const ancount = answerIp ? 1 : 0; const answerLen = answerIp ? 16 : 0; const dnsLen = 12 + question.length + answerLen; const dns = new Uint8Array(dnsLen); dns[0] = id >> 8; dns[1] = id & 255; dns[2] = 129; dns[3] = 128; dns[4] = 0; dns[5] = 1; dns[6] = 0; dns[7] = ancount; dns.set(question, 12); if (answerIp) { let o = 12 + question.length; dns[o++] = 192; dns[o++] = 12; dns[o++] = 0; dns[o++] = 1; dns[o++] = 0; dns[o++] = 1; dns[o++] = 0; dns[o++] = 0; dns[o++] = 0; dns[o++] = 60; dns[o++] = 0; dns[o++] = 4; dns.set(answerIp, o); } const udp = ip + ihl; const srcPort = reqFrame[udp] << 8 | reqFrame[udp + 1]; const frame = this.buildUdp( /* eth dst */ reqFrame.subarray(6, 12), /* eth src */ this.dnsMac, /* ip src */ this.dnsIp, /* ip dst */ reqFrame.subarray(ip + 12, ip + 16), /* src port*/ 53, /* dst port*/ srcPort, dns ); this.opts.transmit(frame); } /* ------------------------------ UDP relay ------------------------------- */ /** Relay a UDP 4-tuple as a connectionless datagram flow to the NaaS uplink. * One uplink session per (client,server) 4-tuple; the guest's datagrams go * out via `send`, and inbound datagrams come back via `onData` re-framed as * UDP from server→client. Idle flows are reaped. The stub refuses loudly. */ handleUdpRelay(frame, ip, ihl) { const udp = ip + ihl; if (frame.length < udp + 8) { this.opts.info("FWD/drop: short UDP"); return; } const srcPort = frame[udp] << 8 | frame[udp + 1]; const dstPort = frame[udp + 2] << 8 | frame[udp + 3]; const udpLen = frame[udp + 4] << 8 | frame[udp + 5]; const payload = frame.subarray(udp + 8, udp + Math.max(8, udpLen)); const clientIp = frame.subarray(ip + 12, ip + 16); const serverIp = frame.subarray(ip + 16, ip + 20); const guestMac = frame.subarray(6, 12); const key = `${fmtIp(clientIp)}:${srcPort}-${fmtIp(serverIp)}:${dstPort}`; let flow = this.udpFlows.get(key); if (!flow) { const host = this.ipToName.get(fmtIp(serverIp)) ?? fmtIp(serverIp); this.opts.info(`RELAY: open udp ${key} -> ${host}:${dstPort} via NaaS uplink`); const f = { key, conn: null, guestMac: Uint8Array.from(guestMac), clientIp: Uint8Array.from(clientIp), serverIp: Uint8Array.from(serverIp), clientPort: srcPort, serverPort: dstPort, idle: null }; this.udpFlows.set(key, f); flow = f; const conn = this.opts.naas.open({ proto: "udp", host, port: dstPort }); f.conn = conn; conn.onData((bytes) => { if (!this.udpFlows.has(key)) return; const dg = this.buildUdp( f.guestMac, this.gwMac, f.serverIp, f.clientIp, f.serverPort, f.clientPort, bytes ); this.opts.transmit(dg); this.armUdpIdle(f); }); conn.onClose((code2, reason) => { this.opts.info(`RELAY: close udp ${key} code=${code2} ${reason}`); this.closeUdp(f); }); conn.onWritable(() => { }); } flow.conn?.send(Uint8Array.from(payload)); this.armUdpIdle(flow); } armUdpIdle(flow) { if (flow.idle) clearTimeout(flow.idle); flow.idle = setTimeout(() => { this.opts.info(`RELAY: udp idle ${flow.key}`); this.closeUdp(flow); }, 6e4); } closeUdp(flow) { if (flow.idle) clearTimeout(flow.idle); flow.conn?.close("udp-close"); flow.conn = null; this.udpFlows.delete(flow.key); } /* --------------------------------- TCP ---------------------------------- */ handleTcp(frame, ip, ihl) { const tcp = ip + ihl; if (frame.length < tcp + 20) { this.opts.info("FWD/drop: short TCP"); return; } const srcPort = frame[tcp] << 8 | frame[tcp + 1]; const dstPort = frame[tcp + 2] << 8 | frame[tcp + 3]; const seq = readU32(frame, tcp + 4); const ack = readU32(frame, tcp + 8); const dataOff = (frame[tcp + 12] >> 4) * 4; if (dataOff < 20 || tcp + dataOff > frame.length) { this.opts.info( `FWD/drop: bad TCP data offset (${dataOff}B, frame ${frame.length}B)` ); return; } const flags = frame[tcp + 13]; const wnd = frame[tcp + 14] << 8 | frame[tcp + 15]; const payloadOff = tcp + dataOff; const payload = frame.subarray(payloadOff, frame.length); const clientIp = frame.subarray(ip + 12, ip + 16); const serverIp = frame.subarray(ip + 16, ip + 20); const guestMac = frame.subarray(6, 12); const FIN = 1, SYN = 2, RST = 4, ACK = 16; const key = `${fmtIp(clientIp)}:${srcPort}-${fmtIp(serverIp)}:${dstPort}`; if (netTrace()) this.opts.info( `TCPTRACE rx ${key} flags=0x${flags.toString(16)} seq=${seq} ack=${ack} wnd=${wnd} len=${payload.length}` ); if (flags & RST) { const f = this.flows.get(key); if (f) f.closed = true; if (f?.conn) f.conn.close("guest-rst"); if (f?.proxy) this.proxyAbort(f, "guest-rst"); this.flows.delete(key); return; } let flow = this.flows.get(key); if (flags & SYN && !(flags & ACK)) { const stale = this.flows.get(key); if (stale) { stale.closed = true; if (stale.conn) { stale.conn.close("syn-reuse"); stale.conn = null; } if (stale.proxy) this.proxyAbort(stale, "syn-reuse"); this.flows.delete(key); this.opts.info(`TCP: SYN reused live 4-tuple ${key} \u2014 tore down stale flow`); } const gwPort = this.gateway?.port ?? DEFAULT_GATEWAY_PORT; const mode = this.gateway && dstPort === gwPort && ipEq(serverIp, this.gwIp) ? "proxy" : this.httpPortMapping && dstPort === 80 ? "http" : "relay"; const ourIsn = Math.floor(Math.random() * 2147483647) >>> 0 || 4096; const synOpts = parseTcpOptions(frame, tcp + 20, tcp + dataOff); if (synOpts.malformed) this.opts.info(`TCP: malformed option area on SYN ${key} \u2014 parsed prefix only`); const wsOk = this.tcpOpt.wscale && synOpts.wscale !== null; const sndWscale = wsOk ? synOpts.wscale : 0; const synAckOpts = buildSynAckOptions(this.tcpOpt, wsOk ? sndWscale : null); flow = { key, mode, guestMac: Uint8Array.from(guestMac), clientIp: Uint8Array.from(clientIp), serverIp: Uint8Array.from(serverIp), clientPort: srcPort, serverPort: dstPort, rcvNxt: seq + 1 >>> 0, sndNxt: ourIsn, sndUna: ourIsn, established: false, reqChunks: [], reqLen: 0, requestDone: false, fetchStarted: false, resp: null, respStartSeq: 0, finSent: false, /* RFC 7323 §2.2: the window field of a SYN is NEVER scaled. */ guestWnd: wnd || RX_WINDOW, sndWscale, rcvWscale: wsOk ? OUR_WSCALE : 0, closed: false, conn: null, outChunks: [], outLen: 0, relayClosed: false, advWnd: RX_WINDOW, proxy: null }; if (mode === "proxy") flow.proxy = newProxyState(); this.flows.set(key, flow); this.sendTcp(flow, SYN | ACK, null, synAckOpts); flow.sndNxt = ourIsn + 1 >>> 0; flow.sndUna = flow.sndNxt; flow.respStartSeq = flow.sndNxt; this.opts.info( `TCP: SYN ${key} -> SYN-ACK (${mode})${wsOk ? ` ws=${sndWscale}/${OUR_WSCALE}` : " ws=off"}${this.tcpOpt.mss ? ` mss=${OUR_MSS}` : ""}` ); if (!this.gateway && dstPort === DEFAULT_GATEWAY_PORT && ipEq(serverIp, this.gwIp)) this.opts.info( `GATEWAY-UNCONFIGURED: the guest dialled ${fmtIp(this.gwIp)}:${DEFAULT_GATEWAY_PORT} (the egress gateway port) but this machine booted with no virtioNet.gateway \u2014 the flow falls to the relay path and will be refused.` ); if (mode === "relay") this.openRelay(flow); return; } if (!flow) { return; } flow.guestWnd = wnd << flow.sndWscale >>> 0; if (flags & ACK) { if (seqInWindow(ack, flow.sndUna, flow.sndNxt)) flow.sndUna = ack; if (!flow.established) flow.established = true; } if (payload.length > 0) { if (seq === flow.rcvNxt) { flow.rcvNxt = flow.rcvNxt + payload.length >>> 0; if (flow.mode === "http") { flow.reqChunks.push(Uint8Array.from(payload)); flow.reqLen += payload.length; this.sendTcp(flow, ACK, null); this.maybeCompleteRequest(flow); } else if (flow.mode === "proxy") { this.proxyData(flow, Uint8Array.from(payload)); this.sendTcp(flow, ACK, null); } else { this.relayGuestData(flow, Uint8Array.from(payload)); this.sendTcp(flow, ACK, null); } } else { this.sendTcp(flow, ACK, null); } } if (flags & FIN) { flow.rcvNxt = flow.rcvNxt + 1 >>> 0; this.sendTcp(flow, ACK, null); if (flow.mode === "relay" && flow.conn) { flow.conn.close("guest-fin"); flow.conn = null; } if (flow.mode === "proxy") this.proxyGuestFin(flow); if (flow.finSent) { this.flows.delete(key); } } if (flow.mode === "relay") this.pumpRelay(flow); else if (flow.mode === "proxy") this.pumpProxy(flow); else if (flow.resp) this.pumpResponse(flow); } maybeCompleteRequest(flow) { if (flow.requestDone || flow.fetchStarted) return; const buf = concat(flow.reqChunks, flow.reqLen); const headerEnd = findHeaderEnd(buf); if (headerEnd < 0) return; const headerText = asciiOf(buf.subarray(0, headerEnd)); const contentLength = parseContentLength(headerText); const bodyStart = headerEnd; const bodyHave = buf.length - bodyStart; if (contentLength > 0 && bodyHave < contentLength) return; flow.requestDone = true; flow.fetchStarted = true; void this.doFetch(flow, headerText, buf.subarray(bodyStart, bodyStart + Math.max(0, contentLength))); } async doFetch(flow, headerText, body) { const ok = await this.ensureKey(); if (!ok) { this.opts.info( `KEY-GATE-REFUSE: ${DEFAULT_NET_KEY_PATH} absent/malformed \u2014 RST ${flow.key}, no fetch served` ); this.rst(flow); return; } const lines = headerText.split("\r\n"); const requestLine = lines[0] ?? ""; const m = /^([A-Z]+)\s+(\S+)\s+HTTP\/(\d\.\d)/.exec(requestLine); if (!m) { this.opts.info(`TCP: malformed request line "${requestLine}" \u2014 RST`); this.rst(flow); return; } const method = m[1]; const path = m[2]; const headers = {}; let host = ""; for (let i = 1; i < lines.length; i++) { const line = lines[i]; if (!line) continue; const ci = line.indexOf(":"); if (ci < 0) continue; const name2 = line.slice(0, ci).trim(); const value = line.slice(ci + 1).trim(); const lname = name2.toLowerCase(); if (lname === "host") host = value; if (lname === "connection" || lname === "proxy-connection" || lname === "keep-alive" || lname === "content-length" || lname === "transfer-encoding") continue; headers[name2] = value; } if (!host) { host = this.ipToName.get(fmtIp(flow.serverIp)) ?? fmtIp(flow.serverIp); } const url = `http://${host}${path.startsWith("/") ? path : "/" + path}`; this.opts.info(`FETCH: ${method} ${url} (flow ${flow.key})`); let respBytes; try { const res = await this.fetchImpl(url, { method, headers, body: method === "GET" || method === "HEAD" ? null : body, redirect: "manual" }); const bodyBuf = new Uint8Array(await res.arrayBuffer()); respBytes = buildHttpResponse(res, bodyBuf); this.opts.info( `FETCH-OK: ${res.status} ${url} (${bodyBuf.length}B body)` ); } catch (e) { const msg = e instanceof Error ? e.message : String(e); this.opts.info(`FETCH-FAIL: ${url}: ${msg} \u2014 RST ${flow.key}`); this.opts.onError?.(e instanceof Error ? e : new Error(msg)); this.rst(flow); return; } flow.resp = respBytes; flow.respStartSeq = flow.sndNxt; this.pumpResponse(flow); } /** Segment the queued response into in-order TCP data segments, respecting * the guest's advertised window (no-tick: never overrun). The FIN is NOT * sent here: it is deferred until the guest has ACKed ALL the response data * (see the ACK path in handleTcp). Rationale — each rx frame triggers a * cross-Worker socket wake of the guest's -517-parked recv coroutine; * sending the data segment and the FIN back-to-back delivered two wakes in * quick succession and raced the coroutine resume (a leaked park slice -> * the hwjs-user-rt "orphan at clear" trap). Serializing data-then-FIN * behind a full guest ACK round-trip gives the recv resume time to settle. * wget completes on Content-Length regardless of the FIN timing. */ pumpResponse(flow) { if (!flow.resp || flow.closed) return; const total = flow.resp.length; for (; ; ) { const sentSoFar = flow.sndNxt - flow.respStartSeq >>> 0; const inflight = flow.sndNxt - flow.sndUna >>> 0; const remaining = total - sentSoFar; if (remaining <= 0) break; const windowRoom = sendRoom(flow, inflight); if (windowRoom <= 0) break; const chunk = Math.min(TCP_MSS, remaining, windowRoom); const seg = flow.resp.subarray(sentSoFar, sentSoFar + chunk); this.sendTcp(flow, 24, seg); flow.sndNxt = flow.sndNxt + chunk >>> 0; } this.maybeFin(flow); } /** Send the FIN once every response byte has been ACKed by the guest. */ maybeFin(flow) { if (!flow.resp || flow.finSent || flow.closed) return; const total = flow.resp.length; const sentAll = flow.sndNxt - flow.respStartSeq >>> 0 >= total; const ackedBytes = flow.sndUna - flow.respStartSeq >>> 0; if (sentAll && ackedBytes >= total) { this.sendTcp(flow, 17, null); flow.sndNxt = flow.sndNxt + 1 >>> 0; flow.finSent = true; this.opts.info(`TCP: response fully ACKed, FIN ${flow.key}`); } } rst(flow) { this.sendTcp(flow, 4, null); flow.closed = true; if (flow.conn) { flow.conn.close("rst"); flow.conn = null; } if (flow.proxy) this.proxyAbort(flow, "rst"); this.flows.delete(flow.key); } /* ------------------------------ flow relay ------------------------------ */ /** Open the per-flow NaaS uplink for a terminated non-:80 TCP flow and wire * the byte channel. The real uplink connects to the host:port and splices * bytes; the refusing stub closes immediately (loud) when VPN is off. */ openRelay(flow) { const host = this.ipToName.get(fmtIp(flow.serverIp)) ?? fmtIp(flow.serverIp); const session = { proto: "tcp", host, port: flow.serverPort }; this.opts.info( `RELAY: open ${flow.key} -> ${host}:${flow.serverPort} via NaaS uplink` ); const conn = this.opts.naas.open(session); flow.conn = conn; conn.onData((bytes) => { if (flow.closed || bytes.length === 0) return; flow.outChunks.push(bytes); flow.outLen += bytes.length; this.pumpRelay(flow); }); conn.onWritable(() => { if (flow.closed) return; if (flow.advWnd !== RX_WINDOW) { flow.advWnd = RX_WINDOW; this.sendTcp(flow, 16, null); } }); conn.onClose((code2, reason) => { if (flow.closed) return; flow.relayClosed = true; flow.conn = null; this.opts.info( `RELAY: close ${flow.key} (${host}:${flow.serverPort}) code=${code2} ${reason}` ); const nothingSent = flow.sndNxt - flow.respStartSeq >>> 0 === 0; if (code2 !== 0 && nothingSent && flow.outLen === 0) { this.rst(flow); return; } if (flow.outLen > 0) this.pumpRelay(flow); else this.maybeFinRelay(flow); }); } /** Guest → relay: hand the guest's bytes to the uplink. If the uplink * backpressures, shrink the advertised window to 0 so the guest stops * sending (reflected on the ACK we send next). Never drops. */ relayGuestData(flow, bytes) { if (!flow.conn) return; const writable = flow.conn.send(bytes); if (!writable) flow.advWnd = 0; } /** Segment queued relay→guest bytes into in-order TCP data segments, * respecting the guest's advertised window (no-tick: never overrun). Bytes * are consumed from the queue as sent (the reliable in-process path does not * retransmit); `conn.ack(n)` returns flow-control credit to the relay. */ pumpRelay(flow) { if (flow.closed) return; for (; ; ) { if (flow.outLen <= 0) break; const inflight = flow.sndNxt - flow.sndUna >>> 0; const windowRoom = sendRoom(flow, inflight); if (windowRoom <= 0) break; const n = Math.min(TCP_MSS, flow.outLen, windowRoom); const seg = this.takeFromQueue(flow, n); this.sendTcp(flow, 24, seg); flow.sndNxt = flow.sndNxt + n >>> 0; flow.conn?.ack(n); } this.maybeFinRelay(flow); } /** Remove and return up to `n` bytes from the front of the outbound queue. */ takeFromQueue(flow, n) { const out = new Uint8Array(n); let filled = 0; while (filled < n && flow.outChunks.length) { const head = flow.outChunks[0]; const take = Math.min(head.length, n - filled); out.set(head.subarray(0, take), filled); filled += take; if (take === head.length) flow.outChunks.shift(); else flow.outChunks[0] = head.subarray(take); } flow.outLen -= filled; return filled === n ? out : out.subarray(0, filled); } /** FIN the guest once the relay closed and all its bytes have been sent. */ maybeFinRelay(flow) { if (flow.finSent || flow.closed) return; if (!flow.relayClosed) return; if (flow.outLen > 0) return; this.sendTcp(flow, 17, null); flow.sndNxt = flow.sndNxt + 1 >>> 0; flow.finSent = true; this.opts.info(`RELAY: drained, FIN ${flow.key}`); } /* ------------------------- egress gateway proxy ------------------------- */ /* * PLAN-BRINTOS-FS-GUEST-ROOT Track N. One `"proxy"` flow == one keep-alive * client connection to the gateway (brintos-fs pools exactly one). Requests * are parsed INCREMENTALLY as segments arrive (contrast the buffered `:80` * mode); bodies stream upstream (buffered only when small with a known * Content-Length — that shape works on every fetch); responses stream back * honoring the guest's advertised window, so backpressure propagates to the * origin. Every refusal is synthesized with an `X-Brintos-Gateway-*` header * AND one host log line (never-silent), and closes the connection so the * de-framing of an unread request body can never desynchronize keep-alive. */ /** Guest → gateway bytes: buffer, then drive the parser/de-framer. */ proxyData(flow, bytes) { const p = flow.proxy; if (p.closing) return; p.buf.push(bytes); p.bufLen += bytes.length; this.proxyDrive(flow); this.proxyRecomputeWindow(flow, false); } /** Run the request parser until it needs more bytes (or the connection is * serialized behind an outstanding response). */ proxyDrive(flow) { const p = flow.proxy; for (; ; ) { if (flow.closed || p.closing) return; if (p.phase === "head") { if (p.respActive) return; if (p.bufLen === 0) return; const buf = concat(p.buf, p.bufLen); const end = findHeaderEnd(buf); if (end < 0) { if (p.bufLen > PROXY_HEAD_MAX) { this.proxySynth( flow, 431, "head-too-large", `request head exceeds ${PROXY_HEAD_MAX} bytes` ); } return; } p.buf = end < buf.length ? [buf.subarray(end)] : []; p.bufLen = buf.length - end; this.proxyBeginRequest(flow, asciiOf(buf.subarray(0, end))); continue; } if (!this.proxyConsumeBody(flow)) return; } } /** Parse one request head; refuse (attributed) or dispatch. */ proxyBeginRequest(flow, headText) { const p = flow.proxy; p.requests++; this.gatewayRequests++; const gw = this.gateway; const lines = headText.split("\r\n"); const m = /^([A-Za-z]+)\s+(\S+)\s+HTTP\/1\.([01])$/.exec(lines[0] ?? ""); const rec = this.gwBegin( flow, m ? m[1].toUpperCase() : "?", m ? m[2] : (lines[0] ?? "").slice(0, 256) ); p.pendingRec = rec; if (!m) { this.proxySynth( flow, 400, "malformed-request-line", `malformed request line "${(lines[0] ?? "").slice(0, 128)}"` ); return; } const method = m[1].toUpperCase(); const target = m[2]; const httpMinor = m[3] === "1" ? 1 : 0; if (method === "CONNECT") { this.proxySynth( flow, 405, "connect-not-supported", "CONNECT tunneling is not supported: the gateway is an allowlist-only absolute-form HTTP proxy (TLS terminates in the host's fetch)" ); return; } if (target.startsWith("/")) { this.proxySynth( flow, 400, "origin-form-not-supported", "origin-form request refused: the gateway accepts absolute-form (http[s]://host/path) targets only" ); return; } let url; try { url = new URL(target); } catch { this.proxySynth( flow, 400, "malformed-target", `unparseable request target "${target.slice(0, 256)}"` ); return; } if (url.protocol !== "http:" && url.protocol !== "https:") { this.proxySynth( flow, 400, "unsupported-scheme", `scheme ${url.protocol} refused (http/https only)` ); return; } rec.origin = url.origin; rec.path = url.pathname + url.search; let doorRouted = false; if (this.appOriginDoorOpens !== null && this.gatewayAppOrigin !== null && url.origin === this.gatewayAppOrigin) { try { doorRouted = this.appOriginDoorOpens(url.pathname) === true; } catch (e) { this.proxySynth( flow, 502, "fsapi-door-unreadable", `${method} ${url.pathname}: this machine's filesystem-API door could not say whether it opens this path \u2014 its route table threw "${(e instanceof Error ? e.message : String(e)).slice(0, 160)}". Nothing was fetched and nothing was sent over the capability port.` ); return; } } if (doorRouted && !this.doorRouteNoted) { this.doorRouteNoted = true; this.opts.info( `GATEWAY: DOOR 1 IS ROUTING \u2014 ${method} ${url.pathname} on ${url.origin} is this machine's own filesystem API, so the ALLOWLIST is not its gate: ${url.origin} is deliberately not on it (the product origin is never plain egress) and this call never leaves over the network \u2014 it goes to the fsapi capability port. The read-only gate below still applies and may still refuse it. Further /fs requests take the same arm, silently.` ); } if (!doorRouted && !this.gatewayOrigins.has(url.origin)) { this.noteRootFsRefusal(method, url, "origin-not-allowlisted"); this.proxySynth( flow, 403, "origin-not-allowlisted", `origin ${url.origin} is not in this machine's egress allowlist`, { blocked: url.origin } ); return; } const mutating = method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE"; let needsOpProof = false; if (gw.readOnly && mutating) { const intent = this.gatewayAppOrigin !== null && this.gatewayAppOrigin === url.origin ? fsApiReadIntent(url.pathname) : "write"; if (intent === "write") { this.proxySynth( flow, 403, "read-only", `${method} ${url.pathname} refused: this machine session holds no machine-write checkout, and this route mutates the repository` ); return; } needsOpProof = intent === "op-in-body"; } if (this.gatewayActive >= (gw.maxConcurrent ?? PROXY_MAX_CONCURRENT)) { this.noteRootFsRefusal(method, url, "too-many-requests"); this.proxySynth( flow, 503, "too-many-requests", `concurrent proxied fetch ceiling reached (${this.gatewayActive})`, { retryAfter: 1 } ); return; } const strip = new Set(HOP_BY_HOP); strip.add("host"); strip.add("expect"); strip.add("content-length"); strip.add("x-brintos-machine-write"); strip.add("x-brintos-checkout-token"); strip.add("x-brintos-fetch-id"); let contentLength = null; let chunked = false; let wantClose = httpMinor === 0; let expectContinue = false; const headers = {}; const seen = /* @__PURE__ */ new Map(); for (let i = 1; i < lines.length; i++) { const line = lines[i]; if (!line) continue; const ci = line.indexOf(":"); if (ci <= 0) { this.proxySynth( flow, 400, "malformed-header", `malformed header line "${line.slice(0, 128)}"` ); return; } const name2 = line.slice(0, ci).trim(); const value = line.slice(ci + 1).trim(); const lname = name2.toLowerCase(); if (lname === "connection") { for (const tok of value.toLowerCase().split(",")) { const t = tok.trim(); if (t === "close") wantClose = true; else if (t === "keep-alive") { if (httpMinor === 0) wantClose = false; } if (t) strip.add(t); } continue; } if (lname === "content-length") { if (!/^\d+$/.test(value)) { this.proxySynth( flow, 400, "malformed-content-length", `malformed Content-Length "${value.slice(0, 64)}"` ); return; } contentLength = parseInt(value, 10); continue; } if (lname === "transfer-encoding") { if (value.toLowerCase().trim() !== "chunked") { this.proxySynth( flow, 501, "unsupported-transfer-encoding", `Transfer-Encoding "${value.slice(0, 64)}" not implemented (chunked only)` ); return; } chunked = true; continue; } if (lname === "expect" && value.toLowerCase().includes("100-continue")) { expectContinue = true; } if (lname === "x-brintos-fetch-id") { rec.fetchId = value.slice(0, 64); continue; } if (strip.has(lname)) continue; const stored = seen.get(lname); if (stored !== void 0) headers[stored] = `${headers[stored]}, ${value}`; else { seen.set(lname, name2); headers[name2] = value; } } if (chunked) contentLength = null; if (gw.checkout && mutating && this.gatewayAppOrigin === url.origin && isFsApiPath(url.pathname)) { headers["X-Brintos-Machine-Write"] = "1"; headers["X-Brintos-Checkout-Token"] = gw.checkout.token; } const bodyMode = chunked ? "chunked" : contentLength !== null && contentLength > 0 ? "clen" : "none"; if (needsOpProof && !(bodyMode === "clen" && contentLength <= PROXY_BODY_BUFFER_MAX)) { this.noteRootFsRefusal(method, url, "read-only-op-unprovable"); this.proxySynth( flow, 403, "read-only-op-unprovable", `${method} ${url.pathname} refused: this machine session holds no machine-write checkout, so this route is allowed only for op="get", and a ${chunked ? "chunked" : contentLength === null || contentLength <= 0 ? "bodyless" : "oversized"} request body cannot be inspected for it` ); return; } const req = { method, url, rec, headers, bodyMode, bodyRemaining: contentLength ?? 0, chunk: { stage: "size", remaining: 0, line: "" }, bodyChunks: null, bodyChunksLen: 0, bufferedCharge: 0, bodyCtrl: null, bodyDone: false, opProof: needsOpProof, abort: new AbortController() }; p.req = req; p.closing = p.closing || wantClose; if (expectContinue) this.proxyEnqueue(flow, asciiBytes("HTTP/1.1 100 Continue\r\n\r\n")); if (req.bodyMode === "none") { req.bodyDone = true; this.proxyDispatch(flow, null, false); return; } p.phase = "body"; if (req.bodyMode === "clen" && req.bodyRemaining <= PROXY_BODY_BUFFER_MAX) { if (this.gatewayBufferedBytes + req.bodyRemaining > PROXY_BUFFERED_BODY_MAX) { this.proxySynth( flow, 503, "too-much-buffered", `buffered request-body budget exhausted (${this.gatewayBufferedBytes}+${req.bodyRemaining} > ${PROXY_BUFFERED_BODY_MAX} bytes)`, { retryAfter: 1 } ); return; } this.gatewayBufferedBytes += req.bodyRemaining; req.bufferedCharge = req.bodyRemaining; req.bodyChunks = []; return; } const stream = new ReadableStream( { start: (c) => { req.bodyCtrl = c; }, pull: () => { this.proxyRecomputeWindow(flow, true); } }, { highWaterMark: PROXY_BODY_STREAM_HWM, size: (c) => c.byteLength } ); this.proxyDispatch(flow, stream, true); } /** De-frame guest body bytes (Content-Length counting or de-chunking) into * the upstream body. Returns false when more bytes are needed. */ proxyConsumeBody(flow) { const p = flow.proxy; const req = p.req; if (!req) { p.buf = []; p.bufLen = 0; return false; } if (req.bodyMode === "clen") { if (req.bodyRemaining > 0) { if (p.bufLen === 0) return false; const n = Math.min(p.bufLen, req.bodyRemaining); this.proxyRouteBody(flow, takeProxyBytes(p, n)); req.bodyRemaining -= n; } if (req.bodyRemaining > 0) return false; this.proxyBodyEnd(flow); return true; } for (; ; ) { const st = req.chunk; if (st.stage === "size" || st.stage === "trailer") { const line = takeProxyLine(p); if (line === null) { if (p.bufLen > PROXY_HEAD_MAX) { this.proxyFrameError(flow, "chunk line exceeds sanity bound"); return false; } return false; } if (st.stage === "size") { const semi = line.indexOf(";"); const hex = (semi >= 0 ? line.slice(0, semi) : line).trim(); if (!/^[0-9a-fA-F]+$/.test(hex)) { this.proxyFrameError(flow, `malformed chunk size "${hex.slice(0, 32)}"`); return false; } const size = parseInt(hex, 16); if (size === 0) { st.stage = "trailer"; continue; } st.remaining = size; st.stage = "data"; continue; } if (line === "") { this.proxyBodyEnd(flow); return true; } continue; } if (st.stage === "data") { if (p.bufLen === 0) return false; const n = Math.min(p.bufLen, st.remaining); this.proxyRouteBody(flow, takeProxyBytes(p, n)); st.remaining -= n; if (st.remaining > 0) return false; st.stage = "data-end"; } if (st.stage === "data-end") { if (p.bufLen < 2) return false; const crlf = takeProxyBytes(p, 2); if (crlf[0] !== 13 || crlf[1] !== 10) { this.proxyFrameError(flow, "missing CRLF after chunk data"); return false; } st.stage = "size"; } } } /** Route de-framed request-body bytes to the buffered or streamed body. */ proxyRouteBody(flow, bytes) { const req = flow.proxy.req; req.rec.up += bytes.length; this.gwTotalUp += bytes.length; if (req.bodyChunks) { req.bodyChunks.push(bytes); req.bodyChunksLen += bytes.length; return; } if (req.bodyCtrl) { try { req.bodyCtrl.enqueue(bytes); } catch { } } } /** The guest's request body is fully received. */ proxyBodyEnd(flow) { const p = flow.proxy; const req = p.req; req.bodyDone = true; p.phase = "head"; if (req.bodyChunks) { const body = concat(req.bodyChunks, req.bodyChunksLen); req.bodyChunks = null; this.proxyRefundBuffered(req); if (req.opProof && !bodyDeclaresOpGet(body)) { this.proxySynth( flow, 403, "read-only", `${req.method} ${req.url.pathname} refused: this machine session holds no machine-write checkout, so this route is allowed only for op="get"` ); return; } this.proxyDispatch(flow, body.length > 0 ? body : null, false); } else if (req.bodyCtrl) { try { req.bodyCtrl.close(); } catch { } req.bodyCtrl = null; } } /** Unrecoverable request-framing error mid-body: loud + RST (the upstream * fetch, if any, is aborted by rst→proxyAbort). */ proxyFrameError(flow, why) { this.opts.info(`GATEWAY: request framing error (${why}) \u2014 RST ${flow.key}`); this.rst(flow); } /** Start the upstream fetch for the current request. */ proxyDispatch(flow, body, streamed) { const p = flow.proxy; p.respActive = true; p.activeHeld = true; this.gatewayActive++; void this.proxyFetch(flow, p.req, body, streamed); } async proxyFetch(flow, req, body, streamed) { const p = flow.proxy; const url = req.url.href; this.opts.info(`GATEWAY: ${req.method} ${url} (flow ${flow.key})`); try { const res = await this.fetchImpl(url, { method: req.method, headers: req.headers, body, // NOTE: redirect:"manual" behaves differently across runtimes — in // Node/undici it yields a real 3xx with a Location we re-frame to the // guest, but in a browser it yields an *opaque-redirect* response // (status 0, no headers). Handling that browser divergence is a // separate live-gate verification item (fix #5, tracked by the // manager) — do not "fix" it here. redirect: "manual", signal: req.abort.signal, ...streamed ? { duplex: "half" } : {} }); const headMs = Date.now() - req.rec.startedMs; if (flow.closed) { this.opts.info( `GATEWAY: ${res.status} for ${req.method} ${url} arrived after ${headMs} ms but flow ${flow.key} is already closed \u2014 the response is dropped` ); return; } this.opts.info( `GATEWAY: ${res.status} ${reasonFor(res.status)} head for ${req.method} ${url} in ${headMs} ms (flow ${flow.key})` ); this.proxyWriteRespHead(flow, req, res); const noBody = req.method === "HEAD" || res.status === 204 || res.status === 304; if (noBody) { if (res.body) void res.body.cancel().catch(() => void 0); this.proxyRespEnd(flow); } else if (res.body && typeof res.body.getReader === "function") { p.respReader = res.body.getReader(); void this.proxyPumpUpstream(flow); } else { const buf = new Uint8Array(await res.arrayBuffer()); if (buf.length > 0) this.proxyEnqueueBody(flow, buf); this.proxyRespEnd(flow); } } catch (e) { const msg = e instanceof Error ? e.message : String(e); if (flow.closed) { this.opts.info( `GATEWAY: ${req.method} ${url} failed after ${Date.now() - req.rec.startedMs} ms (${msg}) but flow ${flow.key} is already closed \u2014 nothing to report to the guest` ); return; } if (!p.respHeadWritten) { this.opts.info(`GATEWAY: upstream fetch failed: ${msg} (${req.method} ${url})`); this.proxyReleaseActive(flow); p.respActive = false; this.proxySynth( flow, 502, "upstream-fetch-failed", `upstream fetch failed: ${msg.slice(0, 256)}` ); } else { this.gwEnd(req.rec, "failed", "upstream-failed-mid-response"); this.opts.info(`GATEWAY: upstream failed mid-response: ${msg} \u2014 RST ${flow.key}`); this.rst(flow); } } } /** Serialize the upstream response head toward the guest, choosing framing: * pass Content-Length through when trustworthy, else re-frame chunked. */ proxyWriteRespHead(flow, req, res) { const p = flow.proxy; req.rec.status = res.status; req.rec.headMs = Date.now(); const entries = headerEntries(res.headers); let contentLength = null; let contentEncoded = false; const out = []; for (const [k, v] of entries) { const lk = k.toLowerCase(); if (HOP_BY_HOP.has(lk)) continue; if (lk === "content-length") { if (/^\d+$/.test(v.trim())) contentLength = parseInt(v.trim(), 10); continue; } if (lk === "content-encoding") { contentEncoded = true; continue; } out.push([k, v]); } if (contentEncoded) contentLength = null; const noBody = req.method === "HEAD" || res.status === 204 || res.status === 304; const reason = res.statusText && res.statusText.length > 0 ? res.statusText : reasonFor(res.status); let head = `HTTP/1.1 ${res.status} ${reason}\r `; for (const [k, v] of out) head += `${k}: ${v}\r `; if (noBody) { if (req.method === "HEAD" && contentLength !== null) head += `Content-Length: ${contentLength}\r `; p.respChunked = false; p.respBytesExpected = 0; } else if (contentLength !== null) { head += `Content-Length: ${contentLength}\r `; p.respChunked = false; p.respBytesExpected = contentLength; } else { head += `Transfer-Encoding: chunked\r `; p.respChunked = true; p.respBytesExpected = -1; } head += `Connection: ${p.closing ? "close" : "keep-alive"}\r \r `; req.rec.contentLength = contentLength ?? -1; p.respBytesSent = 0; p.respHeadWritten = true; this.proxyEnqueue(flow, asciiBytes(head)); } /** Pull the upstream response body only while the guest-bound queue is * below the low-water mark — THE backpressure link to the origin. */ async proxyPumpUpstream(flow) { const p = flow.proxy; if (p.reading) return; p.reading = true; try { while (!flow.closed && p.respReader) { const red = this.gateway?.redDisableBackpressure === true; if (!red && flow.outLen >= PROXY_RESP_LOWAT) break; const reader = p.respReader; const { value, done } = await reader.read(); if (flow.closed || p.respReader !== reader) break; if (done) { p.respReader = null; this.proxyRespEnd(flow); break; } if (value && value.length > 0) this.proxyEnqueueBody(flow, value); this.pumpProxy(flow); } } catch (e) { if (!flow.closed) { const msg = e instanceof Error ? e.message : String(e); this.opts.info(`GATEWAY: upstream body read failed (${msg}) \u2014 RST ${flow.key}`); this.rst(flow); } } finally { p.reading = false; } } /** Queue raw guest-bound bytes and segment what the window allows. */ proxyEnqueue(flow, bytes) { flow.outChunks.push(bytes); flow.outLen += bytes.length; this.pumpProxy(flow); } /** Queue response-BODY bytes with the framing chosen at head time. */ proxyEnqueueBody(flow, bytes) { const p = flow.proxy; if (p.req) p.req.rec.down += bytes.length; this.gwTotalDown += bytes.length; if (p.respChunked) { flow.outChunks.push(asciiBytes(bytes.length.toString(16) + "\r\n")); flow.outChunks.push(bytes); flow.outChunks.push(asciiBytes("\r\n")); flow.outLen += bytes.length + bytes.length.toString(16).length + 4; } else { p.respBytesSent += bytes.length; flow.outChunks.push(bytes); flow.outLen += bytes.length; } this.pumpProxy(flow); } /** The upstream body is exhausted: close the response framing. */ proxyRespEnd(flow) { const p = flow.proxy; if (p.respChunked) { this.proxyEnqueue(flow, asciiBytes("0\r\n\r\n")); } else if (p.respBytesExpected >= 0 && p.respBytesSent !== p.respBytesExpected) { this.opts.info( `GATEWAY: upstream body ${p.respBytesSent}B != Content-Length ${p.respBytesExpected}B \u2014 closing ${flow.key}` ); p.closing = true; } this.proxyFinishRequest(flow); } /** Response complete: release the slot, reset per-request state, and either * close (refusals / Connection: close) or serve the next request. */ proxyFinishRequest(flow) { const p = flow.proxy; if (p.req) { if (p.req.rec.state === "pending") this.opts.info( `GATEWAY: ${p.req.rec.status} complete for ${p.req.method} ${p.req.url.href} \u2014 ${p.req.rec.down} body byte(s) to the guest in ${Date.now() - p.req.rec.startedMs} ms (flow ${flow.key})` ); this.gwEnd(p.req.rec, "done"); } p.pendingRec = null; p.respActive = false; p.respHeadWritten = false; p.respChunked = false; p.respBytesExpected = -1; p.respBytesSent = 0; p.respReader = null; p.req = null; this.proxyReleaseActive(flow); this.proxyRecomputeWindow(flow, true); if (p.closing || p.guestFin) { this.maybeFinProxy(flow); return; } this.proxyDrive(flow); } /** * A gateway refusal landed on the app origin's OWN fs API and it was NOT a * restriction this machine was configured with — the root filesystem is * being refused something it needs. Say so, once, in a full sentence. * * WHY THIS EXISTS. Twice now a machine that could not reach its own fs API * has been debugged as a filesystem or a network problem, because the guest * only ever reports what it sees: a mount that times out, or EIO on the * first binary it execs. The per-refusal `GATEWAY-REFUSE:` line above states * the mechanism but not the consequence, and it scrolls past in a boot that * emits thousands. This line names the consequence, once, so nobody has to * infer that a refusal here and "the machine is hung" are the same event. * * A write refused on a read-only session is deliberately NOT reported here: * it is what a spectator machine is FOR, it is narrated once at boot, and a * warning that fires on correct behaviour is a warning nobody reads. */ rootFsRefusalNoted = false; noteRootFsRefusal(method, url, errToken) { if (this.rootFsRefusalNoted) return; if (this.gatewayAppOrigin === null || this.gatewayAppOrigin !== url.origin) return; if (!isFsApiPath(url.pathname)) return; this.rootFsRefusalNoted = true; this.opts.info( `GATEWAY: REFUSED A ROOT-FILESYSTEM REQUEST \u2014 ${method} ${url.pathname} (${errToken}). This machine's root is served by brintos-fs over THIS gateway, so the guest will report this as an I/O error or a mount timeout, not as a network failure. The cause is here, not in the filesystem. (Further refusals are logged individually above.)` ); } /** Synthesize an attributed refusal (always `Connection: close` so an * unread request body can never desync keep-alive framing). */ proxySynth(flow, status, errToken, message, extra) { const p = flow.proxy; this.gatewayRefusals++; const rec = p.req?.rec ?? p.pendingRec; if (rec) { rec.status = status; this.gwEnd(rec, "refused", errToken); } p.pendingRec = null; const bodyText = `${message} `; let head = `HTTP/1.1 ${status} ${reasonFor(status)}\r X-Brintos-Gateway-Error: ${errToken}\r `; if (extra?.blocked) head += `X-Brintos-Gateway-Blocked: ${extra.blocked}\r `; if (extra?.retryAfter !== void 0) head += `Retry-After: ${extra.retryAfter}\r `; head += `Content-Type: text/plain\r Content-Length: ${bodyText.length}\r Connection: close\r \r `; this.opts.info( `GATEWAY-REFUSE: ${status} ${errToken}: ${message} (flow ${flow.key})` ); p.closing = true; p.req = null; p.phase = "head"; this.proxyEnqueue(flow, asciiBytes(head + bodyText)); this.maybeFinProxy(flow); } /** Segment queued gateway bytes into TCP, honoring the guest's window; then * re-arm the upstream reader / FIN as appropriate. */ pumpProxy(flow) { if (flow.closed || !flow.proxy) return; for (; ; ) { if (flow.outLen <= 0) break; const inflight = flow.sndNxt - flow.sndUna >>> 0; const windowRoom = sendRoom(flow, inflight); if (windowRoom <= 0) break; const n = Math.min(TCP_MSS, flow.outLen, windowRoom); const seg = this.takeFromQueue(flow, n); this.sendTcp(flow, 24, seg); flow.sndNxt = flow.sndNxt + n >>> 0; } const p = flow.proxy; if (p.respReader && flow.outLen < PROXY_RESP_LOWAT) void this.proxyPumpUpstream(flow); this.maybeFinProxy(flow); } /** FIN once the connection is closing and everything has drained. */ maybeFinProxy(flow) { const p = flow.proxy; if (!p || flow.finSent || flow.closed) return; if (!(p.closing || p.guestFin)) return; if (p.respActive || flow.outLen > 0) return; this.sendTcp(flow, 17, null); flow.sndNxt = flow.sndNxt + 1 >>> 0; flow.finSent = true; this.opts.info( `GATEWAY: connection closed ${flow.key} (${p.requests} request(s))` ); if (p.guestFin) this.flows.delete(flow.key); } /** Guest FIN: the client closed its pooled connection (or died mid-body). */ proxyGuestFin(flow) { const p = flow.proxy; p.guestFin = true; const req = p.req; if (req && !req.bodyDone) { this.opts.info( `GATEWAY: guest closed before its request body completed \u2014 aborting upstream (${flow.key})` ); if (req.bodyCtrl) { try { req.bodyCtrl.error(new Error("guest closed the connection early")); } catch { } req.bodyCtrl = null; } this.proxyRefundBuffered(req); req.abort.abort(); this.gwEnd(req.rec, "failed", "guest-closed-mid-request"); p.pendingRec = null; } this.maybeFinProxy(flow); } /** Teardown for RST/rst(): abort upstream work, release the slot. */ proxyAbort(flow, why) { const p = flow.proxy; if (!p) return; if (p.req) { if (p.req.bodyCtrl) { try { p.req.bodyCtrl.error(new Error(`connection aborted (${why})`)); } catch { } p.req.bodyCtrl = null; } this.proxyRefundBuffered(p.req); p.req.abort.abort(); } if (p.respReader) { void p.respReader.cancel().catch(() => void 0); p.respReader = null; } this.gwEnd(p.req?.rec ?? p.pendingRec, "failed", `aborted:${why}`); p.pendingRec = null; this.proxyReleaseActive(flow); } proxyReleaseActive(flow) { const p = flow.proxy; if (p.activeHeld) { p.activeHeld = false; this.gatewayActive--; } } /** FIX #1: refund a request's charge against the global buffered-body budget * (idempotent — a request charges at most once, and every teardown path may * call this). */ proxyRefundBuffered(req) { if (req.bufferedCharge > 0) { this.gatewayBufferedBytes -= req.bufferedCharge; req.bufferedCharge = 0; } } /** Reflect upstream-request backpressure and parse-backlog into the * advertised window; optionally push a window-update ACK on reopen. */ proxyRecomputeWindow(flow, sendUpdate) { const p = flow.proxy; if (!p || flow.closed) return; const ctrl = p.req?.bodyCtrl ?? null; const streamFull = ctrl !== null && ctrl.desiredSize !== null && ctrl.desiredSize <= 0; const backlog = p.bufLen > PROXY_HEAD_MAX; const want = streamFull || backlog ? 0 : RX_WINDOW; if (want !== flow.advWnd) { const reopened = flow.advWnd === 0 && want > 0; flow.advWnd = want; if (reopened && sendUpdate) this.sendTcp(flow, 16, null); } } /** Build + transmit a TCP segment for this flow (server->client). `options` * (SYN-ACK only) must be a multiple of 4 bytes — TCP's data offset counts * 32-bit words. */ sendTcp(flow, flags, payload, options) { const pl = payload ?? EMPTY; const opt = options && options.length ? options : EMPTY; const tcpLen = 20 + opt.length + pl.length; const frame = new Uint8Array(14 + 20 + tcpLen); frame.set(flow.guestMac, 0); frame.set(this.gwMac, 6); frame[12] = 8; frame[13] = 0; const ip = 14; frame[ip] = 69; frame[ip + 1] = 0; writeU16(frame, ip + 2, 20 + tcpLen); writeU16(frame, ip + 4, 0); writeU16(frame, ip + 6, 16384); frame[ip + 8] = 64; frame[ip + 9] = 6; frame.set(flow.serverIp, ip + 12); frame.set(flow.clientIp, ip + 16); const ipc = inetChecksum(frame.subarray(ip, ip + 20)); writeU16(frame, ip + 10, ipc); const tcp = ip + 20; writeU16(frame, tcp, flow.serverPort); writeU16(frame, tcp + 2, flow.clientPort); writeU32(frame, tcp + 4, flow.sndNxt); writeU32(frame, tcp + 8, flow.rcvNxt); frame[tcp + 12] = 5 + opt.length / 4 << 4 & 240; frame[tcp + 13] = flags; writeU16( frame, tcp + 14, flags & 2 ? Math.min(flow.advWnd, 65535) : flow.advWnd >>> flow.rcvWscale & 65535 ); writeU16(frame, tcp + 16, 0); writeU16(frame, tcp + 18, 0); if (opt.length) frame.set(opt, tcp + 20); if (pl.length) frame.set(pl, tcp + 20 + opt.length); const tc = tcpChecksum(flow.serverIp, flow.clientIp, frame.subarray(tcp, tcp + tcpLen)); writeU16(frame, tcp + 16, tc); if (netTrace()) this.opts.info( `TCPTRACE tx ${flow.key} flags=0x${flags.toString(16)} seq=${flow.sndNxt} ack=${flow.rcvNxt} len=${pl.length}` ); this.opts.transmit(frame); } buildUdp(ethDst, ethSrc, ipSrc, ipDst, srcPort, dstPort, payload) { const udpLen = 8 + payload.length; const frame = new Uint8Array(14 + 20 + udpLen); frame.set(ethDst, 0); frame.set(ethSrc, 6); frame[12] = 8; frame[13] = 0; const ip = 14; frame[ip] = 69; writeU16(frame, ip + 2, 20 + udpLen); writeU16(frame, ip + 6, 16384); frame[ip + 8] = 64; frame[ip + 9] = 17; frame.set(ipSrc, ip + 12); frame.set(ipDst, ip + 16); writeU16(frame, ip + 10, inetChecksum(frame.subarray(ip, ip + 20))); const udp = ip + 20; writeU16(frame, udp, srcPort); writeU16(frame, udp + 2, dstPort); writeU16(frame, udp + 4, udpLen); frame.set(payload, udp + 8); writeU16(frame, udp + 6, udpChecksum(ipSrc, ipDst, frame.subarray(udp, udp + udpLen))); return frame; } /* ------------------------------- key gate ------------------------------- */ ensureKey() { if (this.keyOk === void 0) this.keyOk = this.readAndValidateKey(); return this.keyOk; } async readAndValidateKey() { const fs = this.opts.fs; const path = this.opts.keyPath ?? DEFAULT_NET_KEY_PATH; if (!fs) { this.opts.info( `KEY-GATE: no FsView threaded into the net backend \u2014 cannot read ${path}; refusing` ); return false; } let bytes; try { bytes = await readFsFile(fs, path); } catch (e) { this.opts.info( `KEY-GATE: error reading ${path}: ${e instanceof Error ? e.message : String(e)}; refusing` ); return false; } if (!bytes || bytes.length === 0) { this.opts.info(`KEY-GATE: ${path} absent/empty; refusing`); return false; } const text = asciiOf(bytes).trim(); if (!validateNetKey(text)) { this.opts.info( `KEY-GATE: ${path} malformed (expected bnk1.); refusing` ); return false; } this.opts.info(`KEY-GATE: ${path} present + valid \u2014 fetch mapping ENABLED`); return true; } }; function validateNetKey(text) { const m = /^bnk1\.([A-Za-z0-9_-]+)$/.exec(text); if (!m) return false; const b64 = m[1]; const decoded = base64urlDecode(b64); return decoded !== null && decoded.length === 32; } function base64urlDecode(s) { const std = s.replace(/-/g, "+").replace(/_/g, "/"); const pad = std.length % 4 === 0 ? std : std + "=".repeat(4 - std.length % 4); try { if (typeof atob === "function") { const bin = atob(pad); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; } const B = globalThis.Buffer; if (B) return Uint8Array.from(B.from(pad, "base64")); return null; } catch { return null; } } async function readFsFile(fs, absPath) { const parts = absPath.split("/").filter((p) => p.length > 0); let ino = 1; let attr = null; for (const name2 of parts) { const r = await fs.lookup(ino, name2); if (!r) return null; attr = r; ino = r.ino; } if (!attr) return null; const size = attr.size; const chunks = []; let off = 0; const cap = Math.min(size, 1 << 20); while (off < cap) { const want = Math.min(65536, cap - off); const part = await fs.read(ino, off, want); if (!part || part.length === 0) break; chunks.push(Uint8Array.from(part)); off += part.length; if (part.length < want) break; } return concat(chunks, off); } var EMPTY = new Uint8Array(0); function netTrace() { const g = globalThis; return Boolean(g.HWJS_NET_TCPTRACE || g.process?.env?.HWJS_NET_TCPTRACE); } function ipEq(a, b) { return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3]; } function macEq(a, b) { return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5]; } function fmtIp(ip) { return `${ip[0]}.${ip[1]}.${ip[2]}.${ip[3]}`; } function fmtMac(mac) { return Array.from(mac, (b) => b.toString(16).padStart(2, "0")).join(":"); } function swapEth(f) { for (let i = 0; i < 6; i++) { const t = f[i]; f[i] = f[6 + i]; f[6 + i] = t; } } function swapIp(f, ip) { for (let i = 0; i < 4; i++) { const t = f[ip + 12 + i]; f[ip + 12 + i] = f[ip + 16 + i]; f[ip + 16 + i] = t; } } function readU32(b, o) { return (b[o] << 24 | b[o + 1] << 16 | b[o + 2] << 8 | b[o + 3]) >>> 0; } function parseTcpOptions(seg, start, end) { const out = { wscale: null, mss: null, sackOk: false, malformed: false }; let i = start; while (i < end) { const kind = seg[i]; if (kind === TCPOPT_EOL) break; if (kind === TCPOPT_NOP) { i++; continue; } if (i + 1 >= end) { out.malformed = true; break; } const len = seg[i + 1]; if (len < 2 || i + len > end) { out.malformed = true; break; } switch (kind) { case TCPOPT_MSS: if (len === 4 && out.mss === null) out.mss = seg[i + 2] << 8 | seg[i + 3]; break; case TCPOPT_WSCALE: if (len === 3 && out.wscale === null) out.wscale = Math.min(seg[i + 2], TCP_MAX_WSCALE); break; case TCPOPT_SACK_PERM: if (len === 2) out.sackOk = true; break; default: break; } i += len; } return out; } function buildSynAckOptions(gates, peerWscale) { const bytes = []; if (gates.mss) bytes.push(TCPOPT_MSS, 4, OUR_MSS >> 8 & 255, OUR_MSS & 255); if (gates.sackOk) bytes.push(TCPOPT_SACK_PERM, 2); if (gates.wscale && peerWscale !== null) { bytes.push(TCPOPT_NOP, TCPOPT_WSCALE, 3, OUR_WSCALE); } while (bytes.length % 4 !== 0) bytes.push(TCPOPT_NOP); return Uint8Array.from(bytes); } function writeU16(b, o, v) { b[o] = v >> 8 & 255; b[o + 1] = v & 255; } function writeU32(b, o, v) { b[o] = v >>> 24 & 255; b[o + 1] = v >>> 16 & 255; b[o + 2] = v >>> 8 & 255; b[o + 3] = v & 255; } function concat(chunks, total) { const out = new Uint8Array(total); let o = 0; for (const c of chunks) { out.set(c, o); o += c.length; } return out; } function asciiOf(b) { let s = ""; for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i]); return s; } function sendRoom(flow, inflight) { return Math.min(flow.guestWnd, TCP_MAX_INFLIGHT) - inflight; } function seqInWindow(x, una, nxt) { const a = x - una >>> 0; const b = nxt - una >>> 0; return a > 0 && a <= b; } function findHeaderEnd(buf) { for (let i = 3; i < buf.length; i++) { if (buf[i - 3] === 13 && buf[i - 2] === 10 && buf[i - 1] === 13 && buf[i] === 10) return i + 1; } return -1; } function parseContentLength(headerText) { const m = /\r\ncontent-length:\s*(\d+)/i.exec("\r\n" + headerText); return m ? parseInt(m[1], 10) : 0; } function normalizeOrigin(o) { try { const u = new URL(o); return u.origin === "null" ? null : u.origin; } catch { return null; } } function isFsApiPath(pathname) { if (pathname.startsWith("/fs/") || pathname.startsWith("/_blobs/")) return true; return /^\/api\/repos\/[^/]+\/[^/]+\/fs\//.test(pathname); } function fsApiSuffix(pathname) { if (pathname.startsWith("/fs/")) return pathname.slice(3); const m = /^\/api\/repos\/[^/]+\/[^/]+\/fs(\/.*)$/.exec(pathname); return m ? m[1] : null; } function fsApiReadIntent(pathname) { const suffix = fsApiSuffix(pathname); if (suffix === null) return "write"; const route = suffix.endsWith("/") ? suffix.slice(0, -1) : suffix; switch (route) { /* requireRepoAccess(event, 'read'), unconditionally. */ case "/blobs/batch-get": case "/blobs/check": return "read"; /* * `/blobs/get` — THE DOOR'S READ COMPOSITE, and the same defect this * function exists for, one route later. * * It addresses no product endpoint: `blobs-get` is performed by the * embedding page, which forwards `POST /fs/blobs/presign {op:"get"}` * against its binding for authorization — `requireRepoAccess(event, * 'read')` — and only a 2xx lets it answer. So the route this classifies * IS a read, by the same server check that makes `op:"get"` one. * * IT HAD TO BE NAMED HERE OR THE FEATURE WOULD BE DEAD ON ARRIVAL for * exactly the population the 2026-07-27 incident above was about: the * default arm is "write", every anonymous visitor to a public machine holds * no machine-write checkout, and `bfs_api_read_blob_stream` sends this on a * bound mount for EVERY content read. The gateway would have answered * `403 read-only` to the first byte of /sbin/init — a mount that lists its * root and cannot read one file out of it. * * NOT "op-in-body": that arm exists because `/blobs/presign` is a read or a * write depending on `op`, and this route has no such choice — its body is * `{oid}` and nothing else (`blobGetBodyRefusal` refuses any other member), * so there is nothing to defer a verdict for. */ case "/blobs/get": return "read"; /* requireRepoAccess(event, body.op === 'put' ? 'write' : 'read'). */ case "/blobs/presign": case "/blobs/presign-batch": return "op-in-body"; default: return "write"; } } function bodyDeclaresOpGet(body) { if (!body || body.length === 0) return false; try { const parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body)); return typeof parsed === "object" && parsed !== null && parsed.op === "get"; } catch { return false; } } function asciiBytes(s) { const out = new Uint8Array(s.length); for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i) & 255; return out; } function headerEntries(h) { const entries = []; const asHeaders = h; if (!Array.isArray(h) && asHeaders && typeof asHeaders.forEach === "function") { asHeaders.forEach((v, k) => entries.push([k, v])); } else { for (const [k, v] of h) entries.push([k, v]); } return entries; } function takeProxyBytes(p, n) { const out = new Uint8Array(n); let filled = 0; while (filled < n && p.buf.length > 0) { const head = p.buf[0]; const take = Math.min(head.length, n - filled); out.set(head.subarray(0, take), filled); filled += take; if (take === head.length) p.buf.shift(); else p.buf[0] = head.subarray(take); } p.bufLen -= filled; return out; } function findProxyCrlf(p) { let base = 0; let prevCr = false; for (const c of p.buf) { for (let i = 0; i < c.length; i++) { if (prevCr && c[i] === 10) return base + i - 1; prevCr = c[i] === 13; } base += c.length; } return -1; } function takeProxyLine(p) { const at = findProxyCrlf(p); if (at < 0) return null; const raw = takeProxyBytes(p, at + 2); return asciiOf(raw.subarray(0, at)); } function buildHttpResponse(res, body) { const status = res.status; const reason = res.statusText && res.statusText.length ? res.statusText : reasonFor(status); let head = `HTTP/1.1 ${status} ${reason}\r `; const entries = []; const h = res.headers; if (h && typeof h.forEach === "function") { h.forEach((v, k) => entries.push([k, v])); } else { for (const [k, v] of res.headers) entries.push([k, v]); } for (const [k, v] of entries) { const lk = k.toLowerCase(); if (lk === "content-length" || lk === "transfer-encoding" || lk === "connection") continue; head += `${k}: ${v}\r `; } head += `Content-Length: ${body.length}\r `; head += `Connection: close\r `; head += `\r `; const headBytes = new Uint8Array(head.length); for (let i = 0; i < head.length; i++) headBytes[i] = head.charCodeAt(i) & 255; const out = new Uint8Array(headBytes.length + body.length); out.set(headBytes, 0); out.set(body, headBytes.length); return out; } function reasonFor(status) { const m = { 200: "OK", 201: "Created", 204: "No Content", 301: "Moved Permanently", 302: "Found", 304: "Not Modified", 400: "Bad Request", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 431: "Request Header Fields Too Large", 500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable" }; return m[status] ?? "OK"; } function inetChecksum(bytes) { let sum = 0; let i = 0; for (; i + 1 < bytes.length; i += 2) sum += bytes[i] << 8 | bytes[i + 1]; if (i < bytes.length) sum += bytes[i] << 8; while (sum > 65535) sum = (sum & 65535) + (sum >>> 16); return ~sum & 65535; } function l4Checksum(src, dst, proto, segment) { let sum = 0; sum += src[0] << 8 | src[1]; sum += src[2] << 8 | src[3]; sum += dst[0] << 8 | dst[1]; sum += dst[2] << 8 | dst[3]; sum += proto; sum += segment.length; let i = 0; for (; i + 1 < segment.length; i += 2) sum += segment[i] << 8 | segment[i + 1]; if (i < segment.length) sum += segment[i] << 8; while (sum > 65535) sum = (sum & 65535) + (sum >>> 16); return ~sum & 65535; } function tcpChecksum(src, dst, seg) { return l4Checksum(src, dst, 6, seg); } function udpChecksum(src, dst, seg) { const c = l4Checksum(src, dst, 17, seg); return c === 0 ? 65535 : c; } // ../../linux-in-the-browser/hardwarejs/src/devices/virtio_net.ts var VIRTIO_NET_RXQ = 0; var VIRTIO_NET_TXQ = 1; var VIRTIO_NET_HDR_BYTES = 12; var VIRTIO_NET_HDR_NUM_BUFFERS_OFF = 10; var ETH_HLEN = 14; var ETH_P_IP = 2048; var ETH_P_ARP = 2054; var IPV4_MIN_HEADER = 20; var IPV4_SRC_OFF = 12; var IPV4_DST_OFF = 16; var ARP_HTYPE = ETH_HLEN + 0; var ARP_PTYPE = ETH_HLEN + 2; var ARP_HLEN = ETH_HLEN + 4; var ARP_PLEN = ETH_HLEN + 5; var ARP_SPA = ETH_HLEN + 14; var ARP_TPA = ETH_HLEN + 24; var ARP_FRAME_BYTES = ETH_HLEN + 28; var VLAN_HLEN = 4; var ETH_DATA_LEN = 1500; var GOOD_PACKET_LEN = ETH_HLEN + VLAN_HLEN + ETH_DATA_LEN; var MAX_MTU = 65535; var MIN_MTU = 68; var GUEST_PAGE_SIZE = 4096; var PADDED_VNET_HDR_BYTES = 32; var SMALL_RX_BUFFER_BYTES = VIRTIO_NET_HDR_BYTES + GOOD_PACKET_LEN; var VIRTIO_NET_F_MTU = 3; var VIRTIO_NET_F_MRG_RXBUF = 15; var PENDING_RX_MAX_BYTES = 4 * 1024 * 1024; var TX_LOG_FRAMES = 8; var FabricMatcher = class { net32; mask32; network; prefixLength; constructor(network, prefixLength) { if (network.length !== 4) { throw new Error( `virtio-net: a fabric network is 4 bytes, got ${network.length}` ); } if (!Number.isInteger(prefixLength) || prefixLength < 1 || prefixLength > 32) { throw new Error( `virtio-net: fabric prefixLength ${prefixLength} is not 1..32` ); } this.network = network; this.prefixLength = prefixLength; this.mask32 = prefixLength === 32 ? -1 : ~(-1 >>> prefixLength); const n = (network[0] << 24 | network[1] << 16 | network[2] << 8 | network[3]) >>> 0; this.net32 = (n & this.mask32) >>> 0; if (n !== this.net32) { throw new Error( `virtio-net: fabric network ${ipText(network)}/${prefixLength} has host bits set (it means ${ipText(u32ToIp(this.net32))}/${prefixLength})` ); } } /** Does the 4-byte big-endian address at `at` fall in this network? */ contains(frame, at) { const a = (frame[at] << 24 | frame[at + 1] << 16 | frame[at + 2] << 8 | frame[at + 3]) >>> 0; return (a & this.mask32) >>> 0 === this.net32; } get text() { return `${ipText(this.network)}/${this.prefixLength}`; } }; function planeForDestination(frame, fabric) { if (frame.length < ETH_HLEN) return null; const et = frame[12] << 8 | frame[13]; if (et === ETH_P_IP) { if (frame.length < ETH_HLEN + IPV4_MIN_HEADER) return null; return fabric.contains(frame, ETH_HLEN + IPV4_DST_OFF) ? "fabric" : "shim"; } if (et === ETH_P_ARP) { if (frame.length < ARP_FRAME_BYTES) return null; if (frame[ARP_HTYPE] !== 0 || frame[ARP_HTYPE + 1] !== 1 || (frame[ARP_PTYPE] << 8 | frame[ARP_PTYPE + 1]) !== ETH_P_IP || frame[ARP_HLEN] !== 6 || frame[ARP_PLEN] !== 4) { return null; } return fabric.contains(frame, ARP_TPA) ? "fabric" : "shim"; } return null; } function planeForSource(frame, fabric) { if (frame.length < ETH_HLEN) return null; const et = frame[12] << 8 | frame[13]; if (et === ETH_P_IP) { if (frame.length < ETH_HLEN + IPV4_MIN_HEADER) return null; return fabric.contains(frame, ETH_HLEN + IPV4_SRC_OFF) ? "fabric" : "shim"; } if (et === ETH_P_ARP) { if (frame.length < ARP_FRAME_BYTES) return null; return fabric.contains(frame, ARP_SPA) ? "fabric" : "shim"; } return null; } function u32ToIp(x) { return Uint8Array.from([x >>> 24 & 255, x >>> 16 & 255, x >>> 8 & 255, x & 255]); } function ipText(ip) { return `${ip[0]}.${ip[1]}.${ip[2]}.${ip[3]}`; } function bigRxBufferCapacity(mtu) { const skbFrags = Math.ceil(mtu / GUEST_PAGE_SIZE); return VIRTIO_NET_HDR_BYTES + (GUEST_PAGE_SIZE - PADDED_VNET_HDR_BYTES) + skbFrags * GUEST_PAGE_SIZE; } function rxModeFor(mtu, mergeRxBuf) { if (mergeRxBuf) return "merged"; return mtu > ETH_DATA_LEN ? "big" : "small"; } var VirtioNetBackend = class { constructor(opts) { this.opts = opts; this.mem = new GuestMemory(opts); this.mtu = opts.mtu ?? ETH_DATA_LEN; if (!Number.isInteger(this.mtu) || this.mtu < MIN_MTU || this.mtu > MAX_MTU) { throw new Error( `virtio-net: mtu ${this.mtu} outside MIN_MTU..MAX_MTU (${MIN_MTU}..${MAX_MTU}) \u2014 drivers/net/virtio_net.c would refuse it` ); } this.mergeRxBuf = opts.mergeRxBuf === true; this.expectedRxMode = rxModeFor(this.mtu, this.mergeRxBuf); this.link = opts.link ?? null; this.fabric = opts.fabric ?? null; if (this.link && this.fabric) { throw new Error( `virtio-net: both \`link\` and \`fabric\` were given. \`link\` binds the WHOLE NIC to a brintos-link/1 endpoint and leaves the shim inert; \`fabric\` runs both planes on one NIC split by destination. Two answers to "what carries a frame off this NIC" is a device whose behaviour depends on which branch ran first. Use fabricPlaneOverLink() if you meant the second.` ); } this.fabricNet = this.fabric ? new FabricMatcher(this.fabric.network, this.fabric.prefixLength) : null; this.naas = opts.naas ?? new StubNaasUplink({ onEvent: (s) => this.info(s) }); this.shim = new NetShim({ /* The shim's ONE exit, attributed. With no fabric this is exactly * transmitToGuest; with one it is also where a shim answering on a fabric * address would be caught. */ transmit: (frame) => this.injectFrom("shim", frame), info: (s) => this.info(s), naas: this.naas, ...opts.packetUplink ? { packetUplink: opts.packetUplink } : {}, fetchImpl: opts.fetchImpl, ...opts.httpPortMapping !== void 0 ? { httpPortMapping: opts.httpPortMapping } : {}, ...opts.gateway !== void 0 ? { gateway: opts.gateway } : {}, fs: opts.fs, onError: (e) => this.opts.onError?.(e) }); if (this.link) { this.link.onFrames((frames) => { for (const f of frames) this.transmitToGuest(f); }); this.link.onCredit(() => { if (this.txCreditStops > 0) void this.drainTx(); }); this.link.start(); this.info( `bound to a brintos-link fabric (mtu ${this.mtu}, rx mode ${this.expectedRxMode}); the MITM shim is inert on this NIC` ); } if (this.fabric && this.fabricNet) { this.fabric.onFrames((frames) => { for (const f of frames) this.injectFrom("fabric", f); }); this.fabric.onReady?.(() => { if (this.fabricTxStops > 0) void this.drainTx(); }); this.info( `two planes on one NIC: destinations in ${this.fabricNet.text} go to the storage fabric, everything else to the MITM shim` + (opts.gateway ? ` (egress gateway on :${opts.gateway.port ?? 3128})` : "") + `. A frame naming neither is refused, not guessed at.` ); } } opts; /** The ONE way this device addresses guest RAM. See guest_memory.ts. */ mem; queues = /* @__PURE__ */ new Map(); /** Host->guest frames awaiting a free rx buffer. */ pendingRx = []; /** Total bytes queued in `pendingRx` (mirrors it; drives the overflow cap). */ pendingRxBytes = 0; /** Gate-visible counters. */ txFrames = 0; rxFrames = 0; /** Frames dropped because pendingRx hit PENDING_RX_MAX_BYTES (guest stalled * or dead). Never a silent drop: each is attributed (rate-limited log). */ rxOverflowDrops = 0; /** Times pumpRx could not place a frame because the guest's rx queue was * not ready, or had no free buffer. Gate-visible; see the note on * `reportRxStall` for why these are `info` and not `dbg`. */ rxStalls = 0; /** tx batches handed to the link. framesOut/txBatches is the batch size * actually achieved — the number PLAN §3 exists to raise. */ txBatches = 0; /** Times drainTx stopped early because the link held no credit. Not a drop: * the chains stay in the guest's avail ring. */ txCreditStops = 0; /** Buffers consumed by the merged-rx path beyond the first, per frame. */ rxMergedBuffers = 0; rxStallReports = 0; rxStalled = false; loggedTx = 0; /** What the guest is actually doing, once it has posted a buffer. Null * until then — never guessed at from the offer. */ observedRxMode = null; /** The lockstep violation that stopped this device, if any. Terminal. */ negotiationFault = null; negotiationDrops = 0; featureCrossCheckDone = false; mtu; mergeRxBuf; /** The rx mode this host was CONFIGURED for. */ expectedRxMode; /** The MITM shim + its NaaS forward boundary (gate reads the counter). */ shim; naas; /** The bound fabric, if any. Frames go here instead of to the shim. */ link; /** The fabric plane on a SHARED NIC, if any. Mutually exclusive with `link`. */ fabric; /** The prefix test the demux runs. Null unless `fabric` is set. */ fabricNet; /** Gate-visible demux counters. Every frame lands in exactly one of these. */ fabricTxFrames = 0; shimTxFrames = 0; fabricRxFrames = 0; shimRxFrames = 0; /** Guest tx frames the demux could not attribute to a plane. Refused, never * guessed at; each is attributed (rate-limited). */ demuxRefusals = 0; /** Frames a plane injected that carry the OTHER plane's source network — a * mis-wiring, refused rather than delivered. */ crossPlaneRefusals = 0; demuxReports = 0; crossPlaneReports = 0; /** Times drainTx stopped because the fabric plane could not accept. */ fabricTxStops = 0; /** Gate-visible NaaS forward counter (unclassifiable packets refused). */ get naasForwardCount() { return this.naas.count ?? 0; } /** The rx mode the GUEST chose, once it has posted a buffer. */ get rxMode() { return this.observedRxMode; } /** The lockstep violation that stopped this device, if any. */ get fault() { return this.negotiationFault; } /** Handle a QUEUE_NOTIFY doorbell for queue `qidx`. */ onKick(qidx) { if (qidx === VIRTIO_NET_TXQ) { void this.drainTx(); } else if (qidx === VIRTIO_NET_RXQ) { this.dbg(`onKick rxq (guest refilled buffers; pending=${this.pendingRx.length})`); this.pumpRx(); } } /** Teardown hook (idempotent; no timers). */ dispose() { } dbg(s) { this.opts.onDebug?.(s); } info(s) { this.opts.onInfo?.(s); } getQueue(qidx) { let vq = this.queues.get(qidx); if (vq && vq.ready) return vq; const geom = readQueueGeom(this.mem, this.opts.windowBase, qidx); if (!geom.ready || geom.num === 0) return null; vq = new VirtQueue(this.mem, geom); this.queues.set(qidx, vq); return vq; } /* ------------------------------------------------------------------ */ /* TX: guest -> host. */ /* ------------------------------------------------------------------ */ async drainTx() { const vq = this.getQueue(VIRTIO_NET_TXQ); if (!vq) return; if (this.negotiationFault) return; const link = this.link; const fabric = this.fabric; const fabricNet = this.fabricNet; let processed = 0; let batched = 0; const fabricBatch = []; let fabricStalled = false; try { processed = await vq.drainAvail( (req) => { let total = 0; for (const seg of req.readable) total += seg.len; if (total < VIRTIO_NET_HDR_BYTES) { this.opts.onError?.( new Error(`virtio-net: tx chain shorter than the virtio_net_hdr (${total}B)`) ); return 0; } const frame = new Uint8Array(total - VIRTIO_NET_HDR_BYTES); let skip = VIRTIO_NET_HDR_BYTES; let off = 0; for (const seg of req.readable) { if (skip >= seg.len) { skip -= seg.len; continue; } const take = seg.len - skip; this.mem.copyOut(seg.addr + skip, take, frame, off); off += take; skip = 0; } this.txFrames++; if (this.loggedTx < TX_LOG_FRAMES) { this.loggedTx++; this.info( `guest tx frame #${this.txFrames} (${frame.length}B, ethertype 0x${ethertype(frame).toString(16)})` + (this.loggedTx === TX_LOG_FRAMES ? " \u2014 further tx frames are trace-only" : "") ); } this.dbg(`tx frame ${frame.length}B ethertype=0x${ethertype(frame).toString(16)}`); if (link) { if (link.queue(frame)) batched++; } else if (fabric && fabricNet) { const to = planeForDestination(frame, fabricNet); if (to === "fabric") { this.fabricTxFrames++; fabricBatch.push(frame); } else if (to === "shim") { this.shimTxFrames++; this.shim.handleGuestFrame(frame); } else { this.demuxRefusals++; if (this.demuxReports < 4 || this.demuxRefusals % 256 === 0) { this.demuxReports++; const msg = `virtio-net: cannot attribute a ${frame.length}B guest tx frame (ethertype 0x${ethertype(frame).toString(16)}) to a plane \u2014 REFUSED. This NIC carries the storage fabric (${fabricNet.text}) and the MITM shim, and the destination is read from the IPv4 destination or the ARP target. A frame naming neither goes nowhere rather than to whichever consumer is nearer. demux-refusals=${this.demuxRefusals}`; this.opts.onError?.(new Error(msg)); this.info(msg); } } } else { this.shim.handleGuestFrame(frame); } return 0; }, /* CREDIT IS THE BRAKE. Out of credit we stop pulling chains; the guest's * avail ring fills and its own netif_stop_subqueue holds the sender. * Nothing is dropped and nothing is buffered host-side. * * On a SHARED NIC the same brake stops BOTH planes, because there is * one ring and one guest queue. That is head-of-line blocking and it is * the right answer rather than a compromise: a real NIC whose transmit * queue is full stops the queue. Draining shim frames around a fabric * frame we cannot send would mean buffering that frame host-side, which * is the unbounded backlog the credit window exists to make impossible. */ link ? () => link.credit > link.queued : fabric?.canAccept ? () => { if (fabric.canAccept(fabricBatch.length + 1)) return true; fabricStalled = true; return false; } : void 0 ); } catch (e) { this.opts.onError?.(e instanceof Error ? e : new Error(String(e))); return; } if (link && batched > 0) { link.flush(); this.txBatches++; } if (fabric && fabricBatch.length > 0) { fabric.send(fabricBatch); this.txBatches++; } if (fabricStalled) { this.fabricTxStops++; if (this.fabricTxStops === 1 || this.fabricTxStops % 256 === 0) { this.info( `tx paused: the fabric plane cannot accept and ${vq.availPending} chain(s) are left in the guest's avail ring. Both planes stop, because there is one ring \u2014 backpressure, not loss. fabric-tx-stops=${this.fabricTxStops}` ); } } if (link && link.credit <= link.queued && vq.availPending > 0) { this.txCreditStops++; if (this.txCreditStops === 1 || this.txCreditStops % 256 === 0) { this.info( `tx paused on link credit (${vq.availPending} chain(s) left in the guest's avail ring, credit=${link.credit}) \u2014 backpressure, not loss. tx-credit-stops=${this.txCreditStops}` ); } } if (processed > 0) this.raiseInterrupt(); } /* ------------------------------------------------------------------ */ /* RX: host -> guest. */ /* ------------------------------------------------------------------ */ /** * Inject a frame, attributed to the plane that produced it. * * THE REVERSE HALF OF THE DEMUX, and it is a check rather than a routing * decision — both planes inject into the same rx ring, so there is nothing to * route. What there IS to catch is a plane carrying the other plane's * network: a switch uplink wired to the wrong device, or a shim answering on * an address the fabric owns. Either produces a guest whose routes work * intermittently, which is the most expensive shape of network bug there is * to find from inside a guest. * * It costs the same four byte loads as the tx side and no copy. An * UNCLASSIFIABLE injection is NOT refused here — unlike on tx, where the * device must choose a consumer and has none to choose. Here the frame has a * consumer already (the guest), and refusing a broadcast or a protocol this * device does not parse would break the shim's existing ARP and DNS answers. */ injectFrom(plane, frame) { const net = this.fabricNet; if (net) { const from = planeForSource(frame, net); if (from !== null && from !== plane) { this.crossPlaneRefusals++; if (this.crossPlaneReports < 4 || this.crossPlaneRefusals % 256 === 0) { this.crossPlaneReports++; const msg = `virtio-net: the ${plane} plane injected a ${frame.length}B frame whose source belongs to the ${from} plane (fabric is ${net.text}) \u2014 REFUSED. This is a wiring fault, not traffic: a switch uplink on the wrong device, or a shim answering on an address the fabric owns. cross-plane-refusals=${this.crossPlaneRefusals}`; this.opts.onError?.(new Error(msg)); this.info(msg); } return; } if (plane === "fabric") this.fabricRxFrames++; else this.shimRxFrames++; } this.transmitToGuest(frame); } /** Queue a raw ethernet frame for delivery into the guest's rx queue. * Enforces PENDING_RX_MAX_BYTES on the paths that have no credit window; * see the constant for why a bound and a ceiling are not the same thing. */ transmitToGuest(frame) { if (this.negotiationFault) { this.negotiationDrops++; if (this.negotiationDrops <= 2 || this.negotiationDrops % 1024 === 0) { this.info( `REFUSING a ${frame.length}B rx frame: ${this.negotiationFault} (refused=${this.negotiationDrops}). This device does not deliver on a negotiation it cannot trust.` ); } return; } if (frame.length > this.mtu + ETH_HLEN + 4) { this.opts.onError?.( new Error( `virtio-net: refusing a ${frame.length}B frame \u2014 this NIC's mtu is ${this.mtu} (ceiling ${this.mtu + ETH_HLEN + 4}B incl. an 802.1Q tag)` ) ); return; } if (this.pendingRxBytes + frame.length > PENDING_RX_MAX_BYTES) { this.rxOverflowDrops++; if (this.rxOverflowDrops <= 4 || this.rxOverflowDrops % 256 === 0) { const msg = `virtio-net: rx backlog at cap (${this.pendingRxBytes}B / ${PENDING_RX_MAX_BYTES}B, ${this.pendingRx.length} frames) \u2014 the guest is not posting rx buffers (stalled/dead); DROPPED a ${frame.length}B frame. rx-overflow-drops=${this.rxOverflowDrops}` + (this.link ? ` \u2014 WITH a credit window bound, which means the window is wider than this cap and one of the two numbers is wrong.` : ""); this.opts.onError?.(new Error(msg)); this.info(msg); } return; } this.pendingRx.push(frame); this.pendingRxBytes += frame.length; this.pumpRx(); } /** * A host->guest frame could not be placed. NEVER SILENT: an undeliverable * rx frame is indistinguishable, from inside the guest, from a network that * simply does not answer — which is exactly how the 2026-07-25 guest-root * browser failure presented (one ARP out, then `connect to 10.0.2.2:3128 * timed out`). Both arms of this used to be `dbg`, i.e. invisible unless * someone had already thought to turn on the per-frame trace, so the one * fact that would have named the culprit was the one fact the log withheld. * * Rate-limited on the same idiom as rxOverflowDrops (first few, then every * 256th) plus a single recovery line, so a transient backpressure blip * costs two lines and a real stall stays loud. */ reportRxStall(why) { this.rxStalls++; this.rxStalled = true; if (this.rxStallReports < 4 || this.rxStalls % 256 === 0) { this.rxStallReports++; this.info( `rx STALL: ${why} \u2014 ${this.pendingRx.length} frame(s) / ${this.pendingRxBytes}B held host-side, undeliverable. The guest sees silence, not an error. rx-stalls=${this.rxStalls}` ); } } /** * The lockstep violation, named once and terminally. * * PLAN-STORAGE-FABRIC-NFS §9's RED arm: "MRG_RXBUF/F_MTU negotiated on one * side only is refused rather than silently dropping frames." Everything * after this refuses, loudly, and a bound link is faulted so the far end * stops too — a fabric where one direction quietly works is worse to debug * than one that stops. */ raiseNegotiationFault(why) { if (this.negotiationFault) return; this.negotiationFault = why; const msg = `virtio-net: FEATURE NEGOTIATION MISMATCH \u2014 ${why}`; this.opts.onError?.(new Error(msg)); this.info(msg); this.link?.raise("protocol", msg); } /** * Check a posted rx chain against what this host was configured for, and * record what the guest actually chose. * * The three shapes are unmistakable and come straight from `try_fill_recv`: * * add_recvbuf_small 1 writable seg, EXACTLY hdr_len + GOOD_PACKET_LEN * add_recvbuf_big n+2 writable segs; seg[0] is exactly hdr_len, then * PAGE_SIZE - 32, then n x PAGE_SIZE * add_recvbuf_mergeable 1 writable seg, some other length (ewma-sized, * L1-aligned, <= PAGE_SIZE - hdr_len + hole) * * Returns false when the chain is unusable; the caller completes it with * len 0 so the queue cannot wedge. */ assertRxChain(req) { const segs = req.writable; if (segs.length === 0) return false; let cap = 0; for (const s of segs) cap += s.len; let observed; if (segs.length >= 3 && segs[0].len === VIRTIO_NET_HDR_BYTES) { observed = "big"; } else if (segs.length === 1) { observed = segs[0].len === SMALL_RX_BUFFER_BYTES ? "small" : "single"; } else { this.opts.onError?.( new Error( `virtio-net: rx chain of ${segs.length} segment(s) starting at ${segs[0].len}B matches no add_recvbuf_* shape (small posts 1 segment of ${SMALL_RX_BUFFER_BYTES}B, big posts >=3 starting with a ${VIRTIO_NET_HDR_BYTES}B header segment, mergeable posts 1)` ) ); return false; } if (this.observedRxMode === null) { const consistent = this.expectedRxMode === "big" ? observed === "big" : ( /* small and merged both accept a single segment; only a page chain * would mean the guest took an MTU this host never offered. */ observed !== "big" ); this.observedRxMode = consistent ? this.expectedRxMode : observed; this.info( `rx buffers: guest posts ${observed} (${segs.length} seg, ${cap}B capacity); host configured for ${this.expectedRxMode} (mtu ${this.mtu}${this.mergeRxBuf ? ", MRG_RXBUF" : ""})` ); this.crossCheckAcceptedFeatures(); if (this.negotiationFault) return false; if (!consistent) { this.raiseNegotiationFault( `this host was configured for mtu ${this.mtu}${this.mergeRxBuf ? " + VIRTIO_NET_F_MRG_RXBUF" : ""} (rx mode "${this.expectedRxMode}", which posts ${describeShape(this.expectedRxMode)}), but the guest posted ${describeShape(observed)}. The kernel did not accept the feature this host is relying on. virtio-net's offered-features word is KERNEL-side (arch/wasm32/kernel/virtio_net_wasm.c calls wasm_virtio_add_device with it); this is the host-first half of a lockstep pair running against a kernel that has not caught up. Delivering anyway would post up to ${this.mtu + ETH_HLEN}B frames into ${cap - VIRTIO_NET_HDR_BYTES}B buffers, which receive_small drops at drivers/net/virtio_net.c:1838 without telling anyone.` ); return false; } if (this.expectedRxMode !== "merged") { const want = this.expectedRxMode === "big" ? bigRxBufferCapacity(this.mtu) : VIRTIO_NET_HDR_BYTES + ETH_HLEN + this.mtu; if (cap < want) { this.raiseNegotiationFault( `the guest posted a ${cap}B rx buffer, but mtu ${this.mtu} needs ${want}B` + (this.expectedRxMode === "big" ? ` (hdr 12 + (PAGE-32) + ceil(mtu/PAGE) x PAGE)` : ` (hdr 12 + ETH_HLEN + mtu)`) + `. The guest accepted a SMALLER mtu than this host offered \u2014 the kernel's config-space mtu and this host's number disagree.` ); return false; } } } else if (observed === "big" !== (this.observedRxMode === "big")) { this.opts.onError?.( new Error( `virtio-net: rx chain shape changed mid-flight (${this.observedRxMode} -> ${observed}); the queue is corrupt` ) ); return false; } return true; } /** * Corroborate the descriptor-shape verdict against the driver's own accepted * feature word, once. * * NEVER SILENT AND NEVER VACUOUS: if the readback cannot be trusted (see * readAcceptedFeaturesWord0) this says so rather than passing. It is a * cross-check, not the check — the descriptor shape is what the guest DOES, * and this is what it SAYS. */ crossCheckAcceptedFeatures() { if (this.featureCrossCheckDone) return; this.featureCrossCheckDone = true; const acc = readAcceptedFeaturesWord0(this.mem, this.opts.windowBase); if (!acc.readable) { this.info(`accepted-features cross-check UNAVAILABLE: ${acc.why}`); return; } const mtuBit = (acc.word0 & 1 << VIRTIO_NET_F_MTU) !== 0; const mrgBit = (acc.word0 & 1 << VIRTIO_NET_F_MRG_RXBUF) !== 0; this.info( `accepted features word0=0x${acc.word0.toString(16)} (F_MTU=${mtuBit ? 1 : 0}, F_MRG_RXBUF=${mrgBit ? 1 : 0})` ); const wantMtu = this.mtu > ETH_DATA_LEN; if (wantMtu !== mtuBit || this.mergeRxBuf !== mrgBit) { this.raiseNegotiationFault( `the driver accepted F_MTU=${mtuBit ? 1 : 0} F_MRG_RXBUF=${mrgBit ? 1 : 0}, this host expects F_MTU=${wantMtu ? 1 : 0} F_MRG_RXBUF=${this.mergeRxBuf ? 1 : 0}` ); } } /** * Fill available rx buffers with pending frames. * * Three layouts, one writer. The rule that unifies them is the driver's: the * 12-byte virtio_net_hdr occupies the first bytes of the writable region and * the frame follows it, spilling across the remaining segments in order. * That is literally what page_to_skb reconstructs — data at page offset * sizeof(padded_vnet_hdr) then offset 0 in each chained page — and it is also * what receive_small's single buffer wants, and what the first buffer of a * merged chain wants. */ pumpRx() { if (this.negotiationFault) return; const vq = this.getQueue(VIRTIO_NET_RXQ); if (!vq) { this.reportRxStall("guest rx queue not ready"); return; } let wrote = 0; let delivered = 0; while (this.pendingRx.length > 0) { const frame = this.pendingRx[0]; const need = VIRTIO_NET_HDR_BYTES + frame.length; const taken = []; let cap = 0; let bad = false; while (cap < need) { const req = vq.takeAvail(); if (!req) break; if (!this.assertRxChain(req)) { vq.complete(req.head, 0); bad = true; break; } taken.push(req); for (const s of req.writable) cap += s.len; if (this.observedRxMode !== "merged") break; } if (bad) { for (let i = taken.length - 1; i >= 0; i--) vq.complete(taken[i].head, 0); break; } if (taken.length === 0) { this.reportRxStall("no free guest rx buffer"); break; } if (cap < need) { vq.rewind(taken.length); this.reportRxStall( `merged rx ran dry: ${cap}B across ${taken.length} buffer(s) for a ${need}B frame` ); break; } if (taken.length === 1 && this.observedRxMode !== "merged") { const first = taken[0]; if (!this.writeFrameInto(first, frame, 0, frame.length, 0)) { vq.complete(first.head, 0); continue; } this.pendingRx.shift(); this.pendingRxBytes -= frame.length; vq.complete(first.head, need); this.rxFrames++; wrote++; delivered++; continue; } let ok = true; let off = 0; const lens = []; for (let i = 0; i < taken.length && off < frame.length; i++) { const req = taken[i]; let room = 0; for (const s of req.writable) room += s.len; const hdr = i === 0 ? VIRTIO_NET_HDR_BYTES : 0; const take = Math.min(frame.length - off, room - hdr); if (!this.writeFrameInto(req, frame, off, take, i === 0 ? taken.length : 0)) { ok = false; break; } lens.push(hdr + take); off += take; } if (!ok) { for (const req of taken) vq.complete(req.head, 0); continue; } this.pendingRx.shift(); this.pendingRxBytes -= frame.length; for (let i = 0; i < lens.length; i++) vq.complete(taken[i].head, lens[i]); for (let i = lens.length; i < taken.length; i++) vq.complete(taken[i].head, 0); this.rxMergedBuffers += taken.length - 1; this.rxFrames++; wrote++; delivered++; } if (wrote > 0) { this.dbg(`rx: delivered ${wrote} frame(s)`); if (this.rxStalled && this.pendingRx.length === 0) { this.rxStalled = false; this.info(`rx recovered: backlog drained (rx-stalls=${this.rxStalls} total)`); } this.raiseInterrupt(); } if (delivered > 0) this.link?.consume(delivered); } /** * Scatter `[optional header][frame bytes]` across one chain's writable * segments. Returns false (attributed) if a segment address is not in the * live guest memory — the corrupt-descriptor case that used to throw out of * the rx pump. */ writeFrameInto(req, frame, frameOff, frameLen, numBuffers) { const withHeader = numBuffers > 0 || frameOff === 0; try { let src = frameOff; let end = frameOff + frameLen; let hdrLeft = withHeader ? VIRTIO_NET_HDR_BYTES : 0; for (const seg of req.writable) { let at = seg.addr; let room = seg.len; if (hdrLeft > 0) { const n2 = Math.min(hdrLeft, room); this.mem.fill(at, n2, 0); if (numBuffers > 0) { const rel = VIRTIO_NET_HDR_NUM_BUFFERS_OFF - (VIRTIO_NET_HDR_BYTES - hdrLeft); if (rel >= 0 && rel + 2 <= n2) { this.mem.write( at + rel, Uint8Array.from([numBuffers & 255, numBuffers >> 8 & 255]) ); } } at += n2; room -= n2; hdrLeft -= n2; if (room === 0) continue; } if (src >= end) break; const n = Math.min(room, end - src); this.mem.write(at, frame.subarray(src, src + n)); src += n; } if (src < end) { this.opts.onError?.( new Error( `virtio-net: rx chain (head=${req.head}) holds ${req.writable.length} segment(s) but ${end - src}B of a ${frame.length}B frame did not fit` ) ); return false; } return true; } catch (e) { this.opts.onError?.( new Error( `virtio-net: rx buffer unusable (head=${req.head}) \u2014 DROPPED a ${frame.length}B frame: ${e instanceof Error ? e.message : String(e)}` ) ); return false; } } /** Set INTERRUPT_STATUS, mark the IRQ pending, and wake the idle CPU. */ raiseInterrupt() { const i32 = this.mem.i32; const isOff = this.opts.windowBase + VIRTIO_MMIO_INTERRUPT_STATUS; Atomics.or(i32, isOff >> 2, VIRTIO_MMIO_INT_VRING); if (this.opts.suppressIrq) return; const bit2 = 1 << (this.opts.irqBit ?? 2); Atomics.or(i32, this.opts.irqPendingOffset >> 2, bit2); Atomics.add(i32, this.opts.schedWakeupOffset >> 2, 1); Atomics.notify(i32, this.opts.schedWakeupOffset >> 2, 1); } }; function ethertype(frame) { return frame.length >= 14 ? frame[12] << 8 | frame[13] : 0; } function describeShape(mode) { switch (mode) { case "small": return `one ${SMALL_RX_BUFFER_BYTES}B segment, which is add_recvbuf_small with hdr_len + GOOD_PACKET_LEN buffers (drivers/net/virtio_net.c:2434)`; case "big": return `a page chain, which is add_recvbuf_big (drivers/net/virtio_net.c:2464)`; case "merged": case "single": return `one variable-length segment, which is add_recvbuf_small or add_recvbuf_mergeable (drivers/net/virtio_net.c:2434 / :2530) \u2014 either way NOT the page chain add_recvbuf_big posts`; } } // ../../linux-in-the-browser/hardwarejs/src/devices/usb_hcd.ts var INTERRUPT_STATUS_OFF = 96; var HDR_OFF = 256; var PORTS_OFF = 320; var SLOTS_OFF = 384; var SLOT_SIZE = 40; var MAGIC = 1112757591; var VERSION = 1; var SLOT_FREE = 0; var SLOT_SUBMITTED = 1; var SLOT_COMPLETE = 2; var SLOT_CANCELED = 3; var EP_IN = 128; var EP_TYPE_SHIFT = 8; var XFER_CONTROL = 0; var XFER_BULK = 2; var XFER_INT = 3; var PORT_STAT_CONNECTION = 1; var PORT_STAT_LOW_SPEED = 512; var PORT_STAT_HIGH_SPEED = 1024; var PORT_STAT_C_CONNECTION = 1 << 16; var ENODEV = 19; var EPIPE = 32; var EPROTO = 71; var EOVERFLOW = 75; var UsbHcdBackend = class { opts; /** The ONE way this device addresses guest RAM. See guest_memory.ts. */ mem; ports; validated = false; numSlots = 0; numPorts = 0; /** Diagnostics the gates read. */ completions = 0; grantRefusals = 0; constructor(opts) { this.opts = opts; this.mem = new GuestMemory(opts); this.ports = []; } /* -------------------------------------------------------------- */ /* Shared-memory helpers. */ /* -------------------------------------------------------------- */ rd32(off) { return Atomics.load(this.mem.i32, this.opts.windowBase + off >> 2) >>> 0; } wr32(off, v) { Atomics.store(this.mem.i32, this.opts.windowBase + off >> 2, v | 0); } or32(off, v) { Atomics.or(this.mem.i32, this.opts.windowBase + off >> 2, v | 0); } and32(off, v) { Atomics.and(this.mem.i32, this.opts.windowBase + off >> 2, v | 0); } slotOff(slot) { return SLOTS_OFF + slot * SLOT_SIZE; } /** Validate the kernel-seeded header once (loud refuse on mismatch). */ ensureValidated() { if (this.validated) return true; const magic = this.rd32(HDR_OFF + 0); if (magic !== MAGIC) return false; const version2 = this.rd32(HDR_OFF + 4); this.numSlots = this.rd32(HDR_OFF + 8); this.numPorts = this.rd32(HDR_OFF + 12); if (version2 !== VERSION || this.numSlots === 0 || this.numPorts === 0) { this.opts.onError?.( new Error( `usb_hcd: header mismatch (version=${version2} slots=${this.numSlots} ports=${this.numPorts}) \u2014 refusing to serve` ) ); return false; } for (let p = 0; p < this.numPorts; p++) this.ports.push({ device: null, speed: "full", revoked: false, deviceDesc: null, deviceDescFromDevice: false, configDescs: /* @__PURE__ */ new Map(), strings: /* @__PURE__ */ new Map(), guestAddress: 0, claimed: false }); this.validated = true; this.opts.onDebug?.( `usb_hcd: header ok (slots=${this.numSlots} ports=${this.numPorts})` ); return true; } raiseInterrupt() { this.or32(INTERRUPT_STATUS_OFF, 1); if (this.opts.suppressIrq) return; const bit2 = 1 << (this.opts.irqBit ?? 3); const i32 = this.mem.i32; Atomics.or(i32, this.opts.irqPendingOffset >> 2, bit2); Atomics.add(i32, this.opts.schedWakeupOffset >> 2, 1); Atomics.notify(i32, this.opts.schedWakeupOffset >> 2, 1); } /* -------------------------------------------------------------- */ /* Device attach / detach / revoke (the grant boundary). */ /* -------------------------------------------------------------- */ /** * Attach a granted WebUSB device to a free root-hub port. Opens the * device, reads its descriptors (synthesizing any it will not give), * then flips the * port's connect bit + connect-change and raises the IRQ — stock * usbcore enumeration takes it from there. */ async attachDevice(dev, speed = "full") { const deadline = Date.now() + 3e4; while (!this.ensureValidated()) { if (Date.now() > deadline) throw new Error( "usb_hcd: window header never appeared (kernel without CONFIG_USB / wasm-usb HCD?) \u2014 refusing attach" ); await new Promise((r) => setTimeout(r, 25)); } const port = this.ports.findIndex((p) => p.device === null && !p.claimed); if (port < 0) throw new Error("usb_hcd: no free root-hub port"); const ps = this.ports[port]; ps.claimed = true; const fallback = (what, why) => this.opts.onEvent?.({ kind: "descriptor-fallback", port, detail: `${hex4(dev.vendorId)}:${hex4(dev.productId)} ${what}: ${why} \u2014 serving one synthesized from WebUSB metadata, which has no class-specific descriptors` }); let deviceDescFromDevice; let deviceDesc; let configDescs; let strings; try { if (!dev.opened) await dev.open(); try { await dev.reset?.(); } catch (e) { this.opts.onDebug?.(`usb_hcd: attach reset failed (tolerated): ${e}`); } const devRead = await readDeviceDescriptor(dev); deviceDescFromDevice = devRead.ok; deviceDesc = devRead.ok ? fitMaxPacket0(devRead.bytes, speed) : synthesizeDeviceDescriptor(dev); if (!devRead.ok) fallback("device descriptor", devRead.why); configDescs = /* @__PURE__ */ new Map(); for (let i = 0; i < dev.configurations.length; i++) { const cfg = dev.configurations[i]; const r = await readDeviceConfigDescriptor(dev, i, cfg.configurationValue); configDescs.set(cfg.configurationValue, r.ok ? r.bytes : synthesizeConfigDescriptor(cfg)); if (!r.ok) fallback(`configuration ${cfg.configurationValue} descriptor`, r.why); } strings = deviceDescFromDevice ? synthesizeStrings(dev, deviceDesc[14], deviceDesc[15], deviceDesc[16]) : synthesizeStrings(dev); } finally { ps.claimed = false; } ps.device = dev; ps.speed = speed; ps.revoked = false; ps.guestAddress = 0; ps.deviceDescFromDevice = deviceDescFromDevice; ps.deviceDesc = deviceDesc; ps.configDescs = configDescs; ps.strings = strings; const speedBits = speed === "low" ? PORT_STAT_LOW_SPEED : speed === "high" ? PORT_STAT_HIGH_SPEED : 0; this.or32(PORTS_OFF + port * 4, PORT_STAT_CONNECTION | speedBits | PORT_STAT_C_CONNECTION); this.opts.onEvent?.({ kind: "attach", port, detail: `${hex4(dev.vendorId)}:${hex4(dev.productId)} ${dev.productName ?? ""}` }); this.raiseInterrupt(); return port; } /** Detach: clear connect (+speed), latch connect-change, IRQ. */ detachDevice(port) { const ps = this.ports[port]; if (!ps?.device) return; ps.device = null; this.and32(PORTS_OFF + port * 4, ~(PORT_STAT_CONNECTION | PORT_STAT_LOW_SPEED | PORT_STAT_HIGH_SPEED)); this.or32(PORTS_OFF + port * 4, PORT_STAT_C_CONNECTION); this.opts.onEvent?.({ kind: "detach", port, detail: "device detached" }); this.raiseInterrupt(); } /** RED seam: revoke the grant — URBs to the port refuse loudly. */ revokeGrant(port) { const ps = this.ports[port]; if (ps) ps.revoked = true; } /* -------------------------------------------------------------- */ /* URB dispatch. */ /* -------------------------------------------------------------- */ /** Doorbell entry — devid-3 kick with qidx == slot index. */ onKick(slot) { if (!this.ensureValidated()) { this.opts.onError?.( new Error(`usb_hcd: kick for slot ${slot} before header \u2014 dropped loudly`) ); return; } if (slot < 0 || slot >= this.numSlots) { this.opts.onError?.(new Error(`usb_hcd: kick with bad slot ${slot}`)); return; } const base = this.opts.windowBase + this.slotOff(slot); if (Atomics.load(this.mem.i32, base + 0 >> 2) !== SLOT_SUBMITTED) return; void this.handleUrb(slot).catch((e) => { this.opts.onError?.(e instanceof Error ? e : new Error(String(e))); this.completeSlot(slot, 0, -EPROTO); }); } slotView(slot) { const b = this.opts.windowBase + this.slotOff(slot); const dv = this.mem.dv; return { port: dv.getUint32(b + 4, true), epinfo: dv.getUint32(b + 8, true), bufAddr: dv.getUint32(b + 12, true), bufLen: dv.getUint32(b + 16, true), setup: this.mem.read(b + 28, 8) }; } /** Complete @slot: write actual/status, publish COMPLETE, raise IRQ. * A slot the kernel CANCELED in the meantime is freed with attribution. */ completeSlot(slot, actual, status) { const b = this.opts.windowBase + this.slotOff(slot); const stateIdx = b + 0 >> 2; const dv = this.mem.dv; const i32 = this.mem.i32; dv.setUint32(b + 20, actual >>> 0, true); dv.setInt32(b + 24, status | 0, true); const prev = Atomics.compareExchange(i32, stateIdx, SLOT_SUBMITTED, SLOT_COMPLETE); if (prev === SLOT_CANCELED) { Atomics.store(i32, stateIdx, SLOT_FREE); this.opts.onEvent?.({ kind: "cancel-drop", port: dv.getUint32(b + 4, true), detail: `slot ${slot}: completion dropped (kernel canceled the URB)` }); return; } if (prev !== SLOT_SUBMITTED) { this.opts.onError?.( new Error(`usb_hcd: completing slot ${slot} in unexpected state ${prev}`) ); return; } this.completions++; this.opts.onDebug?.(`urb slot=${slot} complete actual=${actual} status=${status}`); this.raiseInterrupt(); } async handleUrb(slot) { const s = this.slotView(slot); const ps = this.ports[s.port]; const dev = ps?.device; if (!dev || ps.revoked) { this.grantRefusals++; this.opts.onEvent?.({ kind: "grant-refuse", port: s.port, detail: `USB-GRANT-REFUSE: URB slot ${slot} to ${!dev ? "empty" : "revoked"} port ${s.port} \u2014 completed -ENODEV` }); this.completeSlot(slot, 0, -ENODEV); return; } const epNum = s.epinfo & 15; const dirIn = (s.epinfo & EP_IN) !== 0; const type = s.epinfo >> EP_TYPE_SHIFT & 3; this.opts.onDebug?.( `urb slot=${slot} port=${s.port} ep=${epNum}${dirIn ? "in" : "out"} type=${type} len=${s.bufLen}` + (type === XFER_CONTROL ? ` setup=[${Array.from(s.setup).map((b) => b.toString(16).padStart(2, "0")).join(" ")}]` : "") ); try { if (type === XFER_CONTROL) { await this.handleControl(slot, s, ps, dev); } else if (type === XFER_BULK || type === XFER_INT) { const bt = dev.vendorId === 4070 && type === XFER_BULK && (this.__bt = (this.__bt ?? 0) + 1) <= 60; if (bt) this.opts.onEvent?.({ kind: "ctl", port: s.port, detail: `submit ${type === XFER_INT ? "INT" : "BULK"} ep${epNum}${dirIn ? "in" : "out"} len=${s.bufLen}` }); if (dirIn) { const key = s.port * 32 + epNum; const chains = this.__inChain ??= /* @__PURE__ */ new Map(); const prevIn = chains.get(key) ?? Promise.resolve(); let releaseIn; const mineIn = new Promise((res) => releaseIn = res); chains.set(key, prevIn.then(() => mineIn)); await prevIn; let r; try { r = await dev.transferIn(epNum, s.bufLen); } finally { releaseIn(); } const n = Math.min(r.data?.byteLength ?? 0, s.bufLen); if (bt) this.opts.onEvent?.({ kind: "ctl", port: s.port, detail: `done ep${epNum}in -> ${r.status} n=${n} [${r.data ? Array.from(new Uint8Array(r.data.buffer, r.data.byteOffset, Math.min(n, 16))).map((x) => x.toString(16).padStart(2, "0")).join(" ") : ""}]` }); if (n > 0 && r.data) this.mem.write( s.bufAddr, new Uint8Array(r.data.buffer, r.data.byteOffset, n) ); this.completeSlot(slot, n, statusToErrno(r.status, this.opts, s.port)); } else { const data = this.mem.read(s.bufAddr, s.bufLen); const r = await dev.transferOut(epNum, data); this.completeSlot( slot, r.bytesWritten, statusToErrno(r.status, this.opts, s.port) ); } } else { this.opts.onEvent?.({ kind: "protocol-error", port: s.port, detail: `slot ${slot}: unsupported transfer type ${type} \u2014 -EPROTO` }); this.completeSlot(slot, 0, -EPROTO); } } catch (e) { this.transferException(slot, s.port, e); } } transferException(slot, port, e) { const msg = e instanceof Error ? `${e.name}: ${e.message}` : String(e); const gone = /NotFoundError|disconnected|no device|LIBUSB_ERROR_NO_DEVICE/i.test(msg); this.opts.onEvent?.({ kind: "transfer-error", port, detail: `slot ${slot}: ${msg} -> ${gone ? "-ENODEV (device gone)" : "-EPROTO"}` }); if (gone) { this.completeSlot(slot, 0, -ENODEV); this.detachDevice(port); } else { this.completeSlot(slot, 0, -EPROTO); } } /* -------------------------------------------------------------- */ /* Control transfers: the standard-request MITM + pass-through. */ /* -------------------------------------------------------------- */ async handleControl(slot, s, ps, dev) { const bmRequestType = s.setup[0]; const bRequest = s.setup[1]; const wValue = s.setup[2] | s.setup[3] << 8; const wIndex = s.setup[4] | s.setup[5] << 8; const wLength = s.setup[6] | s.setup[7] << 8; const dirIn = (bmRequestType & 128) !== 0; const typeBits = bmRequestType >> 5 & 3; const recipBits = bmRequestType & 31; if (typeBits === 0) { switch (bRequest) { case 6: { const descType = wValue >> 8; const descIdx = wValue & 255; let blob; if (descType === 1) blob = ps.deviceDesc ?? void 0; else if (descType === 2) { const cfg = dev.configurations[descIdx]; blob = cfg ? ps.configDescs.get(cfg.configurationValue) : void 0; } else if (descType === 3) { if (ps.deviceDescFromDevice || descIdx !== 0 && !ps.strings.has(descIdx)) { const r = await getDescriptor(dev, wValue, wIndex, wLength); if (r.ok && r.bytes.length >= 2 && r.bytes[1] === 3) blob = r.bytes; } blob ??= ps.strings.get(descIdx); } if (!blob) { this.completeSlot(slot, 0, -EPIPE); return; } const n = Math.min(blob.length, wLength, s.bufLen); this.mem.write(s.bufAddr, blob.subarray(0, n)); this.completeSlot(slot, n, 0); return; } case 5: ps.guestAddress = wValue; this.completeSlot(slot, 0, 0); return; case 9: { const cfg = dev.configurations.find((c) => c.configurationValue === wValue); if (!cfg && wValue !== 0) { this.completeSlot(slot, 0, -EPIPE); return; } await dev.selectConfiguration(wValue); if (cfg) for (const itf of cfg.interfaces) { try { await dev.claimInterface(itf.interfaceNumber); } catch (e) { this.grantRefusals++; this.opts.onEvent?.({ kind: "grant-refuse", port: s.port, detail: `USB-GRANT-REFUSE: claimInterface(${itf.interfaceNumber}) refused: ${e}` }); this.completeSlot(slot, 0, -EPIPE); return; } } this.completeSlot(slot, 0, 0); return; } case 8: { const v = dev.configurations[0]?.configurationValue ?? 1; this.mem.fill(s.bufAddr, 1, v); this.completeSlot(slot, 1, 0); return; } case 11: if (dev.selectAlternateInterface) await dev.selectAlternateInterface(wIndex, wValue); this.completeSlot(slot, 0, 0); return; case 1: if (recipBits === 2 && dev.clearHalt) { const ep = wIndex & 15; const dir = (wIndex & 128) !== 0 ? "in" : "out"; await dev.clearHalt(dir, ep); } this.completeSlot(slot, 0, 0); return; case 0: { const n = Math.min(2, wLength, s.bufLen); this.mem.fill(s.bufAddr, n, 0); this.completeSlot(slot, n, 0); return; } default: this.opts.onEvent?.({ kind: "protocol-error", port: s.port, detail: `slot ${slot}: unmapped STANDARD request 0x${bRequest.toString(16)} \u2014 -EPROTO` }); this.completeSlot(slot, 0, -EPROTO); return; } } const setup = { requestType: typeBits === 1 ? "class" : "vendor", recipient: recipBits === 1 ? "interface" : recipBits === 2 ? "endpoint" : recipBits === 3 ? "other" : "device", request: bRequest, value: wValue, index: wIndex }; const trace = dev.vendorId === 4070; const hx = (u) => Array.from(u).map((x) => x.toString(16).padStart(2, "0")).join(" "); if (dirIn) { const r = await dev.controlTransferIn(setup, wLength); const n = Math.min(r.data?.byteLength ?? 0, s.bufLen); if (trace) this.opts.onEvent?.({ kind: "ctl", port: s.port, detail: `IN req=0x${bRequest.toString(16)} val=0x${hex4(wValue)} idx=0x${hex4(wIndex)} len=${wLength} -> ${r.status} n=${n} [${r.data ? hx(new Uint8Array(r.data.buffer, r.data.byteOffset, n)) : ""}]` }); if (n > 0 && r.data) this.mem.write(s.bufAddr, new Uint8Array(r.data.buffer, r.data.byteOffset, n)); this.completeSlot(slot, n, statusToErrno(r.status, this.opts, s.port)); } else { const data = wLength > 0 ? this.mem.read(s.bufAddr, Math.min(wLength, s.bufLen)) : void 0; const r = await dev.controlTransferOut(setup, data); if (trace) this.opts.onEvent?.({ kind: "ctl", port: s.port, detail: `OUT req=0x${bRequest.toString(16)} val=0x${hex4(wValue)} idx=0x${hex4(wIndex)} len=${wLength} [${data ? hx(data) : ""}] -> ${r.status} wrote=${r.bytesWritten}` }); this.completeSlot(slot, r.bytesWritten, statusToErrno(r.status, this.opts, s.port)); } } }; function statusToErrno(status, opts, port) { if (status === "ok") return 0; opts.onEvent?.({ kind: "transfer-error", port, detail: `transfer status '${status}' -> ${status === "stall" ? "-EPIPE" : "-EOVERFLOW"}` }); return status === "stall" ? -EPIPE : -EOVERFLOW; } function hex4(v) { return v.toString(16).padStart(4, "0"); } function synthesizeDeviceDescriptor(dev) { const d = new Uint8Array(18); const dv = new DataView(d.buffer); d[0] = 18; d[1] = 1; dv.setUint16(2, dev.usbVersionMajor << 8 | dev.usbVersionMinor << 4, true); d[4] = dev.deviceClass; d[5] = dev.deviceSubclass; d[6] = dev.deviceProtocol; d[7] = 64; dv.setUint16(8, dev.vendorId, true); dv.setUint16(10, dev.productId, true); dv.setUint16( 12, dev.deviceVersionMajor << 8 | dev.deviceVersionMinor << 4 | dev.deviceVersionSubminor, true ); d[14] = dev.manufacturerName ? 1 : 0; d[15] = dev.productName ? 2 : 0; d[16] = dev.serialNumber ? 3 : 0; d[17] = dev.configurations.length; return d; } function synthesizeConfigDescriptor(cfg) { const parts = []; let nIfaces = 0; for (const itf of cfg.interfaces) { nIfaces++; for (const alt of itf.alternates) { parts.push( 9, 4, itf.interfaceNumber, alt.alternateSetting, alt.endpoints.length, alt.interfaceClass, alt.interfaceSubclass, alt.interfaceProtocol, 0 ); for (const ep of alt.endpoints) { const addr = ep.endpointNumber | (ep.direction === "in" ? 128 : 0); const attr = ep.type === "bulk" ? 2 : ep.type === "interrupt" ? 3 : 1; parts.push( 7, 5, addr, attr, ep.packetSize & 255, ep.packetSize >> 8, ep.type === "interrupt" ? 1 : 0 ); } } } const total = 9 + parts.length; const d = new Uint8Array(total); d[0] = 9; d[1] = 2; d[2] = total & 255; d[3] = total >> 8; d[4] = nIfaces; d[5] = cfg.configurationValue; d[6] = 0; d[7] = 128; d[8] = 50; d.set(parts, 9); return d; } var DESCRIPTOR_READ_TIMEOUT_MS = 3e3; async function getDescriptor(dev, wValue, wIndex, length, timeoutMs = DESCRIPTOR_READ_TIMEOUT_MS) { let timer; const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve({ ok: false, why: `no answer in ${timeoutMs} ms` }), timeoutMs); }); const read = (async () => { try { const r = await dev.controlTransferIn( { requestType: "standard", recipient: "device", request: 6, value: wValue, index: wIndex }, length ); if (r.status !== "ok" || !r.data) return { ok: false, why: `device answered ${r.status}` }; return { ok: true, bytes: new Uint8Array(r.data.buffer, r.data.byteOffset, r.data.byteLength).slice() }; } catch (e) { return { ok: false, why: `transfer refused (${e instanceof Error ? e.message : String(e)})` }; } })(); try { return await Promise.race([read, timeout]); } finally { clearTimeout(timer); } } async function readDeviceDescriptor(dev) { const r = await getDescriptor(dev, 1 << 8, 0, 18); if (!r.ok) return r; const d = r.bytes; if (d.length !== 18 || d[0] !== 18 || d[1] !== 1) return { ok: false, why: `not a device descriptor (${d.length} B, bLength ${d[0]}, type ${d[1]})` }; const vid = d[8] | d[9] << 8; const pid = d[10] | d[11] << 8; if (vid !== dev.vendorId || pid !== dev.productId || d[17] !== dev.configurations.length) return { ok: false, why: `names ${hex4(vid)}:${hex4(pid)} with ${d[17]} configuration(s)` }; return r; } async function readDeviceConfigDescriptor(dev, index, value) { const head = await getDescriptor(dev, 2 << 8 | index, 0, 9); if (!head.ok) return head; const h = head.bytes; if (h.length < 9 || h[0] !== 9 || h[1] !== 2) return { ok: false, why: `not a configuration descriptor (${h.length} B, bLength ${h[0]}, type ${h[1]})` }; if (h[5] !== value) return { ok: false, why: `index ${index} is configuration ${h[5]}, not ${value}` }; const total = h[2] | h[3] << 8; if (total < 9) return { ok: false, why: `wTotalLength ${total}` }; const full = await getDescriptor(dev, 2 << 8 | index, 0, total); if (!full.ok) return full; const f = full.bytes; if (f.length !== total || f[1] !== 2 || f[5] !== value) return { ok: false, why: `full read gave ${f.length} of ${total} B` }; return full; } function fitMaxPacket0(desc, speed) { const d = desc.slice(); const legal = speed === "low" ? [8] : [8, 16, 32, 64]; if (!legal.includes(d[7])) d[7] = speed === "low" ? 8 : 64; return d; } function synthesizeStrings(dev, iManufacturer = 1, iProduct = 2, iSerialNumber = 3) { const m = /* @__PURE__ */ new Map(); m.set(0, new Uint8Array([4, 3, 9, 4])); const put = (idx, s) => { if (!s) return; const d = new Uint8Array(2 + s.length * 2); d[0] = d.length; d[1] = 3; for (let i = 0; i < s.length; i++) { d[2 + i * 2] = s.charCodeAt(i) & 255; d[3 + i * 2] = s.charCodeAt(i) >> 8; } m.set(idx, d); }; if (iManufacturer) put(iManufacturer, dev.manufacturerName); if (iProduct) put(iProduct, dev.productName); if (iSerialNumber) put(iSerialNumber, dev.serialNumber); return m; } // ../../linux-in-the-browser/hardwarejs/src/devices/virtio_console.ts var VIRTIO_CONSOLE_DEVICE_READY = 0; var VIRTIO_CONSOLE_PORT_ADD = 1; var VIRTIO_CONSOLE_PORT_READY = 3; var VIRTIO_CONSOLE_PORT_OPEN = 6; var VIRTIO_CONSOLE_PORT_NAME = 7; var CPKT_BYTES = 8; var VIRTIO_CONSOLE_CTRL_IN_Q = 2; var VIRTIO_CONSOLE_CTRL_OUT_Q = 3; function portInQueue(portId) { return portId === 0 ? 0 : portId * 2 + 2; } function portOutQueue(portId) { return portId === 0 ? 1 : portId * 2 + 3; } var VIRTIO_CONSOLE_MAX_PORTS = 3; var PENDING_TX_MAX_BYTES = 4 * 1024 * 1024; var VirtioConsolePort = class { constructor(id, name2, dev) { this.id = id; this.name = name2; this.dev = dev; } id; name; dev; /** Host->guest bytes waiting for a guest-posted buffer, or for the open. */ pending = []; pendingLen = 0; sinks = /* @__PURE__ */ new Set(); /** port->guest_connected: userspace has the port open. */ guestOpen = false; /** port->host_connected as the guest sees it: we sent PORT_OPEN(1). */ hostOpen = false; /** Gate-visible counters. */ bytesToGuest = 0; bytesFromGuest = 0; /** Host->guest bytes dropped at PENDING_TX_MAX_BYTES. Never silent. */ overflowDrops = 0; /** True once userspace in the guest has opened /dev/vportp. */ get guestConnected() { return this.guestOpen; } /** True once the host has announced PORT_OPEN(1) for this port. */ get hostConnected() { return this.hostOpen; } /** Host->guest bytes held: no free guest buffer, or the port is not open. */ get pendingBytes() { return this.pendingLen; } /** * Queue bytes for the guest. Held until the guest has the port open (in_intr * would discard them otherwise) and until it has posted a buffer, then * delivered in order, split across as many PAGE_SIZE buffers as it takes. */ write(bytes) { if (bytes.length === 0) return; if (this.pendingLen + bytes.length > PENDING_TX_MAX_BYTES) { this.overflowDrops++; const msg = `virtio-console: port ${this.id} host->guest backlog at cap (${this.pendingLen}B / ${PENDING_TX_MAX_BYTES}B) \u2014 the guest is not posting buffers (closed, stalled, or dead); DROPPED ${bytes.length}B. overflow-drops=${this.overflowDrops}`; this.dev.reportError(new Error(msg)); return; } this.pending.push(bytes.slice()); this.pendingLen += bytes.length; this.pump(); } /** Subscribe to guest->host bytes. Returns an unsubscribe function. */ onData(cb) { this.sinks.add(cb); return () => { this.sinks.delete(cb); }; } /* ---------------- internals, driven by the backend ---------------- */ /** @internal PORT_OPEN from the guest (port_fops_open / _release). */ setGuestConnected(open) { if (this.guestOpen === open) return; this.guestOpen = open; this.dev.reportInfo( `port ${this.id}${this.name ? ` (${this.name})` : ""} ${open ? "opened" : "closed"} by the guest` + (open && this.pendingLen > 0 ? ` \u2014 releasing ${this.pendingLen}B held` : "") ); if (open) this.pump(); } /** @internal the host announced PORT_OPEN(1). */ setHostConnected(open) { this.hostOpen = open; } /** @internal deliver guest->host bytes to every sink. */ deliverFromGuest(bytes) { this.bytesFromGuest += bytes.length; for (const sink of this.sinks) { try { sink(bytes); } catch (e) { this.dev.reportError(e instanceof Error ? e : new Error(String(e))); } } } /** * @internal fill guest-posted in_vq buffers with held bytes, and ring the * doorbell if anything landed. ONE interrupt per burst, and it is raised * HERE rather than by each caller: a filled buffer with no interrupt is a * guest blocked in read(2) that never wakes, and the first version of this * had exactly that hole on the write()-with-a-free-buffer path, where the * only caller that raised was the PORT_OPEN handler. */ pump() { if (!this.guestOpen || this.pendingLen === 0) return 0; const vq = this.dev.queue(portInQueue(this.id)); if (!vq) return 0; let filled = 0; while (this.pendingLen > 0) { const req = vq.takeAvail(); if (!req) break; const seg = req.writable[0]; if (!seg || seg.len === 0) { this.dev.reportError( new Error( `virtio-console: port ${this.id} in_vq buffer unusable (len=${seg ? seg.len : 0}) \u2014 completing it so the queue cannot wedge` ) ); vq.complete(req.head, 0); continue; } const out = this.dev.mem.bytes(seg.addr, seg.len); let wrote = 0; while (wrote < seg.len && this.pending.length > 0) { const head = this.pending[0]; const n = Math.min(head.length, seg.len - wrote); out.set(head.subarray(0, n), wrote); wrote += n; this.pendingLen -= n; if (n === head.length) this.pending.shift(); else this.pending[0] = head.subarray(n); } vq.complete(req.head, wrote); this.bytesToGuest += wrote; filled++; } if (filled > 0) { this.dev.reportDebug(`port ${this.id}: filled ${filled} in_vq buffer(s)`); this.dev.raise(); } return filled; } /** @internal drop everything held (the port went away). */ discardPending() { this.pending.length = 0; this.pendingLen = 0; } }; var VirtioConsoleBackend = class { constructor(opts) { this.opts = opts; this.mem = new GuestMemory(opts); this.specs = opts.ports ?? [{ id: 1, name: "org.brintos.fsproxyd.0" }]; if (this.specs.length === 0) throw new Error( "virtio-console: a device with no ports offers the guest nothing \u2014 configure at least one port (the appliance wants id 1)" ); for (const s of this.specs) { if (!Number.isInteger(s.id) || s.id < 0) throw new Error(`virtio-console: port id ${s.id} is not a port number`); if (this.portsById.has(s.id)) throw new Error(`virtio-console: port id ${s.id} configured twice`); this.portsById.set(s.id, new VirtioConsolePort(s.id, s.name, this)); } this.maxNrPorts = Math.max(...this.specs.map((s) => s.id)) + 1; if (this.maxNrPorts > VIRTIO_CONSOLE_MAX_PORTS) throw new Error( `virtio-console: max_nr_ports ${this.maxNrPorts} needs ${(this.maxNrPorts + 1) * 2} virtqueues, past the arch's WASM_VIRTIO_SHADOW_MAXQ of 8 \u2014 the extra queues' geometry would be unreadable host-side and those ports would carry no bytes` ); } opts; /** @internal the ONE way this device (and every port) reaches guest RAM. */ mem; queues = /* @__PURE__ */ new Map(); portsById = /* @__PURE__ */ new Map(); specs; /** Control messages waiting for a guest-posted c_ivq buffer. */ pendingControl = []; /** virtio_console_config.max_nr_ports the arch registrar must publish. */ maxNrPorts; /** The guest announced DEVICE_READY(1). */ deviceReady = false; /** The port with this id, if it was configured. */ port(id) { return this.portsById.get(id); } /** Every configured port, by id. */ get ports() { return this.portsById; } /** * QUEUE_NOTIFY doorbell for queue `qidx`. SYNCHRONOUS from end to end: * __send_control_msg spins on the control-out used ring, so anything this * defers is a guest that spins instead of a guest that waits. */ onKick(qidx) { try { if (qidx === VIRTIO_CONSOLE_CTRL_OUT_Q) this.drainControlOut(); else if (qidx === VIRTIO_CONSOLE_CTRL_IN_Q) this.pumpControlIn(); else this.onPortKick(qidx); } catch (e) { this.reportError(e instanceof Error ? e : new Error(String(e))); } } /** Teardown hook (idempotent; no timers). */ dispose() { for (const p of this.portsById.values()) p.discardPending(); this.pendingControl.length = 0; } /* ------------------------------------------------------------------ */ /* Control plane. */ /* ------------------------------------------------------------------ */ /** c_ovq: guest -> device control messages (control_work_handler's peer). */ drainControlOut() { const vq = this.queue(VIRTIO_CONSOLE_CTRL_OUT_Q); if (!vq) return; const msgs = []; for (; ; ) { const req = vq.takeAvail(); if (!req) break; const seg = req.readable[0]; let msg = null; if (!seg || seg.len < CPKT_BYTES) { this.reportError( new Error( `virtio-console: control-out chain shorter than a virtio_console_control (${seg ? seg.len : 0}B < ${CPKT_BYTES}B)` ) ); } else { const dv = this.mem.dv; msg = { id: dv.getUint32(seg.addr, true), event: dv.getUint16(seg.addr + 4, true), value: dv.getUint16(seg.addr + 6, true) }; } vq.complete(req.head, 0); if (msg) msgs.push(msg); } if (msgs.length === 0) return; this.raise(); for (const m of msgs) this.handleControlOut(m); } handleControlOut(m) { switch (m.event) { case VIRTIO_CONSOLE_DEVICE_READY: if (!m.value) { this.reportError( new Error( "virtio-console: guest reported DEVICE_READY(0) \u2014 its control queue could not be filled; no port will be offered" ) ); return; } this.deviceReady = true; this.reportInfo( `guest DEVICE_READY \u2014 offering ${this.specs.length} port(s): ` + this.specs.map((s) => `p${s.id}${s.name ? `=${s.name}` : ""}`).join(", ") ); for (const s of this.specs) this.sendControl(s.id, VIRTIO_CONSOLE_PORT_ADD, 1); this.pumpControlIn(); return; case VIRTIO_CONSOLE_PORT_READY: { const port = this.portsById.get(m.id); if (!port) { this.reportError( new Error(`virtio-console: PORT_READY for unconfigured port ${m.id}`) ); return; } if (!m.value) { this.reportError( new Error( `virtio-console: guest failed to add port ${m.id} (PORT_READY(0)) \u2014 /dev/vport*p${m.id} will not exist` ) ); return; } if (port.name !== void 0) this.sendControlWithPayload( m.id, VIRTIO_CONSOLE_PORT_NAME, 1, // NUL-terminated: handle_control_message sizes the allocation from // the used-ring len and strscpy()s, so the terminator is optional // for the driver and expected by everything that reads sysfs. new TextEncoder().encode(`${port.name}\0`) ); port.setHostConnected(true); this.sendControl(m.id, VIRTIO_CONSOLE_PORT_OPEN, 1); this.pumpControlIn(); return; } case VIRTIO_CONSOLE_PORT_OPEN: { const port = this.portsById.get(m.id); if (!port) { this.reportError( new Error(`virtio-console: PORT_OPEN for unconfigured port ${m.id}`) ); return; } port.setGuestConnected(!!m.value); return; } default: this.reportDebug( `control-out event ${m.event} (id=${m.id} value=${m.value}) ignored` ); return; } } /** Queue an 8-byte control message for the guest's c_ivq. */ sendControl(id, event, value) { this.sendControlWithPayload(id, event, value, null); } sendControlWithPayload(id, event, value, payload) { const buf = new Uint8Array(CPKT_BYTES + (payload ? payload.length : 0)); const dv = new DataView(buf.buffer); dv.setUint32(0, id >>> 0, true); dv.setUint16(4, event, true); dv.setUint16(6, value, true); if (payload) buf.set(payload, CPKT_BYTES); this.pendingControl.push(buf); } /** c_ivq: place queued control messages into guest-posted buffers. */ pumpControlIn() { if (this.pendingControl.length === 0) return; const vq = this.queue(VIRTIO_CONSOLE_CTRL_IN_Q); if (!vq) return; let filled = 0; while (this.pendingControl.length > 0) { const req = vq.takeAvail(); if (!req) break; const seg = req.writable[0]; const msg = this.pendingControl[0]; if (!seg || seg.len < msg.length) { this.reportError( new Error( `virtio-console: control-in buffer too small for a ${msg.length}B message (len=${seg ? seg.len : 0}) \u2014 dropping it; the guest will not learn about this port` ) ); this.pendingControl.shift(); vq.complete(req.head, 0); continue; } this.pendingControl.shift(); this.mem.write(seg.addr, msg); vq.complete(req.head, msg.length); filled++; } if (filled > 0) { this.reportDebug(`control-in: delivered ${filled} message(s)`); this.raise(); } } /* ------------------------------------------------------------------ */ /* Data plane. */ /* ------------------------------------------------------------------ */ onPortKick(qidx) { for (const port of this.portsById.values()) { if (qidx === portOutQueue(port.id)) { this.drainPortOut(port); return; } if (qidx === portInQueue(port.id)) { port.pump(); return; } } this.reportDebug(`kick on queue ${qidx}, which no configured port owns`); } /** out_vq: guest -> host bytes (port_fops_write -> __send_to_port). */ drainPortOut(port) { const vq = this.queue(portOutQueue(port.id)); if (!vq) return; const chunks = []; let n = 0; for (; ; ) { const req = vq.takeAvail(); if (!req) break; let total = 0; for (const seg of req.readable) total += seg.len; if (total > 0) { const bytes = new Uint8Array(total); let off = 0; for (const seg of req.readable) { this.mem.copyOut(seg.addr, seg.len, bytes, off); off += seg.len; } chunks.push(bytes); } vq.complete(req.head, 0); n++; } if (n === 0) return; this.raise(); for (const c of chunks) { this.reportDebug(`port ${port.id}: ${c.length}B from the guest`); port.deliverFromGuest(c); } } /* ------------------------------------------------------------------ */ /* Transport plumbing. */ /* ------------------------------------------------------------------ */ /** @internal the split-ring for `qidx`, once the guest has published it. */ queue(qidx) { let vq = this.queues.get(qidx); if (vq && vq.ready) return vq; const geom = readQueueGeom(this.mem, this.opts.windowBase, qidx); if (!geom.ready || geom.num === 0) return null; vq = new VirtQueue(this.mem, geom); this.queues.set(qidx, vq); return vq; } /** @internal */ reportError(e) { this.opts.onError?.(e); } /** @internal */ reportInfo(s) { this.opts.onInfo?.(s); } /** @internal */ reportDebug(s) { this.opts.onDebug?.(s); } /** @internal Set INTERRUPT_STATUS, mark the IRQ pending, wake the CPU. */ raise() { const i32 = this.mem.i32; const isOff = this.opts.windowBase + VIRTIO_MMIO_INTERRUPT_STATUS; Atomics.or(i32, isOff >> 2, VIRTIO_MMIO_INT_VRING); if (this.opts.suppressIrq) return; const bit2 = 1 << (this.opts.irqBit ?? 4); Atomics.or(i32, this.opts.irqPendingOffset >> 2, bit2); Atomics.add(i32, this.opts.schedWakeupOffset >> 2, 1); Atomics.notify(i32, this.opts.schedWakeupOffset >> 2, 1); } }; // ../../linux-in-the-browser/hardwarejs/src/hosttrans-abi.ts var WASM_HOSTTRANS_DEVID = 6; var WASM_HOSTTRANS_MAGIC = 1381255255; var WASM_HOSTTRANS_ABI_VERSION = 1; var WASM_HOSTTRANS_F_SESSION = 1 << 0; var WASM_HOSTTRANS_RING_OFF = 256; var WASM_HOSTTRANS_HEADER_SIZE = 128; var WASM_HOSTTRANS_SQ_SLOTS = 64; var WASM_HOSTTRANS_CQ_SLOTS = 64; var WASM_HOSTTRANS_REQ_V1_SIZE = 40; var WASM_HOSTTRANS_CPL_V1_SIZE = 16; var WASM_HOSTTRANS_OP_NOP = 0; var WASM_HOSTTRANS_OP_READ = 1; var WASM_HOSTTRANS_OP_WRITE = 2; var WASM_HOSTTRANS_OP_FLUSH = 3; var WASM_HOSTTRANS_OP_STAT = 4; var WASM_HOSTTRANS_OP_ECHO = 5; var WASM_HOSTTRANS_OP_CLOSE = 6; function hosttransOpName(opcode) { switch (opcode >>> 0) { case WASM_HOSTTRANS_OP_NOP: return "NOP"; case WASM_HOSTTRANS_OP_READ: return "READ"; case WASM_HOSTTRANS_OP_WRITE: return "WRITE"; case WASM_HOSTTRANS_OP_FLUSH: return "FLUSH"; case WASM_HOSTTRANS_OP_STAT: return "STAT"; case WASM_HOSTTRANS_OP_ECHO: return "ECHO"; case WASM_HOSTTRANS_OP_CLOSE: return "CLOSE"; default: return `opcode ${opcode >>> 0} (not a WASM_HOSTTRANS_OP_*)`; } } var HT = { MAGIC: 0, /* magic — KERNEL, release, STORED LAST (publication fence) */ ABI_VERSION: 4, /* abi_version — kernel */ ACTIVE: 8, /* active — HOST. The grant boundary: the guest refuses * -ENODEV while it is 0, so nothing rides an ungranted * transport and the refusal names the device. */ FEATURES: 12, /* features — kernel-written, host-read (WASM_HOSTTRANS_F_*) */ SCHED_WAKE_OFF: 16, /* sched_wake_off — kernel publishes * &__sched_wakeup_word; 0 = absent */ NOTIFY_SEQ: 20, /* notify_seq — kernel, monotonic kick counter * (diagnostic only; nothing waits on it) */ /* SQ: kernel producer -> host consumer (guest -> host). */ SQ_HEAD: 24, /* sq_head — KERNEL producer, release */ SQ_TAIL: 28, /* sq_tail — HOST consumer */ SQ_SLOTS: 32, /* sq_slots — kernel == WASM_HOSTTRANS_SQ_SLOTS */ /* CQ: host producer -> kernel consumer (host -> guest). */ CQ_HEAD: 36, /* cq_head — HOST producer, release */ CQ_TAIL: 40, /* cq_tail — KERNEL consumer */ CQ_SLOTS: 44, /* cq_slots — kernel == WASM_HOSTTRANS_CQ_SLOTS */ MAX_XFER: 48, /* max_xfer — kernel-declared per-request byte ceiling */ RESERVED: 52 /* reserved[19] — zero. A NEW FIELD CARVES FROM HERE plus a * feature bit; it never moves anything above, because every * offset above is hardcoded in this file and in the guest. */ }; var HT_REQ = { REQUEST_ID: 0, /* request_id — u32, echoed back in the completion */ OPCODE: 4, /* opcode — u32, WASM_HOSTTRANS_OP_* */ OBJECT_ID: 8, /* object_id — u32, the object / cache id */ FLAGS: 12, /* flags — u32 */ OFFSET: 16, /* offset — u64, 8-byte aligned BY CONSTRUCTION (it is why * the two u32s above sit where they sit) */ LENGTH: 24, /* length — u32, requested byte count */ BUF_ADDR: 28, /* buf_addr — u32 buffer descriptor: base. 0 = no buffer. */ BUF_LEN: 32, /* buf_len — u32 buffer descriptor: capacity */ SESSION: 36 /* session — u32, the submitting file's id under * WASM_HOSTTRANS_F_SESSION; 0 for an in-kernel caller and * for every request of a kernel without the bit */ }; var HT_CPL = { REQUEST_ID: 0, /* request_id — u32, the submitting request's id */ STATUS: 4, /* status — s32, 0 or -errno. NEVER a silent 0 on a path that * did not do the work. */ LENGTH: 8, /* length — u32, bytes actually transferred */ RESERVED: 12 /* reserved — u32, zero */ }; var WASM_HOSTTRANS_SQ_OFF = WASM_HOSTTRANS_RING_OFF + WASM_HOSTTRANS_HEADER_SIZE; var WASM_HOSTTRANS_SQ_BYTES = WASM_HOSTTRANS_SQ_SLOTS * WASM_HOSTTRANS_REQ_V1_SIZE; var WASM_HOSTTRANS_CQ_OFF = WASM_HOSTTRANS_SQ_OFF + WASM_HOSTTRANS_SQ_BYTES; var WASM_HOSTTRANS_CQ_BYTES = WASM_HOSTTRANS_CQ_SLOTS * WASM_HOSTTRANS_CPL_V1_SIZE; var WASM_HOSTTRANS_RING_END = WASM_HOSTTRANS_CQ_OFF + WASM_HOSTTRANS_CQ_BYTES; function hosttransSqSlotOffset(index) { return WASM_HOSTTRANS_SQ_OFF + index % WASM_HOSTTRANS_SQ_SLOTS * WASM_HOSTTRANS_REQ_V1_SIZE; } function hosttransCqSlotOffset(index) { return WASM_HOSTTRANS_CQ_OFF + index % WASM_HOSTTRANS_CQ_SLOTS * WASM_HOSTTRANS_CPL_V1_SIZE; } // ../../linux-in-the-browser/hardwarejs/src/devices/hosttrans.ts var EIO3 = 5; var EFAULT2 = 14; var ENOSYS4 = 38; var INTERRUPT_STATUS_OFF2 = 96; var INT_VRING = 1; function makeHostTransportHandler(ops = {}, report) { const echo = (req) => { if (req.buf === null) return { status: -EFAULT2, length: 0 }; const n = Math.min(req.length || req.buf.len, req.buf.len); const bytes = req.buf.read(n); req.buf.write(bytes); return { status: 0, length: n }; }; const builtin = { [WASM_HOSTTRANS_OP_NOP]: () => ({ status: 0, length: 0 }), [WASM_HOSTTRANS_OP_ECHO]: echo, [WASM_HOSTTRANS_OP_CLOSE]: () => ({ status: 0, length: 0 }) }; return (req) => { const fn2 = ops[req.opcode] ?? builtin[req.opcode]; if (fn2 === void 0) { report?.( new Error( `hosttrans: no implementation for ${hosttransOpName(req.opcode)} (request_id ${req.requestId}, object_id ${req.objectId}) \u2014 answering -ENOSYS. This backend was given implementations for [${Object.keys(ops).map((k) => hosttransOpName(Number(k))).join(", ") || "none"}] on top of the stateless NOP/ECHO pair.` ) ); return { status: -ENOSYS4, length: 0 }; } return fn2(req); }; } var HostTransportBackend = class { opts; /** The ONE way this device addresses guest RAM. See guest_memory.ts. */ mem; handler; /** Header validated once; a pseudo slot has no other identity check. */ validated = false; /** The kernel declared WASM_HOSTTRANS_F_SESSION in `features`. */ sessions = false; /** A drain is running (possibly parked on an async handler). */ inFlight = false; /** A doorbell arrived while a drain was running; re-run when it ends. */ rekick = false; /* ---- Diagnostics the gates and the unit test read. ---- */ /** Requests taken off the SQ. */ requestsDrained = 0; /** Completions published to the CQ. */ completions = 0; /** Doorbells refused because `active` was 0 (the grant boundary). */ grantRefusals = 0; /** Times the drain stopped early because the CQ was full. */ cqFullStalls = 0; /** Requests answered -ENOSYS by the default handler. */ unimplemented = 0; constructor(opts) { this.opts = opts; this.mem = new GuestMemory(opts); this.handler = opts.handler ?? makeHostTransportHandler({}, (e) => { this.unimplemented++; this.opts.onError?.(e); }); } /** The devid, the pending-word bit index and the JS irqBit. One number. */ get devid() { return WASM_HOSTTRANS_DEVID; } /* ------------------------------------------------------------------ */ /* The grant boundary. */ /* ------------------------------------------------------------------ */ /** * Grant the transport: store `active = 1`. * * `active` is the HOST's word and the guest's whole permission story — the * guest refuses -ENODEV while it is 0, so a machine whose host never * attached a backend gets a named refusal at open/ioctl rather than an * ioctl that hangs on a ring nobody serves. Separate from the constructor * on purpose: constructing a backend is a host-side act, granting one is a * statement to the guest, and the two happen at different moments (the * kernel's device_initcall may not have seeded the ring yet). */ attach() { const i32 = this.mem.i32; const off = this.opts.windowBase + WASM_HOSTTRANS_RING_OFF + HT.ACTIVE; Atomics.store(i32, off >> 2, 1); this.opts.onInfo?.( `hosttrans: granted (devid ${WASM_HOSTTRANS_DEVID}, window 0x${this.opts.windowBase.toString(16)}, active=1)` ); } /** Revoke the grant: store `active = 0`. The guest's next open/ioctl * refuses -ENODEV by name, and this side refuses every doorbell loudly. */ detach() { const i32 = this.mem.i32; const off = this.opts.windowBase + WASM_HOSTTRANS_RING_OFF + HT.ACTIVE; Atomics.store(i32, off >> 2, 0); this.opts.onInfo?.( `hosttrans: grant REVOKED (devid ${WASM_HOSTTRANS_DEVID}, active=0) \u2014 every doorbell from here on is refused` ); } /** True while the host has granted the transport (the `active` word). */ get active() { const i32 = this.mem.i32; const off = this.opts.windowBase + WASM_HOSTTRANS_RING_OFF + HT.ACTIVE; return Atomics.load(i32, off >> 2) >>> 0 !== 0; } /* ------------------------------------------------------------------ */ /* The doorbell. */ /* ------------------------------------------------------------------ */ /** * QUEUE_NOTIFY doorbell for devid 6. `queue` is always 0 (there is one * SQ), and it is ignored rather than refused: the process-Worker deferral * (virtio_wasm.c wasm_virtio_forward_user_kick) coalesces and REPLAYS * kicks, so this entry point must be idempotent. Draining "from sq_tail to * the acquired sq_head" is idempotent by construction — a replayed kick on * an empty SQ does nothing at all. */ onKick(_queue) { if (!this.active) { this.grantRefusals++; this.opts.onError?.( new Error( `hosttrans: doorbell while active=0 (devid ${WASM_HOSTTRANS_DEVID}, window 0x${this.opts.windowBase.toString(16)}) \u2014 refusing to drain an UNGRANTED transport. Nothing was consumed and sq_tail did not move; call attach() to grant it.` ) ); return; } if (!this.ensureValidated()) return; this.pump(); } /** * Validate the kernel-seeded ring header ONCE, loudly. * * `magic` is read first and is the kernel's publication fence: it is * stored last, with release, so a matching magic means every field below * it is already visible. A magic that has not appeared yet is NOT an * error — the host backend exists as soon as the window is carved, which * is before the kernel's device_initcall runs — but it IS a refusal to * serve, and it says so. */ ensureValidated() { if (this.validated) return true; const base = this.opts.windowBase + WASM_HOSTTRANS_RING_OFF; const i32 = this.mem.i32; const magic = Atomics.load(i32, base + HT.MAGIC >> 2) >>> 0; if (magic !== WASM_HOSTTRANS_MAGIC) { this.opts.onError?.( new Error( `hosttrans: ring header not seeded (magic 0x${magic.toString(16)}, want 0x${WASM_HOSTTRANS_MAGIC.toString(16)} "WHTR") at window 0x${this.opts.windowBase.toString(16)}+0x${WASM_HOSTTRANS_RING_OFF.toString(16)} \u2014 refusing to drain. A kernel without the wasm_hosttrans device, or one whose device_initcall has not run yet, never stores it.` ) ); return false; } const abi = Atomics.load(i32, base + HT.ABI_VERSION >> 2) >>> 0; const sqSlots = Atomics.load(i32, base + HT.SQ_SLOTS >> 2) >>> 0; const cqSlots = Atomics.load(i32, base + HT.CQ_SLOTS >> 2) >>> 0; if (abi !== WASM_HOSTTRANS_ABI_VERSION || sqSlots !== WASM_HOSTTRANS_SQ_SLOTS || cqSlots !== WASM_HOSTTRANS_CQ_SLOTS) { this.opts.onError?.( new Error( `hosttrans: ABI/geometry mismatch \u2014 kernel says abi_version=${abi} sq_slots=${sqSlots} cq_slots=${cqSlots}; this host is built for abi_version=${WASM_HOSTTRANS_ABI_VERSION} sq_slots=${WASM_HOSTTRANS_SQ_SLOTS} cq_slots=${WASM_HOSTTRANS_CQ_SLOTS} (src/hosttrans-abi.ts). Refusing to serve: bump BOTH halves in one commit.` ) ); return false; } this.validated = true; const maxXfer = Atomics.load(i32, base + HT.MAX_XFER >> 2) >>> 0; const features = Atomics.load(i32, base + HT.FEATURES >> 2) >>> 0; this.sessions = (features & WASM_HOSTTRANS_F_SESSION) !== 0; this.opts.onInfo?.( `hosttrans: ring v${abi} up \u2014 ${sqSlots} SQ / ${cqSlots} CQ slots, max_xfer ${maxXfer}B, features 0x${features.toString(16)}` ); return true; } /* ------------------------------------------------------------------ */ /* The drain. */ /* ------------------------------------------------------------------ */ /** Start a drain, or note that one is already running. */ pump() { if (this.inFlight) { this.rekick = true; return; } this.inFlight = true; this.drain(); } /** * Consume the SQ until it is empty, the CQ is full, or a handler goes * async. SYNCHRONOUS for a synchronous handler from end to end: everything * a kick can complete is completed before onKick returns. */ drain() { for (; ; ) { const item = this.take(); if (item === null) break; let res; try { res = this.handler(item.req); } catch (e) { this.publishThrow(item, e); continue; } if (res instanceof Promise) { void this.finishAsync(item, res); return; } this.publish(item, res); } this.settle(); } async finishAsync(item, p) { let res; try { res = await p; } catch (e) { this.publishThrow(item, e); this.drain(); return; } this.publish(item, res); this.drain(); } settle() { this.inFlight = false; if (this.rekick) { this.rekick = false; this.pump(); } } /** * Take the next SQ entry, or null when there is nothing to do. * * THE CQ CHECK COMES FIRST, and that ordering is the whole "short write, * never drop" contract: a request is only consumed once there is somewhere * for its completion to go. Reserving the CQ index here (rather than at * publish time) is also what makes the one-in-flight rule sufficient. */ take() { const win = this.opts.windowBase; const ring = win + WASM_HOSTTRANS_RING_OFF; const i32 = this.mem.i32; const sqHead = Atomics.load(i32, ring + HT.SQ_HEAD >> 2) >>> 0; const sqTail = Atomics.load(i32, ring + HT.SQ_TAIL >> 2) >>> 0; if (sqHead === sqTail) return null; const pending2 = sqHead - sqTail >>> 0; if (pending2 > WASM_HOSTTRANS_SQ_SLOTS) { this.opts.onError?.( new Error( `hosttrans: SQ indices are impossible \u2014 sq_head=${sqHead} sq_tail=${sqTail} means ${pending2} pending in a ${WASM_HOSTTRANS_SQ_SLOTS}-slot ring. Refusing to read a slot the producer may still be filling; this is ring corruption, not backpressure.` ) ); return null; } const cqHead = Atomics.load(i32, ring + HT.CQ_HEAD >> 2) >>> 0; const cqTail = Atomics.load(i32, ring + HT.CQ_TAIL >> 2) >>> 0; const outstanding = cqHead - cqTail >>> 0; if (outstanding > WASM_HOSTTRANS_CQ_SLOTS) { this.opts.onError?.( new Error( `hosttrans: CQ indices are impossible \u2014 cq_head=${cqHead} cq_tail=${cqTail} means ${outstanding} outstanding in a ${WASM_HOSTTRANS_CQ_SLOTS}-slot ring. Refusing to publish.` ) ); return null; } if (outstanding === WASM_HOSTTRANS_CQ_SLOTS) { this.cqFullStalls++; this.opts.onError?.( new Error( `hosttrans: CQ full (${WASM_HOSTTRANS_CQ_SLOTS} completions the guest has not consumed, cq_tail=${cqTail}) with ${pending2} request(s) still in the SQ \u2014 stopping the drain here. NOTHING IS DROPPED: sq_tail stays at ${sqTail} and the next doorbell resumes at that request.` ) ); this.raise(); return null; } const slotOff = win + hosttransSqSlotOffset(sqTail); const dv = this.mem.dv; const bufAddr = dv.getUint32(slotOff + HT_REQ.BUF_ADDR, true); const bufLen = dv.getUint32(slotOff + HT_REQ.BUF_LEN, true); const req = { requestId: dv.getUint32(slotOff + HT_REQ.REQUEST_ID, true), opcode: dv.getUint32(slotOff + HT_REQ.OPCODE, true), objectId: dv.getUint32(slotOff + HT_REQ.OBJECT_ID, true), flags: dv.getUint32(slotOff + HT_REQ.FLAGS, true), offset: dv.getBigUint64(slotOff + HT_REQ.OFFSET, true), length: dv.getUint32(slotOff + HT_REQ.LENGTH, true), buf: bufAddr === 0 ? null : this.makeBuffer(bufAddr, bufLen), session: this.sessions ? dv.getUint32(slotOff + HT_REQ.SESSION, true) : 0 }; Atomics.store(i32, ring + HT.SQ_TAIL >> 2, sqTail + 1 | 0); this.requestsDrained++; return { req, cqIndex: cqHead }; } /** * The handler's window onto the payload. Holds the {@link GuestMemory}, * never a view off it — every call below re-derives, so a buffer held * across an `await` (and across the grow that await allowed) still names * the right bytes. */ makeBuffer(addr, len) { const mem = this.mem; return { addr, len, read(n) { const want = n === void 0 ? len : n; if (want < 0 || want > len) throw new RangeError( `hosttrans buffer read: ${want}B asked of a ${len}B descriptor at 0x${addr.toString(16)} \u2014 the descriptor's capacity is the whole permission, and reading past it would read another allocation` ); return mem.read(addr, want); }, write(bytes, at = 0) { if (at < 0 || at + bytes.length > len) throw new RangeError( `hosttrans buffer write: ${bytes.length}B at +${at} into a ${len}B descriptor at 0x${addr.toString(16)} \u2014 REFUSED rather than truncated. A silent truncation here is a short transfer the guest reports to userspace as a complete one.` ); mem.write(addr + at, bytes); return bytes.length; } }; } /** Publish one completion and raise. Fill the slot, THEN release cq_head. */ publish(item, res) { const win = this.opts.windowBase; const ring = win + WASM_HOSTTRANS_RING_OFF; if (!Number.isInteger(res.status) || res.status > 0) { this.opts.onError?.( new Error( `hosttrans: handler answered status=${res.status} for ${hosttransOpName(item.req.opcode)} request_id ${item.req.requestId}; cpl.status is 0 or -errno and nothing else. Completing -EIO.` ) ); res = { status: -EIO3, length: 0 }; } const cplOff = win + hosttransCqSlotOffset(item.cqIndex); const dv = this.mem.dv; dv.setUint32(cplOff + HT_CPL.REQUEST_ID, item.req.requestId >>> 0, true); dv.setInt32(cplOff + HT_CPL.STATUS, res.status | 0, true); dv.setUint32(cplOff + HT_CPL.LENGTH, res.length >>> 0, true); dv.setUint32(cplOff + HT_CPL.RESERVED, 0, true); const i32 = this.mem.i32; Atomics.store(i32, ring + HT.CQ_HEAD >> 2, item.cqIndex + 1 | 0); this.completions++; this.raise(); } /** A handler that threw is an -EIO completion WITH ATTRIBUTION, never a * dropped request: the guest is blocked on this request_id. */ publishThrow(item, e) { this.opts.onError?.( new Error( `hosttrans: handler threw on ${hosttransOpName(item.req.opcode)} request_id ${item.req.requestId} object_id ${item.req.objectId}: ${e instanceof Error ? e.message : String(e)} \u2014 completing -EIO rather than leaving the guest blocked on it` ) ); this.publish(item, { status: -EIO3, length: 0 }); } /* ------------------------------------------------------------------ */ /* The interrupt. */ /* ------------------------------------------------------------------ */ /** * Inject this device's interrupt: the canonical four atomics. * * The first is decorative for a pseudo slot (see INTERRUPT_STATUS_OFF * above) and is kept so this is the same raise as every sibling backend's. * The three that carry it: set pending bit `irqBit` (== devid, which is * what wasm_virtio_drain_irqs bit-walks into wasm_virtio_devs[6].irq), * bump __sched_wakeup_word, and notify the idle CPU parked on it. * * IF WASM_VIRTIO_MAX_DEV IS STILL 6 KERNEL-SIDE, this raise lands in a * pending word nobody walks: the drain's `bit < WASM_VIRTIO_MAX_DEV` bound * consumes bit 6 and drops it. That much is silent — but the kernel does * NOT get that far, and saying it does sends the reader to the wrong file. * MEASURED 2026-08-27 by building the gate kernel with the constant back at * 6: `wasm_virtio_add_pseudo_device` refuses `devid >= WASM_VIRTIO_MAX_DEV` * outright, so the boot prints `wasm-hosttrans: pseudo-device slot 6 * refused: -22`, /dev/hwjs-transport never appears, and every submit is * refused -ENODEV by name. The devid-6 gate fails on its first assertion in * 413 ms; nothing hangs. The kernel half of this change raises it to 7. */ raise() { const i32 = this.mem.i32; Atomics.or(i32, this.opts.windowBase + INTERRUPT_STATUS_OFF2 >> 2, INT_VRING); if (this.opts.suppressIrq) return; const bit2 = 1 << (this.opts.irqBit ?? WASM_HOSTTRANS_DEVID); Atomics.or(i32, this.opts.irqPendingOffset >> 2, bit2); Atomics.add(i32, this.opts.schedWakeupOffset >> 2, 1); Atomics.notify(i32, this.opts.schedWakeupOffset >> 2, 1); } }; // ../../linux-in-the-browser/hardwarejs/src/bootKernel.ts async function bootKernel(opts) { if (Object.prototype.hasOwnProperty.call(opts, "initramfs")) { throw new Error("bootKernel: initramfs is unsupported; supply the selected root filesystem device."); } const roots = (opts.cmdline ?? "").split(/\s+/).filter((token) => token.startsWith("prestrike.rootfs=")); if (roots.length !== 1 || !["prestrike.rootfs=virtiofs", "prestrike.rootfs=ext4", "prestrike.rootfs=nfs"].includes(roots[0])) { throw new Error("bootKernel: exactly one supported prestrike.rootfs= selection is required (virtiofs, ext4 or nfs); no fallback root."); } if (roots[0] === "prestrike.rootfs=ext4" && !opts.virtioBlk) { throw new Error("bootKernel: ext4 root selected without a virtio block device; no fallback root."); } const wasmSupport = preflightWasmBootSupport(); if (!wasmSupport.ok) { throw new Error(`bootKernel: ${wasmSupport.message}`); } const rootProvider = requireRegisteredGuestRoot({ cmdline: opts.cmdline, fsView: opts.virtioFs?.fs }); if (rootProvider !== void 0) { opts.onDmesg?.( 6, `hwjs-root: guest root served by mount provider "${rootProvider.kind}" <- ${rootProvider.origin}` + (rootProvider.note ? ` (${rootProvider.note})` : "") + ` ` ); } const platform = opts.platform ?? detectPlatform2(); const kernelMemory = opts.ram.kernelMemory; const numVcpu = resolveNumVcpu(opts.num_vcpu); const kernelCpus = numVcpu; { const suppliedPool = opts.spawnHandler?.poolStats?.(); const poolTop = suppliedPool?.enabled && suppliedPool.poolSize > 0 ? suppliedPool.poolSize | 0 : numVcpu - 1; opts.onDmesg?.(6, `hwjs-lanes: kernel CPUs 0..${kernelCpus - 1}, pool lanes 1..${poolTop} `); } if (opts.spawnHandler) { const stats = opts.spawnHandler.poolStats?.(); if (stats?.enabled && stats.poolSize > numVcpu - 1) { throw new Error( `bootKernel: vCPU topology mismatch \u2014 the supplied spawnHandler has a pool of ${stats.poolSize} CPU-Workers (cpu_ids 1..${stats.poolSize}) but num_vcpu=${numVcpu} tells the kernel only CPUs 0..${numVcpu - 1} exist. A pool Worker on a CPU the kernel considers impossible reads __per_cpu_offset==0 and corrupts memory through garbage per-CPU pointers (linux-in-the-browser#61). Pass consistent values: bootKernel({ num_vcpu: N }) with makeKernelSpawnHandler({ maxCpuId: N - 1 }).` ); } opts.spawnHandler.__setLaneCeiling?.(kernelCpus - 1); } const worker = await createWorker2(); const cpu0TookAWorkerRealm = workerRealmOrigin(worker) !== void 0; opts.onDmesg?.( 6, `hwjs-realms: CPU 0 is ${cpu0TookAWorkerRealm ? "a host Worker realm" : "an INLINE realm in the launching thread \u2014 no Worker"}; expecting ${expectedWorkerRealms(kernelCpus)} Worker realm(s) for num_vcpu=${kernelCpus} ` ); if (cpu0TookAWorkerRealm) { throw new Error( `bootKernel: CPU 0 took a host Worker realm (the census holds the realm createWorker returned). CPU 0 and pool lane 1 share the thread that called bootKernel \u2014 that is the only topology this runtime has \u2014 so this is an internal defect in createWorker, not a configuration error, and the machine it would produce has a lane 1 bound in the launching thread while CPU 0 blocks a Worker's.` ); } const pauseSab = opts.pauseBuffer ?? new SharedArrayBuffer(4); const pauseArr = new Int32Array(pauseSab); const dmesg = []; const unimplementedCalls = []; let schedWakeupWordOffset; let spawnRingOffset; let spawnConsumer; let signalRingOffset; let signalConsumer; let ptyBridgeRingOffset; let serialBridgeRingOffset; let virtsndWindowBase; let virtsndBackend; const virtsndPendingKicks = []; let virtblkWindowBase; let virtblkBackend; const virtblkPendingKicks = []; let virtioWindowBase; let virtioIrqPendingOffset; let virtioBackend; const virtioPendingKicks = []; let virtfscacheWindowBase; let virtfscacheBackend; const virtfscachePendingKicks = []; let virtinputWindowBase; let virtinputBackend; const virtinputPendingKicks = []; let virtnetWindowBase; let virtnetBackend; const virtnetPendingKicks = []; let usbWindowBase; let usbBackend2; const usbPendingKicks = []; let virtconWindowBase; let virtconBackend; const virtconPendingKicks = []; let hosttransWindowBase; let hosttransBackend; const hosttransPendingKicks = []; let fbCtrlOffset; let fbMaxWidth = 0; let fbMaxHeight = 0; let displayControlFired = false; let displaySlotsOffset = 0; let displaySlotsFired = false; let schedNudgeTimer; let tickReqOffset; let committedPagesOffset; let kernelSabBytes = kernelMemory.buffer.byteLength; const syncDrainDisabled = !!(globalThis.process?.env?.HWJS_MERGED_NO_SYNC_DRAIN || globalThis.HWJS_MERGED_NO_SYNC_DRAIN); const drainSyncServiceableDevices = () => { if (syncDrainDisabled) return; if (virtconBackend !== void 0) { const qCount = 2 * ((virtconBackend.maxNrPorts | 0) + 1); for (let q = 0; q < qCount; q++) virtconBackend.onKick(q); } virtblkBackend?.onKick(0); virtsndBackend?.onKick(0); if (virtioBackend !== void 0) { virtioBackend.onKick(0); virtioBackend.onKick(1); } if (virtfscacheBackend !== void 0) { virtfscacheBackend.onKick(0); virtfscacheBackend.onKick(1); } }; if (syncDrainDisabled) opts.onDmesg?.( 4, "[hwjs-merged] RED ARM: HWJS_MERGED_NO_SYNC_DRAIN is set \u2014 the synchronous doorbell drain is NOT installed for ANY device (virtio-console, virtio-fs root, virtio-fs /cache). A merged CPU 0 that enters an in-kernel busy-wait on one of them must now end it from inside the guest (budgeted checkpoints); nothing on this side will." ); registerSyncDeviceDrain(drainSyncServiceableDevices); const hostSyncCall = (m) => { if (m?.kind === "virtio-drain-sync") { runSyncDeviceDrain(); return true; } return void 0; }; worker.setHostSyncCall?.(hostSyncCall); opts.spawnHandler?.__setHostSyncCall?.(hostSyncCall); const armSchedNudge = () => { if (schedNudgeTimer !== void 0) return; if (virtblkBackend === void 0 && virtsndBackend === void 0 && virtioBackend === void 0 && virtinputBackend === void 0 && virtnetBackend === void 0 && tickReqOffset === void 0 || schedWakeupWordOffset === void 0) return; const wakeIdx = schedWakeupWordOffset >> 2; const tickIdx = tickReqOffset !== void 0 ? tickReqOffset >> 2 : void 0; schedNudgeTimer = setInterval(() => { try { const i32 = new Int32Array(kernelMemory.buffer); if (tickIdx !== void 0) Atomics.add(i32, tickIdx, 1); Atomics.add(i32, wakeIdx, 1); Atomics.notify(i32, wakeIdx, 1); opts.ram.publishUserSabPages(); } catch { } }, 12); }; const maybeStartVirtioSndBackend = () => { if (virtsndBackend || !opts.virtioSound || virtsndWindowBase === void 0 || virtioIrqPendingOffset === void 0 || schedWakeupWordOffset === void 0) return; virtsndBackend = new VirtioSndBackend({ kernelMemory: kernelMemory.buffer, kernelMemoryWasm: kernelMemory, windowBase: virtsndWindowBase, irqPendingOffset: virtioIrqPendingOffset, schedWakeupOffset: schedWakeupWordOffset, sink: opts.virtioSound.sink, suppressIrq: opts.virtioSound.suppressIrq, onError: (error) => opts.onDmesg?.(3, `[virtio-snd-backend] ${error.message}`) }); for (const q of virtsndPendingKicks) virtsndBackend.onKick(q); virtsndPendingKicks.length = 0; armSchedNudge(); }; const maybeStartVirtioBlkBackend = () => { if (virtblkBackend || !opts.virtioBlk || virtblkWindowBase === void 0 || virtioIrqPendingOffset === void 0 || schedWakeupWordOffset === void 0) return; virtblkBackend = new VirtioBlkBackend({ kernelMemory: kernelMemory.buffer, kernelMemoryWasm: kernelMemory, windowBase: virtblkWindowBase, irqPendingOffset: virtioIrqPendingOffset, schedWakeupOffset: schedWakeupWordOffset, disk: opts.virtioBlk.disk, suppressIrq: opts.virtioBlk.suppressIrq, onError: (error) => opts.onDmesg?.(3, `[virtio-blk-backend] ${error.message}`) }); for (const q of virtblkPendingKicks) virtblkBackend.onKick(q); virtblkPendingKicks.length = 0; armSchedNudge(); }; const maybeStartVirtioBackend = () => { if (virtioBackend !== void 0 || opts.virtioFs === void 0 || virtioWindowBase === void 0 || virtioIrqPendingOffset === void 0 || schedWakeupWordOffset === void 0) return; virtioBackend = new VirtioFsBackend({ kernelMemory: kernelMemory.buffer, /* env.kernel_memory grows on guest demand; the backend re-derives its * views from this Memory whenever the buffer identity changes, because * it follows descriptors into arbitrary guest frames. */ kernelMemoryWasm: kernelMemory, windowBase: virtioWindowBase, irqPendingOffset: virtioIrqPendingOffset, schedWakeupOffset: schedWakeupWordOffset, fs: opts.virtioFs.fs, suppressIrq: opts.virtioFs.suppressIrq, onError: (e) => opts.onDmesg?.(3, `[virtio-fs-backend] ${e.message}`) }); for (const q of virtioPendingKicks) virtioBackend.onKick(q); virtioPendingKicks.length = 0; armSchedNudge(); }; const maybeStartVirtioFsCacheBackend = () => { if (virtfscacheBackend !== void 0 || opts.virtioFsCache === void 0 || virtfscacheWindowBase === void 0 || virtioIrqPendingOffset === void 0 || schedWakeupWordOffset === void 0) return; virtfscacheBackend = new VirtioFsBackend({ kernelMemory: kernelMemory.buffer, kernelMemoryWasm: kernelMemory, windowBase: virtfscacheWindowBase, irqPendingOffset: virtioIrqPendingOffset, schedWakeupOffset: schedWakeupWordOffset, fs: opts.virtioFsCache.fs, suppressIrq: opts.virtioFsCache.suppressIrq, irqBit: 5, /* devid 5 -> pending bit 5 (matches the kernel drain) */ onError: (e) => opts.onDmesg?.(3, `[virtio-fs-cache-backend] ${e.message}`) }); for (const q of virtfscachePendingKicks) virtfscacheBackend.onKick(q); virtfscachePendingKicks.length = 0; armSchedNudge(); }; const maybeStartVirtioInputBackend = () => { if (virtinputBackend !== void 0 || opts.virtioInput === void 0 || virtinputWindowBase === void 0 || virtioIrqPendingOffset === void 0 || schedWakeupWordOffset === void 0) return; virtinputBackend = new VirtioInputBackend({ kernelMemory: kernelMemory.buffer, /* env.kernel_memory grows on guest demand; the backend re-derives its * views from this Memory whenever the buffer identity changes, because * it follows descriptors into arbitrary guest frames. */ kernelMemoryWasm: kernelMemory, windowBase: virtinputWindowBase, irqPendingOffset: virtioIrqPendingOffset, schedWakeupOffset: schedWakeupWordOffset, irqBit: 1, /* device 1 -> pending bit 1 (matches the kernel drain) */ suppressIrq: opts.virtioInput.suppressIrq, onError: (e) => opts.onDmesg?.(3, `[virtio-input-backend] ${e.message}`), /* Diagnostic seam (HWJS-C-1 dual-console debugging): per-event inject/ * IRQ tracing through the normal dmesg channel. Opt-in via the * HWJS_INPUT_DBG env var (node) or a same-named global the operator * can flip from the browser console BEFORE boot. */ ...globalThis.process?.env?.HWJS_INPUT_DBG || globalThis.HWJS_INPUT_DBG ? { onDebug: (s) => opts.onDmesg?.(7, `[virtio-input] ${s}`) } : {} }); for (const q of virtinputPendingKicks) virtinputBackend.onKick(q); virtinputPendingKicks.length = 0; armSchedNudge(); const be = virtinputBackend; opts.onInputReady?.((type, code2, value) => be.injectEvent(type, code2, value)); }; const maybeStartVirtioNetBackend = () => { if (virtnetBackend !== void 0 || opts.virtioNet === void 0 || virtnetWindowBase === void 0 || virtioIrqPendingOffset === void 0 || schedWakeupWordOffset === void 0) return; virtnetBackend = new VirtioNetBackend({ kernelMemory: kernelMemory.buffer, /* env.kernel_memory grows on guest demand; the backend re-derives its * views from this Memory whenever the buffer identity changes, because * it follows descriptors into arbitrary guest frames. */ kernelMemoryWasm: kernelMemory, windowBase: virtnetWindowBase, irqPendingOffset: virtioIrqPendingOffset, schedWakeupOffset: schedWakeupWordOffset, irqBit: 2, /* device 2 -> pending bit 2 (matches the kernel drain) */ suppressIrq: opts.virtioNet.suppressIrq, /* PLAN-STORAGE-FABRIC-NFS §3/§4. Absent => 1500 + the MITM shim, i.e. * exactly what every rig does today. */ ...opts.virtioNet.mtu !== void 0 ? { mtu: opts.virtioNet.mtu } : {}, ...opts.virtioNet.mergeRxBuf !== void 0 ? { mergeRxBuf: opts.virtioNet.mergeRxBuf } : {}, ...opts.virtioNet.link !== void 0 ? { link: opts.virtioNet.link } : {}, /* PLAN-STORAGE-FABRIC-NFS: the appliance's TWO-PLANE NIC. `link` binds * the whole device to the fabric and leaves the shim inert, which is * right for a rig and wrong for the appliance — whose single NIC is also * its egress gateway on 10.0.2.2:3128, the path its in-guest brintos-fs * client fetches over. The device implements the L3 split * (`planeForDestination`); it was simply unreachable from here, so a * `fabric` on the options object was a field bootKernel dropped on the * floor and the appliance's uplink could only ever be "not wired yet". */ ...opts.virtioNet.fabric !== void 0 ? { fabric: opts.virtioNet.fabric } : {}, /* HWJS-C-2.c: thread the served FsView (key gate), the fetch impl, and * the NaaS forward boundary into the MITM shim. */ ...opts.virtioNet.fs !== void 0 ? { fs: opts.virtioNet.fs } : {}, ...opts.virtioNet.fetchImpl !== void 0 ? { fetchImpl: opts.virtioNet.fetchImpl } : {}, ...opts.virtioNet.httpPortMapping !== void 0 ? { httpPortMapping: opts.virtioNet.httpPortMapping } : {}, ...opts.virtioNet.gateway !== void 0 ? { gateway: opts.virtioNet.gateway } : {}, ...opts.virtioNet.naas !== void 0 ? { naas: opts.virtioNet.naas } : {}, ...opts.virtioNet.packetUplink !== void 0 ? { packetUplink: opts.virtioNet.packetUplink } : {}, onError: (e) => opts.onDmesg?.(3, `[virtio-net-backend] ${e.message}`), /* Never-silent contract: notable events (first tx, ARP/DNS/fetch, the * key-gate decision, and every NaaS-forward refusal) reach dmesg. */ onInfo: (s) => opts.onDmesg?.(6, `[virtio-net] ${s}`), /* Verbose per-frame trace, opt-in via HWJS_NET_DBG (node env or a * same-named global flipped from the browser console before boot). */ ...globalThis.process?.env?.HWJS_NET_DBG || globalThis.HWJS_NET_DBG ? { onDebug: (s) => opts.onDmesg?.(7, `[virtio-net] ${s}`) } : {} }); for (const q of virtnetPendingKicks) virtnetBackend.onKick(q); virtnetPendingKicks.length = 0; armSchedNudge(); opts.onNetReady?.(virtnetBackend); }; const maybeStartUsbHcdBackend = () => { if (usbBackend2 !== void 0 || opts.usbHcd === void 0 || usbWindowBase === void 0 || virtioIrqPendingOffset === void 0 || schedWakeupWordOffset === void 0) return; usbBackend2 = new UsbHcdBackend({ kernelMemory: kernelMemory.buffer, /* env.kernel_memory grows on guest demand; the backend re-derives its * views from this Memory whenever the buffer identity changes, because * it follows descriptors into arbitrary guest frames. */ kernelMemoryWasm: kernelMemory, windowBase: usbWindowBase, irqPendingOffset: virtioIrqPendingOffset, schedWakeupOffset: schedWakeupWordOffset, irqBit: 3, /* devid 3 -> pending bit 3 (matches the kernel drain) */ suppressIrq: opts.usbHcd.suppressIrq, onError: (e) => opts.onDmesg?.(3, `[usb-hcd-backend] ${e.message}`), /* Never-silent contract: attach/detach, every grant refusal and * transfer error reach dmesg AND the caller's event stream. */ onEvent: (ev) => { opts.onDmesg?.( ev.kind === "attach" || ev.kind === "detach" ? 6 : 4, `[usb-hcd] ${ev.kind} port ${ev.port}: ${ev.detail}` ); opts.usbHcd?.onEvent?.(ev); }, ...globalThis.process?.env?.HWJS_USB_DBG || globalThis.HWJS_USB_DBG ? { onDebug: (s) => opts.onDmesg?.(7, `[usb-hcd] ${s}`) } : {} }); for (const q of usbPendingKicks) usbBackend2.onKick(q); usbPendingKicks.length = 0; armSchedNudge(); opts.onUsbReady?.(usbBackend2); }; const maybeStartVirtioConsoleBackend = () => { if (virtconBackend !== void 0 || opts.virtioConsole === void 0 || virtconWindowBase === void 0 || virtioIrqPendingOffset === void 0 || schedWakeupWordOffset === void 0) return; virtconBackend = new VirtioConsoleBackend({ kernelMemory: kernelMemory.buffer, /* env.kernel_memory grows on guest demand; the backend re-derives its * views from this Memory whenever the buffer identity changes, because * it follows descriptors into arbitrary guest frames. */ kernelMemoryWasm: kernelMemory, windowBase: virtconWindowBase, irqPendingOffset: virtioIrqPendingOffset, schedWakeupOffset: schedWakeupWordOffset, irqBit: 4, /* devid 4 -> pending bit 4 (matches the kernel drain) */ ...opts.virtioConsole.ports ? { ports: opts.virtioConsole.ports } : {}, ...opts.virtioConsole.suppressIrq ? { suppressIrq: true } : {}, onError: (e) => opts.onDmesg?.(3, `[virtio-console] ${e.message}`), /* Never-silent: the handshake and every open/close reach dmesg. A * machine whose control port never opens has to say so on the console * it does have, because it has no other way to be asked. */ onInfo: (msg) => opts.onDmesg?.(6, `[virtio-console] ${msg}`), ...globalThis.process?.env?.HWJS_VIRTCON_DBG || globalThis.HWJS_VIRTCON_DBG ? { onDebug: (s) => opts.onDmesg?.(7, `[virtio-console] ${s}`) } : {} }); for (const q of virtconPendingKicks) virtconBackend.onKick(q); virtconPendingKicks.length = 0; armSchedNudge(); opts.onConsolePortsReady?.(virtconBackend); }; const maybeStartHostTransBackend = () => { if (hosttransBackend !== void 0 || opts.hostTransport === void 0 || hosttransWindowBase === void 0 || virtioIrqPendingOffset === void 0 || schedWakeupWordOffset === void 0) return; hosttransBackend = new HostTransportBackend({ kernelMemory: kernelMemory.buffer, /* env.kernel_memory grows on guest demand; the backend re-derives its * views from this Memory whenever the buffer identity changes, because * a request's buf_addr points into arbitrary guest frames. */ kernelMemoryWasm: kernelMemory, windowBase: hosttransWindowBase, irqPendingOffset: virtioIrqPendingOffset, schedWakeupOffset: schedWakeupWordOffset, irqBit: 6, /* devid 6 -> pending bit 6 (matches the kernel drain) */ ...opts.hostTransport.handler ? { handler: opts.hostTransport.handler } : {}, ...opts.hostTransport.suppressIrq ? { suppressIrq: true } : {}, onError: (e) => opts.onDmesg?.(3, `[hosttrans] ${e.message}`), /* Never-silent: the grant, the ring validation and every refusal reach * the console the machine actually has. A transport whose guest is * blocked on a ring nobody serves has no other way to be asked. */ onInfo: (msg) => opts.onDmesg?.(6, `[hosttrans] ${msg}`) }); hosttransBackend.attach(); for (const q of hosttransPendingKicks) hosttransBackend.onKick(q); hosttransPendingKicks.length = 0; armSchedNudge(); opts.onHostTransportReady?.(hosttransBackend); }; const maybeFireDisplaySlots = () => { if (displaySlotsFired || opts.onDisplaySlots === void 0 || displaySlotsOffset === 0 || schedWakeupWordOffset === void 0) return; displaySlotsFired = true; const table = displaySlotsOffset; const wakeOffset = schedWakeupWordOffset; const i32 = () => new Int32Array(kernelMemory.buffer); const slot = (d) => { if (!(d >= 1 && d <= WASM32_DISPLAY_SLOTS)) throw new RangeError(`no display slot ${d}`); return table + (d - 1) * DISPLAY_SLOT_BYTES; }; const kick = () => kickKernelScheduler(kernelMemory.buffer, wakeOffset); const request = (d, plugReq) => { const s = slot(d); const m = i32(); Atomics.store(m, s + DS.PLUG_REQ >> 2, plugReq | 0); const seq = Atomics.add(m, s + DS.PLUG_SEQ >> 2, 1) + 1 >>> 0; kick(); return seq; }; opts.onDisplaySlots({ count: WASM32_DISPLAY_SLOTS, plug: (d, maxWidth, maxHeight, width, height) => { const s = slot(d); Atomics.store(i32(), s + DS.CTRL >> 2, (height & 65535) << 16 | width & 65535); return request(d, (maxHeight & 65535) << 16 | maxWidth & 65535); }, unplug: (d) => request(d, 0), read: (d) => { const s = slot(d); const m = i32(); const word2 = (off) => Atomics.load(m, s + off >> 2) >>> 0; const state = word2(DS.STATE) | 0; const maxdim = word2(DS.MAXDIM); const minors = word2(DS.MINORS); const applied = word2(DS.CTRL + 4); const maxWidth = maxdim & 65535; const maxHeight = maxdim >>> 16; const stride = word2(DS.STRIDE); return { ack: word2(DS.PLUG_ACK), state, window: state === 1 ? { base: word2(DS.BASE), width: applied & 65535, height: applied >>> 16, stride, size: stride * maxHeight, format: DISPLAY_SLOT_FORMAT, maxWidth, maxHeight, ctrlOffset: s + DS.CTRL } : null, card: state === 1 ? minors >>> 16 : -1, fb: state === 1 ? minors & 65535 : -1 }; }, setMode: (d, width, height) => { const s = slot(d); const m = i32(); const maxdim = Atomics.load(m, s + DS.MAXDIM >> 2) >>> 0; const w = Math.max(16, Math.min(maxdim & 65535 || 65535, width | 0)); const h = Math.max(16, Math.min(maxdim >>> 16 || 65535, height | 0)); Atomics.store(m, s + DS.CTRL >> 2, h << 16 | w | 0); Atomics.add(m, s + DS.CTRL + 8 >> 2, 1); kick(); } }); }; const maybeFireDisplayControl = () => { if (displayControlFired || opts.onDisplayControl === void 0 || fbCtrlOffset === void 0 || fbCtrlOffset === 0 || schedWakeupWordOffset === void 0) return; displayControlFired = true; const ctrl = fbCtrlOffset; const wakeOffset = schedWakeupWordOffset; opts.onDisplayControl({ setMode: (width, height) => { const w = Math.max(16, Math.min(fbMaxWidth || 65535, width | 0)); const h = Math.max(16, Math.min(fbMaxHeight || 65535, height | 0)); try { const i32 = new Int32Array(kernelMemory.buffer); Atomics.store(i32, ctrl >> 2, h << 16 | w | 0); Atomics.add(i32, ctrl + 8 >> 2, 1); kickKernelScheduler( kernelMemory.buffer, wakeOffset ); } catch { } } }); }; const signalRegistry = opts.signalHandler === void 0 ? opts.signalRegistry ?? createSignalTargetRegistry() : void 0; const ENOSYS5 = -38; let effectiveSpawnHandler; let vmlinuxModule = opts.vmlinuxModule; let vmlinuxCompileError; try { if (vmlinuxModule === void 0) { if (opts.wasmBytes === void 0) { throw new Error( "bootKernel: neither `wasmBytes` nor `vmlinuxModule` was supplied \u2014 there is no kernel image to boot (never-silent)." ); } vmlinuxModule = await WebAssembly.compile(opts.wasmBytes); } } catch (e) { vmlinuxCompileError = e instanceof Error ? e.message : String(e); console.warn( `[hardwarejs] bootKernel: K11-B2a vmlinux WebAssembly.compile failed: ${vmlinuxCompileError}. This Module is what the kernel Worker boots, so the boot below will refuse; the K11-A1 substrate probe should have caught this at boot-prep time.` ); } let hwjsRt; if (vmlinuxModule !== void 0) { hwjsRt = await extractHwjsRt(vmlinuxModule); if (hwjsRt === void 0) { console.log( `[hardwarejs] bootKernel: vmlinux carries no hwjs.rt.so section \u2014 dynamic mains will use main-linked runtimes` ); } } if (opts.spawnHandler) { if (hwjsRt !== void 0 && opts.spawnHandler.carriesHwjsRt !== true) { console.warn( `[hardwarejs] bootKernel: kernel provides a hwjs runtime but you supplied your own spawnHandler \u2014 bootKernel cannot inject it. Pass hwjsRtModule/hwjsRtBytes/hwjsRtProvenance (from extractHwjsRt(vmlinuxModule)) to makeKernelSpawnHandler, or dynamic mains will fail at exec with "kernel ships no libhwjs-rt".` ); } effectiveSpawnHandler = opts.spawnHandler; } else if (opts.userWorkerEntry) { const jsHeapBudget = jsHeapBudgetFromCmdline(opts.cmdline); effectiveSpawnHandler = makeKernelSpawnHandler({ ...jsHeapBudget !== void 0 ? { jsHeapBudgetMiB: jsHeapBudget } : {}, ...opts.spawnHandlerOptions ?? {}, kernelMemory: kernelMemory.buffer, ram: opts.ram, workerEntry: opts.userWorkerEntry, platform, /* K8-B2: hand the registry to the default-constructed spawn * handler so each spawned Worker gets a per-tid signal-pending * region allocated and registered. */ ...signalRegistry !== void 0 ? { signalRegistry } : {}, /* K11-B2a: hand the precompiled vmlinux Module + the * shared kernel WebAssembly.Memory so each spawned process * Worker can instantiate its own per-Worker vmlinux against * the same kernel address space the kernel Worker mutates. */ ...vmlinuxModule !== void 0 ? { vmlinuxModule } : {}, /* The kernel-provided runtime Module rides beside vmlinuxModule * into every spawned process Worker (instantiated first, module #0). */ ...hwjsRt !== void 0 ? { hwjsRtModule: hwjsRt.module, hwjsRtBytes: hwjsRt.bytes, hwjsRtProvenance: hwjsRt.provenance.raw } : {}, kernelMemoryWasm: kernelMemory, /* Cooperative pause: hand each spawned process Worker the same * pause word so a process spawned WHILE paused (or any process * running when pause fires) freezes at its own slice boundary. */ pauseBuffer: pauseSab, /* K11-B3 (post-A-4): size the FIXED pool of process Workers at * num_vcpu - 1. CPU 0 is the kernel Worker; CPUs 1..num_vcpu-1 * are the pool-Worker ids (resident tasks multiplex onto them — * the PROCESS count is unbounded, only the Worker count is * fixed). The spawn handler's cpuRegistry hands out cpu_ids * from [1, maxCpuId]. */ maxCpuId: numVcpu - 1, /* Guest-root T3 (default-topology half): the pool is UNCHANGED at * num_vcpu-1 Workers; the DEDICATED (pthread) Worker allocator gets * the reserved band above it (num_vcpu .. kernelCpus-1), which no * pool Worker can occupy. Equal to maxCpuId when the reserve is 0 — * then the band is empty and the allocator behaves exactly as it * did before. */ laneCeiling: kernelCpus - 1, /* K11-B2a: route process-Worker dmesg lines into the same * sink as the kernel-Worker dmesg, so a user looking at * `bootResult.dmesg` sees both flows interleaved. */ onDmesg: (level, text, _sourceTid) => { dmesg.push({ level: level | 0, text: String(text) }); opts.onDmesg?.(level | 0, String(text)); } }); } else { let warned = false; effectiveSpawnHandler = async (_req) => { if (!warned) { warned = true; console.warn( "[hardwarejs] bootKernel: kernel issued a spawn-ring request but no spawnHandler / userWorkerEntry was supplied. Returning -ENOSYS; the kernel will fail to launch userspace and either fall through to its /init iteration or park. To fix: pass either { spawnHandler: makeKernelSpawnHandler({...}) } or { userWorkerEntry: '...path/to/worker-{node,browser}.mjs' }." ); } return ENOSYS5; }; } let resolveTerminal; const terminalPromise = new Promise((resolve) => { resolveTerminal = resolve; let preStartSeen = false; onMessage2(worker, (msg) => { switch (msg?.kind) { case "dmesg": dmesg.push({ level: msg.level | 0, text: String(msg.text) }); opts.onDmesg?.(msg.level | 0, String(msg.text)); return; case "unimplemented-host-call": unimplementedCalls.push(String(msg.name)); return; case "machine-power": opts.onMachinePower?.((msg.cmd | 0) >>> 0); return; case "sched-wakeup-word-offset": schedWakeupWordOffset = (msg.offset | 0) >>> 0; maybeStartVirtioBlkBackend(); maybeStartVirtioSndBackend(); maybeStartVirtioBackend(); maybeStartVirtioInputBackend(); maybeStartVirtioNetBackend(); maybeStartVirtioConsoleBackend(); maybeFireDisplayControl(); maybeFireDisplaySlots(); armSchedNudge(); return; case "user-sab-pages-offset": opts.ram.attachUserSabPagesWord(kernelMemory.buffer, (msg.offset | 0) >>> 0); return; case "user-sab-pid-table-offset": opts.ram.attachUserSabPidTable( kernelMemory.buffer, (msg.offset | 0) >>> 0, (msg.slotsOffset | 0) >>> 0, typeof msg.maxOffset === "number" ? (msg.maxOffset | 0) >>> 0 : void 0 ); return; case "committed-pages-offset": committedPagesOffset = (msg.offset | 0) >>> 0; return; case "kernel-mem-grown": kernelSabBytes = Number(msg.bytes) || kernelSabBytes; opts.onKernelMemoryGrown?.(kernelSabBytes); opts.onDmesg?.( 6, `[hardwarejs] env.kernel_memory committed ${(kernelSabBytes / (1024 * 1024)).toFixed(0)} MiB of ${(opts.ram.opts.kernelBytes / (1024 * 1024)).toFixed(0)} MiB` ); return; case "tick-req-offset": tickReqOffset = (msg.offset | 0) >>> 0; armSchedNudge(); return; case "virtio-snd-window": virtsndWindowBase = (msg.base | 0) >>> 0; maybeStartVirtioSndBackend(); return; case "virtio-blk-window": virtblkWindowBase = (msg.base | 0) >>> 0; maybeStartVirtioBlkBackend(); maybeStartVirtioSndBackend(); return; case "virtio-window": virtioWindowBase = (msg.base | 0) >>> 0; maybeStartVirtioBackend(); return; case "virtio-fs-cache-window": virtfscacheWindowBase = (msg.base | 0) >>> 0; maybeStartVirtioFsCacheBackend(); return; case "virtio-input-window": virtinputWindowBase = (msg.base | 0) >>> 0; maybeStartVirtioInputBackend(); return; case "virtio-net-window": virtnetWindowBase = (msg.base | 0) >>> 0; maybeStartVirtioNetBackend(); return; case "usb-window": usbWindowBase = (msg.base | 0) >>> 0; maybeStartUsbHcdBackend(); return; case "virtio-console-window": virtconWindowBase = (msg.base | 0) >>> 0; maybeStartVirtioConsoleBackend(); return; case "hosttrans-window": hosttransWindowBase = (msg.base | 0) >>> 0; maybeStartHostTransBackend(); return; case "virtio-irq-pending-offset": virtioIrqPendingOffset = (msg.offset | 0) >>> 0; maybeStartVirtioBlkBackend(); maybeStartVirtioSndBackend(); maybeStartVirtioBackend(); maybeStartVirtioFsCacheBackend(); maybeStartVirtioInputBackend(); maybeStartVirtioNetBackend(); maybeStartUsbHcdBackend(); maybeStartVirtioConsoleBackend(); maybeStartHostTransBackend(); return; case "virtio-kick": if ((msg.devid | 0) === VIRTIO_SND_DEVID) { if (virtsndBackend) virtsndBackend.onKick(msg.qidx | 0); else virtsndPendingKicks.push(msg.qidx | 0); } else if ((msg.devid | 0) === 7) { if (virtblkBackend) virtblkBackend.onKick(msg.qidx | 0); else virtblkPendingKicks.push(msg.qidx | 0); } else if ((msg.devid | 0) === 6) { if (hosttransBackend !== void 0) hosttransBackend.onKick(msg.qidx | 0); else hosttransPendingKicks.push(msg.qidx | 0); } else if ((msg.devid | 0) === 5) { if (virtfscacheBackend !== void 0) virtfscacheBackend.onKick(msg.qidx | 0); else virtfscachePendingKicks.push(msg.qidx | 0); } else if ((msg.devid | 0) === 4) { if (virtconBackend !== void 0) virtconBackend.onKick(msg.qidx | 0); else virtconPendingKicks.push(msg.qidx | 0); } else if ((msg.devid | 0) === 3) { if (usbBackend2 !== void 0) usbBackend2.onKick(msg.qidx | 0); else usbPendingKicks.push(msg.qidx | 0); } else if ((msg.devid | 0) === 2) { if (virtnetBackend !== void 0) virtnetBackend.onKick(msg.qidx | 0); else virtnetPendingKicks.push(msg.qidx | 0); } else if ((msg.devid | 0) === 1) { if (virtinputBackend !== void 0) virtinputBackend.onKick(msg.qidx | 0); else virtinputPendingKicks.push(msg.qidx | 0); } else { if (virtioBackend !== void 0) virtioBackend.onKick(msg.qidx | 0); else virtioPendingKicks.push(msg.qidx | 0); } return; case "fb-window": fbCtrlOffset = (msg.ctrlOffset | 0) >>> 0; fbMaxWidth = msg.maxWidth | 0; fbMaxHeight = msg.maxHeight | 0; displaySlotsOffset = typeof msg.slotsOffset === "number" ? msg.slotsOffset >>> 0 : 0; opts.onFbWindow?.({ base: (msg.base | 0) >>> 0, width: msg.width | 0, height: msg.height | 0, stride: msg.stride | 0, size: msg.size | 0, format: String(msg.format), maxWidth: fbMaxWidth, maxHeight: fbMaxHeight, ctrlOffset: fbCtrlOffset }); maybeFireDisplayControl(); maybeFireDisplaySlots(); return; case "signal-ring-offset": if (signalRingOffset === void 0) { signalRingOffset = (msg.offset | 0) >>> 0; const handler = opts.signalHandler ?? makeSignalHandler({ registry: signalRegistry /* set when signalHandler omitted */ }); signalConsumer = new SignalRingConsumer({ kernelMemory: kernelMemory.buffer, ringOffset: signalRingOffset, handler, onProcessed: opts.onSignalProcessed, onError: (err2) => { const m = err2 instanceof Error ? err2.message : String(err2); opts.onDmesg?.( 3, `[signal-ring-consumer] handler/loop error: ${m}` ); } }); void signalConsumer.start(); } return; case "spawn-ring-offset": if (spawnRingOffset === void 0) { spawnRingOffset = (msg.offset | 0) >>> 0; spawnConsumer = new SpawnRingConsumer({ kernelMemory: kernelMemory.buffer, ringOffset: spawnRingOffset, handler: effectiveSpawnHandler, /* HWJS-A-4.c: after the spawn result + result_notify_word are * written, bump the SPAWNING parent task's wake_seq so its * cooperative Atomics.waitAsync (block-parked during the child * snapshot/instantiate) resolves and the host re-drives it to * read the result. Without this the parent only self-heals on * the ~15ms coop timeout. */ onProcessed: (req, result) => { try { effectiveSpawnHandler.wakeTaskByPid?.(req.parentTid >>> 0); } catch { } opts.onSpawnProcessed?.(req, result); }, onError: (err2) => { const m = err2 instanceof Error ? err2.message : String(err2); opts.onDmesg?.( 3, `[spawn-ring-consumer] handler/loop error: ${m}` ); } }); void spawnConsumer.start(); } return; case "pty-bridge-ring-offset": if (ptyBridgeRingOffset === void 0) { ptyBridgeRingOffset = (msg.offset | 0) >>> 0; opts.onPtyBridgeRingOffset?.( ptyBridgeRingOffset, typeof msg.tableOffset === "number" ? msg.tableOffset >>> 0 : void 0 ); } return; case "serial-bridge-ring-offset": if (serialBridgeRingOffset === void 0) { serialBridgeRingOffset = (msg.offset | 0) >>> 0; opts.onSerialBridgeRingOffset?.(serialBridgeRingOffset); } return; case "pre-start": preStartSeen = true; { const built = []; const missing = []; (opts.virtioConsole !== void 0 ? virtconBackend !== void 0 ? built : missing : built).push("virtio-console"); if (virtioBackend !== void 0) built.push("virtio-fs"); if (virtnetBackend !== void 0) built.push("virtio-net"); if (virtinputBackend !== void 0) built.push("virtio-input"); if (virtsndBackend !== void 0) built.push("virtio-snd"); if (usbBackend2 !== void 0) built.push("usb-hcd"); if (missing.length > 0) opts.onDmesg?.( 4, `hwjs-merged: answering devices-ready with ${missing.join(", ")} DECLARED BUT NOT BUILT. A merged guest that reaches an in-kernel busy-wait on one of those holds the only thread that could build it.` ); postToWorker2(worker, { kind: "devices-ready", built: built.join(",") || "none", missing: missing.join(",") || "none" }); } { const c = workerRealmCensus(); const want = expectedWorkerRealms(kernelCpus); const byOrigin = Object.entries(c.liveByOrigin).filter(([, n]) => n > 0).map(([k, n]) => `${k}=${n}`).join(", ") || "none"; opts.onDmesg?.( c.live === want ? 6 : 4, `hwjs-realms: host Worker realms live=${c.live} [${byOrigin}], expected ${want} for num_vcpu=${kernelCpus} \u2014 ` + (c.live === want ? `AGREES.` : `DISAGREES. One of the two is wrong: either a realm was constructed outside the topology (read the origin breakdown \u2014 it names the call site) or the merge did not take effect where it was reported to. created=${c.created} terminated=${c.terminated} peak=${c.peakLive}.`) + ` ` ); } return; case "returned": resolve({ kind: "returned", message: String(msg.message) }); return; case "kernel-trap": resolve({ kind: "kernel-trap", message: String(msg.message) }); return; case "link-error": resolve({ kind: "link-error", missing: msg.missing }); return; case "instantiate-error": resolve({ kind: "instantiate-error", message: String(msg.message) }); return; case "ctors-trap": resolve({ kind: "ctors-trap", message: String(msg.message) }); return; case "no-entry": resolve({ kind: "no-entry", message: String(msg.message) }); return; case "error": resolve({ kind: "error", message: String(msg.message) }); return; } void preStartSeen; }); onError2(worker, (err2) => { const m = err2 instanceof Error ? err2.message : String(err2); const stk = err2 instanceof Error && err2.stack ? "\nKERNEL-TRAP-STACK: " + err2.stack.split("\n").slice(0, 24).join(" | ") : ""; resolve({ kind: "error", message: m + stk }); }); }); postToWorker2(worker, { kind: "boot", /* The COMPILED Module, not the 22.8 MiB image. `wasmBytes` posted * un-transferred meant the structured clone made a second full copy of * vmlinux in the Worker's realm, which the Worker then compiled a second * time — while this realm was already holding the Module compiled above. * A WebAssembly.Module is structured-cloneable (the same property * kernelSpawnHandler relies on to hand pool Workers their instance), so * the clone carries the compiled code and neither copy nor recompile * happens. `undefined` here means the compile above threw; the Worker * refuses with `vmlinuxCompileError` rather than inventing an image. */ vmlinuxModule, vmlinuxCompileError, kernelMemory, kernelImports: opts.kernelImports ?? {}, cmdline: opts.cmdline ?? "", bootInfoOverride: opts.bootInfoOverride, /* Boot ABI v4: the MACHINE's declared aggregate RAM, which the kernel * reports as MemTotal. It comes from PhysRam — the single place that * knows both the kernel SAB's size and the machine's declared figure — * and defaults there to the kernel SAB, so a caller that never heard of * the aggregate gets exactly its old behaviour. */ declaredMemoryBytes: opts.ram.opts.declaredMemoryBytes, /* THE KERNEL SAB'S SPAN (its wasm `maximum`), which is NOT what is * committed right now. boot_info.total_memory carries this so the kernel * builds mem_map for every frame the memory can ever hold, then reserves * the uncommitted tail out of the buddy allocator. See physRam.ts's * KERNEL_SAB_INITIAL_BYTES and arch/wasm32/mm/memcommit.c. */ kernelMaxBytes: opts.ram.opts.kernelMaxBytes, /* HWJS-A-1: ask the kernel worker to carve a virtio-mmio device * window at the top of kernel memory and emit the wasm_virtiofs= * cmdline param + post the window/irq offsets back. */ virtioBlk: opts.virtioBlk ? { size: opts.virtioBlk.disk.size, readOnly: !!opts.virtioBlk.disk.readOnly } : void 0, virtioSound: opts.virtioSound ? { streams: VIRTIO_SND_STREAMS, chmaps: VIRTIO_SND_CHMAPS } : void 0, virtioFs: opts.virtioFs !== void 0, /* Ask the kernel worker to carve the SECOND virtio-fs window (device 5), * emit wasm_virtiofs_cache= and post its window back. Appliance only. */ virtioFsCache: opts.virtioFsCache !== void 0, /* HWJS-C-1 (DRM + runtime resize): ask the kernel worker to carve the * max-size scanout region (below the virtio window), emit the 7-field * wasm_drmfb= cmdline param (initial visible mode = the requested * size), and post the fb-window geometry (+ display-ctrl offset) back. */ framebuffer: opts.framebuffer !== void 0 ? { width: opts.framebuffer.width ?? 0, height: opts.framebuffer.height ?? 0, /* #33: per-boot carve bound (0 = worker default 1920x1080). */ maxWidth: opts.framebuffer.maxWidth ?? 0, maxHeight: opts.framebuffer.maxHeight ?? 0, suppressHotplug: opts.framebuffer.suppressHotplug === true, resizeGateTimeoutMs: opts.framebuffer.resizeGateTimeoutMs ?? 0 } : void 0, /* HWJS-C-1: ask the kernel worker to carve a second virtio-mmio window * (virtio-input, device 1, below any fb region), emit the wasm_virtinput= * cmdline param, and post the input-window/irq offsets back. */ virtioInput: opts.virtioInput !== void 0 ? { absolutePointer: opts.virtioInput.absolutePointer === true } : void 0, /* HWJS-C-2.b: ask the kernel worker to carve a third virtio-mmio window * (virtio-net, device 2), emit the wasm_virtnet= cmdline param, and post * the net-window/irq offsets back. * * AN OBJECT RATHER THAN A BOOLEAN, on virtio-console's precedent and for * its reason: the OFFERED feature word is chosen kernel-side, from the * cmdline token, and the token is written in the kernel Worker — so the * two numbers that decide the offer (`mtu`, `mergeRxBuf`) have to travel * there. They used not to, and the kernel parser recorded that as the * reason its fourth field was dormant. `undefined` still means "no NIC"; * an object is truthy, so every `if (init.virtioNet)` in the worker keeps * meaning what it meant. */ virtioNet: opts.virtioNet !== void 0 ? { mtu: opts.virtioNet.mtu ?? 0, mergeRxBuf: opts.virtioNet.mergeRxBuf === true } : void 0, /* HWJS-C-3: ask the kernel worker to carve the wasm-usb window (devid 3 * pseudo slot), emit the wasm_usb= cmdline param, and post the * usb-window/irq offsets back. */ usbHcd: opts.usbHcd !== void 0, /* HWJS-C-4: ask the kernel worker to carve the virtio-console window * (device 4), emit the wasm_virtcon=,,, * cmdline param, and post the console-window/irq offsets back. The port * list lives host-side, so the host is what knows max_nr_ports; the arch * registrar only transcribes it into config space. */ virtioConsole: opts.virtioConsole !== void 0 ? { maxNrPorts: Math.max( ...(opts.virtioConsole.ports ?? [{ id: 1 }]).map((p) => p.id) ) + 1 } : void 0, /* Ask the kernel worker to carve the wasm_hosttrans window (devid 6 * pseudo slot), emit the wasm_hosttrans= cmdline param, and post the * hosttrans-window/irq offsets back. A boolean: the handler lives * host-side and nothing about it has to reach the kernel Worker. */ hostTransport: opts.hostTransport !== void 0, /* K11-B3: forwarded into wasm_boot_info.num_cpus so setup_arch * sees the JS-side intent and expands cpu_possible_mask. * * This is exactly `num_vcpu`: CPU 0 (the kernel Worker) plus the * pool's 1..num_vcpu-1. It was `num_vcpu + dedicatedLaneReserve` until * 2026-08-10, when the pthread-Worker lane reserve was retired — its * consumer became a pool resident, so the kernel was preparing * `for_each_possible_cpu` per-CPU state for 8 CPUs nobody used. See * vcpuPolicy.ts. */ numCpus: kernelCpus, /* THE `mergedCpu0` FIELD IS GONE FROM THIS MESSAGE. It carried "does CPU * 0 share its JS thread with pool lane 1?", and the answer is now yes for * every machine — a field that cannot vary is a field the kernel Worker * would have to keep reading to learn nothing. It emits the * `wasm_merged_cpu0` cmdline token and refuses an image without the * merged dispatcher unconditionally instead. */ /* Cooperative pause word for the kernel Worker's top drive loop. */ pauseBuffer: pauseSab }); const pause = () => { Atomics.store(pauseArr, 0, 1); if (schedNudgeTimer !== void 0) { clearInterval(schedNudgeTimer); schedNudgeTimer = void 0; } }; const resume = () => { Atomics.store(pauseArr, 0, 0); Atomics.notify(pauseArr, 0); armSchedNudge(); if (schedWakeupWordOffset !== void 0) { kickKernelScheduler( kernelMemory.buffer, schedWakeupWordOffset ); } }; const isPaused2 = () => Atomics.load(pauseArr, 0) === 1; let disposed = false; const doTeardown = async () => { if (disposed) return; disposed = true; Atomics.store(pauseArr, 0, 0); Atomics.notify(pauseArr, 0); if (schedNudgeTimer !== void 0) { clearInterval(schedNudgeTimer); schedNudgeTimer = void 0; } if (spawnConsumer !== void 0) { try { await spawnConsumer.stop(); } catch { } } if (signalConsumer !== void 0) { try { await signalConsumer.stop(); } catch { } } await terminateWorker2(worker); try { await effectiveSpawnHandler.dispose?.(); } catch { } }; const dispose = async () => { resolveTerminal?.({ kind: "returned", message: "host dispose()" }); await doTeardown(); }; opts.onControls?.({ pause, resume, isPaused: isPaused2, dispose }); let terminal; if (opts.watchdogMs && opts.watchdogMs > 0) { const watchdog = new Promise((resolve) => { setTimeout( () => resolve({ kind: "watchdog", afterMs: opts.watchdogMs }), opts.watchdogMs ); }); terminal = await Promise.race([terminalPromise, watchdog]); } else { terminal = await terminalPromise; } if (terminal.kind === "watchdog") { const text = `[hardwarejs] bootKernel WATCHDOG: machine lifetime cap watchdogMs=${terminal.afterMs}ms reached \u2014 tearing down the kernel Worker + CPU pool NOW (the guest may still have been running; this is an absolute cap, not an inactivity watchdog). A driver still waiting on guest output past this point waits on a dead machine.`; dmesg.push({ level: 0, text }); opts.onDmesg?.(0, text); console.error(text); } await doTeardown(); return { dmesg, terminal, unimplementedCalls, schedWakeupWordOffset, spawnRingOffset, signalRingOffset, ptyBridgeRingOffset, serialBridgeRingOffset }; } function kickKernelScheduler(kernelMemorySab, offset) { if ((offset & 3) !== 0) throw new Error( `kickKernelScheduler: offset 0x${offset.toString(16)} not 4-byte aligned` ); const view = new Int32Array(kernelMemorySab); const idx = offset >>> 2; Atomics.add(view, idx, 1); Atomics.notify(view, idx, 1); } function detectPlatform2() { const g = globalThis; if (typeof g.process !== "undefined" && g.process?.versions?.node) return "node"; return "browser"; } async function createWorker2() { const [{ createInlineRealm: createInlineRealm2 }, { bindKernelWorker: bindKernelWorker2 }] = await Promise.all([ Promise.resolve().then(() => (init_inlineRealm(), inlineRealm_exports)), Promise.resolve().then(() => (init_kernelWorker(), kernelWorker_exports)) ]); return createInlineRealm2(bindKernelWorker2, "kernel-inline"); } function postToWorker2(worker, msg) { worker.postMessage(msg); } function onMessage2(worker, cb) { const w = worker; if (typeof w.on === "function") w.on("message", cb); else w.onmessage = (ev) => cb(ev.data); } function onError2(worker, cb) { const w = worker; if (typeof w.on === "function") w.on("error", cb); else w.onerror = (ev) => cb(ev.error ?? ev.message); } async function terminateWorker2(worker) { noteWorkerRealmTerminated(worker); const w = worker; try { if (typeof w.terminate === "function") { const t = w.terminate(); if (t && typeof t.then === "function") await t; } } catch { } } // ../../linux-in-the-browser/hardwarejs/src/devices/opfs-fs-core.ts var RESOLVED = Promise.resolve(); // ../../linux-in-the-browser/hardwarejs/src/devices/memory-guest-root.ts var DEFAULT_MOUNTPOINTS = ["/dev", "/dev/pts", "/proc", "/sys", "/tmp"]; function createMemoryGuestRoot(spec, opts = {}) { const attrs = /* @__PURE__ */ new Map(); const dirs = /* @__PURE__ */ new Map(); const blobs = /* @__PURE__ */ new Map(); const links = /* @__PURE__ */ new Map(); const inoOf = /* @__PURE__ */ new Map(); let nextIno = 1; const DT = modeOf("dir", 0) >> 12; const FT = modeOf("file", 0) >> 12; const LT = 40960 >> 12; const norm = (p) => { if (!p.startsWith("/")) { throw new TypeError(`memory-guest-root: "${p}" must be absolute`); } const parts = p.split("/").filter((s) => s !== "" && s !== "."); if (parts.includes("..")) { throw new TypeError(`memory-guest-root: "${p}" contains ".."`); } return "/" + parts.join("/"); }; const mkdirp = (p) => { const path = norm(p); const known = inoOf.get(path); if (known !== void 0) return known; const ino = nextIno++; inoOf.set(path, ino); attrs.set(ino, { ino, size: 0, mode: modeOf("dir", 493), nlink: 2, uid: 0, gid: 0, mtimeSec: 1 }); dirs.set(ino, []); if (path !== "/") { const slash = path.lastIndexOf("/"); const parent = mkdirp(slash === 0 ? "/" : path.slice(0, slash)); dirs.get(parent).push({ name: path.slice(slash + 1), ino, type: DT }); } return ino; }; const addChild = (p, ino, type) => { const path = norm(p); const slash = path.lastIndexOf("/"); const parent = mkdirp(slash === 0 ? "/" : path.slice(0, slash)); dirs.get(parent).push({ name: path.slice(slash + 1), ino, type }); inoOf.set(path, ino); }; const toBytes = (v) => typeof v === "string" ? new TextEncoder().encode(v) : v; mkdirp("/"); for (const mp of [ ...opts.mountpoints === false ? [] : opts.mountpoints ?? DEFAULT_MOUNTPOINTS, ...opts.extraMountpoints ?? [] ]) { mkdirp(mp); } const entries = Object.entries(spec); const isLink = (e) => e !== null && typeof e === "object" && "hardlink" in e; for (const [p, e] of entries.filter(([, e2]) => !isLink(e2))) { if (e !== null && typeof e === "object" && "dir" in e && e.dir === true) { const ino2 = mkdirp(p); attrs.get(ino2).mode = modeOf("dir", e.mode ?? 493); continue; } if (e !== null && typeof e === "object" && "symlink" in e) { const ino2 = nextIno++; attrs.set(ino2, { ino: ino2, size: e.symlink.length, mode: 40960 | 511, nlink: 1, uid: 0, gid: 0, mtimeSec: 1 }); links.set(ino2, e.symlink); addChild(p, ino2, LT); continue; } const data = toBytes( e instanceof Uint8Array || typeof e === "string" ? e : e.data ); const mode = e instanceof Uint8Array || typeof e === "string" ? 420 : e.mode ?? 420; const ino = nextIno++; attrs.set(ino, { ino, size: data.length, mode: modeOf("file", mode), nlink: 1, uid: 0, gid: 0, mtimeSec: 1 }); blobs.set(ino, data); addChild(p, ino, FT); const extra = e !== null && typeof e === "object" && Array.isArray(e.links) ? e.links : []; const dirOf = norm(p).slice(0, norm(p).lastIndexOf("/")); for (const name2 of extra) { addChild(name2.startsWith("/") ? name2 : `${dirOf}/${name2}`, ino, FT); attrs.get(ino).nlink += 1; } } for (const [p, e] of entries.filter(([, e2]) => isLink(e2))) { const target = inoOf.get(norm(e.hardlink)); if (target === void 0) { throw new Error( `memory-guest-root: ${p}: hardlink target ${e.hardlink} is not in the spec` ); } addChild(p, target, FT); attrs.get(target).nlink += 1; } const view = { getattr: (ino) => attrs.get(ino) ?? null, lookup: (parent, name2) => { const e = dirs.get(parent)?.find((d) => d.name === name2); return e ? attrs.get(e.ino) ?? null : null; }, readdir: (ino) => dirs.get(ino) ?? [], read: (ino, offset, size) => { const b = blobs.get(ino); return b ? b.subarray(offset, offset + size) : new Uint8Array(0); }, readlink: (ino) => links.get(ino) ?? "", /* Writes exist so a fixture can read back what the guest wrote. They are * not a storage model and nothing persists past this object. */ write: (ino, offset, data) => { let b = blobs.get(ino) ?? new Uint8Array(0); if (offset + data.length > b.length) { const grown = new Uint8Array(offset + data.length); grown.set(b); b = grown; } b.set(data, offset); blobs.set(ino, b); const a = attrs.get(ino); if (a) a.size = b.length; return data.length; }, create: (parent, name2, mode) => { const ino = nextIno++; const attr = { ino, size: 0, mode: modeOf("file", mode & 4095), nlink: 1, uid: 0, gid: 0, mtimeSec: 1 }; attrs.set(ino, attr); blobs.set(ino, new Uint8Array(0)); (dirs.get(parent) ?? []).push({ name: name2, ino, type: FT }); if (!dirs.has(parent)) dirs.set(parent, [{ name: name2, ino, type: FT }]); return attr; }, setattr: (ino, changes) => { const a = attrs.get(ino); if (!a) throw Object.assign(new Error("setattr: no such inode"), { errno: 2 }); if (changes.size !== void 0) { const b = blobs.get(ino) ?? new Uint8Array(0); const next = new Uint8Array(changes.size); next.set(b.subarray(0, Math.min(b.length, changes.size))); blobs.set(ino, next); a.size = changes.size; } if (changes.mode !== void 0) a.mode = modeOf("file", changes.mode & 4095); if (changes.mtimeSec !== void 0) a.mtimeSec = changes.mtimeSec; return a; } }; return defineMountProvider(view, { kind: "memory", origin: "in-memory tree (bytes supplied by the caller)", note: "fixture substrate \u2014 not a filesystem; see HOST-DIRECTORY-GUEST-ROOT.md" }); } // ../../linux-in-the-browser/hardwarejs/src/devices/brintos-link.ts var RX_WINDOW_BUDGET_BYTES = 4 * 1024 * 1024; // ../../linux-in-the-browser/hardwarejs/src/devices/virtual-switch.ts var ETH_HLEN2 = 14; var ARP_HTYPE2 = ETH_HLEN2 + 0; var ARP_PTYPE2 = ETH_HLEN2 + 2; var ARP_HLEN2 = ETH_HLEN2 + 4; var ARP_PLEN2 = ETH_HLEN2 + 5; var ARP_SHA = ETH_HLEN2 + 8; var ARP_SPA2 = ETH_HLEN2 + 14; var ARP_THA = ETH_HLEN2 + 18; var ARP_TPA2 = ETH_HLEN2 + 24; var ARP_FRAME_BYTES2 = ETH_HLEN2 + 28; var DEFAULT_FABRIC_PREFIX = Object.freeze([10, 99]); // ../../linux-in-the-browser/hardwarejs/src/devices/gl-remote.ts var GLR_OBJECT_ID = 1196184113; var GLR = { VIEWPORT: 1, CLEAR_COLOR: 2, CLEAR: 3, CREATE_SHADER: 4, SHADER_SOURCE: 5, COMPILE_SHADER: 6, CREATE_PROGRAM: 7, ATTACH_SHADER: 8, LINK_PROGRAM: 9, USE_PROGRAM: 10, BIND_ATTRIB_LOCATION: 11, GEN_BUFFER: 12, BIND_BUFFER: 13, BUFFER_DATA: 14, ENABLE_VERTEX_ATTRIB_ARRAY: 15, VERTEX_ATTRIB_POINTER: 16, DRAW_ARRAYS: 17, UNIFORM_LOCATION: 18, UNIFORM_4F: 19, UNIFORM_MATRIX_4FV: 20, ENABLE: 21, DISABLE: 22, DRAW_ELEMENTS: 23, SWAP: 24, GEN_TEXTURE: 25, BIND_TEXTURE: 26, TEX_IMAGE_2D: 27, TEX_SUB_IMAGE_2D: 28, TEX_PARAMETERI: 29, ACTIVE_TEXTURE: 30, UNIFORM_1I: 31, UNIFORM_2F: 32, BLEND_FUNC_SEPARATE: 33, SCISSOR: 34, CANVAS_SIZE: 35, DELETE_TEXTURE: 36, PIXEL_STOREI: 37, BLEND_EQUATION: 38, UNIFORM_1F: 39, UNIFORM_3F: 40, DEPTH_FUNC: 41, DEPTH_MASK: 42, CLEAR_DEPTH: 43, GEN_VERTEX_ARRAY: 44, BIND_VERTEX_ARRAY: 45, CULL_FACE: 46, DELETE_BUFFER: 47, DELETE_SHADER: 48, DELETE_PROGRAM: 49, DETACH_SHADER: 50, DISABLE_VERTEX_ATTRIB_ARRAY: 51, GEN_FRAMEBUFFER: 52, BIND_FRAMEBUFFER: 53, DELETE_FRAMEBUFFER: 54, FRAMEBUFFER_TEXTURE_2D: 55, FRAMEBUFFER_RENDERBUFFER: 56, GEN_RENDERBUFFER: 57, BIND_RENDERBUFFER: 58, DELETE_RENDERBUFFER: 59, RENDERBUFFER_STORAGE: 60, BLIT_FRAMEBUFFER: 61, UNIFORM_FV: 62, UNIFORM_IV: 63, UNIFORM_MATRIX_FV: 64, COLOR_MASK: 65, STENCIL_FUNC_SEPARATE: 66, STENCIL_OP_SEPARATE: 67, STENCIL_MASK_SEPARATE: 68, CLEAR_STENCIL: 69, FRONT_FACE: 70, POLYGON_OFFSET: 71, DEPTH_RANGE: 72, BLEND_COLOR: 73, LINE_WIDTH: 74, VERTEX_ATTRIB_4F: 75, BLEND_EQUATION_SEPARATE: 76, BUFFER_SUB_DATA: 77, BUFFER_DATA_SIZE: 78, GENERATE_MIPMAP: 79, COPY_TEX_IMAGE_2D: 80, COPY_TEX_SUB_IMAGE_2D: 81, TEX_IMAGE_3D: 82, TEX_SUB_IMAGE_3D: 83, DELETE_VERTEX_ARRAY: 84, SWAP_INTERVAL: 85, PRESENT_CLAIM: 86, IMPORT_TEXTURE: 87, RELEASE_HANDLE: 88, SURFACE_BUFFERS: 89, /* GLES 3.0 beyond the first set; a guest asks for them with GET_STRING(GLR_EXTENSIONS). */ BIND_BUFFER_RANGE: 90, UNIFORM_BLOCK_BINDING: 91, COPY_BUFFER_SUB_DATA: 92, DRAW_BUFFERS: 93, CLEAR_BUFFER: 94, UNIFORM_UIV: 95, DRAW_ARRAYS_INSTANCED: 96, DRAW_ELEMENTS_INSTANCED: 97, VERTEX_ATTRIB_DIVISOR: 98, VERTEX_ATTRIB_I_POINTER: 99, GEN_SAMPLER: 100, DELETE_SAMPLER: 101, BIND_SAMPLER: 102, SAMPLER_PARAMETERI: 103, SAMPLER_PARAMETERF: 104, TEX_STORAGE_2D: 105, TEX_STORAGE_3D: 106, READ_BUFFER: 107, FRAMEBUFFER_TEXTURE_LAYER: 108, UNIFORM_MATRIX_NM: 109, READ_PIXELS_PBO: 110, TEX_SUB_IMAGE_PBO: 111, /* Queries: each sets the reply READ and ECHO return. */ GET_ERROR: 256, GET_INTEGERV: 257, READ_PIXELS: 258, FINISH: 259, GET_SHADER_STATUS: 260, GET_PROGRAM_STATUS: 261, GET_STRING: 262, INPUT_POLL: 263, CHECK_FRAMEBUFFER_STATUS: 264, GET_ATTRIB_LOCATION: 265, EXPORT_TEXTURE: 266, SURFACE_FRONT: 267, SESSION_INFO: 268, GET_UNIFORM_BLOCK_INDEX: 269, GET_BUFFER_SUB_DATA: 270, GET_ACTIVE_UNIFORMS: 271 }; var GL_READ_FRAMEBUFFER = 36008; var GL_DRAW_FRAMEBUFFER = 36009; var GL_FRAMEBUFFER_BINDING = 36006; var GL_READ_FRAMEBUFFER_BINDING = 36010; var GL_SCISSOR_TEST = 3089; var GL_COMPILE_STATUS = 35713; var GL_LINK_STATUS = 35714; var GL_ACTIVE_UNIFORMS = 35718; var GL_RGBA = 6408; var GL_UNSIGNED_BYTE = 5121; var GlrFramePacer = class { constructor(requestFrame, maxWaitMs = 100) { this.requestFrame = requestFrame; this.maxWaitMs = maxWaitMs; } requestFrame; maxWaitMs; frame = 0; released = 0; ticking = false; idle = 0; waiter = null; /** Null when the swap completes now; else resolves when it may complete. */ swap(interval) { if (interval <= 0) return null; this.idle = 0; if (!this.ticking) { this.ticking = true; this.released = this.frame; this.requestFrame(this.tick); return null; } const target = this.released + interval; if (this.frame >= target) { this.released = this.frame; return null; } return new Promise((resolve) => { const timer = setTimeout(() => this.release(), this.maxWaitMs); this.waiter = { target, resolve, timer }; }); } release() { const w = this.waiter; if (!w) return; this.waiter = null; clearTimeout(w.timer); this.released = this.frame; w.resolve(); } tick = () => { this.frame++; if (this.waiter && this.frame >= this.waiter.target) this.release(); if (this.waiter || ++this.idle < 60) this.requestFrame(this.tick); else this.ticking = false; }; }; var EINVAL3 = 22; var EBADMSG = 74; var GL_INVALID_OPERATION = 1282; var GL_TEXTURE_2D = 3553; var GL_TEXTURE0 = 33984; var GL_RENDERBUFFER = 36161; var GL_ELEMENT_ARRAY_BUFFER = 34963; var GL_PIXEL_UNPACK_BUFFER = 35052; var GL_FRONT = 1028; var GL_BACK = 1029; var GL_FRONT_AND_BACK = 1032; var GL_DITHER = 3024; var GL_COLOR_ATTACHMENT0 = 36064; var GL_COLOR = 6144; var GL_DEPTH_STENCIL = 34041; var GLR_EXTENSIONS = 2135378945; var GLR_EXTENSION_LIST = "GLR1_gles3 GLR1_active_uniforms"; var td = new TextDecoder(); var te = new TextEncoder(); function defaultState(w, h) { return { viewport: [0, 0, w, h], scissor: [0, 0, w, h], clearColor: [0, 0, 0, 0], clearDepth: 1, clearStencil: 0, caps: /* @__PURE__ */ new Map(), blendFunc: [1, 0, 1, 0], blendEq: [32774, 32774], blendColor: [0, 0, 0, 0], colorMask: [1, 1, 1, 1], depthFunc: 513, depthMask: true, depthRange: [0, 1], stencil: [[519, 0, 4294967295, 7680, 7680, 7680, 4294967295], [519, 0, 4294967295, 7680, 7680, 7680, 4294967295]], cullFace: GL_BACK, frontFace: 2305, lineWidth: 1, polygonOffset: [0, 0], pixelStore: /* @__PURE__ */ new Map(), attribs: /* @__PURE__ */ new Map(), program: null, buffers: /* @__PURE__ */ new Map(), vao: null, activeTexture: GL_TEXTURE0, textures: /* @__PURE__ */ new Map(), renderbuffer: null, drawFb: 0, readFb: 0, indexed: /* @__PURE__ */ new Map(), samplers: /* @__PURE__ */ new Map() }; } var PIXEL_STORE_DEFAULT = { 3333: 4, 3317: 4, 37444: 37444 }; var capDefault = (cap) => cap === GL_DITHER; var same = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]); var GlrSession = class { constructor(id, order, pacer, w, h) { this.id = id; this.order = order; this.pacer = pacer; this.st = defaultState(w, h); } id; order; pacer; names = /* @__PURE__ */ new Map(); kinds = /* @__PURE__ */ new Map(); /* Host object -> this session's name, so a binding query answers with it. */ ids = /* @__PURE__ */ new WeakMap(); reply = new Uint8Array(0); /* EGL's default swap interval. */ swapInterval = 1; swaps = 0; /* A refusal of the decoder's own, answered by the next GET_ERROR. */ error = 0; st; frame = null; surface = null; /* The size CANVAS_SIZE asked for while not presenting. */ surfaceSize = null; surfaceBuffers = 2; /* Undefined until made; null is the context's own default vertex array. */ defaultVao = void 0; exports = /* @__PURE__ */ new Set(); }; var GlRemoteDecoder = class { constructor(opts) { this.opts = opts; this.now = opts.now ?? (() => performance.now()); } opts; stats = { batches: 0, commands: 0, queries: 0, bytesIn: 0, bytesOut: 0, swaps: 0, glMs: 0, frameWaits: 0, frameWaitMs: 0, sessions: 0, switches: 0, exports: 0, imports: 0 }; now; sessions = /* @__PURE__ */ new Map(); opened = 0; /* The session whose state the context holds, and that state. */ cur = null; live = null; /* The session that claimed presentation, if any. */ claimant = null; exportsByHandle = /* @__PURE__ */ new Map(); exportOf = /* @__PURE__ */ new Map(); /* References to an exported texture: session names, live handles, surfaces. */ texRefs = /* @__PURE__ */ new Map(); nextHandle = 0; frameWait = null; /** The reply of the last query of session `id` (default 0); READ serves it by offset. */ replyOf(id = 0) { return this.sessions.get(id)?.reply ?? new Uint8Array(0); } /** The reply of the last query of the session that ran last. */ get lastReply() { return this.cur?.reply ?? new Uint8Array(0); } /** Live sessions, oldest first. */ get sessionIds() { return [...this.sessions.values()].sort((a, b) => a.order - b.order).map((s) => s.id); } /** The session that presents: the claimant, else the oldest live session. */ get presenterId() { return this.presenter()?.id ?? null; } /** The texture behind an export handle, for a host-side consumer. */ exportedTexture(handle) { return this.exportsByHandle.get(handle)?.tex ?? null; } /** * The wait the last batch's SWAP owes the display, or null. The transport * completes the batch when it settles; taking it clears it. */ takeFrameWait() { const w = this.frameWait; this.frameWait = null; if (w === null) return null; const t0 = this.now(); this.stats.frameWaits++; return w.then(() => { this.stats.frameWaitMs += this.now() - t0; }); } presenter() { if (this.claimant) return this.claimant; let first = null; for (const s of this.sessions.values()) if (!first || s.order < first.order) first = s; return first; } session(id, gl) { let s = this.sessions.get(id); if (!s) { const pacer = this.opts.requestFrame ? new GlrFramePacer(this.opts.requestFrame) : null; s = new GlrSession(id, this.opened++, pacer, gl.drawingBufferWidth, gl.drawingBufferHeight); if (s.order === 0) s.defaultVao = null; this.sessions.set(id, s); this.stats.sessions = this.sessions.size; } return s; } obj(id) { if (id === 0) return null; const o = this.cur.names.get(id); if (o === void 0) throw new Error(`gl-remote: name ${id} was never created`); return o; } name(id, o, kind) { const s = this.cur; s.names.set(id, o); s.kinds.set(id, kind); if (o !== null && typeof o === "object") s.ids.set(o, id); } del(id, destroy) { const s = this.cur; const o = s.names.get(id); s.names.delete(id); s.kinds.delete(id); if (!o) return; if (this.texRefs.has(o)) { const gl = this.opts.gl(); for (const [k, v] of s.st.textures) { if (v !== o) continue; gl.activeTexture(GL_TEXTURE0 + Math.floor(k / 65536)); gl.bindTexture(k % 65536, null); } gl.activeTexture(s.st.activeTexture); this.unref(gl, o); } else { destroy(o); } this.forget(s.st, o); } /* A deleted object no longer binds anywhere in the context. */ forget(st, o) { if (st.program === o) st.program = null; if (st.vao === o) st.vao = null; if (st.renderbuffer === o) st.renderbuffer = null; for (const m of [st.buffers, st.textures, st.samplers]) for (const [k, v] of m) if (v === o) m.set(k, null); for (const [k, v] of st.indexed) if (v[0] === o) st.indexed.delete(k); } unref(gl, tex) { const n = (this.texRefs.get(tex) ?? 1) - 1; if (n > 0) { this.texRefs.set(tex, n); return; } this.texRefs.delete(tex); this.exportOf.delete(tex); gl.deleteTexture(tex); } exportTexture(owner, tex, ownRefs) { const had = this.exportOf.get(tex); if (had !== void 0) return had; const handle = ++this.nextHandle; this.exportsByHandle.set(handle, { handle, tex, owner }); this.exportOf.set(tex, handle); this.texRefs.set(tex, (this.texRefs.get(tex) ?? 0) + ownRefs + 1); owner.exports.add(handle); this.stats.exports++; return handle; } releaseHandle(gl, handle) { const e = this.exportsByHandle.get(handle); if (!e) return; this.exportsByHandle.delete(handle); e.owner.exports.delete(handle); if (this.exportOf.get(e.tex) === handle) this.exportOf.delete(e.tex); this.unref(gl, e.tex); } /* ---- switching sessions on the one context ---- */ vaoOf(gl, s) { if (s.st.vao) return s.st.vao; if (s.defaultVao === void 0) s.defaultVao = typeof gl.createVertexArray === "function" ? gl.createVertexArray() : null; return s.defaultVao; } activate(gl, s) { if (this.cur === s) return; const from = this.live; this.cur = s; this.live = s.st; if (from === null) { if (s.defaultVao !== null) gl.bindVertexArray?.(this.vaoOf(gl, s)); return; } this.stats.switches++; applyState(gl, from, s.st); if (typeof gl.bindVertexArray === "function") gl.bindVertexArray(this.vaoOf(gl, s)); this.rebindFrames(gl, s); } /* ---- the window surface: framebuffer 0 of each session ---- */ /* The framebuffer the session's name 0 stands for; undefined on WebGL1. */ fboOf(s) { return s.frame?.fbo ?? s.surface?.fbo; } fbo(s, id) { return id === 0 ? this.fboOf(s) ?? null : s.names.get(id) ?? null; } rebindFrames(gl, s) { gl.bindFramebuffer(GL_DRAW_FRAMEBUFFER, this.fbo(s, s.st.drawFb)); gl.bindFramebuffer(GL_READ_FRAMEBUFFER, this.fbo(s, s.st.readFb)); } bindFramebuffer(gl, s, target, id) { gl.bindFramebuffer(target, this.fbo(s, id)); if (target !== GL_READ_FRAMEBUFFER) s.st.drawFb = id; if (target !== GL_DRAW_FRAMEBUFFER) s.st.readFb = id; } /* Make the session's framebuffer 0 what its role needs. */ bindFrame(gl, s) { if (typeof gl.blitFramebuffer !== "function") return; if (s === this.presenter()) { const had = s.surface !== null; if (had && s.surfaceSize) this.opts.resize?.(s.surfaceSize.w, s.surfaceSize.h); this.dropSurface(gl, s); this.makeFrame(gl, s); if (had) this.rebindFrames(gl, s); } else { const had = s.frame !== null; this.dropFrame(gl, s); this.makeSurface(gl, s); if (had) this.rebindFrames(gl, s); } } makeFrame(gl, s) { const w = gl.drawingBufferWidth, h = gl.drawingBufferHeight; if (s.frame && s.frame.w === w && s.frame.h === h) return; this.dropFrame(gl, s); const fbo = gl.createFramebuffer(), color = gl.createRenderbuffer(), depth = gl.createRenderbuffer(); gl.bindRenderbuffer(GL_RENDERBUFFER, color); gl.renderbufferStorage(GL_RENDERBUFFER, 32856, w, h); gl.bindRenderbuffer(GL_RENDERBUFFER, depth); gl.renderbufferStorage(GL_RENDERBUFFER, 35056, w, h); gl.bindRenderbuffer(GL_RENDERBUFFER, s.st.renderbuffer); gl.bindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo); gl.framebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, 36064, GL_RENDERBUFFER, color); gl.framebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, 33306, GL_RENDERBUFFER, depth); s.frame = { fbo, color, depth, w, h }; this.rebindFrames(gl, s); } dropFrame(gl, s) { const f = s.frame; if (!f) return; s.frame = null; gl.deleteFramebuffer(f.fbo); gl.deleteRenderbuffer(f.color); gl.deleteRenderbuffer(f.depth); } makeSurface(gl, s) { const w = s.surfaceSize?.w ?? s.surface?.w ?? gl.drawingBufferWidth; const h = s.surfaceSize?.h ?? s.surface?.h ?? gl.drawingBufferHeight; let f = s.surface; if (f && f.w === w && f.h === h && f.tex.length === s.surfaceBuffers) return; const unit = s.st.activeTexture; const unpack = s.st.buffers.get(GL_PIXEL_UNPACK_BUFFER) ?? null; if (unit !== GL_TEXTURE0) gl.activeTexture(GL_TEXTURE0); if (unpack) gl.bindBuffer(GL_PIXEL_UNPACK_BUFFER, null); if (!f) { f = { fbo: gl.createFramebuffer(), depth: gl.createRenderbuffer(), tex: [], handles: [], back: 0, w, h }; s.surface = f; } while (f.tex.length > s.surfaceBuffers) { f.tex.pop(); this.releaseHandle(gl, f.handles.pop()); } while (f.tex.length < s.surfaceBuffers) { const t = gl.createTexture(); f.tex.push(t); f.handles.push(this.exportTexture(s, t, 0)); } for (const t of f.tex) { gl.bindTexture(GL_TEXTURE_2D, t); gl.texImage2D(GL_TEXTURE_2D, 0, 32856, w, h, 0, 6408, GL_UNSIGNED_BYTE, null); gl.texParameteri(GL_TEXTURE_2D, 10241, 9729); gl.texParameteri(GL_TEXTURE_2D, 10240, 9729); gl.texParameteri(GL_TEXTURE_2D, 10242, 33071); gl.texParameteri(GL_TEXTURE_2D, 10243, 33071); } gl.bindTexture(GL_TEXTURE_2D, s.st.textures.get(texKey(GL_TEXTURE0, GL_TEXTURE_2D)) ?? null); if (unit !== GL_TEXTURE0) gl.activeTexture(unit); if (unpack) gl.bindBuffer(GL_PIXEL_UNPACK_BUFFER, unpack); gl.bindRenderbuffer(GL_RENDERBUFFER, f.depth); gl.renderbufferStorage(GL_RENDERBUFFER, 35056, w, h); gl.bindRenderbuffer(GL_RENDERBUFFER, s.st.renderbuffer); f.w = w; f.h = h; f.back %= f.tex.length; gl.bindFramebuffer(GL_DRAW_FRAMEBUFFER, f.fbo); gl.framebufferTexture2D(GL_DRAW_FRAMEBUFFER, 36064, GL_TEXTURE_2D, f.tex[f.back], 0); gl.framebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, 33306, GL_RENDERBUFFER, f.depth); this.rebindFrames(gl, s); } dropSurface(gl, s) { const f = s.surface; if (!f) return; s.surface = null; gl.deleteFramebuffer(f.fbo); gl.deleteRenderbuffer(f.depth); for (const h of f.handles) this.releaseHandle(gl, h); } /* The back buffer becomes the front; the next one is drawn into. */ flip(gl, s) { const f = s.surface; if (!f) return; f.back = (f.back + 1) % f.tex.length; gl.bindFramebuffer(GL_DRAW_FRAMEBUFFER, f.fbo); gl.framebufferTexture2D(GL_DRAW_FRAMEBUFFER, 36064, GL_TEXTURE_2D, f.tex[f.back], 0); this.rebindFrames(gl, s); } present(gl, s) { const f = s.frame; if (!f) return; const sc = gl.isEnabled(GL_SCISSOR_TEST); if (sc) gl.disable(GL_SCISSOR_TEST); gl.bindFramebuffer(GL_READ_FRAMEBUFFER, f.fbo); gl.bindFramebuffer(GL_DRAW_FRAMEBUFFER, null); gl.blitFramebuffer(0, 0, f.w, f.h, 0, 0, f.w, f.h, 16384, 9728); this.rebindFrames(gl, s); if (sc) gl.enable(GL_SCISSOR_TEST); } /** * The session's file was closed: delete every object it named, its window * surface and exports, and give up presentation if it held it. A texture * another session imported lives on until that session lets go of it. */ closeSession(id) { const s = this.sessions.get(id); if (!s) return; const gl = this.opts.gl(); this.sessions.delete(id); this.stats.sessions = this.sessions.size; if (this.claimant === s) this.claimant = null; if (this.cur === s) this.cur = null; for (const [n, kind] of s.kinds) { const o = s.names.get(n); if (!o || kind === "location") continue; if (kind === "texture" && this.texRefs.has(o)) { this.unref(gl, o); continue; } switch (kind) { case "shader": gl.deleteShader(o); break; case "program": gl.deleteProgram(o); break; case "buffer": gl.deleteBuffer(o); break; case "texture": gl.deleteTexture(o); break; case "vao": gl.deleteVertexArray(o); break; case "framebuffer": gl.deleteFramebuffer(o); break; case "renderbuffer": gl.deleteRenderbuffer(o); break; case "sampler": gl.deleteSampler(o); break; } } s.names.clear(); s.kinds.clear(); this.dropFrame(gl, s); this.dropSurface(gl, s); for (const h of [...s.exports]) this.releaseHandle(gl, h); if (s.defaultVao) gl.deleteVertexArray(s.defaultVao); } setReply(r) { this.cur.reply = r; } /* An integer query's answer: object bindings as the session's names. */ integers(s, v) { if (typeof v === "number") return [v]; if (typeof v === "boolean") return [v ? 1 : 0]; if (v === null || v === void 0) return [0]; if (typeof v === "object" && s.ids.has(v)) return [s.ids.get(v)]; if (typeof v === "object" && typeof v.length === "number") return Array.from(v, (x) => Number(x)); return [0]; } /** Execute one batch of session `sid`. Returns true when it ended in a query. */ execute(bytes, sid = 0) { const gl = this.opts.gl(); const ses = this.session(sid, gl); this.activate(gl, ses); this.bindFrame(gl, ses); const st = ses.st; let presenting = ses === this.presenter(); this.frameWait = null; const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); let p = 0; let queried = false; const t0 = this.now(); this.stats.batches++; this.stats.bytesIn += bytes.byteLength; while (p + 8 <= bytes.byteLength) { const cmd = dv.getUint16(p, true); const n = dv.getUint32(p + 4, true); const a = p + 8; if (a + n > bytes.byteLength) throw new Error(`gl-remote: command ${cmd} at ${p} overruns the batch (${n} bytes)`); const u = (i) => dv.getUint32(a + 4 * i, true); const s = (i) => dv.getInt32(a + 4 * i, true); const f = (i) => dv.getFloat32(a + 4 * i, true); const tail = (i) => bytes.subarray(a + 4 * i, a + n); const bytesAt = (i) => { const len = u(i); if (4 * (i + 1) + len > n) throw new Error(`gl-remote: command ${cmd} at ${p}: ${len} data bytes overrun its ${n} argument bytes`); return tail(i + 1).subarray(0, len); }; const str = (i) => td.decode(bytesAt(i)); const words = (i, k) => { if (4 * (i + k) > n) throw new Error(`gl-remote: command ${cmd} at ${p}: ${k} values from word ${i} overrun its ${n} argument bytes`); }; const floats = (i, k) => { words(i, k); const v = new Float32Array(k); for (let j = 0; j < k; j++) v[j] = f(i + j); return v; }; const ints = (i, k) => { words(i, k); const v = new Int32Array(k); for (let j = 0; j < k; j++) v[j] = s(i + j); return v; }; const faces = (face) => face === GL_FRONT ? [0] : face === GL_BACK ? [1] : face === GL_FRONT_AND_BACK ? [0, 1] : []; this.stats.commands++; queried = cmd >= 256; switch (cmd) { case GLR.VIEWPORT: gl.viewport(s(0), s(1), s(2), s(3)); st.viewport = [s(0), s(1), s(2), s(3)]; break; case GLR.CLEAR_COLOR: gl.clearColor(f(0), f(1), f(2), f(3)); st.clearColor = [f(0), f(1), f(2), f(3)]; break; case GLR.CLEAR: gl.clear(u(0)); break; case GLR.CREATE_SHADER: this.name(u(0), gl.createShader(u(1)), "shader"); break; case GLR.SHADER_SOURCE: gl.shaderSource(this.obj(u(0)), str(1)); break; case GLR.COMPILE_SHADER: gl.compileShader(this.obj(u(0))); break; case GLR.CREATE_PROGRAM: this.name(u(0), gl.createProgram(), "program"); break; case GLR.ATTACH_SHADER: gl.attachShader(this.obj(u(0)), this.obj(u(1))); break; case GLR.LINK_PROGRAM: gl.linkProgram(this.obj(u(0))); break; case GLR.USE_PROGRAM: st.program = this.obj(u(0)); gl.useProgram(st.program); break; case GLR.BIND_ATTRIB_LOCATION: gl.bindAttribLocation(this.obj(u(0)), u(1), str(2)); break; case GLR.GEN_BUFFER: this.name(u(0), gl.createBuffer(), "buffer"); break; case GLR.BIND_BUFFER: { const o = this.obj(u(1)); gl.bindBuffer(u(0), o); if (u(0) !== GL_ELEMENT_ARRAY_BUFFER) st.buffers.set(u(0), o); break; } case GLR.BUFFER_DATA: gl.bufferData(u(0), bytesAt(2), u(1)); break; case GLR.ENABLE_VERTEX_ATTRIB_ARRAY: gl.enableVertexAttribArray(u(0)); break; case GLR.VERTEX_ATTRIB_POINTER: gl.vertexAttribPointer(u(0), s(1), u(2), u(3) !== 0, s(4), u(5)); break; case GLR.DRAW_ARRAYS: gl.drawArrays(u(0), s(1), s(2)); break; case GLR.DRAW_ELEMENTS: gl.drawElements(u(0), s(1), u(2), u(3)); break; case GLR.BIND_BUFFER_RANGE: { const o = this.obj(u(2)); if (u(4) === 0) gl.bindBufferBase(u(0), u(1), o); else gl.bindBufferRange(u(0), u(1), o, u(3), u(4)); const key = u(0) * 256 + u(1); if (o) st.indexed.set(key, [o, u(3), u(4)]); else st.indexed.delete(key); st.buffers.set(u(0), o); break; } case GLR.UNIFORM_BLOCK_BINDING: gl.uniformBlockBinding(this.obj(u(0)), u(1), u(2)); break; case GLR.COPY_BUFFER_SUB_DATA: gl.copyBufferSubData(u(0), u(1), u(2), u(3), u(4)); break; case GLR.DRAW_BUFFERS: { const k = u(0); words(1, k); const fb0 = st.drawFb === 0 && this.fboOf(ses) !== void 0; const bufs = []; for (let i = 0; i < k; i++) bufs.push(fb0 && u(1 + i) === GL_BACK ? GL_COLOR_ATTACHMENT0 : u(1 + i)); gl.drawBuffers(bufs); break; } case GLR.CLEAR_BUFFER: { const buf = u(0), db = s(1), kind = u(2); if (kind === 0) gl.clearBufferfv(buf, db, floats(3, 4)); else if (kind === 1) gl.clearBufferiv(buf, db, ints(3, 4)); else if (kind === 2) { words(3, 4); gl.clearBufferuiv(buf, db, new Uint32Array([u(3), u(4), u(5), u(6)])); } else gl.clearBufferfi(buf === GL_COLOR ? GL_DEPTH_STENCIL : buf, db, f(3), s(4)); break; } case GLR.UNIFORM_UIV: { const loc = this.obj(u(0)), size = u(1), count = u(2); words(3, size * count); const v = new Uint32Array(size * count); for (let i = 0; i < v.length; i++) v[i] = u(3 + i); const fn2 = ["uniform1uiv", "uniform2uiv", "uniform3uiv", "uniform4uiv"][size - 1]; if (!fn2) throw new Error(`gl-remote: UNIFORM_UIV size ${size}`); gl[fn2](loc, v); break; } case GLR.DRAW_ARRAYS_INSTANCED: gl.drawArraysInstanced(u(0), s(1), s(2), s(3)); break; case GLR.DRAW_ELEMENTS_INSTANCED: gl.drawElementsInstanced(u(0), s(1), u(2), u(3), s(4)); break; case GLR.VERTEX_ATTRIB_DIVISOR: gl.vertexAttribDivisor(u(0), u(1)); break; case GLR.VERTEX_ATTRIB_I_POINTER: gl.vertexAttribIPointer(u(0), s(1), u(2), s(3), u(4)); break; case GLR.GEN_SAMPLER: this.name(u(0), gl.createSampler(), "sampler"); break; case GLR.DELETE_SAMPLER: this.del(u(0), (o) => gl.deleteSampler(o)); break; case GLR.BIND_SAMPLER: { const o = this.obj(u(1)); gl.bindSampler(u(0), o); st.samplers.set(u(0), o); break; } case GLR.SAMPLER_PARAMETERI: gl.samplerParameteri(this.obj(u(0)), u(1), s(2)); break; case GLR.SAMPLER_PARAMETERF: gl.samplerParameterf(this.obj(u(0)), u(1), f(2)); break; case GLR.TEX_STORAGE_2D: gl.texStorage2D(u(0), s(1), u(2), s(3), s(4)); break; case GLR.TEX_STORAGE_3D: gl.texStorage3D(u(0), s(1), u(2), s(3), s(4), s(5)); break; case GLR.READ_BUFFER: { const fb0 = st.readFb === 0 && this.fboOf(ses) !== void 0; gl.readBuffer(fb0 && u(0) === GL_BACK ? GL_COLOR_ATTACHMENT0 : u(0)); break; } case GLR.READ_PIXELS_PBO: gl.readPixels(s(0), s(1), s(2), s(3), u(4), u(5), u(6)); break; case GLR.TEX_SUB_IMAGE_PBO: { const layout = [[3314, u(12)], [3317, u(13)], [3315, u(14)], [3316, u(15)]]; for (const [pn, v] of layout) gl.pixelStorei(pn, v); if (u(11) === 3) gl.texSubImage3D(u(0), s(1), s(2), s(3), s(4), s(5), s(6), s(7), u(8), u(9), u(10)); else gl.texSubImage2D(u(0), s(1), s(2), s(3), s(5), s(6), u(8), u(9), u(10)); for (const [pn] of layout) gl.pixelStorei(pn, st.pixelStore.get(pn) ?? PIXEL_STORE_DEFAULT[pn] ?? 0); break; } case GLR.FRAMEBUFFER_TEXTURE_LAYER: gl.framebufferTextureLayer(u(0), u(1), this.obj(u(2)), s(3), s(4)); break; case GLR.UNIFORM_MATRIX_NM: { const loc = this.obj(u(0)), cols = u(1), rows = u(2), count = u(3), tr = u(4) !== 0; const fn2 = { 23: "uniformMatrix2x3fv", 32: "uniformMatrix3x2fv", 24: "uniformMatrix2x4fv", 42: "uniformMatrix4x2fv", 34: "uniformMatrix3x4fv", 43: "uniformMatrix4x3fv" }[cols * 10 + rows]; if (!fn2) throw new Error(`gl-remote: UNIFORM_MATRIX_NM ${cols}x${rows}`); gl[fn2](loc, tr, floats(5, cols * rows * count)); break; } case GLR.UNIFORM_LOCATION: { const pr = this.obj(u(1)); this.name(u(0), pr && gl.getProgramParameter(pr, GL_LINK_STATUS) ? gl.getUniformLocation(pr, str(2)) : null, "location"); break; } case GLR.UNIFORM_4F: gl.uniform4f(this.obj(u(0)), f(1), f(2), f(3), f(4)); break; case GLR.UNIFORM_MATRIX_4FV: { const m = new Float32Array(16); for (let i = 0; i < 16; i++) m[i] = f(1 + i); gl.uniformMatrix4fv(this.obj(u(0)), false, m); break; } case GLR.ENABLE: gl.enable(u(0)); st.caps.set(u(0), true); break; case GLR.DISABLE: gl.disable(u(0)); st.caps.set(u(0), false); break; case GLR.GEN_TEXTURE: this.name(u(0), gl.createTexture(), "texture"); break; case GLR.DELETE_TEXTURE: this.del(u(0), (o) => gl.deleteTexture(o)); break; case GLR.BIND_TEXTURE: { const o = this.obj(u(1)); gl.bindTexture(u(0), o); st.textures.set(texKey(st.activeTexture, u(0)), o); break; } case GLR.TEX_IMAGE_2D: gl.texImage2D(u(0), s(1), u(2), s(3), s(4), 0, u(5), u(6), u(8) ? pixels(u(6), bytesAt(8)) : null); break; case GLR.TEX_SUB_IMAGE_2D: gl.texSubImage2D(u(0), s(1), s(2), s(3), s(4), s(5), u(6), u(7), pixels(u(7), bytesAt(8))); break; case GLR.TEX_PARAMETERI: gl.texParameteri(u(0), u(1), s(2)); break; case GLR.ACTIVE_TEXTURE: gl.activeTexture(u(0)); st.activeTexture = u(0); break; case GLR.UNIFORM_1I: gl.uniform1i(this.obj(u(0)), s(1)); break; case GLR.UNIFORM_2F: gl.uniform2f(this.obj(u(0)), f(1), f(2)); break; case GLR.BLEND_FUNC_SEPARATE: gl.blendFuncSeparate(u(0), u(1), u(2), u(3)); st.blendFunc = [u(0), u(1), u(2), u(3)]; break; case GLR.BLEND_EQUATION: gl.blendEquation(u(0)); st.blendEq = [u(0), u(0)]; break; case GLR.SCISSOR: gl.scissor(s(0), s(1), s(2), s(3)); st.scissor = [s(0), s(1), s(2), s(3)]; break; case GLR.PIXEL_STOREI: gl.pixelStorei(u(0), s(1)); st.pixelStore.set(u(0), s(1)); break; case GLR.UNIFORM_1F: gl.uniform1f(this.obj(u(0)), f(1)); break; case GLR.UNIFORM_3F: gl.uniform3f(this.obj(u(0)), f(1), f(2), f(3)); break; case GLR.DEPTH_FUNC: gl.depthFunc(u(0)); st.depthFunc = u(0); break; case GLR.DEPTH_MASK: gl.depthMask(u(0) !== 0); st.depthMask = u(0) !== 0; break; case GLR.CLEAR_DEPTH: gl.clearDepth(f(0)); st.clearDepth = f(0); break; case GLR.GEN_VERTEX_ARRAY: this.name(u(0), gl.createVertexArray(), "vao"); break; case GLR.BIND_VERTEX_ARRAY: { st.vao = this.obj(u(0)); gl.bindVertexArray(st.vao ?? ses.defaultVao ?? null); break; } case GLR.CULL_FACE: gl.cullFace(u(0)); st.cullFace = u(0); break; case GLR.DELETE_BUFFER: this.del(u(0), (o) => gl.deleteBuffer(o)); break; case GLR.DELETE_SHADER: this.del(u(0), (o) => gl.deleteShader(o)); break; case GLR.DELETE_PROGRAM: this.del(u(0), (o) => gl.deleteProgram(o)); break; case GLR.DETACH_SHADER: gl.detachShader(this.obj(u(0)), this.obj(u(1))); break; case GLR.DISABLE_VERTEX_ATTRIB_ARRAY: gl.disableVertexAttribArray(u(0)); break; case GLR.GEN_FRAMEBUFFER: this.name(u(0), gl.createFramebuffer(), "framebuffer"); break; case GLR.BIND_FRAMEBUFFER: this.bindFramebuffer(gl, ses, u(0), u(1)); break; case GLR.DELETE_FRAMEBUFFER: { const id = u(0); this.del(id, (o) => gl.deleteFramebuffer(o)); if (id !== 0 && (st.drawFb === id || st.readFb === id)) { if (st.drawFb === id) st.drawFb = 0; if (st.readFb === id) st.readFb = 0; if (this.fboOf(ses) !== void 0) this.rebindFrames(gl, ses); } break; } case GLR.FRAMEBUFFER_TEXTURE_2D: gl.framebufferTexture2D(u(0), u(1), u(2), this.obj(u(3)), s(4)); break; case GLR.FRAMEBUFFER_RENDERBUFFER: gl.framebufferRenderbuffer(u(0), u(1), u(2), this.obj(u(3))); break; case GLR.GEN_RENDERBUFFER: this.name(u(0), gl.createRenderbuffer(), "renderbuffer"); break; case GLR.BIND_RENDERBUFFER: st.renderbuffer = this.obj(u(1)); gl.bindRenderbuffer(u(0), st.renderbuffer); break; case GLR.DELETE_RENDERBUFFER: this.del(u(0), (o) => gl.deleteRenderbuffer(o)); break; case GLR.RENDERBUFFER_STORAGE: gl.renderbufferStorage(u(0), u(1), s(2), s(3)); break; case GLR.BLIT_FRAMEBUFFER: gl.blitFramebuffer(s(0), s(1), s(2), s(3), s(4), s(5), s(6), s(7), u(8), u(9)); break; case GLR.UNIFORM_FV: { const size = u(1), count = u(2); if (size < 1 || size > 4) throw new Error(`gl-remote: UNIFORM_FV size ${size}`); gl[`uniform${size}fv`](this.obj(u(0)), floats(3, size * count)); break; } case GLR.UNIFORM_IV: { const size = u(1), count = u(2); if (size < 1 || size > 4) throw new Error(`gl-remote: UNIFORM_IV size ${size}`); gl[`uniform${size}iv`](this.obj(u(0)), ints(3, size * count)); break; } case GLR.UNIFORM_MATRIX_FV: { const dim = u(1), count = u(2); if (dim < 2 || dim > 4) throw new Error(`gl-remote: UNIFORM_MATRIX_FV dimension ${dim}`); gl[`uniformMatrix${dim}fv`](this.obj(u(0)), u(3) !== 0, floats(4, dim * dim * count)); break; } case GLR.COLOR_MASK: gl.colorMask(u(0) !== 0, u(1) !== 0, u(2) !== 0, u(3) !== 0); st.colorMask = [u(0) ? 1 : 0, u(1) ? 1 : 0, u(2) ? 1 : 0, u(3) ? 1 : 0]; break; case GLR.STENCIL_FUNC_SEPARATE: gl.stencilFuncSeparate(u(0), u(1), s(2), u(3)); for (const k of faces(u(0))) st.stencil[k] = [u(1), s(2), u(3), ...st.stencil[k].slice(3)]; break; case GLR.STENCIL_OP_SEPARATE: gl.stencilOpSeparate(u(0), u(1), u(2), u(3)); for (const k of faces(u(0))) st.stencil[k] = [...st.stencil[k].slice(0, 3), u(1), u(2), u(3), st.stencil[k][6]]; break; case GLR.STENCIL_MASK_SEPARATE: gl.stencilMaskSeparate(u(0), u(1)); for (const k of faces(u(0))) st.stencil[k] = [...st.stencil[k].slice(0, 6), u(1)]; break; case GLR.CLEAR_STENCIL: gl.clearStencil(s(0)); st.clearStencil = s(0); break; case GLR.FRONT_FACE: gl.frontFace(u(0)); st.frontFace = u(0); break; case GLR.POLYGON_OFFSET: gl.polygonOffset(f(0), f(1)); st.polygonOffset = [f(0), f(1)]; break; case GLR.DEPTH_RANGE: gl.depthRange(f(0), f(1)); st.depthRange = [f(0), f(1)]; break; case GLR.BLEND_COLOR: gl.blendColor(f(0), f(1), f(2), f(3)); st.blendColor = [f(0), f(1), f(2), f(3)]; break; case GLR.LINE_WIDTH: gl.lineWidth(f(0)); st.lineWidth = f(0); break; case GLR.VERTEX_ATTRIB_4F: gl.vertexAttrib4f(u(0), f(1), f(2), f(3), f(4)); st.attribs.set(u(0), [f(1), f(2), f(3), f(4)]); break; case GLR.BLEND_EQUATION_SEPARATE: gl.blendEquationSeparate(u(0), u(1)); st.blendEq = [u(0), u(1)]; break; case GLR.BUFFER_SUB_DATA: gl.bufferSubData(u(0), u(1), bytesAt(2)); break; case GLR.BUFFER_DATA_SIZE: gl.bufferData(u(0), u(2), u(1)); break; case GLR.GENERATE_MIPMAP: gl.generateMipmap(u(0)); break; case GLR.COPY_TEX_IMAGE_2D: gl.copyTexImage2D(u(0), s(1), u(2), s(3), s(4), s(5), s(6), 0); break; case GLR.COPY_TEX_SUB_IMAGE_2D: gl.copyTexSubImage2D(u(0), s(1), s(2), s(3), s(4), s(5), s(6), s(7)); break; case GLR.TEX_IMAGE_3D: gl.texImage3D(u(0), s(1), u(2), s(3), s(4), s(5), 0, u(6), u(7), u(8) ? pixels(u(7), bytesAt(8)) : null); break; case GLR.TEX_SUB_IMAGE_3D: gl.texSubImage3D(u(0), s(1), s(2), s(3), s(4), s(5), s(6), s(7), u(8), u(9), pixels(u(9), bytesAt(10))); break; case GLR.DELETE_VERTEX_ARRAY: { const was = st.vao; this.del(u(0), (o) => gl.deleteVertexArray(o)); if (was !== null && st.vao === null && ses.defaultVao) gl.bindVertexArray(ses.defaultVao); break; } case GLR.SWAP_INTERVAL: ses.swapInterval = Math.min(u(0), 4); break; case GLR.CANVAS_SIZE: if (u(0) > 0 && u(1) > 0 && u(0) <= 8192 && u(1) <= 8192) ses.surfaceSize = { w: u(0), h: u(1) }; if (presenting) this.opts.resize?.(u(0), u(1)); this.bindFrame(gl, ses); break; case GLR.SWAP: if (presenting) { this.present(gl, ses); this.opts.onSwap?.(); } else { this.flip(gl, ses); } ses.swaps++; this.stats.swaps++; this.frameWait = ses.pacer?.swap(ses.swapInterval) ?? null; break; case GLR.PRESENT_CLAIM: if (u(0) !== 0) { if (this.claimant === null || this.claimant === ses) this.claimant = ses; else ses.error = GL_INVALID_OPERATION; } else if (this.claimant === ses) { this.claimant = null; } presenting = ses === this.presenter(); this.bindFrame(gl, ses); break; case GLR.IMPORT_TEXTURE: { const e = this.exportsByHandle.get(u(1)); if (e) { this.texRefs.set(e.tex, (this.texRefs.get(e.tex) ?? 0) + 1); this.name(u(0), e.tex, "texture"); this.stats.imports++; } else { this.name(u(0), gl.createTexture(), "texture"); ses.error = GL_INVALID_OPERATION; this.opts.onError?.(new Error(`gl-remote: session ${ses.id} imported handle ${u(1)}, which no session exports`)); } break; } case GLR.RELEASE_HANDLE: { const e = this.exportsByHandle.get(u(0)); if (e && e.owner === ses && !ses.surface?.handles.includes(u(0))) this.releaseHandle(gl, u(0)); else ses.error = GL_INVALID_OPERATION; break; } case GLR.SURFACE_BUFFERS: if (u(0) < 2 || u(0) > 4) throw new Error(`gl-remote: SURFACE_BUFFERS ${u(0)}: 2 to 4`); ses.surfaceBuffers = u(0); this.bindFrame(gl, ses); break; case GLR.GET_ERROR: { const e = ses.error || gl.getError(); ses.error = 0; this.setReply(i32s([e])); break; } case GLR.GET_INTEGERV: { const pname = u(0); const v = pname === GL_FRAMEBUFFER_BINDING ? [st.drawFb] : pname === GL_READ_FRAMEBUFFER_BINDING ? [st.readFb] : this.integers(ses, gl.getParameter(pname)); this.setReply(i32s(v)); break; } case GLR.READ_PIXELS: { const w = s(2), h = s(3); const out = new Uint8Array(w * h * 4); gl.readPixels(s(0), s(1), w, h, GL_RGBA, GL_UNSIGNED_BYTE, out); this.setReply(out); break; } case GLR.FINISH: gl.finish(); this.setReply(i32s([0])); break; case GLR.GET_SHADER_STATUS: { const sh = this.obj(u(0)); const ok = gl.getShaderParameter(sh, GL_COMPILE_STATUS) ? 1 : 0; this.setReply(statusReply(ok, ok ? "" : gl.getShaderInfoLog(sh) ?? "")); break; } case GLR.GET_PROGRAM_STATUS: { const pr = this.obj(u(0)); const ok = gl.getProgramParameter(pr, GL_LINK_STATUS) ? 1 : 0; this.setReply(statusReply(ok, ok ? "" : gl.getProgramInfoLog(pr) ?? "")); break; } case GLR.INPUT_POLL: this.setReply((presenting ? this.opts.pollInput?.() : void 0) ?? new Uint8Array(16)); break; case GLR.CHECK_FRAMEBUFFER_STATUS: this.setReply(i32s([gl.checkFramebufferStatus(u(0))])); break; case GLR.GET_ATTRIB_LOCATION: this.setReply(i32s([gl.getAttribLocation(this.obj(u(0)), str(1))])); break; case GLR.GET_STRING: this.setReply(te.encode(u(0) === GLR_EXTENSIONS ? GLR_EXTENSION_LIST : String(gl.getParameter(u(0)) ?? ""))); break; case GLR.GET_UNIFORM_BLOCK_INDEX: this.setReply(i32s([gl.getUniformBlockIndex(this.obj(u(0)), str(1)) | 0])); break; case GLR.GET_ACTIVE_UNIFORMS: this.setReply(activeUniforms(gl, this.obj(u(0)))); break; case GLR.GET_BUFFER_SUB_DATA: { const out = new Uint8Array(u(2)); gl.getBufferSubData(u(0), u(1), out); this.setReply(out); break; } case GLR.EXPORT_TEXTURE: { const tex = this.obj(u(0)); if (!tex || ses.kinds.get(u(0)) !== "texture") throw new Error(`gl-remote: EXPORT_TEXTURE of name ${u(0)}, which is not a texture`); const e = this.exportOf.get(tex); this.setReply(i32s([e !== void 0 ? e : this.exportTexture(ses, tex, 1)])); break; } case GLR.SURFACE_FRONT: { const sf = ses.surface; if (sf) { const front = (sf.back + sf.tex.length - 1) % sf.tex.length; this.setReply(i32s([ses.swaps ? sf.handles[front] : 0, sf.w, sf.h, ses.swaps, sf.tex.length, ...sf.handles])); } else { this.setReply(i32s([0, ses.frame?.w ?? gl.drawingBufferWidth, ses.frame?.h ?? gl.drawingBufferHeight, ses.swaps, 0])); } break; } case GLR.SESSION_INFO: this.setReply(i32s([ses.id, presenting ? 1 : 0, this.sessions.size, this.claimant === ses ? 1 : 0])); break; default: throw new Error(`gl-remote: unknown command ${cmd} at byte ${p}`); } p = a + (n + 3 & ~3); } if (p !== bytes.byteLength) throw new Error(`gl-remote: ${bytes.byteLength - p} trailing bytes after the last command`); this.stats.glMs += this.now() - t0; if (queried) this.stats.queries++; return queried; } }; function texKey(unit, target) { return (unit - GL_TEXTURE0) * 65536 + target; } function applyState(gl, a, b) { if (!same(a.viewport, b.viewport)) gl.viewport(b.viewport[0], b.viewport[1], b.viewport[2], b.viewport[3]); if (!same(a.scissor, b.scissor)) gl.scissor(b.scissor[0], b.scissor[1], b.scissor[2], b.scissor[3]); if (!same(a.clearColor, b.clearColor)) gl.clearColor(b.clearColor[0], b.clearColor[1], b.clearColor[2], b.clearColor[3]); if (a.clearDepth !== b.clearDepth) gl.clearDepth(b.clearDepth); if (a.clearStencil !== b.clearStencil) gl.clearStencil(b.clearStencil); for (const cap of /* @__PURE__ */ new Set([...a.caps.keys(), ...b.caps.keys()])) { const x = a.caps.get(cap) ?? capDefault(cap), y = b.caps.get(cap) ?? capDefault(cap); if (x !== y) y ? gl.enable(cap) : gl.disable(cap); } if (!same(a.blendFunc, b.blendFunc)) gl.blendFuncSeparate(b.blendFunc[0], b.blendFunc[1], b.blendFunc[2], b.blendFunc[3]); if (!same(a.blendEq, b.blendEq)) gl.blendEquationSeparate(b.blendEq[0], b.blendEq[1]); if (!same(a.blendColor, b.blendColor)) gl.blendColor(b.blendColor[0], b.blendColor[1], b.blendColor[2], b.blendColor[3]); if (!same(a.colorMask, b.colorMask)) gl.colorMask(!!b.colorMask[0], !!b.colorMask[1], !!b.colorMask[2], !!b.colorMask[3]); if (a.depthFunc !== b.depthFunc) gl.depthFunc(b.depthFunc); if (a.depthMask !== b.depthMask) gl.depthMask(b.depthMask); if (!same(a.depthRange, b.depthRange)) gl.depthRange(b.depthRange[0], b.depthRange[1]); for (const k of [0, 1]) { const x = a.stencil[k], y = b.stencil[k], face = k === 0 ? GL_FRONT : GL_BACK; if (!same(x.slice(0, 3), y.slice(0, 3))) gl.stencilFuncSeparate(face, y[0], y[1], y[2]); if (!same(x.slice(3, 6), y.slice(3, 6))) gl.stencilOpSeparate(face, y[3], y[4], y[5]); if (x[6] !== y[6]) gl.stencilMaskSeparate(face, y[6]); } if (a.cullFace !== b.cullFace) gl.cullFace(b.cullFace); if (a.frontFace !== b.frontFace) gl.frontFace(b.frontFace); if (a.lineWidth !== b.lineWidth) gl.lineWidth(b.lineWidth); if (!same(a.polygonOffset, b.polygonOffset)) gl.polygonOffset(b.polygonOffset[0], b.polygonOffset[1]); for (const pn of /* @__PURE__ */ new Set([...a.pixelStore.keys(), ...b.pixelStore.keys()])) { const d = PIXEL_STORE_DEFAULT[pn] ?? 0; const y = b.pixelStore.get(pn) ?? d; if ((a.pixelStore.get(pn) ?? d) !== y) gl.pixelStorei(pn, y); } for (const i of /* @__PURE__ */ new Set([...a.attribs.keys(), ...b.attribs.keys()])) { const y = b.attribs.get(i) ?? [0, 0, 0, 1]; if (!same(a.attribs.get(i) ?? [0, 0, 0, 1], y)) gl.vertexAttrib4f(i, y[0], y[1], y[2], y[3]); } if (a.program !== b.program) gl.useProgram(b.program); const touched = /* @__PURE__ */ new Set(); for (const k of /* @__PURE__ */ new Set([...a.indexed.keys(), ...b.indexed.keys()])) { const x = a.indexed.get(k), y = b.indexed.get(k); if (x && y && x[0] === y[0] && x[1] === y[1] && x[2] === y[2]) continue; const t = Math.floor(k / 256), i = k % 256; if (!y) gl.bindBufferBase(t, i, null); else if (y[2] === 0) gl.bindBufferBase(t, i, y[0]); else gl.bindBufferRange(t, i, y[0], y[1], y[2]); touched.add(t); } for (const t of touched) gl.bindBuffer(t, b.buffers.get(t) ?? null); for (const u of /* @__PURE__ */ new Set([...a.samplers.keys(), ...b.samplers.keys()])) { const y = b.samplers.get(u) ?? null; if ((a.samplers.get(u) ?? null) !== y) gl.bindSampler(u, y); } for (const t of /* @__PURE__ */ new Set([...a.buffers.keys(), ...b.buffers.keys()])) { const y = b.buffers.get(t) ?? null; if ((a.buffers.get(t) ?? null) !== y) gl.bindBuffer(t, y); } let unit = a.activeTexture; for (const k of /* @__PURE__ */ new Set([...a.textures.keys(), ...b.textures.keys()])) { const y = b.textures.get(k) ?? null; if ((a.textures.get(k) ?? null) === y) continue; const u = GL_TEXTURE0 + Math.floor(k / 65536); if (u !== unit) { gl.activeTexture(u); unit = u; } gl.bindTexture(k % 65536, y); } if (unit !== b.activeTexture) gl.activeTexture(b.activeTexture); if (a.renderbuffer !== b.renderbuffer) gl.bindRenderbuffer(GL_RENDERBUFFER, b.renderbuffer); } var PIXEL_ARRAYS = { 5120: Int8Array, 5122: Int16Array, 5123: Uint16Array, 5124: Int32Array, 5125: Uint32Array, 5126: Float32Array, 5131: Uint16Array, 32819: Uint16Array, 32820: Uint16Array, 33635: Uint16Array, 33640: Uint32Array, 34042: Uint32Array, 35899: Uint32Array, 35902: Uint32Array }; function pixels(type, b) { const T = PIXEL_ARRAYS[type]; if (!T) return b; const size = T.BYTES_PER_ELEMENT; const src = b.byteOffset % size === 0 ? b : b.slice(); return new T(src.buffer, src.byteOffset, Math.floor(src.byteLength / size)); } function i32s(v) { const out = new Uint8Array(4 * v.length); const dv = new DataView(out.buffer); v.forEach((x, i) => dv.setInt32(4 * i, x | 0, true)); return out; } function activeUniforms(gl, pr) { const n = pr && gl.getProgramParameter(pr, GL_LINK_STATUS) ? Number(gl.getProgramParameter(pr, GL_ACTIVE_UNIFORMS)) | 0 : 0; const rows = []; for (let i = 0; i < n; i++) { const a = gl.getActiveUniform(pr, i); if (a && gl.getUniformLocation(pr, a.name) !== null) rows.push({ size: a.size, type: a.type, name: te.encode(a.name) }); } const out = new Uint8Array(rows.reduce((t, r) => t + 12 + (r.name.length + 3 & ~3), 4)); const dv = new DataView(out.buffer); dv.setInt32(0, rows.length, true); let p = 4; for (const r of rows) { dv.setUint32(p, r.size, true); dv.setUint32(p + 4, r.type, true); dv.setUint32(p + 8, r.name.length, true); out.set(r.name, p + 12); p += 12 + (r.name.length + 3 & ~3); } return out; } function statusReply(ok, log2) { const l = te.encode(log2); const out = new Uint8Array(8 + l.length); const dv = new DataView(out.buffer); dv.setInt32(0, ok, true); dv.setUint32(4, l.length, true); out.set(l, 8); return out; } function makeGlRemoteOps(dec2, report) { const fail = (e) => { const err2 = e instanceof Error ? e : new Error(String(e)); report?.(err2); return { status: -EBADMSG, length: 0 }; }; const mine = (req) => req.objectId === GLR_OBJECT_ID && req.buf !== null; return { [WASM_HOSTTRANS_OP_NOP]: () => ({ status: 0, length: 0 }), [WASM_HOSTTRANS_OP_CLOSE]: (req) => { try { dec2.closeSession(req.session ?? 0); } catch (e) { report?.(e instanceof Error ? e : new Error(String(e))); } return { status: 0, length: 0 }; }, [WASM_HOSTTRANS_OP_WRITE]: (req) => { if (!mine(req)) return { status: -EINVAL3, length: 0 }; const n = Math.min(req.length || req.buf.len, req.buf.len); try { dec2.execute(req.buf.read(n), req.session ?? 0); } catch (e) { return fail(e); } const done = { status: 0, length: n }; const wait = dec2.takeFrameWait(); return wait ? wait.then(() => done) : done; }, [WASM_HOSTTRANS_OP_ECHO]: (req) => { if (!mine(req)) return { status: -EINVAL3, length: 0 }; const n = Math.min(req.length || req.buf.len, req.buf.len); let queried; try { queried = dec2.execute(req.buf.read(n), req.session ?? 0); } catch (e) { return fail(e); } const r = dec2.lastReply; const answer = () => { if (!queried) return { status: 0, length: 0 }; const m = Math.min(r.byteLength, req.buf.len); req.buf.write(r.subarray(0, m)); dec2.stats.bytesOut += m; return { status: 0, length: m }; }; const wait = dec2.takeFrameWait(); return wait ? wait.then(answer) : answer(); }, [WASM_HOSTTRANS_OP_READ]: (req) => { if (!mine(req)) return { status: -EINVAL3, length: 0 }; const r = dec2.replyOf(req.session ?? 0); const off = Number(req.offset); if (off > r.byteLength) return { status: -EINVAL3, length: 0 }; const m = Math.min(r.byteLength - off, req.buf.len, req.length || req.buf.len); req.buf.write(r.subarray(off, off + m)); dec2.stats.bytesOut += m; return { status: 0, length: m }; } }; } // ../../linux-in-the-browser/hardwarejs/src/devices/webgpu-remote-enums.ts var WGPU_FeatureName = { 1: "core-features-and-limits", 2: "depth-clip-control", 3: "depth32float-stencil8", 4: "texture-compression-bc", 5: "texture-compression-bc-sliced-3d", 6: "texture-compression-etc2", 7: "texture-compression-astc", 8: "texture-compression-astc-sliced-3d", 9: "timestamp-query", 10: "indirect-first-instance", 11: "shader-f16", 12: "rg11b10ufloat-renderable", 13: "bgra8unorm-storage", 14: "float32-filterable", 15: "float32-blendable", 16: "clip-distances", 17: "dual-source-blending", 18: "subgroups", 19: "texture-formats-tier1", 20: "texture-formats-tier2", 21: "primitive-index", 22: "texture-component-swizzle", 23: "subgroup-size-control", 24: "texture-compression-unaligned", 25: "atomic-vec2u-min-max" }; // ../../linux-in-the-browser/hardwarejs/src/devices/webgpu-remote.ts var WGR = { CREATE_BUFFER: 2, CREATE_SHADER_MODULE: 3, CREATE_COMPUTE_PIPELINE: 4, CREATE_RENDER_PIPELINE: 5, PIPELINE_GET_BIND_GROUP_LAYOUT: 6, CREATE_BIND_GROUP_LAYOUT: 7, CREATE_PIPELINE_LAYOUT: 8, CREATE_BIND_GROUP: 9, CREATE_TEXTURE: 10, CREATE_TEXTURE_VIEW: 11, CREATE_SAMPLER: 12, CREATE_COMMAND_ENCODER: 13, BEGIN_COMPUTE_PASS: 14, BEGIN_RENDER_PASS: 15, PASS_SET_PIPELINE: 16, PASS_SET_BIND_GROUP: 17, DISPATCH: 18, SET_VERTEX_BUFFER: 19, SET_INDEX_BUFFER: 20, DRAW: 21, DRAW_INDEXED: 22, SET_VIEWPORT: 23, SET_SCISSOR: 24, PASS_END: 25, COPY_B2B: 26, COPY_T2B: 27, COPY_B2T: 28, ENC_FINISH: 29, QUEUE_SUBMIT: 30, QUEUE_WRITE_BUFFER: 31, QUEUE_WRITE_TEXTURE: 32, RELEASE: 33, BUFFER_UNMAP: 34, SURFACE_CONFIGURE: 35, SURFACE_GET_TEXTURE: 36, SURFACE_PRESENT: 37, SET_BLEND_CONSTANT: 38, /* Extension commands: a guest sends them only when EXTENSIONS lists them. */ CLEAR_BUFFER: 39, COPY_T2T: 40, SET_STENCIL_REFERENCE: 41, PUSH_ERROR_SCOPE: 42, /* Queries: each sets the reply that ECHO and READ return. */ PING: 256, GET_ERRORS: 257, QUEUE_WORK_DONE: 258, BUFFER_MAP: 259, ADAPTER_INFO: 260, LIMITS: 261, EXTENSIONS: 262, FEATURES: 263, REQUEST_ADAPTER: 272, REQUEST_DEVICE: 273, POP_ERROR_SCOPE: 274 }; var WGR_FEATURE_ID = Object.fromEntries(Object.entries(WGPU_FeatureName).map(([k, v]) => [v, Number(k)])); var WHOLE = 2 ** 64 - 1; var td2 = new TextDecoder(); var te2 = new TextEncoder(); var WGR_NAMES = Object.fromEntries(Object.entries(WGR).map(([k, v]) => [v, k])); // ../../linux-in-the-browser/hardwarejs/src/devices/web_socket_packet_uplink.ts var WS_BUFFER_CEIL = 8 * 1024 * 1024; // ../../linux-in-the-browser/hardwarejs/src/pty-bridge-abi.ts var WASM_PTY_BRIDGE_MAX_CONSOLES = 32; var WASM_PTY_BRIDGE_NR_RINGS = 2 + WASM_PTY_BRIDGE_MAX_CONSOLES; var WASM_PTY_BRIDGE_INJECT_CAP = 8192; var WASM_PTY_BRIDGE_DRAIN_CAP = 8192; var WASM_PTY_BRIDGE_HEADER_SIZE = 64; var PB = { ACTIVE: 0, /* active */ PTN: 4, /* ptn */ READER_WAKE_OFF: 8, /* reader_wake_off (kernel publishes; JS notifies) */ ABI_VERSION: 12, /* abi_version */ INJECT_HEAD: 16, /* inject_head (JS producer, release) */ INJECT_TAIL: 20, /* inject_tail (kernel consumer) */ INJECT_CAP: 24, /* inject_cap */ /* ABI v3 (was inject_resv): the host bumps it to hang up the ring's * slave — SIGHUP to the session on /dev/pts/. The kernel keeps the * last seq it applied privately; the pty pair survives the hangup. */ HANGUP_SEQ: 28, /* hangup_seq (JS producer, release) */ DRAIN_HEAD: 32, /* drain_head (kernel producer, release) */ DRAIN_TAIL: 36, /* drain_tail (JS consumer) */ DRAIN_NOTIFY: 40, /* drain_notify (kernel bumps + notifies; JS waits) */ DRAIN_CAP: 44, /* drain_cap */ /* linux-in-the-browser#30: kernel-published offset of * __sched_wakeup_word (was reserved[0], always 0 under ABI v1 — a new * consumer feature-detects it, an old consumer ignores it; no version * bump). 0 = ttyd absent (wasm_tty_red / pre-#30 kernel): skip the * kernel-Worker kick and input is reader-pumped only. */ SCHED_WAKE_OFF: 48, /* sched_wake_off */ /* support#12 (ABI v2, was reserved[1..3]): host->guest terminal size. * The host stores WINSIZE_REQ = (rows << 16) | cols — one word so * rows/cols can never be observed torn — then bumps WINSIZE_SEQ with a * release store. The kernel's wasm-ttyd applies the size (which * delivers SIGWINCH to the foreground pgrp) and echoes the seq it * consumed into WINSIZE_ACK. SEQ != ACK is the level-triggered * work-pending predicate, so a resize is never lost and a drag-resize * burst collapses to a single apply of the newest size. */ WINSIZE_REQ: 52, /* winsize_req (JS producer) */ WINSIZE_SEQ: 56, /* winsize_seq (JS producer, release) */ WINSIZE_ACK: 60, /* winsize_ack (kernel consumer echoes seq) */ INJECT_BUF: WASM_PTY_BRIDGE_HEADER_SIZE, /* inject_buf[INJECT_CAP] */ DRAIN_BUF: WASM_PTY_BRIDGE_HEADER_SIZE + WASM_PTY_BRIDGE_INJECT_CAP /* drain_buf[DRAIN_CAP] */ }; var WASM_PTY_BRIDGE_RING_SIZE = WASM_PTY_BRIDGE_HEADER_SIZE + WASM_PTY_BRIDGE_INJECT_CAP + WASM_PTY_BRIDGE_DRAIN_CAP; // ../../linux-in-the-browser/hardwarejs/src/ptyBridge.ts var enc = new TextEncoder(); var EMPTY2 = new Uint8Array(0); var dec = new TextDecoder("utf-8", { fatal: false }); // ../../linux-in-the-browser/hardwarejs/src/serial-bridge-abi.ts var WASM_SERIAL_RX_CAP = 8192; var WASM_SERIAL_TX_CAP = 8192; var WASM_SERIAL_BRIDGE_HEADER_SIZE = 128; var SB = { ABI_VERSION: 0, /* abi_version */ ACTIVE: 4, /* active (HOST sets 1 while a port backend is attached) */ NPORTS: 8, /* nports */ SCHED_WAKE_OFF: 12, /* sched_wake_off (kernel publishes; JS bumps) */ DOORBELL: 16, /* doorbell (kernel bumps + notifies; JS waits) */ OPEN_COUNT: 20, /* open_count */ RX_HEAD: 24, /* rx_head (JS producer, release) */ RX_TAIL: 28, /* rx_tail (kernel consumer) */ RX_CAP: 32, /* rx_cap */ TX_HEAD: 36, /* tx_head (kernel producer, release) */ TX_TAIL: 40, /* tx_tail (JS consumer) */ TX_CAP: 44, /* tx_cap */ CFG_SEQ: 48, /* cfg_seq (kernel bumps after cfg updates) */ CFG_ACK: 52, /* cfg_ack (JS stores last applied seq) */ CFG_BAUD: 56, /* cfg_baud */ CFG_FORMAT: 60, /* cfg_format (SERIAL_FMT_* bits) */ MCTRL_SEQ: 64, /* mctrl_seq (kernel bumps after mctrl updates) */ MCTRL_ACK: 68, /* mctrl_ack (JS stores last applied seq) */ MCTRL: 72, /* mctrl (TIOCM_DTR|TIOCM_RTS + BREAK bit) */ MSTS: 76, /* msts (JS: TIOCM_CTS|CAR|RNG|DSR from getSignals()) */ RX_BUF: WASM_SERIAL_BRIDGE_HEADER_SIZE, /* rx_buf[RX_CAP] */ TX_BUF: WASM_SERIAL_BRIDGE_HEADER_SIZE + WASM_SERIAL_RX_CAP /* tx_buf[TX_CAP] */ }; var WASM_SERIAL_BRIDGE_RING_SIZE = WASM_SERIAL_BRIDGE_HEADER_SIZE + WASM_SERIAL_RX_CAP + WASM_SERIAL_TX_CAP; // src/boot-worker.mjs var KERNEL_WORKER = new URL("./kernelWorker-browser.js", import.meta.url).href; var USER_WORKER = new URL("./worker-browser.js", import.meta.url).href; var log = (t) => self.postMessage({ kind: "log", text: typeof t === "string" ? t : new TextDecoder().decode(t) }); var inject = null; var INSP = 1229869904; var inspSeq = 0; var inspWaiters = /* @__PURE__ */ new Map(); var askPage = (msg) => new Promise((resolve) => { const id = ++inspSeq; inspWaiters.set(id, resolve); self.postMessage({ kind: "insp", id, ...msg }); setTimeout(() => { if (inspWaiters.delete(id)) resolve({ status: -110, data: "" }); }, 5e3); }); async function inspHandler(req) { if (req.opcode === 1) { const rep = await askPage({ op: "read" }); if (!req.buf) return { status: -14, length: 0 }; const b = new TextEncoder().encode(rep.data || ""); const n = Math.min(b.length, req.buf.len); req.buf.write(b.subarray(0, n)); return { status: rep.status | 0, length: n }; } if (req.opcode === 2) { const raw = req.buf ? req.buf.read(Math.min(req.length || req.buf.len, req.buf.len)) : new Uint8Array(0); const rep = await askPage({ op: "write", data: new TextDecoder().decode(raw) }); return { status: rep.status | 0, length: raw.length }; } return { status: 0, length: 0 }; } var pending = []; var usbBackend = null; var usbFilters = null; var usbPorts = /* @__PURE__ */ new Map(); var usbHigh = (d) => d.vendorId === 5562 && d.productId === 43 || // Olimex ARM-USB-OCD-H (FT2232H) d.vendorId === 1027 && (d.productId === 24592 || d.productId === 24596) || d.vendorId === 3034 && (d.productId === 33107 || d.productId === 33106 || d.productId === 33110) || // Realtek USB LAN d.vendorId === 2965; var usbMatch = (d) => !usbFilters || usbFilters.some((f) => (f.vendorId == null || f.vendorId === d.vendorId) && (f.productId == null || f.productId === d.productId)); var usbName = (d) => `${d.vendorId.toString(16).padStart(4, "0")}:${d.productId.toString(16).padStart(4, "0")} ${d.productName || ""}`.trim(); var usbReport = () => self.postMessage({ kind: "usb", ready: !!usbBackend, devices: [...usbPorts].map(([d, port]) => ({ id: usbName(d), serial: d.serialNumber || "", port })) }); async function usbAttachAll() { if (!usbBackend || !self.navigator.usb) return; for (const d of await navigator.usb.getDevices()) { if (usbPorts.has(d) || !usbMatch(d)) continue; try { const port = await usbBackend.attachDevice(d, usbHigh(d) ? "high" : "full"); usbPorts.set(d, port); log(`[usb] attached ${usbName(d)} ${d.serialNumber || ""} -> port ${port} `); } catch (e) { log(`[usb] attach ${usbName(d)} failed: ${e && e.message || e} `); } } usbReport(); } if (self.navigator.usb) { navigator.usb.addEventListener("connect", () => usbAttachAll()); navigator.usb.addEventListener("disconnect", (e) => { const port = usbPorts.get(e.device); if (port === void 0) return; usbPorts.delete(e.device); try { usbBackend.detachDevice(port); } catch { } log(`[usb] detached ${usbName(e.device)} (port ${port}) `); usbReport(); }); } self.onmessage = async (ev) => { const m = ev.data; if (m.kind === "insp-reply") { const w = inspWaiters.get(m.id); if (w) { inspWaiters.delete(m.id); w(m); } return; } if (m.kind === "usb-attach") { usbAttachAll(); return; } if (m.kind === "boot") { try { await boot2(m); } catch (e) { log("BOOT ERR: " + (e && e.stack || e) + "\n"); } } else if (m.kind === "input") { const batch = inject ? [m] : (pending.push(m), []); for (const b of batch) { for (const [t, c, v] of b.events) inject(t, c, v); inject(0, 0, 0); } } }; async function boot2(m) { const { kernelBytes, ramMB, userMB } = m; const glr = m.mode === "glr"; const RAM = ramMB | 0 || 256, USER = userMB | 0 || 64; log("[boot] mode=" + (glr ? "glr" : "legacy") + " PhysRam RAM=" + RAM + "MB USER=" + USER + "MB\n"); const ram = new PhysRam({ kernelBytes: RAM * 1048576, kernelMaxBytes: RAM * 1048576, declaredMemoryBytes: RAM * 1048576, userInitBytes: USER * 1048576 }); log("[boot] compiling kernel (" + kernelBytes.byteLength + " b)\n"); const vmlinuxModule = await WebAssembly.compile(kernelBytes); const hwjsRt = await extractHwjsRt(vmlinuxModule); const signalRegistry = createSignalTargetRegistry(); const tree = { "/dev": { dir: true }, "/proc": { dir: true }, "/sys": { dir: true }, "/tmp": { dir: true }, "/cache": { dir: true }, "/bin": { dir: true }, "/etc": { dir: true }, "/lib": { dir: true }, "/opt": { dir: true }, "/opt/glr": { dir: true } }; let init; if (glr) { for (const f of m.files) { const parts = f.path.split("/"); for (let i = 2; i < parts.length; i++) { const d = parts.slice(0, i).join("/"); if (!tree[d]) tree[d] = { dir: true }; } tree[f.path] = { data: new Uint8Array(f.bytes), mode: f.mode || 420 }; } init = m.init; tree[init] = { data: new Uint8Array(m.initBytes), mode: 493 }; if (m.env) tree["/etc/h7.env"] = { data: new TextEncoder().encode(m.env), mode: 420 }; log("[boot] rootfs: " + init + " (" + m.initBytes.byteLength + " b) + " + m.files.length + " libs\n"); } else { init = "/guiinit"; tree["/guiinit"] = { data: new Uint8Array(m.guiBytes), mode: 493 }; log("[boot] rootfs ready (/guiinit " + m.guiBytes.byteLength + " b)\n"); } const fsView = createMemoryGuestRoot(tree); const spawnHandler = makeKernelSpawnHandler({ kernelMemory: ram.kernelMemory.buffer, ram, workerEntry: USER_WORKER, platform: "browser", signalRegistry, vmlinuxModule, kernelMemoryWasm: ram.kernelMemory, hwjsRtModule: hwjsRt.module, hwjsRtBytes: hwjsRt.bytes, hwjsRtProvenance: hwjsRt.provenance.raw, initArgv: [init, "-i"], initEnvp: ["PATH=/bin", "HOME=/", "TERM=xterm-256color", "PWD=/"], initLowFdRoutes: [0, 1, 2], onUserOutput: (fd, bytes) => { if (fd === 1 || fd === 2) log(bytes); } }); let hostTransport, onHostTransportReady; if (glr) { const canvas = m.canvas; const gl = canvas.getContext("webgl2", { antialias: false, preserveDrawingBuffer: true, alpha: false }); if (!gl) throw new Error("no WebGL2 context on the OffscreenCanvas"); log("[boot] WebGL2: " + gl.getParameter(gl.VERSION) + " / " + gl.getParameter(gl.RENDERER) + " canvas " + canvas.width + "x" + canvas.height + "\n"); let swaps = 0, t0 = 0; const dec2 = new GlRemoteDecoder({ gl: () => gl, requestFrame: typeof requestAnimationFrame === "function" ? (cb) => requestAnimationFrame(cb) : void 0, resize: (w, h) => { canvas.width = w; canvas.height = h; log("[glr] canvas " + w + "x" + h + "\n"); }, onSwap: () => { swaps++; self.postMessage({ kind: "swap", n: swaps, t: performance.now() }); }, onError: (e) => log("[glr] " + e.message + "\n") }); const report = (e) => log("[glr] " + (e && e.message || e) + "\n"); const glrHandler = makeHostTransportHandler(makeGlRemoteOps(dec2, report), report); hostTransport = { handler: (req) => req.objectId === INSP ? inspHandler(req) : glrHandler(req) }; onHostTransportReady = (t) => log("[boot] host transport granted\n"); } log("[boot] bootKernel starting...\n"); await bootKernel({ ram, vmlinuxModule, workerEntry: KERNEL_WORKER, platform: "browser", cmdline: "console=hvc0 loglevel=8 prestrike.rootfs=virtiofs prestrike.repo=local init=" + init, spawnHandler, signalRegistry, virtioFs: { fs: fsView }, ...glr ? { hostTransport, onHostTransportReady, virtioInput: { absolutePointer: true } } : { framebuffer: { width: 1600, height: 960 }, virtioInput: { absolutePointer: false } }, ...m.usb ? { usbHcd: { onEvent: (ev) => log("[usb-hcd] " + JSON.stringify(ev) + "\n") }, onUsbReady: (b) => { usbBackend = b; usbFilters = Array.isArray(m.usb) ? m.usb : null; log("[usb] host controller ready\n"); usbAttachAll(); } } : {}, watchdogMs: 0, onKernelLog: (lvl, text) => log(text), onDmesg: (lvl, text) => log(text), onInputReady: (fn2) => { inject = fn2; for (const b of pending.splice(0)) { for (const [t, c, v] of b.events) inject(t, c, v); inject(0, 0, 0); } log("[boot] input ready\n"); }, onFbWindow: (window) => { log("[boot] FB " + window.width + "x" + window.height + " stride " + window.stride + "\n"); self.postMessage({ kind: "fb", sab: ram.kernelMemory.buffer, window }); } }); log("[boot] bootKernel returned\n"); }