Mes*_*ode 11 c x86 code-generation runtime
#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:
}
Run Code Online (Sandbox Code Playgroud)
CreateFunction- 在内存中占两点(函数范围),分配,将其复制到分配的内存并返回它(void*使用像函数一样调用Assembly)
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);
Run Code Online (Sandbox Code Playgroud)
从功能范围复制:
CopyMemory((void*)(__func_runtime),start,size-1);
Run Code Online (Sandbox Code Playgroud)
但是当我运行这个程序时,我能说:
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
Run Code Online (Sandbox Code Playgroud)
在here它进入另一个功能和奇怪的东西.
void CallRuntimeFunction(void* address) {
__asm {
call address
}
}
Run Code Online (Sandbox Code Playgroud)
这里的地址是一个指向该函数参数的“指针”,它也是一个指针。
指向指针的指针
使用:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
你想调用 func 它是一个指针。当传入 CallRunt... 函数时,这会生成一个指向该指针的新指针。第二度指针。
void* func = CreateFunction(_start,_end);
Run Code Online (Sandbox Code Playgroud)
是的 func 是一个指针
重要提示:检查编译器的“调用约定”选项。尝试一下 decl 一个