sourcemm/sourcemm.cpp
author David Anderson <dvander@alliedmods.net>
Sun Apr 17 03:37:50 2005 +0000 (2005-04-17)
changeset 12 9fd53562f68c
parent 9 01b8b7435e67
child 14 a3f323f6f91d
permissions -rw-r--r--
Fixed a few bugs in console commands
Added hooking of shutdown commands
Warning - Crashes on SH_ADD_HOOK_STATICFUNC?
     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 = 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
    38 
    39 ///////////////////////////////////
    40 // Main code for HL2 Interaction //
    41 ///////////////////////////////////
    42 
    43 void DLLShutdown_handler(void);
    44 SH_DECL_HOOK0_void(IServerGameDLL, DLLShutdown, SH_NOATTRIB, 0);
    45 
    46 //This is where the magic happens
    47 SMM_API void *CreateInterface(const char *name, int *ret)
    48 {
    49 	if (!g_GameDll.loaded)
    50 	{
    51 		//State of the Mod:
    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.
    56 
    57 		if (strcmp(name, INTERFACEVERSION_SERVERGAMEDLL) == 0)
    58 		{
    59 			//We're in.  Give the server our fake class as bait.
    60 			if (ret)
    61 				*ret = IFACE_OK;
    62 
    63 			g_TempGameDLL = new CServerGameDLL;
    64 
    65 			return static_cast<void *>(g_TempGameDLL);
    66 		} else if (strcmp(name, INTERFACEVERSION_SERVERGAMEENTS) == 0) {
    67 			if (ret)
    68 				*ret = IFACE_OK;
    69 
    70 			g_TempGameEnts = new CServerGameEnts;
    71 
    72 			return static_cast<void *>(g_TempGameEnts);
    73 		} else if (strcmp(name, INTERFACEVERSION_SERVERGAMECLIENTS) == 0) {
    74 			if (ret)
    75 				*ret = IFACE_OK;
    76 
    77 			g_TempGameClients = new CServerGameClients;
    78 
    79 			return static_cast<void *>(g_TempGameClients);
    80 		} else if (strcmp(name, INTERFACEVERSION_HLTVDIRECTOR) == 0) {
    81 			if (ret)
    82 				*ret = IFACE_OK;
    83 
    84 			g_TempDirector = new CHLTVDirector;
    85 
    86 			return static_cast<void *>(g_TempDirector);
    87 		} else {
    88 			if (ret)
    89 				*ret = IFACE_FAILED;
    90 
    91 			return NULL;
    92 		}
    93 	} else {
    94 		META_INTERFACE_MACRO(server, g_GameDll.factory);
    95 	}
    96 }
    97 
    98 bool CServerGameDLL::DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn fileSystemFactory, CGlobalVars *pGlobals)
    99 {
   100 	if (!g_GameDll.loaded)
   101 	{
   102 		//Initialize SourceHook
   103 		g_SHPtr = static_cast<SourceHook::ISourceHook *>(&g_SourceHook);
   104 
   105 		//The gamedll isn't loaded yet.  We need to find out where it's hiding.
   106 		IVEngineServer *ive = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
   107 		if (!ive)
   108 		{
   109 			Error("Metamod:Source could not load %s", INTERFACEVERSION_VENGINESERVER);
   110 			return false;
   111 		}
   112 		
   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);
   120 #else
   121 		snprintf(full_path, sizeof(full_path)-1, "%s/bin/server_i486.so", mod_path);
   122 #endif
   123 
   124 		g_BinPath.assign(full_path);
   125 
   126 		//See if the file even exists
   127 		FILE *fp = fopen(g_BinPath.c_str(), "r");
   128 		if (!fp)
   129 		{
   130 			Error("Metamod:Source could not read %s", g_BinPath.c_str());
   131 			return false;
   132 		}
   133 		fclose(fp);
   134 		fp = NULL;
   135 
   136 		//Load the DLL
   137 		g_GameDll.lib = dlmount(g_BinPath.c_str());
   138 		if (!g_GameDll.lib)
   139 		{
   140 			Error("Metamod:Source could not load GameDLL: %s", dlerror());
   141 			return false;
   142 		} else {
   143 			//Find its factory
   144 			g_GameDll.factory = (CreateInterfaceFn)(dlsym(g_GameDll.lib, "CreateInterface"));
   145 			if (!g_GameDll.factory)
   146 			{
   147 				Error("Metamod:Source could not find an entry point in GameDLL: %s", g_BinPath.c_str());
   148 				dlclose(g_GameDll.lib);
   149 				return false;
   150 			}
   151 
   152 			//Find the new IServerGameDLL pointer
   153 			IServerGameDLL *serverDll;
   154 			serverDll = (IServerGameDLL *)((g_GameDll.factory)(INTERFACEVERSION_SERVERGAMEDLL, NULL));
   155 			if (!serverDll)
   156 			{
   157 				Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_SERVERGAMEDLL, g_BinPath.c_str());
   158 				dlclose(g_GameDll.lib);
   159 				return false;
   160 			}
   161 
   162 			g_GameDll.serverGameDLL = serverDll;
   163 
   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);
   167 			if (!g_Engine.icvar)
   168 			{
   169 				Error("Metamod:Source could not find %s in engine!", VENGINE_CVAR_INTERFACE_VERSION);
   170 				dlclose(g_GameDll.lib);
   171 				return false;
   172 			}
   173 			g_Engine.fileSystemFactory = fileSystemFactory;
   174 			g_Engine.pGlobals = pGlobals;
   175 			g_Engine.physicsFactory = physicsFactory;
   176 			g_Engine.engine = ive;
   177 			
   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))
   185 			{
   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);
   189 				return false;
   190 			}
   191 
   192 			//Retrieve the pointers we'll need from the GameDLL
   193 			IServerGameEnts *serverEnts;
   194 			IServerGameClients *serverClients;
   195 			IHLTVDirector *serverHLTV;
   196 
   197 			serverEnts = (IServerGameEnts *)((g_GameDll.factory)(INTERFACEVERSION_SERVERGAMEENTS, NULL));
   198 			if (!serverEnts)
   199 			{
   200 				Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_SERVERGAMEENTS, g_BinPath.c_str());
   201 				dlclose(g_GameDll.lib);
   202 				return false;
   203 			}
   204 
   205 			serverClients = (IServerGameClients *)((g_GameDll.factory)(INTERFACEVERSION_SERVERGAMECLIENTS, NULL));
   206 			if (!serverClients)
   207 			{
   208 				Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_SERVERGAMECLIENTS, g_BinPath.c_str());
   209 				dlclose(g_GameDll.lib);
   210 				return false;
   211 			}
   212 
   213             serverHLTV = (IHLTVDirector *)((g_GameDll.factory)(INTERFACEVERSION_HLTVDIRECTOR, NULL));
   214 			if (!serverHLTV)
   215 			{
   216 				Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_HLTVDIRECTOR, g_BinPath.c_str());
   217 				dlclose(g_GameDll.lib);
   218 				return false;
   219 			}
   220 
   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));
   228 
   229 			SourceHook::SetMemAccess(vtableDst, sizeof(IServerGameDLL), SH_MEM_READ|SH_MEM_WRITE);
   230 			memcpy(vtableDst, vtableSrc, sizeof(IServerGameDLL));
   231 
   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));
   237 
   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));
   243 
   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));
   249 
   250 			//Everything's done.
   251 			g_GameDll.loaded = true;
   252 
   253 			//Initialize our shutdown hook
   254 			SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLShutdown, serverDll, DLLShutdown_handler, false);
   255 
   256 			//Initialize our console hooks
   257 			ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
   258             
   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");
   262 #else
   263 			snprintf(full_path, sizeof(full_path)-1, "%s/%s", g_ModPath.c_str(), "metaplugins.ini");
   264 #endif
   265 
   266 			LoadPluginsFromFile(full_path);
   267 
   268 			return true;
   269 		}
   270 	}
   271 
   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");
   275 
   276 	return false;
   277 }
   278 
   279 void DLLShutdown_handler(void)
   280 {
   281 	//It's time for us to shut down too!
   282 	g_PluginMngr.UnloadAll();
   283 
   284 	//Call the DLL...
   285 	g_GameDll.serverGameDLL->DLLShutdown();
   286 
   287 	//Unload the DLL forcefully
   288 	dlclose(g_GameDll.lib);
   289 	memset(&g_GameDll, 0, sizeof(GameDllInfo));
   290 
   291 	//For now, I'm not gonna bother freeing the memory allocated above.
   292 	//Why?
   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.
   297 
   298 	//DON'T CALL THE GAMEDLL! IT'S GONE!  pinin' for the fjords
   299 	RETURN_META(MRES_SUPERCEDE);
   300 }
   301 
   302 int LoadPluginsFromFile(const char *file)
   303 {
   304 	FILE *fp;
   305 	int total = 0, skipped=0;
   306 	PluginId id;
   307 	bool already;
   308 
   309 	fp = fopen(file, "rt");
   310 	if (!fp)
   311 	{
   312 		LogMessage("[META] Could not open plugins file %s\n", file);
   313 		return -1;
   314 	}
   315 
   316 	char buffer[255], error[255], full_path[128];
   317 	const char *ptr, *ext;
   318 	while (!feof(fp))
   319 	{
   320 		buffer[0] = '\0';
   321 		fgets(buffer, sizeof(buffer)-1, fp);
   322 		if (buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
   323 			continue;
   324 		//First find if it's an absolute path or not...
   325 		if (buffer[0] == '/' || strncmp(&(buffer[1]), ":\\", 2) == 0)
   326 		{
   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)
   330 			{
   331 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   332 			} else {
   333 				if (already)
   334 					skipped++;
   335 				else
   336 					total++;
   337 			}
   338 		} else {
   339 			//Attempt to find a file extension
   340 			ptr = UTIL_GetExtension(buffer);
   341 			//Add an extension if there's none there
   342 			if (!ptr)
   343 			{
   344 #if defined WIN32 || defined _WIN32
   345 				ext = ".dll";
   346 #else
   347 				ext = "_i486.so";
   348 #endif
   349 			} else {
   350 				ext = "";
   351 			}
   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);
   355 #else
   356 			snprintf(full_path, sizeof(full_path)-1, "%s/%s%s", g_ModPath.c_str(), buffer, ext);
   357 #endif
   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)
   360 			{
   361 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   362 			} else {
   363 				if (already)
   364 					skipped++;
   365 				else
   366 					total++;
   367 			}
   368 		}
   369 	}
   370 	fclose(fp);
   371 
   372 	if (skipped)
   373 	{
   374 		LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
   375 	} else {
   376 		LogMessage("[META] Loaded %d plugins from file.", total);
   377 	}
   378 	
   379 	return total;
   380 }
   381 
   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)
   385 {
   386 	META_INTERFACE_MACRO(engine, g_Engine.engineFactory);
   387 }
   388 
   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)
   392 {
   393 	META_INTERFACE_MACRO(physics, g_Engine.physicsFactory);
   394 }
   395 
   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)
   399 {
   400 	META_INTERFACE_MACRO(fileSystem, g_Engine.fileSystemFactory);
   401 }
   402 
   403 void LogMessage(const char *msg, ...)
   404 {
   405 	va_list ap;
   406 	static char buffer[2048];
   407 
   408 	buffer[0] = '\0';
   409 
   410 	va_start(ap, msg);
   411 	vsnprintf(buffer, sizeof(buffer)-5, msg, ap);
   412 	strcat(buffer, "\n");
   413 	va_end(ap);
   414 
   415 	g_Engine.engine->LogPrint(buffer);
   416 }