1 /* ======== SourceHook ========
2 * Copyright (C) 2004-2007 Metamod:Source Development Team
3 * No warranties of any kind
7 * Author(s): Pavol "PM OnoTo" Marko
8 * ============================
11 #ifndef __SOURCEHOOK_IMPL_H__
12 #define __SOURCEHOOK_IMPL_H__
14 #include "sourcehook.h"
16 #include "sh_vector.h"
17 #include "sh_tinyhash.h"
19 #include "sh_listcat.h"
25 ---------------------------------------
27 The purpose of protos is to provide the amount of type information about a function
28 which is required to be able to execute a function call without corrupting the stack.
29 Our protos do not fully do this, but they provide the size of the return value, the number of
30 parameters, and the size of each parameter, which is enough for most situations.
32 There are two version of protos:
41 "attrib|param1_type|param2_type
45 "attrib|ret_type|param1_type"
47 "attrib|ret_type|param2_type"
49 Old protos are deprecated.
52 New protos are in fact pointers to the ProtoInfo structure (see sourcehook.h)
54 Old protos begin with a non-zero byte, new protos begin with a zero byte.
56 Protos are usually stored in a CProto instance.
58 ---------------------------------------
59 Hook managers and hook manager containers
60 Each hookman container is tied to _one_ proto/vtable index/vtable offset info.
61 Hookman containers then contain a list of hook managers provided by plugins, sorted by version.
62 (higher versions come first)
64 Duplicate hook managers are ignored (ie. hook managers where proto, vtable index, vtable offset,
65 plugin, version are the same as in an already exisiting hook manager)
67 A new hook manager is always added to the end of the version group in the corresponding
70 If the new hook manager was added to the beginning of the container (which only happens if
71 it is the first one or if it has a higher version than the previously first hook manager),
72 the now second hook manager is shut down and the new hook manager takes its job.
74 A "hook manager container id" (HMCI) consits of three values: proto, vtbl index, vtbl offset.
75 ---------------------------------------
77 When adding a hook, first the proposed hook manager is added to the corresponding
78 hook manager container as described above.
80 Then the first hook manager in the the manhook container is chosen to handle the function.
82 Removing a hook does not neccessarily unreigster the plugin's hook manager. In order to do this,
83 use RemoveHookManager or UnloadPlugin/
85 Hooks can be paused - they remain in memory but they are not called. In SH, the hook iterator
86 classes handle pausing transparently.
88 The hook loop is supposed to call ShouldContinue before each iteration. This makes hook handlers
89 able to remove themselves.
91 ---------------------------------------
94 !! deprecated !! - see below (new SH_CALL)
96 Call classes are identified by a this pointer and an instance size
98 We use the instance size because a derived class instance and a base class instance could
99 have the same this pointers, and we want to avoid that the derived class
100 (which could be bigger) gets the same callclass as the base class (mainly if the
101 base class' callclass was requested first).
103 Call classes are reference counted.
105 The original function pointers are stored in a vector (in order to allow fast random access).
106 These vectors are stored as the value type of a hash. The key type is int and represents the
109 If the hash key doesn't exist or the vtblidx is out of range or the corresponding element in the
110 vector is NULL, there is no hook on that function.
112 ---------------------------------------
114 Recalls are used for the META_RETURN_(VALUE_)NEWPARAMS macros, ie. to change the parameters
115 in the hook loop on the fly.
117 First, the macro calls DoRecall(), then it calls the function the hook is attached to -> it
118 calls the hookfunc. SourceHook makes sure that the newly invoked hook loop starts where the last
119 one left off and that status variables like status, previous result, override return are kept.
120 When this recurisvely called hookfunc returns, the macro returns what it returned
121 (using MRES_SUPERCEDE). CSourceHookImpl returns false from ShouldContinue so the original hook loop
125 People wanted to be able to use META_RETURN_(VALUE_)NEWPARAMS from post hooks as well. Crazy people!
126 Anyway, for this, we have to know where a hook handler is. Is it executing pre or post hooks at the moment?
127 The only way we can know this is watching when it calls CHookList::GetIter(). So CHookList gets a new variable:
128 m_RequestedFlag. It also gets two new functions: RQFlagReset() and RQFlagGet().
129 HookLoopBegin() calls RQFlagReset on both hooklists of the iface; then DoRecall() checks whether the postlist's
130 RQ flag is set. if yes, the hook loop is in post mode.
132 So, what a about a recall in post mode? The first ShouldContinue returns false and sets Status to supercede.
133 This way the pre hooks and the function call will be skipped. Then, then next ShouldContinue returns true, so we get
134 into the post hooks. HA!
136 Return Values in Post Recalls
137 The easy case is when we already have an override return value. In this case, the status register gets transferred,
138 and so does the override return pointer. So, basically, everything is ok.
140 However, what happens if we don't? ie. the status register is on MRES_IGNORED? In this case we'd have to transfer the
141 orig ret value. But we can't: There's no way to tell the hookfunc: "Use this as orig ret pointer". It uses its own.
142 So, we emulate it. GetOrigRet will return the orig ret pointer from the old hook loop. If still no one overrides it,
143 we'd have to return it. BUT! HOW TO DO THIS? Check out SH_RETURN(). First calls HookLoopEnd(), then decides whether
144 to return the override retval or the orig retval. But it doesn't ask for a new override return. So we give the function
145 the last orig return value as its new override return value; but leave status where it is so everything works, and in
146 HookLoopEnd we make sure that status is high enough so that the override return will be returned. crazy.
148 All this stuff could be much less complicated if I didn't try to preserve binary compatibility :)
151 VP hooks are hooks which are called on a vfnptr, regardless of the this pointer with which it was called. They are
152 implemented as a special CIface instance with m_Ptr = NULL. All Hook Lists have a new "ListCatIterator" which
153 virtually concatenates the NULL-interface-hook-list with their normal hook list.
156 I'm afraid that with the addition of Recalls and VP Hooks, SourceHook is now a pretty complex and hacked-together
157 binary compatible beast which is pretty hard to maintain unless you've written it :)
160 The addition of VP hooks messed up the Call Classes concept (see above) - call classes are bound to an
161 instance pointer; they only work on one of the hooked instances. But VP hooks are called on all instances.
163 That's why now, SH_CALL takes an instance pointer instead of a callclass pointer. It basically does this:
164 1) call SH_GLOB_PTR->SetIgnoreHooks(vfnptr)
166 3) call SH_GLOB_PTR->ResetIgnoreHooks(vfnptr)
168 SourceHook stroes the "ignored vfnptr" and makes CVfnPtr::FindIface return NULL if the CVfnPtr instance
169 corresponds to the ignored vfnptr. This way the hook manager thinks that the instance isn't hooked, and calls
170 the original function. Everything works fine. This works even for VP hooks.
173 // See sourcehook.hxx :)
175 #undef ManualCallClass
180 * @brief The SourceHook implementation class
182 class CSourceHookImpl : public ISourceHook
189 static bool Equal(const char *p1, const char *p2);
190 char *DupProto(const char *src);
191 void FreeProto(char *prot);
193 CProto() : m_Proto(NULL)
197 CProto(const char *szProto) : m_Proto(DupProto(szProto))
201 CProto(const CProto &other) : m_Proto(DupProto(other.m_Proto))
211 void operator = (const char *szProto)
213 m_Proto = DupProto(szProto);
216 void operator = (const CProto &other)
218 m_Proto = DupProto(other.m_Proto);
221 bool operator == (const char *szProto) const
223 return Equal(szProto, m_Proto);
225 bool operator == (const CProto &other) const
227 return Equal(other.m_Proto, m_Proto);
230 const char *GetProto() const
238 * @brief A hook can be removed if you have this information
240 struct RemoveHookInfo
242 RemoveHookInfo(Plugin pplug, void *piface, int tpo, HookManagerPubFunc phookman,
243 ISHDelegate *phandler, bool ppost)
244 : plug(pplug), iface(piface), thisptr_offs(tpo),
245 hookman(phookman), handler(phandler), post(ppost)
252 HookManagerPubFunc hookman;
253 ISHDelegate *handler;
257 struct RemoveHookManInfo
259 RemoveHookManInfo(Plugin pplug, HookManagerPubFunc phookman)
260 : plug(pplug), hookman(phookman)
265 HookManagerPubFunc hookman;
268 // Associates hook ids with info about the hooks
269 // Also used to keep track of used hook ids
291 ISHDelegate *handler;
294 Entry(const CProto &pprt, int pvo, int pvi, void *pvp, void *pai, Plugin pplug, int pto,
295 ISHDelegate *ph, bool ppost)
296 : isfree(false), proto(pprt), vtbl_offs(pvo), vtbl_idx(pvi), vfnptr(pvp),
297 adjustediface(pai), plug(pplug), thisptr_offs(pto), handler(ph), post(ppost)
305 // Internally, hookid 1 is stored as m_Entries[0]
307 CVector<Entry> m_Entries;
310 int New(const CProto &proto, int vtbl_offs, int vtbl_idx, void *vfnptr, void *adjustediface,
311 Plugin plug, int thisptr_offs, ISHDelegate *handler, bool post);
312 bool Remove(int hookid);
313 const Entry * QueryHook(int hookid);
315 // Finds all hooks with the given info, and fills the hookids into output.
316 void FindAllHooks(CVector<int> &output, const CProto &proto, int vtbl_offs, int vtbl_idx,
317 void *adjustediface, Plugin plug, int thisptr_offs, ISHDelegate *handler, bool post);
319 // Removes all hooks with a specified vfnptr
320 bool RemoveAll(void *vfnptr);
325 ISHDelegate *handler; //!< Pointer to the handler
326 bool paused; //!< If true, the hook should not be executed
327 Plugin plug; //!< The owner plugin
328 int thisptr_offs; //!< This pointer offset
329 int hookid; //!< Unique ID given by CHookIDManager
331 bool operator==(int otherid)
333 return hookid == otherid;
337 class CHookList : public IHookList
340 List<HookInfo> *m_VPList; // left-hand list for ListCatIterator -> for VP hooks
341 List<HookInfo> m_List;
345 class CIter : public IHookList::IIter
347 friend class CHookList;
354 ListCatIterator<HookInfo> m_Iter;
356 CIter(CHookList *pList);
361 void Set(CIter *pOther);
365 ISHDelegate *Handler();
370 CIter *m_pNext; // When stored in m_FreeIters and m_UsedIters
371 CIter *m_pPrev; // Only used when stored in m_UsedIters
375 CIter *m_UsedIters; // The last returned and not-yet-released iter is always m_UsedIters
381 void SetRecallState(); // Sets the list into a state where the next returned
382 // iterator (from GetIter) will be a copy of the last
383 // returned iterator, incremented by one. This is used in Recalls.
384 // The hook resets this state automatically on:
385 // GetIter, ReleaseIter
387 void RQFlagReset() { m_RQFlag = false; }
388 bool RQFlagGet() { return m_RQFlag; }
390 CHookList(const CHookList &other);
391 virtual ~CHookList();
393 void operator=(const CHookList &other);
396 void ReleaseIter(IIter *pIter);
398 void SetVPList(List<HookInfo> *newList);
402 // I know, data hiding... But I'm a lazy bastard!
404 class CIface : public IIface
408 CHookList m_PreHooks;
409 CHookList m_PostHooks;
415 IHookList *GetPreHooks();
416 IHookList *GetPostHooks();
418 bool operator==(void *ptr)
422 bool operator!=(void *ptr)
428 class CVfnPtr : public IVfnPtr
431 typedef List<CIface> IfaceList;
432 typedef IfaceList::iterator IfaceListIter;
441 CVfnPtr(void *ptr, void **pOneIgnore);
445 void *GetOrigEntry();
447 virtual IIface *FindIface(void *ptr);
449 bool operator==(void *ptr)
455 class CHookManagerInfo : public IHookManagerInfo
458 typedef List<CVfnPtr> VfnPtrList;
459 typedef VfnPtrList::iterator VfnPtrListIter;
462 HookManagerPubFunc m_Func;
467 void *m_HookfuncVfnptr;
469 VfnPtrList m_VfnPtrs;
471 int m_HookManVersion;
474 virtual ~CHookManagerInfo();
476 IVfnPtr *FindVfnPtr(void *vfnptr);
478 void SetInfo(int vtbl_offs, int vtbl_idx, const char *proto);
479 void SetHookfuncVfnptr(void *hookfunc_vfnptr);
481 void SetVersion(int version);
483 bool operator < (const CHookManagerInfo &other)
485 return m_HookManVersion < other.m_HookManVersion;
490 Descriptor(Plugin pplug, HookManagerPubFunc ppubFunc) : plug(pplug), pubFunc(ppubFunc)
495 HookManagerPubFunc pubFunc;
498 bool operator == (const Descriptor desc)
500 return m_Func == desc.pubFunc && m_Plug == desc.plug;
504 typedef List<CHookManagerInfo> HookManInfoList;
506 class CHookManagerContainer : public HookManInfoList
509 // HMCI (Hook Manager Container Identification)
516 HMCI(const char *proto, int vtbloffs, int vtblidx) :
517 m_Proto(proto), m_VtableOffset(vtbloffs), m_VtableIndex(vtblidx)
524 bool operator==(const HMCI &other) const
527 other.m_VtableIndex == m_VtableIndex &&
528 other.m_Proto == m_Proto &&
529 other.m_VtableOffset == m_VtableOffset;
532 const CProto &GetProto() const
536 int GetVtableOffset() const
538 return m_VtableOffset;
540 int GetVtableIndex() const
542 return m_VtableIndex;
548 CHookManagerContainer(const HMCI &hmci) : m_HCMI(hmci)
551 bool operator == (const HMCI &other) const
553 return m_HCMI == other;
555 void AddHookManager(Plugin plug, const CHookManagerInfo &hookman);
558 class CCallClassImpl : public GenericCallClass
562 typedef SourceHook::CVector<void*> OrigFuncs;
563 typedef SourceHook::THash<int, OrigFuncs> OrigVTables;
565 void *m_Ptr; //!< Pointer to the actual object
566 size_t m_ObjSize; //!< Size of the instance
567 OrigVTables m_VT; //!< Info about vtables & functions
571 CCallClassImpl(void *ptr, size_t size);
572 virtual ~CCallClassImpl();
574 bool operator==(void *other)
576 return m_Ptr == other;
580 void *GetOrigFunc(int vtbloffs, int vtblidx);
582 void ApplyCallClassPatch(int vtbl_offs, int vtbl_idx, void *orig_entry);
583 void RemoveCallClassPatch(int vtbl_offs, int vtbl_idx);
587 * @brief A list of CallClass structures
589 typedef List<CCallClassImpl> Impl_CallClassList;
591 Impl_CallClassList m_CallClasses; //!< A list of already generated callclasses
594 * @brief A list of CHookManagerContainers
596 typedef List<CHookManagerContainer> HookManContList;
598 HookManContList m_HookMans; //!< A list of hook managers
614 META_RES temporaryStatus; //!< Stored during Post1 recall phase
616 RecallType recall; //!< Specifies which kind of recall we're in.
619 const void *pOrigRet;
623 typedef CStack<HookLoopInfo> HookLoopInfoStack;
625 void ApplyCallClassPatches(CCallClassImpl &cc);
626 void ApplyCallClassPatches(void *ifaceptr, int vtbl_offs, int vtbl_idx, void *orig_entry);
627 void RemoveCallClassPatches(void *ifaceptr, int vtbl_offs, int vtbl_idx);
629 void SetPluginPaused(Plugin plug, bool paused);
631 HookLoopInfoStack m_HLIStack;
632 CHookIDManager m_HookIDMan;
634 void *m_OneIgnore; //:TODO:
638 virtual ~CSourceHookImpl();
641 * @brief Returns the interface version
643 int GetIfaceVersion();
646 * @brief Returns the implemnetation version
648 int GetImplVersion();
651 * @brief Make sure that a plugin is not used by any other plugins anymore, and unregister all its hook managers
653 void UnloadPlugin(Plugin plug);
656 * @brief Shut down the whole system, unregister all hook managers
658 void CompleteShutdown();
663 * @return True if the function succeeded, false otherwise
665 * @param plug The unique identifier of the plugin that calls this function
666 * @param iface The interface pointer
667 * @param ifacesize The size of the class iface points to
668 * @param myHookMan A hook manager function that should be capable of handling the function
669 * @param handler A pointer to a FastDelegate containing the hook handler
670 * @param post Set to true if you want a post handler
672 bool AddHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan, ISHDelegate *handler, bool post);
675 * @brief Removes a hook.
677 * @return True if the function succeeded, false otherwise
679 * @param plug The unique identifier of the plugin that calls this function
680 * @param iface The interface pointer
681 * @param thisptr_offs This pointer adjuster
682 * @param myHookMan A hook manager function that should be capable of handling the function
683 * @param handler A pointer to a FastDelegate containing the hook handler
684 * @param post Set to true if you want a post handler
686 bool RemoveHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan, ISHDelegate *handler, bool post);
689 * @brief Removes a hook.
691 * @ return True if the function succeeded, false otherwise
693 * @param info A RemoveHookInfo structure, describing the hook
695 bool RemoveHook(RemoveHookInfo info);
698 * @brief Checks whether a plugin has (a) hook manager(s) that is/are currently used by other plugins
700 * @param plug The unique identifier of the plugin in question
702 bool IsPluginInUse(Plugin plug);
705 * @brief Pauses all hooks of a plugin
707 * @param plug The unique identifier of the plugin
709 void PausePlugin(Plugin plug);
712 * @brief Unpauses all hooks of a plugin
714 * @param plug The unique identifier of the plugin
716 void UnpausePlugin(Plugin plug);
719 * @brief Return a pointer to a callclass. Generate a new one if required.
721 * @param iface The interface pointer
722 * @param size Size of the class instance
724 GenericCallClass *GetCallClass(void *iface, size_t size);
727 * @brief Release a callclass
729 * @param ptr Pointer to the callclass
731 virtual void ReleaseCallClass(GenericCallClass *ptr);
733 virtual void SetRes(META_RES res); //!< Sets the meta result
734 virtual META_RES GetPrevRes(); //!< Gets the meta result of the previously called handler
735 virtual META_RES GetStatus(); //!< Gets the highest meta result
736 virtual const void *GetOrigRet(); //!< Gets the original result. If not in post function, undefined
737 virtual const void *GetOverrideRet(); //!< Gets the override result. If none is specified, NULL
738 virtual void *GetIfacePtr(); //!< Gets the interface pointer
740 //////////////////////////////////////////////////////////////////////////
742 void HookLoopBegin(IIface *pIface); //!< Should be called when a hook loop begins
743 void HookLoopEnd(); //!< Should be called when a hook loop exits
744 void SetCurResPtr(META_RES *mres); //!< Sets pointer to the current meta result
745 void SetPrevResPtr(META_RES *mres); //!< Sets pointer to previous meta result
746 void SetStatusPtr(META_RES *mres); //!< Sets pointer to the status variable
747 void SetIfacePtrPtr(void **pp); //!< Sets pointer to the interface this pointer
748 void SetOrigRetPtr(const void *ptr); //!< Sets the original return pointer
749 void SetOverrideRetPtr(void *ptr); //!< Sets the override result pointer
750 bool ShouldContinue(); //!< Returns false if the hook loop should exit
753 * @brief Remove a hook manager. Auto-removes all hooks attached to it from plugin plug.
755 * @param plug The owner of the hook manager
756 * @param pubFunc The hook manager's info function
758 virtual void RemoveHookManager(Plugin plug, HookManagerPubFunc pubFunc);
759 virtual void RemoveHookManager(RemoveHookManInfo info);
761 virtual void DoRecall(); //!< Initiates a recall sequence
762 virtual void *GetOverrideRetPtr(); //!< Returns the pointer set by SetOverrideRetPtr
764 virtual void *SetupHookLoop(META_RES *statusPtr, META_RES *prevResPtr, META_RES *curResPtr,
765 void **ifacePtrPtr, const void *origRetPtr, void *overrideRetPtr);
768 * @brief Add a (VP) hook.
770 * @return non-zero hook id on success, 0 otherwise
772 * @param plug The unique identifier of the plugin that calls this function
773 * @param mode Can be either Hook_Normal or Hook_VP (vtable-wide hook)
774 * @param iface The interface pointer
775 * The representative interface pointer for VP hooks
776 * The vtable pointer for direct VP hooks !!!
777 * @param ifacesize The size of the class iface points to
778 * @param myHookMan A hook manager function that should be capable of handling the function
779 * @param handler A pointer to a FastDelegate containing the hook handler
780 * @param post Set to true if you want a post handler
782 virtual int AddHookNew(Plugin plug, AddHookMode mode, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan,
783 ISHDelegate *handler, bool post);
786 * @brief Remove a VP hook by ID.
788 * @return true on success, false otherwise
790 * @param plug The unique identifier of the plugin that calls this function
791 * @param hookid The hook id (returned by AddHookNew)
793 virtual bool RemoveHookByID(Plugin plug, int hookid);
796 * @brief Makes sure that hooks are going to be ignored on the next call of vfnptr
798 * @param plug The unique identifier of the plugin that calls this function
799 * @param vfnptr The virtual function pointer of the function in question
801 virtual void SetIgnoreHooks(Plugin plug, void *vfnptr);
804 * @brief Reverses SetIgnoreHooks' effect
806 * @param plug The unique identifier of the plugin that calls this function
807 * @param vfnptr The virtual function pointer of the function in question
809 virtual void ResetIgnoreHooks(Plugin plug, void *vfnptr);