findshlibs-0.10.2/.cargo_vcs_info.json0000644000000001120000000000000132320ustar { "git": { "sha1": "83dbb5de60d46cecc368966171ec58e6f4f4277d" } } findshlibs-0.10.2/.coveralls.yml000064400000000000000000000000000000000000000145670ustar 00000000000000findshlibs-0.10.2/.github/dependabot.yml000064400000000000000000000001770000000000000162030ustar 00000000000000version: 2 updates: - package-ecosystem: cargo directory: "/" schedule: interval: daily open-pull-requests-limit: 10 findshlibs-0.10.2/.github/workflows/main.yml000064400000000000000000000017110000000000000170520ustar 00000000000000name: CI on: push: branches: [ master ] pull_request: branches: [ master ] jobs: test: strategy: matrix: os: ["ubuntu-latest", "macos-latest", "windows-latest"] rust: ["stable", "beta", "nightly", "1.34.0"] runs-on: ${{matrix.os}} steps: - uses: actions/checkout@v2 with: submodules: true - name: Install rust run: | rustup install ${{matrix.rust}} rustup default ${{matrix.rust}} - name: Test debug run: cargo test --verbose - name: Test release run: cargo test --verbose --release rustfmt: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Install rust run: | rustup install stable rustup default stable rustup component add rustfmt - run: cargo fmt --all -- --check doc: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - run: cargo doc findshlibs-0.10.2/.gitignore000064400000000000000000000000320000000000000137710ustar 00000000000000target Cargo.lock *.rs.bk findshlibs-0.10.2/Cargo.lock0000644000000027140000000000000112170ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "cc" version = "1.0.72" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22a9137b95ea06864e018375b72adfb7db6e6f68cfc8df5a04d00288050485ee" [[package]] name = "findshlibs" version = "0.10.2" dependencies = [ "cc", "lazy_static", "libc", "winapi", ] [[package]] name = "lazy_static" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" version = "0.2.107" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fbe5e23404da5b4f555ef85ebed98fb4083e55a00c317800bc2a50ede9f3d219" [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" findshlibs-0.10.2/Cargo.toml0000644000000023460000000000000112430ustar # 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] edition = "2018" name = "findshlibs" version = "0.10.2" 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 = "MIT OR Apache-2.0" repository = "https://github.com/gimli-rs/findshlibs" [dependencies.libc] version = "0.2.104" [build-dependencies.cc] version = "1.0.67" [target."cfg(any(target_os = \"macos\", target_os = \"ios\"))".dependencies.lazy_static] version = "1.4" [target."cfg(target_os = \"windows\")".dependencies.winapi] version = "0.3.9" features = ["psapi", "memoryapi", "libloaderapi", "processthreadsapi"] findshlibs-0.10.2/Cargo.toml.orig0000644000000014610000000000000121770ustar [package] name = "findshlibs" version = "0.10.2" description = "Find the set of shared libraries loaded in the current process with a cross platform API" documentation = "https://docs.rs/findshlibs" edition = "2018" keywords = ["dyld", "dylib", "shared", "library", "dl_iterate_phdr"] license = "MIT OR Apache-2.0" readme = "./README.md" repository = "https://github.com/gimli-rs/findshlibs" [dependencies] libc = "0.2.104" [build-dependencies] # Only needed for Android, but cannot be target dependent # https://github.com/rust-lang/cargo/issues/4932 cc = "1.0.67" [target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies] lazy_static = "1.4" [target.'cfg(target_os = "windows")'.dependencies] winapi = { version = "0.3.9", features = ["psapi", "memoryapi", "libloaderapi", "processthreadsapi"] } findshlibs-0.10.2/Cargo.toml.orig000064400000000000000000000014610000000000000146770ustar 00000000000000[package] name = "findshlibs" version = "0.10.2" description = "Find the set of shared libraries loaded in the current process with a cross platform API" documentation = "https://docs.rs/findshlibs" edition = "2018" keywords = ["dyld", "dylib", "shared", "library", "dl_iterate_phdr"] license = "MIT OR Apache-2.0" readme = "./README.md" repository = "https://github.com/gimli-rs/findshlibs" [dependencies] libc = "0.2.104" [build-dependencies] # Only needed for Android, but cannot be target dependent # https://github.com/rust-lang/cargo/issues/4932 cc = "1.0.67" [target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies] lazy_static = "1.4" [target.'cfg(target_os = "windows")'.dependencies] winapi = { version = "0.3.9", features = ["psapi", "memoryapi", "libloaderapi", "processthreadsapi"] } findshlibs-0.10.2/LICENSE-APACHE000064400000000000000000000251370000000000000137420ustar 00000000000000 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.10.2/LICENSE-MIT000064400000000000000000000020570000000000000134460ustar 00000000000000Copyright (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.10.2/README.md000064400000000000000000000026320000000000000132700ustar 00000000000000# `findshlibs` [![](https://img.shields.io/crates/v/findshlibs.svg)](https://crates.io/crates/findshlibs) [![](https://docs.rs/findshlibs/badge.svg)](https://docs.rs/findshlibs) [![Build Status](https://github.com/gimli-rs/findshlibs/workflows/CI/badge.svg)](https://github.com/gimli-rs/findshlibs/actions) 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 * Windows * Android * iOS 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.10.2/build.rs000064400000000000000000000017660000000000000134650ustar 00000000000000extern crate cc; use std::env; fn main() { match env::var("CARGO_CFG_TARGET_OS").unwrap_or_default().as_str() { "android" => build_android(), _ => {} } } fn build_android() { let expansion = match cc::Build::new().file("src/android-api.c").try_expand() { Ok(result) => result, Err(e) => { println!("cargo:warning=failed to run C compiler: {}", e); return; } }; let expansion = match std::str::from_utf8(&expansion) { Ok(s) => s, Err(_) => return, }; let marker = "APIVERSION"; let i = expansion.find(marker).unwrap_or_default(); let version = expansion[i + marker.len() + 1..] .split_whitespace() .next() .unwrap_or(""); let version = version.parse::().unwrap_or_else(|_| { println!("cargo:warning=failed to get android api version."); 0 }); if version >= 21 { println!("cargo:rustc-cfg=feature=\"dl_iterate_phdr\""); } } findshlibs-0.10.2/examples/list_segments.rs000064400000000000000000000006400000000000000170520ustar 00000000000000extern 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.10.2/src/lib.rs000064400000000000000000000365160000000000000137240ustar 00000000000000//! # `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 //! * Windows //! * Android //! * iOS //! //! 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]: https://searchfox.org/mozilla-central/rev/13148faaa91a1c823a7d68563d9995480e714979/tools/profiler/lul/LulMain.h#17-51 //! //! ## Names and IDs //! //! `findshlibs` also gives access to module names and IDs. Since this is also //! not consistent across operating systems the following general rules apply: //! //! > * `id` refers to the ID of the object file itself. This is generally //! > available on all platforms however it might still not be compiled into //! > the binary in all case. For instance on Linux the `gnu.build-id` note //! > needs to be compiled in (which Rust does automatically). //! > * `debug_id` refers to the ID of the debug file. This only plays a role //! > on Windows where the executable and the debug file (PDB) have a different //! > ID. //! > * `name` is the name of the executable. On most operating systems (and //! > all systems implemented currently) this is not just the name but in fact //! > the entire path to the executable. //! > * `debug_name` is the name of the debug file if known. This is again //! > the case on windows where this will be the path to the PDB file. #![deny(missing_docs)] #[cfg(any(target_os = "macos", target_os = "ios"))] pub mod macos; #[cfg(any( target_os = "linux", all(target_os = "android", feature = "dl_iterate_phdr") ))] pub mod linux; #[cfg(target_os = "windows")] pub mod windows; use std::ffi::OsStr; use std::fmt::{self, Debug}; use std::usize; pub mod unsupported; #[cfg(any( target_os = "linux", all(target_os = "android", feature = "dl_iterate_phdr") ))] use crate::linux as native_mod; #[cfg(any(target_os = "macos", target_os = "ios"))] use crate::macos as native_mod; #[cfg(target_os = "windows")] use crate::windows as native_mod; #[cfg(not(any( target_os = "macos", target_os = "ios", target_os = "linux", all(target_os = "android", feature = "dl_iterate_phdr"), target_os = "windows" )))] 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 = "ios", target_os = "linux", all(target_os = "android", feature = "dl_iterate_phdr"), target_os = "windows" )); 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 = usize where default = 0, display = "{:#x}"; /// Actual virtual memory address. /// /// See the module documentation for details. type Avma = usize where default = 0, display = "{:#x}"; /// Virtual memory bias. /// /// See the module documentation for details. type Bias = usize 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 } /// Returns `true` if this is a segment loaded into memory. #[inline] fn is_load(&self) -> bool { self.is_code() } /// 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(svma.0 + 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; let end = start + self.len(); let address = address.0; 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; let end = start + self.len(); let address = address.0; 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), /// The PE timestamp and size PeSignature(u32, u32), /// A PDB GUID and age, PdbSignature([u8; 16], u32), } 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, SharedLibraryId::PeSignature(_, _) => &[][..], SharedLibraryId::PdbSignature(ref bytes, _) => &*bytes, } } } impl fmt::Display for SharedLibraryId { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { SharedLibraryId::Uuid(ref bytes) => { for (idx, byte) in bytes.iter().enumerate() { if idx == 4 || idx == 6 || idx == 8 || idx == 10 { write!(f, "-")?; } write!(f, "{:02x}", byte)?; } } SharedLibraryId::GnuBuildId(ref bytes) => { for byte in bytes { write!(f, "{:02x}", byte)?; } } SharedLibraryId::PeSignature(timestamp, size_of_image) => { write!(f, "{:08X}{:x}", timestamp, size_of_image)?; } SharedLibraryId::PdbSignature(ref bytes, age) => { for (idx, byte) in bytes.iter().enumerate() { if idx == 4 || idx == 6 || idx == 8 || idx == 10 { write!(f, "-")?; } write!(f, "{:02X}", byte)?; } write!(f, "{:x}", age)?; } } Ok(()) } } impl fmt::Debug for SharedLibraryId { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let name = match *self { SharedLibraryId::Uuid(..) => "Uuid", SharedLibraryId::GnuBuildId(..) => "GnuBuildId", SharedLibraryId::PeSignature(..) => "PeSignature", SharedLibraryId::PdbSignature(..) => "PdbSignature", }; write!(f, "{}(\"{}\")", name, self) } } /// A trait representing a shared library that is loaded in this process. #[allow(clippy::len_without_is_empty)] 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 name of the debug file with this shared library if there is one. fn debug_name(&self) -> Option<&OsStr> { None } /// Get the code-id of this shared library if available. fn id(&self) -> Option; /// Get the debug-id of this shared library if available. fn debug_id(&self) -> Option { self.id() } /// Returns the address of where the library is loaded into virtual /// memory. /// /// This address maps to the `Avma` of the first segment loaded into /// memory. Depending on the platform, this segment may not contain code. fn actual_load_addr(&self) -> Avma { self.segments() .find(|x| x.is_load()) .map(|x| x.actual_virtual_memory_address(self)) .unwrap_or(Avma(usize::MAX)) } #[inline] #[doc(hidden)] #[deprecated(note = "use stated_load_address() instead")] fn load_addr(&self) -> Svma { self.stated_load_addr() } /// Returns the address of where the library prefers to be loaded into /// virtual memory. /// /// This address maps to the `Svma` of the first segment loaded into /// memory. Depending on the platform, this segment may not contain code. fn stated_load_addr(&self) -> Svma { self.segments() .find(|x| x.is_load()) .map(|x| x.stated_virtual_memory_address()) .unwrap_or(Svma(usize::MAX)) } /// Returns the size of the image. /// /// This typically is the size of the executable code segment. This is /// normally used by server side symbolication systems to determine when /// an IP no longer falls into an image. fn len(&self) -> usize { let end_address = self .segments() .filter(|x| x.is_load()) .map(|x| x.actual_virtual_memory_address(self).0 + x.len()) .max() .unwrap_or(usize::MAX); end_address - self.actual_load_addr().0 } /// 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(); Svma(address.0 - bias.0) } /// 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"); } } } #[test] fn test_load_address_bias() { TargetSharedLibrary::each(|lib| { let svma = lib.stated_load_addr(); let avma = lib.actual_load_addr(); assert_eq!(lib.avma_to_svma(avma), svma); }); } } findshlibs-0.10.2/src/linux/mod.rs000064400000000000000000000354070000000000000150720ustar 00000000000000//! Linux-specific implementation of the `SharedLibrary` trait. use libc; use crate::Segment as SegmentTrait; use crate::SharedLibrary as SharedLibraryTrait; use crate::{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::iter; 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 std::usize; #[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; // Normally we would use `Elf32_Nhdr` on 32-bit platforms and `Elf64_Nhdr` on // 64-bit platforms. However, in practice it seems that only `Elf32_Nhdr` is // used, and reading through binutil's `readelf` source confirms this. #[repr(C)] #[derive(Debug, Clone, Copy)] struct Nhdr { 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 SharedLibrary<'a>>, } impl<'a> Segment<'a> { fn phdr(&self) -> &'a Phdr { unsafe { self.phdr.as_ref().unwrap() } } /// You must pass this segment's `SharedLibrary` or else this is wild UB. unsafe fn data(&self, shlib: &SharedLibrary<'a>) -> &'a [u8] { let phdr = self.phdr(); let avma = (shlib.addr as usize).wrapping_add(phdr.p_vaddr as usize); slice::from_raw_parts(avma as *const u8, phdr.p_memsz as usize) } fn is_note(&self) -> bool { self.phdr().p_type == libc::PT_NOTE } /// Parse the contents of a `PT_NOTE` segment. /// /// Returns a triple of /// /// 1. The `NT_*` note type. /// 2. The note name. /// 3. The note descriptor payload. /// /// You must pass this segment's `SharedLibrary` or else this is wild UB. unsafe fn notes( &self, shlib: &SharedLibrary<'a>, ) -> impl Iterator { // `man 5 readelf` says that all of the `Nhdr`, name, and descriptor are // always 4-byte aligned, but we copy this alignment behavior from // `readelf` since that seems to match reality in practice. let alignment = std::cmp::max(self.phdr().p_align as usize, 4); let align_up = move |data: &'a [u8]| { if alignment != 4 && alignment != 8 { return None; } let ptr = data.as_ptr() as usize; let alignment_minus_one = alignment - 1; let aligned_ptr = ptr.checked_add(alignment_minus_one)? & !alignment_minus_one; let diff = aligned_ptr - ptr; if data.len() < diff { None } else { Some(&data[diff..]) } }; let mut data = self.data(shlib); iter::from_fn(move || { if (data.as_ptr() as usize % alignment) != 0 { return None; } // Each entry in a `PT_NOTE` segment begins with a // fixed-size header `Nhdr`. let nhdr_size = mem::size_of::(); let nhdr = try_split_at(&mut data, nhdr_size)?; let nhdr = (nhdr.as_ptr() as *const Nhdr).as_ref().unwrap(); // No need to `align_up` after the `Nhdr` // It is followed by a name of size `n_namesz`. let name_size = nhdr.n_namesz as usize; let name = try_split_at(&mut data, name_size)?; // And after that is the note's (aligned) descriptor payload of size // `n_descsz`. data = align_up(data)?; let desc_size = nhdr.n_descsz as usize; let desc = try_split_at(&mut data, desc_size)?; // Align the data for the next `Nhdr`. data = align_up(data)?; Some((nhdr.n_type, name, desc)) }) .fuse() } } fn try_split_at<'a>(data: &mut &'a [u8], index: usize) -> Option<&'a [u8]> { if data.len() < index { None } else { let (head, tail) = data.split_at(index); *data = tail; Some(head) } } impl<'a> SegmentTrait for Segment<'a> { type SharedLibrary = 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 => "SHLIB", libc::PT_PHDR => "PHDR", libc::PT_TLS => "TLS", 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 { let hdr = self.phdr(); // 0x1 is PT_X for executable hdr.p_type == libc::PT_LOAD && (hdr.p_flags & 0x1) != 0 } #[inline] fn is_load(&self) -> bool { self.phdr().p_type == libc::PT_LOAD } #[inline] fn stated_virtual_memory_address(&self) -> Svma { Svma(self.phdr().p_vaddr as _) } #[inline] fn len(&self) -> usize { 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, { if (*info).dlpi_phdr.is_null() { return CONTINUE; } 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 } } } fn note_segments(&self) -> impl Iterator> { self.segments().filter(|s| s.is_note()) } } 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 { // Search for `PT_NOTE` segments, containing auxilliary information. // Such segments contain a series of "notes" and one kind of note is // `NT_GNU_BUILD_ID`, whose payload contains a unique identifier // generated by the linker. Return the first one we find, if any. for segment in self.note_segments() { for (note_type, note_name, note_descriptor) in unsafe { segment.notes(self) } { if note_type == NT_GNU_BUILD_ID && note_name == b"GNU\0" { return Some(SharedLibraryId::GnuBuildId(note_descriptor.to_vec())); } } } None } #[inline] fn segments(&self) -> Self::SegmentIter { SegmentIter { inner: self.headers.iter(), } } #[inline] fn virtual_memory_bias(&self) -> Bias { Bias(self.addr as usize) } #[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 crate::linux; use crate::{IterationControl, Segment, SharedLibrary}; #[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.iter().any(|x| x.contains("findshlibs"))); assert!(names.iter().any(|x| x.contains("libc.so"))); } #[test] #[cfg(target_os = "linux")] 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.10.2/src/macos/mod.rs000064400000000000000000000256040000000000000150330ustar 00000000000000//! The MacOS implementation of the [SharedLibrary //! trait](../trait.SharedLibrary.html). #![allow(clippy::cast_ptr_alignment)] use lazy_static::lazy_static; use libc; use crate::Segment as SegmentTrait; use crate::SharedLibrary as SharedLibraryTrait; use crate::{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; 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 = 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), Segment::Segment64(seg) => { assert!(seg.vmaddr <= (usize::MAX as u64)); Svma(seg.vmaddr as usize) } } } #[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: usize, 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: usize, 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!( !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 as usize, name); match f(&shlib).into() { IterationControl::Break => break, IterationControl::Continue => continue, } } } } } #[cfg(test)] mod tests { use crate::macos; use crate::{IterationControl, Segment, SharedLibrary}; #[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.10.2/src/unsupported.rs000064400000000000000000000034660000000000000155440ustar 00000000000000//! The fallback implementation of the [SharedLibrary //! trait](../trait.SharedLibrary.html) that does nothing. use crate::Segment as SegmentTrait; use crate::SharedLibrary as SharedLibraryTrait; use crate::{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 = 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.10.2/src/windows/mod.rs000064400000000000000000000274320000000000000154240ustar 00000000000000//! Windows-specific implementation of the `SharedLibrary` trait. use crate::Segment as SegmentTrait; use crate::SharedLibrary as SharedLibraryTrait; use crate::{Bias, IterationControl, SharedLibraryId, Svma}; use std::ffi::{CStr, OsStr, OsString}; use std::fmt; use std::marker::PhantomData; use std::mem; use std::os::windows::ffi::OsStringExt; use std::ptr; use std::slice; use std::usize; use winapi::ctypes::c_char; use winapi::shared::minwindef::{HMODULE, MAX_PATH}; use winapi::um::libloaderapi::{FreeLibrary, LoadLibraryExW, LOAD_LIBRARY_AS_DATAFILE}; use winapi::um::memoryapi::VirtualQuery; use winapi::um::processthreadsapi::GetCurrentProcess; use winapi::um::psapi::{ EnumProcessModules, GetModuleFileNameExW, GetModuleInformation, MODULEINFO, }; use winapi::um::winnt::{ IMAGE_DEBUG_DIRECTORY, IMAGE_DEBUG_TYPE_CODEVIEW, IMAGE_DIRECTORY_ENTRY_DEBUG, IMAGE_DOS_HEADER, IMAGE_DOS_SIGNATURE, IMAGE_NT_HEADERS, IMAGE_NT_SIGNATURE, IMAGE_SCN_CNT_CODE, IMAGE_SECTION_HEADER, MEMORY_BASIC_INFORMATION, MEM_COMMIT, }; // This is 'RSDS'. const CV_SIGNATURE: u32 = 0x5344_5352; /// An unsupported segment pub struct Segment<'a> { section: &'a IMAGE_SECTION_HEADER, } 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 = SharedLibrary<'a>; #[inline] fn name(&self) -> &str { std::str::from_utf8(&self.section.Name) .unwrap_or("") .trim_end_matches('\0') } fn is_code(&self) -> bool { (self.section.Characteristics & IMAGE_SCN_CNT_CODE) != 0 } #[inline] fn stated_virtual_memory_address(&self) -> Svma { Svma(self.section.VirtualAddress as usize) } #[inline] fn len(&self) -> usize { *unsafe { self.section.Misc.VirtualSize() } as usize } } /// An iterator over PE sections. pub struct SegmentIter<'a> { sections: std::slice::Iter<'a, IMAGE_SECTION_HEADER>, } impl<'a> fmt::Debug for SegmentIter<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("SegmentIter").finish() } } impl<'a> Iterator for SegmentIter<'a> { type Item = Segment<'a>; fn next(&mut self) -> Option { self.sections.next().map(|section| Segment { section }) } } #[repr(C)] struct CodeViewRecord70 { signature: u32, pdb_signature: [u8; 16], pdb_age: u32, // This struct has a flexible array containing a UTF-8 \0-terminated string. // This is only represented by its first byte here. pdb_filename: c_char, } /// A shared library on Windows. pub struct SharedLibrary<'a> { module_info: MODULEINFO, module_name: OsString, phantom: PhantomData<&'a ()>, } impl<'a> fmt::Debug for SharedLibrary<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("SharedLibrary") .field("module_base", &self.module_base()) .field("name", &self.name()) .field("debug_name", &self.debug_name()) .field("id", &self.id()) .field("debug_id", &self.debug_id()) .finish() } } impl<'a> SharedLibrary<'a> { fn new(module_info: MODULEINFO, module_name: OsString) -> SharedLibrary<'a> { SharedLibrary { module_info, module_name, phantom: PhantomData, } } #[inline] fn module_base(&self) -> *const c_char { self.module_info.lpBaseOfDll as *const c_char } fn dos_header(&self) -> Option<&IMAGE_DOS_HEADER> { let header: &IMAGE_DOS_HEADER = unsafe { &*(self.module_base() as *const _) }; if header.e_magic == IMAGE_DOS_SIGNATURE { Some(header) } else { None } } fn nt_headers(&self) -> Option<&IMAGE_NT_HEADERS> { self.dos_header().and_then(|dos_header| { let nt_headers: &IMAGE_NT_HEADERS = unsafe { &*(self.module_base().offset(dos_header.e_lfanew as isize) as *const _) }; if nt_headers.Signature == IMAGE_NT_SIGNATURE { Some(nt_headers) } else { None } }) } fn debug_directories(&self) -> &[IMAGE_DEBUG_DIRECTORY] { self.nt_headers().map_or(&[], |nt_headers| { if nt_headers.OptionalHeader.NumberOfRvaAndSizes <= IMAGE_DIRECTORY_ENTRY_DEBUG as u32 { return &[]; } let data_dir = nt_headers.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG as usize]; if data_dir.VirtualAddress == 0 { return &[]; } let size = data_dir.Size as usize; if size % mem::size_of::() != 0 { return &[]; } let nb_dirs = size / mem::size_of::(); unsafe { slice::from_raw_parts( self.module_base().offset(data_dir.VirtualAddress as isize) as *const _, nb_dirs, ) } }) } fn codeview_record70(&self) -> Option<&CodeViewRecord70> { self.debug_directories().iter().find_map(|debug_directory| { if debug_directory.Type != IMAGE_DEBUG_TYPE_CODEVIEW { return None; } let debug_info: &CodeViewRecord70 = unsafe { &*(self .module_base() .offset(debug_directory.AddressOfRawData as isize) as *const _) }; if debug_info.signature == CV_SIGNATURE { Some(debug_info) } else { None } }) } } impl<'a> SharedLibraryTrait for SharedLibrary<'a> { type Segment = Segment<'a>; type SegmentIter = SegmentIter<'a>; #[inline] fn name(&self) -> &OsStr { &self.module_name } #[inline] fn debug_name(&self) -> Option<&OsStr> { self.codeview_record70().and_then(|codeview| { let cstr = unsafe { CStr::from_ptr(&codeview.pdb_filename as *const _) }; if let Ok(s) = cstr.to_str() { Some(OsStr::new(s)) } else { None } }) } fn id(&self) -> Option { self.nt_headers().map(|nt_headers| { SharedLibraryId::PeSignature( nt_headers.FileHeader.TimeDateStamp, nt_headers.OptionalHeader.SizeOfImage, ) }) } #[inline] fn debug_id(&self) -> Option { self.codeview_record70() .map(|codeview| SharedLibraryId::PdbSignature(codeview.pdb_signature, codeview.pdb_age)) } fn segments(&self) -> Self::SegmentIter { let sections = self.nt_headers().map(|nt_headers| unsafe { let base = (nt_headers as *const _ as *const u8).add(mem::size_of::()); slice::from_raw_parts( base as *const IMAGE_SECTION_HEADER, nt_headers.FileHeader.NumberOfSections as usize, ) }); SegmentIter { sections: sections.unwrap_or(&[][..]).iter(), } } #[inline] fn virtual_memory_bias(&self) -> Bias { Bias(self.module_base() as usize) } fn each(mut f: F) where F: FnMut(&Self) -> C, C: Into, { let proc = unsafe { GetCurrentProcess() }; let mut modules_size = 0; unsafe { if EnumProcessModules(proc, ptr::null_mut(), 0, &mut modules_size) == 0 { return; } } let module_count = modules_size / mem::size_of::() as u32; let mut modules = vec![unsafe { mem::zeroed() }; module_count as usize]; unsafe { if EnumProcessModules(proc, modules.as_mut_ptr(), modules_size, &mut modules_size) == 0 { return; } } modules.truncate(modules_size as usize / mem::size_of::()); for module in modules { unsafe { let mut module_path = vec![0u16; MAX_PATH + 1]; let module_path_len = GetModuleFileNameExW( proc, module, module_path.as_mut_ptr(), MAX_PATH as u32 + 1, ) as usize; if module_path_len == 0 { continue; } let mut module_info = mem::zeroed(); if GetModuleInformation( proc, module, &mut module_info, mem::size_of::() as u32, ) == 0 { continue; } // to prevent something else from unloading the module while // we're poking around in memory we load it a second time. This // will effectively just increment the refcount since it has been // loaded before. let handle_lock = LoadLibraryExW( module_path.as_ptr(), ptr::null_mut(), LOAD_LIBRARY_AS_DATAFILE, ); let mut vmem_info = mem::zeroed(); let mut should_break = false; if VirtualQuery( module_info.lpBaseOfDll, &mut vmem_info, mem::size_of::(), ) == mem::size_of::() { let module_path = OsString::from_wide(&module_path[..module_path_len]); if vmem_info.State == MEM_COMMIT { let shlib = SharedLibrary::new(module_info, module_path); match f(&shlib).into() { IterationControl::Break => should_break = true, IterationControl::Continue => {} } } } FreeLibrary(handle_lock); if should_break { break; } } } } } #[cfg(test)] mod tests { use super::super::{IterationControl, Segment, SharedLibrary}; use crate::windows; #[test] fn can_break() { let mut first_count = 0; windows::SharedLibrary::each(|_| { first_count += 1; }); assert!(first_count > 2); let mut second_count = 0; windows::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() { windows::SharedLibrary::each(|shlib| { let _ = shlib.name(); assert!(shlib.debug_name().is_some()); }); } #[test] fn have_code() { windows::SharedLibrary::each(|shlib| { println!("shlib = {:?}", shlib.name()); let mut found_code = false; for seg in shlib.segments() { println!(" segment = {:?}", seg.name()); if seg.is_code() { found_code = true; } } assert!(found_code); }); } #[test] fn get_id() { windows::SharedLibrary::each(|shlib| { assert!(shlib.id().is_some()); assert!(shlib.debug_id().is_some()); }); } }