]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/thread.rs
1e879117f73abf2e185c0d7b57a05ad38aaed1f3
[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 // 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)
38 }
39
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 {
43     panic!()
44 }
45
46 impl Thread {
47     pub unsafe fn new<'a>(stack: usize, p: Box<FnBox() + 'a>)
48                           -> io::Result<Thread> {
49         let p = box p;
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);
53
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) {
57             0 => {}
58             n => {
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,
69                                                            stack_size), 0);
70             }
71         };
72
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);
76
77         return if ret != 0 {
78             Err(io::Error::from_raw_os_error(ret))
79         } else {
80             mem::forget(p); // ownership passed to pthread_create
81             Ok(Thread { id: native })
82         };
83
84         extern fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
85             unsafe { start_thread(main); }
86             ptr::null_mut()
87         }
88     }
89
90     pub fn yield_now() {
91         let ret = unsafe { libc::sched_yield() };
92         debug_assert_eq!(ret, 0);
93     }
94
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
100         // directly.
101         unsafe {
102             libc::prctl(PR_SET_NAME, name.as_ptr() as libc::c_ulong, 0, 0, 0);
103         }
104     }
105
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) {
111         unsafe {
112             libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
113         }
114     }
115
116     #[cfg(any(target_os = "macos", target_os = "ios"))]
117     pub fn set_name(name: &CStr) {
118         unsafe {
119             libc::pthread_setname_np(name.as_ptr());
120         }
121     }
122
123     #[cfg(target_os = "netbsd")]
124     pub fn set_name(name: &CStr) {
125         use ffi::CString;
126         let cname = CString::new(&b"%s"[..]).unwrap();
127         unsafe {
128             libc::pthread_setname_np(libc::pthread_self(), cname.as_ptr(),
129                                      name.as_ptr() as *mut libc::c_void);
130         }
131     }
132     #[cfg(any(target_env = "newlib",
133               target_os = "solaris",
134               target_os = "haiku",
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.
138     }
139
140     pub fn sleep(dur: Duration) {
141         let mut secs = dur.as_secs();
142         let mut nsecs = dur.subsec_nanos() as libc::c_long;
143
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.
146         unsafe {
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,
150                     tv_nsec: nsecs,
151                 };
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;
156                     nsecs = ts.tv_nsec;
157                 } else {
158                     nsecs = 0;
159                 }
160             }
161         }
162     }
163
164     pub fn join(self) {
165         unsafe {
166             let ret = libc::pthread_join(self.id, ptr::null_mut());
167             mem::forget(self);
168             debug_assert_eq!(ret, 0);
169         }
170     }
171
172     pub fn id(&self) -> libc::pthread_t { self.id }
173
174     pub fn into_id(self) -> libc::pthread_t {
175         let id = self.id;
176         mem::forget(self);
177         id
178     }
179 }
180
181 impl Drop for Thread {
182     fn drop(&mut self) {
183         let ret = unsafe { libc::pthread_detach(self.id) };
184         debug_assert_eq!(ret, 0);
185     }
186 }
187
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))]
196 pub mod guard {
197     pub unsafe fn current() -> Option<usize> { None }
198     pub unsafe fn init() -> Option<usize> { None }
199 }
200
201
202 #[cfg(any(all(target_os = "linux", not(target_env = "musl")),
203           target_os = "freebsd",
204           target_os = "macos",
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))]
210 pub mod guard {
211     use libc;
212     use libc::mmap;
213     use libc::{PROT_NONE, MAP_PRIVATE, MAP_ANON, MAP_FAILED, MAP_FIXED};
214     use sys::os;
215
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)
222     }
223
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> {
227         let mut ret = None;
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);
234         if e == 0 {
235             let mut stackaddr = ::ptr::null_mut();
236             let mut stacksize = 0;
237             assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
238                                                    &mut stacksize), 0);
239             ret = Some(stackaddr);
240         }
241         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
242         ret
243     }
244
245     pub unsafe fn init() -> Option<usize> {
246         let psize = os::page_size();
247         let mut stackaddr = match get_stack_start() {
248             Some(addr) => addr,
249             None => return None,
250         };
251
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;
259         if remainder != 0 {
260             stackaddr = ((stackaddr as usize) + psize - remainder)
261                 as *mut libc::c_void;
262         }
263
264         // Rellocate the last page of the stack.
265         // This ensures SIGBUS will be raised on
266         // stack overflow.
267         let result = mmap(stackaddr,
268                           psize as libc::size_t,
269                           PROT_NONE,
270                           MAP_PRIVATE | MAP_ANON | MAP_FIXED,
271                           -1,
272                           0);
273
274         if result != stackaddr || result == MAP_FAILED {
275             panic!("failed to allocate a guard page");
276         }
277
278         let offset = if cfg!(any(target_os = "linux", target_os = "freebsd")) {
279             2
280         } else {
281             1
282         };
283
284         Some(stackaddr as usize + offset * psize)
285     }
286
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)
292     }
293
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)
298     }
299
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);
305
306         let extra = if cfg!(target_os = "bitrig") {3} else {1} * os::page_size();
307         Some(if libc::pthread_main_np() == 1 {
308             // main thread
309             current_stack.ss_sp as usize - current_stack.ss_size as usize + extra
310         } else {
311             // new thread
312             current_stack.ss_sp as usize - current_stack.ss_size as usize
313         })
314     }
315
316     #[cfg(any(target_os = "android", target_os = "freebsd",
317               target_os = "linux", target_os = "netbsd"))]
318     pub unsafe fn current() -> Option<usize> {
319         let mut ret = None;
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);
326         if e == 0 {
327             let mut guardsize = 0;
328             assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
329             if guardsize == 0 {
330                 panic!("there is no guard page");
331             }
332             let mut stackaddr = ::ptr::null_mut();
333             let mut size = 0;
334             assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
335                                                    &mut size), 0);
336
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)
341             } else {
342                 Some(stackaddr as usize + guardsize as usize)
343             };
344         }
345         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
346         ret
347     }
348 }
349
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")]
356 #[allow(deprecated)]
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);
359
360     match __pthread_get_minstack.get() {
361         None => libc::PTHREAD_STACK_MIN as usize,
362         Some(f) => unsafe { f(attr) as usize },
363     }
364 }
365
366 // No point in looking up __pthread_get_minstack() on non-glibc
367 // platforms.
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
372 }
373
374 #[cfg(target_os = "netbsd")]
375 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
376     2048 // just a guess
377 }