core-legacy/CSmmAPI.cpp
author David Anderson <dvander@alliedmods.net>
Thu Oct 29 02:37:52 2009 -0400 (2009-10-29)
changeset 663 e07fd1dc5290
parent 659 b35a5fdbc654
child 665 c2ed9ba7f74c
permissions -rw-r--r--
Fixed circular dependency between sourcemm.h/util.h (build bustage).
     1 /* ======== SourceMM ========
     2  * Copyright (C) 2004-2008 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 #include "vsp_listener.h"
    17 #include "util.h"
    18 
    19 /**
    20  * @brief Implementation of main API interface
    21  * @file CSmmAPI.cpp
    22  */
    23 
    24 using namespace SourceMM;
    25 
    26 CSmmAPI g_SmmAPI;
    27 
    28 CSmmAPI::CSmmAPI()
    29 {
    30 	m_ConPrintf = NULL;
    31 	m_CmdCache = false;
    32 	m_MsgCount = -1;
    33 	m_VSP = false;
    34 }
    35 
    36 CSmmAPI::~CSmmAPI()
    37 {
    38 	m_UserMessages.RemoveAll();
    39 }
    40 
    41 void CSmmAPI::LogMsg(ISmmPlugin *pl, const char *msg, ...)
    42 {
    43 	va_list ap;
    44 	static char buffer[2048];
    45 
    46 	va_start(ap, msg);
    47 	UTIL_FormatArgs(buffer, sizeof(buffer), msg, ap);
    48 	va_end(ap);
    49 
    50 	LogMessage("[%s] %s", pl->GetLogTag(), buffer);
    51 }
    52 
    53 CreateInterfaceFn CSmmAPI::engineFactory(bool syn)
    54 {
    55 	if (syn)
    56 		return EngineFactory;
    57 	return g_Engine.engineFactory;
    58 }
    59 
    60 CreateInterfaceFn CSmmAPI::physicsFactory(bool syn)
    61 {
    62 	if (syn)
    63 		return PhysicsFactory;
    64 	return g_Engine.physicsFactory;
    65 }
    66 
    67 CreateInterfaceFn CSmmAPI::fileSystemFactory(bool syn)
    68 {
    69 	if (syn)
    70 		return FileSystemFactory;
    71 	return g_Engine.fileSystemFactory;
    72 }
    73 
    74 CreateInterfaceFn CSmmAPI::serverFactory(bool syn)
    75 {
    76 	if (syn)
    77 		return ServerFactory;
    78 	return g_GameDll.factory;
    79 }
    80 
    81 CGlobalVars *CSmmAPI::pGlobals()
    82 {
    83 	return g_Engine.pGlobals;
    84 }
    85 
    86 void CSmmAPI::SetLastMetaReturn(META_RES res)
    87 {
    88 	m_Res = res;
    89 }
    90 
    91 META_RES CSmmAPI::GetLastMetaReturn()
    92 {
    93 	return m_Res;
    94 }
    95 
    96 IConCommandBaseAccessor *CSmmAPI::GetCvarBaseAccessor()
    97 {
    98 	return static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor);
    99 }
   100 
   101 bool CSmmAPI::RegisterConCmdBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
   102 {
   103 	if (pCommand->IsCommand())
   104 	{
   105 		g_PluginMngr.AddPluginCmd(plugin, pCommand);
   106 	} else {
   107 		g_PluginMngr.AddPluginCvar(plugin, pCommand);
   108 	}
   109 
   110 	return g_SMConVarAccessor.Register(pCommand);
   111 }
   112 
   113 void CSmmAPI::UnregisterConCmdBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
   114 {
   115 	if (pCommand->IsCommand())
   116 	{
   117 		g_PluginMngr.RemovePluginCmd(plugin, pCommand);
   118 	} else {
   119 		g_PluginMngr.RemovePluginCvar(plugin, pCommand);
   120 	}
   121 
   122 	g_SMConVarAccessor.Unregister(pCommand);
   123 }
   124 
   125 void CSmmAPI::ConPrint(const char *fmt)
   126 {
   127 	(m_ConPrintf)("%s", fmt);
   128 }
   129 
   130 void CSmmAPI::ConPrintf(const char *fmt, ...)
   131 {
   132 	va_list ap;
   133 	static char buffer[4096];
   134 
   135 	va_start(ap, fmt);
   136 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   137 	va_end(ap);
   138 
   139 	(m_ConPrintf)("%s", buffer);
   140 }
   141 
   142 void CSmmAPI::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
   143 {
   144 	CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
   145 	CPluginEventHandler cpeh;
   146 
   147 	cpeh.event = pListener;
   148 	cpeh.got_vsp = false;
   149 
   150 	pl->m_Events.push_back(cpeh);
   151 }
   152 
   153 void *CSmmAPI::MetaFactory(const char *iface, int *_ret, PluginId *id)
   154 {
   155 	if (id)
   156 	{
   157 		*id = 0;
   158 	}
   159 
   160 	if (!iface)
   161 	{
   162 		return NULL;
   163 	}
   164 
   165 	//first check ours... we get first chance!
   166 	if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
   167 	{
   168 		if (_ret)
   169 		{
   170 			*_ret = IFACE_OK;
   171 		}
   172 		return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
   173 	} else if (strcmp(iface, MMIFACE_PLMANAGER) == 0) {
   174 		if (_ret)
   175 		{
   176 			*_ret = IFACE_OK;
   177 		}
   178 		return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
   179 	}
   180 
   181 	CPluginManager::CPlugin *pl;
   182 	SourceHook::List<CPluginEventHandler>::iterator event;
   183 	IMetamodListener *api;
   184 	int ret = 0;
   185 	void *val = NULL;
   186 
   187 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++)
   188 	{
   189 		pl = (*iter);
   190 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++)
   191 		{
   192 			api = (*event).event;
   193 			ret = IFACE_FAILED;
   194 			if ( (val=api->OnMetamodQuery(iface, &ret)) != NULL )
   195 			{
   196 				if (_ret)
   197 					*_ret = ret;
   198 				if (id)
   199 					*id = pl->m_Id;
   200 				return val;
   201 			}
   202 		}
   203 	}
   204 
   205 	if (_ret)
   206 		*_ret = IFACE_FAILED;
   207 
   208 	return NULL;
   209 }
   210 
   211 //////////////////////////////////////////////////////////////////////////
   212 //THERE BE HAX HERE!!!! DON'T TELL ALFRED, BUT GABE WANTED IT THAT WAY. //
   213 // (note: you can find the offset by looking for the text               //
   214 //   "Echo text to console", you'll find the callback cmd pushed on the //
   215 //   stack.)                                                            //
   216 //////////////////////////////////////////////////////////////////////////
   217 
   218 #define SIGLEN			8
   219 #define ENGINE486_SIG	"\x55\x89\xE5\x53\x83\xEC\x14\xBB"
   220 #define ENGINE486_OFFS	40
   221 #define ENGINE686_SIG	"\x53\x83\xEC\x08\xBB\x01\x00\x00"
   222 #define ENGINE686_OFFS	50
   223 #define	ENGINEAMD_SIG	"\x53\x51\xBB\x01\x00\x00\x00\x51"
   224 #define	ENGINEAMD_OFFS	47
   225 #define ENGINEW32_SIG	"\xA1\x2A\x2A\x2A\x2A\x56\xBE\x01"
   226 #define ENGINEW32_OFFS	38
   227 #define IA32_CALL		0xE8
   228 
   229 //Thanks to fysh for the idea of extracting info from "echo" and for
   230 // having the original offsets at hand!
   231 bool CSmmAPI::CacheCmds()
   232 {
   233 	ICvar *pCvar = g_Engine.icvar;
   234 
   235 	ConCommandBase *pBase = pCvar->GetCommands();
   236 	unsigned char *ptr = NULL;
   237 	FnCommandCallback callback = NULL;
   238 	int offs = 0;
   239 
   240 	while (pBase)
   241 	{
   242 		if ( strcmp(pBase->GetName(), "echo") == 0 )
   243 		{
   244 			//callback = //*((FnCommandCallback *)((char *)pBase + offsetof(ConCommand, m_fnCommandCallback)));
   245 			callback = ((ConCommand *)pBase)->GetCallback();
   246 			ptr = (unsigned char *)callback;
   247 		#ifdef OS_LINUX
   248 			if (UTIL_VerifySignature(ptr, ENGINE486_SIG, SIGLEN))
   249 			{
   250 				offs = ENGINE486_OFFS;
   251 			}
   252 			else if (UTIL_VerifySignature(ptr, ENGINE686_SIG, SIGLEN))
   253 			{
   254 				offs = ENGINE686_OFFS;
   255 			}
   256 			else if (UTIL_VerifySignature(ptr, ENGINEAMD_SIG, SIGLEN))
   257 			{
   258 				offs = ENGINEAMD_OFFS;
   259 			}
   260 		#elif defined OS_WIN32 // Only one Windows engine binary so far...
   261 			if (UTIL_VerifySignature(ptr, ENGINEW32_SIG, SIGLEN))
   262 			{
   263 				offs = ENGINEW32_OFFS;
   264 			}
   265 		#endif
   266 
   267 			if (!offs || ptr[offs - 1] != IA32_CALL)
   268 			{
   269 				m_ConPrintf = (CONPRINTF_FUNC)Msg;
   270 				return false;
   271 			}
   272 			//get the relative offset
   273 			m_ConPrintf = *((CONPRINTF_FUNC *)(ptr + offs));
   274 			//add the base offset, to the ip (which is the address+offset + 4 bytes for next instruction)
   275 			m_ConPrintf = (CONPRINTF_FUNC)((unsigned long)m_ConPrintf + (unsigned long)(ptr + offs) + 4);
   276 
   277 			m_CmdCache = true;
   278 
   279 			return true;
   280 		}
   281 		pBase = const_cast<ConCommandBase *>(pBase->GetNext());
   282 	}
   283 
   284 	m_ConPrintf = (CONPRINTF_FUNC)Msg;
   285 
   286 	return false;
   287 }
   288 
   289 bool CSmmAPI::CmdCacheSuccessful()
   290 {
   291 	return m_CmdCache;
   292 }
   293 
   294 void CSmmAPI::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
   295 {
   296 	major = SM_VERS_API_MAJOR;
   297 	minor = SM_VERS_API_MINOR;
   298 	plvers = PLAPI_VERSION;
   299 	plmin = PLAPI_MIN_VERSION;
   300 }
   301 
   302 void CSmmAPI::GetShVersions(int &shvers, int &shimpl)
   303 {
   304 	shvers = SH_IFACE_VERSION;
   305 	shimpl = SH_IMPL_VERSION;
   306 }
   307 
   308 int CSmmAPI::FormatIface(char iface[], unsigned int maxlength)
   309 {
   310 	int length = (int)strlen(iface);
   311 	int i;
   312 	int num = 0;
   313 
   314 	for (i = length - 1; i >= 0; i--)
   315 	{
   316 		if (!isdigit(iface[i]))
   317 		{
   318 			if (i != length - 1)
   319 			{
   320 				num = 1;
   321 			}
   322 			break;
   323 		}
   324 	}
   325 
   326 	if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
   327 	{
   328 		return -1;
   329 	}
   330 
   331 	if (i != length - 1)
   332 		num = atoi(&(iface[++i]));
   333 
   334 	num++;
   335 
   336 	snprintf(&(iface[i]), 4, "%03d", num);
   337 
   338 	return num;
   339 }
   340 
   341 void *CSmmAPI::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
   342 {
   343 	char _if[256];	/* assume no interface goes beyond this */
   344 	size_t len = strlen(iface);
   345 	int num = 0;
   346 	void *pf = NULL;
   347 
   348 	if (max > 999)
   349 		max = 999;
   350 
   351 	if (len + 4 > sizeof(_if))
   352 	{
   353 		if (ret)
   354 		{
   355 			*ret = IFACE_FAILED;
   356 		}
   357 		return NULL;
   358 	}
   359 
   360 	strcpy(_if, iface);
   361 
   362 	do
   363 	{
   364 		if ( (pf = (fn)(_if, ret)) != NULL )
   365 			break;
   366 		if (num > max)
   367 			break;
   368 	} while (( num = FormatIface(_if, len+1) ));
   369 
   370 	return pf;
   371 }
   372 
   373 void *CSmmAPI::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
   374 {
   375 	char buffer[256];	/* assume no interface will go beyond this */
   376 	size_t len = strlen(iface);
   377 	int ret;			/* just in case something doesn't handle NULL properly */
   378 
   379 	if (len > sizeof(buffer) - 4)
   380 	{
   381 		return NULL;
   382 	}
   383 
   384 	strcpy(buffer, iface);
   385 
   386 	if (min != -1)
   387 	{
   388 		char *ptr = &buffer[len - 1];
   389 		int digits = 0;
   390 		while (isdigit(*ptr) && digits <=3)
   391 		{
   392 			*ptr = '\0';
   393 			digits++;
   394 			ptr--;
   395 		}
   396 		if (digits != 3)
   397 		{
   398 			/* for now, assume this is an error */
   399 			strcpy(buffer, iface);
   400 		} else {
   401 			char num[4];
   402 			min = (min == 0) ? 1 : min;
   403 			snprintf(num, sizeof(num), "%03d", min);
   404 			strcat(buffer, num);
   405 		}
   406 	}
   407 
   408 	return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
   409 }
   410 
   411 const char *CSmmAPI::GetBaseDir()
   412 {
   413 	return g_ModPath.c_str();
   414 }
   415 
   416 void CSmmAPI::PathFormat(char *buffer, size_t len, const char *fmt, ...)
   417 {
   418 	va_list ap;
   419 	va_start(ap, fmt);
   420 	size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
   421 	va_end(ap);
   422 
   423 	for (size_t i = 0; i < mylen; i++)
   424 	{
   425 		if (buffer[i] == ALT_SEP_CHAR)
   426 		{
   427 			buffer[i] = PATH_SEP_CHAR;
   428 		}
   429 	}
   430 }
   431 
   432 void CSmmAPI::ClientConPrintf(edict_t *client, const char *fmt, ...)
   433 {
   434 	va_list ap;
   435 	static char buffer[4096];
   436 
   437 	va_start(ap, fmt);
   438 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   439 	va_end(ap);
   440 
   441 	g_Engine.engine->ClientPrintf(client, buffer);
   442 }
   443 
   444 void CSmmAPI::LoadAsVSP()
   445 {
   446 	size_t len;
   447 	char engine_file[PATH_SIZE];
   448 	char rel_path[PATH_SIZE * 2];
   449 
   450 	GetFileOfAddress(g_Engine.engine, engine_file, sizeof(engine_file));
   451 
   452 	/* Chop off the "engine" file part */
   453 	len = strlen(engine_file);
   454 	for (size_t i = len - 1; i >= 0 && i < len; i--)
   455 	{
   456 		if (engine_file[i] == '/'
   457 			|| engine_file[i] == '\\')
   458 		{
   459 			engine_file[i] = '\0';
   460 			break;
   461 		}
   462 	}
   463 
   464 	char our_path[PATH_SIZE];
   465 	GetFileOfAddress((void*)LoadAsGameDLL, our_path, sizeof(our_path));
   466 
   467 	const char *usepath = our_path;
   468 	if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_file, our_path))
   469 		usepath = rel_path;
   470 	
   471 	char command[PATH_SIZE * 2];
   472 	g_VspListener.SetLoadable(true);
   473 	UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
   474 	g_Engine.engine->ServerCommand(command);
   475 }
   476 
   477 void CSmmAPI::EnableVSPListener()
   478 {
   479 	/* If GameInit already passed and we're not already enabled or loaded, go ahead and LoadAsVSP load */
   480 	if (g_bGameInit && !m_VSP && !g_VspListener.IsLoaded() && !g_bIsBridgedAsVsp)
   481 	{
   482 		LoadAsVSP();
   483 	}
   484 	m_VSP = true;
   485 }
   486 
   487 int CSmmAPI::GetGameDLLVersion()
   488 {
   489 	return g_GameDllVersion;
   490 }
   491 
   492 //////////////////////////////////////////////////////////////////////
   493 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED!                      //
   494 // Signatures necessary in finding the pointer to the CUtlDict that //
   495 //   stores user message information.                               //
   496 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad   //
   497 //   message indices. This is our answer to it. Yuck! <:-(          //
   498 //////////////////////////////////////////////////////////////////////
   499 #ifdef OS_WIN32
   500 	/* General Windows sig */
   501 	#define MSGCLASS_SIGLEN		7
   502 	#define MSGCLASS_SIG		"\x8B\x0D\x2A\x2A\x2A\x2A\x56"
   503 	#define MSGCLASS_OFFS		2
   504 
   505 	/* Dystopia Wimdows hack */
   506 	#define MSGCLASS2_SIGLEN	16
   507 	#define MSGCLASS2_SIG		"\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
   508 	#define MSGCLASS2_OFFS		11
   509 
   510 	/* Windows frame pointer sig */
   511 	#define MSGCLASS3_SIGLEN	18
   512 	#define MSGCLASS3_SIG		"\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
   513 	#define MSGCLASS3_OFFS		13
   514 #elif defined OS_LINUX
   515 	/* No frame pointer sig */
   516 	#define MSGCLASS_SIGLEN		14
   517 	#define MSGCLASS_SIG		"\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
   518 	#define MSGCLASS_OFFS		9
   519 
   520 	/* Frame pointer sig */
   521 	#define MSGCLASS2_SIGLEN	16
   522 	#define MSGCLASS2_SIG		"\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
   523 	#define MSGCLASS2_OFFS		11
   524 #endif
   525 
   526 /* This is the ugliest function in all of SourceMM */
   527 /* :TODO: Make this prettier */
   528 bool CSmmAPI::CacheUserMessages()
   529 {
   530 	UserMsgDict *dict = NULL;
   531 	char *vfunc = UTIL_GetOrigFunction(&IServerGameDLL::GetUserMessageInfo, g_GameDll.pGameDLL);
   532 
   533 	if (!vfunc)
   534 	{
   535 		return false;
   536 	}
   537 
   538 	if (UTIL_VerifySignature(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
   539 	{
   540 		/* Get address of CUserMessages instance */
   541 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
   542 
   543 		/* Get address of CUserMessages::m_UserMessages */
   544 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   545 	} else if (UTIL_VerifySignature(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN)) {
   546 	#ifdef OS_WIN32
   547 		/* If we get here, the code is possibly inlined like in Dystopia */
   548 
   549 		/* Get the address of the CUtlRBTree */
   550 		char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
   551 
   552 		/* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
   553 		dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
   554 	#elif defined OS_LINUX
   555 		/* Get address of CUserMessages instance */
   556 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
   557 
   558 		/* Get address of CUserMessages::m_UserMessages */
   559 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   560 	#endif
   561 	#ifdef OS_WIN32
   562 	} else if (UTIL_VerifySignature(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN)) {
   563 		/* Get address of CUserMessages instance */
   564 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
   565 
   566 		/* Get address of CUserMessages::m_UserMessages */
   567 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   568 	#endif
   569 	}
   570 
   571 	if (dict)
   572 	{
   573 		m_MsgCount = dict->Count();
   574 
   575 		/* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
   576 		if (m_MsgCount < 0 || m_MsgCount > 255)
   577 		{
   578 			m_MsgCount = -1;
   579 			return false;
   580 		}
   581 
   582 		UserMessage *msg;
   583 
   584 		/* Cache messages in our CUtlDict */
   585 		for (int i = 0; i < m_MsgCount; i++)
   586 		{
   587 			msg = dict->Element(i);
   588 			m_UserMessages.Insert(msg->name, msg);
   589 		}
   590 
   591 		return true;
   592 	}
   593 
   594 	return false;
   595 }
   596 
   597 bool CSmmAPI::MsgCacheSuccessful()
   598 {
   599 	return m_MsgCount > -1;
   600 }
   601 
   602 int CSmmAPI::GetUserMessageCount()
   603 {
   604 	return m_MsgCount;
   605 }
   606 
   607 int CSmmAPI::FindUserMessage(const char *name, int *size)
   608 {
   609 	int index = m_UserMessages.Find(name);
   610 
   611 	if (size && index > -1)
   612 	{
   613 		UserMessage *msg = m_UserMessages.Element(index);
   614 		*size = msg->size;
   615 	}
   616 
   617 	return index;
   618 }
   619 
   620 const char *CSmmAPI::GetUserMessage(int index, int *size)
   621 {
   622 	if (m_MsgCount <= 0 || index < 0 || index >= m_MsgCount)
   623 	{
   624 		return NULL;
   625 	}
   626 
   627 	UserMessage *msg = m_UserMessages.Element(index);
   628 
   629 	if (size)
   630 	{
   631 		*size = msg->size;
   632 	}
   633 
   634 	return msg->name;
   635 }