GithubHelp home page GithubHelp logo

tsudakageyu / minhook Goto Github PK

View Code? Open in Web Editor NEW
4.0K 137.0 850.0 343 KB

The Minimalistic x86/x64 API Hooking Library for Windows

Home Page: http://www.codeproject.com/KB/winsdk/LibMinHook.aspx

License: Other

C 92.35% Batchfile 0.32% Makefile 0.93% CMake 6.08% Shell 0.32%

minhook's Introduction

MinHook

License

The Minimalistic x86/x64 API Hooking Library for Windows

http://www.codeproject.com/KB/winsdk/LibMinHook.aspx

Version history

  • v1.3.3 - 8 Jan 2017

    • Added a helper function MH_CreateHookApiEx. (Thanks to asm256)
    • Support Visual Studio 2017 RC.
  • v1.3.2.1 - 9 Nov 2015 (Nuget package only)

    • Fixed an insufficient support for Visual Studio 2015.
  • v1.3.2 - 1 Nov 2015

    • Support Visual Studio 2015.
    • Support MinGW.
  • v1.3.2-beta3 - 21 Jul 2015 (Nuget package only)

    • Support MinGW. (Experimental)
  • v1.3.2-beta2 - 18 May 2015

    • Fixed some subtle bugs. (Thanks to RaMMicHaeL)
    • Added a helper function MH_StatusToString. (Thanks to Jan Klass)
  • v1.3.2-beta - 12 May 2015

    • Fixed a possible thread deadlock in x64 mode. (Thanks to Aleh Kazakevich)
    • Reduced the footprint a little more.
    • Support Visual Studio 2015 RC. (Experimental)
  • v1.3.1.1 - 7 Apr 2015 (Nuget package only)

    • Support for WDK8.0 and 8.1.
  • v1.3.1 - 19 Mar 2015

    • No major changes from v1.3.1-beta.
  • v1.3.1-beta - 11 Mar 2015

    • Added a helper function MH_CreateHookApi. (Thanks to uniskz).
    • Fixed a false memory leak reported by some tools.
    • Fixed a degradated compatibility issue.
  • v1.3 - 13 Sep 2014

    • No major changes from v1.3-beta3.
  • v1.3-beta3 - 31 Jul 2014

    • Fixed some small bugs.
    • Improved the memory management.
  • v1.3-beta2 - 21 Jul 2014

    • Changed the parameters to Windows-friendly types. (void* to LPVOID)
    • Fixed some small bugs.
    • Reorganized the source files.
    • Reduced the footprint a little more.
  • v1.3-beta - 17 Jul 2014

    • Rewrote in plain C to reduce the footprint and memory usage. (suggested by Andrey Unis)
    • Simplified the overall code base to make it more readable and maintainable.
    • Changed the license from 3-clause to 2-clause BSD License.
  • v1.2 - 28 Sep 2013

    • Removed boost dependency (jarredholman).
    • Fixed a small bug in the GetRelativeBranchDestination function (pillbug99).
    • Added the MH_RemoveHook function, which removes a hook created with the MH_CreateHook function.
    • Added the following functions to enable or disable multiple hooks in one go: MH_QueueEnableHook, MH_QueueDisableHook, MH_ApplyQueued. This is the preferred way of handling multiple hooks as every call to MH_EnableHook or MH_DisableHook suspends and resumes all threads.
    • Made the functions MH_EnableHook and MH_DisableHook enable/disable all created hooks when the MH_ALL_HOOKS parameter is passed. This, too, is an efficient way of handling multiple hooks.
    • If the target function is too small to be patched with a jump, MinHook tries to place the jump above the function. If that fails as well, the MH_CreateHook function returns MH_ERROR_UNSUPPORTED_FUNCTION. This fixes an issue of hooking the LoadLibraryExW function on Windows 7 x64 (reported by Obble).
  • v1.1 - 26 Nov 2009

    • Changed the interface to create a hook and a trampoline function in one go to prevent the detour function from being called before the trampoline function is created. (reported by xliqz)
    • Shortened the function names from MinHook_* to MH_* to make them handier.
  • v1.0 - 22 Nov 2009

    • Initial release.

Building MinHook - Using vcpkg

You can download and install MinHook using the vcpkg dependency manager:

git clone https://github.com/microsoft/vcpkg
.\vcpkg\bootstrap-vcpkg.bat
.\vcpkg\vcpkg integrate install
.\vcpkg\vcpkg install minhook

The MinHook port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please create an issue or pull request on the vcpkg repository.

minhook's People

Contributors

0x416c69 avatar aeonlucid avatar apple1417 avatar berserkovich avatar dxgldotorg avatar ifarbod avatar jarredholman avatar kissaki avatar kokoseij avatar lilywangl avatar m417z avatar mixaill avatar poweredbypie avatar skyracer2012 avatar tsudakageyu avatar uniskz avatar yogpstop avatar zlofenix avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

minhook's Issues

HowTo Compile it on Visual Studio 2017 new versions

After Visual Studio 2017 updatet to 15.3, compiling any own project depending on this will fail. The owner of minhook doesn't have any more time for this project, so this is the solution to get your projects working:

  1. Download "Source code (zip)" from https://github.com/TsudaKageyu/minhook/releases

  2. If you don't have VS - download the free Visual Studio 2017 community edition

  3. Unzip the source code and open "build\VC15\MinHookVC15.sln"

  4. on left bottom choose "properties" and double click "libMinHook" on the top

  5. set Window-SDK to newest available and save

  6. same for "MinHook"

  7. Now choose "Release" on top and press F7 (=create project)

  8. If everything worked fine, you will find the needed lib in "build\VC15\lib\Release"

Access Internal Buffer

I was wondering if you can add the ability to access the internal buffer since it's conveniently allocated within the 2GB jump distance of the target. I'm aware that a full malloc like allocator may require major changes and that you hope to keep this library as minimal as possible, it would still be better than nothing to implement a fixed size allocator that can only allocate say MEMORY_SLOT_SIZE bytes at a time.

A lot of errors running a short example

Hello i downloaded and installed minhook with nuget like you can see in the picture:
1

Why these errors?:
2

i am trying to run a short example:

// ConsoleApplication6.cpp : définit le point d'entrée pour l'application console.
//
#include <Windows.h>
#include <MinHook.h>
#include "stdafx.h"


