Five parts in, your processor loads, stores, counts, loops and indexes. That is most of what any processor does. If the early parts felt slow, this is where they pay off: today's cartridge program uses only instructions you have already built.
Last time our processor copied a list from one part of memory to another. But the program was still typed by hand into main.rs. A real NES program arrives as a file. Today we read one.
By the end of this part
- Your emulator opens a
.nesfile and checks that it really is one. - It finds the program inside the file and puts it in memory.
- It starts running at the address the cartridge asks for, not one we made up.
- You know what Rust's
&has meant all along.
Get the cartridge
In the course's code folder there is a file called hello.nes. It is a small cartridge I wrote for this course, 40,976 bytes long. Copy it into your nes project folder, next to Cargo.toml. (The program that produced it is in code/mkrom. You do not need it now, but after Part 8 you will be able to read every line of it.)
Three questions stand between us and running it:
- How do we get a file's bytes into a Rust program?
- Which of those bytes are the program?
- Where in the program does the processor start?
A. Reading a file
Rust's standard library has a function for exactly this. Put this at the very top of main.rs:
use std::fs;and replace the first lines of main, where the hand-typed program was, with:
let rom: Vec<u8> = fs::read("hello.nes").expect("could not read hello.nes");
There are two new things in that line.
Vec<u8> is the type of rom. Our arrays so far had their length written in the type, like [u8; 17]. But nobody can know the size of a file before the program runs. A Vec handles that. What is a Vec? A Vec (short for vector) is a list whose length is decided while the program runs. Vec<u8> is a Vec of bytes.
.expect(…) is there because reading a file can fail. Rust has no exceptions. Instead, a function that can fail returns a Result. What is a Result? A Result is a value that is either Ok with the thing you asked for inside, or Err with the reason it went wrong. You cannot use the bytes without first dealing with the possibility of failure. .expect("message") is the bluntest way to deal with it: "give me what is inside the Ok, or else panic with this message".
See it fail. Run before you have copied hello.nes into place (or rename it for a moment):
$ cargo run -q
thread 'main' (4102784) panicked at src/main.rs:133:46:
could not read hello.nes: Os { code: 2, kind: NotFound, message: "No such file or directory" }
Our message, followed by the reason from inside the Err.
B. What is in the file
hello.nes, end to end. Today we only want the shaded part.A .nes file is a copy of the chips inside a cartridge, with a short label stuck on the front. The label is the iNES header. What is the iNES header? The iNES header is the first 16 bytes of a .nes file, which say what kind of cartridge it is and how big its parts are. (The name comes from iNES, an early emulator whose file format everyone adopted.)
After the header comes the PRG ROM. What is PRG ROM? PRG ROM is the part of a cartridge that holds the program: the bytes the processor will run. ("ROM" means read-only memory: a chip whose contents were fixed at the factory.) Byte 4 of the header says how many 16,384-byte blocks of it there are.
That is enough to check the file and cut out the program:
if rom[0..4] != [0x4E, 0x45, 0x53, 0x1A] {
panic!("this is not a NES cartridge file");
}
let prg_size = rom[4] as usize * 16384;
let prg = &rom[16..16 + prg_size];
println!("PRG ROM: {} bytes", prg.len());rom[0..4]is the first four bytes of the Vec. If they are not the signature, we refuse to go on.rom[4] as usize * 16384: byte 4, widened, times the block size. For our file that is 2 × 16,384 = 32,768.&rom[16..16 + prg_size]is a slice (Part 3): a view of the bytes from position 16, just past the header, to the end of the program. No bytes are copied.prgis a window onto part ofrom.
What the & has meant all along
This is a short detour into Rust itself, and the most important one in the course. Add two lines under the fs::read line, as an experiment:
let cartridge = rom;
println!("{} bytes", rom.len());$ cargo run -q
error[E0382]: borrow of moved value: `rom`
--> src/main.rs:136:26
|
133 | let rom: Vec<u8> = fs::read("hello.nes").expect("could not read hello.nes");
| --- move occurs because `rom` has type `Vec<u8>`, which does not implement the `Copy` trait
134 |
135 | let cartridge = rom;
| --- value moved here
136 | println!("{} bytes", rom.len());
| ^^^ value borrowed here after move
...
In most languages those two lines would be fine. In Rust, every value has exactly one owner: one variable that is responsible for it. let cartridge = rom; does not make a copy of forty thousand bytes. It hands the bytes over. From then on cartridge owns them and rom owns nothing, so the compiler refuses to let us use rom.
If handing things over were the only option, Rust would be unusable. The other option is to borrow. What is a borrow? A borrow, written &, is permission to use a value for a while without becoming its owner. &rom[16..] borrows part of rom. load(&mut self, program: &[u8]) borrows a Cpu, with permission to change it (&mut), and borrows some bytes just to look at them (&). When the function returns, the loans end and the owners still have their values.
That is what you have been writing since Part 2. Delete the two experiment lines; the detour is over.
Now the good news. Loading the program into memory needs no new code at all:
let mut cpu = Cpu::new();
cpu.load(prg);load, written in Part 3, takes any slice of bytes and copies it to $8000 onwards. 32,768 bytes from $8000 end exactly at $FFFF. The cartridge fills the top half of memory, as promised in Part 3.
C. Where to start
Until now pc started at $8000 because we decided so. A real 6502 decides nothing. When it is switched on it looks at two fixed addresses, $FFFC and $FFFD, the very end of the cartridge, and takes the two bytes there as the address to start from. Those two bytes are the reset vector. What is the reset vector? The reset vector is the address, stored by the cartridge at $FFFC, where the processor begins running after power-on or reset.
fn reset(&mut self) {
let lo = self.read(0xFFFC) as u16;
let hi = self.read(0xFFFD) as u16;
self.pc = hi * 256 + lo;
}- Power on. The cartridge is in memory but
pchas no meaningful value yet. - Read the byte at
$FFFC. Addresses are little-endian (Part 3), so this is the low byte:0A. - Read the byte at
$FFFD: the high byte,80. - Combine them as in Part 3.
pcbecomes$800A. - The first instruction will be fetched from
$800A. It isA9, an LDA. The ten bytes before it, from$8000, are data.
Add reset to the Cpu, just above fetch:
// Start where the cartridge says: the address stored at $FFFC.
fn reset(&mut self) {
let lo = self.read(0xFFFC) as u16;
let hi = self.read(0xFFFD) as u16;
self.pc = hi * 256 + lo;
}A program that never ends
Here is the program inside hello.nes. I wrote it using only opcodes we have, plus the JMP from last time's exercise:
8000 01 02 03 03 04 00 05 02 06 07 ten bytes of data
800A A9 20 LDA #$20
800C 8D 06 20 STA $2006
800F A9 20 LDA #$20
8011 8D 06 20 STA $2006
8014 A2 00 LDX #$00
8016 BD 00 80 LDA $8000,X next byte of the data
8019 8D 07 20 STA $2007
801C E8 INX
801D E0 0A CPX #$0A done all ten?
801F D0 F5 BNE $8016
8021 4C 21 80 JMP $8021 jump to... itselfYou can read this now. It stores $20 twice to address $2006, then loops ten times, each time loading one byte of the data and storing it to address $2007. Why those addresses, and why the same one ten times over? That is Part 8's story. Today they are just memory slots.
Look at the last line. A NES has no "stop". When a program has nothing more to do, it jumps to itself, forever. If you tried last time's final exercise, you saw what that does to our emulator. So our JMP gets one extra check: a jump whose target is the jump itself means "I am finished", and we leave the loop.
0x4C => {
// JMP: jump to the address that follows
let start = self.pc - 1;
let target = self.fetch_addr();
if target == start {
println!("jumping to itself at ${:04X}: stopping", target);
break;
}
self.pc = target;
}
0x00 => break, // BRK: stopself.pc - 1 is the address of the 4C opcode itself, because fetch has already stepped pc past it.
The end of main is now:
let mut cpu = Cpu::new();
cpu.load(prg);
cpu.reset();
cpu.run();
}Run it. I have cut the middle of the trace; yours will show all ten laps.
$ cargo run -q
PRG ROM: 32768 bytes
800A A9 A=00 X=00 Z=0
800C 8D A=20 X=00 Z=0
800F A9 A=20 X=00 Z=0
8011 8D A=20 X=00 Z=0
8014 A2 A=20 X=00 Z=0
8016 BD A=20 X=00 Z=1
8019 8D A=01 X=00 Z=0
801C E8 A=01 X=00 Z=0
801D E0 A=01 X=01 Z=0
801F D0 A=01 X=01 Z=0
8016 BD A=01 X=01 Z=0
8019 8D A=02 X=01 Z=0
...
8019 8D A=07 X=09 Z=0
801C E8 A=07 X=09 Z=0
801D E0 A=07 X=0A Z=0
801F D0 A=07 X=0A Z=1
8021 4C A=07 X=0A Z=1
jumping to itself at $8021: stopping
The first line of the trace says 800A, not 8000. Nobody typed that address into our Rust code. The cartridge said where to begin, and your emulator listened. That is a program from a .nes file, running on a processor you built.
Shortcuts we took on purpose
- We read two bytes of the header and ignore the rest. The other bytes describe extra hardware that bigger cartridges contain (the word to search for is "mapper"). Left open; ours is the simplest kind.
- We assume the program fills
$8000to$FFFF. Many small cartridges have only 16K of PRG ROM, which the NES shows twice. Left open, but see exercise 3. - Stopping at a jump-to-self is our invention. A real NES keeps running, and other things happen while the program spins. Left open; it is the first thing to change if you continue after this course.
- The file name is fixed in the source. See exercise 2.
What changed today
mainreadshello.nesinto aVec<u8>and checks the iNES signature.- The PRG ROM is sliced out of the file and loaded at
$8000by the oldload. resetsetspcfrom the reset vector at$FFFC.- New opcode:
JMP($4C), which also ends the run when it jumps to itself.
Now you
- Change the file name in
fs::readtoCargo.tomland run. Which of our two error messages do you get, and why that one? - Take the file name from the command line, so that
cargo run -q -- hello.nesworks.Hint
std::env::args().nth(1)gives the first word after the program name, wrapped in a type that might be empty. LikeResult, it has an.expect("…"). Pass the result tofs::readwith a&in front. - On paper: the reset vector is at address
$FFFCin memory. At which position in the file is it? Printromat that position and the next, and check that you see0Aand80.Hint
Memory address$8000is file position 16. - We have not looked at the last 8,192 bytes of the file. Print sixteen of them, starting at position
16 + prg_size + 7 * 16, one per line, using{:08b}as the hole: it prints a byte as eight binary digits. Lean back and squint at the ones. Do you see anything? Part 7 begins with this printout.
Check your understanding
- What is a Vec?
Answer
A list whose length is decided while the program runs. - What is a Result, and what does
.expectdo with one?Answer
A value that is eitherOkwith what you asked for, orErrwith the reason it failed..expectgives you the contents ofOk, or panics with your message. - What is the iNES header?
Answer
The first 16 bytes of a.nesfile, which say what kind of cartridge it is and how big its parts are. - What is PRG ROM?
Answer
The part of a cartridge that holds the program. - What is a borrow?
Answer
Permission, written&, to use a value for a while without becoming its owner. - What is the reset vector?
Answer
The address stored at$FFFCand$FFFDwhere the processor begins running.
Next time
Right now we use the program in the cartridge and ignore the other 8,192 bytes. They are the cartridge's pictures. In Part 7 we decode them and print them, and for the first time your emulator will show you something that is not a number.