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

- Keep macOS subprocess exit handling non-blocking when kqueue reports ESRCH before a terminal child can be reaped.
- Use a private fallback for unusable POSIX `node` shim directories instead of silently dropping `node`, warn when no shim can be created, and honor `BUN_TMPDIR` for the shim like the node-gyp directory.
- Adapt upstream [#35565](https://github.com/oven-sh/bun/pull/35565): key the lifecycle-script and `--bun` `node` shim directory on the user id (`/tmp/bun-node-<uid>-<sha>`), so a shim directory another user created on the same host no longer drops `node` from lifecycle-script `PATH` (upstream [#42048](https://github.com/oven-sh/bun/issues/42048)).
- Adapt upstream [#33288](https://github.com/oven-sh/bun/pull/33288) to preserve `node:diagnostics_channel` subscribers for an in-flight publication when callbacks subscribe, unsubscribe, or publish recursively.
Expand Down
48 changes: 41 additions & 7 deletions src/io/posix_event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,9 @@ static MAX_GENERATION_NUMBER: core::sync::atomic::AtomicUsize =
/// generation number); FreeBSD only has the plain `struct kevent`.
#[cfg(target_os = "macos")]
type KQueueEvent = bun_sys::darwin::kevent64_s;

#[cfg(target_os = "macos")]
const PROCESS_REAP_RETRY_MS: i64 = 10;
#[cfg(target_os = "freebsd")]
type KQueueEvent = bun_sys::freebsd::Kevent;

Expand Down Expand Up @@ -691,9 +694,21 @@ impl FilePoll {
},
Flags::Process => kevent64_s {
ident: u64::try_from(fd.native()).expect("int cast"),
filter: EVFILT::PROC,
data: 0,
fflags: NOTE::EXIT,
filter: if self.flags.contains(Flags::ProcessRetry) {
libc::EVFILT_TIMER
} else {
EVFILT::PROC
},
data: if self.flags.contains(Flags::ProcessRetry) {
PROCESS_REAP_RETRY_MS
} else {
0
},
fflags: if self.flags.contains(Flags::ProcessRetry) {
0
} else {
NOTE::EXIT
},
udata: Pollable::init(self).ptr() as u64,
flags: EV::ADD | one_shot_flag,
ext: [self.generation_number as u64, 0],
Expand Down Expand Up @@ -743,7 +758,17 @@ impl FilePoll {
&raw const TIMEOUT,
)
};
if sys::get_errno(rc) == sys::E::EINTR {
let errno = sys::get_errno(rc);
if errno == sys::E::EINTR {
continue;
}
if errno == sys::E::ESRCH && changelist[0].filter == EVFILT::PROC {
// An exiting PTY session leader may need this loop to drain output before wait4 can reap it.
self.flags.insert(Flags::ProcessRetry);
changelist[0].filter = libc::EVFILT_TIMER;
changelist[0].flags = EV::ADD | EV::ONESHOT;
changelist[0].fflags = 0;
changelist[0].data = PROCESS_REAP_RETRY_MS;
continue;
}
break 'rc rc;
Expand Down Expand Up @@ -977,7 +1002,7 @@ impl FilePoll {
}
#[cfg(target_os = "macos")]
{
use bun_sys::darwin::{EV, EVFILT, NOTE, kevent64, kevent64_s};
use bun_sys::darwin::{EV, EVFILT, kevent64, kevent64_s};
// SAFETY: all-zero is a valid kevent64_s
let mut changelist: [kevent64_s; 2] = bun_core::ffi::zeroed();

Expand Down Expand Up @@ -1011,9 +1036,13 @@ impl FilePoll {
},
Flags::Process => kevent64_s {
ident: u64::try_from(fd.native()).expect("int cast"),
filter: EVFILT::PROC,
filter: if self.flags.contains(Flags::ProcessRetry) {
libc::EVFILT_TIMER
} else {
EVFILT::PROC
},
data: 0,
fflags: NOTE::EXIT,
fflags: 0,
udata: Pollable::init(self).ptr() as u64,
flags: EV::DELETE,
ext: [0, 0],
Expand Down Expand Up @@ -1146,6 +1175,8 @@ impl FilePoll {
self.flags.remove(Flags::PollProcess);
self.flags.remove(Flags::PollMachport);
self.flags.remove(Flags::PollMemoryPressure);
#[cfg(target_os = "macos")]
self.flags.remove(Flags::ProcessRetry);

sys::Result::Ok(())
}
Expand Down Expand Up @@ -1210,6 +1241,9 @@ pub enum Flags {
IgnoreUpdates,

Socket,

#[cfg(target_os = "macos")]
ProcessRetry,
}

pub type FlagsSet = enumset::EnumSet<Flags>;
Expand Down
42 changes: 4 additions & 38 deletions src/spawn/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -362,44 +362,10 @@ impl Process {

#[cfg(unix)]
fn on_wait_pid(&mut self, waitpid_result: &bun_sys::Result<WaitPidResult>, rusage: &Rusage) {
let pid = self.pid;
// Mutated only on the macOS ESRCH retry path below.
#[cfg(target_os = "macos")]
let mut rusage_result = *rusage;
#[cfg(not(target_os = "macos"))]
let rusage_result = *rusage;

let status: Option<Status> = Status::from(pid, waitpid_result).or_else(|| 'brk: {
match self.rewatch_posix() {
Ok(()) => {}
Err(err_) => {
#[cfg(target_os = "macos")]
if err_.get_errno() == bun_sys::E::ESRCH {
break 'brk Status::from(
pid,
&posix_spawn::wait4(
pid,
// Normally we would use WNOHANG to avoid blocking the event loop.
// However, there seems to be a race condition where the operating system
// tells us that the process has already exited (ESRCH) but the waitpid
// call with WNOHANG doesn't return the status yet.
// As a workaround, we use 0 to block the event loop until the status is available.
// This should be fine because the process has already exited, so the data
// should become available basically immediately. Also, testing has shown that this
// occurs extremely rarely and only under high load.
0,
Some(&mut rusage_result),
),
);
}
break 'brk Some(Status::Err(err_));
}
}
None
});

let status = Status::from(self.pid, waitpid_result)
.or_else(|| self.rewatch_posix().err().map(Status::Err));
let Some(status) = status else { return };
self.on_exit(status, &rusage_result);
self.on_exit(status, rusage);
}

pub fn watch_or_reap(&mut self) -> bun_sys::Result<bool> {
Expand All @@ -413,7 +379,7 @@ impl Process {
Err(err) => {
#[cfg(unix)]
if err.get_errno() == bun_sys::E::ESRCH {
self.wait(true);
self.wait(!cfg!(target_os = "macos"));
return Ok(self.has_exited());
}
Err(err)
Expand Down
75 changes: 75 additions & 0 deletions test/js/bun/terminal/terminal-spawn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -612,3 +612,78 @@ describe("Bun.Terminal subprocess integration", () => {
expect(exitCode).toBe(0);
});
});

// macOS can reject EVFILT_PROC while a PTY session leader is still draining in exit().
// Delay the real registration until exit starts; do not synthesize ESRCH.
test.skipIf(process.platform !== "darwin")("ESRCH while a terminal child exits does not block PTY reads", async () => {
using dir = tempDir("terminal-esrch", {
"delay-watch.c": `
#include <sys/event.h>
#include <libproc.h>
#include <sys/proc_info.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>

static int delayed_kevent64(int kq, const struct kevent64_s *changes, int count,
struct kevent64_s *events, int capacity, unsigned int flags, const struct timespec *timeout) {
for (int i = 0; i < count; i++) {
if (changes[i].filter != EVFILT_PROC || !(changes[i].flags & EV_ADD)) continue;
struct timespec start, now;
clock_gettime(CLOCK_MONOTONIC, &start);
for (;;) {
struct proc_bsdinfo info;
int size = proc_pidinfo((int)changes[i].ident, PROC_PIDTBSDINFO, 0, &info, sizeof(info));
if (size != sizeof(info) || (info.pbi_flags & PROC_FLAG_INEXIT)) break;
clock_gettime(CLOCK_MONOTONIC, &now);
if (now.tv_sec - start.tv_sec >= 2) break;
struct timespec pause = {0, 100000};
nanosleep(&pause, NULL);
}
}
int result = kevent64(kq, changes, count, events, capacity, flags, timeout);
if (result == -1 && errno == ESRCH) {
int saved = errno;
write(2, "ESRCH-before-reap\\n", 18);
errno = saved;
}
return result;
}
__attribute__((used, section("__DATA,__interpose")))
static const struct { const void *replacement; const void *original; } interpose = {
(const void *)delayed_kevent64, (const void *)kevent64
};
`,
"fixture.js": `
let output = "";
const proc = Bun.spawn(["/bin/sh", "-c", 'printf "%0512d" 0; exit 3'], {
terminal: { data(_, bytes) { output += new TextDecoder().decode(bytes); } },
});
const code = await proc.exited;
proc.terminal.close();
console.log(JSON.stringify({ length: output.length, code }));
`,
});
const library = `${dir}/delay-watch.dylib`;
await using compiler = Bun.spawn({
cmd: ["cc", "-dynamiclib", `${dir}/delay-watch.c`, "-o", library],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const compilerError = await compiler.stderr.text();
expect(compilerError).toBe("");
expect(await compiler.exited).toBe(0);
await using proc = Bun.spawn({
cmd: [bunExe(), `${dir}/fixture.js`],
env: { ...bunEnv, DYLD_INSERT_LIBRARIES: library },
stdout: "pipe",
stderr: "pipe",
timeout: 3000,
killSignal: "SIGKILL",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stderr).toContain("ESRCH-before-reap");
expect(JSON.parse(stdout)).toEqual({ length: 512, code: 3 });
expect(exitCode).toBe(0);
});
Loading