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; pub struct Thread {
40 id: libc::pthread_t,
41}
42
43unsafe impl Send for Thread {}
46unsafe impl Sync for Thread {}
47
48impl Thread {
49 #[cfg_attr(miri, track_caller)] 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 {
match (&libc::pthread_attr_init(attr.as_mut_ptr()), &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.as_mut_ptr()), 0);
55 let mut attr = DropGuard::new(&mut attr, |attr| {
56 {
match (&libc::pthread_attr_destroy(attr.as_mut_ptr()), &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.as_mut_ptr()), 0)
57 });
58
59 #[cfg(any(target_os = "espidf", target_os = "nuttx"))]
60 if stack > 0 {
61 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 {
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);
80 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 if libc::pthread_attr_setstacksize(attr.as_mut_ptr(), stack_size) != 0 {
92 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!(
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 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 let init = Box::from_raw(data as *mut ThreadInit);
117 let rust_start = init.init();
118
119 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 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));
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 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);
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 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 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 let count = libc::CPU_COUNT(&set) as usize;
220 if count > 0 {
221 return Ok(NonZero::new_unchecked(count));
222 }
223 }
224 }
225 }
226
227 #[cfg(target_os = "netbsd")]
228 {
229 unsafe {
230 let set = libc::_cpuset_create();
231 if !set.is_null() {
232 let mut count: usize = 0;
233 if libc::pthread_getaffinity_np(libc::pthread_self(), libc::_cpuset_size(set), set) == 0 {
234 for i in 0..libc::cpuid_t::MAX {
235 match libc::_cpuset_isset(i, set) {
236 -1 => break,
237 0 => continue,
238 _ => count = count + 1,
239 }
240 }
241 }
242 libc::_cpuset_destroy(set);
243 if let Some(count) = NonZero::new(count) {
244 return Ok(count);
245 }
246 }
247 }
248 }
249
250 let mut cpus: libc::c_uint = 0;
251 let mut cpus_size = size_of_val(&cpus);
252
253 unsafe {
254 cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint;
255 }
256
257 if cpus < 1 {
259 let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
260 let res = unsafe {
261 libc::sysctl(
262 mib.as_mut_ptr(),
263 2,
264 (&raw mut cpus) as *mut _,
265 (&raw mut cpus_size) as *mut _,
266 ptr::null_mut(),
267 0,
268 )
269 };
270
271 if res == -1 {
273 return Err(io::Error::last_os_error());
274 } else if cpus == 0 {
275 return Err(io::Error::UNKNOWN_THREAD_COUNT);
276 }
277 }
278
279 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
280 }
281 any(target_os = "nto", target_os = "qnx") => {
282 unsafe {
283 use libc::_syspage_ptr;
284 if _syspage_ptr.is_null() {
285 Err(io::const_error!(io::ErrorKind::NotFound, "no syspage available"))
286 } else {
287 let cpus = (*_syspage_ptr).num_cpu;
288 NonZero::new(cpus as usize)
289 .ok_or(io::Error::UNKNOWN_THREAD_COUNT)
290 }
291 }
292 }
293 any(target_os = "solaris", target_os = "illumos") => {
294 let mut cpus = 0u32;
295 if unsafe { libc::pset_info(libc::PS_MYID, core::ptr::null_mut(), &mut cpus, core::ptr::null_mut()) } != 0 {
296 return Err(io::Error::UNKNOWN_THREAD_COUNT);
297 }
298 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
299 }
300 target_os = "haiku" => {
301 unsafe {
304 let mut sinfo: libc::system_info = crate::mem::zeroed();
305 let res = libc::get_system_info(&mut sinfo);
306
307 if res != libc::B_OK {
308 return Err(io::Error::UNKNOWN_THREAD_COUNT);
309 }
310
311 Ok(NonZero::new_unchecked(sinfo.cpu_count as usize))
312 }
313 }
314 target_os = "vxworks" => {
315 unsafe{
320 let set = libc::vxCpuEnabledGet();
321 Ok(NonZero::new_unchecked(set.count_ones() as usize))
322 }
323 }
324 _ => {
325 Err(io::const_error!(io::ErrorKind::Unsupported, "getting the number of hardware threads is not supported on the target platform"))
327 }
328 }
329}
330
331pub fn current_os_id() -> Option<u64> {
332 cfg_select! {
338 any(target_os = "android", target_os = "linux") => {
340 use crate::sys::pal::weak::syscall;
341
342 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!(fn gettid() -> libc::pid_t;);
345
346 let id: libc::pid_t = unsafe { gettid() };
348 Some(id as u64)
349 }
350 any(target_os = "nto", target_os = "qnx") => {
351 let id: libc::pid_t = unsafe { libc::gettid() };
353 Some(id as u64)
354 }
355 target_os = "openbsd" => {
356 let id: libc::pid_t = unsafe { libc::getthrid() };
358 Some(id as u64)
359 }
360 target_os = "freebsd" => {
361 let id: libc::c_int = unsafe { libc::pthread_getthreadid_np() };
363 Some(id as u64)
364 }
365 target_os = "netbsd" => {
366 let id: libc::lwpid_t = unsafe { libc::_lwp_self() };
368 Some(id as u64)
369 }
370 any(target_os = "illumos", target_os = "solaris") => {
371 let id: libc::pthread_t = unsafe { libc::pthread_self() };
374 Some(id as u64)
375 }
376 target_vendor = "apple" => {
377 let mut id = 0u64;
379 let status: libc::c_int = unsafe { libc::pthread_threadid_np(0, &mut id) };
381 if status == 0 {
382 Some(id)
383 } else {
384 None
385 }
386 }
387 _ => None,
389 }
390}
391
392#[cfg(any(
393 target_os = "linux",
394 target_os = "nto",
395 target_os = "qnx",
396 target_os = "solaris",
397 target_os = "illumos",
398 target_os = "vxworks",
399 target_os = "cygwin",
400 target_vendor = "apple",
401 target_os = "netbsd",
402))]
403fn truncate_cstr<const MAX_WITH_NUL: usize>(cstr: &CStr) -> [libc::c_char; MAX_WITH_NUL] {
404 let mut result = [0; MAX_WITH_NUL];
405 for (src, dst) in cstr.to_bytes().iter().zip(&mut result[..MAX_WITH_NUL - 1]) {
406 *dst = *src as libc::c_char;
407 }
408 result
409}
410
411#[cfg(target_os = "android")]
412pub fn set_name(name: &CStr) {
413 const PR_SET_NAME: libc::c_int = 15;
414 unsafe {
415 let res = libc::prctl(
416 PR_SET_NAME,
417 name.as_ptr(),
418 0 as libc::c_ulong,
419 0 as libc::c_ulong,
420 0 as libc::c_ulong,
421 );
422 debug_assert_eq!(res, 0);
424 }
425}
426
427#[cfg(any(
428 target_os = "linux",
429 target_os = "freebsd",
430 target_os = "dragonfly",
431 target_os = "nuttx",
432 target_os = "cygwin"
433))]
434pub fn set_name(name: &CStr) {
435 unsafe {
436 cfg_select! {
437 any(target_os = "linux", target_os = "cygwin") => {
438 const TASK_COMM_LEN: usize = 16;
440 let name = truncate_cstr::<{ TASK_COMM_LEN }>(name);
441 }
442 _ => {
443 }
445 };
446 let res = libc::pthread_setname_np(libc::pthread_self(), name.as_ptr());
449 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);
451 }
452}
453
454#[cfg(target_os = "openbsd")]
455pub fn set_name(name: &CStr) {
456 unsafe {
457 libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
458 }
459}
460
461#[cfg(target_vendor = "apple")]
462pub fn set_name(name: &CStr) {
463 unsafe {
464 let name = truncate_cstr::<{ libc::MAXTHREADNAMESIZE }>(name);
465 let res = libc::pthread_setname_np(name.as_ptr());
466 debug_assert_eq!(res, 0);
468 }
469}
470
471#[cfg(target_os = "netbsd")]
472pub fn set_name(name: &CStr) {
473 const PTHREAD_MAX_NAMELEN_NP: usize = 32;
476
477 unsafe {
478 let name = truncate_cstr::<{ PTHREAD_MAX_NAMELEN_NP }>(name);
479 let res = libc::pthread_setname_np(
480 libc::pthread_self(),
481 c"%s".as_ptr(),
482 name.as_ptr() as *mut libc::c_void,
483 );
484 debug_assert_eq!(res, 0);
485 }
486}
487
488#[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto", target_os = "qnx"))]
489pub fn set_name(name: &CStr) {
490 weak!(
491 fn pthread_setname_np(thread: libc::pthread_t, name: *const libc::c_char) -> libc::c_int;
492 );
493
494 if let Some(f) = pthread_setname_np.get() {
495 #[cfg(any(target_os = "nto", target_os = "qnx"))]
496 const THREAD_NAME_MAX: usize = libc::_NTO_THREAD_NAME_MAX as usize;
497 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
498 const THREAD_NAME_MAX: usize = 32;
499
500 let name = truncate_cstr::<{ THREAD_NAME_MAX }>(name);
501 let res = unsafe { f(libc::pthread_self(), name.as_ptr()) };
502 debug_assert_eq!(res, 0);
503 }
504}
505
506#[cfg(target_os = "fuchsia")]
507pub fn set_name(name: &CStr) {
508 use crate::sys::pal::fuchsia::*;
509 unsafe {
510 zx_object_set_property(
511 zx_thread_self(),
512 ZX_PROP_NAME,
513 name.as_ptr() as *const libc::c_void,
514 name.to_bytes().len(),
515 );
516 }
517}
518
519#[cfg(target_os = "haiku")]
520pub fn set_name(name: &CStr) {
521 unsafe {
522 let thread_self = libc::find_thread(ptr::null_mut());
523 let res = libc::rename_thread(thread_self, name.as_ptr());
524 debug_assert_eq!(res, libc::B_OK);
526 }
527}
528
529#[cfg(target_os = "vxworks")]
530pub fn set_name(name: &CStr) {
531 let mut name = truncate_cstr::<{ (libc::VX_TASK_RENAME_LENGTH - 1) as usize }>(name);
532 let res = unsafe { libc::taskNameSet(libc::taskIdSelf(), name.as_mut_ptr()) };
533 debug_assert_eq!(res, libc::OK);
534}
535
536#[cfg(not(target_os = "espidf"))]
537pub fn sleep(dur: Duration) {
538 cfg_select! {
539 any(
542 target_os = "freebsd",
543 target_os = "netbsd",
544 target_os = "linux",
545 target_os = "android",
546 target_os = "solaris",
547 target_os = "illumos",
548 target_os = "dragonfly",
549 target_os = "hurd",
550 target_os = "vxworks",
551 target_os = "wasi",
552 ) => {
553 unsafe fn nanosleep(rqtp: *const libc::timespec, rmtp: *mut libc::timespec) -> libc::c_int {
567 unsafe { libc::clock_nanosleep(crate::sys::time::Instant::CLOCK_ID, 0, rqtp, rmtp) }
568 }
569 }
570 _ => {
571 unsafe fn nanosleep(rqtp: *const libc::timespec, rmtp: *mut libc::timespec) -> libc::c_int {
572 let r = unsafe { libc::nanosleep(rqtp, rmtp) };
573 if r == 0 { 0 } else { sys::io::errno() }
576 }
577 }
578 }
579
580 let mut secs = dur.as_secs();
581 let mut nsecs = dur.subsec_nanos() as _;
582
583 unsafe {
586 while secs > 0 || nsecs > 0 {
587 let mut ts = libc::timespec::default();
588 ts.tv_sec = cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t;
589 ts.tv_nsec = nsecs;
590
591 secs -= ts.tv_sec as u64;
592 let ts_ptr = &raw mut ts;
593 let r = nanosleep(ts_ptr, ts_ptr);
594 if r != 0 {
595 {
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);
596 secs += ts.tv_sec as u64;
597 nsecs = ts.tv_nsec;
598 } else {
599 nsecs = 0;
600 }
601 }
602 }
603}
604
605#[cfg(target_os = "espidf")]
606pub fn sleep(dur: Duration) {
607 const MAX_MICROS: u32 = u32::MAX - 1_000_000 - 1;
617
618 let mut micros = dur.as_micros() + if dur.subsec_nanos() % 1_000 > 0 { 1 } else { 0 };
625
626 while micros > 0 {
627 let st = if micros > MAX_MICROS as u128 { MAX_MICROS } else { micros as u32 };
628 unsafe {
629 libc::usleep(st);
630 }
631
632 micros -= st as u128;
633 }
634}
635
636#[cfg(any(
639 target_os = "freebsd",
640 target_os = "netbsd",
641 target_os = "linux",
642 target_os = "android",
643 target_os = "solaris",
644 target_os = "illumos",
645 target_os = "dragonfly",
646 target_os = "hurd",
647 target_os = "vxworks",
648 target_os = "wasi",
649))]
650pub fn sleep_until(deadline: crate::time::Instant) {
651 use crate::time::Instant;
652
653 #[cfg(all(
654 target_os = "linux",
655 target_env = "gnu",
656 target_pointer_width = "32",
657 not(target_arch = "riscv32")
658 ))]
659 {
660 use crate::sys::pal::time::__timespec64;
661 use crate::sys::pal::weak::weak;
662
663 weak! {
666 fn __clock_nanosleep_time64(
667 clock_id: libc::clockid_t,
668 flags: libc::c_int,
669 req: *const __timespec64,
670 rem: *mut __timespec64,
671 ) -> libc::c_int;
672 }
673
674 if let Some(clock_nanosleep) = __clock_nanosleep_time64.get() {
675 let ts = deadline.into_inner().into_timespec().to_timespec64();
676 loop {
677 let r = unsafe {
678 clock_nanosleep(
679 crate::sys::time::Instant::CLOCK_ID,
680 libc::TIMER_ABSTIME,
681 &ts,
682 core::ptr::null_mut(),
683 )
684 };
685
686 match r {
687 0 => return,
688 libc::EINTR => continue,
689 _ => break,
698 }
699 }
700 }
701 }
702
703 let Some(ts) = deadline.into_inner().into_timespec().to_timespec() else {
704 let now = Instant::now();
708 if let Some(delay) = deadline.checked_duration_since(now) {
709 sleep(delay);
710 }
711 return;
712 };
713
714 unsafe {
715 loop {
717 let res = libc::clock_nanosleep(
718 crate::sys::time::Instant::CLOCK_ID,
719 libc::TIMER_ABSTIME,
720 &ts,
721 core::ptr::null_mut(), );
723
724 if res == 0 {
725 break;
726 } else {
727 {
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!(
728 res,
729 libc::EINTR,
730 "timespec is in range,
731 clockid is valid and kernel should support it"
732 );
733 }
734 }
735 }
736}
737
738#[cfg(target_vendor = "apple")]
739pub fn sleep_until(deadline: crate::time::Instant) {
740 unsafe extern "C" {
741 safe fn mach_wait_until(deadline: u64) -> libc::kern_return_t;
749 }
750
751 let Some(deadline) = deadline.into_inner().into_mach_absolute_time_ceil() else {
754 return;
757 };
758
759 let deadline = deadline.try_into().unwrap_or(u64::MAX);
762 loop {
763 match mach_wait_until(deadline) {
764 libc::KERN_SUCCESS => break,
766 libc::KERN_ABORTED => continue,
772 error => {
774 let description = unsafe { CStr::from_ptr(libc::mach_error_string(error)) };
775 panic!("mach_wait_until failed: {} (code {error})", description.display())
776 }
777 }
778 }
779}
780
781pub fn yield_now() {
782 let ret = unsafe { libc::sched_yield() };
783 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);
784}
785
786#[cfg(any(target_os = "android", target_os = "linux"))]
787mod cgroups {
788 use crate::borrow::Cow;
794 use crate::ffi::OsString;
795 use crate::fs::{File, exists};
796 use crate::io::{BufRead, Read};
797 use crate::os::unix::ffi::OsStringExt;
798 use crate::path::{Path, PathBuf};
799 use crate::str::from_utf8;
800
801 #[derive(#[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)]
802 enum Cgroup {
803 V1,
804 V2,
805 }
806
807 pub(super) fn quota() -> usize {
810 let mut quota = usize::MAX;
811 if falsecfg!(miri) {
812 return quota;
815 }
816
817 let _: Option<()> = try {
818 let mut buf = Vec::with_capacity(128);
819 File::open("/proc/self/cgroup").ok()?.read_to_end(&mut buf).ok()?;
821 let (cgroup_path, version) =
822 buf.split(|&c| c == b'\n').fold(None, |previous, line| {
823 let mut fields = line.splitn(3, |&c| c == b':');
824 let version = match fields.nth(1) {
826 Some(b"") => Cgroup::V2,
827 Some(controllers)
828 if from_utf8(controllers)
829 .is_ok_and(|c| c.split(',').any(|c| c == "cpu")) =>
830 {
831 Cgroup::V1
832 }
833 _ => return previous,
834 };
835
836 if previous.is_some() && version == Cgroup::V2 {
838 return previous;
839 }
840
841 let path = fields.last()?;
842 Some((path[1..].to_owned(), version))
844 })?;
845 let cgroup_path = PathBuf::from(OsString::from_vec(cgroup_path));
846
847 quota = match version {
848 Cgroup::V1 => quota_v1(cgroup_path),
849 Cgroup::V2 => quota_v2(cgroup_path),
850 };
851 };
852
853 quota
854 }
855
856 fn quota_v2(group_path: PathBuf) -> usize {
857 let mut quota = usize::MAX;
858
859 let mut path = PathBuf::with_capacity(128);
860 let mut read_buf = String::with_capacity(20);
861
862 let cgroup_mount = "/sys/fs/cgroup";
864
865 path.push(cgroup_mount);
866 path.push(&group_path);
867
868 path.push("cgroup.controllers");
869
870 if #[allow(non_exhaustive_omitted_patterns)] match exists(&path) {
Err(_) | Ok(false) => true,
_ => false,
}matches!(exists(&path), Err(_) | Ok(false)) {
872 return usize::MAX;
873 };
874
875 path.pop();
876
877 let _: Option<()> = try {
878 while path.starts_with(cgroup_mount) {
879 path.push("cpu.max");
880
881 read_buf.clear();
882
883 if File::open(&path).and_then(|mut f| f.read_to_string(&mut read_buf)).is_ok() {
884 let raw_quota = read_buf.lines().next()?;
885 let mut raw_quota = raw_quota.split(' ');
886 let limit = raw_quota.next()?;
887 let period = raw_quota.next()?;
888 match (limit.parse::<usize>(), period.parse::<usize>()) {
889 (Ok(limit), Ok(period)) if period > 0 => {
890 quota = quota.min(limit / period);
891 }
892 _ => {}
893 }
894 }
895
896 path.pop(); path.pop(); }
899 };
900
901 quota
902 }
903
904 fn quota_v1(group_path: PathBuf) -> usize {
905 let mut quota = usize::MAX;
906 let mut path = PathBuf::with_capacity(128);
907 let mut read_buf = String::with_capacity(20);
908
909 let mounts: &[fn(&Path) -> Option<(_, &Path)>] = &[
912 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu"), p)),
913 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu,cpuacct"), p)),
914 find_mountpoint,
918 ];
919
920 for mount in mounts {
921 let Some((mount, group_path)) = mount(&group_path) else { continue };
922
923 path.clear();
924 path.push(mount.as_ref());
925 path.push(&group_path);
926
927 if #[allow(non_exhaustive_omitted_patterns)] match exists(&path) {
Err(_) | Ok(false) => true,
_ => false,
}matches!(exists(&path), Err(_) | Ok(false)) {
929 continue;
930 }
931
932 while path.starts_with(mount.as_ref()) {
933 let mut parse_file = |name| {
934 path.push(name);
935 read_buf.clear();
936
937 let f = File::open(&path);
938 path.pop(); f.ok()?.read_to_string(&mut read_buf).ok()?;
940 let parsed = read_buf.trim().parse::<usize>().ok()?;
941
942 Some(parsed)
943 };
944
945 let limit = parse_file("cpu.cfs_quota_us");
946 let period = parse_file("cpu.cfs_period_us");
947
948 match (limit, period) {
949 (Some(limit), Some(period)) if period > 0 => quota = quota.min(limit / period),
950 _ => {}
951 }
952
953 path.pop();
954 }
955
956 break;
959 }
960
961 quota
962 }
963
964 fn find_mountpoint(group_path: &Path) -> Option<(Cow<'static, str>, &Path)> {
969 let mut reader = File::open_buffered("/proc/self/mountinfo").ok()?;
970 let mut line = String::with_capacity(256);
971 loop {
972 line.clear();
973 if reader.read_line(&mut line).ok()? == 0 {
974 break;
975 }
976
977 let line = line.trim();
978 let mut items = line.split(' ');
979
980 let sub_path = items.nth(3)?;
981 let mount_point = items.next()?;
982 let mount_opts = items.next_back()?;
983 let filesystem_type = items.nth_back(1)?;
984
985 if filesystem_type != "cgroup" || !mount_opts.split(',').any(|opt| opt == "cpu") {
986 continue;
988 }
989
990 let sub_path = Path::new(sub_path).strip_prefix("/").ok()?;
991
992 if !group_path.starts_with(sub_path) {
993 continue;
996 }
997
998 let trimmed_group_path = group_path.strip_prefix(sub_path).ok()?;
999
1000 return Some((Cow::Owned(mount_point.to_owned()), trimmed_group_path));
1001 }
1002
1003 None
1004 }
1005}
1006
1007#[cfg(all(target_os = "linux", target_env = "gnu"))]
1013unsafe fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
1014 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!(
1018 fn __pthread_get_minstack(attr: *const libc::pthread_attr_t) -> libc::size_t;
1019 );
1020
1021 match __pthread_get_minstack.get() {
1022 None => libc::PTHREAD_STACK_MIN,
1023 Some(f) => unsafe { f(attr) },
1024 }
1025}
1026
1027#[cfg(all(
1029 not(all(target_os = "linux", target_env = "gnu")),
1030 not(any(target_os = "netbsd", target_os = "nuttx"))
1031))]
1032unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
1033 libc::PTHREAD_STACK_MIN
1034}
1035
1036#[cfg(any(target_os = "netbsd", target_os = "nuttx"))]
1037unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
1038 static STACK: crate::sync::OnceLock<usize> = crate::sync::OnceLock::new();
1039
1040 *STACK.get_or_init(|| {
1041 let mut stack = unsafe { libc::sysconf(libc::_SC_THREAD_STACK_MIN) };
1042 if stack < 0 {
1043 stack = 2048; }
1045
1046 stack as usize
1047 })
1048}