Skip to content
systemcoding.dev
Virtualization

The Complete Guide to Writing an Emulator

Learn to write a CPU emulator in C from nothing: registers, memory, the fetch-decode-execute loop, flags, timing, devices, testing and a path to RISC-V.

30 min read
Summarize in AI
Flat illustration of guest machines running on a hypervisor over hardware, with the QEMU, C and RISC-V logos.

An emulator is a program that behaves like another machine. You feed it the machine code of an old game console, a 1970s microprocessor or a modern RISC-V core, and it produces the same results the real chip would, one instruction at a time. People write emulators to preserve software whose hardware has died, to test firmware before the board exists, to learn how processors really work and, frankly, because it is one of the most satisfying programs you can build. This guide teaches the whole craft from zero, in C, using a deliberately tiny processor first and then showing how every idea carries over to real ones. By the end you will have written a complete working CPU core, a memory bus, a display, a test harness and a plan for the next machine. The code uses C11 as implemented by GCC 14 and Clang 19 on Linux, and the examples are written to be correct against those compilers.

You need to read C: structures, pointers, arrays and bitwise operators. You do not need to know assembly, electronics or how any real CPU works, because the guide builds that understanding as it goes. If bit operations are shaky, the post on binary, hex and bit masks in this cluster covers them first.

What this guide covers and what it leaves out

It covers the interpreter style of emulator, where a loop reads each instruction and carries out its effect in software. That is how nearly every first emulator works, and it is enough to run real programs on 8-bit and 32-bit processors at full speed on a modern computer. It covers the CPU, memory and memory-mapped devices, flags, timing, input and output, debugging and testing. It leaves out dynamic recompilation, which translates guest code to host machine code and is covered by the post on interpreters versus JITs, cycle-exact emulation of graphics chips, which is a subject of its own, and hardware virtualization, which runs guest code natively and is the hypervisor cluster's subject. The distinction matters, and the guide explains it in the first section.

If you want to run an existing operating system quickly on the same type of processor as your computer, you want a hypervisor such as KVM, not an emulator. If you want to run code for a different processor, or want to understand a processor completely, you want an emulator, and this guide is for you.

What an emulator is, and what it is not

A machine is a processor plus everything it talks to: memory, a display, input devices, timers. Each processor has an instruction set architecture (ISA), the definition of what bytes mean as instructions and what each does to the machine. To emulate a machine in software, you represent its state as variables, and you write a function that takes the state and one instruction and produces the next state. Do that in a loop and the machine runs.

Three terms get confused, and it helps to separate them.

  • Emulation reproduces the behavior of one machine on a different one, by interpreting or translating its instructions. A CHIP-8 emulator running on an x86-64 laptop is an emulator.

  • Simulation models a design in more detail than behavior, often down to the logic gates or the clock cycle, to study it. The goal is insight into the hardware itself.

  • Virtualization runs guest code directly on the same kind of processor, with hardware help, and intervenes only for privileged operations. KVM is that.

An emulator can be as faithful as you choose. The easiest target reproduces what a program sees through the instruction set. A harder one reproduces timing, so that a game that depends on exact cycle counts behaves correctly. This guide builds the first kind and explains where the second begins.

The anatomy of every emulator

Whatever the machine, an emulator has the same five parts.

  1. CPU state: the registers, including the program counter, a stack pointer, flags and general-purpose registers.

  2. Memory: an array of bytes, plus rules about which addresses are RAM, which are ROM and which are special.

  3. The instruction loop: fetch, decode, execute, repeated.

  4. Devices: the display, keyboard, timers, sound and storage, reached through memory addresses or special instructions.

  5. A host shell: the code that opens a window, reads real keys, plays audio and keeps time.

Keep those parts in separate files or at least separate structures from the first day. The most common reason an emulator becomes unmaintainable is a CPU function that reaches directly into the window library. If the CPU only knows about a bus with read and write, you can test it with no graphics at all.

A toy machine to learn on

Real processors have hundreds of instructions. To learn the structure without drowning, this guide first defines a toy machine, a small 8-bit processor invented for the exercise, and emulates it completely. Everything you learn transfers directly. Its definition:

  • 64 KiB of memory, addressed 0x0000 to 0xFFFF.

  • Registers: an accumulator A (8 bits), a program counter PC (16 bits), and a zero flag Z.

  • Instructions, each one opcode byte optionally followed by a one-byte or two-byte operand:

OpcodeMnemonicOperandEffect
0x00HLTnoneStop the machine
0x01LDI n1 byteA = n
0x02LDA addr2 bytesA = memory[addr]
0x03STA addr2 bytesmemory[addr] = A
0x04ADD addr2 bytesA = A + memory[addr] (wraps at 256)
0x05SUB addr2 bytesA = A - memory[addr] (wraps)
0x06JMP addr2 bytesPC = addr
0x07JZ addr2 bytesif Z is set, PC = addr
0x08OUTnonewrite A as a character to the output

