Skip to content
C++ project #23Advanced

Stack Virtual Machine and Assembler

A two-pass assembler with labels and a bytecode VM with registers, subroutines, overflow-checked arithmetic and protection against runaway programs.

Estimated time
~10 hours to build
Files
7 files · 691 lines
Technologies
C++17, <vector>, <array>, <map>, <limits>, Header/source split

Introduction

The JVM, the .NET runtime and Python's interpreter are all stack machines. Building one demystifies how programs actually run: instructions push and pop values, jumps move the program counter, and calls save return addresses. You will write both the assembler that turns text into instructions and the machine that executes them.

Problem statement

Design an instruction set (stack, arithmetic, comparison, jumps, 26 registers, call/ret, print) and write a two-pass assembler supporting labels, comments and character literals. Then write a VM that executes the program with a step limit, a stack limit and a call-depth limit, detects stack underflow, division by zero and 64-bit overflow, and reports faults with the source line. Run several sample programs, including factorial in a subroutine, Fibonacci and a prime sieve.

Objectives

  • Design an instruction encoding with enum class
  • Write a two-pass assembler that resolves forward references
  • Implement a fetch-decode-execute loop
  • Detect signed overflow without undefined behaviour

Features

  • 25 instructions, labels and ; comments
  • Registers a–z and a separate return stack for call/ret
  • Overflow, underflow, division-by-zero and infinite-loop detection
  • Disassembly listing with label annotations

Concepts demonstrated

  • Virtual machines
  • Assemblers
  • Two-pass translation
  • Overflow-safe arithmetic
  • Interpreters
  • Error handling

System architecture

assemble makes pass 1 over the text, stripping comments and recording each label's instruction index; pass 2 encodes Instr{op, arg, source_line} and resolves label operands, so forward jumps work. run keeps a data stack, a return stack and 26 registers. Each step fetches code[pc], executes it in a switch, and sets the next pc. Arithmetic is checked before it happens with integer comparisons (a > MAX - b), because signed overflow is undefined behaviour and floating-point checks are inexact above 2^53.

TextArchitecture diagram
source text --pass 1--> labels {loop: 2, done: 11}
--pass 2--> [push 5][store n][load n][jz 11] ...
+---------------- run loop ----------------+
| fetch code[pc] -> switch(op) -> pc = next |
+-------------------------------------------+
data stack | return stack | registers a-z

Folder structure

TextProject tree
stack-vm/
├── README.md
├── Makefile
├── src/main.cpp
├── src/vm.cpp
├── src/vm.h
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

Makefile

