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