c generate function and call it

Viewed 269
#include <stdio.h>

#define uint unsigned int
#define AddressOfLabel(sectionname,out) __asm{mov [out],offset sectionname};

void* CreateFunction(void* start,void *end) {
    uint __start=(uint)start,__end=(uint)end-1
        ,size,__func_runtime;
    void* func_runtime=malloc(size=(((__end)-(__start)))+1);
    __func_runtime=(uint)func_runtime;
    memcpy((void*)(__func_runtime),start,size);
    ((char*)func_runtime)[size]=0xC3; //ret
    return func_runtime;
}
void CallRuntimeFunction(void* address) {
    __asm {
        call address
    }
}

main() {
    void* _start,*_end;
    AddressOfLabel(__start,_start);
    AddressOfLabel(__end,_end);
    void* func = CreateFunction(_start,_end);
    CallRuntimeFunction(func); //I expected this method to print "Test"
    //but this method raised exception
    return 0;
__start:
    printf("Test");
__end:
}

CreateFunction - takes two points in memory (function scope), allocate, copy it to the allocated memory and returns it (The void* used like a function to call with Assembly)

CallRuntimeFunction - runs the functions that returns from CreateFunction

#define AddressOfLabel(sectionname,out) - Outs the address of label (sectionname) to variable (out)

When I debugged this code and stepped in the call of CallRuntimeFunction and go to disassembly , I saw alot of ??? instead of assembly code of between __start and __end labels.

I tried to copy machine code between two labels and then run it. But I don't have any idea why I can't call function that allocated with malloc.

Edit:

I changed some code and done part of the work. Runtime Function's memory allocate:

void* func_runtime=VirtualAlloc(0, size=(((__end)-(__start)))+1, MEM_COMMIT, PAGE_EXECUTE_READWRITE);

Copy from function scope:

CopyMemory((void*)(__func_runtime),start,size-1);

But when I ran this program I can that:

mov         esi,esp  
push        0E4FD14h  
call        dword ptr ds:[0E55598h] ; <--- printf ,after that I don't know what is it
add         esp,4  
cmp         esi,esp  
call        000B9DBB  ; <--- here
mov         dword ptr [ebp-198h],0  
lea         ecx,[ebp-34h]  
call        000B9C17  
mov         eax,dword ptr [ebp-198h]
jmp         000D01CB  
ret  

At here it enters to another function and weird stuff.

2 Answers
Related