tuanp.dev

Part 5 of 20 · about an hour

A CPU that can walk through a list

Last time our processor learned to loop. But every lap of the loop did the same thing to the same places. The exercise asked which register already holds a different number on each lap. It is X: 0, then 1, then 2. Today we let an instruction use X as part of an address, and the loop starts doing real work.

By the end of this part

  • Your processor can read from and write to "this address, plus X".
  • It runs a loop that copies a list of bytes from one place in memory to another.
  • You can tell from an instruction's spelling where its value comes from.

A program that copies a word

Here is today's program. The last three bytes are not instructions at all. They are data: the list the program will copy.

8000  A2 00       LDX #$00       start with X = 0
8002  BD 0E 80    LDA $800E,X    load A from address $800E + X
8005  9D 00 02    STA $0200,X    store A at address $0200 + X
8008  E8          INX            add one to X
8009  E0 03       CPX #$03       done three?
800B  D0 F5       BNE $8002      if not, go back
800D  00          BRK            stop
800E  4E 45 53                   the data

Everything except the second and third lines is Part 4's loop. Those two lines are new, and they are written in a new way: an address, a comma, and X.

The address plus X

STA $0200 stores A at address $0200, always. STA $0200,X first adds whatever is in X to the address, and stores A there. With X = 0 that is $0200; with X = 1 it is $0201; with X = 2, $0202. Using a register to pick one item out of a row like this is called indexing, and it is what the X register is mainly for. What is indexing? Indexing is finding an item by adding its position in a list to the address where the list starts.

We now have three different ways an instruction can find the value it works on. The 6502 calls each of these ways an addressing mode. What is an addressing mode? An addressing mode is the rule an instruction uses to find the value it works on. The spelling tells you which one is in use:

mode          written        bytes       the value is...
immediate     LDA #$05       A9 05       the next byte itself
absolute      STA $0200      8D 00 02    at address $0200
absolute,X    STA $0200,X    9D 00 02    at address $0200 + X

The # means "this number itself, not the address with this number". Notice also that the same nickname gets a different opcode in each mode: STA is $8D in absolute mode and $9D in absolute,X mode. To the processor these are simply two different opcodes. The shared nickname is a kindness to humans.

Step through the copy. The program is on the right this time; watch which box X selects.

Three source boxes at addresses 800E, 800F and 8010 hold 4E, 45 and 53. Three destination boxes at 0200, 0201 and 0202 start at 00. As X counts 0, 1, 2, register A picks up each source byte in turn and drops it into the matching destination box.800E800F80104E4553020002010202000000+XX00A00
LDX #$00
LDA $800E,X
STA $0200,X
INX
CPX #$03
BNE (back to LDA)
BRK
  1. X starts at 0. The list sits at $800E; the three slots at $0200 are empty.
  2. LDA $800E,X: X is 0, so load from $800E + 0. A becomes 4E.
  3. STA $0200,X: X is still 0, so store at $0200 + 0. The first slot now holds 4E.
  4. INX makes X = 1. It is not 3 yet, so BNE sends us back to the LDA.
  5. The same LDA instruction, but X is 1 now, so it reads $800F. A becomes 45.
  6. The same STA, and it writes to $0201.
  7. INX makes X = 2. Still not 3; back again.
  8. Third lap: load from $8010, store to $0202. All three bytes are across.
  9. INX makes X = 3. CPX finds it equal to 3, BNE lets us through, and BRK stops.

Two instructions that never change, doing a different job on each lap because X changed. That is the whole trick, and nearly every loop in every NES game is built on it.

Build it

We already have fetch_addr, which reads a two-byte address. The new mode is that, plus X:

src/main.rsSnapshot
    // Read a two-byte address: low byte first, then high byte.
    fn fetch_addr(&mut self) -> u16 {
        let lo = self.fetch() as u16;
        let hi = self.fetch() as u16;
        hi * 256 + lo
    }

    // Read a two-byte address, then add X to it.
    fn fetch_addr_x(&mut self) -> u16 {
        let base = self.fetch_addr();
        base.wrapping_add(self.x as u16)
    }

X is a u8 and the address is a u16; Rust will not add two different number types, so we widen X first with as u16. And we use wrapping_add, because on a real 6502 an address that goes past $FFFF wraps round to $0000.

With that helper, the two new opcodes are copies of ones we have, with one word changed:

                0x8D => {
                    // STA: store A at the address that follows
                    let addr = self.fetch_addr();
                    self.write(addr, self.a);
                }
                0xBD => {
                    // LDA indexed: load A from (address + X)
                    let addr = self.fetch_addr_x();
                    self.a = self.read(addr);
                    self.zero = self.a == 0;
                }
                0x9D => {
                    // STA indexed: store A at (address + X)
                    let addr = self.fetch_addr_x();
                    self.write(addr, self.a);
                }

Compare 0x9D with 0x8D above it. The only difference is which helper finds the address. When a design is right, new features tend to be this cheap.

