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