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