Metadata-Version: 2.5 Name: hg51b-python Version: 0.1.0.dev0 Summary: Readable, pure-Python Hitachi HG51B169 core (the SNES Cx4 of Mega Man X2/X3), instruction-exact Author: alewman License: MIT License Copyright (c) 2026 alewman Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. License-File: LICENSE Classifier: Development Status :: 3 - Alpha Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Topic :: Software Development :: Libraries Classifier: Topic :: System :: Emulators Requires-Python: >=3.11 Provides-Extra: dev Requires-Dist: pytest>=8; extra == 'dev' Requires-Dist: ruff==0.16.8; extra == 'dev' Description-Content-Type: text/markdown # 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-07): core built; rungs 0-4 of [docs/validation.md](docs/validation.md) passed.** Decode of all 65,536 words as bsnes' table; 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 and traces the Cx4; bsnes/ares and MiSTer are read; MAME is HLE only). [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 bsnes' choice as default (decision 4): `SHIFT_LIMIT`, `TRUNCATE_SHIFTED_OPERAND`, `DMA_LOCK`, `STACK_MODEL`, `MUL_LATENCY`, `BUS_DELAY_EXTRA`, `INTERNAL_ACCESS_COST`, `CACHE_PRELOAD`, `CLEAR_IS_NOP`, `LD_P_SOURCE`, `STATUS_MIRROR`, `OPERAND_00_READS_A`, `FAR_SELECT`, `IRQ_DISABLE_SETS_FLAG`, so a comparison flips one without editing code. Tooling, at the family's bar: `CPUState`, `disasm` (bsnes/ares 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 (bsnes `memory.cpp`). The board decodes LoROM with `linear = (bank & 3Fh) << 15 | (address & 7FFFh)`, mirrored like bsnes' `Bus::mirror` (`harness.lorom_offset`), and the two-chip select of SHVC-2DC0N. No Cx4 board fits SRAM: `bus_read` returns 00h there (bsnes: "not open bus"), `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`). bsnes 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` (bsnes, ares, MAME 0.285, Mesen2, snes9x, MiSTer at full commit SHAs, sparse). Every pin is satisfied in place from snes-python's `reference/` (same revision, every sparse path present): nothing is cloned or copied. The cartridges are **bring your own**, read in place from the No-Intro set (`SNES_NO_INTRO`; tests skip without them). The data ROM needs no file: it is computed (decision 3); `HG51B_DATA_ROM` names a BYOR image for the byte comparison. 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 | | `survey_data_rom.py` | compute the data ROM from fullsnes' formulas exactly; compare with BYOR images and the emulators' copies; SHA-1, checksum, float64 margins | | `survey_program.py` | the program at 02:8000-9FFF in every Cx4 cartridge: versions, instruction mix, the contested encodings it uses | | `mesen_cx4_trace.py` | Mesen2 2.1.1 headless: the built-in test (controller 2 B), `--press`, a frame-exact per-instruction Cx4 trace window, `--host` (the S-CPU's $6000-$7FFF stream), the screen | | `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 at `/usr/games/mame`, famicom-python's `MesenCore.so` (Mesen2 `b9fa69dd`), and Pillow for `--png`. 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)).