Skip to content
Closed
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
35 changes: 33 additions & 2 deletions src/jsc/bindings/c-bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,11 @@ extern "C" void Bun__onExit();
extern "C" int32_t bun_stdio_tty[3];
#if !OS(WINDOWS)
static termios termios_to_restore_later[3];
// F_GETFL snapshot for each stdio fd at startup, or -1 if the fcntl failed.
// bun_restore_stdio() uses this to restore the O_NONBLOCK bit on exit so a
// sibling in the same subshell (sharing the pipe file description) does not
// inherit nonblocking stdin after Bun exits. Mirrors Node's ResetStdio().
static int bun_stdio_flags[3] = { -1, -1, -1 };
// Whether Bun itself has modified the termios of each stdio fd during this
// process's lifetime (e.g. via process.stdin.setRawMode). Used to decide
// whether the exit-time termios restore should fire when Bun is acting as a
Expand All @@ -504,6 +509,26 @@ extern "C" void bun_restore_stdio()

#if !OS(WINDOWS)

// Restore the O_NONBLOCK bit to its startup value for every stdio fd.
// fcntl() is async-signal-safe, so this is fine from onExitSignal.
for (int fd = 0; fd < 3; fd++) {
if (bun_stdio_flags[fd] < 0)
continue;
int flags;
do
flags = fcntl(fd, F_GETFL);
while (flags == -1 && errno == EINTR);
if (flags == -1)
continue;
if ((O_NONBLOCK & (flags ^ bun_stdio_flags[fd])) == 0)
continue;
flags = (flags & ~O_NONBLOCK) | (bun_stdio_flags[fd] & O_NONBLOCK);
int err;
do
err = fcntl(fd, F_SETFL, flags);
while (err == -1 && errno == EINTR);
}

// Only suppress the restore when Bun is a pipeline producer (stdout is a
// pipe, not a TTY) and it didn't touch termios itself. That's the #29592
// case — a downstream consumer on the same /dev/pts/* device has already
Expand Down Expand Up @@ -615,7 +640,13 @@ extern "C" void bun_initialize_process()
}
};

