]> git.lizzy.rs Git - rust.git/blob - src/libstd/rt/util.rs
dc55740315349b56c87d4042f3e209e81050c34b
[rust.git] / src / libstd / rt / util.rs
1 // Copyright 2013 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 // ignore-lexer-test FIXME #15677
12
13 use prelude::v1::*;
14
15 use cmp;
16 use env;
17 use fmt;
18 use intrinsics;
19 use libc::{self, uintptr_t};
20 use os;
21 use slice;
22 use str;
23 use sync::atomic::{self, Ordering};
24
25 /// Dynamically inquire about whether we're running under V.
26 /// You should usually not use this unless your test definitely
27 /// can't run correctly un-altered. Valgrind is there to help
28 /// you notice weirdness in normal, un-doctored code paths!
29 pub fn running_on_valgrind() -> bool {
30     extern {
31         fn rust_running_on_valgrind() -> uintptr_t;
32     }
33     unsafe { rust_running_on_valgrind() != 0 }
34 }
35
36 /// Valgrind has a fixed-sized array (size around 2000) of segment descriptors
37 /// wired into it; this is a hard limit and requires rebuilding valgrind if you
38 /// want to go beyond it. Normally this is not a problem, but in some tests, we
39 /// produce a lot of threads casually.  Making lots of threads alone might not
40 /// be a problem _either_, except on OSX, the segments produced for new threads
41 /// _take a while_ to get reclaimed by the OS. Combined with the fact that libuv
42 /// schedulers fork off a separate thread for polling fsevents on OSX, we get a
43 /// perfect storm of creating "too many mappings" for valgrind to handle when
44 /// running certain stress tests in the runtime.
45 pub fn limit_thread_creation_due_to_osx_and_valgrind() -> bool {
46     (cfg!(target_os="macos")) && running_on_valgrind()
47 }
48
49 pub fn min_stack() -> uint {
50     static MIN: atomic::AtomicUsize = atomic::ATOMIC_USIZE_INIT;
51     match MIN.load(Ordering::SeqCst) {
52         0 => {}
53         n => return n - 1,
54     }
55     let amt = env::var("RUST_MIN_STACK").ok().and_then(|s| s.parse().ok());
56     let amt = amt.unwrap_or(2 * 1024 * 1024);
57     // 0 is our sentinel value, so ensure that we'll never see 0 after
58     // initialization has run
59     MIN.store(amt + 1, Ordering::SeqCst);
60     return amt;
61 }
62
63 /// Get's the number of scheduler threads requested by the environment
64 /// either `RUST_THREADS` or `num_cpus`.
65 pub fn default_sched_threads() -> uint {
66     match env::var("RUST_THREADS") {
67         Ok(nstr) => {
68             let opt_n: Option<uint> = nstr.parse().ok();
69             match opt_n {
70                 Some(n) if n > 0 => n,
71                 _ => panic!("`RUST_THREADS` is `{}`, should be a positive integer", nstr)
72             }
73         }
74         Err(..) => {
75             if limit_thread_creation_due_to_osx_and_valgrind() {
76                 1
77             } else {
78                 os::num_cpus()
79             }
80         }
81     }
82 }
83
84 // Indicates whether we should perform expensive sanity checks, including rtassert!
85 //
86 // FIXME: Once the runtime matures remove the `true` below to turn off rtassert,
87 //        etc.
88 pub const ENFORCE_SANITY: bool = true || !cfg!(rtopt) || cfg!(rtdebug) ||
89                                   cfg!(rtassert);
90
91 pub struct Stdio(libc::c_int);
92
93 #[allow(non_upper_case_globals)]
94 pub const Stdout: Stdio = Stdio(libc::STDOUT_FILENO);
95 #[allow(non_upper_case_globals)]
96 pub const Stderr: Stdio = Stdio(libc::STDERR_FILENO);
97
98 impl Stdio {
99     pub fn write_bytes(&mut self, data: &[u8]) {
100         #[cfg(unix)]
101         type WriteLen = libc::size_t;
102         #[cfg(windows)]
103         type WriteLen = libc::c_uint;
104         unsafe {
105             let Stdio(fd) = *self;
106             libc::write(fd,
107                         data.as_ptr() as *const libc::c_void,
108                         data.len() as WriteLen);
109         }
110     }
111 }
112
113 impl fmt::Write for Stdio {
114     fn write_str(&mut self, data: &str) -> fmt::Result {
115         self.write_bytes(data.as_bytes());
116         Ok(()) // yes, we're lying
117     }
118 }
119
120 pub fn dumb_print(args: fmt::Arguments) {
121     let _ = Stderr.write_fmt(args);
122 }
123
124 pub fn abort(args: fmt::Arguments) -> ! {
125     use fmt::Write;
126
127     struct BufWriter<'a> {
128         buf: &'a mut [u8],
129         pos: uint,
130     }
131     impl<'a> fmt::Write for BufWriter<'a> {
132         fn write_str(&mut self, bytes: &str) -> fmt::Result {
133             let left = &mut self.buf[self.pos..];
134             let to_write = &bytes.as_bytes()[..cmp::min(bytes.len(), left.len())];
135             slice::bytes::copy_memory(left, to_write);
136             self.pos += to_write.len();
137             Ok(())
138         }
139     }
140
141     // Convert the arguments into a stack-allocated string
142     let mut msg = [0; 512];
143     let mut w = BufWriter { buf: &mut msg, pos: 0 };
144     let _ = write!(&mut w, "{}", args);
145     let msg = str::from_utf8(&w.buf[..w.pos]).unwrap_or("aborted");
146     let msg = if msg.is_empty() {"aborted"} else {msg};
147     rterrln!("fatal runtime error: {}", msg);
148     unsafe { intrinsics::abort(); }
149 }
150
151 pub unsafe fn report_overflow() {
152     use thread;
153
154     // See the message below for why this is not emitted to the
155     // ^ Where did the message below go?
156     // task's logger. This has the additional conundrum of the
157     // logger may not be initialized just yet, meaning that an FFI
158     // call would happen to initialized it (calling out to libuv),
159     // and the FFI call needs 2MB of stack when we just ran out.
160
161     rterrln!("\nthread '{}' has overflowed its stack",
162              thread::current().name().unwrap_or("<unknown>"));
163 }