Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions src/runtime/api/JSTranspiler.zig
Original file line number Diff line number Diff line change
Expand Up @@ -500,9 +500,16 @@ pub const TransformTask = struct {
var ast_scope = ast_memory_allocator.enter(allocator);
defer ast_scope.exit();

// The parser allocates error message text using the transpiler's
// allocator (the arena above). Collect messages in a local log and
// deep-copy them into `this.log` before the arena is destroyed so
// `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.


this.transpiler.setAllocator(allocator);
this.transpiler.setLog(&this.log);
this.log.msgs.allocator = bun.default_allocator;
this.transpiler.setLog(&local_log);

const jsx = if (this.tsconfig != null)
this.tsconfig.?.mergeJSX(this.transpiler.options.jsx)
Expand Down
41 changes: 41 additions & 0 deletions test/js/bun/transpiler/transpiler-async-error-uaf.test.ts
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");
});
});
Loading