Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Unreleased

- Mark inherited POSIX descriptors close-on-exec at startup like Node, preventing native-spawned children from keeping stdio pipes open after Bun exits.
- Integrate upstream [#40005](https://github.com/oven-sh/bun/pull/40005) at `900eae3`: `node:sqlite` `DatabaseSync.close()` and `Symbol.dispose()` finalize outstanding statements, so WAL/shared-memory files, file locks, and descriptors are released immediately. Virtual-table modules such as FTS5 and sqlite-vec keep ownership of their private statements.
- Publish tagged `main` commits as GitHub releases: release builds for darwin-arm64, darwin-x64, linux-x64 and linux-arm64, smoke-tested on their own platforms, with SHA-256 checksums, a pinnable `manifest.json` naming the fork commit and WebKit revision, and build provenance attestations. See `.github/OPENCLAW_RELEASE.md`.
- Preserve file-URL entry identity and literal `?` paths in `Bun.ModuleGraph`, and avoid retaining GC-backed string views across macro transpilation.
Expand Down
51 changes: 28 additions & 23 deletions src/bun_core/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4650,42 +4650,43 @@ fn spawn_sync_inherit_impl(
// for the non-PTY inherit case. PTY spawns go through spawn_sys.
#[cfg(target_os = "macos")]
let pid: libc::pid_t = {
// StdinBehavior::Ignore → file action opening /dev/null onto fd 0;
// stdout/stderr stay inherited.
unsafe extern "C" {
fn posix_spawn_file_actions_addinherit_np(
actions: *mut libc::posix_spawn_file_actions_t,
fd: libc::c_int,
) -> libc::c_int;
}
let mut actions: libc::posix_spawn_file_actions_t = core::ptr::null_mut();
let actions_ptr: *const libc::posix_spawn_file_actions_t =
if stdin == StdinBehavior::Ignore {
let rc = libc::posix_spawn_file_actions_init(&raw mut actions);
if rc != 0 {
return Err(crate::CrateError::Unexpected);
}
let rc = libc::posix_spawn_file_actions_addopen(
if libc::posix_spawn_file_actions_init(&raw mut actions) != 0 {
return Err(crate::CrateError::Unexpected);
}
for fd in 0..3 {
let rc = if fd == 0 && stdin == StdinBehavior::Ignore {
libc::posix_spawn_file_actions_addopen(
&raw mut actions,
0,
c"/dev/null".as_ptr(),
libc::O_RDONLY,
0,
);
if rc != 0 {
libc::posix_spawn_file_actions_destroy(&raw mut actions);
return Err(crate::CrateError::Unexpected);
}
&raw const actions
)
} else {
core::ptr::null()
posix_spawn_file_actions_addinherit_np(&raw mut actions, fd)
};
if rc != 0 {
libc::posix_spawn_file_actions_destroy(&raw mut actions);
return Err(crate::CrateError::Unexpected);
}
}
let mut pid: libc::pid_t = 0;
let rc = libc::posix_spawnp(
&raw mut pid,
ptrs[0],
actions_ptr,
&raw const actions,
core::ptr::null(),
ptrs.as_ptr().cast::<*mut core::ffi::c_char>(),
environ.cast::<*mut core::ffi::c_char>(),
);
if !actions_ptr.is_null() {
libc::posix_spawn_file_actions_destroy(&raw mut actions);
}
libc::posix_spawn_file_actions_destroy(&raw mut actions);
if rc != 0 {
return Err(crate::CrateError::Unexpected);
}
Expand All @@ -4703,9 +4704,7 @@ fn spawn_sync_inherit_impl(
return Err(crate::CrateError::Unexpected);
}
if pid == 0 {
// Child. execvp inherits stdio + environ, which is exactly the
// "inherit" contract this helper promises. On failure, _exit
// (no destructors / atexit hooks in a forked child).
// Only async-signal-safe calls before exec in the forked child.
if stdin == StdinBehavior::Ignore {
// StdinBehavior::Ignore: fd 0 ← /dev/null.
let devnull = libc::open(c"/dev/null".as_ptr(), libc::O_RDONLY);
Expand All @@ -4716,6 +4715,12 @@ fn spawn_sync_inherit_impl(
libc::close(devnull);
}
}
for fd in 0..3 {
let flags = libc::fcntl(fd, libc::F_GETFD);
if flags < 0 || libc::fcntl(fd, libc::F_SETFD, flags & !libc::FD_CLOEXEC) < 0 {
libc::_exit(127);
}
}
libc::execvp(ptrs[0], ptrs.as_ptr());
libc::_exit(127);
}
Expand Down
8 changes: 6 additions & 2 deletions src/crash_handler/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2906,9 +2906,13 @@ mod draft {
libc::close(i);
}
}
// SAFETY: argv is NUL-terminated array of NUL-terminated strings; environ is the
// process environment block
// SAFETY: fcntl and execve are async-signal-safe; argv and environ are
// NUL-terminated. Only stderr is inherited by the crash reporter.
unsafe {
let flags = libc::fcntl(2, libc::F_GETFD);
if flags != -1 {
libc::fcntl(2, libc::F_SETFD, flags & !libc::FD_CLOEXEC);
}
libc::execve(argv[0], argv.as_ptr(), bun_core::c_environ());
}
// SAFETY: _exit is async-signal-safe in the forked child
Expand Down
29 changes: 23 additions & 6 deletions src/jsc/bindings/c-bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -693,12 +693,6 @@ extern "C" void bun_initialize_process()
setvbuf(stderr, nullptr, _IONBF, 0);

#if OS(LINUX)
// Prevent leaking inherited file descriptors on Linux
// This is less of an issue for macOS due to posix_spawn
// This is best effort, not all linux kernels support close_range or CLOSE_RANGE_CLOEXEC
// To avoid breaking --watch, we skip stdin, stdout, stderr and IPC.
bun_close_range(4, ~0U, CLOSE_RANGE_CLOEXEC);

execve_counting_pid = getpid();
#endif

Expand Down Expand Up @@ -757,6 +751,29 @@ extern "C" void bun_initialize_process()
close(devNullFd_);
}

// Node's InitializeOncePerProcessInternal calls uv_disable_stdio_inheritance,
// including stdio and IPC: exec/spawn callers must explicitly opt back in.
#if OS(LINUX) || OS(FREEBSD)
if (bun_close_range(0, ~0U, CLOSE_RANGE_CLOEXEC) != 0)
#endif
{
// Match libuv's unix/core.c: probe 0..15 even across gaps, then stop on failure.
for (int fd = 0;; fd++) {
int flags;
do {
flags = fcntl(fd, F_GETFD);
} while (flags == -1 && errno == EINTR);
int result = flags;
if (flags != -1) {
do {
result = fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
} while (result == -1 && errno == EINTR);
}
if (result == -1 && fd > 15)
break;
}
}

// Restore TTY state on exit
if (anyTTYs) {
struct sigaction sa;
Expand Down
71 changes: 71 additions & 0 deletions test/js/bun/spawn/spawn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ import {
isBroken,
isDebug,
isLinux,
isMacOS,
isPosix,
isWindows,
libcPathForDlopen,
shellExe,
tempDir,
tmpdirSync,
Expand Down Expand Up @@ -1931,6 +1933,75 @@ describe.skipIf(!isPosix)("file status flags handed to the child", () => {
});
});

// These probes use the Linux/macOS libc ABI through bun:ffi.
describe.skipIf(!(isLinux || isMacOS) || isAndroid)("inherited descriptors are close-on-exec", () => {
it.concurrent("marks stdio and extra pipes before user code uses them", async () => {
await using proc = spawn({
cmd: [
bunExe(),
"-e",
`import { dlopen } from "bun:ffi";
const { symbols: { fcntl } } = dlopen(${JSON.stringify(isMacOS ? "libSystem.B.dylib" : libcPathForDlopen())}, {
fcntl: { args: ["i32", "i32"], returns: "i32" },
});
const flags = [0, 1, 2, 3].map(fd => fcntl(fd, 1));
console.log(JSON.stringify(flags));`,
],
env: bunEnv,
stdio: ["pipe", "pipe", "pipe", "pipe"],
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(JSON.parse(stdout)).toEqual([1, 1, 1, 1]);
expect(stderr).toBe("");
expect(exitCode).toBe(0);
});

it.concurrent("native system children do not inherit stdout", async () => {
await using proc = spawn({
cmd: [
bunExe(),
"-e",
`import { dlopen, ptr } from "bun:ffi";
const { symbols: { system } } = dlopen(${JSON.stringify(isMacOS ? "libSystem.B.dylib" : libcPathForDlopen())}, {
system: { args: ["ptr"], returns: "i32" },
});
const command = Buffer.from("echo leaked-stdout\\0");
const result = system(ptr(command));
console.log("bun-stdout");
console.log(result !== -1);`,
],
env: bunEnv,
stdio: ["pipe", "pipe", "pipe"],
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stdout).toBe("bun-stdout\ntrue\n");
expect(stderr).toBe("");
expect(exitCode).toBe(0);
});

it.concurrent("CLI sync helpers explicitly inherit stdout and stderr", async () => {
using dir = tempDir("spawn-cli-inherit", {
"package.json": JSON.stringify({
name: "spawn-cli-inherit",
scripts: { postinstall: "echo helper-stdout; echo helper-stderr >&2" },
overrides: { "@types/bun": "file:./types-bun", typescript: "file:./typescript" },
}),
"types-bun/package.json": JSON.stringify({ name: "@types/bun", version: "1.0.0" }),
"typescript/package.json": JSON.stringify({ name: "typescript", version: "7.0.0" }),
});
await using proc = spawn({
cmd: [bunExe(), "init", "-y"],
cwd: String(dir),
env: { ...bunEnv, BUN_AGENT_RULE_DISABLED: "1" },
stdio: ["ignore", "pipe", "pipe"],
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stdout).toContain("helper-stdout\n");
expect(stderr).toContain("helper-stderr\n");
expect(exitCode).toBe(0);
});
});

describe.skipIf(!isPosix)("stdio source fds that are also slot numbers", () => {
// File actions run in slot order in the child. The source fd of a later
// slot must survive the actions of the slots before it (the close of an
Expand Down
Loading