loader/loader.cpp
author David Anderson <dvander@alliedmods.net>
Sat Sep 26 17:19:47 2009 -0400 (2009-09-26)
changeset 2808 d3ebb7dd63fc
parent 2782 57d431498ac3
child 2847 1daf209d9dd2
permissions -rw-r--r--
Another forgotten-file for bug 4015. Thanks mqueues.
     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 	#define TF_PATH					"\\tf\\"
    52 	#define DOD_PATH				"\\dod\\"
    53 #else
    54 	#define DLL_EXPORT				extern "C" __attribute__((visibility("default")))
    55 	#define openlib(lib)			dlopen(lib, RTLD_NOW)
    56 	#define closelib(lib)			dlclose(lib)
    57 	#define findsym(lib, sym)		dlsym(lib, sym)
    58 	#define PLATFORM_EXT			".so"
    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 	#define TF_PATH					"/tf/"
    67 	#define DOD_PATH				"/dod/"
    68 #endif
    69 
    70 #define METAMOD_API_MAJOR			2
    71 #define FILENAME_1_4_EP1			"sourcemod.1.ep1" PLATFORM_EXT
    72 #define FILENAME_1_6_EP2			"sourcemod.2.ep2" PLATFORM_EXT
    73 #define FILENAME_1_6_EP2VALVE		"sourcemod.2.ep2v" PLATFORM_EXT
    74 #define FILENAME_1_6_EP1			"sourcemod.2.ep1" PLATFORM_EXT
    75 #define FILENAME_1_6_L4D			"sourcemod.2.l4d" PLATFORM_EXT
    76 #define FILENAME_1_6_DARKM			"sourcemod.2.darkm" PLATFORM_EXT
    77 
    78 HINSTANCE g_hCore = NULL;
    79 bool load_attempted = false;
    80 
    81 size_t UTIL_Format(char *buffer, size_t maxlength, const char *fmt, ...);
    82 
    83 class FailPlugin : public SourceMM::ISmmFailPlugin
    84 {
    85 public:
    86 	int GetApiVersion()
    87 	{
    88 		return fail_version;
    89 	}
    90 
    91 	bool Load(SourceMM::PluginId id, SourceMM::ISmmAPI *ismm, char *error, size_t maxlength, bool late)
    92 	{
    93 		if (error != NULL && maxlength != 0)
    94 		{
    95 			UTIL_Format(error, maxlength, "%s", error_buffer);
    96 		}
    97 		return false;
    98 	}
    99 
   100 	int fail_version;
   101 	char error_buffer[512];
   102 } s_FailPlugin;
   103 
   104 size_t UTIL_Format(char *buffer, size_t maxlength, const char *fmt, ...)
   105 {
   106 	va_list ap;
   107 
   108 	va_start(ap, fmt);
   109 	size_t len = vsnprintf(buffer, maxlength, fmt, ap);
   110 	va_end(ap);
   111 
   112 	if (len >= maxlength)
   113 	{
   114 		len = maxlength - 1;
   115 		buffer[len] = '\0';
   116 	}
   117 
   118 	return len;
   119 }
   120 
   121 METAMOD_PLUGIN *_GetPluginPtr(const char *path, int fail_api)
   122 {
   123 	METAMOD_FN_ORIG_LOAD fn;
   124 	METAMOD_PLUGIN *pl;
   125 	int ret;
   126 
   127 	if (!(g_hCore=openlib(path)))
   128 	{
   129 #if defined __linux__ || defined __APPLE__
   130 		UTIL_Format(s_FailPlugin.error_buffer, 
   131 			sizeof(s_FailPlugin.error_buffer),
   132 			"%s",
   133 			dlerror());
   134 #else
   135 		DWORD err = GetLastError();
   136 
   137 		if (FormatMessageA(
   138 				FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
   139 				NULL,
   140 				err,
   141 				MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
   142 				s_FailPlugin.error_buffer,
   143 				sizeof(s_FailPlugin.error_buffer),
   144 				NULL)
   145 			== 0)
   146 		{
   147 			UTIL_Format(s_FailPlugin.error_buffer, 
   148 				sizeof(s_FailPlugin.error_buffer),
   149 				"unknown error %x",
   150 				err);
   151 		}
   152 #endif
   153 
   154 		s_FailPlugin.fail_version = fail_api;
   155 
   156 		return (METAMOD_PLUGIN *)&s_FailPlugin;
   157 	}
   158 
   159 	if (!(fn=(METAMOD_FN_ORIG_LOAD)findsym(g_hCore, "CreateInterface")))
   160 	{
   161 		goto error;
   162 	}
   163 
   164 	pl = (METAMOD_PLUGIN *)fn(METAMOD_PLAPI_NAME, &ret);
   165 	if (!pl)
   166 	{
   167 		goto error;
   168 	}
   169 
   170 	return pl;
   171 error:
   172 	closelib(g_hCore);
   173 	g_hCore = NULL;
   174 	return NULL;
   175 }
   176 
   177 bool GetFileOfAddress(void *pAddr, char *buffer, size_t maxlength)
   178 {
   179 #if defined _MSC_VER
   180 	MEMORY_BASIC_INFORMATION mem;
   181 	if (!VirtualQuery(pAddr, &mem, sizeof(mem)))
   182 		return false;
   183 	if (mem.AllocationBase == NULL)
   184 		return false;
   185 	HMODULE dll = (HMODULE)mem.AllocationBase;
   186 	GetModuleFileName(dll, (LPTSTR)buffer, maxlength);
   187 #else
   188 	Dl_info info;
   189 	if (!dladdr(pAddr, &info))
   190 		return false;
   191 	if (!info.dli_fbase || !info.dli_fname)
   192 		return false;
   193 	const char *dllpath = info.dli_fname;
   194 	snprintf(buffer, maxlength, "%s", dllpath);
   195 #endif
   196 	return true;
   197 }
   198 
   199 DLL_EXPORT METAMOD_PLUGIN *CreateInterface_MMS(const MetamodVersionInfo *mvi, const MetamodLoaderInfo *mli)
   200 {
   201 	char *filename;
   202 
   203 	load_attempted = true;
   204 	
   205 	if (mvi->api_major > METAMOD_API_MAJOR)
   206 	{
   207 		return NULL;
   208 	}
   209 
   210 	switch (mvi->source_engine)
   211 	{
   212 	case SOURCE_ENGINE_ORIGINAL:
   213 	case SOURCE_ENGINE_EPISODEONE:
   214 		{
   215 			filename = FILENAME_1_6_EP1;
   216 			break;
   217 		}
   218 	case SOURCE_ENGINE_ORANGEBOX:
   219 		{
   220 			if (strstr(mli->pl_path, TF_PATH) || strstr(mli->pl_path, DOD_PATH))
   221 			{
   222 				filename = FILENAME_1_6_EP2VALVE;
   223 				break;
   224 			}
   225 
   226 			filename = FILENAME_1_6_EP2;
   227 			break;
   228 		}
   229 	case SOURCE_ENGINE_LEFT4DEAD:
   230 		{
   231 			filename = FILENAME_1_6_L4D;
   232 			break;
   233 		}
   234 	case SOURCE_ENGINE_DARKMESSIAH:
   235 		{
   236 			filename = FILENAME_1_6_DARKM;
   237 			break;
   238 		}
   239 	default:
   240 		{
   241 			return NULL;
   242 		}
   243 	}
   244 
   245 	char abspath[256];
   246 	UTIL_Format(abspath, sizeof(abspath), "%s" PATH_SEP_CHAR "%s", mli->pl_path, filename);
   247 
   248 	return _GetPluginPtr(abspath, METAMOD_FAIL_API_V2);
   249 }
   250 
   251 DLL_EXPORT void UnloadInterface_MMS()
   252 {
   253 	if (g_hCore)
   254 	{
   255 		closelib(g_hCore);
   256 		g_hCore = NULL;
   257 	}
   258 }
   259 
   260 DLL_EXPORT void *CreateInterface(const char *iface, int *ret)
   261 {
   262 	/**
   263 	 * If a load has already been attempted, bail out immediately.
   264 	 */
   265 	if (load_attempted)
   266 	{
   267 		return NULL;
   268 	}
   269 
   270 	if (strcmp(iface, METAMOD_PLAPI_NAME) == 0)
   271 	{
   272 		char thisfile[256];
   273 		char targetfile[256];
   274 
   275 		if (!GetFileOfAddress((void *)CreateInterface_MMS, thisfile, sizeof(thisfile)))
   276 		{
   277 			return NULL;
   278 		}
   279 
   280 		size_t len = strlen(thisfile);
   281 		for (size_t iter=len-1; iter>=0 && iter<len; iter--)
   282 		{
   283 			if (IsPathSepChar(thisfile[iter]))
   284 			{
   285 				thisfile[iter] = '\0';
   286 				break;
   287 			}
   288 		}
   289 
   290 		UTIL_Format(targetfile, sizeof(targetfile), "%s" PATH_SEP_CHAR FILENAME_1_4_EP1, thisfile);
   291 
   292 		return _GetPluginPtr(targetfile, METAMOD_FAIL_API_V1);
   293 	}
   294 
   295 	return NULL;
   296 }
   297 
   298 #if defined _MSC_VER
   299 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)
   300 {
   301 	if (fdwReason == DLL_PROCESS_DETACH)
   302 	{
   303 		UnloadInterface_MMS();
   304 	}
   305 	return TRUE;
   306 }
   307 #else
   308 __attribute__((destructor)) static void gcc_fini()
   309 {
   310 	UnloadInterface_MMS();
   311 }
   312 #endif
   313 
   314 /* Overload a few things to prevent libstdc++ linking */
   315 #if defined __linux__ || defined __APPLE__
   316 extern "C" void __cxa_pure_virtual(void)
   317 {
   318 }
   319 
   320 void *operator new(size_t size)
   321 {
   322 	return malloc(size);
   323 }
   324 
   325 void *operator new[](size_t size)
   326 {
   327 	return malloc(size);
   328 }
   329 
   330 void operator delete(void *ptr)
   331 {
   332 	free(ptr);
   333 }
   334 
   335 void operator delete[](void * ptr)
   336 {
   337 	free(ptr);
   338 }
   339 #endif
   340 
   341