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