Skip to content

[JSC] ConservativeRoots: only a zero-length JSCellButterfly is referenced from past its end - #637

Closed
robobun wants to merge 1 commit into
mainfrom
robobun/f393bbc6/conservative-roots-cell-butterfly-slack
Closed

robobun wants to merge 1 commit into
mainfrom
robobun/f393bbc6/conservative-roots-cell-butterfly-slack

Conversation

@robobun

@robobun robobun commented Sep 12, 2026

Copy link
Copy Markdown
Collaborator

Problem

  • A Map or Set whose entries come and go leaks: 56 bytes per set + delete on an empty Map (534 MB after 10M cycles), 2.8 KB per cycle with two live 2 KB entries. A full GC frees nothing. node:http tracks connections in such a Set.
  • genericAddPointer (heap/ConservativeRoots.cpp:139) takes a word equal to the end of a MarkedBlock for a reference to its last Auxiliary or JSCellWithIndexingHeader cell. With mimalloc the JSC::VM starts there, and a VM* is in a register at every collection, so that cell is immortal. When it is a replaced Map or Set table, its NextTable pointer keeps every later table and their entries.
gdb at ConservativeRoots::add, release build of Bun main, vm = 0x28907b80000
add #1 (registers)  on entry: size=0
add #2 (stack)      on entry: size=1 roots=[0x28907b7ff20]    <- vm - 0xe0, a replaced table

Fix

  • mayBeReferencedFromPastTheEnd() guards the previous-block rule, the left-neighbour rule and PreciseAllocation::contains(). Auxiliary keeps its 8 bytes of slack. JSCellWithIndexingHeader keeps only the exact end of a 16-byte cell.
  • [JSC] ConservativeRoots: no past-the-end butterfly slack for cells that cannot hold a butterfly (MarkedBlock rule + PreciseAllocation::contains) #398 kept both kinds because a Butterfly* "for a zero-vector-length butterfly without an indexing header is computed one header past the end". Only Auxiliary storage can lack the header. JSCellButterfly::toButterfly() is cell + 16: the end of a zero-length (16-byte) cell, an interior pointer in any longer one.
  • Verified: a Bun release build of this branch keeps both repros flat, and add #2 sees size=0. The Bun PR that pins this preview build adds the test: unfixed keeps 2.2 to 9 MB, fixed 5 KB.

Background

Notes

Repros, release build of Bun main (WebKit cf1b36e), Linux x64, CommonJS entry point:

// 56 bytes per cycle: one 224-byte capacity-8 table per 4 cycles
const m = new Map();
let k = 0;
function churn(n) { for (let i = 0; i < n; i++) { m.set(k, k); m.delete(k); k++; } }
churn(10000); Bun.gc(true);
for (let r = 1; r <= 5; r++) {
  churn(2_000_000); Bun.gc(true);
  console.log(k, m.size, require("bun:jsc").heapStats().heapSize);   // 107 MB, 214 MB, ... 534 MB
}
// 2832 bytes per cycle: every replaced table keeps the entries that were live at the rehash
const s = new Set(), live = [];
let k = 0;
function churn(n) {
  for (let i = 0; i < n; i++) {
    const conn = { id: k++, buffer: new Array(256).fill(k) };
    s.add(conn); live.push(conn);
    if (live.length > 2) s.delete(live.shift());
  }
}
churn(10000); Bun.gc(true);
const h0 = require("bun:jsc").heapStats().heapSize;
churn(200_000); Bun.gc(true);
console.log(s.size, require("bun:jsc").heapStats().heapSize - h0);   // 2, 553 MB. Fixed: 2, 0

How the retainer was found:

  • The heap snapshot does not discriminate. JSCellButterfly::visitChildren appends its slots hidden, so the snapshot has no edge from one table to the next: in a leaking run, 102,430 of 102,434 Cell Butterfly nodes have no incoming edge and no root entry, and only the first of them lacks a real referrer.
  • A parent process read /proc/<pid>/mem, collected every cell with the table's header, and walked the NextTable chain backwards from m_storage. It ends at a table at VM - 0xe0: the last cell of the MarkedBlock whose end is the VM (JSC__VM__runGC's rdi, and the m_vm field of that block's header).
  • The gdb session above breaks on ConservativeRoots::add(void*, void*, JITStubRoutineSet&, CodeBlockSet&) during the third Bun.gc(true). The only word in the register range that is in or near that cell is the VM*. The stack range holds the same VM* in about 30 more slots. After the stack scan the root set holds the table 5 times and 112 other cells.
  • On the fixed build the VM still follows a table block, add #2 sees size=0, and after the stack scan none of the 96 roots is VM - 0xe0.

