Updated for latest hl2sdk-dota changes.
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"
36 #define PAGE_SIZE 4096
37 #define PAGE_ALIGN_UP(x) ((x + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1))
40 #include <mach-o/dyld_images.h>
41 #include <mach-o/loader.h>
42 #include <mach-o/nlist.h>
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::FindPatternInFile(int fd, const char *pattern, size_t len, int &matches, bool &atFuncStart)
73 size = lseek (fd , 0 , SEEK_END);
79 lseek(fd, 0, SEEK_SET);
82 char *ptr, *start, *end;
84 map = mmap(0, size, PROT_READ, MAP_SHARED, fd, 0);
90 void *firstMatch = NULL;
95 for (register size_t i = 0; i < len; i++)
97 if (pattern[i] != '\x2A' && pattern[i] != ptr[i])
109 if( ptr - start >= 1 )
111 unsigned char oneBack = *(unsigned char*)((intptr_t)ptr - 1);
112 if( oneBack != 0xC3 && oneBack != 0xCB && oneBack != 0xCC )
114 if( ptr - start >= 3 )
116 unsigned char threeBack = *(unsigned char*)((intptr_t)ptr - 3);
117 if( threeBack != 0xCA && threeBack != 0xC2 )
139 void *MemoryUtils::FindPattern(const void *libPtr, const char *pattern, size_t len, int &matches, bool &atFuncStart)
149 memset(&lib, 0, sizeof(DynLibInfo));
151 if (!GetLibraryInfo(libPtr, lib))
156 void *firstMatch = NULL;
157 ptr = reinterpret_cast<char *>(lib.baseAddress);
158 end = ptr + lib.memorySize - 1;
163 for (register size_t i = 0; i < len; i++)
165 if (pattern[i] != '\x2A' && pattern[i] != ptr[i])
186 void *MemoryUtils::ResolveSymbol(void *handle, const char *symbol)
188 #ifdef PLATFORM_WINDOWS
190 return GetProcAddress((HMODULE)handle, symbol);
192 #elif defined PLATFORM_LINUX
194 struct link_map *dlmap;
198 Elf32_Ehdr *file_hdr;
199 Elf32_Shdr *sections, *shstrtab_hdr, *symtab_hdr, *strtab_hdr;
201 const char *shstrtab, *strtab;
202 uint16_t section_count;
203 uint32_t symbol_count;
204 LibSymbolTable *libtable;
207 Symbol *symbol_entry;
209 dlmap = (struct link_map *)handle;
215 /* See if we already have a symbol table for this library */
216 for (size_t i = 0; i < m_SymTables.size(); i++)
218 libtable = m_SymTables[i];
219 if (libtable->lib_base == dlmap->l_addr)
221 table = &libtable->table;
222 table2 = &libtable->table2;
227 /* If we don't have a symbol table for this library, then create one */
230 libtable = new LibSymbolTable();
231 libtable->table.Initialize();
232 libtable->table2.Initialize();
233 libtable->lib_base = dlmap->l_addr;
234 libtable->last_pos = 0;
235 table = &libtable->table;
236 table2 = &libtable->table2;
237 m_SymTables.push_back(libtable);
240 /* See if the symbol is already cached in our table */
241 symbol_entry = table->FindSymbol(symbol, strlen(symbol));
242 if (symbol_entry != NULL)
244 return symbol_entry->address;
247 /* If symbol isn't in our table, then we have open the actual library */
248 dlfile = open(dlmap->l_name, O_RDONLY);
249 if (dlfile == -1 || fstat(dlfile, &dlstat) == -1)
255 /* Map library file into memory */
256 file_hdr = (Elf32_Ehdr *)mmap(NULL, dlstat.st_size, PROT_READ, MAP_PRIVATE, dlfile, 0);
257 map_base = (uintptr_t)file_hdr;
258 if (file_hdr == MAP_FAILED)
265 if (file_hdr->e_shoff == 0 || file_hdr->e_shstrndx == SHN_UNDEF)
267 munmap(file_hdr, dlstat.st_size);
271 sections = (Elf32_Shdr *)(map_base + file_hdr->e_shoff);
272 section_count = file_hdr->e_shnum;
273 /* Get ELF section header string table */
274 shstrtab_hdr = §ions[file_hdr->e_shstrndx];
275 shstrtab = (const char *)(map_base + shstrtab_hdr->sh_offset);
277 /* Iterate sections while looking for ELF symbol table and string table */
278 for (uint16_t i = 0; i < section_count; i++)
280 Elf32_Shdr &hdr = sections[i];
281 const char *section_name = shstrtab + hdr.sh_name;
283 if (strcmp(section_name, ".symtab") == 0)
287 else if (strcmp(section_name, ".strtab") == 0)
293 /* Uh oh, we don't have a symbol table or a string table */
294 if (symtab_hdr == NULL || strtab_hdr == NULL)
296 munmap(file_hdr, dlstat.st_size);
300 symtab = (Elf32_Sym *)(map_base + symtab_hdr->sh_offset);
301 strtab = (const char *)(map_base + strtab_hdr->sh_offset);
302 symbol_count = symtab_hdr->sh_size / symtab_hdr->sh_entsize;
304 /* Iterate symbol table starting from the position we were at last time */
305 for (uint32_t i = libtable->last_pos; i < symbol_count; i++)
307 Elf32_Sym &sym = symtab[i];
308 unsigned char sym_type = ELF32_ST_TYPE(sym.st_info);
309 const char *sym_name = strtab + sym.st_name;
312 /* Skip symbols that are undefined or do not refer to functions or objects */
313 if (sym.st_shndx == SHN_UNDEF || (sym_type != STT_FUNC && sym_type != STT_OBJECT))
318 /* Caching symbols as we go along */
319 cur_sym = table->InternSymbol(sym_name, strlen(sym_name), (void *)(dlmap->l_addr + sym.st_value));
320 table2->InternSymbol(sym_name, strlen(sym_name), (void *)(dlmap->l_addr + sym.st_value));
321 if (strcmp(symbol, sym_name) == 0)
323 symbol_entry = cur_sym;
324 libtable->last_pos = ++i;
329 libtable->last_pos = symbol_count;
331 munmap(file_hdr, dlstat.st_size);
332 return symbol_entry ? symbol_entry->address : NULL;
334 #elif defined PLATFORM_APPLE
336 uintptr_t dlbase, linkedit_addr;
337 uint32_t image_count;
338 struct mach_header *file_hdr;
339 struct load_command *loadcmds;
340 struct segment_command *linkedit_hdr;
341 struct symtab_command *symtab_hdr;
342 struct nlist *symtab;
344 uint32_t loadcmd_count;
345 uint32_t symbol_count;
346 LibSymbolTable *libtable;
348 Symbol *symbol_entry;
351 image_count = m_ImageList->infoArrayCount;
356 /* Loop through mach-o images in process.
357 * We can skip index 0 since that is just the executable.
359 for (uint32_t i = 1; i < image_count; i++)
361 const struct dyld_image_info &info = m_ImageList->infoArray[i];
363 /* "Load" each one until we get a matching handle */
364 void *h = dlopen(info.imageFilePath, RTLD_NOLOAD);
367 dlbase = (uintptr_t)info.imageLoadAddress;
377 /* Uh oh, we couldn't find a matching handle */
381 /* See if we already have a symbol table for this library */
382 for (size_t i = 0; i < m_SymTables.size(); i++)
384 libtable = m_SymTables[i];
385 if (libtable->lib_base == dlbase)
387 table = &libtable->table;
392 /* If we don't have a symbol table for this library, then create one */
395 libtable = new LibSymbolTable();
396 libtable->table.Initialize();
397 libtable->lib_base = dlbase;
398 libtable->last_pos = 0;
399 table = &libtable->table;
400 m_SymTables.push_back(libtable);
403 /* See if the symbol is already cached in our table */
404 symbol_entry = table->FindSymbol(symbol, strlen(symbol));
405 if (symbol_entry != NULL)
407 return symbol_entry->address;
410 /* If symbol isn't in our table, then we have to locate it in memory */
412 file_hdr = (struct mach_header *)dlbase;
413 loadcmds = (struct load_command *)(dlbase + sizeof(struct mach_header));
414 loadcmd_count = file_hdr->ncmds;
416 /* Loop through load commands until we find the ones for the symbol table */
417 for (uint32_t i = 0; i < loadcmd_count; i++)
419 if (loadcmds->cmd == LC_SEGMENT && !linkedit_hdr)
421 struct segment_command *seg = (struct segment_command *)loadcmds;
422 if (strcmp(seg->segname, "__LINKEDIT") == 0)
431 else if (loadcmds->cmd == LC_SYMTAB)
433 symtab_hdr = (struct symtab_command *)loadcmds;
440 /* Load commands are not of a fixed size which is why we add the size */
441 loadcmds = (struct load_command *)((uintptr_t)loadcmds + loadcmds->cmdsize);
444 if (!linkedit_hdr || !symtab_hdr || !symtab_hdr->symoff || !symtab_hdr->stroff)
446 /* Uh oh, no symbol table */
450 linkedit_addr = dlbase + linkedit_hdr->vmaddr;
451 symtab = (struct nlist *)(linkedit_addr + symtab_hdr->symoff - linkedit_hdr->fileoff);
452 strtab = (const char *)(linkedit_addr + symtab_hdr->stroff - linkedit_hdr->fileoff);
453 symbol_count = symtab_hdr->nsyms;
455 /* Iterate symbol table starting from the position we were at last time */
456 for (uint32_t i = libtable->last_pos; i < symbol_count; i++)
458 struct nlist &sym = symtab[i];
459 /* Ignore the prepended underscore on all symbols, so +1 here */
460 const char *sym_name = strtab + sym.n_un.n_strx + 1;
463 /* Skip symbols that are undefined */
464 if (sym.n_sect == NO_SECT)
469 /* Caching symbols as we go along */
470 cur_sym = table->InternSymbol(sym_name, strlen(sym_name), (void *)(dlbase + sym.n_value));
471 if (strcmp(symbol, sym_name) == 0)
473 symbol_entry = cur_sym;
474 libtable->last_pos = ++i;
479 return symbol_entry ? symbol_entry->address : NULL;
484 bool MemoryUtils::GetLibraryInfo(const void *libPtr, DynLibInfo &lib)
493 #ifdef PLATFORM_WINDOWS
495 MEMORY_BASIC_INFORMATION info;
496 IMAGE_DOS_HEADER *dos;
497 IMAGE_NT_HEADERS *pe;
498 IMAGE_FILE_HEADER *file;
499 IMAGE_OPTIONAL_HEADER *opt;
501 if (!VirtualQuery(libPtr, &info, sizeof(MEMORY_BASIC_INFORMATION)))
506 baseAddr = reinterpret_cast<uintptr_t>(info.AllocationBase);
508 /* All this is for our insane sanity checks :o */
509 dos = reinterpret_cast<IMAGE_DOS_HEADER *>(baseAddr);
510 pe = reinterpret_cast<IMAGE_NT_HEADERS *>(baseAddr + dos->e_lfanew);
511 file = &pe->FileHeader;
512 opt = &pe->OptionalHeader;
514 /* Check PE magic and signature */
515 if (dos->e_magic != IMAGE_DOS_SIGNATURE || pe->Signature != IMAGE_NT_SIGNATURE || opt->Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC)
520 /* Check architecture, which is 32-bit/x86 right now
521 * Should change this for 64-bit if Valve gets their act together
523 if (file->Machine != IMAGE_FILE_MACHINE_I386)
528 /* For our purposes, this must be a dynamic library */
529 if ((file->Characteristics & IMAGE_FILE_DLL) == 0)
534 /* Finally, we can do this */
535 lib.memorySize = opt->SizeOfImage;
537 #elif defined PLATFORM_LINUX
544 if (!dladdr(libPtr, &info))
549 if (!info.dli_fbase || !info.dli_fname)
554 /* This is for our insane sanity checks :o */
555 baseAddr = reinterpret_cast<uintptr_t>(info.dli_fbase);
556 file = reinterpret_cast<Elf32_Ehdr *>(baseAddr);
558 /* Check ELF magic */
559 if (memcmp(ELFMAG, file->e_ident, SELFMAG) != 0)
564 /* Check ELF version */
565 if (file->e_ident[EI_VERSION] != EV_CURRENT)
570 /* Check ELF architecture, which is 32-bit/x86 right now
571 * Should change this for 64-bit if Valve gets their act together
573 if (file->e_ident[EI_CLASS] != ELFCLASS32 || file->e_machine != EM_386 || file->e_ident[EI_DATA] != ELFDATA2LSB)
578 /* For our purposes, this must be a dynamic library/shared object */
579 if (file->e_type != ET_DYN)
584 phdrCount = file->e_phnum;
585 phdr = reinterpret_cast<Elf32_Phdr *>(baseAddr + file->e_phoff);
587 for (uint16_t i = 0; i < phdrCount; i++)
589 Elf32_Phdr &hdr = phdr[i];
591 /* We only really care about the segment with executable code */
592 if (hdr.p_type == PT_LOAD && hdr.p_flags == (PF_X|PF_R))
594 /* From glibc, elf/dl-load.c:
595 * c->mapend = ((ph->p_vaddr + ph->p_filesz + GLRO(dl_pagesize) - 1)
596 * & ~(GLRO(dl_pagesize) - 1));
598 * In glibc, the segment file size is aligned up to the nearest page size and
599 * added to the virtual address of the segment. We just want the size here.
601 lib.memorySize = PAGE_ALIGN_UP(hdr.p_filesz);
606 #elif defined PLATFORM_APPLE
609 struct mach_header *file;
610 struct segment_command *seg;
613 if (!dladdr(libPtr, &info))
618 if (!info.dli_fbase || !info.dli_fname)
623 /* This is for our insane sanity checks :o */
624 baseAddr = (uintptr_t)info.dli_fbase;
625 file = (struct mach_header *)baseAddr;
627 /* Check Mach-O magic */
628 if (file->magic != MH_MAGIC)
633 /* Check architecture (32-bit/x86) */
634 if (file->cputype != CPU_TYPE_I386 || file->cpusubtype != CPU_SUBTYPE_I386_ALL)
639 /* For our purposes, this must be a dynamic library */
640 if (file->filetype != MH_DYLIB)
645 cmd_count = file->ncmds;
646 seg = (struct segment_command *)(baseAddr + sizeof(struct mach_header));
648 /* Add up memory sizes of mapped segments */
649 for (uint32_t i = 0; i < cmd_count; i++)
651 if (seg->cmd == LC_SEGMENT)
653 lib.memorySize += seg->vmsize;
656 seg = (struct segment_command *)((uintptr_t)seg + seg->cmdsize);
661 lib.baseAddress = reinterpret_cast<void *>(baseAddr);
666 const char* MemoryUtils::ResolveAddr(void *handle, void* addr)
668 struct link_map *dlmap;
669 dlmap = (struct link_map *)handle;
671 LibSymbolTable *libtable;
674 for (size_t i = 0; i < m_SymTables.size(); i++)
676 libtable = m_SymTables[i];
677 if (libtable->lib_base == dlmap->l_addr)
679 table2 = &libtable->table2;
684 if (table2 == NULL) return NULL;
685 Symbol *sym = table2->FindAddr(addr);
686 return sym ? sym->buffer() : NULL;