summaryrefslogtreecommitdiffstats
path: root/third_party/rust/minidump-writer/tests/linux_minidump_writer.rs
blob: d9864bae13e5f90cce4d6484e6ce2fb8df99a90f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
#![cfg(any(target_os = "linux", target_os = "android"))]
#![allow(unused_imports, unused_variables)]

use minidump::*;
use minidump_common::format::{GUID, MINIDUMP_STREAM_TYPE::*};
use minidump_writer::{
    app_memory::AppMemory,
    crash_context::CrashContext,
    errors::*,
    maps_reader::{MappingEntry, MappingInfo, SystemMappingInfo},
    minidump_writer::MinidumpWriter,
    ptrace_dumper::PtraceDumper,
    thread_info::Pid,
};
use nix::{errno::Errno, sys::signal::Signal};
use procfs_core::process::MMPermissions;
use std::collections::HashSet;

use std::{
    io::{BufRead, BufReader},
    os::unix::process::ExitStatusExt,
    process::{Command, Stdio},
};

mod common;
use common::*;

#[derive(Debug, PartialEq)]
enum Context {
    With,
    Without,
}

impl Context {
    pub fn minidump_writer(&self, pid: Pid) -> MinidumpWriter {
        let mut mw = MinidumpWriter::new(pid, pid);
        #[cfg(not(target_arch = "mips"))]
        if self == &Context::With {
            let crash_context = get_crash_context(pid);
            mw.set_crash_context(crash_context);
        }
        mw
    }
}

#[cfg(not(target_arch = "mips"))]
fn get_ucontext() -> Result<crash_context::ucontext_t> {
    let mut context = std::mem::MaybeUninit::uninit();
    unsafe {
        let res = crash_context::crash_context_getcontext(context.as_mut_ptr());
        Errno::result(res)?;

        Ok(context.assume_init())
    }
}

#[cfg(not(target_arch = "mips"))]
fn get_crash_context(tid: Pid) -> CrashContext {
    let siginfo: libc::signalfd_siginfo = unsafe { std::mem::zeroed() };
    let context = get_ucontext().expect("Failed to get ucontext");
    #[cfg(not(target_arch = "arm"))]
    let float_state = unsafe { std::mem::zeroed() };
    CrashContext {
        inner: crash_context::CrashContext {
            siginfo,
            pid: std::process::id() as _,
            tid,
            context,
            #[cfg(not(target_arch = "arm"))]
            float_state,
        },
    }
}

macro_rules! contextual_tests {
    () => {};
    ( fn $name:ident ($ctx:ident : Context) $body:block $($rest:tt)* ) => {
        mod $name {
            use super::*;

            fn test($ctx: Context) $body

            #[test]
            fn run() {
                test(Context::Without)
            }

            #[cfg(not(target_arch = "mips"))]
            #[test]
            fn run_with_context() {
                test(Context::With)
            }
        }
        contextual_tests! { $($rest)* }
    }
}

