Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 40 ยท First Steps

Meet the Toy CPU: Our Runnable Assembly

Meet the toy CPU used in this tutorial: registers, flags, a stack and memory, a readable instruction set you can run in the browser and map to x86-64 and ARM64.

Real x86-64 and ARM64 programs cannot be assembled and run inside a web page. To still let you experiment, this tutorial uses a small toy CPU written in JavaScript. It has registers, flags, byte-addressable memory, a stack and a handful of instructions. Programs written for it use real assembly ideas and nearly real syntax, and they really run when you press the button.

This lesson is the reference for that machine. You will learn its instruction set, run three programs on it, and see how each toy instruction maps to its x86-64 and ARM64 cousins. Later lessons reuse the same machine, so it is worth bookmarking this page.

What the toy CPU has

flowchart LR
    subgraph CPU["Toy CPU"]
        R["Registers r0 to r7<br/>32-bit signed integers"]
        SP["sp: stack pointer"]
        PCR["Program counter<br/>index of next instruction"]
        FL["Flags Z S C O"]
    end
    P["Program<br/>list of instructions"]
    M["Memory<br/>1024 bytes"]
    P -->|"fetch"| PCR
    R <-->|"load and store"| M
    SP -->|"push, pop, call, ret"| M

The toy machine: registers, flags and a program counter in the CPU, 1024 bytes of memory outside it.

  • Registers r0 to r7: eight general-purpose registers, each a 32-bit signed integer. Arithmetic wraps around like a real 32-bit register does.
  • sp: the stack pointer. It starts at 1024, the top of memory, and the stack grows downwards (towards smaller addresses), just like on x86-64 and ARM64.
  • Flags: four status bits set by arithmetic and comparisons: Z (the result was zero), S (the result was negative), C (carry or borrow out of the top bit, as unsigned numbers), O (signed overflow). They are the real x86 flag names; Flags explains them fully.
  • Memory: 1,024 bytes, addresses 0 to 1023. Words (4 bytes) are stored little-endian, as on x86-64 and on common ARM64 systems.
  • Program: a list of instructions, kept separate from the data memory to keep the toy simple. The program counter holds the index of the next instruction.

The syntax

A toy program is plain text, one instruction per line:

TEXT
label:              ; a label names the position of the next instruction
  mov r0, 10        ; destination first, then source
  add r0, r1        ; r0 = r0 + r1
  load r2, [r3+4]   ; read the 4-byte word at address r3 + 4
  jl label          ; jump to a label
  • Everything after ; is a comment.
  • The destination comes first, then the source. This is Intel-style order, the same as ARM, and the reverse of AT&T syntax.
  • Numbers can be decimal (10), negative (-5), hexadecimal (0x1f) or a character ('A').
  • A memory operand is a register in brackets, optionally plus or minus a number: [r1], [r1+4], [r1-8].

The instruction set

Instruction Effect
mov d, s d = s (s is a register or a number)
add d, s / sub d, s d = d + s / d = d - s, sets all four flags
mul d, s d = d * s (low 32 bits), sets Z and S
div d, s / mod d, s integer quotient / remainder (a toy shortcut)
and d, s / or d, s / xor d, s bitwise operations, clear C and O
shl d, s / shr d, s shift left / logical shift right
cmp a, b computes a - b, sets flags, discards the result
jmp L always jump to label L
je, jne jump if equal / not equal (Z)
jl, jle, jg, jge jump on signed less, less-or-equal, greater, greater-or-equal
jb, jae jump on unsigned below / above-or-equal (C)
push s / pop d put a value on the stack / take it back
call L / ret call a subroutine / return from it
load d, [addr] / store [addr], s read / write a 4-byte word in memory
loadb d, [addr] / storeb [addr], s read / write one byte
out s / outc s print a number / print a character
halt, nop stop / do nothing

out and outc are not real instructions. A real program prints by asking the operating system through a system call (see System Calls). The same goes for div and mod: real x86-64 division uses a special register pair and ARM64 has sdiv but no remainder instruction. The toy simplifies them so early programs stay short.

Run your first program

The editor below holds the whole interpreter (about 100 lines of JavaScript) followed by a short program. The program adds 1 + 2 + 3 using a loop, and the interpreter's trace option prints every executed instruction together with the registers r0 to r3 and the flags afterwards. Read the first few lines of the trace and compare them with the program, line by line.

JS Run a toy program with a trace

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

No output.

Three details are worth noticing in the trace:

  1. cmp r1, 4 does not change a register. It only changes the flags. After the first loop pass, r1 is 2, so 2 - 4 is negative and the flags read S=1 and C=1 (a borrow), meaning "less than".
  2. jl again reads those flags. While they say "less", it overwrites the program counter with the position of again; that is the loop.
  3. On the last pass r1 is 4, 4 - 4 is zero, Z=1, the condition jl needs is false, execution falls through to out r0, and the program prints 6. (The trace shows the printed 6 just before the line of the out instruction that produced it.)

