Size for changing memory protection on TargetProc

Oct 28, 2009 at 8:19 AM

I got occasional crash (just on some XP machines) when I hook GetWindowDC.  (EasyHook works perfectly on the other 100 hooked APIs).  I debug into Easyhook.dll and found that the crash happens in the function LhInstallHook:

	*((ULONGLONG*)Hook->TargetProc) = AtomicCache;

The statement copy 8 bytes (ULONGLONG) to the TargetProc.  The debugger prompted me an access denied error for writing an address 6 bytes offset to the TargetProc.  In the early lines of the same function, there is:

	FORCE(RtlProtectMemory(Hook->TargetProc, Hook->EntrySize, PAGE_EXECUTE_READWRITE));

where Hook->EntrySize is 5.

 

If I change the code to 8 as following, it works.

	FORCE(RtlProtectMemory(Hook->TargetProc, 8, PAGE_EXECUTE_READWRITE));

 

Chris, Do you foresee any harm if I do so.

Oct 7, 2010 at 9:27 PM
Edited Oct 7, 2010 at 9:32 PM

Hello,

sorry for reopening old post.

I want add some info. There is a problem with RtlProtectMemory.

The solution to problem is:

#ifdef X64_DRIVER
    FORCE(EntrySize = LhRoundToNextInstruction(InEntryPoint, 16)); //originaly was 12
#else
    FORCE(EntrySize = LhRoundToNextInstruction(InEntryPoint, 8)); //originaly was 5
#endif

value is then used by:

//this code is used only in 32b, so in 64b 12 will probably work

FORCE(RtlProtectMemory(Hook->TargetProc, Hook->EntrySize, PAGE_EXECUTE_READWRITE));

and data are written:

#ifdef X64_DRIVER

...
    *((ULONGLONG*)(Hook->TargetProc + 0)) = AtomicCache_x64;
    *((ULONGLONG*)(Hook->TargetProc + 8)) = AtomicCache;               //reason why 16 (not 12)

#else

...

    *((ULONGLONG*)Hook->TargetProc) = AtomicCache;  //reason why 8 (not 5)
#endif

You may wonder, why it is problem.

It is not problem until LhRoundToNextInstruction is returning >= 8, and this is not happening on some wXP machines with GetWindowDC function --> crash or BSOD.

Finally I hope, this modification wont cause more trouble. :))