liveBook · Manning

Chip-8 memory

As explained in Systems Programming with Zig

CHIP-8 memory is the interpreter's data structure representing the virtual machine's addressable program and data storage.

A CHIP-8 interpreter needs somewhere to keep both bytecode and the state used to execute it. Its addressable memory is 4,096 bytes; instructions occupy two bytes each, combining an opcode with any operands. section 6.2.1 section 6.3.2

A practical Zig representation groups memory and CPU registers in one Memory struct. The data array holds 0x1000 bytes; pc and i are 12-bit registers, and vars holds sixteen 8-bit registers. The I register stores pointers, while pc tracks the program counter. section 6.2.1 section 6.3.2

Listing 6.5 Everything we can remember
pub const Memory = struct {
    const Self = @This();

    pub const total_memory_bytes = 0x1000; #1

    pc: u12, #2
    i: u12, #2
    vars: [16]u8,
    data: [total_memory_bytes]u8,
}

Inspect the fixed-size byte array and register fields in the Memory struct. section 6.3.2

To run a program, create a Memory value, load bytecode with loadProgram, and pass it to the interpreter’s step function. In a frame loop, step after reading the keypad and before drawing the display so input and output stay responsive. section 6.4.4

Addresses 0 through 0x1FF are reserved for the interpreter. One stack implementation starts at address zero: pushing stores the 12-bit program counter in two bytes and advances a stack pointer by two; popping reverses those operations. The stack pointer can be a Memory field or live in reserved memory, but loadProgram must reset it to its base value. section 6.5.6

Loading and stepping bytecode

A runtime can load an original CHIP-8 .bin program and call step 1,000 times per frame. The program may run before every instruction is implemented, although it can still encounter an unimplemented instruction. section 6.4.4

How Systems Programming with Zig covers it

How deep it goes
Specifies the memory and register fields and sketches runtime use and stack storage without detailing bytecode loading.
Examples
Uses original CHIP-8 bytecode programs and a stack starting in reserved interpreter memory.
What you can do after
Build a Memory struct from scratch in Zig, then load bytecode and pass the state to an interpreter step function.
How it connects
Connects bytecode, registers, the program counter, and a stack pointer to interpreter execution.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.