]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/thread.rs
Rollup merge of #47922 - zackmdavis:and_the_case_of_the_unused_field_pattern, r=estebank
[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 #[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<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     pub fn set_name(_name: &CStr) {
143         // Newlib, Illumos, Haiku, and Emscripten have no way to set a thread name.
144     }
145     #[cfg(target_os = "fuchsia")]
146     pub fn set_name(_name: &CStr) {
147         // FIXME: determine whether Fuchsia has a way to set a thread name.
148     }
149
150     pub fn sleep(dur: Duration) {
151         let mut secs = dur.as_secs();
152         let mut nsecs = dur.subsec_nanos() as _;
153
154         // If we're awoken with a signal then the return value will be -1 and
155         // nanosleep will fill in `ts` with the remaining time.
156         unsafe {
157             while secs > 0 || nsecs > 0 {
158                 let mut ts = libc::timespec {
159                     tv_sec: cmp::min(libc::time_t::max_value() as u64, secs) as libc::time_t,
160                     tv_nsec: nsecs,
161                 };
162                 secs -= ts.tv_sec as u64;
163                 if libc::nanosleep(&ts, &mut ts) == -1 {
164                     assert_eq!(os::errno(), libc::EINTR);
165                     secs += ts.tv_sec as u64;
166                     nsecs = ts.tv_nsec;
167                 } else {
168                     nsecs = 0;
169                 }
170             }
171         }
172     }
173
174     pub fn join(self) {
175         unsafe {
176             let ret = libc::pthread_join(self.id, ptr::null_mut());
177             mem::forget(self);
178             assert!(ret == 0,
179                     "failed to join thread: {}", io::Error::from_raw_os_error(ret));
180         }
181     }
182
183     pub fn id(&self) -> libc::pthread_t { self.id }
184
185     pub fn into_id(self) -> libc::pthread_t {
186         let id = self.id;
187         mem::forget(self);
188         id
189     }
190 }
191
192 impl Drop for Thread {
193     fn drop(&mut self) {
194         let ret = unsafe { libc::pthread_detach(self.id) };
195         debug_assert_eq!(ret, 0);
196     }
197 }
198
199 #[cfg(all(not(all(target_os = "linux", not(target_env = "musl"))),
200           not(target_os = "freebsd"),
201           not(target_os = "macos"),
202           not(target_os = "bitrig"),
203           not(all(target_os = "netbsd", not(target_vendor = "rumprun"))),
204           not(target_os = "openbsd"),
205           not(target_os = "solaris")))]
206 #[cfg_attr(test, allow(dead_code))]
207 pub mod guard {
208     use ops::Range;
209     pub type Guard = Range<usize>;
210     pub unsafe fn current() -> Option<Guard> { None }
211     pub unsafe fn init() -> Option<Guard> { None }
212 }
213
214
215 #[cfg(any(all(target_os = "linux", not(target_env = "musl")),
216           target_os = "freebsd",
217           target_os = "macos",
218           target_os = "bitrig",
219           all(target_os = "netbsd", not(target_vendor = "rumprun")),
220           target_os = "openbsd",
221           target_os = "solaris"))]
222 #[cfg_attr(test, allow(dead_code))]
223 pub mod guard {
224     use libc;
225     use libc::mmap;
226     use libc::{PROT_NONE, MAP_PRIVATE, MAP_ANON, MAP_FAILED, MAP_FIXED};
227     use ops::Range;
228     use sys::os;
229
230     // This is initialized in init() and only read from after
231     static mut PAGE_SIZE: usize = 0;
232
233     pub type Guard = Range<usize>;
234
235     #[cfg(target_os = "solaris")]
236     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
237         let mut current_stack: libc::stack_t = ::mem::zeroed();
238         assert_eq!(libc::stack_getbounds(&mut current_stack), 0);
239         Some(current_stack.ss_sp)
240     }
241
242     #[cfg(target_os = "macos")]
243     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
244         let stackaddr = libc::pthread_get_stackaddr_np(libc::pthread_self()) as usize -
245              libc::pthread_get_stacksize_np(libc::pthread_self());
246         Some(stackaddr as *mut libc::c_void)
247     }
248
249     #[cfg(any(target_os = "openbsd", target_os = "bitrig"))]
250     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
251         let mut current_stack: libc::stack_t = ::mem::zeroed();
252         assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(),
253                                              &mut current_stack), 0);
254
255         let extra = if cfg!(target_os = "bitrig") {3} else {1} * PAGE_SIZE;
256         let stackaddr = if libc::pthread_main_np() == 1 {
257             // main thread
258             current_stack.ss_sp as usize - current_stack.ss_size + extra
259         } else {
260             // new thread
261             current_stack.ss_sp as usize - current_stack.ss_size
262         };
263         Some(stackaddr as *mut libc::c_void)
264     }
265
266     #[cfg(any(target_os = "android", target_os = "freebsd",
267               target_os = "linux", target_os = "netbsd", target_os = "l4re"))]
268     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
269         let mut ret = None;
270         let mut attr: libc::pthread_attr_t = ::mem::zeroed();
271         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
272         #[cfg(target_os = "freebsd")]
273             let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
274         #[cfg(not(target_os = "freebsd"))]
275             let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
276         if e == 0 {
277             let mut stackaddr = ::ptr::null_mut();
278             let mut stacksize = 0;
279             assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
280                                                    &mut stacksize), 0);
281             ret = Some(stackaddr);
282         }
283         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
284         ret
285     }
286
287     pub unsafe fn init() -> Option<Guard> {
288         PAGE_SIZE = os::page_size();
289
290         let mut stackaddr = get_stack_start()?;
291
292         // Ensure stackaddr is page aligned! A parent process might
293         // have reset RLIMIT_STACK to be non-page aligned. The
294         // pthread_attr_getstack() reports the usable stack area
295         // stackaddr < stackaddr + stacksize, so if stackaddr is not
296         // page-aligned, calculate the fix such that stackaddr <
297         // new_page_aligned_stackaddr < stackaddr + stacksize
298         let remainder = (stackaddr as usize) % PAGE_SIZE;
299         if remainder != 0 {
300             stackaddr = ((stackaddr as usize) + PAGE_SIZE - remainder)
301                 as *mut libc::c_void;
302         }
303
304         if cfg!(target_os = "linux") {
305             // Linux doesn't allocate the whole stack right away, and
306             // the kernel has its own stack-guard mechanism to fault
307             // when growing too close to an existing mapping.  If we map
308             // our own guard, then the kernel starts enforcing a rather
309             // large gap above that, rendering much of the possible
310             // stack space useless.  See #43052.
311             //
312             // Instead, we'll just note where we expect rlimit to start
313             // faulting, so our handler can report "stack overflow", and
314             // trust that the kernel's own stack guard will work.
315             let stackaddr = stackaddr as usize;
316             Some(stackaddr - PAGE_SIZE..stackaddr)
317         } else {
318             // Reallocate the last page of the stack.
319             // This ensures SIGBUS will be raised on
320             // stack overflow.
321             let result = mmap(stackaddr, PAGE_SIZE, PROT_NONE,
322                               MAP_PRIVATE | MAP_ANON | MAP_FIXED, -1, 0);
323
324             if result != stackaddr || result == MAP_FAILED {
325                 panic!("failed to allocate a guard page");
326             }
327
328             let guardaddr = stackaddr as usize;
329             let offset = if cfg!(target_os = "freebsd") {
330                 2
331             } else {
332                 1
333             };
334
335             Some(guardaddr..guardaddr + offset * PAGE_SIZE)
336         }
337     }
338
339     #[cfg(any(target_os = "macos",
340               target_os = "bitrig",
341               target_os = "openbsd",
342               target_os = "solaris"))]
343     pub unsafe fn current() -> Option<Guard> {
344         let stackaddr = get_stack_start()? as usize;
345         Some(stackaddr - PAGE_SIZE..stackaddr)
346     }
347
348     #[cfg(any(target_os = "android", target_os = "freebsd",
349               target_os = "linux", target_os = "netbsd", target_os = "l4re"))]
350     pub unsafe fn current() -> Option<Guard> {
351         let mut ret = None;
352         let mut attr: libc::pthread_attr_t = ::mem::zeroed();
353         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
354         #[cfg(target_os = "freebsd")]
355             let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
356         #[cfg(not(target_os = "freebsd"))]
357             let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
358         if e == 0 {
359             let mut guardsize = 0;
360             assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
361             if guardsize == 0 {
362                 panic!("there is no guard page");
363             }
364             let mut stackaddr = ::ptr::null_mut();
365             let mut size = 0;
366             assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
367                                                    &mut size), 0);
368
369             let stackaddr = stackaddr as usize;
370             ret = if cfg!(target_os = "freebsd") {
371                 // FIXME does freebsd really fault *below* the guard addr?
372                 let guardaddr = stackaddr - guardsize;
373                 Some(guardaddr - PAGE_SIZE..guardaddr)
374             } else if cfg!(target_os = "netbsd") {
375                 Some(stackaddr - guardsize..stackaddr)
376             } else if cfg!(all(target_os = "linux", target_env = "gnu")) {
377                 // glibc used to include the guard area within the stack, as noted in the BUGS
378                 // section of `man pthread_attr_getguardsize`.  This has been corrected starting
379                 // with glibc 2.27, and in some distro backports, so the guard is now placed at the
380                 // end (below) the stack.  There's no easy way for us to know which we have at
381                 // runtime, so we'll just match any fault in the range right above or below the
382                 // stack base to call that fault a stack overflow.
383                 Some(stackaddr - guardsize..stackaddr + guardsize)
384             } else {
385                 Some(stackaddr..stackaddr + guardsize)
386             };
387         }
388         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
389         ret
390     }
391 }
392
393 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
394 // PTHREAD_STACK_MIN plus however many bytes are needed for thread-local
395 // storage.  We need that information to avoid blowing up when a small stack
396 // is created in an application with big thread-local storage requirements.
397 // See #6233 for rationale and details.
398 #[cfg(target_os = "linux")]
399 #[allow(deprecated)]
400 fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
401     weak!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);
402
403     match __pthread_get_minstack.get() {
404         None => libc::PTHREAD_STACK_MIN,
405         Some(f) => unsafe { f(attr) },
406     }
407 }
408
409 // No point in looking up __pthread_get_minstack() on non-glibc
410 // platforms.
411 #[cfg(all(not(target_os = "linux"),
412           not(target_os = "netbsd")))]
413 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
414     libc::PTHREAD_STACK_MIN
415 }
416
417 #[cfg(target_os = "netbsd")]
418 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
419     2048 // just a guess
420 }