loader/gamedll.cpp
author David Anderson <dvander@alliedmods.net>
Wed Nov 26 00:19:30 2008 -0600 (2008-11-26)
changeset 608 30b546cc4e03
parent 606 764d63a80092
child 637 b66489d8aedc
permissions -rw-r--r--
Updated changelog, added license headers.
     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 #include "valve_commandline.h"
    40 
    41 #undef GetCommandLine
    42 
    43 class IServerGameDLL;
    44 typedef ICommandLine *(*GetCommandLine)();
    45 
    46 #define MAX_GAMEDLL_PATHS	10
    47 
    48 IGameDllBridge* gamedll_bridge = NULL;
    49 static int game_info_detected = 0;
    50 static char gamedll_paths[MAX_GAMEDLL_PATHS][PLATFORM_MAX_PATH];
    51 static void *gamedll_libs[MAX_GAMEDLL_PATHS];
    52 static unsigned int gamedll_path_count = 0;
    53 static void *gamedll_lib = NULL;
    54 static IServerGameDLL *gamedll_iface = NULL;
    55 static QueryValveInterface gamedll_qvi = NULL;
    56 static int gamedll_version = 0;
    57 static int isgd_shutdown_index = -1;
    58 
    59 #if defined _WIN32
    60 #define TIER0_NAME			"bin\\tier0.dll"
    61 #define VSTDLIB_NAME		"bin\\vstdlib.dll"
    62 #define SERVER_NAME			"server.dll"
    63 #elif defined __linux__
    64 #define TIER0_NAME			"bin/tier0_i486.so"
    65 #define VSTDLIB_NAME		"bin/vstdlib_i486.so"
    66 #define SERVER_NAME			"server_i486.so"
    67 #endif
    68 
    69 static bool
    70 mm_DetectGameInformation()
    71 {
    72 	void *lib;
    73 	char error[255];
    74 	GetCommandLine valve_cmdline;
    75 	char mm_path[PLATFORM_MAX_PATH];
    76 	char lib_path[PLATFORM_MAX_PATH];
    77 	char game_name[PLATFORM_MAX_PATH];
    78 	char game_path[PLATFORM_MAX_PATH];
    79 
    80 	if (game_info_detected)
    81 		return game_info_detected == 1 ? true : false;
    82 
    83 	game_info_detected = -1;
    84 
    85 	if (!mm_ResolvePath(TIER0_NAME, lib_path, sizeof(lib_path)))
    86 	{
    87 		mm_LogFatal("Could not find path for: " TIER0_NAME);
    88 		return false;
    89 	}
    90 
    91 	if ((lib = mm_LoadLibrary(lib_path, error, sizeof(error))) == NULL)
    92 	{
    93 		mm_LogFatal("Could not load %s: %s", lib_path, error);
    94 		return false;
    95 	}
    96 
    97 	valve_cmdline = (GetCommandLine)mm_GetLibAddress(lib, "CommandLine_Tier0");
    98 	if (valve_cmdline == NULL)
    99 	{
   100 		/* We probably have a Ship engine. */
   101 		mm_UnloadLibrary(lib);
   102 		if (!mm_ResolvePath(VSTDLIB_NAME, lib_path, sizeof(lib_path)))
   103 		{
   104 			mm_LogFatal("Could not find path for: " VSTDLIB_NAME);
   105 			return false;
   106 		}
   107 
   108 		if ((lib = mm_LoadLibrary(lib_path, error, sizeof(error))) == NULL)
   109 		{
   110 			mm_LogFatal("Could not load %s: %s", lib_path, error);
   111 			return false;
   112 		}
   113 
   114 		valve_cmdline = (GetCommandLine)mm_GetLibAddress(lib, "CommandLine");
   115 	}
   116 
   117 	mm_UnloadLibrary(lib);
   118 
   119 	if (valve_cmdline == NULL)
   120 	{
   121 		mm_LogFatal("Could not locate any command line functionality");
   122 		return false;
   123 	}
   124 
   125 	if (!mm_GetFileOfAddress((void*)mm_DetectGameInformation, mm_path, sizeof(mm_path)))
   126 	{
   127 		mm_LogFatal("Could not locate metamod loader library path");
   128 		return false;
   129 	}
   130 
   131 	mm_Format(game_name,
   132 			  sizeof(game_name),
   133 			  "%s",
   134 			  valve_cmdline()->ParmValue("-game", "hl2"));
   135 	if (!mm_ResolvePath(game_name, game_path, sizeof(game_path)))
   136 	{
   137 		mm_LogFatal("Could not resolve path: %s", game_name);
   138 		return false;
   139 	}
   140 
   141 	FILE *fp;
   142 	char gameinfo_path[PLATFORM_MAX_PATH];
   143 
   144 	mm_PathFormat(gameinfo_path, sizeof(gameinfo_path), "%s/gameinfo.txt", game_path);
   145 	if ((fp = fopen(gameinfo_path, "rt")) == NULL)
   146 	{
   147 		mm_LogFatal("Could not read file: %s", gameinfo_path);
   148 		return false;
   149 	}
   150 
   151 	char temp_path[PLATFORM_MAX_PATH];
   152 	char cur_path[PLATFORM_MAX_PATH];
   153 	getcwd(cur_path, sizeof(cur_path));
   154 
   155 	char *ptr;
   156 	const char *lptr;
   157 	bool search = false;
   158 	char buffer[255], key[128], val[128];
   159 	while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
   160 	{
   161 		mm_TrimComments(buffer);
   162 		mm_TrimLeft(buffer);
   163 		mm_TrimRight(buffer);
   164 
   165 		if (stricmp(buffer, "SearchPaths") == 0)
   166 			search = true;
   167 
   168 		if (!search)
   169 			continue;
   170 
   171 		mm_KeySplit(buffer, key, sizeof(key) - 1, val, sizeof(val) - 1);
   172 		if (stricmp(key, "Game") != 0 && stricmp(key, "GameBin") != 0)
   173 			continue;
   174 
   175 		if (strncmp(val, "|gameinfo_path|", sizeof("|gameinfo_path|") - 1) == 0)
   176 		{
   177 			ptr = &val[sizeof("|gameinfo_path|") - 1];
   178 			if (ptr[0] == '.')
   179 				ptr++;
   180 			lptr = game_path;
   181 		}
   182 		else
   183 		{
   184 			ptr = val;
   185 			lptr = cur_path;
   186 		}
   187 
   188 		if (stricmp(key, "GameBin") == 0)
   189 			mm_PathFormat(temp_path, sizeof(temp_path), "%s/%s/" SERVER_NAME, lptr, ptr);
   190 		else if (!ptr[0])
   191 			mm_PathFormat(temp_path, sizeof(temp_path), "%s/bin/" SERVER_NAME, lptr);
   192 		else
   193 			mm_PathFormat(temp_path, sizeof(temp_path), "%s/%s/bin/" SERVER_NAME, lptr, ptr);
   194 
   195 		if (mm_PathCmp(mm_path, temp_path))
   196 			continue;
   197 
   198 		FILE *exists = fopen(temp_path, "rb");
   199 		if (!exists)
   200 			continue;
   201 		fclose(exists);
   202 
   203 		/* exists is still non-NULL... use this as a flag */
   204 		for (unsigned int i = 0; i < gamedll_path_count; i++)
   205 		{
   206 			if (mm_PathCmp(gamedll_paths[i], temp_path))
   207 			{
   208 				exists = NULL;
   209 				break;
   210 			}
   211 		}
   212 
   213 		if (!exists)
   214 			continue;
   215 
   216 		mm_Format(gamedll_paths[gamedll_path_count],
   217 				  PLATFORM_MAX_PATH,
   218 				  "%s",
   219 				  temp_path);
   220 		gamedll_path_count++;
   221 
   222 		if (gamedll_path_count == MAX_GAMEDLL_PATHS)
   223 			break;
   224 	}
   225 	fclose(fp);
   226 
   227 	game_info_detected = 1;
   228 
   229 	return true;
   230 }
   231 
   232 static void
   233 mm_FreeCachedLibraries()
   234 {
   235 	for (unsigned int i = 0; i < gamedll_path_count; i++)
   236 	{
   237 		if (gamedll_libs[i] == NULL)
   238 			continue;
   239 		mm_UnloadLibrary(gamedll_libs[i]);
   240 	}
   241 }
   242 
   243 static void
   244 mm_PatchDllInit(bool patch);
   245 
   246 static void
   247 mm_PatchDllShutdown();
   248 
   249 static void *isgd_orig_init = NULL;
   250 static void *isgd_orig_shutdown = NULL;
   251 
   252 class VEmptyClass
   253 {
   254 };
   255 
   256 class IServerGameDLL
   257 {
   258 public:
   259 	virtual bool DLLInit(QueryValveInterface engineFactory, 
   260 						 QueryValveInterface physicsFactory, 
   261 						 QueryValveInterface fileSystemFactory, 
   262 						 void *pGlobals)
   263 	{
   264 		MetamodBackend backend = mm_DetermineBackend(engineFactory);
   265 
   266 		char error[255];
   267 		if (backend == MMBackend_UNKNOWN)
   268 		{
   269 			mm_LogFatal("Could not detect engine version");
   270 		}
   271 		else
   272 		{
   273 			if (!mm_LoadMetamodLibrary(backend, error, sizeof(error)))
   274 			{
   275 				mm_LogFatal("Detected engine %d but could not load: %s", backend, error);
   276 			}
   277 			else
   278 			{
   279 				typedef IGameDllBridge *(*GetGameDllBridge)();
   280 				GetGameDllBridge get_bridge = (GetGameDllBridge)mm_GetProcAddress("GetGameDllBridge");
   281 				if (get_bridge == NULL)
   282 				{
   283 					mm_UnloadMetamodLibrary();
   284 					mm_LogFatal("Detected engine %d but could not find GetGameDllBridge callback", backend);
   285 				}
   286 				else
   287 				{
   288 					gamedll_bridge = get_bridge();
   289 				}
   290 			}
   291 		}
   292 
   293 		if (gamedll_bridge)
   294 		{
   295 			gamedll_bridge_info info;
   296 
   297 			info.engineFactory = (QueryValveInterface)engineFactory;
   298 			info.physicsFactory = (QueryValveInterface)physicsFactory;
   299 			info.fsFactory = (QueryValveInterface)fileSystemFactory;
   300 			info.pGlobals = pGlobals;
   301 			info.dllVersion = gamedll_version;
   302 			info.isgd = gamedll_iface;
   303 			info.gsFactory = gamedll_qvi;
   304 
   305 			strcpy(error, "Unknown error");
   306 			if (!gamedll_bridge->DLLInit_Pre(&info, error, sizeof(error)))
   307 			{
   308 				gamedll_bridge = NULL;
   309 				mm_UnloadMetamodLibrary();
   310 				mm_LogFatal("Unknown error loading Metamod for engine %d: %s", backend, error);	
   311 			}
   312 		}
   313 
   314 		/* Call the original */
   315 		bool result;
   316 		{
   317 			union
   318 			{
   319 				bool (VEmptyClass::*mfpnew)(QueryValveInterface engineFactory, 
   320 										 	QueryValveInterface physicsFactory, 
   321 										 	QueryValveInterface fileSystemFactory, 
   322 										 	void *pGlobals);
   323 #if defined _WIN32
   324 				void *addr;
   325 			} u;
   326 			u.addr = isgd_orig_init;
   327 #else
   328 				struct
   329 				{
   330 					void *addr;
   331 					intptr_t adjustor;
   332 				} s;
   333 			} u;
   334 			u.s.addr = isgd_orig_init;
   335 			u.s.adjustor = 0;
   336 #endif
   337 			result = (((VEmptyClass *)gamedll_iface)->*u.mfpnew)(engineFactory,
   338 																 physicsFactory,
   339 																 fileSystemFactory,
   340 																 pGlobals);
   341 		}
   342 
   343 		/**
   344 		 * :TODO: possible logic hole here, what happens if the gamedll REALLY returns false? 
   345 		 * I'm pretty sure we'll die horribly.
   346 		 */
   347 
   348 		if (!result)
   349 		{
   350 			gamedll_bridge->Unload();
   351 			mm_UnloadMetamodLibrary();
   352 			gamedll_bridge = NULL;
   353 		}
   354 		else if (gamedll_bridge != NULL)
   355 		{
   356 			gamedll_bridge->DLLInit_Post(&isgd_shutdown_index);
   357 			assert(isgd_shutdown_index != -1);
   358 			mm_PatchDllShutdown();
   359 		}
   360 
   361 		mm_PatchDllInit(false);
   362 
   363 		return result;
   364 	}
   365 
   366 	virtual void DLLShutdown()
   367 	{
   368 		gamedll_bridge->Unload();
   369 		gamedll_bridge = NULL;
   370 		mm_UnloadMetamodLibrary();
   371 
   372 		/* Call original function */
   373 		{
   374 			union
   375 			{
   376 				void (VEmptyClass::*mfpnew)();
   377 #if defined _WIN32
   378 				void *addr;
   379 			} u;
   380 			u.addr = isgd_orig_shutdown;
   381 #else
   382 				struct
   383 				{
   384 					void *addr;
   385 					intptr_t adjustor;
   386 				} s;
   387 			} u;
   388 			u.s.addr = isgd_orig_shutdown;
   389 			u.s.adjustor = 0;
   390 #endif
   391 			(((VEmptyClass *)gamedll_iface)->*u.mfpnew)();
   392 		}
   393 
   394 		mm_UnloadLibrary(gamedll_lib);
   395 		gamedll_lib = NULL;
   396 	}
   397 };
   398 
   399 static IServerGameDLL isgd_thunk;
   400 
   401 static void
   402 mm_PatchDllInit(bool patch)
   403 {
   404 	void **vtable_src;
   405 	void **vtable_dest;
   406 	SourceHook::MemFuncInfo mfp;
   407 
   408 	SourceHook::GetFuncInfo(&IServerGameDLL::DLLInit, mfp);
   409 
   410 	assert(mfp.isVirtual);
   411 	assert(mfp.thisptroffs == 0);
   412 	assert(mfp.vtbloffs == 0);
   413 
   414 	vtable_src = (void **)*(void **)&isgd_thunk;
   415 	vtable_dest = (void **)*(void **)gamedll_iface;
   416 
   417 	SourceHook::SetMemAccess(&vtable_dest[mfp.vtblindex],
   418 							 sizeof(void*),
   419 							 SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
   420 
   421 	if (patch)
   422 	{
   423 		assert(isgd_orig_init == NULL);
   424 		isgd_orig_init = vtable_dest[mfp.vtblindex];
   425 		vtable_dest[mfp.vtblindex] = vtable_src[mfp.vtblindex];
   426 	}
   427 	else
   428 	{
   429 		assert(isgd_orig_init != NULL);
   430 		vtable_dest[mfp.vtblindex] = isgd_orig_init;
   431 		isgd_orig_init = NULL;
   432 	}
   433 }
   434 
   435 static void
   436 mm_PatchDllShutdown()
   437 {
   438 	void **vtable_src;
   439 	void **vtable_dest;
   440 	SourceHook::MemFuncInfo mfp;
   441 
   442 	mfp.isVirtual = false;
   443 	SourceHook::GetFuncInfo(&IServerGameDLL::DLLShutdown, mfp);
   444 	assert(mfp.isVirtual);
   445 	assert(mfp.thisptroffs == 0);
   446 	assert(mfp.vtbloffs == 0);
   447 
   448 	vtable_src = (void **)*(void **)&isgd_thunk;
   449 	vtable_dest = (void **)*(void **)gamedll_iface;
   450 
   451 	isgd_orig_shutdown = vtable_dest[isgd_shutdown_index];
   452 	vtable_dest[isgd_shutdown_index] = vtable_src[mfp.vtblindex];
   453 }
   454 
   455 static void
   456 mm_PrepForGameLoad()
   457 {
   458 	mm_PatchDllInit(true);
   459 }
   460 
   461 void *
   462 mm_GameDllRequest(const char *name, int *ret)
   463 {
   464 	if (gamedll_lib != NULL && gamedll_bridge == NULL)
   465 	{
   466 		return gamedll_qvi(name, ret);
   467 	}
   468 
   469 	if (strncmp(name, "ServerGameDLL", 13) == 0)
   470 	{
   471 		if (!mm_DetectGameInformation())
   472 		{
   473 			if (ret != NULL)
   474 				*ret = 1;
   475 			return NULL;
   476 		}
   477 
   478 		void *lib;
   479 		char error[255];
   480 		void *ptr = NULL;
   481 		QueryValveInterface qvi;
   482 		for (unsigned int i = 0; i < gamedll_path_count; i++)
   483 		{
   484 			if (gamedll_libs[i] == NULL)
   485 			{
   486 				lib = mm_LoadLibrary(gamedll_paths[i], error, sizeof(error));
   487 				if (lib == NULL)
   488 					continue;
   489 				gamedll_libs[i] = lib;
   490 			}
   491 			lib = gamedll_libs[i];
   492 			qvi = (QueryValveInterface)mm_GetLibAddress(lib, "CreateInterface");
   493 			if (qvi == NULL)
   494 				continue;
   495 			ptr = qvi(name, ret);
   496 			if (ptr != NULL)
   497 			{
   498 				gamedll_libs[i] = NULL;
   499 				break;
   500 			}
   501 		}
   502 
   503 		if (ptr != NULL)
   504 		{
   505 			mm_FreeCachedLibraries();	
   506 			gamedll_lib = lib;
   507 			gamedll_iface = (IServerGameDLL *)ptr;
   508 			gamedll_qvi = qvi;
   509 			gamedll_version = atoi(&name[13]);
   510 			mm_PrepForGameLoad();
   511 
   512 			if (ret != NULL)
   513 				*ret = 0;
   514 			return ptr;
   515 		}
   516 	}
   517 	else if (game_info_detected == 0)
   518 	{
   519 		mm_LogFatal("Received interface request too early: %s", name);
   520 	}
   521 
   522 	if (ret != NULL)
   523 		*ret = 1;
   524 	return NULL;
   525 }
   526