From 238a71ccd4a593f9ef2906e5b6c17e63c1c84339 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:57:36 +0100 Subject: [PATCH 1/6] feat(desktop-gpui): record panics, fatal signals and Windows exceptions in a crash log --- apps/desktop-gpui/Cargo.toml | 6 + apps/desktop-gpui/src/crash_capture.rs | 580 +++++++++++++++++++++++++ apps/desktop-gpui/src/main.rs | 16 +- 3 files changed, 601 insertions(+), 1 deletion(-) create mode 100644 apps/desktop-gpui/src/crash_capture.rs diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.toml index cb8915459b3..8de8fcd39ef 100644 --- a/apps/desktop-gpui/Cargo.toml +++ b/apps/desktop-gpui/Cargo.toml @@ -194,6 +194,12 @@ tray-icon = { version = "0.21.1", default-features = false } windows-sys = { version = "0.59", features = [ "Win32_Foundation", "Win32_Security", + "Win32_Storage_FileSystem", + "Win32_System_Console", + "Win32_System_Diagnostics_Debug", + "Win32_System_IO", + "Win32_System_Kernel", + "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading", diff --git a/apps/desktop-gpui/src/crash_capture.rs b/apps/desktop-gpui/src/crash_capture.rs new file mode 100644 index 00000000000..51f5900d1a4 --- /dev/null +++ b/apps/desktop-gpui/src/crash_capture.rs @@ -0,0 +1,580 @@ +//! Leaves evidence for every way this process can end, in files the Feedback +//! page's log upload already carries. +//! +//! 0.6.1 had none of it: the log file goes through a non-blocking queue, so a +//! panic's last lines died with the process, and a fault, an abort or a stack +//! overflow wrote nothing at all. Users saw Cap vanish during an export and +//! their uploaded logs ended mid-operation. This module adds: +//! +//! - a panic hook that writes the message, location, thread and backtrace +//! straight to [`CRASH_FILE`] before anything else can fail; +//! - fatal signal handlers (Unix) and an unhandled-exception filter plus a +//! stack-overflow handler (Windows) that append one line with what killed +//! the process, using only calls that are safe at that point; +//! - stderr redirected into [`STDERR_FILE`] when no terminal is attached, which +//! is where Rust reports a stack overflow and native libraries complain; +//! - a session marker, so the next launch logs that the previous one ended +//! without a clean quit (a kill, an out-of-memory kill, or a crash no +//! handler could see). + +use std::{ + fs::{File, OpenOptions}, + io::Write as _, + path::{Path, PathBuf}, + sync::OnceLock, +}; + +/// Appended to; read by `cap_utils::log_upload` under the log prefix. +pub const CRASH_FILE: &str = "cap-gpui.log.crashes"; +/// Rewritten per session; the previous session's copy is kept beside it. +pub const STDERR_FILE: &str = "cap-gpui.log.stderr"; +const PREVIOUS_STDERR_FILE: &str = "cap-gpui.log.stderr-previous"; +const SESSION_FILE: &str = "cap-gpui.session"; +/// A crash loop must not fill the disk. +const MAX_CRASH_FILE_BYTES: u64 = 512 * 1024; + +static CRASH_LOG: OnceLock = OnceLock::new(); +static SESSION_MARKER: OnceLock = OnceLock::new(); + +/// Call once, right after logging starts and before any other thread work. +pub fn install(logs_dir: &Path) { + let _ = std::fs::create_dir_all(logs_dir); + let crash_path = logs_dir.join(CRASH_FILE); + if std::fs::metadata(&crash_path).is_ok_and(|metadata| metadata.len() > MAX_CRASH_FILE_BYTES) { + let _ = std::fs::rename(&crash_path, logs_dir.join(format!("{CRASH_FILE}-previous"))); + } + match OpenOptions::new().create(true).append(true).open(&crash_path) { + Ok(file) => { + let _ = CRASH_LOG.set(file); + } + Err(error) => tracing::warn!(%error, "could not open the crash record file"), + } + report_previous_session(logs_dir); + install_panic_hook(); + native::install(); + capture_stderr(logs_dir); +} + +/// Clears the session marker; call from the app's quit path. +pub fn mark_clean_exit() { + if let Some(marker) = SESSION_MARKER.get() { + let _ = std::fs::remove_file(marker); + } +} + +fn now() -> String { + chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true) +} + +fn record(text: &str) { + if let Some(mut file) = CRASH_LOG.get() { + let _ = file.write_all(text.as_bytes()); + } +} + +fn report_previous_session(logs_dir: &Path) { + let marker = logs_dir.join(SESSION_FILE); + if let Ok(previous) = std::fs::read_to_string(&marker) { + let previous = previous.trim(); + let pid = previous + .split_whitespace() + .find_map(|field| field.strip_prefix("pid=")) + .and_then(|pid| pid.parse::().ok()); + if pid.is_some_and(|pid| pid != std::process::id() && !process_alive(pid)) { + tracing::error!(previous = %previous, "the previous Cap session ended without a clean quit"); + record(&format!( + "{} previous session ended without a clean quit: {previous}\n", + now() + )); + } + } + let contents = format!( + "pid={} started={} version={}\n", + std::process::id(), + now(), + env!("CARGO_PKG_VERSION") + ); + if std::fs::write(&marker, contents).is_ok() { + let _ = SESSION_MARKER.set(marker); + } +} + +#[cfg(unix)] +fn process_alive(pid: u32) -> bool { + let Ok(pid) = libc::pid_t::try_from(pid) else { + return false; + }; + // Signal 0 checks existence; EPERM still means the process is there. + unsafe { libc::kill(pid, 0) == 0 || *libc_errno() == libc::EPERM } +} + +#[cfg(target_os = "linux")] +unsafe fn libc_errno() -> *mut libc::c_int { + unsafe { libc::__errno_location() } +} + +#[cfg(target_os = "macos")] +unsafe fn libc_errno() -> *mut libc::c_int { + unsafe { libc::__error() } +} + +#[cfg(windows)] +fn process_alive(pid: u32) -> bool { + use windows_sys::Win32::{ + Foundation::{CloseHandle, STILL_ACTIVE}, + System::Threading::{GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION}, + }; + unsafe { + let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); + if handle.is_null() { + return false; + } + let mut code = 0u32; + let alive = GetExitCodeProcess(handle, &mut code) != 0 && code == STILL_ACTIVE as u32; + CloseHandle(handle); + alive + } +} + +fn install_panic_hook() { + let previous = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + let location = info + .location() + .map(|location| format!("{}:{}:{}", location.file(), location.line(), location.column())) + .unwrap_or_else(|| "".into()); + let message = info + .payload() + .downcast_ref::<&str>() + .map(|message| (*message).to_owned()) + .or_else(|| info.payload().downcast_ref::().cloned()) + .unwrap_or_else(|| "".into()); + let thread = std::thread::current(); + let thread = thread.name().unwrap_or("").to_owned(); + let backtrace = std::backtrace::Backtrace::force_capture(); + // The file first: the tracing queue may never drain if this panic + // takes the process down. + record(&format!( + "{} panic thread={thread} at {location}: {message}\n{backtrace}\n", + now() + )); + tracing::error!(%thread, %location, %message, "panic"); + previous(info); + })); +} + +/// When nothing reads stderr (launched from a dock, a desktop file or +/// Explorer), send it to a file the log upload includes. +fn capture_stderr(logs_dir: &Path) { + use std::io::IsTerminal as _; + if std::io::stderr().is_terminal() { + return; + } + let path = logs_dir.join(STDERR_FILE); + if path.exists() { + let _ = std::fs::rename(&path, logs_dir.join(PREVIOUS_STDERR_FILE)); + } + let Ok(file) = File::create(&path) else { + return; + }; + native::redirect_stderr(file); +} + +#[cfg(unix)] +mod native { + use std::{ + fs::File, + mem::MaybeUninit, + os::fd::{AsRawFd as _, IntoRawFd as _}, + sync::atomic::{AtomicI32, Ordering}, + }; + + const SIGNALS: [libc::c_int; 6] = [ + libc::SIGSEGV, + libc::SIGBUS, + libc::SIGILL, + libc::SIGFPE, + libc::SIGABRT, + libc::SIGTRAP, + ]; + + static CRASH_FD: AtomicI32 = AtomicI32::new(-1); + static mut PREVIOUS: [MaybeUninit; 6] = [const { MaybeUninit::uninit() }; 6]; + + pub fn install() { + let Some(file) = super::CRASH_LOG.get() else { + return; + }; + CRASH_FD.store(file.as_raw_fd(), Ordering::Release); + for (index, signal) in SIGNALS.into_iter().enumerate() { + unsafe { + let mut action: libc::sigaction = std::mem::zeroed(); + action.sa_sigaction = handler as extern "C" fn(libc::c_int, *mut libc::siginfo_t, *mut libc::c_void) as usize; + action.sa_flags = libc::SA_SIGINFO | libc::SA_ONSTACK; + libc::sigemptyset(&mut action.sa_mask); + let previous = (&raw mut PREVIOUS[index]).cast::(); + libc::sigaction(signal, &action, previous); + } + } + } + + pub fn redirect_stderr(file: File) { + let fd = file.into_raw_fd(); + unsafe { + libc::dup2(fd, libc::STDERR_FILENO); + libc::close(fd); + } + } + + /// Async-signal-safe: fixed buffers and `write(2)` only. Restores the + /// previous action (Rust's own stack-overflow reporter for SIGSEGV and + /// SIGBUS) and returns, so the fault repeats into it, or re-raises an + /// asynchronous signal like SIGABRT. + extern "C" fn handler(signal: libc::c_int, info: *mut libc::siginfo_t, _: *mut libc::c_void) { + let mut line = Line::new(); + line.push(b"native crash: signal "); + line.push_decimal(signal as u64); + line.push(b" ("); + line.push(name(signal)); + line.push(b") fault address 0x"); + let address = if info.is_null() { + 0 + } else { + fault_address(info) + }; + line.push_hex(address); + line.push(b" pid "); + line.push_decimal(std::process::id() as u64); + line.push(b"\n"); + let fd = CRASH_FD.load(Ordering::Acquire); + if fd >= 0 { + unsafe { libc::write(fd, line.bytes.as_ptr().cast(), line.len) }; + } + unsafe { + libc::write(libc::STDERR_FILENO, line.bytes.as_ptr().cast(), line.len); + if let Some(index) = SIGNALS.iter().position(|candidate| *candidate == signal) { + let previous = (&raw const PREVIOUS[index]).cast::(); + libc::sigaction(signal, previous, std::ptr::null_mut()); + } + if signal == libc::SIGABRT || signal == libc::SIGTRAP { + libc::raise(signal); + } + } + } + + #[cfg(target_os = "linux")] + fn fault_address(info: *mut libc::siginfo_t) -> u64 { + unsafe { (*info).si_addr() as usize as u64 } + } + + #[cfg(target_os = "macos")] + fn fault_address(info: *mut libc::siginfo_t) -> u64 { + unsafe { (*info).si_addr as usize as u64 } + } + + fn name(signal: libc::c_int) -> &'static [u8] { + match signal { + libc::SIGSEGV => b"SIGSEGV", + libc::SIGBUS => b"SIGBUS", + libc::SIGILL => b"SIGILL", + libc::SIGFPE => b"SIGFPE", + libc::SIGABRT => b"SIGABRT", + libc::SIGTRAP => b"SIGTRAP", + _ => b"signal", + } + } + + struct Line { + bytes: [u8; 160], + len: usize, + } + + impl Line { + fn new() -> Self { + Self { + bytes: [0; 160], + len: 0, + } + } + + fn push(&mut self, text: &[u8]) { + let room = self.bytes.len() - self.len; + let count = text.len().min(room); + self.bytes[self.len..self.len + count].copy_from_slice(&text[..count]); + self.len += count; + } + + fn push_decimal(&mut self, mut value: u64) { + let mut digits = [0u8; 20]; + let mut count = 0; + loop { + digits[count] = b'0' + (value % 10) as u8; + count += 1; + value /= 10; + if value == 0 { + break; + } + } + digits[..count].reverse(); + self.push(&digits[..count]); + } + + fn push_hex(&mut self, value: u64) { + let mut digits = [0u8; 16]; + for (index, digit) in digits.iter_mut().enumerate() { + let nibble = ((value >> ((15 - index) * 4)) & 0xF) as u8; + *digit = if nibble < 10 { b'0' + nibble } else { b'a' + nibble - 10 }; + } + self.push(&digits); + } + } + + #[cfg(test)] + mod tests { + use super::Line; + + #[test] + fn crash_line_formats_without_allocating() { + let mut line = Line::new(); + line.push(b"signal "); + line.push_decimal(11); + line.push(b" at 0x"); + line.push_hex(0xdead_beef); + assert_eq!(&line.bytes[..line.len], b"signal 11 at 0x00000000deadbeef"); + line.push(&[b'x'; 400]); + assert_eq!(line.len, line.bytes.len()); + } + } +} + +#[cfg(windows)] +mod native { + use std::{ + fs::File, + os::windows::io::{AsRawHandle as _, IntoRawHandle as _}, + sync::atomic::{AtomicPtr, Ordering}, + }; + use windows_sys::Win32::{ + Foundation::{EXCEPTION_STACK_OVERFLOW, HANDLE, HMODULE}, + Storage::FileSystem::WriteFile, + System::{ + Console::{STD_ERROR_HANDLE, SetStdHandle}, + Diagnostics::Debug::{ + AddVectoredExceptionHandler, EXCEPTION_POINTERS, SetUnhandledExceptionFilter, + }, + LibraryLoader::{ + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + GetModuleFileNameA, GetModuleHandleExA, + }, + }, + }; + + const EXCEPTION_CONTINUE_SEARCH: i32 = 0; + + static CRASH_HANDLE: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); + /// The filter installed before ours, which still gets the exception. + static PREVIOUS_FILTER: std::sync::OnceLock< + windows_sys::Win32::System::Diagnostics::Debug::LPTOP_LEVEL_EXCEPTION_FILTER, + > = std::sync::OnceLock::new(); + + pub fn install() { + let Some(file) = super::CRASH_LOG.get() else { + return; + }; + CRASH_HANDLE.store(file.as_raw_handle(), Ordering::Release); + unsafe { + let _ = PREVIOUS_FILTER.set(SetUnhandledExceptionFilter(Some(unhandled))); + // First in line, so the overflow is written before Rust's own + // handler prints its message and aborts. + AddVectoredExceptionHandler(1, Some(stack_overflow)); + } + } + + pub fn redirect_stderr(file: File) { + unsafe { + SetStdHandle(STD_ERROR_HANDLE, file.into_raw_handle() as HANDLE); + } + } + + unsafe extern "system" fn unhandled(pointers: *const EXCEPTION_POINTERS) -> i32 { + write_exception(b"native crash: unhandled exception 0x", pointers); + match PREVIOUS_FILTER.get().copied().flatten() { + Some(previous) => unsafe { previous(pointers) }, + None => EXCEPTION_CONTINUE_SEARCH, + } + } + + unsafe extern "system" fn stack_overflow(pointers: *mut EXCEPTION_POINTERS) -> i32 { + let code = unsafe { pointers.as_ref().and_then(|p| p.ExceptionRecord.as_ref()) } + .map(|record| record.ExceptionCode); + if code == Some(EXCEPTION_STACK_OVERFLOW) { + write_exception(b"native crash: stack overflow 0x", pointers); + } + EXCEPTION_CONTINUE_SEARCH + } + + /// Fixed buffers only; the faulting thread may have almost no stack left. + fn write_exception(prefix: &[u8], pointers: *const EXCEPTION_POINTERS) { + fn push(text: &[u8], line: &mut [u8; 400], len: &mut usize) { + let count = text.len().min(line.len() - *len); + line[*len..*len + count].copy_from_slice(&text[..count]); + *len += count; + } + let mut line = [0u8; 400]; + let mut len = 0; + push(prefix, &mut line, &mut len); + let record = unsafe { pointers.as_ref().and_then(|p| p.ExceptionRecord.as_ref()) }; + let (code, address) = record + .map(|record| (record.ExceptionCode as u32 as u64, record.ExceptionAddress as usize)) + .unwrap_or((0, 0)); + push(&hex(code, 8)[..8], &mut line, &mut len); + push(b" at 0x", &mut line, &mut len); + push(&hex(address as u64, 16)[..16], &mut line, &mut len); + let mut module: HMODULE = std::ptr::null_mut(); + let found = address != 0 + && unsafe { + GetModuleHandleExA( + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + address as *const u8, + &mut module, + ) + } != 0; + if found { + let mut name = [0u8; 260]; + let name_len = + unsafe { GetModuleFileNameA(module, name.as_mut_ptr(), name.len() as u32) } as usize; + let base = name[..name_len] + .iter() + .rposition(|byte| *byte == b'\\') + .map_or(0, |index| index + 1); + push(b" in ", &mut line, &mut len); + push(&name[base..name_len], &mut line, &mut len); + push(b"+0x", &mut line, &mut len); + push(&hex((address - module as usize) as u64, 8)[..8], &mut line, &mut len); + } + push(b"\r\n", &mut line, &mut len); + let handle = CRASH_HANDLE.load(Ordering::Acquire); + if !handle.is_null() { + let mut written = 0u32; + unsafe { + WriteFile(handle, line.as_ptr(), len as u32, &mut written, std::ptr::null_mut()) + }; + } + } + + fn hex(value: u64, width: usize) -> [u8; 16] { + let mut digits = [b'0'; 16]; + for index in 0..16 { + let nibble = ((value >> ((15 - index) * 4)) & 0xF) as u8; + digits[index] = if nibble < 10 { b'0' + nibble } else { b'a' + nibble - 10 }; + } + let mut out = [0u8; 16]; + out[..width].copy_from_slice(&digits[16 - width..]); + out + } +} + +/// Each case runs in a child copy of this test binary, because the handlers +/// are process-wide and the child has to actually die. +#[cfg(test)] +mod process_tests { + use std::{path::Path, process::Command}; + + const CHILD: &str = "CAP_CRASH_CAPTURE_CHILD"; + const LOGS: &str = "CAP_CRASH_CAPTURE_LOGS"; + + /// In the child: install the handlers, then die the way `kind` says. + fn child(kind: &str) -> bool { + if std::env::var(CHILD).as_deref() != Ok(kind) { + return false; + } + super::install(Path::new(&std::env::var(LOGS).unwrap())); + match kind { + "fault" => unsafe { std::ptr::write_volatile(std::ptr::null_mut::(), 1) }, + "overflow" => { + #[allow(unconditional_recursion)] + fn recurse(depth: u64) -> u64 { + let frame = [depth; 512]; + std::hint::black_box(&frame); + recurse(depth + 1) + frame[0] + } + std::hint::black_box(recurse(0)); + } + "panic" => panic!("crash capture test panic"), + _ => {} + } + true + } + + struct Died { + crashes: String, + stderr: String, + success: bool, + } + + fn run(test: &str, kind: &str) -> Died { + let logs = tempfile::tempdir().unwrap(); + let status = Command::new(std::env::current_exe().unwrap()) + .args([test, "--exact", "--nocapture", "--test-threads=1"]) + .env(CHILD, kind) + .env(LOGS, logs.path()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::piped()) + .output() + .unwrap(); + let read = |name: &str| std::fs::read_to_string(logs.path().join(name)).unwrap_or_default(); + Died { + crashes: read(super::CRASH_FILE), + stderr: read(super::STDERR_FILE) + &String::from_utf8_lossy(&status.stderr), + success: status.status.success(), + } + } + + #[test] + fn a_memory_fault_is_recorded_and_still_kills_the_process() { + if child("fault") { + return; + } + let died = run( + "crash_capture::process_tests::a_memory_fault_is_recorded_and_still_kills_the_process", + "fault", + ); + assert!(!died.success); + #[cfg(unix)] + assert!(died.crashes.contains("SIGSEGV") || died.crashes.contains("SIGBUS"), "{}", died.crashes); + #[cfg(windows)] + assert!(died.crashes.contains("unhandled exception 0xc0000005"), "{}", died.crashes); + } + + /// Rust's own overflow report must survive: the handler chains to it. + #[test] + fn a_stack_overflow_is_recorded_and_rust_still_reports_it() { + if child("overflow") { + return; + } + let died = run( + "crash_capture::process_tests::a_stack_overflow_is_recorded_and_rust_still_reports_it", + "overflow", + ); + assert!(!died.success); + #[cfg(unix)] + assert!(died.crashes.contains("native crash: signal"), "{}", died.crashes); + #[cfg(windows)] + assert!(died.crashes.contains("stack overflow 0xc00000fd"), "{}", died.crashes); + assert!(died.stderr.contains("overflowed its stack"), "{}", died.stderr); + } + + #[test] + fn a_panic_is_written_before_the_process_ends() { + if child("panic") { + return; + } + let died = run( + "crash_capture::process_tests::a_panic_is_written_before_the_process_ends", + "panic", + ); + assert!(!died.success); + assert!(died.crashes.contains("crash capture test panic"), "{}", died.crashes); + assert!(died.crashes.contains("crash_capture.rs"), "{}", died.crashes); + } +} diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs index 0e915e40837..ac93fed4e93 100644 --- a/apps/desktop-gpui/src/main.rs +++ b/apps/desktop-gpui/src/main.rs @@ -9,6 +9,7 @@ mod assets; mod auth; #[cfg(target_os = "macos")] mod camera_bench; +mod crash_capture; #[cfg(target_os = "macos")] mod camera_blur; #[cfg(any(not(target_os = "macos"), test))] @@ -146,6 +147,14 @@ fn resolve_auto_screenshot_editor(target: &str) -> Option { .map(|item| item.bundle) } +/// Windows ends the process at logoff or shutdown without running +/// `on_app_quit`, so both markers that mean "this session crashed" clear here. +#[cfg(target_os = "windows")] +fn end_windows_session() { + crate::store::clear_handoff_marker(); + crash_capture::mark_clean_exit(); +} + /// stdout, plus a rolling daily file the Feedback page can upload. /// /// Mirrors `src-tauri/src/main.rs`: `tracing_appender::rolling::daily` into @@ -280,6 +289,7 @@ fn main() { } let _log_guard = init_logging(); + crash_capture::install(&diagnostics::logs_dir()); single_instance::acquire(); if cfg!(debug_assertions) { @@ -419,6 +429,10 @@ fn main() { }) .detach(); } + cx.on_app_quit(|_| async { + crash_capture::mark_clean_exit(); + }) + .detach(); app_windows::init(window_handle, session, cx); #[cfg(target_os = "macos")] @@ -584,7 +598,7 @@ fn main() { tracing::warn!(%error, "could not install Main window frame policy"); } if let Err(error) = - platform::install_session_end_handler(&native, crate::store::clear_handoff_marker) + platform::install_session_end_handler(&native, end_windows_session) { tracing::warn!(%error, "could not install the Windows session end handler"); } From 301e0bffb1c325a01b0efe6b1d1c2beef91dd1b6 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:57:36 +0100 Subject: [PATCH 2/6] feat(utils): include crash records and captured stderr in uploaded logs --- crates/utils/src/log_upload.rs | 49 ++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/crates/utils/src/log_upload.rs b/crates/utils/src/log_upload.rs index a206e092ef7..09d5278c60a 100644 --- a/crates/utils/src/log_upload.rs +++ b/crates/utils/src/log_upload.rs @@ -5,6 +5,7 @@ use std::{ }; pub const MAX_LOG_BYTES: usize = 512 * 1024; +const MAX_CRASH_LOG_BYTES: usize = 64 * 1024; pub const MAX_REQUEST_BYTES: usize = 4 * 1024 * 1024; const REQUEST_HEADROOM: usize = 64 * 1024; const MAX_METADATA_BYTES: usize = 512 * 1024; @@ -206,6 +207,22 @@ pub fn collect(dir: &Path, prefix: &str) -> LogBundle { .rev() .map(|(name, path)| (name, path, normal_budget)) .collect(); + // Crash records and captured stderr: what a process wrote as it died, + // which the daily log's non-blocking writer cannot guarantee. + for suffix in [ + "crashes-previous", + "crashes", + "stderr-previous", + "stderr", + ] { + let name = format!("{prefix}.{suffix}"); + let path = dir.join(&name); + if std::fs::symlink_metadata(&path) + .is_ok_and(|metadata| metadata.file_type().is_file() && metadata.len() > 0) + { + selected.push((name, path, MAX_CRASH_LOG_BYTES)); + } + } for suffix in ["diagnostic-previous.jsonl", "diagnostic-current.jsonl"] { let name = format!("{prefix}.{suffix}"); let path = dir.join(&name); @@ -378,6 +395,38 @@ mod tests { ); } + #[test] + fn carries_crash_records_and_captured_stderr_after_the_daily_logs() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("cap-gpui.log.2026-10-22"), "event\n").unwrap(); + std::fs::write( + dir.path().join("cap-gpui.log.crashes"), + "native crash: signal 11 (SIGSEGV)\n", + ) + .unwrap(); + std::fs::write( + dir.path().join("cap-gpui.log.stderr-previous"), + "thread 'main' has overflowed its stack\n", + ) + .unwrap(); + std::fs::write(dir.path().join("cap-gpui.log.stderr"), "").unwrap(); + std::fs::write(dir.path().join("cap-gpui.log.crashes-other"), "private").unwrap(); + let bundle = collect(dir.path(), "cap-gpui.log"); + let names: Vec<_> = bundle.files.iter().map(|file| file.name.as_str()).collect(); + assert_eq!( + names, + [ + "cap-gpui.log.2026-10-22", + "cap-gpui.log.crashes", + "cap-gpui.log.stderr-previous" + ] + ); + assert!(bundle.text.contains("signal 11 (SIGSEGV)")); + assert!(bundle.text.contains("overflowed its stack")); + assert!(!bundle.text.contains("private")); + assert_eq!(bundle.ordinary_end, bundle.text.len()); + } + #[test] fn handles_partial_utf8_missing_logs_and_scan_limits() { let dir = tempfile::tempdir().unwrap(); From 0fc93f5dbc826a4a3d1f8f8cb3c77d6e9941c59d Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:59:51 +0100 Subject: [PATCH 3/6] style(desktop-gpui): rustfmt the crash capture changes --- apps/desktop-gpui/src/crash_capture.rs | 105 ++++++++++++++++++++----- apps/desktop-gpui/src/main.rs | 5 +- crates/utils/src/log_upload.rs | 7 +- 3 files changed, 89 insertions(+), 28 deletions(-) diff --git a/apps/desktop-gpui/src/crash_capture.rs b/apps/desktop-gpui/src/crash_capture.rs index 51f5900d1a4..431a32b02af 100644 --- a/apps/desktop-gpui/src/crash_capture.rs +++ b/apps/desktop-gpui/src/crash_capture.rs @@ -43,7 +43,11 @@ pub fn install(logs_dir: &Path) { if std::fs::metadata(&crash_path).is_ok_and(|metadata| metadata.len() > MAX_CRASH_FILE_BYTES) { let _ = std::fs::rename(&crash_path, logs_dir.join(format!("{CRASH_FILE}-previous"))); } - match OpenOptions::new().create(true).append(true).open(&crash_path) { + match OpenOptions::new() + .create(true) + .append(true) + .open(&crash_path) + { Ok(file) => { let _ = CRASH_LOG.set(file); } @@ -141,7 +145,14 @@ fn install_panic_hook() { std::panic::set_hook(Box::new(move |info| { let location = info .location() - .map(|location| format!("{}:{}:{}", location.file(), location.line(), location.column())) + .map(|location| { + format!( + "{}:{}:{}", + location.file(), + location.line(), + location.column() + ) + }) .unwrap_or_else(|| "".into()); let message = info .payload() @@ -209,7 +220,9 @@ mod native { for (index, signal) in SIGNALS.into_iter().enumerate() { unsafe { let mut action: libc::sigaction = std::mem::zeroed(); - action.sa_sigaction = handler as extern "C" fn(libc::c_int, *mut libc::siginfo_t, *mut libc::c_void) as usize; + action.sa_sigaction = handler + as extern "C" fn(libc::c_int, *mut libc::siginfo_t, *mut libc::c_void) + as usize; action.sa_flags = libc::SA_SIGINFO | libc::SA_ONSTACK; libc::sigemptyset(&mut action.sa_mask); let previous = (&raw mut PREVIOUS[index]).cast::(); @@ -323,7 +336,11 @@ mod native { let mut digits = [0u8; 16]; for (index, digit) in digits.iter_mut().enumerate() { let nibble = ((value >> ((15 - index) * 4)) & 0xF) as u8; - *digit = if nibble < 10 { b'0' + nibble } else { b'a' + nibble - 10 }; + *digit = if nibble < 10 { + b'0' + nibble + } else { + b'a' + nibble - 10 + }; } self.push(&digits); } @@ -363,8 +380,9 @@ mod native { AddVectoredExceptionHandler, EXCEPTION_POINTERS, SetUnhandledExceptionFilter, }, LibraryLoader::{ - GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, - GetModuleFileNameA, GetModuleHandleExA, + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, + GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, GetModuleFileNameA, + GetModuleHandleExA, }, }, }; @@ -425,7 +443,12 @@ mod native { push(prefix, &mut line, &mut len); let record = unsafe { pointers.as_ref().and_then(|p| p.ExceptionRecord.as_ref()) }; let (code, address) = record - .map(|record| (record.ExceptionCode as u32 as u64, record.ExceptionAddress as usize)) + .map(|record| { + ( + record.ExceptionCode as u32 as u64, + record.ExceptionAddress as usize, + ) + }) .unwrap_or((0, 0)); push(&hex(code, 8)[..8], &mut line, &mut len); push(b" at 0x", &mut line, &mut len); @@ -434,7 +457,8 @@ mod native { let found = address != 0 && unsafe { GetModuleHandleExA( - GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS + | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, address as *const u8, &mut module, ) @@ -442,7 +466,8 @@ mod native { if found { let mut name = [0u8; 260]; let name_len = - unsafe { GetModuleFileNameA(module, name.as_mut_ptr(), name.len() as u32) } as usize; + unsafe { GetModuleFileNameA(module, name.as_mut_ptr(), name.len() as u32) } + as usize; let base = name[..name_len] .iter() .rposition(|byte| *byte == b'\\') @@ -450,14 +475,24 @@ mod native { push(b" in ", &mut line, &mut len); push(&name[base..name_len], &mut line, &mut len); push(b"+0x", &mut line, &mut len); - push(&hex((address - module as usize) as u64, 8)[..8], &mut line, &mut len); + push( + &hex((address - module as usize) as u64, 8)[..8], + &mut line, + &mut len, + ); } push(b"\r\n", &mut line, &mut len); let handle = CRASH_HANDLE.load(Ordering::Acquire); if !handle.is_null() { let mut written = 0u32; unsafe { - WriteFile(handle, line.as_ptr(), len as u32, &mut written, std::ptr::null_mut()) + WriteFile( + handle, + line.as_ptr(), + len as u32, + &mut written, + std::ptr::null_mut(), + ) }; } } @@ -466,7 +501,11 @@ mod native { let mut digits = [b'0'; 16]; for index in 0..16 { let nibble = ((value >> ((15 - index) * 4)) & 0xF) as u8; - digits[index] = if nibble < 10 { b'0' + nibble } else { b'a' + nibble - 10 }; + digits[index] = if nibble < 10 { + b'0' + nibble + } else { + b'a' + nibble - 10 + }; } let mut out = [0u8; 16]; out[..width].copy_from_slice(&digits[16 - width..]); @@ -541,9 +580,17 @@ mod process_tests { ); assert!(!died.success); #[cfg(unix)] - assert!(died.crashes.contains("SIGSEGV") || died.crashes.contains("SIGBUS"), "{}", died.crashes); + assert!( + died.crashes.contains("SIGSEGV") || died.crashes.contains("SIGBUS"), + "{}", + died.crashes + ); #[cfg(windows)] - assert!(died.crashes.contains("unhandled exception 0xc0000005"), "{}", died.crashes); + assert!( + died.crashes.contains("unhandled exception 0xc0000005"), + "{}", + died.crashes + ); } /// Rust's own overflow report must survive: the handler chains to it. @@ -558,10 +605,22 @@ mod process_tests { ); assert!(!died.success); #[cfg(unix)] - assert!(died.crashes.contains("native crash: signal"), "{}", died.crashes); + assert!( + died.crashes.contains("native crash: signal"), + "{}", + died.crashes + ); #[cfg(windows)] - assert!(died.crashes.contains("stack overflow 0xc00000fd"), "{}", died.crashes); - assert!(died.stderr.contains("overflowed its stack"), "{}", died.stderr); + assert!( + died.crashes.contains("stack overflow 0xc00000fd"), + "{}", + died.crashes + ); + assert!( + died.stderr.contains("overflowed its stack"), + "{}", + died.stderr + ); } #[test] @@ -574,7 +633,15 @@ mod process_tests { "panic", ); assert!(!died.success); - assert!(died.crashes.contains("crash capture test panic"), "{}", died.crashes); - assert!(died.crashes.contains("crash_capture.rs"), "{}", died.crashes); + assert!( + died.crashes.contains("crash capture test panic"), + "{}", + died.crashes + ); + assert!( + died.crashes.contains("crash_capture.rs"), + "{}", + died.crashes + ); } } diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs index ac93fed4e93..68e9bb6eed7 100644 --- a/apps/desktop-gpui/src/main.rs +++ b/apps/desktop-gpui/src/main.rs @@ -9,7 +9,6 @@ mod assets; mod auth; #[cfg(target_os = "macos")] mod camera_bench; -mod crash_capture; #[cfg(target_os = "macos")] mod camera_blur; #[cfg(any(not(target_os = "macos"), test))] @@ -17,6 +16,7 @@ mod camera_blur_portable; mod camera_loading; mod camera_window; mod controls_window; +mod crash_capture; mod deeplink; mod dev_restore; mod devices; @@ -597,8 +597,7 @@ fn main() { if let Err(error) = platform::install_main_window_frame_policy(&native) { tracing::warn!(%error, "could not install Main window frame policy"); } - if let Err(error) = - platform::install_session_end_handler(&native, end_windows_session) + if let Err(error) = platform::install_session_end_handler(&native, end_windows_session) { tracing::warn!(%error, "could not install the Windows session end handler"); } diff --git a/crates/utils/src/log_upload.rs b/crates/utils/src/log_upload.rs index 09d5278c60a..4117afc5961 100644 --- a/crates/utils/src/log_upload.rs +++ b/crates/utils/src/log_upload.rs @@ -209,12 +209,7 @@ pub fn collect(dir: &Path, prefix: &str) -> LogBundle { .collect(); // Crash records and captured stderr: what a process wrote as it died, // which the daily log's non-blocking writer cannot guarantee. - for suffix in [ - "crashes-previous", - "crashes", - "stderr-previous", - "stderr", - ] { + for suffix in ["crashes-previous", "crashes", "stderr-previous", "stderr"] { let name = format!("{prefix}.{suffix}"); let path = dir.join(&name); if std::fs::symlink_metadata(&path) From c055fb008e4a7daf8de77c9eaddc9e085a29a0b9 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 25 Oct 2026 01:02:10 +0100 Subject: [PATCH 4/6] fix(desktop-gpui): log share export, upload and export task failures --- apps/desktop-gpui/src/editor_export.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/apps/desktop-gpui/src/editor_export.rs b/apps/desktop-gpui/src/editor_export.rs index 77498a4103d..8077de80010 100644 --- a/apps/desktop-gpui/src/editor_export.rs +++ b/apps/desktop-gpui/src/editor_export.rs @@ -1007,7 +1007,8 @@ impl EditorWindow { cx.notify(); }); } - Err(_) => { + Err(error) => { + tracing::error!(%error, "editor export task ended without a result"); let _ = this.update(cx, |this, cx| { if let Some(ui) = this.export.as_mut() { ui.phase = ExportPhase::Failed; @@ -1317,12 +1318,14 @@ impl EditorWindow { show_upload_failure(&this, cx, &error, true); } } - Err(_) => { + Err(error) => { + tracing::error!(%error, "share upload task ended without a result"); show_upload_failure(&this, cx, "Failed to upload recording", true); } } } Ok(Err(error)) => { + tracing::error!(error, "share export failed"); let cancelled = !is_resource_stop(&error) && (error == "Export cancelled" || cancel.load(Ordering::Relaxed)); let _ = this.update(cx, |this, cx| { @@ -1340,7 +1343,8 @@ impl EditorWindow { platform::alert_dialog("Export failed", &error); } } - Err(_) => { + Err(error) => { + tracing::error!(%error, "share export task ended without a result"); show_upload_failure(&this, cx, "Export task failed", false); } } @@ -2831,6 +2835,7 @@ fn show_upload_failure( message: &str, dialog: bool, ) { + tracing::error!(error = message, "share upload failed"); let message = message.to_string(); let _ = this.update(cx, |this, cx| { if let Some(ui) = this.export.as_mut() { From 5845c9cf4d47df9515c630f25452748b9432b0d7 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 25 Oct 2026 01:16:18 +0100 Subject: [PATCH 5/6] fix(desktop-gpui): leave a running instance's session marker and stderr alone --- apps/desktop-gpui/src/crash_capture.rs | 75 ++++++++++++++++++++++---- 1 file changed, 65 insertions(+), 10 deletions(-) diff --git a/apps/desktop-gpui/src/crash_capture.rs b/apps/desktop-gpui/src/crash_capture.rs index 431a32b02af..f1822e8c564 100644 --- a/apps/desktop-gpui/src/crash_capture.rs +++ b/apps/desktop-gpui/src/crash_capture.rs @@ -53,10 +53,13 @@ pub fn install(logs_dir: &Path) { } Err(error) => tracing::warn!(%error, "could not open the crash record file"), } - report_previous_session(logs_dir); + let owns_session = report_previous_session(logs_dir); install_panic_hook(); native::install(); - capture_stderr(logs_dir); + // A second instance hands off and exits; the running one keeps its files. + if owns_session { + capture_stderr(logs_dir); + } } /// Clears the session marker; call from the app's quit path. @@ -76,21 +79,22 @@ fn record(text: &str) { } } -fn report_previous_session(logs_dir: &Path) { +/// False when another running Cap owns the session marker. +fn report_previous_session(logs_dir: &Path) -> bool { let marker = logs_dir.join(SESSION_FILE); - if let Ok(previous) = std::fs::read_to_string(&marker) { - let previous = previous.trim(); - let pid = previous - .split_whitespace() - .find_map(|field| field.strip_prefix("pid=")) - .and_then(|pid| pid.parse::().ok()); - if pid.is_some_and(|pid| pid != std::process::id() && !process_alive(pid)) { + let previous = std::fs::read_to_string(&marker).ok(); + match classify_previous(previous.as_deref(), std::process::id(), process_alive) { + // Another Cap is running and owns the marker: this launch is a second + // instance about to hand off and exit, and must not overwrite it. + Previous::Running => return false, + Previous::Unclean(previous) => { tracing::error!(previous = %previous, "the previous Cap session ended without a clean quit"); record(&format!( "{} previous session ended without a clean quit: {previous}\n", now() )); } + Previous::None => {} } let contents = format!( "pid={} started={} version={}\n", @@ -101,6 +105,28 @@ fn report_previous_session(logs_dir: &Path) { if std::fs::write(&marker, contents).is_ok() { let _ = SESSION_MARKER.set(marker); } + true +} + +#[derive(Debug, PartialEq, Eq)] +enum Previous { + None, + Running, + Unclean(String), +} + +fn classify_previous(marker: Option<&str>, own_pid: u32, alive: impl Fn(u32) -> bool) -> Previous { + let Some(marker) = marker.map(str::trim).filter(|marker| !marker.is_empty()) else { + return Previous::None; + }; + let pid = marker + .split_whitespace() + .find_map(|field| field.strip_prefix("pid=")) + .and_then(|pid| pid.parse::().ok()); + match pid { + Some(pid) if pid != own_pid && alive(pid) => Previous::Running, + _ => Previous::Unclean(marker.to_string()), + } } #[cfg(unix)] @@ -513,6 +539,35 @@ mod native { } } +#[cfg(test)] +mod marker_tests { + use super::{Previous, classify_previous}; + + #[test] + fn a_marker_left_behind_is_an_unclean_end_unless_its_process_still_runs() { + let marker = "pid=41 started=2026-10-25T00:00:00.000Z version=0.6.1"; + assert_eq!(classify_previous(None, 7, |_| false), Previous::None); + assert_eq!(classify_previous(Some(" \n"), 7, |_| false), Previous::None); + assert_eq!( + classify_previous(Some(marker), 7, |_| false), + Previous::Unclean(marker.into()) + ); + assert_eq!( + classify_previous(Some(marker), 7, |pid| pid == 41), + Previous::Running + ); + // A reused pid that is now this process is still a dead session. + assert_eq!( + classify_previous(Some(marker), 41, |_| true), + Previous::Unclean(marker.into()) + ); + assert_eq!( + classify_previous(Some("garbage"), 7, |_| true), + Previous::Unclean("garbage".into()) + ); + } +} + /// Each case runs in a child copy of this test binary, because the handlers /// are process-wide and the child has to actually die. #[cfg(test)] From d81c77b47fe12703f499c2eae7f32541c52625a9 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sun, 25 Oct 2026 01:56:30 +0100 Subject: [PATCH 6/6] fix(desktop-gpui): start the crash session after the instance lock, bound and fully capture stderr --- apps/desktop-gpui/src/crash_capture.rs | 229 ++++++++++++++----------- apps/desktop-gpui/src/editor_export.rs | 6 +- apps/desktop-gpui/src/main.rs | 1 + 3 files changed, 135 insertions(+), 101 deletions(-) diff --git a/apps/desktop-gpui/src/crash_capture.rs b/apps/desktop-gpui/src/crash_capture.rs index f1822e8c564..824b435a4af 100644 --- a/apps/desktop-gpui/src/crash_capture.rs +++ b/apps/desktop-gpui/src/crash_capture.rs @@ -32,11 +32,15 @@ const PREVIOUS_STDERR_FILE: &str = "cap-gpui.log.stderr-previous"; const SESSION_FILE: &str = "cap-gpui.session"; /// A crash loop must not fill the disk. const MAX_CRASH_FILE_BYTES: u64 = 512 * 1024; +/// A native library that keeps complaining must not either; the upload only +/// carries the tail. +const MAX_STDERR_FILE_BYTES: u64 = 8 * 1024 * 1024; static CRASH_LOG: OnceLock = OnceLock::new(); static SESSION_MARKER: OnceLock = OnceLock::new(); /// Call once, right after logging starts and before any other thread work. +/// The session itself starts in [`begin_session`]. pub fn install(logs_dir: &Path) { let _ = std::fs::create_dir_all(logs_dir); let crash_path = logs_dir.join(CRASH_FILE); @@ -53,16 +57,18 @@ pub fn install(logs_dir: &Path) { } Err(error) => tracing::warn!(%error, "could not open the crash record file"), } - let owns_session = report_previous_session(logs_dir); install_panic_hook(); native::install(); - // A second instance hands off and exits; the running one keeps its files. - if owns_session { - capture_stderr(logs_dir); - } } -/// Clears the session marker; call from the app's quit path. +/// Call once this process holds the single-instance lock: a second launch +/// hands off and exits before it can touch the running instance's marker or +/// stderr file, so whatever marker is left belongs to a session that is gone. +pub fn begin_session(logs_dir: &Path) { + report_previous_session(logs_dir); + capture_stderr(logs_dir); +} + pub fn mark_clean_exit() { if let Some(marker) = SESSION_MARKER.get() { let _ = std::fs::remove_file(marker); @@ -79,22 +85,14 @@ fn record(text: &str) { } } -/// False when another running Cap owns the session marker. -fn report_previous_session(logs_dir: &Path) -> bool { +fn report_previous_session(logs_dir: &Path) { let marker = logs_dir.join(SESSION_FILE); - let previous = std::fs::read_to_string(&marker).ok(); - match classify_previous(previous.as_deref(), std::process::id(), process_alive) { - // Another Cap is running and owns the marker: this launch is a second - // instance about to hand off and exit, and must not overwrite it. - Previous::Running => return false, - Previous::Unclean(previous) => { - tracing::error!(previous = %previous, "the previous Cap session ended without a clean quit"); - record(&format!( - "{} previous session ended without a clean quit: {previous}\n", - now() - )); - } - Previous::None => {} + if let Some(previous) = previous_session(std::fs::read_to_string(&marker).ok().as_deref()) { + tracing::error!(previous = %previous, "the previous Cap session ended without a clean quit"); + record(&format!( + "{} previous session ended without a clean quit: {previous}\n", + now() + )); } let contents = format!( "pid={} started={} version={}\n", @@ -105,65 +103,14 @@ fn report_previous_session(logs_dir: &Path) -> bool { if std::fs::write(&marker, contents).is_ok() { let _ = SESSION_MARKER.set(marker); } - true } -#[derive(Debug, PartialEq, Eq)] -enum Previous { - None, - Running, - Unclean(String), -} - -fn classify_previous(marker: Option<&str>, own_pid: u32, alive: impl Fn(u32) -> bool) -> Previous { - let Some(marker) = marker.map(str::trim).filter(|marker| !marker.is_empty()) else { - return Previous::None; - }; - let pid = marker - .split_whitespace() - .find_map(|field| field.strip_prefix("pid=")) - .and_then(|pid| pid.parse::().ok()); - match pid { - Some(pid) if pid != own_pid && alive(pid) => Previous::Running, - _ => Previous::Unclean(marker.to_string()), - } -} - -#[cfg(unix)] -fn process_alive(pid: u32) -> bool { - let Ok(pid) = libc::pid_t::try_from(pid) else { - return false; - }; - // Signal 0 checks existence; EPERM still means the process is there. - unsafe { libc::kill(pid, 0) == 0 || *libc_errno() == libc::EPERM } -} - -#[cfg(target_os = "linux")] -unsafe fn libc_errno() -> *mut libc::c_int { - unsafe { libc::__errno_location() } -} - -#[cfg(target_os = "macos")] -unsafe fn libc_errno() -> *mut libc::c_int { - unsafe { libc::__error() } -} - -#[cfg(windows)] -fn process_alive(pid: u32) -> bool { - use windows_sys::Win32::{ - Foundation::{CloseHandle, STILL_ACTIVE}, - System::Threading::{GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION}, - }; - unsafe { - let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); - if handle.is_null() { - return false; - } - let mut code = 0u32; - let alive = GetExitCodeProcess(handle, &mut code) != 0 && code == STILL_ACTIVE as u32; - CloseHandle(handle); - alive - } +/// The marker a session left behind, which only a clean quit removes. +fn previous_session(marker: Option<&str>) -> Option { + marker + .map(str::trim) + .filter(|marker| !marker.is_empty()) + .map(str::to_owned) } fn install_panic_hook() { @@ -211,10 +158,30 @@ fn capture_stderr(logs_dir: &Path) { if path.exists() { let _ = std::fs::rename(&path, logs_dir.join(PREVIOUS_STDERR_FILE)); } - let Ok(file) = File::create(&path) else { + // Append mode, so writes land at the end again after a trim. + let Ok(file) = OpenOptions::new().create(true).append(true).open(&path) else { return; }; native::redirect_stderr(file); + let _ = std::thread::Builder::new() + .name("cap-stderr-limit".into()) + .spawn(move || { + loop { + std::thread::sleep(std::time::Duration::from_secs(30)); + trim_if_over(&path, MAX_STDERR_FILE_BYTES); + } + }); +} + +fn trim_if_over(path: &Path, max: u64) -> bool { + if !std::fs::metadata(path).is_ok_and(|metadata| metadata.len() > max) { + return false; + } + OpenOptions::new() + .write(true) + .open(path) + .and_then(|file| file.set_len(0)) + .is_ok() } #[cfg(unix)] @@ -434,7 +401,25 @@ mod native { } } + unsafe extern "C" { + fn _open_osfhandle(handle: isize, flags: i32) -> i32; + fn _dup2(from: i32, to: i32) -> i32; + } + + const O_APPEND: i32 = 0x0008; + + /// Rust and `GetStdHandle` callers follow the standard handle; native + /// libraries writing `fprintf(stderr, ...)` go through the C runtime's + /// descriptor 2, which needs its own redirect. pub fn redirect_stderr(file: File) { + if let Ok(crt) = file.try_clone() { + unsafe { + let descriptor = _open_osfhandle(crt.into_raw_handle() as isize, O_APPEND); + if descriptor >= 0 { + _dup2(descriptor, 2); + } + } + } unsafe { SetStdHandle(STD_ERROR_HANDLE, file.into_raw_handle() as HANDLE); } @@ -541,31 +526,39 @@ mod native { #[cfg(test)] mod marker_tests { - use super::{Previous, classify_previous}; + use super::{previous_session, trim_if_over}; + use std::io::Write as _; #[test] - fn a_marker_left_behind_is_an_unclean_end_unless_its_process_still_runs() { + fn any_marker_left_behind_is_an_unclean_end() { let marker = "pid=41 started=2026-10-25T00:00:00.000Z version=0.6.1"; - assert_eq!(classify_previous(None, 7, |_| false), Previous::None); - assert_eq!(classify_previous(Some(" \n"), 7, |_| false), Previous::None); + assert_eq!(previous_session(None), None); + assert_eq!(previous_session(Some(" \n")), None); + assert_eq!(previous_session(Some(marker)), Some(marker.into())); assert_eq!( - classify_previous(Some(marker), 7, |_| false), - Previous::Unclean(marker.into()) - ); - assert_eq!( - classify_previous(Some(marker), 7, |pid| pid == 41), - Previous::Running - ); - // A reused pid that is now this process is still a dead session. - assert_eq!( - classify_previous(Some(marker), 41, |_| true), - Previous::Unclean(marker.into()) - ); - assert_eq!( - classify_previous(Some("garbage"), 7, |_| true), - Previous::Unclean("garbage".into()) + previous_session(Some(&format!("{marker}\n"))), + Some(marker.into()) ); } + + /// The writer keeps its handle open across a trim and must keep writing + /// at the new end, not at its old offset. + #[test] + fn stderr_trims_once_over_the_limit_and_keeps_appending() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(super::STDERR_FILE); + let mut writer = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&path) + .unwrap(); + writer.write_all(&[b'x'; 64]).unwrap(); + assert!(!trim_if_over(&path, 100)); + writer.write_all(&[b'x'; 64]).unwrap(); + assert!(trim_if_over(&path, 100)); + writer.write_all(b"after the trim\n").unwrap(); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "after the trim\n"); + } } /// Each case runs in a child copy of this test binary, because the handlers @@ -577,12 +570,13 @@ mod process_tests { const CHILD: &str = "CAP_CRASH_CAPTURE_CHILD"; const LOGS: &str = "CAP_CRASH_CAPTURE_LOGS"; - /// In the child: install the handlers, then die the way `kind` says. fn child(kind: &str) -> bool { if std::env::var(CHILD).as_deref() != Ok(kind) { return false; } - super::install(Path::new(&std::env::var(LOGS).unwrap())); + let logs = std::env::var(LOGS).unwrap(); + super::install(Path::new(&logs)); + super::begin_session(Path::new(&logs)); match kind { "fault" => unsafe { std::ptr::write_volatile(std::ptr::null_mut::(), 1) }, "overflow" => { @@ -595,6 +589,21 @@ mod process_tests { std::hint::black_box(recurse(0)); } "panic" => panic!("crash capture test panic"), + "native-stderr" => { + let line = b"written by native code\n"; + #[cfg(unix)] + unsafe { + libc::write(2, line.as_ptr().cast(), line.len()); + } + #[cfg(windows)] + unsafe { + unsafe extern "C" { + fn _write(descriptor: i32, buffer: *const u8, count: u32) -> i32; + } + _write(2, line.as_ptr(), line.len() as u32); + } + std::process::exit(0); + } _ => {} } true @@ -603,6 +612,7 @@ mod process_tests { struct Died { crashes: String, stderr: String, + captured_stderr: String, success: bool, } @@ -620,6 +630,7 @@ mod process_tests { Died { crashes: read(super::CRASH_FILE), stderr: read(super::STDERR_FILE) + &String::from_utf8_lossy(&status.stderr), + captured_stderr: read(super::STDERR_FILE), success: status.status.success(), } } @@ -648,6 +659,24 @@ mod process_tests { ); } + /// What a native library prints through the C runtime's stderr. + #[test] + fn native_stderr_writes_reach_the_captured_file() { + if child("native-stderr") { + return; + } + let died = run( + "crash_capture::process_tests::native_stderr_writes_reach_the_captured_file", + "native-stderr", + ); + assert!(died.success); + assert!( + died.captured_stderr.contains("written by native code"), + "{}", + died.stderr + ); + } + /// Rust's own overflow report must survive: the handler chains to it. #[test] fn a_stack_overflow_is_recorded_and_rust_still_reports_it() { diff --git a/apps/desktop-gpui/src/editor_export.rs b/apps/desktop-gpui/src/editor_export.rs index 8077de80010..53252dccb2a 100644 --- a/apps/desktop-gpui/src/editor_export.rs +++ b/apps/desktop-gpui/src/editor_export.rs @@ -1325,9 +1325,13 @@ impl EditorWindow { } } Ok(Err(error)) => { - tracing::error!(error, "share export failed"); let cancelled = !is_resource_stop(&error) && (error == "Export cancelled" || cancel.load(Ordering::Relaxed)); + if cancelled { + tracing::info!(error, "share export cancelled"); + } else { + tracing::error!(error, "share export failed"); + } let _ = this.update(cx, |this, cx| { if let Some(ui) = this.export.as_mut() { if cancelled { diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs index 68e9bb6eed7..d48c8dd55ee 100644 --- a/apps/desktop-gpui/src/main.rs +++ b/apps/desktop-gpui/src/main.rs @@ -292,6 +292,7 @@ fn main() { crash_capture::install(&diagnostics::logs_dir()); single_instance::acquire(); + crash_capture::begin_session(&diagnostics::logs_dir()); if cfg!(debug_assertions) { store::mark_handoff_session(); }