core/panic/
panic_info.rs

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