5 use crate::num::NonZeroUsize;
7 use crate::sys::{os, stack_overflow};
8 use crate::time::Duration;
10 #[cfg(all(target_os = "linux", target_env = "gnu"))]
11 use crate::sys::weak::dlsym;
12 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
13 use crate::sys::weak::weak;
14 #[cfg(not(any(target_os = "l4re", target_os = "vxworks", target_os = "espidf")))]
15 pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
16 #[cfg(target_os = "l4re")]
17 pub const DEFAULT_MIN_STACK_SIZE: usize = 1024 * 1024;
18 #[cfg(target_os = "vxworks")]
19 pub const DEFAULT_MIN_STACK_SIZE: usize = 256 * 1024;
20 #[cfg(target_os = "espidf")]
21 pub const DEFAULT_MIN_STACK_SIZE: usize = 0; // 0 indicates that the stack size configured in the ESP-IDF menuconfig system should be used
23 #[cfg(target_os = "fuchsia")]
25 type zx_handle_t = u32;
26 type zx_status_t = i32;
27 pub const ZX_PROP_NAME: u32 = 3;
30 pub fn zx_object_set_property(
33 value: *const libc::c_void,
34 value_size: libc::size_t,
36 pub fn zx_thread_self() -> zx_handle_t;
44 // Some platforms may have pthread_t as a pointer in which case we still want
45 // a thread to be Send/Sync
46 unsafe impl Send for Thread {}
47 unsafe impl Sync for Thread {}
50 // unsafe: see thread::Builder::spawn_unchecked for safety requirements
51 pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
52 let p = Box::into_raw(box p);
53 let mut native: libc::pthread_t = mem::zeroed();
54 let mut attr: libc::pthread_attr_t = mem::zeroed();
55 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
57 #[cfg(target_os = "espidf")]
59 // Only set the stack if a non-zero value is passed
60 // 0 is used as an indication that the default stack size configured in the ESP-IDF menuconfig system should be used
62 libc::pthread_attr_setstacksize(&mut attr, cmp::max(stack, min_stack_size(&attr))),
67 #[cfg(not(target_os = "espidf"))]
69 let stack_size = cmp::max(stack, min_stack_size(&attr));
71 match libc::pthread_attr_setstacksize(&mut attr, stack_size) {
74 assert_eq!(n, libc::EINVAL);
75 // EINVAL means |stack_size| is either too small or not a
76 // multiple of the system page size. Because it's definitely
77 // >= PTHREAD_STACK_MIN, it must be an alignment issue.
78 // Round up to the nearest page and try again.
79 let page_size = os::page_size();
81 (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1);
82 assert_eq!(libc::pthread_attr_setstacksize(&mut attr, stack_size), 0);
87 let ret = libc::pthread_create(&mut native, &attr, thread_start, p as *mut _);
88 // Note: if the thread creation fails and this assert fails, then p will
89 // be leaked. However, an alternative design could cause double-free
90 // which is clearly worse.
91 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
94 // The thread failed to start and as a result p was not consumed. Therefore, it is
95 // safe to reconstruct the box so that it gets deallocated.
96 drop(Box::from_raw(p));
97 Err(io::Error::from_raw_os_error(ret))
99 Ok(Thread { id: native })
102 extern "C" fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
104 // Next, set up our stack overflow handler which may get triggered if we run
106 let _handler = stack_overflow::Handler::new();
107 // Finally, let's run some code.
108 Box::from_raw(main as *mut Box<dyn FnOnce()>)();
115 let ret = unsafe { libc::sched_yield() };
116 debug_assert_eq!(ret, 0);
119 #[cfg(any(target_os = "linux", target_os = "android"))]
120 pub fn set_name(name: &CStr) {
121 const PR_SET_NAME: libc::c_int = 15;
122 // pthread wrapper only appeared in glibc 2.12, so we use syscall
125 libc::prctl(PR_SET_NAME, name.as_ptr() as libc::c_ulong, 0, 0, 0);
129 #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd"))]
130 pub fn set_name(name: &CStr) {
132 libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
136 #[cfg(any(target_os = "macos", target_os = "ios"))]
137 pub fn set_name(name: &CStr) {
139 libc::pthread_setname_np(name.as_ptr());
143 #[cfg(target_os = "netbsd")]
144 pub fn set_name(name: &CStr) {
145 use crate::ffi::CString;
146 let cname = CString::new(&b"%s"[..]).unwrap();
148 libc::pthread_setname_np(
149 libc::pthread_self(),
151 name.as_ptr() as *mut libc::c_void,
156 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
157 pub fn set_name(name: &CStr) {
159 fn pthread_setname_np(
160 libc::pthread_t, *const libc::c_char
164 if let Some(f) = pthread_setname_np.get() {
166 f(libc::pthread_self(), name.as_ptr());
171 #[cfg(target_os = "fuchsia")]
172 pub fn set_name(name: &CStr) {
175 zx_object_set_property(
178 name.as_ptr() as *const libc::c_void,
179 name.to_bytes().len(),
184 #[cfg(target_os = "haiku")]
185 pub fn set_name(name: &CStr) {
187 let thread_self = libc::find_thread(ptr::null_mut());
188 libc::rename_thread(thread_self, name.as_ptr());
193 target_env = "newlib",
195 target_os = "emscripten",
197 target_os = "vxworks"
199 pub fn set_name(_name: &CStr) {
200 // Newlib, Emscripten, and VxWorks have no way to set a thread name.
203 #[cfg(not(target_os = "espidf"))]
204 pub fn sleep(dur: Duration) {
205 let mut secs = dur.as_secs();
206 let mut nsecs = dur.subsec_nanos() as _;
208 // If we're awoken with a signal then the return value will be -1 and
209 // nanosleep will fill in `ts` with the remaining time.
211 while secs > 0 || nsecs > 0 {
212 let mut ts = libc::timespec {
213 tv_sec: cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t,
216 secs -= ts.tv_sec as u64;
217 let ts_ptr = &mut ts as *mut _;
218 if libc::nanosleep(ts_ptr, ts_ptr) == -1 {
219 assert_eq!(os::errno(), libc::EINTR);
220 secs += ts.tv_sec as u64;
229 #[cfg(target_os = "espidf")]
230 pub fn sleep(dur: Duration) {
231 let mut micros = dur.as_micros();
234 let st = if micros > u32::MAX as u128 { u32::MAX } else { micros as u32 };
237 micros -= st as u128;
244 let ret = libc::pthread_join(self.id, ptr::null_mut());
246 assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
250 pub fn id(&self) -> libc::pthread_t {
254 pub fn into_id(self) -> libc::pthread_t {
261 impl Drop for Thread {
263 let ret = unsafe { libc::pthread_detach(self.id) };
264 debug_assert_eq!(ret, 0);
268 pub fn available_parallelism() -> io::Result<NonZeroUsize> {
271 target_os = "android",
272 target_os = "emscripten",
273 target_os = "fuchsia",
277 target_os = "solaris",
278 target_os = "illumos",
280 #[cfg(any(target_os = "android", target_os = "linux"))]
282 let quota = cgroup2_quota().max(1);
283 let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
285 if libc::sched_getaffinity(0, mem::size_of::<libc::cpu_set_t>(), &mut set) == 0 {
286 let count = libc::CPU_COUNT(&set) as usize;
287 let count = count.min(quota);
288 // SAFETY: affinity mask can't be empty and the quota gets clamped to a minimum of 1
289 return Ok(NonZeroUsize::new_unchecked(count));
293 match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
294 -1 => Err(io::Error::last_os_error()),
295 0 => Err(io::const_io_error!(io::ErrorKind::NotFound, "The number of hardware threads is not known for the target platform")),
296 cpus => Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) }),
298 } else if #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd"))] {
301 let mut cpus: libc::c_uint = 0;
302 let mut cpus_size = crate::mem::size_of_val(&cpus);
305 cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint;
308 // Fallback approach in case of errors or no hardware threads.
310 let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
315 &mut cpus as *mut _ as *mut _,
316 &mut cpus_size as *mut _ as *mut _,
322 // Handle errors if any.
324 return Err(io::Error::last_os_error());
325 } else if cpus == 0 {
326 return Err(io::const_io_error!(io::ErrorKind::NotFound, "The number of hardware threads is not known for the target platform"));
329 Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) })
330 } else if #[cfg(target_os = "openbsd")] {
333 let mut cpus: libc::c_uint = 0;
334 let mut cpus_size = crate::mem::size_of_val(&cpus);
335 let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
341 &mut cpus as *mut _ as *mut _,
342 &mut cpus_size as *mut _ as *mut _,
348 // Handle errors if any.
350 return Err(io::Error::last_os_error());
351 } else if cpus == 0 {
352 return Err(io::const_io_error!(io::ErrorKind::NotFound, "The number of hardware threads is not known for the target platform"));
355 Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) })
356 } else if #[cfg(target_os = "haiku")] {
357 // system_info cpu_count field gets the static data set at boot time with `smp_set_num_cpus`
358 // `get_system_info` calls then `smp_get_num_cpus`
360 let mut sinfo: libc::system_info = crate::mem::zeroed();
361 let res = libc::get_system_info(&mut sinfo);
363 if res != libc::B_OK {
364 return Err(io::const_io_error!(io::ErrorKind::NotFound, "The number of hardware threads is not known for the target platform"));
367 Ok(NonZeroUsize::new_unchecked(sinfo.cpu_count as usize))
370 // FIXME: implement on vxWorks, Redox, l4re
371 Err(io::const_io_error!(io::ErrorKind::Unsupported, "Getting the number of hardware threads is not supported on the target platform"))
376 /// Returns cgroup CPU quota in core-equivalents, rounded down, or usize::MAX if the quota cannot
377 /// be determined or is not set.
378 #[cfg(any(target_os = "android", target_os = "linux"))]
379 fn cgroup2_quota() -> usize {
380 use crate::ffi::OsString;
381 use crate::fs::{try_exists, File};
383 use crate::os::unix::ffi::OsStringExt;
384 use crate::path::PathBuf;
386 let mut quota = usize::MAX;
388 // Attempting to open a file fails under default flags due to isolation.
389 // And Miri does not have parallelism anyway.
393 let _: Option<()> = try {
394 let mut buf = Vec::with_capacity(128);
395 // find our place in the cgroup hierarchy
396 File::open("/proc/self/cgroup").ok()?.read_to_end(&mut buf).ok()?;
397 let cgroup_path = buf
398 .split(|&c| c == b'\n')
400 let mut fields = line.splitn(3, |&c| c == b':');
401 // expect cgroupv2 which has an empty 2nd field
402 if fields.nth(1) != Some(b"") {
405 let path = fields.last()?;
406 // skip leading slash
407 Some(path[1..].to_owned())
410 let cgroup_path = PathBuf::from(OsString::from_vec(cgroup_path));
412 let mut path = PathBuf::with_capacity(128);
413 let mut read_buf = String::with_capacity(20);
415 let cgroup_mount = "/sys/fs/cgroup";
417 path.push(cgroup_mount);
418 path.push(&cgroup_path);
420 path.push("cgroup.controllers");
422 // skip if we're not looking at cgroup2
423 if matches!(try_exists(&path), Err(_) | Ok(false)) {
429 while path.starts_with(cgroup_mount) {
430 path.push("cpu.max");
434 if File::open(&path).and_then(|mut f| f.read_to_string(&mut read_buf)).is_ok() {
435 let raw_quota = read_buf.lines().next()?;
436 let mut raw_quota = raw_quota.split(' ');
437 let limit = raw_quota.next()?;
438 let period = raw_quota.next()?;
439 match (limit.parse::<usize>(), period.parse::<usize>()) {
440 (Ok(limit), Ok(period)) => {
441 quota = quota.min(limit / period);
447 path.pop(); // pop filename
448 path.pop(); // pop dir
456 not(target_os = "linux"),
457 not(target_os = "freebsd"),
458 not(target_os = "macos"),
459 not(target_os = "netbsd"),
460 not(target_os = "openbsd"),
461 not(target_os = "solaris")
463 #[cfg_attr(test, allow(dead_code))]
465 use crate::ops::Range;
466 pub type Guard = Range<usize>;
467 pub unsafe fn current() -> Option<Guard> {
470 pub unsafe fn init() -> Option<Guard> {
477 target_os = "freebsd",
479 target_os = "netbsd",
480 target_os = "openbsd",
481 target_os = "solaris"
483 #[cfg_attr(test, allow(dead_code))]
485 use libc::{mmap, mprotect};
486 use libc::{MAP_ANON, MAP_FAILED, MAP_FIXED, MAP_PRIVATE, PROT_NONE, PROT_READ, PROT_WRITE};
489 use crate::ops::Range;
490 use crate::sync::atomic::{AtomicUsize, Ordering};
493 // This is initialized in init() and only read from after
494 static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0);
496 pub type Guard = Range<usize>;
498 #[cfg(target_os = "solaris")]
499 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
500 let mut current_stack: libc::stack_t = crate::mem::zeroed();
501 assert_eq!(libc::stack_getbounds(&mut current_stack), 0);
502 Some(current_stack.ss_sp)
505 #[cfg(target_os = "macos")]
506 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
507 let th = libc::pthread_self();
509 libc::pthread_get_stackaddr_np(th) as usize - libc::pthread_get_stacksize_np(th);
510 Some(stackaddr as *mut libc::c_void)
513 #[cfg(target_os = "openbsd")]
514 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
515 let mut current_stack: libc::stack_t = crate::mem::zeroed();
516 assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(), &mut current_stack), 0);
518 let stackaddr = if libc::pthread_main_np() == 1 {
520 current_stack.ss_sp as usize - current_stack.ss_size + PAGE_SIZE.load(Ordering::Relaxed)
523 current_stack.ss_sp as usize - current_stack.ss_size
525 Some(stackaddr as *mut libc::c_void)
529 target_os = "android",
530 target_os = "freebsd",
532 target_os = "netbsd",
535 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
537 let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
538 #[cfg(target_os = "freebsd")]
539 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
540 #[cfg(target_os = "freebsd")]
541 let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
542 #[cfg(not(target_os = "freebsd"))]
543 let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
545 let mut stackaddr = crate::ptr::null_mut();
546 let mut stacksize = 0;
547 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut stacksize), 0);
548 ret = Some(stackaddr);
550 if e == 0 || cfg!(target_os = "freebsd") {
551 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
556 // Precondition: PAGE_SIZE is initialized.
557 unsafe fn get_stack_start_aligned() -> Option<*mut libc::c_void> {
558 let page_size = PAGE_SIZE.load(Ordering::Relaxed);
559 assert!(page_size != 0);
560 let stackaddr = get_stack_start()?;
562 // Ensure stackaddr is page aligned! A parent process might
563 // have reset RLIMIT_STACK to be non-page aligned. The
564 // pthread_attr_getstack() reports the usable stack area
565 // stackaddr < stackaddr + stacksize, so if stackaddr is not
566 // page-aligned, calculate the fix such that stackaddr <
567 // new_page_aligned_stackaddr < stackaddr + stacksize
568 let remainder = (stackaddr as usize) % page_size;
569 Some(if remainder == 0 {
572 ((stackaddr as usize) + page_size - remainder) as *mut libc::c_void
576 pub unsafe fn init() -> Option<Guard> {
577 let page_size = os::page_size();
578 PAGE_SIZE.store(page_size, Ordering::Relaxed);
580 if cfg!(all(target_os = "linux", not(target_env = "musl"))) {
581 // Linux doesn't allocate the whole stack right away, and
582 // the kernel has its own stack-guard mechanism to fault
583 // when growing too close to an existing mapping. If we map
584 // our own guard, then the kernel starts enforcing a rather
585 // large gap above that, rendering much of the possible
586 // stack space useless. See #43052.
588 // Instead, we'll just note where we expect rlimit to start
589 // faulting, so our handler can report "stack overflow", and
590 // trust that the kernel's own stack guard will work.
591 let stackaddr = get_stack_start_aligned()?;
592 let stackaddr = stackaddr as usize;
593 Some(stackaddr - page_size..stackaddr)
594 } else if cfg!(all(target_os = "linux", target_env = "musl")) {
595 // For the main thread, the musl's pthread_attr_getstack
596 // returns the current stack size, rather than maximum size
597 // it can eventually grow to. It cannot be used to determine
598 // the position of kernel's stack guard.
600 } else if cfg!(target_os = "freebsd") {
601 // FreeBSD's stack autogrows, and optionally includes a guard page
602 // at the bottom. If we try to remap the bottom of the stack
603 // ourselves, FreeBSD's guard page moves upwards. So we'll just use
604 // the builtin guard page.
605 let stackaddr = get_stack_start_aligned()?;
606 let guardaddr = stackaddr as usize;
607 // Technically the number of guard pages is tunable and controlled
608 // by the security.bsd.stack_guard_page sysctl, but there are
609 // few reasons to change it from the default. The default value has
610 // been 1 ever since FreeBSD 11.1 and 10.4.
611 const GUARD_PAGES: usize = 1;
612 let guard = guardaddr..guardaddr + GUARD_PAGES * page_size;
615 // Reallocate the last page of the stack.
616 // This ensures SIGBUS will be raised on
618 // Systems which enforce strict PAX MPROTECT do not allow
619 // to mprotect() a mapping with less restrictive permissions
620 // than the initial mmap() used, so we mmap() here with
621 // read/write permissions and only then mprotect() it to
622 // no permissions at all. See issue #50313.
623 let stackaddr = get_stack_start_aligned()?;
627 PROT_READ | PROT_WRITE,
628 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
632 if result != stackaddr || result == MAP_FAILED {
633 panic!("failed to allocate a guard page: {}", io::Error::last_os_error());
636 let result = mprotect(stackaddr, page_size, PROT_NONE);
638 panic!("failed to protect the guard page: {}", io::Error::last_os_error());
641 let guardaddr = stackaddr as usize;
643 Some(guardaddr..guardaddr + page_size)
647 #[cfg(any(target_os = "macos", target_os = "openbsd", target_os = "solaris"))]
648 pub unsafe fn current() -> Option<Guard> {
649 let stackaddr = get_stack_start()? as usize;
650 Some(stackaddr - PAGE_SIZE.load(Ordering::Relaxed)..stackaddr)
654 target_os = "android",
655 target_os = "freebsd",
657 target_os = "netbsd",
660 pub unsafe fn current() -> Option<Guard> {
662 let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
663 #[cfg(target_os = "freebsd")]
664 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
665 #[cfg(target_os = "freebsd")]
666 let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
667 #[cfg(not(target_os = "freebsd"))]
668 let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
670 let mut guardsize = 0;
671 assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
673 if cfg!(all(target_os = "linux", target_env = "musl")) {
674 // musl versions before 1.1.19 always reported guard
675 // size obtained from pthread_attr_get_np as zero.
676 // Use page size as a fallback.
677 guardsize = PAGE_SIZE.load(Ordering::Relaxed);
679 panic!("there is no guard page");
682 let mut stackaddr = crate::ptr::null_mut();
684 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut size), 0);
686 let stackaddr = stackaddr as usize;
687 ret = if cfg!(any(target_os = "freebsd", target_os = "netbsd")) {
688 Some(stackaddr - guardsize..stackaddr)
689 } else if cfg!(all(target_os = "linux", target_env = "musl")) {
690 Some(stackaddr - guardsize..stackaddr)
691 } else if cfg!(all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")))
693 // glibc used to include the guard area within the stack, as noted in the BUGS
694 // section of `man pthread_attr_getguardsize`. This has been corrected starting
695 // with glibc 2.27, and in some distro backports, so the guard is now placed at the
696 // end (below) the stack. There's no easy way for us to know which we have at
697 // runtime, so we'll just match any fault in the range right above or below the
698 // stack base to call that fault a stack overflow.
699 Some(stackaddr - guardsize..stackaddr + guardsize)
701 Some(stackaddr..stackaddr + guardsize)
704 if e == 0 || cfg!(target_os = "freebsd") {
705 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
711 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
712 // PTHREAD_STACK_MIN plus bytes needed for thread-local storage.
713 // We need that information to avoid blowing up when a small stack
714 // is created in an application with big thread-local storage requirements.
715 // See #6233 for rationale and details.
716 #[cfg(all(target_os = "linux", target_env = "gnu"))]
717 fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
718 // We use dlsym to avoid an ELF version dependency on GLIBC_PRIVATE. (#23628)
719 // We shouldn't really be using such an internal symbol, but there's currently
720 // no other way to account for the TLS size.
721 dlsym!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);
723 match __pthread_get_minstack.get() {
724 None => libc::PTHREAD_STACK_MIN,
725 Some(f) => unsafe { f(attr) },
729 // No point in looking up __pthread_get_minstack() on non-glibc platforms.
730 #[cfg(all(not(all(target_os = "linux", target_env = "gnu")), not(target_os = "netbsd")))]
731 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
732 libc::PTHREAD_STACK_MIN
735 #[cfg(target_os = "netbsd")]
736 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {