]> git.proxmox.com Git - rustc.git/blob - src/libstd/sys/unix/thread.rs
New upstream version 1.14.0+dfsg1
[rustc.git] / src / libstd / sys / unix / thread.rs
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.
4 //
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.
10
11 use alloc::boxed::FnBox;
12 use cmp;
13 use ffi::CStr;
14 use io;
15 use libc;
16 use mem;
17 use ptr;
18 use sys::os;
19 use time::Duration;
20
21 use sys_common::thread::*;
22
23 pub struct Thread {
24 id: libc::pthread_t,
25 }
26
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 {}
31
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)
38 }
39
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 {
43 panic!()
44 }
45
46 impl Thread {
47 pub unsafe fn new<'a>(stack: usize, p: Box<FnBox() + 'a>)
48 -> io::Result<Thread> {
49 let p = box p;
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);
53
54 let stack_size = cmp::max(stack, min_stack_size(&attr));
55 match pthread_attr_setstacksize(&mut attr,
56 stack_size) {
57 0 => {}
58 n => {
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,
68 stack_size), 0);
69 }
70 };
71
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);
75
76 return if ret != 0 {
77 Err(io::Error::from_raw_os_error(ret))
78 } else {
79 mem::forget(p); // ownership passed to pthread_create
80 Ok(Thread { id: native })
81 };
82
83 extern fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
84 unsafe { start_thread(main); }
85 ptr::null_mut()
86 }
87 }
88
89 pub fn yield_now() {
90 let ret = unsafe { libc::sched_yield() };
91 debug_assert_eq!(ret, 0);
92 }
93
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
99 // directly.
100 unsafe {
101 libc::prctl(PR_SET_NAME, name.as_ptr() as libc::c_ulong, 0, 0, 0);
102 }
103 }
104
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) {
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 ffi::CString;
125 let cname = CString::new(&b"%s"[..]).unwrap();
126 unsafe {
127 libc::pthread_setname_np(libc::pthread_self(), cname.as_ptr(),
128 name.as_ptr() as *mut libc::c_void);
129 }
130 }
131 #[cfg(any(target_env = "newlib",
132 target_os = "solaris",
133 target_os = "haiku",
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.
137 }
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.
141 }
142
143 pub fn sleep(dur: Duration) {
144 let mut secs = dur.as_secs();
145 let mut nsecs = dur.subsec_nanos() as libc::c_long;
146
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.
149 unsafe {
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,
153 tv_nsec: nsecs,
154 };
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;
159 nsecs = ts.tv_nsec;
160 } else {
161 nsecs = 0;
162 }
163 }
164 }
165 }
166
167 pub fn join(self) {
168 unsafe {
169 let ret = libc::pthread_join(self.id, ptr::null_mut());
170 mem::forget(self);
171 debug_assert_eq!(ret, 0);
172 }
173 }
174
175 pub fn id(&self) -> libc::pthread_t { self.id }
176
177 pub fn into_id(self) -> libc::pthread_t {
178 let id = self.id;
179 mem::forget(self);
180 id
181 }
182 }
183
184 impl Drop for Thread {
185 fn drop(&mut self) {
186 let ret = unsafe { libc::pthread_detach(self.id) };
187 debug_assert_eq!(ret, 0);
188 }
189 }
190
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))]
199 pub mod guard {
200 pub unsafe fn current() -> Option<usize> { None }
201 pub unsafe fn init() -> Option<usize> { None }
202 }
203
204
205 #[cfg(any(all(target_os = "linux", not(target_env = "musl")),
206 target_os = "freebsd",
207 target_os = "macos",
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))]
213 pub mod guard {
214 use libc;
215 use libc::mmap;
216 use libc::{PROT_NONE, MAP_PRIVATE, MAP_ANON, MAP_FAILED, MAP_FIXED};
217 use sys::os;
218
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)
225 }
226
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> {
230 let mut ret = None;
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);
237 if e == 0 {
238 let mut stackaddr = ::ptr::null_mut();
239 let mut stacksize = 0;
240 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
241 &mut stacksize), 0);
242 ret = Some(stackaddr);
243 }
244 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
245 ret
246 }
247
248 pub unsafe fn init() -> Option<usize> {
249 let psize = os::page_size();
250 let mut stackaddr = match get_stack_start() {
251 Some(addr) => addr,
252 None => return None,
253 };
254
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;
262 if remainder != 0 {
263 stackaddr = ((stackaddr as usize) + psize - remainder)
264 as *mut libc::c_void;
265 }
266
267 // Rellocate the last page of the stack.
268 // This ensures SIGBUS will be raised on
269 // stack overflow.
270 let result = mmap(stackaddr, psize, PROT_NONE,
271 MAP_PRIVATE | MAP_ANON | MAP_FIXED, -1, 0);
272
273 if result != stackaddr || result == MAP_FAILED {
274 panic!("failed to allocate a guard page");
275 }
276
277 let offset = if cfg!(any(target_os = "linux", target_os = "freebsd")) {
278 2
279 } else {
280 1
281 };
282
283 Some(stackaddr as usize + offset * psize)
284 }
285
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)
291 }
292
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())))
297 }
298
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);
304
305 let extra = if cfg!(target_os = "bitrig") {3} else {1} * os::page_size();
306 Some(if libc::pthread_main_np() == 1 {
307 // main thread
308 current_stack.ss_sp as usize - current_stack.ss_size + extra
309 } else {
310 // new thread
311 current_stack.ss_sp as usize - current_stack.ss_size
312 })
313 }
314
315 #[cfg(any(target_os = "android", target_os = "freebsd",
316 target_os = "linux", target_os = "netbsd"))]
317 pub unsafe fn current() -> Option<usize> {
318 let mut ret = None;
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);
325 if e == 0 {
326 let mut guardsize = 0;
327 assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
328 if guardsize == 0 {
329 panic!("there is no guard page");
330 }
331 let mut stackaddr = ::ptr::null_mut();
332 let mut size = 0;
333 assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
334 &mut size), 0);
335
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)
340 } else {
341 Some(stackaddr as usize + guardsize)
342 };
343 }
344 assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
345 ret
346 }
347 }
348
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")]
355 #[allow(deprecated)]
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);
358
359 match __pthread_get_minstack.get() {
360 None => libc::PTHREAD_STACK_MIN,
361 Some(f) => unsafe { f(attr) },
362 }
363 }
364
365 // No point in looking up __pthread_get_minstack() on non-glibc
366 // platforms.
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
371 }
372
373 #[cfg(target_os = "netbsd")]
374 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
375 2048 // just a guess
376 }