Lesson 5 of 8

The disassembler

Goal

From numbers to readable names

01

Explanation

The list of tuples is precise, but it's all numbers. A disassembler turns it into names a person can read, so instead of (1, 72) you see LOAD 0x48. That's exactly what the big analysis tools do with real CPU instructions, except their table has hundreds of instructions.

Here are the machine's instructions again:

0x00 HALT      break
0x01 LOAD imm  acc = imm
0x02 ADD  imm  acc = (acc+imm) & 0xFF
0x03 XOR  imm  acc = acc ^ imm
0x04 SUB  imm  acc = (acc-imm) & 0xFF
0x05 OUT       out.append(acc)

You'll need a dictionary that maps each opcode to its name:

NAMES = {
    0x00: "HALT", 0x01: "LOAD",
    0x02: "ADD",  0x03: "XOR",
    0x04: "SUB",  0x05: "OUT",
}

The line format is fixed: the instruction's name, then a space and the operand in hex if it has one. The hex function writes a number with the 0x prefix and no leading zeros, so hex(1) returns "0x1" and hex(72) returns "0x48".

The decode function from the previous lesson is already in the starter code, so build on it.

02

Your task

Write the function disasm(program) that returns a list of strings, one line per instruction, such as "LOAD 0x48" for an instruction with an operand and "OUT" for one without.

Checks

5 checks
  1. The first line has LOAD and its operand
  2. An instruction without an operand is just its name
  3. The operand is written with hex, without a leading zero
  4. The full list of five lines
  5. Works on another program you haven't seen
03

Hints

0/3
Track lessons0 of 8 done

Read assembly, calling conventions and control flow, then build a disassembler and an emulator for a tiny machine, patch its bytes and check their integrity.

Intermediate level, 8 lessons, 2 hours in total.

main.py
OutputPython (Pyodide)

Loading Python. This only happens once. Your browser keeps it after that.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.

Track lessons0 of 8 done

Read assembly, calling conventions and control flow, then build a disassembler and an emulator for a tiny machine, patch its bytes and check their integrity.

Intermediate level, 8 lessons, 2 hours in total.