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