3 // ignore-wasm32-bare no libc
6 // ignore-emscripten no processes
7 // ignore-sgx no processes
8 // ignore-fuchsia no fork
10 #![feature(rustc_private)]
11 #![feature(never_type)]
12 #![feature(panic_always_abort)]
16 use std::alloc::{GlobalAlloc, Layout};
18 use std::panic::{self, panic_any};
19 use std::os::unix::process::{CommandExt, ExitStatusExt};
20 use std::process::{self, Command, ExitStatus};
21 use std::sync::atomic::{AtomicU32, Ordering};
25 /// This stunt allocator allows us to spot heap allocations in the child.
26 struct PidChecking<A> {
28 require_pid: AtomicU32,
32 static ALLOCATOR: PidChecking<std::alloc::System> = PidChecking {
33 parent: std::alloc::System,
34 require_pid: AtomicU32::new(0),
37 impl<A> PidChecking<A> {
39 let parent_pid = process::id();
40 eprintln!("engaging allocator trap, parent pid={}", parent_pid);
41 self.require_pid.store(parent_pid, Ordering::Release);
44 let require_pid = self.require_pid.load(Ordering::Acquire);
46 let actual_pid = process::id();
47 if require_pid != actual_pid {
49 libc::raise(libc::SIGUSR1);
56 unsafe impl<A:GlobalAlloc> GlobalAlloc for PidChecking<A> {
57 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
59 self.parent.alloc(layout)
62 unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
64 self.parent.dealloc(ptr, layout)
67 unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
69 self.parent.alloc_zeroed(layout)
72 unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
74 self.parent.realloc(ptr, layout, new_size)
78 fn expect_aborted(status: ExitStatus) {
80 let signal = status.signal().expect("expected child process to die of signal");
82 #[cfg(not(target_os = "android"))]
83 assert!(signal == libc::SIGABRT || signal == libc::SIGILL || signal == libc::SIGTRAP);
85 #[cfg(target_os = "android")]
87 // Android signals an abort() call with SIGSEGV at address 0xdeadbaad
88 // See e.g. https://groups.google.com/g/android-ndk/c/laW1CJc7Icc
89 assert!(signal == libc::SIGSEGV);
91 // Additional checks performed:
92 // 1. Find last tombstone (similar to coredump but in text format) from the
93 // same executable (path) as we are (must be because of usage of fork):
94 // This ensures that we look into the correct tombstone.
95 // 2. Cause of crash is a SIGSEGV with address 0xdeadbaad.
96 // 3. libc::abort call is in one of top two functions on callstack.
97 // The last two steps distinguish between a normal SIGSEGV and one caused
100 let this_exe = std::env::current_exe().unwrap().into_os_string().into_string().unwrap();
101 let exe_string = format!(">>> {this_exe} <<<");
102 let tombstone = (0..100)
103 .map(|n| format!("/data/tombstones/tombstone_{n:02}"))
104 .filter(|f| std::path::Path::new(&f).exists())
105 .map(|f| std::fs::read_to_string(&f).expect("Cannot read tombstone file"))
106 .filter(|f| f.contains(&exe_string))
108 .expect("no tombstone found");
110 println!("Content of tombstone:\n{tombstone}");
113 tombstone.contains("signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr deadbaad")
115 let abort_on_top = tombstone
117 .skip_while(|l| !l.contains("backtrace:"))
119 .take_while(|l| l.starts_with(" #"))
121 .any(|f| f.contains("/system/lib/libc.so (abort"));
122 assert!(abort_on_top);
129 fn run(do_panic: &dyn Fn()) -> ExitStatus {
130 let child = unsafe { libc::fork() };
133 panic::always_abort();
137 let mut status: c_int = 0;
138 let got = unsafe { libc::waitpid(child, &mut status, 0) };
139 assert_eq!(got, child);
140 let status = ExitStatus::from_raw(status.into());
144 fn one(do_panic: &dyn Fn()) {
145 let status = run(do_panic);
146 expect_aborted(status);
150 one(&|| panic!("some message"));
151 one(&|| panic!("message with argument: {}", 42));
155 one(&|| panic_any(Wotsit { }));
157 let mut c = Command::new("echo");
159 c.pre_exec(|| panic!("{}", "crash now!"));
161 let st = c.status().expect("failed to get command status");
164 struct DisplayWithHeap;
165 impl fmt::Display for DisplayWithHeap {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
167 let s = vec![0; 100];
168 let s = std::hint::black_box(s);
173 // Some panics in the stdlib that we want not to allocate, as
174 // otherwise these facilities become impossible to use in the
175 // child after fork, which is really quite awkward.
177 one(&|| { None::<DisplayWithHeap>.unwrap(); });
178 one(&|| { None::<DisplayWithHeap>.expect("unwrapped a none"); });
179 one(&|| { std::str::from_utf8(b"\xff").unwrap(); });
181 let x = [0, 1, 2, 3];
182 let y = x[std::hint::black_box(4)];
183 let _z = std::hint::black_box(y);
186 // Finally, check that our stunt allocator can actually catch an allocation after fork.
187 // ie, that our test is effective.
189 let status = run(&|| panic!("allocating to display... {}", DisplayWithHeap));
191 assert_eq!(status.signal(), Some(libc::SIGUSR1));