-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Fix use-after-free in Bun.Transpiler async transform() error messages #30469
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| import { describe, expect, test } from "bun:test"; | ||
|
|
||
| describe("Transpiler async transform() error lifetime", () => { | ||
| test.concurrent("concurrent async transform() parse errors do not read freed memory", async () => { | ||
| const transpiler = new Bun.Transpiler(); | ||
| const promises: Promise<unknown>[] = []; | ||
| for (let i = 0; i < 50; i++) { | ||
| promises.push( | ||
| transpiler.transform("const x = @@@", "js").then( | ||
| () => null, | ||
| e => e, | ||
| ), | ||
| ); | ||
| } | ||
| const results = await Promise.all(promises); | ||
| for (const r of results) { | ||
| expect(r).toBeInstanceOf(BuildMessage); | ||
| const msg = r as BuildMessage; | ||
| expect(msg.message).toBe('Expected identifier but found "@"'); | ||
| expect(msg.position).toEqual({ | ||
| lineText: "const x = @@@", | ||
| file: "input.js", | ||
| namespace: "file", | ||
| line: 1, | ||
| column: 12, | ||
| length: 1, | ||
| offset: 11, | ||
| }); | ||
| } | ||
| }); | ||
|
|
||
| test.concurrent("async transform() rejects with a usable BuildMessage after arena is freed", async () => { | ||
| const transpiler = new Bun.Transpiler(); | ||
| const err = await transpiler.transform("1 + ", "js").then( | ||
| () => null, | ||
| e => e, | ||
| ); | ||
| expect(err).toBeInstanceOf(BuildMessage); | ||
| expect((err as BuildMessage).message).toBe("Unexpected end of file"); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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_bufallocated frombun.default_allocator(logger.zig:739-740), butLog.deinit()only doesmsgs.clearAndFree()and never frees those buffers, so each failed asynctransform()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 incloneToWithRecycled/Log.deinit, not here.Extended reasoning...
What the issue is
local_log.appendToWithRecycled(&this.log, true)callscloneToWithRecycled(src/logger/logger.zig:723-750), which — whenrecycled == true— performs a deep copy of every message's text, file path, line_text, and notes into freshly-allocated memory owned byother.msgs.allocator. Sincethis.logwas created withlogger.Log.init(bun.default_allocator)(JSTranspiler.zig:479), that allocator isbun.default_allocator. Two allocations are made there:string_builder.allocate(other.msgs.allocator)at logger.zig:739 — one contiguous buffer holding all copied string dataother.msgs.allocator.alloc(Data, total_notes_count)at logger.zig:740 — the notes backing arrayNeither of these is ever freed.
Why nothing frees it
TransformTask.deinit()callsthis.log.deinit(), butLog.deinit()(logger.zig:761-765) only doeslog.msgs.clearAndFree(), which frees theArrayList(Msg)backing storage — not the per-message text slices or the sharednotes_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 becausecloneToWithRecycledpacks all message text into one shared StringBuilder buffer, individualMsg.deinit()calls couldn't correctly free it anyway — it's a single allocation sliced N ways.Step-by-step proof
await transpiler.transform("const x = @@@", "js").TransformTask.run()createsarenaandlocal_log = logger.Log.init(arena.allocator()).Msgintolocal_logwhosedata.text = "Expected identifier but found \"@\"",location.file = "input.js",location.line_text = "const x = @@@"— all arena-allocated.run()returns. Thedeferfires:local_log.appendToWithRecycled(&this.log, true).cloneToWithRecycledcounts ~55 bytes of string data, callsstring_builder.allocate(bun.default_allocator)→ one ~55-byte heap buffer, plusnotes_buf = bun.default_allocator.alloc(Data, 0)(zero-length, so no real alloc for notes here). The Msg inthis.lognow points into that heap buffer.then()readsthis.log, builds aBuildMessageby duping the text again, thenthis.deinit()runs.this.log.deinit()→msgs.clearAndFree()frees the 1-elementArrayList(Msg)storage. The ~55-byte StringBuilder buffer from step 5 is never passed tobun.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_loghas 0 messages,string_builder.cap == 0, andalloc(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, butthen()then read freed memory (the UAF this PR fixes). After: error text lives inbun.default_allocatorand 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 adefault_allocator-backedLogthat 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
cloneToWithRecycledstash the StringBuilder buffer pointer +notes_bufon the destinationLog(e.g. anowned_bufferslist) and haveLog.deinit()free them. That would fix this call site and the dozen others simultaneously. Nothing actionable in JSTranspiler.zig itself.