|
| 1 | +// SPDX-License-Identifier: BUSL-1.1 |
| 2 | + |
| 3 | +//! Process-wide panic reporting that never renders application panic payloads. |
| 4 | +
|
| 5 | +use std::sync::OnceLock; |
| 6 | + |
| 7 | +static PANIC_HOOK: OnceLock<()> = OnceLock::new(); |
| 8 | +const PANIC_DIAGNOSTIC: &[u8] = b"nodedb: process panic intercepted\n"; |
| 9 | + |
| 10 | +#[cfg(unix)] |
| 11 | +fn report_panic() { |
| 12 | + // SAFETY: the byte slice is valid for the duration of the call and |
| 13 | + // `STDERR_FILENO` is the conventional process stderr descriptor. `write` |
| 14 | + // is allocation-free; failures and partial writes are intentionally |
| 15 | + // ignored because panic reporting must never trigger another panic. |
| 16 | + let _ = unsafe { |
| 17 | + libc::write( |
| 18 | + libc::STDERR_FILENO, |
| 19 | + PANIC_DIAGNOSTIC.as_ptr().cast(), |
| 20 | + PANIC_DIAGNOSTIC.len(), |
| 21 | + ) |
| 22 | + }; |
| 23 | +} |
| 24 | + |
| 25 | +#[cfg(not(unix))] |
| 26 | +fn report_panic() { |
| 27 | + use std::io::Write as _; |
| 28 | + |
| 29 | + // The portable fallback performs no formatting and ignores every I/O |
| 30 | + // failure. NodeDB's supported production targets use the Unix path above. |
| 31 | + let _ = std::io::stderr().write_all(PANIC_DIAGNOSTIC); |
| 32 | +} |
| 33 | + |
| 34 | +/// Install the payload-redacting process panic hook exactly once. |
| 35 | +/// |
| 36 | +/// The hook intentionally neither chains the default hook nor examines the |
| 37 | +/// panic payload or source location. Connection-level boundaries handle |
| 38 | +/// expected wire panics; this fixed diagnostic is the last-resort report for |
| 39 | +/// every other task. |
| 40 | +pub fn install() { |
| 41 | + PANIC_HOOK.get_or_init(|| { |
| 42 | + std::panic::set_hook(Box::new(|_| report_panic())); |
| 43 | + }); |
| 44 | +} |
| 45 | + |
| 46 | +#[cfg(test)] |
| 47 | +mod tests { |
| 48 | + use super::*; |
| 49 | + |
| 50 | + #[test] |
| 51 | + fn local_install_state_is_idempotent_without_replacing_global_hook() { |
| 52 | + let state = OnceLock::new(); |
| 53 | + assert!(state.set(()).is_ok()); |
| 54 | + assert!(state.set(()).is_err()); |
| 55 | + } |
| 56 | + |
| 57 | + #[test] |
| 58 | + fn diagnostic_is_fixed_and_payload_free() { |
| 59 | + assert_eq!(PANIC_DIAGNOSTIC, b"nodedb: process panic intercepted\n"); |
| 60 | + assert!( |
| 61 | + !PANIC_DIAGNOSTIC |
| 62 | + .windows(b"secret panic payload".len()) |
| 63 | + .any(|window| window == b"secret panic payload") |
| 64 | + ); |
| 65 | + } |
| 66 | +} |
0 commit comments