The Z flag is set when the result of LDI, LDA, ADD or SUB is zero. Addresses are stored little-endian: low byte first. That mirrors the 6502 and the x86, and you will see why it matters in the memory section.

State: registers and memory

The CPU state is a structure. Using fixed-width integer types from <stdint.h> makes the widths explicit, so that 8-bit arithmetic wraps the way the real chip's does.

toy.hc
#ifndef TOY_H
#define TOY_H

#include <stdbool.h>
#include <stdint.h>

#define MEM_SIZE 0x10000

typedef struct {
    uint8_t  mem[MEM_SIZE];
    uint8_t  a;
    uint16_t pc;
    bool     z;
    bool     halted;
    char     out[256];   /* characters produced by OUT */
    unsigned out_len;
} Toy;

void toy_reset(Toy *m);
void toy_load(Toy *m, uint16_t addr, const uint8_t *data, unsigned len);
void toy_step(Toy *m);
void toy_run(Toy *m, unsigned max_steps);

#endif

An unsigned 8-bit variable wraps automatically in C: uint8_t x = 255; x++; gives 0. That is exactly the behaviour a real 8-bit register has, and it is why emulators use unsigned types for registers. The classic bug is using plain int for a register and forgetting to mask it back to 8 bits after arithmetic.

Memory and endianness

Memory is the array mem. Reading and writing one byte is direct. Reading a 16-bit address operand takes two bytes, and the order in which the two bytes are stored is called endianness. On a little-endian machine the low byte is stored first. The instruction JMP 0x1234 assembles to the bytes 06 34 12: the opcode, then 34, then 12.

Write the two-byte read as a helper and use it everywhere, so the byte order is decided in exactly one place:

bus.cc
#include "toy.h"

static inline uint8_t read8(const Toy *m, uint16_t addr)
{
    return m->mem[addr];
}

static inline uint16_t read16(const Toy *m, uint16_t addr)
{
    return (uint16_t)(m->mem[addr] | (m->mem[(uint16_t)(addr + 1)] << 8));
}

static inline void write8(Toy *m, uint16_t addr, uint8_t value)
{
    m->mem[addr] = value;
}

The cast of addr + 1 to uint16_t makes the address wrap from 0xFFFF to 0x0000, as a 16-bit address bus does. Real chips have many such wrap-around behaviours and programs sometimes depend on them, so decide deliberately what each should do.

Today the write8 function does nothing special. Later, it becomes the place where you decide that writes to the range of ROM are ignored and writes to a particular address update the display. Routing every access through these three functions is the single most useful structural habit in emulator writing, because devices plug in at that one point.

The fetch-decode-execute loop

Every processor repeats three phases. Fetch: read the instruction at the address in the program counter and advance the counter. Decode: work out which instruction the bytes mean. Execute: perform its effect. Written for the toy machine:

cpu.cc
#include "toy.h"
#include <string.h>

uint8_t  read8(const Toy *m, uint16_t addr);
uint16_t read16(const Toy *m, uint16_t addr);

void toy_reset(Toy *m)
{
    memset(m, 0, sizeof *m);
}

void toy_load(Toy *m, uint16_t addr, const uint8_t *data, unsigned len)
{
    for (unsigned i = 0; i < len; i++)
        m->mem[(uint16_t)(addr + i)] = data[i];
}

static void set_a(Toy *m, uint8_t v)
{
    m->a = v;
    m->z = (v == 0);
}

void toy_step(Toy *m)
{
    uint8_t op = m->mem[m->pc++];          /* fetch */

    switch (op) {                          /* decode */
    case 0x00:                             /* HLT */
        m->halted = true;
        break;
    case 0x01: {                           /* LDI n */
        uint8_t n = m->mem[m->pc++];
        set_a(m, n);
        break;
    }
    case 0x02: {                           /* LDA addr */
        uint16_t addr = (uint16_t)(m->mem[m->pc] | (m->mem[(uint16_t)(m->pc + 1)] << 8));
        m->pc += 2;
        set_a(m, m->mem[addr]);
        break;
    }
    case 0x03: {                           /* STA addr */
        uint16_t addr = (uint16_t)(m->mem[m->pc] | (m->mem[(uint16_t)(m->pc + 1)] << 8));
        m->pc += 2;
        m->mem[addr] = m->a;
        break;
    }
    case 0x04: {                           /* ADD addr */
        uint16_t addr = (uint16_t)(m->mem[m->pc] | (m->mem[(uint16_t)(m->pc + 1)] << 8));
        m->pc += 2;
        set_a(m, (uint8_t)(m->a + m->mem[addr]));
        break;
    }
    case 0x05: {                           /* SUB addr */
        uint16_t addr = (uint16_t)(m->mem[m->pc] | (m->mem[(uint16_t)(m->pc + 1)] << 8));
        m->pc += 2;
        set_a(m, (uint8_t)(m->a - m->mem[addr]));
        break;
    }
    case 0x06: {                           /* JMP addr */
        m->pc = (uint16_t)(m->mem[m->pc] | (m->mem[(uint16_t)(m->pc + 1)] << 8));
        break;
    }
    case 0x07: {                           /* JZ addr */
        uint16_t addr = (uint16_t)(m->mem[m->pc] | (m->mem[(uint16_t)(m->pc + 1)] << 8));
        m->pc += 2;
        if (m->z)
            m->pc = addr;
        break;
    }
    case 0x08:                             /* OUT */
        if (m->out_len < sizeof m->out - 1)
            m->out[m->out_len++] = (char)m->a;
        break;
    default:                               /* unknown opcode */
        m->halted = true;
        break;
    }
}

