Skip to content

Commit

Permalink
Auto merge of rust-lang#73441 - alexcrichton:backtrace-gimli, r=Mark-…
Browse files Browse the repository at this point in the history
…Simulacrum

std: Switch from libbacktrace to gimli

This commit is a proof-of-concept for switching the standard library's
backtrace symbolication mechanism on most platforms from libbacktrace to
gimli. The standard library's support for `RUST_BACKTRACE=1` requires
in-process parsing of object files and DWARF debug information to
interpret it and print the filename/line number of stack frames as part
of a backtrace.

Historically this support in the standard library has come from a
library called "libbacktrace". The libbacktrace library seems to have
been extracted from gcc at some point and is written in C. We've had a
lot of issues with libbacktrace over time, unfortunately, though. The
library does not appear to be actively maintained since we've had
patches sit for months-to-years without comments. We have discovered a
good number of soundness issues with the library itself, both when
parsing valid DWARF as well as invalid DWARF. This is enough of an issue
that the libs team has previously decided that we cannot feed untrusted
inputs to libbacktrace. This also doesn't take into account the
portability of libbacktrace which has been difficult to manage and
maintain over time. While possible there are lots of exceptions and it's
the main C dependency of the standard library right now.

For years it's been the desire to switch over to a Rust-based solution
for symbolicating backtraces. It's been assumed that we'll be using the
Gimli family of crates for this purpose, which are targeted at safely
and efficiently parsing DWARF debug information. I've been working
recently to shore up the Gimli support in the `backtrace` crate. As of a
few weeks ago the `backtrace` crate, by default, uses Gimli when loaded
from crates.io. This transition has gone well enough that I figured it
was time to start talking seriously about this change to the standard
library.

This commit is a preview of what's probably the best way to integrate
the `backtrace` crate into the standard library with the Gimli feature
turned on. While today it's used as a crates.io dependency, this commit
switches the `backtrace` crate to a submodule of this repository which
will need to be updated manually. This is not done lightly, but is
thought to be the best solution. The primary reason for this is that the
`backtrace` crate needs to do some pretty nontrivial filesystem
interactions to locate debug information. Working without `std::fs` is
not an option, and while it might be possible to do some sort of
trait-based solution when prototyped it was found to be too unergonomic.
Using a submodule allows the `backtrace` crate to build as a submodule
of the `std` crate itself, enabling it to use `std::fs` and such.

Otherwise this adds new dependencies to the standard library. This step
requires extra attention because this means that these crates are now
going to be included with all Rust programs by default. It's important
to note, however, that we're already shipping libbacktrace with all Rust
programs by default and it has a bunch of C code implementing all of
this internally anyway, so we're basically already switching
already-shipping functionality to Rust from C.

* `object` - this crate is used to parse object file headers and
  contents. Very low-level support is used from this crate and almost
  all of it is disabled. Largely we're just using struct definitions as
  well as convenience methods internally to read bytes and such.

* `addr2line` - this is the main meat of the implementation for
  symbolication. This crate depends on `gimli` for DWARF parsing and
  then provides interfaces needed by the `backtrace` crate to turn an
  address into a filename / line number. This crate is actually pretty
  small (fits in a single file almost!) and mirrors most of what
  `dwarf.c` does for libbacktrace.

* `miniz_oxide` - the libbacktrace crate transparently handles
  compressed debug information which is compressed with zlib. This crate
  is used to decompress compressed debug sections.

* `gimli` - not actually used directly, but a dependency of `addr2line`.

* `adler32`- not used directly either, but a dependency of
  `miniz_oxide`.

The goal of this change is to improve the safety of backtrace
symbolication in the standard library, especially in the face of
possibly malformed DWARF debug information. Even to this day we're still
seeing segfaults in libbacktrace which could possibly become security
vulnerabilities. This change should almost entirely eliminate this
possibility whilc also paving the way forward to adding more features
like split debug information.

Some references for those interested are:

