Jump Tables and Dispatch in 6502 Assembly: JMP (Vector), the RTS Trick and Self-Modifying Jumps

Atari text screen with four lines: ROUTINE 2 (JMP (VECTOR)), ROUTINE 3 (RTS TRICK), ROUTINE 1 (SELF-MODIFIED JMP) and JMP ($37FF) WENT TO $41xx: BUG

Menus, command interpreters, game state machines, sound effects selected by number: all of them come down to the same job. Take a number and run routine number n. Higher-level languages have ON n GOSUB or switch. The 6502 has no indexed jump instruction, so Atari programmers use one of three techniques. This guide shows all three side by side in one tested program, explains why the Atari OS chose the strangest of them, and demonstrates the 6502's best-known bug, which lies in wait for anyone who puts a jump vector in the wrong place.

What you'll learn: building address tables in MADS, dispatching with JMP (vector), with the "RTS trick" and with a self-modifying JMP, what each one costs, how to call a dispatcher so that the routines return properly, and how to avoid the JMP ($xxFF) page bug.

What you need: MADS and an emulator, and the basics from 6502 Addressing Modes, the Atari Way. The example was assembled with MADS and run in atari800.

1. The address table

All three methods start from a table of routine addresses. Splitting it into a low-byte table and a high-byte table means the command number can be used as an index directly, without doubling it:

addrlo  dta <cmd0,<cmd1,<cmd2,<cmd3
addrhi  dta >cmd0,>cmd1,>cmd2,>cmd3

< and > take the low and high byte of an address. With at most 256 entries, X or Y can index the table directly. A single table of 16-bit words (dta a(cmd0),a(cmd1)…) works too, if you double the index with ASL first.

2. Method 1: JMP through a vector

Copy the address into a two-byte vector, preferably in zero page, and jump through it:

via_ind tax
        lda addrlo,x
        sta VEC
        lda addrhi,x
        sta VEC+1
        jmp (VEC)

This is the most readable method and works from ROM, as long as the vector itself is in RAM. The Atari OS uses this pattern constantly with its RAM vectors in page 2: VVBLKI, VDSLST and VIMIRQ are jumped through with JMP (vector).

3. Method 2: the RTS trick

RTS pulls an address from the stack, adds one, and continues there. So if you push "the routine's address minus one", high byte first, an RTS lands exactly at the routine:

via_rts tax
        lda rtshi,x
        pha
        lda rtslo,x
        pha
        rts

rtslo   dta <[cmd0-1],<[cmd1-1],<[cmd2-1],<[cmd3-1]
rtshi   dta >[cmd0-1],>[cmd1-1],>[cmd2-1],>[cmd3-1]

It needs no vector and changes no memory except the stack, so it works in ROM code with no RAM of its own. This is how CIO calls device handlers: the OS source routine CIJUMP pushes the handler's address and executes RTS, with the comment "go to handler indirectly". That is also why the handler tables at $E400, and the table of every handler you write yourself, hold addresses minus one (see Writing Your Own CIO Device Handler). The tables must hold address − 1. Forgetting it makes the routine start one byte late, usually in the middle of an instruction.

4. Method 3: patch the JMP

In RAM you can write the target straight into the operand of a JMP instruction:

via_smc tax
        lda addrlo,x
        sta smc+1
        lda addrhi,x
        sta smc+2
smc     jmp $FFFF           ; operand overwritten above

Self-modifying code is perfectly normal on the 6502, and it is the fastest option when the same target is used many times: patch once, then every later pass through smc costs only the 3-cycle JMP. It cannot work in a cartridge ROM, and it needs care if an interrupt routine might use the same code.

5. Costs

Counting the 6502's cycles for each dispatcher above, from TAX to arriving at the routine:

Method Cycles Needs
JMP (vector) 21 2 bytes of RAM for the vector (in zero page; 2 cycles more if it is elsewhere)
RTS trick 22 nothing but the stack; works in ROM
Self-modifying JMP 21 to patch, 3 per later use the code itself in RAM

They are close enough that the choice is usually about where the code lives, not speed. For a command loop that dispatches once per keypress, any of them will do. For a per-scan-line kernel that switches between handlers, patching ahead of time wins.

6. Calling a dispatcher

The example calls each dispatcher with JSR. The dispatcher then jumps to the routine, and the routine ends with RTS, which returns straight to the code after the original JSR, because the dispatcher's own stack frame was never added. This is the standard pattern: "JSR to the dispatcher, JMP to the routine, RTS back to the caller". Don't end a dispatcher with JSR plus RTS of its own unless you want to run code after the routine.

7. The JMP ($xxFF) bug

On the NMOS 6502, JMP (vector) doesn't carry into the high byte when it reads the vector. If the vector's low byte is at $37FF, the high byte is read from $3700, not $3800. The 65C02 fixed this: it reads $xxFF and the next page correctly, at the cost of an extra cycle.

The last part of the example demonstrates it. The vector at $37FF/$3800 points to a routine at $4000 that prints "OK". But $3700 holds $41, and a second routine at $4100 prints "BUG". On the NMOS 6502 that atari800 emulates, the program printed "JMP ($37FF) WENT TO $41xx: BUG".

