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