1use libc::{
2MAP_ANON, MAP_FAILED, MAP_FIXED, MAP_PRIVATE, PROT_NONE, PROT_READ, PROT_WRITE, SA_ONSTACK,
3SA_SIGINFO, SIG_DFL, SIGBUS, SIGSEGV, SS_DISABLE, sigaction, sigaltstack, sighandler_t,
4};
5#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
6use libc::{mmap as mmap64, mprotect, munmap};
7#[cfg(all(target_os = "linux", target_env = "gnu"))]
8use libc::{mmap64, mprotect, munmap};
910use super::Handler;
11use super::thread_info::{delete_current_info, set_current_info, with_current_info};
12use crate::ops::Range;
13use crate::sync::atomic::{Atomic, AtomicBool, AtomicPtr, AtomicUsize, Ordering};
14use crate::sys::pal::unix::conf;
15use crate::{io, mem, ptr};
1617/// Signal handler for the SIGSEGV and SIGBUS handlers.
18///
19/// We've got guard pages (unmapped pages) at the end of every thread's
20/// stack, so if a thread ends up running into the guard page it'll trigger
21/// this handler. We want to detect these cases and print out a helpful error
22/// saying that the stack has overflowed. All other signals, however, should
23/// go back to what they were originally supposed to do.
24///
25/// This handler currently exists purely to print an informative message
26/// whenever a thread overflows its stack. We then abort to exit and
27/// indicate a crash, but to avoid a misleading SIGSEGV that might lead
28/// users to believe that unsafe code has accessed an invalid pointer; the
29/// SIGSEGV encountered when overflowing the stack is expected and
30/// well-defined.
31///
32/// If this is not a stack overflow, the handler un-registers itself and
33/// then returns (to allow the original signal to be delivered again).
34/// Returning from this kind of signal handler is technically not defined
35/// to work when reading the POSIX spec strictly, but in practice it turns
36/// out many large systems and all implementations allow returning from a
37/// signal handler to work. For a more detailed explanation see the
38/// comments on #26458.
39///
40/// # Safety
41/// Rust doesn't call this, it *gets called* by the kernel, which we expect
42/// to provide valid parameters. Apart from that, this function does not
43/// have any other preconditions.
44unsafe extern "C" fn signal_handler(
45 signum: libc::c_int,
46 info: *mut libc::siginfo_t,
47 _data: *mut libc::c_void,
48) {
49// SAFETY: this pointer is provided by the system and will always point to a valid `siginfo_t`.
50let fault_addr = unsafe { (*info).si_addr().addr() };
5152// `with_current_info` expects that the process aborts after it is
53 // called. If the signal was not caused by a memory access, this might
54 // not be true. We detect this by noticing that the `si_addr` field is
55 // zero if the signal is synthetic.
56if fault_addr != 0 {
57with_current_info(|thread_info| {
58// If the faulting address is within the guard page, then we print a
59 // message saying so and abort.
60if let Some(thread_info) = thread_info61 && thread_info.guard_page_range.contains(&fault_addr)
62 {
63// Hey you! Yes, you modifying the stack overflow message!
64 // Please make sure that all functions called here are
65 // actually async-signal-safe. If they're not, try retrieving
66 // the information beforehand and storing it in `ThreadInfo`.
67 // Thank you!
68 // - says Jonas after having had to watch his carefully
69 // written code get made unsound again.
70let tid = thread_info.tid;
71let name = thread_info.name.as_deref().unwrap_or("<unknown>");
72if let Some(mut out) = crate::sys::stdio::panic_output() {
let _ =
crate::io::Write::write_fmt(&mut out,
format_args!("\nthread \'{0}\' ({1}) has overflowed its stack\n",
name, tid));
};rtprintpanic!("\nthread '{name}' ({tid}) has overflowed its stack\n");
73{
if let Some(mut out) = crate::sys::stdio::panic_output() {
let _ =
crate::io::Write::write_fmt(&mut out,
format_args!("fatal runtime error: {0}, aborting\n",
format_args!("stack overflow")));
};
crate::process::abort();
};rtabort!("stack overflow");
74 }
75 })
76 }
7778// Unregister ourselves by reverting back to the default behavior.
79 // SAFETY: assuming all platforms define struct sigaction as "zero-initializable"
80let mut action: sigaction = unsafe { mem::zeroed() };
81action.sa_sigaction = SIG_DFL;
82// SAFETY: pray this is a well-behaved POSIX implementation of fn sigaction
83unsafe { sigaction(signum, &action, ptr::null_mut()) };
8485// See comment above for why this function returns.
86}
8788static PAGE_SIZE: Atomic<usize> = AtomicUsize::new(0);
89// Store a pointer to the allocation for the main thread's altstack so that
90// tools like valgrind don't complain about a leaked unreachable allocation.
91//
92// If the main thread exits, the process will terminate so there's no use in
93// freeing resources. It also means that the altstack is still installed
94// while TLS destructors are run on the main thread (c.f. #111272).
95static MAIN_ALTSTACK: Atomic<*mut libc::c_void> = AtomicPtr::new(ptr::null_mut());
96static NEED_ALTSTACK: Atomic<bool> = AtomicBool::new(false);
9798/// # Safety
99/// Must be called only once, on the main thread, during program startup.
100pub unsafe fn init() {
101PAGE_SIZE.store(conf::page_size(), Ordering::Relaxed);
102103// SAFETY:
104 // This is only called on the main thread, and since it is still early
105 // in the programs lifetime there is (almost) certainly enough stack
106 // space left to install the guard page.
107let mut guard_page_range = unsafe { install_main_guard() };
108109// Even for panic=immediate-abort, installing the guard pages is important for soundness.
110 // That said, we do not care about giving nice stackoverflow messages via our custom
111 // signal handler, just exit early and let the user enjoy the segfault.
112if falsecfg!(panic = "immediate-abort") {
113return;
114 }
115116// SAFETY: C structures are always zero-initializable.
117let mut action: sigaction = unsafe { mem::zeroed() };
118for &signal in &[SIGSEGV, SIGBUS] {
119// SAFETY: just fetches the current signal handler into action
120unsafe { sigaction(signal, ptr::null_mut(), &mut action) };
121// We assume that overriding the signal handler is always safe,
122 // which might conflict with certain libraries that rely on a
123 // specific signal behaviour. To prevent problems, we only
124 // override the handler if it has not been set yet.
125if action.sa_sigaction == SIG_DFL {
126if !NEED_ALTSTACK.load(Ordering::Relaxed) {
127// haven't set up our sigaltstack yet
128NEED_ALTSTACK.store(true, Ordering::Release);
129let handler = install_sigaltstack();
130 MAIN_ALTSTACK.store(handler.data, Ordering::Relaxed);
131 mem::forget(handler);
132133if let Some(guard_page_range) = guard_page_range.take() {
134 set_current_info(guard_page_range);
135 }
136 }
137138 action.sa_flags = SA_SIGINFO | SA_ONSTACK;
139 action.sa_sigaction = signal_handler
140as unsafe extern "C" fn(i32, *mut libc::siginfo_t, *mut libc::c_void)
141as sighandler_t;
142// SAFETY:
143 // `&action` describes a valid `sigaction` and `signal_handler`
144 // is safe to use as a signal handler for `SIGSEGV` and `SIGBUS`.
145unsafe { sigaction(signal, &action, ptr::null_mut()) };
146 }
147 }
148}
149150pub fn make_handler() -> Handler {
151if falsecfg!(panic = "immediate-abort") || !NEED_ALTSTACK.load(Ordering::Acquire) {
152return Handler::null();
153 }
154155if let Some(guard_page_range) = current_guard() {
156set_current_info(guard_page_range);
157 }
158159install_sigaltstack()
160}
161162fn get_stack() -> libc::stack_t {
163// OpenBSD requires this flag for stack mapping
164 // otherwise the said mapping will fail as a no-op on most systems
165 // and has a different meaning on FreeBSD
166#[cfg(any(
167 target_os = "openbsd",
168 target_os = "netbsd",
169 target_os = "linux",
170 target_os = "dragonfly",
171 ))]
172let flags = MAP_PRIVATE | MAP_ANON | libc::MAP_STACK;
173#[cfg(not(any(
174 target_os = "openbsd",
175 target_os = "netbsd",
176 target_os = "linux",
177 target_os = "dragonfly",
178 )))]
179let flags = MAP_PRIVATE | MAP_ANON;
180181let sigstack_size = sigstack_size();
182let page_size = PAGE_SIZE.load(Ordering::Relaxed);
183184// SAFETY: this does not unmap any existing pages.
185let stackp = unsafe {
186mmap64(ptr::null_mut(), sigstack_size + page_size, PROT_READ | PROT_WRITE, flags, -1, 0)
187 };
188if stackp == MAP_FAILED {
189{
::core::panicking::panic_fmt(format_args!("failed to allocate an alternative stack: {0}",
io::Error::last_os_error()));
};panic!("failed to allocate an alternative stack: {}", io::Error::last_os_error());
190 }
191// SAFETY: this only affects the memory we just allocated.
192let guard_result = unsafe { libc::mprotect(stackp, page_size, PROT_NONE) };
193if guard_result != 0 {
194{
::core::panicking::panic_fmt(format_args!("failed to set up alternative stack guard page: {0}",
io::Error::last_os_error()));
};panic!("failed to set up alternative stack guard page: {}", io::Error::last_os_error());
195 }
196// SAFETY:
197 // The region was allocated with a larger size than `page_size`, so this
198 // addition is within bounds.
199let stackp = unsafe { stackp.add(page_size) };
200201 libc::stack_t { ss_sp: stackp, ss_flags: 0, ss_size: sigstack_size }
202}
203204fn install_sigaltstack() -> Handler {
205// Load the current alternate signal stack to see if we need to install
206 // our own.
207 //
208 // SAFETY: C structures are always zero-initializable.
209let mut stack = unsafe { mem::zeroed() };
210// SAFETY: `&mut stack` is valid for writing a `stack_t`.
211unsafe { sigaltstack(ptr::null(), &mut stack) };
212213// Configure alternate signal stack, if one is not already set.
214if stack.ss_flags & SS_DISABLE != 0 {
215let stack = get_stack();
216// SAFETY:
217 // `stack_t` is a freshly allocated stack that's not used anywhere
218 // else. It contains a guard page, so stack overflows in signal
219 // handlers will not cause undefined behaviour. We must make the
220 // fundamental runtime assumption that it is safe to install an
221 // alternate signal stack if there is none currently installed.
222 // This might conflict with foreign libraries that use the existence
223 // of an alternate signal stack as indication that certain runtime
224 // initialisation by the library has been performed (e.g. old
225 // versions of `std` assumed that certain thread-locals were already
226 // accessed and thus initialized in the thread if the stack overflow
227 // signal was successfully delivered). Such assumptions in other
228 // libraries are fundamentally flawed, so we pay no regard to them.
229unsafe { sigaltstack(&stack, ptr::null_mut()) };
230Handler { data: stack.ss_sp as *mut libc::c_void }
231 } else {
232Handler::null()
233 }
234}
235236/// # Safety
237/// Must only be called with a pointer returned by `make_handler`, and only
238/// once per `Handler`.
239pub unsafe fn drop_handler(data: *mut libc::c_void) {
240if falsecfg!(panic = "immediate-abort") || !NEED_ALTSTACK.load(Ordering::Relaxed) {
241if true {
if !data.is_null() {
::core::panicking::panic("assertion failed: data.is_null()")
};
};debug_assert!(data.is_null());
242// Skip the thread-info-store access below.
243return;
244 }
245246if !data.is_null() {
247let sigstack_size = sigstack_size();
248let page_size = PAGE_SIZE.load(Ordering::Relaxed);
249let disabling_stack = libc::stack_t {
250 ss_sp: ptr::null_mut(),
251 ss_flags: SS_DISABLE,
252// Workaround for bug in macOS implementation of sigaltstack
253 // UNIX2003 which returns ENOMEM when disabling a stack while
254 // passing ss_size smaller than MINSIGSTKSZ. According to POSIX
255 // both ss_sp and ss_size should be ignored in this case.
256ss_size: sigstack_size,
257 };
258// SAFETY:
259 // We assume that disabling the alternate signal stack is always
260 // sound, even if the current alternate signal stack is not the one
261 // we installed in `make_handler`. Any stack overflows from this
262 // point on will abort the program when the kernel tries to write
263 // the signal information to the guard page.
264 //
265 // FIXME: detect if the stack has changed, and only uninstall if it hasn't.
266unsafe { sigaltstack(&disabling_stack, ptr::null_mut()) };
267// The stack returned by `get_stack` is part of a mapping that
268 // started one page earlier, so walk back a page and unmap from
269 // there.
270 //
271 // SAFETY:
272 // This allocation was created by us in `get_stack` and, as the
273 // alternate signal stack is now disabled, is no longer in use.
274unsafe { munmap(data.sub(page_size), sigstack_size + page_size) };
275 }
276277// `make_handler` inserts the current thread's info into the store even if
278 // there is already a signal stack in place, so this cannot be conditional
279 // on `data`.
280delete_current_info();
281}
282283/// Modern kernels on modern hardware can have dynamic signal stack sizes.
284#[cfg(all(any(target_os = "linux", target_os = "android"), not(target_env = "uclibc")))]
285fn sigstack_size() -> usize {
286// SAFETY: `getauxval` is always safe to call.
287let dynamic_sigstksz = unsafe { libc::getauxval(libc::AT_MINSIGSTKSZ) };
288// If getauxval couldn't find the entry, it returns 0,
289 // so take the higher of the "constant" and auxval.
290 // This transparently supports older kernels which don't provide AT_MINSIGSTKSZ
291libc::SIGSTKSZ.max(dynamic_sigstkszas _)
292}
293294/// Not all OS support hardware where this is needed.
295#[cfg(not(all(any(target_os = "linux", target_os = "android"), not(target_env = "uclibc"))))]
296fn sigstack_size() -> usize {
297 libc::SIGSTKSZ
298}
299300#[cfg(any(target_os = "solaris", target_os = "illumos"))]
301fn get_stack_start() -> Option<*mut libc::c_void> {
302// SAFETY: C types are always zero-initializable.
303let mut current_stack: libc::stack_t = unsafe { crate::mem::zeroed() };
304// SAFETY:
305 // The pointer is valid for writing a `stack_t`.
306assert_eq!(unsafe { libc::stack_getbounds(&mut current_stack) }, 0);
307Some(current_stack.ss_sp)
308}
309310#[cfg(target_os = "macos")]
311fn get_stack_start() -> Option<*mut libc::c_void> {
312// SAFETY: always safe to call.
313let th = unsafe { libc::pthread_self() };
314// SAFETY: `th` is a valid `pthread_t`.
315unsafe {
316let stackptr = libc::pthread_get_stackaddr_np(th);
317let stacksize = libc::pthread_get_stacksize_np(th);
318Some(stackptr.map_addr(|addr| addr - stacksize))
319 }
320}
321322#[cfg(target_os = "openbsd")]
323fn get_stack_start() -> Option<*mut libc::c_void> {
324// SAFETY: C types are always zero-initializable.
325let mut current_stack: libc::stack_t = unsafe { crate::mem::zeroed() };
326// SAFETY:
327 // * calling `pthread_self` is always valid and returns a valid `pthread_t`.
328 // * `&mut current_stack` is coerced to a pointer that is valid for writing
329 // a `stack_t`.
330assert_eq!(unsafe { libc::pthread_stackseg_np(libc::pthread_self(), &mut current_stack) }, 0);
331332let stack_ptr = current_stack.ss_sp;
333// SAFETY: this is always safe to call.
334let stackaddr = if unsafe { libc::pthread_main_np() } == 1 {
335// main thread
336stack_ptr.addr() - current_stack.ss_size + PAGE_SIZE.load(Ordering::Relaxed)
337 } else {
338// new thread
339stack_ptr.addr() - current_stack.ss_size
340 };
341Some(stack_ptr.with_addr(stackaddr))
342}
343344#[cfg(any(
345 target_os = "android",
346 target_os = "freebsd",
347 target_os = "netbsd",
348 target_os = "hurd",
349 target_os = "linux",
350 target_os = "l4re"
351))]
352fn get_stack_start() -> Option<*mut libc::c_void> {
353use crate::pin::pin;
354use crate::sys::helpers::COpaque;
355356let mut ret = None;
357let mut attr: COpaque<libc::pthread_attr_t> = COpaque::uninit();
358if !falsecfg!(target_os = "freebsd") {
359attr = COpaque::zeroed();
360 }
361let attr = {
super let mut pinned: ::core::pin::PinMacroHelper<_> =
::core::pin::PinMacroHelper { value: attr };
unsafe { ::core::pin::pin_new_unchecked_in_helper(&mut pinned) }
}pin!(attr);
362// FIXME(pin-ergonomics): remove the next line.
363let attr = attr.into_ref();
364365// SAFETY:
366 // The attributes object has not been initialized yet and will not be
367 // moved until destroyed.
368#[cfg(target_os = "freebsd")]
369assert_eq!(unsafe { libc::pthread_attr_init(attr.get()) }, 0);
370// SAFETY:
371 // * calling `pthread_self` is always valid and returns a valid `pthread_t`
372 // * `attr` is an initialized attribute object that can be written to.
373#[cfg(target_os = "freebsd")]
374let e = unsafe { libc::pthread_attr_get_np(libc::pthread_self(), attr.get()) };
375// SAFETY:
376 // * calling `pthread_self` is always valid and returns a valid `pthread_t`
377 // * `attr` can be written to, and will be initialized by this call.
378#[cfg(not(target_os = "freebsd"))]
379let e = unsafe { libc::pthread_getattr_np(libc::pthread_self(), attr.get()) };
380if e == 0 {
381let mut stackaddr = crate::ptr::null_mut();
382let mut stacksize = 0;
383// SAFETY:
384 // `attr` is an initialized attribute object and both the pointers
385 // are valid for writing.
386{
match (&unsafe {
libc::pthread_attr_getstack(attr.get(), &mut stackaddr,
&mut stacksize)
}, &0) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(
387unsafe { libc::pthread_attr_getstack(attr.get(), &mut stackaddr, &mut stacksize) },
3880
389);
390ret = Some(stackaddr);
391 }
392if e == 0 || falsecfg!(target_os = "freebsd") {
393// SAFETY:
394 // `attr` was initialized either by `pthread_attr_init` (FreeBSD) or
395 // by `pthread_attr_get_np`, and is not used after this point.
396{
match (&unsafe { libc::pthread_attr_destroy(attr.get()) }, &0) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(unsafe { libc::pthread_attr_destroy(attr.get()) }, 0);
397 }
398ret399}
400401fn stack_start_aligned(page_size: usize) -> Option<*mut libc::c_void> {
402let stackptr = get_stack_start()?;
403let stackaddr = stackptr.addr();
404405// Ensure stackaddr is page aligned! A parent process might
406 // have reset RLIMIT_STACK to be non-page aligned. The
407 // pthread_attr_getstack() reports the usable stack area
408 // stackaddr < stackaddr + stacksize, so if stackaddr is not
409 // page-aligned, calculate the fix such that stackaddr <
410 // new_page_aligned_stackaddr < stackaddr + stacksize
411let remainder = stackaddr % page_size;
412Some(if remainder == 0 {
413stackptr414 } else {
415stackptr.with_addr(stackaddr + page_size - remainder)
416 })
417}
418419/// # Safety
420/// This function must only be called from the main thread, and there must
421/// be sufficient stack space remaining to place a stack guard.
422unsafe fn install_main_guard() -> Option<Range<usize>> {
423let page_size = PAGE_SIZE.load(Ordering::Relaxed);
424425// this way someone on any unix-y OS can check that all these compile
426if truecfg!(all(target_os = "linux", not(target_env = "musl"))) {
427install_main_guard_linux(page_size)
428 } else if falsecfg!(all(target_os = "linux", target_env = "musl")) {
429install_main_guard_linux_musl(page_size)
430 } else if falsecfg!(target_os = "freebsd") {
431#[cfg(not(target_os = "freebsd"))]
432return None;
433// The FreeBSD code cannot be checked on non-BSDs.
434#[cfg(target_os = "freebsd")]
435install_main_guard_freebsd(page_size)
436 } else if falsecfg!(any(target_os = "netbsd", target_os = "openbsd")) {
437install_main_guard_bsds(page_size)
438 } else {
439// SAFETY: guaranteed by caller.
440unsafe { install_main_guard_default(page_size) }
441 }
442}
443444fn install_main_guard_linux(page_size: usize) -> Option<Range<usize>> {
445// See the corresponding conditional in init().
446 // Avoid stack_start_aligned, which makes slow syscalls to read /proc/self/maps
447if falsecfg!(panic = "immediate-abort") {
448return None;
449 }
450// Linux doesn't allocate the whole stack right away, and
451 // the kernel has its own stack-guard mechanism to fault
452 // when growing too close to an existing mapping. If we map
453 // our own guard, then the kernel starts enforcing a rather
454 // large gap above that, rendering much of the possible
455 // stack space useless. See #43052.
456 //
457 // Instead, we'll just note where we expect rlimit to start
458 // faulting, so our handler can report "stack overflow", and
459 // trust that the kernel's own stack guard will work.
460let stackptr = stack_start_aligned(page_size)?;
461let stackaddr = stackptr.addr();
462Some(stackaddr - page_size..stackaddr)
463}
464465fn install_main_guard_linux_musl(_page_size: usize) -> Option<Range<usize>> {
466// For the main thread, the musl's pthread_attr_getstack
467 // returns the current stack size, rather than maximum size
468 // it can eventually grow to. It cannot be used to determine
469 // the position of kernel's stack guard.
470None471}
472473#[cfg(target_os = "freebsd")]
474fn install_main_guard_freebsd(page_size: usize) -> Option<Range<usize>> {
475// See the corresponding conditional in install_main_guard_linux().
476if cfg!(panic = "immediate-abort") {
477return None;
478 }
479// FreeBSD's stack autogrows, and optionally includes a guard page
480 // at the bottom. If we try to remap the bottom of the stack
481 // ourselves, FreeBSD's guard page moves upwards. So we'll just use
482 // the builtin guard page.
483let stackptr = stack_start_aligned(page_size)?;
484let guardaddr = stackptr.addr();
485486// The number of guard pages is tunable and controlled by the
487 // security.bsd.stack_guard_page sysctl. By default it is 1,
488 // checking once is enough since it is a boot time config value.
489let mut guard: usize = 0;
490let mut size = size_of_val(&guard);
491let oid = c"security.bsd.stack_guard_page";
492let r = unsafe {
493 libc::sysctlbyname(oid.as_ptr(), (&raw mut guard).cast(), &raw mut size, ptr::null_mut(), 0)
494 };
495let pages = if r == 0 { guard } else { 1 };
496497Some(guardaddr..guardaddr + pages * page_size)
498}
499500fn install_main_guard_bsds(page_size: usize) -> Option<Range<usize>> {
501// See the corresponding conditional in install_main_guard_linux().
502if falsecfg!(panic = "immediate-abort") {
503return None;
504 }
505// OpenBSD stack already includes a guard page, and stack is
506 // immutable.
507 // NetBSD stack includes the guard page.
508 //
509 // We'll just note where we expect rlimit to start
510 // faulting, so our handler can report "stack overflow", and
511 // trust that the kernel's own stack guard will work.
512let stackptr = stack_start_aligned(page_size)?;
513let stackaddr = stackptr.addr();
514Some(stackaddr - page_size..stackaddr)
515}
516517/// # Safety
518/// This function must only be called from the main thread, and there must
519/// be sufficient stack space remaining to place a stack guard.
520unsafe fn install_main_guard_default(page_size: usize) -> Option<Range<usize>> {
521// Reallocate the last page of the stack.
522 // This ensures SIGBUS will be raised on
523 // stack overflow.
524 // Systems which enforce strict PAX MPROTECT do not allow
525 // to mprotect() a mapping with less restrictive permissions
526 // than the initial mmap() used, so we mmap() here with
527 // read/write permissions and only then mprotect() it to
528 // no permissions at all. See issue #50313.
529let stackptr = stack_start_aligned(page_size)?;
530// SAFETY:
531 // The memory region from `stackptr..stackptr + page_size` belongs to
532 // the current thread's stack, and the caller has asserted that there
533 // is sufficient stack space, which means that this will not overwrite
534 // any existing allocations.
535let result = unsafe {
536mmap64(
537stackptr,
538page_size,
539PROT_READ | PROT_WRITE,
540MAP_PRIVATE | MAP_ANON | MAP_FIXED,
541 -1,
5420,
543 )
544 };
545if result != stackptr || result == MAP_FAILED {
546{
::core::panicking::panic_fmt(format_args!("failed to allocate a guard page: {0}",
io::Error::last_os_error()));
};panic!("failed to allocate a guard page: {}", io::Error::last_os_error());
547 }
548549// SAFETY:
550 // Since this function is only called on the main thread, the stack will
551 // not be reused until program exit, so the runtime will never observe
552 // that part of the stack has been made unusable in this way.
553let result = unsafe { mprotect(stackptr, page_size, PROT_NONE) };
554if result != 0 {
555{
::core::panicking::panic_fmt(format_args!("failed to protect the guard page: {0}",
io::Error::last_os_error()));
};panic!("failed to protect the guard page: {}", io::Error::last_os_error());
556 }
557558let guardaddr = stackptr.addr();
559560Some(guardaddr..guardaddr + page_size)
561}
562563#[cfg(any(
564 target_os = "macos",
565 target_os = "openbsd",
566 target_os = "solaris",
567 target_os = "illumos",
568))]
569fn current_guard() -> Option<Range<usize>> {
570let stackptr = get_stack_start()?;
571let stackaddr = stackptr.addr();
572Some(stackaddr - PAGE_SIZE.load(Ordering::Relaxed)..stackaddr)
573}
574575#[cfg(any(
576 target_os = "android",
577 target_os = "freebsd",
578 target_os = "hurd",
579 target_os = "linux",
580 target_os = "netbsd",
581 target_os = "l4re"
582))]
583fn current_guard() -> Option<Range<usize>> {
584use crate::pin::pin;
585use crate::sys::helpers::COpaque;
586587let mut ret = None;
588589let mut attr: COpaque<libc::pthread_attr_t> = COpaque::uninit();
590if !falsecfg!(target_os = "freebsd") {
591attr = COpaque::zeroed();
592 }
593let attr = {
super let mut pinned: ::core::pin::PinMacroHelper<_> =
::core::pin::PinMacroHelper { value: attr };
unsafe { ::core::pin::pin_new_unchecked_in_helper(&mut pinned) }
}pin!(attr);
594// FIXME(pin-ergonomics): remove the next line.
595let attr = attr.into_ref();
596597// SAFETY:
598 // The attributes object has not been initialized yet and will not be
599 // moved until destroyed.
600#[cfg(target_os = "freebsd")]
601assert_eq!(unsafe { libc::pthread_attr_init(attr.get()) }, 0);
602// SAFETY:
603 // * calling `pthread_self` is always valid and returns a valid `pthread_t`
604 // * `attr` is an initialized attribute object that can be written to.
605#[cfg(target_os = "freebsd")]
606let e = unsafe { libc::pthread_attr_get_np(libc::pthread_self(), attr.get()) };
607// SAFETY:
608 // * calling `pthread_self` is always valid and returns a valid `pthread_t`
609 // * `attr` can be written to, and will be initialized by this call.
610#[cfg(not(target_os = "freebsd"))]
611let e = unsafe { libc::pthread_getattr_np(libc::pthread_self(), attr.get()) };
612if e == 0 {
613let mut guardsize = 0;
614// SAFETY:
615 // `attr` is an initialized attribute object and the pointer is valid
616 // for writing.
617{
match (&unsafe {
libc::pthread_attr_getguardsize(attr.get(), &mut guardsize)
}, &0) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(unsafe { libc::pthread_attr_getguardsize(attr.get(), &mut guardsize) }, 0);
618if guardsize == 0 {
619if falsecfg!(all(target_os = "linux", target_env = "musl")) {
620// musl versions before 1.1.19 always reported guard
621 // size obtained from pthread_attr_get_np as zero.
622 // Use page size as a fallback.
623guardsize = PAGE_SIZE.load(Ordering::Relaxed);
624 } else {
625{ ::core::panicking::panic_fmt(format_args!("there is no guard page")); };panic!("there is no guard page");
626 }
627 }
628let mut stackptr = crate::ptr::null_mut::<libc::c_void>();
629let mut size = 0;
630// SAFETY:
631 // `attr` is an initialized attribute object and both the pointers
632 // are valid for writing.
633{
match (&unsafe {
libc::pthread_attr_getstack(attr.get(), &mut stackptr,
&mut size)
}, &0) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(unsafe { libc::pthread_attr_getstack(attr.get(), &mut stackptr, &mut size) }, 0);
634635let stackaddr = stackptr.addr();
636ret = if falsecfg!(any(target_os = "freebsd", target_os = "netbsd", target_os = "hurd")) {
637Some(stackaddr - guardsize..stackaddr)
638 } else if falsecfg!(all(target_os = "linux", target_env = "musl")) {
639Some(stackaddr - guardsize..stackaddr)
640 } else if truecfg!(all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc"))) {
641// glibc used to include the guard area within the stack, as noted in the BUGS
642 // section of `man pthread_attr_getguardsize`. This has been corrected starting
643 // with glibc 2.27, and in some distro backports, so the guard is now placed at the
644 // end (below) the stack. There's no easy way for us to know which we have at
645 // runtime, so we'll just match any fault in the range right above or below the
646 // stack base to call that fault a stack overflow.
647Some(stackaddr - guardsize..stackaddr + guardsize)
648 } else {
649Some(stackaddr..stackaddr + guardsize)
650 };
651 }
652if e == 0 || falsecfg!(target_os = "freebsd") {
653// SAFETY:
654 // `attr` was initialized either by `pthread_attr_init` (FreeBSD) or
655 // by `pthread_attr_get_np`, and is not used after this point.
656{
match (&unsafe { libc::pthread_attr_destroy(attr.get()) }, &0) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(unsafe { libc::pthread_attr_destroy(attr.get()) }, 0);
657 }
658ret659}