]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/thread.rs
Rollup merge of #35877 - KiChjang:issue-35869, r=arielb1
[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     pub fn sleep(dur: Duration) {
124         let mut secs = dur.as_secs();
125         let mut nsecs = dur.subsec_nanos() as libc::c_long;
126
127         // If we're awoken with a signal then the return value will be -1 and
128         // nanosleep will fill in `ts` with the remaining time.
129         unsafe {
130             while secs > 0 || nsecs > 0 {
131                 let mut ts = libc::timespec {
132                     tv_sec: cmp::min(libc::time_t::max_value() as u64, secs) as libc::time_t,
133                     tv_nsec: nsecs,
134                 };
135                 secs -= ts.tv_sec as u64;
136                 if libc::nanosleep(&ts, &mut ts) == -1 {
137                     assert_eq!(os::errno(), libc::EINTR);
138                     secs += ts.tv_sec as u64;
139                     nsecs = ts.tv_nsec;
140                 } else {
141                     nsecs = 0;
142                 }
143             }
144         }
145     }
146
147     pub fn join(self) {
148         unsafe {
149             let ret = libc::pthread_join(self.id, ptr::null_mut());
150             mem::forget(self);
151             debug_assert_eq!(ret, 0);
152         }
153     }
154
155     pub fn id(&self) -> libc::pthread_t { self.id }
156
157     pub fn into_id(self) -> libc::pthread_t {
158         let id = self.id;
159         mem::forget(self);
160         id
161     }
162 }
163
164 impl Drop for Thread {
165     fn drop(&mut self) {
166         let ret = unsafe { libc::pthread_detach(self.id) };
167         debug_assert_eq!(ret, 0);
168     }
169 }
170
171 #[cfg(all(not(all(target_os = "linux", not(target_env = "musl"))),
172           not(target_os = "freebsd"),
173           not(target_os = "macos"),
174           not(target_os = "bitrig"),
175           not(all(target_os = "netbsd", not(target_vendor = "rumprun"))),
176           not(target_os = "openbsd"),
177           not(target_os = "solaris")))]
178 #[cfg_attr(test, allow(dead_code))]
179 pub mod guard {
180     pub unsafe fn current() -> Option<usize> { None }
181     pub unsafe fn init() -> Option<usize> { None }
182 }
183
184
185 #[cfg(any(all(target_os = "linux", not(target_env = "musl")),
186           target_os = "freebsd",
187           target_os = "macos",
188           target_os = "bitrig",
189           all(target_os = "netbsd", not(target_vendor = "rumprun")),
190           target_os = "openbsd",
191           target_os = "solaris"))]
192 #[cfg_attr(test, allow(dead_code))]
193 pub mod guard {
194     use libc;
195     use libc::mmap;
196     use libc::{PROT_NONE, MAP_PRIVATE, MAP_ANON, MAP_FAILED, MAP_FIXED};
197     use sys::os;
198
199     #[cfg(any(target_os = "macos",
200               target_os = "bitrig",
201               target_os = "openbsd",
202               target_os = "solaris"))]
203     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
204         current().map(|s| s as *mut libc::c_void)
205     }
206
207     #[cfg(any(target_os = "android", target_os = "freebsd",
208               target_os = "linux", target_os = "netbsd"))]
209     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
210         let mut ret = None;
211         let mut attr: libc::pthread_attr_t = ::mem::zeroed();
212         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
213         #[cfg(target_os = "freebsd")]
214             let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
215         #[cfg(not(target_os = "freebsd"))]
216             let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
217         if e == 0 {
218             let mut stackaddr = ::ptr::null_mut();
219             let mut stacksize = 0;
220             assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
221                                                    &mut stacksize), 0);
222             ret = Some(stackaddr);
223         }
224         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
225         ret
226     }
227
228     pub unsafe fn init() -> Option<usize> {
229         let psize = os::page_size();
230         let mut stackaddr = match get_stack_start() {
231             Some(addr) => addr,
232             None => return None,
233         };
234
235         // Ensure stackaddr is page aligned! A parent process might
236         // have reset RLIMIT_STACK to be non-page aligned. The
237         // pthread_attr_getstack() reports the usable stack area
238         // stackaddr < stackaddr + stacksize, so if stackaddr is not
239         // page-aligned, calculate the fix such that stackaddr <
240         // new_page_aligned_stackaddr < stackaddr + stacksize
241         let remainder = (stackaddr as usize) % psize;
242         if remainder != 0 {
243             stackaddr = ((stackaddr as usize) + psize - remainder)
244                 as *mut libc::c_void;
245         }
246
247         // Rellocate the last page of the stack.
248         // This ensures SIGBUS will be raised on
249         // stack overflow.
250         let result = mmap(stackaddr,
251                           psize as libc::size_t,
252                           PROT_NONE,
253                           MAP_PRIVATE | MAP_ANON | MAP_FIXED,
254                           -1,
255                           0);
256
257         if result != stackaddr || result == MAP_FAILED {
258             panic!("failed to allocate a guard page");
259         }
260
261         let offset = if cfg!(any(target_os = "linux", target_os = "freebsd")) {
262             2
263         } else {
264             1
265         };
266
267         Some(stackaddr as usize + offset * psize)
268     }
269
270     #[cfg(target_os = "solaris")]
271     pub unsafe fn current() -> Option<usize> {
272         let mut current_stack: libc::stack_t = ::mem::zeroed();
273         assert_eq!(libc::stack_getbounds(&mut current_stack), 0);
274         Some(current_stack.ss_sp as usize)
275     }
276
277     #[cfg(target_os = "macos")]
278     pub unsafe fn current() -> Option<usize> {
279         Some((libc::pthread_get_stackaddr_np(libc::pthread_self()) as libc::size_t -
280               libc::pthread_get_stacksize_np(libc::pthread_self())) as usize)
281     }
282
283     #[cfg(any(target_os = "openbsd", target_os = "bitrig"))]
284     pub unsafe fn current() -> Option<usize> {
285         let mut current_stack: libc::stack_t = ::mem::zeroed();
286         assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(),
287                                              &mut current_stack), 0);
288
289         let extra = if cfg!(target_os = "bitrig") {3} else {1} * os::page_size();
290         Some(if libc::pthread_main_np() == 1 {
291             // main thread
292             current_stack.ss_sp as usize - current_stack.ss_size as usize + extra
293         } else {
294             // new thread
295             current_stack.ss_sp as usize - current_stack.ss_size as usize
296         })
297     }
298
299     #[cfg(any(target_os = "android", target_os = "freebsd",
300               target_os = "linux", target_os = "netbsd"))]
301     pub unsafe fn current() -> Option<usize> {
302         let mut ret = None;
303         let mut attr: libc::pthread_attr_t = ::mem::zeroed();
304         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
305         #[cfg(target_os = "freebsd")]
306             let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
307         #[cfg(not(target_os = "freebsd"))]
308             let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
309         if e == 0 {
310             let mut guardsize = 0;
311             assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
312             if guardsize == 0 {
313                 panic!("there is no guard page");
314             }
315             let mut stackaddr = ::ptr::null_mut();
316             let mut size = 0;
317             assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
318                                                    &mut size), 0);
319
320             ret = if cfg!(target_os = "freebsd") {
321                 Some(stackaddr as usize - guardsize as usize)
322             } else if cfg!(target_os = "netbsd") {
323                 Some(stackaddr as usize)
324             } else {
325                 Some(stackaddr as usize + guardsize as usize)
326             };
327         }
328         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
329         ret
330     }
331 }
332
333 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
334 // PTHREAD_STACK_MIN plus however many bytes are needed for thread-local
335 // storage.  We need that information to avoid blowing up when a small stack
336 // is created in an application with big thread-local storage requirements.
337 // See #6233 for rationale and details.
338 #[cfg(target_os = "linux")]
339 #[allow(deprecated)]
340 fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
341     weak!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);
342
343     match __pthread_get_minstack.get() {
344         None => libc::PTHREAD_STACK_MIN as usize,
345         Some(f) => unsafe { f(attr) as usize },
346     }
347 }
348
349 // No point in looking up __pthread_get_minstack() on non-glibc
350 // platforms.
351 #[cfg(all(not(target_os = "linux"),
352           not(target_os = "netbsd")))]
353 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
354     libc::PTHREAD_STACK_MIN as usize
355 }
356
357 #[cfg(target_os = "netbsd")]
358 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
359     2048 // just a guess
360 }