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