c++函数钩子(dll, asm)

c++ function hook(dll, asm)

本文关键字:asm dll 函数 c++      更新时间:2023-10-16

我编写了一个dll。在这个dll中,我想将另一个dll的函数加载到内存中。这是长时间工作的结果:

typedef int (__fastcall *def_cry)(int a,int b,int fromlen);
def_cry Real_cry;
int __fastcall custom_cry(int a,int b,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);
我的钩子好像坏了。我想我把一些逻辑错误的代码,但我是一个初学者,需要帮助!

您确定要挂接的函数使用__fastcall调用约定吗?

为了钩住从DLL导出的函数,您需要修补调用的所有模块(DLL/exe)的导入表,或者在运行时重写函数的入口点。在CodeProject (这里)上可以找到一篇不错的关于修补导入表的文章。关于使用MS Detours的一个很好的教程可以在这里找到

在调用DetourFunction时,需要提供要钩子的函数的地址。这些值不应该硬编码,因为在DLL中不能保证在特定地址加载。这可以用下面的代码很容易地完成:

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