]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/thread.rs
Change sys::Thread::new to take the thread entry as Box<dyn FnBox() + 'static>̣
[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     pub unsafe fn deinit() {}
215 }
216
217
218 #[cfg(any(all(target_os = "linux", not(target_env = "musl")),
219           target_os = "freebsd",
220           target_os = "macos",
221           target_os = "bitrig",
222           all(target_os = "netbsd", not(target_vendor = "rumprun")),
223           target_os = "openbsd",
224           target_os = "solaris"))]
225 #[cfg_attr(test, allow(dead_code))]
226 pub mod guard {
227     use libc;
228     use libc::{mmap, mprotect};
229     use libc::{PROT_NONE, PROT_READ, PROT_WRITE, MAP_PRIVATE, MAP_ANON, MAP_FAILED, MAP_FIXED};
230     use ops::Range;
231     use sys::os;
232
233     // This is initialized in init() and only read from after
234     static mut PAGE_SIZE: usize = 0;
235
236     pub type Guard = Range<usize>;
237
238     #[cfg(target_os = "solaris")]
239     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
240         let mut current_stack: libc::stack_t = ::mem::zeroed();
241         assert_eq!(libc::stack_getbounds(&mut current_stack), 0);
242         Some(current_stack.ss_sp)
243     }
244
245     #[cfg(target_os = "macos")]
246     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
247         let stackaddr = libc::pthread_get_stackaddr_np(libc::pthread_self()) as usize -
248              libc::pthread_get_stacksize_np(libc::pthread_self());
249         Some(stackaddr as *mut libc::c_void)
250     }
251
252     #[cfg(any(target_os = "openbsd", target_os = "bitrig"))]
253     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
254         let mut current_stack: libc::stack_t = ::mem::zeroed();
255         assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(),
256                                              &mut current_stack), 0);
257
258         let extra = if cfg!(target_os = "bitrig") {3} else {1} * PAGE_SIZE;
259         let stackaddr = if libc::pthread_main_np() == 1 {
260             // main thread
261             current_stack.ss_sp as usize - current_stack.ss_size + extra
262         } else {
263             // new thread
264             current_stack.ss_sp as usize - current_stack.ss_size
265         };
266         Some(stackaddr as *mut libc::c_void)
267     }
268
269     #[cfg(any(target_os = "android", target_os = "freebsd",
270               target_os = "linux", target_os = "netbsd", target_os = "l4re"))]
271     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
272         let mut ret = None;
273         let mut attr: libc::pthread_attr_t = ::mem::zeroed();
274         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
275         #[cfg(target_os = "freebsd")]
276             let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
277         #[cfg(not(target_os = "freebsd"))]
278             let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
279         if e == 0 {
280             let mut stackaddr = ::ptr::null_mut();
281             let mut stacksize = 0;
282             assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
283                                                    &mut stacksize), 0);
284             ret = Some(stackaddr);
285         }
286         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
287         ret
288     }
289
290     // Precondition: PAGE_SIZE is initialized.
291     unsafe fn get_stack_start_aligned() -> Option<*mut libc::c_void> {
292         assert!(PAGE_SIZE != 0);
293         let stackaddr = get_stack_start()?;
294
295         // Ensure stackaddr is page aligned! A parent process might
296         // have reset RLIMIT_STACK to be non-page aligned. The
297         // pthread_attr_getstack() reports the usable stack area
298         // stackaddr < stackaddr + stacksize, so if stackaddr is not
299         // page-aligned, calculate the fix such that stackaddr <
300         // new_page_aligned_stackaddr < stackaddr + stacksize
301         let remainder = (stackaddr as usize) % PAGE_SIZE;
302         Some(if remainder == 0 {
303             stackaddr
304         } else {
305             ((stackaddr as usize) + PAGE_SIZE - remainder) as *mut libc::c_void
306         })
307     }
308
309     pub unsafe fn init() -> Option<Guard> {
310         PAGE_SIZE = os::page_size();
311
312         let stackaddr = get_stack_start_aligned()?;
313
314         if cfg!(target_os = "linux") {
315             // Linux doesn't allocate the whole stack right away, and
316             // the kernel has its own stack-guard mechanism to fault
317             // when growing too close to an existing mapping.  If we map
318             // our own guard, then the kernel starts enforcing a rather
319             // large gap above that, rendering much of the possible
320             // stack space useless.  See #43052.
321             //
322             // Instead, we'll just note where we expect rlimit to start
323             // faulting, so our handler can report "stack overflow", and
324             // trust that the kernel's own stack guard will work.
325             let stackaddr = stackaddr as usize;
326             Some(stackaddr - PAGE_SIZE..stackaddr)
327         } else {
328             // Reallocate the last page of the stack.
329             // This ensures SIGBUS will be raised on
330             // stack overflow.
331             // Systems which enforce strict PAX MPROTECT do not allow
332             // to mprotect() a mapping with less restrictive permissions
333             // than the initial mmap() used, so we mmap() here with
334             // read/write permissions and only then mprotect() it to
335             // no permissions at all. See issue #50313.
336             let result = mmap(stackaddr, PAGE_SIZE, PROT_READ | PROT_WRITE,
337                               MAP_PRIVATE | MAP_ANON | MAP_FIXED, -1, 0);
338             if result != stackaddr || result == MAP_FAILED {
339                 panic!("failed to allocate a guard page");
340             }
341
342             let result = mprotect(stackaddr, PAGE_SIZE, PROT_NONE);
343             if result != 0 {
344                 panic!("failed to protect the guard page");
345             }
346
347             let guardaddr = stackaddr as usize;
348             let offset = if cfg!(target_os = "freebsd") {
349                 2
350             } else {
351                 1
352             };
353
354             Some(guardaddr..guardaddr + offset * PAGE_SIZE)
355         }
356     }
357
358     pub unsafe fn deinit() {
359         if !cfg!(target_os = "linux") {
360             if let Some(stackaddr) = get_stack_start_aligned() {
361                 // Remove the protection on the guard page.
362                 // FIXME: we cannot unmap the page, because when we mmap()
363                 // above it may be already mapped by the OS, which we can't
364                 // detect from mmap()'s return value. If we unmap this page,
365                 // it will lead to failure growing stack size on platforms like
366                 // macOS. Instead, just restore the page to a writable state.
367                 // This ain't Linux, so we probably don't need to care about
368                 // execstack.
369                 let result = mprotect(stackaddr, PAGE_SIZE, PROT_READ | PROT_WRITE);
370
371                 if result != 0 {
372                     panic!("unable to reset the guard page");
373                 }
374             }
375         }
376     }
377
378     #[cfg(any(target_os = "macos",
379               target_os = "bitrig",
380               target_os = "openbsd",
381               target_os = "solaris"))]
382     pub unsafe fn current() -> Option<Guard> {
383         let stackaddr = get_stack_start()? as usize;
384         Some(stackaddr - PAGE_SIZE..stackaddr)
385     }
386
387     #[cfg(any(target_os = "android", target_os = "freebsd",
388               target_os = "linux", target_os = "netbsd", target_os = "l4re"))]
389     pub unsafe fn current() -> Option<Guard> {
390         let mut ret = None;
391         let mut attr: libc::pthread_attr_t = ::mem::zeroed();
392         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
393         #[cfg(target_os = "freebsd")]
394             let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
395         #[cfg(not(target_os = "freebsd"))]
396             let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
397         if e == 0 {
398             let mut guardsize = 0;
399             assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
400             if guardsize == 0 {
401                 panic!("there is no guard page");
402             }
403             let mut stackaddr = ::ptr::null_mut();
404             let mut size = 0;
405             assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
406                                                    &mut size), 0);
407
408             let stackaddr = stackaddr as usize;
409             ret = if cfg!(target_os = "freebsd") {
410                 // FIXME does freebsd really fault *below* the guard addr?
411                 let guardaddr = stackaddr - guardsize;
412                 Some(guardaddr - PAGE_SIZE..guardaddr)
413             } else if cfg!(target_os = "netbsd") {
414                 Some(stackaddr - guardsize..stackaddr)
415             } else if cfg!(all(target_os = "linux", target_env = "gnu")) {
416                 // glibc used to include the guard area within the stack, as noted in the BUGS
417                 // section of `man pthread_attr_getguardsize`.  This has been corrected starting
418                 // with glibc 2.27, and in some distro backports, so the guard is now placed at the
419                 // end (below) the stack.  There's no easy way for us to know which we have at
420                 // runtime, so we'll just match any fault in the range right above or below the
421                 // stack base to call that fault a stack overflow.
422                 Some(stackaddr - guardsize..stackaddr + guardsize)
423             } else {
424                 Some(stackaddr..stackaddr + guardsize)
425             };
426         }
427         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
428         ret
429     }
430 }
431
432 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
433 // PTHREAD_STACK_MIN plus however many bytes are needed for thread-local
434 // storage.  We need that information to avoid blowing up when a small stack
435 // is created in an application with big thread-local storage requirements.
436 // See #6233 for rationale and details.
437 #[cfg(target_os = "linux")]
438 #[allow(deprecated)]
439 fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
440     weak!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);
441
442     match __pthread_get_minstack.get() {
443         None => libc::PTHREAD_STACK_MIN,
444         Some(f) => unsafe { f(attr) },
445     }
446 }
447
448 // No point in looking up __pthread_get_minstack() on non-glibc
449 // platforms.
450 #[cfg(all(not(target_os = "linux"),
451           not(target_os = "netbsd")))]
452 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
453     libc::PTHREAD_STACK_MIN
454 }
455
456 #[cfg(target_os = "netbsd")]
457 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
458     2048 // just a guess
459 }