findshlibs-0.5.0/.coveralls.yml010066400017500001750000000000001314463037000146460ustar0000000000000000findshlibs-0.5.0/.gitignore010066400017500001750000000000321314463037000140500ustar0000000000000000target Cargo.lock *.rs.bk findshlibs-0.5.0/.travis.yml010066400017500001750000000007251314471270200142020ustar0000000000000000sudo: false dist: trusty language: rust os: - linux - osx rust: - nightly - beta - stable addons: sources: - llvm-toolchain-trusty-3.9 # Provides clang-3.9 apt: packages: - binutils-dev - clang-3.9 # Required for bindgen - libcurl4-openssl-dev - libelf-dev - libdw-dev before_install: - source ./ci/before_install.sh env: matrix: - PROFILE="--release" - PROFILE="" script: - PROFILE="$PROFILE" ./ci/script.sh findshlibs-0.5.0/Cargo.toml.orig010064400017500001750000000011421347531253200147540ustar0000000000000000[package] authors = ["Nick Fitzgerald "] description = "Find the set of shared libraries loaded in the current process with a cross platform API" documentation = "https://docs.rs/findshlibs" keywords = ["dyld", "dylib", "shared", "library", "dl_iterate_phdr"] license = "Apache-2.0/MIT" name = "findshlibs" readme = "./README.md" repository = "https://github.com/gimli-rs/findshlibs" version = "0.5.0" [badges.coveralls] repository = "gimli-rs/findshlibs" [badges.travis-ci] repository = "gimli-rs/findshlibs" [dependencies] lazy_static = "1.0.0" libc = "0.2.55" [features] nightly = [] findshlibs-0.5.0/Cargo.toml0000644000000022140000000000000112170ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g. crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "findshlibs" version = "0.5.0" authors = ["Nick Fitzgerald "] description = "Find the set of shared libraries loaded in the current process with a cross platform API" documentation = "https://docs.rs/findshlibs" readme = "./README.md" keywords = ["dyld", "dylib", "shared", "library", "dl_iterate_phdr"] license = "Apache-2.0/MIT" repository = "https://github.com/gimli-rs/findshlibs" [dependencies.lazy_static] version = "1.0.0" [dependencies.libc] version = "0.2.55" [features] nightly = [] [badges.coveralls] repository = "gimli-rs/findshlibs" [badges.travis-ci] repository = "gimli-rs/findshlibs" findshlibs-0.5.0/Cargo.toml.orig0000644000000022150000000000000121570ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "findshlibs" version = "0.5.0" authors = ["Nick Fitzgerald "] description = "Find the set of shared libraries loaded in the current process with a cross platform API" documentation = "https://docs.rs/findshlibs" readme = "./README.md" keywords = ["dyld", "dylib", "shared", "library", "dl_iterate_phdr"] license = "Apache-2.0/MIT" repository = "https://github.com/gimli-rs/findshlibs" [dependencies.lazy_static] version = "1.0.0" [dependencies.libc] version = "0.2.55" [features] nightly = [] [badges.coveralls] repository = "gimli-rs/findshlibs" [badges.travis-ci] repository = "gimli-rs/findshlibs" findshlibs-0.5.0/LICENSE-APACHE010066400017500001750000000251371314463037000140210ustar0000000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. findshlibs-0.5.0/LICENSE-MIT010066400017500001750000000020571314463037000135250ustar0000000000000000Copyright (c) 2015 The Rust Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. findshlibs-0.5.0/README.md010066400017500001750000000030041326422704300133430ustar0000000000000000# `findshlibs` [![](http://meritbadge.herokuapp.com/findshlibs) ![](https://img.shields.io/crates/d/findshlibs.png)](https://crates.io/crates/findshlibs) [![Build Status](https://travis-ci.org/gimli-rs/findshlibs.png?branch=master)](https://travis-ci.org/gimli-rs/findshlibs) [![Coverage Status](https://coveralls.io/repos/github/gimli-rs/findshlibs/badge.svg?branch=master)](https://coveralls.io/github/gimli-rs/findshlibs?branch=master) Find the shared libraries loaded in the current process with a cross platform API. ## Documentation [📚 Documentation on docs.rs 📚](https://docs.rs/findshlibs) ## Example Here is an example program that prints out each shared library that is loaded in the process and the addresses where each of its segments are mapped into memory. ```rust extern crate findshlibs; use findshlibs::{Segment, SharedLibrary, TargetSharedLibrary}; fn main() { TargetSharedLibrary::each(|shlib| { println!("{}", shlib.name().to_string_lossy()); for seg in shlib.segments() { println!(" {}: segment {}", seg.actual_virtual_memory_address(shlib), seg.name().to_string_lossy()); } }); } ``` ## Supported OSes These are the OSes that `findshlibs` currently supports: * Linux * macOS If a platform is not supported then a fallback implementation is used that does nothing. To see if your platform does something at runtime the `TARGET_SUPPORTED` constant can be used. Is your OS missing here? Send us a pull request! findshlibs-0.5.0/ci/before_install.sh010077500017500001750000000010131314471270200160020ustar0000000000000000#!/usr/bin/env bash # We always want backtraces for everything. export RUST_BACKTRACE=1 case "$TRAVIS_OS_NAME" in "osx") brew update brew install llvm@3.9 export LIBCLANG_PATH=$(find /usr/local/Cellar/llvm -type f -name libclang.dylib | head -n 1) export LIBCLANG_PATH=$(dirname $LIBCLANG_PATH) ;; "linux") export LIBCLANG_PATH=/usr/lib/llvm-3.9/lib ;; *) echo "Error: unknown \$TRAVIS_OS_NAME: $TRAVIS_OS_NAME" exit 1 ;; esac findshlibs-0.5.0/ci/script.sh010077500017500001750000000003251326422676200143340ustar0000000000000000#!/usr/bin/env bash set -eux # We always want backtraces for everything. export RUST_BACKTRACE=1 cargo build --examples $PROFILE cargo test $PROFILE if [[ "$PROFILE" == "--release" ]]; then cargo bench fi findshlibs-0.5.0/coverage010077500017500001750000000013241314463037000136060ustar0000000000000000#!/usr/bin/env bash # # Usage: # ./coverage # # Run kcov on the tests, and merge the results. # # Environment variables: # TRAVIS_JOB_ID - id for coveralls, defaults to none # KCOV - path to kcov, defaults to 'kcov' [ -n "$TRAVIS_JOB_ID" ] && COVERALLS_ID="--coveralls-id=$TRAVIS_JOB_ID" [ -z "$KCOV" ] && KCOV=kcov # Rebuild tests with dead code included, and get a list of the filenames. export RUSTFLAGS="-C link-dead-code" TEST_FILES=$(cargo test 2>&1 >/dev/null | awk '/^ Running target\/debug\// { print $2 }') KCOV_OPTS="--verify --exclude-pattern=/.cargo" OUT_DIR=target/kcov for f in $TEST_FILES; do "$KCOV" $KCOV_OPTS "$OUT_DIR" $f done "$KCOV" --merge $KCOV_OPTS $COVERALLS_ID "$OUT_DIR" "$OUT_DIR" findshlibs-0.5.0/examples/list_segments.rs010064400017500001750000000006401347525031100171270ustar0000000000000000extern crate findshlibs; use findshlibs::{Segment, SharedLibrary, TargetSharedLibrary}; fn main() { TargetSharedLibrary::each(|shlib| { println!("{}", shlib.name().to_string_lossy()); for seg in shlib.segments() { println!( " {}: segment {}", seg.actual_virtual_memory_address(shlib), seg.name() ); } }); } findshlibs-0.5.0/src/lib.rs010064400017500001750000000255111347531253200137760ustar0000000000000000//! # `findshlibs` //! //! Find the set of shared libraries currently loaded in this process with a //! cross platform API. //! //! The API entry point is the `TargetSharedLibrary` type and its //! `SharedLibrary::each` trait method implementation. //! //! ## Example //! //! Here is an example program that prints out each shared library that is //! loaded in the process and the addresses where each of its segments are //! mapped into memory. //! //! ``` //! extern crate findshlibs; //! use findshlibs::{Segment, SharedLibrary, TargetSharedLibrary}; //! //! fn main() { //! TargetSharedLibrary::each(|shlib| { //! println!("{}", shlib.name().to_string_lossy()); //! //! for seg in shlib.segments() { //! println!(" {}: segment {}", //! seg.actual_virtual_memory_address(shlib), //! seg.name()); //! } //! }); //! } //! ``` //! //! ## Supported OSes //! //! These are the OSes that `findshlibs` currently supports: //! //! * Linux //! * macOS //! //! If a platform is not supported then a fallback implementation is used that //! does nothing. To see if your platform does something at runtime the //! `TARGET_SUPPORTED` constant can be used. //! //! Is your OS missing here? Send us a pull request! //! //! ## Addresses //! //! Shared libraries' addresses can be confusing. They are loaded somewhere in //! physical memory, but we generally don't care about physical memory //! addresses, because only the OS can see that address and in userspace we can //! only access memory through its virtual memory address. But even "virtual //! memory address" is ambiguous because it isn't clear whether this is the //! address before or after the loader maps the shared library into memory and //! performs relocation. //! //! To clarify between these different kinds of addresses, we borrow some //! terminology from [LUL][]: //! //! > * **SVMA** ("Stated Virtual Memory Address"): this is an address of a //! > symbol (etc) as it is stated in the symbol table, or other //! > metadata, of an object. Such values are typically small and //! > start from zero or thereabouts, unless the object has been //! > prelinked. //! > //! > * **AVMA** ("Actual Virtual Memory Address"): this is the address of a //! > symbol (etc) in a running process, that is, once the associated //! > object has been mapped into a process. Such values are typically //! > much larger than SVMAs, since objects can get mapped arbitrarily //! > far along the address space. //! > //! > * **"Bias"**: the difference between AVMA and SVMA for a given symbol //! > (specifically, AVMA - SVMA). The bias is always an integral //! > number of pages. Once we know the bias for a given object's //! > text section (for example), we can compute the AVMAs of all of //! > its text symbols by adding the bias to their SVMAs. //! //! [LUL]: http://searchfox.org/mozilla-central/rev/13148faaa91a1c823a7d68563d9995480e714979/tools/profiler/lul/LulMain.h#17-51 #![deny(missing_docs)] #[cfg(target_os = "macos")] #[macro_use] extern crate lazy_static; #[cfg(any(target_os = "linux", target_os = "macos"))] extern crate libc; #[cfg(target_os = "macos")] pub mod macos; #[cfg(target_os = "linux")] pub mod linux; use std::ffi::OsStr; use std::fmt::{self, Debug}; use std::ptr; pub mod unsupported; #[cfg(target_os = "linux")] use linux as native_mod; #[cfg(target_os = "macos")] use macos as native_mod; #[cfg(not(any(target_os = "macos", target_os = "linux")))] use unsupported as native_mod; /// The [`SharedLibrary` trait](./trait.SharedLibrary.html) /// implementation for the target operating system. pub type TargetSharedLibrary<'a> = native_mod::SharedLibrary<'a>; /// An indicator if this platform is supported. pub const TARGET_SUPPORTED: bool = cfg!(any(target_os = "macos", target_os = "linux")); macro_rules! simple_newtypes { ( $( $(#[$attr:meta])* type $name:ident = $oldty:ty where default = $default:expr , display = $format:expr ; )* ) => { $( $(#[$attr])* #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct $name(pub $oldty); impl Default for $name { #[inline] fn default() -> Self { $name( $default ) } } impl From<$oldty> for $name { fn from(x: $oldty) -> $name { $name(x) } } impl From<$name> for $oldty { fn from($name(x): $name) -> $oldty { x } } impl fmt::Display for $name { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, $format, self.0) } } )* } } simple_newtypes! { /// Stated virtual memory address. /// /// See the module documentation for details. type Svma = *const u8 where default = ptr::null(), display = "{:p}"; /// Actual virtual memory address. /// /// See the module documentation for details. type Avma = *const u8 where default = ptr::null(), display = "{:p}"; /// Virtual memory bias. /// /// See the module documentation for details. type Bias = isize where default = 0, display = "{:#x}"; } /// A mapped segment in a shared library. #[allow(clippy::len_without_is_empty)] pub trait Segment: Sized + Debug { /// The associated shared library type for this segment. type SharedLibrary: SharedLibrary; /// Get this segment's name. fn name(&self) -> &str; /// Returns `true` if this is a code segment. #[inline] fn is_code(&self) -> bool { false } /// Get this segment's stated virtual address of this segment. /// /// This is the virtual memory address without the bias applied. See the /// module documentation for details. fn stated_virtual_memory_address(&self) -> Svma; /// Get the length of this segment in memory (in bytes). fn len(&self) -> usize; // Provided methods. /// Get this segment's actual virtual memory address. /// /// This is the virtual memory address with the bias applied. See the module /// documentation for details. #[inline] fn actual_virtual_memory_address(&self, shlib: &Self::SharedLibrary) -> Avma { let svma = self.stated_virtual_memory_address(); let bias = shlib.virtual_memory_bias(); Avma(unsafe { svma.0.offset(bias.0) }) } /// Does this segment contain the given address? #[inline] fn contains_svma(&self, address: Svma) -> bool { let start = self.stated_virtual_memory_address().0 as usize; let end = start + self.len(); let address = address.0 as usize; start <= address && address < end } /// Does this segment contain the given address? #[inline] fn contains_avma(&self, shlib: &Self::SharedLibrary, address: Avma) -> bool { let start = self.actual_virtual_memory_address(shlib).0 as usize; let end = start + self.len(); let address = address.0 as usize; start <= address && address < end } } /// Represents an ID for a shared library. #[derive(PartialEq, Eq, Hash)] pub enum SharedLibraryId { /// A UUID (used on mac) Uuid([u8; 16]), /// A GNU build ID GnuBuildId(Vec), } impl SharedLibraryId { /// Returns the raw bytes of the shared library ID. pub fn as_bytes(&self) -> &[u8] { match *self { SharedLibraryId::Uuid(ref bytes) => &*bytes, SharedLibraryId::GnuBuildId(ref bytes) => &bytes, } } } impl fmt::Display for SharedLibraryId { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let (bytes, is_uuid): (&[u8], _) = match *self { SharedLibraryId::Uuid(ref bytes) => (&*bytes, true), SharedLibraryId::GnuBuildId(ref bytes) => (&bytes, false), }; for (idx, byte) in bytes.iter().enumerate() { if is_uuid && (idx == 4 || idx == 6 || idx == 8 || idx == 10) { try!(write!(f, "-")); } try!(write!(f, "{:02x}", byte)); } Ok(()) } } impl fmt::Debug for SharedLibraryId { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { SharedLibraryId::Uuid(..) => { write!(f, "Uuid(\"{}\")", self)?; } SharedLibraryId::GnuBuildId(..) => { write!(f, "GnuBuildId(\"{}\")", self)?; } } Ok(()) } } /// A trait representing a shared library that is loaded in this process. pub trait SharedLibrary: Sized + Debug { /// The associated segment type for this shared library. type Segment: Segment; /// An iterator over a shared library's segments. type SegmentIter: Debug + Iterator; /// Get the name of this shared library. fn name(&self) -> &OsStr; /// Get the debug-id of this shared library if available. fn id(&self) -> Option; /// Iterate over this shared library's segments. fn segments(&self) -> Self::SegmentIter; /// Get the bias of this shared library. /// /// See the module documentation for details. fn virtual_memory_bias(&self) -> Bias; /// Given an AVMA within this shared library, convert it back to an SVMA by /// removing this shared library's bias. #[inline] fn avma_to_svma(&self, address: Avma) -> Svma { let bias = self.virtual_memory_bias(); let reverse_bias = -bias.0; Svma(unsafe { address.0.offset(reverse_bias) }) } /// Find all shared libraries in this process and invoke `f` with each one. fn each(f: F) where F: FnMut(&Self) -> C, C: Into; } /// Control whether iteration over shared libraries should continue or stop. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum IterationControl { /// Stop iteration. Break, /// Continue iteration. Continue, } impl From<()> for IterationControl { #[inline] fn from(_: ()) -> Self { IterationControl::Continue } } #[cfg(test)] mod tests { use super::*; #[test] fn panic_in_each() { use std::panic; match panic::catch_unwind(|| { TargetSharedLibrary::each(|_| panic!("uh oh")); }) { Ok(()) => panic!("Expected a panic, but didn't get one"), Err(any) => { assert!( any.is::<&'static str>(), "panic value should be a &'static str" ); assert_eq!(*any.downcast_ref::<&'static str>().unwrap(), "uh oh"); } } } } findshlibs-0.5.0/src/linux/mod.rs010064400017500001750000000307001347531253200151420ustar0000000000000000//! Linux-specific implementation of the `SharedLibrary` trait. use super::Segment as SegmentTrait; use super::SharedLibrary as SharedLibraryTrait; use super::{Bias, IterationControl, SharedLibraryId, Svma}; use std::any::Any; use std::borrow::Cow; use std::env::current_exe; use std::ffi::{CStr, CString, OsStr}; use std::fmt; use std::isize; use std::marker::PhantomData; use std::mem; use std::os::unix::ffi::OsStrExt; use std::os::unix::ffi::OsStringExt; use std::panic; use std::slice; use libc; #[cfg(target_pointer_width = "32")] type Phdr = libc::Elf32_Phdr; #[cfg(target_pointer_width = "64")] type Phdr = libc::Elf64_Phdr; const NT_GNU_BUILD_ID: u32 = 3; struct Nhdr32 { pub n_namesz: libc::Elf32_Word, pub n_descsz: libc::Elf32_Word, pub n_type: libc::Elf32_Word, } /// A mapped segment in an ELF file. #[derive(Debug)] pub struct Segment<'a> { phdr: *const Phdr, shlib: PhantomData<&'a ::linux::SharedLibrary<'a>>, } impl<'a> SegmentTrait for Segment<'a> { type SharedLibrary = ::linux::SharedLibrary<'a>; fn name(&self) -> &str { unsafe { match self.phdr.as_ref().unwrap().p_type { libc::PT_NULL => "NULL", libc::PT_LOAD => "LOAD", libc::PT_DYNAMIC => "DYNAMIC", libc::PT_INTERP => "INTERP", libc::PT_NOTE => "NOTE", libc::PT_SHLIB => "SHLI", libc::PT_PHDR => "PHDR", libc::PT_TLS => "TLS", libc::PT_NUM => "NUM", libc::PT_LOOS => "LOOS", libc::PT_GNU_EH_FRAME => "GNU_EH_FRAME", libc::PT_GNU_STACK => "GNU_STACK", libc::PT_GNU_RELRO => "GNU_RELRO", _ => "(unknown segment type)", } } } #[inline] fn is_code(&self) -> bool { unsafe { let hdr = self.phdr.as_ref().unwrap(); match hdr.p_type { // 0x1 is PT_X for executable libc::PT_LOAD => (hdr.p_flags & 0x1) != 0, _ => false, } } } #[inline] fn stated_virtual_memory_address(&self) -> Svma { Svma(unsafe { (*self.phdr).p_vaddr as _ }) } #[inline] fn len(&self) -> usize { unsafe { (*self.phdr).p_memsz as _ } } } /// An iterator of mapped segments in a shared library. pub struct SegmentIter<'a> { inner: ::std::slice::Iter<'a, Phdr>, } impl<'a> Iterator for SegmentIter<'a> { type Item = Segment<'a>; #[inline] fn next(&mut self) -> Option { self.inner.next().map(|phdr| Segment { phdr: phdr, shlib: PhantomData, }) } } impl<'a> fmt::Debug for SegmentIter<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let ref phdr = self.inner.as_slice()[0]; f.debug_struct("SegmentIter") .field("phdr", &DebugPhdr(phdr)) .finish() } } /// A shared library on Linux. pub struct SharedLibrary<'a> { size: usize, addr: *const u8, name: Cow<'a, CStr>, headers: &'a [Phdr], } struct IterState { f: F, panic: Option>, idx: usize, } const CONTINUE: libc::c_int = 0; const BREAK: libc::c_int = 1; impl<'a> SharedLibrary<'a> { unsafe fn new(info: &'a libc::dl_phdr_info, size: usize, is_first_lib: bool) -> Self { // try to get the name from the dl_phdr_info. If that fails there are two // cases we can and need to deal with. The first one is if we are the first // loaded library in which case the name is the executable which we can // discover via env::current_exe (reads the proc/self symlink). // // Otherwise if we have a no name we might be a dylib that was loaded with // dlopen in which case we can use dladdr to recover the name. let mut name = Cow::Borrowed(if info.dlpi_name.is_null() { CStr::from_bytes_with_nul_unchecked(b"\0") } else { CStr::from_ptr(info.dlpi_name) }); if name.to_bytes().is_empty() { if is_first_lib { if let Ok(exe) = current_exe() { name = Cow::Owned(CString::from_vec_unchecked(exe.into_os_string().into_vec())); } } else { let mut dlinfo: libc::Dl_info = mem::zeroed(); if libc::dladdr(info.dlpi_addr as *const libc::c_void, &mut dlinfo) != 0 { name = Cow::Owned(CString::from(CStr::from_ptr(dlinfo.dli_fname))); } } } SharedLibrary { size: size, addr: info.dlpi_addr as usize as *const _, name, headers: slice::from_raw_parts(info.dlpi_phdr, info.dlpi_phnum as usize), } } unsafe extern "C" fn callback( info: *mut libc::dl_phdr_info, size: usize, state: *mut libc::c_void, ) -> libc::c_int where F: FnMut(&Self) -> C, C: Into, { let state = &mut *(state as *mut IterState); state.idx += 1; match panic::catch_unwind(panic::AssertUnwindSafe(|| { let info = info.as_ref().unwrap(); let shlib = SharedLibrary::new(info, size, state.idx == 1); (state.f)(&shlib).into() })) { Ok(IterationControl::Continue) => CONTINUE, Ok(IterationControl::Break) => BREAK, Err(panicked) => { state.panic = Some(panicked); BREAK } } } } impl<'a> SharedLibraryTrait for SharedLibrary<'a> { type Segment = Segment<'a>; type SegmentIter = SegmentIter<'a>; #[inline] fn name(&self) -> &OsStr { OsStr::from_bytes(self.name.to_bytes()) } fn id(&self) -> Option { fn align(alignment: usize, offset: &mut usize) { let diff = *offset % alignment; if diff != 0 { *offset += alignment - diff; } } unsafe { for segment in self.segments() { let phdr = segment.phdr.as_ref().unwrap(); if phdr.p_type != libc::PT_NOTE { continue; } let mut alignment = phdr.p_align as usize; // same logic as in gimli which took it from readelf if alignment < 4 { alignment = 4; } else if alignment != 4 && alignment != 8 { continue; } let mut offset = phdr.p_offset as usize; let end = offset + phdr.p_filesz as usize; while offset < end { // we always use an nhdr32 here as 64bit notes have not // been observed in practice. let nhdr = &*((self.addr as usize + offset) as *const Nhdr32); offset += mem::size_of_val(nhdr); offset += nhdr.n_namesz as usize; align(alignment, &mut offset); let value = slice::from_raw_parts(self.addr.add(offset), nhdr.n_descsz as usize); offset += nhdr.n_descsz as usize; align(alignment, &mut offset); if nhdr.n_type as u32 == NT_GNU_BUILD_ID { return Some(SharedLibraryId::GnuBuildId(value.to_vec())); } } } } None } #[inline] fn segments(&self) -> Self::SegmentIter { SegmentIter { inner: self.headers.iter(), } } #[inline] fn virtual_memory_bias(&self) -> Bias { assert!((self.addr as usize) < (isize::MAX as usize)); Bias(self.addr as usize as isize) } #[inline] fn each(f: F) where F: FnMut(&Self) -> C, C: Into, { let mut state = IterState { f: f, panic: None, idx: 0, }; unsafe { libc::dl_iterate_phdr(Some(Self::callback::), &mut state as *mut _ as *mut _); } if let Some(panic) = state.panic { panic::resume_unwind(panic); } } } impl<'a> fmt::Debug for SharedLibrary<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "SharedLibrary {{ size: {:?}, addr: {:?}, ", self.size, self.addr )?; write!(f, "name: {:?}, headers: [", self.name)?; // Debug does not usually have a trailing comma in the list, // last element must be formatted separately. let l = self.headers.len(); self.headers[..(l - 1)] .into_iter() .map(|phdr| write!(f, "{:?}, ", &DebugPhdr(phdr))) .collect::()?; write!(f, "{:?}", &DebugPhdr(&self.headers[l - 1]))?; write!(f, "] }}") } } struct DebugPhdr<'a>(&'a Phdr); impl<'a> fmt::Debug for DebugPhdr<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let phdr = self.0; // The layout is different for 32-bit vs 64-bit, // but since the fields are the same, it shouldn't matter much. f.debug_struct("Phdr") .field("p_type", &phdr.p_type) .field("p_flags", &phdr.p_flags) .field("p_offset", &phdr.p_offset) .field("p_vaddr", &phdr.p_vaddr) .field("p_paddr", &phdr.p_paddr) .field("p_filesz", &phdr.p_filesz) .field("p_memsz", &phdr.p_memsz) .field("p_align", &phdr.p_align) .finish() } } #[cfg(test)] mod tests { use super::super::{IterationControl, Segment, SharedLibrary}; use linux; #[test] fn have_libc() { let mut found_libc = false; linux::SharedLibrary::each(|info| { found_libc |= info .name .to_bytes() .split(|c| *c == b'.' || *c == b'/') .find(|s| s == b"libc") .is_some(); }); assert!(found_libc); } #[test] fn can_break() { let mut first_count = 0; linux::SharedLibrary::each(|_| { first_count += 1; }); assert!(first_count > 2); let mut second_count = 0; linux::SharedLibrary::each(|_| { second_count += 1; if second_count == first_count - 1 { IterationControl::Break } else { IterationControl::Continue } }); assert_eq!(second_count, first_count - 1); } #[test] fn get_name() { use std::ffi::OsStr; let mut names = vec![]; linux::SharedLibrary::each(|shlib| { println!("{:?}", shlib); let name = shlib.name(); if name != OsStr::new("") { names.push(name.to_str().unwrap().to_string()); } }); assert!(names[0].contains("/findshlibs")); assert!(names.iter().any(|x| x.contains("libc.so"))); } #[test] fn get_id() { use std::path::Path; use std::process::Command; linux::SharedLibrary::each(|shlib| { let name = shlib.name(); let id = shlib.id(); if id.is_none() { println!("no id found for {:?}", name); return; } let path: &Path = name.as_ref(); if !path.is_absolute() { return; } let gnu_build_id = id.unwrap().to_string(); let readelf = Command::new("readelf") .arg("-n") .arg(path) .output() .unwrap(); for line in String::from_utf8(readelf.stdout).unwrap().lines() { if let Some(index) = line.find("Build ID: ") { let readelf_build_id = line[index + 9..].trim(); assert_eq!(readelf_build_id, gnu_build_id); } } println!("{}: {}", path.display(), gnu_build_id); }); } #[test] fn have_load_segment() { linux::SharedLibrary::each(|shlib| { println!("shlib = {:?}", shlib.name()); let mut found_load = false; for seg in shlib.segments() { println!(" segment = {:?}", seg.name()); found_load |= seg.name() == "LOAD"; } assert!(found_load); }); } } findshlibs-0.5.0/src/macos/bindings.h010066400017500001750000000000311314463037000157160ustar0000000000000000#include findshlibs-0.5.0/src/macos/bindings.rs010075500017500001750000000002601347525031100161200ustar0000000000000000#![allow(non_snake_case)] #![allow(non_camel_case_types)] #![allow(dead_code)] #![allow(clippy::unreadable_literal)] include!(concat!(env!("OUT_DIR"), "/macos_bindings.rs")); findshlibs-0.5.0/src/macos/mod.rs010064400017500001750000000260251347531253200151120ustar0000000000000000//! The MacOS implementation of the [SharedLibrary //! trait](../trait.SharedLibrary.html). #![allow(clippy::cast_ptr_alignment)] use super::Segment as SegmentTrait; use super::SharedLibrary as SharedLibraryTrait; use super::{Bias, IterationControl, SharedLibraryId, Svma}; use std::ffi::{CStr, OsStr}; use std::fmt; use std::marker::PhantomData; use std::os::unix::ffi::OsStrExt; use std::sync::Mutex; use std::usize; use libc; const LC_UUID: u32 = 27; #[repr(C)] #[derive(Debug, Copy, Clone)] struct uuid_command { cmd: u32, cmdsize: u32, uuid: [u8; 16usize], } lazy_static! { /// A lock protecting dyld FFI calls. /// /// MacOS does not provide an atomic way to iterate shared libraries, so /// *you* must take this lock whenever dynamically adding or removing shared /// libraries to ensure that there are no races with iterating shared /// libraries. pub static ref DYLD_LOCK: Mutex<()> = Mutex::new(()); } /// A Mach-O segment. pub enum Segment<'a> { /// A 32-bit Mach-O segment. Segment32(&'a libc::segment_command), /// A 64-bit Mach-O segment. Segment64(&'a libc::segment_command_64), } impl<'a> fmt::Debug for Segment<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Segment") .field("name", &self.name()) .field("is_code", &self.is_code()) .finish() } } impl<'a> SegmentTrait for Segment<'a> { type SharedLibrary = ::macos::SharedLibrary<'a>; #[inline] fn name(&self) -> &str { let cstr = match *self { Segment::Segment32(seg) => unsafe { CStr::from_ptr(seg.segname.as_ptr()) }, Segment::Segment64(seg) => unsafe { CStr::from_ptr(seg.segname.as_ptr()) }, }; cstr.to_str().unwrap_or("(invalid segment name)") } #[inline] fn is_code(&self) -> bool { self.name().as_bytes() == b"__TEXT" } #[inline] fn stated_virtual_memory_address(&self) -> Svma { match *self { Segment::Segment32(seg) => Svma(seg.vmaddr as usize as *const u8), Segment::Segment64(seg) => { assert!(seg.vmaddr <= (usize::MAX as u64)); Svma(seg.vmaddr as usize as *const u8) } } } #[inline] fn len(&self) -> usize { match *self { Segment::Segment32(seg) => seg.vmsize as usize, Segment::Segment64(seg) => { assert!(seg.vmsize <= (usize::MAX as u64)); seg.vmsize as usize } } } } /// An iterator over Mach-O segments. #[derive(Debug)] pub struct SegmentIter<'a> { phantom: PhantomData<&'a SharedLibrary<'a>>, commands: *const libc::load_command, num_commands: usize, } impl<'a> SegmentIter<'a> { fn find_uuid(&self) -> Option<[u8; 16]> { let mut num_commands = self.num_commands; let mut commands = self.commands; while num_commands > 0 { num_commands -= 1; let this_command = unsafe { commands.as_ref().unwrap() }; let command_size = this_command.cmdsize as isize; if let LC_UUID = this_command.cmd { let uuid_cmd = commands as *const uuid_command; return Some(unsafe { (*uuid_cmd).uuid }); } commands = unsafe { (commands as *const u8).offset(command_size) as *const _ }; } None } } impl<'a> Iterator for SegmentIter<'a> { type Item = Segment<'a>; fn next(&mut self) -> Option { while self.num_commands > 0 { self.num_commands -= 1; let this_command = unsafe { self.commands.as_ref().unwrap() }; let command_size = this_command.cmdsize as isize; match this_command.cmd { libc::LC_SEGMENT => { let segment = self.commands as *const libc::segment_command; let segment = unsafe { segment.as_ref().unwrap() }; self.commands = unsafe { (self.commands as *const u8).offset(command_size) as *const _ }; return Some(Segment::Segment32(segment)); } libc::LC_SEGMENT_64 => { let segment = self.commands as *const libc::segment_command_64; let segment = unsafe { segment.as_ref().unwrap() }; self.commands = unsafe { (self.commands as *const u8).offset(command_size) as *const _ }; return Some(Segment::Segment64(segment)); } _ => { // Some other kind of load command; skip to the next one. self.commands = unsafe { (self.commands as *const u8).offset(command_size) as *const _ }; continue; } } } None } } #[derive(Debug)] enum MachType { Mach32, Mach64, } impl MachType { unsafe fn from_header_ptr(header: *const libc::mach_header) -> Option { header.as_ref().and_then(|header| match header.magic { libc::MH_MAGIC => Some(MachType::Mach32), libc::MH_MAGIC_64 => Some(MachType::Mach64), _ => None, }) } } enum MachHeader<'a> { Header32(&'a libc::mach_header), Header64(&'a libc::mach_header_64), } impl<'a> MachHeader<'a> { unsafe fn from_header_ptr(header: *const libc::mach_header) -> Option> { MachType::from_header_ptr(header).and_then(|ty| match ty { MachType::Mach32 => header.as_ref().map(MachHeader::Header32), MachType::Mach64 => (header as *const libc::mach_header_64) .as_ref() .map(MachHeader::Header64), }) } } /// The MacOS implementation of the [SharedLibrary /// trait](../trait.SharedLibrary.html). /// /// This wraps the `_dyld_image_count` and /// `_dyld_get_image_{header,vmaddr_slide,name}` system APIs from the /// `` header. pub struct SharedLibrary<'a> { header: MachHeader<'a>, slide: isize, name: &'a CStr, } impl<'a> fmt::Debug for SharedLibrary<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("SharedLibrary") .field("name", &self.name()) .field("id", &self.id()) .finish() } } impl<'a> SharedLibrary<'a> { fn new(header: MachHeader<'a>, slide: isize, name: &'a CStr) -> Self { SharedLibrary { header: header, slide: slide, name: name, } } } impl<'a> SharedLibraryTrait for SharedLibrary<'a> { type Segment = Segment<'a>; type SegmentIter = SegmentIter<'a>; #[inline] fn name(&self) -> &OsStr { OsStr::from_bytes(self.name.to_bytes()) } fn id(&self) -> Option { self.segments().find_uuid().map(SharedLibraryId::Uuid) } fn segments(&self) -> Self::SegmentIter { match self.header { MachHeader::Header32(header) => { let num_commands = header.ncmds; let header = header as *const libc::mach_header; let commands = unsafe { header.offset(1) as *const libc::load_command }; SegmentIter { phantom: PhantomData, commands: commands, num_commands: num_commands as usize, } } MachHeader::Header64(header) => { let num_commands = header.ncmds; let header = header as *const libc::mach_header_64; let commands = unsafe { header.offset(1) as *const libc::load_command }; SegmentIter { phantom: PhantomData, commands: commands, num_commands: num_commands as usize, } } } } #[inline] fn virtual_memory_bias(&self) -> Bias { Bias(self.slide) } fn each(mut f: F) where F: FnMut(&Self) -> C, C: Into, { // Make sure we have exclusive access to dyld so that (hopefully) no one // else adds or removes shared libraries while we are iterating them. let _dyld_lock = DYLD_LOCK.lock(); let count = unsafe { libc::_dyld_image_count() }; for image_idx in 0..count { let (header, slide, name) = unsafe { ( libc::_dyld_get_image_header(image_idx), libc::_dyld_get_image_vmaddr_slide(image_idx), libc::_dyld_get_image_name(image_idx), ) }; if let Some(header) = unsafe { MachHeader::from_header_ptr(header) } { assert!( slide != 0, "If we have a header pointer, slide should be valid" ); assert!( !name.is_null(), "If we have a header pointer, name should be valid" ); let name = unsafe { CStr::from_ptr(name) }; let shlib = SharedLibrary::new(header, slide, name); match f(&shlib).into() { IterationControl::Break => break, IterationControl::Continue => continue, } } } } } #[cfg(test)] mod tests { use super::super::{IterationControl, Segment, SharedLibrary}; use macos; #[test] fn have_libdyld() { let mut found_dyld = false; macos::SharedLibrary::each(|shlib| { found_dyld |= shlib .name .to_bytes() .split(|c| *c == b'.' || *c == b'/') .any(|s| s == b"libdyld"); }); assert!(found_dyld); } #[test] fn can_break() { let mut first_count = 0; macos::SharedLibrary::each(|_| { first_count += 1; }); assert!(first_count > 2); let mut second_count = 0; macos::SharedLibrary::each(|_| { second_count += 1; if second_count == first_count - 1 { IterationControl::Break } else { IterationControl::Continue } }); assert_eq!(second_count, first_count - 1); } #[test] fn get_name() { macos::SharedLibrary::each(|shlib| { let _ = shlib.name(); }); } #[test] fn get_id() { macos::SharedLibrary::each(|shlib| { assert!(shlib.id().is_some()); }); } #[test] fn have_text_or_pagezero() { macos::SharedLibrary::each(|shlib| { println!("shlib = {:?}", shlib.name()); let mut found_text_or_pagezero = false; for seg in shlib.segments() { println!(" segment = {:?}", seg.name()); found_text_or_pagezero |= seg.name() == "__TEXT"; found_text_or_pagezero |= seg.name() == "__PAGEZERO"; } assert!(found_text_or_pagezero); }); } } findshlibs-0.5.0/src/unsupported.rs010064400017500001750000000035051347525031100156130ustar0000000000000000//! The fallback implementation of the [SharedLibrary //! trait](../trait.SharedLibrary.html) that does nothing. use super::Segment as SegmentTrait; use super::SharedLibrary as SharedLibraryTrait; use super::{Bias, IterationControl, SharedLibraryId, Svma}; use std::ffi::OsStr; use std::marker::PhantomData; use std::usize; /// An unsupported segment #[derive(Debug)] pub struct Segment<'a> { phantom: PhantomData<&'a SharedLibrary<'a>>, } impl<'a> SegmentTrait for Segment<'a> { type SharedLibrary = ::unsupported::SharedLibrary<'a>; #[inline] fn name(&self) -> &str { unreachable!() } #[inline] fn stated_virtual_memory_address(&self) -> Svma { unreachable!() } #[inline] fn len(&self) -> usize { unreachable!() } } /// An iterator over Mach-O segments. #[derive(Debug)] pub struct SegmentIter<'a> { phantom: PhantomData<&'a SharedLibrary<'a>>, } impl<'a> Iterator for SegmentIter<'a> { type Item = Segment<'a>; fn next(&mut self) -> Option { None } } /// The fallback implementation of the [SharedLibrary /// trait](../trait.SharedLibrary.html). #[derive(Debug)] pub struct SharedLibrary<'a> { phantom: PhantomData<&'a SharedLibrary<'a>>, } impl<'a> SharedLibraryTrait for SharedLibrary<'a> { type Segment = Segment<'a>; type SegmentIter = SegmentIter<'a>; #[inline] fn name(&self) -> &OsStr { unreachable!() } fn id(&self) -> Option { unreachable!() } fn segments(&self) -> Self::SegmentIter { SegmentIter { phantom: PhantomData, } } #[inline] fn virtual_memory_bias(&self) -> Bias { unreachable!() } fn each(_f: F) where F: FnMut(&Self) -> C, C: Into, { } } findshlibs-0.5.0/.cargo_vcs_info.json0000644000000001120000000000000132140ustar00{ "git": { "sha1": "c39efb3a846d8e84d99b2571b93afe3555fd5639" } }