Skip to content
Myr

Enable backtrace support for >= 1.65 stable compilers

Before adoption: this commit came in with the history the project adopted, so no landing records it.

The `std::backtrace` APIs relevant for this crate were stabilized in 1.65. This commit makes anyhow use those API if possible. `std::backtrace` is preferred over the `backtrace` crate, so for 1.65+ compilers, enabling the `backtrace` crate feature does nothing essentially. Previously, when a nightly compiler was used, use of `std::backtrace` as well as the Provider API was enabled. This commit separates those two APIs such that `std::backtrace` is used for nightly OR 1.65+ stable compilers; and the Provider API is used for nightly compilers only.

authored by Lukas Kalbertodt · committed by Lukas Kalbertodt · parent 0a45d76 · Browse files · 7 files+47 added−43 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+47 added−43 removed

  • other:+47 added−43 removed

7 files+47 added−43 removed

modified:src/backtrace.rs+2 added-2 removed
33 unmodified lines
34 None35 };36}3738#[cfg(backtrace)]38#[cfg(provide_api)]39macro_rules! backtrace_if_absent {40 ($err:expr) => {41 match ($err as &dyn std::error::Error).request_ref::<std::backtrace::Backtrace>() {42 Some(_) => None,
1 unmodified line
44 }45 };46}4748#[cfg(all(feature = "std", not(backtrace), feature = "backtrace"))]48#[cfg(all(feature = "std", not(provide_api), any(backtrace, feature = "backtrace")))]49macro_rules! backtrace_if_absent {50 ($err:expr) => {51 backtrace!()52 };
349 unmodified lines
modified:src/context.rs+3 added-3 removed
1 unmodified line
2use crate::{Context, Error, StdError};3use core::convert::Infallible;4use core::fmt::{self, Debug, Display, Write};56#[cfg(backtrace)]6#[cfg(provide_api)]7use std::any::{Demand, Provider};89mod ext {10 use super::*;
131 unmodified lines
142 fn source(&self) -> Option<&(dyn StdError + 'static)> {143 Some(&self.error)144 }145146 #[cfg(backtrace)]146 #[cfg(provide_api)]147 fn provide<'a>(&'a self, demand: &mut Demand<'a>) {148 StdError::provide(&self.error, demand);149 }150}
5 unmodified lines
156 fn source(&self) -> Option<&(dyn StdError + 'static)> {157 Some(unsafe { crate::ErrorImpl::error(self.error.inner.by_ref()) })158 }159160 #[cfg(backtrace)]160 #[cfg(provide_api)]161 fn provide<'a>(&'a self, demand: &mut Demand<'a>) {162 Provider::provide(&self.error, demand);163 }164}
29 unmodified lines
modified:src/error.rs+17 added-19 removed
3 unmodified lines
4use crate::ptr::Mut;5use crate::ptr::{Own, Ref};6use crate::{Error, StdError};7use alloc::boxed::Box;8#[cfg(backtrace)]8#[cfg(provide_api)]9use core::any::Demand;10use core::any::TypeId;11use core::fmt::{self, Debug, Display};12use core::mem::ManuallyDrop;
85 unmodified lines
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"))]102 #[cfg(all(not(provide_api), any(backtrace, feature = "backtrace")))]103 object_backtrace: no_backtrace,104 };105106 // Safety: passing vtable that operates on the right type E.
16 unmodified lines
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"))]127 #[cfg(all(not(provide_api), any(backtrace, feature = "backtrace")))]128 object_backtrace: no_backtrace,129 };130131 // Safety: MessageError is repr(transparent) so it is okay for the
17 unmodified lines
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"))]153 #[cfg(all(not(provide_api), any(backtrace, feature = "backtrace")))]154 object_backtrace: no_backtrace,155 };156157 // Safety: DisplayError is repr(transparent) so it is okay for the
19 unmodified lines
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"))]181 #[cfg(all(not(provide_api), any(backtrace, feature = "backtrace")))]182 object_backtrace: no_backtrace,183 };184185 // Safety: passing vtable that operates on the right type.
17 unmodified lines
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"))]207 #[cfg(all(not(provide_api), any(backtrace, feature = "backtrace")))]208 object_backtrace: no_backtrace,209 };210211 // Safety: BoxedError is repr(transparent) so it is okay for the vtable
104 unmodified lines
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"))]320 #[cfg(all(not(provide_api), any(backtrace, feature = "backtrace")))]321 object_backtrace: context_backtrace::<C>,322 };323324 // As the cause is anyhow::Error, we already have a backtrace for it.
19 unmodified lines
344 /// `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's348 /// Standard library backtraces are only available when using Rust ≥ 1.65.349 /// On older compilers, this function is only available if the crate's350 /// "backtrace" feature is enabled, and will use the `backtrace` crate as351 /// the underlying backtrace implementation.352 ///353 /// ```toml
167 unmodified lines
521 }522 }523}524527#[cfg(backtrace)]525#[cfg(provide_api)]526impl std::any::Provider for Error {527 // Called by thiserror when you have `#[source] anyhow::Error`. This provide528 // implementation includes the anyhow::Error's Backtrace if any, unlike529 // deref'ing to dyn Error where the provide implementation would include
65 unmodified lines
595 object_downcast: unsafe fn(Ref<ErrorImpl>, TypeId) -> Option<Ref<()>>,596 #[cfg(anyhow_no_ptr_addr_of)]597 object_downcast_mut: unsafe fn(Mut<ErrorImpl>, TypeId) -> Option<Mut<()>>,598 object_drop_rest: unsafe fn(Own<ErrorImpl>, TypeId),601 #[cfg(all(not(backtrace), feature = "backtrace"))]599 #[cfg(all(not(provide_api), any(backtrace, feature = "backtrace")))]600 object_backtrace: unsafe fn(Ref<ErrorImpl>) -> Option<&Backtrace>,601}602603// Safety: requires layout of *e to match ErrorImpl<E>.
93 unmodified lines
697 None698 }699}700703#[cfg(all(not(backtrace), feature = "backtrace"))]701#[cfg(all(not(provide_api), any(backtrace, feature = "backtrace")))]702fn no_backtrace(e: Ref<ErrorImpl>) -> Option<&Backtrace> {703 let _ = e;704 None705}
113 unmodified lines
819 }820}821822// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.825#[cfg(all(not(backtrace), feature = "backtrace"))]823#[cfg(all(not(provide_api), any(backtrace, feature = "backtrace")))]824#[allow(clippy::unnecessary_wraps)]825unsafe fn context_backtrace<C>(e: Ref<ErrorImpl>) -> Option<&Backtrace>826where827 C: 'static,
68 unmodified lines
896 this.deref()897 .backtrace898 .as_ref()899 .or_else(|| {902 #[cfg(backtrace)]900 #[cfg(provide_api)]901 return Self::error(this).request_ref::<Backtrace>();904 #[cfg(not(backtrace))]902 #[cfg(not(provide_api))]903 return (vtable(this.ptr).object_backtrace)(this);904 })905 .expect("backtrace capture failed")906 }907910 #[cfg(backtrace)]908 #[cfg(provide_api)]909 unsafe fn provide<'a>(this: Ref<'a, Self>, demand: &mut Demand<'a>) {910 if let Some(backtrace) = &this.deref().backtrace {911 demand.provide_ref(backtrace);912 }
13 unmodified lines
926 fn source(&self) -> Option<&(dyn StdError + 'static)> {927 unsafe { ErrorImpl::error(self.erase()).source() }928 }929932 #[cfg(backtrace)]930 #[cfg(provide_api)]931 fn provide<'a>(&'a self, demand: &mut Demand<'a>) {932 unsafe { ErrorImpl::provide(self.erase(), demand) }933 }934}
56 unmodified lines
modified:src/lib.rs+5 added-9 removed
126 unmodified lines
127//! }128//! # ;129//! ```130//!131//! - If using the nightly channel, or stable with `features = ["backtrace"]`, a132//! backtrace is captured and printed with the error if the underlying error133//! type does not already provide its own. In order to see backtraces, they134//! must be enabled through the environment variables described in135//! [`std::backtrace`]:131//! - If using Rust ≥ 1.65 or `features = ["backtrace"]`, a backtrace is captured132//! and printed with the error if the underlying error type does not already133//! provide its own. In order to see backtraces, they must be enabled through the134//! environment variables described in [`std::backtrace`]:135//!136//! - If you want panics and errors to both have backtraces, set137//! `RUST_BACKTRACE=1`;138//! - If you want only errors to have backtraces, set `RUST_LIB_BACKTRACE=1`;139//! - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and140//! `RUST_LIB_BACKTRACE=0`.141//!143//! The tracking issue for this feature is [rust-lang/rust#53487].144//!142//! [`std::backtrace`]: https://doc.rust-lang.org/std/backtrace/index.html#environment-variables146//! [rust-lang/rust#53487]: https://github.com/rust-lang/rust/issues/53487143//!144//! - Anyhow works with any error type that has an impl of `std::error::Error`,145//! including ones defined in your crate. We do not bundle a `derive(Error)`146//! macro but you can write the impls yourself or use a standalone macro like
59 unmodified lines
206//! will require an explicit `.map_err(Error::msg)` when working with a207//! non-Anyhow error type inside a function that returns Anyhow's error type.208209#![doc(html_root_url = "https://docs.rs/anyhow/1.0.68")]214#![cfg_attr(backtrace, feature(error_generic_member_access, provide_any))]210#![cfg_attr(provide_api, feature(error_generic_member_access, provide_any))]211#![cfg_attr(doc_cfg, feature(doc_cfg))]212#![cfg_attr(not(feature = "std"), no_std)]213#![deny(dead_code, unused_imports, unused_mut)]214#![allow(
462 unmodified lines
modified:src/wrapper.rs+2 added-2 removed
1use crate::StdError;2use core::fmt::{self, Debug, Display};34#[cfg(backtrace)]4#[cfg(provide_api)]5use std::any::Demand;67#[repr(transparent)]8pub struct MessageError<M>(pub M);
64 unmodified lines
73 fn source(&self) -> Option<&(dyn StdError + 'static)> {74 self.0.source()75 }7677 #[cfg(backtrace)]77 #[cfg(provide_api)]78 fn provide<'a>(&'a self, demand: &mut Demand<'a>) {79 self.0.provide(demand);80 }81}
modified:build.rs+14 added-1 removed
55 unmodified lines
56 const _: fn(&dyn Error) -> Option<&Backtrace> = |err| err.request_ref::<Backtrace>();57"#;5859fn main() {60 // If the compile probe succeeds, i.e. if a nightly compiler is used and the61 // provide API exists, then `std::backtrace` is also usable. So `cfg62 // (provide_api)` implies `cfg(backtrace)`. We do set `cfg(backtrace)` in63 // this script explicitly anyway to make the `cfg()` attributes in the main64 // code less complex.65 let mut nightly_backtrace_support = false;66 if cfg!(feature = "std") {67 match compile_probe() {62 Some(status) if status.success() => println!("cargo:rustc-cfg=backtrace"),68 Some(status) if status.success() => {69 println!("cargo:rustc-cfg=provide_api");70 nightly_backtrace_support = true;71 }72 _ => {}73 }74 }75
8 unmodified lines
8485 if rustc < 52 {86 println!("cargo:rustc-cfg=anyhow_no_fmt_arguments_as_str");87 }8889 if nightly_backtrace_support || (cfg!(feature = "std") && rustc >= 65) {90 println!("cargo:rustc-cfg=backtrace");91 }92}9394fn compile_probe() -> Option<ExitStatus> {95 let rustc = env::var_os("RUSTC")?;
49 unmodified lines
modified:README.md+4 added-7 removed