gpt4 book ai didi

winapi - 如何在运行时修补 Windows API 以便它在 x64 中返回 0?

转载 作者:行者123 更新时间:2023-12-01 15:04:11 24 4
gpt4 key购买 nike

在 x86 中,我使用 GetProcAddress() 获取函数地址并编写一个简单的 XOR EAX,EAX; RET 4; 在里面。简单有效。我如何在 x64 中执行相同的操作?

bool DisableSetUnhandledExceptionFilter()
{
const BYTE PatchBytes[5] = { 0x33, 0xC0, 0xC2, 0x04, 0x00 }; // XOR EAX,EAX; RET 4;

// Obtain the address of SetUnhandledExceptionFilter
HMODULE hLib = GetModuleHandle( _T("kernel32.dll") );
if( hLib == NULL )
return false;
BYTE* pTarget = (BYTE*)GetProcAddress( hLib, "SetUnhandledExceptionFilter" );
if( pTarget == 0 )
return false;

// Patch SetUnhandledExceptionFilter
if( !WriteMemory( pTarget, PatchBytes, sizeof(PatchBytes) ) )
return false;
// Ensures out of cache
FlushInstructionCache(GetCurrentProcess(), pTarget, sizeof(PatchBytes));

// Success
return true;
}

static bool WriteMemory( BYTE* pTarget, const BYTE* pSource, DWORD Size )
{
// Check parameters
if( pTarget == 0 )
return false;
if( pSource == 0 )
return false;
if( Size == 0 )
return false;
if( IsBadReadPtr( pSource, Size ) )
return false;
// Modify protection attributes of the target memory page
DWORD OldProtect = 0;
if( !VirtualProtect( pTarget, Size, PAGE_EXECUTE_READWRITE, &OldProtect ) )
return false;
// Write memory
memcpy( pTarget, pSource, Size );
// Restore memory protection attributes of the target memory page
DWORD Temp = 0;
if( !VirtualProtect( pTarget, Size, OldProtect, &Temp ) )
return false;
// Success
return true;
}

此示例改编自此处的代码:http://www.debuginfo.com/articles/debugfilters.html#overwrite .

最佳答案

在 x64 中,返回值在 RAX 中,它是 EAX 的 64 位版本。但是因为写32位子寄存器时高32位被清零,所以“xor eax, eax”等同于“xor rax, rax”,不需要改变。

但是,由于调用约定在 x64 上不同,相同的返回指令在那里不起作用:在 x86 winapi 函数中使用 stdcall 约定,被调用者从堆栈中弹出参数(因此是“retn 4”指令,它将 SetUnhandledExceptionFilter 中的一个参数从堆栈中弹出(您可能想在代码中修复该注释)) .在 x64 中,调用者不会清除堆栈,因此需要使用普通的“retn”指令:

const BYTE PatchBytes[3] = { 0x33, 0xC0, 0xC3 }; // XOR EAX,EAX; RET;

关于winapi - 如何在运行时修补 Windows API 以便它在 x64 中返回 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3010626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com