forked from quasemago/SourceQueryCache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Detour.cpp
90 lines (69 loc) · 2 KB
/
Detour.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
83
84
85
86
87
88
89
90
#include "Detour.h"
cDetour::cDetour() : OrigFunc(NULL), RealFunc(NULL), nSize(0)
{
}
cDetour::~cDetour()
{
UnHookFunction();
delete(char*) OrigFunc;
}
int cDetour::FindOffset(void *Func, int MinOffset)
{
_DecodeResult res;
_DecodedInst decodedInstructions[100];
_DecodeType dt = Decode32Bits;
_OffsetType offset = 0;
unsigned int decodedInstructionsCount = 0;
int InstrSize = 0;
res = distorm_decode(offset, (const unsigned char*)Func, 64, dt, decodedInstructions, sizeof(decodedInstructions) / sizeof(_DecodedInst), &decodedInstructionsCount);
if (res == DECRES_INPUTERR)
return -1;
for (unsigned int i = 0; i < decodedInstructionsCount; ++i)
{
if (InstrSize >= MinOffset)
break;
InstrSize += decodedInstructions[i].size;
}
if (InstrSize < MinOffset)
return -1;
else
return InstrSize;
}
static const char *__JMP = "\x68\x00\x00\x00\x00\xC3";
#define __JMP_Size 6
bool cDetour::HookFunction(void *_OrigFunc, void *_FakeFunc)
{
if (OrigFunc)
{
delete(char*) OrigFunc;
OrigFunc = NULL;
}
bool bResult = true;
int SizeNeeded = FindOffset(_OrigFunc, __JMP_Size);
if (SizeNeeded < 0)
return false;
RealFunc = _OrigFunc;
char MakeJMP[__JMP_Size];
memcpy(MakeJMP, __JMP, __JMP_Size);
unsigned int FakeOffset = (unsigned int)_FakeFunc;
memcpy(MakeJMP + 1, (void*)&FakeOffset, sizeof(FakeOffset));
OrigFunc = (void*)new char[SizeNeeded + __JMP_Size];
bResult &= MemMan.ReadMemory(_OrigFunc, OrigFunc, SizeNeeded);
memcpy((char*)OrigFunc + SizeNeeded, __JMP, __JMP_Size);
unsigned int OrigOffset = (unsigned int)_OrigFunc + SizeNeeded;
memcpy((char*)OrigFunc + SizeNeeded + 1, (void*)&OrigOffset, sizeof(OrigOffset));
nSize = SizeNeeded;
bResult &= MemMan.WriteMemory(_OrigFunc, MakeJMP, __JMP_Size);
bResult &= MemMan.UnProtect(OrigFunc, SizeNeeded + __JMP_Size);
return bResult;
}
bool cDetour::UnHookFunction()
{
if (!OrigFunc || !RealFunc)
return false;
return MemMan.WriteMemory(RealFunc, OrigFunc, __JMP_Size);
}
void* cDetour::OriginalPointer()
{
return OrigFunc;
}