]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/thread.rs
Auto merge of #78605 - nox:relax-elf-relocations, r=nagisa
[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                 let ts_ptr = &mut ts as *mut _;
182                 if libc::nanosleep(ts_ptr, ts_ptr) == -1 {
183                     assert_eq!(os::errno(), libc::EINTR);
184                     secs += ts.tv_sec as u64;
185                     nsecs = ts.tv_nsec;
186                 } else {
187                     nsecs = 0;
188                 }
189             }
190         }
191     }
192
193     pub fn join(self) {
194         unsafe {
195             let ret = libc::pthread_join(self.id, ptr::null_mut());
196             mem::forget(self);
197             assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
198         }
199     }
200
201     pub fn id(&self) -> libc::pthread_t {
202         self.id
203     }
204
205     pub fn into_id(self) -> libc::pthread_t {
206         let id = self.id;
207         mem::forget(self);
208         id
209     }
210 }
211
212 impl Drop for Thread {
213     fn drop(&mut self) {
214         let ret = unsafe { libc::pthread_detach(self.id) };
215         debug_assert_eq!(ret, 0);
216     }
217 }
218
219 #[cfg(all(
220     not(target_os = "linux"),
221     not(target_os = "freebsd"),
222     not(target_os = "macos"),
223     not(all(target_os = "netbsd", not(target_vendor = "rumprun"))),
224     not(target_os = "openbsd"),
225     not(target_os = "solaris")
226 ))]
227 #[cfg_attr(test, allow(dead_code))]
228 pub mod guard {
229     use crate::ops::Range;
230     pub type Guard = Range<usize>;
231     pub unsafe fn current() -> Option<Guard> {
232         None
233     }
234     pub unsafe fn init() -> Option<Guard> {
235         None
236     }
237 }
238
239 #[cfg(any(
240     target_os = "linux",
241     target_os = "freebsd",
242     target_os = "macos",
243     all(target_os = "netbsd", not(target_vendor = "rumprun")),
244     target_os = "openbsd",
245     target_os = "solaris"
246 ))]
247 #[cfg_attr(test, allow(dead_code))]
248 pub mod guard {
249     use libc::{mmap, mprotect};
250     use libc::{MAP_ANON, MAP_FAILED, MAP_FIXED, MAP_PRIVATE, PROT_NONE, PROT_READ, PROT_WRITE};
251
252     use crate::ops::Range;
253     use crate::sync::atomic::{AtomicUsize, Ordering};
254     use crate::sys::os;
255
256     // This is initialized in init() and only read from after
257     static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0);
258
259     pub type Guard = Range<usize>;
260
261     #[cfg(target_os = "solaris")]
262     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
263         let mut current_stack: libc::stack_t = crate::mem::zeroed();
264         assert_eq!(libc::stack_getbounds(&mut current_stack), 0);
265         Some(current_stack.ss_sp)
266     }
267
268     #[cfg(target_os = "macos")]
269     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
270         let th = libc::pthread_self();
271         let stackaddr =
272             libc::pthread_get_stackaddr_np(th) as usize - libc::pthread_get_stacksize_np(th);
273         Some(stackaddr as *mut libc::c_void)
274     }
275
276     #[cfg(target_os = "openbsd")]
277     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
278         let mut current_stack: libc::stack_t = crate::mem::zeroed();
279         assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(), &mut current_stack), 0);
280
281         let stackaddr = if libc::pthread_main_np() == 1 {
282             // main thread
283             current_stack.ss_sp as usize - current_stack.ss_size + PAGE_SIZE.load(Ordering::Relaxed)
284         } else {
285             // new thread
286             current_stack.ss_sp as usize - current_stack.ss_size
287         };
288         Some(stackaddr as *mut libc::c_void)
289     }
290
291     #[cfg(any(
292         target_os = "android",
293         target_os = "freebsd",
294         target_os = "linux",
295         target_os = "netbsd",
296         target_os = "l4re"
297     ))]
298     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
299         let mut ret = None;
300         let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
301         #[cfg(target_os = "freebsd")]
302         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
303         #[cfg(target_os = "freebsd")]
304         let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
305         #[cfg(not(target_os = "freebsd"))]
306         let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
307         if e == 0 {
308             let mut stackaddr = crate::ptr::null_mut();
309             let mut stacksize = 0;
310             assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut stacksize), 0);
311             ret = Some(stackaddr);
312         }
313         if e == 0 || cfg!(target_os = "freebsd") {
314             assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
315         }
316         ret
317     }
318
319     // Precondition: PAGE_SIZE is initialized.
320     unsafe fn get_stack_start_aligned() -> Option<*mut libc::c_void> {
321         let page_size = PAGE_SIZE.load(Ordering::Relaxed);
322         assert!(page_size != 0);
323         let stackaddr = get_stack_start()?;
324
325         // Ensure stackaddr is page aligned! A parent process might
326         // have reset RLIMIT_STACK to be non-page aligned. The
327         // pthread_attr_getstack() reports the usable stack area
328         // stackaddr < stackaddr + stacksize, so if stackaddr is not
329         // page-aligned, calculate the fix such that stackaddr <
330         // new_page_aligned_stackaddr < stackaddr + stacksize
331         let remainder = (stackaddr as usize) % page_size;
332         Some(if remainder == 0 {
333             stackaddr
334         } else {
335             ((stackaddr as usize) + page_size - remainder) as *mut libc::c_void
336         })
337     }
338
339     pub unsafe fn init() -> Option<Guard> {
340         let page_size = os::page_size();
341         PAGE_SIZE.store(page_size, Ordering::Relaxed);
342
343         if cfg!(all(target_os = "linux", not(target_env = "musl"))) {
344             // Linux doesn't allocate the whole stack right away, and
345             // the kernel has its own stack-guard mechanism to fault
346             // when growing too close to an existing mapping.  If we map
347             // our own guard, then the kernel starts enforcing a rather
348             // large gap above that, rendering much of the possible
349             // stack space useless.  See #43052.
350             //
351             // Instead, we'll just note where we expect rlimit to start
352             // faulting, so our handler can report "stack overflow", and
353             // trust that the kernel's own stack guard will work.
354             let stackaddr = get_stack_start_aligned()?;
355             let stackaddr = stackaddr as usize;
356             Some(stackaddr - page_size..stackaddr)
357         } else if cfg!(all(target_os = "linux", target_env = "musl")) {
358             // For the main thread, the musl's pthread_attr_getstack
359             // returns the current stack size, rather than maximum size
360             // it can eventually grow to. It cannot be used to determine
361             // the position of kernel's stack guard.
362             None
363         } else {
364             // Reallocate the last page of the stack.
365             // This ensures SIGBUS will be raised on
366             // stack overflow.
367             // Systems which enforce strict PAX MPROTECT do not allow
368             // to mprotect() a mapping with less restrictive permissions
369             // than the initial mmap() used, so we mmap() here with
370             // read/write permissions and only then mprotect() it to
371             // no permissions at all. See issue #50313.
372             let stackaddr = get_stack_start_aligned()?;
373             let result = mmap(
374                 stackaddr,
375                 page_size,
376                 PROT_READ | PROT_WRITE,
377                 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
378                 -1,
379                 0,
380             );
381             if result != stackaddr || result == MAP_FAILED {
382                 panic!("failed to allocate a guard page");
383             }
384
385             let result = mprotect(stackaddr, page_size, PROT_NONE);
386             if result != 0 {
387                 panic!("failed to protect the guard page");
388             }
389
390             let guardaddr = stackaddr as usize;
391             let offset = if cfg!(target_os = "freebsd") { 2 } else { 1 };
392
393             Some(guardaddr..guardaddr + offset * page_size)
394         }
395     }
396
397     #[cfg(any(target_os = "macos", target_os = "openbsd", target_os = "solaris"))]
398     pub unsafe fn current() -> Option<Guard> {
399         let stackaddr = get_stack_start()? as usize;
400         Some(stackaddr - PAGE_SIZE.load(Ordering::Relaxed)..stackaddr)
401     }
402
403     #[cfg(any(
404         target_os = "android",
405         target_os = "freebsd",
406         target_os = "linux",
407         target_os = "netbsd",
408         target_os = "l4re"
409     ))]
410     pub unsafe fn current() -> Option<Guard> {
411         let mut ret = None;
412         let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
413         #[cfg(target_os = "freebsd")]
414         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
415         #[cfg(target_os = "freebsd")]
416         let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
417         #[cfg(not(target_os = "freebsd"))]
418         let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
419         if e == 0 {
420             let mut guardsize = 0;
421             assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
422             if guardsize == 0 {
423                 if cfg!(all(target_os = "linux", target_env = "musl")) {
424                     // musl versions before 1.1.19 always reported guard
425                     // size obtained from pthread_attr_get_np as zero.
426                     // Use page size as a fallback.
427                     guardsize = PAGE_SIZE.load(Ordering::Relaxed);
428                 } else {
429                     panic!("there is no guard page");
430                 }
431             }
432             let mut stackaddr = crate::ptr::null_mut();
433             let mut size = 0;
434             assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut size), 0);
435
436             let stackaddr = stackaddr as usize;
437             ret = if cfg!(target_os = "freebsd") {
438                 // FIXME does freebsd really fault *below* the guard addr?
439                 let guardaddr = stackaddr - guardsize;
440                 Some(guardaddr - PAGE_SIZE.load(Ordering::Relaxed)..guardaddr)
441             } else if cfg!(target_os = "netbsd") {
442                 Some(stackaddr - guardsize..stackaddr)
443             } else if cfg!(all(target_os = "linux", target_env = "musl")) {
444                 Some(stackaddr - guardsize..stackaddr)
445             } else if cfg!(all(target_os = "linux", target_env = "gnu")) {
446                 // glibc used to include the guard area within the stack, as noted in the BUGS
447                 // section of `man pthread_attr_getguardsize`.  This has been corrected starting
448                 // with glibc 2.27, and in some distro backports, so the guard is now placed at the
449                 // end (below) the stack.  There's no easy way for us to know which we have at
450                 // runtime, so we'll just match any fault in the range right above or below the
451                 // stack base to call that fault a stack overflow.
452                 Some(stackaddr - guardsize..stackaddr + guardsize)
453             } else {
454                 Some(stackaddr..stackaddr + guardsize)
455             };
456         }
457         if e == 0 || cfg!(target_os = "freebsd") {
458             assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
459         }
460         ret
461     }
462 }
463
464 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
465 // PTHREAD_STACK_MIN plus bytes needed for thread-local storage.
466 // We need that information to avoid blowing up when a small stack
467 // is created in an application with big thread-local storage requirements.
468 // See #6233 for rationale and details.
469 #[cfg(target_os = "linux")]
470 #[allow(deprecated)]
471 fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
472     weak!(fn __pthread_get_minstack(*const libc::pthread_attr_t) -> libc::size_t);
473
474     match __pthread_get_minstack.get() {
475         None => libc::PTHREAD_STACK_MIN,
476         Some(f) => unsafe { f(attr) },
477     }
478 }
479
480 // No point in looking up __pthread_get_minstack() on non-glibc
481 // platforms.
482 #[cfg(all(not(target_os = "linux"), not(target_os = "netbsd")))]
483 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
484     libc::PTHREAD_STACK_MIN
485 }
486
487 #[cfg(target_os = "netbsd")]
488 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
489     2048 // just a guess
490 }