use std::cell::Cell;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Once;
pub fn abort_outside_boundaries() {
static INSTALLED: Once = Once::new();
INSTALLED.call_once(|| {
let earlier = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
earlier(info);
if !is_isolated() {
let backtrace = std::backtrace::Backtrace::force_capture();
let _ = std::io::Write::write_fmt(
&mut std::io::stderr().lock(),
format_args!(
"{info}\nbacktrace:\n{backtrace:#}\n\
aborting: the panic above happened outside a panic boundary\n"
),
);
std::process::abort();
}
}));
});
}
pub(crate) fn abort_outside_boundaries_in_release() {
if cfg!(all(panic = "unwind", not(debug_assertions))) {
abort_outside_boundaries();
}
}
thread_local! {
static DEPTH: Cell<usize> = const { Cell::new(0) };
}
pub fn isolate<R>(body: impl FnOnce() -> R) -> std::thread::Result<R> {
struct Entered;
impl Drop for Entered {
fn drop(&mut self) {
DEPTH.with(|depth| depth.set(depth.get().saturating_sub(1)));
}
}
DEPTH.with(|depth| depth.set(depth.get().saturating_add(1)));
let _entered = Entered;
catch_unwind(AssertUnwindSafe(body))
}
#[must_use]
pub fn is_isolated() -> bool {
DEPTH.with(|depth| depth.get() > 0)
}
#[must_use]
pub fn message(payload: &(dyn std::any::Any + Send)) -> &str {
payload
.downcast_ref::<&str>()
.copied()
.or_else(|| payload.downcast_ref::<String>().map(String::as_str))
.unwrap_or("<non-text panic payload>")
}
#[cfg(test)]
mod tests {
use super::*;
use tilo_test_env::SpawnUnderEnvLock as _;
#[test]
fn a_panic_inside_the_boundary_returns_and_the_marker_follows_the_scope() {
assert!(!is_isolated());
let inner = isolate(|| {
assert!(is_isolated());
let nested = isolate(|| panic!("helper failed"));
let payload = nested.expect_err("the nested panic is caught");
assert_eq!(message(payload.as_ref()), "helper failed");
assert!(is_isolated(), "the outer boundary still holds");
7
});
assert_eq!(inner.expect("the outer body returned"), 7);
assert!(!is_isolated());
let formatted = isolate(|| panic!("{} failed", "broker"));
assert_eq!(
message(formatted.expect_err("caught").as_ref()),
"broker failed"
);
assert!(!is_isolated(), "an unwound boundary is left");
}
const FIXTURE: &str = "TILO_RT_PANIC_BOUNDARY_FIXTURE";
#[inline(never)]
fn a_step_that_ends_the_process() {
panic!("worker failed");
}
#[test]
fn panic_boundary_fixture() {
let Ok(scenario) = std::env::var(FIXTURE) else {
return;
};
#[cfg(any(target_os = "linux", target_vendor = "apple"))]
{
let no_core = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
assert_eq!(
unsafe { libc::setrlimit(libc::RLIMIT_CORE, &raw const no_core) },
0
);
}
abort_outside_boundaries();
if scenario == "isolated" {
let helper =
crate::spawn_thread("helper", || isolate(|| panic!("helper failed")).is_err())
.expect("helper thread");
assert!(helper.join().expect("the helper thread returned"));
} else {
let _ = crate::spawn_thread("worker", a_step_that_ends_the_process)
.expect("worker thread")
.join();
}
println!("process survived");
}
#[test]
fn only_a_panic_inside_a_boundary_leaves_the_process_running() {
let run = |scenario: &str| {
std::process::Command::new(std::env::current_exe().expect("test binary"))
.args([
"--exact",
"panic_boundary::tests::panic_boundary_fixture",
"--nocapture",
"--test-threads=1",
])
.env(FIXTURE, scenario)
.env_remove("RUST_BACKTRACE")
.env_remove("RUST_LIB_BACKTRACE")
.output_locked()
.expect("fixture child")
};
let isolated = run("isolated");
assert!(isolated.status.success(), "{isolated:?}");
assert!(String::from_utf8_lossy(&isolated.stdout).contains("process survived"));
let outside = run("outside");
assert!(!outside.status.success(), "{outside:?}");
assert!(!String::from_utf8_lossy(&outside.stdout).contains("process survived"));
let said = String::from_utf8_lossy(&outside.stderr);
assert!(said.contains("backtrace:"), "{said}");
assert!(said.contains("a_step_that_ends_the_process"), "{said}");
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt as _;
assert_eq!(outside.status.signal(), Some(libc_sigabrt()), "{outside:?}");
}
}
#[cfg(unix)]
const fn libc_sigabrt() -> i32 {
6
}
}