#if defined _M_X64
#pragma comment(lib, "libMinHook.x64.lib")
#elif defined _M_IX86
#pragma comment(lib, "libMinHook.x86.lib")
#endif

typedef int (WINAPI *MESSAGEBOXW)(HWND, LPCWSTR, LPCWSTR, UINT);

// Pointer for calling original MessageBoxW.
MESSAGEBOXW fpMessageBoxW = NULL;

// Detour function which overrides MessageBoxW.
int WINAPI DetourMessageBoxW(HWND hWnd, LPCWSTR lpText, LPCWSTR lpCaption, UINT uType)
{
	return fpMessageBoxW(hWnd, L"Hooked!", lpCaption, uType);
}

int main()
{
	// Initialize MinHook.
	if (MH_Initialize() != MH_OK)
	{
		return 1;
	}

	// Create a hook for MessageBoxW, in disabled state.
	if (MH_CreateHook(&MessageBoxW, &DetourMessageBoxW,
		reinterpret_cast<LPVOID*>(&fpMessageBoxW)) != MH_OK)
	{
		return 1;
	}

	// or you can use the new helper function like this.
	//if (MH_CreateHookApiEx(
	//    L"user32", "MessageBoxW", &DetourMessageBoxW, &fpMessageBoxW) != MH_OK)
	//{
	//    return 1;
	//}

	// Enable the hook for MessageBoxW.
	if (MH_EnableHook(&MessageBoxW) != MH_OK)
	{
		return 1;
	}

	// Expected to tell "Hooked!".
	MessageBoxW(NULL, L"Not hooked...", L"MinHook Sample", MB_OK);

	// Disable the hook for MessageBoxW.
	if (MH_DisableHook(&MessageBoxW) != MH_OK)
	{
		return 1;
	}

	// Expected to tell "Not hooked...".
	MessageBoxW(NULL, L"Not hooked...", L"MinHook Sample", MB_OK);

	// Uninitialize MinHook.
	if (MH_Uninitialize() != MH_OK)
	{
		return 1;
	}

	return 0;
}

But show me a lot of errors?:

