Under the hood

Getting started

This repository holds the commented disassembly of King's Valley (Konami, 1985), the 16 KB RC-727 cartridge for the MSX1.

The ROM is not distributed here. You need to put it in the root of the repository as kingsvalley.rom. To check it is the same one:

shasum -a 256 kingsvalley.rom
a8f807a0be90db6a01c43a948215a8761d1d7b92358279d6f2ce2dcfefab5d73

What make does

make listado    builds src/kingsvalley.asm from the trace and the notes
make verify     reassembles the listing and compares it to the ROM, byte for byte
make sanity     the four checks reassembling does NOT cover
make densidad   counts how much of the listing is commented
make imagenes   draws the declared graphic blocks, so you can look at them
make web        builds the bilingual site in docs/

Plain make runs listado, verify, sanity and test.

Why verify is the test that matters

A disassembly can be written many ways, and almost all of them are wrong in some way that does not show. The one test that admits no argument is to reassemble the listing and check that exactly the same ROM comes back: the 16,384 bytes, in the same order, with the same sha256.

That is what make verify does, and it has been run after every batch of work. If it ever fails, the listing is wrong, however nicely it reads.

What reassembling does not cover

Identical bytes say nothing about whether we have understood them. A data block read as if it were code produces the same binary and a lie in the listing. So make sanity runs four separate checks:

The files edited by hand

Only three, all in src/:

src/kingsvalley.asm is generated: never edited by hand.

The pictures

Not one picture on the site is an emulator capture. They are all drawn by tools/pantallas.py from the bytes of the ROM, by running in Python the two script interpreters the Z80 runs. See The code for how they work.

The cartridge

King's Valley, Konami, 1985. Cartridge RC-727, 16,384 bytes, mapped into the MSX's page 1 (0x4000-0x7FFF).

sha256  a8f807a0be90db6a01c43a948215a8761d1d7b92358279d6f2ce2dcfefab5d73

The header

The first ten bytes of the dump are:

41 42 6C 40 00 00 00 00 00 00

41 42 is the AB marker the BIOS looks for to know a cartridge is there. The next two are the address of INIT, little-endian: 6C 40 = 0x406C. The rest — STATEMENT, DEVICE, TEXT — is zero: the cartridge declares only INIT, and everything else hangs off that.

How it boots

arranca_el_juego (0x406C) does four things and no more:

  1. Hooks the interrupt by hand: writes a 0xC3 (jp) into H.KEYI (0xFD9A) and the address 0x401A behind it. It uses no BIOS hook; it builds the instruction byte by byte.
  2. Puts the stack at 0xE700.
  3. Clears 0xE000-0xE6FF with an ldir.
  4. Calls prepara_pantalla and falls into an empty loop.

From there the whole game runs inside the interrupt. The main loop does not exist: it is a jr to itself. It is the same pattern the Sky Jaguar and Konami's Golf disassemblies already document for this same family of Konami cartridges, so it is not a fresh reading but terminology already validated in two other projects.

How the 16 KB break down

traced code         9,803 bytes    59.83 %
declared data       6,581 bytes    40.17 %
unexplained                 0       0.00 %

The 6,581 bytes of data are not "what was left over": they are 117 blocks declared one by one in kingsvalley.notes with a D directive saying what they are, and an F giving the width of their structure — a word, seven bytes, two bytes per entry. That is the series' rule: every table separated and named.

The VDP registers

tabla_registros_vdp (0x45C0) is eight raw bytes, R0 to R7:

02 E2 0E 7F 07 76 03 E4

The VRAM map

With those registers, the 16 KB of VRAM look like this:

0x0000 - 0x17FF   COLOUR table       (768 tiles x 8 bytes, three thirds)
0x1800 - 0x1FFF   SPRITE patterns    (64 sprites of 16x16)
0x2000 - 0x37FF   PATTERN table      (768 tiles x 8 bytes, three thirds)
0x3800 - 0x3AFF   NAME table         (768 cells, 24 rows x 32)
0x3B00 - 0x3B7F   SPRITE attributes  (32 entries Y/X/pattern/colour)

The name table ends exactly at 0x3AFF and the attribute table starts at 0x3B00, back to back. That was checked in the emulator in an earlier batch, by dumping both regions at once.

The RAM map

The game uses 0xE000 up into 0xF000-something. The busiest parts:

