Skip to content
Closed
Show file tree
Hide file tree
Changes from 7 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
126 changes: 47 additions & 79 deletions src/runtime/shell/IOWriter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -762,11 +762,8 @@ impl IOWriter {
if !not_fully_written {
return;
}
// Other end of the socket/pipe closed and we got EPIPE
// (e.g. `ls | echo`). Quick hack: have all writers see an
// error.
s.flags.broken_pipe = true;
self.broken_pipe_for_writers();
// The other end closed (e.g. `ls | echo`): every queued chunk fails with EPIPE.
self.fail_pending_writers(&sys::Error::from_code(E::EPIPE, sys::Tag::write), None);
return;
}
if s.writers[idx].written >= s.writers[idx].len {
Expand Down Expand Up @@ -794,41 +791,10 @@ impl IOWriter {
}
}

fn broken_pipe_for_writers(&self) {
let s = self.state();
debug_assert!(s.flags.broken_pipe);
// NOTE: reshaped for borrowck — collect targets first so we don't
// hold `&mut s.writers` across `cancel_chunks`/`run_yield`.
let mut targets: Vec<ChildPtr> = Vec::new();
for w in &s.writers[s.writer_idx..] {
if w.is_dead() {
continue;
}
if !targets.contains(&w.ptr) {
targets.push(w.ptr);
}
}
for ptr in targets {
let err = sys::Error::from_code(E::EPIPE, sys::Tag::write).to_system_error();
self.run_yield(Yield::OnIoWriterChunk {
child: ptr,
written: 0,
err: Some(err),
});
self.cancel_chunks(ptr);
}
let s = self.state();
s.total_bytes_written = 0;
s.writers.clear();
s.buf.clear();
s.writer_idx = 0;
}