Subroutines and the stack

call and ret give the toy CPU functions. call label pushes the position of the next instruction on the stack and jumps; ret pops that position back into the program counter. Because registers are shared, a routine that needs a value after a nested call must save it, usually with push and pop. The next program computes 5! recursively: factorial(n) is n * factorial(n - 1), and each pending multiplication waits on the stack.

JS Recursive factorial with call and ret

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

No output.

The final sp value of 1024 proves that every push was matched by a pop and every call by a ret: the stack ended exactly where it started. Unbalanced stacks are one of the most common beginner bugs in real assembly, and The Stack shows how to find them.

Memory and bytes

store/load move 4-byte words, storeb/loadb move single bytes. Strings are just bytes in memory, ended by a zero byte (the C convention). The program below writes the word "Hello" into memory at address 100, then walks through it with a pointer in r2 until it meets the zero byte, printing each character and counting them.

JS Strings are bytes in memory

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

No output.

You should see Hello, a length of 5, and the byte values 72 101 108 108 111 0. The pointer-and-loop pattern in this program is how real strlen implementations work, and you will write several of them in Strings and Byte Processing.

How toy code maps to real code

The toy was designed so that every instruction has a direct real counterpart. Real names differ in small ways, but you will recognize them.

Toy x86-64 (Intel syntax) ARM64
mov r0, 5 mov eax, 5 mov w0, #5
add r0, r1 add eax, ebx add w0, w0, w1
cmp r0, r1 / jl L cmp eax, ebx / jl L cmp w0, w1 / b.lt L
load r1, [r2+4] mov ecx, [rdx+4] ldr w1, [x2, #4]
store [r2], r1 mov [rdx], ecx str w1, [x2]
push r0 / pop r1 push rax / pop rcx str x0, [sp, #-16]! / ldr x1, [sp], #16
call f / ret call f / ret bl f / ret

Three differences matter. ARM64 arithmetic instructions take three operands (add w0, w0, w1), x86 overwrites its first operand. ARM64 can only touch memory with explicit load and store instructions, while x86 lets most instructions read memory directly. And ARM64 has no push/pop; it uses a store or load with a pre- or post-indexed stack pointer. You will meet these in ARM64 Basics.

Limits of the toy

Keep these in mind so the toy does not teach you wrong lessons:

  • Registers are 32-bit; real 64-bit registers have rax-style names, partial register names (eax, ax, al) and 64-bit address arithmetic.
  • The stack holds 4-byte values, and call pushes an instruction index, not a byte address. Real x86-64 pushes 8 bytes and requires a 16-byte aligned stack at calls.
  • There are no segments, privilege levels, caches or interrupts.
  • Instructions are not encoded as bytes in memory, so the toy cannot show self-modifying code or buffer overflows over the return address except in the simulation you will see in Security.
  • out, outc, div and mod are conveniences with no single real equivalent.

Everything else (flags, jumps, calls, memory, pointers) works the way the real machines work, which is why the skills transfer.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In sub r0, r1, which register receives the result?

    The destination comes first, so the result of r0 - r1 is stored in r0. Only cmp computes a subtraction purely for the flags.
  2. 2. What does cmp r1, 4 change?

    cmp performs a subtraction, sets Z, S, C and O from it, and throws the result away. A conditional jump can then read those flags.
  3. 3. Which way does the toy stack grow, and where does sp start?

    sp starts at the top of memory (1024) and each push subtracts 4, exactly like the stack on x86-64 and ARM64 grows towards lower addresses.
  4. 4. Why does the factorial program push r0 before the recursive call?

    The nested call reuses r0, so n would be lost. The program saves it on the stack and pops it back afterwards to multiply.

Summary

  • The toy CPU has registers r0 to r7, a stack pointer, four flags (Z, S, C, O), 1,024 bytes of little-endian memory and a program counter.
  • Syntax: one instruction per line, destination first, labels end with a colon, comments start with ;, memory operands use [reg+offset].
  • cmp sets flags without keeping the result; conditional jumps such as jl and je read them.
  • push, pop, call and ret work on a stack that grows downwards from 1024.
  • store/load handle 4-byte words and storeb/loadb single bytes; strings are zero-terminated bytes.
  • Every toy instruction has a real x86-64 and ARM64 counterpart, but the toy is simpler: 32-bit registers, no encoding, and convenience instructions such as out.

Next: Reading Real Assembly from a C Compiler, where you will read genuine compiler output.