| 1 | use std::backtrace::Backtrace; |
| 2 | use std::fs; |
| 3 | use std::panic::PanicHookInfo; |
| 4 | use std::path::{Path, PathBuf}; |
| 5 | use std::sync::OnceLock; |
| 6 | |
| 7 | pub const CRASH_LOG_FILE: &str = "crash.log"; |
| 8 | const MAX_BYTES: u64 = 256 * 1024; |
| 9 | const RING_SLOTS: u32 = 1; |
| 10 | const MERGE_CAP_BYTES: u64 = 128 * 1024; |
| 11 | |
| 12 | static PATH: OnceLock<PathBuf> = OnceLock::new(); |
| 13 | |
| 14 | pub fn install(path: PathBuf) { |
| 15 | let _ = PATH.set(path.clone()); |
| 16 | let previous = std::panic::take_hook(); |
| 17 | std::panic::set_hook(Box::new(move |info| { |
| 18 | let body = entry(info, &Backtrace::force_capture().to_string()); |
| 19 | let _ = crate::diagnostics::append_rotated(&path, MAX_BYTES, RING_SLOTS, &body); |
| 20 | previous(info); |
| 21 | })); |
| 22 | } |
| 23 | |
| 24 | pub fn path() -> Option<PathBuf> { |
| 25 | PATH.get().cloned() |
| 26 | } |
| 27 | |
| 28 | pub fn read_merged(max_bytes: u64) -> String { |
| 29 | let Some(path) = PATH.get() else { |
| 30 | return String::new(); |
| 31 | }; |
| 32 | crate::diagnostics::read_ring_merged(path, RING_SLOTS, max_bytes.min(MERGE_CAP_BYTES).max(1)) |
| 33 | } |
| 34 | |
| 35 | pub fn clear_files(root: &Path) { |
| 36 | for name in [CRASH_LOG_FILE, &format!("{CRASH_LOG_FILE}.1")] { |
| 37 | let path = root.join(name); |
| 38 | if path.exists() { |
| 39 | let _ = fs::remove_file(path); |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | fn entry(info: &PanicHookInfo<'_>, backtrace: &str) -> String { |
| 45 | let location = info |
| 46 | .location() |
| 47 | .map(|location| { |
| 48 | format!( |
| 49 | "{}:{}:{}", |
| 50 | location.file(), |
| 51 | location.line(), |
| 52 | location.column() |
| 53 | ) |
| 54 | }) |
| 55 | .unwrap_or_default(); |
| 56 | let thread = std::thread::current(); |
| 57 | format!( |
| 58 | "=== {} build {} thread {}\npanic at {location}: {}\n{backtrace}\n", |
| 59 | chrono::Utc::now().to_rfc3339(), |
| 60 | crate::version::build_version(), |
| 61 | thread.name().unwrap_or("unnamed"), |
| 62 | message(info), |
| 63 | ) |
| 64 | } |
| 65 | |
| 66 | fn message(info: &PanicHookInfo<'_>) -> String { |
| 67 | let payload = info.payload(); |
| 68 | payload |
| 69 | .downcast_ref::<&str>() |
| 70 | .map(|text| (*text).to_owned()) |
| 71 | .or_else(|| payload.downcast_ref::<String>().cloned()) |
| 72 | .unwrap_or_else(|| "non-text panic payload".to_owned()) |
| 73 | } |