Debian Codegraph @

third_party/rust/minidump-writer/src/bin/test.rs

raw
1 // This binary shouldn't be under /src, but under /tests, but that is
2 // currently not possible (https://github.com/rust-lang/cargo/issues/4356)
3
4 type Error = Box<dyn std::error::Error + std::marker::Send + std::marker::Sync>;
5 pub type Result<T> = std::result::Result<T, Error>;
6
7 #[cfg(any(target_os = "linux", target_os = "android"))]
8 mod linux {
9 use {
10 super::*,
11 error_graph::ErrorList,
12 minidump_writer::{
13 minidump_writer::STOP_TIMEOUT, module_reader, ptrace_dumper::PtraceDumper,
14 LINUX_GATE_LIBRARY_NAME,
15 },
16 nix::{
17 sys::mman::{mmap_anonymous, MapFlags, ProtFlags},
18 unistd::getppid,
19 },
20 };
21
22 macro_rules! test {
23 ($x:expr, $errmsg:expr) => {
24 if !$x {
25 return Err($errmsg.into());
26 }
27 };
28 }
29
30 macro_rules! fail_on_soft_error(($n: ident, $e: expr) => {{
31 let mut $n = ErrorList::default();
32 let __result = $e;
33 if !$n.is_empty() {
34 return Err($n.into());
35 }
36 __result
37 }});
38
39 fn test_setup() -> Result<()> {
40 let ppid = getppid();
41 fail_on_soft_error!(
42 soft_errors,
43 PtraceDumper::new_report_soft_errors(
44 ppid.as_raw(),
45 STOP_TIMEOUT,
46 Default::default(),
47 &mut soft_errors,
48 )?
49 );
50 Ok(())
51 }
52
53 fn test_thread_list() -> Result<()> {
54 let ppid = getppid();
55 let dumper = fail_on_soft_error!(
56 soft_errors,
57 PtraceDumper::new_report_soft_errors(
58 ppid.as_raw(),
59 STOP_TIMEOUT,
60 Default::default(),
61 &mut soft_errors,
62 )?
63 );
64 test!(!dumper.threads.is_empty(), "No threads");
65 test!(
66 dumper
67 .threads
68 .iter()
69 .filter(|x| x.tid == ppid.as_raw())
70 .count()
71 == 1,
72 "Thread found multiple times"
73 );
74
75 test!(
76 dumper
77 .threads
78 .iter()
79 .any(|thread| thread.name.as_deref() == Some("sighup-thread")),
80 "Failed to locate and/or stop sighup-thread"
81 );
82
83 Ok(())
84 }
85
86 fn test_copy_from_process(stack_var: usize, heap_var: usize) -> Result<()> {
87 use minidump_writer::mem_reader::MemReader;
88
89 let ppid = getppid().as_raw();
90 let mut dumper = fail_on_soft_error!(
91 soft_errors,
92 PtraceDumper::new_report_soft_errors(
93 ppid,
94 STOP_TIMEOUT,
95 Default::default(),
96 &mut soft_errors
97 )?
98 );
99
100 fail_on_soft_error!(soft_errors, dumper.suspend_threads(&mut soft_errors));
101
102 // We support 3 different methods of reading memory from another
103 // process, ensure they all function and give the same results
104
105 let expected_stack = 0x11223344usize.to_ne_bytes();
106 let expected_heap = 0x55667788usize.to_ne_bytes();
107
108 let validate = |reader: &mut MemReader| -> Result<()> {
109 let mut val = [0u8; std::mem::size_of::<usize>()];
110 let read = reader.read(stack_var, &mut val)?;
111 assert_eq!(read, val.len());
112 test!(val == expected_stack, "stack var not correct");
113
114 let read = reader.read(heap_var, &mut val)?;
115 assert_eq!(read, val.len());
116 test!(val == expected_heap, "heap var not correct");
117
118 Ok(())
119 };
120
121 // virtual mem
122 {
123 let mut mr = MemReader::for_virtual_mem(ppid);
124 validate(&mut mr)
125 .map_err(|err| format!("failed to validate memory for {mr:?}: {err}"))?;
126 }
127
128 // file
129 {
130 let mut mr = MemReader::for_file(ppid)
131 .map_err(|err| format!("failed to open `/proc/{ppid}/mem`: {err}"))?;
132 validate(&mut mr)
133 .map_err(|err| format!("failed to validate memory for {mr:?}: {err}"))?;
134 }
135
136 // ptrace
137 {
138 let mut mr = MemReader::for_ptrace(ppid);
139 validate(&mut mr)
140 .map_err(|err| format!("failed to validate memory for {mr:?}: {err}"))?;
141 }
142
143 let stack_res =
144 PtraceDumper::copy_from_process(ppid, stack_var, std::mem::size_of::<usize>())?;
145
146 test!(stack_res == expected_stack, "stack var not correct");
147
148 let heap_res =
149 PtraceDumper::copy_from_process(ppid, heap_var, std::mem::size_of::<usize>())?;
150
151 test!(heap_res == expected_heap, "heap var not correct");
152
153 fail_on_soft_error!(soft_errors, dumper.resume_threads(&mut soft_errors));
154
155 Ok(())
156 }
157
158 fn test_find_mappings(addr1: usize, addr2: usize) -> Result<()> {
159 let ppid = getppid();
160 let dumper = fail_on_soft_error!(
161 soft_errors,
162 PtraceDumper::new_report_soft_errors(
163 ppid.as_raw(),
164 STOP_TIMEOUT,
165 Default::default(),
166 &mut soft_errors,
167 )?
168 );
169 dumper
170 .find_mapping(addr1)
171 .ok_or("No mapping for addr1 found")?;
172
173 dumper
174 .find_mapping(addr2)
175 .ok_or("No mapping for addr2 found")?;
176
177 test!(dumper.find_mapping(0).is_none(), "NULL found");
178 Ok(())
179 }
180
181 fn test_file_id() -> Result<()> {
182 let ppid = getppid().as_raw();
183 let exe_link = format!("/proc/{ppid}/exe");
184 let exe_name = std::fs::read_link(exe_link)?.into_os_string();
185
186 let mut dumper = fail_on_soft_error!(
187 soft_errors,
188 PtraceDumper::new_report_soft_errors(
189 ppid,
190 STOP_TIMEOUT,
191 Default::default(),
192 &mut soft_errors
193 )?
194 );
195
196 fail_on_soft_error!(soft_errors, dumper.suspend_threads(&mut soft_errors));
197
198 let mut found_exe = None;
199 for (idx, mapping) in dumper.mappings.iter().enumerate() {
200 if mapping.name.as_ref().map(|x| x.into()).as_ref() == Some(&exe_name) {
201 found_exe = Some(idx);
202 break;
203 }
204 }
205 let idx = found_exe.unwrap();
206 let module_reader::BuildId(id) = dumper.from_process_memory_for_index(idx)?;
207
208 fail_on_soft_error!(soft_errors, dumper.resume_threads(&mut soft_errors));
209
210 assert!(!id.is_empty());
211 assert!(id.iter().any(|&x| x > 0));
212 Ok(())
213 }
214
215 fn test_merged_mappings(path: String, mapped_mem: usize, mem_size: usize) -> Result<()> {
216 // Now check that PtraceDumper interpreted the mappings properly.
217 let dumper = fail_on_soft_error!(
218 soft_errors,
219 PtraceDumper::new_report_soft_errors(
220 getppid().as_raw(),
221 STOP_TIMEOUT,
222 Default::default(),
223 &mut soft_errors,
224 )?
225 );
226 let mut mapping_count = 0;
227 for map in &dumper.mappings {
228 if map
229 .name
230 .as_ref()
231 .is_some_and(|name| name.to_string_lossy().starts_with(&path))
232 {
233 mapping_count += 1;
234 // This mapping should encompass the entire original mapped
235 // range.
236 assert_eq!(map.start_address, mapped_mem);
237 assert_eq!(map.size, mem_size);
238 assert_eq!(0, map.offset);
239 }
240 }
241 assert_eq!(1, mapping_count);
242 Ok(())
243 }
244
245 fn test_linux_gate_mapping_id() -> Result<()> {
246 let ppid = getppid().as_raw();
247 let mut dumper = fail_on_soft_error!(
248 soft_errors,
249 PtraceDumper::new_report_soft_errors(
250 ppid,
251 STOP_TIMEOUT,
252 Default::default(),
253 &mut soft_errors
254 )?
255 );
256 let mut found_linux_gate = false;
257 for mapping in dumper.mappings.clone() {
258 if mapping.name == Some(LINUX_GATE_LIBRARY_NAME.into()) {
259 found_linux_gate = true;
260
261 fail_on_soft_error!(soft_errors, dumper.suspend_threads(&mut soft_errors));
262
263 let module_reader::BuildId(id) =
264 PtraceDumper::from_process_memory_for_mapping(&mapping, ppid)?;
265 test!(!id.is_empty(), "id-vec is empty");
266 test!(id.iter().any(|&x| x > 0), "all id elements are 0");
267
268 fail_on_soft_error!(soft_errors, dumper.resume_threads(&mut soft_errors));
269
270 break;
271 }
272 }
273 test!(found_linux_gate, "found no linux_gate");
274 Ok(())
275 }
276
277 fn test_mappings_include_linux_gate() -> Result<()> {
278 let ppid = getppid().as_raw();
279 let dumper = fail_on_soft_error!(
280 soft_errors,
281 PtraceDumper::new_report_soft_errors(
282 ppid,
283 STOP_TIMEOUT,
284 Default::default(),
285 &mut soft_errors
286 )?
287 );
288 let linux_gate_loc = dumper.auxv.get_linux_gate_address().unwrap();
289 test!(linux_gate_loc != 0, "linux_gate_loc == 0");
290 let mut found_linux_gate = false;
291 for mapping in &dumper.mappings {
292 if mapping.name == Some(LINUX_GATE_LIBRARY_NAME.into()) {
293 found_linux_gate = true;
294 test!(
295 usize::try_from(linux_gate_loc)? == mapping.start_address,
296 "linux_gate_loc != start_address"
297 );
298
299 // This doesn't work here, as we do not test via "fork()", so the addresses are different
300 // let ll = mapping.start_address as *const u8;
301 // for idx in 0..header::SELFMAG {
302 // let mag = unsafe { std::ptr::read(ll.offset(idx as isize)) == header::ELFMAG[idx] };
303 // test!(
304 // mag,
305 // format!("ll: {} != ELFMAG: {} at {}", mag, header::ELFMAG[idx], idx)
306 // )?;
307 // }
308 break;
309 }
310 }
311 test!(found_linux_gate, "found no linux_gate");
312 Ok(())
313 }
314
315 fn spawn_and_wait(num: usize) -> Result<()> {
316 // One less than the requested amount, as the main thread counts as well
317 for _ in 1..num {
318 std::thread::spawn(|| {
319 println!("1");
320 loop {
321 std::thread::park();
322 }
323 });
324 }
325 println!("1");
326 loop {
327 std::thread::park();
328 }
329 }
330
331 fn spawn_name_wait(num: usize) -> Result<()> {
332 // One less than the requested amount, as the main thread counts as well
333 for id in 1..num {
334 std::thread::Builder::new()
335 .name(format!("thread_{}", id))
336 .spawn(|| {
337 println!("1");
338 loop {
339 std::thread::park();
340 }
341 })?;
342 }
343 println!("1");
344 loop {
345 std::thread::park();
346 }
347 }
348
349 fn spawn_mmap_wait() -> Result<()> {
350 let page_size = nix::unistd::sysconf(nix::unistd::SysconfVar::PAGE_SIZE).unwrap();
351 let memory_size = std::num::NonZeroUsize::new(page_size.unwrap() as usize).unwrap();
352 // Get some memory to be mapped by the child-process
353 let mapped_mem = unsafe {
354 mmap_anonymous(
355 None,
356 memory_size,
357 ProtFlags::PROT_READ | ProtFlags::PROT_WRITE,
358 MapFlags::MAP_PRIVATE | MapFlags::MAP_ANON,
359 )
360 .unwrap()
361 };
362
363 println!("{} {}", mapped_mem.as_ptr() as usize, memory_size);
364 loop {
365 std::thread::park();
366 }
367 }
368
369 fn spawn_alloc_wait() -> Result<()> {
370 let page_size = nix::unistd::sysconf(nix::unistd::SysconfVar::PAGE_SIZE).unwrap();
371 let memory_size = page_size.unwrap() as usize;
372
373 let mut values = Vec::<u8>::with_capacity(memory_size);
374 for idx in 0..memory_size {
375 values.push((idx % 255) as u8);
376 }
377
378 println!("{:p} {}", values.as_ptr(), memory_size);
379 loop {
380 std::thread::park();
381 }
382 }
383
384 fn create_files_wait(num: usize) -> Result<()> {
385 let mut file_array = Vec::<tempfile::NamedTempFile>::with_capacity(num);
386 for id in 0..num {
387 let file = tempfile::Builder::new()
388 .prefix("test_file")
389 .suffix::<str>(id.to_string().as_ref())
390 .tempfile()
391 .unwrap();
392 file_array.push(file);
393 println!("1");
394 }
395 println!("1");
396 loop {
397 std::thread::park();
398 // This shouldn't be executed, but we put it here to ensure that
399 // all the files within the array are kept open.
400 println!("{}", file_array.len());
401 }
402 }
403
404 pub(super) fn real_main(args: Vec<String>) -> Result<()> {
405 match args.len() {
406 1 => match args[0].as_ref() {
407 "nop" => Ok(()),
408 "file_id" => test_file_id(),
409 "setup" => test_setup(),
410 "thread_list" => test_thread_list(),
411 "mappings_include_linux_gate" => test_mappings_include_linux_gate(),
412 "linux_gate_mapping_id" => test_linux_gate_mapping_id(),
413 "spawn_mmap_wait" => spawn_mmap_wait(),
414 "spawn_alloc_wait" => spawn_alloc_wait(),
415 _ => Err("Len 1: Unknown test option".into()),
416 },
417 2 => match args[0].as_ref() {
418 "spawn_and_wait" => {
419 let num_of_threads: usize = args[1].parse().unwrap();
420 spawn_and_wait(num_of_threads)
421 }
422 "spawn_name_wait" => {
423 let num_of_threads: usize = args[1].parse().unwrap();
424 spawn_name_wait(num_of_threads)
425 }
426 "create_files_wait" => {
427 let num_of_files: usize = args[1].parse().unwrap();
428 create_files_wait(num_of_files)
429 }
430 _ => Err(format!("Len 2: Unknown test option: {}", args[0]).into()),
431 },
432 3 => {
433 if args[0] == "find_mappings" {
434 let addr1: usize = args[1].parse().unwrap();
435 let addr2: usize = args[2].parse().unwrap();
436 test_find_mappings(addr1, addr2)
437 } else if args[0] == "copy_from_process" {
438 let stack_var: usize = args[1].parse().unwrap();
439 let heap_var: usize = args[2].parse().unwrap();
440 test_copy_from_process(stack_var, heap_var)
441 } else {
442 Err(format!("Len 3: Unknown test option: {}", args[0]).into())
443 }
444 }
445 4 => {
446 if args[0] == "merged_mappings" {
447 let path = &args[1];
448 let mapped_mem: usize = args[2].parse().unwrap();
449 let mem_size: usize = args[3].parse().unwrap();
450 test_merged_mappings(path.to_string(), mapped_mem, mem_size)
451 } else {
452 Err(format!("Len 4: Unknown test option: {}", args[0]).into())
453 }
454 }
455 _ => Err("Unknown test option".into()),
456 }
457 }
458 }
459
460 #[cfg(target_os = "windows")]
461 mod windows {
462 use super::*;
463 use std::mem;
464
465 #[link(name = "kernel32")]
466 extern "system" {
467 pub fn GetCurrentProcessId() -> u32;
468 pub fn GetCurrentThreadId() -> u32;
469 pub fn GetCurrentThread() -> isize;
470 pub fn GetThreadContext(thread: isize, context: *mut crash_context::CONTEXT) -> i32;
471 }
472
473 #[inline(never)]
474 pub(super) fn real_main(args: Vec<String>) -> Result<()> {
475 let exception_code = u32::from_str_radix(&args[0], 16).unwrap();
476
477 // Generate the exception and communicate back where the exception pointers
478 // are
479 unsafe {
480 let mut exception_record: crash_context::EXCEPTION_RECORD = mem::zeroed();
481 let mut exception_context = std::mem::MaybeUninit::uninit();
482
483 let pid = GetCurrentProcessId();
484 let tid = GetCurrentThreadId();
485
486 GetThreadContext(GetCurrentThread(), exception_context.as_mut_ptr());
487
488 let mut exception_context = exception_context.assume_init();
489
490 let exception_ptrs = crash_context::EXCEPTION_POINTERS {
491 ExceptionRecord: &mut exception_record,
492 ContextRecord: &mut exception_context,
493 };
494
495 exception_record.ExceptionCode = exception_code as _;
496
497 let exc_ptr_addr = &exception_ptrs as *const _ as usize;
498
499 println!("{pid} {exc_ptr_addr} {tid} {exception_code:x}");
500
501 // Wait until we're killed
502 loop {
503 std::thread::park();
504 }
505 }
506 }
507 }
508
509 #[cfg(target_os = "macos")]
510 mod mac {
511 use super::*;
512 use std::time::Duration;
513
514 #[inline(never)]
515 pub(super) fn real_main(args: Vec<String>) -> Result<()> {
516 let port_name = args.get(0).ok_or("mach port name not specified")?;
517 let exception: u32 = args.get(1).ok_or("exception code not specified")?.parse()?;
518
519 let client =
520 crash_context::ipc::Client::create(&std::ffi::CString::new(port_name.clone())?)?;
521
522 std::thread::Builder::new()
523 .name("test-thread".to_owned())
524 .spawn(move || {
525 #[inline(never)]
526 fn wait_until_killed(client: crash_context::ipc::Client, exception: u32) {
527 // SAFETY: syscalls
528 let cc = unsafe {
529 crash_context::CrashContext {
530 task: mach2::traps::mach_task_self(),
531 thread: mach2::mach_init::mach_thread_self(),
532 handler_thread: mach2::port::MACH_PORT_NULL,
533 exception: Some(crash_context::ExceptionInfo {
534 kind: exception,
535 code: 0,
536 subcode: None,
537 }),
538 }
539 };
540
541 // Send the crash context to the server and wait for it to
542 // finish dumping, we should be killed shortly afterwards
543 client
544 .send_crash_context(
545 &cc,
546 Some(Duration::from_secs(2)),
547 Some(Duration::from_secs(5)),
548 )
549 .expect("failed to send crash context/receive ack");
550
551 // Wait until we're killed
552 loop {
553 std::thread::park();
554 }
555 }
556
557 wait_until_killed(client, exception)
558 })
559 .unwrap()
560 .join()
561 .unwrap();
562
563 Ok(())
564 }
565 }
566
567 fn main() -> Result<()> {
568 let args: Vec<_> = std::env::args().skip(1).collect();
569
570 cfg_if::cfg_if! {
571 if #[cfg(any(target_os = "linux", target_os = "android"))] {
572 linux::real_main(args)
573 } else if #[cfg(target_os = "windows")] {
574 windows::real_main(args)
575 } else if #[cfg(target_os = "macos")] {
576 mac::real_main(args)
577 } else {
578 unimplemented!();
579 }
580 }
581 }