CodeRigor

LESSON

An assembler for your machine

Write a two-pass assembler and disassembler for a 16-bit machine: labels, constants, data words, precise errors, and a round trip that holds for every word.

You now have registers and RAM, but no comfortable way to give them a program. An assembler turns readable lines such as ADD r1, r2 into 16-bit words, and a disassembler turns words back into text. This lesson pairs with Assembly language vs. machine code (6502 part 3) by Ben Eater, linked under Watch & read. The video moves from hand-written machine code to assembly language, opcodes and labels on a real chip; the machine here is a different, smaller one, so take the ideas and not the encodings. You build both tools in plain Python and have them graded against a decoder that was written separately.

Every word has the same four fields. The opcode sits in bits 15 to 12 and is the instruction's position in this list: NOP LDI MOV ADD SUB AND OR XOR LD ST JMP JZ JNZ JC OUT HALT. The first register (r0 to r3) goes in bits 11 to 10, the second in bits 9 to 8, and a number in bits 7 to 0. An instruction fills only the fields it uses and leaves the others zero. Memory has 256 words, so an address and an immediate both fit in the low byte: 0 to 255.

One instruction word, two instructions
ADD r1, r2 uses both register fields and no number. LDI r2, 42 uses the first register and the number. Unused fields stay zero.
One instruction word, two instructions
ADD r1, r2 uses both register fields and no number. LDI r2, 42 uses the first register and the number. Unused fields stay zero.
Python
OPS = ["NOP", "LDI", "MOV", "ADD", "SUB", "AND", "OR", "XOR",
       "LD", "ST", "JMP", "JZ", "JNZ", "JC", "OUT", "HALT"]
word = OPS.index("ADD") << 12 | 1 << 10 | 2 << 8
print(hex(word), format(word, "016b"))
print(OPS[word >> 12], (word >> 10) & 3, (word >> 8) & 3, word & 255)

The source syntax is small. A line holds an optional label (name:), then an optional instruction, then an optional comment that starts with ;. Two directives exist: .equ NAME value gives a constant a name and emits nothing, and .byte value emits one data word. Numbers may be decimal, 0x hex or 0b binary, and mnemonics and register names ignore case. Splitting a line into tokens is the first small job, and it is where comments and commas disappear.

A jump may name a label that is defined further down, so at JMP end the assembler cannot yet know what end means. The fix is two passes over the same lines. Pass 1 only counts: it keeps a word counter, records each label at the counter's value and adds one for every line that emits a word. Pass 2 encodes each line, now looking every name up in the finished table.

Two passes over the same lines
start / 3
Pass 1 builds the symbol table without encoding anything. Pass 2 encodes with the whole table available, so forward references work.
Two passes over the same lines
Pass 1 builds the symbol table without encoding anything. Pass 2 encodes with the whole table available, so forward references work.

Here is a program that adds 5 + 4 + 3 + 2 + 1.

Text
.equ LIMIT, 5
; sum the numbers down to 1
start: LDI r0, 0
       LDI r1, LIMIT
       LDI r2, 1
loop:  ADD r0, r1
       SUB r1, r2
       JNZ loop
       OUT r0
       HALT

The .equ line and the comment emit nothing, so start is 0 and loop is 3: three words come before it. JNZ loop therefore encodes as 0xC003, and the whole program assembles to 1000 1405 1801 3100 4600 C003 E000 F000 in hex. The same counting in miniature:

Python
lines = ["; sum", ".equ LIMIT, 5", "start: LDI r0, 0", "", "loop: ADD r0, r1", "JNZ loop"]
table, addr = {}, 0
for line in lines:
    tokens = line.split(";")[0].replace(":", ": ").split()
    if tokens and tokens[0].endswith(":"):
        table[tokens[0][:-1]] = addr
        tokens = tokens[1:]
    if tokens and tokens[0] != ".equ":
        addr += 1
print(table, addr)

Two mistakes are common, and both leave a program that assembles without complaint. The first is to number labels by source line instead of by emitted word, so comments and blank lines push every later label too far. The second is to count an .equ as a word. In both cases the code still runs, but every jump after the first comment or constant lands at the wrong place, which is hard to see in a long listing. Two smaller habits matter as well. Report an error with the physical line number, comments and blank lines included, because that is the number an editor shows. And reject a number that does not fit instead of masking it: silently turning 300 into 44 hides the mistake the programmer made.

The assembler must name five kinds of error: unknown op, bad register (r4), immediate out of range (256 or -1), duplicate label and undefined label.

How do you know the output is right? Disassembly prints each word as canonical text, and prints .byte for any word that no instruction spells, such as a NOP with a number in its low byte. Then assembling that text must give back the original word, for every one of the 65536 values. That round trip is necessary but weak: if the encoder and the decoder share the same wrong bit positions they still agree with each other. So the hidden tests also use hand-encoded words, a separate decoder written from the bit layout, and a tiny machine that runs the assembled sum program and expects 15. Even that confirms the layout described in this lesson. It cannot tell you that this layout is a good design for your CPU.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

The video this lesson is paired with: its chapters go from writing machine code by hand to assembly language, opcodes, labels and a looping program. Watch it for the idea of a program being text that becomes numbers, then build that translator for your own machine.