]> git.lizzy.rs Git - rust.git/blob - src/libstd/panic.rs
Fixes doc important trait display on mobile
[rust.git] / src / libstd / panic.rs
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.
4 //
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.
10
11 //! Panic support in the standard library.
12
13 #![stable(feature = "std_panic", since = "1.9.0")]
14
15 use any::Any;
16 use cell::UnsafeCell;
17 use fmt;
18 use ops::{Deref, DerefMut};
19 use panicking;
20 use ptr::{Unique, Shared};
21 use rc::Rc;
22 use sync::{Arc, Mutex, RwLock, atomic};
23 use thread::Result;
24
25 #[stable(feature = "panic_hooks", since = "1.10.0")]
26 pub use panicking::{take_hook, set_hook, PanicInfo, Location};
27
28 /// A marker trait which represents "panic safe" types in Rust.
29 ///
30 /// This trait is implemented by default for many types and behaves similarly in
31 /// terms of inference of implementation to the `Send` and `Sync` traits. The
32 /// purpose of this trait is to encode what types are safe to cross a `catch_unwind`
33 /// boundary with no fear of unwind safety.
34 ///
35 /// ## What is unwind safety?
36 ///
37 /// In Rust a function can "return" early if it either panics or calls a
38 /// function which transitively panics. This sort of control flow is not always
39 /// anticipated, and has the possibility of causing subtle bugs through a
40 /// combination of two critical components:
41 ///
42 /// 1. A data structure is in a temporarily invalid state when the thread
43 ///    panics.
44 /// 2. This broken invariant is then later observed.
45 ///
46 /// Typically in Rust, it is difficult to perform step (2) because catching a
47 /// panic involves either spawning a thread (which in turns makes it difficult
48 /// to later witness broken invariants) or using the `catch_unwind` function in this
49 /// module. Additionally, even if an invariant is witnessed, it typically isn't a
50 /// problem in Rust because there are no uninitialized values (like in C or C++).
51 ///
52 /// It is possible, however, for **logical** invariants to be broken in Rust,
53 /// which can end up causing behavioral bugs. Another key aspect of unwind safety
54 /// in Rust is that, in the absence of `unsafe` code, a panic cannot lead to
55 /// memory unsafety.
56 ///
57 /// That was a bit of a whirlwind tour of unwind safety, but for more information
58 /// about unwind safety and how it applies to Rust, see an [associated RFC][rfc].
59 ///
60 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
61 ///
62 /// ## What is `UnwindSafe`?
63 ///
64 /// Now that we've got an idea of what unwind safety is in Rust, it's also
65 /// important to understand what this trait represents. As mentioned above, one
66 /// way to witness broken invariants is through the `catch_unwind` function in this
67 /// module as it allows catching a panic and then re-using the environment of
68 /// the closure.
69 ///
70 /// Simply put, a type `T` implements `UnwindSafe` if it cannot easily allow
71 /// witnessing a broken invariant through the use of `catch_unwind` (catching a
72 /// panic). This trait is a marker trait, so it is automatically implemented for
73 /// many types, and it is also structurally composed (e.g. a struct is unwind
74 /// safe if all of its components are unwind safe).
75 ///
76 /// Note, however, that this is not an unsafe trait, so there is not a succinct
77 /// contract that this trait is providing. Instead it is intended as more of a
78 /// "speed bump" to alert users of `catch_unwind` that broken invariants may be
79 /// witnessed and may need to be accounted for.
80 ///
81 /// ## Who implements `UnwindSafe`?
82 ///
83 /// Types such as `&mut T` and `&RefCell<T>` are examples which are **not**
84 /// unwind safe. The general idea is that any mutable state which can be shared
85 /// across `catch_unwind` is not unwind safe by default. This is because it is very
86 /// easy to witness a broken invariant outside of `catch_unwind` as the data is
87 /// simply accessed as usual.
88 ///
89 /// Types like `&Mutex<T>`, however, are unwind safe because they implement
90 /// poisoning by default. They still allow witnessing a broken invariant, but
91 /// they already provide their own "speed bumps" to do so.
92 ///
93 /// ## When should `UnwindSafe` be used?
94 ///
95 /// Is not intended that most types or functions need to worry about this trait.
96 /// It is only used as a bound on the `catch_unwind` function and as mentioned above,
97 /// the lack of `unsafe` means it is mostly an advisory. The `AssertUnwindSafe`
98 /// wrapper struct in this module can be used to force this trait to be
99 /// implemented for any closed over variables passed to the `catch_unwind` function
100 /// (more on this below).
101 #[stable(feature = "catch_unwind", since = "1.9.0")]
102 #[rustc_on_unimplemented = "the type {Self} may not be safely transferred \
103                             across an unwind boundary"]
104 pub trait UnwindSafe {}
105
106 /// A marker trait representing types where a shared reference is considered
107 /// unwind safe.
108 ///
109 /// This trait is namely not implemented by `UnsafeCell`, the root of all
110 /// interior mutability.
111 ///
112 /// This is a "helper marker trait" used to provide impl blocks for the
113 /// `UnwindSafe` trait, for more information see that documentation.
114 #[stable(feature = "catch_unwind", since = "1.9.0")]
115 #[rustc_on_unimplemented = "the type {Self} may contain interior mutability \
116                             and a reference may not be safely transferrable \
117                             across a catch_unwind boundary"]
118 pub trait RefUnwindSafe {}
119
120 /// A simple wrapper around a type to assert that it is unwind safe.
121 ///
122 /// When using `catch_unwind` it may be the case that some of the closed over
123 /// variables are not unwind safe. For example if `&mut T` is captured the
124 /// compiler will generate a warning indicating that it is not unwind safe. It
125 /// may not be the case, however, that this is actually a problem due to the
126 /// specific usage of `catch_unwind` if unwind safety is specifically taken into
127 /// account. This wrapper struct is useful for a quick and lightweight
128 /// annotation that a variable is indeed unwind safe.
129 ///
130 /// # Examples
131 ///
132 /// One way to use `AssertUnwindSafe` is to assert that the entire closure
133 /// itself is unwind safe, bypassing all checks for all variables:
134 ///
135 /// ```
136 /// use std::panic::{self, AssertUnwindSafe};
137 ///
138 /// let mut variable = 4;
139 ///
140 /// // This code will not compile because the closure captures `&mut variable`
141 /// // which is not considered unwind safe by default.
142 ///
143 /// // panic::catch_unwind(|| {
144 /// //     variable += 3;
145 /// // });
146 ///
147 /// // This, however, will compile due to the `AssertUnwindSafe` wrapper
148 /// let result = panic::catch_unwind(AssertUnwindSafe(|| {
149 ///     variable += 3;
150 /// }));
151 /// // ...
152 /// ```
153 ///
154 /// Wrapping the entire closure amounts to a blanket assertion that all captured
155 /// variables are unwind safe. This has the downside that if new captures are
156 /// added in the future, they will also be considered unwind safe. Therefore,
157 /// you may prefer to just wrap individual captures, as shown below. This is
158 /// more annotation, but it ensures that if a new capture is added which is not
159 /// unwind safe, you will get a compilation error at that time, which will
160 /// allow you to consider whether that new capture in fact represent a bug or
161 /// not.
162 ///
163 /// ```
164 /// use std::panic::{self, AssertUnwindSafe};
165 ///
166 /// let mut variable = 4;
167 /// let other_capture = 3;
168 ///
169 /// let result = {
170 ///     let mut wrapper = AssertUnwindSafe(&mut variable);
171 ///     panic::catch_unwind(move || {
172 ///         **wrapper += other_capture;
173 ///     })
174 /// };
175 /// // ...
176 /// ```
177 #[stable(feature = "catch_unwind", since = "1.9.0")]
178 pub struct AssertUnwindSafe<T>(
179     #[stable(feature = "catch_unwind", since = "1.9.0")]
180     pub T
181 );
182
183 // Implementations of the `UnwindSafe` trait:
184 //
185 // * By default everything is unwind safe
186 // * pointers T contains mutability of some form are not unwind safe
187 // * Unique, an owning pointer, lifts an implementation
188 // * Types like Mutex/RwLock which are explicilty poisoned are unwind safe
189 // * Our custom AssertUnwindSafe wrapper is indeed unwind safe
190 #[stable(feature = "catch_unwind", since = "1.9.0")]
191 #[allow(unknown_lints)]
192 #[allow(auto_impl)]
193 impl UnwindSafe for .. {}
194 #[stable(feature = "catch_unwind", since = "1.9.0")]
195 impl<'a, T: ?Sized> !UnwindSafe for &'a mut T {}
196 #[stable(feature = "catch_unwind", since = "1.9.0")]
197 impl<'a, T: RefUnwindSafe + ?Sized> UnwindSafe for &'a T {}
198 #[stable(feature = "catch_unwind", since = "1.9.0")]
199 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *const T {}
200 #[stable(feature = "catch_unwind", since = "1.9.0")]
201 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *mut T {}
202 #[unstable(feature = "unique", issue = "27730")]
203 impl<T: UnwindSafe + ?Sized> UnwindSafe for Unique<T> {}
204 #[unstable(feature = "shared", issue = "27730")]
205 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Shared<T> {}
206 #[stable(feature = "catch_unwind", since = "1.9.0")]
207 impl<T: ?Sized> UnwindSafe for Mutex<T> {}
208 #[stable(feature = "catch_unwind", since = "1.9.0")]
209 impl<T: ?Sized> UnwindSafe for RwLock<T> {}
210 #[stable(feature = "catch_unwind", since = "1.9.0")]
211 impl<T> UnwindSafe for AssertUnwindSafe<T> {}
212
213 // not covered via the Shared impl above b/c the inner contents use
214 // Cell/AtomicUsize, but the usage here is unwind safe so we can lift the
215 // impl up one level to Arc/Rc itself
216 #[stable(feature = "catch_unwind", since = "1.9.0")]
217 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Rc<T> {}
218 #[stable(feature = "catch_unwind", since = "1.9.0")]
219 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Arc<T> {}
220
221 // Pretty simple implementations for the `RefUnwindSafe` marker trait,
222 // basically just saying that this is a marker trait and `UnsafeCell` is the
223 // only thing which doesn't implement it (which then transitively applies to
224 // everything else).
225 #[stable(feature = "catch_unwind", since = "1.9.0")]
226 #[allow(unknown_lints)]
227 #[allow(auto_impl)]
228 impl RefUnwindSafe for .. {}
229 #[stable(feature = "catch_unwind", since = "1.9.0")]
230 impl<T: ?Sized> !RefUnwindSafe for UnsafeCell<T> {}
231 #[stable(feature = "catch_unwind", since = "1.9.0")]
232 impl<T> RefUnwindSafe for AssertUnwindSafe<T> {}
233
234 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
235 impl<T: ?Sized> RefUnwindSafe for Mutex<T> {}
236 #[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
237 impl<T: ?Sized> RefUnwindSafe for RwLock<T> {}
238
239 #[cfg(target_has_atomic = "ptr")]
240 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
241 impl RefUnwindSafe for atomic::AtomicIsize {}
242 #[cfg(target_has_atomic = "8")]
243 #[unstable(feature = "integer_atomics", issue = "32976")]
244 impl RefUnwindSafe for atomic::AtomicI8 {}
245 #[cfg(target_has_atomic = "16")]
246 #[unstable(feature = "integer_atomics", issue = "32976")]
247 impl RefUnwindSafe for atomic::AtomicI16 {}
248 #[cfg(target_has_atomic = "32")]
249 #[unstable(feature = "integer_atomics", issue = "32976")]
250 impl RefUnwindSafe for atomic::AtomicI32 {}
251 #[cfg(target_has_atomic = "64")]
252 #[unstable(feature = "integer_atomics", issue = "32976")]
253 impl RefUnwindSafe for atomic::AtomicI64 {}
254
255 #[cfg(target_has_atomic = "ptr")]
256 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
257 impl RefUnwindSafe for atomic::AtomicUsize {}
258 #[cfg(target_has_atomic = "8")]
259 #[unstable(feature = "integer_atomics", issue = "32976")]
260 impl RefUnwindSafe for atomic::AtomicU8 {}
261 #[cfg(target_has_atomic = "16")]
262 #[unstable(feature = "integer_atomics", issue = "32976")]
263 impl RefUnwindSafe for atomic::AtomicU16 {}
264 #[cfg(target_has_atomic = "32")]
265 #[unstable(feature = "integer_atomics", issue = "32976")]
266 impl RefUnwindSafe for atomic::AtomicU32 {}
267 #[cfg(target_has_atomic = "64")]
268 #[unstable(feature = "integer_atomics", issue = "32976")]
269 impl RefUnwindSafe for atomic::AtomicU64 {}
270
271 #[cfg(target_has_atomic = "8")]
272 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
273 impl RefUnwindSafe for atomic::AtomicBool {}
274
275 #[cfg(target_has_atomic = "ptr")]
276 #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
277 impl<T> RefUnwindSafe for atomic::AtomicPtr<T> {}
278
279 #[stable(feature = "catch_unwind", since = "1.9.0")]
280 impl<T> Deref for AssertUnwindSafe<T> {
281     type Target = T;
282
283     fn deref(&self) -> &T {
284         &self.0
285     }
286 }
287
288 #[stable(feature = "catch_unwind", since = "1.9.0")]
289 impl<T> DerefMut for AssertUnwindSafe<T> {
290     fn deref_mut(&mut self) -> &mut T {
291         &mut self.0
292     }
293 }
294
295 #[stable(feature = "catch_unwind", since = "1.9.0")]
296 impl<R, F: FnOnce() -> R> FnOnce<()> for AssertUnwindSafe<F> {
297     type Output = R;
298
299     extern "rust-call" fn call_once(self, _args: ()) -> R {
300         (self.0)()
301     }
302 }
303
304 #[stable(feature = "std_debug", since = "1.16.0")]
305 impl<T: fmt::Debug> fmt::Debug for AssertUnwindSafe<T> {
306     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
307         f.debug_tuple("AssertUnwindSafe")
308             .field(&self.0)
309             .finish()
310     }
311 }
312
313 /// Invokes a closure, capturing the cause of an unwinding panic if one occurs.
314 ///
315 /// This function will return `Ok` with the closure's result if the closure
316 /// does not panic, and will return `Err(cause)` if the closure panics. The
317 /// `cause` returned is the object with which panic was originally invoked.
318 ///
319 /// It is currently undefined behavior to unwind from Rust code into foreign
320 /// code, so this function is particularly useful when Rust is called from
321 /// another language (normally C). This can run arbitrary Rust code, capturing a
322 /// panic and allowing a graceful handling of the error.
323 ///
324 /// It is **not** recommended to use this function for a general try/catch
325 /// mechanism. The `Result` type is more appropriate to use for functions that
326 /// can fail on a regular basis. Additionally, this function is not guaranteed
327 /// to catch all panics, see the "Notes" section below.
328 ///
329 /// The closure provided is required to adhere to the `UnwindSafe` trait to ensure
330 /// that all captured variables are safe to cross this boundary. The purpose of
331 /// this bound is to encode the concept of [exception safety][rfc] in the type
332 /// system. Most usage of this function should not need to worry about this
333 /// bound as programs are naturally unwind safe without `unsafe` code. If it
334 /// becomes a problem the associated `AssertUnwindSafe` wrapper type in this
335 /// module can be used to quickly assert that the usage here is indeed unwind
336 /// safe.
337 ///
338 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
339 ///
340 /// # Notes
341 ///
342 /// Note that this function **may not catch all panics** in Rust. A panic in
343 /// Rust is not always implemented via unwinding, but can be implemented by
344 /// aborting the process as well. This function *only* catches unwinding panics,
345 /// not those that abort the process.
346 ///
347 /// # Examples
348 ///
349 /// ```
350 /// use std::panic;
351 ///
352 /// let result = panic::catch_unwind(|| {
353 ///     println!("hello!");
354 /// });
355 /// assert!(result.is_ok());
356 ///
357 /// let result = panic::catch_unwind(|| {
358 ///     panic!("oh no!");
359 /// });
360 /// assert!(result.is_err());
361 /// ```
362 #[stable(feature = "catch_unwind", since = "1.9.0")]
363 pub fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R> {
364     unsafe {
365         panicking::try(f)
366     }
367 }
368
369 /// Triggers a panic without invoking the panic hook.
370 ///
371 /// This is designed to be used in conjunction with `catch_unwind` to, for
372 /// example, carry a panic across a layer of C code.
373 ///
374 /// # Notes
375 ///
376 /// Note that panics in Rust are not always implemented via unwinding, but they
377 /// may be implemented by aborting the process. If this function is called when
378 /// panics are implemented this way then this function will abort the process,
379 /// not trigger an unwind.
380 ///
381 /// # Examples
382 ///
383 /// ```should_panic
384 /// use std::panic;
385 ///
386 /// let result = panic::catch_unwind(|| {
387 ///     panic!("oh no!");
388 /// });
389 ///
390 /// if let Err(err) = result {
391 ///     panic::resume_unwind(err);
392 /// }
393 /// ```
394 #[stable(feature = "resume_unwind", since = "1.9.0")]
395 pub fn resume_unwind(payload: Box<Any + Send>) -> ! {
396     panicking::update_count_then_panic(payload)
397 }