Skip to content
systemcoding.dev
Virtualization

Write a 6502 CPU Emulator Core in C

Build a 6502 CPU core in C11: registers, the status flags, addressing modes, ADC and SBC with overflow, branches with cycle counts, and a small test program.

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

The MOS Technology 6502 powered the Apple II, the Commodore 64, the Atari 2600's cousin the 6507 and the Nintendo Entertainment System's Ricoh 2A03, and it is the most popular second processor for emulator writers. It is small enough to finish in a weekend, documented to the last undocumented quirk, and its test suites are strong enough that passing them means something. This post builds the CPU core in C11 with GCC 14 or Clang 19: the register file, the status flags, a memory interface, the main addressing modes, a representative set of instructions including ADC and SBC with correct carry and overflow, branches with cycle counts, and a small program to show it working. It follows the MOS MCS6500 programming manual and the instruction timing in the 6502 documentation by Nick Bensema and the 6502.org community. It assumes you have read the fetch-decode-execute post and know hexadecimal and bit masks, covered earlier in this cluster. The core here implements the documented instruction set in part, enough to run real code and extend, and the next posts cover addressing modes and the functional test that proves completeness.

The registers

The 6502 has very few registers, all 8 bits wide except the program counter:

RegisterWidthPurpose
A8Accumulator, the main arithmetic register
X, Y8Index registers
SP8Stack pointer; the stack lives at 0x0100 to 0x01FF
PC16Program counter
P8Processor status flags

The status register P has seven meaningful bits. From bit 7 down: N negative, V overflow, an unused bit that always reads as 1, B break, D decimal mode, I interrupt disable, Z zero and C carry. B is not a real flag stored in the processor: it exists only in the copy of P pushed to the stack by BRK and PHP.

cpu6502.hc
#ifndef CPU6502_H
#define CPU6502_H

#include <stdint.h>

enum {
    FLAG_C = 1u << 0,
    FLAG_Z = 1u << 1,
    FLAG_I = 1u << 2,
    FLAG_D = 1u << 3,
    FLAG_B = 1u << 4,
    FLAG_U = 1u << 5,   /* unused, always 1 */
    FLAG_V = 1u << 6,
    FLAG_N = 1u << 7,
};

typedef struct Cpu {
    uint8_t  a, x, y, sp, p;
    uint16_t pc;
    uint64_t cycles;
    uint8_t  mem[65536];
} Cpu;

void     cpu_reset(Cpu *c);
unsigned cpu_step(Cpu *c);   /* returns the cycles the instruction took */

#endif

Memory is a flat 64 KiB array here. Later, it should become a function pair so that devices and ROM can plug in, as the emulator guide explains. For the CPU core, keeping the array visible makes the tests simple.

Reset and the vectors

The 6502 does not start at address 0. On reset it reads its start address from the reset vector, the two bytes at 0xFFFC and 0xFFFD, low byte first. It also sets the stack pointer to 0xFD after its reset sequence consumes three pushes without writing, sets the interrupt-disable flag and leaves A, X and Y undefined, which an emulator usually zeroes. The other two vectors are the non-maskable interrupt at 0xFFFA and the IRQ and BRK vector at 0xFFFE.

reset.cc
#include <string.h>
#include "cpu6502.h"

void cpu_reset(Cpu *c)
{
    c->a = c->x = c->y = 0;
    c->sp = 0xFD;
    c->p = FLAG_U | FLAG_I;
    c->pc = (uint16_t)(c->mem[0xFFFC] | (c->mem[0xFFFD] << 8));
    c->cycles = 7;     /* the reset sequence takes seven cycles */
}

Flag helpers

Two helpers cover most flag updates. Almost every instruction that produces a value sets Z and N from it, so one function does that, and a second sets or clears a flag by condition.

flags6502.cc
#include "cpu6502.h"

static inline void set_flag(Cpu *c, uint8_t flag, int on)
{
    if (on) c->p |= flag;
    else    c->p &= (uint8_t)~flag;
}

static inline void set_zn(Cpu *c, uint8_t value)
{
    set_flag(c, FLAG_Z, value == 0);
    set_flag(c, FLAG_N, value & 0x80);
}

Keep set_zn as the only place that decides what zero and negative mean. When a test finds a wrong flag, the fix lives in one function.

Addressing modes

An instruction names its operand in one of several ways, called addressing modes, and the next post covers them in full. For now, implement the ones the sample program needs as small functions that return the effective address of the operand and advance PC.

modes.cc
#include "cpu6502.h"

static inline uint8_t fetch8(Cpu *c)
{
    return c->mem[c->pc++];
}

static inline uint16_t fetch16(Cpu *c)
{
    uint16_t lo = fetch8(c);
    uint16_t hi = fetch8(c);
    return (uint16_t)(lo | (hi << 8));
}

