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