Skip to content

Commit 13db3cc

Browse files
committed
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 - #12602 * OOM with libbacktrace - #24231 * Backtrace failure due to use of uninitialized value - #28447 * Possibility to feed untrusted data to libbacktrace - #21889 * Soundness fix for libbacktrace - #33729 * Crash in libbacktrace - #39468 * Support for macOS, never merged - ianlancetaylor/libbacktrace#2 * Performance issues with libbacktrace - #29293, #37477 * Update procedure is quite complicated due to how many patches we need to carry - #50955 * Libbacktrace doesn't work on MinGW with dynamic libs - #71060 * Segfault in libbacktrace on macOS - #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.
1 parent c2dbebd commit 13db3cc

13 files changed

+108
-55
lines changed

.gitmodules

+3
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,6 @@
4444
[submodule "src/tools/rust-analyzer"]
4545
path = src/tools/rust-analyzer
4646
url = https://github.com/rust-analyzer/rust-analyzer.git
47+
[submodule "src/backtrace"]
48+
path = src/backtrace
49+
url = https://github.com/rust-lang/backtrace-rs.git

Cargo.lock

+59-29
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,26 @@
11
# This file is automatically @generated by Cargo.
22
# It is not intended for manual editing.
33
[[package]]
4-
name = "adler32"
5-
version = "1.0.3"
4+
name = "addr2line"
5+
version = "0.13.0"
66
source = "registry+https://github.com/rust-lang/crates.io-index"
7-
checksum = "7e522997b529f05601e05166c07ed17789691f562762c7f3b987263d2dedee5c"
7+
checksum = "1b6a2d3371669ab3ca9797670853d61402b03d0b4b9ebf33d677dfa720203072"
8+
dependencies = [
9+
"compiler_builtins",
10+
"gimli",
11+
"rustc-std-workspace-alloc",
12+
"rustc-std-workspace-core",
13+
]
14+
15+
[[package]]
16+
name = "adler"
17+
version = "0.2.2"
18+
source = "registry+https://github.com/rust-lang/crates.io-index"
19+
checksum = "ccc9a9dd069569f212bc4330af9f17c4afb5e8ce185e83dbb14f1349dda18b10"
20+
dependencies = [
21+
"compiler_builtins",
22+
"rustc-std-workspace-core",
23+
]
824

925
[[package]]
1026
name = "aho-corasick"
@@ -125,28 +141,14 @@ checksum = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d"
125141

126142
[[package]]
127143
name = "backtrace"
128-
version = "0.3.46"
129-
source = "registry+https://github.com/rust-lang/crates.io-index"
130-
checksum = "b1e692897359247cc6bb902933361652380af0f1b7651ae5c5013407f30e109e"
144+
version = "0.3.50"
131145
dependencies = [
132-
"backtrace-sys",
146+
"addr2line",
133147
"cfg-if",
134-
"compiler_builtins",
135148
"libc",
149+
"miniz_oxide",
150+
"object",
136151
"rustc-demangle",
137-
"rustc-std-workspace-core",
138-
]
139-
140-
[[package]]
141-
name = "backtrace-sys"
142-
version = "0.1.37"
143-
source = "registry+https://github.com/rust-lang/crates.io-index"
144-
checksum = "18fbebbe1c9d1f383a9cc7e8ccdb471b91c8d024ee9c2ca5b5346121fe8b4399"
145-
dependencies = [
146-
"cc",
147-
"compiler_builtins",
148-
"libc",
149-
"rustc-std-workspace-core",
150152
]
151153

