TsudaKageyu / minhook

The Minimalistic x86/x64 API Hooking Library for Windows
http://www.codeproject.com/KB/winsdk/LibMinHook.aspx
Other
4.43k stars 897 forks source link

Crash with CloseHandle detour #82

Closed mikkokko closed 5 years ago

mikkokko commented 5 years ago

The crash happens at the original pointer, am i missing something here? Detouring other functions works fine.

typedef BOOL(WINAPI* tCloseHandle)(HANDLE);
tCloseHandle OriginalCloseHandle = NULL;
BOOL DetourCloseHandle(HANDLE hObject)
{
    return OriginalCloseHandle(hObject);
}

BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)
{
    switch (fdwReason)
    {
        case DLL_PROCESS_ATTACH:
        {   
            MH_Initialize();
            MH_CreateHookApiEx(L"kernel32.dll", "CloseHandle", DetourCloseHandle, (LPVOID*)&OriginalCloseHandle, NULL);
            MH_EnableHook(CloseHandle);
Nucleoprotein commented 5 years ago

I think it's loader lock or load order, dont do such things in DllMain... Library functions like CloseHandle can be not loaded yet when you are executing DllMain and pointing to uninitialized memory, but this is little strange because it's kernel32.dll function. Try maybe something like that: MH_CreateHook("CloseHandle", DetourCloseHandle, (LPVOID*)&OriginalCloseHandle) This will not call GetModuleHandleW inside DllMain but use static import from kernel32.dll. DllMain is only useful for Thread Local Storage handling and same very very basic initialization, nothing more, check here: https://docs.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-best-practices With my first contact with creating wrappers for XInput etc. i done same thing and get such strange crashes, then I found a nice way of deferring hooking so it is done later, not in DllMain.

mikkokko commented 5 years ago

@Nucleoprotein Thank you, all good now.