Skip to content
Open
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
113 changes: 105 additions & 8 deletions d3d12/crates/leonida-loader/src/crash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,13 @@ pub fn log_crashes_to(file: std::path::PathBuf) {
}

/// Appends a failure that is not an exception (the host GPU's) to the crash
/// log, with the title's last debug output, and prints it.
/// log, with the title's last debug output, and prints it without panicking
/// if stderr fails (e.g. a closed pipe at shutdown).
pub fn log_crash(text: &str) {
let text = format!("{text}
{}", title_output());
eprint!("{text}");
use std::io::Write as _;
let text = format!("{text}\n{}", title_output());
append_to_log(&text);
let _ = write!(std::io::stderr(), "{text}");
}

fn append_to_log(text: &str) {
Expand Down Expand Up @@ -582,10 +583,14 @@ unsafe fn report(what: &str, info: *const EXCEPTION_POINTERS, to_file: bool) {
String::new()
};
// Printed line by line (a fault while unwinding must not lose the
// lines before it), and kept for the file.
// lines before it), and kept for the file. Never use `eprint!`/`eprintln!`
// here: `report` runs inside `extern "system"` exception handlers, where a
// panic on a closed stderr pipe would abort before the crash log and any
// saved memory ranges are written.
use std::io::Write as _;
let mut text = String::new();
let mut line = |l: String| {
eprintln!("{l}");
let _ = writeln!(std::io::stderr(), "{l}");
text.push_str(&l);
text.push('\n');
};
Expand Down Expand Up @@ -621,16 +626,17 @@ unsafe fn report(what: &str, info: *const EXCEPTION_POINTERS, to_file: bool) {
}
if to_file {
let said = title_output();
eprint!("{said}");
text.push_str(&said);
append_to_log(&text);
let _ = write!(std::io::stderr(), "{said}");
}
#[cfg(feature = "diagnostics")]
for (address, len, file) in SAVE.get().into_iter().flatten() {
// SAFETY: the caller of `save_on_crash` named readable memory.
let bytes = unsafe { std::slice::from_raw_parts(*address as *const u8, *len) };
let saved = std::fs::write(file, bytes);
eprintln!(
let _ = writeln!(
std::io::stderr(),
" saved {address:#x}+{len:#x} to {} ({saved:?})",
file.display()
);
Expand Down Expand Up @@ -1451,4 +1457,95 @@ mod tests {
VirtualFree(page.cast(), 0, MEM_RELEASE);
}
}

#[test]
fn log_crash_and_report_unhandled_write_files_when_stderr_pipe_is_closed() {
use std::io::Write as _;
use std::path::PathBuf;
const CHILD_DIR_ENV: &str = "CRASH_CLOSED_STDERR_DIR";
if let Some(dir) = std::env::var_os(CHILD_DIR_ENV) {
let mut buf = [0u8; 1];
let _ = std::io::Read::read(&mut std::io::stdin(), &mut buf);
assert!(
writeln!(std::io::stderr(), "probe").is_err(),
"expected writing to a closed stderr pipe to fail"
);
let dir = PathBuf::from(dir);
log_crashes_to(dir.join("crashes.log"));
note_title_output("closed-pipe title line");
log_crash("closed-pipe gpu loss");

#[cfg(feature = "diagnostics")]
let payload_a: &'static [u8] = b"crash-dump-a";
#[cfg(feature = "diagnostics")]
let payload_b: &'static [u8] = b"crash-dump-b";
#[cfg(feature = "diagnostics")]
save_on_crash(vec![
(payload_a.as_ptr() as usize, payload_a.len(), dir.join("dump-a.bin")),
(payload_b.as_ptr() as usize, payload_b.len(), dir.join("dump-b.bin")),
]);

// SAFETY: zeroed EXCEPTION_RECORD and CONTEXT with Rsp = 0 (unwind
// stops immediately after pushing Rip) and ExceptionAddress in our
// own code image.
let mut record: EXCEPTION_RECORD = unsafe { std::mem::zeroed() };
record.ExceptionCode = EXCEPTION_BREAKPOINT;
record.ExceptionAddress = report_unhandled as *const () as *mut std::ffi::c_void;
let mut context = Aligned16(unsafe { std::mem::zeroed() });
context.0.Rip = report_unhandled as *const () as usize as u64;
let info = EXCEPTION_POINTERS {
ExceptionRecord: &raw mut record,
ContextRecord: &raw mut context.0,
};
// SAFETY: valid EXCEPTION_POINTERS built above.
unsafe { report_unhandled(&raw const info) };
return;
}

struct TempDir(PathBuf);
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos());
let dir = TempDir(std::env::temp_dir().join(format!(
"leonida-crash-closed-stderr-{}-{nanos}",
std::process::id(),
)));
std::fs::create_dir_all(&dir.0).expect("create temp dir");
let exe = std::env::current_exe().expect("current test executable");
let mut child = std::process::Command::new(exe)
.env(CHILD_DIR_ENV, &dir.0)
.args([
"--exact",
"crash::tests::log_crash_and_report_unhandled_write_files_when_stderr_pipe_is_closed",
"--nocapture",
])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("spawn closed-stderr child");
drop(child.stderr.take());
drop(child.stdin.take());
let output = child.wait_with_output().expect("wait for child");
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("1 passed"),
"crash reporting failed on closed stderr (status={:?}, stdout={stdout})",
output.status,
);
let written = std::fs::read_to_string(dir.0.join("crashes.log")).expect("crashes.log");
assert!(written.contains("closed-pipe gpu loss"), "{written:?}");
assert!(written.contains("closed-pipe title line"), "{written:?}");
assert!(written.contains("unhandled exception 0x80000003"), "{written:?}");
#[cfg(feature = "diagnostics")]
{
assert_eq!(std::fs::read(dir.0.join("dump-a.bin")).expect("dump-a.bin"), b"crash-dump-a");
assert_eq!(std::fs::read(dir.0.join("dump-b.bin")).expect("dump-b.bin"), b"crash-dump-b");
}
}
}
Loading