Skip to main content

quickgui_system/
crash.rs

1//! Bounded crash reporting: panic reports, native fatal-signal reports, retention, and upload.
2//!
3//! Everything the reporter writes is bounded before it reaches the filesystem: report bodies,
4//! extra parameters, retained report counts, and the number of reports one upload attempts.
5//! The native fatal-signal path never allocates, never locks, and never formats through `std`;
6//! it writes a pre-rendered byte template plus a handful of digits into a file descriptor that
7//! was opened while the process was still healthy.
8
9use std::{
10    collections::BTreeMap,
11    fs::{self, File},
12    io::{Read, Write},
13    panic::PanicHookInfo,
14    path::{Path, PathBuf},
15    sync::{
16        Arc, Condvar, Mutex, OnceLock,
17        atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
18    },
19    thread::JoinHandle,
20    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
21};
22
23use serde::{Deserialize, Serialize};
24
25use crate::{AppInfo, Result, SystemIntegrationError, invalid};
26
27/// Schema version stamped into every report QuickGUI writes.
28pub const CRASH_REPORT_SCHEMA_VERSION: u32 = 1;
29/// Hard ceiling for [`CrashReporterOptions::max_reports`].
30pub const MAX_CRASH_REPORTS: usize = 128;
31/// Retention used when the caller does not choose one.
32pub const DEFAULT_MAX_CRASH_REPORTS: usize = 16;
33/// Hard ceiling for [`CrashReporterOptions::max_report_bytes`].
34pub const MAX_CRASH_REPORT_BYTES: usize = 1024 * 1024;
35/// Report size limit used when the caller does not choose one.
36pub const DEFAULT_MAX_CRASH_REPORT_BYTES: usize = 64 * 1024;
37/// Maximum number of retained extra parameters.
38pub const MAX_CRASH_EXTRA_PARAMETERS: usize = 32;
39/// Maximum UTF-8 length of one extra-parameter key.
40pub const MAX_CRASH_PARAMETER_KEY_BYTES: usize = 128;
41/// Maximum UTF-8 length of one extra-parameter value.
42pub const MAX_CRASH_PARAMETER_VALUE_BYTES: usize = 4 * 1024;
43/// Maximum retained panic/hang message length; longer messages are truncated.
44pub const MAX_CRASH_MESSAGE_BYTES: usize = 8 * 1024;
45/// Maximum retained backtrace length; longer backtraces are truncated.
46pub const MAX_CRASH_BACKTRACE_BYTES: usize = 32 * 1024;
47/// Maximum number of reports one [`CrashReporter::upload_pending`] call sends.
48pub const MAX_CRASH_UPLOAD_REPORTS: usize = 32;
49/// Shortest accepted watchdog poll interval.
50pub const MIN_WATCHDOG_INTERVAL: Duration = Duration::from_millis(10);
51/// Longest accepted watchdog poll interval.
52pub const MAX_WATCHDOG_INTERVAL: Duration = Duration::from_secs(300);
53/// Watchdog poll interval used when the caller does not choose one.
54pub const DEFAULT_WATCHDOG_INTERVAL: Duration = Duration::from_secs(5);
55/// Hang threshold used when the caller does not choose one.
56pub const DEFAULT_WATCHDOG_HANG_THRESHOLD: Duration = Duration::from_secs(15);
57
58const REPORT_SUFFIX: &str = ".crash.json";
59const PARTIAL_SUFFIX: &str = ".crash.partial";
60
61/// How a report was produced.
62#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
63#[serde(rename_all = "kebab-case")]
64pub enum CrashKind {
65    /// A Rust panic observed by the installed panic hook.
66    Panic,
67    /// A native fatal signal or structured exception.
68    Signal,
69    /// A main-thread heartbeat that stopped within the configured threshold.
70    Hang,
71}
72
73impl CrashKind {
74    /// The stable wire name used in report JSON.
75    pub const fn as_str(self) -> &'static str {
76        match self {
77            Self::Panic => "panic",
78            Self::Signal => "signal",
79            Self::Hang => "hang",
80        }
81    }
82}
83
84/// Whether a panic report captures a `std::backtrace::Backtrace`.
85#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
86pub enum BacktracePolicy {
87    /// Never capture a backtrace.
88    Disabled,
89    /// Capture only when `RUST_BACKTRACE` enables it (the default).
90    #[default]
91    Environment,
92    /// Always capture, regardless of the environment.
93    Always,
94}
95
96/// Source position recorded for a panic report.
97#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
98pub struct CrashLocation {
99    pub file: String,
100    pub line: u32,
101    pub column: u32,
102}
103
104/// One bounded crash report, as written to and parsed back from disk.
105#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
106#[serde(rename_all = "camelCase")]
107pub struct CrashReport {
108    pub schema_version: u32,
109    pub id: String,
110    pub kind: CrashKind,
111    pub timestamp: String,
112    pub app_name: String,
113    pub app_version: String,
114    pub app_identifier: String,
115    pub operating_system: String,
116    #[serde(default, skip_serializing_if = "Option::is_none")]
117    pub operating_system_version: Option<String>,
118    pub architecture: String,
119    pub process_id: u32,
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    pub thread: Option<String>,
122    pub message: String,
123    #[serde(default, skip_serializing_if = "Option::is_none")]
124    pub location: Option<CrashLocation>,
125    #[serde(default, skip_serializing_if = "Option::is_none")]
126    pub backtrace: Option<String>,
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub signal: Option<i32>,
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub signal_name: Option<String>,
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub fault_address: Option<String>,
133    #[serde(default)]
134    pub parameters: BTreeMap<String, String>,
135}
136
137/// Result of one bounded [`CrashReporter::upload_pending`] pass.
138#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
139pub struct UploadSummary {
140    /// Reports the pass tried to send, at most [`MAX_CRASH_UPLOAD_REPORTS`].
141    pub attempted: usize,
142    /// Reports accepted by the endpoint and then deleted from disk.
143    pub uploaded: usize,
144    /// Reports the endpoint rejected or that could not be sent; these stay on disk.
145    pub failed: usize,
146}
147
148/// Bounded configuration for [`CrashReporter::install`].
149#[derive(Clone, Debug)]
150pub struct CrashReporterOptions {
151    app: AppInfo,
152    directory: Option<PathBuf>,
153    max_reports: usize,
154    max_report_bytes: usize,
155    parameters: BTreeMap<String, String>,
156    upload_endpoint: Option<String>,
157    backtrace: BacktracePolicy,
158    capture_signals: bool,
159}
160
161impl CrashReporterOptions {
162    /// Defaults: `<AppPaths::log_dir>/crashes`, 16 retained reports, 64 KiB per report,
163    /// environment-controlled backtraces, and native fatal-signal capture enabled.
164    pub fn new(app: AppInfo) -> Self {
165        Self {
166            app,
167            directory: None,
168            max_reports: DEFAULT_MAX_CRASH_REPORTS,
169            max_report_bytes: DEFAULT_MAX_CRASH_REPORT_BYTES,
170            parameters: BTreeMap::new(),
171            upload_endpoint: None,
172            backtrace: BacktracePolicy::default(),
173            capture_signals: true,
174        }
175    }
176
177    /// Override the report directory. The path must be absolute.
178    pub fn directory(mut self, directory: impl Into<PathBuf>) -> Self {
179        self.directory = Some(directory.into());
180        self
181    }
182
183    /// Retain at most `maximum` reports, capped at [`MAX_CRASH_REPORTS`].
184    pub fn max_reports(mut self, maximum: usize) -> Result<Self> {
185        if maximum == 0 || maximum > MAX_CRASH_REPORTS {
186            return Err(invalid(format!(
187                "the crash report retention must be between 1 and {MAX_CRASH_REPORTS}"
188            )));
189        }
190        self.max_reports = maximum;
191        Ok(self)
192    }
193
194    /// Write at most `maximum` bytes per report, capped at [`MAX_CRASH_REPORT_BYTES`].
195    pub fn max_report_bytes(mut self, maximum: usize) -> Result<Self> {
196        if !(1024..=MAX_CRASH_REPORT_BYTES).contains(&maximum) {
197            return Err(invalid(format!(
198                "the crash report size limit must be between 1024 and {MAX_CRASH_REPORT_BYTES} bytes"
199            )));
200        }
201        self.max_report_bytes = maximum;
202        Ok(self)
203    }
204
205    /// Add one bounded extra parameter recorded in every report.
206    pub fn extra_parameter(
207        mut self,
208        key: impl Into<String>,
209        value: impl Into<String>,
210    ) -> Result<Self> {
211        let (key, value) = validate_parameter(key.into(), value.into())?;
212        if self.parameters.len() >= MAX_CRASH_EXTRA_PARAMETERS
213            && !self.parameters.contains_key(&key)
214        {
215            return Err(invalid(format!(
216                "at most {MAX_CRASH_EXTRA_PARAMETERS} crash-report parameters are retained"
217            )));
218        }
219        self.parameters.insert(key, value);
220        Ok(self)
221    }
222
223    /// Remember a default HTTPS upload endpoint for [`CrashReporter::upload_pending`].
224    pub fn upload_endpoint(mut self, endpoint: impl Into<String>) -> Result<Self> {
225        let endpoint = endpoint.into();
226        validate_https_url(&endpoint, "the crash upload endpoint")?;
227        self.upload_endpoint = Some(endpoint);
228        Ok(self)
229    }
230
231    /// Choose whether panic reports carry a backtrace.
232    pub fn backtrace(mut self, policy: BacktracePolicy) -> Self {
233        self.backtrace = policy;
234        self
235    }
236
237    /// Disable the native fatal-signal handler and keep only the Rust panic hook.
238    pub fn capture_signals(mut self, capture: bool) -> Self {
239        self.capture_signals = capture;
240        self
241    }
242}
243
244struct ReporterState {
245    directory: PathBuf,
246    app_name: String,
247    app_version: String,
248    app_identifier: String,
249    max_reports: usize,
250    max_report_bytes: usize,
251    parameters: Mutex<BTreeMap<String, String>>,
252    upload_endpoint: Option<String>,
253    backtrace: BacktracePolicy,
254    sequence: AtomicUsize,
255}
256
257/// Cheap cloneable handle to the installed crash reporter.
258#[derive(Clone)]
259pub struct CrashReporter(Arc<ReporterState>);
260
261impl std::fmt::Debug for CrashReporter {
262    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
263        formatter
264            .debug_struct("CrashReporter")
265            .field("directory", &self.0.directory)
266            .field("max_reports", &self.0.max_reports)
267            .field("max_report_bytes", &self.0.max_report_bytes)
268            .finish()
269    }
270}
271
272static INSTALLED: OnceLock<CrashReporter> = OnceLock::new();
273
274impl CrashReporter {
275    /// Install the process-wide panic hook and, unless disabled, the native fatal-signal handler.
276    ///
277    /// Installing twice is an error; use [`CrashReporter::current`] to reach the existing handle.
278    pub fn install(options: CrashReporterOptions) -> Result<Self> {
279        if INSTALLED.get().is_some() {
280            return Err(invalid("the crash reporter is already installed"));
281        }
282        let capture_signals = options.capture_signals;
283        let reporter = Self::detached(options)?;
284        INSTALLED
285            .set(reporter.clone())
286            .map_err(|_| invalid("the crash reporter is already installed"))?;
287        install_panic_hook();
288        if capture_signals {
289            install_signal_handler(&reporter);
290        }
291        Ok(reporter)
292    }
293
294    /// Build a reporter that owns its directory but installs no process-wide hooks.
295    ///
296    /// Deterministic tests and secondary tools use this to exercise writing, retention, parsing,
297    /// and upload without changing global process state.
298    pub fn detached(options: CrashReporterOptions) -> Result<Self> {
299        let directory = match options.directory {
300            Some(directory) => directory,
301            None => default_directory(&options.app)?,
302        };
303        validate_directory(&directory)?;
304        fs::create_dir_all(&directory).map_err(io_error)?;
305        let reporter = Self(Arc::new(ReporterState {
306            directory,
307            app_name: options.app.name().to_owned(),
308            app_version: options.app.version().to_owned(),
309            app_identifier: options.app.identifier().to_owned(),
310            max_reports: options.max_reports,
311            max_report_bytes: options.max_report_bytes,
312            parameters: Mutex::new(options.parameters),
313            upload_endpoint: options.upload_endpoint,
314            backtrace: options.backtrace,
315            sequence: AtomicUsize::new(0),
316        }));
317        promote_partial_reports(reporter.directory())?;
318        prune_reports(reporter.directory(), reporter.0.max_reports)?;
319        Ok(reporter)
320    }
321
322    /// The installed reporter, when [`CrashReporter::install`] has already succeeded.
323    pub fn current() -> Option<Self> {
324        INSTALLED.get().cloned()
325    }
326
327    /// Directory holding retained reports.
328    pub fn directory(&self) -> &Path {
329        &self.0.directory
330    }
331
332    /// Configured retention count.
333    pub fn max_reports(&self) -> usize {
334        self.0.max_reports
335    }
336
337    /// Configured per-report byte limit.
338    pub fn max_report_bytes(&self) -> usize {
339        self.0.max_report_bytes
340    }
341
342    /// Add or replace one bounded extra parameter recorded in later reports.
343    pub fn add_extra_parameter(
344        &self,
345        key: impl Into<String>,
346        value: impl Into<String>,
347    ) -> Result<()> {
348        let (key, value) = validate_parameter(key.into(), value.into())?;
349        let mut parameters = self.parameters();
350        if parameters.len() >= MAX_CRASH_EXTRA_PARAMETERS && !parameters.contains_key(&key) {
351            return Err(invalid(format!(
352                "at most {MAX_CRASH_EXTRA_PARAMETERS} crash-report parameters are retained"
353            )));
354        }
355        parameters.insert(key, value);
356        Ok(())
357    }
358
359    /// Remove one extra parameter, reporting whether it was present.
360    pub fn remove_extra_parameter(&self, key: &str) -> bool {
361        self.parameters().remove(key).is_some()
362    }
363
364    /// A snapshot of the retained extra parameters.
365    pub fn extra_parameters(&self) -> BTreeMap<String, String> {
366        self.parameters().clone()
367    }
368
369    /// Write one caller-built report atomically and apply retention.
370    pub fn capture_report(&self, report: &CrashReport) -> Result<PathBuf> {
371        let path = write_report_atomically(&self.0.directory, report, self.0.max_report_bytes)?;
372        prune_reports(&self.0.directory, self.0.max_reports)?;
373        Ok(path)
374    }
375
376    /// The newest retained report, parsed from disk.
377    pub fn last_crash_report(&self) -> Result<Option<CrashReport>> {
378        Ok(self.pending_reports()?.pop())
379    }
380
381    /// Every retained report in oldest-to-newest order, bounded by the configured retention.
382    pub fn pending_reports(&self) -> Result<Vec<CrashReport>> {
383        read_reports(
384            &self.0.directory,
385            self.0.max_reports,
386            self.0.max_report_bytes,
387        )
388    }
389
390    /// Delete one retained report by identifier, reporting whether it existed.
391    pub fn delete_report(&self, id: &str) -> Result<bool> {
392        validate_report_id(id)?;
393        let path = self.0.directory.join(format!("{id}{REPORT_SUFFIX}"));
394        match fs::remove_file(&path) {
395            Ok(()) => Ok(true),
396            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
397            Err(error) => Err(io_error(error)),
398        }
399    }
400
401    /// The endpoint configured through [`CrashReporterOptions::upload_endpoint`].
402    pub fn upload_endpoint(&self) -> Option<&str> {
403        self.0.upload_endpoint.as_deref()
404    }
405
406    /// Build the exact JSON body one upload sends for a report.
407    pub fn upload_body(report: &CrashReport) -> Result<Vec<u8>> {
408        serde_json::to_vec(report).map_err(io_error)
409    }
410
411    /// POST every retained report to `endpoint`, deleting the ones the endpoint accepts.
412    ///
413    /// At most [`MAX_CRASH_UPLOAD_REPORTS`] reports are sent per call. Reports the endpoint
414    /// rejects stay on disk for the next attempt.
415    pub fn upload_pending(&self, endpoint: &str) -> Result<UploadSummary> {
416        validate_https_url(endpoint, "the crash upload endpoint")?;
417        let reports = self.pending_reports()?;
418        let mut summary = UploadSummary::default();
419        let agent = https_agent();
420        for report in reports.into_iter().take(MAX_CRASH_UPLOAD_REPORTS) {
421            summary.attempted += 1;
422            let body = Self::upload_body(&report)?;
423            match agent
424                .post(endpoint)
425                .header("content-type", "application/json")
426                .send(&body[..])
427            {
428                Ok(response) if (200..300).contains(&response.status().as_u16()) => {
429                    self.delete_report(&report.id)?;
430                    summary.uploaded += 1;
431                }
432                _ => summary.failed += 1,
433            }
434        }
435        Ok(summary)
436    }
437
438    /// Build a report for the current process using the reporter's identity and parameters.
439    pub fn build_report(&self, kind: CrashKind, message: impl Into<String>) -> CrashReport {
440        let system = crate::SystemInfo::current();
441        CrashReport {
442            schema_version: CRASH_REPORT_SCHEMA_VERSION,
443            id: self.next_report_id(),
444            kind,
445            timestamp: format_rfc3339(unix_seconds()),
446            app_name: self.0.app_name.clone(),
447            app_version: self.0.app_version.clone(),
448            app_identifier: self.0.app_identifier.clone(),
449            operating_system: system.name().to_owned(),
450            operating_system_version: system.version().map(str::to_owned),
451            architecture: system.architecture().to_owned(),
452            process_id: std::process::id(),
453            thread: std::thread::current()
454                .name()
455                .map(|name| truncate_utf8(name, MAX_CRASH_PARAMETER_VALUE_BYTES).to_owned()),
456            message: truncate_utf8(&message.into(), MAX_CRASH_MESSAGE_BYTES).to_owned(),
457            location: None,
458            backtrace: None,
459            signal: None,
460            signal_name: None,
461            fault_address: None,
462            parameters: self.extra_parameters(),
463        }
464    }
465
466    fn record_panic(&self, info: &PanicHookInfo<'_>) -> Result<PathBuf> {
467        let message = panic_message(info);
468        let mut report = self.build_report(CrashKind::Panic, message);
469        report.location = info.location().map(|location| CrashLocation {
470            file: truncate_utf8(location.file(), MAX_CRASH_PARAMETER_VALUE_BYTES).to_owned(),
471            line: location.line(),
472            column: location.column(),
473        });
474        report.backtrace = capture_backtrace(self.0.backtrace);
475        self.capture_report(&report)
476    }
477
478    fn next_report_id(&self) -> String {
479        let sequence = self.0.sequence.fetch_add(1, Ordering::Relaxed);
480        report_id(unix_millis(), std::process::id(), sequence)
481    }
482
483    fn parameters(&self) -> std::sync::MutexGuard<'_, BTreeMap<String, String>> {
484        self.0
485            .parameters
486            .lock()
487            .unwrap_or_else(std::sync::PoisonError::into_inner)
488    }
489}
490
491/// Opt-in main-thread hang detector.
492///
493/// The watchdog is **disabled by default** and costs one sleeping thread that wakes every
494/// [`WatchdogOptions::interval`]. At the default five-second interval this is 12 wakeups per
495/// minute and no allocation; enable it only when hang telemetry is worth that idle cost.
496pub struct Watchdog {
497    shared: Arc<WatchdogShared>,
498    handle: Option<JoinHandle<()>>,
499}
500
501/// Bounded watchdog configuration.
502#[derive(Clone, Copy, Debug)]
503pub struct WatchdogOptions {
504    interval: Duration,
505    hang_threshold: Duration,
506}
507
508impl Default for WatchdogOptions {
509    fn default() -> Self {
510        Self {
511            interval: DEFAULT_WATCHDOG_INTERVAL,
512            hang_threshold: DEFAULT_WATCHDOG_HANG_THRESHOLD,
513        }
514    }
515}
516
517impl WatchdogOptions {
518    /// Poll interval, clamped to [`MIN_WATCHDOG_INTERVAL`]..=[`MAX_WATCHDOG_INTERVAL`].
519    pub fn interval(mut self, interval: Duration) -> Result<Self> {
520        if interval < MIN_WATCHDOG_INTERVAL || interval > MAX_WATCHDOG_INTERVAL {
521            return Err(invalid(
522                "the watchdog interval must be between 10 milliseconds and 300 seconds",
523            ));
524        }
525        self.interval = interval;
526        Ok(self)
527    }
528
529    /// Report a hang once the main thread has not beaten for this long.
530    pub fn hang_threshold(mut self, threshold: Duration) -> Result<Self> {
531        if threshold < MIN_WATCHDOG_INTERVAL || threshold > MAX_WATCHDOG_INTERVAL {
532            return Err(invalid(
533                "the watchdog hang threshold must be between 10 milliseconds and 300 seconds",
534            ));
535        }
536        self.hang_threshold = threshold;
537        Ok(self)
538    }
539}
540
541struct WatchdogShared {
542    origin: Instant,
543    last_beat_millis: AtomicU64,
544    reported: AtomicBool,
545    stopped: AtomicBool,
546    wake: Mutex<bool>,
547    condition: Condvar,
548}
549
550impl Watchdog {
551    /// Start the monitor thread. The caller must call [`Watchdog::heartbeat`] from the thread
552    /// whose responsiveness is being observed.
553    pub fn start(reporter: &CrashReporter, options: WatchdogOptions) -> Result<Self> {
554        let shared = Arc::new(WatchdogShared {
555            origin: Instant::now(),
556            last_beat_millis: AtomicU64::new(0),
557            reported: AtomicBool::new(false),
558            stopped: AtomicBool::new(false),
559            wake: Mutex::new(false),
560            condition: Condvar::new(),
561        });
562        let monitor = Arc::clone(&shared);
563        let reporter = reporter.clone();
564        let interval = options.interval;
565        let threshold = options.hang_threshold;
566        let handle = std::thread::Builder::new()
567            .name("quickgui-watchdog".to_owned())
568            .spawn(move || {
569                loop {
570                    let mut wake = monitor
571                        .wake
572                        .lock()
573                        .unwrap_or_else(std::sync::PoisonError::into_inner);
574                    while !*wake {
575                        let (guard, timeout) = monitor
576                            .condition
577                            .wait_timeout(wake, interval)
578                            .unwrap_or_else(std::sync::PoisonError::into_inner);
579                        wake = guard;
580                        if timeout.timed_out() {
581                            break;
582                        }
583                    }
584                    drop(wake);
585                    if monitor.stopped.load(Ordering::Acquire) {
586                        return;
587                    }
588                    let elapsed = monitor
589                        .origin
590                        .elapsed()
591                        .as_millis()
592                        .min(u128::from(u64::MAX)) as u64;
593                    let last = monitor.last_beat_millis.load(Ordering::Acquire);
594                    if watchdog_should_report(
595                        elapsed,
596                        last,
597                        threshold,
598                        monitor.reported.load(Ordering::Acquire),
599                    ) {
600                        monitor.reported.store(true, Ordering::Release);
601                        let report = reporter.build_report(
602                            CrashKind::Hang,
603                            format!(
604                                "the observed thread did not beat for at least {} ms",
605                                threshold.as_millis()
606                            ),
607                        );
608                        let _ = reporter.capture_report(&report);
609                    }
610                }
611            })
612            .map_err(io_error)?;
613        Ok(Self {
614            shared,
615            handle: Some(handle),
616        })
617    }
618
619    /// Record that the observed thread is still running its loop.
620    pub fn heartbeat(&self) {
621        let elapsed = self
622            .shared
623            .origin
624            .elapsed()
625            .as_millis()
626            .min(u128::from(u64::MAX)) as u64;
627        self.shared
628            .last_beat_millis
629            .store(elapsed, Ordering::Release);
630        self.shared.reported.store(false, Ordering::Release);
631    }
632
633    /// Whether the watchdog has already written a hang report for the current stall.
634    pub fn reported_hang(&self) -> bool {
635        self.shared.reported.load(Ordering::Acquire)
636    }
637
638    /// Stop the monitor thread and wait for it to exit.
639    pub fn stop(mut self) {
640        self.shutdown();
641    }
642
643    fn shutdown(&mut self) {
644        self.shared.stopped.store(true, Ordering::Release);
645        {
646            let mut wake = self
647                .shared
648                .wake
649                .lock()
650                .unwrap_or_else(std::sync::PoisonError::into_inner);
651            *wake = true;
652        }
653        self.shared.condition.notify_all();
654        if let Some(handle) = self.handle.take() {
655            let _ = handle.join();
656        }
657    }
658}
659
660impl Drop for Watchdog {
661    fn drop(&mut self) {
662        self.shutdown();
663    }
664}
665
666fn watchdog_should_report(
667    elapsed_millis: u64,
668    last_beat_millis: u64,
669    threshold: Duration,
670    already_reported: bool,
671) -> bool {
672    if already_reported {
673        return false;
674    }
675    let threshold = threshold.as_millis().min(u128::from(u64::MAX)) as u64;
676    elapsed_millis.saturating_sub(last_beat_millis) >= threshold
677}
678
679// ---------------------------------------------------------------------------
680// Directory helpers, shared by the reporter and by deterministic tests.
681// ---------------------------------------------------------------------------
682
683fn default_directory(app: &AppInfo) -> Result<PathBuf> {
684    let paths = app.paths()?;
685    let base = paths
686        .log_dir()
687        .map(Path::to_path_buf)
688        .unwrap_or_else(|| paths.temp_dir().to_path_buf());
689    Ok(base.join("crashes"))
690}
691
692fn validate_directory(directory: &Path) -> Result<()> {
693    let bytes = directory.as_os_str().as_encoded_bytes();
694    if !directory.is_absolute() || bytes.is_empty() || bytes.contains(&0) || bytes.len() > 32 * 1024
695    {
696        return Err(invalid(
697            "the crash report directory must be absolute, NUL-free, and at most 32768 encoded bytes",
698        ));
699    }
700    Ok(())
701}
702
703fn report_id(millis: u64, process_id: u32, sequence: usize) -> String {
704    format!("{millis:013}-{process_id}-{sequence:04}")
705}
706
707fn validate_report_id(id: &str) -> Result<()> {
708    if id.is_empty()
709        || id.len() > 128
710        || !id
711            .bytes()
712            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
713    {
714        return Err(invalid(
715            "a crash report identifier must be nonempty ASCII alphanumerics or hyphens",
716        ));
717    }
718    Ok(())
719}
720
721/// Serialize, size-check, and atomically publish one report.
722fn write_report_atomically(
723    directory: &Path,
724    report: &CrashReport,
725    max_report_bytes: usize,
726) -> Result<PathBuf> {
727    validate_report_id(&report.id)?;
728    fs::create_dir_all(directory).map_err(io_error)?;
729    let mut bytes = serde_json::to_vec(report).map_err(io_error)?;
730    if bytes.len() > max_report_bytes {
731        let mut trimmed = report.clone();
732        trimmed.backtrace = None;
733        trimmed.message = truncate_utf8(&trimmed.message, 1024).to_owned();
734        trimmed.parameters.clear();
735        bytes = serde_json::to_vec(&trimmed).map_err(io_error)?;
736        if bytes.len() > max_report_bytes {
737            return Err(invalid(
738                "the crash report exceeds the configured report size limit",
739            ));
740        }
741    }
742    let final_path = directory.join(format!("{}{REPORT_SUFFIX}", report.id));
743    let temporary = directory.join(format!(".{}.crash.tmp", report.id));
744    {
745        let mut file = File::create(&temporary).map_err(io_error)?;
746        file.write_all(&bytes).map_err(io_error)?;
747        file.sync_all().map_err(io_error)?;
748    }
749    fs::rename(&temporary, &final_path).map_err(|error| {
750        let _ = fs::remove_file(&temporary);
751        io_error(error)
752    })?;
753    Ok(final_path)
754}
755
756/// Delete the oldest reports until at most `max_reports` remain.
757fn prune_reports(directory: &Path, max_reports: usize) -> Result<usize> {
758    let mut names = report_file_names(directory)?;
759    if names.len() <= max_reports {
760        return Ok(0);
761    }
762    names.sort();
763    let excess = names.len() - max_reports;
764    let mut removed = 0;
765    for name in names.into_iter().take(excess) {
766        if fs::remove_file(directory.join(name)).is_ok() {
767            removed += 1;
768        }
769    }
770    Ok(removed)
771}
772
773/// Parse retained reports oldest-first, skipping unreadable or oversized files.
774fn read_reports(
775    directory: &Path,
776    max_reports: usize,
777    max_report_bytes: usize,
778) -> Result<Vec<CrashReport>> {
779    let mut names = report_file_names(directory)?;
780    names.sort();
781    if names.len() > max_reports {
782        names.drain(..names.len() - max_reports);
783    }
784    let mut reports = Vec::with_capacity(names.len());
785    for name in names {
786        let path = directory.join(&name);
787        let Ok(file) = File::open(&path) else {
788            continue;
789        };
790        let mut bytes = Vec::new();
791        if file
792            .take(max_report_bytes as u64 + 1)
793            .read_to_end(&mut bytes)
794            .is_err()
795            || bytes.len() > max_report_bytes
796        {
797            continue;
798        }
799        if let Ok(report) = serde_json::from_slice::<CrashReport>(&bytes) {
800            reports.push(report);
801        }
802    }
803    Ok(reports)
804}
805
806fn report_file_names(directory: &Path) -> Result<Vec<String>> {
807    let entries = match fs::read_dir(directory) {
808        Ok(entries) => entries,
809        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
810        Err(error) => return Err(io_error(error)),
811    };
812    let mut names = Vec::new();
813    for entry in entries.flatten() {
814        let Ok(name) = entry.file_name().into_string() else {
815            continue;
816        };
817        if !name.ends_with(REPORT_SUFFIX) || names.len() >= MAX_CRASH_REPORTS * 4 {
818            continue;
819        }
820        names.push(name);
821    }
822    Ok(names)
823}
824
825/// Promote non-empty signal-handler scratch files written by an earlier process run.
826///
827/// A crashed process leaves a populated `*.crash.partial`; a healthy one leaves an empty file.
828/// Empty files belonging to a process that is no longer alive are removed.
829fn promote_partial_reports(directory: &Path) -> Result<usize> {
830    let entries = match fs::read_dir(directory) {
831        Ok(entries) => entries,
832        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0),
833        Err(error) => return Err(io_error(error)),
834    };
835    let mut promoted = 0;
836    for entry in entries.flatten() {
837        let Ok(name) = entry.file_name().into_string() else {
838            continue;
839        };
840        let Some(stem) = name.strip_suffix(PARTIAL_SUFFIX) else {
841            continue;
842        };
843        let path = directory.join(&name);
844        let empty = entry
845            .metadata()
846            .map(|metadata| metadata.len() == 0)
847            .unwrap_or(true);
848        if empty {
849            if !process_is_alive(partial_process_id(stem)) {
850                let _ = fs::remove_file(&path);
851            }
852            continue;
853        }
854        if fs::rename(&path, directory.join(format!("{stem}{REPORT_SUFFIX}"))).is_ok() {
855            promoted += 1;
856        }
857    }
858    Ok(promoted)
859}
860
861fn partial_process_id(stem: &str) -> Option<u32> {
862    stem.split('-').nth(1).and_then(|value| value.parse().ok())
863}
864
865#[cfg(unix)]
866fn process_is_alive(process_id: Option<u32>) -> bool {
867    let Some(process_id) = process_id else {
868        return false;
869    };
870    if process_id == std::process::id() {
871        return true;
872    }
873    // SAFETY: `kill` with signal 0 performs an existence and permission check only.
874    unsafe { libc::kill(process_id as libc::pid_t, 0) == 0 }
875}
876
877#[cfg(not(unix))]
878fn process_is_alive(process_id: Option<u32>) -> bool {
879    process_id == Some(std::process::id())
880}
881
882// ---------------------------------------------------------------------------
883// Panic hook
884// ---------------------------------------------------------------------------
885
886fn install_panic_hook() {
887    static HOOK: OnceLock<()> = OnceLock::new();
888    HOOK.get_or_init(|| {
889        let previous = std::panic::take_hook();
890        std::panic::set_hook(Box::new(move |info| {
891            if let Some(reporter) = CrashReporter::current() {
892                let _ = reporter.record_panic(info);
893            }
894            previous(info);
895        }));
896    });
897}
898
899fn panic_message(info: &PanicHookInfo<'_>) -> String {
900    let payload = info.payload();
901    if let Some(message) = payload.downcast_ref::<&str>() {
902        (*message).to_owned()
903    } else if let Some(message) = payload.downcast_ref::<String>() {
904        message.clone()
905    } else {
906        "the process panicked with a non-string payload".to_owned()
907    }
908}
909
910fn capture_backtrace(policy: BacktracePolicy) -> Option<String> {
911    use std::backtrace::{Backtrace, BacktraceStatus};
912
913    let backtrace = match policy {
914        BacktracePolicy::Disabled => return None,
915        BacktracePolicy::Environment => Backtrace::capture(),
916        BacktracePolicy::Always => Backtrace::force_capture(),
917    };
918    if backtrace.status() != BacktraceStatus::Captured {
919        return None;
920    }
921    let text = backtrace.to_string();
922    Some(truncate_utf8(&text, MAX_CRASH_BACKTRACE_BYTES).to_owned())
923}
924
925// ---------------------------------------------------------------------------
926// Native fatal-signal path
927// ---------------------------------------------------------------------------
928
929/// Pre-rendered pieces of a native fatal-fault report.
930///
931/// The handler writes `head`, the timestamp digits, `signal_prefix`, the signal number,
932/// `name_prefix`, a static signal name, `address_prefix`, hexadecimal digits, `thread_prefix`,
933/// hexadecimal digits, and finally `tail`. No allocation, locking, or formatting machinery is
934/// involved, so every operation is async-signal-safe.
935struct SignalTemplate {
936    head: Box<[u8]>,
937    signal_prefix: &'static [u8],
938    name_prefix: &'static [u8],
939    address_prefix: &'static [u8],
940    thread_prefix: &'static [u8],
941    tail: &'static [u8],
942}
943
944impl SignalTemplate {
945    fn new(reporter: &CrashReporter, id: &str) -> Self {
946        let system = crate::SystemInfo::current();
947        let parameters = reporter.extra_parameters();
948        let mut head = String::with_capacity(512);
949        head.push_str("{\"schemaVersion\":");
950        head.push_str(&CRASH_REPORT_SCHEMA_VERSION.to_string());
951        push_field(&mut head, "id", id);
952        push_field(&mut head, "kind", CrashKind::Signal.as_str());
953        push_field(&mut head, "appName", &reporter.0.app_name);
954        push_field(&mut head, "appVersion", &reporter.0.app_version);
955        push_field(&mut head, "appIdentifier", &reporter.0.app_identifier);
956        push_field(&mut head, "operatingSystem", system.name());
957        if let Some(version) = system.version() {
958            push_field(&mut head, "operatingSystemVersion", version);
959        }
960        push_field(&mut head, "architecture", system.architecture());
961        head.push_str(",\"processId\":");
962        head.push_str(&std::process::id().to_string());
963        push_field(
964            &mut head,
965            "message",
966            "the process terminated on a fatal native fault",
967        );
968        head.push_str(",\"parameters\":{");
969        for (index, (key, value)) in parameters.iter().enumerate() {
970            if index > 0 {
971                head.push(',');
972            }
973            head.push('"');
974            head.push_str(&json_escape(key));
975            head.push_str("\":\"");
976            head.push_str(&json_escape(value));
977            head.push('"');
978        }
979        head.push_str("},\"timestamp\":\"");
980        Self {
981            head: head.into_bytes().into_boxed_slice(),
982            signal_prefix: b"\",\"signal\":",
983            name_prefix: b",\"signalName\":\"",
984            address_prefix: b"\",\"faultAddress\":\"0x",
985            thread_prefix: b"\",\"thread\":\"0x",
986            tail: b"\"}",
987        }
988    }
989}
990
991fn push_field(buffer: &mut String, key: &str, value: &str) {
992    buffer.push_str(",\"");
993    buffer.push_str(key);
994    buffer.push_str("\":\"");
995    buffer.push_str(&json_escape(value));
996    buffer.push('"');
997}
998
999fn json_escape(value: &str) -> String {
1000    let mut escaped = String::with_capacity(value.len());
1001    for character in value.chars() {
1002        match character {
1003            '"' => escaped.push_str("\\\""),
1004            '\\' => escaped.push_str("\\\\"),
1005            '\n' => escaped.push_str("\\n"),
1006            '\r' => escaped.push_str("\\r"),
1007            '\t' => escaped.push_str("\\t"),
1008            character if (character as u32) < 0x20 => {
1009                escaped.push_str(&format!("\\u{:04x}", character as u32));
1010            }
1011            character => escaped.push(character),
1012        }
1013    }
1014    escaped
1015}
1016
1017#[cfg(unix)]
1018mod native {
1019    use super::{CrashReporter, PARTIAL_SUFFIX, SignalTemplate, report_id, unix_millis};
1020    use std::{
1021        os::fd::{IntoRawFd, RawFd},
1022        sync::atomic::{AtomicBool, AtomicPtr, Ordering},
1023    };
1024
1025    /// Fatal faults QuickGUI reports. `SIGABRT` is included so aborts from the runtime and from
1026    /// double panics are recorded like hardware faults.
1027    pub(super) const FATAL_SIGNALS: [libc::c_int; 5] = [
1028        libc::SIGSEGV,
1029        libc::SIGBUS,
1030        libc::SIGILL,
1031        libc::SIGFPE,
1032        libc::SIGABRT,
1033    ];
1034
1035    pub(super) fn signal_name(signal: libc::c_int) -> &'static str {
1036        match signal {
1037            libc::SIGSEGV => "SIGSEGV",
1038            libc::SIGBUS => "SIGBUS",
1039            libc::SIGILL => "SIGILL",
1040            libc::SIGFPE => "SIGFPE",
1041            libc::SIGABRT => "SIGABRT",
1042            _ => "SIGNAL",
1043        }
1044    }
1045
1046    struct SignalState {
1047        descriptor: RawFd,
1048        template: SignalTemplate,
1049        written: AtomicBool,
1050    }
1051
1052    static STATE: AtomicPtr<SignalState> = AtomicPtr::new(std::ptr::null_mut());
1053
1054    pub(super) fn install(reporter: &CrashReporter) {
1055        if !STATE.load(Ordering::Acquire).is_null() {
1056            return;
1057        }
1058        let id = report_id(unix_millis(), std::process::id(), 0);
1059        let path = reporter.directory().join(format!("{id}{PARTIAL_SUFFIX}"));
1060        let Ok(file) = std::fs::OpenOptions::new()
1061            .create(true)
1062            .write(true)
1063            .truncate(true)
1064            .open(&path)
1065        else {
1066            return;
1067        };
1068        let state = Box::into_raw(Box::new(SignalState {
1069            descriptor: file.into_raw_fd(),
1070            template: SignalTemplate::new(reporter, &id),
1071            written: AtomicBool::new(false),
1072        }));
1073        if STATE
1074            .compare_exchange(
1075                std::ptr::null_mut(),
1076                state,
1077                Ordering::AcqRel,
1078                Ordering::Acquire,
1079            )
1080            .is_err()
1081        {
1082            // SAFETY: `state` was just created here and never published.
1083            drop(unsafe { Box::from_raw(state) });
1084            return;
1085        }
1086        // SAFETY: `action` is fully initialized before `sigaction` reads it, and the handler only
1087        // performs async-signal-safe work. `SA_RESETHAND` restores the default disposition so the
1088        // re-raise below terminates the process with the original fault.
1089        unsafe {
1090            let mut action: libc::sigaction = std::mem::zeroed();
1091            action.sa_sigaction = handle as *const () as usize;
1092            libc::sigemptyset(&raw mut action.sa_mask);
1093            action.sa_flags = libc::SA_SIGINFO | libc::SA_ONSTACK | libc::SA_RESETHAND;
1094            for signal in FATAL_SIGNALS {
1095                libc::sigaction(signal, &raw const action, std::ptr::null_mut());
1096            }
1097        }
1098    }
1099
1100    extern "C" fn handle(
1101        signal: libc::c_int,
1102        info: *mut libc::siginfo_t,
1103        _context: *mut libc::c_void,
1104    ) {
1105        let state = STATE.load(Ordering::Acquire);
1106        if !state.is_null() {
1107            // SAFETY: the pointer was published once by `install` and is never freed or replaced.
1108            let state = unsafe { &*state };
1109            if !state.written.swap(true, Ordering::AcqRel) {
1110                let address = if info.is_null() {
1111                    0
1112                } else {
1113                    // SAFETY: the kernel passes a valid `siginfo_t` for `SA_SIGINFO` handlers.
1114                    unsafe { (*info).si_addr() as usize }
1115                };
1116                // SAFETY: the thread identifier is read as an opaque integer only.
1117                let thread = unsafe { libc::pthread_self() as usize };
1118                write_report(state, signal, address, thread);
1119            }
1120        }
1121        // SAFETY: `SA_RESETHAND` already restored the default disposition for this signal.
1122        unsafe {
1123            libc::raise(signal);
1124        }
1125    }
1126
1127    fn write_report(state: &SignalState, signal: libc::c_int, address: usize, thread: usize) {
1128        let mut scratch = [0_u8; 32];
1129        write_bytes(state.descriptor, &state.template.head);
1130        // SAFETY: `time` is on the POSIX async-signal-safe list.
1131        let seconds = unsafe { libc::time(std::ptr::null_mut()) } as i64;
1132        let length = super::format_rfc3339_into(seconds, &mut scratch);
1133        write_bytes(state.descriptor, &scratch[..length]);
1134        write_bytes(state.descriptor, state.template.signal_prefix);
1135        let length = format_decimal(signal as i64, &mut scratch);
1136        write_bytes(state.descriptor, &scratch[..length]);
1137        write_bytes(state.descriptor, state.template.name_prefix);
1138        write_bytes(state.descriptor, signal_name(signal).as_bytes());
1139        write_bytes(state.descriptor, state.template.address_prefix);
1140        let length = format_hex(address, &mut scratch);
1141        write_bytes(state.descriptor, &scratch[..length]);
1142        write_bytes(state.descriptor, state.template.thread_prefix);
1143        let length = format_hex(thread, &mut scratch);
1144        write_bytes(state.descriptor, &scratch[..length]);
1145        write_bytes(state.descriptor, state.template.tail);
1146        // SAFETY: `fsync` is a plain syscall wrapper.
1147        unsafe {
1148            libc::fsync(state.descriptor);
1149        }
1150    }
1151
1152    fn write_bytes(descriptor: RawFd, bytes: &[u8]) {
1153        let mut offset = 0;
1154        while offset < bytes.len() {
1155            // SAFETY: the slice range is in bounds and `write` is async-signal-safe.
1156            let written = unsafe {
1157                libc::write(
1158                    descriptor,
1159                    bytes[offset..].as_ptr().cast(),
1160                    bytes.len() - offset,
1161                )
1162            };
1163            if written <= 0 {
1164                return;
1165            }
1166            offset += written as usize;
1167        }
1168    }
1169
1170    fn format_decimal(value: i64, out: &mut [u8; 32]) -> usize {
1171        let negative = value < 0;
1172        let mut magnitude = value.unsigned_abs();
1173        let mut digits = [0_u8; 20];
1174        let mut count = 0;
1175        loop {
1176            digits[count] = b'0' + (magnitude % 10) as u8;
1177            magnitude /= 10;
1178            count += 1;
1179            if magnitude == 0 {
1180                break;
1181            }
1182        }
1183        let mut length = 0;
1184        if negative {
1185            out[0] = b'-';
1186            length = 1;
1187        }
1188        for index in (0..count).rev() {
1189            out[length] = digits[index];
1190            length += 1;
1191        }
1192        length
1193    }
1194
1195    fn format_hex(value: usize, out: &mut [u8; 32]) -> usize {
1196        const DIGITS: &[u8; 16] = b"0123456789abcdef";
1197        let mut buffer = [0_u8; 16];
1198        let mut magnitude = value;
1199        let mut count = 0;
1200        loop {
1201            buffer[count] = DIGITS[magnitude % 16];
1202            magnitude /= 16;
1203            count += 1;
1204            if magnitude == 0 {
1205                break;
1206            }
1207        }
1208        for index in 0..count {
1209            out[index] = buffer[count - 1 - index];
1210        }
1211        count
1212    }
1213
1214    #[cfg(test)]
1215    mod tests {
1216        use super::*;
1217
1218        #[test]
1219        fn formats_decimal_and_hexadecimal_without_allocating() {
1220            let mut scratch = [0_u8; 32];
1221            let length = format_decimal(-11, &mut scratch);
1222            assert_eq!(&scratch[..length], b"-11");
1223            let length = format_decimal(0, &mut scratch);
1224            assert_eq!(&scratch[..length], b"0");
1225            let length = format_hex(0x7f_ab_cd, &mut scratch);
1226            assert_eq!(&scratch[..length], b"7fabcd");
1227            let length = format_hex(0, &mut scratch);
1228            assert_eq!(&scratch[..length], b"0");
1229        }
1230
1231        #[test]
1232        fn names_every_reported_fatal_signal() {
1233            for signal in FATAL_SIGNALS {
1234                assert_ne!(signal_name(signal), "SIGNAL");
1235            }
1236        }
1237    }
1238}
1239
1240#[cfg(windows)]
1241mod native {
1242    use super::{CrashReporter, PARTIAL_SUFFIX, SignalTemplate, report_id, unix_millis};
1243    use std::{
1244        fs::File,
1245        io::Write,
1246        sync::atomic::{AtomicBool, AtomicPtr, Ordering},
1247    };
1248    use windows_sys::Win32::{
1249        Foundation::EXCEPTION_ACCESS_VIOLATION,
1250        System::Diagnostics::Debug::{EXCEPTION_POINTERS, SetUnhandledExceptionFilter},
1251    };
1252
1253    const EXCEPTION_CONTINUE_SEARCH: i32 = 0;
1254
1255    struct SignalState {
1256        file: std::sync::Mutex<File>,
1257        template: SignalTemplate,
1258        written: AtomicBool,
1259    }
1260
1261    static STATE: AtomicPtr<SignalState> = AtomicPtr::new(std::ptr::null_mut());
1262
1263    pub(super) fn install(reporter: &CrashReporter) {
1264        if !STATE.load(Ordering::Acquire).is_null() {
1265            return;
1266        }
1267        let id = report_id(unix_millis(), std::process::id(), 0);
1268        let path = reporter.directory().join(format!("{id}{PARTIAL_SUFFIX}"));
1269        let Ok(file) = std::fs::OpenOptions::new()
1270            .create(true)
1271            .write(true)
1272            .truncate(true)
1273            .open(&path)
1274        else {
1275            return;
1276        };
1277        let state = Box::into_raw(Box::new(SignalState {
1278            file: std::sync::Mutex::new(file),
1279            template: SignalTemplate::new(reporter, &id),
1280            written: AtomicBool::new(false),
1281        }));
1282        if STATE
1283            .compare_exchange(
1284                std::ptr::null_mut(),
1285                state,
1286                Ordering::AcqRel,
1287                Ordering::Acquire,
1288            )
1289            .is_err()
1290        {
1291            // SAFETY: `state` was just created here and never published.
1292            drop(unsafe { Box::from_raw(state) });
1293            return;
1294        }
1295        // SAFETY: the filter pointer stays valid for the life of the process.
1296        unsafe {
1297            SetUnhandledExceptionFilter(Some(handle));
1298        }
1299    }
1300
1301    unsafe extern "system" fn handle(exception: *const EXCEPTION_POINTERS) -> i32 {
1302        let state = STATE.load(Ordering::Acquire);
1303        if !state.is_null() {
1304            // SAFETY: the pointer was published once by `install` and is never freed.
1305            let state = unsafe { &*state };
1306            if !state.written.swap(true, Ordering::AcqRel) {
1307                let (code, address) = if exception.is_null() {
1308                    (0_u32, 0_usize)
1309                } else {
1310                    // SAFETY: Windows passes a valid record to an unhandled-exception filter.
1311                    unsafe {
1312                        let record = (*exception).ExceptionRecord;
1313                        if record.is_null() {
1314                            (0, 0)
1315                        } else {
1316                            (
1317                                (*record).ExceptionCode as u32,
1318                                (*record).ExceptionAddress as usize,
1319                            )
1320                        }
1321                    }
1322                };
1323                write_report(state, code, address);
1324            }
1325        }
1326        EXCEPTION_CONTINUE_SEARCH
1327    }
1328
1329    fn write_report(state: &SignalState, code: u32, address: usize) {
1330        let name = if code == EXCEPTION_ACCESS_VIOLATION as u32 {
1331            "EXCEPTION_ACCESS_VIOLATION"
1332        } else {
1333            "EXCEPTION"
1334        };
1335        let Ok(mut file) = state.file.lock() else {
1336            return;
1337        };
1338        let mut bytes = Vec::with_capacity(state.template.head.len() + 128);
1339        bytes.extend_from_slice(&state.template.head);
1340        bytes.extend_from_slice(super::format_rfc3339(super::unix_seconds()).as_bytes());
1341        bytes.extend_from_slice(state.template.signal_prefix);
1342        bytes.extend_from_slice(format!("{}", code as i64).as_bytes());
1343        bytes.extend_from_slice(state.template.name_prefix);
1344        bytes.extend_from_slice(name.as_bytes());
1345        bytes.extend_from_slice(state.template.address_prefix);
1346        bytes.extend_from_slice(format!("{address:x}").as_bytes());
1347        bytes.extend_from_slice(state.template.thread_prefix);
1348        bytes.extend_from_slice(format!("{:x}", std::process::id()).as_bytes());
1349        bytes.extend_from_slice(state.template.tail);
1350        let _ = file.write_all(&bytes);
1351        let _ = file.flush();
1352    }
1353}
1354
1355#[cfg(any(unix, windows))]
1356fn install_signal_handler(reporter: &CrashReporter) {
1357    native::install(reporter);
1358}
1359
1360#[cfg(not(any(unix, windows)))]
1361fn install_signal_handler(_reporter: &CrashReporter) {}
1362
1363// ---------------------------------------------------------------------------
1364// Small shared helpers
1365// ---------------------------------------------------------------------------
1366
1367fn validate_parameter(key: String, value: String) -> Result<(String, String)> {
1368    if key.is_empty() || key.len() > MAX_CRASH_PARAMETER_KEY_BYTES || key.contains('\0') {
1369        return Err(invalid(format!(
1370            "a crash parameter key must be nonempty, NUL-free, and at most {MAX_CRASH_PARAMETER_KEY_BYTES} UTF-8 bytes"
1371        )));
1372    }
1373    if value.len() > MAX_CRASH_PARAMETER_VALUE_BYTES || value.contains('\0') {
1374        return Err(invalid(format!(
1375            "a crash parameter value must be NUL-free and at most {MAX_CRASH_PARAMETER_VALUE_BYTES} UTF-8 bytes"
1376        )));
1377    }
1378    Ok((key, value))
1379}
1380
1381fn validate_https_url(value: &str, name: &str) -> Result<()> {
1382    if value.len() > 16 * 1024 || value.contains('\0') || !value.starts_with("https://") {
1383        return Err(invalid(format!("{name} must be a bounded HTTPS URL")));
1384    }
1385    Ok(())
1386}
1387
1388fn https_agent() -> ureq::Agent {
1389    let config = ureq::Agent::config_builder().https_only(true).build();
1390    ureq::Agent::new_with_config(config)
1391}
1392
1393fn truncate_utf8(value: &str, maximum: usize) -> &str {
1394    if value.len() <= maximum {
1395        return value;
1396    }
1397    let mut end = maximum;
1398    while end > 0 && !value.is_char_boundary(end) {
1399        end -= 1;
1400    }
1401    &value[..end]
1402}
1403
1404fn unix_seconds() -> i64 {
1405    SystemTime::now()
1406        .duration_since(UNIX_EPOCH)
1407        .map(|elapsed| elapsed.as_secs() as i64)
1408        .unwrap_or_default()
1409}
1410
1411fn unix_millis() -> u64 {
1412    SystemTime::now()
1413        .duration_since(UNIX_EPOCH)
1414        .map(|elapsed| elapsed.as_millis().min(u128::from(u64::MAX)) as u64)
1415        .unwrap_or_default()
1416}
1417
1418/// `YYYY-MM-DDTHH:MM:SSZ` for a Unix timestamp, using only integer arithmetic.
1419fn format_rfc3339(seconds: i64) -> String {
1420    let mut buffer = [0_u8; 32];
1421    let length = format_rfc3339_into(seconds, &mut buffer);
1422    String::from_utf8_lossy(&buffer[..length]).into_owned()
1423}
1424
1425/// Allocation-free RFC 3339 rendering used by both the panic and the fatal-fault paths.
1426fn format_rfc3339_into(seconds: i64, out: &mut [u8; 32]) -> usize {
1427    let days = seconds.div_euclid(86_400);
1428    let remainder = seconds.rem_euclid(86_400);
1429    let (year, month, day) = civil_from_days(days);
1430    let hour = remainder / 3_600;
1431    let minute = (remainder % 3_600) / 60;
1432    let second = remainder % 60;
1433
1434    let mut index = 0;
1435    write_padded(out, &mut index, year.clamp(0, 9_999) as u64, 4);
1436    out[index] = b'-';
1437    index += 1;
1438    write_padded(out, &mut index, u64::from(month), 2);
1439    out[index] = b'-';
1440    index += 1;
1441    write_padded(out, &mut index, u64::from(day), 2);
1442    out[index] = b'T';
1443    index += 1;
1444    write_padded(out, &mut index, hour as u64, 2);
1445    out[index] = b':';
1446    index += 1;
1447    write_padded(out, &mut index, minute as u64, 2);
1448    out[index] = b':';
1449    index += 1;
1450    write_padded(out, &mut index, second as u64, 2);
1451    out[index] = b'Z';
1452    index += 1;
1453    index
1454}
1455
1456fn write_padded(out: &mut [u8; 32], index: &mut usize, value: u64, width: usize) {
1457    let mut digits = [0_u8; 20];
1458    let mut count = 0;
1459    let mut magnitude = value;
1460    loop {
1461        digits[count] = b'0' + (magnitude % 10) as u8;
1462        magnitude /= 10;
1463        count += 1;
1464        if magnitude == 0 {
1465            break;
1466        }
1467    }
1468    for _ in count..width {
1469        out[*index] = b'0';
1470        *index += 1;
1471    }
1472    for position in (0..count).rev() {
1473        out[*index] = digits[position];
1474        *index += 1;
1475    }
1476}
1477
1478/// Howard Hinnant's `civil_from_days`: days since 1970-01-01 to a proleptic Gregorian date.
1479fn civil_from_days(days: i64) -> (i64, u32, u32) {
1480    let shifted = days + 719_468;
1481    let era = shifted.div_euclid(146_097);
1482    let day_of_era = shifted.rem_euclid(146_097);
1483    let year_of_era =
1484        (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
1485    let year = year_of_era + era * 400;
1486    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
1487    let shifted_month = (5 * day_of_year + 2) / 153;
1488    let day = (day_of_year - (153 * shifted_month + 2) / 5 + 1) as u32;
1489    let month = if shifted_month < 10 {
1490        shifted_month + 3
1491    } else {
1492        shifted_month - 9
1493    } as u32;
1494    (if month <= 2 { year + 1 } else { year }, month, day)
1495}
1496
1497fn io_error(error: impl ToString) -> SystemIntegrationError {
1498    SystemIntegrationError::Platform(Arc::from(error.to_string()))
1499}
1500
1501#[cfg(test)]
1502mod tests {
1503    use super::*;
1504
1505    fn temporary_directory(label: &str) -> PathBuf {
1506        let directory = std::env::temp_dir().join(format!(
1507            "quickgui-crash-{label}-{}-{}",
1508            std::process::id(),
1509            unix_millis()
1510        ));
1511        let _ = fs::remove_dir_all(&directory);
1512        fs::create_dir_all(&directory).unwrap();
1513        directory
1514    }
1515
1516    fn reporter(directory: &Path) -> CrashReporter {
1517        let app = AppInfo::new("Crash Fixture", "1.2.3", "com.example.crash").unwrap();
1518        CrashReporter::detached(
1519            CrashReporterOptions::new(app)
1520                .directory(directory)
1521                .capture_signals(false)
1522                .max_reports(3)
1523                .unwrap(),
1524        )
1525        .unwrap()
1526    }
1527
1528    #[test]
1529    fn formats_rfc3339_timestamps_without_a_date_library() {
1530        assert_eq!(format_rfc3339(0), "1970-01-01T00:00:00Z");
1531        assert_eq!(format_rfc3339(1_700_000_000), "2023-11-14T22:13:20Z");
1532        assert_eq!(format_rfc3339(951_782_400), "2000-02-29T00:00:00Z");
1533    }
1534
1535    #[test]
1536    fn writes_and_parses_a_bounded_report() {
1537        let directory = temporary_directory("roundtrip");
1538        let reporter = reporter(&directory);
1539        reporter.add_extra_parameter("channel", "beta").unwrap();
1540        let mut report = reporter.build_report(CrashKind::Panic, "boom");
1541        report.location = Some(CrashLocation {
1542            file: "src/app.rs".to_owned(),
1543            line: 12,
1544            column: 3,
1545        });
1546        let path = reporter.capture_report(&report).unwrap();
1547        assert!(path.exists());
1548
1549        let parsed = reporter.last_crash_report().unwrap().unwrap();
1550        assert_eq!(parsed.kind, CrashKind::Panic);
1551        assert_eq!(parsed.message, "boom");
1552        assert_eq!(parsed.app_name, "Crash Fixture");
1553        assert_eq!(parsed.app_version, "1.2.3");
1554        assert_eq!(parsed.app_identifier, "com.example.crash");
1555        assert_eq!(
1556            parsed.parameters.get("channel").map(String::as_str),
1557            Some("beta")
1558        );
1559        assert_eq!(parsed.location.unwrap().line, 12);
1560        assert_eq!(parsed.schema_version, CRASH_REPORT_SCHEMA_VERSION);
1561        fs::remove_dir_all(&directory).unwrap();
1562    }
1563
1564    #[test]
1565    fn retains_only_the_newest_reports() {
1566        let directory = temporary_directory("retention");
1567        let reporter = reporter(&directory);
1568        for index in 0..8 {
1569            let report = reporter.build_report(CrashKind::Panic, format!("crash {index}"));
1570            reporter.capture_report(&report).unwrap();
1571        }
1572        let reports = reporter.pending_reports().unwrap();
1573        assert_eq!(reports.len(), 3);
1574        assert_eq!(reports[0].message, "crash 5");
1575        assert_eq!(reports[2].message, "crash 7");
1576        assert_eq!(report_file_names(&directory).unwrap().len(), 3);
1577        fs::remove_dir_all(&directory).unwrap();
1578    }
1579
1580    #[test]
1581    fn deletes_reports_by_identifier() {
1582        let directory = temporary_directory("delete");
1583        let reporter = reporter(&directory);
1584        let report = reporter.build_report(CrashKind::Panic, "boom");
1585        reporter.capture_report(&report).unwrap();
1586        assert!(reporter.delete_report(&report.id).unwrap());
1587        assert!(!reporter.delete_report(&report.id).unwrap());
1588        assert!(reporter.pending_reports().unwrap().is_empty());
1589        assert!(reporter.delete_report("../escape").is_err());
1590        fs::remove_dir_all(&directory).unwrap();
1591    }
1592
1593    #[test]
1594    fn drops_oversized_report_bodies_before_writing() {
1595        let directory = temporary_directory("oversize");
1596        let app = AppInfo::new("Crash Fixture", "1.0.0", "com.example.crash").unwrap();
1597        let reporter = CrashReporter::detached(
1598            CrashReporterOptions::new(app)
1599                .directory(&directory)
1600                .capture_signals(false)
1601                .max_report_bytes(2048)
1602                .unwrap(),
1603        )
1604        .unwrap();
1605        let mut report = reporter.build_report(CrashKind::Panic, "x".repeat(4096));
1606        report.backtrace = Some("frame\n".repeat(1024));
1607        reporter.capture_report(&report).unwrap();
1608        let stored = reporter.last_crash_report().unwrap().unwrap();
1609        assert!(stored.backtrace.is_none());
1610        assert_eq!(stored.message.len(), 1024);
1611        fs::remove_dir_all(&directory).unwrap();
1612    }
1613
1614    #[test]
1615    fn bounds_extra_parameters() {
1616        let directory = temporary_directory("parameters");
1617        let reporter = reporter(&directory);
1618        for index in 0..MAX_CRASH_EXTRA_PARAMETERS {
1619            reporter
1620                .add_extra_parameter(format!("key{index}"), "value")
1621                .unwrap();
1622        }
1623        assert!(reporter.add_extra_parameter("overflow", "value").is_err());
1624        assert!(reporter.add_extra_parameter("key0", "replacement").is_ok());
1625        assert!(reporter.add_extra_parameter("", "value").is_err());
1626        assert!(
1627            reporter
1628                .add_extra_parameter("key", "v".repeat(MAX_CRASH_PARAMETER_VALUE_BYTES + 1))
1629                .is_err()
1630        );
1631        assert!(reporter.remove_extra_parameter("key0"));
1632        assert!(!reporter.remove_extra_parameter("key0"));
1633        fs::remove_dir_all(&directory).unwrap();
1634    }
1635
1636    #[test]
1637    fn promotes_populated_partial_reports_and_removes_empty_ones() {
1638        let directory = temporary_directory("partial");
1639        let app = AppInfo::new("Crash Fixture", "1.0.0", "com.example.crash").unwrap();
1640        let template_reporter = CrashReporter::detached(
1641            CrashReporterOptions::new(app.clone())
1642                .directory(&directory)
1643                .capture_signals(false),
1644        )
1645        .unwrap();
1646        let id = report_id(1_700_000_000_000, 999_999, 0);
1647        let template = SignalTemplate::new(&template_reporter, &id);
1648        let mut bytes = Vec::new();
1649        bytes.extend_from_slice(&template.head);
1650        bytes.extend_from_slice(format_rfc3339(1_700_000_000).as_bytes());
1651        bytes.extend_from_slice(template.signal_prefix);
1652        bytes.extend_from_slice(b"11");
1653        bytes.extend_from_slice(template.name_prefix);
1654        bytes.extend_from_slice(b"SIGSEGV");
1655        bytes.extend_from_slice(template.address_prefix);
1656        bytes.extend_from_slice(b"deadbeef");
1657        bytes.extend_from_slice(template.thread_prefix);
1658        bytes.extend_from_slice(b"1f");
1659        bytes.extend_from_slice(template.tail);
1660        fs::write(directory.join(format!("{id}{PARTIAL_SUFFIX}")), &bytes).unwrap();
1661        let empty = report_id(1_700_000_000_001, 999_998, 0);
1662        fs::write(directory.join(format!("{empty}{PARTIAL_SUFFIX}")), b"").unwrap();
1663
1664        assert_eq!(promote_partial_reports(&directory).unwrap(), 1);
1665        let reports = read_reports(&directory, 16, DEFAULT_MAX_CRASH_REPORT_BYTES).unwrap();
1666        assert_eq!(reports.len(), 1);
1667        let report = &reports[0];
1668        assert_eq!(report.kind, CrashKind::Signal);
1669        assert_eq!(report.signal, Some(11));
1670        assert_eq!(report.signal_name.as_deref(), Some("SIGSEGV"));
1671        assert_eq!(report.fault_address.as_deref(), Some("0xdeadbeef"));
1672        assert_eq!(report.thread.as_deref(), Some("0x1f"));
1673        assert_eq!(report.timestamp, "2023-11-14T22:13:20Z");
1674        assert_eq!(report.app_identifier, "com.example.crash");
1675        assert!(!directory.join(format!("{empty}{PARTIAL_SUFFIX}")).exists());
1676        fs::remove_dir_all(&directory).unwrap();
1677    }
1678
1679    #[test]
1680    fn escapes_reserved_json_characters_in_the_signal_template() {
1681        let directory = temporary_directory("escape");
1682        let app = AppInfo::new("Quote \" App", "1.0.0", "com.example.crash").unwrap();
1683        let reporter = CrashReporter::detached(
1684            CrashReporterOptions::new(app)
1685                .directory(&directory)
1686                .capture_signals(false)
1687                .extra_parameter("note", "line\nbreak")
1688                .unwrap(),
1689        )
1690        .unwrap();
1691        let template = SignalTemplate::new(&reporter, "1-2-3");
1692        let head = String::from_utf8(template.head.to_vec()).unwrap();
1693        assert!(head.contains("Quote \\\" App"));
1694        assert!(head.contains("line\\nbreak"));
1695        fs::remove_dir_all(&directory).unwrap();
1696    }
1697
1698    #[test]
1699    fn rejects_plain_http_upload_endpoints_before_any_request() {
1700        let directory = temporary_directory("upload");
1701        let reporter = reporter(&directory);
1702        assert!(reporter.upload_pending("http://example.com/crash").is_err());
1703        assert_eq!(
1704            reporter
1705                .upload_pending("https://example.invalid/crash")
1706                .unwrap(),
1707            UploadSummary::default(),
1708        );
1709        let report = reporter.build_report(CrashKind::Panic, "boom");
1710        let body = CrashReporter::upload_body(&report).unwrap();
1711        let decoded: CrashReport = serde_json::from_slice(&body).unwrap();
1712        assert_eq!(decoded, report);
1713        fs::remove_dir_all(&directory).unwrap();
1714    }
1715
1716    #[test]
1717    fn watchdog_reports_one_hang_and_resets_after_a_heartbeat() {
1718        assert!(!watchdog_should_report(
1719            100,
1720            90,
1721            Duration::from_millis(50),
1722            false
1723        ));
1724        assert!(watchdog_should_report(
1725            200,
1726            90,
1727            Duration::from_millis(50),
1728            false
1729        ));
1730        assert!(!watchdog_should_report(
1731            200,
1732            90,
1733            Duration::from_millis(50),
1734            true
1735        ));
1736
1737        let directory = temporary_directory("watchdog");
1738        let reporter = reporter(&directory);
1739        let watchdog = Watchdog::start(
1740            &reporter,
1741            WatchdogOptions::default()
1742                .interval(Duration::from_millis(10))
1743                .unwrap()
1744                .hang_threshold(Duration::from_millis(20))
1745                .unwrap(),
1746        )
1747        .unwrap();
1748        let deadline = Instant::now() + Duration::from_secs(10);
1749        while Instant::now() < deadline && reporter.pending_reports().unwrap().is_empty() {
1750            std::thread::sleep(Duration::from_millis(10));
1751        }
1752        watchdog.stop();
1753        let reports = reporter.pending_reports().unwrap();
1754        assert_eq!(reports.len(), 1, "the watchdog reports a hang exactly once");
1755        assert_eq!(reports[0].kind, CrashKind::Hang);
1756        fs::remove_dir_all(&directory).unwrap();
1757    }
1758
1759    #[test]
1760    fn rejects_out_of_range_options() {
1761        let app = AppInfo::new("Crash Fixture", "1.0.0", "com.example.crash").unwrap();
1762        assert!(
1763            CrashReporterOptions::new(app.clone())
1764                .max_reports(0)
1765                .is_err()
1766        );
1767        assert!(
1768            CrashReporterOptions::new(app.clone())
1769                .max_reports(MAX_CRASH_REPORTS + 1)
1770                .is_err()
1771        );
1772        assert!(
1773            CrashReporterOptions::new(app.clone())
1774                .max_report_bytes(16)
1775                .is_err()
1776        );
1777        assert!(
1778            CrashReporterOptions::new(app.clone())
1779                .upload_endpoint("http://example.com")
1780                .is_err()
1781        );
1782        assert!(
1783            WatchdogOptions::default()
1784                .interval(Duration::from_millis(1))
1785                .is_err()
1786        );
1787        assert!(
1788            WatchdogOptions::default()
1789                .hang_threshold(Duration::from_secs(600))
1790                .is_err()
1791        );
1792        assert!(
1793            CrashReporter::detached(CrashReporterOptions::new(app).directory("relative/crashes"),)
1794                .is_err()
1795        );
1796    }
1797}