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 let ts_ptr = &mut ts as *mut _;
182 if libc::nanosleep(ts_ptr, ts_ptr) == -1 {
183 assert_eq!(os::errno(), libc::EINTR);
184 secs += ts.tv_sec as u64;
195 let ret = libc::pthread_join(self.id, ptr::null_mut());
197 assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
201 pub fn id(&self) -> libc::pthread_t {
205 pub fn into_id(self) -> libc::pthread_t {
212 impl Drop for Thread {
214 let ret = unsafe { libc::pthread_detach(self.id) };
215 debug_assert_eq!(ret, 0);
220 not(target_os = "linux"),
221 not(target_os = "freebsd"),
222 not(target_os = "macos"),
223 not(all(target_os = "netbsd", not(target_vendor = "rumprun"))),
224 not(target_os = "openbsd"),
225 not(target_os = "solaris")
227 #[cfg_attr(test, allow(dead_code))]
229 use crate::ops::Range;
230 pub type Guard = Range<usize>;
231 pub unsafe fn current() -> Option<Guard> {
234 pub unsafe fn init() -> Option<Guard> {
241 target_os = "freebsd",
243 all(target_os = "netbsd", not(target_vendor = "rumprun")),
244 target_os = "openbsd",
245 target_os = "solaris"
247 #[cfg_attr(test, allow(dead_code))]
249 use libc::{mmap, mprotect};
250 use libc::{MAP_ANON, MAP_FAILED, MAP_FIXED, MAP_PRIVATE, PROT_NONE, PROT_READ, PROT_WRITE};
252 use crate::ops::Range;
253 use crate::sync::atomic::{AtomicUsize, Ordering};
256 // This is initialized in init() and only read from after
257 static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0);
259 pub type Guard = Range<usize>;
261 #[cfg(target_os = "solaris")]
262 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
263 let mut current_stack: libc::stack_t = crate::mem::zeroed();
264 assert_eq!(libc::stack_getbounds(&mut current_stack), 0);
265 Some(current_stack.ss_sp)
268 #[cfg(target_os = "macos")]
269 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
270 let th = libc::pthread_self();
272 libc::pthread_get_stackaddr_np(th) as usize - libc::pthread_get_stacksize_np(th);
273 Some(stackaddr as *mut libc::c_void)
276 #[cfg(target_os = "openbsd")]
277 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
278 let mut current_stack: libc::stack_t = crate::mem::zeroed();
279 assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(), &mut current_stack), 0);
281 let stackaddr = if libc::pthread_main_np() == 1 {
283 current_stack.ss_sp as usize - current_stack.ss_size + PAGE_SIZE.load(Ordering::Relaxed)
286 current_stack.ss_sp as usize - current_stack.ss_size
288 Some(stackaddr as *mut libc::c_void)
292 target_os = "android",
293 target_os = "freebsd",
295 target_os = "netbsd",
298 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
300 let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
301 #[cfg(target_os = "freebsd")]
302 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
303 #[cfg(target_os = "freebsd")]
304 let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
305 #[cfg(not(target_os = "freebsd"))]
306 let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
308 let mut stackaddr = crate::ptr::null_mut();
309 let mut stacksize = 0;
310 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut stacksize), 0);
311 ret = Some(stackaddr);
313 if e == 0 || cfg!(target_os = "freebsd") {
314 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
319 // Precondition: PAGE_SIZE is initialized.
320 unsafe fn get_stack_start_aligned() -> Option<*mut libc::c_void> {
321 let page_size = PAGE_SIZE.load(Ordering::Relaxed);
322 assert!(page_size != 0);
323 let stackaddr = get_stack_start()?;
325 // Ensure stackaddr is page aligned! A parent process might
326 // have reset RLIMIT_STACK to be non-page aligned. The
327 // pthread_attr_getstack() reports the usable stack area
328 // stackaddr < stackaddr + stacksize, so if stackaddr is not
329 // page-aligned, calculate the fix such that stackaddr <
330 // new_page_aligned_stackaddr < stackaddr + stacksize
331 let remainder = (stackaddr as usize) % page_size;
332 Some(if remainder == 0 {
335 ((stackaddr as usize) + page_size - remainder) as *mut libc::c_void
339 pub unsafe fn init() -> Option<Guard> {
340 let page_size = os::page_size();
341 PAGE_SIZE.store(page_size, Ordering::Relaxed);
343 if cfg!(all(target_os = "linux", not(target_env = "musl"))) {
344 // Linux doesn't allocate the whole stack right away, and
345 // the kernel has its own stack-guard mechanism to fault
346 // when growing too close to an existing mapping. If we map
347 // our own guard, then the kernel starts enforcing a rather
348 // large gap above that, rendering much of the possible
349 // stack space useless. See #43052.
351 // Instead, we'll just note where we expect rlimit to start
352 // faulting, so our handler can report "stack overflow", and
353 // trust that the kernel's own stack guard will work.
354 let stackaddr = get_stack_start_aligned()?;
355 let stackaddr = stackaddr as usize;
356 Some(stackaddr - page_size..stackaddr)
357 } else if cfg!(all(target_os = "linux", target_env = "musl")) {
358 // For the main thread, the musl's pthread_attr_getstack
359 // returns the current stack size, rather than maximum size
360 // it can eventually grow to. It cannot be used to determine
361 // the position of kernel's stack guard.
364 // Reallocate the last page of the stack.
365 // This ensures SIGBUS will be raised on
367 // Systems which enforce strict PAX MPROTECT do not allow
368 // to mprotect() a mapping with less restrictive permissions
369 // than the initial mmap() used, so we mmap() here with
370 // read/write permissions and only then mprotect() it to
371 // no permissions at all. See issue #50313.
372 let stackaddr = get_stack_start_aligned()?;
376 PROT_READ | PROT_WRITE,
377 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
381 if result != stackaddr || result == MAP_FAILED {
382 panic!("failed to allocate a guard page");
385 let result = mprotect(stackaddr, page_size, PROT_NONE);
387 panic!("failed to protect the guard page");
390 let guardaddr = stackaddr as usize;
391 let offset = if cfg!(target_os = "freebsd") { 2 } else { 1 };
393 Some(guardaddr..guardaddr + offset * page_size)
397 #[cfg(any(target_os = "macos", target_os = "openbsd", target_os = "solaris"))]
398 pub unsafe fn current() -> Option<Guard> {
399 let stackaddr = get_stack_start()? as usize;
400 Some(stackaddr - PAGE_SIZE.load(Ordering::Relaxed)..stackaddr)
404 target_os = "android",
405 target_os = "freebsd",
407 target_os = "netbsd",
410 pub unsafe fn current() -> Option<Guard> {
412 let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
413 #[cfg(target_os = "freebsd")]
414 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
415 #[cfg(target_os = "freebsd")]
416 let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
417 #[cfg(not(target_os = "freebsd"))]
418 let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
420 let mut guardsize = 0;
421 assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
423 if cfg!(all(target_os = "linux", target_env = "musl")) {
424 // musl versions before 1.1.19 always reported guard
425 // size obtained from pthread_attr_get_np as zero.
426 // Use page size as a fallback.
427 guardsize = PAGE_SIZE.load(Ordering::Relaxed);
429 panic!("there is no guard page");
432 let mut stackaddr = crate::ptr::null_mut();
434 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut size), 0);
436 let stackaddr = stackaddr as usize;
437 ret = if cfg!(target_os = "freebsd") {
438 // FIXME does freebsd really fault *below* the guard addr?
439 let guardaddr = stackaddr - guardsize;
440 Some(guardaddr - PAGE_SIZE.load(Ordering::Relaxed)..guardaddr)
441 } else if cfg!(target_os = "netbsd") {
442 Some(stackaddr - guardsize..stackaddr)
443 } else if cfg!(all(target_os = "linux", target_env = "musl")) {
444 Some(stackaddr - guardsize..stackaddr)
445 } else if cfg!(all(target_os = "linux", target_env = "gnu")) {
446 // glibc used to include the guard area within the stack, as noted in the BUGS
447 // section of `man pthread_attr_getguardsize`. This has been corrected starting
448 // with glibc 2.27, and in some distro backports, so the guard is now placed at the
449 // end (below) the stack. There's no easy way for us to know which we have at
450 // runtime, so we'll just match any fault in the range right above or below the
451 // stack base to call that fault a stack overflow.
452 Some(stackaddr - guardsize..stackaddr + guardsize)
454 Some(stackaddr..stackaddr + guardsize)
457 if e == 0 || cfg!(target_os = "freebsd") {
458 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
464 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
465 // PTHREAD_STACK_MIN plus bytes needed for thread-local storage.
466 // We need that information to avoid blowing up when a small stack
467 // is created in an application with big thread-local storage requirements.
468 // See #6233 for rationale and details.
469 #[cfg(target_os = "linux")]
471 fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
472 weak!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);
474 match __pthread_get_minstack.get() {
475 None => libc::PTHREAD_STACK_MIN,
476 Some(f) => unsafe { f(attr) },
480 // No point in looking up __pthread_get_minstack() on non-glibc
482 #[cfg(all(not(target_os = "linux"), not(target_os = "netbsd")))]
483 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
484 libc::PTHREAD_STACK_MIN
487 #[cfg(target_os = "netbsd")]
488 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {