1 /* ======== SourceMM ========
2 * Copyright (C) 2004-2005 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 * ============================
14 #include "CServerGameDLL.h"
15 #include "CServerGameEnts.h"
16 #include "CServerGameClients.h"
17 #include "CHLTVDirector.h"
18 #include "concommands.h"
23 * @brief Implementation of main SourceMM GameDLL functionality
27 CServerGameDLL *g_TempGameDLL = NULL;
28 CServerGameEnts *g_TempGameEnts = NULL;
29 CServerGameClients *g_TempGameClients = NULL;
30 CHLTVDirector *g_TempDirector = NULL;
31 GameDllInfo g_GameDll = {false, NULL, NULL};
32 EngineInfo g_Engine = {NULL, NULL, NULL, NULL};
33 SourceHook::CSourceHookImpl g_SourceHook;
34 SourceHook::ISourceHook *g_SHPtr;
35 std::string g_ModPath;
36 std::string g_BinPath;
37 PluginId g_PLID = Pl_Console; //Technically, SourceMM is the "Console" plugin... :p
39 ///////////////////////////////////
40 // Main code for HL2 Interaction //
41 ///////////////////////////////////
43 void DLLShutdown_handler(void);
44 SH_DECL_HOOK0_void(IServerGameDLL, DLLShutdown, SH_NOATTRIB, 0);
46 //This is where the magic happens
47 SMM_API void *CreateInterface(const char *name, int *ret)
49 if (!g_GameDll.loaded)
52 // Currently, HL2 Engine has loaded Metamod:Source
53 // It is now asking it to get an interface. We don't have one,
54 // so we're gonna try to give it a fake one to get the information we need.
55 // Then we'll swap the vtables with the real one from the real gamedll.
57 if (strcmp(name, INTERFACEVERSION_SERVERGAMEDLL) == 0)
59 //We're in. Give the server our fake class as bait.
63 g_TempGameDLL = new CServerGameDLL;
65 return static_cast<void *>(g_TempGameDLL);
66 } else if (strcmp(name, INTERFACEVERSION_SERVERGAMEENTS) == 0) {
70 g_TempGameEnts = new CServerGameEnts;
72 return static_cast<void *>(g_TempGameEnts);
73 } else if (strcmp(name, INTERFACEVERSION_SERVERGAMECLIENTS) == 0) {
77 g_TempGameClients = new CServerGameClients;
79 return static_cast<void *>(g_TempGameClients);
80 } else if (strcmp(name, INTERFACEVERSION_HLTVDIRECTOR) == 0) {
84 g_TempDirector = new CHLTVDirector;
86 return static_cast<void *>(g_TempDirector);
94 META_INTERFACE_MACRO(server, g_GameDll.factory);
98 bool CServerGameDLL::DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn fileSystemFactory, CGlobalVars *pGlobals)
100 if (!g_GameDll.loaded)
102 //Initialize SourceHook
103 g_SHPtr = static_cast<SourceHook::ISourceHook *>(&g_SourceHook);
105 //The gamedll isn't loaded yet. We need to find out where it's hiding.
106 IVEngineServer *ive = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
109 Error("Metamod:Source could not load %s", INTERFACEVERSION_VENGINESERVER);
113 //Guess the file name
114 //We'll have better heurestics[sp?] later on
115 char mod_path[128], full_path[255];
116 ive->GetGameDir(mod_path, sizeof(mod_path)-1);
117 g_ModPath.assign(mod_path);
118 #if defined WIN32 || defined _WIN32
119 snprintf(full_path, sizeof(full_path)-1, "%s\\bin\\server.dll", mod_path);
121 snprintf(full_path, sizeof(full_path)-1, "%s/bin/server_i486.so", mod_path);
124 g_BinPath.assign(full_path);
126 //See if the file even exists
127 FILE *fp = fopen(g_BinPath.c_str(), "r");
130 Error("Metamod:Source could not read %s", g_BinPath.c_str());
137 g_GameDll.lib = dlmount(g_BinPath.c_str());
140 Error("Metamod:Source could not load GameDLL: %s", dlerror());
144 g_GameDll.factory = (CreateInterfaceFn)(dlsym(g_GameDll.lib, "CreateInterface"));
145 if (!g_GameDll.factory)
147 Error("Metamod:Source could not find an entry point in GameDLL: %s", g_BinPath.c_str());
148 dlclose(g_GameDll.lib);
152 //Find the new IServerGameDLL pointer
153 IServerGameDLL *serverDll;
154 serverDll = (IServerGameDLL *)((g_GameDll.factory)(INTERFACEVERSION_SERVERGAMEDLL, NULL));
157 Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_SERVERGAMEDLL, g_BinPath.c_str());
158 dlclose(g_GameDll.lib);
162 g_GameDll.serverGameDLL = serverDll;
164 //Set this information early in case our wrappers are called somehow
165 g_Engine.engineFactory = engineFactory;
166 g_Engine.icvar = (ICvar *)(g_Engine.engineFactory)(VENGINE_CVAR_INTERFACE_VERSION, NULL);
169 Error("Metamod:Source could not find %s in engine!", VENGINE_CVAR_INTERFACE_VERSION);
170 dlclose(g_GameDll.lib);
173 g_Engine.fileSystemFactory = fileSystemFactory;
174 g_Engine.pGlobals = pGlobals;
175 g_Engine.physicsFactory = physicsFactory;
176 g_Engine.engine = ive;
178 //Attempt to load the GameDLL
179 // Note that nothing will be intercepting yet.
180 // This is the one and only call that plugins have no chance of seeing.
181 // Likewise, you won't be able to trick the Server DLL into loading random things.
182 // Luckily, because of SourceHook, this really isn't a problem - you can change
183 // the virtual interfaces in anything it requests.
184 if (!serverDll->DLLInit(EngineFactory, PhysicsFactory, FileSystemFactory, pGlobals))
186 //For some reason, the GameDLL failed to load.
187 Error("Metamod:Source: GameDLL %s refused to load.", g_BinPath.c_str());
188 dlclose(g_GameDll.lib);
192 //Retrieve the pointers we'll need from the GameDLL
193 IServerGameEnts *serverEnts;
194 IServerGameClients *serverClients;
195 IHLTVDirector *serverHLTV;
197 serverEnts = (IServerGameEnts *)((g_GameDll.factory)(INTERFACEVERSION_SERVERGAMEENTS, NULL));
200 Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_SERVERGAMEENTS, g_BinPath.c_str());
201 dlclose(g_GameDll.lib);
205 serverClients = (IServerGameClients *)((g_GameDll.factory)(INTERFACEVERSION_SERVERGAMECLIENTS, NULL));
208 Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_SERVERGAMECLIENTS, g_BinPath.c_str());
209 dlclose(g_GameDll.lib);
213 serverHLTV = (IHLTVDirector *)((g_GameDll.factory)(INTERFACEVERSION_HLTVDIRECTOR, NULL));
216 Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_HLTVDIRECTOR, g_BinPath.c_str());
217 dlclose(g_GameDll.lib);
221 //The GameDLL has given the go - now we'll swap the vtables ( eww! )
222 //This ugly hack will patch the pointer we've given the engine
223 // so it will just be calling the real GameDLL instead.
224 // Unlike Metamod:HL1, this is the effect we want, rather than duplicating
225 // the entire class (because SourceHook doesn't do that).
226 void *vtableDst = ((void *)(g_TempGameDLL));
227 void *vtableSrc = ((void *)(serverDll));
229 SourceHook::SetMemAccess(vtableDst, sizeof(IServerGameDLL), SH_MEM_READ|SH_MEM_WRITE);
230 memcpy(vtableDst, vtableSrc, sizeof(IServerGameDLL));
232 //Now patch IServerGameEnts
233 vtableDst = ((void *)(g_TempGameEnts));
234 vtableSrc = ((void *)(serverEnts));
235 SourceHook::SetMemAccess(vtableDst, sizeof(IServerGameEnts), SH_MEM_READ|SH_MEM_WRITE);
236 memcpy(vtableDst, vtableSrc, sizeof(IServerGameEnts));
238 //Now patch IServerGameClients
239 vtableDst = ((void *)(g_TempGameClients));
240 vtableSrc = ((void *)(serverClients));
241 SourceHook::SetMemAccess(vtableDst, sizeof(IServerGameClients), SH_MEM_READ|SH_MEM_WRITE);
242 memcpy(vtableDst, vtableSrc, sizeof(IServerGameClients));
244 //Now patch IHLTVDirector
245 vtableDst = ((void *)(g_TempDirector));
246 vtableSrc = ((void *)(serverHLTV));
247 SourceHook::SetMemAccess(vtableDst, sizeof(IHLTVDirector), SH_MEM_READ|SH_MEM_WRITE);
248 memcpy(vtableDst, vtableSrc, sizeof(IHLTVDirector));
251 g_GameDll.loaded = true;
253 //Initialize our shutdown hook
254 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLShutdown, serverDll, DLLShutdown_handler, false);
256 //Initialize our console hooks
257 ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
259 //Now it's safe to load plugins.
260 #if defined WIN32 || defined _WIN32
261 snprintf(full_path, sizeof(full_path)-1, "%s\\%s", g_ModPath.c_str(), "metaplugins.ini");
263 snprintf(full_path, sizeof(full_path)-1, "%s/%s", g_ModPath.c_str(), "metaplugins.ini");
266 LoadPluginsFromFile(full_path);
272 //Somehow, the function got here. This should be impossible, as not only is it
273 // only called once, but the vtables should be overridden.
274 Error("Metamod:Source fatal error - IServerGameDLL::DLLInit() called inappropriately");
279 void DLLShutdown_handler(void)
281 //It's time for us to shut down too!
282 g_PluginMngr.UnloadAll();
285 g_GameDll.serverGameDLL->DLLShutdown();
287 //Unload the DLL forcefully
288 dlclose(g_GameDll.lib);
289 memset(&g_GameDll, 0, sizeof(GameDllInfo));
291 //For now, I'm not gonna bother freeing the memory allocated above.
293 // 1. We're exiting the application (I should hope!)
294 // 2. If we're not exiting, we just deallocated the gamedll, so we're about to crash out ANYWAY
295 // 3. We never saved the original vtable pointers, and we'd have to copy them back to get our destructors.
296 //Soooo... we'll just accept our fate here.
298 //DON'T CALL THE GAMEDLL! IT'S GONE! pinin' for the fjords
299 RETURN_META(MRES_SUPERCEDE);
302 int LoadPluginsFromFile(const char *file)
305 int total = 0, skipped=0;
309 fp = fopen(file, "rt");
312 LogMessage("[META] Could not open plugins file %s\n", file);
316 char buffer[255], error[255], full_path[128];
317 const char *ptr, *ext;
321 fgets(buffer, sizeof(buffer)-1, fp);
322 if (buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
324 //First find if it's an absolute path or not...
325 if (buffer[0] == '/' || strncmp(&(buffer[1]), ":\\", 2) == 0)
327 //If we're in an absolute path, ignore our normal heuristics
328 id = g_PluginMngr.Load(buffer, Pl_File, already, error, sizeof(error)-1);
329 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
331 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
339 //Attempt to find a file extension
340 ptr = UTIL_GetExtension(buffer);
341 //Add an extension if there's none there
344 #if defined WIN32 || defined _WIN32
352 //Format the new path
353 #if defined WIN32 || defined _WIN32
354 snprintf(full_path, sizeof(full_path)-1, "%s\\%s%s", g_ModPath.c_str(), buffer, ext);
356 snprintf(full_path, sizeof(full_path)-1, "%s/%s%s", g_ModPath.c_str(), buffer, ext);
358 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error)-1);
359 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
361 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
374 LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
376 LogMessage("[META] Loaded %d plugins from file.", total);
382 //Wrapper function. This is called when the GameDLL thinks it's using
383 // the engine's real engineFactory.
384 void *EngineFactory(const char *name, int *ret)
386 META_INTERFACE_MACRO(engine, g_Engine.engineFactory);
389 //Wrapper function. This is called when the GameDLL thinks it's using
390 // the engine's real physicsFactory.
391 void *PhysicsFactory(const char *name, int *ret)
393 META_INTERFACE_MACRO(physics, g_Engine.physicsFactory);
396 //Wrapper function. This is called when the GameDLL thinks it's using
397 // the engine's real fileSystemFactory.
398 void *FileSystemFactory(const char *name, int *ret)
400 META_INTERFACE_MACRO(fileSystem, g_Engine.fileSystemFactory);
403 void LogMessage(const char *msg, ...)
406 static char buffer[2048];
411 vsnprintf(buffer, sizeof(buffer)-5, msg, ap);
412 strcat(buffer, "\n");
415 g_Engine.engine->LogPrint(buffer);