PVOID HeapMemory = NULL;
PVOID MainFunctionAddress = NULL;
int RunFunction(int* a, int* b){
*a = *a + 1; *b = *b + 1;return *a + *b;
}
VOID main(int argc, char* argv[])
{
MainFunctionAddress = GetDbgFunctionPointerAddress(main);
//申请内存属性为读写权限
HeapMemory = VirtualAlloc(NULL, PAGE_SIZE, MEM_COMMIT | MEM_RESERVE,PAGE_READWRITE);
int a=1, b=11;
LPVOID Address = (LPVOID)RunFunction;
Address = GetDbgFunctionPointerAddress(RunFunction);
//将RunFunction的内容复制到HeapMemory。
RtlCopyMemory(HeapMemory, Address, 0x3b);
ZxDebug(("HeapMemory = %p MainFunctionAddress=%p \n", HeapMemory, MainFunctionAddress));
__try
{
//执行HeapMemory,asmcall jmp r8
//内存属性为读写,执行函数会产生异常
for(int i =0 ; i < 3; i++)
asmcall((PVOID)&a, (PVOID)&b, HeapMemory);
}__except(FilterException(GetExceptionCode(), GetExceptionInformation()))
{
ZxDebug((__FUNCTION__"():: EXCEPTION_EXECUTE_HANDLE\n"));
}
ZxDebug((__FUNCTION__"():: a = %d b = %d\n", a, b));
}
int FilterException(ULONG ExceptionCode, _EXCEPTION_POINTERS* Exception)
{
MEMORY_BASIC_INFORMATION Mbi={};
SIZE_T Size = VirtualQuery(Exception->ExceptionRecord->ExceptionAddress, &Mbi, sizeof(MEMORY_BASIC_INFORMATION));
DWORD flOldProtect = 0;
ZxDebug((__FUNCTION__"():: ExceptionAddress:%p \n", Exception->ExceptionRecord->ExceptionAddress));
if (Exception->ExceptionRecord->ExceptionAddress == HeapMemory)
{
assert(ExceptionCode == STATUS_ACCESS_VIOLATION && Mbi.Protect == PAGE_READWRITE);
assert(Exception->ExceptionRecord->ExceptionAddress == HeapMemory);
PVOID NextRip = (PVOID)(*(ULONG_PTR*)Exception->ContextRecord->Rsp);
int a = *(int*)Exception->ContextRecord->Rcx; int b = *(int*)Exception->ContextRecord->Rdx;
ZxDebug((__FUNCTION__"():: RunFunction(a = %d b= %d) NextRip=%p\n", a, b, NextRip));
//将HeapMemory内存属性改为可执行。将Main函数改为不可执行
VirtualProtect(HeapMemory, PAGE_SIZE, PAGE_EXECUTE_READ,&flOldProtect);
VirtualProtect((PVOID)MainFunctionAddress, PAGE_SIZE, PAGE_READWRITE,&flOldProtect);
}else
{
assert(ExceptionCode == STATUS_ACCESS_VIOLATION && Mbi.Protect == PAGE_READWRITE);
if ((ULONG_PTR)MainFunctionAddress <= (ULONG_PTR)Exception->ExceptionRecord->ExceptionAddress
&&(ULONG_PTR)Exception->ExceptionRecord->ExceptionAddress <= (ULONG_PTR)MainFunctionAddress +PAGE_SIZE)
{
int Ret = (Exception->ContextRecord->Rax);
PVOID NextRip = (PVOID)(*(ULONG_PTR*)Exception->ContextRecord->Rsp);
ZxDebug((__FUNCTION__"():: (%d)RunFunction(a , b) NextRip=%p\n", Ret, NextRip));
//将Main函数改为可执行
VirtualProtect((PVOID)MainFunctionAddress, PAGE_SIZE, PAGE_EXECUTE_READ,&flOldProtect);
//将HeapMemory内存属性改为不可执行。
VirtualProtect(HeapMemory, PAGE_SIZE, PAGE_READWRITE,&flOldProtect);
}
}
return EXCEPTION_CONTINUE_EXECUTION;
}