void toy_run(Toy *m, unsigned max_steps)
{
    for (unsigned i = 0; i < max_steps && !m->halted; i++)
        toy_step(m);
}

The switch is the decoder. Notice that the operand is read at the moment it is needed and the program counter is advanced by exactly the operand's size. Getting pc arithmetic wrong is the second most common beginner bug: a two-byte operand must advance pc by two, and a jump must replace the counter and not add to it.

The repeated address-reading expression is ugly, which is itself a lesson. Real emulators factor each way of finding an operand into a function called an addressing mode. The 6502 post in this cluster is about that, and the toy machine has only one mode, absolute.

Running a first program

To use the machine you need machine code. Write a program that prints OK and halts, and assemble it by hand, which is feasible because the instruction set is small. LDI 'O' is 01 4F, OUT is 08, LDI 'K' is 01 4B, OUT is 08 and HLT is 00.

main.cc
#include <stdio.h>
#include "toy.h"

int main(void)
{
    static Toy m;
    const uint8_t prog[] = {
        0x01, 'O', 0x08,     /* LDI 'O'; OUT */
        0x01, 'K', 0x08,     /* LDI 'K'; OUT */
        0x00,                /* HLT */
    };

    toy_reset(&m);
    toy_load(&m, 0x0000, prog, sizeof prog);
    toy_run(&m, 1000);

    m.out[m.out_len] = '\0';
    printf("output: %s\n", m.out);
    printf("pc=0x%04x a=0x%02x\n", m.pc, m.a);
    return 0;
}
Text
output: OK
pc=0x0007 a=0x4b

The program counter ends at 7, one past the HLT, because fetch advances it before the instruction executes. That is true of real processors too, and it matters when you implement jumps relative to the next instruction. Compile with gcc -std=c11 -Wall -Wextra -O2 main.c cpu.c bus.c -o toy.

Flags, and why they are where bugs live

The Z flag shows the pattern that makes real processors harder than the toy. Instructions have side effects on a status register: whether the last result was zero, negative, carried out of the top bit or overflowed. Later instructions branch on those. Emulating a processor accurately means emulating every flag side effect of every instruction, and most emulator bugs are a flag set wrongly in an edge case.

Take addition with a carry. The 8-bit result wraps, and the carry flag records whether the true sum needed a ninth bit. Computing it correctly means doing the sum in a wider type:

flags.cc
#include <stdint.h>
#include <stdio.h>

typedef struct { uint8_t result; unsigned carry; unsigned zero; unsigned negative; } AddResult;

AddResult add8(uint8_t a, uint8_t b)
{
    unsigned wide = (unsigned)a + (unsigned)b;   /* up to 510 */
    AddResult r;
    r.result   = (uint8_t)wide;
    r.carry    = wide > 0xff;
    r.zero     = r.result == 0;
    r.negative = (r.result & 0x80) != 0;
    return r;
}

int main(void)
{
    AddResult r = add8(0xf0, 0x20);
    printf("result=0x%02x carry=%u zero=%u negative=%u\n",
           r.result, r.carry, r.zero, r.negative);
    return 0;
}
Text
result=0x10 carry=1 zero=0 negative=0

The same sum shows that signed overflow is a different thing from carry. 0x70 + 0x70 gives 0xE0, which is a carry of 0 but a signed overflow, since two positive numbers produced a negative one. The overflow flag is ((a ^ result) & (b ^ result) & 0x80) != 0, a formula worth memorizing because every two's-complement processor needs it. The post on the 6502 functional test suite shows how to find these bugs systematically.

Memory-mapped input and output

