Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 55 ยท Real-World Projects

Project: A Tiny CPU Simulator

Build a tiny CPU in JavaScript with registers, memory and an instruction set. Watch fetch-decode-execute run a countdown, then add an assembler with labels.

A processor looks mysterious until you build one. In this project you will write a tiny CPU simulator in about sixty lines: four registers, a block of memory, a program counter, and a loop that repeats the three steps every real CPU performs forever: fetch an instruction, decode it and execute it. You will run a countdown program, watch a trace of every step, and then write a small assembler so that you can write programs as text instead of raw numbers.

This project ties together The CPU, Machine Code and Assembly and Memory: RAM, Cache and the Memory Hierarchy. The CPU here is a toy, not a model of any real chip, but its structure is the same one inside every processor.

The machine we are building

Our machine has these parts:

  • Memory: an array of 64 numbers. It holds both the program and the data (the stored-program idea).
  • Registers: four small, fast storage slots named R0 to R3.
  • Program counter (PC): the address of the next instruction.
  • Instructions of three cells each: an opcode (which operation) and two operands.
flowchart LR
  PC["Program counter"] --> F["Fetch: read 3 cells at PC"]
  F --> D["Decode: which opcode?"]
  D --> E["Execute: change registers, memory or PC"]
  E --> PC

The cycle never stops until a HALT instruction: fetch, decode, execute, repeat.

The instruction set has nine instructions, which is plenty to compute with:

Opcode Name Operands Effect
0 HALT none stop the machine
1 LOADI reg, value put a constant into a register
2 LOAD reg, address copy memory cell into a register
3 STORE address, reg copy a register into a memory cell
4 ADD reg1, reg2 reg1 = reg1 + reg2
5 SUB reg1, reg2 reg1 = reg1 - reg2
6 JNZ reg, address jump to address if the register is not zero
7 PRINT reg output the register's value
8 JMP address jump to address

JNZ ("jump if not zero") is what makes a loop possible. A machine that can only run top to bottom can never repeat anything, and a machine with a conditional jump can compute almost anything.

Step 1: the CPU and a hand-written program

Programs are numbers, so the first program is a list of numbers laid out three per instruction. This countdown loads 3 into R0, loads 1 into R1, then repeatedly prints R0, subtracts R1 from it and jumps back while R0 is not zero. The jump targets are addresses, so address 6 is the third instruction (3 cells each, starting from 0).

The run function is the heart of the project. Read the switch as the decode-and-execute stage.

JS Step 1: the CPU runs a countdown (with a trace)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The trace shows the cycle at work. The pc jumps back to 6 each time JNZ finds R0 is not zero, and finally falls through to HALT. The machine performs 12 steps to print three numbers: two setup instructions, three instructions for each of the three passes through the loop, and the halt. The trace line is printed before the instruction executes, so each regs= shows the state going into that step.

Notice that nothing in the CPU knows what "countdown" means. It only follows the program counter and obeys opcodes. All the intelligence is in the program, and a different list of numbers in memory makes the same hardware do a different job. That is the stored-program idea.

Step 2: an assembler

Writing programs as number lists is miserable and easy to get wrong, which is why people invented assembly language: a text form with names for opcodes, registers and addresses. An assembler translates it to numbers. Ours does two passes:

  1. Pass one walks the lines, counts instruction positions and records where each label (a name followed by a colon) points.
  2. Pass two emits three numbers per instruction, replacing register names like R2 with their number and labels with their address.

Two passes are needed because a jump may refer to a label that appears later in the file, and you can't know its address until you have seen everything before it.

JS Step 2: assemble and run a program that sums 1 to 10

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The program adds 10 + 9 + ... + 1 and gets 55, stored in memory cell 60 and printed. The first line of output shows the machine code, which is what the hardware really sees: no names, no comments, no labels. Notice how a typo in an instruction name is caught by the assembler before anything runs; error checking at translation time is one of the reasons assemblers (and, later, compilers) exist. The idea of translating text to executable form is explored in Programming Languages, Compilers and Interpreters.

Step 3: safety, bugs and breaking things

Real CPUs raise exceptions on illegal instructions and stop runaway programs through timers from the operating system. Our simulator has simple versions of both: an illegal opcode throws, and maxSteps stops a program that never halts. That matters here: with a mistake such as JNZ pointing at itself, the CPU would loop forever, since it has no idea its program is stuck.

Because a program and its data share one memory, a bug can also overwrite the program itself. A STORE to an address inside the code changes an instruction. In a real computer, the operating system prevents this by marking code regions read-only, as covered in Memory Management. The next stand-in shows both failure modes: self-modifying code, and an endless loop caught by the step limit.

JS Step 3: what happens when programs go wrong

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the second program, the STORE at address 3 copies R0 (99) into memory cell 9, replacing the opcode of the second PRINT. The first PRINT works, then the CPU decodes opcode 99, which does not exist. In the healthy version the same store goes to cell 40, far from the code, and both PRINT instructions run. Many real security attacks work by getting a program to treat attacker-provided data as instructions, which is why modern systems separate writable data from executable code.

Ideas to extend it

  • Add a MUL instruction, or CALL and RET using a stack (that is how functions work).
  • Add a flags register and CMP, JEQ, JLT instructions, borrowing from Project: A Binary Calculator.
  • Add memory-mapped output: any STORE to address 63 prints a character.
  • Write the Fibonacci sequence or a prime tester in your assembly.
  • Count how many steps each program takes and compare which is more efficient, the beginning of thinking about speed in Algorithms and Problem Solving.

What is real and what is the stand-in? The fetch-decode-execute cycle, registers, a program counter, opcodes, conditional jumps, labels and two-pass assembling are all genuine. The details are simplified: real instructions are packed into bits rather than three whole numbers, real CPUs overlap many instructions in a pipeline, and real programs call into an operating system. JavaScript is playing the role of the electronics.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What are the three steps of the cycle that the simulator repeats?

    The CPU fetches the instruction at the program counter, decodes the opcode and executes it, then repeats.
  2. 2. Which instruction makes loops possible in the toy instruction set?

    A conditional jump changes the program counter based on data, so the same instructions can run repeatedly until a condition changes.
  3. 3. Why does the assembler need two passes?

    Pass one records where every label is; pass two can then replace label names with addresses, even for forward jumps.
  4. 4. A program stores a value into the address of one of its own instructions. What can happen?

    Code and data share memory in the stored-program design, so a stray write can alter the program unless the operating system protects it.
  5. 5. What is the job of the maxSteps limit in the simulator?

    A CPU cannot tell a deliberate endless loop from a bug; the step limit imitates the operating system's ability to stop a runaway program.

Summary

  • A CPU is a loop: fetch the instruction at the program counter, decode the opcode, execute it, advance.
  • Registers hold values being worked on; memory holds both program and data.
  • A conditional jump such as JNZ turns straight-line code into loops and decisions.
  • An assembler turns readable names and labels into numbers, using one pass to find labels and one to emit code.
  • Because code is data, bugs and attacks can overwrite instructions; real systems add protections.
  • Runaway programs are stopped from outside the program, by a step limit here and by the operating system in real life.

Next, see how data is organized on storage: Project: A Mini File System.