tsudakageyu / minhook Goto Github PK
View Code? Open in Web Editor NEWThe Minimalistic x86/x64 API Hooking Library for Windows
Home Page: http://www.codeproject.com/KB/winsdk/LibMinHook.aspx
License: Other
The Minimalistic x86/x64 API Hooking Library for Windows
Home Page: http://www.codeproject.com/KB/winsdk/LibMinHook.aspx
License: Other
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...
For example, this thread:
https://bytes.com/topic/c/answers/584600-casting-function-pointers-void
Is there any way for the API to allow some kind of void(*funcPtr)()
or something instead, that would be kosher in standard C++.
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();
you have any plans to make a version for windows kernel hooking x64 and x86?
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.
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:
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.
Can you please release compiled binaries on github.
CodeProject download links are all broken.
Nuget wont install on VS2017 .Net 4.6.2
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!
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?
To cross compile on linux, you have to change in src/trampoline.c :
and
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).
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:
Download "Source code (zip)" from https://github.com/TsudaKageyu/minhook/releases
If you don't have VS - download the free Visual Studio 2017 community edition
Unzip the source code and open "build\VC15\MinHookVC15.sln"
on left bottom choose "properties" and double click "libMinHook" on the top
set Window-SDK to newest available and save
same for "MinHook"
Now choose "Release" on top and press F7 (=create project)
If everything worked fine, you will find the needed lib in "build\VC15\lib\Release"
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!
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.
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
2017~
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;
}```
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:
MAX_MEMORY_RANGE
defined as 0x02000000
? Why not something along the lines of 0x80000000
, which is the range of the long jump?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.
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.
I have tried with Asp.net web application hosted in IIS server. After many attempt i couldn't succeed .Is there any way to do that?
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 :
but works if I remove one of the two functions that returns the same in the same vtable :
Sorry for my bad english :)
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;
}
Does this library has in built functionality for hooking API calls in a different process via injection ?
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 ?
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
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
Hello i downloaded and installed minhook with nuget like you can see in the picture:
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
minhook fails on double jmp and doesn't restore the dll previous state.
Can u give a sample if it's possible?
Reproduction:
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);
}
If still unable to reproduce, install Visual Assist X (i had no time to check whether this is related, imo. it's not)
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!
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
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.
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.
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:
Does somebody have an idea or any clue how to debug/solve this problem?
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...?
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
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
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.
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 ==========
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.
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?
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
.
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.
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);
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.
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.
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.
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.