镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Commit 2285b23

Browse files
committed
fix(gc): root binary coercion operands (#784)
Publish both original binary operands before the first observable ToPrimitive call, replace each precise-root slot with its completed primitive, and reload the pair after right-side coercion. Primitive-only arithmetic retains the root-free fast path. Add deterministic moving-nursery witnesses for a pending right operand and a completed left StringData cell, plus once-only left-to-right coverage across string add, numeric, relational, bitwise, loose equality, abrupt completion, and a generator VM path. Tests: focused normal and TSan relocation and semantic units pass 2/2 with no leaks; adjacent two-value concat passes in both modes; six exact-parent Test262 operator families remain 246/246 passing (0 flips); threadfuzz passes 400/400 from seed 1.
1 parent 9f79e91 commit 2285b23

2 files changed

Lines changed: 185 additions & 8 deletions

File tree

‎src/context.zig‎

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21561,6 +21561,122 @@ test "variadic String concat roots pending arguments across moving nursery" {
2156121561
try std.testing.expect(last_argument_before != last_argument_after);
2156221562
}
2156321563

21564+
test "binary coercion roots pending and completed operands across moving nursery" {
21565+
if (!jit.supported or builtin.cpu.arch != .aarch64) return error.SkipZigTest;
21566+
21567+
const Harness = struct {
21568+
fn create() !*Context {
21569+
const ctx = try Context.createWith(std.testing.allocator, .{
21570+
.enable_gc = true,
21571+
.enable_jit = true,
21572+
});
21573+
errdefer ctx.destroy();
21574+
_ = try ctx.evaluate(
21575+
\\function binaryMovingLoop(n) {
21576+
\\ var total = 0;
21577+
\\ var i = 0;
21578+
\\ while (i < n) { total = total + i; i = i + 1; }
21579+
\\ return total;
21580+
\\}
21581+
\\for (var warm = 0; warm < 10; warm = warm + 1) binaryMovingLoop(4096);
21582+
);
21583+
const loop_object = ctx.global_object.getOwn("binaryMovingLoop").?.asObj();
21584+
const loop: *interp.Function = @ptrCast(@alignCast(loop_object.jsFunction().?));
21585+
const chunk = loop.chunk.?;
21586+
try std.testing.expectEqual(jit.TierState.ready, chunk.tier.loadState());
21587+
try std.testing.expect(chunk.tier.loadCode().?.manages_steps);
21588+
ctx.collectGarbage();
21589+
ctx.gc.?.nursery_threshold_bytes = std.math.maxInt(usize);
21590+
return ctx;
21591+
}
21592+
};
21593+
21594+
// The left conversion evacuates the nursery while the original right
21595+
// object has not yet been converted. Its precise operand root must be
21596+
// rewritten before the right-side ToPrimitive begins.
21597+
{
21598+
const ctx = try Harness.create();
21599+
defer ctx.destroy();
21600+
_ = try ctx.evaluate(
21601+
\\globalThis.binaryMovingLeft = {
21602+
\\ valueOf() { binaryMovingLoop(20000); return 7; }
21603+
\\};
21604+
\\globalThis.binaryMovingRight = { valueOf() { return 9; } };
21605+
);
21606+
const right_before = ctx.global_object.getOwn("binaryMovingRight").?.asObj();
21607+
21608+
const gc_saved = gc_mod.setActiveContext(ctx);
21609+
defer gc_mod.restoreActiveContext(gc_saved);
21610+
const sa_saved = strcell.setActiveArena(ctx.arena());
21611+
defer _ = strcell.setActiveArena(sa_saved);
21612+
const ss_saved = stack_scan.enter(@frameAddress());
21613+
defer stack_scan.leave(ss_saved);
21614+
var machine = ctx.interpreter();
21615+
try ctx.pushActiveInterpreter(&machine);
21616+
defer ctx.popActiveInterpreter(&machine);
21617+
const ai_saved = gc_mod.setActiveInterpreter(&machine);
21618+
defer _ = gc_mod.setActiveInterpreter(ai_saved);
21619+
21620+
const heap = ctx.gc.?;
21621+
heap.nursery_threshold_bytes = 1;
21622+
ctx.movingCheckpointRequest().store(true, .release);
21623+
const moving_before = heap.accounting().moving_minor_collections;
21624+
const result = try machine.applyBinary(
21625+
.add,
21626+
ctx.global_object.getOwn("binaryMovingLeft").?,
21627+
ctx.global_object.getOwn("binaryMovingRight").?,
21628+
);
21629+
try std.testing.expectEqual(@as(f64, 16), result.asNum());
21630+
try std.testing.expectEqual(moving_before + 1, heap.accounting().moving_minor_collections);
21631+
try std.testing.expect(right_before != ctx.global_object.getOwn("binaryMovingRight").?.asObj());
21632+
try std.testing.expect(!ctx.gc_relocation_active.load(.acquire));
21633+
}
21634+
21635+
// The left conversion completes first. The right conversion then evacuates
21636+
// the returned young StringData, proving that the completed primitive
21637+
// replaced the original left-object root before observable right-side code.
21638+
{
21639+
const ctx = try Harness.create();
21640+
defer ctx.destroy();
21641+
_ = try ctx.evaluate(
21642+
\\globalThis.binaryMovingLeftText = "left".repeat(2);
21643+
\\globalThis.binaryMovingLeft = {
21644+
\\ valueOf() { return binaryMovingLeftText; }
21645+
\\};
21646+
\\globalThis.binaryMovingRight = {
21647+
\\ valueOf() { binaryMovingLoop(20000); return "right".repeat(2); }
21648+
\\};
21649+
);
21650+
const left_text_before = ctx.global_object.getOwn("binaryMovingLeftText").?.asStringCell();
21651+
21652+
const gc_saved = gc_mod.setActiveContext(ctx);
21653+
defer gc_mod.restoreActiveContext(gc_saved);
21654+
const sa_saved = strcell.setActiveArena(ctx.arena());
21655+
defer _ = strcell.setActiveArena(sa_saved);
21656+
const ss_saved = stack_scan.enter(@frameAddress());
21657+
defer stack_scan.leave(ss_saved);
21658+
var machine = ctx.interpreter();
21659+
try ctx.pushActiveInterpreter(&machine);
21660+
defer ctx.popActiveInterpreter(&machine);
21661+
const ai_saved = gc_mod.setActiveInterpreter(&machine);
21662+
defer _ = gc_mod.setActiveInterpreter(ai_saved);
21663+
21664+
const heap = ctx.gc.?;
21665+
heap.nursery_threshold_bytes = 1;
21666+
ctx.movingCheckpointRequest().store(true, .release);
21667+
const moving_before = heap.accounting().moving_minor_collections;
21668+
const result = try machine.applyBinary(
21669+
.add,
21670+
ctx.global_object.getOwn("binaryMovingLeft").?,
21671+
ctx.global_object.getOwn("binaryMovingRight").?,
21672+
);
21673+
try std.testing.expectEqualStrings("leftleftrightright", try result.asWtf8(ctx.gpa));
21674+
try std.testing.expectEqual(moving_before + 1, heap.accounting().moving_minor_collections);
21675+
try std.testing.expect(left_text_before != ctx.global_object.getOwn("binaryMovingLeftText").?.asStringCell());
21676+
try std.testing.expect(!ctx.gc_relocation_active.load(.acquire));
21677+
}
21678+
}
21679+
2156421680
test "GC requested compaction rewrites active Promise job native roots" {
2156521681
if (!jit.supported or builtin.cpu.arch != .aarch64) return error.SkipZigTest;
2156621682

‎src/interpreter.zig‎

Lines changed: 69 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19192,15 +19192,40 @@ pub const Interpreter = struct {
1919219192

1919319193
pub fn applyBinary(self: *Interpreter, op_in: ast.BinaryOp, l_in: Value, r_in: Value) EvalError!Value {
1919419194
const op = op_in;
19195+
const l_object = l_in.isObject() and !l_in.asObj().is_bigint and !l_in.asObj().is_symbol;
19196+
const r_object = r_in.isObject() and !r_in.asObj().is_bigint and !r_in.asObj().is_symbol;
19197+
const has_observable_coercion = switch (op) {
19198+
.add, .sub, .mul, .div, .mod, .pow, .lt, .le, .gt, .ge, .bit_and, .bit_or, .bit_xor, .shl, .shr, .ushr => l_object or r_object,
19199+
.eq, .neq => (l_object and !r_object and !r_in.isUndefined() and !r_in.isNull()) or
19200+
(r_object and !l_object and !l_in.isUndefined() and !l_in.isNull()),
19201+
else => false,
19202+
};
19203+
// Primitive-only arithmetic stays on the existing root-free fast path.
19204+
// Once either side can run user code, publish both originals before the
19205+
// first ToPrimitive so a moving checkpoint cannot stale the other side.
19206+
const roots_mark: ?usize = if (self.gc != null and has_observable_coercion) roots: {
19207+
const mark = try self.pushTempRoot(l_in);
19208+
errdefer self.restoreTempRoots(mark);
19209+
const right_root = try self.pushTempRoot(r_in);
19210+
std.debug.assert(right_root == mark + 1);
19211+
break :roots mark;
19212+
} else null;
19213+
defer if (roots_mark) |mark| self.restoreTempRoots(mark);
19214+
1919519215
var l = l_in;
1919619216
var r = r_in;
1919719217
// Coerce object operands to primitives first (ToPrimitive). `+` uses the
1919819218
// "default" hint; the other arithmetic / relational / bitwise ops use
1919919219
// "number". Equality and instanceof/in handle objects themselves.
1920019220
switch (op) {
1920119221
.add => {
19202-
l = try self.toPrimitive(l, .default);
19203-
r = try self.toPrimitive(r, .default);
19222+
l = try self.toPrimitive(if (roots_mark) |mark| self.tempRoot(mark, l) else l, .default);
19223+
if (roots_mark) |mark| self.setTempRoot(mark, l);
19224+
r = try self.toPrimitive(if (roots_mark) |mark| self.tempRoot(mark + 1, r) else r, .default);
19225+
if (roots_mark) |mark| {
19226+
self.setTempRoot(mark + 1, r);
19227+
l = self.tempRoot(mark, l);
19228+
}
1920419229
},
1920519230
.sub, .mul, .div, .mod, .pow, .lt, .le, .gt, .ge, .bit_and, .bit_or, .bit_xor, .shl, .shr, .ushr => {
1920619231
// ApplyStringOrNumericBinaryOperator evaluates ToNumeric(lhs)
@@ -19209,10 +19234,15 @@ pub const Interpreter = struct {
1920919234
// each operand in order: a throwing lhs conversion must abort
1921019235
// before the rhs operand is coerced at all (its `valueOf` must not
1921119236
// run). (BigInt mixing is diagnosed later, after both ToNumerics.)
19212-
l = try self.toPrimitive(l, .number);
19237+
l = try self.toPrimitive(if (roots_mark) |mark| self.tempRoot(mark, l) else l, .number);
19238+
if (roots_mark) |mark| self.setTempRoot(mark, l);
1921319239
if (l.isObject() and l.asObj().is_symbol)
1921419240
return self.throwError("TypeError", "Cannot convert a Symbol value to a number");
19215-
r = try self.toPrimitive(r, .number);
19241+
r = try self.toPrimitive(if (roots_mark) |mark| self.tempRoot(mark + 1, r) else r, .number);
19242+
if (roots_mark) |mark| {
19243+
self.setTempRoot(mark + 1, r);
19244+
l = self.tempRoot(mark, l);
19245+
}
1921619246
if (r.isObject() and r.asObj().is_symbol)
1921719247
return self.throwError("TypeError", "Cannot convert a Symbol value to a number");
1921819248
},
@@ -19224,13 +19254,21 @@ pub const Interpreter = struct {
1922419254
// objects compare by identity, and an object vs null/undefined is
1922519255
// always unequal, so neither is coerced. A BigInt/Symbol value is
1922619256
// boxed as an object here but counts as a primitive operand.
19227-
const l_obj = l.isObject() and !l.asObj().is_bigint and !l.asObj().is_symbol;
19228-
const r_obj = r.isObject() and !r.asObj().is_bigint and !r.asObj().is_symbol;
19229-
if (l_obj and !r_obj and !r.isUndefined() and !r.isNull()) l = try self.toPrimitive(l, .default);
19230-
if (r_obj and !l_obj and !l.isUndefined() and !l.isNull()) r = try self.toPrimitive(r, .default);
19257+
if (l_object and !r_object and !r.isUndefined() and !r.isNull()) {
19258+
l = try self.toPrimitive(if (roots_mark) |mark| self.tempRoot(mark, l) else l, .default);
19259+
if (roots_mark) |mark| self.setTempRoot(mark, l);
19260+
}
19261+
if (r_object and !l_object and !l.isUndefined() and !l.isNull()) {
19262+
r = try self.toPrimitive(if (roots_mark) |mark| self.tempRoot(mark + 1, r) else r, .default);
19263+
if (roots_mark) |mark| self.setTempRoot(mark + 1, r);
19264+
}
1923119265
},
1923219266
else => {},
1923319267
}
19268+
if (roots_mark) |mark| {
19269+
l = self.tempRoot(mark, l);
19270+
r = self.tempRoot(mark + 1, r);
19271+
}
1923419272
// (Symbol operands for the number-hint ops above were already rejected
1923519273
// in-order during their ToNumeric coercion.)
1923619274
// BigInt operands. Arithmetic/bitwise require both to be BigInt (mixing
@@ -53487,6 +53525,29 @@ test "variadic string concat uses one exact canonical construction" {
5348753525
try std.testing.expectEqualStrings("RAB|rab", try receiver_order.asWtf8(a));
5348853526
}
5348953527

53528+
test "binary observable coercions remain once-only and left-to-right" {
53529+
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
53530+
defer arena.deinit();
53531+
const result = try evalSource(arena.allocator(),
53532+
\\let log = '';
53533+
\\function operand(mark, value, fail) {
53534+
\\ return { valueOf() { log += mark; if (fail) throw 1; return value; } };
53535+
\\}
53536+
\\const results = [];
53537+
\\results.push(operand('a', 'A', false) + operand('b', 'B', false));
53538+
\\results.push(operand('c', 7, false) - operand('d', 2, false));
53539+
\\results.push(operand('e', 2, false) < operand('f', 3, false));
53540+
\\results.push(operand('g', 6, false) & operand('h', 3, false));
53541+
\\results.push(operand('i', 5, false) == 5);
53542+
\\results.push(5 == operand('j', 5, false));
53543+
\\try { operand('k', 0, true) + operand('x', 1, false); } catch {}
53544+
\\function* vmBinary(left, right) { return left + right; }
53545+
\\results.push(vmBinary(operand('l', 'L', false), operand('m', 'M', false)).next().value);
53546+
\\results.join(',') + '|' + log
53547+
);
53548+
try std.testing.expectEqualStrings("AB,5,true,2,true,true,LM|abcdefghijklm", try result.asWtf8(arena.allocator()));
53549+
}
53550+
5349053551
test "ToString canonicalizes object-produced StringData" {
5349153552
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
5349253553
defer arena.deinit();

0 commit comments

Comments
 (0)