loader/loader.cpp
author David Anderson <dvander@alliedmods.net>
Mon Jul 04 15:33:11 2011 -0700 (2011-07-04)
changeset 3328 5873eac6b9b1
parent 3261 e4359292e59a
child 3373 c6463cdc2180
permissions -rw-r--r--
Clobber
     1 /**
     2  * vim: set ts=4 sw=4 tw=99 noet :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2010 AlliedModders LLC.  All rights reserved.
     6  * =============================================================================
     7  *
     8  * This program is free software; you can redistribute it and/or modify it under
     9  * the terms of the GNU General Public License, version 3.0, as published by the
    10  * Free Software Foundation.
    11  * 
    12  * This program is distributed in the hope that it will be useful, but WITHOUT
    13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    14  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
    15  * details.
    16  *
    17  * You should have received a copy of the GNU General Public License along with
    18  * this program.  If not, see <http://www.gnu.org/licenses/>.
    19  *
    20  * As a special exception, AlliedModders LLC gives you permission to link the
    21  * code of this program (as well as its derivative works) to "Half-Life 2," the
    22  * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
    23  * by the Valve Corporation.  You must obey the GNU General Public License in
    24  * all respects for all other code used.  Additionally, AlliedModders LLC grants
    25  * this exception to all derivative works.  AlliedModders LLC defines further
    26  * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
    27  * or <http://www.sourcemod.net/license.php>.
    28  */
    29 
    30 #include <ISmmPluginExt.h>
    31 #include <stdarg.h>
    32 #include <string.h>
    33 #include <stdio.h>
    34 #include <stdlib.h>
    35 
    36 #if defined _MSC_VER
    37 	#define DLL_EXPORT				extern "C" __declspec(dllexport)
    38 	#define openlib(lib)			LoadLibrary(lib)
    39 	#define closelib(lib)			FreeLibrary(lib)
    40 	#define findsym(lib, sym)		GetProcAddress(lib, sym)
    41 	#define PLATFORM_EXT			".dll"
    42 	#define vsnprintf				_vsnprintf
    43 	#define PATH_SEP_CHAR			"\\"
    44 	inline bool IsPathSepChar(char c) 
    45 	{
    46 		return (c == '/' || c == '\\');
    47 	}
    48 	#include <Windows.h>
    49 #else
    50 	#define DLL_EXPORT				extern "C" __attribute__((visibility("default")))
    51 	#define openlib(lib)			dlopen(lib, RTLD_NOW)
    52 	#define closelib(lib)			dlclose(lib)
    53 	#define findsym(lib, sym)		dlsym(lib, sym)
    54 	#if defined __linux__
    55 	#define PLATFORM_EXT			".so"
    56 	#elif defined __APPLE__
    57 	#define PLATFORM_EXT			".dylib"
    58 	#endif
    59 	typedef void *					HINSTANCE;
    60 	#define PATH_SEP_CHAR			"/"
    61 	inline bool IsPathSepChar(char c) 
    62 	{
    63 		return (c == '/');
    64 	}
    65 	#include <dlfcn.h>
    66 #endif
    67 
    68 #define METAMOD_API_MAJOR			2
    69 #define FILENAME_1_4_EP1			"sourcemod.1.ep1" PLATFORM_EXT
    70 #define FILENAME_1_6_EP2			"sourcemod.2.ep2" PLATFORM_EXT
    71 #define FILENAME_1_6_EP2VALVE		"sourcemod.2.ep2v" PLATFORM_EXT
    72 #define FILENAME_1_6_EP1			"sourcemod.2.ep1" PLATFORM_EXT
    73 #define FILENAME_1_6_L4D			"sourcemod.2.l4d" PLATFORM_EXT
    74 #define FILENAME_1_6_DARKM			"sourcemod.2.darkm" PLATFORM_EXT
    75 #define FILENAME_1_6_L4D2			"sourcemod.2.l4d2" PLATFORM_EXT
    76 #define FILENAME_1_6_SWARM			"sourcemod.2.swarm" PLATFORM_EXT
    77 #define FILENAME_1_6_BGT			"sourcemod.2.bgt" PLATFORM_EXT
    78 
    79 HINSTANCE g_hCore = NULL;
    80 bool load_attempted = false;
    81 
    82 size_t UTIL_Format(char *buffer, size_t maxlength, const char *fmt, ...);
    83 
    84 class FailPlugin : public SourceMM::ISmmFailPlugin
    85 {
    86 public:
    87 	int GetApiVersion()
    88 	{
    89 		return fail_version;
    90 	}
    91 
    92 	bool Load(SourceMM::PluginId id, SourceMM::ISmmAPI *ismm, char *error, size_t maxlength, bool late)
    93 	{
    94 		if (error != NULL && maxlength != 0)
    95 		{
    96 			UTIL_Format(error, maxlength, "%s", error_buffer);
    97 		}
    98 		return false;
    99 	}
   100 
   101 	int fail_version;
   102 	char error_buffer[512];
   103 } s_FailPlugin;
   104 
   105 size_t UTIL_Format(char *buffer, size_t maxlength, const char *fmt, ...)
   106 {
   107 	va_list ap;
   108 
   109 	va_start(ap, fmt);
   110 	size_t len = vsnprintf(buffer, maxlength, fmt, ap);
   111 	va_end(ap);
   112 
   113 	if (len >= maxlength)
   114 	{
   115 		len = maxlength - 1;
   116 		buffer[len] = '\0';
   117 	}
   118 
   119 	return len;
   120 }
   121 
   122 METAMOD_PLUGIN *_GetPluginPtr(const char *path, int fail_api)
   123 {
   124 	METAMOD_FN_ORIG_LOAD fn;
   125 	METAMOD_PLUGIN *pl;
   126 	int ret;
   127 
   128 	if (!(g_hCore=openlib(path)))
   129 	{
   130 #if defined __linux__ || defined __APPLE__
   131 		UTIL_Format(s_FailPlugin.error_buffer, 
   132 			sizeof(s_FailPlugin.error_buffer),
   133 			"%s",
   134 			dlerror());
   135 #else
   136 		DWORD err = GetLastError();
   137 
   138 		if (FormatMessageA(
   139 				FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
   140 				NULL,
   141 				err,
   142 				MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
   143 				s_FailPlugin.error_buffer,
   144 				sizeof(s_FailPlugin.error_buffer),
   145 				NULL)
   146 			== 0)
   147 		{
   148 			UTIL_Format(s_FailPlugin.error_buffer, 
   149 				sizeof(s_FailPlugin.error_buffer),
   150 				"unknown error %x",
   151 				err);
   152 		}
   153 #endif
   154 
   155 		s_FailPlugin.fail_version = fail_api;
   156 
   157 		return (METAMOD_PLUGIN *)&s_FailPlugin;
   158 	}
   159 
   160 	if (!(fn=(METAMOD_FN_ORIG_LOAD)findsym(g_hCore, "CreateInterface")))
   161 	{
   162 		goto error;
   163 	}
   164 
   165 	pl = (METAMOD_PLUGIN *)fn(METAMOD_PLAPI_NAME, &ret);
   166 	if (!pl)
   167 	{
   168 		goto error;
   169 	}
   170 
   171 	return pl;
   172 error:
   173 	closelib(g_hCore);
   174 	g_hCore = NULL;
   175 	return NULL;
   176 }
   177 
   178 bool GetFileOfAddress(void *pAddr, char *buffer, size_t maxlength)
   179 {
   180 #if defined _MSC_VER
   181 	MEMORY_BASIC_INFORMATION mem;
   182 	if (!VirtualQuery(pAddr, &mem, sizeof(mem)))
   183 		return false;
   184 	if (mem.AllocationBase == NULL)
   185 		return false;
   186 	HMODULE dll = (HMODULE)mem.AllocationBase;
   187 	GetModuleFileName(dll, (LPTSTR)buffer, maxlength);
   188 #else
   189 	Dl_info info;
   190 	if (!dladdr(pAddr, &info))
   191 		return false;
   192 	if (!info.dli_fbase || !info.dli_fname)
   193 		return false;
   194 	const char *dllpath = info.dli_fname;
   195 	snprintf(buffer, maxlength, "%s", dllpath);
   196 #endif
   197 	return true;
   198 }
   199 
   200 DLL_EXPORT METAMOD_PLUGIN *CreateInterface_MMS(const MetamodVersionInfo *mvi, const MetamodLoaderInfo *mli)
   201 {
   202 	const char *filename;
   203 
   204 	load_attempted = true;
   205 	
   206 	if (mvi->api_major > METAMOD_API_MAJOR)
   207 	{
   208 		return NULL;
   209 	}
   210 
   211 	switch (mvi->source_engine)
   212 	{
   213 	case SOURCE_ENGINE_ORIGINAL:
   214 	case SOURCE_ENGINE_EPISODEONE:
   215 		{
   216 			filename = FILENAME_1_6_EP1;
   217 			break;
   218 		}
   219 	case SOURCE_ENGINE_ORANGEBOX:
   220 		{
   221 			filename = FILENAME_1_6_EP2;
   222 			break;
   223 		}
   224 	case SOURCE_ENGINE_LEFT4DEAD:
   225 		{
   226 			filename = FILENAME_1_6_L4D;
   227 			break;
   228 		}
   229 	case SOURCE_ENGINE_DARKMESSIAH:
   230 		{
   231 			filename = FILENAME_1_6_DARKM;
   232 			break;
   233 		}
   234 	case SOURCE_ENGINE_ORANGEBOXVALVE:
   235 		{
   236 			filename = FILENAME_1_6_EP2VALVE;
   237 			break;
   238 		}
   239 	case SOURCE_ENGINE_LEFT4DEAD2:
   240 		{
   241 			filename = FILENAME_1_6_L4D2;
   242 			break;
   243 		}
   244 	case SOURCE_ENGINE_ALIENSWARM:
   245 		{
   246 			filename = FILENAME_1_6_SWARM;
   247 			break;
   248 		}
   249 	case SOURCE_ENGINE_BLOODYGOODTIME:
   250 		{
   251 			filename = FILENAME_1_6_BGT;
   252 			break;
   253 		}
   254 	default:
   255 		{
   256 			return NULL;
   257 		}
   258 	}
   259 
   260 	char abspath[256];
   261 	UTIL_Format(abspath, sizeof(abspath), "%s" PATH_SEP_CHAR "%s", mli->pl_path, filename);
   262 
   263 	return _GetPluginPtr(abspath, METAMOD_FAIL_API_V2);
   264 }
   265 
   266 DLL_EXPORT void UnloadInterface_MMS()
   267 {
   268 	if (g_hCore)
   269 	{
   270 		closelib(g_hCore);
   271 		g_hCore = NULL;
   272 	}
   273 }
   274 
   275 DLL_EXPORT void *CreateInterface(const char *iface, int *ret)
   276 {
   277 	/**
   278 	 * If a load has already been attempted, bail out immediately.
   279 	 */
   280 	if (load_attempted)
   281 	{
   282 		return NULL;
   283 	}
   284 
   285 	if (strcmp(iface, METAMOD_PLAPI_NAME) == 0)
   286 	{
   287 		char thisfile[256];
   288 		char targetfile[256];
   289 
   290 		if (!GetFileOfAddress((void *)CreateInterface_MMS, thisfile, sizeof(thisfile)))
   291 		{
   292 			return NULL;
   293 		}
   294 
   295 		size_t len = strlen(thisfile);
   296 		for (size_t iter=len-1; iter<len; iter--)
   297 		{
   298 			if (IsPathSepChar(thisfile[iter]))
   299 			{
   300 				thisfile[iter] = '\0';
   301 				break;
   302 			}
   303 		}
   304 
   305 		UTIL_Format(targetfile, sizeof(targetfile), "%s" PATH_SEP_CHAR FILENAME_1_4_EP1, thisfile);
   306 
   307 		return _GetPluginPtr(targetfile, METAMOD_FAIL_API_V1);
   308 	}
   309 
   310 	return NULL;
   311 }
   312 
   313 #if defined _MSC_VER
   314 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)
   315 {
   316 	if (fdwReason == DLL_PROCESS_DETACH)
   317 	{
   318 		UnloadInterface_MMS();
   319 	}
   320 	return TRUE;
   321 }
   322 #else
   323 __attribute__((destructor)) static void gcc_fini()
   324 {
   325 	UnloadInterface_MMS();
   326 }
   327 #endif
   328 
   329 /* Overload a few things to prevent libstdc++ linking */
   330 #if defined __linux__ || defined __APPLE__
   331 extern "C" void __cxa_pure_virtual(void)
   332 {
   333 }
   334 
   335 void *operator new(size_t size)
   336 {
   337 	return malloc(size);
   338 }
   339 
   340 void *operator new[](size_t size)
   341 {
   342 	return malloc(size);
   343 }
   344 
   345 void operator delete(void *ptr)
   346 {
   347 	free(ptr);
   348 }
   349 
   350 void operator delete[](void * ptr)
   351 {
   352 	free(ptr);
   353 }
   354 #endif
   355 
   356