BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / native_dumps.rs

native_dumps.rs

native_dumps.rs 10.3 KiB Download Raw
1use std::path::PathBuf;
2
3#[cfg(windows)]
4pub fn install(directory: PathBuf, crash_log: PathBuf) {
5 windows_impl::install(directory, crash_log);
6}
7
8#[cfg(not(windows))]
9pub fn install(_directory: PathBuf, _crash_log: PathBuf) {}
10
11#[cfg(windows)]
12pub fn heartbeat() {
13 windows_impl::heartbeat();
14}
15
16#[cfg(not(windows))]
17pub fn heartbeat() {}
18
19#[cfg(any(windows, test))]
20mod policy {
21 use std::time::{Duration, SystemTime};
22
23 pub struct StallDetector {
24 threshold: Duration,
25 reported: bool,
26 }
27
28 impl StallDetector {
29 pub fn new(threshold: Duration) -> Self {
30 Self {
31 threshold,
32 reported: false,
33 }
34 }
35
36 pub fn observe(&mut self, heartbeat_age: Option<Duration>) -> Option<Duration> {
37 let age = heartbeat_age?;
38 if age < self.threshold {
39 self.reported = false;
40 return None;
41 }
42 if self.reported {
43 return None;
44 }
45 self.reported = true;
46 Some(age)
47 }
48 }
49
50 pub fn dumps_to_delete(
51 mut dumps: Vec<(String, SystemTime)>,
52 maximum_after_write: usize,
53 ) -> Vec<String> {
54 let keep = maximum_after_write.saturating_sub(1);
55 if dumps.len() <= keep {
56 return Vec::new();
57 }
58 dumps.sort_by(|left, right| left.1.cmp(&right.1).then_with(|| left.0.cmp(&right.0)));
59 let surplus = dumps.len() - keep;
60 dumps.into_iter().take(surplus).map(|dump| dump.0).collect()
61 }
62}
63
64#[cfg(windows)]
65mod windows_impl {
66 use std::fs::{self, File, OpenOptions};
67 use std::io::Write;
68 use std::os::windows::io::AsRawHandle;
69 use std::path::{Path, PathBuf};
70 use std::sync::OnceLock;
71 use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
72 use std::time::{Duration, Instant, SystemTime};
73
74 use windows::Win32::Foundation::HANDLE;
75 use windows::Win32::System::Diagnostics::Debug::{
76 EXCEPTION_POINTERS, MINIDUMP_EXCEPTION_INFORMATION, MINIDUMP_TYPE,
77 MiniDumpWithIndirectlyReferencedMemory, MiniDumpWithThreadInfo,
78 MiniDumpWithUnloadedModules, MiniDumpWriteDump, SetUnhandledExceptionFilter,
79 };
80 use windows::Win32::System::Threading::{
81 GetCurrentProcess, GetCurrentProcessId, GetCurrentThreadId,
82 };
83 use windows::core::BOOL;
84
85 use super::policy::{StallDetector, dumps_to_delete};
86
87 const EXCEPTION_CONTINUE_SEARCH: i32 = 0;
88 const HANG_THRESHOLD: Duration = Duration::from_secs(10);
89 const MAX_DUMP_FILES: usize = 5;
90 const WATCHDOG_INTERVAL: Duration = Duration::from_secs(1);
91
92 struct Paths {
93 directory: PathBuf,
94 crash_log: PathBuf,
95 }
96
97 static PATHS: OnceLock<Paths> = OnceLock::new();
98 static STARTED: OnceLock<Instant> = OnceLock::new();
99 static LAST_HEARTBEAT_MILLIS: AtomicU64 = AtomicU64::new(0);
100 static WRITING: AtomicBool = AtomicBool::new(false);
101
102 pub fn install(directory: PathBuf, crash_log: PathBuf) {
103 if fs::create_dir_all(&directory).is_err() {
104 return;
105 }
106 if PATHS
107 .set(Paths {
108 directory,
109 crash_log,
110 })
111 .is_err()
112 {
113 return;
114 }
115 STARTED.get_or_init(Instant::now);
116 unsafe {
117 SetUnhandledExceptionFilter(Some(exception_filter));
118 libc::signal(libc::SIGABRT, abort_handler as *const () as usize);
119 }
120 let _ = std::thread::Builder::new()
121 .name("hang-watchdog".to_owned())
122 .spawn(watch_for_hangs);
123 }
124
125 pub fn heartbeat() {
126 let elapsed = STARTED.get_or_init(Instant::now).elapsed();
127 LAST_HEARTBEAT_MILLIS.store(elapsed.as_millis() as u64 + 1, Ordering::Relaxed);
128 }
129
130 fn heartbeat_age() -> Option<Duration> {
131 let stored = LAST_HEARTBEAT_MILLIS.load(Ordering::Relaxed);
132 if stored == 0 {
133 return None;
134 }
135 let elapsed = STARTED.get()?.elapsed();
136 Some(elapsed.saturating_sub(Duration::from_millis(stored - 1)))
137 }
138
139 fn watch_for_hangs() {
140 let mut detector = StallDetector::new(HANG_THRESHOLD);
141 loop {
142 std::thread::sleep(WATCHDOG_INTERVAL);
143 let Some(stalled_for) = detector.observe(heartbeat_age()) else {
144 continue;
145 };
146 if let Some(file_name) = write_dump("hang", None) {
147 append_crash_log(&format!("hang {}s dump {file_name}", stalled_for.as_secs()));
148 }
149 }
150 }
151
152 unsafe extern "system" fn exception_filter(pointers: *const EXCEPTION_POINTERS) -> i32 {
153 let code = unsafe {
154 pointers
155 .as_ref()
156 .and_then(|pointers| pointers.ExceptionRecord.as_ref())
157 .map(|record| record.ExceptionCode.0)
158 .unwrap_or_default()
159 };
160 if let Some(file_name) = write_dump("crash", Some(pointers)) {
161 append_crash_log(&format!("native crash 0x{code:08x} dump {file_name}"));
162 }
163 EXCEPTION_CONTINUE_SEARCH
164 }
165
166 extern "C" fn abort_handler(_signal: i32) {
167 if let Some(file_name) = write_dump("abort", None) {
168 append_crash_log(&format!("abort dump {file_name}"));
169 }
170 unsafe {
171 libc::signal(libc::SIGABRT, libc::SIG_DFL);
172 libc::abort();
173 }
174 }
175
176 fn write_dump(prefix: &str, pointers: Option<*const EXCEPTION_POINTERS>) -> Option<String> {
177 let paths = PATHS.get()?;
178 if WRITING.swap(true, Ordering::SeqCst) {
179 return None;
180 }
181 let file_name = write_dump_file(paths, prefix, pointers);
182 WRITING.store(false, Ordering::SeqCst);
183 file_name
184 }
185
186 fn write_dump_file(
187 paths: &Paths,
188 prefix: &str,
189 pointers: Option<*const EXCEPTION_POINTERS>,
190 ) -> Option<String> {
191 prune_dumps(&paths.directory);
192 let file_name = format!(
193 "{prefix}-{}.dmp",
194 chrono::Utc::now().format("%Y%m%dT%H%M%SZ")
195 );
196 let file = File::create(paths.directory.join(&file_name)).ok()?;
197 let mut exception_information = pointers.map(|pointers| MINIDUMP_EXCEPTION_INFORMATION {
198 ThreadId: unsafe { GetCurrentThreadId() },
199 ExceptionPointers: pointers as *mut EXCEPTION_POINTERS,
200 ClientPointers: BOOL(0),
201 });
202 let exception_parameter = exception_information
203 .as_mut()
204 .map(|information| information as *const MINIDUMP_EXCEPTION_INFORMATION);
205 let dump_type = MINIDUMP_TYPE(
206 MiniDumpWithThreadInfo.0
207 | MiniDumpWithUnloadedModules.0
208 | MiniDumpWithIndirectlyReferencedMemory.0,
209 );
210 let written = unsafe {
211 MiniDumpWriteDump(
212 GetCurrentProcess(),
213 GetCurrentProcessId(),
214 HANDLE(file.as_raw_handle()),
215 dump_type,
216 exception_parameter,
217 None,
218 None,
219 )
220 };
221 written.ok().map(|_| file_name)
222 }
223
224 fn prune_dumps(directory: &Path) {
225 let Ok(entries) = fs::read_dir(directory) else {
226 return;
227 };
228 let dumps = entries
229 .flatten()
230 .filter(|entry| {
231 entry
232 .path()
233 .extension()
234 .is_some_and(|extension| extension == "dmp")
235 })
236 .map(|entry| {
237 let modified = entry
238 .metadata()
239 .and_then(|metadata| metadata.modified())
240 .unwrap_or(SystemTime::UNIX_EPOCH);
241 (entry.file_name().to_string_lossy().into_owned(), modified)
242 })
243 .collect();
244 for file_name in dumps_to_delete(dumps, MAX_DUMP_FILES) {
245 let _ = fs::remove_file(directory.join(file_name));
246 }
247 }
248
249 fn append_crash_log(detail: &str) {
250 let Some(paths) = PATHS.get() else {
251 return;
252 };
253 if let Ok(mut file) = OpenOptions::new()
254 .create(true)
255 .append(true)
256 .open(&paths.crash_log)
257 {
258 let _ = writeln!(
259 file,
260 "=== {} build {} {detail}",
261 chrono::Utc::now().to_rfc3339(),
262 crate::version::build_version(),
263 );
264 }
265 }
266}
267
268#[cfg(test)]
269mod tests {
270 use std::time::{Duration, SystemTime};
271
272 use super::policy::{StallDetector, dumps_to_delete};
273
274 fn seconds(value: u64) -> Option<Duration> {
275 Some(Duration::from_secs(value))
276 }
277
278 #[test]
279 fn no_report_before_first_heartbeat() {
280 let mut detector = StallDetector::new(Duration::from_secs(10));
281 assert_eq!(detector.observe(None), None);
282 }
283
284 #[test]
285 fn reports_once_after_threshold() {
286 let mut detector = StallDetector::new(Duration::from_secs(10));
287 assert_eq!(detector.observe(seconds(9)), None);
288 assert_eq!(detector.observe(seconds(10)), seconds(10));
289 assert_eq!(detector.observe(seconds(11)), None);
290 assert_eq!(detector.observe(seconds(30)), None);
291 }
292
293 #[test]
294 fn rearms_after_heartbeats_resume() {
295 let mut detector = StallDetector::new(Duration::from_secs(10));
296 assert_eq!(detector.observe(seconds(12)), seconds(12));
297 assert_eq!(detector.observe(seconds(1)), None);
298 assert_eq!(detector.observe(seconds(15)), seconds(15));
299 }
300
301 fn dump(name: &str, age: u64) -> (String, SystemTime) {
302 (
303 name.to_owned(),
304 SystemTime::UNIX_EPOCH + Duration::from_secs(age),
305 )
306 }
307
308 #[test]
309 fn keeps_room_for_the_new_dump() {
310 let dumps = vec![
311 dump("e.dmp", 5),
312 dump("a.dmp", 1),
313 dump("c.dmp", 3),
314 dump("b.dmp", 2),
315 dump("d.dmp", 4),
316 ];
317 assert_eq!(dumps_to_delete(dumps, 5), vec!["a.dmp".to_owned()]);
318 }
319
320 #[test]
321 fn deletes_nothing_below_the_limit() {
322 let dumps = vec![dump("a.dmp", 1), dump("b.dmp", 2)];
323 assert!(dumps_to_delete(dumps, 5).is_empty());
324 }
325
326 #[test]
327 fn deletes_all_surplus_oldest_first() {
328 let dumps = (1..=8)
329 .map(|age| dump(&format!("{age}.dmp"), age))
330 .collect();
331 assert_eq!(
332 dumps_to_delete(dumps, 5),
333 vec!["1.dmp", "2.dmp", "3.dmp", "4.dmp"]
334 );
335 }
336}