Debian Codegraph @

third_party/rust/minidump-writer/src/linux/minidump_writer.rs

raw
1 pub use crate::linux::auxv::{AuxvType, DirectAuxvDumpInfo};
2 use {
3 crate::{
4 auxv::AuxvDumpInfo,
5 dir_section::{DirSection, DumpBuf},
6 linux::{
7 app_memory::AppMemoryList,
8 crash_context::CrashContext,
9 dso_debug,
10 errors::WriterError,
11 maps_reader::{MappingInfo, MappingList},
12 ptrace_dumper::PtraceDumper,
13 sections::*,
14 },
15 mem_writer::{Buffer, MemoryArrayWriter, MemoryWriter, MemoryWriterError},
16 minidump_format::*,
17 Pid,
18 },
19 error_graph::{ErrorList, WriteErrorList},
20 std::{
21 io::{Seek, Write},
22 time::Duration,
23 },
24 };
25
26 pub enum CrashingThreadContext {
27 None,
28 CrashContext(MDLocationDescriptor),
29 CrashContextPlusAddress((MDLocationDescriptor, usize)),
30 }
31
32 /// The default timeout after a `SIGSTOP` after which minidump writing proceeds
33 /// regardless of the process state
34 pub const STOP_TIMEOUT: Duration = Duration::from_millis(100);
35
36 pub struct MinidumpWriter {
37 pub process_id: Pid,
38 pub blamed_thread: Pid,
39 pub minidump_size_limit: Option<u64>,
40 pub skip_stacks_if_mapping_unreferenced: bool,
41 pub principal_mapping_address: Option<usize>,
42 pub user_mapping_list: MappingList,
43 pub app_memory: AppMemoryList,
44 pub memory_blocks: Vec<MDMemoryDescriptor>,
45 pub principal_mapping: Option<MappingInfo>,
46 pub sanitize_stack: bool,
47 pub crash_context: Option<CrashContext>,
48 pub crashing_thread_context: CrashingThreadContext,
49 pub stop_timeout: Duration,
50 pub direct_auxv_dump_info: Option<DirectAuxvDumpInfo>,
51 }
52
53 // This doesn't work yet:
54 // https://github.com/rust-lang/rust/issues/43408
55 // fn write<T: Sized, P: AsRef<Path>>(path: P, value: T) -> Result<()> {
56 // let mut file = std::fs::File::open(path)?;
57 // let bytes: [u8; size_of::<T>()] = unsafe { transmute(value) };
58 // file.write_all(&bytes)?;
59 // Ok(())
60 // }
61
62 type Result<T> = std::result::Result<T, WriterError>;
63
64 impl MinidumpWriter {
65 pub fn new(process: Pid, blamed_thread: Pid) -> Self {
66 Self {
67 process_id: process,
68 blamed_thread,
69 minidump_size_limit: None,
70 skip_stacks_if_mapping_unreferenced: false,
71 principal_mapping_address: None,
72 user_mapping_list: MappingList::new(),
73 app_memory: AppMemoryList::new(),
74 memory_blocks: Vec::new(),
75 principal_mapping: None,
76 sanitize_stack: false,
77 crash_context: None,
78 crashing_thread_context: CrashingThreadContext::None,
79 stop_timeout: STOP_TIMEOUT,
80 direct_auxv_dump_info: None,
81 }
82 }
83
84 pub fn set_minidump_size_limit(&mut self, limit: u64) -> &mut Self {
85 self.minidump_size_limit = Some(limit);
86 self
87 }
88
89 pub fn set_user_mapping_list(&mut self, user_mapping_list: MappingList) -> &mut Self {
90 self.user_mapping_list = user_mapping_list;
91 self
92 }
93
94 pub fn set_principal_mapping_address(&mut self, principal_mapping_address: usize) -> &mut Self {
95 self.principal_mapping_address = Some(principal_mapping_address);
96 self
97 }
98
99 pub fn set_app_memory(&mut self, app_memory: AppMemoryList) -> &mut Self {
100 self.app_memory = app_memory;
101 self
102 }
103
104 pub fn set_crash_context(&mut self, crash_context: CrashContext) -> &mut Self {
105 self.crash_context = Some(crash_context);
106 self
107 }
108
109 pub fn skip_stacks_if_mapping_unreferenced(&mut self) -> &mut Self {
110 self.skip_stacks_if_mapping_unreferenced = true; // Off by default
111 self
112 }
113
114 pub fn sanitize_stack(&mut self) -> &mut Self {
115 self.sanitize_stack = true; // Off by default
116 self
117 }
118
119 /// Sets the timeout after `SIGSTOP` is sent to the process, if the process
120 /// has not stopped by the time the timeout has reached, we proceed with
121 /// minidump generation
122 pub fn stop_timeout(&mut self, duration: Duration) -> &mut Self {
123 self.stop_timeout = duration;
124 self
125 }
126
127 /// Directly set important Auxv info determined by the crashing process
128 ///
129 /// Since `/proc/{pid}/auxv` can sometimes be inaccessible, the calling process should prefer to transfer this
130 /// information directly using the Linux `getauxval()` call (if possible).
131 ///
132 /// Any field that is set to `0` will be considered unset. In that case, minidump-writer might try other techniques
133 /// to obtain it (like reading `/proc/{pid}/auxv`).
134 pub fn set_direct_auxv_dump_info(
135 &mut self,
136 direct_auxv_dump_info: DirectAuxvDumpInfo,
137 ) -> &mut Self {
138 self.direct_auxv_dump_info = Some(direct_auxv_dump_info);
139 self
140 }
141
142 /// Generates a minidump and writes to the destination provided. Returns the in-memory
143 /// version of the minidump as well.
144 pub fn dump(&mut self, destination: &mut (impl Write + Seek)) -> Result<Vec<u8>> {
145 let auxv = self
146 .direct_auxv_dump_info
147 .clone()
148 .map(AuxvDumpInfo::from)
149 .unwrap_or_default();
150
151 let mut soft_errors = ErrorList::default();
152
153 let mut dumper = PtraceDumper::new_report_soft_errors(
154 self.process_id,
155 self.stop_timeout,
156 auxv,
157 soft_errors.subwriter(WriterError::InitErrors),
158 )?;
159
160 let threads_count = dumper.threads.len();
161
162 dumper.suspend_threads(soft_errors.subwriter(WriterError::SuspendThreadsErrors));
163
164 if dumper.threads.is_empty() {
165 soft_errors.push(WriterError::SuspendNoThreadsLeft(threads_count));
166 }
167
168 dumper.late_init()?;
169
170 if self.skip_stacks_if_mapping_unreferenced {
171 if let Some(address) = self.principal_mapping_address {
172 self.principal_mapping = dumper.find_mapping_no_bias(address).cloned();
173 }
174
175 if !self.crash_thread_references_principal_mapping(&dumper) {
176 soft_errors.push(WriterError::PrincipalMappingNotReferenced);
177 }
178 }
179
180 let mut buffer = Buffer::with_capacity(0);
181 self.generate_dump(&mut buffer, &mut dumper, soft_errors, destination)?;
182
183 Ok(buffer.into())
184 }
185
186 fn crash_thread_references_principal_mapping(&self, dumper: &PtraceDumper) -> bool {
187 if self.crash_context.is_none() || self.principal_mapping.is_none() {
188 return false;
189 }
190
191 let low_addr = self
192 .principal_mapping
193 .as_ref()
194 .unwrap()
195 .system_mapping_info
196 .start_address;
197 let high_addr = self
198 .principal_mapping
199 .as_ref()
200 .unwrap()
201 .system_mapping_info
202 .end_address;
203
204 let pc = self
205 .crash_context
206 .as_ref()
207 .unwrap()
208 .get_instruction_pointer();
209 let stack_pointer = self.crash_context.as_ref().unwrap().get_stack_pointer();
210
211 if pc >= low_addr && pc < high_addr {
212 return true;
213 }
214
215 let (valid_stack_pointer, stack_len) = match dumper.get_stack_info(stack_pointer) {
216 Ok(x) => x,
217 Err(_) => {
218 return false;
219 }
220 };
221
222 let stack_copy = match PtraceDumper::copy_from_process(
223 self.blamed_thread,
224 valid_stack_pointer,
225 stack_len,
226 ) {
227 Ok(x) => x,
228 Err(_) => {
229 return false;
230 }
231 };
232
233 let sp_offset = stack_pointer.saturating_sub(valid_stack_pointer);
234 self.principal_mapping
235 .as_ref()
236 .unwrap()
237 .stack_has_pointer_to_mapping(&stack_copy, sp_offset)
238 }
239
240 fn generate_dump(
241 &mut self,
242 buffer: &mut DumpBuf,
243 dumper: &mut PtraceDumper,
244 mut soft_errors: ErrorList<WriterError>,
245 destination: &mut (impl Write + Seek),
246 ) -> Result<()> {
247 // A minidump file contains a number of tagged streams. This is the number
248 // of streams which we write.
249 let num_writers = 18u32;
250
251 let mut header_section = MemoryWriter::<MDRawHeader>::alloc(buffer)?;
252
253 let mut dir_section = DirSection::new(buffer, num_writers, destination)?;
254
255 let header = MDRawHeader {
256 signature: MD_HEADER_SIGNATURE,
257 version: MD_HEADER_VERSION,
258 stream_count: num_writers,
259 // header.get()->stream_directory_rva = dir.position();
260 stream_directory_rva: dir_section.position(),
261 checksum: 0, /* Can be 0. In fact, that's all that's
262 * been found in minidump files. */
263 time_date_stamp: std::time::SystemTime::now()
264 .duration_since(std::time::UNIX_EPOCH)?
265 .as_secs() as u32, // TODO: This is not Y2038 safe, but thats how its currently defined as
266 flags: 0,
267 };
268 header_section.set_value(buffer, header)?;
269
270 // Ensure the header gets flushed. If we crash somewhere below,
271 // we should have a mostly-intact dump
272 dir_section.write_to_file(buffer, None)?;
273
274 let dirent = thread_list_stream::write(self, buffer, dumper)?;
275 dir_section.write_to_file(buffer, Some(dirent))?;
276
277 let dirent = mappings::write(self, buffer, dumper)?;
278 dir_section.write_to_file(buffer, Some(dirent))?;
279
280 app_memory::write(self, buffer)?;
281 dir_section.write_to_file(buffer, None)?;
282
283 let dirent = memory_list_stream::write(self, buffer)?;
284 dir_section.write_to_file(buffer, Some(dirent))?;
285
286 let dirent = exception_stream::write(self, buffer)?;
287 dir_section.write_to_file(buffer, Some(dirent))?;
288
289 let dirent = systeminfo_stream::write(
290 buffer,
291 soft_errors.subwriter(WriterError::WriteSystemInfoErrors),
292 )?;
293 dir_section.write_to_file(buffer, Some(dirent))?;
294
295 let dirent = memory_info_list_stream::write(self, buffer)?;
296 dir_section.write_to_file(buffer, Some(dirent))?;
297
298 let dirent = match self.write_file(buffer, "/proc/cpuinfo") {
299 Ok(location) => MDRawDirectory {
300 stream_type: MDStreamType::LinuxCpuInfo as u32,
301 location,
302 },
303 Err(e) => {
304 soft_errors.push(WriterError::WriteCpuInfoFailed(e));
305 Default::default()
306 }
307 };
308 dir_section.write_to_file(buffer, Some(dirent))?;
309
310 let dirent = match self.write_file(buffer, &format!("/proc/{}/status", self.blamed_thread))
311 {
312 Ok(location) => MDRawDirectory {
313 stream_type: MDStreamType::LinuxProcStatus as u32,
314 location,
315 },
316 Err(e) => {
317 soft_errors.push(WriterError::WriteThreadProcStatusFailed(e));
318 Default::default()
319 }
320 };
321 dir_section.write_to_file(buffer, Some(dirent))?;
322
323 let dirent = match self
324 .write_file(buffer, "/etc/lsb-release")
325 .or_else(|_| self.write_file(buffer, "/etc/os-release"))
326 {
327 Ok(location) => MDRawDirectory {
328 stream_type: MDStreamType::LinuxLsbRelease as u32,
329 location,
330 },
331 Err(e) => {
332 soft_errors.push(WriterError::WriteOsReleaseInfoFailed(e));
333 Default::default()
334 }
335 };
336 dir_section.write_to_file(buffer, Some(dirent))?;
337
338 let dirent = match self.write_file(buffer, &format!("/proc/{}/cmdline", self.blamed_thread))
339 {
340 Ok(location) => MDRawDirectory {
341 stream_type: MDStreamType::LinuxCmdLine as u32,
342 location,
343 },
344 Err(e) => {
345 soft_errors.push(WriterError::WriteCommandLineFailed(e));
346 Default::default()
347 }
348 };
349 dir_section.write_to_file(buffer, Some(dirent))?;
350
351 let dirent = match self.write_file(buffer, &format!("/proc/{}/environ", self.blamed_thread))
352 {
353 Ok(location) => MDRawDirectory {
354 stream_type: MDStreamType::LinuxEnviron as u32,
355 location,
356 },
357 Err(e) => {
358 soft_errors.push(WriterError::WriteEnvironmentFailed(e));
359 Default::default()
360 }
361 };
362 dir_section.write_to_file(buffer, Some(dirent))?;
363
364 let dirent = match self.write_file(buffer, &format!("/proc/{}/auxv", self.blamed_thread)) {
365 Ok(location) => MDRawDirectory {
366 stream_type: MDStreamType::LinuxAuxv as u32,
367 location,
368 },
369 Err(e) => {
370 soft_errors.push(WriterError::WriteAuxvFailed(e));
371 Default::default()
372 }
373 };
374 dir_section.write_to_file(buffer, Some(dirent))?;
375
376 let dirent = match self.write_file(buffer, &format!("/proc/{}/maps", self.blamed_thread)) {
377 Ok(location) => MDRawDirectory {
378 stream_type: MDStreamType::LinuxMaps as u32,
379 location,
380 },
381 Err(e) => {
382 soft_errors.push(WriterError::WriteMapsFailed(e));
383 Default::default()
384 }
385 };
386 dir_section.write_to_file(buffer, Some(dirent))?;
387
388 let dirent = match dso_debug::write_dso_debug_stream(buffer, self.process_id, &dumper.auxv)
389 {
390 Ok(dirent) => dirent,
391 Err(e) => {
392 soft_errors.push(WriterError::WriteDSODebugStreamFailed(e));
393 Default::default()
394 }
395 };
396 dir_section.write_to_file(buffer, Some(dirent))?;
397
398 let dirent = match self.write_file(buffer, &format!("/proc/{}/limits", self.blamed_thread))
399 {
400 Ok(location) => MDRawDirectory {
401 stream_type: MDStreamType::MozLinuxLimits as u32,
402 location,
403 },
404 Err(e) => {
405 soft_errors.push(WriterError::WriteLimitsFailed(e));
406 Default::default()
407 }
408 };
409 dir_section.write_to_file(buffer, Some(dirent))?;
410
411 let dirent = thread_names_stream::write(buffer, dumper)?;
412 dir_section.write_to_file(buffer, Some(dirent))?;
413
414 let dirent = match handle_data_stream::write(self, buffer) {
415 Ok(dirent) => dirent,
416 Err(e) => {
417 soft_errors.push(WriterError::WriteHandleDataStreamFailed(e));
418 Default::default()
419 }
420 };
421 dir_section.write_to_file(buffer, Some(dirent))?;
422
423 // ========================================================================================
424 //
425 // PAST THIS BANNER, THE THREADS ARE RUNNING IN THE TARGET PROCESS AGAIN. IF YOU NEED TO
426 // ADD NEW ENTRIES THAT ACCESS THE TARGET MEMORY, DO IT BEFORE HERE!
427 //
428 // ========================================================================================
429
430 // Collect any last-minute soft errors when trying to restart threads
431 dumper.resume_threads(soft_errors.subwriter(WriterError::ResumeThreadsErrors));
432
433 // If this fails, there's really nothing we can do about that (other than ignore it).
434 let dirent = write_soft_errors(buffer, soft_errors)
435 .map(|location| MDRawDirectory {
436 stream_type: MDStreamType::MozSoftErrors as u32,
437 location,
438 })
439 .unwrap_or_default();
440 dir_section.write_to_file(buffer, Some(dirent))?;
441
442 // If you add more directory entries, don't forget to update num_writers, above.
443 Ok(())
444 }
445
446 #[allow(clippy::unused_self)]
447 fn write_file(
448 &self,
449 buffer: &mut DumpBuf,
450 filename: &str,
451 ) -> std::result::Result<MDLocationDescriptor, MemoryWriterError> {
452 let content = std::fs::read(filename)?;
453
454 let section = MemoryArrayWriter::write_bytes(buffer, &content);
455 Ok(section.location())
456 }
457 }
458
459 fn write_soft_errors(
460 buffer: &mut DumpBuf,
461 soft_errors: ErrorList<WriterError>,
462 ) -> Result<MDLocationDescriptor> {
463 let soft_errors_json_str =
464 serde_json::to_string_pretty(&soft_errors).map_err(WriterError::ConvertToJsonFailed)?;
465 let section = MemoryArrayWriter::write_bytes(buffer, soft_errors_json_str.as_bytes());
466 Ok(section.location())
467 }