Skip to content

bake: fix use-after-free in ~DevServerSourceProvider during VM teardown - #34035

Merged
Jarred-Sumner merged 1 commit into
mainfrom
farm/f8e6015a/fix-leaksan-skiplist-typo
Jul 12, 2026
Merged

Jarred-Sumner merged 1 commit into
mainfrom
farm/f8e6015a/fix-leaksan-skiplist-typo

Conversation

@robobun

@robobun robobun commented Jul 12, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes test/bake/dev/request-cookies.test.ts going red on the debian 13 x64-asan lane (seen in build 72183 and build 71964):

dev| ==1715==ERROR: AddressSanitizer: SEGV on unknown address 0x000000007490
error: DevServer panicked
      at gracefulExit (test/bake/bake-harness.ts:614:17)
✗  DEV:request-cookies-1: request.cookies.get() basic functionality

Cause

~DevServerSourceProvider held a raw Zig::GlobalObject* and called m_globalObject->bunVM() to reach Bun__removeDevServerSourceProvider. Under BUN_DESTRUCT_VM_ON_EXIT=1 (set by the CI runner for the asan lane), the harness's process.exit(0) runs Zig__GlobalObject__destructOnExit, which does gcUnprotect(globalObject) then collectNow(Sync, Full) then two vm.derefSuppressingSaferCPPChecking(). The global object cell is swept during collectNow, but the provider's last Ref is only released later from ~CodeCache inside ~JSC::VM, so the destructor read m_bunVM out of a freed cell.

With bmalloc the freed cell usually still holds the old value and the read happens to work, which is why this was ~0.5% in CI and never reproduced locally. When the memory is reused with a zero at that offset the Rust side receives a null VirtualMachine* and the next access is (null)->source_mappings.mutex, which lands at exactly 0x7490.

Deterministic ASAN backtrace with Malloc=1:

==79839==ERROR: AddressSanitizer: heap-use-after-free ...
    #0  Zig::GlobalObject::bunVM() const  ZigGlobalObject.h:353
    #1  Bake::DevServerSourceProvider::~DevServerSourceProvider()  DevServerSourceProvider.h:65
    ...
    #7  JSC::SourceCodeKey::~SourceCodeKey()
    #12 JSC::CodeCacheMap::~CodeCacheMap()
    #16 JSC::VM::~VM()
    #18 Zig__GlobalObject__destructOnExit  ZigGlobalObject.cpp:4049
    #19 VirtualMachine::global_exit  VirtualMachine.rs:1603
    #20 Bun__Process__exit

Fix

Store the Rust VirtualMachine* directly (void* m_bunVM), captured in create(), so the destructor no longer indirects through a GC cell. This mirrors Zig::SourceProvider, which already stores m_bunVM for the same reason. The Rust VirtualMachine outlives every GC cell (step 10 of global_exit is self.destroy(), after destructOnExit has finished).

Verification

New ASAN-only case in test/bake/dev/server-sourcemap.test.ts runs the dev server with Malloc=1 + BUN_DESTRUCT_VM_ON_EXIT=1 so ASAN poisons the swept global-object cell, making the UAF deterministic. Added an env option to the devTest harness so the test can set those for the spawned dev server.

# fail-before (src/ stashed)
SUMMARY: AddressSanitizer: heap-use-after-free ZigGlobalObject.h:353:48 in Zig::GlobalObject::bunVM() const
(fail)  DEV:server-sourcemap-5: DevServerSourceProvider destructor does not touch the swept global object on process exit

# pass-after
(pass)  DEV:server-sourcemap-5: DevServerSourceProvider destructor does not touch the swept global object on process exit

test/bake/dev/server-sourcemap.test.ts (5 tests) and test/bake/dev/request-cookies.test.ts (2 tests) are green. request-cookies.test.ts now also passes under the full CI LeakSan config (BUN_DESTRUCT_VM_ON_EXIT=1 + detect_leaks=1).

