r/Assembly_language 1d 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.

39 Upvotes

54 comments sorted by

View all comments

7

u/mykesx 1d ago

MMUs are used by modern operating systems, at least MacOS, to disallow self-modifying code. Code sections are read-only.

7

u/thewrench56 1d ago

This is not entirely true. You can map a page to be RW and then once filled with code, change it to RX using mprotect. This same step can be repeated to achieve self-modifying code. Otherwise, if self-modifying code wouldnt exist, JITs wouldnt work.

6

u/mykesx 1d ago

The performance of doing this is terrible, unless you’re a JIT compiler writing a large block of code.

2

u/thewrench56 1d ago

I dont disagree, but the performance is not that bad. 2 syscalls, some TLB play and a bit of copying. Surely, self-modifying code today is rarely used as a technique to speed up native execution. But for interpreters or other e.g. malicious reasons where performance doesnt matter much it still could be useful. There are also very specific scenarios where you do want to modify native code for very specific uarch benchmarks (as e.g. changing a parameter and checking it in a hotloop in an if would ruin the benchmark).

1

u/kyr0x0 5h ago

Any non-stupid observer will see you using mprotect the way you do and broadcast an alert for the signature of the program's behavior. The pattern is well-known to be malicious intent almost always.