A machine with only memory and a CPU can compute but not interact. Devices attach in two ways. Memory-mapped I/O gives a device a range of addresses: reading or writing them talks to the device, not to RAM. Port I/O uses separate instructions and a separate address space. The toy machine's OUT is port-like, but most small processors use memory mapping, and it is easy to add with the read8 and write8 functions.

Add a rule to the bus: a write to address 0xFF00 prints the byte to the output, and a read from 0xFF01 returns 1 if a key is available. The CPU's STA 0xFF00 now prints, with no special instruction.

bus_mmio.cc
#include <stdint.h>
#include <stdio.h>

#define PORT_OUT 0xFF00
#define PORT_KEY 0xFF01

typedef struct {
    uint8_t ram[0x10000];
    int     key_pending;
} Bus;

uint8_t bus_read(Bus *b, uint16_t addr)
{
    if (addr == PORT_KEY)
        return b->key_pending ? 1 : 0;
    return b->ram[addr];
}

void bus_write(Bus *b, uint16_t addr, uint8_t v)
{
    if (addr == PORT_OUT) {
        putchar(v);
        return;
    }
    b->ram[addr] = v;
}

The pattern scales to a real display: a range of memory is video RAM, and the host shell reads it each frame and draws it. A write to a special address starts a sound. A read from another returns the state of a controller. All of it is the same two functions growing more cases, which is why those functions are the place an emulator is organized around.

Timing: how fast should it run

Real processors run at a fixed clock rate, and the original software was written for it. A game's speed is set by how many instructions execute per frame. If your emulator runs instructions as fast as the host can, the game runs absurdly fast.

The standard fix is a frame-based loop: decide how many CPU cycles pass per video frame, run that many, draw the frame and wait until the next frame time. To do that you need each instruction's cycle count. The simplest approach is a table, plus counting cycles in step:

timing.cc
#include <stdint.h>

/* cycles per opcode for the toy machine; 0 means unused */
static const uint8_t cycles[256] = {
    [0x00] = 1, [0x01] = 2, [0x02] = 4, [0x03] = 4,
    [0x04] = 4, [0x05] = 4, [0x06] = 3, [0x07] = 3, [0x08] = 2,
};

/* Run until a frame's worth of cycles has elapsed. */
void run_frame(Toy *m, unsigned cycles_per_frame)
{
    unsigned spent = 0;
    while (spent < cycles_per_frame && !m->halted) {
        uint8_t op = m->mem[m->pc];
        toy_step(m);
        spent += cycles[op];
    }
}

With a 1 MHz toy clock and 60 frames per second, cycles_per_frame is 16,666. The host side calls run_frame, presents the screen and sleeps until the next sixtieth of a second. This instruction-stepped approach is accurate enough for a large share of software. Programs that change graphics registers in the middle of a frame, which many console games do, need cycle-exact emulation, where the CPU and the video chip advance in lockstep. That is a deep topic, and the post on cycle stepping versus catch-up scheduling covers it.

Putting it together: a loop that counts

A program with a loop shows jumps and flags working together. This one counts from 3 down to 0, printing a digit each time, using a data byte at address 0x0100 for the counter and another at 0x0101 containing the constant 1:

Hand-assembling by byte offset is exactly how early programmers worked, and it is why every machine got an assembler: one wrong address and a jump lands in the middle of an operand. Check each offset below against the comments, since the JZ must target the HLT at 0x0018 and the JMP at 0x0015 must return to the top.

countdown.cc
#include <stdio.h>
#include "toy.h"

int main(void)
{
    static Toy m;
    toy_reset(&m);

    const uint8_t prog[] = {
        0x02, 0x00, 0x01,   /* 0000 LDA 0x0100 */
        0x07, 0x18, 0x00,   /* 0003 JZ  0x0018 */
        0x01, '0',          /* 0006 LDI '0'    */
        0x04, 0x00, 0x01,   /* 0008 ADD 0x0100 */
        0x08,               /* 000B OUT        */
        0x02, 0x00, 0x01,   /* 000C LDA 0x0100 */
        0x05, 0x01, 0x01,   /* 000F SUB 0x0101 */
        0x03, 0x00, 0x01,   /* 0012 STA 0x0100 */
        0x06, 0x00, 0x00,   /* 0015 JMP 0x0000 */
        0x00,               /* 0018 HLT        */
    };

    toy_load(&m, 0x0000, prog, sizeof prog);
    m.mem[0x0100] = 3;
    m.mem[0x0101] = 1;

    toy_run(&m, 1000);
    m.out[m.out_len] = '\0';
    printf("%s\n", m.out);
    return 0;
}
Text
321

Trace the first pass: LDA loads 3, Z is clear, so JZ does not jump. LDI '0' gives 0x30, ADD adds 3 to reach 0x33 ('3') and OUT prints it. The counter is decremented and stored, and JMP returns to the start. After three passes the counter is zero, LDA sets Z, JZ jumps to the HLT and the machine stops. The output is 321.

