Skip to main content

egui_pop_platform/
crash.rs

1//! Crash reports, written on the machine and offered on the next start.
2//! Nothing is sent anywhere.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! [`CrashPlugin`] marks the session as running (`session-<pid>.json` in
8//! the crash directory, `<state>/crashes`) and installs a panic hook
9//! (chained to the one before it). A panic writes `panic-<pid>.json`:
10//! the application's name and version, the OS and its release, the
11//! thread, the message, where, a backtrace, the last log lines (from
12//! the app's [`crate::logs`]) and the tail of the host's journal.
13//! A clean exit (the `app.exit` step) takes the marker and the panics of
14//! the session away: a panic a fault boundary caught does not make a
15//! report.
16//!
17//! On the next start, a marker left by a session that is gone means it
18//! did not end cleanly: its panics, or a report saying it ended without
19//! closing (killed, out of memory, a crash in native code) with the last
20//! lines of its log file, become `report-<time>-<pid>.json`, and the
21//! step runs (ADR 0011):
22//!
23//! - `crash.report`: a report to offer, `{ "path", "report" }`. By
24//!   default the report (with whatever a before-hook added by
25//!   redirecting it) is written back and offered in a toast that stays,
26//!   with a button showing the file (`crash.reveal`). An application
27//!   adds data with a before-hook, sends it with an after-hook (its own
28//!   service, after asking the user), or replaces it with a dialog of
29//!   its own.
30//!
31//! The reports stay until dismissed (`crash.dismiss`, [`Crashes`]).
32//!
33//! ```
34//! use egui_pop_api::App;
35//! use egui_pop_api::toasts::{TOASTS, ToastsPlugin};
36//! use egui_pop_platform::crash::{self, CrashPlugin, Report};
37//!
38//! let dir = std::env::temp_dir().join(format!("egui-pop-crash-doc-{}", std::process::id()));
39//! // A session that died: its marker and its panic stay.
40//! crash::simulate(&dir, 4_000_000, &Report::panic("Demo", "1.0", "index out of bounds"))
41//!     .unwrap();
42//! let ctx = egui::Context::default();
43//! let mut app = App::builder()
44//!     .plugin(ToastsPlugin)
45//!     .plugin(CrashPlugin::new("Demo", "1.0").dir(&dir).hook(false))
46//!     .build(&ctx)
47//!     .unwrap();
48//! app.logic(&ctx);
49//! let toasts = app.handle().service(&TOASTS).unwrap();
50//! assert!(toasts.shown()[0].toast.text.contains("closed unexpectedly"));
51//! # std::fs::remove_dir_all(&dir).unwrap();
52//! ```
53
54use std::collections::VecDeque;
55use std::path::{Path, PathBuf};
56use std::sync::{Arc, Mutex, RwLock};
57
58use egui_pop_api::app::STEP_EXIT;
59use egui_pop_api::hooks::On;
60use egui_pop_api::services::ServiceToken;
61use egui_pop_api::steps::StepSpec;
62use egui_pop_api::toasts::{TOASTS, Toast};
63use egui_pop_api::{AppHandle, Ctx, Plugin, PluginError};
64use egui_pop_core::lock;
65use egui_pop_core::strings;
66use egui_pop_model::commands::CommandSpec;
67use egui_pop_model::ids::{CommandId, PluginId, StepId};
68use serde::{Deserialize, Serialize};
69use serde_json::{Value as Json, json};
70
71/// The plugin's id.
72pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.crash");
73/// A report to offer: `{ "path", "report" }`.
74pub const STEP_REPORT: StepId = StepId::from_static("crash.report");
75/// Shows a report's file (`{ "path" }`).
76pub const CMD_REVEAL: CommandId = CommandId::from_static("crash.reveal");
77/// Deletes a report (`{ "path" }`).
78pub const CMD_DISMISS: CommandId = CommandId::from_static("crash.dismiss");
79/// The reports, as a service.
80pub const CRASHES: ServiceToken<Crashes> = ServiceToken::new("platform.crashes");
81/// How many journal events a report quotes.
82pub const JOURNAL_TAIL: usize = 50;
83/// How many log lines a report quotes.
84pub const LOG_TAIL: usize = 100;
85
86/// One panic.
87#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
88pub struct Panic {
89    pub time: String,
90    pub thread: String,
91    pub message: String,
92    /// `file:line:column`.
93    pub location: String,
94    pub backtrace: String,
95}
96
97/// A crash report.
98#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
99pub struct Report {
100    pub app: String,
101    pub version: String,
102    /// `linux`, `windows`, `macos`.
103    pub os: String,
104    pub arch: String,
105    /// The OS's own name for itself (`Fedora Linux 44`), when known.
106    pub os_release: String,
107    pub pid: u32,
108    /// When the session started.
109    pub started: String,
110    /// `panic`, or `ended` (the session went without closing and without
111    /// a panic: killed, out of memory, a crash in native code).
112    pub kind: String,
113    /// The panics, first to last (a report's message is the last one's).
114    pub panics: Vec<Panic>,
115    /// The last log lines.
116    pub log: Vec<String>,
117    /// The tail of the host's journal.
118    pub journal: Vec<Json>,
119    /// What the application added (a before-hook on `crash.report`).
120    #[serde(default)]
121    pub extra: Json,
122}
123
124impl Report {
125    /// A report for this machine, without panics yet.
126    pub fn new(app: &str, version: &str) -> Report {
127        Report {
128            app: app.into(),
129            version: version.into(),
130            os: std::env::consts::OS.into(),
131            arch: std::env::consts::ARCH.into(),
132            os_release: os_release(),
133            pid: crate::dirs::pid(),
134            started: crate::logs::now(),
135            kind: "ended".into(),
136            ..Report::default()
137        }
138    }
139
140    /// A report of one panic with `message`, for tests and the gallery.
141    pub fn panic(app: &str, version: &str, message: &str) -> Report {
142        let mut r = Report::new(app, version);
143        r.kind = "panic".into();
144        r.panics.push(Panic {
145            time: crate::logs::now(),
146            thread: "main".into(),
147            message: message.into(),
148            location: "src/main.rs:1:1".into(),
149            backtrace: String::new(),
150        });
151        r
152    }
153
154    /// What the report says in one line.
155    pub fn summary(&self) -> String {
156        match self.panics.last() {
157            Some(p) => format!("{} at {}", p.message, p.location),
158            None => "it ended without closing".into(),
159        }
160    }
161}
162
163/// The OS's name for itself: `PRETTY_NAME` of `/etc/os-release` on
164/// Linux, empty elsewhere.
165fn os_release() -> String {
166    if cfg!(target_os = "linux") {
167        std::fs::read_to_string("/etc/os-release")
168            .ok()
169            .and_then(|t| {
170                t.lines()
171                    .find_map(|l| l.strip_prefix("PRETTY_NAME="))
172                    .map(|v| v.trim_matches('"').to_string())
173            })
174            .unwrap_or_default()
175    } else {
176        String::new()
177    }
178}
179
180fn session_file(dir: &Path, pid: u32) -> PathBuf {
181    dir.join(format!("session-{pid}.json"))
182}
183
184fn panic_file(dir: &Path, pid: u32) -> PathBuf {
185    dir.join(format!("panic-{pid}.json"))
186}
187
188/// Whether a process still runs (Linux; elsewhere a session left is
189/// taken as gone).
190fn alive(pid: u32) -> bool {
191    pid == crate::dirs::pid()
192        || (cfg!(target_os = "linux") && Path::new(&format!("/proc/{pid}")).exists())
193}
194
195fn write_json(path: &Path, value: &impl Serialize) -> std::io::Result<()> {
196    let text = serde_json::to_string_pretty(value).map_err(std::io::Error::other)?;
197    let tmp = path.with_extension("tmp");
198    std::fs::write(&tmp, text)?;
199    std::fs::rename(tmp, path)
200}
201
202/// Leaves what a session that died leaves: its marker, and its panic
203/// when `report` has one (for tests and the gallery; `pid` should name
204/// no running process).
205pub fn simulate(dir: &Path, pid: u32, report: &Report) -> std::io::Result<()> {
206    std::fs::create_dir_all(dir)?;
207    let mut r = report.clone();
208    r.pid = pid;
209    write_json(&session_file(dir, pid), &r)?;
210    if !r.panics.is_empty() {
211        write_json(&panic_file(dir, pid), &r)?;
212    }
213    Ok(())
214}
215
216/// The last lines of a text file.
217fn last_lines(path: &Path, n: usize) -> Vec<String> {
218    std::fs::read_to_string(path)
219        .map(|t| {
220            let lines: Vec<&str> = t.lines().collect();
221            lines[lines.len().saturating_sub(n)..]
222                .iter()
223                .map(|l| l.to_string())
224                .collect()
225        })
226        .unwrap_or_default()
227}
228
229/// Turns the sessions that died into reports: returns the reports'
230/// files, newest last.
231pub fn collect(dir: &Path, log_file: Option<&Path>) -> Vec<PathBuf> {
232    let Ok(entries) = std::fs::read_dir(dir) else {
233        return Vec::new();
234    };
235    let mut out = Vec::new();
236    for e in entries.flatten() {
237        let name = e.file_name().to_string_lossy().into_owned();
238        let Some(pid) = name
239            .strip_prefix("session-")
240            .and_then(|r| r.strip_suffix(".json"))
241            .and_then(|p| p.parse::<u32>().ok())
242        else {
243            continue;
244        };
245        if alive(pid) {
246            continue;
247        }
248        let session: Option<Report> = std::fs::read_to_string(e.path())
249            .ok()
250            .and_then(|t| serde_json::from_str(&t).ok());
251        let panicked: Option<Report> = std::fs::read_to_string(panic_file(dir, pid))
252            .ok()
253            .and_then(|t| serde_json::from_str(&t).ok());
254        let report = match (panicked, session) {
255            (Some(r), _) => r,
256            (None, Some(mut r)) => {
257                r.kind = "ended".into();
258                if let Some(log) = log_file {
259                    r.log = last_lines(log, LOG_TAIL);
260                }
261                r
262            }
263            (None, None) => continue,
264        };
265        let stamp = crate::logs::now().replace([':', '.'], "-");
266        let path = dir.join(format!("report-{stamp}-{pid}.json"));
267        if write_json(&path, &report).is_ok() {
268            let _ = std::fs::remove_file(e.path());
269            let _ = std::fs::remove_file(panic_file(dir, pid));
270            out.push(path);
271        }
272    }
273    out.sort();
274    out
275}
276
277/// What the panic hook reads: this session's report so far, where to
278/// write it and the app's logs. Shared with the hook (process-wide).
279#[derive(Debug, Default)]
280struct HookState {
281    dir: Option<PathBuf>,
282    report: Report,
283    journal: VecDeque<Json>,
284    #[cfg(feature = "logs")]
285    logs: Option<crate::logs::Logs>,
286}
287
288static HOOK: RwLock<Option<Arc<Mutex<HookState>>>> = RwLock::new(None);
289
290/// Installs the panic hook once per process (chained to the one before).
291fn install_hook() {
292    static ONCE: std::sync::Once = std::sync::Once::new();
293    ONCE.call_once(|| {
294        let previous = std::panic::take_hook();
295        std::panic::set_hook(Box::new(move |info| {
296            write_panic(info);
297            previous(info);
298        }));
299    });
300}
301
302/// Writes the panic into this session's panic file. Never blocks: a
303/// state held elsewhere is skipped.
304fn write_panic(info: &std::panic::PanicHookInfo<'_>) {
305    let Some(state) = HOOK.try_read().ok().and_then(|h| h.clone()) else {
306        return;
307    };
308    let Ok(mut s) = state.try_lock() else {
309        return;
310    };
311    let Some(dir) = s.dir.clone() else {
312        return;
313    };
314    let message = if let Some(m) = info.payload().downcast_ref::<&str>() {
315        (*m).to_string()
316    } else if let Some(m) = info.payload().downcast_ref::<String>() {
317        m.clone()
318    } else {
319        "a panic without a message".into()
320    };
321    let panic = Panic {
322        time: crate::logs::now(),
323        thread: std::thread::current()
324            .name()
325            .unwrap_or("unnamed")
326            .to_string(),
327        message,
328        location: info
329            .location()
330            .map(|l| format!("{}:{}:{}", l.file(), l.line(), l.column()))
331            .unwrap_or_default(),
332        backtrace: std::backtrace::Backtrace::force_capture().to_string(),
333    };
334    s.report.kind = "panic".into();
335    s.report.panics.push(panic);
336    #[cfg(feature = "logs")]
337    if let Some(l) = s.logs.clone() {
338        let tail = l.tail();
339        s.report.log = tail[tail.len().saturating_sub(LOG_TAIL)..].to_vec();
340        l.flush();
341    }
342    s.report.journal = s.journal.iter().cloned().collect();
343    let _ = std::fs::create_dir_all(&dir);
344    let _ = write_json(&panic_file(&dir, s.report.pid), &s.report);
345}
346
347/// The reports on this machine, as a service.
348#[derive(Clone, Debug)]
349pub struct Crashes {
350    dir: PathBuf,
351    log_file: Option<PathBuf>,
352    pending: Arc<Mutex<Vec<PathBuf>>>,
353}
354
355impl Crashes {
356    /// The crash directory.
357    pub fn dir(&self) -> &Path {
358        &self.dir
359    }
360
361    /// The reports kept, oldest first.
362    pub fn reports(&self) -> Vec<PathBuf> {
363        let mut out: Vec<PathBuf> = std::fs::read_dir(&self.dir)
364            .map(|d| {
365                d.flatten()
366                    .map(|e| e.path())
367                    .filter(|p| {
368                        p.file_name()
369                            .is_some_and(|n| n.to_string_lossy().starts_with("report-"))
370                    })
371                    .collect()
372            })
373            .unwrap_or_default();
374        out.sort();
375        out
376    }
377
378    /// A report, read.
379    pub fn read(&self, path: &Path) -> Option<Report> {
380        serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
381    }
382
383    /// Deletes a report.
384    pub fn dismiss(&self, path: &Path) -> Result<(), String> {
385        if path.parent() != Some(self.dir.as_path()) {
386            return Err(format!("{} is not a report", path.display()));
387        }
388        std::fs::remove_file(path).map_err(|e| e.to_string())
389    }
390
391    /// Looks for sessions that died again (the plugin does at start);
392    /// their reports are offered at the next pass.
393    pub fn scan(&self) -> usize {
394        let found = collect(&self.dir, self.log_file.as_deref());
395        let n = found.len();
396        lock(&self.pending).extend(found);
397        n
398    }
399}
400
401/// Runs `crash.report` for a report's file.
402fn offer(app: &AppHandle, crashes: &Crashes, path: &Path) {
403    let Some(report) = crashes.read(path) else {
404        return;
405    };
406    let args = json!({ "path": path, "report": report });
407    app.step(&STEP_REPORT, args, |app, args| {
408        let path = PathBuf::from(args["path"].as_str().unwrap_or_default());
409        // What a before-hook added stays with the report.
410        if let Ok(report) = serde_json::from_value::<Report>(args["report"].clone()) {
411            write_json(&path, &report).map_err(|e| e.to_string())?;
412        }
413        let toasts = app
414            .service(&TOASTS)
415            .ok_or("no toasts to offer the report in")?;
416        let app_name = args["report"]["app"].as_str().unwrap_or_default();
417        let ctx = app.egui();
418        toasts.notify(
419            Toast::warning(&strings::tr_args(
420                &ctx,
421                &crate::strings::CRASH_OFFER,
422                &[("app", app_name)],
423            ))
424            .sticky()
425            .action(
426                &strings::tr(&ctx, &crate::strings::CRASH_SHOW),
427                CMD_REVEAL,
428                json!({ "path": path }),
429            ),
430        );
431        Ok(json!({ "offered": true, "path": path }))
432    });
433}
434
435/// Crash reports, as a plugin (see the module).
436#[derive(Debug)]
437pub struct CrashPlugin {
438    app: String,
439    version: String,
440    dir: Option<PathBuf>,
441    hook: bool,
442    state: Option<Arc<Mutex<HookState>>>,
443}
444
445impl CrashPlugin {
446    /// For the application `app` (its name or id) at `version`
447    /// (`env!("CARGO_PKG_VERSION")`), in [`crate::dirs::crash_dir`].
448    pub fn new(app: &str, version: &str) -> Self {
449        Self {
450            app: app.into(),
451            version: version.into(),
452            dir: None,
453            hook: true,
454            state: None,
455        }
456    }
457
458    /// Another crash directory.
459    pub fn dir(mut self, dir: impl Into<PathBuf>) -> Self {
460        self.dir = Some(dir.into());
461        self
462    }
463
464    /// Whether to install the panic hook (on by default; tests turn it
465    /// off, their panics being failures).
466    pub fn hook(mut self, on: bool) -> Self {
467        self.hook = on;
468        self
469    }
470}
471
472impl Plugin for CrashPlugin {
473    fn id(&self) -> PluginId {
474        PLUGIN
475    }
476
477    fn title(&self) -> String {
478        "Crash reports".into()
479    }
480
481    fn priority(&self) -> i32 {
482        // Early, after the logs: the others' connecting is covered.
483        190
484    }
485
486    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
487        let dir = self
488            .dir
489            .clone()
490            .or_else(|| crate::dirs::crash_dir(&self.app))
491            .unwrap_or_else(|| crate::dirs::temp_dir().join(&self.app).join("crashes"));
492        ctx.step(
493            StepSpec::new(
494                STEP_REPORT,
495                "A crash report from the last session is offered (`path`, `report`); a before-hook may add to `report.extra`, an after-hook may send it.",
496            )
497            .args(json!({ "path": "report.json", "report": { "app": "Demo", "kind": "panic" } })),
498        )?;
499        // The app's own logs, not the process's: several apps in one
500        // process (tests) each quote theirs.
501        #[cfg(feature = "logs")]
502        let logs = ctx.app().service(&crate::logs::LOGS).map(|l| (*l).clone());
503        let log_file = None::<PathBuf>;
504        #[cfg(feature = "logs")]
505        let log_file = log_file.or_else(|| logs.as_ref().map(|l| l.path().to_path_buf()));
506        let crashes = Crashes {
507            dir: dir.clone(),
508            log_file,
509            pending: Arc::default(),
510        };
511        crashes.scan();
512        ctx.service(&CRASHES, crashes.clone())?;
513        let reveal = crashes.clone();
514        ctx.command(
515            CommandSpec::new(CMD_REVEAL, "Show a crash report", "Help")
516                .description("Opens a crash report's file (`path`).")
517                .args(json!({ "path": "report.json" }))
518                .hidden(),
519            move |call| {
520                let path = PathBuf::from(call.args["path"].as_str().ok_or("`path` is missing")?);
521                if path.parent() != Some(reveal.dir()) {
522                    return Err(format!("{} is not a report", path.display()));
523                }
524                crate::dirs::reveal(&path)?;
525                Ok(json!({ "path": path }))
526            },
527        )?;
528        let dismiss = crashes.clone();
529        ctx.command(
530            CommandSpec::new(CMD_DISMISS, "Delete a crash report", "Help")
531                .icon("delete")
532                .description("Deletes a crash report (`path`).")
533                .args(json!({ "path": "report.json" }))
534                .hidden(),
535            move |call| {
536                let path = PathBuf::from(call.args["path"].as_str().ok_or("`path` is missing")?);
537                dismiss.dismiss(&path)?;
538                Ok(json!({ "dismissed": path }))
539            },
540        )?;
541        // This session runs: its marker says so until a clean exit.
542        let report = Report::new(&self.app, &self.version);
543        // Without a place to write (a read-only home), panics still reach
544        // the hook before it, and nothing is offered. The web has no file
545        // system: the marker is not tried there, and nothing is logged.
546        #[cfg(not(target_arch = "wasm32"))]
547        if let Err(e) = std::fs::create_dir_all(&dir)
548            .and_then(|()| write_json(&session_file(&dir, report.pid), &report))
549        {
550            log::warn!(target: "egui_pop", "crash reports: {}: {e}", dir.display());
551        }
552        let state = Arc::new(Mutex::new(HookState {
553            dir: Some(dir.clone()),
554            report,
555            journal: VecDeque::new(),
556            #[cfg(feature = "logs")]
557            logs,
558        }));
559        // The hook is the process's: only an app that installs it is
560        // written to, not one that turned it off (a test beside others).
561        if self.hook {
562            *HOOK
563                .write()
564                .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(state.clone());
565            install_hook();
566        }
567        self.state = Some(state.clone());
568        let mut seen = 0;
569        ctx.on(On::Pass, move |app, _| {
570            // The journal's tail, for the hook.
571            let events = app.events_since(seen);
572            if let Some(last) = events.last() {
573                seen = last.seq;
574                let mut s = lock(&state);
575                for e in events {
576                    s.journal.push_back(json!({
577                        "seq": e.seq, "source": e.source, "name": e.name, "data": e.data,
578                    }));
579                }
580                while s.journal.len() > JOURNAL_TAIL {
581                    s.journal.pop_front();
582                }
583            }
584            let pending: Vec<PathBuf> = lock(&crashes.pending).drain(..).collect();
585            for path in pending {
586                offer(app, &crashes, &path);
587            }
588        });
589        let pid = crate::dirs::pid();
590        ctx.after(STEP_EXIT, move |_, _, _| {
591            let _ = std::fs::remove_file(session_file(&dir, pid));
592            let _ = std::fs::remove_file(panic_file(&dir, pid));
593        });
594        Ok(())
595    }
596
597    fn disconnect(&mut self, _ctx: &mut Ctx<'_>) {
598        if let Some(state) = self.state.take() {
599            let mut hook = HOOK
600                .write()
601                .unwrap_or_else(std::sync::PoisonError::into_inner);
602            if hook.as_ref().is_some_and(|h| Arc::ptr_eq(h, &state)) {
603                *hook = None;
604            }
605            let s = lock(&state);
606            if let Some(dir) = &s.dir {
607                let _ = std::fs::remove_file(session_file(dir, s.report.pid));
608                let _ = std::fs::remove_file(panic_file(dir, s.report.pid));
609            }
610        }
611    }
612}