Введение
В компьютерной науке самомодифицирующийся код (SMC или SMoC) — это код, который изменяет собственные инструкции во время выполнения, обычно для сокращения длины пути выполнения инструкций и повышения производительности или просто для уменьшения избыточности схожего кода, что упрощает поддержку. Термин обычно применяется только к коду, где самомодификация является намеренной, а не к ситуациям, когда код случайно изменяет себя из-за ошибки, такой как переполнение буфера. Самомодифицирующийся код может включать перезапись существующих инструкций или генерацию нового кода во время выполнения и передачу управления этому коду. Самомодификация может использоваться как альтернатива методу "установки флага" и условного ветвления программы, применяемому главным образом для уменьшения количества проверок условий. Этот метод часто используется для условного вызова кода тестирования/отладки без дополнительных вычислительных затрат на каждый цикл ввода-вывода. Изменения могут выполняться: только во время инициализации на основе входных параметров (когда процесс чаще описывается как "конфигурация" программного обеспечения и в некоторой степени аналогичен, с точки зрения аппаратного обеспечения, установке перемычек на печатных платах). Изменение указателей точек входа в программу является эквивалентным косвенным методом самомодификации, но требует одновременного существования одного или нескольких альтернативных путей выполнения инструкций, что увеличивает размер программы. в процессе выполнения ("на лету") — на основе конкретных состояний программы, достигнутых в ходе выполнения.
In computer science, self modifying code (SMC or SMoC) is code that alters its own instructions while it is executing – usually to reduce the instruction path length and improve performance or simply to reduce otherwise repetitively similar code, thus simplifying maintenance. The term is usually only applied to code where the self modification is intentional, not in situations where code accidentally modifies itself due to an error such as a buffer overflow. Self modifying code can involve overwriting existing instructions or generating new code at run time and transferring control to that code. Self modification can be used as an alternative to the method of "flag setting" and conditional program branching, used primarily to reduce the number of times a condition needs to be tested. The method is frequently used for conditionally invoking test/debugging code without requiring additional computational overhead for every input/output cycle. The modifications may be performed:
only during initialization – based on input parameters (when the process is more commonly described as software 'configuration' and is somewhat analogous, in hardware terms, to setting jumpers for printed circuit boards). Alteration of program entry pointers is an equivalent indirect method of self modification, but requiring the co existence of one or more alternative instruction paths, increasing the program size. throughout execution ("on the fly") – based on particular program states that have been reached during the execution
In either case, the modifications may be performed directly to the machine code instructions themselves, by overlaying new instructions over the existing ones (for example: altering a compare and branch to an unconditional branch or alternatively a 'NOP'). In the IBM System/360 architecture, and its successors up to z/Architecture, an EXECUTE (EX) instruction logically overlays the second byte of its target instruction with the low order 8 bits of register 1. This provides the effect of self modification although the actual instruction in storage is not altered.
В любом случае, изменения могут выполняться непосредственно в инструкциях машинного кода путем наложения новых инструкций поверх существующих (например, изменение инструкции сравнения и ветвления на безусловное ветвление или, альтернативно, вставкой "NOP"). В архитектуре IBM System/360 и ее преемниках до z/Architecture, инструкция EXECUTE (EX) логически заменяет второй байт целевой инструкции младшими 8 битами регистра 1. Это обеспечивает эффект самомодификации, хотя фактическая инструкция в памяти не изменяется.
In computer science, self modifying code (SMC or SMoC) is code that alters its own instructions while it is executing – usually to reduce the instruction path length and improve performance or simply to reduce otherwise repetitively similar code, thus simplifying maintenance. The term is usually only applied to code where the self modification is intentional, not in situations where code accidentally modifies itself due to an error such as a buffer overflow. Self modifying code can involve overwriting existing instructions or generating new code at run time and transferring control to that code. Self modification can be used as an alternative to the method of "flag setting" and conditional program branching, used primarily to reduce the number of times a condition needs to be tested. The method is frequently used for conditionally invoking test/debugging code without requiring additional computational overhead for every input/output cycle. The modifications may be performed:
only during initialization – based on input parameters (when the process is more commonly described as software 'configuration' and is somewhat analogous, in hardware terms, to setting jumpers for printed circuit boards). Alteration of program entry pointers is an equivalent indirect method of self modification, but requiring the co existence of one or more alternative instruction paths, increasing the program size. throughout execution ("on the fly") – based on particular program states that have been reached during the execution
In either case, the modifications may be performed directly to the machine code instructions themselves, by overlaying new instructions over the existing ones (for example: altering a compare and branch to an unconditional branch or alternatively a 'NOP'). In the IBM System/360 architecture, and its successors up to z/Architecture, an EXECUTE (EX) instruction logically overlays the second byte of its target instruction with the low order 8 bits of register 1. This provides the effect of self modification although the actual instruction in storage is not altered.
Язык сборки
Самомодифицирующийся код довольно просто реализовать при использовании языка ассемблера. Инструкции могут быть динамически созданы в памяти (или же перезаписаны поверх существующего кода в незащищенной области памяти программ). В меньшей степени, ядро DR DOS также оптимизирует критически важные участки кода при загрузке, в зависимости от поколения используемого процессора.