Skip to content

Fix use-after-free in Bun.Transpiler async transform() error messages#30469

Closed
robobun wants to merge 2 commits into
mainfrom
farm/2691ca7d/fix-transpiler-async-error-uaf
Closed

Fix use-after-free in Bun.Transpiler async transform() error messages#30469
robobun wants to merge 2 commits into
mainfrom
farm/2691ca7d/fix-transpiler-async-error-uaf

Conversation

@robobun

@robobun robobun commented May 11, 2026

Copy link
Copy Markdown
Collaborator

What does this PR do?

Fixes a use-after-free in Bun.Transpiler#transform() (the async variant) when parsing fails.

TransformTask.run() runs on a worker thread and uses a MimallocArena as the transpiler's allocator for parsing. Error message text produced by the parser is allocated from that arena. The arena is destroyed when run() returns. Later, then() runs on the JS thread and calls log.toJS()BuildMessage.create()Msg.clone()allocator.dupe(u8, text), which reads the freed arena memory.

Under ASAN this shows as use-after-poison in Data.clone; in release builds the rejection's BuildMessage contains garbage bytes instead of the real error message.

Fix

Collect parse messages in a local arena-backed log and deep-copy them into the task's persistent log (backed by bun.default_allocator) via appendToWithRecycled(..., true) in a defer that runs before the arena is destroyed.

How did you verify your code works?

Minimal repro (crashes under ASAN before, garbage message text in release before):

const transpiler = new Bun.Transpiler();
const promises = [];
for (let i = 0; i < 50; i++) {
  promises.push(transpiler.transform("const x = @@@", "js").catch(e => e));
}
await Promise.all(promises);

Added a regression test in test/js/bun/transpiler/transpiler-async-error-uaf.test.ts that asserts the rejection is a BuildMessage with the correct message and position. The test fails on current main (receives garbage bytes like "H)yôP)yôX)yô") and passes with this fix. Existing transpiler tests continue to pass.

TransformTask.run() uses a MimallocArena for parsing that is destroyed when
run() returns on the worker thread. Parse error message text is allocated
from that arena. When then() later runs on the JS thread and converts the
log to a BuildMessage, it reads freed memory.

Collect messages in a local arena-backed log and deep-copy them into the
task's persistent log (backed by bun.default_allocator) before the arena is
destroyed.
@robobun

robobun commented May 11, 2026

Copy link
Copy Markdown
Collaborator Author
Updated 5:21 PM PT - May 10th, 2026

@autofix-ci[bot], your commit d20758f has 1 failures in Build #53205 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 30469

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

bun-30469 --bun

@coderabbitai

coderabbitai Bot commented May 11, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack
No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 8edf1690-0cd8-44a2-ab17-4c00bb386e97

📥 Commits

Reviewing files that changed from the base of the PR and between c6f8b27 and d20758f.

📒 Files selected for processing (1)
  • test/js/bun/transpiler/transpiler-async-error-uaf.test.ts

Walkthrough

TransformTask.run now writes transpiler errors to an arena-allocated local_log and defers deep-copying those messages into this.log before freeing the arena. Two concurrent tests verify returned BuildMessage errors and their position metadata remain usable after the arena is freed.

Changes

Async Transpiler Error Lifetime Safety

Layer / File(s) Summary
Memory Safety Fix
src/runtime/api/JSTranspiler.zig
TransformTask.run allocates local_log from the task arena, points the transpiler at it, and defers copying/recycling messages into this.log before arena cleanup to prevent UAF when JS reads errors.
Test Validation
test/js/bun/transpiler/transpiler-async-error-uaf.test.ts
Two concurrent tests validate that transpiler.transform() rejections are BuildMessage instances with correct message and position metadata and remain usable after the underlying arena is freed.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely describes the main change: fixing a use-after-free bug in Bun.Transpiler async error handling.
Description check ✅ Passed The description provides comprehensive coverage of both required sections with clear explanations of the problem, the fix, and verification steps.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

@github-actions

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. Fix use-after-free in Bun.Transpiler async transform() errors #29958 - Fixes the same UAF in TransformTask.run() where MimallocArena is destroyed before log messages are read in then(); uses appendToWithRecycled to deep-copy the log
  2. JSTranspiler: fix use-after-free of log messages in async transform() #30180 - Fixes the identical UAF in the TransformTask run()/then() path with arena-backed log deep-copied via cloneToWithRecycled before arena teardown
  3. Fix use-after-free in Bun.Transpiler async transform() errors #30263 - Same root cause (arena destroyed in run(), log text read in then()) with the same deep-clone fix into bun.default_allocator
  4. Fix use-after-free in Bun.Transpiler.transform() error reporting #30309 - Fixes the same MimallocArena lifetime UAF in TransformTask.run() by cloning log messages into bun.default_allocator in a defer before arena.deinit()

🤖 Generated with Claude Code

@robobun

robobun commented May 11, 2026

Copy link
Copy Markdown
Collaborator Author

Duplicate of #30263 (already approved).

