(index<- ) ./libstd/rt/util.rs
git branch: * master 5200215 auto merge of #14035 : alexcrichton/rust/experimental, r=huonw
modified: Fri Apr 25 22:40:04 2014
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 use container::Container;
12 use fmt;
13 use from_str::FromStr;
14 use io::IoResult;
15 use io;
16 use iter::Iterator;
17 use libc;
18 use option::{Some, None, Option};
19 use os;
20 use result::Ok;
21 use str::StrSlice;
22 use unstable::running_on_valgrind;
23 use slice::ImmutableVector;
24
25 // Indicates whether we should perform expensive sanity checks, including rtassert!
26 // FIXME: Once the runtime matures remove the `true` below to turn off rtassert, etc.
27 pub static ENFORCE_SANITY: bool = true || !cfg!(rtopt) || cfg!(rtdebug) || cfg!(rtassert);
28
29 /// Get the number of cores available
30 pub fn num_cpus() -> uint {
31 unsafe {
32 return rust_get_num_cpus();
33 }
34
35 extern {
36 fn rust_get_num_cpus() -> libc::uintptr_t;
37 }
38 }
39
40 /// Valgrind has a fixed-sized array (size around 2000) of segment descriptors
41 /// wired into it; this is a hard limit and requires rebuilding valgrind if you
42 /// want to go beyond it. Normally this is not a problem, but in some tests, we
43 /// produce a lot of threads casually. Making lots of threads alone might not
44 /// be a problem _either_, except on OSX, the segments produced for new threads
45 /// _take a while_ to get reclaimed by the OS. Combined with the fact that libuv
46 /// schedulers fork off a separate thread for polling fsevents on OSX, we get a
47 /// perfect storm of creating "too many mappings" for valgrind to handle when
48 /// running certain stress tests in the runtime.
49 pub fn limit_thread_creation_due_to_osx_and_valgrind() -> bool {
50 (cfg!(target_os="macos")) && running_on_valgrind()
51 }
52
53 /// Get's the number of scheduler threads requested by the environment
54 /// either `RUST_THREADS` or `num_cpus`.
55 pub fn default_sched_threads() -> uint {
56 match os::getenv("RUST_THREADS") {
57 Some(nstr) => {
58 let opt_n: Option<uint> = FromStr::from_str(nstr);
59 match opt_n {
60 Some(n) if n > 0 => n,
61 _ => rtabort!("`RUST_THREADS` is `{}`, should be a positive integer", nstr)
62 }
63 }
64 None => {
65 if limit_thread_creation_due_to_osx_and_valgrind() {
66 1
67 } else {
68 num_cpus()
69 }
70 }
71 }
72 }
73
74 pub struct Stdio(libc::c_int);
75
76 pub static Stdout: Stdio = Stdio(libc::STDOUT_FILENO);
77 pub static Stderr: Stdio = Stdio(libc::STDERR_FILENO);
78
79 impl io::Writer for Stdio {
80 fn write(&mut self, data: &[u8]) -> IoResult<()> {
81 #[cfg(unix)]
82 type WriteLen = libc::size_t;
83 #[cfg(windows)]
84 type WriteLen = libc::c_uint;
85 unsafe {
86 let Stdio(fd) = *self;
87 libc::write(fd,
88 data.as_ptr() as *libc::c_void,
89 data.len() as WriteLen);
90 }
91 Ok(()) // yes, we're lying
92 }
93 }
94
95 pub fn dumb_println(args: &fmt::Arguments) {
96 let mut w = Stderr;
97 let _ = fmt::writeln(&mut w as &mut io::Writer, args);
98 }
99
100 pub fn abort(msg: &str) -> ! {
101 let msg = if !msg.is_empty() { msg } else { "aborted" };
102 let hash = msg.chars().fold(0, |accum, val| accum + (val as uint) );
103 let quote = match hash % 10 {
104 0 => "
105 It was from the artists and poets that the pertinent answers came, and I
106 know that panic would have broken loose had they been able to compare notes.
107 As it was, lacking their original letters, I half suspected the compiler of
108 having asked leading questions, or of having edited the correspondence in
109 corroboration of what he had latently resolved to see.",
110 1 => "
111 There are not many persons who know what wonders are opened to them in the
112 stories and visions of their youth; for when as children we listen and dream,
113 we think but half-formed thoughts, and when as men we try to remember, we are
114 dulled and prosaic with the poison of life. But some of us awake in the night
115 with strange phantasms of enchanted hills and gardens, of fountains that sing
116 in the sun, of golden cliffs overhanging murmuring seas, of plains that stretch
117 down to sleeping cities of bronze and stone, and of shadowy companies of heroes
118 that ride caparisoned white horses along the edges of thick forests; and then
119 we know that we have looked back through the ivory gates into that world of
120 wonder which was ours before we were wise and unhappy.",
121 2 => "
122 Instead of the poems I had hoped for, there came only a shuddering blackness
123 and ineffable loneliness; and I saw at last a fearful truth which no one had
124 ever dared to breathe before â the unwhisperable secret of secrets â The fact
125 that this city of stone and stridor is not a sentient perpetuation of Old New
126 York as London is of Old London and Paris of Old Paris, but that it is in fact
127 quite dead, its sprawling body imperfectly embalmed and infested with queer
128 animate things which have nothing to do with it as it was in life.",
129 3 => "
130 The ocean ate the last of the land and poured into the smoking gulf, thereby
131 giving up all it had ever conquered. From the new-flooded lands it flowed
132 again, uncovering death and decay; and from its ancient and immemorial bed it
133 trickled loathsomely, uncovering nighted secrets of the years when Time was
134 young and the gods unborn. Above the waves rose weedy remembered spires. The
135 moon laid pale lilies of light on dead London, and Paris stood up from its damp
136 grave to be sanctified with star-dust. Then rose spires and monoliths that were
137 weedy but not remembered; terrible spires and monoliths of lands that men never
138 knew were lands...",
139 4 => "
140 There was a night when winds from unknown spaces whirled us irresistibly into
141 limitless vacuum beyond all thought and entity. Perceptions of the most
142 maddeningly untransmissible sort thronged upon us; perceptions of infinity
143 which at the time convulsed us with joy, yet which are now partly lost to my
144 memory and partly incapable of presentation to others.",
145 _ => "You've met with a terrible fate, haven't you?"
146 };
147 rterrln!("{}", "");
148 rterrln!("{}", quote);
149 rterrln!("{}", "");
150 rterrln!("fatal runtime error: {}", msg);
151
152 {
153 let mut err = Stderr;
154 let _err = ::rt::backtrace::write(&mut err);
155 }
156 abort();
157
158 fn abort() -> ! {
159 use intrinsics;
160 unsafe { intrinsics::abort() }
161 }
162 }