# Handoff: build `arm7tdmi-python`, the Game Boy Advance's CPU core > **Historical (2026-10-21), kept as the build's record.** The core is built. > Since 2026-11-19 the family charter's rule governs: GPL, LGPL and MPL source > (NanoBoyAdvance, mGBA, MAME's GPL files) is **run as a closed box, never > read**, and what such a run shows is tagged OBSERVED. Where this brief names > those trees, read "build and run", not "open". docs/provenance.md "Wave 2" > records what was rewritten. ## Context you are inheriting The family's shape is **chips are cores, boards compose cores**. Each core is certified on its own against its oracles and pinned by the boards that use it. This core's first user is `gba-python` (`/data/emu/gba-python`, being prepared in parallel); later users could be the Nintendo DS's ARM7 side and arcade boards with an ARM7TDMI. A board that finds a corner of this core raises it **on the core** (an issue or a PR here; re-certification is fine), never as a workaround in the board. Models for the code and the tooling: - `z80-python` (`/data/emu/z80-python`, v0.4.0 on PyPI): the readability contract (one instruction family per module, one mnemonic per handler docstring, the hardware reason as a comment on the line that encodes it), the tooling bar (`state.py`, `disasm.py`, `debug.py`, `trace.py`, `console.py`, `python -m`), `docs/` layout, oracle tiers. - `6502-python` (`/data/emu/6502-python`): **every CPU cycle is one bus callback, in chip order**. - `sm83-python` (`/data/emu/sm83-python`): the same plus **internal cycles as callbacks with the address the CPU drives**, the closest model for this core's contract; its `docs/handoff-brief.md` is the template of this one. - `m6800-python` (`/data/emu/m6800-python`): the rung ladder, a generated opcode map, scripts that drive referees. The user's rules that bind this work: - **Oracle tiers**: hardware-captured > hardware-corrected > emulator-derived; manufacturer documentation is stated as such and loses to hardware where they disagree; a low-tier oracle is a detector, never a judge; state the tier of every claim. - **Python floor 3.11** (the newest PyPy supports): `requires-python = ">=3.11"`, ruff `target-version = "py311"`, CPython and PyPy both green. - **Reference cores are correct, not fast.** A `-fast` fork is later work. - **Modern over compat**: callables, dataclasses, no shims. - **No dangerous-looking shell one-liners** in scripts or docs (no `rm -rf`, `sed -i`); keep CI minimal (PyPy only, main + PRs, cancel in progress) if and when a GitHub repository exists. This repository is **local git only** until rung 3 passes ("Decided by the user" 6). ### Read, in this order, before writing code 1. `README.md`. 2. `docs/start-here.md`: registers and banks, the two instruction sets, the pipeline and what PC reads as, the four cycle types, exceptions, what the core does not own. 3. `docs/timing.md`: every instruction class as a sequence of N, S, I cycles with address and width, converted from the TRM's tables. 4. `docs/undocumented-behavior.md`: items U1–U21, contradictions C1–C11. 5. `docs/validation.md`: every oracle with tier and pin; what ran here; the rungs. 6. `/data/emu/sm83-python/docs/handoff-brief.md` and `/data/emu/z80-python/docs/start-here.md` ("The embedding contract"). Then `python scripts/fetch_references.py` (4 documents, 12 repositories, about 1 GB of which the SingleStepTests corpus is 840 MB), `python scripts/build_referees.py` (NanoBoyAdvance's ARM core as a referee, 20 s with g++) and `python scripts/referee_sst.py` to see the measured agreement for yourself. ## Decisions already made - **Name `arm7tdmi-python`**, import package `arm7tdmi_python`, class `ARM7TDMI`. The CPU is the ARM7TDMI core (architecture ARMv4T); the GBA's "CPU" chip (AGB CPU) is a system-on-a-chip around it, and everything outside the core belongs to `gba-python`. - **No coprocessor.** The GBA ties CPA and CPB high, so every coprocessor instruction except CP14 MRC/MCR takes the undefined-instruction trap (TRM 4.6). There are no C cycles on the GBA's bus. The core still decodes CDP/LDC/STC/MCR/MRC so the trap happens with the right cycle sequence; a later coprocessor hook is an extension, not this build. - **No debug logic.** EmbeddedICE, scan chains and DBGRQ are out of scope. CP14's register transfers exist on the die (TRM 4.6, U17) and are modelled only as far as the hardware test in validation.md shows. - **Little-endian only.** The GBA ties BIGEND low. Big-endian is not built. - **Fetch-first `step()`**: a step is one instruction as the TRM's tables count it: from the cycle that fetches `pc+2L` (the prefetch that overlaps the instruction's first execute cycle) to the instruction's last cycle. The pipeline (two fetched opcodes) is core state, as it is in the corpus. This is how SingleStepTests ARM7TDMI and NanoBoyAdvance count, so their cases compare cycle for cycle (timing.md "How to read the tables"). ## The bus contract (required) One callback per bus cycle, in chip order, **including internal (I) cycles**: ```python cpu = ARM7TDMI(read, write, idle) # read(address, width, access) -> int one N or S cycle that reads # write(address, width, value, access) one N or S cycle that writes # idle(address) one I cycle: no transfer; address is # what the CPU drives (timing.md); also # CP14's C cycles, with # cpu.coprocessor_cycle true (U17) # width is 8, 16 or 32 (MAS[1:0]); value and the returned data are that wide. # access is a bit set: # SEQ = 1 the cycle is sequential (S), else nonsequential (N) [SEQ pin] # CODE = 2 an opcode fetch [nOPC low] # LOCK = 8 a locked cycle: SWP's read and write (C10) [LOCK pin] # (bit 2 is left free for a board's own use, such as DMA) # cpu.cpsr, cpu.privileged (nTRANS), cpu.thumb (TBIT) are readable inside # callbacks, as the pins are. cycles = cpu.step() # cycles == number of callbacks made ``` - The **address is the one the core drives**, unaligned bits included: an `LDR` from `0x03000001` reads `(0x03000001, 32, N)` and the core rotates the word it gets back (U1); a `STR` to `0x03000002` writes there with width 32. Forcing alignment is the memory system's job: the GBA's bus ignores the low bits (GBATEK "ARM CPU Memory Alignments"), and the board does that. Opcode fetches are the exception: their address is R15 with its low bits cleared (C3). - **The core is exact in cycle types; the board turns them into clocks.** The core never counts waitstates, never models the GBA's prefetch buffer, and never knows a memory map. Each callback is one CPU cycle plus whatever waitstates the board decides; the board advances its devices inside the callbacks, never by adding `step()`'s return value on top. - **`SEQ` follows the TRM, including merged IS cycles.** After an I cycle the next fetch is S at the address the I cycle drove (TRM 3.3.4; timing.md). The GBA's memory controller does not honour that merge: NanoBoyAdvance, mGBA and the SingleStepTests corpus all time that fetch as N, and they pass the hardware-captured timing tests (validation.md). The board, which sees the preceding `idle()`, applies that rule; the core reports the pin. The rule is written once, as `arm7tdmi_python.gba_access(access, after_idle)`, which returns the access with SEQ cleared after an I cycle; the rung-1 comparison and gba-python both call it. The user confirmed this split (decision 1). - `idle`'s address: the TRM shows the address the CPU puts out during each I cycle (`pc+3L` after a register-specified shift, a multiply, a load). Pass it. The GBA does not decode it as far as anyone has shown, but the next fetch starts there, and a future board might care. - **Interrupts are levels the board drives**: `cpu.irq` and `cpu.fiq` (True = the line asserted, i.e. nIRQ/nFIQ low). The board may change them inside any callback. The core samples them **at the start of each `step()`**, which is the end of the previous instruction (TRM 2.8.4, 2.8.5: "at the end of each instruction"). The core does not model the input synchronizer: the board delays its line by however much the hardware tests show (the GBA's IRQ delay is a board measurement). A line is masked only if its I/F bit was set both when the previous instruction **started** and when it **ended** (U14): clearing I or F acts at once, setting it acts one instruction late (TEST ROM: alyosha-tas `psr` judges the late set, `irq/IRQ_sub` and `IRQ_sub_slow` the prompt clear, both on gba-python's board; DOC: TRM 2.8.4, the sample at the end of each instruction; F follows I by analogy, HYPOTHESIS). An accepted IRQ or FIQ makes that `step()` the exception entry (fetch, N at the vector, S at vector+4: timing.md "Exceptions"), not an instruction. - **Halting is the board's.** The GBA's HALTCNT stops the CPU clock; the board simply stops calling `step()` until an interrupt. There is no halted state in the core. A board that wants the cycles counted calls nothing. - **Reset**: `cpu.reset()` enters supervisor mode, ARM state, I and F set, PC at 0 (TRM 2.10), and the next `step()` makes the two refill fetches (N at 0, S at 4) before executing. The GBA's BIOS is loaded by the board. - **State for the harness**: `cpu.state` is a dataclass with R0–R15 (the current mode's view), the six banks, CPSR, five SPSRs, the two pipeline opcodes and `next_fetch_seq` (whether the next fetch is S). It loads from and saves to the SingleStepTests layout (validation.md "The corpus's state layout": R8–R14 there are always the user bank). - Keep the contract transcribable: plain integers, no generators or coroutines in the hot path, so `arm7tdmi-rust` and `-fast` forks can copy it. ## Your task Build `src/arm7tdmi_python/` to the contract above and pass the rungs in [validation.md](validation.md) "The plan", in order. In summary: 0. **Tables and the schedule test.** Decode tables for ARM (the 12-bit `bits[27:20]:bits[7:4]` index the referees use) and Thumb (`bits[15:6]`), generated, with every entry naming its handler; a readability test (one mnemonic per handler docstring). A per-class bus-schedule test generated from timing.md's tables: for each class and path, the sequence of (type, address, width) the core produces equals the TRM's. 1. **SingleStepTests ARM7TDMI**, 45 files × 50,000 cases: registers, all banks, CPSR, SPSRs, pipeline, `next_fetch_seq`, and every transaction's kind, width, address, write data and N/S/code/lock bits, in order. The corpus has no I cycles; compare the core's sequence with I cycles removed, and compare the I cycles against the NBA referee (it records them). The corpus is emulator-derived (an older NBA), so agreement with the NBA referee is drift between revisions, not confirmation. validation.md sorts the 55,344 cases where it disagrees with today's NanoBoyAdvance into three classes: the core follows the corpus on C3 and C4, and C2 (which the corpus README lists as a known issue) is excluded as unverified. It lists the overrides where the core deliberately follows the TRM or hardware (C1, C5, the four CP14 encodings alyosha-tas tests, C10) and the other exclusions (untested CP14 encodings, `0xDExx` until a hardware test decides, decision 4). Rung 1 passes when every non-excluded case agrees after those overrides, which live in `tests/sst_overrides.json`, each with its reason; excluded cases are reported as a count, never as passes. 2. **jsmolka `arm.gba` and `thumb.gba`** in the minimal harness (below): r12 is 0 when the result screen is reached. 3. **alyosha-tas tests that need no timer** in the harness: its `arm/arm.gba` (jsmolka's with changed `data_processing` and `psr_transfer`) and `thumb/blx.gba`, `thumb/cpy.gba` (hardware tests of U19). Its `psr`, `LDM/*`, `Coprocessor_14` and `Push/Pop_no_regs` use timers or IRQs: rung 5. 4. **The multiply model as judge** (no harness needed, so it gates alongside rung 1): MUL/MLA/UMULL/SMULL/UMLAL/SMLAL results, C and `m` against zayd's model (`reference/build/mul_model.so`, which already agrees with every corpus multiply) on 10^6 random and edge operands per form. 5. **Through the board**: gba-python's milestone that runs ARMWrestler, FuzzARM's ROMs, mGBA suite (`carry`, `multiply-long`, `shifter`, `timing`) and the alyosha-tas timer-based tests certifies what only a board can exercise. Its failures that are the core's come back here as issues or PRs. ### The minimal harness (`arm7tdmi_python.harness`) A host that is not a GBA, for rungs 2–3 and the CLI: ROM at `0x08000000` (mirrored as the cartridge is), 256 KiB at `0x02000000`, 32 KiB at `0x03000000`, I/O at `0x04000000` as plain RAM except `DISPSTAT` (`0x04000004`) whose bit 0 (VBlank) toggles on every read so jsmolka's `m_vsync` completes, VRAM/palette as RAM. Start in System mode, ARM state, at `0x08000000`, with SP_sys `0x03007F00`, SP_irq `0x03007FA0`, SP_svc `0x03007FE0` (the values the GBA BIOS leaves, GBATEK "BIOS RAM Usage"). Stop on a branch to itself. Report r12. No BIOS: an SWI in a harness test is an error. ### Tooling at the family bar `state.py` (as above), `disasm.py` (ARM and Thumb, sharing the generated tables; check against MAME's or mGBA's disassembly of the same words), `debug.py` (`DebugSession` with breakpoints, bus watchpoints that see I cycles too), `trace.py` (JSONL, the family schema with `kind` = read, write, internal, plus `width` and `access`), `console.py`, `py.typed`, and `python -m arm7tdmi_python ROM.gba [--max-cycles N] [--trace out.jsonl]` running a ROM in the harness and printing r12. ## Decided by the user (2026-10-21) The user accepted every recommendation. Build to these; raise new evidence against one as an issue rather than changing it silently. 1. **Merged IS.** The core reports the TRM's S on the fetch after an I cycle. The board converts it to N, and rung 1 maps it when comparing to the corpus; both call the one helper `arm7tdmi_python.gba_access`, so the rule is written once. No constructor flag. 2. **SingleStepTests is the rung-1 gate, as a detector.** Use it with the override file (validation.md), and call it a detector in every claim. 3. **CP14 MRC/MCR (C6) follow the hardware test.** Override only the corpus cases with the four encodings alyosha-tas's `Coprocessor_14` exercises; exclude the rest of the 1,500 as unverified. 4. **Thumb `0xDE00–0xDEFF` and `0xE800–0xEFFF` (C7, C8).** The core takes the undefined trap for both ranges, provisionally (ARM's rule; mGBA and ares agree, NBA and the corpus do not). The corpus's 50,000 `DExx` cases are excluded from the gate. Write a small hardware test ROM covering both ranges for the user to run on a GBA; its result decides, and overrides the provisional choice. 5. **Undefined-instruction trap timing (C5).** The TRM: an I cycle before the vector fetch (2S+N+I). The board's timing tests can revisit it. 6. **GitHub.** Local until rung 3 passes, then public like the other cores.