loader/gamedll.cpp
author Scott Ehlert <ds@alliedmods.net>
Wed Feb 18 01:38:23 2009 -0600 (2009-02-18)
changeset 637 b66489d8aedc
parent 608 30b546cc4e03
child 681 a9f34c9f06e7
permissions -rw-r--r--
Added support for Dark Messiah engine and game. (no bug, r=me).

The development of this feature would not be possible without the support of the following people from the game's community:
Dylan Riggs, Carl Pettengill, Ed Moreland, and Christian.
     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_i486.so"
    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 	return true;
   179 }
   180 
   181 static void
   182 mm_FreeCachedLibraries()
   183 {
   184 	for (unsigned int i = 0; i < gamedll_path_count; i++)
   185 	{
   186 		if (gamedll_libs[i] == NULL)
   187 			continue;
   188 		mm_UnloadLibrary(gamedll_libs[i]);
   189 	}
   190 }
   191 
   192 static void
   193 mm_PatchDllInit(bool patch);
   194 
   195 static void
   196 mm_PatchDllShutdown();
   197 
   198 static void *isgd_orig_init = NULL;
   199 static void *isgd_orig_shutdown = NULL;
   200 
   201 class VEmptyClass
   202 {
   203 };
   204 
   205 class IServerGameDLL
   206 {
   207 public:
   208 	virtual bool DLLInit(QueryValveInterface engineFactory, 
   209 						 QueryValveInterface physicsFactory, 
   210 						 QueryValveInterface fileSystemFactory, 
   211 						 void *pGlobals)
   212 	{
   213 		MetamodBackend backend = mm_DetermineBackend(engineFactory, game_name);
   214 
   215 		char error[255];
   216 		if (backend == MMBackend_UNKNOWN)
   217 		{
   218 			mm_LogFatal("Could not detect engine version");
   219 		}
   220 		else
   221 		{
   222 			if (!mm_LoadMetamodLibrary(backend, error, sizeof(error)))
   223 			{
   224 				mm_LogFatal("Detected engine %d but could not load: %s", backend, error);
   225 			}
   226 			else
   227 			{
   228 				typedef IGameDllBridge *(*GetGameDllBridge)();
   229 				GetGameDllBridge get_bridge = (GetGameDllBridge)mm_GetProcAddress("GetGameDllBridge");
   230 				if (get_bridge == NULL)
   231 				{
   232 					mm_UnloadMetamodLibrary();
   233 					mm_LogFatal("Detected engine %d but could not find GetGameDllBridge callback", backend);
   234 				}
   235 				else
   236 				{
   237 					gamedll_bridge = get_bridge();
   238 				}
   239 			}
   240 		}
   241 
   242 		if (gamedll_bridge)
   243 		{
   244 			gamedll_bridge_info info;
   245 
   246 			info.engineFactory = (QueryValveInterface)engineFactory;
   247 			info.physicsFactory = (QueryValveInterface)physicsFactory;
   248 			info.fsFactory = (QueryValveInterface)fileSystemFactory;
   249 			info.pGlobals = pGlobals;
   250 			info.dllVersion = gamedll_version;
   251 			info.isgd = gamedll_iface;
   252 			info.gsFactory = gamedll_qvi;
   253 
   254 			strcpy(error, "Unknown error");
   255 			if (!gamedll_bridge->DLLInit_Pre(&info, error, sizeof(error)))
   256 			{
   257 				gamedll_bridge = NULL;
   258 				mm_UnloadMetamodLibrary();
   259 				mm_LogFatal("Unknown error loading Metamod for engine %d: %s", backend, error);	
   260 			}
   261 		}
   262 
   263 		/* Call the original */
   264 		bool result;
   265 		{
   266 			union
   267 			{
   268 				bool (VEmptyClass::*mfpnew)(QueryValveInterface engineFactory, 
   269 										 	QueryValveInterface physicsFactory, 
   270 										 	QueryValveInterface fileSystemFactory, 
   271 										 	void *pGlobals);
   272 #if defined _WIN32
   273 				void *addr;
   274 			} u;
   275 			u.addr = isgd_orig_init;
   276 #else
   277 				struct
   278 				{
   279 					void *addr;
   280 					intptr_t adjustor;
   281 				} s;
   282 			} u;
   283 			u.s.addr = isgd_orig_init;
   284 			u.s.adjustor = 0;
   285 #endif
   286 			result = (((VEmptyClass *)gamedll_iface)->*u.mfpnew)(engineFactory,
   287 																 physicsFactory,
   288 																 fileSystemFactory,
   289 																 pGlobals);
   290 		}
   291 
   292 		/**
   293 		 * :TODO: possible logic hole here, what happens if the gamedll REALLY returns false? 
   294 		 * I'm pretty sure we'll die horribly.
   295 		 */
   296 
   297 		if (!result)
   298 		{
   299 			gamedll_bridge->Unload();
   300 			mm_UnloadMetamodLibrary();
   301 			gamedll_bridge = NULL;
   302 		}
   303 		else if (gamedll_bridge != NULL)
   304 		{
   305 			gamedll_bridge->DLLInit_Post(&isgd_shutdown_index);
   306 			assert(isgd_shutdown_index != -1);
   307 			mm_PatchDllShutdown();
   308 		}
   309 
   310 		mm_PatchDllInit(false);
   311 
   312 		return result;
   313 	}
   314 
   315 	virtual void DLLShutdown()
   316 	{
   317 		gamedll_bridge->Unload();
   318 		gamedll_bridge = NULL;
   319 		mm_UnloadMetamodLibrary();
   320 
   321 		/* Call original function */
   322 		{
   323 			union
   324 			{
   325 				void (VEmptyClass::*mfpnew)();
   326 #if defined _WIN32
   327 				void *addr;
   328 			} u;
   329 			u.addr = isgd_orig_shutdown;
   330 #else
   331 				struct
   332 				{
   333 					void *addr;
   334 					intptr_t adjustor;
   335 				} s;
   336 			} u;
   337 			u.s.addr = isgd_orig_shutdown;
   338 			u.s.adjustor = 0;
   339 #endif
   340 			(((VEmptyClass *)gamedll_iface)->*u.mfpnew)();
   341 		}
   342 
   343 		mm_UnloadLibrary(gamedll_lib);
   344 		gamedll_lib = NULL;
   345 	}
   346 };
   347 
   348 static IServerGameDLL isgd_thunk;
   349 
   350 static void
   351 mm_PatchDllInit(bool patch)
   352 {
   353 	void **vtable_src;
   354 	void **vtable_dest;
   355 	SourceHook::MemFuncInfo mfp;
   356 
   357 	SourceHook::GetFuncInfo(&IServerGameDLL::DLLInit, mfp);
   358 
   359 	assert(mfp.isVirtual);
   360 	assert(mfp.thisptroffs == 0);
   361 	assert(mfp.vtbloffs == 0);
   362 
   363 	vtable_src = (void **)*(void **)&isgd_thunk;
   364 	vtable_dest = (void **)*(void **)gamedll_iface;
   365 
   366 	SourceHook::SetMemAccess(&vtable_dest[mfp.vtblindex],
   367 							 sizeof(void*),
   368 							 SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
   369 
   370 	if (patch)
   371 	{
   372 		assert(isgd_orig_init == NULL);
   373 		isgd_orig_init = vtable_dest[mfp.vtblindex];
   374 		vtable_dest[mfp.vtblindex] = vtable_src[mfp.vtblindex];
   375 	}
   376 	else
   377 	{
   378 		assert(isgd_orig_init != NULL);
   379 		vtable_dest[mfp.vtblindex] = isgd_orig_init;
   380 		isgd_orig_init = NULL;
   381 	}
   382 }
   383 
   384 static void
   385 mm_PatchDllShutdown()
   386 {
   387 	void **vtable_src;
   388 	void **vtable_dest;
   389 	SourceHook::MemFuncInfo mfp;
   390 
   391 	mfp.isVirtual = false;
   392 	SourceHook::GetFuncInfo(&IServerGameDLL::DLLShutdown, mfp);
   393 	assert(mfp.isVirtual);
   394 	assert(mfp.thisptroffs == 0);
   395 	assert(mfp.vtbloffs == 0);
   396 
   397 	vtable_src = (void **)*(void **)&isgd_thunk;
   398 	vtable_dest = (void **)*(void **)gamedll_iface;
   399 
   400 	isgd_orig_shutdown = vtable_dest[isgd_shutdown_index];
   401 	vtable_dest[isgd_shutdown_index] = vtable_src[mfp.vtblindex];
   402 }
   403 
   404 static void
   405 mm_PrepForGameLoad()
   406 {
   407 	mm_PatchDllInit(true);
   408 }
   409 
   410 void *
   411 mm_GameDllRequest(const char *name, int *ret)
   412 {
   413 	if (gamedll_lib != NULL && gamedll_bridge == NULL)
   414 	{
   415 		return gamedll_qvi(name, ret);
   416 	}
   417 
   418 	if (strncmp(name, "ServerGameDLL", 13) == 0)
   419 	{
   420 		if (!mm_DetectGameInformation())
   421 		{
   422 			if (ret != NULL)
   423 				*ret = 1;
   424 			return NULL;
   425 		}
   426 
   427 		void *lib;
   428 		char error[255];
   429 		void *ptr = NULL;
   430 		QueryValveInterface qvi;
   431 		for (unsigned int i = 0; i < gamedll_path_count; i++)
   432 		{
   433 			if (gamedll_libs[i] == NULL)
   434 			{
   435 				lib = mm_LoadLibrary(gamedll_paths[i], error, sizeof(error));
   436 				if (lib == NULL)
   437 					continue;
   438 				gamedll_libs[i] = lib;
   439 			}
   440 			lib = gamedll_libs[i];
   441 			qvi = (QueryValveInterface)mm_GetLibAddress(lib, "CreateInterface");
   442 			if (qvi == NULL)
   443 				continue;
   444 			ptr = qvi(name, ret);
   445 			if (ptr != NULL)
   446 			{
   447 				gamedll_libs[i] = NULL;
   448 				break;
   449 			}
   450 		}
   451 
   452 		if (ptr != NULL)
   453 		{
   454 			mm_FreeCachedLibraries();	
   455 			gamedll_lib = lib;
   456 			gamedll_iface = (IServerGameDLL *)ptr;
   457 			gamedll_qvi = qvi;
   458 			gamedll_version = atoi(&name[13]);
   459 			mm_PrepForGameLoad();
   460 
   461 			if (ret != NULL)
   462 				*ret = 0;
   463 			return ptr;
   464 		}
   465 	}
   466 	else if (game_info_detected == 0)
   467 	{
   468 		mm_LogFatal("Received interface request too early: %s", name);
   469 	}
   470 
   471 	if (ret != NULL)
   472 		*ret = 1;
   473 	return NULL;
   474 }
   475