c++ function hook(dll, asm)
I program a dll. In this dll, I want to hook another dll's function loaded into memory. This is the result of many hours of work:
typedef int (__fastcall *def_cry)(int a,int b,int fromlen);
def_cry Real_cry;
int __fastcall custom_cry(int a,int 开发者_如何学Pythonb,int fromlen) {
Log("cry ...");
__asm nop;
return Real_cry(a, b, fromlen);
}
DWORD imageBaseOtherDll = 0x39500000;
DWORD functionOffset = 0x395742F8;
DWORD imageBase = (DWORD)GetModuleHandle("otherDll.dll");
DWORD functionOffset = imageBase + (functionOffset - imageBaseOtherDll);
Real_cry = (def_cry)DetourFunction((PBYTE)functionOffset,(PBYTE)&custom_cry);
It seems, my hook doesn't work. I think i put some logical errors in the code but I'm a beginner and nned help!
Are you sure the function you are hooking uses the __fastcall
calling convention?
In order to hook a function exported from a DLL you will need to either patch the import tables of all modules (dll/exe) that call it or rewrite the functions entry point at runtime. A decent article on patching the import table can be found on CodeProject here. A good tutorial on using MS Detours can be found here.
You need to supply the address of the function you want to hook when you call DetourFunction. These values should not be hard coded as in your DLL is not guaranteed to load at a specific address. This can be done quite easily with the following code:
// Get the module containing the function to hook
HMODULE targetModule = GetModuleHandle("otherDll.dll");
// Get the address of the function to hook
FARPROC targetFunction = GetProcAddress(targetModule, "cry");
// Go hook it.
Real_cry = (def_cry)DetourFunction((PBYTE)targetFunction,(PBYTE)&custom_cry);
精彩评论