c++ - 使用 Microsoft Detours 时出现访问冲突

标签 c++ x86 detours

我在使用 Microsoft Detours 时遇到访问冲突问题。我制作了一个 dll,将其加载到第三方应用程序中。我正在使用 Detours 制作一个 Trampiline 函数,它是一个未记录的函数,Ida Pro 显示为:

void __thiscall sub_6142E0(int a2, int a3)

我的代码如下所示: #include“stdafx.h” #包括 #包括

typedef void(__stdcall* pFunc)(int d1, int d2);
pFunc FuncToDetour = (pFunc)(0x6142EC);

void MyFunc(int d1, int d2)//Function does not mach call convension __thiscall. Possible problem?
{
    printf("a2 %i, a1 %i);\n", d1, d2);
    FuncToDetour(d1, d2);
}

void Init()
{
    DetourTransactionBegin();
    DetourUpdateThread(GetCurrentThread());
    DetourAttach(&(PVOID&)FuncToDetour, MyFunc);
    DetourTransactionCommit();
}

我要拦截的函数的原始汇编是这样的:

sub_6142E0 proc near

arg_0= dword ptr  8
arg_4= dword ptr  0Ch

push    ebp
mov     ebp, esp
mov     eax, [ecx+8]
mov     ecx, [ebp+arg_4]
mov     edx, [ebp+arg_0]

Detours 的改变确实导致了这样的结果:

.text:006142EC jmp     near ptr unk_F9C6802
...
d3d9.dll:0F9C6802 jmp     near ptr unk_F9D5FE0 //jump to function in my dll
...
void MyFunc(int d1, int d2)//my function
{
    printf("updateHealth(%i, %i);\n", d1, d2);
}
...
Stack[00004A8C]:0019FB4C sub     ah, bh
Stack[00004A8C]:0019FB4E sbb     [eax], eax //eax=0x491B -> access violation
Stack[00004A8C]:0019FB50 cmc
Stack[00004A8C]:0019FB51 inc     si
Stack[00004A8C]:0019FB53 add     [eax], dl
Stack[00004A8C]:0019FB55 add     [eax], eax
Stack[00004A8C]:0019FB57 add     [eax+80019FDh], cl
Stack[00004A8C]:0019FB5D add     byte_19FC6415[eax], dh
Stack[00004A8C]:0019FB5D ; -------------------------------------------------

我收到的错误消息是:

The instruction 0x19FB4E referenced memory at 0x491B. The memory could not be written -> 0000491B (exc.code c0000005, tid 19084)

最佳答案

我将尝试回答我自己的问题。

这归结为两个函数之间的调用约定不匹配。我想要 Hook 的函数正在使用 __thiscall我的功能正在使用 __cdecl (默认调用约定)。 __thiscall 用作类中成员函数的调用约定,其中在调用成员函数时将“this 指针”传递到 ecx 寄存器中。

在我的例子中,ecx 是在调用 MyFunc 时写入的,以便设置堆栈帧(我认为)。当我从 Trampoline 函数调用它时,我 Hook 的函数将获得无效的 this 指针。

检查这个link有关如何正确完成此操作的一些解释和示例。

关于c++ - 使用 Microsoft Detours 时出现访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34245393/

相关文章:

c++ - 防止 DLL 文件通过 MS Detours 加载到我的进程中

c++ - 如何获取 ConnectEx() 指针

c++ - 从 blitz 数组中获取存储类型

assembly - 汇编-shr指令打开进位标志?

c++ - 截取特定窗口的屏幕截图 - C++/Qt

assembly - 什么是参数推序

linux - Intel x86与x64系统调用

c++ - 使用 UnhookWindowsHookEx() 解除 Hook 时,多个程序崩溃

c++ - 在重载类方法上使用 std::bind()

c++ - c++中的一个定义规则