1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Panic support in the standard library.
13 #![stable(feature = "std_panic", since = "1.9.0")]
20 use ops::{Deref, DerefMut};
22 use ptr::{Unique, NonNull};
24 use sync::{Arc, Mutex, RwLock, atomic};
25 use task::{LocalWaker, Poll};
28 #[stable(feature = "panic_hooks", since = "1.10.0")]
29 pub use panicking::{take_hook, set_hook};
31 #[stable(feature = "panic_hooks", since = "1.10.0")]
32 pub use core::panic::{PanicInfo, Location};
34 /// A marker trait which represents "panic safe" types in Rust.
36 /// This trait is implemented by default for many types and behaves similarly in
37 /// terms of inference of implementation to the [`Send`] and [`Sync`] traits. The
38 /// purpose of this trait is to encode what types are safe to cross a [`catch_unwind`]
39 /// boundary with no fear of unwind safety.
41 /// [`Send`]: ../marker/trait.Send.html
42 /// [`Sync`]: ../marker/trait.Sync.html
43 /// [`catch_unwind`]: ./fn.catch_unwind.html
45 /// ## What is unwind safety?
47 /// In Rust a function can "return" early if it either panics or calls a
48 /// function which transitively panics. This sort of control flow is not always
49 /// anticipated, and has the possibility of causing subtle bugs through a
50 /// combination of two critical components:
52 /// 1. A data structure is in a temporarily invalid state when the thread
54 /// 2. This broken invariant is then later observed.
56 /// Typically in Rust, it is difficult to perform step (2) because catching a
57 /// panic involves either spawning a thread (which in turns makes it difficult
58 /// to later witness broken invariants) or using the `catch_unwind` function in this
59 /// module. Additionally, even if an invariant is witnessed, it typically isn't a
60 /// problem in Rust because there are no uninitialized values (like in C or C++).
62 /// It is possible, however, for **logical** invariants to be broken in Rust,
63 /// which can end up causing behavioral bugs. Another key aspect of unwind safety
64 /// in Rust is that, in the absence of `unsafe` code, a panic cannot lead to
67 /// That was a bit of a whirlwind tour of unwind safety, but for more information
68 /// about unwind safety and how it applies to Rust, see an [associated RFC][rfc].
70 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
72 /// ## What is `UnwindSafe`?
74 /// Now that we've got an idea of what unwind safety is in Rust, it's also
75 /// important to understand what this trait represents. As mentioned above, one
76 /// way to witness broken invariants is through the `catch_unwind` function in this
77 /// module as it allows catching a panic and then re-using the environment of
80 /// Simply put, a type `T` implements `UnwindSafe` if it cannot easily allow
81 /// witnessing a broken invariant through the use of `catch_unwind` (catching a
82 /// panic). This trait is an auto trait, so it is automatically implemented for
83 /// many types, and it is also structurally composed (e.g., a struct is unwind
84 /// safe if all of its components are unwind safe).
86 /// Note, however, that this is not an unsafe trait, so there is not a succinct
87 /// contract that this trait is providing. Instead it is intended as more of a
88 /// "speed bump" to alert users of `catch_unwind` that broken invariants may be
89 /// witnessed and may need to be accounted for.
91 /// ## Who implements `UnwindSafe`?
93 /// Types such as `&mut T` and `&RefCell<T>` are examples which are **not**
94 /// unwind safe. The general idea is that any mutable state which can be shared
95 /// across `catch_unwind` is not unwind safe by default. This is because it is very
96 /// easy to witness a broken invariant outside of `catch_unwind` as the data is
97 /// simply accessed as usual.
99 /// Types like `&Mutex<T>`, however, are unwind safe because they implement
100 /// poisoning by default. They still allow witnessing a broken invariant, but
101 /// they already provide their own "speed bumps" to do so.
103 /// ## When should `UnwindSafe` be used?
105 /// It is not intended that most types or functions need to worry about this trait.
106 /// It is only used as a bound on the `catch_unwind` function and as mentioned
107 /// above, the lack of `unsafe` means it is mostly an advisory. The
108 /// [`AssertUnwindSafe`] wrapper struct can be used to force this trait to be
109 /// implemented for any closed over variables passed to `catch_unwind`.
111 /// [`AssertUnwindSafe`]: ./struct.AssertUnwindSafe.html
112 #[stable(feature = "catch_unwind", since = "1.9.0")]
113 #[rustc_on_unimplemented(
114 message="the type `{Self}` may not be safely transferred across an unwind boundary",
115 label="`{Self}` may not be safely transferred across an unwind boundary",
117 pub auto trait UnwindSafe {}
119 /// A marker trait representing types where a shared reference is considered
122 /// This trait is namely not implemented by [`UnsafeCell`], the root of all
123 /// interior mutability.
125 /// This is a "helper marker trait" used to provide impl blocks for the
126 /// [`UnwindSafe`] trait, for more information see that documentation.
128 /// [`UnsafeCell`]: ../cell/struct.UnsafeCell.html
129 /// [`UnwindSafe`]: ./trait.UnwindSafe.html
130 #[stable(feature = "catch_unwind", since = "1.9.0")]
131 #[rustc_on_unimplemented(
132 message="the type `{Self}` may contain interior mutability and a reference may not be safely \
133 transferrable across a catch_unwind boundary",
134 label="`{Self}` may contain interior mutability and a reference may not be safely \
135 transferrable across a catch_unwind boundary",
137 pub auto trait RefUnwindSafe {}
139 /// A simple wrapper around a type to assert that it is unwind safe.
141 /// When using [`catch_unwind`] it may be the case that some of the closed over
142 /// variables are not unwind safe. For example if `&mut T` is captured the
143 /// compiler will generate a warning indicating that it is not unwind safe. It
144 /// may not be the case, however, that this is actually a problem due to the
145 /// specific usage of [`catch_unwind`] if unwind safety is specifically taken into
146 /// account. This wrapper struct is useful for a quick and lightweight
147 /// annotation that a variable is indeed unwind safe.
149 /// [`catch_unwind`]: ./fn.catch_unwind.html
152 /// One way to use `AssertUnwindSafe` is to assert that the entire closure
153 /// itself is unwind safe, bypassing all checks for all variables:
156 /// use std::panic::{self, AssertUnwindSafe};
158 /// let mut variable = 4;
160 /// // This code will not compile because the closure captures `&mut variable`
161 /// // which is not considered unwind safe by default.
163 /// // panic::catch_unwind(|| {
164 /// // variable += 3;
167 /// // This, however, will compile due to the `AssertUnwindSafe` wrapper
168 /// let result = panic::catch_unwind(AssertUnwindSafe(|| {
174 /// Wrapping the entire closure amounts to a blanket assertion that all captured
175 /// variables are unwind safe. This has the downside that if new captures are
176 /// added in the future, they will also be considered unwind safe. Therefore,
177 /// you may prefer to just wrap individual captures, as shown below. This is
178 /// more annotation, but it ensures that if a new capture is added which is not
179 /// unwind safe, you will get a compilation error at that time, which will
180 /// allow you to consider whether that new capture in fact represent a bug or
184 /// use std::panic::{self, AssertUnwindSafe};
186 /// let mut variable = 4;
187 /// let other_capture = 3;
190 /// let mut wrapper = AssertUnwindSafe(&mut variable);
191 /// panic::catch_unwind(move || {
192 /// **wrapper += other_capture;
197 #[stable(feature = "catch_unwind", since = "1.9.0")]
198 pub struct AssertUnwindSafe<T>(
199 #[stable(feature = "catch_unwind", since = "1.9.0")]
203 // Implementations of the `UnwindSafe` trait:
205 // * By default everything is unwind safe
206 // * pointers T contains mutability of some form are not unwind safe
207 // * Unique, an owning pointer, lifts an implementation
208 // * Types like Mutex/RwLock which are explicitly poisoned are unwind safe
209 // * Our custom AssertUnwindSafe wrapper is indeed unwind safe
211 #[stable(feature = "catch_unwind", since = "1.9.0")]
212 impl<'a, T: ?Sized> !UnwindSafe for &'a mut T {}
213 #[stable(feature = "catch_unwind", since = "1.9.0")]
214 impl<'a, T: RefUnwindSafe + ?Sized> UnwindSafe for &'a T {}
215 #[stable(feature = "catch_unwind", since = "1.9.0")]
216 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *const T {}
217 #[stable(feature = "catch_unwind", since = "1.9.0")]
218 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *mut T {}
219 #[unstable(feature = "ptr_internals", issue = "0")]
220 impl<T: UnwindSafe + ?Sized> UnwindSafe for Unique<T> {}
221 #[stable(feature = "nonnull", since = "1.25.0")]
222 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for NonNull<T> {}
223 #[stable(feature = "catch_unwind", since = "1.9.0")]
224 impl<T: ?Sized> UnwindSafe for Mutex<T> {}
225 #[stable(feature = "catch_unwind", since = "1.9.0")]
226 impl<T: ?Sized> UnwindSafe for RwLock<T> {}
227 #[stable(feature = "catch_unwind", since = "1.9.0")]
228 impl<T> UnwindSafe for AssertUnwindSafe<T> {}
230 // not covered via the Shared impl above b/c the inner contents use
231 // Cell/AtomicUsize, but the usage here is unwind safe so we can lift the
232 // impl up one level to Arc/Rc itself
233 #[stable(feature = "catch_unwind", since = "1.9.0")]
234 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Rc<T> {}
235 #[stable(feature = "catch_unwind", since = "1.9.0")]
236 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Arc<T> {}
238 // Pretty simple implementations for the `RefUnwindSafe` marker trait,
239 // basically just saying that `UnsafeCell` is the
240 // only thing which doesn't implement it (which then transitively applies to
242 #[stable(feature = "catch_unwind", since = "1.9.0")]
243 impl<T: ?Sized> !RefUnwindSafe for UnsafeCell<T> {}
244 #[stable(feature = "catch_unwind", since = "1.9.0")]
245 impl<T> RefUnwindSafe for AssertUnwindSafe<T> {}
247 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
248 impl<T: ?Sized> RefUnwindSafe for Mutex<T> {}
249 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
250 impl<T: ?Sized> RefUnwindSafe for RwLock<T> {}
252 #[cfg(target_has_atomic = "ptr")]
253 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
254 impl RefUnwindSafe for atomic::AtomicIsize {}
255 #[cfg(target_has_atomic = "8")]
256 #[unstable(feature = "integer_atomics", issue = "32976")]
257 impl RefUnwindSafe for atomic::AtomicI8 {}
258 #[cfg(target_has_atomic = "16")]
259 #[unstable(feature = "integer_atomics", issue = "32976")]
260 impl RefUnwindSafe for atomic::AtomicI16 {}
261 #[cfg(target_has_atomic = "32")]
262 #[unstable(feature = "integer_atomics", issue = "32976")]
263 impl RefUnwindSafe for atomic::AtomicI32 {}
264 #[cfg(target_has_atomic = "64")]
265 #[unstable(feature = "integer_atomics", issue = "32976")]
266 impl RefUnwindSafe for atomic::AtomicI64 {}
267 #[cfg(all(not(stage0), target_has_atomic = "128"))]
268 #[unstable(feature = "integer_atomics", issue = "32976")]
269 impl RefUnwindSafe for atomic::AtomicI128 {}
271 #[cfg(target_has_atomic = "ptr")]
272 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
273 impl RefUnwindSafe for atomic::AtomicUsize {}
274 #[cfg(target_has_atomic = "8")]
275 #[unstable(feature = "integer_atomics", issue = "32976")]
276 impl RefUnwindSafe for atomic::AtomicU8 {}
277 #[cfg(target_has_atomic = "16")]
278 #[unstable(feature = "integer_atomics", issue = "32976")]
279 impl RefUnwindSafe for atomic::AtomicU16 {}
280 #[cfg(target_has_atomic = "32")]
281 #[unstable(feature = "integer_atomics", issue = "32976")]
282 impl RefUnwindSafe for atomic::AtomicU32 {}
283 #[cfg(target_has_atomic = "64")]
284 #[unstable(feature = "integer_atomics", issue = "32976")]
285 impl RefUnwindSafe for atomic::AtomicU64 {}
286 #[cfg(all(not(stage0), target_has_atomic = "128"))]
287 #[unstable(feature = "integer_atomics", issue = "32976")]
288 impl RefUnwindSafe for atomic::AtomicU128 {}
290 #[cfg(target_has_atomic = "8")]
291 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
292 impl RefUnwindSafe for atomic::AtomicBool {}
294 #[cfg(target_has_atomic = "ptr")]
295 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
296 impl<T> RefUnwindSafe for atomic::AtomicPtr<T> {}
298 #[stable(feature = "catch_unwind", since = "1.9.0")]
299 impl<T> Deref for AssertUnwindSafe<T> {
302 fn deref(&self) -> &T {
307 #[stable(feature = "catch_unwind", since = "1.9.0")]
308 impl<T> DerefMut for AssertUnwindSafe<T> {
309 fn deref_mut(&mut self) -> &mut T {
314 #[stable(feature = "catch_unwind", since = "1.9.0")]
315 impl<R, F: FnOnce() -> R> FnOnce<()> for AssertUnwindSafe<F> {
318 extern "rust-call" fn call_once(self, _args: ()) -> R {
323 #[stable(feature = "std_debug", since = "1.16.0")]
324 impl<T: fmt::Debug> fmt::Debug for AssertUnwindSafe<T> {
325 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
326 f.debug_tuple("AssertUnwindSafe")
332 #[unstable(feature = "futures_api", issue = "50547")]
333 impl<'a, F: Future> Future for AssertUnwindSafe<F> {
334 type Output = F::Output;
336 fn poll(self: Pin<&mut Self>, lw: &LocalWaker) -> Poll<Self::Output> {
337 let pinned_field = unsafe { Pin::map_unchecked_mut(self, |x| &mut x.0) };
338 F::poll(pinned_field, lw)
342 /// Invokes a closure, capturing the cause of an unwinding panic if one occurs.
344 /// This function will return `Ok` with the closure's result if the closure
345 /// does not panic, and will return `Err(cause)` if the closure panics. The
346 /// `cause` returned is the object with which panic was originally invoked.
348 /// It is currently undefined behavior to unwind from Rust code into foreign
349 /// code, so this function is particularly useful when Rust is called from
350 /// another language (normally C). This can run arbitrary Rust code, capturing a
351 /// panic and allowing a graceful handling of the error.
353 /// It is **not** recommended to use this function for a general try/catch
354 /// mechanism. The [`Result`] type is more appropriate to use for functions that
355 /// can fail on a regular basis. Additionally, this function is not guaranteed
356 /// to catch all panics, see the "Notes" section below.
358 /// [`Result`]: ../result/enum.Result.html
360 /// The closure provided is required to adhere to the [`UnwindSafe`] trait to ensure
361 /// that all captured variables are safe to cross this boundary. The purpose of
362 /// this bound is to encode the concept of [exception safety][rfc] in the type
363 /// system. Most usage of this function should not need to worry about this
364 /// bound as programs are naturally unwind safe without `unsafe` code. If it
365 /// becomes a problem the [`AssertUnwindSafe`] wrapper struct can be used to quickly
366 /// assert that the usage here is indeed unwind safe.
368 /// [`AssertUnwindSafe`]: ./struct.AssertUnwindSafe.html
369 /// [`UnwindSafe`]: ./trait.UnwindSafe.html
371 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
375 /// Note that this function **may not catch all panics** in Rust. A panic in
376 /// Rust is not always implemented via unwinding, but can be implemented by
377 /// aborting the process as well. This function *only* catches unwinding panics,
378 /// not those that abort the process.
385 /// let result = panic::catch_unwind(|| {
386 /// println!("hello!");
388 /// assert!(result.is_ok());
390 /// let result = panic::catch_unwind(|| {
391 /// panic!("oh no!");
393 /// assert!(result.is_err());
395 #[stable(feature = "catch_unwind", since = "1.9.0")]
396 pub fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R> {
402 /// Triggers a panic without invoking the panic hook.
404 /// This is designed to be used in conjunction with [`catch_unwind`] to, for
405 /// example, carry a panic across a layer of C code.
407 /// [`catch_unwind`]: ./fn.catch_unwind.html
411 /// Note that panics in Rust are not always implemented via unwinding, but they
412 /// may be implemented by aborting the process. If this function is called when
413 /// panics are implemented this way then this function will abort the process,
414 /// not trigger an unwind.
421 /// let result = panic::catch_unwind(|| {
422 /// panic!("oh no!");
425 /// if let Err(err) = result {
426 /// panic::resume_unwind(err);
429 #[stable(feature = "resume_unwind", since = "1.9.0")]
430 pub fn resume_unwind(payload: Box<dyn Any + Send>) -> ! {
431 panicking::update_count_then_panic(payload)