c生成函数并调用它

时间:2012-07-31 11:39:42

标签: c x86 runtime code-generation

#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 - 在内存中占两点(函数作用域),分配,复制到已分配的内存并返回它(void*像函数一样用于调用程序集)

CallRuntimeFunction - 运行从CreateFunction

返回的函数

#define AddressOfLabel(sectionname,out) - 将标签(sectionname)的地址输出到变量(out)

当我调试此代码并进入CallRuntimeFunction的调用并进入反汇编时, 我看到了很多???而不是__start__end标签之间的汇编代码。

我尝试在两个标签之间复制机器代码,然后运行它。但我不知道为什么我不能调用用malloc分配的函数。

编辑:

我更改了一些代码并完成了部分工作。 运行时函数的内存分配:

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

从功能范围复制:

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

但是当我运行这个程序时,我能说:

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  

here,它会进入另一个函数和奇怪的东西。

2 个答案:

答案 0 :(得分:2)

void CallRuntimeFunction(void* address) {
    __asm {
        call address
    }
}

这里的地址是这个函数的一个参数的“指针”,它也是一个指针。

指向指针的指针

使用:

void CallRuntimeFunction(void* address) {
_asm {
    mov ecx,[address] //we get address of "func"
    mov ecx,[ecx]   //we get "func"
    call [ecx]      //we jump func(ecx is an address. yes)
    }
}

你想调用func这是一个指针。当你在CallRunt ...函数中传递时,会生成一个指向该指针的新指针。二度指针。

void* func = CreateFunction(_start,_end);

是的func是一个指针

重要提示:检查编译器“调用约定”选项。尝试decl one

答案 1 :(得分:0)

确保在函数代码生成和调用之间使高速缓存(指令和数据)无效。有关详细信息,请参阅自我修改代码

相关问题