0xE000  active task index               0xE003  frame counter
0xE004  task counter                    0xE009  this frame's input
0xE010  PSG sound engine block          0xE049  score, in BCD
0xE043  high score, in BCD              0xE050  round counter
0xE054  room number                     0xE0B0  sprite buffer (32 x 4)
0xE134  the explorer's record           0xE14E  enemy descriptors
0xE164  how many enemies                0xE16A  the enemies (22 B each)
0xE1C5  7-byte entities                 0xE1F5  9-byte entities
0xE264  17-byte entities                0xE2CC  another 9-byte list
0xE31E  blocks that open (7 B)          0xE3FF  traps (9 B)
0xE700  the room buffer, 96-byte row stride

Konami's hidden mark

Konami hid the catalogue number and the title in katakana at the end of many of its cartridges. Manuel Pazos (@ManuelPazosMSX) found it, and he should be credited.

This cartridge has it, ending exactly at 0x7FFF:

RC-727    O U   KE   NO   TA   NI

OU KE NO TA NI is 王家の谷, the game's Japanese title: the Valley of the Kings.

The search is done with tools/busca_marca_konami.py, which scans all 16,384 positions, not just the end: there are cartridges in this family where the mark is not where you expect, and taking a negative on faith without sweeping the whole ROM is the easy way to get it wrong.

The two script interpreters

Almost everything the cartridge draws is compressed as scripts for one of two different interpreters. They must not be confused, because the same bytes read with the other one give noise:

One stretch of ROM can serve both: 0x47FE is a graphics script that writes letters into the name table, and 0x480E — sixteen bytes further on, inside the same stretch — is a text script that starts halfway and shares the tail.

The code

The listing's 651 routines all have a name and a description, and 45.5 % of the instructions carry a comment of their own. This page walks through the pieces you need in order to read the rest.

The task dispatcher

The game is a state machine with eleven tasks. avanza_un_cuadro (0x40A3) bumps the frame counter and despacha_tarea_activa (0x40B6) jumps to whichever task the low byte of 0xE000 names.

The dispatch uses a trick that shows up seven times in the cartridge:

    call L_404B
    defw target0, target1, target2, ...

L_404B (0x404B) does add a,a, recovers the return address with pop hl — which is precisely the table following the call — and reads the right word from there. Then jp (hl). The table is never executed: it is read off the stack.

All seven tables are declared in the .nocode, because otherwise the tracer reads them as code and out comes a listing that reassembles fine and lies.

The position record

The piece that opens up the rest of the game is not a player routine: it is lee_celda_de_sala (0x50BC), read backwards. It takes a pointer to a position record in HL and uses:

That gives the format of the explorer's record, which starts at 0xE137, and three bytes below it sits the state — confirmed by sondea_una_celda (0x5092), which with HL at 0xE137 does dec hl three times and reads the result as the state to compare against 2.

That same format is used by the entities, the enemies and the candidate position scratch at 0xE149. Which is why the probe routines serve all of them.

The 24-bit arithmetic

avanza_posicion_24_bits (0x73F6) is the engine behind every movement. It comes in with HL pointing at a 16-bit pair and DE holding the velocity, and does:

    add hl,de       ; the two low bytes
    ld a,b
    adc a,c         ; and the third, with the carry

That is twenty-four bits: fraction, low pixel, high pixel. For the explorer those three bytes are 0xE138, 0xE139 and 0xE13A.

Bit 0 of (IX-2) — which for the explorer is 0xE136, the direction byte — decides whether the velocity is negated before adding, with a two's complement of DE and a complement of C. That is how the same code serves both directions, and why that bit is "which way he faces".

The six entity lists

Six parallel tables, each with its own accessor. You do not have to guess how big an entry is: it is in the multiplication.

routine chain stride base index limit
0x6A12 i, 3i, 7i 7 0xE1C5 0xE1F4 —
0x65A5 2i, 4i, 8i, +i 9 0xE1F5 0xE1F4 0xE1F3
0x5AF6 2i, 4i, 8i, 16i, +i 17 0xE264 0xE262 0xE263
0x73D3 2i, 6i, 22i 22 0xE16A 0xE165 0xE164
0x68C2 2i, 4i, 8i, +i 9 0xE3FF 0xE3FD 0xE3FE
0x6A09 i, 3i, 7i 7 0xE31E 0xE31C 0xE31D

The first two share an index (0xE1F4): they are two blocks of fields of the same entity, split across two areas of memory.

The chains are nested, too: campo_de_entidad_17 prepares 2i and joins the chain halfway at indexa_paso_17, which carries on to 16i; campo_de_entidad_9 joins one step earlier at indexa_paso_9, and the last three adds are shared by both. It saves bytes at the cost of having to read the whole chain to know the stride.

The pushed loop closers

Five entity loops do this before dispatching:

    ld hl,<closer>
    push hl
    ...
    jp (hl)         ; off to whichever routine

