caddy-hexspell 1.2.3

Dependency-free Rust library for parsing and patching PE, ELF, and Mach-O executables with a 1:1 on-disk API
Documentation

HexSpell

A lightweight, dependency-free Rust library for parsing and patching PE, ELF, and Mach-O executables.

Crates.io License: MIT

Overview

HexSpell is a small parsing library for executable binaries. It has no runtime dependencies — only the Rust standard library — so it stays easy to embed, audit, and ship.

Parse PE, ELF, and Mach-O files (including FAT Mach-O), read headers and tables, and write changes back to disk when you need to patch an executable.

  • Zero dependencies — no external crates at runtime.
  • Lightweight — focused on parsing and patching; no heavy framework around the formats.
  • Multi-format — PE (Windows), ELF (Linux), and Mach-O (macOS) in one crate.
  • Parse and patch — read entry points, sections, imports, exports, and more; update headers and write the file back with write_file.
  • Structural edits — insert sections and load segments, sync layout, apply relocations.
  • PE generation (write feature with pe) — construct x86/x64 EXEs and DLLs from section bytes, with imports, exports, relocations, TLS, and resources.
  • PE memory reconstruction (pe-reconstruct with pe) — convert a contiguous RVA-addressed snapshot into a file-aligned PE with PE::from_memory_image. See the reconstruction guide.
  • Resource editing (write feature with pe) — edit lossless owned trees transactionally; helpers for manifests, strings, versions, and icons.
  • ELF and Mach-O writers (elf,write, macho,write) — owned construction, checked layouts, scoped dynamic linking, TLS/unwind metadata and transactional custom-data/FAT edits; Mach-O uses external signing. See the generation guide and validation matrix.
  • Signature containers (write with pe, elf, or macho) — edit PE certificate tables, Linux appended PKCS#7 trailers, and Mach-O signature blobs for external signers. See the signing guide.
  • Lazy parsers — imports, exports, TLS, exceptions, symbols, and other tables parsed on demand.
  • Endianness-aware — ELF and Mach-O byte order handled via ByteOrder.

See docs/coverage.md for exactly what is modeled per format. See the PE generation guide and the pe_hello, pe_dll, and Windows pe_dll_load examples for construction and validation. Formats (pe, elf, macho) and the public helper interface (common) have independent default-enabled features. The opt-in write feature enables construction and editing for the selected formats without enabling any formats itself. Use features = ["write"] with defaults, or default-features = false, features = ["elf", "write"] for just the ELF writer with no_std + alloc. See feature selection and 1.2.2 migration.

Installation

cargo add hexspell

Or add it manually to Cargo.toml:

[dependencies]
hexspell = "1.0"

Quick start

use hexspell::pe::PE;

fn main() {
    let mut pe = PE::from_file("app.exe").expect("failed to parse PE");

    // Read header fields from the parsed file.
    println!("architecture: {}", pe.architecture());
    println!("entry point:  {:#x}", pe.optional_header.entry_point.value);

    // Patch the entry point and write the modified file back to disk.
    pe.optional_header
        .entry_point
        .update(&mut pe.buffer, 0x36D4)
        .unwrap();

    pe.write_file("app-patched.exe").expect("failed to write PE");
}

ELF and Mach-O follow the same pattern (ELF::from_file, MachO::from_file). For big-endian binaries, use Field::update_with with the format's byte_order().

Examples

Reading key header fields per format:

use hexspell::pe::PE;

let pe = PE::from_file("tests/samples/sample1.exe").unwrap();
println!("PE type:     {:?}", pe.optional_header.pe_type().unwrap());
println!("checksum:    {:#010x}", pe.optional_header.checksum.value);
println!("sections:    {}", pe.coff_header.number_of_sections.value);
println!("size_of_img: {:#x}", pe.optional_header.size_of_image.value);
use hexspell::elf::ELF;

let elf = ELF::from_file("tests/samples/linux").unwrap();
println!("entry:      {:#x}", elf.header.entry.value);
println!("byte order: {:?}", elf.byte_order().unwrap());
println!("ph / sh:    {} / {}", elf.header.ph_num.value, elf.header.sh_num.value);
use hexspell::macho::MachO;