It is layout dependent, not a regression in one release. With the same two scripts Bun 1.2.0, 1.3.11, 1.3.12 and 1.4.3 leak, and 1.1.34, 1.2.23, 1.3.0 and 1.3.5 do not. On 1.4.3 the script leaks as a CommonJS entry point and does not leak as ESM. In 1.3.11 the block before the VM holds 320-byte tables and the mechanism is the same.

An Auxiliary cell that the rule keeps costs only the cell: the collector does not visit an auxiliary cell. A JSCellButterfly is visited, which is what makes the chain possible. PreciseAllocation keeps #398's inclusive <= end bound for every kind that gets no slack.

Also run on the fixed build: test/js/bun/jsc-stress/, test/js/bun/jsc/, test/js/bun/gc/, inspect.test.js, structured-clone.test.ts, expect.test.js, and a Map/Set/spread script (iteration across replaced and cleared tables, a live iterator across 100 rehashes, zero-length spreads) under collectContinuously=1, slowPathAllocsBetweenGCs=3 and 5, useJIT=0, and scribbleFreeCells=1 sweepSynchronously=1. All give the same output as the unfixed build.

…nced from past its end

A word equal to the end of a MarkedBlock marked the last cell of that
block when the block held Auxiliary or JSCellWithIndexingHeader cells,
because a Butterfly* can point past the end of its storage. The memory
after a MarkedBlock belongs to whoever the allocator gave it to. With
mimalloc the JSC::VM itself can start there, and a VM* is in a register
or a frame at every collection, so that cell never dies.

For an Auxiliary cell that costs the cell. A JSCellWithIndexingHeader
cell is a JSCellButterfly and has children. When it is a Map or Set
table that the collection has replaced (rehash or clear), it points at
the table that replaced it. So it keeps every later table, and each of
those keeps the keys and values it held when it was replaced. A Set of
two or three live 2 KB entries, one added and one deleted per cycle,
grew the heap by 2.8 KB per cycle. A Map that only ever became empty
again grew it by 56 bytes per set + delete.

The past-the-end case exists for Auxiliary storage only: a butterfly
with no IndexingHeader and no indexed payload is computed
sizeof(IndexingHeader) past its end. A JSCellButterfly holds its
IndexingHeader inside the cell, and toButterfly() is the cell plus
sizeof(JSCellButterfly). That is the end of the cell only for a
zero-length butterfly, which is a 16-byte cell. In a longer one it is an
interior pointer, and an interior pointer finds its cell without the
past-the-end rule.

So apply the rule to JSCellWithIndexingHeader only for 16-byte cells and
only at exactly the end. Auxiliary cells keep the full
sizeof(IndexingHeader) slack. The same test now guards the
previous-block rule, the left-neighbour rule and
PreciseAllocation::contains().

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reviewed this and didn't find any bugs — the reasoning and arithmetic check out — but since it narrows conservative GC root scanning (the direction where a mistake is a use-after-free) and Source/JavaScriptCore is CODEOWNERS-gated, a human JSC reviewer should still sign off.

What was reviewed:

  • mayBeReferencedFromPastTheEnd is strictly narrower than the old mayHaveIndexingHeader gate only for JSCellWithIndexingHeader; JSCell and Auxiliary behavior is unchanged.
  • JSCellButterfly::toButterfly() is cell + offsetOfData() (= cell + 16), so its Butterfly* is past-the-end only for a 16-byte cell and then exactly at the end — matches cellSize == sizeof(JSCellButterfly) && !bytesPastTheEnd.
  • The three call sites' overshoot arithmetic: pointer - candidate for the previous block, pointer - alignedPointer for the left neighbour, and the PreciseAllocation gate falling through to the <= end bound for JSCellWithIndexingHeader.
  • JSCellWithIndexingHeader is used only by immutableButterflyAuxiliarySpace (JSCellButterfly), so no other cell type loses coverage.
Extended reasoning...

Overview

This PR tightens the past-the-end pointer handling in Source/JavaScriptCore/heap/ConservativeRoots.cpp. It replaces the coarse mayHaveIndexingHeader(kind) gate at three sites (PreciseAllocation bounds, previous-MarkedBlock last-cell, and left-neighbour-in-same-block) with a new mayBeReferencedFromPastTheEnd(kind, cellSize, bytesPastTheEnd) predicate that encodes exactly when a Butterfly* can legitimately land at or past a cell's end. For Auxiliary the 8-byte slack is preserved; for JSCellWithIndexingHeader only the exact end of a sizeof(JSCellButterfly)-sized cell is accepted; JSCell remains excluded. The motivation is a real leak where a VM* in a register at every collection aliases the end of a MarkedBlock of Map/Set tables, pinning a NextTable chain forever.

