Self-modifying code is a software technique in which an application creates or changes a part of its program code in the process of execution. Such code is usually used in programs written for a processor with von Neumann memory organization. This is a principle of shared code and memory data storage. Most of the currently most popular processors correspond to the von Neumann’s architecture. For example, Intel processors of the x86 / IA-64 family.
Types of code modification
The method is divided into the following types depending on modification time:
- Modification during initialization – is performed once, before running the modifiable code
- Modification on the fly (on-the-fly) – changing the program state during execution
The change occurs directly in the machine code, when new instructions overwrite the old ones, in both cases. E.g. a conditional transition – JZ, JNZ, JE, JNE, etc. – is replaced by an unconditional JMP or NOP transition . An instruction set of IBM / 360 and Z / Architecture has an EXECUTE (EX) instruction that rewrites the target instruction (written in the second byte of the EX command) with the least significant 8 bits of the register 1. It helps to implement a standard, legal method for temporary changes of instructions on these architectures.
The need to apply the method of “self-modifying”
The process of the code modification during the program execution is quite dangerous and can lead to an emergency termination. In many cases it is viruses and other spyware that put a program into the category of “self-modifying programs” with an intention to cause damage in one way or another. Nevertheless, sometimes there are situations when code modification during a program execution is necessary to make changes “on the fly” in a code of a third-party library without the source code. Program products-analyzers often use code modification to intercept calls carried out by the analyzed process components to collect various kinds of statistics.