How to write a Game Boy emulator – Part 7: Blargg's CPU test ROM #6
This post is part of a blog series about writing a Game Boy emulator.
Now that we've emulated the bios, it's time to emulate a rom. But we're not ready to emulate full games yet. To emulate a game, we'd have to implement a lot more CPU instructions, implement interrupts, sprites, input... which is a bit too much right now. The next step is to emulate Blargg's CPU test ROM #6.
Blargg's test roms are available here: http://gbdev.gg8.se/files/roms/blargg-gb-tests/ . Download "cpu_instrs.zip", extract the archive, go in the folder "individual", and take the file named "06-ld r,r.gb". It's a 32 768-byte file with this SHA-256 hash:
17ada54b0b9c1a33cd5429fce5b765e42392189ca36da96312222ffe309e7ed1
Test roms are used to test the accuracy of emulators. They give a certain output on real Game Boys, and emulators should give the same output. If your emulator fails a test rom, it means it has an error. If your emulator passes a test rom, it doesn't prove the absence of bugs, but it must be doing something right.
Why start with test rom #6? Why not start with #1? I suspect that #6 is the easiest to pass. It tests the LD operation which is one of the simplest.
First we need to load the rom into memory. The rom is mapped to memory locations 0x0000-0x7FFF (32 768 bytes). This is slightly inaccurate: during bios execution, the first 256 bytes of memory (0x0000-0x00FF) are mapped to the bios, not to the rom. When the bios writes to memory location 0xFF50, this permanently unmaps the bios from memory, and maps the first 256 bytes of the rom in its place.
If there is no cartridge/rom, then memory locations 0x0100-0x7FFF return 0xFF and the bios enters an infinite loop reading these values.
You'll need to implement a dozen CPU operations or so. If everything works well, your emulator should display this:

The test rom will write in memory locations 0xFF01 (SB: Serial transfer data) and 0xFF02 (SC: Serial transfer Control). These memory-mapped I/O locations are used to send data on the link cable . The rom must write the byte to send to 0xFF01, and then write 0x81 to 0xFF02 to initiate the transfer of the byte. This is very simplified, but the point is that Blargg's test roms send their output to the link cable. They do that so you can test your emulator with no graphical display.
The bytes written to 0xFF01 should give this string:
06-ld r,r
Passed