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.
15 use alloc::boxed::FnBox;
19 use libc::consts::os::posix01::PTHREAD_STACK_MIN;
26 use sys_common::stack::RED_ZONE;
27 use sys_common::thread::*;
33 // Some platforms may have pthread_t as a pointer in which case we still want
34 // a thread to be Send/Sync
35 unsafe impl Send for Thread {}
36 unsafe impl Sync for Thread {}
39 pub unsafe fn new<'a>(stack: usize, p: Box<FnBox() + 'a>)
40 -> io::Result<Thread> {
42 let mut native: libc::pthread_t = mem::zeroed();
43 let mut attr: libc::pthread_attr_t = mem::zeroed();
44 assert_eq!(pthread_attr_init(&mut attr), 0);
46 // Reserve room for the red zone, the runtime's stack of last resort.
47 let stack_size = cmp::max(stack, RED_ZONE + min_stack_size(&attr));
48 match pthread_attr_setstacksize(&mut attr, stack_size as libc::size_t) {
51 assert_eq!(n, libc::EINVAL);
52 // EINVAL means |stack_size| is either too small or not a
53 // multiple of the system page size. Because it's definitely
54 // >= PTHREAD_STACK_MIN, it must be an alignment issue.
55 // Round up to the nearest page and try again.
56 let page_size = os::page_size();
57 let stack_size = (stack_size + page_size - 1) &
58 (-(page_size as isize - 1) as usize - 1);
59 let stack_size = stack_size as libc::size_t;
60 assert_eq!(pthread_attr_setstacksize(&mut attr, stack_size), 0);
64 let ret = pthread_create(&mut native, &attr, thread_start,
65 &*p as *const _ as *mut _);
66 assert_eq!(pthread_attr_destroy(&mut attr), 0);
69 Err(io::Error::from_raw_os_error(ret))
71 mem::forget(p); // ownership passed to pthread_create
72 Ok(Thread { id: native })
76 extern fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
77 unsafe { start_thread(main); }
83 let ret = unsafe { sched_yield() };
84 debug_assert_eq!(ret, 0);
87 #[cfg(any(target_os = "linux", target_os = "android"))]
88 pub fn set_name(name: &str) {
89 // pthread wrapper only appeared in glibc 2.12, so we use syscall
92 fn prctl(option: libc::c_int, arg2: libc::c_ulong,
93 arg3: libc::c_ulong, arg4: libc::c_ulong,
94 arg5: libc::c_ulong) -> libc::c_int;
96 const PR_SET_NAME: libc::c_int = 15;
97 let cname = CString::new(name).unwrap_or_else(|_| {
98 panic!("thread name may not contain interior null bytes")
101 prctl(PR_SET_NAME, cname.as_ptr() as libc::c_ulong, 0, 0, 0);
105 #[cfg(any(target_os = "freebsd",
106 target_os = "dragonfly",
107 target_os = "bitrig",
108 target_os = "netbsd",
109 target_os = "openbsd"))]
110 pub fn set_name(name: &str) {
112 fn pthread_set_name_np(tid: libc::pthread_t,
113 name: *const libc::c_char);
115 let cname = CString::new(name).unwrap();
117 pthread_set_name_np(pthread_self(), cname.as_ptr());
121 #[cfg(any(target_os = "macos", target_os = "ios"))]
122 pub fn set_name(name: &str) {
124 fn pthread_setname_np(name: *const libc::c_char) -> libc::c_int;
126 let cname = CString::new(name).unwrap();
128 pthread_setname_np(cname.as_ptr());
132 pub fn sleep(dur: Duration) {
133 let mut ts = libc::timespec {
134 tv_sec: dur.secs() as libc::time_t,
135 tv_nsec: dur.extra_nanos() as libc::c_long,
138 // If we're awoken with a signal then the return value will be -1 and
139 // nanosleep will fill in `ts` with the remaining time.
141 while libc::nanosleep(&ts, &mut ts) == -1 {
142 assert_eq!(os::errno(), libc::EINTR);
149 let ret = pthread_join(self.id, ptr::null_mut());
151 debug_assert_eq!(ret, 0);
156 impl Drop for Thread {
158 let ret = unsafe { pthread_detach(self.id) };
159 debug_assert_eq!(ret, 0);
163 #[cfg(all(not(target_os = "linux"),
164 not(target_os = "macos"),
165 not(target_os = "bitrig"),
166 not(target_os = "netbsd"),
167 not(target_os = "openbsd")))]
169 pub unsafe fn current() -> usize { 0 }
170 pub unsafe fn main() -> usize { 0 }
171 pub unsafe fn init() {}
175 #[cfg(any(target_os = "linux",
177 target_os = "bitrig",
178 target_os = "netbsd",
179 target_os = "openbsd"))]
180 #[allow(unused_imports)]
182 use libc::{self, pthread_t};
183 use libc::funcs::posix88::mman::mmap;
184 use libc::consts::os::posix88::{PROT_NONE,
191 use super::{pthread_self, pthread_attr_destroy};
194 // These are initialized in init() and only read from after
195 static mut GUARD_PAGE: usize = 0;
197 #[cfg(any(target_os = "macos",
198 target_os = "bitrig",
199 target_os = "netbsd",
200 target_os = "openbsd"))]
201 unsafe fn get_stack_start() -> *mut libc::c_void {
202 current() as *mut libc::c_void
205 #[cfg(any(target_os = "linux", target_os = "android"))]
206 unsafe fn get_stack_start() -> *mut libc::c_void {
207 let mut attr: libc::pthread_attr_t = mem::zeroed();
208 assert_eq!(pthread_getattr_np(pthread_self(), &mut attr), 0);
209 let mut stackaddr = ptr::null_mut();
210 let mut stacksize = 0;
211 assert_eq!(pthread_attr_getstack(&attr, &mut stackaddr, &mut stacksize), 0);
212 assert_eq!(pthread_attr_destroy(&mut attr), 0);
216 pub unsafe fn init() {
217 let psize = os::page_size();
218 let mut stackaddr = get_stack_start();
220 // Ensure stackaddr is page aligned! A parent process might
221 // have reset RLIMIT_STACK to be non-page aligned. The
222 // pthread_attr_getstack() reports the usable stack area
223 // stackaddr < stackaddr + stacksize, so if stackaddr is not
224 // page-aligned, calculate the fix such that stackaddr <
225 // new_page_aligned_stackaddr < stackaddr + stacksize
226 let remainder = (stackaddr as usize) % psize;
228 stackaddr = ((stackaddr as usize) + psize - remainder)
229 as *mut libc::c_void;
232 // Rellocate the last page of the stack.
233 // This ensures SIGBUS will be raised on
235 let result = mmap(stackaddr,
236 psize as libc::size_t,
238 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
242 if result != stackaddr || result == MAP_FAILED {
243 panic!("failed to allocate a guard page");
246 let offset = if cfg!(target_os = "linux") {2} else {1};
248 GUARD_PAGE = stackaddr as usize + offset * psize;
251 pub unsafe fn main() -> usize {
255 #[cfg(target_os = "macos")]
256 pub unsafe fn current() -> usize {
258 fn pthread_get_stackaddr_np(thread: pthread_t) -> *mut libc::c_void;
259 fn pthread_get_stacksize_np(thread: pthread_t) -> libc::size_t;
261 (pthread_get_stackaddr_np(pthread_self()) as libc::size_t -
262 pthread_get_stacksize_np(pthread_self())) as usize
265 #[cfg(any(target_os = "openbsd", target_os = "netbsd", target_os = "bitrig"))]
266 pub unsafe fn current() -> usize {
269 ss_sp: *mut libc::c_void,
270 ss_size: libc::size_t,
271 ss_flags: libc::c_int,
274 fn pthread_main_np() -> libc::c_uint;
275 fn pthread_stackseg_np(thread: pthread_t,
276 sinfo: *mut stack_t) -> libc::c_uint;
279 let mut current_stack: stack_t = mem::zeroed();
280 assert_eq!(pthread_stackseg_np(pthread_self(), &mut current_stack), 0);
282 let extra = if cfg!(target_os = "bitrig") {3} else {1} * os::page_size();
283 if pthread_main_np() == 1 {
285 current_stack.ss_sp as usize - current_stack.ss_size as usize + extra
288 current_stack.ss_sp as usize - current_stack.ss_size as usize
292 #[cfg(any(target_os = "linux", target_os = "android"))]
293 pub unsafe fn current() -> usize {
294 let mut attr: libc::pthread_attr_t = mem::zeroed();
295 assert_eq!(pthread_getattr_np(pthread_self(), &mut attr), 0);
296 let mut guardsize = 0;
297 assert_eq!(pthread_attr_getguardsize(&attr, &mut guardsize), 0);
299 panic!("there is no guard page");
301 let mut stackaddr = ptr::null_mut();
303 assert_eq!(pthread_attr_getstack(&attr, &mut stackaddr, &mut size), 0);
304 assert_eq!(pthread_attr_destroy(&mut attr), 0);
306 stackaddr as usize + guardsize as usize
309 #[cfg(any(target_os = "linux", target_os = "android"))]
311 fn pthread_getattr_np(native: libc::pthread_t,
312 attr: *mut libc::pthread_attr_t) -> libc::c_int;
313 fn pthread_attr_getguardsize(attr: *const libc::pthread_attr_t,
314 guardsize: *mut libc::size_t) -> libc::c_int;
315 fn pthread_attr_getstack(attr: *const libc::pthread_attr_t,
316 stackaddr: *mut *mut libc::c_void,
317 stacksize: *mut libc::size_t) -> libc::c_int;
321 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
322 // PTHREAD_STACK_MIN plus however many bytes are needed for thread-local
323 // storage. We need that information to avoid blowing up when a small stack
324 // is created in an application with big thread-local storage requirements.
325 // See #6233 for rationale and details.
327 // Use dlsym to get the symbol value at runtime, both for
328 // compatibility with older versions of glibc, and to avoid creating
329 // dependencies on GLIBC_PRIVATE symbols. Assumes that we've been
330 // dynamically linked to libpthread but that is currently always the
331 // case. We previously used weak linkage (under the same assumption),
332 // but that caused Debian to detect an unnecessarily strict versioned
333 // dependency on libc6 (#23628).
334 #[cfg(target_os = "linux")]
335 fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
336 use dynamic_lib::DynamicLibrary;
339 type F = unsafe extern "C" fn(*const libc::pthread_attr_t) -> libc::size_t;
340 static INIT: Once = Once::new();
341 static mut __pthread_get_minstack: Option<F> = None;
344 let lib = match DynamicLibrary::open(None) {
349 if let Ok(f) = lib.symbol("__pthread_get_minstack") {
350 __pthread_get_minstack = Some(mem::transmute::<*const (), F>(f));
355 match unsafe { __pthread_get_minstack } {
356 None => PTHREAD_STACK_MIN as usize,
357 Some(f) => unsafe { f(attr) as usize },
361 // No point in looking up __pthread_get_minstack() on non-glibc
363 #[cfg(not(target_os = "linux"))]
364 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
365 PTHREAD_STACK_MIN as usize
369 fn pthread_self() -> libc::pthread_t;
370 fn pthread_create(native: *mut libc::pthread_t,
371 attr: *const libc::pthread_attr_t,
372 f: extern fn(*mut libc::c_void) -> *mut libc::c_void,
373 value: *mut libc::c_void) -> libc::c_int;
374 fn pthread_join(native: libc::pthread_t,
375 value: *mut *mut libc::c_void) -> libc::c_int;
376 fn pthread_attr_init(attr: *mut libc::pthread_attr_t) -> libc::c_int;
377 fn pthread_attr_destroy(attr: *mut libc::pthread_attr_t) -> libc::c_int;
378 fn pthread_attr_setstacksize(attr: *mut libc::pthread_attr_t,
379 stack_size: libc::size_t) -> libc::c_int;
380 fn pthread_attr_setdetachstate(attr: *mut libc::pthread_attr_t,
381 state: libc::c_int) -> libc::c_int;
382 fn pthread_detach(thread: libc::pthread_t) -> libc::c_int;
383 fn sched_yield() -> libc::c_int;