Skip to content
Myr

error.rs

This file

Path

src/error.rs

1,001 lines · 34.7 KiB · Rust

Last changed by

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

History of this file

Take it

1use crate::backtrace::Backtrace;2use crate::chain::Chain;3#[cfg(any(feature = "std", 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;9use core::fmt::{self, Debug, Display};10use core::mem::ManuallyDrop;11#[cfg(not(anyhow_no_ptr_addr_of))]12use core::ptr;13use core::ptr::NonNull;14#[cfg(backtrace)]15use std::error::{self, Request};1617#[cfg(feature = "std")]18use core::ops::{Deref, DerefMut};1920impl Error {21    /// Create a new error object from any error type.22    ///23    /// The error type must be threadsafe and `'static`, so that the `Error`24    /// will be as well.25    ///26    /// If the error type does not provide a backtrace, a backtrace will be27    /// created here to ensure that a backtrace exists.28    #[cfg(feature = "std")]29    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]30    #[cold]31    #[must_use]32    pub fn new<E>(error: E) -> Self33    where34        E: StdError + Send + Sync + 'static,35    {36        let backtrace = backtrace_if_absent!(&error);37        Error::from_std(error, backtrace)38    }3940    /// Create a new error object from a printable error message.41    ///42    /// If the argument implements std::error::Error, prefer `Error::new`43    /// instead which preserves the underlying error's cause chain and44    /// backtrace. If the argument may or may not implement std::error::Error45    /// now or in the future, use `anyhow!(err)` which handles either way46    /// correctly.47    ///48    /// `Error::msg("...")` is equivalent to `anyhow!("...")` but occasionally49    /// convenient in places where a function is preferable over a macro, such50    /// as iterator or stream combinators:51    ///52    /// ```53    /// # mod ffi {54    /// #     pub struct Input;55    /// #     pub struct Output;56    /// #     pub async fn do_some_work(_: Input) -> Result<Output, &'static str> {57    /// #         unimplemented!()58    /// #     }59    /// # }60    /// #61    /// # use ffi::{Input, Output};62    /// #63    /// use anyhow::{Error, Result};64    /// use futures::stream::{Stream, StreamExt, TryStreamExt};65    ///66    /// async fn demo<S>(stream: S) -> Result<Vec<Output>>67    /// where68    ///     S: Stream<Item = Input>,69    /// {70    ///     stream71    ///         .then(ffi::do_some_work) // returns Result<Output, &str>72    ///         .map_err(Error::msg)73    ///         .try_collect()74    ///         .await75    /// }76    /// ```77    #[cold]78    #[must_use]79    pub fn msg<M>(message: M) -> Self80    where81        M: Display + Debug + Send + Sync + 'static,82    {83        Error::from_adhoc(message, backtrace!())84    }8586    #[cfg(feature = "std")]87    #[cold]88    pub(crate) fn from_std<E>(error: E, backtrace: Option<Backtrace>) -> Self89    where90        E: StdError + Send + Sync + 'static,91    {92        let vtable = &ErrorVTable {93            object_drop: object_drop::<E>,94            object_ref: object_ref::<E>,95            #[cfg(anyhow_no_ptr_addr_of)]96            object_mut: object_mut::<E>,97            object_boxed: object_boxed::<E>,98            object_downcast: object_downcast::<E>,99            #[cfg(anyhow_no_ptr_addr_of)]100            object_downcast_mut: object_downcast_mut::<E>,101            object_drop_rest: object_drop_front::<E>,102            #[cfg(all(not(backtrace), feature = "backtrace"))]103            object_backtrace: no_backtrace,104        };105106        // Safety: passing vtable that operates on the right type E.107        unsafe { Error::construct(error, vtable, backtrace) }108    }109110    #[cold]111    pub(crate) fn from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> Self112    where113        M: Display + Debug + Send + Sync + 'static,114    {115        use crate::wrapper::MessageError;116        let error: MessageError<M> = MessageError(message);117        let vtable = &ErrorVTable {118            object_drop: object_drop::<MessageError<M>>,119            object_ref: object_ref::<MessageError<M>>,120            #[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]121            object_mut: object_mut::<MessageError<M>>,122            object_boxed: object_boxed::<MessageError<M>>,123            object_downcast: object_downcast::<M>,124            #[cfg(anyhow_no_ptr_addr_of)]125            object_downcast_mut: object_downcast_mut::<M>,126            object_drop_rest: object_drop_front::<M>,127            #[cfg(all(not(backtrace), feature = "backtrace"))]128            object_backtrace: no_backtrace,129        };130131        // Safety: MessageError is repr(transparent) so it is okay for the132        // vtable to allow casting the MessageError<M> to M.133        unsafe { Error::construct(error, vtable, backtrace) }134    }135136    #[cold]137    pub(crate) fn from_display<M>(message: M, backtrace: Option<Backtrace>) -> Self138    where139        M: Display + Send + Sync + 'static,140    {141        use crate::wrapper::DisplayError;142        let error: DisplayError<M> = DisplayError(message);143        let vtable = &ErrorVTable {144            object_drop: object_drop::<DisplayError<M>>,145            object_ref: object_ref::<DisplayError<M>>,146            #[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]147            object_mut: object_mut::<DisplayError<M>>,148            object_boxed: object_boxed::<DisplayError<M>>,149            object_downcast: object_downcast::<M>,150            #[cfg(anyhow_no_ptr_addr_of)]151            object_downcast_mut: object_downcast_mut::<M>,152            object_drop_rest: object_drop_front::<M>,153            #[cfg(all(not(backtrace), feature = "backtrace"))]154            object_backtrace: no_backtrace,155        };156157        // Safety: DisplayError is repr(transparent) so it is okay for the158        // vtable to allow casting the DisplayError<M> to M.159        unsafe { Error::construct(error, vtable, backtrace) }160    }161162    #[cfg(feature = "std")]163    #[cold]164    pub(crate) fn from_context<C, E>(context: C, error: E, backtrace: Option<Backtrace>) -> Self165    where166        C: Display + Send + Sync + 'static,167        E: StdError + Send + Sync + 'static,168    {169        let error: ContextError<C, E> = ContextError { context, error };170171        let vtable = &ErrorVTable {172            object_drop: object_drop::<ContextError<C, E>>,173            object_ref: object_ref::<ContextError<C, E>>,174            #[cfg(anyhow_no_ptr_addr_of)]175            object_mut: object_mut::<ContextError<C, E>>,176            object_boxed: object_boxed::<ContextError<C, E>>,177            object_downcast: context_downcast::<C, E>,178            #[cfg(anyhow_no_ptr_addr_of)]179            object_downcast_mut: context_downcast_mut::<C, E>,180            object_drop_rest: context_drop_rest::<C, E>,181            #[cfg(all(not(backtrace), feature = "backtrace"))]182            object_backtrace: no_backtrace,183        };184185        // Safety: passing vtable that operates on the right type.186        unsafe { Error::construct(error, vtable, backtrace) }187    }188189    #[cfg(feature = "std")]190    #[cold]191    pub(crate) fn from_boxed(192        error: Box<dyn StdError + Send + Sync>,193        backtrace: Option<Backtrace>,194    ) -> Self {195        use crate::wrapper::BoxedError;196        let error = BoxedError(error);197        let vtable = &ErrorVTable {198            object_drop: object_drop::<BoxedError>,199            object_ref: object_ref::<BoxedError>,200            #[cfg(anyhow_no_ptr_addr_of)]201            object_mut: object_mut::<BoxedError>,202            object_boxed: object_boxed::<BoxedError>,203            object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,204            #[cfg(anyhow_no_ptr_addr_of)]205            object_downcast_mut: object_downcast_mut::<Box<dyn StdError + Send + Sync>>,206            object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,207            #[cfg(all(not(backtrace), feature = "backtrace"))]208            object_backtrace: no_backtrace,209        };210211        // Safety: BoxedError is repr(transparent) so it is okay for the vtable212        // to allow casting to Box<dyn StdError + Send + Sync>.213        unsafe { Error::construct(error, vtable, backtrace) }214    }215216    // Takes backtrace as argument rather than capturing it here so that the217    // user sees one fewer layer of wrapping noise in the backtrace.218    //219    // Unsafe because the given vtable must have sensible behavior on the error220    // value of type E.221    #[cold]222    unsafe fn construct<E>(223        error: E,224        vtable: &'static ErrorVTable,225        backtrace: Option<Backtrace>,226    ) -> Self227    where228        E: StdError + Send + Sync + 'static,229    {230        let inner: Box<ErrorImpl<E>> = Box::new(ErrorImpl {231            vtable,232            backtrace,233            _object: error,234        });235        // Erase the concrete type of E from the compile-time type system. This236        // is equivalent to the safe unsize coercion from Box<ErrorImpl<E>> to237        // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the238        // result is a thin pointer. The necessary behavior for manipulating the239        // underlying ErrorImpl<E> is preserved in the vtable provided by the240        // caller rather than a builtin fat pointer vtable.241        let inner = Own::new(inner).cast::<ErrorImpl>();242        Error { inner }243    }244245    /// Wrap the error value with additional context.246    ///247    /// For attaching context to a `Result` as it is propagated, the248    /// [`Context`][crate::Context] extension trait may be more convenient than249    /// this function.250    ///251    /// The primary reason to use `error.context(...)` instead of252    /// `result.context(...)` via the `Context` trait would be if the context253    /// needs to depend on some data held by the underlying error:254    ///255    /// ```256    /// # use std::fmt::{self, Debug, Display};257    /// #258    /// # type T = ();259    /// #260    /// # impl std::error::Error for ParseError {}261    /// # impl Debug for ParseError {262    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {263    /// #         unimplemented!()264    /// #     }265    /// # }266    /// # impl Display for ParseError {267    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {268    /// #         unimplemented!()269    /// #     }270    /// # }271    /// #272    /// use anyhow::Result;273    /// use std::fs::File;274    /// use std::path::Path;275    ///276    /// struct ParseError {277    ///     line: usize,278    ///     column: usize,279    /// }280    ///281    /// fn parse_impl(file: File) -> Result<T, ParseError> {282    ///     # const IGNORE: &str = stringify! {283    ///     ...284    ///     # };285    ///     # unimplemented!()286    /// }287    ///288    /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {289    ///     let file = File::open(&path)?;290    ///     parse_impl(file).map_err(|error| {291    ///         let context = format!(292    ///             "only the first {} lines of {} are valid",293    ///             error.line, path.as_ref().display(),294    ///         );295    ///         anyhow::Error::new(error).context(context)296    ///     })297    /// }298    /// ```299    #[cold]300    #[must_use]301    pub fn context<C>(self, context: C) -> Self302    where303        C: Display + Send + Sync + 'static,304    {305        let error: ContextError<C, Error> = ContextError {306            context,307            error: self,308        };309310        let vtable = &ErrorVTable {311            object_drop: object_drop::<ContextError<C, Error>>,312            object_ref: object_ref::<ContextError<C, Error>>,313            #[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]314            object_mut: object_mut::<ContextError<C, Error>>,315            object_boxed: object_boxed::<ContextError<C, Error>>,316            object_downcast: context_chain_downcast::<C>,317            #[cfg(anyhow_no_ptr_addr_of)]318            object_downcast_mut: context_chain_downcast_mut::<C>,319            object_drop_rest: context_chain_drop_rest::<C>,320            #[cfg(all(not(backtrace), feature = "backtrace"))]321            object_backtrace: context_backtrace::<C>,322        };323324        // As the cause is anyhow::Error, we already have a backtrace for it.325        let backtrace = None;326327        // Safety: passing vtable that operates on the right type.328        unsafe { Error::construct(error, vtable, backtrace) }329    }330331    /// Get the backtrace for this Error.332    ///333    /// In order for the backtrace to be meaningful, one of the two environment334    /// variables `RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1` must be defined335    /// and `RUST_LIB_BACKTRACE` must not be `0`. Backtraces are somewhat336    /// expensive to capture in Rust, so we don't necessarily want to be337    /// capturing them all over the place all the time.338    ///339    /// - If you want panics and errors to both have backtraces, set340    ///   `RUST_BACKTRACE=1`;341    /// - If you want only errors to have backtraces, set342    ///   `RUST_LIB_BACKTRACE=1`;343    /// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and344    ///   `RUST_LIB_BACKTRACE=0`.345    ///346    /// # Stability347    ///348    /// Standard library backtraces are only available on the nightly channel.349    /// Tracking issue: [rust-lang/rust#53487][tracking].350    ///351    /// On stable compilers, this function is only available if the crate's352    /// "backtrace" feature is enabled, and will use the `backtrace` crate as353    /// the underlying backtrace implementation.354    ///355    /// ```toml356    /// [dependencies]357    /// anyhow = { version = "1.0", features = ["backtrace"] }358    /// ```359    ///360    /// [tracking]: https://github.com/rust-lang/rust/issues/53487361    #[cfg(any(backtrace, feature = "backtrace"))]362    #[cfg_attr(doc_cfg, doc(cfg(any(nightly, feature = "backtrace"))))]363    pub fn backtrace(&self) -> &impl_backtrace!() {364        unsafe { ErrorImpl::backtrace(self.inner.by_ref()) }365    }366367    /// An iterator of the chain of source errors contained by this Error.368    ///369    /// This iterator will visit every error in the cause chain of this error370    /// object, beginning with the error that this error object was created371    /// from.372    ///373    /// # Example374    ///375    /// ```376    /// use anyhow::Error;377    /// use std::io;378    ///379    /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {380    ///     for cause in error.chain() {381    ///         if let Some(io_error) = cause.downcast_ref::<io::Error>() {382    ///             return Some(io_error.kind());383    ///         }384    ///     }385    ///     None386    /// }387    /// ```388    #[cfg(feature = "std")]389    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]390    #[cold]391    pub fn chain(&self) -> Chain {392        unsafe { ErrorImpl::chain(self.inner.by_ref()) }393    }394395    /// The lowest level cause of this error &mdash; this error's cause's396    /// cause's cause etc.397    ///398    /// The root cause is the last error in the iterator produced by399    /// [`chain()`][Error::chain].400    #[cfg(feature = "std")]401    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]402    pub fn root_cause(&self) -> &(dyn StdError + 'static) {403        self.chain().last().unwrap()404    }405406    /// Returns true if `E` is the type held by this error object.407    ///408    /// For errors with context, this method returns true if `E` matches the409    /// type of the context `C` **or** the type of the error on which the410    /// context has been attached. For details about the interaction between411    /// context and downcasting, [see here].412    ///413    /// [see here]: trait.Context.html#effect-on-downcasting414    pub fn is<E>(&self) -> bool415    where416        E: Display + Debug + Send + Sync + 'static,417    {418        self.downcast_ref::<E>().is_some()419    }420421    /// Attempt to downcast the error object to a concrete type.422    pub fn downcast<E>(mut self) -> Result<E, Self>423    where424        E: Display + Debug + Send + Sync + 'static,425    {426        let target = TypeId::of::<E>();427        let inner = self.inner.by_mut();428        unsafe {429            // Use vtable to find NonNull<()> which points to a value of type E430            // somewhere inside the data structure.431            #[cfg(not(anyhow_no_ptr_addr_of))]432            let addr = match (vtable(inner.ptr).object_downcast)(inner.by_ref(), target) {433                Some(addr) => addr.by_mut().extend(),434                None => return Err(self),435            };436            #[cfg(anyhow_no_ptr_addr_of)]437            let addr = match (vtable(inner.ptr).object_downcast_mut)(inner, target) {438                Some(addr) => addr.extend(),439                None => return Err(self),440            };441442            // Prepare to read E out of the data structure. We'll drop the rest443            // of the data structure separately so that E is not dropped.444            let outer = ManuallyDrop::new(self);445446            // Read E from where the vtable found it.447            let error = addr.cast::<E>().read();448449            // Drop rest of the data structure outside of E.450            (vtable(outer.inner.ptr).object_drop_rest)(outer.inner, target);451452            Ok(error)453        }454    }455456    /// Downcast this error object by reference.457    ///458    /// # Example459    ///460    /// ```461    /// # use anyhow::anyhow;462    /// # use std::fmt::{self, Display};463    /// # use std::task::Poll;464    /// #465    /// # #[derive(Debug)]466    /// # enum DataStoreError {467    /// #     Censored(()),468    /// # }469    /// #470    /// # impl Display for DataStoreError {471    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {472    /// #         unimplemented!()473    /// #     }474    /// # }475    /// #476    /// # impl std::error::Error for DataStoreError {}477    /// #478    /// # const REDACTED_CONTENT: () = ();479    /// #480    /// # let error = anyhow!("...");481    /// # let root_cause = &error;482    /// #483    /// # let ret =484    /// // If the error was caused by redaction, then return a tombstone instead485    /// // of the content.486    /// match root_cause.downcast_ref::<DataStoreError>() {487    ///     Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),488    ///     None => Err(error),489    /// }490    /// # ;491    /// ```492    pub fn downcast_ref<E>(&self) -> Option<&E>493    where494        E: Display + Debug + Send + Sync + 'static,495    {496        let target = TypeId::of::<E>();497        unsafe {498            // Use vtable to find NonNull<()> which points to a value of type E499            // somewhere inside the data structure.500            let addr = (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?;501            Some(addr.cast::<E>().deref())502        }503    }504505    /// Downcast this error object by mutable reference.506    pub fn downcast_mut<E>(&mut self) -> Option<&mut E>507    where508        E: Display + Debug + Send + Sync + 'static,509    {510        let target = TypeId::of::<E>();511        unsafe {512            // Use vtable to find NonNull<()> which points to a value of type E513            // somewhere inside the data structure.514515            #[cfg(not(anyhow_no_ptr_addr_of))]516            let addr =517                (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?.by_mut();518519            #[cfg(anyhow_no_ptr_addr_of)]520            let addr = (vtable(self.inner.ptr).object_downcast_mut)(self.inner.by_mut(), target)?;521522            Some(addr.cast::<E>().deref_mut())523        }524    }525526    #[cfg(backtrace)]527    pub(crate) fn provide<'a>(&'a self, request: &mut Request<'a>) {528        unsafe { ErrorImpl::provide(self.inner.by_ref(), request) }529    }530531    // Called by thiserror when you have `#[source] anyhow::Error`. This provide532    // implementation includes the anyhow::Error's Backtrace if any, unlike533    // deref'ing to dyn Error where the provide implementation would include534    // only the original error's Backtrace from before it got wrapped into an535    // anyhow::Error.536    #[cfg(backtrace)]537    #[doc(hidden)]538    pub fn thiserror_provide<'a>(&'a self, request: &mut Request<'a>) {539        Self::provide(self, request);540    }541}542543#[cfg(feature = "std")]544#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]545impl<E> From<E> for Error546where547    E: StdError + Send + Sync + 'static,548{549    #[cold]550    fn from(error: E) -> Self {551        let backtrace = backtrace_if_absent!(&error);552        Error::from_std(error, backtrace)553    }554}555556#[cfg(feature = "std")]557#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]558impl Deref for Error {559    type Target = dyn StdError + Send + Sync + 'static;560561    fn deref(&self) -> &Self::Target {562        unsafe { ErrorImpl::error(self.inner.by_ref()) }563    }564}565566#[cfg(feature = "std")]567#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]568impl DerefMut for Error {569    fn deref_mut(&mut self) -> &mut Self::Target {570        unsafe { ErrorImpl::error_mut(self.inner.by_mut()) }571    }572}573574impl Display for Error {575    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {576        unsafe { ErrorImpl::display(self.inner.by_ref(), formatter) }577    }578}579580impl Debug for Error {581    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {582        unsafe { ErrorImpl::debug(self.inner.by_ref(), formatter) }583    }584}585586impl Drop for Error {587    fn drop(&mut self) {588        unsafe {589            // Invoke the vtable's drop behavior.590            (vtable(self.inner.ptr).object_drop)(self.inner);591        }592    }593}594595struct ErrorVTable {596    object_drop: unsafe fn(Own<ErrorImpl>),597    object_ref: unsafe fn(Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>,598    #[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]599    object_mut: unsafe fn(Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static),600    object_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,601    object_downcast: unsafe fn(Ref<ErrorImpl>, TypeId) -> Option<Ref<()>>,602    #[cfg(anyhow_no_ptr_addr_of)]603    object_downcast_mut: unsafe fn(Mut<ErrorImpl>, TypeId) -> Option<Mut<()>>,604    object_drop_rest: unsafe fn(Own<ErrorImpl>, TypeId),605    #[cfg(all(not(backtrace), feature = "backtrace"))]606    object_backtrace: unsafe fn(Ref<ErrorImpl>) -> Option<&Backtrace>,607}608609// Safety: requires layout of *e to match ErrorImpl<E>.610unsafe fn object_drop<E>(e: Own<ErrorImpl>) {611    // Cast back to ErrorImpl<E> so that the allocator receives the correct612    // Layout to deallocate the Box's memory.613    let unerased_own = e.cast::<ErrorImpl<E>>();614    drop(unsafe { unerased_own.boxed() });615}616617// Safety: requires layout of *e to match ErrorImpl<E>.618unsafe fn object_drop_front<E>(e: Own<ErrorImpl>, target: TypeId) {619    // Drop the fields of ErrorImpl other than E as well as the Box allocation,620    // without dropping E itself. This is used by downcast after doing a621    // ptr::read to take ownership of the E.622    let _ = target;623    let unerased_own = e.cast::<ErrorImpl<ManuallyDrop<E>>>();624    drop(unsafe { unerased_own.boxed() });625}626627// Safety: requires layout of *e to match ErrorImpl<E>.628unsafe fn object_ref<E>(e: Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>629where630    E: StdError + Send + Sync + 'static,631{632    // Attach E's native StdError vtable onto a pointer to self._object.633634    let unerased_ref = e.cast::<ErrorImpl<E>>();635636    #[cfg(not(anyhow_no_ptr_addr_of))]637    return Ref::from_raw(unsafe {638        NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object) as *mut E)639    });640641    #[cfg(anyhow_no_ptr_addr_of)]642    return Ref::new(unsafe { &unerased_ref.deref()._object });643}644645// Safety: requires layout of *e to match ErrorImpl<E>, and for `e` to be derived646// from a `&mut`647#[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]648unsafe fn object_mut<E>(e: Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static)649where650    E: StdError + Send + Sync + 'static,651{652    // Attach E's native StdError vtable onto a pointer to self._object.653    let unerased_mut = e.cast::<ErrorImpl<E>>();654    unsafe { &mut unerased_mut.deref_mut()._object }655}656657// Safety: requires layout of *e to match ErrorImpl<E>.658unsafe fn object_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>659where660    E: StdError + Send + Sync + 'static,661{662    // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.663    let unerased_own = e.cast::<ErrorImpl<E>>();664    unsafe { unerased_own.boxed() }665}666667// Safety: requires layout of *e to match ErrorImpl<E>.668unsafe fn object_downcast<E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>669where670    E: 'static,671{672    if TypeId::of::<E>() == target {673        // Caller is looking for an E pointer and e is ErrorImpl<E>, take a674        // pointer to its E field.675676        let unerased_ref = e.cast::<ErrorImpl<E>>();677678        #[cfg(not(anyhow_no_ptr_addr_of))]679        return Some(680            Ref::from_raw(unsafe {681                NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object) as *mut E)682            })683            .cast::<()>(),684        );685686        #[cfg(anyhow_no_ptr_addr_of)]687        return Some(Ref::new(unsafe { &unerased_ref.deref()._object }).cast::<()>());688    } else {689        None690    }691}692693// Safety: requires layout of *e to match ErrorImpl<E>.694#[cfg(anyhow_no_ptr_addr_of)]695unsafe fn object_downcast_mut<E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>696where697    E: 'static,698{699    if TypeId::of::<E>() == target {700        // Caller is looking for an E pointer and e is ErrorImpl<E>, take a701        // pointer to its E field.702        let unerased_mut = e.cast::<ErrorImpl<E>>();703        let unerased = unsafe { unerased_mut.deref_mut() };704        Some(Mut::new(&mut unerased._object).cast::<()>())705    } else {706        None707    }708}709710#[cfg(all(not(backtrace), feature = "backtrace"))]711fn no_backtrace(e: Ref<ErrorImpl>) -> Option<&Backtrace> {712    let _ = e;713    None714}715716// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.717#[cfg(feature = "std")]718unsafe fn context_downcast<C, E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>719where720    C: 'static,721    E: 'static,722{723    if TypeId::of::<C>() == target {724        let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();725        let unerased = unsafe { unerased_ref.deref() };726        Some(Ref::new(&unerased._object.context).cast::<()>())727    } else if TypeId::of::<E>() == target {728        let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();729        let unerased = unsafe { unerased_ref.deref() };730        Some(Ref::new(&unerased._object.error).cast::<()>())731    } else {732        None733    }734}735736// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.737#[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]738unsafe fn context_downcast_mut<C, E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>739where740    C: 'static,741    E: 'static,742{743    if TypeId::of::<C>() == target {744        let unerased_mut = e.cast::<ErrorImpl<ContextError<C, E>>>();745        let unerased = unsafe { unerased_mut.deref_mut() };746        Some(Mut::new(&mut unerased._object.context).cast::<()>())747    } else if TypeId::of::<E>() == target {748        let unerased_mut = e.cast::<ErrorImpl<ContextError<C, E>>>();749        let unerased = unsafe { unerased_mut.deref_mut() };750        Some(Mut::new(&mut unerased._object.error).cast::<()>())751    } else {752        None753    }754}755756// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.757#[cfg(feature = "std")]758unsafe fn context_drop_rest<C, E>(e: Own<ErrorImpl>, target: TypeId)759where760    C: 'static,761    E: 'static,762{763    // Called after downcasting by value to either the C or the E and doing a764    // ptr::read to take ownership of that value.765    if TypeId::of::<C>() == target {766        let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>();767        drop(unsafe { unerased_own.boxed() });768    } else {769        let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>();770        drop(unsafe { unerased_own.boxed() });771    }772}773774// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.775unsafe fn context_chain_downcast<C>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>776where777    C: 'static,778{779    let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();780    let unerased = unsafe { unerased_ref.deref() };781    if TypeId::of::<C>() == target {782        Some(Ref::new(&unerased._object.context).cast::<()>())783    } else {784        // Recurse down the context chain per the inner error's vtable.785        let source = &unerased._object.error;786        unsafe { (vtable(source.inner.ptr).object_downcast)(source.inner.by_ref(), target) }787    }788}789790// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.791#[cfg(anyhow_no_ptr_addr_of)]792unsafe fn context_chain_downcast_mut<C>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>793where794    C: 'static,795{796    let unerased_mut = e.cast::<ErrorImpl<ContextError<C, Error>>>();797    let unerased = unsafe { unerased_mut.deref_mut() };798    if TypeId::of::<C>() == target {799        Some(Mut::new(&mut unerased._object.context).cast::<()>())800    } else {801        // Recurse down the context chain per the inner error's vtable.802        let source = &mut unerased._object.error;803        unsafe { (vtable(source.inner.ptr).object_downcast_mut)(source.inner.by_mut(), target) }804    }805}806807// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.808unsafe fn context_chain_drop_rest<C>(e: Own<ErrorImpl>, target: TypeId)809where810    C: 'static,811{812    // Called after downcasting by value to either the C or one of the causes813    // and doing a ptr::read to take ownership of that value.814    if TypeId::of::<C>() == target {815        let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>();816        // Drop the entire rest of the data structure rooted in the next Error.817        drop(unsafe { unerased_own.boxed() });818    } else {819        let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>();820        let unerased = unsafe { unerased_own.boxed() };821        // Read the Own<ErrorImpl> from the next error.822        let inner = unerased._object.error.inner;823        drop(unerased);824        let vtable = unsafe { vtable(inner.ptr) };825        // Recursively drop the next error using the same target typeid.826        unsafe { (vtable.object_drop_rest)(inner, target) };827    }828}829830// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.831#[cfg(all(not(backtrace), feature = "backtrace"))]832#[allow(clippy::unnecessary_wraps)]833unsafe fn context_backtrace<C>(e: Ref<ErrorImpl>) -> Option<&Backtrace>834where835    C: 'static,836{837    let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();838    let unerased = unsafe { unerased_ref.deref() };839    let backtrace = unsafe { ErrorImpl::backtrace(unerased._object.error.inner.by_ref()) };840    Some(backtrace)841}842843// NOTE: If working with `ErrorImpl<()>`, references should be avoided in favor844// of raw pointers and `NonNull`.845// repr C to ensure that E remains in the final position.846#[repr(C)]847pub(crate) struct ErrorImpl<E = ()> {848    vtable: &'static ErrorVTable,849    backtrace: Option<Backtrace>,850    // NOTE: Don't use directly. Use only through vtable. Erased type may have851    // different alignment.852    _object: E,853}854855// Reads the vtable out of `p`. This is the same as `p.as_ref().vtable`, but856// avoids converting `p` into a reference.857unsafe fn vtable(p: NonNull<ErrorImpl>) -> &'static ErrorVTable {858    // NOTE: This assumes that `ErrorVTable` is the first field of ErrorImpl.859    unsafe { *(p.as_ptr() as *const &'static ErrorVTable) }860}861862// repr C to ensure that ContextError<C, E> has the same layout as863// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.864#[repr(C)]865pub(crate) struct ContextError<C, E> {866    pub context: C,867    pub error: E,868}869870impl<E> ErrorImpl<E> {871    fn erase(&self) -> Ref<ErrorImpl> {872        // Erase the concrete type of E but preserve the vtable in self.vtable873        // for manipulating the resulting thin pointer. This is analogous to an874        // unsize coercion.875        Ref::new(self).cast::<ErrorImpl>()876    }877}878879impl ErrorImpl {880    pub(crate) unsafe fn error(this: Ref<Self>) -> &(dyn StdError + Send + Sync + 'static) {881        // Use vtable to attach E's native StdError vtable for the right882        // original type E.883        unsafe { (vtable(this.ptr).object_ref)(this).deref() }884    }885886    #[cfg(feature = "std")]887    pub(crate) unsafe fn error_mut(this: Mut<Self>) -> &mut (dyn StdError + Send + Sync + 'static) {888        // Use vtable to attach E's native StdError vtable for the right889        // original type E.890891        #[cfg(not(anyhow_no_ptr_addr_of))]892        return unsafe {893            (vtable(this.ptr).object_ref)(this.by_ref())894                .by_mut()895                .deref_mut()896        };897898        #[cfg(anyhow_no_ptr_addr_of)]899        return unsafe { (vtable(this.ptr).object_mut)(this) };900    }901902    #[cfg(any(backtrace, feature = "backtrace"))]903    pub(crate) unsafe fn backtrace(this: Ref<Self>) -> &Backtrace {904        // This unwrap can only panic if the underlying error's backtrace method905        // is nondeterministic, which would only happen in maliciously906        // constructed code.907        unsafe { this.deref() }908            .backtrace909            .as_ref()910            .or_else(|| {911                #[cfg(backtrace)]912                return error::request_ref::<Backtrace>(unsafe { Self::error(this) });913                #[cfg(not(backtrace))]914                return unsafe { (vtable(this.ptr).object_backtrace)(this) };915            })916            .expect("backtrace capture failed")917    }918919    #[cfg(backtrace)]920    unsafe fn provide<'a>(this: Ref<'a, Self>, request: &mut Request<'a>) {921        if let Some(backtrace) = unsafe { &this.deref().backtrace } {922            request.provide_ref(backtrace);923        }924        unsafe { Self::error(this) }.provide(request);925    }926927    #[cold]928    pub(crate) unsafe fn chain(this: Ref<Self>) -> Chain {929        Chain::new(unsafe { Self::error(this) })930    }931}932933impl<E> StdError for ErrorImpl<E>934where935    E: StdError,936{937    fn source(&self) -> Option<&(dyn StdError + 'static)> {938        unsafe { ErrorImpl::error(self.erase()).source() }939    }940941    #[cfg(backtrace)]942    fn provide<'a>(&'a self, request: &mut Request<'a>) {943        unsafe { ErrorImpl::provide(self.erase(), request) }944    }945}946947impl<E> Debug for ErrorImpl<E>948where949    E: Debug,950{951    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {952        unsafe { ErrorImpl::debug(self.erase(), formatter) }953    }954}955956impl<E> Display for ErrorImpl<E>957where958    E: Display,959{960    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {961        unsafe { Display::fmt(ErrorImpl::error(self.erase()), formatter) }962    }963}964965impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {966    #[cold]967    fn from(error: Error) -> Self {968        let outer = ManuallyDrop::new(error);969        unsafe {970            // Use vtable to attach ErrorImpl<E>'s native StdError vtable for971            // the right original type E.972            (vtable(outer.inner.ptr).object_boxed)(outer.inner)973        }974    }975}976977impl From<Error> for Box<dyn StdError + Send + 'static> {978    fn from(error: Error) -> Self {979        Box::<dyn StdError + Send + Sync>::from(error)980    }981}982983impl From<Error> for Box<dyn StdError + 'static> {984    fn from(error: Error) -> Self {985        Box::<dyn StdError + Send + Sync>::from(error)986    }987}988989#[cfg(feature = "std")]990impl AsRef<dyn StdError + Send + Sync> for Error {991    fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {992        &**self993    }994}995996#[cfg(feature = "std")]997impl AsRef<dyn StdError> for Error {998    fn as_ref(&self) -> &(dyn StdError + 'static) {999        &**self1000    }1001}