extensions/sdktools/output.cpp
author David Anderson <dvander@alliedmods.net>
Sat Apr 12 01:33:55 2008 +0000 (2008-04-12)
changeset 1992 4d48f66b2a77
parent 1990 de135d1f05b1
child 2026 03b4a9c4a70e
permissions -rw-r--r--
fixed crash bug on shutdown
removed implementations from header
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod SDKTools Extension
     5  * Copyright (C) 2004-2008 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 "extension.h"
    33 #include "output.h"
    34 
    35 ISourcePawnEngine *spengine = NULL;
    36 EntityOutputManager g_OutputManager;
    37 
    38 EntityOutputManager::EntityOutputManager()
    39 {
    40 	info_address = NULL;
    41 	info_callback = NULL;
    42 	HookCount = 0;
    43 	is_detoured = false;
    44 	enabled = false;
    45 }
    46 
    47 EntityOutputManager::~EntityOutputManager()
    48 {
    49 	if (!enabled)
    50 	{
    51 		return;
    52 	}
    53 
    54 	EntityOutputs->Destroy();
    55 	ClassNames->Destroy();
    56 	ShutdownFireEventDetour();
    57 }
    58 
    59 void EntityOutputManager::Init()
    60 {
    61 	enabled = CreateFireEventDetour();
    62 
    63 	if (!enabled)
    64 	{
    65 		return;
    66 	}
    67 
    68 	EntityOutputs = adtfactory->CreateBasicTrie();
    69 	ClassNames = adtfactory->CreateBasicTrie();
    70 }
    71 
    72 bool EntityOutputManager::IsEnabled()
    73 {
    74 	return enabled;
    75 }
    76 
    77 bool EntityOutputManager::CreateFireEventDetour()
    78 {
    79 	if (!g_pGameConf->GetMemSig("FireOutput", &info_address) || !info_address)
    80 	{
    81 		g_pSM->LogError(myself, "Could not locate FireOutput - Disabling Entity Outputs");
    82 		return false;
    83 	}
    84 
    85 	if (!g_pGameConf->GetOffset("FireOutputBackup", (int *)&(info_restore.bytes)))
    86 	{
    87 		g_pSM->LogError(myself, "Could not locate FireOutputBackup - Disabling Entity Outputs");
    88 		return false;
    89 	}
    90 
    91 	/* First, save restore bits */
    92 	for (size_t i=0; i<info_restore.bytes; i++)
    93 	{
    94 		info_restore.patch[i] = ((unsigned char *)info_address)[i];
    95 	}
    96 
    97 	info_callback = spengine->ExecAlloc(100);
    98 	JitWriter wr;
    99 	JitWriter *jit = &wr;
   100 	wr.outbase = (jitcode_t)info_callback;
   101 	wr.outptr = wr.outbase;
   102 
   103 	/* Function we are detouring into is
   104 	 *
   105 	 * void FireEventDetour(CBaseEntityOutput(void *) *pOutput, CBaseEntity *pActivator, CBaseEntity *pCaller, float fDelay = 0 )
   106 	 */
   107 
   108 	/* push		fDelay [esp+20h]
   109 	 * push		pCaller [esp+1Ch]
   110 	 * push		pActivator [esp+18h]
   111 	 * push		pOutput [ecx]
   112 	 */
   113 
   114 
   115 #if defined PLATFORM_WINDOWS
   116 
   117 	IA32_Push_Rm_Disp8_ESP(jit, 32);
   118 	IA32_Push_Rm_Disp8_ESP(jit, 32);
   119 	IA32_Push_Rm_Disp8_ESP(jit, 32);
   120 
   121 	/* variant_t doesnt do anything so i'll disable this bit */
   122 	//IA32_Push_Rm_Disp8_ESP(jit, 32);
   123 	//IA32_Push_Rm_Disp8_ESP(jit, 32);
   124 	//IA32_Push_Rm_Disp8_ESP(jit, 32);
   125 	//IA32_Push_Rm_Disp8_ESP(jit, 32); 
   126 	//IA32_Push_Rm_Disp8_ESP(jit, 32);
   127 
   128 	IA32_Push_Reg(jit, REG_ECX);
   129 
   130 #elif defined PLATFORM_LINUX
   131 	IA32_Push_Rm_Disp8_ESP(jit, 20);
   132 	IA32_Push_Rm_Disp8_ESP(jit, 20);
   133 	IA32_Push_Rm_Disp8_ESP(jit, 20);
   134 	// We miss the variant_t pointer
   135 	IA32_Push_Rm_Disp8_ESP(jit, 16);
   136 #endif
   137 
   138 	jitoffs_t call = IA32_Call_Imm32(jit, 0); 
   139 	IA32_Write_Jump32_Abs(jit, call, (void *)TempDetour);
   140 
   141 	
   142 #if defined PLATFORM_LINUX
   143 	IA32_Add_Rm_Imm8(jit, REG_ESP, 4, MOD_REG);		//add esp, 4
   144 #elif defined PLATFORM_WINDOWS
   145 	IA32_Pop_Reg(jit, REG_ECX);
   146 #endif
   147 
   148 	IA32_Add_Rm_Imm8(jit, REG_ESP, 12, MOD_REG);	//add esp, 12 (0Ch)
   149 
   150 
   151 	/* Patch old bytes in */
   152 	for (size_t i=0; i<info_restore.bytes; i++)
   153 	{
   154 		jit->write_ubyte(info_restore.patch[i]);
   155 	}
   156 
   157 	/* Return to the original function */
   158 	call = IA32_Jump_Imm32(jit, 0);
   159 	IA32_Write_Jump32_Abs(jit, call, (unsigned char *)info_address + info_restore.bytes);
   160 
   161 	return true;
   162 }
   163 
   164 void EntityOutputManager::InitFireEventDetour()
   165 {
   166 	if (!is_detoured)
   167 	{
   168 		DoGatePatch((unsigned char *)info_address, &info_callback);
   169 		is_detoured = true;
   170 	}
   171 }
   172 
   173 void EntityOutputManager::DeleteFireEventDetour()
   174 {
   175 	if (is_detoured)
   176 	{
   177 		ShutdownFireEventDetour();
   178 	}
   179 
   180 	if (info_callback)
   181 	{
   182 		/* Free the gate */
   183 		spengine->ExecFree(info_callback);
   184 		info_callback = NULL;
   185 	}
   186 }
   187 
   188 void TempDetour(void *pOutput, CBaseEntity *pActivator, CBaseEntity *pCaller, float fDelay)
   189 {
   190 	g_OutputManager.FireEventDetour(pOutput, pActivator, pCaller, fDelay);
   191 }
   192 
   193 void EntityOutputManager::ShutdownFireEventDetour()
   194 {
   195 	if (info_callback)
   196 	{
   197 		/* Remove the patch */
   198 		ApplyPatch(info_address, 0, &info_restore, NULL);
   199 		is_detoured = false;
   200 	}
   201 }
   202 
   203 void EntityOutputManager::FireEventDetour(void *pOutput, CBaseEntity *pActivator, CBaseEntity *pCaller, float fDelay)
   204 {
   205 	char sOutput[20];
   206 	Q_snprintf(sOutput, sizeof(sOutput), "%x", pOutput);
   207 
   208 	// attempt to directly lookup a hook using the pOutput pointer
   209 	OutputNameStruct *pOutputName = NULL;
   210 
   211 	edict_t *pEdict = gameents->BaseEntityToEdict(pCaller);
   212 
   213 	/* TODO: Add support for entities without an edict */
   214 	if (pEdict == NULL)
   215 	{
   216 		return;
   217 	}
   218 
   219 	bool fastLookup = false;
   220 	
   221 	// Fast lookup failed - check the slow way for hooks that havn't fired yet
   222 	if ((fastLookup = EntityOutputs->Retrieve(sOutput, (void **)&pOutputName)) == false)
   223 	{
   224 		const char *classname = pEdict->GetClassName();
   225 		const char *outputname = FindOutputName(pOutput, pCaller);
   226 
   227 		pOutputName = FindOutputPointer(classname, outputname, false);
   228 
   229 		if (!pOutputName)
   230 		{
   231 			return;
   232 		}
   233 	}
   234 
   235 	if (!pOutputName->hooks.empty())
   236 	{
   237 		if (!fastLookup)
   238 		{
   239 			// hook exists on this classname and output - map it into our quick find trie
   240 			EntityOutputs->Insert(sOutput, pOutputName);
   241 		}
   242 
   243 		SourceHook::List<omg_hooks *>::iterator _iter;
   244 
   245 		omg_hooks *hook;
   246 
   247 		_iter = pOutputName->hooks.begin();
   248 
   249 		while (_iter != pOutputName->hooks.end())
   250 		{
   251 			hook = (omg_hooks *)*_iter;
   252 
   253 			hook->in_use = true;
   254 
   255 			int serial = pEdict->m_NetworkSerialNumber;
   256 			
   257 			if (serial != hook->entity_filter && hook->entity_index == engine->IndexOfEdict(pEdict))
   258 			{
   259 				// same entity index but different serial number. Entity has changed, kill the hook.
   260 				_iter = pOutputName->hooks.erase(_iter);
   261 				CleanUpHook(hook);
   262 
   263 				continue;
   264 			}
   265 
   266 			if (hook->entity_filter == -1 || hook->entity_filter == serial) // Global classname hook
   267 			{
   268 				/*
   269 				Handle_t handle;
   270 
   271 				if (Value.FieldType() == FIELD_VOID)
   272 				{
   273 					handle = 0;
   274 				}
   275 				else
   276 				{
   277 					varhandle_t *varhandle = new varhandle_t;
   278 					memmove ((void *)&varhandle->crab, (void *)&Value, sizeof(variant_t));
   279 
   280 					handle = handlesys->CreateHandle(VariantHandle, (void *)varhandle, hook->pf->GetParentContext()->GetIdentity(), myself->GetIdentity(), NULL);
   281 				}
   282 				*/
   283 
   284 				//fire the forward to hook->pf
   285 				hook->pf->PushString(pOutputName->Name);
   286 				hook->pf->PushCell(engine->IndexOfEdict(pEdict));
   287 				
   288 				edict_t *pEdictActivator = gameents->BaseEntityToEdict(pActivator);
   289 				if (!pEdictActivator)
   290 				{
   291 					hook->pf->PushCell(-1);
   292 				}
   293 				else
   294 				{
   295 					hook->pf->PushCell(engine->IndexOfEdict(pEdictActivator));
   296 				}
   297 				//hook->pf->PushCell(handle);
   298 				hook->pf->PushFloat(fDelay);
   299 				hook->pf->Execute(NULL);
   300 
   301 				if ((hook->entity_filter != -1) && hook->only_once)
   302 				{
   303 					_iter = pOutputName->hooks.erase(_iter);
   304 					CleanUpHook(hook);
   305 
   306 					continue;
   307 				}
   308 
   309 				if (hook->delete_me)
   310 				{
   311 					_iter = pOutputName->hooks.erase(_iter);
   312 					CleanUpHook(hook);
   313 					continue;
   314 				}
   315 
   316 				hook->in_use = false;
   317 				_iter++;
   318 
   319 				continue;
   320 			}
   321 		}
   322 	}
   323 }
   324 
   325 omg_hooks *EntityOutputManager::NewHook()
   326 {
   327 	omg_hooks *hook;
   328 
   329 	if (FreeHooks.empty())
   330 	{
   331 		hook = new omg_hooks;
   332 	}
   333 	else
   334 	{
   335 		hook = g_OutputManager.FreeHooks.front();
   336 		g_OutputManager.FreeHooks.pop();
   337 	}
   338 
   339 	return hook;
   340 }
   341 
   342 void EntityOutputManager::OnHookAdded()
   343 {
   344 	HookCount++;
   345 
   346 	if (HookCount == 1)
   347 	{
   348 		// This is the first hook created
   349 		InitFireEventDetour();
   350 	}
   351 }
   352 
   353 void EntityOutputManager::OnHookRemoved()
   354 {
   355 	HookCount--;
   356 
   357 	if (HookCount == 0)
   358 	{
   359 		//we need to check if we are inside a detour. easy.
   360 		//if we are how do we 
   361 		ShutdownFireEventDetour();
   362 	}
   363 }
   364 
   365 void EntityOutputManager::CleanUpHook(omg_hooks *hook)
   366 {
   367 	FreeHooks.push(hook);
   368 
   369 	OnHookRemoved();
   370 
   371 	IPlugin *pPlugin = plsys->FindPluginByContext(hook->pf->GetParentContext()->GetContext());
   372 	SourceHook::List<omg_hooks *> *pList = NULL;
   373 
   374 	if (!pPlugin->GetProperty("OutputHookList", (void **)&pList, false) || !pList)
   375 	{
   376 		return;
   377 	}
   378 
   379 	SourceHook::List<omg_hooks *>::iterator p_iter = pList->begin();
   380 
   381 	omg_hooks *pluginHook;
   382 
   383 	while (p_iter != pList->end())
   384 	{
   385 		pluginHook = (omg_hooks *)*p_iter;
   386 		if (pluginHook == hook)
   387 		{
   388 			p_iter = pList->erase(p_iter);
   389 		}
   390 		else
   391 		{
   392 			p_iter++;
   393 		}
   394 	}
   395 }
   396 
   397 void EntityOutputManager::OnPluginDestroyed(IPlugin *plugin)
   398 {
   399 	SourceHook::List<omg_hooks *> *pList = NULL;
   400 
   401 	if (plugin->GetProperty("OutputHookList", (void **)&pList, true))
   402 	{
   403 		SourceHook::List<omg_hooks *>::iterator p_iter = pList->begin();
   404 		omg_hooks *hook;
   405 
   406 		while (p_iter != pList->end())
   407 		{
   408 			hook = (omg_hooks *)*p_iter;
   409 		
   410 			p_iter = pList->erase(p_iter); //remove from this plugins list
   411 			hook->m_parent->hooks.remove(hook); // remove from the y's list
   412 
   413 			FreeHooks.push(hook); //save the omg_hook
   414 
   415 			OnHookRemoved();
   416 		}		
   417 	}
   418 }
   419 
   420 OutputNameStruct *EntityOutputManager::FindOutputPointer(const char *classname, const char *outputname, bool create)
   421 {
   422 	ClassNameStruct *pClassname;
   423 	
   424 	if (!ClassNames->Retrieve(classname, (void **)&pClassname))
   425 	{
   426 		if (create)
   427 		{
   428 			pClassname = new ClassNameStruct;
   429 			ClassNames->Insert(classname, pClassname);
   430 		}
   431 		else
   432 		{
   433 			return NULL;
   434 		}
   435 	}
   436 
   437 	OutputNameStruct *pOutputName;
   438 
   439 	if (!pClassname->OutputList->Retrieve(outputname, (void **)&pOutputName))
   440 	{
   441 		if (create)
   442 		{
   443 			pOutputName = new OutputNameStruct;
   444 			pClassname->OutputList->Insert(outputname, pOutputName);
   445 			strncpy(pOutputName->Name, outputname, sizeof(pOutputName->Name));
   446 			pOutputName->Name[49] = 0;
   447 		}
   448 		else
   449 		{
   450 			return NULL;
   451 		}
   452 	}
   453 
   454 	return pOutputName;
   455 }
   456 
   457 // Iterate the datamap of pCaller and look for output pointers with the same address as pOutput
   458 const char *EntityOutputManager::FindOutputName(void *pOutput, CBaseEntity *pCaller)
   459 {
   460 	datamap_t *pMap = gamehelpers->GetDataMap(pCaller);
   461 
   462 	while (pMap)
   463 	{
   464 		for (int i=0; i<pMap->dataNumFields; i++)
   465 		{
   466 			if (pMap->dataDesc[i].flags & FTYPEDESC_OUTPUT)
   467 			{
   468 				if ((char *)pCaller + pMap->dataDesc[i].fieldOffset[0] == pOutput)
   469 				{
   470 					return pMap->dataDesc[i].externalName;
   471 				}
   472 			}
   473 		}
   474 		pMap = pMap->baseMap;
   475 	}
   476 
   477 	return NULL;
   478 }
   479 
   480 #if 0
   481 // Almost identical copy of this function from cbase.cpp - FIELD_EHANDLE changed to remove dependencies
   482 const char *variant_t::ToString( void ) const
   483 {
   484 	COMPILE_TIME_ASSERT( sizeof(string_t) == sizeof(int) );
   485 
   486 	static char szBuf[512];
   487 
   488 	switch (fieldType)
   489 	{
   490 	case FIELD_STRING:
   491 		{
   492 			return(STRING(iszVal));
   493 		}
   494 
   495 	case FIELD_BOOLEAN:
   496 		{
   497 			if (bVal == 0)
   498 			{
   499 				Q_strncpy(szBuf, "false",sizeof(szBuf));
   500 			}
   501 			else
   502 			{
   503 				Q_strncpy(szBuf, "true",sizeof(szBuf));
   504 			}
   505 			return(szBuf);
   506 		}
   507 
   508 	case FIELD_INTEGER:
   509 		{
   510 			Q_snprintf( szBuf, sizeof( szBuf ), "%i", iVal );
   511 			return(szBuf);
   512 		}
   513 
   514 	case FIELD_FLOAT:
   515 		{
   516 			Q_snprintf(szBuf,sizeof(szBuf), "%g", flVal);
   517 			return(szBuf);
   518 		}
   519 
   520 	case FIELD_COLOR32:
   521 		{
   522 			Q_snprintf(szBuf,sizeof(szBuf), "%d %d %d %d", (int)rgbaVal.r, (int)rgbaVal.g, (int)rgbaVal.b, (int)rgbaVal.a);
   523 			return(szBuf);
   524 		}
   525 
   526 	case FIELD_VECTOR:
   527 		{
   528 			Q_snprintf(szBuf,sizeof(szBuf), "[%g %g %g]", (double)vecVal[0], (double)vecVal[1], (double)vecVal[2]);
   529 			return(szBuf);
   530 		}
   531 
   532 	case FIELD_VOID:
   533 		{
   534 			szBuf[0] = '\0';
   535 			return(szBuf);
   536 		}
   537 
   538 	case FIELD_EHANDLE:
   539 		{
   540 			CBaseHandle temp = eVal;
   541 
   542 			const char *pszName = g_OutputManager.BaseHandleToEdict(temp)->GetClassName();
   543 
   544 			if (pszName == NULL)
   545 			{
   546 				Q_strncpy( szBuf, "<<null entity>>", 512 );
   547 				return (szBuf);
   548 			}
   549 
   550 			Q_strncpy( szBuf, pszName, 512 );
   551 			return (szBuf);
   552 		}
   553 
   554 	default:
   555 		break;
   556 	}
   557 
   558 	return("No conversion to string");
   559 }
   560 #endif
   561 
   562 // Thanks SM core
   563 edict_t *EntityOutputManager::BaseHandleToEdict(CBaseHandle &hndl)
   564 {
   565 	if (!hndl.IsValid())
   566 	{
   567 		return NULL;
   568 	}
   569 
   570 	int index = hndl.GetEntryIndex();
   571 
   572 	edict_t *pStoredEdict;
   573 
   574 	pStoredEdict = engine->PEntityOfEntIndex(index);
   575 
   576 	if (pStoredEdict == NULL)
   577 	{
   578 		return NULL;
   579 	}
   580 
   581 	IServerEntity *pSE = pStoredEdict->GetIServerEntity();
   582 
   583 	if (pSE == NULL)
   584 	{
   585 		return NULL;
   586 	}
   587 
   588 	if (pSE->GetRefEHandle() != hndl)
   589 	{
   590 		return NULL;
   591 	}
   592 
   593 	return pStoredEdict;
   594 }