sourcemm/sourcemm.cpp
author Pavol Marko <pavolmarko@gmail.com>
Fri May 06 09:44:41 2005 +0000 (2005-05-06)
changeset 63 ee7abd0da4dd
parent 52 948ae76c45b5
child 73 4b84e1b27390
permissions -rw-r--r--
Moved adding of FCVAR_GAMEDLL to Unload; added SourceHook iface/impl info to meta version
     1 /* ======== SourceMM ========
     2 * Copyright (C) 2004-2005 Metamod:Source Development Team
     3 * No warranties of any kind
     4 *
     5 * License: zlib/libpng
     6 *
     7 * Author(s): David "BAILOPAN" Anderson
     8 * Contributor(s): Scott "Damaged Soul" Ehlert
     9 *				: Pavol "PM OnoTo" Marko
    10 * ============================
    11 */
    12 
    13 #include <interface.h>
    14 #include <eiface.h>
    15 #include "CServerGameDLL.h"
    16 #include "CServerGameEnts.h"
    17 #include "CServerGameClients.h"
    18 #include "CHLTVDirector.h"
    19 #include "sourcemm.h"
    20 #include "concommands.h"
    21 #include "CSmmAPI.h"
    22 #include "util.h"
    23 
    24 /**
    25  * @brief Implementation of main SourceMM GameDLL functionality
    26  * @file sourcemm.cpp
    27  */
    28 
    29 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, 0);
    30 
    31 CServerGameDLL g_TempGameDLL;
    32 CServerGameEnts g_TempGameEnts;
    33 CServerGameClients g_TempGameClients;
    34 CHLTVDirector g_TempDirector;
    35 GameDllInfo g_GameDll = {false, NULL, NULL};
    36 EngineInfo g_Engine = {NULL, NULL, NULL, NULL};
    37 SourceHook::CSourceHookImpl g_SourceHook;
    38 SourceHook::ISourceHook *g_SHPtr;
    39 std::string g_ModPath;
    40 std::string g_BinPath;
    41 PluginId g_PLID = Pl_Console;		//Technically, SourceMM is the "Console" plugin... :p
    42 bool bInShutdown = false;
    43 bool bInFirstLevel = true;
    44 
    45 ///////////////////////////////////
    46 // Main code for HL2 Interaction //
    47 ///////////////////////////////////
    48 
    49 //This is where the magic happens
    50 SMM_API void *CreateInterface(const char *name, int *ret)
    51 {
    52 	if (!g_GameDll.loaded)
    53 	{
    54 		//State of the Mod:
    55 		// Currently, HL2 Engine has loaded Metamod:Source
    56 		// It is now asking it to get an interface.  We don't have one,
    57 		//  so we're gonna try to give it a fake one to get the information we need.
    58 		//  Then, the the interface will forward the calls to the original interface
    59 
    60 		if (strcmp(name, INTERFACEVERSION_SERVERGAMEDLL) == 0)
    61 		{
    62 			//We're in.  Give the server our fake class as bait.
    63 			if (ret)
    64 				*ret = IFACE_OK;
    65 			return static_cast<void *>(&g_TempGameDLL);
    66 		} else if (strcmp(name, INTERFACEVERSION_SERVERGAMEENTS) == 0) {
    67 			if (ret)
    68 				*ret = IFACE_OK;
    69 
    70 			return static_cast<void *>(&g_TempGameEnts);
    71 		} else if (strcmp(name, INTERFACEVERSION_SERVERGAMECLIENTS) == 0) {
    72 			if (ret)
    73 				*ret = IFACE_OK;
    74 
    75 			return static_cast<void *>(&g_TempGameClients);
    76 		} else if (strcmp(name, INTERFACEVERSION_HLTVDIRECTOR) == 0) {
    77 			if (ret)
    78 				*ret = IFACE_OK;
    79 
    80 			return static_cast<void *>(&g_TempDirector);
    81 		} else {
    82 			if (ret)
    83 				*ret = IFACE_FAILED;
    84 
    85 			return NULL;
    86 		}
    87 	} else {
    88 		META_INTERFACE_MACRO(server, g_GameDll.factory);
    89 	}
    90 }
    91 
    92 bool CServerGameDLL::DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn fileSystemFactory, CGlobalVars *pGlobals)
    93 {
    94 	if (m_pOrig)
    95 		return m_pOrig->DLLInit(engineFactory, physicsFactory, fileSystemFactory, pGlobals);
    96 
    97 	if (!g_GameDll.loaded)
    98 	{
    99 		//Initialize SourceHook
   100 		g_SHPtr = static_cast<SourceHook::ISourceHook *>(&g_SourceHook);
   101 
   102 		//The gamedll isn't loaded yet.  We need to find out where it's hiding.
   103 		IVEngineServer *ive = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
   104 		if (!ive)
   105 		{
   106 			Error("Metamod:Source could not load %s", INTERFACEVERSION_VENGINESERVER);
   107 			return false;
   108 		}
   109 		
   110 		//Guess the file name
   111 		//We'll have better heurestics[sp?] later on
   112 		char mod_path[128], full_path[255];
   113 		ive->GetGameDir(mod_path, sizeof(mod_path)-1);
   114 		g_ModPath.assign(mod_path);
   115 #if defined WIN32 || defined _WIN32
   116 		snprintf(full_path, sizeof(full_path)-1, "%s\\bin\\server.dll", mod_path);
   117 #else
   118 		snprintf(full_path, sizeof(full_path)-1, "%s/bin/server_i486.so", mod_path);
   119 #endif
   120 
   121 		g_BinPath.assign(full_path);
   122 
   123 		//See if the file even exists
   124 		FILE *fp = fopen(g_BinPath.c_str(), "r");
   125 		if (!fp)
   126 		{
   127 			Error("Metamod:Source could not read %s", g_BinPath.c_str());
   128 			return false;
   129 		}
   130 		fclose(fp);
   131 		fp = NULL;
   132 
   133 		//Load the DLL
   134 		g_GameDll.lib = dlmount(g_BinPath.c_str());
   135 		if (!g_GameDll.lib)
   136 		{
   137 			Error("Metamod:Source could not load GameDLL: %s", dlerror());
   138 			return false;
   139 		} else {
   140 			//Find its factory
   141 			g_GameDll.factory = (CreateInterfaceFn)(dlsym(g_GameDll.lib, "CreateInterface"));
   142 			if (!g_GameDll.factory)
   143 			{
   144 				Error("Metamod:Source could not find an entry point in GameDLL: %s", g_BinPath.c_str());
   145 				dlclose(g_GameDll.lib);
   146 				return false;
   147 			}
   148 
   149 			//Find the new IServerGameDLL pointer
   150 			IServerGameDLL *serverDll;
   151 			serverDll = (IServerGameDLL *)((g_GameDll.factory)(INTERFACEVERSION_SERVERGAMEDLL, NULL));
   152 			if (!serverDll)
   153 			{
   154 				Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_SERVERGAMEDLL, g_BinPath.c_str());
   155 				dlclose(g_GameDll.lib);
   156 				return false;
   157 			}
   158 
   159 			//Set this information early in case our wrappers are called somehow
   160 			g_Engine.engineFactory = engineFactory;
   161 			g_Engine.icvar = (ICvar *)(g_Engine.engineFactory)(VENGINE_CVAR_INTERFACE_VERSION, NULL);
   162 			if (!g_Engine.icvar)
   163 			{
   164 				Error("Metamod:Source could not find %s in engine!", VENGINE_CVAR_INTERFACE_VERSION);
   165 				dlclose(g_GameDll.lib);
   166 				return false;
   167 			}
   168 			g_Engine.fileSystemFactory = fileSystemFactory;
   169 			g_Engine.pGlobals = pGlobals;
   170 			g_Engine.physicsFactory = physicsFactory;
   171 			g_Engine.engine = ive;
   172 			
   173 			//Attempt to load the GameDLL
   174 			// Note that nothing will be intercepting yet.
   175 			// This is the one and only call that plugins have no chance of seeing.
   176 			// Likewise, you won't be able to trick the Server DLL into loading random things.
   177 			// Luckily, because of SourceHook, this really isn't a problem - you can change
   178 			//  the virtual interfaces in anything it requests.
   179 			if (!serverDll->DLLInit(EngineFactory, PhysicsFactory, FileSystemFactory, pGlobals))
   180 			{
   181 				//For some reason, the GameDLL failed to load. 
   182 				Error("Metamod:Source: GameDLL %s refused to load.", g_BinPath.c_str());
   183 				dlclose(g_GameDll.lib);
   184 				return false;
   185 			}
   186 
   187 			//Retrieve the pointers we'll need from the GameDLL
   188 			IServerGameEnts *serverEnts;
   189 			IServerGameClients *serverClients;
   190 			IHLTVDirector *serverHLTV;
   191 
   192 			serverEnts = (IServerGameEnts *)((g_GameDll.factory)(INTERFACEVERSION_SERVERGAMEENTS, NULL));
   193 			if (!serverEnts)
   194 			{
   195 				Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_SERVERGAMEENTS, g_BinPath.c_str());
   196 				dlclose(g_GameDll.lib);
   197 				return false;
   198 			}
   199 
   200 			serverClients = (IServerGameClients *)((g_GameDll.factory)(INTERFACEVERSION_SERVERGAMECLIENTS, NULL));
   201 			if (!serverClients)
   202 			{
   203 				Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_SERVERGAMECLIENTS, g_BinPath.c_str());
   204 				dlclose(g_GameDll.lib);
   205 				return false;
   206 			}
   207 
   208             serverHLTV = (IHLTVDirector *)((g_GameDll.factory)(INTERFACEVERSION_HLTVDIRECTOR, NULL));
   209 			if (!serverHLTV)
   210 			{
   211 				Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_HLTVDIRECTOR, g_BinPath.c_str());
   212 				dlclose(g_GameDll.lib);
   213 				return false;
   214 			}
   215 			
   216 			// Now tell the global temp classes that they can call the original functions
   217 			g_TempDirector.SetOrig(serverHLTV);
   218 			g_TempGameClients.SetOrig(serverClients);
   219 			g_TempGameEnts.SetOrig(serverEnts);
   220 			g_TempGameDLL.SetOrig(serverDll);
   221 
   222 			//Everything's done.
   223 			g_GameDll.loaded = true;
   224 
   225 			//Initialize our console hooks
   226 			ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
   227             
   228 			//Now it's safe to load plugins.
   229 #if defined WIN32 || defined _WIN32
   230 			snprintf(full_path, sizeof(full_path)-1, "%s\\addons\\metamod\\%s", g_ModPath.c_str(), "metaplugins.ini");
   231 #else
   232 			snprintf(full_path, sizeof(full_path)-1, "%s/addons/metamod/%s", g_ModPath.c_str(), "metaplugins.ini");
   233 #endif
   234 
   235 			LoadPluginsFromFile(full_path);
   236 
   237 			//All plugins are now loaded.
   238 			g_PluginMngr.SetAllLoaded();
   239 
   240 			//Like metamod, reload plugins at the end of the map.
   241 			//This is so plugins can hook everything on load, BUT, new plugins will be reloaded
   242 			// if the server is shut down (silly, but rare case).
   243 			bInFirstLevel = true;
   244 			SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, serverDll, LevelShutdown_handler, false);
   245 
   246 			return true;
   247 		}
   248 	}
   249 
   250 	//Somehow, the function got here.  This should be impossible.
   251 	Error("Metamod:Source fatal error - IServerGameDLL::DLLInit() called inappropriately");
   252 
   253 	return false;
   254 }
   255 
   256 // The engine uses the DLL even after it has call DLLShutdown, so we unload it
   257 // when it unloads us
   258 #if defined _WIN32
   259 	BOOL WINAPI DllMain(
   260 						HINSTANCE hinstDLL,
   261 						DWORD fdwReason,
   262 						LPVOID lpvReserved
   263 						)
   264 	{
   265 		if (fdwReason == DLL_PROCESS_DETACH)
   266 		{
   267 			if (g_GameDll.lib && g_GameDll.loaded)
   268 				dlclose(g_GameDll.lib);
   269 			memset(&g_GameDll, 0, sizeof(GameDllInfo));
   270 		}
   271 		return TRUE;
   272 	}
   273 #elif defined __linux__
   274 	void __attribute__ ((destructor)) app_fini(void)
   275 	{
   276 		if (g_GameDll.lib && g_GameDll.loaded)
   277 			dlclose(g_GameDll.lib);
   278 		memset(&g_GameDll, 0, sizeof(GameDllInfo));
   279 	}
   280 #endif
   281 
   282 void CServerGameDLL::DLLShutdown()
   283 {
   284     //Call the original function
   285 	m_pOrig->DLLShutdown();
   286 
   287 	//Unload plugins
   288 	g_PluginMngr.UnloadAll();
   289 
   290 	// Shutdown sourcehook now
   291 	g_SourceHook.CompleteShutdown();
   292 
   293 	// Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly
   294 	g_SMConVarAccessor.MarkCommandsAsGameDLL();
   295 }
   296 
   297 int LoadPluginsFromFile(const char *file)
   298 {
   299 	FILE *fp;
   300 	int total = 0, skipped=0;
   301 	PluginId id;
   302 	bool already;
   303 
   304 	fp = fopen(file, "rt");
   305 	if (!fp)
   306 	{
   307 		LogMessage("[META] Could not open plugins file %s\n", file);
   308 		return -1;
   309 	}
   310 
   311 	char buffer[255], error[255], full_path[128];
   312 	const char *ptr, *ext;
   313 	size_t length;
   314 	while (!feof(fp))
   315 	{
   316 		buffer[0] = '\0';
   317 		fgets(buffer, sizeof(buffer)-1, fp);
   318 		length = strlen(buffer);
   319 		if (!length)
   320 			continue;
   321 		if (buffer[length-1] == '\n')
   322 			buffer[length-1] = '\0';
   323 		if (buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
   324 			continue;
   325 		//First find if it's an absolute path or not...
   326 		if (buffer[0] == '/' || strncmp(&(buffer[1]), ":\\", 2) == 0)
   327 		{
   328 			//If we're in an absolute path, ignore our normal heuristics
   329 			id = g_PluginMngr.Load(buffer, Pl_File, already, error, sizeof(error)-1);
   330 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   331 			{
   332 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   333 			} else {
   334 				if (already)
   335 					skipped++;
   336 				else
   337 					total++;
   338 			}
   339 		} else {
   340 			//Attempt to find a file extension
   341 			ptr = UTIL_GetExtension(buffer);
   342 			//Add an extension if there's none there
   343 			if (!ptr)
   344 			{
   345 #if defined WIN32 || defined _WIN32
   346 				ext = ".dll";
   347 #else
   348 				ext = "_i486.so";
   349 #endif
   350 			} else {
   351 				ext = "";
   352 			}
   353 			//Format the new path
   354 #if defined WIN32 || defined _WIN32
   355 			snprintf(full_path, sizeof(full_path)-1, "%s\\%s%s", g_ModPath.c_str(), buffer, ext);
   356 #else
   357 			snprintf(full_path, sizeof(full_path)-1, "%s/%s%s", g_ModPath.c_str(), buffer, ext);
   358 #endif
   359 			id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error)-1);
   360 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   361 			{
   362 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   363 			} else {
   364 				if (already)
   365 					skipped++;
   366 				else
   367 					total++;
   368 			}
   369 		}
   370 	}
   371 	fclose(fp);
   372 
   373 	if (skipped)
   374 	{
   375 		LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
   376 	} else {
   377 		LogMessage("[META] Loaded %d plugins from file.", total);
   378 	}
   379 	
   380 	return total;
   381 }
   382 
   383 //Wrapper function.  This is called when the GameDLL thinks it's using
   384 // the engine's real engineFactory.
   385 void *EngineFactory(const char *name, int *ret)
   386 {
   387 	META_INTERFACE_MACRO(engine, g_Engine.engineFactory);
   388 }
   389 
   390 //Wrapper function.  This is called when the GameDLL thinks it's using
   391 // the engine's real physicsFactory.
   392 void *PhysicsFactory(const char *name, int *ret)
   393 {
   394 	META_INTERFACE_MACRO(physics, g_Engine.physicsFactory);
   395 }
   396 
   397 //Wrapper function.  This is called when the GameDLL thinks it's using
   398 // the engine's real fileSystemFactory.
   399 void *FileSystemFactory(const char *name, int *ret)
   400 {
   401 	META_INTERFACE_MACRO(fileSystem, g_Engine.fileSystemFactory);
   402 }
   403 
   404 void LogMessage(const char *msg, ...)
   405 {
   406 	va_list ap;
   407 	static char buffer[2048];
   408 
   409 	buffer[0] = '\0';
   410 
   411 	va_start(ap, msg);
   412 	vsnprintf(buffer, sizeof(buffer)-5, msg, ap);
   413 	strcat(buffer, "\n");
   414 	va_end(ap);
   415 
   416 	g_Engine.engine->LogPrint(buffer);
   417 }
   418 
   419 void LevelShutdown_handler(void)
   420 {
   421 	if (!bInFirstLevel)
   422 	{
   423 		char full_path[255];
   424 #if defined WIN32 || defined _WIN32
   425 		snprintf(full_path, sizeof(full_path)-1, "%s\\addons\\metamod\\%s", g_ModPath.c_str(), "metaplugins.ini");
   426 #else
   427 		snprintf(full_path, sizeof(full_path)-1, "%s/addons/metamod/%s", g_ModPath.c_str(), "metaplugins.ini");
   428 #endif
   429 		LoadPluginsFromFile(full_path);
   430 	} else {
   431 		bInFirstLevel = false;
   432 	}
   433 
   434 	RETURN_META(MRES_IGNORED);
   435 }