Search code examples
assemblyx86self-modifying

Find a minimal self-modifiying code example for educational purpose in x86 assembler?


I am looking for a few lines long example demonstrating a self-modifying code in x86 assembler for educational purpose (does not need to do something meaningful but needs to clearly write his own code and then execute it when you read the code itself).

I did browse a bit the Web, but all the examples are either way too complex or just not really self-explanatory. I might have missed the right place to go, so feel free to suggest links or code.


Solution

  • Many processors cannot see modifications to code immediately after it gets changed, and execute the old bytes instead. For example the following code will still (most of the time) increment eax, even after the 'inc' instruction is overwritten with the 'nop'-s. You should almost always see eax=1, and get eax=0 if an exception happened after the 'mov'.

    ; Intel syntax
    
    .arch   i386
    .text
    start:
            xor     %eax, %eax
            mov     word ptr change, 0x9090
    change: inc     %eax
            nop
            ret
    

    If EFLAGS.TF=1 eax will always be 0. Whether this is useful is another story. Long time ago a friend used self-modifying code for obfuscation purposes, and had several traps as above that relied on the processor to actually ignore the change.