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(target_os = "solaris", target_os = "illumos", target_os = "nto",))]
16use crate::sys::weak::weak;
17use crate::thread::ThreadInit;
18use crate::time::Duration;
19use crate::{cmp, io, ptr, sys};
20#[cfg(not(any(
21 target_os = "l4re",
22 target_os = "vxworks",
23 target_os = "espidf",
24 target_os = "nuttx"
25)))]
26pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
27#[cfg(target_os = "l4re")]
28pub const DEFAULT_MIN_STACK_SIZE: usize = 1024 * 1024;
29#[cfg(target_os = "vxworks")]
30pub const DEFAULT_MIN_STACK_SIZE: usize = 256 * 1024;
31#[cfg(any(target_os = "espidf", target_os = "nuttx"))]
32pub const DEFAULT_MIN_STACK_SIZE: usize = 0; pub struct Thread {
35 id: libc::pthread_t,
36}
37
38unsafe impl Send for Thread {}
41unsafe impl Sync for Thread {}
42
43impl Thread {
44 #[cfg_attr(miri, track_caller)] pub unsafe fn new(stack: usize, init: Box<ThreadInit>) -> io::Result<Thread> {
47 let data = init;
48 let mut attr: mem::MaybeUninit<libc::pthread_attr_t> = mem::MaybeUninit::uninit();
49 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);
50 let mut attr = DropGuard::new(&mut attr, |attr| {
51 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)
52 });
53
54 #[cfg(any(target_os = "espidf", target_os = "nuttx"))]
55 if stack > 0 {
56 assert_eq!(
59 libc::pthread_attr_setstacksize(
60 attr.as_mut_ptr(),
61 cmp::max(stack, min_stack_size(attr.as_ptr()))
62 ),
63 0
64 );
65 }
66
67 #[cfg(not(any(target_os = "espidf", target_os = "nuttx")))]
68 {
69 let stack_size = cmp::max(stack, min_stack_size(attr.as_ptr()));
70
71 match libc::pthread_attr_setstacksize(attr.as_mut_ptr(), stack_size) {
72 0 => {}
73 n => {
74 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);
75 let page_size = sys::pal::conf::page_size();
80 let stack_size =
81 (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1);
82
83 if libc::pthread_attr_setstacksize(attr.as_mut_ptr(), stack_size) != 0 {
87 return Err(crate::hint::must_use(crate::io::Error::from_static_message(const {
&crate::io::SimpleMessage {
kind: io::ErrorKind::InvalidInput,
message: "invalid stack size",
}
}))io::const_error!(
88 io::ErrorKind::InvalidInput,
89 "invalid stack size"
90 ));
91 }
92 }
93 };
94 }
95
96 let data = Box::into_raw(data);
97 let mut native: libc::pthread_t = mem::zeroed();
98 let ret = libc::pthread_create(&mut native, attr.as_ptr(), thread_start, data as *mut _);
99 return if ret == 0 {
100 Ok(Thread { id: native })
101 } else {
102 drop(Box::from_raw(data));
105 Err(io::Error::from_raw_os_error(ret))
106 };
107
108 extern "C" fn thread_start(data: *mut libc::c_void) -> *mut libc::c_void {
109 unsafe {
110 let init = Box::from_raw(data as *mut ThreadInit);
112 let rust_start = init.init();
113
114 let _handler = sys::stack_overflow::Handler::new();
117
118 rust_start();
119 }
120 ptr::null_mut()
121 }
122 }
123
124 pub fn join(self) {
125 let id = self.into_id();
126 let ret = unsafe { libc::pthread_join(id, ptr::null_mut()) };
127 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));
128 }
129
130 #[cfg(not(target_os = "wasi"))]
131 pub fn id(&self) -> libc::pthread_t {
132 self.id
133 }
134
135 pub fn into_id(self) -> libc::pthread_t {
136 ManuallyDrop::new(self).id
137 }
138}
139
140impl Drop for Thread {
141 fn drop(&mut self) {
142 let ret = unsafe { libc::pthread_detach(self.id) };
143 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);
144 }
145}
146
147pub fn available_parallelism() -> io::Result<NonZero<usize>> {
148 cfg_select! {
149 any(
150 target_os = "android",
151 target_os = "emscripten",
152 target_os = "fuchsia",
153 target_os = "hurd",
154 target_os = "linux",
155 target_os = "aix",
156 target_vendor = "apple",
157 target_os = "cygwin",
158 target_os = "redox",
159 target_os = "wasi",
160 ) => {
161 #[allow(unused_assignments)]
162 #[allow(unused_mut)]
163 let mut quota = usize::MAX;
164
165 #[cfg(any(target_os = "android", target_os = "linux"))]
166 {
167 quota = cgroups::quota().max(1);
168 let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
169 unsafe {
170 if libc::sched_getaffinity(0, size_of::<libc::cpu_set_t>(), &mut set) == 0 {
171 let count = libc::CPU_COUNT(&set) as usize;
172 let count = count.min(quota);
173
174 if let Some(count) = NonZero::new(count) {
179 return Ok(count)
180 }
181 }
182 }
183 }
184 match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
185 -1 => Err(io::Error::last_os_error()),
186 0 => Err(io::Error::UNKNOWN_THREAD_COUNT),
187 cpus => {
188 let count = cpus as usize;
189 let count = count.min(quota);
191 Ok(unsafe { NonZero::new_unchecked(count) })
192 }
193 }
194 }
195 any(
196 target_os = "freebsd",
197 target_os = "dragonfly",
198 target_os = "openbsd",
199 target_os = "netbsd",
200 ) => {
201 use crate::ptr;
202
203 #[cfg(target_os = "freebsd")]
204 {
205 let mut set: libc::cpuset_t = unsafe { mem::zeroed() };
206 unsafe {
207 if libc::cpuset_getaffinity(
208 libc::CPU_LEVEL_WHICH,
209 libc::CPU_WHICH_PID,
210 -1,
211 size_of::<libc::cpuset_t>(),
212 &mut set,
213 ) == 0 {
214 let count = libc::CPU_COUNT(&set) as usize;
215 if count > 0 {
216 return Ok(NonZero::new_unchecked(count));
217 }
218 }
219 }
220 }
221
222 #[cfg(target_os = "netbsd")]
223 {
224 unsafe {
225 let set = libc::_cpuset_create();
226 if !set.is_null() {
227 let mut count: usize = 0;
228 if libc::pthread_getaffinity_np(libc::pthread_self(), libc::_cpuset_size(set), set) == 0 {
229 for i in 0..libc::cpuid_t::MAX {
230 match libc::_cpuset_isset(i, set) {
231 -1 => break,
232 0 => continue,
233 _ => count = count + 1,
234 }
235 }
236 }
237 libc::_cpuset_destroy(set);
238 if let Some(count) = NonZero::new(count) {
239 return Ok(count);
240 }
241 }
242 }
243 }
244
245 let mut cpus: libc::c_uint = 0;
246 let mut cpus_size = size_of_val(&cpus);
247
248 unsafe {
249 cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint;
250 }
251
252 if cpus < 1 {
254 let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
255 let res = unsafe {
256 libc::sysctl(
257 mib.as_mut_ptr(),
258 2,
259 (&raw mut cpus) as *mut _,
260 (&raw mut cpus_size) as *mut _,
261 ptr::null_mut(),
262 0,
263 )
264 };
265
266 if res == -1 {
268 return Err(io::Error::last_os_error());
269 } else if cpus == 0 {
270 return Err(io::Error::UNKNOWN_THREAD_COUNT);
271 }
272 }
273
274 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
275 }
276 target_os = "nto" => {
277 unsafe {
278 use libc::_syspage_ptr;
279 if _syspage_ptr.is_null() {
280 Err(io::const_error!(io::ErrorKind::NotFound, "no syspage available"))
281 } else {
282 let cpus = (*_syspage_ptr).num_cpu;
283 NonZero::new(cpus as usize)
284 .ok_or(io::Error::UNKNOWN_THREAD_COUNT)
285 }
286 }
287 }
288 any(target_os = "solaris", target_os = "illumos") => {
289 let mut cpus = 0u32;
290 if unsafe { libc::pset_info(libc::PS_MYID, core::ptr::null_mut(), &mut cpus, core::ptr::null_mut()) } != 0 {
291 return Err(io::Error::UNKNOWN_THREAD_COUNT);
292 }
293 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
294 }
295 target_os = "haiku" => {
296 unsafe {
299 let mut sinfo: libc::system_info = crate::mem::zeroed();
300 let res = libc::get_system_info(&mut sinfo);
301
302 if res != libc::B_OK {
303 return Err(io::Error::UNKNOWN_THREAD_COUNT);
304 }
305
306 Ok(NonZero::new_unchecked(sinfo.cpu_count as usize))
307 }
308 }
309 target_os = "vxworks" => {
310 unsafe{
315 let set = libc::vxCpuEnabledGet();
316 Ok(NonZero::new_unchecked(set.count_ones() as usize))
317 }
318 }
319 _ => {
320 Err(io::const_error!(io::ErrorKind::Unsupported, "getting the number of hardware threads is not supported on the target platform"))
322 }
323 }
324}
325
326pub fn current_os_id() -> Option<u64> {
327 cfg_select! {
333 any(target_os = "android", target_os = "linux") => {
335 use crate::sys::pal::weak::syscall;
336
337 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;);
340
341 let id: libc::pid_t = unsafe { gettid() };
343 Some(id as u64)
344 }
345 target_os = "nto" => {
346 let id: libc::pid_t = unsafe { libc::gettid() };
348 Some(id as u64)
349 }
350 target_os = "openbsd" => {
351 let id: libc::pid_t = unsafe { libc::getthrid() };
353 Some(id as u64)
354 }
355 target_os = "freebsd" => {
356 let id: libc::c_int = unsafe { libc::pthread_getthreadid_np() };
358 Some(id as u64)
359 }
360 target_os = "netbsd" => {
361 let id: libc::lwpid_t = unsafe { libc::_lwp_self() };
363 Some(id as u64)
364 }
365 any(target_os = "illumos", target_os = "solaris") => {
366 let id: libc::pthread_t = unsafe { libc::pthread_self() };
369 Some(id as u64)
370 }
371 target_vendor = "apple" => {
372 let mut id = 0u64;
374 let status: libc::c_int = unsafe { libc::pthread_threadid_np(0, &mut id) };
376 if status == 0 {
377 Some(id)
378 } else {
379 None
380 }
381 }
382 _ => None,
384 }
385}
386
387#[cfg(any(
388 target_os = "linux",
389 target_os = "nto",
390 target_os = "solaris",
391 target_os = "illumos",
392 target_os = "vxworks",
393 target_os = "cygwin",
394 target_vendor = "apple",
395))]
396fn truncate_cstr<const MAX_WITH_NUL: usize>(cstr: &CStr) -> [libc::c_char; MAX_WITH_NUL] {
397 let mut result = [0; MAX_WITH_NUL];
398 for (src, dst) in cstr.to_bytes().iter().zip(&mut result[..MAX_WITH_NUL - 1]) {
399 *dst = *src as libc::c_char;
400 }
401 result
402}
403
404#[cfg(target_os = "android")]
405pub fn set_name(name: &CStr) {
406 const PR_SET_NAME: libc::c_int = 15;
407 unsafe {
408 let res = libc::prctl(
409 PR_SET_NAME,
410 name.as_ptr(),
411 0 as libc::c_ulong,
412 0 as libc::c_ulong,
413 0 as libc::c_ulong,
414 );
415 debug_assert_eq!(res, 0);
417 }
418}
419
420#[cfg(any(
421 target_os = "linux",
422 target_os = "freebsd",
423 target_os = "dragonfly",
424 target_os = "nuttx",
425 target_os = "cygwin"
426))]
427pub fn set_name(name: &CStr) {
428 unsafe {
429 cfg_select! {
430 any(target_os = "linux", target_os = "cygwin") => {
431 const TASK_COMM_LEN: usize = 16;
433 let name = truncate_cstr::<{ TASK_COMM_LEN }>(name);
434 }
435 _ => {
436 }
438 };
439 let res = libc::pthread_setname_np(libc::pthread_self(), name.as_ptr());
442 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);
444 }
445}
446
447#[cfg(target_os = "openbsd")]
448pub fn set_name(name: &CStr) {
449 unsafe {
450 libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
451 }
452}
453
454#[cfg(target_vendor = "apple")]
455pub fn set_name(name: &CStr) {
456 unsafe {
457 let name = truncate_cstr::<{ libc::MAXTHREADNAMESIZE }>(name);
458 let res = libc::pthread_setname_np(name.as_ptr());
459 debug_assert_eq!(res, 0);
461 }
462}
463
464#[cfg(target_os = "netbsd")]
465pub fn set_name(name: &CStr) {
466 unsafe {
467 let res = libc::pthread_setname_np(
468 libc::pthread_self(),
469 c"%s".as_ptr(),
470 name.as_ptr() as *mut libc::c_void,
471 );
472 debug_assert_eq!(res, 0);
473 }
474}
475
476#[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto"))]
477pub fn set_name(name: &CStr) {
478 weak!(
479 fn pthread_setname_np(thread: libc::pthread_t, name: *const libc::c_char) -> libc::c_int;
480 );
481
482 if let Some(f) = pthread_setname_np.get() {
483 #[cfg(target_os = "nto")]
484 const THREAD_NAME_MAX: usize = libc::_NTO_THREAD_NAME_MAX as usize;
485 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
486 const THREAD_NAME_MAX: usize = 32;
487
488 let name = truncate_cstr::<{ THREAD_NAME_MAX }>(name);
489 let res = unsafe { f(libc::pthread_self(), name.as_ptr()) };
490 debug_assert_eq!(res, 0);
491 }
492}
493
494#[cfg(target_os = "fuchsia")]
495pub fn set_name(name: &CStr) {
496 use crate::sys::pal::fuchsia::*;
497 unsafe {
498 zx_object_set_property(
499 zx_thread_self(),
500 ZX_PROP_NAME,
501 name.as_ptr() as *const libc::c_void,
502 name.to_bytes().len(),
503 );
504 }
505}
506
507#[cfg(target_os = "haiku")]
508pub fn set_name(name: &CStr) {
509 unsafe {
510 let thread_self = libc::find_thread(ptr::null_mut());
511 let res = libc::rename_thread(thread_self, name.as_ptr());
512 debug_assert_eq!(res, libc::B_OK);
514 }
515}
516
517#[cfg(target_os = "vxworks")]
518pub fn set_name(name: &CStr) {
519 let mut name = truncate_cstr::<{ (libc::VX_TASK_RENAME_LENGTH - 1) as usize }>(name);
520 let res = unsafe { libc::taskNameSet(libc::taskIdSelf(), name.as_mut_ptr()) };
521 debug_assert_eq!(res, libc::OK);
522}
523
524#[cfg(not(target_os = "espidf"))]
525pub fn sleep(dur: Duration) {
526 cfg_select! {
527 any(
530 target_os = "freebsd",
531 target_os = "netbsd",
532 target_os = "linux",
533 target_os = "android",
534 target_os = "solaris",
535 target_os = "illumos",
536 target_os = "dragonfly",
537 target_os = "hurd",
538 target_os = "vxworks",
539 target_os = "wasi",
540 ) => {
541 unsafe fn nanosleep(rqtp: *const libc::timespec, rmtp: *mut libc::timespec) -> libc::c_int {
555 unsafe { libc::clock_nanosleep(crate::sys::time::Instant::CLOCK_ID, 0, rqtp, rmtp) }
556 }
557 }
558 _ => {
559 unsafe fn nanosleep(rqtp: *const libc::timespec, rmtp: *mut libc::timespec) -> libc::c_int {
560 let r = unsafe { libc::nanosleep(rqtp, rmtp) };
561 if r == 0 { 0 } else { sys::io::errno() }
564 }
565 }
566 }
567
568 let mut secs = dur.as_secs();
569 let mut nsecs = dur.subsec_nanos() as _;
570
571 unsafe {
574 while secs > 0 || nsecs > 0 {
575 let mut ts = libc::timespec::default();
576 ts.tv_sec = cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t;
577 ts.tv_nsec = nsecs;
578
579 secs -= ts.tv_sec as u64;
580 let ts_ptr = &raw mut ts;
581 let r = nanosleep(ts_ptr, ts_ptr);
582 if r != 0 {
583 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);
584 secs += ts.tv_sec as u64;
585 nsecs = ts.tv_nsec;
586 } else {
587 nsecs = 0;
588 }
589 }
590 }
591}
592
593#[cfg(target_os = "espidf")]
594pub fn sleep(dur: Duration) {
595 const MAX_MICROS: u32 = u32::MAX - 1_000_000 - 1;
605
606 let mut micros = dur.as_micros() + if dur.subsec_nanos() % 1_000 > 0 { 1 } else { 0 };
613
614 while micros > 0 {
615 let st = if micros > MAX_MICROS as u128 { MAX_MICROS } else { micros as u32 };
616 unsafe {
617 libc::usleep(st);
618 }
619
620 micros -= st as u128;
621 }
622}
623
624#[cfg(any(
627 target_os = "freebsd",
628 target_os = "netbsd",
629 target_os = "linux",
630 target_os = "android",
631 target_os = "solaris",
632 target_os = "illumos",
633 target_os = "dragonfly",
634 target_os = "hurd",
635 target_os = "vxworks",
636 target_os = "wasi",
637))]
638pub fn sleep_until(deadline: crate::time::Instant) {
639 use crate::time::Instant;
640
641 #[cfg(all(
642 target_os = "linux",
643 target_env = "gnu",
644 target_pointer_width = "32",
645 not(target_arch = "riscv32")
646 ))]
647 {
648 use crate::sys::pal::time::__timespec64;
649 use crate::sys::pal::weak::weak;
650
651 weak! {
654 fn __clock_nanosleep_time64(
655 clock_id: libc::clockid_t,
656 flags: libc::c_int,
657 req: *const __timespec64,
658 rem: *mut __timespec64,
659 ) -> libc::c_int;
660 }
661
662 if let Some(clock_nanosleep) = __clock_nanosleep_time64.get() {
663 let ts = deadline.into_inner().into_timespec().to_timespec64();
664 loop {
665 let r = unsafe {
666 clock_nanosleep(
667 crate::sys::time::Instant::CLOCK_ID,
668 libc::TIMER_ABSTIME,
669 &ts,
670 core::ptr::null_mut(),
671 )
672 };
673
674 match r {
675 0 => return,
676 libc::EINTR => continue,
677 _ => break,
686 }
687 }
688 }
689 }
690
691 let Some(ts) = deadline.into_inner().into_timespec().to_timespec() else {
692 let now = Instant::now();
696 if let Some(delay) = deadline.checked_duration_since(now) {
697 sleep(delay);
698 }
699 return;
700 };
701
702 unsafe {
703 loop {
705 let res = libc::clock_nanosleep(
706 crate::sys::time::Instant::CLOCK_ID,
707 libc::TIMER_ABSTIME,
708 &ts,
709 core::ptr::null_mut(), );
711
712 if res == 0 {
713 break;
714 } else {
715 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!(
716 res,
717 libc::EINTR,
718 "timespec is in range,
719 clockid is valid and kernel should support it"
720 );
721 }
722 }
723 }
724}
725
726#[cfg(target_vendor = "apple")]
727pub fn sleep_until(deadline: crate::time::Instant) {
728 unsafe extern "C" {
729 safe fn mach_wait_until(deadline: u64) -> libc::kern_return_t;
737 }
738
739 let Some(deadline) = deadline.into_inner().into_mach_absolute_time_ceil() else {
742 return;
745 };
746
747 let deadline = deadline.try_into().unwrap_or(u64::MAX);
750 loop {
751 match mach_wait_until(deadline) {
752 libc::KERN_SUCCESS => break,
754 libc::KERN_ABORTED => continue,
760 error => {
762 let description = unsafe { CStr::from_ptr(libc::mach_error_string(error)) };
763 panic!("mach_wait_until failed: {} (code {error})", description.display())
764 }
765 }
766 }
767}
768
769pub fn yield_now() {
770 let ret = unsafe { libc::sched_yield() };
771 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);
772}
773
774#[cfg(any(target_os = "android", target_os = "linux"))]
775mod cgroups {
776 use crate::borrow::Cow;
782 use crate::ffi::OsString;
783 use crate::fs::{File, exists};
784 use crate::io::{BufRead, Read};
785 use crate::os::unix::ffi::OsStringExt;
786 use crate::path::{Path, PathBuf};
787 use crate::str::from_utf8;
788
789 #[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)]
790 enum Cgroup {
791 V1,
792 V2,
793 }
794
795 pub(super) fn quota() -> usize {
798 let mut quota = usize::MAX;
799 if falsecfg!(miri) {
800 return quota;
803 }
804
805 let _: Option<()> = try {
806 let mut buf = Vec::with_capacity(128);
807 File::open("/proc/self/cgroup").ok()?.read_to_end(&mut buf).ok()?;
809 let (cgroup_path, version) =
810 buf.split(|&c| c == b'\n').fold(None, |previous, line| {
811 let mut fields = line.splitn(3, |&c| c == b':');
812 let version = match fields.nth(1) {
814 Some(b"") => Cgroup::V2,
815 Some(controllers)
816 if from_utf8(controllers)
817 .is_ok_and(|c| c.split(',').any(|c| c == "cpu")) =>
818 {
819 Cgroup::V1
820 }
821 _ => return previous,
822 };
823
824 if previous.is_some() && version == Cgroup::V2 {
826 return previous;
827 }
828
829 let path = fields.last()?;
830 Some((path[1..].to_owned(), version))
832 })?;
833 let cgroup_path = PathBuf::from(OsString::from_vec(cgroup_path));
834
835 quota = match version {
836 Cgroup::V1 => quota_v1(cgroup_path),
837 Cgroup::V2 => quota_v2(cgroup_path),
838 };
839 };
840
841 quota
842 }
843
844 fn quota_v2(group_path: PathBuf) -> usize {
845 let mut quota = usize::MAX;
846
847 let mut path = PathBuf::with_capacity(128);
848 let mut read_buf = String::with_capacity(20);
849
850 let cgroup_mount = "/sys/fs/cgroup";
852
853 path.push(cgroup_mount);
854 path.push(&group_path);
855
856 path.push("cgroup.controllers");
857
858 if #[allow(non_exhaustive_omitted_patterns)] match exists(&path) {
Err(_) | Ok(false) => true,
_ => false,
}matches!(exists(&path), Err(_) | Ok(false)) {
860 return usize::MAX;
861 };
862
863 path.pop();
864
865 let _: Option<()> = try {
866 while path.starts_with(cgroup_mount) {
867 path.push("cpu.max");
868
869 read_buf.clear();
870
871 if File::open(&path).and_then(|mut f| f.read_to_string(&mut read_buf)).is_ok() {
872 let raw_quota = read_buf.lines().next()?;
873 let mut raw_quota = raw_quota.split(' ');
874 let limit = raw_quota.next()?;
875 let period = raw_quota.next()?;
876 match (limit.parse::<usize>(), period.parse::<usize>()) {
877 (Ok(limit), Ok(period)) if period > 0 => {
878 quota = quota.min(limit / period);
879 }
880 _ => {}
881 }
882 }
883
884 path.pop(); path.pop(); }
887 };
888
889 quota
890 }
891
892 fn quota_v1(group_path: PathBuf) -> usize {
893 let mut quota = usize::MAX;
894 let mut path = PathBuf::with_capacity(128);
895 let mut read_buf = String::with_capacity(20);
896
897 let mounts: &[fn(&Path) -> Option<(_, &Path)>] = &[
900 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu"), p)),
901 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu,cpuacct"), p)),
902 find_mountpoint,
906 ];
907
908 for mount in mounts {
909 let Some((mount, group_path)) = mount(&group_path) else { continue };
910
911 path.clear();
912 path.push(mount.as_ref());
913 path.push(&group_path);
914
915 if #[allow(non_exhaustive_omitted_patterns)] match exists(&path) {
Err(_) | Ok(false) => true,
_ => false,
}matches!(exists(&path), Err(_) | Ok(false)) {
917 continue;
918 }
919
920 while path.starts_with(mount.as_ref()) {
921 let mut parse_file = |name| {
922 path.push(name);
923 read_buf.clear();
924
925 let f = File::open(&path);
926 path.pop(); f.ok()?.read_to_string(&mut read_buf).ok()?;
928 let parsed = read_buf.trim().parse::<usize>().ok()?;
929
930 Some(parsed)
931 };
932
933 let limit = parse_file("cpu.cfs_quota_us");
934 let period = parse_file("cpu.cfs_period_us");
935
936 match (limit, period) {
937 (Some(limit), Some(period)) if period > 0 => quota = quota.min(limit / period),
938 _ => {}
939 }
940
941 path.pop();
942 }
943
944 break;
947 }
948
949 quota
950 }
951
952 fn find_mountpoint(group_path: &Path) -> Option<(Cow<'static, str>, &Path)> {
957 let mut reader = File::open_buffered("/proc/self/mountinfo").ok()?;
958 let mut line = String::with_capacity(256);
959 loop {
960 line.clear();
961 if reader.read_line(&mut line).ok()? == 0 {
962 break;
963 }
964
965 let line = line.trim();
966 let mut items = line.split(' ');
967
968 let sub_path = items.nth(3)?;
969 let mount_point = items.next()?;
970 let mount_opts = items.next_back()?;
971 let filesystem_type = items.nth_back(1)?;
972
973 if filesystem_type != "cgroup" || !mount_opts.split(',').any(|opt| opt == "cpu") {
974 continue;
976 }
977
978 let sub_path = Path::new(sub_path).strip_prefix("/").ok()?;
979
980 if !group_path.starts_with(sub_path) {
981 continue;
984 }
985
986 let trimmed_group_path = group_path.strip_prefix(sub_path).ok()?;
987
988 return Some((Cow::Owned(mount_point.to_owned()), trimmed_group_path));
989 }
990
991 None
992 }
993}
994
995#[cfg(all(target_os = "linux", target_env = "gnu"))]
1001unsafe fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
1002 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!(
1006 fn __pthread_get_minstack(attr: *const libc::pthread_attr_t) -> libc::size_t;
1007 );
1008
1009 match __pthread_get_minstack.get() {
1010 None => libc::PTHREAD_STACK_MIN,
1011 Some(f) => unsafe { f(attr) },
1012 }
1013}
1014
1015#[cfg(all(
1017 not(all(target_os = "linux", target_env = "gnu")),
1018 not(any(target_os = "netbsd", target_os = "nuttx"))
1019))]
1020unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
1021 libc::PTHREAD_STACK_MIN
1022}
1023
1024#[cfg(any(target_os = "netbsd", target_os = "nuttx"))]
1025unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
1026 static STACK: crate::sync::OnceLock<usize> = crate::sync::OnceLock::new();
1027
1028 *STACK.get_or_init(|| {
1029 let mut stack = unsafe { libc::sysconf(libc::_SC_THREAD_STACK_MIN) };
1030 if stack < 0 {
1031 stack = 2048; }
1033
1034 stack as usize
1035 })
1036}