crashes.rs

  1use crash_handler::{CrashEventResult, CrashHandler};
  2use log::info;
  3use minidumper::{Client, LoopAction, MinidumpBinary};
  4use release_channel::{RELEASE_CHANNEL, ReleaseChannel};
  5use serde::{Deserialize, Serialize};
  6
  7#[cfg(not(target_os = "windows"))]
  8use smol::process::Command;
  9
 10#[cfg(target_os = "macos")]
 11use std::sync::atomic::AtomicU32;
 12use std::{
 13    env,
 14    fs::{self, File},
 15    io,
 16    panic::{self, PanicHookInfo},
 17    path::{Path, PathBuf},
 18    process::{self},
 19    sync::{
 20        Arc, OnceLock,
 21        atomic::{AtomicBool, Ordering},
 22    },
 23    thread,
 24    time::Duration,
 25};
 26
 27// set once the crash handler has initialized and the client has connected to it
 28pub static CRASH_HANDLER: OnceLock<Arc<Client>> = OnceLock::new();
 29// set when the first minidump request is made to avoid generating duplicate crash reports
 30pub static REQUESTED_MINIDUMP: AtomicBool = AtomicBool::new(false);
 31const CRASH_HANDLER_PING_TIMEOUT: Duration = Duration::from_secs(60);
 32const CRASH_HANDLER_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
 33
 34#[cfg(target_os = "macos")]
 35static PANIC_THREAD_ID: AtomicU32 = AtomicU32::new(0);
 36
 37pub async fn init(crash_init: InitCrashHandler) {
 38    let gen_var = match env::var("ZED_GENERATE_MINIDUMPS") {
 39        Ok(v) => {
 40            if v == "false" || v == "0" {
 41                Some(false)
 42            } else {
 43                Some(true)
 44            }
 45        }
 46        Err(_) => None,
 47    };
 48
 49    match (gen_var, *RELEASE_CHANNEL) {
 50        (Some(false), _) | (None, ReleaseChannel::Dev) => {
 51            let old_hook = panic::take_hook();
 52            panic::set_hook(Box::new(move |info| {
 53                unsafe { env::set_var("RUST_BACKTRACE", "1") };
 54                old_hook(info);
 55                // prevent the macOS crash dialog from popping up
 56                if cfg!(target_os = "macos") {
 57                    std::process::exit(1);
 58                }
 59            }));
 60            return;
 61        }
 62        _ => {
 63            panic::set_hook(Box::new(panic_hook));
 64        }
 65    }
 66
 67    let exe = env::current_exe().expect("unable to find ourselves");
 68    let zed_pid = process::id();
 69    // TODO: we should be able to get away with using 1 crash-handler process per machine,
 70    // but for now we append the PID of the current process which makes it unique per remote
 71    // server or interactive zed instance. This solves an issue where occasionally the socket
 72    // used by the crash handler isn't destroyed correctly which causes it to stay on the file
 73    // system and block further attempts to initialize crash handlers with that socket path.
 74    let socket_name = paths::temp_dir().join(format!("zed-crash-handler-{zed_pid}"));
 75    #[cfg(not(target_os = "windows"))]
 76    let _crash_handler = Command::new(exe)
 77        .arg("--crash-handler")
 78        .arg(&socket_name)
 79        .spawn()
 80        .expect("unable to spawn server process");
 81
 82    #[cfg(target_os = "windows")]
 83    spawn_crash_handler_windows(&exe, &socket_name);
 84
 85    #[cfg(target_os = "linux")]
 86    let server_pid = _crash_handler.id();
 87    info!("spawning crash handler process");
 88
 89    let mut elapsed = Duration::ZERO;
 90    let retry_frequency = Duration::from_millis(100);
 91    let mut maybe_client = None;
 92    while maybe_client.is_none() {
 93        if let Ok(client) = Client::with_name(socket_name.as_path()) {
 94            maybe_client = Some(client);
 95            info!("connected to crash handler process after {elapsed:?}");
 96            break;
 97        }
 98        elapsed += retry_frequency;
 99        smol::Timer::after(retry_frequency).await;
100    }
101    let client = maybe_client.unwrap();
102    client
103        .send_message(1, serde_json::to_vec(&crash_init).unwrap())
104        .unwrap();
105
106    let client = Arc::new(client);
107    let handler = CrashHandler::attach(unsafe {
108        let client = client.clone();
109        crash_handler::make_crash_event(move |crash_context: &crash_handler::CrashContext| {
110            // only request a minidump once
111            let res = if REQUESTED_MINIDUMP
112                .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
113                .is_ok()
114            {
115                #[cfg(target_os = "macos")]
116                suspend_all_other_threads();
117
118                // on macos this "ping" is needed to ensure that all our
119                // `client.send_message` calls have been processed before we trigger the
120                // minidump request.
121                client.ping().ok();
122                client.request_dump(crash_context).is_ok()
123            } else {
124                true
125            };
126            CrashEventResult::Handled(res)
127        })
128    })
129    .expect("failed to attach signal handler");
130
131    #[cfg(target_os = "linux")]
132    {
133        handler.set_ptracer(Some(server_pid));
134    }
135    CRASH_HANDLER.set(client.clone()).ok();
136    std::mem::forget(handler);
137    info!("crash handler registered");
138
139    loop {
140        client.ping().ok();
141        smol::Timer::after(Duration::from_secs(10)).await;
142    }
143}
144
145#[cfg(target_os = "macos")]
146unsafe fn suspend_all_other_threads() {
147    let task = unsafe { mach2::traps::current_task() };
148    let mut threads: mach2::mach_types::thread_act_array_t = std::ptr::null_mut();
149    let mut count = 0;
150    unsafe {
151        mach2::task::task_threads(task, &raw mut threads, &raw mut count);
152    }
153    let current = unsafe { mach2::mach_init::mach_thread_self() };
154    let panic_thread = PANIC_THREAD_ID.load(Ordering::SeqCst);
155    for i in 0..count {
156        let t = unsafe { *threads.add(i as usize) };
157        if t != current && t != panic_thread {
158            unsafe { mach2::thread_act::thread_suspend(t) };
159        }
160    }
161}
162
163pub struct CrashServer {
164    initialization_params: OnceLock<InitCrashHandler>,
165    panic_info: OnceLock<CrashPanic>,
166    active_gpu: OnceLock<system_specs::GpuSpecs>,
167    has_connection: Arc<AtomicBool>,
168}
169
170#[derive(Debug, Deserialize, Serialize, Clone)]
171pub struct CrashInfo {
172    pub init: InitCrashHandler,
173    pub panic: Option<CrashPanic>,
174    pub minidump_error: Option<String>,
175    pub gpus: Vec<system_specs::GpuInfo>,
176    pub active_gpu: Option<system_specs::GpuSpecs>,
177}
178
179#[derive(Debug, Deserialize, Serialize, Clone)]
180pub struct InitCrashHandler {
181    pub session_id: String,
182    pub zed_version: String,
183    pub binary: String,
184    pub release_channel: String,
185    pub commit_sha: String,
186}
187
188#[derive(Deserialize, Serialize, Debug, Clone)]
189pub struct CrashPanic {
190    pub message: String,
191    pub span: String,
192}
193
194impl minidumper::ServerHandler for CrashServer {
195    fn create_minidump_file(&self) -> Result<(File, PathBuf), io::Error> {
196        let err_message = "Missing initialization data";
197        let dump_path = paths::logs_dir()
198            .join(
199                &self
200                    .initialization_params
201                    .get()
202                    .expect(err_message)
203                    .session_id,
204            )
205            .with_extension("dmp");
206        let file = File::create(&dump_path)?;
207        Ok((file, dump_path))
208    }
209
210    fn on_minidump_created(&self, result: Result<MinidumpBinary, minidumper::Error>) -> LoopAction {
211        let minidump_error = match result {
212            Ok(MinidumpBinary { mut file, path, .. }) => {
213                use io::Write;
214                file.flush().ok();
215                // TODO: clean this up once https://github.com/EmbarkStudios/crash-handling/issues/101 is addressed
216                drop(file);
217                let original_file = File::open(&path).unwrap();
218                let compressed_path = path.with_extension("zstd");
219                let compressed_file = File::create(&compressed_path).unwrap();
220                zstd::stream::copy_encode(original_file, compressed_file, 0).ok();
221                fs::rename(&compressed_path, path).unwrap();
222                None
223            }
224            Err(e) => Some(format!("{e:?}")),
225        };
226
227        #[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
228        let gpus = vec![];
229
230        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
231        let gpus = match system_specs::read_gpu_info_from_sys_class_drm() {
232            Ok(gpus) => gpus,
233            Err(err) => {
234                log::warn!("Failed to collect GPU information for crash report: {err}");
235                vec![]
236            }
237        };
238
239        let crash_info = CrashInfo {
240            init: self
241                .initialization_params
242                .get()
243                .expect("not initialized")
244                .clone(),
245            panic: self.panic_info.get().cloned(),
246            minidump_error,
247            active_gpu: self.active_gpu.get().cloned(),
248            gpus,
249        };
250
251        let crash_data_path = paths::logs_dir()
252            .join(&crash_info.init.session_id)
253            .with_extension("json");
254
255        fs::write(crash_data_path, serde_json::to_vec(&crash_info).unwrap()).ok();
256
257        LoopAction::Exit
258    }
259
260    fn on_message(&self, kind: u32, buffer: Vec<u8>) {
261        match kind {
262            1 => {
263                let init_data =
264                    serde_json::from_slice::<InitCrashHandler>(&buffer).expect("invalid init data");
265                self.initialization_params
266                    .set(init_data)
267                    .expect("already initialized");
268            }
269            2 => {
270                let panic_data =
271                    serde_json::from_slice::<CrashPanic>(&buffer).expect("invalid panic data");
272                self.panic_info.set(panic_data).expect("already panicked");
273            }
274            3 => {
275                let gpu_specs: system_specs::GpuSpecs =
276                    bincode::deserialize(&buffer).expect("gpu specs");
277                // we ignore the case where it was already set because this message is sent
278                // on each new window. in theory all zed windows should be using the same
279                // GPU so this is fine.
280                self.active_gpu.set(gpu_specs).ok();
281            }
282            _ => {
283                panic!("invalid message kind");
284            }
285        }
286    }
287
288    fn on_client_disconnected(&self, _clients: usize) -> LoopAction {
289        LoopAction::Exit
290    }
291
292    fn on_client_connected(&self, _clients: usize) -> LoopAction {
293        self.has_connection.store(true, Ordering::SeqCst);
294        LoopAction::Continue
295    }
296}
297
298pub fn panic_hook(info: &PanicHookInfo) {
299    // Don't handle a panic on threads that are not relevant to the main execution.
300    if extension_host::wasm_host::IS_WASM_THREAD.with(|v| v.load(Ordering::Acquire)) {
301        log::error!("wasm thread panicked!");
302        return;
303    }
304
305    let message = info.payload_as_str().unwrap_or("Box<Any>").to_owned();
306
307    let span = info
308        .location()
309        .map(|loc| format!("{}:{}", loc.file(), loc.line()))
310        .unwrap_or_default();
311
312    let current_thread = std::thread::current();
313    let thread_name = current_thread.name().unwrap_or("<unnamed>");
314
315    // wait 500ms for the crash handler process to start up
316    // if it's still not there just write panic info and no minidump
317    let retry_frequency = Duration::from_millis(100);
318    for _ in 0..5 {
319        if let Some(client) = CRASH_HANDLER.get() {
320            let location = info
321                .location()
322                .map_or_else(|| "<unknown>".to_owned(), |location| location.to_string());
323            log::error!("thread '{thread_name}' panicked at {location}:\n{message}...");
324            client
325                .send_message(
326                    2,
327                    serde_json::to_vec(&CrashPanic { message, span }).unwrap(),
328                )
329                .ok();
330            log::error!("triggering a crash to generate a minidump...");
331
332            #[cfg(target_os = "macos")]
333            PANIC_THREAD_ID.store(
334                unsafe { mach2::mach_init::mach_thread_self() },
335                Ordering::SeqCst,
336            );
337
338            cfg_if::cfg_if! {
339                if #[cfg(target_os = "windows")] {
340                    // https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-
341                    CrashHandler.simulate_exception(Some(234)); // (MORE_DATA_AVAILABLE)
342                    break;
343                } else {
344                    std::process::abort();
345                }
346            }
347        }
348        thread::sleep(retry_frequency);
349    }
350}
351
352#[cfg(target_os = "windows")]
353fn spawn_crash_handler_windows(exe: &Path, socket_name: &Path) {
354    use std::ffi::OsStr;
355    use std::iter::once;
356    use std::os::windows::ffi::OsStrExt;
357    use windows::Win32::System::Threading::{
358        CreateProcessW, PROCESS_CREATION_FLAGS, PROCESS_INFORMATION, STARTF_FORCEOFFFEEDBACK,
359        STARTUPINFOW,
360    };
361    use windows::core::PWSTR;
362
363    let mut command_line: Vec<u16> = OsStr::new(&format!(
364        "\"{}\" --crash-handler \"{}\"",
365        exe.display(),
366        socket_name.display()
367    ))
368    .encode_wide()
369    .chain(once(0))
370    .collect();
371
372    let mut startup_info = STARTUPINFOW::default();
373    startup_info.cb = std::mem::size_of::<STARTUPINFOW>() as u32;
374
375    // By default, Windows enables a "busy" cursor when a GUI application is launched.
376    // This cursor is disabled once the application starts processing window messages.
377    // Since the crash handler process doesn't process messages, this "busy" cursor stays enabled for a long time.
378    // Disable the cursor feedback to prevent this from happening.
379    startup_info.dwFlags = STARTF_FORCEOFFFEEDBACK;
380
381    let mut process_info = PROCESS_INFORMATION::default();
382
383    unsafe {
384        CreateProcessW(
385            None,
386            Some(PWSTR(command_line.as_mut_ptr())),
387            None,
388            None,
389            false,
390            PROCESS_CREATION_FLAGS(0),
391            None,
392            None,
393            &startup_info,
394            &mut process_info,
395        )
396        .expect("unable to spawn server process");
397
398        windows::Win32::Foundation::CloseHandle(process_info.hProcess).ok();
399        windows::Win32::Foundation::CloseHandle(process_info.hThread).ok();
400    }
401}
402
403pub fn crash_server(socket: &Path) {
404    let Ok(mut server) = minidumper::Server::with_name(socket) else {
405        log::info!("Couldn't create socket, there may already be a running crash server");
406        return;
407    };
408
409    let shutdown = Arc::new(AtomicBool::new(false));
410    let has_connection = Arc::new(AtomicBool::new(false));
411
412    thread::Builder::new()
413        .name("CrashServerTimeout".to_owned())
414        .spawn({
415            let shutdown = shutdown.clone();
416            let has_connection = has_connection.clone();
417            move || {
418                std::thread::sleep(CRASH_HANDLER_CONNECT_TIMEOUT);
419                if !has_connection.load(Ordering::SeqCst) {
420                    shutdown.store(true, Ordering::SeqCst);
421                }
422            }
423        })
424        .unwrap();
425
426    server
427        .run(
428            Box::new(CrashServer {
429                initialization_params: OnceLock::new(),
430                panic_info: OnceLock::new(),
431                has_connection,
432                active_gpu: OnceLock::new(),
433            }),
434            &shutdown,
435            Some(CRASH_HANDLER_PING_TIMEOUT),
436        )
437        .expect("failed to run server");
438}