use std::process::{Command, ExitStatus, Output};
pub use crate::child::KILLED_RUNS;
pub const OVERFLOW_REPORT: &str = "has overflowed its stack";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Probe {
Fits,
Overflows,
}
pub fn classify(status: ExitStatus, stdout: &[u8], stderr: &[u8]) -> Result<Probe, String> {
let out = String::from_utf8_lossy(stdout);
let err = String::from_utf8_lossy(stderr);
let tail = || format!("\n--- stdout\n{}\n--- stderr\n{}", last(&out), last(&err));
if status.success() {
return if out.contains("test result: ok. 1 passed;") {
Ok(Probe::Fits)
} else {
Err(format!("the probe did not run (no test matched){}", tail()))
};
}
let reported = err.contains(OVERFLOW_REPORT);
match (signal(status), status.code()) {
(Some(ABORT), _) if reported => Ok(Probe::Overflows),
(Some(ABORT), _) => Err(format!(
"the probe aborted with no stack overflow reported (an allocation that failed \
prints \"memory allocation of N bytes failed\"){}",
tail()
)),
(Some(KILL), _) => Err(format!(
"the probe was killed (SIGKILL: the OOM killer, or a person){}",
tail()
)),
(Some(s), _) => Err(format!(
"the probe died of signal {s}, with{} a stack overflow reported{}",
if reported { "" } else { "out" },
tail()
)),
(None, Some(101)) => Err(format!("the probe panicked{}", tail())),
(None, code) => Err(format!("the probe exited with {code:?}{}", tail())),
}
}
const ABORT: i32 = 6;
const KILL: i32 = 9;
#[cfg(unix)]
fn signal(status: ExitStatus) -> Option<i32> {
std::os::unix::process::ExitStatusExt::signal(&status)
}
#[cfg(not(unix))]
fn signal(_: ExitStatus) -> Option<i32> {
None
}
fn last(text: &str) -> String {
crate::child::tail(text.as_bytes())
}
#[track_caller]
#[must_use]
pub fn run(probe: &str, var: &str, value: &str) -> Probe {
let exe = std::env::current_exe().expect("the test binary's path");
let Output {
status,
stdout,
stderr,
} = crate::child::output(
Command::new(exe)
.args(["--exact", probe, "--ignored", "--test-threads=1"])
.env(var, value),
)
.unwrap_or_else(|e| panic!("cannot start probe {probe}: {e}"));
classify(status, &stdout, &stderr)
.unwrap_or_else(|e| panic!("probe {probe} with {var}={value:?}: {e}"))
}
#[track_caller]
#[must_use]
pub fn fits(probe: &str, var: &str, value: &str) -> bool {
run(probe, var, value) == Probe::Fits
}
#[track_caller]
pub fn least(hi: usize, what: &str, mut fits: impl FnMut(usize) -> bool) -> usize {
assert!(fits(hi), "{what} overflows {hi} bytes");
let (mut lo, mut hi) = (0, hi);
while hi - lo > 4 << 10 {
let mid = usize::midpoint(lo, hi) / 4096 * 4096;
if fits(mid) {
hi = mid;
} else {
lo = mid;
}
}
hi
}
#[cfg(test)]
mod tests {
use super::{Probe, classify, least, run};
use crate::child::Marks;
const VAR: &str = "UNITYRS_TESTKIT_STACK_PROBE";
#[test]
#[ignore = "run by the stack probe tests"]
fn probe() {
let Ok(what) = std::env::var(VAR) else {
return;
};
if let Some(spec) = what.strip_prefix("killed:") {
crate::child::kill_self_while(spec);
}
let t = std::thread::Builder::new().stack_size(256 << 10);
t.spawn(move || match what.as_str() {
"recurse" => {
std::hint::black_box(recurse(0));
}
"panic" => panic!("the probe's own panic"),
"alloc" => {
std::alloc::handle_alloc_error(
std::alloc::Layout::from_size_align(1 << 40, 8).unwrap(),
);
}
_ => {}
})
.unwrap()
.join()
.unwrap();
}
fn recurse(n: u64) -> u64 {
if std::hint::black_box(n) == u64::MAX {
return 0;
}
let pad = std::hint::black_box([n; 64]);
recurse(n + 1).wrapping_add(pad[0])
}
const PROBE: &str = "stack::tests::probe";
fn refused(what: &str) -> String {
let r = std::panic::catch_unwind(|| run(PROBE, VAR, what));
let p = r.expect_err(what);
p.downcast_ref::<String>().cloned().unwrap_or_default()
}
#[test]
fn a_pass_fits_and_a_stack_overflow_overflows() {
assert_eq!(run(PROBE, VAR, "pass"), Probe::Fits);
assert_eq!(run(PROBE, VAR, "recurse"), Probe::Overflows);
}
#[test]
fn every_other_failure_is_no_measurement() {
let m = refused("panic");
assert!(m.contains("the probe panicked"), "{m}");
assert!(m.contains("the probe's own panic"), "{m}");
let m = refused("alloc");
assert!(m.contains("aborted with no stack overflow reported"), "{m}");
assert!(m.contains("memory allocation of"), "{m}");
let r = std::panic::catch_unwind(|| run("stack::tests::no_such_probe", VAR, "pass"));
let m = r.expect_err("no such probe");
let m = m.downcast_ref::<String>().cloned().unwrap_or_default();
assert!(m.contains("the probe did not run"), "{m}");
}
#[cfg(unix)]
#[test]
fn only_an_abort_with_the_overflow_report_is_an_overflow() {
use std::os::unix::process::ExitStatusExt;
let report =
b"\nthread 'w' has overflowed its stack\nfatal runtime error: stack overflow\n";
let of = |raw: i32, err: &[u8]| classify(ExitStatusExt::from_raw(raw), b"", err);
assert_eq!(of(6, report), Ok(Probe::Overflows));
assert!(
of(6, b"")
.unwrap_err()
.contains("no stack overflow reported")
);
assert!(of(9, report).unwrap_err().contains("SIGKILL"));
assert!(of(11, b"").unwrap_err().contains("signal 11"));
assert!(of(101 << 8, report).unwrap_err().contains("panicked"));
assert!(of(0, b"").unwrap_err().contains("did not run"));
let passed = b"test result: ok. 1 passed; 0 failed; 0 ignored";
assert_eq!(
classify(ExitStatusExt::from_raw(0), passed, b""),
Ok(Probe::Fits)
);
}
#[cfg(unix)]
#[test]
fn a_child_killed_from_outside_is_run_again() {
let marks = Marks::new("stack-again");
let spec = format!("killed:{}:{}", super::KILLED_RUNS - 1, marks.0.display());
assert_eq!(run(PROBE, VAR, &spec), Probe::Fits);
assert_eq!(
marks.runs(),
usize::try_from(super::KILLED_RUNS - 1).unwrap()
);
}
#[cfg(unix)]
#[test]
fn a_child_killed_on_every_run_fails_saying_so() {
let marks = Marks::new("stack-always");
let spec = format!("killed:{}:{}", super::KILLED_RUNS, marks.0.display());
let m = refused(&spec);
assert_eq!(marks.runs(), usize::try_from(super::KILLED_RUNS).unwrap());
let want = format!(
"killed by SIGKILL on each of its {} runs",
super::KILLED_RUNS
);
assert!(m.contains(&want), "{m}");
assert!(m.contains("the OOM killer"), "{m}");
}
#[test]
fn least_bisects_to_four_kib() {
let need = 1_234_567;
let got = least(8 << 20, "a model", |s| s >= need);
assert!(got >= need && got - need < 4 << 10, "{got}");
}
}