core-legacy/CSmmAPI.cpp
author Scott Ehlert <ds@alliedmods.net>
Thu Dec 10 00:59:50 2009 -0600 (2009-12-10)
changeset 689 4065ba5e9155
parent 683 b507295429f9
child 714 966f819588a2
permissions -rw-r--r--
Rewrote user message caching code to always use IServerGameDLL::GetUserMessageInfo (bug 4117, r=dvander).

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