contextual_tests! {
    fn test_write_dump(context: Context) {
        let num_of_threads = 3;
        let mut child = start_child_and_wait_for_threads(num_of_threads);
        let pid = child.id() as i32;

        let mut tmpfile = tempfile::Builder::new()
            .prefix("write_dump")
            .tempfile()
            .unwrap();

        let mut tmp = context.minidump_writer(pid);
        let in_memory_buffer = tmp.dump(&mut tmpfile).expect("Could not write minidump");
        child.kill().expect("Failed to kill process");

        // Reap child
        let waitres = child.wait().expect("Failed to wait for child");
        let status = waitres.signal().expect("Child did not die due to signal");
        assert_eq!(waitres.code(), None);
        assert_eq!(status, Signal::SIGKILL as i32);

        let meta = std::fs::metadata(tmpfile.path()).expect("Couldn't get metadata for tempfile");
        assert!(meta.len() > 0);

        let mem_slice = std::fs::read(tmpfile.path()).expect("Failed to minidump");
        assert_eq!(mem_slice.len(), in_memory_buffer.len());
        assert_eq!(mem_slice, in_memory_buffer);
    }

    fn test_write_and_read_dump_from_parent(context: Context) {
        let mut child = start_child_and_return(&["spawn_mmap_wait"]);
        let pid = child.id() as i32;

        let mut tmpfile = tempfile::Builder::new()
            .prefix("write_and_read_dump")
            .tempfile()
            .unwrap();

        let mut f = BufReader::new(child.stdout.as_mut().expect("Can't open stdout"));
        let mut buf = String::new();
        let _ = f
            .read_line(&mut buf)
            .expect("Couldn't read address provided by child");
        let mut output = buf.split_whitespace();
        let mmap_addr = output
            .next()
            .unwrap()
            .parse()
            .expect("unable to parse mmap_addr");
        let memory_size = output
            .next()
            .unwrap()
            .parse()
            .expect("unable to parse memory_size");
        // Add information about the mapped memory.
        let mapping = MappingInfo {
            start_address: mmap_addr,
            size: memory_size,
            offset: 0,
            permissions: MMPermissions::READ | MMPermissions::WRITE,
            name: Some("a fake mapping".into()),
            system_mapping_info: SystemMappingInfo {
                start_address: mmap_addr,
                end_address: mmap_addr + memory_size,
            },
        };

        let identifier = vec![
            0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE,
            0xFF,
        ];
        let entry = MappingEntry {
            mapping,
            identifier,
        };

        let mut tmp = context.minidump_writer(pid);

        tmp.set_user_mapping_list(vec![entry])
            .dump(&mut tmpfile)
            .expect("Could not write minidump");

        child.kill().expect("Failed to kill process");
        // Reap child
        let waitres = child.wait().expect("Failed to wait for child");
        let status = waitres.signal().expect("Child did not die due to signal");
        assert_eq!(waitres.code(), None);
        assert_eq!(status, Signal::SIGKILL as i32);

        let dump = Minidump::read_path(tmpfile.path()).expect("Failed to read minidump");
        let module_list: MinidumpModuleList = dump
            .get_stream()
            .expect("Couldn't find stream MinidumpModuleList");
        let module = module_list
            .module_at_address(mmap_addr as u64)
            .expect("Couldn't find user mapping module");
        assert_eq!(module.base_address(), mmap_addr as u64);
        assert_eq!(module.size(), memory_size as u64);
        assert_eq!(module.code_file(), "a fake mapping");
        assert_eq!(
            module.debug_identifier(),
            Some("33221100554477668899AABBCCDDEEFF0".parse().unwrap())
        );

        let _: MinidumpException = dump.get_stream().expect("Couldn't find MinidumpException");
        let _: MinidumpThreadList = dump.get_stream().expect("Couldn't find MinidumpThreadList");
        let _: MinidumpMemoryList = dump.get_stream().expect("Couldn't find MinidumpMemoryList");
        let _: MinidumpSystemInfo = dump.get_stream().expect("Couldn't find MinidumpSystemInfo");
        let _ = dump
            .get_raw_stream(LinuxCpuInfo as u32)
            .expect("Couldn't find LinuxCpuInfo");
        let _ = dump
            .get_raw_stream(LinuxProcStatus as u32)
            .expect("Couldn't find LinuxProcStatus");
        let _ = dump
            .get_raw_stream(LinuxCmdLine as u32)
            .expect("Couldn't find LinuxCmdLine");
        let _ = dump
            .get_raw_stream(LinuxEnviron as u32)
            .expect("Couldn't find LinuxEnviron");
        let _ = dump
            .get_raw_stream(LinuxAuxv as u32)
            .expect("Couldn't find LinuxAuxv");
        let _ = dump
            .get_raw_stream(LinuxMaps as u32)
            .expect("Couldn't find LinuxMaps");
        let _ = dump
            .get_raw_stream(LinuxDsoDebug as u32)
            .expect("Couldn't find LinuxDsoDebug");
        let _ = dump
            .get_raw_stream(MozLinuxLimits as u32)
            .expect("Couldn't find MozLinuxLimits");
    }

    fn test_write_with_additional_memory(context: Context) {
        let mut child = start_child_and_return(&["spawn_alloc_wait"]);
        let pid = child.id() as i32;

        let mut tmpfile = tempfile::Builder::new()
            .prefix("additional_memory")
            .tempfile()
            .unwrap();

        let mut f = BufReader::new(child.stdout.as_mut().expect("Can't open stdout"));
        let mut buf = String::new();
        let _ = f
            .read_line(&mut buf)
            .expect("Couldn't read address provided by child");
        let mut output = buf.split_whitespace();
        let memory_addr = usize::from_str_radix(output.next().unwrap().trim_start_matches("0x"), 16)
            .expect("unable to parse mmap_addr");
        let memory_size = output
            .next()
            .unwrap()
            .parse()
            .expect("unable to parse memory_size");

        let app_memory = AppMemory {
            ptr: memory_addr,
            length: memory_size,
        };

        let mut tmp = context.minidump_writer(pid);

        tmp.set_app_memory(vec![app_memory])
            .dump(&mut tmpfile)
            .expect("Could not write minidump");

        child.kill().expect("Failed to kill process");
        // Reap child
        let waitres = child.wait().expect("Failed to wait for child");
        let status = waitres.signal().expect("Child did not die due to signal");
        assert_eq!(waitres.code(), None);
        assert_eq!(status, Signal::SIGKILL as i32);

        // Read dump file and check its contents
        let dump = Minidump::read_path(tmpfile.path()).expect("Failed to read minidump");

        let section: MinidumpMemoryList = dump.get_stream().expect("Couldn't find MinidumpMemoryList");
        let region = section
            .memory_at_address(memory_addr as u64)
            .expect("Couldn't find memory region");

        assert_eq!(region.base_address, memory_addr as u64);
        assert_eq!(region.size, memory_size as u64);

        let mut values = Vec::<u8>::with_capacity(memory_size);
        for idx in 0..memory_size {
            values.push((idx % 255) as u8);
        }

        // Verify memory contents.
        assert_eq!(region.bytes, values);
    }

    fn test_skip_if_requested(context: Context) {
        let num_of_threads = 1;
        let mut child = start_child_and_wait_for_threads(num_of_threads);
        let pid = child.id() as i32;

        let mut tmpfile = tempfile::Builder::new()
            .prefix("skip_if_requested")
            .tempfile()
            .unwrap();

        let mut tmp = context.minidump_writer(pid);

        let pr_mapping_addr;
        #[cfg(target_pointer_width = "64")]
        {
            pr_mapping_addr = 0x0102030405060708;
        }
        #[cfg(target_pointer_width = "32")]
        {
            pr_mapping_addr = 0x010203040;
        };
        let res = tmp
            .skip_stacks_if_mapping_unreferenced()
            .set_principal_mapping_address(pr_mapping_addr)
            .dump(&mut tmpfile);
        child.kill().expect("Failed to kill process");

        // Reap child
        let waitres = child.wait().expect("Failed to wait for child");
        let status = waitres.signal().expect("Child did not die due to signal");
        assert_eq!(waitres.code(), None);
        assert_eq!(status, Signal::SIGKILL as i32);

        assert!(res.is_err());
    }

    fn test_sanitized_stacks(context: Context) {
        if context == Context::With {
            // FIXME the context's stack pointer very often doesn't lie in mapped memory, resulting
            // in the stack memory having 0 size (so no slice will match `defaced` in the
            // assertion).
            return;
        }
        let num_of_threads = 1;
        let mut child = start_child_and_wait_for_threads(num_of_threads);
        let pid = child.id() as i32;

        let mut tmpfile = tempfile::Builder::new()
            .prefix("sanitized_stacks")
            .tempfile()
            .unwrap();

        let mut tmp = context.minidump_writer(pid);
        tmp.sanitize_stack()
            .dump(&mut tmpfile)
            .expect("Faild to dump minidump");
        child.kill().expect("Failed to kill process");

        // Reap child
        let waitres = child.wait().expect("Failed to wait for child");
        let status = waitres.signal().expect("Child did not die due to signal");
        assert_eq!(waitres.code(), None);
        assert_eq!(status, Signal::SIGKILL as i32);

        // Read dump file and check its contents
        let dump = Minidump::read_path(tmpfile.path()).expect("Failed to read minidump");
        let dump_array = std::fs::read(tmpfile.path()).expect("Failed to read minidump as vec");
        let thread_list: MinidumpThreadList =
            dump.get_stream().expect("Couldn't find MinidumpThreadList");

        let defaced;
        #[cfg(target_pointer_width = "64")]
        {
            defaced = 0x0defaced0defacedusize.to_ne_bytes();
        }
        #[cfg(target_pointer_width = "32")]
        {
            defaced = 0x0defacedusize.to_ne_bytes()
        };

        for thread in thread_list.threads {
            let mem = thread.raw.stack.memory;
            let start = mem.rva as usize;
            let end = (mem.rva + mem.data_size) as usize;
            let slice = &dump_array.as_slice()[start..end];
            assert!(slice.windows(defaced.len()).any(|window| window == defaced));
        }
    }

    fn test_write_early_abort(context: Context) {
        let mut child = start_child_and_return(&["spawn_alloc_wait"]);
        let pid = child.id() as i32;

        let mut tmpfile = tempfile::Builder::new()
            .prefix("additional_memory")
            .tempfile()
            .unwrap();

        let mut f = BufReader::new(child.stdout.as_mut().expect("Can't open stdout"));
        let mut buf = String::new();
        let _ = f
            .read_line(&mut buf)
            .expect("Couldn't read address provided by child");
        let mut output = buf.split_whitespace();
        // We do not read the actual memory_address, but use NULL, which
        // should create an error during dumping and lead to a truncated minidump.
        let _ = usize::from_str_radix(output.next().unwrap().trim_start_matches("0x"), 16)
            .expect("unable to parse mmap_addr");
        let memory_addr = 0;
        let memory_size = output
            .next()
            .unwrap()
            .parse()
            .expect("unable to parse memory_size");

        let app_memory = AppMemory {
            ptr: memory_addr,
            length: memory_size,
        };

        let mut tmp = context.minidump_writer(pid);

        // This should fail, because during the dump an error is detected (try_from fails)
        match tmp.set_app_memory(vec![app_memory]).dump(&mut tmpfile) {
            Err(WriterError::SectionAppMemoryError(_)) => (),
            _ => panic!("Wrong kind of error returned"),
        }

        child.kill().expect("Failed to kill process");
        // Reap child
        let waitres = child.wait().expect("Failed to wait for child");
        let status = waitres.signal().expect("Child did not die due to signal");
        assert_eq!(waitres.code(), None);
        assert_eq!(status, Signal::SIGKILL as i32);

        // Read dump file and check its contents. There should be a truncated minidump available
        let dump = Minidump::read_path(tmpfile.path()).expect("Failed to read minidump");
        // Should be there
        let _: MinidumpThreadList = dump.get_stream().expect("Couldn't find MinidumpThreadList");
        let _: MinidumpModuleList = dump.get_stream().expect("Couldn't find MinidumpThreadList");

        // Should be missing:
        assert!(dump.get_stream::<MinidumpMemoryList>().is_err());
    }

    fn test_named_threads(context: Context) {
        let num_of_threads = 5;
        let mut child = start_child_and_wait_for_named_threads(num_of_threads);
        let pid = child.id() as i32;

        let mut tmpfile = tempfile::Builder::new()
            .prefix("named_threads")
            .tempfile()
            .unwrap();

        let mut tmp = context.minidump_writer(pid);
        let _ = tmp.dump(&mut tmpfile).expect("Could not write minidump");
        child.kill().expect("Failed to kill process");

        // Reap child
        let waitres = child.wait().expect("Failed to wait for child");
        let status = waitres.signal().expect("Child did not die due to signal");
        assert_eq!(waitres.code(), None);
        assert_eq!(status, Signal::SIGKILL as i32);

        // Read dump file and check its contents. There should be a truncated minidump available
        let dump = Minidump::read_path(tmpfile.path()).expect("Failed to read minidump");

        let threads: MinidumpThreadList = dump.get_stream().expect("Couldn't find MinidumpThreadList");

        let thread_names: MinidumpThreadNames = dump
            .get_stream()
            .expect("Couldn't find MinidumpThreadNames");

        let thread_ids: Vec<_> = threads.threads.iter().map(|t| t.raw.thread_id).collect();
        let names: HashSet<_> = thread_ids
            .iter()
            .map(|id| thread_names.get_name(*id).unwrap_or_default())
            .map(|cow| cow.into_owned())
            .collect();
        let mut expected = HashSet::new();
        expected.insert("test".to_string());
        for id in 1..num_of_threads {
            expected.insert(format!("thread_{}", id));
        }
        assert_eq!(expected, names);

    }

    fn test_file_descriptors(context: Context) {
        let num_of_files = 5;
        let mut child = start_child_and_wait_for_create_files(num_of_files);
        let pid = child.id() as i32;

        let mut tmpfile = tempfile::Builder::new()
            .prefix("testfiles")
            .tempfile()
            .unwrap();

        let mut tmp = context.minidump_writer(pid);
        let _ = tmp.dump(&mut tmpfile).expect("Could not write minidump");
        child.kill().expect("Failed to kill process");

        // Reap child
        let waitres = child.wait().expect("Failed to wait for child");
        let status = waitres.signal().expect("Child did not die due to signal");
        assert_eq!(waitres.code(), None);
        assert_eq!(status, Signal::SIGKILL as i32);

        // Read dump file and check its contents. There should be a truncated minidump available
        let dump = Minidump::read_path(tmpfile.path()).expect("Failed to read minidump");
        let fds: MinidumpHandleDataStream = dump.get_stream().expect("Couldn't find MinidumpHandleDataStream");
        // We check that we create num_of_files plus stdin, stdout and stderr
        for i in 0..2 {
            let descriptor = fds.handles.get(i).expect("Descriptor should be present");
            let fd = *descriptor.raw.handle().expect("Handle should be populated");
            assert_eq!(fd, i as u64);
        }

        for i in 3..num_of_files {
            let descriptor = fds.handles.get(i).expect("Descriptor should be present");
            let object_name = descriptor.object_name.as_ref().expect("The path should be populated");
            let file_name = object_name.split('/').last().expect("The filename should be present");
            assert!(file_name.starts_with("test_file"));
            assert!(file_name.ends_with(&(i - 3).to_string()));
        }
    }
}

