tuanp.dev

Part 6 of 20 · about an hour

Load a real cartridge file

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 .nes file 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:

  1. How do we get a file's bytes into a Rust program?
  2. Which of those bytes are the program?
  3. 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:

src/main.rsSnapshot
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

The cartridge file drawn as three sections in a row: a small header of 16 bytes, a large PRG ROM section of 32,768 bytes labelled "the program", and a CHR ROM section of 8,192 bytes labelled "the pictures".headerPRG ROMCHR ROM16 bytes32,768 bytes8,192 byteswhat kind ofcartridgethe programthe pictures(Part 7)
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.)

The first six bytes of the header: 4E, 45, 53, 1A, 02, 01. The first four are bracketed as "N, E, S and an end marker: the signature". Byte 4, holding 02, means two times 16K of program. Byte 5, holding 01, means one times 8K of pictures.0123454E45531A0201… then ten zerossignature: "NES" + end mark2 × 16K of program1 × 8K pictures
You have met the first three bytes before: they are the "NES" our processor copied in Part 5.

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. prg is a window onto part of rom.

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.

Two memory boxes at FFFC and FFFD hold 0A and 80. They are read as low byte and high byte and combined into the address 800A, which is put into pc. A dashed arrow then leads from the pair to the memory box at 800A, which holds A9, the first opcode of the program.8000800A800BFFFCFFFD01…A920…0A80pc?lo = ?hi = ?
fn reset(&mut self) {
    let lo = self.read(0xFFFC) as u16;
    let hi = self.read(0xFFFD) as u16;
    self.pc = hi * 256 + lo;
}
  1. Power on. The cartridge is in memory but pc has no meaningful value yet.
  2. Read the byte at $FFFC. Addresses are little-endian (Part 3), so this is the low byte: 0A.
  3. Read the byte at $FFFD: the high byte, 80.
  4. Combine them as in Part 3. pc becomes $800A.
  5. The first instruction will be fetched from $800A. It is A9, 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... itself

You 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: stop

self.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 $8000 to $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

  • main reads hello.nes into a Vec<u8> and checks the iNES signature.
  • The PRG ROM is sliced out of the file and loaded at $8000 by the old load.
  • reset sets pc from the reset vector at $FFFC.
  • New opcode: JMP ($4C), which also ends the run when it jumps to itself.

Now you

  1. Change the file name in fs::read to Cargo.toml and run. Which of our two error messages do you get, and why that one?
  2. Take the file name from the command line, so that cargo run -q -- hello.nes works.
    Hintstd::env::args().nth(1) gives the first word after the program name, wrapped in a type that might be empty. Like Result, it has an .expect("…"). Pass the result to fs::read with a & in front.
  3. On paper: the reset vector is at address $FFFC in memory. At which position in the file is it? Print rom at that position and the next, and check that you see 0A and 80.
    HintMemory address $8000 is file position 16.
  4. 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

  1. What is a Vec?
    AnswerA list whose length is decided while the program runs.
  2. What is a Result, and what does .expect do with one?
    AnswerA value that is either Ok with what you asked for, or Err with the reason it failed. .expect gives you the contents of Ok, or panics with your message.
  3. What is the iNES header?
    AnswerThe first 16 bytes of a .nes file, which say what kind of cartridge it is and how big its parts are.
  4. What is PRG ROM?
    AnswerThe part of a cartridge that holds the program.
  5. What is a borrow?
    AnswerPermission, written &, to use a value for a while without becoming its owner.
  6. What is the reset vector?
    AnswerThe address stored at $FFFC and $FFFD where 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.