Under the hood

Getting started

This repository holds a commented disassembly of Konami's Mahjong for the MSX (Konami, 1984, cartridge RC-707). Everything here comes out of the binary and can be generated from it again.

What you need

The ROM goes in the root, as mahjong.rom. It is exactly 32768 bytes:

sha256  24cb5bda5f55dcd5ab1343fb61ebac67e8c292f9714ee7a492431e33188b9b40

make comprueba checks it.

The commands

make listado        # rebuilds src/mahjong.asm from the annotations
make verify         # reassembles and compares with the ROM, byte for byte
make sanity         # nothing declared as data may come out as code,
                    # and not one byte may be left unassigned
make notas          # no dangling and no duplicated comment
make test           # the checks
make densidad       # how many instructions carry a comment, routine by routine
make capturas       # redoes the web pictures with openMSX
make web            # rebuilds this web

What is in each folder

   
src/mahjong.entries the entry points, each with its justification
src/mahjong.nocode the ranges the tracer must not read as code
src/mahjong.notes the only file edited by hand: every annotation
src/mahjong.asm the listing, generated by tools/mkasm.py
tools/ the tracer, the listing generator and the measuring tools
tests/ the checks on the listing and the annotations
docs/ this web

How to read the listing

The annotations are anchored to an address, so they survive a retrace. The directives follow theNestruo's guidelines:

   
L a label and what the routine does
C a comment on that line
B a block header before that address
D a data range, with its name and its explanation
F the row width of a data block

The 340 named routines are named after what they do, not after where they sit, and the 89 data blocks each carry a name, a size and the width of their rows, which is what lets you read them as tables instead of as a run of bytes.

How it was done

The tracer follows the real flow from the entry points. Whatever cannot be worked out statically is declared by hand in the .entries, with the reason written next to it: the INIT vector from the header, the interrupt hook INIT writes into H.KEYI, and the thirty-two destinations of the dispatcher's five tables, which ends in jp (hl) and cannot be followed through.

That dispatcher also forces the opposite: the tables sit embedded right behind the call that invokes it, so those bytes are data even though they are in the middle of the code. They are declared in the .nocode, and make sanity checks that none of them is read as an instruction.

There is no assumption dressed up as a fact here. What is not known is in Open questions, and it says so.

So that it can be repeated

make verify reassembles the listing and compares the result with the original ROM. It has to come out identical, byte for byte. And make sanity then checks what reassembling cannot catch: that no range declared as data is being read as code, and that not one of the 32768 bytes is left unassigned.

The pictures on this web are not made by hand either. make capturas boots the cartridge in openMSX with nothing being drawn, dumps video memory at fixed instants and builds the PNG from the dump; the first pass does not press a single key, because the demo plays itself.

The cartridge

It is 32 KB taking up two pages of the MSX map, from 0x4000 to 0xBFFF, and an MSX1 handles them comfortably: no megaROM, no bank switching, no extra sound hardware.

The sixteen bytes the BIOS reads

4000:  41 42 10 40 00 00 00 00 00 00 00 00 00 00 00 00
       A  B  INIT=0x4010

The header declares AB and an INIT vector, and leaves the other three pointers —STATEMENT, DEVICE and TEXT— at zero. The cartridge adds no BASIC statements and does not declare itself as a device: it boots and takes the machine.

But the BIOS only maps page 1 when it reads that header, so the top half of the cartridge does not exist yet when INIT starts. The first thing 0x4010 does is switch it on itself: it reads its own slot with RSLREG, keeps the two bits for page 1 and calls ENASLT with H = 0x80, which is page 2. From that call on there are 32 KB in sight.

The rest of the startup is short: it writes jp 0x4071 into the interrupt hook H.KEYI (0xFD9A), puts the stack at 0xE400, clears in one go the 1024 bytes from 0xE000 to 0xE3FF —which are every variable the game has—, sets up the PSG and the VDP, and drops into a jump to itself it never leaves. The rest is in The code.

The VDP, with the two tables swapped

It is SCREEN 2 with 16×16 sprites, and the eight registers are loaded from the list at 0x4A1A:

table where
colours 0x0000
sprite patterns 0x1800
patterns 0x2000
names 0x3800
sprite attributes 0x3B00

The striking part is the order: R3 = 0x7F and R4 = 0x07 put the colours at the bottom and the patterns on top, exactly the other way round from what the usual values give (0xFF and 0x03). It works just the same, but anyone reading a dump assuming the usual layout will read one thing for the other.

There is another detail that throws you when reading the drawing lists: the VRAM destinations they carry are sixteen bits and fall outside video memory, which on an MSX1 is 16 KB. 0x7962 is not a bug: SETWRT swallows the top two bits and writes to 0x3962, that is, row 11, column 2 of the name table. Every list in the cartridge is written that way.

The two drawing interpreters

Almost everything that reaches the screen is a list that goes through one of these two.

Format A is read by 0x4099, and it is the simple one: two bytes of VRAM destination and then the bytes as they are, with 0xFE for "another destination follows" and 0xFF to finish. The clever part is that it has two doors: entering at 0x409D the bytes pass through untouched and the list draws, and entering at 0x4099 an and c with C = 0 turns them all into zero and the very same list erases. There is no second table to switch off what was switched on.

Format B is read by 0x468F, and it compresses: each order is a seven-bit counter, and bit 7 says whether what follows is that many literal bytes or a single byte to be repeated that many times. The font, the tile drawings and the backgrounds all come up through it.

The letters and the tiles

The tile numbers of the labels are shifted ASCII. The font at 0x83B1 is 48 patterns going to tiles 0xC0 through 0xEF: the ten digits, the copyright circle, the hyphen and A to Z, so that a letter's tile is its ASCII plus 0x90. That is why the cartridge's labels read in clear in a dump, with nothing to decode. The same block is copied to the colour table and to the pattern table, so the letters come out coloured.

A tile's drawing is six consecutive tiles, two wide by three tall, and the table at 0x4735 gives the first of the six from the tile's code: one row per suit, another for the honours, and all of them stepping down six at a time. In the honours row there are two values that are not tiles: code 0x38 draws the back and 0x39 the empty slot.

The sound

The cartridge brings its own player, at 0x9C4A. You ask for a sound with its number in A, and that number is also its priority: if the channel is already carrying a higher one, the request is ignored. Below 0x8D they are effects and all go to the same channel; above that they are music on three channels.

Each channel is eleven bytes of RAM —counter, duration, number, pointer, octave, volume, repeat count— and the driver takes one step per frame from the interrupt. A sound's orders are one byte each: 0x2n sets the duration, 0x1n sends a noise to PSG register 6, 0xFE repeats and 0xFF ends; in an effect, the high nibble is the volume and the next twelve bits the period.

The pitches come from twelve divisors at 0x9FD9, one per semitone, and the octave is got by doubling the period as many times as the note's register says: the more it doubles, the lower it sounds. There are 33 sounds in the pointer table at 0x9CA3, and thirty-one places in the cartridge ask for one.

The last 8,219 bytes

From 0x9FE5 to 0xBFFF there are 8,219 bytes of 0xFF in a row, and not one instruction in the cartridge points there. The content ends at 0x9FE4, twenty-seven bytes short of the 24 KB boundary, which means the program was written to fit in 24.

What the binary does not say is which chip the cartridge carried, because 0xFF is what you get back from both an unprogrammed EPROM and an unconnected bus. It could be a 32 KB memory with the last bank blank or a 24 KB one the dumper read eight too many from, and from the dump the two are identical.

The mark that is not there

Many Konami cartridges of this period hide their RC-7xx catalogue number and the game's title in katakana at the end of the ROM; it was Manuel Pazos (@ManuelPazosMSX) who found that out.

This one does not carry it. In all 32768 bytes there is not one RC-7 in ASCII, nor the word KONAMI, nor anything resembling that signature: the last byte with content belongs to the semitone table, and behind it there is only filler. The RC-707 of this cartridge comes from the catalogue, not from the binary.

The code

Of the cartridge's 32768 bytes, 15,432 are code and 17,336 are data. Not one is left unassigned.

The whole game runs inside the interrupt

When INIT has finished setting the machine up, it does not call any main loop: it reaches 0x404F, which is a jr to itself, and stays there forever. Everything else hangs off the H.KEYI hook it has just installed.

404F:  jr 404Fh

The interrupt routine does three things in order. It acknowledges the VDP, it moves the sound —always, whatever happens—, and then it looks at the semaphore at 0xE005: if the previous frame is still inside, it leaves without more ado; if not, it raises it, reopens interrupts, reads the controls and gives the state machine one beat. That semaphore is the only thing keeping a long frame from overlapping the next one.

So a frame of this game is a call, not a turn of a loop, and all the state has to live outside the stack. Hence the kilobyte from 0xE000 to 0xE3FF full of counters, cursors and flags.

The dispatcher that reads itself

The fifteen states and their steps are dispatched by this routine, and it is not the usual one:

408F:  add a,a          ; each entry is two bytes
4090:  pop hl           ; the RETURN address is the table
4091:  call 4063h       ; HL += A
4094:  ld e,(hl)
4095:  inc hl
4096:  ld d,(hl)
4097:  ex de,hl
4098:  jp (hl)          ; and jump: there is no coming back here