152154
[[package]]
@@ -688,9 +690,9 @@ dependencies = [
688690

689691
[[package]]
690692
name = "crc32fast"
691-
version = "1.1.2"
693+
version = "1.2.0"
692694
source = "registry+https://github.com/rust-lang/crates.io-index"
693-
checksum = "e91d5240c6975ef33aeb5f148f35275c25eda8e8a5f95abe421978b05b8bf192"
695+
checksum = "ba125de2af0df55319f41944744ad91c71113bf74a4646efff39afe1f6842db1"
694696
dependencies = [
695697
"cfg-if",
696698
]
@@ -1023,9 +1025,9 @@ checksum = "37ab347416e802de484e4d03c7316c48f1ecb56574dfd4a46a80f173ce1de04d"
10231025

10241026
[[package]]
10251027
name = "flate2"
1026-
version = "1.0.12"
1028+
version = "1.0.16"
10271029
source = "registry+https://github.com/rust-lang/crates.io-index"
1028-
checksum = "ad3c5233c9a940c8719031b423d7e6c16af66e031cb0420b0896f5245bf181d3"
1030+
checksum = "68c90b0fc46cf89d227cc78b40e494ff81287a92dd07631e5af0d06fe3cf885e"
10291031
dependencies = [
10301032
"cfg-if",
10311033
"crc32fast",
@@ -1159,6 +1161,17 @@ dependencies = [
11591161
"wasi",
11601162
]
11611163

1164+
[[package]]
1165+
name = "gimli"
1166+
version = "0.22.0"
1167+
source = "registry+https://github.com/rust-lang/crates.io-index"
1168+
checksum = "aaf91faf136cb47367fa430cd46e37a788775e7fa104f8b4bcb3861dc389b724"
1169+
dependencies = [
1170+
"compiler_builtins",
1171+
"rustc-std-workspace-alloc",
1172+
"rustc-std-workspace-core",
1173+
]
1174+
11621175
[[package]]
11631176
name = "git2"
11641177
version = "0.13.5"
@@ -1819,11 +1832,14 @@ dependencies = [
18191832

18201833
[[package]]
18211834
name = "miniz_oxide"
1822-
version = "0.3.5"
1835+
version = "0.4.0"
18231836
source = "registry+https://github.com/rust-lang/crates.io-index"
1824-
checksum = "6f3f74f726ae935c3f514300cc6773a0c9492abc5e972d42ba0c0ebb88757625"
1837+
checksum = "be0f75932c1f6cfae3c04000e40114adf955636e19040f9c0a2c380702aa1c7f"
18251838
dependencies = [
1826-
"adler32",
1839+
"adler",
1840+
"compiler_builtins",
1841+
"rustc-std-workspace-alloc",
1842+
"rustc-std-workspace-core",
18271843
]
18281844

18291845
[[package]]
@@ -1955,6 +1971,17 @@ dependencies = [
19551971
"libc",
19561972
]
19571973

1974+
[[package]]
1975+
name = "object"
1976+
version = "0.20.0"
1977+
source = "registry+https://github.com/rust-lang/crates.io-index"
1978+
checksum = "1ab52be62400ca80aa00285d25253d7f7c437b7375c4de678f5405d3afe82ca5"
1979+
dependencies = [
1980+
"compiler_builtins",
1981+
"rustc-std-workspace-alloc",
1982+
"rustc-std-workspace-core",
1983+
]
1984+
19581985
[[package]]
19591986
name = "once_cell"
19601987
version = "1.1.0"
@@ -4332,8 +4359,8 @@ dependencies = [
43324359
name = "std"
43334360
version = "0.0.0"
43344361
dependencies = [
4362+
"addr2line",
43354363
"alloc",
4336-
"backtrace",
43374364
"cfg-if",
43384365
"compiler_builtins",
43394366
"core",
@@ -4342,10 +4369,13 @@ dependencies = [
43424369
"hashbrown",
43434370
"hermit-abi",
43444371
"libc",
4372+
"miniz_oxide",
4373+
"object",
43454374
"panic_abort",
43464375
"panic_unwind",
43474376
"profiler_builtins",
43484377
"rand 0.7.3",
4378+
"rustc-demangle",
43494379
"unwind",
43504380
"wasi",
43514381
]

Cargo.toml

+6
Original file line numberDiff line numberDiff line change
@@ -79,5 +79,11 @@ rustc-std-workspace-core = { path = 'src/tools/rustc-std-workspace-core' }
7979
rustc-std-workspace-alloc = { path = 'src/tools/rustc-std-workspace-alloc' }
8080
rustc-std-workspace-std = { path = 'src/tools/rustc-std-workspace-std' }
8181

82+
# This crate's integration with libstd is a bit wonky, so we use a submodule
83+
# instead of a crates.io dependency. Make sure everything else in the repo is
84+
# also using the submodule, however, so we can avoid duplicate copies of the
85+
# source code for this crate.
86+
backtrace = { path = "src/backtrace" }
87+
8288
[patch."https://github.com/rust-lang/rust-clippy"]
8389
clippy_lints = { path = "src/tools/clippy/clippy_lints" }

rustfmt.toml

+1
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ ignore = [
3030
"src/tools/rust-analyzer",
3131
"src/tools/rust-installer",
3232
"src/tools/rustfmt",
33+
"src/backtrace",
3334

3435
# We do not format this file as it is externally sourced and auto-generated.
3536
"src/libstd/sys/cloudabi/abi/cloudabi.rs",

src/backtrace

Submodule backtrace added at 8f89434

src/libstd/Cargo.toml

+15-9
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,15 @@ profiler_builtins = { path = "../libprofiler_builtins", optional = true }
2525
unwind = { path = "../libunwind" }
2626
hashbrown = { version = "0.6.2", default-features = false, features = ['rustc-dep-of-std'] }
2727

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

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

4953
[features]
5054
backtrace = [
51-
"backtrace_rs/dbghelp", # backtrace/symbolize on MSVC
52-
"backtrace_rs/libbacktrace", # symbolize on most platforms
53-
"backtrace_rs/libunwind", # backtrace on most platforms
54-
"backtrace_rs/dladdr", # symbolize on platforms w/o libbacktrace
55+
"gimli-symbolize",
56+
'addr2line/rustc-dep-of-std',
57+
'object/rustc-dep-of-std',
58+
'rustc-demangle/rustc-dep-of-std',
59+
'miniz_oxide/rustc-dep-of-std',
5560
]
61+
gimli-symbolize = []
5662

5763
panic-unwind = ["panic_unwind"]
5864
profiler = ["profiler_builtins"]

src/libstd/backtrace.rs

+10-11
Original file line numberDiff line numberDiff line change
@@ -91,15 +91,14 @@
9191
// `Backtrace`, but that's a relatively small price to pay relative to capturing
9292
// a backtrace or actually symbolizing it.
9393

94+
use crate::backtrace_rs::{self, BytesOrWideString};
9495
use crate::env;
9596
use crate::ffi::c_void;
9697
use crate::fmt;
9798
use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst};
9899
use crate::sync::Mutex;
99100
use crate::sys_common::backtrace::{lock, output_filename};
100101
use crate::vec::Vec;
101-
use backtrace::BytesOrWideString;
102-
use backtrace_rs as backtrace;
103102

104103
/// A captured OS thread stack backtrace.
105104
///
@@ -150,7 +149,7 @@ struct BacktraceFrame {
150149
}
151150

152151
enum RawFrame {
153-
Actual(backtrace::Frame),
152+
Actual(backtrace_rs::Frame),
154153
#[cfg(test)]
155154
Fake,
156155
}
@@ -197,7 +196,7 @@ impl fmt::Debug for BacktraceSymbol {
197196
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
198197
write!(fmt, "{{ ")?;
199198

200-
if let Some(fn_name) = self.name.as_ref().map(|b| backtrace::SymbolName::new(b)) {
199+
if let Some(fn_name) = self.name.as_ref().map(|b| backtrace_rs::SymbolName::new(b)) {
201200
write!(fmt, "fn: \"{:#}\"", fn_name)?;
202201
} else {
203202
write!(fmt, "fn: <unknown>")?;
@@ -223,7 +222,7 @@ impl fmt::Debug for BytesOrWide {
223222
BytesOrWide::Bytes(w) => BytesOrWideString::Bytes(w),
224223
BytesOrWide::Wide(w) => BytesOrWideString::Wide(w),
225224
},
226-
backtrace::PrintFmt::Short,
225+
backtrace_rs::PrintFmt::Short,
227226
crate::env::current_dir().as_ref().ok(),
228227
)
229228
}
@@ -299,7 +298,7 @@ impl Backtrace {
299298
let mut frames = Vec::new();
300299
let mut actual_start = None;
301300
unsafe {
302-
backtrace::trace_unsynchronized(|frame| {
301+
backtrace_rs::trace_unsynchronized(|frame| {
303302
frames.push(BacktraceFrame {
304303
frame: RawFrame::Actual(frame.clone()),
305304
symbols: Vec::new(),
@@ -350,9 +349,9 @@ impl fmt::Display for Backtrace {
350349

351350
let full = fmt.alternate();
352351
let (frames, style) = if full {
353-
(&capture.frames[..], backtrace::PrintFmt::Full)
352+
(&capture.frames[..], backtrace_rs::PrintFmt::Full)
354353
} else {
355-
(&capture.frames[capture.actual_start..], backtrace::PrintFmt::Short)
354+
(&capture.frames[capture.actual_start..], backtrace_rs::PrintFmt::Short)
356355
};
357356

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

367-
let mut f = backtrace::BacktraceFmt::new(fmt, style, &mut print_path);
366+
let mut f = backtrace_rs::BacktraceFmt::new(fmt, style, &mut print_path);
368367
f.add_context()?;
369368
for frame in frames {
370369
let mut f = f.frame();
@@ -374,7 +373,7 @@ impl fmt::Display for Backtrace {
374373
for symbol in frame.symbols.iter() {
375374
f.print_raw(
376375
frame.frame.ip(),
377-
symbol.name.as_ref().map(|b| backtrace::SymbolName::new(b)),
376+
symbol.name.as_ref().map(|b| backtrace_rs::SymbolName::new(b)),
378377
symbol.filename.as_ref().map(|b| match b {
379378
BytesOrWide::Bytes(w) => BytesOrWideString::Bytes(w),
380379
BytesOrWide::Wide(w) => BytesOrWideString::Wide(w),
@@ -409,7 +408,7 @@ impl Capture {
409408
RawFrame::Fake => unimplemented!(),
410409
};
411410
unsafe {
412-
backtrace::resolve_frame_unsynchronized(frame, |symbol| {
411+
backtrace_rs::resolve_frame_unsynchronized(frame, |symbol| {
413412
symbols.push(BacktraceSymbol {
414413
name: symbol.name().map(|m| m.as_bytes().to_vec()),
415414
filename: symbol.filename_raw().map(|b| match b {

src/libstd/build.rs

+1
Original file line numberDiff line numberDiff line change
@@ -87,4 +87,5 @@ fn main() {
8787
println!("cargo:rustc-cfg=feature=\"restricted-std\"");
8888
}
8989
println!("cargo:rustc-env=STD_ENV_ARCH={}", env::var("CARGO_CFG_TARGET_ARCH").unwrap());
90+
println!("cargo:rustc-cfg=backtrace_in_libstd");
9091
}

src/libstd/lib.rs

+4
Original file line numberDiff line numberDiff line change
@@ -508,6 +508,10 @@ mod panicking;
508508
// compiler
509509
pub mod rt;
510510

511+
#[path = "../backtrace/src/lib.rs"]
512+
#[allow(dead_code, unused_attributes)]
513+
mod backtrace_rs;
514+
511515
// Pull in the `std_detect` crate directly into libstd. The contents of
512516
// `std_detect` are in a different repository: rust-lang/stdarch.
513517
//

src/libstd/panicking.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ fn default_hook(info: &PanicInfo<'_>) {
171171
// If this is a double panic, make sure that we print a backtrace
172172
// for this panic. Otherwise only print it if logging is enabled.
173173
let backtrace_env = if panic_count::get() >= 2 {
174-
RustBacktrace::Print(backtrace_rs::PrintFmt::Full)
174+
RustBacktrace::Print(crate::backtrace_rs::PrintFmt::Full)
175175
} else {
176176
backtrace::rust_backtrace_env()
177177
};

src/libstd/sys_common/backtrace.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use crate::backtrace_rs::{self, BacktraceFmt, BytesOrWideString, PrintFmt};
12
use crate::borrow::Cow;
23
/// Common code for printing the backtrace in the same way across the different
34
/// supported platforms.
@@ -9,8 +10,6 @@ use crate::path::{self, Path, PathBuf};
910
use crate::sync::atomic::{self, Ordering};
1011
use crate::sys::mutex::Mutex;
1112

12-
use backtrace_rs::{BacktraceFmt, BytesOrWideString, PrintFmt};
13-
1413
/// Max number of frames to print.
1514
const MAX_NB_FRAMES: usize = 100;
1615

0 commit comments

Comments
 (0)