BlueGit

ict rusty-teams

Files

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

native_dumps.rs

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