]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/thread.rs
Rollup merge of #56914 - glaubitz:ignore-tests, r=alexcrichton
[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 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 #[cfg(not(target_os = "l4re"))]
24 pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
25 #[cfg(target_os = "l4re")]
26 pub const DEFAULT_MIN_STACK_SIZE: usize = 1024 * 1024;
27
28 pub struct Thread {
29     id: libc::pthread_t,
30 }
31
32 // Some platforms may have pthread_t as a pointer in which case we still want
33 // a thread to be Send/Sync
34 unsafe impl Send for Thread {}
35 unsafe impl Sync for Thread {}
36
37 // The pthread_attr_setstacksize symbol doesn't exist in the emscripten libc,
38 // so we have to not link to it to satisfy emcc's ERROR_ON_UNDEFINED_SYMBOLS.
39 #[cfg(not(target_os = "emscripten"))]
40 unsafe fn pthread_attr_setstacksize(attr: *mut libc::pthread_attr_t,
41                                     stack_size: libc::size_t) -> libc::c_int {
42     libc::pthread_attr_setstacksize(attr, stack_size)
43 }
44
45 #[cfg(target_os = "emscripten")]
46 unsafe fn pthread_attr_setstacksize(_attr: *mut libc::pthread_attr_t,
47                                     _stack_size: libc::size_t) -> libc::c_int {
48     panic!()
49 }
50
51 impl Thread {
52     // unsafe: see thread::Builder::spawn_unchecked for safety requirements
53     pub unsafe fn new(stack: usize, p: Box<dyn FnBox()>)
54                           -> io::Result<Thread> {
55         let p = box p;
56         let mut native: libc::pthread_t = mem::zeroed();
57         let mut attr: libc::pthread_attr_t = mem::zeroed();
58         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
59
60         let stack_size = cmp::max(stack, min_stack_size(&attr));
61
62         match pthread_attr_setstacksize(&mut attr,
63                                         stack_size) {
64             0 => {}
65             n => {
66                 assert_eq!(n, libc::EINVAL);
67                 // EINVAL means |stack_size| is either too small or not a
68                 // multiple of the system page size.  Because it's definitely
69                 // >= PTHREAD_STACK_MIN, it must be an alignment issue.
70                 // Round up to the nearest page and try again.
71                 let page_size = os::page_size();
72                 let stack_size = (stack_size + page_size - 1) &
73                                  (-(page_size as isize - 1) as usize - 1);
74                 assert_eq!(libc::pthread_attr_setstacksize(&mut attr,
75                                                            stack_size), 0);
76             }
77         };
78
79         let ret = libc::pthread_create(&mut native, &attr, thread_start,
80                                        &*p as *const _ as *mut _);
81         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
82
83         return if ret != 0 {
84             Err(io::Error::from_raw_os_error(ret))
85         } else {
86             mem::forget(p); // ownership passed to pthread_create
87             Ok(Thread { id: native })
88         };
89
90         extern fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
91             unsafe { start_thread(main as *mut u8); }
92             ptr::null_mut()
93         }
94     }
95
96     pub fn yield_now() {
97         let ret = unsafe { libc::sched_yield() };
98         debug_assert_eq!(ret, 0);
99     }
100
101     #[cfg(any(target_os = "linux",
102               target_os = "android"))]
103     pub fn set_name(name: &CStr) {
104         const PR_SET_NAME: libc::c_int = 15;
105         // pthread wrapper only appeared in glibc 2.12, so we use syscall
106         // directly.
107         unsafe {
108             libc::prctl(PR_SET_NAME, name.as_ptr() as libc::c_ulong, 0, 0, 0);
109         }
110     }
111
112     #[cfg(any(target_os = "freebsd",
113               target_os = "dragonfly",
114               target_os = "bitrig",
115               target_os = "openbsd"))]
116     pub fn set_name(name: &CStr) {
117         unsafe {
118             libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
119         }
120     }
121
122     #[cfg(any(target_os = "macos", target_os = "ios"))]
123     pub fn set_name(name: &CStr) {
124         unsafe {
125             libc::pthread_setname_np(name.as_ptr());
126         }
127     }
128
129     #[cfg(target_os = "netbsd")]
130     pub fn set_name(name: &CStr) {
131         use ffi::CString;
132         let cname = CString::new(&b"%s"[..]).unwrap();
133         unsafe {
134             libc::pthread_setname_np(libc::pthread_self(), cname.as_ptr(),
135                                      name.as_ptr() as *mut libc::c_void);
136         }
137     }
138     #[cfg(any(target_env = "newlib",
139               target_os = "solaris",
140               target_os = "haiku",
141               target_os = "l4re",
142               target_os = "emscripten",
143               target_os = "hermit"))]
144     pub fn set_name(_name: &CStr) {
145         // Newlib, Illumos, Haiku, and Emscripten have no way to set a thread name.
146     }
147     #[cfg(target_os = "fuchsia")]
148     pub fn set_name(_name: &CStr) {
149         // FIXME: determine whether Fuchsia has a way to set a thread name.
150     }
151
152     pub fn sleep(dur: Duration) {
153         let mut secs = dur.as_secs();
154         let mut nsecs = dur.subsec_nanos() as _;
155
156         // If we're awoken with a signal then the return value will be -1 and
157         // nanosleep will fill in `ts` with the remaining time.
158         unsafe {
159             while secs > 0 || nsecs > 0 {
160                 let mut ts = libc::timespec {
161                     tv_sec: cmp::min(libc::time_t::max_value() as u64, secs) as libc::time_t,
162                     tv_nsec: nsecs,
163                 };
164                 secs -= ts.tv_sec as u64;
165                 if libc::nanosleep(&ts, &mut ts) == -1 {
166                     assert_eq!(os::errno(), libc::EINTR);
167                     secs += ts.tv_sec as u64;
168                     nsecs = ts.tv_nsec;
169                 } else {
170                     nsecs = 0;
171                 }
172             }
173         }
174     }
175
176     pub fn join(self) {
177         unsafe {
178             let ret = libc::pthread_join(self.id, ptr::null_mut());
179             mem::forget(self);
180             assert!(ret == 0,
181                     "failed to join thread: {}", io::Error::from_raw_os_error(ret));
182         }
183     }
184
185     pub fn id(&self) -> libc::pthread_t { self.id }
186
187     pub fn into_id(self) -> libc::pthread_t {
188         let id = self.id;
189         mem::forget(self);
190         id
191     }
192 }
193
194 impl Drop for Thread {
195     fn drop(&mut self) {
196         let ret = unsafe { libc::pthread_detach(self.id) };
197         debug_assert_eq!(ret, 0);
198     }
199 }
200
201 #[cfg(all(not(all(target_os = "linux", not(target_env = "musl"))),
202           not(target_os = "freebsd"),
203           not(target_os = "macos"),
204           not(target_os = "bitrig"),
205           not(all(target_os = "netbsd", not(target_vendor = "rumprun"))),
206           not(target_os = "openbsd"),
207           not(target_os = "solaris")))]
208 #[cfg_attr(test, allow(dead_code))]
209 pub mod guard {
210     use ops::Range;
211     pub type Guard = Range<usize>;
212     pub unsafe fn current() -> Option<Guard> { None }
213     pub unsafe fn init() -> Option<Guard> { None }
214 }
215
216
217 #[cfg(any(all(target_os = "linux", not(target_env = "musl")),
218           target_os = "freebsd",
219           target_os = "macos",
220           target_os = "bitrig",
221           all(target_os = "netbsd", not(target_vendor = "rumprun")),
222           target_os = "openbsd",
223           target_os = "solaris"))]
224 #[cfg_attr(test, allow(dead_code))]
225 pub mod guard {
226     use libc;
227     use libc::{mmap, mprotect};
228     use libc::{PROT_NONE, PROT_READ, PROT_WRITE, MAP_PRIVATE, MAP_ANON, MAP_FAILED, MAP_FIXED};
229     use ops::Range;
230     use sys::os;
231
232     // This is initialized in init() and only read from after
233     static mut PAGE_SIZE: usize = 0;
234
235     pub type Guard = Range<usize>;
236
237     #[cfg(target_os = "solaris")]
238     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
239         let mut current_stack: libc::stack_t = ::mem::zeroed();
240         assert_eq!(libc::stack_getbounds(&mut current_stack), 0);
241         Some(current_stack.ss_sp)
242     }
243
244     #[cfg(target_os = "macos")]
245     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
246         let stackaddr = libc::pthread_get_stackaddr_np(libc::pthread_self()) as usize -
247              libc::pthread_get_stacksize_np(libc::pthread_self());
248         Some(stackaddr as *mut libc::c_void)
249     }
250
251     #[cfg(any(target_os = "openbsd", target_os = "bitrig"))]
252     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
253         let mut current_stack: libc::stack_t = ::mem::zeroed();
254         assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(),
255                                              &mut current_stack), 0);
256
257         let extra = if cfg!(target_os = "bitrig") {3} else {1} * PAGE_SIZE;
258         let stackaddr = if libc::pthread_main_np() == 1 {
259             // main thread
260             current_stack.ss_sp as usize - current_stack.ss_size + extra
261         } else {
262             // new thread
263             current_stack.ss_sp as usize - current_stack.ss_size
264         };
265         Some(stackaddr as *mut libc::c_void)
266     }
267
268     #[cfg(any(target_os = "android", target_os = "freebsd",
269               target_os = "linux", target_os = "netbsd", target_os = "l4re"))]
270     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
271         let mut ret = None;
272         let mut attr: libc::pthread_attr_t = ::mem::zeroed();
273         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
274         #[cfg(target_os = "freebsd")]
275             let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
276         #[cfg(not(target_os = "freebsd"))]
277             let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
278         if e == 0 {
279             let mut stackaddr = ::ptr::null_mut();
280             let mut stacksize = 0;
281             assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
282                                                    &mut stacksize), 0);
283             ret = Some(stackaddr);
284         }
285         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
286         ret
287     }
288
289     // Precondition: PAGE_SIZE is initialized.
290     unsafe fn get_stack_start_aligned() -> Option<*mut libc::c_void> {
291         assert!(PAGE_SIZE != 0);
292         let stackaddr = get_stack_start()?;
293
294         // Ensure stackaddr is page aligned! A parent process might
295         // have reset RLIMIT_STACK to be non-page aligned. The
296         // pthread_attr_getstack() reports the usable stack area
297         // stackaddr < stackaddr + stacksize, so if stackaddr is not
298         // page-aligned, calculate the fix such that stackaddr <
299         // new_page_aligned_stackaddr < stackaddr + stacksize
300         let remainder = (stackaddr as usize) % PAGE_SIZE;
301         Some(if remainder == 0 {
302             stackaddr
303         } else {
304             ((stackaddr as usize) + PAGE_SIZE - remainder) as *mut libc::c_void
305         })
306     }
307
308     pub unsafe fn init() -> Option<Guard> {
309         PAGE_SIZE = os::page_size();
310
311         let stackaddr = get_stack_start_aligned()?;
312
313         if cfg!(target_os = "linux") {
314             // Linux doesn't allocate the whole stack right away, and
315             // the kernel has its own stack-guard mechanism to fault
316             // when growing too close to an existing mapping.  If we map
317             // our own guard, then the kernel starts enforcing a rather
318             // large gap above that, rendering much of the possible
319             // stack space useless.  See #43052.
320             //
321             // Instead, we'll just note where we expect rlimit to start
322             // faulting, so our handler can report "stack overflow", and
323             // trust that the kernel's own stack guard will work.
324             let stackaddr = stackaddr as usize;
325             Some(stackaddr - PAGE_SIZE..stackaddr)
326         } else {
327             // Reallocate the last page of the stack.
328             // This ensures SIGBUS will be raised on
329             // stack overflow.
330             // Systems which enforce strict PAX MPROTECT do not allow
331             // to mprotect() a mapping with less restrictive permissions
332             // than the initial mmap() used, so we mmap() here with
333             // read/write permissions and only then mprotect() it to
334             // no permissions at all. See issue #50313.
335             let result = mmap(stackaddr, PAGE_SIZE, PROT_READ | PROT_WRITE,
336                               MAP_PRIVATE | MAP_ANON | MAP_FIXED, -1, 0);
337             if result != stackaddr || result == MAP_FAILED {
338                 panic!("failed to allocate a guard page");
339             }
340
341             let result = mprotect(stackaddr, PAGE_SIZE, PROT_NONE);
342             if result != 0 {
343                 panic!("failed to protect the guard page");
344             }
345
346             let guardaddr = stackaddr as usize;
347             let offset = if cfg!(target_os = "freebsd") {
348                 2
349             } else {
350                 1
351             };
352
353             Some(guardaddr..guardaddr + offset * PAGE_SIZE)
354         }
355     }
356
357     #[cfg(any(target_os = "macos",
358               target_os = "bitrig",
359               target_os = "openbsd",
360               target_os = "solaris"))]
361     pub unsafe fn current() -> Option<Guard> {
362         let stackaddr = get_stack_start()? as usize;
363         Some(stackaddr - PAGE_SIZE..stackaddr)
364     }
365
366     #[cfg(any(target_os = "android", target_os = "freebsd",
367               target_os = "linux", target_os = "netbsd", target_os = "l4re"))]
368     pub unsafe fn current() -> Option<Guard> {
369         let mut ret = None;
370         let mut attr: libc::pthread_attr_t = ::mem::zeroed();
371         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
372         #[cfg(target_os = "freebsd")]
373             let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
374         #[cfg(not(target_os = "freebsd"))]
375             let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
376         if e == 0 {
377             let mut guardsize = 0;
378             assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
379             if guardsize == 0 {
380                 panic!("there is no guard page");
381             }
382             let mut stackaddr = ::ptr::null_mut();
383             let mut size = 0;
384             assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
385                                                    &mut size), 0);
386
387             let stackaddr = stackaddr as usize;
388             ret = if cfg!(target_os = "freebsd") {
389                 // FIXME does freebsd really fault *below* the guard addr?
390                 let guardaddr = stackaddr - guardsize;
391                 Some(guardaddr - PAGE_SIZE..guardaddr)
392             } else if cfg!(target_os = "netbsd") {
393                 Some(stackaddr - guardsize..stackaddr)
394             } else if cfg!(all(target_os = "linux", target_env = "gnu")) {
395                 // glibc used to include the guard area within the stack, as noted in the BUGS
396                 // section of `man pthread_attr_getguardsize`.  This has been corrected starting
397                 // with glibc 2.27, and in some distro backports, so the guard is now placed at the
398                 // end (below) the stack.  There's no easy way for us to know which we have at
399                 // runtime, so we'll just match any fault in the range right above or below the
400                 // stack base to call that fault a stack overflow.
401                 Some(stackaddr - guardsize..stackaddr + guardsize)
402             } else {
403                 Some(stackaddr..stackaddr + guardsize)
404             };
405         }
406         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
407         ret
408     }
409 }
410
411 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
412 // PTHREAD_STACK_MIN plus however many bytes are needed for thread-local
413 // storage.  We need that information to avoid blowing up when a small stack
414 // is created in an application with big thread-local storage requirements.
415 // See #6233 for rationale and details.
416 #[cfg(target_os = "linux")]
417 #[allow(deprecated)]
418 fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
419     weak!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);
420
421     match __pthread_get_minstack.get() {
422         None => libc::PTHREAD_STACK_MIN,
423         Some(f) => unsafe { f(attr) },
424     }
425 }
426
427 // No point in looking up __pthread_get_minstack() on non-glibc
428 // platforms.
429 #[cfg(all(not(target_os = "linux"),
430           not(target_os = "netbsd")))]
431 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
432     libc::PTHREAD_STACK_MIN
433 }
434
435 #[cfg(target_os = "netbsd")]
436 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
437     2048 // just a guess
438 }