]> git.lizzy.rs Git - rust.git/blob - src/test/ui/process/process-panic-after-fork.rs
Stabilize File::options()
[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-android: FIXME(#85261)
9
10 #![feature(bench_black_box)]
11 #![feature(rustc_private)]
12 #![feature(never_type)]
13 #![feature(panic_always_abort)]
14
15 extern crate libc;
16
17 use std::alloc::{GlobalAlloc, Layout};
18 use std::fmt;
19 use std::panic::{self, panic_any};
20 use std::os::unix::process::{CommandExt, ExitStatusExt};
21 use std::process::{self, Command, ExitStatus};
22 use std::sync::atomic::{AtomicU32, Ordering};
23
24 use libc::c_int;
25
26 #[cfg(not(target_os = "linux"))]
27 fn getpid() -> u32 {
28     process::id()
29 }
30
31 /// We need to directly use the getpid syscall instead of using `process::id()`
32 /// because the libc wrapper might return incorrect values after a process was
33 /// forked.
34 #[cfg(target_os = "linux")]
35 fn getpid() -> u32 {
36     unsafe {
37         libc::syscall(libc::SYS_getpid) as _
38     }
39 }
40
41 /// This stunt allocator allows us to spot heap allocations in the child.
42 struct PidChecking<A> {
43     parent: A,
44     require_pid: AtomicU32,
45 }
46
47 #[global_allocator]
48 static ALLOCATOR: PidChecking<std::alloc::System> = PidChecking {
49     parent: std::alloc::System,
50     require_pid: AtomicU32::new(0),
51 };
52
53 impl<A> PidChecking<A> {
54     fn engage(&self) {
55         let parent_pid = process::id();
56         eprintln!("engaging allocator trap, parent pid={}", parent_pid);
57         self.require_pid.store(parent_pid, Ordering::Release);
58     }
59     fn check(&self) {
60         let require_pid = self.require_pid.load(Ordering::Acquire);
61         if require_pid != 0 {
62             let actual_pid = getpid();
63             if require_pid != actual_pid {
64                 unsafe {
65                     libc::raise(libc::SIGUSR1);
66                 }
67             }
68         }
69     }
70 }
71
72 unsafe impl<A:GlobalAlloc> GlobalAlloc for PidChecking<A> {
73     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
74         self.check();
75         self.parent.alloc(layout)
76     }
77
78     unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
79         self.check();
80         self.parent.dealloc(ptr, layout)
81     }
82
83     unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
84         self.check();
85         self.parent.alloc_zeroed(layout)
86     }
87
88     unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
89         self.check();
90         self.parent.realloc(ptr, layout, new_size)
91     }
92 }
93
94 fn expect_aborted(status: ExitStatus) {
95     dbg!(status);
96     let signal = status.signal().expect("expected child process to die of signal");
97     assert!(signal == libc::SIGABRT || signal == libc::SIGILL || signal == libc::SIGTRAP);
98 }
99
100 fn main() {
101     ALLOCATOR.engage();
102
103     fn run(do_panic: &dyn Fn()) -> ExitStatus {
104         let child = unsafe { libc::fork() };
105         assert!(child >= 0);
106         if child == 0 {
107             panic::always_abort();
108             do_panic();
109             process::exit(0);
110         }
111         let mut status: c_int = 0;
112         let got = unsafe { libc::waitpid(child, &mut status, 0) };
113         assert_eq!(got, child);
114         let status = ExitStatus::from_raw(status.into());
115         status
116     }
117
118     fn one(do_panic: &dyn Fn()) {
119         let status = run(do_panic);
120         expect_aborted(status);
121     }
122
123     one(&|| panic!());
124     one(&|| panic!("some message"));
125     one(&|| panic!("message with argument: {}", 42));
126
127     #[derive(Debug)]
128     struct Wotsit { }
129     one(&|| panic_any(Wotsit { }));
130
131     let mut c = Command::new("echo");
132     unsafe {
133         c.pre_exec(|| panic!("{}", "crash now!"));
134     }
135     let st = c.status().expect("failed to get command status");
136     expect_aborted(st);
137
138     struct DisplayWithHeap;
139     impl fmt::Display for DisplayWithHeap {
140         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
141             let s = vec![0; 100];
142             let s = std::hint::black_box(s);
143             write!(f, "{:?}", s)
144         }
145     }
146
147     // Some panics in the stdlib that we want not to allocate, as
148     // otherwise these facilities become impossible to use in the
149     // child after fork, which is really quite awkward.
150
151     one(&|| { None::<DisplayWithHeap>.unwrap(); });
152     one(&|| { None::<DisplayWithHeap>.expect("unwrapped a none"); });
153     one(&|| { std::str::from_utf8(b"\xff").unwrap(); });
154     one(&|| {
155         let x = [0, 1, 2, 3];
156         let y = x[std::hint::black_box(4)];
157         let _z = std::hint::black_box(y);
158     });
159
160     // Finally, check that our stunt allocator can actually catch an allocation after fork.
161     // ie, that our test is effective.
162
163     let status = run(&|| panic!("allocating to display... {}", DisplayWithHeap));
164     dbg!(status);
165     assert_eq!(status.signal(), Some(libc::SIGUSR1));
166 }