Gravité Code Description Projet Fichier Ligne État de la suppression
Erreur C2143 erreur de syntaxe : absence de ')' avant '' ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 14
Erreur C2143 erreur de syntaxe : absence de ';' avant '
' ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 14
Erreur C2059 erreur de syntaxe : ')' ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 14
Erreur C2065 'HWND' : identificateur non déclaré ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 14
Erreur C2065 'LPCWSTR' : identificateur non déclaré ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 14
Erreur C2065 'UINT' : identificateur non déclaré ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 14
Erreur C4430 spécificateur de type manquant - int est pris en compte par défaut. Remarque : C++ ne prend pas en charge int par défaut ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 14
Erreur C2440 'initialisation' : impossible de convertir de 'initializer list' en 'int *' ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 14
Erreur C4430 spécificateur de type manquant - int est pris en compte par défaut. Remarque : C++ ne prend pas en charge int par défaut ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 17
Erreur C2040 'MESSAGEBOXW' : les niveaux d'indirection de 'int' et de 'int *' sont différents ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 17
Erreur C2146 erreur de syntaxe : absence de ';' avant l'identificateur 'fpMessageBoxW' ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 17
Erreur C2377 'WINAPI' : redéfinition ; un typedef ne peut pas être surchargé avec un autre symbole ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 20
Erreur C2146 erreur de syntaxe : absence de ';' avant l'identificateur 'DetourMessageBoxW' ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 20
Erreur C2065 'HWND' : identificateur non déclaré ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 20
Erreur C2146 erreur de syntaxe : absence de ')' avant l'identificateur 'hWnd' ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 20
Erreur C2143 erreur de syntaxe : absence de ';' avant '{' ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 21
Erreur C2447 '{' : en-tête de fonction manquant (liste formelle à l'ancien format ?) ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 21
Erreur C3861 'MH_Initialize' : identificateur introuvable ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 28
Erreur C2065 'MH_OK' : identificateur non déclaré ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 28
Erreur C2065 'MessageBoxW' : identificateur non déclaré ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 34
Erreur C2065 'DetourMessageBoxW' : identificateur non déclaré ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 34
Erreur C2061 erreur de syntaxe : identificateur 'LPVOID' ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 35
Erreur C2143 erreur de syntaxe : absence de ';' avant '{' ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 36
Erreur C2065 'MessageBoxW' : identificateur non déclaré ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 48
Erreur C3861 'MH_EnableHook' : identificateur introuvable ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 48
Erreur C2065 'MH_OK' : identificateur non déclaré ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 48
Erreur C2065 'MB_OK' : identificateur non déclaré ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 54
Erreur C3861 'MessageBoxW' : identificateur introuvable ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 54
Erreur C2065 'MessageBoxW' : identificateur non déclaré ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 57
Erreur C3861 'MH_DisableHook' : identificateur introuvable ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 57
Erreur C2065 'MH_OK' : identificateur non déclaré ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 57
Erreur C2065 'MB_OK' : identificateur non déclaré ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 63
Erreur C3861 'MessageBoxW' : identificateur introuvable ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 63
Erreur C3861 'MH_Uninitialize' : identificateur introuvable ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 66
Erreur C2065 'MH_OK' : identificateur non déclaré ConsoleApplication6 c:\users\androide\documents\visual studio 2015\projects\consoleapplication6\consoleapplication6\consoleapplication6.cpp 66

Multiple Hooks On Different Api Results In Crash

Doing more than 2 api hooks on NT functions seem to crash the program, any idea?
Also 0 errors, all hooks say they are placed fine.

if (MH_Initialize() != MH_OK)
{
	OutputDebugString("FAILED INIT");
	return;
}

if (MH_CreateHook(&NtDeviceIoControlFile, &NewNtDeviceIoControlFile, reinterpret_cast<LPVOID*>(&OldNtDeviceIoControlFile)) != MH_OK)
{
	OutputDebugString("FAILED HOOKING");
	return;
}
OutputDebugString("NtDeviceIoControlFile Hooked");

if (MH_CreateHook(&NtQueryInformationFile, &NewNtQueryInformationFile, reinterpret_cast<LPVOID*>(&OldNtQueryInformationFile)) != MH_OK)
{
	OutputDebugString("FAILED HOOKING");
	return;
}
OutputDebugString("NtQueryInformationFile Hooked");

if (MH_CreateHook(&NtQueryDirectoryFile, &NewNtQueryDirectoryFile, reinterpret_cast<LPVOID*>(&OldNtQueryDirectoryFile)) != MH_OK)
{
	OutputDebugString("FAILED HOOKING");
	return;
}
OutputDebugString("NtQueryDirectoryFile Hooked");

if (MH_CreateHook(&NtQueryObject, &NewNtQueryObject, reinterpret_cast<LPVOID*>(&OldNtQueryObject)) != MH_OK)
{
	OutputDebugString("FAILED HOOKING");
	return;
}
OutputDebugString("NtQueryDirectoryFile Hooked");

if (MH_EnableHook(MH_ALL_HOOKS) != MH_OK)
{
	OutputDebugString("FAILED ENABLE");
	return;
}

Linux is case sensitive

To cross compile on linux, you have to change in src/trampoline.c :

include "./hde/hde32.h" to #include "./HDE/hde32.h"

and

include "./hde/hde64.h" to #include "./HDE/hde64.h"

(VisualStudio 15/17) dllimport, calls are not resolved correctly

Minhook correctly patches the location of a call to a function, Foo, when you get it using GetProcAddress, but if functions are dllimport'ed and called from your code the compiler will have inserted an indirect call directly to the "__imp_Foo" location, bypassing the trampolined section.
I haven't traced through the guts of Minhook to completely understand how it decides where to patch, but from what I could see it appears not to traverse the initial jmp, to patch the actual target. Is that intentional?

I just want to make sure I'm not misunderstanding how to use Minhook here, so here's an example, with a "fix", which is an extended version of GetProcAddress, that will traverse an indirect jmp to the actual target location, before hooking it, to demonstrate that the hooking then works.

#include <windows.h>
#include "minhook-1.3.3/include/MinHook.h"

typedef BOOL(WINAPI *ExtTextOutAProcA)(HDC hdc, int X, int Y, UINT fuOptions, const RECT *lprc, LPCTSTR lpString, UINT cbCount, const INT *lpDx);

BOOL WINAPI ExtTextOutAProcAHooked(HDC hdc, int X, int Y, UINT fuOptions, const RECT *lprc, LPCTSTR lpString, UINT cbCount, const INT *lpDx)
{
 // set a breakpoint here!
    return FALSE;
}

FARPROC GetProcAddressEx(HINSTANCE module, LPCSTR name)
{
    auto org = GetProcAddress(module, name);
    if(!org)
        return org;

    auto                 target  = reinterpret_cast<const uint8_t *>(org);
    static const uint8_t jmprm[] = { 0xff, 0x25 };
    if(!memcmp(target, jmprm, sizeof(jmprm)))
    {
        // address of target is at offset
#ifdef _M_X64
        // jmp + RIP relative offset to target address
        auto jmptarget = *reinterpret_cast<const uint64_t *>(uintptr_t(target) + 6 +
                                                             *reinterpret_cast<const uint32_t *>(target + 2));
#else
        // jmp + absolute offset to target address
        auto jmptarget = *reinterpret_cast<const uint32_t *>(*reinterpret_cast<const uint32_t *>(target + 2));
#endif
        org = FARPROC(jmptarget);
    }
    return org;
}

int main()
{
    auto gdi32full = LoadLibraryA("gdi32full.dll");
    //WORKS:
    auto proc = reinterpret_cast<ExtTextOutAProcA>(GetProcAddressEx(gdi32full, "ExtTextOutA"));
    //doesn't work... auto proc = reinterpret_cast<ExtTextOutAProcA>(GetProcAddress(gdi32full, "ExtTextOutA"));

    MH_Initialize();
    MH_CreateHook(reinterpret_cast<LPVOID>(proc), reinterpret_cast<const LPVOID>(ExtTextOutAProcAHooked), nullptr);
    MH_EnableHook(MH_ALL_HOOKS);
    ExtTextOutA(nullptr, 0, 0, 0, nullptr, "foo", 0, nullptr);
    MH_Uninitialize();
    ExtTextOutA(nullptr, 0, 0, 0, nullptr, "foo", 0, nullptr);
    return 0;
}```

ARM64 support

I was wondering if there are any plans to support ARM? This might be of general interest, in particular for the upcoming Windows 10 ARM release.

Possible memory leak

Hello,

I'm x360ce dev, and I found out that something is leaking memory in x360ce and it seems it's related to MinHook. I used Visual Leak Detector (https://vld.codeplex.com) to detect that leak:

WARNING: Visual Leak Detector detected memory leaks!
---------- Block 1136 at 0x02E105B8: 1280 bytes ----------
Leak Hash: 0x80F207D5, Count: 1, Total 1280 bytes
Call Stack (TID 5308):
0x778B1520 (File and line number not available): ntdll.dll!RtlAllocateHeap
f:\builds[working_copy]\x360ce\x360ce\3rdparty\libminhook\src\hook.c (120): XINPUT1_3.dll!NewHookEntry + 0x19 bytes
f:\builds[working_copy]\x360ce\x360ce\3rdparty\libminhook\src\hook.c (526): XINPUT1_3.dll!MH_CreateHook + 0x5 bytes
f:\builds[working_copy]\x360ce\x360ce\inputhook\inputhook.h (29): XINPUT1_3.dll!IH_CreateHookF<long (__stdcall*)(_GUID const &,IUnknown *,unsigned long,_GUID const &,void * *)> + 0x11 bytes
f:\builds[working_copy]\x360ce\x360ce\inputhook\hookcom.cpp (360): XINPUT1_3.dll!InputHook::HookCOM + 0x1A bytes
f:\builds[working_copy]\x360ce\x360ce\inputhook\inputhook.cpp (164): XINPUT1_3.dll!InputHook::InputHook
f:\builds[working_copy]\x360ce\x360ce\x360ce\inputhookmanager.h (9): XINPUT1_3.dll!InputHookManager::InputHookManager + 0x33 bytes
f:\builds[working_copy]\x360ce\x360ce\x360ce\inputhookmanager.h (14): XINPUT1_3.dll!InputHookManager::Get + 0x34 bytes
f:\builds[working_copy]\x360ce\x360ce\x360ce\dllmain.cpp (24): XINPUT1_3.dll!InitInstance
f:\builds[working_copy]\x360ce\x360ce\x360ce\dllmain.cpp (52): XINPUT1_3.dll!DllMain
f:\dd\vctools\crt\crtw32\dllstuff\crtdll.c (508): XINPUT1_3.dll!__DllMainCRTStartup + 0x11 bytes
f:\dd\vctools\crt\crtw32\dllstuff\crtdll.c (472): XINPUT1_3.dll!_DllMainCRTStartup + 0x11 bytes
0x778B9EA6 (File and line number not available): ntdll.dll!RtlInitializeCriticalSection + 0x126 bytes
0x778B9E22 (File and line number not available): ntdll.dll!RtlInitializeCriticalSection + 0xA2 bytes
0x778C8505 (File and line number not available): ntdll.dll!RtlIsCriticalSectionLockedByThread + 0x2A5 bytes
0x778C844D (File and line number not available): ntdll.dll!RtlIsCriticalSectionLockedByThread + 0x1ED bytes
0x778CC115 (File and line number not available): ntdll.dll!RtlGetVersion + 0x7C5 bytes
0x778CE889 (File and line number not available): ntdll.dll!RtlInitializeHandleTable + 0xE89 bytes
0x778CDA45 (File and line number not available): ntdll.dll!RtlInitializeHandleTable + 0x45 bytes
0x778CB5B0 (File and line number not available): ntdll.dll!LdrInitializeThunk + 0x10 bytes
Data:
90 05 24 76 5D C7 13 0F E0 0F 21 76 8B FF 55 8B ..$v]... ..!v..U.
EC F0 AD BA 20 F0 AD BA 00 02 03 05 CC CC CC CC ........ ........
00 02 03 05 CC CC CC CC 20 62 25 76 75 D7 13 0F ........ .b%vu...
C0 0F 21 76 8B FF 55 8B EC F0 AD BA 20 F0 AD BA ..!v..U. ........
00 02 03 05 CC CC CC CC 00 02 03 05 CC CC CC CC ........ ........
00 AB 26 76 A7 D2 13 0F A0 0F 21 76 8B FF 55 8B ..&v.... ..!v..U.
EC F0 AD BA 20 F0 AD BA 00 02 03 05 CC CC CC CC ........ ........
00 02 03 05 CC CC CC CC 90 B8 22 76 A4 DF 13 0F ........ .."v....
80 0F 21 76 8B FF 55 8B EC F0 AD BA 20 F0 AD BA ..!v..U. ........
00 02 03 05 CC CC CC CC 00 02 03 05 CC CC CC CC ........ ........
5A DE 13 0F 64 DE 13 0F 60 0F 21 76 E9 FF EA 01 Z...d... `.!v....
00 F0 AD BA 08 F0 AD BA 00 CC CC CC CC CC CC CC ........ ........
00 CC CC CC CC CC CC CC 00 17 51 71 DB C1 13 0F ........ ..Qq....
40 0F 21 76 8B FF 55 8B EC F0 AD BA 20 F0 AD BA @.!v..U. ........
00 02 03 05 CC CC CC CC 00 02 03 05 CC CC CC CC ........ ........
40 E0 18 6C 23 CA 13 0F 20 0F 21 76 6A 0C B8 AC @..l#... ..!vj...

Visual Leak Detector detected 1 memory leak in heap 0x02E10000

That is detected after call to MH_Uninitialize().
I already do a quick look and it seems that you initialize heap memory using HeapAlloc in NewHookEntry (g_hooks.pItems) but not freeing it on MH_Uninitialize(). Or maybe I need to remove all hooks before calling MH_Uninitialize() (but this will be stupid because I need to disable all hooks before and this is already done in MH_Uninitialize())?

PS: HeapDestroy will NOT free all memory for you.

MH_CreateHook - pTarget - parameter query

Needs pTarget in MH_CreateHook point to function (address where code execution appeared after "jump" or "call") or it can be some random address in code/text segment of process memory?

My guess is that it can not be cause Detour could mess up some registers which are in use. But thanks to my very noobish knowledge of Assembly I can not say if your code handle this or not :D

Missing __movsb symbol with MSVC

I'm trying to build minhook (8fda4f5) with my project under MSVC compiler, unfortunately the compiler compain that __movsb is undefined.

FAILED: content.dll content.dll.lib content.dll.pdb
ninja -t msvc -e environment.x64 -- ../../third_party/llvm-build/Release+Asserts/bin/lld-link.exe /nologo /IMPLIB:./content.dll.lib /DLL /OUT:./content.dll /PDB:./content.dll.pdb @./content.dll.rsp
lld-link: error: undefined symbol: __movsb
>>> referenced by F:\halton_work\redcore_70\src\third_party\minhook\src\trampoline.c:154
>>>               obj/content/common/common/trampoline.obj:(CreateTrampolineFunction)
>>> referenced by F:\halton_work\redcore_70\src\third_party\minhook\src\trampoline.c:279
>>>               obj/content/common/common/trampoline.obj:(CreateTrampolineFunction)
ninja: build stopped: subcommand failed.

In some cases the MH_CreateHookApi is useless.

example

MH_CreateHookApi(L"user32.dll" , "CreateWindowExW",fuga,&org_fuga);
MH_CreateHookApi(L"kernelbase.dll" , "LoadLibraryExW",hoge,&org_hoge);
// Only All Enable , because I dont have pTarget.
MH_EnableHook(MH_ALL_HOOKS);
// but I want "CreateWindowExW" be still disable.

My suggestion

MH_STATUS WINAPI MH_CreateHookApiEx(LPCWSTR pszModule,
    LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal,BOOL bQueue)
{
  HMODULE hModule;
  LPVOID pTarget;
  MH_STATUS err;
  hModule = GetModuleHandleW(pszModule);
  if (hModule == NULL)
    return MH_ERROR_MODULE_NOT_FOUND;
  pTarget = (LPVOID)GetProcAddress(hModule, pszProcName);
  if (pTarget == NULL)
    return MH_ERROR_FUNCTION_NOT_FOUND;
  err = MH_CreateHook(pTarget, pDetour, ppOriginal);
  if (err == MH_OK && bQueue)
    err = MH_QueueEnableHook(pTarget);
  return err;
}
MH_CreateHookApiEx(L"user32.dll" , "CreateWindowExW",fuga,&org_fuga,FALSE);
MH_CreateHookApiEx(L"kernelbase.dll" , "LoadLibraryExW",hoge,&org_hoge,TRUE);
MH_ApplyQueued();

Minor performance increase, cache misalignment with MEMORY_BLOCK

Not a breaking problem, but I noticed the MEMORY_BLOCK struct is not even half cache (16 byte) aligned.
If you at minimal align 16 it (make the header size % 16 = 0), then you will guarantee each allocation block (used by trampolines) to be at minimal align 16 as well.

Notice that Window compile/linker tools like MSVC align functions to at least align 16 by default (padding with 0xCC or 0x90 as you know). You can see for your self in a debugger or using a dissembler like IDA Pro.

Maybe less of an performance gain on current generation CPUs but the last time I did profiling (admittedly a long time ago) the difference was just a handful of cycles for aligned vs over a hundred cycles for misaligned branch targets!

Also when it comes to math calculating a block slot address, it's a simple power of 2 for aligned vs the instructions need to multiply or divide the odd sizes of 12 or 18 bytes (for 32bit and 64bit mode respectively).

You can either just add adding compile switch padding (4 bytes for 32bit mode to round to 16, or 14 to round up to 32bytes for 64bit mode), or use a compiler specific construct that will automatically pad the structure length for you.

Note also in either case of fixing the alignment you don't even loose a slot. I.E. 4096-16/32 = 127 slots regardless if size(MEMORY_BLOCK) is 12 or 16 bytes (for 32bit mode example).

How to build as a static lib not dll

I want to build MinHook as a static lib that I can link to without having to have the dll beside my program
My program is built with /MT runtime and doesn't use any dlls and I don't want to use MinHook as a dll

Not able to hook undocumented functions

With minhook, I am not able to hook Undocumented functions. When will this be fixed?
I was trying Mhook for x64 but it is riddled with bugs (outdated) and minhook is my last option.
I've successfully hooked TerminateProcess but NtTerminateProcess isn't working.

VS12 libMinHook project always rebuilds

Take me awhile to debug why libMinHook project always rebuilds -extreme painful when you run debug. Root cause is VS2013 stupidity - when you set Debug Information Format to None then PDB file is not created in output directory, and it cause missing output ... :

32  1635.171124 6864    devenv.exe  CPS Verbose: 0 :
33  1635.171182 6864    devenv.exe  Project 'E:\SourceTree\x360ce\MinHook\build\VC12\libMinHook.vcxproj' not up to date because 1 build outputs were missing.
34  1635.171250 6864    devenv.exe  CPS Verbose: 0 :
35  1635.171285 6864    devenv.exe  up to date is missing: 'E:\SOURCETREE\X360CE\MINHOOK\BUILD\VC12\WIN32\RELEASE\LIBMINHOOK\VC120.PDB'

Solution is to delete Program Database File Name in Output Files (which is set to default value of "$(IntDir)vc$(PlatformToolsetVersion).pdb") or change Debug Information Format.

NuGet package doesn't work after updating to Visual Studio 2017 15.3

Updated to the latest Visual Studio 2017 release today, and now whenever I try to build my project in Release configuration, I get the following link error:

LINK : fatal error C1047: The object or library file 'C:\Users\Anton\git\app\packages\minhook.1.3.3\build\native\..\..\lib\native\lib\libMinHook.lib' was created with an older compiler than other objects; rebuild old objects and libraries

It worked perfectly well on the previous vs2017 release.

After quick googling, seems like other projects have encountered a similar issue: zeux/pugixml#157 and the problem seems to be in LTCG which is enabled by default in Release and affects the ability to link libraries built with different Visual C++ toolset versions.

hook free in debug mode failed

I try to hook "malloc" and "free" in my project. However, I find that "free" can only be hooked in release mode, while "malloc" can be hooked in bose debug and release mode. Here is my code:

#include "MinHook.h"
#include<iostream>
typedef void * (__cdecl *PtrMalloc)(size_t);
typedef void(__cdecl *PtrFree)(void *);





PtrMalloc orgi_malloc;
PtrFree orgi_free;
int inter_a, inter_b;
void *my_malloc(size_t size)
{
	inter_a++;
	return orgi_malloc(size);
}

void my_free(void*p)
{
	inter_b++;
	orgi_free(p);
	return;
}



int main()
{
	MH_Initialize();
	MH_CreateHook(&malloc, my_malloc, (void**)&orgi_malloc);
	MH_CreateHook(&free, my_free, (void**)&orgi_free);
	MH_EnableHook(&free);
	MH_EnableHook(&malloc);
	int *a = new int[1000];
	delete[]a;
	a = new int[100];
	delete[]a;
	inter_a;
	inter_b;
	return 0;
}

I wish you can help me, thank you!

Possible bug on x64?

Hi.

I guess there is a small bug when compiling for x64?

On this line in trampoline.c

if (oldPos >= sizeof(JMP_REL))

JMP_REL

Will always have the sizeof == 5.
But on x64 this size should be 14.

Am I wrong on this?
Did I miss something?

Hook works at startup, but stop working soon

Hi

I inject my DLL into a process using AppInit_DLLs registry key.
I use GetModuleFileNameW() and hardcoded process name to ignore others processes.

In minimal test I successfully hook CloseHandle() function.


typedef BOOL(WINAPI *CLOSE_HANDLE)(HANDLE);
CLOSE_HANDLE CloseHandleTrampoline = CloseHandle;
BOOL WINAPI CloseHandleHooked(
	_In_ HANDLE hObject
)
{
	LONG c = InterlockedIncrement(&counter);
        Log(L"CloseHandle counter: %d\n", (int)counter);
	return CloseHandleTrampoline(hObject);
}

...
void HookInit()
{
       // checking process names
       ...

	if (MH_Initialize() != MH_OK)
	{
		Log(L"MH_Initialize() fails\n");
		return;
	}
	if (MH_CreateHookApiEx(L"kernel32", "CloseHandle", &CloseHandleHooked, &CloseHandleTrampoline) != MH_OK)
            
	{
		Log(L"MH_CreateHookApiEx() fails for CloseHandle\n");
	}
	if (MH_EnableHook(MH_ALL_HOOKS) != MH_OK)
	{
		Log(L"MH_EnableHook(MH_ALL_HOOKS) fail\n");
	}
       Log(L"32 bit process hooked [%lu]\n",  GetCurrentProcessId());
}

My Log() function just open a file, write and close, uses CloseHandleTrampoline() to avoid infinity recursion.

When I start my process I see some CloseHandle() logs but after a second I don't see such logs and I'm sure that my test and production programs do call CloseHandle() during this time .

The hook DLL is still loading in address space of my process, but the behaviour looks like original state of kernel21.dll was restored.
I can repeat on 2 different computes:

  • Windows 8.1 desktop - my home dev PC
  • Windows Server 2008 R2 Enterprise - test server in the cloud

Does somebody have an idea or any clue how to debug/solve this problem?

version mingw errors undefined

Hello i got undefined errors when i add linking files.
So The errors are:

C:\Users\Androide\Desktop\minhook\Dynamic>g++ -o bot.exe Dynamic.o hook.o hde32.
o buffer.o trampoline.o
hook.o:hook.c:(.text+0x60b): undefined reference to `OpenThread'
hook.o:hook.c:(.text+0x69d): undefined reference to `OpenThread'
hook.o:hook.c:(.text+0xa2c): undefined reference to `InitializeBuffer'
hook.o:hook.c:(.text+0xa7d): undefined reference to `UninitializeBuffer'
hook.o:hook.c:(.text+0xb14): undefined reference to `IsExecutableAddress'
hook.o:hook.c:(.text+0xb27): undefined reference to `IsExecutableAddress'
hook.o:hook.c:(.text+0xb52): undefined reference to `AllocateBuffer'
hook.o:hook.c:(.text+0xb7c): undefined reference to `CreateTrampolineFunction'
hook.o:hook.c:(.text+0xca0): undefined reference to `FreeBuffer'
hook.o:hook.c:(.text+0xd82): undefined reference to `FreeBuffer'
C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/mingw32/4.9.2/../../../../mingw
32/bin/ld.exe: hook.o: bad reloc address 0x13c in section `.rdata'
C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/mingw32/4.9.2/../../../../mingw
32/bin/ld.exe: final link failed: Invalid operation
collect2.exe: error: ld returned 1 exit status

I added hook.c library to linking but return all these errors...

automatically hook functions when dlls load

hello,

Now, MH_CreateHookApi cannot support this role. If GetModuleHandleW returns NULL, MH_CreateHookApi also returns MH_ERROR_MODULE_NOT_FOUND error.

when dlls load, I want to hook automatically detour functions already registered.

Do you have a plan to support this?

call function instead of jumping to it?

Why can I only do a jump to the *ppOriginal address returned MH_CreateHook()? Doing a call from C++ or assembly does not work, for some reason I have to use a jmp instruction for it to work...?

Unable to change toolset from v140_xp to v140

Hello TsudaKageyu,

I'm trying to build minhook for v140 however it seems impossible to change the projects to this configuration. Target Platform and Target Platform Version in config shows blank in my VS. Please take a look at it when you can.

Regards.
Isaac Lascasas.

Present hook

This might not even be MinHook related, but I'm attempting to do basic drawings with a d3d11 present hook using ID3D11SwapChain as seen here:

if (MH_Initialize() != MH_OK) { return 1; }

if (MH_CreateHook((DWORD_PTR*)pSwapChainVTable[8], PresentHook, reinterpret_cast<void**>(&phookD3D11Present)) != MH_OK) { return 1; }
if (MH_EnableHook((DWORD_PTR*)pSwapChainVTable[8]) != MH_OK) { return 1; }
D3D11_HOOK_API void ImplHookDX11_Present(ID3D11Device* device, ID3D11DeviceContext* ctx, IDXGISwapChain* swap_chain)
{
	renderer->BeginScene();

	renderer->DrawHealthBar(50, 50, 100, 50, 100);

	renderer->EndScene();
}

HRESULT __stdcall PresentHook(IDXGISwapChain* pSwapChain, UINT SyncInterval, UINT Flags)
{
	std::call_once(g_isInitialized, [&]() {
		pSwapChain->GetDevice(__uuidof(g_pd3dDevice), reinterpret_cast<void**>(&g_pd3dDevice));
		g_pd3dDevice->GetImmediateContext(&g_pd3dContext);

		renderer = new D3D11Renderer(pSwapChain);
		renderer->Initialize();
		});

	ImplHookDX11_Present(g_pd3dDevice, g_pd3dContext, g_pSwapChain);

	return phookD3D11Present(pSwapChain, SyncInterval, Flags);
}

Result:
video of issue

Issue:
The issue is that the drawings shortly appears but quickly disappears, does anyone know what the reason of this could be?

Expected result:
I'm expecting the render to stay on screen without going away after half a second

__try/__finally can cause a deadlock in x64 mode.

Hi ! I found a bug in MinHook (hook.c).

Problem

In x64 mode, the __try/__finally blocks between the Freeze() and Unfreeze() calls
can cause a deadlock if other thread was frozen inside the LoadLibrary or FreeLibrary.

Description

Internally, x64 stack unwinding (RtlUnwindEx -> RtlLookupFunctionTable) and
loading/unloading a dll (LdrLoadDll/LdrUnloadDll) are using the same synchronization
lock in the ntdll.dll (RTL_SRWLOCK ntdll!LdrpInvertedFunctionTable). If the thread
was frozen while holding the lock then no other thread can perform stack unwinding
or load/unload dll. This cause a deadlock.

Example call stacks

Thread-1 (main):

    nt!KiSwapContext+0x7a
    nt!KiCommitThreadWait+0x1d2
    nt!KeWaitForSingleObject+0x19f
    nt!NtWaitForKeyedEvent+0x15a
    nt!KiSystemServiceCopyEnd+0x13
    ntdll!NtWaitForKeyedEvent+0xa           3. Try to acquire lock = DEADLOCK !
    ntdll! ?? ::FNODOBFM::`string'+0x95b7
    ntdll!RtlLookupFunctionTable+0x3b
    ntdll!RtlLookupFunctionEntry+0x31
    ntdll!RtlUnwindEx+0xd7
    kernel32!RtlUnwindExStub+0x1e
    MinHookDeadlock!_local_unwind+0x1c      2. Begin unwinding the stack.
    MinHookDeadlock!EnableHook+0x144        1. Setting the hook (see hook.c, line 664).
    MinHookDeadlock!main+0xa3
    MinHookDeadlock!__tmainCRTStartup+0x144
    kernel32!BaseThreadInitThunk+0xd
    ntdll!RtlUserThreadStart+0x1d

Thread-2 (worker):

    nt!KiSwapContext+0x7a
    nt!KiCommitThreadWait+0x1d2
    nt!KeWaitForSingleObject+0x19f
    nt!KiSuspendThread+0x54                     3. Somebody was called Freeze().
    nt!KiDeliverApc+0x201
    nt!KiApcInterrupt+0xd7
    ntdll!RtlAcquireSRWLockExclusive+0x19       2. Acquiring the lock.
    ntdll!RtlInsertInvertedFunctionTable+0x20
    ntdll!LdrpFindOrMapDll+0x738
    ntdll!LdrpLoadDll+0x148
    ntdll!LdrLoadDll+0x9a
    KERNELBASE!LoadLibraryExW+0x19c             1. Loading the dll.
    MinHookDeadlock!ThreadProc+0x1d
    MinHookDeadlock!_callthreadstartex+0x17
    MinHookDeadlock!_threadstartex+0x102
    kernel32!BaseThreadInitThunk+0xd
    ntdll!RtlUserThreadStart+0x1d

Example

I have an example source code and compiled exe (VS2013 update 4,
tested on Windows 7 64-bit):

https://drive.google.com/file/d/0B3wmqwvKYtEUYm5UbkRjencydmc/view?usp=sharing

Note that is not easy to reproduce this bug and you may need much time.

Solution

Remove all __try/__finally blocks from hook.c.

DLL Builds VS2017 & codeproject

  1. Can you please release compiled binaries on github.

  2. CodeProject download links are all broken.

  3. Nuget wont install on VS2017 .Net 4.6.2

Support for languages other than C/C++

Hi, I came across this library about couple days ago. It's great, and I thought it could be even better if there are supports for languages other than C/C++. So I just wrote my extremely simple Go (Golang) version of minhook while trying to figure out how to utilize it in Go. I think it might be a good example for how this library can be used in different languages. If anyone's interested, please visit https://github.com/NaniteFactory/gominhook. Any issues or suggestions are welcome. xD

Defines

Can you add checks for x32 and x64 builds? Because cotire unity build makes all as one file and defines for x32 and x64 in table*.h redefines each other.

has issues when hooking unidentified byts

there is my project code
`
PVOID g_adr_func = nullptr;
int Detour_test()
{
return reinterpret_cast<int (__stdcall*) ()>(g_adr_func)();
}

int main()
{
MH_STATUS status = MH_UNKNOWN;
status = MH_Initialize();
if (MH_OK != status)
{
std::cout << "Initlize faild" << std::endl;
return 0;
}

PVOID adr_func = VirtualAlloc(NULL, 0x1000, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (!adr_func)
{
	std::cout << "allcate faild" << std::endl;
	return 0;
}
std::cout << std::hex << adr_func << std::endl;
uint8_t byts[] = {0xE8, 0xE8, 0x56, 0xFB, 0x60, 0xFE, 0xFF, 0xFF, 0x8B, 0x4D, 0x08, 0x8B, 0xD0};
memcpy(adr_func, byts, sizeof(byts));
g_adr_func = adr_func;


status = MH_CreateHook(adr_func, Detour_test, NULL);
if (status != MH_OK)
{
	std::cout << "CreateHook faild" << std::endl;
	goto out_exit;
}


out_exit:
if (adr_func)
	VirtualFree(adr_func, 0, MEM_RELEASE);


std::cin.ignore();

}
`

its createhook unsucessfully.
because of the unidentified btys after {0xE8, 0xE8, 0x56, 0xFB, 0x60}
its need to fix,its sure that call{0xe8} is 5 bytes

Question about multihooking

Hello,

my knowledge is not sufficient enough to understand the intrinsics of the library itself, but I want to provide something like multiple hooking support. I'm aware that there is a fork doing that for the price of few features, but reading across the internet I started to believe that if the control is in single hands it may be possible to reorder properly the hooks. Hence, my question is does the proper chain of first-in, last-out has to be kept with regard the creation of a hook, or only for enable/disable? Or for both? Or not possible at all in this repo?

Thank you!

Windows 7

Create Hook is failing on windows 7 with MH_ERROR_MEMORY_ALLOC

Any Idea how to resolve this? Its contained a injected DLL. It works fine on Windows 10

Compatibility with Microsoft's new "ProcessDynamicCodePolicy"

In Windows 10 Windows 8, Microsoft introduced ProcessDynamicCodePolicy, a new security feature that forbids allocating or protecting dynamically allocated memory with PAGE_EXECUTE_READWRITE or any execution permission. It breaks MinHook, because it allocates virtual memory with that protection.

MH_CreateHook() returns MH_ERROR_MEMORY_ALLOC, and the exact error is:

#define STATUS_DYNAMIC_CODE_BLOCKED 0xC0000604

Steps to reproduce the error:

Inject something that uses MinHook into Microsoft Edge's content process ( MicrosoftEdgeCP.exe ) or any other process that uses "Dynamic code prohibited" policy.

Here's a screenshot of the process' information:

http://prntscr.com/e3wekq


I'm not familiar with the way MinHook handles memory, but I guess that it could simply allocate memory with PAGE_READWRITE protection and set it to PAGE_EXECUTE_READ when a hook is created using that memory piece.

Donation link invalid

Hey hey!

You might already be aware of that but the donation link is invalid due to the service behind shutting down. As I'd like to throw a few bucks at this great project please consider moving to e.g. Patreon, GoFundMe, PayPal or whatever pleases you, thanks!

Hook fails in certain condition

I'm hooking a virtual function like this :
MH_CreateHook(myTarget, &myHook, reinterpret_cast<void**>( &myOriginal ) )
myTarget is a virtual function I got in a vtable.
If I hook a function in the same vtable that returns the same thing (for exemple myTarget just returns true, and another function in the same vtable also return only true, it will not hook the second one because MinHook thinks it is the same function :
image

but works if I remove one of the two functions that returns the same in the same vtable :
image

Sorry for my bad english :)

MH_CreateHook always return MH_ERROR_NOT_EXECUTABLE

Hi,

I just tried following code but it always return MH_ERROR_NOT_EXECUTABLE.

    LPVOID targ = GetProcAddress(LoadLibraryA("kernel32.dll"), "OpenProcess");
    MH_STATUS sts = MH_CreateHook(&targ, &hook_OpenProcess, reinterpret_cast<LPVOID*>(&hooked_OpenProcess));
    if (sts != MH_OK)
    {
        WTL(MH_StatusToString(sts));
        return 0;
    }

    if (MH_EnableHook(&targ) != MH_OK)
    {
        return 0;
    }

Used on x64 module... Following code worked fine:

    MH_STATUS sts = MH_CreateHook(&OpenProcess, &hook_OpenProcess, reinterpret_cast<LPVOID*>(&hooked_OpenProcess));
    if (sts != MH_OK)
    {
        WTL(MH_StatusToString(sts));
        return 0;
    }

    if (MH_EnableHook(&OpenProcess) != MH_OK)
    {
        return 0;
    }

But why?
Compiled with VS2015 Update 1.

MinGW build generates wrong code

Due to the usage of bitfields in the HOOK_ENTRY struct (hook.c), the -funsigned-bitfields flag need to be passed to the gcc compiler. If this flag is not passed, the generated code is wrong.

To fix the issue, change the line in the MinGW makefile:
CFLAGS:=-masm=intel -Wall -Werror -std=c11
to
CFLAGS:=-masm=intel -Wall -Werror -std=c11 -funsigned-bitfields

EDIT:
and of course the flag needs to be added to the make.bat file as well, I forgot about that.

Crash with CloseHandle detour

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);

