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(all(target_env = "p1", target_feature = "atomics")))) {
56 return Err(io::Error::UNSUPPORTED_PLATFORM);
57 }
58
59 let data = init;
60 let mut attr: mem::MaybeUninit<libc::pthread_attr_t> = mem::MaybeUninit::uninit();
61 assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0);
62 let mut attr = DropGuard::new(&mut attr, |attr| {
63 assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0)
64 });
65
66 #[cfg(any(target_os = "espidf", target_os = "nuttx"))]
67 if stack > 0 {
68 assert_eq!(
71 libc::pthread_attr_setstacksize(
72 attr.as_mut_ptr(),
73 cmp::max(stack, min_stack_size(attr.as_ptr()))
74 ),
75 0
76 );
77 }
78
79 #[cfg(not(any(target_os = "espidf", target_os = "nuttx")))]
80 {
81 let stack_size = cmp::max(stack, min_stack_size(attr.as_ptr()));
82
83 match libc::pthread_attr_setstacksize(attr.as_mut_ptr(), stack_size) {
84 0 => {}
85 n => {
86 assert_eq!(n, libc::EINVAL);
87 let page_size = sys::os::page_size();
92 let stack_size =
93 (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1);
94
95 if libc::pthread_attr_setstacksize(attr.as_mut_ptr(), stack_size) != 0 {
99 return Err(io::const_error!(
100 io::ErrorKind::InvalidInput,
101 "invalid stack size"
102 ));
103 }
104 }
105 };
106 }
107
108 let data = Box::into_raw(data);
109 let mut native: libc::pthread_t = mem::zeroed();
110 let ret = libc::pthread_create(&mut native, attr.as_ptr(), thread_start, data as *mut _);
111 return if ret == 0 {
112 Ok(Thread { id: native })
113 } else {
114 drop(Box::from_raw(data));
117 Err(io::Error::from_raw_os_error(ret))
118 };
119
120 extern "C" fn thread_start(data: *mut libc::c_void) -> *mut libc::c_void {
121 unsafe {
122 let init = Box::from_raw(data as *mut ThreadInit);
124 let rust_start = init.init();
125
126 let _handler = sys::stack_overflow::Handler::new();
129
130 rust_start();
131 }
132 ptr::null_mut()
133 }
134 }
135
136 pub fn join(self) {
137 let id = self.into_id();
138 let ret = unsafe { libc::pthread_join(id, ptr::null_mut()) };
139 assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
140 }
141
142 #[cfg(not(target_os = "wasi"))]
143 pub fn id(&self) -> libc::pthread_t {
144 self.id
145 }
146
147 pub fn into_id(self) -> libc::pthread_t {
148 ManuallyDrop::new(self).id
149 }
150}
151
152impl Drop for Thread {
153 fn drop(&mut self) {
154 let ret = unsafe { libc::pthread_detach(self.id) };
155 debug_assert_eq!(ret, 0);
156 }
157}
158
159pub fn available_parallelism() -> io::Result<NonZero<usize>> {
160 cfg_select! {
161 any(
162 target_os = "android",
163 target_os = "emscripten",
164 target_os = "fuchsia",
165 target_os = "hurd",
166 target_os = "linux",
167 target_os = "aix",
168 target_vendor = "apple",
169 target_os = "cygwin",
170 ) => {
171 #[allow(unused_assignments)]
172 #[allow(unused_mut)]
173 let mut quota = usize::MAX;
174
175 #[cfg(any(target_os = "android", target_os = "linux"))]
176 {
177 quota = cgroups::quota().max(1);
178 let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
179 unsafe {
180 if libc::sched_getaffinity(0, size_of::<libc::cpu_set_t>(), &mut set) == 0 {
181 let count = libc::CPU_COUNT(&set) as usize;
182 let count = count.min(quota);
183
184 if let Some(count) = NonZero::new(count) {
189 return Ok(count)
190 }
191 }
192 }
193 }
194 match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
195 -1 => Err(io::Error::last_os_error()),
196 0 => Err(io::Error::UNKNOWN_THREAD_COUNT),
197 cpus => {
198 let count = cpus as usize;
199 let count = count.min(quota);
201 Ok(unsafe { NonZero::new_unchecked(count) })
202 }
203 }
204 }
205 any(
206 target_os = "freebsd",
207 target_os = "dragonfly",
208 target_os = "openbsd",
209 target_os = "netbsd",
210 ) => {
211 use crate::ptr;
212
213 #[cfg(target_os = "freebsd")]
214 {
215 let mut set: libc::cpuset_t = unsafe { mem::zeroed() };
216 unsafe {
217 if libc::cpuset_getaffinity(
218 libc::CPU_LEVEL_WHICH,
219 libc::CPU_WHICH_PID,
220 -1,
221 size_of::<libc::cpuset_t>(),
222 &mut set,
223 ) == 0 {
224 let count = libc::CPU_COUNT(&set) as usize;
225 if count > 0 {
226 return Ok(NonZero::new_unchecked(count));
227 }
228 }
229 }
230 }
231
232 #[cfg(target_os = "netbsd")]
233 {
234 unsafe {
235 let set = libc::_cpuset_create();
236 if !set.is_null() {
237 let mut count: usize = 0;
238 if libc::pthread_getaffinity_np(libc::pthread_self(), libc::_cpuset_size(set), set) == 0 {
239 for i in 0..libc::cpuid_t::MAX {
240 match libc::_cpuset_isset(i, set) {
241 -1 => break,
242 0 => continue,
243 _ => count = count + 1,
244 }
245 }
246 }
247 libc::_cpuset_destroy(set);
248 if let Some(count) = NonZero::new(count) {
249 return Ok(count);
250 }
251 }
252 }
253 }
254
255 let mut cpus: libc::c_uint = 0;
256 let mut cpus_size = size_of_val(&cpus);
257
258 unsafe {
259 cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint;
260 }
261
262 if cpus < 1 {
264 let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
265 let res = unsafe {
266 libc::sysctl(
267 mib.as_mut_ptr(),
268 2,
269 (&raw mut cpus) as *mut _,
270 (&raw mut cpus_size) as *mut _,
271 ptr::null_mut(),
272 0,
273 )
274 };
275
276 if res == -1 {
278 return Err(io::Error::last_os_error());
279 } else if cpus == 0 {
280 return Err(io::Error::UNKNOWN_THREAD_COUNT);
281 }
282 }
283
284 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
285 }
286 target_os = "nto" => {
287 unsafe {
288 use libc::_syspage_ptr;
289 if _syspage_ptr.is_null() {
290 Err(io::const_error!(io::ErrorKind::NotFound, "no syspage available"))
291 } else {
292 let cpus = (*_syspage_ptr).num_cpu;
293 NonZero::new(cpus as usize)
294 .ok_or(io::Error::UNKNOWN_THREAD_COUNT)
295 }
296 }
297 }
298 any(target_os = "solaris", target_os = "illumos") => {
299 let mut cpus = 0u32;
300 if unsafe { libc::pset_info(libc::PS_MYID, core::ptr::null_mut(), &mut cpus, core::ptr::null_mut()) } != 0 {
301 return Err(io::Error::UNKNOWN_THREAD_COUNT);
302 }
303 Ok(unsafe { NonZero::new_unchecked(cpus as usize) })
304 }
305 target_os = "haiku" => {
306 unsafe {
309 let mut sinfo: libc::system_info = crate::mem::zeroed();
310 let res = libc::get_system_info(&mut sinfo);
311
312 if res != libc::B_OK {
313 return Err(io::Error::UNKNOWN_THREAD_COUNT);
314 }
315
316 Ok(NonZero::new_unchecked(sinfo.cpu_count as usize))
317 }
318 }
319 target_os = "vxworks" => {
320 unsafe{
325 let set = libc::vxCpuEnabledGet();
326 Ok(NonZero::new_unchecked(set.count_ones() as usize))
327 }
328 }
329 _ => {
330 Err(io::const_error!(io::ErrorKind::Unsupported, "getting the number of hardware threads is not supported on the target platform"))
332 }
333 }
334}
335
336pub fn current_os_id() -> Option<u64> {
337 cfg_select! {
343 any(target_os = "android", target_os = "linux") => {
345 use crate::sys::pal::weak::syscall;
346
347 syscall!(fn gettid() -> libc::pid_t;);
350
351 let id: libc::pid_t = unsafe { gettid() };
353 Some(id as u64)
354 }
355 target_os = "nto" => {
356 let id: libc::pid_t = unsafe { libc::gettid() };
358 Some(id as u64)
359 }
360 target_os = "openbsd" => {
361 let id: libc::pid_t = unsafe { libc::getthrid() };
363 Some(id as u64)
364 }
365 target_os = "freebsd" => {
366 let id: libc::c_int = unsafe { libc::pthread_getthreadid_np() };
368 Some(id as u64)
369 }
370 target_os = "netbsd" => {
371 let id: libc::lwpid_t = unsafe { libc::_lwp_self() };
373 Some(id as u64)
374 }
375 any(target_os = "illumos", target_os = "solaris") => {
376 let id: libc::pthread_t = unsafe { libc::pthread_self() };
379 Some(id as u64)
380 }
381 target_vendor = "apple" => {
382 let mut id = 0u64;
384 let status: libc::c_int = unsafe { libc::pthread_threadid_np(0, &mut id) };
386 if status == 0 {
387 Some(id)
388 } else {
389 None
390 }
391 }
392 _ => None,
394 }
395}
396
397#[cfg(any(
398 target_os = "linux",
399 target_os = "nto",
400 target_os = "solaris",
401 target_os = "illumos",
402 target_os = "vxworks",
403 target_os = "cygwin",
404 target_vendor = "apple",
405))]
406fn truncate_cstr<const MAX_WITH_NUL: usize>(cstr: &CStr) -> [libc::c_char; MAX_WITH_NUL] {
407 let mut result = [0; MAX_WITH_NUL];
408 for (src, dst) in cstr.to_bytes().iter().zip(&mut result[..MAX_WITH_NUL - 1]) {
409 *dst = *src as libc::c_char;
410 }
411 result
412}
413
414#[cfg(target_os = "android")]
415pub fn set_name(name: &CStr) {
416 const PR_SET_NAME: libc::c_int = 15;
417 unsafe {
418 let res = libc::prctl(
419 PR_SET_NAME,
420 name.as_ptr(),
421 0 as libc::c_ulong,
422 0 as libc::c_ulong,
423 0 as libc::c_ulong,
424 );
425 debug_assert_eq!(res, 0);
427 }
428}
429
430#[cfg(any(
431 target_os = "linux",
432 target_os = "freebsd",
433 target_os = "dragonfly",
434 target_os = "nuttx",
435 target_os = "cygwin"
436))]
437pub fn set_name(name: &CStr) {
438 unsafe {
439 cfg_select! {
440 any(target_os = "linux", target_os = "cygwin") => {
441 const TASK_COMM_LEN: usize = 16;
443 let name = truncate_cstr::<{ TASK_COMM_LEN }>(name);
444 }
445 _ => {
446 }
448 };
449 let res = libc::pthread_setname_np(libc::pthread_self(), name.as_ptr());
452 debug_assert_eq!(res, 0);
454 }
455}
456
457#[cfg(target_os = "openbsd")]
458pub fn set_name(name: &CStr) {
459 unsafe {
460 libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
461 }
462}
463
464#[cfg(target_vendor = "apple")]
465pub fn set_name(name: &CStr) {
466 unsafe {
467 let name = truncate_cstr::<{ libc::MAXTHREADNAMESIZE }>(name);
468 let res = libc::pthread_setname_np(name.as_ptr());
469 debug_assert_eq!(res, 0);
471 }
472}
473
474#[cfg(target_os = "netbsd")]
475pub fn set_name(name: &CStr) {
476 unsafe {
477 let res = libc::pthread_setname_np(
478 libc::pthread_self(),
479 c"%s".as_ptr(),
480 name.as_ptr() as *mut libc::c_void,
481 );
482 debug_assert_eq!(res, 0);
483 }
484}
485
486#[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto"))]
487pub fn set_name(name: &CStr) {
488 weak!(
489 fn pthread_setname_np(thread: libc::pthread_t, name: *const libc::c_char) -> libc::c_int;
490 );
491
492 if let Some(f) = pthread_setname_np.get() {
493 #[cfg(target_os = "nto")]
494 const THREAD_NAME_MAX: usize = libc::_NTO_THREAD_NAME_MAX as usize;
495 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
496 const THREAD_NAME_MAX: usize = 32;
497
498 let name = truncate_cstr::<{ THREAD_NAME_MAX }>(name);
499 let res = unsafe { f(libc::pthread_self(), name.as_ptr()) };
500 debug_assert_eq!(res, 0);
501 }
502}
503
504#[cfg(target_os = "fuchsia")]
505pub fn set_name(name: &CStr) {
506 use crate::sys::pal::fuchsia::*;
507 unsafe {
508 zx_object_set_property(
509 zx_thread_self(),
510 ZX_PROP_NAME,
511 name.as_ptr() as *const libc::c_void,
512 name.to_bytes().len(),
513 );
514 }
515}
516
517#[cfg(target_os = "haiku")]
518pub fn set_name(name: &CStr) {
519 unsafe {
520 let thread_self = libc::find_thread(ptr::null_mut());
521 let res = libc::rename_thread(thread_self, name.as_ptr());
522 debug_assert_eq!(res, libc::B_OK);
524 }
525}
526
527#[cfg(target_os = "vxworks")]
528pub fn set_name(name: &CStr) {
529 let mut name = truncate_cstr::<{ (libc::VX_TASK_RENAME_LENGTH - 1) as usize }>(name);
530 let res = unsafe { libc::taskNameSet(libc::taskIdSelf(), name.as_mut_ptr()) };
531 debug_assert_eq!(res, libc::OK);
532}
533
534#[cfg(not(any(target_os = "espidf", target_os = "wasi")))]
535pub fn sleep(dur: Duration) {
536 let mut secs = dur.as_secs();
537 let mut nsecs = dur.subsec_nanos() as _;
538
539 unsafe {
542 while secs > 0 || nsecs > 0 {
543 let mut ts = libc::timespec {
544 tv_sec: cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t,
545 tv_nsec: nsecs,
546 };
547 secs -= ts.tv_sec as u64;
548 let ts_ptr = &raw mut ts;
549 if libc::nanosleep(ts_ptr, ts_ptr) == -1 {
550 assert_eq!(sys::io::errno(), libc::EINTR);
551 secs += ts.tv_sec as u64;
552 nsecs = ts.tv_nsec;
553 } else {
554 nsecs = 0;
555 }
556 }
557 }
558}
559
560#[cfg(any(
561 target_os = "espidf",
562 target_os = "wasi",
566))]
567pub fn sleep(dur: Duration) {
568 const MAX_MICROS: u32 = u32::MAX - 1_000_000 - 1;
578
579 let mut micros = dur.as_micros() + if dur.subsec_nanos() % 1_000 > 0 { 1 } else { 0 };
586
587 while micros > 0 {
588 let st = if micros > MAX_MICROS as u128 { MAX_MICROS } else { micros as u32 };
589 unsafe {
590 libc::usleep(st);
591 }
592
593 micros -= st as u128;
594 }
595}
596
597#[cfg(any(
600 target_os = "freebsd",
601 target_os = "netbsd",
602 target_os = "linux",
603 target_os = "android",
604 target_os = "solaris",
605 target_os = "illumos",
606 target_os = "dragonfly",
607 target_os = "hurd",
608 target_os = "fuchsia",
609 target_os = "vxworks",
610 target_os = "wasi",
611))]
612pub fn sleep_until(deadline: crate::time::Instant) {
613 use crate::time::Instant;
614
615 let Some(ts) = deadline.into_inner().into_timespec().to_timespec() else {
616 let now = Instant::now();
620 if let Some(delay) = deadline.checked_duration_since(now) {
621 sleep(delay);
622 }
623 return;
624 };
625
626 unsafe {
627 loop {
629 let res = libc::clock_nanosleep(
630 crate::sys::time::Instant::CLOCK_ID,
631 libc::TIMER_ABSTIME,
632 &ts,
633 core::ptr::null_mut(), );
635
636 if res == 0 {
637 break;
638 } else {
639 assert_eq!(
640 res,
641 libc::EINTR,
642 "timespec is in range,
643 clockid is valid and kernel should support it"
644 );
645 }
646 }
647 }
648}
649
650pub fn yield_now() {
651 let ret = unsafe { libc::sched_yield() };
652 debug_assert_eq!(ret, 0);
653}
654
655#[cfg(any(target_os = "android", target_os = "linux"))]
656mod cgroups {
657 use crate::borrow::Cow;
663 use crate::ffi::OsString;
664 use crate::fs::{File, exists};
665 use crate::io::{BufRead, Read};
666 use crate::os::unix::ffi::OsStringExt;
667 use crate::path::{Path, PathBuf};
668 use crate::str::from_utf8;
669
670 #[derive(PartialEq)]
671 enum Cgroup {
672 V1,
673 V2,
674 }
675
676 pub(super) fn quota() -> usize {
679 let mut quota = usize::MAX;
680 if cfg!(miri) {
681 return quota;
684 }
685
686 let _: Option<()> = try {
687 let mut buf = Vec::with_capacity(128);
688 File::open("/proc/self/cgroup").ok()?.read_to_end(&mut buf).ok()?;
690 let (cgroup_path, version) =
691 buf.split(|&c| c == b'\n').fold(None, |previous, line| {
692 let mut fields = line.splitn(3, |&c| c == b':');
693 let version = match fields.nth(1) {
695 Some(b"") => Cgroup::V2,
696 Some(controllers)
697 if from_utf8(controllers)
698 .is_ok_and(|c| c.split(',').any(|c| c == "cpu")) =>
699 {
700 Cgroup::V1
701 }
702 _ => return previous,
703 };
704
705 if previous.is_some() && version == Cgroup::V2 {
707 return previous;
708 }
709
710 let path = fields.last()?;
711 Some((path[1..].to_owned(), version))
713 })?;
714 let cgroup_path = PathBuf::from(OsString::from_vec(cgroup_path));
715
716 quota = match version {
717 Cgroup::V1 => quota_v1(cgroup_path),
718 Cgroup::V2 => quota_v2(cgroup_path),
719 };
720 };
721
722 quota
723 }
724
725 fn quota_v2(group_path: PathBuf) -> usize {
726 let mut quota = usize::MAX;
727
728 let mut path = PathBuf::with_capacity(128);
729 let mut read_buf = String::with_capacity(20);
730
731 let cgroup_mount = "/sys/fs/cgroup";
733
734 path.push(cgroup_mount);
735 path.push(&group_path);
736
737 path.push("cgroup.controllers");
738
739 if matches!(exists(&path), Err(_) | Ok(false)) {
741 return usize::MAX;
742 };
743
744 path.pop();
745
746 let _: Option<()> = try {
747 while path.starts_with(cgroup_mount) {
748 path.push("cpu.max");
749
750 read_buf.clear();
751
752 if File::open(&path).and_then(|mut f| f.read_to_string(&mut read_buf)).is_ok() {
753 let raw_quota = read_buf.lines().next()?;
754 let mut raw_quota = raw_quota.split(' ');
755 let limit = raw_quota.next()?;
756 let period = raw_quota.next()?;
757 match (limit.parse::<usize>(), period.parse::<usize>()) {
758 (Ok(limit), Ok(period)) if period > 0 => {
759 quota = quota.min(limit / period);
760 }
761 _ => {}
762 }
763 }
764
765 path.pop(); path.pop(); }
768 };
769
770 quota
771 }
772
773 fn quota_v1(group_path: PathBuf) -> usize {
774 let mut quota = usize::MAX;
775 let mut path = PathBuf::with_capacity(128);
776 let mut read_buf = String::with_capacity(20);
777
778 let mounts: &[fn(&Path) -> Option<(_, &Path)>] = &[
781 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu"), p)),
782 |p| Some((Cow::Borrowed("/sys/fs/cgroup/cpu,cpuacct"), p)),
783 find_mountpoint,
787 ];
788
789 for mount in mounts {
790 let Some((mount, group_path)) = mount(&group_path) else { continue };
791
792 path.clear();
793 path.push(mount.as_ref());
794 path.push(&group_path);
795
796 if matches!(exists(&path), Err(_) | Ok(false)) {
798 continue;
799 }
800
801 while path.starts_with(mount.as_ref()) {
802 let mut parse_file = |name| {
803 path.push(name);
804 read_buf.clear();
805
806 let f = File::open(&path);
807 path.pop(); f.ok()?.read_to_string(&mut read_buf).ok()?;
809 let parsed = read_buf.trim().parse::<usize>().ok()?;
810
811 Some(parsed)
812 };
813
814 let limit = parse_file("cpu.cfs_quota_us");
815 let period = parse_file("cpu.cfs_period_us");
816
817 match (limit, period) {
818 (Some(limit), Some(period)) if period > 0 => quota = quota.min(limit / period),
819 _ => {}
820 }
821
822 path.pop();
823 }
824
825 break;
828 }
829
830 quota
831 }
832
833 fn find_mountpoint(group_path: &Path) -> Option<(Cow<'static, str>, &Path)> {
838 let mut reader = File::open_buffered("/proc/self/mountinfo").ok()?;
839 let mut line = String::with_capacity(256);
840 loop {
841 line.clear();
842 if reader.read_line(&mut line).ok()? == 0 {
843 break;
844 }
845
846 let line = line.trim();
847 let mut items = line.split(' ');
848
849 let sub_path = items.nth(3)?;
850 let mount_point = items.next()?;
851 let mount_opts = items.next_back()?;
852 let filesystem_type = items.nth_back(1)?;
853
854 if filesystem_type != "cgroup" || !mount_opts.split(',').any(|opt| opt == "cpu") {
855 continue;
857 }
858
859 let sub_path = Path::new(sub_path).strip_prefix("/").ok()?;
860
861 if !group_path.starts_with(sub_path) {
862 continue;
865 }
866
867 let trimmed_group_path = group_path.strip_prefix(sub_path).ok()?;
868
869 return Some((Cow::Owned(mount_point.to_owned()), trimmed_group_path));
870 }
871
872 None
873 }
874}
875
876#[cfg(all(target_os = "linux", target_env = "gnu"))]
882unsafe fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
883 dlsym!(
887 fn __pthread_get_minstack(attr: *const libc::pthread_attr_t) -> libc::size_t;
888 );
889
890 match __pthread_get_minstack.get() {
891 None => libc::PTHREAD_STACK_MIN,
892 Some(f) => unsafe { f(attr) },
893 }
894}
895
896#[cfg(all(
898 not(all(target_os = "linux", target_env = "gnu")),
899 not(any(target_os = "netbsd", target_os = "nuttx"))
900))]
901unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
902 libc::PTHREAD_STACK_MIN
903}
904
905#[cfg(any(target_os = "netbsd", target_os = "nuttx"))]
906unsafe fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
907 static STACK: crate::sync::OnceLock<usize> = crate::sync::OnceLock::new();
908
909 *STACK.get_or_init(|| {
910 let mut stack = unsafe { libc::sysconf(libc::_SC_THREAD_STACK_MIN) };
911 if stack < 0 {
912 stack = 2048; }
914
915 stack as usize
916 })
917}