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