From 6901f8a225954033b3aa13f67db7c90b9155ce2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Lucas?= <55464917+jlucaso1@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:30:03 -0300 Subject: [PATCH] js: allocate an SMP kernel's memory once, shared, at a boot and a restore, so that memoryFallbackMiB applies to it (#10) An SMP kernel imports a shared memory, which the JS API does not show. boot() assumed an unshared one, allocated it, got a LinkError and allocated again, shared. It now guesses the sharing from the atomics feature in the module's target_features section, as moduleIsMemory64() does for the memory type; the retry stays for a wrong guess (a module with atomics on an unshared memory). memoryFallbackMiB only applied to the unshared allocation: where the shared one then failed, boot was rejected with the LinkError and no fallback was tried. It now applies to the shared allocation. Co-authored-by: Pooya Parsa --- .agents/kernel.md | 5 ++-- js/core/kernel.ts | 58 ++++++++++++++++++++++++++++++----------------- test/api.test.ts | 43 +++++++++++++++++++++++++++++++++++ 3 files changed, 83 insertions(+), 23 deletions(-) diff --git a/.agents/kernel.md b/.agents/kernel.md index 9c0cfb0..c2856f8 100644 --- a/.agents/kernel.md +++ b/.agents/kernel.md @@ -407,8 +407,9 @@ through Binaryen (`wasm-opt -g --memory64-lowering --table64-lowering`, about 1 s) to make `vmlinux32.wasm`. Pointers stay i64 in the code and at the JS boundary, so imports, exports and JSPI are unchanged; only memory and table accesses are wrapped to i32, which is exact because RAM is below -4 GiB. The runtime picks the memory type with `moduleIsMemory64()`, which -reads the module's `target_features` section. +4 GiB. The runtime picks the memory type with `moduleIsMemory64()` and a +shared memory with `moduleIsSharedMemory()`, which read the module's +`target_features` section. The lowered build runs at the same speed in V8, is about 20% faster in JavaScriptCore, and needs no memory64. The bundle, the page, the CLI's diff --git a/js/core/kernel.ts b/js/core/kernel.ts index 8333294..7ff780f 100644 --- a/js/core/kernel.ts +++ b/js/core/kernel.ts @@ -239,6 +239,27 @@ export interface KernelConfig { spawnSampler?: (init: SamplerInit) => SamplerHandle; } +/** Whether the linker's "target_features" section lists `feature`; undefined in a module without the section. */ +function moduleFeature(module: WebAssembly.Module, feature: string): boolean | undefined { + const secs = WebAssembly.Module.customSections(module, "target_features"); + if (!secs.length) return undefined; + const b = new Uint8Array(secs[0]!); + let p = 0; + const leb = () => { + let v = 0, s = 0, c; + do { c = b[p++]!; v |= (c & 0x7f) << s; s += 7; } while (c & 0x80); + return v; + }; + for (let n = leb(); n > 0 && p < b.length; n--) { + const prefix = String.fromCharCode(b[p++]!); + const len = leb(); + const name = textDecoder.decode(b.subarray(p, p + len)); + p += len; + if (name === feature) return prefix !== "-"; + } + return false; +} + /** * Does this kernel module import a 64-bit (memory64) memory? * @@ -252,23 +273,17 @@ export interface KernelConfig { * boot() retries with the other memory type if instantiation fails. */ export function moduleIsMemory64(module: WebAssembly.Module): boolean { - const secs = WebAssembly.Module.customSections(module, "target_features"); - if (!secs.length) return true; - const b = new Uint8Array(secs[0]!); - let p = 0; - const leb = () => { - let v = 0, s = 0, c; - do { c = b[p++]!; v |= (c & 0x7f) << s; s += 7; } while (c & 0x80); - return v; - }; - for (let n = leb(); n > 0 && p < b.length; n--) { - const prefix = String.fromCharCode(b[p++]!); - const len = leb(); - const name = textDecoder.decode(b.subarray(p, p + len)); - p += len; - if (name === "memory64") return prefix !== "-"; - } - return false; + return moduleFeature(module, "memory64") ?? true; +} + +/** + * Does this kernel module import a shared memory? A guess from its wasm + * atomics, which --shared-memory needs and the UP kernel does without (a + * KW_ATOMICS=1 build has them on an unshared memory); boot() retries with + * the other sharing if instantiation fails. + */ +function moduleIsSharedMemory(module: WebAssembly.Module): boolean { + return moduleFeature(module, "atomics") ?? false; } /** @@ -1189,6 +1204,7 @@ export class Kernel { if (!memImport) throw new Error("vmlinux must import its memory"); const guessed = this.opts.memory64 === undefined && !restore; this.memory64 = restore ? restore.memory64 : guessed ? moduleIsMemory64(module) : !!this.opts.memory64; + this.sharedMemory = moduleIsSharedMemory(module); if (restore) { // No fallback sizes: the kernel sized RAM from this memory at boot. this.memory = Kernel.newMemory(restore.memory.byteLength / 65536, this.memory64, this.sharedMemory); @@ -1205,10 +1221,10 @@ export class Kernel { this.onStage("instantiate"); // The JS API does not show whether the memory import is shared (a - // kernel linked with --shared-memory): retry once with the other - // sharing when the engine says that is the mismatch; and, for a - // guessed memory type (a module without target_features), once with - // the other type. + // kernel linked with --shared-memory), so that is a guess + // (moduleIsSharedMemory): retry once with the other sharing when the + // engine says it was wrong; and, for a guessed memory type (a module + // without target_features), once with the other type. let instance: WebAssembly.Instance | undefined; let flippedShared = false, flippedType = !guessed; while (!instance) { diff --git a/test/api.test.ts b/test/api.test.ts index c6f819b..b54f15d 100644 --- a/test/api.test.ts +++ b/test/api.test.ts @@ -2737,6 +2737,49 @@ describe("api", { concurrency: CONCURRENCY }, () => { }); +// Not with the others: it replaces WebAssembly.Memory, which every boot uses. +test("SMP: the kernel's memory is allocated once, shared, at a boot and at a restore; memoryFallbackMiB applies where a shared memory cannot be had", + { skip: !hasSmpPatch && "the kernel under test carries no SMP kernel" }, async (t) => { + const kernel = await sdk.loadKernelModule(readFileSync(kernelFile), { smp: true }); + const { Memory } = WebAssembly; + const asked: string[] = []; + let maxSharedMiB = Infinity; + WebAssembly.Memory = new Proxy(Memory, { + construct(target, args: [WebAssembly.MemoryDescriptor], newTarget) { + const mib = Number(args[0].initial) / 16; + if (mib >= 128) asked.push(`${mib} MiB${args[0].shared ? " shared" : ""}`); + if (args[0].shared && mib > maxSharedMiB) throw new RangeError("could not allocate memory"); + return Reflect.construct(target, args, newTarget) as WebAssembly.Memory; + }, + }); + try { + const opts = { kernel, cpus: 1, worker: false, vsock: false, log: () => {} }; + const vm = await boot(t, { ...opts, memoryMiB: 512 }); + const a = screen(vm); + await a.waitFor(PROMPT); + // Saved once init is done starting the shell (as above). + vm.write("echo up-$((6*7))\n"); + await a.waitFor(/up-42/); + const snap = await vm.snapshot({ stop: true }); + assert.deepEqual(asked.splice(0), ["512 MiB shared"]); + + const vm2 = await boot(t, { ...opts, restore: snap }); + const b = screen(vm2); + vm2.write("echo restored-$((6*7))\n"); + await b.waitFor(/restored-42/); + await vm2.stop({ reason: "test" }); + assert.deepEqual(asked.splice(0), ["512 MiB shared"]); + + maxSharedMiB = 256; + const vm3 = await boot(t, { ...opts, memoryMiB: 512, memoryFallbackMiB: [384, 256] }); + await screen(vm3).waitFor(PROMPT); + assert.equal(vm3.memoryMiB, 256); + assert.deepEqual(asked, ["512 MiB shared", "384 MiB shared", "256 MiB shared"]); + } finally { + WebAssembly.Memory = Memory; + } +}); + // Not with the others: it changes globalThis.crossOriginIsolated, which every worker-mode boot reads. test("worker mode: messages where SharedArrayBuffer cannot be used (a page that is not cross-origin isolated); shared: true then rejects", async (t) => { const g = globalThis as { crossOriginIsolated?: boolean };