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