]> git.lizzy.rs Git - rust.git/blob - library/std/src/panic.rs
Auto merge of #95548 - rcvalle:rust-cfi-2, r=nagisa
[rust.git] / library / std / src / panic.rs
1 //! Panic support in the standard library.
2
3 #![stable(feature = "std_panic", since = "1.9.0")]
4
5 use crate::any::Any;
6 use crate::collections;
7 use crate::panicking;
8 use crate::sync::atomic::{AtomicUsize, Ordering};
9 use crate::sync::{Mutex, RwLock};
10 use crate::thread::Result;
11
12 #[doc(hidden)]
13 #[unstable(feature = "edition_panic", issue = "none", reason = "use panic!() instead")]
14 #[allow_internal_unstable(libstd_sys_internals, const_format_args, core_panic, rt)]
15 #[cfg_attr(not(test), rustc_diagnostic_item = "std_panic_2015_macro")]
16 #[rustc_macro_transparency = "semitransparent"]
17 pub macro panic_2015 {
18     () => ({
19         $crate::rt::begin_panic("explicit panic")
20     }),
21     ($msg:expr $(,)?) => ({
22         $crate::rt::begin_panic($msg)
23     }),
24     // Special-case the single-argument case for const_panic.
25     ("{}", $arg:expr $(,)?) => ({
26         $crate::rt::panic_display(&$arg)
27     }),
28     ($fmt:expr, $($arg:tt)+) => ({
29         $crate::rt::panic_fmt($crate::const_format_args!($fmt, $($arg)+))
30     }),
31 }
32
33 #[doc(hidden)]
34 #[unstable(feature = "edition_panic", issue = "none", reason = "use panic!() instead")]
35 pub use core::panic::panic_2021;
36
37 #[stable(feature = "panic_hooks", since = "1.10.0")]
38 pub use crate::panicking::{set_hook, take_hook};
39
40 #[unstable(feature = "panic_update_hook", issue = "92649")]
41 pub use crate::panicking::update_hook;
42
43 #[stable(feature = "panic_hooks", since = "1.10.0")]
44 pub use core::panic::{Location, PanicInfo};
45
46 #[stable(feature = "catch_unwind", since = "1.9.0")]
47 pub use core::panic::{AssertUnwindSafe, RefUnwindSafe, UnwindSafe};
48
49 /// Panic the current thread with the given message as the panic payload.
50 ///
51 /// The message can be of any (`Any + Send`) type, not just strings.
52 ///
53 /// The message is wrapped in a `Box<'static + Any + Send>`, which can be
54 /// accessed later using [`PanicInfo::payload`].
55 ///
56 /// See the [`panic!`] macro for more information about panicking.
57 #[stable(feature = "panic_any", since = "1.51.0")]
58 #[inline]
59 #[track_caller]
60 pub fn panic_any<M: 'static + Any + Send>(msg: M) -> ! {
61     crate::panicking::begin_panic(msg);
62 }
63
64 #[stable(feature = "catch_unwind", since = "1.9.0")]
65 impl<T: ?Sized> UnwindSafe for Mutex<T> {}
66 #[stable(feature = "catch_unwind", since = "1.9.0")]
67 impl<T: ?Sized> UnwindSafe for RwLock<T> {}
68
69 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
70 impl<T: ?Sized> RefUnwindSafe for Mutex<T> {}
71 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
72 impl<T: ?Sized> RefUnwindSafe for RwLock<T> {}
73
74 // https://github.com/rust-lang/rust/issues/62301
75 #[stable(feature = "hashbrown", since = "1.36.0")]
76 impl<K, V, S> UnwindSafe for collections::HashMap<K, V, S>
77 where
78     K: UnwindSafe,
79     V: UnwindSafe,
80     S: UnwindSafe,
81 {
82 }
83
84 /// Invokes a closure, capturing the cause of an unwinding panic if one occurs.
85 ///
86 /// This function will return `Ok` with the closure's result if the closure
87 /// does not panic, and will return `Err(cause)` if the closure panics. The
88 /// `cause` returned is the object with which panic was originally invoked.
89 ///
90 /// It is currently undefined behavior to unwind from Rust code into foreign
91 /// code, so this function is particularly useful when Rust is called from
92 /// another language (normally C). This can run arbitrary Rust code, capturing a
93 /// panic and allowing a graceful handling of the error.
94 ///
95 /// It is **not** recommended to use this function for a general try/catch
96 /// mechanism. The [`Result`] type is more appropriate to use for functions that
97 /// can fail on a regular basis. Additionally, this function is not guaranteed
98 /// to catch all panics, see the "Notes" section below.
99 ///
100 /// The closure provided is required to adhere to the [`UnwindSafe`] trait to ensure
101 /// that all captured variables are safe to cross this boundary. The purpose of
102 /// this bound is to encode the concept of [exception safety][rfc] in the type
103 /// system. Most usage of this function should not need to worry about this
104 /// bound as programs are naturally unwind safe without `unsafe` code. If it
105 /// becomes a problem the [`AssertUnwindSafe`] wrapper struct can be used to quickly
106 /// assert that the usage here is indeed unwind safe.
107 ///
108 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
109 ///
110 /// # Notes
111 ///
112 /// Note that this function **might not catch all panics** in Rust. A panic in
113 /// Rust is not always implemented via unwinding, but can be implemented by
114 /// aborting the process as well. This function *only* catches unwinding panics,
115 /// not those that abort the process.
116 ///
117 /// Also note that unwinding into Rust code with a foreign exception (e.g.
118 /// an exception thrown from C++ code) is undefined behavior.
119 ///
120 /// # Examples
121 ///
122 /// ```
123 /// use std::panic;
124 ///
125 /// let result = panic::catch_unwind(|| {
126 ///     println!("hello!");
127 /// });
128 /// assert!(result.is_ok());
129 ///
130 /// let result = panic::catch_unwind(|| {
131 ///     panic!("oh no!");
132 /// });
133 /// assert!(result.is_err());
134 /// ```
135 #[stable(feature = "catch_unwind", since = "1.9.0")]
136 pub fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R> {
137     unsafe { panicking::r#try(f) }
138 }
139
140 /// Triggers a panic without invoking the panic hook.
141 ///
142 /// This is designed to be used in conjunction with [`catch_unwind`] to, for
143 /// example, carry a panic across a layer of C code.
144 ///
145 /// # Notes
146 ///
147 /// Note that panics in Rust are not always implemented via unwinding, but they
148 /// may be implemented by aborting the process. If this function is called when
149 /// panics are implemented this way then this function will abort the process,
150 /// not trigger an unwind.
151 ///
152 /// # Examples
153 ///
154 /// ```should_panic
155 /// use std::panic;
156 ///
157 /// let result = panic::catch_unwind(|| {
158 ///     panic!("oh no!");
159 /// });
160 ///
161 /// if let Err(err) = result {
162 ///     panic::resume_unwind(err);
163 /// }
164 /// ```
165 #[stable(feature = "resume_unwind", since = "1.9.0")]
166 pub fn resume_unwind(payload: Box<dyn Any + Send>) -> ! {
167     panicking::rust_panic_without_hook(payload)
168 }
169
170 /// Make all future panics abort directly without running the panic hook or unwinding.
171 ///
172 /// There is no way to undo this; the effect lasts until the process exits or
173 /// execs (or the equivalent).
174 ///
175 /// # Use after fork
176 ///
177 /// This function is particularly useful for calling after `libc::fork`.  After `fork`, in a
178 /// multithreaded program it is (on many platforms) not safe to call the allocator.  It is also
179 /// generally highly undesirable for an unwind to unwind past the `fork`, because that results in
180 /// the unwind propagating to code that was only ever expecting to run in the parent.
181 ///
182 /// `panic::always_abort()` helps avoid both of these.  It directly avoids any further unwinding,
183 /// and if there is a panic, the abort will occur without allocating provided that the arguments to
184 /// panic can be formatted without allocating.
185 ///
186 /// Examples
187 ///
188 /// ```no_run
189 /// #![feature(panic_always_abort)]
190 /// use std::panic;
191 ///
192 /// panic::always_abort();
193 ///
194 /// let _ = panic::catch_unwind(|| {
195 ///     panic!("inside the catch");
196 /// });
197 ///
198 /// // We will have aborted already, due to the panic.
199 /// unreachable!();
200 /// ```
201 #[unstable(feature = "panic_always_abort", issue = "84438")]
202 pub fn always_abort() {
203     crate::panicking::panic_count::set_always_abort();
204 }
205
206 /// The configuration for whether and how the default panic hook will capture
207 /// and display the backtrace.
208 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
209 #[unstable(feature = "panic_backtrace_config", issue = "93346")]
210 #[non_exhaustive]
211 pub enum BacktraceStyle {
212     /// Prints a terser backtrace which ideally only contains relevant
213     /// information.
214     Short,
215     /// Prints a backtrace with all possible information.
216     Full,
217     /// Disable collecting and displaying backtraces.
218     Off,
219 }
220
221 impl BacktraceStyle {
222     pub(crate) fn full() -> Option<Self> {
223         if cfg!(feature = "backtrace") { Some(BacktraceStyle::Full) } else { None }
224     }
225
226     fn as_usize(self) -> usize {
227         match self {
228             BacktraceStyle::Short => 1,
229             BacktraceStyle::Full => 2,
230             BacktraceStyle::Off => 3,
231         }
232     }
233
234     fn from_usize(s: usize) -> Option<Self> {
235         Some(match s {
236             0 => return None,
237             1 => BacktraceStyle::Short,
238             2 => BacktraceStyle::Full,
239             3 => BacktraceStyle::Off,
240             _ => unreachable!(),
241         })
242     }
243 }
244
245 // Tracks whether we should/can capture a backtrace, and how we should display
246 // that backtrace.
247 //
248 // Internally stores equivalent of an Option<BacktraceStyle>.
249 static SHOULD_CAPTURE: AtomicUsize = AtomicUsize::new(0);
250
251 /// Configure whether the default panic hook will capture and display a
252 /// backtrace.
253 ///
254 /// The default value for this setting may be set by the `RUST_BACKTRACE`
255 /// environment variable; see the details in [`get_backtrace_style`].
256 #[unstable(feature = "panic_backtrace_config", issue = "93346")]
257 pub fn set_backtrace_style(style: BacktraceStyle) {
258     if !cfg!(feature = "backtrace") {
259         // If the `backtrace` feature of this crate isn't enabled, skip setting.
260         return;
261     }
262     SHOULD_CAPTURE.store(style.as_usize(), Ordering::Release);
263 }
264
265 /// Checks whether the standard library's panic hook will capture and print a
266 /// backtrace.
267 ///
268 /// This function will, if a backtrace style has not been set via
269 /// [`set_backtrace_style`], read the environment variable `RUST_BACKTRACE` to
270 /// determine a default value for the backtrace formatting:
271 ///
272 /// The first call to `get_backtrace_style` may read the `RUST_BACKTRACE`
273 /// environment variable if `set_backtrace_style` has not been called to
274 /// override the default value. After a call to `set_backtrace_style` or
275 /// `get_backtrace_style`, any changes to `RUST_BACKTRACE` will have no effect.
276 ///
277 /// `RUST_BACKTRACE` is read according to these rules:
278 ///
279 /// * `0` for `BacktraceStyle::Off`
280 /// * `full` for `BacktraceStyle::Full`
281 /// * `1` for `BacktraceStyle::Short`
282 /// * Other values are currently `BacktraceStyle::Short`, but this may change in
283 ///   the future
284 ///
285 /// Returns `None` if backtraces aren't currently supported.
286 #[unstable(feature = "panic_backtrace_config", issue = "93346")]
287 pub fn get_backtrace_style() -> Option<BacktraceStyle> {
288     if !cfg!(feature = "backtrace") {
289         // If the `backtrace` feature of this crate isn't enabled quickly return
290         // `Unsupported` so this can be constant propagated all over the place
291         // to optimize away callers.
292         return None;
293     }
294     if let Some(style) = BacktraceStyle::from_usize(SHOULD_CAPTURE.load(Ordering::Acquire)) {
295         return Some(style);
296     }
297
298     // Setting environment variables for Fuchsia components isn't a standard
299     // or easily supported workflow. For now, display backtraces by default.
300     let format = if cfg!(target_os = "fuchsia") {
301         BacktraceStyle::Full
302     } else {
303         crate::env::var_os("RUST_BACKTRACE")
304             .map(|x| {
305                 if &x == "0" {
306                     BacktraceStyle::Off
307                 } else if &x == "full" {
308                     BacktraceStyle::Full
309                 } else {
310                     BacktraceStyle::Short
311                 }
312             })
313             .unwrap_or(BacktraceStyle::Off)
314     };
315     set_backtrace_style(format);
316     Some(format)
317 }
318
319 #[cfg(test)]
320 mod tests;