a cpu emulator
I was learning llvm so I took a break and went on twitter, while scrolling I saw this guy speaking about the cpu emulator he built, while looking closely I even saw he is Nigerian and was like woah let me know him. I was reading through his tweet and saw "...functional CPU emulator from scratch in c++", Immediately, I went to chatgpt too ask how it relates to what I am currently studying (as of writing this, I am studying computer architecture, compilers and databases) and it explained so well on how the emulator relates to these topics, so I decided to build one myself.
The emulator and the assembler compile to WebAssembly, and web/ holds a small frontend for them
(source editor, datapath, registers, memory, machine code listing, symbols and an execution trace).
zig build web # builds cpu.wasm and copies web/ into zig-out/web
python3 -m http.server -d zig-out/web 8000 # any static server works, file:// does notThen open http://localhost:8000. Shortcuts: F10 step, F8 run or pause. Click a line number to set a breakpoint.
src/assembler/assembler.zig turns assembly text into the word stream the CPU decodes (every field is one
32-bit little-endian word, so LOAD R0, 3 is 0x10 0x00 0x03).
; comments start with ; or //
.data ; variables, placed in RAM from 0x1000
count: .word 42 ; also .byte .half .dword .ascii .asciiz .space
name: .asciiz "KCPU"
age: 10 ; shorthand for .word 10
.text ; instructions, placed in ROM from 0x0000
start:
LOAD R1, 0x2A ; LD and LDI work too, numbers can be decimal, 0x, 0b, 0o, 'c' or negative
LOAD R2, count ; a variable name becomes its address
MOV R3, R1
ADD R3, R2
SUB R3, R1
HLTJump instructions (JMP, JZ, JNZ) are recognised but the assembler rejects them for now.
- Emulating a CPU in C++ by Dave Poo
- 32-bit CPU in C++ -> David start here.
- Writing your first emulator Part I
- Write your own Virtual CPU (in C++ Code)
Start Rohan's article and build alongside it, but in Zig rather than C++. When you reach instruction execution, start watching Dave Poo—not to copy the 6502, but > to study his implementation/testing methodology. After your basic emulator executes programs correctly, read Gecko and compare its cycle-oriented model against > > your simplified fetch/decode/execute model.