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_scanner.cpp
More file actions
310 lines (266 loc) · 8.9 KB
/
Copy pathmemory_scanner.cpp
File metadata and controls
310 lines (266 loc) · 8.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
/**
* =============================================================================
* 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 <stdio.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <fcntl.h>
#include <link.h>
#include <sys/mman.h>
#endif
#include "dynload.h"
#include "memory_scanner.h"
#include "memory_tools.h"
#include "utility/sp_util.h"
//-----------------------------------------------------------------------------
// BinaryFile class
//-----------------------------------------------------------------------------
CBinaryFile::CBinaryFile(unsigned long ulAddr, unsigned long ulSize)
{
m_ulAddr = ulAddr;
m_ulSize = ulSize;
}
CPointer* CBinaryFile::find_signature(object oSignature)
{
// This is required because there's no straight way to get a string from a python
// object from boost (without using the stl).
unsigned char* sigstr = NULL;
PyArg_Parse(oSignature.ptr(), "y", &sigstr);
if (!sigstr)
return new CPointer();
// Search for a cached signature
for (std::list<Signature_t>::iterator iter=m_Signatures.begin(); iter != m_Signatures.end(); iter++)
{
Signature_t sig = *iter;
if (strcmp((const char *) sig.m_szSignature, (const char *) sigstr) == 0)
return new CPointer(sig.m_ulAddr);
}
int iLength = len(oSignature);
unsigned char* base = (unsigned char *) m_ulAddr;
unsigned char* end = (unsigned char *) (base + m_ulSize - iLength);
while(base < end)
{
int i = 0;
for(; i < iLength; i++)
{
if (sigstr[i] == '\x2A')
continue;
if (sigstr[i] != base[i])
break;
}
if (i == iLength)
{
unsigned long ulAddr = (unsigned long) base;
// Add our signature to the cache
Signature_t sig_t = {new unsigned char[iLength+1], ulAddr};
strcpy((char*) sig_t.m_szSignature, (char*) sigstr);
m_Signatures.push_back(sig_t);
return new CPointer(ulAddr);
}
base++;
}
return new CPointer();
}
CPointer* CBinaryFile::find_symbol(char* szSymbol)
{
#ifdef _WIN32
return new CPointer((unsigned long) GetProcAddress((HMODULE) m_ulAddr, szSymbol));
#elif defined(__linux__)
// -----------------------------------------
// We need to use mmap now that VALVe has
// made them all private!
// Thank you to DamagedSoul from AlliedMods
// for the following code.
// It can be found at:
// http://hg.alliedmods.net/sourcemod-central/file/dc361050274d/core/logic/MemoryUtils.cpp
// -----------------------------------------
struct link_map *dlmap;
struct stat dlstat;
int dlfile;
uintptr_t map_base;
Elf32_Ehdr *file_hdr;
Elf32_Shdr *sections, *shstrtab_hdr, *symtab_hdr, *strtab_hdr;
Elf32_Sym *symtab;
const char *shstrtab, *strtab;
uint16_t section_count;
uint32_t symbol_count;
dlmap = (struct link_map *) m_ulAddr;
symtab_hdr = NULL;
strtab_hdr = NULL;
dlfile = open(dlmap->l_name, O_RDONLY);
if (dlfile == -1 || fstat(dlfile, &dlstat) == -1)
{
close(dlfile);
return new CPointer();
}
/* Map library file into memory */
file_hdr = (Elf32_Ehdr *)mmap(NULL, dlstat.st_size, PROT_READ, MAP_PRIVATE, dlfile, 0);
map_base = (uintptr_t)file_hdr;
if (file_hdr == MAP_FAILED)
{
close(dlfile);
return new CPointer();
}
close(dlfile);
if (file_hdr->e_shoff == 0 || file_hdr->e_shstrndx == SHN_UNDEF)
{
munmap(file_hdr, dlstat.st_size);
return new CPointer();
}
sections = (Elf32_Shdr *)(map_base + file_hdr->e_shoff);
section_count = file_hdr->e_shnum;
/* Get ELF section header string table */
shstrtab_hdr = §ions[file_hdr->e_shstrndx];
shstrtab = (const char *)(map_base + shstrtab_hdr->sh_offset);
/* Iterate sections while looking for ELF symbol table and string table */
for (uint16_t i = 0; i < section_count; i++)
{
Elf32_Shdr &hdr = sections[i];
const char *section_name = shstrtab + hdr.sh_name;
if (strcmp(section_name, ".symtab") == 0)
symtab_hdr = &hdr;
else if (strcmp(section_name, ".strtab") == 0)
strtab_hdr = &hdr;
}
/* Uh oh, we don't have a symbol table or a string table */
if (symtab_hdr == NULL || strtab_hdr == NULL)
{
munmap(file_hdr, dlstat.st_size);
return new CPointer();
}
symtab = (Elf32_Sym *)(map_base + symtab_hdr->sh_offset);
strtab = (const char *)(map_base + strtab_hdr->sh_offset);
symbol_count = symtab_hdr->sh_size / symtab_hdr->sh_entsize;
void* sym_addr = NULL;
/* Iterate symbol table starting from the position we were at last time */
for (uint32_t i = 0; i < symbol_count; i++)
{
Elf32_Sym &sym = symtab[i];
unsigned char sym_type = ELF32_ST_TYPE(sym.st_info);
const char *sym_name = strtab + sym.st_name;
/* Skip symbols that are undefined or do not refer to functions or objects */
if (sym.st_shndx == SHN_UNDEF || (sym_type != STT_FUNC && sym_type != STT_OBJECT))
continue;
if (strcmp(szSymbol, sym_name) == 0)
{
sym_addr = (void *)(dlmap->l_addr + sym.st_value);
break;
}
}
// Unmap the file now.
munmap(file_hdr, dlstat.st_size);
return new CPointer((unsigned long) sym_addr);
#else
#error "BinaryFile::find_symbol() is not implemented on this OS"
#endif
}
CPointer* CBinaryFile::find_pointer(object oIdentifier, int iOffset)
{
CPointer* ptr = find_address(oIdentifier);
return ptr->is_valid() ? ptr->get_ptr(iOffset) : ptr;
}
CPointer* CBinaryFile::find_address(object oIdentifier)
{
#ifdef _WIN32
if(CheckClassname(oIdentifier, "bytes"))
return find_signature(oIdentifier);
#endif
return find_symbol(extract<char*>(oIdentifier));
}
//-----------------------------------------------------------------------------
// CBinaryManager class
//-----------------------------------------------------------------------------
// Small helper function
bool str_ends_with(const char *szString, const char *szSuffix)
{
int stringlen = strlen(szString);
int suffixlen = strlen(szSuffix);
if (suffixlen > stringlen)
return false;
return strncmp(szString + stringlen - suffixlen, szSuffix, suffixlen) == 0;
}
CBinaryFile* CBinaryManager::find_binary(char* szPath, bool bSrvCheck /* = true */)
{
std::string szBinaryPath = szPath;
#ifdef __linux__
if (bSrvCheck && !str_ends_with(szBinaryPath.data(), "_srv"))
szBinaryPath += "_srv.so";
else if (!str_ends_with(szBinaryPath.data(), ".so"))
szBinaryPath += ".so";
#endif
unsigned long ulAddr = (unsigned long) dlLoadLibrary(szBinaryPath.data());
if (!ulAddr)
{
szBinaryPath = "Unable to find " + szBinaryPath;
#ifdef _WIN32
if (!str_ends_with(szBinaryPath.data(), ".dll"))
szBinaryPath += ".dll";
#endif
BOOST_RAISE_EXCEPTION(PyExc_IOError, szBinaryPath.data())
}
// Search for an existing BinaryFile object
for (std::list<CBinaryFile *>::iterator iter=m_Binaries.begin(); iter != m_Binaries.end(); iter++)
{
CBinaryFile* binary = *iter;
if (binary->get_address() == ulAddr)
{
// We don't need to open it several times
dlFreeLibrary((DLLib *) ulAddr);
return binary;
}
}
unsigned long ulSize;
#ifdef _WIN32
IMAGE_DOS_HEADER* dos = (IMAGE_DOS_HEADER *) ulAddr;
IMAGE_NT_HEADERS* nt = (IMAGE_NT_HEADERS *) ((BYTE *) dos + dos->e_lfanew);
ulSize = nt->OptionalHeader.SizeOfImage;
#elif defined(__linux__)
// TODO: Retrieve whole size
struct stat buf;
if (stat(szBinaryPath.data(), &buf) == -1)
{
dlFreeLibrary((DLLib *) ulAddr);
return NULL;
}
ulSize = buf.st_size;
#else
#error "BinaryManager::find_binary() is not implemented on this OS"
#endif
// Create a new Binary object and add it to the list
CBinaryFile* binary = new CBinaryFile(ulAddr, ulSize);
m_Binaries.push_front(binary);
return binary;
}
//-----------------------------------------------------------------------------
// Functions
//-----------------------------------------------------------------------------
CBinaryFile* find_binary(char* szPath, bool bSrvCheck /* = true */)
{
return s_pBinaryManager->find_binary(szPath, bSrvCheck);
}