loader/gamedll.cpp
author Asher Baker <asherkin@gmail.com>
Sun May 27 02:16:08 2012 +0100 (2012-05-27)
changeset 783 ba8cd35102b1
parent 705 a1001281dcb1
child 820 a05f33ba5ad4
permissions -rw-r--r--
Added META_NO_HL2SDK define to stop MM:S headers using the HL2SDK (bug 5079, r=dvander).
     1 /**
     2  * vim: set ts=4 sw=4 tw=99 noet :
     3  * ======================================================
     4  * Metamod:Source
     5  * Copyright (C) 2004-2009 AlliedModders LLC and authors.
     6  * All rights reserved.
     7  * ======================================================
     8  *
     9  * This software is provided 'as-is', without any express or implied warranty.
    10  * In no event will the authors be held liable for any damages arising from 
    11  * the use of this software.
    12  * 
    13  * Permission is granted to anyone to use this software for any purpose, 
    14  * including commercial applications, and to alter it and redistribute it 
    15  * freely, subject to the following restrictions:
    16  *
    17  * 1. The origin of this software must not be misrepresented; you must not 
    18  * claim that you wrote the original software. If you use this software in a 
    19  * product, an acknowledgment in the product documentation would be 
    20  * appreciated but is not required.
    21  * 2. Altered source versions must be plainly marked as such, and must not be
    22  * misrepresented as being the original software.
    23  * 3. This notice may not be removed or altered from any source distribution.
    24  */
    25 
    26 #include <stdio.h>
    27 #include <ctype.h>
    28 #include <string.h>
    29 #include <assert.h>
    30 #include <stdlib.h>
    31 #include <stddef.h>
    32 #include "loader.h"
    33 #include <sh_memfuncinfo.h>
    34 #include <sh_memory.h>
    35 #include "utility.h"
    36 #include "gamedll.h"
    37 
    38 class IServerGameDLL;
    39 
    40 #define MAX_GAMEDLL_PATHS	10
    41 
    42 IGameDllBridge* gamedll_bridge = NULL;
    43 static int game_info_detected = 0;
    44 static const char *game_name = NULL;
    45 static char gamedll_paths[MAX_GAMEDLL_PATHS][PLATFORM_MAX_PATH];
    46 static void *gamedll_libs[MAX_GAMEDLL_PATHS];
    47 static unsigned int gamedll_path_count = 0;
    48 static void *gamedll_lib = NULL;
    49 static IServerGameDLL *gamedll_iface = NULL;
    50 static QueryValveInterface gamedll_qvi = NULL;
    51 static int gamedll_version = 0;
    52 static int isgd_shutdown_index = -1;
    53 static char mm_path[PLATFORM_MAX_PATH];
    54 
    55 #if defined _WIN32
    56 #define SERVER_NAME			"server.dll"
    57 #elif defined __APPLE__
    58 #define SERVER_NAME			"server.dylib"
    59 #elif defined __linux__
    60 #define SERVER_NAME			"server" LIB_SUFFIX
    61 #endif
    62 
    63 static bool
    64 mm_DetectGameInformation()
    65 {
    66 	char game_path[PLATFORM_MAX_PATH];
    67 
    68 	if (game_info_detected)
    69 		return game_info_detected == 1 ? true : false;
    70 
    71 	game_info_detected = -1;
    72 
    73 	if ((game_name = mm_GetGameName()) == NULL)
    74 	{
    75 		return false;
    76 	}
    77 
    78 	if (!mm_GetFileOfAddress((void*)mm_DetectGameInformation, mm_path, sizeof(mm_path)))
    79 	{
    80 		mm_LogFatal("Could not locate Metamod loader library path");
    81 		return false;
    82 	}
    83 
    84 	if (!mm_ResolvePath(game_name, game_path, sizeof(game_path)))
    85 	{
    86 		mm_LogFatal("Could not resolve path: %s", game_name);
    87 		return false;
    88 	}
    89 
    90 	FILE *fp;
    91 	char gameinfo_path[PLATFORM_MAX_PATH];
    92 
    93 	mm_PathFormat(gameinfo_path, sizeof(gameinfo_path), "%s/gameinfo.txt", game_path);
    94 	if ((fp = fopen(gameinfo_path, "rt")) == NULL)
    95 	{
    96 		mm_LogFatal("Could not read file: %s", gameinfo_path);
    97 		return false;
    98 	}
    99 
   100 	char temp_path[PLATFORM_MAX_PATH];
   101 	char cur_path[PLATFORM_MAX_PATH];
   102 	getcwd(cur_path, sizeof(cur_path));
   103 
   104 	char *ptr;
   105 	const char *lptr;
   106 	bool search = false;
   107 	char buffer[255], key[128], val[128];
   108 	while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
   109 	{
   110 		mm_TrimComments(buffer);
   111 		mm_TrimLeft(buffer);
   112 		mm_TrimRight(buffer);
   113 
   114 		if (stricmp(buffer, "SearchPaths") == 0)
   115 			search = true;
   116 
   117 		if (!search)
   118 			continue;
   119 
   120 		mm_KeySplit(buffer, key, sizeof(key) - 1, val, sizeof(val) - 1);
   121 		if (stricmp(key, "Game") != 0 && stricmp(key, "GameBin") != 0)
   122 			continue;
   123 
   124 		if (strncmp(val, "|gameinfo_path|", sizeof("|gameinfo_path|") - 1) == 0)
   125 		{
   126 			ptr = &val[sizeof("|gameinfo_path|") - 1];
   127 			if (ptr[0] == '.')
   128 				ptr++;
   129 			lptr = game_path;
   130 		}
   131 		else
   132 		{
   133 			ptr = val;
   134 			lptr = cur_path;
   135 		}
   136 
   137 		if (stricmp(key, "GameBin") == 0)
   138 			mm_PathFormat(temp_path, sizeof(temp_path), "%s/%s/" SERVER_NAME, lptr, ptr);
   139 		else if (!ptr[0])
   140 			mm_PathFormat(temp_path, sizeof(temp_path), "%s/bin/" SERVER_NAME, lptr);
   141 		else
   142 			mm_PathFormat(temp_path, sizeof(temp_path), "%s/%s/bin/" SERVER_NAME, lptr, ptr);
   143 
   144 		if (mm_PathCmp(mm_path, temp_path))
   145 			continue;
   146 
   147 		FILE *exists = fopen(temp_path, "rb");
   148 		if (!exists)
   149 			continue;
   150 		fclose(exists);
   151 
   152 		/* exists is still non-NULL... use this as a flag */
   153 		for (unsigned int i = 0; i < gamedll_path_count; i++)
   154 		{
   155 			if (mm_PathCmp(gamedll_paths[i], temp_path))
   156 			{
   157 				exists = NULL;
   158 				break;
   159 			}
   160 		}
   161 
   162 		if (!exists)
   163 			continue;
   164 
   165 		mm_Format(gamedll_paths[gamedll_path_count],
   166 				  PLATFORM_MAX_PATH,
   167 				  "%s",
   168 				  temp_path);
   169 		gamedll_path_count++;
   170 
   171 		if (gamedll_path_count == MAX_GAMEDLL_PATHS)
   172 			break;
   173 	}
   174 	fclose(fp);
   175 
   176 	game_info_detected = 1;
   177 
   178 	if (gamedll_path_count == 0)
   179 	{
   180 		mm_LogFatal("Could not detect any valid game paths in gameinfo.txt");
   181 		return false;
   182 	}
   183 
   184 	return true;
   185 }
   186 
   187 static void
   188 mm_FreeCachedLibraries()
   189 {
   190 	for (unsigned int i = 0; i < gamedll_path_count; i++)
   191 	{
   192 		if (gamedll_libs[i] == NULL)
   193 			continue;
   194 		mm_UnloadLibrary(gamedll_libs[i]);
   195 	}
   196 }
   197 
   198 static void
   199 mm_PatchDllInit(bool patch);
   200 
   201 static void
   202 mm_PatchDllShutdown();
   203 
   204 static void *isgd_orig_init = NULL;
   205 static void *isgd_orig_shutdown = NULL;
   206 
   207 class VEmptyClass
   208 {
   209 };
   210 
   211 class IServerGameDLL
   212 {
   213 public:
   214 	virtual bool DLLInit(QueryValveInterface engineFactory, 
   215 						 QueryValveInterface physicsFactory, 
   216 						 QueryValveInterface fileSystemFactory, 
   217 						 void *pGlobals)
   218 	{
   219 		mm_backend = mm_DetermineBackend(engineFactory, game_name);
   220 
   221 		char error[255];
   222 		if (mm_backend == MMBackend_UNKNOWN)
   223 		{
   224 			mm_LogFatal("Could not detect engine version");
   225 		}
   226 		else
   227 		{
   228 			if (!mm_LoadMetamodLibrary(mm_backend, error, sizeof(error)))
   229 			{
   230 				mm_LogFatal("Detected engine %d but could not load: %s", mm_backend, error);
   231 			}
   232 			else
   233 			{
   234 				typedef IGameDllBridge *(*GetGameDllBridge)();
   235 				GetGameDllBridge get_bridge = (GetGameDllBridge)mm_GetProcAddress("GetGameDllBridge");
   236 				if (get_bridge == NULL)
   237 				{
   238 					mm_UnloadMetamodLibrary();
   239 					mm_LogFatal("Detected engine %d but could not find GetGameDllBridge callback", mm_backend);
   240 				}
   241 				else
   242 				{
   243 					gamedll_bridge = get_bridge();
   244 				}
   245 			}
   246 		}
   247 
   248 		if (gamedll_bridge)
   249 		{
   250 			gamedll_bridge_info info;
   251 
   252 			info.engineFactory = (QueryValveInterface)engineFactory;
   253 			info.physicsFactory = (QueryValveInterface)physicsFactory;
   254 			info.fsFactory = (QueryValveInterface)fileSystemFactory;
   255 			info.pGlobals = pGlobals;
   256 			info.dllVersion = gamedll_version;
   257 			info.isgd = gamedll_iface;
   258 			info.gsFactory = gamedll_qvi;
   259 			info.vsp_listener_path = mm_path;
   260 
   261 			strcpy(error, "Unknown error");
   262 			if (!gamedll_bridge->DLLInit_Pre(&info, error, sizeof(error)))
   263 			{
   264 				gamedll_bridge = NULL;
   265 				mm_UnloadMetamodLibrary();
   266 				mm_LogFatal("Unknown error loading Metamod for engine %d: %s", mm_backend, error);	
   267 			}
   268 		}
   269 
   270 		/* Call the original */
   271 		bool result;
   272 		{
   273 			union
   274 			{
   275 				bool (VEmptyClass::*mfpnew)(QueryValveInterface engineFactory, 
   276 										 	QueryValveInterface physicsFactory, 
   277 										 	QueryValveInterface fileSystemFactory, 
   278 										 	void *pGlobals);
   279 #if defined _WIN32
   280 				void *addr;
   281 			} u;
   282 			u.addr = isgd_orig_init;
   283 #else
   284 				struct
   285 				{
   286 					void *addr;
   287 					intptr_t adjustor;
   288 				} s;
   289 			} u;
   290 			u.s.addr = isgd_orig_init;
   291 			u.s.adjustor = 0;
   292 #endif
   293 			result = (((VEmptyClass *)gamedll_iface)->*u.mfpnew)(engineFactory,
   294 																 physicsFactory,
   295 																 fileSystemFactory,
   296 																 pGlobals);
   297 		}
   298 
   299 		/**
   300 		 * :TODO: possible logic hole here, what happens if the gamedll REALLY returns false? 
   301 		 * I'm pretty sure we'll die horribly.
   302 		 */
   303 
   304 		if (!result)
   305 		{
   306 			gamedll_bridge->Unload();
   307 			mm_UnloadMetamodLibrary();
   308 			gamedll_bridge = NULL;
   309 		}
   310 		else if (gamedll_bridge != NULL)
   311 		{
   312 			gamedll_bridge->DLLInit_Post(&isgd_shutdown_index);
   313 			assert(isgd_shutdown_index != -1);
   314 			mm_PatchDllShutdown();
   315 		}
   316 
   317 		mm_PatchDllInit(false);
   318 
   319 		return result;
   320 	}
   321 
   322 	virtual void DLLShutdown()
   323 	{
   324 		gamedll_bridge->Unload();
   325 		gamedll_bridge = NULL;
   326 		mm_UnloadMetamodLibrary();
   327 
   328 		/* Call original function */
   329 		{
   330 			union
   331 			{
   332 				void (VEmptyClass::*mfpnew)();
   333 #if defined _WIN32
   334 				void *addr;
   335 			} u;
   336 			u.addr = isgd_orig_shutdown;
   337 #else
   338 				struct
   339 				{
   340 					void *addr;
   341 					intptr_t adjustor;
   342 				} s;
   343 			} u;
   344 			u.s.addr = isgd_orig_shutdown;
   345 			u.s.adjustor = 0;
   346 #endif
   347 			(((VEmptyClass *)gamedll_iface)->*u.mfpnew)();
   348 		}
   349 
   350 		mm_UnloadLibrary(gamedll_lib);
   351 		gamedll_lib = NULL;
   352 	}
   353 };
   354 
   355 static IServerGameDLL isgd_thunk;
   356 
   357 static void
   358 mm_PatchDllInit(bool patch)
   359 {
   360 	void **vtable_src;
   361 	void **vtable_dest;
   362 	SourceHook::MemFuncInfo mfp;
   363 
   364 	SourceHook::GetFuncInfo(&IServerGameDLL::DLLInit, mfp);
   365 
   366 	assert(mfp.isVirtual);
   367 	assert(mfp.thisptroffs == 0);
   368 	assert(mfp.vtbloffs == 0);
   369 
   370 	vtable_src = (void **)*(void **)&isgd_thunk;
   371 	vtable_dest = (void **)*(void **)gamedll_iface;
   372 
   373 	SourceHook::SetMemAccess(&vtable_dest[mfp.vtblindex],
   374 							 sizeof(void*),
   375 							 SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
   376 
   377 	if (patch)
   378 	{
   379 		assert(isgd_orig_init == NULL);
   380 		isgd_orig_init = vtable_dest[mfp.vtblindex];
   381 		vtable_dest[mfp.vtblindex] = vtable_src[mfp.vtblindex];
   382 	}
   383 	else
   384 	{
   385 		assert(isgd_orig_init != NULL);
   386 		vtable_dest[mfp.vtblindex] = isgd_orig_init;
   387 		isgd_orig_init = NULL;
   388 	}
   389 }
   390 
   391 static void
   392 mm_PatchDllShutdown()
   393 {
   394 	void **vtable_src;
   395 	void **vtable_dest;
   396 	SourceHook::MemFuncInfo mfp;
   397 
   398 	mfp.isVirtual = false;
   399 	SourceHook::GetFuncInfo(&IServerGameDLL::DLLShutdown, mfp);
   400 	assert(mfp.isVirtual);
   401 	assert(mfp.thisptroffs == 0);
   402 	assert(mfp.vtbloffs == 0);
   403 
   404 	vtable_src = (void **)*(void **)&isgd_thunk;
   405 	vtable_dest = (void **)*(void **)gamedll_iface;
   406 
   407 	isgd_orig_shutdown = vtable_dest[isgd_shutdown_index];
   408 	vtable_dest[isgd_shutdown_index] = vtable_src[mfp.vtblindex];
   409 }
   410 
   411 static void
   412 mm_PrepForGameLoad()
   413 {
   414 	mm_PatchDllInit(true);
   415 }
   416 
   417 void *
   418 mm_GameDllRequest(const char *name, int *ret)
   419 {
   420 	if (gamedll_lib != NULL && gamedll_bridge == NULL)
   421 	{
   422 		return gamedll_qvi(name, ret);
   423 	}
   424 
   425 	if (strncmp(name, "ServerGameDLL", 13) == 0)
   426 	{
   427 		if (!mm_DetectGameInformation())
   428 		{
   429 			if (ret != NULL)
   430 				*ret = 1;
   431 			return NULL;
   432 		}
   433 
   434 		void *lib;
   435 		char error[255];
   436 		void *ptr = NULL;
   437 		QueryValveInterface qvi;
   438 		for (unsigned int i = 0; i < gamedll_path_count; i++)
   439 		{
   440 			if (gamedll_libs[i] == NULL)
   441 			{
   442 				lib = mm_LoadLibrary(gamedll_paths[i], error, sizeof(error));
   443 				if (lib == NULL)
   444 					continue;
   445 				gamedll_libs[i] = lib;
   446 			}
   447 			lib = gamedll_libs[i];
   448 			qvi = (QueryValveInterface)mm_GetLibAddress(lib, "CreateInterface");
   449 			if (qvi == NULL)
   450 				continue;
   451 			ptr = qvi(name, ret);
   452 			if (ptr != NULL)
   453 			{
   454 				gamedll_libs[i] = NULL;
   455 				break;
   456 			}
   457 		}
   458 
   459 		if (ptr != NULL)
   460 		{
   461 			mm_FreeCachedLibraries();	
   462 			gamedll_lib = lib;
   463 			gamedll_iface = (IServerGameDLL *)ptr;
   464 			gamedll_qvi = qvi;
   465 			gamedll_version = atoi(&name[13]);
   466 			mm_PrepForGameLoad();
   467 
   468 			if (ret != NULL)
   469 				*ret = 0;
   470 			return ptr;
   471 		}
   472 	}
   473 	else if (game_info_detected == 0)
   474 	{
   475 		mm_LogFatal("Received interface request too early: %s", name);
   476 	}
   477 
   478 	if (ret != NULL)
   479 		*ret = 1;
   480 	return NULL;
   481 }
   482