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 assert!(signal == libc::SIGABRT || signal == libc::SIGSEGV);
89 if signal == libc::SIGSEGV {
90 // Pre-KitKat versions of Android signal an abort() with SIGSEGV at address 0xdeadbaad
91 // See e.g. https://groups.google.com/g/android-ndk/c/laW1CJc7Icc
93 // This behavior was changed in KitKat to send a standard SIGABRT signal.
94 // See: https://r.android.com/60341
96 // Additional checks performed:
97 // 1. Find last tombstone (similar to coredump but in text format) from the
98 // same executable (path) as we are (must be because of usage of fork):
99 // This ensures that we look into the correct tombstone.
100 // 2. Cause of crash is a SIGSEGV with address 0xdeadbaad.
101 // 3. libc::abort call is in one of top two functions on callstack.
102 // The last two steps distinguish between a normal SIGSEGV and one caused
105 let this_exe = std::env::current_exe().unwrap().into_os_string().into_string().unwrap();
106 let exe_string = format!(">>> {this_exe} <<<");
107 let tombstone = (0..100)
108 .map(|n| format!("/data/tombstones/tombstone_{n:02}"))
109 .filter(|f| std::path::Path::new(&f).exists())
110 .map(|f| std::fs::read_to_string(&f).expect("Cannot read tombstone file"))
111 .filter(|f| f.contains(&exe_string))
113 .expect("no tombstone found");
115 println!("Content of tombstone:\n{tombstone}");
118 .contains("signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr deadbaad"));
119 let abort_on_top = tombstone
121 .skip_while(|l| !l.contains("backtrace:"))
123 .take_while(|l| l.starts_with(" #"))
125 .any(|f| f.contains("/system/lib/libc.so (abort"));
126 assert!(abort_on_top);
134 fn run(do_panic: &dyn Fn()) -> ExitStatus {
135 let child = unsafe { libc::fork() };
138 panic::always_abort();
142 let mut status: c_int = 0;
143 let got = unsafe { libc::waitpid(child, &mut status, 0) };
144 assert_eq!(got, child);
145 let status = ExitStatus::from_raw(status.into());
149 fn one(do_panic: &dyn Fn()) {
150 let status = run(do_panic);
151 expect_aborted(status);
155 one(&|| panic!("some message"));
156 one(&|| panic!("message with argument: {}", 42));
160 one(&|| panic_any(Wotsit { }));
162 let mut c = Command::new("echo");
164 c.pre_exec(|| panic!("{}", "crash now!"));
166 let st = c.status().expect("failed to get command status");
169 struct DisplayWithHeap;
170 impl fmt::Display for DisplayWithHeap {
171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
172 let s = vec![0; 100];
173 let s = std::hint::black_box(s);
178 // Some panics in the stdlib that we want not to allocate, as
179 // otherwise these facilities become impossible to use in the
180 // child after fork, which is really quite awkward.
182 one(&|| { None::<DisplayWithHeap>.unwrap(); });
183 one(&|| { None::<DisplayWithHeap>.expect("unwrapped a none"); });
184 one(&|| { std::str::from_utf8(b"\xff").unwrap(); });
186 let x = [0, 1, 2, 3];
187 let y = x[std::hint::black_box(4)];
188 let _z = std::hint::black_box(y);
191 // Finally, check that our stunt allocator can actually catch an allocation after fork.
192 // ie, that our test is effective.
194 let status = run(&|| panic!("allocating to display... {}", DisplayWithHeap));
196 assert_eq!(status.signal(), Some(libc::SIGUSR1));