Debugging an emulator

Emulators fail silently. The program runs, the screen shows garbage and nothing tells you which of ten thousand instructions went wrong. Build three tools early.

A trace prints each instruction as it executes, with the program counter and the registers. Add a flag to toy_step that prints a line before each fetch:

trace.cc
#include <stdio.h>
#include "toy.h"

void trace(const Toy *m)
{
    printf("%04x  op=%02x  A=%02x Z=%d\n",
           m->pc, m->mem[m->pc], m->a, m->z);
}

For the first instructions of the countdown program the trace looks like this:

Text
0000  op=02  A=00 Z=0
0003  op=07  A=03 Z=0
0006  op=01  A=03 Z=0
0008  op=04  A=30 Z=0
000b  op=08  A=33 Z=0

A trace is also how you compare against a reference. If a trusted emulator exists for your machine, run the same program in both and compare traces line by line. The first line that differs is the bug, found in minutes instead of hours. Many processors have published trace logs for exactly this purpose.

A single-step mode executes one instruction and waits for a key, so you can inspect state. A breakpoint stops when the program counter reaches an address, which is a comparison in the run loop. These three together make an emulator debuggable, and adding them early saves the most time of anything in this guide.

Testing a CPU core

Trust in a CPU core comes from tests, written before you need them. Three levels work well.

Unit tests per instruction. For each opcode, set up the registers and memory, execute one step and check the result and flags. They are tedious and catch the majority of bugs early. Table-driven tests keep them short.

Test ROMs. The community that preserves each processor has written programs that exercise every instruction and report failures. They run in your emulator and print pass or fail. For the 6502 the functional test by Klaus Dormann is the standard, and the post on passing it explains how to use it. For the Game Boy's CPU there are test ROMs by Blargg. Passing one is strong evidence of correctness.

Single-step JSON suites. Some projects publish, for each opcode, thousands of cases listing the initial state, one instruction and the final state, recorded from real hardware or a trusted model. You load a case, run one step and compare. The post on validating with single-step JSON test suites builds that harness.

Here is the shape of a unit test for the toy machine's ADD, written without a framework:

test_add.cc
#include <assert.h>
#include <stdio.h>
#include "toy.h"

static void test_add_wraps_and_sets_zero(void)
{
    static Toy m;
    toy_reset(&m);
    m.a = 0xff;
    m.mem[0x0100] = 0x01;
    const uint8_t prog[] = { 0x04, 0x00, 0x01 };   /* ADD 0x0100 */
    toy_load(&m, 0, prog, sizeof prog);

    toy_step(&m);

    assert(m.a == 0x00);
    assert(m.z == true);
    assert(m.pc == 3);
}

int main(void)
{
    test_add_wraps_and_sets_zero();
    puts("all tests passed");
    return 0;
}
Text
all tests passed

Subroutines and the stack

A processor with only jumps cannot call a function and return, because a return needs to know where the call came from. The solution is a stack: a region of memory with a stack pointer register. A call pushes the return address and jumps. A return pops it into the program counter.

Extend the toy machine with two instructions, CALL addr (opcode 0x09) and RET (opcode 0x0A), and a 16-bit stack pointer sp, which starts at 0xFFFE and grows downward. The common convention on small processors is that the stack grows toward lower addresses, so a push first decrements the pointer and then writes.

stack.cc
#include "toy.h"

/* Add `uint16_t sp;` to the Toy structure and set it to 0xFFFE in toy_reset. */

static void push16(Toy *m, uint16_t value)
{
    m->sp = (uint16_t)(m->sp - 2);
    m->mem[m->sp]                    = (uint8_t)(value & 0xff);
    m->mem[(uint16_t)(m->sp + 1)]    = (uint8_t)(value >> 8);
}

static uint16_t pop16(Toy *m)
{
    uint16_t lo = m->mem[m->sp];
    uint16_t hi = m->mem[(uint16_t)(m->sp + 1)];
    m->sp = (uint16_t)(m->sp + 2);
    return (uint16_t)(lo | (hi << 8));
}

/* Inside the switch in toy_step: */
case 0x09: {                                   /* CALL addr */
    uint16_t addr = (uint16_t)(m->mem[m->pc] | (m->mem[(uint16_t)(m->pc + 1)] << 8));
    m->pc += 2;
    push16(m, m->pc);                          /* return address: the next instruction */
    m->pc = addr;
    break;
}
case 0x0a:                                     /* RET */
    m->pc = pop16(m);
    break;

