-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmem.cpp
82 lines (62 loc) · 1.98 KB
/
mem.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include "pch.h"
#include "mem.h"
void mem::Patch(BYTE* dst, BYTE* src, unsigned int size)
{
DWORD oldprotect;
VirtualProtect(dst, size, PAGE_EXECUTE_READWRITE, &oldprotect);
memcpy(dst, src, size);
VirtualProtect(dst, size, oldprotect, &oldprotect);
}
DWORD mem::HookFunc(BYTE* targetFunc, BYTE* OurFunc, unsigned int size)
{
if (size < 5)
return NULL;
DWORD oldprotect;
VirtualProtect(targetFunc, size, PAGE_EXECUTE_READWRITE, &oldprotect);
memset(targetFunc, 0x90, size); // Nop
DWORD relativeAddress = ((DWORD)OurFunc - (DWORD)targetFunc) - 5;
*targetFunc = 0xE9;
*(DWORD*)((DWORD)targetFunc + 1) = relativeAddress;
VirtualProtect(targetFunc, size, oldprotect, &oldprotect);
return (DWORD)((BYTE*)targetFunc + size);
}
BYTE* mem::TrampHook(BYTE* targetFunc, BYTE* OurFunc, unsigned int size)
{
if (size < 5)
return nullptr;
// Create Gateway
unsigned int GatewaySize = size + 5;
BYTE* gateway = (BYTE*)VirtualAlloc(0, GatewaySize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (gateway == nullptr)
return nullptr;
// Debug: NOP
memset(gateway, 0x90, GatewaySize);
// Write the stolen bytes to the gateway
memcpy_s(gateway, size, targetFunc, size);
// Get the gateway to destination address
uintptr_t gatewayRelativeAddr = targetFunc - gateway - 5;
// add the jmp opcode to the end of the gateway
*(gateway + size) = 0xE9;
// Write the address of the gateway to the jmp
*(uintptr_t*)((uintptr_t)gateway + size + 1) = gatewayRelativeAddr;
// Perform the detour
mem::HookFunc(targetFunc, OurFunc, size);
return gateway;
}
void mem::Nop(BYTE* dst, unsigned int size)
{
DWORD oldprotect;
VirtualProtect(dst, size, PAGE_EXECUTE_READWRITE, &oldprotect);
memset(dst, 0x90, size);
VirtualProtect(dst, size, oldprotect, &oldprotect);
}
uintptr_t mem::FindDMAAddy(uintptr_t ptr, std::vector<unsigned int> offsets)
{
uintptr_t addr = ptr;
for (unsigned int i = 0; i < offsets.size(); ++i)
{
addr = *(uintptr_t*)addr;
addr += offsets[i];
}
return addr;
}