4 ms·
Sibling answer about the cache is correct: there's very little benefit to doing this on a modern system. And it tends to trip security systems. Many exploits ar
by pjc50 5y ago
Sibling answer about the cache is correct: there's very little benefit to doing this on a modern system. And it tends to trip security systems. Many exploits are some form of "trick code that wasn't self modifying into modifying itself, or jumping into this buffer in data space that I've just given you".
There might be benefits to "modify-once" code in some circumstances because of how branch prediction works. If you determine that a branch is being consistently mispredicted you can speed it up by changing the code so that it is correctly predicted - invert the test, swap the branch targets, apply a prefix instruction, etc.
It is not unusual to have CPU-specific bits of code gated behind a CPUID check; you could maybe gain a bit by doing the check and then hardwiring a branch or pasting the code into the middle of a loop.
A related trick is the "micro-interpreter". You build a hyper-specialised language and run short programs in that - which can then use self-modification as well, because they're counted as "data" and not code. I think there was a game that used this (Flashback maybe?)