this example copy a given function.
the first intention is to make self-modifying function.
but it seems can be an example as it is. so I post it.
this program calls clone_func which get size of the function first and then use malloc(the c function) to acquire memory space. then just copy using
you can learn following things
1. function's prologue
2. function's epilogue
3. c calling convention
4. how to use invoke macro
5. how to use stack for local variable
6. access to function's parameters
7. how to use rep movsb
8. how to use c function
the code is here
format PE console
entry start
include "win32a.inc"
msg: db 'number: %d',10,0
func1:
push ebp
mov ebp, esp
invoke printf, msg
add esp, 4
mov esp, ebp
pop ebp
ret
dd func1
.size: dd $ - func1
;get_func_size(func)
get_func_size:
push ebp
mov ebp, esp
mov ecx, 0
mov edx, [ebp+8]
jmp .loop1
.loop2:
inc ecx
.loop1:
cmp dword [edx+ecx], edx
jne .loop2
mov eax, ecx
mov esp, ebp
pop ebp
ret
clone_func:
push ebp
mov ebp, esp
sub esp, 40
push dword func1
call get_func_size
add esp, 4
mov [ebp-4], eax ;size of func
invoke malloc, eax
add esp, 4
mov [ebp-8], eax ;addr of new func
mov ecx, [ebp-4]
mov edi, [ebp-8]
mov esi, [ebp+8] ;addr of orig func
cld
rep movsb
mov eax, [ebp-8]
mov esp, ebp
pop ebp
ret
start:
push dword func1
call clone_func
add esp, 4
call eax
call func1
invoke getch
invoke
data import
library msvcrt,'msvcrt.dll'
import msvcrt,printf,'printf',getch,'_getch',exit,'exit',malloc,'malloc'
end data