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 dataEverything 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 + XThe # 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.
LDX #$00
LDA $800E,X
STA $0200,X
INX
CPX #$03
BNE (back to LDA)
BRK- X starts at 0. The list sits at
$800E; the three slots at$0200are empty. LDA $800E,X: X is 0, so load from$800E+ 0. A becomes 4E.STA $0200,X: X is still 0, so store at$0200+ 0. The first slot now holds 4E.- INX makes X = 1. It is not 3 yet, so BNE sends us back to the LDA.
- The same LDA instruction, but X is 1 now, so it reads
$800F. A becomes 45. - The same STA, and it writes to
$0201. - INX makes X = 2. Still not 3; back again.
- Third lap: load from
$8010, store to$0202. All three bytes are across. - 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:
// 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..0x0203walksaddrthrough$0200,$0201,$0202. The end of a range is not included.print!isprintln!without the new line at the end. The emptyprintln!()afterwards finishes the line.as charturns 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
matchis fine for a dozen opcodes.
What changed today
fetch_addr_xreads an address and adds X to it.- New opcodes:
LDAabsolute,X ($BD) andSTAabsolute,X ($9D). - The program carries its own data after its last instruction.
mainprints memory as characters.
Now you
- 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?
- On paper, before running: if you change
STA $0200,XtoSTA $0201,Xbut leave the printing code alone, what is printed? - Add the opcode
$4C, nicknamedJMP, "jump": the next two bytes are an address, andpcis set to it. No flag is involved. Test it with4C 05 80 A9 01 A9 02 00: whichLDAis skipped?Hint
Two lines:let target = self.fetch_addr();andself.pc = target; - Think first, then try: what does the three-byte program
4C 00 80do? (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
- What is indexing?
Answer
Finding an item by adding its position in a list to the address where the list starts. - What is an addressing mode?
Answer
The rule an instruction uses to find the value it works on. - What is the difference between
LDA #$05andLDA $0005?Answer
The first loads the number 5 itself (immediate mode). The second loads whatever byte is stored at address$0005(absolute mode). - What stops the processor from running data as if it were instructions?
Answer
Nothing but the program itself: it must stop or jump away beforepcreaches 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.