flat assembler
Message board for the users of flat assembler.

flat assembler > Examples and Tutorials > clone function

Author
Thread Post new topic Reply to topic
taeyun



Joined: 12 Jan 2014
Posts: 42
Location: south korea
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
Code:
rep movsb    


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

Code:
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
    

_________________
influenced by
elements(Euclid)
rules for the direction of the mind(Descartes)
Post 16 Mar 2014, 07:34
View user's profile Send private message Reply with quote
Display posts from previous:
Post new topic Reply to topic

Jump to:  


< Last Thread | Next Thread >
Forum Rules:
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


Copyright © 1999-2018, Tomasz Grysztar.

Powered by rwasa.