Finally main, with the new program. At the end we print the three slots, not as hex this time but as characters:

fn main() {
    let program: [u8; 17] = [
        0xA2, 0x00,       // 8000  LDX #$00
        0xBD, 0x0E, 0x80, // 8002  LDA $800E,X
        0x9D, 0x00, 0x02, // 8005  STA $0200,X
        0xE8,             // 8008  INX
        0xE0, 0x03,       // 8009  CPX #$03
        0xD0, 0xF5,       // 800B  BNE $8002
        0x00,             // 800D  BRK
        0x4E, 0x45, 0x53, // 800E  the data: "NES"
    ];

    let mut cpu = Cpu::new();
    cpu.load(&program);
    cpu.run();

    print!("$0200: ");
    for addr in 0x0200..0x0203 {
        print!("{}", cpu.read(addr) as char);
    }
    println!();
}
  • for addr in 0x0200..0x0203 walks addr through $0200, $0201, $0202. The end of a range is not included.
  • print! is println! without the new line at the end. The empty println!() afterwards finishes the line.
  • as char turns a byte into the character with that number.
$ cargo run -q
8000  A2  A=00 X=00 Z=0
8002  BD  A=00 X=00 Z=1
8005  9D  A=4E X=00 Z=0
8008  E8  A=4E X=00 Z=0
8009  E0  A=4E X=01 Z=0
800B  D0  A=4E X=01 Z=0
8002  BD  A=4E X=01 Z=0
8005  9D  A=45 X=01 Z=0
8008  E8  A=45 X=01 Z=0
8009  E0  A=45 X=02 Z=0
800B  D0  A=45 X=02 Z=0
8002  BD  A=45 X=02 Z=0
8005  9D  A=53 X=02 Z=0
8008  E8  A=53 X=02 Z=0
8009  E0  A=53 X=03 Z=0
800B  D0  A=53 X=03 Z=1
800D  00  A=53 X=03 Z=1
$0200: NES

The bytes 4E 45 53 were letters all along.

Data and code are the same stuff

The processor has no idea that 4E 45 53 is "data". Those bytes sit in the same memory as the instructions, and the only thing that keeps the processor from running them is that BRK stops it first. Prove it. Delete the BRK line from the program. Everything after it slides down by one address, so the list now starts at $800D: change 0x0E to 0x0D in the LDA line, and [u8; 17] to [u8; 16].

What will happen when the loop finishes?

$ cargo run -q
8000  A2  A=00 X=00 Z=0
8002  BD  A=00 X=00 Z=1
...
800B  D0  A=53 X=03 Z=1
800D  4E  A=53 X=03 Z=1
thread 'main' (4102735) panicked at src/main.rs:107:22:
unknown opcode $4E

(I have cut the middle of the trace, marked ....) The processor walked straight off the end of the program into the letter N and tried to carry it out as an instruction. On a real NES there is nothing to panic: it would do whatever $4E happens to mean and keep going, into nonsense. Every programmer for the machine had to make sure pc never wandered into data.

Put the BRK back.

Shortcuts we took on purpose

  • The 6502 has thirteen addressing modes. We have three. Left open; they are all variations on "work out an address, then read or write there".
  • Real emulators do not write the address logic into every opcode's arm. They use a table of 256 entries saying which instruction and which mode each opcode is. Left open; our match is fine for a dozen opcodes.

What changed today

  • fetch_addr_x reads an address and adds X to it.
  • New opcodes: LDA absolute,X ($BD) and STA absolute,X ($9D).
  • The program carries its own data after its last instruction.
  • main prints memory as characters.

Now you

  1. Make the program copy a five-letter word of your choice. Look the letters up in an ASCII table. Which numbers in the program have to change, and which stay the same?
  2. On paper, before running: if you change STA $0200,X to STA $0201,X but leave the printing code alone, what is printed?
  3. Add the opcode $4C, nicknamed JMP, "jump": the next two bytes are an address, and pc is set to it. No flag is involved. Test it with 4C 05 80 A9 01 A9 02 00: which LDA is skipped?
    HintTwo lines: let target = self.fetch_addr(); and self.pc = target;
  4. Think first, then try: what does the three-byte program 4C 00 80 do? (Press Ctrl-C to get your terminal back.) Odd as it looks, this is how real NES programs end, and Part 6 has to deal with it.

Check your understanding

  1. What is indexing?
    AnswerFinding an item by adding its position in a list to the address where the list starts.
  2. What is an addressing mode?
    AnswerThe rule an instruction uses to find the value it works on.
  3. What is the difference between LDA #$05 and LDA $0005?
    AnswerThe first loads the number 5 itself (immediate mode). The second loads whatever byte is stored at address $0005 (absolute mode).
  4. What stops the processor from running data as if it were instructions?
    AnswerNothing but the program itself: it must stop or jump away before pc reaches the data.

Next time

Right now every program we run is typed into our Rust source as an array. Real NES programs come in files. In Part 6 we open a cartridge file, find the program inside it, and let the cartridge tell us where to start.