]> git.lizzy.rs Git - rust.git/blob - src/libstd/panicking.rs
Auto merge of #24865 - bluss:range-size, r=alexcrichton
[rust.git] / src / libstd / panicking.rs
1 // Copyright 2014 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 #![unstable(feature = "std_misc")]
12
13 use prelude::v1::*;
14 use io::prelude::*;
15
16 use any::Any;
17 use cell::RefCell;
18 use rt::{backtrace, unwind};
19 use sys::stdio::Stderr;
20 use sys_common::thread_info;
21
22 thread_local! {
23     pub static LOCAL_STDERR: RefCell<Option<Box<Write + Send>>> = {
24         RefCell::new(None)
25     }
26 }
27
28 pub fn on_panic(obj: &(Any+Send), file: &'static str, line: u32) {
29     let msg = match obj.downcast_ref::<&'static str>() {
30         Some(s) => *s,
31         None => match obj.downcast_ref::<String>() {
32             Some(s) => &s[..],
33             None => "Box<Any>",
34         }
35     };
36     let mut err = Stderr::new();
37     let thread = thread_info::current_thread();
38     let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");
39     let prev = LOCAL_STDERR.with(|s| s.borrow_mut().take());
40     match prev {
41         Some(mut stderr) => {
42             // FIXME: what to do when the thread printing panics?
43             let _ = writeln!(stderr,
44                              "thread '{}' panicked at '{}', {}:{}\n",
45                              name, msg, file, line);
46             if backtrace::log_enabled() {
47                 let _ = backtrace::write(&mut *stderr);
48             }
49             let mut s = Some(stderr);
50             LOCAL_STDERR.with(|slot| {
51                 *slot.borrow_mut() = s.take();
52             });
53         }
54         None => {
55             let _ = writeln!(&mut err, "thread '{}' panicked at '{}', {}:{}",
56                              name, msg, file, line);
57             if backtrace::log_enabled() {
58                 let _ = backtrace::write(&mut err);
59             }
60         }
61     }
62
63     // If this is a double panic, make sure that we printed a backtrace
64     // for this panic.
65     if unwind::panicking() && !backtrace::log_enabled() {
66         let _ = backtrace::write(&mut err);
67     }
68 }