Skip to content
37 changes: 37 additions & 0 deletions src/io/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2234,6 +2234,10 @@ pub mod closer {
pub struct Closer {
pub(crate) fd: Fd,
task: WorkPoolTask,
#[cfg(all(debug_assertions, any(target_os = "linux", target_os = "android")))]
scheduled_from: bun_core::StoredTrace,
#[cfg(all(debug_assertions, any(target_os = "linux", target_os = "android")))]
scheduled_on_tid: i64,
}

#[cfg(not(windows))]
Expand All @@ -2243,6 +2247,35 @@ pub mod closer {
unsafe impl bun_threading::work_pool::OwnedTask for Closer {
fn run(self: Box<Self>) {
use bun_sys::FdExt;
#[cfg(all(debug_assertions, any(target_os = "linux", target_os = "android")))]
{
#[allow(clippy::print_stderr)]
if let Some(err) = self.fd.close_allowing_bad_file_descriptor(None) {
if err.errno == bun_sys::E::EBADF as _ {
std::eprintln!(
"\n==================== Closer: close({}) = EBADF ====================",
self.fd.native()
);
std::eprintln!(
"this Closer was scheduled on tid {} at:",
self.scheduled_on_tid
);
bun_core::dump_stack_trace(
&self.scheduled_from.trace(),
bun_core::DumpStackTraceOptions::default(),
);
std::eprintln!(
"======================================================================\n"
);
panic!(
"Closer: fd {} was already closed when the async close ran (see report above)",
self.fd.native()
);
}
}
return;
}
#[allow(unreachable_code)]
self.fd.close();
}
}
Expand All @@ -2258,6 +2291,10 @@ pub mod closer {
node: Default::default(),
callback: <Self as bun_threading::work_pool::OwnedTask>::__callback,
},
#[cfg(all(debug_assertions, any(target_os = "linux", target_os = "android")))]
scheduled_from: bun_core::StoredTrace::capture(None),
#[cfg(all(debug_assertions, any(target_os = "linux", target_os = "android")))]
scheduled_on_tid: bun_sys::close_ledger::current_tid(),
}));
}
}
Expand Down
91 changes: 91 additions & 0 deletions src/sys/close_ledger.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
//! Debug-only (`debug_assertions`) diagnostics for double closes.
//!
//! Every successful `close(2)` issued through `bun_sys` records the calling
//! thread and a frame-pointer stack trace, keyed by fd number. When a later
//! close of the same number fails with `EBADF` (a use-after-close, or a second
//! owner closing a descriptor it does not own), the reporter prints the code
//! path that closed it first. Traces are printed as raw return addresses
//! (symbolize them against the binary with llvm-symbolizer).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

#![allow(clippy::print_stderr)]

use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};

use bun_core::{DumpStackTraceOptions, StoredTrace};

#[derive(Clone, Copy)]
struct Slot {
/// 0 = never recorded.
seq: u64,
tid: i64,
trace: StoredTrace,
}

impl Slot {
const EMPTY: Slot = Slot {
seq: 0,
tid: 0,
trace: StoredTrace::EMPTY,
};
}

const MAX_TRACKED_FD: usize = 4096;

static LEDGER: Mutex<[Slot; MAX_TRACKED_FD]> = Mutex::new([Slot::EMPTY; MAX_TRACKED_FD]);
static SEQ: AtomicU64 = AtomicU64::new(1);

pub fn current_tid() -> i64 {
// SAFETY: SYS_gettid takes no arguments and cannot fail.
unsafe { libc::syscall(libc::SYS_gettid) as i64 }
}

/// Record that `fd` was just closed successfully by the current thread.
pub fn record_closed(fd: i32) {
if fd < 0 || fd as usize >= MAX_TRACKED_FD {
return;
}
let slot = Slot {
seq: SEQ.fetch_add(1, Ordering::Relaxed),
tid: current_tid(),
trace: StoredTrace::capture(None),
};
let mut ledger = match LEDGER.lock() {
Ok(l) => l,
Err(poisoned) => poisoned.into_inner(),
};
ledger[fd as usize] = slot;
}