bool anyFlags = false;
for (int fd = 0; fd < 3; fd++) {
do
bun_stdio_flags[fd] = fcntl(fd, F_GETFL);
while (bun_stdio_flags[fd] == -1 && errno == EINTR);
anyFlags = anyFlags || bun_stdio_flags[fd] >= 0;

int result = isatty(fd);
if (result == 0) {
if (errno == EBADF) [[unlikely]] {
Expand All @@ -641,8 +672,8 @@ extern "C" void bun_initialize_process()
close(devNullFd_);
}

// Restore TTY state on exit
if (anyTTYs) {
// Restore TTY state / O_NONBLOCK on signal exit
if (anyTTYs || anyFlags) {
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sigemptyset(&sa.sa_mask);
Expand Down
37 changes: 36 additions & 1 deletion src/runtime/webcore/FileReader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,10 +159,31 @@ impl Lazy {
'brk: {
#[cfg(unix)]
{
let rc = open_as_nonblocking_tty(pl_fd.native(), sys::O::RDONLY);
// libuv `uv_tty_init`: reopen the tty with the fd's
// existing access mode so the fresh file description
// keeps O_RDWR when the original had it, then `dup2`
// it back onto the stdio fd. That leaves fd 0 itself
// nonblocking without touching the file description
// shared with the parent shell. Only stdin is swapped
// in place; stdout/stderr readers keep using a
// separate read-only fd so the write side's
// blocking-tty contract on fd 1/2 is untouched and a
// `> /dev/tty` (O_WRONLY) fd 1 still yields a
// readable reopened fd.
let accmode = if *pl_fd == Fd::stdin() {
sys::get_fcntl_flags(*pl_fd)
.map(|f| f as i32 & sys::O::ACCMODE)
.unwrap_or(sys::O::RDONLY)
} else {
sys::O::RDONLY
};
let rc = open_as_nonblocking_tty(pl_fd.native(), accmode);
Comment thread
robobun marked this conversation as resolved.
Resolved
if rc > -1 {
is_nonblocking = true;
file.is_atty = Some(true);
if *pl_fd == Fd::stdin() {
let _ = sys::dup2(Fd::from_native(rc), *pl_fd);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
break 'brk Fd::from_native(rc);
}
}
Expand Down Expand Up @@ -249,6 +270,20 @@ impl Lazy {
FileType::File
};

// libuv `uv_pipe_open` / `uv_tty_init` set O_NONBLOCK on the adopted
// stdio fd. Node exposes that via `process.stdin`: once the stream
// is started, `fs.readSync(0, …)` returns EAGAIN instead of blocking
// (issue #5305). The tty path above already swapped in a nonblocking
// file description; this covers pipe/socket stdin and the tty
// fallback when reopening failed. Scoped to stdin so a
// `Bun.stdout.stream()` reader does not mutate fd 1/2. The startup
// O_NONBLOCK bit is restored in `bun_restore_stdio()`.
if fd == Fd::stdin() && this.pollable && !is_nonblocking {
if sys::set_nonblocking(fd).is_ok() {
is_nonblocking = true;
}
}

// pretend it's a non-blocking pipe if it's a TTY
if is_nonblocking && this.file_type != FileType::Socket {
this.file_type = FileType::NonblockingPipe;
Expand Down
2 changes: 2 additions & 0 deletions src/sys/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1216,6 +1216,8 @@ pub mod O {
pub const NOCTTY: i32 = libc::O_NOCTTY;
#[cfg(windows)]
pub const NOCTTY: i32 = 0;
#[cfg(unix)]
pub const ACCMODE: i32 = libc::O_ACCMODE;
#[cfg(windows)]
pub const ACCMODE: i32 = 3;
#[cfg(target_os = "macos")]
Expand Down
204 changes: 204 additions & 0 deletions test/js/node/process/stdin/process-stdin-nonblock.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
// Once `process.stdin` starts reading, Node/libuv put the stdin file
// descriptor into nonblocking mode (`uv_pipe_open` / `uv_tty_init` both call
// `uv__nonblock(fd, 1)`). Bun used to leave fd 0 untouched, so a direct
// `fs.readSync(0, buf)` afterwards would block on an empty pipe (or, on a raw
// TTY, return one keystroke at a time) instead of throwing `EAGAIN` like Node.
// https://github.com/oven-sh/bun/issues/5305
import { expect, test } from "bun:test";
import { bunEnv, bunExe, isLinux, isMacOS, isPosix, libcPathForDlopen, tempDir } from "harness";
import path from "node:path";

// O_NONBLOCK is a Unix fd flag; the Windows stdin path is libuv-backed and
// `fs.readSync` there never observes EAGAIN.
test.skipIf(!isPosix)(
"fs.readSync(0) throws EAGAIN once process.stdin is reading (pipe)",
async () => {
const script = `
const fs = require("fs");
const readline = require("readline");
readline.createInterface({ input: process.stdin, output: process.stdout });
try {
const n = fs.readSync(0, Buffer.alloc(64));
console.log("RETURNED:" + n);
} catch (e) {
console.log("ERROR:" + e.code);
}
process.exit(0);
`;

await using proc = Bun.spawn({
cmd: [bunExe(), "-e", script],
env: bunEnv,
stdin: "pipe",
stdout: "pipe",
stderr: "pipe",
});

// Without the fix the child is parked in a blocking read() on fd 0, so the
// only way to distinguish pass from fail is a deadline. Closing stdin would
// unblock that read with a 0-byte result, which masks the bug; keeping the
// write end open forces the blocking read to stay blocked.
const exited = await Promise.race([proc.exited, Bun.sleep(30_000).then(() => "timeout" as const)]);
if (exited === "timeout") {
proc.kill(9);
await proc.exited;
}

const [stdout, stderr] = await Promise.all([proc.stdout.text(), proc.stderr.text()]);

expect(stderr).toBe("");
expect({ stdout: stdout.trim(), exited }).toEqual({ stdout: "ERROR:EAGAIN", exited: 0 });
},
60_000,
);

test.skipIf(!isPosix)("fd 0 is left alone when stdin is a regular file", async () => {
// O_NONBLOCK is meaningless on a regular file; the reader should leave the
// fd flags untouched so `fs.readSync(0, buf)` keeps returning data.
using dir = tempDir("stdin-nonblock-file", {
"in.txt": "regular file body\n",
});

const script = `
const fs = require("fs");
process.stdin.resume();
const buf = Buffer.alloc(16);
const n = fs.readSync(0, buf);
console.log("READ:" + n + ":" + buf.toString("utf8", 0, n));
process.exit(0);
`;

await using proc = Bun.spawn({
cmd: [bunExe(), "-e", script],
env: bunEnv,
stdin: Bun.file(path.join(String(dir), "in.txt")),
stdout: "pipe",
stderr: "pipe",
});

const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);

expect(stderr).toBe("");
expect(stdout.trim()).toBe("READ:16:regular file bod");
expect(exitCode).toBe(0);
});

test.skipIf(!isPosix)(
"tty stdin: fd 0 becomes nonblocking and keeps its access mode",
async () => {
// Bun.spawn({ terminal }) hands the child a pty slave on fd 0/1/2.
// After process.stdin starts, fd 0 should be swapped for a fresh
// nonblocking file description with the original O_RDWR access mode, so
// fs.writeSync(0, ...) still succeeds and fs.readSync(0, ...) sees EAGAIN.
const script = `
const fs = require("fs");
process.stdin.resume();
let write = "ok";
try { fs.writeSync(0, "x"); } catch (e) { write = e.code; }
// Drain anything the pty already buffered, then the next read must
// throw EAGAIN because fd 0 is nonblocking.
let read;
for (;;) {
try {
if (fs.readSync(0, Buffer.alloc(256)) === 0) { read = "EOF"; break; }
} catch (e) { read = e.code; break; }
}
process.stdout.write("RESULT " + JSON.stringify({ isTTY: process.stdin.isTTY, write, read }));
process.exit(0);
`;

let output = "";
const decoder = new TextDecoder();
const done = Promise.withResolvers<void>();

const proc = Bun.spawn({
cmd: [bunExe(), "-e", script],
env: bunEnv,
terminal: {
cols: 200,
rows: 24,
data(_t, chunk: Uint8Array) {
output += decoder.decode(chunk, { stream: true });
if (output.includes("RESULT ") && output.includes("}")) done.resolve();
},
exit() {
done.resolve();
},
},
});

await Promise.race([done.promise, Bun.sleep(30_000)]);
proc.kill();
await proc.exited;
proc.terminal?.close();
output += decoder.decode();

const stripped = Bun.stripANSI(output).replace(/[\r\n]/g, "");
const match = stripped.match(/RESULT (\{[^}]*\})/);
if (!match) {
throw new Error("child did not emit RESULT; terminal output was: " + JSON.stringify(output));
}
expect(JSON.parse(match[1])).toEqual({ isTTY: true, write: "ok", read: "EAGAIN" });
},
60_000,
);

// `libcPathForDlopen()` covers glibc/musl/darwin; FreeBSD is not mapped yet.
test.skipIf(!(isLinux || isMacOS))("O_NONBLOCK on pipe stdin is restored when bun exits", async () => {
// `producer | { bun; sibling }` share one read-end file description. Node
// restores its startup O_NONBLOCK bit on the way out (ResetStdio); Bun
// should too so `sibling` does not inherit a nonblocking stdin.
using dir = tempDir("stdin-nonblock-restore", {
// fs.readSync(0) on a pipe whose write end is already closed returns 0
// either way, so probe the O_NONBLOCK bit directly via fcntl(F_GETFL).
"probe.js": `
const { dlopen, FFIType } = require("bun:ffi");
const { symbols: { fcntl } } = dlopen(process.env.LIBC, {
fcntl: { args: [FFIType.int, FFIType.int, FFIType.int], returns: FFIType.int },
});
const { O_NONBLOCK } = require("node:fs").constants;
console.log((fcntl(0, 3, 0) & O_NONBLOCK) ? "NONBLOCKING" : "BLOCKING");
Comment thread
robobun marked this conversation as resolved.
Resolved
`,
"middle.js": `process.stdin.resume(); process.exit(0);`,
});

await using proc = Bun.spawn({
cmd: ["sh", "-c", `"$BUN" probe.js && "$BUN" middle.js && "$BUN" probe.js`],
env: { ...bunEnv, BUN: bunExe(), LIBC: libcPathForDlopen() },
cwd: String(dir),
stdin: "pipe",
stdout: "pipe",
stderr: "pipe",
});
await proc.stdin.end();

const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stderr).toBe("");
expect(stdout.trim().split("\n")).toEqual(["BLOCKING", "BLOCKING"]);
expect(exitCode).toBe(0);
});

test.skipIf(!isPosix)("process.stdin still delivers data over a nonblocking pipe", async () => {
const script = `
let got = "";
process.stdin.on("data", d => (got += d));
process.stdin.on("end", () => console.log("GOT:" + got));
`;

await using proc = Bun.spawn({
cmd: [bunExe(), "-e", script],
env: bunEnv,
stdin: "pipe",
stdout: "pipe",
stderr: "pipe",
});

proc.stdin.write("hello world");
await proc.stdin.end();

const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);

expect(stderr).toBe("");
expect(stdout.trim()).toBe("GOT:hello world");
expect(exitCode).toBe(0);
});
Loading