tilo_rt/
panic_boundary.rs1use std::cell::Cell;
21use std::panic::{AssertUnwindSafe, catch_unwind};
22use std::sync::Once;
23
24pub fn abort_outside_boundaries() {
28 static INSTALLED: Once = Once::new();
29 INSTALLED.call_once(|| {
30 let earlier = std::panic::take_hook();
31 std::panic::set_hook(Box::new(move |info| {
32 earlier(info);
33 if !is_isolated() {
34 let backtrace = std::backtrace::Backtrace::force_capture();
42 let _ = std::io::Write::write_fmt(
43 &mut std::io::stderr().lock(),
44 format_args!(
45 "{info}\nbacktrace:\n{backtrace:#}\n\
46 aborting: the panic above happened outside a panic boundary\n"
47 ),
48 );
49 std::process::abort();
50 }
51 }));
52 });
53}
54
55pub(crate) fn abort_outside_boundaries_in_release() {
56 if cfg!(all(panic = "unwind", not(debug_assertions))) {
57 abort_outside_boundaries();
58 }
59}
60
61thread_local! {
62 static DEPTH: Cell<usize> = const { Cell::new(0) };
63}
64
65pub fn isolate<R>(body: impl FnOnce() -> R) -> std::thread::Result<R> {
74 struct Entered;
75 impl Drop for Entered {
76 fn drop(&mut self) {
77 DEPTH.with(|depth| depth.set(depth.get().saturating_sub(1)));
78 }
79 }
80 DEPTH.with(|depth| depth.set(depth.get().saturating_add(1)));
81 let _entered = Entered;
82 catch_unwind(AssertUnwindSafe(body))
83}
84
85#[must_use]
88pub fn is_isolated() -> bool {
89 DEPTH.with(|depth| depth.get() > 0)
90}
91
92#[must_use]
94pub fn message(payload: &(dyn std::any::Any + Send)) -> &str {
95 payload
96 .downcast_ref::<&str>()
97 .copied()
98 .or_else(|| payload.downcast_ref::<String>().map(String::as_str))
99 .unwrap_or("<non-text panic payload>")
100}
101
102#[cfg(test)]
103mod tests {
104 use super::*;
105 use tilo_test_env::SpawnUnderEnvLock as _;
106
107 #[test]
108 fn a_panic_inside_the_boundary_returns_and_the_marker_follows_the_scope() {
109 assert!(!is_isolated());
110 let inner = isolate(|| {
111 assert!(is_isolated());
112 let nested = isolate(|| panic!("helper failed"));
113 let payload = nested.expect_err("the nested panic is caught");
114 assert_eq!(message(payload.as_ref()), "helper failed");
115 assert!(is_isolated(), "the outer boundary still holds");
116 7
117 });
118 assert_eq!(inner.expect("the outer body returned"), 7);
119 assert!(!is_isolated());
120
121 let formatted = isolate(|| panic!("{} failed", "broker"));
122 assert_eq!(
123 message(formatted.expect_err("caught").as_ref()),
124 "broker failed"
125 );
126 assert!(!is_isolated(), "an unwound boundary is left");
127 }
128
129 const FIXTURE: &str = "TILO_RT_PANIC_BOUNDARY_FIXTURE";
130
131 #[inline(never)]
134 fn a_step_that_ends_the_process() {
135 panic!("worker failed");
136 }
137
138 #[test]
139 fn panic_boundary_fixture() {
140 let Ok(scenario) = std::env::var(FIXTURE) else {
141 return;
142 };
143 #[cfg(any(target_os = "linux", target_vendor = "apple"))]
146 {
147 let no_core = libc::rlimit {
148 rlim_cur: 0,
149 rlim_max: 0,
150 };
151 assert_eq!(
153 unsafe { libc::setrlimit(libc::RLIMIT_CORE, &raw const no_core) },
154 0
155 );
156 }
157 abort_outside_boundaries();
158 if scenario == "isolated" {
159 let helper =
160 crate::spawn_thread("helper", || isolate(|| panic!("helper failed")).is_err())
161 .expect("helper thread");
162 assert!(helper.join().expect("the helper thread returned"));
163 } else {
164 let _ = crate::spawn_thread("worker", a_step_that_ends_the_process)
165 .expect("worker thread")
166 .join();
167 }
168 println!("process survived");
169 }
170
171 #[test]
172 fn only_a_panic_inside_a_boundary_leaves_the_process_running() {
173 let run = |scenario: &str| {
174 std::process::Command::new(std::env::current_exe().expect("test binary"))
175 .args([
176 "--exact",
177 "panic_boundary::tests::panic_boundary_fixture",
178 "--nocapture",
179 "--test-threads=1",
180 ])
181 .env(FIXTURE, scenario)
182 .env_remove("RUST_BACKTRACE")
186 .env_remove("RUST_LIB_BACKTRACE")
187 .output_locked()
188 .expect("fixture child")
189 };
190 let isolated = run("isolated");
191 assert!(isolated.status.success(), "{isolated:?}");
192 assert!(String::from_utf8_lossy(&isolated.stdout).contains("process survived"));
193
194 let outside = run("outside");
195 assert!(!outside.status.success(), "{outside:?}");
196 assert!(!String::from_utf8_lossy(&outside.stdout).contains("process survived"));
197 let said = String::from_utf8_lossy(&outside.stderr);
200 assert!(said.contains("backtrace:"), "{said}");
201 assert!(said.contains("a_step_that_ends_the_process"), "{said}");
202 #[cfg(unix)]
203 {
204 use std::os::unix::process::ExitStatusExt as _;
205 assert_eq!(outside.status.signal(), Some(libc_sigabrt()), "{outside:?}");
206 }
207 }
208
209 #[cfg(unix)]
210 const fn libc_sigabrt() -> i32 {
211 6
212 }
213}