Skip to content
Myr

Merge pull request #439 from dtolnay/backtrace

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

Remove `feature = "backtrace"` conditional code

authored by David Tolnay · committed by GitHub · parents 2a2a3ce, a42fc2c · Browse files · 4 files+17 added−407 removed
This commit

State

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

Diff stats

4 files+17 added−407 removed

  • other:+17 added−407 removed

4 files+17 added−407 removed

modified:src/backtrace.rs+4 added-362 removed
1#[cfg(std_backtrace)]2pub(crate) use std::backtrace::{Backtrace, BacktraceStatus};34#[cfg(all(not(std_backtrace), feature = "backtrace"))]5pub(crate) use self::capture::{Backtrace, BacktraceStatus};67#[cfg(not(any(std_backtrace, feature = "backtrace")))]4#[cfg(not(std_backtrace))]5pub(crate) enum Backtrace {}67#[cfg(std_backtrace)]11macro_rules! impl_backtrace {12 () => {13 std::backtrace::Backtrace14 };15}1617#[cfg(all(not(std_backtrace), feature = "backtrace"))]18macro_rules! impl_backtrace {19 () => {20 impl core::fmt::Debug + core::fmt::Display21 };22}2324#[cfg(any(std_backtrace, feature = "backtrace"))]8macro_rules! backtrace {9 () => {10 Some(crate::backtrace::Backtrace::capture())11 };12}1331#[cfg(not(any(std_backtrace, feature = "backtrace")))]14#[cfg(not(std_backtrace))]15macro_rules! backtrace {16 () => {17 None18 };
11 unmodified lines
3031#[cfg(all(32 any(feature = "std", not(anyhow_no_core_error)),33 not(error_generic_member_access),51 any(std_backtrace, feature = "backtrace")34 std_backtrace35))]36macro_rules! backtrace_if_absent {37 ($err:expr) => {38 backtrace!()39 };40}4159#[cfg(all(60 any(feature = "std", not(anyhow_no_core_error)),61 not(std_backtrace),62 not(feature = "backtrace"),63))]42#[cfg(all(any(feature = "std", not(anyhow_no_core_error)), not(std_backtrace)))]43macro_rules! backtrace_if_absent {44 ($err:expr) => {45 None46 };47}4870#[cfg(all(not(std_backtrace), feature = "backtrace"))]71mod capture {72 use alloc::borrow::{Cow, ToOwned as _};73 use alloc::vec::Vec;74 use backtrace::{BacktraceFmt, BytesOrWideString, Frame, PrintFmt, SymbolName};75 use core::cell::UnsafeCell;76 use core::fmt::{self, Debug, Display};77 use core::sync::atomic::{AtomicUsize, Ordering};78 use std::env;79 use std::path::{self, Path, PathBuf};80 use std::sync::Once;8182 pub(crate) struct Backtrace {83 inner: Inner,84 }8586 pub(crate) enum BacktraceStatus {87 Unsupported,88 Disabled,89 Captured,90 }9192 enum Inner {93 Unsupported,94 Disabled,95 Captured(LazilyResolvedCapture),96 }9798 struct Capture {99 actual_start: usize,100 resolved: bool,101 frames: Vec<BacktraceFrame>,102 }103104 struct BacktraceFrame {105 frame: Frame,106 symbols: Vec<BacktraceSymbol>,107 }108109 struct BacktraceSymbol {110 name: Option<Vec<u8>>,111 filename: Option<BytesOrWide>,112 lineno: Option<u32>,113 colno: Option<u32>,114 }115116 enum BytesOrWide {117 Bytes(Vec<u8>),118 Wide(Vec<u16>),119 }120121 impl Debug for Backtrace {122 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {123 let capture = match &self.inner {124 Inner::Unsupported => return fmt.write_str("<unsupported>"),125 Inner::Disabled => return fmt.write_str("<disabled>"),126 Inner::Captured(c) => c.force(),127 };128129 let frames = &capture.frames[capture.actual_start..];130131 write!(fmt, "Backtrace ")?;132133 let mut dbg = fmt.debug_list();134135 for frame in frames {136 if frame.frame.ip().is_null() {137 continue;138 }139140 dbg.entries(&frame.symbols);141 }142143 dbg.finish()144 }145 }146147 impl Debug for BacktraceFrame {148 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {149 let mut dbg = fmt.debug_list();150 dbg.entries(&self.symbols);151 dbg.finish()152 }153 }154155 impl Debug for BacktraceSymbol {156 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {157 write!(fmt, "{{ ")?;158159 if let Some(fn_name) = self.name.as_ref().map(|b| SymbolName::new(b)) {160 write!(fmt, "fn: \"{:#}\"", fn_name)?;161 } else {162 write!(fmt, "fn: <unknown>")?;163 }164165 if let Some(fname) = self.filename.as_ref() {166 write!(fmt, ", file: \"{:?}\"", fname)?;167 }168169 if let Some(line) = self.lineno {170 write!(fmt, ", line: {:?}", line)?;171 }172173 write!(fmt, " }}")174 }175 }176177 impl Debug for BytesOrWide {178 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {179 output_filename(180 fmt,181 match self {182 BytesOrWide::Bytes(w) => BytesOrWideString::Bytes(w),183 BytesOrWide::Wide(w) => BytesOrWideString::Wide(w),184 },185 PrintFmt::Short,186 env::current_dir().as_ref().ok(),187 )188 }189 }190191 impl Backtrace {192 fn enabled() -> bool {193 static ENABLED: AtomicUsize = AtomicUsize::new(0);194 match ENABLED.load(Ordering::Relaxed) {195 0 => {}196 1 => return false,197 _ => return true,198 }199 let enabled = match env::var_os("RUST_LIB_BACKTRACE") {200 Some(s) => s != "0",201 None => match env::var_os("RUST_BACKTRACE") {202 Some(s) => s != "0",203 None => false,204 },205 };206 ENABLED.store(enabled as usize + 1, Ordering::Relaxed);207 enabled208 }209210 #[inline(never)] // want to make sure there's a frame here to remove211 pub(crate) fn capture() -> Backtrace {212 if Backtrace::enabled() {213 Backtrace::create(Backtrace::capture as usize)214 } else {215 let inner = Inner::Disabled;216 Backtrace { inner }217 }218 }219220 // Capture a backtrace which starts just before the function addressed221 // by `ip`222 fn create(ip: usize) -> Backtrace {223 let mut frames = Vec::new();224 let mut actual_start = None;225 backtrace::trace(|frame| {226 frames.push(BacktraceFrame {227 frame: frame.clone(),228 symbols: Vec::new(),229 });230 if frame.symbol_address() as usize == ip && actual_start.is_none() {231 actual_start = Some(frames.len() + 1);232 }233 true234 });235236 // If no frames came out, assume that this is an unsupported platform237 // since `backtrace` doesn't provide a way of learning this right238 // now, and this should be a good enough approximation.239 let inner = if frames.is_empty() {240 Inner::Unsupported241 } else {242 Inner::Captured(LazilyResolvedCapture::new(Capture {243 actual_start: actual_start.unwrap_or(0),244 frames,245 resolved: false,246 }))247 };248249 Backtrace { inner }250 }251252 pub(crate) fn status(&self) -> BacktraceStatus {253 match self.inner {254 Inner::Unsupported => BacktraceStatus::Unsupported,255 Inner::Disabled => BacktraceStatus::Disabled,256 Inner::Captured(_) => BacktraceStatus::Captured,257 }258 }259 }260261 impl Display for Backtrace {262 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {263 let capture = match &self.inner {264 Inner::Unsupported => return fmt.write_str("unsupported backtrace"),265 Inner::Disabled => return fmt.write_str("disabled backtrace"),266 Inner::Captured(c) => c.force(),267 };268269 let full = fmt.alternate();270 let (frames, style) = if full {271 (&capture.frames[..], PrintFmt::Full)272 } else {273 (&capture.frames[capture.actual_start..], PrintFmt::Short)274 };275276 // When printing paths we try to strip the cwd if it exists,277 // otherwise we just print the path as-is. Note that we also only do278 // this for the short format, because if it's full we presumably279 // want to print everything.280 let cwd = env::current_dir();281 let mut print_path = move |fmt: &mut fmt::Formatter, path: BytesOrWideString| {282 output_filename(fmt, path, style, cwd.as_ref().ok())283 };284285 let mut f = BacktraceFmt::new(fmt, style, &mut print_path);286 f.add_context()?;287 for frame in frames {288 let mut f = f.frame();289 if frame.symbols.is_empty() {290 f.print_raw(frame.frame.ip(), None, None, None)?;291 } else {292 for symbol in frame.symbols.iter() {293 f.print_raw_with_column(294 frame.frame.ip(),295 symbol.name.as_ref().map(|b| SymbolName::new(b)),296 symbol.filename.as_ref().map(|b| match b {297 BytesOrWide::Bytes(w) => BytesOrWideString::Bytes(w),298 BytesOrWide::Wide(w) => BytesOrWideString::Wide(w),299 }),300 symbol.lineno,301 symbol.colno,302 )?;303 }304 }305 }306 f.finish()?;307 Ok(())308 }309 }310311 struct LazilyResolvedCapture {312 sync: Once,313 capture: UnsafeCell<Capture>,314 }315316 impl LazilyResolvedCapture {317 fn new(capture: Capture) -> Self {318 LazilyResolvedCapture {319 sync: Once::new(),320 capture: UnsafeCell::new(capture),321 }322 }323324 fn force(&self) -> &Capture {325 self.sync.call_once(|| {326 // Safety: This exclusive reference can't overlap with any327 // others. `Once` guarantees callers will block until this328 // closure returns. `Once` also guarantees only a single caller329 // will enter this closure.330 unsafe { &mut *self.capture.get() }.resolve();331 });332333 // Safety: This shared reference can't overlap with the exclusive334 // reference above.335 unsafe { &*self.capture.get() }336 }337 }338339 // Safety: Access to the inner value is synchronized using a thread-safe340 // `Once`. So long as `Capture` is `Sync`, `LazilyResolvedCapture` is too341 unsafe impl Sync for LazilyResolvedCapture where Capture: Sync {}342343 impl Capture {344 fn resolve(&mut self) {345 // If we're already resolved, nothing to do!346 if self.resolved {347 return;348 }349 self.resolved = true;350351 for frame in self.frames.iter_mut() {352 let symbols = &mut frame.symbols;353 let frame = &frame.frame;354 backtrace::resolve_frame(frame, |symbol| {355 symbols.push(BacktraceSymbol {356 name: symbol.name().map(|m| m.as_bytes().to_vec()),357 filename: symbol.filename_raw().map(|b| match b {358 BytesOrWideString::Bytes(b) => BytesOrWide::Bytes(b.to_owned()),359 BytesOrWideString::Wide(b) => BytesOrWide::Wide(b.to_owned()),360 }),361 lineno: symbol.lineno(),362 colno: symbol.colno(),363 });364 });365 }366 }367 }368369 // Prints the filename of the backtrace frame.370 fn output_filename(371 fmt: &mut fmt::Formatter,372 bows: BytesOrWideString,373 print_fmt: PrintFmt,374 cwd: Option<&PathBuf>,375 ) -> fmt::Result {376 let file: Cow<Path> = match bows {377 #[cfg(unix)]378 BytesOrWideString::Bytes(bytes) => {379 use std::os::unix::ffi::OsStrExt;380 Path::new(std::ffi::OsStr::from_bytes(bytes)).into()381 }382 #[cfg(not(unix))]383 BytesOrWideString::Bytes(bytes) => {384 Path::new(std::str::from_utf8(bytes).unwrap_or("<unknown>")).into()385 }386 #[cfg(windows)]387 BytesOrWideString::Wide(wide) => {388 use std::os::windows::ffi::OsStringExt;389 Cow::Owned(std::ffi::OsString::from_wide(wide).into())390 }391 #[cfg(not(windows))]392 BytesOrWideString::Wide(_wide) => Path::new("<unknown>").into(),393 };394 if print_fmt == PrintFmt::Short && file.is_absolute() {395 if let Some(cwd) = cwd {396 if let Ok(stripped) = file.strip_prefix(&cwd) {397 if let Some(s) = stripped.to_str() {398 return write!(fmt, ".{}{}", path::MAIN_SEPARATOR, s);399 }400 }401 }402 }403 Display::fmt(&file.display(), fmt)404 }405}40649fn _assert_send_sync() {50 fn assert<T: Send + Sync>() {}51 assert::<Backtrace>();52}
modified:src/error.rs+12 added-39 removed
153 unmodified lines
154 object_boxed: object_boxed::<E>,155 object_reallocate_boxed: object_reallocate_boxed::<E>,156 object_downcast: object_downcast::<E>,157 object_drop_rest: object_drop_front::<E>,158 #[cfg(all(159 not(error_generic_member_access),160 any(std_backtrace, feature = "backtrace")161 ))]158 #[cfg(all(not(error_generic_member_access), std_backtrace))]159 object_backtrace: no_backtrace,160 };161162 // Safety: passing vtable that operates on the right type E.
15 unmodified lines
178 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]179 object_reallocate_boxed: object_reallocate_boxed::<MessageError<M>>,180 object_downcast: object_downcast::<M>,181 object_drop_rest: object_drop_front::<M>,185 #[cfg(all(186 not(error_generic_member_access),187 any(std_backtrace, feature = "backtrace")188 ))]182 #[cfg(all(not(error_generic_member_access), std_backtrace))]183 object_backtrace: no_backtrace,184 };185186 // Safety: MessageError is repr(transparent) so it is okay for the
16 unmodified lines
203 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]204 object_reallocate_boxed: object_reallocate_boxed::<DisplayError<M>>,205 object_downcast: object_downcast::<M>,206 object_drop_rest: object_drop_front::<M>,213 #[cfg(all(214 not(error_generic_member_access),215 any(std_backtrace, feature = "backtrace")216 ))]207 #[cfg(all(not(error_generic_member_access), std_backtrace))]208 object_backtrace: no_backtrace,209 };210211 // Safety: DisplayError is repr(transparent) so it is okay for the
22 unmodified lines
234 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]235 object_reallocate_boxed: object_reallocate_boxed::<ContextError<C, E>>,236 object_downcast: context_downcast::<C, E>,237 object_drop_rest: context_drop_rest::<C, E>,247 #[cfg(all(248 not(error_generic_member_access),249 any(std_backtrace, feature = "backtrace")250 ))]238 #[cfg(all(not(error_generic_member_access), std_backtrace))]239 object_backtrace: no_backtrace,240 };241242 // Safety: passing vtable that operates on the right type.
16 unmodified lines
259 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]260 object_reallocate_boxed: object_reallocate_boxed::<BoxedError>,261 object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,262 object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,275 #[cfg(all(276 not(error_generic_member_access),277 any(std_backtrace, feature = "backtrace")278 ))]263 #[cfg(all(not(error_generic_member_access), std_backtrace))]264 object_backtrace: no_backtrace,265 };266267 // Safety: BoxedError is repr(transparent) so it is okay for the vtable
103 unmodified lines
371 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]372 object_reallocate_boxed: object_reallocate_boxed::<ContextError<C, Error>>,373 object_downcast: context_chain_downcast::<C>,374 object_drop_rest: context_chain_drop_rest::<C>,390 #[cfg(all(391 not(error_generic_member_access),392 any(std_backtrace, feature = "backtrace")393 ))]375 #[cfg(all(not(error_generic_member_access), std_backtrace))]376 object_backtrace: context_backtrace::<C>,377 };378379 // As the cause is anyhow::Error, we already have a backtrace for it.
29 unmodified lines
409 /// ```toml410 /// [dependencies]411 /// anyhow = { version = "1.0", features = ["backtrace"] }412 /// ```431 #[cfg(any(std_backtrace, feature = "backtrace"))]432 pub fn backtrace(&self) -> &impl_backtrace!() {413 #[cfg(std_backtrace)]414 pub fn backtrace(&self) -> &std::backtrace::Backtrace {415 unsafe { ErrorImpl::backtrace(self.inner.by_ref()) }416 }417418 /// An iterator of the chain of source errors contained by this Error.
308 unmodified lines
727 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]728 object_reallocate_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,729 object_downcast: unsafe fn(Ref<ErrorImpl>, TypeId) -> Option<Ref<()>>,730 object_drop_rest: unsafe fn(Own<ErrorImpl>, TypeId),749 #[cfg(all(750 not(error_generic_member_access),751 any(std_backtrace, feature = "backtrace")752 ))]731 #[cfg(all(not(error_generic_member_access), std_backtrace))]732 object_backtrace: unsafe fn(Ref<ErrorImpl>) -> Option<&Backtrace>,733}734735// Safety: requires layout of *e to match ErrorImpl<E>.
67 unmodified lines
803 None804 }805}806828#[cfg(all(829 not(error_generic_member_access),830 any(std_backtrace, feature = "backtrace")831))]807#[cfg(all(not(error_generic_member_access), std_backtrace))]808fn no_backtrace(e: Ref<ErrorImpl>) -> Option<&Backtrace> {809 let _ = e;810 None811}
75 unmodified lines
887 }888}889890// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.915#[cfg(all(916 not(error_generic_member_access),917 any(std_backtrace, feature = "backtrace")918))]891#[cfg(all(not(error_generic_member_access), std_backtrace))]892#[allow(clippy::unnecessary_wraps)]893unsafe fn context_backtrace<C>(e: Ref<ErrorImpl>) -> Option<&Backtrace>894where895 C: 'static,
57 unmodified lines
953 .deref_mut()954 }955 }956984 #[cfg(any(std_backtrace, feature = "backtrace"))]957 #[cfg(std_backtrace)]958 pub(crate) unsafe fn backtrace(this: Ref<Self>) -> &Backtrace {959 // This unwrap can only panic if the underlying error's backtrace method960 // is nondeterministic, which would only happen in maliciously961 // constructed code.
98 unmodified lines
modified:src/fmt.rs+1 added-1 removed
38 unmodified lines
39 write!(indented, "{}", error)?;40 }41 }4243 #[cfg(any(std_backtrace, feature = "backtrace"))]43 #[cfg(std_backtrace)]44 {45 use crate::backtrace::BacktraceStatus;46 use alloc::string::ToString;47
111 unmodified lines
modified:build.rs-5 removed
7 unmodified lines
8use std::path::Path;9use std::process::{self, Command, Stdio};10use std::str;1112#[cfg(all(feature = "backtrace", not(feature = "std")))]13compile_error! {14 "`backtrace` feature without `std` feature is not supported"15}1612fn main() {13 let mut error_generic_member_access = false;14 if cfg!(feature = "std") {15 println!("cargo:rerun-if-changed=src/nightly.rs");
187 unmodified lines