C++ hooking a dll?
Is there a quick way to hook a dll in c++? I know there is Microsoft's Detours thing, but isn't there a quick开发者_如何学编程 a simple way just to hook a few dll functions?
For example I want to hook a the function void mytestfunction()
in the dll mytestdll.dll
to hook_mytestfunction()
.
thanks in advance!
Probably the easiest way is to put your own wrapper DLL with the same name in the directory of the EXE, and put a copy of the hooked DLL in the same directory with a new name. Then, in the IAT of your wrapper DLL, redirect any non-intercepted call to the wrapped DLL (export forwarding), and implement the others yourself.
To redirect functions, put the following line in your .DEF file: Foo=wrapped_mytestdll.Foo
where Foo is the (mangled) function name and wrapped_mytestdll
is the new name of the copied DLL.
As a result, the affected EXE loads your wrapper DLL, and in turn the wrapped DLL. Functions in your wrapper DLL take precedence over the wrapped DLL. The only calls not intercepted are calls by the wrapped DLL to itself, as those don't go through your IAT.
(I've since found a link to a tool to generate a basic ".DEF" file, but haven't tested it myself. Use at your own risk.)
Detours is the quick and simple way!
I assume if you're hooking a DLL that you're hooking the exports of that DLL?
In that case you can perform a simple IAT (and potentially EAT if necessary) hook.
The advantage of IAT/EAT hooks over Detours is that the application and removal of the hooks is 100% safe (as you're not replacing code, you're replacing a pointer, so there is no chance of a race condition), and it's easy to do the hooks on native x64 processes too (which Microsoft's Detours library can't do unless you fork out 10 grand for the Prof edition).
Yes, there are 3rd party detour libraries which have x64 support and take care of most of the race conditions and what-not, but some of them are really expensive, and others are just a pain to work with.
IAT/EAT hooks are quick and easy, and there is sample code for performing them available in the book "Windows via C/C++" (along with a multitude of places on the interwebs).
This is a fairly generic answer I know, but it's hard to go into more detail without more information on what you're trying to do exactly.
I've used this some times ago with success :
http://software.intel.com/en-us/articles/intercepting-system-api-calls/
However I google it and could find something new at code project with great grades :
http://www.codeproject.com/KB/winsdk/LibMinHook.aspx
Just call GetProcAddress(hDll, "mytestfunction"), and write jmp hook_mytestfunction
there, then place instructions at start of mytestfunction in hook_mytestfunction.
It's really quick and easy, of course if you understand it. If you don't - use MS Detours or another library. Usually you can do it without understanding of how it works.
精彩评论