Lesson 7 of 8
Patching bytes
- 15 min
- 6 checks
- 3 hints
- Go to task
Goal
One byte changes the behavior
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)
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- Patching changes the requested byte
- The original stays as it was
- The result is bytes and keeps the same length
- The patched program prints the letter J
- patched is the result of calling patch on program
- Works on another program and index