1 //! Panic support in the standard library.
3 #![stable(feature = "std_panic", since = "1.9.0")]
6 use crate::cell::UnsafeCell;
7 use crate::collections;
9 use crate::future::Future;
10 use crate::ops::{Deref, DerefMut};
13 use crate::ptr::{NonNull, Unique};
15 use crate::stream::Stream;
16 use crate::sync::atomic;
17 use crate::sync::{Arc, Mutex, RwLock};
18 use crate::task::{Context, Poll};
19 use crate::thread::Result;
22 #[unstable(feature = "edition_panic", issue = "none", reason = "use panic!() instead")]
23 #[allow_internal_unstable(libstd_sys_internals)]
24 #[cfg_attr(not(test), rustc_diagnostic_item = "std_panic_2015_macro")]
25 #[rustc_macro_transparency = "semitransparent"]
26 pub macro panic_2015 {
28 $crate::rt::begin_panic("explicit panic")
30 ($msg:expr $(,)?) => ({
31 $crate::rt::begin_panic($msg)
33 ($fmt:expr, $($arg:tt)+) => ({
34 $crate::rt::begin_panic_fmt(&$crate::format_args!($fmt, $($arg)+))
39 #[unstable(feature = "edition_panic", issue = "none", reason = "use panic!() instead")]
40 pub use core::panic::panic_2021;
42 #[stable(feature = "panic_hooks", since = "1.10.0")]
43 pub use crate::panicking::{set_hook, take_hook};
45 #[stable(feature = "panic_hooks", since = "1.10.0")]
46 pub use core::panic::{Location, PanicInfo};
48 /// Panic the current thread with the given message as the panic payload.
50 /// The message can be of any (`Any + Send`) type, not just strings.
52 /// The message is wrapped in a `Box<'static + Any + Send>`, which can be
53 /// accessed later using [`PanicInfo::payload`].
55 /// See the [`panic!`] macro for more information about panicking.
56 #[stable(feature = "panic_any", since = "1.51.0")]
59 pub fn panic_any<M: 'static + Any + Send>(msg: M) -> ! {
60 crate::panicking::begin_panic(msg);
63 /// A marker trait which represents "panic safe" types in Rust.
65 /// This trait is implemented by default for many types and behaves similarly in
66 /// terms of inference of implementation to the [`Send`] and [`Sync`] traits. The
67 /// purpose of this trait is to encode what types are safe to cross a [`catch_unwind`]
68 /// boundary with no fear of unwind safety.
70 /// ## What is unwind safety?
72 /// In Rust a function can "return" early if it either panics or calls a
73 /// function which transitively panics. This sort of control flow is not always
74 /// anticipated, and has the possibility of causing subtle bugs through a
75 /// combination of two critical components:
77 /// 1. A data structure is in a temporarily invalid state when the thread
79 /// 2. This broken invariant is then later observed.
81 /// Typically in Rust, it is difficult to perform step (2) because catching a
82 /// panic involves either spawning a thread (which in turns makes it difficult
83 /// to later witness broken invariants) or using the `catch_unwind` function in this
84 /// module. Additionally, even if an invariant is witnessed, it typically isn't a
85 /// problem in Rust because there are no uninitialized values (like in C or C++).
87 /// It is possible, however, for **logical** invariants to be broken in Rust,
88 /// which can end up causing behavioral bugs. Another key aspect of unwind safety
89 /// in Rust is that, in the absence of `unsafe` code, a panic cannot lead to
92 /// That was a bit of a whirlwind tour of unwind safety, but for more information
93 /// about unwind safety and how it applies to Rust, see an [associated RFC][rfc].
95 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
97 /// ## What is `UnwindSafe`?
99 /// Now that we've got an idea of what unwind safety is in Rust, it's also
100 /// important to understand what this trait represents. As mentioned above, one
101 /// way to witness broken invariants is through the `catch_unwind` function in this
102 /// module as it allows catching a panic and then re-using the environment of
105 /// Simply put, a type `T` implements `UnwindSafe` if it cannot easily allow
106 /// witnessing a broken invariant through the use of `catch_unwind` (catching a
107 /// panic). This trait is an auto trait, so it is automatically implemented for
108 /// many types, and it is also structurally composed (e.g., a struct is unwind
109 /// safe if all of its components are unwind safe).
111 /// Note, however, that this is not an unsafe trait, so there is not a succinct
112 /// contract that this trait is providing. Instead it is intended as more of a
113 /// "speed bump" to alert users of `catch_unwind` that broken invariants may be
114 /// witnessed and may need to be accounted for.
116 /// ## Who implements `UnwindSafe`?
118 /// Types such as `&mut T` and `&RefCell<T>` are examples which are **not**
119 /// unwind safe. The general idea is that any mutable state which can be shared
120 /// across `catch_unwind` is not unwind safe by default. This is because it is very
121 /// easy to witness a broken invariant outside of `catch_unwind` as the data is
122 /// simply accessed as usual.
124 /// Types like `&Mutex<T>`, however, are unwind safe because they implement
125 /// poisoning by default. They still allow witnessing a broken invariant, but
126 /// they already provide their own "speed bumps" to do so.
128 /// ## When should `UnwindSafe` be used?
130 /// It is not intended that most types or functions need to worry about this trait.
131 /// It is only used as a bound on the `catch_unwind` function and as mentioned
132 /// above, the lack of `unsafe` means it is mostly an advisory. The
133 /// [`AssertUnwindSafe`] wrapper struct can be used to force this trait to be
134 /// implemented for any closed over variables passed to `catch_unwind`.
135 #[stable(feature = "catch_unwind", since = "1.9.0")]
136 #[cfg_attr(all(not(bootstrap), not(test)), lang = "unwind_safe")]
137 #[rustc_on_unimplemented(
138 message = "the type `{Self}` may not be safely transferred across an unwind boundary",
139 label = "`{Self}` may not be safely transferred across an unwind boundary"
141 pub auto trait UnwindSafe {}
143 /// A marker trait representing types where a shared reference is considered
146 /// This trait is namely not implemented by [`UnsafeCell`], the root of all
147 /// interior mutability.
149 /// This is a "helper marker trait" used to provide impl blocks for the
150 /// [`UnwindSafe`] trait, for more information see that documentation.
151 #[stable(feature = "catch_unwind", since = "1.9.0")]
152 #[cfg_attr(all(not(bootstrap), not(test)), lang = "ref_unwind_safe")]
153 #[rustc_on_unimplemented(
154 message = "the type `{Self}` may contain interior mutability and a reference may not be safely \
155 transferrable across a catch_unwind boundary",
156 label = "`{Self}` may contain interior mutability and a reference may not be safely \
157 transferrable across a catch_unwind boundary"
159 pub auto trait RefUnwindSafe {}
161 /// A simple wrapper around a type to assert that it is unwind safe.
163 /// When using [`catch_unwind`] it may be the case that some of the closed over
164 /// variables are not unwind safe. For example if `&mut T` is captured the
165 /// compiler will generate a warning indicating that it is not unwind safe. It
166 /// may not be the case, however, that this is actually a problem due to the
167 /// specific usage of [`catch_unwind`] if unwind safety is specifically taken into
168 /// account. This wrapper struct is useful for a quick and lightweight
169 /// annotation that a variable is indeed unwind safe.
173 /// One way to use `AssertUnwindSafe` is to assert that the entire closure
174 /// itself is unwind safe, bypassing all checks for all variables:
177 /// use std::panic::{self, AssertUnwindSafe};
179 /// let mut variable = 4;
181 /// // This code will not compile because the closure captures `&mut variable`
182 /// // which is not considered unwind safe by default.
184 /// // panic::catch_unwind(|| {
185 /// // variable += 3;
188 /// // This, however, will compile due to the `AssertUnwindSafe` wrapper
189 /// let result = panic::catch_unwind(AssertUnwindSafe(|| {
195 /// Wrapping the entire closure amounts to a blanket assertion that all captured
196 /// variables are unwind safe. This has the downside that if new captures are
197 /// added in the future, they will also be considered unwind safe. Therefore,
198 /// you may prefer to just wrap individual captures, as shown below. This is
199 /// more annotation, but it ensures that if a new capture is added which is not
200 /// unwind safe, you will get a compilation error at that time, which will
201 /// allow you to consider whether that new capture in fact represent a bug or
205 /// use std::panic::{self, AssertUnwindSafe};
207 /// let mut variable = 4;
208 /// let other_capture = 3;
211 /// let mut wrapper = AssertUnwindSafe(&mut variable);
212 /// panic::catch_unwind(move || {
213 /// **wrapper += other_capture;
218 #[stable(feature = "catch_unwind", since = "1.9.0")]
219 pub struct AssertUnwindSafe<T>(#[stable(feature = "catch_unwind", since = "1.9.0")] pub T);
221 // Implementations of the `UnwindSafe` trait:
223 // * By default everything is unwind safe
224 // * pointers T contains mutability of some form are not unwind safe
225 // * Unique, an owning pointer, lifts an implementation
226 // * Types like Mutex/RwLock which are explicitly poisoned are unwind safe
227 // * Our custom AssertUnwindSafe wrapper is indeed unwind safe
229 #[stable(feature = "catch_unwind", since = "1.9.0")]
230 impl<T: ?Sized> !UnwindSafe for &mut T {}
231 #[stable(feature = "catch_unwind", since = "1.9.0")]
232 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for &T {}
233 #[stable(feature = "catch_unwind", since = "1.9.0")]
234 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *const T {}
235 #[stable(feature = "catch_unwind", since = "1.9.0")]
236 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *mut T {}
237 #[unstable(feature = "ptr_internals", issue = "none")]
238 impl<T: UnwindSafe + ?Sized> UnwindSafe for Unique<T> {}
239 #[stable(feature = "nonnull", since = "1.25.0")]
240 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for NonNull<T> {}
241 #[stable(feature = "catch_unwind", since = "1.9.0")]
242 impl<T: ?Sized> UnwindSafe for Mutex<T> {}
243 #[stable(feature = "catch_unwind", since = "1.9.0")]
244 impl<T: ?Sized> UnwindSafe for RwLock<T> {}
245 #[stable(feature = "catch_unwind", since = "1.9.0")]
246 impl<T> UnwindSafe for AssertUnwindSafe<T> {}
248 // not covered via the Shared impl above b/c the inner contents use
249 // Cell/AtomicUsize, but the usage here is unwind safe so we can lift the
250 // impl up one level to Arc/Rc itself
251 #[stable(feature = "catch_unwind", since = "1.9.0")]
252 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Rc<T> {}
253 #[stable(feature = "catch_unwind", since = "1.9.0")]
254 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Arc<T> {}
256 // Pretty simple implementations for the `RefUnwindSafe` marker trait,
257 // basically just saying that `UnsafeCell` is the
258 // only thing which doesn't implement it (which then transitively applies to
260 #[stable(feature = "catch_unwind", since = "1.9.0")]
261 impl<T: ?Sized> !RefUnwindSafe for UnsafeCell<T> {}
262 #[stable(feature = "catch_unwind", since = "1.9.0")]
263 impl<T> RefUnwindSafe for AssertUnwindSafe<T> {}
265 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
266 impl<T: ?Sized> RefUnwindSafe for Mutex<T> {}
267 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
268 impl<T: ?Sized> RefUnwindSafe for RwLock<T> {}
270 #[cfg(target_has_atomic_load_store = "ptr")]
271 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
272 impl RefUnwindSafe for atomic::AtomicIsize {}
273 #[cfg(target_has_atomic_load_store = "8")]
274 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
275 impl RefUnwindSafe for atomic::AtomicI8 {}
276 #[cfg(target_has_atomic_load_store = "16")]
277 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
278 impl RefUnwindSafe for atomic::AtomicI16 {}
279 #[cfg(target_has_atomic_load_store = "32")]
280 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
281 impl RefUnwindSafe for atomic::AtomicI32 {}
282 #[cfg(target_has_atomic_load_store = "64")]
283 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
284 impl RefUnwindSafe for atomic::AtomicI64 {}
285 #[cfg(target_has_atomic_load_store = "128")]
286 #[unstable(feature = "integer_atomics", issue = "32976")]
287 impl RefUnwindSafe for atomic::AtomicI128 {}
289 #[cfg(target_has_atomic_load_store = "ptr")]
290 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
291 impl RefUnwindSafe for atomic::AtomicUsize {}
292 #[cfg(target_has_atomic_load_store = "8")]
293 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
294 impl RefUnwindSafe for atomic::AtomicU8 {}
295 #[cfg(target_has_atomic_load_store = "16")]
296 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
297 impl RefUnwindSafe for atomic::AtomicU16 {}
298 #[cfg(target_has_atomic_load_store = "32")]
299 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
300 impl RefUnwindSafe for atomic::AtomicU32 {}
301 #[cfg(target_has_atomic_load_store = "64")]
302 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
303 impl RefUnwindSafe for atomic::AtomicU64 {}
304 #[cfg(target_has_atomic_load_store = "128")]
305 #[unstable(feature = "integer_atomics", issue = "32976")]
306 impl RefUnwindSafe for atomic::AtomicU128 {}
308 #[cfg(target_has_atomic_load_store = "8")]
309 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
310 impl RefUnwindSafe for atomic::AtomicBool {}
312 #[cfg(target_has_atomic_load_store = "ptr")]
313 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
314 impl<T> RefUnwindSafe for atomic::AtomicPtr<T> {}
316 // https://github.com/rust-lang/rust/issues/62301
317 #[stable(feature = "hashbrown", since = "1.36.0")]
318 impl<K, V, S> UnwindSafe for collections::HashMap<K, V, S>
326 #[stable(feature = "catch_unwind", since = "1.9.0")]
327 impl<T> Deref for AssertUnwindSafe<T> {
330 fn deref(&self) -> &T {
335 #[stable(feature = "catch_unwind", since = "1.9.0")]
336 impl<T> DerefMut for AssertUnwindSafe<T> {
337 fn deref_mut(&mut self) -> &mut T {
342 #[stable(feature = "catch_unwind", since = "1.9.0")]
343 impl<R, F: FnOnce() -> R> FnOnce<()> for AssertUnwindSafe<F> {
346 extern "rust-call" fn call_once(self, _args: ()) -> R {
351 #[stable(feature = "std_debug", since = "1.16.0")]
352 impl<T: fmt::Debug> fmt::Debug for AssertUnwindSafe<T> {
353 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
354 f.debug_tuple("AssertUnwindSafe").field(&self.0).finish()
358 #[stable(feature = "futures_api", since = "1.36.0")]
359 impl<F: Future> Future for AssertUnwindSafe<F> {
360 type Output = F::Output;
362 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
363 let pinned_field = unsafe { Pin::map_unchecked_mut(self, |x| &mut x.0) };
364 F::poll(pinned_field, cx)
368 #[unstable(feature = "async_stream", issue = "79024")]
369 impl<S: Stream> Stream for AssertUnwindSafe<S> {
372 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<S::Item>> {
373 unsafe { self.map_unchecked_mut(|x| &mut x.0) }.poll_next(cx)
376 fn size_hint(&self) -> (usize, Option<usize>) {
381 /// Invokes a closure, capturing the cause of an unwinding panic if one occurs.
383 /// This function will return `Ok` with the closure's result if the closure
384 /// does not panic, and will return `Err(cause)` if the closure panics. The
385 /// `cause` returned is the object with which panic was originally invoked.
387 /// It is currently undefined behavior to unwind from Rust code into foreign
388 /// code, so this function is particularly useful when Rust is called from
389 /// another language (normally C). This can run arbitrary Rust code, capturing a
390 /// panic and allowing a graceful handling of the error.
392 /// It is **not** recommended to use this function for a general try/catch
393 /// mechanism. The [`Result`] type is more appropriate to use for functions that
394 /// can fail on a regular basis. Additionally, this function is not guaranteed
395 /// to catch all panics, see the "Notes" section below.
397 /// The closure provided is required to adhere to the [`UnwindSafe`] trait to ensure
398 /// that all captured variables are safe to cross this boundary. The purpose of
399 /// this bound is to encode the concept of [exception safety][rfc] in the type
400 /// system. Most usage of this function should not need to worry about this
401 /// bound as programs are naturally unwind safe without `unsafe` code. If it
402 /// becomes a problem the [`AssertUnwindSafe`] wrapper struct can be used to quickly
403 /// assert that the usage here is indeed unwind safe.
405 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
409 /// Note that this function **may not catch all panics** in Rust. A panic in
410 /// Rust is not always implemented via unwinding, but can be implemented by
411 /// aborting the process as well. This function *only* catches unwinding panics,
412 /// not those that abort the process.
414 /// Also note that unwinding into Rust code with a foreign exception (e.g.
415 /// an exception thrown from C++ code) is undefined behavior.
422 /// let result = panic::catch_unwind(|| {
423 /// println!("hello!");
425 /// assert!(result.is_ok());
427 /// let result = panic::catch_unwind(|| {
428 /// panic!("oh no!");
430 /// assert!(result.is_err());
432 #[stable(feature = "catch_unwind", since = "1.9.0")]
433 pub fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R> {
434 unsafe { panicking::r#try(f) }
437 /// Triggers a panic without invoking the panic hook.
439 /// This is designed to be used in conjunction with [`catch_unwind`] to, for
440 /// example, carry a panic across a layer of C code.
444 /// Note that panics in Rust are not always implemented via unwinding, but they
445 /// may be implemented by aborting the process. If this function is called when
446 /// panics are implemented this way then this function will abort the process,
447 /// not trigger an unwind.
454 /// let result = panic::catch_unwind(|| {
455 /// panic!("oh no!");
458 /// if let Err(err) = result {
459 /// panic::resume_unwind(err);
462 #[stable(feature = "resume_unwind", since = "1.9.0")]
463 pub fn resume_unwind(payload: Box<dyn Any + Send>) -> ! {
464 panicking::rust_panic_without_hook(payload)
467 /// Make all future panics abort directly without running the panic hook or unwinding.
469 /// There is no way to undo this; the effect lasts until the process exits or
470 /// execs (or the equivalent).
474 /// This function is particularly useful for calling after `libc::fork`. After `fork`, in a
475 /// multithreaded program it is (on many platforms) not safe to call the allocator. It is also
476 /// generally highly undesirable for an unwind to unwind past the `fork`, because that results in
477 /// the unwind propagating to code that was only ever expecting to run in the parent.
479 /// `panic::always_abort()` helps avoid both of these. It directly avoids any further unwinding,
480 /// and if there is a panic, the abort will occur without allocating provided that the arguments to
481 /// panic can be formatted without allocating.
486 /// #![feature(panic_always_abort)]
489 /// panic::always_abort();
491 /// let _ = panic::catch_unwind(|| {
492 /// panic!("inside the catch");
495 /// // We will have aborted already, due to the panic.
498 #[unstable(feature = "panic_always_abort", issue = "84438")]
499 pub fn always_abort() {
500 crate::panicking::panic_count::set_always_abort();