loader/loader.cpp
author Fyren <fyrenmoo@gmail.com>
Fri Oct 30 13:26:13 2009 +1300 (2009-10-30)
changeset 2847 1daf209d9dd2
parent 2782 57d431498ac3
child 2860 d8f31a35b1cb
permissions -rw-r--r--
Inital SM fixes for l4d2 and linux makefile updates
     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 #define FILENAME_1_6_L4D2			"sourcemod.2.l4d2" 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 	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 			if (strstr(mli->pl_path, TF_PATH) || strstr(mli->pl_path, DOD_PATH))
   222 			{
   223 				filename = FILENAME_1_6_EP2VALVE;
   224 				break;
   225 			}
   226 
   227 			filename = FILENAME_1_6_EP2;
   228 			break;
   229 		}
   230 	case SOURCE_ENGINE_LEFT4DEAD:
   231 		{
   232 			filename = FILENAME_1_6_L4D;
   233 			break;
   234 		}
   235 	case SOURCE_ENGINE_DARKMESSIAH:
   236 		{
   237 			filename = FILENAME_1_6_DARKM;
   238 			break;
   239 		}
   240 	case SOURCE_ENGINE_LEFT4DEAD2:
   241 		{
   242 			filename = FILENAME_1_6_L4D2;
   243 			break;
   244 		}
   245 	default:
   246 		{
   247 			return NULL;
   248 		}
   249 	}
   250 
   251 	char abspath[256];
   252 	UTIL_Format(abspath, sizeof(abspath), "%s" PATH_SEP_CHAR "%s", mli->pl_path, filename);
   253 
   254 	return _GetPluginPtr(abspath, METAMOD_FAIL_API_V2);
   255 }
   256 
   257 DLL_EXPORT void UnloadInterface_MMS()
   258 {
   259 	if (g_hCore)
   260 	{
   261 		closelib(g_hCore);
   262 		g_hCore = NULL;
   263 	}
   264 }
   265 
   266 DLL_EXPORT void *CreateInterface(const char *iface, int *ret)
   267 {
   268 	/**
   269 	 * If a load has already been attempted, bail out immediately.
   270 	 */
   271 	if (load_attempted)
   272 	{
   273 		return NULL;
   274 	}
   275 
   276 	if (strcmp(iface, METAMOD_PLAPI_NAME) == 0)
   277 	{
   278 		char thisfile[256];
   279 		char targetfile[256];
   280 
   281 		if (!GetFileOfAddress((void *)CreateInterface_MMS, thisfile, sizeof(thisfile)))
   282 		{
   283 			return NULL;
   284 		}
   285 
   286 		size_t len = strlen(thisfile);
   287 		for (size_t iter=len-1; iter>=0 && iter<len; iter--)
   288 		{
   289 			if (IsPathSepChar(thisfile[iter]))
   290 			{
   291 				thisfile[iter] = '\0';
   292 				break;
   293 			}
   294 		}
   295 
   296 		UTIL_Format(targetfile, sizeof(targetfile), "%s" PATH_SEP_CHAR FILENAME_1_4_EP1, thisfile);
   297 
   298 		return _GetPluginPtr(targetfile, METAMOD_FAIL_API_V1);
   299 	}
   300 
   301 	return NULL;
   302 }
   303 
   304 #if defined _MSC_VER
   305 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)
   306 {
   307 	if (fdwReason == DLL_PROCESS_DETACH)
   308 	{
   309 		UnloadInterface_MMS();
   310 	}
   311 	return TRUE;
   312 }
   313 #else
   314 __attribute__((destructor)) static void gcc_fini()
   315 {
   316 	UnloadInterface_MMS();
   317 }
   318 #endif
   319 
   320 /* Overload a few things to prevent libstdc++ linking */
   321 #if defined __linux__ || defined __APPLE__
   322 extern "C" void __cxa_pure_virtual(void)
   323 {
   324 }
   325 
   326 void *operator new(size_t size)
   327 {
   328 	return malloc(size);
   329 }
   330 
   331 void *operator new[](size_t size)
   332 {
   333 	return malloc(size);
   334 }
   335 
   336 void operator delete(void *ptr)
   337 {
   338 	free(ptr);
   339 }
   340 
   341 void operator delete[](void * ptr)
   342 {
   343 	free(ptr);
   344 }
   345 #endif
   346 
   347