r/EmuDev • u/Entertainment_Real • 1d ago
Gameboy DMG01 HALT bug explained
I've ran into the halt bug while developing a web based game boi emulator in Rust. I don't understand AI's explanation:
Right now execute_halt (src/cpu/operations/control.rs:111) treats "IME clear + interrupt already pending" as a plain NOP. On hardware that combination triggers the HALT bug: the CPU doesn't halt, and PC fails to increment after fetching the next opcode — so that byte gets read twice. HALT; INC A runs INC A twice. For a multi-byte instruction it's nastier: in HALT; LD A,$14 (bytes 3E 14), the operand fetch re-reads the stuck 3E, so you get LD A,$3E and execution resumes at the 14 byte, which is decoded as a fresh opcode.
The clean fix in your architecture (operand reads are all pc + 1-relative) is a one-byte PC rewind at fetch time:
with PC rewound by one, every operand read (pc + 1) lands back on the opcode byte — exactly the hardware's duplicated read — and next_pc = pc + length resumes one byte early, which is also what hardware does. It even gets the HALT; CB .. case right (the CB byte doubles, decoding as SET 1,E). One thing to update when you do this: the test at tests/cpu/control.rs:729 currently asserts the NOP approximation, so it will need to assert the double-execution instead. No urgency — Blargg's cpu_instrs doesn't need it; only the dedicated halt_bug.gb ROM does
I don't understand the nature of the bug and I defo don't understand why decrementing the PC fixes it. HELP!