The bug is from a89e61f (#22138), which introduced DevServerSourceProvider with the raw global-object pointer.


[review] gate passed · iteration 1 · 3 files touched

fails on main (without fix)
ASAN without fix: 1 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/bake/dev/request-cookies.test.ts test/bake/dev/server-sourcemap.test.ts
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: checking for self-update (current version: 1.29.0)
bun test v1.4.0 (722d6f067)

test/bake/dev/server-sourcemap.test.ts:
Dev server testing directory: /tmp/bun-dev-test-tI2Y82
bun add v1.4.0 (722d6f067)
Resolving dependencies
Resolved, downloaded and extracted [2]
Saved lockfile

installed react@0.0.0-experimental-603e6108-20241029
installed react-dom@0.0.0-experimental-603e6108-20241029
installed react-server-dom-bun@0.0.0-experimental-603e6108-20241029
installed react-refresh@0.0.0-experimental-603e6108-20241029

6 packages installed [462.00ms]
bun install v1.4.0 (722d6f067)

Checked 6 installs across 7 packages (no changes) [167.00ms]
�[0;30mdev|�[0m Started development server: http://localhost:37377
�[0;30mdev|�[0m �[32mBundled page in 2125ms�[0m�[2m:�[0
... (truncated)

release without fix: all passed
bun test v1.4.0-canary.1 (1498d7b77)

test/bake/dev/server-sourcemap.test.ts:
Dev server testing directory: /tmp/bun-dev-test-7LPeWv
bun add v1.4.0-canary.1 (1498d7b77)
Resolving dependencies
Resolved, downloaded and extracted [0]
Saved lockfile

installed react@0.0.0-experimental-603e6108-20241029
installed react-dom@0.0.0-experimental-603e6108-20241029
installed react-server-dom-bun@0.0.0-experimental-603e6108-20241029
installed react-refresh@0.0.0-experimental-603e6108-20241029

6 packages installed [9.00ms]
bun install v1.4.0-canary.1 (1498d7b77)

Checked 6 installs across 7 packages (no changes) [0.00ms]
�[0;30mdev|�[0m Started development server: http://localhost:43275
�[0;30mdev|�[0m �[32mBundled page in 47ms�[0m�[2m:�[0m pages/[...slug].tsx �[2m+ 2 more�[0m
�[0;30mdev|�[0m �[0m�[1m1 |�[0m �[0m�[35mexport�[0m �[0m�[35mdefault�[0m �[0m�[35masync�[0m �[0m�[35mfunction�[0m MyPage(params) {
�[0;30mdev|�[0m �[0m�[1m2 |�[0m   myFunc()�[0m�[2m;�[0m
�[0;30mdev|�[0m �[0m�[1m3 |�[0m   �[0m�[35mreturn�[0m �[0m<�[0mh1>{JSON�[0m�[3m�[1m.stringify�[0m(params)}�[0m<�[0m/h1>�[0m�[2m;�[0m
�[0;30mdev|�[0m �[0m�[1m4 |�[0m }
�[0;30mdev|�[0m �[0m�[1m5 |�[0m 
�[0;30mdev|�[0m �[0m�
... (truncated)
passes on PR (with fix)
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/bake/dev/request-cookies.test.ts test/bake/dev/server-sourcemap.test.ts
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: checking for self-update (current version: 1.29.0)
bun test v1.4.0 (722d6f067)

test/bake/dev/server-sourcemap.test.ts:
Dev server testing directory: /tmp/bun-dev-test-dkR1se
bun add v1.4.0 (722d6f067)
Resolving dependencies
Resolved, downloaded and extracted [0]
Saved lockfile

installed react@0.0.0-experimental-603e6108-20241029
installed react-dom@0.0.0-experimental-603e6108-20241029
installed react-server-dom-bun@0.0.0-experimental-603e6108-20241029
installed react-refresh@0.0.0-experimental-603e6108-20241029

6 packages installed [119.00ms]
bun install v1.4.0 (722d6f067)

Checked 6 installs across 7 packages (no changes) [97.00ms]
�[0;30mdev|�[0m Started development server: http://localhost:44249
�[0;30mdev|�[0m �[32mBundled page in 2351ms�[0m�[2m:�[0m
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: checking for self-update (current version: 1.29.0)
[configured] bun-profile → bun (stripped) in 690ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[0/6] cargo bun_bin → libbun_rust.a (--target x86_64-unknown-linux-gnu)
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: component rust-std is up to date

  nightly-2026-05-06-x86_64-unknown-linux-gnu unchanged - rustc 1.97.0-nightly (e95e73209 2026-05-05)

info: checking for self-update (current version: 1.29.0)
�[1m�[92m   Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core)
�[1m�[92m   Compiling�[0m bun_errno v0.0.0 (/workspace/bun/src/errno)
�[1m�[92m   Compiling�[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr)
�[1m�[92m   Compiling�[0m bun_boringssl_sys v0.0.0 (/workspace/bun/src/boringssl
... (truncated)
diff hotspot
src/runtime/bake/DevServerSourceProvider.h | 13 +++++++-----
 test/bake/bake-harness.ts                  |  5 +++++
 test/bake/dev/server-sourcemap.test.ts     | 34 ++++++++++++++++++++++++++++++
 3 files changed, 47 insertions(+), 5 deletions(-)

gate history · 1 passed · 0 rejected · iteration 1

evidence per changed file
file                                        reads  edits  tests
src/runtime/bake/DevServerSourceProvider.h      1      2      0
test/bake/bake-harness.ts                       8      2      0
test/bake/dev/server-sourcemap.test.ts          1      4      0

@robobun robobun mentioned this pull request Jul 12, 2026
@robobun

robobun commented Jul 12, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 7:33 AM PT - Jul 12th, 2026

❌ @robobun, your commit 722d6f0 has 2 failures in Build #72230 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 34035

That installs a local version of the PR into your bun-34035 executable, so you can run:

bun-34035 --bun

@coderabbitai

coderabbitai Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@robobun, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 14 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: f5a42eb6-5a89-49b1-8545-416549690a9e

📥 Commits

Reviewing files that changed from the base of the PR and between 0c9627d and 722d6f0.

📒 Files selected for processing (3)
  • src/runtime/bake/DevServerSourceProvider.h
  • test/bake/bake-harness.ts
  • test/bake/dev/server-sourcemap.test.ts

Walkthrough

The dev server source provider now retains its VM pointer for destruction-time unregistering. The bake test harness supports per-test environment variables, and an ASAN-only sourcemap test exercises server availability and teardown behavior.

Changes

Dev server teardown

Layer / File(s) Summary
Retain VM for provider teardown
src/runtime/bake/DevServerSourceProvider.h
The provider stores the Rust VM pointer during creation and uses it to unregister safely during destruction.
Add ASAN teardown regression test
test/bake/bake-harness.ts, test/bake/dev/server-sourcemap.test.ts
Per-test environment overrides are passed to spawned servers, and an ASAN-only test verifies serving / before teardown.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly names the main fix: a use-after-free in DevServerSourceProvider during VM teardown.
Description check ✅ Passed The description explains the fix and verification, but it should use the required template headings.

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

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM — one-line typo fix in the LeakSan skip-list.

Verified test/bake/dev/request-cookies.test.ts exists and react-cookies.test.ts does not; the corrected entry now matches the file it was meant to exclude, alongside its two siblings in the same dev-server-exit block. No runtime code touched.

Extended reasoning...

Overview

Single-character-class fix in test/no-validate-leaksan.txt, changing react-cookies.test.ts → request-cookies.test.ts. This is a plain-text skip-list consumed by scripts/runner.node.mjs to decide which tests get BUN_DESTRUCT_VM_ON_EXIT=1 + LeakSanitizer on the ASAN CI lane. The old entry pointed to a file that has never existed, so the intended test was never actually excluded.

Security risks

None. This is CI test-runner configuration only — no runtime, auth, crypto, or user-facing code is touched.

Level of scrutiny

Minimal. This is a mechanical typo correction in a test infrastructure allowlist. I verified on disk that test/bake/dev/request-cookies.test.ts exists and test/bake/dev/react-cookies.test.ts does not, which is the entire correctness question. The entry sits in the dev-server-on-exit block next to react-response.test.ts and server-sourcemap.test.ts, matching the original intent from #22138 as described.

Other factors

The effect is strictly to reduce what runs under LeakSan for one file — it cannot introduce new failures, only suppress a known ~0.5% flake on the ASAN lane during process teardown. The PR description's investigation is thorough and the fix is the obvious one. No outstanding reviewer comments, no prior reviews from me.

@Jarred-Sumner

Copy link
Copy Markdown
Collaborator

No. Fix the leaks.

@robobun

robobun commented Jul 12, 2026

Copy link
Copy Markdown
Collaborator Author

Understood. Reverting the skip-list edit and looking for the actual dev-server exit crash instead.

What I have so far: the SEGV is at null+0x7490 during gracefulExit on the asan lane (after the test body has already asserted the cookie value), when server.stop(true) + the harness fullGC() loop and then process.exit(0) run the BUN_DESTRUCT_VM_ON_EXIT teardown. The asan report is header-only (abort_on_error=1) so there's no stack, and 50+ local release-asan runs with the full CI env didn't reproduce it. I'll try to force the teardown path deterministically and trace what's at that offset.

@robobun
robobun force-pushed the farm/f8e6015a/fix-leaksan-skiplist-typo branch from ab7c182 to 0c9627d Compare July 12, 2026 12:55
@robobun robobun changed the title test(no-validate-leaksan): fix react-cookies -> request-cookies typo bake: fix use-after-free in ~DevServerSourceProvider during VM teardown Jul 12, 2026
@robobun

robobun commented Jul 12, 2026

Copy link
Copy Markdown
Collaborator Author

Replaced with the real fix. The 0x7490 crash was ~DevServerSourceProvider reading m_globalObject->bunVM() through a Zig::GlobalObject* that had already been swept during destructOnExit's collectNow; the provider outlives the global object because its last ref is held by CodeCacheMap and only drops in ~JSC::VM. Now stores void* m_bunVM directly, matching Zig::SourceProvider. Deterministic under Malloc=1, new ASAN-only test in server-sourcemap.test.ts fails before and passes after. request-cookies.test.ts is clean under the CI LeakSan config with this change.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/bake/dev/server-sourcemap.test.ts`:
- Around line 205-211: Shorten the explanatory comment above the
DevServerSourceProvider teardown test to no more than three lines, retaining
only the essential cause-and-effect details needed to explain the Malloc=1 and
BUN_DESTRUCT_VM_ON_EXIT=1 settings.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 014877a9-d544-4ca2-98a0-94efab655f5a

📥 Commits

Reviewing files that changed from the base of the PR and between ab7c182 and 0c9627d.

📒 Files selected for processing (3)
  • src/runtime/bake/DevServerSourceProvider.h
  • test/bake/bake-harness.ts
  • test/bake/dev/server-sourcemap.test.ts

Comment thread test/bake/dev/server-sourcemap.test.ts Resolved
…obalObject

~DevServerSourceProvider held a raw Zig::GlobalObject* and called
m_globalObject->bunVM() in its destructor. Under BUN_DESTRUCT_VM_ON_EXIT
the teardown in Zig__GlobalObject__destructOnExit runs
gcUnprotect(globalObject) then collectNow(Sync, Full) then
vm.derefSuppressingSaferCPPChecking() twice. The global object cell is
swept during collectNow, and the provider's last Ref is released later
from ~CodeCache inside ~JSC::VM, so the destructor was reading a field
out of a freed cell. With bmalloc the freed cell usually still held the
old m_bunVM value and the read happened to work; in the rare case where
the memory was reused with a zero at that offset the next access was
(null)->source_mappings.mutex at offset 0x7490 and surfaced as
'AddressSanitizer: SEGV on unknown address 0x7490' during gracefulExit
in test/bake/dev/request-cookies.test.ts on the x64-asan lane.

Store the Rust VirtualMachine pointer directly, the way
Zig::SourceProvider already does, so the destructor no longer indirects
through a GC cell.

The new ASAN-only test in server-sourcemap.test.ts runs the dev server
with Malloc=1 (routes JSC cell allocation through system malloc so ASAN
poisons the swept cell) plus BUN_DESTRUCT_VM_ON_EXIT=1; on the unfixed
build it deterministically reports 'heap-use-after-free ... in
Zig::GlobalObject::bunVM() const' from ~DevServerSourceProvider and the
harness throws 'DevServer panicked'. Adds an 'env' option to devTest so
the test can set those for the spawned dev server.
@robobun
robobun force-pushed the farm/f8e6015a/fix-leaksan-skiplist-typo branch from 0c9627d to 722d6f0 Compare July 12, 2026 13:02

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I didn't find any issues, but this is a memory-safety fix in JSC destructor-ordering code and Jarred already engaged on an earlier revision, so it's worth a human sign-off.

Checked: the new void* m_bunVM pattern exactly matches Zig::SourceProvider (ZigSourceProvider.h:76, same rationale comment). Verified in VirtualMachine::global_exit that Zig__GlobalObject__destructOnExit (which runs ~JSC::VM → ~CodeCache → this destructor) precedes self.destroy(), so the captured VirtualMachine* is live for the whole destructor. The Rust export signature (vm: &mut VirtualMachine) is unchanged. The harness env spread is placed last in mergeWindowEnvs so per-test overrides win.

Extended reasoning...

Overview

Three files:

  • src/runtime/bake/DevServerSourceProvider.h: replaces the raw Zig::GlobalObject* member with void* m_bunVM, captured once in create() via zigGlobalObject->bunVM(). The destructor now passes the stored pointer directly to Bun__removeDevServerSourceProvider instead of dereferencing a GC cell that may have been swept.
  • test/bake/bake-harness.ts: adds an optional env field to DevServerTest and spreads it (last) into the spawned dev-server's environment.
  • test/bake/dev/server-sourcemap.test.ts: adds an ASAN-gated regression test that sets Malloc=1 + BUN_DESTRUCT_VM_ON_EXIT=1 to make the swept-cell read deterministic, then relies on the harness's gracefulExit() to exercise the teardown path.

Security risks

None. This is a lifetime fix internal to the dev-server source-provider bookkeeping; no user-controlled input, no auth/crypto/permissions surface.

Level of scrutiny

High — this is native memory-safety code at the intersection of JSC GC sweep ordering and Rust VM teardown. The fix is small and mechanical (it copies the exact pattern already used by Zig::SourceProvider for the same reason, per the comment at ZigSourceProvider.h:74-76), and the PR description's lifetime argument checks out against VirtualMachine::global_exit (destructOnExit at line 1603 runs before self.destroy() at line 1613). But destructor-ordering fixes in the JSC integration are exactly the class of change a maintainer should confirm.

Other factors

  • Jarred already reviewed an earlier revision of this PR ("No. Fix the leaks.") and the PR was substantially rewritten in response. He should confirm the rewrite is what he wanted.
  • No CODEOWNERS entry covers src/runtime/bake/.
  • The regression test is ASAN-only (correctly gated on isASAN), sets detect_leaks=0 to keep it hermetic against outer-runner LSan config, and the harness's OutputLineStream panic detector already matches AddressSanitizer output so a UAF would fail gracefulExit().
  • The harness ...options.env spread is placed after all fixed keys, so tests can override e.g. ASAN_OPTIONS as intended; mergeWindowEnvs is variadic and already used with the two-element array shape here.

@robobun

robobun commented Jul 12, 2026

Copy link
Copy Markdown
Collaborator Author

CI on build 72230: the x64-asan lane is 20/20 green, including the new DevServerSourceProvider teardown test and request-cookies.test.ts. The only red is test/js/bun/jsc/bun-jsc.test.ts on aarch64 (profile can be called multiple times: profiler sampled zero traces for fib(26)); it is unrelated to this change, also flaky in builds 72185 and 72204, and already being tracked as a main break.

@Jarred-Sumner
Jarred-Sumner merged commit 134838f into main Jul 12, 2026
75 of 78 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the farm/f8e6015a/fix-leaksan-skiplist-typo branch July 12, 2026 23:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants