Self-modifying code is quite straightforward to write when using assembly language (taking into account the CPU cache). It is also supported by some high level language interpreters such as SNOBOL4, the Lisp programming language, or the ALTER verb in COBOL. It is more difficult to implement on compilers but compilers such as Clipper and Spitbol make a fair attempt at it, and COBOL almost encourages it. One batch programming technique is to use self-modifying code. Most scripting languages such as Perl and Python are interpreted, which means that the program can generate new code and execute it; usually, this is done in a variable, but it can also be performed by writing out a new file and running it in the scripting language interpreter.
Self-modifying code can be used for various purposes:
The second and third types are probably the kinds mostly used also in high-level languages, such as LISP.
repeat N times {
if STATE is 1
increase A by one
else
decrease A by one
do something with A
}
Self-modifying code in this case would simply be a matter of rewriting the loop like this:
repeat N times {
increase A by one
do something with A}
when STATE has to switch {
replace the opcode "increase" above with the opcode to decrease}
Note that 2-state replacement of the opcode can be easily written as 'xor var at address with the value "opcodeOf(Inc) xor opcodeOf(dec)"'.
Choosing this solution will have to depend of course on the value of 'N' and the frequency of state changing.
Self-modifying code can either be seen as a feature like any other (or even as just delayed code-editing), or as a bad practice which makes code harder to read and maintain.
In the early days of computers, self-modifying code was used often in order to reduce the usage of memory, which was extremely limited, and didn't pose any problem. It was also used to implement subroutine calls and returns when the instruction set only provided simple branching or skipping instructions to vary the control flow. This application is still relevant in certain ultra-RISC architectures, at least theoretically; see for example One instruction set computer. Donald Knuth's MIX architecture also used self-modifying code to implement subroutine calls.
Already, critical systems which are too complex for people to fully manage in real time, such as the Internet and electrical distribution networks routinely rely upon self-modifying behaviors (though not necessarily self-modifying code) in order to function acceptably.
Self-modifying code is also sometimes used by programs that do not want to reveal their presence — such as computer viruses and some shellcodes. Viruses and shellcodes that use self-modifying code mostly do this in combination with polymorphic code. Polymorphic viruses are sometimes called primitive self-mutators. Modifying a piece of running code is also used in certain attacks, such as buffer overflows.
Traditional machine learning systems have a fixed, pre-programmed learning algorithm to adjust their parameters. However, since the 1980s Jürgen Schmidhuber has published several self-modifying systems with the ability to change their own learning algorithm. They avoid the danger of catastrophic self-rewrites by making sure that self-modifications will survive only if they are useful according to a user-given fitness function or error function or reward function.
As consequence of the troubles that can be caused by these exploits, an OS feature called W^X (for "write xor execute") has been developed which prohibits a program from making any page of memory both writable and executable. Some systems prevent a writable page from ever being changed to be executable, even if write permission is removed. Other systems provide a back door of sorts, allowing multiple mappings of a page of memory to have different permissions. A relatively portable way to bypass W^X is to create a file with all permissions, then map the file into memory twice. On Linux, one may use an undocumented SysV shared memory flag to get executable shared memory without needing to create a file. On Windows Vista and Windows XP the W^X protection is named Data Execution Prevention and can be disabled via the Control Panel.
Regardless, at a meta-level, programs can still modify their own behavior by changing data stored elsewhere (see Metaprogramming) or via use of polymorphism.
Graphics drivers for modern GPUs perform JIT-Compilation of DirectX or OpenGL/GLSL geometry and fragment shaders, and can thus be seen as self-modifying code, sometimes distributed over multiple processors and DSPs (or even self-modifying hardware).
Some CPU Architecture Emulators use similar techniques as JIT-Compilers (simulated instruction set as "programming language" that becomes compiled for the target processor).
In some cases short sections of self-modifying code executes more slowly on modern processors. This is because a modern processor will usually try to keep blocks of code in its cache memory. Each time the program rewrites a part of itself, the rewritten part must be loaded into the cache again, which results in a slight delay, if the modified codelet shares the same cache line with the modifying code, as is the case when the modified memory address is located within a few bytes to the one of the modifying code.
The cache invalidation issue on modern processors usually means that self-modifying code would still be faster only when the modification will occur rarely, such as in the case of a state switching inside an inner loop.
Most modern processors load the machine code before they execute it, which means that if an instruction that is too near the instruction pointer is modified, the processor will not notice, but instead execute the code as it was before it was modified. See Prefetch Input Queue (PIQ). PC processors have to handle self-modifying code correctly for backwards compatibility reasons but they are far from efficient at doing so.
The Synthesis kernel was extremely fast, but was written entirely in assembly. The resulting lack of portability has prevented Massalin's optimization ideas from being adopted by any production kernel. However, the structure of the techniques suggests that they could be captured by a higher level language, albeit one more complex than existing mid-level languages. Such a language and compiler could allow development of extremely fast operating systems and applications.
Paul Haeberli and Bruce Karsh have objected to the "marginalization" of self-modifying code, and optimization in general, in favor of reduced development costs, drawing a parallel to the "heavy religious atmosphere" which the Italian Futurist movement rebelled against.