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