detours vs minhook

Hi,

I have created a c++ complete project to hook GOG game and work perfectly (this add a unofficial Force Feedback support).

To to it I have found on github a custom version of d3d9.dll with with DllMain inside.

I have put in my code with detours with succefull hook the game without any problems.

Now I have used the some project to another GOG game but this time becouse there is no d3d9.dll inside I have used another github dll libogg.dll.

libogg don't have DllMain I have added it myself and my log confirm that both DLL_PROCESS_ATTACH and DLL_PROCESS_DETACH was called correcly.

Unfortunatenly I have many ussue to to hook, many times the app crash in "DetourAttach" and when work (random) the hook don't seem work correcly.

I have do the some with zlib with the some result.

At the moment I don't have a prcise idea about why this happen.

Do you think it is a good idea switch to minhook ? Or my attemp is wrong ?

Sometimes, GetMemoryBlock returns NULL

I got a bug report from a user, and after some investigation, it turned out that the GetMemoryBlock function returns NULL for one of the functions on his machine. That means that MinHook could not find a memory block near the origin function (± 16MB).

Before I dive to the code and try to implement a solution, I have a couple of questions:

  • Why is MAX_MEMORY_RANGE defined as 0x02000000? Why not something along the lines of 0x80000000, which is the range of the long jump?
  • Why is the scan for a new block implemented this way? Why scan for every 0x1000-th address instead of using VirtualQuery? Why is 0x1000 hardcoded, isn't it more correct to use the system allocation granularity?

