目录

x86 和 x64 共用HOOK类

目录

InHook.h

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#pragma once

#ifdef _WIN64
typedef unsigned __int64  SELF_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[byte_length];
        uchar m_myByte[byte_length];
        SELF_PTR m_oldFuncAddr;
        SELF_PTR m_myFuncAddr;
private:
        static InHook* m_pInstance;                
};

InHook.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#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[0] = { 0xe9 };
        int offset = m_myFuncAddr - m_oldFuncAddr - byte_length;
        memcpy(&m_myByte[1], &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

1
2
3
4
5
6
7
8
#include <Windows.h>
#include "InHook.h"

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

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

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