Skip to content

Commit ea3333b

Browse files
committed
fix(codegen): start the wasm heap after the last data segment (#830)
The core-wasm heap-pointer global was initialised to a fixed 1024 while string literals were laid out from a fixed 2048, so any program that bump-allocated more than ~1 KiB overwrote its own literals: #829's 60-concatenation repro printed 21 lines, then `label_number_22abe`, then trapped out of bounds. The interpreter printed all 60. Fix at source in lib/codegen.ml ("Linear-memory layout"): - literals start at static_data_base (= scratch_end = 1024); - after code generation, memory_layout_of_datas computes data_end from the emitted segments, and the heap global is set to align8(max(scratch_end, data_end)); the memory's initial page count covers it; - check_memory_layout refuses (compile-time error) any module whose heap base is below the end of static data, whose segments overlap or dip into the scratch region, or whose memory does not hold the static data. There is no memory.grow path; heap exhaustion stays a loud OOB trap. Tests: test/test_wasm_heap_layout.ml (layout check, static layout of compiled programs, and under Bun's WASI: the #829 repro, literals intact after ~40 KiB of allocation, exhaustion traps loudly). Three fail on the old layout; the gate alone refuses the old layout at compile time. Docs: docs/WASM-MEMORY-LAYOUT.adoc (invariant), SOUNDNESS.adoc row #830 (stamp ee211d3, resealed), audit of the other #829 divergences in docs/reports/AUDIT-2026-12-01-backend-divergences.adoc (follow-ups Closes #830 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01J4QvDjPsKtu8zU9b32Cv1P
1 parent c2a5493 commit ea3333b

8 files changed

Lines changed: 725 additions & 7 deletions

File tree

‎.machine_readable/descriptiles/STATE.deed‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,3 +256,14 @@ landed = [
256256
"docs: bindings/stdlib/alib roadmap Tracking sections de-staled to live umbrellas #446/#412/#413"
257257
]
258258
umbrella-446 = "stays open — STEP 1-3 done, STEP 4/5 long-running"
259+
260+
[[session-delta]]
261+
# Appended 2026-12-01 — core-wasm heap/literal overlap fix (#830).
262+
# Mirror entry only; soundness status is docs/SOUNDNESS.adoc (row #830).
263+
date = "2026-12-01"
264+
issue = "#830"
265+
landed = [
266+
"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)",
267+
"tests: test/test_wasm_heap_layout.ml (layout check, static layout, #829 repro + 40 KiB allocation + exhaustion under Bun WASI)",
268+
"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)"
269+
]

‎docs/SOUNDNESS.adoc‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
// Freshness stamp — a real main-ancestor commit (survives squash-merge); advance
55
// it (and --reseal) in any change that touches a soundness path. See "Keeping
66
// this honest" and tools/check-soundness-ledger.sh (property 4).
7-
:ground-truth-sha: ee211d3
7+
:ground-truth-sha: c2a5493
88
:ground-truth-date: 2026-12-01
99
:stamp-verified-by: tools/check-soundness-ledger.sh
1010
:toc: macro
@@ -252,6 +252,26 @@ function compiled before its closure signature existed emit invalid wasm.
252252
| `test/test_wasm_call_resolution.ml` (`test_wasm_param_shadows_fn`,
253253
`test_wasm_let_shadows_fn`, `test_wasm_unshadowed_fn_still_direct`,
254254
`test_wasm_call_indirect_type_interned` — all four fail on `ee211d3`)
255+
256+
| #830
257+
| Core-wasm heap allocations can no longer overwrite string literals. The
258+
heap-pointer global used to start at a fixed 1024 while literals were laid
259+
out from a fixed 2048, so a program that allocated more than ~1 KiB
260+
silently corrupted its own literals (#829's 60-line repro printed 21 lines,
261+
then `label_number_22abe`, then trapped). The heap base is now computed
262+
after code generation as the 8-aligned end of the last data segment, the
263+
initial memory covers it, and `generate_module` refuses (compile-time
264+
error) any module whose heap base lies below the end of static data. There
265+
is no `memory.grow`; exhausting the heap is an out-of-bounds trap, not a
266+
write into the literal region. Layout invariant:
267+
`docs/WASM-MEMORY-LAYOUT.adoc`.
268+
| `fixed`
269+
| `test/test_wasm_heap_layout.ml` (`test_wasm_heap_base_below_data_end_refused`
270+
— the gate refuses the old layout; `test_wasm_heap_after_literals_static`;
271+
`test_wasm_heap_repro_runs` and
272+
`test_wasm_heap_literals_intact_after_alloc` — run under Bun's WASI;
273+
`test_wasm_heap_exhaustion_traps`); `lib/codegen.ml`
274+
`memory_layout_of_datas` / `check_memory_layout`
255275
|===
256276

257277
== Still open — read before claiming "sound"

‎docs/WASM-MEMORY-LAYOUT.adoc‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
// SPDX-License-Identifier: CC-BY-SA-4.0
2+
// SPDX-FileCopyrightText: 2026 hyperpolymath
3+
= Core-Wasm Linear-Memory Layout
4+
:toc: macro
5+
:icons: font
6+
7+
This page describes how the core-wasm backend (`lib/codegen.ml`) lays out
8+
the single linear memory of every module it emits. It also states the
9+
invariant that the layout must keep. The status of the hole this invariant
10+
closes (#830) is recorded in link:SOUNDNESS.adoc[SOUNDNESS.adoc], and that
11+
ledger is the authority for it.
12+
13+
toc::[]
14+
15+
== Regions
16+
17+
[cols="2,2,5",options="header"]
18+
|===
19+
| Region | Range | Contents
20+
21+
| Runtime scratch
22+
| `[0, scratch_end)` = `[0, 1024)`
23+
| Fixed-address words that `lib/wasi_runtime.ml` writes: the WASI iovec,
24+
the `nwritten` cell and the int-to-string buffer.
25+
26+
| Static data
27+
| `[static_data_base, data_end)`, with `static_data_base = 1024`
28+
| Every active data segment. Today these are string literals, each stored as
29+
`[len: i32][utf8 bytes]` and laid out one after another by `gen_literal`.
30+
31+
| Heap
32+
| `[heap_base, …)`
33+
| The bump allocator behind the heap-pointer global: strings built at run
34+
time, arrays, tuples, records, closures, `float_to_string` buffers and
35+
clock scratch.
36+
|===
37+
38+
`heap_base = align8(max(scratch_end, data_end))`. The initial memory size is
39+
`max(1, ceil(heap_base / 65536))` pages.
40+
41+
== Invariant
42+
43+
*No heap allocation overlaps a static data segment.*
44+
45+
The heap pointer starts at `heap_base`. Allocation only ever increases it,
46+
so every heap address is at least `data_end`.
47+
48+
The constants and functions that keep this invariant are in `lib/codegen.ml`,
49+
under _Linear-memory layout (core-wasm)_:
50+
51+
`memory_layout_of_datas`::
52+
Computes `data_end`, `heap_base` and the page count from the data segments
53+
the module actually carries. It returns an error if two segments overlap or
54+
if a segment lies in the scratch region.
55+
56+
`generate_module`::
57+
Calls `memory_layout_of_datas` after code generation has finished, so every
58+
literal has already been laid out. It then patches the heap-pointer global
59+
to `heap_base` and sizes the memory.
60+
61+
`check_memory_layout`::
62+
Runs on the finished module. It refuses the module with a compile-time
63+
error if the heap global starts below `data_end`, or if the initial memory
64+
does not hold the static data.
65+
66+
An error from either check is an internal compiler error. It is reported
67+
loudly. The compiler never emits a module that would corrupt itself.
68+
69+
== Memory growth
70+
71+
The backend never emits `memory.grow`. If a program allocates past the end
72+
of the module's pages, the access is a wasm out-of-bounds trap. That is a
73+
loud failure, and it never writes into the static region.
74+
75+
If a growth path is added, it must grow memory in place (as `memory.grow`
76+
does) and must not move or reuse `[static_data_base, heap_base)`. When that
77+
happens, `test_wasm_heap_exhaustion_traps` should be changed to expect the
78+
full output.
79+
80+
== History
81+
82+
Before #830 the heap global was initialised to a fixed 1024, and literals
83+
were laid out from a fixed 2048. Any program that allocated more than about
84+
1 KiB overwrote its own literals. In #829's reproduction, 60 concatenated
85+
`println` calls printed 21 correct lines, then `label_number_22abe`, then
86+
trapped.
87+
88+
== Tests
89+
90+
All of these are in `test/test_wasm_heap_layout.ml`, which runs as part of
91+
`dune runtest`. The run tests SKIP when `bun` is not installed.
92+
93+
* `test_wasm_heap_base_below_data_end_refused`: the check refuses the old
94+
layout, overlapping segments, and a segment in the scratch region.
95+
* `test_wasm_heap_after_literals_static`: compiled programs start the heap at
96+
`heap_base`, and their memory covers the static data.
97+
* `test_wasm_heap_repro_runs`: #829's reproduction prints all 60 lines.
98+
* `test_wasm_heap_literals_intact_after_alloc`: after about 40 KiB of
99+
allocation, every literal is still intact.
100+
* `test_wasm_heap_exhaustion_traps`: allocating past the page traps loudly.
101+
102+
== Built artefacts
103+
104+
Wasm built by an older compiler still has the overlapping layout, and
105+
recompiling it fixes that. To check a module, read its heap global and its
106+
data segments with `wasm-tools print`. If the module has a mutable i32
107+
global initialised to `1024` and data segments starting at `2048`, it was
108+
built before the fix. This includes `editors/vscode/out/extension.cjs`,
109+
which embeds such a module. The estate tracking note is #834.
Lines changed: 216 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,216 @@
1+
// SPDX-License-Identifier: CC-BY-SA-4.0
2+
// SPDX-FileCopyrightText: 2026 hyperpolymath
3+
= Backend Divergence Audit (2026-12-01)
4+
:toc: macro
5+
:icons: font
6+
7+
This audit follows the #830 fix. The Unicode thread (#829) found several ways
8+
the backends disagree. The owner asked whether any of the others needs the
9+
same at-source treatment as the wasm heap/literal overlap.
10+
11+
Each finding below was reproduced on `main` `ee211d3` with the built compiler.
12+
For each one, the audit records the evidence, a classification and a
13+
recommended fix. The PR that adds this audit implements only #830. The other
14+
findings are filed as issues. Those that change language semantics are marked
15+
for the owner's review.
16+
17+
Soundness-hole status is recorded in link:../SOUNDNESS.adoc[SOUNDNESS.adoc], and
18+
that ledger is the authority for it. This report is a dated input to it.
19+
20+
toc::[]
21+
22+
== Classification used
23+
24+
Soundness hole::
25+
A well-typed program silently gets a wrong value or corrupts state on a
26+
supported path.
27+
28+
Silent divergence::
29+
Backends give different observable results for the same well-typed program,
30+
and nothing fails.
31+
32+
Loud divergence::
33+
A backend refuses or crashes on a well-typed program that another backend
34+
runs. This breaks progress for that backend, but it never gives a
35+
plausible-wrong result.
36+
37+
== Summary
38+
39+
[cols="3,2,2,2",options="header"]
40+
|===
41+
| Finding | Class | Changes semantics? | Tracking
42+
43+
| Core-wasm heap overlaps string literals
44+
| *Soundness hole*: silent memory corruption
45+
| No
46+
| #830 (fixed in this PR); estate rebuilds #834
47+
48+
| String indices are octets on interp/wasm but UTF-16 units on Bun-ESM
49+
| Silent divergence
50+
| *Yes*: owner decision
51+
| #831
52+
53+
| Plain-JS backend has no string builtins (run-time `ReferenceError`)
54+
| Loud divergence, at the wrong phase
55+
| No
56+
| #832
57+
58+
| `eval` rejects self-recursion, forward and mutual references, and `let mut`
59+
| Loud divergence (the reference interpreter)
60+
| No
61+
| #833
62+
|===
63+
64+
== 1. Core-wasm heap overlaps string literals (#830)
65+
66+
Evidence::
67+
Sixty `println("label_number_N" ++ " ok")` calls, compiled to wasm and run
68+
with `bun run`, printed 21 correct lines, then `label_number_22abe`, then
69+
`RuntimeError: Out of bounds memory access`. `affinescript eval` printed all
70+
60 lines. Cause: the heap global was initialised to a fixed `1024`, and
71+
literals were laid out from a fixed `2048`.
72+
73+
Classification::
74+
Soundness hole: silent corruption of static data. The trap comes only after
75+
the corrupted line has been printed.
76+
77+
Fix (implemented)::
78+
The heap base is computed after code generation as the 8-aligned end of the
79+
last data segment, and the memory is sized to cover it. The module is
80+
refused if the heap base is below the end of static data. See
81+
link:../WASM-MEMORY-LAYOUT.adoc[WASM-MEMORY-LAYOUT.adoc].
82+
+
83+
Alternatives considered:
84+
+
85+
* Bounds-checked allocation with `memory.grow`. This is needed eventually,
86+
but on its own it would not move the heap off the literals.
87+
* A separate memory for literals (multi-memory). This is not yet supported
88+
by every target host.
89+
* Literals in a WasmGC `array i8`. That is only possible on the GC backend.
90+
+
91+
Computing the layout from the emitted segments was chosen because it makes
92+
the invariant structural and checks it in one place.
93+
94+
== 2. String index units differ by backend (#831)
95+
96+
Evidence::
97+
+
98+
[cols="3,1,1,1",options="header"]
99+
|===
100+
| Probe | interp | core wasm | Bun-ESM
101+
| `len("é")` | 2 | 2 | 1
102+
| `len("🦜")` | 4 | 4 | 2
103+
| `string_char_code_at("🦜", 0)` | 240 | 240 | 55358
104+
|===
105+
+
106+
`lib/codegen_deno.ml:1240` lowers `len` to JS `.length`. `string_get` and
107+
`string_sub` (`:1244-1245`) use JS indices in the same way.
108+
109+
Classification::
110+
Silent divergence (#560 class). It is not a type-soundness hole, but it
111+
produces the same kind of wrong answer: the same program prints different
112+
numbers on different backends.
113+
114+
Recommended fix (*most elegant and correct*)::
115+
Use octet offsets everywhere, with boundary checks. `len` counts UTF-8 octets
116+
on every backend. `string_get` and `string_sub` fail loudly when an offset is
117+
not on a character boundary. Code that works with characters moves to the
118+
#829 code-point API.
119+
120+
Most dependable, type-led::
121+
Make offsets an opaque type (`Utf8Offset`) that only `find`, iteration and
122+
`utf8_byte_length` can produce. Mixing units then becomes a type error. This
123+
pairs with the recommended fix, and it is the one with a proof story: a
124+
phantom-unit argument is a short preservation lemma.
125+
126+
Outside the box::
127+
Represent `String` on Bun as a `Uint8Array` of UTF-8. All backends would then
128+
share one representation. The cost is transcoding at every JS host boundary.
129+
130+
Stop-gap::
131+
Refuse `len`, `string_get` and `string_sub` on Bun-ESM, and point to the #829
132+
API. This fails loudly, but it breaks existing Bun code.
133+
134+
Scope::
135+
This reaches beyond the repo. Estate Bun-ESM code, such as the DEED printer,
136+
counts in UTF-16 units today. The owner needs to decide.
137+
138+
== 3. Plain-JS backend has no string builtins (#832)
139+
140+
Evidence::
141+
`affinescript compile idx.affine -o idx.js` succeeds. Running the result
142+
with `node idx.js` fails with `ReferenceError: int_to_string is not defined`.
143+
`lib/js_codegen.ml:171` emits a free `ExprVar` as a bare name, and nothing
144+
checks it against what the backend provides.
145+
146+
Classification::
147+
Loud divergence, but at run time instead of compile time.
148+
149+
Recommended fix (*most elegant and correct*)::
150+
Add a closed-world check at codegen. Each text backend declares which
151+
builtins it can lower. Any free identifier that is neither bound by the
152+
program nor in that table makes codegen return `Error`. This removes the
153+
whole bug class, not only on JS.
154+
155+
Most dependable::
156+
Share the Bun-ESM builtin lowering table with `js_codegen`, so there is one
157+
source of truth.
158+
159+
Outside the box::
160+
Retire the plain-JS backend, as was done for Deno-ESM.
161+
162+
== 4. `affinescript eval` diverges from `compile` (#833)
163+
164+
Evidence::
165+
Self-recursion fails with `Runtime error: Unbound variable: g`. A forward
166+
reference fails with `Unbound variable: helper`, reported as a *type* error,
167+
and so does mutual recursion. `let mut` with `while` fails with
168+
`Type mismatch: Expected mutable reference`. The interpreter's `println`
169+
prints `"2"` with the quotes. Bun-ESM and wasm run all of these correctly.
170+
171+
Root causes::
172+
* `lib/interp.ml:1151`: a top-level closure captures the environment from
173+
before its own binding exists (there is no letrec).
174+
* `bin/main.ml:315` and `:363`: `eval` type-checks with its own fold of
175+
`check_decl`. That fold skips the forward pass in
176+
`Typecheck.check_program` (`lib/typecheck.ml:2656`).
177+
* `lib/interp.ml:507`: `StmtLet` ignores `mut`, so the cell that `assign`
178+
needs is never created.
179+
180+
Classification::
181+
Loud divergence. The reference interpreter refuses well-typed programs, and
182+
the `eval` frontend accepts less than `compile` does. No silent wrong value
183+
was found. A same-name shadowing probe is refused by the flattener (E0206).
184+
185+
Recommended fix (*most elegant and correct*)::
186+
* Make `eval` call `check_program`, so every command shares one frontend
187+
entry.
188+
* Make `eval_program` two-phase, with a recursive top-level environment.
189+
* Make `let mut` bind a `VMut` cell, make reads dereference it, and make
190+
assignment resolve to that cell.
191+
* Make `println` print the raw string.
192+
193+
Most dependable::
194+
Add a differential `eval`-versus-Bun stdout test over the codegen fixture
195+
corpus. It catches the class, not just these instances.
196+
197+
Outside the box::
198+
Move the CLI's interpreter role onto `solo_cesk`. That would also unblock
199+
#623.
200+
201+
== Reaching beyond this repo
202+
203+
* #834 tracks rebuilding core-wasm artefacts built before #830 in other
204+
estate repos. In this repo, `editors/vscode/out/extension.cjs` is confirmed
205+
affected and also stale.
206+
* The decision on #831 changes what Bun-ESM consumers across the estate
207+
observe.
208+
209+
== Possible proof work
210+
211+
The #830 invariant (`heap_base >= data_end`, the heap pointer only
212+
increases, and every allocation is at or above the heap pointer) is a
213+
two-line lemma over the bump allocator. It belongs next to the existing K-1
214+
codegen-preservation work in `formal/`, as a frame property: _no store
215+
issued by heap allocation aliases a data segment_. It is not claimed here.
216+
The implementation fix is test-anchored, not proved.

0 commit comments

Comments
 (0)