ds@700: /**
ds@2863: * vim: set ts=4 sw=4 tw=99 noet :
ds@1330: * =============================================================================
dvander@1231: * SourceMod
ds@2992: * Copyright (C) 2004-2010 AlliedModders LLC. All rights reserved.
ds@1330: * =============================================================================
ds@700: *
ds@1330: * This program is free software; you can redistribute it and/or modify it under
ds@1330: * the terms of the GNU General Public License, version 3.0, as published by the
ds@1330: * Free Software Foundation.
dvander@1231: *
ds@1330: * This program is distributed in the hope that it will be useful, but WITHOUT
ds@1330: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
ds@1330: * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
ds@1330: * details.
dvander@1231: *
ds@1330: * You should have received a copy of the GNU General Public License along with
ds@1330: * this program. If not, see .
dvander@1231: *
ds@1330: * As a special exception, AlliedModders LLC gives you permission to link the
ds@1330: * code of this program (as well as its derivative works) to "Half-Life 2," the
ds@1330: * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
ds@1330: * by the Valve Corporation. You must obey the GNU General Public License in
ds@1330: * all respects for all other code used. Additionally, AlliedModders LLC grants
ds@1330: * this exception to all derivative works. AlliedModders LLC defines further
ds@1330: * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
ds@1330: * or .
ds@700: */
ds@700:
ds@700: #include "MemoryUtils.h"
ds@700: #ifdef PLATFORM_LINUX
ds@2863: #include
ds@2863: #include
ds@2863: #include
ds@3103:
ds@3103: #define PAGE_SIZE 4096
ds@3103: #define PAGE_ALIGN_UP(x) ((x + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1))
ds@700: #endif
ds@2992: #ifdef PLATFORM_APPLE
ds@2992: #include
ds@2992: #include
ds@2992: #include
ds@2992: #endif
ds@700:
ds@700: MemoryUtils g_MemUtils;
ds@700:
ds@700: MemoryUtils::MemoryUtils()
ds@700: {
ds@2992: #ifdef PLATFORM_APPLE
ds@700:
ds@2992: /* Get pointer to struct that describes all loaded mach-o images in process */
ds@2992: struct nlist list[2];
ds@2992: memset(list, 0, sizeof(list));
ds@2992: list[0].n_un.n_name = (char *)"_dyld_all_image_infos";
ds@2992: nlist("/usr/lib/dyld", list);
ds@2992: m_ImageList = (struct dyld_all_image_infos *)list[0].n_value;
ds@700:
ds@700: #endif
ds@700: }
ds@700:
ds@2863: MemoryUtils::~MemoryUtils()
ds@2863: {
ds@2992: #if defined PLATFORM_LINUX || defined PLATFORM_APPLE
ds@2863: for (size_t i = 0; i < m_SymTables.size(); i++)
ds@2863: {
ds@2863: delete m_SymTables[i];
ds@2863: }
ds@2863: m_SymTables.clear();
ds@2863: #endif
ds@2863: }
ds@2863:
ds@702: void MemoryUtils::OnSourceModAllInitialized()
ds@702: {
dvander@2999: sharesys->AddInterface(NULL, this);
ds@702: }
ds@702:
ds@701: void *MemoryUtils::FindPattern(const void *libPtr, const char *pattern, size_t len)
ds@700: {
ds@700: DynLibInfo lib;
ds@700: bool found;
ds@700: char *ptr, *end;
ds@700:
ds@700: memset(&lib, 0, sizeof(DynLibInfo));
ds@700:
ds@700: if (!GetLibraryInfo(libPtr, lib))
ds@700: {
ds@700: return NULL;
ds@700: }
ds@700:
ds@700: ptr = reinterpret_cast(lib.baseAddress);
ds@700: end = ptr + lib.memorySize;
ds@700:
ds@700: while (ptr < end)
ds@700: {
ds@700: found = true;
ds@700: for (register size_t i = 0; i < len; i++)
ds@700: {
ds@700: if (pattern[i] != '\x2A' && pattern[i] != ptr[i])
ds@700: {
ds@700: found = false;
ds@700: break;
ds@700: }
ds@700: }
ds@700:
ds@700: if (found)
ds@700: return ptr;
ds@700:
ds@700: ptr++;
ds@700: }
ds@700:
ds@700: return NULL;
ds@700: }
ds@700:
ds@2863: void *MemoryUtils::ResolveSymbol(void *handle, const char *symbol)
ds@2863: {
ds@2863: #ifdef PLATFORM_WINDOWS
ds@2863:
ds@2863: return GetProcAddress((HMODULE)handle, symbol);
ds@2992:
ds@2863: #elif defined PLATFORM_LINUX
ds@2863:
ds@2863: struct link_map *dlmap;
ds@2863: struct stat dlstat;
ds@2863: int dlfile;
ds@2863: uintptr_t map_base;
ds@2863: Elf32_Ehdr *file_hdr;
ds@2863: Elf32_Shdr *sections, *shstrtab_hdr, *symtab_hdr, *strtab_hdr;
ds@2863: Elf32_Sym *symtab;
ds@2863: const char *shstrtab, *strtab;
ds@2863: uint16_t section_count;
ds@2863: uint32_t symbol_count;
ds@2863: LibSymbolTable *libtable;
ds@2863: SymbolTable *table;
ds@2863: Symbol *symbol_entry;
ds@2863:
ds@2863: dlmap = (struct link_map *)handle;
ds@2863: symtab_hdr = NULL;
ds@2863: strtab_hdr = NULL;
ds@2863: table = NULL;
ds@2863:
ds@2863: /* See if we already have a symbol table for this library */
ds@2863: for (size_t i = 0; i < m_SymTables.size(); i++)
ds@2863: {
ds@2863: libtable = m_SymTables[i];
ds@2863: if (libtable->lib_base == dlmap->l_addr)
ds@2863: {
ds@2863: table = &libtable->table;
ds@2863: break;
ds@2863: }
ds@2863: }
ds@2863:
ds@2863: /* If we don't have a symbol table for this library, then create one */
ds@2863: if (table == NULL)
ds@2863: {
ds@2863: libtable = new LibSymbolTable();
ds@2863: libtable->table.Initialize();
ds@2863: libtable->lib_base = dlmap->l_addr;
ds@2863: libtable->last_pos = 0;
ds@2863: table = &libtable->table;
ds@2863: m_SymTables.push_back(libtable);
ds@2863: }
ds@2863:
ds@2863: /* See if the symbol is already cached in our table */
ds@2863: symbol_entry = table->FindSymbol(symbol, strlen(symbol));
ds@2863: if (symbol_entry != NULL)
ds@2863: {
ds@2863: return symbol_entry->address;
ds@2863: }
ds@2863:
ds@2863: /* If symbol isn't in our table, then we have open the actual library */
ds@2863: dlfile = open(dlmap->l_name, O_RDONLY);
ds@2863: if (dlfile == -1 || fstat(dlfile, &dlstat) == -1)
ds@2863: {
ds@2863: close(dlfile);
ds@2863: return NULL;
ds@2863: }
ds@2863:
ds@2863: /* Map library file into memory */
ds@2863: file_hdr = (Elf32_Ehdr *)mmap(NULL, dlstat.st_size, PROT_READ, MAP_PRIVATE, dlfile, 0);
ds@2863: map_base = (uintptr_t)file_hdr;
ds@2863: if (file_hdr == MAP_FAILED)
ds@2863: {
ds@2863: close(dlfile);
ds@2863: return NULL;
ds@2863: }
ds@2863: close(dlfile);
ds@2863:
ds@2863: if (file_hdr->e_shoff == 0 || file_hdr->e_shstrndx == SHN_UNDEF)
ds@2863: {
ds@2863: munmap(file_hdr, dlstat.st_size);
ds@2863: return NULL;
ds@2863: }
ds@2863:
ds@2863: sections = (Elf32_Shdr *)(map_base + file_hdr->e_shoff);
ds@2863: section_count = file_hdr->e_shnum;
ds@2863: /* Get ELF section header string table */
ds@2863: shstrtab_hdr = §ions[file_hdr->e_shstrndx];
ds@2863: shstrtab = (const char *)(map_base + shstrtab_hdr->sh_offset);
ds@2863:
ds@2863: /* Iterate sections while looking for ELF symbol table and string table */
ds@2863: for (uint16_t i = 0; i < section_count; i++)
ds@2863: {
ds@2863: Elf32_Shdr &hdr = sections[i];
ds@2863: const char *section_name = shstrtab + hdr.sh_name;
ds@2863:
ds@2863: if (strcmp(section_name, ".symtab") == 0)
ds@2863: {
ds@2863: symtab_hdr = &hdr;
ds@2863: }
ds@2863: else if (strcmp(section_name, ".strtab") == 0)
ds@2863: {
ds@2863: strtab_hdr = &hdr;
ds@2863: }
ds@2863: }
ds@2863:
ds@2863: /* Uh oh, we don't have a symbol table or a string table */
ds@2863: if (symtab_hdr == NULL || strtab_hdr == NULL)
ds@2863: {
ds@2863: munmap(file_hdr, dlstat.st_size);
ds@2863: return NULL;
ds@2863: }
ds@2863:
ds@2863: symtab = (Elf32_Sym *)(map_base + symtab_hdr->sh_offset);
ds@2863: strtab = (const char *)(map_base + strtab_hdr->sh_offset);
ds@2863: symbol_count = symtab_hdr->sh_size / symtab_hdr->sh_entsize;
ds@2863:
ds@2863: /* Iterate symbol table starting from the position we were at last time */
ds@2863: for (uint32_t i = libtable->last_pos; i < symbol_count; i++)
ds@2863: {
ds@2863: Elf32_Sym &sym = symtab[i];
ds@2863: unsigned char sym_type = ELF32_ST_TYPE(sym.st_info);
ds@2863: const char *sym_name = strtab + sym.st_name;
ds@2863: Symbol *cur_sym;
ds@2863:
ds@2863: /* Skip symbols that are undefined or do not refer to functions or objects */
ds@2863: if (sym.st_shndx == SHN_UNDEF || (sym_type != STT_FUNC && sym_type != STT_OBJECT))
ds@2863: {
ds@2863: continue;
ds@2863: }
ds@2863:
ds@2863: /* Caching symbols as we go along */
ds@2863: cur_sym = table->InternSymbol(sym_name, strlen(sym_name), (void *)(dlmap->l_addr + sym.st_value));
ds@2863: if (strcmp(symbol, sym_name) == 0)
ds@2863: {
ds@2863: symbol_entry = cur_sym;
ds@2863: libtable->last_pos = ++i;
ds@2863: break;
ds@2863: }
ds@2863: }
ds@2863:
ds@2863: munmap(file_hdr, dlstat.st_size);
ds@2863: return symbol_entry ? symbol_entry->address : NULL;
ds@2863:
ds@2992: #elif defined PLATFORM_APPLE
ds@2992:
ds@3037: uintptr_t dlbase, linkedit_addr;
ds@2992: uint32_t image_count;
ds@2992: struct mach_header *file_hdr;
ds@2992: struct load_command *loadcmds;
ds@3037: struct segment_command *linkedit_hdr;
ds@2992: struct symtab_command *symtab_hdr;
ds@2992: struct nlist *symtab;
ds@2992: const char *strtab;
ds@2992: uint32_t loadcmd_count;
ds@2992: uint32_t symbol_count;
ds@2992: LibSymbolTable *libtable;
ds@2992: SymbolTable *table;
ds@2992: Symbol *symbol_entry;
ds@2992:
ds@2992: dlbase = 0;
ds@2992: image_count = m_ImageList->infoArrayCount;
ds@3037: linkedit_hdr = NULL;
ds@2992: symtab_hdr = NULL;
ds@3037: table = NULL;
ds@2992:
ds@2992: /* Loop through mach-o images in process.
ds@2992: * We can skip index 0 since that is just the executable.
ds@2992: */
ds@2992: for (uint32_t i = 1; i < image_count; i++)
ds@2992: {
ds@2992: const struct dyld_image_info &info = m_ImageList->infoArray[i];
ds@2992:
ds@2992: /* "Load" each one until we get a matching handle */
ds@2992: void *h = dlopen(info.imageFilePath, RTLD_NOLOAD);
ds@2992: if (h == handle)
ds@2992: {
ds@2992: dlbase = (uintptr_t)info.imageLoadAddress;
ds@2992: dlclose(h);
ds@2992: break;
ds@2992: }
ds@2992:
ds@2992: dlclose(h);
ds@2992: }
ds@2992:
ds@2992: if (!dlbase)
ds@2992: {
ds@2992: /* Uh oh, we couldn't find a matching handle */
ds@2992: return NULL;
ds@2992: }
ds@2992:
ds@2992: /* See if we already have a symbol table for this library */
ds@2992: for (size_t i = 0; i < m_SymTables.size(); i++)
ds@2992: {
ds@2992: libtable = m_SymTables[i];
ds@2992: if (libtable->lib_base == dlbase)
ds@2992: {
ds@2992: table = &libtable->table;
ds@2992: break;
ds@2992: }
ds@2992: }
ds@2992:
ds@2992: /* If we don't have a symbol table for this library, then create one */
ds@2992: if (table == NULL)
ds@2992: {
ds@2992: libtable = new LibSymbolTable();
ds@2992: libtable->table.Initialize();
ds@2992: libtable->lib_base = dlbase;
ds@2992: libtable->last_pos = 0;
ds@2992: table = &libtable->table;
ds@2992: m_SymTables.push_back(libtable);
ds@2992: }
ds@2992:
ds@2992: /* See if the symbol is already cached in our table */
ds@2992: symbol_entry = table->FindSymbol(symbol, strlen(symbol));
ds@2992: if (symbol_entry != NULL)
ds@2992: {
ds@2992: return symbol_entry->address;
ds@2992: }
ds@2992:
ds@2992: /* If symbol isn't in our table, then we have to locate it in memory */
ds@2992:
ds@2992: file_hdr = (struct mach_header *)dlbase;
ds@2992: loadcmds = (struct load_command *)(dlbase + sizeof(struct mach_header));
ds@2992: loadcmd_count = file_hdr->ncmds;
ds@2992:
ds@3037: /* Loop through load commands until we find the ones for the symbol table */
ds@2992: for (uint32_t i = 0; i < loadcmd_count; i++)
ds@2992: {
ds@3037: if (loadcmds->cmd == LC_SEGMENT && !linkedit_hdr)
ds@3037: {
ds@3037: struct segment_command *seg = (struct segment_command *)loadcmds;
ds@3037: if (strcmp(seg->segname, "__LINKEDIT") == 0)
ds@3037: {
ds@3037: linkedit_hdr = seg;
ds@3037: if (symtab_hdr)
ds@3037: {
ds@3037: break;
ds@3037: }
ds@3037: }
ds@3037: }
ds@3037: else if (loadcmds->cmd == LC_SYMTAB)
ds@2992: {
ds@2992: symtab_hdr = (struct symtab_command *)loadcmds;
ds@3037: if (linkedit_hdr)
ds@3037: {
ds@3037: break;
ds@3037: }
ds@2992: }
ds@3037:
ds@2992: /* Load commands are not of a fixed size which is why we add the size */
ds@2992: loadcmds = (struct load_command *)((uintptr_t)loadcmds + loadcmds->cmdsize);
ds@2992: }
ds@2992:
ds@3037: if (!linkedit_hdr || !symtab_hdr || !symtab_hdr->symoff || !symtab_hdr->stroff)
ds@2992: {
ds@2992: /* Uh oh, no symbol table */
ds@2992: return NULL;
ds@2992: }
ds@3037:
ds@3037: linkedit_addr = dlbase + linkedit_hdr->vmaddr;
ds@3037: symtab = (struct nlist *)(linkedit_addr + symtab_hdr->symoff - linkedit_hdr->fileoff);
ds@3037: strtab = (const char *)(linkedit_addr + symtab_hdr->stroff - linkedit_hdr->fileoff);
ds@2992: symbol_count = symtab_hdr->nsyms;
ds@2992:
ds@2992: /* Iterate symbol table starting from the position we were at last time */
ds@2992: for (uint32_t i = libtable->last_pos; i < symbol_count; i++)
ds@2992: {
ds@2992: struct nlist &sym = symtab[i];
ds@2992: /* Ignore the prepended underscore on all symbols, so +1 here */
ds@2992: const char *sym_name = strtab + sym.n_un.n_strx + 1;
ds@2992: Symbol *cur_sym;
ds@2992:
ds@2992: /* Skip symbols that are undefined */
ds@2992: if (sym.n_sect == NO_SECT)
ds@2992: {
ds@2992: continue;
ds@2992: }
ds@2992:
ds@2992: /* Caching symbols as we go along */
ds@2992: cur_sym = table->InternSymbol(sym_name, strlen(sym_name), (void *)(dlbase + sym.n_value));
ds@2992: if (strcmp(symbol, sym_name) == 0)
ds@2992: {
ds@2992: symbol_entry = cur_sym;
ds@2992: libtable->last_pos = ++i;
ds@2992: break;
ds@2992: }
ds@2992: }
ds@2992:
ds@2992: return symbol_entry ? symbol_entry->address : NULL;
ds@2992:
ds@2863: #endif
ds@2863: }
ds@2863:
ds@701: bool MemoryUtils::GetLibraryInfo(const void *libPtr, DynLibInfo &lib)
ds@700: {
ds@2992: uintptr_t baseAddr;
ds@700:
ds@700: if (libPtr == NULL)
ds@700: {
ds@700: return false;
ds@700: }
ds@700:
ds@700: #ifdef PLATFORM_WINDOWS
ds@700:
ds@700: MEMORY_BASIC_INFORMATION info;
ds@700: IMAGE_DOS_HEADER *dos;
ds@700: IMAGE_NT_HEADERS *pe;
ds@700: IMAGE_FILE_HEADER *file;
ds@700: IMAGE_OPTIONAL_HEADER *opt;
ds@700:
ds@700: if (!VirtualQuery(libPtr, &info, sizeof(MEMORY_BASIC_INFORMATION)))
ds@700: {
ds@700: return false;
ds@700: }
ds@700:
ds@2992: baseAddr = reinterpret_cast(info.AllocationBase);
ds@700:
ds@700: /* All this is for our insane sanity checks :o */
ds@700: dos = reinterpret_cast(baseAddr);
ds@700: pe = reinterpret_cast(baseAddr + dos->e_lfanew);
ds@700: file = &pe->FileHeader;
ds@700: opt = &pe->OptionalHeader;
ds@700:
ds@700: /* Check PE magic and signature */
ds@700: if (dos->e_magic != IMAGE_DOS_SIGNATURE || pe->Signature != IMAGE_NT_SIGNATURE || opt->Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC)
ds@700: {
ds@700: return false;
ds@700: }
ds@700:
ds@700: /* Check architecture, which is 32-bit/x86 right now
ds@700: * Should change this for 64-bit if Valve gets their act together
ds@700: */
ds@700: if (file->Machine != IMAGE_FILE_MACHINE_I386)
ds@700: {
ds@700: return false;
ds@700: }
ds@700:
ds@700: /* For our purposes, this must be a dynamic library */
ds@700: if ((file->Characteristics & IMAGE_FILE_DLL) == 0)
ds@700: {
ds@700: return false;
ds@700: }
ds@700:
ds@700: /* Finally, we can do this */
ds@700: lib.memorySize = opt->SizeOfImage;
ds@700:
ds@700: #elif defined PLATFORM_LINUX
ds@700:
ds@700: Dl_info info;
ds@700: Elf32_Ehdr *file;
ds@700: Elf32_Phdr *phdr;
ds@700: uint16_t phdrCount;
ds@700:
ds@700: if (!dladdr(libPtr, &info))
ds@700: {
ds@700: return false;
ds@700: }
ds@700:
ds@700: if (!info.dli_fbase || !info.dli_fname)
ds@700: {
ds@700: return false;
ds@700: }
ds@700:
ds@700: /* This is for our insane sanity checks :o */
ds@2992: baseAddr = reinterpret_cast(info.dli_fbase);
ds@700: file = reinterpret_cast(baseAddr);
ds@700:
ds@700: /* Check ELF magic */
ds@700: if (memcmp(ELFMAG, file->e_ident, SELFMAG) != 0)
ds@700: {
ds@700: return false;
ds@700: }
ds@700:
ds@700: /* Check ELF version */
ds@700: if (file->e_ident[EI_VERSION] != EV_CURRENT)
ds@700: {
ds@700: return false;
ds@700: }
ds@700:
ds@700: /* Check ELF architecture, which is 32-bit/x86 right now
ds@700: * Should change this for 64-bit if Valve gets their act together
ds@700: */
ds@700: if (file->e_ident[EI_CLASS] != ELFCLASS32 || file->e_machine != EM_386 || file->e_ident[EI_DATA] != ELFDATA2LSB)
ds@700: {
ds@700: return false;
ds@700: }
ds@700:
ds@700: /* For our purposes, this must be a dynamic library/shared object */
ds@700: if (file->e_type != ET_DYN)
ds@700: {
ds@700: return false;
ds@700: }
ds@700:
ds@700: phdrCount = file->e_phnum;
ds@700: phdr = reinterpret_cast(baseAddr + file->e_phoff);
ds@3103:
ds@700: for (uint16_t i = 0; i < phdrCount; i++)
ds@700: {
ds@700: Elf32_Phdr &hdr = phdr[i];
ds@700:
ds@3103: /* We only really care about the segment with executable code */
ds@3103: if (hdr.p_type == PT_LOAD && hdr.p_flags == (PF_X|PF_R))
ds@700: {
ds@3103: /* From glibc, elf/dl-load.c:
ds@3103: * c->mapend = ((ph->p_vaddr + ph->p_filesz + GLRO(dl_pagesize) - 1)
ds@3103: * & ~(GLRO(dl_pagesize) - 1));
ds@3103: *
ds@3103: * In glibc, the segment file size is aligned up to the nearest page size and
ds@3103: * added to the virtual address of the segment. We just want the size here.
ds@3103: */
ds@3103: lib.memorySize = PAGE_ALIGN_UP(hdr.p_filesz);
ds@3103: break;
ds@700: }
ds@700: }
ds@3103:
ds@2992: #elif defined PLATFORM_APPLE
ds@2992:
ds@2992: Dl_info info;
ds@2992: struct mach_header *file;
ds@2992: struct segment_command *seg;
ds@2992: uint32_t cmd_count;
ds@2992:
ds@2992: if (!dladdr(libPtr, &info))
ds@2992: {
ds@2992: return false;
ds@2992: }
ds@2992:
ds@2992: if (!info.dli_fbase || !info.dli_fname)
ds@2992: {
ds@2992: return false;
ds@2992: }
ds@2992:
ds@2992: /* This is for our insane sanity checks :o */
ds@2992: baseAddr = (uintptr_t)info.dli_fbase;
ds@2992: file = (struct mach_header *)baseAddr;
ds@2992:
ds@2992: /* Check Mach-O magic */
ds@2992: if (file->magic != MH_MAGIC)
ds@2992: {
ds@2992: return false;
ds@2992: }
ds@2992:
ds@2992: /* Check architecture (32-bit/x86) */
ds@2992: if (file->cputype != CPU_TYPE_I386 || file->cpusubtype != CPU_SUBTYPE_I386_ALL)
ds@2992: {
ds@2992: return false;
ds@2992: }
ds@2992:
ds@2992: /* For our purposes, this must be a dynamic library */
ds@2992: if (file->filetype != MH_DYLIB)
ds@2992: {
ds@2992: return false;
ds@2992: }
ds@2992:
ds@2992: cmd_count = file->ncmds;
ds@2992: seg = (struct segment_command *)(baseAddr + sizeof(struct mach_header));
ds@2992:
ds@2992: /* Add up memory sizes of mapped segments */
ds@2992: for (uint32_t i = 0; i < cmd_count; i++)
ds@2992: {
ds@2992: if (seg->cmd == LC_SEGMENT)
ds@2992: {
ds@2992: lib.memorySize += seg->vmsize;
ds@2992: }
ds@2992:
ds@2992: seg = (struct segment_command *)((uintptr_t)seg + seg->cmdsize);
ds@2992: }
ds@700:
ds@700: #endif
ds@700:
ds@700: lib.baseAddress = reinterpret_cast(baseAddr);
ds@700:
ds@700: return true;
ds@700: }