Skip to main content

anvil/
panic.rs

1//! Panics never cross the FFI: every adapter runs the plugin's code under
2//! `catch_unwind`. The panic hook keeps the message (with its place) for the
3//! adapter that catches it, and logs a panic no adapter catches.
4
5use std::any::Any;
6use std::cell::{Cell, RefCell};
7use std::panic::{self as std_panic, AssertUnwindSafe};
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::sync::Once;
10
11use crate::host::{Host, LogLevel};
12
13thread_local! {
14    static CATCHING: Cell<u32> = const { Cell::new(0) };
15    static MESSAGE: RefCell<Option<String>> = const { RefCell::new(None) };
16}
17
18static HOOK: Once = Once::new();
19
20/// Installs the panic hook once (at load). Each plugin DLL has its own copy of
21/// the standard library, so the hook is this plugin's only.
22pub(crate) fn install_hook() {
23    HOOK.call_once(|| {
24        // A panic no adapter catches also goes to the hook before (stderr).
25        let previous = std_panic::take_hook();
26        std_panic::set_hook(Box::new(move |info| {
27            let text = match info.location() {
28                Some(at) => format!(
29                    "{} at {}:{}",
30                    payload_text(info.payload()),
31                    at.file(),
32                    at.line()
33                ),
34                None => payload_text(info.payload()),
35            };
36            // try_with: a thread that is ending has no thread-locals left.
37            if CATCHING.try_with(Cell::get).unwrap_or(0) > 0 {
38                let _ = MESSAGE.try_with(|message| *message.borrow_mut() = Some(text));
39            } else {
40                if let Some(host) = Host::current() {
41                    host.log(LogLevel::Error, format_args!("panic: {text}"));
42                }
43                previous(info);
44            }
45        }));
46    });
47}
48
49fn payload_text(payload: &(dyn Any + Send)) -> String {
50    if let Some(text) = payload.downcast_ref::<&str>() {
51        (*text).to_owned()
52    } else if let Some(text) = payload.downcast_ref::<String>() {
53        text.clone()
54    } else {
55        "a panic without a message".to_owned()
56    }
57}
58
59/// The text of a caught panic: the hook's message (with its place) when it
60/// is this payload's. A panic the plugin caught itself, inside an adapter,
61/// leaves its message behind; a later payload that did not pass the hook
62/// (`resume_unwind`) must not be named by it.
63fn text_of(kept: Option<String>, payload: &(dyn Any + Send)) -> String {
64    let own = payload_text(payload);
65    // The hook writes the payload's text, alone or followed by " at file:line".
66    match kept {
67        Some(kept)
68            if kept
69                .strip_prefix(own.as_str())
70                .is_some_and(|rest| rest.is_empty() || rest.starts_with(" at ")) =>
71        {
72            kept
73        }
74        _ => own,
75    }
76}
77
78/// Runs `body`; a panic comes back as its message (and place).
79pub(crate) fn catch<R>(body: impl FnOnce() -> R) -> Result<R, String> {
80    catch_raw(body).map_err(|payload| {
81        let text = text_of(
82            MESSAGE.with(|message| message.borrow_mut().take()),
83            &*payload,
84        );
85        // Dropping a payload may panic in turn; never let that out.
86        let _ = std_panic::catch_unwind(AssertUnwindSafe(move || drop(payload)));
87        text
88    })
89}
90
91/// Runs `body` with the hook keeping the message; the payload comes back.
92pub(crate) fn catch_raw<R>(body: impl FnOnce() -> R) -> std::thread::Result<R> {
93    CATCHING.with(|n| n.set(n.get() + 1));
94    let result = std_panic::catch_unwind(AssertUnwindSafe(body));
95    CATCHING.with(|n| n.set(n.get() - 1));
96    result
97}
98
99/// Goes on with a panic that [`catch_raw`] caught. `resume_unwind` does not
100/// call the hook again, so the message the hook kept stays for an adapter of
101/// this thread that catches it further out; with none, it is logged now, as
102/// the hook logs a panic no adapter catches.
103pub(crate) fn resume(payload: Box<dyn Any + Send>) -> ! {
104    if CATCHING.try_with(Cell::get).unwrap_or(0) == 0 {
105        let kept = MESSAGE
106            .try_with(|message| message.borrow_mut().take())
107            .ok()
108            .flatten();
109        let text = text_of(kept, &*payload);
110        let _ = catch(|| {
111            if let Some(host) = Host::current() {
112                host.log(LogLevel::Error, format_args!("panic: {text}"));
113            }
114        });
115    }
116    std_panic::resume_unwind(payload)
117}
118
119/// The adapters' rule: a panic is logged once per callback (`logged` is the
120/// callback's flag), and `fallback` is answered instead of unwinding.
121pub(crate) fn run_callback<R>(
122    what: &str,
123    logged: &AtomicBool,
124    fallback: R,
125    body: impl FnOnce() -> R,
126) -> R {
127    match catch(body) {
128        Ok(value) => value,
129        Err(text) => {
130            if !logged.swap(true, Ordering::AcqRel) {
131                let _ = catch(|| {
132                    if let Some(host) = Host::current() {
133                        host.log(
134                            LogLevel::Error,
135                            format_args!(
136                                "{what}: the callback panicked ({text}); the game carries on, and later panics of this callback are not logged"
137                            ),
138                        );
139                    }
140                });
141            }
142            fallback
143        }
144    }
145}
146
147/// Runs `body`; a panic is logged as "`what` panicked (…)" and `fallback` is
148/// returned instead of unwinding. For function-hook detours and other plain
149/// functions the game calls directly, where no adapter of this crate stands
150/// between: a panic out of an `extern "C"` function aborts the game.
151pub fn catch_panic<R>(what: &str, fallback: R, body: impl FnOnce() -> R) -> R {
152    match catch(body) {
153        Ok(value) => value,
154        Err(text) => {
155            let _ = catch(|| {
156                if let Some(host) = Host::current() {
157                    host.log(
158                        LogLevel::Error,
159                        format_args!("{what} panicked ({text}); carrying on"),
160                    );
161                }
162            });
163            fallback
164        }
165    }
166}