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.h
More file actions
385 lines (314 loc) · 10.5 KB
/
Copy pathmemory_tools.h
File metadata and controls
385 lines (314 loc) · 10.5 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
/**
* =============================================================================
* 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.
*/
#ifndef _MEMORY_TOOLS_H
#define _MEMORY_TOOLS_H
#include <malloc.h>
#include "memalloc.h"
#include "dyncall.h"
#include "dyncall_signature.h"
#include "utility/wrap_macros.h"
#include "DynamicHooks.h"
using namespace DynamicHooks;
#include "boost/python.hpp"
using namespace boost::python;
// Externals
extern DCCallVM* g_pCallVM;
extern dict g_oExposedClasses;
//---------------------------------------------------------------------------------
// Macros
//---------------------------------------------------------------------------------
// Use this macro to add this class to get_pointer()
#define ADD_PTR(classname) \
.def("_ptr", \
&__ptr__<classname>, \
manage_new_object_policy() \
)
// Use this macro to add this class to make_object()
#define ADD_OBJ(classname) \
.def("_obj", \
&__obj__<classname>, \
reference_existing_object_policy() \
).staticmethod("_obj")
// Use this macro to add this class to get_size()
// Note: This must be at the end of the class definition!
#define ADD_SIZE(classname) \
.attr("_size") = sizeof(classname);
// Use this macro to add the class to the ExposedClasses dict
#define STORE_CLASS(classname, pyname) \
extern dict g_oExposedClasses; \
g_oExposedClasses[XSTRINGIFY(classname)] = scope().attr(pyname);
// Use this macro to add the class to the three functions
// Note: This must be at the end of the class definition!
#define ADD_MEM_TOOLS(classname, pyname) \
ADD_PTR(classname) \
ADD_OBJ(classname) \
ADD_SIZE(classname) \
STORE_CLASS(classname, pyname)
#define ADD_MEM_TOOLS_WRAPPER(classname, realname, pyname) \
ADD_PTR(classname) \
ADD_OBJ(classname) \
ADD_SIZE(classname) \
STORE_CLASS(realname, pyname)
//-----------------------------------------------------------------------------
// Memory functions
//-----------------------------------------------------------------------------
inline size_t UTIL_GetMemSize(void* ptr)
{
#ifdef _WIN32
return g_pMemAlloc->GetSize(ptr);
#elif defined(__linux__)
return malloc_usable_size(ptr);
#else
#error "Implement me!"
#endif
}
inline void* UTIL_Alloc(size_t size)
{
void* pPtr = NULL;
#ifdef _WIN32
pPtr = g_pMemAlloc->IndirectAlloc(size);
#elif defined(__linux__)
pPtr = malloc(size);
#else
#error "Implement me!"
#endif
memset(pPtr, 0, size);
return pPtr;
}
inline void* UTIL_Realloc(void* ptr, size_t size)
{
void* pPtr = NULL;
#ifdef _WIN32
pPtr = g_pMemAlloc->Realloc(ptr, size);
#elif defined(__linux__)
pPtr = realloc(ptr, size);
#else
#error "Implement me!"
#endif
return pPtr;
}
inline void UTIL_Dealloc(void* ptr)
{
#ifdef _WIN32
g_pMemAlloc->Free(ptr);
#elif defined(__linux__)
free(ptr);
#else
#error "Implement me!"
#endif
}
//-----------------------------------------------------------------------------
// Convention enum
//-----------------------------------------------------------------------------
inline int GetDynCallConvention(Convention_t eConv)
{
switch (eConv)
{
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
case CONV_STDCALL: return DC_CALL_C_X86_WIN32_STD;
}
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Unsupported calling convention.")
return 0;
}
enum Argument_t
{
ARG_BOOL = DC_SIGCHAR_BOOL,
ARG_CHAR = DC_SIGCHAR_CHAR,
ARG_UCHAR = DC_SIGCHAR_UCHAR,
ARG_SHORT = DC_SIGCHAR_SHORT,
ARG_USHORT = DC_SIGCHAR_USHORT,
ARG_INT = DC_SIGCHAR_INT,
ARG_UINT = DC_SIGCHAR_UINT,
ARG_LONG = DC_SIGCHAR_LONG,
ARG_ULONG = DC_SIGCHAR_ULONG,
ARG_LONGLONG = DC_SIGCHAR_LONGLONG,
ARG_ULONGLONG = DC_SIGCHAR_ULONGLONG,
ARG_FLOAT = DC_SIGCHAR_FLOAT,
ARG_DOUBLE = DC_SIGCHAR_DOUBLE,
ARG_POINTER = DC_SIGCHAR_POINTER,
ARG_STRING = DC_SIGCHAR_STRING
};
enum ReturnType_t
{
RET_VOID = DC_SIGCHAR_VOID,
RET_BOOL = DC_SIGCHAR_BOOL,
RET_CHAR = DC_SIGCHAR_CHAR,
RET_UCHAR = DC_SIGCHAR_UCHAR,
RET_SHORT = DC_SIGCHAR_SHORT,
RET_USHORT = DC_SIGCHAR_USHORT,
RET_INT = DC_SIGCHAR_INT,
RET_UINT = DC_SIGCHAR_UINT,
RET_LONG = DC_SIGCHAR_LONG,
RET_ULONG = DC_SIGCHAR_ULONG,
RET_LONGLONG = DC_SIGCHAR_LONGLONG,
RET_ULONGLONG = DC_SIGCHAR_ULONGLONG,
RET_FLOAT = DC_SIGCHAR_FLOAT,
RET_DOUBLE = DC_SIGCHAR_DOUBLE,
RET_POINTER = DC_SIGCHAR_POINTER,
RET_STRING = DC_SIGCHAR_STRING
};
//-----------------------------------------------------------------------------
// CPointer class
//-----------------------------------------------------------------------------
class CFunction;
class CPointer
{
public:
CPointer(unsigned long ulAddr = 0, bool bAutoDealloc = false);
operator unsigned long() const { return m_ulAddr; }
// Implement some operators
template<class T>
const CPointer* operator+(T const& rhs)
{ return new CPointer(m_ulAddr + rhs); }
template<class T>
const CPointer* operator-(T const& rhs)
{ return new CPointer(m_ulAddr - rhs); }
template<class T>
const CPointer* operator+=(T const& rhs)
{ m_ulAddr += rhs; return this; }
template<class T>
const CPointer* operator-=(T const& rhs)
{ m_ulAddr -= rhs; return this; }
bool operator!()
{ return !m_ulAddr; }
template<class T>
bool operator==(T const& rhs)
{ return m_ulAddr == rhs; }
template<class T>
bool operator!=(T const& rhs)
{ return m_ulAddr != rhs; }
template<class T>
T Get(int iOffset = 0)
{
if (!IsValid())
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Pointer is NULL.")
return *(T *) (m_ulAddr + iOffset);
}
template<class T>
void Set(T value, int iOffset = 0)
{
if (!IsValid())
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Pointer is NULL.")
unsigned long newAddr = m_ulAddr + iOffset;
*(T *) newAddr = value;
}
const char * GetStringArray(int iOffset = 0);
void SetStringArray(char* szText, int iOffset = 0);
CPointer* GetPtr(int iOffset = 0);
void SetPtr(object oPtr, int iOffset = 0);
bool IsOverlapping(object oOther, unsigned long ulNumBytes);
CPointer* SearchBytes(object oBytes, unsigned long ulNumBytes);
int Compare(object oOther, unsigned long ulNum);
void Copy(object oDest, unsigned long ulNumBytes);
void Move(object oDest, unsigned long ulNumBytes);
unsigned long GetSize() { return UTIL_GetMemSize((void *) m_ulAddr); }
bool IsValid() { return m_ulAddr != 0; }
CPointer* GetVirtualFunc(int iIndex);
virtual CPointer* Realloc(int iSize);
virtual void Dealloc() { UTIL_Dealloc((void *) m_ulAddr); m_ulAddr = 0; }
CFunction* MakeFunction(Convention_t eConv, boost::python::tuple args, object return_type);
CFunction* MakeVirtualFunction(int iIndex, Convention_t eConv, boost::python::tuple args, object return_type);
static void CallCallback(PyObject* self, char* szCallback);
static void PreDealloc(PyObject* self);
static CPointer* PreRealloc(PyObject* self, int iSize);
static void __del__(PyObject* self);
public:
unsigned long m_ulAddr;
bool m_bAutoDealloc;
};
//---------------------------------------------------------------------------------
// Converts a Python CPointer object or an integer to an unsigned long.
//---------------------------------------------------------------------------------
class CFunction: public CPointer
{
public:
CFunction(unsigned long ulAddr, Convention_t eConv, boost::python::tuple args, object return_type);
object Call(boost::python::tuple args, dict kw);
object CallTrampoline(boost::python::tuple args, dict kw);
handle<> AddHook(DynamicHooks::HookType_t eType, PyObject* pCallable);
void RemoveHook(DynamicHooks::HookType_t eType, PyObject* pCallable);
handle<> AddPreHook(PyObject* pCallable)
{ return AddHook(HOOKTYPE_PRE, pCallable); }
handle<> AddPostHook(PyObject* pCallable)
{ return AddHook(HOOKTYPE_POST, pCallable); }
void RemovePreHook(PyObject* pCallable)
{ RemoveHook(HOOKTYPE_PRE, pCallable); }
void RemovePostHook(PyObject* pCallable)
{ RemoveHook(HOOKTYPE_POST, pCallable); }
public:
boost::python::tuple m_Args;
object m_oReturnType;
Convention_t m_eConv;
};
//-----------------------------------------------------------------------------
// Functions
//-----------------------------------------------------------------------------
inline CPointer* ExtractPointer(object oPtr)
{
if(PyObject_HasAttrString(oPtr.ptr(), "_ptr"))
oPtr = oPtr.attr("_ptr")();
CPointer* pPtr = extract<CPointer *>(oPtr);
return pPtr;
}
inline CPointer* Alloc(int iSize, bool bAutoDealloc = true)
{
return new CPointer((unsigned long) UTIL_Alloc(iSize), bAutoDealloc);
}
template<class T>
CPointer* __ptr__(T* pThis)
{
return new CPointer((unsigned long) pThis);
}
template<class T>
T* __obj__(CPointer* pPtr)
{
return (T *) pPtr->m_ulAddr;
}
inline object GetObjectPointer(object obj)
{
if (!PyObject_HasAttrString(obj.ptr(), "_ptr"))
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Unable to retrieve a pointer of this object.");
return obj.attr("_ptr")();
}
inline object MakeObject(object cls, CPointer* pPtr)
{
if (!PyObject_HasAttrString(cls.ptr(), "_obj"))
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Unable to make an object using this class.");
return cls.attr("_obj")(ptr(pPtr));
}
inline object GetSize(object cls)
{
if (!PyObject_HasAttrString(cls.ptr(), "_size"))
BOOST_RAISE_EXCEPTION(PyExc_ValueError, "Unable to retrieve the size of this class.");
return cls.attr("_size");
}
#endif // _MEMORY_TOOLS_H