Mm, oopsy. ICvar::GetCommandLineValue could return NULL for the plugins file. That would be bad. :(
(Now fixed with a call to GetPluginsFile in case it is NULL)
1 /* ======== SourceMM ========
2 * Copyright (C) 2004-2006 Metamod:Source Development Team
3 * No warranties of any kind
7 * Author(s): David "BAILOPAN" Anderson
8 * Contributor(s): Scott "Damaged Soul" Ehlert
9 * : Pavol "PM OnoTo" Marko
10 * ============================
13 #include <interface.h>
16 #include "concommands.h"
21 using namespace SourceMM;
24 * @brief Implementation of main SourceMM GameDLL functionality
28 SH_DECL_HOOK4(IServerGameDLL, DLLInit, SH_NOATTRIB, false, bool, CreateInterfaceFn, CreateInterfaceFn, CreateInterfaceFn, CGlobalVars *);
29 SH_DECL_HOOK0_void(IServerGameDLL, DLLShutdown, SH_NOATTRIB, false);
30 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
31 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
32 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
33 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
34 void DLLShutdown_handler();
35 void LevelShutdown_handler();
36 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background);
38 GameDllInfo g_GameDll = {false, NULL, NULL, NULL};
40 SourceHook::CSourceHookImpl g_SourceHook;
41 SourceHook::ISourceHook *g_SHPtr = &g_SourceHook;
42 SourceHook::String g_ModPath;
43 SourceHook::String g_BinPath;
44 PluginId g_PLID = Pl_Console; //Technically, SourceMM is the "Console" plugin... :p
45 bool bInFirstLevel = true;
46 bool gParsedGameInfo = false;
47 SourceHook::List<GameDllInfo *> gamedll_list;
48 SourceHook::CallClass<IServerGameDLL> *dllExec;
50 void ClearGamedllList();
53 #define IFACE_MACRO(orig,nam) \
54 CPluginManager::CPlugin *pl; \
55 SourceHook::List<IMetamodListener *>::iterator event; \
56 IMetamodListener *api; \
59 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
61 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
63 mret = IFACE_FAILED; \
64 if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
65 if (ret) *ret = mret; \
70 return (orig)(iface, ret);
72 #define ITER_EVENT(evn, args) \
73 CPluginManager::CPlugin *pl; \
74 SourceHook::List<IMetamodListener *>::iterator event; \
75 IMetamodListener *api; \
76 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
78 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
84 ///////////////////////////////////
85 // Main code for HL2 Interaction //
86 ///////////////////////////////////
88 //Initialize everything here
91 char full_path[260] = {0};
92 GetFileOfAddress(g_GameDll.factory, full_path, sizeof(full_path)-1);
93 g_BinPath.assign(full_path);
95 //Like metamod, reload plugins at the end of the map.
96 //This is so plugins can hook everything on load, BUT, new plugins will be reloaded
97 // if the server is shut down (silly, but rare case).
100 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit, false);
101 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit_Post, true);
102 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLShutdown, g_GameDll.pGameDLL, DLLShutdown_handler, false);
103 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
104 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
107 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
109 g_Engine.engineFactory = engineFactory;
110 g_Engine.fileSystemFactory = filesystemFactory;
111 g_Engine.physicsFactory = physicsFactory;
112 g_Engine.pGlobals = pGlobals;
114 g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
115 if (!g_Engine.engine)
117 Error("Could not find IVEngineServer! Metamod cannot load.");
120 g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
123 Error("Could not find ICvar! Metamod cannot load.");
127 g_Engine.loaded = true;
129 //Initialize our console hooks
130 ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
132 if (!g_SmmAPI.CacheCmds())
134 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
135 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
139 const char *pluginFile = g_Engine.icvar->GetCommandLineValue("mm_pluginsfile");
141 pluginFile = GetPluginsFile();
144 g_SmmAPI.PathFormat(full_path, sizeof(full_path)-1, "%s/%s", g_ModPath.c_str(), pluginFile);
146 LoadPluginsFromFile(full_path);
148 bInFirstLevel = true;
150 dllExec = SH_GET_CALLCLASS(g_GameDll.pGameDLL);
152 RETURN_META_VALUE(MRES_IGNORED, true);
155 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
157 g_PluginMngr.SetAllLoaded();
158 RETURN_META_VALUE(MRES_IGNORED, true);
161 //This is where the magic happens
162 SMM_API void *CreateInterface(const char *iface, int *ret)
164 if (!gParsedGameInfo)
166 gParsedGameInfo = true;
167 char curpath[260] = {0};
168 char dllpath[260] = {0};
169 getcwd(curpath, sizeof(curpath)-1);
170 if (!GetFileOfAddress((void *)CreateInterface, dllpath, sizeof(dllpath)-1))
172 Error("GetFileOfAddress() failed! Metamod cannot load.");
175 SourceHook::String s_dllpath(dllpath);
176 //begin the heuristics for searching for the mod path (these are quite ugly).
177 //for OS compatibility purposes, we're going to do case insensitivity on windows.
178 size_t path_len = strlen(curpath);
179 size_t dll_len = strlen(dllpath);
181 //strip the dll path off
182 //:TODO: with path stuff - in Linux, \ can exist in a file path as a non-seperator!
183 for (size_t i=dll_len-1; i>0; i--)
185 if (dllpath[i] == '\\' || dllpath[i] == '/')
189 //save path by stripping off file name and ending terminator
196 //strip absolute path terminators if any!
197 if (curpath[path_len-1] == '/' || curpath[path_len-1] == '\\')
198 curpath[--path_len] = '\0';
200 //if the base path doesn't fit into the module path, something is wrong!
201 // ex: c:\games\srcds
203 if (path_len > dll_len)
205 Error("Could not detect GameDLL path! Metamod cannot load[1].");
209 //we are now in such a position that the two dir names SHOULD MATCH!
210 typedef int (*STRNCMP)(const char *str1, const char *str2, size_t n);
218 if ( ((cmp)(curpath, dllpath, path_len)) != 0 )
220 //:TODO: In this case, we should read /proc/self/maps and find srcds!
221 Error("Could not detect GameDLL path! Metamod cannot load[2].");
224 //this will skip past the dir and its separator char
225 char *ptr = &(dllpath[path_len+1]);
226 path_len = strlen(ptr);
227 for (size_t i=0; i<path_len; i++)
229 if (ptr[i] == '/' || ptr[i] == '\\')
233 Error("Could not detect GameDLL path! Metamod cannot load[3].");
242 //WE NOW HAVE A GUESS AT THE MOD DIR. OH MY GOD.
244 snprintf(temp_path, sizeof(temp_path)-1,
250 g_ModPath.assign(temp_path);
252 snprintf(temp_path, sizeof(temp_path)-1,
258 FILE *fp = fopen(temp_path, "rt");
261 Error("Unable to open gameinfo.txt! Metamod cannot load.");
265 char key[128], val[128];
267 const char *gameinfo = "|gameinfo_path|";
268 size_t gameinfo_len = strlen(gameinfo);
270 bool gamebin = false;
275 fgets(buffer, sizeof(buffer)-1, fp);
276 len = strlen(buffer);
277 if (buffer[len-1] == '\n')
278 buffer[--len] = '\0';
279 UTIL_TrimComments(buffer);
280 UTIL_TrimLeft(buffer);
281 UTIL_TrimRight(buffer);
282 if (stricmp(buffer, "SearchPaths") == 0)
286 UTIL_KeySplit(buffer, key, sizeof(key)-1, val, sizeof(val)-1);
287 if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
289 if (stricmp(key, "Game") == 0)
294 if (strncmp(val, gameinfo, gameinfo_len) == 0)
296 ptr = &(val[gameinfo_len]);
299 lptr = g_ModPath.c_str();
304 size_t ptr_len = strlen(ptr);
305 if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
306 ptr[--ptr_len] = '\0';
307 //no need to append "bin"
310 g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s/%s", lptr, ptr, SERVER_DLL);
312 g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
314 if (!UTIL_PathCmp(s_dllpath.c_str(), temp_path))
316 FILE *fp = fopen(temp_path, "rb");
319 //:TODO: Optimize this a bit!
320 SourceHook::List<GameDllInfo *>::iterator iter;
323 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
326 if (GetFileOfAddress(pCheck->factory, buffer, sizeof(buffer)-1))
328 if (UTIL_PathCmp(temp_path, buffer))
338 HINSTANCE gamedll = dlmount(temp_path);
341 CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
347 GameDllInfo *pInfo = new GameDllInfo;
349 pInfo->lib = gamedll;
350 pInfo->loaded = true;
351 pInfo->pGameDLL = NULL;
352 gamedll_list.push_back(pInfo);
359 if (!g_GameDll.loaded)
361 const char *str = "ServerGameDLL";
362 size_t len = strlen(str);
364 if (strncmp(iface, str, len) == 0)
366 //This is the interface we want! Right now we support versions 3 and 4.
367 int version = atoi(&(iface[len]));
368 if (version < MIN_GAMEDLL_VERSION || version > MAX_GAMEDLL_VERSION)
370 Error("GameDLL version %d is not supported by Metamod!", version);
373 SourceHook::List<GameDllInfo *>::iterator iter;
374 GameDllInfo *pInfo = NULL;
376 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
379 ptr = (pInfo->factory)(iface, ret);
382 //this is our gamedll. unload the others.
383 gamedll_list.erase(iter);
385 pInfo->pGameDLL = static_cast<IServerGameDLL *>(ptr);
391 if (g_GameDll.loaded)
401 //:TODO: .. something a bit more intelligent?
402 Error("Engine requested unknown interface before GameDLL was known!");
407 //if we got here, there's definitely a gamedll.
408 IFACE_MACRO(g_GameDll.factory, GameDLL);
411 void ClearGamedllList()
413 SourceHook::List<GameDllInfo *>::iterator iter;
416 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
423 gamedll_list.clear();
426 void DLLShutdown_handler()
429 g_PluginMngr.UnloadAll();
431 // Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly
432 g_SMConVarAccessor.MarkCommandsAsGameDLL();
433 g_SMConVarAccessor.UnregisterGameDLLCommands();
435 SH_CALL(dllExec, &IServerGameDLL::DLLShutdown)();
437 SH_RELEASE_CALLCLASS(dllExec);
440 g_SourceHook.CompleteShutdown();
442 if (g_GameDll.lib && g_GameDll.loaded)
443 dlclose(g_GameDll.lib);
444 memset(&g_GameDll, 0, sizeof(GameDllInfo));
446 RETURN_META(MRES_SUPERCEDE);
449 int LoadPluginsFromFile(const char *file)
452 int total = 0, skipped=0;
456 fp = fopen(file, "rt");
459 LogMessage("[META] Could not open plugins file %s\n", file);
463 char buffer[255], error[255], full_path[128];
464 const char *ptr, *ext;
469 fgets(buffer, sizeof(buffer)-1, fp);
470 length = strlen(buffer);
473 if (buffer[length-1] == '\n')
474 buffer[length-1] = '\0';
476 UTIL_TrimLeft(buffer);
477 UTIL_TrimRight(buffer);
479 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
481 //First find if it's an absolute path or not...
482 if (buffer[0] == '/' || strncmp(&(buffer[1]), ":\\", 2) == 0)
484 //If we're in an absolute path, ignore our normal heuristics
485 id = g_PluginMngr.Load(buffer, Pl_File, already, error, sizeof(error)-1);
486 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
488 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
496 //Attempt to find a file extension
497 ptr = UTIL_GetExtension(buffer);
498 //Add an extension if there's none there
501 #if defined WIN32 || defined _WIN32
509 //Format the new path
510 g_SmmAPI.PathFormat(full_path, sizeof(full_path)-1, "%s/%s%s", g_ModPath.c_str(), buffer, ext);
511 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error)-1);
512 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
514 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
527 LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
529 LogMessage("[META] Loaded %d plugins from file.", total);
535 //Wrapper function. This is called when the GameDLL thinks it's using
536 // the engine's real engineFactory.
537 void *EngineFactory(const char *iface, int *ret)
539 IFACE_MACRO(g_Engine.engineFactory, Engine);
542 //Wrapper function. This is called when the GameDLL thinks it's using
543 // the engine's real physicsFactory.
544 void *PhysicsFactory(const char *iface, int *ret)
546 IFACE_MACRO(g_Engine.physicsFactory, Physics);
549 //Wrapper function. This is called when the GameDLL thinks it's using
550 // the engine's real fileSystemFactory.
551 void *FileSystemFactory(const char *iface, int *ret)
553 IFACE_MACRO(g_Engine.fileSystemFactory, FileSystem);
556 void LogMessage(const char *msg, ...)
559 static char buffer[2048];
564 vsnprintf(buffer, sizeof(buffer)-5, msg, ap);
565 strcat(buffer, "\n");
568 if (!g_Engine.engine)
570 fprintf(stdout, "%s", buffer);
572 g_Engine.engine->LogPrint(buffer);
576 void LevelShutdown_handler(void)
581 g_SmmAPI.PathFormat(full_path, sizeof(full_path) - 1, "%s/%s", g_ModPath.c_str(), GetPluginsFile());
583 LoadPluginsFromFile(full_path);
585 bInFirstLevel = false;
588 ITER_EVENT(OnLevelShutdown, ());
590 RETURN_META(MRES_IGNORED);
593 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
595 if (!g_SmmAPI.CacheSuccessful())
597 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
598 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
601 #if (defined _DEBUG || defined DEBUG) && (defined OS_WIN32)
602 SetUnhandledExceptionFilter(NULL);
605 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
607 RETURN_META_VALUE(MRES_IGNORED, false);
610 #if defined __GNUC__ && (__GNUC__ == 3)
611 void * ::operator new(size_t size) {
612 return(calloc(1, size));
615 void * ::operator new[](size_t size) {
616 return(calloc(1, size));
619 void ::operator delete(void * ptr) {
624 void ::operator delete[](void * ptr) {