The detail that trips people up is which address is pushed. By the time CALL executes, pc has already advanced past the operand, so it points at the next instruction, which is exactly what RET should return to. Some real processors differ: the 6502's JSR pushes the address of the last byte of the instruction, one less than the return point, and its RTS adds one after popping. When you emulate a real chip, the documentation is explicit about this, and getting it off by one is a classic bug that makes a program jump into the middle of an instruction.

The stack also shows why the bus matters. The stack lives in ordinary RAM, so a program that writes to addresses near the stack pointer corrupts its own return addresses, exactly as on real hardware. You do not add a rule for that. It emerges from modelling the machine faithfully.

Interrupts

An interrupt is a signal from a device that makes the processor stop what it is doing, save its place and run a handler. A timer ticks, a key is pressed or a frame finishes drawing, and the program needs to react without polling constantly.

Emulating one has four steps. A device raises a flag meaning "interrupt pending". Between instructions, the main loop checks that flag and a flag saying whether the processor currently accepts interrupts. If both allow it, the CPU pushes the program counter, clears the accept flag so a handler is not itself interrupted, and loads the program counter from a fixed address, called a vector. A return-from-interrupt instruction pops the counter back and sets the accept flag again.

irq.cc
#include "toy.h"

#define IRQ_VECTOR 0x0100

/* Toy additions: bool irq_pending; bool irq_enabled; */

void toy_step_with_irq(Toy *m)
{
    if (m->irq_pending && m->irq_enabled) {
        m->irq_pending = false;
        m->irq_enabled = false;
        /* push16 as defined earlier */
        extern void toy_push16(Toy *, uint16_t);
        toy_push16(m, m->pc);
        m->pc = IRQ_VECTOR;
        return;
    }
    toy_step(m);
}

Checking only between instructions is the right granularity for an instruction-accurate core, and it is how most machines behave too, since a processor finishes the instruction it is executing before taking the interrupt. The subtle cases are instructions that enable interrupts: many processors delay the effect by one instruction, so that a return directly after the enable cannot be interrupted before it executes. The reference manual for each chip states the rule, and test ROMs check it.

Writing a disassembler first

A disassembler turns machine code back into readable instructions. It is the second most useful tool after the trace, and writing it is nearly free once you have the opcode table, because decoding is the same work. A disassembler for the toy machine is a function that returns the text of the instruction at an address and its length:

disasm.cc
#include <stdio.h>
#include "toy.h"

/* Writes the instruction at addr into out and returns its length in bytes. */
unsigned disasm(const Toy *m, uint16_t addr, char *out, unsigned cap)
{
    uint8_t op = m->mem[addr];
    uint16_t abs = (uint16_t)(m->mem[(uint16_t)(addr + 1)] |
                              (m->mem[(uint16_t)(addr + 2)] << 8));
    switch (op) {
    case 0x00: snprintf(out, cap, "HLT");            return 1;
    case 0x01: snprintf(out, cap, "LDI #$%02x", m->mem[(uint16_t)(addr + 1)]); return 2;
    case 0x02: snprintf(out, cap, "LDA $%04x", abs); return 3;
    case 0x03: snprintf(out, cap, "STA $%04x", abs); return 3;
    case 0x04: snprintf(out, cap, "ADD $%04x", abs); return 3;
    case 0x05: snprintf(out, cap, "SUB $%04x", abs); return 3;
    case 0x06: snprintf(out, cap, "JMP $%04x", abs); return 3;
    case 0x07: snprintf(out, cap, "JZ  $%04x", abs); return 3;
    case 0x08: snprintf(out, cap, "OUT");            return 1;
    default:   snprintf(out, cap, ".byte $%02x", op); return 1;
    }
}

Run it over the first instructions of the countdown program and it prints:

Text
0000  LDA $0100
0003  JZ  $0018
0006  LDI #$30
0008  ADD $0100
000b  OUT

When you debug a real program, the disassembly beside the trace tells you what the machine was trying to do at the moment it went wrong, which is far more useful than raw bytes. The instruction length that the function returns is also how you walk through a program without losing alignment.

A display

The toy machine prints characters, but most machines draw pixels. A display in an emulator is, at its simplest, a block of memory the program writes and a host-side routine that reads and shows. Choose a layout and make the video memory a region of the bus.

Suppose the toy machine gains a 32 by 16 monochrome display at addresses 0x2000 to 0x21FF, one byte per pixel with a nonzero value meaning lit. The host code draws it by reading that range each frame. You do not need a graphics library to prove it works: print the frame as text.

display.cc
#include <stdio.h>
#include "toy.h"

#define VRAM   0x2000
#define VRAM_W 32
#define VRAM_H 16

void draw_text(const Toy *m)
{
    for (unsigned y = 0; y < VRAM_H; y++) {
        for (unsigned x = 0; x < VRAM_W; x++)
            putchar(m->mem[VRAM + y * VRAM_W + x] ? '#' : '.');
        putchar('\n');
    }
}

