2 * vim: set ts=4 sw=4 tw=99 noet :
3 * =============================================================================
5 * Copyright (C) 2004-2010 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
30 #include "MemoryUtils.h"
38 #include <mach-o/dyld_images.h>
39 #include <mach-o/loader.h>
40 #include <mach-o/nlist.h>
43 MemoryUtils g_MemUtils;
45 MemoryUtils::MemoryUtils()
49 /* Get pointer to struct that describes all loaded mach-o images in process */
51 memset(list, 0, sizeof(list));
52 list[0].n_un.n_name = (char *)"_dyld_all_image_infos";
53 nlist("/usr/lib/dyld", list);
54 m_ImageList = (struct dyld_all_image_infos *)list[0].n_value;
59 MemoryUtils::~MemoryUtils()
61 #if defined PLATFORM_LINUX || defined PLATFORM_APPLE
62 for (size_t i = 0; i < m_SymTables.size(); i++)
64 delete m_SymTables[i];
70 void MemoryUtils::OnSourceModAllInitialized()
72 g_ShareSys.AddInterface(NULL, this);
75 void *MemoryUtils::FindPattern(const void *libPtr, const char *pattern, size_t len)
81 memset(&lib, 0, sizeof(DynLibInfo));
83 if (!GetLibraryInfo(libPtr, lib))
88 ptr = reinterpret_cast<char *>(lib.baseAddress);
89 end = ptr + lib.memorySize;
94 for (register size_t i = 0; i < len; i++)
96 if (pattern[i] != '\x2A' && pattern[i] != ptr[i])
112 void *MemoryUtils::ResolveSymbol(void *handle, const char *symbol)
114 #ifdef PLATFORM_WINDOWS
116 return GetProcAddress((HMODULE)handle, symbol);
118 #elif defined PLATFORM_LINUX
120 struct link_map *dlmap;
124 Elf32_Ehdr *file_hdr;
125 Elf32_Shdr *sections, *shstrtab_hdr, *symtab_hdr, *strtab_hdr;
127 const char *shstrtab, *strtab;
128 uint16_t section_count;
129 uint32_t symbol_count;
130 LibSymbolTable *libtable;
132 Symbol *symbol_entry;
134 dlmap = (struct link_map *)handle;
139 /* See if we already have a symbol table for this library */
140 for (size_t i = 0; i < m_SymTables.size(); i++)
142 libtable = m_SymTables[i];
143 if (libtable->lib_base == dlmap->l_addr)
145 table = &libtable->table;
150 /* If we don't have a symbol table for this library, then create one */
153 libtable = new LibSymbolTable();
154 libtable->table.Initialize();
155 libtable->lib_base = dlmap->l_addr;
156 libtable->last_pos = 0;
157 table = &libtable->table;
158 m_SymTables.push_back(libtable);
161 /* See if the symbol is already cached in our table */
162 symbol_entry = table->FindSymbol(symbol, strlen(symbol));
163 if (symbol_entry != NULL)
165 return symbol_entry->address;
168 /* If symbol isn't in our table, then we have open the actual library */
169 dlfile = open(dlmap->l_name, O_RDONLY);
170 if (dlfile == -1 || fstat(dlfile, &dlstat) == -1)
176 /* Map library file into memory */
177 file_hdr = (Elf32_Ehdr *)mmap(NULL, dlstat.st_size, PROT_READ, MAP_PRIVATE, dlfile, 0);
178 map_base = (uintptr_t)file_hdr;
179 if (file_hdr == MAP_FAILED)
186 if (file_hdr->e_shoff == 0 || file_hdr->e_shstrndx == SHN_UNDEF)
188 munmap(file_hdr, dlstat.st_size);
192 sections = (Elf32_Shdr *)(map_base + file_hdr->e_shoff);
193 section_count = file_hdr->e_shnum;
194 /* Get ELF section header string table */
195 shstrtab_hdr = §ions[file_hdr->e_shstrndx];
196 shstrtab = (const char *)(map_base + shstrtab_hdr->sh_offset);
198 /* Iterate sections while looking for ELF symbol table and string table */
199 for (uint16_t i = 0; i < section_count; i++)
201 Elf32_Shdr &hdr = sections[i];
202 const char *section_name = shstrtab + hdr.sh_name;
204 if (strcmp(section_name, ".symtab") == 0)
208 else if (strcmp(section_name, ".strtab") == 0)
214 /* Uh oh, we don't have a symbol table or a string table */
215 if (symtab_hdr == NULL || strtab_hdr == NULL)
217 munmap(file_hdr, dlstat.st_size);
221 symtab = (Elf32_Sym *)(map_base + symtab_hdr->sh_offset);
222 strtab = (const char *)(map_base + strtab_hdr->sh_offset);
223 symbol_count = symtab_hdr->sh_size / symtab_hdr->sh_entsize;
225 /* Iterate symbol table starting from the position we were at last time */
226 for (uint32_t i = libtable->last_pos; i < symbol_count; i++)
228 Elf32_Sym &sym = symtab[i];
229 unsigned char sym_type = ELF32_ST_TYPE(sym.st_info);
230 const char *sym_name = strtab + sym.st_name;
233 /* Skip symbols that are undefined or do not refer to functions or objects */
234 if (sym.st_shndx == SHN_UNDEF || (sym_type != STT_FUNC && sym_type != STT_OBJECT))
239 /* Caching symbols as we go along */
240 cur_sym = table->InternSymbol(sym_name, strlen(sym_name), (void *)(dlmap->l_addr + sym.st_value));
241 if (strcmp(symbol, sym_name) == 0)
243 symbol_entry = cur_sym;
244 libtable->last_pos = ++i;
249 munmap(file_hdr, dlstat.st_size);
250 return symbol_entry ? symbol_entry->address : NULL;
252 #elif defined PLATFORM_APPLE
255 uint32_t image_count;
256 struct mach_header *file_hdr;
257 struct load_command *loadcmds;
258 struct symtab_command *symtab_hdr;
259 struct nlist *symtab;
261 uint32_t loadcmd_count;
262 uint32_t symbol_count;
263 LibSymbolTable *libtable;
265 Symbol *symbol_entry;
268 image_count = m_ImageList->infoArrayCount;
271 /* Loop through mach-o images in process.
272 * We can skip index 0 since that is just the executable.
274 for (uint32_t i = 1; i < image_count; i++)
276 const struct dyld_image_info &info = m_ImageList->infoArray[i];
278 /* "Load" each one until we get a matching handle */
279 void *h = dlopen(info.imageFilePath, RTLD_NOLOAD);
282 dlbase = (uintptr_t)info.imageLoadAddress;
292 /* Uh oh, we couldn't find a matching handle */
296 /* See if we already have a symbol table for this library */
297 for (size_t i = 0; i < m_SymTables.size(); i++)
299 libtable = m_SymTables[i];
300 if (libtable->lib_base == dlbase)
302 table = &libtable->table;
307 /* If we don't have a symbol table for this library, then create one */
310 libtable = new LibSymbolTable();
311 libtable->table.Initialize();
312 libtable->lib_base = dlbase;
313 libtable->last_pos = 0;
314 table = &libtable->table;
315 m_SymTables.push_back(libtable);
318 /* See if the symbol is already cached in our table */
319 symbol_entry = table->FindSymbol(symbol, strlen(symbol));
320 if (symbol_entry != NULL)
322 return symbol_entry->address;
325 /* If symbol isn't in our table, then we have to locate it in memory */
327 file_hdr = (struct mach_header *)dlbase;
328 loadcmds = (struct load_command *)(dlbase + sizeof(struct mach_header));
329 loadcmd_count = file_hdr->ncmds;
331 /* Loop through load commands until we find the one for the symbol table */
332 for (uint32_t i = 0; i < loadcmd_count; i++)
334 if (loadcmds->cmd == LC_SYMTAB)
336 symtab_hdr = (struct symtab_command *)loadcmds;
340 /* Load commands are not of a fixed size which is why we add the size */
341 loadcmds = (struct load_command *)((uintptr_t)loadcmds + loadcmds->cmdsize);
344 if (!symtab_hdr || !symtab_hdr->symoff || !symtab_hdr->stroff)
346 /* Uh oh, no symbol table */
350 symtab = (struct nlist *)(dlbase + symtab_hdr->symoff);
351 strtab = (const char *)(dlbase + symtab_hdr->stroff);
352 symbol_count = symtab_hdr->nsyms;
354 /* Iterate symbol table starting from the position we were at last time */
355 for (uint32_t i = libtable->last_pos; i < symbol_count; i++)
357 struct nlist &sym = symtab[i];
358 /* Ignore the prepended underscore on all symbols, so +1 here */
359 const char *sym_name = strtab + sym.n_un.n_strx + 1;
362 /* Skip symbols that are undefined */
363 if (sym.n_sect == NO_SECT)
368 /* Caching symbols as we go along */
369 cur_sym = table->InternSymbol(sym_name, strlen(sym_name), (void *)(dlbase + sym.n_value));
370 if (strcmp(symbol, sym_name) == 0)
372 symbol_entry = cur_sym;
373 libtable->last_pos = ++i;
378 return symbol_entry ? symbol_entry->address : NULL;
383 bool MemoryUtils::GetLibraryInfo(const void *libPtr, DynLibInfo &lib)
392 #ifdef PLATFORM_WINDOWS
394 MEMORY_BASIC_INFORMATION info;
395 IMAGE_DOS_HEADER *dos;
396 IMAGE_NT_HEADERS *pe;
397 IMAGE_FILE_HEADER *file;
398 IMAGE_OPTIONAL_HEADER *opt;
400 if (!VirtualQuery(libPtr, &info, sizeof(MEMORY_BASIC_INFORMATION)))
405 baseAddr = reinterpret_cast<uintptr_t>(info.AllocationBase);
407 /* All this is for our insane sanity checks :o */
408 dos = reinterpret_cast<IMAGE_DOS_HEADER *>(baseAddr);
409 pe = reinterpret_cast<IMAGE_NT_HEADERS *>(baseAddr + dos->e_lfanew);
410 file = &pe->FileHeader;
411 opt = &pe->OptionalHeader;
413 /* Check PE magic and signature */
414 if (dos->e_magic != IMAGE_DOS_SIGNATURE || pe->Signature != IMAGE_NT_SIGNATURE || opt->Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC)
419 /* Check architecture, which is 32-bit/x86 right now
420 * Should change this for 64-bit if Valve gets their act together
422 if (file->Machine != IMAGE_FILE_MACHINE_I386)
427 /* For our purposes, this must be a dynamic library */
428 if ((file->Characteristics & IMAGE_FILE_DLL) == 0)
433 /* Finally, we can do this */
434 lib.memorySize = opt->SizeOfImage;
436 #elif defined PLATFORM_LINUX
443 if (!dladdr(libPtr, &info))
448 if (!info.dli_fbase || !info.dli_fname)
453 /* This is for our insane sanity checks :o */
454 baseAddr = reinterpret_cast<uintptr_t>(info.dli_fbase);
455 file = reinterpret_cast<Elf32_Ehdr *>(baseAddr);
457 /* Check ELF magic */
458 if (memcmp(ELFMAG, file->e_ident, SELFMAG) != 0)
463 /* Check ELF version */
464 if (file->e_ident[EI_VERSION] != EV_CURRENT)
469 /* Check ELF architecture, which is 32-bit/x86 right now
470 * Should change this for 64-bit if Valve gets their act together
472 if (file->e_ident[EI_CLASS] != ELFCLASS32 || file->e_machine != EM_386 || file->e_ident[EI_DATA] != ELFDATA2LSB)
477 /* For our purposes, this must be a dynamic library/shared object */
478 if (file->e_type != ET_DYN)
483 phdrCount = file->e_phnum;
484 phdr = reinterpret_cast<Elf32_Phdr *>(baseAddr + file->e_phoff);
486 /* Add up the memory sizes of segments marked as PT_LOAD as those are the only ones that should be in memory */
487 for (uint16_t i = 0; i < phdrCount; i++)
489 Elf32_Phdr &hdr = phdr[i];
491 if (hdr.p_type == PT_LOAD)
493 lib.memorySize += hdr.p_memsz;
497 #elif defined PLATFORM_APPLE
500 struct mach_header *file;
501 struct segment_command *seg;
504 if (!dladdr(libPtr, &info))
509 if (!info.dli_fbase || !info.dli_fname)
514 /* This is for our insane sanity checks :o */
515 baseAddr = (uintptr_t)info.dli_fbase;
516 file = (struct mach_header *)baseAddr;
518 /* Check Mach-O magic */
519 if (file->magic != MH_MAGIC)
524 /* Check architecture (32-bit/x86) */
525 if (file->cputype != CPU_TYPE_I386 || file->cpusubtype != CPU_SUBTYPE_I386_ALL)
530 /* For our purposes, this must be a dynamic library */
531 if (file->filetype != MH_DYLIB)
536 cmd_count = file->ncmds;
537 seg = (struct segment_command *)(baseAddr + sizeof(struct mach_header));
539 /* Add up memory sizes of mapped segments */
540 for (uint32_t i = 0; i < cmd_count; i++)
542 if (seg->cmd == LC_SEGMENT)
544 lib.memorySize += seg->vmsize;
547 seg = (struct segment_command *)((uintptr_t)seg + seg->cmdsize);
552 lib.baseAddress = reinterpret_cast<void *>(baseAddr);