core/ConsoleDetours.cpp
author Scott Ehlert <ds@alliedmods.net>
Fri Nov 06 16:24:40 2009 -0600 (2009-11-06)
changeset 2863 d740d9cdf53a
parent 2844 87f951bece2d
child 3010 8ea042c00c80
permissions -rw-r--r--
Added IMemoryUtils::ResolveSymbol() for resolving symbols hidden via GCC's -fvisibility=hidden (bug 4091, r=dvander,pred).

Right now, this is only used on L4D2 where it is needed.
     1 /**
     2  * vim: set ts=4 sw=4 tw=99 noet :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2009 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 /**
    33  * On SourceHook v4.3 or lower, there are no DVP hooks. Very sad, right?
    34  * Only do this on newer versions. For the older code, we'll do an incredibly
    35  * hacky detour.
    36  *
    37  * The idea of the "non-hacky" (yeah... no) code is that every unique
    38  * ConCommand vtable gets its own DVP hook. We watch for unloading and
    39  * loading commands to remove stale hooks from SH.
    40  */
    41 
    42 #include "sourcemod.h"
    43 #include "sourcemm_api.h"
    44 #include "Logger.h"
    45 #include "compat_wrappers.h"
    46 #include "ConsoleDetours.h"
    47 #include "GameConfigs.h"
    48 #include "sm_stringutil.h"
    49 #include "ConCmdManager.h"
    50 #include "HalfLife2.h"
    51 #include "ConCommandBaseIterator.h"
    52 #include "ShareSys.h"
    53 
    54 #if defined PLATFORM_LINUX
    55 # include <dlfcn.h>
    56 # include <sys/mman.h>
    57 # include <stdint.h>
    58 # include <unistd.h>
    59 #endif
    60 
    61 #if SH_IMPL_VERSION >= 5
    62 # if SOURCE_ENGINE >= SE_ORANGEBOX
    63 	SH_DECL_EXTERN1_void(ConCommand, Dispatch, SH_NOATTRIB, false, const CCommand &);
    64 # else
    65 	SH_DECL_EXTERN0_void(ConCommand, Dispatch, SH_NOATTRIB, false);
    66 # endif
    67 #else
    68 # if SH_IMPL_VERSION >= 4
    69  extern int __SourceHook_FHVPAddConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>,bool);
    70  extern int __SourceHook_FHAddConCommandDispatch(void *, bool, class fastdelegate::FastDelegate0<void>);
    71 # else
    72  extern bool __SourceHook_FHAddConCommandDispatch(void *, bool, class fastdelegate::FastDelegate0<void>);
    73 # endif
    74 extern bool __SourceHook_FHRemoveConCommandDispatch(void *, bool, class fastdelegate::FastDelegate0<void>);
    75 #endif
    76 
    77 #if SH_IMPL_VERSION >= 4
    78 
    79 class GenericCommandHooker : public IConCommandLinkListener
    80 {
    81 	struct HackInfo
    82 	{
    83 		void **vtable;
    84 		int hook;
    85 		unsigned int refcount;
    86 	};
    87 	CVector<HackInfo> vtables;
    88 	bool enabled;
    89 	SourceHook::MemFuncInfo dispatch;
    90 
    91 	inline void **GetVirtualTable(ConCommandBase *pBase)
    92 	{
    93 		return *reinterpret_cast<void***>(reinterpret_cast<char*>(pBase) +
    94 		                                  dispatch.thisptroffs +
    95 		                                  dispatch.vtbloffs);
    96 	}
    97 
    98 	inline bool FindVtable(void **ptr, size_t& index)
    99 	{
   100 		for (size_t i = 0; i < vtables.size(); i++)
   101 		{
   102 			if (vtables[i].vtable == ptr)
   103 			{
   104 				index = i;
   105 				return true;
   106 			}
   107 		}
   108 		return false;
   109 	}
   110 
   111 	void MakeHookable(ConCommandBase *pBase)
   112 	{
   113 		if (!pBase->IsCommand())
   114 			return;
   115 
   116 		ConCommand *cmd = (ConCommand*)pBase;
   117 		void **vtable = GetVirtualTable(cmd);
   118 
   119 		size_t index;
   120 		if (!FindVtable(vtable, index))
   121 		{
   122 			HackInfo hack;
   123 			hack.vtable = vtable;
   124 			hack.hook = SH_ADD_VPHOOK(ConCommand, Dispatch, cmd, SH_MEMBER(this, &GenericCommandHooker::Dispatch), false);
   125 			hack.refcount = 1;
   126 			vtables.push_back(hack);
   127 		}
   128 		else
   129 		{
   130 			vtables[index].refcount++;
   131 		}
   132 	}
   133 
   134 # if SOURCE_ENGINE >= SE_ORANGEBOX
   135 	void Dispatch(const CCommand& args)
   136 # else
   137 	void Dispatch()
   138 # endif
   139 	{
   140 		cell_t res = ConsoleDetours::Dispatch(META_IFACEPTR(ConCommand)
   141 # if SOURCE_ENGINE >= SE_ORANGEBOX
   142 			, args
   143 # endif
   144 			);
   145 		if (res >= Pl_Handled)
   146 			RETURN_META(MRES_SUPERCEDE);
   147 	}
   148 
   149 	void ReparseCommandList()
   150 	{
   151 		for (size_t i = 0; i < vtables.size(); i++)
   152 			vtables[i].refcount = 0;
   153 		for (ConCommandBaseIterator iter; iter.IsValid(); iter.Next())
   154 			MakeHookable(iter.Get());
   155 		CVector<HackInfo>::iterator iter = vtables.begin();
   156 		while (iter != vtables.end())
   157 		{
   158 			if ((*iter).refcount)
   159 			{
   160 				iter++;
   161 				continue;
   162 			}
   163 			/* Damn it. This event happens AFTER the plugin has unloaded!
   164 			 * There's two options. Remove the hook now and hope SH's memory
   165 			 * protection will prevent a crash. Otherwise, we can wait until
   166 			 * the server shuts down and more likely crash then.
   167 			 *
   168 			 * This situation only arises if:
   169 			 * 1) Someone has used AddCommandFilter()
   170 			 * 2) ... on a Dark Messiah server (mm:s new api)
   171 			 * 3) ... and another MM:S plugin that uses ConCommands has unloaded.
   172 			 *
   173 			 * Even though the impact is really small, we'll wait until the
   174 			 * server shuts down, so normal operation isn't interrupted.
   175 			 *
   176 			 * See bug 4018.
   177 			 */
   178 			iter = vtables.erase(iter);
   179 		}
   180 	}
   181 
   182 	void UnhookCommand(ConCommandBase *pBase)
   183 	{
   184 		if (!pBase->IsCommand())
   185 			return;
   186 
   187 		ConCommand *cmd = (ConCommand*)pBase;
   188 		void **vtable = GetVirtualTable(cmd);
   189 
   190 		size_t index;
   191 		if (!FindVtable(vtable, index))
   192 		{
   193 			g_Logger.LogError("Console detour tried to unhook command \"%s\" but it wasn't found", pBase->GetName());
   194 			return;
   195 		}
   196 
   197 		assert(vtables[index].refcount > 0);
   198 		vtables[index].refcount--;
   199 		if (vtables[index].refcount == 0)
   200 		{
   201 			SH_REMOVE_HOOK_ID(vtables[index].hook);
   202 			vtables.erase(vtables.iterAt(index));
   203 		}
   204 	}
   205 
   206 public:
   207 	GenericCommandHooker() : enabled(false)
   208 	{
   209 	}
   210 
   211 	bool Enable()
   212 	{
   213 		SourceHook::GetFuncInfo(&ConCommand::Dispatch, dispatch);
   214 
   215 		if (dispatch.thisptroffs < 0)
   216 		{
   217 			g_Logger.LogError("Command filter could not determine ConCommand layout");
   218 			return false;
   219 		}
   220 
   221 		for (ConCommandBaseIterator iter; iter.IsValid(); iter.Next())
   222 			MakeHookable(iter.Get());
   223 
   224 		if (!vtables.size())
   225 		{
   226 			g_Logger.LogError("Command filter could not find any cvars!");
   227 			return false;
   228 		}
   229 
   230 		enabled = true;
   231 
   232 		return true;
   233 	}
   234 
   235 	void Disable()
   236 	{
   237 		for (size_t i = 0; i < vtables.size(); i++)
   238 			SH_REMOVE_HOOK_ID(vtables[i].hook);
   239 		vtables.clear();
   240 	}
   241 
   242 	virtual void OnLinkConCommand(ConCommandBase *pBase)
   243 	{
   244 		if (!enabled)
   245 			return;
   246 		MakeHookable(pBase);
   247 	}
   248 
   249 	virtual void OnUnlinkConCommand(ConCommandBase *pBase)
   250 	{
   251 		if (!enabled)
   252 			return;
   253 		if (pBase == NULL)
   254 			ReparseCommandList();
   255 		else
   256 			UnhookCommand(pBase);
   257 	}
   258 };
   259 
   260 /**
   261  * END DVP HOOK VERSION
   262  */
   263 
   264 #else /* SH_IMPL_VERSION >= 4 */
   265 
   266 /**
   267  * BEGIN ENGINE DETOUR VERSION
   268  */
   269 
   270 # include <jit/jit_helpers.h>
   271 # include <jit/x86/x86_macros.h>
   272 
   273 class GenericCommandHooker
   274 {
   275 	struct Patch
   276 	{
   277 		Patch() : applied(false)
   278 		{
   279 		}
   280 
   281 		bool applied;
   282 		void *base;
   283 		unsigned char search[16];
   284 		size_t search_len;
   285 		size_t offset;
   286 		size_t saveat;
   287 		int regparam;
   288 		void *detour;
   289 	};
   290 	
   291 	Patch ces;
   292 	Patch cgc;
   293 
   294 public:
   295  	static void DelayedActivation(void *inparam)
   296  	{
   297  		GenericCommandHooker *cdtrs = reinterpret_cast<GenericCommandHooker*>(inparam);
   298  		/* Safe to re-enter because the frame queue is lock+swapped. */
   299  		if ((!cdtrs->ces.applied || !cdtrs->cgc.applied) &&
   300  		    g_HL2.PeekCommandStack() != NULL)
   301  		{
   302  			g_SourceMod.AddFrameAction(GenericCommandHooker::DelayedActivation, cdtrs);
   303  			return;
   304  		}
   305  
   306  		if (!cdtrs->ces.applied)
   307  			cdtrs->ApplyPatch(&cdtrs->ces);
   308  		if (!cdtrs->cgc.applied)
   309  			cdtrs->ApplyPatch(&cdtrs->cgc);
   310  	}
   311 
   312 	bool Enable()
   313 	{
   314 		const char *platform = NULL;
   315 # if defined(PLATFORM_WINDOWS)
   316 		platform = "Windows";
   317 # else	
   318 		void *addrInBase = (void *)g_SMAPI->GetEngineFactory(false);
   319 		Dl_info info;
   320 		if (!dladdr(addrInBase, &info))
   321 		{
   322 			g_Logger.LogError("Command filter could not find engine name");
   323 			return false;
   324 		}
   325 		if (strstr(info.dli_fname, "engine_i486"))
   326 		{
   327 			platform = "Linux_486";
   328 		}
   329 		else if (strstr(info.dli_fname, "engine_i686"))
   330 		{
   331 			platform = "Linux_686";
   332 		}
   333 		else if (strstr(info.dli_fname, "engine_amd"))
   334 		{
   335 			platform = "Linux_AMD";
   336 		}
   337 		else
   338 		{
   339 			g_Logger.LogError("Command filter could not determine engine (%s)", info.dli_fname);
   340 			return false;
   341 		}
   342 # endif
   343 
   344 		if (!PrepPatch("Cmd_ExecuteString", "CES", platform, &ces))
   345 			return false;
   346 		if (!PrepPatch("CGameClient::ExecuteString", "CGC", platform, &cgc))
   347 			return false;
   348 
   349  		if (g_HL2.PeekCommandStack() != NULL)
   350  		{
   351  			g_SourceMod.AddFrameAction(GenericCommandHooker::DelayedActivation, this);
   352  			return true;
   353  		}
   354 
   355 		ApplyPatch(&ces);
   356 		ApplyPatch(&cgc);
   357 
   358 		return true;
   359 	}
   360 
   361 	void Disable()
   362 	{
   363 		UndoPatch(&ces);
   364 		UndoPatch(&cgc);
   365 	}
   366 
   367 private:
   368 
   369 # if !defined PLATFORM_WINDOWS
   370 #  define PAGE_READWRITE     PROT_READ|PROT_WRITE
   371 #  define PAGE_EXECUTE_READ  PROT_READ|PROT_EXEC
   372 
   373 	static inline uintptr_t AddrToPage(uintptr_t address)
   374 	{
   375 		return (address & ~(uintptr_t(sysconf(_SC_PAGE_SIZE) - 1)));
   376 	}
   377 
   378 # endif
   379 
   380 	void Protect(void *addr, size_t length, int prot)
   381 	{
   382 # if defined PLATFORM_WINDOWS
   383 		DWORD ignore;
   384 		VirtualProtect(addr, length, prot, &ignore);
   385 # else
   386 		uintptr_t startPage = AddrToPage(uintptr_t(addr));
   387 		length += (uintptr_t(addr) - startPage);
   388 		mprotect((void*)startPage, length, prot);
   389 # endif
   390 	}
   391 
   392 	void UndoPatch(Patch *patch)
   393 	{
   394 		if (!patch->applied || patch->detour == NULL)
   395 			return;
   396 
   397 		g_pSourcePawn->FreePageMemory(patch->detour);
   398 
   399 		unsigned char *source = (unsigned char *)patch->base + patch->offset;
   400 		Protect(source, patch->search_len, PAGE_READWRITE);
   401 		for (size_t i = 0; i < patch->search_len; i++)
   402 			source[i] = patch->search[i];
   403 		Protect(source, patch->search_len, PAGE_EXECUTE_READ);
   404 	}
   405 
   406 	void ApplyPatch(Patch *patch)
   407 	{
   408 		assert(!patch->applied);
   409 
   410 		size_t length = 0;
   411 		void *callback = (void*)&ConsoleDetours::Dispatch;
   412 
   413 		/* Bogus assignment to make compiler is doing the right thing. */
   414 		patch->detour = callback;
   415 
   416 		/* Assemgle the detour. */
   417 		JitWriter writer;
   418 		writer.outbase = NULL;
   419 		writer.outptr = NULL;
   420 		do
   421 		{
   422 			/* Need a specific register, or value on stack? */
   423 			if (patch->regparam != -1)
   424 				IA32_Push_Reg(&writer, patch->regparam);
   425 			/* Call real function. */
   426 			IA32_Write_Jump32_Abs(&writer, IA32_Call_Imm32(&writer, 0), callback);
   427 			/* Restore stack. */
   428 			if (patch->regparam != -1)
   429 				IA32_Pop_Reg(&writer, patch->regparam);
   430 			/* Copy any saved bytes */
   431 			if (patch->saveat)
   432 			{
   433 				for (size_t i = patch->saveat; i < patch->search_len; i++)
   434 				{
   435 					writer.write_ubyte(patch->search[i]);
   436 				}
   437 			}
   438 			/* Jump back to the caller. */
   439 			unsigned char *target = (unsigned char *)patch->base + patch->offset + patch->search_len;
   440 			IA32_Jump_Imm32_Abs(&writer, target);
   441 			/* Assemble, if we can. */
   442 			if (writer.outbase == NULL)
   443 			{
   444 				length = writer.outptr - writer.outbase;
   445 				patch->detour = g_pSourcePawn->AllocatePageMemory(length);
   446 				if (patch->detour == NULL)
   447 				{
   448 					g_Logger.LogError("Ran out of memory!");
   449 					return;
   450 				}
   451 				g_pSourcePawn->SetReadWrite(patch->detour);
   452 				writer.outbase = (jitcode_t)patch->detour;
   453 				writer.outptr = writer.outbase;
   454 			}
   455 			else
   456 			{
   457 				break;
   458 			}
   459 		} while (true);
   460 
   461 		g_pSourcePawn->SetReadExecute(patch->detour);
   462 
   463 		unsigned char *source = (unsigned char *)patch->base + patch->offset;
   464 		Protect(source, 6, PAGE_READWRITE);
   465 		source[0] = 0xFF;
   466 		source[1] = 0x25;
   467 		*(void **)&source[2] = &patch->detour;
   468 		Protect(source, 6, PAGE_EXECUTE_READ);
   469 
   470 		patch->applied = true;
   471 	}
   472 
   473 	bool PrepPatch(const char *signature, const char *name, const char *platform, Patch *patch)
   474 	{
   475 		/* Get the base address of the function. */
   476 		if (!g_pGameConf->GetMemSig(signature, &patch->base) || patch->base == NULL)
   477 		{
   478 			g_Logger.LogError("Command filter could not find signature: %s", signature);
   479 			return false;
   480 		}
   481 
   482 		const char *value;
   483 		char keyname[255];
   484 
   485 		/* Get the verification bytes that will be written over. */
   486 		UTIL_Format(keyname, sizeof(keyname), "%s_Patch_%s", name, platform);
   487 		if ((value = g_pGameConf->GetKeyValue(keyname)) == NULL)
   488 		{
   489 			g_Logger.LogError("Command filter could not find key: %s", keyname);
   490 			return false;
   491 		}
   492 		patch->search_len = UTIL_DecodeHexString(patch->search, sizeof(patch->search), value);
   493 		if (patch->search_len < 6)
   494 		{
   495 			g_Logger.LogError("Error decoding %s value, or not long enough", keyname);
   496 			return false;
   497 		}
   498 
   499 		/* Get the offset into the function. */
   500 		UTIL_Format(keyname, sizeof(keyname), "%s_Offset_%s", name, platform);
   501 		if ((value = g_pGameConf->GetKeyValue(keyname)) == NULL)
   502 		{
   503 			g_Logger.LogError("Command filter could not find key: %s", keyname);
   504 			return false;
   505 		}
   506 		patch->offset = atoi(value);
   507 		if (patch->offset > 20000)
   508 		{
   509 			g_Logger.LogError("Command filter %s value is bogus", keyname);
   510 			return false;
   511 		}
   512 
   513 		/* Get the number of bytes to save from what was written over. */
   514 		patch->saveat = 0;
   515 		UTIL_Format(keyname, sizeof(keyname), "%s_Save_%s", name, platform);
   516 		if ((value = g_pGameConf->GetKeyValue(keyname)) != NULL)
   517 		{
   518 			patch->saveat = atoi(value);
   519 			if (patch->saveat >= patch->search_len)
   520 			{
   521 				g_Logger.LogError("Command filter %s value is too large", keyname);
   522 				return false;
   523 			}
   524 		}
   525 
   526 		/* Get register for parameter, if any. */
   527 		patch->regparam = -1;
   528 		UTIL_Format(keyname, sizeof(keyname), "%s_Reg_%s", name, platform);
   529 		if ((value = g_pGameConf->GetKeyValue(keyname)) != NULL)
   530 		{
   531 			patch->regparam = atoi(value);
   532 		}
   533 
   534 		/* Everything loaded from gamedata, make sure the patch will succeed. */
   535 		unsigned char *address = (unsigned char *)patch->base + patch->offset;
   536 		for (size_t i = 0; i < patch->search_len; i++)
   537 		{
   538 			if (address[i] != patch->search[i])
   539 			{
   540 				g_Logger.LogError("Command filter %s has changed (byte %x is not %x sub-offset %d)",
   541 				                  name, address[i], patch->search[i], i);
   542 				return false;
   543 			}
   544 		}
   545 
   546 		return true;
   547 	}
   548 };
   549 
   550 static bool dummy_hook_set = false;
   551 void DummyHook()
   552 {
   553 	if (dummy_hook_set)
   554 	{
   555 		dummy_hook_set = false;
   556 		RETURN_META(MRES_SUPERCEDE);
   557 	}
   558 }
   559 
   560 #endif
   561 
   562 /**
   563  * BEGIN THE ACTUALLY GENERIC CODE.
   564  */
   565 
   566 #define FEATURECAP_COMMANDLISTENER  "command listener"
   567 
   568 static GenericCommandHooker s_GenericHooker;
   569 ConsoleDetours g_ConsoleDetours;
   570 
   571 ConsoleDetours::ConsoleDetours() : status(FeatureStatus_Unknown)
   572 {
   573 }
   574 
   575 void ConsoleDetours::OnSourceModAllInitialized()
   576 {
   577 	m_pForward = g_Forwards.CreateForwardEx("OnAnyCommand", ET_Hook, 3, NULL, Param_Cell,
   578 	                                        Param_String, Param_Cell);
   579 	g_ShareSys.AddCapabilityProvider(NULL, this, FEATURECAP_COMMANDLISTENER);
   580 }
   581 
   582 void ConsoleDetours::OnSourceModShutdown()
   583 {
   584 	List<Listener*>::iterator iter = m_Listeners.begin();
   585 	while (iter != m_Listeners.end())
   586 	{
   587 		Listener *listener = (*iter);
   588 		g_Forwards.ReleaseForward(listener->forward);
   589 		delete listener;
   590 		iter = m_Listeners.erase(iter);
   591 	}
   592 
   593 	g_Forwards.ReleaseForward(m_pForward);
   594 	s_GenericHooker.Disable();
   595 }
   596 
   597 FeatureStatus ConsoleDetours::GetFeatureStatus(FeatureType type, const char *name)
   598 {
   599 	return GetStatus();
   600 }
   601 
   602 FeatureStatus ConsoleDetours::GetStatus()
   603 {
   604 	if (status == FeatureStatus_Unknown)
   605 	{
   606 		status = s_GenericHooker.Enable() ? FeatureStatus_Available : FeatureStatus_Unavailable;
   607 	}
   608 	return status;
   609 }
   610 
   611 bool ConsoleDetours::AddListener(IPluginFunction *fun, const char *command)
   612 {
   613 	if (GetStatus() != FeatureStatus_Available)
   614 		return false;
   615 
   616 	if (command == NULL)
   617 	{
   618 		m_pForward->AddFunction(fun);
   619 	}
   620 	else
   621 	{
   622 		const char *str = UTIL_ToLowerCase(command);
   623 		Listener *listener;
   624 		Listener **plistener = m_CmdLookup.retrieve(str);
   625 		if (plistener == NULL)
   626 		{
   627 			listener = new Listener;
   628 			listener->forward = g_Forwards.CreateForwardEx(NULL, ET_Hook, 3, NULL, Param_Cell,
   629 			                                               Param_String, Param_Cell);
   630 			m_CmdLookup.insert(str, listener);
   631 		}
   632 		else
   633 		{
   634 			listener = *plistener;
   635 		}
   636 		listener->forward->AddFunction(fun);
   637 		delete [] str;
   638 	}
   639 
   640 	return true;
   641 }
   642 
   643 bool ConsoleDetours::RemoveListener(IPluginFunction *fun, const char *command)
   644 {
   645 	if (command == NULL)
   646 	{
   647 		return m_pForward->RemoveFunction(fun);
   648 	}
   649 	else
   650 	{
   651 		const char *str = UTIL_ToLowerCase(command);
   652 		Listener *listener;
   653 		Listener **plistener = m_CmdLookup.retrieve(str);
   654 		delete [] str;
   655 		if (plistener == NULL)
   656 			return false;
   657 		listener = *plistener;
   658 		return listener->forward->RemoveFunction(fun);
   659 	}
   660 }
   661 
   662 cell_t ConsoleDetours::InternalDispatch(int client, const CCommand& args)
   663 {
   664 	char name[255];
   665 	const char *realname = args.Arg(0);
   666 	size_t len = strlen(realname);
   667 	for (size_t i = 0; i < len; i++)
   668 	{
   669 		if (realname[i] >= 'A' && realname[i] <= 'Z')
   670 			name[i] = tolower(realname[i]);
   671 		else
   672 			name[i] = realname[i];
   673 	}
   674 	name[len] = '\0';
   675 
   676 	cell_t result = Pl_Continue;
   677 	m_pForward->PushCell(client);
   678 	m_pForward->PushString(name);
   679 	m_pForward->PushCell(args.ArgC() - 1);
   680 	m_pForward->Execute(&result, NULL);
   681 
   682 	/* Don't let plugins block this. */
   683 	if (strcmp(name, "sm") == 0)
   684 		result = Pl_Continue;
   685 
   686 	if (result >= Pl_Stop)
   687 		return result;
   688 	
   689 	Listener **plistener = m_CmdLookup.retrieve(name);
   690 	if (plistener == NULL)
   691 		return result;
   692 	Listener *listener = *plistener;
   693 	if (listener->forward->GetFunctionCount() == 0)
   694 		return result;
   695 
   696 	cell_t result2 = Pl_Continue;
   697 	listener->forward->PushCell(client);
   698 	listener->forward->PushString(name);
   699 	listener->forward->PushCell(args.ArgC() - 1);
   700 	listener->forward->Execute(&result2, NULL);
   701 
   702 	if (result2 > result)
   703 		result = result2;
   704 
   705 	/* "sm" should not have flown through the above. */
   706 	assert(strcmp(name, "sm") != 0 || result == Pl_Continue);
   707 
   708 	return result;
   709 }
   710 
   711 #if SOURCE_ENGINE >= SE_ORANGEBOX
   712 cell_t ConsoleDetours::Dispatch(ConCommand *pBase, const CCommand& args)
   713 {
   714 #else
   715 cell_t ConsoleDetours::Dispatch(ConCommand *pBase)
   716 {
   717 	CCommand args;
   718 #endif
   719 	g_HL2.PushCommandStack(&args);
   720 	cell_t res = g_ConsoleDetours.InternalDispatch(g_ConCmds.GetCommandClient(), args);
   721 	g_HL2.PopCommandStack();
   722 
   723 #if SH_IMPL_VERSION < 4
   724 	if (res >= Pl_Handled)
   725 	{
   726 		/* See bug 4020 - we can't optimize this because looking at the vtable
   727 		 * is probably more expensive, since there's no SH_GET_ORIG_VFNPTR_ENTRY.
   728 		 */
   729 		SH_ADD_HOOK_STATICFUNC(ConCommand, Dispatch, pBase, DummyHook, false);
   730 		dummy_hook_set = true;
   731 		pBase->Dispatch();
   732 		SH_REMOVE_HOOK_STATICFUNC(ConCommand, Dispatch, pBase, DummyHook, false);
   733 	}
   734 	else
   735 	{
   736 		/* Make sure the command gets invoked. See bug 4019 on making this better. */
   737 		pBase->Dispatch();
   738 	}
   739 #endif
   740 
   741 	return res;
   742 }