A program that writes 1 to the first four pixels of the first row makes the first line of the output ####............................. Once that works, replacing putchar with a call to a library such as SDL, which can draw a rectangle for each lit pixel, is mechanical, and the emulator core never changes. That separation is the point of the earlier advice about keeping the host shell apart from the machine.

For machines whose graphics hardware is more elaborate, with tile maps and sprites, the same split holds: the emulator maintains the video chip's registers and memory, and a renderer function turns that state into pixels once per frame. The timing section explains when to call it.

Input and the host loop

Input mirrors output. The host shell reads real key events and stores them into a state the machine can read through the bus, such as the PORT_KEY register above. Never let the emulator core call the keyboard library directly. Instead, the host loop does the following each frame, in order:

  1. Poll the host for events and update the input state.

  2. Run the emulated machine for one frame's worth of cycles.

  3. Render the video memory to the window.

  4. Wait for the next frame time.

That loop is the same for every machine, and writing it once as a small program that owns the window and calls run_frame means each new CPU only supplies the run_frame and render functions.

The mistakes everyone makes

Experienced emulator writers have a shared list of bugs. Knowing it in advance saves days.

  • Forgetting to wrap. An address or register that should wrap around at its width does not, because an intermediate was computed in int. Mask or cast at every step.

  • Sign extension errors. A relative branch offset is a signed byte. Reading it as uint8_t makes backward branches jump forward by up to 255 bytes. Cast to int8_t first.

  • Advancing the program counter at the wrong time. Some instructions use the counter's value before the increment, and others after. Read the documentation for the exact definition.

  • Flag edge cases. Carry on subtraction is usually the inverse of borrow, which differs between processors. Test every flag on every arithmetic instruction.

  • Undocumented behavior that software relies on. Real programs use unofficial opcodes and quirks. Begin with the documented set and let test failures tell you which quirks matter.

  • Reading uninitialized state. Real hardware powers on with defined or random register values. Decide what your reset does, and check what the documentation says.

  • Mixing host and guest endianness. If you load multi-byte values by casting a pointer, your code is wrong on a host with the opposite byte order. Assemble values from bytes explicitly, as the read16 function does.

Keep this list next to the tests. When a program misbehaves, the cause is almost always on it.

From the toy to real machines

Every real emulator is the toy machine with more of each part: more registers, more instructions, more addressing modes, more flags and more devices. The progression through this cluster is deliberately gentle.

CHIP-8 is the best first real target. It is a virtual machine designed in the 1970s for simple games, with 35 instructions, a 64 by 32 monochrome display and a sixteen-key keypad, and there is a post for writing it in C and another in Rust. It teaches display, input and timers in a few hundred lines.

The 6502 is the processor of the Apple II, the Commodore 64 and the NES. Its addressing modes, flags and quirks such as the decimal mode make it the standard second step. The posts here cover the CPU core, the addressing modes, the functional test suite and decimal mode.

The Game Boy's SM83 has a similar structure with a different flag layout, including the half-carry flag that is the source of many bugs, and it adds memory bank controllers on its cartridges.

RISC-V RV32I is a modern, clean, documented instruction set with fixed-width instructions, and it is a good place to learn how a 32-bit ISA decodes. An RV32I core with the multiply and compressed extensions can eventually boot Linux, which is the last post in the emulator sequence.

At each step the same loop applies: build the core, write the tests, add devices, then tune.

Reading the documentation so you decode correctly

The hardest part of a first emulator is often not the code but reading the manual. Instruction set documents list each instruction with its encoding, its operands, its effect on flags and its cycle count, and the information you need is spread across those columns. Build the opcode table in the order the manual gives it, one row at a time, and tick each row off after you have written the case and a unit test for it.

Look first for the encoding diagram, which shows which bits of the opcode select the operation and which select the operands. Many instruction sets, RISC-V among them, pack fields into fixed bit positions, and the decoder is a few shifts and masks. Others, such as the 6502, have an irregular opcode map that you can only express as a table of 256 entries. Both are fine. What matters is writing the decode in a form where you can see the manual's table in your code, so that a mismatch is obvious on inspection.

Decoding with shifts and masks looks like this for an instruction whose top four bits select the operation and whose low twelve bits are an operand, the layout used by CHIP-8:

decode.cc
#include <stdint.h>
#include <stdio.h>

int main(void)
{
    uint16_t instr = 0xA2F0;

    unsigned op   = (instr & 0xF000) >> 12;   /* top nibble selects the operation */
    unsigned nnn  = instr & 0x0FFF;           /* low 12 bits: an address */
    unsigned x    = (instr & 0x0F00) >> 8;    /* second nibble: a register index */
    unsigned kk   = instr & 0x00FF;           /* low byte: an immediate */

    printf("op=%X nnn=%03X x=%X kk=%02X\n", op, nnn, x, kk);
    return 0;
}
Text
op=A nnn=2F0 x=2 kk=F0

