Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159"""test_precompiled_kernel.py — guard the precompiled-kernel build step + prove thecanonical-kernel tests run the EXACT device bytes.
Two responsibilities, both creed-shaped (hunt, don't pass):
1. STALENESS GUARD (the trapnet for the build step). build/kernel.bin must match a fresh build (byte-identical). If a source file changed and the binary wasn't rebuilt, every canonical-kernel test would silently run against a stale artifact. This fails loud, telling you to `make kernel.bin`. Same ethos as test_size_budget's snapshot guardrail — a regenerating fixture that can't silently drift.
2. DEVICE-BYTES PROOF (the correctness win that motivated precompiling). The canonical-kernel tests build at base=0 (the device base). The firmware patcher injects the kernel at base=0x4690 (the cave's absolute address). Branch- bearing primitives encode differently per base, so the bytes differ — BUT the *branch-free* words (26 of 33) are byte-identical, and the patcher's build is the same source at a shifted base. This test pins the relationship: every branch-free word's bytes in the test image (base=0) equal its bytes in the cave image (base=0x4690). If that ever stops holding, the tests are no longer running device-representative bytes and the precompile's whole point is gone."""import osimport pytest
from src.kernel_image import BIN_PATH, MAP_PATH, load_canonical_kernelfrom src.build_kernel import build as build_fresh
pytestmark = pytest.mark.skipif( not os.path.exists(BIN_PATH), reason=f"{BIN_PATH} not built — run `make` (or `uv run python -m src.build_kernel`)")
class TestStalenessGuard: """build/kernel.bin must match a fresh build. A stale binary silently invalidates every canonical-kernel test."""
def test_binary_matches_fresh_build(self): """The on-disk binary must be byte-identical to a fresh build. If a source changed and `make` wasn't rerun, this fails — telling you to rebuild, not to debug a phantom test failure.""" on_disk = open(BIN_PATH, "rb").read() fresh_image, _, _ = build_fresh(base=0) assert on_disk == fresh_image, ( f"{BIN_PATH} is STALE — it doesn't match a fresh build. " f"Rebuild it:\n make force (or: uv run python -m src.build_kernel)")
def test_map_matches_fresh_build(self): """The on-disk address map must match a fresh build's map. A stale map means addr_map['quit_cfa'] etc. point at the wrong addresses.""" on_disk = open(MAP_PATH).read().strip() _, fresh_map, _ = build_fresh(base=0) import json fresh_text = json.dumps(fresh_map, indent=2, sort_keys=True) assert on_disk == fresh_text, ( f"{MAP_PATH} is STALE — doesn't match a fresh build's map. Rebuild:\n" f" make force")
def test_map_and_binary_agree_on_size(self): """The map's recorded size must match the binary's actual length. A mismatch means one was rebuilt without the other.""" image, addr = load_canonical_kernel() assert len(image) == addr["size"], ( f"binary is {len(image)}B but map says {addr['size']}B — rebuild " f"both together: `make force`")
def test_catch_the_bug_corruption_detected(self): """Negative control: a deliberately-corrupted binary must NOT match a fresh build (proves the staleness check isn't a no-op).""" on_disk = bytearray(open(BIN_PATH, "rb").read()) on_disk[100] ^= 0xFF # corrupt one byte fresh_image, _, _ = build_fresh(base=0) assert bytes(on_disk) != fresh_image, ( "corrupted binary matched fresh build — staleness check is broken")
class TestDeviceBytesProof: """The canonical-kernel tests (base=0) must run bytes representative of what ships in the cave (base=0x4690). Branch-free words are byte-identical across bases; branch-bearing words differ. Pin both facts."""
def test_only_address_embedding_words_differ_across_bases(self): """A word's assembled bytes may legitimately differ between the base=0 test image and the base=0x4690 cave image ONLY if it embeds a base- relative code address. Two known mechanisms: (a) a branch/label (intra-word PC-relative — caught by the clang_asm classifier) and (b) a movw/movt pair that materialises an ABSOLUTE code address like DOCOL or EXIT (NOT caught by the classifier — that false-negative is exactly what this test guards, since `:` and `;` bake in DOCOL/EXIT).
Everything else must be byte-identical. If a word that embeds no code address ever starts differing across bases, the canonical-kernel tests are no longer running device-representative bytes and the precompile's whole point collapses — fail loud, naming the offender.
Empirically (and what this test pins): every word that does NOT embed a code address is byte-identical; the only differing words are `:` and `;` (DOCOL/EXIT materialisers). The classifier's blind spot is the dragon; this test is the trapnet for it.""" from src.firmware_patcher import CAVE_OFF from src.clang_asm import _is_base_sensitive
def word_bytes(image, m, name, base): info = m["words"][name] off = info["addr"] - base # absolute addr -> image-relative offset return bytes(image[off:off + info["size"]])
test_image, test_map, _ = build_fresh(base=0) cave_image, cave_map, _ = build_fresh(base=CAVE_OFF)
# Words that materialise absolute code addresses without a label/branch. # : and ; both do `movw/movt r, #DOCOL_or_EXIT_addr`. Keep this list # DELIBERATE and named: if a new word joins it, that's a classifier # regression — investigate, don't append blindly. EMBEDS_CODE_ADDR = {":", ";"}
unexpected_diff = [] # words that differ but embed NO code address unexpected_same = [] # branch-bearing words whose bytes somehow match for name in test_map["words"]: cave_info = cave_map["words"].get(name) if cave_info is None: continue # new word, not in both tb = word_bytes(test_image, test_map, name, 0) cb = word_bytes(cave_image, cave_map, name, CAVE_OFF) src = test_map["sources"].get(name, "") embeds_addr = (name in EMBEDS_CODE_ADDR) or _is_base_sensitive(src) if (tb == cb) and embeds_addr: unexpected_same.append(name) elif (tb != cb) and not embeds_addr: unexpected_diff.append(name)
assert not unexpected_diff, ( "words that embed no code address differ across bases — the " "canonical-kernel tests are NOT running device-representative " f"bytes: {unexpected_diff}. Either the word gained a hidden code " "address (add to EMBEDS_CODE_ADDR with a comment naming it) or the " "build is genuinely broken.") # We do NOT assert unexpected_same is empty: a branch to an in-word # label can assemble identically at both bases when the relative offset # happens to be invariant. That's benign. The dangerous case is a # differing branch-free word, which is caught above.
def test_kernel_fits_cave(self): """The precompiled kernel must fit the 6.5KB cave (sanity).""" image, addr = load_canonical_kernel() assert addr["size"] <= addr["cave_budget"], ( f"kernel {addr['size']}B > cave budget {addr['cave_budget']}B")
def test_addresses_are_base_zero(self): """The canonical-kernel binary is built at base=0: NEXT must be at addr 0, and QUIT/INTERPRET must be at their offset addresses (not shifted by a base). Pins that the tests aren't accidentally running a base=0x100 image.""" _, addr = load_canonical_kernel() assert addr["base"] == 0, f"kernel map base is {addr['base']}, expected 0" assert addr["next_abs"] == 0, ( f"NEXT at 0x{addr['next_abs']:x}, expected 0x0 (base=0)")