7 use crate::time::Duration;
9 use crate::sys_common::thread::*;
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;
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 {}
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)
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 {
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> {
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);
48 let stack_size = cmp::max(stack, min_stack_size(&attr));
50 match pthread_attr_setstacksize(&mut attr,
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,
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);
72 Err(io::Error::from_raw_os_error(ret))
74 mem::forget(p); // ownership passed to pthread_create
75 Ok(Thread { id: native })
78 extern fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
79 unsafe { start_thread(main as *mut u8); }
85 let ret = unsafe { libc::sched_yield() };
86 debug_assert_eq!(ret, 0);
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
96 libc::prctl(PR_SET_NAME, name.as_ptr() as libc::c_ulong, 0, 0, 0);
100 #[cfg(any(target_os = "freebsd",
101 target_os = "dragonfly",
102 target_os = "openbsd"))]
103 pub fn set_name(name: &CStr) {
105 libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
109 #[cfg(any(target_os = "macos", target_os = "ios"))]
110 pub fn set_name(name: &CStr) {
112 libc::pthread_setname_np(name.as_ptr());
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();
121 libc::pthread_setname_np(libc::pthread_self(), cname.as_ptr(),
122 name.as_ptr() as *mut libc::c_void);
126 #[cfg(target_os = "solaris")]
127 pub fn set_name(name: &CStr) {
129 fn pthread_setname_np(
130 libc::pthread_t, *const libc::c_char
134 if let Some(f) = pthread_setname_np.get() {
135 unsafe { f(libc::pthread_self(), name.as_ptr()); }
139 #[cfg(any(target_env = "newlib",
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.
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.
153 pub fn sleep(dur: Duration) {
154 let mut secs = dur.as_secs();
155 let mut nsecs = dur.subsec_nanos() as _;
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.
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,
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;
179 let ret = libc::pthread_join(self.id, ptr::null_mut());
182 "failed to join thread: {}", io::Error::from_raw_os_error(ret));
186 pub fn id(&self) -> libc::pthread_t { self.id }
188 pub fn into_id(self) -> libc::pthread_t {
195 impl Drop for Thread {
197 let ret = unsafe { libc::pthread_detach(self.id) };
198 debug_assert_eq!(ret, 0);
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))]
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 }
217 #[cfg(any(all(target_os = "linux", not(target_env = "musl")),
218 target_os = "freebsd",
220 all(target_os = "netbsd", not(target_vendor = "rumprun")),
221 target_os = "openbsd",
222 target_os = "solaris"))]
223 #[cfg_attr(test, allow(dead_code))]
225 use libc::{mmap, mprotect};
226 use libc::{PROT_NONE, PROT_READ, PROT_WRITE, MAP_PRIVATE, MAP_ANON, MAP_FAILED, MAP_FIXED};
228 use crate::ops::Range;
231 // This is initialized in init() and only read from after
232 static mut PAGE_SIZE: usize = 0;
234 pub type Guard = Range<usize>;
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)
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)
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);
256 let stackaddr = if libc::pthread_main_np() == 1 {
258 current_stack.ss_sp as usize - current_stack.ss_size + PAGE_SIZE
261 current_stack.ss_sp as usize - current_stack.ss_size
263 Some(stackaddr as *mut libc::c_void)
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> {
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);
277 let mut stackaddr = crate::ptr::null_mut();
278 let mut stacksize = 0;
279 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
281 ret = Some(stackaddr);
283 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
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()?;
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 {
302 ((stackaddr as usize) + PAGE_SIZE - remainder) as *mut libc::c_void
306 pub unsafe fn init() -> Option<Guard> {
307 PAGE_SIZE = os::page_size();
309 let stackaddr = get_stack_start_aligned()?;
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.
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)
325 // Reallocate the last page of the stack.
326 // This ensures SIGBUS will be raised on
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");
339 let result = mprotect(stackaddr, PAGE_SIZE, PROT_NONE);
341 panic!("failed to protect the guard page");
344 let guardaddr = stackaddr as usize;
345 let offset = if cfg!(target_os = "freebsd") {
351 Some(guardaddr..guardaddr + offset * PAGE_SIZE)
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)
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> {
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);
374 let mut guardsize = 0;
375 assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
377 panic!("there is no guard page");
379 let mut stackaddr = crate::ptr::null_mut();
381 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
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)
400 Some(stackaddr..stackaddr + guardsize)
403 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
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")]
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);
418 match __pthread_get_minstack.get() {
419 None => libc::PTHREAD_STACK_MIN,
420 Some(f) => unsafe { f(attr) },
424 // No point in looking up __pthread_get_minstack() on non-glibc
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
432 #[cfg(target_os = "netbsd")]
433 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {