""" kernel_image.py — Load the precompiled canonical kernel + its address map. Tests that exercise the canonical kernel (the image that ships in the cave) load build/kernel.bin instead of rebuilding. This makes clang a build-time concern only — `make kernel.bin` runs the assembler once; tests just read bytes. The companion build/kernel.map.json carries every word's absolute address, the colon cfas (INTERPRET/QUIT), HALT spin, and SRAM layout — everything a test previously read off a live `KernelBuilder` object (kb.words, kb.quit_cfa, etc.). Loading replaces rebuilding with zero loss of information. Use: from src.kernel_image import load_canonical_kernel image, addr = load_canonical_kernel() vm = ForthVM(image) quit_cfa = addr["quit_cfa"] # was kb.quit_cfa plus_addr = addr["words"]["+"]["addr"] # was kb.words["+"][0] """ import json import os BUILD_DIR = os.path.join(os.path.dirname(__file__), "..", "build") BIN_PATH = os.path.join(BUILD_DIR, "kernel.bin") MAP_PATH = os.path.join(BUILD_DIR, "kernel.map.json") def load_canonical_kernel(): """Load build/kernel.bin + build/kernel.map.json. Returns (image_bytes, addr_map). Raises FileNotFoundError with a hint to `make kernel.bin` if the artifacts are missing.""" if not os.path.exists(BIN_PATH): raise FileNotFoundError( f"{BIN_PATH} not found — build it first:\n" f" make # from the project root\n" f" or: uv run python -m src.build_kernel") with open(BIN_PATH, "rb") as f: image = f.read() with open(MAP_PATH) as f: addr_map = json.load(f) return image, addr_map class KernelMap: """Adapter that exposes the address map with the SAME attribute surface a live `KernelBuilder` object offers to tests — so tests can switch from rebuilding (kb = KernelBuilder(...); kb.words, kb.quit_cfa) to loading (km = KernelMap(addr_map); km.words, km.quit_cfa) with no call-site changes. Attributes mirrored (the read-only ones tests use): words : {name: (addr, body_bytes)} ← note: reconstructs body_bytes from the image so tests that read body length still work colon_addrs : {name: cfa_abs} entries : {name: cfa_abs} interpret_cfa, quit_cfa, halt_cfa, halt_spin : int next_addr : int (alias of the map's size — the used-image length) NOT mirrored: the build_* / add_* / lay_entry methods (those are build-time only; if a test needs them it must build live, not load).""" def __init__(self, addr_map, image): self._map = addr_map self._image = image # Reconstruct words as {name: (addr, body_bytes)} — tests read # kb.words[name][0] (addr) and len(kb.words[name][1]) (size). The map # stores addr+size, so slice the image to recover body_bytes. self.words = { name: (info["addr"], image[info["addr"]:info["addr"] + info["size"]]) for name, info in addr_map["words"].items() } self.colon_addrs = dict(addr_map["colon_addrs"]) self.entries = dict(addr_map["entries"]) # Canonical ASM source for every code word (mirrors KernelBuilder.sources). # Loaded from the map so tests using the precompiled kernel get the same # single-source-of-truth bodies as a live build. See build_kernel.build. self.sources = dict(addr_map.get("sources", {})) self.interpret_cfa = addr_map["interpret_cfa"] self.quit_cfa = addr_map["quit_cfa"] self.halt_cfa = addr_map["halt_cfa"] self.halt_spin = addr_map["halt_spin"] self.next_addr = addr_map["size"] # code is the working bytearray in a live builder; tests that index # kb.code (offset-indexed) get the image bytes. Rare; provided for # compatibility. self.code = bytearray(image) def load_kernel_map(): """Load the canonical kernel and return (KernelMap, image_bytes). The KernelMap mirrors the KernelBuilder read-surface tests use, sourced from the precompiled address map. Drop-in for the old `kb, image = _build()` pattern.""" image, addr_map = load_canonical_kernel() return KernelMap(addr_map, image), image