From 4b165e5f274921d5e7279beb34d577cf4e87ff92 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 17 Jul 2026 06:26:12 +0000 Subject: [PATCH 1/4] threading: don't touch WaitGroup after publishing count==0 in finish() WaitGroup::finish() decremented raw_count to 0 and then locked/unlocked the mutex and signalled the condvar. Once raw_count is 0 a concurrent wait() can observe it and return, after which the caller is free to drop the WaitGroup, so the trailing mutex.lock()/cond.signal() are writes to freed memory. Observed as a rare ASAN heap-use-after-free on a Bun Pool thread during back-to-back Bun.build() calls (bun-build-api.test.ts, debian 13 x64-asan). The failing pc maps to Mutex::FutexImpl::lock_slow's state.swap(CONTENDED), reached from WaitGroup::finish() acting on the source-map wait groups inside the heap-allocated BundleV2 on the error path of a sourcemap + link-time-error build. finish() now only publishes 0 while holding the mutex, so wait() cannot return (and the caller cannot free the WaitGroup) until after finish()'s unlock(). The fast path for count>1 stays lock-free via a CAS loop. --- src/install/PackageInstall.rs | 14 +--- src/threading/WaitGroup.rs | 34 +++++--- ...bun-build-sourcemap-link-error-uaf.test.ts | 79 +++++++++++++++++++ 3 files changed, 107 insertions(+), 20 deletions(-) create mode 100644 test/bundler/bun-build-sourcemap-link-error-uaf.test.ts diff --git a/src/install/PackageInstall.rs b/src/install/PackageInstall.rs index d21790e80947..a9a55c30a6b6 100644 --- a/src/install/PackageInstall.rs +++ b/src/install/PackageInstall.rs @@ -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 { diff --git a/src/threading/WaitGroup.rs b/src/threading/WaitGroup.rs index 584fea64aaa7..f64c40547fab 100644 --- a/src/threading/WaitGroup.rs +++ b/src/threading/WaitGroup.rs @@ -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) { diff --git a/test/bundler/bun-build-sourcemap-link-error-uaf.test.ts b/test/bundler/bun-build-sourcemap-link-error-uaf.test.ts new file mode 100644 index 000000000000..b25403c8d5d3 --- /dev/null +++ b/test/bundler/bun-build-sourcemap-link-error-uaf.test.ts @@ -0,0 +1,79 @@ +import { test, expect } 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 = { + "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++; + } +} +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, +); From a9841a5359f4034bd502d5217d7668ca8ebd6326 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Fri, 17 Jul 2026 06:29:36 +0000 Subject: [PATCH 2/4] [autofix.ci] apply automated fixes --- test/bundler/bun-build-sourcemap-link-error-uaf.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/bundler/bun-build-sourcemap-link-error-uaf.test.ts b/test/bundler/bun-build-sourcemap-link-error-uaf.test.ts index b25403c8d5d3..caeaadeb8170 100644 --- a/test/bundler/bun-build-sourcemap-link-error-uaf.test.ts +++ b/test/bundler/bun-build-sourcemap-link-error-uaf.test.ts @@ -1,4 +1,4 @@ -import { test, expect } from "bun:test"; +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 From 97f2eba2070c325293da674f3ff7e0adfab58e6d Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 17 Jul 2026 06:56:58 +0000 Subject: [PATCH 3/4] test: validate the expected linker error in the catch block Also switch the child fixture's path import from require() to a module-scope import. --- .../bundler/bun-build-sourcemap-link-error-uaf.test.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/test/bundler/bun-build-sourcemap-link-error-uaf.test.ts b/test/bundler/bun-build-sourcemap-link-error-uaf.test.ts index caeaadeb8170..b205879e1f98 100644 --- a/test/bundler/bun-build-sourcemap-link-error-uaf.test.ts +++ b/test/bundler/bun-build-sourcemap-link-error-uaf.test.ts @@ -37,7 +37,7 @@ test.skipIf(!isASAN)( // Inline runner so a single child process performs every iteration. files["run.ts"] = ` -const { join } = require("path"); +import { join } from "node:path"; const dir = process.argv[2]; const iters = parseInt(process.argv[3], 10); let failed = 0; @@ -50,7 +50,13 @@ for (let i = 0; i < iters; i++) { }); console.error("unexpected success at iter", i); process.exit(1); - } catch { + } catch (error) { + if ( + !(error instanceof AggregateError) || + !error.errors.some(e => String(e?.message).includes("No matching export")) + ) { + throw error; + } failed++; } } From 4d06bedc1c3d3fbf77bbf0dfdc08d847dbae3343 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 17 Jul 2026 07:07:22 +0000 Subject: [PATCH 4/4] Replace the bundler stress test with a WaitGroup unit test Self-review: the 300-iteration Bun.build() stress loop cannot fail on the unpatched build (29,000 iterations across three configurations didn't fire) so it is CI time with no regression-detection value, and a new standalone test file goes against the 'add to the existing test file' convention. Drop it and add a #[cfg(test)] unit test that drops a boxed WaitGroup immediately after wait() returns; it runs under 'cargo test -p bun_threading' and documents the invariant directly on the primitive. --- src/threading/WaitGroup.rs | 33 +++++++ ...bun-build-sourcemap-link-error-uaf.test.ts | 85 ------------------- 2 files changed, 33 insertions(+), 85 deletions(-) delete mode 100644 test/bundler/bun-build-sourcemap-link-error-uaf.test.ts diff --git a/src/threading/WaitGroup.rs b/src/threading/WaitGroup.rs index f64c40547fab..1ad251ca2725 100644 --- a/src/threading/WaitGroup.rs +++ b/src/threading/WaitGroup.rs @@ -89,3 +89,36 @@ impl WaitGroup { self.mutex.unlock(); } } + +#[cfg(test)] +mod tests { + use super::*; + + // After `wait()` returns the caller may drop the `WaitGroup`; `finish()` + // must therefore not touch `self` once it has published `raw_count == 0`. + #[test] + fn wait_returning_means_finish_is_done_with_self() { + for _ in 0..10_000 { + let wg = Box::into_raw(Box::new(WaitGroup::init_with_count(1))); + struct SendPtr(*mut WaitGroup); + // SAFETY: `WaitGroup` is `Sync`; the raw pointer is only ever + // dereferenced while the pointee is live (joined below). + unsafe impl Send for SendPtr {} + let p = SendPtr(wg); + let t = std::thread::spawn(move || { + let p = p; + // SAFETY: `wg` is live until `drop(Box::from_raw(..))` below, + // which happens-before `join()`, so the pointee outlives this + // deref iff `finish()` is done with `self` by the time + // `wait()` returns — the property under test. + unsafe { (*p.0).finish() }; + }); + // SAFETY: `wg` is the freshly-boxed allocation; sole owner here. + unsafe { + (*wg).wait(); + drop(Box::from_raw(wg)); + } + t.join().unwrap(); + } + } +} diff --git a/test/bundler/bun-build-sourcemap-link-error-uaf.test.ts b/test/bundler/bun-build-sourcemap-link-error-uaf.test.ts deleted file mode 100644 index b205879e1f98..000000000000 --- a/test/bundler/bun-build-sourcemap-link-error-uaf.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -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 = { - "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"] = ` -import { join } from "node: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 (error) { - if ( - !(error instanceof AggregateError) || - !error.errors.some(e => String(e?.message).includes("No matching export")) - ) { - throw error; - } - failed++; - } -} -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, -);