]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/thread.rs
Add netbsd amd64 support
[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 #![allow(dead_code)]
12
13 use prelude::v1::*;
14
15 use alloc::boxed::FnBox;
16 use cmp;
17 use ffi::CString;
18 use io;
19 use libc::consts::os::posix01::PTHREAD_STACK_MIN;
20 use libc;
21 use mem;
22 use ptr;
23 use sys::os;
24 use time::Duration;
25
26 use sys_common::stack::RED_ZONE;
27 use sys_common::thread::*;
28
29 pub struct Thread {
30     id: libc::pthread_t,
31 }
32
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 {}
37
38 impl Thread {
39     pub unsafe fn new<'a>(stack: usize, p: Box<FnBox() + 'a>)
40                           -> io::Result<Thread> {
41         let p = box p;
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);
45
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) {
49             0 => {}
50             n => {
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);
61             }
62         };
63
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);
67
68         return if ret != 0 {
69             Err(io::Error::from_raw_os_error(ret))
70         } else {
71             mem::forget(p); // ownership passed to pthread_create
72             Ok(Thread { id: native })
73         };
74
75         #[no_stack_check]
76         extern fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
77             unsafe { start_thread(main); }
78             0 as *mut _
79         }
80     }
81
82     pub fn yield_now() {
83         let ret = unsafe { sched_yield() };
84         debug_assert_eq!(ret, 0);
85     }
86
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
90         // directly.
91         extern {
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;
95         }
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")
99         });
100         unsafe {
101             prctl(PR_SET_NAME, cname.as_ptr() as libc::c_ulong, 0, 0, 0);
102         }
103     }
104
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) {
111         extern {
112             fn pthread_set_name_np(tid: libc::pthread_t,
113                                    name: *const libc::c_char);
114         }
115         let cname = CString::new(name).unwrap();
116         unsafe {
117             pthread_set_name_np(pthread_self(), cname.as_ptr());
118         }
119     }
120
121     #[cfg(any(target_os = "macos", target_os = "ios"))]
122     pub fn set_name(name: &str) {
123         extern {
124             fn pthread_setname_np(name: *const libc::c_char) -> libc::c_int;
125         }
126         let cname = CString::new(name).unwrap();
127         unsafe {
128             pthread_setname_np(cname.as_ptr());
129         }
130     }
131
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,
136         };
137
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.
140         unsafe {
141             while libc::nanosleep(&ts, &mut ts) == -1 {
142                 assert_eq!(os::errno(), libc::EINTR);
143             }
144         }
145     }
146
147     pub fn join(self) {
148         unsafe {
149             let ret = pthread_join(self.id, ptr::null_mut());
150             mem::forget(self);
151             debug_assert_eq!(ret, 0);
152         }
153     }
154 }
155
156 impl Drop for Thread {
157     fn drop(&mut self) {
158         let ret = unsafe { pthread_detach(self.id) };
159         debug_assert_eq!(ret, 0);
160     }
161 }
162
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")))]
168 pub mod guard {
169     pub unsafe fn current() -> usize { 0 }
170     pub unsafe fn main() -> usize { 0 }
171     pub unsafe fn init() {}
172 }
173
174
175 #[cfg(any(target_os = "linux",
176           target_os = "macos",
177           target_os = "bitrig",
178           target_os = "netbsd",
179           target_os = "openbsd"))]
180 #[allow(unused_imports)]
181 pub mod guard {
182     use libc::{self, pthread_t};
183     use libc::funcs::posix88::mman::mmap;
184     use libc::consts::os::posix88::{PROT_NONE,
185                                     MAP_PRIVATE,
186                                     MAP_ANON,
187                                     MAP_FAILED,
188                                     MAP_FIXED};
189     use mem;
190     use ptr;
191     use super::{pthread_self, pthread_attr_destroy};
192     use sys::os;
193
194     // These are initialized in init() and only read from after
195     static mut GUARD_PAGE: usize = 0;
196
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
203     }
204
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);
213         stackaddr
214     }
215
216     pub unsafe fn init() {
217         let psize = os::page_size();
218         let mut stackaddr = get_stack_start();
219
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;
227         if remainder != 0 {
228             stackaddr = ((stackaddr as usize) + psize - remainder)
229                 as *mut libc::c_void;
230         }
231
232         // Rellocate the last page of the stack.
233         // This ensures SIGBUS will be raised on
234         // stack overflow.
235         let result = mmap(stackaddr,
236                           psize as libc::size_t,
237                           PROT_NONE,
238                           MAP_PRIVATE | MAP_ANON | MAP_FIXED,
239                           -1,
240                           0);
241
242         if result != stackaddr || result == MAP_FAILED {
243             panic!("failed to allocate a guard page");
244         }
245
246         let offset = if cfg!(target_os = "linux") {2} else {1};
247
248         GUARD_PAGE = stackaddr as usize + offset * psize;
249     }
250
251     pub unsafe fn main() -> usize {
252         GUARD_PAGE
253     }
254
255     #[cfg(target_os = "macos")]
256     pub unsafe fn current() -> usize {
257         extern {
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;
260         }
261         (pthread_get_stackaddr_np(pthread_self()) as libc::size_t -
262          pthread_get_stacksize_np(pthread_self())) as usize
263     }
264
265     #[cfg(any(target_os = "openbsd", target_os = "netbsd", target_os = "bitrig"))]
266     pub unsafe fn current() -> usize {
267         #[repr(C)]
268         struct stack_t {
269             ss_sp: *mut libc::c_void,
270             ss_size: libc::size_t,
271             ss_flags: libc::c_int,
272         }
273         extern {
274             fn pthread_main_np() -> libc::c_uint;
275             fn pthread_stackseg_np(thread: pthread_t,
276                                    sinfo: *mut stack_t) -> libc::c_uint;
277         }
278
279         let mut current_stack: stack_t = mem::zeroed();
280         assert_eq!(pthread_stackseg_np(pthread_self(), &mut current_stack), 0);
281
282         let extra = if cfg!(target_os = "bitrig") {3} else {1} * os::page_size();
283         if pthread_main_np() == 1 {
284             // main thread
285             current_stack.ss_sp as usize - current_stack.ss_size as usize + extra
286         } else {
287             // new thread
288             current_stack.ss_sp as usize - current_stack.ss_size as usize
289         }
290     }
291
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);
298         if guardsize == 0 {
299             panic!("there is no guard page");
300         }
301         let mut stackaddr = ptr::null_mut();
302         let mut size = 0;
303         assert_eq!(pthread_attr_getstack(&attr, &mut stackaddr, &mut size), 0);
304         assert_eq!(pthread_attr_destroy(&mut attr), 0);
305
306         stackaddr as usize + guardsize as usize
307     }
308
309     #[cfg(any(target_os = "linux", target_os = "android"))]
310     extern {
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;
318     }
319 }
320
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.
326 //
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;
337     use sync::Once;
338
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;
342
343     INIT.call_once(|| {
344         let lib = match DynamicLibrary::open(None) {
345             Ok(l) => l,
346             Err(..) => return,
347         };
348         unsafe {
349             if let Ok(f) = lib.symbol("__pthread_get_minstack") {
350                 __pthread_get_minstack = Some(mem::transmute::<*const (), F>(f));
351             }
352         }
353     });
354
355     match unsafe { __pthread_get_minstack } {
356         None => PTHREAD_STACK_MIN as usize,
357         Some(f) => unsafe { f(attr) as usize },
358     }
359 }
360
361 // No point in looking up __pthread_get_minstack() on non-glibc
362 // platforms.
363 #[cfg(not(target_os = "linux"))]
364 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
365     PTHREAD_STACK_MIN as usize
366 }
367
368 extern {
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;
384 }