diff --git a/.agents/kwemu.md b/.agents/kwemu.md index 08fb6b5..1e761b2 100644 --- a/.agents/kwemu.md +++ b/.agents/kwemu.md @@ -585,7 +585,7 @@ These imports exist only with `-Dkwemu-jit`. The kernel host is | Import | | | --- | --- | -| `kw_host_jit_caps() -> u32` | bit 0 = JIT available (0: never compile), bit 1 = 32-bit memory (lowered kernel: the code imports a 32-bit `env.memory` and wraps addresses), bit 2 = eager. Called once, from `kw_cpu_init`. | +| `kw_host_jit_caps() -> u32` | bit 0 = JIT available (0: never compile), bit 1 = 32-bit memory (lowered kernel: the code imports a 32-bit `env.memory` and wraps addresses), bit 2 = eager, bit 3 = shared memory (the code declares its `env.memory` import shared, with a maximum of 65536 pages for memory32 and 262144 for memory64; the host sets it when the kernel's memory is a SharedArrayBuffer). Called once, from `kw_cpu_init`. | | `kw_host_jit_compile(ptr, len, slot) -> i32` | Compile the module at `ptr` (it imports `env.memory` and exports `f`) synchronously with `new WebAssembly.Module` and `table.set` its `f` into `slot` (a BigInt index for table64). 0 = installed, < 0 = failed (slot untouched, and that block is never compiled). | | `kw_host_jit_free(slot)` | Put back the stub that was there before the first compile, and drop the module. | diff --git a/build.zig b/build.zig index 085deeb..8fa8cbc 100644 --- a/build.zig +++ b/build.zig @@ -45,7 +45,8 @@ pub fn build(b: *std.Build) void { // ---- kwemu: the CPU core as a library for the real kernel ----------------- // wasm64 relocatable object + static archive with the C ABI of // include/kw_emu.h; conservative wasm features (mvp + memory64): no - // threads/atomics/TLS/bulk-memory/sign-ext/nontrapping-fptoint. + // threads/atomics/TLS/bulk-memory/sign-ext/nontrapping-fptoint, unless + // -Dkwemu-atomics (below). const lib_optimize = b.option(std.builtin.OptimizeMode, "lib-optimize", "Optimization mode for libkwemu (default: ReleaseFast)") orelse .ReleaseFast; // Tail-call threaded dispatch (one function per op, return_call_indirect // chains). Adds the wasm `tail_call` feature to the object, so the @@ -62,13 +63,23 @@ pub fn build(b: *std.Build) void { // Operand sets per op of the randomized F/D differential unit test // (interpreter vs JIT, wasm64 unit tests only); 0 = its small default. const fp_fuzz = b.option(u32, "kwemu-fp-fuzz", "kwemu: random operand sets per op in the F/D JIT differential test (default: 0 = 4096)") orelse 0; + // wasm atomics + bulk memory in the wasm64 objects, so that a kernel + // linked with --shared-memory (wasm-ld refuses objects without both) + // can include kwemu. kwemu itself stays single-threaded: guest + // AMO/LR/SC are not made atomic by this. + const atomics = b.option(bool, "kwemu-atomics", "kwemu: build the wasm64 objects with the atomics and bulk-memory features, for a shared-memory kernel (default: false)") orelse false; const kw_opts_mod = kwOptions(b, tail_call, stats, jit, jit_threshold, jit_grow, fp_fuzz); const kw_opts_jit_mod = if (jit) kw_opts_mod else kwOptions(b, tail_call, stats, true, jit_threshold, jit_grow, fp_fuzz); const wasm64 = b.resolveTargetQuery(.{ .cpu_arch = .wasm64, .os_tag = .freestanding, .cpu_model = .{ .explicit = &std.Target.wasm.cpu.mvp }, - .cpu_features_add = if (tail_call) std.Target.wasm.featureSet(&.{.tail_call}) else .empty, + .cpu_features_add = blk: { + var f: std.Target.Cpu.Feature.Set = .empty; + if (tail_call) f.addFeatureSet(std.Target.wasm.featureSet(&.{.tail_call})); + if (atomics) f.addFeatureSet(std.Target.wasm.featureSet(&.{ .atomics, .bulk_memory })); + break :blk f; + }, }); const kw_h_wasm = kwHeader(b, wasm64, lib_optimize); const kw_h_native = kwHeader(b, native, optimize); diff --git a/js/core/jit.ts b/js/core/jit.ts index fdff806..b0c516d 100644 --- a/js/core/jit.ts +++ b/js/core/jit.ts @@ -107,6 +107,7 @@ export interface JitHostOptions { const CAP_AVAILABLE = 1; const CAP_MEM32 = 2; +const CAP_SHARED = 8; /** kwemu's emit buffer is 16 KiB; anything much larger is not from kwemu. */ const MAX_MODULE = 1 << 20; /** Failure messages logged before going quiet. */ @@ -214,7 +215,8 @@ export class JitHost { this.#warn("the kernel exports no __indirect_function_table; JIT off"); return 0; } - return CAP_AVAILABLE | (this.#opts.memory64() ? 0 : CAP_MEM32); + const shared = typeof SharedArrayBuffer !== "undefined" && this.#opts.memory().buffer instanceof SharedArrayBuffer; + return CAP_AVAILABLE | (this.#opts.memory64() ? 0 : CAP_MEM32) | (shared ? CAP_SHARED : 0); } compile(ptr: bigint | number, len: bigint | number, slot: number): number { @@ -235,8 +237,10 @@ export class JitHost { const mem = this.#opts.memory(); if (!(n > 0 && n <= MAX_MODULE && p >= 0 && p + n <= mem.buffer.byteLength)) throw new Error(`bad module range ${p}+${n}`); // The Module constructor copies the bytes, so a view into the - // kernel's memory is enough. - const module = new WebAssembly.Module(new Uint8Array(mem.buffer, p, n)); + // kernel's memory is enough, unless the memory is shared (the JS + // API takes no shared views; V8 accepts them, others need not). + const view = new Uint8Array(mem.buffer, p, n); + const module = new WebAssembly.Module(mem.buffer instanceof ArrayBuffer ? view : view.slice()); const f = new WebAssembly.Instance(module, { env: { memory: mem } }).exports.f; if (typeof f !== "function") throw new Error("the module exports no function f"); const idx = this.#big ? BigInt(slot) : slot; diff --git a/js/core/kernel.ts b/js/core/kernel.ts index 8c49da7..e814e92 100644 --- a/js/core/kernel.ts +++ b/js/core/kernel.ts @@ -274,6 +274,8 @@ export class Kernel { shm: ShmDevice; memory!: WebAssembly.Memory; memory64 = false; + /** The module imports a shared memory (a kernel linked with --shared-memory). */ + sharedMemory = false; wasi!: WasiHost; exports: WebAssembly.Exports | undefined; /** Address of wasm_host_irqs, once instantiated. */ @@ -386,7 +388,7 @@ export class Kernel { const p = Number(ptr); let end = p; while (end < p + max && u8[end] !== 0) end++; - return textDecoder.decode(u8.subarray(p, end)); + return textDecoder.decode(u8.slice(p, end)); // a copy: TextDecoder may refuse a shared memory's view } fatal(msg: string): void { @@ -682,11 +684,11 @@ export class Kernel { this.exit({ code: 254, reason: String(e), kind: "trap", error: e }); } - /** A fixed-size memory of `pages` 64 KiB pages, 64-bit (BigInt sizes) or 32-bit. */ - static newMemory(pages: number, memory64: boolean): WebAssembly.Memory { + /** A fixed-size memory of `pages` 64 KiB pages, 64-bit (BigInt sizes) or 32-bit, shared or not. */ + static newMemory(pages: number, memory64: boolean, shared = false): WebAssembly.Memory { return memory64 - ? new WebAssembly.Memory({ initial: BigInt(pages), maximum: BigInt(pages), address: "i64" } as unknown as WebAssembly.MemoryDescriptor) - : new WebAssembly.Memory({ initial: pages, maximum: pages }); + ? new WebAssembly.Memory({ initial: BigInt(pages), maximum: BigInt(pages), address: "i64", shared } as unknown as WebAssembly.MemoryDescriptor) + : new WebAssembly.Memory({ initial: pages, maximum: pages, shared }); } /** @@ -702,7 +704,7 @@ export class Kernel { const pages = Math.ceil((mib * 1024 * 1024) / 65536); try { if (!this.memory64 && pages > 65536) throw new RangeError("more than 4 GiB needs the wasm64 (memory64) kernel"); - const memory = Kernel.newMemory(pages, this.memory64); + const memory = Kernel.newMemory(pages, this.memory64, this.sharedMemory); if (failures.length) this.log(`[host] allocated ${mib} MiB after failing: ${failures.join("; ")}`); this.onStage("memory", { mib, requestedMiB: memoryMiB, failures, memory64: this.memory64 }); return memory; @@ -738,7 +740,7 @@ export class Kernel { this.memory64 = restore ? restore.memory64 : guessed ? moduleIsMemory64(module) : !!this.opts.memory64; 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.memory = Kernel.newMemory(restore.memory.byteLength / 65536, this.memory64, this.sharedMemory); this.onStage("memory", { mib: memoryMiB, requestedMiB: memoryMiB, failures: [], memory64: this.memory64 }); } else { this.memory = this.allocateMemory(memoryMiB, initrd?.length ?? 0); @@ -751,22 +753,36 @@ export class Kernel { }); this.onStage("instantiate"); - let instance: WebAssembly.Instance; - try { - instance = await WebAssembly.instantiate(module, this.imports()); - } catch (e) { - // Wrong memory type (a module without target_features): retry once - // with the other one, same size. - if (!guessed || !(e instanceof WebAssembly.LinkError)) throw e; - const pages = this.memory.buffer.byteLength / 65536; + // 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. + let instance: WebAssembly.Instance | undefined; + let flippedShared = false, flippedType = !guessed; + while (!instance) { try { - this.memory = Kernel.newMemory(pages, !this.memory64); - this.memory64 = !this.memory64; - } catch { - throw e; + instance = await WebAssembly.instantiate(module, this.imports()); + } catch (e) { + if (!(e instanceof WebAssembly.LinkError)) throw e; + const pages = this.memory.buffer.byteLength / 65536; + let memory64 = this.memory64, shared = this.sharedMemory; + if (!flippedShared && /\bshared\b/i.test(e.message)) { + flippedShared = true; + shared = !shared; + } else if (!flippedType) { + flippedType = true; + memory64 = !memory64; + } else throw e; + try { + this.memory = Kernel.newMemory(pages, memory64, shared); + } catch { + throw e; + } + if (memory64 !== this.memory64) this.log(`[host] memory type guess was wrong (${e.message}); using a ${memory64 ? "64" : "32"}-bit memory`); + this.memory64 = memory64; + this.sharedMemory = shared; } - this.log(`[host] memory type guess was wrong (${e.message}); using a ${this.memory64 ? "64" : "32"}-bit memory`); - instance = await WebAssembly.instantiate(module, this.imports()); } const ex = (this.exports = instance.exports); const addr = (name: string) => { diff --git a/js/core/wasi.ts b/js/core/wasi.ts index 62fbaf2..352d715 100644 --- a/js/core/wasi.ts +++ b/js/core/wasi.ts @@ -324,8 +324,11 @@ export class WasiHost { }, random_get(buf: number, len: number): number { const u8 = w.u8(); - for (let off = 0; off < len; off += 65536) - crypto.getRandomValues(u8.subarray(buf + off, buf + Math.min(len, off + 65536))); + // Through a copy: getRandomValues refuses a shared memory's view in browsers. + for (let off = 0; off < len; off += 65536) { + const n = Math.min(len - off, 65536); + u8.set(crypto.getRandomValues(new Uint8Array(n)), buf + off); + } return ERRNO.SUCCESS; }, @@ -337,7 +340,7 @@ export class WasiHost { for (const [p, len] of w.iovecs(iovs, n)) { if (!len) continue; if (f.type === "stdout") k.opts.write(u8.slice(p, p + len)); - else w.stderr = (w.stderr + decoder.decode(u8.subarray(p, p + len))).slice(-4096); + else w.stderr = (w.stderr + decoder.decode(u8.slice(p, p + len))).slice(-4096); total += len; } w.dv().setUint32(nwritten, total, true); @@ -405,7 +408,7 @@ export class WasiHost { if (!d) return ERRNO.BADF; if (d.type !== "dir") return ERRNO.NOTDIR; if (oflags & (OFLAGS_CREAT | OFLAGS_TRUNC)) return ERRNO.ROFS; - const name = decoder.decode(w.u8().subarray(path, path + pathLen)).replace(/^(\.?\/)+/, ""); + const name = decoder.decode(w.u8().slice(path, path + pathLen)).replace(/^(\.?\/)+/, ""); const data = d.files.get(name); if (!data) return ERRNO.NOENT; if (oflags & OFLAGS_DIRECTORY) return ERRNO.NOTDIR; diff --git a/src/emu/jit.zig b/src/emu/jit.zig index 5cec1cc..e6cd4ea 100644 --- a/src/emu/jit.zig +++ b/src/emu/jit.zig @@ -14,7 +14,9 @@ //! kw_host_jit_caps() -> u32 //! bit 0: JIT available; bit 1: the memory is 32-bit (memory64-lowered //! module: the generated code imports a 32-bit memory and wraps every -//! address); bit 2: eager (compile on the first entry; tests). +//! address); bit 2: eager (compile on the first entry; tests); +//! bit 3: the memory is shared (the generated code declares its +//! import shared, with the largest maximum of its type). //! Called once, by kw_cpu_init. //! kw_host_jit_compile(ptr, len, slot: u32) -> i32 //! Compile the `len` bytes at `ptr` (a module importing env.memory and @@ -79,6 +81,7 @@ pub const code_side = 128; pub const cap_available: u32 = 1; pub const cap_mem32: u32 = 2; pub const cap_eager: u32 = 4; +pub const cap_shared: u32 = 8; /// Most blocks in one compiled region (see "regions" below). pub const max_members = 16; @@ -1066,6 +1069,8 @@ const Emit = struct { pos: usize = 0, ok: bool = true, mem32: bool, + /// The kernel's memory is shared (cap_shared): the import says so. + shared: bool = false, /// Open blocks/loops/ifs; the exit block is the outermost. nest: u32 = 0, /// The frm == RNE test for dynamic rounding modes has been emitted (frm @@ -1256,7 +1261,7 @@ fn emitModule(cpu: *Cpu, b: *const Block, rg: ?*Region, limit: *usize) Error!usi const live = use.read | use.write; const flive = use.fread | use.fwrite; - var e: Emit = .{ .buf = &cpu.priv.jit.buf, .mem32 = cpu.priv.jit.caps & cap_mem32 != 0 }; + var e: Emit = .{ .buf = &cpu.priv.jit.buf, .mem32 = cpu.priv.jit.caps & cap_mem32 != 0, .shared = cpu.priv.jit.caps & cap_shared != 0 }; e.rg = rg; e.fma_inline = fma_inline; // a region's members set their own e.aes_inline = aes_inline; @@ -1284,9 +1289,15 @@ fn emitModule(cpu: *Cpu, b: *const Block, rg: ?*Region, limit: *usize) Error!usi // type 0: (i64 i64 i64 i64) -> i64 (f); type 1: (i64 i64 i64) -> i64 (the helpers) e.ops(&.{ 0x01, 0x10, 0x02, 0x60, 0x04, W.i64_t, W.i64_t, W.i64_t, W.i64_t, 0x01, W.i64_t }); e.ops(&.{ 0x60, 0x03, W.i64_t, W.i64_t, W.i64_t, 0x01, W.i64_t }); - // import env.memory: memory64 (flags 4) or memory32, min 0 - e.ops(&.{ 0x02, 0x0f, 0x01, 0x03, 'e', 'n', 'v', 0x06, 'm', 'e', 'm', 'o', 'r', 'y', 0x02 }); - e.ops(&.{ if (e.mem32) 0x00 else 0x04, 0x00 }); + // import env.memory: memory64 (flags 4) or memory32, min 0; a shared + // memory (flags | 3) needs a maximum, which an import matches when the + // memory's is not larger: 65536 pages (4 GiB) for memory32, 262144 + // (16 GiB, the kernel's --max-memory) for memory64. + e.ops(&.{ 0x02, if (e.shared) 0x12 else 0x0f, 0x01, 0x03, 'e', 'n', 'v', 0x06, 'm', 'e', 'm', 'o', 'r', 'y', 0x02 }); + if (e.shared) + e.ops(&.{ if (e.mem32) 0x03 else 0x07, 0x00, 0x80, 0x80, if (e.mem32) 0x04 else 0x10 }) + else + e.ops(&.{ if (e.mem32) 0x00 else 0x04, 0x00 }); // functions: f (type 0), then the helpers (type 1) e.ops(&.{ 0x03, @intCast(1 + nfn), @intCast(nfn), 0x00 }); for (1..nfn) |_| e.op(0x01); diff --git a/test/kwemu-test.mjs b/test/kwemu-test.mjs index 2d17861..f4f2c3e 100644 --- a/test/kwemu-test.mjs +++ b/test/kwemu-test.mjs @@ -9,7 +9,8 @@ // exactly as many instructions (instret) as the wasm64 interpreter // * wasm32+jit: the JIT harness lowered with Binaryen // (wasm-opt --memory64-lowering --table64-lowering, as the kernel is; -// --enable-memory64 because Zig emits no target_features section); +// --enable-memory64 because Zig emits no target_features section, and +// bulk memory and threads for a -Dkwemu-atomics build); // skipped with a note if vendor/toolchain/binaryen is missing ($WASM_OPT // overrides the path) // usage: node test/kwemu-test.mjs [--bench-only] @@ -38,7 +39,7 @@ let jit32Module = null, jit32Note = ""; else { const dir = await mkdtemp(join(tmpdir(), "kwemu-jit32-")); const out = join(dir, "kwemu-harness-jit32.wasm"); - const p = spawnSync(wasmOpt, ["-g", "--enable-memory64", "--memory64-lowering", "--table64-lowering", jitPath, "-o", out], { encoding: "utf8" }); + const p = spawnSync(wasmOpt, ["-g", "--enable-memory64", "--enable-bulk-memory", "--enable-threads", "--memory64-lowering", "--table64-lowering", jitPath, "-o", out], { encoding: "utf8" }); if (p.status !== 0) jit32Note = `FAIL wasm-opt lowering: ${p.stderr}`; else jit32Module = await WebAssembly.compile(await readFile(out)); await rm(dir, { recursive: true, force: true });