The same bits mean different things for different instructions, so the decoder extracts every field it might need and each case uses only the ones it wants. That is how nearly every fixed-width instruction decoder works.

Choosing a dispatch structure

The switch in the toy machine is the simplest way to dispatch, and it is a good place to stay for a long time. Compilers turn a dense switch into a jump table, so the cost per instruction is one indirect jump. Two alternatives appear in real emulators.

An array of function pointers, indexed by opcode, separates each instruction into its own function. It scales to 256 opcodes without a single huge function, makes it easy to share implementations between opcodes that differ only in a register, and allows generating the table with macros. The cost is a function call per instruction, which a compiler may inline if the table is constant.

A computed goto, a GCC and Clang extension, jumps through a table of labels and repeats the dispatch at the end of each instruction handler, which gives the processor's branch predictor a separate jump to learn for each handler instead of one shared indirect jump. It can make an interpreter measurably faster on some hardware, and the post on VM dispatch covers it. It is not standard C, so keep it behind a compile-time option and keep a plain switch as the fallback.

Pick the structure that makes the code easiest to check against the manual, and change it only after a measurement shows the dispatch is the bottleneck, which for the machines in this cluster it almost never is.

Determinism, save states and replays

An emulator that behaves identically every time it is given the same input has a valuable property: determinism. It makes bugs reproducible, lets you record an input sequence and replay it exactly, and makes save states trivial. A save state is a snapshot of the whole machine: registers, memory and device state. If all of it lives in one structure with no hidden state elsewhere, saving is writing that structure to a file and loading is reading it back.

savestate.cc
#include <stdio.h>
#include "toy.h"

int save_state(const Toy *m, const char *path)
{
    FILE *f = fopen(path, "wb");
    if (!f) return -1;
    size_t n = fwrite(m, sizeof *m, 1, f);
    fclose(f);
    return n == 1 ? 0 : -1;
}

int load_state(Toy *m, const char *path)
{
    FILE *f = fopen(path, "rb");
    if (!f) return -1;
    size_t n = fread(m, sizeof *m, 1, f);
    fclose(f);
    return n == 1 ? 0 : -1;
}

This works because the toy machine's state is a plain structure with no pointers. If you later add pointers, such as a pointer to a ROM image, the file would contain host addresses that mean nothing after a restart, so keep machine state pointer-free or serialize field by field. Structure padding also makes the file format depend on the compiler, so a robust version writes each field with a fixed width and order. For learning, the simple version is enough.

Determinism requires removing sources of randomness from the machine: use a fixed seed for any random number generator the guest sees, and never let host timing influence guest-visible state. When both hold, a recorded input log and an initial state reproduce a run exactly, which turns a rare crash into a regression test.

Performance, once it works

A correct emulator is usually fast enough. A modern computer executes billions of host instructions per second, and an 8-bit machine needs about a million guest instructions per second. A plain switch interpreter written in C runs a 1 MHz machine at many times real speed. Optimize only when a measurement says to.

When you do need speed, the progression is: first make the decode cheap, using a table of function pointers or a computed goto instead of nested conditions. Then avoid doing work per instruction that can be done per block, such as checking for pending interrupts, which can be done once per scanline or frame. Then, if necessary, cache decoded instructions. Only at the end consider dynamic recompilation, which translates blocks of guest code into host machine code. That multiplies speed and complexity, and is covered by the post on interpreters, JITs and recompilers. Most emulators never need it.

Who this does not fit

If you want to run guest code for the same architecture as your computer, with near-native speed, you need virtualization, and the hypervisor guide in this cluster is the better start. If you want to understand a real chip down to the signals, you want a hardware description language and a simulator, which the hardware cluster covers. If you want to play games, use an existing emulator, since mature ones exist for nearly every console. Write your own to learn, to preserve something obscure or to build tooling no existing emulator provides, such as a firmware test harness for a microcontroller you are developing.

A checklist for any new emulator

Before starting any machine, collect the following, because every one of them will be needed.

  1. The documentation: the instruction set reference and a memory map. Read it twice.

  2. A reference emulator or trace: even one you only use for comparison.

  3. Test ROMs or test suites for the CPU.

  4. A small first program: a ROM you can run before the whole system exists.

  5. A bus abstraction from day one, so devices attach to memory reads and writes.

  6. A trace and a single-step mode, built before the first game.

Following that order turns the project from an act of faith into a series of checkable steps.

Also inHardware
Taggedcbeginner
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.