Extending a zero-dependency ISA auditor to 3 OS formats and 3 CPU architectures
isa-audit started as a Linux x86-64 ELF64 checker. Shipping portable native binaries quickly showed that one container format and one ISA are not enough: release pipelines emit Linux ELF64 binaries for x86-64, AArch64, and RISC-V 64 servers, macOS Universal/Fat bundles carrying both x86_64 and arm64 Mach-O slices, and Windows PE32+ .exe and .dll builds for AMD64 and ARM64.
Expanding to three OS executable formats and three CPU architectures without pulling in external crates or relaxing #![forbid(unsafe_code)] meant separating container parsing cleanly from instruction decoding, building fast compile-time prefilters for variable-length and fixed-width ISAs alike, and leaning on deterministic fuzzing and cross-OS CI to catch the subtle failures that unit tests miss.
ExecSection + SymbolSpan view so scanning, symbol attribution, policy allowlisting, and report emitters stay format-agnostic.
1. Three OS binary containers, one normalized executable view
Every binary parser in isa-audit (ElfBinary::parse in src/elf.rs, parse_macho64 in src/macho.rs, and parse_pe32plus in src/pe.rs) returns the exact same borrowed container view: a TargetArch tag, a list of executable slices (ExecSection<'a> carrying section index, name, virtual address, file offset, and borrowed &'a [u8]), and a sorted Vec<SymbolSpan>. Nothing inside audit_binary() in src/analyzer.rs knows whether bytes came from an ELF .text section, a Mach-O __TEXT,__text slice inside a Universal binary, or a PE32+ DLL.
Each container format brings its own real-world quirks during directory walks and parsing:
- In
src/elf.rs, Linux ELF64 binaries extractSHT_PROGBITSsections markedSHF_EXECINSTR(falling back to executablePT_LOADsegments when section headers are stripped) and harvestSTT_FUNCandSTT_GNU_IFUNCsymbols, including extended section indices viaSHN_XINDEX. For files at or above 1 MiB,try_load_selective_elfskips non-executable.rodataand.eh_frameentirely. - In
src/macho.rs, standalone 64-bit little-endian Mach-O files (MH_MAGIC_64) unpack executableLC_SEGMENT_64sections andLC_SYMTABspans. Universal/Fat containers (FAT_MAGIC = 0xCAFEBABE,FAT_MAGIC_64 = 0xCAFEBABF) emit labeled per-slice reports (path(x86_64),path(arm64)) and shift finding offsets by the slice offset. Because Java.classfiles also begin with0xCAFEBABE, bothsniff_macho_or_fat_file()andFatBinary::parse()reject false positives by validating1 <= nfat_arch <= MAX_FAT_ARCHES, checking table bounds and alignment against file length, verifyingcpu_type_to_arch(cputype), and probing every slice's inner magic forMH_MAGIC_64or Unix archive!<arch>\n. - In
src/pe.rs, Windows PE32+ (AMD64 = 0x8664,ARM64 = 0xAA64) loaders skip non-PE DOSMZfiles cleanly, select sections markedIMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_CNT_CODE, and clamp each section's decoded span toraw_size.min(virtual_size)so zero-padded file-alignment slack at the end of.textis never decoded as bogus instructions. Symbol attribution merges Export Directory entries (priority 0, skipping forwarder RVAs inside the export directory range) with optional COFF symbol tables and/offsetlong section names.
2. Decoding variable-length RISC-V 64 alongside x86-64 and AArch64
With x86-64 (1 to 15 bytes, legacy/REX/VEX/EVEX) and AArch64 (fixed 4-byte little-endian words over chunks_exact(4)), adding RISC-V 64 (EM_RISCV = 243) introduced a third decoding geometry: mixed 16-bit compressed instructions (RVC and Zcb), standard 32-bit instructions, and 48/64-bit reserved encoding lengths defined by Unprivileged ISA Spec Section 1.5.
In src/decoder_riscv64.rs, instruction length comes directly from the low bits of byte 0: (b0 & 0x03) != 0x03 advances 2 bytes into classify_rvc16(), (b0 & 0x1F) != 0x1F advances 4 bytes, (b0 & 0x3F) == 0x1F advances 6 bytes, (b0 & 0x7F) == 0x3F advances 8 bytes, and 0x7F steps 2 bytes to preserve compressed alignment without panicking on embedded data.
For 32-bit instructions, a compile-time 128-entry lookup table over the 7-bit major opcode (RV32_OPCODE_HAS_EXT: [bool; 128]) skips 116 of 128 opcodes straight to IsaFeature::RiscvBase without reading the upper three bytes. Only 12 major opcodes enter classify_rv32(), and an exhaustive 65,536-halfword test guarantees the 16-bit fast prefilter never drops a Zcb instruction.
The trickiest encoding boundary sits on LOAD-FP (0x07) and STORE-FP (0x27), where scalar floating-point, half-precision Zfh, and RVV 1.0 vector memory instructions share the same major opcodes and separate solely on the 3-bit width (funct3) field:
// LOAD-FP (0x07) and STORE-FP (0x27):
// width 001 -> Zfh (flh / fsh)
// width 010/011/100 -> baseline scalar flw/fld/flq and fsw/fsd/fsq
// width 000/101/110/111 -> RVV 1.0 vector loads/stores (vle*/vse*)
0x07 => match funct3 {
1 => rv_insn(4, IsaFeature::RiscvZfh, "flh"),
0 | 5 | 6 | 7 => rv_insn(4, IsaFeature::RiscvV, "vload"),
_ => rv_insn(4, IsaFeature::RiscvBase, "fload"),
},
0x27 => match funct3 {
1 => rv_insn(4, IsaFeature::RiscvZfh, "fsh"),
0 | 5 | 6 | 7 => rv_insn(4, IsaFeature::RiscvV, "vstore"),
_ => rv_insn(4, IsaFeature::RiscvBase, "fstore"),
},
Similarly, on OP-FP (0x53), half-precision Zfh must match both fmt == 2 (binary16 arithmetic) and cross-precision conversions like fcvt.s.h and fcvt.d.h (funct5 == 0x08 && rs2 == 2) whose destination format is single or double. Rather than trusting hand-assembled bitfields, all 154 test vectors in tests/decoder_riscv64.rs were generated and cross-checked directly against LLVM 23 (llvm-mc --triple=riscv64 --show-encoding) across all 12 RISC-V 64 feature classes (rv64-base, rv-zba, rv-zbb, rv-zbc, rv-zbs, rv-zfh, rv-v, rv-zknd, rv-zkne, rv-zknh, rv-zicond, rv-zcb) and 4 RVA profiles (rv64gc, rva20u64, rva22u64, rva23u64).
3. Two real bugs caught by fuzzing and cross-OS CI
Expanding parser coverage exposed two defects that clean synthetic fixtures never triggered. The first came from adding the 2,400-case mutated EM_RISCV ELF64 parser fuzzer (fuzz_riscv64_elf64_parser_2400_mutated_inputs), which generated a binary whose sh_entsize sat close to usize::MAX. Inside parse_symtab_into() in src/elf.rs, iteration 0 started at pos = 0 and advanced via pos.checked_add(step) to Some(usize::MAX - 10) without overflowing. On iteration 1, the loop condition while pos + ELF64_SYM_SIZE <= sym_bytes.len() added 24 to usize::MAX - 10, panicking in debug builds and risking silent wraparound in release builds. Replacing the guard with while let Some(end) = pos.checked_add(ELF64_SYM_SIZE) closed the overflow permanently.
The second surfaced on Windows CI in tests/workflow_features.rs. To verify HTML report XSS escaping end to end, an integration test created a fixture file on disk named app_&<1>.elf. Linux ext4 and macOS APFS accepted it without complaint, while Windows CI failed immediately with InvalidFilename (OS error 123) because NTFS forbids <, >, ", |, ?, *, and : in filenames. Splitting the test kept portable special characters (app_&'1.elf) on disk while injecting hostile <script>alert("x&'y")</script> payloads into embedded ELF symbol names and JSON baseline "path" fields, verifying identical HTML escaping across all three OS runners.
4. Coverage, feature matrix, and verification totals
A compile-time assertion (assert!(IsaFeature::COUNT <= 128) in src/analyzer.rs) keeps feature bitsets compact across all three architectures. Current repository totals at commit bc7f4a1:
| Architecture | OS Containers | Features | Profiles | Ground Truth & Fuzz Corpus |
|---|---|---|---|---|
x86-64 |
ELF64, Mach-O/Fat, PE32+, ar |
44 | 9 (v1..v4, avx-no-fma, icelake, zen4/5, spr) |
Live g++ -O2 kernels + 60,000 decoder fuzz cases |
AArch64 |
ELF64, Mach-O/Fat, PE32+, ar |
17 | 6 (armv8.0-a to neoverse-v2 / graviton4) |
llvm-mc vectors + 60,000 decoder fuzz cases |
RISC-V 64 |
ELF64, ar |
12 | 4 (rv64gc, rva20u64, rva22u64, rva23u64) |
154 LLVM 23 llvm-mc vectors + 60,000 decoder fuzz cases |
| Total | 3 OS formats + archives + JSON/TOML | 73 | 19 | 131 tests, 193,200 fuzz cases (180k decoders + 13.2k parsers) |
Limitations
- RISC-V 64 currently targets little-endian ELF64 (
EM_RISCV = 243) andararchives; 32-bitRV32and big-endian binaries are out of scope. - Static decoding cannot prove whether runtime CPUID,
getauxval(AT_HWCAP), orriscv_hwprobeguards surround an instruction; runtime-dispatched functions should be scoped explicitly with--allow-symbol 'GLOB=FEAT,...'. - Packed or encrypted binaries (such as UPX-compressed executables) conceal their real instruction stream until unpacked at runtime.