From 8dc385505733ad8ab33cf7160195ec589d5c48c7 Mon Sep 17 00:00:00 2001 From: bobcatchris <83428450+bobcatchris@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:28:00 -0600 Subject: [PATCH 1/2] d3d12: avoid stderr panic in game_actions and watch (D3D12-GAME-ACTIONS-AND-WATCH-NO-STDERR-PANIC) --- d3d12/apps/leonida/src/game_actions.rs | 73 +++++++++++++++++++++++--- d3d12/apps/leonida/src/run.rs | 52 +++++++++++++++++- 2 files changed, 118 insertions(+), 7 deletions(-) diff --git a/d3d12/apps/leonida/src/game_actions.rs b/d3d12/apps/leonida/src/game_actions.rs index 8f675218d7..0ad52f1c23 100644 --- a/d3d12/apps/leonida/src/game_actions.rs +++ b/d3d12/apps/leonida/src/game_actions.rs @@ -25,7 +25,7 @@ use std::collections::VecDeque; use std::panic::{AssertUnwindSafe, catch_unwind}; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, Ordering}; use std::sync::{Mutex, OnceLock}; use std::time::Duration; @@ -389,15 +389,21 @@ fn out_dir() -> PathBuf { std::env::temp_dir().join("leonida-actions") } -/// A line for the console and the log file. +/// A line for the console and the log file. Writes the file sink first and +/// does NOT use `eprintln!`, which panics if stderr fails (e.g. a closed pipe +/// at shutdown, from the title frame hook or the `leonida-game-actions` +/// thread); failed stderr writes are silently dropped. fn log(line: &str) { + log_to(&out_dir(), line); +} + +fn log_to(dir: &Path, line: &str) { use std::io::Write as _; - eprintln!("Leonida: game actions: {line}"); - let dir = out_dir(); - let _ = std::fs::create_dir_all(&dir); + let _ = std::fs::create_dir_all(dir); if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("log.txt")) { let _ = writeln!(file, "{line}"); } + let _ = writeln!(std::io::stderr(), "Leonida: game actions: {line}"); } fn thread_id() -> u64 { @@ -960,7 +966,7 @@ unsafe extern "win64" fn deferred(_ticket: *mut u32) { // SAFETY: this is the deferred call, on the title's thread. if catch_unwind(AssertUnwindSafe(|| unsafe { game.work() })).is_err() { BROKEN.store(true, Ordering::Relaxed); - eprintln!("Leonida: game actions: the runtime's work in the title failed; nothing more is done there"); + log("the runtime's work in the title failed; nothing more is done there"); } } @@ -1440,4 +1446,59 @@ mod tests { assert_eq!(storage[0], 0x1122_3344); assert!(available("player.wanted").is_none() || on()); } + + #[test] + fn log_writes_file_and_does_not_panic_when_stderr_pipe_is_closed() { + use std::io::Write as _; + const CHILD_DIR_ENV: &str = "GAME_ACTIONS_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_to(&dir, "closed-pipe line 1"); + log_to(&dir, "closed-pipe line 2"); + 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-game-actions-closed-stderr-{}-{nanos}", + std::process::id(), + ))); + 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", + "game_actions::tests::log_writes_file_and_does_not_panic_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"), + "game_actions::log failed on closed stderr (status={:?}, stdout={stdout})", + output.status, + ); + let written = std::fs::read_to_string(dir.0.join("log.txt")).expect("log.txt"); + assert!(written.contains("closed-pipe line 1") && written.contains("closed-pipe line 2"), "{written:?}"); + } } diff --git a/d3d12/apps/leonida/src/run.rs b/d3d12/apps/leonida/src/run.rs index 45f7e36389..c17882fcd7 100644 --- a/d3d12/apps/leonida/src/run.rs +++ b/d3d12/apps/leonida/src/run.rs @@ -337,7 +337,7 @@ fn watch(base: usize, size: usize) { // SAFETY: four bytes inside the mapped image, checked above. let value = unsafe { ((base + rva) as *const u32).read_volatile() }; if *seen != Some(value) { - eprintln!("Leonida: title+{rva:#x} = {value:#x}"); + report_watch(rva, value); *seen = Some(value); } } @@ -346,6 +346,15 @@ fn watch(base: usize, size: usize) { }); } +/// Writes a watched-value change to stderr without panicking if stderr fails +/// (e.g. a closed pipe at shutdown on this detached polling thread); failed +/// writes are silently dropped. +#[cfg(all(windows, feature = "diagnostics"))] +fn report_watch(rva: usize, value: u32) { + use std::io::Write as _; + let _ = writeln!(std::io::stderr(), "Leonida: title+{rva:#x} = {value:#x}"); +} + /// Debugging aid: `LEONIDA_POKE=:,...` (hex) writes the byte at /// each title+rva twice a second. A title that ends itself when its main /// loop has not ticked for a while (Grand Theft Auto VI: 30 s) runs on @@ -594,6 +603,47 @@ mod tests { let expected_ok = true; assert_eq!(super::check_cpu_features().is_ok(), expected_ok); } + + #[cfg(feature = "diagnostics")] + #[test] + fn watch_report_does_not_panic_when_stderr_pipe_is_closed() { + use std::io::Write as _; + const CHILD_ENV: &str = "RUN_WATCH_CLOSED_STDERR_TEST"; + if std::env::var_os(CHILD_ENV).is_some() { + 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" + ); + for value in 0..3 { + super::report_watch(0x1234, value); + } + return; + } + let exe = std::env::current_exe().expect("current test executable"); + let mut child = std::process::Command::new(exe) + .env(CHILD_ENV, "1") + .args([ + "--exact", + "run::tests::watch_report_does_not_panic_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"), + "run::report_watch failed on closed stderr (status={:?}, stdout={stdout})", + output.status, + ); + } } #[cfg(test)] From d2c08c14ff896462f52df6b2447471cf904e19aa Mon Sep 17 00:00:00 2001 From: bobcatchris <83428450+bobcatchris@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:25:28 -0600 Subject: [PATCH 2/2] d3d12: run watch closed-stderr test in default workspace test build --- d3d12/apps/leonida/src/run.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/d3d12/apps/leonida/src/run.rs b/d3d12/apps/leonida/src/run.rs index c17882fcd7..dd7e18a784 100644 --- a/d3d12/apps/leonida/src/run.rs +++ b/d3d12/apps/leonida/src/run.rs @@ -349,7 +349,8 @@ fn watch(base: usize, size: usize) { /// Writes a watched-value change to stderr without panicking if stderr fails /// (e.g. a closed pipe at shutdown on this detached polling thread); failed /// writes are silently dropped. -#[cfg(all(windows, feature = "diagnostics"))] +#[cfg(all(windows, any(feature = "diagnostics", test)))] +#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] fn report_watch(rva: usize, value: u32) { use std::io::Write as _; let _ = writeln!(std::io::stderr(), "Leonida: title+{rva:#x} = {value:#x}"); @@ -604,7 +605,6 @@ mod tests { assert_eq!(super::check_cpu_features().is_ok(), expected_ok); } - #[cfg(feature = "diagnostics")] #[test] fn watch_report_does_not_panic_when_stderr_pipe_is_closed() { use std::io::Write as _;