Skip to main content

crate_plugin_kit/
panic.rs

1//! `catch_unwind` 工具。
2//!
3//! # 为什么需要它,以及它为什么**不能**是唯一一道防线
4//!
5//! 插件是 `dlopen` 进来的代码。它 panic 一次,宿主整个进程就没了。
6//! 所以宿主要在**每一次**跨边界调用外面包一层 `catch_unwind`。
7//!
8//! ⚠️ 但从 Rust 1.81 起,**让 panic 越过 `extern "C"` 边界会直接 abort** ——
9//! 也就是说:
10//!
11//! ```text
12//! 插件内部 panic
13//!    └─ 如果从插件的 extern "C" 函数里逃出来 → abort(宿主侧 catch_unwind 完全没用)
14//! ```
15//!
16//! 所以正确做法是**两层**:
17//!
18//! | 层 | 在哪 | 干什么 |
19//! | - | ---- | ------ |
20//! | 内层 | 插件侧(契约 crate 的 `export!` 宏生成) | 把 panic 转成错误码,**不让它碰到 `extern "C"` 边界** |
21//! | 外层 | 宿主侧(就是这里) | 兜住"插件用 `panic=abort` 编的""插件忘了包"之类的意外 |
22//!
23//! 外层这道防线在插件自己没包住时仍然有效 —— 前提是插件也是 `panic=unwind` 编的。
24//! 这就是宿主 `Cargo.toml` 要写 `panic = "unwind"` 的原因。
25
26use crate::error::{KitError, KitResult};
27
28/// 把一次跨边界调用包进 `catch_unwind`。
29///
30/// `what` 只用于错误信息,例如 `"entry()"` / `"command()"`。
31///
32/// # 例子
33///
34/// ```no_run
35/// use crate_plugin_kit::panic::guard;
36///
37/// // 假装这是一次读到插件导出符号、然后调用它的过程
38/// fn call_plugin(entry: *const (), arg: u32) -> u32 {
39///     guard("command()", || unsafe { read_field(entry) + arg }).unwrap_or(0)
40/// }
41///
42/// /// # Safety
43/// /// 调用方保证 `entry` 指向一个布局匹配的结构体。
44/// unsafe fn read_field(_entry: *const ()) -> u32 { 1 }
45/// ```
46pub fn guard<T>(what: &str, f: impl FnOnce() -> T) -> KitResult<T> {
47    // `AssertUnwindSafe`:我们只要求"panic 不要掀翻进程",
48    // 不承诺捕获之后继续使用捕获现场的那些可变状态 —— 调用方拿到 Err 就中止当前操作。
49    std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_err(|_| {
50        KitError::PluginPanicked {
51            what: what.to_string(),
52        }
53    })
54}
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59
60    #[test]
61    fn passes_through_normal_values() {
62        let got = guard("test()", || 42).unwrap();
63        assert_eq!(got, 42);
64    }
65
66    #[test]
67    fn catches_panic() {
68        let got: KitResult<()> = guard("test()", || panic!("boom"));
69        assert!(matches!(got, Err(KitError::PluginPanicked { .. })));
70    }
71}