diff --git a/.machine_readable/descriptiles/STATE.deed b/.machine_readable/descriptiles/STATE.deed index 1e5084af..4455a23d 100644 --- a/.machine_readable/descriptiles/STATE.deed +++ b/.machine_readable/descriptiles/STATE.deed @@ -256,3 +256,14 @@ landed = [ "docs: bindings/stdlib/alib roadmap Tracking sections de-staled to live umbrellas #446/#412/#413" ] umbrella-446 = "stays open — STEP 1-3 done, STEP 4/5 long-running" + +[[session-delta]] +# Appended 2026-12-01 — core-wasm heap/literal overlap fix (#830). +# Mirror entry only; soundness status is docs/SOUNDNESS.adoc (row #830). +date = "2026-12-01" +issue = "#830" +landed = [ + "codegen: heap base computed after codegen as align8(end of last data segment); memory sized to cover it; module refused if heap base < data end (docs/WASM-MEMORY-LAYOUT.adoc)", + "tests: test/test_wasm_heap_layout.ml (layout check, static layout, #829 repro + 40 KiB allocation + exhaustion under Bun WASI)", + "audit: docs/reports/AUDIT-2026-12-01-backend-divergences.adoc; follow-ups #831 (string index units, owner decision), #832 (js builtins), #833 (eval), #834 (estate rebuilds)" +] diff --git a/docs/SOUNDNESS.adoc b/docs/SOUNDNESS.adoc index 32644df0..06380d00 100644 --- a/docs/SOUNDNESS.adoc +++ b/docs/SOUNDNESS.adoc @@ -4,7 +4,7 @@ // Freshness stamp — a real main-ancestor commit (survives squash-merge); advance // it (and --reseal) in any change that touches a soundness path. See "Keeping // this honest" and tools/check-soundness-ledger.sh (property 4). -:ground-truth-sha: 4248912 +:ground-truth-sha: 0cf73b2 :ground-truth-date: 2026-12-01 :stamp-verified-by: tools/check-soundness-ledger.sh :toc: macro @@ -291,6 +291,26 @@ write, so a user `int_to_string` / `string_slice` does not capture them. core wasm; every wasm case fails on `4248912`. Also: an `extern fn` in scope keeps the lowering; the lowerings still run; `show`/`slice` are not captured; a local and an imported definition win) + +| #830 +| Core-wasm heap allocations can no longer overwrite string literals. The +heap-pointer global used to start at a fixed 1024 while literals were laid +out from a fixed 2048, so a program that allocated more than ~1 KiB +silently corrupted its own literals (#829's 60-line repro printed 21 lines, +then `label_number_22abe`, then trapped). The heap base is now computed +after code generation as the 8-aligned end of the last data segment, the +initial memory covers it, and `generate_module` refuses (compile-time +error) any module whose heap base lies below the end of static data. There +is no `memory.grow`; exhausting the heap is an out-of-bounds trap, not a +write into the literal region. Layout invariant: +`docs/WASM-MEMORY-LAYOUT.adoc`. +| `fixed` +| `test/test_wasm_heap_layout.ml` (`test_wasm_heap_base_below_data_end_refused` +— the gate refuses the old layout; `test_wasm_heap_after_literals_static`; +`test_wasm_heap_repro_runs` and +`test_wasm_heap_literals_intact_after_alloc` — run under Bun's WASI; +`test_wasm_heap_exhaustion_traps`); `lib/codegen.ml` +`memory_layout_of_datas` / `check_memory_layout` |=== == Still open — read before claiming "sound" diff --git a/docs/WASM-MEMORY-LAYOUT.adoc b/docs/WASM-MEMORY-LAYOUT.adoc new file mode 100644 index 00000000..6bd0a671 --- /dev/null +++ b/docs/WASM-MEMORY-LAYOUT.adoc @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 +// SPDX-FileCopyrightText: 2026 hyperpolymath += Core-Wasm Linear-Memory Layout +:toc: macro +:icons: font + +This page describes how the core-wasm backend (`lib/codegen.ml`) lays out +the single linear memory of every module it emits. It also states the +invariant that the layout must keep. The status of the hole this invariant +closes (#830) is recorded in link:SOUNDNESS.adoc[SOUNDNESS.adoc], and that +ledger is the authority for it. + +toc::[] + +== Regions + +[cols="2,2,5",options="header"] +|=== +| Region | Range | Contents + +| Runtime scratch +| `[0, scratch_end)` = `[0, 1024)` +| Fixed-address words that `lib/wasi_runtime.ml` writes: the WASI iovec, +the `nwritten` cell and the int-to-string buffer. + +| Static data +| `[static_data_base, data_end)`, with `static_data_base = 1024` +| Every active data segment. Today these are string literals, each stored as +`[len: i32][utf8 bytes]` and laid out one after another by `gen_literal`. + +| Heap +| `[heap_base, …)` +| The bump allocator behind the heap-pointer global: strings built at run +time, arrays, tuples, records, closures, `float_to_string` buffers and +clock scratch. +|=== + +`heap_base = align8(max(scratch_end, data_end))`. The initial memory size is +`max(1, ceil(heap_base / 65536))` pages. + +== Invariant + +*No heap allocation overlaps a static data segment.* + +The heap pointer starts at `heap_base`. Allocation only ever increases it, +so every heap address is at least `data_end`. + +The constants and functions that keep this invariant are in `lib/codegen.ml`, +under _Linear-memory layout (core-wasm)_: + +`memory_layout_of_datas`:: +Computes `data_end`, `heap_base` and the page count from the data segments +the module actually carries. It returns an error if two segments overlap or +if a segment lies in the scratch region. + +`generate_module`:: +Calls `memory_layout_of_datas` after code generation has finished, so every +literal has already been laid out. It then patches the heap-pointer global +to `heap_base` and sizes the memory. + +`check_memory_layout`:: +Runs on the finished module. It refuses the module with a compile-time +error if the heap global starts below `data_end`, or if the initial memory +does not hold the static data. + +An error from either check is an internal compiler error. It is reported +loudly. The compiler never emits a module that would corrupt itself. + +== Memory growth + +The backend never emits `memory.grow`. If a program allocates past the end +of the module's pages, the access is a wasm out-of-bounds trap. That is a +loud failure, and it never writes into the static region. + +If a growth path is added, it must grow memory in place (as `memory.grow` +does) and must not move or reuse `[static_data_base, heap_base)`. When that +happens, `test_wasm_heap_exhaustion_traps` should be changed to expect the +full output. + +== History + +Before #830 the heap global was initialised to a fixed 1024, and literals +were laid out from a fixed 2048. Any program that allocated more than about +1 KiB overwrote its own literals. In #829's reproduction, 60 concatenated +`println` calls printed 21 correct lines, then `label_number_22abe`, then +trapped. + +== Tests + +All of these are in `test/test_wasm_heap_layout.ml`, which runs as part of +`dune runtest`. The run tests SKIP when `bun` is not installed. + +* `test_wasm_heap_base_below_data_end_refused`: the check refuses the old +layout, overlapping segments, and a segment in the scratch region. +* `test_wasm_heap_after_literals_static`: compiled programs start the heap at +`heap_base`, and their memory covers the static data. +* `test_wasm_heap_repro_runs`: #829's reproduction prints all 60 lines. +* `test_wasm_heap_literals_intact_after_alloc`: after about 40 KiB of +allocation, every literal is still intact. +* `test_wasm_heap_exhaustion_traps`: allocating past the page traps loudly. + +== Built artefacts + +Wasm built by an older compiler still has the overlapping layout, and +recompiling it fixes that. To check a module, read its heap global and its +data segments with `wasm-tools print`. If the module has a mutable i32 +global initialised to `1024` and data segments starting at `2048`, it was +built before the fix. This includes `editors/vscode/out/extension.cjs`, +which embeds such a module. The estate tracking note is #834. diff --git a/docs/reports/AUDIT-2026-12-01-backend-divergences.adoc b/docs/reports/AUDIT-2026-12-01-backend-divergences.adoc new file mode 100644 index 00000000..9bfde042 --- /dev/null +++ b/docs/reports/AUDIT-2026-12-01-backend-divergences.adoc @@ -0,0 +1,327 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 +// SPDX-FileCopyrightText: 2026 hyperpolymath += Backend Divergence Audit (2026-12-01) +:toc: macro +:icons: font + +This audit follows the #830 fix. Findings 5 to 8 were added after the #829 thread reported them. The Unicode thread (#829) found several ways +the backends disagree. The owner asked whether any of the others needs the +same at-source treatment as the wasm heap/literal overlap. + +Each finding below was reproduced on `main` `ee211d3` with the built compiler. +For each one, the audit records the evidence, a classification and a +recommended fix. The PR that adds this audit implements only #830. The other +findings are filed as issues. Those that change language semantics are marked +for the owner's review. + +Soundness-hole status is recorded in link:../SOUNDNESS.adoc[SOUNDNESS.adoc], and +that ledger is the authority for it. This report is a dated input to it. + +toc::[] + +== Classification used + +Soundness hole:: +A well-typed program silently gets a wrong value or corrupts state on a +supported path. + +Silent divergence:: +Backends give different observable results for the same well-typed program, +and nothing fails. + +Loud divergence:: +A backend refuses or crashes on a well-typed program that another backend +runs. This breaks progress for that backend, but it never gives a +plausible-wrong result. + +== Summary + +[cols="3,2,2,2",options="header"] +|=== +| Finding | Class | Changes semantics? | Tracking + +| Core-wasm heap overlaps string literals +| *Soundness hole*: silent memory corruption +| No +| #830 (fixed in this PR); estate rebuilds #834 + +| String indices are octets on interp/wasm but UTF-16 units on Bun-ESM +| Silent divergence +| *Yes*: owner decision +| #831 + +| Plain-JS backend has no string builtins (run-time `ReferenceError`) +| Loud divergence, at the wrong phase +| No +| #832 + +| `eval` rejects self-recursion, forward and mutual references, and `let mut` +| Loud divergence (the reference interpreter) +| No +| #833 + +| A user fn named like a wasm-intercepted intrinsic is silently replaced +| *Soundness hole*: silent wrong value +| No +| #836 (fixed by #841, merged) + +| An intrinsic used as a value (e.g. `len`) emits a bare name on Bun-ESM +| Loud divergence, at the wrong phase +| No +| #837 + +| A local or parameter does not shadow a same-named top-level fn on wasm +| *Soundness hole*: silent wrong value +| No (wasm is brought in line with interp and Bun) +| #838 (fixed by #840, merged) + +| A named fn passed as a value fails to compile on wasm +| Loud divergence (compile-time refusal) +| No +| #839 +|=== + +== 1. Core-wasm heap overlaps string literals (#830) + +Evidence:: +Sixty `println("label_number_N" ++ " ok")` calls, compiled to wasm and run +with `bun run`, printed 21 correct lines, then `label_number_22abe`, then +`RuntimeError: Out of bounds memory access`. `affinescript eval` printed all +60 lines. Cause: the heap global was initialised to a fixed `1024`, and +literals were laid out from a fixed `2048`. + +Classification:: +Soundness hole: silent corruption of static data. The trap comes only after +the corrupted line has been printed. + +Fix (implemented):: +The heap base is computed after code generation as the 8-aligned end of the +last data segment, and the memory is sized to cover it. The module is +refused if the heap base is below the end of static data. See +link:../WASM-MEMORY-LAYOUT.adoc[WASM-MEMORY-LAYOUT.adoc]. ++ +Alternatives considered: ++ +* Bounds-checked allocation with `memory.grow`. This is needed eventually, +but on its own it would not move the heap off the literals. +* A separate memory for literals (multi-memory). This is not yet supported +by every target host. +* Literals in a WasmGC `array i8`. That is only possible on the GC backend. ++ +Computing the layout from the emitted segments was chosen because it makes +the invariant structural and checks it in one place. + +== 2. String index units differ by backend (#831) + +Evidence:: ++ +[cols="3,1,1,1",options="header"] +|=== +| Probe | interp | core wasm | Bun-ESM +| `len("é")` | 2 | 2 | 1 +| `len("🦜")` | 4 | 4 | 2 +| `string_char_code_at("🦜", 0)` | 240 | 240 | 55358 +|=== ++ +`lib/codegen_deno.ml:1240` lowers `len` to JS `.length`. `string_get` and +`string_sub` (`:1244-1245`) use JS indices in the same way. + +Classification:: +Silent divergence (#560 class). It is not a type-soundness hole, but it +produces the same kind of wrong answer: the same program prints different +numbers on different backends. + +Recommended fix (*most elegant and correct*):: +Use octet offsets everywhere, with boundary checks. `len` counts UTF-8 octets +on every backend. `string_get` and `string_sub` fail loudly when an offset is +not on a character boundary. Code that works with characters moves to the +#829 code-point API. + +Most dependable, type-led:: +Make offsets an opaque type (`Utf8Offset`) that only `find`, iteration and +`utf8_byte_length` can produce. Mixing units then becomes a type error. This +pairs with the recommended fix, and it is the one with a proof story: a +phantom-unit argument is a short preservation lemma. + +Outside the box:: +Represent `String` on Bun as a `Uint8Array` of UTF-8. All backends would then +share one representation. The cost is transcoding at every JS host boundary. + +Stop-gap:: +Refuse `len`, `string_get` and `string_sub` on Bun-ESM, and point to the #829 +API. This fails loudly, but it breaks existing Bun code. + +Scope:: +This reaches beyond the repo. Estate Bun-ESM code, such as the DEED printer, +counts in UTF-16 units today. The owner needs to decide. + +== 3. Plain-JS backend has no string builtins (#832) + +Evidence:: +`affinescript compile idx.affine -o idx.js` succeeds. Running the result +with `node idx.js` fails with `ReferenceError: int_to_string is not defined`. +`lib/js_codegen.ml:171` emits a free `ExprVar` as a bare name, and nothing +checks it against what the backend provides. + +Classification:: +Loud divergence, but at run time instead of compile time. + +Recommended fix (*most elegant and correct*):: +Add a closed-world check at codegen. Each text backend declares which +builtins it can lower. Any free identifier that is neither bound by the +program nor in that table makes codegen return `Error`. This removes the +whole bug class, not only on JS. + +Most dependable:: +Share the Bun-ESM builtin lowering table with `js_codegen`, so there is one +source of truth. + +Outside the box:: +Retire the plain-JS backend, as was done for Deno-ESM. + +== 4. `affinescript eval` diverges from `compile` (#833) + +Evidence:: +Self-recursion fails with `Runtime error: Unbound variable: g`. A forward +reference fails with `Unbound variable: helper`, reported as a *type* error, +and so does mutual recursion. `let mut` with `while` fails with +`Type mismatch: Expected mutable reference`. The interpreter's `println` +prints `"2"` with the quotes. Bun-ESM and wasm run all of these correctly. + +Root causes:: +* `lib/interp.ml:1151`: a top-level closure captures the environment from +before its own binding exists (there is no letrec). +* `bin/main.ml:315` and `:363`: `eval` type-checks with its own fold of +`check_decl`. That fold skips the forward pass in +`Typecheck.check_program` (`lib/typecheck.ml:2656`). +* `lib/interp.ml:507`: `StmtLet` ignores `mut`, so the cell that `assign` +needs is never created. + +Classification:: +Loud divergence. The reference interpreter refuses well-typed programs, and +the `eval` frontend accepts less than `compile` does. No silent wrong value +was found. A same-name shadowing probe is refused by the flattener (E0206). + +Recommended fix (*most elegant and correct*):: +* Make `eval` call `check_program`, so every command shares one frontend +entry. +* Make `eval_program` two-phase, with a recursive top-level environment. +* Make `let mut` bind a `VMut` cell, make reads dereference it, and make +assignment resolve to that cell. +* Make `println` print the raw string. + +Most dependable:: +Add a differential `eval`-versus-Bun stdout test over the codegen fixture +corpus. It catches the class, not just these instances. + +Outside the box:: +Move the CLI's interpreter role onto `solo_cesk`. That would also unblock +#623. + +== 5. Wasm replaces a user function named like an intrinsic (#836) + +Reported by the #829 thread after the first version of this audit, and +reproduced independently. + +Evidence:: +On `main`, `fn string_sub(s: String, a: Int, b: Int) -> Int { 7 }` called from +`main` prints `7` on the interpreter and on Bun-ESM, but `1024` on core wasm +(`1040` with #830). That number is the heap address of the intrinsic's +substring. `wasm-tools print` shows the user's function compiled as func 1, +which `main` never calls. Cause: `gen_expr` in `lib/codegen.ml` intercepts 20 +names by spelling (`ExprVar id when id.name = "…"`) before checking whether +the name resolves to a user declaration. + +Classification:: +*Soundness hole*: a silent wrong value on a supported path. Fixed on `main` by +#841 (`0cf73b2`), which `docs/SOUNDNESS.adoc` records as `fixed`. #841 guards +all 26 arms through `intrinsic_callee`: a name the program defines wins, and +an `extern fn` keeps its lowering. An earlier version of this PR pinned the +hole with an xfail test. The pin was dropped when #841 landed. + +Recommended fix (*most elegant and correct*):: +Tag builtin calls at resolution and match on the tag in codegen, so a user +declaration always shadows the builtin. + +Most dependable:: +Add a per-arm `not (is_user_defined …)` guard, with one run test per name. + +Stop-gap:: +Refuse a user top-level declaration that reuses an intercepted name on wasm. + +== 6. Intrinsics used as values on Bun-ESM (#837) + +Evidence:: +`apply(len, "abc")` prints `3` on the interpreter. On Bun-ESM it fails with +`ReferenceError: len is not defined` at run time. Core wasm refuses it at +compile time (`UnboundVariable "len"`). + +Classification:: +Loud divergence, at the wrong phase. This is the same class as #832. + +Recommended fix (*most elegant and correct*):: +Eta-expand an intrinsic in value position in a shared pre-codegen pass, so +it becomes first-class on every backend. + +Most dependable:: +Refuse it at codegen on Bun-ESM, as wasm already does. + +== 7. A local does not shadow a top-level function on wasm (#838) + +Evidence:: +`fn helper(s: String) -> Int { 7 }` together with +`fn call(helper: fn(String) -> Int) -> Int { helper("x") }` and +`call(|s| 9)` prints `9` on the interpreter and on Bun-ESM. Core wasm printed +`7`, and so did a let-bound closure. Cause: the generic `ExprApp` arm of +`gen_expr` consulted `func_indices` before `ctx.locals`. ++ +While fixing this, a second bug appeared. The three `CallIndirect` sites looked +up the closure signature in the type section without adding it. A higher-order +function compiled before any function with that signature therefore emitted +invalid wasm. + +Classification:: +The shadowing bug is a *soundness hole* (a silent wrong value). The invalid +wasm is a loud divergence. + +Fix (*most elegant and correct*, implemented in #840, merged):: +Look up locals first in the call arm, as the `ExprVar` paths already do. Add +one `intern_type` helper and use it at all three `CallIndirect` sites. This +changes which function a call reaches only where wasm disagreed with the +interpreter and Bun-ESM. A name that is not a local resolves as before. Four +run tests fail on `ee211d3` and pass since #840 (`c2a5493`). + +== 8. A named function passed as a value fails to compile on wasm (#839) + +Evidence:: +`call(nine)`, where `nine` is a top-level function, fails to compile on core +wasm with `UnboundVariable "nine"`. The interpreter and Bun-ESM print `9`. + +Classification:: +Loud divergence (a compile-time refusal). + +Recommended fix (*most elegant and correct*):: +Lower a named function in value position to a closure with a null +environment, plus a trampoline that drops the environment argument. This +reuses the existing `(func_id, env_ptr)` ABI, and the same pass would serve +#837. + +Most dependable:: +Keep the refusal, but name the cause and the workaround (`|s| nine(s)`). + +== Reaching beyond this repo + +* #834 tracks rebuilding core-wasm artefacts built before #830 in other +estate repos. In this repo, `editors/vscode/out/extension.cjs` is confirmed +affected and also stale. +* The decision on #831 changes what Bun-ESM consumers across the estate +observe. + +== Possible proof work + +The #830 invariant (`heap_base >= data_end`, the heap pointer only +increases, and every allocation is at or above the heap pointer) is a +two-line lemma over the bump allocator. It belongs next to the existing K-1 +codegen-preservation work in `formal/`, as a frame property: _no store +issued by heap allocation aliases a data segment_. It is not claimed here. +The implementation fix is test-anchored, not proved. diff --git a/lib/codegen.ml b/lib/codegen.ml index c2931a62..0b04b284 100644 --- a/lib/codegen.ml +++ b/lib/codegen.ml @@ -184,6 +184,128 @@ let import_func_count (ctx : context) : int = | _ -> acc ) 0 ctx.imports +(* ── Linear-memory layout (core-wasm) ────────────────────────────────── + + Every core-wasm module this backend emits uses one linear memory, laid + out in three disjoint regions: + + [0, scratch_end) runtime scratch: the WASI iovec / + nwritten words and the int-to-string + buffer that [Wasi_runtime] writes at + fixed low addresses + [static_data_base, data_end) static data: every active data + segment (string literals), laid out + contiguously by [gen_literal] + [heap_base, …) heap: the bump allocator behind the + heap-pointer global + + with heap_base = align8 (max scratch_end data_end). + + INVARIANT (no allocation overlaps a static data segment): the heap + pointer is initialised to heap_base and only ever increases, so every + heap address is >= data_end. [finalise_memory_layout] computes + heap_base from the data segments actually emitted, after the whole + module has been generated, and refuses (compile-time error) a module + whose segments overlap one another, dip into the scratch region, or + reach heap_base. There is no `memory.grow` path; heap exhaustion past + the module's pages is a wasm out-of-bounds trap (loud), never a write + into the static region. + + Before this, the heap global was initialised to a fixed 1024 while + literals were laid out from a fixed 2048, so any program that bump- + allocated more than ~1 KiB overwrote its own string literals (60 + concatenated `println`s printed 21 correct lines, then + `label_number_22abe`, then trapped). *) + +(** End of the fixed-address runtime scratch region. *) +let scratch_end = 1024 + +(** First address of the static data (string literal) region. *) +let static_data_base = scratch_end + +(** Heap alignment, in bytes. 8 keeps f64 boxes and i64 scratch aligned. *) +let heap_align = 8 + +let wasm_page_size = 65536 + +let align_up (n : int) (a : int) : int = (n + a - 1) / a * a + +(** Computed layout of a module's linear memory. *) +type memory_layout = { + ml_data_end : int; (** one past the last byte of any data segment *) + ml_heap_base : int; (** initial heap pointer; >= ml_data_end, aligned *) + ml_min_pages : int; (** initial memory size, covering [0, heap_base) *) +} + +(** Compute the layout from the data segments a module will carry, and + check the invariant. [Error] means the backend produced an + overlapping layout: an internal compiler bug, reported loudly rather + than emitted as a module that corrupts itself. *) +let memory_layout_of_datas (datas : data list) : memory_layout result = + let segs = + List.sort compare + (List.map (fun d -> (d.d_offset, d.d_offset + Bytes.length d.d_data)) datas) + in + let rec check_disjoint = function + | (_, e1) :: (((s2, _) :: _) as rest) -> + if s2 < e1 then + Error (UnsupportedFeature (Printf.sprintf + "internal error (wasm memory layout): data segments overlap at \ + offset %d" s2)) + else check_disjoint rest + | _ -> Ok () + in + let* () = check_disjoint segs in + let* () = + match segs with + | (s, _) :: _ when s < scratch_end -> + Error (UnsupportedFeature (Printf.sprintf + "internal error (wasm memory layout): data segment at offset %d lies \ + in the runtime scratch region [0, %d)" s scratch_end)) + | _ -> Ok () + in + let data_end = List.fold_left (fun acc (_, e) -> max acc e) 0 segs in + let heap_base = align_up (max scratch_end data_end) heap_align in + let min_pages = max 1 ((heap_base + wasm_page_size - 1) / wasm_page_size) in + if heap_base < data_end then + (* Unreachable by construction; kept as the named, tested check. *) + Error (UnsupportedFeature (Printf.sprintf + "internal error (wasm memory layout): heap base %d is below the end of \ + static data %d" heap_base data_end)) + else Ok { ml_data_end = data_end; ml_heap_base = heap_base; + ml_min_pages = min_pages } + +(** Check an emitted module against the layout invariant: the heap + pointer global (if any) starts at or above the end of every data + segment, and the initial memory covers all static data. This is the + check the regression suite runs over compiled fixtures. *) +let check_memory_layout ?heap_global (m : wasm_module) : unit result = + let* layout = memory_layout_of_datas m.datas in + let* () = + match heap_global with + | None -> Ok () + | Some idx -> + (match List.nth_opt m.globals idx with + | Some { g_init = [I32Const base]; _ } -> + let base = Int32.to_int base in + if base < layout.ml_data_end then + Error (UnsupportedFeature (Printf.sprintf + "internal error (wasm memory layout): heap base %d is below the \ + end of static data %d; allocations would overwrite literals" + base layout.ml_data_end)) + else Ok () + | _ -> + Error (UnsupportedFeature + "internal error (wasm memory layout): heap pointer global is not \ + an i32 constant")) + in + match m.mems with + | [{ mem_type = { lim_min; _ } }] when lim_min * wasm_page_size < layout.ml_data_end -> + Error (UnsupportedFeature (Printf.sprintf + "internal error (wasm memory layout): %d page(s) of memory do not hold \ + static data ending at %d" lim_min layout.ml_data_end)) + | _ -> Ok () + (** Create initial context *) let create_context () : context = { types = []; @@ -210,7 +332,7 @@ let create_context () : context = { fn_ret_structs = []; variant_tags = []; string_data = []; - next_string_offset = 2048; (* Start strings after heap at offset 2048 *) + next_string_offset = static_data_base; (* literals: see "Linear-memory layout" *) datas = []; ownership_annots = []; wasi_func_indices = []; @@ -425,12 +547,15 @@ let ensure_heap_ptr (ctx : context) : (context * int) = match ctx.heap_ptr with | Some idx -> (ctx, idx) | None -> - (* Create heap pointer global initialized to 1024 (1KB) *) + (* Create the heap pointer global. Its initialiser is a placeholder: + [finalise_memory_layout] overwrites it with the real heap base + (the aligned end of the static data region) once every literal + has been laid out. See "Linear-memory layout". *) let idx = List.length ctx.globals in let heap_global = { g_type = I32; g_mutable = true; - g_init = [I32Const 1024l]; (* Start heap at 1KB *) + g_init = [I32Const (Int32.of_int static_data_base)]; } in ({ ctx with globals = ctx.globals @ [heap_global]; @@ -4682,11 +4807,25 @@ let generate_module ?loader (prog : program) : wasm_module result = [] in - Ok { + (* Linear-memory layout: place the heap after the last static data + segment and size the initial memory to cover it. Done here, after + every literal has been laid out, so the heap base is computed from + the segments actually emitted rather than assumed. *) + let* layout = memory_layout_of_datas ctx'.datas in + let final_globals = + match ctx'.heap_ptr with + | None -> final_globals + | Some hidx -> + List.mapi (fun i g -> + if i = hidx then + { g with g_init = [I32Const (Int32.of_int layout.ml_heap_base)] } + else g) final_globals + in + let m = { types = final_types; funcs = final_funcs; tables = tables; - mems = [{ mem_type = { lim_min = 1; lim_max = None } }]; (* 1 page default *) + mems = [{ mem_type = { lim_min = layout.ml_min_pages; lim_max = None } }]; globals = final_globals; exports = final_exports; imports = ctx'.imports; @@ -4694,4 +4833,6 @@ let generate_module ?loader (prog : program) : wasm_module result = datas = List.rev ctx'.datas; (* Reverse to get original order *) start = None; custom_sections; - } + } in + let* () = check_memory_layout ?heap_global:ctx'.heap_ptr m in + Ok m diff --git a/test/test_main.ml b/test/test_main.ml index 777d038a..745e857b 100644 --- a/test/test_main.ml +++ b/test/test_main.ml @@ -42,6 +42,7 @@ let () = ("float_to_string format (#643)", Test_float_format.tests); ("Wasm call resolution", Test_wasm_call_resolution.tests); ("User fn named like an intrinsic (#836)", Test_intrinsic_shadow.tests); + ("Wasm heap/literal layout", Test_wasm_heap_layout.tests); ("ESM runtime pruning", Test_runtime_prune.tests); ("Stdlib algebraic laws (batch 1)", Test_stdlib_laws.tests); ("Solo CESK (VM M1, ADR-0025)", Test_solo_cesk.tests); diff --git a/test/test_wasm_heap_layout.ml b/test/test_wasm_heap_layout.ml new file mode 100644 index 00000000..9d25c306 --- /dev/null +++ b/test/test_wasm_heap_layout.ml @@ -0,0 +1,214 @@ +(* SPDX-License-Identifier: MPL-2.0 *) +(* SPDX-FileCopyrightText: 2026 hyperpolymath *) + +(** Core-wasm linear-memory layout: no heap allocation may overlap a + static data segment. + + The hole: the heap-pointer global started at a fixed 1024 while + string literals were laid out from a fixed 2048, so a program that + bump-allocated more than ~1 KiB overwrote its own literals. Sixty + `println("label_number_N" ++ " ok")` calls printed 21 correct lines, + then `label_number_22abe`, then trapped out of bounds; the + interpreter printed all sixty. Found by the Unicode thread (#829). + + The fix ([Codegen.memory_layout_of_datas] / [check_memory_layout]): + the heap base is computed after code generation as the aligned end + of the last data segment, and the module is refused if the + invariant does not hold. + + Three kinds of test: + - layout: the check refuses the old layout and accepts the new one; + - static: every compiled fixture satisfies heap base >= data end; + - run: the compiled wasm runs under Bun's WASI and every literal is + printed intact after heavy allocation. These SKIP (pass, with a + message) where `bun` is not installed, as CI's coverage job is. *) + +open Affinescript + +(* The CLI's wasm pipeline: resolve, typecheck (which records String `++` + sites), elaborate them to byte concatenation, fold, generate. *) +let compile src = + let prog = Parse_driver.parse_string ~file:"" src in + let loader = Module_loader.create (Module_loader.default_config ()) in + match Resolve.resolve_program_with_loader prog loader with + | Error (e, _) -> Alcotest.failf "resolve: %s" (Resolve.show_resolve_error e) + | Ok (rctx, itc) -> + match Typecheck.check_program ~import_types:itc.Typecheck.name_types + rctx.symbols prog with + | Error e -> Alcotest.failf "typecheck: %s" (Typecheck.format_type_error e) + | Ok _ -> + let prog = Opt.fold_constants_program + (Typecheck.elaborate_string_concat prog) in + match Codegen.generate_module ~loader prog with + | Ok m -> m + | Error e -> Alcotest.failf "codegen: %s" (Codegen.show_codegen_error e) + +let seg offset len : Wasm.data = + { Wasm.d_data = Bytes.make len 'x'; d_offset = offset } + +let i32_global n : Wasm.global = + { Wasm.g_type = Wasm.I32; g_mutable = true; g_init = [Wasm.I32Const (Int32.of_int n)] } + +let module_with ~heap_init ~datas : Wasm.wasm_module = + { (Wasm.empty_module ()) with + Wasm.globals = [i32_global heap_init]; + mems = [{ Wasm.mem_type = { Wasm.lim_min = 1; lim_max = None } }]; + datas } + +let data_end (m : Wasm.wasm_module) = + List.fold_left (fun acc (d : Wasm.data) -> + max acc (d.d_offset + Bytes.length d.d_data)) 0 m.datas + +(* The sixty-line reproduction from #829. *) +let repro_src = + let b = Buffer.create 4096 in + Buffer.add_string b "fn main() -> () {\n"; + for i = 1 to 60 do + Buffer.add_string b + (Printf.sprintf " println(\"label_number_%d\" ++ \" ok\");\n" i) + done; + Buffer.add_string b "}\n"; + Buffer.contents b + +let repro_expected = + List.init 60 (fun i -> Printf.sprintf "label_number_%d ok" (i + 1)) + +(* Allocates ~40 KiB (100 growing concatenations), well past 1 KiB but + inside the module's one page, then prints every literal again. *) +let alloc_src iterations = Printf.sprintf {|fn main() -> () { + println("before_alpha"); + let mut i = 0; + let mut acc = ""; + while i < %d { + acc = acc ++ "abcdefgh"; + i = i + 1; + } + println(int_to_string(len(acc))); + println("after_beta"); + println("after_gamma_with_a_longer_literal_body"); + println("before_alpha"); +} +|} iterations + +let alloc_expected = + [ "before_alpha"; "800"; "after_beta"; + "after_gamma_with_a_longer_literal_body"; "before_alpha" ] + +(* ---- layout ---------------------------------------------------------- *) + +(* The check itself: it must refuse the old layout (heap at 1024, a + literal at 2048) and accept a heap placed after the data. *) +let test_wasm_heap_base_below_data_end_refused () = + let old_layout = module_with ~heap_init:1024 ~datas:[seg 2048 64] in + (match Codegen.check_memory_layout ~heap_global:0 old_layout with + | Error _ -> () + | Ok () -> Alcotest.fail "heap base 1024 below data end 2112 was accepted"); + let fixed = module_with ~heap_init:2112 ~datas:[seg 2048 64] in + (match Codegen.check_memory_layout ~heap_global:0 fixed with + | Ok () -> () + | Error e -> Alcotest.failf "a heap after the data was refused: %s" + (Codegen.show_codegen_error e)); + (* Overlapping segments and segments in the scratch region are refused. *) + (match Codegen.memory_layout_of_datas [seg 1024 16; seg 1030 4] with + | Error _ -> () + | Ok _ -> Alcotest.fail "overlapping data segments were accepted"); + (match Codegen.memory_layout_of_datas [seg 16 4] with + | Error _ -> () + | Ok _ -> Alcotest.fail "a data segment in the scratch region was accepted"); + (* Static data larger than a page is covered by the initial memory. *) + match Codegen.memory_layout_of_datas [seg 1024 70000] with + | Error e -> Alcotest.failf "layout: %s" (Codegen.show_codegen_error e) + | Ok l -> + Alcotest.(check bool) "heap base >= data end" true (l.ml_heap_base >= l.ml_data_end); + Alcotest.(check int) "heap base is 8-aligned" 0 (l.ml_heap_base mod 8); + Alcotest.(check bool) "pages cover the heap base" true + (l.ml_min_pages * 65536 >= l.ml_heap_base) + +(* ---- static ---------------------------------------------------------- *) + +(* Every compiled program satisfies the invariant: one global starts at + the computed heap base, none starts inside the static data region, and + the initial memory holds all of it. *) +let test_wasm_heap_after_literals_static () = + List.iter (fun (what, src) -> + let m = compile src in + let dend = data_end m in + Alcotest.(check bool) (what ^ ": has literals past 1 KiB") true (dend > 1024); + match Codegen.memory_layout_of_datas m.datas with + | Error e -> Alcotest.failf "%s: %s" what (Codegen.show_codegen_error e) + | Ok l -> + let inits = List.filter_map (fun (g : Wasm.global) -> + match g.g_init with + | [Wasm.I32Const n] when g.g_mutable -> Some (Int32.to_int n) + | _ -> None) m.globals in + Alcotest.(check bool) (what ^ ": heap global starts at the heap base") + true (List.mem l.ml_heap_base inits); + Alcotest.(check bool) (what ^ ": no mutable global starts inside static data") + false (List.exists (fun n -> n >= Codegen.static_data_base && n < dend) inits); + (match m.mems with + | [{ Wasm.mem_type = { lim_min; _ } }] -> + Alcotest.(check bool) (what ^ ": memory covers static data") true + (lim_min * 65536 >= dend) + | _ -> Alcotest.failf "%s: expected one memory" what)) + [ ("repro", repro_src); ("alloc", alloc_src 100) ] + +(* ---- run under Bun's WASI --------------------------------------------- *) + +let bun_available () = Sys.command "bun --version > /dev/null 2>&1" = 0 + +let run_wasm (m : Wasm.wasm_module) : string list * Unix.process_status = + let file = Filename.temp_file "wasm_heap_layout" ".wasm" in + Wasm_encode.write_module_to_file file m; + let ic = Unix.open_process_in + ("bun run " ^ Filename.quote file ^ " 2>/dev/null") in + let rec read acc = + match input_line ic with + | l -> read (l :: acc) + | exception End_of_file -> List.rev acc + in + let lines = read [] in + let st = Unix.close_process_in ic in + (try Sys.remove file with Sys_error _ -> ()); + (lines, st) + +let skip_without_bun name f () = + if bun_available () then f () + else Printf.printf "SKIP %s: bun not installed\n%!" name + +(* The #829 reproduction prints all sixty lines, exactly as the + interpreter does, and exits 0. *) +let test_wasm_heap_repro_runs () = + let lines, st = run_wasm (compile repro_src) in + Alcotest.(check (list string)) "all sixty literals intact" repro_expected lines; + Alcotest.(check bool) "exit 0" true (st = Unix.WEXITED 0) + +(* ~40 KiB of allocation, then every literal is printed intact. *) +let test_wasm_heap_literals_intact_after_alloc () = + let lines, st = run_wasm (compile (alloc_src 100)) in + Alcotest.(check (list string)) "literals intact after allocation" + alloc_expected lines; + Alcotest.(check bool) "exit 0" true (st = Unix.WEXITED 0) + +(* Past the module's single page there is no memory.grow: exhaustion is + a loud out-of-bounds trap, never a write into the literal region. The + literal printed before the loop is intact and nothing after it is + printed. If a growth path is added, this test changes to expect the + full output. *) +let test_wasm_heap_exhaustion_traps () = + let lines, st = run_wasm (compile (alloc_src 400)) in + Alcotest.(check (list string)) "only the pre-loop literal, intact" + [ "before_alpha" ] lines; + Alcotest.(check bool) "non-zero exit (trap)" true (st <> Unix.WEXITED 0) + +let tests = [ + Alcotest.test_case "heap base below data end is refused" `Quick + test_wasm_heap_base_below_data_end_refused; + Alcotest.test_case "compiled heap starts after literals" `Quick + test_wasm_heap_after_literals_static; + Alcotest.test_case "#829 repro: 60 literals intact (bun)" `Quick + (skip_without_bun "repro" test_wasm_heap_repro_runs); + Alcotest.test_case "literals intact after 40 KiB of allocation (bun)" `Quick + (skip_without_bun "alloc" test_wasm_heap_literals_intact_after_alloc); + Alcotest.test_case "heap exhaustion traps loudly (bun)" `Quick + (skip_without_bun "exhaustion" test_wasm_heap_exhaustion_traps); +] diff --git a/tools/soundness-anchors.sha256 b/tools/soundness-anchors.sha256 index 58f6020c..a0fc409a 100644 --- a/tools/soundness-anchors.sha256 +++ b/tools/soundness-anchors.sha256 @@ -8,15 +8,21 @@ 2bbd1b989fd0097530eede3e5230258e0e1092271a23ff7dff20cca65c0e612e suite:test/test_wasm_call_resolution.ml 2dfe36a21983a7dfb7ffa1157f7ddec9865a531a92682976b8fd677e4825e78d test:test_801_impl_methods_refused 3b74c20f201d0d53c2fbab5582a681d3dfc3cf978a0aea676ecc6400087452d9 suite:test/test_intrinsic_shadow.ml +45eb0f3aa5f643afbd003248998dd5a046688418647b491e0f2d4bb55fcbd0f2 test:test_wasm_heap_exhaustion_traps 546939eaa3c64c82edd23da0a3ba7f74bcf7378cfe1e426132dd1a9f8fd46050 test:test_801_transitive_public_and_const 5b84a4f71aa65f9aa9383e31c0cb624291c4f9d0de7cca4a0ea6a76fe85aea35 fixture:test/e2e/fixtures/handle_resume_nontail.affine +61a824a9bbd1243c27aab2687e7ef0da1afdfd208cd26187908797f16adad163 test:test_wasm_heap_repro_runs 68f0f4ad2462f146b87f491b7456aff9a56b77397344d22c62f4f4ff5ca6e3ae fixture:test/e2e/fixtures/assume_rejected.affine 6dc672457b5dc5840e58a5d5014d192c459d038ab57f9b09fa3234a1e3df985c test:test_wasm_unshadowed_fn_still_direct +74c7d6f7b9bc62f6781267b2544557e39171232f4eaa80fca5e7bc1458c8258d test:test_wasm_heap_after_literals_static +755533123e155bb5022dc50a2da1051e6ed7c6db32ed8ad0c0f6afc88552b91f suite:test/test_wasm_heap_layout.ml +77da9fd1a02d0c585d3a851b4f513cf678e0f94f084dc5e1719ab29efcf15e15 test:test_wasm_heap_base_below_data_end_refused 7f416f186a15511ec5c64d2b96bfffbdf9e7c8c0879951d56c80e46129e2ea48 test:test_stub_backend_return_fenced 80541ee00580b4dccee4657cbd31d11a1ddaa18cc49813b48f686c9509f314dc suite:test/test_borrow_polonius.ml 832d4c8b64176706535334a5dbbb16345f42b75ac9b1a93f0a5dc371d84b5a0d test:test_801_same_name_in_two_modules 874a5531cd8bc402adf4b66277b21b15d921efe06a7128ea6583bcd6e55781ba test:test_resume_nontail_xfail 89b920568ab703102c224d40a1846efef67d60b88aed4cddc9a84e6f095a47d1 suite:test/test_block_scope.ml +94b346ae2d57068c6096411126b2e4dc9cc6da83816056339079cf3811629deb test:test_wasm_heap_literals_intact_after_alloc ac1da10c3206605304f11e869f6aa07acba57f6f8248bb2dfacca19984f86c31 test:test_coherence_duplicate_rejected ad1e66df361641660125a84fb4694785357d542b0a7856de8f28e4d81f8635b5 test:test_wasm_let_shadows_fn b76c7824a9b1570d66752359a28d75ebdfaedb5de5ad68c343a0a2c26ad4221c fixture:test/e2e/fixtures/async_sync_fallback.affine