6 use crate::sys::{os, stack_overflow};
7 use crate::time::Duration;
9 #[cfg(not(target_os = "l4re"))]
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;
18 // Some platforms may have pthread_t as a pointer in which case we still want
19 // a thread to be Send/Sync
20 unsafe impl Send for Thread {}
21 unsafe impl Sync for Thread {}
23 // The pthread_attr_setstacksize symbol doesn't exist in the emscripten libc,
24 // so we have to not link to it to satisfy emcc's ERROR_ON_UNDEFINED_SYMBOLS.
25 #[cfg(not(target_os = "emscripten"))]
26 unsafe fn pthread_attr_setstacksize(
27 attr: *mut libc::pthread_attr_t,
28 stack_size: libc::size_t,
30 libc::pthread_attr_setstacksize(attr, stack_size)
33 #[cfg(target_os = "emscripten")]
34 unsafe fn pthread_attr_setstacksize(
35 _attr: *mut libc::pthread_attr_t,
36 _stack_size: libc::size_t,
42 // unsafe: see thread::Builder::spawn_unchecked for safety requirements
43 pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
44 let p = Box::into_raw(box p);
45 let mut native: libc::pthread_t = mem::zeroed();
46 let mut attr: libc::pthread_attr_t = mem::zeroed();
47 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
49 let stack_size = cmp::max(stack, min_stack_size(&attr));
51 match pthread_attr_setstacksize(&mut attr, stack_size) {
54 assert_eq!(n, libc::EINVAL);
55 // EINVAL means |stack_size| is either too small or not a
56 // multiple of the system page size. Because it's definitely
57 // >= PTHREAD_STACK_MIN, it must be an alignment issue.
58 // Round up to the nearest page and try again.
59 let page_size = os::page_size();
61 (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1);
62 assert_eq!(libc::pthread_attr_setstacksize(&mut attr, stack_size), 0);
66 let ret = libc::pthread_create(&mut native, &attr, thread_start, p as *mut _);
67 // Note: if the thread creation fails and this assert fails, then p will
68 // be leaked. However, an alternative design could cause double-free
69 // which is clearly worse.
70 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
73 // The thread failed to start and as a result p was not consumed. Therefore, it is
74 // safe to reconstruct the box so that it gets deallocated.
75 drop(Box::from_raw(p));
76 Err(io::Error::from_raw_os_error(ret))
78 Ok(Thread { id: native })
81 extern "C" fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
83 // Next, set up our stack overflow handler which may get triggered if we run
85 let _handler = stack_overflow::Handler::new();
86 // Finally, let's run some code.
87 Box::from_raw(main as *mut Box<dyn FnOnce()>)();
94 let ret = unsafe { libc::sched_yield() };
95 debug_assert_eq!(ret, 0);
98 #[cfg(any(target_os = "linux", target_os = "android"))]
99 pub fn set_name(name: &CStr) {
100 const PR_SET_NAME: libc::c_int = 15;
101 // pthread wrapper only appeared in glibc 2.12, so we use syscall
104 libc::prctl(PR_SET_NAME, name.as_ptr() as libc::c_ulong, 0, 0, 0);
108 #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd"))]
109 pub fn set_name(name: &CStr) {
111 libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
115 #[cfg(any(target_os = "macos", target_os = "ios"))]
116 pub fn set_name(name: &CStr) {
118 libc::pthread_setname_np(name.as_ptr());
122 #[cfg(target_os = "netbsd")]
123 pub fn set_name(name: &CStr) {
124 use crate::ffi::CString;
125 let cname = CString::new(&b"%s"[..]).unwrap();
127 libc::pthread_setname_np(
128 libc::pthread_self(),
130 name.as_ptr() as *mut libc::c_void,
135 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
136 pub fn set_name(name: &CStr) {
138 fn pthread_setname_np(
139 libc::pthread_t, *const libc::c_char
143 if let Some(f) = pthread_setname_np.get() {
145 f(libc::pthread_self(), name.as_ptr());
151 target_env = "newlib",
154 target_os = "emscripten",
157 pub fn set_name(_name: &CStr) {
158 // Newlib, Haiku, and Emscripten have no way to set a thread name.
160 #[cfg(target_os = "fuchsia")]
161 pub fn set_name(_name: &CStr) {
162 // FIXME: determine whether Fuchsia has a way to set a thread name.
165 pub fn sleep(dur: Duration) {
166 let mut secs = dur.as_secs();
167 let mut nsecs = dur.subsec_nanos() as _;
169 // If we're awoken with a signal then the return value will be -1 and
170 // nanosleep will fill in `ts` with the remaining time.
172 while secs > 0 || nsecs > 0 {
173 let mut ts = libc::timespec {
174 tv_sec: cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t,
177 secs -= ts.tv_sec as u64;
178 if libc::nanosleep(&ts, &mut ts) == -1 {
179 assert_eq!(os::errno(), libc::EINTR);
180 secs += ts.tv_sec as u64;
191 let ret = libc::pthread_join(self.id, ptr::null_mut());
193 assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
197 pub fn id(&self) -> libc::pthread_t {
201 pub fn into_id(self) -> libc::pthread_t {
208 impl Drop for Thread {
210 let ret = unsafe { libc::pthread_detach(self.id) };
211 debug_assert_eq!(ret, 0);
216 not(all(target_os = "linux", not(target_env = "musl"))),
217 not(target_os = "freebsd"),
218 not(target_os = "macos"),
219 not(all(target_os = "netbsd", not(target_vendor = "rumprun"))),
220 not(target_os = "openbsd"),
221 not(target_os = "solaris")
223 #[cfg_attr(test, allow(dead_code))]
225 use crate::ops::Range;
226 pub type Guard = Range<usize>;
227 pub unsafe fn current() -> Option<Guard> {
230 pub unsafe fn init() -> Option<Guard> {
236 all(target_os = "linux", not(target_env = "musl")),
237 target_os = "freebsd",
239 all(target_os = "netbsd", not(target_vendor = "rumprun")),
240 target_os = "openbsd",
241 target_os = "solaris"
243 #[cfg_attr(test, allow(dead_code))]
245 use libc::{mmap, mprotect};
246 use libc::{MAP_ANON, MAP_FAILED, MAP_FIXED, MAP_PRIVATE, PROT_NONE, PROT_READ, PROT_WRITE};
248 use crate::ops::Range;
249 use crate::sync::atomic::{AtomicUsize, Ordering};
252 // This is initialized in init() and only read from after
253 static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0);
255 pub type Guard = Range<usize>;
257 #[cfg(target_os = "solaris")]
258 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
259 let mut current_stack: libc::stack_t = crate::mem::zeroed();
260 assert_eq!(libc::stack_getbounds(&mut current_stack), 0);
261 Some(current_stack.ss_sp)
264 #[cfg(target_os = "macos")]
265 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
266 let th = libc::pthread_self();
268 libc::pthread_get_stackaddr_np(th) as usize - libc::pthread_get_stacksize_np(th);
269 Some(stackaddr as *mut libc::c_void)
272 #[cfg(target_os = "openbsd")]
273 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
274 let mut current_stack: libc::stack_t = crate::mem::zeroed();
275 assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(), &mut current_stack), 0);
277 let stackaddr = if libc::pthread_main_np() == 1 {
279 current_stack.ss_sp as usize - current_stack.ss_size + PAGE_SIZE.load(Ordering::Relaxed)
282 current_stack.ss_sp as usize - current_stack.ss_size
284 Some(stackaddr as *mut libc::c_void)
288 target_os = "android",
289 target_os = "freebsd",
291 target_os = "netbsd",
294 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
296 let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
297 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
298 #[cfg(target_os = "freebsd")]
299 let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
300 #[cfg(not(target_os = "freebsd"))]
301 let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
303 let mut stackaddr = crate::ptr::null_mut();
304 let mut stacksize = 0;
305 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut stacksize), 0);
306 ret = Some(stackaddr);
308 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
312 // Precondition: PAGE_SIZE is initialized.
313 unsafe fn get_stack_start_aligned() -> Option<*mut libc::c_void> {
314 let page_size = PAGE_SIZE.load(Ordering::Relaxed);
315 assert!(page_size != 0);
316 let stackaddr = get_stack_start()?;
318 // Ensure stackaddr is page aligned! A parent process might
319 // have reset RLIMIT_STACK to be non-page aligned. The
320 // pthread_attr_getstack() reports the usable stack area
321 // stackaddr < stackaddr + stacksize, so if stackaddr is not
322 // page-aligned, calculate the fix such that stackaddr <
323 // new_page_aligned_stackaddr < stackaddr + stacksize
324 let remainder = (stackaddr as usize) % page_size;
325 Some(if remainder == 0 {
328 ((stackaddr as usize) + page_size - remainder) as *mut libc::c_void
332 pub unsafe fn init() -> Option<Guard> {
333 let page_size = os::page_size();
334 PAGE_SIZE.store(page_size, Ordering::Relaxed);
336 let stackaddr = get_stack_start_aligned()?;
338 if cfg!(target_os = "linux") {
339 // Linux doesn't allocate the whole stack right away, and
340 // the kernel has its own stack-guard mechanism to fault
341 // when growing too close to an existing mapping. If we map
342 // our own guard, then the kernel starts enforcing a rather
343 // large gap above that, rendering much of the possible
344 // stack space useless. See #43052.
346 // Instead, we'll just note where we expect rlimit to start
347 // faulting, so our handler can report "stack overflow", and
348 // trust that the kernel's own stack guard will work.
349 let stackaddr = stackaddr as usize;
350 Some(stackaddr - page_size..stackaddr)
352 // Reallocate the last page of the stack.
353 // This ensures SIGBUS will be raised on
355 // Systems which enforce strict PAX MPROTECT do not allow
356 // to mprotect() a mapping with less restrictive permissions
357 // than the initial mmap() used, so we mmap() here with
358 // read/write permissions and only then mprotect() it to
359 // no permissions at all. See issue #50313.
363 PROT_READ | PROT_WRITE,
364 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
368 if result != stackaddr || result == MAP_FAILED {
369 panic!("failed to allocate a guard page");
372 let result = mprotect(stackaddr, page_size, PROT_NONE);
374 panic!("failed to protect the guard page");
377 let guardaddr = stackaddr as usize;
378 let offset = if cfg!(target_os = "freebsd") { 2 } else { 1 };
380 Some(guardaddr..guardaddr + offset * page_size)
384 #[cfg(any(target_os = "macos", target_os = "openbsd", target_os = "solaris"))]
385 pub unsafe fn current() -> Option<Guard> {
386 let stackaddr = get_stack_start()? as usize;
387 Some(stackaddr - PAGE_SIZE.load(Ordering::Relaxed)..stackaddr)
391 target_os = "android",
392 target_os = "freebsd",
394 target_os = "netbsd",
397 pub unsafe fn current() -> Option<Guard> {
399 let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
400 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
401 #[cfg(target_os = "freebsd")]
402 let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
403 #[cfg(not(target_os = "freebsd"))]
404 let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
406 let mut guardsize = 0;
407 assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
409 panic!("there is no guard page");
411 let mut stackaddr = crate::ptr::null_mut();
413 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut size), 0);
415 let stackaddr = stackaddr as usize;
416 ret = if cfg!(target_os = "freebsd") {
417 // FIXME does freebsd really fault *below* the guard addr?
418 let guardaddr = stackaddr - guardsize;
419 Some(guardaddr - PAGE_SIZE.load(Ordering::Relaxed)..guardaddr)
420 } else if cfg!(target_os = "netbsd") {
421 Some(stackaddr - guardsize..stackaddr)
422 } else if cfg!(all(target_os = "linux", target_env = "gnu")) {
423 // glibc used to include the guard area within the stack, as noted in the BUGS
424 // section of `man pthread_attr_getguardsize`. This has been corrected starting
425 // with glibc 2.27, and in some distro backports, so the guard is now placed at the
426 // end (below) the stack. There's no easy way for us to know which we have at
427 // runtime, so we'll just match any fault in the range right above or below the
428 // stack base to call that fault a stack overflow.
429 Some(stackaddr - guardsize..stackaddr + guardsize)
431 Some(stackaddr..stackaddr + guardsize)
434 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
439 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
440 // PTHREAD_STACK_MIN plus bytes needed for thread-local storage.
441 // We need that information to avoid blowing up when a small stack
442 // is created in an application with big thread-local storage requirements.
443 // See #6233 for rationale and details.
444 #[cfg(target_os = "linux")]
446 fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
447 weak!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);
449 match __pthread_get_minstack.get() {
450 None => libc::PTHREAD_STACK_MIN,
451 Some(f) => unsafe { f(attr) },
455 // No point in looking up __pthread_get_minstack() on non-glibc
457 #[cfg(all(not(target_os = "linux"), not(target_os = "netbsd")))]
458 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
459 libc::PTHREAD_STACK_MIN
462 #[cfg(target_os = "netbsd")]
463 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {