ArticleslgStudy

science

Self-modifying code

Self-modifying code is a science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Self-modifying code rather than just read about it. In short: 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. The term is usually only applied to code where the self-modification is deliberate, not in situations where code accidentally modifies itself due to an error such as a buff…

Key takeaways

  • Self-modifying code belongs to science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Self-modifying code to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Self-modifying code from memory before moving on to harder problems.

Reference excerpt

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. The term is usually only applied to code where the self-modification is deliberate, 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. 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 requires 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.

Application in low and high level languages Self-modification can be accomplished in a variety of ways depending upon the programming language and its support for pointers and/or access to dynamic compiler or interpreter "engines":

overlay of existing instructions (or parts of instructions such as opcode, register, flags or addresses) direct creation of whole instructions or sequences of instructions in memory creation or modification of source code statements followed by a "mini compile" or a dynamic interpretation (see eval statement) creating an entire program dynamically and then executing it

Assembly language Self-modifying code is quite straightforward to implement when using assembly language. Instructions can be dynamically created in memory (or else overlaid over existing code in non-protected program storage), in a sequence equivalent to the ones that a standard compiler may generate as the object code. With modern processors, there can be unintended side effects on the CPU cache that must be considered. The method was frequently used for testing "first time" conditions, as in this suitably commented IBM/360 assembler example. It uses instruction overlay to reduce the instruction path length by (N × 1) − 1, where N is the number of records on the file (−1 being the overhead to perform the overlay).

SUBRTN NOP OPENED FIRST TIME HERE? * The NOP is x'4700'<Address_of_opened> OI SUBRTN+1,X'F0' YES, CHANGE NOP TO UNCONDITIONAL BRANCH (47F0...) OPEN INPUT AND OPEN THE INPUT FILE SINCE IT'S THE FIRST TIME THRU OPENED GET INPUT NORMAL PROCESSING RESUMES HERE ...

Alternative code might involve testing a "flag" each time through. The unconditional branch is slightly faster than a compare instruction, as well as reducing the overall path length. In later operating systems for programs residing in protected storage, this technique could not be used, and so changing the pointer to the subroutine would be used instead. The pointer would reside in dynamic storage and could be altered at will after the first pass to bypass the OPEN (having to load a pointer first instead of a direct branch and link to the subroutine would add N instructions to the path length – but there would be a corresponding reduction of N for the unconditional branch that would no longer be required). Below is an example in Zilog Z80 assembly language. The code increments register B in range [0, 5]. The CP compare instruction is modified on each loop.

Self-modifying code is sometimes used to overcome limitations in a machine's instruction set. For example, in the Intel 8080 instruction set, one cannot input a byte from an input port that is specified in a register. The input port is statically encoded in the instruction itself, as the second byte of a two-byte instruction. Using self-modifying code, it is possible to store a register's contents into the second byte of the instruction, then execute the modified instruction in order to achieve the desired effect.

High-level languages Some compiled languages explicitly permit self-modifying code. For example, the ALTER verb in COBOL may be implemented as a branch instruction that is modified during execution. Some batch programming techniques involve the use of self-modifying code. Clipper and SPITBOL also provide facilities for explicit self-modification. The Algol compiler on B6700 systems offered an interface to the operating system whereby executing code could pass a text string or a named disc file to the Algol compiler and was then able to invoke the new version of a procedure. With interpreted languages, the "machine code" is the source text and may be susceptible to editing on-the-fly: in SNOBOL the source statements being executed are elements of a text array. Other languages, such as Perl and Python, allow programs to create new code at run-time and execute it using an eval function, but do not allow existing code to be mutated. The illusion of modification (even though no machine code is really being overwritten) is achieved by modifying function pointers, as in this JavaScript example:

Lisp macros also allow runtime code generation without parsing a string containing program code. The Push programming language is a genetic programming system that is explicitly designed for creating self-modifying programs. While not a high-level language, it is not as low-level as assembly language.

Compound modification Prior to the advent of multiple windows, command-line systems might offer a menu system involving the modification of a running command script. Suppose an MS-DOS batch file MENU.BAT contains the following:

:start SHOWMENU.EXE

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Self-modifying code

Start with the simplest possible case. Write down what Self-modifying code claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Self-modifying code before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Self-modifying code ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Self-modifying code

In research
Self-modifying code appears in science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Self-modifying code in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Self-modifying code is common in secondary-school and first-year university syllabi. It links to neighbouring topics Programming paradigms, so understanding it makes those chapters shorter.
In everyday life
Look for Self-modifying code outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Self-modifying code” →

How to study Self-modifying code in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Self-modifying code means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Self-modifying code out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Self-modifying code in simple terms?

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. The term is usually only applied to code where the s…

Why does Self-modifying code matter?

Because it connects several science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Self-modifying code?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Self-modifying code.

Tags

  • Programming paradigms

Keep exploring