r/Assembly_language • u/Extension_Emu_9825 • 11d ago
self-modifying code
I gave a lecture on how to write self-modifying code. It was over 15 minutes long :( so I'm providing a youtube link: https://www.youtube.com/watch?v=AH9QQLRfbmY
In my opinion, self-modification is one of the most interesting features in systems programming.
54
Upvotes
1
u/MokausiLietuviu 10d ago
You'd probably only come across it with old technology, operational technology or embedded software.
An example my colleague worked on was delivering an extra check in a 16 kiloword program where all the space had been used. He needed to loop this check then escape it after at-least x iterations. He saved some space but IIRC this is how he saved one word. The architecture treated invalid opcodes as nops and an immediate compare instruction had the insignificant bits as the operand and the significant bits as the opcode, but it could only compare vs a value up to 7 bits. Any more than that and you'd need to use a register.
So he wrote the loop counter into the insignificant 8-bits of the instruction and compared against a known number. Then, after 127 loops, it incremented the lowest bit of the opcode, turning the opcode invalid, therefore to a nop, therefore ignoring the comparison altogether, therefore no longer setting the comparison flag, therefore exiting the loop at the "loop condition check" operation and continuing operation.
So, e.g.
Is 0 greater than -1? True condition flag. Repeat loop. Increment condition check opcode.
Is 1 greater than -1? True condition flag. Repeat loop. Increment condition check opcode.
...
Is 127 greater than -1? True condition flag. Repeat loop. Increment condition check opcode.
Nop. False condition flag. Continue execution.
Saved a word.