core/logic/GameConfigs.cpp
author Asher Baker <asherkin@gmail.com>
Thu May 16 14:58:14 2013 +0100 (2013-05-16)
changeset 3920 e4fa6b583893
parent 3664 3db8a3ec8d56
child 3961 0dc477c29792
permissions -rw-r--r--
Fixed copy-paste error in 116256b519b5.
     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_POSIX
    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               "mac"
    82 #define PLATFORM_SERVER_BINARY      "server.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 && strcmp(name, "mac") != 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 			} else if (strcmp(s_TempSig.library, "matchmaking_ds") == 0) {
   519 				addrInBase = smcore.matchmakingDSFactory;
   520 			}
   521 			void *final_addr = NULL;
   522 			if (addrInBase == NULL)
   523 			{
   524 				smcore.LogError("[SM] Unrecognized library \"%s\" (gameconf \"%s\")", 
   525 					s_TempSig.library, 
   526 					m_CurFile);
   527 			} else {
   528 				if (s_TempSig.sig[0] == '@')
   529 				{
   530 #if defined PLATFORM_WINDOWS
   531 					MEMORY_BASIC_INFORMATION mem;
   532 
   533 					if (VirtualQuery(addrInBase, &mem, sizeof(mem)))
   534 						final_addr = g_MemUtils.ResolveSymbol(mem.AllocationBase, &s_TempSig.sig[1]);
   535 					else
   536 						smcore.LogError("[SM] Unable to find library \"%s\" in memory (gameconf \"%s\")", s_TempSig.library, m_File);
   537 #elif defined PLATFORM_POSIX
   538 					Dl_info info;
   539 					/* GNU only: returns 0 on error, inconsistent! >:[ */
   540 					if (dladdr(addrInBase, &info) != 0)
   541 					{
   542 						void *handle = dlopen(info.dli_fname, RTLD_NOW);
   543 						if (handle)
   544 						{
   545 							if (smcore.SymbolsAreHidden())
   546 								final_addr = g_MemUtils.ResolveSymbol(handle, &s_TempSig.sig[1]);
   547 							else
   548 								final_addr = dlsym(handle, &s_TempSig.sig[1]);
   549 							dlclose(handle);
   550 						} else {
   551 							smcore.LogError("[SM] Unable to load library \"%s\" (gameconf \"%s\")",
   552 								s_TempSig.library,
   553 								m_File);
   554 						}
   555 					} else {
   556 						smcore.LogError("[SM] Unable to find library \"%s\" in memory (gameconf \"%s\")",
   557 							s_TempSig.library,
   558 							m_File);
   559 					}
   560 #endif
   561 				}
   562 				if (final_addr)
   563 				{
   564 					goto skip_find;
   565 				}
   566 				/* First, preprocess the signature */
   567 				unsigned char real_sig[511];
   568 				size_t real_bytes;
   569 				size_t length;
   570 
   571 				real_bytes = 0;
   572 				length = strlen(s_TempSig.sig);
   573 
   574 				real_bytes = UTIL_DecodeHexString(real_sig, sizeof(real_sig), s_TempSig.sig);
   575 
   576 				if (real_bytes >= 1)
   577 				{
   578 					final_addr = g_MemUtils.FindPattern(addrInBase, (char*)real_sig, real_bytes);
   579 				}
   580 			}
   581 
   582 skip_find:
   583 			m_Sigs.replace(m_offset, final_addr);
   584 			m_ParseState = PSTATE_GAMEDEFS_SIGNATURES;
   585 
   586 			break;
   587 		}
   588 	case PSTATE_GAMEDEFS_ADDRESSES:
   589 		{
   590 			m_ParseState = PSTATE_GAMEDEFS;
   591 			break;
   592 		}
   593 	case PSTATE_GAMEDEFS_ADDRESSES_ADDRESS:
   594 		{
   595 			m_ParseState = PSTATE_GAMEDEFS_ADDRESSES;
   596 
   597 			if (m_Address[0] == '\0')
   598 			{
   599 				smcore.LogError("[SM] Address sections must have names (gameconf \"%s\")", m_CurFile);
   600 				break;
   601 			}
   602 			if (m_AddressSignature[0] == '\0')
   603 			{
   604 				smcore.LogError("[SM] Address section for \"%s\" did not specify a signature (gameconf \"%s\")", m_Address, m_CurFile);
   605 				break;
   606 			}
   607 
   608 			AddressConf addrConf(m_AddressSignature, sizeof(m_AddressSignature), m_AddressReadCount, m_AddressRead);
   609 			m_pAddresses->replace(m_Address, addrConf);
   610 
   611 			break;
   612 		}
   613 	case PSTATE_GAMEDEFS_ADDRESSES_ADDRESS_READ:
   614 		{
   615 			m_ParseState = PSTATE_GAMEDEFS_ADDRESSES_ADDRESS;
   616 			break;
   617 		}
   618 	}
   619 
   620 	return SMCResult_Continue;
   621 }
   622 
   623 #define MSTATE_NONE		0
   624 #define MSTATE_MAIN		1
   625 #define MSTATE_FILE		2
   626 
   627 class MasterReader : public ITextListener_SMC
   628 {
   629 public:
   630 	virtual void ReadSMC_ParseStart()
   631 	{
   632 		state = MSTATE_NONE;
   633 		ignoreLevel = 0;
   634 	}
   635 
   636 	virtual SMCResult ReadSMC_NewSection(const SMCStates *states, const char *name)
   637 	{
   638 		if (ignoreLevel)
   639 		{
   640 			return SMCResult_Continue;
   641 		}
   642 
   643 		if (state == MSTATE_NONE)
   644 		{
   645 			if (strcmp(name, "Game Master") == 0)
   646 			{
   647 				state = MSTATE_MAIN;
   648 			}
   649 			else
   650 			{
   651 				ignoreLevel++;
   652 			}
   653 		}
   654 		else if (state == MSTATE_MAIN)
   655 		{
   656 			strncopy(cur_file, name, sizeof(cur_file));
   657 			had_engine = false;
   658 			matched_engine = false;
   659 			had_game = false;
   660 			matched_game = false;
   661 			state = MSTATE_FILE;
   662 		}
   663 		else if (state == MSTATE_FILE)
   664 		{
   665 			ignoreLevel++;
   666 		}
   667 
   668 		return SMCResult_Continue;
   669 	}
   670 
   671 	virtual SMCResult ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
   672 	{
   673 		if (ignoreLevel || state != MSTATE_FILE)
   674 		{
   675 			return SMCResult_Continue;
   676 		}
   677 
   678 		if (strcmp(key, "engine") == 0)
   679 		{
   680 			had_engine = true;
   681 			if (DoesEngineMatch(value))
   682 			{
   683 				matched_engine = true;
   684 			}
   685 		}
   686 		else if (strcmp(key, "game") == 0)
   687 		{
   688 			had_game = true;
   689 			if (DoesGameMatch(value))
   690 			{
   691 				matched_game = true;
   692 			}
   693 		}
   694 
   695 		return SMCResult_Continue;
   696 	}
   697 
   698 	virtual SMCResult ReadSMC_LeavingSection(const SMCStates *states)
   699 	{
   700 		if (ignoreLevel)
   701 		{
   702 			ignoreLevel--;
   703 			return SMCResult_Continue;
   704 		}
   705 
   706 		if (state == MSTATE_FILE)
   707 		{
   708 			/* The four success conditions:
   709 			 * 1. Needed nothing.
   710 			 * 2. Needed game only.
   711 			 * 3. Needed engine only.
   712 			 * 4. Needed both engine and game.
   713 			 * Final result is minimized via k-map.
   714 			 */
   715 #if 0
   716 			if ((!had_engine && !had_game) ||
   717 				(!had_engine && (had_game && matched_game)) ||
   718 				(!had_game && (had_engine && matched_engine)) ||
   719 				((had_game && had_engine) && (matched_game && matched_engine)))
   720 #endif
   721 			if ((!had_engine && !had_game) ||
   722 				(!had_engine && matched_game) ||
   723 				(!had_game && matched_engine) ||
   724 				(matched_engine && matched_game))
   725 			{
   726 				fileList->push_back(cur_file);
   727 			}
   728 			state = MSTATE_MAIN;
   729 		}
   730 		else if (state == MSTATE_MAIN)
   731 		{
   732 			state = MSTATE_NONE;
   733 		}
   734 
   735 		return SMCResult_Continue;
   736 	}
   737 public:
   738 	List<String> *fileList;
   739 	unsigned int state;
   740 	unsigned int ignoreLevel;
   741 	char cur_file[PLATFORM_MAX_PATH];
   742 	bool had_engine;
   743 	bool matched_engine;
   744 	bool had_game;
   745 	bool matched_game;
   746 };
   747 
   748 static MasterReader master_reader;
   749 
   750 bool CGameConfig::Reparse(char *error, size_t maxlength)
   751 {
   752 	/* Reset cached data */
   753 	m_pStrings->Reset();
   754 	m_Offsets.clear();
   755 	m_Props.clear();
   756 	m_Keys.clear();
   757 	m_pAddresses->clear();
   758 
   759 	char path[PLATFORM_MAX_PATH];
   760 
   761 	/* See if we can use the extended gamedata format. */
   762 	g_pSM->BuildPath(Path_SM, path, sizeof(path), "gamedata/%s/master.games.txt", m_File);
   763 	if (!libsys->PathExists(path))
   764 	{
   765 		/* Nope, use the old mechanism. */
   766 		smcore.Format(path, sizeof(path), "%s.txt", m_File);
   767 		return EnterFile(path, error, maxlength);
   768 	}
   769 
   770 	/* Otherwise, it's time to parse the master. */
   771 	SMCError err;
   772 	SMCStates state = {0, 0};
   773 	List<String> fileList;
   774 	master_reader.fileList = &fileList;
   775 
   776 	err = textparsers->ParseSMCFile(path, &master_reader, &state, error, maxlength);
   777 	if (err != SMCError_Okay)
   778 	{
   779 		const char *msg = textparsers->GetSMCErrorString(err);
   780 
   781 		smcore.LogError("[SM] Error parsing master gameconf file \"%s\":", path);
   782 		smcore.LogError("[SM] Error %d on line %d, col %d: %s", 
   783 			err,
   784 			state.line,
   785 			state.col,
   786 			msg ? msg : "Unknown error");
   787 		return false;
   788 	}
   789 
   790 	/* Go through each file we found and parse it. */
   791 	List<String>::iterator iter;
   792 	for (iter = fileList.begin(); iter != fileList.end(); iter++)
   793 	{
   794 		smcore.Format(path, sizeof(path), "%s/%s", m_File, (*iter).c_str());
   795 		if (!EnterFile(path, error, maxlength))
   796 		{
   797 			return false;
   798 		}
   799 	}
   800 
   801 	/* Parse the contents of the 'custom' directory */
   802 	g_pSM->BuildPath(Path_SM, path, sizeof(path), "gamedata/%s/custom", m_File);
   803 	IDirectory *customDir = libsys->OpenDirectory(path);
   804 
   805 	if (!customDir)
   806 	{
   807 		return true;
   808 	}
   809 
   810 	while (customDir->MoreFiles())
   811 	{
   812 		if (!customDir->IsEntryFile())
   813 		{
   814 			customDir->NextEntry();
   815 			continue;
   816 		}
   817 		
   818 		const char *curFile = customDir->GetEntryName();
   819 
   820 		/* Only allow .txt files */
   821 		int len = strlen(curFile);
   822 		if (len > 4 && strcmp(&curFile[len-4], ".txt") != 0)
   823 		{
   824 			customDir->NextEntry();
   825 			continue;	
   826 		}
   827 
   828 		smcore.Format(path, sizeof(path), "%s/custom/%s", m_File, curFile);
   829 		if (!EnterFile(path, error, maxlength))
   830 		{
   831 			libsys->CloseDirectory(customDir);
   832 			return false;
   833 		}
   834 
   835 		customDir->NextEntry();
   836 	}
   837 
   838 	libsys->CloseDirectory(customDir);
   839 	return true;
   840 }
   841 
   842 bool CGameConfig::EnterFile(const char *file, char *error, size_t maxlength)
   843 {
   844 	SMCError err;
   845 	SMCStates state = {0, 0};
   846 
   847 	g_pSM->BuildPath(Path_SM, m_CurFile, sizeof(m_CurFile), "gamedata/%s", file);
   848 
   849 	/* Initialize parse states */
   850 	m_IgnoreLevel = 0;
   851 	bShouldBeReadingDefault = true;
   852 	m_ParseState = PSTATE_NONE;
   853 
   854 	if ((err=textparsers->ParseSMCFile(m_CurFile, this, &state, error, maxlength))
   855 		!= SMCError_Okay)
   856 	{
   857 		const char *msg;
   858 
   859 		msg = textparsers->GetSMCErrorString(err);
   860 
   861 		smcore.LogError("[SM] Error parsing gameconfig file \"%s\":", m_CurFile);
   862 		smcore.LogError("[SM] Error %d on line %d, col %d: %s", 
   863 			err,
   864 			state.line,
   865 			state.col,
   866 			msg ? msg : "Unknown error");
   867 
   868 		if (m_ParseState == PSTATE_GAMEDEFS_CUSTOM)
   869 		{
   870 			//error occurred while parsing a custom section
   871 			m_CustomHandler->ReadSMC_ParseEnd(true, true);
   872 			m_CustomHandler = NULL;
   873 			m_CustomLevel = 0;
   874 		}
   875 
   876 		return false;
   877 	}
   878 
   879 	return true;
   880 }
   881 
   882 bool CGameConfig::GetOffset(const char *key, int *value)
   883 {
   884 	int *pvalue;
   885 	if ((pvalue = m_Offsets.retrieve(key)) == NULL)
   886 		return false;
   887 
   888 	*value = *pvalue;
   889 	return true;
   890 }
   891 
   892 const char *CGameConfig::GetKeyValue(const char *key)
   893 {
   894 	int *pkey;
   895 	if ((pkey = m_Keys.retrieve(key)) == NULL)
   896 		return NULL;
   897 	return m_pStrings->GetString(*pkey);
   898 }
   899 
   900 //memory addresses below 0x10000 are automatically considered invalid for dereferencing
   901 #define VALID_MINIMUM_MEMORY_ADDRESS 0x10000
   902 
   903 bool CGameConfig::GetAddress(const char *key, void **retaddr)
   904 {
   905 	AddressConf *addrConf;
   906 
   907 	addrConf = m_pAddresses->retrieve(key);
   908 	if (!addrConf)
   909 	{
   910 		*retaddr = NULL;
   911 		return false;
   912 	}
   913 
   914 	void *addr;
   915 	if (!GetMemSig(addrConf->signatureName, &addr))
   916 	{
   917 		*retaddr = NULL;
   918 		return false;
   919 	}
   920 
   921 	for (int i = 0; i < addrConf->readCount; ++i)
   922 	{
   923 		int offset = addrConf->read[i];
   924 
   925 		//NULLs in the middle of an indirection chain are bad, end NULL is ok
   926 		if (addr ==  NULL || reinterpret_cast<uintptr_t>(addr) < VALID_MINIMUM_MEMORY_ADDRESS)
   927 		{
   928 			*retaddr = NULL;
   929 			return false;
   930 		}
   931 		addr = *(reinterpret_cast<void**>(reinterpret_cast<uint8_t*>(addr) + offset));
   932 	}
   933 
   934 	*retaddr = addr;
   935 	return true;
   936 }
   937 
   938 static inline unsigned minOf(unsigned a, unsigned b)
   939 {
   940 	return a <= b ? a : b;
   941 }
   942 
   943 CGameConfig::AddressConf::AddressConf(char *sigName, unsigned sigLength, unsigned readCount, int *read)
   944 {
   945 	unsigned readLimit = minOf(readCount, sizeof(this->read) / sizeof(this->read[0]));
   946 
   947 	strncopy(signatureName, sigName, sizeof(signatureName) / sizeof(signatureName[0]));
   948 	this->readCount = readLimit;
   949 	memcpy(&this->read[0], read, sizeof(this->read[0])*readLimit);
   950 }
   951 
   952 SendProp *CGameConfig::GetSendProp(const char *key)
   953 {
   954 	SendProp **pProp;
   955 
   956 	if ((pProp = m_Props.retrieve(key)) == NULL)
   957 		return NULL;
   958 
   959 	return *pProp;
   960 }
   961 
   962 bool CGameConfig::GetMemSig(const char *key, void **addr)
   963 {
   964 	void **paddr;
   965 	if ((paddr = m_Sigs.retrieve(key)) == NULL)
   966 		return false;
   967 	*addr = *paddr;
   968 	return true;
   969 }
   970 
   971 void CGameConfig::IncRefCount()
   972 {
   973 	m_RefCount++;
   974 }
   975 
   976 unsigned int CGameConfig::DecRefCount()
   977 {
   978 	m_RefCount--;
   979 	return m_RefCount;
   980 }
   981 
   982 GameConfigManager::GameConfigManager()
   983 {
   984 }
   985 
   986 GameConfigManager::~GameConfigManager()
   987 {
   988 }
   989 
   990 void GameConfigManager::OnSourceModStartup(bool late)
   991 {
   992 	LoadGameConfigFile("core.games", &g_pGameConf, NULL, 0);
   993 
   994 	strncopy(g_Game, g_pSM->GetGameFolderName(), sizeof(g_Game));
   995 	strncopy(g_GameDesc + 1, smcore.GetGameDescription(), sizeof(g_GameDesc) - 1);
   996 	smcore.GetGameName(g_GameName + 1, sizeof(g_GameName) - 1);
   997 }
   998 
   999 void GameConfigManager::OnSourceModAllInitialized()
  1000 {
  1001 	/* NOW initialize the game file */
  1002 	CGameConfig *pGameConf = (CGameConfig *)g_pGameConf;
  1003 	
  1004 	char error[255];
  1005 	if (!pGameConf->Reparse(error, sizeof(error)))
  1006 	{
  1007 		/* :TODO: log */
  1008 	}
  1009 
  1010 	sharesys->AddInterface(NULL, this);
  1011 }
  1012 
  1013 void GameConfigManager::OnSourceModAllShutdown()
  1014 {
  1015 	CloseGameConfigFile(g_pGameConf);
  1016 }
  1017 
  1018 bool GameConfigManager::LoadGameConfigFile(const char *file, IGameConfig **_pConfig, char *error, size_t maxlength)
  1019 {
  1020 #if 0
  1021 	/* A crash was detected during last load - We block the gamedata loading so it hopefully won't happen again */
  1022 	if (g_blockGameDataLoad)
  1023 	{
  1024 		UTIL_Format(error, maxlength, "GameData loaded blocked due to detected crash");
  1025 		return false;
  1026 	}
  1027 #endif
  1028 
  1029 	CGameConfig *pConfig;
  1030 	CGameConfig **ppConfig;
  1031 
  1032 	if ((ppConfig = m_Lookup.retrieve(file)) != NULL)
  1033 	{
  1034 		pConfig = *ppConfig;
  1035 		pConfig->IncRefCount();
  1036 		*_pConfig = pConfig;
  1037 		return true;
  1038 	}
  1039 
  1040 	pConfig = new CGameConfig(file);
  1041 
  1042 	/* :HACKHACK: Don't parse the main config file */
  1043 	bool retval = true;
  1044 	if (_pConfig != &g_pGameConf)
  1045 	{
  1046 		retval = pConfig->Reparse(error, maxlength);
  1047 	}
  1048 
  1049 	m_cfgs.push_back(pConfig);
  1050 	m_Lookup.insert(file, pConfig);
  1051 
  1052 	pConfig->IncRefCount();
  1053 
  1054 	*_pConfig = pConfig;
  1055 
  1056 	return retval;
  1057 }
  1058 
  1059 void GameConfigManager::CloseGameConfigFile(IGameConfig *cfg)
  1060 {
  1061 	CGameConfig *pConfig = (CGameConfig *)cfg;
  1062 
  1063 	if (pConfig->DecRefCount() == 0)
  1064 	{
  1065 		m_Lookup.remove(pConfig->m_File);
  1066 		delete pConfig;
  1067 	}
  1068 }
  1069 
  1070 extern Handle_t g_GameConfigsType;
  1071 
  1072 IGameConfig *GameConfigManager::ReadHandle(Handle_t hndl, IdentityToken_t *ident, HandleError *err)
  1073 {
  1074 	HandleSecurity sec(ident, g_pCoreIdent);
  1075 	IGameConfig *conf = NULL;
  1076 	HandleError _err = handlesys->ReadHandle(hndl, g_GameConfigsType, &sec, (void **)&conf);
  1077 
  1078 	if (err)
  1079 	{
  1080 		*err = _err;
  1081 	}
  1082 
  1083 	return conf;
  1084 }
  1085 
  1086 void GameConfigManager::AddUserConfigHook(const char *sectionname, ITextListener_SMC *listener)
  1087 {
  1088 	m_customHandlers.insert(sectionname, listener);
  1089 }
  1090 
  1091 void GameConfigManager::RemoveUserConfigHook(const char *sectionname, ITextListener_SMC *listener)
  1092 {
  1093 	ITextListener_SMC **pListener = m_customHandlers.retrieve(sectionname);
  1094 
  1095 	if (pListener == NULL)
  1096 	{
  1097 		return;
  1098 	}
  1099 
  1100 	if (*pListener != listener)
  1101 	{
  1102 		return;
  1103 	}
  1104 
  1105 	m_customHandlers.remove(sectionname);
  1106 	
  1107 	return;
  1108 }
  1109 
  1110 void GameConfigManager::AcquireLock()
  1111 {
  1112 }
  1113 
  1114 void GameConfigManager::ReleaseLock()
  1115 {
  1116 }