P.S. another thing that I've stumbled upon and I want to ask: does the 64-bit relay have a purpose, or is it a historical leftover? As far as I see, just the trampoline can be used instead, but perhaps I'm missing something.

Warning: /LTCG specified but no code generation required

When built with Visual Studio 2013 (VC12), the following warning is displayed:

LINK : /LTCG specified but no code generation required; remove /LTCG from the link command line to improve linker performance

Full log:

1>------ Build started: Project: libMinHook, Configuration: Release Win32 ------
1>  buffer.c
1>  hde32.c
1>  hook.c
1>  trampoline.c
1>  Generating Code...
1>  libMinHook.vcxproj -> C:\minhook\build\VC12\lib\Release\libMinHook.x86.lib
2>------ Build started: Project: MinHook, Configuration: Release Win32 ------
2>     Creating library C:\minhook\build\VC12\bin\Release\MinHook.x86.lib and object C:\minhook\build\VC12\bin\Release\MinHook.x86.exp
2>  LINK : /LTCG specified but no code generation required; remove /LTCG from the link command line to improve linker performance
2>  MinHook.vcxproj -> C:\minhook\build\VC12\bin\Release\MinHook.x86.dll
========== Build: 2 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

MinHook hook of NtEnumerateKey crashes in VS2015 Win 10

