Skip to main content

std/sys/thread/
unix.rs

1#[cfg(not(any(
2    target_env = "newlib",
3    target_os = "l4re",
4    target_os = "emscripten",
5    target_os = "redox",
6    target_os = "hurd",
7    target_os = "aix",
8    target_os = "wasi",
9)))]
10use crate::ffi::CStr;
11use crate::mem::{self, DropGuard, ManuallyDrop};
12use crate::num::NonZero;
13use crate::pin::pin;
14use crate::sys::helpers::COpaque;
15#[cfg(all(target_os = "linux", target_env = "gnu"))]
16use crate::sys::weak::dlsym;
17#[cfg(any(
18    target_os = "solaris",
19    target_os = "illumos",
20    target_os = "nto",
21    target_os = "qnx",
22))]
23use crate::sys::weak::weak;
24use crate::thread::ThreadInit;
25use crate::time::Duration;
26use crate::{cmp, io, ptr, sys};
27#[cfg(not(any(
28    target_os = "l4re",
29    target_os = "vxworks",
30    target_os = "espidf",
31    target_os = "nuttx"
32)))]
33pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
34#[cfg(target_os = "l4re")]
35pub const DEFAULT_MIN_STACK_SIZE: usize = 1024 * 1024;
36#[cfg(target_os = "vxworks")]
37pub const DEFAULT_MIN_STACK_SIZE: usize = 256 * 1024;
38#[cfg(any(target_os = "espidf", target_os = "nuttx"))]
39pub const DEFAULT_MIN_STACK_SIZE: usize = 0; // 0 indicates that the stack size configured in the ESP-IDF/NuttX menuconfig system should be used
40
41pub struct Thread {
42    id: libc::pthread_t,
43}
44
45// Some platforms may have pthread_t as a pointer in which case we still want
46// a thread to be Send/Sync
47unsafe impl Send for Thread {}
48unsafe impl Sync for Thread {}
49
50impl Thread {
51    // unsafe: see thread::Builder::spawn_unchecked for safety requirements
52    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
53    pub unsafe fn new(stack: usize, init: Box<ThreadInit>) -> io::Result<Thread> {
54        let data = init;
55        let attr = {
    super let mut pinned: ::core::pin::PinMacroHelper<_> =
        ::core::pin::PinMacroHelper {
            value: COpaque::<libc::pthread_attr_t>::uninit(),
        };
    unsafe { ::core::pin::pin_new_unchecked_in_helper(&mut pinned) }
}pin!(COpaque::<libc::pthread_attr_t>::uninit());
56        // FIXME(pin-ergonomics): remove the next line.
57        let attr = attr.into_ref();
58
59        {
    match (&libc::pthread_attr_init(attr.get()), &0) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(libc::pthread_attr_init(attr.get()), 0);
60        let attr =
61            DropGuard::new(attr, |attr| {
    match (&libc::pthread_attr_destroy(attr.get()), &0) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
}assert_eq!(libc::pthread_attr_destroy(attr.get()), 0));
62
63        #[cfg(any(target_os = "espidf", target_os = "nuttx"))]
64        if stack > 0 {
65            // Only set the stack if a non-zero value is passed
66            // 0 is used as an indication that the default stack size configured in the ESP-IDF/NuttX menuconfig system should be used
67            assert_eq!(
68                libc::pthread_attr_setstacksize(
69                    attr.get(),
70                    cmp::max(stack, min_stack_size(attr.as_ptr()))
71                ),
72                0
73            );
74        }
75
76        #[cfg(not(any(target_os = "espidf", target_os = "nuttx")))]
77        {
78            let stack_size = cmp::max(stack, min_stack_size(attr.get()));
79
80            match libc::pthread_attr_setstacksize(attr.get(), stack_size) {
81                0 => {}
82                n => {
83                    {
    match (&n, &libc::EINVAL) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(n, libc::EINVAL);
84                    // EINVAL means |stack_size| is either too small or not a
85                    // multiple of the system page size. Because it's definitely
86                    // >= PTHREAD_STACK_MIN, it must be an alignment issue.
87                    // Round up to the nearest page and try again.
88                    let page_size = sys::pal::conf::page_size();
89                    let stack_size =
90                        (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1);
91
92                    // Some libc implementations, e.g. musl, place an upper bound
93                    // on the stack size, in which case we can only gracefully return
94                    // an error here.
95                    if libc::pthread_attr_setstacksize(attr.get(), stack_size) != 0 {
96                        return Err(::core::hint::must_use(::core::io::Error::from_static_message(const {
                &::core::io::SimpleMessage {
                        kind: io::ErrorKind::InvalidInput,
                        message: "invalid stack size",
                    }
            }))io::const_error!(
97                            io::ErrorKind::InvalidInput,
98                            "invalid stack size"
99                        ));
100                    }
101                }
102            };
103        }
104
105        let data = Box::into_raw(data);
106        let mut native: libc::pthread_t = mem::zeroed();
107        let ret = libc::pthread_create(&mut native, attr.get(), thread_start, data as *mut _);
108        return if ret == 0 {
109            Ok(Thread { id: native })
110        } else {
111            // The thread failed to start and as a result `data` was not consumed.
112            // Therefore, it is safe to reconstruct the box so that it gets deallocated.
113            drop(Box::from_raw(data));
114            Err(io::Error::from_raw_os_error(ret))
115        };
116
117        extern "C" fn thread_start(data: *mut libc::c_void) -> *mut libc::c_void {
118            unsafe {
119                // SAFETY: we are simply recreating the box that was leaked earlier.
120                let init = Box::from_raw(data as *mut ThreadInit);
121                let rust_start = init.init();
122
123                // Now that the thread information is set, set up our stack
124                // overflow handler.
125                let _handler = sys::stack_overflow::Handler::new();
126
127                rust_start();
128            }
129            ptr::null_mut()
130        }
131    }
132
133    pub fn join(self) {
134        let id = self.into_id();
135        let ret = unsafe { libc::pthread_join(id, ptr::null_mut()) };
136        if !(ret == 0) {
    {
        ::core::panicking::panic_fmt(format_args!("failed to join thread: {0}",
                io::Error::from_raw_os_error(ret)));
    }
};assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
137    }
138
139    #[cfg(not(target_os = "wasi"))]
140    pub fn id(&self) -> libc::pthread_t {
141        self.id
142    }
143
144    pub fn into_id(self) -> libc::pthread_t {
145        ManuallyDrop::new(self).id
146    }
147}
148
149impl Drop for Thread {
150    fn drop(&mut self) {
151        let ret = unsafe { libc::pthread_detach(self.id) };
152        if true {
    {
        match (&ret, &0) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(ret, 0);
153    }
154}
155
156pub fn available_parallelism() -> io::Result<NonZero<usize>> {
157    cfg_select! {
158        any(
159            target_os = "android",
160            target_os = "emscripten",
161            target_os = "fuchsia",
162            target_os = "hurd",
163            target_os = "linux",
164            target_os = "aix",
165            target_vendor = "apple",
166            target_os = "cygwin",
167            target_os = "redox",
168            target_os = "wasi",
169        ) => {
170            #[allow(unused_assignments)]
171            #[allow(unused_mut)]
172            let mut quota = usize::MAX;
173
174            #[cfg(any(target_os = "android", target_os = "linux"))]
175            {
176                quota = cgroups::quota().max(1);
177                let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
178                unsafe {
179                    if libc::sched_getaffinity(0, size_of::<libc::cpu_set_t>(), &mut set) == 0 {
180                        let count = libc::CPU_COUNT(&set) as usize;
181                        let count = count.min(quota);
182
183                        // According to sched_getaffinity's API it should always be non-zero, but
184                        // some old MIPS kernels were buggy and zero-initialized the mask if
185                        // none was explicitly set.
186                        // In that case we use the sysconf fallback.
187                        if let Some(count) = NonZero::new(count) {
188                            return Ok(count);
189                        }
190                    }
191                }
192            }
193            match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
194                -1 => Err(io::Error::last_os_error()),
195                0 => Err(io::Error::UNKNOWN_THREAD_COUNT),
196                cpus => {
197                    let count = cpus as usize;
198                    // Cover the unusual situation where we were able to get the quota but not the affinity mask
199                    let count = count.min(quota);
200                    Ok(unsafe { NonZero::new_unchecked(count) })
201                }
202            }
203        }
204        any(
205            target_os = "freebsd",
206            target_os = "dragonfly",
207            target_os = "openbsd",
208            target_os = "netbsd",
209        ) => {
210            use crate::ptr;
211
212            #[cfg(target_os = "freebsd")]
213            {
214                let mut set: libc::cpuset_t = unsafe { mem::zeroed() };
215                unsafe {
216                    if libc::cpuset_getaffinity(
217                        libc::CPU_LEVEL_WHICH,
218                        libc::CPU_WHICH_PID,
219                        -1,
220                        size_of::<libc::cpuset_t>(),
221                        &mut set,
222                    ) == 0
223                    {
224                        let count = libc::CPU_COUNT(&set) as usize;
225                        if count > 0 {
226                            return Ok(NonZero::new_unchecked(count));
227                        }
228                    }
229                }
230            }
231
232            #[cfg(target_os = "netbsd")]
233            {
234                unsafe {
235                    let set = libc::_cpuset_create();
236                    if !set.is_null() {
237                        let mut count: usize = 0;
238                        if libc::pthread_getaffinity_np(
239                            libc::pthread_self(),
240                            libc::_cpuset_size(set),
241                            set,
242                        ) == 0
243                        {
244                            for i in 0..libc::cpuid_t::MAX {
245                                match libc::_cpuset_isset(i, set) {
246                                    -1 => break,
247                                    0 => continue,
248                                    _ => count = count + 1,
249                                }
250                            }
251                        }
252                        libc::_cpuset_destroy(set);
253                        if let Some(count) = NonZero::new(count) {
254                            return Ok(count);
255                        }
256                    }
257                }
258            }
259
260            let mut cpus: libc::c_uint = 0;
261            let mut cpus_size = size_of_val(&cpus);
262
263            unsafe {
264                cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint;
265            }
266
267            // Fallback approach in case of errors or no hardware threads.
268            if cpus < 1 {
269                let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
270                let res = unsafe {
271                    libc::sysctl(
272                        mib.as_mut_ptr(),
273                        2,
274                        (&raw mut cpus) as *mut _,
275                        (&raw mut cpus_size) as *mut _,
276                        ptr::null_mut(),
277                        0,
278                    )
279                };
280
281                // Handle errors if any.
282                if res == -1 {
283                    return Err(io::Error::last_os_error());
284                } else if cpus == 0 {
285                    return Err(io::Error::UNKNOWN_THREAD_COUNT);
286                }
287            }
288
289            Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
290        }
291        any(target_os = "nto", target_os = "qnx") => unsafe {
292            use libc::_syspage_ptr;
293            if _syspage_ptr.is_null() {
294                Err(io::const_error!(io::ErrorKind::NotFound, "no syspage available"))
295            } else {
296                let cpus = (*_syspage_ptr).num_cpu;
297                NonZero::new(cpus as usize).ok_or(io::Error::UNKNOWN_THREAD_COUNT)
298            }
299        },
300        any(target_os = "solaris", target_os = "illumos") => {
301            let mut cpus = 0u32;
302            if unsafe {
303                libc::pset_info(
304                    libc::PS_MYID,
305                    core::ptr::null_mut(),
306                    &mut cpus,
307                    core::ptr::null_mut(),
308                )
309            } != 0
310            {
311                return Err(io::Error::UNKNOWN_THREAD_COUNT);
312            }
313            Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
314        }
315        target_os = "haiku" => {
316            // system_info cpu_count field gets the static data set at boot time with `smp_set_num_cpus`
317            // `get_system_info` calls then `smp_get_num_cpus`
318            unsafe {
319                let mut sinfo: libc::system_info = crate::mem::zeroed();
320                let res = libc::get_system_info(&mut sinfo);
321
322                if res != libc::B_OK {
323                    return Err(io::Error::UNKNOWN_THREAD_COUNT);
324                }
325
326                Ok(NonZero::new_unchecked(sinfo.cpu_count as usize))
327            }
328        }
329        target_os = "vxworks" => {
330            // Note: there is also `vxCpuConfiguredGet`, closer to _SC_NPROCESSORS_CONF
331            // expectations than the actual cores availability.
332
333            // SAFETY: `vxCpuEnabledGet` always fetches a mask with at least one bit set
334            unsafe {
335                let set = libc::vxCpuEnabledGet();
336                Ok(NonZero::new_unchecked(set.count_ones() as usize))
337            }
338        }
339        _ => {
340            // FIXME: implement on l4re
341            Err(io::const_error!(
342                io::ErrorKind::Unsupported,
343                "getting the number of hardware threads is not supported on the target platform"
344            ))
345        }
346    }
347}
348
349pub fn current_os_id() -> Option<u64> {
350    // Most Unix platforms have a way to query an integer ID of the current thread, all with
351    // slightly different spellings.
352    //
353    // The OS thread ID is used rather than `pthread_self` so as to match what will be displayed
354    // for process inspection (debuggers, trace, `top`, etc.).
355    cfg_select! {
356        // Most platforms have a function returning a `pid_t` or int, which is an `i32`.
357        any(target_os = "android", target_os = "linux") => {
358            use crate::sys::pal::weak::syscall;
359
360            // `libc::gettid` is only available on glibc 2.30+, but the syscall is available
361            // since Linux 2.4.11.
362            unsafe fn gettid() -> libc::pid_t {
    let ref gettid: ExternWeak<unsafe extern "C" fn() -> libc::pid_t> =
        {
            unsafe extern "C" {
                #[linkage = "extern_weak"]
                static gettid: Option<unsafe extern "C" fn() -> libc::pid_t>;
            }

            #[allow(unused_unsafe)]
            ExternWeak::new(unsafe { gettid })
        };
    if let Some(fun) = gettid.get() {
        unsafe { fun() }
    } else { unsafe { libc::syscall(libc::SYS_gettid) as libc::pid_t } }
}syscall!(
363                fn gettid() -> libc::pid_t;
364            );
365
366            // SAFETY: FFI call with no preconditions.
367            let id: libc::pid_t = unsafe { gettid() };
368            Some(id as u64)
369        }
370        any(target_os = "nto", target_os = "qnx") => {
371            // SAFETY: FFI call with no preconditions.
372            let id: libc::pid_t = unsafe { libc::gettid() };
373            Some(id as u64)
374        }
375        target_os = "openbsd" => {
376            // SAFETY: FFI call with no preconditions.
377            let id: libc::pid_t = unsafe { libc::getthrid() };
378            Some(id as u64)
379        }
380        target_os = "freebsd" => {
381            // SAFETY: FFI call with no preconditions.
382            let id: libc::c_int = unsafe { libc::pthread_getthreadid_np() };
383            Some(id as u64)
384        }
385        target_os = "netbsd" => {
386            // SAFETY: FFI call with no preconditions.
387            let id: libc::lwpid_t = unsafe { libc::_lwp_self() };
388            Some(id as u64)
389        }
390        any(target_os = "illumos", target_os = "solaris") => {
391            // On Illumos and Solaris, the `pthread_t` is the same as the OS thread ID.
392            // SAFETY: FFI call with no preconditions.
393            let id: libc::pthread_t = unsafe { libc::pthread_self() };
394            Some(id as u64)
395        }
396        target_vendor = "apple" => {
397            // Apple allows querying arbitrary thread IDs, `thread=NULL` queries the current thread.
398            let mut id = 0u64;
399            // SAFETY: `thread_id` is a valid pointer, no other preconditions.
400            let status: libc::c_int = unsafe { libc::pthread_threadid_np(0, &mut id) };
401            if status == 0 { Some(id) } else { None }
402        }
403        // Other platforms don't have an OS thread ID or don't have a way to access it.
404        _ => None,
405    }
406}
407
408#[cfg(any(
409    target_os = "linux",
410    target_os = "nto",
411    target_os = "qnx",
412    target_os = "solaris",
413    target_os = "illumos",
414    target_os = "vxworks",
415    target_os = "cygwin",
416    target_vendor = "apple",
417    target_os = "netbsd",
418))]
419fn truncate_cstr<const MAX_WITH_NUL: usize>(cstr: &CStr) -> [libc::c_char; MAX_WITH_NUL] {
420    let mut result = [0; MAX_WITH_NUL];
421    for (src, dst) in cstr.to_bytes().iter().zip(&mut result[..MAX_WITH_NUL - 1]) {
422        *dst = *src as libc::c_char;
423    }
424    result
425}
426
427#[cfg(target_os = "android")]
428pub fn set_name(name: &CStr) {
429    const PR_SET_NAME: libc::c_int = 15;
430    unsafe {
431        let res = libc::prctl(
432            PR_SET_NAME,
433            name.as_ptr(),
434            0 as libc::c_ulong,
435            0 as libc::c_ulong,
436            0 as libc::c_ulong,
437        );
438        // We have no good way of propagating errors here, but in debug-builds let's check that this actually worked.
439        debug_assert_eq!(res, 0);
440    }
441}
442
443#[cfg(any(
444    target_os = "linux",
445    target_os = "freebsd",
446    target_os = "dragonfly",
447    target_os = "nuttx",
448    target_os = "cygwin"
449))]
450pub fn set_name(name: &CStr) {
451    unsafe {
452        cfg_select! {
453            any(target_os = "linux", target_os = "cygwin") => {
454                // Linux and Cygwin limits the allowed length of the name.
455                const TASK_COMM_LEN: usize = 16;
456                let name = truncate_cstr::<{ TASK_COMM_LEN }>(name);
457            }
458            _ => {
459                // FreeBSD, DragonFly BSD and NuttX do not enforce length limits.
460            }
461        };
462        // Available since glibc 2.12, musl 1.1.16, and uClibc 1.0.20 for Linux,
463        // FreeBSD 12.2 and 13.0, and DragonFly BSD 6.0.
464        let res = libc::pthread_setname_np(libc::pthread_self(), name.as_ptr());
465        // We have no good way of propagating errors here, but in debug-builds let's check that this actually worked.
466        if true {
    {
        match (&res, &0) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(res, 0);
467    }
468}
469
470#[cfg(target_os = "openbsd")]
471pub fn set_name(name: &CStr) {
472    unsafe {
473        libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
474    }
475}
476
477#[cfg(target_vendor = "apple")]
478pub fn set_name(name: &CStr) {
479    unsafe {
480        let name = truncate_cstr::<{ libc::MAXTHREADNAMESIZE }>(name);
481        let res = libc::pthread_setname_np(name.as_ptr());
482        // We have no good way of propagating errors here, but in debug-builds let's check that this actually worked.
483        debug_assert_eq!(res, 0);
484    }
485}
486
487#[cfg(target_os = "netbsd")]
488pub fn set_name(name: &CStr) {
489    // See https://github.com/NetBSD/src/blob/8d40872b4c550a802379f3b9c22a40212d5e149d/lib/libpthread/pthread.h#L281
490    // FIXME: move to libc.
491    const PTHREAD_MAX_NAMELEN_NP: usize = 32;
492
493    unsafe {
494        let name = truncate_cstr::<{ PTHREAD_MAX_NAMELEN_NP }>(name);
495        let res = libc::pthread_setname_np(
496            libc::pthread_self(),
497            c"%s".as_ptr(),
498            name.as_ptr() as *mut libc::c_void,
499        );
500        debug_assert_eq!(res, 0);
501    }
502}
503
504#[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto", target_os = "qnx"))]
505pub fn set_name(name: &CStr) {
506    weak!(
507        fn pthread_setname_np(thread: libc::pthread_t, name: *const libc::c_char) -> libc::c_int;
508    );
509
510    if let Some(f) = pthread_setname_np.get() {
511        #[cfg(any(target_os = "nto", target_os = "qnx"))]
512        const THREAD_NAME_MAX: usize = libc::_NTO_THREAD_NAME_MAX as usize;
513        #[cfg(any(target_os = "solaris", target_os = "illumos"))]
514        const THREAD_NAME_MAX: usize = 32;
515
516        let name = truncate_cstr::<{ THREAD_NAME_MAX }>(name);
517        let res = unsafe { f(libc::pthread_self(), name.as_ptr()) };
518        debug_assert_eq!(res, 0);
519    }
520}
521
522#[cfg(target_os = "fuchsia")]
523pub fn set_name(name: &CStr) {
524    use crate::sys::pal::fuchsia::*;
525    unsafe {
526        zx_object_set_property(
527            zx_thread_self(),
528            ZX_PROP_NAME,
529            name.as_ptr() as *const libc::c_void,
530            name.to_bytes().len(),
531        );
532    }
533}
534
535#[cfg(target_os = "haiku")]
536pub fn set_name(name: &CStr) {
537    unsafe {
538        let thread_self = libc::find_thread(ptr::null_mut());
539        let res = libc::rename_thread(thread_self, name.as_ptr());
540        // We have no good way of propagating errors here, but in debug-builds let's check that this actually worked.
541        debug_assert_eq!(res, libc::B_OK);
542    }
543}
544
545#[cfg(target_os = "vxworks")]
546pub fn set_name(name: &CStr) {
547    let mut name = truncate_cstr::<{ (libc::VX_TASK_RENAME_LENGTH - 1) as usize }>(name);
548    let res = unsafe { libc::taskNameSet(libc::taskIdSelf(), name.as_mut_ptr()) };
549    debug_assert_eq!(res, libc::OK);
550}
551
552#[cfg(not(target_os = "espidf"))]
553pub fn sleep(dur: Duration) {
554    cfg_select! {
555        // Any unix that has clock_nanosleep
556        // If this list changes update the MIRI chock_nanosleep shim
557        any(
558            target_os = "freebsd",
559            target_os = "netbsd",
560            target_os = "linux",
561            target_os = "android",
562            target_os = "solaris",
563            target_os = "illumos",
564            target_os = "dragonfly",
565            target_os = "hurd",
566            target_os = "vxworks",
567            target_os = "wasi",
568        ) => {
569            // POSIX specifies that `nanosleep` uses CLOCK_REALTIME, but is not
570            // affected by clock adjustments. The timing of `sleep` however should
571            // be tied to `Instant` where possible. Thus, we use `clock_nanosleep`
572            // with a relative time interval instead, which allows explicitly
573            // specifying the clock.
574            //
575            // In practice, most systems (like e.g. Linux) actually use
576            // CLOCK_MONOTONIC for `nanosleep` anyway, but others like FreeBSD don't
577            // so it's better to be safe.
578            //
579            // wasi-libc prior to WebAssembly/wasi-libc#696 has a broken implementation
580            // of `nanosleep` which used `CLOCK_REALTIME` even though it is unsupported
581            // on WASIp2. Using `clock_nanosleep` directly bypasses the issue.
582            unsafe fn nanosleep(
583                rqtp: *const libc::timespec,
584                rmtp: *mut libc::timespec,
585            ) -> libc::c_int {
586                unsafe { libc::clock_nanosleep(crate::sys::time::Instant::CLOCK_ID, 0, rqtp, rmtp) }
587            }
588        }
589        _ => {
590            unsafe fn nanosleep(
591                rqtp: *const libc::timespec,
592                rmtp: *mut libc::timespec,
593            ) -> libc::c_int {
594                let r = unsafe { libc::nanosleep(rqtp, rmtp) };
595                // `clock_nanosleep` returns the error number directly, so mimic
596                // that behaviour to make the shared code below simpler.
597                if r == 0 { 0 } else { sys::io::errno() }
598            }
599        }
600    }
601
602    let mut secs = dur.as_secs();
603    let mut nsecs = dur.subsec_nanos() as _;
604
605    // If we're awoken with a signal then the return value will be -1 and
606    // nanosleep will fill in `ts` with the remaining time.
607    unsafe {
608        while secs > 0 || nsecs > 0 {
609            let mut ts = libc::timespec::default();
610            ts.tv_sec = cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t;
611            ts.tv_nsec = nsecs;
612
613            secs -= ts.tv_sec as u64;
614            let ts_ptr = &raw mut ts;
615            let r = nanosleep(ts_ptr, ts_ptr);
616            if r != 0 {
617                {
    match (&r, &libc::EINTR) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(r, libc::EINTR);
618                secs += ts.tv_sec as u64;
619                nsecs = ts.tv_nsec;
620            } else {
621                nsecs = 0;
622            }
623        }
624    }
625}
626
627#[cfg(target_os = "espidf")]
628pub fn sleep(dur: Duration) {
629    // ESP-IDF does not have `nanosleep`, so we use `usleep` instead.
630    // As per the documentation of `usleep`, it is expected to support
631    // sleep times as big as at least up to 1 second.
632    //
633    // ESP-IDF does support almost up to `u32::MAX`, but due to a potential integer overflow in its
634    // `usleep` implementation
635    // (https://github.com/espressif/esp-idf/blob/d7ca8b94c852052e3bc33292287ef4dd62c9eeb1/components/newlib/time.c#L210),
636    // we limit the sleep time to the maximum one that would not cause the underlying `usleep` implementation to overflow
637    // (`portTICK_PERIOD_MS` can be anything between 1 to 1000, and is 10 by default).
638    const MAX_MICROS: u32 = u32::MAX - 1_000_000 - 1;
639
640    // Add any nanoseconds smaller than a microsecond as an extra microsecond
641    // so as to comply with the `std::thread::sleep` contract which mandates
642    // implementations to sleep for _at least_ the provided `dur`.
643    // We can't overflow `micros` as it is a `u128`, while `Duration` is a pair of
644    // (`u64` secs, `u32` nanos), where the nanos are strictly smaller than 1 second
645    // (i.e. < 1_000_000_000)
646    let mut micros = dur.as_micros() + if dur.subsec_nanos() % 1_000 > 0 { 1 } else { 0 };
647
648    while micros > 0 {
649        let st = if micros > MAX_MICROS as u128 { MAX_MICROS } else { micros as u32 };
650        unsafe {
651            libc::usleep(st);
652        }
653
654        micros -= st as u128;
655    }
656}
657
658// Any unix that has clock_nanosleep
659// If this list changes update the MIRI chock_nanosleep shim
660#[cfg(any(
661    target_os = "freebsd",
662    target_os = "netbsd",
663    target_os = "linux",
664    target_os = "android",
665    target_os = "solaris",
666    target_os = "illumos",
667    target_os = "dragonfly",
668    target_os = "hurd",
669    target_os = "vxworks",
670    target_os = "wasi",
671))]
672pub fn sleep_until(deadline: crate::time::Instant) {
673    use crate::time::Instant;
674
675    let timespec = deadline.into_inner().into_timespec();
676    if timespec.tv_sec < 0 {
677        // `clock_nanosleep` fails with EINVAL if
678        // > The tp argument to clock_settime() is outside the range for the
679        // > given clock ID.
680        //
681        // This specification allows *any* clock range, which means we'd
682        // theoretically have to detect whether the time point is in the
683        // future (and block indefinitely) or the past (and return immediately)
684        // when encountering `EINVAL`. But since all existing implementations
685        // interpret this as saying that negative `tv_sec` values are unsupported,
686        // we can just test that and return – given that POSIX specifies that
687        // `CLOCK_MONOTONIC` measures the time "since an unspecified amount
688        // in the past" negative values are definitely in the past. If you
689        // observe any platform returning `EINVAL` for more cases, please
690        // file a bug; we'd need to  add logic handling `EINVAL` when it
691        // occurs.
692        return;
693    }
694
695    #[cfg(all(
696        target_os = "linux",
697        target_env = "gnu",
698        target_pointer_width = "32",
699        not(target_arch = "riscv32")
700    ))]
701    {
702        use crate::sys::pal::time::__timespec64;
703        use crate::sys::pal::weak::weak;
704
705        // This got added in glibc 2.31, along with a 64-bit `clock_gettime`
706        // function.
707        weak! {
708            fn __clock_nanosleep_time64(
709                clock_id: libc::clockid_t,
710                flags: libc::c_int,
711                req: *const __timespec64,
712                rem: *mut __timespec64,
713            ) -> libc::c_int;
714        }
715
716        if let Some(clock_nanosleep) = __clock_nanosleep_time64.get() {
717            let ts = timespec.to_timespec64();
718            loop {
719                let r = unsafe {
720                    clock_nanosleep(
721                        crate::sys::time::Instant::CLOCK_ID,
722                        libc::TIMER_ABSTIME,
723                        &ts,
724                        core::ptr::null_mut(),
725                    )
726                };
727
728                match r {
729                    0 => return,
730                    libc::EINTR => continue,
731                    // If the underlying kernel doesn't support the 64-bit
732                    // syscall, `__clock_nanosleep_time64` will fail. The
733                    // error code nowadays is EOVERFLOW, but it used to be
734                    // ENOSYS – so just don't rely on any particular value.
735                    // The parameters are all valid, so the only reasons
736                    // why the call might fail are EINTR and the call not
737                    // being supported. Fall through to the clamping version
738                    // in that case.
739                    _ => break,
740                }
741            }
742        }
743    }
744
745    let Some(ts) = timespec.to_timespec() else {
746        // The deadline is further in the future then can be passed to
747        // clock_nanosleep. We have to use Self::sleep instead. This might
748        // happen on 32 bit platforms, especially closer to 2038.
749        let now = Instant::now();
750        if let Some(delay) = deadline.checked_duration_since(now) {
751            sleep(delay);
752        }
753        return;
754    };
755
756    unsafe {
757        // When we get interrupted (res = EINTR) call clock_nanosleep again
758        loop {
759            let res = libc::clock_nanosleep(
760                crate::sys::time::Instant::CLOCK_ID,
761                libc::TIMER_ABSTIME,
762                &ts,
763                core::ptr::null_mut(), // not required with TIMER_ABSTIME
764            );
765
766            if res == 0 {
767                break;
768            } else {
769                {
    match (&res, &libc::EINTR) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val,
                    ::core::option::Option::Some(format_args!("timespec is in range,\n                         clockid is valid and kernel should support it")));
            }
        }
    }
};assert_eq!(
770                    res,
771                    libc::EINTR,
772                    "timespec is in range,
773                         clockid is valid and kernel should support it"
774                );
775            }
776        }
777    }
778}
779
780#[cfg(target_vendor = "apple")]
781pub fn sleep_until(deadline: crate::time::Instant) {
782    unsafe extern "C" {
783        // This is defined in the public header mach/mach_time.h alongside
784        // `mach_absolute_time`, and like it has been available since the very
785        // beginning.
786        //
787        // There isn't really any documentation on this function, except for a
788        // short reference in technical note 2169:
789        // https://developer.apple.com/library/archive/technotes/tn2169/_index.html
790        safe fn mach_wait_until(deadline: u64) -> libc::kern_return_t;
791    }
792
793    // Make sure to round up to ensure that we definitely sleep until after
794    // the deadline has elapsed.
795    let Some(deadline) = deadline.into_inner().into_mach_absolute_time_ceil() else {
796        // Since the deadline is before the system boot time, it has already
797        // passed, so we can return immediately.
798        return;
799    };
800
801    // If the deadline is not representable, then sleep for the maximum duration
802    // possible and worry about the potential clock issues later (in ca. 600 years).
803    let deadline = deadline.try_into().unwrap_or(u64::MAX);
804    loop {
805        match mach_wait_until(deadline) {
806            // Success! The deadline has passed.
807            libc::KERN_SUCCESS => break,
808            // If the sleep gets interrupted by a signal, `mach_wait_until`
809            // returns KERN_ABORTED, so we need to restart the syscall.
810            // Also see Apple's implementation of the POSIX `nanosleep`, which
811            // converts this error to the POSIX equivalent EINTR:
812            // https://github.com/apple-oss-distributions/Libc/blob/55b54c0a0c37b3b24393b42b90a4c561d6c606b1/gen/nanosleep.c#L281-L306
813            libc::KERN_ABORTED => continue,
814            // All other errors indicate that something has gone wrong...
815            error => {
816                let description = unsafe { CStr::from_ptr(libc::mach_error_string(error)) };
817                panic!("mach_wait_until failed: {} (code {error})", description.display())
818            }
819        }
820    }
821}
822
823#[cfg(target_os = "fuchsia")]
824pub fn sleep_until(deadline: crate::time::Instant) {
825    use crate::sys::pal::fuchsia::{zx_cvt, zx_nanosleep};
826
827    let deadline = deadline.into_inner().into_deadline();
828    if let Err(error) = zx_cvt(zx_nanosleep(deadline)) {
829        panic!("zx_nanosleep failed: {error}");
830    }
831}
832
833pub fn yield_now() {
834    let ret = unsafe { libc::sched_yield() };
835    if true {
    {
        match (&ret, &0) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(ret, 0);
836}
837
838#[cfg(any(target_os = "android", target_os = "linux"))]
839mod cgroups {
840    //! Currently not covered
841    //! * cgroup v2 in non-standard mountpoints
842    //! * paths containing control characters or spaces, since those would be escaped in procfs
843    //!   output and we don't unescape
844
845    use crate::borrow::Cow;
846    use crate::ffi::OsString;
847    use crate::fs::{File, exists};
848    use crate::io::{BufRead, Read};
849    use crate::os::unix::ffi::OsStringExt;
850    use crate::path::{Path, PathBuf};
851    use crate::str::from_utf8;
852
853    #[derive(#[automatically_derived]
impl ::core::marker::StructuralPartialEq for Cgroup { }
#[automatically_derived]
impl ::core::cmp::PartialEq for Cgroup {
    #[inline]
    fn eq(&self, other: &Cgroup) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
854    enum Cgroup {
855        V1,
856        V2,
857    }
858
859    /// Returns cgroup CPU quota in core-equivalents, rounded down or usize::MAX if the quota cannot
860    /// be determined or is not set.
861    pub(super) fn quota() -> usize {
862        let mut quota = usize::MAX;
863        if falsecfg!(miri) {
864            // Attempting to open a file fails under default flags due to isolation.
865            // And Miri does not have parallelism anyway.
866            return quota;
867        }
868
869        let _: Option<()> = try {
870            let mut buf = Vec::with_capacity(128);
871            // find our place in the cgroup hierarchy
872            File::open("/proc/self/cgroup").ok()?.read_to_end(&mut buf).ok()?;
873            let (cgroup_path, version) =
874                buf.split(|&c| c == b'\n').fold(None, |previous, line| {
875                    let mut fields = line.splitn(3, |&c| c == b':');
876                    // 2nd field is a list of controllers for v1 or empty for v2
877                    let version = match fields.nth(1) {
878                        Some(b"") => Cgroup::V2,
879                        Some(controllers)
880                            if from_utf8(controllers)
881                                .is_ok_and(|c| c.split(',').any(|c| c == "cpu")) =>
882                        {
883                            Cgroup::V1
884                        }
885                        _ => return previous,
886                    };
887
888                    // already-found v1 trumps v2 since it explicitly specifies its controllers
889                    if previous.is_some() && version == Cgroup::V2 {
890                        return previous;
891                    }
892
893                    let path = fields.last()?;
894                    // skip leading slash
895                    Some((path[1..].to_owned(), version))
896                })?;
897            let cgroup_path = PathBuf::from(OsString::from_vec(cgroup_path));
898
899            quota = match version {
900                Cgroup::V1 => quota_v1(cgroup_path),
901                Cgroup::V2 => quota_v2(cgroup_path),
902            };
903        };
904
905        quota
906    }
907
908    fn quota_v2(group_path: PathBuf) -> usize {
909        let mut quota = usize::MAX;
910
911        let mut path = PathBuf::with_capacity(128);
912        let mut read_buf = String::with_capacity(20);
913
914        // standard mount location defined in file-hierarchy(7) manpage
915        let cgroup_mount = "/sys/fs/cgroup";
916
917        path.push(cgroup_mount);
918        path.push(&group_path);
919
920        path.push("cgroup.controllers");
921
922        // skip if we're not looking at cgroup2
923        if #[allow(non_exhaustive_omitted_patterns)] match exists(&path) {
    Err(_) | Ok(false) => true,
    _ => false,
}matches!(exists(&path), Err(_) | Ok(false)) {
924            return usize::MAX;
925        };
926
927        path.pop();
928
929        let _: Option<()> = try {
930            while path.starts_with(cgroup_mount) {
931                path.push("cpu.max");
932
933                read_buf.clear();
934
935                if File::open(&path).and_then(|mut f| f.read_to_string(&mut read_buf)).is_ok() {
936                    let raw_quota = read_buf.lines().next()?;
937                    let mut raw_quota = raw_quota.split(' ');
938                    let limit = raw_quota.next()?;
939                    let period = raw_quota.next()?;
940                    match (limit.parse::<usize>(), period.parse::<usize>()) {
941                        (Ok(limit), Ok(period)) if period > 0 => {
942                            quota = quota.min(limit / period);
943                        }
944                        _ => {}
945                    }
946                }
947
948                path.pop(); // pop filename
949                path.pop(); // pop dir
950            }
951        };
952
953        quota
954    }
955
956    fn quota_v1(group_path: PathBuf) -> usize {
957        let mut quota = usize::MAX;
958        let mut path = PathBuf::with_capacity(128);
959        let mut read_buf = String::with_capacity(20);
960
961        // Hardcode commonly used locations mentioned in the cgroups(7) manpage
962        // if that doesn't work scan mountinfo and adjust `group_path` for bind-mounts
963        let mounts: &[fn(&Path) -> Option<(_, &Path)>] = &[
964            |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu"), p)),
965            |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu,cpuacct"), p)),
966            // this can be expensive on systems with tons of mountpoints
967            // but we only get to this point when /proc/self/cgroups explicitly indicated
968            // this process belongs to a cpu-controller cgroup v1 and the defaults didn't work
969            find_mountpoint,
970        ];
971
972        for mount in mounts {
973            let Some((mount, group_path)) = mount(&group_path) else { continue };
974
975            path.clear();
976            path.push(mount.as_ref());
977            path.push(&group_path);
978
979            // skip if we guessed the mount incorrectly
980            if #[allow(non_exhaustive_omitted_patterns)] match exists(&path) {
    Err(_) | Ok(false) => true,
    _ => false,
}matches!(exists(&path), Err(_) | Ok(false)) {
981                continue;
982            }
983
984            while path.starts_with(mount.as_ref()) {
985                let mut parse_file = |name| {
986                    path.push(name);
987                    read_buf.clear();
988
989                    let f = File::open(&path);
990                    path.pop(); // restore buffer before any early returns
991                    f.ok()?.read_to_string(&mut read_buf).ok()?;
992                    let parsed = read_buf.trim().parse::<usize>().ok()?;
993
994                    Some(parsed)
995                };
996
997                let limit = parse_file("cpu.cfs_quota_us");
998                let period = parse_file("cpu.cfs_period_us");
999
1000                match (limit, period) {
1001                    (Some(limit), Some(period)) if period > 0 => quota = quota.min(limit / period),
1002                    _ => {}
1003                }
1004
1005                path.pop();
1006            }
1007
1008            // we passed the try_exists above so we should have traversed the correct hierarchy
1009            // when reaching this line
1010            break;
1011        }
1012
1013        quota
1014    }
1015
1016    /// Scan mountinfo for cgroup v1 mountpoint with a cpu controller
1017    ///
1018    /// If the cgroupfs is a bind mount then `group_path` is adjusted to skip
1019    /// over the already-included prefix
1020    fn find_mountpoint(group_path: &Path) -> Option<(Cow<'static, str>, &Path)> {
1021        let mut reader = File::open_buffered("/proc/self/mountinfo").ok()?;
1022        let mut line = String::with_capacity(256);
1023        loop {
1024            line.clear();
1025            if reader.read_line(&mut line).ok()? == 0 {
1026                break;
1027            }
1028
1029            let line = line.trim();
1030            let mut items = line.split(' ');
1031
1032            let sub_path = items.nth(3)?;
1033            let mount_point = items.next()?;
1034            let mount_opts = items.next_back()?;
1035            let filesystem_type = items.nth_back(1)?;
1036
1037            if filesystem_type != "cgroup" || !mount_opts.split(',').any(|opt| opt == "cpu") {
1038                // not a cgroup / not a cpu-controller
1039                continue;
1040            }
1041
1042            let sub_path = Path::new(sub_path).strip_prefix("/").ok()?;
1043
1044            if !group_path.starts_with(sub_path) {
1045                // this is a bind-mount and the bound subdirectory
1046                // does not contain the cgroup this process belongs to
1047                continue;
1048            }
1049
1050            let trimmed_group_path = group_path.strip_prefix(sub_path).ok()?;
1051
1052            return Some((Cow::Owned(mount_point.to_owned()), trimmed_group_path));
1053        }
1054
1055        None
1056    }
1057}
1058
1059// glibc >= 2.15 has a __pthread_get_minstack() function that returns
1060// PTHREAD_STACK_MIN plus bytes needed for thread-local storage.
1061// We need that information to avoid blowing up when a small stack
1062// is created in an application with big thread-local storage requirements.
1063// See #6233 for rationale and details.
1064#[cfg(all(target_os = "linux", target_env = "gnu"))]
1065unsafe fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
1066    // We use dlsym to avoid an ELF version dependency on GLIBC_PRIVATE. (#23628)
1067    // We shouldn't really be using such an internal symbol, but there's currently
1068    // no other way to account for the TLS size.
1069    static DLSYM:
    DlsymWeak<unsafe extern "C" fn(*const libc::pthread_attr_t)
        -> libc::size_t> =
    {
        let Ok(name) =
            CStr::from_bytes_with_nul("__pthread_get_minstack\u{0}".as_bytes()) else {
                {
                    ::core::panicking::panic_fmt(format_args!("symbol name may not contain NUL"));
                }
            };
        unsafe { DlsymWeak::new(name) }
    };
let __pthread_get_minstack = &DLSYM;dlsym!(
1070        fn __pthread_get_minstack(attr: *const libc::pthread_attr_t) -> libc::size_t;
1071    );
1072
1073    match __pthread_get_minstack.get() {
1074        None => libc::PTHREAD_STACK_MIN,
1075        Some(f) => unsafe { f(attr) },
1076    }
1077}
1078
1079// No point in looking up __pthread_get_minstack() on non-glibc platforms.
1080#[cfg(all(
1081    not(all(target_os = "linux", target_env = "gnu")),
1082    not(any(target_os = "netbsd", target_os = "nuttx"))
1083))]
1084unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
1085    libc::PTHREAD_STACK_MIN
1086}
1087
1088#[cfg(any(target_os = "netbsd", target_os = "nuttx"))]
1089unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
1090    static STACK: crate::sync::OnceLock<usize> = crate::sync::OnceLock::new();
1091
1092    *STACK.get_or_init(|| {
1093        let mut stack = unsafe { libc::sysconf(libc::_SC_THREAD_STACK_MIN) };
1094        if stack < 0 {
1095            stack = 2048; // just a guess
1096        }
1097
1098        stack as usize
1099    })
1100}