core/GameConfigs.cpp
author Nicholas Hastings <skamonkey@gmail.com>
Mon Feb 08 19:57:20 2010 -0800 (2010-02-08)
changeset 2914 bf5f9aa53abe
parent 2906 33cc9854bd97
child 2962 130639d897c2
permissions -rw-r--r--
Fixed FindEntityByClassname crash in Synergy (bug 4235, r=dvander).
     1 /**
     2  * vim: set ts=4 sw=4 tw=99 noet :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2009 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 <string.h>
    31 #include <stdlib.h>
    32 #include "GameConfigs.h"
    33 #include "sm_stringutil.h"
    34 #include "sourcemod.h"
    35 #include "sourcemm_api.h"
    36 #include "HalfLife2.h"
    37 #include "Logger.h"
    38 #include "ShareSys.h"
    39 #include "MemoryUtils.h"
    40 #include "LibrarySys.h"
    41 #include "HandleSys.h"
    42 #include "logic_bridge.h"
    43 
    44 #if defined PLATFORM_LINUX
    45 #include <dlfcn.h>
    46 #endif
    47 
    48 GameConfigManager g_GameConfigs;
    49 IGameConfig *g_pGameConf = NULL;
    50 static char g_Game[256];
    51 static char g_GameDesc[256] = {'!', '\0'};
    52 static char g_GameName[256] = {'$', '\0'};
    53 
    54 #define PSTATE_NONE						0
    55 #define PSTATE_GAMES					1
    56 #define PSTATE_GAMEDEFS					2
    57 #define PSTATE_GAMEDEFS_OFFSETS			3
    58 #define PSTATE_GAMEDEFS_OFFSETS_OFFSET	4
    59 #define PSTATE_GAMEDEFS_KEYS			5
    60 #define PSTATE_GAMEDEFS_SUPPORTED		6
    61 #define PSTATE_GAMEDEFS_SIGNATURES		7
    62 #define PSTATE_GAMEDEFS_SIGNATURES_SIG	8
    63 #define PSTATE_GAMEDEFS_CRC				9
    64 #define PSTATE_GAMEDEFS_CRC_BINARY		10
    65 #define PSTATE_GAMEDEFS_CUSTOM			11
    66 #define PSTATE_GAMEDEFS_ADDRESSES		12
    67 #define PSTATE_GAMEDEFS_ADDRESSES_ADDRESS	13
    68 #define PSTATE_GAMEDEFS_ADDRESSES_ADDRESS_READ	14
    69 
    70 #if defined PLATFORM_WINDOWS
    71 #define PLATFORM_NAME				"windows"
    72 #define PLATFORM_SERVER_BINARY		"server.dll"
    73 #elif defined PLATFORM_LINUX
    74 #define PLATFORM_NAME				"linux"
    75 #define PLATFORM_SERVER_BINARY		"server_i486.so"
    76 #elif defined PLATFORM_APPLE
    77 #define PLATFORM_NAME               "undef"
    78 #define PLATFORM_SERVER_BINARY      "undef.dylib"
    79 #endif
    80 
    81 struct TempSigInfo
    82 {
    83 	void Reset()
    84 	{
    85 		library[0] = '\0';
    86 		sig[0] = '\0';
    87 	}
    88 	char sig[512];
    89 	char library[64];
    90 } s_TempSig;
    91 unsigned int s_ServerBinCRC;
    92 bool s_ServerBinCRC_Ok = false;
    93 
    94 static bool DoesGameMatch(const char *value)
    95 {
    96 #if defined PLATFORM_WINDOWS
    97 	if (strcasecmp(value, g_Game) == 0 ||
    98 #else
    99 	if (strcmp(value, g_Game) == 0 ||
   100 #endif
   101 		strcmp(value, g_GameDesc) == 0 ||
   102 		strcmp(value, g_GameName) == 0)
   103 	{
   104 		return true;
   105 	}
   106 	return false;
   107 }
   108 
   109 static bool DoesEngineMatch(const char *value)
   110 {
   111 #if SOURCE_ENGINE == SE_EPISODEONE
   112 	if (strcmp(value, "original") == 0)
   113 #elif SOURCE_ENGINE == SE_DARKMESSIAH
   114 	if (strcmp(value, "darkmessiah") == 0)
   115 #elif SOURCE_ENGINE == SE_ORANGEBOX
   116 	if (strcmp(value, "orangebox") == 0)
   117 #elif SOURCE_ENGINE == SE_ORANGEBOXVALVE
   118 	if (strcmp(value, "orangebox_valve") == 0)
   119 #elif SOURCE_ENGINE == SE_LEFT4DEAD
   120 	if (strcmp(value, "left4dead") == 0)
   121 #elif SOURCE_ENGINE == SE_LEFT4DEAD2
   122 	if (strcmp(value, "left4dead2") == 0)
   123 #else
   124 #error "Unknown engine type"
   125 #endif
   126 	{
   127 		return true;
   128 	}
   129 	return false;
   130 }
   131 
   132 CGameConfig::CGameConfig(const char *file)
   133 {
   134 	strncopy(m_File, file, sizeof(m_File));
   135 	m_pOffsets = sm_trie_create();
   136 	m_pProps = sm_trie_create();
   137 	m_pKeys = sm_trie_create();
   138 	m_pAddresses = new KTrie<AddressConf>();
   139 	m_pSigs = sm_trie_create();
   140 	m_pStrings = new BaseStringTable(512);
   141 	m_RefCount = 0;
   142 
   143 	m_CustomLevel = 0;
   144 	m_CustomHandler = NULL;
   145 }
   146 
   147 CGameConfig::~CGameConfig()
   148 {
   149 	sm_trie_destroy(m_pOffsets);
   150 	sm_trie_destroy(m_pProps);
   151 	sm_trie_destroy(m_pKeys);
   152 	delete m_pAddresses;
   153 	sm_trie_destroy(m_pSigs);
   154 	delete m_pStrings;
   155 }
   156 
   157 SMCResult CGameConfig::ReadSMC_NewSection(const SMCStates *states, const char *name)
   158 {
   159 	if (m_IgnoreLevel)
   160 	{
   161 		m_IgnoreLevel++;
   162 		return SMCResult_Continue;
   163 	}
   164 
   165 	switch (m_ParseState)
   166 	{
   167 	case PSTATE_NONE:
   168 		{
   169 			if (strcmp(name, "Games") == 0)
   170 			{
   171 				m_ParseState = PSTATE_GAMES;
   172 			} else {
   173 				m_IgnoreLevel++;
   174 			}
   175 			break;
   176 		}
   177 	case PSTATE_GAMES:
   178 		{
   179 			if (strcmp(name, "*") == 0 ||
   180 				strcmp(name, "#default") == 0 ||
   181 				DoesGameMatch(name))
   182 			{
   183 				bShouldBeReadingDefault = true;
   184 				m_ParseState = PSTATE_GAMEDEFS;
   185 				strncopy(m_Game, name, sizeof(m_Game));
   186 			} else {
   187 				m_IgnoreLevel++;
   188 			}
   189 			break;
   190 		}
   191 	case PSTATE_GAMEDEFS:
   192 		{
   193 			if (strcmp(name, "Offsets") == 0)
   194 			{
   195 				m_ParseState = PSTATE_GAMEDEFS_OFFSETS;
   196 			}
   197 			else if (strcmp(name, "Keys") == 0)
   198 			{
   199 				m_ParseState = PSTATE_GAMEDEFS_KEYS;
   200 			}
   201 			else if ((strcmp(name, "#supported") == 0) && (strcmp(m_Game, "#default") == 0))
   202 			{
   203 				m_ParseState = PSTATE_GAMEDEFS_SUPPORTED;
   204 				/* Ignore this section unless we get a game. */
   205 				bShouldBeReadingDefault = false;
   206 				had_game = false;
   207 				matched_game = false;
   208 				had_engine = false;
   209 				matched_engine = false;
   210 			}
   211 			else if (strcmp(name, "Signatures") == 0)
   212 			{
   213 				m_ParseState = PSTATE_GAMEDEFS_SIGNATURES;
   214 			}
   215 			else if (strcmp(name, "CRC") == 0)
   216 			{
   217 				m_ParseState = PSTATE_GAMEDEFS_CRC;
   218 				bShouldBeReadingDefault = false;
   219 			}
   220 			else if (strcmp(name, "Addresses") == 0)
   221 			{
   222 				m_ParseState = PSTATE_GAMEDEFS_ADDRESSES;
   223 			}
   224 			else
   225 			{
   226 				ITextListener_SMC **pListen = g_GameConfigs.m_customHandlers.retrieve(name);
   227 
   228 				if (pListen != NULL)
   229 				{
   230 					m_CustomLevel = 0;
   231 					m_ParseState = PSTATE_GAMEDEFS_CUSTOM;
   232 					m_CustomHandler = *pListen;
   233 					m_CustomHandler->ReadSMC_ParseStart();
   234 					break;
   235 				}
   236 
   237 				m_IgnoreLevel++;
   238 			}
   239 			break;
   240 		}
   241 	case PSTATE_GAMEDEFS_OFFSETS:
   242 		{
   243 			m_Prop[0] = '\0';
   244 			m_Class[0] = '\0';
   245 			strncopy(m_offset, name, sizeof(m_offset));
   246 			m_ParseState = PSTATE_GAMEDEFS_OFFSETS_OFFSET;
   247 			break;
   248 		}
   249 	case PSTATE_GAMEDEFS_SIGNATURES:
   250 		{
   251 			strncopy(m_offset, name, sizeof(m_offset));
   252 			s_TempSig.Reset();
   253 			m_ParseState = PSTATE_GAMEDEFS_SIGNATURES_SIG;
   254 			break;
   255 		}
   256 	case PSTATE_GAMEDEFS_CRC:
   257 		{
   258 			char error[255];
   259 			error[0] = '\0';
   260 			if (strcmp(name, "server") != 0)
   261 			{
   262 				UTIL_Format(error, sizeof(error), "Unrecognized library \"%s\"", name);
   263 			} 
   264 			else if (!s_ServerBinCRC_Ok)
   265 			{
   266 				FILE *fp;
   267 				char path[PLATFORM_MAX_PATH];
   268 
   269 				g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "bin/" PLATFORM_SERVER_BINARY);
   270 				if ((fp = fopen(path, "rb")) == NULL)
   271 				{
   272 					UTIL_Format(error, sizeof(error), "Could not open binary: %s", path);
   273 				} else {
   274 					size_t size;
   275 					void *buffer;
   276 
   277 					fseek(fp, 0, SEEK_END);
   278 					size = ftell(fp);
   279 					fseek(fp, 0, SEEK_SET);
   280 
   281 					buffer = malloc(size);
   282 					fread(buffer, size, 1, fp);
   283 					s_ServerBinCRC = UTIL_CRC32(buffer, size);
   284 					free(buffer);
   285 					s_ServerBinCRC_Ok = true;
   286 					fclose(fp);
   287 				}
   288 			}
   289 			if (error[0] != '\0')
   290 			{
   291 				m_IgnoreLevel = 1;
   292 				g_Logger.LogError("[SM] Error while parsing CRC section for \"%s\" (%s):", m_Game, m_CurFile);
   293 				g_Logger.LogError("[SM] %s", error);
   294 			} else {
   295 				m_ParseState = PSTATE_GAMEDEFS_CRC_BINARY;
   296 			}
   297 			break;
   298 		}
   299 	case PSTATE_GAMEDEFS_CUSTOM:
   300 		{
   301 			m_CustomLevel++;
   302 			return m_CustomHandler->ReadSMC_NewSection(states, name);
   303 			break;
   304 		}
   305 	case PSTATE_GAMEDEFS_ADDRESSES:
   306 		{
   307 			m_Address[0] = '\0';
   308 			m_AddressSignature[0] = '\0';
   309 			m_AddressReadCount = 0;
   310 
   311 			strncopy(m_Address, name, sizeof(m_Address));
   312 			m_ParseState = PSTATE_GAMEDEFS_ADDRESSES_ADDRESS;
   313 
   314 			break;
   315 		}
   316 	case PSTATE_GAMEDEFS_ADDRESSES_ADDRESS:
   317 		{
   318 			if (strcmp(name, PLATFORM_NAME) == 0)
   319 			{
   320 				m_ParseState = PSTATE_GAMEDEFS_ADDRESSES_ADDRESS_READ;
   321 			}
   322 			else
   323 			{
   324 				if (strcmp(name, "linux") != 0 && strcmp(name, "windows") != 0)
   325 				{
   326 					g_Logger.LogError("[SM] Error while parsing Address section for \"%s\" (%s):", m_Address, m_CurFile);
   327 					g_Logger.LogError("[SM] Unrecognized platform \"%s\"", name);
   328 				}
   329 				m_IgnoreLevel = 1;
   330 			}
   331 			break;
   332 		}
   333 	/* No sub-sections allowed:
   334 	 case PSTATE_GAMEDEFS_OFFSETS_OFFSET:
   335 	 case PSTATE_GAMEDEFS_KEYS:
   336 	 case PSTATE_GAMEDEFS_SUPPORTED:
   337 	 case PSTATE_GAMEDEFS_SIGNATURES_SIG:
   338 	 case PSTATE_GAMEDEFS_CRC_BINARY:
   339 	 case PSTATE_GAMEDEFS_ADDRESSES_ADDRESS_READ:
   340 	 */
   341 	default:
   342 		{
   343 			/* If we don't know what we got, start ignoring */
   344 			m_IgnoreLevel++;
   345 			break;
   346 		}
   347 	}
   348 
   349 	return SMCResult_Continue;
   350 }
   351 
   352 SMCResult CGameConfig::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
   353 {
   354 	if (m_IgnoreLevel)
   355 	{
   356 		return SMCResult_Continue;
   357 	}
   358 
   359 	if (m_ParseState == PSTATE_GAMEDEFS_OFFSETS_OFFSET)
   360 	{
   361 		if (strcmp(key, "class") == 0)
   362 		{
   363 			strncopy(m_Class, value, sizeof(m_Class));
   364 		} else if (strcmp(key, "prop") == 0) {
   365 			strncopy(m_Prop, value, sizeof(m_Prop));
   366 		} else if (strcmp(key, PLATFORM_NAME) == 0) {
   367 			int val = atoi(value);
   368 			sm_trie_replace(m_pOffsets, m_offset, (void *)val);
   369 		}
   370 	} else if (m_ParseState == PSTATE_GAMEDEFS_KEYS) {
   371 		int id = m_pStrings->AddString(value);
   372 		sm_trie_replace(m_pKeys, key, (void *)id);
   373 	} else if (m_ParseState == PSTATE_GAMEDEFS_SUPPORTED) {
   374 		if (strcmp(key, "game") == 0)
   375 		{
   376 			had_game = true;
   377 			if (DoesGameMatch(value))
   378 			{
   379 				matched_game = true;
   380 			}
   381 			if ((!had_engine && matched_game) || (matched_engine && matched_game))
   382 			{
   383 				bShouldBeReadingDefault = true;
   384 			}
   385 		}
   386 		else if (strcmp(key, "engine") == 0)
   387 		{
   388 			had_engine = true;
   389 			if (DoesEngineMatch(value))
   390 			{
   391 				matched_engine = true;
   392 			}
   393 			if ((!had_game && matched_engine) || (matched_game && matched_engine))
   394 			{
   395 				bShouldBeReadingDefault = true;
   396 			}
   397 		}
   398 	} else if (m_ParseState == PSTATE_GAMEDEFS_SIGNATURES_SIG) {
   399 		if (strcmp(key, PLATFORM_NAME) == 0)
   400 		{
   401 			strncopy(s_TempSig.sig, value, sizeof(s_TempSig.sig));
   402 		} else if (strcmp(key, "library") == 0) {
   403 			strncopy(s_TempSig.library, value, sizeof(s_TempSig.library));
   404 		}
   405 	} else if (m_ParseState == PSTATE_GAMEDEFS_CRC_BINARY) {
   406 		if (strcmp(key, PLATFORM_NAME) == 0 
   407 			&& s_ServerBinCRC_Ok
   408 			&& !bShouldBeReadingDefault)
   409 		{
   410 			unsigned int crc = 0;
   411 			sscanf(value, "%08X", &crc);
   412 			if (s_ServerBinCRC == crc)
   413 			{
   414 				bShouldBeReadingDefault = true;
   415 			}
   416 		}
   417 	} else if (m_ParseState == PSTATE_GAMEDEFS_ADDRESSES_ADDRESS || m_ParseState == PSTATE_GAMEDEFS_ADDRESSES_ADDRESS_READ) {
   418 		if (strcmp(key, "read") == 0) {
   419 			int limit = sizeof(m_AddressRead)/sizeof(m_AddressRead[0]);
   420 			if (m_AddressReadCount < limit)
   421 			{
   422 				m_AddressRead[m_AddressReadCount] = atoi(value);
   423 				m_AddressReadCount++;
   424 			}
   425 			else
   426 			{
   427 				g_Logger.LogError("[SM] Error parsing Address \"%s\", does not support more than %d read offsets (gameconf \"%s\")", m_Address, limit, m_CurFile);
   428 			}
   429 		} else if (strcmp(key, "signature") == 0) {
   430 			strncopy(m_AddressSignature, value, sizeof(m_AddressSignature));
   431 		}
   432 	} else if (m_ParseState == PSTATE_GAMEDEFS_CUSTOM) {
   433 		return m_CustomHandler->ReadSMC_KeyValue(states, key, value);
   434 	}
   435 
   436 	return SMCResult_Continue;
   437 }
   438 
   439 SMCResult CGameConfig::ReadSMC_LeavingSection(const SMCStates *states)
   440 {
   441 	if (m_IgnoreLevel)
   442 	{
   443 		m_IgnoreLevel--;
   444 		return SMCResult_Continue;
   445 	}
   446 
   447 	if (m_CustomLevel)
   448 	{
   449 		m_CustomLevel--;
   450 		m_CustomHandler->ReadSMC_LeavingSection(states);
   451 		return SMCResult_Continue;
   452 	}
   453 
   454 	switch (m_ParseState)
   455 	{
   456 	case PSTATE_GAMES:
   457 		{
   458 			m_ParseState = PSTATE_NONE;
   459 			break;
   460 		}
   461 	case PSTATE_GAMEDEFS:
   462 		{
   463 			m_ParseState = PSTATE_GAMES;
   464 			break;
   465 		}
   466 	case PSTATE_GAMEDEFS_CUSTOM:
   467 		{
   468 			m_ParseState = PSTATE_GAMEDEFS;
   469 			m_CustomHandler->ReadSMC_ParseEnd(false, false);
   470 			break;
   471 		}
   472 	case PSTATE_GAMEDEFS_KEYS:
   473 	case PSTATE_GAMEDEFS_OFFSETS:
   474 		{
   475 			m_ParseState = PSTATE_GAMEDEFS;
   476 			break;
   477 		}
   478 	case PSTATE_GAMEDEFS_OFFSETS_OFFSET:
   479 		{
   480 			/* Parse the offset... */
   481 			if (m_Class[0] != '\0'
   482 				&& m_Prop[0] != '\0')
   483 			{
   484 				SendProp *pProp = g_HL2.FindInSendTable(m_Class, m_Prop);
   485 				if (pProp)
   486 				{
   487 					int val = pProp->GetOffset();
   488 					sm_trie_replace(m_pOffsets, m_offset, (void *)val);
   489 					sm_trie_replace(m_pProps, m_offset, pProp);
   490 				} else {
   491 					/* Check if it's a non-default game and no offsets exist */
   492 					if (((strcmp(m_Game, "*") != 0) && strcmp(m_Game, "#default") != 0)
   493 						&& (!sm_trie_retrieve(m_pOffsets, m_offset, NULL)))
   494 					{
   495 						g_Logger.LogError("[SM] Unable to find property %s.%s (file \"%s\") (mod \"%s\")", 
   496 							m_Class,
   497 							m_Prop,
   498 							m_CurFile,
   499 							m_Game);
   500 					}
   501 				}
   502 			}
   503 			m_ParseState = PSTATE_GAMEDEFS_OFFSETS;
   504 			break;
   505 		}
   506 	case PSTATE_GAMEDEFS_CRC:
   507 	case PSTATE_GAMEDEFS_SUPPORTED:
   508 		{
   509 			if (!bShouldBeReadingDefault)
   510 			{
   511 				/* If we shouldn't read the rest of this section, set the ignore level. */
   512 				m_IgnoreLevel = 1;
   513 				m_ParseState = PSTATE_GAMES;
   514 			} else {
   515 				m_ParseState = PSTATE_GAMEDEFS;
   516 			}
   517 			break;
   518 		}
   519 	case PSTATE_GAMEDEFS_CRC_BINARY:
   520 		{
   521 			m_ParseState = PSTATE_GAMEDEFS_CRC;
   522 			break;
   523 		}
   524 	case PSTATE_GAMEDEFS_SIGNATURES:
   525 		{
   526 			m_ParseState = PSTATE_GAMEDEFS;
   527 			break;
   528 		}
   529 	case PSTATE_GAMEDEFS_SIGNATURES_SIG:
   530 		{
   531 			if (s_TempSig.library[0] == '\0')
   532 			{
   533 				/* assume server */
   534 				strncopy(s_TempSig.library, "server", sizeof(s_TempSig.library));
   535 			}
   536 			void *addrInBase = NULL;
   537 			if (strcmp(s_TempSig.library, "server") == 0)
   538 			{
   539 				addrInBase = (void *)g_SMAPI->GetServerFactory(false);
   540 			} else if (strcmp(s_TempSig.library, "engine") == 0) {
   541 				addrInBase = (void *)g_SMAPI->GetEngineFactory(false);
   542 			}
   543 			void *final_addr = NULL;
   544 			if (addrInBase == NULL)
   545 			{
   546 				g_Logger.LogError("[SM] Unrecognized library \"%s\" (gameconf \"%s\")", 
   547 					s_TempSig.library, 
   548 					m_CurFile);
   549 			} else {
   550 #if defined PLATFORM_LINUX
   551 				if (s_TempSig.sig[0] == '@')
   552 				{
   553 					Dl_info info;
   554 					/* GNU only: returns 0 on error, inconsistent! >:[ */
   555 					if (dladdr(addrInBase, &info) != 0)
   556 					{
   557 						void *handle = dlopen(info.dli_fname, RTLD_NOW);
   558 						if (handle)
   559 						{
   560 #if SOURCE_ENGINE == SE_LEFT4DEAD2
   561 							final_addr = g_MemUtils.ResolveSymbol(handle, &s_TempSig.sig[1]);
   562 #else
   563 							final_addr = dlsym(handle, &s_TempSig.sig[1]);
   564 #endif
   565 							dlclose(handle);
   566 						} else {
   567 							g_Logger.LogError("[SM] Unable to load library \"%s\" (gameconf \"%s\")",
   568 								s_TempSig.library,
   569 								m_File);
   570 						}
   571 					} else {
   572 						g_Logger.LogError("[SM] Unable to find library \"%s\" in memory (gameconf \"%s\")",
   573 							s_TempSig.library,
   574 							m_File);
   575 					}
   576 				}
   577 				if (final_addr)
   578 				{
   579 					goto skip_find;
   580 				}
   581 #endif
   582 				/* First, preprocess the signature */
   583 				unsigned char real_sig[511];
   584 				size_t real_bytes;
   585 				size_t length;
   586 
   587 				real_bytes = 0;
   588 				length = strlen(s_TempSig.sig);
   589 
   590 				real_bytes = UTIL_DecodeHexString(real_sig, sizeof(real_sig), s_TempSig.sig);
   591 
   592 				if (real_bytes >= 1)
   593 				{
   594 					final_addr = g_MemUtils.FindPattern(addrInBase, (char*)real_sig, real_bytes);
   595 				}
   596 			}
   597 
   598 #if defined PLATFORM_LINUX
   599 skip_find:
   600 #endif
   601 			sm_trie_replace(m_pSigs, m_offset, final_addr);
   602 			m_ParseState = PSTATE_GAMEDEFS_SIGNATURES;
   603 
   604 			break;
   605 		}
   606 	case PSTATE_GAMEDEFS_ADDRESSES:
   607 		{
   608 			m_ParseState = PSTATE_GAMEDEFS;
   609 			break;
   610 		}
   611 	case PSTATE_GAMEDEFS_ADDRESSES_ADDRESS:
   612 		{
   613 			m_ParseState = PSTATE_GAMEDEFS_ADDRESSES;
   614 
   615 			if (m_Address[0] == '\0')
   616 			{
   617 				g_Logger.LogError("[SM] Address sections must have names (gameconf \"%s\")", m_CurFile);
   618 				break;
   619 			}
   620 			if (m_AddressSignature[0] == '\0')
   621 			{
   622 				g_Logger.LogError("[SM] Address section for \"%s\" did not specify a signature (gameconf \"%s\")", m_Address, m_CurFile);
   623 				break;
   624 			}
   625 
   626 			AddressConf addrConf(m_AddressSignature, sizeof(m_AddressSignature), m_AddressReadCount, m_AddressRead);
   627 			m_pAddresses->replace(m_Address, addrConf);
   628 
   629 			break;
   630 		}
   631 	case PSTATE_GAMEDEFS_ADDRESSES_ADDRESS_READ:
   632 		{
   633 			m_ParseState = PSTATE_GAMEDEFS_ADDRESSES_ADDRESS;
   634 			break;
   635 		}
   636 	}
   637 
   638 	return SMCResult_Continue;
   639 }
   640 
   641 #define MSTATE_NONE		0
   642 #define MSTATE_MAIN		1
   643 #define MSTATE_FILE		2
   644 
   645 class MasterReader : public ITextListener_SMC
   646 {
   647 public:
   648 	virtual void ReadSMC_ParseStart()
   649 	{
   650 		state = MSTATE_NONE;
   651 		ignoreLevel = 0;
   652 	}
   653 
   654 	virtual SMCResult ReadSMC_NewSection(const SMCStates *states, const char *name)
   655 	{
   656 		if (ignoreLevel)
   657 		{
   658 			return SMCResult_Continue;
   659 		}
   660 
   661 		if (state == MSTATE_NONE)
   662 		{
   663 			if (strcmp(name, "Game Master") == 0)
   664 			{
   665 				state = MSTATE_MAIN;
   666 			}
   667 			else
   668 			{
   669 				ignoreLevel++;
   670 			}
   671 		}
   672 		else if (state == MSTATE_MAIN)
   673 		{
   674 			strncopy(cur_file, name, sizeof(cur_file));
   675 			had_engine = false;
   676 			matched_engine = false;
   677 			had_game = false;
   678 			matched_game = false;
   679 			state = MSTATE_FILE;
   680 		}
   681 		else if (state == MSTATE_FILE)
   682 		{
   683 			ignoreLevel++;
   684 		}
   685 
   686 		return SMCResult_Continue;
   687 	}
   688 
   689 	virtual SMCResult ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
   690 	{
   691 		if (ignoreLevel || state != MSTATE_FILE)
   692 		{
   693 			return SMCResult_Continue;
   694 		}
   695 
   696 		if (strcmp(key, "engine") == 0)
   697 		{
   698 			had_engine = true;
   699 			if (DoesEngineMatch(value))
   700 			{
   701 				matched_engine = true;
   702 			}
   703 		}
   704 		else if (strcmp(key, "game") == 0)
   705 		{
   706 			had_game = true;
   707 			if (DoesGameMatch(value))
   708 			{
   709 				matched_game = true;
   710 			}
   711 		}
   712 
   713 		return SMCResult_Continue;
   714 	}
   715 
   716 	virtual SMCResult ReadSMC_LeavingSection(const SMCStates *states)
   717 	{
   718 		if (ignoreLevel)
   719 		{
   720 			ignoreLevel--;
   721 			return SMCResult_Continue;
   722 		}
   723 
   724 		if (state == MSTATE_FILE)
   725 		{
   726 			/* The four success conditions:
   727 			 * 1. Needed nothing.
   728 			 * 2. Needed game only.
   729 			 * 3. Needed engine only.
   730 			 * 4. Needed both engine and game.
   731 			 * Final result is minimized via k-map.
   732 			 */
   733 #if 0
   734 			if ((!had_engine && !had_game) ||
   735 				(!had_engine && (had_game && matched_game)) ||
   736 				(!had_game && (had_engine && matched_engine)) ||
   737 				((had_game && had_engine) && (matched_game && matched_engine)))
   738 #endif
   739 			if ((!had_engine && !had_game) ||
   740 				(!had_engine && matched_game) ||
   741 				(!had_game && matched_engine) ||
   742 				(matched_engine && matched_game))
   743 			{
   744 				fileList->push_back(cur_file);
   745 			}
   746 			state = MSTATE_MAIN;
   747 		}
   748 		else if (state == MSTATE_MAIN)
   749 		{
   750 			state = MSTATE_NONE;
   751 		}
   752 
   753 		return SMCResult_Continue;
   754 	}
   755 public:
   756 	List<String> *fileList;
   757 	unsigned int state;
   758 	unsigned int ignoreLevel;
   759 	char cur_file[PLATFORM_MAX_PATH];
   760 	bool had_engine;
   761 	bool matched_engine;
   762 	bool had_game;
   763 	bool matched_game;
   764 };
   765 
   766 static MasterReader master_reader;
   767 
   768 bool CGameConfig::Reparse(char *error, size_t maxlength)
   769 {
   770 	/* Reset cached data */
   771 	m_pStrings->Reset();
   772 	sm_trie_clear(m_pOffsets);
   773 	sm_trie_clear(m_pProps);
   774 	sm_trie_clear(m_pKeys);
   775 	m_pAddresses->clear();
   776 
   777 	char path[PLATFORM_MAX_PATH];
   778 
   779 	/* See if we can use the extended gamedata format. */
   780 	g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "gamedata/%s/master.games.txt", m_File);
   781 	if (!g_LibSys.PathExists(path))
   782 	{
   783 		/* Nope, use the old mechanism. */
   784 		UTIL_Format(path, sizeof(path), "%s.txt", m_File);
   785 		return EnterFile(path, error, maxlength);
   786 	}
   787 
   788 	/* Otherwise, it's time to parse the master. */
   789 	SMCError err;
   790 	SMCStates state = {0, 0};
   791 	List<String> fileList;
   792 	master_reader.fileList = &fileList;
   793 
   794 	err = textparsers->ParseSMCFile(path, &master_reader, &state, error, maxlength);
   795 	if (err != SMCError_Okay)
   796 	{
   797 		const char *msg = textparsers->GetSMCErrorString(err);
   798 
   799 		g_Logger.LogError("[SM] Error parsing master gameconf file \"%s\":", path);
   800 		g_Logger.LogError("[SM] Error %d on line %d, col %d: %s", 
   801 			err,
   802 			state.line,
   803 			state.col,
   804 			msg ? msg : "Unknown error");
   805 		return false;
   806 	}
   807 
   808 	/* Go through each file we found and parse it. */
   809 	List<String>::iterator iter;
   810 	for (iter = fileList.begin(); iter != fileList.end(); iter++)
   811 	{
   812 		UTIL_Format(path, sizeof(path), "%s/%s", m_File, (*iter).c_str());
   813 		if (!EnterFile(path, error, maxlength))
   814 		{
   815 			return false;
   816 		}
   817 	}
   818 
   819 	/* Parse the contents of the 'custom' directory */
   820 	g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "gamedata/%s/custom", m_File);
   821 	IDirectory *customDir = g_LibSys.OpenDirectory(path);
   822 
   823 	if (!customDir)
   824 	{
   825 		return true;
   826 	}
   827 
   828 	while (customDir->MoreFiles())
   829 	{
   830 		if (!customDir->IsEntryFile())
   831 		{
   832 			customDir->NextEntry();
   833 			continue;
   834 		}
   835 		
   836 		const char *curFile = customDir->GetEntryName();
   837 
   838 		/* Only allow .txt files */
   839 		int len = strlen(curFile);
   840 		if (len > 4 && strcmp(&curFile[len-4], ".txt") != 0)
   841 		{
   842 			customDir->NextEntry();
   843 			continue;	
   844 		}
   845 
   846 		UTIL_Format(path, sizeof(path), "%s/custom/%s", m_File, curFile);
   847 		if (!EnterFile(path, error, maxlength))
   848 		{
   849 			g_LibSys.CloseDirectory(customDir);
   850 			return false;
   851 		}
   852 
   853 		customDir->NextEntry();
   854 	}
   855 
   856 	g_LibSys.CloseDirectory(customDir);
   857 	return true;
   858 }
   859 
   860 bool CGameConfig::EnterFile(const char *file, char *error, size_t maxlength)
   861 {
   862 	SMCError err;
   863 	SMCStates state = {0, 0};
   864 
   865 	g_SourceMod.BuildPath(Path_SM, m_CurFile, sizeof(m_CurFile), "gamedata/%s", file);
   866 
   867 	/* Initialize parse states */
   868 	m_IgnoreLevel = 0;
   869 	bShouldBeReadingDefault = true;
   870 	m_ParseState = PSTATE_NONE;
   871 
   872 	if ((err=textparsers->ParseSMCFile(m_CurFile, this, &state, error, maxlength))
   873 		!= SMCError_Okay)
   874 	{
   875 		const char *msg;
   876 
   877 		msg = textparsers->GetSMCErrorString(err);
   878 
   879 		g_Logger.LogError("[SM] Error parsing gameconfig file \"%s\":", m_CurFile);
   880 		g_Logger.LogError("[SM] Error %d on line %d, col %d: %s", 
   881 			err,
   882 			state.line,
   883 			state.col,
   884 			msg ? msg : "Unknown error");
   885 
   886 		if (m_ParseState == PSTATE_GAMEDEFS_CUSTOM)
   887 		{
   888 			//error occurred while parsing a custom section
   889 			m_CustomHandler->ReadSMC_ParseEnd(true, true);
   890 			m_CustomHandler = NULL;
   891 			m_CustomLevel = 0;
   892 		}
   893 
   894 		return false;
   895 	}
   896 
   897 	return true;
   898 }
   899 
   900 bool CGameConfig::GetOffset(const char *key, int *value)
   901 {
   902 	void *obj;
   903 
   904 	if (!sm_trie_retrieve(m_pOffsets, key, &obj))
   905 	{
   906 		return false;
   907 	}
   908 
   909 	*value = (int)obj;
   910 	
   911 	return true;
   912 }
   913 
   914 const char *CGameConfig::GetKeyValue(const char *key)
   915 {
   916 	void *obj;
   917 	if (!sm_trie_retrieve(m_pKeys, key, &obj))
   918 	{
   919 		return NULL;
   920 	}
   921 	return m_pStrings->GetString((int)obj);
   922 }
   923 
   924 //memory addresses below 0x10000 are automatically considered invalid for dereferencing
   925 #define VALID_MINIMUM_MEMORY_ADDRESS 0x10000
   926 
   927 bool CGameConfig::GetAddress(const char *key, void **retaddr)
   928 {
   929 	AddressConf *addrConf;
   930 
   931 	addrConf = m_pAddresses->retrieve(key);
   932 	if (!addrConf)
   933 	{
   934 		*retaddr = NULL;
   935 		return false;
   936 	}
   937 
   938 	void *addr;
   939 	if (!GetMemSig(addrConf->signatureName, &addr))
   940 	{
   941 		*retaddr = NULL;
   942 		return false;
   943 	}
   944 
   945 	for (int i = 0; i < addrConf->readCount; ++i)
   946 	{
   947 		int offset = addrConf->read[i];
   948 
   949 		//NULLs in the middle of an indirection chain are bad, end NULL is ok
   950 		if (addr ==  NULL || reinterpret_cast<uintptr_t>(addr) < VALID_MINIMUM_MEMORY_ADDRESS)
   951 		{
   952 			*retaddr = NULL;
   953 			return false;
   954 		}
   955 		addr = *(reinterpret_cast<void**>(reinterpret_cast<uint8_t*>(addr) + offset));
   956 	}
   957 
   958 	*retaddr = addr;
   959 	return true;
   960 }
   961 
   962 CGameConfig::AddressConf::AddressConf(char *sigName, unsigned sigLength, unsigned readCount, int *read)
   963 {
   964 	unsigned readLimit = min(readCount, sizeof(this->read) / sizeof(this->read[0]));
   965 
   966 	strncopy(signatureName, sigName, sizeof(signatureName) / sizeof(signatureName[0]));
   967 	this->readCount = readLimit;
   968 	memcpy(&this->read[0], read, sizeof(this->read[0])*readLimit);
   969 }
   970 
   971 SendProp *CGameConfig::GetSendProp(const char *key)
   972 {
   973 	SendProp *pProp;
   974 
   975 	if (!sm_trie_retrieve(m_pProps, key, (void **)&pProp))
   976 	{
   977 		return NULL;
   978 	}
   979 
   980 	return pProp;
   981 }
   982 
   983 bool CGameConfig::GetMemSig(const char *key, void **addr)
   984 {
   985 	return sm_trie_retrieve(m_pSigs, key, addr);
   986 }
   987 
   988 void CGameConfig::IncRefCount()
   989 {
   990 	m_RefCount++;
   991 }
   992 
   993 unsigned int CGameConfig::DecRefCount()
   994 {
   995 	m_RefCount--;
   996 	return m_RefCount;
   997 }
   998 
   999 GameConfigManager::GameConfigManager()
  1000 {
  1001 	m_pLookup = sm_trie_create();
  1002 }
  1003 
  1004 GameConfigManager::~GameConfigManager()
  1005 {
  1006 	sm_trie_destroy(m_pLookup);
  1007 }
  1008 
  1009 void GameConfigManager::OnSourceModStartup(bool late)
  1010 {
  1011 	LoadGameConfigFile("core.games", &g_pGameConf, NULL, 0);
  1012 
  1013 	strncopy(g_Game, g_SourceMod.GetGameFolderName(), sizeof(g_Game));
  1014 	strncopy(g_GameDesc + 1, SERVER_CALL(GetGameDescription)(), sizeof(g_GameDesc) - 1);
  1015 
  1016 	KeyValues *pGameInfo = new KeyValues("GameInfo");
  1017 	if (g_HL2.KVLoadFromFile(pGameInfo, basefilesystem, "gameinfo.txt"))
  1018 	{
  1019 		const char *str;
  1020 		if ((str = pGameInfo->GetString("game", NULL)) != NULL)
  1021 		{
  1022 			strncopy(g_GameName + 1, str, sizeof(g_GameName) - 1);
  1023 		}
  1024 	}
  1025 	pGameInfo->deleteThis();
  1026 }
  1027 
  1028 void GameConfigManager::OnSourceModAllInitialized()
  1029 {
  1030 	/* NOW initialize the game file */
  1031 	CGameConfig *pGameConf = (CGameConfig *)g_pGameConf;
  1032 	
  1033 	char error[255];
  1034 	if (!pGameConf->Reparse(error, sizeof(error)))
  1035 	{
  1036 		/* :TODO: log */
  1037 	}
  1038 
  1039 	g_ShareSys.AddInterface(NULL, this);
  1040 }
  1041 
  1042 void GameConfigManager::OnSourceModAllShutdown()
  1043 {
  1044 	CloseGameConfigFile(g_pGameConf);
  1045 }
  1046 
  1047 bool GameConfigManager::LoadGameConfigFile(const char *file, IGameConfig **_pConfig, char *error, size_t maxlength)
  1048 {
  1049 #if 0
  1050 	/* A crash was detected during last load - We block the gamedata loading so it hopefully won't happen again */
  1051 	if (g_blockGameDataLoad)
  1052 	{
  1053 		UTIL_Format(error, maxlength, "GameData loaded blocked due to detected crash");
  1054 		return false;
  1055 	}
  1056 #endif
  1057 
  1058 	CGameConfig *pConfig;
  1059 
  1060 	if (sm_trie_retrieve(m_pLookup, file, (void **)&pConfig))
  1061 	{
  1062 		pConfig->IncRefCount();
  1063 		*_pConfig = pConfig;
  1064 		return true;
  1065 	}
  1066 
  1067 	pConfig = new CGameConfig(file);
  1068 
  1069 	/* :HACKHACK: Don't parse the main config file */
  1070 	bool retval = true;
  1071 	if (_pConfig != &g_pGameConf)
  1072 	{
  1073 		retval = pConfig->Reparse(error, maxlength);
  1074 	}
  1075 
  1076 	m_cfgs.push_back(pConfig);
  1077 	sm_trie_insert(m_pLookup, file, pConfig);
  1078 
  1079 	pConfig->IncRefCount();
  1080 
  1081 	*_pConfig = pConfig;
  1082 
  1083 	return retval;
  1084 }
  1085 
  1086 void GameConfigManager::CloseGameConfigFile(IGameConfig *cfg)
  1087 {
  1088 	CGameConfig *pConfig = (CGameConfig *)cfg;
  1089 
  1090 	if (pConfig->DecRefCount() == 0)
  1091 	{
  1092 		sm_trie_delete(m_pLookup, pConfig->m_File);
  1093 		delete pConfig;
  1094 	}
  1095 }
  1096 
  1097 extern HandleType_t g_GameConfigsType;
  1098 
  1099 IGameConfig *GameConfigManager::ReadHandle(Handle_t hndl, IdentityToken_t *ident, HandleError *err)
  1100 {
  1101 	HandleSecurity sec(ident, g_pCoreIdent);
  1102 	IGameConfig *conf = NULL;
  1103 	HandleError _err = g_HandleSys.ReadHandle(hndl, g_GameConfigsType, &sec, (void **)&conf);
  1104 
  1105 	if (err)
  1106 	{
  1107 		*err = _err;
  1108 	}
  1109 
  1110 	return conf;
  1111 }
  1112 
  1113 void GameConfigManager::AddUserConfigHook(const char *sectionname, ITextListener_SMC *listener)
  1114 {
  1115 	m_customHandlers.insert(sectionname, listener);
  1116 }
  1117 
  1118 void GameConfigManager::RemoveUserConfigHook(const char *sectionname, ITextListener_SMC *listener)
  1119 {
  1120 	ITextListener_SMC **pListener = m_customHandlers.retrieve(sectionname);
  1121 
  1122 	if (pListener == NULL)
  1123 	{
  1124 		return;
  1125 	}
  1126 
  1127 	if (*pListener != listener)
  1128 	{
  1129 		return;
  1130 	}
  1131 
  1132 	m_customHandlers.remove(sectionname);
  1133 	
  1134 	return;
  1135 }
  1136 
  1137 void GameConfigManager::AcquireLock()
  1138 {
  1139 }
  1140 
  1141 void GameConfigManager::ReleaseLock()
  1142 {
  1143 }