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"
46 #if defined PLATFORM_LINUX
50 GameConfigManager g_GameConfigs;
51 IGameConfig *g_pGameConf = NULL;
53 char g_GameDesc[256] = {'!', '\0'};
54 char g_GameName[256] = {'$', '\0'};
57 #define PSTATE_GAMES 1
58 #define PSTATE_GAMEDEFS 2
59 #define PSTATE_GAMEDEFS_OFFSETS 3
60 #define PSTATE_GAMEDEFS_OFFSETS_OFFSET 4
61 #define PSTATE_GAMEDEFS_KEYS 5
62 #define PSTATE_GAMEDEFS_SUPPORTED 6
63 #define PSTATE_GAMEDEFS_SIGNATURES 7
64 #define PSTATE_GAMEDEFS_SIGNATURES_SIG 8
65 #define PSTATE_GAMEDEFS_CRC 9
66 #define PSTATE_GAMEDEFS_CRC_BINARY 10
67 #define PSTATE_GAMEDEFS_CUSTOM 11
69 #if defined PLATFORM_WINDOWS
70 #define PLATFORM_NAME "windows"
71 #define PLATFORM_SERVER_BINARY "server.dll"
72 #elif defined PLATFORM_LINUX
73 #define PLATFORM_NAME "linux"
74 #define PLATFORM_SERVER_BINARY "server_i486.so"
75 #elif defined PLATFORM_APPLE
76 #define PLATFORM_NAME "undef"
77 #define PLATFORM_SERVER_BINARY "undef.dylib"
90 unsigned int s_ServerBinCRC;
91 bool s_ServerBinCRC_Ok = false;
93 static bool DoesGameMatch(const char *value)
95 if (strcmp(value, g_Game) == 0 ||
96 strcmp(value, g_GameDesc) == 0 ||
97 strcmp(value, g_GameName) == 0)
104 static bool DoesEngineMatch(const char *value)
106 #if SOURCE_ENGINE == SE_EPISODEONE
107 if (strcmp(value, "original") == 0)
108 #elif SOURCE_ENGINE == SE_ORANGEBOX
109 if (strcmp(value, "orangebox") == 0)
110 #elif SOURCE_ENGINE == SE_LEFT4DEAD
111 if (strcmp(value, "left4dead") == 0)
113 #error "Unknown engine type"
121 CGameConfig::CGameConfig(const char *file)
123 strncopy(m_File, file, sizeof(m_File));
124 m_pOffsets = sm_trie_create();
125 m_pProps = sm_trie_create();
126 m_pKeys = sm_trie_create();
127 m_pSigs = sm_trie_create();
128 m_pStrings = new BaseStringTable(512);
132 m_CustomHandler = NULL;
135 CGameConfig::~CGameConfig()
137 sm_trie_destroy(m_pOffsets);
138 sm_trie_destroy(m_pProps);
139 sm_trie_destroy(m_pKeys);
140 sm_trie_destroy(m_pSigs);
144 SMCResult CGameConfig::ReadSMC_NewSection(const SMCStates *states, const char *name)
149 return SMCResult_Continue;
152 switch (m_ParseState)
156 if (strcmp(name, "Games") == 0)
158 m_ParseState = PSTATE_GAMES;
166 if (strcmp(name, "*") == 0 ||
167 strcmp(name, "#default") == 0 ||
170 bShouldBeReadingDefault = true;
171 m_ParseState = PSTATE_GAMEDEFS;
172 strncopy(m_Game, name, sizeof(m_Game));
178 case PSTATE_GAMEDEFS:
180 if (strcmp(name, "Offsets") == 0)
182 m_ParseState = PSTATE_GAMEDEFS_OFFSETS;
184 else if (strcmp(name, "Keys") == 0)
186 m_ParseState = PSTATE_GAMEDEFS_KEYS;
188 else if ((strcmp(name, "#supported") == 0) && (strcmp(m_Game, "#default") == 0))
190 m_ParseState = PSTATE_GAMEDEFS_SUPPORTED;
191 /* Ignore this section unless we get a game. */
192 bShouldBeReadingDefault = false;
194 matched_game = false;
196 matched_engine = false;
198 else if (strcmp(name, "Signatures") == 0)
200 m_ParseState = PSTATE_GAMEDEFS_SIGNATURES;
202 else if (strcmp(name, "CRC") == 0)
204 m_ParseState = PSTATE_GAMEDEFS_CRC;
205 bShouldBeReadingDefault = false;
209 ITextListener_SMC **pListen = g_GameConfigs.m_customHandlers.retrieve(name);
214 m_ParseState = PSTATE_GAMEDEFS_CUSTOM;
215 m_CustomHandler = *pListen;
216 m_CustomHandler->ReadSMC_ParseStart();
224 case PSTATE_GAMEDEFS_OFFSETS:
228 strncopy(m_offset, name, sizeof(m_offset));
229 m_ParseState = PSTATE_GAMEDEFS_OFFSETS_OFFSET;
232 case PSTATE_GAMEDEFS_SIGNATURES:
234 strncopy(m_offset, name, sizeof(m_offset));
236 m_ParseState = PSTATE_GAMEDEFS_SIGNATURES_SIG;
239 case PSTATE_GAMEDEFS_CRC:
243 if (strcmp(name, "server") != 0)
245 UTIL_Format(error, sizeof(error), "Unrecognized library \"%s\"", name);
247 else if (!s_ServerBinCRC_Ok)
250 char path[PLATFORM_MAX_PATH];
252 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "bin/" PLATFORM_SERVER_BINARY);
253 if ((fp = fopen(path, "rb")) == NULL)
255 UTIL_Format(error, sizeof(error), "Could not open binary: %s", path);
260 fseek(fp, 0, SEEK_END);
262 fseek(fp, 0, SEEK_SET);
264 buffer = malloc(size);
265 fread(buffer, size, 1, fp);
266 s_ServerBinCRC = UTIL_CRC32(buffer, size);
268 s_ServerBinCRC_Ok = true;
272 if (error[0] != '\0')
275 g_Logger.LogError("[SM] Error while parsing CRC section for \"%s\" (%s):", m_Game, m_CurFile);
276 g_Logger.LogError("[SM] %s", error);
278 m_ParseState = PSTATE_GAMEDEFS_CRC_BINARY;
282 case PSTATE_GAMEDEFS_CUSTOM:
285 return m_CustomHandler->ReadSMC_NewSection(states, name);
288 /* No sub-sections allowed:
289 case PSTATE_GAMEDEFS_OFFSETS_OFFSET:
290 case PSTATE_GAMEDEFS_KEYS:
291 case PSTATE_GAMEDEFS_SUPPORTED:
292 case PSTATE_GAMEDEFS_SIGNATURES_SIG:
293 case PSTATE_GAMEDEFS_CRC_BINARY:
297 /* If we don't know what we got, start ignoring */
303 return SMCResult_Continue;
306 SMCResult CGameConfig::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
310 return SMCResult_Continue;
313 if (m_ParseState == PSTATE_GAMEDEFS_OFFSETS_OFFSET)
315 if (strcmp(key, "class") == 0)
317 strncopy(m_Class, value, sizeof(m_Class));
318 } else if (strcmp(key, "prop") == 0) {
319 strncopy(m_Prop, value, sizeof(m_Prop));
320 } else if (strcmp(key, PLATFORM_NAME) == 0) {
321 int val = atoi(value);
322 sm_trie_replace(m_pOffsets, m_offset, (void *)val);
324 } else if (m_ParseState == PSTATE_GAMEDEFS_KEYS) {
325 int id = m_pStrings->AddString(value);
326 sm_trie_replace(m_pKeys, key, (void *)id);
327 } else if (m_ParseState == PSTATE_GAMEDEFS_SUPPORTED) {
328 if (strcmp(key, "game") == 0)
331 if (DoesGameMatch(value))
335 if ((!had_engine && matched_game) || (matched_engine && matched_game))
337 bShouldBeReadingDefault = true;
340 else if (strcmp(key, "engine") == 0)
343 if (DoesEngineMatch(value))
345 matched_engine = true;
347 if ((!had_game && matched_engine) || (matched_game && matched_engine))
349 bShouldBeReadingDefault = true;
352 } else if (m_ParseState == PSTATE_GAMEDEFS_SIGNATURES_SIG) {
353 if (strcmp(key, PLATFORM_NAME) == 0)
355 strncopy(s_TempSig.sig, value, sizeof(s_TempSig.sig));
356 } else if (strcmp(key, "library") == 0) {
357 strncopy(s_TempSig.library, value, sizeof(s_TempSig.library));
359 } else if (m_ParseState == PSTATE_GAMEDEFS_CRC_BINARY) {
360 if (strcmp(key, PLATFORM_NAME) == 0
362 && !bShouldBeReadingDefault)
364 unsigned int crc = 0;
365 sscanf(value, "%08X", &crc);
366 if (s_ServerBinCRC == crc)
368 bShouldBeReadingDefault = true;
371 } else if (m_ParseState == PSTATE_GAMEDEFS_CUSTOM) {
372 return m_CustomHandler->ReadSMC_KeyValue(states, key, value);
375 return SMCResult_Continue;
378 SMCResult CGameConfig::ReadSMC_LeavingSection(const SMCStates *states)
383 return SMCResult_Continue;
389 m_CustomHandler->ReadSMC_LeavingSection(states);
390 return SMCResult_Continue;
393 switch (m_ParseState)
397 m_ParseState = PSTATE_NONE;
400 case PSTATE_GAMEDEFS:
402 m_ParseState = PSTATE_GAMES;
405 case PSTATE_GAMEDEFS_CUSTOM:
407 m_ParseState = PSTATE_GAMEDEFS;
408 m_CustomHandler->ReadSMC_ParseEnd(false, false);
411 case PSTATE_GAMEDEFS_KEYS:
412 case PSTATE_GAMEDEFS_OFFSETS:
414 m_ParseState = PSTATE_GAMEDEFS;
417 case PSTATE_GAMEDEFS_OFFSETS_OFFSET:
419 /* Parse the offset... */
420 if (m_Class[0] != '\0'
421 && m_Prop[0] != '\0')
423 SendProp *pProp = g_HL2.FindInSendTable(m_Class, m_Prop);
426 int val = pProp->GetOffset();
427 sm_trie_replace(m_pOffsets, m_offset, (void *)val);
428 sm_trie_replace(m_pProps, m_offset, pProp);
430 /* Check if it's a non-default game and no offsets exist */
431 if (((strcmp(m_Game, "*") != 0) && strcmp(m_Game, "#default") != 0)
432 && (!sm_trie_retrieve(m_pOffsets, m_offset, NULL)))
434 g_Logger.LogError("[SM] Unable to find property %s.%s (file \"%s\") (mod \"%s\")",
442 m_ParseState = PSTATE_GAMEDEFS_OFFSETS;
445 case PSTATE_GAMEDEFS_CRC:
446 case PSTATE_GAMEDEFS_SUPPORTED:
448 if (!bShouldBeReadingDefault)
450 /* If we shouldn't read the rest of this section, set the ignore level. */
452 m_ParseState = PSTATE_GAMES;
454 m_ParseState = PSTATE_GAMEDEFS;
458 case PSTATE_GAMEDEFS_CRC_BINARY:
460 m_ParseState = PSTATE_GAMEDEFS_CRC;
463 case PSTATE_GAMEDEFS_SIGNATURES:
465 m_ParseState = PSTATE_GAMEDEFS;
468 case PSTATE_GAMEDEFS_SIGNATURES_SIG:
470 if (s_TempSig.library[0] == '\0')
473 strncopy(s_TempSig.library, "server", sizeof(s_TempSig.library));
475 void *addrInBase = NULL;
476 if (strcmp(s_TempSig.library, "server") == 0)
478 addrInBase = (void *)g_SMAPI->GetServerFactory(false);
479 } else if (strcmp(s_TempSig.library, "engine") == 0) {
480 addrInBase = (void *)g_SMAPI->GetEngineFactory(false);
482 void *final_addr = NULL;
483 if (addrInBase == NULL)
485 g_Logger.LogError("[SM] Unrecognized library \"%s\" (gameconf \"%s\")",
489 #if defined PLATFORM_LINUX
490 if (s_TempSig.sig[0] == '@')
493 /* GNU only: returns 0 on error, inconsistent! >:[ */
494 if (dladdr(addrInBase, &info) != 0)
496 void *handle = dlopen(info.dli_fname, RTLD_NOW);
499 final_addr = dlsym(handle, &s_TempSig.sig[1]);
502 g_Logger.LogError("[SM] Unable to load library \"%s\" (gameconf \"%s\")",
507 g_Logger.LogError("[SM] Unable to find library \"%s\" in memory (gameconf \"%s\")",
517 /* First, preprocess the signature */
523 length = strlen(s_TempSig.sig);
525 for (size_t i=0; i<length; i++)
527 if (real_bytes >= sizeof(real_sig))
531 real_sig[real_bytes++] = s_TempSig.sig[i];
532 if (s_TempSig.sig[i] == '\\'
533 && s_TempSig.sig[i+1] == 'x')
539 /* Get the hex part */
542 s_byte[0] = s_TempSig.sig[i+2];
543 s_byte[1] = s_TempSig.sig[i+3];
545 /* Read it as an integer */
546 sscanf(s_byte, "%x", &r_byte);
548 real_sig[real_bytes-1] = r_byte;
556 final_addr = g_MemUtils.FindPattern(addrInBase, real_sig, real_bytes);
560 #if defined PLATFORM_LINUX
563 sm_trie_replace(m_pSigs, m_offset, final_addr);
564 m_ParseState = PSTATE_GAMEDEFS_SIGNATURES;
570 return SMCResult_Continue;
573 #define MSTATE_NONE 0
574 #define MSTATE_MAIN 1
575 #define MSTATE_FILE 2
577 class MasterReader : public ITextListener_SMC
580 virtual void ReadSMC_ParseStart()
586 virtual SMCResult ReadSMC_NewSection(const SMCStates *states, const char *name)
590 return SMCResult_Continue;
593 if (state == MSTATE_NONE)
595 if (strcmp(name, "Game Master") == 0)
604 else if (state == MSTATE_MAIN)
606 strncopy(cur_file, name, sizeof(cur_file));
608 matched_engine = false;
610 matched_game = false;
613 else if (state == MSTATE_FILE)
618 return SMCResult_Continue;
621 virtual SMCResult ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
623 if (ignoreLevel || state != MSTATE_FILE)
625 return SMCResult_Continue;
628 if (strcmp(key, "engine") == 0)
631 if (DoesEngineMatch(value))
633 matched_engine = true;
636 else if (strcmp(key, "game") == 0)
639 if (DoesGameMatch(value))
645 return SMCResult_Continue;
648 virtual SMCResult ReadSMC_LeavingSection(const SMCStates *states)
653 return SMCResult_Continue;
656 if (state == MSTATE_FILE)
658 /* The four success conditions:
660 * 2. Needed game only.
661 * 3. Needed engine only.
662 * 4. Needed both engine and game.
663 * Final result is minimized via k-map.
666 if ((!had_engine && !had_game) ||
667 (!had_engine && (had_game && matched_game)) ||
668 (!had_game && (had_engine && matched_engine)) ||
669 ((had_game && had_engine) && (matched_game && matched_engine)))
671 if ((!had_engine && !had_game) ||
672 (!had_engine && matched_game) ||
673 (!had_game && matched_engine) ||
674 (matched_engine && matched_game))
676 fileList->push_back(cur_file);
680 else if (state == MSTATE_MAIN)
685 return SMCResult_Continue;
688 List<String> *fileList;
690 unsigned int ignoreLevel;
691 char cur_file[PLATFORM_MAX_PATH];
698 static MasterReader master_reader;
700 bool CGameConfig::Reparse(char *error, size_t maxlength)
702 /* Reset cached data */
704 sm_trie_clear(m_pOffsets);
705 sm_trie_clear(m_pProps);
706 sm_trie_clear(m_pKeys);
708 char path[PLATFORM_MAX_PATH];
710 /* See if we can use the extended gamedata format. */
711 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "gamedata/%s/master.games.txt", m_File);
712 if (!g_LibSys.PathExists(path))
714 /* Nope, use the old mechanism. */
715 UTIL_Format(path, sizeof(path), "%s.txt", m_File);
716 return EnterFile(path, error, maxlength);
719 /* Otherwise, it's time to parse the master. */
721 SMCStates state = {0, 0};
722 List<String> fileList;
723 master_reader.fileList = &fileList;
725 err = textparsers->ParseSMCFile(path, &master_reader, &state, error, maxlength);
726 if (err != SMCError_Okay)
728 const char *msg = textparsers->GetSMCErrorString(err);
730 g_Logger.LogError("[SM] Error parsing master gameconf file \"%s\":", path);
731 g_Logger.LogError("[SM] Error %d on line %d, col %d: %s",
735 msg ? msg : "Unknown error");
739 /* Go through each file we found and parse it. */
740 List<String>::iterator iter;
741 for (iter = fileList.begin(); iter != fileList.end(); iter++)
743 UTIL_Format(path, sizeof(path), "%s/%s", m_File, (*iter).c_str());
744 if (!EnterFile(path, error, maxlength))
753 bool CGameConfig::EnterFile(const char *file, char *error, size_t maxlength)
756 SMCStates state = {0, 0};
758 g_SourceMod.BuildPath(Path_SM, m_CurFile, sizeof(m_CurFile), "gamedata/%s", file);
760 /* Initialize parse states */
762 bShouldBeReadingDefault = true;
763 m_ParseState = PSTATE_NONE;
765 g_GameConfigs.AcquireLock();
767 if ((err=textparsers->ParseSMCFile(m_CurFile, this, &state, error, maxlength))
772 g_GameConfigs.ReleaseLock();
774 msg = textparsers->GetSMCErrorString(err);
776 g_Logger.LogError("[SM] Error parsing gameconfig file \"%s\":", m_CurFile);
777 g_Logger.LogError("[SM] Error %d on line %d, col %d: %s",
781 msg ? msg : "Unknown error");
783 if (m_ParseState == PSTATE_GAMEDEFS_CUSTOM)
785 //error occurred while parsing a custom section
786 m_CustomHandler->ReadSMC_ParseEnd(true, true);
787 m_CustomHandler = NULL;
794 g_GameConfigs.ReleaseLock();
799 bool CGameConfig::GetOffset(const char *key, int *value)
803 if (!sm_trie_retrieve(m_pOffsets, key, &obj))
813 const char *CGameConfig::GetKeyValue(const char *key)
816 if (!sm_trie_retrieve(m_pKeys, key, &obj))
820 return m_pStrings->GetString((int)obj);
823 SendProp *CGameConfig::GetSendProp(const char *key)
827 if (!sm_trie_retrieve(m_pProps, key, (void **)&pProp))
835 bool CGameConfig::GetMemSig(const char *key, void **addr)
837 return sm_trie_retrieve(m_pSigs, key, addr);
840 void CGameConfig::IncRefCount()
845 unsigned int CGameConfig::DecRefCount()
851 GameConfigManager::GameConfigManager()
853 m_pLookup = sm_trie_create();
856 GameConfigManager::~GameConfigManager()
858 sm_trie_destroy(m_pLookup);
861 void GameConfigManager::OnSourceModStartup(bool late)
863 m_FileLock = g_pThreader->MakeMutex();
865 LoadGameConfigFile("core.games", &g_pGameConf, NULL, 0);
867 strncopy(g_Game, g_SourceMod.GetGameFolderName(), sizeof(g_Game));
868 strncopy(g_GameDesc + 1, SERVER_CALL(GetGameDescription)(), sizeof(g_GameDesc) - 1);
870 KeyValues *pGameInfo = new KeyValues("GameInfo");
871 if (g_HL2.KVLoadFromFile(pGameInfo, basefilesystem, "gameinfo.txt"))
874 if ((str = pGameInfo->GetString("game", NULL)) != NULL)
876 strncopy(g_GameName + 1, str, sizeof(g_GameName) - 1);
879 pGameInfo->deleteThis();
882 void GameConfigManager::OnSourceModAllInitialized()
884 /* NOW initialize the game file */
885 CGameConfig *pGameConf = (CGameConfig *)g_pGameConf;
888 if (!pGameConf->Reparse(error, sizeof(error)))
893 g_ShareSys.AddInterface(NULL, this);
896 void GameConfigManager::OnSourceModAllShutdown()
898 CloseGameConfigFile(g_pGameConf);
899 m_FileLock->DestroyThis();
902 bool GameConfigManager::LoadGameConfigFile(const char *file, IGameConfig **_pConfig, char *error, size_t maxlength)
905 /* A crash was detected during last load - We block the gamedata loading so it hopefully won't happen again */
906 if (g_blockGameDataLoad)
908 UTIL_Format(error, maxlength, "GameData loaded blocked due to detected crash");
913 CGameConfig *pConfig;
915 if (sm_trie_retrieve(m_pLookup, file, (void **)&pConfig))
917 pConfig->IncRefCount();
922 pConfig = new CGameConfig(file);
924 /* :HACKHACK: Don't parse the main config file */
926 if (_pConfig != &g_pGameConf)
928 retval = pConfig->Reparse(error, maxlength);
931 m_cfgs.push_back(pConfig);
932 sm_trie_insert(m_pLookup, file, pConfig);
934 pConfig->IncRefCount();
941 void GameConfigManager::CloseGameConfigFile(IGameConfig *cfg)
943 CGameConfig *pConfig = (CGameConfig *)cfg;
945 if (pConfig->DecRefCount() == 0)
947 sm_trie_delete(m_pLookup, pConfig->m_File);
952 extern HandleType_t g_GameConfigsType;
954 IGameConfig *GameConfigManager::ReadHandle(Handle_t hndl, IdentityToken_t *ident, HandleError *err)
956 HandleSecurity sec(ident, g_pCoreIdent);
957 IGameConfig *conf = NULL;
958 HandleError _err = g_HandleSys.ReadHandle(hndl, g_GameConfigsType, &sec, (void **)&conf);
968 void GameConfigManager::AddUserConfigHook(const char *sectionname, ITextListener_SMC *listener)
970 m_customHandlers.insert(sectionname, listener);
973 void GameConfigManager::RemoveUserConfigHook(const char *sectionname, ITextListener_SMC *listener)
975 ITextListener_SMC **pListener = m_customHandlers.retrieve(sectionname);
977 if (pListener == NULL)
982 if (*pListener != listener)
987 m_customHandlers.remove(sectionname);
992 void GameConfigManager::AcquireLock()
997 void GameConfigManager::ReleaseLock()
999 m_FileLock->Unlock();