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_tools.cpp
More file actions
507 lines (426 loc) · 16.1 KB
/
Copy pathmemory_tools.cpp
File metadata and controls
507 lines (426 loc) · 16.1 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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
/**
* =============================================================================
* Source Python
* Copyright (C) 2012 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
//-----------------------------------------------------------------------------
#include <stdlib.h>
#include <string>
#include "dyncall.h"
#include "memory_hooks.h"
#include "memory_tools.h"
#include "utilities/wrap_macros.h"
#include "utilities/sp_util.h"
#include "utilities/call_python.h"
// DynamicHooks
#include "conventions/x86MsCdecl.h"
#include "conventions/x86MsThiscall.h"
#include "conventions/x86MsStdcall.h"
#include "conventions/x86GccCdecl.h"
#include "conventions/x86GccThiscall.h"
DCCallVM* g_pCallVM = dcNewCallVM(4096);
extern std::map<CHook *, std::map<HookType_t, std::list<PyObject *> > > g_mapCallbacks;
dict g_oExposedClasses;
//-----------------------------------------------------------------------------
// Functions
//-----------------------------------------------------------------------------
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;
}
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;
}
//-----------------------------------------------------------------------------
// CPointer class
//-----------------------------------------------------------------------------
CPointer::CPointer(unsigned long ulAddr /* = 0 */, bool bAutoDealloc /* false */)
{
m_ulAddr = ulAddr;
m_bAutoDealloc = bAutoDealloc;
}
const char * CPointer::GetStringArray(int iOffset /* = 0 */)
{
if (!IsValid())
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Pointer is NULL.")
return (const char *) m_ulAddr + iOffset;
}
void CPointer::SetStringArray(char* szText, int iOffset /* = 0 */)
{
if (!IsValid())
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Pointer is NULL.")
strcpy((char *) (m_ulAddr + iOffset), szText);
}
CPointer* CPointer::GetPtr(int iOffset /* = 0 */)
{
if (!IsValid())
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Pointer is NULL.")
return new CPointer(*(unsigned long *) (m_ulAddr + iOffset));
}
void CPointer::SetPtr(object oPtr, int iOffset /* = 0 */)
{
if (!IsValid())
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Pointer is NULL.")
CPointer* pPtr = ExtractPointer(oPtr);
*(unsigned long *) (m_ulAddr + iOffset) = pPtr->m_ulAddr;
}
int CPointer::Compare(object oOther, unsigned long ulNum)
{
CPointer* pOther = ExtractPointer(oOther);
if (!m_ulAddr || !pOther->IsValid())
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "At least one pointer is NULL.")
return memcmp((void *) m_ulAddr, (void *) pOther->m_ulAddr, ulNum);
}
bool CPointer::IsOverlapping(object oOther, unsigned long ulNumBytes)
{
CPointer* pOther = ExtractPointer(oOther);
if (m_ulAddr <= pOther->m_ulAddr)
return m_ulAddr + ulNumBytes > pOther->m_ulAddr;
return pOther->m_ulAddr + ulNumBytes > m_ulAddr;
}
CPointer* CPointer::SearchBytes(object oBytes, unsigned long ulNumBytes)
{
if (!m_ulAddr)
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Pointer is NULL.")
unsigned long iByteLen = len(oBytes);
if (ulNumBytes < iByteLen)
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Search range is too small.")
unsigned char* base = (unsigned char *) m_ulAddr;
unsigned char* end = (unsigned char *) (m_ulAddr + ulNumBytes - (iByteLen - 1));
unsigned char* bytes = NULL;
PyArg_Parse(oBytes.ptr(), "y", &bytes);
if(!bytes)
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Unable to parse the signature.");
while (base < end)
{
unsigned long i = 0;
for(; i < iByteLen; i++)
{
if (bytes[i] == '\x2A')
continue;
if (bytes[i] != base[i])
break;
}
if (i == iByteLen)
return new CPointer((unsigned long) base);
base++;
}
return new CPointer();
}
void CPointer::Copy(object oDest, unsigned long ulNumBytes)
{
CPointer* pDest = ExtractPointer(oDest);
if (!m_ulAddr || !pDest->IsValid())
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "At least one pointer is NULL.")
if (IsOverlapping(oDest, ulNumBytes))
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Pointers are overlapping!")
memcpy((void *) pDest->m_ulAddr, (void *) m_ulAddr, ulNumBytes);
}
void CPointer::Move(object oDest, unsigned long ulNumBytes)
{
CPointer* pDest = ExtractPointer(oDest);
if (!m_ulAddr || !pDest->IsValid())
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "At least one pointer is NULL.")
memmove((void *) pDest->m_ulAddr, (void *) m_ulAddr, ulNumBytes);
}
CPointer* CPointer::GetVirtualFunc(int iIndex)
{
if (!IsValid())
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Pointer is NULL.")
void** vtable = *(void ***) m_ulAddr;
if (!vtable)
return new CPointer();
return new CPointer((unsigned long) vtable[iIndex]);
}
CPointer* CPointer::Realloc(int iSize)
{
return new CPointer((unsigned long) UTIL_Realloc((void *) m_ulAddr, iSize));
}
CFunction* CPointer::MakeFunction(object oCallingConvention, object oArgs, object oReturnType)
{
if (!IsValid())
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Pointer is NULL.")
return new CFunction(m_ulAddr, oCallingConvention, oArgs, oReturnType);
}
CFunction* CPointer::MakeVirtualFunction(int iIndex, object oCallingConvention, object args, object return_type)
{
return GetVirtualFunc(iIndex)->MakeFunction(oCallingConvention, args, return_type);
}
void CPointer::CallCallback(PyObject* self, char* szCallback)
{
if (PyObject_HasAttrString(self, szCallback))
{
PyObject* callback = PyObject_GetAttrString(self, szCallback);
if (callback && PyCallable_Check(callback))
{
if (!PyObject_HasAttrString(callback, "__self__"))
{
xdecref(PyObject_CallFunction(callback, "O", self));
}
else
{
xdecref(PyObject_CallMethod(self, szCallback, NULL));
}
}
xdecref(callback);
}
}
void CPointer::PreDealloc(PyObject* self)
{
CallCallback(self, "on_dealloc");
CPointer* pointer = extract<CPointer *>(self);
pointer->Dealloc();
}
CPointer* CPointer::PreRealloc(PyObject* self, int iSize)
{
CallCallback(self, "on_realloc");
CPointer* pointer = extract<CPointer *>(self);
return pointer->Realloc(iSize);
}
void CPointer::__del__(PyObject* self)
{
CPointer* ptr = extract<CPointer *>(self);
if (ptr->m_bAutoDealloc)
{
PythonLog(4, "Automatically deallocating pointer at %u.", ptr->m_ulAddr);
PreDealloc(self);
}
}
//-----------------------------------------------------------------------------
// CFunction class
//-----------------------------------------------------------------------------
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);
}
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.
Py_INCREF(_oCallingConvention.ptr());
m_pCallingConvention = extract<ICallingConvention*>(_oCallingConvention);
}
// 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;
m_tArgs = tArgs;
m_eReturnType = eReturnType;
m_oConverter = oConverter;
}
bool CFunction::IsCallable()
{
return (m_eCallingConvention != CONV_CUSTOM) && (m_iCallingConvention != -1);
}
bool CFunction::IsHookable()
{
return m_pCallingConvention != NULL;
}
object CFunction::Call(tuple args, dict kw)
{
if (!IsCallable())
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Function is not callable.")
if (!IsValid())
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Function pointer is NULL.")
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: dcCallVoid(g_pCallVM, m_ulAddr); break;
case DATA_TYPE_BOOL: return object(dcCallBool(g_pCallVM, m_ulAddr));
case DATA_TYPE_CHAR: return object(dcCallChar(g_pCallVM, m_ulAddr));
case DATA_TYPE_UCHAR: return object((unsigned char) dcCallChar(g_pCallVM, m_ulAddr));
case DATA_TYPE_SHORT: return object(dcCallShort(g_pCallVM, m_ulAddr));
case DATA_TYPE_USHORT: return object((unsigned short) dcCallShort(g_pCallVM, m_ulAddr));
case DATA_TYPE_INT: return object(dcCallInt(g_pCallVM, m_ulAddr));
case DATA_TYPE_UINT: return object((unsigned int) dcCallInt(g_pCallVM, m_ulAddr));
case DATA_TYPE_LONG: return object(dcCallLong(g_pCallVM, m_ulAddr));
case DATA_TYPE_ULONG: return object((unsigned long) dcCallLong(g_pCallVM, m_ulAddr));
case DATA_TYPE_LONG_LONG: return object(dcCallLongLong(g_pCallVM, m_ulAddr));
case DATA_TYPE_ULONG_LONG: return object((unsigned long long) dcCallLongLong(g_pCallVM, m_ulAddr));
case DATA_TYPE_FLOAT: return object(dcCallFloat(g_pCallVM, m_ulAddr));
case DATA_TYPE_DOUBLE: return object(dcCallDouble(g_pCallVM, m_ulAddr));
case DATA_TYPE_POINTER:
{
CPointer pPtr = CPointer(dcCallPointer(g_pCallVM, m_ulAddr));
if (!m_oConverter.is_none())
return m_oConverter(pPtr);
return object(pPtr);
}
case DATA_TYPE_STRING: return object((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.")
if (!IsValid())
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Function pointer is NULL.")
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);
}
handle<> CFunction::AddHook(HookType_t eType, PyObject* pCallable)
{
if (!IsHookable())
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Function is not hookable.")
if (!IsValid())
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Function pointer is NULL.")
// Hook the function
CHook* pHook = GetHookManager()->FindHook((void *) m_ulAddr);
if (!pHook)
{
pHook = GetHookManager()->HookFunction((void *) m_ulAddr, m_pCallingConvention);
}
// Add the hook handler. If it's already added, it won't be added twice
pHook->AddCallback(eType, (HookHandlerFn *) (void *) &SP_HookHandler);
// Add the callback to our map
g_mapCallbacks[pHook][eType].push_back(pCallable);
// Return the callback, so we can use this method as a decorator
return handle<>(borrowed(pCallable));
}
void CFunction::RemoveHook(HookType_t eType, PyObject* pCallable)
{
if (!IsValid())
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Function pointer is NULL.")
CHook* pHook = GetHookManager()->FindHook((void *) m_ulAddr);
if (!pHook)
return;
g_mapCallbacks[pHook][eType].remove(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);
}