* Original addition of libbacktrace - rust-lang#12602
* OOM with libbacktrace - rust-lang#24231
* Backtrace failure due to use of uninitialized value - rust-lang#28447
* Possibility to feed untrusted data to libbacktrace - rust-lang#21889
* Soundness fix for libbacktrace - rust-lang#33729
* Crash in libbacktrace - rust-lang#39468
* Support for macOS, never merged - ianlancetaylor/libbacktrace#2
* Performance issues with libbacktrace - rust-lang#29293, rust-lang#37477
* Update procedure is quite complicated due to how many patches we
  need to carry - rust-lang#50955
* Libbacktrace doesn't work on MinGW with dynamic libs - rust-lang#71060
* Segfault in libbacktrace on macOS - rust-lang#71397

Switching to Rust will not make us immune to all of these issues. The
crashes are expected to go away, but correctness and performance may
still have bugs arise. The gimli and `backtrace` crates, however, are
actively maintained unlike libbacktrace, so this should enable us to at
least efficiently apply fixes as situations come up.

---

I want to note that my purpose for creating a PR here is to start a conversation about this. I think that all the various pieces are in place that this is compelling enough that I think this transition should be talked about seriously. There are a number of items which still need to be addressed before actually merging this PR, however:

* [ ] `gimli` needs to be published to crates.io
* [ ] `addr2line` needs a publish
* [ ] `miniz_oxide` needs a publish
* [ ] Tests probably shouldn't recommend the `gimli` crate's traits for implementing
* [ ] The `backtrace` crate's branch changes need to be merged to the master branch (rust-lang/backtrace-rs#349)
* [ ] The support for `libbacktrace` on some platforms needs to be audited to see if we should support more strategies in the gimli implementation - rust-lang/backtrace-rs#325, rust-lang/backtrace-rs#326, rust-lang/backtrace-rs#350, rust-lang/backtrace-rs#351

Most of the merging/publishing I'm not actively pushing on right now. It's a bit wonky for crates to support libstd so I'm holding off on pulling the trigger everywhere until there's a bit more discussion about how to go through with this. Namely rust-lang/backtrace-rs#349 I'm going to hold off merging until we decide to go through with the submodule strategy.

In any case this is a pretty major change, so I suspect that the compiler team is likely going to be interested in this. I don't mean to force changes by dumping a bunch of code by any means. Integration of external crates into the standard library is so difficult I wanted to have a proof-of-concept to review while talking about whether to do this at all (hence the PR), but I'm more than happy to follow any processes needed to merge this. I must admit though that I'm not entirely sure myself at this time what the process would be to decide to merge this, so I'm hoping others can help me figure that out!
  • Loading branch information
bors committed Jul 18, 2020
2 parents 7d31ffc + 13db3cc commit 1fa54ad
Show file tree
Hide file tree
Showing 13 changed files with 108 additions and 55 deletions.
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,6 @@
[submodule "src/tools/rust-analyzer"]
path = src/tools/rust-analyzer
url = https://github.com/rust-analyzer/rust-analyzer.git
[submodule "src/backtrace"]
path = src/backtrace
url = https://github.com/rust-lang/backtrace-rs.git
88 changes: 59 additions & 29 deletions Cargo.lock
Original file line number Diff line number Diff line change
@@ -1,10 +1,26 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "adler32"
version = "1.0.3"
name = "addr2line"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e522997b529f05601e05166c07ed17789691f562762c7f3b987263d2dedee5c"
checksum = "1b6a2d3371669ab3ca9797670853d61402b03d0b4b9ebf33d677dfa720203072"
dependencies = [
"compiler_builtins",
"gimli",
"rustc-std-workspace-alloc",
"rustc-std-workspace-core",
]

[[package]]
name = "adler"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccc9a9dd069569f212bc4330af9f17c4afb5e8ce185e83dbb14f1349dda18b10"
dependencies = [
"compiler_builtins",
"rustc-std-workspace-core",
]

[[package]]
name = "aho-corasick"
Expand Down Expand Up @@ -125,28 +141,14 @@ checksum = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d"

[[package]]
name = "backtrace"
version = "0.3.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1e692897359247cc6bb902933361652380af0f1b7651ae5c5013407f30e109e"
version = "0.3.50"
dependencies = [
"backtrace-sys",
"addr2line",
"cfg-if",
"compiler_builtins",
"libc",
"miniz_oxide",
"object",
"rustc-demangle",
"rustc-std-workspace-core",
]

