]> git.lizzy.rs Git - rust.git/blob - tests/ui/process/process-panic-after-fork.rs
Rollup merge of #106648 - Nilstrieb:poly-cleanup, r=compiler-errors
[rust.git] / tests / ui / process / process-panic-after-fork.rs
1 // run-pass
2 // no-prefer-dynamic
3 // ignore-wasm32-bare no libc
4 // ignore-windows
5 // ignore-sgx no libc
6 // ignore-emscripten no processes
7 // ignore-sgx no processes
8 // ignore-fuchsia no fork
9
10 #![feature(rustc_private)]
11 #![feature(never_type)]
12 #![feature(panic_always_abort)]
13
14 extern crate libc;
15
16 use std::alloc::{GlobalAlloc, Layout};
17 use std::fmt;
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};
22
23 use libc::c_int;
24
25 /// This stunt allocator allows us to spot heap allocations in the child.
26 struct PidChecking<A> {
27     parent: A,
28     require_pid: AtomicU32,
29 }
30
31 #[global_allocator]
32 static ALLOCATOR: PidChecking<std::alloc::System> = PidChecking {
33     parent: std::alloc::System,
34     require_pid: AtomicU32::new(0),
35 };
36
37 impl<A> PidChecking<A> {
38     fn engage(&self) {
39         let parent_pid = process::id();
40         eprintln!("engaging allocator trap, parent pid={}", parent_pid);
41         self.require_pid.store(parent_pid, Ordering::Release);
42     }
43     fn check(&self) {
44         let require_pid = self.require_pid.load(Ordering::Acquire);
45         if require_pid != 0 {
46             let actual_pid = process::id();
47             if require_pid != actual_pid {
48                 unsafe {
49                     libc::raise(libc::SIGUSR1);
50                 }
51             }
52         }
53     }
54 }
55
56 unsafe impl<A:GlobalAlloc> GlobalAlloc for PidChecking<A> {
57     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
58         self.check();
59         self.parent.alloc(layout)
60     }
61
62     unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
63         self.check();
64         self.parent.dealloc(ptr, layout)
65     }
66
67     unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
68         self.check();
69         self.parent.alloc_zeroed(layout)
70     }
71
72     unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
73         self.check();
74         self.parent.realloc(ptr, layout, new_size)
75     }
76 }
77
78 fn expect_aborted(status: ExitStatus) {
79     dbg!(status);
80     let signal = status.signal().expect("expected child process to die of signal");
81
82     #[cfg(not(target_os = "android"))]
83     assert!(signal == libc::SIGABRT || signal == libc::SIGILL || signal == libc::SIGTRAP);
84
85     #[cfg(target_os = "android")]
86     {
87         assert!(signal == libc::SIGABRT || signal == libc::SIGSEGV);
88
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
92             //
93             // This behavior was changed in KitKat to send a standard SIGABRT signal.
94             // See: https://r.android.com/60341
95             //
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
103             // by libc::abort.
104
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))
112                 .last()
113                 .expect("no tombstone found");
114
115             println!("Content of tombstone:\n{tombstone}");
116
117             assert!(tombstone
118                 .contains("signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr deadbaad"));
119             let abort_on_top = tombstone
120                 .lines()
121                 .skip_while(|l| !l.contains("backtrace:"))
122                 .skip(1)
123                 .take_while(|l| l.starts_with("    #"))
124                 .take(2)
125                 .any(|f| f.contains("/system/lib/libc.so (abort"));
126             assert!(abort_on_top);
127         }
128     }
129 }
130
131 fn main() {
132     ALLOCATOR.engage();
133
134     fn run(do_panic: &dyn Fn()) -> ExitStatus {
135         let child = unsafe { libc::fork() };
136         assert!(child >= 0);
137         if child == 0 {
138             panic::always_abort();
139             do_panic();
140             process::exit(0);
141         }
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());
146         status
147     }
148
149     fn one(do_panic: &dyn Fn()) {
150         let status = run(do_panic);
151         expect_aborted(status);
152     }
153
154     one(&|| panic!());
155     one(&|| panic!("some message"));
156     one(&|| panic!("message with argument: {}", 42));
157
158     #[derive(Debug)]
159     struct Wotsit { }
160     one(&|| panic_any(Wotsit { }));
161
162     let mut c = Command::new("echo");
163     unsafe {
164         c.pre_exec(|| panic!("{}", "crash now!"));
165     }
166     let st = c.status().expect("failed to get command status");
167     expect_aborted(st);
168
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);
174             write!(f, "{:?}", s)
175         }
176     }
177
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.
181
182     one(&|| { None::<DisplayWithHeap>.unwrap(); });
183     one(&|| { None::<DisplayWithHeap>.expect("unwrapped a none"); });
184     one(&|| { std::str::from_utf8(b"\xff").unwrap(); });
185     one(&|| {
186         let x = [0, 1, 2, 3];
187         let y = x[std::hint::black_box(4)];
188         let _z = std::hint::black_box(y);
189     });
190
191     // Finally, check that our stunt allocator can actually catch an allocation after fork.
192     // ie, that our test is effective.
193
194     let status = run(&|| panic!("allocating to display... {}", DisplayWithHeap));
195     dbg!(status);
196     assert_eq!(status.signal(), Some(libc::SIGUSR1));
197 }