From 9835e2ae736235810b4ea1c162ca5e65c547e770 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sat, 18 May 2024 04:49:50 +0200 Subject: Merging upstream version 1.71.1+dfsg1. Signed-off-by: Daniel Baumann --- library/backtrace/.github/workflows/main.yml | 36 +-- library/backtrace/Cargo.toml | 22 +- library/backtrace/src/backtrace/libunwind.rs | 3 +- library/backtrace/src/dbghelp.rs | 2 +- library/backtrace/src/print.rs | 2 +- library/backtrace/src/print/fuchsia.rs | 2 +- library/backtrace/src/symbolize/gimli.rs | 2 + .../src/symbolize/gimli/libs_dl_iterate_phdr.rs | 20 +- .../backtrace/src/symbolize/gimli/libs_macos.rs | 4 +- library/backtrace/src/symbolize/gimli/macho.rs | 4 +- .../backtrace/src/symbolize/gimli/mmap_windows.rs | 2 +- .../symbolize/gimli/parse_running_mmaps_unix.rs | 242 +++++++++++++++++++++ library/backtrace/src/windows.rs | 6 +- library/backtrace/tests/common/mod.rs | 14 ++ library/backtrace/tests/concurrent-panics.rs | 14 +- library/backtrace/tests/current-exe-mismatch.rs | 137 ++++++++++++ library/backtrace/tests/skip_inner_frames.rs | 2 +- 17 files changed, 464 insertions(+), 50 deletions(-) create mode 100644 library/backtrace/src/symbolize/gimli/parse_running_mmaps_unix.rs create mode 100644 library/backtrace/tests/common/mod.rs create mode 100644 library/backtrace/tests/current-exe-mismatch.rs (limited to 'library/backtrace') diff --git a/library/backtrace/.github/workflows/main.yml b/library/backtrace/.github/workflows/main.yml index c11b08dfd..24d814363 100644 --- a/library/backtrace/.github/workflows/main.yml +++ b/library/backtrace/.github/workflows/main.yml @@ -13,13 +13,14 @@ jobs: name: Test runs-on: ${{ matrix.os }} strategy: + fail-fast: false matrix: include: - - os: ubuntu-latest + - os: ubuntu-20.04 rust: stable - - os: ubuntu-latest + - os: ubuntu-20.04 rust: beta - - os: ubuntu-latest + - os: ubuntu-20.04 rust: nightly - os: macos-latest rust: stable @@ -34,7 +35,7 @@ jobs: - os: windows-latest rust: stable-x86_64-gnu steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v3 with: submodules: true - name: Install Rust (rustup) @@ -118,7 +119,7 @@ jobs: name: Windows AArch64 runs-on: windows-latest steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v3 with: submodules: true - name: Install Rust @@ -141,7 +142,7 @@ jobs: - target: x86_64-apple-ios sdk: iphonesimulator steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v3 with: submodules: true - run: rustup target add ${{ matrix.target }} @@ -154,8 +155,9 @@ jobs: docker: name: Docker - runs-on: ubuntu-latest + runs-on: ubuntu-20.04 strategy: + fail-fast: false matrix: target: - aarch64-unknown-linux-gnu @@ -174,7 +176,7 @@ jobs: - i686-linux-android - x86_64-linux-android steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v3 with: submodules: true - name: Install Rust @@ -187,9 +189,9 @@ jobs: rustfmt: name: Rustfmt - runs-on: ubuntu-latest + runs-on: ubuntu-20.04 steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v3 with: submodules: true - name: Install Rust @@ -198,17 +200,17 @@ jobs: build: name: Build Targets - runs-on: ubuntu-latest + runs-on: ubuntu-20.04 strategy: matrix: target: - wasm32-unknown-unknown - wasm32-wasi - - x86_64-fuchsia + - x86_64-unknown-fuchsia - x86_64-fortanix-unknown-sgx - x86_64-unknown-illumos steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v3 with: submodules: true - name: Install Rust @@ -221,9 +223,9 @@ jobs: msrv: name: MSRV - runs-on: ubuntu-latest + runs-on: ubuntu-20.04 steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v3 with: submodules: true - name: Install Rust @@ -232,9 +234,9 @@ jobs: miri: name: Miri - runs-on: ubuntu-latest + runs-on: ubuntu-20.04 steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v3 with: submodules: true - name: Install Miri diff --git a/library/backtrace/Cargo.toml b/library/backtrace/Cargo.toml index ef1c5ec00..477909111 100644 --- a/library/backtrace/Cargo.toml +++ b/library/backtrace/Cargo.toml @@ -1,9 +1,9 @@ [package] name = "backtrace" -version = "0.3.66" +version = "0.3.67" authors = ["The Rust Project Developers"] build = "build.rs" -license = "MIT/Apache-2.0" +license = "MIT OR Apache-2.0" readme = "README.md" repository = "https://github.com/rust-lang/backtrace-rs" homepage = "https://github.com/rust-lang/backtrace-rs" @@ -35,16 +35,13 @@ serde = { version = "1.0", optional = true, features = ['derive'] } rustc-serialize = { version = "0.3", optional = true } # Optionally demangle C++ frames' symbols in backtraces. -cpp_demangle = { default-features = false, version = "0.3.0", optional = true } +cpp_demangle = { default-features = false, version = "0.4.0", optional = true, features = ["alloc"] } - -# Optional dependencies enabled through the `gimli-symbolize` feature, do not -# use these features directly. -addr2line = { version = "0.17.0", default-features = false } -miniz_oxide = { version = "0.5.0", default-features = false } +addr2line = { version = "0.19.0", default-features = false } +miniz_oxide = { version = "0.6.0", default-features = false } [dependencies.object] -version = "0.29.0" +version = "0.30.0" default-features = false features = ['read_core', 'elf', 'macho', 'pe', 'unaligned', 'archive'] @@ -61,7 +58,7 @@ dylib-dep = { path = "crates/dylib-dep" } libloading = "0.7" [features] -# By default libstd support and gimli-symbolize is used to symbolize addresses. +# By default libstd support is enabled. default = ["std"] # Include std support. This enables types like `Backtrace`. @@ -130,3 +127,8 @@ edition = '2018' name = "concurrent-panics" required-features = ["std"] harness = false + +[[test]] +name = "current-exe-mismatch" +required-features = ["std"] +harness = false diff --git a/library/backtrace/src/backtrace/libunwind.rs b/library/backtrace/src/backtrace/libunwind.rs index ef77edda5..c319fe45a 100644 --- a/library/backtrace/src/backtrace/libunwind.rs +++ b/library/backtrace/src/backtrace/libunwind.rs @@ -158,7 +158,8 @@ mod uw { not(all(target_os = "android", target_arch = "arm")), not(all(target_os = "freebsd", target_arch = "arm")), not(all(target_os = "linux", target_arch = "arm")), - not(all(target_os = "horizon", target_arch = "arm")) + not(all(target_os = "horizon", target_arch = "arm")), + not(all(target_os = "vita", target_arch = "arm")), ))] { extern "C" { pub fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> libc::uintptr_t; diff --git a/library/backtrace/src/dbghelp.rs b/library/backtrace/src/dbghelp.rs index e01002beb..edeec653d 100644 --- a/library/backtrace/src/dbghelp.rs +++ b/library/backtrace/src/dbghelp.rs @@ -79,7 +79,7 @@ macro_rules! dbghelp { static mut DBGHELP: Dbghelp = Dbghelp { // Initially we haven't loaded the DLL dll: 0 as *mut _, - // Initiall all functions are set to zero to say they need to be + // Initially all functions are set to zero to say they need to be // dynamically loaded. $($name: 0,)* }; diff --git a/library/backtrace/src/print.rs b/library/backtrace/src/print.rs index cc677122a..174d8ae5c 100644 --- a/library/backtrace/src/print.rs +++ b/library/backtrace/src/print.rs @@ -135,7 +135,7 @@ impl BacktraceFrameFmt<'_, '_, '_> { symbol.name(), // TODO: this isn't great that we don't end up printing anything // with non-utf8 filenames. Thankfully almost everything is utf8 so - // this shouldn't be too too bad. + // this shouldn't be too bad. symbol .filename() .and_then(|p| Some(BytesOrWideString::Bytes(p.to_str()?.as_bytes()))), diff --git a/library/backtrace/src/print/fuchsia.rs b/library/backtrace/src/print/fuchsia.rs index 959253acb..ce3f17862 100644 --- a/library/backtrace/src/print/fuchsia.rs +++ b/library/backtrace/src/print/fuchsia.rs @@ -25,7 +25,7 @@ const PT_NOTE: u32 = 4; // Now we have to replicate, bit for bit, the structure of the dl_phdr_info // type used by fuchsia's current dynamic linker. Chromium also has this ABI -// boundary as well as crashpad. Eventully we'd like to move these cases to +// boundary as well as crashpad. Eventually we'd like to move these cases to // use elf-search but we'd need to provide that in the SDK and that has not // yet been done. Thus we (and they) are stuck having to use this method // which incurs a tight coupling with the fuchsia libc. diff --git a/library/backtrace/src/symbolize/gimli.rs b/library/backtrace/src/symbolize/gimli.rs index 5f10122dd..cd4cec58c 100644 --- a/library/backtrace/src/symbolize/gimli.rs +++ b/library/backtrace/src/symbolize/gimli.rs @@ -184,6 +184,8 @@ cfg_if::cfg_if! { ))] { mod libs_dl_iterate_phdr; use libs_dl_iterate_phdr::native_libraries; + #[path = "gimli/parse_running_mmaps_unix.rs"] + mod parse_running_mmaps; } else if #[cfg(target_env = "libnx")] { mod libs_libnx; use libs_libnx::native_libraries; diff --git a/library/backtrace/src/symbolize/gimli/libs_dl_iterate_phdr.rs b/library/backtrace/src/symbolize/gimli/libs_dl_iterate_phdr.rs index a011e6080..9f0304ce8 100644 --- a/library/backtrace/src/symbolize/gimli/libs_dl_iterate_phdr.rs +++ b/library/backtrace/src/symbolize/gimli/libs_dl_iterate_phdr.rs @@ -17,6 +17,20 @@ pub(super) fn native_libraries() -> Vec { return ret; } +fn infer_current_exe(base_addr: usize) -> OsString { + if let Ok(entries) = super::parse_running_mmaps::parse_maps() { + let opt_path = entries + .iter() + .find(|e| e.ip_matches(base_addr) && e.pathname().len() > 0) + .map(|e| e.pathname()) + .cloned(); + if let Some(path) = opt_path { + return path; + } + } + env::current_exe().map(|e| e.into()).unwrap_or_default() +} + // `info` should be a valid pointers. // `vec` should be a valid pointer to a `std::Vec`. unsafe extern "C" fn callback( @@ -28,8 +42,12 @@ unsafe extern "C" fn callback( let libs = &mut *(vec as *mut Vec); let is_main_prog = info.dlpi_name.is_null() || *info.dlpi_name == 0; let name = if is_main_prog { + // The man page for dl_iterate_phdr says that the first object visited by + // callback is the main program; so the first time we encounter a + // nameless entry, we can assume its the main program and try to infer its path. + // After that, we cannot continue that assumption, and we use an empty string. if libs.is_empty() { - env::current_exe().map(|e| e.into()).unwrap_or_default() + infer_current_exe(info.dlpi_addr as usize) } else { OsString::new() } diff --git a/library/backtrace/src/symbolize/gimli/libs_macos.rs b/library/backtrace/src/symbolize/gimli/libs_macos.rs index 17703b88a..438bbff6f 100644 --- a/library/backtrace/src/symbolize/gimli/libs_macos.rs +++ b/library/backtrace/src/symbolize/gimli/libs_macos.rs @@ -113,8 +113,8 @@ fn native_library(i: u32) -> Option { // file offset 0 with a nonzero size. For whatever reason when this // is present it appears to mean that the symbol table is relative // to just the vmaddr slide for the library. If it's *not* present - // then the symbol table is relative to the the vmaddr slide plus - // the segment's stated address. + // then the symbol table is relative to the vmaddr slide plus the + // segment's stated address. // // To handle this situation if we *don't* find a text section at // file offset zero then we increase the bias by the first text diff --git a/library/backtrace/src/symbolize/gimli/macho.rs b/library/backtrace/src/symbolize/gimli/macho.rs index ec5673843..adea97a09 100644 --- a/library/backtrace/src/symbolize/gimli/macho.rs +++ b/library/backtrace/src/symbolize/gimli/macho.rs @@ -13,8 +13,8 @@ type MachSection = ::Section; type MachNlist = ::Nlist; impl Mapping { - // The loading path for OSX is is so different we just have a completely - // different implementation of the function here. On OSX we need to go + // The loading path for macOS is so different we just have a completely + // different implementation of the function here. On macOS we need to go // probing the filesystem for a bunch of files. pub fn new(path: &Path) -> Option { // First up we need to load the unique UUID which is stored in the macho diff --git a/library/backtrace/src/symbolize/gimli/mmap_windows.rs b/library/backtrace/src/symbolize/gimli/mmap_windows.rs index 22f53fe03..b39509d8c 100644 --- a/library/backtrace/src/symbolize/gimli/mmap_windows.rs +++ b/library/backtrace/src/symbolize/gimli/mmap_windows.rs @@ -6,7 +6,7 @@ use core::ptr; use core::slice; pub struct Mmap { - // keep the file alive to prevent it from ebeing deleted which would cause + // keep the file alive to prevent it from being deleted which would cause // us to read bad data. _file: File, ptr: *mut c_void, diff --git a/library/backtrace/src/symbolize/gimli/parse_running_mmaps_unix.rs b/library/backtrace/src/symbolize/gimli/parse_running_mmaps_unix.rs new file mode 100644 index 000000000..a196ffcfb --- /dev/null +++ b/library/backtrace/src/symbolize/gimli/parse_running_mmaps_unix.rs @@ -0,0 +1,242 @@ +// Note: This file is only currently used on targets that call out to the code +// in `mod libs_dl_iterate_phdr` (e.g. linux, freebsd, ...); it may be more +// general purpose, but it hasn't been tested elsewhere. + +use super::mystd::fs::File; +use super::mystd::io::Read; +use super::mystd::str::FromStr; +use super::{OsString, String, Vec}; + +#[derive(PartialEq, Eq, Debug)] +pub(super) struct MapsEntry { + /// start (inclusive) and limit (exclusive) of address range. + address: (usize, usize), + /// The perms field are the permissions for the entry + /// + /// r = read + /// w = write + /// x = execute + /// s = shared + /// p = private (copy on write) + perms: [char; 4], + /// Offset into the file (or "whatever"). + offset: usize, + /// device (major, minor) + dev: (usize, usize), + /// inode on the device. 0 indicates that no inode is associated with the memory region (e.g. uninitalized data aka BSS). + inode: usize, + /// Usually the file backing the mapping. + /// + /// Note: The man page for proc includes a note about "coordination" by + /// using readelf to see the Offset field in ELF program headers. pnkfelix + /// is not yet sure if that is intended to be a comment on pathname, or what + /// form/purpose such coordination is meant to have. + /// + /// There are also some pseudo-paths: + /// "[stack]": The initial process's (aka main thread's) stack. + /// "[stack:]": a specific thread's stack. (This was only present for a limited range of Linux verisons; it was determined to be too expensive to provide.) + /// "[vdso]": Virtual dynamically linked shared object + /// "[heap]": The process's heap + /// + /// The pathname can be blank, which means it is an anonymous mapping + /// obtained via mmap. + /// + /// Newlines in pathname are replaced with an octal escape sequence. + /// + /// The pathname may have "(deleted)" appended onto it if the file-backed + /// path has been deleted. + /// + /// Note that modifications like the latter two indicated above imply that + /// in general the pathname may be ambiguous. (I.e. you cannot tell if the + /// denoted filename actually ended with the text "(deleted)", or if that + /// was added by the maps rendering. + pathname: OsString, +} + +pub(super) fn parse_maps() -> Result, &'static str> { + let mut v = Vec::new(); + let mut proc_self_maps = + File::open("/proc/self/maps").map_err(|_| "Couldn't open /proc/self/maps")?; + let mut buf = String::new(); + let _bytes_read = proc_self_maps + .read_to_string(&mut buf) + .map_err(|_| "Couldn't read /proc/self/maps")?; + for line in buf.lines() { + v.push(line.parse()?); + } + + Ok(v) +} + +impl MapsEntry { + pub(super) fn pathname(&self) -> &OsString { + &self.pathname + } + + pub(super) fn ip_matches(&self, ip: usize) -> bool { + self.address.0 <= ip && ip < self.address.1 + } +} + +impl FromStr for MapsEntry { + type Err = &'static str; + + // Format: address perms offset dev inode pathname + // e.g.: "ffffffffff600000-ffffffffff601000 --xp 00000000 00:00 0 [vsyscall]" + // e.g.: "7f5985f46000-7f5985f48000 rw-p 00039000 103:06 76021795 /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2" + // e.g.: "35b1a21000-35b1a22000 rw-p 00000000 00:00 0" + fn from_str(s: &str) -> Result { + let mut parts = s + .split(' ') // space-separated fields + .filter(|s| s.len() > 0); // multiple spaces implies empty strings that need to be skipped. + let range_str = parts.next().ok_or("Couldn't find address")?; + let perms_str = parts.next().ok_or("Couldn't find permissions")?; + let offset_str = parts.next().ok_or("Couldn't find offset")?; + let dev_str = parts.next().ok_or("Couldn't find dev")?; + let inode_str = parts.next().ok_or("Couldn't find inode")?; + let pathname_str = parts.next().unwrap_or(""); // pathname may be omitted. + + let hex = |s| usize::from_str_radix(s, 16).map_err(|_| "Couldn't parse hex number"); + let address = { + // This could use `range_str.split_once('-')` once the MSRV passes 1.52. + if let Some(idx) = range_str.find('-') { + let (start, rest) = range_str.split_at(idx); + let (_div, limit) = rest.split_at(1); + (hex(start)?, hex(limit)?) + } else { + return Err("Couldn't parse address range"); + } + }; + let perms: [char; 4] = { + let mut chars = perms_str.chars(); + let mut c = || chars.next().ok_or("insufficient perms"); + let perms = [c()?, c()?, c()?, c()?]; + if chars.next().is_some() { + return Err("too many perms"); + } + perms + }; + let offset = hex(offset_str)?; + let dev = { + // This could use `dev_str.split_once(':')` once the MSRV passes 1.52. + if let Some(idx) = dev_str.find(':') { + let (major, rest) = dev_str.split_at(idx); + let (_div, minor) = rest.split_at(1); + (hex(major)?, hex(minor)?) + } else { + return Err("Couldn't parse dev")?; + } + }; + let inode = hex(inode_str)?; + let pathname = pathname_str.into(); + + Ok(MapsEntry { + address, + perms, + offset, + dev, + inode, + pathname, + }) + } +} + +// Make sure we can parse 64-bit sample output if we're on a 64-bit target. +#[cfg(target_pointer_width = "64")] +#[test] +fn check_maps_entry_parsing_64bit() { + assert_eq!( + "ffffffffff600000-ffffffffff601000 --xp 00000000 00:00 0 \ + [vsyscall]" + .parse::() + .unwrap(), + MapsEntry { + address: (0xffffffffff600000, 0xffffffffff601000), + perms: ['-', '-', 'x', 'p'], + offset: 0x00000000, + dev: (0x00, 0x00), + inode: 0x0, + pathname: "[vsyscall]".into(), + } + ); + + assert_eq!( + "7f5985f46000-7f5985f48000 rw-p 00039000 103:06 76021795 \ + /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2" + .parse::() + .unwrap(), + MapsEntry { + address: (0x7f5985f46000, 0x7f5985f48000), + perms: ['r', 'w', '-', 'p'], + offset: 0x00039000, + dev: (0x103, 0x06), + inode: 0x76021795, + pathname: "/usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2".into(), + } + ); + assert_eq!( + "35b1a21000-35b1a22000 rw-p 00000000 00:00 0" + .parse::() + .unwrap(), + MapsEntry { + address: (0x35b1a21000, 0x35b1a22000), + perms: ['r', 'w', '-', 'p'], + offset: 0x00000000, + dev: (0x00, 0x00), + inode: 0x0, + pathname: Default::default(), + } + ); +} + +// (This output was taken from a 32-bit machine, but will work on any target) +#[test] +fn check_maps_entry_parsing_32bit() { + /* Example snippet of output: + 08056000-08077000 rw-p 00000000 00:00 0 [heap] + b7c79000-b7e02000 r--p 00000000 08:01 60662705 /usr/lib/locale/locale-archive + b7e02000-b7e03000 rw-p 00000000 00:00 0 + */ + assert_eq!( + "08056000-08077000 rw-p 00000000 00:00 0 \ + [heap]" + .parse::() + .unwrap(), + MapsEntry { + address: (0x08056000, 0x08077000), + perms: ['r', 'w', '-', 'p'], + offset: 0x00000000, + dev: (0x00, 0x00), + inode: 0x0, + pathname: "[heap]".into(), + } + ); + + assert_eq!( + "b7c79000-b7e02000 r--p 00000000 08:01 60662705 \ + /usr/lib/locale/locale-archive" + .parse::() + .unwrap(), + MapsEntry { + address: (0xb7c79000, 0xb7e02000), + perms: ['r', '-', '-', 'p'], + offset: 0x00000000, + dev: (0x08, 0x01), + inode: 0x60662705, + pathname: "/usr/lib/locale/locale-archive".into(), + } + ); + assert_eq!( + "b7e02000-b7e03000 rw-p 00000000 00:00 0" + .parse::() + .unwrap(), + MapsEntry { + address: (0xb7e02000, 0xb7e03000), + perms: ['r', 'w', '-', 'p'], + offset: 0x00000000, + dev: (0x00, 0x00), + inode: 0x0, + pathname: Default::default(), + } + ); +} diff --git a/library/backtrace/src/windows.rs b/library/backtrace/src/windows.rs index d091874f1..9ec3ba99b 100644 --- a/library/backtrace/src/windows.rs +++ b/library/backtrace/src/windows.rs @@ -162,8 +162,8 @@ macro_rules! ffi { ffi!($($rest)*); ); - (extern "system" { $(pub fn $name:ident($($args:tt)*) -> $ret:ty;)* } $($rest:tt)*) => ( - extern "system" { + ($(#[$meta:meta])* extern "system" { $(pub fn $name:ident($($args:tt)*) -> $ret:ty;)* } $($rest:tt)*) => ( + $(#[$meta])* extern "system" { $(pub fn $name($($args)*) -> $ret;)* } @@ -371,6 +371,7 @@ ffi! { pub type LPCVOID = *const c_void; pub type LPMODULEENTRY32W = *mut MODULEENTRY32W; + #[link(name = "kernel32")] extern "system" { pub fn GetCurrentProcess() -> HANDLE; pub fn GetCurrentThread() -> HANDLE; @@ -438,6 +439,7 @@ ffi! { #[cfg(target_pointer_width = "64")] ffi! { + #[link(name = "kernel32")] extern "system" { pub fn RtlLookupFunctionEntry( ControlPc: DWORD64, diff --git a/library/backtrace/tests/common/mod.rs b/library/backtrace/tests/common/mod.rs new file mode 100644 index 000000000..3c07934fd --- /dev/null +++ b/library/backtrace/tests/common/mod.rs @@ -0,0 +1,14 @@ +/// Some tests only make sense in contexts where they can re-exec the test +/// itself. Not all contexts support this, so you can call this method to find +/// out which case you are in. +pub fn cannot_reexec_the_test() -> bool { + // These run in docker containers on CI where they can't re-exec the test, + // so just skip these for CI. No other reason this can't run on those + // platforms though. + // Miri does not have support for re-execing a file + cfg!(unix) + && (cfg!(target_arch = "arm") + || cfg!(target_arch = "aarch64") + || cfg!(target_arch = "s390x")) + || cfg!(miri) +} diff --git a/library/backtrace/tests/concurrent-panics.rs b/library/backtrace/tests/concurrent-panics.rs index 470245cc9..a44a26771 100644 --- a/library/backtrace/tests/concurrent-panics.rs +++ b/library/backtrace/tests/concurrent-panics.rs @@ -9,17 +9,11 @@ const PANICS: usize = 100; const THREADS: usize = 8; const VAR: &str = "__THE_TEST_YOU_ARE_LUKE"; +mod common; + fn main() { - // These run in docker containers on CI where they can't re-exec the test, - // so just skip these for CI. No other reason this can't run on those - // platforms though. - // Miri does not have support for re-execing a file - if cfg!(unix) - && (cfg!(target_arch = "arm") - || cfg!(target_arch = "aarch64") - || cfg!(target_arch = "s390x")) - || cfg!(miri) - { + // If we cannot re-exec this test, there's no point in trying to do it. + if common::cannot_reexec_the_test() { println!("test result: ok"); return; } diff --git a/library/backtrace/tests/current-exe-mismatch.rs b/library/backtrace/tests/current-exe-mismatch.rs new file mode 100644 index 000000000..21c67bcbf --- /dev/null +++ b/library/backtrace/tests/current-exe-mismatch.rs @@ -0,0 +1,137 @@ +// rust-lang/rust#101913: when you run your program explicitly via `ld.so`, +// `std::env::current_exe` will return the path of *that* program, and not +// the Rust program itself. + +use std::io::{BufRead, BufReader}; +use std::path::{Path, PathBuf}; +use std::process::Command; + +mod common; + +fn main() { + if std::env::var(VAR).is_err() { + // the parent waits for the child; then we then handle either printing + // "test result: ok", "test result: ignored", or panicking. + match parent() { + Ok(()) => { + println!("test result: ok"); + } + Err(EarlyExit::IgnoreTest(_)) => { + println!("test result: ignored"); + } + Err(EarlyExit::IoError(e)) => { + println!("{} parent encoutered IoError: {:?}", file!(), e); + panic!(); + } + } + } else { + // println!("{} running child", file!()); + child().unwrap(); + } +} + +const VAR: &str = "__THE_TEST_YOU_ARE_LUKE"; + +#[derive(Debug)] +enum EarlyExit { + IgnoreTest(String), + IoError(std::io::Error), +} + +impl From for EarlyExit { + fn from(e: std::io::Error) -> Self { + EarlyExit::IoError(e) + } +} + +fn parent() -> Result<(), EarlyExit> { + // If we cannot re-exec this test, there's no point in trying to do it. + if common::cannot_reexec_the_test() { + return Err(EarlyExit::IgnoreTest("(cannot reexec)".into())); + } + + let me = std::env::current_exe().unwrap(); + let ld_so = find_interpreter(&me)?; + + // use interp to invoke current exe, yielding child test. + // + // (if you're curious what you might compare this against, you can try + // swapping in the below definition for `result`, which is the easy case of + // not using the ld.so interpreter directly that Rust handled fine even + // prior to resolution of rust-lang/rust#101913.) + // + // let result = Command::new(me).env(VAR, "1").output()?; + let result = Command::new(ld_so).env(VAR, "1").arg(&me).output().unwrap(); + + if result.status.success() { + return Ok(()); + } + println!("stdout:\n{}", String::from_utf8_lossy(&result.stdout)); + println!("stderr:\n{}", String::from_utf8_lossy(&result.stderr)); + println!("code: {}", result.status); + panic!(); +} + +fn child() -> Result<(), EarlyExit> { + let bt = backtrace::Backtrace::new(); + println!("{:?}", bt); + + let mut found_my_name = false; + + let my_filename = file!(); + 'frames: for frame in bt.frames() { + let symbols = frame.symbols(); + if symbols.is_empty() { + continue; + } + + for sym in symbols { + if let Some(filename) = sym.filename() { + if filename.ends_with(my_filename) { + // huzzah! + found_my_name = true; + break 'frames; + } + } + } + } + + assert!(found_my_name); + + Ok(()) +} + +// we use the `readelf` command to extract the path to the interpreter requested +// by our binary. +// +// if we cannot `readelf` for some reason, or if we fail to parse its output, +// then we will just give up on this test (and not treat it as a test failure). +fn find_interpreter(me: &Path) -> Result { + let result = Command::new("readelf") + .arg("-l") + .arg(me) + .output() + .map_err(|_err| EarlyExit::IgnoreTest("readelf invocation failed".into()))?; + if result.status.success() { + let r = BufReader::new(&result.stdout[..]); + for line in r.lines() { + let line = line?; + let line = line.trim(); + let prefix = "[Requesting program interpreter: "; + // This could use `line.split_once` and `suffix.rsplit_once` once the MSRV passes 1.52 + if let Some(idx) = line.find(prefix) { + let (_, suffix) = line.split_at(idx + prefix.len()); + if let Some(idx) = suffix.rfind("]") { + let (found_path, _ignore_remainder) = suffix.split_at(idx); + return Ok(found_path.into()); + } + } + } + + Err(EarlyExit::IgnoreTest( + "could not find interpreter from readelf output".into(), + )) + } else { + Err(EarlyExit::IgnoreTest("readelf returned non-success".into())) + } +} diff --git a/library/backtrace/tests/skip_inner_frames.rs b/library/backtrace/tests/skip_inner_frames.rs index 8b57bef52..60bba35e6 100644 --- a/library/backtrace/tests/skip_inner_frames.rs +++ b/library/backtrace/tests/skip_inner_frames.rs @@ -4,7 +4,7 @@ use backtrace::Backtrace; // function for frames which reports the starting address of a symbol. As a // result it's only enabled on a few platforms. const ENABLED: bool = cfg!(all( - // Windows hasn't really been tested, and OSX doesn't support actually + // Windows hasn't really been tested, and macOS doesn't support actually // finding an enclosing frame, so disable this target_os = "linux", // On ARM finding the enclosing function is simply returning the ip itself. -- cgit v1.2.3