Sub topic 12
Keeping panics out of C
This chapter assumes you know how Rust panics work, how to pass a callback to C (the previous chapter), and that extern "C" functions use the C ABI. It covers why a panic must not cross into C and how to stop it.
Why unwinding across C is a problem
A panic normally unwinds the stack. Rust runs destructors frame by frame until something catches the panic or the thread ends. C frames have no unwind information that Rust understands. If a panic leaves a Rust function and enters a C frame, the program's behavior is not defined by the C ABI.
Current Rust handles this for you in the common case. A function declared extern "C" aborts the process if a panic tries to escape it. This is defined behavior, but it is probably not what you want from a library. An abort kills the whole program with no chance to clean up or report an error.
The variant extern "C-unwind" allows unwinding across the boundary. Use it only when the C side is built to propagate unwinding, for example C++ code or C compiled with unwind tables. A plain C library almost never is.
The usual approach is to catch the panic inside the callback and turn it into a status code that C already understands.
Catching the panic
std::panic::catch_unwind runs a closure and returns Err if it panicked. Wrap the entire body of every Rust function that C can call.
use std::ffi::{c_int, c_void};
use std::panic::{catch_unwind, AssertUnwindSafe};
extern "C" fn on_item(value: c_int, user_data: *mut c_void) -> c_int {
let result = catch_unwind(AssertUnwindSafe(|| {
let sum = unsafe { &mut *(user_data as *mut i64) };
*sum += i64::from(value);
}));
if result.is_ok() { 0 } else { -1 }
}Three details matter here.
- The closure holds a raw pointer, which is not
UnwindSafe.AssertUnwindSafetells the compiler you accept that. You are promising that no code will later observe broken state left behind by the panic. - The callback now returns
c_int. The C side must agree to treat0as success and nonzero as failure, and it must stop iterating when it sees a failure. If C ignores the return value, you have hidden the panic without handling it. catch_unwindonly catches unwinding panics. If the crate is built withpanic = "abort", a panic ends the process before any catch runs. This is acceptable, but you should know which mode you are in.
Keeping the failure visible
A status code tells C that something went wrong, but it loses the panic message. Two options keep more information.
- Store a flag or the payload in your user data, so the Rust code that started the C call can inspect it afterward.
- Resume the panic on the Rust side once control returns from C, using
std::panic::resume_unwind.
The second option means the panic crosses only Rust frames, which is safe.
use std::ffi::{c_int, c_void};
use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe};
struct State {
sum: i64,
panic: Option<Box<dyn std::any::Any + Send>>,
}
extern "C" fn on_item(value: c_int, user_data: *mut c_void) -> c_int {
let state = unsafe { &mut *(user_data as *mut State) };
if state.panic.is_some() {
return -1;
}
match catch_unwind(AssertUnwindSafe(|| {
state.sum += i64::from(value);
})) {
Ok(()) => 0,
Err(payload) => {
state.panic = Some(payload);
-1
}
}
}
fn finish(state: State) -> i64 {
if let Some(payload) = state.panic {
resume_unwind(payload);
}
state.sum
}After the C iterator returns, a wrapper calls finish. If the callback panicked, the panic resumes there, in Rust code, as if the C call had never been in the way.
Common mistakes
| Mistake | Result |
|---|---|
| Letting a panic leave a plain `extern "C"` function | The process aborts |
| Using `extern "C-unwind"` with a C library that cannot unwind | Undefined behavior |
| Catching the panic but returning success | C continues with half-finished work |
| Panicking inside `Drop` while already unwinding | The process aborts |
| Assuming `catch_unwind` works with `panic = "abort"` | The process ends without a catch |
Exercise
A Rust callback registered with a C library is declared extern "C" and contains data.unwrap(). What happens if data is None, and how would you change the callback so that the C code can respond to the failure?
Show answer
The unwrap panics, and because the function is extern "C" the panic cannot escape it, so the process aborts. To let C respond, wrap the body in catch_unwind(AssertUnwindSafe(|| ...)), return a status code such as -1 when it returns Err, and make sure the C code checks that return value and stops. Optionally store the payload in the user data and call resume_unwind after the C call returns.
Exercise
When is extern "C-unwind" the right choice instead of catch_unwind?
Show answer
When the C or C++ side is built to let unwinding pass through its frames, and you want a panic to propagate through it to a Rust caller, or an exception to propagate into Rust. For a plain C library that has no unwind support, catch the panic and return a status code.