# hg51b-python A readable, pure-Python **Hitachi HG51B169** core, instruction-exact: the SNES **Capcom Cx4** in *Mega Man X2* and *Mega Man X3* (*Rockman X2/X3*). A 24-bit CPU with 16-bit instructions that fetches its program from the cartridge ROM into a two-page cache, with a 24 x 24 multiplier, sixteen 24-bit registers, 3 KiB of data RAM, a 3 KiB data ROM of math tables, a DMA engine and its own ROM bus. Its first user is the board `snes-python` (milestone 7: "Cx4 self-test PASS"). **Status (2026-11-19): core built; rungs 0-4 of [docs/validation.md](docs/validation.md) passed; provenance rewrite (Wave 2) done: [docs/provenance.md](docs/provenance.md).** Decode of all 65,536 words as byuu's table (ares, ISC); directed tests per family, each naming its U/C entry; the data ROM computed from fullsnes' formulas equals a real chip's dump (SHA-1 a002f4ef...); **the games' own built-in Cx4 test passes all eight items** in the board-free harness on Mega Man X2 and X3 (every retail region), with the expected values read out of each cartridge's 65816 test code; five Mesen2 2.1.1 windows (boot, the test, X2's title, X2's intro stage, X3's title) replay in lockstep from power-on with **no instruction divergence** (rung 4 numbers in validation.md). Rung 5 (HLE comparison) is a follow-up; rung 6 is snes-python's. No dependencies, CPython and PyPy (Python 3.11+). Correct, not fast. Local git only. **There is no manufacturer document, hardware capture, test ROM with console results or die model for this chip.** The judges are the games' own built-in Cx4 test (hold controller 2 B at power-on), a real chip's data ROM dump (reproduced exactly by formula), research (fullsnes) and emulator-tier detectors: Mesen2 runs here as a closed box, traces the Cx4 and runs homebrew probe cartridges (`scripts/cx4_probe.py`); byuu's model is read in its ISC form, ares; MAME is HLE only. GPL and unlicensed sources (bsnes, Mesen2, snes9x, MAME's Cx4, MiSTer) are closed boxes: run, never read. [docs/validation.md](docs/validation.md) ranks them; [docs/claims.md](docs/claims.md) says how strongly each behaviour is claimed. ```python from hg51b_python import HG51B, data_rom cx4 = HG51B( bus_read=lambda address: rom_byte(address), # the chip's ROM/SRAM bus: 24-bit address -> byte bus_write=lambda address, value: None, # SRAM writes (none fitted on Cx4 boards) data_rom=None, # None: computed (U21); or load_data_rom(path) ) cx4.reset() # power-on state (U20); keeps the data RAM (C15) cx4.run(clocks) # advance by chip clocks; returns the instructions executed cx4.read(0x7F5E) # S-CPU read of $6000-$7FFF (bank ignored); no side effect cx4.write(0x7F4F, 0x89) # S-CPU write; $7F47/$7F48/$7F4F start DMA/preload/program when halted cx4.irq # /IRQ asserted (U13) cx4.owns_rom_bus # a cache load, DMA or bus access in flight (U16) cx4.vector(0x0A) # the byte the S-CPU reads at $00:FFEA while owns_rom_bus cx4.data_ram # 3,072-byte bytearray state = cx4.capture_state() # CPUState: registers, I/O, cache, DMA, bus, memories cx4.restore_state(state) ``` The contested behaviours (C1-C18 in [docs/undocumented-behavior.md](docs/undocumented-behavior.md)) are class attributes with byuu's choice (ares) as default (decision 4): `SHIFT_LIMIT`, `STACK_MODEL`, `MUL_LATENCY`, `BUS_DELAY_EXTRA`, `INTERNAL_ACCESS_COST`, `CLEAR_IS_NOP`, `LD_P_SOURCE`, `STATUS_MIRROR`, `OPERAND_00_READS_A` (default: fullsnes), `FAR_SELECT`, `IRQ_DISABLE_SETS_FLAG`, so a comparison flips one without editing code. Every other position is a closed-box Mesen2 observation (OBSERVED, cited to its probe) or a document's reading. C2, C3 and C9 have no switch since Wave 2 (the old alternatives rested on reading Mesen2's and MiSTer's sources). Tooling, at the family's bar: `CPUState`, `disasm` (byuu's mnemonics), `DebugSession` (breakpoints on PB:PC, data RAM, S-CPU and bus-read watchpoints), JSONL traces (instruction, S-CPU access, cache load, DMA), a command debugger that can also act as the S-CPU, the `harness` (the games' driver and their built-in test), the Mesen2 `replay`, and: ```sh python -m hg51b_python "Mega Man X2 (USA).zip" # the built-in test python -m hg51b_python CART --test-function 0E:54 --r0 0x123456 # one routine python -m hg51b_python CART --test-function 0E:89 --trace run.jsonl python -m hg51b_python CART --test-function 0E:40 --debug -c "step 8" -c registers python -m hg51b_python CART --replay tests/mesen_traces/x2-play # rung 4 ``` ## Setting up ```sh python3 -m venv .venv && .venv/bin/pip install -e '.[dev]' pypy3.11 -m venv .venv-pypy && .venv-pypy/bin/pip install -e '.[dev]' .venv/bin/python -m pytest -m "not slow" # the quick loop (seconds) python -I scripts/record_mesen_windows.py # the rung 4 recordings (~2 min) nice -n 19 .venv-pypy/bin/python -m pytest -m slow # LDMAC and the Mesen2 replays ``` ## Wiring it into a board (snes-python milestone 7) The core is the die; the board owns the crystal, the cartridge ROM and the S-CPU side of the connector (handoff brief "The core boundary"). - **Clock**: 20 MHz, one chip clock per crystal cycle (C14). Accumulate `master_clocks * 176` and run `owed // 189` chip clocks (NTSC; PAL 2,000,000/2,128,137), **before every S-CPU access** to $6000-$7FFF or to the ROM, as `necdsp.py` does. `run` charges whole units (an instruction, one cache or DMA byte) and carries the overrun into the next call: the chip is at most one unit ahead of the board's time, never behind. - **The chip's bus** (`bus_read`/`bus_write`): 24-bit SNES-style addresses, called only for the ROM (00-3F/80-BF:8000-FFFF, C0-FF:0000-FFFF) and SRAM (70-77:0000-7FFF) regions; the core answers its own data RAM (00-3F/80-BF:6000-6BFF, 7000-7BFF) and I/O block, and reads 00h from anything else (ares `hitachidsp/memory.cpp`). The board decodes LoROM with `linear = (bank & 3Fh) << 15 | (address & 7FFFh)`, mirrored like byuu's `Bus::mirror` (ares, ISC) (`harness.lorom_offset`), and the two-chip select of SHVC-2DC0N. No Cx4 board fits SRAM: `bus_read` returns 00h there (ares `memory.cpp` l.77), `bus_write` ignores. - **S-CPU map**: banks 00-3F/80-BF $6000-$7FFF go to `read`/`write` (the core ignores the bank). ROM reads go to the board's ROM unless `owns_rom_bus`; then they read open bus, except $00:FFE0-$FFFF (and the 80 mirror), which read `vector(address & 0x1F)` (U16; C12 is the board's switch `BLOCK_ROM_WHEN_BUSY`). ares also answers $00:FFC0-$FFDF then, from $7F40-$7F5F: `read(0x7F40 + (address & 0x1F))`, side-effect free. - **IRQ**: OR `irq` into the cartridge IRQ. The games disable it ($7F51 = 01h). - **Data ROM**: `data_rom=None` computes the 1,024 words (65 ms on CPython, cached); a BYOR `cx4.bin` is read with `load_data_rom(path)` (SHA-1 checked). - **Reset**: the console's reset calls `reset()` (C15: power-on state, data RAM kept). - **Save states**: `capture_state()` / `restore_state()` carry everything, including the cache pages and an in-flight load or DMA. ## What is fetched Nothing third-party is committed. `scripts/fetch_references.py` fills `reference/` from `scripts/pinned_files.json` (fullsnes) and `scripts/pinned_repos.json` (ares and MAME's CC0 `hash/snes.xml` to read; bsnes, Mesen2, snes9x and MAME's `snescx4.cpp` recorded as closed boxes, MiSTer as not opened, at full commit SHAs). A pin can be satisfied in place from a sibling checkout's `reference/` (same revision): nothing is cloned or copied then. The cartridges are **bring your own**, read in place from the No-Intro set (`NO_INTRO_DIR`, or `SNES_NO_INTRO` for the SNES directory itself; tests skip without them). The data ROM needs no file: it is computed (decision 3); `scripts/check_data_rom.py` compares a BYOR dump (`HG51B_DATA_ROM`, or found through `MAME_ROMPATH`). Never commit a ROM, data ROM image, trace or screenshot. ## Scripts | Script | What | | --- | --- | | `fetch_references.py` | fetch, verify, or find in place the pinned documents and source trees | | `check_data_rom.py` | compare the computed data ROM with a player's dump found through `HG51B_DATA_ROM` or `MAME_ROMPATH`, by the SHA-1 in MAME's CC0 software list | | `cx4_probe.py` | closed-box Mesen2 probes: homebrew Cx4 cartridges built here, traced, replayed on the core (C1-C18 observations; recordings in `tests/mesen_probes/`) | | `survey_program.py` | the program at 02:8000-9FFF in every Cx4 cartridge: versions, instruction mix, the contested encodings it uses | | `$EMU_TOOLS_GPL/tools/mesen2/run.py --machine snes-cx4` (not in this repository: mesen2-runner 0.2.0, the GPL-3.0-or-later tool in emu-tools-gpl, run as a separate program) | Mesen2 2.1.1 headless: the built-in test (`--hold-test`, controller 2 B), presses (`--input`), a frame-exact per-instruction Cx4 trace window (`--trace cx4-text --trace-window START:END`), the S-CPU's $6000-$7FFF stream (`--trace host`), the screen (`--frames-out`); OBSERVED (Mesen2 b9fa69d via mesen2-runner 0.2.0) | | `record_mesen_windows.py` | the five rung 4 recordings into `tests/mesen_traces/` | | `mame_cx4_host.py` | MAME 0.285: the S-CPU's accesses to $6000-$7FFF, input presses, screens (HLE: command level only) | They need `7z`, MAME 0.285 (`mame` on the path), `EMU_TOOLS_GPL` naming an emu-tools-gpl checkout with mesen2-runner's Mesen2 `b9fa69dd` built (its `build.sh`, or `MESEN_CORE`; without the variable the Mesen2 scripts stop with exit status 3, naming it), and Pillow for pictures. Run anything that reads `reference/` or a ROM with `python -I`, heavy runs under `nice -n 19`. ## Documents [docs/README.md](docs/README.md) is the index; [docs/handoff-brief.md](docs/handoff-brief.md) is the build session's task and the decisions. MIT licensed ([LICENSE](LICENSE)); the ares ISC notice and the other permissive notices are in [NOTICE](NOTICE).