Initial Import of beta structs extension.
3 * =============================================================================
5 * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
6 * =============================================================================
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.
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
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/>.
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>.
34 #include "GameConfigs.h"
35 #include "sm_stringutil.h"
36 #include "sourcemod.h"
37 #include "sourcemm_api.h"
38 #include "HalfLife2.h"
41 #include "MemoryUtils.h"
42 #include "LibrarySys.h"
43 #include "HandleSys.h"
45 #include "GameDataFetcher.h"
47 #if defined PLATFORM_LINUX
51 GameConfigManager g_GameConfigs;
52 IGameConfig *g_pGameConf = NULL;
54 char g_GameDesc[256] = {'!', '\0'};
55 char g_GameName[256] = {'$', '\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
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"
88 unsigned int s_ServerBinCRC;
89 bool s_ServerBinCRC_Ok = false;
91 CGameConfig::CGameConfig(const char *file)
93 m_pFile = sm_strdup(file);
94 m_pOffsets = sm_trie_create();
95 m_pProps = sm_trie_create();
96 m_pKeys = sm_trie_create();
97 m_pSigs = sm_trie_create();
98 m_pStrings = new BaseStringTable(512);
102 m_CustomHandler = NULL;
105 CGameConfig::~CGameConfig()
107 sm_trie_destroy(m_pOffsets);
108 sm_trie_destroy(m_pProps);
109 sm_trie_destroy(m_pKeys);
110 sm_trie_destroy(m_pSigs);
115 SMCResult CGameConfig::ReadSMC_NewSection(const SMCStates *states, const char *name)
120 return SMCResult_Continue;
123 switch (m_ParseState)
127 if (strcmp(name, "Games") == 0)
129 m_ParseState = PSTATE_GAMES;
137 if ((strcmp(name, "*") == 0)
138 || (strcmp(name, "#default") == 0)
139 || (strcasecmp(name, g_Game) == 0)
140 || (strcasecmp(name, g_GameDesc) == 0)
141 || (strcasecmp(name, g_GameName) == 0))
143 bShouldBeReadingDefault = true;
144 m_ParseState = PSTATE_GAMEDEFS;
145 strncopy(m_Game, name, sizeof(m_Game));
151 case PSTATE_GAMEDEFS:
153 if (strcmp(name, "Offsets") == 0)
155 m_ParseState = PSTATE_GAMEDEFS_OFFSETS;
157 else if (strcmp(name, "Keys") == 0)
159 m_ParseState = PSTATE_GAMEDEFS_KEYS;
161 else if ((strcmp(name, "#supported") == 0)
162 && (strcmp(m_Game, "#default") == 0))
164 m_ParseState = PSTATE_GAMEDEFS_SUPPORTED;
165 /* Ignore this section unless we get a game. */
166 bShouldBeReadingDefault = false;
168 else if (strcmp(name, "Signatures") == 0)
170 m_ParseState = PSTATE_GAMEDEFS_SIGNATURES;
172 else if (strcmp(name, "CRC") == 0)
174 m_ParseState = PSTATE_GAMEDEFS_CRC;
175 bShouldBeReadingDefault = false;
179 ITextListener_SMC **pListen = g_GameConfigs.m_customHandlers.retrieve(name);
184 m_ParseState = PSTATE_GAMEDEFS_CUSTOM;
185 m_CustomHandler = *pListen;
186 m_CustomHandler->ReadSMC_ParseStart();
194 case PSTATE_GAMEDEFS_OFFSETS:
198 strncopy(m_offset, name, sizeof(m_offset));
199 m_ParseState = PSTATE_GAMEDEFS_OFFSETS_OFFSET;
202 case PSTATE_GAMEDEFS_SIGNATURES:
204 strncopy(m_offset, name, sizeof(m_offset));
206 m_ParseState = PSTATE_GAMEDEFS_SIGNATURES_SIG;
209 case PSTATE_GAMEDEFS_CRC:
213 if (strcmp(name, "server") != 0)
215 UTIL_Format(error, sizeof(error), "Unrecognized library \"%s\"", name);
217 else if (!s_ServerBinCRC_Ok)
220 char path[PLATFORM_MAX_PATH];
222 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "bin/" PLATFORM_SERVER_BINARY);
223 if ((fp = fopen(path, "rb")) == NULL)
225 UTIL_Format(error, sizeof(error), "Could not open binary: %s", path);
230 fseek(fp, 0, SEEK_END);
232 fseek(fp, 0, SEEK_SET);
234 buffer = malloc(size);
235 fread(buffer, size, 1, fp);
236 s_ServerBinCRC = UTIL_CRC32(buffer, size);
238 s_ServerBinCRC_Ok = true;
242 if (error[0] != '\0')
245 g_Logger.LogError("[SM] Error while parsing CRC section for \"%s\" (%s):", m_Game, m_pFile);
246 g_Logger.LogError("[SM] %s", error);
248 m_ParseState = PSTATE_GAMEDEFS_CRC_BINARY;
252 case PSTATE_GAMEDEFS_CUSTOM:
255 return m_CustomHandler->ReadSMC_NewSection(states, name);
258 /* No sub-sections allowed:
259 case PSTATE_GAMEDEFS_OFFSETS_OFFSET:
260 case PSTATE_GAMEDEFS_KEYS:
261 case PSTATE_GAMEDEFS_SUPPORTED:
262 case PSTATE_GAMEDEFS_SIGNATURES_SIG:
263 case PSTATE_GAMEDEFS_CRC_BINARY:
267 /* If we don't know what we got, start ignoring */
273 return SMCResult_Continue;
276 SMCResult CGameConfig::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
280 return SMCResult_Continue;
283 if (m_ParseState == PSTATE_GAMEDEFS_OFFSETS_OFFSET)
285 if (strcmp(key, "class") == 0)
287 strncopy(m_Class, value, sizeof(m_Class));
288 } else if (strcmp(key, "prop") == 0) {
289 strncopy(m_Prop, value, sizeof(m_Prop));
290 } else if (strcmp(key, PLATFORM_NAME) == 0) {
291 int val = atoi(value);
292 sm_trie_replace(m_pOffsets, m_offset, (void *)val);
294 } else if (m_ParseState == PSTATE_GAMEDEFS_KEYS) {
295 int id = m_pStrings->AddString(value);
296 sm_trie_replace(m_pKeys, key, (void *)id);
297 } else if (m_ParseState == PSTATE_GAMEDEFS_SUPPORTED) {
298 if (strcmp(key, "game") == 0
299 && (strcasecmp(value, g_Game) == 0
300 || strcasecmp(value, g_GameDesc) == 0
301 || strcasecmp(value, g_GameName) == 0)
304 bShouldBeReadingDefault = true;
306 } else if (m_ParseState == PSTATE_GAMEDEFS_SIGNATURES_SIG) {
307 if (strcmp(key, PLATFORM_NAME) == 0)
309 strncopy(s_TempSig.sig, value, sizeof(s_TempSig.sig));
310 } else if (strcmp(key, "library") == 0) {
311 strncopy(s_TempSig.library, value, sizeof(s_TempSig.library));
313 } else if (m_ParseState == PSTATE_GAMEDEFS_CRC_BINARY) {
314 if (strcmp(key, PLATFORM_NAME) == 0
316 && !bShouldBeReadingDefault)
318 unsigned int crc = 0;
319 sscanf(value, "%08X", &crc);
320 if (s_ServerBinCRC == crc)
322 bShouldBeReadingDefault = true;
325 } else if (m_ParseState == PSTATE_GAMEDEFS_CUSTOM) {
326 return m_CustomHandler->ReadSMC_KeyValue(states, key, value);
329 return SMCResult_Continue;
332 SMCResult CGameConfig::ReadSMC_LeavingSection(const SMCStates *states)
337 return SMCResult_Continue;
343 m_CustomHandler->ReadSMC_LeavingSection(states);
344 return SMCResult_Continue;
347 switch (m_ParseState)
351 m_ParseState = PSTATE_NONE;
354 case PSTATE_GAMEDEFS:
356 m_ParseState = PSTATE_GAMES;
359 case PSTATE_GAMEDEFS_CUSTOM:
361 m_ParseState = PSTATE_GAMEDEFS;
362 m_CustomHandler->ReadSMC_ParseEnd(false, false);
365 case PSTATE_GAMEDEFS_KEYS:
366 case PSTATE_GAMEDEFS_OFFSETS:
368 m_ParseState = PSTATE_GAMEDEFS;
371 case PSTATE_GAMEDEFS_OFFSETS_OFFSET:
373 /* Parse the offset... */
374 if (m_Class[0] != '\0'
375 && m_Prop[0] != '\0')
377 SendProp *pProp = g_HL2.FindInSendTable(m_Class, m_Prop);
380 int val = pProp->GetOffset();
381 sm_trie_replace(m_pOffsets, m_offset, (void *)val);
382 sm_trie_replace(m_pProps, m_offset, pProp);
384 /* Check if it's a non-default game and no offsets exist */
385 if (((strcmp(m_Game, "*") != 0) && strcmp(m_Game, "#default") != 0)
386 && (!sm_trie_retrieve(m_pOffsets, m_offset, NULL)))
388 g_Logger.LogError("[SM] Unable to find property %s.%s (file \"%s\") (mod \"%s\")",
396 m_ParseState = PSTATE_GAMEDEFS_OFFSETS;
399 case PSTATE_GAMEDEFS_CRC:
400 case PSTATE_GAMEDEFS_SUPPORTED:
402 if (!bShouldBeReadingDefault)
404 /* If we shouldn't read the rest of this section, set the ignore level. */
406 m_ParseState = PSTATE_GAMES;
408 m_ParseState = PSTATE_GAMEDEFS;
412 case PSTATE_GAMEDEFS_CRC_BINARY:
414 m_ParseState = PSTATE_GAMEDEFS_CRC;
417 case PSTATE_GAMEDEFS_SIGNATURES:
419 m_ParseState = PSTATE_GAMEDEFS;
422 case PSTATE_GAMEDEFS_SIGNATURES_SIG:
424 if (s_TempSig.library[0] == '\0')
427 strncopy(s_TempSig.library, "server", sizeof(s_TempSig.library));
429 void *addrInBase = NULL;
430 if (strcmp(s_TempSig.library, "server") == 0)
432 addrInBase = (void *)g_SMAPI->GetServerFactory(false);
433 } else if (strcmp(s_TempSig.library, "engine") == 0) {
434 addrInBase = (void *)g_SMAPI->GetEngineFactory(false);
436 void *final_addr = NULL;
437 if (addrInBase == NULL)
439 g_Logger.LogError("[SM] Unrecognized library \"%s\" (gameconf \"%s\")",
443 #if defined PLATFORM_LINUX
444 if (s_TempSig.sig[0] == '@')
447 /* GNU only: returns 0 on error, inconsistent! >:[ */
448 if (dladdr(addrInBase, &info) != 0)
450 void *handle = dlopen(info.dli_fname, RTLD_NOW);
453 final_addr = dlsym(handle, &s_TempSig.sig[1]);
456 g_Logger.LogError("[SM] Unable to load library \"%s\" (gameconf \"%s\")",
461 g_Logger.LogError("[SM] Unable to find library \"%s\" in memory (gameconf \"%s\")",
471 /* First, preprocess the signature */
477 length = strlen(s_TempSig.sig);
479 for (size_t i=0; i<length; i++)
481 if (real_bytes >= sizeof(real_sig))
485 real_sig[real_bytes++] = s_TempSig.sig[i];
486 if (s_TempSig.sig[i] == '\\'
487 && s_TempSig.sig[i+1] == 'x')
493 /* Get the hex part */
496 s_byte[0] = s_TempSig.sig[i+2];
497 s_byte[1] = s_TempSig.sig[i+3];
499 /* Read it as an integer */
500 sscanf(s_byte, "%x", &r_byte);
502 real_sig[real_bytes-1] = r_byte;
510 final_addr = g_MemUtils.FindPattern(addrInBase, real_sig, real_bytes);
514 #if defined PLATFORM_LINUX
517 sm_trie_replace(m_pSigs, m_offset, final_addr);
518 m_ParseState = PSTATE_GAMEDEFS_SIGNATURES;
524 return SMCResult_Continue;
527 bool CGameConfig::Reparse(char *error, size_t maxlength)
530 SMCStates state = {0, 0};
532 char path[PLATFORM_MAX_PATH];
533 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "gamedata/%s.txt", m_pFile);
534 /* Backwards compatibility */
535 if (!g_LibSys.PathExists(path))
537 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "configs/gamedata/%s.txt", m_pFile);
540 /* Initialize parse states */
542 bShouldBeReadingDefault = true;
543 m_ParseState = PSTATE_NONE;
544 /* Reset cached data */
546 sm_trie_clear(m_pOffsets);
547 sm_trie_clear(m_pProps);
548 sm_trie_clear(m_pKeys);
550 if ((err=textparsers->ParseSMCFile(path, this, &state, error, maxlength))
555 msg = textparsers->GetSMCErrorString(err);
557 g_Logger.LogError("[SM] Error parsing gameconfig file \"%s\":", path);
558 g_Logger.LogError("[SM] Error %d on line %d, col %d: %s",
562 msg ? msg : "Unknown error");
564 if (m_ParseState == PSTATE_GAMEDEFS_CUSTOM)
566 //error occurred while parsing a custom section
567 m_CustomHandler->ReadSMC_ParseEnd(true, true);
568 m_CustomHandler = NULL;
578 bool CGameConfig::GetOffset(const char *key, int *value)
582 if (!sm_trie_retrieve(m_pOffsets, key, &obj))
592 const char *CGameConfig::GetKeyValue(const char *key)
595 if (!sm_trie_retrieve(m_pKeys, key, &obj))
599 return m_pStrings->GetString((int)obj);
602 SendProp *CGameConfig::GetSendProp(const char *key)
606 if (!sm_trie_retrieve(m_pProps, key, (void **)&pProp))
614 bool CGameConfig::GetMemSig(const char *key, void **addr)
616 return sm_trie_retrieve(m_pSigs, key, addr);
619 void CGameConfig::IncRefCount()
624 unsigned int CGameConfig::DecRefCount()
630 GameConfigManager::GameConfigManager()
632 m_pLookup = sm_trie_create();
635 GameConfigManager::~GameConfigManager()
637 sm_trie_destroy(m_pLookup);
640 void GameConfigManager::OnSourceModStartup(bool late)
642 LoadGameConfigFile("core.games", &g_pGameConf, NULL, 0);
644 strncopy(g_Game, g_SourceMod.GetGameFolderName(), sizeof(g_Game));
645 strncopy(g_GameDesc + 1, SERVER_CALL(GetGameDescription)(), sizeof(g_GameDesc) - 1);
647 KeyValues *pGameInfo = new KeyValues("GameInfo");
648 if (g_HL2.KVLoadFromFile(pGameInfo, basefilesystem, "gameinfo.txt"))
651 if ((str = pGameInfo->GetString("game", NULL)) != NULL)
653 strncopy(g_GameName + 1, str, sizeof(g_GameName) - 1);
656 pGameInfo->deleteThis();
659 void GameConfigManager::OnSourceModAllInitialized()
661 /* NOW initialize the game file */
662 CGameConfig *pGameConf = (CGameConfig *)g_pGameConf;
665 if (!pGameConf->Reparse(error, sizeof(error)))
670 g_ShareSys.AddInterface(NULL, this);
673 void GameConfigManager::OnSourceModAllShutdown()
675 CloseGameConfigFile(g_pGameConf);
678 bool GameConfigManager::LoadGameConfigFile(const char *file, IGameConfig **_pConfig, char *error, size_t maxlength)
680 /* A crash was detected during last load - We block the gamedata loading so it hopefully won't happen again */
681 if (g_blockGameDataLoad)
683 UTIL_Format(error, maxlength, "GameData loaded blocked due to detected crash");
687 CGameConfig *pConfig;
689 if (sm_trie_retrieve(m_pLookup, file, (void **)&pConfig))
691 pConfig->IncRefCount();
696 pConfig = new CGameConfig(file);
698 /* :HACKHACK: Don't parse the main config file */
700 if (_pConfig != &g_pGameConf)
702 retval = pConfig->Reparse(error, maxlength);
705 m_cfgs.push_back(pConfig);
706 sm_trie_insert(m_pLookup, file, pConfig);
708 pConfig->IncRefCount();
715 void GameConfigManager::CloseGameConfigFile(IGameConfig *cfg)
717 CGameConfig *pConfig = (CGameConfig *)cfg;
719 if (pConfig->DecRefCount() == 0)
721 sm_trie_delete(m_pLookup, pConfig->m_pFile);
726 extern HandleType_t g_GameConfigsType;
728 IGameConfig *GameConfigManager::ReadHandle(Handle_t hndl, IdentityToken_t *ident, HandleError *err)
730 HandleSecurity sec(ident, g_pCoreIdent);
731 IGameConfig *conf = NULL;
732 HandleError _err = g_HandleSys.ReadHandle(hndl, g_GameConfigsType, &sec, (void **)&conf);
742 void GameConfigManager::AddUserConfigHook( const char *sectionname, ITextListener_SMC *listener )
744 m_customHandlers.insert(sectionname, listener);
747 void GameConfigManager::RemoveUserConfigHook( const char *sectionname, ITextListener_SMC *listener )
749 ITextListener_SMC **pListener = m_customHandlers.retrieve(sectionname);
751 if (pListener == NULL)
756 if (*pListener != listener)
761 m_customHandlers.remove(sectionname);