loader/loader.cpp
author David Anderson <dvander@alliedmods.net>
Sun Dec 28 03:23:45 2008 -0500 (2008-12-28)
changeset 2479 44e8e76d4e53
parent 2400 76b7b4575e21
parent 2471 194be299b700
child 2583 d3b2571c378b
permissions -rw-r--r--
Merge from sourcemod-1.1 branch.
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2008 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  * Version: $Id$
    30  */
    31 
    32 #include <ISmmPluginExt.h>
    33 #include <stdarg.h>
    34 #include <string.h>
    35 #include <stdio.h>
    36 #include <stdlib.h>
    37 
    38 #if defined _MSC_VER
    39 	#define DLL_EXPORT				extern "C" __declspec(dllexport)
    40 	#define openlib(lib)			LoadLibrary(lib)
    41 	#define closelib(lib)			FreeLibrary(lib)
    42 	#define findsym(lib, sym)		GetProcAddress(lib, sym)
    43 	#define PLATFORM_EXT			".dll"
    44 	#define vsnprintf				_vsnprintf
    45 	#define PATH_SEP_CHAR			"\\"
    46 	inline bool IsPathSepChar(char c) 
    47 	{
    48 		return (c == '/' || c == '\\');
    49 	}
    50 	#include <Windows.h>
    51 #else
    52 	#define DLL_EXPORT				extern "C" __attribute__((visibility("default")))
    53 	#define openlib(lib)			dlopen(lib, RTLD_NOW)
    54 	#define closelib(lib)			dlclose(lib)
    55 	#define findsym(lib, sym)		dlsym(lib, sym)
    56 	#define PLATFORM_EXT			".so"
    57 	typedef void *					HINSTANCE;
    58 	#define PATH_SEP_CHAR			"/"
    59 	inline bool IsPathSepChar(char c) 
    60 	{
    61 		return (c == '/');
    62 	}
    63 	#include <dlfcn.h>
    64 #endif
    65 
    66 #define METAMOD_API_MAJOR			2
    67 #define FILENAME_1_4_EP1			"sourcemod.1.ep1" PLATFORM_EXT
    68 #define FILENAME_1_6_EP2			"sourcemod.2.ep2" PLATFORM_EXT
    69 #define FILENAME_1_6_EP1			"sourcemod.2.ep1" PLATFORM_EXT
    70 #define FILENAME_1_7_L4D			"sourcemod.2.l4d" PLATFORM_EXT
    71 
    72 HINSTANCE g_hCore = NULL;
    73 bool load_attempted = false;
    74 
    75 size_t UTIL_Format(char *buffer, size_t maxlength, const char *fmt, ...);
    76 
    77 class FailPlugin : public SourceMM::ISmmFailPlugin
    78 {
    79 public:
    80 	int GetApiVersion()
    81 	{
    82 		return fail_version;
    83 	}
    84 
    85 	bool Load(SourceMM::PluginId id, SourceMM::ISmmAPI *ismm, char *error, size_t maxlength, bool late)
    86 	{
    87 		if (error != NULL && maxlength != 0)
    88 		{
    89 			UTIL_Format(error, maxlength, "%s", error_buffer);
    90 		}
    91 		return false;
    92 	}
    93 
    94 	int fail_version;
    95 	char error_buffer[512];
    96 } s_FailPlugin;
    97 
    98 size_t UTIL_Format(char *buffer, size_t maxlength, const char *fmt, ...)
    99 {
   100 	va_list ap;
   101 
   102 	va_start(ap, fmt);
   103 	size_t len = vsnprintf(buffer, maxlength, fmt, ap);
   104 	va_end(ap);
   105 
   106 	if (len >= maxlength)
   107 	{
   108 		len = maxlength - 1;
   109 		buffer[len] = '\0';
   110 	}
   111 
   112 	return len;
   113 }
   114 
   115 METAMOD_PLUGIN *_GetPluginPtr(const char *path, int fail_api)
   116 {
   117 	METAMOD_FN_ORIG_LOAD fn;
   118 	METAMOD_PLUGIN *pl;
   119 	int ret;
   120 
   121 	if (!(g_hCore=openlib(path)))
   122 	{
   123 #if defined __linux__ || defined __APPLE__
   124 		UTIL_Format(s_FailPlugin.error_buffer, 
   125 			sizeof(s_FailPlugin.error_buffer),
   126 			"%s",
   127 			dlerror());
   128 #else
   129 		DWORD err = GetLastError();
   130 
   131 		if (FormatMessageA(
   132 				FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
   133 				NULL,
   134 				err,
   135 				MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
   136 				s_FailPlugin.error_buffer,
   137 				sizeof(s_FailPlugin.error_buffer),
   138 				NULL)
   139 			== 0)
   140 		{
   141 			UTIL_Format(s_FailPlugin.error_buffer, 
   142 				sizeof(s_FailPlugin.error_buffer),
   143 				"unknown error %x",
   144 				err);
   145 		}
   146 #endif
   147 
   148 		s_FailPlugin.fail_version = fail_api;
   149 
   150 		return (METAMOD_PLUGIN *)&s_FailPlugin;
   151 	}
   152 
   153 	if (!(fn=(METAMOD_FN_ORIG_LOAD)findsym(g_hCore, "CreateInterface")))
   154 	{
   155 		goto error;
   156 	}
   157 
   158 	pl = (METAMOD_PLUGIN *)fn(METAMOD_PLAPI_NAME, &ret);
   159 	if (!pl)
   160 	{
   161 		goto error;
   162 	}
   163 
   164 	return pl;
   165 error:
   166 	closelib(g_hCore);
   167 	g_hCore = NULL;
   168 	return NULL;
   169 }
   170 
   171 bool GetFileOfAddress(void *pAddr, char *buffer, size_t maxlength)
   172 {
   173 #if defined _MSC_VER
   174 	MEMORY_BASIC_INFORMATION mem;
   175 	if (!VirtualQuery(pAddr, &mem, sizeof(mem)))
   176 		return false;
   177 	if (mem.AllocationBase == NULL)
   178 		return false;
   179 	HMODULE dll = (HMODULE)mem.AllocationBase;
   180 	GetModuleFileName(dll, (LPTSTR)buffer, maxlength);
   181 #else
   182 	Dl_info info;
   183 	if (!dladdr(pAddr, &info))
   184 		return false;
   185 	if (!info.dli_fbase || !info.dli_fname)
   186 		return false;
   187 	const char *dllpath = info.dli_fname;
   188 	snprintf(buffer, maxlength, "%s", dllpath);
   189 #endif
   190 	return true;
   191 }
   192 
   193 DLL_EXPORT METAMOD_PLUGIN *CreateInterface_MMS(const MetamodVersionInfo *mvi, const MetamodLoaderInfo *mli)
   194 {
   195 	char *filename;
   196 
   197 	load_attempted = true;
   198 	
   199 	if (mvi->api_major > METAMOD_API_MAJOR)
   200 	{
   201 		return NULL;
   202 	}
   203 
   204 	switch (mvi->source_engine)
   205 	{
   206 	case SOURCE_ENGINE_ORANGEBOX:
   207 		{
   208 			filename = FILENAME_1_6_EP2;
   209 			break;
   210 		}
   211 	case SOURCE_ENGINE_EPISODEONE:
   212 	case SOURCE_ENGINE_ORIGINAL:
   213 		{
   214 			filename = FILENAME_1_6_EP1;
   215 			break;
   216 		}
   217 	case SOURCE_ENGINE_LEFT4DEAD:
   218 		{
   219 			filename = FILENAME_1_7_L4D;
   220 			break;
   221 		}
   222 	default:
   223 		{
   224 			return NULL;
   225 		}
   226 	}
   227 
   228 	char abspath[256];
   229 	UTIL_Format(abspath, sizeof(abspath), "%s" PATH_SEP_CHAR "%s", mli->pl_path, filename);
   230 
   231 	return _GetPluginPtr(abspath, METAMOD_FAIL_API_V2);
   232 }
   233 
   234 DLL_EXPORT void UnloadInterface_MMS()
   235 {
   236 	if (g_hCore)
   237 	{
   238 		closelib(g_hCore);
   239 		g_hCore = NULL;
   240 	}
   241 }
   242 
   243 DLL_EXPORT void *CreateInterface(const char *iface, int *ret)
   244 {
   245 	/**
   246 	 * If a load has already been attempted, bail out immediately.
   247 	 */
   248 	if (load_attempted)
   249 	{
   250 		return NULL;
   251 	}
   252 
   253 	if (strcmp(iface, METAMOD_PLAPI_NAME) == 0)
   254 	{
   255 		char thisfile[256];
   256 		char targetfile[256];
   257 
   258 		if (!GetFileOfAddress((void *)CreateInterface_MMS, thisfile, sizeof(thisfile)))
   259 		{
   260 			return NULL;
   261 		}
   262 
   263 		size_t len = strlen(thisfile);
   264 		for (size_t iter=len-1; iter>=0 && iter<len; iter--)
   265 		{
   266 			if (IsPathSepChar(thisfile[iter]))
   267 			{
   268 				thisfile[iter] = '\0';
   269 				break;
   270 			}
   271 		}
   272 
   273 		UTIL_Format(targetfile, sizeof(targetfile), "%s" PATH_SEP_CHAR FILENAME_1_4_EP1, thisfile);
   274 
   275 		return _GetPluginPtr(targetfile, METAMOD_FAIL_API_V1);
   276 	}
   277 
   278 	return NULL;
   279 }
   280 
   281 #if defined _MSC_VER
   282 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)
   283 {
   284 	if (fdwReason == DLL_PROCESS_DETACH)
   285 	{
   286 		UnloadInterface_MMS();
   287 	}
   288 	return TRUE;
   289 }
   290 #else
   291 __attribute__((destructor)) static void gcc_fini()
   292 {
   293 	UnloadInterface_MMS();
   294 }
   295 #endif
   296 
   297 /* Overload a few things to prevent libstdc++ linking */
   298 #if defined __linux__ || defined __APPLE__
   299 extern "C" void __cxa_pure_virtual(void)
   300 {
   301 }
   302 
   303 void *operator new(size_t size)
   304 {
   305 	return malloc(size);
   306 }
   307 
   308 void *operator new[](size_t size)
   309 {
   310 	return malloc(size);
   311 }
   312 
   313 void operator delete(void *ptr)
   314 {
   315 	free(ptr);
   316 }
   317 
   318 void operator delete[](void * ptr)
   319 {
   320 	free(ptr);
   321 }
   322 #endif
   323 
   324