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