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