loader/gamedll.cpp
author Scott Ehlert <ds@alliedmods.net>
Sun Nov 15 22:52:54 2009 -0500 (2009-11-15)
changeset 681 a9f34c9f06e7
parent 637 b66489d8aedc
child 683 b507295429f9
permissions -rw-r--r--
Fixed crash on Linux when loading via gameinfo.txt on Left 4 Dead 2 (bug 4111, r=dvander).
     1 /**
     2  * vim: set ts=4 :
     3  * ======================================================
     4  * Metamod:Source
     5  * Copyright (C) 2004-2008 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  * Version: $Id$
    26  */
    27 
    28 #include <stdio.h>
    29 #include <ctype.h>
    30 #include <string.h>
    31 #include <assert.h>
    32 #include <stdlib.h>
    33 #include <stddef.h>
    34 #include "loader.h"
    35 #include <sh_memfuncinfo.h>
    36 #include <sh_memory.h>
    37 #include "utility.h"
    38 #include "gamedll.h"
    39 
    40 class IServerGameDLL;
    41 
    42 #define MAX_GAMEDLL_PATHS	10
    43 
    44 IGameDllBridge* gamedll_bridge = NULL;
    45 static int game_info_detected = 0;
    46 static const char *game_name = NULL;
    47 static char gamedll_paths[MAX_GAMEDLL_PATHS][PLATFORM_MAX_PATH];
    48 static void *gamedll_libs[MAX_GAMEDLL_PATHS];
    49 static unsigned int gamedll_path_count = 0;
    50 static void *gamedll_lib = NULL;
    51 static IServerGameDLL *gamedll_iface = NULL;
    52 static QueryValveInterface gamedll_qvi = NULL;
    53 static int gamedll_version = 0;
    54 static int isgd_shutdown_index = -1;
    55 
    56 #if defined _WIN32
    57 #define SERVER_NAME			"server.dll"
    58 #elif defined __linux__
    59 #define SERVER_NAME			"server" BINARY_SUFFIX
    60 #endif
    61 
    62 static bool
    63 mm_DetectGameInformation()
    64 {
    65 	char mm_path[PLATFORM_MAX_PATH];
    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 		MetamodBackend backend = mm_DetermineBackend(engineFactory, game_name);
   220 
   221 		char error[255];
   222 		if (backend == MMBackend_UNKNOWN)
   223 		{
   224 			mm_LogFatal("Could not detect engine version");
   225 		}
   226 		else
   227 		{
   228 			if (!mm_LoadMetamodLibrary(backend, error, sizeof(error)))
   229 			{
   230 				mm_LogFatal("Detected engine %d but could not load: %s", 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", 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 
   260 			strcpy(error, "Unknown error");
   261 			if (!gamedll_bridge->DLLInit_Pre(&info, error, sizeof(error)))
   262 			{
   263 				gamedll_bridge = NULL;
   264 				mm_UnloadMetamodLibrary();
   265 				mm_LogFatal("Unknown error loading Metamod for engine %d: %s", backend, error);	
   266 			}
   267 		}
   268 
   269 		/* Call the original */
   270 		bool result;
   271 		{
   272 			union
   273 			{
   274 				bool (VEmptyClass::*mfpnew)(QueryValveInterface engineFactory, 
   275 										 	QueryValveInterface physicsFactory, 
   276 										 	QueryValveInterface fileSystemFactory, 
   277 										 	void *pGlobals);
   278 #if defined _WIN32
   279 				void *addr;
   280 			} u;
   281 			u.addr = isgd_orig_init;
   282 #else
   283 				struct
   284 				{
   285 					void *addr;
   286 					intptr_t adjustor;
   287 				} s;
   288 			} u;
   289 			u.s.addr = isgd_orig_init;
   290 			u.s.adjustor = 0;
   291 #endif
   292 			result = (((VEmptyClass *)gamedll_iface)->*u.mfpnew)(engineFactory,
   293 																 physicsFactory,
   294 																 fileSystemFactory,
   295 																 pGlobals);
   296 		}
   297 
   298 		/**
   299 		 * :TODO: possible logic hole here, what happens if the gamedll REALLY returns false? 
   300 		 * I'm pretty sure we'll die horribly.
   301 		 */
   302 
   303 		if (!result)
   304 		{
   305 			gamedll_bridge->Unload();
   306 			mm_UnloadMetamodLibrary();
   307 			gamedll_bridge = NULL;
   308 		}
   309 		else if (gamedll_bridge != NULL)
   310 		{
   311 			gamedll_bridge->DLLInit_Post(&isgd_shutdown_index);
   312 			assert(isgd_shutdown_index != -1);
   313 			mm_PatchDllShutdown();
   314 		}
   315 
   316 		mm_PatchDllInit(false);
   317 
   318 		return result;
   319 	}
   320 
   321 	virtual void DLLShutdown()
   322 	{
   323 		gamedll_bridge->Unload();
   324 		gamedll_bridge = NULL;
   325 		mm_UnloadMetamodLibrary();
   326 
   327 		/* Call original function */
   328 		{
   329 			union
   330 			{
   331 				void (VEmptyClass::*mfpnew)();
   332 #if defined _WIN32
   333 				void *addr;
   334 			} u;
   335 			u.addr = isgd_orig_shutdown;
   336 #else
   337 				struct
   338 				{
   339 					void *addr;
   340 					intptr_t adjustor;
   341 				} s;
   342 			} u;
   343 			u.s.addr = isgd_orig_shutdown;
   344 			u.s.adjustor = 0;
   345 #endif
   346 			(((VEmptyClass *)gamedll_iface)->*u.mfpnew)();
   347 		}
   348 
   349 		mm_UnloadLibrary(gamedll_lib);
   350 		gamedll_lib = NULL;
   351 	}
   352 };
   353 
   354 static IServerGameDLL isgd_thunk;
   355 
   356 static void
   357 mm_PatchDllInit(bool patch)
   358 {
   359 	void **vtable_src;
   360 	void **vtable_dest;
   361 	SourceHook::MemFuncInfo mfp;
   362 
   363 	SourceHook::GetFuncInfo(&IServerGameDLL::DLLInit, mfp);
   364 
   365 	assert(mfp.isVirtual);
   366 	assert(mfp.thisptroffs == 0);
   367 	assert(mfp.vtbloffs == 0);
   368 
   369 	vtable_src = (void **)*(void **)&isgd_thunk;
   370 	vtable_dest = (void **)*(void **)gamedll_iface;
   371 
   372 	SourceHook::SetMemAccess(&vtable_dest[mfp.vtblindex],
   373 							 sizeof(void*),
   374 							 SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
   375 
   376 	if (patch)
   377 	{
   378 		assert(isgd_orig_init == NULL);
   379 		isgd_orig_init = vtable_dest[mfp.vtblindex];
   380 		vtable_dest[mfp.vtblindex] = vtable_src[mfp.vtblindex];
   381 	}
   382 	else
   383 	{
   384 		assert(isgd_orig_init != NULL);
   385 		vtable_dest[mfp.vtblindex] = isgd_orig_init;
   386 		isgd_orig_init = NULL;
   387 	}
   388 }
   389 
   390 static void
   391 mm_PatchDllShutdown()
   392 {
   393 	void **vtable_src;
   394 	void **vtable_dest;
   395 	SourceHook::MemFuncInfo mfp;
   396 
   397 	mfp.isVirtual = false;
   398 	SourceHook::GetFuncInfo(&IServerGameDLL::DLLShutdown, mfp);
   399 	assert(mfp.isVirtual);
   400 	assert(mfp.thisptroffs == 0);
   401 	assert(mfp.vtbloffs == 0);
   402 
   403 	vtable_src = (void **)*(void **)&isgd_thunk;
   404 	vtable_dest = (void **)*(void **)gamedll_iface;
   405 
   406 	isgd_orig_shutdown = vtable_dest[isgd_shutdown_index];
   407 	vtable_dest[isgd_shutdown_index] = vtable_src[mfp.vtblindex];
   408 }
   409 
   410 static void
   411 mm_PrepForGameLoad()
   412 {
   413 	mm_PatchDllInit(true);
   414 }
   415 
   416 void *
   417 mm_GameDllRequest(const char *name, int *ret)
   418 {
   419 	if (gamedll_lib != NULL && gamedll_bridge == NULL)
   420 	{
   421 		return gamedll_qvi(name, ret);
   422 	}
   423 
   424 	if (strncmp(name, "ServerGameDLL", 13) == 0)
   425 	{
   426 		if (!mm_DetectGameInformation())
   427 		{
   428 			if (ret != NULL)
   429 				*ret = 1;
   430 			return NULL;
   431 		}
   432 
   433 		void *lib;
   434 		char error[255];
   435 		void *ptr = NULL;
   436 		QueryValveInterface qvi;
   437 		for (unsigned int i = 0; i < gamedll_path_count; i++)
   438 		{
   439 			if (gamedll_libs[i] == NULL)
   440 			{
   441 				lib = mm_LoadLibrary(gamedll_paths[i], error, sizeof(error));
   442 				if (lib == NULL)
   443 					continue;
   444 				gamedll_libs[i] = lib;
   445 			}
   446 			lib = gamedll_libs[i];
   447 			qvi = (QueryValveInterface)mm_GetLibAddress(lib, "CreateInterface");
   448 			if (qvi == NULL)
   449 				continue;
   450 			ptr = qvi(name, ret);
   451 			if (ptr != NULL)
   452 			{
   453 				gamedll_libs[i] = NULL;
   454 				break;
   455 			}
   456 		}
   457 
   458 		if (ptr != NULL)
   459 		{
   460 			mm_FreeCachedLibraries();	
   461 			gamedll_lib = lib;
   462 			gamedll_iface = (IServerGameDLL *)ptr;
   463 			gamedll_qvi = qvi;
   464 			gamedll_version = atoi(&name[13]);
   465 			mm_PrepForGameLoad();
   466 
   467 			if (ret != NULL)
   468 				*ret = 0;
   469 			return ptr;
   470 		}
   471 	}
   472 	else if (game_info_detected == 0)
   473 	{
   474 		mm_LogFatal("Received interface request too early: %s", name);
   475 	}
   476 
   477 	if (ret != NULL)
   478 		*ret = 1;
   479 	return NULL;
   480 }
   481