tuanp.dev

Part 3 of 20 · about an hour

A CPU with a memory

Last time our processor learned to count in a register. But two registers are all the storage it has, and the program it runs sits outside it in a separate Rust array. A real NES has neither problem: it has one big memory, and the program lives inside it. Today we build that.

By the end of this part

  • Your Cpu has 65,536 bytes of memory and runs its program from inside that memory.
  • It can store a register into any memory slot you name.
  • You can read a two-byte address the way the 6502 writes it: backwards.

A program last time's Cpu cannot run

Here is today's program. It puts $2A into one memory slot and $07 into the next:

A9 2A       LDA #$2A     put $2A into A
8D 00 02    STA $0200    store A in memory slot $0200
A9 07       LDA #$07     put $07 into A
8D 01 02    STA $0201    store A in memory slot $0201
00          BRK          stop

What will Part 2's Cpu make of it? Guess, then paste the eleven bytes into last time's program and run it.

$ cargo run -q
thread 'main' (4147678) panicked at src/main.rs:26:22:
unknown opcode $8D

As it should. $8D is STA, "store A", and it needs somewhere to store to.

Memory and addresses

The NES's processor is wired to a long row of byte-sized slots. That row is its memory. What is memory? Memory is a numbered row of bytes that the processor can read from and write to.

The number of a slot is its address. What is an address? An address is the position of one byte in memory. The 6502 uses two bytes to write an address, so addresses run from $0000 to $FFFF: 65,536 slots.

Memory drawn as one long row of boxes with gaps. Addresses 0000 onward, then 0200 and 0201 labelled "free space for the program's data", then 8000, 8001, 8002 holding A9, 2A, 8D labelled "the program is loaded here", ending at FFFF.000002000201800080018002FFFF………000000A92A8D00free space forthe program's datathe programis loaded here
One row, 65,536 boxes. The program is just some of the bytes in it, and pc is now an address.

Why does the program go at $8000? Because that is where a NES cartridge appears when you plug it in: the top half of memory, $8000 to $FFFF. The low addresses are the console's own working space. We will follow the same layout from the start.

Give the Cpu its memory

Two fields change in the struct:

src/main.rsSnapshot
struct Cpu {
    a: u8,
    x: u8,
    pc: u16,
    memory: [u8; 0x10000],
}

impl Cpu {
    fn new() -> Cpu {
        Cpu { a: 0, x: 0, pc: 0x8000, memory: [0; 0x10000] }
    }
  • memory: [u8; 0x10000] is an array of $10000 bytes, which is 65,536. [0; 0x10000] fills it with zeros.
  • pc: u16. A u16 is an unsigned 16-bit number, two bytes, 0 to 65,535. That is exactly the range of addresses, so it is the natural type for one. It starts at 0x8000.

Next, two small methods that are the only way the rest of the code touches memory:

    fn read(&self, addr: u16) -> u8 {
        self.memory[addr as usize]
    }
 
    fn write(&mut self, addr: u16, value: u8) {
        self.memory[addr as usize] = value;
    }

What is as usize doing there? Leave it out and ask the compiler:

$ cargo run -q
error[E0277]: the type `[u8]` cannot be indexed by `u16`
  --> src/main.rs:14:21
   |
14 |         self.memory[addr]
   |                     ^^^^ slice indices are of type `usize` or ranges of `usize`
   |
   ...
error: could not compile `nes` (bin "nes") due to 1 previous error

This is your first compiler error in this course, and it is worth a slow read, because you will see hundreds. It gives the file, line and column; it shows the line with the problem underlined; and it says what it wanted: array positions must be of type usize, the number type Rust uses for sizes and positions. Rust never converts between number types behind your back. You convert in the open, with as: addr as usize.

The program must get into memory somehow:

    // Copy a program into memory, starting at $8000.
    fn load(&mut self, program: &[u8]) {
        for i in 0..program.len() {
            self.memory[0x8000 + i] = program[i];
        }
    }

for i in 0..program.len() runs the body once for each i from 0 up to, but not including, the length. And &[u8], which we met last time, has a name: it is a slice. What is a slice? A slice is a view onto a run of values that live somewhere else; it knows where they start and how many there are. A slice of a 3-byte array and a slice of an 11-byte array have the same type, which is why load accepts any program.

Addresses are written backwards

Look again at the bytes for STA $0200:

8D 00 02

The opcode, then 00, then 02. The address $0200 has been split into its two bytes and stored with the low one first. The 6502 always does this. The convention is called little-endian. What is little-endian? Little-endian means a multi-byte number is stored with its least significant byte first.

Three boxes holding 8D, 00 and 02. The 00 is labelled low byte and the 02 is labelled high byte. Arrows cross over so that 02 comes first and 00 second in the address 0200 written below.8D0002STAlow bytehigh byte$ 02 00hi × 256 + lo2 × 256 + 0 = 512
The byte that arrives second is the one that counts for more.

Why multiply by 256? For the same reason the "3" in 37 is worth thirty: it sits one place to the left. One place to the left, in bytes, is worth 256.

In code, we first want a helper for "read the byte at pc and step past it", since we do that constantly. Then reading an address is two of those:

    // Read the byte at pc, then move pc past it.
    fn fetch(&mut self) -> u8 {
        let byte = self.read(self.pc);
        self.pc += 1;
        byte
    }
 
    // 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
    }

The as u16 widens each byte to 16 bits before the arithmetic. Without it, hi * 256 would be done in a u8 and would overflow at once. (Part 2 taught us what Rust thinks of that.)

Now watch STA $0200 happen, one fetch at a time.

The pc arrow walks along memory from address 8000: A9, 2A, 8D, 00, 02. Register A becomes 2A. The low byte 00 and high byte 02 are fetched and combined into address 0200, and the memory box at 0200 changes from 00 to 2A.80008001800280038004A92A8D0002A00pclo = ?hi = ?addr = $0200020000
fn fetch_addr(&mut self) -> u16 {
  let lo = self.fetch() as u16;
  let hi = self.fetch() as u16;
  hi * 256 + lo
}

0xA9 => self.a = self.fetch(),
0x8D => {
  let addr = self.fetch_addr();
  self.write(addr, self.a);
}
  1. The program has been loaded at $8000 and pc points there. A is 0 and so is memory slot $0200.
  2. A9 2A is our old friend LDA. A becomes 2A and pc is now $8002.
  3. Fetch the next opcode: $8D, STA. It is followed by a two-byte address.
  4. First fetch: the low byte of the address, 00.
  5. Second fetch: the high byte, 02. Put together: 2 × 256 + 0 is address $0200.
  6. Write A to that address. Memory slot $0200 now holds 2A.

The new run loop

With fetch doing the stepping, the loop gets shorter. run no longer takes the program as a parameter, because the program is in memory now.

    fn run(&mut self) {
        loop {
            let opcode = self.fetch();

            match opcode {
                0xA9 => self.a = self.fetch(), // LDA: load the next byte into A
                0x8D => {
                    // STA: store A at the address that follows
                    let addr = self.fetch_addr();
                    self.write(addr, self.a);
                }
                0xAA => self.x = self.a,                 // TAX: copy A into X
                0xE8 => self.x = self.x.wrapping_add(1), // INX: add one to X
                0x00 => break,                           // BRK: stop
                _ => panic!("unknown opcode ${:02X}", opcode),
            }
        }
    }

And main loads the program, runs it, and peeks at memory afterwards:

fn main() {
    let program: [u8; 11] = [
        0xA9, 0x2A,       // LDA #$2A
        0x8D, 0x00, 0x02, // STA $0200
        0xA9, 0x07,       // LDA #$07
        0x8D, 0x01, 0x02, // STA $0201
        0x00,             // BRK
    ];

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

    println!("A = ${:02X}  X = ${:02X}", cpu.a, cpu.x);
    println!("$0200: {:02X} {:02X} {:02X}", cpu.read(0x0200), cpu.read(0x0201), cpu.read(0x0202));
}
$ cargo run -q
A = $07  X = $00
$0200: 2A 07 00

Two values written by a 6502 program, still sitting in memory after it stopped.

Shortcuts we took on purpose

  • All 65,536 slots are plain storage. On a real NES some address ranges are not memory at all but connections to other chips. That is what read and write are for: they are the two doors we will rebuild in Part 8.
  • The program is loaded at $8000 and pc starts there because we say so. A real cartridge says where to start. Fixed in Part 6.
  • If pc ever stepped past $FFFF, self.pc += 1 would panic. Left open; no program in this course goes there.

What changed today

  • The Cpu has a memory field of 65,536 bytes, reached only through read and write.
  • load copies a program into memory at $8000; pc is a u16 address that starts there.
  • fetch reads one byte at pc; fetch_addr reads a little-endian address.
  • The processor knows STA ($8D): store A at an address.

Now you

  1. On paper: which three bytes are STA $07FF? Which address does 8D 34 12 store to? Check by running them.
  2. Add opcode $AD. It is also nicknamed LDA, but instead of loading the next byte it loads from the address in the next two bytes. Test it: store a value, load a different value into A, then load the stored one back.
    HintIt is STA with self.a = self.read(addr) in place of the write.
  3. Write, as bytes, a program that stores $2A into each of the five slots $0200 to $0204. How many bytes long is it? How long would it be for two hundred slots? There must be a better way, and Part 4 starts on it.
  4. From a blank file again. This time, try to write fetch and fetch_addr from memory before anything else.

Check your understanding

  1. What is memory?
    AnswerA numbered row of bytes that the processor can read from and write to.
  2. What is an address?
    AnswerThe position of one byte in memory. On the 6502 it is two bytes long, $0000 to $FFFF.
  3. What is a slice?
    AnswerA view onto a run of values that live somewhere else; it knows where they start and how many there are.
  4. What is little-endian?
    AnswerStoring a multi-byte number with its least significant byte first. $0200 is stored as 00 02.
  5. Why do we write addr as usize?
    AnswerArray positions must be usize, and Rust never converts between number types unless we ask with as.

Next time

Right now a program runs straight from top to bottom, once. To do something two hundred times you must write it out two hundred times. In Part 4 the processor learns to go back and do it again.