#[test]
fn test_minidump_size_limit() {
    let num_of_threads = 40;
    let mut child = start_child_and_wait_for_threads(num_of_threads);
    let pid = child.id() as i32;

    let mut total_normal_stack_size = 0;
    let normal_file_size;
    // First, write a minidump with no size limit.
    {
        let mut tmpfile = tempfile::Builder::new()
            .prefix("write_dump_unlimited")
            .tempfile()
            .unwrap();

        MinidumpWriter::new(pid, pid)
            .dump(&mut tmpfile)
            .expect("Could not write minidump");

        let meta = std::fs::metadata(tmpfile.path()).expect("Couldn't get metadata for tempfile");
        assert!(meta.len() > 0);

        normal_file_size = meta.len();

        // Read dump file and check its contents
        let dump = Minidump::read_path(tmpfile.path()).expect("Failed to read minidump");
        let thread_list: MinidumpThreadList =
            dump.get_stream().expect("Couldn't find MinidumpThreadList");
        for thread in thread_list.threads {
            assert!(thread.raw.thread_id > 0);
            assert!(thread.raw.stack.memory.data_size > 0);
            total_normal_stack_size += thread.raw.stack.memory.data_size;
        }
    }

    // Second, write a minidump with a size limit big enough to not trigger
    // anything.
    {
        // Set size limit arbitrarily 2MiB larger than the normal file size -- such
        // that the limiting code will not kick in.
        let minidump_size_limit = normal_file_size + 2 * 1024 * 1024;

        let mut tmpfile = tempfile::Builder::new()
            .prefix("write_dump_pseudolimited")
            .tempfile()
            .unwrap();

        MinidumpWriter::new(pid, pid)
            .set_minidump_size_limit(minidump_size_limit)
            .dump(&mut tmpfile)
            .expect("Could not write minidump");

        let meta = std::fs::metadata(tmpfile.path()).expect("Couldn't get metadata for tempfile");

        // Make sure limiting wasn't actually triggered.  NOTE: If you fail this,
        // first make sure that "minidump_size_limit" above is indeed set to a
        // large enough value -- the limit-checking code in minidump_writer.rs
        // does just a rough estimate.
        // TODO: Fix this properly
        //assert_eq!(meta.len(), normal_file_size);
        let min = std::cmp::min(meta.len(), normal_file_size);
        let max = std::cmp::max(meta.len(), normal_file_size);

        // Setting a stack limit limits the size of non-main stacks even before
        // the limit is reached. This will cause slight variations in size
        // between a limited and an unlimited minidump.
        assert!(max - min < 1024, "max = {max:} min = {min:}");
    }

    // Third, write a minidump with a size limit small enough to be triggered.
    {
        // Set size limit to some arbitrary amount, such that the limiting code
        // will kick in.  The equation used to set this value was determined by
        // simply reversing the size-limit logic a little bit in order to pick a
        // size we know will trigger it.

        // Copyied from sections/thread_list_stream.rs
        const LIMIT_AVERAGE_THREAD_STACK_LENGTH: u64 = 8 * 1024;
        let mut minidump_size_limit = LIMIT_AVERAGE_THREAD_STACK_LENGTH * 40;

        // If, in reality, each of the threads' stack is *smaller* than
        // kLimitAverageThreadStackLength, the normal file size could very well be
        // smaller than the arbitrary limit that was just set.  In that case,
        // either of these numbers should trigger the size-limiting code, but we
        // might as well pick the smallest.
        if normal_file_size < minidump_size_limit {
            minidump_size_limit = normal_file_size;
        }

        let mut tmpfile = tempfile::Builder::new()
            .prefix("write_dump_limited")
            .tempfile()
            .unwrap();

        MinidumpWriter::new(pid, pid)
            .set_minidump_size_limit(minidump_size_limit)
            .dump(&mut tmpfile)
            .expect("Could not write minidump");

        let meta = std::fs::metadata(tmpfile.path()).expect("Couldn't get metadata for tempfile");
        assert!(meta.len() > 0);
        // Make sure the file size is at least smaller than the original.  If this
        // fails because it's the same size, then the size-limit logic didn't kick
        // in like it was supposed to.
        assert!(meta.len() < normal_file_size);

        let mut total_limit_stack_size = 0;
        // Read dump file and check its contents
        let dump = Minidump::read_path(tmpfile.path()).expect("Failed to read minidump");
        let thread_list: MinidumpThreadList =
            dump.get_stream().expect("Couldn't find MinidumpThreadList");
        for thread in thread_list.threads {
            assert!(thread.raw.thread_id > 0);
            assert!(thread.raw.stack.memory.data_size > 0);
            total_limit_stack_size += thread.raw.stack.memory.data_size;
        }

        // Make sure stack size shrunk by at least 1KB per extra thread.
        // Note: The 1KB is arbitrary, and assumes that the thread stacks are big
        // enough to shrink by that much.  For example, if each thread stack was
        // originally only 2KB, the current size-limit logic wouldn't actually
        // shrink them because that's the size to which it tries to shrink.  If
        // you fail this part of the test due to something like that, the test
        // logic should probably be improved to account for your situation.

        // Copyied from sections/thread_list_stream.rs
        const LIMIT_BASE_THREAD_COUNT: usize = 20;
        const MIN_PER_EXTRA_THREAD_STACK_REDUCTION: usize = 1024;
        let min_expected_reduction =
            (40 - LIMIT_BASE_THREAD_COUNT) * MIN_PER_EXTRA_THREAD_STACK_REDUCTION;
        assert!(total_limit_stack_size < total_normal_stack_size - min_expected_reduction as u32);
    }

    child.kill().expect("Failed to kill process");

    // Reap child
    let waitres = child.wait().expect("Failed to wait for child");
    let status = waitres.signal().expect("Child did not die due to signal");
    assert_eq!(waitres.code(), None);
    assert_eq!(status, Signal::SIGKILL as i32);
}

