Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
14 changes: 4 additions & 10 deletions src/install/PackageInstall.rs
Original file line number Diff line number Diff line change
Expand Up @@ -535,16 +535,10 @@ impl HardLinkWindowsInstallTask {
// whose internal Release/Acquire on the task queue is what publishes the
// first-call `MaybeUninit::write` below.
//
// We must NOT re-assign the whole struct each call: even though `copy()` always reaches `queue.wait()`
// before returning (see the loop_err handling there), `WaitGroup::wait()` can
// return while the last worker is still inside `WaitGroup::finish()` *after*
// its `fetch_sub` — touching `mutex`/`cond` for the lock-unlock-signal dance.
// Overwriting `wait_group` (or forming `&mut HardLinkQueue` at all) would race
// with that trailing access. Instead, on re-init we only drain `errored_task`
// through its own mutex; `wait_group`'s counter is already 0 and its
// Mutex/Condvar are `Sync`, so a stale `finish()` tail concurrently
// locking/signalling them is well-defined. `thread_pool` points at the
// process-wide `PackageManager` singleton and never changes.
// On re-init we only drain `errored_task` through its own mutex instead of
// re-assigning the whole struct: `wait_group`'s counter is already 0 and
// `thread_pool` points at the process-wide `PackageManager` singleton that
// never changes, so a fresh write would be a no-op anyway.
static INITIALIZED: core::sync::atomic::AtomicBool =
core::sync::atomic::AtomicBool::new(false);
unsafe {
Expand Down
34 changes: 24 additions & 10 deletions src/threading/WaitGroup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,20 +47,34 @@ impl WaitGroup {
}

pub fn finish(&self) {
let old_count = self.raw_count.fetch_sub(1, Ordering::AcqRel);
if old_count > 1 {
return;
// Fast path: decrement lock-free while there are other outstanding
// tasks. We cannot unconditionally `fetch_sub(1)` and then lock/signal
// for the last one: the moment `raw_count` reaches 0 a concurrent
// `wait()` can observe it, return, and the caller drop the `WaitGroup`,
// so any later `self.mutex`/`self.cond` access is a use-after-free.
let mut old = self.raw_count.load(Ordering::Relaxed);
while old > 1 {
match self.raw_count.compare_exchange_weak(
old,
old - 1,
Ordering::AcqRel,
Ordering::Relaxed,
) {
Ok(_) => return,
Err(cur) => old = cur,
}
}

// This is the last task, so we need to signal the condition. If we were to call `cond.signal`
// right now, a concurrent call to `wait` which has read a non-zero count (from before we
// decremented it above) but which has not yet called `cond.wait` will miss the signal and
// end up blocking forever. A thread in this state (in between reading the count and calling
// `cond.wait`) is necessarily holding the mutex, so by locking and unlocking the mutex here,
// we ensure that it reaches the call to `cond.wait` before we call `cond.signal`.
// We are (or a concurrent `add` may yet make us not) the last one.
// Publish `raw_count == 0` only while holding the mutex so `wait()`,
// which checks the count under the same mutex, cannot return until our
// `unlock()` below. Signal before unlocking so the waiter's reacquire
// serializes after every `self` access we make.
self.mutex.lock();
self.mutex.unlock();
let old_count = self.raw_count.fetch_sub(1, Ordering::AcqRel);
debug_assert!(old_count >= 1);
self.cond.signal();
self.mutex.unlock();
}

pub fn wait(&self) {
Expand Down
79 changes: 79 additions & 0 deletions test/bundler/bun-build-sourcemap-link-error-uaf.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { expect, test } from "bun:test";
import { bunEnv, bunExe, isASAN, tempDir } from "harness";

// Regression guard for a heap-use-after-free observed under ASAN during
// back-to-back Bun.build() calls that enable sourcemaps and fail with a
// link-time "no matching export" error. `compute_data_for_source_map`
// schedules source-map tasks onto the work pool, then `link()` returns Err,
// and the caller waits on the source-map WaitGroups before dropping the
// heap-allocated BundleV2. The last worker's `WaitGroup::finish()` must not
// touch `self` after publishing count==0 because that lets `wait()` return
// and the owner free the WaitGroup; the slow-path `Mutex::lock()` that
// followed would then write to freed memory. The window needs the worker to
// be futex-parked in `Mutex::lock_slow` past the drop, so this is a stress
// loop rather than a deterministic probe. ASAN-only: release builds would
// just silently write to freed-but-unreused memory.
test.skipIf(!isASAN)(
"Bun.build sourcemap + link-time error drops BundleV2 only after the last source-map WaitGroup::finish() is done",
async () => {
const N_FILES = 8;
const N_ITER = 300;

const files: Record<string, string> = {
"package.json": `{"type":"module"}`,
};
let entry = "";
for (let i = 0; i < N_FILES; i++) {
entry += `import { v${i} } from "./leaf${i}";\n`;
}
entry += `export const out = [${Array.from({ length: N_FILES }, (_, i) => `v${i}`).join(",")}];\n`;
files["entry.ts"] = entry;
// leaf0 imports a binding that entry.ts does not export: a link-time
// error detected after source-map tasks are already scheduled.
files["leaf0.ts"] = `import { DOES_NOT_EXIST } from "./entry";\nexport const v0 = DOES_NOT_EXIST;\n`;
for (let i = 1; i < N_FILES; i++) {
files[`leaf${i}.ts`] = `export const v${i} = ${i};\n`;
}

// Inline runner so a single child process performs every iteration.
files["run.ts"] = `
const { join } = require("path");
const dir = process.argv[2];
const iters = parseInt(process.argv[3], 10);
let failed = 0;
for (let i = 0; i < iters; i++) {
try {
await Bun.build({
entrypoints: [join(dir, "entry.ts")],
sourcemap: "external",
outdir: join(dir, "out"),
});
console.error("unexpected success at iter", i);
process.exit(1);
} catch {
failed++;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
console.log("failed=" + failed + " of " + iters);
`;

using dir = tempDir("bun-build-sourcemap-link-error-uaf", files);

await using proc = Bun.spawn({
cmd: [bunExe(), "run.ts", String(dir), String(N_ITER)],
env: bunEnv,
cwd: String(dir),
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);

// ASAN aborts the child with a heap-use-after-free report on stderr when
// the race fires; otherwise every iteration rejects with a build error.
expect(stderr).not.toContain("AddressSanitizer");
expect(stderr).not.toContain("heap-use-after-free");
expect(stdout.trim()).toBe(`failed=${N_ITER} of ${N_ITER}`);
expect(exitCode).toBe(0);
},
60_000,

Check warning on line 78 in test/bundler/bun-build-sourcemap-link-error-uaf.test.ts

View check run for this annotation

Claude / Claude Code Review

Explicit 60_000ms test timeout violates test/CLAUDE.md

nit: `test/CLAUDE.md` says "**CRITICAL**: Do not set a timeout on tests. Bun already has timeouts", and REVIEW.md's guidance is to shrink the workload rather than raise the per-test timeout. If 300 ASAN iterations fit under the harness default you can drop the `60_000`; if they don't, consider trimming `N_ITER` instead. Acknowledged that neighboring bundler tests (e.g. `bun-build-api.test.ts`) do the same and that the iteration count here is load-bearing, so not blocking.
Comment thread
robobun marked this conversation as resolved.
Resolved
);
Loading