Skip to content
Open
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
16 changes: 15 additions & 1 deletion src/jsc/bindings/c-bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -88,13 +88,27 @@ extern "C" int32_t set_process_priority(int32_t pid, int32_t priority)
}

#if !OS(WINDOWS)
#if defined(O_EXEC) && !OS(LINUX)
// Not the owner-bit test below: like open(O_EXEC), it asks the kernel whether the effective user may execute the file.
static NEVER_INLINE bool isExecutableFileByPath(const char* path)
{
struct stat st;
return stat(path, &st) == 0 && S_ISREG(st.st_mode) && faccessat(AT_FDCWD, path, X_OK, AT_EACCESS) == 0;
}
Comment on lines +93 to +97

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.

🟣 pre-existing, not blocking: macOS users with an ACL that denies readattr on an executable get two different Bun.which answers for the same file depending on how many descriptors are open. isExecutableFileByPath at src/jsc/bindings/c-bindings.cpp:96 starts with stat, which such an ACL refuses with EACCES, so the probe says no while open(O_EXEC) at c-bindings.cpp:104 says yes with a descriptor free. The PR accepts this as a trade-off, but the test at test/js/bun/util/which.test.ts:489 asserts withDescriptors equals withoutDescriptors, which this file class violates. Fix: skip the stat when it fails with EACCES and answer from faccessat(X_OK, AT_EACCESS) alone (it needs no readattr), keeping S_ISREG only when stat succeeds, so the two probes agree on this population too.
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

Trigger: a process on macOS with the descriptor table full (EMFILE at c-bindings.cpp:108) looks up a 0755 file whose ACL has deny readattr; the PR's own measurement names this as the one fixture of 25 that differs. isExecutableFileByPath at c-bindings.cpp:96 requires stat to succeed before faccessat runs, and stat fails with EACCES under that ACL, so Bun.which returns null and spawn-by-name reports ENOENT "Executable not found in $PATH" (src/runtime/api/bun/js_bun_spawn_bindings.rs:138), where Node reports EMFILE. On the base branch the answer was also null, so this is not a regression on its own, but the PR's stated contract (doc at src/sys/lib.rs:3024: it "answers also when the process has no descriptor left") and its own test invariant (which.test.ts:489 withDescriptors toEqual withoutDescriptors) are not met for this file class. Remedy: when stat fails with EACCES, fall through to faccessat alone, so the probe matches open(O_EXEC) for readattr-denied executables.

Verification: Trigger: macOS, descriptor table full, and the candidate on PATH is a 0755 file whose ACL denies readattr. A stat failure at src/jsc/bindings/c-bindings.cpp:96 short-circuits to false before faccessat is consulted. The equality assertion at test/js/bun/util/which.test.ts:489-499 never exercises the readattr case. On the base commit the same file under EMFILE already returned false.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not adopted. Without stat the probe does not know what kind of file it has.

  • faccessat(X_OK) alone also says yes for a directory that can be searched, and for a FIFO or a socket with the execute bits. open(O_EXEC) refuses all three on every Mac that was measured. So the change moves the disagreement to another kind of file. It does not remove it.
  • Nothing that avoids readattr returns the type. getattrlist(ATTR_CMN_OBJTYPE) needs the same right, and it failed with EACCES on this fixture.
  • faccessat alone was not measured under this ACL on a Mac. That part is read from XNU.

The case stays as the second bullet of Downsides. With no descriptor left, the answer for this file was null on main too. You are right that the test does not cover it: it has no fixture of this kind.

#endif // defined(O_EXEC) && !OS(LINUX)

