core/logic/MemoryUtils.cpp
author Nicholas Hastings <skamonkey@gmail.com>
Wed Aug 14 14:20:57 2013 -0400 (2013-08-14)
changeset 4008 490b01aa0683
parent 3753 404f6a847c9e
permissions -rw-r--r--
Updated some CS:GO gamedata.
     1 /**
     2  * vim: set ts=4 sw=4 tw=99 noet :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2011 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 #ifdef PLATFORM_LINUX
    32 #include <fcntl.h>
    33 #include <link.h>
    34 #include <sys/mman.h>
    35 
    36 #define PAGE_SIZE			4096
    37 #define PAGE_ALIGN_UP(x)	((x + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1))
    38 #endif
    39 
    40 #ifdef PLATFORM_APPLE
    41 #include <AvailabilityMacros.h>
    42 #include <mach/task.h>
    43 #include <mach-o/dyld_images.h>
    44 #include <mach-o/loader.h>
    45 #include <mach-o/nlist.h>
    46 
    47 /* Define things from 10.6 SDK for older SDKs */
    48 #ifndef MAC_OS_X_VERSION_10_6
    49 struct task_dyld_info
    50 {
    51 	mach_vm_address_t all_image_info_addr;
    52 	mach_vm_size_t all_image_info_size;
    53 };
    54 typedef struct task_dyld_info task_dyld_info_data_t;
    55 #define TASK_DYLD_INFO 17
    56 #define TASK_DYLD_INFO_COUNT (sizeof(task_dyld_info_data_t) / sizeof(natural_t))
    57 #endif // MAC_OS_X_VERSION_10_6
    58 #endif // PLATFORM_APPLE
    59 
    60 MemoryUtils g_MemUtils;
    61 
    62 MemoryUtils::MemoryUtils()
    63 {
    64 #ifdef PLATFORM_APPLE
    65 
    66 	Gestalt(gestaltSystemVersionMajor, &m_OSXMajor);
    67 	Gestalt(gestaltSystemVersionMinor, &m_OSXMinor);
    68 
    69 	/* Get pointer to struct that describes all loaded mach-o images in process */
    70 	if ((m_OSXMajor == 10 && m_OSXMinor >= 6) || m_OSXMajor > 10)
    71 	{
    72 		task_dyld_info_data_t dyld_info;
    73 		mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
    74 		task_info(mach_task_self(), TASK_DYLD_INFO, (task_info_t)&dyld_info, &count);
    75 		m_ImageList = (struct dyld_all_image_infos *)dyld_info.all_image_info_addr;
    76 	}
    77 	else
    78 	{
    79 		struct nlist list[2];
    80 		memset(list, 0, sizeof(list));
    81 		list[0].n_un.n_name = (char *)"_dyld_all_image_infos";
    82 		nlist("/usr/lib/dyld", list);
    83 		m_ImageList = (struct dyld_all_image_infos *)list[0].n_value;
    84 	}
    85 
    86 #endif
    87 }
    88 
    89 MemoryUtils::~MemoryUtils()
    90 {
    91 #if defined PLATFORM_LINUX || defined PLATFORM_APPLE
    92 	for (size_t i = 0; i < m_SymTables.size(); i++)
    93 	{
    94 		delete m_SymTables[i];
    95 	}
    96 	m_SymTables.clear();
    97 #endif
    98 }
    99 
   100 void MemoryUtils::OnSourceModAllInitialized()
   101 {
   102 	sharesys->AddInterface(NULL, this);
   103 }
   104 
   105 void *MemoryUtils::FindPattern(const void *libPtr, const char *pattern, size_t len)
   106 {
   107 	DynLibInfo lib;
   108 	bool found;
   109 	char *ptr, *end;
   110 
   111 	memset(&lib, 0, sizeof(DynLibInfo));
   112 
   113 	if (!GetLibraryInfo(libPtr, lib))
   114 	{
   115 		return NULL;
   116 	}
   117 
   118 	ptr = reinterpret_cast<char *>(lib.baseAddress);
   119 	end = ptr + lib.memorySize - len;
   120 
   121 	while (ptr < end)
   122 	{
   123 		found = true;
   124 		for (register size_t i = 0; i < len; i++)
   125 		{
   126 			if (pattern[i] != '\x2A' && pattern[i] != ptr[i])
   127 			{
   128 				found = false;
   129 				break;
   130 			}
   131 		}
   132 
   133 		if (found)
   134 			return ptr;
   135 
   136 		ptr++;
   137 	}
   138 
   139 	return NULL;
   140 }
   141 
   142 void *MemoryUtils::ResolveSymbol(void *handle, const char *symbol)
   143 {
   144 #ifdef PLATFORM_WINDOWS
   145 
   146 	return GetProcAddress((HMODULE)handle, symbol);
   147 	
   148 #elif defined PLATFORM_LINUX
   149 
   150 	struct link_map *dlmap;
   151 	struct stat dlstat;
   152 	int dlfile;
   153 	uintptr_t map_base;
   154 	Elf32_Ehdr *file_hdr;
   155 	Elf32_Shdr *sections, *shstrtab_hdr, *symtab_hdr, *strtab_hdr;
   156 	Elf32_Sym *symtab;
   157 	const char *shstrtab, *strtab;
   158 	uint16_t section_count;
   159 	uint32_t symbol_count;
   160 	LibSymbolTable *libtable;
   161 	SymbolTable *table;
   162 	Symbol *symbol_entry;
   163 
   164 	dlmap = (struct link_map *)handle;
   165 	symtab_hdr = NULL;
   166 	strtab_hdr = NULL;
   167 	table = NULL;
   168 	
   169 	/* See if we already have a symbol table for this library */
   170 	for (size_t i = 0; i < m_SymTables.size(); i++)
   171 	{
   172 		libtable = m_SymTables[i];
   173 		if (libtable->lib_base == dlmap->l_addr)
   174 		{
   175 			table = &libtable->table;
   176 			break;
   177 		}
   178 	}
   179 
   180 	/* If we don't have a symbol table for this library, then create one */
   181 	if (table == NULL)
   182 	{
   183 		libtable = new LibSymbolTable();
   184 		libtable->table.Initialize();
   185 		libtable->lib_base = dlmap->l_addr;
   186 		libtable->last_pos = 0;
   187 		table = &libtable->table;
   188 		m_SymTables.push_back(libtable);
   189 	}
   190 
   191 	/* See if the symbol is already cached in our table */
   192 	symbol_entry = table->FindSymbol(symbol, strlen(symbol));
   193 	if (symbol_entry != NULL)
   194 	{
   195 		return symbol_entry->address;
   196 	}
   197 
   198 	/* If symbol isn't in our table, then we have open the actual library */
   199 	dlfile = open(dlmap->l_name, O_RDONLY);
   200 	if (dlfile == -1 || fstat(dlfile, &dlstat) == -1)
   201 	{
   202 		close(dlfile);
   203 		return NULL;
   204 	}
   205 
   206 	/* Map library file into memory */
   207 	file_hdr = (Elf32_Ehdr *)mmap(NULL, dlstat.st_size, PROT_READ, MAP_PRIVATE, dlfile, 0);
   208 	map_base = (uintptr_t)file_hdr;
   209 	if (file_hdr == MAP_FAILED)
   210 	{
   211 		close(dlfile);
   212 		return NULL;
   213 	}
   214 	close(dlfile);
   215 
   216 	if (file_hdr->e_shoff == 0 || file_hdr->e_shstrndx == SHN_UNDEF)
   217 	{
   218 		munmap(file_hdr, dlstat.st_size);
   219 		return NULL;
   220 	}
   221 
   222 	sections = (Elf32_Shdr *)(map_base + file_hdr->e_shoff);
   223 	section_count = file_hdr->e_shnum;
   224 	/* Get ELF section header string table */
   225 	shstrtab_hdr = &sections[file_hdr->e_shstrndx];
   226 	shstrtab = (const char *)(map_base + shstrtab_hdr->sh_offset);
   227 
   228 	/* Iterate sections while looking for ELF symbol table and string table */
   229 	for (uint16_t i = 0; i < section_count; i++)
   230 	{
   231 		Elf32_Shdr &hdr = sections[i];
   232 		const char *section_name = shstrtab + hdr.sh_name;
   233 
   234 		if (strcmp(section_name, ".symtab") == 0)
   235 		{
   236 			symtab_hdr = &hdr;
   237 		}
   238 		else if (strcmp(section_name, ".strtab") == 0)
   239 		{
   240 			strtab_hdr = &hdr;
   241 		}
   242 	}
   243 
   244 	/* Uh oh, we don't have a symbol table or a string table */
   245 	if (symtab_hdr == NULL || strtab_hdr == NULL)
   246 	{
   247 		munmap(file_hdr, dlstat.st_size);
   248 		return NULL;
   249 	}
   250 
   251 	symtab = (Elf32_Sym *)(map_base + symtab_hdr->sh_offset);
   252 	strtab = (const char *)(map_base + strtab_hdr->sh_offset);
   253 	symbol_count = symtab_hdr->sh_size / symtab_hdr->sh_entsize;
   254 
   255 	/* Iterate symbol table starting from the position we were at last time */
   256 	for (uint32_t i = libtable->last_pos; i < symbol_count; i++)
   257 	{
   258 		Elf32_Sym &sym = symtab[i];
   259 		unsigned char sym_type = ELF32_ST_TYPE(sym.st_info);
   260 		const char *sym_name = strtab + sym.st_name;
   261 		Symbol *cur_sym;
   262 
   263 		/* Skip symbols that are undefined or do not refer to functions or objects */
   264 		if (sym.st_shndx == SHN_UNDEF || (sym_type != STT_FUNC && sym_type != STT_OBJECT))
   265 		{
   266 			continue;
   267 		}
   268 
   269 		/* Caching symbols as we go along */
   270 		cur_sym = table->InternSymbol(sym_name, strlen(sym_name), (void *)(dlmap->l_addr + sym.st_value));
   271 		if (strcmp(symbol, sym_name) == 0)
   272 		{
   273 			symbol_entry = cur_sym;
   274 			libtable->last_pos = ++i;
   275 			break;
   276 		}
   277 	}
   278 
   279 	munmap(file_hdr, dlstat.st_size);
   280 	return symbol_entry ? symbol_entry->address : NULL;
   281 
   282 #elif defined PLATFORM_APPLE
   283 	
   284 	uintptr_t dlbase, linkedit_addr;
   285 	uint32_t image_count;
   286 	struct mach_header *file_hdr;
   287 	struct load_command *loadcmds;
   288 	struct segment_command *linkedit_hdr;
   289 	struct symtab_command *symtab_hdr;
   290 	struct nlist *symtab;
   291 	const char *strtab;
   292 	uint32_t loadcmd_count;
   293 	uint32_t symbol_count;
   294 	LibSymbolTable *libtable;
   295 	SymbolTable *table;
   296 	Symbol *symbol_entry;
   297 	
   298 	dlbase = 0;
   299 	image_count = m_ImageList->infoArrayCount;
   300 	linkedit_hdr = NULL;
   301 	symtab_hdr = NULL;
   302 	table = NULL;
   303 	
   304 	/* Loop through mach-o images in process.
   305 	 * We can skip index 0 since that is just the executable.
   306 	 */
   307 	for (uint32_t i = 1; i < image_count; i++)
   308 	{
   309 		const struct dyld_image_info &info = m_ImageList->infoArray[i];
   310 		
   311 		/* "Load" each one until we get a matching handle */
   312 		void *h = dlopen(info.imageFilePath, RTLD_NOLOAD);
   313 		if (h == handle)
   314 		{
   315 			dlbase = (uintptr_t)info.imageLoadAddress;
   316 			dlclose(h);
   317 			break;
   318 		}
   319 		
   320 		dlclose(h);
   321 	}
   322 	
   323 	if (!dlbase)
   324 	{
   325 		/* Uh oh, we couldn't find a matching handle */
   326 		return NULL;
   327 	}
   328 	
   329 	/* See if we already have a symbol table for this library */
   330 	for (size_t i = 0; i < m_SymTables.size(); i++)
   331 	{
   332 		libtable = m_SymTables[i];
   333 		if (libtable->lib_base == dlbase)
   334 		{
   335 			table = &libtable->table;
   336 			break;
   337 		}
   338 	}
   339 	
   340 	/* If we don't have a symbol table for this library, then create one */
   341 	if (table == NULL)
   342 	{
   343 		libtable = new LibSymbolTable();
   344 		libtable->table.Initialize();
   345 		libtable->lib_base = dlbase;
   346 		libtable->last_pos = 0;
   347 		table = &libtable->table;
   348 		m_SymTables.push_back(libtable);
   349 	}
   350 	
   351 	/* See if the symbol is already cached in our table */
   352 	symbol_entry = table->FindSymbol(symbol, strlen(symbol));
   353 	if (symbol_entry != NULL)
   354 	{
   355 		return symbol_entry->address;
   356 	}
   357 	
   358 	/* If symbol isn't in our table, then we have to locate it in memory */
   359 	
   360 	file_hdr = (struct mach_header *)dlbase;
   361 	loadcmds = (struct load_command *)(dlbase + sizeof(struct mach_header));
   362 	loadcmd_count = file_hdr->ncmds;
   363 	
   364 	/* Loop through load commands until we find the ones for the symbol table */
   365 	for (uint32_t i = 0; i < loadcmd_count; i++)
   366 	{
   367 		if (loadcmds->cmd == LC_SEGMENT && !linkedit_hdr)
   368 		{
   369 			struct segment_command *seg = (struct segment_command *)loadcmds;
   370 			if (strcmp(seg->segname, "__LINKEDIT") == 0)
   371 			{
   372 				linkedit_hdr = seg;
   373 				if (symtab_hdr)
   374 				{
   375 					break;
   376 				}
   377 			}
   378 		}
   379 		else if (loadcmds->cmd == LC_SYMTAB)
   380 		{
   381 			symtab_hdr = (struct symtab_command *)loadcmds;
   382 			if (linkedit_hdr)
   383 			{
   384 				break;
   385 			}
   386 		}
   387 
   388 		/* Load commands are not of a fixed size which is why we add the size */
   389 		loadcmds = (struct load_command *)((uintptr_t)loadcmds + loadcmds->cmdsize);
   390 	}
   391 	
   392 	if (!linkedit_hdr || !symtab_hdr || !symtab_hdr->symoff || !symtab_hdr->stroff)
   393 	{
   394 		/* Uh oh, no symbol table */
   395 		return NULL;
   396 	}
   397 
   398 	linkedit_addr = dlbase + linkedit_hdr->vmaddr;
   399 	symtab = (struct nlist *)(linkedit_addr + symtab_hdr->symoff - linkedit_hdr->fileoff);
   400 	strtab = (const char *)(linkedit_addr + symtab_hdr->stroff - linkedit_hdr->fileoff);
   401 	symbol_count = symtab_hdr->nsyms;
   402 	
   403 	/* Iterate symbol table starting from the position we were at last time */
   404 	for (uint32_t i = libtable->last_pos; i < symbol_count; i++)
   405 	{
   406 		struct nlist &sym = symtab[i];
   407 		/* Ignore the prepended underscore on all symbols, so +1 here */
   408 		const char *sym_name = strtab + sym.n_un.n_strx + 1;
   409 		Symbol *cur_sym;
   410 		
   411 		/* Skip symbols that are undefined */
   412 		if (sym.n_sect == NO_SECT)
   413 		{
   414 			continue;
   415 		}
   416 		
   417 		/* Caching symbols as we go along */
   418 		cur_sym = table->InternSymbol(sym_name, strlen(sym_name), (void *)(dlbase + sym.n_value));
   419 		if (strcmp(symbol, sym_name) == 0)
   420 		{
   421 			symbol_entry = cur_sym;
   422 			libtable->last_pos = ++i;
   423 			break;
   424 		}
   425 	}
   426 	
   427 	return symbol_entry ? symbol_entry->address : NULL;
   428 
   429 #endif
   430 }
   431 
   432 bool MemoryUtils::GetLibraryInfo(const void *libPtr, DynLibInfo &lib)
   433 {
   434 	uintptr_t baseAddr;
   435 
   436 	if (libPtr == NULL)
   437 	{
   438 		return false;
   439 	}
   440 
   441 #ifdef PLATFORM_WINDOWS
   442 
   443 	MEMORY_BASIC_INFORMATION info;
   444 	IMAGE_DOS_HEADER *dos;
   445 	IMAGE_NT_HEADERS *pe;
   446 	IMAGE_FILE_HEADER *file;
   447 	IMAGE_OPTIONAL_HEADER *opt;
   448 
   449 	if (!VirtualQuery(libPtr, &info, sizeof(MEMORY_BASIC_INFORMATION)))
   450 	{
   451 		return false;
   452 	}
   453 
   454 	baseAddr = reinterpret_cast<uintptr_t>(info.AllocationBase);
   455 
   456 	/* All this is for our insane sanity checks :o */
   457 	dos = reinterpret_cast<IMAGE_DOS_HEADER *>(baseAddr);
   458 	pe = reinterpret_cast<IMAGE_NT_HEADERS *>(baseAddr + dos->e_lfanew);
   459 	file = &pe->FileHeader;
   460 	opt = &pe->OptionalHeader;
   461 
   462 	/* Check PE magic and signature */
   463 	if (dos->e_magic != IMAGE_DOS_SIGNATURE || pe->Signature != IMAGE_NT_SIGNATURE || opt->Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC)
   464 	{
   465 		return false;
   466 	}
   467 
   468 	/* Check architecture, which is 32-bit/x86 right now
   469 	 * Should change this for 64-bit if Valve gets their act together
   470 	 */
   471 	if (file->Machine != IMAGE_FILE_MACHINE_I386)
   472 	{
   473 		return false;
   474 	}
   475 
   476 	/* For our purposes, this must be a dynamic library */
   477 	if ((file->Characteristics & IMAGE_FILE_DLL) == 0)
   478 	{
   479 		return false;
   480 	}
   481 
   482 	/* Finally, we can do this */
   483 	lib.memorySize = opt->SizeOfImage;
   484 
   485 #elif defined PLATFORM_LINUX
   486 
   487 	Dl_info info;
   488 	Elf32_Ehdr *file;
   489 	Elf32_Phdr *phdr;
   490 	uint16_t phdrCount;
   491 
   492 	if (!dladdr(libPtr, &info))
   493 	{
   494 		return false;
   495 	}
   496 
   497 	if (!info.dli_fbase || !info.dli_fname)
   498 	{
   499 		return false;
   500 	}
   501 
   502 	/* This is for our insane sanity checks :o */
   503 	baseAddr = reinterpret_cast<uintptr_t>(info.dli_fbase);
   504 	file = reinterpret_cast<Elf32_Ehdr *>(baseAddr);
   505 
   506 	/* Check ELF magic */
   507 	if (memcmp(ELFMAG, file->e_ident, SELFMAG) != 0)
   508 	{
   509 		return false;
   510 	}
   511 
   512 	/* Check ELF version */
   513 	if (file->e_ident[EI_VERSION] != EV_CURRENT)
   514 	{
   515 		return false;
   516 	}
   517 
   518 	/* Check ELF architecture, which is 32-bit/x86 right now
   519 	 * Should change this for 64-bit if Valve gets their act together
   520 	 */
   521 	if (file->e_ident[EI_CLASS] != ELFCLASS32 || file->e_machine != EM_386 || file->e_ident[EI_DATA] != ELFDATA2LSB)
   522 	{
   523 		return false;
   524 	}
   525 
   526 	/* For our purposes, this must be a dynamic library/shared object */
   527 	if (file->e_type != ET_DYN)
   528 	{
   529 		return false;
   530 	}
   531 
   532 	phdrCount = file->e_phnum;
   533 	phdr = reinterpret_cast<Elf32_Phdr *>(baseAddr + file->e_phoff);
   534 
   535 	for (uint16_t i = 0; i < phdrCount; i++)
   536 	{
   537 		Elf32_Phdr &hdr = phdr[i];
   538 
   539 		/* We only really care about the segment with executable code */
   540 		if (hdr.p_type == PT_LOAD && hdr.p_flags == (PF_X|PF_R))
   541 		{
   542 			/* From glibc, elf/dl-load.c:
   543 			 * c->mapend = ((ph->p_vaddr + ph->p_filesz + GLRO(dl_pagesize) - 1) 
   544 			 *             & ~(GLRO(dl_pagesize) - 1));
   545 			 *
   546 			 * In glibc, the segment file size is aligned up to the nearest page size and
   547 			 * added to the virtual address of the segment. We just want the size here.
   548 			 */
   549 			lib.memorySize = PAGE_ALIGN_UP(hdr.p_filesz);
   550 			break;
   551 		}
   552 	}
   553 
   554 #elif defined PLATFORM_APPLE
   555 
   556 	Dl_info info;
   557 	struct mach_header *file;
   558 	struct segment_command *seg;
   559 	uint32_t cmd_count;
   560 
   561 	if (!dladdr(libPtr, &info))
   562 	{
   563 		return false;
   564 	}
   565 
   566 	if (!info.dli_fbase || !info.dli_fname)
   567 	{
   568 		return false;
   569 	}
   570 
   571 	/* This is for our insane sanity checks :o */
   572 	baseAddr = (uintptr_t)info.dli_fbase;
   573 	file = (struct mach_header *)baseAddr;
   574 
   575 	/* Check Mach-O magic */
   576 	if (file->magic != MH_MAGIC)
   577 	{
   578 		return false;
   579 	}
   580 
   581 	/* Check architecture (32-bit/x86) */
   582 	if (file->cputype != CPU_TYPE_I386 || file->cpusubtype != CPU_SUBTYPE_I386_ALL)
   583 	{
   584 		return false;
   585 	}
   586 
   587 	/* For our purposes, this must be a dynamic library */
   588 	if (file->filetype != MH_DYLIB)
   589 	{
   590 		return false;
   591 	}
   592 
   593 	cmd_count = file->ncmds;
   594 	seg = (struct segment_command *)(baseAddr + sizeof(struct mach_header));
   595 	
   596 	/* Add up memory sizes of mapped segments */
   597 	for (uint32_t i = 0; i < cmd_count; i++)
   598 	{		
   599 		if (seg->cmd == LC_SEGMENT)
   600 		{
   601 			lib.memorySize += seg->vmsize;
   602 		}
   603 		
   604 		seg = (struct segment_command *)((uintptr_t)seg + seg->cmdsize);
   605 	}
   606 
   607 #endif
   608 
   609 	lib.baseAddress = reinterpret_cast<void *>(baseAddr);
   610 
   611 	return true;
   612 }