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