]> git.lizzy.rs Git - rust.git/blob - src/libstd/panicking.rs
Rollup merge of #35620 - cvubrugier:master, r=Manishearth
[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::RefCell;
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 #[stable(feature = "panic_hooks", since = "1.10.0")]
89 pub fn set_hook(hook: Box<Fn(&PanicInfo) + 'static + Sync + Send>) {
90     if thread::panicking() {
91         panic!("cannot modify the panic hook from a panicking thread");
92     }
93
94     unsafe {
95         HOOK_LOCK.write();
96         let old_hook = HOOK;
97         HOOK = Hook::Custom(Box::into_raw(hook));
98         HOOK_LOCK.write_unlock();
99
100         if let Hook::Custom(ptr) = old_hook {
101             Box::from_raw(ptr);
102         }
103     }
104 }
105
106 /// Unregisters the current panic hook, returning it.
107 ///
108 /// If no custom hook is registered, the default hook will be returned.
109 ///
110 /// # Panics
111 ///
112 /// Panics if called from a panicking thread.
113 #[stable(feature = "panic_hooks", since = "1.10.0")]
114 pub fn take_hook() -> Box<Fn(&PanicInfo) + 'static + Sync + Send> {
115     if thread::panicking() {
116         panic!("cannot modify the panic hook from a panicking thread");
117     }
118
119     unsafe {
120         HOOK_LOCK.write();
121         let hook = HOOK;
122         HOOK = Hook::Default;
123         HOOK_LOCK.write_unlock();
124
125         match hook {
126             Hook::Default => Box::new(default_hook),
127             Hook::Custom(ptr) => {Box::from_raw(ptr)} // FIXME #30530
128         }
129     }
130 }
131
132 /// A struct providing information about a panic.
133 #[stable(feature = "panic_hooks", since = "1.10.0")]
134 pub struct PanicInfo<'a> {
135     payload: &'a (Any + Send),
136     location: Location<'a>,
137 }
138
139 impl<'a> PanicInfo<'a> {
140     /// Returns the payload associated with the panic.
141     ///
142     /// This will commonly, but not always, be a `&'static str` or `String`.
143     #[stable(feature = "panic_hooks", since = "1.10.0")]
144     pub fn payload(&self) -> &(Any + Send) {
145         self.payload
146     }
147
148     /// Returns information about the location from which the panic originated,
149     /// if available.
150     ///
151     /// This method will currently always return `Some`, but this may change
152     /// in future versions.
153     #[stable(feature = "panic_hooks", since = "1.10.0")]
154     pub fn location(&self) -> Option<&Location> {
155         Some(&self.location)
156     }
157 }
158
159 /// A struct containing information about the location of a panic.
160 #[stable(feature = "panic_hooks", since = "1.10.0")]
161 pub struct Location<'a> {
162     file: &'a str,
163     line: u32,
164 }
165
166 impl<'a> Location<'a> {
167     /// Returns the name of the source file from which the panic originated.
168     #[stable(feature = "panic_hooks", since = "1.10.0")]
169     pub fn file(&self) -> &str {
170         self.file
171     }
172
173     /// Returns the line number from which the panic originated.
174     #[stable(feature = "panic_hooks", since = "1.10.0")]
175     pub fn line(&self) -> u32 {
176         self.line
177     }
178 }
179
180 fn default_hook(info: &PanicInfo) {
181     #[cfg(any(not(cargobuild), feature = "backtrace"))]
182     use sys_common::backtrace;
183
184     // If this is a double panic, make sure that we print a backtrace
185     // for this panic. Otherwise only print it if logging is enabled.
186     #[cfg(any(not(cargobuild), feature = "backtrace"))]
187     let log_backtrace = {
188         let panics = update_panic_count(0);
189
190         panics >= 2 || backtrace::log_enabled()
191     };
192
193     let file = info.location.file;
194     let line = info.location.line;
195
196     let msg = match info.payload.downcast_ref::<&'static str>() {
197         Some(s) => *s,
198         None => match info.payload.downcast_ref::<String>() {
199             Some(s) => &s[..],
200             None => "Box<Any>",
201         }
202     };
203     let mut err = Stderr::new().ok();
204     let thread = thread_info::current_thread();
205     let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");
206
207     let write = |err: &mut ::io::Write| {
208         let _ = writeln!(err, "thread '{}' panicked at '{}', {}:{}",
209                          name, msg, file, line);
210
211         #[cfg(any(not(cargobuild), feature = "backtrace"))]
212         {
213             use sync::atomic::{AtomicBool, Ordering};
214
215             static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
216
217             if log_backtrace {
218                 let _ = backtrace::write(err);
219             } else if FIRST_PANIC.compare_and_swap(true, false, Ordering::SeqCst) {
220                 let _ = writeln!(err, "note: Run with `RUST_BACKTRACE=1` for a backtrace.");
221             }
222         }
223     };
224
225     let prev = LOCAL_STDERR.with(|s| s.borrow_mut().take());
226     match (prev, err.as_mut()) {
227         (Some(mut stderr), _) => {
228             write(&mut *stderr);
229             let mut s = Some(stderr);
230             LOCAL_STDERR.with(|slot| {
231                 *slot.borrow_mut() = s.take();
232             });
233         }
234         (None, Some(ref mut err)) => { write(err) }
235         _ => {}
236     }
237 }
238
239
240 #[cfg(not(test))]
241 #[doc(hidden)]
242 #[unstable(feature = "update_panic_count", issue = "0")]
243 pub fn update_panic_count(amt: isize) -> usize {
244     use cell::Cell;
245     thread_local! { static PANIC_COUNT: Cell<usize> = Cell::new(0) }
246
247     PANIC_COUNT.with(|c| {
248         let next = (c.get() as isize + amt) as usize;
249         c.set(next);
250         return next
251     })
252 }
253
254 #[cfg(test)]
255 pub use realstd::rt::update_panic_count;
256
257 /// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
258 pub unsafe fn try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<Any + Send>> {
259     struct Data<F, R> {
260         f: F,
261         r: R,
262     }
263
264     // We do some sketchy operations with ownership here for the sake of
265     // performance. The `Data` structure is never actually fully valid, but
266     // instead it always contains at least one uninitialized field. We can only
267     // pass pointers down to `__rust_maybe_catch_panic` (can't pass objects by
268     // value), so we do all the ownership tracking here manully.
269     //
270     // Note that this is all invalid if any of these functions unwind, but the
271     // whole point of this function is to prevent that! As a result we go
272     // through a transition where:
273     //
274     // * First, only the closure we're going to call is initialized. The return
275     //   value is uninitialized.
276     // * When we make the function call, the `do_call` function below, we take
277     //   ownership of the function pointer, replacing it with uninitialized
278     //   data. At this point the `Data` structure is entirely uninitialized, but
279     //   it won't drop due to an unwind because it's owned on the other side of
280     //   the catch panic.
281     // * If the closure successfully returns, we write the return value into the
282     //   data's return slot. Note that `ptr::write` is used as it's overwriting
283     //   uninitialized data.
284     // * Finally, when we come back out of the `__rust_maybe_catch_panic` we're
285     //   in one of two states:
286     //
287     //      1. The closure didn't panic, in which case the return value was
288     //         filled in. We have to be careful to `forget` the closure,
289     //         however, as ownership was passed to the `do_call` function.
290     //      2. The closure panicked, in which case the return value wasn't
291     //         filled in. In this case the entire `data` structure is invalid,
292     //         so we forget the entire thing.
293     //
294     // Once we stack all that together we should have the "most efficient'
295     // method of calling a catch panic whilst juggling ownership.
296     let mut any_data = 0;
297     let mut any_vtable = 0;
298     let mut data = Data {
299         f: f,
300         r: mem::uninitialized(),
301     };
302
303     let r = __rust_maybe_catch_panic(do_call::<F, R>,
304                                      &mut data as *mut _ as *mut u8,
305                                      &mut any_data,
306                                      &mut any_vtable);
307
308     return if r == 0 {
309         let Data { f, r } = data;
310         mem::forget(f);
311         debug_assert!(update_panic_count(0) == 0);
312         Ok(r)
313     } else {
314         mem::forget(data);
315         update_panic_count(-1);
316         debug_assert!(update_panic_count(0) == 0);
317         Err(mem::transmute(raw::TraitObject {
318             data: any_data as *mut _,
319             vtable: any_vtable as *mut _,
320         }))
321     };
322
323     fn do_call<F: FnOnce() -> R, R>(data: *mut u8) {
324         unsafe {
325             let data = data as *mut Data<F, R>;
326             let f = ptr::read(&mut (*data).f);
327             ptr::write(&mut (*data).r, f());
328         }
329     }
330 }
331
332 /// Determines whether the current thread is unwinding because of panic.
333 pub fn panicking() -> bool {
334     update_panic_count(0) != 0
335 }
336
337 /// Entry point of panic from the libcore crate.
338 #[cfg(not(test))]
339 #[lang = "panic_fmt"]
340 #[unwind]
341 pub extern fn rust_begin_panic(msg: fmt::Arguments,
342                                file: &'static str,
343                                line: u32) -> ! {
344     begin_panic_fmt(&msg, &(file, line))
345 }
346
347 /// The entry point for panicking with a formatted message.
348 ///
349 /// This is designed to reduce the amount of code required at the call
350 /// site as much as possible (so that `panic!()` has as low an impact
351 /// on (e.g.) the inlining of other functions as possible), by moving
352 /// the actual formatting into this shared place.
353 #[unstable(feature = "libstd_sys_internals",
354            reason = "used by the panic! macro",
355            issue = "0")]
356 #[inline(never)] #[cold]
357 pub fn begin_panic_fmt(msg: &fmt::Arguments,
358                        file_line: &(&'static str, u32)) -> ! {
359     use fmt::Write;
360
361     // We do two allocations here, unfortunately. But (a) they're
362     // required with the current scheme, and (b) we don't handle
363     // panic + OOM properly anyway (see comment in begin_panic
364     // below).
365
366     let mut s = String::new();
367     let _ = s.write_fmt(*msg);
368     begin_panic(s, file_line)
369 }
370
371 /// This is the entry point of panicking for panic!() and assert!().
372 #[unstable(feature = "libstd_sys_internals",
373            reason = "used by the panic! macro",
374            issue = "0")]
375 #[inline(never)] #[cold] // avoid code bloat at the call sites as much as possible
376 pub fn begin_panic<M: Any + Send>(msg: M, file_line: &(&'static str, u32)) -> ! {
377     // Note that this should be the only allocation performed in this code path.
378     // Currently this means that panic!() on OOM will invoke this code path,
379     // but then again we're not really ready for panic on OOM anyway. If
380     // we do start doing this, then we should propagate this allocation to
381     // be performed in the parent of this thread instead of the thread that's
382     // panicking.
383
384     rust_panic_with_hook(Box::new(msg), file_line)
385 }
386
387 /// Executes the primary logic for a panic, including checking for recursive
388 /// panics and panic hooks.
389 ///
390 /// This is the entry point or panics from libcore, formatted panics, and
391 /// `Box<Any>` panics. Here we'll verify that we're not panicking recursively,
392 /// run panic hooks, and then delegate to the actual implementation of panics.
393 #[inline(never)]
394 #[cold]
395 fn rust_panic_with_hook(msg: Box<Any + Send>,
396                         file_line: &(&'static str, u32)) -> ! {
397     let (file, line) = *file_line;
398
399     let panics = update_panic_count(1);
400
401     // If this is the third nested call (e.g. panics == 2, this is 0-indexed),
402     // the panic hook probably triggered the last panic, otherwise the
403     // double-panic check would have aborted the process. In this case abort the
404     // process real quickly as we don't want to try calling it again as it'll
405     // probably just panic again.
406     if panics > 2 {
407         util::dumb_print(format_args!("thread panicked while processing \
408                                        panic. aborting.\n"));
409         unsafe { intrinsics::abort() }
410     }
411
412     unsafe {
413         let info = PanicInfo {
414             payload: &*msg,
415             location: Location {
416                 file: file,
417                 line: line,
418             },
419         };
420         HOOK_LOCK.read();
421         match HOOK {
422             Hook::Default => default_hook(&info),
423             Hook::Custom(ptr) => (*ptr)(&info),
424         }
425         HOOK_LOCK.read_unlock();
426     }
427
428     if panics > 1 {
429         // If a thread panics while it's already unwinding then we
430         // have limited options. Currently our preference is to
431         // just abort. In the future we may consider resuming
432         // unwinding or otherwise exiting the thread cleanly.
433         util::dumb_print(format_args!("thread panicked while panicking. \
434                                        aborting.\n"));
435         unsafe { intrinsics::abort() }
436     }
437
438     rust_panic(msg)
439 }
440
441 /// Shim around rust_panic. Called by resume_unwind.
442 pub fn update_count_then_panic(msg: Box<Any + Send>) -> ! {
443     update_panic_count(1);
444     rust_panic(msg)
445 }
446
447 /// A private no-mangle function on which to slap yer breakpoints.
448 #[no_mangle]
449 #[allow(private_no_mangle_fns)] // yes we get it, but we like breakpoints
450 pub fn rust_panic(msg: Box<Any + Send>) -> ! {
451     let code = unsafe {
452         let obj = mem::transmute::<_, raw::TraitObject>(msg);
453         __rust_start_panic(obj.data as usize, obj.vtable as usize)
454     };
455     rtabort!("failed to initiate panic, error {}", code)
456 }