Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am using API Hooking as suggested in this example:

API/Function Hooking/Interception Using JMP Instruction aka splicing

One of the functions which I am hooking is the BitBlt() function. In the hooked function, I am creating a new thread using CreateThread().

BOOL WINAPI MY_BitBlt(HDC hdcDest, int xDest, int yDest, int width, int height, HDC hdcSrc, int xSrc, int ySrc, DWORD dwRop)
{
    VirtualProtect((LPVOID)pOrig_BitBlt_Address, SIZE_6, my_BitBlt_Protect, NULL);
    memcpy(pOrig_BitBlt_Address, old_BitBlt_Bytes, SIZE_6);
    BOOL rv = Real_BitBlt(hdcDest, xDest, yDest, width, height, hdcSrc, xSrc, ySrc, dwRop); // Calls the actual function
    memcpy(pOrig_BitBlt_Address, JMP_BitBlt, SIZE_6);
    VirtualProtect((LPVOID)pOrig_BitBlt_Address, SIZE_6, old_BitBlt_Protect, NULL);
    CreateThread(NULL, 0, _SampleProc, NULL , 0, 0);
    ...
    return rv;
}

Sometimes, even after unloading the DLL, the thread created inside of BitBlt() remains in memory and causes an Access Violation exception, which in turn leads to application crash. The crash is inconsistent.

Then I tried creating a thread with an empty thread proc, this too led to a crash.

If I don't create a new thread, the crash does not occur.

Is it not safe to create threads inside of a hooked function?

Note : I use SetWindowsHookEx() for DLL injection.

My overall idea is to get some information from a target application to my application. To achieve this, I first load my dll into my application and then use SetWindowsHookEx() to apply a thread specific hook. When my dll gets loaded into target process I perform API hooking as mentioned above.

What I have tried:

I have a way around by using shared memory instead of creating threads . Also I have heard people saying I should be using Trampoline in this scenario but I could not get an example on this even though I have a basic idea of it works. Can someone help me with this problem?
Posted
Updated 11-Oct-17 12:11pm

1 solution

Hi,

That code on wikipedia is poor quality... it doesn't even use the FlushInstructionCache function[^] to avoid a crash or suspend other in-process threads. Yep, that code is designed for a 1 core processor and a single-threaded application. Otherwise the code will cause intermittent crashes.

On a computer with multiple cores... the instructions surrounding BitBlt may be in the L1,L2 or L3 cpu cache...

Also... to avoid race conditions most hook libraries suspend all other threads except itself... then write the trampoline instructions.


Best Wishes,
-David Delaune
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900