The ret of the dispatched routine does not return to the caller: it falls into the closer, which bumps the index and jumps back into the loop body. All five closers have the same shape:

    ld hl,<index>
    inc (hl)
    ld a,(hl)
    inc hl
    cp (hl)
    jp nz,<body>
    ret

That is 87 bytes of code a static tracer cannot reach, because the address travels through the stack as if it were data. They are declared in the .entries with their justification.

Drawing: two interpreters

dibuja_guion (0x451A) reads one-byte commands:

C = B0 & 0x7F
  C != 0 and bit 7 set    -> copy C raw bytes from the script into VRAM
  C != 0 and bit 7 clear  -> read ONE byte and repeat it C times
  B0 == 0x00              -> end
  B0 == 0x80              -> read a word with another VRAM address and carry on

Telling 0x00 from 0x80 is settled rather nicely: the byte is read twice, once masked with 0x7F and once raw, and the two are compared. If they match, bit 7 was clear.

The VDP auto-increments after each write, so a script paints a continuous stretch. dibuja_guion_x3_tercios (0x44F1) repeats the same script three times 0x800 apart: SCREEN 2's three thirds.

escribe_guion_de_texto (0x4051) is a different language altogether: a word with the address, characters, 0xFE to jump and 0xFF to end. The characters are in ASCII minus 0x20.

The sound engine

The PSG player lives at 0x7A9E-0x7CE2, forty routines. Each channel is a fourteen-byte structure, and there are three, at 0xE010, 0xE01E and 0xE02C.

PSG register 7 — the mixer — is used to switch channel C between tone and noise note by note: conmuta_ruido_canal_c alternates 0x9C (tones A and B with noise on C) and 0xB8 (all three tones, no noise). That is the percussion.

The note byte has two halves, and the high nibble is not the octave: it is the index into tabla_periodos_nota, 0 to 9. The octave comes from a separate field of the channel structure, set by an earlier control command.

The score, in BCD

suma_al_marcador (0x4412) keeps six digits in packed BCD. You do not have to deduce it: the daas sit after every add and every adc.

Same with divide_entre_diez (0x439A), which turns a small binary into two digits by subtracting ten at a time and counting in the high nibble.

What the cartridge never does

Two code blocks are called by nobody: 0x4501 and 0x4542. The second is the counterpart of prepara_escritura_vdp for reading VRAM — it calls SETRD and takes the read port from system variable 0x0007, just as the other takes the write port from 0x0006.

That it is there and unused says something about the design: this cartridge never reads VRAM back. It writes and forgets. All the game state lives in RAM, including a full copy of the room at 0xE700.

In the emulator

Reading opcodes is not enough for everything. Some things can only be settled by watching what the machine actually does, and for that there are eight openMSX scripts in tools/.

They all follow the same pattern: a breakpoint at INIT (0x406C) to arm the watchpoints after page 1 really is the cartridge, blind input driven by fixed-seed random keypresses, and a real-time watchdog in case something hangs.

"C:/Program Files/openMSX/openmsx.exe" -machine C-BIOS_MSX1_EU \
    -cart kingsvalley.rom -script tools/omsx_task_trace.tcl

omsx_task_trace.tcl — the task cycle

A write watchpoint on 0xE000, the active task index, taking a screenshot and the PC on every change. Ninety seconds of menu and demo.

The full cycle came out like this, identified from the screenshots, not guessed:

0 (Konami logo) -> 1 (title) -> 3 -> 4 (room name) -> 5 (room at rest)
  -> 6 (the demo moves) -> [4 again, repeats] -> 7 (pause) -> 0

The surprise that nearly ruined the batch: the 0→1 and 1→3 transitions are not fired by each task's natural frame cascade — which does exist and reads fine in the opcodes — but by revisa_teclado_y_salta_menu (0x4644). The PC of the write, measured, lands at 0x4663 and 0x4679, inside that routine. Because the test script presses keys from 1.5 seconds in, the "skip with a keypress" path always beats the natural wait.

Without that second PC= field in the log, the comment would have credited the transitions to the wrong routine.

omsx_dump_sala.tcl — the room buffer

A breakpoint at 0x6B09, the exx that closes the unpacking of one band, and a dump of 0xE700 onwards.

An earlier attempt used 0x6D3B — the first ret that appears around there in the listing — and gave row 0 right and 0xFF for the rest: that ret closes a different routine, not the real end of the unpacking. With the right breakpoint: 0 differences across 352 cells of room 1 against the Python decoder.

Two corrections came out of that check that static reading had not caught:

omsx_dump_sprites.tcl — the attribute table

Dumps VRAM 0x3B00-0x3B7F and RAM 0xE0B0-0xE12F at seven moments, and also searches for which name table cells use patterns 0x51, 0x52, 0x53 and 0x5C.

It confirmed three things: that the name table is 768 bytes from 0x3800 and ends exactly at 0x3AFF, back to back with the attribute table; that the buffer values are plausible Y/X/pattern/colour, with Y=0xE1 (−31) on the entries parked off screen; and that the pattern parpadea_patron_borde rewrites (0x0288/8 = 0x51 exactly) is byte for byte the same index the four corners of the stone frame use in all five sampled rooms.

omsx_check_4644.tcl — the write that never lands

0x403E does real self-modifying code: it writes a pop hl + ret over the first byte of task 1. But it does so identically every time without reading any state that changes, and that did not add up.

Breakpoints at 0x4644, 0x403E and 0x40E4, 120 emulated seconds. The real result: 0x403E runs 92 times — so it is a normal path, not some rare case — but the first byte of task 1 still reads 0x10 on all nine occasions that task runs afterwards, because the write lands in 0x4000-0x7FFF, which is ROM.

What that measurement could not tell us is why. It is a copy protection: harmless in a cartridge, lethal in a copy loaded into RAM. See Findings.

omsx_dump_mapa.tcl — the whole room, elements included

omsx_dump_sala.tcl stops in the middle of unpacking one band, which only proves the walls. This one stops at 0x4176, the first place where carga_la_sala and reparte_entidades_de_la_sala have both finished and nothing has painted the entrance door yet, and dumps the complete 23x96 map buffer from 0xE700.

The demo only ever plays pyramid 5, so the level is forced at 0x6A90 — both 0xE054 and 0xE055, because the first thing that routine does is copy one over the other — and the machine is reset between levels.

python3 tools/mapas.py --comprueba kingsvalley.rom 0x4000 work/omsx_mapa

Fifteen dumps, 31,680 cells compared, 0 differences.

omsx_vram_sala.tcl — the picture itself

The same forcing, but stopping at 0x4185, with the room already on screen and the sprites in place, and dumping all 16 KB of VRAM plus the eight VDP registers. Then, two emulated seconds later, the sprite attribute table again — the mummies are not there when the room is built, they arrive on a timer — which is where the explorer's two colours and each mummy type's colour were read.

python3 tools/mapas.py --vram kingsvalley.rom 0x4000 work/omsx_vram

Fifteen levels; name table, pattern table, colour table and sprite pattern table; 0 differences. Of the pattern and colour tables only the tiles the screen actually uses are required to match — the rest of those tables is leftovers from the title screen that the game neither rewrites nor reads.

omsx_vram_menus.tcl — the title screen and the valley map

The rooms were compared against the machine; the menu screens were not, and two mistakes hid there. This dumps both.

The title screen is caught at 0x43B7, the end of dibuja_titulo_y_texto_ya. The valley map is harder: it only comes up when a pyramid is cleared, and the demo never clears one. It is forced at 0x4176 — a point that runs every time a room is built — by blanking the whole name table and then setting PC to 0x41C0, the pair of calls that build the map. Blanking first is what makes the dump conclusive: whatever appears in the name table afterwards was written by the map's own code.

cd tools && python pantallas.py --vram ../kingsvalley.rom 0x4000         ../work/omsx_menus

Two screens; name table, pattern table and colour table; 0 differences.

omsx_barrido_huecos.tcl and omsx_quien_lee.tcl

Both generic: the first sweeps the unclassified gaps setting read watchpoints, and the second answers "who reads this address" by setting a watchpoint and recording the PC.

What is NOT checked against a running machine

This needs saying just as plainly:

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, 51 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)
Knightmare 19 249 tono_con_periodo_explicito (0x7BF7) = toca_la_nota
Konami's Boxing 18 190 dibuja_guion_con_direccion (0x4514) = descomprime_desde_palabra
The Goonies 18 253 tono_con_periodo_explicito (0x7BF7) = toca_la_nota
Hyper Rally 18 220 tono_con_periodo_explicito (0x7BF7) = CANAL_TONO_60BA
Hyper Sports 3 17 237 procesa_comando_de_control (0x7C5B) = mandato_de_pista_larga
Road Fighter 17 218 arranca_el_juego (0x406C) = init_del_cartucho
Konami’s Soccer 17 212 tono_con_periodo_explicito (0x7BF7) = escribe_el_periodo_y_el_volumen
Pippols 16 203 procesa_comando_de_control (0x7C5B) = PISTA_MANDOS
Yie Ar Kung-Fu 15 174 suma_al_marcador (0x4412) = suma_a_la_puntuacion
Hyper Sports 2 14 155 arranca_con_forma_elegida (0x7CB6) = PERIODO_DE_LA_NOTA

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.