let macho = MachO::from_file("tests/samples/machO-OSX-x86-ls").unwrap();
println!("load commands: {}", macho.header.ncmds.value);
println!("byte order:    {:?}", macho.byte_order());
println!("first segment: {}", macho.segments[0].name());

Inserting a new PE section (for example, to inject code):

use hexspell::pe::PE;
use hexspell::pe::section::{NewSection, CODE, READ, EXECUTE};

let mut pe = PE::from_file("tests/samples/sample1.exe").unwrap();

pe.insert_section(NewSection {
    name: ".shell".to_string(),
    data: vec![0x90; 64], // your payload here
    characteristics: CODE | READ | EXECUTE,
})
.unwrap();

// Point the entry to the start of the new section.
let new_va = pe.sections.last().unwrap().virtual_address.value;
pe.optional_header
    .entry_point
    .update(&mut pe.buffer, new_va)
    .unwrap();

pe.write_file("tests/out/modified.exe").unwrap();

More runnable examples and per-format walkthroughs live in the user guide.

Documentation

Contributing

Issues and pull requests are welcome — open an issue to report a bug or discuss a change. Contributors and agents should follow the conventions in AGENTS.md (tests required, cargo fmt + cargo test before finishing, no runtime dependencies).

Test coverage

Install cargo-llvm-cov and the LLVM tools for your Rust toolchain:

rustup component add llvm-tools-preview
cargo install cargo-llvm-cov --locked

For a Nix-managed toolchain, provide matching LLVM tools through LLVM_COV and LLVM_PROFDATA if the shell does not include llvm-tools-preview.

Collect coverage and generate local reports:

cargo llvm-cov --all-features --lib --tests --no-report
mkdir -p coverage
cargo llvm-cov report --ignore-filename-regex '(^|/)(tests|examples|benches)/' --lcov --output-path coverage/lcov.info
cargo llvm-cov report --ignore-filename-regex '(^|/)(tests|examples|benches)/' --html --output-dir coverage
cargo llvm-cov report --ignore-filename-regex '(^|/)(tests|examples|benches)/'

Open coverage/html/index.html to inspect covered and uncovered library lines. Reports stay in the ignored coverage/ directory; nothing is uploaded. No minimum percentage is enforced. Coverage includes unit and integration tests with all features, including write. It excludes test/example/benchmark source files from the reported totals; doctests, ignored tests, fuzz harnesses, and platform-specific runtime acceptance scripts are not measured. This is separate from the format coverage matrix.

License

Distributed under the terms of the MIT License. See LICENSE for details.

no_std support

The std feature is enabled by default and preserves the file I/O APIs. Disable default features for no_std + alloc:

[dependencies]
hexspell = { git = "https://github.com/CaddyGlow/HexSpell", default-features = false, features = ["pe", "elf", "macho", "common"] }

In this mode, PE, ELF and Mach-O parsing from buffers, field edits, layout operations and validation remain available. from_file, write_file, file-based Mach-O FAT helpers, and FileParseError::Io require std. Errors implement core::error::Error in both modes.

Owned buffers, strings and parsed tables require an allocator supplied by the application. The borrowed pe::view::PeHeaders API does not allocate; this is not an allocator-free configuration of the entire crate.

use hexspell::pe::view::PeHeaders;

fn machine(bytes: &[u8]) -> Result<u16, hexspell::errors::FileParseError> {
    Ok(PeHeaders::parse(bytes)?.coff.machine.value)
}

Validate both modes with cargo test and cargo test --no-default-features. cargo check --no-default-features --target thumbv7em-none-eabi checks a target without a standard library.

Read-only parsing can borrow existing bytes with PE::from_slice, ELF::from_slice, and MachO::from_slice, avoiding a full file copy. Use owned from_buffer or from_file inputs for editing.

For allocation-free header-only inspection, use pe::view::PeHeaders, elf::view::ElfHeaders, or macho::view::MachHeaders (thin Mach-O). Referenced tables are inspected on demand.

Read-only directory inspection can stream PE imports, exports, base relocations, and debug records without collecting tables. ELF entry views and Mach-O command and FAT views avoid temporary allocations. Borrowed name accessors preserve owned editing support. Version 1.2.0 changes relocation and import-descriptor access; see the migration guide.

Fuzzing harnesses, corpus generation, and crash replay are documented in fuzz/README.md.