[[package]]
name = "backtrace-sys"
version = "0.1.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "18fbebbe1c9d1f383a9cc7e8ccdb471b91c8d024ee9c2ca5b5346121fe8b4399"
dependencies = [
"cc",
"compiler_builtins",
"libc",
"rustc-std-workspace-core",
]

[[package]]
Expand Down Expand Up @@ -688,9 +690,9 @@ dependencies = [

[[package]]
name = "crc32fast"
version = "1.1.2"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e91d5240c6975ef33aeb5f148f35275c25eda8e8a5f95abe421978b05b8bf192"
checksum = "ba125de2af0df55319f41944744ad91c71113bf74a4646efff39afe1f6842db1"
dependencies = [
"cfg-if",
]
Expand Down Expand Up @@ -1023,9 +1025,9 @@ checksum = "37ab347416e802de484e4d03c7316c48f1ecb56574dfd4a46a80f173ce1de04d"

[[package]]
name = "flate2"
version = "1.0.12"
version = "1.0.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad3c5233c9a940c8719031b423d7e6c16af66e031cb0420b0896f5245bf181d3"
checksum = "68c90b0fc46cf89d227cc78b40e494ff81287a92dd07631e5af0d06fe3cf885e"
dependencies = [
"cfg-if",
"crc32fast",
Expand Down Expand Up @@ -1159,6 +1161,17 @@ dependencies = [
"wasi",
]

[[package]]
name = "gimli"
version = "0.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aaf91faf136cb47367fa430cd46e37a788775e7fa104f8b4bcb3861dc389b724"
dependencies = [
"compiler_builtins",
"rustc-std-workspace-alloc",
"rustc-std-workspace-core",
]

[[package]]
name = "git2"
version = "0.13.5"
Expand Down Expand Up @@ -1819,11 +1832,14 @@ dependencies = [

[[package]]
name = "miniz_oxide"
version = "0.3.5"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f3f74f726ae935c3f514300cc6773a0c9492abc5e972d42ba0c0ebb88757625"
checksum = "be0f75932c1f6cfae3c04000e40114adf955636e19040f9c0a2c380702aa1c7f"
dependencies = [
"adler32",
"adler",
"compiler_builtins",
"rustc-std-workspace-alloc",
"rustc-std-workspace-core",
]

[[package]]
Expand Down Expand Up @@ -1955,6 +1971,17 @@ dependencies = [
"libc",
]

[[package]]
name = "object"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ab52be62400ca80aa00285d25253d7f7c437b7375c4de678f5405d3afe82ca5"
dependencies = [
"compiler_builtins",
"rustc-std-workspace-alloc",
"rustc-std-workspace-core",
]

[[package]]
name = "once_cell"
version = "1.1.0"
Expand Down Expand Up @@ -4339,8 +4366,8 @@ dependencies = [
name = "std"
version = "0.0.0"
dependencies = [
"addr2line",
"alloc",
"backtrace",
"cfg-if",
"compiler_builtins",
"core",
Expand All @@ -4349,10 +4376,13 @@ dependencies = [
"hashbrown",
"hermit-abi",
"libc",
"miniz_oxide",
"object",
"panic_abort",
"panic_unwind",
"profiler_builtins",
"rand 0.7.3",
"rustc-demangle",
"unwind",
"wasi",
]
Expand Down
6 changes: 6 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -79,5 +79,11 @@ rustc-std-workspace-core = { path = 'src/tools/rustc-std-workspace-core' }
rustc-std-workspace-alloc = { path = 'src/tools/rustc-std-workspace-alloc' }
rustc-std-workspace-std = { path = 'src/tools/rustc-std-workspace-std' }

# This crate's integration with libstd is a bit wonky, so we use a submodule
# instead of a crates.io dependency. Make sure everything else in the repo is
# also using the submodule, however, so we can avoid duplicate copies of the
# source code for this crate.
backtrace = { path = "src/backtrace" }

[patch."https://github.com/rust-lang/rust-clippy"]
clippy_lints = { path = "src/tools/clippy/clippy_lints" }
1 change: 1 addition & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ ignore = [
"src/tools/rust-analyzer",
"src/tools/rust-installer",
"src/tools/rustfmt",
"src/backtrace",

# We do not format this file as it is externally sourced and auto-generated.
"src/libstd/sys/cloudabi/abi/cloudabi.rs",
Expand Down
1 change: 1 addition & 0 deletions src/backtrace
Submodule backtrace added at 8f8943
24 changes: 15 additions & 9 deletions src/libstd/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,15 @@ profiler_builtins = { path = "../libprofiler_builtins", optional = true }
unwind = { path = "../libunwind" }
hashbrown = { version = "0.6.2", default-features = false, features = ['rustc-dep-of-std'] }

[dependencies.backtrace_rs]
package = "backtrace"
version = "0.3.46"
default-features = false # without the libstd `backtrace` feature, stub out everything
features = [ "rustc-dep-of-std" ] # enable build support for integrating into libstd
# Dependencies of the `backtrace` crate
addr2line = { version = "0.13.0", optional = true, default-features = false }
rustc-demangle = { version = "0.1.4", optional = true }
miniz_oxide = { version = "0.4.0", optional = true, default-features = false }
[dependencies.object]
version = "0.20"
optional = true
default-features = false
features = ['read_core', 'elf', 'macho', 'pe']

[dev-dependencies]
rand = "0.7"
Expand All @@ -48,11 +52,13 @@ wasi = { version = "0.9.0", features = ['rustc-dep-of-std'], default-features =

[features]
backtrace = [
"backtrace_rs/dbghelp", # backtrace/symbolize on MSVC
"backtrace_rs/libbacktrace", # symbolize on most platforms
"backtrace_rs/libunwind", # backtrace on most platforms
"backtrace_rs/dladdr", # symbolize on platforms w/o libbacktrace
"gimli-symbolize",
'addr2line/rustc-dep-of-std',
'object/rustc-dep-of-std',
'rustc-demangle/rustc-dep-of-std',
'miniz_oxide/rustc-dep-of-std',
]
gimli-symbolize = []

panic-unwind = ["panic_unwind"]
profiler = ["profiler_builtins"]
Expand Down
21 changes: 10 additions & 11 deletions src/libstd/backtrace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,15 +91,14 @@
// `Backtrace`, but that's a relatively small price to pay relative to capturing
// a backtrace or actually symbolizing it.

use crate::backtrace_rs::{self, BytesOrWideString};
use crate::env;
use crate::ffi::c_void;
use crate::fmt;
use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst};
use crate::sync::Mutex;
use crate::sys_common::backtrace::{lock, output_filename};
use crate::vec::Vec;
use backtrace::BytesOrWideString;
use backtrace_rs as backtrace;

/// A captured OS thread stack backtrace.
///
Expand Down Expand Up @@ -150,7 +149,7 @@ struct BacktraceFrame {
}

enum RawFrame {
Actual(backtrace::Frame),
Actual(backtrace_rs::Frame),
#[cfg(test)]
Fake,
}
Expand Down Expand Up @@ -197,7 +196,7 @@ impl fmt::Debug for BacktraceSymbol {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "{{ ")?;

if let Some(fn_name) = self.name.as_ref().map(|b| backtrace::SymbolName::new(b)) {
if let Some(fn_name) = self.name.as_ref().map(|b| backtrace_rs::SymbolName::new(b)) {
write!(fmt, "fn: \"{:#}\"", fn_name)?;
} else {
write!(fmt, "fn: <unknown>")?;
Expand All @@ -223,7 +222,7 @@ impl fmt::Debug for BytesOrWide {
BytesOrWide::Bytes(w) => BytesOrWideString::Bytes(w),
BytesOrWide::Wide(w) => BytesOrWideString::Wide(w),
},
backtrace::PrintFmt::Short,
backtrace_rs::PrintFmt::Short,
crate::env::current_dir().as_ref().ok(),
)
}
Expand Down Expand Up @@ -299,7 +298,7 @@ impl Backtrace {
let mut frames = Vec::new();
let mut actual_start = None;
unsafe {
backtrace::trace_unsynchronized(|frame| {
backtrace_rs::trace_unsynchronized(|frame| {
frames.push(BacktraceFrame {
frame: RawFrame::Actual(frame.clone()),
symbols: Vec::new(),
Expand Down Expand Up @@ -350,9 +349,9 @@ impl fmt::Display for Backtrace {

let full = fmt.alternate();
let (frames, style) = if full {
(&capture.frames[..], backtrace::PrintFmt::Full)
(&capture.frames[..], backtrace_rs::PrintFmt::Full)
} else {
(&capture.frames[capture.actual_start..], backtrace::PrintFmt::Short)
(&capture.frames[capture.actual_start..], backtrace_rs::PrintFmt::Short)
};

// When printing paths we try to strip the cwd if it exists, otherwise
Expand All @@ -364,7 +363,7 @@ impl fmt::Display for Backtrace {
output_filename(fmt, path, style, cwd.as_ref().ok())
};

let mut f = backtrace::BacktraceFmt::new(fmt, style, &mut print_path);
let mut f = backtrace_rs::BacktraceFmt::new(fmt, style, &mut print_path);
f.add_context()?;
for frame in frames {
let mut f = f.frame();
Expand All @@ -374,7 +373,7 @@ impl fmt::Display for Backtrace {
for symbol in frame.symbols.iter() {
f.print_raw(
frame.frame.ip(),
symbol.name.as_ref().map(|b| backtrace::SymbolName::new(b)),
symbol.name.as_ref().map(|b| backtrace_rs::SymbolName::new(b)),
symbol.filename.as_ref().map(|b| match b {
BytesOrWide::Bytes(w) => BytesOrWideString::Bytes(w),
BytesOrWide::Wide(w) => BytesOrWideString::Wide(w),
Expand Down Expand Up @@ -409,7 +408,7 @@ impl Capture {
RawFrame::Fake => unimplemented!(),
};
unsafe {
backtrace::resolve_frame_unsynchronized(frame, |symbol| {
backtrace_rs::resolve_frame_unsynchronized(frame, |symbol| {
symbols.push(BacktraceSymbol {
name: symbol.name().map(|m| m.as_bytes().to_vec()),
filename: symbol.filename_raw().map(|b| match b {
Expand Down
1 change: 1 addition & 0 deletions src/libstd/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,5 @@ fn main() {
println!("cargo:rustc-cfg=feature=\"restricted-std\"");
}
println!("cargo:rustc-env=STD_ENV_ARCH={}", env::var("CARGO_CFG_TARGET_ARCH").unwrap());
println!("cargo:rustc-cfg=backtrace_in_libstd");
}
4 changes: 4 additions & 0 deletions src/libstd/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,10 @@ mod panicking;
// compiler
pub mod rt;

#[path = "../backtrace/src/lib.rs"]
#[allow(dead_code, unused_attributes)]
mod backtrace_rs;

// Pull in the `std_detect` crate directly into libstd. The contents of
// `std_detect` are in a different repository: rust-lang/stdarch.
//
Expand Down
2 changes: 1 addition & 1 deletion src/libstd/panicking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ fn default_hook(info: &PanicInfo<'_>) {
// If this is a double panic, make sure that we print a backtrace
// for this panic. Otherwise only print it if logging is enabled.
let backtrace_env = if panic_count::get() >= 2 {
RustBacktrace::Print(backtrace_rs::PrintFmt::Full)
RustBacktrace::Print(crate::backtrace_rs::PrintFmt::Full)
} else {
backtrace::rust_backtrace_env()
};
Expand Down
3 changes: 1 addition & 2 deletions src/libstd/sys_common/backtrace.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::backtrace_rs::{self, BacktraceFmt, BytesOrWideString, PrintFmt};
use crate::borrow::Cow;
/// Common code for printing the backtrace in the same way across the different
/// supported platforms.
Expand All @@ -9,8 +10,6 @@ use crate::path::{self, Path, PathBuf};
use crate::sync::atomic::{self, Ordering};
use crate::sys::mutex::Mutex;

use backtrace_rs::{BacktraceFmt, BytesOrWideString, PrintFmt};

/// Max number of frames to print.
const MAX_NB_FRAMES: usize = 100;

Expand Down
Loading

0 comments on commit 1fa54ad

Please sign in to comment.