Single-pass compatibility matrices, linker quirks, and 642x profiling wins
Synthetic unit tests keep parsers honest on small fixtures, yet production inputs expose two failure modes that small tests hide. First, real toolchains emit valid binary layouts that contradict textbook assumptions. Second, quadratic bookkeeping and repeated parse passes stay invisible on ten-line files and blow up as soon as a tool faces 42,000 XML elements, 80,000 CSV rows, or 1,844 shared libraries in /usr/lib.
While shipping single-pass compatibility matrices and running oa benchmarks across three zero-dependency Rust tools, profiling real corpora surfaced a genuine LLD and mold DT_VERDEF bug, removed a 642x quadratic XML parser cliff, cut peak memory by up to 67.4% in streaming statistics, and replaced N-pass CI shell loops with single-pass compatibility matrices. Every speedup below was verified with oa compare --pairs 9 --warmup 2 --check-output --metric pareto and bit-for-bit identical output SHA-256 hashes.
isa-audit matrix and bincompat matrix separate expensive artifact decoding from cheap policy evaluation so N target checks pay the parse cost once.
1. Profiling 1,844 real DSOs caught an LLD and mold DT_VERDEF bug
Before benchmarking bincompat exports, I pointed it at every ELF64 shared library under /usr/lib on an Arch Linux workstation: 1,844 real production DSOs compiled with GCC, Clang, GNU ld, LLD, and mold. Our unit tests, 1,600+ fuzz inputs, and GNU nm/readelf parity checks on libc.so.6, libm.so.6, libz.so.1, and libstdc++.so.6 had all passed.
On the full /usr/lib corpus, three libraries immediately tripped BincompatError::CorruptVerdef with a cycle diagnostic at byte offset 40 inside .gnu.version_d: libgallium-26.2.5-arch3.1.so, libjansson.so.4.15.1, and libjson-glib-1.0.so.0.1000.8. None of those libraries was corrupt. Inspecting their SHT_GNU_VERDEF tables showed why: GNU ld emits a fresh Elf64_Verdaux chain for each Elf64_Verdef entry, whereas LLD and mold deduplicate identical parent Elf64_Verdaux records across separate Elf64_Verdef entries to save bytes.
In bincompat/src/elf.rs, both parse_verdef_from_source() (used for section-stripped PT_DYNAMIC binaries) and parse_verdef_section() had allocated one table-wide visited_aux: SmallVisited set outside the Verdef loop. The second version entry pointing into a shared Verdaux tail looked like a cycle even though each individual entry's parent chain remained acyclic. Moving visited_aux inside each Verdef iteration in bincompat#28 fixed all three system libraries while keeping genuine intra-entry cycle rejection intact:
let mut visited_verdef = SmallVisited::new();
let mut vd_rel = 0u64;
for vd_idx in 0..verdef_num {
// ... validate Verdef header and detect Verdef-list cycles ...
let mut name = String::new();
let mut parents = Vec::with_capacity(usize::from(vd_cnt.saturating_sub(1)));
// Track visited aux offsets per Verdef entry: linkers like LLD and mold
// legally deduplicate identical Elf64_Verdaux records across Verdef entries.
let mut visited_aux = SmallVisited::new();
for aux_idx in 0..vd_cnt {
if !visited_aux.insert(aux_rel) {
return Err(BincompatError::CorruptVerdef { /* ... */ });
}
Regression tests in tests/exports_and_verdef.rs now construct both sectioned and section-stripped ELF64 binaries with shared Elf64_Verdaux offsets alongside true cyclic chains so the parser cannot regress on either path.
2. Eliminating a 642x quadratic XML parser cliff and cutting stats RSS by 67%
In convto#31 (shipped in convto v0.7.0), profiling a 1.5 MB XML fixture with 42,000 elements immediately turned up a single line dominating wall time: convto fmt --stdout took 14,815.50 ms. Inside src/data.rs, XmlParser::parse_element() computed let open_line = self.line_at(self.pos); at the top of every opening tag so error messages could cite the element's starting line.
Because line_at(pos) scanned the prefix &self.bytes[..pos] counting newline bytes on every element, parsing 42,000 elements turned linear work into an O(N^2) sweep over roughly 30 billion bytes. Deferring line calculation strictly to error paths removed the quadratic cliff completely. While touching XmlParser, I also replaced owned String tag, attribute, and child keys with borrowed &'a str slices, switched duplicate-attribute and repeated-child maps to lazy Option<HashSet> / Option<HashMap> promotion at 16 entries, added ASCII byte fast paths for XML identifiers, and added an element-only fast path in write_xml_element():
fn parse_element(&mut self) -> Result<(&'a str, Value), String> {
let open_pos = self.pos;
self.depth += 1;
if self.depth > MAX_NESTING_DEPTH {
return Err(format!(
"XML line {}: maximum nesting depth ({MAX_NESTING_DEPTH}) exceeded",
self.line_at(open_pos)
));
}
self.pos += 1;
let tag_name = self.parse_name()?;
let mut attrs: Vec<(&'a str, Value)> = Vec::new();
let mut seen_attrs: Option<HashSet<&'a str>> = None;
Wall time on the 42,000-element XML workload dropped from 14,815.50 ms to 23.05 ms (642.26x faster, 95% CI [624.18x, 689.09x], p = 0.0004) with identical SHA-256 output.
In the same PR, profiling convto stats --json on 80,000 CSV rows (4.9 MB) and 60,000 JSONL records (8.8 MB) pointed to two different costs: materializing the entire parsed AST in memory before summarizing, and calling format!() on every cell to insert into one string HashSet for distinct-value counts. Replacing that generic set in src/stats.rs with typed zero-allocation buckets (a u8 bitmask for booleans, HashSet<i64> for integers, HashSet<u64> for float bits, and HashSet<String> only for strings) plus direct streaming readers (for_each_delimited_row and for_each_jsonl_value) doubled throughput while cutting peak RSS by 63.4% on CSV and 67.4% on JSONL.
3. Batch bincompat exports across 1,844 shared libraries
After fixing the LLD/mold DT_VERDEF parser bug, profiling bincompat exports -r /usr/lib across all 1,844 DSOs (190.9 MB of text output, 205.4 MB of JSON output) exposed three bottlenecks in src/elf.rs and src/exports.rs:
exportscalled the full ELF analyzer, parsingDT_VERNEEDimports,PT_GNU_PROPERTYnotes, and stack-canary checks that the exports renderer threw away. AddingInternalAnalyzeConfiglets export-only runs parse only SONAME,.dynsym,.gnu.version, and.gnu.version_d.- Rendering allocated a new
qualified_name()Stringper symbol to measure column width and write lines, and escaped JSON strings character by character. Adding a zero-allocationqualified_name_len()helper, direct buffer writes, a 256-entry JSON escape lookup table, and compiled ASCII wildcard matching for--filterremoved the per-symbol allocation churn. - Collecting all 1,844
BinaryAnalysisstructs in memory before formatting kept peak RSS high. Formatting each library into worker-local chunks and droppingBinaryAnalysisimmediately cut peak memory by 23.9% to 64.5%.
Tool & workload (--check-output) |
Before -> After | Speedup (p) |
Peak RSS |
|---|---|---|---|
convto fmt --stdout (1.5 MB XML, 42k elems) |
14,815.50 -> 23.05 ms | 642.26x (0.0004) |
Pareto clean |
convto stats --json (4.9 MB CSV, 80k rows) |
115.07 -> 52.14 ms | 2.12x (0.0004) |
76,136 -> 27,872 KiB (-63.4%) |
convto stats --json (8.8 MB JSONL, 60k rows) |
95.96 -> 50.02 ms | 1.90x (0.0004) |
61,852 -> 20,180 KiB (-67.4%) |
convto fmt --stdout (1.8 MB ENV, 30k keys) |
26.38 -> 25.02 ms | 1.06x (0.0036) |
Pareto clean |
bincompat exports text (1,844 DSOs, 190.9 MB) |
527.54 -> 150.78 ms | 3.47x (0.0004) |
-42.0% |
bincompat exports JSON (1,844 DSOs, 205.4 MB) |
424.13 -> 173.69 ms | 2.40x (0.0004) |
-23.9% |
bincompat exports --filter '*init*' (1,844 DSOs) |
527.95 -> 59.84 ms | 8.96x (0.0004) |
-64.5% |
All seven rows ran oa compare --pairs 9 --warmup 2 --check-output --metric pareto with bit-for-bit identical stdout SHA-256 hashes between baseline and candidate binaries.
4. Single-pass compatibility matrices and bounded static archives
Release engineers rarely want a binary yes/no answer for one target alone. They want to know the oldest CPU profile or Linux distribution a build actually supports, and which exact instruction or symbol blocks the next older tier. Wrapping isa-audit check or bincompat check in a shell loop over 15 or 19 targets works, but it re-reads and re-decodes every executable byte N times.
In isa-audit v0.9.0 (#30, #31), I extended container loading to 64-bit Windows COFF .obj and MSVC/LLVM .lib static archives in src/pe.rs (covering AMD64 0x8664 and ARM64 0xAA64 while skipping short Windows import stubs starting with 0x0000 0xFFFF) and added a hard DoS cap of MAX_ARCHIVE_MEMBERS = 100_000 (ArchiveError::TooManyMembers) in src/archive.rs backed by 1,500 mutated archive and COFF64 fuzz inputs. On top of that single decode pass, isa-audit matrix (src/matrix.rs) evaluates every built-in profile for the binary's architecture plus custom [profiles.<name>] entries from isa-audit.toml and reports minimum_profile. Recording per-feature suppression counts in src/analyzer.rs during the single decode pass lets --allow-symbol and --ignore-ifunc flip affected profiles from FAIL to PASS with zero extra disassembly.
bincompat matrix (src/matrix.rs in bincompat#28) follows the exact same separation. It parses each ELF64 file, recursive directory tree, or --tree transitive dependency closure once, evaluates all 15 built-in Linux distro baselines (14 glibc targets from centos-7 to ubuntu-26.04 plus alpine/musl) with full --config, --allow-symbol, --ignore-weak-symbols, and hardening flags, and emits supported_targets, oldest_glibc_target, and blocking BC001 to BC016 rule IDs across Text, JSON, Markdown, and self-contained dark/light HTML reports.
5. Reproduce locally
# Single-pass CPU compatibility matrix across ELF64, Mach-O/Fat, PE32+, and COFF64 .lib
isa-audit matrix ./dist/app --format markdown
isa-audit matrix ./build/libcore.lib --ignore-ifunc --format html -o isa-matrix.html
# Single-pass 15-distro compatibility matrix (including transitive --tree closure)
bincompat matrix ./dist/app --tree --require-hardening --format html -o distro-matrix.html
# Streaming Kahan-summed stats and Draft 2020-12 schema inference across 9 formats
convto stats ./benchmarks.jsonl --json
convto schema ./benchmarks.jsonl --strict
Limitations
isa-audit matrixandbincompat matrixinspect static binary metadata and executable sections; runtime CPU dispatch behind function pointers or dynamicdlopen()libraries remains invisible to static analysis.- In
convto stats, distinct-value tracking is capped at 100,000 unique values per column to keep streaming RSS bounded on multi-million-row inputs; overflow setsunique_capped: trueexplicitly instead of spilling to disk. - Single-pass
bincompat exportsfiltering relies on exact symbol and ASCII glob matching rather than regex engines to preserve zero external crates and predictable linear matching time.