sourcemm/CSmmAPI.cpp
author Scott Ehlert <ds@alliedmods.net>
Thu Feb 08 09:19:19 2007 +0000 (2007-02-08)
changeset 280 946485e00593
parent 278 614ea295cd25
child 282 7a237e9ea5a1
permissions -rw-r--r--
Renamed convar.h to convar_smm.h in order to avoid potential compiling problems with the order of include directories.
     1 /* ======== SourceMM ========
     2 * Copyright (C) 2004-2006 Metamod:Source Development Team
     3 * No warranties of any kind
     4 *
     5 * License: zlib/libpng
     6 *
     7 * Author(s): David "BAILOPAN" Anderson
     8 * ============================
     9 */
    10 
    11 #include "convar_smm.h"
    12 #include "CSmmAPI.h"
    13 #include "sourcemm.h"
    14 #include "concommands.h"
    15 #include "CPlugin.h"
    16 
    17 /**
    18  * @brief Implementation of main API interface
    19  * @file CSmmAPI.cpp
    20  */
    21 
    22 using namespace SourceMM;
    23 
    24 CSmmAPI g_SmmAPI;
    25 
    26 CSmmAPI::CSmmAPI()
    27 {
    28 	m_ConPrintf = NULL;
    29 	m_Cache = false;
    30 }
    31 
    32 void CSmmAPI::LogMsg(ISmmPlugin *pl, const char *msg, ...)
    33 {
    34 	va_list ap;
    35 	static char buffer[2048];
    36 
    37 	buffer[0] = '\0';
    38 
    39 	va_start(ap, msg);
    40 	vsnprintf(buffer, sizeof(buffer)-1, msg, ap);
    41 	va_end(ap);
    42 
    43 	LogMessage("[%s] %s", pl->GetLogTag(), buffer);
    44 }
    45 
    46 CreateInterfaceFn CSmmAPI::engineFactory(bool syn)
    47 {
    48 	if (syn)
    49 		return EngineFactory;
    50 	return g_Engine.engineFactory;
    51 }
    52 
    53 CreateInterfaceFn CSmmAPI::physicsFactory(bool syn)
    54 {
    55 	if (syn)
    56 		return PhysicsFactory;
    57 	return g_Engine.physicsFactory;
    58 }
    59 
    60 CreateInterfaceFn CSmmAPI::fileSystemFactory(bool syn)
    61 {
    62 	if (syn)
    63 		return FileSystemFactory;
    64 	return g_Engine.fileSystemFactory;
    65 }
    66 
    67 CreateInterfaceFn CSmmAPI::serverFactory(bool syn)
    68 {
    69 	if (syn)
    70 		return CreateInterface;
    71 	return g_GameDll.factory;
    72 }
    73 
    74 CGlobalVars *CSmmAPI::pGlobals()
    75 {
    76 	return g_Engine.pGlobals;
    77 }
    78 
    79 void CSmmAPI::SetLastMetaReturn(META_RES res)
    80 {
    81 	m_Res = res;
    82 }
    83 
    84 META_RES CSmmAPI::GetLastMetaReturn()
    85 {
    86 	return m_Res;
    87 }
    88 
    89 IConCommandBaseAccessor *CSmmAPI::GetCvarBaseAccessor()
    90 {
    91 	return static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor);
    92 }
    93 
    94 bool CSmmAPI::RegisterConCmdBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
    95 {
    96 	if (pCommand->IsCommand())
    97 	{
    98 		g_PluginMngr.AddPluginCmd(plugin, pCommand);
    99 	} else {
   100 		g_PluginMngr.AddPluginCvar(plugin, pCommand);
   101 	}
   102 
   103 	return g_SMConVarAccessor.Register(pCommand);
   104 }
   105 
   106 void CSmmAPI::UnregisterConCmdBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
   107 {
   108 	if (pCommand->IsCommand())
   109 	{
   110 		g_PluginMngr.RemovePluginCmd(plugin, pCommand);
   111 	} else {
   112 		g_PluginMngr.RemovePluginCvar(plugin, pCommand);
   113 	}
   114 
   115 	g_SMConVarAccessor.Unregister(pCommand);
   116 }
   117 
   118 void CSmmAPI::ConPrint(const char *fmt)
   119 {
   120 	(m_ConPrintf)("%s", fmt);
   121 }
   122 
   123 void CSmmAPI::ConPrintf(const char *fmt, ...)
   124 {
   125 	va_list ap;
   126 	static char buf[4096];
   127 	va_start(ap, fmt);
   128 	vsnprintf(buf, sizeof(buf)-1, fmt, ap);
   129 	ConPrint(buf);
   130 	va_end(ap);
   131 }
   132 
   133 void CSmmAPI::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
   134 {
   135 	CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
   136 
   137 	pl->m_Events.push_back(pListener);
   138 }
   139 
   140 void *CSmmAPI::MetaFactory(const char *iface, int *_ret, PluginId *id)
   141 {
   142 	if (id)
   143 		*id = 0;
   144 
   145 	if (!iface)
   146 		return NULL;
   147 
   148 	//first check ours... we get first chance!
   149 	if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
   150 	{
   151 		if (_ret)
   152 			*_ret = IFACE_OK;
   153 		return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
   154 	} else if (strcmp(iface, MMIFACE_PLMANAGER) == 0) {
   155 		if (_ret)
   156 			*_ret = IFACE_OK;
   157 		return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
   158 	}
   159 
   160 	CPluginManager::CPlugin *pl;
   161 	SourceHook::List<IMetamodListener *>::iterator event;
   162 	IMetamodListener *api;
   163 	int ret = 0;
   164 	void *val = NULL;
   165 
   166 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++)
   167 	{
   168 		pl = (*iter);
   169 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++)
   170 		{
   171 			api = (*event);
   172 			ret = IFACE_FAILED;
   173 			if ( (val=api->OnMetamodQuery(iface, &ret)) != NULL )
   174 			{
   175 				if (_ret)
   176 					*_ret = ret;
   177 				if (id)
   178 					*id = pl->m_Id;
   179 				return val;
   180 			}
   181 		}
   182 	}
   183 
   184 	if (_ret)
   185 		*_ret = IFACE_FAILED;
   186 
   187 	return NULL;
   188 }
   189 
   190 //////////////////////////////////////////////////////////////////////////
   191 //THERE BE HAX HERE!!!! DON'T TELL ALFRED, BUT GABE WANTED IT THAT WAY. //
   192 // (note: you can find the offset by looking for the text               //
   193 //   "Echo text to console", you'll find the callback cmd pushed on the //
   194 //   stack.)                                                            //
   195 //////////////////////////////////////////////////////////////////////////
   196 
   197 #define SIGLEN			8
   198 #define ENGINE486_SIG	"\x55\x89\xE5\x53\x83\xEC\x14\xBB"
   199 #define ENGINE486_OFFS	40
   200 #define ENGINE686_SIG	"\x53\x83\xEC\x08\xBB\x01\x00\x00"
   201 #define ENGINE686_OFFS	50
   202 #define	ENGINEAMD_SIG	"\x53\x51\xBB\x01\x00\x00\x00\x51"
   203 #define	ENGINEAMD_OFFS	47
   204 #define ENGINEW32_SIG	"\xA1\x2A\x2A\x2A\x2A\x56\xBE\x01"
   205 #define ENGINEW32_OFFS	38
   206 #define IA32_CALL		0xE8
   207 
   208 bool vcmp(const void *_addr1, const void *_addr2, size_t len)
   209 {
   210 	unsigned char *addr1 = (unsigned char *)_addr1;
   211 	unsigned char *addr2 = (unsigned char *)_addr2;
   212 
   213 	for (size_t i=0; i<len; i++)
   214 	{
   215 		if (addr2[i] == '*')
   216 			continue;
   217 		if (addr1[i] != addr2[i])
   218 			return false;
   219 	}
   220 
   221 	return true;
   222 }
   223 
   224 //Thanks to fysh for the idea of extracting info from "echo" and for
   225 // having the original offsets at hand!
   226 bool CSmmAPI::CacheCmds()
   227 {
   228 	ICvar *pCvar = g_Engine.icvar;
   229 
   230 	ConCommandBase *pBase = pCvar->GetCommands();
   231 	unsigned char *ptr = NULL;
   232 	FnCommandCallback callback = NULL;
   233 	int offs = 0;
   234 
   235 	while (pBase)
   236 	{
   237 		if ( strcmp(pBase->GetName(), "echo") == 0 )
   238 		{
   239 			//callback = //*((FnCommandCallback *)((char *)pBase + offsetof(ConCommand, m_fnCommandCallback)));
   240 			callback = ((ConCommand *)pBase)->GetCallback();
   241 			ptr = (unsigned char *)callback;
   242 		#ifdef OS_LINUX
   243 			if (vcmp(ptr, ENGINE486_SIG, SIGLEN))
   244 			{
   245 				offs = ENGINE486_OFFS;
   246 			}
   247 			else if (vcmp(ptr, ENGINE686_SIG, SIGLEN))
   248 			{
   249 				offs = ENGINE686_OFFS;
   250 			}
   251 			else if (vcmp(ptr, ENGINEAMD_SIG, SIGLEN))
   252 			{
   253 				offs = ENGINEAMD_OFFS;
   254 			}
   255 		#elif defined OS_WIN32 // Only one Windows engine binary so far...
   256 			if (vcmp(ptr, ENGINEW32_SIG, SIGLEN))
   257 			{
   258 				offs = ENGINEW32_OFFS;
   259 			}
   260 		#endif
   261 
   262 			if (!offs || ptr[offs-1] != IA32_CALL)
   263 			{
   264 				m_ConPrintf = (CONPRINTF_FUNC)Msg;
   265 				return false;
   266 			}
   267 			//get the relative offset
   268 			m_ConPrintf = *((CONPRINTF_FUNC *)(ptr + offs));
   269 			//add the base offset, to the ip (which is the address+offset + 4 bytes for next instruction)
   270 			m_ConPrintf = (CONPRINTF_FUNC)((unsigned long)m_ConPrintf + (unsigned long)(ptr + offs) + 4);
   271 
   272 			m_Cache = true;
   273 
   274 			return true;
   275 		}
   276 		pBase = const_cast<ConCommandBase *>(pBase->GetNext());
   277 	}
   278 
   279 	m_ConPrintf = (CONPRINTF_FUNC)Msg;
   280 
   281 	return false;
   282 }
   283 
   284 bool CSmmAPI::CacheSuccessful()
   285 {
   286 	return m_Cache;
   287 }
   288 
   289 void CSmmAPI::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
   290 {
   291 	major = SM_VERS_API_MAJOR;
   292 	minor = SM_VERS_API_MINOR;
   293 	plvers = PLAPI_VERSION;
   294 	plmin = PLAPI_MIN_VERSION;
   295 }
   296 
   297 void CSmmAPI::GetShVersions(int &shvers, int &shimpl)
   298 {
   299 	shvers = SH_IFACE_VERSION;
   300 	shimpl = SH_IMPL_VERSION;
   301 }
   302 
   303 int CSmmAPI::FormatIface(char iface[], unsigned int maxlength)
   304 {
   305 	int length = (int)strlen(iface);
   306 	int i;
   307 	int num = 0;
   308 
   309 	for (i=length-1; i>=0; i--)
   310 	{
   311 		if (!isdigit(iface[i]))
   312 		{
   313 			if (i != length-1)
   314 			{
   315 				num = 1;
   316 			}
   317 			break;
   318 		}
   319 	}
   320 
   321 	if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length+3)) )
   322 	{
   323 		return -1;
   324 	}
   325 
   326 	if (i != length-1)
   327 		num = atoi(&(iface[++i]));
   328 
   329 	num++;
   330 
   331 	snprintf(&(iface[i]), 4, "%03d", num);
   332 
   333 	return num;
   334 }
   335 
   336 void *CSmmAPI::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
   337 {
   338 	char _if[256];	/* assume no interface goes beyond this */
   339 	size_t len = strlen(iface);
   340 	int num = 0;
   341 	void *pf = NULL;
   342 
   343 	if (max > 999)
   344 		max = 999;
   345 
   346 	if (len + 4 > sizeof(_if))
   347 	{
   348 		if (ret)
   349 		{
   350 			*ret = IFACE_FAILED;
   351 		}
   352 		return NULL;
   353 	}
   354 
   355 	strcpy(_if, iface);
   356 
   357 	do
   358 	{
   359 		if ( (pf = (fn)(_if, ret)) != NULL )
   360 			break;
   361 		if (num > max)
   362 			break;
   363 	} while (( num = FormatIface(_if, len+1) ));
   364 
   365 	return pf;
   366 }
   367 
   368 void *CSmmAPI::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
   369 {
   370 	char buffer[256];	/* assume no interface will go beyond this */
   371 	int len = static_cast<int>(strlen(iface));
   372 	int ret;			/* just in case something doesn't handle NULL properly */
   373 
   374 	if (len > static_cast<int>(sizeof(buffer) - 4))
   375 	{
   376 		return NULL;
   377 	}
   378 
   379 	strcpy(buffer, iface);
   380 
   381 	if (min != -1)
   382 	{
   383 		char *ptr = &buffer[len-1];
   384 		int digits = 0;
   385 		while (isdigit(*ptr) && digits <=3)
   386 		{
   387 			*ptr = '\0';
   388 			digits++;
   389 			ptr--;
   390 		}
   391 		if (digits != 3)
   392 		{
   393 			/* for now, assume this is an error */
   394 			strcpy(buffer, iface);
   395 		} else {
   396 			char num[4];
   397 			min = (min == 0) ? 1 : min;
   398 			snprintf(num, sizeof(num), "%03d", min);
   399 			strcat(buffer, num);
   400 		}
   401 	}
   402 
   403 	return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
   404 }
   405 
   406 const char *CSmmAPI::GetBaseDir()
   407 {
   408 	return g_ModPath.c_str();
   409 }
   410 
   411 void CSmmAPI::PathFormat(char *buffer, size_t len, const char *fmt, ...)
   412 {
   413 	va_list ap;
   414 	va_start(ap,fmt);
   415 	size_t mylen = vsnprintf(buffer, len, fmt, ap);
   416 	va_end(ap);
   417 
   418 	if (mylen == 0xFFFFFFFF || mylen >= len)
   419 	{
   420 		mylen = len - 1;
   421 	}
   422 
   423 	for (size_t i=0; i<mylen; i++)
   424 	{
   425 		if (buffer[i] == ALT_SEP_CHAR)
   426 			buffer[i] = PATH_SEP_CHAR;
   427 	}
   428 }
   429 
   430 void CSmmAPI::ClientConPrintf(edict_t *client, const char *fmt, ...)
   431 {
   432 	va_list ap;
   433 	static char buf[4096];
   434 	va_start(ap, fmt);
   435 	vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
   436 	g_Engine.engine->ClientPrintf(client, buf);
   437 	va_end(ap);
   438 }