使用fastcall 代替汇编hook thiscall

利用fastcall中ecx edx传递的特性,解决了ecx需要内嵌汇编才能实现hook thiscall函数的问题。

#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <string>
#include "mhook-lib/mhook.h"

class A
{
private:
    int m_data;
    char* m_sz[20];

public:
    int setMsg(const char* pstr, int data)
    {
        if (pstr != NULL && *(char*)pstr != '\0')
        {
            memcpy(m_sz, pstr, 20);
        }

        m_data = data;

        return 0;
    }


    void showMsg()
    {
        if (m_sz[0] != '\0')
        {
            printf("%s,%d\n", m_sz,m_data);
        }
    }


};



typedef int (__thiscall A::* TYPE_Ptr)(const char* pstr, int data);


typedef int (__fastcall * TYPE_setMsgPtr)(void* pthis,  void* notUsed, const char*, int);

TYPE_setMsgPtr pNew;


int __fastcall HookSetMsg(void * pThis ,void * notUsed, const char* pstr, int data)
{

    printf("hook new function\n");
    return pNew(pThis, notUsed, pstr, data);
}




TYPE_setMsgPtr pfnSetMsg = NULL;

//实现hook thiscall 的方法,不需要用naked汇编
int main(int argc, char **argv)
{
    A* theA = new A();
    theA->setMsg("hello A!", 12);
    
    theA->showMsg();

    TYPE_Ptr px = &A::setMsg;
    int x = *(int*)&px;

    //printf("%p,%p\n", px, x);

    pNew = (TYPE_setMsgPtr)x;
    Mhook_SetHook((PVOID*)&pNew, HookSetMsg);

    theA->setMsg("hello B!", 14);
    theA->showMsg();

    theA->setMsg("hello C!", 1);
    theA->showMsg();

    return 0;
}

仅列出关键代码,其他不展示了,不懂的留言。

posted @ 2019-04-03 16:52  _**  阅读(1160)  评论(2编辑  收藏  举报