rt/hosted.rs
1// hosted -- what rt has for a program with the standard library (feature std, docs/CRATES.md
2// CR6); the only file of rt that names std, compiled only with that feature. std brings the panic
3// handler, the allocator and the memory functions then (lib.rs, mem.rs and os.rs leave theirs out).
4//
5// panic_hook() std's panics end as rt's panic handler ends them without std
6// abort_on_unwind(f) (feature unwind) a panic that leaves f ends the program as an uncaught one
7// panic_take() (feature unwind) the last panic of the calling thread, as text
8//
9// With the feature unwind and panic = "unwind" a panic unwinds: the hook only keeps its text (LAST)
10// and reports nothing, since the app may catch it. It is reported where it leaves JFLib's threads
11// and the program's start (abort_on_unwind) or reaches a function that cannot unwind (an extern
12// callback such as a window procedure: core panics once more there, with one of NOUNWIND's texts).
13
14#[cfg(feature = "unwind")]
15use alloc::string::String;
16
17/// (feature std) std's panics end as rt's panic handler ends them without std: one line on stderr,
18/// the crash hook, exit code 3. plat's start of a std program installs it; replacing it with
19/// `std::panic::set_hook` gives up JFLib's crash report for panics. With the feature `unwind` and
20/// `panic = "unwind"` it reports only a panic nobody catches: one that leaves the program's start or
21/// a thread of JFLib's, or reaches a callback of the system ([`abort_on_unwind`]).
22pub fn panic_hook() {
23 std::panic::set_hook(alloc::boxed::Box::new(on_panic));
24}
25
26#[cfg(not(all(feature = "unwind", panic = "unwind")))]
27fn on_panic(info: &std::panic::PanicHookInfo) {
28 crate::panic_report(info)
29}
30
31// core's texts of a second panic on a thread that is unwinding: it reached a function that cannot
32// unwind (extern "C" / "system"), or a destructor panicked during the unwinding
33#[cfg(all(feature = "unwind", panic = "unwind"))]
34const NOUNWIND: [&str; 2] = ["panic in a function that cannot unwind", "panic in a destructor during cleanup"];
35
36#[cfg(all(feature = "unwind", panic = "unwind"))]
37fn on_panic(info: &std::panic::PanicHookInfo) {
38 if info.payload_as_str().is_some_and(|m| NOUNWIND.contains(&m)) {
39 report_last(None, info) // the panic that was unwinding
40 }
41 let text = alloc::format!("{info}");
42 let _ = LAST.try_with(|l| l.try_borrow_mut().map(|mut s| *s = Some(text)));
43}
44
45#[cfg(feature = "unwind")]
46std::thread_local! {
47 // the last panic of this thread as the hook saw it: "panicked at FILE:LINE:COL:\nMESSAGE"
48 static LAST: core::cell::RefCell<Option<String>> = const { core::cell::RefCell::new(None) };
49}
50
51/// the end of a panic nobody caught: the text the hook kept for it (when it ends in the payload's
52/// message, or the payload has none), else `now`; JFLib's crash report, exit code 3
53#[cfg(feature = "unwind")]
54fn report_last(message: Option<&str>, now: &dyn core::fmt::Display) -> ! {
55 let last = LAST.try_with(|l| l.try_borrow_mut().ok().and_then(|mut s| s.take())).ok().flatten();
56 match last {
57 Some(text) if message.is_none_or(|m| text.ends_with(m)) => crate::panic_report(&text),
58 _ => crate::panic_report(now),
59 }
60}
61
62/// (feature `unwind`) run `f`; a panic that leaves it ends the program as an uncaught panic:
63/// JFLib's crash report (the panic's text on stderr, the crash hook), exit code 3. plat runs its
64/// threads and the program's start through it, so only the app's own `std::panic::catch_unwind`
65/// (on any thread) keeps a panic from ending the program. With `panic = "abort"` it is `f()`.
66#[cfg(feature = "unwind")]
67pub fn abort_on_unwind<R>(f: impl FnOnce() -> R) -> R {
68 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
69 Ok(r) => r,
70 Err(payload) => {
71 let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::<String>().map(|s| s.as_str()));
72 report_last(message, &message.unwrap_or("panicked (no message)"))
73 }
74 }
75}
76
77/// (feature `unwind`) the last panic on the calling thread as JFLib's crash report shows it
78/// (`"panicked at FILE:LINE:COL:\nMESSAGE"`), taken: for a panic the app caught with
79/// `std::panic::catch_unwind`, whose payload holds the message alone. None when no panic came
80/// since the last call (or the program is built with `panic = "abort"`).
81#[cfg(feature = "unwind")]
82pub fn panic_take() -> Option<String> {
83 LAST.try_with(|l| l.try_borrow_mut().ok().and_then(|mut s| s.take())).ok().flatten()
84}