diff --git a/src/bun_core/lib.rs b/src/bun_core/lib.rs index 05728ddc1439..0ba309061f5d 100644 --- a/src/bun_core/lib.rs +++ b/src/bun_core/lib.rs @@ -566,6 +566,7 @@ bun_dispatch::link_interface! { fn create_file(cwd: Fd, path: &[u8]) -> core::result::Result; fn quiet_writer_from_fd(fd: Fd) -> output::QuietWriter; fn quiet_writer_adapt(qw: output::QuietWriter, buf: *mut u8, len: usize) -> output::QuietWriterAdapter; + fn quiet_writer_adapter_take_err(a: &mut output::QuietWriterAdapter) -> i32; fn quiet_writer_flush(qw: &mut output::QuietWriter); fn quiet_writer_write_all(qw: &mut output::QuietWriter, bytes: &[u8]) -> bool; fn quiet_writer_fd(qw: &output::QuietWriter) -> Fd; diff --git a/src/bun_core/output.rs b/src/bun_core/output.rs index 3274e5c074cb..3c5140e81b7f 100644 --- a/src/bun_core/output.rs +++ b/src/bun_core/output.rs @@ -106,6 +106,15 @@ impl QuietWriterAdapter { // the io::Writer is the first field (repr(C)). unsafe { &mut *std::ptr::from_mut::(self).cast::() } } + /// Take and clear the sticky write errno this adapter's `write_all`/`flush` + /// recorded (raw `libc` value). See `ConsoleObject::forward_write_error`. + #[inline] + pub fn take_err(&mut self) -> Option { + match output_sink().quiet_writer_adapter_take_err(self) { + 0 => None, + errno => Some(errno), + } + } } /// Opaque file handle. Replaces `bun_sys::File` in this crate. diff --git a/src/js/builtins/ProcessObjectInternals.ts b/src/js/builtins/ProcessObjectInternals.ts index 37681a67f7c6..e2b88d22233a 100644 --- a/src/js/builtins/ProcessObjectInternals.ts +++ b/src/js/builtins/ProcessObjectInternals.ts @@ -55,6 +55,10 @@ export function getStdioWriteStream( stream = new fs.WriteStream(null, { autoClose: false, fd, $fastPath: true }); stream.readable = false; stream._type = "fs"; + // Node's stdio (net.Socket / SyncWriteStream) has autoDestroy:true paired + // with the _destroy -> _undestroy() override below, so errorOrDestroy + // emits 'error' per failed write and the stream stays writable. + stream._writableState.autoDestroy = true; // When stdout/stderr are piped or connected to a socket, they should have Symbol.asyncIterator // to match Node.js behavior where they become Duplex streams (Socket) @@ -65,11 +69,6 @@ export function getStdioWriteStream( // stdout/stderr don't produce readable data, so yield nothing })(); }; - } else { - // File-backed stdio: Node's SyncWriteStream runs end() -> finish -> - // destroy -> the _destroy override below -> _undestroy(), which resets - // writable state so later writes succeed. autoClose:false disabled that. - stream._writableState.autoDestroy = true; } } @@ -77,9 +76,18 @@ export function getStdioWriteStream( stream.destroySoon = stream.destroy; stream._destroy = function (err, cb) { cb(err); + // Bun keeps running after an uncaughtException (unlike Node), so preserve + // errorEmitted across _undestroy() when no 'error' listener is attached + // to keep emitErrorNT's one-shot guard latched instead of re-reporting + // forever. With a listener, reset it so the listener fires per write. + const w = this._writableState; + const hadErrorEmitted = w.errorEmitted; this._undestroy(); + if (this.listenerCount("error") === 0) { + w.errorEmitted = hadErrorEmitted; + } - if (!this._writableState.emitClose) { + if (!w.emitClose) { process.nextTick(() => { this.emit("close"); }); diff --git a/src/jsc/ConsoleObject.rs b/src/jsc/ConsoleObject.rs index 895848fcd305..6f9f094f0766 100644 --- a/src/jsc/ConsoleObject.rs +++ b/src/jsc/ConsoleObject.rs @@ -348,6 +348,54 @@ impl Drop for FlushOnDrop<'_> { } } +#[inline] +fn level_uses_stderr(message_type: MessageType, level: MessageLevel) -> bool { + matches!(level, MessageLevel::Warning | MessageLevel::Error) + || message_type == MessageType::Assert +} + +unsafe extern "C" { + fn Bun__ConsoleObject__onStdioWriteError(global: &JSGlobalObject, fd: i32, err: JSValue); +} + +/// Surface any write errno the console adapter recorded on +/// `process.stdout`/`stderr` as an `'error'` event. Bun's native `console.*` +/// writes to the fd directly, bypassing the stream; Node routes through +/// `process.stdout.write()`. The C++ side drops it when no `'error'` listener +/// is attached (matching `test-process-external-stdio-close`). +fn forward_write_error(global: &JSGlobalObject, is_stderr: bool) { + let errno = { + // SAFETY: single-JS-thread top-level host call; `&mut` is scoped to + // this block so nothing derived from it is live across the re-entrant + // FFI below. + let console = unsafe { vm_console_mut(global) }; + let backing = if is_stderr { + &mut console.error_writer_backing + } else { + &mut console.writer_backing + }; + match backing.take_err() { + None => return, + Some(e) => e, + } + }; + // Don't call into JS under a pending exception; errno was cleared above. + if global.has_exception() { + return; + } + // EAGAIN/EINTR are filtered at record time (drain_to_fd), so any errno + // reaching here is non-transient. + debug_assert!(errno != bun_sys::E::EAGAIN as i32 && errno != bun_sys::E::EINTR as i32); + let sys_err = bun_sys::Error::new(errno, bun_sys::Tag::write); + let js_err = crate::SysErrorJsc::to_js(&sys_err, global); + if global.has_exception() { + return; + } + // SAFETY: C++ side resolves `process.stdout`/`stderr` and calls + // `.destroy(err)`; `js_err` is stack-rooted for the call's duration. + unsafe { Bun__ConsoleObject__onStdioWriteError(global, if is_stderr { 2 } else { 1 }, js_err) }; +} + /// #[crate::host_call] pub extern "C" fn message_with_type_and_level( @@ -358,6 +406,7 @@ pub extern "C" fn message_with_type_and_level( vals: *const JSValue, len: usize, ) { + let is_stderr = level_uses_stderr(message_type, level); if let Err(err) = message_with_type_and_level_(ctype, message_type, level, global, vals, len) { // The exception is already set on the VM (`JsError::Thrown`); for OOM // make sure something is pending. Mirrors `host_fn::void_from_js_error`. @@ -366,6 +415,8 @@ pub extern "C" fn message_with_type_and_level( } debug_assert!(global.has_exception()); } + // Safe with a pending exception: clears the sticky errno and returns early. + forward_write_error(global, is_stderr); } fn message_with_type_and_level_( @@ -407,8 +458,7 @@ fn message_with_type_and_level_( // Lock/unlock a mutex incase two JS threads are console.log'ing at the same // time. We do this the slightly annoying way to avoid assigning a pointer. - let use_stderr = matches!(level, MessageLevel::Warning | MessageLevel::Error) - || message_type == MessageType::Assert; + let use_stderr = level_uses_stderr(message_type, level); let _stream_lock = ConsoleStreamLock::acquire(use_stderr); if message_type == MessageType::Clear { @@ -544,7 +594,13 @@ fn message_with_type_and_level_( // SAFETY: see [`vm_console`]. `writer` (above) is dead in this arm — // the only later uses are in the mutually-exclusive `Trace` block, and // `message_type == Log` here. - let w = unsafe { (*console).writer() }; + let w = unsafe { + if use_stderr { + (*console).error_writer() + } else { + (*console).writer() + } + }; let _ = w.write_all(b"\n"); let _ = w.flush(); } else if message_type != MessageType::Trace { @@ -5801,6 +5857,7 @@ pub(crate) extern "C" fn Bun__ConsoleObject__count( let _ = writeln!(writer, "{}: {}", bstr::BStr::new(slice), current); } let _ = writer.flush(); + forward_write_error(global_this, false); } #[unsafe(no_mangle)] @@ -5933,7 +5990,7 @@ pub(crate) extern "C" fn Bun__ConsoleObject__timeLog( // SAFETY: caller passes a valid (args, args_len) pair. for &arg in unsafe { bun_core::ffi::slice(args, args_len) } { let Ok(tag) = formatter::Tag::get(arg, global) else { - return; + break; }; let _ = bun_io::Write::write_all(&mut writer, b" "); if Output::enable_ansi_colors_stderr() { @@ -5944,6 +6001,7 @@ pub(crate) extern "C" fn Bun__ConsoleObject__timeLog( } let _ = bun_io::Write::write_all(&mut writer, b"\n"); let _ = bun_io::Write::flush(&mut writer); + forward_write_error(global, true); } /// Stamp out the empty `Bun__ConsoleObject__*` C-ABI hooks that JSC's diff --git a/src/jsc/bindings/BunProcess.cpp b/src/jsc/bindings/BunProcess.cpp index 31bfe950540a..f1e0014a4632 100644 --- a/src/jsc/bindings/BunProcess.cpp +++ b/src/jsc/bindings/BunProcess.cpp @@ -4449,6 +4449,58 @@ extern "C" void Process__emitErrorEvent(Zig::GlobalObject* global, EncodedJSValu } } +// Surface a failed native console.* write on process.stdout/stderr via +// stream.destroy(err); its _destroy override _undestroy()s so the stream stays +// writable and 'error' fires on nextTick. Dropped when no 'error' listener is +// attached, matching Node's createWriteErrorHandler (test-process-external-stdio-close); +// a direct process.stdout.write() still surfaces an uncaught EPIPE via writeFast. +extern "C" void Bun__ConsoleObject__onStdioWriteError(Zig::GlobalObject* global, int32_t fd, EncodedJSValue encodedError) +{ + auto& vm = JSC::getVM(global); + auto scope = DECLARE_TOP_EXCEPTION_SCOPE(vm); + + // If process (or the target stream) was never touched, no 'error' listener + // can be attached; getDirect avoids reifying the lazy PropertyCallback. + if (!global->hasProcessObject()) + return; + auto* process = global->processObject(); + JSValue stream = process->getDirect(vm, fd == 2 ? Identifier::fromString(vm, "stderr"_s) : Identifier::fromString(vm, "stdout"_s)); + if (!stream || !stream.isObject()) + return; + JSObject* streamObj = stream.getObject(); + + JSValue listenerCountFn = streamObj->get(global, Identifier::fromString(vm, "listenerCount"_s)); + if (scope.exception()) [[unlikely]] { + (void)scope.tryClearException(); + return; + } + if (listenerCountFn.isCallable()) { + JSC::MarkedArgumentBuffer lcArgs; + lcArgs.append(jsString(vm, String("error"_s))); + JSValue count = JSC::call(global, listenerCountFn, JSC::getCallData(listenerCountFn), stream, lcArgs); + if (scope.exception()) [[unlikely]] { + (void)scope.tryClearException(); + return; + } + if (count.isNumber() && count.asNumber() == 0) + return; + } + + JSValue destroyFn = streamObj->get(global, Identifier::fromString(vm, "destroy"_s)); + if (scope.exception()) [[unlikely]] { + (void)scope.tryClearException(); + return; + } + if (!destroyFn.isCallable()) + return; + + JSC::MarkedArgumentBuffer args; + args.append(JSValue::decode(encodedError)); + JSC::call(global, destroyFn, JSC::getCallData(destroyFn), stream, args); + if (scope.exception()) [[unlikely]] + (void)scope.tryClearException(); +} + /* Source for Process.lut.h @begin processObjectTable _debugEnd Process_stubEmptyFunction Function 0 diff --git a/src/sys/lib.rs b/src/sys/lib.rs index d9b75097803f..c7d25a48dca6 100644 --- a/src/sys/lib.rs +++ b/src/sys/lib.rs @@ -9453,6 +9453,9 @@ struct SysQuietWriterAdapter { buf: *mut u8, cap: usize, pos: usize, + /// First write errno since the last `take_err()` (`0` = none); sticky so + /// `ConsoleObject` can check once after a `console.*` call's writes. + err: i32, } const _: () = { assert!( @@ -9466,16 +9469,30 @@ const _: () = { }; impl SysQuietWriterAdapter { - /// View of the bytes buffered so far (`buf[0..pos]`). Centralises the - /// (ptr, len) → slice reconstruction; the buffer is owned by the adapter - /// and lives for `&self`. + /// `fd_write_all_quiet` that also records the first I/O error's errno into + /// `self.err` (sticky across calls; cleared by `quiet_writer_adapter_take_err`). #[inline] - fn buffered(&self) -> &[u8] { - // SAFETY: `buf` is a `cap`-byte allocation owned by this adapter (set - // at construction); `pos <= cap` is upheld by `adapter_write_all` - // (drains before writing past `cap`). Bytes `[0, pos)` were written by - // `copy_nonoverlapping` and are initialized. Borrow tied to `&self`. - unsafe { core::slice::from_raw_parts(self.buf, self.pos) } + fn drain_to_fd(&mut self, mut bytes: &[u8]) { + while !bytes.is_empty() { + match write(self.fd, bytes) { + Ok(0) => { + if self.err == 0 { + self.err = E::EPIPE as i32; + } + return; + } + Ok(n) => bytes = &bytes[n..], + Err(e) => { + let errno = e.get_errno(); + // Transients are never forwarded; recording one would mask + // a real error from a later drain in the same console.* call. + if self.err == 0 && errno != E::EAGAIN && errno != E::EINTR { + self.err = errno as i32; + } + return; + } + } + } } } @@ -9486,18 +9503,21 @@ unsafe fn adapter_write_all( // SAFETY: `w` points at the first field of a SysQuietWriterAdapter (repr(C)). let this = unsafe { &mut *w.cast::() }; if this.cap == 0 { - let _ = fd_write_all_quiet(this.fd, bytes); + this.drain_to_fd(bytes); return Ok(()); } if this.pos + bytes.len() > this.cap { // Drain buffered bytes first. if this.pos > 0 { - let _ = fd_write_all_quiet(this.fd, this.buffered()); + // SAFETY: `buf[0..pos]` was initialized by the `copy_nonoverlapping` + // below on a prior call; `pos <= cap` is upheld by this guard. + let buffered = unsafe { core::slice::from_raw_parts(this.buf, this.pos) }; + this.drain_to_fd(buffered); this.pos = 0; } // Large writes bypass the buffer so the next small write still coalesces. if bytes.len() >= this.cap { - let _ = fd_write_all_quiet(this.fd, bytes); + this.drain_to_fd(bytes); return Ok(()); } } @@ -9514,7 +9534,9 @@ unsafe fn adapter_flush(w: *mut bun_core::io::Writer) -> core::result::Result<() // SAFETY: `w` points at the first field of a SysQuietWriterAdapter (repr(C)). let this = unsafe { &mut *w.cast::() }; if this.pos > 0 { - let _ = fd_write_all_quiet(this.fd, this.buffered()); + // SAFETY: `buf[0..pos]` is initialized — see `adapter_write_all`. + let buffered = unsafe { core::slice::from_raw_parts(this.buf, this.pos) }; + this.drain_to_fd(buffered); this.pos = 0; } Ok(()) @@ -9566,12 +9588,19 @@ bun_core::link_impl_OutputSink! { buf, cap: len, pos: 0, + err: 0, }; let mut out = bun_core::output::QuietWriterAdapter::uninit(); // SAFETY: size/align asserted in const block above; out is repr(C) [u8;64]. core::ptr::write((&raw mut out).cast::(), concrete); out }, + quiet_writer_adapter_take_err(a) => { + // SAFETY: `a` is the opaque envelope written by `quiet_writer_adapt` + // above; concrete repr is `SysQuietWriterAdapter` (size/align asserted). + let concrete = (&raw mut *a).cast::(); + core::mem::take(&mut (*concrete).err) + }, // QuietWriter itself is unbuffered (buffering lives in the Adapter). quiet_writer_flush(_qw) => (), quiet_writer_write_all(qw, bytes) => fd_write_all_quiet(qw_fd(qw), bytes), diff --git a/test/js/node/process/process-stdio.test.ts b/test/js/node/process/process-stdio.test.ts index ba35bc4f0484..310901066a20 100644 --- a/test/js/node/process/process-stdio.test.ts +++ b/test/js/node/process/process-stdio.test.ts @@ -1,6 +1,7 @@ import { spawn, spawnSync } from "bun"; import { describe, expect, test } from "bun:test"; -import { bunEnv, bunExe } from "harness"; +import { bunEnv, bunExe, isWindows } from "harness"; +import cp from "node:child_process"; import path from "path"; import { isatty } from "tty"; describe.concurrent("process-stdio", () => { @@ -159,3 +160,114 @@ describe.concurrent("process-stdio", () => { ); }); }); + +// EPIPE on a broken-pipe stdout: once the reader is gone, both console.log and +// process.stdout.write should surface an 'error' event on process.stdout with +// code EPIPE, and (absent a listener) report one uncaught error and exit 1. +// console.log writes natively to fd 1 and used to swallow the error entirely; +// process.stdout.write went through errorOrDestroy with autoDestroy:false and +// latched after the first emit. https://github.com/oven-sh/bun/issues/7251 +// +// Not describe.concurrent: the existing process-stdio block above already +// saturates the debug+ASAN process budget; adding five more concurrent children +// pushes the timer-paced stdin tests over their 5s timeout. +describe.skipIf(isWindows)("process.stdout/stderr EPIPE after reader closes", () => { + // Spawn a child with the target stream piped and immediately destroy the read + // end; the child waits for that by reading stdin to EOF (we close it), then + // writes. Pure event-driven: no timers. + const childBody = (which: "stdout" | "stderr", fn: "console" | "write", withListener: boolean) => { + const other = which === "stdout" ? "stderr" : "stdout"; + const consoleFn = which === "stdout" ? "log" : "error"; + return ` + const seen = []; + ${ + withListener + ? `process.${which}.on("error", e => seen.push(e.code + ":" + e.syscall + ":" + e.errno));` + : `process.on("uncaughtException", e => seen.push("uncaught:" + e.code));` + } + process.on("exit", c => process.${other}.write(JSON.stringify({ seen, exit: c }) + "\\n")); + process.stdin.resume(); + process.stdin.on("end", async () => { + for (let i = 0; i < 4; i++) { + ${fn === "write" ? `process.${which}.write("x" + i + "\\n");` : `console.${consoleFn}("x" + i);`} + await new Promise(r => process.nextTick(r)); + await new Promise(r => process.nextTick(r)); + } + process.${other}.write("[done]\\n"); + process.exit(); + });`; + }; + + async function run(which: "stdout" | "stderr", fn: "console" | "write", withListener: boolean) { + const other = which === "stdout" ? "stderr" : "stdout"; + const child = cp.spawn(bunExe(), ["-e", childBody(which, fn, withListener)], { + stdio: ["pipe", "pipe", "pipe"], + env: bunEnv, + }); + let report = ""; + child[other].on("data", d => (report += d.toString())); + child[which].destroy(); + child.stdin.end(); + const exitCode = await new Promise(r => child.on("close", code => r(code ?? -1))); + const lines = report.trim().split("\n"); + const reportLine = lines.find(l => l.startsWith("{")); + if (!reportLine || !lines.includes("[done]")) { + // Surface the child's actual output/exit instead of a JSON.parse error. + expect({ report, exitCode }).toEqual({ report: expect.stringContaining("[done]"), exitCode: 0 }); + } + const result = JSON.parse(reportLine!) as { seen: string[]; exit: number }; + expect(exitCode).toBe(result.exit); + return result; + } + + test.each([ + ["stdout", "console"], + ["stdout", "write"], + ["stderr", "console"], + ["stderr", "write"], + ] as const)("%s %s with 'error' listener: fires EPIPE per write, exit 0", async (which, fn) => { + const { seen, exit } = await run(which, fn, true); + // One 'error' event per write that hit the dead pipe. The first one or two + // may land before the kernel notices the reader is gone, so require at + // least 2 (out of 4) rather than exactly 4. + expect(seen.length).toBeGreaterThanOrEqual(2); + for (const e of seen) expect(e).toBe("EPIPE:write:-32"); + expect(exit).toBe(0); + }); + + test("console.log without 'error' listener: failure is swallowed", async () => { + // Node's createWriteErrorHandler adds a noop 'error' listener so a + // console.log to a dead pipe doesn't crash (test-process-external-stdio-close). + const { seen, exit } = await run("stdout", "console", false); + expect(seen).toEqual([]); + expect(exit).toBe(0); + }); + + test("process.stdout.write without 'error' listener: one uncaughtException EPIPE", async () => { + const { seen, exit } = await run("stdout", "write", false); + // emitErrorNT's one-shot guard stays latched once nobody is listening, so + // exactly one uncaughtException is delivered for the whole sequence (not + // one per write). The test's uncaughtException handler swallows it, hence + // exit 0. + expect(seen).toEqual(["uncaught:EPIPE"]); + expect(exit).toBe(0); + }); + + test("console.log | head with listener can break the loop (#7251)", async () => { + const child = cp.spawn( + bunExe(), + [ + "-e", + `process.stdout.on("error", e => { process.stderr.write("handler:" + e.code + "\\n"); process.exit(0); }); + (function go() { console.log("line"); setImmediate(go); })();`, + ], + { stdio: ["ignore", "pipe", "pipe"], env: bunEnv }, + ); + let stderr = ""; + child.stderr.on("data", d => (stderr += d.toString())); + child.stdout.once("data", () => child.stdout.destroy()); + const exitCode = await new Promise(r => child.on("close", code => r(code ?? -1))); + expect(stderr).toContain("handler:EPIPE"); + expect(exitCode).toBe(0); + }); +}); diff --git a/test/js/node/process/process-stdout-write-after-end.test.ts b/test/js/node/process/process-stdout-write-after-end.test.ts index 32ceb8f1cc7c..599bec6a04b2 100644 --- a/test/js/node/process/process-stdout-write-after-end.test.ts +++ b/test/js/node/process/process-stdout-write-after-end.test.ts @@ -24,9 +24,13 @@ test.concurrent.each(["stdout", "stderr"] as const)( const lines = reportPipe.trim().split("\n"); const report = JSON.parse(lines[lines.length - 1]); + // Node's pipe stdio is a net.Socket with autoDestroy:true, so end() runs + // finish -> destroy -> _undestroy, which resets writableEnded/writable. + // The write-after-end contract (ret=false, ERR_STREAM_WRITE_AFTER_END, + // bytes not delivered) is enforced at write() time, before that reset. expect(report).toEqual({ - writableEnded: true, - writable: false, + writableEnded: false, + writable: true, ret: false, cbErr: "ERR_STREAM_WRITE_AFTER_END", ev: ["err:ERR_STREAM_WRITE_AFTER_END"],