使用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;
}

僅列出關鍵代碼,其他不展示了,不懂的留言。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM