crate_plugin_kit/panic.rs
1//! `catch_unwind` helpers.
2//!
3//! # Why it is needed, and why it cannot be the only line of defense
4//!
5//! Plugins are code brought in by `dlopen`. One panic in a plugin takes the whole
6//! host process down. So the host wraps every cross-boundary call in `catch_unwind`.
7//!
8//! But since Rust 1.81, letting a panic cross an `extern "C"` boundary aborts
9//! outright — meaning:
10//!
11//! ```text
12//! panic inside the plugin
13//! └─ if it escapes the plugin's extern "C" function → abort (a catch_unwind on
14//! the host side is useless)
15//! ```
16//!
17//! So the correct setup has two layers:
18//!
19//! | Layer | Where | What it does |
20//! | - | ---- | ------ |
21//! | Inner | Plugin side (generated by the contract crate's `export!` macro) | Turns the panic into an error code, never letting it reach the `extern "C"` boundary |
22//! | Outer | Host side (here) | Catches surprises such as a plugin built with `panic=abort`, or a plugin that forgot to wrap |
23//!
24//! The outer layer still works when the plugin does not wrap itself — provided the
25//! plugin was also built with `panic=unwind`. That is why the host's `Cargo.toml`
26//! sets `panic = "unwind"`.
27
28use crate::error::{KitError, KitResult};
29
30/// Wraps one cross-boundary call in `catch_unwind`.
31///
32/// `what` is only used in the error message, e.g. `"entry()"` / `"command()"`.
33///
34/// # Example
35///
36/// ```no_run
37/// use crate_plugin_kit::panic::guard;
38///
39/// // Pretend this reads an exported symbol from a plugin and then calls it
40/// fn call_plugin(entry: *const (), arg: u32) -> u32 {
41/// guard("command()", || unsafe { read_field(entry) + arg }).unwrap_or(0)
42/// }
43///
44/// /// # Safety
45/// /// The caller guarantees that `entry` points at a struct with a matching layout.
46/// unsafe fn read_field(_entry: *const ()) -> u32 { 1 }
47/// ```
48pub fn guard<T>(what: &str, f: impl FnOnce() -> T) -> KitResult<T> {
49 // `AssertUnwindSafe`: all we require is that the panic does not take the process
50 // down. We do not promise that mutable state at the catch site is usable
51 // afterwards — the caller aborts the current operation on `Err`.
52 std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_err(|_| {
53 KitError::PluginPanicked {
54 what: what.to_string(),
55 }
56 })
57}
58
59#[cfg(test)]
60mod tests {
61 use super::*;
62
63 #[test]
64 fn passes_through_normal_values() {
65 let got = guard("test()", || 42).unwrap();
66 assert_eq!(got, 42);
67 }
68
69 #[test]
70 fn catches_panic() {
71 let got: KitResult<()> = guard("test()", || panic!("boom"));
72 assert!(matches!(got, Err(KitError::PluginPanicked { .. })));
73 }
74}