]> git.proxmox.com Git - rustc.git/blame - library/std/src/panicking.rs
New upstream version 1.54.0+dfsg1
[rustc.git] / library / std / src / 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
3dfed10e
XL
10#![deny(unsafe_op_in_unsafe_fn)]
11
dfeec247 12use core::panic::{BoxMeUp, Location, PanicInfo};
532ac7d7
XL
13
14use crate::any::Any;
15use crate::fmt;
16use crate::intrinsics;
e74abb32 17use crate::mem::{self, ManuallyDrop};
dfeec247 18use crate::process;
e74abb32 19use crate::sync::atomic::{AtomicBool, Ordering};
532ac7d7 20use crate::sys::stdio::panic_output;
dfeec247 21use crate::sys_common::backtrace::{self, RustBacktrace};
17df50a5
XL
22use crate::sys_common::rwlock::StaticRWLock;
23use crate::sys_common::thread_info;
532ac7d7
XL
24use crate::thread;
25
26#[cfg(not(test))]
fc512014 27use crate::io::set_output_capture;
532ac7d7
XL
28// make sure to use the stderr output configured
29// by libtest in the real copy of std
30#[cfg(test)]
fc512014 31use realstd::io::set_output_capture;
1a4d82fc 32
a7813a04
XL
33// Binary interface to the panic runtime that the standard library depends on.
34//
35// The standard library is tagged with `#![needs_panic_runtime]` (introduced in
36// RFC 1513) to indicate that it requires some other crate tagged with
37// `#![panic_runtime]` to exist somewhere. Each panic runtime is intended to
38// implement these symbols (with the same signatures) so we can get matched up
39// to them.
40//
41// One day this may look a little less ad-hoc with the compiler helping out to
42// hook up these functions, but it is not this day!
43#[allow(improper_ctypes)]
dfeec247 44extern "C" {
ba9703b0 45 fn __rust_panic_cleanup(payload: *mut u8) -> *mut (dyn Any + Send + 'static);
60c5eb7d 46
5869c6ff
XL
47 /// `payload` is passed through another layer of raw pointers as `&mut dyn Trait` is not
48 /// FFI-safe. `BoxMeUp` lazily performs allocation only when needed (this avoids allocations
49 /// when using the "abort" panic runtime).
83c7162d 50 #[unwind(allowed)]
5869c6ff 51 fn __rust_start_panic(payload: *mut &mut dyn BoxMeUp) -> u32;
a7813a04
XL
52}
53
dfeec247
XL
54/// This function is called by the panic runtime if FFI code catches a Rust
55/// panic but doesn't rethrow it. We don't support this case since it messes
56/// with our panic count.
57#[cfg(not(test))]
58#[rustc_std_internal_symbol]
59extern "C" fn __rust_drop_panic() -> ! {
60 rtabort!("Rust panics must be rethrown");
61}
62
1b1a35ee
XL
63/// This function is called by the panic runtime if it catches an exception
64/// object which does not correspond to a Rust panic.
65#[cfg(not(test))]
66#[rustc_std_internal_symbol]
67extern "C" fn __rust_foreign_exception() -> ! {
68 rtabort!("Rust cannot catch foreign exceptions");
69}
70
9cc50fc6 71#[derive(Copy, Clone)]
54a0048b 72enum Hook {
9cc50fc6 73 Default,
532ac7d7 74 Custom(*mut (dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send)),
9cc50fc6
SL
75}
76
17df50a5 77static HOOK_LOCK: StaticRWLock = StaticRWLock::new();
54a0048b 78static mut HOOK: Hook = Hook::Default;
9cc50fc6 79
54a0048b 80/// Registers a custom panic hook, replacing any that was previously registered.
9cc50fc6 81///
a7813a04
XL
82/// The panic hook is invoked when a thread panics, but before the panic runtime
83/// is invoked. As such, the hook will run with both the aborting and unwinding
84/// runtimes. The default hook prints a message to standard error and generates
85/// a backtrace if requested, but this behavior can be customized with the
83c7162d
XL
86/// `set_hook` and [`take_hook`] functions.
87///
88/// [`take_hook`]: ./fn.take_hook.html
9cc50fc6 89///
54a0048b 90/// The hook is provided with a `PanicInfo` struct which contains information
9cc50fc6
SL
91/// about the origin of the panic, including the payload passed to `panic!` and
92/// the source code location from which the panic originated.
93///
54a0048b 94/// The panic hook is a global resource.
9cc50fc6
SL
95///
96/// # Panics
97///
98/// Panics if called from a panicking thread.
9e0c209e
SL
99///
100/// # Examples
101///
102/// The following will print "Custom panic hook":
103///
104/// ```should_panic
105/// use std::panic;
106///
107/// panic::set_hook(Box::new(|_| {
108/// println!("Custom panic hook");
109/// }));
110///
111/// panic!("Normal panic");
112/// ```
a7813a04 113#[stable(feature = "panic_hooks", since = "1.10.0")]
532ac7d7 114pub fn set_hook(hook: Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send>) {
9cc50fc6 115 if thread::panicking() {
54a0048b 116 panic!("cannot modify the panic hook from a panicking thread");
9cc50fc6
SL
117 }
118
9cc50fc6 119 unsafe {
17df50a5 120 let guard = HOOK_LOCK.write();
54a0048b
SL
121 let old_hook = HOOK;
122 HOOK = Hook::Custom(Box::into_raw(hook));
17df50a5 123 drop(guard);
9cc50fc6 124
54a0048b 125 if let Hook::Custom(ptr) = old_hook {
dfeec247
XL
126 #[allow(unused_must_use)]
127 {
dc9dc135
XL
128 Box::from_raw(ptr);
129 }
9cc50fc6
SL
130 }
131 }
132}
133
54a0048b 134/// Unregisters the current panic hook, returning it.
9cc50fc6 135///
83c7162d
XL
136/// *See also the function [`set_hook`].*
137///
138/// [`set_hook`]: ./fn.set_hook.html
139///
54a0048b 140/// If no custom hook is registered, the default hook will be returned.
9cc50fc6
SL
141///
142/// # Panics
143///
144/// Panics if called from a panicking thread.
9e0c209e
SL
145///
146/// # Examples
147///
148/// The following will print "Normal panic":
149///
150/// ```should_panic
151/// use std::panic;
152///
153/// panic::set_hook(Box::new(|_| {
154/// println!("Custom panic hook");
155/// }));
156///
157/// let _ = panic::take_hook();
158///
159/// panic!("Normal panic");
160/// ```
a7813a04 161#[stable(feature = "panic_hooks", since = "1.10.0")]
532ac7d7 162pub fn take_hook() -> Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send> {
9cc50fc6 163 if thread::panicking() {
54a0048b 164 panic!("cannot modify the panic hook from a panicking thread");
9cc50fc6
SL
165 }
166
167 unsafe {
17df50a5 168 let guard = HOOK_LOCK.write();
54a0048b
SL
169 let hook = HOOK;
170 HOOK = Hook::Default;
17df50a5 171 drop(guard);
9cc50fc6 172
54a0048b
SL
173 match hook {
174 Hook::Default => Box::new(default_hook),
476ff2be 175 Hook::Custom(ptr) => Box::from_raw(ptr),
9cc50fc6
SL
176 }
177 }
178}
179
532ac7d7 180fn default_hook(info: &PanicInfo<'_>) {
9cc50fc6
SL
181 // If this is a double panic, make sure that we print a backtrace
182 // for this panic. Otherwise only print it if logging is enabled.
17df50a5 183 let backtrace_env = if panic_count::get_count() >= 2 {
3dfed10e 184 RustBacktrace::Print(crate::backtrace_rs::PrintFmt::Full)
e1599b0c 185 } else {
e74abb32 186 backtrace::rust_backtrace_env()
5bcae85e 187 };
9cc50fc6 188
dc9dc135
XL
189 // The current implementation always returns `Some`.
190 let location = info.location().unwrap();
9cc50fc6 191
0531ce1d 192 let msg = match info.payload().downcast_ref::<&'static str>() {
1a4d82fc 193 Some(s) => *s,
0531ce1d 194 None => match info.payload().downcast_ref::<String>() {
85aaf69f 195 Some(s) => &s[..],
17df50a5 196 None => "Box<dyn Any>",
dfeec247 197 },
1a4d82fc 198 };
d9579d0f
AL
199 let thread = thread_info::current_thread();
200 let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");
b039eaaf 201
532ac7d7 202 let write = |err: &mut dyn crate::io::Write| {
dfeec247 203 let _ = writeln!(err, "thread '{}' panicked at '{}', {}", name, msg, location);
7453a54e 204
e74abb32 205 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
5bcae85e 206
e74abb32
XL
207 match backtrace_env {
208 RustBacktrace::Print(format) => drop(backtrace::print(err, format)),
209 RustBacktrace::Disabled => {}
210 RustBacktrace::RuntimeDisabled => {
211 if FIRST_PANIC.swap(false, Ordering::SeqCst) {
dfeec247
XL
212 let _ = writeln!(
213 err,
f035d41b 214 "note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace"
dfeec247 215 );
e74abb32 216 }
5bcae85e 217 }
b039eaaf
SL
218 }
219 };
220
fc512014
XL
221 if let Some(local) = set_output_capture(None) {
222 write(&mut *local.lock().unwrap_or_else(|e| e.into_inner()));
223 set_output_capture(Some(local));
0731742a
XL
224 } else if let Some(mut out) = panic_output() {
225 write(&mut out);
1a4d82fc 226 }
b039eaaf 227}
1a4d82fc 228
5bcae85e
SL
229#[cfg(not(test))]
230#[doc(hidden)]
dfeec247 231#[unstable(feature = "update_panic_count", issue = "none")]
f035d41b 232pub mod panic_count {
532ac7d7 233 use crate::cell::Cell;
f035d41b
XL
234 use crate::sync::atomic::{AtomicUsize, Ordering};
235
17df50a5
XL
236 pub const ALWAYS_ABORT_FLAG: usize = 1 << (usize::BITS - 1);
237
f035d41b
XL
238 // Panic count for the current thread.
239 thread_local! { static LOCAL_PANIC_COUNT: Cell<usize> = Cell::new(0) }
240
241 // Sum of panic counts from all threads. The purpose of this is to have
242 // a fast path in `is_zero` (which is used by `panicking`). In any particular
243 // thread, if that thread currently views `GLOBAL_PANIC_COUNT` as being zero,
244 // then `LOCAL_PANIC_COUNT` in that thread is zero. This invariant holds before
245 // and after increase and decrease, but not necessarily during their execution.
17df50a5
XL
246 //
247 // Additionally, the top bit of GLOBAL_PANIC_COUNT (GLOBAL_ALWAYS_ABORT_FLAG)
248 // records whether panic::always_abort() has been called. This can only be
249 // set, never cleared.
250 //
251 // This could be viewed as a struct containing a single bit and an n-1-bit
252 // value, but if we wrote it like that it would be more than a single word,
253 // and even a newtype around usize would be clumsy because we need atomics.
254 // But we use such a tuple for the return type of increase().
255 //
256 // Stealing a bit is fine because it just amounts to assuming that each
257 // panicking thread consumes at least 2 bytes of address space.
f035d41b
XL
258 static GLOBAL_PANIC_COUNT: AtomicUsize = AtomicUsize::new(0);
259
17df50a5
XL
260 pub fn increase() -> (bool, usize) {
261 (
262 GLOBAL_PANIC_COUNT.fetch_add(1, Ordering::Relaxed) & ALWAYS_ABORT_FLAG != 0,
263 LOCAL_PANIC_COUNT.with(|c| {
264 let next = c.get() + 1;
265 c.set(next);
266 next
267 }),
268 )
f035d41b
XL
269 }
270
17df50a5 271 pub fn decrease() {
f035d41b
XL
272 GLOBAL_PANIC_COUNT.fetch_sub(1, Ordering::Relaxed);
273 LOCAL_PANIC_COUNT.with(|c| {
274 let next = c.get() - 1;
275 c.set(next);
276 next
17df50a5
XL
277 });
278 }
279
280 pub fn set_always_abort() {
281 GLOBAL_PANIC_COUNT.fetch_or(ALWAYS_ABORT_FLAG, Ordering::Relaxed);
f035d41b
XL
282 }
283
17df50a5
XL
284 // Disregards ALWAYS_ABORT_FLAG
285 pub fn get_count() -> usize {
f035d41b
XL
286 LOCAL_PANIC_COUNT.with(|c| c.get())
287 }
5bcae85e 288
17df50a5 289 // Disregards ALWAYS_ABORT_FLAG
f035d41b 290 #[inline]
17df50a5
XL
291 pub fn count_is_zero() -> bool {
292 if GLOBAL_PANIC_COUNT.load(Ordering::Relaxed) & !ALWAYS_ABORT_FLAG == 0 {
f035d41b
XL
293 // Fast path: if `GLOBAL_PANIC_COUNT` is zero, all threads
294 // (including the current one) will have `LOCAL_PANIC_COUNT`
295 // equal to zero, so TLS access can be avoided.
296 //
297 // In terms of performance, a relaxed atomic load is similar to a normal
298 // aligned memory read (e.g., a mov instruction in x86), but with some
299 // compiler optimization restrictions. On the other hand, a TLS access
300 // might require calling a non-inlinable function (such as `__tls_get_addr`
301 // when using the GD TLS model).
302 true
303 } else {
304 is_zero_slow_path()
305 }
306 }
307
308 // Slow path is in a separate function to reduce the amount of code
309 // inlined from `is_zero`.
310 #[inline(never)]
311 #[cold]
312 fn is_zero_slow_path() -> bool {
313 LOCAL_PANIC_COUNT.with(|c| c.get() == 0)
314 }
5bcae85e
SL
315}
316
317#[cfg(test)]
f035d41b 318pub use realstd::rt::panic_count;
5bcae85e 319
a7813a04 320/// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
532ac7d7 321pub unsafe fn r#try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>> {
8bb4bdeb 322 union Data<F, R> {
e74abb32
XL
323 f: ManuallyDrop<F>,
324 r: ManuallyDrop<R>,
ba9703b0 325 p: ManuallyDrop<Box<dyn Any + Send>>,
5bcae85e 326 }
a7813a04 327
5bcae85e 328 // We do some sketchy operations with ownership here for the sake of
ba9703b0
XL
329 // performance. We can only pass pointers down to `do_call` (can't pass
330 // objects by value), so we do all the ownership tracking here manually
331 // using a union.
5bcae85e 332 //
8bb4bdeb 333 // We go through a transition where:
5bcae85e 334 //
ba9703b0 335 // * First, we set the data field `f` to be the argumentless closure that we're going to call.
5bcae85e 336 // * When we make the function call, the `do_call` function below, we take
ba9703b0 337 // ownership of the function pointer. At this point the `data` union is
8bb4bdeb 338 // entirely uninitialized.
5bcae85e 339 // * If the closure successfully returns, we write the return value into the
ba9703b0
XL
340 // data's return slot (field `r`).
341 // * If the closure panics (`do_catch` below), we write the panic payload into field `p`.
342 // * Finally, when we come back out of the `try` intrinsic we're
5bcae85e
SL
343 // in one of two states:
344 //
345 // 1. The closure didn't panic, in which case the return value was
ba9703b0
XL
346 // filled in. We move it out of `data.r` and return it.
347 // 2. The closure panicked, in which case the panic payload was
348 // filled in. We move it out of `data.p` and return it.
5bcae85e
SL
349 //
350 // Once we stack all that together we should have the "most efficient'
351 // method of calling a catch panic whilst juggling ownership.
dfeec247 352 let mut data = Data { f: ManuallyDrop::new(f) };
b039eaaf 353
ba9703b0 354 let data_ptr = &mut data as *mut _ as *mut u8;
3dfed10e
XL
355 // SAFETY:
356 //
357 // Access to the union's fields: this is `std` and we know that the `r#try`
358 // intrinsic fills in the `r` or `p` union field based on its return value.
359 //
360 // The call to `intrinsics::r#try` is made safe by:
361 // - `do_call`, the first argument, can be called with the initial `data_ptr`.
362 // - `do_catch`, the second argument, can be called with the `data_ptr` as well.
363 // See their safety preconditions for more informations
364 unsafe {
365 return if intrinsics::r#try(do_call::<F, R>, data_ptr, do_catch::<F, R>) == 0 {
366 Ok(ManuallyDrop::into_inner(data.r))
367 } else {
368 Err(ManuallyDrop::into_inner(data.p))
369 };
370 }
a7813a04 371
ba9703b0
XL
372 // We consider unwinding to be rare, so mark this function as cold. However,
373 // do not mark it no-inline -- that decision is best to leave to the
374 // optimizer (in most cases this function is not inlined even as a normal,
375 // non-cold function, though, as of the writing of this comment).
376 #[cold]
377 unsafe fn cleanup(payload: *mut u8) -> Box<dyn Any + Send + 'static> {
3dfed10e
XL
378 // SAFETY: The whole unsafe block hinges on a correct implementation of
379 // the panic handler `__rust_panic_cleanup`. As such we can only
380 // assume it returns the correct thing for `Box::from_raw` to work
381 // without undefined behavior.
382 let obj = unsafe { Box::from_raw(__rust_panic_cleanup(payload)) };
f035d41b 383 panic_count::decrease();
ba9703b0
XL
384 obj
385 }
386
3dfed10e
XL
387 // SAFETY:
388 // data must be non-NUL, correctly aligned, and a pointer to a `Data<F, R>`
389 // Its must contains a valid `f` (type: F) value that can be use to fill
390 // `data.r`.
391 //
392 // This function cannot be marked as `unsafe` because `intrinsics::r#try`
393 // expects normal function pointers.
f9f354fc 394 #[inline]
5bcae85e 395 fn do_call<F: FnOnce() -> R, R>(data: *mut u8) {
3dfed10e 396 // SAFETY: this is the responsibilty of the caller, see above.
5bcae85e
SL
397 unsafe {
398 let data = data as *mut Data<F, R>;
e74abb32
XL
399 let data = &mut (*data);
400 let f = ManuallyDrop::take(&mut data.f);
401 data.r = ManuallyDrop::new(f());
5bcae85e 402 }
a7813a04 403 }
ba9703b0
XL
404
405 // We *do* want this part of the catch to be inlined: this allows the
406 // compiler to properly track accesses to the Data union and optimize it
407 // away most of the time.
3dfed10e
XL
408 //
409 // SAFETY:
410 // data must be non-NUL, correctly aligned, and a pointer to a `Data<F, R>`
411 // Since this uses `cleanup` it also hinges on a correct implementation of
412 // `__rustc_panic_cleanup`.
413 //
414 // This function cannot be marked as `unsafe` because `intrinsics::r#try`
415 // expects normal function pointers.
ba9703b0
XL
416 #[inline]
417 fn do_catch<F: FnOnce() -> R, R>(data: *mut u8, payload: *mut u8) {
3dfed10e
XL
418 // SAFETY: this is the responsibilty of the caller, see above.
419 //
420 // When `__rustc_panic_cleaner` is correctly implemented we can rely
421 // on `obj` being the correct thing to pass to `data.p` (after wrapping
422 // in `ManuallyDrop`).
ba9703b0
XL
423 unsafe {
424 let data = data as *mut Data<F, R>;
425 let data = &mut (*data);
426 let obj = cleanup(payload);
427 data.p = ManuallyDrop::new(obj);
428 }
429 }
a7813a04
XL
430}
431
432/// Determines whether the current thread is unwinding because of panic.
f035d41b 433#[inline]
a7813a04 434pub fn panicking() -> bool {
17df50a5 435 !panic_count::count_is_zero()
a7813a04
XL
436}
437
a7813a04
XL
438/// The entry point for panicking with a formatted message.
439///
440/// This is designed to reduce the amount of code required at the call
441/// site as much as possible (so that `panic!()` has as low an impact
442/// on (e.g.) the inlining of other functions as possible), by moving
443/// the actual formatting into this shared place.
dfeec247 444#[unstable(feature = "libstd_sys_internals", reason = "used by the panic! macro", issue = "none")]
a1dfa0c6
XL
445#[cold]
446// If panic_immediate_abort, inline the abort call,
447// otherwise avoid inlining because of it is cold path.
dfeec247
XL
448#[cfg_attr(not(feature = "panic_immediate_abort"), track_caller)]
449#[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
450#[cfg_attr(feature = "panic_immediate_abort", inline)]
451pub fn begin_panic_fmt(msg: &fmt::Arguments<'_>) -> ! {
a1dfa0c6 452 if cfg!(feature = "panic_immediate_abort") {
f035d41b 453 intrinsics::abort()
a1dfa0c6
XL
454 }
455
dfeec247 456 let info = PanicInfo::internal_constructor(Some(msg), Location::caller());
60c5eb7d 457 begin_panic_handler(&info)
94b46f34 458}
83c7162d 459
60c5eb7d
XL
460/// Entry point of panics from the libcore crate (`panic_impl` lang item).
461#[cfg_attr(not(test), panic_handler)]
462#[unwind(allowed)]
463pub fn begin_panic_handler(info: &PanicInfo<'_>) -> ! {
8faf50e0
XL
464 struct PanicPayload<'a> {
465 inner: &'a fmt::Arguments<'a>,
466 string: Option<String>,
83c7162d
XL
467 }
468
8faf50e0
XL
469 impl<'a> PanicPayload<'a> {
470 fn new(inner: &'a fmt::Arguments<'a>) -> PanicPayload<'a> {
471 PanicPayload { inner, string: None }
472 }
83c7162d 473
8faf50e0 474 fn fill(&mut self) -> &mut String {
532ac7d7 475 use crate::fmt::Write;
83c7162d 476
8faf50e0 477 let inner = self.inner;
60c5eb7d 478 // Lazily, the first time this gets called, run the actual string formatting.
8faf50e0
XL
479 self.string.get_or_insert_with(|| {
480 let mut s = String::new();
481 drop(s.write_fmt(*inner));
482 s
483 })
484 }
94b46f34 485 }
83c7162d 486
8faf50e0 487 unsafe impl<'a> BoxMeUp for PanicPayload<'a> {
60c5eb7d 488 fn take_box(&mut self) -> *mut (dyn Any + Send) {
dfeec247
XL
489 // We do two allocations here, unfortunately. But (a) they're required with the current
490 // scheme, and (b) we don't handle panic + OOM properly anyway (see comment in
491 // begin_panic below).
416331ca 492 let contents = mem::take(self.fill());
8faf50e0
XL
493 Box::into_raw(Box::new(contents))
494 }
041b39d2 495
8faf50e0
XL
496 fn get(&mut self) -> &(dyn Any + Send) {
497 self.fill()
498 }
499 }
94b46f34 500
29967ef6
XL
501 struct StrPanicPayload(&'static str);
502
503 unsafe impl BoxMeUp for StrPanicPayload {
504 fn take_box(&mut self) -> *mut (dyn Any + Send) {
505 Box::into_raw(Box::new(self.0))
506 }
507
508 fn get(&mut self) -> &(dyn Any + Send) {
509 &self.0
510 }
511 }
512
94b46f34
XL
513 let loc = info.location().unwrap(); // The current implementation always returns Some
514 let msg = info.message().unwrap(); // The current implementation always returns Some
3dfed10e 515 crate::sys_common::backtrace::__rust_end_short_backtrace(move || {
29967ef6
XL
516 if let Some(msg) = msg.as_str() {
517 rust_panic_with_hook(&mut StrPanicPayload(msg), info.message(), loc);
518 } else {
519 rust_panic_with_hook(&mut PanicPayload::new(msg), info.message(), loc);
520 }
3dfed10e 521 })
94b46f34
XL
522}
523
60c5eb7d
XL
524/// This is the entry point of panicking for the non-format-string variants of
525/// panic!() and assert!(). In particular, this is the only entry point that supports
526/// arbitrary payloads, not just format strings.
dfeec247
XL
527#[unstable(feature = "libstd_sys_internals", reason = "used by the panic! macro", issue = "none")]
528#[cfg_attr(not(test), lang = "begin_panic")]
529// lang item for CTFE panic support
a1dfa0c6
XL
530// never inline unless panic_immediate_abort to avoid code
531// bloat at the call sites as much as possible
dfeec247 532#[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
a1dfa0c6 533#[cold]
dfeec247 534#[track_caller]
74b04a01 535pub fn begin_panic<M: Any + Send>(msg: M) -> ! {
a1dfa0c6 536 if cfg!(feature = "panic_immediate_abort") {
f035d41b 537 intrinsics::abort()
a1dfa0c6
XL
538 }
539
3dfed10e
XL
540 let loc = Location::caller();
541 return crate::sys_common::backtrace::__rust_end_short_backtrace(move || {
542 rust_panic_with_hook(&mut PanicPayload::new(msg), None, loc)
543 });
83c7162d
XL
544
545 struct PanicPayload<A> {
546 inner: Option<A>,
547 }
548
549 impl<A: Send + 'static> PanicPayload<A> {
550 fn new(inner: A) -> PanicPayload<A> {
551 PanicPayload { inner: Some(inner) }
552 }
553 }
554
555 unsafe impl<A: Send + 'static> BoxMeUp for PanicPayload<A> {
60c5eb7d 556 fn take_box(&mut self) -> *mut (dyn Any + Send) {
dfeec247
XL
557 // Note that this should be the only allocation performed in this code path. Currently
558 // this means that panic!() on OOM will invoke this code path, but then again we're not
559 // really ready for panic on OOM anyway. If we do start doing this, then we should
560 // propagate this allocation to be performed in the parent of this thread instead of the
561 // thread that's panicking.
83c7162d 562 let data = match self.inner.take() {
8faf50e0 563 Some(a) => Box::new(a) as Box<dyn Any + Send>,
60c5eb7d 564 None => process::abort(),
83c7162d
XL
565 };
566 Box::into_raw(data)
567 }
568
8faf50e0 569 fn get(&mut self) -> &(dyn Any + Send) {
83c7162d
XL
570 match self.inner {
571 Some(ref a) => a,
60c5eb7d 572 None => process::abort(),
83c7162d
XL
573 }
574 }
575 }
a7813a04
XL
576}
577
83c7162d 578/// Central point for dispatching panics.
a7813a04 579///
83c7162d
XL
580/// Executes the primary logic for a panic, including checking for recursive
581/// panics, panic hooks, and finally dispatching to the panic runtime to either
582/// abort or unwind.
dfeec247
XL
583fn rust_panic_with_hook(
584 payload: &mut dyn BoxMeUp,
585 message: Option<&fmt::Arguments<'_>>,
586 location: &Location<'_>,
587) -> ! {
17df50a5 588 let (must_abort, panics) = panic_count::increase();
a7813a04 589
0731742a 590 // If this is the third nested call (e.g., panics == 2, this is 0-indexed),
a7813a04
XL
591 // the panic hook probably triggered the last panic, otherwise the
592 // double-panic check would have aborted the process. In this case abort the
593 // process real quickly as we don't want to try calling it again as it'll
594 // probably just panic again.
17df50a5
XL
595 if must_abort || panics > 2 {
596 if panics > 2 {
597 // Don't try to print the message in this case
598 // - perhaps that is causing the recursive panics.
599 rtprintpanic!("thread panicked while processing panic. aborting.\n");
600 } else {
601 // Unfortunately, this does not print a backtrace, because creating
602 // a `Backtrace` will allocate, which we must to avoid here.
603 let panicinfo = PanicInfo::internal_constructor(message, location);
604 rtprintpanic!("{}\npanicked after panic::always_abort(), aborting.\n", panicinfo);
605 }
f035d41b 606 intrinsics::abort()
b039eaaf
SL
607 }
608
9cc50fc6 609 unsafe {
dfeec247 610 let mut info = PanicInfo::internal_constructor(message, location);
17df50a5 611 let _guard = HOOK_LOCK.read();
54a0048b 612 match HOOK {
60c5eb7d 613 // Some platforms (like wasm) know that printing to stderr won't ever actually
83c7162d 614 // print anything, and if that's the case we can skip the default
60c5eb7d
XL
615 // hook. Since string formatting happens lazily when calling `payload`
616 // methods, this means we avoid formatting the string at all!
617 // (The panic runtime might still call `payload.take_box()` though and trigger
618 // formatting.)
0731742a 619 Hook::Default if panic_output().is_none() => {}
83c7162d
XL
620 Hook::Default => {
621 info.set_payload(payload.get());
622 default_hook(&info);
623 }
624 Hook::Custom(ptr) => {
625 info.set_payload(payload.get());
626 (*ptr)(&info);
627 }
0731742a 628 };
9cc50fc6 629 }
b039eaaf 630
5bcae85e 631 if panics > 1 {
b039eaaf
SL
632 // If a thread panics while it's already unwinding then we
633 // have limited options. Currently our preference is to
634 // just abort. In the future we may consider resuming
635 // unwinding or otherwise exiting the thread cleanly.
17df50a5 636 rtprintpanic!("thread panicked while panicking. aborting.\n");
f035d41b 637 intrinsics::abort()
1a4d82fc 638 }
a7813a04 639
0531ce1d 640 rust_panic(payload)
a7813a04
XL
641}
642
60c5eb7d
XL
643/// This is the entry point for `resume_unwind`.
644/// It just forwards the payload to the panic runtime.
645pub fn rust_panic_without_hook(payload: Box<dyn Any + Send>) -> ! {
f035d41b 646 panic_count::increase();
83c7162d 647
8faf50e0 648 struct RewrapBox(Box<dyn Any + Send>);
83c7162d
XL
649
650 unsafe impl BoxMeUp for RewrapBox {
60c5eb7d 651 fn take_box(&mut self) -> *mut (dyn Any + Send) {
83c7162d
XL
652 Box::into_raw(mem::replace(&mut self.0, Box::new(())))
653 }
654
8faf50e0 655 fn get(&mut self) -> &(dyn Any + Send) {
83c7162d
XL
656 &*self.0
657 }
658 }
659
60c5eb7d 660 rust_panic(&mut RewrapBox(payload))
5bcae85e
SL
661}
662
0bf4aa26
XL
663/// An unmangled function (through `rustc_std_internal_symbol`) on which to slap
664/// yer breakpoints.
665#[inline(never)]
666#[cfg_attr(not(test), rustc_std_internal_symbol)]
667fn rust_panic(mut msg: &mut dyn BoxMeUp) -> ! {
a7813a04 668 let code = unsafe {
8faf50e0 669 let obj = &mut msg as *mut &mut dyn BoxMeUp;
5869c6ff 670 __rust_start_panic(obj)
a7813a04
XL
671 };
672 rtabort!("failed to initiate panic, error {}", code)
1a4d82fc 673}