Update gamedata for CS:S update.
2 * vim: set ts=4 sw=4 tw=99 noet :
3 * =============================================================================
5 * Copyright (C) 2004-2009 AlliedModders LLC. All rights reserved.
6 * =============================================================================
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.
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
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/>.
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>.
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
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.
42 #include "sourcemod.h"
43 #include "sourcemm_api.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>
55 #if defined PLATFORM_POSIX
57 # include <sys/mman.h>
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 &);
68 SH_DECL_EXTERN0_void(ConCommand, Dispatch, SH_NOATTRIB, false);
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>);
75 extern bool __SourceHook_FHAddConCommandDispatch(void *, bool, class fastdelegate::FastDelegate0<void>);
77 extern bool __SourceHook_FHRemoveConCommandDispatch(void *, bool, class fastdelegate::FastDelegate0<void>);
80 #if SH_IMPL_VERSION >= 4
82 class GenericCommandHooker : public IConCommandLinkListener
88 unsigned int refcount;
90 CVector<HackInfo> vtables;
92 SourceHook::MemFuncInfo dispatch;
94 inline void **GetVirtualTable(ConCommandBase *pBase)
96 return *reinterpret_cast<void***>(reinterpret_cast<char*>(pBase) +
97 dispatch.thisptroffs +
101 inline bool FindVtable(void **ptr, size_t& index)
103 for (size_t i = 0; i < vtables.size(); i++)
105 if (vtables[i].vtable == ptr)
114 void MakeHookable(ConCommandBase *pBase)
116 if (!pBase->IsCommand())
119 ConCommand *cmd = (ConCommand*)pBase;
120 void **vtable = GetVirtualTable(cmd);
123 if (!FindVtable(vtable, index))
126 hack.vtable = vtable;
127 hack.hook = SH_ADD_VPHOOK(ConCommand, Dispatch, cmd, SH_MEMBER(this, &GenericCommandHooker::Dispatch), false);
129 vtables.push_back(hack);
133 vtables[index].refcount++;
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)
145 cell_t res = ConsoleDetours::Dispatch(META_IFACEPTR(ConCommand)
146 # if SOURCE_ENGINE >= SE_ORANGEBOX
150 if (res >= Pl_Handled)
151 RETURN_META(MRES_SUPERCEDE);
154 void ReparseCommandList()
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())
163 if ((*iter).refcount)
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.
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.
178 * Even though the impact is really small, we'll wait until the
179 * server shuts down, so normal operation isn't interrupted.
183 iter = vtables.erase(iter);
187 void UnhookCommand(ConCommandBase *pBase)
189 if (!pBase->IsCommand())
192 ConCommand *cmd = (ConCommand*)pBase;
193 void **vtable = GetVirtualTable(cmd);
196 if (!FindVtable(vtable, index))
198 g_Logger.LogError("Console detour tried to unhook command \"%s\" but it wasn't found", pBase->GetName());
202 assert(vtables[index].refcount > 0);
203 vtables[index].refcount--;
204 if (vtables[index].refcount == 0)
206 SH_REMOVE_HOOK_ID(vtables[index].hook);
207 vtables.erase(vtables.iterAt(index));
212 GenericCommandHooker() : enabled(false)
218 SourceHook::GetFuncInfo(&ConCommand::Dispatch, dispatch);
220 if (dispatch.thisptroffs < 0)
222 g_Logger.LogError("Command filter could not determine ConCommand layout");
226 for (ConCommandBaseIterator iter; iter.IsValid(); iter.Next())
227 MakeHookable(iter.Get());
231 g_Logger.LogError("Command filter could not find any cvars!");
242 for (size_t i = 0; i < vtables.size(); i++)
243 SH_REMOVE_HOOK_ID(vtables[i].hook);
247 virtual void OnLinkConCommand(ConCommandBase *pBase)
254 virtual void OnUnlinkConCommand(ConCommandBase *pBase)
259 ReparseCommandList();
261 UnhookCommand(pBase);
266 * END DVP HOOK VERSION
269 #else /* SH_IMPL_VERSION >= 4 */
272 * BEGIN ENGINE DETOUR VERSION
275 # include <jit/jit_helpers.h>
276 # include <jit/x86/x86_macros.h>
278 class GenericCommandHooker
282 Patch() : applied(false)
288 unsigned char search[16];
300 static void DelayedActivation(void *inparam)
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)
307 g_SourceMod.AddFrameAction(GenericCommandHooker::DelayedActivation, cdtrs);
311 if (!cdtrs->ces.applied)
312 cdtrs->ApplyPatch(&cdtrs->ces);
313 if (!cdtrs->cgc.applied)
314 cdtrs->ApplyPatch(&cdtrs->cgc);
319 const char *platform = NULL;
320 # if defined(PLATFORM_WINDOWS)
321 platform = "Windows";
323 void *addrInBase = (void *)g_SMAPI->GetEngineFactory(false);
325 if (!dladdr(addrInBase, &info))
327 g_Logger.LogError("Command filter could not find engine name");
330 if (strstr(info.dli_fname, "engine_i486"))
332 platform = "Linux_486";
334 else if (strstr(info.dli_fname, "engine_i686"))
336 platform = "Linux_686";
338 else if (strstr(info.dli_fname, "engine_amd"))
340 platform = "Linux_AMD";
344 g_Logger.LogError("Command filter could not determine engine (%s)", info.dli_fname);
349 if (!PrepPatch("Cmd_ExecuteString", "CES", platform, &ces))
351 if (!PrepPatch("CGameClient::ExecuteString", "CGC", platform, &cgc))
354 if (g_HL2.PeekCommandStack() != NULL)
356 g_SourceMod.AddFrameAction(GenericCommandHooker::DelayedActivation, this);
374 # if !defined PLATFORM_WINDOWS
375 # define PAGE_READWRITE PROT_READ|PROT_WRITE
376 # define PAGE_EXECUTE_READ PROT_READ|PROT_EXEC
378 static inline uintptr_t AddrToPage(uintptr_t address)
380 return (address & ~(uintptr_t(sysconf(_SC_PAGE_SIZE) - 1)));
385 void Protect(void *addr, size_t length, int prot)
387 # if defined PLATFORM_WINDOWS
389 VirtualProtect(addr, length, prot, &ignore);
391 uintptr_t startPage = AddrToPage(uintptr_t(addr));
392 length += (uintptr_t(addr) - startPage);
393 mprotect((void*)startPage, length, prot);
397 void UndoPatch(Patch *patch)
399 if (!patch->applied || patch->detour == NULL)
402 g_pSourcePawn->FreePageMemory(patch->detour);
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);
411 void ApplyPatch(Patch *patch)
413 assert(!patch->applied);
416 void *callback = (void*)&ConsoleDetours::Dispatch;
418 /* Bogus assignment to make compiler is doing the right thing. */
419 patch->detour = callback;
421 /* Assemgle the detour. */
423 writer.outbase = NULL;
424 writer.outptr = NULL;
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);
433 if (patch->regparam != -1)
434 IA32_Pop_Reg(&writer, patch->regparam);
435 /* Copy any saved bytes */
438 for (size_t i = patch->saveat; i < patch->search_len; i++)
440 writer.write_ubyte(patch->search[i]);
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)
449 length = writer.outptr - writer.outbase;
450 patch->detour = g_pSourcePawn->AllocatePageMemory(length);
451 if (patch->detour == NULL)
453 g_Logger.LogError("Ran out of memory!");
456 g_pSourcePawn->SetReadWrite(patch->detour);
457 writer.outbase = (jitcode_t)patch->detour;
458 writer.outptr = writer.outbase;
466 g_pSourcePawn->SetReadExecute(patch->detour);
468 unsigned char *source = (unsigned char *)patch->base + patch->offset;
469 Protect(source, 6, PAGE_READWRITE);
472 *(void **)&source[2] = &patch->detour;
473 Protect(source, 6, PAGE_EXECUTE_READ);
475 patch->applied = true;
478 bool PrepPatch(const char *signature, const char *name, const char *platform, Patch *patch)
480 /* Get the base address of the function. */
481 if (!g_pGameConf->GetMemSig(signature, &patch->base) || patch->base == NULL)
483 g_Logger.LogError("Command filter could not find signature: %s", signature);
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)
494 g_Logger.LogError("Command filter could not find key: %s", keyname);
497 patch->search_len = UTIL_DecodeHexString(patch->search, sizeof(patch->search), value);
498 if (patch->search_len < 6)
500 g_Logger.LogError("Error decoding %s value, or not long enough", keyname);
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)
508 g_Logger.LogError("Command filter could not find key: %s", keyname);
511 patch->offset = atoi(value);
512 if (patch->offset > 20000)
514 g_Logger.LogError("Command filter %s value is bogus", keyname);
518 /* Get the number of bytes to save from what was written over. */
520 UTIL_Format(keyname, sizeof(keyname), "%s_Save_%s", name, platform);
521 if ((value = g_pGameConf->GetKeyValue(keyname)) != NULL)
523 patch->saveat = atoi(value);
524 if (patch->saveat >= patch->search_len)
526 g_Logger.LogError("Command filter %s value is too large", keyname);
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)
536 patch->regparam = atoi(value);
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++)
543 if (address[i] != patch->search[i])
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);
555 static bool dummy_hook_set = false;
560 dummy_hook_set = false;
561 RETURN_META(MRES_SUPERCEDE);
568 * BEGIN THE ACTUALLY GENERIC CODE.
571 #define FEATURECAP_COMMANDLISTENER "command listener"
573 static GenericCommandHooker s_GenericHooker;
574 ConsoleDetours g_ConsoleDetours;
576 ConsoleDetours::ConsoleDetours() : status(FeatureStatus_Unknown)
580 void ConsoleDetours::OnSourceModAllInitialized()
582 m_pForward = forwardsys->CreateForwardEx("OnAnyCommand", ET_Hook, 3, NULL, Param_Cell,
583 Param_String, Param_Cell);
584 sharesys->AddCapabilityProvider(NULL, this, FEATURECAP_COMMANDLISTENER);
587 void ConsoleDetours::OnSourceModShutdown()
589 for (StringHashMap<IChangeableForward *>::iterator iter = m_Listeners.iter();
593 forwardsys->ReleaseForward(iter->value);
596 forwardsys->ReleaseForward(m_pForward);
597 s_GenericHooker.Disable();
600 FeatureStatus ConsoleDetours::GetFeatureStatus(FeatureType type, const char *name)
605 FeatureStatus ConsoleDetours::GetStatus()
607 if (status == FeatureStatus_Unknown)
609 status = s_GenericHooker.Enable() ? FeatureStatus_Available : FeatureStatus_Unavailable;
614 bool ConsoleDetours::AddListener(IPluginFunction *fun, const char *command)
616 if (GetStatus() != FeatureStatus_Available)
621 m_pForward->AddFunction(fun);
625 ke::AutoArray<char> str(UTIL_ToLowerCase(command));
626 IChangeableForward *forward;
627 if (!m_Listeners.retrieve(str, &forward))
629 forward = forwardsys->CreateForwardEx(NULL, ET_Hook, 3, NULL, Param_Cell,
630 Param_String, Param_Cell);
631 m_Listeners.insert(str, forward);
633 forward->AddFunction(fun);
639 bool ConsoleDetours::RemoveListener(IPluginFunction *fun, const char *command)
643 return m_pForward->RemoveFunction(fun);
647 ke::AutoArray<char> str(UTIL_ToLowerCase(command));
648 IChangeableForward *forward;
649 if (!m_Listeners.retrieve(str, &forward))
651 return forward->RemoveFunction(fun);
655 cell_t ConsoleDetours::InternalDispatch(int client, const CCommand& args)
658 const char *realname = args.Arg(0);
659 size_t len = strlen(realname);
661 // Disallow command strings that are too long, for now.
662 if (len >= sizeof(name) - 1)
665 for (size_t i = 0; i < len; i++)
667 if (realname[i] >= 'A' && realname[i] <= 'Z')
668 name[i] = tolower(realname[i]);
670 name[i] = realname[i];
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);
680 /* Don't let plugins block this. */
681 if (strcmp(name, "sm") == 0)
682 result = Pl_Continue;
684 if (result >= Pl_Handled)
687 IChangeableForward *forward;
688 if (!m_Listeners.retrieve(name, &forward))
690 if (forward->GetFunctionCount() == 0)
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);
699 if (result2 > result)
702 /* "sm" should not have flown through the above. */
703 assert(strcmp(name, "sm") != 0 || result == Pl_Continue);
708 #if SOURCE_ENGINE >= SE_ORANGEBOX
709 cell_t ConsoleDetours::Dispatch(ConCommand *pBase, const CCommand& args)
712 cell_t ConsoleDetours::Dispatch(ConCommand *pBase)
716 g_HL2.PushCommandStack(&args);
717 cell_t res = g_ConsoleDetours.InternalDispatch(g_ConCmds.GetCommandClient(), args);
718 g_HL2.PopCommandStack();
720 #if SH_IMPL_VERSION < 4
721 if (res >= Pl_Handled)
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.
726 SH_ADD_HOOK(ConCommand, Dispatch, pBase, SH_STATIC(DummyHook), false);
727 dummy_hook_set = true;
729 SH_REMOVE_HOOK(ConCommand, Dispatch, pBase, SH_STATIC(DummyHook), false);
733 /* Make sure the command gets invoked. See bug 4019 on making this better. */