core/GameConfigs.cpp
author David Anderson <dvander@alliedmods.net>
Sun Jul 08 03:17:29 2007 +0000 (2007-07-08)
changeset 1057 de136462a416
parent 1054 70d735c2c3eb
child 1061 2f4060d4bf2e
permissions -rw-r--r--
gameconfs can now inherit properly with a new trie replace function
     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_replace(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_replace(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_replace(m_pOffsets, m_offset, (void *)val);
   253 					sm_trie_replace(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 				m_ParseState = PSTATE_GAMES;
   277 			} else {
   278 				m_ParseState = PSTATE_GAMEDEFS;
   279 			}
   280 			break;
   281 		}
   282 	case PSTATE_GAMEDEFS_SIGNATURES:
   283 		{
   284 			m_ParseState = PSTATE_GAMEDEFS;
   285 			break;
   286 		}
   287 	case PSTATE_GAMEDEFS_SIGNATURES_SIG:
   288 		{
   289 			if (s_TempSig.library[0] == '\0')
   290 			{
   291 				/* assume server */
   292 				strncopy(s_TempSig.library, "server", sizeof(s_TempSig.library));
   293 			}
   294 			void *addrInBase = NULL;
   295 			if (strcmp(s_TempSig.library, "server") == 0)
   296 			{
   297 				addrInBase = (void *)g_SMAPI->serverFactory(false);
   298 			} else if (strcmp(s_TempSig.library, "engine") == 0) {
   299 				addrInBase = (void *)g_SMAPI->engineFactory(false);
   300 			}
   301 			void *final_addr = NULL;
   302 			if (addrInBase == NULL)
   303 			{
   304 				g_Logger.LogError("[SM] Unrecognized library \"%s\" (gameconf \"%s\")", 
   305 					s_TempSig.library, 
   306 					m_pFile);
   307 			} else {
   308 #if defined PLATFORM_LINUX
   309 				if (s_TempSig.sig[0] == '@')
   310 				{
   311 					Dl_info info;
   312 					/* GNU only: returns 0 on error, inconsistent! >:[ */
   313 					if (dladdr(addrInBase, &info) != 0)
   314 					{
   315 						void *handle = dlopen(info.dli_fname, RTLD_NOW);
   316 						if (handle)
   317 						{
   318 							final_addr = dlsym(handle, &s_TempSig.sig[1]);
   319 							dlclose(handle);
   320 						} else {
   321 							g_Logger.LogError("[SM] Unable to load library \"%s\" (gameconf \"%s\")",
   322 								s_TempSig.library,
   323 								m_pFile);
   324 						}
   325 					} else {
   326 						g_Logger.LogError("[SM] Unable to find library \"%s\" in memory (gameconf \"%s\")",
   327 							s_TempSig.library,
   328 							m_pFile);
   329 					}
   330 				}
   331 				if (final_addr)
   332 				{
   333 					goto skip_find;
   334 				}
   335 #endif
   336 				/* First, preprocess the signature */
   337 				char real_sig[255];
   338 				size_t real_bytes;
   339 				size_t length;
   340 
   341 				real_bytes = 0;
   342 				length = strlen(s_TempSig.sig);
   343 
   344 				for (size_t i=0; i<length; i++)
   345 				{
   346 					if (real_bytes >= sizeof(real_sig))
   347 					{
   348 						break;
   349 					}
   350 					real_sig[real_bytes++] = s_TempSig.sig[i];
   351 					if (s_TempSig.sig[i] == '\\'
   352 						&& s_TempSig.sig[i+1] == 'x')
   353 					{
   354 						if (i + 3 >= length)
   355 						{
   356 							continue;
   357 						}
   358 						/* Get the hex part */
   359 						char s_byte[3];
   360 						int r_byte;
   361 						s_byte[0] = s_TempSig.sig[i+2];
   362 						s_byte[1] = s_TempSig.sig[i+3];
   363 						s_byte[2] = '\0';
   364 						/* Read it as an integer */
   365 						sscanf(s_byte, "%x", &r_byte);
   366 						/* Save the value */
   367 						real_sig[real_bytes-1] = r_byte;
   368 						/* Adjust index */
   369 						i += 3;
   370 					}
   371 				}
   372 
   373 				if (real_bytes < 1)
   374 				{
   375 					g_Logger.LogError("[SM] Invalid signature (name \"%s\") (gameconf \"%s\")",
   376 						m_offset,
   377 						m_pFile);
   378 				} else {
   379 					final_addr = g_MemUtils.FindPattern(addrInBase, real_sig, real_bytes);
   380 				}
   381 			}
   382 
   383 #if defined PLATFORM_LINUX
   384 skip_find:
   385 #endif
   386 			sm_trie_replace(m_pSigs, m_offset, final_addr);
   387 			m_ParseState = PSTATE_GAMEDEFS_SIGNATURES;
   388 
   389 			break;
   390 		}
   391 	}
   392 
   393 	return SMCParse_Continue;
   394 }
   395 
   396 bool CGameConfig::Reparse(char *error, size_t maxlength)
   397 {
   398 	SMCParseError err;
   399 
   400 	char path[PLATFORM_MAX_PATH];
   401 	g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "gamedata/%s.txt", m_pFile);
   402 	/* Backwards compatibility */
   403 	if (!g_LibSys.PathExists(path))
   404 	{
   405 		g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "configs/gamedata/%s.txt", m_pFile);
   406 	}
   407 
   408 	/* Initialize parse states */
   409 	m_IgnoreLevel = 0;
   410 	bShouldBeReadingDefault = true;
   411 	m_ParseState = PSTATE_NONE;
   412 	/* Reset cached data */
   413 	m_pStrings->Reset();
   414 	sm_trie_clear(m_pOffsets);
   415 	sm_trie_clear(m_pProps);
   416 	sm_trie_clear(m_pKeys);
   417 
   418 	if ((err=g_TextParser.ParseFile_SMC(path, this, NULL, NULL))
   419 		!= SMCParse_Okay)
   420 	{
   421 		if (error && (err != SMCParse_Custom))
   422 		{
   423 			const char *str = g_TextParser.GetSMCErrorString(err);
   424 			snprintf(error, maxlength, "%s", str);
   425 		}
   426 		return false;
   427 	}
   428 
   429 	return true;
   430 }
   431 
   432 bool CGameConfig::GetOffset(const char *key, int *value)
   433 {
   434 	void *obj;
   435 
   436 	if (!sm_trie_retrieve(m_pOffsets, key, &obj))
   437 	{
   438 		return false;
   439 	}
   440 
   441 	*value = (int)obj;
   442 	
   443 	return true;
   444 }
   445 
   446 const char *CGameConfig::GetKeyValue(const char *key)
   447 {
   448 	void *obj;
   449 	if (!sm_trie_retrieve(m_pKeys, key, &obj))
   450 	{
   451 		return NULL;
   452 	}
   453 	return m_pStrings->GetString((int)obj);
   454 }
   455 
   456 SendProp *CGameConfig::GetSendProp(const char *key)
   457 {
   458 	SendProp *pProp;
   459 
   460 	if (!sm_trie_retrieve(m_pProps, key, (void **)&pProp))
   461 	{
   462 		return NULL;
   463 	}
   464 
   465 	return pProp;
   466 }
   467 
   468 bool CGameConfig::GetMemSig(const char *key, void **addr)
   469 {
   470 	return sm_trie_retrieve(m_pSigs, key, addr);
   471 }
   472 
   473 void CGameConfig::IncRefCount()
   474 {
   475 	m_RefCount++;
   476 }
   477 
   478 unsigned int CGameConfig::DecRefCount()
   479 {
   480 	m_RefCount--;
   481 	return m_RefCount;
   482 }
   483 
   484 GameConfigManager::GameConfigManager()
   485 {
   486 	m_pLookup = sm_trie_create();
   487 }
   488 
   489 GameConfigManager::~GameConfigManager()
   490 {
   491 	sm_trie_destroy(m_pLookup);
   492 }
   493 
   494 void GameConfigManager::OnSourceModStartup(bool late)
   495 {
   496 	LoadGameConfigFile("core.games", &g_pGameConf, NULL, 0);
   497 
   498 	strncopy(g_mod, g_SourceMod.GetGameFolderName(), sizeof(g_mod));
   499 }
   500 
   501 void GameConfigManager::OnSourceModAllInitialized()
   502 {
   503 	/* NOW initialize the game file */
   504 	CGameConfig *pGameConf = (CGameConfig *)g_pGameConf;
   505 	
   506 	char error[255];
   507 	if (!pGameConf->Reparse(error, sizeof(error)))
   508 	{
   509 		/* :TODO: log */
   510 	}
   511 
   512 	g_ShareSys.AddInterface(NULL, this);
   513 }
   514 
   515 void GameConfigManager::OnSourceModAllShutdown()
   516 {
   517 	CloseGameConfigFile(g_pGameConf);
   518 }
   519 
   520 bool GameConfigManager::LoadGameConfigFile(const char *file, IGameConfig **_pConfig, char *error, size_t maxlength)
   521 {
   522 	CGameConfig *pConfig;
   523 
   524 	if (sm_trie_retrieve(m_pLookup, file, (void **)&pConfig))
   525 	{
   526 		pConfig->IncRefCount();
   527 		*_pConfig = pConfig;
   528 		return true;
   529 	}
   530 
   531 	pConfig = new CGameConfig(file);
   532 
   533 	/* :HACKHACK: Don't parse the main config file */
   534 	bool retval = true;
   535 	if (_pConfig != &g_pGameConf)
   536 	{
   537 		retval = pConfig->Reparse(error, maxlength);
   538 	}
   539 
   540 	m_cfgs.push_back(pConfig);
   541 	sm_trie_insert(m_pLookup, file, pConfig);
   542 
   543 	pConfig->IncRefCount();
   544 
   545 	*_pConfig = pConfig;
   546 
   547 	return retval;
   548 }
   549 
   550 void GameConfigManager::CloseGameConfigFile(IGameConfig *cfg)
   551 {
   552 	CGameConfig *pConfig = (CGameConfig *)cfg;
   553 
   554 	if (pConfig->DecRefCount() == 0)
   555 	{
   556 		sm_trie_delete(m_pLookup, pConfig->m_pFile);
   557 		delete pConfig;
   558 	}
   559 }
   560 
   561 extern HandleType_t g_GameConfigsType;
   562 
   563 IGameConfig *GameConfigManager::ReadHandle(Handle_t hndl, IdentityToken_t *ident, HandleError *err)
   564 {
   565 	HandleSecurity sec(ident, g_pCoreIdent);
   566 	IGameConfig *conf = NULL;
   567 	HandleError _err = g_HandleSys.ReadHandle(hndl, g_GameConfigsType, &sec, (void **)&conf);
   568 
   569 	if (err)
   570 	{
   571 		*err = _err;
   572 	}
   573 
   574 	return conf;
   575 }