error.rs
This file
Path
src/error.rs
1,031 lines · 36.2 KiB · Rust
Last changed by
Add construct_ prefix to name of private construct functionsDavid Tolnaybefore adoption671f700
History of this fileTake it
1use crate::backtrace::Backtrace;2use crate::chain::Chain;3#[cfg(any(feature = "std", not(anyhow_no_core_error), anyhow_no_ptr_addr_of))]4use crate::ptr::Mut;5use crate::ptr::{Own, Ref};6use crate::{Error, StdError};7use alloc::boxed::Box;8use core::any::TypeId;9#[cfg(error_generic_member_access)]10use core::error::{self, Request};11use core::fmt::{self, Debug, Display};12use core::mem::ManuallyDrop;13#[cfg(any(feature = "std", not(anyhow_no_core_error)))]14use core::ops::{Deref, DerefMut};15#[cfg(not(anyhow_no_core_unwind_safe))]16use core::panic::{RefUnwindSafe, UnwindSafe};17#[cfg(not(anyhow_no_ptr_addr_of))]18use core::ptr;19use core::ptr::NonNull;20#[cfg(all(feature = "std", anyhow_no_core_unwind_safe))]21use std::panic::{RefUnwindSafe, UnwindSafe};2223impl Error {24 /// Create a new error object from any error type.25 ///26 /// The error type must be threadsafe and `'static`, so that the `Error`27 /// will be as well.28 ///29 /// If the error type does not provide a backtrace, a backtrace will be30 /// created here to ensure that a backtrace exists.31 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]32 #[cold]33 #[must_use]34 pub fn new<E>(error: E) -> Self35 where36 E: StdError + Send + Sync + 'static,37 {38 let backtrace = backtrace_if_absent!(&error);39 Error::construct_from_std(error, backtrace)40 }4142 /// Create a new error object from a printable error message.43 ///44 /// If the argument implements std::error::Error, prefer `Error::new`45 /// instead which preserves the underlying error's cause chain and46 /// backtrace. If the argument may or may not implement std::error::Error47 /// now or in the future, use `anyhow!(err)` which handles either way48 /// correctly.49 ///50 /// `Error::msg("...")` is equivalent to `anyhow!("...")` but occasionally51 /// convenient in places where a function is preferable over a macro, such52 /// as iterator or stream combinators:53 ///54 /// ```55 /// # mod ffi {56 /// # pub struct Input;57 /// # pub struct Output;58 /// # pub async fn do_some_work(_: Input) -> Result<Output, &'static str> {59 /// # unimplemented!()60 /// # }61 /// # }62 /// #63 /// # use ffi::{Input, Output};64 /// #65 /// use anyhow::{Error, Result};66 /// use futures::stream::{Stream, StreamExt, TryStreamExt};67 ///68 /// async fn demo<S>(stream: S) -> Result<Vec<Output>>69 /// where70 /// S: Stream<Item = Input>,71 /// {72 /// stream73 /// .then(ffi::do_some_work) // returns Result<Output, &str>74 /// .map_err(Error::msg)75 /// .try_collect()76 /// .await77 /// }78 /// ```79 #[cold]80 #[must_use]81 pub fn msg<M>(message: M) -> Self82 where83 M: Display + Debug + Send + Sync + 'static,84 {85 Error::construct_from_adhoc(message, backtrace!())86 }8788 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]89 #[cold]90 pub(crate) fn construct_from_std<E>(error: E, backtrace: Option<Backtrace>) -> Self91 where92 E: StdError + Send + Sync + 'static,93 {94 let vtable = &ErrorVTable {95 object_drop: object_drop::<E>,96 object_ref: object_ref::<E>,97 #[cfg(anyhow_no_ptr_addr_of)]98 object_mut: object_mut::<E>,99 object_boxed: object_boxed::<E>,100 object_downcast: object_downcast::<E>,101 #[cfg(anyhow_no_ptr_addr_of)]102 object_downcast_mut: object_downcast_mut::<E>,103 object_drop_rest: object_drop_front::<E>,104 #[cfg(all(105 not(error_generic_member_access),106 any(std_backtrace, feature = "backtrace")107 ))]108 object_backtrace: no_backtrace,109 };110111 // Safety: passing vtable that operates on the right type E.112 unsafe { Error::construct(error, vtable, backtrace) }113 }114115 #[cold]116 pub(crate) fn construct_from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> Self117 where118 M: Display + Debug + Send + Sync + 'static,119 {120 use crate::wrapper::MessageError;121 let error: MessageError<M> = MessageError(message);122 let vtable = &ErrorVTable {123 object_drop: object_drop::<MessageError<M>>,124 object_ref: object_ref::<MessageError<M>>,125 #[cfg(all(any(feature = "std", not(anyhow_no_core_error)), anyhow_no_ptr_addr_of))]126 object_mut: object_mut::<MessageError<M>>,127 object_boxed: object_boxed::<MessageError<M>>,128 object_downcast: object_downcast::<M>,129 #[cfg(anyhow_no_ptr_addr_of)]130 object_downcast_mut: object_downcast_mut::<M>,131 object_drop_rest: object_drop_front::<M>,132 #[cfg(all(133 not(error_generic_member_access),134 any(std_backtrace, feature = "backtrace")135 ))]136 object_backtrace: no_backtrace,137 };138139 // Safety: MessageError is repr(transparent) so it is okay for the140 // vtable to allow casting the MessageError<M> to M.141 unsafe { Error::construct(error, vtable, backtrace) }142 }143144 #[cold]145 pub(crate) fn construct_from_display<M>(message: M, backtrace: Option<Backtrace>) -> Self146 where147 M: Display + Send + Sync + 'static,148 {149 use crate::wrapper::DisplayError;150 let error: DisplayError<M> = DisplayError(message);151 let vtable = &ErrorVTable {152 object_drop: object_drop::<DisplayError<M>>,153 object_ref: object_ref::<DisplayError<M>>,154 #[cfg(all(any(feature = "std", not(anyhow_no_core_error)), anyhow_no_ptr_addr_of))]155 object_mut: object_mut::<DisplayError<M>>,156 object_boxed: object_boxed::<DisplayError<M>>,157 object_downcast: object_downcast::<M>,158 #[cfg(anyhow_no_ptr_addr_of)]159 object_downcast_mut: object_downcast_mut::<M>,160 object_drop_rest: object_drop_front::<M>,161 #[cfg(all(162 not(error_generic_member_access),163 any(std_backtrace, feature = "backtrace")164 ))]165 object_backtrace: no_backtrace,166 };167168 // Safety: DisplayError is repr(transparent) so it is okay for the169 // vtable to allow casting the DisplayError<M> to M.170 unsafe { Error::construct(error, vtable, backtrace) }171 }172173 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]174 #[cold]175 pub(crate) fn construct_from_context<C, E>(176 context: C,177 error: E,178 backtrace: Option<Backtrace>,179 ) -> Self180 where181 C: Display + Send + Sync + 'static,182 E: StdError + Send + Sync + 'static,183 {184 let error: ContextError<C, E> = ContextError { context, error };185186 let vtable = &ErrorVTable {187 object_drop: object_drop::<ContextError<C, E>>,188 object_ref: object_ref::<ContextError<C, E>>,189 #[cfg(anyhow_no_ptr_addr_of)]190 object_mut: object_mut::<ContextError<C, E>>,191 object_boxed: object_boxed::<ContextError<C, E>>,192 object_downcast: context_downcast::<C, E>,193 #[cfg(anyhow_no_ptr_addr_of)]194 object_downcast_mut: context_downcast_mut::<C, E>,195 object_drop_rest: context_drop_rest::<C, E>,196 #[cfg(all(197 not(error_generic_member_access),198 any(std_backtrace, feature = "backtrace")199 ))]200 object_backtrace: no_backtrace,201 };202203 // Safety: passing vtable that operates on the right type.204 unsafe { Error::construct(error, vtable, backtrace) }205 }206207 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]208 #[cold]209 pub(crate) fn construct_from_boxed(210 error: Box<dyn StdError + Send + Sync>,211 backtrace: Option<Backtrace>,212 ) -> Self {213 use crate::wrapper::BoxedError;214 let error = BoxedError(error);215 let vtable = &ErrorVTable {216 object_drop: object_drop::<BoxedError>,217 object_ref: object_ref::<BoxedError>,218 #[cfg(anyhow_no_ptr_addr_of)]219 object_mut: object_mut::<BoxedError>,220 object_boxed: object_boxed::<BoxedError>,221 object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,222 #[cfg(anyhow_no_ptr_addr_of)]223 object_downcast_mut: object_downcast_mut::<Box<dyn StdError + Send + Sync>>,224 object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,225 #[cfg(all(226 not(error_generic_member_access),227 any(std_backtrace, feature = "backtrace")228 ))]229 object_backtrace: no_backtrace,230 };231232 // Safety: BoxedError is repr(transparent) so it is okay for the vtable233 // to allow casting to Box<dyn StdError + Send + Sync>.234 unsafe { Error::construct(error, vtable, backtrace) }235 }236237 // Takes backtrace as argument rather than capturing it here so that the238 // user sees one fewer layer of wrapping noise in the backtrace.239 //240 // Unsafe because the given vtable must have sensible behavior on the error241 // value of type E.242 #[cold]243 unsafe fn construct<E>(244 error: E,245 vtable: &'static ErrorVTable,246 backtrace: Option<Backtrace>,247 ) -> Self248 where249 E: StdError + Send + Sync + 'static,250 {251 let inner: Box<ErrorImpl<E>> = Box::new(ErrorImpl {252 vtable,253 backtrace,254 _object: error,255 });256 // Erase the concrete type of E from the compile-time type system. This257 // is equivalent to the safe unsize coercion from Box<ErrorImpl<E>> to258 // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the259 // result is a thin pointer. The necessary behavior for manipulating the260 // underlying ErrorImpl<E> is preserved in the vtable provided by the261 // caller rather than a builtin fat pointer vtable.262 let inner = Own::new(inner).cast::<ErrorImpl>();263 Error { inner }264 }265266 /// Wrap the error value with additional context.267 ///268 /// For attaching context to a `Result` as it is propagated, the269 /// [`Context`][crate::Context] extension trait may be more convenient than270 /// this function.271 ///272 /// The primary reason to use `error.context(...)` instead of273 /// `result.context(...)` via the `Context` trait would be if the context274 /// needs to depend on some data held by the underlying error:275 ///276 /// ```277 /// # use std::fmt::{self, Debug, Display};278 /// #279 /// # type T = ();280 /// #281 /// # impl std::error::Error for ParseError {}282 /// # impl Debug for ParseError {283 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {284 /// # unimplemented!()285 /// # }286 /// # }287 /// # impl Display for ParseError {288 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {289 /// # unimplemented!()290 /// # }291 /// # }292 /// #293 /// use anyhow::Result;294 /// use std::fs::File;295 /// use std::path::Path;296 ///297 /// struct ParseError {298 /// line: usize,299 /// column: usize,300 /// }301 ///302 /// fn parse_impl(file: File) -> Result<T, ParseError> {303 /// # const IGNORE: &str = stringify! {304 /// ...305 /// # };306 /// # unimplemented!()307 /// }308 ///309 /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {310 /// let file = File::open(&path)?;311 /// parse_impl(file).map_err(|error| {312 /// let context = format!(313 /// "only the first {} lines of {} are valid",314 /// error.line, path.as_ref().display(),315 /// );316 /// anyhow::Error::new(error).context(context)317 /// })318 /// }319 /// ```320 #[cold]321 #[must_use]322 pub fn context<C>(self, context: C) -> Self323 where324 C: Display + Send + Sync + 'static,325 {326 let error: ContextError<C, Error> = ContextError {327 context,328 error: self,329 };330331 let vtable = &ErrorVTable {332 object_drop: object_drop::<ContextError<C, Error>>,333 object_ref: object_ref::<ContextError<C, Error>>,334 #[cfg(all(any(feature = "std", not(anyhow_no_core_error)), anyhow_no_ptr_addr_of))]335 object_mut: object_mut::<ContextError<C, Error>>,336 object_boxed: object_boxed::<ContextError<C, Error>>,337 object_downcast: context_chain_downcast::<C>,338 #[cfg(anyhow_no_ptr_addr_of)]339 object_downcast_mut: context_chain_downcast_mut::<C>,340 object_drop_rest: context_chain_drop_rest::<C>,341 #[cfg(all(342 not(error_generic_member_access),343 any(std_backtrace, feature = "backtrace")344 ))]345 object_backtrace: context_backtrace::<C>,346 };347348 // As the cause is anyhow::Error, we already have a backtrace for it.349 let backtrace = None;350351 // Safety: passing vtable that operates on the right type.352 unsafe { Error::construct(error, vtable, backtrace) }353 }354355 /// Get the backtrace for this Error.356 ///357 /// In order for the backtrace to be meaningful, one of the two environment358 /// variables `RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1` must be defined359 /// and `RUST_LIB_BACKTRACE` must not be `0`. Backtraces are somewhat360 /// expensive to capture in Rust, so we don't necessarily want to be361 /// capturing them all over the place all the time.362 ///363 /// - If you want panics and errors to both have backtraces, set364 /// `RUST_BACKTRACE=1`;365 /// - If you want only errors to have backtraces, set366 /// `RUST_LIB_BACKTRACE=1`;367 /// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and368 /// `RUST_LIB_BACKTRACE=0`.369 ///370 /// # Stability371 ///372 /// Standard library backtraces are only available when using Rust ≥373 /// 1.65. On older compilers, this function is only available if the crate's374 /// "backtrace" feature is enabled, and will use the `backtrace` crate as375 /// the underlying backtrace implementation. The return type of this376 /// function on old compilers is `&(impl Debug + Display)`.377 ///378 /// ```toml379 /// [dependencies]380 /// anyhow = { version = "1.0", features = ["backtrace"] }381 /// ```382 #[cfg(any(std_backtrace, feature = "backtrace"))]383 pub fn backtrace(&self) -> &impl_backtrace!() {384 unsafe { ErrorImpl::backtrace(self.inner.by_ref()) }385 }386387 /// An iterator of the chain of source errors contained by this Error.388 ///389 /// This iterator will visit every error in the cause chain of this error390 /// object, beginning with the error that this error object was created391 /// from.392 ///393 /// # Example394 ///395 /// ```396 /// use anyhow::Error;397 /// use std::io;398 ///399 /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {400 /// for cause in error.chain() {401 /// if let Some(io_error) = cause.downcast_ref::<io::Error>() {402 /// return Some(io_error.kind());403 /// }404 /// }405 /// None406 /// }407 /// ```408 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]409 #[cold]410 pub fn chain(&self) -> Chain {411 unsafe { ErrorImpl::chain(self.inner.by_ref()) }412 }413414 /// The lowest level cause of this error — this error's cause's415 /// cause's cause etc.416 ///417 /// The root cause is the last error in the iterator produced by418 /// [`chain()`][Error::chain].419 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]420 pub fn root_cause(&self) -> &(dyn StdError + 'static) {421 self.chain().last().unwrap()422 }423424 /// Returns true if `E` is the type held by this error object.425 ///426 /// For errors with context, this method returns true if `E` matches the427 /// type of the context `C` **or** the type of the error on which the428 /// context has been attached. For details about the interaction between429 /// context and downcasting, [see here].430 ///431 /// [see here]: trait.Context.html#effect-on-downcasting432 pub fn is<E>(&self) -> bool433 where434 E: Display + Debug + Send + Sync + 'static,435 {436 self.downcast_ref::<E>().is_some()437 }438439 /// Attempt to downcast the error object to a concrete type.440 pub fn downcast<E>(mut self) -> Result<E, Self>441 where442 E: Display + Debug + Send + Sync + 'static,443 {444 let target = TypeId::of::<E>();445 let inner = self.inner.by_mut();446 unsafe {447 // Use vtable to find NonNull<()> which points to a value of type E448 // somewhere inside the data structure.449 #[cfg(not(anyhow_no_ptr_addr_of))]450 let addr = match (vtable(inner.ptr).object_downcast)(inner.by_ref(), target) {451 Some(addr) => addr.by_mut().extend(),452 None => return Err(self),453 };454 #[cfg(anyhow_no_ptr_addr_of)]455 let addr = match (vtable(inner.ptr).object_downcast_mut)(inner, target) {456 Some(addr) => addr.extend(),457 None => return Err(self),458 };459460 // Prepare to read E out of the data structure. We'll drop the rest461 // of the data structure separately so that E is not dropped.462 let outer = ManuallyDrop::new(self);463464 // Read E from where the vtable found it.465 let error = addr.cast::<E>().read();466467 // Drop rest of the data structure outside of E.468 (vtable(outer.inner.ptr).object_drop_rest)(outer.inner, target);469470 Ok(error)471 }472 }473474 /// Downcast this error object by reference.475 ///476 /// # Example477 ///478 /// ```479 /// # use anyhow::anyhow;480 /// # use std::fmt::{self, Display};481 /// # use std::task::Poll;482 /// #483 /// # #[derive(Debug)]484 /// # enum DataStoreError {485 /// # Censored(()),486 /// # }487 /// #488 /// # impl Display for DataStoreError {489 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {490 /// # unimplemented!()491 /// # }492 /// # }493 /// #494 /// # impl std::error::Error for DataStoreError {}495 /// #496 /// # const REDACTED_CONTENT: () = ();497 /// #498 /// # let error = anyhow!("...");499 /// # let root_cause = &error;500 /// #501 /// # let ret =502 /// // If the error was caused by redaction, then return a tombstone instead503 /// // of the content.504 /// match root_cause.downcast_ref::<DataStoreError>() {505 /// Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),506 /// None => Err(error),507 /// }508 /// # ;509 /// ```510 pub fn downcast_ref<E>(&self) -> Option<&E>511 where512 E: Display + Debug + Send + Sync + 'static,513 {514 let target = TypeId::of::<E>();515 unsafe {516 // Use vtable to find NonNull<()> which points to a value of type E517 // somewhere inside the data structure.518 let addr = (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?;519 Some(addr.cast::<E>().deref())520 }521 }522523 /// Downcast this error object by mutable reference.524 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>525 where526 E: Display + Debug + Send + Sync + 'static,527 {528 let target = TypeId::of::<E>();529 unsafe {530 // Use vtable to find NonNull<()> which points to a value of type E531 // somewhere inside the data structure.532533 #[cfg(not(anyhow_no_ptr_addr_of))]534 let addr =535 (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?.by_mut();536537 #[cfg(anyhow_no_ptr_addr_of)]538 let addr = (vtable(self.inner.ptr).object_downcast_mut)(self.inner.by_mut(), target)?;539540 Some(addr.cast::<E>().deref_mut())541 }542 }543544 #[cfg(error_generic_member_access)]545 pub(crate) fn provide<'a>(&'a self, request: &mut Request<'a>) {546 unsafe { ErrorImpl::provide(self.inner.by_ref(), request) }547 }548549 // Called by thiserror when you have `#[source] anyhow::Error`. This provide550 // implementation includes the anyhow::Error's Backtrace if any, unlike551 // deref'ing to dyn Error where the provide implementation would include552 // only the original error's Backtrace from before it got wrapped into an553 // anyhow::Error.554 #[cfg(error_generic_member_access)]555 #[doc(hidden)]556 pub fn thiserror_provide<'a>(&'a self, request: &mut Request<'a>) {557 Self::provide(self, request);558 }559}560561#[cfg(any(feature = "std", not(anyhow_no_core_error)))]562impl<E> From<E> for Error563where564 E: StdError + Send + Sync + 'static,565{566 #[cold]567 fn from(error: E) -> Self {568 let backtrace = backtrace_if_absent!(&error);569 Error::construct_from_std(error, backtrace)570 }571}572573#[cfg(any(feature = "std", not(anyhow_no_core_error)))]574impl Deref for Error {575 type Target = dyn StdError + Send + Sync + 'static;576577 fn deref(&self) -> &Self::Target {578 unsafe { ErrorImpl::error(self.inner.by_ref()) }579 }580}581582#[cfg(any(feature = "std", not(anyhow_no_core_error)))]583impl DerefMut for Error {584 fn deref_mut(&mut self) -> &mut Self::Target {585 unsafe { ErrorImpl::error_mut(self.inner.by_mut()) }586 }587}588589impl Display for Error {590 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {591 unsafe { ErrorImpl::display(self.inner.by_ref(), formatter) }592 }593}594595impl Debug for Error {596 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {597 unsafe { ErrorImpl::debug(self.inner.by_ref(), formatter) }598 }599}600601impl Drop for Error {602 fn drop(&mut self) {603 unsafe {604 // Invoke the vtable's drop behavior.605 (vtable(self.inner.ptr).object_drop)(self.inner);606 }607 }608}609610struct ErrorVTable {611 object_drop: unsafe fn(Own<ErrorImpl>),612 object_ref: unsafe fn(Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>,613 #[cfg(all(any(feature = "std", not(anyhow_no_core_error)), anyhow_no_ptr_addr_of))]614 object_mut: unsafe fn(Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static),615 object_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,616 object_downcast: unsafe fn(Ref<ErrorImpl>, TypeId) -> Option<Ref<()>>,617 #[cfg(anyhow_no_ptr_addr_of)]618 object_downcast_mut: unsafe fn(Mut<ErrorImpl>, TypeId) -> Option<Mut<()>>,619 object_drop_rest: unsafe fn(Own<ErrorImpl>, TypeId),620 #[cfg(all(621 not(error_generic_member_access),622 any(std_backtrace, feature = "backtrace")623 ))]624 object_backtrace: unsafe fn(Ref<ErrorImpl>) -> Option<&Backtrace>,625}626627// Safety: requires layout of *e to match ErrorImpl<E>.628unsafe fn object_drop<E>(e: Own<ErrorImpl>) {629 // Cast back to ErrorImpl<E> so that the allocator receives the correct630 // Layout to deallocate the Box's memory.631 let unerased_own = e.cast::<ErrorImpl<E>>();632 drop(unsafe { unerased_own.boxed() });633}634635// Safety: requires layout of *e to match ErrorImpl<E>.636unsafe fn object_drop_front<E>(e: Own<ErrorImpl>, target: TypeId) {637 // Drop the fields of ErrorImpl other than E as well as the Box allocation,638 // without dropping E itself. This is used by downcast after doing a639 // ptr::read to take ownership of the E.640 let _ = target;641 let unerased_own = e.cast::<ErrorImpl<ManuallyDrop<E>>>();642 drop(unsafe { unerased_own.boxed() });643}644645// Safety: requires layout of *e to match ErrorImpl<E>.646unsafe fn object_ref<E>(e: Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>647where648 E: StdError + Send + Sync + 'static,649{650 // Attach E's native StdError vtable onto a pointer to self._object.651652 let unerased_ref = e.cast::<ErrorImpl<E>>();653654 #[cfg(not(anyhow_no_ptr_addr_of))]655 return Ref::from_raw(unsafe {656 NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object) as *mut E)657 });658659 #[cfg(anyhow_no_ptr_addr_of)]660 return Ref::new(unsafe { &unerased_ref.deref()._object });661}662663// Safety: requires layout of *e to match ErrorImpl<E>, and for `e` to be derived664// from a `&mut`665#[cfg(all(any(feature = "std", not(anyhow_no_core_error)), anyhow_no_ptr_addr_of))]666unsafe fn object_mut<E>(e: Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static)667where668 E: StdError + Send + Sync + 'static,669{670 // Attach E's native StdError vtable onto a pointer to self._object.671 let unerased_mut = e.cast::<ErrorImpl<E>>();672 unsafe { &mut unerased_mut.deref_mut()._object }673}674675// Safety: requires layout of *e to match ErrorImpl<E>.676unsafe fn object_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>677where678 E: StdError + Send + Sync + 'static,679{680 // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.681 let unerased_own = e.cast::<ErrorImpl<E>>();682 unsafe { unerased_own.boxed() }683}684685// Safety: requires layout of *e to match ErrorImpl<E>.686unsafe fn object_downcast<E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>687where688 E: 'static,689{690 if TypeId::of::<E>() == target {691 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a692 // pointer to its E field.693694 let unerased_ref = e.cast::<ErrorImpl<E>>();695696 #[cfg(not(anyhow_no_ptr_addr_of))]697 return Some(698 Ref::from_raw(unsafe {699 NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object) as *mut E)700 })701 .cast::<()>(),702 );703704 #[cfg(anyhow_no_ptr_addr_of)]705 return Some(Ref::new(unsafe { &unerased_ref.deref()._object }).cast::<()>());706 } else {707 None708 }709}710711// Safety: requires layout of *e to match ErrorImpl<E>.712#[cfg(anyhow_no_ptr_addr_of)]713unsafe fn object_downcast_mut<E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>714where715 E: 'static,716{717 if TypeId::of::<E>() == target {718 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a719 // pointer to its E field.720 let unerased_mut = e.cast::<ErrorImpl<E>>();721 let unerased = unsafe { unerased_mut.deref_mut() };722 Some(Mut::new(&mut unerased._object).cast::<()>())723 } else {724 None725 }726}727728#[cfg(all(729 not(error_generic_member_access),730 any(std_backtrace, feature = "backtrace")731))]732fn no_backtrace(e: Ref<ErrorImpl>) -> Option<&Backtrace> {733 let _ = e;734 None735}736737// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.738#[cfg(any(feature = "std", not(anyhow_no_core_error)))]739unsafe fn context_downcast<C, E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>740where741 C: 'static,742 E: 'static,743{744 if TypeId::of::<C>() == target {745 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();746 let unerased = unsafe { unerased_ref.deref() };747 Some(Ref::new(&unerased._object.context).cast::<()>())748 } else if TypeId::of::<E>() == target {749 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();750 let unerased = unsafe { unerased_ref.deref() };751 Some(Ref::new(&unerased._object.error).cast::<()>())752 } else {753 None754 }755}756757// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.758#[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]759unsafe fn context_downcast_mut<C, E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>760where761 C: 'static,762 E: 'static,763{764 if TypeId::of::<C>() == target {765 let unerased_mut = e.cast::<ErrorImpl<ContextError<C, E>>>();766 let unerased = unsafe { unerased_mut.deref_mut() };767 Some(Mut::new(&mut unerased._object.context).cast::<()>())768 } else if TypeId::of::<E>() == target {769 let unerased_mut = e.cast::<ErrorImpl<ContextError<C, E>>>();770 let unerased = unsafe { unerased_mut.deref_mut() };771 Some(Mut::new(&mut unerased._object.error).cast::<()>())772 } else {773 None774 }775}776777// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.778#[cfg(any(feature = "std", not(anyhow_no_core_error)))]779unsafe fn context_drop_rest<C, E>(e: Own<ErrorImpl>, target: TypeId)780where781 C: 'static,782 E: 'static,783{784 // Called after downcasting by value to either the C or the E and doing a785 // ptr::read to take ownership of that value.786 if TypeId::of::<C>() == target {787 let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>();788 drop(unsafe { unerased_own.boxed() });789 } else {790 let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>();791 drop(unsafe { unerased_own.boxed() });792 }793}794795// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.796unsafe fn context_chain_downcast<C>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>797where798 C: 'static,799{800 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();801 let unerased = unsafe { unerased_ref.deref() };802 if TypeId::of::<C>() == target {803 Some(Ref::new(&unerased._object.context).cast::<()>())804 } else {805 // Recurse down the context chain per the inner error's vtable.806 let source = &unerased._object.error;807 unsafe { (vtable(source.inner.ptr).object_downcast)(source.inner.by_ref(), target) }808 }809}810811// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.812#[cfg(anyhow_no_ptr_addr_of)]813unsafe fn context_chain_downcast_mut<C>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>814where815 C: 'static,816{817 let unerased_mut = e.cast::<ErrorImpl<ContextError<C, Error>>>();818 let unerased = unsafe { unerased_mut.deref_mut() };819 if TypeId::of::<C>() == target {820 Some(Mut::new(&mut unerased._object.context).cast::<()>())821 } else {822 // Recurse down the context chain per the inner error's vtable.823 let source = &mut unerased._object.error;824 unsafe { (vtable(source.inner.ptr).object_downcast_mut)(source.inner.by_mut(), target) }825 }826}827828// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.829unsafe fn context_chain_drop_rest<C>(e: Own<ErrorImpl>, target: TypeId)830where831 C: 'static,832{833 // Called after downcasting by value to either the C or one of the causes834 // and doing a ptr::read to take ownership of that value.835 if TypeId::of::<C>() == target {836 let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>();837 // Drop the entire rest of the data structure rooted in the next Error.838 drop(unsafe { unerased_own.boxed() });839 } else {840 let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>();841 let unerased = unsafe { unerased_own.boxed() };842 // Read the Own<ErrorImpl> from the next error.843 let inner = unerased._object.error.inner;844 drop(unerased);845 let vtable = unsafe { vtable(inner.ptr) };846 // Recursively drop the next error using the same target typeid.847 unsafe { (vtable.object_drop_rest)(inner, target) };848 }849}850851// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.852#[cfg(all(853 not(error_generic_member_access),854 any(std_backtrace, feature = "backtrace")855))]856#[allow(clippy::unnecessary_wraps)]857unsafe fn context_backtrace<C>(e: Ref<ErrorImpl>) -> Option<&Backtrace>858where859 C: 'static,860{861 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();862 let unerased = unsafe { unerased_ref.deref() };863 let backtrace = unsafe { ErrorImpl::backtrace(unerased._object.error.inner.by_ref()) };864 Some(backtrace)865}866867// NOTE: If working with `ErrorImpl<()>`, references should be avoided in favor868// of raw pointers and `NonNull`.869// repr C to ensure that E remains in the final position.870#[repr(C)]871pub(crate) struct ErrorImpl<E = ()> {872 vtable: &'static ErrorVTable,873 backtrace: Option<Backtrace>,874 // NOTE: Don't use directly. Use only through vtable. Erased type may have875 // different alignment.876 _object: E,877}878879// Reads the vtable out of `p`. This is the same as `p.as_ref().vtable`, but880// avoids converting `p` into a reference.881unsafe fn vtable(p: NonNull<ErrorImpl>) -> &'static ErrorVTable {882 // NOTE: This assumes that `ErrorVTable` is the first field of ErrorImpl.883 unsafe { *(p.as_ptr() as *const &'static ErrorVTable) }884}885886// repr C to ensure that ContextError<C, E> has the same layout as887// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.888#[repr(C)]889pub(crate) struct ContextError<C, E> {890 pub context: C,891 pub error: E,892}893894impl<E> ErrorImpl<E> {895 fn erase(&self) -> Ref<ErrorImpl> {896 // Erase the concrete type of E but preserve the vtable in self.vtable897 // for manipulating the resulting thin pointer. This is analogous to an898 // unsize coercion.899 Ref::new(self).cast::<ErrorImpl>()900 }901}902903impl ErrorImpl {904 pub(crate) unsafe fn error(this: Ref<Self>) -> &(dyn StdError + Send + Sync + 'static) {905 // Use vtable to attach E's native StdError vtable for the right906 // original type E.907 unsafe { (vtable(this.ptr).object_ref)(this).deref() }908 }909910 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]911 pub(crate) unsafe fn error_mut(this: Mut<Self>) -> &mut (dyn StdError + Send + Sync + 'static) {912 // Use vtable to attach E's native StdError vtable for the right913 // original type E.914915 #[cfg(not(anyhow_no_ptr_addr_of))]916 return unsafe {917 (vtable(this.ptr).object_ref)(this.by_ref())918 .by_mut()919 .deref_mut()920 };921922 #[cfg(anyhow_no_ptr_addr_of)]923 return unsafe { (vtable(this.ptr).object_mut)(this) };924 }925926 #[cfg(any(std_backtrace, feature = "backtrace"))]927 pub(crate) unsafe fn backtrace(this: Ref<Self>) -> &Backtrace {928 // This unwrap can only panic if the underlying error's backtrace method929 // is nondeterministic, which would only happen in maliciously930 // constructed code.931 unsafe { this.deref() }932 .backtrace933 .as_ref()934 .or_else(|| {935 #[cfg(error_generic_member_access)]936 return error::request_ref::<Backtrace>(unsafe { Self::error(this) });937 #[cfg(not(error_generic_member_access))]938 return unsafe { (vtable(this.ptr).object_backtrace)(this) };939 })940 .expect("backtrace capture failed")941 }942943 #[cfg(error_generic_member_access)]944 unsafe fn provide<'a>(this: Ref<'a, Self>, request: &mut Request<'a>) {945 if let Some(backtrace) = unsafe { &this.deref().backtrace } {946 request.provide_ref(backtrace);947 }948 unsafe { Self::error(this) }.provide(request);949 }950951 #[cold]952 pub(crate) unsafe fn chain(this: Ref<Self>) -> Chain {953 Chain::new(unsafe { Self::error(this) })954 }955}956957impl<E> StdError for ErrorImpl<E>958where959 E: StdError,960{961 fn source(&self) -> Option<&(dyn StdError + 'static)> {962 unsafe { ErrorImpl::error(self.erase()).source() }963 }964965 #[cfg(error_generic_member_access)]966 fn provide<'a>(&'a self, request: &mut Request<'a>) {967 unsafe { ErrorImpl::provide(self.erase(), request) }968 }969}970971impl<E> Debug for ErrorImpl<E>972where973 E: Debug,974{975 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {976 unsafe { ErrorImpl::debug(self.erase(), formatter) }977 }978}979980impl<E> Display for ErrorImpl<E>981where982 E: Display,983{984 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {985 unsafe { Display::fmt(ErrorImpl::error(self.erase()), formatter) }986 }987}988989impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {990 #[cold]991 fn from(error: Error) -> Self {992 let outer = ManuallyDrop::new(error);993 unsafe {994 // Use vtable to attach ErrorImpl<E>'s native StdError vtable for995 // the right original type E.996 (vtable(outer.inner.ptr).object_boxed)(outer.inner)997 }998 }999}10001001impl From<Error> for Box<dyn StdError + Send + 'static> {1002 fn from(error: Error) -> Self {1003 Box::<dyn StdError + Send + Sync>::from(error)1004 }1005}10061007impl From<Error> for Box<dyn StdError + 'static> {1008 fn from(error: Error) -> Self {1009 Box::<dyn StdError + Send + Sync>::from(error)1010 }1011}10121013#[cfg(any(feature = "std", not(anyhow_no_core_error)))]1014impl AsRef<dyn StdError + Send + Sync> for Error {1015 fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {1016 &**self1017 }1018}10191020#[cfg(any(feature = "std", not(anyhow_no_core_error)))]1021impl AsRef<dyn StdError> for Error {1022 fn as_ref(&self) -> &(dyn StdError + 'static) {1023 &**self1024 }1025}10261027#[cfg(any(feature = "std", not(anyhow_no_core_unwind_safe)))]1028impl UnwindSafe for Error {}10291030#[cfg(any(feature = "std", not(anyhow_no_core_unwind_safe)))]1031impl RefUnwindSafe for Error {}