1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//! `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;
/// 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 }
/// ```