Skip to content
Myr

Merge pull request #143 from dtolnay/backtrace

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

Add stable backtrace feature

authored by David Tolnay · committed by GitHub · parents 7e85bae, 0ba6408 · 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

6 files+452 added−14 removed

modified:.github/workflows/ci.yml+17 added
modified:src/backtrace.rs+369 added-4 removed
1#[cfg(backtrace)]2pub(crate) use std::backtrace::Backtrace;2pub(crate) use std::backtrace::{Backtrace, BacktraceStatus};34#[cfg(not(backtrace))]4#[cfg(all(not(backtrace), feature = "backtrace"))]5pub(crate) use self::capture::{Backtrace, BacktraceStatus};67#[cfg(not(any(backtrace, feature = "backtrace")))]8pub(crate) enum Backtrace {}910#[cfg(backtrace)]11macro_rules! impl_backtrace {12 () => {13 std::backtrace::Backtrace14 };15}1617#[cfg(all(not(backtrace), feature = "backtrace"))]18macro_rules! impl_backtrace {19 () => {20 impl core::fmt::Debug + core::fmt::Display21 };22}2324#[cfg(any(backtrace, feature = "backtrace"))]25macro_rules! backtrace {26 () => {27 Some(crate::backtrace::Backtrace::capture())28 };29}3014#[cfg(not(backtrace))]31#[cfg(not(any(backtrace, feature = "backtrace")))]32macro_rules! backtrace {33 () => {34 None35 };
8 unmodified lines
44 }45 };46}4731#[cfg(all(feature = "std", not(backtrace)))]48#[cfg(all(feature = "std", not(backtrace), feature = "backtrace"))]49macro_rules! backtrace_if_absent {50 ($err:expr) => {51 backtrace!()52 };53}5455#[cfg(all(feature = "std", not(backtrace), not(feature = "backtrace")))]56macro_rules! backtrace_if_absent {57 ($err:expr) => {58 None59 };60}6162#[cfg(all(not(backtrace), feature = "backtrace"))]63mod 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;7273 pub(crate) struct Backtrace {74 inner: Inner,75 }7677 pub(crate) enum BacktraceStatus {78 Unsupported,79 Disabled,80 Captured,81 }8283 enum Inner {84 Unsupported,85 Disabled,86 Captured(LazilyResolvedCapture),87 }8889 struct Capture {90 actual_start: usize,91 resolved: bool,92 frames: Vec<BacktraceFrame>,93 }9495 struct BacktraceFrame {96 frame: Frame,97 symbols: Vec<BacktraceSymbol>,98 }99100 struct BacktraceSymbol {101 name: Option<Vec<u8>>,102 filename: Option<BytesOrWide>,103 lineno: Option<u32>,104 colno: Option<u32>,105 }106107 enum BytesOrWide {108 Bytes(Vec<u8>),109 Wide(Vec<u16>),110 }111112 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 };119120 let frames = &capture.frames[capture.actual_start..];121122 write!(fmt, "Backtrace ")?;123124 let mut dbg = fmt.debug_list();125126 for frame in frames {127 if frame.frame.ip().is_null() {128 continue;129 }130131 dbg.entries(&frame.symbols);132 }133134 dbg.finish()135 }136 }137138 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 }145146 impl Debug for BacktraceSymbol {147 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {148 write!(fmt, "{{ ")?;149150 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 }155156 if let Some(fname) = self.filename.as_ref() {157 write!(fmt, ", file: \"{:?}\"", fname)?;158 }159160 if let Some(line) = self.lineno {161 write!(fmt, ", line: {:?}", line)?;162 }163164 write!(fmt, " }}")165 }166 }167168 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 }181182 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 }200201 #[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 }210211 // 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 });226227 // 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 };239240 Backtrace { inner }241 }242243 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 }251252 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 };259260 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 };266267 // 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 };275276 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 }301302 struct LazilyResolvedCapture {303 sync: Once,304 capture: UnsafeCell<Capture>,305 }306307 impl LazilyResolvedCapture {308 fn new(capture: Capture) -> Self {309 LazilyResolvedCapture {310 sync: Once::new(),311 capture: UnsafeCell::new(capture),312 }313 }314315 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 });323324 // Safety: This shared reference can't overlap with the exclusive325 // reference above.326 unsafe { &*self.capture.get() }327 }328 }329330 // 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 {}333334 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;341342 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 }359360 // 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}397398fn _assert_send_sync() {399 fn _assert<T: Send + Sync>() {}400 _assert::<Backtrace>();401}
modified:src/error.rs+56 added-8 removed
84 unmodified lines
85 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 };9293 // Safety: passing vtable that operates on the right type E.94 unsafe { Error::construct(error, vtable, backtrace) }
13 unmodified lines
108 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 };115116 // Safety: MessageError is repr(transparent) so it is okay for the117 // vtable to allow casting the MessageError<M> to M.
14 unmodified lines
132 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 };139140 // Safety: DisplayError is repr(transparent) so it is okay for the141 // vtable to allow casting the DisplayError<M> to M.
15 unmodified lines
157 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 };164165 // Safety: passing vtable that operates on the right type.166 unsafe { Error::construct(error, vtable, backtrace) }
13 unmodified lines
180 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 };187188 // Safety: BoxedError is repr(transparent) so it is okay for the vtable189 // to allow casting to Box<dyn StdError + Send + Sync>.
99 unmodified lines
289 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 };296297 // As the cause is anyhow::Error, we already have a backtrace for it.298 let backtrace = None;
3 unmodified lines
302 }303304 /// 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 be
5 unmodified lines
315 /// `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 }339340 /// An iterator of the chain of source errors contained by this Error.
201 unmodified lines
542 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}549550// Safety: requires layout of *e to match ErrorImpl<E>.551unsafe fn object_drop<E>(e: Own<ErrorImpl>) {
71 unmodified lines
623 None624 }625}626627#[cfg(all(not(backtrace), feature = "backtrace"))]628fn no_backtrace(e: Ref<ErrorImpl>) -> Option<&Backtrace> {629 let _ = e;630 None631}632633// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.634#[cfg(feature = "std")]635unsafe fn context_downcast<C, E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>636where
108 unmodified lines
745 (vtable.object_drop_rest)(inner, target);746 }747}748749// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.750#[cfg(all(not(backtrace), feature = "backtrace"))]751#[allow(clippy::unnecessary_wraps)]752unsafe fn context_backtrace<C>(e: Ref<ErrorImpl>) -> Option<&Backtrace>753where754 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}760761// 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 lines
807 // original type E.808 (vtable(this.ptr).object_mut)(this)809 }810768 #[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 }827828 pub(crate) unsafe fn chain(this: Ref<Self>) -> Chain {
72 unmodified lines
modified:src/fmt.rs+2 added-2 removed
37 unmodified lines
38 write!(indented, "{}", error)?;39 }40 }4142 #[cfg(backtrace)]42 #[cfg(any(backtrace, feature = "backtrace"))]43 {44 use std::backtrace::BacktraceStatus;44 use crate::backtrace::BacktraceStatus;4546 let backtrace = Self::backtrace(this);47 if let BacktraceStatus::Captured = backtrace.status() {48 let mut backtrace = backtrace.to_string();
107 unmodified lines
modified:build.rs+5 added
2 unmodified lines
3use std::path::Path;4use std::process::{Command, ExitStatus, Stdio};5use std::str;67#[cfg(all(feature = "backtrace", not(feature = "std")))]8compile_error! {9 "`backtrace` feature without `std` feature is not supported"10}1112// 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.15const PROBE: &str = r#"
73 unmodified lines
modified:Cargo.toml+3 added