The pop hl keeps the return address and uses it as the base of the table, which means the table sits right behind the call that invokes the dispatcher. It saves the ld hl,table on every call, and in exchange whichever handler comes out inherits as its return address whatever lay under the table.

There are five tables written that way, and between them they are the whole skeleton of the game: fifteen words for the states at 0x40ED, and two, two, nine and four for the steps of states 7, 10, 11 and 12.

For a disassembly this is a problem twice over: the jp (hl) cuts the trace, and the bytes behind each call are data in the middle of the code. The thirty-two destinations are declared by hand in the .entries and the five ranges in the .nocode, each with its justification written alongside.

One set of variables for both players

The call menu, the hand engine and the yaku detector do not know whose turn it is. They always work on the same addresses, and what happens before and after is a copy: 0x517A brings into those shared variables the ones belonging to whoever is playing —cursor, drawn-tile slot, last slot, tsumo flag, riichi and waits— and 0x51BC puts them back.

It is the reason the machine can call pon or chi going through the very same menu dispatcher a person does: its variables are loaded, the call bit is set, and in it goes the way a player would.

The hand engine

Deciding whether a hand is complete is the largest thing in the cartridge (0x5F3E-0x656D), and it is not a table nor a generic search: it is a hand-written tree of cases over the already sorted hand. At each step it looks at the tile under the cursor and the three or four after it, and off what it finds —equal, consecutive, loose— hangs a different branch. What it finds it records in four lists: runs, triplets, quads and the pair, each set with a flag saying whether it is open.

When a branch does not work out there is backtracking, but it is not recursive: a copy of the hand and of the sets is saved into one of two slots, with one byte saying how many copies there are and another which branch to try on restoring. Two levels and not one more. If they run out, the hand is declared undecomposable.

On top of that engine runs the yaku detector at 0x7B3F: twenty-seven checks that read what the four lists left behind and record every yaku that fits with its han.

And all of it leans on how a tile is encoded. The number goes in the low nibble, so "the next one in the run" is a subtraction giving 0xFF, and the honours, starting at 0x31, cannot fit into any run without anyone having to check.

How it was done, and why you can trust it

The listing is not written by hand. tools/z80trace.py follows the real flow from the declared entry points, tools/mkasm.py builds the .asm with the address-anchored annotations, and the numbers come out of that.

make verify reassembles and compares against the original ROM: it has to come out identical byte for byte, and it does. But that alone is not enough, because data read as code gives the same binary —the bytes do not change, what changes is what is said about them—, so make sanity also checks that no range declared as data shows up as an instruction, that no entry point falls inside a data area, and that not one of the 32768 bytes is left unassigned.

On top of that there are two more measures. make notas catches the two mistakes that get lost in silence when annotating: a comment anchored to an address that is not an instruction, and two comments for the same one. And tools/densidad.py measures, routine by routine, how many instructions carry a comment:

   
labelled code blocks 1,001
of those, with a name of their own 340
data blocks, with their name and row width 89
instructions 7,548
instructions with a comment 2,320 (30.7 %)
routines under 10 % commented 0

That last row is the one that matters: a routine with a name but not a single comment is christened, not explained, and there is none of those left here.

Code shared with other Konami cartridges

This disassembly has been compared, instruction by instruction, with every other Konami one in the series. A block counts when the same instructions, at least six of them from a label to its ret or its unconditional jump, are in both cartridges; the addresses are left aside, because they change from one cartridge to the next. Of the other 57, 46 have at least one block in common with this one; these are the ones that share the most:

Cartridge Blocks Instructions For example (here = there)
Magical Tree 20 208 limpia_la_pantalla_entera (0x45EC) = limpia_la_pantalla
Circus Charlie 19 183 limpia_la_pantalla_entera (0x45EC) = limpia_la_pantalla
Cabbage Patch Kids 18 214 rellena_la_vram (0x45F6) = RELLENA_VRAM
Hyper Sports 1 15 186 carga_los_canales (0x9C8A) = SUMA_BONUS_7BE3
Comic Bakery 14 141 carga_los_canales (0x9C8A) = arranca_la_voz
Super Cobra 12 123 pinta_lista_formato_b (0x468F) = PINTA_ROTULO
Yie Ar Kung-Fu 8 103 pide_un_sonido (0x9C4A) = pon_la_melodia
Road Fighter 6 62 despacha_por_tabla (0x408F) = despacha_por_indice
Athletic Land 5 43 copia_dentro_de_la_vram (0x4648) = COPIA_VRAM_A_VRAM
Konami’s Billiards 5 55 despacha_por_tabla (0x408F) = despachador

The whole matrix, the 58 cartridges against each other, is on The routines in the series database, along with the method and the program that measures it.