]> git.lizzy.rs Git - rust.git/blob - src/test/ui/process/process-panic-after-fork.rs
Auto merge of #106025 - matthiaskrgr:rollup-vz5rqah, r=matthiaskrgr
[rust.git] / src / test / 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         // 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);
90
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
98         // by libc::abort.
99
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))
107             .last()
108             .expect("no tombstone found");
109
110         println!("Content of tombstone:\n{tombstone}");
111
112         assert!(
113             tombstone.contains("signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr deadbaad")
114         );
115         let abort_on_top = tombstone
116             .lines()
117             .skip_while(|l| !l.contains("backtrace:"))
118             .skip(1)
119             .take_while(|l| l.starts_with("    #"))
120             .take(2)
121             .any(|f| f.contains("/system/lib/libc.so (abort"));
122         assert!(abort_on_top);
123     }
124 }
125
126 fn main() {
127     ALLOCATOR.engage();
128
129     fn run(do_panic: &dyn Fn()) -> ExitStatus {
130         let child = unsafe { libc::fork() };
131         assert!(child >= 0);
132         if child == 0 {
133             panic::always_abort();
134             do_panic();
135             process::exit(0);
136         }
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());
141         status
142     }
143
144     fn one(do_panic: &dyn Fn()) {
145         let status = run(do_panic);
146         expect_aborted(status);
147     }
148
149     one(&|| panic!());
150     one(&|| panic!("some message"));
151     one(&|| panic!("message with argument: {}", 42));
152
153     #[derive(Debug)]
154     struct Wotsit { }
155     one(&|| panic_any(Wotsit { }));
156
157     let mut c = Command::new("echo");
158     unsafe {
159         c.pre_exec(|| panic!("{}", "crash now!"));
160     }
161     let st = c.status().expect("failed to get command status");
162     expect_aborted(st);
163
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);
169             write!(f, "{:?}", s)
170         }
171     }
172
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.
176
177     one(&|| { None::<DisplayWithHeap>.unwrap(); });
178     one(&|| { None::<DisplayWithHeap>.expect("unwrapped a none"); });
179     one(&|| { std::str::from_utf8(b"\xff").unwrap(); });
180     one(&|| {
181         let x = [0, 1, 2, 3];
182         let y = x[std::hint::black_box(4)];
183         let _z = std::hint::black_box(y);
184     });
185
186     // Finally, check that our stunt allocator can actually catch an allocation after fork.
187     // ie, that our test is effective.
188
189     let status = run(&|| panic!("allocating to display... {}", DisplayWithHeap));
190     dbg!(status);
191     assert_eq!(status.signal(), Some(libc::SIGUSR1));
192 }