6 use crate::sys::{os, stack_overflow};
7 use crate::time::Duration;
9 #[cfg(not(any(target_os = "l4re", target_os = "vxworks")))]
10 pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
11 #[cfg(target_os = "l4re")]
12 pub const DEFAULT_MIN_STACK_SIZE: usize = 1024 * 1024;
13 #[cfg(target_os = "vxworks")]
14 pub const DEFAULT_MIN_STACK_SIZE: usize = 256 * 1024;
20 // Some platforms may have pthread_t as a pointer in which case we still want
21 // a thread to be Send/Sync
22 unsafe impl Send for Thread {}
23 unsafe impl Sync for Thread {}
25 // The pthread_attr_setstacksize symbol doesn't exist in the emscripten libc,
26 // so we have to not link to it to satisfy emcc's ERROR_ON_UNDEFINED_SYMBOLS.
27 #[cfg(not(target_os = "emscripten"))]
28 unsafe fn pthread_attr_setstacksize(
29 attr: *mut libc::pthread_attr_t,
30 stack_size: libc::size_t,
32 libc::pthread_attr_setstacksize(attr, stack_size)
35 #[cfg(target_os = "emscripten")]
36 unsafe fn pthread_attr_setstacksize(
37 _attr: *mut libc::pthread_attr_t,
38 _stack_size: libc::size_t,
44 // unsafe: see thread::Builder::spawn_unchecked for safety requirements
45 pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
46 let p = Box::into_raw(box p);
47 let mut native: libc::pthread_t = mem::zeroed();
48 let mut attr: libc::pthread_attr_t = mem::zeroed();
49 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
51 let stack_size = cmp::max(stack, min_stack_size(&attr));
53 match pthread_attr_setstacksize(&mut attr, stack_size) {
56 assert_eq!(n, libc::EINVAL);
57 // EINVAL means |stack_size| is either too small or not a
58 // multiple of the system page size. Because it's definitely
59 // >= PTHREAD_STACK_MIN, it must be an alignment issue.
60 // Round up to the nearest page and try again.
61 let page_size = os::page_size();
63 (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1);
64 assert_eq!(libc::pthread_attr_setstacksize(&mut attr, stack_size), 0);
68 let ret = libc::pthread_create(&mut native, &attr, thread_start, p as *mut _);
69 // Note: if the thread creation fails and this assert fails, then p will
70 // be leaked. However, an alternative design could cause double-free
71 // which is clearly worse.
72 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
75 // The thread failed to start and as a result p was not consumed. Therefore, it is
76 // safe to reconstruct the box so that it gets deallocated.
77 drop(Box::from_raw(p));
78 Err(io::Error::from_raw_os_error(ret))
80 Ok(Thread { id: native })
83 extern "C" fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
85 // Next, set up our stack overflow handler which may get triggered if we run
87 let _handler = stack_overflow::Handler::new();
88 // Finally, let's run some code.
89 Box::from_raw(main as *mut Box<dyn FnOnce()>)();
96 let ret = unsafe { libc::sched_yield() };
97 debug_assert_eq!(ret, 0);
100 #[cfg(any(target_os = "linux", target_os = "android"))]
101 pub fn set_name(name: &CStr) {
102 const PR_SET_NAME: libc::c_int = 15;
103 // pthread wrapper only appeared in glibc 2.12, so we use syscall
106 libc::prctl(PR_SET_NAME, name.as_ptr() as libc::c_ulong, 0, 0, 0);
110 #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd"))]
111 pub fn set_name(name: &CStr) {
113 libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
117 #[cfg(any(target_os = "macos", target_os = "ios"))]
118 pub fn set_name(name: &CStr) {
120 libc::pthread_setname_np(name.as_ptr());
124 #[cfg(target_os = "netbsd")]
125 pub fn set_name(name: &CStr) {
126 use crate::ffi::CString;
127 let cname = CString::new(&b"%s"[..]).unwrap();
129 libc::pthread_setname_np(
130 libc::pthread_self(),
132 name.as_ptr() as *mut libc::c_void,
137 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
138 pub fn set_name(name: &CStr) {
140 fn pthread_setname_np(
141 libc::pthread_t, *const libc::c_char
145 if let Some(f) = pthread_setname_np.get() {
147 f(libc::pthread_self(), name.as_ptr());
153 target_env = "newlib",
156 target_os = "emscripten",
158 target_os = "vxworks"
160 pub fn set_name(_name: &CStr) {
161 // Newlib, Haiku, Emscripten, and VxWorks have no way to set a thread name.
163 #[cfg(target_os = "fuchsia")]
164 pub fn set_name(_name: &CStr) {
165 // FIXME: determine whether Fuchsia has a way to set a thread name.
168 pub fn sleep(dur: Duration) {
169 let mut secs = dur.as_secs();
170 let mut nsecs = dur.subsec_nanos() as _;
172 // If we're awoken with a signal then the return value will be -1 and
173 // nanosleep will fill in `ts` with the remaining time.
175 while secs > 0 || nsecs > 0 {
176 let mut ts = libc::timespec {
177 tv_sec: cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t,
180 secs -= ts.tv_sec as u64;
181 if libc::nanosleep(&ts, &mut ts) == -1 {
182 assert_eq!(os::errno(), libc::EINTR);
183 secs += ts.tv_sec as u64;
194 let ret = libc::pthread_join(self.id, ptr::null_mut());
196 assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
200 pub fn id(&self) -> libc::pthread_t {
204 pub fn into_id(self) -> libc::pthread_t {
211 impl Drop for Thread {
213 let ret = unsafe { libc::pthread_detach(self.id) };
214 debug_assert_eq!(ret, 0);
219 not(target_os = "linux"),
220 not(target_os = "freebsd"),
221 not(target_os = "macos"),
222 not(all(target_os = "netbsd", not(target_vendor = "rumprun"))),
223 not(target_os = "openbsd"),
224 not(target_os = "solaris")
226 #[cfg_attr(test, allow(dead_code))]
228 use crate::ops::Range;
229 pub type Guard = Range<usize>;
230 pub unsafe fn current() -> Option<Guard> {
233 pub unsafe fn init() -> Option<Guard> {
240 target_os = "freebsd",
242 all(target_os = "netbsd", not(target_vendor = "rumprun")),
243 target_os = "openbsd",
244 target_os = "solaris"
246 #[cfg_attr(test, allow(dead_code))]
248 use libc::{mmap, mprotect};
249 use libc::{MAP_ANON, MAP_FAILED, MAP_FIXED, MAP_PRIVATE, PROT_NONE, PROT_READ, PROT_WRITE};
251 use crate::ops::Range;
252 use crate::sync::atomic::{AtomicUsize, Ordering};
255 // This is initialized in init() and only read from after
256 static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0);
258 pub type Guard = Range<usize>;
260 #[cfg(target_os = "solaris")]
261 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
262 let mut current_stack: libc::stack_t = crate::mem::zeroed();
263 assert_eq!(libc::stack_getbounds(&mut current_stack), 0);
264 Some(current_stack.ss_sp)
267 #[cfg(target_os = "macos")]
268 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
269 let th = libc::pthread_self();
271 libc::pthread_get_stackaddr_np(th) as usize - libc::pthread_get_stacksize_np(th);
272 Some(stackaddr as *mut libc::c_void)
275 #[cfg(target_os = "openbsd")]
276 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
277 let mut current_stack: libc::stack_t = crate::mem::zeroed();
278 assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(), &mut current_stack), 0);
280 let stackaddr = if libc::pthread_main_np() == 1 {
282 current_stack.ss_sp as usize - current_stack.ss_size + PAGE_SIZE.load(Ordering::Relaxed)
285 current_stack.ss_sp as usize - current_stack.ss_size
287 Some(stackaddr as *mut libc::c_void)
291 target_os = "android",
292 target_os = "freebsd",
294 target_os = "netbsd",
297 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
299 let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
300 #[cfg(target_os = "freebsd")]
301 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
302 #[cfg(target_os = "freebsd")]
303 let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
304 #[cfg(not(target_os = "freebsd"))]
305 let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
307 let mut stackaddr = crate::ptr::null_mut();
308 let mut stacksize = 0;
309 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut stacksize), 0);
310 ret = Some(stackaddr);
312 if e == 0 || cfg!(target_os = "freebsd") {
313 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
318 // Precondition: PAGE_SIZE is initialized.
319 unsafe fn get_stack_start_aligned() -> Option<*mut libc::c_void> {
320 let page_size = PAGE_SIZE.load(Ordering::Relaxed);
321 assert!(page_size != 0);
322 let stackaddr = get_stack_start()?;
324 // Ensure stackaddr is page aligned! A parent process might
325 // have reset RLIMIT_STACK to be non-page aligned. The
326 // pthread_attr_getstack() reports the usable stack area
327 // stackaddr < stackaddr + stacksize, so if stackaddr is not
328 // page-aligned, calculate the fix such that stackaddr <
329 // new_page_aligned_stackaddr < stackaddr + stacksize
330 let remainder = (stackaddr as usize) % page_size;
331 Some(if remainder == 0 {
334 ((stackaddr as usize) + page_size - remainder) as *mut libc::c_void
338 pub unsafe fn init() -> Option<Guard> {
339 let page_size = os::page_size();
340 PAGE_SIZE.store(page_size, Ordering::Relaxed);
342 if cfg!(all(target_os = "linux", not(target_env = "musl"))) {
343 // Linux doesn't allocate the whole stack right away, and
344 // the kernel has its own stack-guard mechanism to fault
345 // when growing too close to an existing mapping. If we map
346 // our own guard, then the kernel starts enforcing a rather
347 // large gap above that, rendering much of the possible
348 // stack space useless. See #43052.
350 // Instead, we'll just note where we expect rlimit to start
351 // faulting, so our handler can report "stack overflow", and
352 // trust that the kernel's own stack guard will work.
353 let stackaddr = get_stack_start_aligned()?;
354 let stackaddr = stackaddr as usize;
355 Some(stackaddr - page_size..stackaddr)
356 } else if cfg!(all(target_os = "linux", target_env = "musl")) {
357 // For the main thread, the musl's pthread_attr_getstack
358 // returns the current stack size, rather than maximum size
359 // it can eventually grow to. It cannot be used to determine
360 // the position of kernel's stack guard.
363 // Reallocate the last page of the stack.
364 // This ensures SIGBUS will be raised on
366 // Systems which enforce strict PAX MPROTECT do not allow
367 // to mprotect() a mapping with less restrictive permissions
368 // than the initial mmap() used, so we mmap() here with
369 // read/write permissions and only then mprotect() it to
370 // no permissions at all. See issue #50313.
371 let stackaddr = get_stack_start_aligned()?;
375 PROT_READ | PROT_WRITE,
376 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
380 if result != stackaddr || result == MAP_FAILED {
381 panic!("failed to allocate a guard page");
384 let result = mprotect(stackaddr, page_size, PROT_NONE);
386 panic!("failed to protect the guard page");
389 let guardaddr = stackaddr as usize;
390 let offset = if cfg!(target_os = "freebsd") { 2 } else { 1 };
392 Some(guardaddr..guardaddr + offset * page_size)
396 #[cfg(any(target_os = "macos", target_os = "openbsd", target_os = "solaris"))]
397 pub unsafe fn current() -> Option<Guard> {
398 let stackaddr = get_stack_start()? as usize;
399 Some(stackaddr - PAGE_SIZE.load(Ordering::Relaxed)..stackaddr)
403 target_os = "android",
404 target_os = "freebsd",
406 target_os = "netbsd",
409 pub unsafe fn current() -> Option<Guard> {
411 let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
412 #[cfg(target_os = "freebsd")]
413 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
414 #[cfg(target_os = "freebsd")]
415 let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
416 #[cfg(not(target_os = "freebsd"))]
417 let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
419 let mut guardsize = 0;
420 assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
422 if cfg!(all(target_os = "linux", target_env = "musl")) {
423 // musl versions before 1.1.19 always reported guard
424 // size obtained from pthread_attr_get_np as zero.
425 // Use page size as a fallback.
426 guardsize = PAGE_SIZE.load(Ordering::Relaxed);
428 panic!("there is no guard page");
431 let mut stackaddr = crate::ptr::null_mut();
433 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut size), 0);
435 let stackaddr = stackaddr as usize;
436 ret = if cfg!(target_os = "freebsd") {
437 // FIXME does freebsd really fault *below* the guard addr?
438 let guardaddr = stackaddr - guardsize;
439 Some(guardaddr - PAGE_SIZE.load(Ordering::Relaxed)..guardaddr)
440 } else if cfg!(target_os = "netbsd") {
441 Some(stackaddr - guardsize..stackaddr)
442 } else if cfg!(all(target_os = "linux", target_env = "musl")) {
443 Some(stackaddr - guardsize..stackaddr)
444 } else if cfg!(all(target_os = "linux", target_env = "gnu")) {
445 // glibc used to include the guard area within the stack, as noted in the BUGS
446 // section of `man pthread_attr_getguardsize`. This has been corrected starting
447 // with glibc 2.27, and in some distro backports, so the guard is now placed at the
448 // end (below) the stack. There's no easy way for us to know which we have at
449 // runtime, so we'll just match any fault in the range right above or below the
450 // stack base to call that fault a stack overflow.
451 Some(stackaddr - guardsize..stackaddr + guardsize)
453 Some(stackaddr..stackaddr + guardsize)
456 if e == 0 || cfg!(target_os = "freebsd") {
457 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
463 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
464 // PTHREAD_STACK_MIN plus bytes needed for thread-local storage.
465 // We need that information to avoid blowing up when a small stack
466 // is created in an application with big thread-local storage requirements.
467 // See #6233 for rationale and details.
468 #[cfg(target_os = "linux")]
470 fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
471 weak!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);
473 match __pthread_get_minstack.get() {
474 None => libc::PTHREAD_STACK_MIN,
475 Some(f) => unsafe { f(attr) },
479 // No point in looking up __pthread_get_minstack() on non-glibc
481 #[cfg(all(not(target_os = "linux"), not(target_os = "netbsd")))]
482 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
483 libc::PTHREAD_STACK_MIN
486 #[cfg(target_os = "netbsd")]
487 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {