feat(diagnostics): write minidumps on native crash, abort and UI hang
- Unhandled exception filter and SIGABRT handler write a dump to native-dumps/ and a crash.log line - Watchdog writes one hang dump when the UI heartbeat stalls for 10 s - Keeps the 5 newest dumps Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -316,6 +316,7 @@ dependencies = [
316
316
"futures-util",
317
317
"gpui-kit",
318
318
"image",
319
"libc",
319
320
"log",
320
321
"mcp",
321
322
"raw-window-handle",
@@ -4075,6 +4076,8 @@ dependencies = [
4075
4076
[[package]]
4076
4077
name = "gpui-pre-windows"
4077
4078
version = "0.3.8"
4079
source = "registry+https://github.com/rust-lang/crates.io-index"
4080
checksum = "371f9bb13f97e3bea2f8b8e5e81232bb74d735153c244ae67f7400e743925b1c"
4078
4081
dependencies = [
4079
4082
"accesskit",
4080
4083
"accesskit_windows",
@@ -316,6 +316,7 @@ dependencies = [316
"futures-util",316
"futures-util",317
"gpui-kit",317
"gpui-kit",318
"image",318
"image",319
"libc",319
"log",320
"log",320
"mcp",321
"mcp",321
"raw-window-handle",322
"raw-window-handle",@@ -4075,6 +4076,8 @@ dependencies = [4075
[[package]]4076
[[package]]4076
name = "gpui-pre-windows"4077
name = "gpui-pre-windows"4077
version = "0.3.8"4078
version = "0.3.8"4079
source = "registry+https://github.com/rust-lang/crates.io-index"4080
checksum = "371f9bb13f97e3bea2f8b8e5e81232bb74d735153c244ae67f7400e743925b1c"4078
dependencies = [4081
dependencies = [4079
"accesskit",4082
"accesskit",4080
"accesskit_windows",4083
"accesskit_windows",@@ -33,6 +33,7 @@ raw-window-handle = "0.6"
33
33
x11rb = { version = "0.13", features = ["shape"] }
34
34
35
35
[target.'cfg(windows)'.dependencies]
36
libc = "0.2"
36
37
rodio = { version = "0.22", default-features = false, features = ["playback", "mp3"] }
37
38
tray-icon = { version = "0.21", default-features = false }
38
39
windows = { version = "0.62", features = [
@@ -40,6 +41,9 @@ windows = { version = "0.62", features = [
40
41
"Win32_Graphics_Dwm",
41
42
"Win32_Graphics_Gdi",
42
43
"Win32_Security",
44
"Win32_System_Diagnostics_Debug",
45
"Win32_System_Kernel",
46
"Win32_System_SystemServices",
43
47
"Win32_System_DataExchange",
44
48
"Win32_System_Memory",
45
49
"Win32_System_Ole",
@@ -33,6 +33,7 @@ raw-window-handle = "0.6"33
x11rb = { version = "0.13", features = ["shape"] }33
x11rb = { version = "0.13", features = ["shape"] }34
34
35
[target.'cfg(windows)'.dependencies]35
[target.'cfg(windows)'.dependencies]36
libc = "0.2"36
rodio = { version = "0.22", default-features = false, features = ["playback", "mp3"] }37
rodio = { version = "0.22", default-features = false, features = ["playback", "mp3"] }37
tray-icon = { version = "0.21", default-features = false }38
tray-icon = { version = "0.21", default-features = false }38
windows = { version = "0.62", features = [39
windows = { version = "0.62", features = [@@ -40,6 +41,9 @@ windows = { version = "0.62", features = [40
"Win32_Graphics_Dwm",41
"Win32_Graphics_Dwm",41
"Win32_Graphics_Gdi",42
"Win32_Graphics_Gdi",42
"Win32_Security",43
"Win32_Security",44
"Win32_System_Diagnostics_Debug",45
"Win32_System_Kernel",46
"Win32_System_SystemServices",43
"Win32_System_DataExchange",47
"Win32_System_DataExchange",44
"Win32_System_Memory",48
"Win32_System_Memory",45
"Win32_System_Ole",49
"Win32_System_Ole",@@ -21,6 +21,7 @@ pub mod fuzzy;
21
21
pub mod image_clipboard;
22
22
pub mod image_view_math;
23
23
pub mod inline_image;
24
pub mod native_dumps;
24
25
pub mod notify;
25
26
pub mod presence_link;
26
27
pub mod read_state;
@@ -21,6 +21,7 @@ pub mod fuzzy;21
pub mod image_clipboard;21
pub mod image_clipboard;22
pub mod image_view_math;22
pub mod image_view_math;23
pub mod inline_image;23
pub mod inline_image;24
pub mod native_dumps;24
pub mod notify;25
pub mod notify;25
pub mod presence_link;26
pub mod presence_link;26
pub mod read_state;27
pub mod read_state;@@ -0,0 +1,336 @@
1
use std::path::PathBuf;
2
3
#[cfg(windows)]
4
pub fn install(directory: PathBuf, crash_log: PathBuf) {
5
windows_impl::install(directory, crash_log);
6
}
7
8
#[cfg(not(windows))]
9
pub fn install(_directory: PathBuf, _crash_log: PathBuf) {}
10
11
#[cfg(windows)]
12
pub fn heartbeat() {
13
windows_impl::heartbeat();
14
}
15
16
#[cfg(not(windows))]
17
pub fn heartbeat() {}
18
19
#[cfg(any(windows, test))]
20
mod 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)]
65
mod 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)]
269
mod 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
}
@@ -0,0 +1,336 @@1
use std::path::PathBuf;2
3
#[cfg(windows)]4
pub fn install(directory: PathBuf, crash_log: PathBuf) {5
windows_impl::install(directory, crash_log);6
}7
8
#[cfg(not(windows))]9
pub fn install(_directory: PathBuf, _crash_log: PathBuf) {}10
11
#[cfg(windows)]12
pub fn heartbeat() {13
windows_impl::heartbeat();14
}15
16
#[cfg(not(windows))]17
pub fn heartbeat() {}18
19
#[cfg(any(windows, test))]20
mod 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)]65
mod 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 PATHS107
.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
pointers155
.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_SEARCH164
}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_name184
}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_information203
.as_mut()204
.map(|information| information as *const MINIDUMP_EXCEPTION_INFORMATION);205
let dump_type = MINIDUMP_TYPE(206
MiniDumpWithThreadInfo.0207
| MiniDumpWithUnloadedModules.0208
| 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 = entries229
.flatten()230
.filter(|entry| {231
entry232
.path()233
.extension()234
.is_some_and(|extension| extension == "dmp")235
})236
.map(|entry| {237
let modified = entry238
.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)]269
mod 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
}@@ -92,6 +92,8 @@ fn parse_arguments() -> Arguments {
92
92
arguments
93
93
}
94
94
95
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(1);
96
95
97
fn data_path(name: &str) -> PathBuf {
96
98
ProjectDirs::from("", "", store::DATA_DIR_NAME)
97
99
.map(|directories| directories.data_local_dir().join(name))
@@ -138,6 +140,10 @@ fn open_store(path: &std::path::Path) -> Store {
138
140
fn main() {
139
141
app_base::version::set_build_version(VERSION_MARKER.trim_start_matches("teams-build:"));
140
142
crash_log::install(data_path(crash_log::CRASH_LOG_FILE));
143
app_base::native_dumps::install(
144
data_path("native-dumps"),
145
data_path(crash_log::CRASH_LOG_FILE),
146
);
141
147
diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));
142
148
let arguments = parse_arguments();
143
149
if !arguments.demo && arguments.database.is_none() {
@@ -242,6 +248,13 @@ fn main() {
242
248
})
243
249
.detach();
244
250
cx.activate(true);
251
cx.spawn(async move |cx| {
252
loop {
253
app_base::native_dumps::heartbeat();
254
cx.background_executor().timer(HEARTBEAT_INTERVAL).await;
255
}
256
})
257
.detach();
245
258
});
246
259
presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);
247
260
#[cfg(windows)]
@@ -92,6 +92,8 @@ fn parse_arguments() -> Arguments {92
arguments92
arguments93
}93
}94
94
95
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(1);96
95
fn data_path(name: &str) -> PathBuf {97
fn data_path(name: &str) -> PathBuf {96
ProjectDirs::from("", "", store::DATA_DIR_NAME)98
ProjectDirs::from("", "", store::DATA_DIR_NAME)97
.map(|directories| directories.data_local_dir().join(name))99
.map(|directories| directories.data_local_dir().join(name))@@ -138,6 +140,10 @@ fn open_store(path: &std::path::Path) -> Store {138
fn main() {140
fn main() {139
app_base::version::set_build_version(VERSION_MARKER.trim_start_matches("teams-build:"));141
app_base::version::set_build_version(VERSION_MARKER.trim_start_matches("teams-build:"));140
crash_log::install(data_path(crash_log::CRASH_LOG_FILE));142
crash_log::install(data_path(crash_log::CRASH_LOG_FILE));143
app_base::native_dumps::install(144
data_path("native-dumps"),145
data_path(crash_log::CRASH_LOG_FILE),146
);141
diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));147
diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));142
let arguments = parse_arguments();148
let arguments = parse_arguments();143
if !arguments.demo && arguments.database.is_none() {149
if !arguments.demo && arguments.database.is_none() {@@ -242,6 +248,13 @@ fn main() {242
})248
})243
.detach();249
.detach();244
cx.activate(true);250
cx.activate(true);251
cx.spawn(async move |cx| {252
loop {253
app_base::native_dumps::heartbeat();254
cx.background_executor().timer(HEARTBEAT_INTERVAL).await;255
}256
})257
.detach();245
});258
});246
presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);259
presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);247
#[cfg(windows)]260
#[cfg(windows)]