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