]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/thread.rs
Add support for the Haiku operating system on x86 and x86_64 machines
[rust.git] / src / libstd / sys / unix / thread.rs
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.
4 //
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.
10
11 use alloc::boxed::FnBox;
12 use cmp;
13 use ffi::CStr;
14 use io;
15 use libc;
16 use mem;
17 use ptr;
18 use sys::os;
19 use time::Duration;
20
21 use sys_common::thread::*;
22
23 pub struct Thread {
24     id: libc::pthread_t,
25 }
26
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 {}
31
32 impl Thread {
33     pub unsafe fn new<'a>(stack: usize, p: Box<FnBox() + 'a>)
34                           -> io::Result<Thread> {
35         let p = box p;
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);
39
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) {
43             0 => {}
44             n => {
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,
55                                                            stack_size), 0);
56             }
57         };
58
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);
62
63         return if ret != 0 {
64             Err(io::Error::from_raw_os_error(ret))
65         } else {
66             mem::forget(p); // ownership passed to pthread_create
67             Ok(Thread { id: native })
68         };
69
70         extern fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
71             unsafe { start_thread(main); }
72             ptr::null_mut()
73         }
74     }
75
76     pub fn yield_now() {
77         let ret = unsafe { libc::sched_yield() };
78         debug_assert_eq!(ret, 0);
79     }
80
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
86         // directly.
87         unsafe {
88             libc::prctl(PR_SET_NAME, name.as_ptr() as libc::c_ulong, 0, 0, 0);
89         }
90     }
91
92     #[cfg(any(target_os = "freebsd",
93               target_os = "dragonfly",
94               target_os = "bitrig",
95               target_os = "openbsd"))]
96     pub fn set_name(name: &CStr) {
97         unsafe {
98             libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
99         }
100     }
101
102     #[cfg(any(target_os = "macos", target_os = "ios"))]
103     pub fn set_name(name: &CStr) {
104         unsafe {
105             libc::pthread_setname_np(name.as_ptr());
106         }
107     }
108
109     #[cfg(target_os = "netbsd")]
110     pub fn set_name(name: &CStr) {
111         use ffi::CString;
112         let cname = CString::new(&b"%s"[..]).unwrap();
113         unsafe {
114             libc::pthread_setname_np(libc::pthread_self(), cname.as_ptr(),
115                                      name.as_ptr() as *mut libc::c_void);
116         }
117     }
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.
121     }
122
123     #[cfg(target_os = "haiku")]
124     pub fn set_name(_name: &CStr) {
125         // Haiku has no way to set a thread name.
126     }
127
128     pub fn sleep(dur: Duration) {
129         let mut secs = dur.as_secs();
130         let mut nsecs = dur.subsec_nanos() as libc::c_long;
131
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.
134         unsafe {
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,
138                     tv_nsec: nsecs,
139                 };
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;
144                     nsecs = ts.tv_nsec;
145                 } else {
146                     nsecs = 0;
147                 }
148             }
149         }
150     }
151
152     pub fn join(self) {
153         unsafe {
154             let ret = libc::pthread_join(self.id, ptr::null_mut());
155             mem::forget(self);
156             debug_assert_eq!(ret, 0);
157         }
158     }
159
160     pub fn id(&self) -> libc::pthread_t { self.id }
161
162     pub fn into_id(self) -> libc::pthread_t {
163         let id = self.id;
164         mem::forget(self);
165         id
166     }
167 }
168
169 impl Drop for Thread {
170     fn drop(&mut self) {
171         let ret = unsafe { libc::pthread_detach(self.id) };
172         debug_assert_eq!(ret, 0);
173     }
174 }
175
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))]
184 pub mod guard {
185     pub unsafe fn current() -> Option<usize> { None }
186     pub unsafe fn init() -> Option<usize> { None }
187 }
188
189
190 #[cfg(any(all(target_os = "linux", not(target_env = "musl")),
191           target_os = "freebsd",
192           target_os = "macos",
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))]
198 pub mod guard {
199     use libc;
200     use libc::mmap;
201     use libc::{PROT_NONE, MAP_PRIVATE, MAP_ANON, MAP_FAILED, MAP_FIXED};
202     use sys::os;
203
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)
210     }
211
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> {
215         let mut ret = None;
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);
222         if e == 0 {
223             let mut stackaddr = ::ptr::null_mut();
224             let mut stacksize = 0;
225             assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
226                                                    &mut stacksize), 0);
227             ret = Some(stackaddr);
228         }
229         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
230         ret
231     }
232
233     pub unsafe fn init() -> Option<usize> {
234         let psize = os::page_size();
235         let mut stackaddr = match get_stack_start() {
236             Some(addr) => addr,
237             None => return None,
238         };
239
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;
247         if remainder != 0 {
248             stackaddr = ((stackaddr as usize) + psize - remainder)
249                 as *mut libc::c_void;
250         }
251
252         // Rellocate the last page of the stack.
253         // This ensures SIGBUS will be raised on
254         // stack overflow.
255         let result = mmap(stackaddr,
256                           psize as libc::size_t,
257                           PROT_NONE,
258                           MAP_PRIVATE | MAP_ANON | MAP_FIXED,
259                           -1,
260                           0);
261
262         if result != stackaddr || result == MAP_FAILED {
263             panic!("failed to allocate a guard page");
264         }
265
266         let offset = if cfg!(any(target_os = "linux", target_os = "freebsd")) {
267             2
268         } else {
269             1
270         };
271
272         Some(stackaddr as usize + offset * psize)
273     }
274
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)
280     }
281
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)
286     }
287
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);
293
294         let extra = if cfg!(target_os = "bitrig") {3} else {1} * os::page_size();
295         Some(if libc::pthread_main_np() == 1 {
296             // main thread
297             current_stack.ss_sp as usize - current_stack.ss_size as usize + extra
298         } else {
299             // new thread
300             current_stack.ss_sp as usize - current_stack.ss_size as usize
301         })
302     }
303
304     #[cfg(any(target_os = "android", target_os = "freebsd",
305               target_os = "linux", target_os = "netbsd"))]
306     pub unsafe fn current() -> Option<usize> {
307         let mut ret = None;
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);
314         if e == 0 {
315             let mut guardsize = 0;
316             assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
317             if guardsize == 0 {
318                 panic!("there is no guard page");
319             }
320             let mut stackaddr = ::ptr::null_mut();
321             let mut size = 0;
322             assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
323                                                    &mut size), 0);
324
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)
329             } else {
330                 Some(stackaddr as usize + guardsize as usize)
331             };
332         }
333         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
334         ret
335     }
336 }
337
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")]
344 #[allow(deprecated)]
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);
347
348     match __pthread_get_minstack.get() {
349         None => libc::PTHREAD_STACK_MIN as usize,
350         Some(f) => unsafe { f(attr) as usize },
351     }
352 }
353
354 // No point in looking up __pthread_get_minstack() on non-glibc
355 // platforms.
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
360 }
361
362 #[cfg(target_os = "netbsd")]
363 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
364     2048 // just a guess
365 }