### Example: Parsing with Explicit Context Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/container.md Demonstrates how to create and use an explicit context for parsing. ```APIDOC ## Example: Parsing with Explicit Context ```rust use goblin::container::{Ctx, Container}; use scroll::LE; // Parse a 64-bit little-endian binary explicitly let ctx = Ctx::new(Container::Big, LE); // The context is passed to parsing functions // that need to interpret binary data correctly ``` ``` -------------------------------- ### Ctx::new() Example Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/container.md Demonstrates creating a `Ctx` for a 64-bit little-endian binary. This context is then used for parsing. ```rust use goblin::container::{Container, Ctx}; use scroll::LE; // Create context for 64-bit little-endian let ctx = Ctx::new(Container::Big, LE); ``` -------------------------------- ### Example: Using ParseOptions with Elf::parse_with_opts Source: https://github.com/m4b/goblin/blob/master/_autodocs/configuration.md Demonstrates how to create custom ParseOptions, including setting permissive mode, and then use them to parse an ELF file. ```rust use goblin::options::ParseOptions; use goblin::elf::Elf; let opts = ParseOptions::default() .with_parse_mode(ParseOptions::permissive().parse_mode); let elf = Elf::parse_with_opts(&bytes, &opts)?; ``` -------------------------------- ### Example: Extracting Context from Binary Header Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/container.md Shows how to determine the container context from a parsed binary's header. ```APIDOC ## Example: Extracting Context from Binary Header ```rust use goblin::elf::Elf; use goblin::container::Container; let bytes = std::fs::read("binary.elf")?; let elf = Elf::parse(&bytes)?; // Determine context from parsed binary let is_64 = elf.is_64; let is_little = elf.little_endian; let container = if is_64 { Container::Big } else { Container::Little }; let endian = if is_little { scroll::LE } else { scroll::BE }; println!("Binary: {} endian, {}-bit", if is_little { "little" } else { "big" }, if is_64 { "64" } else { "32" }); ``` ``` -------------------------------- ### Example: Parsing with Explicit Context Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/container.md Demonstrates how to explicitly create a `Ctx` for a 64-bit little-endian binary and how this context is passed to parsing functions to ensure correct interpretation of binary data. ```rust use goblin::container::{Ctx, Container}; use scroll::LE; // Parse a 64-bit little-endian binary explicitly let ctx = Ctx::new(Container::Big, LE); // The context is passed to parsing functions // that need to interpret binary data correctly ``` -------------------------------- ### Example: ELF Section Names Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/strtab.md Demonstrates how to retrieve section names from an ELF file's string table. ```APIDOC ## Example: ELF Section Names ```rust use goblin::elf::Elf; let bytes = std::fs::read("binary.elf")?; let elf = Elf::parse(&bytes)?; // Get section names from the string table for section in &elf.section_headers { if let Some(name) = elf.shdr_strtab.get_at(section.sh_name as usize) { println!("Section: {} @ 0x{:x}", name, section.sh_addr); } } ``` ``` -------------------------------- ### Example: Enabling Goblin Debug Logging with RUST_LOG Source: https://github.com/m4b/goblin/blob/master/_autodocs/configuration.md Shows how to set the RUST_LOG environment variable to enable detailed debug output for Goblin's parsing operations during development. ```bash RUST_LOG=goblin=debug cargo run ``` -------------------------------- ### Example: Extracting Context from Binary Header Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/container.md Shows how to parse an ELF binary, extract its 64-bit status and endianness from the header, and then construct the appropriate `Container` and `scroll::Endian` values for a `Ctx`. ```rust use goblin::elf::Elf; use goblin::container::Container; let bytes = std::fs::read("binary.elf")?; let elf = Elf::parse(&bytes)?; // Determine context from parsed binary let is_64 = elf.is_64; let is_little = elf.little_endian; let container = if is_64 { Container::Big } else { Container::Little }; let endian = if is_little { scroll::LE } else { scroll::BE }; println!("Binary: {} endian, {}-bit", if is_little { "little" } else { "big" }, if is_64 { "64" } else { "32" }); ``` -------------------------------- ### Configure MSBuild for Manual Clang Toolchain Source: https://github.com/m4b/goblin/blob/master/etc/projects/bingen/README.md Customize MSBuild to reference a manually installed Clang toolchain by providing the LLVM installation directory and toolchain version. ```xml C:/path/to/llvm/bin xx.xxxx.x ``` -------------------------------- ### Example: ELF Symbol Names Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/strtab.md Illustrates how to extract dynamic symbol names from an ELF file's string table. ```APIDOC ## Example: ELF Symbol Names ```rust // Get dynamic symbol names for sym in elf.dynsyms.iter() { if let Some(name) = elf.dynstrtab.get_at(sym.st_name as usize) { println!("Symbol: {} (size: {})", name, sym.st_size); } } ``` ``` -------------------------------- ### Parse Binary File and Identify Format Source: https://github.com/m4b/goblin/blob/master/_autodocs/INTRODUCTION.md This minimal example demonstrates how to read a binary file into bytes and parse it using Goblin's Object::parse function. It then matches on the parsed object to identify the binary format (ELF, PE, or Mach-O) and prints its entry point or a generic message. ```rust use goblin::Object; fn main() -> Result<(), Box> { let bytes = std::fs::read("binary")?; match Object::parse(&bytes)? { Object::Elf(elf) => println!("ELF entry: 0x{:x}", elf.entry), Object::PE(pe) => println!("PE entry: 0x{:x}", pe.entry), Object::Mach(mach) => println!("Mach-O binary"), _ => println!("Other format"), } Ok(()) } ``` -------------------------------- ### Ctx From Container Conversion Example Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/container.md Example of converting a `Container::Big` into a `Ctx` using the `From` trait. The endianness will default to the host's. ```rust let ctx: Ctx = Container::Big.into(); ``` -------------------------------- ### PE Module Documentation Source: https://github.com/m4b/goblin/blob/master/_autodocs/COMPLETION_SUMMARY.txt Detailed documentation for the PE parsing capabilities, including structures, functions, and examples. ```APIDOC ## PE Module ### Description This section covers the API for parsing and analyzing Portable Executable (PE) files, commonly used on Windows systems. It includes details on imports, exports, resources, and debug information. ### Key Components - **PE Header**: Access to the main PE header structures. - **Imports**: Information about imported functions and libraries. - **Exports**: Details on exported functions and symbols. - **Resources**: Parsing and accessing embedded resources. - **Debug Information**: Handling of debug data. ### Usage ```rust // Example of opening and parsing a PE file (conceptual) use goblin::pe::PE; fn parse_pe(file_path: &str) -> Result { let mut file = std::fs::File::open(file_path)?; PE::from_stream(&mut file) } ``` ### Documentation Principles - All exported types are documented. - Function signatures are complete. - Parameter tables and return type descriptions are provided. - Error conditions and code examples are included. ``` -------------------------------- ### Parse PE Binaries with Goblin Source: https://github.com/m4b/goblin/blob/master/_autodocs/INTRODUCTION.md Parse Portable Executable (PE) binaries to get information like entry point, image base, libraries, and exports. Requires `goblin::pe::PE`. ```rust use goblin::pe::PE; let bytes = std::fs::read("app.exe")?; let pe = PE::parse(&bytes)?; println!("Is 64-bit: {}", pe.is_64); println!("Entry: 0x{:x} (RVA)", pe.entry); println!("Image base: 0x{:x}", pe.image_base); println!("Libraries:"); for lib in &pe.libraries { println!(" {}", lib); } println!("Exports:"); for export in &pe.exports { println!(" {} @ 0x{:x}", export.name, export.rva); } ``` -------------------------------- ### Mach-O Module Documentation Source: https://github.com/m4b/goblin/blob/master/_autodocs/COMPLETION_SUMMARY.txt Detailed documentation for the Mach-O parsing capabilities, including structures, functions, and examples. ```APIDOC ## Mach-O Module ### Description This section provides documentation for the Mach-O (Mach Object) file format parser, used on macOS and iOS. It covers segments, symbols, imports, exports, and FAT binary information. ### Key Components - **Mach-O Header**: Access to the Mach-O header. - **Segments**: Information about memory segments. - **Symbols**: Symbol table details. - **Imports/Exports**: Function and symbol import/export information. - **FAT Binary**: Handling of universal binaries containing multiple architectures. ### Usage ```rust // Example of opening and parsing a Mach-O file (conceptual) use goblin::mach::Mach; fn parse_mach_o(file_path: &str) -> Result { let mut file = std::fs::File::open(file_path)?; Mach::from_stream(&mut file) } ``` ### Documentation Principles - Consistent documentation format across all files. - Uniformity in table formatting and code blocks. - Extensive linking between related topics. ``` -------------------------------- ### Ctx From Endian Conversion Example Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/container.md Example of converting `scroll::LE` into a `Ctx` using the `From` trait. The container size will default to the host's. ```rust use scroll::LE; let ctx: Ctx = LE.into(); ``` -------------------------------- ### ELF Module Documentation Source: https://github.com/m4b/goblin/blob/master/_autodocs/COMPLETION_SUMMARY.txt Detailed documentation for the ELF parsing capabilities, including structures, functions, and examples. ```APIDOC ## ELF Module ### Description This section details the API for parsing and analyzing ELF (Executable and Linkable Format) files. It covers headers, sections, symbols, relocations, and dynamic linking information. ### Key Components - **ELF Header**: Access to the primary ELF header information. - **Sections**: Parsing and iterating through ELF sections. - **Symbols**: Accessing symbol tables and symbol information. - **Relocations**: Handling relocation entries. - **Dynamic Linking**: Information related to dynamic linking. ### Usage ```rust // Example of opening and parsing an ELF file (conceptual) use goblin::elf::Elf; fn parse_elf(file_path: &str) -> Result { let mut file = std::fs::File::open(file_path)?; Elf::from_stream(&mut file) } ``` ### Documentation Principles - Each public type is documented separately. - Every function includes its full signature. - All parameters are documented in tables. - Return types are provided with descriptions. - Error conditions are explicitly listed. - Practical code examples are included. ``` -------------------------------- ### Archive Module Documentation Source: https://github.com/m4b/goblin/blob/master/_autodocs/COMPLETION_SUMMARY.txt Detailed documentation for the Archive parsing capabilities, including structures, functions, and examples. ```APIDOC ## Archive Module ### Description This section details the API for parsing archive files, such as static libraries (`.a` files). It covers members, symbol indexes, and support for SysV and BSD archive formats. ### Key Components - **Archive Members**: Accessing individual members within the archive. - **Symbol Index**: Information about the archive's symbol index. - **Format Support**: Handling of SysV and BSD archive variants. ### Usage ```rust // Example of opening and parsing an Archive file (conceptual) use goblin::archive::Archive; fn parse_archive(file_path: &str) -> Result { let mut file = std::fs::File::open(file_path)?; Archive::from_stream(&mut file) } ``` ### Documentation Principles - All modules are covered. - Format-specific details are included. - Edge cases are noted in the documentation. ``` -------------------------------- ### Handling ELF Parsing Errors Source: https://github.com/m4b/goblin/blob/master/_autodocs/errors.md Demonstrates how to match on specific goblin Error variants when parsing an ELF file. This example shows handling `BadMagic`, `Malformed`, and other general errors. ```rust use goblin::elf::Elf; use goblin::error::Error; match Elf::parse(&bytes) { Ok(elf) => println!("Parsed: {} sections", elf.section_headers.len()), Err(Error::BadMagic(magic)) => eprintln!("Not ELF: 0x{:x}", magic), Err(Error::Malformed(msg)) => eprintln!("Corrupted ELF: {}", msg), Err(e) => eprintln!("Error: {}", e), } ``` -------------------------------- ### Get Member Size Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/archive.md Returns the size of this member's data in bytes. ```rust pub fn size(&self) -> usize ``` -------------------------------- ### Get String Table Size Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/strtab.md Returns the total size of the string table in bytes. ```rust pub fn len(&self) -> usize ``` -------------------------------- ### Get Member Raw Name Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/archive.md Returns the raw member name including padding and terminators. ```rust pub fn raw_name(&self) -> &'a str ``` -------------------------------- ### Goblin Library Entry Points Source: https://github.com/m4b/goblin/blob/master/_autodocs/COMPLETION_SUMMARY.txt The Goblin library provides several entry points for parsing different binary file formats. Each format has specific functions for opening and accessing its contents. ```APIDOC ## Goblin Library API Overview ### Description The Goblin library offers functions to parse and analyze various binary file formats. Key formats supported include ELF, PE, Mach-O, and Archives. ### Entry Points - **ELF Parsing**: Functions to open and parse ELF files. - **PE Parsing**: Functions to open and parse Portable Executable (PE) files. - **Mach-O Parsing**: Functions to open and parse Mach-O files. - **Archive Parsing**: Functions to open and parse archive files (e.g., static libraries). ### Features - Comprehensive coverage of exported functions and types. - Detailed documentation for parameters, return types, and error conditions. - Practical code examples demonstrating usage patterns. - Cross-referencing between related topics and source code locations. ``` -------------------------------- ### Goblin All Formats Configuration Source: https://github.com/m4b/goblin/blob/master/_autodocs/configuration.md Enables full support for all binary formats by default in Goblin. ```toml [dependencies] goblin = { version = "0.10" } ``` -------------------------------- ### Generate hello.so with GCC Source: https://github.com/m4b/goblin/blob/master/tests/bins/elf/gnu_hash/README.md Compile a C source file into a shared object library using GCC. Ensure the necessary flags for shared library creation and position-independent code are used. ```bash % gcc -o hello.so helloworld.c -Wl,--as-needed -shared -fPIC ``` -------------------------------- ### Get Member Extended Name Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/archive.md Returns the member name, handling both BSD and SysV naming conventions. ```rust pub fn extended_name(&self) -> &'a str ``` -------------------------------- ### Build Binary with CMake Source: https://github.com/m4b/goblin/blob/master/etc/projects/bingen/README.md Build the project's binary using CMake's build command in the release configuration. ```bash cmake --build . --config release ``` -------------------------------- ### Configuration Options Source: https://github.com/m4b/goblin/blob/master/_autodocs/COMPLETION_SUMMARY.txt Details on configuration options available for the Goblin library. ```APIDOC ## Configuration Options ### Description This section lists and explains all available configuration options for the Goblin library. ### Options - All configuration options are listed. - Descriptions detail their purpose and usage. ### Example ```rust // Conceptual example of using configuration options use goblin::options::GoblinOptions; let mut options = GoblinOptions::default(); // Set specific options here, e.g.: // options.parse_debug_info = true; // Pass options to parsing functions if supported // let result = goblin::elf::Elf::from_stream_with_options(&mut file, &options)?; ``` ``` -------------------------------- ### Goblin Minimal Standard Library Configuration Source: https://github.com/m4b/goblin/blob/master/_autodocs/configuration.md Configures Goblin with the standard library support and ELF 32/64-bit formats, offering minimal overhead. ```toml [dependencies] goblin = { version = "0.10", default-features = false, features = ["std", "elf32", "elf64"] } ``` -------------------------------- ### Parse PE File and List Imports/Exports/Sections Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/pe.md Reads a PE file from disk, parses it using Goblin, and then iterates through its imports, exports, and sections, printing relevant information for each. Ensure the file exists and is a valid PE file. ```rust use goblin::pe::PE; let bytes = std::fs::read("library.dll")?; let pe = PE::parse(&bytes)?; // List all imported functions for import in &pe.imports { println!("{} <- {}", import.name, import.dll); } // List all exported functions for export in &pe.exports { println!("Export: {} @ 0x{:x}", export.name, export.rva); } // Check sections for section in &pe.sections { let name = String::from_utf8_lossy(§ion.name); println!("Section: {} at 0x{:x}", name.trim_end_matches('\0'), section.virtual_address); } ``` -------------------------------- ### Get String by Offset (Unsafe) Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/strtab.md Retrieves a string without bounds checking. Use this only if the offset has already been validated. Panics if bytes are invalid UTF-8. ```rust pub fn get_unsafe(&self, offset: usize) -> Option<&'a str> ``` -------------------------------- ### Get String by Offset (Safe) Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/strtab.md Retrieves a string from the table using a byte offset. Returns None if the offset is out of bounds. Use this for safe access. ```rust pub fn get_at(&self, offset: usize) -> Option<&'a str> ``` ```rust if let Some(name) = strtab.get_at(section_header.sh_name as usize) { println!("Section name: {}", name); } ``` -------------------------------- ### Create Build Directory with CMake Source: https://github.com/m4b/goblin/blob/master/etc/projects/bingen/README.md Use this command to create a build directory for your project. ```bash mkdir build ``` -------------------------------- ### Parse PE and List Imports Source: https://github.com/m4b/goblin/blob/master/_autodocs/README.md Parses a byte slice as a PE (Portable Executable) binary and lists the imported DLLs and their associated names. Requires the `PE` type from the `goblin::pe` module. ```rust use goblin::pe::PE; let pe = PE::parse(&bytes)?; for import in &pe.imports { println!("{} <- {}", import.name, import.dll); } ``` -------------------------------- ### Get Imported Symbols Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/mach.md Returns a list of imported symbols from the Mach-O binary, including dyld binding information. Returns an error if retrieval fails. ```rust pub fn imports(&self) -> error::Result>> ``` -------------------------------- ### Configure Project with CMake and Clang Source: https://github.com/m4b/goblin/blob/master/etc/projects/bingen/README.md Configure the project using CMake with the Ninja generator, specifying a Release build type and setting clang-cl as the C++ compiler. ```bash cmake .. -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_COMPILER=clang-cl ``` -------------------------------- ### Get Relocations by Segment Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/mach.md Returns a vector containing all relocations found in the binary. These relocations are organized by segment and section, providing tuples of (section_index, relocations, section_info). ```rust pub fn relocations(&self) -> error::Result, segment::Section)>> ``` -------------------------------- ### Navigate to Build Directory with CMake Source: https://github.com/m4b/goblin/blob/master/etc/projects/bingen/README.md Change your current directory to the newly created build directory. ```bash cd build ``` -------------------------------- ### Get Exported Symbols Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/mach.md Returns a list of exported symbols or functions from the Mach-O binary, typically associated with dynamic library exports. Returns an error if retrieval fails. ```rust pub fn exports(&self) -> error::Result>> ``` ```rust for export in macho.exports()? { println!("Export: {} @ 0x{:x}", export.name, export.address); } ``` -------------------------------- ### Goblin Minimal no_std Configuration Source: https://github.com/m4b/goblin/blob/master/_autodocs/configuration.md Configures Goblin for a minimal no_std environment, enabling only ELF 32-bit and 64-bit support without heap allocation. ```toml [dependencies] goblin = { version = "0.10", default-features = false, features = ["elf32", "elf64"] } ``` -------------------------------- ### Default Implementation for Ctx Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/container.md Returns a context matching the host machine's native pointer width and endianness. ```APIDOC ## Default Implementation ```rust impl Default for Ctx { fn default() -> Self { ... } } ``` Returns a context matching the host machine's native pointer width and endianness. ``` -------------------------------- ### Initialize Env Logger Source: https://github.com/m4b/goblin/blob/master/_autodocs/configuration.md Call env_logger::init() in your main function to activate Goblin's debug output. ```rust fn main() { env_logger::init(); // Now goblin debug output will appear } ``` -------------------------------- ### Ctx::new() Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/container.md Creates a new context with specified container size and endianness. ```APIDOC ## Ctx::new() ```rust pub fn new(container: Container, le: scroll::Endian) -> Self ``` Creates a new context with specified container size and endianness. **Parameters:** | Name | Type | Required | Default | Description | |------|------|----------|---------|-------------| | container | `Container` | Yes | — | Binary size (Little/Big) | | le | `scroll::Endian` | Yes | — | Byte order (LE/BE) | **Return type:** `Ctx` **Example:** ```rust use goblin::container::{Container, Ctx}; use scroll::LE; // Create context for 64-bit little-endian let ctx = Ctx::new(Container::Big, LE); ``` ``` -------------------------------- ### Inspect Dynamic Symbols of hello.so Source: https://github.com/m4b/goblin/blob/master/tests/bins/elf/gnu_hash/README.md Use readelf to display the dynamic symbol table of the generated shared object. This table lists symbols that are dynamically linked. ```bash % readelf --dyn-syms hello.so ``` -------------------------------- ### Goblin Project Module Structure Source: https://github.com/m4b/goblin/blob/master/_autodocs/INTRODUCTION.md Illustrates the directory and file layout of the Goblin Rust project, showing the organization of code for different executable formats like ELF, PE, and Mach-O. ```text goblin/ ├── lib.rs # Entry point, Object enum, generic functions ├── container.rs # Container and Ctx types ├── error.rs # Error types ├── options.rs # ParseMode and ParseOptions ├── strtab.rs # String table implementation ├── elf/ │ ├── mod.rs # Elf struct, unified parser │ ├── header.rs # ELF headers │ ├── program_header.rs # Program headers │ ├── section_header.rs # Section headers │ ├── sym.rs # Symbols │ ├── reloc.rs # Relocations │ ├── dynamic.rs # Dynamic linking │ ├── note.rs # Notes │ └── symver.rs # Symbol versioning ├── pe/ │ ├── mod.rs # PE struct, parser │ ├── header.rs # PE headers │ ├── section_table.rs # Sections │ ├── export.rs # Exports │ ├── import.rs # Imports │ └── ... (many more) ├── mach/ │ ├── mod.rs # MachO struct, parser │ ├── header.rs # Mach-O headers │ ├── load_command.rs # Load commands │ ├── segment.rs # Segments │ ├── symbols.rs # Symbols │ └── ... (related) └── archive/ └── mod.rs # Archive struct, member parsing ``` -------------------------------- ### From for Ctx Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/container.md Creates a context from a container, using the default host endianness. ```APIDOC ## From Container ```rust impl From for Ctx { fn from(container: Container) -> Self { ... } } ``` Creates a context from a container, using the default host endianness. **Example:** ```rust let ctx: Ctx = Container::Big.into(); ``` ``` -------------------------------- ### Parse Mach-O Binaries with Goblin Source: https://github.com/m4b/goblin/blob/master/_autodocs/INTRODUCTION.md Parse Mach-O binaries, including universal binaries. Extracts entry point, architecture info, libraries, and symbols. Requires `goblin::mach::Mach`. ```rust use goblin::mach::Mach; let bytes = std::fs::read("app")?; match Mach::parse(&bytes)? { Mach::Binary(macho) => { println!("Entry: 0x{:x}", macho.entry); println!("Is 64-bit: {}", macho.is_64); println!("Libraries: {:?}", macho.libs); for sym in macho.symbols() { println!("Symbol: {} @ 0x{:x}", sym.name, sym.address); } }, Mach::Fat(fat) => { println!("Universal binary: {} architectures", fat.arches.len()); for arch in &fat.arches { println!(" CPU: 0x{:x}", arch.cputype); } }, } ``` -------------------------------- ### Windows Executable Build Configuration Source: https://github.com/m4b/goblin/blob/master/etc/projects/bingen/CMakeLists.txt Configures the build for a Windows executable named 'bin'. It sets the system name to Windows, defines the source file, and applies specific compile and link options for optimization and binary characteristics. ```cmake set(CMAKE_SYSTEM_NAME Windows) add_executable(bin WIN32 "main.cc") set_target_properties(bin PROPERTIES LANGUAGE CXX) target_compile_options(bin PRIVATE /GS- # Disable generation of stack check handlers /GL # Enable whole program optimization ) target_link_options(bin PRIVATE /ENTRY:main # Explicit entry symbol since there are no CRT/libs to be linked /MANIFEST:NO # Disable manifest /NODEFAULTLIB # No libs; we want a pure binary /FIXED # No relocs /DYNAMICBASE:NO # No ASLR /SAFESEH # No unwinds /MERGE:.data=.text /MERGE:.CRT=.text /MERGE:.tls=.text # Combine sections to avoid paddings ) ``` -------------------------------- ### ParseOptions::new() and ParseOptions::default() Source: https://github.com/m4b/goblin/blob/master/_autodocs/configuration.md Creates default parsing options, which are configured for strict mode. ```rust pub fn new() -> Self pub fn default() -> Self ``` -------------------------------- ### Ctx::new() Constructor Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/container.md Creates a new `Ctx` with specified container size and endianness. Use this to explicitly define the parsing context for a binary. ```rust pub fn new(container: Container, le: scroll::Endian) -> Self ``` -------------------------------- ### Handle Goblin Archive Errors Source: https://github.com/m4b/goblin/blob/master/_autodocs/errors.md Demonstrates how to parse an archive and handle potential errors such as BadMagic or other parsing issues. This is useful when dealing with Unix archive files. ```rust use goblin::archive::Archive; use goblin::error::Error; match Archive::parse(&bytes) { Ok(archive) => { for member in archive.members() { println!("Member: {}", member.extended_name()); } }, Err(Error::BadMagic(_)) => eprintln!("Not a Unix archive"), Err(e) => eprintln!("Error: {}", e), } ``` -------------------------------- ### CONTAINER Constant Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/container.md The default container for the host machine. ```APIDOC ## CONTAINER ```rust pub const CONTAINER: Container = ...; ``` The default container for the host machine. - 64-bit host: `Container::Big` - 32-bit host: `Container::Little` This constant reflects the `target_pointer_width` at compile time. ``` -------------------------------- ### Minimal ELF-Only Crate Configuration Source: https://github.com/m4b/goblin/blob/master/_autodocs/configuration.md Configure Cargo.toml to include only ELF parsing features for a minimal Goblin build. This enables cross-platform endianness support. ```toml [dependencies] goblin = { version = "0.10", default-features = false, features = ["std", "elf32", "elf64", "endian_fd"] } ``` -------------------------------- ### File Reading with Error Handling (Rust) Source: https://github.com/m4b/goblin/blob/master/_autodocs/errors.md Demonstrates how to read a file and parse it as a Goblin object, converting potential parsing errors into std::io::Error for consistent handling. This snippet requires the 'std' feature to be enabled for Error::IO. ```rust use std::fs; use goblin::Object; use goblin::error::Error; let result = fs::read("binary").and_then(|bytes| { Object::parse(&bytes).map_err(|e| { std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()) }) }); match result { Ok(Object::Elf(elf)) => println!("OK"), Err(e) => eprintln!("Failed: {}", e), } ``` -------------------------------- ### Parse ELF Binaries with Goblin Source: https://github.com/m4b/goblin/blob/master/_autodocs/INTRODUCTION.md Parse ELF binaries to access sections and dynamic symbols. Requires `goblin::elf::Elf`. ```rust use goblin::elf::Elf; let bytes = std::fs::read("app")?; let elf = Elf::parse(&bytes)?; println!("Sections: {}", elf.section_headers.len()); for section in &elf.section_headers { if let Some(name) = elf.shdr_strtab.get_at(section.sh_name as usize) { println!(" {}", name); } } println!("Dynamic symbols: {}", elf.dynsyms.len()); for sym in elf.dynsyms.iter() { if let Some(name) = elf.dynstrtab.get_at(sym.st_name as usize) { println!(" {} @ 0x{:x}", name, sym.st_value); } } ``` -------------------------------- ### Listing Archive Contents and Extracting Objects Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/archive.md Demonstrates how to parse an archive file, iterate through its members, and extract and parse a specific object file within the archive. Requires the 'library.a' file to exist. ```rust use goblin::archive::Archive; let bytes = std::fs::read("library.a")?; let archive = Archive::parse(&bytes)?; println!("Archive contents:"); for member in archive.members() { let name = member.extended_name(); let size = member.size(); println!(" {} ({} bytes)", name, size); } // Extract and parse an object file if let Some(member) = archive.get_member("main.o") { let obj_data = archive.extract_member(member)?; match goblin::Object::parse(obj_data)? { goblin::Object::Elf(elf) => { println!("Found ELF object with {} symbols", elf.dynsyms.len()); }, _ => println!("Not an ELF object"), } } ``` -------------------------------- ### Add Goblin and Env Logger Dependencies Source: https://github.com/m4b/goblin/blob/master/_autodocs/configuration.md Include Goblin and env_logger in your Cargo.toml to enable logging for Goblin's warnings during permissive parsing. ```toml [dependencies] goblin = "0.10" env_logger = "0.11" ``` -------------------------------- ### Hint Source: https://github.com/m4b/goblin/blob/master/_autodocs/types.md Represents the result of peeking at binary magic bytes to identify the file format. ```APIDOC ## Hint ### Description Result of peeking at binary magic bytes. ### Enum `Hint` ### Variants - `Elf(HintData)`: ELF format with endianness/bitness hint - `Mach(HintData)`: Mach-O format with hint data - `MachFat(usize)`: Universal Mach-O with architecture count - `PE`: PE32/PE32+ Windows binary - `TE`: Terse Executable - `COFF`: COFF object file - `Archive`: Unix/BSD archive - `Unknown(u64)`: Unknown magic number ``` -------------------------------- ### Enabling Permissive Parsing with ParseOptions Source: https://github.com/m4b/goblin/blob/master/_autodocs/errors.md Shows how to create `ParseOptions` to enable permissive parsing, which allows the parser to recover from certain errors by using default values or truncating ranges. ```rust use goblin::elf::Elf; use goblin::options::ParseOptions; let opts = ParseOptions::permissive(); match Elf::parse_with_opts(&bytes, &opts) { Ok(elf) => { // Some sections may have been replaced with defaults println!("Parsed with {} sections", elf.section_headers.len()); }, Err(e) => eprintln!("Critical error: {}", e), } ``` -------------------------------- ### Inspect Section Headers of hello.so Source: https://github.com/m4b/goblin/blob/master/tests/bins/elf/gnu_hash/README.md Use readelf to view the section headers of the shared object. This provides details about the different sections within the ELF file, such as their type, address, and size. ```bash % readelf --section-headers hello.so ``` -------------------------------- ### Parse Any Binary Format with Goblin Source: https://github.com/m4b/goblin/blob/master/_autodocs/INTRODUCTION.md Use `Object::parse` to detect and parse common binary formats. Handles ELF, PE, Mach-O, and Archives. ```rust use goblin::Object; let bytes = std::fs::read("binary")?; match Object::parse(&bytes)? { Object::Elf(elf) => println!("ELF entry: 0x{:x}", elf.entry), Object::PE(pe) => println!("PE base: 0x{:x}", pe.image_base), Object::Mach(mach) => println!("Mach-O entry: 0x{:x}", match mach { goblin::mach::Mach::Binary(m) => m.entry, goblin::mach::Mach::Fat(_) => 0, }), Object::Archive(archive) => { for member in archive.members() { println!("Member: {}", member.extended_name()); } }, _ => {} } ``` -------------------------------- ### Goblin Cross-platform Binary Analysis Configuration Source: https://github.com/m4b/goblin/blob/master/_autodocs/configuration.md Enables Goblin's default features along with `endian_fd` for parsing foreign-endian binaries, useful for analyzing MIPS on x86 systems. ```toml [dependencies] goblin = { version = "0.10", default-features = true, features = ["endian_fd"] } ``` -------------------------------- ### Convenience Method to Parse Entire Slice Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/strtab.md The `new_preparsed` method provides a convenient way to parse an entire byte slice as a string table. It requires the `alloc` feature and returns a `Result`. ```rust let strtab = Strtab::new_preparsed(string_table_bytes, 0)?; ``` -------------------------------- ### Ctx::size() Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/container.md Returns the pointer/address byte size for this container: 4 for 32-bit, 8 for 64-bit. ```APIDOC ## Ctx::size() ```rust pub fn size(self) -> usize ``` Returns the pointer/address byte size for this container: 4 for 32-bit, 8 for 64-bit. **Return type:** `usize` — Typical pointer size (4 or 8). **Note:** This returns a default pointer size and may not be accurate for all architectures (e.g., AVR, x16). ``` -------------------------------- ### Parse Archives with Goblin Source: https://github.com/m4b/goblin/blob/master/_autodocs/INTRODUCTION.md Parse archive files (e.g., `.a` files) to list members and their sizes. Requires `goblin::archive::Archive`. ```rust use goblin::archive::Archive; let bytes = std::fs::read("library.a")?; let archive = Archive::parse(&bytes)?; for member in archive.members() { let name = member.extended_name(); let size = member.size(); println!("{} ({} bytes)", name, size); } ``` -------------------------------- ### Container Source: https://github.com/m4b/goblin/blob/master/_autodocs/types.md Represents the binary container size, either 32-bit (Little) or 64-bit (Big). ```APIDOC ## Container ### Description Binary container size (32-bit or 64-bit). ### Enum `Container` ### Members - `Little`: 32-bit container - `Big`: 64-bit container ``` -------------------------------- ### Ctx::size() Method Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/container.md Returns the pointer/address byte size for the `Ctx`'s container (4 for 32-bit, 8 for 64-bit). Note that this is a default size and may not be accurate for all architectures. ```rust pub fn size(self) -> usize ``` -------------------------------- ### HintData Source: https://github.com/m4b/goblin/blob/master/_autodocs/types.md Contains metadata extracted from binary magic bytes, indicating endianness and bitness. ```APIDOC ## HintData ### Description Metadata extracted from binary magic bytes. ### Struct `HintData` ### Fields - `is_lsb` (bool): Little-endian if true - `is_64` (Option): Some(true) = 64-bit, Some(false) = 32-bit, None = unknown ``` -------------------------------- ### From for Ctx Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/container.md Creates a context from endianness, using the default host container size. ```APIDOC ## From Endian ```rust impl From for Ctx { fn from(le: scroll::Endian) -> Self { ... } } ``` Creates a context from endianness, using the default host container size. **Example:** ```rust use scroll::LE; let ctx: Ctx = LE.into(); ``` ``` -------------------------------- ### Displaying Goblin Parse Errors Source: https://github.com/m4b/goblin/blob/master/_autodocs/errors.md Demonstrates how to catch and display a `goblin::Error` when parsing binary data fails. This is useful for providing user-friendly error messages. ```rust use goblin::Object; if let Err(e) = Object::parse(&bytes) { eprintln!("Parse error: {}", e); // Output: "Parse error: Invalid magic number: 0x1234" } ``` -------------------------------- ### Ctx Struct Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/container.md A complete binary parsing context combining container size and byte-order endianness. ```APIDOC ## Ctx Struct ```rust #[derive(Debug, Copy, Clone, PartialEq)] pub struct Ctx { pub container: Container, pub le: scroll::Endian, } ``` A complete binary parsing context combining container size and byte-order endianness. | Field | Type | Description | |-------|------|-------------| | container | `Container` | Binary size (32 or 64-bit) | | le | `scroll::Endian` | Endianness (little or big endian) | ``` -------------------------------- ### Peek Bytes for Format Detection Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/object.md Examines the first 16 bytes of binary data to determine the likely format. Requires specific features to be enabled. ```rust pub fn peek_bytes(bytes: &[u8; 16]) -> error::Result ``` -------------------------------- ### Parse Any Binary with Goblin Source: https://github.com/m4b/goblin/blob/master/_autodocs/00_START_HERE.md Use this snippet to parse a binary file and identify its type (ELF, PE, Mach-O, Archive). Requires reading the file into bytes first. ```rust use goblin::Object; let bytes = std::fs::read("binary")?; match Object::parse(&bytes)? { Object::Elf(elf) => println!("ELF entry: 0x{:x}", elf.entry), Object::PE(pe) => println!("PE image base: 0x{:x}", pe.image_base), Object::Mach(mach) => println!("Mach-O binary"), Object::Archive(archive) => println!("Archive with {} members", archive.members().count()), _ => println!("Unknown format"), } ``` -------------------------------- ### Configure Container Size by Pointer Width Source: https://github.com/m4b/goblin/blob/master/_autodocs/configuration.md This snippet configures the container size based on the target pointer width at compile time. Use this to adapt behavior for 64-bit versus other architectures. ```rust #[cfg(target_pointer_width = "64")] pub const CONTAINER: Container = Container::Big; #[cfg(not(target_pointer_width = "64"))] pub const CONTAINER: Container = Container::Little; ``` -------------------------------- ### Parse Mach-O Universal Binary Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/mach.md Reads a Mach-O file and parses it as either a single-architecture binary or a universal (fat) binary. Displays entry point and architecture details. ```rust use goblin::mach::Mach; let bytes = std::fs::read("app.macho")?; match Mach::parse(&bytes)? { Mach::Binary(macho) => { println!("Single architecture:"); println!(" Entry: 0x{:x}", macho.entry); println!(" 64-bit: {}", macho.is_64); }, Mach::Fat(fat) => { println!("Universal binary with {} architectures:", fat.arches.len()); for arch in &fat.arches { println!(" CPU: 0x{:x} @ offset 0x{:x}", arch.cputype, arch.offset); } }, } ``` -------------------------------- ### Add Goblin to Project Dependencies Source: https://github.com/m4b/goblin/blob/master/_autodocs/INTRODUCTION.md Add the Goblin crate to your project's Cargo.toml file to include it as a dependency. ```toml [dependencies] goblin = "0.10" ``` -------------------------------- ### PE::parse Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/pe.md Parses a PE binary from a byte slice. This is the most straightforward method for parsing PE files when default options are sufficient. ```APIDOC ## PE::parse ### Description Parses a PE binary from a byte slice. ### Method `parse` ### Parameters #### Path Parameters - **bytes** (`&[u8]`) - Required - The complete PE binary data ### Return type `error::Result>` - A parsed PE struct or error. ### Example ```rust use goblin::pe::PE; let bytes = std::fs::read("binary.exe")?; let pe = PE::parse(&bytes)?; println!("Entry: 0x{:x}", pe.entry); println!("Is 64-bit: {}", pe.is_64); println!("Is DLL: {}", pe.is_lib); println!("Image base: 0x{:x}", pe.image_base); println!("Imports: {}", pe.imports.len()); println!("Exports: {}", pe.exports.len()); ``` ``` -------------------------------- ### Ctx Source: https://github.com/m4b/goblin/blob/master/_autodocs/types.md Defines the complete binary parsing context, including container size and endianness. ```APIDOC ## Ctx ### Description Complete binary parsing context with container size and endianness. ### Struct `Ctx` ### Fields - `container` (Container): Binary size - `le` (scroll::Endian): Byte order (LE or BE from scroll crate) ``` -------------------------------- ### HintData Struct for ELF/Mach-O Metadata Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/object.md Contains metadata about an ELF or Mach-O binary, including endianness and bitness. ```rust pub struct HintData { pub is_lsb: bool, pub is_64: Option, } ``` -------------------------------- ### Error Conversion from TryFromIntError (Rust) Source: https://github.com/m4b/goblin/blob/master/_autodocs/errors.md Shows the implementation of From for goblin::error::Error. This allows integer conversion errors to be automatically converted into a Malformed error within Goblin. ```rust impl From for Error { fn from(err: TryFromIntError) -> Error { Error::Malformed(format!("Integer do not fit: {err}")) } } ``` -------------------------------- ### PE::parse_with_opts Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/pe.md Parses a PE binary with custom options. This method allows fine-grained control over the parsing process, such as enabling or disabling the parsing of imports and exports, and choosing between strict or permissive parsing modes. ```APIDOC ## PE::parse_with_opts ### Description Parses a PE binary with custom options. Options control whether imports/exports are parsed and parsing mode (strict/permissive). ### Method `parse_with_opts` ### Parameters #### Path Parameters - **bytes** (`&[u8]`) - Required - The PE binary data - **opts** (`&options::ParseOptions`) - Required - Parsing options ### Return type `error::Result>` - A parsed PE struct or error. ``` -------------------------------- ### Import Struct Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/pe.md Represents a single imported function or symbol by a PE file. ```APIDOC ## Import Struct A single imported function or symbol. ### Fields - **name** (`&str`) - Import name (or empty if ordinal-only) - **dll** (`&str`) - DLL it's imported from - **ordinal** (`u16`) - Ordinal number (if imported by ordinal) ``` -------------------------------- ### get_at Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/strtab.md Retrieves a string from the string table at a specified byte offset. This method includes bounds checking for safety. ```APIDOC ## get_at ### Description Gets a string from the string table by byte offset. Returns `None` if the offset is out of bounds. ### Method Signature `pub fn get_at(&self, offset: usize) -> Option<&'a str>` ### Parameters #### Path Parameters - **offset** (`usize`) - Required - Byte offset in the string table ### Return Type `Option<&'a str>` - The string or None. ### Example ```rust if let Some(name) = strtab.get_at(section_header.sh_name as usize) { println!("Section name: {}", name); } ``` ``` -------------------------------- ### Strtab::new Source: https://github.com/m4b/goblin/blob/master/_autodocs/api-reference/strtab.md Creates a Strtab without preparsing, suitable for scenarios where memory control is paramount and minimal parsing overhead is desired. Note that this method does not preparse strings, which might affect access pattern optimality. ```APIDOC ## Strtab::new ### Description Creates a `Strtab` without preparsing. Use this when you control memory and want minimal parsing overhead. Note: does not preparse, so access patterns may not be optimal. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method Signature ```rust pub fn new(bytes: &'a [u8], delim: u8) -> Self ``` ### Parameters - **bytes** (`&[u8]`) - Required - The backing byte data - **delim** (`u8`) - Required - String delimiter (typically 0 for null-terminated) ### Return type `Strtab<'a>` ### Example ```rust use goblin::strtab::Strtab; // Create from a null-terminated string table let data = b"name\0type\0value\0"; let strtab = Strtab::new(data, 0); // Access strings by byte offset let name = strtab.get_at(0); // Some("name") let typ = strtab.get_at(5); // Some("type") ``` ``` -------------------------------- ### Environment Variables Source: https://github.com/m4b/goblin/blob/master/_autodocs/configuration.md Goblin respects standard Rust environment variables for development and debugging. ```APIDOC ## Environment Variables Goblin respects the following standard Rust environment variables during development: | Variable | Effect | |----------|--------| | `RUST_LOG` | Controls logging output (requires `log` feature and env_logger) | | `RUST_LOG=goblin=debug` | Enables debug logging for goblin parsing | **Example:** ```bash RUST_LOG=goblin=debug cargo run ``` Enables debug output for parser operations: - String table parsing - Section header parsing - Symbol table operations - Import/export processing ``` -------------------------------- ### CMake Project Configuration Source: https://github.com/m4b/goblin/blob/master/etc/projects/bingen/CMakeLists.txt Sets the minimum required CMake version and project name. The ENABLE_TLS option controls whether TLS is generated in the binary. ```cmake cmake_minimum_required(VERSION 3.12) project(bingen LANGUAGES CXX) option(ENABLE_TLS "Whether to generate TLS in resulting binary" ON) if(ENABLE_TLS) add_definitions(-DENABLE_TLS) endif() ``` -------------------------------- ### Add libgoblin to Cargo.toml Source: https://github.com/m4b/goblin/blob/master/README.md Include libgoblin as a dependency in your project's Cargo.toml file. Ensure you are using a compatible Rust version. ```toml [dependencies] goblin = "0.10" ``` -------------------------------- ### Parse PE Binary with Goblin Source: https://github.com/m4b/goblin/blob/master/_autodocs/00_START_HERE.md Parses a PE (Portable Executable) binary after it has been read into bytes. Provides access to exports and imports. ```rust use goblin::pe::PE; let pe = PE::parse(&bytes)?; println!("Exports: {}", pe.exports.len()); println!("Imports: {}", pe.imports.len()); ```