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