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 {}
33 pub unsafe fn new<'a>(stack: usize, p: Box<FnBox() + 'a>)
34 -> io::Result<Thread> {
36 let mut native: libc::pthread_t = mem::zeroed();
37 let mut attr: libc::pthread_attr_t = mem::zeroed();
38 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
40 let stack_size = cmp::max(stack, min_stack_size(&attr));
41 match libc::pthread_attr_setstacksize(&mut attr,
42 stack_size as libc::size_t) {
45 assert_eq!(n, libc::EINVAL);
46 // EINVAL means |stack_size| is either too small or not a
47 // multiple of the system page size. Because it's definitely
48 // >= PTHREAD_STACK_MIN, it must be an alignment issue.
49 // Round up to the nearest page and try again.
50 let page_size = os::page_size();
51 let stack_size = (stack_size + page_size - 1) &
52 (-(page_size as isize - 1) as usize - 1);
53 let stack_size = stack_size as libc::size_t;
54 assert_eq!(libc::pthread_attr_setstacksize(&mut attr,
59 let ret = libc::pthread_create(&mut native, &attr, thread_start,
60 &*p as *const _ as *mut _);
61 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
64 Err(io::Error::from_raw_os_error(ret))
66 mem::forget(p); // ownership passed to pthread_create
67 Ok(Thread { id: native })
70 extern fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
71 unsafe { start_thread(main); }
77 let ret = unsafe { libc::sched_yield() };
78 debug_assert_eq!(ret, 0);
81 #[cfg(any(target_os = "linux",
82 target_os = "android"))]
83 pub fn set_name(name: &CStr) {
84 const PR_SET_NAME: libc::c_int = 15;
85 // pthread wrapper only appeared in glibc 2.12, so we use syscall
88 libc::prctl(PR_SET_NAME, name.as_ptr() as libc::c_ulong, 0, 0, 0);
92 #[cfg(any(target_os = "freebsd",
93 target_os = "dragonfly",
95 target_os = "openbsd"))]
96 pub fn set_name(name: &CStr) {
98 libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
102 #[cfg(any(target_os = "macos", target_os = "ios"))]
103 pub fn set_name(name: &CStr) {
105 libc::pthread_setname_np(name.as_ptr());
109 #[cfg(target_os = "netbsd")]
110 pub fn set_name(name: &CStr) {
112 let cname = CString::new(&b"%s"[..]).unwrap();
114 libc::pthread_setname_np(libc::pthread_self(), cname.as_ptr(),
115 name.as_ptr() as *mut libc::c_void);
118 #[cfg(any(target_env = "newlib", target_os = "solaris", target_os = "emscripten"))]
119 pub fn set_name(_name: &CStr) {
120 // Newlib, Illumos and Emscripten have no way to set a thread name.
123 #[cfg(target_os = "haiku")]
124 pub fn set_name(_name: &CStr) {
125 // Haiku has no way to set a thread name.
128 pub fn sleep(dur: Duration) {
129 let mut secs = dur.as_secs();
130 let mut nsecs = dur.subsec_nanos() as libc::c_long;
132 // If we're awoken with a signal then the return value will be -1 and
133 // nanosleep will fill in `ts` with the remaining time.
135 while secs > 0 || nsecs > 0 {
136 let mut ts = libc::timespec {
137 tv_sec: cmp::min(libc::time_t::max_value() as u64, secs) as libc::time_t,
140 secs -= ts.tv_sec as u64;
141 if libc::nanosleep(&ts, &mut ts) == -1 {
142 assert_eq!(os::errno(), libc::EINTR);
143 secs += ts.tv_sec as u64;
154 let ret = libc::pthread_join(self.id, ptr::null_mut());
156 debug_assert_eq!(ret, 0);
160 pub fn id(&self) -> libc::pthread_t { self.id }
162 pub fn into_id(self) -> libc::pthread_t {
169 impl Drop for Thread {
171 let ret = unsafe { libc::pthread_detach(self.id) };
172 debug_assert_eq!(ret, 0);
176 #[cfg(all(not(all(target_os = "linux", not(target_env = "musl"))),
177 not(target_os = "freebsd"),
178 not(target_os = "macos"),
179 not(target_os = "bitrig"),
180 not(all(target_os = "netbsd", not(target_vendor = "rumprun"))),
181 not(target_os = "openbsd"),
182 not(target_os = "solaris")))]
183 #[cfg_attr(test, allow(dead_code))]
185 pub unsafe fn current() -> Option<usize> { None }
186 pub unsafe fn init() -> Option<usize> { None }
190 #[cfg(any(all(target_os = "linux", not(target_env = "musl")),
191 target_os = "freebsd",
193 target_os = "bitrig",
194 all(target_os = "netbsd", not(target_vendor = "rumprun")),
195 target_os = "openbsd",
196 target_os = "solaris"))]
197 #[cfg_attr(test, allow(dead_code))]
201 use libc::{PROT_NONE, MAP_PRIVATE, MAP_ANON, MAP_FAILED, MAP_FIXED};
204 #[cfg(any(target_os = "macos",
205 target_os = "bitrig",
206 target_os = "openbsd",
207 target_os = "solaris"))]
208 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
209 current().map(|s| s as *mut libc::c_void)
212 #[cfg(any(target_os = "android", target_os = "freebsd",
213 target_os = "linux", target_os = "netbsd"))]
214 unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
216 let mut attr: libc::pthread_attr_t = ::mem::zeroed();
217 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
218 #[cfg(target_os = "freebsd")]
219 let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
220 #[cfg(not(target_os = "freebsd"))]
221 let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
223 let mut stackaddr = ::ptr::null_mut();
224 let mut stacksize = 0;
225 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
227 ret = Some(stackaddr);
229 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
233 pub unsafe fn init() -> Option<usize> {
234 let psize = os::page_size();
235 let mut stackaddr = match get_stack_start() {
240 // Ensure stackaddr is page aligned! A parent process might
241 // have reset RLIMIT_STACK to be non-page aligned. The
242 // pthread_attr_getstack() reports the usable stack area
243 // stackaddr < stackaddr + stacksize, so if stackaddr is not
244 // page-aligned, calculate the fix such that stackaddr <
245 // new_page_aligned_stackaddr < stackaddr + stacksize
246 let remainder = (stackaddr as usize) % psize;
248 stackaddr = ((stackaddr as usize) + psize - remainder)
249 as *mut libc::c_void;
252 // Rellocate the last page of the stack.
253 // This ensures SIGBUS will be raised on
255 let result = mmap(stackaddr,
256 psize as libc::size_t,
258 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
262 if result != stackaddr || result == MAP_FAILED {
263 panic!("failed to allocate a guard page");
266 let offset = if cfg!(any(target_os = "linux", target_os = "freebsd")) {
272 Some(stackaddr as usize + offset * psize)
275 #[cfg(target_os = "solaris")]
276 pub unsafe fn current() -> Option<usize> {
277 let mut current_stack: libc::stack_t = ::mem::zeroed();
278 assert_eq!(libc::stack_getbounds(&mut current_stack), 0);
279 Some(current_stack.ss_sp as usize)
282 #[cfg(target_os = "macos")]
283 pub unsafe fn current() -> Option<usize> {
284 Some((libc::pthread_get_stackaddr_np(libc::pthread_self()) as libc::size_t -
285 libc::pthread_get_stacksize_np(libc::pthread_self())) as usize)
288 #[cfg(any(target_os = "openbsd", target_os = "bitrig"))]
289 pub unsafe fn current() -> Option<usize> {
290 let mut current_stack: libc::stack_t = ::mem::zeroed();
291 assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(),
292 &mut current_stack), 0);
294 let extra = if cfg!(target_os = "bitrig") {3} else {1} * os::page_size();
295 Some(if libc::pthread_main_np() == 1 {
297 current_stack.ss_sp as usize - current_stack.ss_size as usize + extra
300 current_stack.ss_sp as usize - current_stack.ss_size as usize
304 #[cfg(any(target_os = "android", target_os = "freebsd",
305 target_os = "linux", target_os = "netbsd"))]
306 pub unsafe fn current() -> Option<usize> {
308 let mut attr: libc::pthread_attr_t = ::mem::zeroed();
309 assert_eq!(libc::pthread_attr_init(&mut attr), 0);
310 #[cfg(target_os = "freebsd")]
311 let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
312 #[cfg(not(target_os = "freebsd"))]
313 let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
315 let mut guardsize = 0;
316 assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
318 panic!("there is no guard page");
320 let mut stackaddr = ::ptr::null_mut();
322 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
325 ret = if cfg!(target_os = "freebsd") {
326 Some(stackaddr as usize - guardsize as usize)
327 } else if cfg!(target_os = "netbsd") {
328 Some(stackaddr as usize)
330 Some(stackaddr as usize + guardsize as usize)
333 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
338 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
339 // PTHREAD_STACK_MIN plus however many bytes are needed for thread-local
340 // storage. We need that information to avoid blowing up when a small stack
341 // is created in an application with big thread-local storage requirements.
342 // See #6233 for rationale and details.
343 #[cfg(target_os = "linux")]
345 fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
346 weak!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);
348 match __pthread_get_minstack.get() {
349 None => libc::PTHREAD_STACK_MIN as usize,
350 Some(f) => unsafe { f(attr) as usize },
354 // No point in looking up __pthread_get_minstack() on non-glibc
356 #[cfg(all(not(target_os = "linux"),
357 not(target_os = "netbsd")))]
358 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
359 libc::PTHREAD_STACK_MIN as usize
362 #[cfg(target_os = "netbsd")]
363 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {