loader/gamedll.cpp
author David Anderson <dvander@alliedmods.net>
Sun Nov 23 20:18:17 2008 -0800 (2008-11-23)
changeset 587 3cbfdd9088d3
parent 586 ed3320c98dd7
child 588 41649fe12c7b
permissions -rw-r--r--
Fix loader building on windows.
     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 				gamedll_bridge = get_bridge();
   260 			}
   261 		}
   262 
   263 		if (gamedll_bridge)
   264 		{
   265 			gamedll_bridge_info info;
   266 
   267 			info.engineFactory = (QueryValveInterface)engineFactory;
   268 			info.physicsFactory = (QueryValveInterface)physicsFactory;
   269 			info.fsFactory = (QueryValveInterface)fileSystemFactory;
   270 			info.pGlobals = pGlobals;
   271 			info.dllVersion = gamedll_version;
   272 			info.isgd = gamedll_iface;
   273 			info.gsFactory = gamedll_qvi;
   274 
   275 			strcpy(error, "Unknown error");
   276 			if (!gamedll_bridge->DLLInit_Pre(&info, error, sizeof(error)))
   277 			{
   278 				gamedll_bridge = NULL;
   279 				mm_UnloadMetamodLibrary();
   280 				mm_LogFatal("Unknown error loading Metamod for engine %d: %s", backend, error);	
   281 			}
   282 		}
   283 
   284 		/* Call the original */
   285 		bool result;
   286 		{
   287 			union
   288 			{
   289 				bool (VEmptyClass::*mfpnew)(QueryValveInterface engineFactory, 
   290 										 	QueryValveInterface physicsFactory, 
   291 										 	QueryValveInterface fileSystemFactory, 
   292 										 	void *pGlobals);
   293 #if defined _WIN32
   294 				void *addr;
   295 			} u;
   296 			u.addr = isgd_orig_init;
   297 #else
   298 				struct
   299 				{
   300 					void *addr;
   301 					intptr_t adjustor;
   302 				} s;
   303 			} u;
   304 			u.s.addr = isgd_orig_init;
   305 			u.s.adjustor = 0;
   306 #endif
   307 			result = (((VEmptyClass *)gamedll_iface)->*u.mfpnew)(engineFactory,
   308 																 physicsFactory,
   309 																 fileSystemFactory,
   310 																 pGlobals);
   311 		}
   312 
   313 		/**
   314 		 * :TODO: possible logic hole here, what happens if the gamedll REALLY returns false? 
   315 		 * I'm pretty sure we'll die horribly.
   316 		 */
   317 
   318 		if (!result)
   319 		{
   320 			gamedll_bridge->Unload();
   321 			mm_UnloadMetamodLibrary();
   322 			gamedll_bridge = NULL;
   323 		}
   324 		else if (gamedll_bridge != NULL)
   325 		{
   326 			gamedll_bridge->DLLInit_Post(&isgd_shutdown_index);
   327 			assert(isgd_shutdown_index != -1);
   328 			mm_PatchDllShutdown();
   329 		}
   330 
   331 		mm_PatchDllInit(false);
   332 
   333 		return result;
   334 	}
   335 
   336 	virtual void DLLShutdown()
   337 	{
   338 		gamedll_bridge->Unload();
   339 		gamedll_bridge = NULL;
   340 		mm_UnloadMetamodLibrary();
   341 
   342 		/* Call original function */
   343 		{
   344 			union
   345 			{
   346 				void (VEmptyClass::*mfpnew)();
   347 #if defined _WIN32
   348 				void *addr;
   349 			} u;
   350 			u.addr = isgd_orig_shutdown;
   351 #else
   352 				struct
   353 				{
   354 					void *addr;
   355 					intptr_t adjustor;
   356 				} s;
   357 			} u;
   358 			u.s.addr = isgd_orig_shutdown;
   359 			u.s.adjustor = 0;
   360 #endif
   361 			(((VEmptyClass *)gamedll_iface)->*u.mfpnew)();
   362 		}
   363 
   364 		mm_UnloadLibrary(gamedll_lib);
   365 		gamedll_lib = NULL;
   366 	}
   367 };
   368 
   369 static IServerGameDLL isgd_thunk;
   370 
   371 static void
   372 mm_PatchDllInit(bool patch)
   373 {
   374 	void **vtable_src;
   375 	void **vtable_dest;
   376 	SourceHook::MemFuncInfo mfp;
   377 
   378 	SourceHook::GetFuncInfo(&IServerGameDLL::DLLInit, mfp);
   379 
   380 	assert(mfp.isVirtual);
   381 	assert(mfp.thisptroffs == 0);
   382 	assert(mfp.vtbloffs == 0);
   383 
   384 	vtable_src = (void **)*(void **)&isgd_thunk;
   385 	vtable_dest = (void **)*(void **)gamedll_iface;
   386 
   387 	SourceHook::SetMemAccess(&vtable_dest[mfp.vtblindex],
   388 							 sizeof(void*),
   389 							 SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
   390 
   391 	if (patch)
   392 	{
   393 		assert(isgd_orig_init == NULL);
   394 		isgd_orig_init = vtable_dest[mfp.vtblindex];
   395 		vtable_dest[mfp.vtblindex] = vtable_src[mfp.vtblindex];
   396 	}
   397 	else
   398 	{
   399 		assert(isgd_orig_init != NULL);
   400 		vtable_dest[mfp.vtblindex] = isgd_orig_init;
   401 		isgd_orig_init = NULL;
   402 	}
   403 }
   404 
   405 static void
   406 mm_PatchDllShutdown()
   407 {
   408 	void **vtable_src;
   409 	void **vtable_dest;
   410 	SourceHook::MemFuncInfo mfp;
   411 
   412 	mfp.isVirtual = false;
   413 	SourceHook::GetFuncInfo(&IServerGameDLL::DLLShutdown, mfp);
   414 	assert(mfp.isVirtual);
   415 	assert(mfp.thisptroffs == 0);
   416 	assert(mfp.vtbloffs == 0);
   417 
   418 	vtable_src = (void **)*(void **)&isgd_thunk;
   419 	vtable_dest = (void **)*(void **)gamedll_iface;
   420 
   421 	isgd_orig_shutdown = vtable_dest[isgd_shutdown_index];
   422 	vtable_dest[isgd_shutdown_index] = vtable_src[mfp.vtblindex];
   423 }
   424 
   425 static void
   426 mm_PrepForGameLoad()
   427 {
   428 	mm_PatchDllInit(true);
   429 }
   430 
   431 void *
   432 mm_GameDllRequest(const char *name, int *ret)
   433 {
   434 	if (gamedll_lib != NULL && gamedll_bridge == NULL)
   435 	{
   436 		mm_LogFatal("Requested unknown interface before game load: %s", name);
   437 		return gamedll_qvi(name, ret);
   438 	}
   439 
   440 	if (strncmp(name, "ServerGameDLL", 13) == 0)
   441 	{
   442 		if (!mm_DetectGameInformation())
   443 		{
   444 			if (ret != NULL)
   445 				*ret = 1;
   446 			return NULL;
   447 		}
   448 
   449 		void *lib;
   450 		char error[255];
   451 		void *ptr = NULL;
   452 		QueryValveInterface qvi;
   453 		for (unsigned int i = 0; i < gamedll_path_count; i++)
   454 		{
   455 			if (gamedll_libs[i] == NULL)
   456 			{
   457 				lib = mm_LoadLibrary(gamedll_paths[i], error, sizeof(error));
   458 				if (lib == NULL)
   459 					continue;
   460 				gamedll_libs[i] = lib;
   461 			}
   462 			lib = gamedll_libs[i];
   463 			qvi = (QueryValveInterface)mm_GetLibAddress(lib, "CreateInterface");
   464 			if (qvi == NULL)
   465 				continue;
   466 			ptr = qvi(name, ret);
   467 			if (ptr != NULL)
   468 			{
   469 				gamedll_libs[i] = NULL;
   470 				break;
   471 			}
   472 		}
   473 
   474 		if (ptr != NULL)
   475 		{
   476 			mm_FreeCachedLibraries();	
   477 			gamedll_lib = lib;
   478 			gamedll_iface = (IServerGameDLL *)ptr;
   479 			gamedll_qvi = qvi;
   480 			gamedll_version = atoi(&name[13]);
   481 			mm_PrepForGameLoad();
   482 
   483 			if (ret != NULL)
   484 				*ret = 0;
   485 			return ptr;
   486 		}
   487 	}
   488 	else if (game_info_detected == 0)
   489 	{
   490 		mm_LogFatal("Received interface request too early: %s", name);
   491 	}
   492 
   493 	if (ret != NULL)
   494 		*ret = 1;
   495 	return NULL;
   496 }
   497