static inline uint16_t addr_imm(Cpu *c)  { return c->pc++; }
static inline uint16_t addr_zp(Cpu *c)   { return fetch8(c); }
static inline uint16_t addr_zpx(Cpu *c)  { return (uint8_t)(fetch8(c) + c->x); }
static inline uint16_t addr_abs(Cpu *c)  { return fetch16(c); }
static inline uint16_t addr_abx(Cpu *c)  { return (uint16_t)(fetch16(c) + c->x); }

Immediate mode returns the address of the byte right after the opcode, so the operand is read from there with the same mem[addr] code as every other mode. That uniformity is the reason to compute an address instead of a value: an instruction like LDA then needs one body for all of its modes, and the zero-page indexed mode wraps inside the zero page because of the cast to uint8_t.

Arithmetic: ADC and SBC

Addition with carry is the instruction most emulators get wrong first. The result is A + M + C. The carry flag is set if the true sum exceeds 255. The overflow flag is set if two operands of the same sign give a result of the opposite sign, which the expression (~(a ^ m) & (a ^ sum) & 0x80) captures: the first term is nonzero when a and m have the same sign, and the second when a and the result differ in sign.

adc.cc
#include "cpu6502.h"

static inline void set_flag(Cpu *c, uint8_t flag, int on);
static inline void set_zn(Cpu *c, uint8_t value);

static void adc(Cpu *c, uint8_t m)
{
    unsigned sum = (unsigned)c->a + m + (c->p & FLAG_C ? 1u : 0u);
    uint8_t result = (uint8_t)sum;

    set_flag(c, FLAG_C, sum > 0xFF);
    set_flag(c, FLAG_V, (~(c->a ^ m) & (c->a ^ result) & 0x80));
    c->a = result;
    set_zn(c, c->a);
}

static void sbc(Cpu *c, uint8_t m)
{
    adc(c, (uint8_t)~m);       /* subtraction is addition of the complement */
}

The sbc trick works because the 6502 defines subtraction as A - M - (1 - C), which equals A + (~M) + C in two's complement, and the carry flag acts as "no borrow". That is why programs execute SEC before a subtraction and CLC before an addition. This code ignores decimal mode, where D is set and the instructions work on binary-coded decimal. The decimal mode post covers it.

Branches and their cycle counts

Branch instructions take a signed 8-bit offset relative to the address after the instruction. A branch not taken costs 2 cycles. Taken, it costs 3, and it costs 4 if the target is on a different 256-byte page than the next instruction, because the processor needs an extra cycle to fix the high byte. Emulating timing means counting these.

branch.cc
#include "cpu6502.h"

static unsigned branch(Cpu *c, int condition)
{
    int8_t offset = (int8_t)c->mem[c->pc++];
    unsigned cycles = 2;
    if (condition) {
        uint16_t target = (uint16_t)(c->pc + offset);
        cycles += 1;
        if ((target & 0xFF00) != (c->pc & 0xFF00))
            cycles += 1;
        c->pc = target;
    }
    return cycles;
}

The cast (int8_t) is essential: it turns an offset byte of 0xFB into -5, a jump backwards. Reading it as unsigned makes every backward loop jump forward by up to 251 bytes, a symptom that makes programs run off into data.

The step function

The instruction step fetches an opcode and switches on it. Each case computes its operand address, performs the operation and returns the cycle count. This listing covers a useful subset: loads, stores, arithmetic, compare, increments, a few flag instructions, JMP, BNE and BEQ.

step6502.cc
#include "cpu6502.h"

static inline void set_flag(Cpu *c, uint8_t flag, int on);
static inline void set_zn(Cpu *c, uint8_t value);
static void adc(Cpu *c, uint8_t m);
static void sbc(Cpu *c, uint8_t m);
static unsigned branch(Cpu *c, int condition);
static inline uint16_t addr_imm(Cpu *c);
static inline uint16_t addr_zp(Cpu *c);
static inline uint16_t addr_zpx(Cpu *c);
static inline uint16_t addr_abs(Cpu *c);
static inline uint16_t addr_abx(Cpu *c);

static void compare(Cpu *c, uint8_t reg, uint8_t m)
{
    set_flag(c, FLAG_C, reg >= m);
    set_zn(c, (uint8_t)(reg - m));
}

