如何正确使用c++中的Detour库来处理已知内存地址的函数的简单钩子

How to use the Detour library in C++ properly for a simple hook of a function with known memory adress?

本文关键字:地址 内存 函数 简单 处理 何正确 c++ 中的 Detour      更新时间:2023-10-16

我有麻烦得到我的第一个钩子使用绕道工作。我使用Detour 3.0。

我的代码编译得很好,我可以使用Winject注入DLL,但是,我应该挂钩的函数似乎没有被挂钩。我试图在notepad中挂钩InsertDateTime函数。
http://www.9injector.com/winject-injector/

我已经使用IDA Pro Free在十六进制符号中找到了InsertDateTime的地址。

下面的代码中是否有任何基本错误,或者进程中的内存在每次调用时不一定在同一时间?

注入DLL的代码如下:

 // dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include <windows.h>
#include "detours.h"
#pragma comment(lib, "detours.lib")
//
int(__stdcall* InsertDateTime)(int) = (int(__stdcall*)(int))(0x0100978A);
int MyInsertDateTime(int x) //Our function
{
//Messagebox
MessageBox(NULL, TEXT("InsertDateTime Just Got Called"), TEXT("InsertDateTime"), MB_OK);
return InsertDateTime(x); //Return the origional function
}
BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call) //Decide what to do
{
case DLL_PROCESS_ATTACH: //On dll attach
    //InsertDateTime = (int (__stdcall*)(int))DetourAttach((PVOID*)0x0100978A, MyInsertDateTime);
    //MessageBox(NULL, TEXT("InsertDateTime Just Got Called"), TEXT("InsertDateTime"), MB_OK);
    DetourAttach((PVOID*)(&InsertDateTime), (PVOID)MyInsertDateTime);
    //if(!errorCode) {
    //Detour successful
break;
case DLL_THREAD_ATTACH: //On thread attach
        DetourAttach((PVOID*)(&InsertDateTime), (PVOID)MyInsertDateTime);
break;
case DLL_THREAD_DETACH: //On thread detach
break;
case DLL_PROCESS_DETACH: //on process detach
    DetourDetach((PVOID*)0x0100978A, InsertDateTime);
break;
}
return TRUE;
}

代码也大多取自Detour 1.5的旧教程。参考:http://www.moddb.com/groups/ibepex/tutorials/function-hooking

Detours使用了一个类似于数据库的事务系统。在调用Attach或Detach之前,您必须启动事务,并且只有在提交事务时才会应用更改。

DetourTransactionBegin();
DetourAttach(...);
DetourAttach(...);
DetourTransactionCommit();

我认为这是在2.0中引入的,这可以解释为什么你的1.5教程代码没有包含它。