How to avoid it:

  • Keep vectors off the last byte of a page. Zero-page vectors are the easy way: a vector at $CB–$CC can't straddle a page.
  • Watch automatically placed data. A vector declared among other variables can drift onto $xxFF as the program grows. MADS's .align can keep it safe, or keep vectors at the start of the data.
  • The Atari OS RAM vectors in page 2 are all safely placed.

8. The complete program

; Three ways to dispatch on a command number, plus the JMP ($xxFF) bug.
SAVMSC  = $58
PTR     = $CB
VEC     = $CD               ; 2-byte zero-page vector

        org $3000
start   lda #0
        sta row
        lda #2              ; method 1: JMP (VEC) via split tables
        jsr via_ind
        lda #3              ; method 2: the RTS trick
        jsr via_rts
        lda #1              ; method 3: self-modifying JMP
        jsr via_smc
        jsr bugtest         ; JMP indirect with the vector at $xxFF
        jmp *

; --- method 1: copy the address into a vector, JMP (VEC) ---
via_ind tax
        lda addrlo,x
        sta VEC
        lda addrhi,x
        sta VEC+1
        jmp (VEC)           ; the routine's RTS returns to our caller

; --- method 2: push address-1, then RTS "returns" into the routine ---
via_rts tax
        lda rtshi,x
        pha
        lda rtslo,x
        pha
        rts

; --- method 3: patch the operand of a JMP instruction ---
via_smc tax
        lda addrlo,x
        sta smc+1
        lda addrhi,x
        sta smc+2
smc     jmp $FFFF           ; operand overwritten above

; --- the four routines: each prints its own message ---
cmd0    ldx #0
        jmp say
cmd1    ldx #1
        jmp say
cmd2    ldx #2
        jmp say
cmd3    ldx #3
        jmp say

addrlo  dta <cmd0,<cmd1,<cmd2,<cmd3
addrhi  dta >cmd0,>cmd1,>cmd2,>cmd3
rtslo   dta <[cmd0-1],<[cmd1-1],<[cmd2-1],<[cmd3-1]
rtshi   dta >[cmd0-1],>[cmd1-1],>[cmd2-1],>[cmd3-1]

; print message X on the next screen row
say     stx tmp
        lda row
        tay
        lda SAVMSC
        clc
        adc rowlo,y
        sta PTR
        lda SAVMSC+1
        adc rowhi,y
        sta PTR+1
        inc row
        lda tmp
        asl
        asl
        asl
        asl
        asl                 ; 32 characters per message
        tax
        ldy #0
s1      lda msgs,x
        sta (PTR),y
        inx
        iny
        cpy #32
        bne s1
        rts

bugtest jmp (bugvec)        ; vector's low byte is at $37FF

tmp     dta 0
row     dta 0
rowlo   :8 dta <[#*40]
rowhi   :8 dta >[#*40]
msgs    dta d'ROUTINE 0                       '
        dta d'ROUTINE 1 (SELF-MODIFIED JMP)   '
        dta d'ROUTINE 2 (JMP (VECTOR))        '
        dta d'ROUTINE 3 (RTS TRICK)           '
        dta d'JMP ($37FF) WENT TO $41xx: BUG  '
        dta d'JMP ($37FF) WENT TO $40xx: OK   '

        org $3700
        dta >wrong          ; the NMOS 6502 takes the high byte from here

        org $37FF
bugvec  dta <right          ; low byte...
        dta >right          ; ...high byte at $3800, where it should come from

        org $4000
right   ldx #5
        jmp say
        org $4100
wrong   ldx #4
        jmp say

        run start

The routines cmd0–cmd3 each print their own line. The program asks method 1 for routine 2, method 2 for routine 3 and method 3 for routine 1, so each line on the screen proves that the right routine ran.

Troubleshooting

  • Crash right after a dispatch with the RTS trick: the table holds the addresses instead of address − 1, or the bytes were pushed in the wrong order (high byte first).
  • The wrong routine runs, but only sometimes: the index is outside the table. Check the range before dispatching (CMP #count, BCS error).
  • An indirect jump goes to a strange address: the vector straddles a page boundary ($xxFF).
  • Self-modifying dispatch fails in a cartridge: ROM can't be written. Use a vector or the RTS trick.
  • A routine returns to the wrong place: the dispatcher was reached with JMP and the routine ends in RTS, so there is no return address. Call the dispatcher with JSR.

Further reading

  • Atari, Operating System Source Listing: CIO's GOHAND and CIJUMP routines and the "addresses minus one" handler table.
  • Avery Lee, Altirra Hardware Reference Manual, chapter 3: the JMP (abs) page-wrap bug and its fix on the 65C02.
  • On this site: 6502 Addressing Modes, the Atari Way, The OS Jump Table: Calling the Atari Operating System the Supported Way, Writing Your Own CIO Device Handler, Relocatable Machine Code in BASIC Strings.

Credits