Self modifying code example

Started by Vortex, May 03, 2026, 12:37:58 PM

Previous topic - Next topic

Vortex

Hello,

A simple example of self modifying code. The procedure in the virtual address space is modified : the sub instruction replaced by add.

.386
.model flat,stdcall
option casemap:none

include     SMCtest.inc

.data

str1        db '80 + 20 = %u',0

.code

start:

    call    main
    invoke  ExitProcess,0

main PROC USES esi edi ebx

LOCAL pMem:DWORD

    invoke  VirtualAlloc,0,4096,\
            MEM_COMMIT or MEM_RESERVE,\
            PAGE_EXECUTE_READWRITE

    mov     pMem,eax
    mov     edi,eax
    mov     esi,OFFSET Calculate

    mov     ecx,ProcLen
    rep     movsb   ; Copy the procedure Calculate
                    ; to virtual address space

    lea     ecx,[eax+4]

                    ; Modify the procedure

    mov     BYTE PTR [ecx],_ADD

    push    80
    push    20
    call    eax

    invoke  printf,ADDR str1,eax

    invoke  VirtualFree,pMem,0,MEM_RELEASE
    ret

main ENDP

OPTION PROLOGUE:NONE
OPTION EPILOGUE:NONE

Calculate PROC a:DWORD,b:DWORD

    mov     eax,DWORD PTR [esp+8]
    sub     eax,DWORD PTR [esp+4]
    retn    2*4

Calculate ENDP

OPTION PROLOGUE:PrologueDef
OPTION EPILOGUE:EpilogueDef

END start
Code it... That's all...