Lesson 7 of 8

Patching bytes

Goal

One byte changes the behavior

01

Explanation

Patching means changing the bytes of an existing program so that its behavior changes, without rebuilding it from source. It's useful when you fix a bug in an old program of yours whose source code is lost, or when you test your understanding during analysis: if this byte is the operand of LOAD, changing it changes the output. If the output changes the way you expected, you've understood the program.

Python's bytes type can't be changed once it's created, so the line program[1] = 0x4a raises an error. A bytearray, on the other hand, is a mutable version: you copy the bytes into it, change what you want, then turn it back into bytes:

ba = bytearray(data)
ba[i] = new_value
patched = bytes(ba)

Copying matters: never modify the original, because you may need to compare the two versions or apply another patch from the same starting point.

The machine's instructions, as you already know them:

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)
02

Your task

Write the function patch(program, index, value) that returns a new bytes copy in which the byte at index equals value, leaving the original unchanged. Then patch the LOAD operand in program and store the result in patched so that it prints the letter J instead of H. The run emulator from the previous lesson is there for you to try it out.

Checks

6 checks
  1. Patching changes the requested byte
  2. The original stays as it was
  3. The result is bytes and keeps the same length
  4. The patched program prints the letter J
  5. patched is the result of calling patch on program
  6. Works on another program and index
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.