<div align="center">
# HexSpell
**A lightweight, dependency-free Rust library for parsing and patching PE, ELF, and Mach-O executables.**
<img src="https://github.com/M3str3/HexSpell/assets/62236987/8d5d500a-acb1-45d0-a63e-ec610b5e5ccc" alt="HexSpell" width="400">
[](https://crates.io/crates/hexspell)
[](LICENSE)
</div>
## 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](docs/guide.md#reconstructing-a-pe-memory-image).
- **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](docs/guide.md#elf-and-mach-o-generation-and-transactional-editing) and [validation matrix](docs/elf-macho-generation-validation.md).
- **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](docs/guide.md#signature-containers-and-external-signers).
- **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`](docs/coverage.md) for exactly what is modeled per format.
See the [PE generation guide](docs/guide.md#pe-generation-and-resource-editing) 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](docs/guide.md#features-and-migrating-to-122).
## Installation
```bash
cargo add hexspell
```
Or add it manually to `Cargo.toml`:
```toml
[dependencies]
hexspell = "1.0"
```
## Quick start
```rust
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:
```rust
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);
```
```rust
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);
```
```rust
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):
```rust
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](docs/guide.md).
## Documentation
- [User guide](docs/guide.md) — design principles, per-format examples, error handling.
- [Layout accessors](docs/layout.md) — `field()` / `field_mut()` on ELF/Mach-O layout enums.
- [Coverage matrix](docs/coverage.md) — what is modeled vs not, per format.
- [ELF and Mach-O creation and editing plan](docs/elf-macho-generation-plan.md) — supported writer profiles, implementation milestones, and validation gates.
- [Changelog](CHANGELOG.md) — notable changes per release.
## Contributing
Issues and pull requests are welcome — [open an issue](https://github.com/M3str3/HexSpell/issues) to
report a bug or discuss a change. Contributors and agents should follow the conventions in
[`AGENTS.md`](AGENTS.md) (tests required, `cargo fmt` + `cargo test` before finishing, no runtime
dependencies).
### Test coverage
Install [cargo-llvm-cov](https://github.com/taiki-e/cargo-llvm-cov) and the LLVM
tools for your Rust toolchain:
```sh
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:
```sh
cargo llvm-cov --all-features --lib --tests --no-report
mkdir -p 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](docs/coverage.md).
## License
Distributed under the terms of the MIT License. See [LICENSE](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`:
```toml
[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.
```rust
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](docs/guide.md#migrating-to-120).
Fuzzing harnesses, corpus generation, and crash replay are documented in [fuzz/README.md](fuzz/README.md).