Security risks

Conservative root scanning is what keeps C++-visible JS objects alive across GC. Narrowing it is the memory-safety-risky direction: a false negative means an object is collected while a live Butterfly* still refers to it, i.e. use-after-free. I verified the invariant the change relies on — JSCellButterfly::toButterfly() returns cell + offsetOfData() (rounded sizeof(JSCellButterfly), i.e. 16), so the only past-the-end case is a zero-length 16-byte cell with the pointer exactly at its end — and that JSCellWithIndexingHeader is used solely by immutableButterflyAuxiliarySpace. The overshoot computations at each call site are correct (pointer - candidate is the offset into the next block = distance past the previous block's end; pointer - alignedPointer is the offset into the right-hand cell; the PreciseAllocation site passes sizeof(IndexingHeader) so JSCellWithIndexingHeader falls to the <= end branch, which still covers the zero-length case). There is no injection/auth/data-exposure surface here; the risk is purely GC correctness.

Level of scrutiny

High. This is core GC marking logic where an off-by-one or a missed producer of past-the-end pointers would manifest as rare, allocator-layout-dependent UAFs. The path is also under CODEOWNERS (/Source/JavaScriptCore → WebKit/jsc-reviewers). Per the approval guidelines, CODEOWNERS coverage plus memory-safety-critical narrowing means a human reviewer with JSC heap expertise should confirm the invariant that no other code path (including JIT lowerings of toButterfly) can produce a Butterfly* more than 0 bytes past a JSCellWithIndexingHeader cell.

Other factors

The PR description reports targeted testing under collectContinuously=1, slowPathAllocsBetweenGCs, useJIT=0, and scribbleFreeCells=1 sweepSynchronously=1, plus the Map/Set repros going flat, which is the right kind of coverage for this change. The diff is small, well-commented, and self-contained to one file. I found no logic errors, but the correctness argument leans on layout invariants (sizeof(JSCellButterfly) == 16, size-class alignment, JSCellButterfly being the sole JSCellWithIndexingHeader occupant) that a JSC reviewer should ratify.

@github-actions

Copy link
Copy Markdown

Preview Builds

Commit Release Date
5a01779f autobuild-preview-pr-637-5a01779f 2026-09-12 10:48:53 UTC

@coderabbitai

coderabbitai Bot commented Sep 12, 2026

Copy link
Copy Markdown

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Essentials

Run ID: d0919940-5d85-4614-8959-13f233ba1199

📥 Commits

Reviewing files that changed from the base of the PR and between cf1b36e and 5a01779.

📒 Files selected for processing (1)
  • Source/JavaScriptCore/heap/ConservativeRoots.cpp

Included review availability: Your plan provides up to 5 included reviews per hour; 1 remains after this review.


Walkthrough

The change adds cell-kind- and offset-aware validation for past-the-end pointers in conservative root detection. Precise allocations, previous-block butterflies, and adjacent-cell fallback checks now use this validation.

Changes

Conservative root boundary validation

Layer / File(s) Summary
Past-the-end pointer validation
Source/JavaScriptCore/heap/ConservativeRoots.cpp
Adds JSCellButterfly support and validates past-the-end pointers for ordinary cells, indexing-header cells, and auxiliary allocations.
Boundary detection updates
Source/JavaScriptCore/heap/ConservativeRoots.cpp
Updates precise-allocation, previous-block butterfly, and adjacent-cell checks to use exact offset validation and candidate-atom checks.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 5a017

No actionable merge-blocking risk is currently supported.

🚥 Pre-merge checks | ✅ 3 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides a detailed, relevant explanation of the bug, fix, reproductions, and validation. It does not include the required Bugzilla link, review status line, or changed-file and functi… Add the bug title and Bugzilla URL, include the required "Reviewed by NOBODY (OOPS!)." line or actual review information, and list each changed file with the affected functions or classes using the repository template format.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the JSC ConservativeRoots change and the zero-length JSCellButterfly past-the-end reference rule.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description provides a detailed, relevant explanation of the bug, fix, reproductions, and validation. It does not include the required Bugzilla link, review status line, or changed-file and function list from the repository template.

  • Fix all pre-merge checks with AI

Warning

Git: CodeRabbit could not clone the repository, so clone-backed analysis was skipped and this review may be incomplete. Verify repository clone access, such as SSH credentials, before requesting another full review. If clone access is intentionally unavailable, use path_filters to narrow the review scope.


Comment @coderabbitai help to get the list of available commands.

@robobun

robobun commented Sep 12, 2026

Copy link
Copy Markdown
Collaborator Author

Closing: #636 is the same fix for the same bug and was opened first. The one difference and the evidence from this PR are noted there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant