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
::*;
27 // Some platforms may have pthread_t as a pointer in which case we still want
28 // a thread to be Send/Sync
29 unsafe impl Send
for Thread {}
30 unsafe impl Sync
for Thread {}
32 // The pthread_attr_setstacksize symbol doesn't exist in the emscripten libc,
33 // so we have to not link to it to satisfy emcc's ERROR_ON_UNDEFINED_SYMBOLS.
34 #[cfg(not(target_os = "emscripten"))]
35 unsafe fn pthread_attr_setstacksize(attr
: *mut libc
::pthread_attr_t
,
36 stack_size
: libc
::size_t
) -> libc
::c_int
{
37 libc
::pthread_attr_setstacksize(attr
, stack_size
)
40 #[cfg(target_os = "emscripten")]
41 unsafe fn pthread_attr_setstacksize(_attr
: *mut libc
::pthread_attr_t
,
42 _stack_size
: libc
::size_t
) -> libc
::c_int
{
47 pub unsafe fn new
<'a
>(stack
: usize, p
: Box
<FnBox() + 'a
>)
48 -> io
::Result
<Thread
> {
50 let mut native
: libc
::pthread_t
= mem
::zeroed();
51 let mut attr
: libc
::pthread_attr_t
= mem
::zeroed();
52 assert_eq
!(libc
::pthread_attr_init(&mut attr
), 0);
54 let stack_size
= cmp
::max(stack
, min_stack_size(&attr
));
55 match pthread_attr_setstacksize(&mut attr
,
59 assert_eq
!(n
, libc
::EINVAL
);
60 // EINVAL means |stack_size| is either too small or not a
61 // multiple of the system page size. Because it's definitely
62 // >= PTHREAD_STACK_MIN, it must be an alignment issue.
63 // Round up to the nearest page and try again.
64 let page_size
= os
::page_size();
65 let stack_size
= (stack_size
+ page_size
- 1) &
66 (-(page_size
as isize - 1) as usize - 1);
67 assert_eq
!(libc
::pthread_attr_setstacksize(&mut attr
,
72 let ret
= libc
::pthread_create(&mut native
, &attr
, thread_start
,
73 &*p
as *const _
as *mut _
);
74 assert_eq
!(libc
::pthread_attr_destroy(&mut attr
), 0);
77 Err(io
::Error
::from_raw_os_error(ret
))
79 mem
::forget(p
); // ownership passed to pthread_create
80 Ok(Thread { id: native }
)
83 extern fn thread_start(main
: *mut libc
::c_void
) -> *mut libc
::c_void
{
84 unsafe { start_thread(main); }
90 let ret
= unsafe { libc::sched_yield() }
;
91 debug_assert_eq
!(ret
, 0);
94 #[cfg(any(target_os = "linux",
95 target_os
= "android"))]
96 pub fn set_name(name
: &CStr
) {
97 const PR_SET_NAME
: libc
::c_int
= 15;
98 // pthread wrapper only appeared in glibc 2.12, so we use syscall
101 libc
::prctl(PR_SET_NAME
, name
.as_ptr() as libc
::c_ulong
, 0, 0, 0);
105 #[cfg(any(target_os = "freebsd",
106 target_os
= "dragonfly",
107 target_os
= "bitrig",
108 target_os
= "openbsd"))]
109 pub fn set_name(name
: &CStr
) {
111 libc
::pthread_set_name_np(libc
::pthread_self(), name
.as_ptr());
115 #[cfg(any(target_os = "macos", target_os = "ios"))]
116 pub fn set_name(name
: &CStr
) {
118 libc
::pthread_setname_np(name
.as_ptr());
122 #[cfg(target_os = "netbsd")]
123 pub fn set_name(name
: &CStr
) {
125 let cname
= CString
::new(&b
"%s"[..]).unwrap();
127 libc
::pthread_setname_np(libc
::pthread_self(), cname
.as_ptr(),
128 name
.as_ptr() as *mut libc
::c_void
);
131 #[cfg(any(target_env = "newlib",
132 target_os
= "solaris",
134 target_os
= "emscripten"))]
135 pub fn set_name(_name
: &CStr
) {
136 // Newlib, Illumos, Haiku, and Emscripten have no way to set a thread name.
138 #[cfg(target_os = "fuchsia")]
139 pub fn set_name(_name
: &CStr
) {
140 // FIXME: determine whether Fuchsia has a way to set a thread name.
143 pub fn sleep(dur
: Duration
) {
144 let mut secs
= dur
.as_secs();
145 let mut nsecs
= dur
.subsec_nanos() as libc
::c_long
;
147 // If we're awoken with a signal then the return value will be -1 and
148 // nanosleep will fill in `ts` with the remaining time.
150 while secs
> 0 || nsecs
> 0 {
151 let mut ts
= libc
::timespec
{
152 tv_sec
: cmp
::min(libc
::time_t
::max_value() as u64, secs
) as libc
::time_t
,
155 secs
-= ts
.tv_sec
as u64;
156 if libc
::nanosleep(&ts
, &mut ts
) == -1 {
157 assert_eq
!(os
::errno(), libc
::EINTR
);
158 secs
+= ts
.tv_sec
as u64;
169 let ret
= libc
::pthread_join(self.id
, ptr
::null_mut());
171 debug_assert_eq
!(ret
, 0);
175 pub fn id(&self) -> libc
::pthread_t { self.id }
177 pub fn into_id(self) -> libc
::pthread_t
{
184 impl Drop
for Thread
{
186 let ret
= unsafe { libc::pthread_detach(self.id) }
;
187 debug_assert_eq
!(ret
, 0);
191 #[cfg(all(not(all(target_os = "linux", not(target_env = "musl"))),
192 not(target_os
= "freebsd"),
193 not(target_os
= "macos"),
194 not(target_os
= "bitrig"),
195 not(all(target_os
= "netbsd", not(target_vendor
= "rumprun"))),
196 not(target_os
= "openbsd"),
197 not(target_os
= "solaris")))]
198 #[cfg_attr(test, allow(dead_code))]
200 pub unsafe fn current() -> Option
<usize> { None }
201 pub unsafe fn init() -> Option
<usize> { None }
205 #[cfg(any(all(target_os = "linux", not(target_env = "musl")),
206 target_os
= "freebsd",
208 target_os
= "bitrig",
209 all(target_os
= "netbsd", not(target_vendor
= "rumprun")),
210 target_os
= "openbsd",
211 target_os
= "solaris"))]
212 #[cfg_attr(test, allow(dead_code))]
216 use libc
::{PROT_NONE, MAP_PRIVATE, MAP_ANON, MAP_FAILED, MAP_FIXED}
;
219 #[cfg(any(target_os = "macos",
220 target_os
= "bitrig",
221 target_os
= "openbsd",
222 target_os
= "solaris"))]
223 unsafe fn get_stack_start() -> Option
<*mut libc
::c_void
> {
224 current().map(|s
| s
as *mut libc
::c_void
)
227 #[cfg(any(target_os = "android", target_os = "freebsd",
228 target_os
= "linux", target_os
= "netbsd"))]
229 unsafe fn get_stack_start() -> Option
<*mut libc
::c_void
> {
231 let mut attr
: libc
::pthread_attr_t
= ::mem
::zeroed();
232 assert_eq
!(libc
::pthread_attr_init(&mut attr
), 0);
233 #[cfg(target_os = "freebsd")]
234 let e
= libc
::pthread_attr_get_np(libc
::pthread_self(), &mut attr
);
235 #[cfg(not(target_os = "freebsd"))]
236 let e
= libc
::pthread_getattr_np(libc
::pthread_self(), &mut attr
);
238 let mut stackaddr
= ::ptr
::null_mut();
239 let mut stacksize
= 0;
240 assert_eq
!(libc
::pthread_attr_getstack(&attr
, &mut stackaddr
,
242 ret
= Some(stackaddr
);
244 assert_eq
!(libc
::pthread_attr_destroy(&mut attr
), 0);
248 pub unsafe fn init() -> Option
<usize> {
249 let psize
= os
::page_size();
250 let mut stackaddr
= match get_stack_start() {
255 // Ensure stackaddr is page aligned! A parent process might
256 // have reset RLIMIT_STACK to be non-page aligned. The
257 // pthread_attr_getstack() reports the usable stack area
258 // stackaddr < stackaddr + stacksize, so if stackaddr is not
259 // page-aligned, calculate the fix such that stackaddr <
260 // new_page_aligned_stackaddr < stackaddr + stacksize
261 let remainder
= (stackaddr
as usize) % psize
;
263 stackaddr
= ((stackaddr
as usize) + psize
- remainder
)
264 as *mut libc
::c_void
;
267 // Rellocate the last page of the stack.
268 // This ensures SIGBUS will be raised on
270 let result
= mmap(stackaddr
, psize
, PROT_NONE
,
271 MAP_PRIVATE
| MAP_ANON
| MAP_FIXED
, -1, 0);
273 if result
!= stackaddr
|| result
== MAP_FAILED
{
274 panic
!("failed to allocate a guard page");
277 let offset
= if cfg
!(any(target_os
= "linux", target_os
= "freebsd")) {
283 Some(stackaddr
as usize + offset
* psize
)
286 #[cfg(target_os = "solaris")]
287 pub unsafe fn current() -> Option
<usize> {
288 let mut current_stack
: libc
::stack_t
= ::mem
::zeroed();
289 assert_eq
!(libc
::stack_getbounds(&mut current_stack
), 0);
290 Some(current_stack
.ss_sp
as usize)
293 #[cfg(target_os = "macos")]
294 pub unsafe fn current() -> Option
<usize> {
295 Some((libc
::pthread_get_stackaddr_np(libc
::pthread_self()) as usize -
296 libc
::pthread_get_stacksize_np(libc
::pthread_self())))
299 #[cfg(any(target_os = "openbsd", target_os = "bitrig"))]
300 pub unsafe fn current() -> Option
<usize> {
301 let mut current_stack
: libc
::stack_t
= ::mem
::zeroed();
302 assert_eq
!(libc
::pthread_stackseg_np(libc
::pthread_self(),
303 &mut current_stack
), 0);
305 let extra
= if cfg
!(target_os
= "bitrig") {3}
else {1}
* os
::page_size();
306 Some(if libc
::pthread_main_np() == 1 {
308 current_stack
.ss_sp
as usize - current_stack
.ss_size
+ extra
311 current_stack
.ss_sp
as usize - current_stack
.ss_size
315 #[cfg(any(target_os = "android", target_os = "freebsd",
316 target_os
= "linux", target_os
= "netbsd"))]
317 pub unsafe fn current() -> Option
<usize> {
319 let mut attr
: libc
::pthread_attr_t
= ::mem
::zeroed();
320 assert_eq
!(libc
::pthread_attr_init(&mut attr
), 0);
321 #[cfg(target_os = "freebsd")]
322 let e
= libc
::pthread_attr_get_np(libc
::pthread_self(), &mut attr
);
323 #[cfg(not(target_os = "freebsd"))]
324 let e
= libc
::pthread_getattr_np(libc
::pthread_self(), &mut attr
);
326 let mut guardsize
= 0;
327 assert_eq
!(libc
::pthread_attr_getguardsize(&attr
, &mut guardsize
), 0);
329 panic
!("there is no guard page");
331 let mut stackaddr
= ::ptr
::null_mut();
333 assert_eq
!(libc
::pthread_attr_getstack(&attr
, &mut stackaddr
,
336 ret
= if cfg
!(target_os
= "freebsd") {
337 Some(stackaddr
as usize - guardsize
)
338 } else if cfg
!(target_os
= "netbsd") {
339 Some(stackaddr
as usize)
341 Some(stackaddr
as usize + guardsize
)
344 assert_eq
!(libc
::pthread_attr_destroy(&mut attr
), 0);
349 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
350 // PTHREAD_STACK_MIN plus however many bytes are needed for thread-local
351 // storage. We need that information to avoid blowing up when a small stack
352 // is created in an application with big thread-local storage requirements.
353 // See #6233 for rationale and details.
354 #[cfg(target_os = "linux")]
356 fn min_stack_size(attr
: *const libc
::pthread_attr_t
) -> usize {
357 weak
!(fn __pthread_get_minstack(*const libc
::pthread_attr_t
) -> libc
::size_t
);
359 match __pthread_get_minstack
.get() {
360 None
=> libc
::PTHREAD_STACK_MIN
,
361 Some(f
) => unsafe { f(attr) }
,
365 // No point in looking up __pthread_get_minstack() on non-glibc
367 #[cfg(all(not(target_os = "linux"),
368 not(target_os
= "netbsd")))]
369 fn min_stack_size(_
: *const libc
::pthread_attr_t
) -> usize {
370 libc
::PTHREAD_STACK_MIN
373 #[cfg(target_os = "netbsd")]
374 fn min_stack_size(_
: *const libc
::pthread_attr_t
) -> usize {