#[test]
fn test_with_deleted_binary() {
    let num_of_threads = 1;
    let binary_copy_dir = tempfile::Builder::new()
        .prefix("deleted_binary")
        .tempdir()
        .unwrap();
    let binary_copy = binary_copy_dir.as_ref().join("binary_copy");

    let path: &'static str = std::env!("CARGO_BIN_EXE_test");

    std::fs::copy(path, &binary_copy).expect("Failed to copy binary");
    let mem_slice = std::fs::read(&binary_copy).expect("Failed to read binary");

    let mut child = Command::new(&binary_copy)
        .env("RUST_BACKTRACE", "1")
        .arg("spawn_and_wait")
        .arg(format!("{}", num_of_threads))
        .stdout(Stdio::piped())
        .spawn()
        .expect("failed to execute child");
    wait_for_threads(&mut child, num_of_threads);

    let pid = child.id() as i32;

    let build_id = PtraceDumper::elf_file_identifier_from_mapped_file(&mem_slice)
        .expect("Failed to get build_id");

    let guid = GUID {
        data1: u32::from_ne_bytes(build_id[0..4].try_into().unwrap()),
        data2: u16::from_ne_bytes(build_id[4..6].try_into().unwrap()),
        data3: u16::from_ne_bytes(build_id[6..8].try_into().unwrap()),
        data4: build_id[8..16].try_into().unwrap(),
    };

    // guid_to_string() is not public in minidump, so copied it here
    // And append a zero, because module IDs include an "age" field
    // which is always zero on Linux.
    let filtered = format!(
        "{:08X}{:04X}{:04X}{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}0",
        guid.data1,
        guid.data2,
        guid.data3,
        guid.data4[0],
        guid.data4[1],
        guid.data4[2],
        guid.data4[3],
        guid.data4[4],
        guid.data4[5],
        guid.data4[6],
        guid.data4[7],
    );
    // Strip out dashes
    //let mut filtered: String = identifier.chars().filter(|x| *x != '-').collect();

    std::fs::remove_file(&binary_copy).expect("Failed to remove binary");

    let mut tmpfile = tempfile::Builder::new()
        .prefix("deleted_binary")
        .tempfile()
        .unwrap();

    MinidumpWriter::new(pid, pid)
        .dump(&mut tmpfile)
        .expect("Could not write minidump");

    child.kill().expect("Failed to kill process");

    // Reap child
    let waitres = child.wait().expect("Failed to wait for child");
    let status = waitres.signal().expect("Child did not die due to signal");
    assert_eq!(waitres.code(), None);
    assert_eq!(status, Signal::SIGKILL as i32);

    // Begin checks on dump
    let meta = std::fs::metadata(tmpfile.path()).expect("Couldn't get metadata for tempfile");
    assert!(meta.len() > 0);

    let dump = Minidump::read_path(tmpfile.path()).expect("Failed to read minidump");
    let module_list: MinidumpModuleList = dump
        .get_stream()
        .expect("Couldn't find stream MinidumpModuleList");
    let main_module = module_list
        .main_module()
        .expect("Could not get main module");
    assert_eq!(main_module.code_file(), binary_copy.to_string_lossy());
    assert_eq!(main_module.debug_identifier(), filtered.parse().ok());
}

#[test]
fn test_memory_info_list_stream() {
    let mut child = start_child_and_wait_for_threads(1);
    let pid = child.id() as i32;

    let mut tmpfile = tempfile::Builder::new()
        .prefix("memory_info_list_stream")
        .tempfile()
        .unwrap();

    // Write a minidump
    MinidumpWriter::new(pid, pid)
        .dump(&mut tmpfile)
        .expect("cound not write minidump");
    child.kill().expect("Failed to kill process");

    // Ensure the minidump has a MemoryInfoListStream present and has at least one entry.
    let dump = Minidump::read_path(tmpfile.path()).expect("failed to read minidump");
    let list: MinidumpMemoryInfoList = dump.get_stream().expect("no memory info list");
    assert!(list.iter().count() > 1);
}