Skip to main content

tilo_rt/
panic_boundary.rs

1//! Which panics a process survives.
2//!
3//! Release builds unwind, but a Tilo process still ends on the first panic: on
4//! starting a runtime or a thread through this crate, it installs a hook that aborts
5//! once every earlier hook (a crash log) has run, so code keeps the abort-on-panic
6//! contract it is written against and a task's panic is never swallowed by its
7//! runtime.
8//!
9//! The one exception is a thread inside [`isolate`], where the panic unwinds to the
10//! boundary and the helper's owner decides what happens next — the compositor
11//! isolates its helpers this way. Debug and test builds keep unwinding everywhere;
12//! under `panic = "abort"` [`isolate`] only runs its body.
13//!
14//! The abort writes its own backtrace, captured at the panic, rather than leaving
15//! it to std's hook: that one prints only what `RUST_BACKTRACE` asks for, and its
16//! short form prints no frames at all in a build without a symbol table (every
17//! development build is stripped). A process that ends says where it ended,
18//! whatever the environment and the symbol table are.
19
20use std::cell::Cell;
21use std::panic::{AssertUnwindSafe, catch_unwind};
22use std::sync::Once;
23
24/// Abort the process on any panic outside [`isolate`], after the hooks
25/// installed before this one (which it calls first) have reported it.
26/// Idempotent; a hook installed later should chain to this one.
27pub 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                // The earlier hooks may have written to a capture the abort
35                // discards, as a test harness's is: say on the process's own
36                // stderr what ended it, and where, so no abort goes unexplained.
37                // The backtrace is captured here and printed in full: std's hook
38                // answers to `RUST_BACKTRACE`, and its short form names no frame
39                // at all when the symbol table is stripped, which is every
40                // development build's.
41                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
65/// Run `body` as a panic boundary: a panic inside it (on this thread)
66/// unwinds to here and is returned as `Err` with its payload, and
67/// [`is_isolated`] answers `true` meanwhile so the process's panic hook lets
68/// it unwind.
69///
70/// `body` must leave nothing half-updated that outlives it, or whoever
71/// reads that state afterwards must tolerate it (poisoned locks read as
72/// unavailable, a dropped channel as closed).
73pub 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/// Whether the calling thread is inside [`isolate`]: a panic hook that
86/// aborts the process for any other panic returns for this one.
87#[must_use]
88pub fn is_isolated() -> bool {
89    DEPTH.with(|depth| depth.get() > 0)
90}
91
92/// The panic message in `payload`, for a log line.
93#[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    /// The step the child panics in: a function of its own, so the frame the abort prints is
132    /// named with a word this test wrote rather than a closure's mangled one.
133    #[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        // The abort is the outcome under test, not a crash to debug: it must
144        // not leave a core file in the directory the tests run in.
145        #[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            // SAFETY: `setrlimit` only reads the limit it is handed.
152            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                // The hook prints the backtrace whether or not a variable asks
183                // for one: without either, std's own hook prints no frames, so
184                // every frame the child says is the abort's own.
185                .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        // A process that ends says where: the backtrace the hook captured names
198        // the step that panicked.
199        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}