extern "C" bool is_executable_file(const char* path)
{
#if defined(O_EXEC) && !OS(LINUX)
// musl defines O_EXEC as O_PATH, which opens any file.
int fd = open(path, O_EXEC | O_CLOEXEC | O_NONBLOCK | O_NOCTTY, 0);
if (fd < 0)
if (fd < 0) {
int error = errno;
// These two errors say that no descriptor was free. They are not an answer about the path.
if (error == EMFILE || error == ENFILE) [[unlikely]]
return isExecutableFileByPath(path);
return false;
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
}
close(fd);
return true;
#endif // defined(O_EXEC) && !OS(LINUX)
Expand Down
7 changes: 7 additions & 0 deletions src/runtime/cli/open.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,13 @@ impl Editor {
let _ = opened.close(); // close error is non-actionable
return Some(path.as_bytes());
}
// No descriptor was free for the open, so ask about the path.
bun_sys::Result::Err(err)
if matches!(err.get_errno(), bun_sys::E::EMFILE | bun_sys::E::ENFILE)
&& bun_sys::access(path, bun_sys::posix::R_OK).is_ok() =>
{
return Some(path.as_bytes());
}
bun_sys::Result::Err(_) => {}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/sys/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3021,7 +3021,7 @@ mod posix_impl {
unsafe { libc::faccessat(dir.native(), sub.as_ptr(), libc::F_OK, 0) == 0 }
}
}
/// Calls extern C `is_executable_file` (c-bindings.cpp:72-89) via FFI.
/// Whether a `$PATH` search takes `path` as the command. `is_executable_file` in c-bindings.cpp has the rule of each platform. It answers also when the process has no descriptor left.
pub fn is_executable_file_path(path: &ZStr) -> bool {
unsafe extern "C" {
// `c_char`, not `i8` — `char` is unsigned on aarch64/arm/ppc, so
Expand Down
74 changes: 74 additions & 0 deletions test/js/bun/spawn/spawn-path.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,80 @@ echo "hello from script"`,
expect(status).toBe(0);
});

// The PATH search needs no descriptor, so with none left the command is still found. The spawn then fails when it
// makes the pipes, with EMFILE, as in Node. macOS opened each PATH candidate to test it, found nothing, and
// reported ENOENT: "Executable not found in $PATH".
test.skipIf(isWindows)("spawn finds a command on PATH when the process has no descriptor left", async () => {
using dir = tempDir("spawn-path-no-descriptor", { "tool": "#!/bin/sh\necho tool ran\n" });
chmodSync(path.join(String(dir), "tool"), 0o755);

const fixture = /* js */ `
const cp = require("node:child_process");
const fs = require("node:fs");
const env = { PATH: process.env.TOOL_DIR };
const code = fn => {
try {
fn();
return "spawned";
} catch (error) {
return error.code;
}
};
const spawnEvent = name =>
new Promise(resolve => {
const child = cp.spawn(name, [], { env, stdio: "pipe" });
child.once("error", error => resolve(error.code));
child.once("close", () => resolve("spawned"));
});

// A debug build reads its internal modules from disk on first use, and that needs a descriptor.
const warmUp = [
cp.spawnSync("tool", [], { env, stdio: "pipe" }).status,
Bun.spawnSync({ cmd: ["tool"], env, stdout: "pipe", stderr: "pipe" }).exitCode,
await spawnEvent("tool"),
await spawnEvent("missing-tool"),
];

const held = [];
try {
for (;;) held.push(fs.openSync("/dev/null", "r"));
} catch {}
const noDescriptorLeft = {
"child_process.spawnSync": cp.spawnSync("tool", [], { env, stdio: "pipe" }).error?.code,
"child_process.spawn": await spawnEvent("tool"),
"Bun.spawnSync": code(() => Bun.spawnSync({ cmd: ["tool"], env, stdout: "pipe", stderr: "pipe" })),
"Bun.spawn": code(() => Bun.spawn({ cmd: ["tool"], env, stdout: "pipe", stderr: "pipe" })),
};
for (const fd of held) fs.closeSync(fd);

const afterClose = cp.spawnSync("tool", [], { env, stdio: "pipe", encoding: "utf8" }).stdout;
console.log(JSON.stringify({ warmUp, heldSome: held.length > 0, noDescriptorLeft, afterClose }));
`;

await using proc = Bun.spawn({
// `ulimit -n` also sets the hard limit, so the runtime cannot raise it again.
cmd: ["/bin/sh", "-c", 'ulimit -n 128 && exec "$@"', "sh", bunExe(), "-e", fixture],
env: { ...bunEnv, TOOL_DIR: String(dir) },
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);

expect(stderr).toBe("");
expect(JSON.parse(stdout)).toEqual({
warmUp: [0, 0, "spawned", "ENOENT"],
heldSome: true,
noDescriptorLeft: {
"child_process.spawnSync": "EMFILE",
"child_process.spawn": "EMFILE",
"Bun.spawnSync": "EMFILE",
"Bun.spawn": "EMFILE",
},
afterClose: "tool ran\n",
});
expect(exitCode).toBe(0);
});

// What a Windows environment has. bunEnv spells it `PATH`.
test.skipIf(!isWindows)("spawn uses the PATH that env spells `Path`", async () => {
using dir = tempDir("spawn-path-spelling", { "only-here.cmd": "@echo found\r\n" });
Expand Down
20 changes: 11 additions & 9 deletions test/js/bun/spawn/spawn-sync-loop-init-fail.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@
import { describe, expect, test } from "bun:test";
import { bunEnv, bunExe, isPosix } from "harness";

// Absolute argv[0] so PATH lookup (which_for_spawn) is skipped; on musl that
// lookup fails under EMFILE before the event loop is created and turns the
// failure into ENOENT instead of exercising us_create_loop.
const fixture = /* js */ `
// `/bin/sh` skips the PATH lookup (which_for_spawn), so that row tests
// us_create_loop alone. `sh` runs the lookup before the event loop is created:
// the lookup must find the command with no descriptor free, and then the
// failure comes from us_create_loop all the same.
const fixture = (command: string) => /* js */ `
import * as fs from "node:fs";
// Warm anything lazily opened on first use so the fd fill below leaves zero
// descriptors for us_create_loop itself (not for a module loader read).
Expand All @@ -27,7 +28,7 @@ const fixture = /* js */ `

let first;
try {
Bun.spawnSync({ cmd: ["/bin/sh", "-c", ":"], stdio: ["ignore", "ignore", "ignore"] });
Bun.spawnSync({ cmd: [${JSON.stringify(command)}, "-c", ":"], stdio: ["ignore", "ignore", "ignore"] });
first = { ok: false, msg: "UNEXPECTED: spawnSync succeeded" };
} catch (e) {
first = { ok: true, code: e?.code, msg: String(e?.message ?? e) };
Expand All @@ -40,16 +41,17 @@ const fixture = /* js */ `

// Descriptors are free again: the isolated loop was not cached on failure,
// so this call creates it successfully and runs the child.
const retry = Bun.spawnSync({ cmd: ["/bin/sh", "-c", ":"], stdio: ["ignore", "ignore", "ignore"] });
const retry = Bun.spawnSync({ cmd: [${JSON.stringify(command)}, "-c", ":"], stdio: ["ignore", "ignore", "ignore"] });
console.error("retry exit:", retry.exitCode);
console.error("SURVIVED");
`;

describe.skipIf(!isPosix)("Bun.spawnSync event-loop creation under EMFILE", () => {
test("throws instead of aborting the process", async () => {
test.concurrent.each(["/bin/sh", "sh"])("throws instead of aborting the process: %s", async command => {
await using proc = Bun.spawn({
cmd: ["/bin/sh", "-c", `ulimit -n 512 && exec "$1" --no-install -e "$2"`, "sh", bunExe(), fixture],
env: bunEnv,
cmd: ["/bin/sh", "-c", `ulimit -n 512 && exec "$1" --no-install -e "$2"`, "sh", bunExe(), fixture(command)],
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// A fixed PATH, so that the `sh` row finds its command whatever PATH the test runner has.
env: { ...bunEnv, PATH: "/bin:/usr/bin" },
stdout: "pipe",
stderr: "pipe",
});
Expand Down
146 changes: 144 additions & 2 deletions test/js/bun/util/which.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { $, which } from "bun";
import { dlopen, ptr } from "bun:ffi";
import { expect, jest, test } from "bun:test";
import { isArm64, isIntelMacOS, isWindows, tempDir, tmpdirSync } from "harness";
import { bunEnv, bunExe, isArm64, isIntelMacOS, isMacOS, isWindows, tempDir, tmpdirSync } from "harness";
import { mkfifo } from "mkfifo";
import { chmodSync, copyFileSync, existsSync, mkdirSync, realpathSync, rmdirSync, rmSync, symlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { tmpdir, userInfo } from "node:os";
import { basename, join } from "node:path";

$.nothrow();
Expand Down Expand Up @@ -409,3 +410,144 @@ test("Bun.which can find executables in a non-ascii directory", async () => {
process.chdir(cwd);
}
});

// Runs `fixture` with a low descriptor limit, so that it can use up every descriptor in a short loop.
// `ulimit -n` also sets the hard limit, so the runtime cannot raise it again.
async function runWithDescriptorLimit(fixture: string, env: Record<string, string>) {
await using proc = Bun.spawn({
cmd: ["/bin/sh", "-c", 'ulimit -n 128 && exec "$@"', "sh", bunExe(), "-e", fixture],
env: { ...bunEnv, ...env },
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
return { stdout, stderr, exitCode };
}

// The lookup asks a question about a path, which needs no descriptor. macOS opened each candidate to ask it, so
// with no descriptor left every command was "not found".
test.skipIf(isWindows)("which finds a command when the process has no descriptor left", async () => {
// On macOS an ACL can refuse a file that has the execute bits, and grant one that has none. The owner bit says the
// opposite for both files, so these rows fail if the lookup reads only the mode when it has no descriptor.
const aclRows = isMacOS && process.getuid!() !== 0;
using dir = tempDir("which-no-descriptor", {
"tool": "#!/bin/sh\n",
"not-executable": "#!/bin/sh\n",
"folder/keep": "",
...(aclRows ? { "acl-denied": "#!/bin/sh\n", "acl-allowed": "#!/bin/sh\n" } : {}),
});
const base = String(dir);
chmodSync(join(base, "tool"), 0o755);
chmodSync(join(base, "not-executable"), 0o644);
symlinkSync("tool", join(base, "link"));
mkfifo(join(base, "fifo"), 0o755);
const acls: [file: string, mode: number, entry: string][] = aclRows
? [
["acl-denied", 0o755, "everyone deny execute"],
["acl-allowed", 0o644, `${userInfo().username} allow execute`],
]
: [];

const fixture = /* js */ `
const fs = require("node:fs");
const dir = process.env.TOOL_DIR;
const lookups = () => ({
bare: Bun.which("tool", { PATH: dir }),
relative: Bun.which("./tool", { PATH: "", cwd: dir }),
absolute: Bun.which(dir + "/tool", { PATH: "" }),
symlink: Bun.which("link", { PATH: dir }),
notExecutable: Bun.which("not-executable", { PATH: dir }),
fifo: Bun.which("fifo", { PATH: dir }),
directory: Bun.which("folder", { PATH: dir }),
missing: Bun.which("missing", { PATH: dir }),
...(process.env.ACL_ROWS && {
aclDenied: Bun.which("acl-denied", { PATH: dir }),
aclAllowed: Bun.which("acl-allowed", { PATH: dir }),
}),
});
const withDescriptors = lookups();
const held = [];
try {
for (;;) held.push(fs.openSync("/dev/null", "r"));
} catch {}
const withoutDescriptors = lookups();
// LeakSanitizer reads /proc/self/task at exit, which needs a free descriptor.
for (const fd of held) fs.closeSync(fd);
console.log(JSON.stringify({ heldSome: held.length > 0, withDescriptors, withoutDescriptors }));
`;
try {
for (const [file, mode, entry] of acls) {
chmodSync(join(base, file), mode);
const { exitCode, stderr } = Bun.spawnSync(["/bin/chmod", "+a", entry, join(base, file)]);
expect({ file, exitCode, stderr: stderr.toString() }).toEqual({ file, exitCode: 0, stderr: "" });
}
const { stdout, stderr, exitCode } = await runWithDescriptorLimit(fixture, {
TOOL_DIR: base,
ACL_ROWS: aclRows ? "1" : "",
});

const answers = {
bare: join(base, "tool"),
relative: join(base, "tool"),
absolute: join(base, "tool"),
symlink: join(base, "link"),
notExecutable: null,
fifo: null,
directory: null,
missing: null,
...(aclRows && { aclDenied: null, aclAllowed: join(base, "acl-allowed") }),
};
expect(stderr).toBe("");
expect(JSON.parse(stdout)).toEqual({ heldSome: true, withDescriptors: answers, withoutDescriptors: answers });
expect(exitCode).toBe(0);
} finally {
for (const [file] of acls) Bun.spawnSync(["/bin/chmod", "-N", join(base, file)]);
}
});

// Each step has one more descriptor free than the step before. A step either fails for want of a descriptor or
// runs the command. On macOS the step that had descriptors for the shell but none for the lookup printed
// "bun: command not found: tool".
test.skipIf(isWindows)("the shell does not call a command missing when descriptors run out", async () => {
using dir = tempDir("which-shell-no-descriptor", { "tool": "#!/bin/sh\necho tool ran\n" });
chmodSync(join(String(dir), "tool"), 0o755);

const fixture = /* js */ `
const fs = require("node:fs");
Bun.$.env({ PATH: process.env.TOOL_DIR });
async function run() {
try {
const { exitCode, stdout, stderr } = await Bun.$\`tool\`.nothrow().quiet();
if (exitCode === 0 && stdout.toString() === "tool ran\\n") return "ran";
if (exitCode !== 0 && stderr.toString().includes("Too many open files")) return "EMFILE";
return { exitCode, stdout: stdout.toString(), stderr: stderr.toString() };
} catch (error) {
return error.code ?? String(error);
}
}
// A debug build reads its internal modules from disk on first use, and that needs a descriptor.
const warmUp = await run();
const held = [];
try {
for (;;) held.push(fs.openSync("/dev/null", "r"));
} catch {}
const steps = [];
while (held.length > 0 && steps.at(-1) !== "ran") {
steps.push(await run());
fs.closeSync(held.pop());
}
for (const fd of held) fs.closeSync(fd);
console.log(JSON.stringify({ warmUp, steps }));
`;
const { stdout, stderr, exitCode } = await runWithDescriptorLimit(fixture, { TOOL_DIR: String(dir) });

expect(stderr).toBe("");
const { warmUp, steps } = JSON.parse(stdout);
expect({
warmUp,
first: steps[0],
last: steps.at(-1),
neitherOutOfDescriptorsNorRan: steps.filter((step: unknown) => step !== "EMFILE" && step !== "ran"),
}).toEqual({ warmUp: "ran", first: "EMFILE", last: "ran", neitherOutOfDescriptorsNorRan: [] });
expect(exitCode).toBe(0);
});
Loading