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