]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/thread.rs
f3a45d24657399dd33cdd564bc1b09c95f0c1dfc
[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     pub unsafe fn new<'a>(stack: usize, p: Box<dyn FnBox() + 'a>)
53                           -> io::Result<Thread> {
54         let p = box p;
55         let mut native: libc::pthread_t = mem::zeroed();
56         let mut attr: libc::pthread_attr_t = mem::zeroed();
57         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
58
59         let stack_size = cmp::max(stack, min_stack_size(&attr));
60
61         match pthread_attr_setstacksize(&mut attr,
62                                         stack_size) {
63             0 => {}
64             n => {
65                 assert_eq!(n, libc::EINVAL);
66                 // EINVAL means |stack_size| is either too small or not a
67                 // multiple of the system page size.  Because it's definitely
68                 // >= PTHREAD_STACK_MIN, it must be an alignment issue.
69                 // Round up to the nearest page and try again.
70                 let page_size = os::page_size();
71                 let stack_size = (stack_size + page_size - 1) &
72                                  (-(page_size as isize - 1) as usize - 1);
73                 assert_eq!(libc::pthread_attr_setstacksize(&mut attr,
74                                                            stack_size), 0);
75             }
76         };
77
78         let ret = libc::pthread_create(&mut native, &attr, thread_start,
79                                        &*p as *const _ as *mut _);
80         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
81
82         return if ret != 0 {
83             Err(io::Error::from_raw_os_error(ret))
84         } else {
85             mem::forget(p); // ownership passed to pthread_create
86             Ok(Thread { id: native })
87         };
88
89         extern fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
90             unsafe { start_thread(main as *mut u8); }
91             ptr::null_mut()
92         }
93     }
94
95     pub fn yield_now() {
96         let ret = unsafe { libc::sched_yield() };
97         debug_assert_eq!(ret, 0);
98     }
99
100     #[cfg(any(target_os = "linux",
101               target_os = "android"))]
102     pub fn set_name(name: &CStr) {
103         const PR_SET_NAME: libc::c_int = 15;
104         // pthread wrapper only appeared in glibc 2.12, so we use syscall
105         // directly.
106         unsafe {
107             libc::prctl(PR_SET_NAME, name.as_ptr() as libc::c_ulong, 0, 0, 0);
108         }
109     }
110
111     #[cfg(any(target_os = "freebsd",
112               target_os = "dragonfly",
113               target_os = "bitrig",
114               target_os = "openbsd"))]
115     pub fn set_name(name: &CStr) {
116         unsafe {
117             libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
118         }
119     }
120
121     #[cfg(any(target_os = "macos", target_os = "ios"))]
122     pub fn set_name(name: &CStr) {
123         unsafe {
124             libc::pthread_setname_np(name.as_ptr());
125         }
126     }
127
128     #[cfg(target_os = "netbsd")]
129     pub fn set_name(name: &CStr) {
130         use ffi::CString;
131         let cname = CString::new(&b"%s"[..]).unwrap();
132         unsafe {
133             libc::pthread_setname_np(libc::pthread_self(), cname.as_ptr(),
134                                      name.as_ptr() as *mut libc::c_void);
135         }
136     }
137     #[cfg(any(target_env = "newlib",
138               target_os = "solaris",
139               target_os = "haiku",
140               target_os = "l4re",
141               target_os = "emscripten",
142               target_os = "hermit"))]
143     pub fn set_name(_name: &CStr) {
144         // Newlib, Illumos, Haiku, and Emscripten have no way to set a thread name.
145     }
146     #[cfg(target_os = "fuchsia")]
147     pub fn set_name(_name: &CStr) {
148         // FIXME: determine whether Fuchsia has a way to set a thread name.
149     }
150
151     pub fn sleep(dur: Duration) {
152         let mut secs = dur.as_secs();
153         let mut nsecs = dur.subsec_nanos() as _;
154
155         // If we're awoken with a signal then the return value will be -1 and
156         // nanosleep will fill in `ts` with the remaining time.
157         unsafe {
158             while secs > 0 || nsecs > 0 {
159                 let mut ts = libc::timespec {
160                     tv_sec: cmp::min(libc::time_t::max_value() as u64, secs) as libc::time_t,
161                     tv_nsec: nsecs,
162                 };
163                 secs -= ts.tv_sec as u64;
164                 if libc::nanosleep(&ts, &mut ts) == -1 {
165                     assert_eq!(os::errno(), libc::EINTR);
166                     secs += ts.tv_sec as u64;
167                     nsecs = ts.tv_nsec;
168                 } else {
169                     nsecs = 0;
170                 }
171             }
172         }
173     }
174
175     pub fn join(self) {
176         unsafe {
177             let ret = libc::pthread_join(self.id, ptr::null_mut());
178             mem::forget(self);
179             assert!(ret == 0,
180                     "failed to join thread: {}", io::Error::from_raw_os_error(ret));
181         }
182     }
183
184     pub fn id(&self) -> libc::pthread_t { self.id }
185
186     pub fn into_id(self) -> libc::pthread_t {
187         let id = self.id;
188         mem::forget(self);
189         id
190     }
191 }
192
193 impl Drop for Thread {
194     fn drop(&mut self) {
195         let ret = unsafe { libc::pthread_detach(self.id) };
196         debug_assert_eq!(ret, 0);
197     }
198 }
199
200 #[cfg(all(not(all(target_os = "linux", not(target_env = "musl"))),
201           not(target_os = "freebsd"),
202           not(target_os = "macos"),
203           not(target_os = "bitrig"),
204           not(all(target_os = "netbsd", not(target_vendor = "rumprun"))),
205           not(target_os = "openbsd"),
206           not(target_os = "solaris")))]
207 #[cfg_attr(test, allow(dead_code))]
208 pub mod guard {
209     use ops::Range;
210     pub type Guard = Range<usize>;
211     pub unsafe fn current() -> Option<Guard> { None }
212     pub unsafe fn init() -> Option<Guard> { None }
213     pub unsafe fn deinit() {}
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     pub unsafe fn deinit() {
358         if !cfg!(target_os = "linux") {
359             if let Some(stackaddr) = get_stack_start_aligned() {
360                 // Remove the protection on the guard page.
361                 // FIXME: we cannot unmap the page, because when we mmap()
362                 // above it may be already mapped by the OS, which we can't
363                 // detect from mmap()'s return value. If we unmap this page,
364                 // it will lead to failure growing stack size on platforms like
365                 // macOS. Instead, just restore the page to a writable state.
366                 // This ain't Linux, so we probably don't need to care about
367                 // execstack.
368                 let result = mprotect(stackaddr, PAGE_SIZE, PROT_READ | PROT_WRITE);
369
370                 if result != 0 {
371                     panic!("unable to reset the guard page");
372                 }
373             }
374         }
375     }
376
377     #[cfg(any(target_os = "macos",
378               target_os = "bitrig",
379               target_os = "openbsd",
380               target_os = "solaris"))]
381     pub unsafe fn current() -> Option<Guard> {
382         let stackaddr = get_stack_start()? as usize;
383         Some(stackaddr - PAGE_SIZE..stackaddr)
384     }
385
386     #[cfg(any(target_os = "android", target_os = "freebsd",
387               target_os = "linux", target_os = "netbsd", target_os = "l4re"))]
388     pub unsafe fn current() -> Option<Guard> {
389         let mut ret = None;
390         let mut attr: libc::pthread_attr_t = ::mem::zeroed();
391         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
392         #[cfg(target_os = "freebsd")]
393             let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
394         #[cfg(not(target_os = "freebsd"))]
395             let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
396         if e == 0 {
397             let mut guardsize = 0;
398             assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
399             if guardsize == 0 {
400                 panic!("there is no guard page");
401             }
402             let mut stackaddr = ::ptr::null_mut();
403             let mut size = 0;
404             assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
405                                                    &mut size), 0);
406
407             let stackaddr = stackaddr as usize;
408             ret = if cfg!(target_os = "freebsd") {
409                 // FIXME does freebsd really fault *below* the guard addr?
410                 let guardaddr = stackaddr - guardsize;
411                 Some(guardaddr - PAGE_SIZE..guardaddr)
412             } else if cfg!(target_os = "netbsd") {
413                 Some(stackaddr - guardsize..stackaddr)
414             } else if cfg!(all(target_os = "linux", target_env = "gnu")) {
415                 // glibc used to include the guard area within the stack, as noted in the BUGS
416                 // section of `man pthread_attr_getguardsize`.  This has been corrected starting
417                 // with glibc 2.27, and in some distro backports, so the guard is now placed at the
418                 // end (below) the stack.  There's no easy way for us to know which we have at
419                 // runtime, so we'll just match any fault in the range right above or below the
420                 // stack base to call that fault a stack overflow.
421                 Some(stackaddr - guardsize..stackaddr + guardsize)
422             } else {
423                 Some(stackaddr..stackaddr + guardsize)
424             };
425         }
426         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
427         ret
428     }
429 }
430
431 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
432 // PTHREAD_STACK_MIN plus however many bytes are needed for thread-local
433 // storage.  We need that information to avoid blowing up when a small stack
434 // is created in an application with big thread-local storage requirements.
435 // See #6233 for rationale and details.
436 #[cfg(target_os = "linux")]
437 #[allow(deprecated)]
438 fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
439     weak!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);
440
441     match __pthread_get_minstack.get() {
442         None => libc::PTHREAD_STACK_MIN,
443         Some(f) => unsafe { f(attr) },
444     }
445 }
446
447 // No point in looking up __pthread_get_minstack() on non-glibc
448 // platforms.
449 #[cfg(all(not(target_os = "linux"),
450           not(target_os = "netbsd")))]
451 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
452     libc::PTHREAD_STACK_MIN
453 }
454
455 #[cfg(target_os = "netbsd")]
456 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
457     2048 // just a guess
458 }