-
Notifications
You must be signed in to change notification settings - Fork 4.7k
JSTranspiler: fix use-after-free of log messages in async transform() #30180
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
Open
robobun
wants to merge
1
commit into
main
Choose a base branch
from
farm/e07bc738/transpiler-async-log-uaf
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
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
25 changes: 25 additions & 0 deletions
25
test/js/bun/transpiler/transpiler-async-log-uaf-fixture.ts
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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,31 @@ | ||
| import { expect, test } from "bun:test"; | ||
| import { bunEnv, bunExe } from "harness"; | ||
| import path from "node:path"; | ||
|
|
||
| // `Bun.Transpiler.transform()` runs parsing on a worker thread using an arena | ||
| // allocator. Log messages (text + locations) were allocated from that arena, | ||
| // which was freed before the promise was settled on the JS thread, leading to | ||
| // a use-after-free when rendering the error. Run the repro in a subprocess so | ||
| // an ASAN abort is observed as a test failure rather than killing the runner. | ||
| test("async transform with parse errors does not read freed log messages", async () => { | ||
| await using proc = Bun.spawn({ | ||
| cmd: [bunExe(), path.join(import.meta.dir, "transpiler-async-log-uaf-fixture.ts")], | ||
| env: bunEnv, | ||
| stdout: "pipe", | ||
| stderr: "pipe", | ||
| }); | ||
|
|
||
| const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); | ||
|
|
||
| expect({ | ||
| stdout: stdout.trim(), | ||
| exitCode, | ||
| signalCode: proc.signalCode, | ||
| asan: stderr.includes("AddressSanitizer"), | ||
| }).toEqual({ | ||
| stdout: "DONE", | ||
| exitCode: 0, | ||
| signalCode: null, | ||
| asan: false, | ||
| }); | ||
| }); |
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 (pre-existing pattern, not blocking):
cloneToWithRecycled()allocates the string-builder backing buffer andnotes_buffrombun.default_allocator, butLog.deinit()only frees themsgsArrayList — so each asynctransform()that emits parse errors now leaks those two small allocations. This is the same leak that already exists inRuntimeTranspilerStore.zig:326(and othercloneToWithRecycledcallers), and trading the UAF for a bounded error-path leak is the right call here; the proper fix belongs inlogger.zig(haveLogtrack/free the cloned buffers) as a follow-up.Extended reasoning...
What the bug is
cloneToWithRecycled()(src/logger.zig:797-823) deep-copies log messages by computing the total byte length of all message text/locations, callingstring_builder.allocate(other.msgs.allocator)for one contiguous string buffer, andother.msgs.allocator.alloc(Data, notes_count)for the notes array. InTransformTask.run(),otheristhis.log, which was initialized inTransformTask.create()withlogger.Log.init(bun.default_allocator)— so both allocations come frombun.default_allocator.The cloned
Msgstructs hold slices into these two buffers, but theLogstruct itself (logger.zig:604-610) has no field tracking the backing allocations.Log.deinit()(logger.zig:835-836) is justmsgs.clearAndFree(), which frees theArrayList(Msg)storage but never frees the string-builder buffer or the notes buffer.TransformTask.deinit()callsthis.log.deinit()and nothing else touches these buffers, so they leak.Code path
TransformTask.create()→this.log = logger.Log.init(bun.default_allocator), sothis.log.msgs.allocator == bun.default_allocator.TransformTask.run()parses with an arena-backed locallog; on scope exit,defer log.cloneToWithRecycled(&this.log, true)runs.cloneToWithRecycled:string_builder.allocate(this.log.msgs.allocator)andthis.log.msgs.allocator.alloc(Data, notes_count)allocate frombun.default_allocator. The localstring_buildergoes out of scope; the only references to its buffer are theMsg.data.text/.locationslices.then()callsthis.log.toJS()→BuildMessage.create→Msg.clonewhichallocator.dupe()s the strings again into JS-owned memory. Ownership of the original buffers is never transferred.TransformTask.deinit()→this.log.deinit()→msgs.clearAndFree(). The string buffer and notes buffer are never freed.Why existing code doesn't prevent it
Logsimply has no ownership model for the auxiliary bufferscloneToWithRecycledcreates — there is no field to store them anddeinit()doesn't iterate messages. This is a design gap inlogger.zig, not something specific to this call site. The identical leak already exists atsrc/bun.js/RuntimeTranspilerStore.zig:326(the pattern this PR explicitly follows), and in othercloneToWithRecycledcallers likebundle_v2.zig/HTMLBundle.zig.Impact
Small, error-path-only leak: each async
transform()call that produces parse errors/warnings leaks one string buffer (sized to the total error text) plus one[]Datafor notes, frombun.default_allocator. Before this PR the same strings lived in the arena, which was freed (hence the UAF) — so this PR converts a crash into a bounded leak, which is a strict improvement.Step-by-step proof
Repro:
for (let i = 0; i < N; i++) await t.transform('const x: = y;', 'ts').catch(()=>{});cloneToWithRecycledallocates a string buffer of ~tens of bytes frombun.default_allocator.then()rejects,deinit()runs,msgs.clearAndFree()frees theMsg[]array.Loghas no field for it, so it cannot be freed.How to fix (follow-up, not for this PR)
Fix in
logger.zigrather than at each call site: either haveLogstore thestring_builderbuffer /notes_bufhandles populated bycloneToWithRecycledand free them inLog.deinit(), or havecloneToWithRecycledallocate per-message owned strings thatMsg.deinitcan free. Given the same pattern is used inRuntimeTranspilerStore, a single fix there cleans up all call sites.