]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/thread.rs
Rollup merge of #87759 - m-ou-se:linux-process-sealed, r=jyn514
[rust.git] / library / std / src / sys / unix / thread.rs
1 use crate::cmp;
2 use crate::ffi::CStr;
3 use crate::io;
4 use crate::mem;
5 use crate::num::NonZeroUsize;
6 use crate::ptr;
7 use crate::sys::{os, stack_overflow};
8 use crate::time::Duration;
9
10 #[cfg(any(target_os = "linux", target_os = "solaris", target_os = "illumos"))]
11 use crate::sys::weak::weak;
12 #[cfg(not(any(target_os = "l4re", target_os = "vxworks")))]
13 pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
14 #[cfg(target_os = "l4re")]
15 pub const DEFAULT_MIN_STACK_SIZE: usize = 1024 * 1024;
16 #[cfg(target_os = "vxworks")]
17 pub const DEFAULT_MIN_STACK_SIZE: usize = 256 * 1024;
18
19 #[cfg(target_os = "fuchsia")]
20 mod zircon {
21     type zx_handle_t = u32;
22     type zx_status_t = i32;
23     pub const ZX_PROP_NAME: u32 = 3;
24
25     extern "C" {
26         pub fn zx_object_set_property(
27             handle: zx_handle_t,
28             property: u32,
29             value: *const libc::c_void,
30             value_size: libc::size_t,
31         ) -> zx_status_t;
32         pub fn zx_thread_self() -> zx_handle_t;
33     }
34 }
35
36 pub struct Thread {
37     id: libc::pthread_t,
38 }
39
40 // Some platforms may have pthread_t as a pointer in which case we still want
41 // a thread to be Send/Sync
42 unsafe impl Send for Thread {}
43 unsafe impl Sync for Thread {}
44
45 impl Thread {
46     // unsafe: see thread::Builder::spawn_unchecked for safety requirements
47     pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
48         let p = Box::into_raw(box p);
49         let mut native: libc::pthread_t = mem::zeroed();
50         let mut attr: libc::pthread_attr_t = mem::zeroed();
51         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
52
53         let stack_size = cmp::max(stack, min_stack_size(&attr));
54
55         match libc::pthread_attr_setstacksize(&mut attr, stack_size) {
56             0 => {}
57             n => {
58                 assert_eq!(n, libc::EINVAL);
59                 // EINVAL means |stack_size| is either too small or not a
60                 // multiple of the system page size.  Because it's definitely
61                 // >= PTHREAD_STACK_MIN, it must be an alignment issue.
62                 // Round up to the nearest page and try again.
63                 let page_size = os::page_size();
64                 let stack_size =
65                     (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1);
66                 assert_eq!(libc::pthread_attr_setstacksize(&mut attr, stack_size), 0);
67             }
68         };
69
70         let ret = libc::pthread_create(&mut native, &attr, thread_start, p as *mut _);
71         // Note: if the thread creation fails and this assert fails, then p will
72         // be leaked. However, an alternative design could cause double-free
73         // which is clearly worse.
74         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
75
76         return if ret != 0 {
77             // The thread failed to start and as a result p was not consumed. Therefore, it is
78             // safe to reconstruct the box so that it gets deallocated.
79             drop(Box::from_raw(p));
80             Err(io::Error::from_raw_os_error(ret))
81         } else {
82             Ok(Thread { id: native })
83         };
84
85         extern "C" fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
86             unsafe {
87                 // Next, set up our stack overflow handler which may get triggered if we run
88                 // out of stack.
89                 let _handler = stack_overflow::Handler::new();
90                 // Finally, let's run some code.
91                 Box::from_raw(main as *mut Box<dyn FnOnce()>)();
92             }
93             ptr::null_mut()
94         }
95     }
96
97     pub fn yield_now() {
98         let ret = unsafe { libc::sched_yield() };
99         debug_assert_eq!(ret, 0);
100     }
101
102     #[cfg(any(target_os = "linux", 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", target_os = "dragonfly", target_os = "openbsd"))]
113     pub fn set_name(name: &CStr) {
114         unsafe {
115             libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
116         }
117     }
118
119     #[cfg(any(target_os = "macos", target_os = "ios"))]
120     pub fn set_name(name: &CStr) {
121         unsafe {
122             libc::pthread_setname_np(name.as_ptr());
123         }
124     }
125
126     #[cfg(target_os = "netbsd")]
127     pub fn set_name(name: &CStr) {
128         use crate::ffi::CString;
129         let cname = CString::new(&b"%s"[..]).unwrap();
130         unsafe {
131             libc::pthread_setname_np(
132                 libc::pthread_self(),
133                 cname.as_ptr(),
134                 name.as_ptr() as *mut libc::c_void,
135             );
136         }
137     }
138
139     #[cfg(any(target_os = "solaris", target_os = "illumos"))]
140     pub fn set_name(name: &CStr) {
141         weak! {
142             fn pthread_setname_np(
143                 libc::pthread_t, *const libc::c_char
144             ) -> libc::c_int
145         }
146
147         if let Some(f) = pthread_setname_np.get() {
148             unsafe {
149                 f(libc::pthread_self(), name.as_ptr());
150             }
151         }
152     }
153
154     #[cfg(target_os = "fuchsia")]
155     pub fn set_name(name: &CStr) {
156         use self::zircon::*;
157         unsafe {
158             zx_object_set_property(
159                 zx_thread_self(),
160                 ZX_PROP_NAME,
161                 name.as_ptr() as *const libc::c_void,
162                 name.to_bytes().len(),
163             );
164         }
165     }
166
167     #[cfg(target_os = "haiku")]
168     pub fn set_name(name: &CStr) {
169         unsafe {
170             let thread_self = libc::find_thread(ptr::null_mut());
171             libc::rename_thread(thread_self, name.as_ptr());
172         }
173     }
174
175     #[cfg(any(
176         target_env = "newlib",
177         target_os = "l4re",
178         target_os = "emscripten",
179         target_os = "redox",
180         target_os = "vxworks"
181     ))]
182     pub fn set_name(_name: &CStr) {
183         // Newlib, Emscripten, and VxWorks have no way to set a thread name.
184     }
185
186     pub fn sleep(dur: Duration) {
187         let mut secs = dur.as_secs();
188         let mut nsecs = dur.subsec_nanos() as _;
189
190         // If we're awoken with a signal then the return value will be -1 and
191         // nanosleep will fill in `ts` with the remaining time.
192         unsafe {
193             while secs > 0 || nsecs > 0 {
194                 let mut ts = libc::timespec {
195                     tv_sec: cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t,
196                     tv_nsec: nsecs,
197                 };
198                 secs -= ts.tv_sec as u64;
199                 let ts_ptr = &mut ts as *mut _;
200                 if libc::nanosleep(ts_ptr, ts_ptr) == -1 {
201                     assert_eq!(os::errno(), libc::EINTR);
202                     secs += ts.tv_sec as u64;
203                     nsecs = ts.tv_nsec;
204                 } else {
205                     nsecs = 0;
206                 }
207             }
208         }
209     }
210
211     pub fn join(self) {
212         unsafe {
213             let ret = libc::pthread_join(self.id, ptr::null_mut());
214             mem::forget(self);
215             assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
216         }
217     }
218
219     pub fn id(&self) -> libc::pthread_t {
220         self.id
221     }
222
223     pub fn into_id(self) -> libc::pthread_t {
224         let id = self.id;
225         mem::forget(self);
226         id
227     }
228 }
229
230 impl Drop for Thread {
231     fn drop(&mut self) {
232         let ret = unsafe { libc::pthread_detach(self.id) };
233         debug_assert_eq!(ret, 0);
234     }
235 }
236
237 pub fn available_concurrency() -> io::Result<NonZeroUsize> {
238     cfg_if::cfg_if! {
239         if #[cfg(any(
240             target_os = "android",
241             target_os = "emscripten",
242             target_os = "fuchsia",
243             target_os = "ios",
244             target_os = "linux",
245             target_os = "macos",
246             target_os = "solaris",
247             target_os = "illumos",
248         ))] {
249             match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
250                 -1 => Err(io::Error::last_os_error()),
251                 0 => Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform")),
252                 cpus => Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) }),
253             }
254         } else if #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd"))] {
255             use crate::ptr;
256
257             let mut cpus: libc::c_uint = 0;
258             let mut cpus_size = crate::mem::size_of_val(&cpus);
259
260             unsafe {
261                 cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint;
262             }
263
264             // Fallback approach in case of errors or no hardware threads.
265             if cpus < 1 {
266                 let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
267                 let res = unsafe {
268                     libc::sysctl(
269                         mib.as_mut_ptr(),
270                         2,
271                         &mut cpus as *mut _ as *mut _,
272                         &mut cpus_size as *mut _ as *mut _,
273                         ptr::null_mut(),
274                         0,
275                     )
276                 };
277
278                 // Handle errors if any.
279                 if res == -1 {
280                     return Err(io::Error::last_os_error());
281                 } else if cpus == 0 {
282                     return Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform"));
283                 }
284             }
285             Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) })
286         } else if #[cfg(target_os = "openbsd")] {
287             use crate::ptr;
288
289             let mut cpus: libc::c_uint = 0;
290             let mut cpus_size = crate::mem::size_of_val(&cpus);
291             let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0];
292
293             let res = unsafe {
294                 libc::sysctl(
295                     mib.as_mut_ptr(),
296                     2,
297                     &mut cpus as *mut _ as *mut _,
298                     &mut cpus_size as *mut _ as *mut _,
299                     ptr::null_mut(),
300                     0,
301                 )
302             };
303
304             // Handle errors if any.
305             if res == -1 {
306                 return Err(io::Error::last_os_error());
307             } else if cpus == 0 {
308                 return Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform"));
309             }
310
311             Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) })
312         } else {
313             // FIXME: implement on vxWorks, Redox, Haiku, l4re
314             Err(io::Error::new_const(io::ErrorKind::Unsupported, &"Getting the number of hardware threads is not supported on the target platform"))
315         }
316     }
317 }
318
319 #[cfg(all(
320     not(target_os = "linux"),
321     not(target_os = "freebsd"),
322     not(target_os = "macos"),
323     not(target_os = "netbsd"),
324     not(target_os = "openbsd"),
325     not(target_os = "solaris")
326 ))]
327 #[cfg_attr(test, allow(dead_code))]
328 pub mod guard {
329     use crate::ops::Range;
330     pub type Guard = Range<usize>;
331     pub unsafe fn current() -> Option<Guard> {
332         None
333     }
334     pub unsafe fn init() -> Option<Guard> {
335         None
336     }
337 }
338
339 #[cfg(any(
340     target_os = "linux",
341     target_os = "freebsd",
342     target_os = "macos",
343     target_os = "netbsd",
344     target_os = "openbsd",
345     target_os = "solaris"
346 ))]
347 #[cfg_attr(test, allow(dead_code))]
348 pub mod guard {
349     use libc::{mmap, mprotect};
350     use libc::{MAP_ANON, MAP_FAILED, MAP_FIXED, MAP_PRIVATE, PROT_NONE, PROT_READ, PROT_WRITE};
351
352     use crate::io;
353     use crate::ops::Range;
354     use crate::sync::atomic::{AtomicUsize, Ordering};
355     use crate::sys::os;
356
357     // This is initialized in init() and only read from after
358     static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0);
359
360     pub type Guard = Range<usize>;
361
362     #[cfg(target_os = "solaris")]
363     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
364         let mut current_stack: libc::stack_t = crate::mem::zeroed();
365         assert_eq!(libc::stack_getbounds(&mut current_stack), 0);
366         Some(current_stack.ss_sp)
367     }
368
369     #[cfg(target_os = "macos")]
370     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
371         let th = libc::pthread_self();
372         let stackaddr =
373             libc::pthread_get_stackaddr_np(th) as usize - libc::pthread_get_stacksize_np(th);
374         Some(stackaddr as *mut libc::c_void)
375     }
376
377     #[cfg(target_os = "openbsd")]
378     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
379         let mut current_stack: libc::stack_t = crate::mem::zeroed();
380         assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(), &mut current_stack), 0);
381
382         let stackaddr = if libc::pthread_main_np() == 1 {
383             // main thread
384             current_stack.ss_sp as usize - current_stack.ss_size + PAGE_SIZE.load(Ordering::Relaxed)
385         } else {
386             // new thread
387             current_stack.ss_sp as usize - current_stack.ss_size
388         };
389         Some(stackaddr as *mut libc::c_void)
390     }
391
392     #[cfg(any(
393         target_os = "android",
394         target_os = "freebsd",
395         target_os = "linux",
396         target_os = "netbsd",
397         target_os = "l4re"
398     ))]
399     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
400         let mut ret = None;
401         let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
402         #[cfg(target_os = "freebsd")]
403         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
404         #[cfg(target_os = "freebsd")]
405         let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
406         #[cfg(not(target_os = "freebsd"))]
407         let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
408         if e == 0 {
409             let mut stackaddr = crate::ptr::null_mut();
410             let mut stacksize = 0;
411             assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut stacksize), 0);
412             ret = Some(stackaddr);
413         }
414         if e == 0 || cfg!(target_os = "freebsd") {
415             assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
416         }
417         ret
418     }
419
420     // Precondition: PAGE_SIZE is initialized.
421     unsafe fn get_stack_start_aligned() -> Option<*mut libc::c_void> {
422         let page_size = PAGE_SIZE.load(Ordering::Relaxed);
423         assert!(page_size != 0);
424         let stackaddr = get_stack_start()?;
425
426         // Ensure stackaddr is page aligned! A parent process might
427         // have reset RLIMIT_STACK to be non-page aligned. The
428         // pthread_attr_getstack() reports the usable stack area
429         // stackaddr < stackaddr + stacksize, so if stackaddr is not
430         // page-aligned, calculate the fix such that stackaddr <
431         // new_page_aligned_stackaddr < stackaddr + stacksize
432         let remainder = (stackaddr as usize) % page_size;
433         Some(if remainder == 0 {
434             stackaddr
435         } else {
436             ((stackaddr as usize) + page_size - remainder) as *mut libc::c_void
437         })
438     }
439
440     pub unsafe fn init() -> Option<Guard> {
441         let page_size = os::page_size();
442         PAGE_SIZE.store(page_size, Ordering::Relaxed);
443
444         if cfg!(all(target_os = "linux", not(target_env = "musl"))) {
445             // Linux doesn't allocate the whole stack right away, and
446             // the kernel has its own stack-guard mechanism to fault
447             // when growing too close to an existing mapping.  If we map
448             // our own guard, then the kernel starts enforcing a rather
449             // large gap above that, rendering much of the possible
450             // stack space useless.  See #43052.
451             //
452             // Instead, we'll just note where we expect rlimit to start
453             // faulting, so our handler can report "stack overflow", and
454             // trust that the kernel's own stack guard will work.
455             let stackaddr = get_stack_start_aligned()?;
456             let stackaddr = stackaddr as usize;
457             Some(stackaddr - page_size..stackaddr)
458         } else if cfg!(all(target_os = "linux", target_env = "musl")) {
459             // For the main thread, the musl's pthread_attr_getstack
460             // returns the current stack size, rather than maximum size
461             // it can eventually grow to. It cannot be used to determine
462             // the position of kernel's stack guard.
463             None
464         } else if cfg!(target_os = "freebsd") {
465             // FreeBSD's stack autogrows, and optionally includes a guard page
466             // at the bottom.  If we try to remap the bottom of the stack
467             // ourselves, FreeBSD's guard page moves upwards.  So we'll just use
468             // the builtin guard page.
469             let stackaddr = get_stack_start_aligned()?;
470             let guardaddr = stackaddr as usize;
471             // Technically the number of guard pages is tunable and controlled
472             // by the security.bsd.stack_guard_page sysctl, but there are
473             // few reasons to change it from the default.  The default value has
474             // been 1 ever since FreeBSD 11.1 and 10.4.
475             const GUARD_PAGES: usize = 1;
476             let guard = guardaddr..guardaddr + GUARD_PAGES * page_size;
477             Some(guard)
478         } else {
479             // Reallocate the last page of the stack.
480             // This ensures SIGBUS will be raised on
481             // stack overflow.
482             // Systems which enforce strict PAX MPROTECT do not allow
483             // to mprotect() a mapping with less restrictive permissions
484             // than the initial mmap() used, so we mmap() here with
485             // read/write permissions and only then mprotect() it to
486             // no permissions at all. See issue #50313.
487             let stackaddr = get_stack_start_aligned()?;
488             let result = mmap(
489                 stackaddr,
490                 page_size,
491                 PROT_READ | PROT_WRITE,
492                 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
493                 -1,
494                 0,
495             );
496             if result != stackaddr || result == MAP_FAILED {
497                 panic!("failed to allocate a guard page: {}", io::Error::last_os_error());
498             }
499
500             let result = mprotect(stackaddr, page_size, PROT_NONE);
501             if result != 0 {
502                 panic!("failed to protect the guard page: {}", io::Error::last_os_error());
503             }
504
505             let guardaddr = stackaddr as usize;
506
507             Some(guardaddr..guardaddr + page_size)
508         }
509     }
510
511     #[cfg(any(target_os = "macos", target_os = "openbsd", target_os = "solaris"))]
512     pub unsafe fn current() -> Option<Guard> {
513         let stackaddr = get_stack_start()? as usize;
514         Some(stackaddr - PAGE_SIZE.load(Ordering::Relaxed)..stackaddr)
515     }
516
517     #[cfg(any(
518         target_os = "android",
519         target_os = "freebsd",
520         target_os = "linux",
521         target_os = "netbsd",
522         target_os = "l4re"
523     ))]
524     pub unsafe fn current() -> Option<Guard> {
525         let mut ret = None;
526         let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
527         #[cfg(target_os = "freebsd")]
528         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
529         #[cfg(target_os = "freebsd")]
530         let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
531         #[cfg(not(target_os = "freebsd"))]
532         let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
533         if e == 0 {
534             let mut guardsize = 0;
535             assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
536             if guardsize == 0 {
537                 if cfg!(all(target_os = "linux", target_env = "musl")) {
538                     // musl versions before 1.1.19 always reported guard
539                     // size obtained from pthread_attr_get_np as zero.
540                     // Use page size as a fallback.
541                     guardsize = PAGE_SIZE.load(Ordering::Relaxed);
542                 } else {
543                     panic!("there is no guard page");
544                 }
545             }
546             let mut stackaddr = crate::ptr::null_mut();
547             let mut size = 0;
548             assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut size), 0);
549
550             let stackaddr = stackaddr as usize;
551             ret = if cfg!(any(target_os = "freebsd", target_os = "netbsd")) {
552                 Some(stackaddr - guardsize..stackaddr)
553             } else if cfg!(all(target_os = "linux", target_env = "musl")) {
554                 Some(stackaddr - guardsize..stackaddr)
555             } else if cfg!(all(target_os = "linux", target_env = "gnu")) {
556                 // glibc used to include the guard area within the stack, as noted in the BUGS
557                 // section of `man pthread_attr_getguardsize`.  This has been corrected starting
558                 // with glibc 2.27, and in some distro backports, so the guard is now placed at the
559                 // end (below) the stack.  There's no easy way for us to know which we have at
560                 // runtime, so we'll just match any fault in the range right above or below the
561                 // stack base to call that fault a stack overflow.
562                 Some(stackaddr - guardsize..stackaddr + guardsize)
563             } else {
564                 Some(stackaddr..stackaddr + guardsize)
565             };
566         }
567         if e == 0 || cfg!(target_os = "freebsd") {
568             assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
569         }
570         ret
571     }
572 }
573
574 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
575 // PTHREAD_STACK_MIN plus bytes needed for thread-local storage.
576 // We need that information to avoid blowing up when a small stack
577 // is created in an application with big thread-local storage requirements.
578 // See #6233 for rationale and details.
579 #[cfg(target_os = "linux")]
580 #[allow(deprecated)]
581 fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
582     weak!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);
583
584     match __pthread_get_minstack.get() {
585         None => libc::PTHREAD_STACK_MIN,
586         Some(f) => unsafe { f(attr) },
587     }
588 }
589
590 // No point in looking up __pthread_get_minstack() on non-glibc
591 // platforms.
592 #[cfg(all(not(target_os = "linux"), not(target_os = "netbsd")))]
593 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
594     libc::PTHREAD_STACK_MIN
595 }
596
597 #[cfg(target_os = "netbsd")]
598 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
599     2048 // just a guess
600 }