Sub topic 12
Keeping panics out of C
This chapter assumes you have read the earlier chapters on extern "C" declarations, callbacks, and status codes. You should also know what a panic is in Rust (panic!, unwrap on None, integer overflow in debug builds, out-of-bounds indexing) and that the default behavior is to unwind the stack and run destructors.
Why a panic is a problem at the boundary
C has no concept of Rust's unwinding. When a panic starts, the Rust runtime walks up the call stack, running Drop implementations until it finds a catch_unwind or reaches the top of the thread. If the stack contains a C frame, that walk has to pass through code that has no unwind information and no destructors, and possibly no cooperation from the compiler.
Rust handles this in two ways, depending on the function's ABI string:
extern "C"functions are assumed not to unwind. Since Rust 1.81, if a panic tries to leave anextern "C"function, the runtime prints a message and aborts the process. Before 1.81 this was undefined behavior.extern "C-unwind"functions are allowed to unwind across the boundary. Use this only when the other side also supports unwinding (for example C++ code that expects to propagate exceptions, or C compiled with-fexceptions).
An abort is safer than undefined behavior, but it still kills the whole process. A C host such as a database, an editor plugin, or a game engine would rather get an error code. So the rule for Rust code that C can call is: a panic must never escape an extern "C" function. Catch it, convert it to a status the C caller understands, and return normally.
The basic pattern: catch_unwind
std::panic::catch_unwind runs a closure and returns Result<T, Box<dyn Any + Send>>. It returns Ok with the closure's value if the closure finishes, and Err with the panic payload if it panics.
The closure must be UnwindSafe. This marker trait warns you that a panic could leave data half-updated and visible to code that runs afterward. Mutable references are not UnwindSafe, so a closure that captures &mut i64 will not compile. AssertUnwindSafe is a wrapper that tells the compiler you have thought about it. Use it deliberately, not by reflex (see the gotchas below).
Here is the callback from the previous chapter with a guard added. It is a complete program, so you can run it without a C library by calling the callback directly:
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 = sum
.checked_add(i64::from(value))
.expect("sum overflowed");
}));
if result.is_ok() { 0 } else { -1 }
}
fn main() {
let mut sum: i64 = 0;
let p = &mut sum as *mut i64 as *mut c_void;
println!("first call returned {}", on_item(5, p));
println!("sum is {sum}");
sum = i64::MAX;
let p = &mut sum as *mut i64 as *mut c_void;
println!("second call returned {}", on_item(1, p));
}The first call returns 0. The second call panics inside the closure because the addition overflows, catch_unwind intercepts it, and the function returns -1. The default panic hook still prints the message to stderr, so you will see sum overflowed in the output. That message is useful for debugging, and it does not mean the panic escaped.
A real C API usually documents what the callback's return value means (for example, "nonzero stops the iteration"). Pick the code that fits that contract.
A reusable guard
If you export several functions to C, writing catch_unwind in each one invites mistakes. A small helper keeps the pattern in one place:
use std::ffi::c_int;
use std::panic::{catch_unwind, AssertUnwindSafe};
const OK: c_int = 0;
const ERR_PANIC: c_int = -1;
fn guard<F: FnOnce() -> c_int>(f: F) -> c_int {
match catch_unwind(AssertUnwindSafe(f)) {
Ok(code) => code,
Err(_) => ERR_PANIC,
}
}
#[unsafe(no_mangle)]
pub extern "C" fn rust_add_checked(a: c_int, b: c_int, out: *mut c_int) -> c_int {
guard(|| {
if out.is_null() {
return -2;
}
let sum = a.checked_add(b).expect("overflow in rust_add_checked");
unsafe { *out = sum };
OK
})
}
fn main() {
let mut out = 0;
println!("{}", rust_add_checked(2, 3, &mut out));
println!("{}", rust_add_checked(i32::MAX, 1, &mut out));
}Two things are worth noting. The function is exported with #[unsafe(no_mangle)] so C can find it by its plain name. The null check returns a distinct code (-2) so the C caller can tell "you passed a bad pointer" from "Rust panicked."
Gotchas
catch_unwind does not work with panic = "abort"
If your crate is built with panic = "abort" in the Cargo profile, a panic aborts immediately. There is nothing to catch, and catch_unwind always returns Ok for code that finishes. For a library that C programs load, this is sometimes the right choice, because it makes the failure behavior simple and predictable. Decide on purpose, and document it. If you rely on catch_unwind for error reporting, do not set panic = "abort".
Not all failures are panics
catch_unwind catches only Rust panics. It does not catch these:
- A stack overflow, which aborts the process.
- Running out of memory, which usually aborts.
- A segmentation fault from a bad pointer in
unsafecode. - A C++ exception or a
longjmppassing through Rust frames.
The last item is a real hazard. If C code calls your Rust callback, and your callback calls back into C code that does longjmp over Rust frames, the Rust destructors in between never run. Avoid designs where non-local jumps cross Rust frames.
The panic payload can itself panic
When catch_unwind returns Err(payload), the payload is a Box<dyn Any + Send> holding arbitrary user data. If that payload's Drop panics, you get a second panic with no handler, and Rust aborts. In the examples above, Err(_) drops the payload right away, which is fine for typical &str and String payloads. If you need to inspect the payload, do so carefully and do not run complicated code on it.
Be honest about AssertUnwindSafe
AssertUnwindSafe silences a compiler check. In the callback above, a panic after a partial update could leave *sum in a state the C caller later reads. Here that is harmless: checked_add either completes the update or panics before it. In larger functions, consider whether a panic halfway through leaves your data consistent. Prefer to do fallible work first, and update shared state last.
Do not hold locks across the boundary
If a callback panics while holding a Mutex, the mutex becomes poisoned. After you return an error to C, later calls that lock the same mutex will see PoisonError. Handle that case explicitly, or keep lock scopes small and inside the guarded closure.
Avoid allocation-free tricks that skip the guard
Some code sets a global flag in a custom panic hook and relies on the hook alone. A hook runs before unwinding starts but does not stop the unwind. It is a place to log, not a replacement for catch_unwind.
Reporting the panic to the caller
Returning -1 loses information. You have a few options for passing more:
- Distinct status codes. Reserve a code such as
ERR_PANICand document it in your C header. - A last-error function. Store a message in a
thread_local!and exportconst char *mylib_last_error(void), the wayerrnoandGetLastErrorwork. Keep the storedCStringalive until the next call so the pointer stays valid. - A flag in the user data. For callbacks, put a
panicked: boolin the struct you pass asuser_data. After the C iterator returns, your safe wrapper checks the flag and can callstd::panic::resume_unwindto re-raise the original panic in Rust code, which is allowed to unwind.
Option 3 is the cleanest for callbacks that are driven from Rust. The C library only ever sees a status code, and the Rust caller sees the same panic it would have seen in pure Rust. Store the payload in the user data, return a "stop" code to C, and call resume_unwind(payload) once control is back in Rust.
When to use "C-unwind"
extern "C-unwind" exists for the case where unwinding across the language boundary is intended. The usual example is Rust called from C++ that has try/catch, or Rust that calls into a C++ library that throws and expects Rust code up the stack to handle it. Both sides must agree on the unwinding mechanism, and you have to build and test that combination.
For plain C libraries, extern "C" plus a guard is almost always the right choice. A C library has no way to handle a Rust panic, so there is nothing to gain from letting it propagate.
Checklist
- Every
extern "C"function that C can call has its body insidecatch_unwind, or provably cannot panic. - The panic result is converted to a documented status code.
- No lock, borrow, or half-built state is left inconsistent when a panic is caught.
- The crate's
panicsetting matches the strategy:unwindif you catch,abortif you accept termination. unwrap,expect, indexing, and arithmetic inside callbacks are replaced with checked operations where practical, so panics are rare.
Exercise
A Rust library built with the default profile exports extern "C" fn process(p: *const u8, len: usize) -> c_int. Its body indexes a slice with slice[len], which can panic. With Rust 1.81 or later and no catch_unwind, what happens when C passes a bad length, and what should you change?
Show answer
The panic tries to unwind out of an extern "C" function, so the runtime aborts the whole process. To fix it, wrap the body in catch_unwind(AssertUnwindSafe(...)) and return a documented error code on Err. Better still, use slice.get(len) or validate len first so the panic does not happen at all.
Exercise
Why does catch_unwind fail to catch panics when the crate sets panic = "abort" in its Cargo profile?
Show answer
With panic = "abort", a panic terminates the process immediately instead of unwinding the stack. No unwinding means no point where catch_unwind can intercept it. If you want to convert panics into error codes, keep the default panic = "unwind".