extensions/sdktools/output.cpp
author Matt Woodrow <pred@alliedmods.net>
Fri Apr 25 05:20:17 2008 +0000 (2008-04-25)
changeset 2026 03b4a9c4a70e
parent 1992 4d48f66b2a77
child 2062 88443d433b8c
permissions -rw-r--r--
Cleaned up a few sdktools files.
     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 	IA32_Push_Reg(jit, REG_ECX);
   122 
   123 #elif defined PLATFORM_LINUX
   124 	IA32_Push_Rm_Disp8_ESP(jit, 20);
   125 	IA32_Push_Rm_Disp8_ESP(jit, 20);
   126 	IA32_Push_Rm_Disp8_ESP(jit, 20);
   127 
   128 	IA32_Push_Rm_Disp8_ESP(jit, 16);
   129 #endif
   130 
   131 	jitoffs_t call = IA32_Call_Imm32(jit, 0); 
   132 	IA32_Write_Jump32_Abs(jit, call, (void *)TempDetour);
   133 
   134 	
   135 #if defined PLATFORM_LINUX
   136 	IA32_Add_Rm_Imm8(jit, REG_ESP, 4, MOD_REG);		//add esp, 4
   137 #elif defined PLATFORM_WINDOWS
   138 	IA32_Pop_Reg(jit, REG_ECX);
   139 #endif
   140 
   141 	IA32_Add_Rm_Imm8(jit, REG_ESP, 12, MOD_REG);	//add esp, 12 (0Ch)
   142 
   143 
   144 	/* Patch old bytes in */
   145 	for (size_t i=0; i<info_restore.bytes; i++)
   146 	{
   147 		jit->write_ubyte(info_restore.patch[i]);
   148 	}
   149 
   150 	/* Return to the original function */
   151 	call = IA32_Jump_Imm32(jit, 0);
   152 	IA32_Write_Jump32_Abs(jit, call, (unsigned char *)info_address + info_restore.bytes);
   153 
   154 	return true;
   155 }
   156 
   157 void EntityOutputManager::InitFireEventDetour()
   158 {
   159 	if (!is_detoured)
   160 	{
   161 		DoGatePatch((unsigned char *)info_address, &info_callback);
   162 		is_detoured = true;
   163 	}
   164 }
   165 
   166 void EntityOutputManager::DeleteFireEventDetour()
   167 {
   168 	if (is_detoured)
   169 	{
   170 		ShutdownFireEventDetour();
   171 	}
   172 
   173 	if (info_callback)
   174 	{
   175 		/* Free the gate */
   176 		spengine->ExecFree(info_callback);
   177 		info_callback = NULL;
   178 	}
   179 }
   180 
   181 void TempDetour(void *pOutput, CBaseEntity *pActivator, CBaseEntity *pCaller, float fDelay)
   182 {
   183 	g_OutputManager.FireEventDetour(pOutput, pActivator, pCaller, fDelay);
   184 }
   185 
   186 void EntityOutputManager::ShutdownFireEventDetour()
   187 {
   188 	if (info_callback)
   189 	{
   190 		/* Remove the patch */
   191 		ApplyPatch(info_address, 0, &info_restore, NULL);
   192 		is_detoured = false;
   193 	}
   194 }
   195 
   196 void EntityOutputManager::FireEventDetour(void *pOutput, CBaseEntity *pActivator, CBaseEntity *pCaller, float fDelay)
   197 {
   198 	char sOutput[20];
   199 	Q_snprintf(sOutput, sizeof(sOutput), "%x", pOutput);
   200 
   201 	// attempt to directly lookup a hook using the pOutput pointer
   202 	OutputNameStruct *pOutputName = NULL;
   203 
   204 	edict_t *pEdict = gameents->BaseEntityToEdict(pCaller);
   205 
   206 	/* TODO: Add support for entities without an edict */
   207 	if (pEdict == NULL)
   208 	{
   209 		return;
   210 	}
   211 
   212 	bool fastLookup = false;
   213 	
   214 	// Fast lookup failed - check the slow way for hooks that havn't fired yet
   215 	if ((fastLookup = EntityOutputs->Retrieve(sOutput, (void **)&pOutputName)) == false)
   216 	{
   217 		const char *classname = pEdict->GetClassName();
   218 		const char *outputname = FindOutputName(pOutput, pCaller);
   219 
   220 		pOutputName = FindOutputPointer(classname, outputname, false);
   221 
   222 		if (!pOutputName)
   223 		{
   224 			return;
   225 		}
   226 	}
   227 
   228 	if (!pOutputName->hooks.empty())
   229 	{
   230 		if (!fastLookup)
   231 		{
   232 			// hook exists on this classname and output - map it into our quick find trie
   233 			EntityOutputs->Insert(sOutput, pOutputName);
   234 		}
   235 
   236 		SourceHook::List<omg_hooks *>::iterator _iter;
   237 
   238 		omg_hooks *hook;
   239 
   240 		_iter = pOutputName->hooks.begin();
   241 
   242 		while (_iter != pOutputName->hooks.end())
   243 		{
   244 			hook = (omg_hooks *)*_iter;
   245 
   246 			hook->in_use = true;
   247 
   248 			int serial = pEdict->m_NetworkSerialNumber;
   249 			
   250 			if (serial != hook->entity_filter && hook->entity_index == engine->IndexOfEdict(pEdict))
   251 			{
   252 				// same entity index but different serial number. Entity has changed, kill the hook.
   253 				_iter = pOutputName->hooks.erase(_iter);
   254 				CleanUpHook(hook);
   255 
   256 				continue;
   257 			}
   258 
   259 			if (hook->entity_filter == -1 || hook->entity_filter == serial) // Global classname hook
   260 			{
   261 				//fire the forward to hook->pf
   262 				hook->pf->PushString(pOutputName->Name);
   263 				hook->pf->PushCell(engine->IndexOfEdict(pEdict));
   264 				
   265 				edict_t *pEdictActivator = gameents->BaseEntityToEdict(pActivator);
   266 				if (!pEdictActivator)
   267 				{
   268 					hook->pf->PushCell(-1);
   269 				}
   270 				else
   271 				{
   272 					hook->pf->PushCell(engine->IndexOfEdict(pEdictActivator));
   273 				}
   274 				//hook->pf->PushCell(handle);
   275 				hook->pf->PushFloat(fDelay);
   276 				hook->pf->Execute(NULL);
   277 
   278 				if ((hook->entity_filter != -1) && hook->only_once)
   279 				{
   280 					_iter = pOutputName->hooks.erase(_iter);
   281 					CleanUpHook(hook);
   282 
   283 					continue;
   284 				}
   285 
   286 				if (hook->delete_me)
   287 				{
   288 					_iter = pOutputName->hooks.erase(_iter);
   289 					CleanUpHook(hook);
   290 					continue;
   291 				}
   292 
   293 				hook->in_use = false;
   294 				_iter++;
   295 
   296 				continue;
   297 			}
   298 		}
   299 	}
   300 }
   301 
   302 omg_hooks *EntityOutputManager::NewHook()
   303 {
   304 	omg_hooks *hook;
   305 
   306 	if (FreeHooks.empty())
   307 	{
   308 		hook = new omg_hooks;
   309 	}
   310 	else
   311 	{
   312 		hook = g_OutputManager.FreeHooks.front();
   313 		g_OutputManager.FreeHooks.pop();
   314 	}
   315 
   316 	return hook;
   317 }
   318 
   319 void EntityOutputManager::OnHookAdded()
   320 {
   321 	HookCount++;
   322 
   323 	if (HookCount == 1)
   324 	{
   325 		// This is the first hook created
   326 		InitFireEventDetour();
   327 	}
   328 }
   329 
   330 void EntityOutputManager::OnHookRemoved()
   331 {
   332 	HookCount--;
   333 
   334 	if (HookCount == 0)
   335 	{
   336 		ShutdownFireEventDetour();
   337 	}
   338 }
   339 
   340 void EntityOutputManager::CleanUpHook(omg_hooks *hook)
   341 {
   342 	FreeHooks.push(hook);
   343 
   344 	OnHookRemoved();
   345 
   346 	IPlugin *pPlugin = plsys->FindPluginByContext(hook->pf->GetParentContext()->GetContext());
   347 	SourceHook::List<omg_hooks *> *pList = NULL;
   348 
   349 	if (!pPlugin->GetProperty("OutputHookList", (void **)&pList, false) || !pList)
   350 	{
   351 		return;
   352 	}
   353 
   354 	SourceHook::List<omg_hooks *>::iterator p_iter = pList->begin();
   355 
   356 	omg_hooks *pluginHook;
   357 
   358 	while (p_iter != pList->end())
   359 	{
   360 		pluginHook = (omg_hooks *)*p_iter;
   361 		if (pluginHook == hook)
   362 		{
   363 			p_iter = pList->erase(p_iter);
   364 		}
   365 		else
   366 		{
   367 			p_iter++;
   368 		}
   369 	}
   370 }
   371 
   372 void EntityOutputManager::OnPluginDestroyed(IPlugin *plugin)
   373 {
   374 	SourceHook::List<omg_hooks *> *pList = NULL;
   375 
   376 	if (plugin->GetProperty("OutputHookList", (void **)&pList, true))
   377 	{
   378 		SourceHook::List<omg_hooks *>::iterator p_iter = pList->begin();
   379 		omg_hooks *hook;
   380 
   381 		while (p_iter != pList->end())
   382 		{
   383 			hook = (omg_hooks *)*p_iter;
   384 		
   385 			p_iter = pList->erase(p_iter); //remove from this plugins list
   386 			hook->m_parent->hooks.remove(hook); // remove from the y's list
   387 
   388 			FreeHooks.push(hook); //save the omg_hook
   389 
   390 			OnHookRemoved();
   391 		}		
   392 	}
   393 }
   394 
   395 OutputNameStruct *EntityOutputManager::FindOutputPointer(const char *classname, const char *outputname, bool create)
   396 {
   397 	ClassNameStruct *pClassname;
   398 	
   399 	if (!ClassNames->Retrieve(classname, (void **)&pClassname))
   400 	{
   401 		if (create)
   402 		{
   403 			pClassname = new ClassNameStruct;
   404 			ClassNames->Insert(classname, pClassname);
   405 		}
   406 		else
   407 		{
   408 			return NULL;
   409 		}
   410 	}
   411 
   412 	OutputNameStruct *pOutputName;
   413 
   414 	if (!pClassname->OutputList->Retrieve(outputname, (void **)&pOutputName))
   415 	{
   416 		if (create)
   417 		{
   418 			pOutputName = new OutputNameStruct;
   419 			pClassname->OutputList->Insert(outputname, pOutputName);
   420 			strncpy(pOutputName->Name, outputname, sizeof(pOutputName->Name));
   421 			pOutputName->Name[49] = 0;
   422 		}
   423 		else
   424 		{
   425 			return NULL;
   426 		}
   427 	}
   428 
   429 	return pOutputName;
   430 }
   431 
   432 // Iterate the datamap of pCaller and look for output pointers with the same address as pOutput
   433 const char *EntityOutputManager::FindOutputName(void *pOutput, CBaseEntity *pCaller)
   434 {
   435 	datamap_t *pMap = gamehelpers->GetDataMap(pCaller);
   436 
   437 	while (pMap)
   438 	{
   439 		for (int i=0; i<pMap->dataNumFields; i++)
   440 		{
   441 			if (pMap->dataDesc[i].flags & FTYPEDESC_OUTPUT)
   442 			{
   443 				if ((char *)pCaller + pMap->dataDesc[i].fieldOffset[0] == pOutput)
   444 				{
   445 					return pMap->dataDesc[i].externalName;
   446 				}
   447 			}
   448 		}
   449 		pMap = pMap->baseMap;
   450 	}
   451 
   452 	return NULL;
   453 }
   454 
   455 // Thanks SM core
   456 edict_t *EntityOutputManager::BaseHandleToEdict(CBaseHandle &hndl)
   457 {
   458 	if (!hndl.IsValid())
   459 	{
   460 		return NULL;
   461 	}
   462 
   463 	int index = hndl.GetEntryIndex();
   464 
   465 	edict_t *pStoredEdict;
   466 
   467 	pStoredEdict = engine->PEntityOfEntIndex(index);
   468 
   469 	if (pStoredEdict == NULL)
   470 	{
   471 		return NULL;
   472 	}
   473 
   474 	IServerEntity *pSE = pStoredEdict->GetIServerEntity();
   475 
   476 	if (pSE == NULL)
   477 	{
   478 		return NULL;
   479 	}
   480 
   481 	if (pSE->GetRefEHandle() != hndl)
   482 	{
   483 		return NULL;
   484 	}
   485 
   486 	return pStoredEdict;
   487 }