forked from Source-Python-Dev-Team/Source.Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_function.cpp
More file actions
414 lines (349 loc) · 13.9 KB
/
memory_function.cpp
File metadata and controls
414 lines (349 loc) · 13.9 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
/**
* =============================================================================
* Source Python
* Copyright (C) 2012-2015 Source Python Development Team. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the Source Python Team gives you permission
* to link the code of this program (as well as its derivative works) to
* "Half-Life 2," the "Source Engine," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, the Source.Python
* Development Team grants this exception to all derivative works.
*/
// ============================================================================
// >> INCLUDES
// ============================================================================
// DynCall
#include "dyncall.h"
#include "dyncall_signature.h"
// Memory
#include "memory_function.h"
#include "memory_utilities.h"
#include "memory_hooks.h"
// DynamicHooks
#include "conventions/x86MsCdecl.h"
#include "conventions/x86MsThiscall.h"
#include "conventions/x86MsStdcall.h"
#include "conventions/x86GccCdecl.h"
#include "conventions/x86GccThiscall.h"
// Source.Python
#include "utilities/call_python.h"
// ============================================================================
// >> EXTERNALS
// ============================================================================
extern std::map<CHook *, std::map<HookType_t, std::list<object> > > g_mapCallbacks;
// ============================================================================
// >> GLOBAL VARIABLES
// ============================================================================
DCCallVM* g_pCallVM = dcNewCallVM(4096);
// ============================================================================
// >> GetDynCallConvention
// ============================================================================
int GetDynCallConvention(Convention_t eConv)
{
switch (eConv)
{
case CONV_CUSTOM: return -1;
case CONV_CDECL: return DC_CALL_C_DEFAULT;
case CONV_THISCALL:
#ifdef _WIN32
return DC_CALL_C_X86_WIN32_THIS_MS;
#else
return DC_CALL_C_X86_WIN32_THIS_GNU;
#endif
#ifdef _WIN32
case CONV_STDCALL: return DC_CALL_C_X86_WIN32_STD;
#endif
}
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Unsupported calling convention.")
return -1;
}
// ============================================================================
// >> MakeDynamicHooksConvention
// ============================================================================
ICallingConvention* MakeDynamicHooksConvention(Convention_t eConv, std::vector<DataType_t> vecArgTypes, DataType_t returnType, int iAlignment=4)
{
#ifdef _WIN32
switch (eConv)
{
case CONV_CDECL: return new x86MsCdecl(vecArgTypes, returnType, iAlignment);
case CONV_THISCALL: return new x86MsThiscall(vecArgTypes, returnType, iAlignment);
case CONV_STDCALL: return new x86MsStdcall(vecArgTypes, returnType, iAlignment);
}
#else
switch (eConv)
{
case CONV_CDECL: return new x86GccCdecl(vecArgTypes, returnType, iAlignment);
case CONV_THISCALL: return new x86GccThiscall(vecArgTypes, returnType, iAlignment);
}
#endif
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Unsupported calling convention.")
return NULL;
}
// ============================================================================
// >> CFunction
// ============================================================================
CFunction::CFunction(unsigned long ulAddr, object oCallingConvention, object oArgs, object oReturnType)
:CPointer(ulAddr)
{
// Step 1: Validate and convert the argument types
m_tArgs = tuple(oArgs);
// Step 2: Determine the return type/converter
try
{
// If this line succeds...
m_eReturnType = extract<DataType_t>(oReturnType);
// ...no converter will be used
m_oConverter = object();
}
catch( ... )
{
PyErr_Clear();
// If this happens the return type is a converter for a pointer
m_eReturnType = DATA_TYPE_POINTER;
m_oConverter = oReturnType;
}
// Step 3: Determine the calling convention
try
{
// If this line succeeds the user wants to create a function with the built-in calling conventions
m_eCallingConvention = extract<Convention_t>(oCallingConvention);
m_pCallingConvention = MakeDynamicHooksConvention(m_eCallingConvention, ObjectToDataTypeVector(m_tArgs), m_eReturnType);
// We allocated the calling convention, we are responsible to cleanup.
m_bAllocatedCallingConvention = true;
}
catch( ... )
{
PyErr_Clear();
// A custom calling convention will be used...
m_eCallingConvention = CONV_CUSTOM;
object _oCallingConvention = oCallingConvention(m_tArgs, m_eReturnType);
// FIXME:
// This is required to fix a crash, but it will also cause a memory leak,
// because no calling convention object that is created via this method will ever be deleted.
// TODO: Pretty sure this was required due to the missing held type definition. It was added, but wasn't tested yet.
Py_INCREF(_oCallingConvention.ptr());
m_pCallingConvention = extract<ICallingConvention*>(_oCallingConvention);
// We didn't allocate the calling convention, someone else is responsible for it.
m_bAllocatedCallingConvention = false;
}
// Step 4: Get the DynCall calling convention
m_iCallingConvention = GetDynCallConvention(m_eCallingConvention);
}
CFunction::CFunction(unsigned long ulAddr, Convention_t eCallingConvention,
int iCallingConvention, ICallingConvention* pCallingConvention, tuple tArgs,
DataType_t eReturnType, object oConverter)
:CPointer(ulAddr)
{
m_eCallingConvention = eCallingConvention;
m_iCallingConvention = iCallingConvention;
m_pCallingConvention = pCallingConvention;
// We didn't allocate the calling convention, someone else is responsible for it.
m_bAllocatedCallingConvention = false;
m_tArgs = tArgs;
m_eReturnType = eReturnType;
m_oConverter = oConverter;
}
CFunction::~CFunction()
{
// If we didn't allocate the calling convention, then it is not our responsibility.
if (!m_bAllocatedCallingConvention)
return;
CHook* pHook = GetHookManager()->FindHook((void *) m_ulAddr);
// DynamicHooks will take care of it for us from there.
if (pHook && pHook->m_pCallingConvention == m_pCallingConvention)
return;
// Cleanup.
delete m_pCallingConvention;
m_pCallingConvention = NULL;
}
bool CFunction::IsCallable()
{
return (m_eCallingConvention != CONV_CUSTOM) && (m_iCallingConvention != -1);
}
bool CFunction::IsHookable()
{
return m_pCallingConvention != NULL;
}
bool CFunction::IsHooked()
{
return GetHookManager()->FindHook((void *) m_ulAddr) != NULL;
}
template<class ReturnType, class Function>
ReturnType CallHelper(Function func, DCCallVM* vm, unsigned long addr)
{
ReturnType result;
TRY_SEGV()
result = (ReturnType) func(vm, addr);
EXCEPT_SEGV()
return result;
}
void CallHelperVoid(DCCallVM* vm, unsigned long addr)
{
TRY_SEGV()
dcCallVoid(vm, addr);
EXCEPT_SEGV()
}
object CFunction::Call(tuple args, dict kw)
{
if (!IsCallable())
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Function is not callable.")
Validate();
if (len(args) != len(m_tArgs))
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Number of passed arguments is not equal to the required number.")
// Reset VM and set the calling convention
dcReset(g_pCallVM);
dcMode(g_pCallVM, m_iCallingConvention);
// Loop through all passed arguments and add them to the VM
for(int i=0; i < len(args); i++)
{
object arg = args[i];
switch(extract<DataType_t>(m_tArgs[i]))
{
case DATA_TYPE_BOOL: dcArgBool(g_pCallVM, extract<bool>(arg)); break;
case DATA_TYPE_CHAR: dcArgChar(g_pCallVM, extract<char>(arg)); break;
case DATA_TYPE_UCHAR: dcArgChar(g_pCallVM, extract<unsigned char>(arg)); break;
case DATA_TYPE_SHORT: dcArgShort(g_pCallVM, extract<short>(arg)); break;
case DATA_TYPE_USHORT: dcArgShort(g_pCallVM, extract<unsigned short>(arg)); break;
case DATA_TYPE_INT: dcArgInt(g_pCallVM, extract<int>(arg)); break;
case DATA_TYPE_UINT: dcArgInt(g_pCallVM, extract<unsigned int>(arg)); break;
case DATA_TYPE_LONG: dcArgLong(g_pCallVM, extract<long>(arg)); break;
case DATA_TYPE_ULONG: dcArgLong(g_pCallVM, extract<unsigned long>(arg)); break;
case DATA_TYPE_LONG_LONG: dcArgLongLong(g_pCallVM, extract<long long>(arg)); break;
case DATA_TYPE_ULONG_LONG: dcArgLongLong(g_pCallVM, extract<unsigned long long>(arg)); break;
case DATA_TYPE_FLOAT: dcArgFloat(g_pCallVM, extract<float>(arg)); break;
case DATA_TYPE_DOUBLE: dcArgDouble(g_pCallVM, extract<double>(arg)); break;
case DATA_TYPE_POINTER:
{
unsigned long ulAddr = 0;
if (arg.ptr() != Py_None)
ulAddr = ExtractPointer(arg)->m_ulAddr;
dcArgPointer(g_pCallVM, ulAddr);
break;
}
case DATA_TYPE_STRING: dcArgPointer(g_pCallVM, (unsigned long) (void *) extract<char *>(arg)); break;
default: BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Unknown argument type.")
}
}
// Call the function
switch(m_eReturnType)
{
case DATA_TYPE_VOID: CallHelperVoid(g_pCallVM, m_ulAddr); break;
case DATA_TYPE_BOOL: return object(CallHelper<bool>(dcCallBool, g_pCallVM, m_ulAddr));
case DATA_TYPE_CHAR: return object(CallHelper<char>(dcCallChar, g_pCallVM, m_ulAddr));
case DATA_TYPE_UCHAR: return object(CallHelper<unsigned char>(dcCallChar, g_pCallVM, m_ulAddr));
case DATA_TYPE_SHORT: return object(CallHelper<short>(dcCallShort, g_pCallVM, m_ulAddr));
case DATA_TYPE_USHORT: return object(CallHelper<unsigned short>(dcCallShort, g_pCallVM, m_ulAddr));
case DATA_TYPE_INT: return object(CallHelper<int>(dcCallInt, g_pCallVM, m_ulAddr));
case DATA_TYPE_UINT: return object(CallHelper<unsigned int>(dcCallInt, g_pCallVM, m_ulAddr));
case DATA_TYPE_LONG: return object(CallHelper<long>(dcCallLong, g_pCallVM, m_ulAddr));
case DATA_TYPE_ULONG: return object(CallHelper<unsigned long>(dcCallLong, g_pCallVM, m_ulAddr));
case DATA_TYPE_LONG_LONG: return object(CallHelper<long long>(dcCallLongLong, g_pCallVM, m_ulAddr));
case DATA_TYPE_ULONG_LONG: return object(CallHelper<unsigned long long>(dcCallLongLong, g_pCallVM, m_ulAddr));
case DATA_TYPE_FLOAT: return object(CallHelper<float>(dcCallFloat, g_pCallVM, m_ulAddr));
case DATA_TYPE_DOUBLE: return object(CallHelper<double>(dcCallDouble, g_pCallVM, m_ulAddr));
case DATA_TYPE_POINTER:
{
CPointer pPtr = CPointer(CallHelper<unsigned long>(dcCallPointer, g_pCallVM, m_ulAddr));
if (!m_oConverter.is_none())
return m_oConverter(pPtr);
return object(pPtr);
}
case DATA_TYPE_STRING: return object(CallHelper<const char *>(dcCallPointer, g_pCallVM, m_ulAddr));
default: BOOST_RAISE_EXCEPTION(PyExc_TypeError, "Unknown return type.")
}
return object();
}
object CFunction::CallTrampoline(tuple args, dict kw)
{
if (!IsCallable())
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Function is not callable.")
Validate();
CHook* pHook = GetHookManager()->FindHook((void *) m_ulAddr);
if (!pHook)
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Function was not hooked.")
return CFunction((unsigned long) pHook->m_pTrampoline, m_eCallingConvention,
m_iCallingConvention, m_pCallingConvention, m_tArgs, m_eReturnType, m_oConverter).Call(args, kw);
}
object CFunction::SkipHooks(tuple args, dict kw)
{
if (IsHooked())
return CallTrampoline(args, kw);
return Call(args, kw);
}
CHook* HookFunctionHelper(void* addr, ICallingConvention* pConv)
{
CHook* result;
TRY_SEGV()
result = GetHookManager()->HookFunction(addr, pConv);
EXCEPT_SEGV()
return result;
}
void CFunction::AddHook(HookType_t eType, PyObject* pCallable)
{
if (!IsHookable())
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Function is not hookable.")
Validate();
CHook* pHook = GetHookManager()->FindHook((void *) m_ulAddr);
// Prepare arguments for log message
str type = str(eType);
const char* szType = extract<const char*>(type);
str convention = str(m_eCallingConvention);
const char* szConvention = extract<const char*>(convention);
str args = str(m_tArgs);
const char* szArgs = extract<const char*>(args);
str return_type = str(m_eReturnType);
const char* szReturnType = extract<const char*>(return_type);
object oCallback = object(handle<>(borrowed(pCallable)));
str callback = str(oCallback);
const char* szCallback = extract<const char*>(callback);
PythonLog(
4,
"Hooking function: type=%s, addr=%u, conv=%s, args=%s, rtype=%s, callback=%s",
szType,
m_ulAddr,
szConvention,
szArgs,
szReturnType,
szCallback
);
if (!pHook) {
pHook = HookFunctionHelper((void *) m_ulAddr, m_pCallingConvention);
// DynamicHooks will handle our convention from there, regardless if we allocated it or not.
m_bAllocatedCallingConvention = false;
}
// Add the hook handler. If it's already added, it won't be added twice
pHook->AddCallback(eType, (HookHandlerFn *) (void *) &SP_HookHandler);
g_mapCallbacks[pHook][eType].push_back(object(handle<>(borrowed(pCallable))));
}
void CFunction::RemoveHook(HookType_t eType, PyObject* pCallable)
{
Validate();
CHook* pHook = GetHookManager()->FindHook((void *) m_ulAddr);
if (!pHook)
return;
g_mapCallbacks[pHook][eType].remove(object(handle<>(borrowed(pCallable))));
}
void CFunction::DeleteHook()
{
CHook* pHook = GetHookManager()->FindHook((void *) m_ulAddr);
if (!pHook)
return;
g_mapCallbacks.erase(pHook);
// Set the calling convention to NULL, because DynamicHooks will delete it otherwise.
pHook->m_pCallingConvention = NULL;
GetHookManager()->UnhookFunction((void *) m_ulAddr);
}