1use crash_handler::CrashHandler;
2use log::info;
3use minidumper::{Client, LoopAction, MinidumpBinary};
4use release_channel::{RELEASE_CHANNEL, ReleaseChannel};
5use serde::{Deserialize, Serialize};
6
7use std::{
8 env,
9 fs::{self, File},
10 io,
11 panic::Location,
12 path::{Path, PathBuf},
13 process::{self, Command},
14 sync::{
15 Arc, OnceLock,
16 atomic::{AtomicBool, Ordering},
17 },
18 thread,
19 time::Duration,
20};
21
22// set once the crash handler has initialized and the client has connected to it
23pub static CRASH_HANDLER: OnceLock<Arc<Client>> = OnceLock::new();
24// set when the first minidump request is made to avoid generating duplicate crash reports
25pub static REQUESTED_MINIDUMP: AtomicBool = AtomicBool::new(false);
26const CRASH_HANDLER_PING_TIMEOUT: Duration = Duration::from_secs(60);
27const CRASH_HANDLER_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
28
29pub async fn init(crash_init: InitCrashHandler) {
30 if *RELEASE_CHANNEL == ReleaseChannel::Dev && env::var("ZED_GENERATE_MINIDUMPS").is_err() {
31 return;
32 }
33
34 let exe = env::current_exe().expect("unable to find ourselves");
35 let zed_pid = process::id();
36 // TODO: we should be able to get away with using 1 crash-handler process per machine,
37 // but for now we append the PID of the current process which makes it unique per remote
38 // server or interactive zed instance. This solves an issue where occasionally the socket
39 // used by the crash handler isn't destroyed correctly which causes it to stay on the file
40 // system and block further attempts to initialize crash handlers with that socket path.
41 let socket_name = paths::temp_dir().join(format!("zed-crash-handler-{zed_pid}"));
42 #[allow(unused)]
43 let server_pid = Command::new(exe)
44 .arg("--crash-handler")
45 .arg(&socket_name)
46 .spawn()
47 .expect("unable to spawn server process")
48 .id();
49 info!("spawning crash handler process");
50
51 let mut elapsed = Duration::ZERO;
52 let retry_frequency = Duration::from_millis(100);
53 let mut maybe_client = None;
54 while maybe_client.is_none() {
55 if let Ok(client) = Client::with_name(socket_name.as_path()) {
56 maybe_client = Some(client);
57 info!("connected to crash handler process after {elapsed:?}");
58 break;
59 }
60 elapsed += retry_frequency;
61 smol::Timer::after(retry_frequency).await;
62 }
63 let client = maybe_client.unwrap();
64 client
65 .send_message(1, serde_json::to_vec(&crash_init).unwrap())
66 .unwrap();
67
68 let client = Arc::new(client);
69 let handler = crash_handler::CrashHandler::attach(unsafe {
70 let client = client.clone();
71 crash_handler::make_crash_event(move |crash_context: &crash_handler::CrashContext| {
72 // only request a minidump once
73 let res = if REQUESTED_MINIDUMP
74 .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
75 .is_ok()
76 {
77 client.ping().unwrap();
78 client.request_dump(crash_context).is_ok()
79 } else {
80 true
81 };
82 crash_handler::CrashEventResult::Handled(res)
83 })
84 })
85 .expect("failed to attach signal handler");
86
87 #[cfg(target_os = "linux")]
88 {
89 handler.set_ptracer(Some(server_pid));
90 }
91 CRASH_HANDLER.set(client.clone()).ok();
92 std::mem::forget(handler);
93 info!("crash handler registered");
94
95 loop {
96 client.ping().ok();
97 smol::Timer::after(Duration::from_secs(10)).await;
98 }
99}
100
101pub struct CrashServer {
102 initialization_params: OnceLock<InitCrashHandler>,
103 panic_info: OnceLock<CrashPanic>,
104 has_connection: Arc<AtomicBool>,
105}
106
107#[derive(Debug, Deserialize, Serialize, Clone)]
108pub struct CrashInfo {
109 pub init: InitCrashHandler,
110 pub panic: Option<CrashPanic>,
111}
112
113#[derive(Debug, Deserialize, Serialize, Clone)]
114pub struct InitCrashHandler {
115 pub session_id: String,
116 pub zed_version: String,
117 pub release_channel: String,
118 pub commit_sha: String,
119 // pub gpu: String,
120}
121
122#[derive(Deserialize, Serialize, Debug, Clone)]
123pub struct CrashPanic {
124 pub message: String,
125 pub span: String,
126}
127
128impl minidumper::ServerHandler for CrashServer {
129 fn create_minidump_file(&self) -> Result<(File, PathBuf), io::Error> {
130 let err_message = "Missing initialization data";
131 let dump_path = paths::logs_dir()
132 .join(
133 &self
134 .initialization_params
135 .get()
136 .expect(err_message)
137 .session_id,
138 )
139 .with_extension("dmp");
140 let file = File::create(&dump_path)?;
141 Ok((file, dump_path))
142 }
143
144 fn on_minidump_created(&self, result: Result<MinidumpBinary, minidumper::Error>) -> LoopAction {
145 match result {
146 Ok(mut md_bin) => {
147 use io::Write;
148 let _ = md_bin.file.flush();
149 info!("wrote minidump to disk {:?}", md_bin.path);
150 }
151 Err(e) => {
152 info!("failed to write minidump: {:#}", e);
153 }
154 }
155
156 let crash_info = CrashInfo {
157 init: self
158 .initialization_params
159 .get()
160 .expect("not initialized")
161 .clone(),
162 panic: self.panic_info.get().cloned(),
163 };
164
165 let crash_data_path = paths::logs_dir()
166 .join(&crash_info.init.session_id)
167 .with_extension("json");
168
169 fs::write(crash_data_path, serde_json::to_vec(&crash_info).unwrap()).ok();
170
171 LoopAction::Exit
172 }
173
174 fn on_message(&self, kind: u32, buffer: Vec<u8>) {
175 match kind {
176 1 => {
177 let init_data =
178 serde_json::from_slice::<InitCrashHandler>(&buffer).expect("invalid init data");
179 self.initialization_params
180 .set(init_data)
181 .expect("already initialized");
182 }
183 2 => {
184 let panic_data =
185 serde_json::from_slice::<CrashPanic>(&buffer).expect("invalid panic data");
186 self.panic_info.set(panic_data).expect("already panicked");
187 }
188 _ => {
189 panic!("invalid message kind");
190 }
191 }
192 }
193
194 fn on_client_disconnected(&self, _clients: usize) -> LoopAction {
195 LoopAction::Exit
196 }
197
198 fn on_client_connected(&self, _clients: usize) -> LoopAction {
199 self.has_connection.store(true, Ordering::SeqCst);
200 LoopAction::Continue
201 }
202}
203
204pub fn handle_panic(message: String, span: Option<&Location>) {
205 let span = span
206 .map(|loc| format!("{}:{}", loc.file(), loc.line()))
207 .unwrap_or_default();
208
209 // wait 500ms for the crash handler process to start up
210 // if it's still not there just write panic info and no minidump
211 let retry_frequency = Duration::from_millis(100);
212 for _ in 0..5 {
213 if let Some(client) = CRASH_HANDLER.get() {
214 client
215 .send_message(
216 2,
217 serde_json::to_vec(&CrashPanic { message, span }).unwrap(),
218 )
219 .ok();
220 log::error!("triggering a crash to generate a minidump...");
221 #[cfg(target_os = "linux")]
222 CrashHandler.simulate_signal(crash_handler::Signal::Trap as u32);
223 #[cfg(not(target_os = "linux"))]
224 CrashHandler.simulate_exception(None);
225 break;
226 }
227 thread::sleep(retry_frequency);
228 }
229}
230
231pub fn crash_server(socket: &Path) {
232 let Ok(mut server) = minidumper::Server::with_name(socket) else {
233 log::info!("Couldn't create socket, there may already be a running crash server");
234 return;
235 };
236
237 let shutdown = Arc::new(AtomicBool::new(false));
238 let has_connection = Arc::new(AtomicBool::new(false));
239
240 std::thread::spawn({
241 let shutdown = shutdown.clone();
242 let has_connection = has_connection.clone();
243 move || {
244 std::thread::sleep(CRASH_HANDLER_CONNECT_TIMEOUT);
245 if !has_connection.load(Ordering::SeqCst) {
246 shutdown.store(true, Ordering::SeqCst);
247 }
248 }
249 });
250
251 server
252 .run(
253 Box::new(CrashServer {
254 initialization_params: OnceLock::new(),
255 panic_info: OnceLock::new(),
256 has_connection,
257 }),
258 &shutdown,
259 Some(CRASH_HANDLER_PING_TIMEOUT),
260 )
261 .expect("failed to run server");
262}