Self-modifying code: Difference between revisions

Content deleted Content added
Chris Roy (talk | contribs)
m recomended->recommended
No edit summary
Line 1:
In [[computer science]], '''self-modifying code''' is code that modifies itself. This is straightforward to write when using [[assembly language]] and is also supported by some high level language interpreters such as [[SNOBOL4]] or the [[Lisp programming language]]. It is more difficult to implement on compilers but compilers such as [[Clipper programming language|Clipper]] and [[Spitbol]] make a fair attempt at it. Batch programming [[scripting programming language|script]]s often involve self modifying code as well.
 
[[Reconfigurable computing]] could be said to be self-modifying <i>hardware</i>. This technique blurs the border between software and hardware.
 
 
Line 54 ⟶ 56:
 
Because of the security implications of self-modifying code, some [[operating system]]s go to lengths to rule it out. Recent versions of [[OpenBSD]], for instance, have a feature known as W^X (for "write [[xor]] execute", meaning a program can only write, or execute, ''but not both'') which inhibits alteration of memory pages which harbor executable code. Programs which depend upon rewriting their own machine code cannot execute in such an environment.
 
Most modern processors loads the mashinecode before they executes it, wich 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 <i>before</i> it was modified. See [[Instruction Prefetch Queue]] (PIQ)
 
==Example [[nasm]]-[[syntax]] [[x86]]-assembly algorithm that determines the size of PIQ==
 
xor cx, cx ; zero register cx
xor ax, ax ; zero register ax
 
mov dx, cs ; change dx to edx for protected mode.
mov [code_segment], dx ; "calculate" codeseg in the far jump below (edx here too)
 
around:
cmp ax, 1 ; check if ax has been alterd
je found_size
 
mov [nop_field+cx], 0x90 ; 0x90 = opcode "nop" (NO oPeration)
inc cx
 
db 0xEA ; 0xEA = opcode "far jump"
dw flush_queue ; should be followed by offset (rm = "dw", pm = "dd")
code_segment:
dw 0 ; and then the code segment (calculated above)
flush_queue:
mov [nop_field+cx], 0x40 ; 0x40 = opcode "inc ax" (INCrease ax)
 
nop_field:
nop times 256
jmp around
found_size:
;
; register cx now contains the size of the PIQ
; this code is for [[realmode]], but it could easily be changed into
; running for [[protected mode]] as well. just change the "dw" for
; the offset to "dd". you need also change dx to edx at the top as
; well. (dw and dx = 16 bit adressing, dd and edx = 32 bit adressing)
;
 
 
==Example algorithm (theoretical!)==