1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
21 use sys_common::thread::*;
23 #[cfg(not(target_os = "l4re"))]
24 pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
25 #[cfg(target_os = "l4re")]
26 pub const DEFAULT_MIN_STACK_SIZE: usize = 1024 * 1024;
32 // Some platforms may have pthread_t as a pointer in which case we still want
33 // a thread to be Send/Sync
34 unsafe impl Send for Thread {}
35 unsafe impl Sync for Thread {}
37 // The pthread_attr_setstacksize symbol doesn't exist in the emscripten libc,
38 // so we have to not link to it to satisfy emcc's ERROR_ON_UNDEFINED_SYMBOLS.
39 #[cfg(not(target_os = "emscripten"))]
40 unsafe fn pthread_attr_setstacksize(attr: *mut libc::pthread_attr_t,
41 stack_size: libc::size_t) -> libc::c_int {
42 libc::pthread_attr_setstacksize(attr, stack_size)
45 #[cfg(target_os = "emscripten")]
46 unsafe fn pthread_attr_setstacksize(_attr: *mut libc::pthread_attr_t,
47 _stack_size: libc::size_t) -> libc::c_int {
52 // unsafe: see thread::Builder::spawn_unchecked for safety requirements
53 pub unsafe fn new(stack: usize, p: Box<dyn FnBox()>)
54 -> io::Result<Thread> {
56 let mut native: libc::pthread_t = mem::zeroed();
57 let mut attr: libc::pthread_attr_t = mem::zeroed();
58 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
60 let stack_size = cmp::max(stack, min_stack_size(&attr));
62 match pthread_attr_setstacksize(&mut attr,
66 assert_eq!(n, libc::EINVAL);
67 // EINVAL means |stack_size| is either too small or not a
68 // multiple of the system page size. Because it's definitely
69 // >= PTHREAD_STACK_MIN, it must be an alignment issue.
70 // Round up to the nearest page and try again.
71 let page_size = os::page_size();
72 let stack_size = (stack_size + page_size - 1) &
73 (-(page_size as isize - 1) as usize - 1);
74 assert_eq!(libc::pthread_attr_setstacksize(&mut attr,
79 let ret = libc::pthread_create(&mut native, &attr, thread_start,
80 &*p as *const _ as *mut _);
81 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
84 Err(io::Error::from_raw_os_error(ret))
86 mem::forget(p); // ownership passed to pthread_create
87 Ok(Thread { id: native })
90 extern fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
91 unsafe { start_thread(main as *mut u8); }
97 let ret = unsafe { libc::sched_yield() };
98 debug_assert_eq!(ret, 0);
101 #[cfg(any(target_os = "linux",
102 target_os = "android"))]
103 pub fn set_name(name: &CStr) {
104 const PR_SET_NAME: libc::c_int = 15;
105 // pthread wrapper only appeared in glibc 2.12, so we use syscall
108 libc::prctl(PR_SET_NAME, name.as_ptr() as libc::c_ulong, 0, 0, 0);
112 #[cfg(any(target_os = "freebsd",
113 target_os = "dragonfly",
114 target_os = "bitrig",
115 target_os = "openbsd"))]
116 pub fn set_name(name: &CStr) {
118 libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
122 #[cfg(any(target_os = "macos", target_os = "ios"))]
123 pub fn set_name(name: &CStr) {
125 libc::pthread_setname_np(name.as_ptr());
129 #[cfg(target_os = "netbsd")]
130 pub fn set_name(name: &CStr) {
132 let cname = CString::new(&b"%s"[..]).unwrap();
134 libc::pthread_setname_np(libc::pthread_self(), cname.as_ptr(),
135 name.as_ptr() as *mut libc::c_void);
138 #[cfg(any(target_env = "newlib",
139 target_os = "solaris",
142 target_os = "emscripten",
143 target_os = "hermit"))]
144 pub fn set_name(_name: &CStr) {
145 // Newlib, Illumos, Haiku, and Emscripten have no way to set a thread name.
147 #[cfg(target_os = "fuchsia")]
148 pub fn set_name(_name: &CStr) {
149 // FIXME: determine whether Fuchsia has a way to set a thread name.
152 pub fn sleep(dur: Duration) {
153 let mut secs = dur.as_secs();
154 let mut nsecs = dur.subsec_nanos() as _;
156 // If we're awoken with a signal then the return value will be -1 and
157 // nanosleep will fill in `ts` with the remaining time.
159 while secs > 0 || nsecs > 0 {
160 let mut ts = libc::timespec {
161 tv_sec: cmp::min(libc::time_t::max_value() as u64, secs) as libc::time_t,
164 secs -= ts.tv_sec as u64;
165 if libc::nanosleep(&ts, &mut ts) == -1 {
166 assert_eq!(os::errno(), libc::EINTR);
167 secs += ts.tv_sec as u64;
178 let ret = libc::pthread_join(self.id, ptr::null_mut());
181 "failed to join thread: {}", io::Error::from_raw_os_error(ret));
185 pub fn id(&self) -> libc::pthread_t { self.id }
187 pub fn into_id(self) -> libc::pthread_t {
194 impl Drop for Thread {
196 let ret = unsafe { libc::pthread_detach(self.id) };
197 debug_assert_eq!(ret, 0);
201 #[cfg(all(not(all(target_os = "linux", not(target_env = "musl"))),
202 not(target_os = "freebsd"),
203 not(target_os = "macos"),
204 not(target_os = "bitrig"),
205 not(all(target_os = "netbsd", not(target_vendor = "rumprun"))),
206 not(target_os = "openbsd"),
207 not(target_os = "solaris")))]
208 #[cfg_attr(test, allow(dead_code))]
211 pub type Guard = Range<usize>;
212 pub unsafe fn current() -> Option<Guard> { None }
213 pub unsafe fn init() -> Option<Guard> { None }
214 pub unsafe fn deinit() {}
218 #[cfg(any(all(target_os = "linux", not(target_env = "musl")),
219 target_os = "freebsd",
221 target_os = "bitrig",
222 all(target_os = "netbsd", not(target_vendor = "rumprun")),
223 target_os = "openbsd",
224 target_os = "solaris"))]
225 #[cfg_attr(test, allow(dead_code))]
228 use libc::{mmap, mprotect};
229 use libc::{PROT_NONE, PROT_READ, PROT_WRITE, MAP_PRIVATE, MAP_ANON, MAP_FAILED, MAP_FIXED};
233 // This is initialized in init() and only read from after
234 static mut PAGE_SIZE: usize = 0;
236 pub type Guard = Range<usize>;
238 #[cfg(target_os = "solaris")]
239 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
240 let mut current_stack: libc::stack_t = ::mem::zeroed();
241 assert_eq!(libc::stack_getbounds(&mut current_stack), 0);
242 Some(current_stack.ss_sp)
245 #[cfg(target_os = "macos")]
246 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
247 let stackaddr = libc::pthread_get_stackaddr_np(libc::pthread_self()) as usize -
248 libc::pthread_get_stacksize_np(libc::pthread_self());
249 Some(stackaddr as *mut libc::c_void)
252 #[cfg(any(target_os = "openbsd", target_os = "bitrig"))]
253 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
254 let mut current_stack: libc::stack_t = ::mem::zeroed();
255 assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(),
256 &mut current_stack), 0);
258 let extra = if cfg!(target_os = "bitrig") {3} else {1} * PAGE_SIZE;
259 let stackaddr = if libc::pthread_main_np() == 1 {
261 current_stack.ss_sp as usize - current_stack.ss_size + extra
264 current_stack.ss_sp as usize - current_stack.ss_size
266 Some(stackaddr as *mut libc::c_void)
269 #[cfg(any(target_os = "android", target_os = "freebsd",
270 target_os = "linux", target_os = "netbsd", target_os = "l4re"))]
271 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
273 let mut attr: libc::pthread_attr_t = ::mem::zeroed();
274 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
275 #[cfg(target_os = "freebsd")]
276 let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
277 #[cfg(not(target_os = "freebsd"))]
278 let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
280 let mut stackaddr = ::ptr::null_mut();
281 let mut stacksize = 0;
282 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
284 ret = Some(stackaddr);
286 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
290 // Precondition: PAGE_SIZE is initialized.
291 unsafe fn get_stack_start_aligned() -> Option<*mut libc::c_void> {
292 assert!(PAGE_SIZE != 0);
293 let stackaddr = get_stack_start()?;
295 // Ensure stackaddr is page aligned! A parent process might
296 // have reset RLIMIT_STACK to be non-page aligned. The
297 // pthread_attr_getstack() reports the usable stack area
298 // stackaddr < stackaddr + stacksize, so if stackaddr is not
299 // page-aligned, calculate the fix such that stackaddr <
300 // new_page_aligned_stackaddr < stackaddr + stacksize
301 let remainder = (stackaddr as usize) % PAGE_SIZE;
302 Some(if remainder == 0 {
305 ((stackaddr as usize) + PAGE_SIZE - remainder) as *mut libc::c_void
309 pub unsafe fn init() -> Option<Guard> {
310 PAGE_SIZE = os::page_size();
312 let stackaddr = get_stack_start_aligned()?;
314 if cfg!(target_os = "linux") {
315 // Linux doesn't allocate the whole stack right away, and
316 // the kernel has its own stack-guard mechanism to fault
317 // when growing too close to an existing mapping. If we map
318 // our own guard, then the kernel starts enforcing a rather
319 // large gap above that, rendering much of the possible
320 // stack space useless. See #43052.
322 // Instead, we'll just note where we expect rlimit to start
323 // faulting, so our handler can report "stack overflow", and
324 // trust that the kernel's own stack guard will work.
325 let stackaddr = stackaddr as usize;
326 Some(stackaddr - PAGE_SIZE..stackaddr)
328 // Reallocate the last page of the stack.
329 // This ensures SIGBUS will be raised on
331 // Systems which enforce strict PAX MPROTECT do not allow
332 // to mprotect() a mapping with less restrictive permissions
333 // than the initial mmap() used, so we mmap() here with
334 // read/write permissions and only then mprotect() it to
335 // no permissions at all. See issue #50313.
336 let result = mmap(stackaddr, PAGE_SIZE, PROT_READ | PROT_WRITE,
337 MAP_PRIVATE | MAP_ANON | MAP_FIXED, -1, 0);
338 if result != stackaddr || result == MAP_FAILED {
339 panic!("failed to allocate a guard page");
342 let result = mprotect(stackaddr, PAGE_SIZE, PROT_NONE);
344 panic!("failed to protect the guard page");
347 let guardaddr = stackaddr as usize;
348 let offset = if cfg!(target_os = "freebsd") {
354 Some(guardaddr..guardaddr + offset * PAGE_SIZE)
358 pub unsafe fn deinit() {
359 if !cfg!(target_os = "linux") {
360 if let Some(stackaddr) = get_stack_start_aligned() {
361 // Remove the protection on the guard page.
362 // FIXME: we cannot unmap the page, because when we mmap()
363 // above it may be already mapped by the OS, which we can't
364 // detect from mmap()'s return value. If we unmap this page,
365 // it will lead to failure growing stack size on platforms like
366 // macOS. Instead, just restore the page to a writable state.
367 // This ain't Linux, so we probably don't need to care about
369 let result = mprotect(stackaddr, PAGE_SIZE, PROT_READ | PROT_WRITE);
372 panic!("unable to reset the guard page");
378 #[cfg(any(target_os = "macos",
379 target_os = "bitrig",
380 target_os = "openbsd",
381 target_os = "solaris"))]
382 pub unsafe fn current() -> Option<Guard> {
383 let stackaddr = get_stack_start()? as usize;
384 Some(stackaddr - PAGE_SIZE..stackaddr)
387 #[cfg(any(target_os = "android", target_os = "freebsd",
388 target_os = "linux", target_os = "netbsd", target_os = "l4re"))]
389 pub unsafe fn current() -> Option<Guard> {
391 let mut attr: libc::pthread_attr_t = ::mem::zeroed();
392 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
393 #[cfg(target_os = "freebsd")]
394 let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
395 #[cfg(not(target_os = "freebsd"))]
396 let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
398 let mut guardsize = 0;
399 assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
401 panic!("there is no guard page");
403 let mut stackaddr = ::ptr::null_mut();
405 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
408 let stackaddr = stackaddr as usize;
409 ret = if cfg!(target_os = "freebsd") {
410 // FIXME does freebsd really fault *below* the guard addr?
411 let guardaddr = stackaddr - guardsize;
412 Some(guardaddr - PAGE_SIZE..guardaddr)
413 } else if cfg!(target_os = "netbsd") {
414 Some(stackaddr - guardsize..stackaddr)
415 } else if cfg!(all(target_os = "linux", target_env = "gnu")) {
416 // glibc used to include the guard area within the stack, as noted in the BUGS
417 // section of `man pthread_attr_getguardsize`. This has been corrected starting
418 // with glibc 2.27, and in some distro backports, so the guard is now placed at the
419 // end (below) the stack. There's no easy way for us to know which we have at
420 // runtime, so we'll just match any fault in the range right above or below the
421 // stack base to call that fault a stack overflow.
422 Some(stackaddr - guardsize..stackaddr + guardsize)
424 Some(stackaddr..stackaddr + guardsize)
427 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
432 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
433 // PTHREAD_STACK_MIN plus however many bytes are needed for thread-local
434 // storage. We need that information to avoid blowing up when a small stack
435 // is created in an application with big thread-local storage requirements.
436 // See #6233 for rationale and details.
437 #[cfg(target_os = "linux")]
439 fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
440 weak!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);
442 match __pthread_get_minstack.get() {
443 None => libc::PTHREAD_STACK_MIN,
444 Some(f) => unsafe { f(attr) },
448 // No point in looking up __pthread_get_minstack() on non-glibc
450 #[cfg(all(not(target_os = "linux"),
451 not(target_os = "netbsd")))]
452 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
453 libc::PTHREAD_STACK_MIN
456 #[cfg(target_os = "netbsd")]
457 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {