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