A Rust plugin host wraps each plugin call in std::panic::catch_unwind — what does that protect against, and which failures does it not catch?
answer
- only unwinding panics
- UnwindSafe as a speed bump
- AssertUnwindSafe for captured &mut
- abort, double panic, stack overflow
- state left half-updated
basics
~20 scatch_unwind stops an unwinding panic and returns Err with the payload, so one buggy plugin does not take the host thread down. It catches nothing that aborts: panic=abort builds, a destructor panicking during unwinding, stack overflow, allocation failure.
solid answer
~40 s`catch_unwind(f)` runs `f` and returns `Ok(value)`, or `Err(Box<dyn Any + Send>)` with the payload if `f` panics by unwinding; the host can log it, disable that plugin and carry on. The closure must be `UnwindSafe`, so capturing a `&mut` or a `&RefCell` fails with E0277 ("may not be safely transferred across an unwind boundary"); wrapping it in `AssertUnwindSafe` is how you accept that the plugin may leave that state half-updated. The limits are the real answer: it only sees unwinding panics, so a `panic=abort` build, a destructor panicking during cleanup, a panic inside the hook, a stack overflow and an allocation failure all still kill the process. The hook still prints for every caught panic, and std's docs advise against using it as general try/catch. Real isolation for untrusted plugins is a separate process.
code
rust · 32 linesuse std::panic::{self, AssertUnwindSafe};
fn run_plugin(name: &str, stats: &mut Vec<String>, plugin: fn(&mut Vec<String>)) {
let result = panic::catch_unwind(AssertUnwindSafe(|| plugin(stats)));
match result {
Ok(()) => println!("{name}: ok"),
Err(payload) => {
let msg = payload
.downcast_ref::<&str>()
.copied()
.or_else(|| payload.downcast_ref::<String>().map(String::as_str))
.unwrap_or("<non-string payload>");
println!("{name}: panicked with {msg:?}, disabling it");
}
}
}
fn good(stats: &mut Vec<String>) {
stats.push("good ran".into());
}
fn bad(stats: &mut Vec<String>) {
stats.push("bad started".into()); // left behind: the panic does not roll it back
panic!("bad plugin: unexpected input");
}
fn main() {
let mut stats = Vec::new();
run_plugin("good", &mut stats, good);
run_plugin("bad", &mut stats, bad);
println!("{stats:?}");
}go deeper
Know that std::panic::catch_unwind exists, that it returns Err when the closure panics, and that it is a last resort, not normal error handling.
Explain the UnwindSafe bound, why &mut and &RefCell captures fail with E0277, and what AssertUnwindSafe does and does not promise.
List what slips past it, abort builds, panics in destructors or the hook, stack overflow, allocation failure, and design the host around half-updated state.
Decide when in-process isolation is enough and when untrusted code must move to a separate process, given what catch_unwind cannot survive.
## What catch_unwind returns `std::panic::catch_unwind` runs a closure and stops an **unwinding** panic at that call: `pub fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> std::thread::Result<R>` If the closure returns normally you get `Ok(value)`. If it panics and the panic unwinds, every destructor between the panic and this call runs, and you get `Err(payload)`, the same `Box<dyn Any + Send + 'static>` that `JoinHandle::join` hands back. Downcast it to `&str` or `String` to read the message. std adds one warning: **be careful dropping that `Err`**, because dropping the payload can itself panic. For a plugin host this is the right tool for one job: a plugin that hits a bug (an out-of-bounds index, a failed `unwrap`) should not take the host thread down with it. The host catches the panic, logs it, disables the plugin, and keeps serving the others. ## UnwindSafe and AssertUnwindSafe The `F: UnwindSafe` bound exists because a panic can leave data in a **logically** inconsistent state: half of a two-step update done, a counter bumped but the matching list not. `UnwindSafe` is an auto trait, like `Send`: a closure is unwind safe when everything it captures is. Mutable state reachable after the catch is not, so `&mut T` and `&RefCell<T>` fail the bound: `error[E0277]: the type `&mut i32` may not be safely transferred across an unwind boundary` Three facts keep this in proportion: - `UnwindSafe` is **not an unsafe trait**. std calls it a "speed bump": without `unsafe` code a panic cannot cause memory unsafety, only broken logical invariants. - `std::panic::AssertUnwindSafe(..)` wraps a closure or value and asserts the bound. It **does not repair anything**; it records that you have thought about the half-updated state. - Some shared types are unwind safe because they guard against this themselves; how a lock reports that its holder panicked is covered with mutexes and threads. So in a plugin host, wrap the call in `AssertUnwindSafe`, and treat whatever the plugin could mutate as suspect afterwards: discard it, rebuild it, or validate it. ## What it does not catch `catch_unwind` "might not catch all Rust panics", in std's words, and several fatal failures are not panics at all: | Failure inside the closure | Outcome | |---|---| | `panic!`, failed `unwrap`, index out of bounds, unwind build | `Err(payload)` | | any panic in a `-C panic=abort` build | process aborts | | a `Drop` impl panicking while an earlier panic unwinds | abort: `panic in a destructor during cleanup` | | the panic hook itself panicking | abort: `thread panicked while processing panic. aborting.` | | stack overflow | not a panic: std prints `has overflowed its stack` and aborts | | allocation failure, with std's default handler | prints `memory allocation of N bytes failed` and aborts | | a panic on a thread the closure spawned | not seen here; it surfaces through that thread's `join` | Foreign exceptions unwinding in through an FFI boundary are a separate matter, and catching one has unspecified results; that belongs with foreign function calls. ## Side effects even when it works - The **panic hook still runs** for a caught panic, before unwinding, so the default message still reaches stderr. Replace or chain the hook if the host wants its own log format. - **Unwinding is slow** compared with returning a value; Rust's implementation is optimised for the case where nothing unwinds. - std says plainly that `catch_unwind` is **not recommended as a general try/catch**. A plugin that fails on bad input should return a `Result` through the plugin interface; `catch_unwind` is the backstop for bugs. ## Designing the host 1. Wrap each plugin entry point in `catch_unwind(AssertUnwindSafe(|| ...))`. 2. On `Err`, log the payload, mark the plugin as failed, and drop or rebuild any state it could touch. 3. To pass a panic further up after logging, call `std::panic::resume_unwind(payload)`; it re-raises the panic **without calling the hook again**, and in an abort build it aborts. 4. Build the host with the unwind strategy, or none of this works. 5. For code you do not trust, run it in a **separate process**: no in-process mechanism survives an abort, a stack overflow or memory corruption by `unsafe` code.
- How does a Rust plugin host re-raise a panic it caught with catch_unwind after logging it?Pass the payload to `std::panic::resume_unwind(payload)`. It starts unwinding again with the original payload and does not call the panic hook a second time, so the message is not printed twice. Under the abort strategy it aborts instead.
- Why not wrap a Rust parser in catch_unwind and turn every panic into an Err?std recommends against `catch_unwind` as a general try/catch: `Result` is the right type for failures that happen regularly, unwinding is slow, the hook prints for every caught panic, and it is not guaranteed to catch all panics, since an abort build ignores it. Fix the parser to return errors for bad input instead.
- Does catch_unwind in Rust catch a panic on a thread that the closure spawns?No. Every thread has its own recovery point at its root. A panic on the spawned thread ends that thread and is reported by `JoinHandle::join` as `Err`; the `catch_unwind` on the original thread never sees it.
- catch_unwind is a try/catch suited to routine error handling.
- AssertUnwindSafe makes the captured state consistent again.
- catch_unwind also catches panics in a panic = abort build.
- A caught panic never prints anything to stderr.
- UnwindSafe is an unsafe trait, so breaking it is undefined behaviour.