1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use alloc
::boxed
::FnBox
;
21 use sys_common
::thread
::*;
23 #[cfg(not(target_os = "l4re"))]
24 pub const DEFAULT_MIN_STACK_SIZE
: usize = 2 * 1024 * 1024;
25 #[cfg(target_os = "l4re")]
26 pub const DEFAULT_MIN_STACK_SIZE
: usize = 1024 * 1024;
32 // Some platforms may have pthread_t as a pointer in which case we still want
33 // a thread to be Send/Sync
34 unsafe impl Send
for Thread {}
35 unsafe impl Sync
for Thread {}
37 // The pthread_attr_setstacksize symbol doesn't exist in the emscripten libc,
38 // so we have to not link to it to satisfy emcc's ERROR_ON_UNDEFINED_SYMBOLS.
39 #[cfg(not(target_os = "emscripten"))]
40 unsafe fn pthread_attr_setstacksize(attr
: *mut libc
::pthread_attr_t
,
41 stack_size
: libc
::size_t
) -> libc
::c_int
{
42 libc
::pthread_attr_setstacksize(attr
, stack_size
)
45 #[cfg(target_os = "emscripten")]
46 unsafe fn pthread_attr_setstacksize(_attr
: *mut libc
::pthread_attr_t
,
47 _stack_size
: libc
::size_t
) -> libc
::c_int
{
52 pub unsafe fn new
<'a
>(stack
: usize, p
: Box
<FnBox() + 'a
>)
53 -> io
::Result
<Thread
> {
55 let mut native
: libc
::pthread_t
= mem
::zeroed();
56 let mut attr
: libc
::pthread_attr_t
= mem
::zeroed();
57 assert_eq
!(libc
::pthread_attr_init(&mut attr
), 0);
59 let stack_size
= cmp
::max(stack
, min_stack_size(&attr
));
61 match pthread_attr_setstacksize(&mut attr
,
65 assert_eq
!(n
, libc
::EINVAL
);
66 // EINVAL means |stack_size| is either too small or not a
67 // multiple of the system page size. Because it's definitely
68 // >= PTHREAD_STACK_MIN, it must be an alignment issue.
69 // Round up to the nearest page and try again.
70 let page_size
= os
::page_size();
71 let stack_size
= (stack_size
+ page_size
- 1) &
72 (-(page_size
as isize - 1) as usize - 1);
73 assert_eq
!(libc
::pthread_attr_setstacksize(&mut attr
,
78 let ret
= libc
::pthread_create(&mut native
, &attr
, thread_start
,
79 &*p
as *const _
as *mut _
);
80 assert_eq
!(libc
::pthread_attr_destroy(&mut attr
), 0);
83 Err(io
::Error
::from_raw_os_error(ret
))
85 mem
::forget(p
); // ownership passed to pthread_create
86 Ok(Thread { id: native }
)
89 extern fn thread_start(main
: *mut libc
::c_void
) -> *mut libc
::c_void
{
90 unsafe { start_thread(main as *mut u8); }
96 let ret
= unsafe { libc::sched_yield() }
;
97 debug_assert_eq
!(ret
, 0);
100 #[cfg(any(target_os = "linux",
101 target_os
= "android"))]
102 pub fn set_name(name
: &CStr
) {
103 const PR_SET_NAME
: libc
::c_int
= 15;
104 // pthread wrapper only appeared in glibc 2.12, so we use syscall
107 libc
::prctl(PR_SET_NAME
, name
.as_ptr() as libc
::c_ulong
, 0, 0, 0);
111 #[cfg(any(target_os = "freebsd",
112 target_os
= "dragonfly",
113 target_os
= "bitrig",
114 target_os
= "openbsd"))]
115 pub fn set_name(name
: &CStr
) {
117 libc
::pthread_set_name_np(libc
::pthread_self(), name
.as_ptr());
121 #[cfg(any(target_os = "macos", target_os = "ios"))]
122 pub fn set_name(name
: &CStr
) {
124 libc
::pthread_setname_np(name
.as_ptr());
128 #[cfg(target_os = "netbsd")]
129 pub fn set_name(name
: &CStr
) {
131 let cname
= CString
::new(&b
"%s"[..]).unwrap();
133 libc
::pthread_setname_np(libc
::pthread_self(), cname
.as_ptr(),
134 name
.as_ptr() as *mut libc
::c_void
);
137 #[cfg(any(target_env = "newlib",
138 target_os
= "solaris",
141 target_os
= "emscripten"))]
142 pub fn set_name(_name
: &CStr
) {
143 // Newlib, Illumos, Haiku, and Emscripten have no way to set a thread name.
145 #[cfg(target_os = "fuchsia")]
146 pub fn set_name(_name
: &CStr
) {
147 // FIXME: determine whether Fuchsia has a way to set a thread name.
150 pub fn sleep(dur
: Duration
) {
151 let mut secs
= dur
.as_secs();
152 let mut nsecs
= dur
.subsec_nanos() as _
;
154 // If we're awoken with a signal then the return value will be -1 and
155 // nanosleep will fill in `ts` with the remaining time.
157 while secs
> 0 || nsecs
> 0 {
158 let mut ts
= libc
::timespec
{
159 tv_sec
: cmp
::min(libc
::time_t
::max_value() as u64, secs
) as libc
::time_t
,
162 secs
-= ts
.tv_sec
as u64;
163 if libc
::nanosleep(&ts
, &mut ts
) == -1 {
164 assert_eq
!(os
::errno(), libc
::EINTR
);
165 secs
+= ts
.tv_sec
as u64;
176 let ret
= libc
::pthread_join(self.id
, ptr
::null_mut());
179 "failed to join thread: {}", io
::Error
::from_raw_os_error(ret
));
183 pub fn id(&self) -> libc
::pthread_t { self.id }
185 pub fn into_id(self) -> libc
::pthread_t
{
192 impl Drop
for Thread
{
194 let ret
= unsafe { libc::pthread_detach(self.id) }
;
195 debug_assert_eq
!(ret
, 0);
199 #[cfg(all(not(all(target_os = "linux", not(target_env = "musl"))),
200 not(target_os
= "freebsd"),
201 not(target_os
= "macos"),
202 not(target_os
= "bitrig"),
203 not(all(target_os
= "netbsd", not(target_vendor
= "rumprun"))),
204 not(target_os
= "openbsd"),
205 not(target_os
= "solaris")))]
206 #[cfg_attr(test, allow(dead_code))]
208 pub unsafe fn current() -> Option
<usize> { None }
209 pub unsafe fn init() -> Option
<usize> { None }
213 #[cfg(any(all(target_os = "linux", not(target_env = "musl")),
214 target_os
= "freebsd",
216 target_os
= "bitrig",
217 all(target_os
= "netbsd", not(target_vendor
= "rumprun")),
218 target_os
= "openbsd",
219 target_os
= "solaris"))]
220 #[cfg_attr(test, allow(dead_code))]
224 use libc
::{PROT_NONE, MAP_PRIVATE, MAP_ANON, MAP_FAILED, MAP_FIXED}
;
227 #[cfg(any(target_os = "macos",
228 target_os
= "bitrig",
229 target_os
= "openbsd",
230 target_os
= "solaris"))]
231 unsafe fn get_stack_start() -> Option
<*mut libc
::c_void
> {
232 current().map(|s
| s
as *mut libc
::c_void
)
235 #[cfg(any(target_os = "android", target_os = "freebsd",
236 target_os
= "linux", target_os
= "netbsd", target_os
= "l4re"))]
237 unsafe fn get_stack_start() -> Option
<*mut libc
::c_void
> {
239 let mut attr
: libc
::pthread_attr_t
= ::mem
::zeroed();
240 assert_eq
!(libc
::pthread_attr_init(&mut attr
), 0);
241 #[cfg(target_os = "freebsd")]
242 let e
= libc
::pthread_attr_get_np(libc
::pthread_self(), &mut attr
);
243 #[cfg(not(target_os = "freebsd"))]
244 let e
= libc
::pthread_getattr_np(libc
::pthread_self(), &mut attr
);
246 let mut stackaddr
= ::ptr
::null_mut();
247 let mut stacksize
= 0;
248 assert_eq
!(libc
::pthread_attr_getstack(&attr
, &mut stackaddr
,
250 ret
= Some(stackaddr
);
252 assert_eq
!(libc
::pthread_attr_destroy(&mut attr
), 0);
256 pub unsafe fn init() -> Option
<usize> {
257 let psize
= os
::page_size();
258 let mut stackaddr
= match get_stack_start() {
263 // Ensure stackaddr is page aligned! A parent process might
264 // have reset RLIMIT_STACK to be non-page aligned. The
265 // pthread_attr_getstack() reports the usable stack area
266 // stackaddr < stackaddr + stacksize, so if stackaddr is not
267 // page-aligned, calculate the fix such that stackaddr <
268 // new_page_aligned_stackaddr < stackaddr + stacksize
269 let remainder
= (stackaddr
as usize) % psize
;
271 stackaddr
= ((stackaddr
as usize) + psize
- remainder
)
272 as *mut libc
::c_void
;
275 if cfg
!(target_os
= "linux") {
276 // Linux doesn't allocate the whole stack right away, and
277 // the kernel has its own stack-guard mechanism to fault
278 // when growing too close to an existing mapping. If we map
279 // our own guard, then the kernel starts enforcing a rather
280 // large gap above that, rendering much of the possible
281 // stack space useless. See #43052.
283 // Instead, we'll just note where we expect rlimit to start
284 // faulting, so our handler can report "stack overflow", and
285 // trust that the kernel's own stack guard will work.
286 Some(stackaddr
as usize)
288 // Reallocate the last page of the stack.
289 // This ensures SIGBUS will be raised on
291 let result
= mmap(stackaddr
, psize
, PROT_NONE
,
292 MAP_PRIVATE
| MAP_ANON
| MAP_FIXED
, -1, 0);
294 if result
!= stackaddr
|| result
== MAP_FAILED
{
295 panic
!("failed to allocate a guard page");
298 let offset
= if cfg
!(target_os
= "freebsd") {
304 Some(stackaddr
as usize + offset
* psize
)
308 #[cfg(target_os = "solaris")]
309 pub unsafe fn current() -> Option
<usize> {
310 let mut current_stack
: libc
::stack_t
= ::mem
::zeroed();
311 assert_eq
!(libc
::stack_getbounds(&mut current_stack
), 0);
312 Some(current_stack
.ss_sp
as usize)
315 #[cfg(target_os = "macos")]
316 pub unsafe fn current() -> Option
<usize> {
317 Some((libc
::pthread_get_stackaddr_np(libc
::pthread_self()) as usize -
318 libc
::pthread_get_stacksize_np(libc
::pthread_self())))
321 #[cfg(any(target_os = "openbsd", target_os = "bitrig"))]
322 pub unsafe fn current() -> Option
<usize> {
323 let mut current_stack
: libc
::stack_t
= ::mem
::zeroed();
324 assert_eq
!(libc
::pthread_stackseg_np(libc
::pthread_self(),
325 &mut current_stack
), 0);
327 let extra
= if cfg
!(target_os
= "bitrig") {3}
else {1}
* os
::page_size();
328 Some(if libc
::pthread_main_np() == 1 {
330 current_stack
.ss_sp
as usize - current_stack
.ss_size
+ extra
333 current_stack
.ss_sp
as usize - current_stack
.ss_size
337 #[cfg(any(target_os = "android", target_os = "freebsd",
338 target_os
= "linux", target_os
= "netbsd", target_os
= "l4re"))]
339 pub unsafe fn current() -> Option
<usize> {
341 let mut attr
: libc
::pthread_attr_t
= ::mem
::zeroed();
342 assert_eq
!(libc
::pthread_attr_init(&mut attr
), 0);
343 #[cfg(target_os = "freebsd")]
344 let e
= libc
::pthread_attr_get_np(libc
::pthread_self(), &mut attr
);
345 #[cfg(not(target_os = "freebsd"))]
346 let e
= libc
::pthread_getattr_np(libc
::pthread_self(), &mut attr
);
348 let mut guardsize
= 0;
349 assert_eq
!(libc
::pthread_attr_getguardsize(&attr
, &mut guardsize
), 0);
351 panic
!("there is no guard page");
353 let mut stackaddr
= ::ptr
::null_mut();
355 assert_eq
!(libc
::pthread_attr_getstack(&attr
, &mut stackaddr
,
358 ret
= if cfg
!(target_os
= "freebsd") {
359 Some(stackaddr
as usize - guardsize
)
360 } else if cfg
!(target_os
= "netbsd") {
361 Some(stackaddr
as usize)
363 Some(stackaddr
as usize + guardsize
)
366 assert_eq
!(libc
::pthread_attr_destroy(&mut attr
), 0);
371 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
372 // PTHREAD_STACK_MIN plus however many bytes are needed for thread-local
373 // storage. We need that information to avoid blowing up when a small stack
374 // is created in an application with big thread-local storage requirements.
375 // See #6233 for rationale and details.
376 #[cfg(target_os = "linux")]
378 fn min_stack_size(attr
: *const libc
::pthread_attr_t
) -> usize {
379 weak
!(fn __pthread_get_minstack(*const libc
::pthread_attr_t
) -> libc
::size_t
);
381 match __pthread_get_minstack
.get() {
382 None
=> libc
::PTHREAD_STACK_MIN
,
383 Some(f
) => unsafe { f(attr) }
,
387 // No point in looking up __pthread_get_minstack() on non-glibc
389 #[cfg(all(not(target_os = "linux"),
390 not(target_os
= "netbsd")))]
391 fn min_stack_size(_
: *const libc
::pthread_attr_t
) -> usize {
392 libc
::PTHREAD_STACK_MIN
395 #[cfg(target_os = "netbsd")]
396 fn min_stack_size(_
: *const libc
::pthread_attr_t
) -> usize {