core/MemoryUtils.cpp
author Scott Ehlert <ds@alliedmods.net>
Thu May 13 04:20:41 2010 -0500 (2010-05-13)
changeset 2992 affc67b319f4
parent 2863 d740d9cdf53a
permissions -rw-r--r--
Add support for Mac OS X to ResolveSymbol() and FindPattern() in IMemUtils (bug 4392, r=dvander).
     1 /**
     2  * vim: set ts=4 sw=4 tw=99 noet :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2010 AlliedModders LLC.  All rights reserved.
     6  * =============================================================================
     7  *
     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.
    11  * 
    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
    15  * details.
    16  *
    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/>.
    19  *
    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>.
    28  */
    29 
    30 #include "MemoryUtils.h"
    31 #include "ShareSys.h"
    32 #ifdef PLATFORM_LINUX
    33 #include <fcntl.h>
    34 #include <link.h>
    35 #include <sys/mman.h>
    36 #endif
    37 #ifdef PLATFORM_APPLE
    38 #include <mach-o/dyld_images.h>
    39 #include <mach-o/loader.h>
    40 #include <mach-o/nlist.h>
    41 #endif
    42 
    43 MemoryUtils g_MemUtils;
    44 
    45 MemoryUtils::MemoryUtils()
    46 {
    47 #ifdef PLATFORM_APPLE
    48 
    49 	/* Get pointer to struct that describes all loaded mach-o images in process */
    50 	struct nlist list[2];
    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;
    55 
    56 #endif
    57 }
    58 
    59 MemoryUtils::~MemoryUtils()
    60 {
    61 #if defined PLATFORM_LINUX || defined PLATFORM_APPLE
    62 	for (size_t i = 0; i < m_SymTables.size(); i++)
    63 	{
    64 		delete m_SymTables[i];
    65 	}
    66 	m_SymTables.clear();
    67 #endif
    68 }
    69 
    70 void MemoryUtils::OnSourceModAllInitialized()
    71 {
    72 	g_ShareSys.AddInterface(NULL, this);
    73 }
    74 
    75 void *MemoryUtils::FindPattern(const void *libPtr, const char *pattern, size_t len)
    76 {
    77 	DynLibInfo lib;
    78 	bool found;
    79 	char *ptr, *end;
    80 
    81 	memset(&lib, 0, sizeof(DynLibInfo));
    82 
    83 	if (!GetLibraryInfo(libPtr, lib))
    84 	{
    85 		return NULL;
    86 	}
    87 
    88 	ptr = reinterpret_cast<char *>(lib.baseAddress);
    89 	end = ptr + lib.memorySize;
    90 
    91 	while (ptr < end)
    92 	{
    93 		found = true;
    94 		for (register size_t i = 0; i < len; i++)
    95 		{
    96 			if (pattern[i] != '\x2A' && pattern[i] != ptr[i])
    97 			{
    98 				found = false;
    99 				break;
   100 			}
   101 		}
   102 
   103 		if (found)
   104 			return ptr;
   105 
   106 		ptr++;
   107 	}
   108 
   109 	return NULL;
   110 }
   111 
   112 void *MemoryUtils::ResolveSymbol(void *handle, const char *symbol)
   113 {
   114 #ifdef PLATFORM_WINDOWS
   115 
   116 	return GetProcAddress((HMODULE)handle, symbol);
   117 	
   118 #elif defined PLATFORM_LINUX
   119 
   120 	struct link_map *dlmap;
   121 	struct stat dlstat;
   122 	int dlfile;
   123 	uintptr_t map_base;
   124 	Elf32_Ehdr *file_hdr;
   125 	Elf32_Shdr *sections, *shstrtab_hdr, *symtab_hdr, *strtab_hdr;
   126 	Elf32_Sym *symtab;
   127 	const char *shstrtab, *strtab;
   128 	uint16_t section_count;
   129 	uint32_t symbol_count;
   130 	LibSymbolTable *libtable;
   131 	SymbolTable *table;
   132 	Symbol *symbol_entry;
   133 
   134 	dlmap = (struct link_map *)handle;
   135 	symtab_hdr = NULL;
   136 	strtab_hdr = NULL;
   137 	table = NULL;
   138 	
   139 	/* See if we already have a symbol table for this library */
   140 	for (size_t i = 0; i < m_SymTables.size(); i++)
   141 	{
   142 		libtable = m_SymTables[i];
   143 		if (libtable->lib_base == dlmap->l_addr)
   144 		{
   145 			table = &libtable->table;
   146 			break;
   147 		}
   148 	}
   149 
   150 	/* If we don't have a symbol table for this library, then create one */
   151 	if (table == NULL)
   152 	{
   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);
   159 	}
   160 
   161 	/* See if the symbol is already cached in our table */
   162 	symbol_entry = table->FindSymbol(symbol, strlen(symbol));
   163 	if (symbol_entry != NULL)
   164 	{
   165 		return symbol_entry->address;
   166 	}
   167 
   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)
   171 	{
   172 		close(dlfile);
   173 		return NULL;
   174 	}
   175 
   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)
   180 	{
   181 		close(dlfile);
   182 		return NULL;
   183 	}
   184 	close(dlfile);
   185 
   186 	if (file_hdr->e_shoff == 0 || file_hdr->e_shstrndx == SHN_UNDEF)
   187 	{
   188 		munmap(file_hdr, dlstat.st_size);
   189 		return NULL;
   190 	}
   191 
   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 = &sections[file_hdr->e_shstrndx];
   196 	shstrtab = (const char *)(map_base + shstrtab_hdr->sh_offset);
   197 
   198 	/* Iterate sections while looking for ELF symbol table and string table */
   199 	for (uint16_t i = 0; i < section_count; i++)
   200 	{
   201 		Elf32_Shdr &hdr = sections[i];
   202 		const char *section_name = shstrtab + hdr.sh_name;
   203 
   204 		if (strcmp(section_name, ".symtab") == 0)
   205 		{
   206 			symtab_hdr = &hdr;
   207 		}
   208 		else if (strcmp(section_name, ".strtab") == 0)
   209 		{
   210 			strtab_hdr = &hdr;
   211 		}
   212 	}
   213 
   214 	/* Uh oh, we don't have a symbol table or a string table */
   215 	if (symtab_hdr == NULL || strtab_hdr == NULL)
   216 	{
   217 		munmap(file_hdr, dlstat.st_size);
   218 		return NULL;
   219 	}
   220 
   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;
   224 
   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++)
   227 	{
   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;
   231 		Symbol *cur_sym;
   232 
   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))
   235 		{
   236 			continue;
   237 		}
   238 
   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)
   242 		{
   243 			symbol_entry = cur_sym;
   244 			libtable->last_pos = ++i;
   245 			break;
   246 		}
   247 	}
   248 
   249 	munmap(file_hdr, dlstat.st_size);
   250 	return symbol_entry ? symbol_entry->address : NULL;
   251 
   252 #elif defined PLATFORM_APPLE
   253 	
   254 	uintptr_t dlbase;
   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;
   260 	const char *strtab;
   261 	uint32_t loadcmd_count;
   262 	uint32_t symbol_count;
   263 	LibSymbolTable *libtable;
   264 	SymbolTable *table;
   265 	Symbol *symbol_entry;
   266 	
   267 	dlbase = 0;
   268 	image_count = m_ImageList->infoArrayCount;
   269 	symtab_hdr = NULL;
   270 	
   271 	/* Loop through mach-o images in process.
   272 	 * We can skip index 0 since that is just the executable.
   273 	 */
   274 	for (uint32_t i = 1; i < image_count; i++)
   275 	{
   276 		const struct dyld_image_info &info = m_ImageList->infoArray[i];
   277 		
   278 		/* "Load" each one until we get a matching handle */
   279 		void *h = dlopen(info.imageFilePath, RTLD_NOLOAD);
   280 		if (h == handle)
   281 		{
   282 			dlbase = (uintptr_t)info.imageLoadAddress;
   283 			dlclose(h);
   284 			break;
   285 		}
   286 		
   287 		dlclose(h);
   288 	}
   289 	
   290 	if (!dlbase)
   291 	{
   292 		/* Uh oh, we couldn't find a matching handle */
   293 		return NULL;
   294 	}
   295 	
   296 	/* See if we already have a symbol table for this library */
   297 	for (size_t i = 0; i < m_SymTables.size(); i++)
   298 	{
   299 		libtable = m_SymTables[i];
   300 		if (libtable->lib_base == dlbase)
   301 		{
   302 			table = &libtable->table;
   303 			break;
   304 		}
   305 	}
   306 	
   307 	/* If we don't have a symbol table for this library, then create one */
   308 	if (table == NULL)
   309 	{
   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);
   316 	}
   317 	
   318 	/* See if the symbol is already cached in our table */
   319 	symbol_entry = table->FindSymbol(symbol, strlen(symbol));
   320 	if (symbol_entry != NULL)
   321 	{
   322 		return symbol_entry->address;
   323 	}
   324 	
   325 	/* If symbol isn't in our table, then we have to locate it in memory */
   326 	
   327 	file_hdr = (struct mach_header *)dlbase;
   328 	loadcmds = (struct load_command *)(dlbase + sizeof(struct mach_header));
   329 	loadcmd_count = file_hdr->ncmds;
   330 	
   331 	/* Loop through load commands until we find the one for the symbol table */
   332 	for (uint32_t i = 0; i < loadcmd_count; i++)
   333 	{
   334 		if (loadcmds->cmd == LC_SYMTAB)
   335 		{
   336 			symtab_hdr = (struct symtab_command *)loadcmds;
   337 			break;
   338 		}
   339 		
   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);
   342 	}
   343 	
   344 	if (!symtab_hdr || !symtab_hdr->symoff || !symtab_hdr->stroff)
   345 	{
   346 		/* Uh oh, no symbol table */
   347 		return NULL;
   348 	}
   349 	
   350 	symtab = (struct nlist *)(dlbase + symtab_hdr->symoff);
   351 	strtab = (const char *)(dlbase + symtab_hdr->stroff);
   352 	symbol_count = symtab_hdr->nsyms;
   353 	
   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++)
   356 	{
   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;
   360 		Symbol *cur_sym;
   361 		
   362 		/* Skip symbols that are undefined */
   363 		if (sym.n_sect == NO_SECT)
   364 		{
   365 			continue;
   366 		}
   367 		
   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)
   371 		{
   372 			symbol_entry = cur_sym;
   373 			libtable->last_pos = ++i;
   374 			break;
   375 		}
   376 	}
   377 	
   378 	return symbol_entry ? symbol_entry->address : NULL;
   379 
   380 #endif
   381 }
   382 
   383 bool MemoryUtils::GetLibraryInfo(const void *libPtr, DynLibInfo &lib)
   384 {
   385 	uintptr_t baseAddr;
   386 
   387 	if (libPtr == NULL)
   388 	{
   389 		return false;
   390 	}
   391 
   392 #ifdef PLATFORM_WINDOWS
   393 
   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;
   399 
   400 	if (!VirtualQuery(libPtr, &info, sizeof(MEMORY_BASIC_INFORMATION)))
   401 	{
   402 		return false;
   403 	}
   404 
   405 	baseAddr = reinterpret_cast<uintptr_t>(info.AllocationBase);
   406 
   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;
   412 
   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)
   415 	{
   416 		return false;
   417 	}
   418 
   419 	/* Check architecture, which is 32-bit/x86 right now
   420 	 * Should change this for 64-bit if Valve gets their act together
   421 	 */
   422 	if (file->Machine != IMAGE_FILE_MACHINE_I386)
   423 	{
   424 		return false;
   425 	}
   426 
   427 	/* For our purposes, this must be a dynamic library */
   428 	if ((file->Characteristics & IMAGE_FILE_DLL) == 0)
   429 	{
   430 		return false;
   431 	}
   432 
   433 	/* Finally, we can do this */
   434 	lib.memorySize = opt->SizeOfImage;
   435 
   436 #elif defined PLATFORM_LINUX
   437 
   438 	Dl_info info;
   439 	Elf32_Ehdr *file;
   440 	Elf32_Phdr *phdr;
   441 	uint16_t phdrCount;
   442 
   443 	if (!dladdr(libPtr, &info))
   444 	{
   445 		return false;
   446 	}
   447 
   448 	if (!info.dli_fbase || !info.dli_fname)
   449 	{
   450 		return false;
   451 	}
   452 
   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);
   456 
   457 	/* Check ELF magic */
   458 	if (memcmp(ELFMAG, file->e_ident, SELFMAG) != 0)
   459 	{
   460 		return false;
   461 	}
   462 
   463 	/* Check ELF version */
   464 	if (file->e_ident[EI_VERSION] != EV_CURRENT)
   465 	{
   466 		return false;
   467 	}
   468 
   469 	/* Check ELF architecture, which is 32-bit/x86 right now
   470 	 * Should change this for 64-bit if Valve gets their act together
   471 	 */
   472 	if (file->e_ident[EI_CLASS] != ELFCLASS32 || file->e_machine != EM_386 || file->e_ident[EI_DATA] != ELFDATA2LSB)
   473 	{
   474 		return false;
   475 	}
   476 
   477 	/* For our purposes, this must be a dynamic library/shared object */
   478 	if (file->e_type != ET_DYN)
   479 	{
   480 		return false;
   481 	}
   482 
   483 	phdrCount = file->e_phnum;
   484 	phdr = reinterpret_cast<Elf32_Phdr *>(baseAddr + file->e_phoff);
   485 	
   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++)
   488 	{
   489 		Elf32_Phdr &hdr = phdr[i];
   490 
   491 		if (hdr.p_type == PT_LOAD)
   492 		{
   493 			lib.memorySize += hdr.p_memsz;
   494 		}
   495 	}
   496 	
   497 #elif defined PLATFORM_APPLE
   498 
   499 	Dl_info info;
   500 	struct mach_header *file;
   501 	struct segment_command *seg;
   502 	uint32_t cmd_count;
   503 
   504 	if (!dladdr(libPtr, &info))
   505 	{
   506 		return false;
   507 	}
   508 
   509 	if (!info.dli_fbase || !info.dli_fname)
   510 	{
   511 		return false;
   512 	}
   513 
   514 	/* This is for our insane sanity checks :o */
   515 	baseAddr = (uintptr_t)info.dli_fbase;
   516 	file = (struct mach_header *)baseAddr;
   517 
   518 	/* Check Mach-O magic */
   519 	if (file->magic != MH_MAGIC)
   520 	{
   521 		return false;
   522 	}
   523 
   524 	/* Check architecture (32-bit/x86) */
   525 	if (file->cputype != CPU_TYPE_I386 || file->cpusubtype != CPU_SUBTYPE_I386_ALL)
   526 	{
   527 		return false;
   528 	}
   529 
   530 	/* For our purposes, this must be a dynamic library */
   531 	if (file->filetype != MH_DYLIB)
   532 	{
   533 		return false;
   534 	}
   535 
   536 	cmd_count = file->ncmds;
   537 	seg = (struct segment_command *)(baseAddr + sizeof(struct mach_header));
   538 	
   539 	/* Add up memory sizes of mapped segments */
   540 	for (uint32_t i = 0; i < cmd_count; i++)
   541 	{		
   542 		if (seg->cmd == LC_SEGMENT)
   543 		{
   544 			lib.memorySize += seg->vmsize;
   545 		}
   546 		
   547 		seg = (struct segment_command *)((uintptr_t)seg + seg->cmdsize);
   548 	}
   549 
   550 #endif
   551 
   552 	lib.baseAddress = reinterpret_cast<void *>(baseAddr);
   553 
   554 	return true;
   555 }