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.
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.
18 use sync::StaticRwLock;
19 use sync::atomic::{AtomicBool, Ordering};
20 use sys::stdio::Stderr;
21 use sys_common::backtrace;
22 use sys_common::thread_info;
26 thread_local! { pub static PANIC_COUNT: Cell<usize> = Cell::new(0) }
29 pub static LOCAL_STDERR: RefCell<Option<Box<Write + Send>>> = {
34 #[derive(Copy, Clone)]
37 Custom(*mut (Fn(&PanicInfo) + 'static + Sync + Send)),
40 static HANDLER_LOCK: StaticRwLock = StaticRwLock::new();
41 static mut HANDLER: Handler = Handler::Default;
42 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
44 /// Registers a custom panic handler, replacing any that was previously
47 /// The panic handler is invoked when a thread panics, but before it begins
48 /// unwinding the stack. The default handler prints a message to standard error
49 /// and generates a backtrace if requested, but this behavior can be customized
50 /// with the `set_handler` and `take_handler` functions.
52 /// The handler is provided with a `PanicInfo` struct which contains information
53 /// about the origin of the panic, including the payload passed to `panic!` and
54 /// the source code location from which the panic originated.
56 /// The panic handler is a global resource.
60 /// Panics if called from a panicking thread.
61 #[unstable(feature = "panic_handler", reason = "awaiting feedback", issue = "30449")]
62 pub fn set_handler<F>(handler: F) where F: Fn(&PanicInfo) + 'static + Sync + Send {
63 if thread::panicking() {
64 panic!("cannot modify the panic handler from a panicking thread");
67 let handler = Box::new(handler);
69 let lock = HANDLER_LOCK.write();
70 let old_handler = HANDLER;
71 HANDLER = Handler::Custom(Box::into_raw(handler));
74 if let Handler::Custom(ptr) = old_handler {
80 /// Unregisters the current panic handler, returning it.
82 /// If no custom handler is registered, the default handler will be returned.
86 /// Panics if called from a panicking thread.
87 #[unstable(feature = "panic_handler", reason = "awaiting feedback", issue = "30449")]
88 pub fn take_handler() -> Box<Fn(&PanicInfo) + 'static + Sync + Send> {
89 if thread::panicking() {
90 panic!("cannot modify the panic handler from a panicking thread");
94 let lock = HANDLER_LOCK.write();
95 let handler = HANDLER;
96 HANDLER = Handler::Default;
100 Handler::Default => Box::new(default_handler),
101 Handler::Custom(ptr) => {Box::from_raw(ptr)} // FIXME #30530
106 /// A struct providing information about a panic.
107 #[unstable(feature = "panic_handler", reason = "awaiting feedback", issue = "30449")]
108 pub struct PanicInfo<'a> {
109 payload: &'a (Any + Send),
110 location: Location<'a>,
113 impl<'a> PanicInfo<'a> {
114 /// Returns the payload associated with the panic.
116 /// This will commonly, but not always, be a `&'static str` or `String`.
117 #[unstable(feature = "panic_handler", reason = "awaiting feedback", issue = "30449")]
118 pub fn payload(&self) -> &(Any + Send) {
122 /// Returns information about the location from which the panic originated,
125 /// This method will currently always return `Some`, but this may change
126 /// in future versions.
127 #[unstable(feature = "panic_handler", reason = "awaiting feedback", issue = "30449")]
128 pub fn location(&self) -> Option<&Location> {
133 /// A struct containing information about the location of a panic.
134 #[unstable(feature = "panic_handler", reason = "awaiting feedback", issue = "30449")]
135 pub struct Location<'a> {
140 impl<'a> Location<'a> {
141 /// Returns the name of the source file from which the panic originated.
142 #[unstable(feature = "panic_handler", reason = "awaiting feedback", issue = "30449")]
143 pub fn file(&self) -> &str {
147 /// Returns the line number from which the panic originated.
148 #[unstable(feature = "panic_handler", reason = "awaiting feedback", issue = "30449")]
149 pub fn line(&self) -> u32 {
154 fn default_handler(info: &PanicInfo) {
155 let panics = PANIC_COUNT.with(|s| s.get());
157 // If this is a double panic, make sure that we print a backtrace
158 // for this panic. Otherwise only print it if logging is enabled.
159 let log_backtrace = panics >= 2 || backtrace::log_enabled();
161 let file = info.location.file;
162 let line = info.location.line;
164 let msg = match info.payload.downcast_ref::<&'static str>() {
166 None => match info.payload.downcast_ref::<String>() {
171 let mut err = Stderr::new().ok();
172 let thread = thread_info::current_thread();
173 let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");
175 let write = |err: &mut ::io::Write| {
176 let _ = writeln!(err, "thread '{}' panicked at '{}', {}:{}",
177 name, msg, file, line);
180 let _ = backtrace::write(err);
181 } else if FIRST_PANIC.compare_and_swap(true, false, Ordering::SeqCst) {
182 let _ = writeln!(err, "note: Run with `RUST_BACKTRACE=1` for a backtrace.");
186 let prev = LOCAL_STDERR.with(|s| s.borrow_mut().take());
187 match (prev, err.as_mut()) {
188 (Some(mut stderr), _) => {
190 let mut s = Some(stderr);
191 LOCAL_STDERR.with(|slot| {
192 *slot.borrow_mut() = s.take();
195 (None, Some(ref mut err)) => { write(err) }
200 pub fn on_panic(obj: &(Any+Send), file: &'static str, line: u32) {
201 let panics = PANIC_COUNT.with(|s| {
202 let count = s.get() + 1;
207 // If this is the third nested call, on_panic triggered the last panic,
208 // otherwise the double-panic check would have aborted the process.
209 // Even if it is likely that on_panic was unable to log the backtrace,
210 // abort immediately to avoid infinite recursion, so that attaching a
211 // debugger provides a useable stacktrace.
213 util::dumb_print(format_args!("thread panicked while processing \
214 panic. aborting.\n"));
215 unsafe { intrinsics::abort() }
218 let info = PanicInfo {
227 let _lock = HANDLER_LOCK.read();
229 Handler::Default => default_handler(&info),
230 Handler::Custom(ptr) => (*ptr)(&info),
235 // If a thread panics while it's already unwinding then we
236 // have limited options. Currently our preference is to
237 // just abort. In the future we may consider resuming
238 // unwinding or otherwise exiting the thread cleanly.
239 util::dumb_print(format_args!("thread panicked while panicking. \
241 unsafe { intrinsics::abort() }