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
134 changes: 124 additions & 10 deletions d3d12/apps/leonida/src/warm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
//! processes of their own: a compiler that crashes or hangs costs one pipeline.

use std::collections::HashSet;
use std::io::{BufRead, BufReader, Write};
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::process::{Child, Command, Stdio};
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::{Duration, Instant};
Expand Down Expand Up @@ -329,8 +329,12 @@ fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
}

/// Has a process make `these`; how many it made, and how it ended if not well.
fn child(these: &[usize], store: Option<&Path>, mut each: impl FnMut(usize, f64, bool)) -> (usize, Option<String>) {
// (The store's list is in a file: thousands of numbers do not fit a command line.)
fn child(
these: &[usize],
store: Option<&Path>,
mut each: impl FnMut(usize, f64, bool),
) -> (usize, Option<String>) {
// (The stores list is in a file: thousands of numbers do not fit a command line.)
let list = match store {
Some(file) => format!("@{}", file.display()),
None => these.iter().map(usize::to_string).collect::<Vec<_>>().join(","),
Expand All @@ -346,19 +350,67 @@ fn child(these: &[usize], store: Option<&Path>, mut each: impl FnMut(usize, f64,
// (The store is one process the launcher waits for: not idle.)
command.creation_flags(IDLE_PRIORITY_CLASS);
}
command.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn()
// Piped and read, not discarded: a stack overflow shows on the childs stderr and
// that is what this reports; a null stderr would leave collect_child with nothing.
command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
});
let Ok(mut process) = spawned else { return (these.len(), None) };
let Some(out) = process.stdout.take() else { return (these.len(), None) };
let Ok(process) = spawned else {
return (these.len(), None);
};
collect_child(process, these.len(), LONGEST, each)
}

fn collect_child(
mut process: Child,
total: usize,
quiet_limit: Duration,
mut each: impl FnMut(usize, f64, bool),
) -> (usize, Option<String>) {
let (Some(out), Some(err)) = (process.stdout.take(), process.stderr.take()) else {
return (total, None);
};
let process = Mutex::new(process);
let (heard, over) = (Mutex::new(Instant::now()), AtomicBool::new(false));
let hung = AtomicBool::new(false);
let stack_overflow = AtomicBool::new(false);
let mut made = 0;
std::thread::scope(|s| {
s.spawn(|| {
let mut err = BufReader::new(err);
let mut line = Vec::new();
// Wine can leave a process alive after its Rust thread hit the stack guard.
// Drain stderr without saving driver output or treating it as progress.
const MAX_DIAGNOSTIC: u64 = 4096;
loop {
line.clear();
let read = err.by_ref().take(MAX_DIAGNOSTIC).read_until(b'\n', &mut line);
if !read.is_ok_and(|n| n != 0) {
break;
}
if line.len() as u64 == MAX_DIAGNOSTIC && !line.ends_with(b"\n") {
if err.skip_until(b'\n').is_err() {
break;
}
continue;
}
let diagnostic = line.trim_ascii();
if diagnostic.starts_with(b"thread '")
&& diagnostic.ends_with(b" has overflowed its stack")
{
stack_overflow.store(true, Ordering::Relaxed);
let _ = lock(&process).kill();
return;
}
}
});
s.spawn(|| {
while !over.load(Ordering::Relaxed) {
std::thread::sleep(Duration::from_millis(500));
if lock(&heard).elapsed() > LONGEST {
if lock(&heard).elapsed() > quiet_limit {
hung.store(true, Ordering::Relaxed);
let _ = lock(&process).kill();
return;
Expand All @@ -379,12 +431,15 @@ fn child(these: &[usize], store: Option<&Path>, mut each: impl FnMut(usize, f64,
over.store(true, Ordering::Relaxed);
});
let status = lock(&process).wait();
if stack_overflow.load(Ordering::Relaxed) {
return (made, Some("compiler process stack overflow".into()));
}
let well = status.as_ref().is_ok_and(|s| s.success());
if well {
return (these.len(), None);
return (total, None);
}
let why = if hung.load(Ordering::Relaxed) {
format!("hung for {} s", LONGEST.as_secs())
format!("hung for {} s", quiet_limit.as_secs())
} else {
status.map_or_else(|e| e.to_string(), |s| format!("{s}"))
};
Expand All @@ -411,3 +466,62 @@ fn make(dir: &Path, these: &str) -> Result<()> {
let _ = out.flush();
std::process::exit(0)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn warm_child_fixture() {
let Ok(mode) = std::env::var("LEONIDA_TEST_WARM_CHILD") else {
return;
};
println!("\nmade 7 2.00 1");
println!("at 8");
std::io::stdout().flush().unwrap();
if mode == "overflow" {
std::io::stderr().write_all(&[b'x'; 8192]).unwrap();
eprintln!();
eprintln!("thread 'main' (36) has overflowed its stack");
}
// Simulate a process whose remaining threads stay alive after the diagnostic.
loop {
std::thread::park();
}
}

fn run_fixture(mode: &str, quiet_limit: Duration) -> (usize, Option<String>) {
let process = Command::new(std::env::current_exe().unwrap())
.args(["--exact", "warm::tests::warm_child_fixture", "--nocapture"])
.env("LEONIDA_TEST_WARM_CHILD", mode)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let mut reported = Vec::new();
let result = collect_child(process, 2, quiet_limit, |n, ms, there| {
reported.push((n, ms, there));
});
assert_eq!(reported, [(7, 2.0, true)]);
result
}

#[test]
fn reports_stack_overflow_before_waiting_for_the_timeout() {
let quiet_limit = Duration::from_secs(8);
let started = Instant::now();
assert_eq!(
run_fixture("overflow", quiet_limit),
(1, Some("compiler process stack overflow".into()))
);
assert!(started.elapsed() < quiet_limit, "the watchdog had to stop the child");
}

#[test]
fn silent_child_still_times_out() {
assert_eq!(
run_fixture("quiet", Duration::from_secs(2)),
(1, Some("hung for 2 s".into()))
);
}
}