crate-plugin-kit 0.3.2

Installs and loads cdylib plugins and builds their prebuilt assets.
Documentation
//! `catch_unwind` helpers.
//!
//! # Why it is needed, and why it cannot be the only line of defense
//!
//! Plugins are code brought in by `dlopen`. One panic in a plugin takes the whole
//! host process down. So the host wraps every cross-boundary call in `catch_unwind`.
//!
//! But since Rust 1.81, letting a panic cross an `extern "C"` boundary aborts
//! outright — meaning:
//!
//! ```text
//! panic inside the plugin
//!    └─ if it escapes the plugin's extern "C" function → abort (a catch_unwind on
//!       the host side is useless)
//! ```
//!
//! So the correct setup has two layers:
//!
//! | Layer | Where | What it does |
//! | - | ---- | ------ |
//! | 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 |
//! | Outer | Host side (here) | Catches surprises such as a plugin built with `panic=abort`, or a plugin that forgot to wrap |
//!
//! The outer layer still works when the plugin does not wrap itself — provided the
//! plugin was also built with `panic=unwind`. That is why the host's `Cargo.toml`
//! sets `panic = "unwind"`.

use crate::error::{KitError, KitResult};

/// Wraps one cross-boundary call in `catch_unwind`.
///
/// `what` is only used in the error message, e.g. `"entry()"` / `"command()"`.
///
/// # Example
///
/// ```no_run
/// use crate_plugin_kit::panic::guard;
///
/// // Pretend this reads an exported symbol from a plugin and then calls it
/// fn call_plugin(entry: *const (), arg: u32) -> u32 {
///     guard("command()", || unsafe { read_field(entry) + arg }).unwrap_or(0)
/// }
///
/// /// # Safety
/// /// The caller guarantees that `entry` points at a struct with a matching layout.
/// unsafe fn read_field(_entry: *const ()) -> u32 { 1 }
/// ```
pub fn guard<T>(what: &str, f: impl FnOnce() -> T) -> KitResult<T> {
    // `AssertUnwindSafe`: all we require is that the panic does not take the process
    // down. We do not promise that mutable state at the catch site is usable
    // afterwards — the caller aborts the current operation on `Err`.
    std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_err(|_| {
        KitError::PluginPanicked {
            what: what.to_string(),
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn passes_through_normal_values() {
        let got = guard("test()", || 42).unwrap();
        assert_eq!(got, 42);
    }

    #[test]
    fn catches_panic() {
        let got: KitResult<()> = guard("test()", || panic!("boom"));
        assert!(matches!(got, Err(KitError::PluginPanicked { .. })));
    }
}