core/GameConfigs.cpp
author David Anderson <dvander@alliedmods.net>
Wed Feb 25 20:25:20 2009 -0500 (2009-02-25)
changeset 2613 46c76edb0875
parent 2471 194be299b700
child 2517 312e73edd971
permissions -rw-r--r--
Removed tag sourcemod-1.1.1
     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 #include "GameDataFetcher.h"
    46 
    47 #if defined PLATFORM_LINUX
    48 #include <dlfcn.h>
    49 #endif
    50 
    51 GameConfigManager g_GameConfigs;
    52 IGameConfig *g_pGameConf = NULL;
    53 char g_Game[256];
    54 char g_GameDesc[256] = {'!', '\0'};
    55 char g_GameName[256] = {'$', '\0'};
    56 
    57 #define PSTATE_NONE						0
    58 #define PSTATE_GAMES					1
    59 #define PSTATE_GAMEDEFS					2
    60 #define PSTATE_GAMEDEFS_OFFSETS			3
    61 #define PSTATE_GAMEDEFS_OFFSETS_OFFSET	4
    62 #define PSTATE_GAMEDEFS_KEYS			5
    63 #define PSTATE_GAMEDEFS_SUPPORTED		6
    64 #define PSTATE_GAMEDEFS_SIGNATURES		7
    65 #define PSTATE_GAMEDEFS_SIGNATURES_SIG	8
    66 #define PSTATE_GAMEDEFS_CRC				9
    67 #define PSTATE_GAMEDEFS_CRC_BINARY		10
    68 #define PSTATE_GAMEDEFS_CUSTOM			11
    69 
    70 #if defined PLATFORM_WINDOWS
    71 #define PLATFORM_NAME				"windows"
    72 #define PLATFORM_SERVER_BINARY		"server.dll"
    73 #elif defined PLATFORM_LINUX
    74 #define PLATFORM_NAME				"linux"
    75 #define PLATFORM_SERVER_BINARY		"server_i486.so"
    76 #elif defined PLATFORM_APPLE
    77 #define PLATFORM_NAME               "undef"
    78 #define PLATFORM_SERVER_BINARY      "undef.dylib"
    79 #endif
    80 
    81 struct TempSigInfo
    82 {
    83 	void Reset()
    84 	{
    85 		library[0] = '\0';
    86 		sig[0] = '\0';
    87 	}
    88 	char sig[512];
    89 	char library[64];
    90 } s_TempSig;
    91 unsigned int s_ServerBinCRC;
    92 bool s_ServerBinCRC_Ok = false;
    93 
    94 CGameConfig::CGameConfig(const char *file)
    95 {
    96 	m_pFile = sm_strdup(file);
    97 	m_pOffsets = sm_trie_create();
    98 	m_pProps = sm_trie_create();
    99 	m_pKeys = sm_trie_create();
   100 	m_pSigs = sm_trie_create();
   101 	m_pStrings = new BaseStringTable(512);
   102 	m_RefCount = 0;
   103 
   104 	m_CustomLevel = 0;
   105 	m_CustomHandler = NULL;
   106 }
   107 
   108 CGameConfig::~CGameConfig()
   109 {
   110 	sm_trie_destroy(m_pOffsets);
   111 	sm_trie_destroy(m_pProps);
   112 	sm_trie_destroy(m_pKeys);
   113 	sm_trie_destroy(m_pSigs);
   114 	delete [] m_pFile;
   115 	delete m_pStrings;
   116 }
   117 
   118 SMCResult CGameConfig::ReadSMC_NewSection(const SMCStates *states, const char *name)
   119 {
   120 	if (m_IgnoreLevel)
   121 	{
   122 		m_IgnoreLevel++;
   123 		return SMCResult_Continue;
   124 	}
   125 
   126 	switch (m_ParseState)
   127 	{
   128 	case PSTATE_NONE:
   129 		{
   130 			if (strcmp(name, "Games") == 0)
   131 			{
   132 				m_ParseState = PSTATE_GAMES;
   133 			} else {
   134 				m_IgnoreLevel++;
   135 			}
   136 			break;
   137 		}
   138 	case PSTATE_GAMES:
   139 		{
   140 			if ((strcmp(name, "*") == 0)
   141 				|| (strcmp(name, "#default") == 0)
   142 				|| (strcasecmp(name, g_Game) == 0)
   143 				|| (strcasecmp(name, g_GameDesc) == 0)
   144 				|| (strcasecmp(name, g_GameName) == 0))
   145 			{
   146 				bShouldBeReadingDefault = true;
   147 				m_ParseState = PSTATE_GAMEDEFS;
   148 				strncopy(m_Game, name, sizeof(m_Game));
   149 			} else {
   150 				m_IgnoreLevel++;
   151 			}
   152 			break;
   153 		}
   154 	case PSTATE_GAMEDEFS:
   155 		{
   156 			if (strcmp(name, "Offsets") == 0)
   157 			{
   158 				m_ParseState = PSTATE_GAMEDEFS_OFFSETS;
   159 			}
   160 			else if (strcmp(name, "Keys") == 0)
   161 			{
   162 				m_ParseState = PSTATE_GAMEDEFS_KEYS;
   163 			}
   164 			else if ((strcmp(name, "#supported") == 0)
   165 					 && (strcmp(m_Game, "#default") == 0))
   166 			{
   167 				m_ParseState = PSTATE_GAMEDEFS_SUPPORTED;
   168 				/* Ignore this section unless we get a game. */
   169 				bShouldBeReadingDefault = false;
   170 			}
   171 			else if (strcmp(name, "Signatures") == 0)
   172 			{
   173 				m_ParseState = PSTATE_GAMEDEFS_SIGNATURES;
   174 			}
   175 			else if (strcmp(name, "CRC") == 0)
   176 			{
   177 				m_ParseState = PSTATE_GAMEDEFS_CRC;
   178 				bShouldBeReadingDefault = false;
   179 			}
   180 			else
   181 			{
   182 				ITextListener_SMC **pListen = g_GameConfigs.m_customHandlers.retrieve(name);
   183 
   184 				if (pListen != NULL)
   185 				{
   186 					m_CustomLevel = 0;
   187 					m_ParseState = PSTATE_GAMEDEFS_CUSTOM;
   188 					m_CustomHandler = *pListen;
   189 					m_CustomHandler->ReadSMC_ParseStart();
   190 					break;
   191 				}
   192 
   193 				m_IgnoreLevel++;
   194 			}
   195 			break;
   196 		}
   197 	case PSTATE_GAMEDEFS_OFFSETS:
   198 		{
   199 			m_Prop[0] = '\0';
   200 			m_Class[0] = '\0';
   201 			strncopy(m_offset, name, sizeof(m_offset));
   202 			m_ParseState = PSTATE_GAMEDEFS_OFFSETS_OFFSET;
   203 			break;
   204 		}
   205 	case PSTATE_GAMEDEFS_SIGNATURES:
   206 		{
   207 			strncopy(m_offset, name, sizeof(m_offset));
   208 			s_TempSig.Reset();
   209 			m_ParseState = PSTATE_GAMEDEFS_SIGNATURES_SIG;
   210 			break;
   211 		}
   212 	case PSTATE_GAMEDEFS_CRC:
   213 		{
   214 			char error[255];
   215 			error[0] = '\0';
   216 			if (strcmp(name, "server") != 0)
   217 			{
   218 				UTIL_Format(error, sizeof(error), "Unrecognized library \"%s\"", name);
   219 			} 
   220 			else if (!s_ServerBinCRC_Ok)
   221 			{
   222 				FILE *fp;
   223 				char path[PLATFORM_MAX_PATH];
   224 
   225 				g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "bin/" PLATFORM_SERVER_BINARY);
   226 				if ((fp = fopen(path, "rb")) == NULL)
   227 				{
   228 					UTIL_Format(error, sizeof(error), "Could not open binary: %s", path);
   229 				} else {
   230 					size_t size;
   231 					void *buffer;
   232 
   233 					fseek(fp, 0, SEEK_END);
   234 					size = ftell(fp);
   235 					fseek(fp, 0, SEEK_SET);
   236 
   237 					buffer = malloc(size);
   238 					fread(buffer, size, 1, fp);
   239 					s_ServerBinCRC = UTIL_CRC32(buffer, size);
   240 					free(buffer);
   241 					s_ServerBinCRC_Ok = true;
   242 					fclose(fp);
   243 				}
   244 			}
   245 			if (error[0] != '\0')
   246 			{
   247 				m_IgnoreLevel = 1;
   248 				g_Logger.LogError("[SM] Error while parsing CRC section for \"%s\" (%s):", m_Game, m_pFile);
   249 				g_Logger.LogError("[SM] %s", error);
   250 			} else {
   251 				m_ParseState = PSTATE_GAMEDEFS_CRC_BINARY;
   252 			}
   253 			break;
   254 		}
   255 	case PSTATE_GAMEDEFS_CUSTOM:
   256 		{
   257 			m_CustomLevel++;
   258 			return m_CustomHandler->ReadSMC_NewSection(states, name);
   259 			break;
   260 		}
   261 	/* No sub-sections allowed:
   262 	 case PSTATE_GAMEDEFS_OFFSETS_OFFSET:
   263 	 case PSTATE_GAMEDEFS_KEYS:
   264 	 case PSTATE_GAMEDEFS_SUPPORTED:
   265 	 case PSTATE_GAMEDEFS_SIGNATURES_SIG:
   266 	 case PSTATE_GAMEDEFS_CRC_BINARY:
   267 	 */
   268 	default:
   269 		{
   270 			/* If we don't know what we got, start ignoring */
   271 			m_IgnoreLevel++;
   272 			break;
   273 		}
   274 	}
   275 
   276 	return SMCResult_Continue;
   277 }
   278 
   279 SMCResult CGameConfig::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
   280 {
   281 	if (m_IgnoreLevel)
   282 	{
   283 		return SMCResult_Continue;
   284 	}
   285 
   286 	if (m_ParseState == PSTATE_GAMEDEFS_OFFSETS_OFFSET)
   287 	{
   288 		if (strcmp(key, "class") == 0)
   289 		{
   290 			strncopy(m_Class, value, sizeof(m_Class));
   291 		} else if (strcmp(key, "prop") == 0) {
   292 			strncopy(m_Prop, value, sizeof(m_Prop));
   293 		} else if (strcmp(key, PLATFORM_NAME) == 0) {
   294 			int val = atoi(value);
   295 			sm_trie_replace(m_pOffsets, m_offset, (void *)val);
   296 		}
   297 	} else if (m_ParseState == PSTATE_GAMEDEFS_KEYS) {
   298 		int id = m_pStrings->AddString(value);
   299 		sm_trie_replace(m_pKeys, key, (void *)id);
   300 	} else if (m_ParseState == PSTATE_GAMEDEFS_SUPPORTED) {
   301 		if (strcmp(key, "game") == 0
   302 			&& (strcasecmp(value, g_Game) == 0 
   303 				|| strcasecmp(value, g_GameDesc) == 0
   304 				|| strcasecmp(value, g_GameName) == 0)
   305 				)
   306 		{
   307 			bShouldBeReadingDefault = true;
   308 		}
   309 	} else if (m_ParseState == PSTATE_GAMEDEFS_SIGNATURES_SIG) {
   310 		if (strcmp(key, PLATFORM_NAME) == 0)
   311 		{
   312 			strncopy(s_TempSig.sig, value, sizeof(s_TempSig.sig));
   313 		} else if (strcmp(key, "library") == 0) {
   314 			strncopy(s_TempSig.library, value, sizeof(s_TempSig.library));
   315 		}
   316 	} else if (m_ParseState == PSTATE_GAMEDEFS_CRC_BINARY) {
   317 		if (strcmp(key, PLATFORM_NAME) == 0 
   318 			&& s_ServerBinCRC_Ok
   319 			&& !bShouldBeReadingDefault)
   320 		{
   321 			unsigned int crc = 0;
   322 			sscanf(value, "%08X", &crc);
   323 			if (s_ServerBinCRC == crc)
   324 			{
   325 				bShouldBeReadingDefault = true;
   326 			}
   327 		}
   328 	} else if (m_ParseState == PSTATE_GAMEDEFS_CUSTOM) {
   329 		return m_CustomHandler->ReadSMC_KeyValue(states, key, value);
   330 	}
   331 
   332 	return SMCResult_Continue;
   333 }
   334 
   335 SMCResult CGameConfig::ReadSMC_LeavingSection(const SMCStates *states)
   336 {
   337 	if (m_IgnoreLevel)
   338 	{
   339 		m_IgnoreLevel--;
   340 		return SMCResult_Continue;
   341 	}
   342 
   343 	if (m_CustomLevel)
   344 	{
   345 		m_CustomLevel--;
   346 		m_CustomHandler->ReadSMC_LeavingSection(states);
   347 		return SMCResult_Continue;
   348 	}
   349 
   350 	switch (m_ParseState)
   351 	{
   352 	case PSTATE_GAMES:
   353 		{
   354 			m_ParseState = PSTATE_NONE;
   355 			break;
   356 		}
   357 	case PSTATE_GAMEDEFS:
   358 		{
   359 			m_ParseState = PSTATE_GAMES;
   360 			break;
   361 		}
   362 	case PSTATE_GAMEDEFS_CUSTOM:
   363 		{
   364 			m_ParseState = PSTATE_GAMEDEFS;
   365 			m_CustomHandler->ReadSMC_ParseEnd(false, false);
   366 			break;
   367 		}
   368 	case PSTATE_GAMEDEFS_KEYS:
   369 	case PSTATE_GAMEDEFS_OFFSETS:
   370 		{
   371 			m_ParseState = PSTATE_GAMEDEFS;
   372 			break;
   373 		}
   374 	case PSTATE_GAMEDEFS_OFFSETS_OFFSET:
   375 		{
   376 			/* Parse the offset... */
   377 			if (m_Class[0] != '\0'
   378 				&& m_Prop[0] != '\0')
   379 			{
   380 				SendProp *pProp = g_HL2.FindInSendTable(m_Class, m_Prop);
   381 				if (pProp)
   382 				{
   383 					int val = pProp->GetOffset();
   384 					sm_trie_replace(m_pOffsets, m_offset, (void *)val);
   385 					sm_trie_replace(m_pProps, m_offset, pProp);
   386 				} else {
   387 					/* Check if it's a non-default game and no offsets exist */
   388 					if (((strcmp(m_Game, "*") != 0) && strcmp(m_Game, "#default") != 0)
   389 						&& (!sm_trie_retrieve(m_pOffsets, m_offset, NULL)))
   390 					{
   391 						g_Logger.LogError("[SM] Unable to find property %s.%s (file \"%s\") (mod \"%s\")", 
   392 							m_Class,
   393 							m_Prop,
   394 							m_pFile,
   395 							m_Game);
   396 					}
   397 				}
   398 			}
   399 			m_ParseState = PSTATE_GAMEDEFS_OFFSETS;
   400 			break;
   401 		}
   402 	case PSTATE_GAMEDEFS_CRC:
   403 	case PSTATE_GAMEDEFS_SUPPORTED:
   404 		{
   405 			if (!bShouldBeReadingDefault)
   406 			{
   407 				/* If we shouldn't read the rest of this section, set the ignore level. */
   408 				m_IgnoreLevel = 1;
   409 				m_ParseState = PSTATE_GAMES;
   410 			} else {
   411 				m_ParseState = PSTATE_GAMEDEFS;
   412 			}
   413 			break;
   414 		}
   415 	case PSTATE_GAMEDEFS_CRC_BINARY:
   416 		{
   417 			m_ParseState = PSTATE_GAMEDEFS_CRC;
   418 			break;
   419 		}
   420 	case PSTATE_GAMEDEFS_SIGNATURES:
   421 		{
   422 			m_ParseState = PSTATE_GAMEDEFS;
   423 			break;
   424 		}
   425 	case PSTATE_GAMEDEFS_SIGNATURES_SIG:
   426 		{
   427 			if (s_TempSig.library[0] == '\0')
   428 			{
   429 				/* assume server */
   430 				strncopy(s_TempSig.library, "server", sizeof(s_TempSig.library));
   431 			}
   432 			void *addrInBase = NULL;
   433 			if (strcmp(s_TempSig.library, "server") == 0)
   434 			{
   435 				addrInBase = (void *)g_SMAPI->GetServerFactory(false);
   436 			} else if (strcmp(s_TempSig.library, "engine") == 0) {
   437 				addrInBase = (void *)g_SMAPI->GetEngineFactory(false);
   438 			}
   439 			void *final_addr = NULL;
   440 			if (addrInBase == NULL)
   441 			{
   442 				g_Logger.LogError("[SM] Unrecognized library \"%s\" (gameconf \"%s\")", 
   443 					s_TempSig.library, 
   444 					m_pFile);
   445 			} else {
   446 #if defined PLATFORM_LINUX
   447 				if (s_TempSig.sig[0] == '@')
   448 				{
   449 					Dl_info info;
   450 					/* GNU only: returns 0 on error, inconsistent! >:[ */
   451 					if (dladdr(addrInBase, &info) != 0)
   452 					{
   453 						void *handle = dlopen(info.dli_fname, RTLD_NOW);
   454 						if (handle)
   455 						{
   456 							final_addr = dlsym(handle, &s_TempSig.sig[1]);
   457 							dlclose(handle);
   458 						} else {
   459 							g_Logger.LogError("[SM] Unable to load library \"%s\" (gameconf \"%s\")",
   460 								s_TempSig.library,
   461 								m_pFile);
   462 						}
   463 					} else {
   464 						g_Logger.LogError("[SM] Unable to find library \"%s\" in memory (gameconf \"%s\")",
   465 							s_TempSig.library,
   466 							m_pFile);
   467 					}
   468 				}
   469 				if (final_addr)
   470 				{
   471 					goto skip_find;
   472 				}
   473 #endif
   474 				/* First, preprocess the signature */
   475 				char real_sig[511];
   476 				size_t real_bytes;
   477 				size_t length;
   478 
   479 				real_bytes = 0;
   480 				length = strlen(s_TempSig.sig);
   481 
   482 				for (size_t i=0; i<length; i++)
   483 				{
   484 					if (real_bytes >= sizeof(real_sig))
   485 					{
   486 						break;
   487 					}
   488 					real_sig[real_bytes++] = s_TempSig.sig[i];
   489 					if (s_TempSig.sig[i] == '\\'
   490 						&& s_TempSig.sig[i+1] == 'x')
   491 					{
   492 						if (i + 3 >= length)
   493 						{
   494 							continue;
   495 						}
   496 						/* Get the hex part */
   497 						char s_byte[3];
   498 						int r_byte;
   499 						s_byte[0] = s_TempSig.sig[i+2];
   500 						s_byte[1] = s_TempSig.sig[i+3];
   501 						s_byte[2] = '\0';
   502 						/* Read it as an integer */
   503 						sscanf(s_byte, "%x", &r_byte);
   504 						/* Save the value */
   505 						real_sig[real_bytes-1] = r_byte;
   506 						/* Adjust index */
   507 						i += 3;
   508 					}
   509 				}
   510 
   511 				if (real_bytes >= 1)
   512 				{
   513 					final_addr = g_MemUtils.FindPattern(addrInBase, real_sig, real_bytes);
   514 				}
   515 			}
   516 
   517 #if defined PLATFORM_LINUX
   518 skip_find:
   519 #endif
   520 			sm_trie_replace(m_pSigs, m_offset, final_addr);
   521 			m_ParseState = PSTATE_GAMEDEFS_SIGNATURES;
   522 
   523 			break;
   524 		}
   525 	}
   526 
   527 	return SMCResult_Continue;
   528 }
   529 
   530 bool CGameConfig::Reparse(char *error, size_t maxlength)
   531 {
   532 	SMCError err;
   533 	SMCStates state = {0, 0};
   534 
   535 	char path[PLATFORM_MAX_PATH];
   536 	g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "gamedata/%s.txt", m_pFile);
   537 	/* Backwards compatibility */
   538 	if (!g_LibSys.PathExists(path))
   539 	{
   540 		g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "configs/gamedata/%s.txt", m_pFile);
   541 	}
   542 
   543 	/* Initialize parse states */
   544 	m_IgnoreLevel = 0;
   545 	bShouldBeReadingDefault = true;
   546 	m_ParseState = PSTATE_NONE;
   547 	/* Reset cached data */
   548 	m_pStrings->Reset();
   549 	sm_trie_clear(m_pOffsets);
   550 	sm_trie_clear(m_pProps);
   551 	sm_trie_clear(m_pKeys);
   552 
   553 	if ((err=textparsers->ParseSMCFile(path, this, &state, error, maxlength))
   554 		!= SMCError_Okay)
   555 	{
   556 		const char *msg;
   557 
   558 		msg = textparsers->GetSMCErrorString(err);
   559 
   560 		g_Logger.LogError("[SM] Error parsing gameconfig file \"%s\":", path);
   561 		g_Logger.LogError("[SM] Error %d on line %d, col %d: %s", 
   562 			err,
   563 			state.line,
   564 			state.col,
   565 			msg ? msg : "Unknown error");
   566 
   567 		if (m_ParseState == PSTATE_GAMEDEFS_CUSTOM)
   568 		{
   569 			//error occurred while parsing a custom section
   570 			m_CustomHandler->ReadSMC_ParseEnd(true, true);
   571 			m_CustomHandler = NULL;
   572 			m_CustomLevel = 0;
   573 		}
   574 
   575 		return false;
   576 	}
   577 
   578 	return true;
   579 }
   580 
   581 bool CGameConfig::GetOffset(const char *key, int *value)
   582 {
   583 	void *obj;
   584 
   585 	if (!sm_trie_retrieve(m_pOffsets, key, &obj))
   586 	{
   587 		return false;
   588 	}
   589 
   590 	*value = (int)obj;
   591 	
   592 	return true;
   593 }
   594 
   595 const char *CGameConfig::GetKeyValue(const char *key)
   596 {
   597 	void *obj;
   598 	if (!sm_trie_retrieve(m_pKeys, key, &obj))
   599 	{
   600 		return NULL;
   601 	}
   602 	return m_pStrings->GetString((int)obj);
   603 }
   604 
   605 SendProp *CGameConfig::GetSendProp(const char *key)
   606 {
   607 	SendProp *pProp;
   608 
   609 	if (!sm_trie_retrieve(m_pProps, key, (void **)&pProp))
   610 	{
   611 		return NULL;
   612 	}
   613 
   614 	return pProp;
   615 }
   616 
   617 bool CGameConfig::GetMemSig(const char *key, void **addr)
   618 {
   619 	return sm_trie_retrieve(m_pSigs, key, addr);
   620 }
   621 
   622 void CGameConfig::IncRefCount()
   623 {
   624 	m_RefCount++;
   625 }
   626 
   627 unsigned int CGameConfig::DecRefCount()
   628 {
   629 	m_RefCount--;
   630 	return m_RefCount;
   631 }
   632 
   633 GameConfigManager::GameConfigManager()
   634 {
   635 	m_pLookup = sm_trie_create();
   636 }
   637 
   638 GameConfigManager::~GameConfigManager()
   639 {
   640 	sm_trie_destroy(m_pLookup);
   641 }
   642 
   643 void GameConfigManager::OnSourceModStartup(bool late)
   644 {
   645 	LoadGameConfigFile("core.games", &g_pGameConf, NULL, 0);
   646 
   647 	strncopy(g_Game, g_SourceMod.GetGameFolderName(), sizeof(g_Game));
   648 	strncopy(g_GameDesc + 1, SERVER_CALL(GetGameDescription)(), sizeof(g_GameDesc) - 1);
   649 
   650 	KeyValues *pGameInfo = new KeyValues("GameInfo");
   651 	if (g_HL2.KVLoadFromFile(pGameInfo, basefilesystem, "gameinfo.txt"))
   652 	{
   653 		const char *str;
   654 		if ((str = pGameInfo->GetString("game", NULL)) != NULL)
   655 		{
   656 			strncopy(g_GameName + 1, str, sizeof(g_GameName) - 1);
   657 		}
   658 	}
   659 	pGameInfo->deleteThis();
   660 }
   661 
   662 void GameConfigManager::OnSourceModAllInitialized()
   663 {
   664 	/* NOW initialize the game file */
   665 	CGameConfig *pGameConf = (CGameConfig *)g_pGameConf;
   666 	
   667 	char error[255];
   668 	if (!pGameConf->Reparse(error, sizeof(error)))
   669 	{
   670 		/* :TODO: log */
   671 	}
   672 
   673 	g_ShareSys.AddInterface(NULL, this);
   674 }
   675 
   676 void GameConfigManager::OnSourceModAllShutdown()
   677 {
   678 	CloseGameConfigFile(g_pGameConf);
   679 }
   680 
   681 bool GameConfigManager::LoadGameConfigFile(const char *file, IGameConfig **_pConfig, char *error, size_t maxlength)
   682 {
   683 	/* A crash was detected during last load - We block the gamedata loading so it hopefully won't happen again */
   684 	if (g_blockGameDataLoad)
   685 	{
   686 		UTIL_Format(error, maxlength, "GameData loaded blocked due to detected crash");
   687 		return false;
   688 	}
   689 
   690 	CGameConfig *pConfig;
   691 
   692 	if (sm_trie_retrieve(m_pLookup, file, (void **)&pConfig))
   693 	{
   694 		pConfig->IncRefCount();
   695 		*_pConfig = pConfig;
   696 		return true;
   697 	}
   698 
   699 	pConfig = new CGameConfig(file);
   700 
   701 	/* :HACKHACK: Don't parse the main config file */
   702 	bool retval = true;
   703 	if (_pConfig != &g_pGameConf)
   704 	{
   705 		retval = pConfig->Reparse(error, maxlength);
   706 	}
   707 
   708 	m_cfgs.push_back(pConfig);
   709 	sm_trie_insert(m_pLookup, file, pConfig);
   710 
   711 	pConfig->IncRefCount();
   712 
   713 	*_pConfig = pConfig;
   714 
   715 	return retval;
   716 }
   717 
   718 void GameConfigManager::CloseGameConfigFile(IGameConfig *cfg)
   719 {
   720 	CGameConfig *pConfig = (CGameConfig *)cfg;
   721 
   722 	if (pConfig->DecRefCount() == 0)
   723 	{
   724 		sm_trie_delete(m_pLookup, pConfig->m_pFile);
   725 		delete pConfig;
   726 	}
   727 }
   728 
   729 extern HandleType_t g_GameConfigsType;
   730 
   731 IGameConfig *GameConfigManager::ReadHandle(Handle_t hndl, IdentityToken_t *ident, HandleError *err)
   732 {
   733 	HandleSecurity sec(ident, g_pCoreIdent);
   734 	IGameConfig *conf = NULL;
   735 	HandleError _err = g_HandleSys.ReadHandle(hndl, g_GameConfigsType, &sec, (void **)&conf);
   736 
   737 	if (err)
   738 	{
   739 		*err = _err;
   740 	}
   741 
   742 	return conf;
   743 }
   744 
   745 void GameConfigManager::AddUserConfigHook( const char *sectionname, ITextListener_SMC *listener )
   746 {
   747 	m_customHandlers.insert(sectionname, listener);
   748 }
   749 
   750 void GameConfigManager::RemoveUserConfigHook( const char *sectionname, ITextListener_SMC *listener )
   751 {
   752 	ITextListener_SMC **pListener = m_customHandlers.retrieve(sectionname);
   753 
   754 	if (pListener == NULL)
   755 	{
   756 		return;
   757 	}
   758 
   759 	if (*pListener != listener)
   760 	{
   761 		return;
   762 	}
   763 
   764 	m_customHandlers.remove(sectionname);
   765 	
   766 	return;
   767 }