core/ConsoleDetours.cpp
changeset 2807 973290878e2f
child 2841 dde3dd0b4b8b
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/core/ConsoleDetours.cpp	Sat Sep 26 17:14:50 2009 -0400
     1.3 @@ -0,0 +1,702 @@
     1.4 +/**
     1.5 + * vim: set ts=4 sw=4 tw=99 noet :
     1.6 + * =============================================================================
     1.7 + * SourceMod
     1.8 + * Copyright (C) 2004-2009 AlliedModders LLC.  All rights reserved.
     1.9 + * =============================================================================
    1.10 + *
    1.11 + * This program is free software; you can redistribute it and/or modify it under
    1.12 + * the terms of the GNU General Public License, version 3.0, as published by the
    1.13 + * Free Software Foundation.
    1.14 + *
    1.15 + * This program is distributed in the hope that it will be useful, but WITHOUT
    1.16 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    1.17 + * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
    1.18 + * details.
    1.19 + *
    1.20 + * You should have received a copy of the GNU General Public License along with
    1.21 + * this program.  If not, see <http://www.gnu.org/licenses/>.
    1.22 + *
    1.23 + * As a special exception, AlliedModders LLC gives you permission to link the
    1.24 + * code of this program (as well as its derivative works) to "Half-Life 2," the
    1.25 + * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
    1.26 + * by the Valve Corporation.  You must obey the GNU General Public License in
    1.27 + * all respects for all other code used.  Additionally, AlliedModders LLC grants
    1.28 + * this exception to all derivative works.  AlliedModders LLC defines further
    1.29 + * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
    1.30 + * or <http://www.sourcemod.net/license.php>.
    1.31 + *
    1.32 + * Version: $Id$
    1.33 + */
    1.34 +
    1.35 +/**
    1.36 + * On SourceHook v4.3 or lower, there are no DVP hooks. Very sad, right?
    1.37 + * Only do this on newer version. For the older code, we'll do an incredibly
    1.38 + * hacky detour.
    1.39 + *
    1.40 + * The idea of the "non-hacky" (yeah... no) code is that every unique
    1.41 + * ConCommand vtable gets its own DVP hook. We watch for unloading and
    1.42 + * loading commands to remove stale hooks from SH.
    1.43 + */
    1.44 +
    1.45 +#include "sourcemod.h"
    1.46 +#include "sourcemm_api.h"
    1.47 +#include "Logger.h"
    1.48 +#include "compat_wrappers.h"
    1.49 +#include "ConsoleDetours.h"
    1.50 +#include "GameConfigs.h"
    1.51 +#include "sm_stringutil.h"
    1.52 +#include "ConCmdManager.h"
    1.53 +#include "HalfLife2.h"
    1.54 +#include "ConCommandBaseIterator.h"
    1.55 +
    1.56 +#if defined PLATFORM_LINUX
    1.57 +# include <dlfcn.h>
    1.58 +# include <sys/mman.h>
    1.59 +# include <stdint.h>
    1.60 +# include <unistd.h>
    1.61 +#endif
    1.62 +
    1.63 +#if SH_IMPL_VERSION >= 5
    1.64 +# if SOURCE_ENGINE >= SE_ORANGEBOX
    1.65 +	SH_DECL_EXTERN1_void(ConCommand, Dispatch, SH_NOATTRIB, false, const CCommand &);
    1.66 +# else
    1.67 +	SH_DECL_EXTERN0_void(ConCommand, Dispatch, SH_NOATTRIB, false);
    1.68 +# endif
    1.69 +#elif SH_IMPL_VERSION == 3
    1.70 +extern bool __SourceHook_FHAddConCommandDispatch(void *, bool, class fastdelegate::FastDelegate0<void>);
    1.71 +extern bool __SourceHook_FHRemoveConCommandDispatch(void *, bool, class fastdelegate::FastDelegate0<void>);
    1.72 +#endif
    1.73 +
    1.74 +#if SH_IMPL_VERSION >= 4
    1.75 +
    1.76 +class GenericCommandHooker : public IConCommandLinkListener
    1.77 +{
    1.78 +	struct HackInfo
    1.79 +	{
    1.80 +		void **vtable;
    1.81 +		int hook;
    1.82 +		unsigned int refcount;
    1.83 +	};
    1.84 +	CVector<HackInfo> vtables;
    1.85 +	bool enabled;
    1.86 +	SourceHook::MemFuncInfo dispatch;
    1.87 +
    1.88 +	inline void **GetVirtualTable(ConCommandBase *pBase)
    1.89 +	{
    1.90 +		return *reinterpret_cast<void***>(reinterpret_cast<char*>(pBase) +
    1.91 +		                                  dispatch.thisptroffs +
    1.92 +		                                  dispatch.vtbloffs);
    1.93 +	}
    1.94 +
    1.95 +	inline bool FindVtable(void **ptr, size_t& index)
    1.96 +	{
    1.97 +		for (size_t i = 0; i < vtables.size(); i++)
    1.98 +		{
    1.99 +			if (vtables[i].vtable == ptr)
   1.100 +			{
   1.101 +				index = i;
   1.102 +				return true;
   1.103 +			}
   1.104 +		}
   1.105 +		return false;
   1.106 +	}
   1.107 +
   1.108 +	void MakeHookable(ConCommandBase *pBase)
   1.109 +	{
   1.110 +		if (!pBase->IsCommand())
   1.111 +			return;
   1.112 +
   1.113 +		ConCommand *cmd = (ConCommand*)pBase;
   1.114 +		void **vtable = GetVirtualTable(cmd);
   1.115 +
   1.116 +		size_t index;
   1.117 +		if (!FindVtable(vtable, index))
   1.118 +		{
   1.119 +			HackInfo hack;
   1.120 +			hack.vtable = vtable;
   1.121 +			hack.hook = SH_ADD_VPHOOK(ConCommand, Dispatch, cmd, SH_MEMBER(this, &GenericCommandHooker::Dispatch), false);
   1.122 +			hack.refcount = 1;
   1.123 +			vtables.push_back(hack);
   1.124 +		}
   1.125 +		else
   1.126 +		{
   1.127 +			vtables[index].refcount++;
   1.128 +		}
   1.129 +	}
   1.130 +
   1.131 +# if SOURCE_ENGINE >= SE_ORANGEBOX
   1.132 +	void Dispatch(const CCommand& args)
   1.133 +# else
   1.134 +	void Dispatch()
   1.135 +# endif
   1.136 +	{
   1.137 +		cell_t res = ConsoleDetours::Dispatch(META_IFACEPTR(ConCommand)
   1.138 +# if SOURCE_ENGINE >= SE_ORANGEBOX
   1.139 +			, args
   1.140 +# endif
   1.141 +			);
   1.142 +		if (res >= Pl_Handled)
   1.143 +			RETURN_META(MRES_SUPERCEDE);
   1.144 +	}
   1.145 +
   1.146 +	void ReparseCommandList()
   1.147 +	{
   1.148 +		for (size_t i = 0; i < vtables.size(); i++)
   1.149 +			vtables[i].refcount = 0;
   1.150 +		for (ConCommandBaseIterator iter; iter.IsValid(); iter.Next())
   1.151 +			MakeHookable(iter.Get());
   1.152 +		CVector<HackInfo>::iterator iter = vtables.begin();
   1.153 +		while (iter != vtables.end())
   1.154 +		{
   1.155 +			if ((*iter).refcount)
   1.156 +				continue;
   1.157 +			/* Damn it. This event happens AFTER the plugin has unloaded!
   1.158 +			 * There's two options. Remove the hook now and hope SH's memory
   1.159 +			 * protection will prevent a crash. Otherwise, we can wait until
   1.160 +			 * the server shuts down and more likely crash then.
   1.161 +			 *
   1.162 +			 * This situation only arises if:
   1.163 +			 * 1) Someone has used AddCommandFilter()
   1.164 +			 * 2) ... on a Dark Messiah server (mm:s new api)
   1.165 +			 * 3) ... and another MM:S plugin that uses ConCommands has unloaded.
   1.166 +			 *
   1.167 +			 * Even though the impact is really small, we'll wait until the
   1.168 +			 * server shuts down, so normal operation isn't interrupted.
   1.169 +			 *
   1.170 +			 * See bug 4018.
   1.171 +			 */
   1.172 +			iter = vtables.erase(iter);
   1.173 +		}
   1.174 +	}
   1.175 +
   1.176 +	void UnhookCommand(ConCommandBase *pBase)
   1.177 +	{
   1.178 +		if (!pBase->IsCommand())
   1.179 +			return;
   1.180 +
   1.181 +		ConCommand *cmd = (ConCommand*)pBase;
   1.182 +		void **vtable = GetVirtualTable(cmd);
   1.183 +
   1.184 +		size_t index;
   1.185 +		if (!FindVtable(vtable, index))
   1.186 +		{
   1.187 +			g_Logger.LogError("Console detour tried to unhook command \"%s\" but it wasn't found", pBase->GetName());
   1.188 +			return;
   1.189 +		}
   1.190 +
   1.191 +		assert(vtables[index].refcount > 0);
   1.192 +		vtables[index].refcount--;
   1.193 +		if (vtables[index].refcount == 0)
   1.194 +		{
   1.195 +			SH_REMOVE_HOOK_ID(vtables[index].hook);
   1.196 +			vtables.erase(vtables.iterAt(index));
   1.197 +		}
   1.198 +	}
   1.199 +
   1.200 +public:
   1.201 +	GenericCommandHooker() : enabled(false)
   1.202 +	{
   1.203 +	}
   1.204 +
   1.205 +	bool Enable()
   1.206 +	{
   1.207 +		SourceHook::GetFuncInfo(&ConCommand::Dispatch, dispatch);
   1.208 +
   1.209 +		if (dispatch.thisptroffs < 0)
   1.210 +		{
   1.211 +			g_Logger.LogError("Command filter could not determine ConCommand layout");
   1.212 +			return false;
   1.213 +		}
   1.214 +
   1.215 +		for (ConCommandBaseIterator iter; iter.IsValid(); iter.Next())
   1.216 +			MakeHookable(iter.Get());
   1.217 +
   1.218 +		if (!vtables.size())
   1.219 +		{
   1.220 +			g_Logger.LogError("Command filter could not find any cvars!");
   1.221 +			return false;
   1.222 +		}
   1.223 +
   1.224 +		enabled = true;
   1.225 +
   1.226 +		return true;
   1.227 +	}
   1.228 +
   1.229 +	void Disable()
   1.230 +	{
   1.231 +		for (size_t i = 0; i < vtables.size(); i++)
   1.232 +			SH_REMOVE_HOOK_ID(vtables[i].hook);
   1.233 +		vtables.clear();
   1.234 +	}
   1.235 +
   1.236 +	virtual void OnLinkConCommand(ConCommandBase *pBase)
   1.237 +	{
   1.238 +		if (!enabled)
   1.239 +			return;
   1.240 +		MakeHookable(pBase);
   1.241 +	}
   1.242 +
   1.243 +	virtual void OnUnlinkConCommand(ConCommandBase *pBase)
   1.244 +	{
   1.245 +		if (!enabled)
   1.246 +			return;
   1.247 +		if (pBase == NULL)
   1.248 +			ReparseCommandList();
   1.249 +		else
   1.250 +			UnhookCommand(pBase);
   1.251 +	}
   1.252 +};
   1.253 +
   1.254 +/**
   1.255 + * END DVP HOOK VERSION
   1.256 + */
   1.257 +
   1.258 +#else /* SH_IMPL_VERSION >= 4 */
   1.259 +
   1.260 +/**
   1.261 + * BEGIN ENGINE DETOUR VERSION
   1.262 + */
   1.263 +
   1.264 +# include <jit/jit_helpers.h>
   1.265 +# include <jit/x86/x86_macros.h>
   1.266 +
   1.267 +class GenericCommandHooker
   1.268 +{
   1.269 +	struct Patch
   1.270 +	{
   1.271 +		Patch() : applied(false)
   1.272 +		{
   1.273 +		}
   1.274 +
   1.275 +		bool applied;
   1.276 +		void *base;
   1.277 +		unsigned char search[16];
   1.278 +		size_t search_len;
   1.279 +		size_t offset;
   1.280 +		size_t saveat;
   1.281 +		int regparam;
   1.282 +		void *detour;
   1.283 +	};
   1.284 +	
   1.285 +	Patch ces;
   1.286 +	Patch cgc;
   1.287 +
   1.288 +public:
   1.289 +	bool Enable()
   1.290 +	{
   1.291 +		const char *platform = NULL;
   1.292 +# if defined(PLATFORM_WINDOWS)
   1.293 +		platform = "Windows";
   1.294 +# else	
   1.295 +		void *addrInBase = (void *)g_SMAPI->GetEngineFactory(false);
   1.296 +		Dl_info info;
   1.297 +		if (!dladdr(addrInBase, &info))
   1.298 +		{
   1.299 +			g_Logger.LogError("Command filter could not find engine name");
   1.300 +			return false;
   1.301 +		}
   1.302 +		if (strstr(info.dli_fname, "engine_i486"))
   1.303 +		{
   1.304 +			platform = "Linux_486";
   1.305 +		}
   1.306 +		else if (strstr(info.dli_fname, "engine_i686"))
   1.307 +		{
   1.308 +			platform = "Linux_686";
   1.309 +		}
   1.310 +		else if (strstr(info.dli_fname, "engine_amd"))
   1.311 +		{
   1.312 +			platform = "Linux_AMD";
   1.313 +		}
   1.314 +		else
   1.315 +		{
   1.316 +			g_Logger.LogError("Command filter could not determine engine (%s)", info.dli_fname);
   1.317 +			return false;
   1.318 +		}
   1.319 +# endif
   1.320 +
   1.321 +		if (!PrepPatch("Cmd_ExecuteString", "CES", platform, &ces))
   1.322 +			return false;
   1.323 +		if (!PrepPatch("CGameClient::ExecuteString", "CGC", platform, &cgc))
   1.324 +			return false;
   1.325 +
   1.326 +		ApplyPatch(&ces);
   1.327 +		ApplyPatch(&cgc);
   1.328 +
   1.329 +		return true;
   1.330 +	}
   1.331 +
   1.332 +	void Disable()
   1.333 +	{
   1.334 +		UndoPatch(&ces);
   1.335 +		UndoPatch(&cgc);
   1.336 +	}
   1.337 +
   1.338 +private:
   1.339 +
   1.340 +# if !defined PLATFORM_WINDOWS
   1.341 +#  define PAGE_READWRITE     PROT_READ|PROT_WRITE
   1.342 +#  define PAGE_EXECUTE_READ  PROT_READ|PROT_EXEC
   1.343 +
   1.344 +	static inline uintptr_t AddrToPage(uintptr_t address)
   1.345 +	{
   1.346 +		return (address & ~(uintptr_t(sysconf(_SC_PAGE_SIZE) - 1)));
   1.347 +	}
   1.348 +
   1.349 +# endif
   1.350 +
   1.351 +	void Protect(void *addr, size_t length, int prot)
   1.352 +	{
   1.353 +# if defined PLATFORM_WINDOWS
   1.354 +		DWORD ignore;
   1.355 +		VirtualProtect(addr, length, prot, &ignore);
   1.356 +# else
   1.357 +		uintptr_t startPage = AddrToPage(uintptr_t(addr));
   1.358 +		length += (uintptr_t(addr) - startPage);
   1.359 +		mprotect((void*)startPage, length, prot);
   1.360 +# endif
   1.361 +	}
   1.362 +
   1.363 +	void UndoPatch(Patch *patch)
   1.364 +	{
   1.365 +		if (!patch->applied || patch->detour == NULL)
   1.366 +			return;
   1.367 +
   1.368 +		g_pSourcePawn->FreePageMemory(patch->detour);
   1.369 +
   1.370 +		unsigned char *source = (unsigned char *)patch->base + patch->offset;
   1.371 +		Protect(source, patch->search_len, PAGE_READWRITE);
   1.372 +		for (size_t i = 0; i < patch->search_len; i++)
   1.373 +			source[i] = patch->search[i];
   1.374 +		Protect(source, patch->search_len, PAGE_EXECUTE_READ);
   1.375 +	}
   1.376 +
   1.377 +	void ApplyPatch(Patch *patch)
   1.378 +	{
   1.379 +		assert(!patch->applied);
   1.380 +
   1.381 +		size_t length = 0;
   1.382 +		void *callback = (void*)&ConsoleDetours::Dispatch;
   1.383 +
   1.384 +		/* Bogus assignment to make compiler is doing the right thing. */
   1.385 +		patch->detour = callback;
   1.386 +
   1.387 +		/* Assemgle the detour. */
   1.388 +		JitWriter writer;
   1.389 +		writer.outbase = NULL;
   1.390 +		writer.outptr = NULL;
   1.391 +		do
   1.392 +		{
   1.393 +			/* Need a specific register, or value on stack? */
   1.394 +			if (patch->regparam != -1)
   1.395 +				IA32_Push_Reg(&writer, patch->regparam);
   1.396 +			/* Call real function. */
   1.397 +			IA32_Write_Jump32_Abs(&writer, IA32_Call_Imm32(&writer, 0), callback);
   1.398 +			/* Restore stack. */
   1.399 +			if (patch->regparam != -1)
   1.400 +				IA32_Pop_Reg(&writer, patch->regparam);
   1.401 +			/* Copy any saved bytes */
   1.402 +			if (patch->saveat)
   1.403 +			{
   1.404 +				for (size_t i = patch->saveat; i < patch->search_len; i++)
   1.405 +				{
   1.406 +					writer.write_ubyte(patch->search[i]);
   1.407 +				}
   1.408 +			}
   1.409 +			/* Jump back to the caller. */
   1.410 +			unsigned char *target = (unsigned char *)patch->base + patch->offset + patch->search_len;
   1.411 +			IA32_Jump_Imm32_Abs(&writer, target);
   1.412 +			/* Assemble, if we can. */
   1.413 +			if (writer.outbase == NULL)
   1.414 +			{
   1.415 +				length = writer.outptr - writer.outbase;
   1.416 +				patch->detour = g_pSourcePawn->AllocatePageMemory(length);
   1.417 +				if (patch->detour == NULL)
   1.418 +				{
   1.419 +					g_Logger.LogError("Ran out of memory!");
   1.420 +					return;
   1.421 +				}
   1.422 +				g_pSourcePawn->SetReadWrite(patch->detour);
   1.423 +				writer.outbase = (jitcode_t)patch->detour;
   1.424 +				writer.outptr = writer.outbase;
   1.425 +			}
   1.426 +			else
   1.427 +			{
   1.428 +				break;
   1.429 +			}
   1.430 +		} while (true);
   1.431 +
   1.432 +		g_pSourcePawn->SetReadExecute(patch->detour);
   1.433 +
   1.434 +		unsigned char *source = (unsigned char *)patch->base + patch->offset;
   1.435 +		Protect(source, 6, PAGE_READWRITE);
   1.436 +		source[0] = 0xFF;
   1.437 +		source[1] = 0x25;
   1.438 +		*(void **)&source[2] = &patch->detour;
   1.439 +		Protect(source, 6, PAGE_EXECUTE_READ);
   1.440 +
   1.441 +		patch->applied = true;
   1.442 +	}
   1.443 +
   1.444 +	bool PrepPatch(const char *signature, const char *name, const char *platform, Patch *patch)
   1.445 +	{
   1.446 +		/* Get the base address of the function. */
   1.447 +		if (!g_pGameConf->GetMemSig(signature, &patch->base) || patch->base == NULL)
   1.448 +		{
   1.449 +			g_Logger.LogError("Command filter could not find signature: %s", signature);
   1.450 +			return false;
   1.451 +		}
   1.452 +
   1.453 +		const char *value;
   1.454 +		char keyname[255];
   1.455 +
   1.456 +		/* Get the verification bytes that will be written over. */
   1.457 +		UTIL_Format(keyname, sizeof(keyname), "%s_Patch_%s", name, platform);
   1.458 +		if ((value = g_pGameConf->GetKeyValue(keyname)) == NULL)
   1.459 +		{
   1.460 +			g_Logger.LogError("Command filter could not find key: %s", keyname);
   1.461 +			return false;
   1.462 +		}
   1.463 +		patch->search_len = UTIL_DecodeHexString(patch->search, sizeof(patch->search), value);
   1.464 +		if (patch->search_len < 6)
   1.465 +		{
   1.466 +			g_Logger.LogError("Error decoding %s value, or not long enough", keyname);
   1.467 +			return false;
   1.468 +		}
   1.469 +
   1.470 +		/* Get the offset into the function. */
   1.471 +		UTIL_Format(keyname, sizeof(keyname), "%s_Offset_%s", name, platform);
   1.472 +		if ((value = g_pGameConf->GetKeyValue(keyname)) == NULL)
   1.473 +		{
   1.474 +			g_Logger.LogError("Command filter could not find key: %s", keyname);
   1.475 +			return false;
   1.476 +		}
   1.477 +		patch->offset = atoi(value);
   1.478 +		if (patch->offset > 20000)
   1.479 +		{
   1.480 +			g_Logger.LogError("Command filter %s value is bogus", keyname);
   1.481 +			return false;
   1.482 +		}
   1.483 +
   1.484 +		/* Get the number of bytes to save from what was written over. */
   1.485 +		patch->saveat = 0;
   1.486 +		UTIL_Format(keyname, sizeof(keyname), "%s_Save_%s", name, platform);
   1.487 +		if ((value = g_pGameConf->GetKeyValue(keyname)) != NULL)
   1.488 +		{
   1.489 +			patch->saveat = atoi(value);
   1.490 +			if (patch->saveat >= patch->search_len)
   1.491 +			{
   1.492 +				g_Logger.LogError("Command filter %s value is too large", keyname);
   1.493 +				return false;
   1.494 +			}
   1.495 +		}
   1.496 +
   1.497 +		/* Get register for parameter, if any. */
   1.498 +		patch->regparam = -1;
   1.499 +		UTIL_Format(keyname, sizeof(keyname), "%s_Reg_%s", name, platform);
   1.500 +		if ((value = g_pGameConf->GetKeyValue(keyname)) != NULL)
   1.501 +		{
   1.502 +			patch->regparam = atoi(value);
   1.503 +		}
   1.504 +
   1.505 +		/* Everything loaded from gamedata, make sure the patch will succeed. */
   1.506 +		unsigned char *address = (unsigned char *)patch->base + patch->offset;
   1.507 +		for (size_t i = 0; i < patch->search_len; i++)
   1.508 +		{
   1.509 +			if (address[i] != patch->search[i])
   1.510 +			{
   1.511 +				g_Logger.LogError("Command filter %s has changed (byte %x is not %x sub-offset %d)",
   1.512 +				                  name, address[i], patch->search[i], i);
   1.513 +				return false;
   1.514 +			}
   1.515 +		}
   1.516 +
   1.517 +		return true;
   1.518 +	}
   1.519 +};
   1.520 +
   1.521 +static bool dummy_hook_set = false;
   1.522 +void DummyHook()
   1.523 +{
   1.524 +	if (dummy_hook_set)
   1.525 +	{
   1.526 +		dummy_hook_set = false;
   1.527 +		RETURN_META(MRES_SUPERCEDE);
   1.528 +	}
   1.529 +}
   1.530 +
   1.531 +#endif
   1.532 +
   1.533 +/**
   1.534 + * BEGIN THE ACTUALLY GENERIC CODE.
   1.535 + */
   1.536 +
   1.537 +static GenericCommandHooker s_GenericHooker;
   1.538 +ConsoleDetours g_ConsoleDetours;
   1.539 +
   1.540 +ConsoleDetours::ConsoleDetours() : triedToEnable(false), isEnabled(false)
   1.541 +{
   1.542 +}
   1.543 +
   1.544 +void ConsoleDetours::OnSourceModAllInitialized()
   1.545 +{
   1.546 +	m_pForward = g_Forwards.CreateForwardEx("OnAnyCommand", ET_Hook, 3, NULL, Param_Cell,
   1.547 +	                                        Param_String, Param_Cell);
   1.548 +}
   1.549 +
   1.550 +void ConsoleDetours::OnSourceModShutdown()
   1.551 +{
   1.552 +	List<Listener*>::iterator iter = m_Listeners.begin();
   1.553 +	while (iter != m_Listeners.end())
   1.554 +	{
   1.555 +		Listener *listener = (*iter);
   1.556 +		g_Forwards.ReleaseForward(listener->forward);
   1.557 +		delete listener;
   1.558 +		iter = m_Listeners.erase(iter);
   1.559 +	}
   1.560 +
   1.561 +	g_Forwards.ReleaseForward(m_pForward);
   1.562 +	s_GenericHooker.Disable();
   1.563 +}
   1.564 +
   1.565 +bool ConsoleDetours::IsAvailable()
   1.566 +{
   1.567 +	if (triedToEnable)
   1.568 +		return isEnabled;
   1.569 +	isEnabled = s_GenericHooker.Enable();
   1.570 +	triedToEnable = true;
   1.571 +	return isEnabled;
   1.572 +}
   1.573 +
   1.574 +bool ConsoleDetours::AddListener(IPluginFunction *fun, const char *command)
   1.575 +{
   1.576 +	if (!IsAvailable())
   1.577 +		return false;
   1.578 +
   1.579 +	if (command == NULL)
   1.580 +	{
   1.581 +		m_pForward->AddFunction(fun);
   1.582 +	}
   1.583 +	else
   1.584 +	{
   1.585 +		const char *str = UTIL_ToLowerCase(command);
   1.586 +		Listener *listener;
   1.587 +		Listener **plistener = m_CmdLookup.retrieve(str);
   1.588 +		if (plistener == NULL)
   1.589 +		{
   1.590 +			listener = new Listener;
   1.591 +			listener->forward = g_Forwards.CreateForwardEx(NULL, ET_Hook, 3, NULL, Param_Cell,
   1.592 +			                                               Param_String, Param_Cell);
   1.593 +			m_CmdLookup.insert(str, listener);
   1.594 +		}
   1.595 +		else
   1.596 +		{
   1.597 +			listener = *plistener;
   1.598 +		}
   1.599 +		listener->forward->AddFunction(fun);
   1.600 +		delete [] str;
   1.601 +	}
   1.602 +
   1.603 +	return true;
   1.604 +}
   1.605 +
   1.606 +bool ConsoleDetours::RemoveListener(IPluginFunction *fun, const char *command)
   1.607 +{
   1.608 +	if (command == NULL)
   1.609 +	{
   1.610 +		return m_pForward->RemoveFunction(fun);
   1.611 +	}
   1.612 +	else
   1.613 +	{
   1.614 +		const char *str = UTIL_ToLowerCase(command);
   1.615 +		Listener *listener;
   1.616 +		Listener **plistener = m_CmdLookup.retrieve(str);
   1.617 +		delete [] str;
   1.618 +		if (plistener == NULL)
   1.619 +			return false;
   1.620 +		listener = *plistener;
   1.621 +		return listener->forward->RemoveFunction(fun);
   1.622 +	}
   1.623 +}
   1.624 +
   1.625 +cell_t ConsoleDetours::InternalDispatch(int client, const CCommand& args)
   1.626 +{
   1.627 +	char name[255];
   1.628 +	const char *realname = args.Arg(0);
   1.629 +	size_t len = strlen(realname);
   1.630 +	for (size_t i = 0; i < len; i++)
   1.631 +	{
   1.632 +		if (realname[i] >= 'A' && realname[i] <= 'Z')
   1.633 +			name[i] = tolower(realname[i]);
   1.634 +		else
   1.635 +			name[i] = realname[i];
   1.636 +	}
   1.637 +	name[len] = '\0';
   1.638 +
   1.639 +	cell_t result = Pl_Continue;
   1.640 +	m_pForward->PushCell(client);
   1.641 +	m_pForward->PushString(name);
   1.642 +	m_pForward->PushCell(args.ArgC() - 1);
   1.643 +	m_pForward->Execute(&result, NULL);
   1.644 +
   1.645 +	/* Don't let plugins block this. */
   1.646 +	if (strcmp(name, "sm") == 0)
   1.647 +		result = Pl_Continue;
   1.648 +
   1.649 +	if (result >= Pl_Stop)
   1.650 +		return result;
   1.651 +	
   1.652 +	Listener **plistener = m_CmdLookup.retrieve(name);
   1.653 +	if (plistener == NULL)
   1.654 +		return result;
   1.655 +	Listener *listener = *plistener;
   1.656 +	if (listener->forward->GetFunctionCount() == 0)
   1.657 +		return result;
   1.658 +
   1.659 +	cell_t result2 = Pl_Continue;
   1.660 +	listener->forward->PushCell(client);
   1.661 +	listener->forward->PushString(name);
   1.662 +	listener->forward->PushCell(args.ArgC() - 1);
   1.663 +	listener->forward->Execute(&result2, NULL);
   1.664 +
   1.665 +	if (result2 > result)
   1.666 +		result = result2;
   1.667 +
   1.668 +	/* "sm" should not have flown through the above. */
   1.669 +	assert(strcmp(name, "sm") != 0 || result == Pl_Continue);
   1.670 +
   1.671 +	return result;
   1.672 +}
   1.673 +
   1.674 +#if SOURCE_ENGINE >= SE_ORANGEBOX
   1.675 +cell_t ConsoleDetours::Dispatch(ConCommand *pBase, const CCommand& args)
   1.676 +{
   1.677 +#else
   1.678 +cell_t ConsoleDetours::Dispatch(ConCommand *pBase)
   1.679 +{
   1.680 +	CCommand args;
   1.681 +#endif
   1.682 +	g_HL2.PushCommandStack(&args);
   1.683 +	cell_t res = g_ConsoleDetours.InternalDispatch(g_ConCmds.GetCommandClient(), args);
   1.684 +	g_HL2.PopCommandStack();
   1.685 +
   1.686 +#if SH_IMPL_VERSION < 4
   1.687 +	if (res >= Pl_Handled)
   1.688 +	{
   1.689 +		/* See bug 4020 - we can't optimize this because looking at the vtable
   1.690 +		 * is probably more expensive, since there's no SH_GET_ORIG_VFNPTR_ENTRY.
   1.691 +		 */
   1.692 +		SH_ADD_HOOK_STATICFUNC(ConCommand, Dispatch, pBase, DummyHook, false);
   1.693 +		dummy_hook_set = true;
   1.694 +		pBase->Dispatch();
   1.695 +		SH_REMOVE_HOOK_STATICFUNC(ConCommand, Dispatch, pBase, DummyHook, false);
   1.696 +	}
   1.697 +	else
   1.698 +	{
   1.699 +		/* Make sure the command gets invoked. See bug 4019 on making this better. */
   1.700 +		pBase->Dispatch();
   1.701 +	}
   1.702 +#endif
   1.703 +
   1.704 +	return res;
   1.705 +}