/// Shared failure bookkeeping: mark broken pipes, reset the queue, and
/// return the still-pending children that have to be told their chunk
/// failed. The queue is reset *before* any of them runs so that a child
/// re-enqueueing from its callback is not wiped afterwards.
fn fail_pending_writers(&self, err: &sys::Error) -> Vec<ChildPtr> {
/// Fails every chunk still queued, oldest first, each with its own error completion.
fn fail_pending_writers(&self, err: &sys::Error, withhold: Option<ChildPtr>) -> Option<Yield> {
// A completion may drop the last external `Arc` to this writer.
let _keepalive = self.keepalive();
self.set_writing(false);
let s = self.state();
if err.get_errno() == E::EPIPE {
Expand All @@ -839,41 +805,60 @@ impl IOWriter {
// must be rejected by `handle_dead_writer`, not queued onto a writer
// whose handle the error path is tearing down.
s.err = Some(err.clone());
crate::shell_log!(
"IOWriter(fd={}) failing {} queued chunk(s): {:?}",
s.fd,
s.writers.len().saturating_sub(s.writer_idx),
err.get_errno()
);
// Writers before writer_idx have already had their callback fired and
// may have been freed; only notify the still-pending ones, dedup'd.
let mut pending: Vec<ChildPtr> = Vec::new();
for w in &s.writers[s.writer_idx..] {
if !w.is_dead() && !pending.contains(&w.ptr) {
pending.push(w.ptr);
// may have been freed; only notify the still-pending ones.
let mut idx = s.writer_idx;
let mut withheld: Option<usize> = None;
// Re-derived every iteration: a callback may `cancel_chunks` the entries behind it.
while let Some(w) = self.state().writers.get(idx) {
let (dead, child, this_idx) = (w.is_dead(), w.ptr, idx);
idx += 1;
if dead {
continue;
}
// `withhold`'s `enqueue` is on the stack: its first live chunk is returned, not run.
if withheld.is_none() && withhold == Some(child) {
withheld = Some(this_idx);
continue;
}
// `SystemError` is not `Clone`: each completion derives its own.
self.run_yield(Yield::OnIoWriterChunk {
child,
written: 0,
err: Some(err.to_shell_system_error()),
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
let withheld = withheld
.and_then(|i| self.state().writers.get(i))
.filter(|w| !w.is_dead())
.map(|w| Yield::OnIoWriterChunk {
child: w.ptr,
written: 0,
err: Some(err.to_shell_system_error()),
});
let s = self.state();
s.total_bytes_written = 0;
s.writer_idx = 0;
s.buf.clear();
s.writers.clear();
pending
withheld
}

/// Write failure reported by the `bun_io` writer callbacks. Each pending
/// child's error completion is driven through its own `Yield::run`; on
/// chunk's error completion is driven through its own `Yield::run`; on
/// POSIX these callbacks only fire from the event loop, with no trampoline
/// on the stack. On Windows uv can also deliver a synchronous submission
/// failure from under `write()` (`start_with_current_pipe` returns `Ok`
/// unconditionally), a re-entry `write()` cannot turn into a
/// `WriteOutcome::Failed`.
fn on_error(&self, err: &sys::Error) {
let _keepalive = self.keepalive();
for ptr in self.fail_pending_writers(err) {
// `SystemError` owns `bun_core::String`s by value (no shared
// refcount yet), so re-derive a fresh one per callee instead of
// cloning the stored error.
let ee = err.to_shell_system_error();
self.run_yield(Yield::OnIoWriterChunk {
child: ptr,
written: 0,
err: Some(ee),
});
}
self.fail_pending_writers(err, None);
}

/// Synchronous write failure while `child`'s `enqueue` call (and therefore
Expand All @@ -886,26 +871,9 @@ impl IOWriter {
/// re-registration fails while other children are still queued, those are
/// dispatched the way the async path dispatches them.
fn on_sync_error(&self, child: ChildPtr, err: &sys::Error) -> Yield {
let _keepalive = self.keepalive();
let mut completion = None;
for ptr in self.fail_pending_writers(err) {
// `SystemError` owns `bun_core::String`s by value (no shared
// refcount yet), so re-derive a fresh one per callee.
let y = Yield::OnIoWriterChunk {
child: ptr,
written: 0,
err: Some(err.to_shell_system_error()),
};
if completion.is_none() && ptr == child {
completion = Some(y);
} else {
self.run_yield(y);
}
}
// The writer `enqueue` just pushed for `child` is live and at or past
// `writer_idx`, so it is always in the pending list.
debug_assert!(completion.is_some());
completion.unwrap_or_else(Yield::done)
// `None`: an inline completion made `child` cancel its chunks, so it has finished.
self.fail_pending_writers(err, Some(child))
.unwrap_or_else(Yield::done)
}

fn on_close(&self) {
Expand Down
13 changes: 9 additions & 4 deletions src/runtime/shell/builtin/cat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ impl Cat {
tag: ReaderTag::Cat,
};
// Writing to stdout errored: cancel everything and finish.
Self::cancel_stdout_chunks(interp, cmd);
Comment thread
robobun marked this conversation as resolved.
Resolved
// Pull the reader `Arc` out of
// state before calling `remove_reader`, then drop it.
match &mut Self::state_mut(interp, cmd).state {
Expand Down Expand Up @@ -395,13 +396,17 @@ impl Cat {
CatState::WaitingWriteErr | CatState::Idle => Step::Suspend,
};
if cancel {
let wchild = ChildPtr::new(cmd, WriterTag::Builtin);
if let BuiltinIO::Fd(fd) = &Builtin::of(interp, cmd).stdout {
fd.writer.cancel_chunks(wchild);
}
Self::cancel_stdout_chunks(interp, cmd);
}
Comment thread
robobun marked this conversation as resolved.
Resolved
step.run(interp, cmd)
}

fn cancel_stdout_chunks(interp: &Interpreter, cmd: NodeId) {
if let BuiltinIO::Fd(fd) = &Builtin::of(interp, cmd).stdout {
fd.writer
.cancel_chunks(ChildPtr::new(cmd, WriterTag::Builtin));
}
}
}

#[derive(Clone, Copy, Default)]
Expand Down
15 changes: 11 additions & 4 deletions src/runtime/shell/subproc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1599,14 +1599,16 @@ impl CapturedWriter {
.writer
.clone()
.expect("CapturedWriter live without writer");
// The CapturedWriter lives outside the NodeId arena (embedded in a
// heap-allocated PipeReader), so dispatch is by raw pointer — see
// `io_writer::ChildPtr::subproc_capture` / `WriterTag::Subproc`.
let child = io_writer::ChildPtr::subproc_capture(std::ptr::from_mut(self).cast::<c_void>());
let child = self.child_ptr();
let y = writer.enqueue(child, None, chunk);
self.parent().run_yield(y);
}

/// This writer's identity on the IOWriter queue, see `ChildPtr::subproc_capture`.
fn child_ptr(&mut self) -> io_writer::ChildPtr {
io_writer::ChildPtr::subproc_capture(std::ptr::from_mut(self).cast::<c_void>())
}

pub(crate) fn on_iowriter_chunk(&mut self, amount: usize, err: Option<SystemError>) -> Yield {
let addr = std::ptr::from_mut(self) as usize;
let written = self.written + amount;
Expand Down Expand Up @@ -1634,6 +1636,11 @@ impl CapturedWriter {
e.syscall
);
self.err = Some(e);
// The chunks still queued must not call back: the Cmd below can free this PipeReader.
let child = self.child_ptr();
if let Some(writer) = &self.writer {
writer.cancel_chunks(child);
}
} else if !all_written {
return Yield::Suspended;
}
Expand Down
37 changes: 37 additions & 0 deletions test/js/bun/shell/epipe-fixture.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading