Add stable backtrace feature
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Tolnay · committed by David Tolnay · parent 7e85bae · Browse files · 6 files·+452 added−14 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+452 added−14 removed
- other:+452 added−14 removed
Provenance
- Commit
0ba6408- Tree
0f6cc31- Author
David Tolnay <dtolnay@gmail.com>- Committer
David Tolnay <dtolnay@gmail.com>- Parent
7e85bae
6 files changed+452 added−14 removed
modified:.github/workflows/ci.yml+17 added
18 unmodified lines1920212223242526272829303132333435368 unmodified lines4546474849505152535455565758596013 unmodified lines18 unmodified lines with: toolchain: ${{matrix.rust}} - run: cargo test - run: cargo check --no-default-features - run: cargo check --features backtrace
backtrace: name: Rust 1.42.0 runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: dtolnay/rust-toolchain@1.42.0 - run: cargo check --features backtrace
nostd: name: Rust 1.36.0 runs-on: ubuntu-latest steps:8 unmodified lines - uses: actions/checkout@v2 - uses: dtolnay/rust-toolchain@1.34.0 - run: cargo check
windows: name: Windows runs-on: windows-latest steps: - uses: actions/checkout@v2 - uses: dtolnay/rust-toolchain@stable - run: cargo check --features backtrace
clippy: name: Clippy runs-on: ubuntu-latest steps:13 unmodified linesmodified:src/backtrace.rs+369 added-4 removed
1 #[cfg(backtrace)]2-pub(crate) use std::backtrace::Backtrace;2+pub(crate) use std::backtrace::{Backtrace, BacktraceStatus};3 4-#[cfg(not(backtrace))]4+#[cfg(all(not(backtrace), feature = "backtrace"))]5+pub(crate) use self::capture::{Backtrace, BacktraceStatus};6+7+#[cfg(not(any(backtrace, feature = "backtrace")))]8 pub(crate) enum Backtrace {}9 10 #[cfg(backtrace)]11+macro_rules! impl_backtrace {12+ () => {13+ std::backtrace::Backtrace14+ };15+}16+17+#[cfg(all(not(backtrace), feature = "backtrace"))]18+macro_rules! impl_backtrace {19+ () => {20+ impl core::fmt::Debug + core::fmt::Display21+ };22+}23+24+#[cfg(any(backtrace, feature = "backtrace"))]25 macro_rules! backtrace {26 () => {27 Some(crate::backtrace::Backtrace::capture())28 };29 }30 14-#[cfg(not(backtrace))]31+#[cfg(not(any(backtrace, feature = "backtrace")))]32 macro_rules! backtrace {33 () => {34 None35 };8 unmodified lines44 }45 };46 }47 31-#[cfg(all(feature = "std", not(backtrace)))]48+#[cfg(all(feature = "std", not(backtrace), feature = "backtrace"))]49 macro_rules! backtrace_if_absent {50 ($err:expr) => {51+ backtrace!()52+ };53+}54+55+#[cfg(all(feature = "std", not(backtrace), not(feature = "backtrace")))]56+macro_rules! backtrace_if_absent {57+ ($err:expr) => {58 None59 };60 }61+62+#[cfg(all(not(backtrace), feature = "backtrace"))]63+mod capture {64+ use backtrace::{BacktraceFmt, BytesOrWideString, Frame, PrintFmt, SymbolName};65+ use core::cell::UnsafeCell;66+ use core::fmt::{self, Debug, Display};67+ use core::sync::atomic::{AtomicUsize, Ordering};68+ use std::borrow::Cow;69+ use std::env;70+ use std::path::{self, Path, PathBuf};71+ use std::sync::Once;72+73+ pub(crate) struct Backtrace {74+ inner: Inner,75+ }76+77+ pub(crate) enum BacktraceStatus {78+ Unsupported,79+ Disabled,80+ Captured,81+ }82+83+ enum Inner {84+ Unsupported,85+ Disabled,86+ Captured(LazilyResolvedCapture),87+ }88+89+ struct Capture {90+ actual_start: usize,91+ resolved: bool,92+ frames: Vec<BacktraceFrame>,93+ }94+95+ struct BacktraceFrame {96+ frame: Frame,97+ symbols: Vec<BacktraceSymbol>,98+ }99+100+ struct BacktraceSymbol {101+ name: Option<Vec<u8>>,102+ filename: Option<BytesOrWide>,103+ lineno: Option<u32>,104+ colno: Option<u32>,105+ }106+107+ enum BytesOrWide {108+ Bytes(Vec<u8>),109+ Wide(Vec<u16>),110+ }111+112+ impl Debug for Backtrace {113+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {114+ let capture = match &self.inner {115+ Inner::Unsupported => return fmt.write_str("<unsupported>"),116+ Inner::Disabled => return fmt.write_str("<disabled>"),117+ Inner::Captured(c) => c.force(),118+ };119+120+ let frames = &capture.frames[capture.actual_start..];121+122+ write!(fmt, "Backtrace ")?;123+124+ let mut dbg = fmt.debug_list();125+126+ for frame in frames {127+ if frame.frame.ip().is_null() {128+ continue;129+ }130+131+ dbg.entries(&frame.symbols);132+ }133+134+ dbg.finish()135+ }136+ }137+138+ impl Debug for BacktraceFrame {139+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {140+ let mut dbg = fmt.debug_list();141+ dbg.entries(&self.symbols);142+ dbg.finish()143+ }144+ }145+146+ impl Debug for BacktraceSymbol {147+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {148+ write!(fmt, "{{ ")?;149+150+ if let Some(fn_name) = self.name.as_ref().map(|b| SymbolName::new(b)) {151+ write!(fmt, "fn: \"{:#}\"", fn_name)?;152+ } else {153+ write!(fmt, "fn: <unknown>")?;154+ }155+156+ if let Some(fname) = self.filename.as_ref() {157+ write!(fmt, ", file: \"{:?}\"", fname)?;158+ }159+160+ if let Some(line) = self.lineno {161+ write!(fmt, ", line: {:?}", line)?;162+ }163+164+ write!(fmt, " }}")165+ }166+ }167+168+ impl Debug for BytesOrWide {169+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {170+ output_filename(171+ fmt,172+ match self {173+ BytesOrWide::Bytes(w) => BytesOrWideString::Bytes(w),174+ BytesOrWide::Wide(w) => BytesOrWideString::Wide(w),175+ },176+ PrintFmt::Short,177+ env::current_dir().as_ref().ok(),178+ )179+ }180+ }181+182+ impl Backtrace {183+ fn enabled() -> bool {184+ static ENABLED: AtomicUsize = AtomicUsize::new(0);185+ match ENABLED.load(Ordering::SeqCst) {186+ 0 => {}187+ 1 => return false,188+ _ => return true,189+ }190+ let enabled = match env::var_os("RUST_LIB_BACKTRACE") {191+ Some(s) => s != "0",192+ None => match env::var_os("RUST_BACKTRACE") {193+ Some(s) => s != "0",194+ None => false,195+ },196+ };197+ ENABLED.store(enabled as usize + 1, Ordering::SeqCst);198+ enabled199+ }200+201+ #[inline(never)] // want to make sure there's a frame here to remove202+ pub(crate) fn capture() -> Backtrace {203+ if Backtrace::enabled() {204+ Backtrace::create(Backtrace::capture as usize)205+ } else {206+ let inner = Inner::Disabled;207+ Backtrace { inner }208+ }209+ }210+211+ // Capture a backtrace which starts just before the function addressed212+ // by `ip`213+ fn create(ip: usize) -> Backtrace {214+ let mut frames = Vec::new();215+ let mut actual_start = None;216+ backtrace::trace(|frame| {217+ frames.push(BacktraceFrame {218+ frame: frame.clone(),219+ symbols: Vec::new(),220+ });221+ if frame.symbol_address() as usize == ip && actual_start.is_none() {222+ actual_start = Some(frames.len() + 1);223+ }224+ true225+ });226+227+ // If no frames came out assume that this is an unsupported platform228+ // since `backtrace` doesn't provide a way of learning this right229+ // now, and this should be a good enough approximation.230+ let inner = if frames.is_empty() {231+ Inner::Unsupported232+ } else {233+ Inner::Captured(LazilyResolvedCapture::new(Capture {234+ actual_start: actual_start.unwrap_or(0),235+ frames,236+ resolved: false,237+ }))238+ };239+240+ Backtrace { inner }241+ }242+243+ pub(crate) fn status(&self) -> BacktraceStatus {244+ match self.inner {245+ Inner::Unsupported => BacktraceStatus::Unsupported,246+ Inner::Disabled => BacktraceStatus::Disabled,247+ Inner::Captured(_) => BacktraceStatus::Captured,248+ }249+ }250+ }251+252+ impl Display for Backtrace {253+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {254+ let capture = match &self.inner {255+ Inner::Unsupported => return fmt.write_str("unsupported backtrace"),256+ Inner::Disabled => return fmt.write_str("disabled backtrace"),257+ Inner::Captured(c) => c.force(),258+ };259+260+ let full = fmt.alternate();261+ let (frames, style) = if full {262+ (&capture.frames[..], PrintFmt::Full)263+ } else {264+ (&capture.frames[capture.actual_start..], PrintFmt::Short)265+ };266+267+ // When printing paths we try to strip the cwd if it exists,268+ // otherwise we just print the path as-is. Note that we also only do269+ // this for the short format, because if it's full we presumably270+ // want to print everything.271+ let cwd = env::current_dir();272+ let mut print_path = move |fmt: &mut fmt::Formatter, path: BytesOrWideString| {273+ output_filename(fmt, path, style, cwd.as_ref().ok())274+ };275+276+ let mut f = BacktraceFmt::new(fmt, style, &mut print_path);277+ f.add_context()?;278+ for frame in frames {279+ let mut f = f.frame();280+ if frame.symbols.is_empty() {281+ f.print_raw(frame.frame.ip(), None, None, None)?;282+ } else {283+ for symbol in frame.symbols.iter() {284+ f.print_raw_with_column(285+ frame.frame.ip(),286+ symbol.name.as_ref().map(|b| SymbolName::new(b)),287+ symbol.filename.as_ref().map(|b| match b {288+ BytesOrWide::Bytes(w) => BytesOrWideString::Bytes(w),289+ BytesOrWide::Wide(w) => BytesOrWideString::Wide(w),290+ }),291+ symbol.lineno,292+ symbol.colno,293+ )?;294+ }295+ }296+ }297+ f.finish()?;298+ Ok(())299+ }300+ }301+302+ struct LazilyResolvedCapture {303+ sync: Once,304+ capture: UnsafeCell<Capture>,305+ }306+307+ impl LazilyResolvedCapture {308+ fn new(capture: Capture) -> Self {309+ LazilyResolvedCapture {310+ sync: Once::new(),311+ capture: UnsafeCell::new(capture),312+ }313+ }314+315+ fn force(&self) -> &Capture {316+ self.sync.call_once(|| {317+ // Safety: This exclusive reference can't overlap with any318+ // others. `Once` guarantees callers will block until this319+ // closure returns. `Once` also guarantees only a single caller320+ // will enter this closure.321+ unsafe { &mut *self.capture.get() }.resolve();322+ });323+324+ // Safety: This shared reference can't overlap with the exclusive325+ // reference above.326+ unsafe { &*self.capture.get() }327+ }328+ }329+330+ // Safety: Access to the inner value is synchronized using a thread-safe331+ // `Once`. So long as `Capture` is `Sync`, `LazilyResolvedCapture` is too332+ unsafe impl Sync for LazilyResolvedCapture where Capture: Sync {}333+334+ impl Capture {335+ fn resolve(&mut self) {336+ // If we're already resolved, nothing to do!337+ if self.resolved {338+ return;339+ }340+ self.resolved = true;341+342+ for frame in self.frames.iter_mut() {343+ let symbols = &mut frame.symbols;344+ let frame = &frame.frame;345+ backtrace::resolve_frame(frame, |symbol| {346+ symbols.push(BacktraceSymbol {347+ name: symbol.name().map(|m| m.as_bytes().to_vec()),348+ filename: symbol.filename_raw().map(|b| match b {349+ BytesOrWideString::Bytes(b) => BytesOrWide::Bytes(b.to_owned()),350+ BytesOrWideString::Wide(b) => BytesOrWide::Wide(b.to_owned()),351+ }),352+ lineno: symbol.lineno(),353+ colno: symbol.colno(),354+ });355+ });356+ }357+ }358+ }359+360+ // Prints the filename of the backtrace frame.361+ fn output_filename(362+ fmt: &mut fmt::Formatter,363+ bows: BytesOrWideString,364+ print_fmt: PrintFmt,365+ cwd: Option<&PathBuf>,366+ ) -> fmt::Result {367+ let file: Cow<Path> = match bows {368+ #[cfg(unix)]369+ BytesOrWideString::Bytes(bytes) => {370+ use std::os::unix::ffi::OsStrExt;371+ Path::new(std::ffi::OsStr::from_bytes(bytes)).into()372+ }373+ #[cfg(not(unix))]374+ BytesOrWideString::Bytes(bytes) => {375+ Path::new(std::str::from_utf8(bytes).unwrap_or("<unknown>")).into()376+ }377+ #[cfg(windows)]378+ BytesOrWideString::Wide(wide) => {379+ use std::os::windows::ffi::OsStringExt;380+ Cow::Owned(std::ffi::OsString::from_wide(wide).into())381+ }382+ #[cfg(not(windows))]383+ BytesOrWideString::Wide(_wide) => Path::new("<unknown>").into(),384+ };385+ if print_fmt == PrintFmt::Short && file.is_absolute() {386+ if let Some(cwd) = cwd {387+ if let Ok(stripped) = file.strip_prefix(&cwd) {388+ if let Some(s) = stripped.to_str() {389+ return write!(fmt, ".{}{}", path::MAIN_SEPARATOR, s);390+ }391+ }392+ }393+ }394+ Display::fmt(&file.display(), fmt)395+ }396+}397+398+fn _assert_send_sync() {399+ fn _assert<T: Send + Sync>() {}400+ _assert::<Backtrace>();401+}modified:src/error.rs+56 added-8 removed
84 unmodified lines85 object_boxed: object_boxed::<E>,86 object_downcast: object_downcast::<E>,87 object_downcast_mut: object_downcast_mut::<E>,88 object_drop_rest: object_drop_front::<E>,89+ #[cfg(all(not(backtrace), feature = "backtrace"))]90+ object_backtrace: no_backtrace,91 };92 93 // Safety: passing vtable that operates on the right type E.94 unsafe { Error::construct(error, vtable, backtrace) }13 unmodified lines108 object_boxed: object_boxed::<MessageError<M>>,109 object_downcast: object_downcast::<M>,110 object_downcast_mut: object_downcast_mut::<M>,111 object_drop_rest: object_drop_front::<M>,112+ #[cfg(all(not(backtrace), feature = "backtrace"))]113+ object_backtrace: no_backtrace,114 };115 116 // Safety: MessageError is repr(transparent) so it is okay for the117 // vtable to allow casting the MessageError<M> to M.14 unmodified lines132 object_boxed: object_boxed::<DisplayError<M>>,133 object_downcast: object_downcast::<M>,134 object_downcast_mut: object_downcast_mut::<M>,135 object_drop_rest: object_drop_front::<M>,136+ #[cfg(all(not(backtrace), feature = "backtrace"))]137+ object_backtrace: no_backtrace,138 };139 140 // Safety: DisplayError is repr(transparent) so it is okay for the141 // vtable to allow casting the DisplayError<M> to M.15 unmodified lines157 object_boxed: object_boxed::<ContextError<C, E>>,158 object_downcast: context_downcast::<C, E>,159 object_downcast_mut: context_downcast_mut::<C, E>,160 object_drop_rest: context_drop_rest::<C, E>,161+ #[cfg(all(not(backtrace), feature = "backtrace"))]162+ object_backtrace: no_backtrace,163 };164 165 // Safety: passing vtable that operates on the right type.166 unsafe { Error::construct(error, vtable, backtrace) }13 unmodified lines180 object_boxed: object_boxed::<BoxedError>,181 object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,182 object_downcast_mut: object_downcast_mut::<Box<dyn StdError + Send + Sync>>,183 object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,184+ #[cfg(all(not(backtrace), feature = "backtrace"))]185+ object_backtrace: no_backtrace,186 };187 188 // Safety: BoxedError is repr(transparent) so it is okay for the vtable189 // to allow casting to Box<dyn StdError + Send + Sync>.99 unmodified lines289 object_boxed: object_boxed::<ContextError<C, Error>>,290 object_downcast: context_chain_downcast::<C>,291 object_downcast_mut: context_chain_downcast_mut::<C>,292 object_drop_rest: context_chain_drop_rest::<C>,293+ #[cfg(all(not(backtrace), feature = "backtrace"))]294+ object_backtrace: context_backtrace::<C>,295 };296 297 // As the cause is anyhow::Error, we already have a backtrace for it.298 let backtrace = None;3 unmodified lines302 }303 304 /// Get the backtrace for this Error.305 ///294- /// Backtraces are only available on the nightly channel. Tracking issue:295- /// [rust-lang/rust#53487][tracking].296- ///306 /// In order for the backtrace to be meaningful, one of the two environment307 /// variables `RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1` must be defined308 /// and `RUST_LIB_BACKTRACE` must not be `0`. Backtraces are somewhat309 /// expensive to capture in Rust, so we don't necessarily want to be5 unmodified lines315 /// `RUST_LIB_BACKTRACE=1`;316 /// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and317 /// `RUST_LIB_BACKTRACE=0`.318 ///319+ /// # Stability320+ ///321+ /// Standard library backtraces are only available on the nightly channel.322+ /// Tracking issue: [rust-lang/rust#53487][tracking].323+ ///324+ /// On stable compilers, this function is only available if the crate's325+ /// "backtrace" feature is enabled, and will use the `backtrace` crate as326+ /// the underlying backtrace implementation.327+ ///328+ /// ```toml329+ /// [dependencies]330+ /// anyhow = { version = "1.0", features = ["backtrace"] }331+ /// ```332+ ///333 /// [tracking]: https://github.com/rust-lang/rust/issues/53487311- #[cfg(backtrace)]312- #[cfg_attr(doc_cfg, doc(cfg(nightly)))]313- pub fn backtrace(&self) -> &Backtrace {334+ #[cfg(any(backtrace, feature = "backtrace"))]335+ #[cfg_attr(doc_cfg, doc(cfg(any(nightly, feature = "backtrace"))))]336+ pub fn backtrace(&self) -> &impl_backtrace!() {337 unsafe { ErrorImpl::backtrace(self.inner.by_ref()) }338 }339 340 /// An iterator of the chain of source errors contained by this Error.201 unmodified lines542 object_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,543 object_downcast: unsafe fn(Ref<ErrorImpl>, TypeId) -> Option<Ref<()>>,544 object_downcast_mut: unsafe fn(Mut<ErrorImpl>, TypeId) -> Option<Mut<()>>,545 object_drop_rest: unsafe fn(Own<ErrorImpl>, TypeId),546+ #[cfg(all(not(backtrace), feature = "backtrace"))]547+ object_backtrace: unsafe fn(Ref<ErrorImpl>) -> Option<&Backtrace>,548 }549 550 // Safety: requires layout of *e to match ErrorImpl<E>.551 unsafe fn object_drop<E>(e: Own<ErrorImpl>) {71 unmodified lines623 None624 }625 }626 627+#[cfg(all(not(backtrace), feature = "backtrace"))]628+fn no_backtrace(e: Ref<ErrorImpl>) -> Option<&Backtrace> {629+ let _ = e;630+ None631+}632+633 // Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.634 #[cfg(feature = "std")]635 unsafe fn context_downcast<C, E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>636 where108 unmodified lines745 (vtable.object_drop_rest)(inner, target);746 }747 }748 749+// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.750+#[cfg(all(not(backtrace), feature = "backtrace"))]751+#[allow(clippy::unnecessary_wraps)]752+unsafe fn context_backtrace<C>(e: Ref<ErrorImpl>) -> Option<&Backtrace>753+where754+ C: 'static,755+{756+ let unerased = e.cast::<ErrorImpl<ContextError<C, Error>>>().deref();757+ let backtrace = ErrorImpl::backtrace(unerased._object.error.inner.by_ref());758+ Some(backtrace)759+}760+761 // NOTE: If working with `ErrorImpl<()>`, references should be avoided in favor762 // of raw pointers and `NonNull`.763 // repr C to ensure that E remains in the final position.764 #[repr(C)]42 unmodified lines807 // original type E.808 (vtable(this.ptr).object_mut)(this)809 }810 768- #[cfg(backtrace)]811+ #[cfg(any(backtrace, feature = "backtrace"))]812 pub(crate) unsafe fn backtrace(this: Ref<Self>) -> &Backtrace {813 // This unwrap can only panic if the underlying error's backtrace method814 // is nondeterministic, which would only happen in maliciously815 // constructed code.816 this.deref()817 .backtrace818 .as_ref()776- .or_else(|| Self::error(this).backtrace())819+ .or_else(|| {820+ #[cfg(backtrace)]821+ return Self::error(this).backtrace();822+ #[cfg(all(not(backtrace), feature = "backtrace"))]823+ return (vtable(this.ptr).object_backtrace)(this);824+ })825 .expect("backtrace capture failed")826 }827 828 pub(crate) unsafe fn chain(this: Ref<Self>) -> Chain {72 unmodified linesmodified:src/fmt.rs+2 added-2 removed
37 unmodified lines38 write!(indented, "{}", error)?;39 }40 }41 42- #[cfg(backtrace)]42+ #[cfg(any(backtrace, feature = "backtrace"))]43 {44- use std::backtrace::BacktraceStatus;44+ use crate::backtrace::BacktraceStatus;45 46 let backtrace = Self::backtrace(this);47 if let BacktraceStatus::Captured = backtrace.status() {48 let mut backtrace = backtrace.to_string();107 unmodified linesmodified:build.rs+5 added
2 unmodified lines3 use std::path::Path;4 use std::process::{Command, ExitStatus, Stdio};5 use std::str;6 7+#[cfg(all(feature = "backtrace", not(feature = "std")))]8+compile_error! {9+ "`backtrace` feature without `std` feature is not supported"10+}11+12 // This code exercises the surface area that we expect of the std Backtrace13 // type. If the current toolchain is able to compile it, we go ahead and use14 // backtrace in anyhow.15 const PROBE: &str = r#"73 unmodified linesmodified:Cargo.toml+3 added
12 unmodified lines13141516171819202122236 unmodified lines12 unmodified lines[features]default = ["std"]std = []
[dependencies]backtrace = { version = "0.3", optional = true }
[dev-dependencies]futures = { version = "0.3", default-features = false }rustversion = "1.0"syn = { version = "1.0", features = ["full"] }6 unmodified lines