unsigned cpu_step(Cpu *c)
{
    uint8_t op = c->mem[c->pc++];
    unsigned cyc;

    switch (op) {
    case 0xA9: c->a = c->mem[addr_imm(c)]; set_zn(c, c->a); cyc = 2; break; /* LDA #   */
    case 0xA5: c->a = c->mem[addr_zp(c)];  set_zn(c, c->a); cyc = 3; break; /* LDA zp  */
    case 0xB5: c->a = c->mem[addr_zpx(c)]; set_zn(c, c->a); cyc = 4; break; /* LDA zp,X */
    case 0xAD: c->a = c->mem[addr_abs(c)]; set_zn(c, c->a); cyc = 4; break; /* LDA abs */
    case 0xA2: c->x = c->mem[addr_imm(c)]; set_zn(c, c->x); cyc = 2; break; /* LDX #   */
    case 0xA0: c->y = c->mem[addr_imm(c)]; set_zn(c, c->y); cyc = 2; break; /* LDY #   */
    case 0x85: c->mem[addr_zp(c)]  = c->a; cyc = 3; break;                  /* STA zp  */
    case 0x8D: c->mem[addr_abs(c)] = c->a; cyc = 4; break;                  /* STA abs */
    case 0x9D: c->mem[addr_abx(c)] = c->a; cyc = 5; break;                  /* STA abs,X */
    case 0x69: adc(c, c->mem[addr_imm(c)]); cyc = 2; break;                 /* ADC #   */
    case 0xE9: sbc(c, c->mem[addr_imm(c)]); cyc = 2; break;                 /* SBC #   */
    case 0xC9: compare(c, c->a, c->mem[addr_imm(c)]); cyc = 2; break;       /* CMP #   */
    case 0xE8: c->x++; set_zn(c, c->x); cyc = 2; break;                     /* INX     */
    case 0xCA: c->x--; set_zn(c, c->x); cyc = 2; break;                     /* DEX     */
    case 0xC8: c->y++; set_zn(c, c->y); cyc = 2; break;                     /* INY     */
    case 0x18: set_flag(c, FLAG_C, 0); cyc = 2; break;                      /* CLC     */
    case 0x38: set_flag(c, FLAG_C, 1); cyc = 2; break;                      /* SEC     */
    case 0xEA: cyc = 2; break;                                              /* NOP     */
    case 0x4C: c->pc = (uint16_t)(c->mem[c->pc] | (c->mem[c->pc + 1] << 8)); cyc = 3; break; /* JMP abs */
    case 0xD0: cyc = branch(c, !(c->p & FLAG_Z)); break;                    /* BNE     */
    case 0xF0: cyc = branch(c,  (c->p & FLAG_Z)); break;                    /* BEQ     */
    default:   cyc = 2; break;                                              /* unimplemented: treat as NOP */
    }
    c->cycles += cyc;
    return cyc;
}

INX and DEX wrap at 8 bits because x is a uint8_t, so DEX from 0 gives 255 with N set. The default case silently treating an unknown opcode as a two-cycle no-op is convenient while building, and dangerous later. Replace it with a loud failure once most opcodes exist, so a missing instruction cannot hide.

Running a program

Assemble a loop by hand: load 3 into X, decrement until zero, then store a marker. Place it at 0x0600 and set the reset vector to point there.

main6502.cc
#include <stdio.h>
#include <string.h>
#include "cpu6502.h"

int main(void)
{
    static Cpu c;
    memset(&c, 0, sizeof c);

    const uint8_t prog[] = {
        0xA2, 0x03,         /* 0600 LDX #$03   */
        0xCA,               /* 0602 DEX        */
        0xD0, 0xFD,         /* 0603 BNE $0602  (offset -3) */
        0xA9, 0x42,         /* 0605 LDA #$42   */
        0x8D, 0x00, 0x02,   /* 0607 STA $0200  */
    };
    memcpy(&c.mem[0x0600], prog, sizeof prog);
    c.mem[0xFFFC] = 0x00;
    c.mem[0xFFFD] = 0x06;

    cpu_reset(&c);
    while (c.pc < 0x060A)
        cpu_step(&c);

    printf("A=%02X X=%02X P=%02X mem[0200]=%02X cycles=%llu\n",
           c.a, c.x, c.p, c.mem[0x0200], (unsigned long long)c.cycles);
    return 0;
}
Text
A=42 X=00 P=24 mem[0200]=42 cycles=29

Check the numbers by hand, because that habit finds real bugs. The reset sequence accounts for 7 cycles. LDX #3 takes 2. DEX runs three times at 2 cycles each, which is 6. BNE is taken twice at 3 cycles each, since the target is on the same page, and not taken once at 2 cycles, which is 8. LDA #$42 takes 2 and STA $0200 takes 4. The total is 7 + 2 + 6 + 8 + 2 + 4 = 29. The status byte is 0x24 because reset leaves the unused bit and the interrupt-disable flag set, the last DEX set Z, and the following LDA cleared it again.

The offset byte 0xFD in the branch is -3. The BNE operand sits at 0x0604, the counter is 0x0605 after the fetch, and the target 0x0602 is three bytes back from that. Branches are relative to the address after the instruction, which is the most common thing to miscount when assembling by hand.

What is missing

This core is a skeleton of the documented instruction set. It lacks the full set of addressing modes, the stack instructions (PHA, PLA, PHP, PLP, JSR, RTS, RTI, BRK), the shifts and rotates, the logical operations AND, ORA and EOR, BIT, the remaining branches, interrupts, decimal mode and the page-crossing cycle penalties for indexed reads. Each is an hour of work with the manual open, and the functional test suite tells you which you forgot. The addressing modes post is the right next step.

Also inHardware
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.