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.
11 use alloc::boxed::FnBox;
21 use sys_common::thread::*;
27 // Some platforms may have pthread_t as a pointer in which case we still want
28 // a thread to be Send/Sync
29 unsafe impl Send for Thread {}
30 unsafe impl Sync for Thread {}
32 // The pthread_attr_setstacksize symbol doesn't exist in the emscripten libc,
33 // so we have to not link to it to satisfy emcc's ERROR_ON_UNDEFINED_SYMBOLS.
34 #[cfg(not(target_os = "emscripten"))]
35 unsafe fn pthread_attr_setstacksize(attr: *mut libc::pthread_attr_t,
36 stack_size: libc::size_t) -> libc::c_int {
37 libc::pthread_attr_setstacksize(attr, stack_size)
40 #[cfg(target_os = "emscripten")]
41 unsafe fn pthread_attr_setstacksize(_attr: *mut libc::pthread_attr_t,
42 _stack_size: libc::size_t) -> libc::c_int {
47 pub unsafe fn new<'a>(stack: usize, p: Box<FnBox() + 'a>)
48 -> io::Result<Thread> {
50 let mut native: libc::pthread_t = mem::zeroed();
51 let mut attr: libc::pthread_attr_t = mem::zeroed();
52 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
54 let stack_size = cmp::max(stack, min_stack_size(&attr));
55 match pthread_attr_setstacksize(&mut attr,
56 stack_size as libc::size_t) {
59 assert_eq!(n, libc::EINVAL);
60 // EINVAL means |stack_size| is either too small or not a
61 // multiple of the system page size. Because it's definitely
62 // >= PTHREAD_STACK_MIN, it must be an alignment issue.
63 // Round up to the nearest page and try again.
64 let page_size = os::page_size();
65 let stack_size = (stack_size + page_size - 1) &
66 (-(page_size as isize - 1) as usize - 1);
67 let stack_size = stack_size as libc::size_t;
68 assert_eq!(libc::pthread_attr_setstacksize(&mut attr,
73 let ret = libc::pthread_create(&mut native, &attr, thread_start,
74 &*p as *const _ as *mut _);
75 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
78 Err(io::Error::from_raw_os_error(ret))
80 mem::forget(p); // ownership passed to pthread_create
81 Ok(Thread { id: native })
84 extern fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
85 unsafe { start_thread(main); }
91 let ret = unsafe { libc::sched_yield() };
92 debug_assert_eq!(ret, 0);
95 #[cfg(any(target_os = "linux",
96 target_os = "android"))]
97 pub fn set_name(name: &CStr) {
98 const PR_SET_NAME: libc::c_int = 15;
99 // pthread wrapper only appeared in glibc 2.12, so we use syscall
102 libc::prctl(PR_SET_NAME, name.as_ptr() as libc::c_ulong, 0, 0, 0);
106 #[cfg(any(target_os = "freebsd",
107 target_os = "dragonfly",
108 target_os = "bitrig",
109 target_os = "openbsd"))]
110 pub fn set_name(name: &CStr) {
112 libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
116 #[cfg(any(target_os = "macos", target_os = "ios"))]
117 pub fn set_name(name: &CStr) {
119 libc::pthread_setname_np(name.as_ptr());
123 #[cfg(target_os = "netbsd")]
124 pub fn set_name(name: &CStr) {
126 let cname = CString::new(&b"%s"[..]).unwrap();
128 libc::pthread_setname_np(libc::pthread_self(), cname.as_ptr(),
129 name.as_ptr() as *mut libc::c_void);
132 #[cfg(any(target_env = "newlib",
133 target_os = "solaris",
135 target_os = "emscripten"))]
136 pub fn set_name(_name: &CStr) {
137 // Newlib, Illumos, Haiku, and Emscripten have no way to set a thread name.
140 pub fn sleep(dur: Duration) {
141 let mut secs = dur.as_secs();
142 let mut nsecs = dur.subsec_nanos() as libc::c_long;
144 // If we're awoken with a signal then the return value will be -1 and
145 // nanosleep will fill in `ts` with the remaining time.
147 while secs > 0 || nsecs > 0 {
148 let mut ts = libc::timespec {
149 tv_sec: cmp::min(libc::time_t::max_value() as u64, secs) as libc::time_t,
152 secs -= ts.tv_sec as u64;
153 if libc::nanosleep(&ts, &mut ts) == -1 {
154 assert_eq!(os::errno(), libc::EINTR);
155 secs += ts.tv_sec as u64;
166 let ret = libc::pthread_join(self.id, ptr::null_mut());
168 debug_assert_eq!(ret, 0);
172 pub fn id(&self) -> libc::pthread_t { self.id }
174 pub fn into_id(self) -> libc::pthread_t {
181 impl Drop for Thread {
183 let ret = unsafe { libc::pthread_detach(self.id) };
184 debug_assert_eq!(ret, 0);
188 #[cfg(all(not(all(target_os = "linux", not(target_env = "musl"))),
189 not(target_os = "freebsd"),
190 not(target_os = "macos"),
191 not(target_os = "bitrig"),
192 not(all(target_os = "netbsd", not(target_vendor = "rumprun"))),
193 not(target_os = "openbsd"),
194 not(target_os = "solaris")))]
195 #[cfg_attr(test, allow(dead_code))]
197 pub unsafe fn current() -> Option<usize> { None }
198 pub unsafe fn init() -> Option<usize> { None }
202 #[cfg(any(all(target_os = "linux", not(target_env = "musl")),
203 target_os = "freebsd",
205 target_os = "bitrig",
206 all(target_os = "netbsd", not(target_vendor = "rumprun")),
207 target_os = "openbsd",
208 target_os = "solaris"))]
209 #[cfg_attr(test, allow(dead_code))]
213 use libc::{PROT_NONE, MAP_PRIVATE, MAP_ANON, MAP_FAILED, MAP_FIXED};
216 #[cfg(any(target_os = "macos",
217 target_os = "bitrig",
218 target_os = "openbsd",
219 target_os = "solaris"))]
220 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
221 current().map(|s| s as *mut libc::c_void)
224 #[cfg(any(target_os = "android", target_os = "freebsd",
225 target_os = "linux", target_os = "netbsd"))]
226 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
228 let mut attr: libc::pthread_attr_t = ::mem::zeroed();
229 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
230 #[cfg(target_os = "freebsd")]
231 let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
232 #[cfg(not(target_os = "freebsd"))]
233 let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
235 let mut stackaddr = ::ptr::null_mut();
236 let mut stacksize = 0;
237 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
239 ret = Some(stackaddr);
241 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
245 pub unsafe fn init() -> Option<usize> {
246 let psize = os::page_size();
247 let mut stackaddr = match get_stack_start() {
252 // Ensure stackaddr is page aligned! A parent process might
253 // have reset RLIMIT_STACK to be non-page aligned. The
254 // pthread_attr_getstack() reports the usable stack area
255 // stackaddr < stackaddr + stacksize, so if stackaddr is not
256 // page-aligned, calculate the fix such that stackaddr <
257 // new_page_aligned_stackaddr < stackaddr + stacksize
258 let remainder = (stackaddr as usize) % psize;
260 stackaddr = ((stackaddr as usize) + psize - remainder)
261 as *mut libc::c_void;
264 // Rellocate the last page of the stack.
265 // This ensures SIGBUS will be raised on
267 let result = mmap(stackaddr,
268 psize as libc::size_t,
270 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
274 if result != stackaddr || result == MAP_FAILED {
275 panic!("failed to allocate a guard page");
278 let offset = if cfg!(any(target_os = "linux", target_os = "freebsd")) {
284 Some(stackaddr as usize + offset * psize)
287 #[cfg(target_os = "solaris")]
288 pub unsafe fn current() -> Option<usize> {
289 let mut current_stack: libc::stack_t = ::mem::zeroed();
290 assert_eq!(libc::stack_getbounds(&mut current_stack), 0);
291 Some(current_stack.ss_sp as usize)
294 #[cfg(target_os = "macos")]
295 pub unsafe fn current() -> Option<usize> {
296 Some((libc::pthread_get_stackaddr_np(libc::pthread_self()) as libc::size_t -
297 libc::pthread_get_stacksize_np(libc::pthread_self())) as usize)
300 #[cfg(any(target_os = "openbsd", target_os = "bitrig"))]
301 pub unsafe fn current() -> Option<usize> {
302 let mut current_stack: libc::stack_t = ::mem::zeroed();
303 assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(),
304 &mut current_stack), 0);
306 let extra = if cfg!(target_os = "bitrig") {3} else {1} * os::page_size();
307 Some(if libc::pthread_main_np() == 1 {
309 current_stack.ss_sp as usize - current_stack.ss_size as usize + extra
312 current_stack.ss_sp as usize - current_stack.ss_size as usize
316 #[cfg(any(target_os = "android", target_os = "freebsd",
317 target_os = "linux", target_os = "netbsd"))]
318 pub unsafe fn current() -> Option<usize> {
320 let mut attr: libc::pthread_attr_t = ::mem::zeroed();
321 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
322 #[cfg(target_os = "freebsd")]
323 let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
324 #[cfg(not(target_os = "freebsd"))]
325 let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
327 let mut guardsize = 0;
328 assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
330 panic!("there is no guard page");
332 let mut stackaddr = ::ptr::null_mut();
334 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
337 ret = if cfg!(target_os = "freebsd") {
338 Some(stackaddr as usize - guardsize as usize)
339 } else if cfg!(target_os = "netbsd") {
340 Some(stackaddr as usize)
342 Some(stackaddr as usize + guardsize as usize)
345 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
350 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
351 // PTHREAD_STACK_MIN plus however many bytes are needed for thread-local
352 // storage. We need that information to avoid blowing up when a small stack
353 // is created in an application with big thread-local storage requirements.
354 // See #6233 for rationale and details.
355 #[cfg(target_os = "linux")]
357 fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
358 weak!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);
360 match __pthread_get_minstack.get() {
361 None => libc::PTHREAD_STACK_MIN as usize,
362 Some(f) => unsafe { f(attr) as usize },
366 // No point in looking up __pthread_get_minstack() on non-glibc
368 #[cfg(all(not(target_os = "linux"),
369 not(target_os = "netbsd")))]
370 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
371 libc::PTHREAD_STACK_MIN as usize
374 #[cfg(target_os = "netbsd")]
375 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {