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)))]
9use crate::ffi::CStr;
10use crate::mem::{self, ManuallyDrop};
11use crate::num::NonZero;
12#[cfg(all(target_os = "linux", target_env = "gnu"))]
13use crate::sys::weak::dlsym;
14#[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto",))]
15use crate::sys::weak::weak;
16use crate::sys::{os, stack_overflow};
17use crate::time::Duration;
18use crate::{cmp, io, ptr};
19#[cfg(not(any(
20 target_os = "l4re",
21 target_os = "vxworks",
22 target_os = "espidf",
23 target_os = "nuttx"
24)))]
25pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
26#[cfg(target_os = "l4re")]
27pub const DEFAULT_MIN_STACK_SIZE: usize = 1024 * 1024;
28#[cfg(target_os = "vxworks")]
29pub const DEFAULT_MIN_STACK_SIZE: usize = 256 * 1024;
30#[cfg(any(target_os = "espidf", target_os = "nuttx"))]
31pub const DEFAULT_MIN_STACK_SIZE: usize = 0; struct ThreadData {
34 name: Option<Box<str>>,
35 f: Box<dyn FnOnce()>,
36}
37
38pub struct Thread {
39 id: libc::pthread_t,
40}
41
42unsafe impl Send for Thread {}
45unsafe impl Sync for Thread {}
46
47impl Thread {
48 #[cfg_attr(miri, track_caller)] pub unsafe fn new(
51 stack: usize,
52 name: Option<&str>,
53 f: Box<dyn FnOnce()>,
54 ) -> io::Result<Thread> {
55 let data = Box::into_raw(Box::new(ThreadData { name: name.map(Box::from), f }));
56 let mut native: libc::pthread_t = mem::zeroed();
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
60 #[cfg(any(target_os = "espidf", target_os = "nuttx"))]
61 if stack > 0 {
62 assert_eq!(
65 libc::pthread_attr_setstacksize(
66 attr.as_mut_ptr(),
67 cmp::max(stack, min_stack_size(attr.as_ptr()))
68 ),
69 0
70 );
71 }
72
73 #[cfg(not(any(target_os = "espidf", target_os = "nuttx")))]
74 {
75 let stack_size = cmp::max(stack, min_stack_size(attr.as_ptr()));
76
77 match libc::pthread_attr_setstacksize(attr.as_mut_ptr(), stack_size) {
78 0 => {}
79 n => {
80 assert_eq!(n, libc::EINVAL);
81 let page_size = os::page_size();
86 let stack_size =
87 (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1);
88
89 if libc::pthread_attr_setstacksize(attr.as_mut_ptr(), stack_size) != 0 {
93 assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0);
94 drop(Box::from_raw(data));
95 return Err(io::const_error!(
96 io::ErrorKind::InvalidInput,
97 "invalid stack size"
98 ));
99 }
100 }
101 };
102 }
103
104 let ret = libc::pthread_create(&mut native, attr.as_ptr(), thread_start, data as *mut _);
105 assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0);
109
110 return if ret != 0 {
111 drop(Box::from_raw(data));
114 Err(io::Error::from_raw_os_error(ret))
115 } else {
116 Ok(Thread { id: native })
117 };
118
119 extern "C" fn thread_start(data: *mut libc::c_void) -> *mut libc::c_void {
120 unsafe {
121 let data = Box::from_raw(data as *mut ThreadData);
122 let _handler = stack_overflow::Handler::new(data.name);
125 (data.f)();
127 }
128 ptr::null_mut()
129 }
130 }
131
132 pub fn join(self) {
133 let id = self.into_id();
134 let ret = unsafe { libc::pthread_join(id, ptr::null_mut()) };
135 assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
136 }
137
138 pub fn id(&self) -> libc::pthread_t {
139 self.id
140 }
141
142 pub fn into_id(self) -> libc::pthread_t {
143 ManuallyDrop::new(self).id
144 }
145}
146
147impl Drop for Thread {
148 fn drop(&mut self) {
149 let ret = unsafe { libc::pthread_detach(self.id) };
150 debug_assert_eq!(ret, 0);
151 }
152}
153
154pub fn available_parallelism() -> io::Result<NonZero<usize>> {
155 cfg_select! {
156 any(
157 target_os = "android",
158 target_os = "emscripten",
159 target_os = "fuchsia",
160 target_os = "hurd",
161 target_os = "linux",
162 target_os = "aix",
163 target_vendor = "apple",
164 target_os = "cygwin",
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 target_os = "nto" => {
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 extern "C" {
318 fn vxCpuEnabledGet() -> libc::cpuset_t;
319 }
320
321 unsafe{
323 let set = vxCpuEnabledGet();
324 Ok(NonZero::new_unchecked(set.count_ones() as usize))
325 }
326 }
327 _ => {
328 Err(io::const_error!(io::ErrorKind::Unsupported, "getting the number of hardware threads is not supported on the target platform"))
330 }
331 }
332}
333
334pub fn current_os_id() -> Option<u64> {
335 cfg_select! {
341 any(target_os = "android", target_os = "linux") => {
343 use crate::sys::pal::weak::syscall;
344
345 syscall!(fn gettid() -> libc::pid_t;);
348
349 let id: libc::pid_t = unsafe { gettid() };
351 Some(id as u64)
352 }
353 target_os = "nto" => {
354 let id: libc::pid_t = unsafe { libc::gettid() };
356 Some(id as u64)
357 }
358 target_os = "openbsd" => {
359 let id: libc::pid_t = unsafe { libc::getthrid() };
361 Some(id as u64)
362 }
363 target_os = "freebsd" => {
364 let id: libc::c_int = unsafe { libc::pthread_getthreadid_np() };
366 Some(id as u64)
367 }
368 target_os = "netbsd" => {
369 let id: libc::lwpid_t = unsafe { libc::_lwp_self() };
371 Some(id as u64)
372 }
373 any(target_os = "illumos", target_os = "solaris") => {
374 let id: libc::pthread_t = unsafe { libc::pthread_self() };
377 Some(id as u64)
378 }
379 target_vendor = "apple" => {
380 let mut id = 0u64;
382 let status: libc::c_int = unsafe { libc::pthread_threadid_np(0, &mut id) };
384 if status == 0 {
385 Some(id)
386 } else {
387 None
388 }
389 }
390 _ => None,
392 }
393}
394
395#[cfg(any(
396 target_os = "linux",
397 target_os = "nto",
398 target_os = "solaris",
399 target_os = "illumos",
400 target_os = "vxworks",
401 target_os = "cygwin",
402 target_vendor = "apple",
403))]
404fn truncate_cstr<const MAX_WITH_NUL: usize>(cstr: &CStr) -> [libc::c_char; MAX_WITH_NUL] {
405 let mut result = [0; MAX_WITH_NUL];
406 for (src, dst) in cstr.to_bytes().iter().zip(&mut result[..MAX_WITH_NUL - 1]) {
407 *dst = *src as libc::c_char;
408 }
409 result
410}
411
412#[cfg(target_os = "android")]
413pub fn set_name(name: &CStr) {
414 const PR_SET_NAME: libc::c_int = 15;
415 unsafe {
416 let res = libc::prctl(
417 PR_SET_NAME,
418 name.as_ptr(),
419 0 as libc::c_ulong,
420 0 as libc::c_ulong,
421 0 as libc::c_ulong,
422 );
423 debug_assert_eq!(res, 0);
425 }
426}
427
428#[cfg(any(
429 target_os = "linux",
430 target_os = "freebsd",
431 target_os = "dragonfly",
432 target_os = "nuttx",
433 target_os = "cygwin"
434))]
435pub fn set_name(name: &CStr) {
436 unsafe {
437 cfg_select! {
438 any(target_os = "linux", target_os = "cygwin") => {
439 const TASK_COMM_LEN: usize = 16;
441 let name = truncate_cstr::<{ TASK_COMM_LEN }>(name);
442 }
443 _ => {
444 }
446 };
447 let res = libc::pthread_setname_np(libc::pthread_self(), name.as_ptr());
450 debug_assert_eq!(res, 0);
452 }
453}
454
455#[cfg(target_os = "openbsd")]
456pub fn set_name(name: &CStr) {
457 unsafe {
458 libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
459 }
460}
461
462#[cfg(target_vendor = "apple")]
463pub fn set_name(name: &CStr) {
464 unsafe {
465 let name = truncate_cstr::<{ libc::MAXTHREADNAMESIZE }>(name);
466 let res = libc::pthread_setname_np(name.as_ptr());
467 debug_assert_eq!(res, 0);
469 }
470}
471
472#[cfg(target_os = "netbsd")]
473pub fn set_name(name: &CStr) {
474 unsafe {
475 let res = libc::pthread_setname_np(
476 libc::pthread_self(),
477 c"%s".as_ptr(),
478 name.as_ptr() as *mut libc::c_void,
479 );
480 debug_assert_eq!(res, 0);
481 }
482}
483
484#[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto"))]
485pub fn set_name(name: &CStr) {
486 weak!(
487 fn pthread_setname_np(thread: libc::pthread_t, name: *const libc::c_char) -> libc::c_int;
488 );
489
490 if let Some(f) = pthread_setname_np.get() {
491 #[cfg(target_os = "nto")]
492 const THREAD_NAME_MAX: usize = libc::_NTO_THREAD_NAME_MAX as usize;
493 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
494 const THREAD_NAME_MAX: usize = 32;
495
496 let name = truncate_cstr::<{ THREAD_NAME_MAX }>(name);
497 let res = unsafe { f(libc::pthread_self(), name.as_ptr()) };
498 debug_assert_eq!(res, 0);
499 }
500}
501
502#[cfg(target_os = "fuchsia")]
503pub fn set_name(name: &CStr) {
504 use crate::sys::pal::fuchsia::*;
505 unsafe {
506 zx_object_set_property(
507 zx_thread_self(),
508 ZX_PROP_NAME,
509 name.as_ptr() as *const libc::c_void,
510 name.to_bytes().len(),
511 );
512 }
513}
514
515#[cfg(target_os = "haiku")]
516pub fn set_name(name: &CStr) {
517 unsafe {
518 let thread_self = libc::find_thread(ptr::null_mut());
519 let res = libc::rename_thread(thread_self, name.as_ptr());
520 debug_assert_eq!(res, libc::B_OK);
522 }
523}
524
525#[cfg(target_os = "vxworks")]
526pub fn set_name(name: &CStr) {
527 let mut name = truncate_cstr::<{ (libc::VX_TASK_RENAME_LENGTH - 1) as usize }>(name);
528 let res = unsafe { libc::taskNameSet(libc::taskIdSelf(), name.as_mut_ptr()) };
529 debug_assert_eq!(res, libc::OK);
530}
531
532#[cfg(not(target_os = "espidf"))]
533pub fn sleep(dur: Duration) {
534 let mut secs = dur.as_secs();
535 let mut nsecs = dur.subsec_nanos() as _;
536
537 unsafe {
540 while secs > 0 || nsecs > 0 {
541 let mut ts = libc::timespec {
542 tv_sec: cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t,
543 tv_nsec: nsecs,
544 };
545 secs -= ts.tv_sec as u64;
546 let ts_ptr = &raw mut ts;
547 if libc::nanosleep(ts_ptr, ts_ptr) == -1 {
548 assert_eq!(os::errno(), libc::EINTR);
549 secs += ts.tv_sec as u64;
550 nsecs = ts.tv_nsec;
551 } else {
552 nsecs = 0;
553 }
554 }
555 }
556}
557
558#[cfg(target_os = "espidf")]
559pub fn sleep(dur: Duration) {
560 const MAX_MICROS: u32 = u32::MAX - 1_000_000 - 1;
570
571 let mut micros = dur.as_micros() + if dur.subsec_nanos() % 1_000 > 0 { 1 } else { 0 };
578
579 while micros > 0 {
580 let st = if micros > MAX_MICROS as u128 { MAX_MICROS } else { micros as u32 };
581 unsafe {
582 libc::usleep(st);
583 }
584
585 micros -= st as u128;
586 }
587}
588
589#[cfg(any(
592 target_os = "freebsd",
593 target_os = "netbsd",
594 target_os = "linux",
595 target_os = "android",
596 target_os = "solaris",
597 target_os = "illumos",
598 target_os = "dragonfly",
599 target_os = "hurd",
600 target_os = "fuchsia",
601 target_os = "vxworks",
602))]
603pub fn sleep_until(deadline: crate::time::Instant) {
604 use crate::time::Instant;
605
606 let Some(ts) = deadline.into_inner().into_timespec().to_timespec() else {
607 let now = Instant::now();
611 if let Some(delay) = deadline.checked_duration_since(now) {
612 sleep(delay);
613 }
614 return;
615 };
616
617 unsafe {
618 loop {
620 let res = libc::clock_nanosleep(
621 crate::sys::time::Instant::CLOCK_ID,
622 libc::TIMER_ABSTIME,
623 &ts,
624 core::ptr::null_mut(), );
626
627 if res == 0 {
628 break;
629 } else {
630 assert_eq!(
631 res,
632 libc::EINTR,
633 "timespec is in range,
634 clockid is valid and kernel should support it"
635 );
636 }
637 }
638 }
639}
640
641pub fn yield_now() {
642 let ret = unsafe { libc::sched_yield() };
643 debug_assert_eq!(ret, 0);
644}
645
646#[cfg(any(target_os = "android", target_os = "linux"))]
647mod cgroups {
648 use crate::borrow::Cow;
654 use crate::ffi::OsString;
655 use crate::fs::{File, exists};
656 use crate::io::{BufRead, Read};
657 use crate::os::unix::ffi::OsStringExt;
658 use crate::path::{Path, PathBuf};
659 use crate::str::from_utf8;
660
661 #[derive(PartialEq)]
662 enum Cgroup {
663 V1,
664 V2,
665 }
666
667 pub(super) fn quota() -> usize {
670 let mut quota = usize::MAX;
671 if cfg!(miri) {
672 return quota;
675 }
676
677 let _: Option<()> = try {
678 let mut buf = Vec::with_capacity(128);
679 File::open("/proc/self/cgroup").ok()?.read_to_end(&mut buf).ok()?;
681 let (cgroup_path, version) =
682 buf.split(|&c| c == b'\n').fold(None, |previous, line| {
683 let mut fields = line.splitn(3, |&c| c == b':');
684 let version = match fields.nth(1) {
686 Some(b"") => Cgroup::V2,
687 Some(controllers)
688 if from_utf8(controllers)
689 .is_ok_and(|c| c.split(',').any(|c| c == "cpu")) =>
690 {
691 Cgroup::V1
692 }
693 _ => return previous,
694 };
695
696 if previous.is_some() && version == Cgroup::V2 {
698 return previous;
699 }
700
701 let path = fields.last()?;
702 Some((path[1..].to_owned(), version))
704 })?;
705 let cgroup_path = PathBuf::from(OsString::from_vec(cgroup_path));
706
707 quota = match version {
708 Cgroup::V1 => quota_v1(cgroup_path),
709 Cgroup::V2 => quota_v2(cgroup_path),
710 };
711 };
712
713 quota
714 }
715
716 fn quota_v2(group_path: PathBuf) -> usize {
717 let mut quota = usize::MAX;
718
719 let mut path = PathBuf::with_capacity(128);
720 let mut read_buf = String::with_capacity(20);
721
722 let cgroup_mount = "/sys/fs/cgroup";
724
725 path.push(cgroup_mount);
726 path.push(&group_path);
727
728 path.push("cgroup.controllers");
729
730 if matches!(exists(&path), Err(_) | Ok(false)) {
732 return usize::MAX;
733 };
734
735 path.pop();
736
737 let _: Option<()> = try {
738 while path.starts_with(cgroup_mount) {
739 path.push("cpu.max");
740
741 read_buf.clear();
742
743 if File::open(&path).and_then(|mut f| f.read_to_string(&mut read_buf)).is_ok() {
744 let raw_quota = read_buf.lines().next()?;
745 let mut raw_quota = raw_quota.split(' ');
746 let limit = raw_quota.next()?;
747 let period = raw_quota.next()?;
748 match (limit.parse::<usize>(), period.parse::<usize>()) {
749 (Ok(limit), Ok(period)) if period > 0 => {
750 quota = quota.min(limit / period);
751 }
752 _ => {}
753 }
754 }
755
756 path.pop(); path.pop(); }
759 };
760
761 quota
762 }
763
764 fn quota_v1(group_path: PathBuf) -> usize {
765 let mut quota = usize::MAX;
766 let mut path = PathBuf::with_capacity(128);
767 let mut read_buf = String::with_capacity(20);
768
769 let mounts: &[fn(&Path) -> Option<(_, &Path)>] = &[
772 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu"), p)),
773 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu,cpuacct"), p)),
774 find_mountpoint,
778 ];
779
780 for mount in mounts {
781 let Some((mount, group_path)) = mount(&group_path) else { continue };
782
783 path.clear();
784 path.push(mount.as_ref());
785 path.push(&group_path);
786
787 if matches!(exists(&path), Err(_) | Ok(false)) {
789 continue;
790 }
791
792 while path.starts_with(mount.as_ref()) {
793 let mut parse_file = |name| {
794 path.push(name);
795 read_buf.clear();
796
797 let f = File::open(&path);
798 path.pop(); f.ok()?.read_to_string(&mut read_buf).ok()?;
800 let parsed = read_buf.trim().parse::<usize>().ok()?;
801
802 Some(parsed)
803 };
804
805 let limit = parse_file("cpu.cfs_quota_us");
806 let period = parse_file("cpu.cfs_period_us");
807
808 match (limit, period) {
809 (Some(limit), Some(period)) if period > 0 => quota = quota.min(limit / period),
810 _ => {}
811 }
812
813 path.pop();
814 }
815
816 break;
819 }
820
821 quota
822 }
823
824 fn find_mountpoint(group_path: &Path) -> Option<(Cow<'static, str>, &Path)> {
829 let mut reader = File::open_buffered("/proc/self/mountinfo").ok()?;
830 let mut line = String::with_capacity(256);
831 loop {
832 line.clear();
833 if reader.read_line(&mut line).ok()? == 0 {
834 break;
835 }
836
837 let line = line.trim();
838 let mut items = line.split(' ');
839
840 let sub_path = items.nth(3)?;
841 let mount_point = items.next()?;
842 let mount_opts = items.next_back()?;
843 let filesystem_type = items.nth_back(1)?;
844
845 if filesystem_type != "cgroup" || !mount_opts.split(',').any(|opt| opt == "cpu") {
846 continue;
848 }
849
850 let sub_path = Path::new(sub_path).strip_prefix("/").ok()?;
851
852 if !group_path.starts_with(sub_path) {
853 continue;
856 }
857
858 let trimmed_group_path = group_path.strip_prefix(sub_path).ok()?;
859
860 return Some((Cow::Owned(mount_point.to_owned()), trimmed_group_path));
861 }
862
863 None
864 }
865}
866
867#[cfg(all(target_os = "linux", target_env = "gnu"))]
873unsafe fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
874 dlsym!(
878 fn __pthread_get_minstack(attr: *const libc::pthread_attr_t) -> libc::size_t;
879 );
880
881 match __pthread_get_minstack.get() {
882 None => libc::PTHREAD_STACK_MIN,
883 Some(f) => unsafe { f(attr) },
884 }
885}
886
887#[cfg(all(
889 not(all(target_os = "linux", target_env = "gnu")),
890 not(any(target_os = "netbsd", target_os = "nuttx"))
891))]
892unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
893 libc::PTHREAD_STACK_MIN
894}
895
896#[cfg(any(target_os = "netbsd", target_os = "nuttx"))]
897unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
898 static STACK: crate::sync::OnceLock<usize> = crate::sync::OnceLock::new();
899
900 *STACK.get_or_init(|| {
901 let mut stack = unsafe { libc::sysconf(libc::_SC_THREAD_STACK_MIN) };
902 if stack < 0 {
903 stack = 2048; }
905
906 stack as usize
907 })
908}