loader/gamedll.cpp
author Nicholas Hastings <skamonkey@gmail.com>
Wed May 21 17:26:09 2014 -0400 (2014-05-21)
changeset 917 95639ee45d3d
parent 896 0f4ca0bedc67
permissions -rw-r--r--
Trigger build for hl2sdk-l4d changes.
     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 char game_name[128];
    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 	mm_GetGameName(game_name, sizeof(game_name));
    74 
    75 	if (!mm_GetFileOfAddress((void*)mm_DetectGameInformation, mm_path, sizeof(mm_path)))
    76 	{
    77 		mm_LogFatal("Could not locate Metamod loader library path");
    78 		return false;
    79 	}
    80 
    81 	if (!mm_ResolvePath(game_name, game_path, sizeof(game_path)))
    82 	{
    83 		mm_LogFatal("Could not resolve path: %s", game_name);
    84 		return false;
    85 	}
    86 
    87 	FILE *fp;
    88 	char gameinfo_path[PLATFORM_MAX_PATH];
    89 
    90 	mm_PathFormat(gameinfo_path, sizeof(gameinfo_path), "%s/gameinfo.txt", game_path);
    91 	if ((fp = fopen(gameinfo_path, "rt")) == NULL)
    92 	{
    93 		mm_LogFatal("Could not read file: %s", gameinfo_path);
    94 		return false;
    95 	}
    96 
    97 	char temp_path[PLATFORM_MAX_PATH];
    98 	char cur_path[PLATFORM_MAX_PATH];
    99 	getcwd(cur_path, sizeof(cur_path));
   100 
   101 	char *ptr;
   102 	const char *lptr;
   103 	bool search = false;
   104 	char buffer[255], key[128], val[128];
   105 	while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
   106 	{
   107 		mm_TrimComments(buffer);
   108 		mm_TrimLeft(buffer);
   109 		mm_TrimRight(buffer);
   110 
   111 		if (stricmp(buffer, "SearchPaths") == 0)
   112 			search = true;
   113 
   114 		if (!search)
   115 			continue;
   116 
   117 		mm_KeySplit(buffer, key, sizeof(key) - 1, val, sizeof(val) - 1);
   118 		if (stricmp(key, "Game") != 0 && stricmp(key, "GameBin") != 0)
   119 			continue;
   120 
   121 		if (strncmp(val, "|gameinfo_path|", sizeof("|gameinfo_path|") - 1) == 0)
   122 		{
   123 			ptr = &val[sizeof("|gameinfo_path|") - 1];
   124 			if (ptr[0] == '.')
   125 				ptr++;
   126 			lptr = game_path;
   127 		}
   128 		else
   129 		{
   130 			ptr = val;
   131 			lptr = cur_path;
   132 		}
   133 
   134 		if (stricmp(key, "GameBin") == 0)
   135 			mm_PathFormat(temp_path, sizeof(temp_path), "%s/%s/" SERVER_NAME, lptr, ptr);
   136 		else if (!ptr[0])
   137 			mm_PathFormat(temp_path, sizeof(temp_path), "%s/bin/" SERVER_NAME, lptr);
   138 		else
   139 			mm_PathFormat(temp_path, sizeof(temp_path), "%s/%s/bin/" SERVER_NAME, lptr, ptr);
   140 
   141 		if (mm_PathCmp(mm_path, temp_path))
   142 			continue;
   143 
   144 		FILE *exists = fopen(temp_path, "rb");
   145 		if (!exists)
   146 			continue;
   147 		fclose(exists);
   148 
   149 		/* exists is still non-NULL... use this as a flag */
   150 		for (unsigned int i = 0; i < gamedll_path_count; i++)
   151 		{
   152 			if (mm_PathCmp(gamedll_paths[i], temp_path))
   153 			{
   154 				exists = NULL;
   155 				break;
   156 			}
   157 		}
   158 
   159 		if (!exists)
   160 			continue;
   161 
   162 		mm_Format(gamedll_paths[gamedll_path_count],
   163 				  PLATFORM_MAX_PATH,
   164 				  "%s",
   165 				  temp_path);
   166 		gamedll_path_count++;
   167 
   168 		if (gamedll_path_count == MAX_GAMEDLL_PATHS)
   169 			break;
   170 	}
   171 	fclose(fp);
   172 
   173 	game_info_detected = 1;
   174 
   175 	if (gamedll_path_count == 0)
   176 	{
   177 		mm_LogFatal("Could not detect any valid game paths in gameinfo.txt");
   178 		return false;
   179 	}
   180 
   181 	return true;
   182 }
   183 
   184 static void
   185 mm_FreeCachedLibraries()
   186 {
   187 	for (unsigned int i = 0; i < gamedll_path_count; i++)
   188 	{
   189 		if (gamedll_libs[i] == NULL)
   190 			continue;
   191 		mm_UnloadLibrary(gamedll_libs[i]);
   192 	}
   193 }
   194 
   195 static void
   196 mm_PatchDllInit(bool patch);
   197 
   198 static void
   199 mm_PatchDllShutdown();
   200 
   201 static void *isgd_orig_init = NULL;
   202 static void *isgd_orig_shutdown = NULL;
   203 
   204 class VEmptyClass
   205 {
   206 };
   207 
   208 class IServerGameDLL
   209 {
   210 public:
   211 	virtual bool DLLInit(QueryValveInterface engineFactory, 
   212 						 QueryValveInterface physicsFactory, 
   213 						 QueryValveInterface fileSystemFactory, 
   214 						 void *pGlobals)
   215 	{
   216 		mm_backend = mm_DetermineBackend(engineFactory, gamedll_qvi, game_name);
   217 
   218 		char error[255];
   219 		if (mm_backend == MMBackend_UNKNOWN)
   220 		{
   221 			mm_LogFatal("Could not detect engine version");
   222 		}
   223 		else
   224 		{
   225 			if (!mm_LoadMetamodLibrary(mm_backend, error, sizeof(error)))
   226 			{
   227 				mm_LogFatal("Detected engine %d but could not load: %s", mm_backend, error);
   228 			}
   229 			else
   230 			{
   231 				typedef IGameDllBridge *(*GetGameDllBridge)();
   232 				GetGameDllBridge get_bridge = (GetGameDllBridge)mm_GetProcAddress("GetGameDllBridge");
   233 				if (get_bridge == NULL)
   234 				{
   235 					mm_UnloadMetamodLibrary();
   236 					mm_LogFatal("Detected engine %d but could not find GetGameDllBridge callback", mm_backend);
   237 				}
   238 				else
   239 				{
   240 					gamedll_bridge = get_bridge();
   241 				}
   242 			}
   243 		}
   244 
   245 		if (gamedll_bridge)
   246 		{
   247 			gamedll_bridge_info info;
   248 
   249 			info.engineFactory = (QueryValveInterface)engineFactory;
   250 			info.physicsFactory = (QueryValveInterface)physicsFactory;
   251 			info.fsFactory = (QueryValveInterface)fileSystemFactory;
   252 			info.pGlobals = pGlobals;
   253 			info.dllVersion = gamedll_version;
   254 			info.isgd = gamedll_iface;
   255 			info.gsFactory = gamedll_qvi;
   256 			info.vsp_listener_path = mm_path;
   257 
   258 			strcpy(error, "Unknown error");
   259 			if (!gamedll_bridge->DLLInit_Pre(&info, error, sizeof(error)))
   260 			{
   261 				gamedll_bridge = NULL;
   262 				mm_UnloadMetamodLibrary();
   263 				mm_LogFatal("Unknown error loading Metamod for engine %d: %s", mm_backend, error);	
   264 			}
   265 		}
   266 
   267 		/* Call the original */
   268 		bool result;
   269 		{
   270 			union
   271 			{
   272 				bool (VEmptyClass::*mfpnew)(QueryValveInterface engineFactory, 
   273 										 	QueryValveInterface physicsFactory, 
   274 										 	QueryValveInterface fileSystemFactory, 
   275 										 	void *pGlobals);
   276 #if defined _WIN32
   277 				void *addr;
   278 			} u;
   279 			u.addr = isgd_orig_init;
   280 #else
   281 				struct
   282 				{
   283 					void *addr;
   284 					intptr_t adjustor;
   285 				} s;
   286 			} u;
   287 			u.s.addr = isgd_orig_init;
   288 			u.s.adjustor = 0;
   289 #endif
   290 			result = (((VEmptyClass *)gamedll_iface)->*u.mfpnew)(engineFactory,
   291 																 physicsFactory,
   292 																 fileSystemFactory,
   293 																 pGlobals);
   294 		}
   295 
   296 		/**
   297 		 * :TODO: possible logic hole here, what happens if the gamedll REALLY returns false? 
   298 		 * I'm pretty sure we'll die horribly.
   299 		 */
   300 
   301 		if (!result)
   302 		{
   303 			gamedll_bridge->Unload();
   304 			mm_UnloadMetamodLibrary();
   305 			gamedll_bridge = NULL;
   306 		}
   307 		else if (gamedll_bridge != NULL)
   308 		{
   309 			gamedll_bridge->DLLInit_Post(&isgd_shutdown_index);
   310 			assert(isgd_shutdown_index != -1);
   311 			mm_PatchDllShutdown();
   312 		}
   313 
   314 		mm_PatchDllInit(false);
   315 
   316 		return result;
   317 	}
   318 
   319 	virtual void DLLShutdown()
   320 	{
   321 		gamedll_bridge->Unload();
   322 		gamedll_bridge = NULL;
   323 		mm_UnloadMetamodLibrary();
   324 
   325 		/* Call original function */
   326 		{
   327 			union
   328 			{
   329 				void (VEmptyClass::*mfpnew)();
   330 #if defined _WIN32
   331 				void *addr;
   332 			} u;
   333 			u.addr = isgd_orig_shutdown;
   334 #else
   335 				struct
   336 				{
   337 					void *addr;
   338 					intptr_t adjustor;
   339 				} s;
   340 			} u;
   341 			u.s.addr = isgd_orig_shutdown;
   342 			u.s.adjustor = 0;
   343 #endif
   344 			(((VEmptyClass *)gamedll_iface)->*u.mfpnew)();
   345 		}
   346 
   347 		mm_UnloadLibrary(gamedll_lib);
   348 		gamedll_lib = NULL;
   349 	}
   350 };
   351 
   352 static IServerGameDLL isgd_thunk;
   353 
   354 static void
   355 mm_PatchDllInit(bool patch)
   356 {
   357 	void **vtable_src;
   358 	void **vtable_dest;
   359 	SourceHook::MemFuncInfo mfp;
   360 
   361 	SourceHook::GetFuncInfo(&IServerGameDLL::DLLInit, mfp);
   362 
   363 	assert(mfp.isVirtual);
   364 	assert(mfp.thisptroffs == 0);
   365 	assert(mfp.vtbloffs == 0);
   366 
   367 	vtable_src = (void **)*(void **)&isgd_thunk;
   368 	vtable_dest = (void **)*(void **)gamedll_iface;
   369 
   370 	SourceHook::SetMemAccess(&vtable_dest[mfp.vtblindex],
   371 							 sizeof(void*),
   372 							 SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
   373 
   374 	if (patch)
   375 	{
   376 		assert(isgd_orig_init == NULL);
   377 		isgd_orig_init = vtable_dest[mfp.vtblindex];
   378 		vtable_dest[mfp.vtblindex] = vtable_src[mfp.vtblindex];
   379 	}
   380 	else
   381 	{
   382 		assert(isgd_orig_init != NULL);
   383 		vtable_dest[mfp.vtblindex] = isgd_orig_init;
   384 		isgd_orig_init = NULL;
   385 	}
   386 }
   387 
   388 static void
   389 mm_PatchDllShutdown()
   390 {
   391 	void **vtable_src;
   392 	void **vtable_dest;
   393 	SourceHook::MemFuncInfo mfp;
   394 
   395 	mfp.isVirtual = false;
   396 	SourceHook::GetFuncInfo(&IServerGameDLL::DLLShutdown, mfp);
   397 	assert(mfp.isVirtual);
   398 	assert(mfp.thisptroffs == 0);
   399 	assert(mfp.vtbloffs == 0);
   400 
   401 	vtable_src = (void **)*(void **)&isgd_thunk;
   402 	vtable_dest = (void **)*(void **)gamedll_iface;
   403 
   404 	isgd_orig_shutdown = vtable_dest[isgd_shutdown_index];
   405 	vtable_dest[isgd_shutdown_index] = vtable_src[mfp.vtblindex];
   406 }
   407 
   408 static void
   409 mm_PrepForGameLoad()
   410 {
   411 	mm_PatchDllInit(true);
   412 }
   413 
   414 void *
   415 mm_GameDllRequest(const char *name, int *ret)
   416 {
   417 	if (gamedll_lib != NULL && gamedll_bridge == NULL)
   418 	{
   419 		return gamedll_qvi(name, ret);
   420 	}
   421 
   422 	if (strncmp(name, "ServerGameDLL", 13) == 0)
   423 	{
   424 		if (!mm_DetectGameInformation())
   425 		{
   426 			if (ret != NULL)
   427 				*ret = 1;
   428 			return NULL;
   429 		}
   430 
   431 		void *lib;
   432 		char error[255];
   433 		void *ptr = NULL;
   434 		QueryValveInterface qvi;
   435 		for (unsigned int i = 0; i < gamedll_path_count; i++)
   436 		{
   437 			if (gamedll_libs[i] == NULL)
   438 			{
   439 				lib = mm_LoadLibrary(gamedll_paths[i], error, sizeof(error));
   440 				if (lib == NULL)
   441 					continue;
   442 				gamedll_libs[i] = lib;
   443 			}
   444 			lib = gamedll_libs[i];
   445 			qvi = (QueryValveInterface)mm_GetLibAddress(lib, "CreateInterface");
   446 			if (qvi == NULL)
   447 				continue;
   448 			ptr = qvi(name, ret);
   449 			if (ptr != NULL)
   450 			{
   451 				gamedll_libs[i] = NULL;
   452 				break;
   453 			}
   454 		}
   455 
   456 		if (ptr != NULL)
   457 		{
   458 			mm_FreeCachedLibraries();	
   459 			gamedll_lib = lib;
   460 			gamedll_iface = (IServerGameDLL *)ptr;
   461 			gamedll_qvi = qvi;
   462 			gamedll_version = atoi(&name[13]);
   463 			mm_PrepForGameLoad();
   464 
   465 			if (ret != NULL)
   466 				*ret = 0;
   467 			return ptr;
   468 		}
   469 	}
   470 	else if (game_info_detected == 0)
   471 	{
   472 		mm_LogFatal("Received interface request too early: %s", name);
   473 	}
   474 
   475 	if (ret != NULL)
   476 		*ret = 1;
   477 	return NULL;
   478 }
   479