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 stopWhat 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.
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:
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$10000bytes, which is 65,536.[0; 0x10000]fills it with zeros.pc: u16. Au16is 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 at0x8000.
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.
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.
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);
}- The program has been loaded at
$8000andpcpoints there. A is 0 and so is memory slot$0200. A9 2Ais our old friend LDA. A becomes 2A andpcis now$8002.- Fetch the next opcode:
$8D, STA. It is followed by a two-byte address. - First fetch: the low byte of the address,
00. - Second fetch: the high byte,
02. Put together: 2 × 256 + 0 is address$0200. - Write A to that address. Memory slot
$0200now 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
readandwriteare for: they are the two doors we will rebuild in Part 8. - The program is loaded at
$8000andpcstarts there because we say so. A real cartridge says where to start. Fixed in Part 6. - If
pcever stepped past$FFFF,self.pc += 1would panic. Left open; no program in this course goes there.
What changed today
- The Cpu has a
memoryfield of 65,536 bytes, reached only throughreadandwrite. loadcopies a program into memory at$8000;pcis au16address that starts there.fetchreads one byte atpc;fetch_addrreads a little-endian address.- The processor knows
STA($8D): store A at an address.
Now you
- On paper: which three bytes are
STA $07FF? Which address does8D 34 12store to? Check by running them. - Add opcode
$AD. It is also nicknamedLDA, 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.Hint
It isSTAwithself.a = self.read(addr)in place of the write. - Write, as bytes, a program that stores
$2Ainto each of the five slots$0200to$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. - From a blank file again. This time, try to write
fetchandfetch_addrfrom memory before anything else.
Check your understanding
- What is memory?
Answer
A numbered row of bytes that the processor can read from and write to. - What is an address?
Answer
The position of one byte in memory. On the 6502 it is two bytes long,$0000to$FFFF. - What is a slice?
Answer
A view onto a run of values that live somewhere else; it knows where they start and how many there are. - What is little-endian?
Answer
Storing a multi-byte number with its least significant byte first.$0200is stored as00 02. - Why do we write
addr as usize?Answer
Array positions must beusize, and Rust never converts between number types unless we ask withas.
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.