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::{self, 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 a marker 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 = "the type {Self} may not be safely transferred \
114 across an unwind boundary"]
115 pub auto trait UnwindSafe {}
117 /// A marker trait representing types where a shared reference is considered
120 /// This trait is namely not implemented by [`UnsafeCell`], the root of all
121 /// interior mutability.
123 /// This is a "helper marker trait" used to provide impl blocks for the
124 /// [`UnwindSafe`] trait, for more information see that documentation.
126 /// [`UnsafeCell`]: ../cell/struct.UnsafeCell.html
127 /// [`UnwindSafe`]: ./trait.UnwindSafe.html
128 #[stable(feature = "catch_unwind", since = "1.9.0")]
129 #[rustc_on_unimplemented = "the type {Self} may contain interior mutability \
130 and a reference may not be safely transferrable \
131 across a catch_unwind boundary"]
132 pub auto trait RefUnwindSafe {}
134 /// A simple wrapper around a type to assert that it is unwind safe.
136 /// When using [`catch_unwind`] it may be the case that some of the closed over
137 /// variables are not unwind safe. For example if `&mut T` is captured the
138 /// compiler will generate a warning indicating that it is not unwind safe. It
139 /// may not be the case, however, that this is actually a problem due to the
140 /// specific usage of [`catch_unwind`] if unwind safety is specifically taken into
141 /// account. This wrapper struct is useful for a quick and lightweight
142 /// annotation that a variable is indeed unwind safe.
144 /// [`catch_unwind`]: ./fn.catch_unwind.html
147 /// One way to use `AssertUnwindSafe` is to assert that the entire closure
148 /// itself is unwind safe, bypassing all checks for all variables:
151 /// use std::panic::{self, AssertUnwindSafe};
153 /// let mut variable = 4;
155 /// // This code will not compile because the closure captures `&mut variable`
156 /// // which is not considered unwind safe by default.
158 /// // panic::catch_unwind(|| {
159 /// // variable += 3;
162 /// // This, however, will compile due to the `AssertUnwindSafe` wrapper
163 /// let result = panic::catch_unwind(AssertUnwindSafe(|| {
169 /// Wrapping the entire closure amounts to a blanket assertion that all captured
170 /// variables are unwind safe. This has the downside that if new captures are
171 /// added in the future, they will also be considered unwind safe. Therefore,
172 /// you may prefer to just wrap individual captures, as shown below. This is
173 /// more annotation, but it ensures that if a new capture is added which is not
174 /// unwind safe, you will get a compilation error at that time, which will
175 /// allow you to consider whether that new capture in fact represent a bug or
179 /// use std::panic::{self, AssertUnwindSafe};
181 /// let mut variable = 4;
182 /// let other_capture = 3;
185 /// let mut wrapper = AssertUnwindSafe(&mut variable);
186 /// panic::catch_unwind(move || {
187 /// **wrapper += other_capture;
192 #[stable(feature = "catch_unwind", since = "1.9.0")]
193 pub struct AssertUnwindSafe<T>(
194 #[stable(feature = "catch_unwind", since = "1.9.0")]
198 // Implementations of the `UnwindSafe` trait:
200 // * By default everything is unwind safe
201 // * pointers T contains mutability of some form are not unwind safe
202 // * Unique, an owning pointer, lifts an implementation
203 // * Types like Mutex/RwLock which are explicitly poisoned are unwind safe
204 // * Our custom AssertUnwindSafe wrapper is indeed unwind safe
206 #[stable(feature = "catch_unwind", since = "1.9.0")]
207 impl<'a, T: ?Sized> !UnwindSafe for &'a mut T {}
208 #[stable(feature = "catch_unwind", since = "1.9.0")]
209 impl<'a, T: RefUnwindSafe + ?Sized> UnwindSafe for &'a T {}
210 #[stable(feature = "catch_unwind", since = "1.9.0")]
211 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *const T {}
212 #[stable(feature = "catch_unwind", since = "1.9.0")]
213 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *mut T {}
214 #[unstable(feature = "ptr_internals", issue = "0")]
215 impl<T: UnwindSafe + ?Sized> UnwindSafe for Unique<T> {}
216 #[stable(feature = "nonnull", since = "1.25.0")]
217 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for NonNull<T> {}
218 #[stable(feature = "catch_unwind", since = "1.9.0")]
219 impl<T: ?Sized> UnwindSafe for Mutex<T> {}
220 #[stable(feature = "catch_unwind", since = "1.9.0")]
221 impl<T: ?Sized> UnwindSafe for RwLock<T> {}
222 #[stable(feature = "catch_unwind", since = "1.9.0")]
223 impl<T> UnwindSafe for AssertUnwindSafe<T> {}
225 // not covered via the Shared impl above b/c the inner contents use
226 // Cell/AtomicUsize, but the usage here is unwind safe so we can lift the
227 // impl up one level to Arc/Rc itself
228 #[stable(feature = "catch_unwind", since = "1.9.0")]
229 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Rc<T> {}
230 #[stable(feature = "catch_unwind", since = "1.9.0")]
231 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Arc<T> {}
233 // Pretty simple implementations for the `RefUnwindSafe` marker trait,
234 // basically just saying that `UnsafeCell` is the
235 // only thing which doesn't implement it (which then transitively applies to
237 #[stable(feature = "catch_unwind", since = "1.9.0")]
238 impl<T: ?Sized> !RefUnwindSafe for UnsafeCell<T> {}
239 #[stable(feature = "catch_unwind", since = "1.9.0")]
240 impl<T> RefUnwindSafe for AssertUnwindSafe<T> {}
242 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
243 impl<T: ?Sized> RefUnwindSafe for Mutex<T> {}
244 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
245 impl<T: ?Sized> RefUnwindSafe for RwLock<T> {}
247 #[cfg(target_has_atomic = "ptr")]
248 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
249 impl RefUnwindSafe for atomic::AtomicIsize {}
250 #[cfg(target_has_atomic = "8")]
251 #[unstable(feature = "integer_atomics", issue = "32976")]
252 impl RefUnwindSafe for atomic::AtomicI8 {}
253 #[cfg(target_has_atomic = "16")]
254 #[unstable(feature = "integer_atomics", issue = "32976")]
255 impl RefUnwindSafe for atomic::AtomicI16 {}
256 #[cfg(target_has_atomic = "32")]
257 #[unstable(feature = "integer_atomics", issue = "32976")]
258 impl RefUnwindSafe for atomic::AtomicI32 {}
259 #[cfg(target_has_atomic = "64")]
260 #[unstable(feature = "integer_atomics", issue = "32976")]
261 impl RefUnwindSafe for atomic::AtomicI64 {}
263 #[cfg(target_has_atomic = "ptr")]
264 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
265 impl RefUnwindSafe for atomic::AtomicUsize {}
266 #[cfg(target_has_atomic = "8")]
267 #[unstable(feature = "integer_atomics", issue = "32976")]
268 impl RefUnwindSafe for atomic::AtomicU8 {}
269 #[cfg(target_has_atomic = "16")]
270 #[unstable(feature = "integer_atomics", issue = "32976")]
271 impl RefUnwindSafe for atomic::AtomicU16 {}
272 #[cfg(target_has_atomic = "32")]
273 #[unstable(feature = "integer_atomics", issue = "32976")]
274 impl RefUnwindSafe for atomic::AtomicU32 {}
275 #[cfg(target_has_atomic = "64")]
276 #[unstable(feature = "integer_atomics", issue = "32976")]
277 impl RefUnwindSafe for atomic::AtomicU64 {}
279 #[cfg(target_has_atomic = "8")]
280 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
281 impl RefUnwindSafe for atomic::AtomicBool {}
283 #[cfg(target_has_atomic = "ptr")]
284 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
285 impl<T> RefUnwindSafe for atomic::AtomicPtr<T> {}
287 #[stable(feature = "catch_unwind", since = "1.9.0")]
288 impl<T> Deref for AssertUnwindSafe<T> {
291 fn deref(&self) -> &T {
296 #[stable(feature = "catch_unwind", since = "1.9.0")]
297 impl<T> DerefMut for AssertUnwindSafe<T> {
298 fn deref_mut(&mut self) -> &mut T {
303 #[stable(feature = "catch_unwind", since = "1.9.0")]
304 impl<R, F: FnOnce() -> R> FnOnce<()> for AssertUnwindSafe<F> {
307 extern "rust-call" fn call_once(self, _args: ()) -> R {
312 #[stable(feature = "std_debug", since = "1.16.0")]
313 impl<T: fmt::Debug> fmt::Debug for AssertUnwindSafe<T> {
314 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
315 f.debug_tuple("AssertUnwindSafe")
321 #[unstable(feature = "futures_api", issue = "50547")]
322 impl<'a, F: Future> Future for AssertUnwindSafe<F> {
323 type Output = F::Output;
325 fn poll(mut self: PinMut<Self>, cx: &mut task::Context) -> Poll<Self::Output> {
327 let pinned_field = PinMut::new_unchecked(
328 &mut PinMut::get_mut(self.reborrow()).0
331 pinned_field.poll(cx)
336 /// Invokes a closure, capturing the cause of an unwinding panic if one occurs.
338 /// This function will return `Ok` with the closure's result if the closure
339 /// does not panic, and will return `Err(cause)` if the closure panics. The
340 /// `cause` returned is the object with which panic was originally invoked.
342 /// It is currently undefined behavior to unwind from Rust code into foreign
343 /// code, so this function is particularly useful when Rust is called from
344 /// another language (normally C). This can run arbitrary Rust code, capturing a
345 /// panic and allowing a graceful handling of the error.
347 /// It is **not** recommended to use this function for a general try/catch
348 /// mechanism. The [`Result`] type is more appropriate to use for functions that
349 /// can fail on a regular basis. Additionally, this function is not guaranteed
350 /// to catch all panics, see the "Notes" section below.
352 /// [`Result`]: ../result/enum.Result.html
354 /// The closure provided is required to adhere to the [`UnwindSafe`] trait to ensure
355 /// that all captured variables are safe to cross this boundary. The purpose of
356 /// this bound is to encode the concept of [exception safety][rfc] in the type
357 /// system. Most usage of this function should not need to worry about this
358 /// bound as programs are naturally unwind safe without `unsafe` code. If it
359 /// becomes a problem the [`AssertUnwindSafe`] wrapper struct can be used to quickly
360 /// assert that the usage here is indeed unwind safe.
362 /// [`AssertUnwindSafe`]: ./struct.AssertUnwindSafe.html
363 /// [`UnwindSafe`]: ./trait.UnwindSafe.html
365 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
369 /// Note that this function **may not catch all panics** in Rust. A panic in
370 /// Rust is not always implemented via unwinding, but can be implemented by
371 /// aborting the process as well. This function *only* catches unwinding panics,
372 /// not those that abort the process.
379 /// let result = panic::catch_unwind(|| {
380 /// println!("hello!");
382 /// assert!(result.is_ok());
384 /// let result = panic::catch_unwind(|| {
385 /// panic!("oh no!");
387 /// assert!(result.is_err());
389 #[stable(feature = "catch_unwind", since = "1.9.0")]
390 pub fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R> {
396 /// Triggers a panic without invoking the panic hook.
398 /// This is designed to be used in conjunction with [`catch_unwind`] to, for
399 /// example, carry a panic across a layer of C code.
401 /// [`catch_unwind`]: ./fn.catch_unwind.html
405 /// Note that panics in Rust are not always implemented via unwinding, but they
406 /// may be implemented by aborting the process. If this function is called when
407 /// panics are implemented this way then this function will abort the process,
408 /// not trigger an unwind.
415 /// let result = panic::catch_unwind(|| {
416 /// panic!("oh no!");
419 /// if let Err(err) = result {
420 /// panic::resume_unwind(err);
423 #[stable(feature = "resume_unwind", since = "1.9.0")]
424 pub fn resume_unwind(payload: Box<Any + Send>) -> ! {
425 panicking::update_count_then_panic(payload)