]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/thread.rs
Rollup merge of #76635 - scottmcm:slice-as-chunks, r=LukasKalbertodt
[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::ptr;
6 use crate::sys::{os, stack_overflow};
7 use crate::time::Duration;
8
9 #[cfg(not(any(target_os = "l4re", target_os = "vxworks")))]
10 pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
11 #[cfg(target_os = "l4re")]
12 pub const DEFAULT_MIN_STACK_SIZE: usize = 1024 * 1024;
13 #[cfg(target_os = "vxworks")]
14 pub const DEFAULT_MIN_STACK_SIZE: usize = 256 * 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(
29     attr: *mut libc::pthread_attr_t,
30     stack_size: libc::size_t,
31 ) -> libc::c_int {
32     libc::pthread_attr_setstacksize(attr, stack_size)
33 }
34
35 #[cfg(target_os = "emscripten")]
36 unsafe fn pthread_attr_setstacksize(
37     _attr: *mut libc::pthread_attr_t,
38     _stack_size: libc::size_t,
39 ) -> libc::c_int {
40     panic!()
41 }
42
43 impl Thread {
44     // unsafe: see thread::Builder::spawn_unchecked for safety requirements
45     pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
46         let p = Box::into_raw(box p);
47         let mut native: libc::pthread_t = mem::zeroed();
48         let mut attr: libc::pthread_attr_t = mem::zeroed();
49         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
50
51         let stack_size = cmp::max(stack, min_stack_size(&attr));
52
53         match pthread_attr_setstacksize(&mut attr, stack_size) {
54             0 => {}
55             n => {
56                 assert_eq!(n, libc::EINVAL);
57                 // EINVAL means |stack_size| is either too small or not a
58                 // multiple of the system page size.  Because it's definitely
59                 // >= PTHREAD_STACK_MIN, it must be an alignment issue.
60                 // Round up to the nearest page and try again.
61                 let page_size = os::page_size();
62                 let stack_size =
63                     (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1);
64                 assert_eq!(libc::pthread_attr_setstacksize(&mut attr, stack_size), 0);
65             }
66         };
67
68         let ret = libc::pthread_create(&mut native, &attr, thread_start, p as *mut _);
69         // Note: if the thread creation fails and this assert fails, then p will
70         // be leaked. However, an alternative design could cause double-free
71         // which is clearly worse.
72         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
73
74         return if ret != 0 {
75             // The thread failed to start and as a result p was not consumed. Therefore, it is
76             // safe to reconstruct the box so that it gets deallocated.
77             drop(Box::from_raw(p));
78             Err(io::Error::from_raw_os_error(ret))
79         } else {
80             Ok(Thread { id: native })
81         };
82
83         extern "C" fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
84             unsafe {
85                 // Next, set up our stack overflow handler which may get triggered if we run
86                 // out of stack.
87                 let _handler = stack_overflow::Handler::new();
88                 // Finally, let's run some code.
89                 Box::from_raw(main as *mut Box<dyn FnOnce()>)();
90             }
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", target_os = "android"))]
101     pub fn set_name(name: &CStr) {
102         const PR_SET_NAME: libc::c_int = 15;
103         // pthread wrapper only appeared in glibc 2.12, so we use syscall
104         // directly.
105         unsafe {
106             libc::prctl(PR_SET_NAME, name.as_ptr() as libc::c_ulong, 0, 0, 0);
107         }
108     }
109
110     #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd"))]
111     pub fn set_name(name: &CStr) {
112         unsafe {
113             libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
114         }
115     }
116
117     #[cfg(any(target_os = "macos", target_os = "ios"))]
118     pub fn set_name(name: &CStr) {
119         unsafe {
120             libc::pthread_setname_np(name.as_ptr());
121         }
122     }
123
124     #[cfg(target_os = "netbsd")]
125     pub fn set_name(name: &CStr) {
126         use crate::ffi::CString;
127         let cname = CString::new(&b"%s"[..]).unwrap();
128         unsafe {
129             libc::pthread_setname_np(
130                 libc::pthread_self(),
131                 cname.as_ptr(),
132                 name.as_ptr() as *mut libc::c_void,
133             );
134         }
135     }
136
137     #[cfg(any(target_os = "solaris", target_os = "illumos"))]
138     pub fn set_name(name: &CStr) {
139         weak! {
140             fn pthread_setname_np(
141                 libc::pthread_t, *const libc::c_char
142             ) -> libc::c_int
143         }
144
145         if let Some(f) = pthread_setname_np.get() {
146             unsafe {
147                 f(libc::pthread_self(), name.as_ptr());
148             }
149         }
150     }
151
152     #[cfg(any(
153         target_env = "newlib",
154         target_os = "haiku",
155         target_os = "l4re",
156         target_os = "emscripten",
157         target_os = "redox",
158         target_os = "vxworks"
159     ))]
160     pub fn set_name(_name: &CStr) {
161         // Newlib, Haiku, Emscripten, and VxWorks have no way to set a thread name.
162     }
163     #[cfg(target_os = "fuchsia")]
164     pub fn set_name(_name: &CStr) {
165         // FIXME: determine whether Fuchsia has a way to set a thread name.
166     }
167
168     pub fn sleep(dur: Duration) {
169         let mut secs = dur.as_secs();
170         let mut nsecs = dur.subsec_nanos() as _;
171
172         // If we're awoken with a signal then the return value will be -1 and
173         // nanosleep will fill in `ts` with the remaining time.
174         unsafe {
175             while secs > 0 || nsecs > 0 {
176                 let mut ts = libc::timespec {
177                     tv_sec: cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t,
178                     tv_nsec: nsecs,
179                 };
180                 secs -= ts.tv_sec as u64;
181                 if libc::nanosleep(&ts, &mut ts) == -1 {
182                     assert_eq!(os::errno(), libc::EINTR);
183                     secs += ts.tv_sec as u64;
184                     nsecs = ts.tv_nsec;
185                 } else {
186                     nsecs = 0;
187                 }
188             }
189         }
190     }
191
192     pub fn join(self) {
193         unsafe {
194             let ret = libc::pthread_join(self.id, ptr::null_mut());
195             mem::forget(self);
196             assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
197         }
198     }
199
200     pub fn id(&self) -> libc::pthread_t {
201         self.id
202     }
203
204     pub fn into_id(self) -> libc::pthread_t {
205         let id = self.id;
206         mem::forget(self);
207         id
208     }
209 }
210
211 impl Drop for Thread {
212     fn drop(&mut self) {
213         let ret = unsafe { libc::pthread_detach(self.id) };
214         debug_assert_eq!(ret, 0);
215     }
216 }
217
218 #[cfg(all(
219     not(target_os = "linux"),
220     not(target_os = "freebsd"),
221     not(target_os = "macos"),
222     not(all(target_os = "netbsd", not(target_vendor = "rumprun"))),
223     not(target_os = "openbsd"),
224     not(target_os = "solaris")
225 ))]
226 #[cfg_attr(test, allow(dead_code))]
227 pub mod guard {
228     use crate::ops::Range;
229     pub type Guard = Range<usize>;
230     pub unsafe fn current() -> Option<Guard> {
231         None
232     }
233     pub unsafe fn init() -> Option<Guard> {
234         None
235     }
236 }
237
238 #[cfg(any(
239     target_os = "linux",
240     target_os = "freebsd",
241     target_os = "macos",
242     all(target_os = "netbsd", not(target_vendor = "rumprun")),
243     target_os = "openbsd",
244     target_os = "solaris"
245 ))]
246 #[cfg_attr(test, allow(dead_code))]
247 pub mod guard {
248     use libc::{mmap, mprotect};
249     use libc::{MAP_ANON, MAP_FAILED, MAP_FIXED, MAP_PRIVATE, PROT_NONE, PROT_READ, PROT_WRITE};
250
251     use crate::ops::Range;
252     use crate::sync::atomic::{AtomicUsize, Ordering};
253     use crate::sys::os;
254
255     // This is initialized in init() and only read from after
256     static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0);
257
258     pub type Guard = Range<usize>;
259
260     #[cfg(target_os = "solaris")]
261     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
262         let mut current_stack: libc::stack_t = crate::mem::zeroed();
263         assert_eq!(libc::stack_getbounds(&mut current_stack), 0);
264         Some(current_stack.ss_sp)
265     }
266
267     #[cfg(target_os = "macos")]
268     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
269         let th = libc::pthread_self();
270         let stackaddr =
271             libc::pthread_get_stackaddr_np(th) as usize - libc::pthread_get_stacksize_np(th);
272         Some(stackaddr as *mut libc::c_void)
273     }
274
275     #[cfg(target_os = "openbsd")]
276     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
277         let mut current_stack: libc::stack_t = crate::mem::zeroed();
278         assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(), &mut current_stack), 0);
279
280         let stackaddr = if libc::pthread_main_np() == 1 {
281             // main thread
282             current_stack.ss_sp as usize - current_stack.ss_size + PAGE_SIZE.load(Ordering::Relaxed)
283         } else {
284             // new thread
285             current_stack.ss_sp as usize - current_stack.ss_size
286         };
287         Some(stackaddr as *mut libc::c_void)
288     }
289
290     #[cfg(any(
291         target_os = "android",
292         target_os = "freebsd",
293         target_os = "linux",
294         target_os = "netbsd",
295         target_os = "l4re"
296     ))]
297     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
298         let mut ret = None;
299         let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
300         #[cfg(target_os = "freebsd")]
301         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
302         #[cfg(target_os = "freebsd")]
303         let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
304         #[cfg(not(target_os = "freebsd"))]
305         let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
306         if e == 0 {
307             let mut stackaddr = crate::ptr::null_mut();
308             let mut stacksize = 0;
309             assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut stacksize), 0);
310             ret = Some(stackaddr);
311         }
312         if e == 0 || cfg!(target_os = "freebsd") {
313             assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
314         }
315         ret
316     }
317
318     // Precondition: PAGE_SIZE is initialized.
319     unsafe fn get_stack_start_aligned() -> Option<*mut libc::c_void> {
320         let page_size = PAGE_SIZE.load(Ordering::Relaxed);
321         assert!(page_size != 0);
322         let stackaddr = get_stack_start()?;
323
324         // Ensure stackaddr is page aligned! A parent process might
325         // have reset RLIMIT_STACK to be non-page aligned. The
326         // pthread_attr_getstack() reports the usable stack area
327         // stackaddr < stackaddr + stacksize, so if stackaddr is not
328         // page-aligned, calculate the fix such that stackaddr <
329         // new_page_aligned_stackaddr < stackaddr + stacksize
330         let remainder = (stackaddr as usize) % page_size;
331         Some(if remainder == 0 {
332             stackaddr
333         } else {
334             ((stackaddr as usize) + page_size - remainder) as *mut libc::c_void
335         })
336     }
337
338     pub unsafe fn init() -> Option<Guard> {
339         let page_size = os::page_size();
340         PAGE_SIZE.store(page_size, Ordering::Relaxed);
341
342         if cfg!(all(target_os = "linux", not(target_env = "musl"))) {
343             // Linux doesn't allocate the whole stack right away, and
344             // the kernel has its own stack-guard mechanism to fault
345             // when growing too close to an existing mapping.  If we map
346             // our own guard, then the kernel starts enforcing a rather
347             // large gap above that, rendering much of the possible
348             // stack space useless.  See #43052.
349             //
350             // Instead, we'll just note where we expect rlimit to start
351             // faulting, so our handler can report "stack overflow", and
352             // trust that the kernel's own stack guard will work.
353             let stackaddr = get_stack_start_aligned()?;
354             let stackaddr = stackaddr as usize;
355             Some(stackaddr - page_size..stackaddr)
356         } else if cfg!(all(target_os = "linux", target_env = "musl")) {
357             // For the main thread, the musl's pthread_attr_getstack
358             // returns the current stack size, rather than maximum size
359             // it can eventually grow to. It cannot be used to determine
360             // the position of kernel's stack guard.
361             None
362         } else {
363             // Reallocate the last page of the stack.
364             // This ensures SIGBUS will be raised on
365             // stack overflow.
366             // Systems which enforce strict PAX MPROTECT do not allow
367             // to mprotect() a mapping with less restrictive permissions
368             // than the initial mmap() used, so we mmap() here with
369             // read/write permissions and only then mprotect() it to
370             // no permissions at all. See issue #50313.
371             let stackaddr = get_stack_start_aligned()?;
372             let result = mmap(
373                 stackaddr,
374                 page_size,
375                 PROT_READ | PROT_WRITE,
376                 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
377                 -1,
378                 0,
379             );
380             if result != stackaddr || result == MAP_FAILED {
381                 panic!("failed to allocate a guard page");
382             }
383
384             let result = mprotect(stackaddr, page_size, PROT_NONE);
385             if result != 0 {
386                 panic!("failed to protect the guard page");
387             }
388
389             let guardaddr = stackaddr as usize;
390             let offset = if cfg!(target_os = "freebsd") { 2 } else { 1 };
391
392             Some(guardaddr..guardaddr + offset * page_size)
393         }
394     }
395
396     #[cfg(any(target_os = "macos", target_os = "openbsd", target_os = "solaris"))]
397     pub unsafe fn current() -> Option<Guard> {
398         let stackaddr = get_stack_start()? as usize;
399         Some(stackaddr - PAGE_SIZE.load(Ordering::Relaxed)..stackaddr)
400     }
401
402     #[cfg(any(
403         target_os = "android",
404         target_os = "freebsd",
405         target_os = "linux",
406         target_os = "netbsd",
407         target_os = "l4re"
408     ))]
409     pub unsafe fn current() -> Option<Guard> {
410         let mut ret = None;
411         let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
412         #[cfg(target_os = "freebsd")]
413         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
414         #[cfg(target_os = "freebsd")]
415         let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
416         #[cfg(not(target_os = "freebsd"))]
417         let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
418         if e == 0 {
419             let mut guardsize = 0;
420             assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
421             if guardsize == 0 {
422                 if cfg!(all(target_os = "linux", target_env = "musl")) {
423                     // musl versions before 1.1.19 always reported guard
424                     // size obtained from pthread_attr_get_np as zero.
425                     // Use page size as a fallback.
426                     guardsize = PAGE_SIZE.load(Ordering::Relaxed);
427                 } else {
428                     panic!("there is no guard page");
429                 }
430             }
431             let mut stackaddr = crate::ptr::null_mut();
432             let mut size = 0;
433             assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut size), 0);
434
435             let stackaddr = stackaddr as usize;
436             ret = if cfg!(target_os = "freebsd") {
437                 // FIXME does freebsd really fault *below* the guard addr?
438                 let guardaddr = stackaddr - guardsize;
439                 Some(guardaddr - PAGE_SIZE.load(Ordering::Relaxed)..guardaddr)
440             } else if cfg!(target_os = "netbsd") {
441                 Some(stackaddr - guardsize..stackaddr)
442             } else if cfg!(all(target_os = "linux", target_env = "musl")) {
443                 Some(stackaddr - guardsize..stackaddr)
444             } else if cfg!(all(target_os = "linux", target_env = "gnu")) {
445                 // glibc used to include the guard area within the stack, as noted in the BUGS
446                 // section of `man pthread_attr_getguardsize`.  This has been corrected starting
447                 // with glibc 2.27, and in some distro backports, so the guard is now placed at the
448                 // end (below) the stack.  There's no easy way for us to know which we have at
449                 // runtime, so we'll just match any fault in the range right above or below the
450                 // stack base to call that fault a stack overflow.
451                 Some(stackaddr - guardsize..stackaddr + guardsize)
452             } else {
453                 Some(stackaddr..stackaddr + guardsize)
454             };
455         }
456         if e == 0 || cfg!(target_os = "freebsd") {
457             assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
458         }
459         ret
460     }
461 }
462
463 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
464 // PTHREAD_STACK_MIN plus bytes needed for thread-local storage.
465 // We need that information to avoid blowing up when a small stack
466 // is created in an application with big thread-local storage requirements.
467 // See #6233 for rationale and details.
468 #[cfg(target_os = "linux")]
469 #[allow(deprecated)]
470 fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
471     weak!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);
472
473     match __pthread_get_minstack.get() {
474         None => libc::PTHREAD_STACK_MIN,
475         Some(f) => unsafe { f(attr) },
476     }
477 }
478
479 // No point in looking up __pthread_get_minstack() on non-glibc
480 // platforms.
481 #[cfg(all(not(target_os = "linux"), not(target_os = "netbsd")))]
482 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
483     libc::PTHREAD_STACK_MIN
484 }
485
486 #[cfg(target_os = "netbsd")]
487 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
488     2048 // just a guess
489 }