20 lines
MakefileMakefile
# Generated for KENHOLT Skills. Usage: make | make test | make clean
CXX = g++
CXXFLAGS = -std=c++17 -Wall -Wextra -O2
SRC := $(wildcard src/*.cpp)
HDR := $(wildcard src/*.h src/*.hpp)
ARGS := $(shell cat tests/args.txt 2>/dev/null)
INPUT := $(wildcard tests/sample-input.txt)
app: $(SRC) $(HDR)
$(CXX) $(CXXFLAGS) -Isrc $(SRC) -o app
test: app
./app $(ARGS) $(if $(INPUT),< $(INPUT),) > actual.txt
diff actual.txt tests/expected-output.txt && echo "Test passed: output matches tests/expected-output.txt"
clean:
rm -f app app.exe actual.txt
.PHONY: test clean

What each file does

src/vm.h
The instruction set, Instr and Program, error types, and the assemble / run / disassemble interface.
src/vm.cpp
The opcode table, the two-pass assembler, the execution loop with all safety checks and the disassembler.
src/main.cpp
Splits the input into named programs, assembles and runs each, and prints the results.
Makefile
Build automation: make builds ./app, make test runs the sample session and compares it with the expected output, make clean removes build files.

How to run it

Build

Terminal
g++ -std=c++17 -Wall -Wextra -Isrc src/*.cpp -o app
# or simply: make

Run

Terminal
./app # Linux / macOS
.\app.exe # Windows

Test against the expected output

Terminal
./app < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt # no output means they match
# Windows PowerShell:
# Get-Content tests\sample-input.txt | .\app.exe > actual.txt
# Compare-Object (Get-Content actual.txt) (Get-Content tests\expected-output.txt)

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
=== arithmetic ===
0 push 6
1 push 7
2 mul
3 push 2
4 sub
5 print
6 halt
---
40
[ok: 7 instructions, 7 steps, max stack 2]
=== countdown ===
5
4
3
2
1
Go!
[ok: 19 instructions, 57 steps, max stack 2]
=== factorial (subroutine) ===
479001600
2432902008176640000
[ok: 25 instructions, 415 steps, max stack 2]
=== fibonacci ===
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
[ok: 20 instructions, 216 steps, max stack 3]
=== primes below 40 ===
2
3
5
7
11
13
17
19
23
29
31
37
[ok: 31 instructions, 1381 steps, max stack 2]
=== errors: division by zero ===
1
[runtime error at line 5 (div): division by zero]
=== errors: underflow ===
[runtime error at line 2 (add): stack underflow]
=== errors: overflow ===
[runtime error at line 13 (mul): integer overflow]
=== errors: infinite loop ===
[runtime error at line 1 (jmp): step limit reached (infinite loop?)]
=== errors: bad assembly ===
[assembly error, line 1: 'x' is not a number]
=== errors: undefined label ===
[assembly error, line 1: undefined label 'nowhere']
Input
program arithmetic listing
        push 6
        push 7
        mul             ; 42
        push 2
        sub             ; 40
        print
        halt

program countdown
        push 5
        store n
loop:   load n
        jz done         ; stop when n == 0
        load n
        print
        load n
        push 1
        sub
        store n
        jmp loop
done:   push 'G'
        printc
        push 'o'
        printc
        push '!'
        printc
        push 10
        printc

program factorial (subroutine)
        push 12
        call fact
        print
        push 20
        call fact
        print
        halt
; fact: ( n -- n! ) iterative, uses registers a (counter) and r (result)
fact:   store a
        push 1
        store r
f_loop: load a
        push 1
        gt
        jz f_done
        load r
        load a
        mul
        store r
        load a
        push 1
        sub
        store a
        jmp f_loop
f_done: load r
        ret

program fibonacci
        push 0
        store a
        push 1
        store b
        push 15
        store n
next:   load a
        print
        load a
        load b
        dup
        store a
        add
        store b
        load n
        push 1
        sub
        dup
        store n
        jnz next

program primes below 40
        push 2
        store n
outer:  load n
        push 40
        lt
        jz end
        push 2
        store d
inner:  load d
        load d
        mul
        load n
        gt
        jnz is_prime     ; d*d > n: no divisor found
        load n
        load d
        mod
        jz not_prime
        load d
        push 1
        add
        store d
        jmp inner
is_prime: load n
        print
not_prime: load n
        push 1
        add
        store n
        jmp outer
end:    halt

program errors: division by zero
        push 1
        print
        push 10
        push 0
        div
        print

program errors: underflow
        push 1
        add

program errors: overflow
        push 21
        call fact2
        print
        halt
fact2:  dup
        push 1
        gt
        jz base
        dup
        push 1
        sub
        call fact2
        mul
        ret
base:   ret

program errors: infinite loop
spin:   jmp spin

program errors: bad assembly
        push x
        jmp nowhere

program errors: undefined label
        jmp nowhere

Testing

  • Compare ./app < tests/sample-input.txt with tests/expected-output.txt.
  • factorial prints 12! = 479001600 and 20! = 2432902008176640000; 21! is reported as an integer overflow.
  • primes below 40 prints the 12 primes from 2 to 37.
  • Faults are reported with the source line: division by zero (line 5), underflow (line 2), the step limit for an infinite loop and undefined labels at assembly time.

Common errors

Jumps land on the wrong instruction

Labels must record the index of the next *instruction*, not the source line number, which counts blank and comment lines.

Wrong results for big multiplications

Don't detect overflow by computing in double or long double; check with integer comparisons before multiplying.

Possible improvements

  • Add a read instruction for input
  • Add memory (an array) with load/store by address
  • Write a compiler from the Expression Interpreter's AST to this bytecode

Additional challenges

  1. 1Add a single-step debugger that prints the stack after each instruction.
  2. 2Encode programs to a binary file and load them back.
  3. 3Add tail-call optimisation for call followed by ret.

Built and tested it yourself? Mark it to update your dashboard.