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