Skip to content

Commit ce00cb0

Browse files
author
Ralph Küpper
committed
Merge branch 'pr7214-merge' into pr7212-merge
2 parents 370b277 + 8d2a264 commit ce00cb0

8 files changed

Lines changed: 335 additions & 4 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
### Fixed
2+
3+
- **codegen/runtime: three more root-store holes from #7202's enumeration and #7207's review (#7209, #7208, #7215)**. Same invariant as #7207 — a GC-managed value's storage must be one the collector actually rewrites — reached three ways it had not been reached before: a slot that was *reserved and never bound*, a slot that was never reserved at all, and a raw borrow into a heap payload.
4+
5+
- **The `catch (e)` parameter (#7209)**. `collect_pointer_typed_locals` assigns the catch parameter a shadow-slot index — it is implicitly `Any`, i.e. pointer-possible — so `js_shadow_frame_enter`'s count already included it. `stmt/try_stmt.rs` allocated the storage with `alloca_entry`, stored the exception into it, and never emitted `js_shadow_slot_bind`: **the frame was sized for a root that did not exist**, `active[idx]` stayed false forever, and the collector never dereferenced the alloca. Sharper than an ordinary missing root because `js_clear_exception()` runs two lines earlier and drops the RUNTIME's own reference — from there the exception is reachable only through unrooted stack memory while arbitrary user code runs, so a precise-roots collection can **sweep** it rather than merely relocate it. Fixed with `emit_shadow_slot_bind_for_local`, which reuses the reserved index rather than growing the frame; emitted after the store rather than hoisted to entry setup, because on the non-throwing path the alloca is never written and an entry-hoisted bind would make the slot active over uninitialized stack bytes.
6+
7+
- **A closure's captured `this` / `new.target` (#7208)**. `codegen/method.rs:316` and `:1344` size their frames `m.len() + 1` and bind that extra slot to the `this` alloca; `codegen/closure.rs:589` used `m.len()` and reserved nothing, so there was no index to bind and both capture slots — plain `blk.alloca(DOUBLE)` holding a heap receiver for the whole body, read by every `ctx.this_stack.last()` consumer — were invisible to the collector. The in-tree comment exempting them ("the capture reads … run in the entry-block prologue, ahead of any statement that could collect") justifies the timing of the READ and says nothing about the lifetime of the SLOT. Now reserves one index per captured `this` / `new.target` and binds each inline in the entry block immediately after its store.
8+
9+
- **The `Object.assign` string source (#7215)**, from CodeRabbit's review of #7207. `str_bytes_from_jsvalue` returns a pointer INTO the source `StringHeader`'s data region for any string past the 5-byte SSO limit — header and payload are one contiguous `arena_alloc_gc` block and `GC_TYPE_STRING` is `movable` — and its own safety note forbids holding that pointer across a GC cycle. `object_assign_string_source` held it across three allocation points per character. #7207 opened a `RuntimeHandleScope` in that very function and rooted the target, the key and the value; it missed the source because the source is a *borrow*, not a JSValue in that frame. Snapshotted once before the loop, matching the `expandos` precedent a few lines down.
10+
11+
### Testing
12+
13+
- `test-files/test_gap_gc_catch_param_rooting.ts` and `test_gap_gc_closure_this_capture_rooting.ts`, both registered in `test-parity/gc_repsel_corpus.txt`. At `origin/main` (`1679e22b4`), compiled **and** run with `PERRY_GC_MOVING_LOOP_POLLS=1`: the closure one is `exit=139` (SIGSEGV) 3/3 and `bad 4` on the evacuating arm; the catch one is `message 8 field 8` of 400, 3/3 deterministic. Both clean 5/5 under polls with this change, 3/3 on the evacuating arm, 3/3 under the shipped default, byte-exact against Node 26.5.1. The corpus entry notes that `catch_param_rooting` is the one member that can also fail under a **non-moving** precise-roots collection — the sweep case — so it belongs on `cons_scan_off`, not only on the `requires=move` arms.
14+
- `test_gap_gc_assign_string_source_rooting.ts` ships **green at base**, and the fix comment says so rather than implying a witness. An instrumented build rooted both the source and the target inside the copy loop and counted relocations: `chars=26001 src_moves=0 tgt_moves=1`. The target moved — so a moving collection genuinely occurs inside that function, which is what makes #7207's target rooting load-bearing — but that source could not move, because at 26 KB it exceeds `LARGE_OBJECT_THRESHOLD_BYTES` (16 KiB) and `arena_alloc_gc` births it `GC_FLAG_TENURED` in the non-moving old generation. Under the threshold it is a movable nursery string, but one call then allocates too little to reliably span a collection; four shapes across four arm configurations, up to 120 observed GC cycles, all stayed clean. The exposure is the band just under 16 KiB, and the safety margin rests entirely on a tunable constant — which is the reason to fix it rather than document it.

‎crates/perry-codegen/src/codegen/closure.rs‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -586,7 +586,21 @@ pub(super) fn compile_closure(
586586
let flat_const_ids: std::collections::HashSet<u32> =
587587
cross_module.flat_const_arrays.keys().copied().collect();
588588
let m = crate::collectors::collect_pointer_typed_locals(params, body, &flat_const_ids);
589-
lf.enable_shadow_frame(m.len() as u32);
589+
// #7208: reserve one slot per CAPTURED `this` / `new.target`, exactly
590+
// as `codegen/method.rs:316` and `:1344` do with their `+ 1`.
591+
//
592+
// Both are `blk.alloca(DOUBLE)` holding a heap receiver for the WHOLE
593+
// closure body, read by every `ctx.this_stack.last()` consumer. Without
594+
// a reserved index there is nothing to bind them to, so an evacuating
595+
// minor neither marked nor rewrote them and every load below a
596+
// collection point named from-space. The in-tree note further down
597+
// ("the `this` / `new.target` capture reads ... run in the entry-block
598+
// prologue, ahead of any statement that could collect") justifies the
599+
// timing of the READ; it says nothing about the lifetime of the SLOT,
600+
// which spans the body.
601+
let capture_root_slots =
602+
u32::from(captures_this || enclosing_class.is_some()) + u32::from(captures_new_target);
603+
lf.enable_shadow_frame(m.len() as u32 + capture_root_slots);
590604
m
591605
} else {
592606
std::collections::HashMap::new()
@@ -681,6 +695,13 @@ pub(super) fn compile_closure(
681695
// Arrow-in-class leftover path (`enclosing_class.is_some()` without
682696
// the object-literal patch) keeps the old 0.0 sentinel — reads
683697
// return a bogus value but don't crash.
698+
// #7208: the two reserved indices sit immediately above the local slots,
699+
// mirroring `method.rs`'s single `this_shadow_slot_idx`. Bound INLINE right
700+
// after each store, in the same entry block, so the store dominates the
701+
// bind — an entry-setup hoist would make the slot active while the alloca
702+
// still held stack garbage.
703+
let capture_root_base = shadow_slot_map.len() as u32;
704+
let bind_capture_slot = super::helpers::shadow_stack_enabled();
684705
let new_target_stack = if captures_new_target {
685706
let new_target_cap_idx = auto_captures.len() as u32;
686707
let blk = lf.block_mut(0).unwrap();
@@ -693,6 +714,12 @@ pub(super) fn compile_closure(
693714
);
694715
let v = blk.bitcast_i64_to_double(&bits);
695716
blk.store(DOUBLE, &v, &slot);
717+
if bind_capture_slot {
718+
blk.call_void(
719+
"js_shadow_slot_bind",
720+
&[(I32, &capture_root_base.to_string()), (PTR, &slot)],
721+
);
722+
}
696723
vec![slot]
697724
} else {
698725
Vec::new()
@@ -714,6 +741,14 @@ pub(super) fn compile_closure(
714741
} else {
715742
blk.store(DOUBLE, "0.0", &slot);
716743
}
744+
if bind_capture_slot {
745+
// The `new.target` slot took `capture_root_base` when it existed.
746+
let idx = capture_root_base + u32::from(captures_new_target);
747+
blk.call_void(
748+
"js_shadow_slot_bind",
749+
&[(I32, &idx.to_string()), (PTR, &slot)],
750+
);
751+
}
717752
vec![slot]
718753
} else {
719754
Vec::new()

‎crates/perry-codegen/src/stmt/try_stmt.rs‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,28 @@ pub(crate) fn lower_try(
114114
let slot = ctx.func.alloca_entry(DOUBLE);
115115
ctx.locals.insert(*id, slot.clone());
116116
ctx.block().store(DOUBLE, &exc, &slot);
117+
// #7209: BIND the slot the frame is already sized for.
118+
//
119+
// `collect_pointer_typed_locals` assigns the catch parameter an
120+
// index — it is implicitly `Any`, i.e. pointer-possible — so
121+
// `js_shadow_frame_enter`'s count already includes it. Nothing ever
122+
// bound it, so `active[idx]` stayed false and the collector never
123+
// dereferenced this alloca: the frame was sized for a root that did
124+
// not exist.
125+
//
126+
// Sharper than an ordinary missing root, because
127+
// `js_clear_exception()` two lines up has already dropped the
128+
// RUNTIME's reference. From here the exception is reachable only
129+
// through this alloca, and the catch body is arbitrary user code —
130+
// so a precise-roots collection can SWEEP it, not merely move it.
131+
//
132+
// Emitted here rather than hoisted to entry setup precisely because
133+
// the slot must not go active before the store: on the non-throwing
134+
// path this alloca is never written, and an entry-hoisted bind
135+
// would hand the root-word decoder uninitialized stack bytes. After
136+
// the store is what `Stmt::Let` does for every ordinary local, and
137+
// it reuses the RESERVED index rather than growing the frame.
138+
crate::expr::emit_shadow_slot_bind_for_local(ctx, *id);
117139
}
118140
if let Some(f) = finally {
119141
// Per spec TryStatement : try Block Catch Finally — a throw

‎crates/perry-runtime/src/object/alloc.rs‎

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1141,12 +1141,42 @@ unsafe fn object_assign_string_source(
11411141
let Ok(s) = std::str::from_utf8(bytes) else {
11421142
return;
11431143
};
1144+
// #7214: SNAPSHOT the source before allocating anything.
1145+
//
1146+
// `str_bytes_from_jsvalue` returns a pointer INTO the source
1147+
// `StringHeader`'s data region for any string past the SSO limit (header
1148+
// and payload are one contiguous `arena_alloc_gc` block), and its own
1149+
// safety note says so: "Callers must not hold this pointer past a
1150+
// subsequent `scratch` modification or a GC cycle that could sweep the
1151+
// heap-backed `StringHeader`." The loop below holds it across three
1152+
// allocation points per character.
1153+
//
1154+
// MEASURED, because the size argument that makes this survivable is not one
1155+
// to rely on. An instrumented build rooted both the source and the target
1156+
// and counted relocations across the loop: on a 26 001-character source,
1157+
// `src_moves=0 tgt_moves=1` — collections DO happen inside this function
1158+
// (which is what makes the #7200 target rooting above load-bearing), but
1159+
// that source could not move because at 26 KB it is over
1160+
// `LARGE_OBJECT_THRESHOLD_BYTES` and `arena_alloc_gc` births it TENURED in
1161+
// the non-moving old generation. Shrink it under the threshold and it
1162+
// becomes a movable nursery string — but then one call allocates too little
1163+
// to reliably span a collection, and none was observed.
1164+
//
1165+
// So the exposure is real and narrow: a source in the band just under
1166+
// 16 KiB is both movable and long enough to allocate ~32 000 times. There
1167+
// is NO runtime witness for it and I am not implying otherwise; what there
1168+
// is, is a documented callee contract this violated and a safety margin
1169+
// that rests entirely on a tunable constant. One owned copy on a path that
1170+
// is already O(n) removes the dependence.
1171+
let owned: String = s.to_string();
1172+
11441173
// #7200: three allocations per iteration (`key_ptr`, `value_ptr`, and the
1145-
// write funnel's interning/growth) with `target` and `key_ptr` live across
1146-
// them. The second `js_string_from_bytes` alone can move the first.
1174+
// write funnel's interning / keys-array growth) with `target` and `key_ptr`
1175+
// live across them. The probe above measured `tgt_moves=1`, so the target
1176+
// half of this is not hypothetical.
11471177
let scope = crate::gc::RuntimeHandleScope::new();
11481178
let tgt_h = scope.root_raw_mut_ptr(target);
1149-
for (idx, ch) in s.chars().enumerate() {
1179+
for (idx, ch) in owned.chars().enumerate() {
11501180
let iter_scope = crate::gc::RuntimeHandleScope::new();
11511181
let key = idx.to_string();
11521182
let key_ptr = crate::string::js_string_from_bytes(key.as_ptr(), key.len() as u32);
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// #7214: `Object.assign(t, str)` / `{ ...str }` decoded the SOURCE string once,
2+
// into a raw `(*const u8, len)` view, and then held that borrow across every
3+
// allocation in the copy loop.
4+
//
5+
// `str_bytes_from_jsvalue` returns a pointer INTO the source `StringHeader`'s
6+
// data region for any string past the SSO limit, and says so in its own safety
7+
// note: "Callers must not hold this pointer past a subsequent `scratch`
8+
// modification or a GC cycle that could sweep the heap-backed `StringHeader`."
9+
// `object_assign_string_source` built a `&str` on that pointer and then hit
10+
// THREE allocation points per character — two `js_string_from_bytes` calls and
11+
// the write funnel's key interning / keys-array growth.
12+
//
13+
// #7207 opened a `RuntimeHandleScope` in that very function and rooted the
14+
// target, the key and the value. It did not root the source, because the source
15+
// is not a JSValue in that frame at all — it is a borrow. So an evacuating
16+
// minor moved the string and `chars()` walked from-space for every remaining
17+
// character.
18+
//
19+
// LIVE BY CONSTRUCTION AND ONLY ON THE MOVING ARMS. The source is a FRESH heap
20+
// string per iteration (built with `repeat`, well past the SSO limit), reachable
21+
// only from a shadow-bound local — so it survives the minor, which means it
22+
// MOVES. A non-moving collection leaves the bytes where they are and the borrow
23+
// stays accidentally valid.
24+
25+
const ALPHA = "abcdefghijklmnopqrstuvwxyz";
26+
const WIDTH = 208;
27+
28+
function run(): string {
29+
let badChar = 0;
30+
let badCount = 0;
31+
for (let r = 0; r < 300; r++) {
32+
// Past SHORT_STRING_MAX_LEN, so this is a real heap `StringHeader` in the
33+
// nursery rather than an inline short string copied into the caller's
34+
// scratch buffer.
35+
const src: string = ALPHA.repeat(8);
36+
const out: any = Object.assign({}, src);
37+
let seen = 0;
38+
for (let i = 0; i < WIDTH; i++) {
39+
const got = out[i];
40+
if (got !== undefined) {
41+
seen++;
42+
}
43+
if (got !== ALPHA[i % 26]) {
44+
badChar++;
45+
break;
46+
}
47+
}
48+
if (seen !== WIDTH) {
49+
badCount++;
50+
}
51+
}
52+
return "char " + badChar + " count " + badCount;
53+
}
54+
55+
console.log("bad", run());
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// #7209: the `catch (e)` parameter has a shadow slot RESERVED for it and never
2+
// BOUND, so the exception object has no root at all for the whole catch body.
3+
//
4+
// `collectors/pointer_locals.rs` assigns the catch parameter a slot index (it
5+
// is implicitly `Any`, i.e. pointer-possible), so `js_shadow_frame_enter`'s
6+
// count already includes it. `stmt/try_stmt.rs` then allocates the parameter's
7+
// storage with `alloca_entry` and stores the exception into it — and never
8+
// emits `js_shadow_slot_bind`, so `active[idx]` stays false forever and the
9+
// collector never dereferences the alloca. The frame is sized for a root that
10+
// does not exist.
11+
//
12+
// What makes it sharp rather than merely untidy: `js_clear_exception()` runs
13+
// BEFORE the catch body is lowered, dropping the runtime's own reference. From
14+
// that point the only thing referring to the exception is the unrooted alloca.
15+
// Under a precise-roots collection the object can be SWEPT, not merely moved.
16+
//
17+
// LIVE BY CONSTRUCTION. `churn()` allocates hard enough to reach the collector,
18+
// and `e` is read AFTER it — both the message string and a field stored on the
19+
// error, so a relocated `Error` and a reclaimed one both show up.
20+
21+
function churn(): number {
22+
const a: any[] = [];
23+
for (let i = 0; i < 600; i++) {
24+
a.push({ i: i, s: "e" });
25+
}
26+
return a.length;
27+
}
28+
29+
function run(): string {
30+
let badChurn = 0;
31+
let badMessage = 0;
32+
let badField = 0;
33+
for (let r = 0; r < 400; r++) {
34+
try {
35+
const err: any = new Error("boom" + r);
36+
err.tag = r;
37+
throw err;
38+
} catch (e: any) {
39+
// The exception is live across this call and nothing else refers to it.
40+
const n = churn();
41+
if (n !== 600) badChurn++;
42+
if (e.message !== "boom" + r) badMessage++;
43+
if (e.tag !== r) badField++;
44+
}
45+
}
46+
return "churn " + badChurn + " message " + badMessage + " field " + badField;
47+
}
48+
49+
console.log("bad", run());
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// #7208: a closure's captured `this` lives in a plain `alloca_entry` that no
2+
// `js_shadow_slot_bind` names, so the collector neither marks nor rewrites it.
3+
//
4+
// `codegen/closure.rs` sized its shadow frame `enable_shadow_frame(m.len())`
5+
// where `codegen/method.rs` uses `m.len() + 1` — and that `+1` IS the `this`
6+
// slot, which `method.rs` then binds. Closures reserved nothing, so there was
7+
// no index to bind and the receiver was unrooted for the whole body.
8+
//
9+
// The in-tree comment claiming the capture reads are "exempt ... they run in
10+
// the entry-block prologue, ahead of any statement that could collect"
11+
// justifies the timing of the READ. It says nothing about the lifetime of the
12+
// SLOT, which spans every statement in the body — including the ones that
13+
// collect.
14+
//
15+
// LIVE BY CONSTRUCTION. The receiver is a temporary: after `make()` returns it
16+
// is reachable ONLY from the closure's capture cell, which IS a traced root —
17+
// so an evacuating minor MOVES it rather than freeing it, rewrites the capture
18+
// cell, and leaves the prologue's alloca copy naming from-space. `churn()` runs
19+
// between the prologue read and the `this.tag` read.
20+
21+
function churn(): number {
22+
const a: any[] = [];
23+
for (let i = 0; i < 600; i++) {
24+
a.push({ i: i, s: "c" });
25+
}
26+
return a.length;
27+
}
28+
29+
class Holder {
30+
tag: number;
31+
label: string;
32+
constructor(t: number) {
33+
this.tag = t;
34+
this.label = "h";
35+
}
36+
make(): () => string {
37+
return () => {
38+
const n = churn();
39+
return this.label + ":" + (this.tag + (n - 600));
40+
};
41+
}
42+
}
43+
44+
function run(): number {
45+
let bad = 0;
46+
for (let r = 0; r < 400; r++) {
47+
const f = new Holder(r).make();
48+
if (f() !== "h:" + r) {
49+
bad++;
50+
}
51+
}
52+
return bad;
53+
}
54+
55+
console.log("bad", run());

0 commit comments

Comments
 (0)