]> git.lizzy.rs Git - rust.git/blob - library/std/src/panic.rs
Merge commit '0e87918536b9833bbc6c683d1f9d51ee2bf03ef1' into clippyup
[rust.git] / library / std / src / panic.rs
1 //! Panic support in the standard library.
2
3 #![stable(feature = "std_panic", since = "1.9.0")]
4
5 use crate::any::Any;
6 use crate::cell::UnsafeCell;
7 use crate::collections;
8 use crate::fmt;
9 use crate::future::Future;
10 use crate::ops::{Deref, DerefMut};
11 use crate::panicking;
12 use crate::pin::Pin;
13 use crate::ptr::{NonNull, Unique};
14 use crate::rc::Rc;
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;
20
21 #[doc(hidden)]
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 {
27     () => ({
28         $crate::rt::begin_panic("explicit panic")
29     }),
30     ($msg:expr $(,)?) => ({
31         $crate::rt::begin_panic($msg)
32     }),
33     ($fmt:expr, $($arg:tt)+) => ({
34         $crate::rt::begin_panic_fmt(&$crate::format_args!($fmt, $($arg)+))
35     }),
36 }
37
38 #[doc(hidden)]
39 #[unstable(feature = "edition_panic", issue = "none", reason = "use panic!() instead")]
40 pub use core::panic::panic_2021;
41
42 #[stable(feature = "panic_hooks", since = "1.10.0")]
43 pub use crate::panicking::{set_hook, take_hook};
44
45 #[stable(feature = "panic_hooks", since = "1.10.0")]
46 pub use core::panic::{Location, PanicInfo};
47
48 /// Panic the current thread with the given message as the panic payload.
49 ///
50 /// The message can be of any (`Any + Send`) type, not just strings.
51 ///
52 /// The message is wrapped in a `Box<'static + Any + Send>`, which can be
53 /// accessed later using [`PanicInfo::payload`].
54 ///
55 /// See the [`panic!`] macro for more information about panicking.
56 #[stable(feature = "panic_any", since = "1.51.0")]
57 #[inline]
58 pub fn panic_any<M: 'static + Any + Send>(msg: M) -> ! {
59     crate::panicking::begin_panic(msg);
60 }
61
62 /// A marker trait which represents "panic safe" types in Rust.
63 ///
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.
68 ///
69 /// ## What is unwind safety?
70 ///
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:
75 ///
76 /// 1. A data structure is in a temporarily invalid state when the thread
77 ///    panics.
78 /// 2. This broken invariant is then later observed.
79 ///
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++).
85 ///
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
89 /// memory unsafety.
90 ///
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].
93 ///
94 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
95 ///
96 /// ## What is `UnwindSafe`?
97 ///
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
102 /// the closure.
103 ///
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).
109 ///
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.
114 ///
115 /// ## Who implements `UnwindSafe`?
116 ///
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.
122 ///
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.
126 ///
127 /// ## When should `UnwindSafe` be used?
128 ///
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"
138 )]
139 pub auto trait UnwindSafe {}
140
141 /// A marker trait representing types where a shared reference is considered
142 /// unwind safe.
143 ///
144 /// This trait is namely not implemented by [`UnsafeCell`], the root of all
145 /// interior mutability.
146 ///
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"
155 )]
156 pub auto trait RefUnwindSafe {}
157
158 /// A simple wrapper around a type to assert that it is unwind safe.
159 ///
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.
167 ///
168 /// # Examples
169 ///
170 /// One way to use `AssertUnwindSafe` is to assert that the entire closure
171 /// itself is unwind safe, bypassing all checks for all variables:
172 ///
173 /// ```
174 /// use std::panic::{self, AssertUnwindSafe};
175 ///
176 /// let mut variable = 4;
177 ///
178 /// // This code will not compile because the closure captures `&mut variable`
179 /// // which is not considered unwind safe by default.
180 ///
181 /// // panic::catch_unwind(|| {
182 /// //     variable += 3;
183 /// // });
184 ///
185 /// // This, however, will compile due to the `AssertUnwindSafe` wrapper
186 /// let result = panic::catch_unwind(AssertUnwindSafe(|| {
187 ///     variable += 3;
188 /// }));
189 /// // ...
190 /// ```
191 ///
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
199 /// not.
200 ///
201 /// ```
202 /// use std::panic::{self, AssertUnwindSafe};
203 ///
204 /// let mut variable = 4;
205 /// let other_capture = 3;
206 ///
207 /// let result = {
208 ///     let mut wrapper = AssertUnwindSafe(&mut variable);
209 ///     panic::catch_unwind(move || {
210 ///         **wrapper += other_capture;
211 ///     })
212 /// };
213 /// // ...
214 /// ```
215 #[stable(feature = "catch_unwind", since = "1.9.0")]
216 pub struct AssertUnwindSafe<T>(#[stable(feature = "catch_unwind", since = "1.9.0")] pub T);
217
218 // Implementations of the `UnwindSafe` trait:
219 //
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
225
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> {}
244
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> {}
252
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
256 // everything else).
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> {}
261
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> {}
266
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 {}
285
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 {}
304
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 {}
308
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> {}
312
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>
316 where
317     K: UnwindSafe,
318     V: UnwindSafe,
319     S: UnwindSafe,
320 {
321 }
322
323 #[stable(feature = "catch_unwind", since = "1.9.0")]
324 impl<T> Deref for AssertUnwindSafe<T> {
325     type Target = T;
326
327     fn deref(&self) -> &T {
328         &self.0
329     }
330 }
331
332 #[stable(feature = "catch_unwind", since = "1.9.0")]
333 impl<T> DerefMut for AssertUnwindSafe<T> {
334     fn deref_mut(&mut self) -> &mut T {
335         &mut self.0
336     }
337 }
338
339 #[stable(feature = "catch_unwind", since = "1.9.0")]
340 impl<R, F: FnOnce() -> R> FnOnce<()> for AssertUnwindSafe<F> {
341     type Output = R;
342
343     extern "rust-call" fn call_once(self, _args: ()) -> R {
344         (self.0)()
345     }
346 }
347
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()
352     }
353 }
354
355 #[stable(feature = "futures_api", since = "1.36.0")]
356 impl<F: Future> Future for AssertUnwindSafe<F> {
357     type Output = F::Output;
358
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)
362     }
363 }
364
365 #[unstable(feature = "async_stream", issue = "79024")]
366 impl<S: Stream> Stream for AssertUnwindSafe<S> {
367     type Item = S::Item;
368
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)
371     }
372
373     fn size_hint(&self) -> (usize, Option<usize>) {
374         self.0.size_hint()
375     }
376 }
377
378 /// Invokes a closure, capturing the cause of an unwinding panic if one occurs.
379 ///
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.
383 ///
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.
388 ///
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.
393 ///
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.
401 ///
402 /// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
403 ///
404 /// # Notes
405 ///
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.
410 ///
411 /// Also note that unwinding into Rust code with a foreign exception (e.g.
412 /// an exception thrown from C++ code) is undefined behavior.
413 ///
414 /// # Examples
415 ///
416 /// ```
417 /// use std::panic;
418 ///
419 /// let result = panic::catch_unwind(|| {
420 ///     println!("hello!");
421 /// });
422 /// assert!(result.is_ok());
423 ///
424 /// let result = panic::catch_unwind(|| {
425 ///     panic!("oh no!");
426 /// });
427 /// assert!(result.is_err());
428 /// ```
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) }
432 }
433
434 /// Triggers a panic without invoking the panic hook.
435 ///
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.
438 ///
439 /// # Notes
440 ///
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.
445 ///
446 /// # Examples
447 ///
448 /// ```should_panic
449 /// use std::panic;
450 ///
451 /// let result = panic::catch_unwind(|| {
452 ///     panic!("oh no!");
453 /// });
454 ///
455 /// if let Err(err) = result {
456 ///     panic::resume_unwind(err);
457 /// }
458 /// ```
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)
462 }
463
464 #[cfg(test)]
465 mod tests;