@robobun robobun closed this May 11, 2026
@robobun robobun deleted the farm/2691ca7d/fix-transpiler-async-error-uaf branch May 11, 2026 00:20
// `then()` on the JS thread does not read freed memory.
var local_log = logger.Log.init(allocator);
local_log.level = this.log.level;
defer bun.handleOom(local_log.appendToWithRecycled(&this.log, true));

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.

🟡 Nit: appendToWithRecycled(&this.log, true) deep-copies message text into a StringBuilder buffer + notes_buf allocated from bun.default_allocator (logger.zig:739-740), but Log.deinit() only does msgs.clearAndFree() and never frees those buffers, so each failed async transform() now leaks ~tens of bytes. Trading the UAF for this small error-path leak is clearly the right call and matches the established pattern (RuntimeTranspilerStore.zig, BundleThread.zig, ParseTask.zig, etc.) and the known TODO at logger.zig:767 — just flagging for awareness; a real fix belongs in cloneToWithRecycled/Log.deinit, not here.

Extended reasoning...

What the issue is

local_log.appendToWithRecycled(&this.log, true) calls cloneToWithRecycled (src/logger/logger.zig:723-750), which — when recycled == true — performs a deep copy of every message's text, file path, line_text, and notes into freshly-allocated memory owned by other.msgs.allocator. Since this.log was created with logger.Log.init(bun.default_allocator) (JSTranspiler.zig:479), that allocator is bun.default_allocator. Two allocations are made there:

  • string_builder.allocate(other.msgs.allocator) at logger.zig:739 — one contiguous buffer holding all copied string data
  • other.msgs.allocator.alloc(Data, total_notes_count) at logger.zig:740 — the notes backing array

Neither of these is ever freed.

Why nothing frees it

TransformTask.deinit() calls this.log.deinit(), but Log.deinit() (logger.zig:761-765) only does log.msgs.clearAndFree(), which frees the ArrayList(Msg) backing storage — not the per-message text slices or the shared notes_buf. The codebase explicitly acknowledges this at logger.zig:767 with a TODO noting that "deinit does not de-initialize the log; it clears it."

The consumer side doesn't free it either: then()log.toJS()BuildMessage.create()Msg.clone()allocator.dupe(u8, text) makes another copy without taking ownership of the original. And because cloneToWithRecycled packs all message text into one shared StringBuilder buffer, individual Msg.deinit() calls couldn't correctly free it anyway — it's a single allocation sliced N ways.

Step-by-step proof

  1. User calls await transpiler.transform("const x = @@@", "js").
  2. TransformTask.run() creates arena and local_log = logger.Log.init(arena.allocator()).
  3. Parser fails and pushes a Msg into local_log whose data.text = "Expected identifier but found \"@\"", location.file = "input.js", location.line_text = "const x = @@@" — all arena-allocated.
  4. run() returns. The defer fires: local_log.appendToWithRecycled(&this.log, true).
  5. cloneToWithRecycled counts ~55 bytes of string data, calls string_builder.allocate(bun.default_allocator) → one ~55-byte heap buffer, plus notes_buf = bun.default_allocator.alloc(Data, 0) (zero-length, so no real alloc for notes here). The Msg in this.log now points into that heap buffer.
  6. Arena is destroyed (fine — nothing points into it anymore).
  7. JS thread: then() reads this.log, builds a BuildMessage by duping the text again, then this.deinit() runs.
  8. this.log.deinit()msgs.clearAndFree() frees the 1-element ArrayList(Msg) storage. The ~55-byte StringBuilder buffer from step 5 is never passed to bun.default_allocator.free. Leaked.

The regression test runs 50 failing transforms, so it leaks ~50 × ~55 bytes ≈ 2-3 KB total. On the success path local_log has 0 messages, string_builder.cap == 0, and alloc(u8, 0) doesn't actually allocate, so there's no leak when parsing succeeds.

Before vs. after this PR

Before: error text lived in the arena and was freed by arena.deinit() — no leak, but then() then read freed memory (the UAF this PR fixes). After: error text lives in bun.default_allocator and is never freed — no UAF, small leak. This is unambiguously the right trade.

Why this is a nit, not a blocker

This exact pattern — appendToWithRecycled/cloneToWithRecycled(.., true) into a default_allocator-backed Log that is later only .deinit()'d — is already used identically in 10+ places: RuntimeTranspilerStore.zig:326, BundleThread.zig:153/160, ParseTask.zig:356/367/378, bundle_v2.zig:3639/3787, HTMLBundle.zig:330, npm.zig:1745, Installer.zig:172. The PR is following established codebase convention, and the limitation is documented at logger.zig:767. The leak is error-path only and tiny.

How to fix (out of scope here)

The proper fix is in the logger module: have cloneToWithRecycled stash the StringBuilder buffer pointer + notes_buf on the destination Log (e.g. an owned_buffers list) and have Log.deinit() free them. That would fix this call site and the dozen others simultaneously. Nothing actionable in JSTranspiler.zig itself.

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.

1 participant