]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/thread.rs
Make std::thread::available_concurrency support process-limited number of CPUs
[rust.git] / library / std / src / sys / unix / thread.rs
1 use crate::cmp;
2 use crate::ffi::CStr;
3 use crate::io;
4 use crate::mem;
5 use crate::num::NonZeroUsize;
6 use crate::ptr;
7 use crate::sys::{os, stack_overflow};
8 use crate::time::Duration;
9
10 #[cfg(any(target_os = "linux", target_os = "solaris", target_os = "illumos"))]
11 use crate::sys::weak::weak;
12 #[cfg(not(any(target_os = "l4re", target_os = "vxworks", target_os = "espidf")))]
13 pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
14 #[cfg(target_os = "l4re")]
15 pub const DEFAULT_MIN_STACK_SIZE: usize = 1024 * 1024;
16 #[cfg(target_os = "vxworks")]
17 pub const DEFAULT_MIN_STACK_SIZE: usize = 256 * 1024;
18 #[cfg(target_os = "espidf")]
19 pub const DEFAULT_MIN_STACK_SIZE: usize = 0; // 0 indicates that the stack size configured in the ESP-IDF menuconfig system should be used
20
21 #[cfg(target_os = "fuchsia")]
22 mod zircon {
23     type zx_handle_t = u32;
24     type zx_status_t = i32;
25     pub const ZX_PROP_NAME: u32 = 3;
26
27     extern "C" {
28         pub fn zx_object_set_property(
29             handle: zx_handle_t,
30             property: u32,
31             value: *const libc::c_void,
32             value_size: libc::size_t,
33         ) -> zx_status_t;
34         pub fn zx_thread_self() -> zx_handle_t;
35     }
36 }
37
38 pub struct Thread {
39     id: libc::pthread_t,
40 }
41
42 // Some platforms may have pthread_t as a pointer in which case we still want
43 // a thread to be Send/Sync
44 unsafe impl Send for Thread {}
45 unsafe impl Sync for Thread {}
46
47 impl Thread {
48     // unsafe: see thread::Builder::spawn_unchecked for safety requirements
49     pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
50         let p = Box::into_raw(box p);
51         let mut native: libc::pthread_t = mem::zeroed();
52         let mut attr: libc::pthread_attr_t = mem::zeroed();
53         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
54
55         #[cfg(target_os = "espidf")]
56         if stack > 0 {
57             // Only set the stack if a non-zero value is passed
58             // 0 is used as an indication that the default stack size configured in the ESP-IDF menuconfig system should be used
59             assert_eq!(
60                 libc::pthread_attr_setstacksize(&mut attr, cmp::max(stack, min_stack_size(&attr))),
61                 0
62             );
63         }
64
65         #[cfg(not(target_os = "espidf"))]
66         {
67             let stack_size = cmp::max(stack, min_stack_size(&attr));
68
69             match libc::pthread_attr_setstacksize(&mut attr, stack_size) {
70                 0 => {}
71                 n => {
72                     assert_eq!(n, libc::EINVAL);
73                     // EINVAL means |stack_size| is either too small or not a
74                     // multiple of the system page size.  Because it's definitely
75                     // >= PTHREAD_STACK_MIN, it must be an alignment issue.
76                     // Round up to the nearest page and try again.
77                     let page_size = os::page_size();
78                     let stack_size =
79                         (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1);
80                     assert_eq!(libc::pthread_attr_setstacksize(&mut attr, stack_size), 0);
81                 }
82             };
83         }
84
85         let ret = libc::pthread_create(&mut native, &attr, thread_start, p as *mut _);
86         // Note: if the thread creation fails and this assert fails, then p will
87         // be leaked. However, an alternative design could cause double-free
88         // which is clearly worse.
89         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
90
91         return if ret != 0 {
92             // The thread failed to start and as a result p was not consumed. Therefore, it is
93             // safe to reconstruct the box so that it gets deallocated.
94             drop(Box::from_raw(p));
95             Err(io::Error::from_raw_os_error(ret))
96         } else {
97             Ok(Thread { id: native })
98         };
99
100         extern "C" fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
101             unsafe {
102                 // Next, set up our stack overflow handler which may get triggered if we run
103                 // out of stack.
104                 let _handler = stack_overflow::Handler::new();
105                 // Finally, let's run some code.
106                 Box::from_raw(main as *mut Box<dyn FnOnce()>)();
107             }
108             ptr::null_mut()
109         }
110     }
111
112     pub fn yield_now() {
113         let ret = unsafe { libc::sched_yield() };
114         debug_assert_eq!(ret, 0);
115     }
116
117     #[cfg(any(target_os = "linux", target_os = "android"))]
118     pub fn set_name(name: &CStr) {
119         const PR_SET_NAME: libc::c_int = 15;
120         // pthread wrapper only appeared in glibc 2.12, so we use syscall
121         // directly.
122         unsafe {
123             libc::prctl(PR_SET_NAME, name.as_ptr() as libc::c_ulong, 0, 0, 0);
124         }
125     }
126
127     #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd"))]
128     pub fn set_name(name: &CStr) {
129         unsafe {
130             libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
131         }
132     }
133
134     #[cfg(any(target_os = "macos", target_os = "ios"))]
135     pub fn set_name(name: &CStr) {
136         unsafe {
137             libc::pthread_setname_np(name.as_ptr());
138         }
139     }
140
141     #[cfg(target_os = "netbsd")]
142     pub fn set_name(name: &CStr) {
143         use crate::ffi::CString;
144         let cname = CString::new(&b"%s"[..]).unwrap();
145         unsafe {
146             libc::pthread_setname_np(
147                 libc::pthread_self(),
148                 cname.as_ptr(),
149                 name.as_ptr() as *mut libc::c_void,
150             );
151         }
152     }
153
154     #[cfg(any(target_os = "solaris", target_os = "illumos"))]
155     pub fn set_name(name: &CStr) {
156         weak! {
157             fn pthread_setname_np(
158                 libc::pthread_t, *const libc::c_char
159             ) -> libc::c_int
160         }
161
162         if let Some(f) = pthread_setname_np.get() {
163             unsafe {
164                 f(libc::pthread_self(), name.as_ptr());
165             }
166         }
167     }
168
169     #[cfg(target_os = "fuchsia")]
170     pub fn set_name(name: &CStr) {
171         use self::zircon::*;
172         unsafe {
173             zx_object_set_property(
174                 zx_thread_self(),
175                 ZX_PROP_NAME,
176                 name.as_ptr() as *const libc::c_void,
177                 name.to_bytes().len(),
178             );
179         }
180     }
181
182     #[cfg(target_os = "haiku")]
183     pub fn set_name(name: &CStr) {
184         unsafe {
185             let thread_self = libc::find_thread(ptr::null_mut());
186             libc::rename_thread(thread_self, name.as_ptr());
187         }
188     }
189
190     #[cfg(any(
191         target_env = "newlib",
192         target_os = "l4re",
193         target_os = "emscripten",
194         target_os = "redox",
195         target_os = "vxworks"
196     ))]
197     pub fn set_name(_name: &CStr) {
198         // Newlib, Emscripten, and VxWorks have no way to set a thread name.
199     }
200
201     #[cfg(not(target_os = "espidf"))]
202     pub fn sleep(dur: Duration) {
203         let mut secs = dur.as_secs();
204         let mut nsecs = dur.subsec_nanos() as _;
205
206         // If we're awoken with a signal then the return value will be -1 and
207         // nanosleep will fill in `ts` with the remaining time.
208         unsafe {
209             while secs > 0 || nsecs > 0 {
210                 let mut ts = libc::timespec {
211                     tv_sec: cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t,
212                     tv_nsec: nsecs,
213                 };
214                 secs -= ts.tv_sec as u64;
215                 let ts_ptr = &mut ts as *mut _;
216                 if libc::nanosleep(ts_ptr, ts_ptr) == -1 {
217                     assert_eq!(os::errno(), libc::EINTR);
218                     secs += ts.tv_sec as u64;
219                     nsecs = ts.tv_nsec;
220                 } else {
221                     nsecs = 0;
222                 }
223             }
224         }
225     }
226
227     #[cfg(target_os = "espidf")]
228     pub fn sleep(dur: Duration) {
229         let mut micros = dur.as_micros();
230         unsafe {
231             while micros > 0 {
232                 let st = if micros > u32::MAX as u128 { u32::MAX } else { micros as u32 };
233                 libc::usleep(st);
234
235                 micros -= st as u128;
236             }
237         }
238     }
239
240     pub fn join(self) {
241         unsafe {
242             let ret = libc::pthread_join(self.id, ptr::null_mut());
243             mem::forget(self);
244             assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
245         }
246     }
247
248     pub fn id(&self) -> libc::pthread_t {
249         self.id
250     }
251
252     pub fn into_id(self) -> libc::pthread_t {
253         let id = self.id;
254         mem::forget(self);
255         id
256     }
257 }
258
259 impl Drop for Thread {
260     fn drop(&mut self) {
261         let ret = unsafe { libc::pthread_detach(self.id) };
262         debug_assert_eq!(ret, 0);
263     }
264 }
265
266 pub fn available_parallelism() -> io::Result<NonZeroUsize> {
267     cfg_if::cfg_if! {
268         if #[cfg(any(
269             target_os = "android",
270             target_os = "emscripten",
271             target_os = "fuchsia",
272             target_os = "ios",
273             target_os = "linux",
274             target_os = "macos",
275             target_os = "solaris",
276             target_os = "illumos",
277         ))] {
278             #[cfg(any(target_os = "android", target_os = "linux"))]
279             {
280                 let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
281                 if unsafe { libc::sched_getaffinity(0, mem::size_of::<libc::cpu_set_t>(), &mut set) } == 0 {
282                     let count = unsafe { libc::CPU_COUNT(&set) };
283                     return Ok(unsafe { NonZeroUsize::new_unchecked(count as usize) });
284                 }
285             }
286             match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
287                 -1 => Err(io::Error::last_os_error()),
288                 0 => Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform")),
289                 cpus => Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) }),
290             }
291         } else if #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd"))] {
292             use crate::ptr;
293
294             let mut cpus: libc::c_uint = 0;
295             let mut cpus_size = crate::mem::size_of_val(&cpus);
296
297             unsafe {
298                 cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint;
299             }
300
301             // Fallback approach in case of errors or no hardware threads.
302             if cpus < 1 {
303                 let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
304                 let res = unsafe {
305                     libc::sysctl(
306                         mib.as_mut_ptr(),
307                         2,
308                         &mut cpus as *mut _ as *mut _,
309                         &mut cpus_size as *mut _ as *mut _,
310                         ptr::null_mut(),
311                         0,
312                     )
313                 };
314
315                 // Handle errors if any.
316                 if res == -1 {
317                     return Err(io::Error::last_os_error());
318                 } else if cpus == 0 {
319                     return Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform"));
320                 }
321             }
322             Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) })
323         } else if #[cfg(target_os = "openbsd")] {
324             use crate::ptr;
325
326             let mut cpus: libc::c_uint = 0;
327             let mut cpus_size = crate::mem::size_of_val(&cpus);
328             let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
329
330             let res = unsafe {
331                 libc::sysctl(
332                     mib.as_mut_ptr(),
333                     2,
334                     &mut cpus as *mut _ as *mut _,
335                     &mut cpus_size as *mut _ as *mut _,
336                     ptr::null_mut(),
337                     0,
338                 )
339             };
340
341             // Handle errors if any.
342             if res == -1 {
343                 return Err(io::Error::last_os_error());
344             } else if cpus == 0 {
345                 return Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform"));
346             }
347
348             Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) })
349         } else if #[cfg(target_os = "haiku")] {
350             // system_info cpu_count field gets the static data set at boot time with `smp_set_num_cpus`
351             // `get_system_info` calls then `smp_get_num_cpus`
352             unsafe {
353                 let mut sinfo: libc::system_info = crate::mem::zeroed();
354                 let res = libc::get_system_info(&mut sinfo);
355
356                 if res != libc::B_OK {
357                     return Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform"));
358                 }
359
360                 Ok(NonZeroUsize::new_unchecked(sinfo.cpu_count as usize))
361             }
362         } else {
363             // FIXME: implement on vxWorks, Redox, l4re
364             Err(io::Error::new_const(io::ErrorKind::Unsupported, &"Getting the number of hardware threads is not supported on the target platform"))
365         }
366     }
367 }
368
369 #[cfg(all(
370     not(target_os = "linux"),
371     not(target_os = "freebsd"),
372     not(target_os = "macos"),
373     not(target_os = "netbsd"),
374     not(target_os = "openbsd"),
375     not(target_os = "solaris")
376 ))]
377 #[cfg_attr(test, allow(dead_code))]
378 pub mod guard {
379     use crate::ops::Range;
380     pub type Guard = Range<usize>;
381     pub unsafe fn current() -> Option<Guard> {
382         None
383     }
384     pub unsafe fn init() -> Option<Guard> {
385         None
386     }
387 }
388
389 #[cfg(any(
390     target_os = "linux",
391     target_os = "freebsd",
392     target_os = "macos",
393     target_os = "netbsd",
394     target_os = "openbsd",
395     target_os = "solaris"
396 ))]
397 #[cfg_attr(test, allow(dead_code))]
398 pub mod guard {
399     use libc::{mmap, mprotect};
400     use libc::{MAP_ANON, MAP_FAILED, MAP_FIXED, MAP_PRIVATE, PROT_NONE, PROT_READ, PROT_WRITE};
401
402     use crate::io;
403     use crate::ops::Range;
404     use crate::sync::atomic::{AtomicUsize, Ordering};
405     use crate::sys::os;
406
407     // This is initialized in init() and only read from after
408     static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0);
409
410     pub type Guard = Range<usize>;
411
412     #[cfg(target_os = "solaris")]
413     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
414         let mut current_stack: libc::stack_t = crate::mem::zeroed();
415         assert_eq!(libc::stack_getbounds(&mut current_stack), 0);
416         Some(current_stack.ss_sp)
417     }
418
419     #[cfg(target_os = "macos")]
420     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
421         let th = libc::pthread_self();
422         let stackaddr =
423             libc::pthread_get_stackaddr_np(th) as usize - libc::pthread_get_stacksize_np(th);
424         Some(stackaddr as *mut libc::c_void)
425     }
426
427     #[cfg(target_os = "openbsd")]
428     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
429         let mut current_stack: libc::stack_t = crate::mem::zeroed();
430         assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(), &mut current_stack), 0);
431
432         let stackaddr = if libc::pthread_main_np() == 1 {
433             // main thread
434             current_stack.ss_sp as usize - current_stack.ss_size + PAGE_SIZE.load(Ordering::Relaxed)
435         } else {
436             // new thread
437             current_stack.ss_sp as usize - current_stack.ss_size
438         };
439         Some(stackaddr as *mut libc::c_void)
440     }
441
442     #[cfg(any(
443         target_os = "android",
444         target_os = "freebsd",
445         target_os = "linux",
446         target_os = "netbsd",
447         target_os = "l4re"
448     ))]
449     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
450         let mut ret = None;
451         let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
452         #[cfg(target_os = "freebsd")]
453         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
454         #[cfg(target_os = "freebsd")]
455         let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
456         #[cfg(not(target_os = "freebsd"))]
457         let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
458         if e == 0 {
459             let mut stackaddr = crate::ptr::null_mut();
460             let mut stacksize = 0;
461             assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut stacksize), 0);
462             ret = Some(stackaddr);
463         }
464         if e == 0 || cfg!(target_os = "freebsd") {
465             assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
466         }
467         ret
468     }
469
470     // Precondition: PAGE_SIZE is initialized.
471     unsafe fn get_stack_start_aligned() -> Option<*mut libc::c_void> {
472         let page_size = PAGE_SIZE.load(Ordering::Relaxed);
473         assert!(page_size != 0);
474         let stackaddr = get_stack_start()?;
475
476         // Ensure stackaddr is page aligned! A parent process might
477         // have reset RLIMIT_STACK to be non-page aligned. The
478         // pthread_attr_getstack() reports the usable stack area
479         // stackaddr < stackaddr + stacksize, so if stackaddr is not
480         // page-aligned, calculate the fix such that stackaddr <
481         // new_page_aligned_stackaddr < stackaddr + stacksize
482         let remainder = (stackaddr as usize) % page_size;
483         Some(if remainder == 0 {
484             stackaddr
485         } else {
486             ((stackaddr as usize) + page_size - remainder) as *mut libc::c_void
487         })
488     }
489
490     pub unsafe fn init() -> Option<Guard> {
491         let page_size = os::page_size();
492         PAGE_SIZE.store(page_size, Ordering::Relaxed);
493
494         if cfg!(all(target_os = "linux", not(target_env = "musl"))) {
495             // Linux doesn't allocate the whole stack right away, and
496             // the kernel has its own stack-guard mechanism to fault
497             // when growing too close to an existing mapping.  If we map
498             // our own guard, then the kernel starts enforcing a rather
499             // large gap above that, rendering much of the possible
500             // stack space useless.  See #43052.
501             //
502             // Instead, we'll just note where we expect rlimit to start
503             // faulting, so our handler can report "stack overflow", and
504             // trust that the kernel's own stack guard will work.
505             let stackaddr = get_stack_start_aligned()?;
506             let stackaddr = stackaddr as usize;
507             Some(stackaddr - page_size..stackaddr)
508         } else if cfg!(all(target_os = "linux", target_env = "musl")) {
509             // For the main thread, the musl's pthread_attr_getstack
510             // returns the current stack size, rather than maximum size
511             // it can eventually grow to. It cannot be used to determine
512             // the position of kernel's stack guard.
513             None
514         } else if cfg!(target_os = "freebsd") {
515             // FreeBSD's stack autogrows, and optionally includes a guard page
516             // at the bottom.  If we try to remap the bottom of the stack
517             // ourselves, FreeBSD's guard page moves upwards.  So we'll just use
518             // the builtin guard page.
519             let stackaddr = get_stack_start_aligned()?;
520             let guardaddr = stackaddr as usize;
521             // Technically the number of guard pages is tunable and controlled
522             // by the security.bsd.stack_guard_page sysctl, but there are
523             // few reasons to change it from the default.  The default value has
524             // been 1 ever since FreeBSD 11.1 and 10.4.
525             const GUARD_PAGES: usize = 1;
526             let guard = guardaddr..guardaddr + GUARD_PAGES * page_size;
527             Some(guard)
528         } else {
529             // Reallocate the last page of the stack.
530             // This ensures SIGBUS will be raised on
531             // stack overflow.
532             // Systems which enforce strict PAX MPROTECT do not allow
533             // to mprotect() a mapping with less restrictive permissions
534             // than the initial mmap() used, so we mmap() here with
535             // read/write permissions and only then mprotect() it to
536             // no permissions at all. See issue #50313.
537             let stackaddr = get_stack_start_aligned()?;
538             let result = mmap(
539                 stackaddr,
540                 page_size,
541                 PROT_READ | PROT_WRITE,
542                 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
543                 -1,
544                 0,
545             );
546             if result != stackaddr || result == MAP_FAILED {
547                 panic!("failed to allocate a guard page: {}", io::Error::last_os_error());
548             }
549
550             let result = mprotect(stackaddr, page_size, PROT_NONE);
551             if result != 0 {
552                 panic!("failed to protect the guard page: {}", io::Error::last_os_error());
553             }
554
555             let guardaddr = stackaddr as usize;
556
557             Some(guardaddr..guardaddr + page_size)
558         }
559     }
560
561     #[cfg(any(target_os = "macos", target_os = "openbsd", target_os = "solaris"))]
562     pub unsafe fn current() -> Option<Guard> {
563         let stackaddr = get_stack_start()? as usize;
564         Some(stackaddr - PAGE_SIZE.load(Ordering::Relaxed)..stackaddr)
565     }
566
567     #[cfg(any(
568         target_os = "android",
569         target_os = "freebsd",
570         target_os = "linux",
571         target_os = "netbsd",
572         target_os = "l4re"
573     ))]
574     pub unsafe fn current() -> Option<Guard> {
575         let mut ret = None;
576         let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
577         #[cfg(target_os = "freebsd")]
578         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
579         #[cfg(target_os = "freebsd")]
580         let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
581         #[cfg(not(target_os = "freebsd"))]
582         let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
583         if e == 0 {
584             let mut guardsize = 0;
585             assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
586             if guardsize == 0 {
587                 if cfg!(all(target_os = "linux", target_env = "musl")) {
588                     // musl versions before 1.1.19 always reported guard
589                     // size obtained from pthread_attr_get_np as zero.
590                     // Use page size as a fallback.
591                     guardsize = PAGE_SIZE.load(Ordering::Relaxed);
592                 } else {
593                     panic!("there is no guard page");
594                 }
595             }
596             let mut stackaddr = crate::ptr::null_mut();
597             let mut size = 0;
598             assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut size), 0);
599
600             let stackaddr = stackaddr as usize;
601             ret = if cfg!(any(target_os = "freebsd", target_os = "netbsd")) {
602                 Some(stackaddr - guardsize..stackaddr)
603             } else if cfg!(all(target_os = "linux", target_env = "musl")) {
604                 Some(stackaddr - guardsize..stackaddr)
605             } else if cfg!(all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")))
606             {
607                 // glibc used to include the guard area within the stack, as noted in the BUGS
608                 // section of `man pthread_attr_getguardsize`.  This has been corrected starting
609                 // with glibc 2.27, and in some distro backports, so the guard is now placed at the
610                 // end (below) the stack.  There's no easy way for us to know which we have at
611                 // runtime, so we'll just match any fault in the range right above or below the
612                 // stack base to call that fault a stack overflow.
613                 Some(stackaddr - guardsize..stackaddr + guardsize)
614             } else {
615                 Some(stackaddr..stackaddr + guardsize)
616             };
617         }
618         if e == 0 || cfg!(target_os = "freebsd") {
619             assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
620         }
621         ret
622     }
623 }
624
625 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
626 // PTHREAD_STACK_MIN plus bytes needed for thread-local storage.
627 // We need that information to avoid blowing up when a small stack
628 // is created in an application with big thread-local storage requirements.
629 // See #6233 for rationale and details.
630 #[cfg(target_os = "linux")]
631 #[allow(deprecated)]
632 fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
633     weak!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);
634
635     match __pthread_get_minstack.get() {
636         None => libc::PTHREAD_STACK_MIN,
637         Some(f) => unsafe { f(attr) },
638     }
639 }
640
641 // No point in looking up __pthread_get_minstack() on non-glibc
642 // platforms.
643 #[cfg(all(not(target_os = "linux"), not(target_os = "netbsd")))]
644 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
645     libc::PTHREAD_STACK_MIN
646 }
647
648 #[cfg(target_os = "netbsd")]
649 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
650     2048 // just a guess
651 }