core/GameConfigs.cpp
author David Anderson <dvander@alliedmods.net>
Sun Jun 17 07:32:31 2007 +0000 (2007-06-17)
changeset 969 0cd7fc27e054
parent 964 97ba56f99bc1
child 971 d3a94f3f1529
permissions -rw-r--r--
fixed a state bug in the gameconf parser that would break parsing after a signature section was done
     1 /**
     2  * vim: set ts=4 :
     3  * ===============================================================
     4  * SourceMod (C)2004-2007 AlliedModders LLC.  All rights reserved.
     5  * ===============================================================
     6  *
     7  * This file is not open source and may not be copied without explicit
     8  * written permission of AlliedModders LLC.  This file may not be redistributed 
     9  * in whole or significant part.
    10  * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
    11  *
    12  * Version: $Id$
    13  */
    14 
    15 #include <string.h>
    16 #include <stdlib.h>
    17 #include "GameConfigs.h"
    18 #include "TextParsers.h"
    19 #include "sm_stringutil.h"
    20 #include "sourcemod.h"
    21 #include "sourcemm_api.h"
    22 #include "HalfLife2.h"
    23 #include "Logger.h"
    24 #include "ShareSys.h"
    25 #include "MemoryUtils.h"
    26 #include "LibrarySys.h"
    27 #include "HandleSys.h"
    28 
    29 #if defined PLATFORM_LINUX
    30 #include <dlfcn.h>
    31 #endif
    32 
    33 GameConfigManager g_GameConfigs;
    34 IGameConfig *g_pGameConf = NULL;
    35 char g_mod[255];
    36 
    37 #define PSTATE_NONE						0
    38 #define PSTATE_GAMES					1
    39 #define PSTATE_GAMEDEFS					2
    40 #define PSTATE_GAMEDEFS_OFFSETS			3
    41 #define PSTATE_GAMEDEFS_OFFSETS_OFFSET	4
    42 #define PSTATE_GAMEDEFS_KEYS			5
    43 #define PSTATE_GAMEDEFS_SUPPORTED		6
    44 #define PSTATE_GAMEDEFS_SIGNATURES		7
    45 #define PSTATE_GAMEDEFS_SIGNATURES_SIG	8
    46 
    47 #if defined PLATFORM_WINDOWS
    48 #define PLATFORM_NAME	"windows"
    49 #elif defined PLATFORM_LINUX
    50 #define PLATFORM_NAME	"linux"
    51 #endif
    52 
    53 struct TempSigInfo
    54 {
    55 	void Reset()
    56 	{
    57 		library[0] = '\0';
    58 		sig[0] = '\0';
    59 	}
    60 	char sig[512];
    61 	char library[64];
    62 } s_TempSig;
    63 
    64 CGameConfig::CGameConfig(const char *file)
    65 {
    66 	m_pFile = sm_strdup(file);
    67 	m_pOffsets = sm_trie_create();
    68 	m_pProps = sm_trie_create();
    69 	m_pKeys = sm_trie_create();
    70 	m_pSigs = sm_trie_create();
    71 	m_pStrings = new BaseStringTable(512);
    72 	m_RefCount = 0;
    73 }
    74 
    75 CGameConfig::~CGameConfig()
    76 {
    77 	sm_trie_destroy(m_pOffsets);
    78 	sm_trie_destroy(m_pProps);
    79 	sm_trie_destroy(m_pKeys);
    80 	sm_trie_destroy(m_pSigs);
    81 	delete [] m_pFile;
    82 	delete m_pStrings;
    83 }
    84 
    85 SMCParseResult CGameConfig::ReadSMC_NewSection(const char *name, bool opt_quotes)
    86 {
    87 	if (m_IgnoreLevel)
    88 	{
    89 		m_IgnoreLevel++;
    90 		return SMCParse_Continue;
    91 	}
    92 
    93 	switch (m_ParseState)
    94 	{
    95 	case PSTATE_NONE:
    96 		{
    97 			if (strcmp(name, "Games") == 0)
    98 			{
    99 				m_ParseState = PSTATE_GAMES;
   100 			} else {
   101 				m_IgnoreLevel++;
   102 			}
   103 			break;
   104 		}
   105 	case PSTATE_GAMES:
   106 		{
   107 			if ((strcmp(name, "*") == 0)
   108 				|| (strcmp(name, "#default") == 0)
   109 				|| (strcmp(name, g_mod) == 0))
   110 			{
   111 				m_ParseState = PSTATE_GAMEDEFS;
   112 				strncopy(m_mod, name, sizeof(m_mod));
   113 			} else {
   114 				m_IgnoreLevel++;
   115 			}
   116 			break;
   117 		}
   118 	case PSTATE_GAMEDEFS:
   119 		{
   120 			if (strcmp(name, "Offsets") == 0)
   121 			{
   122 				m_ParseState = PSTATE_GAMEDEFS_OFFSETS;
   123 			}
   124 			else if (strcmp(name, "Keys") == 0)
   125 			{
   126 				m_ParseState = PSTATE_GAMEDEFS_KEYS;
   127 			}
   128 			else if ((strcmp(name, "#supported") == 0)
   129 					 && (strcmp(m_mod, "#default") == 0))
   130 			{
   131 				m_ParseState = PSTATE_GAMEDEFS_SUPPORTED;
   132 				/* Ignore this section unless we get a game. */
   133 				bShouldBeReadingDefault = false;
   134 			}
   135 			else if (strcmp(name, "Signatures") == 0)
   136 			{
   137 				m_ParseState = PSTATE_GAMEDEFS_SIGNATURES;
   138 			}
   139 			else
   140 			{
   141 				m_IgnoreLevel++;
   142 			}
   143 			break;
   144 		}
   145 	case PSTATE_GAMEDEFS_OFFSETS:
   146 		{
   147 			m_prop[0] = '\0';
   148 			m_class[0] = '\0';
   149 			strncopy(m_offset, name, sizeof(m_offset));
   150 			m_ParseState = PSTATE_GAMEDEFS_OFFSETS_OFFSET;
   151 			break;
   152 		}
   153 	case PSTATE_GAMEDEFS_SIGNATURES:
   154 		{
   155 			strncopy(m_offset, name, sizeof(m_offset));
   156 			s_TempSig.Reset();
   157 			m_ParseState = PSTATE_GAMEDEFS_SIGNATURES_SIG;
   158 			break;
   159 		}
   160 	/* No sub-sections allowed:
   161 	 case PSTATE_GAMEDEFS_OFFSETS_OFFSET:
   162 	 case PSTATE_GAMEDEFS_KEYS:
   163 	 case PSTATE_GAMEDEFS_SUPPORTED:
   164 	 case PSTATE_GAMEDEFS_SIGNATURES_SIG:
   165 	 */
   166 	default:
   167 		{
   168 			/* If we don't know what we got, start ignoring */
   169 			m_IgnoreLevel++;
   170 			break;
   171 		}
   172 	}
   173 
   174 	return SMCParse_Continue;
   175 }
   176 
   177 SMCParseResult CGameConfig::ReadSMC_KeyValue(const char *key, const char *value, bool key_quotes, bool value_quotes)
   178 {
   179 	if (m_IgnoreLevel)
   180 	{
   181 		return SMCParse_Continue;
   182 	}
   183 
   184 	if (m_ParseState == PSTATE_GAMEDEFS_OFFSETS_OFFSET)
   185 	{
   186 		if (strcmp(key, "class") == 0)
   187 		{
   188 			strncopy(m_class, value, sizeof(m_class));
   189 		} else if (strcmp(key, "prop") == 0) {
   190 			strncopy(m_prop, value, sizeof(m_prop));
   191 		} else if (strcmp(key, PLATFORM_NAME) == 0) {
   192 			int val = atoi(value);
   193 			sm_trie_insert(m_pOffsets, m_offset, (void *)val);
   194 		}
   195 	} else if (m_ParseState == PSTATE_GAMEDEFS_KEYS) {
   196 		int id = m_pStrings->AddString(value);
   197 		sm_trie_insert(m_pKeys, key, (void *)id);
   198 	} else if (m_ParseState == PSTATE_GAMEDEFS_SUPPORTED) {
   199 		if (strcmp(key, "game") == 0
   200 			&& strcmp(value, g_mod) == 0)
   201 		{
   202 			bShouldBeReadingDefault = true;
   203 		}
   204 	} else if (m_ParseState == PSTATE_GAMEDEFS_SIGNATURES_SIG) {
   205 		if (strcmp(key, PLATFORM_NAME) == 0)
   206 		{
   207 			strncopy(s_TempSig.sig, value, sizeof(s_TempSig.sig));
   208 		} else if (strcmp(key, "library") == 0) {
   209 			strncopy(s_TempSig.library, value, sizeof(s_TempSig.library));
   210 		}
   211 	}
   212 
   213 	return SMCParse_Continue;
   214 }
   215 
   216 SMCParseResult CGameConfig::ReadSMC_LeavingSection()
   217 {
   218 	if (m_IgnoreLevel)
   219 	{
   220 		m_IgnoreLevel--;
   221 		return SMCParse_Continue;
   222 	}
   223 
   224 	switch (m_ParseState)
   225 	{
   226 	case PSTATE_GAMES:
   227 		{
   228 			m_ParseState = PSTATE_NONE;
   229 			break;
   230 		}
   231 	case PSTATE_GAMEDEFS:
   232 		{
   233 			m_ParseState = PSTATE_GAMES;
   234 			break;
   235 		}
   236 	case PSTATE_GAMEDEFS_KEYS:
   237 	case PSTATE_GAMEDEFS_OFFSETS:
   238 		{
   239 			m_ParseState = PSTATE_GAMEDEFS;
   240 			break;
   241 		}
   242 	case PSTATE_GAMEDEFS_OFFSETS_OFFSET:
   243 		{
   244 			/* Parse the offset... */
   245 			if (m_class[0] != '\0'
   246 				&& m_prop[0] != '\0')
   247 			{
   248 				SendProp *pProp = g_HL2.FindInSendTable(m_class, m_prop);
   249 				if (pProp)
   250 				{
   251 					int val = pProp->GetOffset();
   252 					sm_trie_insert(m_pOffsets, m_offset, (void *)val);
   253 					sm_trie_insert(m_pProps, m_offset, pProp);
   254 				} else {
   255 					/* Check if it's a non-default game and no offsets exist */
   256 					if (((strcmp(m_mod, "*") != 0) && strcmp(m_mod, "#default") != 0)
   257 						&& (!sm_trie_retrieve(m_pOffsets, m_offset, NULL)))
   258 					{
   259 						g_Logger.LogError("[SM] Unable to find property %s.%s (file \"%s\") (mod \"%s\")", 
   260 							m_class,
   261 							m_prop,
   262 							m_pFile,
   263 							m_mod);
   264 					}
   265 				}
   266 			}
   267 			m_ParseState = PSTATE_GAMEDEFS_OFFSETS;
   268 			break;
   269 		}
   270 	case PSTATE_GAMEDEFS_SUPPORTED:
   271 		{
   272 			if (!bShouldBeReadingDefault)
   273 			{
   274 				/* If we shouldn't read the rest of this section, set the ignore level. */
   275 				m_IgnoreLevel = 1;
   276 			}
   277 			m_ParseState = PSTATE_GAMEDEFS;
   278 			break;
   279 		}
   280 	case PSTATE_GAMEDEFS_SIGNATURES:
   281 		{
   282 			m_ParseState = PSTATE_GAMEDEFS;
   283 			break;
   284 		}
   285 	case PSTATE_GAMEDEFS_SIGNATURES_SIG:
   286 		{
   287 			if (s_TempSig.library[0] == '\0')
   288 			{
   289 				/* assume server */
   290 				strncopy(s_TempSig.library, "server", sizeof(s_TempSig.library));
   291 			}
   292 			void *addrInBase = NULL;
   293 			if (strcmp(s_TempSig.library, "server") == 0)
   294 			{
   295 				addrInBase = (void *)g_SMAPI->serverFactory(false);
   296 			} else if (strcmp(s_TempSig.library, "engine") == 0) {
   297 				addrInBase = (void *)g_SMAPI->engineFactory(false);
   298 			}
   299 			void *final_addr = NULL;
   300 			if (addrInBase == NULL)
   301 			{
   302 				g_Logger.LogError("[SM] Unrecognized library \"%s\" (gameconf \"%s\")", 
   303 					s_TempSig.library, 
   304 					m_pFile);
   305 			} else {
   306 #if defined PLATFORM_LINUX
   307 				if (s_TempSig.sig[0] == '@')
   308 				{
   309 					Dl_info info;
   310 					/* GNU only: returns 0 on error, inconsistent! >:[ */
   311 					if (dladdr(addrInBase, &info) == 0)
   312 					{
   313 						void *handle = dlopen(info.dli_fname, RTLD_NOW);
   314 						if (handle)
   315 						{
   316 							final_addr = dlsym(handle, &s_TempSig.sig[1]);
   317 							dlclose(handle);
   318 						} else {
   319 							g_Logger.LogError("[SM] Unable to load library \"%s\" (gameconf \"%s\")",
   320 								s_TempSig.library,
   321 								m_pFile);
   322 						}
   323 					} else {
   324 						g_Logger.LogError("[SM] Unable to find library \"%s\" in memory (gameconf \"%s\")",
   325 							s_TempSig.library,
   326 							m_pFile);
   327 					}
   328 					if (!final_addr)
   329 					{
   330 						g_Logger.LogError("[SM] Unable to find named symbol (symbol \"%s\") (library \"%s\") (gameconf \"%s\")",
   331 							&s_TempSig.sig[1],
   332 							s_TempSig.library,
   333 							m_pFile);
   334 					}
   335 				}
   336 				if (final_addr)
   337 				{
   338 					goto skip_find;
   339 				}
   340 #endif
   341 				/* First, preprocess the signature */
   342 				char real_sig[255];
   343 				size_t real_bytes;
   344 				size_t length;
   345 
   346 				real_bytes = 0;
   347 				length = strlen(s_TempSig.sig);
   348 
   349 				for (size_t i=0; i<length; i++)
   350 				{
   351 					if (real_bytes >= sizeof(real_sig))
   352 					{
   353 						break;
   354 					}
   355 					real_sig[real_bytes++] = s_TempSig.sig[i];
   356 					if (s_TempSig.sig[i] == '\\'
   357 						&& s_TempSig.sig[i+1] == 'x')
   358 					{
   359 						if (i + 3 >= length)
   360 						{
   361 							continue;
   362 						}
   363 						/* Get the hex part */
   364 						char s_byte[3];
   365 						int r_byte;
   366 						s_byte[0] = s_TempSig.sig[i+2];
   367 						s_byte[1] = s_TempSig.sig[i+3];
   368 						s_byte[2] = '\0';
   369 						/* Read it as an integer */
   370 						sscanf(s_byte, "%x", &r_byte);
   371 						/* Save the value */
   372 						real_sig[real_bytes-1] = r_byte;
   373 						/* Adjust index */
   374 						i += 3;
   375 					}
   376 				}
   377 
   378 				if (real_bytes < 1)
   379 				{
   380 					g_Logger.LogError("[SM] Invalid signature (name \"%s\") (gameconf \"%s\")",
   381 						m_offset,
   382 						m_pFile);
   383 				} else {
   384 					final_addr = g_MemUtils.FindPattern(addrInBase, real_sig, real_bytes);
   385 					if (!final_addr)
   386 					{
   387 						g_Logger.LogError("[SM] Unable to find signature (name \"%s\") (gameconf \"%s\")", 
   388 							m_offset,
   389 							m_pFile);
   390 					}
   391 				}
   392 			}
   393 
   394 #if defined PLATFORM_LINUX
   395 skip_find:
   396 #endif
   397 			sm_trie_insert(m_pSigs, m_offset, final_addr);
   398 			m_ParseState = PSTATE_GAMEDEFS_SIGNATURES;
   399 
   400 			break;
   401 		}
   402 	}
   403 
   404 	return SMCParse_Continue;
   405 }
   406 
   407 bool CGameConfig::Reparse(char *error, size_t maxlength)
   408 {
   409 	SMCParseError err;
   410 
   411 	char path[PLATFORM_MAX_PATH];
   412 	g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "gamedata/%s.txt", m_pFile);
   413 	/* Backwards compatibility */
   414 	if (!g_LibSys.PathExists(path))
   415 	{
   416 		g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "configs/gamedata/%s.txt", m_pFile);
   417 	}
   418 
   419 	/* Initialize parse states */
   420 	m_IgnoreLevel = 0;
   421 	bShouldBeReadingDefault = true;
   422 	m_ParseState = PSTATE_NONE;
   423 	/* Reset cached data */
   424 	m_pStrings->Reset();
   425 	sm_trie_clear(m_pOffsets);
   426 	sm_trie_clear(m_pProps);
   427 	sm_trie_clear(m_pKeys);
   428 
   429 	if ((err=g_TextParser.ParseFile_SMC(path, this, NULL, NULL))
   430 		!= SMCParse_Okay)
   431 	{
   432 		if (error && (err != SMCParse_Custom))
   433 		{
   434 			const char *str = g_TextParser.GetSMCErrorString(err);
   435 			snprintf(error, maxlength, "%s", str);
   436 		}
   437 		return false;
   438 	}
   439 
   440 	return true;
   441 }
   442 
   443 bool CGameConfig::GetOffset(const char *key, int *value)
   444 {
   445 	void *obj;
   446 
   447 	if (!sm_trie_retrieve(m_pOffsets, key, &obj))
   448 	{
   449 		return false;
   450 	}
   451 
   452 	*value = (int)obj;
   453 	
   454 	return true;
   455 }
   456 
   457 const char *CGameConfig::GetKeyValue(const char *key)
   458 {
   459 	void *obj;
   460 	if (!sm_trie_retrieve(m_pKeys, key, &obj))
   461 	{
   462 		return NULL;
   463 	}
   464 	return m_pStrings->GetString((int)obj);
   465 }
   466 
   467 SendProp *CGameConfig::GetSendProp(const char *key)
   468 {
   469 	SendProp *pProp;
   470 
   471 	if (!sm_trie_retrieve(m_pProps, key, (void **)&pProp))
   472 	{
   473 		return NULL;
   474 	}
   475 
   476 	return pProp;
   477 }
   478 
   479 bool CGameConfig::GetMemSig(const char *key, void **addr)
   480 {
   481 	return sm_trie_retrieve(m_pSigs, key, addr);
   482 }
   483 
   484 void CGameConfig::IncRefCount()
   485 {
   486 	m_RefCount++;
   487 }
   488 
   489 unsigned int CGameConfig::DecRefCount()
   490 {
   491 	m_RefCount--;
   492 	return m_RefCount;
   493 }
   494 
   495 GameConfigManager::GameConfigManager()
   496 {
   497 	m_pLookup = sm_trie_create();
   498 }
   499 
   500 GameConfigManager::~GameConfigManager()
   501 {
   502 	sm_trie_destroy(m_pLookup);
   503 }
   504 
   505 void GameConfigManager::OnSourceModStartup(bool late)
   506 {
   507 	LoadGameConfigFile("core.games", &g_pGameConf, NULL, 0);
   508 
   509 	strncopy(g_mod, g_SourceMod.GetGameFolderName(), sizeof(g_mod));
   510 }
   511 
   512 void GameConfigManager::OnSourceModAllInitialized()
   513 {
   514 	/* NOW initialize the game file */
   515 	CGameConfig *pGameConf = (CGameConfig *)g_pGameConf;
   516 	
   517 	char error[255];
   518 	if (!pGameConf->Reparse(error, sizeof(error)))
   519 	{
   520 		/* :TODO: log */
   521 	}
   522 
   523 	g_ShareSys.AddInterface(NULL, this);
   524 }
   525 
   526 void GameConfigManager::OnSourceModAllShutdown()
   527 {
   528 	CloseGameConfigFile(g_pGameConf);
   529 }
   530 
   531 bool GameConfigManager::LoadGameConfigFile(const char *file, IGameConfig **_pConfig, char *error, size_t maxlength)
   532 {
   533 	CGameConfig *pConfig;
   534 
   535 	if (sm_trie_retrieve(m_pLookup, file, (void **)&pConfig))
   536 	{
   537 		pConfig->IncRefCount();
   538 		*_pConfig = pConfig;
   539 		return true;
   540 	}
   541 
   542 	pConfig = new CGameConfig(file);
   543 
   544 	/* :HACKHACK: Don't parse the main config file */
   545 	bool retval = true;
   546 	if (_pConfig != &g_pGameConf)
   547 	{
   548 		retval = pConfig->Reparse(error, maxlength);
   549 	}
   550 
   551 	m_cfgs.push_back(pConfig);
   552 	sm_trie_insert(m_pLookup, file, pConfig);
   553 
   554 	pConfig->IncRefCount();
   555 
   556 	*_pConfig = pConfig;
   557 
   558 	return retval;
   559 }
   560 
   561 void GameConfigManager::CloseGameConfigFile(IGameConfig *cfg)
   562 {
   563 	CGameConfig *pConfig = (CGameConfig *)cfg;
   564 
   565 	if (pConfig->DecRefCount() == 0)
   566 	{
   567 		delete pConfig;
   568 	}
   569 }
   570 
   571 extern HandleType_t g_GameConfigsType;
   572 
   573 IGameConfig *GameConfigManager::ReadHandle(Handle_t hndl, IdentityToken_t *ident, HandleError *err)
   574 {
   575 	HandleSecurity sec(ident, g_pCoreIdent);
   576 	IGameConfig *conf = NULL;
   577 	HandleError _err = g_HandleSys.ReadHandle(hndl, g_GameConfigsType, &sec, (void **)&conf);
   578 
   579 	if (err)
   580 	{
   581 		*err = _err;
   582 	}
   583 
   584 	return conf;
   585 }