Reproduction:

  • Set a hook of NtEnumerateKey of ntdll module using MH_CreateHook and MH_Enable. In MH_CreateHook use a trampoline
  • Prototype of detour function looks like this:
NTSTATUS hookNtEnumKey(_In_      HANDLE                KeyHandle,
    _In_      ULONG                 Index,
    _In_      KEY_INFORMATION_CLASS KeyInformationClass,
    _Out_opt_ PVOID                 KeyInformation,
    _In_      ULONG                 Length,
    _Out_     PULONG                ResultLength)
{
    return tramp_nt_enum_key(KeyHandle, Index, KeyInformationClass, KeyInformation, Length, ResultLength);
}
  • Inject DLL to Visual Studio 2015 build 14.0 x86
  • Go to File->Open->Project Solution to open file browser
  • App will crash just after returning from hookNtEnumKey proc - the status will be returned correctly but possibly something wrong happens on stack afterwards.

If still unable to reproduce, install Visual Assist X (i had no time to check whether this is related, imo. it's not)

Program crashes

Hi, this is my 2nd time here. The first time was due to not reading the changelogs and I am stupid for that (passing MH_ALL_HOOKS fixed my problem). This time my program is crashing. I am hooking TerminateProcess. I inject my dll into Taskmgr, try to terminate the protected process then
the messagebox pops up and I'm able to hit ok then the crash comes so I'm thinking it's crashing on "return 0" but I don't know why. > 1 = success and 0 = failure according to the msdn
this is my code http://pastebin.com/fR0m2AJQ

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.