// ../../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]; } var WASM_DYLINK_MEM_INFO = 1; var WASM_DYLINK_NEEDED = 2; var WASM_DYLINK_EXPORT_INFO = 3; var WASM_DYLINK_IMPORT_INFO = 4; var WASM_SYMBOL_BINDING_MASK = 3; var WASM_SYMBOL_BINDING_WEAK = 1; var WASM_SYMBOL_TLS = 1024; var __sharedWasmSourceOk; function wasmSource(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(); } var __dynLoaderDecoder = new TextDecoder(); function decodeMaybeShared(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 = decodeMaybeShared(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(decodeMaybeShared(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 = decodeMaybeShared(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 = decodeMaybeShared(b.subarray(sp, sp + len)); sp += len; [len, sp] = readU32LEB(b, sp); const nm2 = decodeMaybeShared(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 = decodeMaybeShared(b.subarray(p, p + len)); p += len; [len, p] = readU32LEB(b, p); const fld = decodeMaybeShared(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 = decodeMaybeShared(b.subarray(p, p + len)); p += len; [len, p] = readU32LEB(b, p); fld = decodeMaybeShared(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 = decodeMaybeShared(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, decodeMaybeShared(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; } var importedFunctionNamesByModule = /* @__PURE__ */ new WeakMap(); function importedFunctionNamesOf(module, bytes) { let names = importedFunctionNamesByModule.get(module); if (names === void 0) { names = parseImportedFunctionNames(bytes); importedFunctionNamesByModule.set(module, names); } return names; } var moduleFactsByModule = /* @__PURE__ */ new WeakMap(); function moduleFactsOf(module) { let f = moduleFactsByModule.get(module); if (f === void 0) { f = /* @__PURE__ */ Object.create(null); moduleFactsByModule.set(module, f); } return f; } var moduleKeptByModule = /* @__PURE__ */ new WeakMap(); 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 }; } var PACKED_KINDS = ["function", "table", "memory", "global", "tag"]; 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; } var neededExportersRoot = { next: /* @__PURE__ */ new WeakMap(), maps: null }; 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 = decodeMaybeShared(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; } var LINK_FACTS_FORMAT = 1; var linkFactsStore = null; 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; } var DLSYM_RTLD_DEFAULT = 0; var DLSYM_RTLD_NEXT = 4294967295; var DLSYM_CALLER_IMPORTS = /* @__PURE__ */ new Set(["dlsym", "dlvsym"]); 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(live, recorded) { const seen = new Set((recorded || []).map(([n]) => n)); return live.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}`; } var 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" ]); 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 && decodeMaybeShared(b.subarray(q, q + len)) === "wasm.linux.soname") { return decodeMaybeShared(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; } var 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" ]); var NEEDED_STD_NAME = /^_Z(T[IVSTC]|G[VR]|Z|T[hv](n?[0-9]+_)+)?N?K?St/; 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 = decodeMaybeShared(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]; } var HWJS_RT_BRK_RESERVE = 1 * 1024 * 1024; var HWJS_RT_WINDOW_SIZE = 8 * 1024 * 1024; var HWJS_RT_PAGE = 4096; 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 = decodeMaybeShared(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; } var HWJS_RT_STACK_CARVE = 64 * 1024; var HWJS_ROOT_DATA = 1; var HWJS_ROOT_STACK = 2; var HWJS_ROOT_ARENA = 3; var HWJS_ROOT_RECORD_BYTES = 16; 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 dataSectionSegmentBytes(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 = retainedLibraryInfo(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 dataSectionSegmentBytes(b, p, secEnd); if (id === 0 && retained && size === RETAINED_DATA_BYTES - 2 && b[p] === RETAINED_DATA_NAME.length) { let q = p + 1, named = true; for (let i = 0; i < RETAINED_DATA_NAME.length; i++) { if (b[q + i] !== RETAINED_DATA_NAME.charCodeAt(i)) { named = false; break; } } q += RETAINED_DATA_NAME.length; if (named) return (b[q] | b[q + 1] << 8 | b[q + 2] << 16 | b[q + 3] << 24) >>> 0; } p = secEnd; } return 0; } var HWJS_LIBC_WINDOW_SIZE = 16 * 1024 * 1024; function deriveHwjsLibcWindowBase(wasmBytes) { return deriveHwjsRtWindowBase(wasmBytes) + HWJS_RT_WINDOW_SIZE >>> 0; } var 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 ]); var 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 ]); 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; } var SHA256_WASM_CHUNK = 1 << 18; 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 pages = 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, pages]), ...section2(7, [2, 1, 109, 2, 0, 1, 98, 0, 0]), ...section2(10, codeSec) ]); } var wasmSha256; 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; } var SHA256_ABC = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; var hostSha256; 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); } 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; 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 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); } } 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 tableWritesOfBytes(bytes) { if (!retainedLibraryInfo(bytes) || hasCodeSection(bytes)) return scanTableWrites(bytes); const p = bytes.length - RETAINED_MARKER_BYTES - TABLE_WRITES_BYTES; if (p < 8 || bytes[p] !== 0 || bytes[p + 1] !== TABLE_WRITES_BYTES - 2 || bytes[p + 2] !== TABLE_WRITES_NAME.length) return "unknown"; for (let i = 0; i < TABLE_WRITES_NAME.length; i++) { if (bytes[p + 3 + i] !== TABLE_WRITES_NAME.charCodeAt(i)) return "unknown"; } return TABLE_WRITES_CODES[bytes[p + 3 + TABLE_WRITES_NAME.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 = decodeMaybeShared(b.subarray(p, p + len)); p += len; [len, p] = readU32LEB(b, p); const fld = decodeMaybeShared(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 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 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; } function sharedLibWireLength(bytes) { const kept = retainedLibraryInfo(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 = retainedLibraryInfo(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 && !retainedLibraryInfo(prev.bytes)) prev.bytes = bytes; return prev; } var 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(); } }; 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" }; } var RT_DRIVE_ENTRY_OPS = /* @__PURE__ */ new Set(["__hwjs_drive", "__hwjs_drive_resume"]); 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); }; } var TERMINUS_HOOK = "__hwjs_uncaught_unwinding"; 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 (decodeMaybeShared(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(decodeMaybeShared(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}`; }); } var NEEDED_VIEW_IMPORT_MODULES = /* @__PURE__ */ new Set(["env", "GOT.func", "GOT.mem"]); 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 = 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 needed-list carrier is legal (a concatenated/tampered artifact; 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)" ); } 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 = decodeMaybeShared(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 = decodeMaybeShared(b.subarray(p, p + len)); p += len; [len, p] = readU32LEB(b, p); fld = decodeMaybeShared(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(decodeMaybeShared(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 = decodeMaybeShared(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, decodeMaybeShared(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"); } var SIDE_TLS_EXPORTS = Object.freeze( ["__tls_base", "__tls_size", "__tls_align", "__wasm_init_tls"] ); 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 }; } var MAIN_TLS_BRK_BYTES = 1 * 1024 * 1024; var MAIN_TLS_CARVE_BYTES = MAIN_TLS_BRK_BYTES >>> 1; 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)` ); } } var tableLedgers = /* @__PURE__ */ new WeakMap(); var TABLE_LEDGER_VERIFY = (globalThis.process?.env?.HWJS_TABLE_LEDGER_VERIFY || "") === "1"; 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).` ); }; } var tableIndexes = /* @__PURE__ */ new WeakMap(); var tableProtoSet = typeof WebAssembly === "object" ? WebAssembly.Table.prototype.set : void 0; var tableProtoGrow = typeof WebAssembly === "object" ? WebAssembly.Table.prototype.grow : void 0; function tableSet(table, idx, fn2) { tableProtoSet.call(table, idx, fn2); } function tableGrow(table, delta) { return tableProtoGrow.call(table, delta); } var slotAllocators = /* @__PURE__ */ new WeakMap(); 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; } }; } var planRegions = /* @__PURE__ */ new WeakMap(); var appendCounts = /* @__PURE__ */ new WeakMap(); 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}` ); } } var linkPlanReport = null; var linkPlanTold = /* @__PURE__ */ new Set(); 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); } var 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: "" }; 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(wasmSource(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 live = exports.__hwjs_drive_abi() | 0; if (live !== manifest.driveAbi) { throw new Error( `hwjs-dlopen: lying hwjs.abi manifest \u2014 manifest drive_abi=${manifest.driveAbi} but exports.__hwjs_drive_abi() returned ${live} (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; } var xmodDerivedSigs = /* @__PURE__ */ new Map(); 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; } var XMOD_MARSHAL_SECTION = "hwjs.xmod_marshal"; 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; } var XMOD_CONSULT_CACHE_PAGES = 4; var 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 ]); var 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 ]); var xmodConsultCacheModules = /* @__PURE__ */ new Map(); var xmodConsultCacheMemory = null; var xmodConsultGeneration = null; var xmodConsultGenerationValue = 1n; var xmodConsultMissed = false; var xmodConsultLastOwner = 0; function xmodConsultInvalidate() { if (xmodDerivedSigs.size > 0) xmodDerivedSigs.clear(); if (!xmodConsultMissed || !xmodConsultGeneration) return; xmodConsultMissed = false; xmodConsultGenerationValue += 1n; xmodConsultGeneration.value = xmodConsultGenerationValue; } var XMOD_CONSULT_GEN_IMPORT = "__hwjs_xmod_consult_gen"; 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); }; } var 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(); } }; var 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(); } }; 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 }; } var 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 ]); var neededCtorTrampolineModule = null; 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; } var DRIVE_DONE = 53406; var DRIVE_DONE_LIVE = 53407; var PARK_NONE = 0; var PARK_DLOPEN = 3; var PARK_RESCHED = 4; var PARK_PREEMPT = 6; 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; } var HEAP_REALM_BASE_KIB = 24 * 1024; var HEAP_INSTANCE_BASE_KIB = 16; var heapChargeWords = null; var heapChargeSlot = -1; var heapInstancesKiB = 0; var heapInstanceCosts = /* @__PURE__ */ new WeakMap(); var heapInstanceFinalizer = typeof FinalizationRegistry === "function" ? new FinalizationRegistry((kib) => { heapInstancesKiB -= kib; heapChargePublish(); }) : null; 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(); } var HEAP_COLLECT_PROBE_BYTES = 2 ** 35 - 65536; var heapIsNode = typeof process !== "undefined" && !!(process.versions && process.versions.node); 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; } // ../../linux-in-the-browser/hardwarejs/src/macrotask.mjs var HAVE_SET_IMMEDIATE = typeof setImmediate === "function"; var HAVE_MESSAGE_CHANNEL = typeof MessageChannel === "function"; var MACROTASK_TURN_KIND = HAVE_SET_IMMEDIATE ? "setImmediate" : HAVE_MESSAGE_CHANNEL ? "MessageChannel" : "setTimeout"; var MACROTASK_FAIRNESS_MS = 100; var fairnessLastMs = 0; var beltTurns = 0; var turns = 0; var macrotaskChannel = null; var macrotaskWaiters = []; var macrotaskPortRef = (p) => { if (typeof p.ref === "function") p.ref(); }; var macrotaskPortUnref = (p) => { if (typeof p.unref === "function") p.unref(); }; function portTurn() { if (macrotaskChannel === null) { const ch = new MessageChannel(); ch.port1.onmessage = () => { const resolve = macrotaskWaiters.shift(); if (resolve) resolve(); if (macrotaskWaiters.length === 0) macrotaskPortUnref(ch.port1); }; macrotaskPortUnref(ch.port1); macrotaskPortUnref(ch.port2); macrotaskChannel = ch; } return new Promise((resolve) => { if (macrotaskWaiters.length === 0) macrotaskPortRef(macrotaskChannel.port1); macrotaskWaiters.push(resolve); macrotaskChannel.port2.postMessage(0); }); } function macrotaskTurn() { turns++; if (MACROTASK_TURN_KIND === "setImmediate") { return new Promise((resolve) => { setImmediate(resolve); }); } if (MACROTASK_TURN_KIND !== "MessageChannel") { return new Promise((resolve) => { setTimeout(resolve, 0); }); } const turn = portTurn(); const now = Date.now(); if (now - fairnessLastMs < MACROTASK_FAIRNESS_MS) return turn; fairnessLastMs = now; beltTurns++; return turn.then(() => new Promise((resolve) => { setTimeout(resolve, 0); })); } // ../../linux-in-the-browser/hardwarejs/src/preemptTimer.mjs var PREEMPT_WORD_BYTES = 12; var PT = Object.freeze({ ACTIVE: 0, HEADER: 4, STRIDE: 4, TOKEN: 0, SLICE_US: 1, GEN: 2 }); var PT_CLOCK_F64 = 1; var PT_SLOTS = 512; var TICK_MS = 1; var TICKS_PER_TURN = 8; var IDLE_WAIT_MS = 1e3; 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, nowMs) { 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] = nowMs; state.fired[s] = 0; } if (state.fired[s]) continue; const token = Atomics.load(ctl, b + PT.TOKEN); if (token === 0) continue; if ((nowMs - 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(); } } var preemptViews = /* @__PURE__ */ new Map(); function preemptAddPort(port) { port.onmessage = (ev) => preemptPortMessage(preemptViews, ev.data); } // ../../linux-in-the-browser/hardwarejs/src/hwjsTcb.mjs var HWJS_TCB_ABI = 1; var 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 }); var TCB_STATE = Object.freeze({ FREE: 0, LIVE: 1 }); function hasTcbRuntime(exports) { return !!exports && typeof exports.__hwjs_tcb_field === "function" && typeof exports.__hwjs_tcb_bind === "function" && typeof exports.__hwjs_thread_attach === "function"; } var 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."; 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 }; } var TCB_EBUSY = 16; var TCB_ERESTART = 517; var tcbRetryable = (errno) => errno === TCB_EBUSY || errno === TCB_ERESTART; 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; } // ../../linux-in-the-browser/hardwarejs/src/uaccessBoundary.mjs var UACCESS_LEAF_IMPORTS = Object.freeze([ "raw_copy_to_user", "raw_copy_from_user", "raw_clear_user" ]); var PARKING_IMPORT_NAMESPACE = "hwjs_suspend"; function auditVmlinuxSingleMemory(module) { const problems = []; let memoryImports = 0; for (const imp of WebAssembly.Module.imports(module)) { if (imp.kind === "memory") { memoryImports++; if (!(imp.module === "env" && imp.name === "kernel_memory")) { problems.push( `vmlinux imports memory ${imp.module}.${imp.name} \u2014 the kernel is a SINGLE-memory module now (only env.kernel_memory). A stale multi-memory vmlinux.wasm (the deleted env.user_memory splice) cannot boot on this host: rebuild the kernel (uaccess is host-serviced via linux.raw_copy_*_user; multi-memory is also what WebKit/iPadOS rejects \u2014 litb#68).` ); } } if (imp.module === PARKING_IMPORT_NAMESPACE && UACCESS_LEAF_IMPORTS.includes(imp.name)) { problems.push( `vmlinux declares kernel-memory service import '${imp.name}' in parking namespace '${PARKING_IMPORT_NAMESPACE}' \u2014 the uaccess crossing would be a coroutine suspend boundary by construction, which is the silently-catastrophic wiring the leaf witness exists to refuse (PLAN-THREADS-SINGLE-MEMORY \xA75 R1).` ); } } if (memoryImports > 1) { problems.push( `vmlinux imports ${memoryImports} memories \u2014 exactly one (env.kernel_memory) is the single-memory contract.` ); } return problems; } function makeUaccessLeafBoundary(opts) { const { userMemory, kernelMemory, refuse: refuse2, context, redPark } = opts; if (typeof refuse2 !== "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) { refuse2( `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) => { refuse2( `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) => { refuse2(`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) { refuse2( `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) { refuse2( `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 }; } // ../../linux-in-the-browser/hardwarejs/src/uaccessCopies.mjs var leb = (n) => { const o = []; do { let b = n & 127; n >>>= 7; if (n) b |= 128; o.push(b); } while (n); return o; }; var name = (s) => [...leb(s.length), ...[...s].map((c) => c.charCodeAt(0))]; var section = (id, body) => [id, ...leb(body.length), ...body]; var vec = (items) => [...leb(items.length), ...items.flat()]; var code = (ops) => [...leb(ops.length + 2), 0, ...ops, 11]; var header = [0, 97, 115, 109, 1, 0, 0, 0]; var I32 = 127; var fn = (params, results) => [96, ...vec(params.map((t) => [t])), ...vec(results.map((t) => [t]))]; var T_COPY = 0; var T_CLEAR = 1; var T_PAGES = 2; var TYPES = section(1, vec([fn([I32, I32, I32], [I32]), fn([I32, I32], [I32]), fn([], [I32])])); var get = (i) => [32, i]; var MEM_USER = 0; var MEM_KERNEL = 1; var 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 */ ]; var orNotCopied = (n, body) => [4, I32, ...get(n), 5, ...body, 65, 0, 11]; var 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]) ])) ]); var door = (i, type, args) => code([...args.flatMap((a) => get(a)), 65, i, 17, type, 0]); var 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])])) ]); var 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])])) ]); var fillModule; var fillByMemory = /* @__PURE__ */ new WeakMap(); 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); } var copiesModule; var doorModule; 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; } var copiesByUser = /* @__PURE__ */ new WeakMap(); 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); } }; } // ../../linux-in-the-browser/hardwarejs/src/wasmJit.mjs var SYS_WASM_JIT = 1031; var WASM_JIT_PROBE = 0; var WASM_JIT_INSTALL = 1; var WASM_JIT_RESET = 2; var WASM_JIT_ERROR = 3; var WASM_JIT_REGISTER_HELPERS = 4; var WASM_JIT_EVICT = 5; var WASM_JIT_ABI = 2; var WASM_JIT_MAX_MODULE_BYTES = 4 << 20; var WASM_JIT_MAX_LIVE_SLOTS = 65536; var WASM_JIT_MAX_LIVE_BYTES = 64 << 20; var WASM_JIT_MAX_FUNCS = 256; var WASM_JIT_MAX_HELPERS = 64; var WASM_JIT_MAX_LIVE_INSTALLS = 4096; var WASM_JIT_MAX_LIVE_FUNCS = WASM_JIT_MAX_LIVE_SLOTS; var WASM_JIT_MAX_TABLE = 1 << 20; var WASM_JIT_MAX_TYPES = 16; var WASM_JIT_MAX_NESTING = 1024; var WASM_JIT_MAX_LOCALS = 256; var WASM_JIT_MAX_LIVE_INSTRS = 20 << 16; var WASM_JIT_INSTALL_INSTRS = 112; var WASM_JIT_FUNC_INSTRS = 6; var WASM_JIT_BYTES_PER_INSTR = 112; var WASM_JIT_MAX_FUNC_INSTRS = 1024; var WASM_JIT_MAX_HELPER_PARAMS = 8; var WASM_JIT_PROBE_INFO_BYTES = 56; var WASM_JIT_FEATURE_RETURN_CALL = 1; var WASM_JIT_FEATURE_SIMD128 = 2; var WASM_JIT_FEATURE_EVICT = 4; var WASM_JIT_LOG_CAP = 16; var WASM_JIT_ENTRY_SIG = "(i32,i32,f32)->i32"; var SIG_ENTRY = Uint8Array.of(96, 3, 127, 127, 125, 1, 127); var SIG_EMPTY = Uint8Array.of(96, 0, 0); var WASM_JIT_TABLE_IMPORT = "__wasm_jit_table"; var WASM_JIT_NATIVE_SECTION = "llvm.func_attr.annotate.hwjs.native.v1"; var EPERM = 1; var E2BIG = 7; var ENOEXEC = 8; var ENOMEM = 12; var EFAULT = 14; var EINVAL = 22; var ENOSPC = 28; var ENOTSUP = 95; var ESTALE = 116; var ERRNO_NAME = { [EPERM]: "EPERM", [E2BIG]: "E2BIG", [ENOEXEC]: "ENOEXEC", [ENOMEM]: "ENOMEM", [EFAULT]: "EFAULT", [EINVAL]: "EINVAL", [ENOSPC]: "ENOSPC", [ENOTSUP]: "ENOTSUP", [ESTALE]: "ESTALE" }; var OP_NAME = ["PROBE", "INSTALL", "RESET", "ERROR", "REGISTER_HELPERS", "EVICT"]; var ALLOWED_SECTIONS = /* @__PURE__ */ new Set([0, 1, 2, 3, 7, 10]); var SECTION_NAME = [ "custom", "type", "import", "function", "table", "memory", "global", "export", "start", "element", "code", "data", "datacount", "tag" ]; var KIND_NAME = ["function", "table", "memory", "global", "tag"]; var 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" }; var 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" }; var EPOCH_SEQ_LIMIT = 1 << 23; var epochTag = -1; var epochSeq = 0; 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 }; } var 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 ); var 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 ); var featureBits = -1; 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); } var ENGINE_TEXT_CAP = 240; var UNSAFE_CHARS = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/g; 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")}`; }); } var errText = (e) => wasmJitCleanText(e instanceof Error ? e.message : String(e)); var UTF8 = new TextDecoder("utf-8", { fatal: true }); var Malformed = class extends Error { }; var Refused = class extends Error { constructor(errno, text) { super(text); this.errno = errno; } }; var 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; } }; 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; } var lebLen = (v) => v < 128 ? 1 : v < 16384 ? 2 : v < 2097152 ? 3 : v < 268435456 ? 4 : 5; 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; } var K_BAD = 0; var K_NONE = 1; var K_BLOCK = 2; var K_U32 = 3; var K_BRTABLE = 4; var K_CALLIND = 5; var K_MEMARG = 6; var K_MEMIDX = 7; var K_LEB = 8; var K_F32 = 9; var K_F64 = 10; var K_SELT = 11; var K_FC = 12; var K_FD = 13; var K_FE = 14; var K_HEAPTYPE = 15; var K_TRYTABLE = 16; var K_END = 17; var 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; var 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"; var R_TABLE = "table access: the process table and the JIT table are written by the host only"; var R_REF = "function references: generated code calls only through call_indirect on the JIT table"; var 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"]] ]); var R_SEG = "segment ops: generated modules carry no data or element segments"; var 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]] ]); var 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 ]); var R_ATOMIC_WAIT = "blocks the OS thread outside the coroutine protocol: every task on this Worker stalls"; var 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]] ]); var RV = 0; 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; } var malformed = (fn2, pos) => new Malformed(`function ${fn2}: instruction at byte ${pos} runs past its body`); var tooDeep = (fn2, pos, depth, max) => new Refused(E2BIG, `function ${fn2}, byte ${pos}: blocks nest ${depth} deep > ${max}`); var pastEnd = (fn2, pos) => new Malformed(`function ${fn2}: instruction at byte ${pos} follows the body's final end`); var DEPTH = 0; function openBlock(max) { return ++DEPTH > max; } var TARGETS = 0; 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; } var tooLong = (fn2, pos, n, max) => new Refused(E2BIG, `function ${fn2}, byte ${pos}: ${n} instructions > ${max} per function (br_table targets count one each)`); var unknownOp = (fn2, at, what) => new Refused(EPERM, `function ${fn2}, byte ${at}: unknown opcode ${what} (the scan refuses what it does not know)`); var defaultDeny = (fn2, at, name2, why) => { throw new Refused(EPERM, `function ${fn2}, byte ${at}: ${name2} is not allowed (${why})`); }; var INSTRS = 0; 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; } var 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 */ ]; var WARM_CODE = Uint8Array.from([1, ...uleb32(WARM_BODY.length + 3), 1, 2, 123, ...WARM_BODY]); function uleb32(n) { const out = []; do { let x = n & 127; n >>>= 7; if (n) x |= 128; out.push(x); } while (n); return out; } var scanWarm = false; function warmScanner() { scanWarm = true; for (let i = 0; i < 2; i++) scanWasmJitCode(WARM_CODE, 0, WARM_CODE.length); } var imageFactsCache = /* @__PURE__ */ new WeakMap(); 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; } var imageSnapshots = /* @__PURE__ */ new WeakMap(); 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 ""; } var slotPools = /* @__PURE__ */ new WeakMap(); 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, 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 { log(line); } catch (_e) { } } function refuse2(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 refuse2(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 refuse2(op, e.errno, e.message); if (e instanceof Malformed) return refuse2(op, ENOEXEC, `malformed module: ${e.message}`); return refuse2(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 refuse2(WASM_JIT_PROBE, EINVAL, `info len ${len} < ${WASM_JIT_PROBE_INFO_BYTES}`); } if (!inMemory(info, WASM_JIT_PROBE_INFO_BYTES)) { return refuse2(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 refuse2(op, EINVAL, "n = 0 helpers"); if (n > WASM_JIT_MAX_HELPERS) return refuse2(op, E2BIG, `n = ${n} helpers > ${WASM_JIT_MAX_HELPERS}`); if (!inMemory(ptr, n * 4)) { return refuse2(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 refuse2(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 refuse2(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 refuse2(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 refuse2(op, EFAULT, `module 0x${ptr.toString(16)}+${len} is outside user memory (${memBytes} bytes)`); } if (!inMemory(slotsPtr, cap * 4)) { return refuse2(op, EFAULT, `slots 0x${slotsPtr.toString(16)}+${cap}*4 is outside user memory (${memBytes} bytes)`); } if (len > WASM_JIT_MAX_MODULE_BYTES) { return refuse2(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 refuse2(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 refuse2(op, EINVAL, "the module exports nothing; INSTALL needs f0..f(n-1)"); if (n > cap) return refuse2(op, EINVAL, `the module exports ${n} functions; slots[] holds cap=${cap}`); if (rec.liveSlots + n > WASM_JIT_MAX_LIVE_SLOTS) { return refuse2(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 refuse2(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 refuse2(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 refuse2(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 refuse2(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 refuse2(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 refuse2(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 ? refuse2(op, ENOEXEC, `CompileError: ${errText(e)}`) : refuse2(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 refuse2(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 refuse2(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 refuse2(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 ? refuse2(op, ENOEXEC, `LinkError: ${errText(e)}`) : refuse2(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 refuse2(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 refuse2(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 refuse2(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 refuse2(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 refuse2(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 refuse2(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 refuse2(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 live = []; 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) live.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 = live; 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}`); } } } // ../../linux-in-the-browser/hardwarejs/src/capsummaryRegistry.mjs var CAPSUMMARY_RECORD_VERSION = 1; var CAPSUMMARY_MAX_RECORDS = 16384; var CAPSUMMARY_MAX_TARGETS = 1 << 20; var MASK64 = (1n << 64n) - 1n; 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); } var bit = (bits, arg) => (bits & 1n << BigInt(arg)) !== 0n; 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 }; } }; } // ../../linux-in-the-browser/hardwarejs/src/pause.mjs var WAIT_BOUND_MS = 200; var TIMER_FALLBACK_MS = 50; 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)); } } } // ../../linux-in-the-browser/hardwarejs/src/violationWitness.mjs var VIOLATION_BUF_STRIDE = 512; var VIOLATION_LANE_CEILING = 2048; var VIOLATION_PREFIXES = ["hwjs-user-rt VIOLATION", "hwjs-rt VIOLATION"]; 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")}`; } // ../../linux-in-the-browser/hardwarejs/src/worker.mjs var SIGNAL_REGION_BYTES = 40; var 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 }; var REQUEST = 1; var RESPONSE = 2; var IDLE = 0; var CTRL_I32_REAPED = 15; var SYS_EXIT = 60; var SYS_EXIT_GROUP = 231; var SYS_CLONE = 56; var SYS_SCHED_SETAFFINITY = 203; var SYS_WASM_DLOPEN = 1040; var SYS_WASM_DLSYM = 1041; var SYS_WASM_DLCLOSE = 1042; var HWJS_DLOPEN_REISSUE = 1; var SYS_WASM_DLERROR = 1043; var SYS_WASM_DLOPEN_LOADED = 1050; var SYS_WASM_DLADDR = 1051; var SYS_WASM_EXEC_LOAD_BEGIN = 1044; var SYS_WASM_EXEC_LOAD_STEP = 1045; var WASM_EXEC_HOST_KEEPS_ARGV0 = 1; var WASM_EXEC_PREFIX_KEEPS_ARGV0 = 1; var EXEC_LOAD_HOST_FLAGS = WASM_EXEC_HOST_KEEPS_ARGV0; function decodeExecArgvPrefix(bytes, argc, flags, requested) { const dec = new TextDecoder(); const argv = []; let start = 0; for (let i = 0; i < bytes.length; i++) { if (bytes[i] === 0) { argv.push(dec.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)]; } var SYS_WASM_LIBC_STAGE = 1046; var SYS_WASM_DLOPEN_LOAD = 1047; var SYS_WASM_NEEDED_STAGE = 1048; var SYS_WASM_ROOT_MAP = 1049; var HWJS_ERESTART_RESCHED = -517; var HWJS_ERESTARTNOINTR = -513; var replaysModuleGraph = (mode) => mode === "fork-resume" || mode === "thread" || mode === "migrate-resume"; var MIG_OFFERED = 0; var MIG_CLAIMED = 1; var MIG_BOUND = 2; var MIG_ABORTED = 3; var MIG_COMMIT_MS = 1e4; var MIG_PLACE_MS = 3e3; var MIG_ABORT_TIMEOUT = 1; var MIG_ABORT_NO_LANE = 2; var MIG_ABORT_BIND = 3; var MIG_ABORT_HOST = 4; var MIG_ABORT_UNCLAIMED = 5; 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; } } } var SYS_WASM_EXIT_BY_SIGNAL = 1027; var SYS_WASM_SIGCONSUME = 1028; var SYS_WASM_SETJMP = 1029; var SYS_WASM_LONGJMP = 1030; var execImageResolver = null; function setExecImageResolver(fn2) { execImageResolver = fn2; } var __utf8Decoder = new TextDecoder("utf-8", { fatal: false }); var SGSEG_SIZE = 8; 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_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(kernelBuffer, off, listBytes); const segs = []; let sum = 0; for (let i = 0; i < n; i++) { const sOff = dv.getUint32(i * SGSEG_SIZE, true) >>> 0; const sLen = dv.getUint32(i * SGSEG_SIZE + 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; } var sharedWasmSourceOk; 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 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 decodeMaybeShared2(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 }); } var cpuWorker = null; var laneResidents = /* @__PURE__ */ new Set(); var laneRecByInit = /* @__PURE__ */ new WeakMap(); var laneInboxI32 = null; 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()); } var preemptCtlI32 = null; var preemptPort = null; var preemptSlotBase = 0; var preemptSliceMax = 0; var preemptClock = null; var preemptTokenSeq = 0; var preemptSlot = 0; var preemptWarned = false; 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; } var 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; })(); var 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; })(); var PREEMPT_SLICE_MERGED_US = 1e3; function preemptUnregister(token) { if (token !== 0 && preemptPort !== null) { try { preemptPort.postMessage({ t: "unreg", token }); } catch (_e) { } } } var workerSharedLibs = /* @__PURE__ */ new Map(); var sharedLibPaths = /* @__PURE__ */ new Map(); var neededSubstitutes = /* @__PURE__ */ new Map(); var neededSurfaces = /* @__PURE__ */ new Map(); var neededSubstituteNoted = /* @__PURE__ */ new Set(); var threadPlacementProviders = /* @__PURE__ */ new Map(); var dlPlacementPulls = /* @__PURE__ */ new Map(); var dlPlacementPullSeq = 1; var DL_PLACEMENT_PULL_TRIES = 3; var heapStatsFn = null; var heapGuardNoted = false; var 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) { } })(); var HEAP_TRACE = !!globalThis.process?.env?.HWJS_HEAP_TRACE; var heapSnapshotTaken = false; 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) { } } } } var HEAP_GUARD_MAX_MARGIN = 512 * 1024 * 1024; 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) { } } } var HEAP_COLLECT_DELAY_MS = 200; var HEAP_COLLECT_MIN_GAP_MS = 1e3; var HEAP_COLLECT_PERIOD_MS = 5e3; var heapCollectTimer = null; var heapCollectLast = 0; 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) { } } var HWJS_EXIT_UNWIND = { hwjsExitUnwind: true }; var HWJS_REAPED_UNWIND = { hwjsReapedUnwind: true }; 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(); } } var HWJS_EXEC_UNWIND = { hwjsExecUnwind: true }; function isDesignedUnwind(e) { return e === HWJS_EXIT_UNWIND || e === HWJS_EXEC_UNWIND || e === HWJS_REAPED_UNWIND || e === HWJS_TASK_REAPED; } var HWJS_TASK_REAPED = { hwjsTaskReaped: true }; var reapableTasks = /* @__PURE__ */ new Map(); 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, onTerminate, callHostSync }) { workerHostPost = post; workerHostSyncCall = typeof callHostSync === "function" ? callHostSync : null; onTerminate?.(() => { cpuWorker?.stop?.(); }); onMessage(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) }); } }); } var processVmlinuxInstanceCount = 0; var 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; })(); var 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; })(); var 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; })(); var 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; })(); var 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); })(); var HWJS_BREATH_ADAPT = HWJS_BREATH_SLICE_US > 0 && HWJS_SP_REFILL_MAX > HWJS_SP_REFILL; var HWJS_BREATH_BESIDE = !(typeof process !== "undefined" && process.env.HWJS_BREATH_BESIDE === "0"); var BREATH_TARGET_MS = HWJS_BREATH_SLICE_US / 1e3; var BREATH_LONG_MS = BREATH_TARGET_MS * 2.5; var BREATH_SHARE_FRAC = 0.5; var BREATH_COST_HALF_MS = 50; 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, nowMs, 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 - nowMs) * frac; if (!(d > 0)) return 0; if (d < h) h = d; } return h; } var HWJS_PARK_PREEMPT = 6; 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." ); } var HWJS_NO_SP_YIELD = typeof process !== "undefined" && !!process.env.HWJS_NO_SP_YIELD; var 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; })(); var 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; })(); var HWJS_BREATH_CENSUS = typeof process !== "undefined" && process.env.HWJS_BREATH_CENSUS === "1"; var HWJS_SCHED_YIELD_ALWAYS = typeof process !== "undefined" && process.env.HWJS_SCHED_YIELD_ALWAYS === "1"; var HWJS_ACCT_DBG = typeof process !== "undefined" && !!process.env.HWJS_ACCT_DBG; var HWJS_XMOD_CONSULT_TRACE = globalThis.process?.env?.HWJS_XMOD_CONSULT_TRACE === "1"; var HWJS_XMOD_CONSULT_CACHE = globalThis.process?.env?.HWJS_XMOD_CONSULT_CACHE !== "0"; var HWJS_XMOD_CONSULT_STATS = globalThis.process?.env?.HWJS_XMOD_CONSULT_STATS === "1"; var HWJS_FPCAST_TRACE = globalThis.process?.env?.HWJS_FPCAST_TRACE === "1"; var HWJS_FPCAST_VERSION = 1; var HWJS_NO_RECLAIM_RETRY = typeof process !== "undefined" && !!process.env.HWJS_NO_RECLAIM_RETRY; var 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; })(); var HWJS_RECLAIM_SETTLE_MS = [50, 500, 2e3]; var 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; var 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; var 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; })(); var THR_TRACE = typeof process !== "undefined" && !!process.env.HWJS_THR_TRACE; var SCHED_TRACE = typeof process !== "undefined" && !!process.env?.HWJS_WORKER_SCHED_TRACE; var 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; })(); var 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; })(); var HOST_PERF = typeof performance !== "undefined" && typeof performance.now === "function" ? performance : null; var HOST_TIME_ORIGIN = HOST_PERF !== null && typeof HOST_PERF.timeOrigin === "number" ? HOST_PERF.timeOrigin : null; var schedNow = HOST_PERF !== null ? () => HOST_PERF.now() : () => Date.now(); function schedTrace(post, text) { if (!SCHED_TRACE) return; try { post({ kind: "dmesg", level: 6, text: `hwjs-schedtrace t=${schedNow().toFixed(1)} ${text}` }); } catch (_e) { } } var WORKER_STALL_THRESHOLD_MS = 1e3; 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 }) }; } var HOLD_REPORT_OFF = { tick() { }, end() { }, holds: () => 0 }; 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 nowMs = schedNow(); if (nowMs < next) return; next = nowMs + SCHED_TRACE_HOLD_MS; holds++; if (!announced) { announced = true; schedTrace(post, `DRIVE-ENTER ${head}`); } schedTrace(post, `HOLD ${head} #${holds} held=${(nowMs - 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}`); } }; } var HWJS_LANE_WOULD_BLOCK = -517; var WASM32_PARK_CONSUMER_NONE = 0; var WASM32_PARK_CONSUMER_HOST = 2; var HWJS_LANE_RESIDUE_CEILING = 65536; 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 dispatchSyscall(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, 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) { } } var rt4ByKernel = /* @__PURE__ */ new WeakMap(); var workerKernels = /* @__PURE__ */ new WeakMap(); var workerKernelsNoMemory = {}; 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; } var KERNEL_IMPORT_ARGS_MAX = 6; 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 pending = lanes.get(key); if (!pending) { 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; } pending = instantiateWorkerKernel(key, init, post, task); lanes.set(key, pending); pending.then((c) => { if (!c && lanes.get(key) === pending) lanes.delete(key); }); } const cpu = await pending; 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; } var threadImageContexts = /* @__PURE__ */ new Map(); var wasmJitMemories = makeWasmJitMemoryLedger(); var THREAD_IMAGE_SHARING = (globalThis.process?.env?.HWJS_THREAD_IMAGE_PRIVATE || "") !== "1"; var threadViewRaw = /* @__PURE__ */ new WeakMap(); var THREAD_SHAPE_PER_THREAD_FIELDS = /* @__PURE__ */ new Set(["tlsBase", "live"]); 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 td = 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 = td.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 pages = kernPagesOf(); if (pages === kernI32Pages) return kernI32View; kernI32Pages = pages; } 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(); } } var HWJS_EMMAP_PARKED = -540; var isRestartValue = (r) => r <= -512 && r >= -517 && r !== -515; function execStageRefusalErrno(err) { const e = err !== null && typeof err === "object" ? err.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 = (err, parked, lost) => ({ done, err, 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 same = k.mfd === req.mfd && k.len === req.len && k.prot === req.prot && k.flags === req.flags && k.off === req.off && k.epoch === epoch(); if (same) { 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; } }; } var FMG_BUCKET_END = 2 + 1024; var FMG_LOG_HEAD = FMG_BUCKET_END; var FMG_LOG_IDS = FMG_BUCKET_END + 1; var FMG_LOG_BASE = FMG_BUCKET_END + 2; var FMG_LOG_SLOTS = 512; var FMG_LOG_STRIDE = 8; var FMG_WATCH_BASE = FMG_LOG_BASE + FMG_LOG_SLOTS * FMG_LOG_STRIDE; var FILE_MAP_GEN_WORDS = FMG_WATCH_BASE + (FMG_BUCKET_END - 2); var FMG_LIVE = 0; var FMG_ALL = 1; var FMG_LOG_MAX_PER_PUBLISH = 16; var TMPFS_MAGIC = 16914836; var RAMFS_MAGIC = 2240043254; var DRM_MAJOR = 226; var WASMDRM_GEM_PWRITE = 1075340352; var WASMDRM_GEM_PREAD = 1075340353; 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); } var 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] ]); var 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 ]); 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 = () => { } }) { 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) log(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) => { log(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, pages) => { if (!logOn || pages.length === 0) return; const i0 = Atomics.add(gen, FMG_LOG_HEAD, pages.length); for (let j = 0; j < pages.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, pages[j][0]); Atomics.store(gen, b + 4, pages[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 pages = []; 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; log(3, `writable MAP_SHARED publish to fd=${e.file.fd} at 0x${pos.toString(16)} failed: errno ${-r}`); } continue; } pages.push([Math.floor(pos / 4096), Math.ceil((pos + len) / 4096)]); } } finally { if (pages.length > 0) { let rs = mergeRanges(pages); 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) log(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; } var TASK_STATE_OFF = 12; 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; }); } var SIGPEND_I32_PENDING_LO = 0; var SIGPEND_I32_WAKE_WORD = 2; var SIGPEND_I32_SIGCHLD_DELIVERY_SEQ = 6; var SIGCHLD_PENDING_BIT_LO = 1 << 17 - 1; 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 }; } var SIGKILL_PENDING_BIT_LO = 1 << 9 - 1; 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; } var HOST_ANSWERED = /* @__PURE__ */ new Set([ 9, 10, 11, 12, 24, 26, 60, 231 ]); var WASM_SYSCALL_NR_MAX = 1200; var HOST_ANSWERS_NR = new Uint8Array(WASM_SYSCALL_NR_MAX); for (const nr of HOST_ANSWERED) HOST_ANSWERS_NR[nr] = 1; var 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. */ ]); var SYS_ENV_KNOB = /^(HWJS_RED_|HWJS_EXPERIMENTAL_|A4C_)/; 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(nowMs) { return breathRefillFor( breathCostHi > breathCostPrev ? breathCostHi : breathCostPrev, othersSliceHorizonIn( laneResidents, laneRec, nowMs, 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(decodeMaybeShared2(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 mib = (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 (${mib(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) ~${mib(reclaimStats.livePages)} MiB in size, ${reclaimStats.zombieCount} exited-but-uncollected SAB(s) ~${mib(reclaimStats.zombiePages)} MiB awaiting GC, kernel SAB ${mib(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 (${mib(minPages)} MiB) user_memory minimum but this process's Memory holds ${curPages} pages (${mib(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 enc = new TextEncoder().encode(`${message} `).subarray(0, 4096); new Uint8Array(init.memory.buffer).set(enc, s.scratch); s.scratchFor = ""; syscall(1, 2, s.scratch, enc.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 enc = new TextEncoder().encode(path); if (enc.length >= 4096) { rc = -36; break; } if (s.scratchFor !== path) { const u8 = new Uint8Array(init.memory.buffer); u8.set(enc, s.scratch); u8[s.scratch + enc.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 = retainedLibraryBytes(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 = retainedLibraryInfo(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 pending = 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 (pending.length === 0) { return servicePreloadStage(imageBytes, info.needed, context, yieldWouldBlock); } name2 = pending[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 = decodeMaybeShared2(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 = decodeMaybeShared2(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 = retainedLibraryBytes(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 enc = new TextEncoder().encode(path); if (enc.length >= 4096) continue; if (s.scratchFor !== path) { const u8 = new Uint8Array(init.memory.buffer); u8.set(enc, s.scratch); u8[s.scratch + enc.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 enc = new TextEncoder().encode(`${line} `).subarray(0, 4096); new Uint8Array(init.memory.buffer).set(enc, a >>> 0); syscall(1, 2, a >>> 0, enc.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 decodeMaybeShared2(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, live = c.live; const verdict = xmodConsultVerdict({ inDead: !!dead, inFootprint: !!live, inElem: c.inElem, hasRec: c.hasRec, recOtherSig: c.recOtherSig, recAny: c.recAny, regRan: c.regRan, fromMain, fromRt, marshal }); if (verdict === 2) { const where = live ? `"${live.path}" (moduleId=${live.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 "${live.path}" (moduleId=${live.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 ? retainedLibraryInfo(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 enc = new TextEncoder().encode(path); const u8 = new Uint8Array(init.memory.buffer); u8.set(enc, p.scratch); u8[p.scratch + enc.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 decodeMaybeShared2(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 pages = _uPagesOf(); if (pages === _uPages) return; _uPages = pages; } 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 nowMs = Date.now(); const deadlineMs = rec ? rec.deadlineMs : timeout_ms === Infinity ? Infinity : nowMs + timeout_ms; if (nowMs >= 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(nowMs) { 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 + nowMs) preemptClock[PT_CLOCK_F64] = HOST_TIME_ORIGIN + nowMs; 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 pending = acctT0 - acctSliceT0 - acctSliceSyscallMs - acctSettledMs; if (pending >= ACCT_SETTLE_MS) { acctReportUser(pending); acctSettledMs += pending; } } 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 pages = filePagesMain + of(hwjsRtHandle) + of(libcSoHandle); for (const e of neededSoHandles) if (e) pages += of(e.handle); for (const m of dlopenModules.values()) if (m && !m.mainScope) pages += of(m.handle); if (pages !== filePagesPublished) { Atomics.store(kernelI32Live(), filePagesWord, pages); filePagesPublished = pages; } } 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 = decodeMaybeShared2(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 refuse2 = (err, 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 ${-err} (linux-in-the-browser#72)` }); } catch (_e) { } return err | 0; }; if (mfd === -1) return refuse2(-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 refuse2( -19, "no in-Worker kernel context to populate from the file" ); if ((flags & 16) !== 0) return refuse2( -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 refuse2(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 refuse2( -19, `GEM_PREAD population failed (errno ${-preadErr})` ); if (preadErr === -38) return refuse2( -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 : refuse2(-13, "fd not open for reading"); } if (preadErr === -29 || preadErr === -21 || preadErr === -22) return refuse2( -19, `fd does not support positioned read (pread errno ${-preadErr})` ); return refuse2(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 refuse2(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 same = 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 (!same) { 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 enc = new TextEncoder(); const strBufs = [...argvArr, ...envpArr].map((s) => enc.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 refuse2 = (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) refuse2("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) refuse2("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") refuse2("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) refuse2("the terminus chain parked but its adopted top is DONE (park protocol breach)"); return exp.__hwjs_drive_adopt_parked() >>> 0; } refuse2(`__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(); refuse2("longjmp target not found (dead, stale, or foreign jmp_buf) and no __hwjs_status_longjmp_lost export to report it faithfully"); } refuse2("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 live = 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 (live !== 0) { post({ kind: "user-report", pid: init.pid, message: `thread block 0x${(currentTcb >>> 0).toString(16)} terminus with ${live} 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) }; } } var USER_MODULE_CACHE_MAX = 8; var userModuleCache = /* @__PURE__ */ new Map(); var userModuleCompiles = 0; var userModuleCacheHits = 0; var userModuleHostAdopted = 0; var hostUserModules = /* @__PURE__ */ new Map(); var workerHostPost = null; var workerHostSyncCall = null; var MERGED_DMESG_STALL_MS = 1e3; var dmesgTurnPending = false; var dmesgTurnArmedMs = 0; var dmesgSyncNoted = false; 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(wasmSource2(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 }; } var SO_MODULE_CACHE_MAX = 8; var soModuleCompiles = 0; var soModuleCacheHits = 0; var soModuleCompiledWireBytes = 0; var soModulesLive = 0; var soModuleFinalizer = typeof FinalizationRegistry === "function" ? new FinalizationRegistry(() => { soModulesLive = Math.max(0, soModulesLive - 1); }) : null; 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)}`; } var soModuleCache = new SoModuleCache(SO_MODULE_CACHE_MAX, soModuleCacheKey); 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 = retainedLibraryInfo(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(wasmSource2(bytes)); soModuleCompiles++; soModuleCompiledWireBytes += bytes.length; if (soModuleFinalizer) { soModulesLive++; soModuleFinalizer.register(module, key); } if (found) soModuleCache.add(found.id, module); return { module, key, cached: false }; } var LINK_PLAN_ENV = typeof process !== "undefined" && process.env || {}; var LINK_PLAN_ON = LINK_PLAN_ENV.HWJS_LINK_PLAN !== "0"; var LINK_PLAN_CHECK = LINK_PLAN_ENV.HWJS_LINK_PLAN_CHECK === "1"; var LINK_PLAN_TRACE = LINK_PLAN_ENV.HWJS_LINK_PLAN_TRACE === "1"; if (LINK_PLAN_TRACE) linkPlanStats.traceForget = true; function linkPlanOpts() { if (!LINK_PLAN_ON) return {}; return { preMain: true, ...LINK_PLAN_CHECK ? { linkPlanCheck: true } : {} }; } var CLOSURE_PLAN_ON = LINK_PLAN_ENV.HWJS_CLOSURE_PLAN !== "0"; var CLOSURE_PLAN_TRACE = LINK_PLAN_ENV.HWJS_CLOSURE_PLAN_TRACE === "1"; var LINK_FACTS_MAX = 4096; var linkFacts = /* @__PURE__ */ new Map(); 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); } } } 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) { } } }); } var closurePlanStats = { hit: 0, miss: 0, recorded: 0, off: 0 }; 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; } // ../../linux-in-the-browser/hardwarejs/src/worker-browser.mjs var postWorkerError = (m) => { try { self.postMessage(m); } catch (_e) { } }; self.addEventListener("error", (ev) => { const e = ev && ev.error; const message = e instanceof Error ? `${e.message} ${e.stack ?? ""}` : ev && ev.message ? `${ev.message}${ev.filename ? ` (at ${ev.filename}:${ev.lineno ?? "?"}:${ev.colno ?? "?"})` : ""}` : "worker-browser: uncaught error event with no detail"; postWorkerError({ kind: "error", pid: -1, message }); }); self.addEventListener("unhandledrejection", (ev) => { const r = ev && ev.reason; const message = r instanceof Error ? `unhandled rejection: ${r.message} ${r.stack ?? ""}` : `unhandled rejection: ${String(r)}`; postWorkerError({ kind: "error", pid: -1, message }); }); bindWorker({ post: (m) => self.postMessage(m), onMessage: (cb) => { self.onmessage = (ev) => cb(ev.data); } });