From 4b86377b6f77a4f1b9da88b3af7f6bc7710a33e0 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 4 Aug 2026 06:40:54 +0000 Subject: [PATCH 01/15] resolver: close the store_fd directory handle when readdir fails read_directory_with_iterator opens a directory, then iterates it. The close guard was gated on '!store_fd || need_to_close_files()', which is the 'we never intend to cache this fd' condition. When store_fd is set (bun test / --hot / --watch / install) and the fd budget is high (always on Windows, almost always on POSIX after the rlimit bump), the guard never closed. On the success path that is correct: the fd is published into the cached DirEntry. On the error paths it leaked: DirnameStore.append_slice? and the readdir Err arm both return before the fd is published. The guard now also tracks whether the handle has been published. Until it has, a freshly-opened handle is closed on every exit path; once readdir returns Ok (which writes e.fd = handle when store_fd), the guard is disarmed and the existing success-path behaviour is unchanged. --- src/resolver/lib.rs | 20 ++- .../resolver-readdir-error-fd-leak.test.ts | 121 ++++++++++++++++++ 2 files changed, 135 insertions(+), 6 deletions(-) create mode 100644 test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts diff --git a/src/resolver/lib.rs b/src/resolver/lib.rs index edc0325bef15..3f0b7d5f2c04 100644 --- a/src/resolver/lib.rs +++ b/src/resolver/lib.rs @@ -1227,12 +1227,15 @@ pub mod fs { }, }; - // Close the handle on every exit path. Use - // scopeguard so close happens even if `readdir`/`put` early-return with `?`. + // A freshly-opened handle is ours to close on every exit path until it + // is published into the returned DirEntry; `handle_published` flips + // once that happens so the `store_fd` success path keeps the fd while + // the `?`/error returns below still close it. let should_close_handle = !had_handle && (!store_fd || self.need_to_close_files()); - let _close_guard = scopeguard::guard(handle, move |h| { - if should_close_handle { - let _ = bun_sys::close(h); + let handle_published = core::cell::Cell::new(false); + let _close_guard = scopeguard::guard((), |()| { + if !had_handle && (should_close_handle || !handle_published.get()) { + let _ = bun_sys::close(handle); } }); @@ -1259,7 +1262,12 @@ pub mod fs { }); let mut entries = match self.readdir(store_fd, prev, dir, generation, handle, iterator) { - Ok(e) => e, + Ok(e) => { + // `e.fd == handle` when `store_fd`; every remaining path moves + // `e` into long-lived storage before the next `?`. + handle_published.set(true); + e + } Err(err) => { if let Some(existing) = in_place { // SAFETY: see above. diff --git a/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts b/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts new file mode 100644 index 000000000000..a472c87dd041 --- /dev/null +++ b/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts @@ -0,0 +1,121 @@ +// The resolver opens a directory and then iterates it via getdents64. When the +// open succeeds but iteration fails, and the resolver was asked to cache the +// fd (store_fd, set by bun test / --hot / --watch / install), the fd must be +// closed on that error path. The guard that closes it used to be gated on the +// "don't store" condition, so a store_fd run leaked one directory fd per +// failed read. +// +// getdents64 is reached through libc's variadic syscall(), so an LD_PRELOAD +// shim can make it fail with EIO for fds whose /proc/self/fd target contains a +// marker string. The inner process runs under --hot (store_fd=true), resolves +// one path per marker directory, then counts open fds that still point at a +// marker directory. +import { afterAll, beforeAll, expect, test } from "bun:test"; +import { bunEnv, bunExe, isLinux, isMusl, tempDir } from "harness"; +import { join } from "node:path"; + +const cc = Bun.which("cc") || Bun.which("gcc") || Bun.which("clang"); +const DIR_COUNT = 16; +const MARKER = "__FAIL_GETDENTS__"; + +const SHIM_C = /* c */ ` +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include + +static long (*real_syscall)(long, long, long, long, long, long, long); + +long syscall(long number, ...) { + va_list ap; + long a, b, c, d, e, f; + va_start(ap, number); + a = va_arg(ap, long); b = va_arg(ap, long); c = va_arg(ap, long); + d = va_arg(ap, long); e = va_arg(ap, long); f = va_arg(ap, long); + va_end(ap); + if (!real_syscall) + real_syscall = (long (*)(long, long, long, long, long, long, long))dlsym(RTLD_NEXT, "syscall"); + if (number == SYS_getdents64) { + char link[64], target[4096]; + snprintf(link, sizeof link, "/proc/self/fd/%ld", a); + ssize_t n = readlink(link, target, sizeof(target) - 1); + if (n > 0) { + target[n] = 0; + if (strstr(target, "${MARKER}")) { + errno = EIO; + return -1; + } + } + } + return real_syscall(number, a, b, c, d, e, f); +} +`; + +const INNER = /* ts */ ` +import { readdirSync, readlinkSync } from "node:fs"; +const N = ${DIR_COUNT}; +for (let i = 0; i < N; i++) { + try { + require.resolve("./d" + i + "${MARKER}/m.ts"); + } catch {} +} +let leaked = 0; +for (const name of readdirSync("/proc/self/fd")) { + try { + const target = readlinkSync("/proc/self/fd/" + name); + if (target.includes("${MARKER}")) leaked++; + } catch {} +} +console.log("LEAKED=" + leaked); +process.exit(0); +`; + +let dir: ReturnType; +let shimPath: string; + +beforeAll(async () => { + if (!isLinux || isMusl || !cc) return; + const files: Record = { + "shim.c": SHIM_C, + "inner.ts": INNER, + "package.json": "{}", + }; + for (let i = 0; i < DIR_COUNT; i++) files[`d${i}${MARKER}/m.ts`] = `export {};\n`; + dir = tempDir("resolver-readdir-fail-leak", files); + shimPath = join(String(dir), "shim.so"); + await using ccProc = Bun.spawn({ + cmd: [cc, "-shared", "-fPIC", "-o", shimPath, join(String(dir), "shim.c"), "-ldl"], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [ccOut, ccErr, ccExit] = await Promise.all([ccProc.stdout.text(), ccProc.stderr.text(), ccProc.exited]); + if (ccExit !== 0) throw new Error(`shim compile failed: ${ccErr || ccOut}`); +}); + +afterAll(() => { + dir?.[Symbol.dispose](); +}); + +// LD_PRELOAD interposition requires a dynamic libc; the musl build links libc +// statically, so the shim cannot intercept syscall() there. +test.skipIf(!isLinux || isMusl || !cc)( + "resolver closes the directory fd when readdir fails after a successful open (store_fd)", + async () => { + const existing = bunEnv.LD_PRELOAD; + await using proc = Bun.spawn({ + cmd: [bunExe(), "--hot", "inner.ts"], + cwd: String(dir), + env: { ...bunEnv, LD_PRELOAD: existing ? `${shimPath}:${existing}` : shimPath }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + const m = stdout.match(/LEAKED=(\d+)/); + expect({ stdout: m?.[0], stderr, exitCode }).toEqual({ stdout: "LEAKED=0", stderr: "", exitCode: 0 }); + }, +); From bcb1e1d511a9253a1ef432b6c11726ccb94b589f Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 4 Aug 2026 07:28:42 +0000 Subject: [PATCH 02/15] drop redundant had_handle factor; have the test prove the shim fired --- src/resolver/lib.rs | 4 ++-- .../resolver-readdir-error-fd-leak.test.ts | 16 ++++++++++++---- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/resolver/lib.rs b/src/resolver/lib.rs index 3f0b7d5f2c04..037853775c40 100644 --- a/src/resolver/lib.rs +++ b/src/resolver/lib.rs @@ -1231,10 +1231,10 @@ pub mod fs { // is published into the returned DirEntry; `handle_published` flips // once that happens so the `store_fd` success path keeps the fd while // the `?`/error returns below still close it. - let should_close_handle = !had_handle && (!store_fd || self.need_to_close_files()); + let close_even_if_published = !store_fd || self.need_to_close_files(); let handle_published = core::cell::Cell::new(false); let _close_guard = scopeguard::guard((), |()| { - if !had_handle && (should_close_handle || !handle_published.get()) { + if !had_handle && (close_even_if_published || !handle_published.get()) { let _ = bun_sys::close(handle); } }); diff --git a/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts b/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts index a472c87dd041..b6a3057e2bb0 100644 --- a/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts +++ b/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts @@ -58,10 +58,13 @@ long syscall(long number, ...) { const INNER = /* ts */ ` import { readdirSync, readlinkSync } from "node:fs"; const N = ${DIR_COUNT}; +let failed = 0; for (let i = 0; i < N; i++) { try { require.resolve("./d" + i + "${MARKER}/m.ts"); - } catch {} + } catch { + failed++; + } } let leaked = 0; for (const name of readdirSync("/proc/self/fd")) { @@ -70,7 +73,7 @@ for (const name of readdirSync("/proc/self/fd")) { if (target.includes("${MARKER}")) leaked++; } catch {} } -console.log("LEAKED=" + leaked); +console.log("FAILED=" + failed + " LEAKED=" + leaked); process.exit(0); `; @@ -115,7 +118,12 @@ test.skipIf(!isLinux || isMusl || !cc)( stderr: "pipe", }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - const m = stdout.match(/LEAKED=(\d+)/); - expect({ stdout: m?.[0], stderr, exitCode }).toEqual({ stdout: "LEAKED=0", stderr: "", exitCode: 0 }); + // FAILED=DIR_COUNT proves the shim actually fired; if bun stops routing + // getdents64 through libc's syscall() the resolves succeed and this trips. + expect({ stdout: stdout.trim(), stderr, exitCode }).toEqual({ + stdout: `FAILED=${DIR_COUNT} LEAKED=0`, + stderr: "", + exitCode: 0, + }); }, ); From e1db020f20658667d05059d6d4b815c9eed4d715 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 4 Aug 2026 07:30:35 +0000 Subject: [PATCH 03/15] trim guard comments --- src/resolver/lib.rs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/resolver/lib.rs b/src/resolver/lib.rs index 037853775c40..e9e657f5d279 100644 --- a/src/resolver/lib.rs +++ b/src/resolver/lib.rs @@ -1227,10 +1227,8 @@ pub mod fs { }, }; - // A freshly-opened handle is ours to close on every exit path until it - // is published into the returned DirEntry; `handle_published` flips - // once that happens so the `store_fd` success path keeps the fd while - // the `?`/error returns below still close it. + // Close a freshly-opened handle on every exit path until it is + // published into the returned DirEntry (the `store_fd` success path). let close_even_if_published = !store_fd || self.need_to_close_files(); let handle_published = core::cell::Cell::new(false); let _close_guard = scopeguard::guard((), |()| { @@ -1263,8 +1261,6 @@ pub mod fs { let mut entries = match self.readdir(store_fd, prev, dir, generation, handle, iterator) { Ok(e) => { - // `e.fd == handle` when `store_fd`; every remaining path moves - // `e` into long-lived storage before the next `?`. handle_published.set(true); e } From 924be772d9f50f13dc43b512f4b8d6bf96add3a3 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 4 Aug 2026 07:31:46 +0000 Subject: [PATCH 04/15] drop guard comment; variable names carry it --- src/resolver/lib.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/resolver/lib.rs b/src/resolver/lib.rs index e9e657f5d279..6b0f10417df0 100644 --- a/src/resolver/lib.rs +++ b/src/resolver/lib.rs @@ -1227,8 +1227,6 @@ pub mod fs { }, }; - // Close a freshly-opened handle on every exit path until it is - // published into the returned DirEntry (the `store_fd` success path). let close_even_if_published = !store_fd || self.need_to_close_files(); let handle_published = core::cell::Cell::new(false); let _close_guard = scopeguard::guard((), |()| { From af70e3a84fe0d7dcb5490fcb5e6b8de1e5da9201 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 4 Aug 2026 09:06:00 +0000 Subject: [PATCH 05/15] ci: retrigger From e3694aba27c12381efe03b44b3abd2a76eab17cb Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 4 Aug 2026 09:29:02 +0000 Subject: [PATCH 06/15] close caller-supplied handle on the not-yet-published branch too The only Some(handle) caller (the bun test scanner) disarms its Dir guard via into_raw() before the call, so read_directory_with_iterator owns the fd on that path as well. Closing whenever the fd was never published covers both arms; the close-even-after-publish (!store_fd / fd-budget) behaviour stays gated on !had_handle so a caller-supplied fd that was successfully cached is never double-closed. Add a second test driving bun test's scanner through the same shim. --- src/resolver/lib.rs | 5 +- .../resolver-readdir-error-fd-leak.test.ts | 56 +++++++++++++++++-- 2 files changed, 56 insertions(+), 5 deletions(-) diff --git a/src/resolver/lib.rs b/src/resolver/lib.rs index 6b0f10417df0..3729bb2653cf 100644 --- a/src/resolver/lib.rs +++ b/src/resolver/lib.rs @@ -1168,6 +1168,9 @@ pub mod fs { // https://twitter.com/jarredsumner/status/1655464485245845506 /// Caller borrows the returned `EntriesOption`. When `FeatureFlags::ENABLE_ENTRY_CACHE` /// is `false`, it is not safe to store this pointer past the current function call. + /// + /// `maybe_handle` is owned: on success it is published into the cached + /// `DirEntry.fd` when `store_fd`; on any error before that it is closed. pub fn read_directory_with_iterator( &mut self, dir_maybe_trail_slash: &[u8], @@ -1230,7 +1233,7 @@ pub mod fs { let close_even_if_published = !store_fd || self.need_to_close_files(); let handle_published = core::cell::Cell::new(false); let _close_guard = scopeguard::guard((), |()| { - if !had_handle && (close_even_if_published || !handle_published.get()) { + if !handle_published.get() || (!had_handle && close_even_if_published) { let _ = bun_sys::close(handle); } }); diff --git a/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts b/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts index b6a3057e2bb0..629a2e4deec8 100644 --- a/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts +++ b/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts @@ -106,14 +106,20 @@ afterAll(() => { // LD_PRELOAD interposition requires a dynamic libc; the musl build links libc // statically, so the shim cannot intercept syscall() there. -test.skipIf(!isLinux || isMusl || !cc)( - "resolver closes the directory fd when readdir fails after a successful open (store_fd)", +const skip = !isLinux || isMusl || !cc; + +function shimEnv() { + const existing = bunEnv.LD_PRELOAD; + return { ...bunEnv, LD_PRELOAD: existing ? `${shimPath}:${existing}` : shimPath }; +} + +test.skipIf(skip)( + "resolver closes the directory fd when readdir fails after a successful open (store_fd, fresh handle)", async () => { - const existing = bunEnv.LD_PRELOAD; await using proc = Bun.spawn({ cmd: [bunExe(), "--hot", "inner.ts"], cwd: String(dir), - env: { ...bunEnv, LD_PRELOAD: existing ? `${shimPath}:${existing}` : shimPath }, + env: shimEnv(), stdout: "pipe", stderr: "pipe", }); @@ -127,3 +133,45 @@ test.skipIf(!isLinux || isMusl || !cc)( }); }, ); + +// The `bun test` scanner opens each subdirectory itself and hands the fd to +// read_directory_with_iterator(Some(fd)), which is the had_handle=true arm of +// the same guard. The scanner's Dir guard is disarmed via into_raw(), so the +// function owns the fd on that path too. +test.skipIf(skip)( + "resolver closes a caller-supplied directory fd when readdir fails (bun test scanner)", + async () => { + const files: Record = { + "package.json": "{}", + "count.test.ts": /* ts */ ` + import { test } from "bun:test"; + import { readdirSync, readlinkSync } from "node:fs"; + test("count", () => { + let leaked = 0; + for (const name of readdirSync("/proc/self/fd")) { + try { + if (readlinkSync("/proc/self/fd/" + name).includes("${MARKER}")) leaked++; + } catch {} + } + console.log("LEAKED=" + leaked); + }); + `, + }; + for (let i = 0; i < DIR_COUNT; i++) files[`d${i}${MARKER}/noop.txt`] = ""; + using scanDir = tempDir("resolver-readdir-scanner-leak", files); + await using proc = Bun.spawn({ + cmd: [bunExe(), "test", "."], + cwd: String(scanDir), + env: shimEnv(), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + const m = stdout.match(/LEAKED=(\d+)/); + expect({ leaked: m?.[0], stderr: stderr.includes("1 pass"), exitCode }).toEqual({ + leaked: "LEAKED=0", + stderr: true, + exitCode: 0, + }); + }, +); From 688eb737919869252359d1e7160f919937c2f258 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 4 Aug 2026 09:30:43 +0000 Subject: [PATCH 07/15] one-line doc for maybe_handle ownership --- src/resolver/lib.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/resolver/lib.rs b/src/resolver/lib.rs index 3729bb2653cf..a1fe74b45db1 100644 --- a/src/resolver/lib.rs +++ b/src/resolver/lib.rs @@ -1168,9 +1168,7 @@ pub mod fs { // https://twitter.com/jarredsumner/status/1655464485245845506 /// Caller borrows the returned `EntriesOption`. When `FeatureFlags::ENABLE_ENTRY_CACHE` /// is `false`, it is not safe to store this pointer past the current function call. - /// - /// `maybe_handle` is owned: on success it is published into the cached - /// `DirEntry.fd` when `store_fd`; on any error before that it is closed. + /// `maybe_handle` is owned: published into `DirEntry.fd` on success when `store_fd`, closed otherwise. pub fn read_directory_with_iterator( &mut self, dir_maybe_trail_slash: &[u8], From faddcaa7c6e13f44bdf050cbd4019a70257801ce Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Tue, 4 Aug 2026 09:33:15 +0000 Subject: [PATCH 08/15] [autofix.ci] apply automated fixes --- .../resolver-readdir-error-fd-leak.test.ts | 47 +++++++++---------- 1 file changed, 22 insertions(+), 25 deletions(-) diff --git a/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts b/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts index 629a2e4deec8..847cca6ef705 100644 --- a/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts +++ b/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts @@ -138,12 +138,10 @@ test.skipIf(skip)( // read_directory_with_iterator(Some(fd)), which is the had_handle=true arm of // the same guard. The scanner's Dir guard is disarmed via into_raw(), so the // function owns the fd on that path too. -test.skipIf(skip)( - "resolver closes a caller-supplied directory fd when readdir fails (bun test scanner)", - async () => { - const files: Record = { - "package.json": "{}", - "count.test.ts": /* ts */ ` +test.skipIf(skip)("resolver closes a caller-supplied directory fd when readdir fails (bun test scanner)", async () => { + const files: Record = { + "package.json": "{}", + "count.test.ts": /* ts */ ` import { test } from "bun:test"; import { readdirSync, readlinkSync } from "node:fs"; test("count", () => { @@ -156,22 +154,21 @@ test.skipIf(skip)( console.log("LEAKED=" + leaked); }); `, - }; - for (let i = 0; i < DIR_COUNT; i++) files[`d${i}${MARKER}/noop.txt`] = ""; - using scanDir = tempDir("resolver-readdir-scanner-leak", files); - await using proc = Bun.spawn({ - cmd: [bunExe(), "test", "."], - cwd: String(scanDir), - env: shimEnv(), - stdout: "pipe", - stderr: "pipe", - }); - const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - const m = stdout.match(/LEAKED=(\d+)/); - expect({ leaked: m?.[0], stderr: stderr.includes("1 pass"), exitCode }).toEqual({ - leaked: "LEAKED=0", - stderr: true, - exitCode: 0, - }); - }, -); + }; + for (let i = 0; i < DIR_COUNT; i++) files[`d${i}${MARKER}/noop.txt`] = ""; + using scanDir = tempDir("resolver-readdir-scanner-leak", files); + await using proc = Bun.spawn({ + cmd: [bunExe(), "test", "."], + cwd: String(scanDir), + env: shimEnv(), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + const m = stdout.match(/LEAKED=(\d+)/); + expect({ leaked: m?.[0], stderr: stderr.includes("1 pass"), exitCode }).toEqual({ + leaked: "LEAKED=0", + stderr: true, + exitCode: 0, + }); +}); From df2f6a68ec7759b55b23813dfd88d7de327e4158 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 4 Aug 2026 09:35:37 +0000 Subject: [PATCH 09/15] scanner test: prove the shim fired via unreachable sentinel test files --- .../bun/resolve/resolver-readdir-error-fd-leak.test.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts b/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts index 847cca6ef705..a60b0982f6f8 100644 --- a/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts +++ b/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts @@ -155,7 +155,8 @@ test.skipIf(skip)("resolver closes a caller-supplied directory fd when readdir f }); `, }; - for (let i = 0; i < DIR_COUNT; i++) files[`d${i}${MARKER}/noop.txt`] = ""; + for (let i = 0; i < DIR_COUNT; i++) + files[`d${i}${MARKER}/unreachable.test.ts`] = `import { test } from "bun:test"; test("unreachable-marker", () => {});`; using scanDir = tempDir("resolver-readdir-scanner-leak", files); await using proc = Bun.spawn({ cmd: [bunExe(), "test", "."], @@ -166,9 +167,12 @@ test.skipIf(skip)("resolver closes a caller-supplied directory fd when readdir f }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); const m = stdout.match(/LEAKED=(\d+)/); - expect({ leaked: m?.[0], stderr: stderr.includes("1 pass"), exitCode }).toEqual({ + // unreachable-marker stays undiscovered iff the shim made the marker dirs + // unreadable; if bun stops routing getdents64 through libc syscall() this trips. + expect({ leaked: m?.[0], shimFired: !stderr.includes("unreachable-marker"), onePass: stderr.includes("1 pass"), exitCode }).toEqual({ leaked: "LEAKED=0", - stderr: true, + shimFired: true, + onePass: true, exitCode: 0, }); }); From e7c58f8dae4ce59f6ce72a9a950dda4f20ed9ddb Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Tue, 4 Aug 2026 09:37:59 +0000 Subject: [PATCH 10/15] [autofix.ci] apply automated fixes --- .../bun/resolve/resolver-readdir-error-fd-leak.test.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts b/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts index a60b0982f6f8..d4377b5da9e8 100644 --- a/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts +++ b/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts @@ -156,7 +156,8 @@ test.skipIf(skip)("resolver closes a caller-supplied directory fd when readdir f `, }; for (let i = 0; i < DIR_COUNT; i++) - files[`d${i}${MARKER}/unreachable.test.ts`] = `import { test } from "bun:test"; test("unreachable-marker", () => {});`; + files[`d${i}${MARKER}/unreachable.test.ts`] = + `import { test } from "bun:test"; test("unreachable-marker", () => {});`; using scanDir = tempDir("resolver-readdir-scanner-leak", files); await using proc = Bun.spawn({ cmd: [bunExe(), "test", "."], @@ -169,7 +170,12 @@ test.skipIf(skip)("resolver closes a caller-supplied directory fd when readdir f const m = stdout.match(/LEAKED=(\d+)/); // unreachable-marker stays undiscovered iff the shim made the marker dirs // unreadable; if bun stops routing getdents64 through libc syscall() this trips. - expect({ leaked: m?.[0], shimFired: !stderr.includes("unreachable-marker"), onePass: stderr.includes("1 pass"), exitCode }).toEqual({ + expect({ + leaked: m?.[0], + shimFired: !stderr.includes("unreachable-marker"), + onePass: stderr.includes("1 pass"), + exitCode, + }).toEqual({ leaked: "LEAKED=0", shimFired: true, onePass: true, From 3889f0758cd74363c3f1904d5b1445df55496901 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 4 Aug 2026 09:51:50 +0000 Subject: [PATCH 11/15] arm the close guard before the cache-hit / ? returns The guard was armed after the cache lookup, so a caller-supplied handle leaked on the three earlier exits (get_or_put? OOM, the cached-entry return, and the cached-NotFound return). The guard now holds the Option from function entry and is armed before any exit path; open_dir writes into the same cell on a cache miss. The doc comment's ownership contract is now accurate for every return. Also surface the actual LEAKED count / pass count in the scanner test's assertion object so a failure diff is informative. --- src/resolver/lib.rs | 28 +++++++++++-------- .../resolver-readdir-error-fd-leak.test.ts | 11 ++++---- 2 files changed, 22 insertions(+), 17 deletions(-) diff --git a/src/resolver/lib.rs b/src/resolver/lib.rs index a1fe74b45db1..9562920e7f0e 100644 --- a/src/resolver/lib.rs +++ b/src/resolver/lib.rs @@ -1180,6 +1180,18 @@ pub mod fs { let dir = strings::paths::without_trailing_slash_windows_path(dir_maybe_trail_slash); crate::Resolver::assert_valid_cache_key(dir); + + let had_handle = maybe_handle.is_some(); + let close_even_if_published = !store_fd || self.need_to_close_files(); + let owned_handle = core::cell::Cell::new(maybe_handle); + let handle_published = core::cell::Cell::new(false); + let _close_guard = scopeguard::guard((), |()| { + let Some(h) = owned_handle.get() else { return }; + if !handle_published.get() || (!had_handle && close_even_if_published) { + let _ = bun_sys::close(h); + } + }); + let mut cache_result: Option = None; let _unlock_guard = if bun_core::FeatureFlags::ENABLE_ENTRY_CACHE { Some(self.entries_mutex.lock_guard()) @@ -1219,23 +1231,17 @@ pub mod fs { } } - let had_handle = maybe_handle.is_some(); - let handle: Fd = match maybe_handle { + let handle: Fd = match owned_handle.get() { Some(h) => h, None => match self.open_dir(dir) { - Ok(h) => h, + Ok(h) => { + owned_handle.set(Some(h)); + h + } Err(err) => return self.read_directory_error(dir, err), }, }; - let close_even_if_published = !store_fd || self.need_to_close_files(); - let handle_published = core::cell::Cell::new(false); - let _close_guard = scopeguard::guard((), |()| { - if !handle_published.get() || (!had_handle && close_even_if_published) { - let _ = bun_sys::close(handle); - } - }); - // if we get this far, it's a real directory, so we can just store the dir name. // An in-place refresh always keeps the slot's existing interned name: callers // spell the same directory with and without a trailing slash, and rewriting diff --git a/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts b/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts index d4377b5da9e8..4a74b33a32ee 100644 --- a/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts +++ b/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts @@ -167,18 +167,17 @@ test.skipIf(skip)("resolver closes a caller-supplied directory fd when readdir f stderr: "pipe", }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - const m = stdout.match(/LEAKED=(\d+)/); // unreachable-marker stays undiscovered iff the shim made the marker dirs // unreadable; if bun stops routing getdents64 through libc syscall() this trips. expect({ - leaked: m?.[0], - shimFired: !stderr.includes("unreachable-marker"), - onePass: stderr.includes("1 pass"), + leaked: stdout.match(/LEAKED=\d+/)?.[0] ?? stdout, + passCount: stderr.match(/(\d+) pass/)?.[1] ?? stderr, + sawUnreachable: stderr.includes("unreachable-marker"), exitCode, }).toEqual({ leaked: "LEAKED=0", - shimFired: true, - onePass: true, + passCount: "1", + sawUnreachable: false, exitCode: 0, }); }); From c67bf0f7f07cb6e3f05c6f1f54c0fafd6bddd67b Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 4 Aug 2026 10:04:31 +0000 Subject: [PATCH 12/15] set handle_published only when readdir actually stored the handle readdir writes e.fd = handle only when store_fd; checking e.fd == handle makes the 'published' flag accurate for a hypothetical caller that passes Some(fd) with store_fd=false (none exist today, but the doc comment now claims ownership on every path). --- src/resolver/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/resolver/lib.rs b/src/resolver/lib.rs index 9562920e7f0e..aebc4a29a982 100644 --- a/src/resolver/lib.rs +++ b/src/resolver/lib.rs @@ -1266,7 +1266,7 @@ pub mod fs { let mut entries = match self.readdir(store_fd, prev, dir, generation, handle, iterator) { Ok(e) => { - handle_published.set(true); + handle_published.set(e.fd == handle); e } Err(err) => { From 1bc11bd1759ee5b3e21c4def9df97e2bef0b6c63 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 4 Aug 2026 10:14:44 +0000 Subject: [PATCH 13/15] do not close on readdir Err when a non-void iterator may have dispatched the fd readdir sets dir.fd = handle before iterating and add_entry_with_store calls iterator.next(entry, self.fd) for each entry produced, so when a later getdents64 batch fails the iterator (Scanner) has already queued ScanEntry { relative_dir: handle }. Closing the fd here would make the scan loop open_dir_at against a freed (or kernel-reused) fd number. When I::IS_VOID (every read_directory caller: load_as_file, install, lockfile) the iterator is never called and closing on Err is safe; that is the leak this PR fixes. When not (only the bun test scanner), the Err arm now treats the fd as published so the pre-PR 'hold and leak' behaviour is kept on that one path. Repurpose the scanner test to guard the hold: it now asserts HELD=16, so a future change that closes in this path (reintroducing the use-after-close) flips it. --- src/resolver/lib.rs | 6 +- .../resolver-readdir-error-fd-leak.test.ts | 80 ++++++++++--------- 2 files changed, 48 insertions(+), 38 deletions(-) diff --git a/src/resolver/lib.rs b/src/resolver/lib.rs index aebc4a29a982..4ac4726df906 100644 --- a/src/resolver/lib.rs +++ b/src/resolver/lib.rs @@ -1168,7 +1168,7 @@ pub mod fs { // https://twitter.com/jarredsumner/status/1655464485245845506 /// Caller borrows the returned `EntriesOption`. When `FeatureFlags::ENABLE_ENTRY_CACHE` /// is `false`, it is not safe to store this pointer past the current function call. - /// `maybe_handle` is owned: published into `DirEntry.fd` on success when `store_fd`, closed otherwise. + /// `maybe_handle` is owned by this call. pub fn read_directory_with_iterator( &mut self, dir_maybe_trail_slash: &[u8], @@ -1270,6 +1270,10 @@ pub mod fs { e } Err(err) => { + // A non-void iterator has already observed the fd for every + // entry yielded before the failure; closing now would use a + // freed fd in the caller's queued work. Leak instead. + handle_published.set(store_fd && !I::IS_VOID); if let Some(existing) = in_place { // SAFETY: see above. unsafe { (*existing).data.clear() }; diff --git a/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts b/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts index 4a74b33a32ee..6e79e43164a8 100644 --- a/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts +++ b/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts @@ -135,49 +135,55 @@ test.skipIf(skip)( ); // The `bun test` scanner opens each subdirectory itself and hands the fd to -// read_directory_with_iterator(Some(fd)), which is the had_handle=true arm of -// the same guard. The scanner's Dir guard is disarmed via into_raw(), so the -// function owns the fd on that path too. -test.skipIf(skip)("resolver closes a caller-supplied directory fd when readdir fails (bun test scanner)", async () => { - const files: Record = { - "package.json": "{}", - "count.test.ts": /* ts */ ` +// read_directory_with_iterator(Some(fd), iterator=ScannerDirIter). The iterator +// queues ScanEntry { relative_dir: fd } for every entry it sees during +// iteration, so when a later getdents64 batch fails the queued entries still +// hold the fd and closing it here would be a use-after-close in the scan loop. +// The guard therefore treats the fd as published once a non-void iterator is in +// play, so the scanner's readdir-error path still holds one fd per directory. +test.skipIf(skip)( + "bun test scanner keeps the directory fd when readdir fails (non-void iterator dispatched it)", + async () => { + const files: Record = { + "package.json": "{}", + "count.test.ts": /* ts */ ` import { test } from "bun:test"; import { readdirSync, readlinkSync } from "node:fs"; test("count", () => { - let leaked = 0; + let held = 0; for (const name of readdirSync("/proc/self/fd")) { try { - if (readlinkSync("/proc/self/fd/" + name).includes("${MARKER}")) leaked++; + if (readlinkSync("/proc/self/fd/" + name).includes("${MARKER}")) held++; } catch {} } - console.log("LEAKED=" + leaked); + console.log("HELD=" + held); }); `, - }; - for (let i = 0; i < DIR_COUNT; i++) - files[`d${i}${MARKER}/unreachable.test.ts`] = - `import { test } from "bun:test"; test("unreachable-marker", () => {});`; - using scanDir = tempDir("resolver-readdir-scanner-leak", files); - await using proc = Bun.spawn({ - cmd: [bunExe(), "test", "."], - cwd: String(scanDir), - env: shimEnv(), - stdout: "pipe", - stderr: "pipe", - }); - const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - // unreachable-marker stays undiscovered iff the shim made the marker dirs - // unreadable; if bun stops routing getdents64 through libc syscall() this trips. - expect({ - leaked: stdout.match(/LEAKED=\d+/)?.[0] ?? stdout, - passCount: stderr.match(/(\d+) pass/)?.[1] ?? stderr, - sawUnreachable: stderr.includes("unreachable-marker"), - exitCode, - }).toEqual({ - leaked: "LEAKED=0", - passCount: "1", - sawUnreachable: false, - exitCode: 0, - }); -}); + }; + for (let i = 0; i < DIR_COUNT; i++) + files[`d${i}${MARKER}/unreachable.test.ts`] = + `import { test } from "bun:test"; test("unreachable-marker", () => {});`; + using scanDir = tempDir("resolver-readdir-scanner-hold", files); + await using proc = Bun.spawn({ + cmd: [bunExe(), "test", "."], + cwd: String(scanDir), + env: shimEnv(), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + // unreachable-marker stays undiscovered iff the shim made the marker dirs + // unreadable; if bun stops routing getdents64 through libc syscall() this trips. + expect({ + held: stdout.match(/HELD=\d+/)?.[0] ?? stdout, + passCount: stderr.match(/(\d+) pass/)?.[1] ?? stderr, + sawUnreachable: stderr.includes("unreachable-marker"), + exitCode, + }).toEqual({ + held: `HELD=${DIR_COUNT}`, + passCount: "1", + sawUnreachable: false, + exitCode: 0, + }); + }, +); From 3cb7ef2c98debf2182b91e8b89858ab09bb664b5 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 4 Aug 2026 10:16:29 +0000 Subject: [PATCH 14/15] one-line comment for the non-void iterator Err arm --- src/resolver/lib.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/resolver/lib.rs b/src/resolver/lib.rs index 4ac4726df906..f1b7b25bfeca 100644 --- a/src/resolver/lib.rs +++ b/src/resolver/lib.rs @@ -1270,9 +1270,7 @@ pub mod fs { e } Err(err) => { - // A non-void iterator has already observed the fd for every - // entry yielded before the failure; closing now would use a - // freed fd in the caller's queued work. Leak instead. + // Non-void iterators already hold the fd; closing would use-after-free it. handle_published.set(store_fd && !I::IS_VOID); if let Some(existing) = in_place { // SAFETY: see above. From 4502d27eb5c37b0a82ddfe195b05675f46aced15 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 4 Aug 2026 10:32:11 +0000 Subject: [PATCH 15/15] keep handle_published consistent with the defensive entries.fd fallback --- src/resolver/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/resolver/lib.rs b/src/resolver/lib.rs index f1b7b25bfeca..6ea3a24397bc 100644 --- a/src/resolver/lib.rs +++ b/src/resolver/lib.rs @@ -1294,6 +1294,7 @@ pub mod fs { } if store_fd && !entries.fd.is_valid() { entries.fd = handle; + handle_published.set(true); } // SAFETY: `entries_ptr` is either a live BSSMap slot (`in_place`) or a fresh