loader/gamedll.cpp
author Scott Ehlert <ds@alliedmods.net>
Sun Nov 22 23:54:55 2009 -0600 (2009-11-22)
changeset 683 b507295429f9
parent 681 a9f34c9f06e7
child 705 a1001281dcb1
permissions -rw-r--r--
Fixed VSP listener on Linux when loaded via gameinfo.txt on Left 4 Dead 2 (bug 4113, r=dvander).

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