Lesson 4 of 8

A tiny machine: decoding

Goal

Instructions of different lengths

01

Explanation

From here on you build analysis tools yourself, for a tiny machine we invented for these lessons. A virtual machine is a program that executes instructions encoded as bytes, called bytecode, just as Python itself does with your code. Understanding a small invented machine is the shortest path to understanding real ones.

Our machine has a single slot called the accumulator, which starts at zero, and six instructions. Each instruction starts with one byte, the opcode, and four of them are followed by a second byte, the operand. Each line below shows the opcode, then its name, then imm if it takes an operand, then its effect written in Python:

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)

So the program 01 48 05 00 reads like this: LOAD with the operand 0x48, then OUT, then HALT. The byte 48 isn't an instruction but the operand of the instruction before it. That's the most important idea in decoding: instructions vary in length, so you can't know where the next instruction starts until you know the length of the current one.

That's why you walk the bytes with an index i. You read the opcode at program[i], and if it has an operand you read it from program[i + 1] and move ahead two bytes; otherwise you move ahead one byte. When you reach HALT you stop, because the bytes after it aren't instructions.

02

Your task

Write the function decode(program) that returns a list of tuples, one per instruction, in the form (opcode, operand), where the operand is None for an instruction that has no operand. Stop after HALT.

Checks

6 checks
  1. The first instruction is LOAD with its operand
  2. OUT has no operand
  3. The full list of five instructions
  4. Stops at HALT and reads nothing after it
  5. Works on another program you haven't seen
  6. An operand is never read as an opcode, even when its value matches one
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.

–/6

Checks start once the environment is ready.

6 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.