use std::collections::HashMap;
use std::path::Path;
use std::process::Command;
use object::read::elf::ElfFile32;
use object::{Object, ObjectSection};
const GOLDEN_OFF_TEXT_FNV1A: u64 = 0xa68a_a2da_e5af_e4a7;
const GOLDEN_OFF_TEXT_LEN: usize = 576;
const GOLDEN_DEFAULT_TEXT_FNV1A: u64 = 0x9577_c583_bc14_5a46;
const GOLDEN_DEFAULT_TEXT_LEN: usize = 452;
fn synth() -> &'static str {
env!("CARGO_BIN_EXE_synth")
}
fn fixture() -> std::path::PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../..")
.join("scripts/repro/const_cse.wat")
}
fn compile(out: &str, cse: bool) -> Vec<u8> {
let mut cmd = Command::new(synth());
if cse {
cmd.env_remove("SYNTH_CONST_CSE");
} else {
cmd.env("SYNTH_CONST_CSE", "0");
}
let status = cmd
.args([
"compile",
fixture().to_str().unwrap(),
"-o",
out,
"-b",
"arm",
"--target",
"cortex-m4",
"--all-exports",
])
.status()
.expect("run synth compile");
assert!(status.success(), "synth compile failed (cse={cse})");
std::fs::read(out).expect("read ELF")
}
fn sections(elf: &[u8]) -> HashMap<String, Vec<u8>> {
let obj = ElfFile32::<object::Endianness>::parse(elf).expect("parse ELF");
let mut out = HashMap::new();
for sec in obj.sections() {
if let Ok(name) = sec.name()
&& !name.is_empty()
{
out.insert(name.to_string(), sec.data().unwrap_or(&[]).to_vec());
}
}
out
}
fn func_text_len(elf: &[u8], name: &str) -> usize {
use object::ObjectSymbol;
let obj = ElfFile32::<object::Endianness>::parse(elf).expect("parse ELF");
for sym in obj.symbols() {
if sym.name() == Ok(name) {
return sym.size() as usize;
}
}
panic!("symbol {name} not found");
}
fn compile_fixture(rel: &str, out: &str, cse: bool) -> Vec<u8> {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../..")
.join(rel);
let mut cmd = Command::new(synth());
if cse {
cmd.env_remove("SYNTH_CONST_CSE");
} else {
cmd.env("SYNTH_CONST_CSE", "0");
}
let status = cmd
.args([
"compile",
path.to_str().unwrap(),
"-o",
out,
"-b",
"arm",
"--target",
"cortex-m4",
"--all-exports",
])
.status()
.expect("run synth compile");
assert!(status.success(), "synth compile failed ({rel}, cse={cse})");
std::fs::read(out).expect("read ELF")
}
fn func_sizes(elf: &[u8]) -> HashMap<String, usize> {
use object::{ObjectSymbol, SymbolKind};
let obj = ElfFile32::<object::Endianness>::parse(elf).expect("parse ELF");
let mut out = HashMap::new();
for sym in obj.symbols() {
if sym.kind() == SymbolKind::Text
&& sym.size() > 0
&& let Ok(name) = sym.name()
{
out.insert(name.to_string(), sym.size() as usize);
}
}
out
}
fn corpus_offon(rel: &str, tag: &str) -> (HashMap<String, usize>, HashMap<String, usize>) {
let off = func_sizes(&compile_fixture(
rel,
&format!("/tmp/cse_{tag}_off.elf"),
false,
));
let on = func_sizes(&compile_fixture(
rel,
&format!("/tmp/cse_{tag}_on.elf"),
true,
));
for (name, &off_len) in &off {
let on_len = *on.get(name).unwrap_or(&off_len);
assert!(
on_len <= off_len,
"no function may grow under default const-CSE: {name} opt-out={off_len}B default={on_len}B ({rel})"
);
}
(off, on)
}
#[test]
fn const_cse_pr2_recovers_headroom_wins_without_growth_242() {
let (fs_off, fs_on) = corpus_offon("scripts/repro/flight_seam.wat", "fseam");
let (off, on) = (fs_off["flight_algo"], fs_on["flight_algo"]);
assert!(
on < off,
"PR2 must shrink flight_seam::flight_algo on headroom: off={off}B on={on}B"
);
let (s_off, s_on) = corpus_offon("scripts/repro/const_cse.wat", "spill");
let (off, on) = (s_off["spill12"], s_on["spill12"]);
assert!(
on < off,
"PR2 must shrink const_cse::spill12 (32-bit movw+movt hoist): off={off}B on={on}B"
);
assert!(
off - on >= 8,
"expected a real spill12 win (≥1 movw+movt pair, 8B), got {}B",
off - on
);
let (ff_off, ff_on) = corpus_offon("scripts/repro/flat_flight/flat_flight.loom.wasm", "flatf");
assert_eq!(
ff_on["flat_flight"], ff_off["flat_flight"],
"flat_flight is pressure-saturated (peak 11 > pool 9); the guard declines, so it stays equal"
);
}
fn fnv1a64(bytes: &[u8]) -> u64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for &b in bytes {
h ^= b as u64;
h = h.wrapping_mul(0x0000_0100_0000_01b3);
}
h
}
#[test]
fn const_cse_escape_hatch_restores_old_bytes_242() {
let off = compile("/tmp/const_cse_off.elf", false);
let text = sections(&off).remove(".text").expect(".text present");
assert_eq!(
text.len(),
GOLDEN_OFF_TEXT_LEN,
"opt-out .text length drifted from the pre-flip baseline"
);
assert_eq!(
fnv1a64(&text),
GOLDEN_OFF_TEXT_FNV1A,
"SYNTH_CONST_CSE=0 optimized-path .text drifted from the pre-const-CSE \
baseline — the opt-out is supposed to restore the pre-flip bytes; \
re-bless the golden ONLY if this was an intentional optimized-path \
lowering change"
);
}
#[test]
fn const_cse_default_matches_flip_golden_242() {
let on = compile("/tmp/const_cse_def.elf", true);
let text = sections(&on).remove(".text").expect(".text present");
assert_eq!(
(text.len(), fnv1a64(&text)),
(GOLDEN_DEFAULT_TEXT_LEN, GOLDEN_DEFAULT_TEXT_FNV1A),
"shipped-default optimized-path .text drifted from the flip golden — \
if intentional, re-run const_cse_differential.py on this commit and \
re-pin (they move together)"
);
}
#[test]
fn const_cse_on_shrinks_headroom_function_242() {
let off = compile("/tmp/const_cse_red_off.elf", false);
let on = compile("/tmp/const_cse_red_on.elf", true);
let off_len = func_text_len(&off, "large3");
let on_len = func_text_len(&on, "large3");
assert!(
on_len < off_len,
"const-CSE must shrink large3 on headroom: off={off_len}B on={on_len}B"
);
assert!(
off_len - on_len >= 8,
"expected ≥8B saved (≥1 movw+movt pair), got {}B",
off_len - on_len
);
}