A Rust progress callback passed to a C library as an `extern "C"` function panics; what happens in Rust 1.99, and how should the wrapper prevent it?
answer
- a boundary that cannot unwind
- abort since 1.81
- catch it before the boundary
- the -unwind ABI variants
- void pointer back to a closure
basics
~20 sSince Rust 1.81 the panic aborts the whole process at the extern "C" boundary instead of unwinding into C. The wrapper's callback should run user code inside catch_unwind and return an error code to C.
solid answer
~50 sAn `extern "C"` function is a boundary that may not unwind. When a panic reaches it, Rust 1.81 and later abort the process with `panic in a function that cannot unwind`, instead of the undefined behaviour of letting the unwind run through C frames. So a progress callback that panics takes down the host program. The wrapper fixes this in its **trampoline**, the `extern "C" fn` it registers with C: it casts the `void *ctx` back to the user's closure, calls it inside `std::panic::catch_unwind`, and turns `Err` into the library's "stop" return code. `extern "C-unwind"` (stable since 1.71) is the other option, but only when the frames in between are built to unwind, such as C++ compiled with exceptions, and Rust catches the panic further up. Under `panic = "abort"` nothing unwinds at all and `catch_unwind` catches nothing.
code
rust · 23 linesuse std::ffi::{c_int, c_void};
unsafe extern "C" {
// libc's qsort calls `compar` from C frames.
fn qsort(base: *mut c_void, n: usize, size: usize,
compar: extern "C" fn(*const c_void, *const c_void) -> c_int);
}
extern "C" fn by_value(a: *const c_void, b: *const c_void) -> c_int {
// SAFETY: qsort passes pointers to two elements of the i32 array below.
let (a, b) = unsafe { (*a.cast::<i32>(), *b.cast::<i32>()) };
if a < 0 || b < 0 {
panic!("negative key");
}
a.cmp(&b) as c_int
}
fn main() {
let mut keys = [3, 1, -2];
// SAFETY: base, n and size describe `keys` exactly.
unsafe { qsort(keys.as_mut_ptr().cast(), keys.len(), size_of::<i32>(), by_value) };
println!("{keys:?}");
}go deeper
Recall that a panic must not cross into C: on current Rust it aborts the process at an extern "C" boundary.
Explain the trampoline with a void pointer context, and catch_unwind turning a panic into an error code that C understands.
Lay out the matrix: abort for C since 1.81, C-unwind only when both sides unwind, undefined behaviour for foreign exceptions through C, nothing caught under panic = abort. Re-raise with resume_unwind after returning.
Set the rule for every exported or callback function: panic-free or wrapped in catch_unwind, and C-unwind only where the foreign side is built for it, checked in review.
## The setup: callbacks with a context pointer C libraries report progress or ask for data through **callbacks**: a function pointer plus an opaque `void *ctx` that the library hands back on every call. A typical header: ```c typedef int (*kz_progress_fn)(void *ctx, size_t done, size_t total); int kz_compress(..., kz_progress_fn progress, void *ctx); ``` A Rust closure cannot be passed as `kz_progress_fn` directly. A capturing closure has no C ABI and does not coerce to an `extern "C" fn` pointer. The standard pattern is a generic **trampoline**: 1. Write `extern "C" fn trampoline<F: FnMut(usize, usize) -> bool>(ctx: *mut c_void, done: usize, total: usize) -> c_int`. Each closure type `F` gets its own monomorphised C-ABI function. 2. Pass `trampoline::<F>` as the function pointer, and a pointer to the closure, `(&raw mut f).cast::<c_void>()`, as `ctx`. 3. Inside the trampoline, cast `ctx` back to `*mut F` and call it. The closure must outlive every call the library makes. A stack closure is fine when the library calls back only *during* `kz_compress`. If the library keeps the callback after returning, box the closure and free it when the callback is unregistered. In the Rust declaration, the nullable C function pointer becomes `Option<extern "C" fn(...)>`, because Rust function pointers are never null and `None` is passed as null. ## What a panic does at the boundary Unwinding is how a Rust panic normally travels. It walks back up the stack, running destructors, until something catches it or the thread ends. C frames have no idea how to take part, so an `extern "C"` function is defined as a boundary that **cannot unwind**: | Situation | Behaviour on Rust 1.99 | |---|---| | A Rust panic reaches an `extern "C"` function's boundary | the process **aborts**: `panic in a function that cannot unwind` (since Rust 1.81; earlier it was undefined behaviour) | | A panic reaches an `extern "C-unwind"` boundary | it **unwinds** through the foreign frames (since Rust 1.71) | | A C++ exception enters Rust through a function declared `"C"` | **undefined behaviour**, per the Reference | | A `C-unwind` function unwinds into code that cannot unwind, such as C built with `-fno-exceptions` | **undefined behaviour**, per the Reference | | The crate is built with `panic = "abort"` | every panic aborts immediately, whatever the ABI | The abort is *safe*, since no memory is corrupted, but for a library it is a terrible outcome: a bug in a progress bar kills the host process, and the host's own cleanup never runs. rustc 1.99 prints the original panic message, then `panic in a function that cannot unwind`, then `thread caused non-unwinding panic. aborting.` ## The fix: catch inside the trampoline ```rust match catch_unwind(AssertUnwindSafe(|| f(done, total))) { Ok(true) => 0, Ok(false) | Err(_) => 1, } ``` - `std::panic::catch_unwind` stops an **unwinding** panic and returns `Err(payload)`. The trampoline converts it into the library's "abort the operation" code, so C cleans up normally and returns an error to Rust. - `AssertUnwindSafe` is needed because a `&mut F` capture is not `UnwindSafe`. The assertion is honest here, since the closure is not used again after a panic. The wrapper can store the payload and call `std::panic::resume_unwind` once control is back in Rust, so the caller sees the original panic. - The panic hook still runs first, so the message is printed or logged. `catch_unwind` has documented limits. It does nothing when panics abort (`panic = "abort"`), and catching a *foreign* exception with it either aborts or returns an opaque `Err`, and which one happens is unspecified. ## When C-unwind is the right tool `"C-unwind"`, with `"system-unwind"` and other `-unwind` variants, exists for code that *wants* unwinding to cross the boundary: - Rust calling C++ that may throw, declared in an `unsafe extern "C-unwind"` block, so the exception can unwind through Rust frames. - A Rust callback called by C++ code compiled with exceptions, where the panic should unwind through the C++ frames, running their destructors, to a `catch_unwind` in an outer Rust caller. It is wrong for an ordinary C library. The Reference makes unwinding into code that does not support it undefined behaviour, so switching a callback to `C-unwind` to "avoid the abort" swaps a safe crash for undefined behaviour. ## What reviewers look for 1. Every `extern "C"` function that runs user or fallible Rust code wraps it in `catch_unwind`, or is provably panic-free. 2. The `ctx` pointer's target outlives every call, and its type is exactly the `F` the trampoline was instantiated with. 3. Release builds with `panic = "abort"` are understood to abort on any callback panic, with no recovery. 4. `C-unwind` appears only where both sides are built to unwind.
- Why can't the wrapper pass the user's closure to C directly as the callback?A capturing closure is an anonymous struct whose call uses the Rust ABI; only non-capturing closures coerce to function pointers, and those are Rust-ABI `fn` pointers, not `extern "C" fn`. The trampoline is a real `extern "C" fn`, generic over the closure type, and recovers the closure's state from the `void *ctx` argument.
- Should the trampoline swallow the panic or re-raise it?Re-raise it once Rust is back in control. Store the payload from `catch_unwind` beside the closure, return the stop code to C, and after `kz_compress` returns call `std::panic::resume_unwind(payload)`. The caller then sees the original panic instead of a vague error code, and no unwind ever crosses C frames.
- A panic in an extern "C" callback unwinds through C to the Rust caller.
- Switching the callback to C-unwind is always the safe fix.
- catch_unwind also catches panics when panic = "abort" is set.
- Passing a capturing closure as an extern "C" fn pointer works.
- Before and after Rust 1.81, a panic escaping extern "C" behaves the same.
Assumes Rust 1.99; panics escaping extern "C" functions abort since Rust 1.81, and the C-unwind ABI is stable since Rust 1.71.