The assembler languages of the 1960s used self-modifying code to implement function calls without a stack.
Knuth, v1, 1ed p. 182:
MAX100 STJ EXIT ;Subroutine linkage ENT3 100 ;M1. Initialize JMP 2F 1H CMPA X,3 ;M3. Compare JGE *+3 2H ENT2 0,3 ;M4. Change m LDA X,3 ;(New maximum found) DEC3 1 ;M5. Decrease k J3P 1B ;M2. All tested? EXIT JMP * ;Return to main program
In a larger program containing this encoding as a subroutine, one “JMP MAX100” command will cause register A to be set to the current maximum location value X + 1 - X + 100, and the maximum position will appear in rI2. The subroutine in this case is reached by the instructions "MAX100 STJ EXIT", and then "EXIT JMP *". Due to how the J-register works, the exit instruction will then move to the place following the place where the original reference to the MAX100 was made.
Edit: It may be difficult to understand what is happening, even with a brief explanation here. On the MAX100 STJ EXIT line, MAX100 STJ EXIT , MAX100 is the label for the instruction (and therefore for the procedure as a whole), STJ means STORE in the jump register (where we just came from), EXIT means the memory location marked as “EXIT” is the target of STORE. EXIT , we will see later the label of the last instruction. So this is code rewriting! But many instructions (including STJ here) implicitly rewrite only part of the operand of a command word. Thus, JMP remains untouched, and * is a dummy marker, since there really is nothing significant in it, it is only overwritten.
Self-modifying code is also used where indirect addressing is unavailable, and yet the address you need is right there in the register. PDP-1 LISP:
dap .+1 ;deposit address part of accumulator in (IP+1) lac xy ;load accumulator with (ADDRESS) [xy is a dummy symbol, just like * above]
These two commands execute ACC := (ACC) by changing the operand of the load command.
Modifications like these are relatively safe, and on ancient architectures they are needed.
luser droog Sep 17 '11 at 5:53 2011-09-17 05:53
source share