std/sys/pal/unix/
thread.rs

1use crate::ffi::CStr;
2use crate::mem::{self, ManuallyDrop};
3use crate::num::NonZero;
4#[cfg(all(target_os = "linux", target_env = "gnu"))]
5use crate::sys::weak::dlsym;
6#[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto",))]
7use crate::sys::weak::weak;
8use crate::sys::{os, stack_overflow};
9use crate::time::{Duration, Instant};
10use crate::{cmp, io, ptr};
11#[cfg(not(any(
12    target_os = "l4re",
13    target_os = "vxworks",
14    target_os = "espidf",
15    target_os = "nuttx"
16)))]
17pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
18#[cfg(target_os = "l4re")]
19pub const DEFAULT_MIN_STACK_SIZE: usize = 1024 * 1024;
20#[cfg(target_os = "vxworks")]
21pub const DEFAULT_MIN_STACK_SIZE: usize = 256 * 1024;
22#[cfg(any(target_os = "espidf", target_os = "nuttx"))]
23pub const DEFAULT_MIN_STACK_SIZE: usize = 0; // 0 indicates that the stack size configured in the ESP-IDF/NuttX menuconfig system should be used
24
25struct ThreadData {
26    name: Option<Box<str>>,
27    f: Box<dyn FnOnce()>,
28}
29
30pub struct Thread {
31    id: libc::pthread_t,
32}
33
34// Some platforms may have pthread_t as a pointer in which case we still want
35// a thread to be Send/Sync
36unsafe impl Send for Thread {}
37unsafe impl Sync for Thread {}
38
39impl Thread {
40    // unsafe: see thread::Builder::spawn_unchecked for safety requirements
41    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
42    pub unsafe fn new(
43        stack: usize,
44        name: Option<&str>,
45        f: Box<dyn FnOnce()>,
46    ) -> io::Result<Thread> {
47        let data = Box::into_raw(Box::new(ThreadData { name: name.map(Box::from), f }));
48        let mut native: libc::pthread_t = mem::zeroed();
49        let mut attr: mem::MaybeUninit<libc::pthread_attr_t> = mem::MaybeUninit::uninit();
50        assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0);
51
52        #[cfg(any(target_os = "espidf", target_os = "nuttx"))]
53        if stack > 0 {
54            // Only set the stack if a non-zero value is passed
55            // 0 is used as an indication that the default stack size configured in the ESP-IDF/NuttX menuconfig system should be used
56            assert_eq!(
57                libc::pthread_attr_setstacksize(
58                    attr.as_mut_ptr(),
59                    cmp::max(stack, min_stack_size(attr.as_ptr()))
60                ),
61                0
62            );
63        }
64
65        #[cfg(not(any(target_os = "espidf", target_os = "nuttx")))]
66        {
67            let stack_size = cmp::max(stack, min_stack_size(attr.as_ptr()));
68
69            match libc::pthread_attr_setstacksize(attr.as_mut_ptr(), stack_size) {
70                0 => {}
71                n => {
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();
78                    let stack_size =
79                        (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1);
80
81                    // Some libc implementations, e.g. musl, place an upper bound
82                    // on the stack size, in which case we can only gracefully return
83                    // an error here.
84                    if libc::pthread_attr_setstacksize(attr.as_mut_ptr(), stack_size) != 0 {
85                        assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0);
86                        drop(Box::from_raw(data));
87                        return Err(io::const_error!(
88                            io::ErrorKind::InvalidInput,
89                            "invalid stack size"
90                        ));
91                    }
92                }
93            };
94        }
95
96        let ret = libc::pthread_create(&mut native, attr.as_ptr(), thread_start, data as *mut _);
97        // Note: if the thread creation fails and this assert fails, then p will
98        // be leaked. However, an alternative design could cause double-free
99        // which is clearly worse.
100        assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0);
101
102        return if ret != 0 {
103            // The thread failed to start and as a result p was not consumed. Therefore, it is
104            // safe to reconstruct the box so that it gets deallocated.
105            drop(Box::from_raw(data));
106            Err(io::Error::from_raw_os_error(ret))
107        } else {
108            Ok(Thread { id: native })
109        };
110
111        extern "C" fn thread_start(data: *mut libc::c_void) -> *mut libc::c_void {
112            unsafe {
113                let data = Box::from_raw(data as *mut ThreadData);
114                // Next, set up our stack overflow handler which may get triggered if we run
115                // out of stack.
116                let _handler = stack_overflow::Handler::new(data.name);
117                // Finally, let's run some code.
118                (data.f)();
119            }
120            ptr::null_mut()
121        }
122    }
123
124    pub fn yield_now() {
125        let ret = unsafe { libc::sched_yield() };
126        debug_assert_eq!(ret, 0);
127    }
128
129    #[cfg(target_os = "android")]
130    pub fn set_name(name: &CStr) {
131        const PR_SET_NAME: libc::c_int = 15;
132        unsafe {
133            let res = libc::prctl(
134                PR_SET_NAME,
135                name.as_ptr(),
136                0 as libc::c_ulong,
137                0 as libc::c_ulong,
138                0 as libc::c_ulong,
139            );
140            // We have no good way of propagating errors here, but in debug-builds let's check that this actually worked.
141            debug_assert_eq!(res, 0);
142        }
143    }
144
145    #[cfg(any(
146        target_os = "linux",
147        target_os = "freebsd",
148        target_os = "dragonfly",
149        target_os = "nuttx",
150        target_os = "cygwin"
151    ))]
152    pub fn set_name(name: &CStr) {
153        unsafe {
154            cfg_select! {
155                any(target_os = "linux", target_os = "cygwin") => {
156                    // Linux and Cygwin limits the allowed length of the name.
157                    const TASK_COMM_LEN: usize = 16;
158                    let name = truncate_cstr::<{ TASK_COMM_LEN }>(name);
159                }
160                _ => {
161                    // FreeBSD, DragonFly BSD and NuttX do not enforce length limits.
162                }
163            };
164            // Available since glibc 2.12, musl 1.1.16, and uClibc 1.0.20 for Linux,
165            // FreeBSD 12.2 and 13.0, and DragonFly BSD 6.0.
166            let res = libc::pthread_setname_np(libc::pthread_self(), name.as_ptr());
167            // We have no good way of propagating errors here, but in debug-builds let's check that this actually worked.
168            debug_assert_eq!(res, 0);
169        }
170    }
171
172    #[cfg(target_os = "openbsd")]
173    pub fn set_name(name: &CStr) {
174        unsafe {
175            libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
176        }
177    }
178
179    #[cfg(target_vendor = "apple")]
180    pub fn set_name(name: &CStr) {
181        unsafe {
182            let name = truncate_cstr::<{ libc::MAXTHREADNAMESIZE }>(name);
183            let res = libc::pthread_setname_np(name.as_ptr());
184            // We have no good way of propagating errors here, but in debug-builds let's check that this actually worked.
185            debug_assert_eq!(res, 0);
186        }
187    }
188
189    #[cfg(target_os = "netbsd")]
190    pub fn set_name(name: &CStr) {
191        unsafe {
192            let res = libc::pthread_setname_np(
193                libc::pthread_self(),
194                c"%s".as_ptr(),
195                name.as_ptr() as *mut libc::c_void,
196            );
197            debug_assert_eq!(res, 0);
198        }
199    }
200
201    #[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto"))]
202    pub fn set_name(name: &CStr) {
203        weak!(
204            fn pthread_setname_np(
205                thread: libc::pthread_t,
206                name: *const libc::c_char,
207            ) -> libc::c_int;
208        );
209
210        if let Some(f) = pthread_setname_np.get() {
211            #[cfg(target_os = "nto")]
212            const THREAD_NAME_MAX: usize = libc::_NTO_THREAD_NAME_MAX as usize;
213            #[cfg(any(target_os = "solaris", target_os = "illumos"))]
214            const THREAD_NAME_MAX: usize = 32;
215
216            let name = truncate_cstr::<{ THREAD_NAME_MAX }>(name);
217            let res = unsafe { f(libc::pthread_self(), name.as_ptr()) };
218            debug_assert_eq!(res, 0);
219        }
220    }
221
222    #[cfg(target_os = "fuchsia")]
223    pub fn set_name(name: &CStr) {
224        use super::fuchsia::*;
225        unsafe {
226            zx_object_set_property(
227                zx_thread_self(),
228                ZX_PROP_NAME,
229                name.as_ptr() as *const libc::c_void,
230                name.to_bytes().len(),
231            );
232        }
233    }
234
235    #[cfg(target_os = "haiku")]
236    pub fn set_name(name: &CStr) {
237        unsafe {
238            let thread_self = libc::find_thread(ptr::null_mut());
239            let res = libc::rename_thread(thread_self, name.as_ptr());
240            // We have no good way of propagating errors here, but in debug-builds let's check that this actually worked.
241            debug_assert_eq!(res, libc::B_OK);
242        }
243    }
244
245    #[cfg(target_os = "vxworks")]
246    pub fn set_name(name: &CStr) {
247        let mut name = truncate_cstr::<{ (libc::VX_TASK_RENAME_LENGTH - 1) as usize }>(name);
248        let res = unsafe { libc::taskNameSet(libc::taskIdSelf(), name.as_mut_ptr()) };
249        debug_assert_eq!(res, libc::OK);
250    }
251
252    #[cfg(any(
253        target_env = "newlib",
254        target_os = "l4re",
255        target_os = "emscripten",
256        target_os = "redox",
257        target_os = "hurd",
258        target_os = "aix",
259    ))]
260    pub fn set_name(_name: &CStr) {
261        // Newlib and Emscripten have no way to set a thread name.
262    }
263
264    #[cfg(not(target_os = "espidf"))]
265    pub fn sleep(dur: Duration) {
266        let mut secs = dur.as_secs();
267        let mut nsecs = dur.subsec_nanos() as _;
268
269        // If we're awoken with a signal then the return value will be -1 and
270        // nanosleep will fill in `ts` with the remaining time.
271        unsafe {
272            while secs > 0 || nsecs > 0 {
273                let mut ts = libc::timespec {
274                    tv_sec: cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t,
275                    tv_nsec: nsecs,
276                };
277                secs -= ts.tv_sec as u64;
278                let ts_ptr = &raw mut ts;
279                if libc::nanosleep(ts_ptr, ts_ptr) == -1 {
280                    assert_eq!(os::errno(), libc::EINTR);
281                    secs += ts.tv_sec as u64;
282                    nsecs = ts.tv_nsec;
283                } else {
284                    nsecs = 0;
285                }
286            }
287        }
288    }
289
290    #[cfg(target_os = "espidf")]
291    pub fn sleep(dur: Duration) {
292        // ESP-IDF does not have `nanosleep`, so we use `usleep` instead.
293        // As per the documentation of `usleep`, it is expected to support
294        // sleep times as big as at least up to 1 second.
295        //
296        // ESP-IDF does support almost up to `u32::MAX`, but due to a potential integer overflow in its
297        // `usleep` implementation
298        // (https://github.com/espressif/esp-idf/blob/d7ca8b94c852052e3bc33292287ef4dd62c9eeb1/components/newlib/time.c#L210),
299        // we limit the sleep time to the maximum one that would not cause the underlying `usleep` implementation to overflow
300        // (`portTICK_PERIOD_MS` can be anything between 1 to 1000, and is 10 by default).
301        const MAX_MICROS: u32 = u32::MAX - 1_000_000 - 1;
302
303        // Add any nanoseconds smaller than a microsecond as an extra microsecond
304        // so as to comply with the `std::thread::sleep` contract which mandates
305        // implementations to sleep for _at least_ the provided `dur`.
306        // We can't overflow `micros` as it is a `u128`, while `Duration` is a pair of
307        // (`u64` secs, `u32` nanos), where the nanos are strictly smaller than 1 second
308        // (i.e. < 1_000_000_000)
309        let mut micros = dur.as_micros() + if dur.subsec_nanos() % 1_000 > 0 { 1 } else { 0 };
310
311        while micros > 0 {
312            let st = if micros > MAX_MICROS as u128 { MAX_MICROS } else { micros as u32 };
313            unsafe {
314                libc::usleep(st);
315            }
316
317            micros -= st as u128;
318        }
319    }
320
321    // Any unix that has clock_nanosleep
322    // If this list changes update the MIRI chock_nanosleep shim
323    #[cfg(any(
324        target_os = "freebsd",
325        target_os = "netbsd",
326        target_os = "linux",
327        target_os = "android",
328        target_os = "solaris",
329        target_os = "illumos",
330        target_os = "dragonfly",
331        target_os = "hurd",
332        target_os = "fuchsia",
333        target_os = "vxworks",
334    ))]
335    pub fn sleep_until(deadline: Instant) {
336        let Some(ts) = deadline.into_inner().into_timespec().to_timespec() else {
337            // The deadline is further in the future then can be passed to
338            // clock_nanosleep. We have to use Self::sleep instead. This might
339            // happen on 32 bit platforms, especially closer to 2038.
340            let now = Instant::now();
341            if let Some(delay) = deadline.checked_duration_since(now) {
342                Self::sleep(delay);
343            }
344            return;
345        };
346
347        unsafe {
348            // When we get interrupted (res = EINTR) call clock_nanosleep again
349            loop {
350                let res = libc::clock_nanosleep(
351                    super::time::Instant::CLOCK_ID,
352                    libc::TIMER_ABSTIME,
353                    &ts,
354                    core::ptr::null_mut(), // not required with TIMER_ABSTIME
355                );
356
357                if res == 0 {
358                    break;
359                } else {
360                    assert_eq!(
361                        res,
362                        libc::EINTR,
363                        "timespec is in range,
364                         clockid is valid and kernel should support it"
365                    );
366                }
367            }
368        }
369    }
370
371    // Any unix that does not have clock_nanosleep
372    #[cfg(not(any(
373        target_os = "freebsd",
374        target_os = "netbsd",
375        target_os = "linux",
376        target_os = "android",
377        target_os = "solaris",
378        target_os = "illumos",
379        target_os = "dragonfly",
380        target_os = "hurd",
381        target_os = "fuchsia",
382        target_os = "vxworks",
383    )))]
384    pub fn sleep_until(deadline: Instant) {
385        let now = Instant::now();
386        if let Some(delay) = deadline.checked_duration_since(now) {
387            Self::sleep(delay);
388        }
389    }
390
391    pub fn join(self) {
392        let id = self.into_id();
393        let ret = unsafe { libc::pthread_join(id, ptr::null_mut()) };
394        assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
395    }
396
397    pub fn id(&self) -> libc::pthread_t {
398        self.id
399    }
400
401    pub fn into_id(self) -> libc::pthread_t {
402        ManuallyDrop::new(self).id
403    }
404}
405
406impl Drop for Thread {
407    fn drop(&mut self) {
408        let ret = unsafe { libc::pthread_detach(self.id) };
409        debug_assert_eq!(ret, 0);
410    }
411}
412
413pub(crate) fn current_os_id() -> Option<u64> {
414    // Most Unix platforms have a way to query an integer ID of the current thread, all with
415    // slightly different spellings.
416    //
417    // The OS thread ID is used rather than `pthread_self` so as to match what will be displayed
418    // for process inspection (debuggers, trace, `top`, etc.).
419    cfg_select! {
420        // Most platforms have a function returning a `pid_t` or int, which is an `i32`.
421        any(target_os = "android", target_os = "linux") => {
422            use crate::sys::weak::syscall;
423
424            // `libc::gettid` is only available on glibc 2.30+, but the syscall is available
425            // since Linux 2.4.11.
426            syscall!(fn gettid() -> libc::pid_t;);
427
428            // SAFETY: FFI call with no preconditions.
429            let id: libc::pid_t = unsafe { gettid() };
430            Some(id as u64)
431        }
432        target_os = "nto" => {
433            // SAFETY: FFI call with no preconditions.
434            let id: libc::pid_t = unsafe { libc::gettid() };
435            Some(id as u64)
436        }
437        target_os = "openbsd" => {
438            // SAFETY: FFI call with no preconditions.
439            let id: libc::pid_t = unsafe { libc::getthrid() };
440            Some(id as u64)
441        }
442        target_os = "freebsd" => {
443            // SAFETY: FFI call with no preconditions.
444            let id: libc::c_int = unsafe { libc::pthread_getthreadid_np() };
445            Some(id as u64)
446        }
447        target_os = "netbsd" => {
448            // SAFETY: FFI call with no preconditions.
449            let id: libc::lwpid_t = unsafe { libc::_lwp_self() };
450            Some(id as u64)
451        }
452        any(target_os = "illumos", target_os = "solaris") => {
453            // On Illumos and Solaris, the `pthread_t` is the same as the OS thread ID.
454            // SAFETY: FFI call with no preconditions.
455            let id: libc::pthread_t = unsafe { libc::pthread_self() };
456            Some(id as u64)
457        }
458        target_vendor = "apple" => {
459            // Apple allows querying arbitrary thread IDs, `thread=NULL` queries the current thread.
460            let mut id = 0u64;
461            // SAFETY: `thread_id` is a valid pointer, no other preconditions.
462            let status: libc::c_int = unsafe { libc::pthread_threadid_np(0, &mut id) };
463            if status == 0 {
464                Some(id)
465            } else {
466                None
467            }
468        }
469        // Other platforms don't have an OS thread ID or don't have a way to access it.
470        _ => None,
471    }
472}
473
474#[cfg(any(
475    target_os = "linux",
476    target_os = "nto",
477    target_os = "solaris",
478    target_os = "illumos",
479    target_os = "vxworks",
480    target_os = "cygwin",
481    target_vendor = "apple",
482))]
483fn truncate_cstr<const MAX_WITH_NUL: usize>(cstr: &CStr) -> [libc::c_char; MAX_WITH_NUL] {
484    let mut result = [0; MAX_WITH_NUL];
485    for (src, dst) in cstr.to_bytes().iter().zip(&mut result[..MAX_WITH_NUL - 1]) {
486        *dst = *src as libc::c_char;
487    }
488    result
489}
490
491pub fn available_parallelism() -> io::Result<NonZero<usize>> {
492    cfg_select! {
493        any(
494            target_os = "android",
495            target_os = "emscripten",
496            target_os = "fuchsia",
497            target_os = "hurd",
498            target_os = "linux",
499            target_os = "aix",
500            target_vendor = "apple",
501            target_os = "cygwin",
502        ) => {
503            #[allow(unused_assignments)]
504            #[allow(unused_mut)]
505            let mut quota = usize::MAX;
506
507            #[cfg(any(target_os = "android", target_os = "linux"))]
508            {
509                quota = cgroups::quota().max(1);
510                let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
511                unsafe {
512                    if libc::sched_getaffinity(0, size_of::<libc::cpu_set_t>(), &mut set) == 0 {
513                        let count = libc::CPU_COUNT(&set) as usize;
514                        let count = count.min(quota);
515
516                        // According to sched_getaffinity's API it should always be non-zero, but
517                        // some old MIPS kernels were buggy and zero-initialized the mask if
518                        // none was explicitly set.
519                        // In that case we use the sysconf fallback.
520                        if let Some(count) = NonZero::new(count) {
521                            return Ok(count)
522                        }
523                    }
524                }
525            }
526            match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
527                -1 => Err(io::Error::last_os_error()),
528                0 => Err(io::Error::UNKNOWN_THREAD_COUNT),
529                cpus => {
530                    let count = cpus as usize;
531                    // Cover the unusual situation where we were able to get the quota but not the affinity mask
532                    let count = count.min(quota);
533                    Ok(unsafe { NonZero::new_unchecked(count) })
534                }
535            }
536        }
537        any(
538           target_os = "freebsd",
539           target_os = "dragonfly",
540           target_os = "openbsd",
541           target_os = "netbsd",
542        ) => {
543            use crate::ptr;
544
545            #[cfg(target_os = "freebsd")]
546            {
547                let mut set: libc::cpuset_t = unsafe { mem::zeroed() };
548                unsafe {
549                    if libc::cpuset_getaffinity(
550                        libc::CPU_LEVEL_WHICH,
551                        libc::CPU_WHICH_PID,
552                        -1,
553                        size_of::<libc::cpuset_t>(),
554                        &mut set,
555                    ) == 0 {
556                        let count = libc::CPU_COUNT(&set) as usize;
557                        if count > 0 {
558                            return Ok(NonZero::new_unchecked(count));
559                        }
560                    }
561                }
562            }
563
564            #[cfg(target_os = "netbsd")]
565            {
566                unsafe {
567                    let set = libc::_cpuset_create();
568                    if !set.is_null() {
569                        let mut count: usize = 0;
570                        if libc::pthread_getaffinity_np(libc::pthread_self(), libc::_cpuset_size(set), set) == 0 {
571                            for i in 0..libc::cpuid_t::MAX {
572                                match libc::_cpuset_isset(i, set) {
573                                    -1 => break,
574                                    0 => continue,
575                                    _ => count = count + 1,
576                                }
577                            }
578                        }
579                        libc::_cpuset_destroy(set);
580                        if let Some(count) = NonZero::new(count) {
581                            return Ok(count);
582                        }
583                    }
584                }
585            }
586
587            let mut cpus: libc::c_uint = 0;
588            let mut cpus_size = size_of_val(&cpus);
589
590            unsafe {
591                cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint;
592            }
593
594            // Fallback approach in case of errors or no hardware threads.
595            if cpus < 1 {
596                let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
597                let res = unsafe {
598                    libc::sysctl(
599                        mib.as_mut_ptr(),
600                        2,
601                        (&raw mut cpus) as *mut _,
602                        (&raw mut cpus_size) as *mut _,
603                        ptr::null_mut(),
604                        0,
605                    )
606                };
607
608                // Handle errors if any.
609                if res == -1 {
610                    return Err(io::Error::last_os_error());
611                } else if cpus == 0 {
612                    return Err(io::Error::UNKNOWN_THREAD_COUNT);
613                }
614            }
615
616            Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
617        }
618        target_os = "nto" => {
619            unsafe {
620                use libc::_syspage_ptr;
621                if _syspage_ptr.is_null() {
622                    Err(io::const_error!(io::ErrorKind::NotFound, "no syspage available"))
623                } else {
624                    let cpus = (*_syspage_ptr).num_cpu;
625                    NonZero::new(cpus as usize)
626                        .ok_or(io::Error::UNKNOWN_THREAD_COUNT)
627                }
628            }
629        }
630        any(target_os = "solaris", target_os = "illumos") => {
631            let mut cpus = 0u32;
632            if unsafe { libc::pset_info(libc::PS_MYID, core::ptr::null_mut(), &mut cpus, core::ptr::null_mut()) } != 0 {
633                return Err(io::Error::UNKNOWN_THREAD_COUNT);
634            }
635            Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
636        }
637        target_os = "haiku" => {
638            // system_info cpu_count field gets the static data set at boot time with `smp_set_num_cpus`
639            // `get_system_info` calls then `smp_get_num_cpus`
640            unsafe {
641                let mut sinfo: libc::system_info = crate::mem::zeroed();
642                let res = libc::get_system_info(&mut sinfo);
643
644                if res != libc::B_OK {
645                    return Err(io::Error::UNKNOWN_THREAD_COUNT);
646                }
647
648                Ok(NonZero::new_unchecked(sinfo.cpu_count as usize))
649            }
650        }
651        target_os = "vxworks" => {
652            // Note: there is also `vxCpuConfiguredGet`, closer to _SC_NPROCESSORS_CONF
653            // expectations than the actual cores availability.
654            unsafe extern "C" {
655                fn vxCpuEnabledGet() -> libc::cpuset_t;
656            }
657
658            // SAFETY: `vxCpuEnabledGet` always fetches a mask with at least one bit set
659            unsafe{
660                let set = vxCpuEnabledGet();
661                Ok(NonZero::new_unchecked(set.count_ones() as usize))
662            }
663        }
664        _ => {
665            // FIXME: implement on Redox, l4re
666            Err(io::const_error!(io::ErrorKind::Unsupported, "getting the number of hardware threads is not supported on the target platform"))
667        }
668    }
669}
670
671#[cfg(any(target_os = "android", target_os = "linux"))]
672mod cgroups {
673    //! Currently not covered
674    //! * cgroup v2 in non-standard mountpoints
675    //! * paths containing control characters or spaces, since those would be escaped in procfs
676    //!   output and we don't unescape
677
678    use crate::borrow::Cow;
679    use crate::ffi::OsString;
680    use crate::fs::{File, exists};
681    use crate::io::{BufRead, Read};
682    use crate::os::unix::ffi::OsStringExt;
683    use crate::path::{Path, PathBuf};
684    use crate::str::from_utf8;
685
686    #[derive(PartialEq)]
687    enum Cgroup {
688        V1,
689        V2,
690    }
691
692    /// Returns cgroup CPU quota in core-equivalents, rounded down or usize::MAX if the quota cannot
693    /// be determined or is not set.
694    pub(super) fn quota() -> usize {
695        let mut quota = usize::MAX;
696        if cfg!(miri) {
697            // Attempting to open a file fails under default flags due to isolation.
698            // And Miri does not have parallelism anyway.
699            return quota;
700        }
701
702        let _: Option<()> = try {
703            let mut buf = Vec::with_capacity(128);
704            // find our place in the cgroup hierarchy
705            File::open("/proc/self/cgroup").ok()?.read_to_end(&mut buf).ok()?;
706            let (cgroup_path, version) =
707                buf.split(|&c| c == b'\n').fold(None, |previous, line| {
708                    let mut fields = line.splitn(3, |&c| c == b':');
709                    // 2nd field is a list of controllers for v1 or empty for v2
710                    let version = match fields.nth(1) {
711                        Some(b"") => Cgroup::V2,
712                        Some(controllers)
713                            if from_utf8(controllers)
714                                .is_ok_and(|c| c.split(',').any(|c| c == "cpu")) =>
715                        {
716                            Cgroup::V1
717                        }
718                        _ => return previous,
719                    };
720
721                    // already-found v1 trumps v2 since it explicitly specifies its controllers
722                    if previous.is_some() && version == Cgroup::V2 {
723                        return previous;
724                    }
725
726                    let path = fields.last()?;
727                    // skip leading slash
728                    Some((path[1..].to_owned(), version))
729                })?;
730            let cgroup_path = PathBuf::from(OsString::from_vec(cgroup_path));
731
732            quota = match version {
733                Cgroup::V1 => quota_v1(cgroup_path),
734                Cgroup::V2 => quota_v2(cgroup_path),
735            };
736        };
737
738        quota
739    }
740
741    fn quota_v2(group_path: PathBuf) -> usize {
742        let mut quota = usize::MAX;
743
744        let mut path = PathBuf::with_capacity(128);
745        let mut read_buf = String::with_capacity(20);
746
747        // standard mount location defined in file-hierarchy(7) manpage
748        let cgroup_mount = "/sys/fs/cgroup";
749
750        path.push(cgroup_mount);
751        path.push(&group_path);
752
753        path.push("cgroup.controllers");
754
755        // skip if we're not looking at cgroup2
756        if matches!(exists(&path), Err(_) | Ok(false)) {
757            return usize::MAX;
758        };
759
760        path.pop();
761
762        let _: Option<()> = try {
763            while path.starts_with(cgroup_mount) {
764                path.push("cpu.max");
765
766                read_buf.clear();
767
768                if File::open(&path).and_then(|mut f| f.read_to_string(&mut read_buf)).is_ok() {
769                    let raw_quota = read_buf.lines().next()?;
770                    let mut raw_quota = raw_quota.split(' ');
771                    let limit = raw_quota.next()?;
772                    let period = raw_quota.next()?;
773                    match (limit.parse::<usize>(), period.parse::<usize>()) {
774                        (Ok(limit), Ok(period)) if period > 0 => {
775                            quota = quota.min(limit / period);
776                        }
777                        _ => {}
778                    }
779                }
780
781                path.pop(); // pop filename
782                path.pop(); // pop dir
783            }
784        };
785
786        quota
787    }
788
789    fn quota_v1(group_path: PathBuf) -> usize {
790        let mut quota = usize::MAX;
791        let mut path = PathBuf::with_capacity(128);
792        let mut read_buf = String::with_capacity(20);
793
794        // Hardcode commonly used locations mentioned in the cgroups(7) manpage
795        // if that doesn't work scan mountinfo and adjust `group_path` for bind-mounts
796        let mounts: &[fn(&Path) -> Option<(_, &Path)>] = &[
797            |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu"), p)),
798            |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu,cpuacct"), p)),
799            // this can be expensive on systems with tons of mountpoints
800            // but we only get to this point when /proc/self/cgroups explicitly indicated
801            // this process belongs to a cpu-controller cgroup v1 and the defaults didn't work
802            find_mountpoint,
803        ];
804
805        for mount in mounts {
806            let Some((mount, group_path)) = mount(&group_path) else { continue };
807
808            path.clear();
809            path.push(mount.as_ref());
810            path.push(&group_path);
811
812            // skip if we guessed the mount incorrectly
813            if matches!(exists(&path), Err(_) | Ok(false)) {
814                continue;
815            }
816
817            while path.starts_with(mount.as_ref()) {
818                let mut parse_file = |name| {
819                    path.push(name);
820                    read_buf.clear();
821
822                    let f = File::open(&path);
823                    path.pop(); // restore buffer before any early returns
824                    f.ok()?.read_to_string(&mut read_buf).ok()?;
825                    let parsed = read_buf.trim().parse::<usize>().ok()?;
826
827                    Some(parsed)
828                };
829
830                let limit = parse_file("cpu.cfs_quota_us");
831                let period = parse_file("cpu.cfs_period_us");
832
833                match (limit, period) {
834                    (Some(limit), Some(period)) if period > 0 => quota = quota.min(limit / period),
835                    _ => {}
836                }
837
838                path.pop();
839            }
840
841            // we passed the try_exists above so we should have traversed the correct hierarchy
842            // when reaching this line
843            break;
844        }
845
846        quota
847    }
848
849    /// Scan mountinfo for cgroup v1 mountpoint with a cpu controller
850    ///
851    /// If the cgroupfs is a bind mount then `group_path` is adjusted to skip
852    /// over the already-included prefix
853    fn find_mountpoint(group_path: &Path) -> Option<(Cow<'static, str>, &Path)> {
854        let mut reader = File::open_buffered("/proc/self/mountinfo").ok()?;
855        let mut line = String::with_capacity(256);
856        loop {
857            line.clear();
858            if reader.read_line(&mut line).ok()? == 0 {
859                break;
860            }
861
862            let line = line.trim();
863            let mut items = line.split(' ');
864
865            let sub_path = items.nth(3)?;
866            let mount_point = items.next()?;
867            let mount_opts = items.next_back()?;
868            let filesystem_type = items.nth_back(1)?;
869
870            if filesystem_type != "cgroup" || !mount_opts.split(',').any(|opt| opt == "cpu") {
871                // not a cgroup / not a cpu-controller
872                continue;
873            }
874
875            let sub_path = Path::new(sub_path).strip_prefix("/").ok()?;
876
877            if !group_path.starts_with(sub_path) {
878                // this is a bind-mount and the bound subdirectory
879                // does not contain the cgroup this process belongs to
880                continue;
881            }
882
883            let trimmed_group_path = group_path.strip_prefix(sub_path).ok()?;
884
885            return Some((Cow::Owned(mount_point.to_owned()), trimmed_group_path));
886        }
887
888        None
889    }
890}
891
892// glibc >= 2.15 has a __pthread_get_minstack() function that returns
893// PTHREAD_STACK_MIN plus bytes needed for thread-local storage.
894// We need that information to avoid blowing up when a small stack
895// is created in an application with big thread-local storage requirements.
896// See #6233 for rationale and details.
897#[cfg(all(target_os = "linux", target_env = "gnu"))]
898unsafe fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
899    // We use dlsym to avoid an ELF version dependency on GLIBC_PRIVATE. (#23628)
900    // We shouldn't really be using such an internal symbol, but there's currently
901    // no other way to account for the TLS size.
902    dlsym!(
903        fn __pthread_get_minstack(attr: *const libc::pthread_attr_t) -> libc::size_t;
904    );
905
906    match __pthread_get_minstack.get() {
907        None => libc::PTHREAD_STACK_MIN,
908        Some(f) => unsafe { f(attr) },
909    }
910}
911
912// No point in looking up __pthread_get_minstack() on non-glibc platforms.
913#[cfg(all(
914    not(all(target_os = "linux", target_env = "gnu")),
915    not(any(target_os = "netbsd", target_os = "nuttx"))
916))]
917unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
918    libc::PTHREAD_STACK_MIN
919}
920
921#[cfg(any(target_os = "netbsd", target_os = "nuttx"))]
922unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
923    static STACK: crate::sync::OnceLock<usize> = crate::sync::OnceLock::new();
924
925    *STACK.get_or_init(|| {
926        let mut stack = unsafe { libc::sysconf(libc::_SC_THREAD_STACK_MIN) };
927        if stack < 0 {
928            stack = 2048; // just a guess
929        }
930
931        stack as usize
932    })
933}