How do I patch a Windows API at runtime so that it to returns 0 in x64?

Posted by Jorge Vasquez on Stack Overflow See other posts from Stack Overflow or by Jorge Vasquez
Published on 2010-06-09T23:06:41Z Indexed on 2010/06/09 23:12 UTC
Read the original article Hit count: 251

Filed under:
|
|
|
|

In x86, I get the function address using GetProcAddress() and write a simple XOR EAX,EAX; RET; in it. Simple and effective. How do I do the same in x64?

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

  // 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;
}

This example is adapted from code found here: http://www.debuginfo.com/articles/debugfilters.html#overwrite .

© Stack Overflow or respective owner

Related posts about winapi

Related posts about assembly