]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/stack_overflow.rs
Rollup merge of #78070 - RalfJung:const-panic-test, r=oli-obk
[rust.git] / library / std / src / sys / unix / stack_overflow.rs
1 #![cfg_attr(test, allow(dead_code))]
2
3 use self::imp::{drop_handler, make_handler};
4
5 pub use self::imp::cleanup;
6 pub use self::imp::init;
7
8 pub struct Handler {
9     _data: *mut libc::c_void,
10 }
11
12 impl Handler {
13     pub unsafe fn new() -> Handler {
14         make_handler()
15     }
16
17     fn null() -> Handler {
18         Handler { _data: crate::ptr::null_mut() }
19     }
20 }
21
22 impl Drop for Handler {
23     fn drop(&mut self) {
24         unsafe {
25             drop_handler(self);
26         }
27     }
28 }
29
30 #[cfg(any(
31     target_os = "linux",
32     target_os = "macos",
33     target_os = "dragonfly",
34     target_os = "freebsd",
35     target_os = "solaris",
36     target_os = "illumos",
37     all(target_os = "netbsd", not(target_vendor = "rumprun")),
38     target_os = "openbsd"
39 ))]
40 mod imp {
41     use super::Handler;
42     use crate::mem;
43     use crate::ptr;
44
45     use libc::MAP_FAILED;
46     use libc::{mmap, munmap};
47     use libc::{sigaction, sighandler_t, SA_ONSTACK, SA_SIGINFO, SIGBUS, SIG_DFL};
48     use libc::{sigaltstack, SIGSTKSZ, SS_DISABLE};
49     use libc::{MAP_ANON, MAP_PRIVATE, PROT_NONE, PROT_READ, PROT_WRITE, SIGSEGV};
50
51     use crate::sync::atomic::{AtomicBool, AtomicPtr, Ordering};
52     use crate::sys::unix::os::page_size;
53     use crate::sys_common::thread_info;
54
55     #[cfg(any(target_os = "linux", target_os = "android"))]
56     unsafe fn siginfo_si_addr(info: *mut libc::siginfo_t) -> usize {
57         #[repr(C)]
58         struct siginfo_t {
59             a: [libc::c_int; 3], // si_signo, si_errno, si_code
60             si_addr: *mut libc::c_void,
61         }
62
63         (*(info as *const siginfo_t)).si_addr as usize
64     }
65
66     #[cfg(not(any(target_os = "linux", target_os = "android")))]
67     unsafe fn siginfo_si_addr(info: *mut libc::siginfo_t) -> usize {
68         (*info).si_addr as usize
69     }
70
71     // Signal handler for the SIGSEGV and SIGBUS handlers. We've got guard pages
72     // (unmapped pages) at the end of every thread's stack, so if a thread ends
73     // up running into the guard page it'll trigger this handler. We want to
74     // detect these cases and print out a helpful error saying that the stack
75     // has overflowed. All other signals, however, should go back to what they
76     // were originally supposed to do.
77     //
78     // This handler currently exists purely to print an informative message
79     // whenever a thread overflows its stack. We then abort to exit and
80     // indicate a crash, but to avoid a misleading SIGSEGV that might lead
81     // users to believe that unsafe code has accessed an invalid pointer; the
82     // SIGSEGV encountered when overflowing the stack is expected and
83     // well-defined.
84     //
85     // If this is not a stack overflow, the handler un-registers itself and
86     // then returns (to allow the original signal to be delivered again).
87     // Returning from this kind of signal handler is technically not defined
88     // to work when reading the POSIX spec strictly, but in practice it turns
89     // out many large systems and all implementations allow returning from a
90     // signal handler to work. For a more detailed explanation see the
91     // comments on #26458.
92     unsafe extern "C" fn signal_handler(
93         signum: libc::c_int,
94         info: *mut libc::siginfo_t,
95         _data: *mut libc::c_void,
96     ) {
97         use crate::sys_common::util::report_overflow;
98
99         let guard = thread_info::stack_guard().unwrap_or(0..0);
100         let addr = siginfo_si_addr(info);
101
102         // If the faulting address is within the guard page, then we print a
103         // message saying so and abort.
104         if guard.start <= addr && addr < guard.end {
105             report_overflow();
106             rtabort!("stack overflow");
107         } else {
108             // Unregister ourselves by reverting back to the default behavior.
109             let mut action: sigaction = mem::zeroed();
110             action.sa_sigaction = SIG_DFL;
111             sigaction(signum, &action, ptr::null_mut());
112
113             // See comment above for why this function returns.
114         }
115     }
116
117     static MAIN_ALTSTACK: AtomicPtr<libc::c_void> = AtomicPtr::new(ptr::null_mut());
118     static NEED_ALTSTACK: AtomicBool = AtomicBool::new(false);
119
120     pub unsafe fn init() {
121         let mut action: sigaction = mem::zeroed();
122         for &signal in &[SIGSEGV, SIGBUS] {
123             sigaction(signal, ptr::null_mut(), &mut action);
124             // Configure our signal handler if one is not already set.
125             if action.sa_sigaction == SIG_DFL {
126                 action.sa_flags = SA_SIGINFO | SA_ONSTACK;
127                 action.sa_sigaction = signal_handler as sighandler_t;
128                 sigaction(signal, &action, ptr::null_mut());
129                 NEED_ALTSTACK.store(true, Ordering::Relaxed);
130             }
131         }
132
133         let handler = make_handler();
134         MAIN_ALTSTACK.store(handler._data, Ordering::Relaxed);
135         mem::forget(handler);
136     }
137
138     pub unsafe fn cleanup() {
139         Handler { _data: MAIN_ALTSTACK.load(Ordering::Relaxed) };
140     }
141
142     unsafe fn get_stackp() -> *mut libc::c_void {
143         let stackp = mmap(
144             ptr::null_mut(),
145             SIGSTKSZ + page_size(),
146             PROT_READ | PROT_WRITE,
147             MAP_PRIVATE | MAP_ANON,
148             -1,
149             0,
150         );
151         if stackp == MAP_FAILED {
152             panic!("failed to allocate an alternative stack");
153         }
154         let guard_result = libc::mprotect(stackp, page_size(), PROT_NONE);
155         if guard_result != 0 {
156             panic!("failed to set up alternative stack guard page");
157         }
158         stackp.add(page_size())
159     }
160
161     #[cfg(any(
162         target_os = "linux",
163         target_os = "macos",
164         target_os = "freebsd",
165         target_os = "netbsd",
166         target_os = "openbsd",
167         target_os = "solaris",
168         target_os = "illumos"
169     ))]
170     unsafe fn get_stack() -> libc::stack_t {
171         libc::stack_t { ss_sp: get_stackp(), ss_flags: 0, ss_size: SIGSTKSZ }
172     }
173
174     #[cfg(target_os = "dragonfly")]
175     unsafe fn get_stack() -> libc::stack_t {
176         libc::stack_t { ss_sp: get_stackp() as *mut i8, ss_flags: 0, ss_size: SIGSTKSZ }
177     }
178
179     pub unsafe fn make_handler() -> Handler {
180         if !NEED_ALTSTACK.load(Ordering::Relaxed) {
181             return Handler::null();
182         }
183         let mut stack = mem::zeroed();
184         sigaltstack(ptr::null(), &mut stack);
185         // Configure alternate signal stack, if one is not already set.
186         if stack.ss_flags & SS_DISABLE != 0 {
187             stack = get_stack();
188             sigaltstack(&stack, ptr::null_mut());
189             Handler { _data: stack.ss_sp as *mut libc::c_void }
190         } else {
191             Handler::null()
192         }
193     }
194
195     pub unsafe fn drop_handler(handler: &mut Handler) {
196         if !handler._data.is_null() {
197             let stack = libc::stack_t {
198                 ss_sp: ptr::null_mut(),
199                 ss_flags: SS_DISABLE,
200                 // Workaround for bug in macOS implementation of sigaltstack
201                 // UNIX2003 which returns ENOMEM when disabling a stack while
202                 // passing ss_size smaller than MINSIGSTKSZ. According to POSIX
203                 // both ss_sp and ss_size should be ignored in this case.
204                 ss_size: SIGSTKSZ,
205             };
206             sigaltstack(&stack, ptr::null_mut());
207             // We know from `get_stackp` that the alternate stack we installed is part of a mapping
208             // that started one page earlier, so walk back a page and unmap from there.
209             munmap(handler._data.sub(page_size()), SIGSTKSZ + page_size());
210         }
211     }
212 }
213
214 #[cfg(not(any(
215     target_os = "linux",
216     target_os = "macos",
217     target_os = "dragonfly",
218     target_os = "freebsd",
219     target_os = "solaris",
220     target_os = "illumos",
221     all(target_os = "netbsd", not(target_vendor = "rumprun")),
222     target_os = "openbsd",
223 )))]
224 mod imp {
225     pub unsafe fn init() {}
226
227     pub unsafe fn cleanup() {}
228
229     pub unsafe fn make_handler() -> super::Handler {
230         super::Handler::null()
231     }
232
233     pub unsafe fn drop_handler(_handler: &mut super::Handler) {}
234 }