diff --git a/src/resolver/lib.rs b/src/resolver/lib.rs index edc0325bef15..6ea3a24397bc 100644 --- a/src/resolver/lib.rs +++ b/src/resolver/lib.rs @@ -1168,6 +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 by this call. pub fn read_directory_with_iterator( &mut self, dir_maybe_trail_slash: &[u8], @@ -1179,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()) @@ -1218,24 +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), }, }; - // Close the handle on every exit path. Use - // scopeguard so close happens even if `readdir`/`put` early-return with `?`. - 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); - } - }); - // 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 @@ -1259,8 +1265,13 @@ pub mod fs { }); let mut entries = match self.readdir(store_fd, prev, dir, generation, handle, iterator) { - Ok(e) => e, + Ok(e) => { + handle_published.set(e.fd == handle); + e + } Err(err) => { + // 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. unsafe { (*existing).data.clear() }; @@ -1283,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 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..6e79e43164a8 --- /dev/null +++ b/test/js/bun/resolve/resolver-readdir-error-fd-leak.test.ts @@ -0,0 +1,189 @@ +// 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}; +let failed = 0; +for (let i = 0; i < N; i++) { + try { + require.resolve("./d" + i + "${MARKER}/m.ts"); + } catch { + failed++; + } +} +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("FAILED=" + failed + " 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. +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 () => { + await using proc = Bun.spawn({ + cmd: [bunExe(), "--hot", "inner.ts"], + cwd: String(dir), + env: shimEnv(), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + // 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, + }); + }, +); + +// The `bun test` scanner opens each subdirectory itself and hands the fd to +// 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 held = 0; + for (const name of readdirSync("/proc/self/fd")) { + try { + if (readlinkSync("/proc/self/fd/" + name).includes("${MARKER}")) held++; + } catch {} + } + 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-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, + }); + }, +);