5 use crate::num::NonZeroUsize;
7 use crate::sys::{os, stack_overflow};
8 use crate::time::Duration;
10 #[cfg(any(target_os = "linux", target_os = "solaris", target_os = "illumos"))]
11 use crate::sys::weak::weak;
12 #[cfg(not(any(target_os = "l4re", target_os = "vxworks")))]
13 pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
14 #[cfg(target_os = "l4re")]
15 pub const DEFAULT_MIN_STACK_SIZE: usize = 1024 * 1024;
16 #[cfg(target_os = "vxworks")]
17 pub const DEFAULT_MIN_STACK_SIZE: usize = 256 * 1024;
19 #[cfg(target_os = "fuchsia")]
21 type zx_handle_t = u32;
22 type zx_status_t = i32;
23 pub const ZX_PROP_NAME: u32 = 3;
26 pub fn zx_object_set_property(
29 value: *const libc::c_void,
30 value_size: libc::size_t,
32 pub fn zx_thread_self() -> zx_handle_t;
40 // Some platforms may have pthread_t as a pointer in which case we still want
41 // a thread to be Send/Sync
42 unsafe impl Send for Thread {}
43 unsafe impl Sync for Thread {}
46 // unsafe: see thread::Builder::spawn_unchecked for safety requirements
47 pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
48 let p = Box::into_raw(box p);
49 let mut native: libc::pthread_t = mem::zeroed();
50 let mut attr: libc::pthread_attr_t = mem::zeroed();
51 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
53 let stack_size = cmp::max(stack, min_stack_size(&attr));
55 match libc::pthread_attr_setstacksize(&mut attr, stack_size) {
58 assert_eq!(n, libc::EINVAL);
59 // EINVAL means |stack_size| is either too small or not a
60 // multiple of the system page size. Because it's definitely
61 // >= PTHREAD_STACK_MIN, it must be an alignment issue.
62 // Round up to the nearest page and try again.
63 let page_size = os::page_size();
65 (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1);
66 assert_eq!(libc::pthread_attr_setstacksize(&mut attr, stack_size), 0);
70 let ret = libc::pthread_create(&mut native, &attr, thread_start, p as *mut _);
71 // Note: if the thread creation fails and this assert fails, then p will
72 // be leaked. However, an alternative design could cause double-free
73 // which is clearly worse.
74 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
77 // The thread failed to start and as a result p was not consumed. Therefore, it is
78 // safe to reconstruct the box so that it gets deallocated.
79 drop(Box::from_raw(p));
80 Err(io::Error::from_raw_os_error(ret))
82 Ok(Thread { id: native })
85 extern "C" fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
87 // Next, set up our stack overflow handler which may get triggered if we run
89 let _handler = stack_overflow::Handler::new();
90 // Finally, let's run some code.
91 Box::from_raw(main as *mut Box<dyn FnOnce()>)();
98 let ret = unsafe { libc::sched_yield() };
99 debug_assert_eq!(ret, 0);
102 #[cfg(any(target_os = "linux", target_os = "android"))]
103 pub fn set_name(name: &CStr) {
104 const PR_SET_NAME: libc::c_int = 15;
105 // pthread wrapper only appeared in glibc 2.12, so we use syscall
108 libc::prctl(PR_SET_NAME, name.as_ptr() as libc::c_ulong, 0, 0, 0);
112 #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd"))]
113 pub fn set_name(name: &CStr) {
115 libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
119 #[cfg(any(target_os = "macos", target_os = "ios"))]
120 pub fn set_name(name: &CStr) {
122 libc::pthread_setname_np(name.as_ptr());
126 #[cfg(target_os = "netbsd")]
127 pub fn set_name(name: &CStr) {
128 use crate::ffi::CString;
129 let cname = CString::new(&b"%s"[..]).unwrap();
131 libc::pthread_setname_np(
132 libc::pthread_self(),
134 name.as_ptr() as *mut libc::c_void,
139 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
140 pub fn set_name(name: &CStr) {
142 fn pthread_setname_np(
143 libc::pthread_t, *const libc::c_char
147 if let Some(f) = pthread_setname_np.get() {
149 f(libc::pthread_self(), name.as_ptr());
154 #[cfg(target_os = "fuchsia")]
155 pub fn set_name(name: &CStr) {
158 zx_object_set_property(
161 name.as_ptr() as *const libc::c_void,
162 name.to_bytes().len(),
167 #[cfg(target_os = "haiku")]
168 pub fn set_name(name: &CStr) {
170 let thread_self = libc::find_thread(ptr::null_mut());
171 libc::rename_thread(thread_self, name.as_ptr());
176 target_env = "newlib",
178 target_os = "emscripten",
180 target_os = "vxworks"
182 pub fn set_name(_name: &CStr) {
183 // Newlib, Emscripten, and VxWorks have no way to set a thread name.
186 pub fn sleep(dur: Duration) {
187 let mut secs = dur.as_secs();
188 let mut nsecs = dur.subsec_nanos() as _;
190 // If we're awoken with a signal then the return value will be -1 and
191 // nanosleep will fill in `ts` with the remaining time.
193 while secs > 0 || nsecs > 0 {
194 let mut ts = libc::timespec {
195 tv_sec: cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t,
198 secs -= ts.tv_sec as u64;
199 let ts_ptr = &mut ts as *mut _;
200 if libc::nanosleep(ts_ptr, ts_ptr) == -1 {
201 assert_eq!(os::errno(), libc::EINTR);
202 secs += ts.tv_sec as u64;
213 let ret = libc::pthread_join(self.id, ptr::null_mut());
215 assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
219 pub fn id(&self) -> libc::pthread_t {
223 pub fn into_id(self) -> libc::pthread_t {
230 impl Drop for Thread {
232 let ret = unsafe { libc::pthread_detach(self.id) };
233 debug_assert_eq!(ret, 0);
237 pub fn available_concurrency() -> io::Result<NonZeroUsize> {
240 target_os = "android",
241 target_os = "emscripten",
242 target_os = "fuchsia",
246 target_os = "solaris",
247 target_os = "illumos",
249 match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
250 -1 => Err(io::Error::last_os_error()),
251 0 => Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform")),
252 cpus => Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) }),
254 } else if #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd"))] {
257 let mut cpus: libc::c_uint = 0;
258 let mut cpus_size = crate::mem::size_of_val(&cpus);
261 cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint;
264 // Fallback approach in case of errors or no hardware threads.
266 let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
271 &mut cpus as *mut _ as *mut _,
272 &mut cpus_size as *mut _ as *mut _,
278 // Handle errors if any.
280 return Err(io::Error::last_os_error());
281 } else if cpus == 0 {
282 return Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform"));
285 Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) })
286 } else if #[cfg(target_os = "openbsd")] {
289 let mut cpus: libc::c_uint = 0;
290 let mut cpus_size = crate::mem::size_of_val(&cpus);
291 let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
297 &mut cpus as *mut _ as *mut _,
298 &mut cpus_size as *mut _ as *mut _,
304 // Handle errors if any.
306 return Err(io::Error::last_os_error());
307 } else if cpus == 0 {
308 return Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform"));
311 Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) })
313 // FIXME: implement on vxWorks, Redox, Haiku, l4re
314 Err(io::Error::new_const(io::ErrorKind::Unsupported, &"Getting the number of hardware threads is not supported on the target platform"))
320 not(target_os = "linux"),
321 not(target_os = "freebsd"),
322 not(target_os = "macos"),
323 not(target_os = "netbsd"),
324 not(target_os = "openbsd"),
325 not(target_os = "solaris")
327 #[cfg_attr(test, allow(dead_code))]
329 use crate::ops::Range;
330 pub type Guard = Range<usize>;
331 pub unsafe fn current() -> Option<Guard> {
334 pub unsafe fn init() -> Option<Guard> {
341 target_os = "freebsd",
343 target_os = "netbsd",
344 target_os = "openbsd",
345 target_os = "solaris"
347 #[cfg_attr(test, allow(dead_code))]
349 use libc::{mmap, mprotect};
350 use libc::{MAP_ANON, MAP_FAILED, MAP_FIXED, MAP_PRIVATE, PROT_NONE, PROT_READ, PROT_WRITE};
353 use crate::ops::Range;
354 use crate::sync::atomic::{AtomicUsize, Ordering};
357 // This is initialized in init() and only read from after
358 static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0);
360 pub type Guard = Range<usize>;
362 #[cfg(target_os = "solaris")]
363 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
364 let mut current_stack: libc::stack_t = crate::mem::zeroed();
365 assert_eq!(libc::stack_getbounds(&mut current_stack), 0);
366 Some(current_stack.ss_sp)
369 #[cfg(target_os = "macos")]
370 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
371 let th = libc::pthread_self();
373 libc::pthread_get_stackaddr_np(th) as usize - libc::pthread_get_stacksize_np(th);
374 Some(stackaddr as *mut libc::c_void)
377 #[cfg(target_os = "openbsd")]
378 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
379 let mut current_stack: libc::stack_t = crate::mem::zeroed();
380 assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(), &mut current_stack), 0);
382 let stackaddr = if libc::pthread_main_np() == 1 {
384 current_stack.ss_sp as usize - current_stack.ss_size + PAGE_SIZE.load(Ordering::Relaxed)
387 current_stack.ss_sp as usize - current_stack.ss_size
389 Some(stackaddr as *mut libc::c_void)
393 target_os = "android",
394 target_os = "freebsd",
396 target_os = "netbsd",
399 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
401 let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
402 #[cfg(target_os = "freebsd")]
403 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
404 #[cfg(target_os = "freebsd")]
405 let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
406 #[cfg(not(target_os = "freebsd"))]
407 let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
409 let mut stackaddr = crate::ptr::null_mut();
410 let mut stacksize = 0;
411 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut stacksize), 0);
412 ret = Some(stackaddr);
414 if e == 0 || cfg!(target_os = "freebsd") {
415 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
420 // Precondition: PAGE_SIZE is initialized.
421 unsafe fn get_stack_start_aligned() -> Option<*mut libc::c_void> {
422 let page_size = PAGE_SIZE.load(Ordering::Relaxed);
423 assert!(page_size != 0);
424 let stackaddr = get_stack_start()?;
426 // Ensure stackaddr is page aligned! A parent process might
427 // have reset RLIMIT_STACK to be non-page aligned. The
428 // pthread_attr_getstack() reports the usable stack area
429 // stackaddr < stackaddr + stacksize, so if stackaddr is not
430 // page-aligned, calculate the fix such that stackaddr <
431 // new_page_aligned_stackaddr < stackaddr + stacksize
432 let remainder = (stackaddr as usize) % page_size;
433 Some(if remainder == 0 {
436 ((stackaddr as usize) + page_size - remainder) as *mut libc::c_void
440 pub unsafe fn init() -> Option<Guard> {
441 let page_size = os::page_size();
442 PAGE_SIZE.store(page_size, Ordering::Relaxed);
444 if cfg!(all(target_os = "linux", not(target_env = "musl"))) {
445 // Linux doesn't allocate the whole stack right away, and
446 // the kernel has its own stack-guard mechanism to fault
447 // when growing too close to an existing mapping. If we map
448 // our own guard, then the kernel starts enforcing a rather
449 // large gap above that, rendering much of the possible
450 // stack space useless. See #43052.
452 // Instead, we'll just note where we expect rlimit to start
453 // faulting, so our handler can report "stack overflow", and
454 // trust that the kernel's own stack guard will work.
455 let stackaddr = get_stack_start_aligned()?;
456 let stackaddr = stackaddr as usize;
457 Some(stackaddr - page_size..stackaddr)
458 } else if cfg!(all(target_os = "linux", target_env = "musl")) {
459 // For the main thread, the musl's pthread_attr_getstack
460 // returns the current stack size, rather than maximum size
461 // it can eventually grow to. It cannot be used to determine
462 // the position of kernel's stack guard.
464 } else if cfg!(target_os = "freebsd") {
465 // FreeBSD's stack autogrows, and optionally includes a guard page
466 // at the bottom. If we try to remap the bottom of the stack
467 // ourselves, FreeBSD's guard page moves upwards. So we'll just use
468 // the builtin guard page.
469 let stackaddr = get_stack_start_aligned()?;
470 let guardaddr = stackaddr as usize;
471 // Technically the number of guard pages is tunable and controlled
472 // by the security.bsd.stack_guard_page sysctl, but there are
473 // few reasons to change it from the default. The default value has
474 // been 1 ever since FreeBSD 11.1 and 10.4.
475 const GUARD_PAGES: usize = 1;
476 let guard = guardaddr..guardaddr + GUARD_PAGES * page_size;
479 // Reallocate the last page of the stack.
480 // This ensures SIGBUS will be raised on
482 // Systems which enforce strict PAX MPROTECT do not allow
483 // to mprotect() a mapping with less restrictive permissions
484 // than the initial mmap() used, so we mmap() here with
485 // read/write permissions and only then mprotect() it to
486 // no permissions at all. See issue #50313.
487 let stackaddr = get_stack_start_aligned()?;
491 PROT_READ | PROT_WRITE,
492 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
496 if result != stackaddr || result == MAP_FAILED {
497 panic!("failed to allocate a guard page: {}", io::Error::last_os_error());
500 let result = mprotect(stackaddr, page_size, PROT_NONE);
502 panic!("failed to protect the guard page: {}", io::Error::last_os_error());
505 let guardaddr = stackaddr as usize;
507 Some(guardaddr..guardaddr + page_size)
511 #[cfg(any(target_os = "macos", target_os = "openbsd", target_os = "solaris"))]
512 pub unsafe fn current() -> Option<Guard> {
513 let stackaddr = get_stack_start()? as usize;
514 Some(stackaddr - PAGE_SIZE.load(Ordering::Relaxed)..stackaddr)
518 target_os = "android",
519 target_os = "freebsd",
521 target_os = "netbsd",
524 pub unsafe fn current() -> Option<Guard> {
526 let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
527 #[cfg(target_os = "freebsd")]
528 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
529 #[cfg(target_os = "freebsd")]
530 let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
531 #[cfg(not(target_os = "freebsd"))]
532 let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
534 let mut guardsize = 0;
535 assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
537 if cfg!(all(target_os = "linux", target_env = "musl")) {
538 // musl versions before 1.1.19 always reported guard
539 // size obtained from pthread_attr_get_np as zero.
540 // Use page size as a fallback.
541 guardsize = PAGE_SIZE.load(Ordering::Relaxed);
543 panic!("there is no guard page");
546 let mut stackaddr = crate::ptr::null_mut();
548 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut size), 0);
550 let stackaddr = stackaddr as usize;
551 ret = if cfg!(any(target_os = "freebsd", target_os = "netbsd")) {
552 Some(stackaddr - guardsize..stackaddr)
553 } else if cfg!(all(target_os = "linux", target_env = "musl")) {
554 Some(stackaddr - guardsize..stackaddr)
555 } else if cfg!(all(target_os = "linux", target_env = "gnu")) {
556 // glibc used to include the guard area within the stack, as noted in the BUGS
557 // section of `man pthread_attr_getguardsize`. This has been corrected starting
558 // with glibc 2.27, and in some distro backports, so the guard is now placed at the
559 // end (below) the stack. There's no easy way for us to know which we have at
560 // runtime, so we'll just match any fault in the range right above or below the
561 // stack base to call that fault a stack overflow.
562 Some(stackaddr - guardsize..stackaddr + guardsize)
564 Some(stackaddr..stackaddr + guardsize)
567 if e == 0 || cfg!(target_os = "freebsd") {
568 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
574 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
575 // PTHREAD_STACK_MIN plus bytes needed for thread-local storage.
576 // We need that information to avoid blowing up when a small stack
577 // is created in an application with big thread-local storage requirements.
578 // See #6233 for rationale and details.
579 #[cfg(target_os = "linux")]
581 fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
582 weak!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);
584 match __pthread_get_minstack.get() {
585 None => libc::PTHREAD_STACK_MIN,
586 Some(f) => unsafe { f(attr) },
590 // No point in looking up __pthread_get_minstack() on non-glibc
592 #[cfg(all(not(target_os = "linux"), not(target_os = "netbsd")))]
593 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
594 libc::PTHREAD_STACK_MIN
597 #[cfg(target_os = "netbsd")]
598 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {