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