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