艾鱼 发表于 2021-8-31 17:11:30

x86 和 x64 共用HOOK类

本帖最后由 艾鱼 于 2021-8-31 17:12 编辑

参考其他资料写的,有问题请指出,谢谢。



InHook.h
```
#pragma once

#ifdef _WIN64
typedef unsigned __int64SELF_PTR;
#else
typedef unsigned int SELF_PTR;
#endif

#if _WIN64
constexpr int byte_length = 9;
#else
constexpr int byte_length = 5;
#endif // 0

class InHook
{
public:
        void Initalize(SELF_PTR oldAddr, SELF_PTR myAddr);
        static InHook* GetInitalize();
        // 修改地址
        void motifyAddress();
        // 恢复地址
        void restoreAddress();
        using uchar = unsigned char;
        uchar m_oldByte;
        uchar m_myByte;
        SELF_PTR m_oldFuncAddr;
        SELF_PTR m_myFuncAddr;
private:
        static InHook* m_pInstance;               
};

```

InHook.cpp
```
#include "pch.h"
#include "InHook.h"

InHook* InHook::m_pInstance = NULL;

InHook* InHook::GetInitalize()
{
        if (m_pInstance == NULL)
        {
                m_pInstance = new InHook;
        }
        return m_pInstance;
}

//修改地址页面属性,返回原地址属性
DWORD motifyMemoryAttributes(SELF_PTR myAddr, SELF_PTR attributes = PAGE_EXECUTE_READWRITE)
{
        DWORD oldAttributes;
        VirtualProtect((void*)myAddr, byte_length, attributes, &oldAttributes);
        return oldAttributes;
}

void InHook::Initalize(SELF_PTR oldAddr, SELF_PTR myAddr)
{
        memcpy(&oldAddr, &m_oldFuncAddr, sizeof(oldAddr));
        memcpy(&myAddr, &m_myFuncAddr, sizeof(myAddr));

        m_myByte = { 0xe9 };
        int offset = m_myFuncAddr - m_oldFuncAddr - byte_length;
        memcpy(&m_myByte, &offset, byte_length - 1);
        DWORD attributes = motifyMemoryAttributes(m_oldFuncAddr);
        memcpy(m_oldByte, (void*)m_oldFuncAddr, byte_length);
        motifyMemoryAttributes(m_oldFuncAddr, attributes);

}

// 修改地址
void InHook::motifyAddress()
{
        DWORD attributes = motifyMemoryAttributes(m_oldFuncAddr);
        memcpy((void*)m_oldFuncAddr, m_myByte, byte_length);
        motifyMemoryAttributes(m_oldFuncAddr, attributes);
}

// 恢复地址
void InHook::restoreAddress()
{
        DWORD attributes = motifyMemoryAttributes(m_oldFuncAddr);
        memcpy((void*)m_oldFuncAddr, m_oldByte, byte_length);
        motifyMemoryAttributes(m_oldFuncAddr, attributes);
}

```


调用示例:
main.cpp
```
#include <Windows.h>
#include "InHook.h"

InHook::GetInitalize()->Initalize(d3d9Device_table,(SELF_PTR)hkEndScene);

InHook::GetInitalize()->motifyAddress();

InHook::GetInitalize()->restoreAddress();

```
页: [1]
查看完整版本: x86 和 x64 共用HOOK类