core/panic/
panic_info.rs

1#[cfg(not(feature = "ferrocene_certified"))]
2use crate::fmt::{self, Display};
3use crate::panic::Location;
4use crate::panicking::PanicFmt;
5
6/// A struct providing information about a panic.
7///
8/// A `PanicInfo` structure is passed to the panic handler defined by `#[panic_handler]`.
9///
10/// For the type used by the panic hook mechanism in `std`, see [`std::panic::PanicHookInfo`].
11///
12/// [`std::panic::PanicHookInfo`]: ../../std/panic/struct.PanicHookInfo.html
13#[lang = "panic_info"]
14#[stable(feature = "panic_hooks", since = "1.10.0")]
15#[cfg_attr(not(feature = "ferrocene_certified"), derive(Debug))]
16pub struct PanicInfo<'a> {
17    #[cfg_attr(feature = "ferrocene_certified", expect(dead_code))]
18    message: &'a PanicFmt<'a>,
19    location: &'a Location<'a>,
20    #[cfg(not(feature = "ferrocene_certified"))]
21    can_unwind: bool,
22    #[cfg(not(feature = "ferrocene_certified"))]
23    force_no_backtrace: bool,
24}
25
26/// A message that was given to the `panic!()` macro.
27///
28/// The [`Display`] implementation of this type will format the message with the arguments
29/// that were given to the `panic!()` macro.
30///
31/// See [`PanicInfo::message`].
32#[stable(feature = "panic_info_message", since = "1.81.0")]
33#[cfg(not(feature = "ferrocene_certified"))]
34pub struct PanicMessage<'a> {
35    message: &'a fmt::Arguments<'a>,
36}
37
38// Ferrocene addition: When `ferrocene_certified` is enabled, `PanicInfo` only holds a reference to
39// a static string with the panic message. This `impl` adds a new builder to reflect that.
40#[cfg(feature = "ferrocene_certified")]
41impl<'a> PanicInfo<'a> {
42    #[inline]
43    pub(crate) fn new(message: &'a PanicFmt<'a>, location: &'a Location<'a>) -> Self {
44        PanicInfo { message, location }
45    }
46}
47
48impl<'a> PanicInfo<'a> {
49    #[inline]
50    #[cfg(not(feature = "ferrocene_certified"))]
51    pub(crate) fn new(
52        // Ferrocene annotation: Replace `fmt::Arguments` by the `PanicFmt` alias.
53        message: &'a PanicFmt<'a>,
54        location: &'a Location<'a>,
55        can_unwind: bool,
56        force_no_backtrace: bool,
57    ) -> Self {
58        PanicInfo { location, message, can_unwind, force_no_backtrace }
59    }
60
61    /// The message that was given to the `panic!` macro.
62    ///
63    /// # Example
64    ///
65    /// The type returned by this method implements `Display`, so it can
66    /// be passed directly to [`write!()`] and similar macros.
67    ///
68    /// [`write!()`]: core::write
69    ///
70    /// ```ignore (no_std)
71    /// #[panic_handler]
72    /// fn panic_handler(panic_info: &PanicInfo<'_>) -> ! {
73    ///     write!(DEBUG_OUTPUT, "panicked: {}", panic_info.message());
74    ///     loop {}
75    /// }
76    /// ```
77    #[must_use]
78    #[stable(feature = "panic_info_message", since = "1.81.0")]
79    #[cfg(not(feature = "ferrocene_certified"))]
80    pub fn message(&self) -> PanicMessage<'_> {
81        PanicMessage { message: self.message }
82    }
83
84    /// Returns information about the location from which the panic originated,
85    /// if available.
86    ///
87    /// This method will currently always return [`Some`], but this may change
88    /// in future versions.
89    ///
90    /// # Examples
91    ///
92    /// ```should_panic
93    /// use std::panic;
94    ///
95    /// panic::set_hook(Box::new(|panic_info| {
96    ///     if let Some(location) = panic_info.location() {
97    ///         println!("panic occurred in file '{}' at line {}",
98    ///             location.file(),
99    ///             location.line(),
100    ///         );
101    ///     } else {
102    ///         println!("panic occurred but can't get location information...");
103    ///     }
104    /// }));
105    ///
106    /// panic!("Normal panic");
107    /// ```
108    #[must_use]
109    #[stable(feature = "panic_hooks", since = "1.10.0")]
110    pub fn location(&self) -> Option<&Location<'_>> {
111        // NOTE: If this is changed to sometimes return None,
112        // deal with that case in std::panicking::default_hook and core::panicking::panic_fmt.
113        Some(&self.location)
114    }
115
116    /// Returns the payload associated with the panic.
117    ///
118    /// On this type, `core::panic::PanicInfo`, this method never returns anything useful.
119    /// It only exists because of compatibility with [`std::panic::PanicHookInfo`],
120    /// which used to be the same type.
121    ///
122    /// See [`std::panic::PanicHookInfo::payload`].
123    ///
124    /// [`std::panic::PanicHookInfo`]: ../../std/panic/struct.PanicHookInfo.html
125    /// [`std::panic::PanicHookInfo::payload`]: ../../std/panic/struct.PanicHookInfo.html#method.payload
126    #[deprecated(since = "1.81.0", note = "this never returns anything useful")]
127    #[stable(feature = "panic_hooks", since = "1.10.0")]
128    #[allow(deprecated, deprecated_in_future)]
129    #[cfg(not(feature = "ferrocene_certified"))]
130    pub fn payload(&self) -> &(dyn crate::any::Any + Send) {
131        struct NoPayload;
132        &NoPayload
133    }
134
135    /// Returns whether the panic handler is allowed to unwind the stack from
136    /// the point where the panic occurred.
137    ///
138    /// This is true for most kinds of panics with the exception of panics
139    /// caused by trying to unwind out of a `Drop` implementation or a function
140    /// whose ABI does not support unwinding.
141    ///
142    /// It is safe for a panic handler to unwind even when this function returns
143    /// false, however this will simply cause the panic handler to be called
144    /// again.
145    #[must_use]
146    #[unstable(feature = "panic_can_unwind", issue = "92988")]
147    #[cfg(not(feature = "ferrocene_certified"))]
148    pub fn can_unwind(&self) -> bool {
149        self.can_unwind
150    }
151
152    #[unstable(
153        feature = "panic_internals",
154        reason = "internal details of the implementation of the `panic!` and related macros",
155        issue = "none"
156    )]
157    #[doc(hidden)]
158    #[inline]
159    #[cfg(not(feature = "ferrocene_certified"))]
160    pub fn force_no_backtrace(&self) -> bool {
161        self.force_no_backtrace
162    }
163}
164
165#[stable(feature = "panic_hook_display", since = "1.26.0")]
166#[cfg(not(feature = "ferrocene_certified"))]
167impl Display for PanicInfo<'_> {
168    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
169        formatter.write_str("panicked at ")?;
170        self.location.fmt(formatter)?;
171        formatter.write_str(":\n")?;
172        formatter.write_fmt(*self.message)?;
173        Ok(())
174    }
175}
176
177#[cfg(not(feature = "ferrocene_certified"))]
178impl<'a> PanicMessage<'a> {
179    /// Gets the formatted message, if it has no arguments to be formatted at runtime.
180    ///
181    /// This can be used to avoid allocations in some cases.
182    ///
183    /// # Guarantees
184    ///
185    /// For `panic!("just a literal")`, this function is guaranteed to
186    /// return `Some("just a literal")`.
187    ///
188    /// For most cases with placeholders, this function will return `None`.
189    ///
190    /// See [`fmt::Arguments::as_str`] for details.
191    #[stable(feature = "panic_info_message", since = "1.81.0")]
192    #[rustc_const_stable(feature = "const_arguments_as_str", since = "1.84.0")]
193    #[must_use]
194    #[inline]
195    pub const fn as_str(&self) -> Option<&'static str> {
196        self.message.as_str()
197    }
198}
199
200#[stable(feature = "panic_info_message", since = "1.81.0")]
201#[cfg(not(feature = "ferrocene_certified"))]
202impl Display for PanicMessage<'_> {
203    #[inline]
204    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
205        formatter.write_fmt(*self.message)
206    }
207}
208
209#[stable(feature = "panic_info_message", since = "1.81.0")]
210#[cfg(not(feature = "ferrocene_certified"))]
211impl fmt::Debug for PanicMessage<'_> {
212    #[inline]
213    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
214        formatter.write_fmt(*self.message)
215    }
216}