runic_diagnostics/
panic_support.rs1#[cfg(feature = "std")]
2use alloc::{
3 boxed::Box,
4 string::{String, ToString},
5};
6#[cfg(feature = "std")]
7use core::{cell::Cell, fmt};
8#[cfg(feature = "std")]
9use std::{
10 io::{self, Write},
11 panic::{self, PanicHookInfo},
12 sync::Mutex,
13};
14
15use crate::Report;
16#[cfg(feature = "std")]
17use crate::{
18 TerminalPolicy,
19 terminal::{PANIC_FALLBACK, write_stderr_fallback},
20};
21
22#[cfg(feature = "std")]
24#[derive(Clone, Copy, Debug, Eq, PartialEq)]
25pub struct PanicHookOptions {
26 pub terminal_policy: TerminalPolicy,
27}
28
29#[cfg(feature = "std")]
30impl PanicHookOptions {
31 pub const DEFAULT: Self = Self {
32 terminal_policy: TerminalPolicy::DEFAULT,
33 };
34
35 pub const fn new(terminal_policy: TerminalPolicy) -> Self {
36 Self { terminal_policy }
37 }
38}
39
40#[cfg(feature = "std")]
41impl Default for PanicHookOptions {
42 fn default() -> Self {
43 Self::DEFAULT
44 }
45}
46
47#[cfg(feature = "std")]
49#[derive(Clone, Copy, Debug, Eq, PartialEq)]
50pub enum InstallHookError {
51 PanickingThread,
52 IncompatibleOptions {
53 installed: PanicHookOptions,
54 requested: PanicHookOptions,
55 },
56}
57
58#[cfg(feature = "std")]
59impl fmt::Display for InstallHookError {
60 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
61 match self {
62 Self::PanickingThread => {
63 formatter.write_str("cannot install a panic hook from a panicking thread")
64 }
65 Self::IncompatibleOptions { .. } => formatter
66 .write_str("a diagnostic panic hook is already installed with different options"),
67 }
68 }
69}
70
71#[cfg(feature = "std")]
72impl core::error::Error for InstallHookError {}
73
74#[cfg(feature = "std")]
75static INSTALLATION: Mutex<Option<PanicHookOptions>> = Mutex::new(None);
76
77#[cfg(feature = "std")]
78std::thread_local! {
79 static HOOK_ACTIVE: Cell<bool> = const { Cell::new(false) };
80}
81
82#[cfg(feature = "std")]
83struct HookGuard;
84
85#[cfg(feature = "std")]
86impl HookGuard {
87 fn enter() -> Option<Self> {
88 HOOK_ACTIVE
89 .try_with(|active| {
90 if active.get() {
91 false
92 } else {
93 active.set(true);
94 true
95 }
96 })
97 .ok()
98 .filter(|entered| *entered)
99 .map(|_| Self)
100 }
101}
102
103#[cfg(feature = "std")]
104impl Drop for HookGuard {
105 fn drop(&mut self) {
106 let _ = HOOK_ACTIVE.try_with(|active| active.set(false));
107 }
108}
109
110#[cfg(feature = "std")]
111struct ReportPanic {
112 _report: Report,
113 framed_record: String,
114}
115
116#[cfg(feature = "std")]
121pub fn install_panic_hook(options: PanicHookOptions) -> core::result::Result<(), InstallHookError> {
122 if std::thread::panicking() {
123 return Err(InstallHookError::PanickingThread);
124 }
125
126 let mut installation = INSTALLATION.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
127 if let Some(installed) = *installation {
128 return if installed == options {
129 Ok(())
130 } else {
131 Err(InstallHookError::IncompatibleOptions {
132 installed,
133 requested: options,
134 })
135 };
136 }
137
138 let previous = panic::take_hook();
139 panic::set_hook(Box::new(move |info| dispatch_hook(info, previous.as_ref())));
140 *installation = Some(options);
141 Ok(())
142}
143
144#[cfg(feature = "std")]
145fn dispatch_hook(
146 info: &PanicHookInfo<'_>,
147 previous: &(dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static),
148) {
149 let Some(_guard) = HookGuard::enter() else {
150 write_stderr_fallback(PANIC_FALLBACK);
151 return;
152 };
153
154 let Some(payload) = info.payload().downcast_ref::<ReportPanic>() else {
155 previous(info);
156 return;
157 };
158
159 let stderr = io::stderr();
160 let mut lock = stderr.lock();
161 if lock.write_all(payload.framed_record.as_bytes()).is_err() || lock.flush().is_err() {
162 drop(lock);
163 write_stderr_fallback(PANIC_FALLBACK);
164 }
165}
166
167#[cfg(feature = "std")]
168fn installed_options() -> Option<PanicHookOptions> {
169 *INSTALLATION.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
170}
171
172#[cfg(feature = "std")]
173#[doc(hidden)]
174#[track_caller]
175pub fn panic_report(report: Report) -> ! {
176 if std::thread::panicking() {
177 write_stderr_fallback(PANIC_FALLBACK);
178 std::process::abort();
179 }
180
181 let installed = installed_options();
182 let options = installed.unwrap_or_default();
183 let mut framed_record =
184 report.display().with_config(options.terminal_policy.resolve()).to_string();
185 framed_record.push('\n');
186 match installed {
187 Some(_) => panic::panic_any(ReportPanic {
188 _report: report,
189 framed_record,
190 }),
191 None => panic::panic_any(framed_record),
192 }
193}
194
195#[cfg(not(feature = "std"))]
196#[doc(hidden)]
197#[track_caller]
198pub fn panic_report(report: Report) -> ! {
199 panic!("{report}")
200}