Skip to content
Open
Show file tree
Hide file tree
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
73 changes: 67 additions & 6 deletions d3d12/apps/leonida/src/game_actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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");
}
}

Expand Down Expand Up @@ -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:?}");
}
}
52 changes: 51 additions & 1 deletion d3d12/apps/leonida/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand All @@ -346,6 +346,16 @@ 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, 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}");
}

/// Debugging aid: `LEONIDA_POKE=<rva>:<byte>,...` (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
Expand Down Expand Up @@ -594,6 +604,46 @@ mod tests {
let expected_ok = true;
assert_eq!(super::check_cpu_features().is_ok(), expected_ok);
}

#[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)]
Expand Down
Loading