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