rust / expert
Snippet
Intercepting Panic Unwinding for Safe Boundaries
In Rust, panics cause stack unwinding unless configured to abort. Using catch_unwind, we can catch panics at FFI boundaries or thread roots, preventing the process from crashing. AssertUnwindSafe is used to declare that the captured environment won't break logic invariants if a panic occurs.
snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use std::panic::{catch_unwind, AssertUnwindSafe};fn run_untrusted_code<F: FnOnce()>(f: F) -> Result<(), &'static str> {let result = catch_unwind(AssertUnwindSafe(f));match result {Ok(_) => Ok(()),Err(_) => Err("Untrusted execution panicked!"),}}fn main() {let res = run_untrusted_code(|| {panic!("Oops!");});assert!(res.is_err());}
Breakdown
1
catch_unwind(AssertUnwindSafe(f))
Executes the closure and catches any panic that occurs during execution, wrapping the result in a Result.
2
AssertUnwindSafe(f)
Asserts that the closure is safe to unwind, bypassing the compiler's default, conservative UnwindSafe checks.