Debian Codegraph @

third_party/rust/minidump-writer/tests/linux_minidump_writer.rs

raw
1 #![cfg(any(target_os = "linux", target_os = "android"))]
2 #![allow(unused_imports, unused_variables)]
3
4 use {
5 common::*,
6 minidump::*,
7 minidump_common::format::{GUID, MINIDUMP_STREAM_TYPE::*},
8 minidump_writer::{
9 app_memory::AppMemory,
10 crash_context::CrashContext,
11 errors::*,
12 maps_reader::{MappingEntry, MappingInfo, SystemMappingInfo},
13 minidump_writer::MinidumpWriter,
14 module_reader::{BuildId, ReadFromModule},
15 ptrace_dumper::PtraceDumper,
16 Pid,
17 },
18 nix::{errno::Errno, sys::signal::Signal},
19 procfs_core::process::MMPermissions,
20 serde_json::json,
21 std::{
22 collections::HashSet,
23 io::{BufRead, BufReader},
24 os::unix::process::ExitStatusExt,
25 process::{Command, Stdio},
26 },
27 };
28
29 mod common;
30
31 #[derive(Debug, PartialEq)]
32 enum Context {
33 With,
34 Without,
35 }
36
37 impl Context {
38 pub fn minidump_writer(&self, pid: Pid) -> MinidumpWriter {
39 let mut mw = MinidumpWriter::new(pid, pid);
40 #[cfg(not(target_arch = "mips"))]
41 if self == &Context::With {
42 let crash_context = get_crash_context(pid);
43 mw.set_crash_context(crash_context);
44 }
45 mw
46 }
47 }
48
49 #[cfg(not(target_arch = "mips"))]
50 fn get_ucontext() -> Result<crash_context::ucontext_t> {
51 let mut context = std::mem::MaybeUninit::uninit();
52 unsafe {
53 let res = crash_context::crash_context_getcontext(context.as_mut_ptr());
54 Errno::result(res)?;
55
56 Ok(context.assume_init())
57 }
58 }
59
60 #[cfg(not(target_arch = "mips"))]
61 fn get_crash_context(tid: Pid) -> CrashContext {
62 let siginfo: libc::signalfd_siginfo = unsafe { std::mem::zeroed() };
63 let context = get_ucontext().expect("Failed to get ucontext");
64 #[cfg(not(target_arch = "arm"))]
65 let float_state = unsafe { std::mem::zeroed() };
66 CrashContext {
67 inner: crash_context::CrashContext {
68 siginfo,
69 pid: std::process::id() as _,
70 tid,
71 context,
72 #[cfg(not(target_arch = "arm"))]
73 float_state,
74 },
75 }
76 }
77
78 macro_rules! contextual_test {
79 ( $(#[$attr:meta])? fn $name:ident ($ctx:ident : Context) $body:block ) => {
80 mod $name {
81 use super::*;
82
83 fn test($ctx: Context) $body
84
85 #[test]
86 $(#[$attr])?
87 fn without_context() {
88 test(Context::Without)
89 }
90
91 #[cfg(not(target_arch = "mips"))]
92 #[test]
93 $(#[$attr])?
94 fn with_context() {
95 test(Context::With)
96 }
97 }
98 }
99 }
100
101 contextual_test! {
102 fn write_dump(context: Context) {
103 let num_of_threads = 3;
104 let mut child = start_child_and_wait_for_threads(num_of_threads);
105 let pid = child.id() as i32;
106
107 let mut tmpfile = tempfile::Builder::new()
108 .prefix("write_dump")
109 .tempfile()
110 .unwrap();
111
112 let mut tmp = context.minidump_writer(pid);
113 let in_memory_buffer = tmp.dump(&mut tmpfile).expect("Could not write minidump");
114 child.kill().expect("Failed to kill process");
115
116 // Reap child
117 let waitres = child.wait().expect("Failed to wait for child");
118 let status = waitres.signal().expect("Child did not die due to signal");
119 assert_eq!(waitres.code(), None);
120 assert_eq!(status, Signal::SIGKILL as i32);
121
122 let meta = std::fs::metadata(tmpfile.path()).expect("Couldn't get metadata for tempfile");
123 assert!(meta.len() > 0);
124
125 let mem_slice = std::fs::read(tmpfile.path()).expect("Failed to minidump");
126 assert_eq!(mem_slice.len(), in_memory_buffer.len());
127 assert_eq!(mem_slice, in_memory_buffer);
128 }
129 }
130
131 contextual_test! {
132 #[ignore]
133 fn write_and_read_dump_from_parent(context: Context) {
134 let mut child = start_child_and_return(&["spawn_mmap_wait"]);
135 let pid = child.id() as i32;
136
137 let mut tmpfile = tempfile::Builder::new()
138 .prefix("write_and_read_dump")
139 .tempfile()
140 .unwrap();
141
142 let mut f = BufReader::new(child.stdout.as_mut().expect("Can't open stdout"));
143 let mut buf = String::new();
144 let _ = f
145 .read_line(&mut buf)
146 .expect("Couldn't read address provided by child");
147 let mut output = buf.split_whitespace();
148 let mmap_addr = output
149 .next()
150 .unwrap()
151 .parse()
152 .expect("unable to parse mmap_addr");
153 let memory_size = output
154 .next()
155 .unwrap()
156 .parse()
157 .expect("unable to parse memory_size");
158 // Add information about the mapped memory.
159 let mapping = MappingInfo {
160 start_address: mmap_addr,
161 size: memory_size,
162 offset: 0,
163 permissions: MMPermissions::READ | MMPermissions::WRITE,
164 name: Some("a fake mapping".into()),
165 system_mapping_info: SystemMappingInfo {
166 start_address: mmap_addr,
167 end_address: mmap_addr + memory_size,
168 },
169 };
170
171 let identifier = vec![
172 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE,
173 0xFF,
174 ];
175 let entry = MappingEntry {
176 mapping,
177 identifier,
178 };
179
180 let mut tmp = context.minidump_writer(pid);
181
182 tmp.set_user_mapping_list(vec![entry])
183 .dump(&mut tmpfile)
184 .expect("Could not write minidump");
185
186 child.kill().expect("Failed to kill process");
187 // Reap child
188 let waitres = child.wait().expect("Failed to wait for child");
189 let status = waitres.signal().expect("Child did not die due to signal");
190 assert_eq!(waitres.code(), None);
191 assert_eq!(status, Signal::SIGKILL as i32);
192
193 let dump = Minidump::read_path(tmpfile.path()).expect("Failed to read minidump");
194 let module_list: MinidumpModuleList = dump
195 .get_stream()
196 .expect("Couldn't find stream MinidumpModuleList");
197 let module = module_list
198 .module_at_address(mmap_addr as u64)
199 .expect("Couldn't find user mapping module");
200 assert_eq!(module.base_address(), mmap_addr as u64);
201 assert_eq!(module.size(), memory_size as u64);
202 assert_eq!(module.code_file(), "a fake mapping");
203 assert_eq!(
204 module.debug_identifier(),
205 Some("33221100554477668899AABBCCDDEEFF0".parse().unwrap())
206 );
207
208 let _: MinidumpException = dump.get_stream().expect("Couldn't find MinidumpException");
209 let _: MinidumpThreadList = dump.get_stream().expect("Couldn't find MinidumpThreadList");
210 let _: MinidumpMemoryList = dump.get_stream().expect("Couldn't find MinidumpMemoryList");
211 let _: MinidumpSystemInfo = dump.get_stream().expect("Couldn't find MinidumpSystemInfo");
212 let _ = dump
213 .get_raw_stream(LinuxCpuInfo as u32)
214 .expect("Couldn't find LinuxCpuInfo");
215 let _ = dump
216 .get_raw_stream(LinuxProcStatus as u32)
217 .expect("Couldn't find LinuxProcStatus");
218 let _ = dump
219 .get_raw_stream(LinuxCmdLine as u32)
220 .expect("Couldn't find LinuxCmdLine");
221 let _ = dump
222 .get_raw_stream(LinuxEnviron as u32)
223 .expect("Couldn't find LinuxEnviron");
224 let _ = dump
225 .get_raw_stream(LinuxAuxv as u32)
226 .expect("Couldn't find LinuxAuxv");
227 let _ = dump
228 .get_raw_stream(LinuxMaps as u32)
229 .expect("Couldn't find LinuxMaps");
230 let _ = dump
231 .get_raw_stream(LinuxDsoDebug as u32)
232 .expect("Couldn't find LinuxDsoDebug");
233 let _ = dump
234 .get_raw_stream(MozLinuxLimits as u32)
235 .expect("Couldn't find MozLinuxLimits");
236 }
237 }
238
239 contextual_test! {
240 fn write_with_additional_memory(context: Context) {
241 let mut child = start_child_and_return(&["spawn_alloc_wait"]);
242 let pid = child.id() as i32;
243
244 let mut tmpfile = tempfile::Builder::new()
245 .prefix("additional_memory")
246 .tempfile()
247 .unwrap();
248
249 let mut f = BufReader::new(child.stdout.as_mut().expect("Can't open stdout"));
250 let mut buf = String::new();
251 let _ = f
252 .read_line(&mut buf)
253 .expect("Couldn't read address provided by child");
254 let mut output = buf.split_whitespace();
255 let memory_addr = usize::from_str_radix(output.next().unwrap().trim_start_matches("0x"), 16)
256 .expect("unable to parse mmap_addr");
257 let memory_size = output
258 .next()
259 .unwrap()
260 .parse()
261 .expect("unable to parse memory_size");
262
263 let app_memory = AppMemory {
264 ptr: memory_addr,
265 length: memory_size,
266 };
267
268 let mut tmp = context.minidump_writer(pid);
269
270 tmp.set_app_memory(vec![app_memory])
271 .dump(&mut tmpfile)
272 .expect("Could not write minidump");
273
274 child.kill().expect("Failed to kill process");
275 // Reap child
276 let waitres = child.wait().expect("Failed to wait for child");
277 let status = waitres.signal().expect("Child did not die due to signal");
278 assert_eq!(waitres.code(), None);
279 assert_eq!(status, Signal::SIGKILL as i32);
280
281 // Read dump file and check its contents
282 let dump = Minidump::read_path(tmpfile.path()).expect("Failed to read minidump");
283
284 let section: MinidumpMemoryList = dump.get_stream().expect("Couldn't find MinidumpMemoryList");
285 let region = section
286 .memory_at_address(memory_addr as u64)
287 .expect("Couldn't find memory region");
288
289 assert_eq!(region.base_address, memory_addr as u64);
290 assert_eq!(region.size, memory_size as u64);
291
292 let mut values = Vec::<u8>::with_capacity(memory_size);
293 for idx in 0..memory_size {
294 values.push((idx % 255) as u8);
295 }
296
297 // Verify memory contents.
298 assert_eq!(region.bytes, values);
299 }
300 }
301
302 contextual_test! {
303 fn skip_if_requested(context: Context) {
304 let expected_errors = vec![
305 json!("PrincipalMappingNotReferenced"),
306 ];
307
308 let num_of_threads = 1;
309 let mut child = start_child_and_wait_for_threads(num_of_threads);
310 let pid = child.id() as i32;
311
312 let mut tmpfile = tempfile::Builder::new()
313 .prefix("skip_if_requested")
314 .tempfile()
315 .unwrap();
316
317 let mut tmp = context.minidump_writer(pid);
318
319 let pr_mapping_addr;
320 #[cfg(target_pointer_width = "64")]
321 {
322 pr_mapping_addr = 0x0102030405060708;
323 }
324 #[cfg(target_pointer_width = "32")]
325 {
326 pr_mapping_addr = 0x010203040;
327 };
328 let res = tmp
329 .skip_stacks_if_mapping_unreferenced()
330 .set_principal_mapping_address(pr_mapping_addr)
331 .dump(&mut tmpfile);
332 child.kill().expect("Failed to kill process");
333
334 // Reap child
335 let waitres = child.wait().expect("Failed to wait for child");
336 let status = waitres.signal().expect("Child did not die due to signal");
337 assert_eq!(waitres.code(), None);
338 assert_eq!(status, Signal::SIGKILL as i32);
339
340 // Ensure the MozSoftErrors stream contains the expected errors
341 let dump = Minidump::read_path(tmpfile.path()).expect("failed to read minidump");
342 assert_soft_errors_in_minidump(&dump, &expected_errors);
343 }
344 }
345
346 contextual_test! {
347 fn sanitized_stacks(context: Context) {
348 if context == Context::With {
349 // FIXME the context's stack pointer very often doesn't lie in mapped memory, resulting
350 // in the stack memory having 0 size (so no slice will match `defaced` in the
351 // assertion).
352 return;
353 }
354 let num_of_threads = 1;
355 let mut child = start_child_and_wait_for_threads(num_of_threads);
356 let pid = child.id() as i32;
357
358 let mut tmpfile = tempfile::Builder::new()
359 .prefix("sanitized_stacks")
360 .tempfile()
361 .unwrap();
362
363 let mut tmp = context.minidump_writer(pid);
364 tmp.sanitize_stack()
365 .dump(&mut tmpfile)
366 .expect("Faild to dump minidump");
367 child.kill().expect("Failed to kill process");
368
369 // Reap child
370 let waitres = child.wait().expect("Failed to wait for child");
371 let status = waitres.signal().expect("Child did not die due to signal");
372 assert_eq!(waitres.code(), None);
373 assert_eq!(status, Signal::SIGKILL as i32);
374
375 // Read dump file and check its contents
376 let dump = Minidump::read_path(tmpfile.path()).expect("Failed to read minidump");
377 let dump_array = std::fs::read(tmpfile.path()).expect("Failed to read minidump as vec");
378 let thread_list: MinidumpThreadList =
379 dump.get_stream().expect("Couldn't find MinidumpThreadList");
380
381 let defaced;
382 #[cfg(target_pointer_width = "64")]
383 {
384 defaced = 0x0defaced0defacedusize.to_ne_bytes();
385 }
386 #[cfg(target_pointer_width = "32")]
387 {
388 defaced = 0x0defacedusize.to_ne_bytes()
389 };
390
391 for thread in thread_list.threads {
392 let mem = thread.raw.stack.memory;
393 let start = mem.rva as usize;
394 let end = (mem.rva + mem.data_size) as usize;
395 let slice = &dump_array.as_slice()[start..end];
396 assert!(slice.windows(defaced.len()).any(|window| window == defaced));
397 }
398 }
399 }
400
401 contextual_test! {
402 fn write_early_abort(context: Context) {
403 let mut child = start_child_and_return(&["spawn_alloc_wait"]);
404 let pid = child.id() as i32;
405
406 let mut tmpfile = tempfile::Builder::new()
407 .prefix("additional_memory")
408 .tempfile()
409 .unwrap();
410
411 let mut f = BufReader::new(child.stdout.as_mut().expect("Can't open stdout"));
412 let mut buf = String::new();
413 let _ = f
414 .read_line(&mut buf)
415 .expect("Couldn't read address provided by child");
416 let mut output = buf.split_whitespace();
417 // We do not read the actual memory_address, but use NULL, which
418 // should create an error during dumping and lead to a truncated minidump.
419 let _ = usize::from_str_radix(output.next().unwrap().trim_start_matches("0x"), 16)
420 .expect("unable to parse mmap_addr");
421 let memory_addr = 0;
422 let memory_size = output
423 .next()
424 .unwrap()
425 .parse()
426 .expect("unable to parse memory_size");
427
428 let app_memory = AppMemory {
429 ptr: memory_addr,
430 length: memory_size,
431 };
432
433 let mut tmp = context.minidump_writer(pid);
434
435 // This should fail, because during the dump an error is detected (try_from fails)
436 match tmp.set_app_memory(vec![app_memory]).dump(&mut tmpfile) {
437 Err(WriterError::SectionAppMemoryError(_)) => (),
438 _ => panic!("Wrong kind of error returned"),
439 }
440
441 child.kill().expect("Failed to kill process");
442 // Reap child
443 let waitres = child.wait().expect("Failed to wait for child");
444 let status = waitres.signal().expect("Child did not die due to signal");
445 assert_eq!(waitres.code(), None);
446 assert_eq!(status, Signal::SIGKILL as i32);
447
448 // Read dump file and check its contents. There should be a truncated minidump available
449 let dump = Minidump::read_path(tmpfile.path()).expect("Failed to read minidump");
450 // Should be there
451 let _: MinidumpThreadList = dump.get_stream().expect("Couldn't find MinidumpThreadList");
452 let _: MinidumpModuleList = dump.get_stream().expect("Couldn't find MinidumpThreadList");
453
454 // Should be missing:
455 assert!(dump.get_stream::<MinidumpMemoryList>().is_err());
456 }
457 }
458
459 contextual_test! {
460 fn named_threads(context: Context) {
461 let num_of_threads = 5;
462 let mut child = start_child_and_wait_for_named_threads(num_of_threads);
463 let pid = child.id() as i32;
464
465 let mut tmpfile = tempfile::Builder::new()
466 .prefix("named_threads")
467 .tempfile()
468 .unwrap();
469
470 let mut tmp = context.minidump_writer(pid);
471 let _ = tmp.dump(&mut tmpfile).expect("Could not write minidump");
472 child.kill().expect("Failed to kill process");
473
474 // Reap child
475 let waitres = child.wait().expect("Failed to wait for child");
476 let status = waitres.signal().expect("Child did not die due to signal");
477 assert_eq!(waitres.code(), None);
478 assert_eq!(status, Signal::SIGKILL as i32);
479
480 // Read dump file and check its contents. There should be a truncated minidump available
481 let dump = Minidump::read_path(tmpfile.path()).expect("Failed to read minidump");
482
483 let threads: MinidumpThreadList = dump.get_stream().expect("Couldn't find MinidumpThreadList");
484
485 let thread_names: MinidumpThreadNames = dump
486 .get_stream()
487 .expect("Couldn't find MinidumpThreadNames");
488
489 let thread_ids: Vec<_> = threads.threads.iter().map(|t| t.raw.thread_id).collect();
490 let names: HashSet<_> = thread_ids
491 .iter()
492 .map(|id| thread_names.get_name(*id).unwrap_or_default())
493 .map(|cow| cow.into_owned())
494 .collect();
495 let mut expected = HashSet::new();
496 expected.insert("test".to_string());
497 for id in 1..num_of_threads {
498 expected.insert(format!("thread_{}", id));
499 }
500 assert_eq!(expected, names);
501 }
502 }
503
504 contextual_test! {
505 fn file_descriptors(context: Context) {
506 let num_of_files = 5;
507 let mut child = start_child_and_wait_for_create_files(num_of_files);
508 let pid = child.id() as i32;
509
510 let mut tmpfile = tempfile::Builder::new()
511 .prefix("testfiles")
512 .tempfile()
513 .unwrap();
514
515 let mut tmp = context.minidump_writer(pid);
516 let _ = tmp.dump(&mut tmpfile).expect("Could not write minidump");
517 child.kill().expect("Failed to kill process");
518
519 // Reap child
520 let waitres = child.wait().expect("Failed to wait for child");
521 let status = waitres.signal().expect("Child did not die due to signal");
522 assert_eq!(waitres.code(), None);
523 assert_eq!(status, Signal::SIGKILL as i32);
524
525 // Read dump file and check its contents. There should be a truncated minidump available
526 let dump = Minidump::read_path(tmpfile.path()).expect("Failed to read minidump");
527 let fds: MinidumpHandleDataStream = dump.get_stream().expect("Couldn't find MinidumpHandleDataStream");
528 // We check that we create num_of_files plus stdin, stdout and stderr
529 for i in 0..3 {
530 let descriptor = fds.handles.get(i).expect("Descriptor should be present");
531 let fd = *descriptor.raw.handle().expect("Handle should be populated");
532 assert_eq!(fd, i as u64);
533 }
534
535 let non_std_files = &fds.handles[3..];
536
537 // We need to handle the android case where additional pipes might be opened and
538 // interspersed with the test_files (emulator? adb?) so that CI doesn't sporadically fail
539 for i in 0..num_of_files {
540 if !non_std_files.iter().any(|descriptor| {
541 let Some(name) = &descriptor.object_name else { return false; };
542 let Some(file_name) = name.rsplit_once('/').map(|(_, fname)| fname) else { return false; };
543 if !file_name.starts_with("test_file") {
544 return false;
545 }
546
547 file_name.ends_with(&i.to_string())
548 }) {
549 panic!("unable to locate expected file `test_file{i}` in file handle stream");
550 }
551 }
552 }
553 }
554
555 #[test]
556 fn minidump_size_limit() {
557 let num_of_threads = 40;
558 let mut child = start_child_and_wait_for_threads(num_of_threads);
559 let pid = child.id() as i32;
560
561 let mut total_normal_stack_size = 0;
562 let normal_file_size;
563 // First, write a minidump with no size limit.
564 {
565 let mut tmpfile = tempfile::Builder::new()
566 .prefix("write_dump_unlimited")
567 .tempfile()
568 .unwrap();
569
570 MinidumpWriter::new(pid, pid)
571 .dump(&mut tmpfile)
572 .expect("Could not write minidump");
573
574 let meta = std::fs::metadata(tmpfile.path()).expect("Couldn't get metadata for tempfile");
575 assert!(meta.len() > 0);
576
577 normal_file_size = meta.len();
578
579 // Read dump file and check its contents
580 let dump = Minidump::read_path(tmpfile.path()).expect("Failed to read minidump");
581 let thread_list: MinidumpThreadList =
582 dump.get_stream().expect("Couldn't find MinidumpThreadList");
583 for thread in thread_list.threads {
584 assert!(thread.raw.thread_id > 0);
585 assert!(thread.raw.stack.memory.data_size > 0);
586 total_normal_stack_size += thread.raw.stack.memory.data_size;
587 }
588 }
589
590 // Second, write a minidump with a size limit big enough to not trigger
591 // anything.
592 {
593 // Set size limit arbitrarily 2MiB larger than the normal file size -- such
594 // that the limiting code will not kick in.
595 let minidump_size_limit = normal_file_size + 2 * 1024 * 1024;
596
597 let mut tmpfile = tempfile::Builder::new()
598 .prefix("write_dump_pseudolimited")
599 .tempfile()
600 .unwrap();
601
602 MinidumpWriter::new(pid, pid)
603 .set_minidump_size_limit(minidump_size_limit)
604 .dump(&mut tmpfile)
605 .expect("Could not write minidump");
606
607 let meta = std::fs::metadata(tmpfile.path()).expect("Couldn't get metadata for tempfile");
608
609 // Make sure limiting wasn't actually triggered. NOTE: If you fail this,
610 // first make sure that "minidump_size_limit" above is indeed set to a
611 // large enough value -- the limit-checking code in minidump_writer.rs
612 // does just a rough estimate.
613 // TODO: Fix this properly
614 //assert_eq!(meta.len(), normal_file_size);
615 let min = std::cmp::min(meta.len(), normal_file_size);
616 let max = std::cmp::max(meta.len(), normal_file_size);
617
618 // Setting a stack limit limits the size of non-main stacks even before
619 // the limit is reached. This will cause slight variations in size
620 // between a limited and an unlimited minidump.
621 assert!(max - min < 1024, "max = {max:} min = {min:}");
622 }
623
624 // Third, write a minidump with a size limit small enough to be triggered.
625 {
626 // Set size limit to some arbitrary amount, such that the limiting code
627 // will kick in. The equation used to set this value was determined by
628 // simply reversing the size-limit logic a little bit in order to pick a
629 // size we know will trigger it.
630
631 // Copyied from sections/thread_list_stream.rs
632 const LIMIT_AVERAGE_THREAD_STACK_LENGTH: u64 = 8 * 1024;
633 let mut minidump_size_limit = LIMIT_AVERAGE_THREAD_STACK_LENGTH * 40;
634
635 // If, in reality, each of the threads' stack is *smaller* than
636 // kLimitAverageThreadStackLength, the normal file size could very well be
637 // smaller than the arbitrary limit that was just set. In that case,
638 // either of these numbers should trigger the size-limiting code, but we
639 // might as well pick the smallest.
640 if normal_file_size < minidump_size_limit {
641 minidump_size_limit = normal_file_size;
642 }
643
644 let mut tmpfile = tempfile::Builder::new()
645 .prefix("write_dump_limited")
646 .tempfile()
647 .unwrap();
648
649 MinidumpWriter::new(pid, pid)
650 .set_minidump_size_limit(minidump_size_limit)
651 .dump(&mut tmpfile)
652 .expect("Could not write minidump");
653
654 let meta = std::fs::metadata(tmpfile.path()).expect("Couldn't get metadata for tempfile");
655 assert!(meta.len() > 0);
656 // Make sure the file size is at least smaller than the original. If this
657 // fails because it's the same size, then the size-limit logic didn't kick
658 // in like it was supposed to.
659 assert!(meta.len() < normal_file_size);
660
661 let mut total_limit_stack_size = 0;
662 // Read dump file and check its contents
663 let dump = Minidump::read_path(tmpfile.path()).expect("Failed to read minidump");
664 let thread_list: MinidumpThreadList =
665 dump.get_stream().expect("Couldn't find MinidumpThreadList");
666 for thread in thread_list.threads {
667 assert!(thread.raw.thread_id > 0);
668 assert!(thread.raw.stack.memory.data_size > 0);
669 total_limit_stack_size += thread.raw.stack.memory.data_size;
670 }
671
672 // Make sure stack size shrunk by at least 1KB per extra thread.
673 // Note: The 1KB is arbitrary, and assumes that the thread stacks are big
674 // enough to shrink by that much. For example, if each thread stack was
675 // originally only 2KB, the current size-limit logic wouldn't actually
676 // shrink them because that's the size to which it tries to shrink. If
677 // you fail this part of the test due to something like that, the test
678 // logic should probably be improved to account for your situation.
679
680 // Copyied from sections/thread_list_stream.rs
681 const LIMIT_BASE_THREAD_COUNT: usize = 20;
682 const MIN_PER_EXTRA_THREAD_STACK_REDUCTION: usize = 1024;
683 let min_expected_reduction =
684 (40 - LIMIT_BASE_THREAD_COUNT) * MIN_PER_EXTRA_THREAD_STACK_REDUCTION;
685 assert!(total_limit_stack_size < total_normal_stack_size - min_expected_reduction as u32);
686 }
687
688 child.kill().expect("Failed to kill process");
689
690 // Reap child
691 let waitres = child.wait().expect("Failed to wait for child");
692 let status = waitres.signal().expect("Child did not die due to signal");
693 assert_eq!(waitres.code(), None);
694 assert_eq!(status, Signal::SIGKILL as i32);
695 }
696
697 #[test]
698 fn with_deleted_binary() {
699 let num_of_threads = 1;
700 let binary_copy_dir = tempfile::Builder::new()
701 .prefix("deleted_binary")
702 .tempdir()
703 .unwrap();
704 let binary_copy = binary_copy_dir.as_ref().join("binary_copy");
705
706 let path: String = if let Ok(p) = std::env::var("TEST_HELPER") {
707 p
708 } else {
709 std::env!("CARGO_BIN_EXE_test").into()
710 };
711
712 std::fs::copy(path, &binary_copy).expect("Failed to copy binary");
713 let mem_slice = std::fs::read(&binary_copy).expect("Failed to read binary");
714
715 let mut child = Command::new(&binary_copy)
716 .env("RUST_BACKTRACE", "1")
717 .arg("spawn_and_wait")
718 .arg(num_of_threads.to_string())
719 .stdout(Stdio::piped())
720 .spawn()
721 .expect("failed to execute child");
722 wait_for_threads(&mut child, num_of_threads);
723
724 let pid = child.id() as i32;
725
726 let BuildId(mut build_id) =
727 BuildId::read_from_module(mem_slice.as_slice().into()).expect("Failed to get build_id");
728
729 std::fs::remove_file(&binary_copy).expect("Failed to remove binary");
730
731 let mut tmpfile = tempfile::Builder::new()
732 .prefix("deleted_binary")
733 .tempfile()
734 .unwrap();
735
736 MinidumpWriter::new(pid, pid)
737 .dump(&mut tmpfile)
738 .expect("Could not write minidump");
739
740 child.kill().expect("Failed to kill process");
741
742 // Reap child
743 let waitres = child.wait().expect("Failed to wait for child");
744 let status = waitres.signal().expect("Child did not die due to signal");
745 assert_eq!(waitres.code(), None);
746 assert_eq!(status, Signal::SIGKILL as i32);
747
748 // Begin checks on dump
749 let meta = std::fs::metadata(tmpfile.path()).expect("Couldn't get metadata for tempfile");
750 assert!(meta.len() > 0);
751
752 let dump = Minidump::read_path(tmpfile.path()).expect("Failed to read minidump");
753 let module_list: MinidumpModuleList = dump
754 .get_stream()
755 .expect("Couldn't find stream MinidumpModuleList");
756 let main_module = module_list
757 .main_module()
758 .expect("Could not get main module");
759 //assert_eq!(main_module.code_file(), binary_copy.to_string_lossy());
760
761 let did = main_module
762 .debug_identifier()
763 .expect("expected value debug id");
764 {
765 let uuid = did.uuid();
766 let uuid = uuid.as_bytes();
767
768 // Swap bytes in the original to match the expected uuid
769 if cfg!(target_endian = "little") {
770 build_id[..4].reverse();
771 build_id[4..6].reverse();
772 build_id[6..8].reverse();
773 }
774
775 // The build_id from the binary can be as little as 8 bytes, eg LLD uses
776 // xxhash to calculate the build_id by default from 10+
777 build_id.resize(16, 0);
778
779 assert_eq!(uuid.as_slice(), &build_id);
780 }
781
782 // The 'age'/appendix, always 0 on non-windows targets
783 assert_eq!(did.appendix(), 0);
784 }
785
786 #[test]
787 fn memory_info_list_stream() {
788 let mut child = start_child_and_wait_for_threads(1);
789 let pid = child.id() as i32;
790
791 let mut tmpfile = tempfile::Builder::new()
792 .prefix("memory_info_list_stream")
793 .tempfile()
794 .unwrap();
795
796 // Write a minidump
797 MinidumpWriter::new(pid, pid)
798 .dump(&mut tmpfile)
799 .expect("cound not write minidump");
800 child.kill().expect("Failed to kill process");
801 child.wait().expect("Failed to wait on killed process");
802
803 // Ensure the minidump has a MemoryInfoListStream present and has at least one entry.
804 let dump = Minidump::read_path(tmpfile.path()).expect("failed to read minidump");
805 let list: MinidumpMemoryInfoList = dump.get_stream().expect("no memory info list");
806 assert!(list.iter().count() > 1);
807 }