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