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", target_os = "espidf")))]
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;
18 #[cfg(target_os = "espidf")]
19 pub const DEFAULT_MIN_STACK_SIZE: usize = 0; // 0 indicates that the stack size configured in the ESP-IDF menuconfig system should be used
21 #[cfg(target_os = "fuchsia")]
23 type zx_handle_t = u32;
24 type zx_status_t = i32;
25 pub const ZX_PROP_NAME: u32 = 3;
28 pub fn zx_object_set_property(
31 value: *const libc::c_void,
32 value_size: libc::size_t,
34 pub fn zx_thread_self() -> zx_handle_t;
42 // Some platforms may have pthread_t as a pointer in which case we still want
43 // a thread to be Send/Sync
44 unsafe impl Send for Thread {}
45 unsafe impl Sync for Thread {}
48 // unsafe: see thread::Builder::spawn_unchecked for safety requirements
49 pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
50 let p = Box::into_raw(box p);
51 let mut native: libc::pthread_t = mem::zeroed();
52 let mut attr: libc::pthread_attr_t = mem::zeroed();
53 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
55 #[cfg(target_os = "espidf")]
57 // Only set the stack if a non-zero value is passed
58 // 0 is used as an indication that the default stack size configured in the ESP-IDF menuconfig system should be used
60 libc::pthread_attr_setstacksize(&mut attr, cmp::max(stack, min_stack_size(&attr))),
65 #[cfg(not(target_os = "espidf"))]
67 let stack_size = cmp::max(stack, min_stack_size(&attr));
69 match libc::pthread_attr_setstacksize(&mut attr, stack_size) {
72 assert_eq!(n, libc::EINVAL);
73 // EINVAL means |stack_size| is either too small or not a
74 // multiple of the system page size. Because it's definitely
75 // >= PTHREAD_STACK_MIN, it must be an alignment issue.
76 // Round up to the nearest page and try again.
77 let page_size = os::page_size();
79 (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1);
80 assert_eq!(libc::pthread_attr_setstacksize(&mut attr, stack_size), 0);
85 let ret = libc::pthread_create(&mut native, &attr, thread_start, p as *mut _);
86 // Note: if the thread creation fails and this assert fails, then p will
87 // be leaked. However, an alternative design could cause double-free
88 // which is clearly worse.
89 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
92 // The thread failed to start and as a result p was not consumed. Therefore, it is
93 // safe to reconstruct the box so that it gets deallocated.
94 drop(Box::from_raw(p));
95 Err(io::Error::from_raw_os_error(ret))
97 Ok(Thread { id: native })
100 extern "C" fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
102 // Next, set up our stack overflow handler which may get triggered if we run
104 let _handler = stack_overflow::Handler::new();
105 // Finally, let's run some code.
106 Box::from_raw(main as *mut Box<dyn FnOnce()>)();
113 let ret = unsafe { libc::sched_yield() };
114 debug_assert_eq!(ret, 0);
117 #[cfg(any(target_os = "linux", target_os = "android"))]
118 pub fn set_name(name: &CStr) {
119 const PR_SET_NAME: libc::c_int = 15;
120 // pthread wrapper only appeared in glibc 2.12, so we use syscall
123 libc::prctl(PR_SET_NAME, name.as_ptr() as libc::c_ulong, 0, 0, 0);
127 #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd"))]
128 pub fn set_name(name: &CStr) {
130 libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
134 #[cfg(any(target_os = "macos", target_os = "ios"))]
135 pub fn set_name(name: &CStr) {
137 libc::pthread_setname_np(name.as_ptr());
141 #[cfg(target_os = "netbsd")]
142 pub fn set_name(name: &CStr) {
143 use crate::ffi::CString;
144 let cname = CString::new(&b"%s"[..]).unwrap();
146 libc::pthread_setname_np(
147 libc::pthread_self(),
149 name.as_ptr() as *mut libc::c_void,
154 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
155 pub fn set_name(name: &CStr) {
157 fn pthread_setname_np(
158 libc::pthread_t, *const libc::c_char
162 if let Some(f) = pthread_setname_np.get() {
164 f(libc::pthread_self(), name.as_ptr());
169 #[cfg(target_os = "fuchsia")]
170 pub fn set_name(name: &CStr) {
173 zx_object_set_property(
176 name.as_ptr() as *const libc::c_void,
177 name.to_bytes().len(),
182 #[cfg(target_os = "haiku")]
183 pub fn set_name(name: &CStr) {
185 let thread_self = libc::find_thread(ptr::null_mut());
186 libc::rename_thread(thread_self, name.as_ptr());
191 target_env = "newlib",
193 target_os = "emscripten",
195 target_os = "vxworks"
197 pub fn set_name(_name: &CStr) {
198 // Newlib, Emscripten, and VxWorks have no way to set a thread name.
201 #[cfg(not(target_os = "espidf"))]
202 pub fn sleep(dur: Duration) {
203 let mut secs = dur.as_secs();
204 let mut nsecs = dur.subsec_nanos() as _;
206 // If we're awoken with a signal then the return value will be -1 and
207 // nanosleep will fill in `ts` with the remaining time.
209 while secs > 0 || nsecs > 0 {
210 let mut ts = libc::timespec {
211 tv_sec: cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t,
214 secs -= ts.tv_sec as u64;
215 let ts_ptr = &mut ts as *mut _;
216 if libc::nanosleep(ts_ptr, ts_ptr) == -1 {
217 assert_eq!(os::errno(), libc::EINTR);
218 secs += ts.tv_sec as u64;
227 #[cfg(target_os = "espidf")]
228 pub fn sleep(dur: Duration) {
229 let mut micros = dur.as_micros();
232 let st = if micros > u32::MAX as u128 { u32::MAX } else { micros as u32 };
235 micros -= st as u128;
242 let ret = libc::pthread_join(self.id, ptr::null_mut());
244 assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
248 pub fn id(&self) -> libc::pthread_t {
252 pub fn into_id(self) -> libc::pthread_t {
259 impl Drop for Thread {
261 let ret = unsafe { libc::pthread_detach(self.id) };
262 debug_assert_eq!(ret, 0);
266 pub fn available_parallelism() -> io::Result<NonZeroUsize> {
269 target_os = "android",
270 target_os = "emscripten",
271 target_os = "fuchsia",
275 target_os = "solaris",
276 target_os = "illumos",
278 #[cfg(any(target_os = "android", target_os = "linux"))]
280 let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
281 if unsafe { libc::sched_getaffinity(0, mem::size_of::<libc::cpu_set_t>(), &mut set) } == 0 {
282 let count = unsafe { libc::CPU_COUNT(&set) };
283 return Ok(unsafe { NonZeroUsize::new_unchecked(count as usize) });
286 match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
287 -1 => Err(io::Error::last_os_error()),
288 0 => Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform")),
289 cpus => Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) }),
291 } else if #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd"))] {
294 let mut cpus: libc::c_uint = 0;
295 let mut cpus_size = crate::mem::size_of_val(&cpus);
298 cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint;
301 // Fallback approach in case of errors or no hardware threads.
303 let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
308 &mut cpus as *mut _ as *mut _,
309 &mut cpus_size as *mut _ as *mut _,
315 // Handle errors if any.
317 return Err(io::Error::last_os_error());
318 } else if cpus == 0 {
319 return Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform"));
322 Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) })
323 } else if #[cfg(target_os = "openbsd")] {
326 let mut cpus: libc::c_uint = 0;
327 let mut cpus_size = crate::mem::size_of_val(&cpus);
328 let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
334 &mut cpus as *mut _ as *mut _,
335 &mut cpus_size as *mut _ as *mut _,
341 // Handle errors if any.
343 return Err(io::Error::last_os_error());
344 } else if cpus == 0 {
345 return Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform"));
348 Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) })
349 } else if #[cfg(target_os = "haiku")] {
350 // system_info cpu_count field gets the static data set at boot time with `smp_set_num_cpus`
351 // `get_system_info` calls then `smp_get_num_cpus`
353 let mut sinfo: libc::system_info = crate::mem::zeroed();
354 let res = libc::get_system_info(&mut sinfo);
356 if res != libc::B_OK {
357 return Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform"));
360 Ok(NonZeroUsize::new_unchecked(sinfo.cpu_count as usize))
363 // FIXME: implement on vxWorks, Redox, l4re
364 Err(io::Error::new_const(io::ErrorKind::Unsupported, &"Getting the number of hardware threads is not supported on the target platform"))
370 not(target_os = "linux"),
371 not(target_os = "freebsd"),
372 not(target_os = "macos"),
373 not(target_os = "netbsd"),
374 not(target_os = "openbsd"),
375 not(target_os = "solaris")
377 #[cfg_attr(test, allow(dead_code))]
379 use crate::ops::Range;
380 pub type Guard = Range<usize>;
381 pub unsafe fn current() -> Option<Guard> {
384 pub unsafe fn init() -> Option<Guard> {
391 target_os = "freebsd",
393 target_os = "netbsd",
394 target_os = "openbsd",
395 target_os = "solaris"
397 #[cfg_attr(test, allow(dead_code))]
399 use libc::{mmap, mprotect};
400 use libc::{MAP_ANON, MAP_FAILED, MAP_FIXED, MAP_PRIVATE, PROT_NONE, PROT_READ, PROT_WRITE};
403 use crate::ops::Range;
404 use crate::sync::atomic::{AtomicUsize, Ordering};
407 // This is initialized in init() and only read from after
408 static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0);
410 pub type Guard = Range<usize>;
412 #[cfg(target_os = "solaris")]
413 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
414 let mut current_stack: libc::stack_t = crate::mem::zeroed();
415 assert_eq!(libc::stack_getbounds(&mut current_stack), 0);
416 Some(current_stack.ss_sp)
419 #[cfg(target_os = "macos")]
420 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
421 let th = libc::pthread_self();
423 libc::pthread_get_stackaddr_np(th) as usize - libc::pthread_get_stacksize_np(th);
424 Some(stackaddr as *mut libc::c_void)
427 #[cfg(target_os = "openbsd")]
428 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
429 let mut current_stack: libc::stack_t = crate::mem::zeroed();
430 assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(), &mut current_stack), 0);
432 let stackaddr = if libc::pthread_main_np() == 1 {
434 current_stack.ss_sp as usize - current_stack.ss_size + PAGE_SIZE.load(Ordering::Relaxed)
437 current_stack.ss_sp as usize - current_stack.ss_size
439 Some(stackaddr as *mut libc::c_void)
443 target_os = "android",
444 target_os = "freebsd",
446 target_os = "netbsd",
449 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
451 let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
452 #[cfg(target_os = "freebsd")]
453 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
454 #[cfg(target_os = "freebsd")]
455 let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
456 #[cfg(not(target_os = "freebsd"))]
457 let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
459 let mut stackaddr = crate::ptr::null_mut();
460 let mut stacksize = 0;
461 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut stacksize), 0);
462 ret = Some(stackaddr);
464 if e == 0 || cfg!(target_os = "freebsd") {
465 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
470 // Precondition: PAGE_SIZE is initialized.
471 unsafe fn get_stack_start_aligned() -> Option<*mut libc::c_void> {
472 let page_size = PAGE_SIZE.load(Ordering::Relaxed);
473 assert!(page_size != 0);
474 let stackaddr = get_stack_start()?;
476 // Ensure stackaddr is page aligned! A parent process might
477 // have reset RLIMIT_STACK to be non-page aligned. The
478 // pthread_attr_getstack() reports the usable stack area
479 // stackaddr < stackaddr + stacksize, so if stackaddr is not
480 // page-aligned, calculate the fix such that stackaddr <
481 // new_page_aligned_stackaddr < stackaddr + stacksize
482 let remainder = (stackaddr as usize) % page_size;
483 Some(if remainder == 0 {
486 ((stackaddr as usize) + page_size - remainder) as *mut libc::c_void
490 pub unsafe fn init() -> Option<Guard> {
491 let page_size = os::page_size();
492 PAGE_SIZE.store(page_size, Ordering::Relaxed);
494 if cfg!(all(target_os = "linux", not(target_env = "musl"))) {
495 // Linux doesn't allocate the whole stack right away, and
496 // the kernel has its own stack-guard mechanism to fault
497 // when growing too close to an existing mapping. If we map
498 // our own guard, then the kernel starts enforcing a rather
499 // large gap above that, rendering much of the possible
500 // stack space useless. See #43052.
502 // Instead, we'll just note where we expect rlimit to start
503 // faulting, so our handler can report "stack overflow", and
504 // trust that the kernel's own stack guard will work.
505 let stackaddr = get_stack_start_aligned()?;
506 let stackaddr = stackaddr as usize;
507 Some(stackaddr - page_size..stackaddr)
508 } else if cfg!(all(target_os = "linux", target_env = "musl")) {
509 // For the main thread, the musl's pthread_attr_getstack
510 // returns the current stack size, rather than maximum size
511 // it can eventually grow to. It cannot be used to determine
512 // the position of kernel's stack guard.
514 } else if cfg!(target_os = "freebsd") {
515 // FreeBSD's stack autogrows, and optionally includes a guard page
516 // at the bottom. If we try to remap the bottom of the stack
517 // ourselves, FreeBSD's guard page moves upwards. So we'll just use
518 // the builtin guard page.
519 let stackaddr = get_stack_start_aligned()?;
520 let guardaddr = stackaddr as usize;
521 // Technically the number of guard pages is tunable and controlled
522 // by the security.bsd.stack_guard_page sysctl, but there are
523 // few reasons to change it from the default. The default value has
524 // been 1 ever since FreeBSD 11.1 and 10.4.
525 const GUARD_PAGES: usize = 1;
526 let guard = guardaddr..guardaddr + GUARD_PAGES * page_size;
529 // Reallocate the last page of the stack.
530 // This ensures SIGBUS will be raised on
532 // Systems which enforce strict PAX MPROTECT do not allow
533 // to mprotect() a mapping with less restrictive permissions
534 // than the initial mmap() used, so we mmap() here with
535 // read/write permissions and only then mprotect() it to
536 // no permissions at all. See issue #50313.
537 let stackaddr = get_stack_start_aligned()?;
541 PROT_READ | PROT_WRITE,
542 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
546 if result != stackaddr || result == MAP_FAILED {
547 panic!("failed to allocate a guard page: {}", io::Error::last_os_error());
550 let result = mprotect(stackaddr, page_size, PROT_NONE);
552 panic!("failed to protect the guard page: {}", io::Error::last_os_error());
555 let guardaddr = stackaddr as usize;
557 Some(guardaddr..guardaddr + page_size)
561 #[cfg(any(target_os = "macos", target_os = "openbsd", target_os = "solaris"))]
562 pub unsafe fn current() -> Option<Guard> {
563 let stackaddr = get_stack_start()? as usize;
564 Some(stackaddr - PAGE_SIZE.load(Ordering::Relaxed)..stackaddr)
568 target_os = "android",
569 target_os = "freebsd",
571 target_os = "netbsd",
574 pub unsafe fn current() -> Option<Guard> {
576 let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
577 #[cfg(target_os = "freebsd")]
578 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
579 #[cfg(target_os = "freebsd")]
580 let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
581 #[cfg(not(target_os = "freebsd"))]
582 let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
584 let mut guardsize = 0;
585 assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
587 if cfg!(all(target_os = "linux", target_env = "musl")) {
588 // musl versions before 1.1.19 always reported guard
589 // size obtained from pthread_attr_get_np as zero.
590 // Use page size as a fallback.
591 guardsize = PAGE_SIZE.load(Ordering::Relaxed);
593 panic!("there is no guard page");
596 let mut stackaddr = crate::ptr::null_mut();
598 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut size), 0);
600 let stackaddr = stackaddr as usize;
601 ret = if cfg!(any(target_os = "freebsd", target_os = "netbsd")) {
602 Some(stackaddr - guardsize..stackaddr)
603 } else if cfg!(all(target_os = "linux", target_env = "musl")) {
604 Some(stackaddr - guardsize..stackaddr)
605 } else if cfg!(all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")))
607 // glibc used to include the guard area within the stack, as noted in the BUGS
608 // section of `man pthread_attr_getguardsize`. This has been corrected starting
609 // with glibc 2.27, and in some distro backports, so the guard is now placed at the
610 // end (below) the stack. There's no easy way for us to know which we have at
611 // runtime, so we'll just match any fault in the range right above or below the
612 // stack base to call that fault a stack overflow.
613 Some(stackaddr - guardsize..stackaddr + guardsize)
615 Some(stackaddr..stackaddr + guardsize)
618 if e == 0 || cfg!(target_os = "freebsd") {
619 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
625 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
626 // PTHREAD_STACK_MIN plus bytes needed for thread-local storage.
627 // We need that information to avoid blowing up when a small stack
628 // is created in an application with big thread-local storage requirements.
629 // See #6233 for rationale and details.
630 #[cfg(target_os = "linux")]
632 fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
633 weak!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);
635 match __pthread_get_minstack.get() {
636 None => libc::PTHREAD_STACK_MIN,
637 Some(f) => unsafe { f(attr) },
641 // No point in looking up __pthread_get_minstack() on non-glibc
643 #[cfg(all(not(target_os = "linux"), not(target_os = "netbsd")))]
644 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
645 libc::PTHREAD_STACK_MIN
648 #[cfg(target_os = "netbsd")]
649 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {