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 if cfg!(all(target_os = "wasi", not(target_feature = "atomics"))) {
53 return Err(io::Error::UNSUPPORTED_PLATFORM);
54 }
55
56 let data = init;
57 let mut attr: mem::MaybeUninit<libc::pthread_attr_t> = mem::MaybeUninit::uninit();
58 assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0);
59 let mut attr = DropGuard::new(&mut attr, |attr| {
60 assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0)
61 });
62
63 #[cfg(any(target_os = "espidf", target_os = "nuttx"))]
64 if stack > 0 {
65 assert_eq!(
68 libc::pthread_attr_setstacksize(
69 attr.as_mut_ptr(),
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.as_ptr()));
79
80 match libc::pthread_attr_setstacksize(attr.as_mut_ptr(), stack_size) {
81 0 => {}
82 n => {
83 assert_eq!(n, libc::EINVAL);
84 let page_size = sys::os::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.as_mut_ptr(), stack_size) != 0 {
96 return Err(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.as_ptr(), 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 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 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 ) => {
168 #[allow(unused_assignments)]
169 #[allow(unused_mut)]
170 let mut quota = usize::MAX;
171
172 #[cfg(any(target_os = "android", target_os = "linux"))]
173 {
174 quota = cgroups::quota().max(1);
175 let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
176 unsafe {
177 if libc::sched_getaffinity(0, size_of::<libc::cpu_set_t>(), &mut set) == 0 {
178 let count = libc::CPU_COUNT(&set) as usize;
179 let count = count.min(quota);
180
181 if let Some(count) = NonZero::new(count) {
186 return Ok(count)
187 }
188 }
189 }
190 }
191 match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
192 -1 => Err(io::Error::last_os_error()),
193 0 => Err(io::Error::UNKNOWN_THREAD_COUNT),
194 cpus => {
195 let count = cpus as usize;
196 let count = count.min(quota);
198 Ok(unsafe { NonZero::new_unchecked(count) })
199 }
200 }
201 }
202 any(
203 target_os = "freebsd",
204 target_os = "dragonfly",
205 target_os = "openbsd",
206 target_os = "netbsd",
207 ) => {
208 use crate::ptr;
209
210 #[cfg(target_os = "freebsd")]
211 {
212 let mut set: libc::cpuset_t = unsafe { mem::zeroed() };
213 unsafe {
214 if libc::cpuset_getaffinity(
215 libc::CPU_LEVEL_WHICH,
216 libc::CPU_WHICH_PID,
217 -1,
218 size_of::<libc::cpuset_t>(),
219 &mut set,
220 ) == 0 {
221 let count = libc::CPU_COUNT(&set) as usize;
222 if count > 0 {
223 return Ok(NonZero::new_unchecked(count));
224 }
225 }
226 }
227 }
228
229 #[cfg(target_os = "netbsd")]
230 {
231 unsafe {
232 let set = libc::_cpuset_create();
233 if !set.is_null() {
234 let mut count: usize = 0;
235 if libc::pthread_getaffinity_np(libc::pthread_self(), libc::_cpuset_size(set), set) == 0 {
236 for i in 0..libc::cpuid_t::MAX {
237 match libc::_cpuset_isset(i, set) {
238 -1 => break,
239 0 => continue,
240 _ => count = count + 1,
241 }
242 }
243 }
244 libc::_cpuset_destroy(set);
245 if let Some(count) = NonZero::new(count) {
246 return Ok(count);
247 }
248 }
249 }
250 }
251
252 let mut cpus: libc::c_uint = 0;
253 let mut cpus_size = size_of_val(&cpus);
254
255 unsafe {
256 cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint;
257 }
258
259 if cpus < 1 {
261 let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
262 let res = unsafe {
263 libc::sysctl(
264 mib.as_mut_ptr(),
265 2,
266 (&raw mut cpus) as *mut _,
267 (&raw mut cpus_size) as *mut _,
268 ptr::null_mut(),
269 0,
270 )
271 };
272
273 if res == -1 {
275 return Err(io::Error::last_os_error());
276 } else if cpus == 0 {
277 return Err(io::Error::UNKNOWN_THREAD_COUNT);
278 }
279 }
280
281 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
282 }
283 target_os = "nto" => {
284 unsafe {
285 use libc::_syspage_ptr;
286 if _syspage_ptr.is_null() {
287 Err(io::const_error!(io::ErrorKind::NotFound, "no syspage available"))
288 } else {
289 let cpus = (*_syspage_ptr).num_cpu;
290 NonZero::new(cpus as usize)
291 .ok_or(io::Error::UNKNOWN_THREAD_COUNT)
292 }
293 }
294 }
295 any(target_os = "solaris", target_os = "illumos") => {
296 let mut cpus = 0u32;
297 if unsafe { libc::pset_info(libc::PS_MYID, core::ptr::null_mut(), &mut cpus, core::ptr::null_mut()) } != 0 {
298 return Err(io::Error::UNKNOWN_THREAD_COUNT);
299 }
300 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
301 }
302 target_os = "haiku" => {
303 unsafe {
306 let mut sinfo: libc::system_info = crate::mem::zeroed();
307 let res = libc::get_system_info(&mut sinfo);
308
309 if res != libc::B_OK {
310 return Err(io::Error::UNKNOWN_THREAD_COUNT);
311 }
312
313 Ok(NonZero::new_unchecked(sinfo.cpu_count as usize))
314 }
315 }
316 target_os = "vxworks" => {
317 unsafe{
322 let set = libc::vxCpuEnabledGet();
323 Ok(NonZero::new_unchecked(set.count_ones() as usize))
324 }
325 }
326 _ => {
327 Err(io::const_error!(io::ErrorKind::Unsupported, "getting the number of hardware threads is not supported on the target platform"))
329 }
330 }
331}
332
333pub fn current_os_id() -> Option<u64> {
334 cfg_select! {
340 any(target_os = "android", target_os = "linux") => {
342 use crate::sys::pal::weak::syscall;
343
344 syscall!(fn gettid() -> libc::pid_t;);
347
348 let id: libc::pid_t = unsafe { gettid() };
350 Some(id as u64)
351 }
352 target_os = "nto" => {
353 let id: libc::pid_t = unsafe { libc::gettid() };
355 Some(id as u64)
356 }
357 target_os = "openbsd" => {
358 let id: libc::pid_t = unsafe { libc::getthrid() };
360 Some(id as u64)
361 }
362 target_os = "freebsd" => {
363 let id: libc::c_int = unsafe { libc::pthread_getthreadid_np() };
365 Some(id as u64)
366 }
367 target_os = "netbsd" => {
368 let id: libc::lwpid_t = unsafe { libc::_lwp_self() };
370 Some(id as u64)
371 }
372 any(target_os = "illumos", target_os = "solaris") => {
373 let id: libc::pthread_t = unsafe { libc::pthread_self() };
376 Some(id as u64)
377 }
378 target_vendor = "apple" => {
379 let mut id = 0u64;
381 let status: libc::c_int = unsafe { libc::pthread_threadid_np(0, &mut id) };
383 if status == 0 {
384 Some(id)
385 } else {
386 None
387 }
388 }
389 _ => None,
391 }
392}
393
394#[cfg(any(
395 target_os = "linux",
396 target_os = "nto",
397 target_os = "solaris",
398 target_os = "illumos",
399 target_os = "vxworks",
400 target_os = "cygwin",
401 target_vendor = "apple",
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 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 unsafe {
474 let res = libc::pthread_setname_np(
475 libc::pthread_self(),
476 c"%s".as_ptr(),
477 name.as_ptr() as *mut libc::c_void,
478 );
479 debug_assert_eq!(res, 0);
480 }
481}
482
483#[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto"))]
484pub fn set_name(name: &CStr) {
485 weak!(
486 fn pthread_setname_np(thread: libc::pthread_t, name: *const libc::c_char) -> libc::c_int;
487 );
488
489 if let Some(f) = pthread_setname_np.get() {
490 #[cfg(target_os = "nto")]
491 const THREAD_NAME_MAX: usize = libc::_NTO_THREAD_NAME_MAX as usize;
492 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
493 const THREAD_NAME_MAX: usize = 32;
494
495 let name = truncate_cstr::<{ THREAD_NAME_MAX }>(name);
496 let res = unsafe { f(libc::pthread_self(), name.as_ptr()) };
497 debug_assert_eq!(res, 0);
498 }
499}
500
501#[cfg(target_os = "fuchsia")]
502pub fn set_name(name: &CStr) {
503 use crate::sys::pal::fuchsia::*;
504 unsafe {
505 zx_object_set_property(
506 zx_thread_self(),
507 ZX_PROP_NAME,
508 name.as_ptr() as *const libc::c_void,
509 name.to_bytes().len(),
510 );
511 }
512}
513
514#[cfg(target_os = "haiku")]
515pub fn set_name(name: &CStr) {
516 unsafe {
517 let thread_self = libc::find_thread(ptr::null_mut());
518 let res = libc::rename_thread(thread_self, name.as_ptr());
519 debug_assert_eq!(res, libc::B_OK);
521 }
522}
523
524#[cfg(target_os = "vxworks")]
525pub fn set_name(name: &CStr) {
526 let mut name = truncate_cstr::<{ (libc::VX_TASK_RENAME_LENGTH - 1) as usize }>(name);
527 let res = unsafe { libc::taskNameSet(libc::taskIdSelf(), name.as_mut_ptr()) };
528 debug_assert_eq!(res, libc::OK);
529}
530
531#[cfg(not(any(target_os = "espidf", target_os = "wasi")))]
532pub fn sleep(dur: Duration) {
533 let mut secs = dur.as_secs();
534 let mut nsecs = dur.subsec_nanos() as _;
535
536 unsafe {
539 while secs > 0 || nsecs > 0 {
540 let mut ts = libc::timespec {
541 tv_sec: cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t,
542 tv_nsec: nsecs,
543 };
544 secs -= ts.tv_sec as u64;
545 let ts_ptr = &raw mut ts;
546 if libc::nanosleep(ts_ptr, ts_ptr) == -1 {
547 assert_eq!(sys::io::errno(), libc::EINTR);
548 secs += ts.tv_sec as u64;
549 nsecs = ts.tv_nsec;
550 } else {
551 nsecs = 0;
552 }
553 }
554 }
555}
556
557#[cfg(any(
558 target_os = "espidf",
559 target_os = "wasi",
563))]
564pub fn sleep(dur: Duration) {
565 const MAX_MICROS: u32 = u32::MAX - 1_000_000 - 1;
575
576 let mut micros = dur.as_micros() + if dur.subsec_nanos() % 1_000 > 0 { 1 } else { 0 };
583
584 while micros > 0 {
585 let st = if micros > MAX_MICROS as u128 { MAX_MICROS } else { micros as u32 };
586 unsafe {
587 libc::usleep(st);
588 }
589
590 micros -= st as u128;
591 }
592}
593
594#[cfg(any(
597 target_os = "freebsd",
598 target_os = "netbsd",
599 target_os = "linux",
600 target_os = "android",
601 target_os = "solaris",
602 target_os = "illumos",
603 target_os = "dragonfly",
604 target_os = "hurd",
605 target_os = "fuchsia",
606 target_os = "vxworks",
607 target_os = "wasi",
608))]
609pub fn sleep_until(deadline: crate::time::Instant) {
610 use crate::time::Instant;
611
612 let Some(ts) = deadline.into_inner().into_timespec().to_timespec() else {
613 let now = Instant::now();
617 if let Some(delay) = deadline.checked_duration_since(now) {
618 sleep(delay);
619 }
620 return;
621 };
622
623 unsafe {
624 loop {
626 let res = libc::clock_nanosleep(
627 crate::sys::time::Instant::CLOCK_ID,
628 libc::TIMER_ABSTIME,
629 &ts,
630 core::ptr::null_mut(), );
632
633 if res == 0 {
634 break;
635 } else {
636 assert_eq!(
637 res,
638 libc::EINTR,
639 "timespec is in range,
640 clockid is valid and kernel should support it"
641 );
642 }
643 }
644 }
645}
646
647#[cfg(target_vendor = "apple")]
648pub fn sleep_until(deadline: crate::time::Instant) {
649 unsafe extern "C" {
650 safe fn mach_wait_until(deadline: u64) -> libc::kern_return_t;
658 }
659
660 let Some(deadline) = deadline.into_inner().into_mach_absolute_time_ceil() else {
663 return;
666 };
667
668 let deadline = deadline.try_into().unwrap_or(u64::MAX);
671 loop {
672 match mach_wait_until(deadline) {
673 libc::KERN_SUCCESS => break,
675 libc::KERN_ABORTED => continue,
681 error => {
683 let description = unsafe { CStr::from_ptr(libc::mach_error_string(error)) };
684 panic!("mach_wait_until failed: {} (code {error})", description.display())
685 }
686 }
687 }
688}
689
690pub fn yield_now() {
691 let ret = unsafe { libc::sched_yield() };
692 debug_assert_eq!(ret, 0);
693}
694
695#[cfg(any(target_os = "android", target_os = "linux"))]
696mod cgroups {
697 use crate::borrow::Cow;
703 use crate::ffi::OsString;
704 use crate::fs::{File, exists};
705 use crate::io::{BufRead, Read};
706 use crate::os::unix::ffi::OsStringExt;
707 use crate::path::{Path, PathBuf};
708 use crate::str::from_utf8;
709
710 #[derive(PartialEq)]
711 enum Cgroup {
712 V1,
713 V2,
714 }
715
716 pub(super) fn quota() -> usize {
719 let mut quota = usize::MAX;
720 if cfg!(miri) {
721 return quota;
724 }
725
726 let _: Option<()> = try {
727 let mut buf = Vec::with_capacity(128);
728 File::open("/proc/self/cgroup").ok()?.read_to_end(&mut buf).ok()?;
730 let (cgroup_path, version) =
731 buf.split(|&c| c == b'\n').fold(None, |previous, line| {
732 let mut fields = line.splitn(3, |&c| c == b':');
733 let version = match fields.nth(1) {
735 Some(b"") => Cgroup::V2,
736 Some(controllers)
737 if from_utf8(controllers)
738 .is_ok_and(|c| c.split(',').any(|c| c == "cpu")) =>
739 {
740 Cgroup::V1
741 }
742 _ => return previous,
743 };
744
745 if previous.is_some() && version == Cgroup::V2 {
747 return previous;
748 }
749
750 let path = fields.last()?;
751 Some((path[1..].to_owned(), version))
753 })?;
754 let cgroup_path = PathBuf::from(OsString::from_vec(cgroup_path));
755
756 quota = match version {
757 Cgroup::V1 => quota_v1(cgroup_path),
758 Cgroup::V2 => quota_v2(cgroup_path),
759 };
760 };
761
762 quota
763 }
764
765 fn quota_v2(group_path: PathBuf) -> usize {
766 let mut quota = usize::MAX;
767
768 let mut path = PathBuf::with_capacity(128);
769 let mut read_buf = String::with_capacity(20);
770
771 let cgroup_mount = "/sys/fs/cgroup";
773
774 path.push(cgroup_mount);
775 path.push(&group_path);
776
777 path.push("cgroup.controllers");
778
779 if matches!(exists(&path), Err(_) | Ok(false)) {
781 return usize::MAX;
782 };
783
784 path.pop();
785
786 let _: Option<()> = try {
787 while path.starts_with(cgroup_mount) {
788 path.push("cpu.max");
789
790 read_buf.clear();
791
792 if File::open(&path).and_then(|mut f| f.read_to_string(&mut read_buf)).is_ok() {
793 let raw_quota = read_buf.lines().next()?;
794 let mut raw_quota = raw_quota.split(' ');
795 let limit = raw_quota.next()?;
796 let period = raw_quota.next()?;
797 match (limit.parse::<usize>(), period.parse::<usize>()) {
798 (Ok(limit), Ok(period)) if period > 0 => {
799 quota = quota.min(limit / period);
800 }
801 _ => {}
802 }
803 }
804
805 path.pop(); path.pop(); }
808 };
809
810 quota
811 }
812
813 fn quota_v1(group_path: PathBuf) -> usize {
814 let mut quota = usize::MAX;
815 let mut path = PathBuf::with_capacity(128);
816 let mut read_buf = String::with_capacity(20);
817
818 let mounts: &[fn(&Path) -> Option<(_, &Path)>] = &[
821 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu"), p)),
822 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu,cpuacct"), p)),
823 find_mountpoint,
827 ];
828
829 for mount in mounts {
830 let Some((mount, group_path)) = mount(&group_path) else { continue };
831
832 path.clear();
833 path.push(mount.as_ref());
834 path.push(&group_path);
835
836 if matches!(exists(&path), Err(_) | Ok(false)) {
838 continue;
839 }
840
841 while path.starts_with(mount.as_ref()) {
842 let mut parse_file = |name| {
843 path.push(name);
844 read_buf.clear();
845
846 let f = File::open(&path);
847 path.pop(); f.ok()?.read_to_string(&mut read_buf).ok()?;
849 let parsed = read_buf.trim().parse::<usize>().ok()?;
850
851 Some(parsed)
852 };
853
854 let limit = parse_file("cpu.cfs_quota_us");
855 let period = parse_file("cpu.cfs_period_us");
856
857 match (limit, period) {
858 (Some(limit), Some(period)) if period > 0 => quota = quota.min(limit / period),
859 _ => {}
860 }
861
862 path.pop();
863 }
864
865 break;
868 }
869
870 quota
871 }
872
873 fn find_mountpoint(group_path: &Path) -> Option<(Cow<'static, str>, &Path)> {
878 let mut reader = File::open_buffered("/proc/self/mountinfo").ok()?;
879 let mut line = String::with_capacity(256);
880 loop {
881 line.clear();
882 if reader.read_line(&mut line).ok()? == 0 {
883 break;
884 }
885
886 let line = line.trim();
887 let mut items = line.split(' ');
888
889 let sub_path = items.nth(3)?;
890 let mount_point = items.next()?;
891 let mount_opts = items.next_back()?;
892 let filesystem_type = items.nth_back(1)?;
893
894 if filesystem_type != "cgroup" || !mount_opts.split(',').any(|opt| opt == "cpu") {
895 continue;
897 }
898
899 let sub_path = Path::new(sub_path).strip_prefix("/").ok()?;
900
901 if !group_path.starts_with(sub_path) {
902 continue;
905 }
906
907 let trimmed_group_path = group_path.strip_prefix(sub_path).ok()?;
908
909 return Some((Cow::Owned(mount_point.to_owned()), trimmed_group_path));
910 }
911
912 None
913 }
914}
915
916#[cfg(all(target_os = "linux", target_env = "gnu"))]
922unsafe fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
923 dlsym!(
927 fn __pthread_get_minstack(attr: *const libc::pthread_attr_t) -> libc::size_t;
928 );
929
930 match __pthread_get_minstack.get() {
931 None => libc::PTHREAD_STACK_MIN,
932 Some(f) => unsafe { f(attr) },
933 }
934}
935
936#[cfg(all(
938 not(all(target_os = "linux", target_env = "gnu")),
939 not(any(target_os = "netbsd", target_os = "nuttx"))
940))]
941unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
942 libc::PTHREAD_STACK_MIN
943}
944
945#[cfg(any(target_os = "netbsd", target_os = "nuttx"))]
946unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
947 static STACK: crate::sync::OnceLock<usize> = crate::sync::OnceLock::new();
948
949 *STACK.get_or_init(|| {
950 let mut stack = unsafe { libc::sysconf(libc::_SC_THREAD_STACK_MIN) };
951 if stack < 0 {
952 stack = 2048; }
954
955 stack as usize
956 })
957}