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")]
58 pub fn panic_any<M: 'static + Any + Send>(msg: M) -> ! {
59 crate::panicking::begin_panic(msg);
62 /// A marker trait which represents "panic safe" types in Rust.
64 /// This trait is implemented by default for many types and behaves similarly in
65 /// terms of inference of implementation to the [`Send`] and [`Sync`] traits. The
66 /// purpose of this trait is to encode what types are safe to cross a [`catch_unwind`]
67 /// boundary with no fear of unwind safety.
69 /// ## What is unwind safety?
71 /// In Rust a function can "return" early if it either panics or calls a
72 /// function which transitively panics. This sort of control flow is not always
73 /// anticipated, and has the possibility of causing subtle bugs through a
74 /// combination of two critical components:
76 /// 1. A data structure is in a temporarily invalid state when the thread
78 /// 2. This broken invariant is then later observed.
80 /// Typically in Rust, it is difficult to perform step (2) because catching a
81 /// panic involves either spawning a thread (which in turns makes it difficult
82 /// to later witness broken invariants) or using the `catch_unwind` function in this
83 /// module. Additionally, even if an invariant is witnessed, it typically isn't a
84 /// problem in Rust because there are no uninitialized values (like in C or C++).
86 /// It is possible, however, for **logical** invariants to be broken in Rust,
87 /// which can end up causing behavioral bugs. Another key aspect of unwind safety
88 /// in Rust is that, in the absence of `unsafe` code, a panic cannot lead to
91 /// That was a bit of a whirlwind tour of unwind safety, but for more information
92 /// about unwind safety and how it applies to Rust, see an [associated RFC][rfc].
94 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
96 /// ## What is `UnwindSafe`?
98 /// Now that we've got an idea of what unwind safety is in Rust, it's also
99 /// important to understand what this trait represents. As mentioned above, one
100 /// way to witness broken invariants is through the `catch_unwind` function in this
101 /// module as it allows catching a panic and then re-using the environment of
104 /// Simply put, a type `T` implements `UnwindSafe` if it cannot easily allow
105 /// witnessing a broken invariant through the use of `catch_unwind` (catching a
106 /// panic). This trait is an auto trait, so it is automatically implemented for
107 /// many types, and it is also structurally composed (e.g., a struct is unwind
108 /// safe if all of its components are unwind safe).
110 /// Note, however, that this is not an unsafe trait, so there is not a succinct
111 /// contract that this trait is providing. Instead it is intended as more of a
112 /// "speed bump" to alert users of `catch_unwind` that broken invariants may be
113 /// witnessed and may need to be accounted for.
115 /// ## Who implements `UnwindSafe`?
117 /// Types such as `&mut T` and `&RefCell<T>` are examples which are **not**
118 /// unwind safe. The general idea is that any mutable state which can be shared
119 /// across `catch_unwind` is not unwind safe by default. This is because it is very
120 /// easy to witness a broken invariant outside of `catch_unwind` as the data is
121 /// simply accessed as usual.
123 /// Types like `&Mutex<T>`, however, are unwind safe because they implement
124 /// poisoning by default. They still allow witnessing a broken invariant, but
125 /// they already provide their own "speed bumps" to do so.
127 /// ## When should `UnwindSafe` be used?
129 /// It is not intended that most types or functions need to worry about this trait.
130 /// It is only used as a bound on the `catch_unwind` function and as mentioned
131 /// above, the lack of `unsafe` means it is mostly an advisory. The
132 /// [`AssertUnwindSafe`] wrapper struct can be used to force this trait to be
133 /// implemented for any closed over variables passed to `catch_unwind`.
134 #[stable(feature = "catch_unwind", since = "1.9.0")]
135 #[rustc_on_unimplemented(
136 message = "the type `{Self}` may not be safely transferred across an unwind boundary",
137 label = "`{Self}` may not be safely transferred across an unwind boundary"
139 pub auto trait UnwindSafe {}
141 /// A marker trait representing types where a shared reference is considered
144 /// This trait is namely not implemented by [`UnsafeCell`], the root of all
145 /// interior mutability.
147 /// This is a "helper marker trait" used to provide impl blocks for the
148 /// [`UnwindSafe`] trait, for more information see that documentation.
149 #[stable(feature = "catch_unwind", since = "1.9.0")]
150 #[rustc_on_unimplemented(
151 message = "the type `{Self}` may contain interior mutability and a reference may not be safely \
152 transferrable across a catch_unwind boundary",
153 label = "`{Self}` may contain interior mutability and a reference may not be safely \
154 transferrable across a catch_unwind boundary"
156 pub auto trait RefUnwindSafe {}
158 /// A simple wrapper around a type to assert that it is unwind safe.
160 /// When using [`catch_unwind`] it may be the case that some of the closed over
161 /// variables are not unwind safe. For example if `&mut T` is captured the
162 /// compiler will generate a warning indicating that it is not unwind safe. It
163 /// may not be the case, however, that this is actually a problem due to the
164 /// specific usage of [`catch_unwind`] if unwind safety is specifically taken into
165 /// account. This wrapper struct is useful for a quick and lightweight
166 /// annotation that a variable is indeed unwind safe.
170 /// One way to use `AssertUnwindSafe` is to assert that the entire closure
171 /// itself is unwind safe, bypassing all checks for all variables:
174 /// use std::panic::{self, AssertUnwindSafe};
176 /// let mut variable = 4;
178 /// // This code will not compile because the closure captures `&mut variable`
179 /// // which is not considered unwind safe by default.
181 /// // panic::catch_unwind(|| {
182 /// // variable += 3;
185 /// // This, however, will compile due to the `AssertUnwindSafe` wrapper
186 /// let result = panic::catch_unwind(AssertUnwindSafe(|| {
192 /// Wrapping the entire closure amounts to a blanket assertion that all captured
193 /// variables are unwind safe. This has the downside that if new captures are
194 /// added in the future, they will also be considered unwind safe. Therefore,
195 /// you may prefer to just wrap individual captures, as shown below. This is
196 /// more annotation, but it ensures that if a new capture is added which is not
197 /// unwind safe, you will get a compilation error at that time, which will
198 /// allow you to consider whether that new capture in fact represent a bug or
202 /// use std::panic::{self, AssertUnwindSafe};
204 /// let mut variable = 4;
205 /// let other_capture = 3;
208 /// let mut wrapper = AssertUnwindSafe(&mut variable);
209 /// panic::catch_unwind(move || {
210 /// **wrapper += other_capture;
215 #[stable(feature = "catch_unwind", since = "1.9.0")]
216 pub struct AssertUnwindSafe<T>(#[stable(feature = "catch_unwind", since = "1.9.0")] pub T);
218 // Implementations of the `UnwindSafe` trait:
220 // * By default everything is unwind safe
221 // * pointers T contains mutability of some form are not unwind safe
222 // * Unique, an owning pointer, lifts an implementation
223 // * Types like Mutex/RwLock which are explicitly poisoned are unwind safe
224 // * Our custom AssertUnwindSafe wrapper is indeed unwind safe
226 #[stable(feature = "catch_unwind", since = "1.9.0")]
227 impl<T: ?Sized> !UnwindSafe for &mut T {}
228 #[stable(feature = "catch_unwind", since = "1.9.0")]
229 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for &T {}
230 #[stable(feature = "catch_unwind", since = "1.9.0")]
231 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *const T {}
232 #[stable(feature = "catch_unwind", since = "1.9.0")]
233 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *mut T {}
234 #[unstable(feature = "ptr_internals", issue = "none")]
235 impl<T: UnwindSafe + ?Sized> UnwindSafe for Unique<T> {}
236 #[stable(feature = "nonnull", since = "1.25.0")]
237 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for NonNull<T> {}
238 #[stable(feature = "catch_unwind", since = "1.9.0")]
239 impl<T: ?Sized> UnwindSafe for Mutex<T> {}
240 #[stable(feature = "catch_unwind", since = "1.9.0")]
241 impl<T: ?Sized> UnwindSafe for RwLock<T> {}
242 #[stable(feature = "catch_unwind", since = "1.9.0")]
243 impl<T> UnwindSafe for AssertUnwindSafe<T> {}
245 // not covered via the Shared impl above b/c the inner contents use
246 // Cell/AtomicUsize, but the usage here is unwind safe so we can lift the
247 // impl up one level to Arc/Rc itself
248 #[stable(feature = "catch_unwind", since = "1.9.0")]
249 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Rc<T> {}
250 #[stable(feature = "catch_unwind", since = "1.9.0")]
251 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Arc<T> {}
253 // Pretty simple implementations for the `RefUnwindSafe` marker trait,
254 // basically just saying that `UnsafeCell` is the
255 // only thing which doesn't implement it (which then transitively applies to
257 #[stable(feature = "catch_unwind", since = "1.9.0")]
258 impl<T: ?Sized> !RefUnwindSafe for UnsafeCell<T> {}
259 #[stable(feature = "catch_unwind", since = "1.9.0")]
260 impl<T> RefUnwindSafe for AssertUnwindSafe<T> {}
262 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
263 impl<T: ?Sized> RefUnwindSafe for Mutex<T> {}
264 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
265 impl<T: ?Sized> RefUnwindSafe for RwLock<T> {}
267 #[cfg(target_has_atomic_load_store = "ptr")]
268 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
269 impl RefUnwindSafe for atomic::AtomicIsize {}
270 #[cfg(target_has_atomic_load_store = "8")]
271 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
272 impl RefUnwindSafe for atomic::AtomicI8 {}
273 #[cfg(target_has_atomic_load_store = "16")]
274 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
275 impl RefUnwindSafe for atomic::AtomicI16 {}
276 #[cfg(target_has_atomic_load_store = "32")]
277 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
278 impl RefUnwindSafe for atomic::AtomicI32 {}
279 #[cfg(target_has_atomic_load_store = "64")]
280 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
281 impl RefUnwindSafe for atomic::AtomicI64 {}
282 #[cfg(target_has_atomic_load_store = "128")]
283 #[unstable(feature = "integer_atomics", issue = "32976")]
284 impl RefUnwindSafe for atomic::AtomicI128 {}
286 #[cfg(target_has_atomic_load_store = "ptr")]
287 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
288 impl RefUnwindSafe for atomic::AtomicUsize {}
289 #[cfg(target_has_atomic_load_store = "8")]
290 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
291 impl RefUnwindSafe for atomic::AtomicU8 {}
292 #[cfg(target_has_atomic_load_store = "16")]
293 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
294 impl RefUnwindSafe for atomic::AtomicU16 {}
295 #[cfg(target_has_atomic_load_store = "32")]
296 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
297 impl RefUnwindSafe for atomic::AtomicU32 {}
298 #[cfg(target_has_atomic_load_store = "64")]
299 #[stable(feature = "integer_atomics_stable", since = "1.34.0")]
300 impl RefUnwindSafe for atomic::AtomicU64 {}
301 #[cfg(target_has_atomic_load_store = "128")]
302 #[unstable(feature = "integer_atomics", issue = "32976")]
303 impl RefUnwindSafe for atomic::AtomicU128 {}
305 #[cfg(target_has_atomic_load_store = "8")]
306 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
307 impl RefUnwindSafe for atomic::AtomicBool {}
309 #[cfg(target_has_atomic_load_store = "ptr")]
310 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
311 impl<T> RefUnwindSafe for atomic::AtomicPtr<T> {}
313 // https://github.com/rust-lang/rust/issues/62301
314 #[stable(feature = "hashbrown", since = "1.36.0")]
315 impl<K, V, S> UnwindSafe for collections::HashMap<K, V, S>
323 #[stable(feature = "catch_unwind", since = "1.9.0")]
324 impl<T> Deref for AssertUnwindSafe<T> {
327 fn deref(&self) -> &T {
332 #[stable(feature = "catch_unwind", since = "1.9.0")]
333 impl<T> DerefMut for AssertUnwindSafe<T> {
334 fn deref_mut(&mut self) -> &mut T {
339 #[stable(feature = "catch_unwind", since = "1.9.0")]
340 impl<R, F: FnOnce() -> R> FnOnce<()> for AssertUnwindSafe<F> {
343 extern "rust-call" fn call_once(self, _args: ()) -> R {
348 #[stable(feature = "std_debug", since = "1.16.0")]
349 impl<T: fmt::Debug> fmt::Debug for AssertUnwindSafe<T> {
350 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
351 f.debug_tuple("AssertUnwindSafe").field(&self.0).finish()
355 #[stable(feature = "futures_api", since = "1.36.0")]
356 impl<F: Future> Future for AssertUnwindSafe<F> {
357 type Output = F::Output;
359 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
360 let pinned_field = unsafe { Pin::map_unchecked_mut(self, |x| &mut x.0) };
361 F::poll(pinned_field, cx)
365 #[unstable(feature = "async_stream", issue = "79024")]
366 impl<S: Stream> Stream for AssertUnwindSafe<S> {
369 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<S::Item>> {
370 unsafe { self.map_unchecked_mut(|x| &mut x.0) }.poll_next(cx)
373 fn size_hint(&self) -> (usize, Option<usize>) {
378 /// Invokes a closure, capturing the cause of an unwinding panic if one occurs.
380 /// This function will return `Ok` with the closure's result if the closure
381 /// does not panic, and will return `Err(cause)` if the closure panics. The
382 /// `cause` returned is the object with which panic was originally invoked.
384 /// It is currently undefined behavior to unwind from Rust code into foreign
385 /// code, so this function is particularly useful when Rust is called from
386 /// another language (normally C). This can run arbitrary Rust code, capturing a
387 /// panic and allowing a graceful handling of the error.
389 /// It is **not** recommended to use this function for a general try/catch
390 /// mechanism. The [`Result`] type is more appropriate to use for functions that
391 /// can fail on a regular basis. Additionally, this function is not guaranteed
392 /// to catch all panics, see the "Notes" section below.
394 /// The closure provided is required to adhere to the [`UnwindSafe`] trait to ensure
395 /// that all captured variables are safe to cross this boundary. The purpose of
396 /// this bound is to encode the concept of [exception safety][rfc] in the type
397 /// system. Most usage of this function should not need to worry about this
398 /// bound as programs are naturally unwind safe without `unsafe` code. If it
399 /// becomes a problem the [`AssertUnwindSafe`] wrapper struct can be used to quickly
400 /// assert that the usage here is indeed unwind safe.
402 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
406 /// Note that this function **may not catch all panics** in Rust. A panic in
407 /// Rust is not always implemented via unwinding, but can be implemented by
408 /// aborting the process as well. This function *only* catches unwinding panics,
409 /// not those that abort the process.
411 /// Also note that unwinding into Rust code with a foreign exception (e.g.
412 /// an exception thrown from C++ code) is undefined behavior.
419 /// let result = panic::catch_unwind(|| {
420 /// println!("hello!");
422 /// assert!(result.is_ok());
424 /// let result = panic::catch_unwind(|| {
425 /// panic!("oh no!");
427 /// assert!(result.is_err());
429 #[stable(feature = "catch_unwind", since = "1.9.0")]
430 pub fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R> {
431 unsafe { panicking::r#try(f) }
434 /// Triggers a panic without invoking the panic hook.
436 /// This is designed to be used in conjunction with [`catch_unwind`] to, for
437 /// example, carry a panic across a layer of C code.
441 /// Note that panics in Rust are not always implemented via unwinding, but they
442 /// may be implemented by aborting the process. If this function is called when
443 /// panics are implemented this way then this function will abort the process,
444 /// not trigger an unwind.
451 /// let result = panic::catch_unwind(|| {
452 /// panic!("oh no!");
455 /// if let Err(err) = result {
456 /// panic::resume_unwind(err);
459 #[stable(feature = "resume_unwind", since = "1.9.0")]
460 pub fn resume_unwind(payload: Box<dyn Any + Send>) -> ! {
461 panicking::rust_panic_without_hook(payload)