]> git.lizzy.rs Git - rust.git/blob - src/libstd/panicking.rs
Make PanicInfo::message available for std::panic! with a formatting string.
[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 //! Implementation of various bits and pieces of the `panic!` macro and
12 //! associated runtime pieces.
13 //!
14 //! Specifically, this module contains the implementation of:
15 //!
16 //! * Panic hooks
17 //! * Executing a panic up to doing the actual implementation
18 //! * Shims around "try"
19
20 use io::prelude::*;
21
22 use any::Any;
23 use cell::RefCell;
24 use core::panic::{PanicInfo, Location};
25 use fmt;
26 use intrinsics;
27 use mem;
28 use ptr;
29 use raw;
30 use sys::stdio::Stderr;
31 use sys_common::rwlock::RWLock;
32 use sys_common::thread_info;
33 use sys_common::util;
34 use thread;
35
36 thread_local! {
37     pub static LOCAL_STDERR: RefCell<Option<Box<Write + Send>>> = {
38         RefCell::new(None)
39     }
40 }
41
42 // Binary interface to the panic runtime that the standard library depends on.
43 //
44 // The standard library is tagged with `#![needs_panic_runtime]` (introduced in
45 // RFC 1513) to indicate that it requires some other crate tagged with
46 // `#![panic_runtime]` to exist somewhere. Each panic runtime is intended to
47 // implement these symbols (with the same signatures) so we can get matched up
48 // to them.
49 //
50 // One day this may look a little less ad-hoc with the compiler helping out to
51 // hook up these functions, but it is not this day!
52 #[allow(improper_ctypes)]
53 extern {
54     fn __rust_maybe_catch_panic(f: fn(*mut u8),
55                                 data: *mut u8,
56                                 data_ptr: *mut usize,
57                                 vtable_ptr: *mut usize) -> u32;
58     #[unwind]
59     fn __rust_start_panic(data: usize, vtable: usize) -> u32;
60 }
61
62 #[derive(Copy, Clone)]
63 enum Hook {
64     Default,
65     Custom(*mut (Fn(&PanicInfo) + 'static + Sync + Send)),
66 }
67
68 static HOOK_LOCK: RWLock = RWLock::new();
69 static mut HOOK: Hook = Hook::Default;
70
71 /// Registers a custom panic hook, replacing any that was previously registered.
72 ///
73 /// The panic hook is invoked when a thread panics, but before the panic runtime
74 /// is invoked. As such, the hook will run with both the aborting and unwinding
75 /// runtimes. The default hook prints a message to standard error and generates
76 /// a backtrace if requested, but this behavior can be customized with the
77 /// `set_hook` and `take_hook` functions.
78 ///
79 /// The hook is provided with a `PanicInfo` struct which contains information
80 /// about the origin of the panic, including the payload passed to `panic!` and
81 /// the source code location from which the panic originated.
82 ///
83 /// The panic hook is a global resource.
84 ///
85 /// # Panics
86 ///
87 /// Panics if called from a panicking thread.
88 ///
89 /// # Examples
90 ///
91 /// The following will print "Custom panic hook":
92 ///
93 /// ```should_panic
94 /// use std::panic;
95 ///
96 /// panic::set_hook(Box::new(|_| {
97 ///     println!("Custom panic hook");
98 /// }));
99 ///
100 /// panic!("Normal panic");
101 /// ```
102 #[stable(feature = "panic_hooks", since = "1.10.0")]
103 pub fn set_hook(hook: Box<Fn(&PanicInfo) + 'static + Sync + Send>) {
104     if thread::panicking() {
105         panic!("cannot modify the panic hook from a panicking thread");
106     }
107
108     unsafe {
109         HOOK_LOCK.write();
110         let old_hook = HOOK;
111         HOOK = Hook::Custom(Box::into_raw(hook));
112         HOOK_LOCK.write_unlock();
113
114         if let Hook::Custom(ptr) = old_hook {
115             Box::from_raw(ptr);
116         }
117     }
118 }
119
120 /// Unregisters the current panic hook, returning it.
121 ///
122 /// If no custom hook is registered, the default hook will be returned.
123 ///
124 /// # Panics
125 ///
126 /// Panics if called from a panicking thread.
127 ///
128 /// # Examples
129 ///
130 /// The following will print "Normal panic":
131 ///
132 /// ```should_panic
133 /// use std::panic;
134 ///
135 /// panic::set_hook(Box::new(|_| {
136 ///     println!("Custom panic hook");
137 /// }));
138 ///
139 /// let _ = panic::take_hook();
140 ///
141 /// panic!("Normal panic");
142 /// ```
143 #[stable(feature = "panic_hooks", since = "1.10.0")]
144 pub fn take_hook() -> Box<Fn(&PanicInfo) + 'static + Sync + Send> {
145     if thread::panicking() {
146         panic!("cannot modify the panic hook from a panicking thread");
147     }
148
149     unsafe {
150         HOOK_LOCK.write();
151         let hook = HOOK;
152         HOOK = Hook::Default;
153         HOOK_LOCK.write_unlock();
154
155         match hook {
156             Hook::Default => Box::new(default_hook),
157             Hook::Custom(ptr) => Box::from_raw(ptr),
158         }
159     }
160 }
161
162 fn default_hook(info: &PanicInfo) {
163     #[cfg(feature = "backtrace")]
164     use sys_common::backtrace;
165
166     // If this is a double panic, make sure that we print a backtrace
167     // for this panic. Otherwise only print it if logging is enabled.
168     #[cfg(feature = "backtrace")]
169     let log_backtrace = {
170         let panics = update_panic_count(0);
171
172         if panics >= 2 {
173             Some(backtrace::PrintFormat::Full)
174         } else {
175             backtrace::log_enabled()
176         }
177     };
178
179     let location = info.location().unwrap();  // The current implementation always returns Some
180     let file = location.file();
181     let line = location.line();
182     let col = location.column();
183
184     let msg = match info.payload().downcast_ref::<&'static str>() {
185         Some(s) => *s,
186         None => match info.payload().downcast_ref::<String>() {
187             Some(s) => &s[..],
188             None => "Box<Any>",
189         }
190     };
191     let mut err = Stderr::new().ok();
192     let thread = thread_info::current_thread();
193     let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");
194
195     let write = |err: &mut ::io::Write| {
196         let _ = writeln!(err, "thread '{}' panicked at '{}', {}:{}:{}",
197                          name, msg, file, line, col);
198
199         #[cfg(feature = "backtrace")]
200         {
201             use sync::atomic::{AtomicBool, Ordering};
202
203             static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
204
205             if let Some(format) = log_backtrace {
206                 let _ = backtrace::print(err, format);
207             } else if FIRST_PANIC.compare_and_swap(true, false, Ordering::SeqCst) {
208                 let _ = writeln!(err, "note: Run with `RUST_BACKTRACE=1` for a backtrace.");
209             }
210         }
211     };
212
213     let prev = LOCAL_STDERR.with(|s| s.borrow_mut().take());
214     match (prev, err.as_mut()) {
215         (Some(mut stderr), _) => {
216             write(&mut *stderr);
217             let mut s = Some(stderr);
218             LOCAL_STDERR.with(|slot| {
219                 *slot.borrow_mut() = s.take();
220             });
221         }
222         (None, Some(ref mut err)) => { write(err) }
223         _ => {}
224     }
225 }
226
227
228 #[cfg(not(test))]
229 #[doc(hidden)]
230 #[unstable(feature = "update_panic_count", issue = "0")]
231 pub fn update_panic_count(amt: isize) -> usize {
232     use cell::Cell;
233     thread_local! { static PANIC_COUNT: Cell<usize> = Cell::new(0) }
234
235     PANIC_COUNT.with(|c| {
236         let next = (c.get() as isize + amt) as usize;
237         c.set(next);
238         return next
239     })
240 }
241
242 #[cfg(test)]
243 pub use realstd::rt::update_panic_count;
244
245 /// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
246 pub unsafe fn try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<Any + Send>> {
247     #[allow(unions_with_drop_fields)]
248     union Data<F, R> {
249         f: F,
250         r: R,
251     }
252
253     // We do some sketchy operations with ownership here for the sake of
254     // performance. We can only  pass pointers down to
255     // `__rust_maybe_catch_panic` (can't pass objects by value), so we do all
256     // the ownership tracking here manually using a union.
257     //
258     // We go through a transition where:
259     //
260     // * First, we set the data to be the closure that we're going to call.
261     // * When we make the function call, the `do_call` function below, we take
262     //   ownership of the function pointer. At this point the `Data` union is
263     //   entirely uninitialized.
264     // * If the closure successfully returns, we write the return value into the
265     //   data's return slot. Note that `ptr::write` is used as it's overwriting
266     //   uninitialized data.
267     // * Finally, when we come back out of the `__rust_maybe_catch_panic` we're
268     //   in one of two states:
269     //
270     //      1. The closure didn't panic, in which case the return value was
271     //         filled in. We move it out of `data` and return it.
272     //      2. The closure panicked, in which case the return value wasn't
273     //         filled in. In this case the entire `data` union is invalid, so
274     //         there is no need to drop anything.
275     //
276     // Once we stack all that together we should have the "most efficient'
277     // method of calling a catch panic whilst juggling ownership.
278     let mut any_data = 0;
279     let mut any_vtable = 0;
280     let mut data = Data {
281         f,
282     };
283
284     let r = __rust_maybe_catch_panic(do_call::<F, R>,
285                                      &mut data as *mut _ as *mut u8,
286                                      &mut any_data,
287                                      &mut any_vtable);
288
289     return if r == 0 {
290         debug_assert!(update_panic_count(0) == 0);
291         Ok(data.r)
292     } else {
293         update_panic_count(-1);
294         debug_assert!(update_panic_count(0) == 0);
295         Err(mem::transmute(raw::TraitObject {
296             data: any_data as *mut _,
297             vtable: any_vtable as *mut _,
298         }))
299     };
300
301     fn do_call<F: FnOnce() -> R, R>(data: *mut u8) {
302         unsafe {
303             let data = data as *mut Data<F, R>;
304             let f = ptr::read(&mut (*data).f);
305             ptr::write(&mut (*data).r, f());
306         }
307     }
308 }
309
310 /// Determines whether the current thread is unwinding because of panic.
311 pub fn panicking() -> bool {
312     update_panic_count(0) != 0
313 }
314
315 /// Entry point of panic from the libcore crate.
316 #[cfg(not(test))]
317 #[lang = "panic_fmt"]
318 #[unwind]
319 pub extern fn rust_begin_panic(msg: fmt::Arguments,
320                                file: &'static str,
321                                line: u32,
322                                col: u32) -> ! {
323     begin_panic_fmt(&msg, &(file, line, col))
324 }
325
326 /// The entry point for panicking with a formatted message.
327 ///
328 /// This is designed to reduce the amount of code required at the call
329 /// site as much as possible (so that `panic!()` has as low an impact
330 /// on (e.g.) the inlining of other functions as possible), by moving
331 /// the actual formatting into this shared place.
332 #[unstable(feature = "libstd_sys_internals",
333            reason = "used by the panic! macro",
334            issue = "0")]
335 #[inline(never)] #[cold]
336 pub fn begin_panic_fmt(msg: &fmt::Arguments,
337                        file_line_col: &(&'static str, u32, u32)) -> ! {
338     use fmt::Write;
339
340     // We do two allocations here, unfortunately. But (a) they're
341     // required with the current scheme, and (b) we don't handle
342     // panic + OOM properly anyway (see comment in begin_panic
343     // below).
344
345     let mut s = String::new();
346     let _ = s.write_fmt(*msg);
347     rust_panic_with_hook(Box::new(s), Some(msg), file_line_col)
348 }
349
350 /// This is the entry point of panicking for panic!() and assert!().
351 #[unstable(feature = "libstd_sys_internals",
352            reason = "used by the panic! macro",
353            issue = "0")]
354 #[inline(never)] #[cold] // avoid code bloat at the call sites as much as possible
355 pub fn begin_panic<M: Any + Send>(msg: M, file_line_col: &(&'static str, u32, u32)) -> ! {
356     // Note that this should be the only allocation performed in this code path.
357     // Currently this means that panic!() on OOM will invoke this code path,
358     // but then again we're not really ready for panic on OOM anyway. If
359     // we do start doing this, then we should propagate this allocation to
360     // be performed in the parent of this thread instead of the thread that's
361     // panicking.
362
363     rust_panic_with_hook(Box::new(msg), None, file_line_col)
364 }
365
366 /// Executes the primary logic for a panic, including checking for recursive
367 /// panics and panic hooks.
368 ///
369 /// This is the entry point or panics from libcore, formatted panics, and
370 /// `Box<Any>` panics. Here we'll verify that we're not panicking recursively,
371 /// run panic hooks, and then delegate to the actual implementation of panics.
372 #[inline(never)]
373 #[cold]
374 fn rust_panic_with_hook(payload: Box<Any + Send>,
375                         message: Option<&fmt::Arguments>,
376                         file_line_col: &(&'static str, u32, u32)) -> ! {
377     let (file, line, col) = *file_line_col;
378
379     let panics = update_panic_count(1);
380
381     // If this is the third nested call (e.g. panics == 2, this is 0-indexed),
382     // the panic hook probably triggered the last panic, otherwise the
383     // double-panic check would have aborted the process. In this case abort the
384     // process real quickly as we don't want to try calling it again as it'll
385     // probably just panic again.
386     if panics > 2 {
387         util::dumb_print(format_args!("thread panicked while processing \
388                                        panic. aborting.\n"));
389         unsafe { intrinsics::abort() }
390     }
391
392     unsafe {
393         let info = PanicInfo::internal_constructor(
394             &*payload,
395             message,
396             Location::internal_constructor(file, line, col),
397         );
398         HOOK_LOCK.read();
399         match HOOK {
400             Hook::Default => default_hook(&info),
401             Hook::Custom(ptr) => (*ptr)(&info),
402         }
403         HOOK_LOCK.read_unlock();
404     }
405
406     if panics > 1 {
407         // If a thread panics while it's already unwinding then we
408         // have limited options. Currently our preference is to
409         // just abort. In the future we may consider resuming
410         // unwinding or otherwise exiting the thread cleanly.
411         util::dumb_print(format_args!("thread panicked while panicking. \
412                                        aborting.\n"));
413         unsafe { intrinsics::abort() }
414     }
415
416     rust_panic(payload)
417 }
418
419 /// Shim around rust_panic. Called by resume_unwind.
420 pub fn update_count_then_panic(msg: Box<Any + Send>) -> ! {
421     update_panic_count(1);
422     rust_panic(msg)
423 }
424
425 /// A private no-mangle function on which to slap yer breakpoints.
426 #[no_mangle]
427 #[allow(private_no_mangle_fns)] // yes we get it, but we like breakpoints
428 pub fn rust_panic(msg: Box<Any + Send>) -> ! {
429     let code = unsafe {
430         let obj = mem::transmute::<_, raw::TraitObject>(msg);
431         __rust_start_panic(obj.data as usize, obj.vtable as usize)
432     };
433     rtabort!("failed to initiate panic, error {}", code)
434 }