fn last_close(fd: i32) -> Option<Slot> {
if fd < 0 || fd as usize >= MAX_TRACKED_FD {
return None;
}
let ledger = match LEDGER.lock() {
Ok(l) => l,
Err(poisoned) => poisoned.into_inner(),
};
let slot = ledger[fd as usize];
(slot.seq != 0).then_some(slot)
}

/// Print an EBADF report for a close attempt of `fd` made by `what`: the
/// current stack, then the stack that closed `fd` last.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code

pub fn report_ebadf(what: &str, fd: i32) {
let now = StoredTrace::capture(None);
eprintln!("\n==================== close({fd}) = EBADF ({what}) ====================");

Check failure on line 75 in src/sys/close_ledger.rs

View workflow job for this annotation

GitHub Actions / cargo clippy

use of a disallowed macro `std::eprintln`
eprintln!("this close attempt is on tid {} at:", current_tid());

Check failure on line 76 in src/sys/close_ledger.rs

View workflow job for this annotation

GitHub Actions / cargo clippy

use of a disallowed macro `std::eprintln`
bun_core::dump_stack_trace(&now.trace(), DumpStackTraceOptions::default());
match last_close(fd) {
Some(slot) => {
eprintln!(

Check failure on line 80 in src/sys/close_ledger.rs

View workflow job for this annotation

GitHub Actions / cargo clippy

use of a disallowed macro `std::eprintln`
"fd {fd} was last closed successfully (close #{}) on tid {} at:",
slot.seq, slot.tid
);
bun_core::dump_stack_trace(&slot.trace.trace(), DumpStackTraceOptions::default());
}
None => eprintln!(

Check failure on line 86 in src/sys/close_ledger.rs

View workflow job for this annotation

GitHub Actions / cargo clippy

use of a disallowed macro `std::eprintln`
"fd {fd}: no successful close recorded through bun_sys (closed by C/C++ code, or never closed)"
),
}
eprintln!("======================================================================\n");

Check failure on line 90 in src/sys/close_ledger.rs

View workflow job for this annotation

GitHub Actions / cargo clippy

use of a disallowed macro `std::eprintln`
}
8 changes: 8 additions & 0 deletions src/sys/fd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,14 @@ impl FdExt for Fd {

#[cfg(debug_assertions)]
{
#[cfg(any(target_os = "linux", target_os = "android"))]
match result {
Some(ref err) if err.errno == sys::E::EBADF as _ => {
sys::close_ledger::report_ebadf("FdExt::close", self.native());
}
Some(_) => {}
None => sys::close_ledger::record_closed(self.native()),
}
if let Some(ref err) = result {
if err.errno == sys::E::EBADF as _ {
bun_core::debug_warn!(
Expand Down
10 changes: 9 additions & 1 deletion src/sys/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ pub extern crate bun_core as bun_str;
pub extern crate bun_libuv_sys;
pub mod fd;
pub use fd::{ErrorCase, FdExt, MakeLibUvOwnedError, RawFd};
#[cfg(all(debug_assertions, any(target_os = "linux", target_os = "android")))]
pub mod close_ledger;
#[path = "Error.rs"]
mod error;
pub use error::Error;
Expand Down Expand Up @@ -2009,9 +2011,15 @@ mod posix_impl {
{
return match super::linux_syscall::close(fd.native()) {
Err(e) if e == libc::EBADF => {
#[cfg(debug_assertions)]
crate::close_ledger::report_ebadf("bun_sys::close", fd.native());
Err(Error::from_code_int(libc::EBADF, Tag::close).with_fd(fd))
}
_ => Ok(()),
_ => {
#[cfg(debug_assertions)]
crate::close_ledger::record_closed(fd.native());
Ok(())
}
};
}
#[cfg(not(any(target_os = "linux", target_os = "android")))]
Expand Down
Loading