1use std::process::{Command, ExitStatus, Output};
32
33pub use crate::child::KILLED_RUNS;
34
35pub const OVERFLOW_REPORT: &str = "has overflowed its stack";
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub enum Probe {
41 Fits,
43 Overflows,
45}
46
47pub fn classify(status: ExitStatus, stdout: &[u8], stderr: &[u8]) -> Result<Probe, String> {
53 let out = String::from_utf8_lossy(stdout);
54 let err = String::from_utf8_lossy(stderr);
55 let tail = || format!("\n--- stdout\n{}\n--- stderr\n{}", last(&out), last(&err));
56 if status.success() {
57 return if out.contains("test result: ok. 1 passed;") {
58 Ok(Probe::Fits)
59 } else {
60 Err(format!("the probe did not run (no test matched){}", tail()))
61 };
62 }
63 let reported = err.contains(OVERFLOW_REPORT);
64 match (signal(status), status.code()) {
65 (Some(ABORT), _) if reported => Ok(Probe::Overflows),
66 (Some(ABORT), _) => Err(format!(
67 "the probe aborted with no stack overflow reported (an allocation that failed \
68 prints \"memory allocation of N bytes failed\"){}",
69 tail()
70 )),
71 (Some(KILL), _) => Err(format!(
72 "the probe was killed (SIGKILL: the OOM killer, or a person){}",
73 tail()
74 )),
75 (Some(s), _) => Err(format!(
76 "the probe died of signal {s}, with{} a stack overflow reported{}",
77 if reported { "" } else { "out" },
78 tail()
79 )),
80 (None, Some(101)) => Err(format!("the probe panicked{}", tail())),
81 (None, code) => Err(format!("the probe exited with {code:?}{}", tail())),
82 }
83}
84
85const ABORT: i32 = 6;
86const KILL: i32 = 9;
87
88#[cfg(unix)]
89fn signal(status: ExitStatus) -> Option<i32> {
90 std::os::unix::process::ExitStatusExt::signal(&status)
91}
92
93#[cfg(not(unix))]
94fn signal(_: ExitStatus) -> Option<i32> {
95 None
96}
97
98fn last(text: &str) -> String {
100 crate::child::tail(text.as_bytes())
101}
102
103#[track_caller]
113#[must_use]
114pub fn run(probe: &str, var: &str, value: &str) -> Probe {
115 let exe = std::env::current_exe().expect("the test binary's path");
116 let Output {
117 status,
118 stdout,
119 stderr,
120 } = crate::child::output(
121 Command::new(exe)
122 .args(["--exact", probe, "--ignored", "--test-threads=1"])
123 .env(var, value),
124 )
125 .unwrap_or_else(|e| panic!("cannot start probe {probe}: {e}"));
126 classify(status, &stdout, &stderr)
127 .unwrap_or_else(|e| panic!("probe {probe} with {var}={value:?}: {e}"))
128}
129
130#[track_caller]
136#[must_use]
137pub fn fits(probe: &str, var: &str, value: &str) -> bool {
138 run(probe, var, value) == Probe::Fits
139}
140
141#[track_caller]
147pub fn least(hi: usize, what: &str, mut fits: impl FnMut(usize) -> bool) -> usize {
148 assert!(fits(hi), "{what} overflows {hi} bytes");
149 let (mut lo, mut hi) = (0, hi);
150 while hi - lo > 4 << 10 {
151 let mid = usize::midpoint(lo, hi) / 4096 * 4096;
152 if fits(mid) {
153 hi = mid;
154 } else {
155 lo = mid;
156 }
157 }
158 hi
159}
160
161#[cfg(test)]
162mod tests {
163 use super::{Probe, classify, least, run};
164 use crate::child::Marks;
165
166 const VAR: &str = "UNITYRS_TESTKIT_STACK_PROBE";
167
168 #[test]
174 #[ignore = "run by the stack probe tests"]
175 fn probe() {
176 let Ok(what) = std::env::var(VAR) else {
177 return;
178 };
179 if let Some(spec) = what.strip_prefix("killed:") {
180 crate::child::kill_self_while(spec);
181 }
182 let t = std::thread::Builder::new().stack_size(256 << 10);
183 t.spawn(move || match what.as_str() {
184 "recurse" => {
185 std::hint::black_box(recurse(0));
186 }
187 "panic" => panic!("the probe's own panic"),
188 "alloc" => {
189 std::alloc::handle_alloc_error(
190 std::alloc::Layout::from_size_align(1 << 40, 8).unwrap(),
191 );
192 }
193 _ => {}
194 })
195 .unwrap()
196 .join()
197 .unwrap();
198 }
199
200 fn recurse(n: u64) -> u64 {
201 if std::hint::black_box(n) == u64::MAX {
202 return 0;
203 }
204 let pad = std::hint::black_box([n; 64]);
205 recurse(n + 1).wrapping_add(pad[0])
206 }
207
208 const PROBE: &str = "stack::tests::probe";
209
210 fn refused(what: &str) -> String {
211 let r = std::panic::catch_unwind(|| run(PROBE, VAR, what));
212 let p = r.expect_err(what);
213 p.downcast_ref::<String>().cloned().unwrap_or_default()
214 }
215
216 #[test]
218 fn a_pass_fits_and_a_stack_overflow_overflows() {
219 assert_eq!(run(PROBE, VAR, "pass"), Probe::Fits);
220 assert_eq!(run(PROBE, VAR, "recurse"), Probe::Overflows);
221 }
222
223 #[test]
227 fn every_other_failure_is_no_measurement() {
228 let m = refused("panic");
229 assert!(m.contains("the probe panicked"), "{m}");
230 assert!(m.contains("the probe's own panic"), "{m}");
231 let m = refused("alloc");
232 assert!(m.contains("aborted with no stack overflow reported"), "{m}");
233 assert!(m.contains("memory allocation of"), "{m}");
234 let r = std::panic::catch_unwind(|| run("stack::tests::no_such_probe", VAR, "pass"));
235 let m = r.expect_err("no such probe");
236 let m = m.downcast_ref::<String>().cloned().unwrap_or_default();
237 assert!(m.contains("the probe did not run"), "{m}");
238 }
239
240 #[cfg(unix)]
244 #[test]
245 fn only_an_abort_with_the_overflow_report_is_an_overflow() {
246 use std::os::unix::process::ExitStatusExt;
247 let report =
248 b"\nthread 'w' has overflowed its stack\nfatal runtime error: stack overflow\n";
249 let of = |raw: i32, err: &[u8]| classify(ExitStatusExt::from_raw(raw), b"", err);
250 assert_eq!(of(6, report), Ok(Probe::Overflows));
251 assert!(
252 of(6, b"")
253 .unwrap_err()
254 .contains("no stack overflow reported")
255 );
256 assert!(of(9, report).unwrap_err().contains("SIGKILL"));
257 assert!(of(11, b"").unwrap_err().contains("signal 11"));
258 assert!(of(101 << 8, report).unwrap_err().contains("panicked"));
259 assert!(of(0, b"").unwrap_err().contains("did not run"));
260 let passed = b"test result: ok. 1 passed; 0 failed; 0 ignored";
261 assert_eq!(
262 classify(ExitStatusExt::from_raw(0), passed, b""),
263 Ok(Probe::Fits)
264 );
265 }
266
267 #[cfg(unix)]
271 #[test]
272 fn a_child_killed_from_outside_is_run_again() {
273 let marks = Marks::new("stack-again");
274 let spec = format!("killed:{}:{}", super::KILLED_RUNS - 1, marks.0.display());
275 assert_eq!(run(PROBE, VAR, &spec), Probe::Fits);
276 assert_eq!(
277 marks.runs(),
278 usize::try_from(super::KILLED_RUNS - 1).unwrap()
279 );
280 }
281
282 #[cfg(unix)]
284 #[test]
285 fn a_child_killed_on_every_run_fails_saying_so() {
286 let marks = Marks::new("stack-always");
287 let spec = format!("killed:{}:{}", super::KILLED_RUNS, marks.0.display());
288 let m = refused(&spec);
289 assert_eq!(marks.runs(), usize::try_from(super::KILLED_RUNS).unwrap());
290 let want = format!(
291 "killed by SIGKILL on each of its {} runs",
292 super::KILLED_RUNS
293 );
294 assert!(m.contains(&want), "{m}");
295 assert!(m.contains("the OOM killer"), "{m}");
296 }
297
298 #[test]
300 fn least_bisects_to_four_kib() {
301 let need = 1_234_567;
302 let got = least(8 << 20, "a model", |s| s >= need);
303 assert!(got >= need && got - need < 4 << 10, "{got}");
304 }
305}