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; pub struct Thread {
42 id: libc::pthread_t,
43}
44
45unsafe impl Send for Thread {}
48unsafe impl Sync for Thread {}
49
50impl Thread {
51 #[cfg_attr(miri, track_caller)] 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 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 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 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 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 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 let init = Box::from_raw(data as *mut ThreadInit);
121 let rust_start = init.init();
122
123 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 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 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 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 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 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 unsafe {
335 let set = libc::vxCpuEnabledGet();
336 Ok(NonZero::new_unchecked(set.count_ones() as usize))
337 }
338 }
339 _ => {
340 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 cfg_select! {
356 any(target_os = "android", target_os = "linux") => {
358 use crate::sys::pal::weak::syscall;
359
360 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 let id: libc::pid_t = unsafe { gettid() };
368 Some(id as u64)
369 }
370 any(target_os = "nto", target_os = "qnx") => {
371 let id: libc::pid_t = unsafe { libc::gettid() };
373 Some(id as u64)
374 }
375 target_os = "openbsd" => {
376 let id: libc::pid_t = unsafe { libc::getthrid() };
378 Some(id as u64)
379 }
380 target_os = "freebsd" => {
381 let id: libc::c_int = unsafe { libc::pthread_getthreadid_np() };
383 Some(id as u64)
384 }
385 target_os = "netbsd" => {
386 let id: libc::lwpid_t = unsafe { libc::_lwp_self() };
388 Some(id as u64)
389 }
390 any(target_os = "illumos", target_os = "solaris") => {
391 let id: libc::pthread_t = unsafe { libc::pthread_self() };
394 Some(id as u64)
395 }
396 target_vendor = "apple" => {
397 let mut id = 0u64;
399 let status: libc::c_int = unsafe { libc::pthread_threadid_np(0, &mut id) };
401 if status == 0 { Some(id) } else { None }
402 }
403 _ => 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 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 const TASK_COMM_LEN: usize = 16;
456 let name = truncate_cstr::<{ TASK_COMM_LEN }>(name);
457 }
458 _ => {
459 }
461 };
462 let res = libc::pthread_setname_np(libc::pthread_self(), name.as_ptr());
465 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 debug_assert_eq!(res, 0);
484 }
485}
486
487#[cfg(target_os = "netbsd")]
488pub fn set_name(name: &CStr) {
489 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 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(
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 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 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 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 const MAX_MICROS: u32 = u32::MAX - 1_000_000 - 1;
639
640 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#[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 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 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 _ => break,
740 }
741 }
742 }
743 }
744
745 let Some(ts) = timespec.to_timespec() else {
746 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 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(), );
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 safe fn mach_wait_until(deadline: u64) -> libc::kern_return_t;
791 }
792
793 let Some(deadline) = deadline.into_inner().into_mach_absolute_time_ceil() else {
796 return;
799 };
800
801 let deadline = deadline.try_into().unwrap_or(u64::MAX);
804 loop {
805 match mach_wait_until(deadline) {
806 libc::KERN_SUCCESS => break,
808 libc::KERN_ABORTED => continue,
814 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 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 pub(super) fn quota() -> usize {
862 let mut quota = usize::MAX;
863 if falsecfg!(miri) {
864 return quota;
867 }
868
869 let _: Option<()> = try {
870 let mut buf = Vec::with_capacity(128);
871 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 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 if previous.is_some() && version == Cgroup::V2 {
890 return previous;
891 }
892
893 let path = fields.last()?;
894 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 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 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(); path.pop(); }
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 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 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 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(); 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 break;
1011 }
1012
1013 quota
1014 }
1015
1016 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 continue;
1040 }
1041
1042 let sub_path = Path::new(sub_path).strip_prefix("/").ok()?;
1043
1044 if !group_path.starts_with(sub_path) {
1045 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#[cfg(all(target_os = "linux", target_env = "gnu"))]
1065unsafe fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
1066 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#[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; }
1097
1098 stack as usize
1099 })
1100}