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.
176 * @brief The SourceHook implementation class
178 class CSourceHookImpl : public ISourceHook
185 static bool Equal(const char *p1, const char *p2);
186 char *DupProto(const char *src);
187 void FreeProto(char *prot);
189 CProto() : m_Proto(NULL)
193 CProto(const char *szProto) : m_Proto(DupProto(szProto))
197 CProto(const CProto &other) : m_Proto(DupProto(other.m_Proto))
207 void operator = (const char *szProto)
209 m_Proto = DupProto(szProto);
212 void operator = (const CProto &other)
214 m_Proto = DupProto(other.m_Proto);
217 bool operator == (const char *szProto) const
219 return Equal(szProto, m_Proto);
221 bool operator == (const CProto &other) const
223 return Equal(other.m_Proto, m_Proto);
226 const char *GetProto() const
234 * @brief A hook can be removed if you have this information
236 struct RemoveHookInfo
238 RemoveHookInfo(Plugin pplug, void *piface, int tpo, HookManagerPubFunc phookman,
239 ISHDelegate *phandler, bool ppost)
240 : plug(pplug), iface(piface), thisptr_offs(tpo),
241 hookman(phookman), handler(phandler), post(ppost)
248 HookManagerPubFunc hookman;
249 ISHDelegate *handler;
253 struct RemoveHookManInfo
255 RemoveHookManInfo(Plugin pplug, HookManagerPubFunc phookman)
256 : plug(pplug), hookman(phookman)
261 HookManagerPubFunc hookman;
264 // Associates hook ids with info about the hooks
265 // Also used to keep track of used hook ids
287 ISHDelegate *handler;
290 Entry(const CProto &pprt, int pvo, int pvi, void *pvp, void *pai, Plugin pplug, int pto,
291 ISHDelegate *ph, bool ppost)
292 : isfree(false), proto(pprt), vtbl_offs(pvo), vtbl_idx(pvi), vfnptr(pvp),
293 adjustediface(pai), plug(pplug), thisptr_offs(pto), handler(ph), post(ppost)
301 // Internally, hookid 1 is stored as m_Entries[0]
303 CVector<Entry> m_Entries;
306 int New(const CProto &proto, int vtbl_offs, int vtbl_idx, void *vfnptr, void *adjustediface,
307 Plugin plug, int thisptr_offs, ISHDelegate *handler, bool post);
308 bool Remove(int hookid);
309 const Entry * QueryHook(int hookid);
311 // Finds all hooks with the given info, and fills the hookids into output.
312 void FindAllHooks(CVector<int> &output, const CProto &proto, int vtbl_offs, int vtbl_idx,
313 void *adjustediface, Plugin plug, int thisptr_offs, ISHDelegate *handler, bool post);
315 // Removes all hooks with a specified vfnptr
316 bool RemoveAll(void *vfnptr);
321 ISHDelegate *handler; //!< Pointer to the handler
322 bool paused; //!< If true, the hook should not be executed
323 Plugin plug; //!< The owner plugin
324 int thisptr_offs; //!< This pointer offset
325 int hookid; //!< Unique ID given by CHookIDManager
327 bool operator==(int otherid)
329 return hookid == otherid;
333 class CHookList : public IHookList
336 List<HookInfo> *m_VPList; // left-hand list for ListCatIterator -> for VP hooks
337 List<HookInfo> m_List;
341 class CIter : public IHookList::IIter
343 friend class CHookList;
350 ListCatIterator<HookInfo> m_Iter;
352 CIter(CHookList *pList);
357 void Set(CIter *pOther);
361 ISHDelegate *Handler();
366 CIter *m_pNext; // When stored in m_FreeIters and m_UsedIters
367 CIter *m_pPrev; // Only used when stored in m_UsedIters
371 CIter *m_UsedIters; // The last returned and not-yet-released iter is always m_UsedIters
377 void SetRecallState(); // Sets the list into a state where the next returned
378 // iterator (from GetIter) will be a copy of the last
379 // returned iterator, incremented by one. This is used in Recalls.
380 // The hook resets this state automatically on:
381 // GetIter, ReleaseIter
383 void RQFlagReset() { m_RQFlag = false; }
384 bool RQFlagGet() { return m_RQFlag; }
386 CHookList(const CHookList &other);
387 virtual ~CHookList();
389 void operator=(const CHookList &other);
392 void ReleaseIter(IIter *pIter);
394 void SetVPList(List<HookInfo> *newList);
398 // I know, data hiding... But I'm a lazy bastard!
400 class CIface : public IIface
404 CHookList m_PreHooks;
405 CHookList m_PostHooks;
411 IHookList *GetPreHooks();
412 IHookList *GetPostHooks();
414 bool operator==(void *ptr)
418 bool operator!=(void *ptr)
424 class CVfnPtr : public IVfnPtr
427 typedef List<CIface> IfaceList;
428 typedef IfaceList::iterator IfaceListIter;
437 CVfnPtr(void *ptr, void **pOneIgnore);
441 void *GetOrigEntry();
443 virtual IIface *FindIface(void *ptr);
445 bool operator==(void *ptr)
451 class CHookManagerInfo : public IHookManagerInfo
454 typedef List<CVfnPtr> VfnPtrList;
455 typedef VfnPtrList::iterator VfnPtrListIter;
458 HookManagerPubFunc m_Func;
463 void *m_HookfuncVfnptr;
465 VfnPtrList m_VfnPtrs;
467 int m_HookManVersion;
470 virtual ~CHookManagerInfo();
472 IVfnPtr *FindVfnPtr(void *vfnptr);
474 void SetInfo(int vtbl_offs, int vtbl_idx, const char *proto);
475 void SetHookfuncVfnptr(void *hookfunc_vfnptr);
477 void SetVersion(int version);
479 bool operator < (const CHookManagerInfo &other)
481 return m_HookManVersion < other.m_HookManVersion;
486 Descriptor(Plugin pplug, HookManagerPubFunc ppubFunc) : plug(pplug), pubFunc(ppubFunc)
491 HookManagerPubFunc pubFunc;
494 bool operator == (const Descriptor desc)
496 return m_Func == desc.pubFunc && m_Plug == desc.plug;
500 typedef List<CHookManagerInfo> HookManInfoList;
502 class CHookManagerContainer : public HookManInfoList
505 // HMCI (Hook Manager Container Identification)
512 HMCI(const char *proto, int vtbloffs, int vtblidx) :
513 m_Proto(proto), m_VtableOffset(vtbloffs), m_VtableIndex(vtblidx)
520 bool operator==(const HMCI &other) const
523 other.m_VtableIndex == m_VtableIndex &&
524 other.m_Proto == m_Proto &&
525 other.m_VtableOffset == m_VtableOffset;
528 const CProto &GetProto() const
532 int GetVtableOffset() const
534 return m_VtableOffset;
536 int GetVtableIndex() const
538 return m_VtableIndex;
544 CHookManagerContainer(const HMCI &hmci) : m_HCMI(hmci)
547 bool operator == (const HMCI &other) const
549 return m_HCMI == other;
551 void AddHookManager(Plugin plug, const CHookManagerInfo &hookman);
554 class CCallClassImpl : public DeprecatedCallClass<void>
558 typedef SourceHook::CVector<void*> OrigFuncs;
559 typedef SourceHook::THash<int, OrigFuncs> OrigVTables;
561 void *m_Ptr; //!< Pointer to the actual object
562 size_t m_ObjSize; //!< Size of the instance
563 OrigVTables m_VT; //!< Info about vtables & functions
567 CCallClassImpl(void *ptr, size_t size);
568 virtual ~CCallClassImpl();
570 bool operator==(void *other)
572 return m_Ptr == other;
576 void *GetOrigFunc(int vtbloffs, int vtblidx);
578 void ApplyCallClassPatch(int vtbl_offs, int vtbl_idx, void *orig_entry);
579 void RemoveCallClassPatch(int vtbl_offs, int vtbl_idx);
583 * @brief A list of CallClass structures
585 typedef List<CCallClassImpl> Impl_CallClassList;
587 Impl_CallClassList m_CallClasses; //!< A list of already generated callclasses
590 * @brief A list of CHookManagerContainers
592 typedef List<CHookManagerContainer> HookManContList;
594 HookManContList m_HookMans; //!< A list of hook managers
610 META_RES temporaryStatus; //!< Stored during Post1 recall phase
612 RecallType recall; //!< Specifies which kind of recall we're in.
615 const void *pOrigRet;
619 typedef CStack<HookLoopInfo> HookLoopInfoStack;
621 void ApplyCallClassPatches(CCallClassImpl &cc);
622 void ApplyCallClassPatches(void *ifaceptr, int vtbl_offs, int vtbl_idx, void *orig_entry);
623 void RemoveCallClassPatches(void *ifaceptr, int vtbl_offs, int vtbl_idx);
625 void SetPluginPaused(Plugin plug, bool paused);
627 HookLoopInfoStack m_HLIStack;
628 CHookIDManager m_HookIDMan;
630 void *m_OneIgnore; //:TODO:
634 virtual ~CSourceHookImpl();
637 * @brief Returns the interface version
639 int GetIfaceVersion();
642 * @brief Returns the implemnetation version
644 int GetImplVersion();
647 * @brief Make sure that a plugin is not used by any other plugins anymore, and unregister all its hook managers
649 void UnloadPlugin(Plugin plug);
652 * @brief Shut down the whole system, unregister all hook managers
654 void CompleteShutdown();
659 * @return True if the function succeeded, false otherwise
661 * @param plug The unique identifier of the plugin that calls this function
662 * @param iface The interface pointer
663 * @param ifacesize The size of the class iface points to
664 * @param myHookMan A hook manager function that should be capable of handling the function
665 * @param handler A pointer to a FastDelegate containing the hook handler
666 * @param post Set to true if you want a post handler
668 bool AddHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan, ISHDelegate *handler, bool post);
671 * @brief Removes a hook.
673 * @return True if the function succeeded, false otherwise
675 * @param plug The unique identifier of the plugin that calls this function
676 * @param iface The interface pointer
677 * @param thisptr_offs This pointer adjuster
678 * @param myHookMan A hook manager function that should be capable of handling the function
679 * @param handler A pointer to a FastDelegate containing the hook handler
680 * @param post Set to true if you want a post handler
682 bool RemoveHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan, ISHDelegate *handler, bool post);
685 * @brief Removes a hook.
687 * @ return True if the function succeeded, false otherwise
689 * @param info A RemoveHookInfo structure, describing the hook
691 bool RemoveHook(RemoveHookInfo info);
694 * @brief Checks whether a plugin has (a) hook manager(s) that is/are currently used by other plugins
696 * @param plug The unique identifier of the plugin in question
698 bool IsPluginInUse(Plugin plug);
701 * @brief Pauses all hooks of a plugin
703 * @param plug The unique identifier of the plugin
705 void PausePlugin(Plugin plug);
708 * @brief Unpauses all hooks of a plugin
710 * @param plug The unique identifier of the plugin
712 void UnpausePlugin(Plugin plug);
715 * @brief Return a pointer to a callclass. Generate a new one if required.
717 * @param iface The interface pointer
718 * @param size Size of the class instance
720 DeprecatedCallClass<void> *GetCallClass(void *iface, size_t size);
723 * @brief Release a callclass
725 * @param ptr Pointer to the callclass
727 virtual void ReleaseCallClass(DeprecatedCallClass<void> *ptr);
729 virtual void SetRes(META_RES res); //!< Sets the meta result
730 virtual META_RES GetPrevRes(); //!< Gets the meta result of the previously called handler
731 virtual META_RES GetStatus(); //!< Gets the highest meta result
732 virtual const void *GetOrigRet(); //!< Gets the original result. If not in post function, undefined
733 virtual const void *GetOverrideRet(); //!< Gets the override result. If none is specified, NULL
734 virtual void *GetIfacePtr(); //!< Gets the interface pointer
736 //////////////////////////////////////////////////////////////////////////
738 void HookLoopBegin(IIface *pIface); //!< Should be called when a hook loop begins
739 void HookLoopEnd(); //!< Should be called when a hook loop exits
740 void SetCurResPtr(META_RES *mres); //!< Sets pointer to the current meta result
741 void SetPrevResPtr(META_RES *mres); //!< Sets pointer to previous meta result
742 void SetStatusPtr(META_RES *mres); //!< Sets pointer to the status variable
743 void SetIfacePtrPtr(void **pp); //!< Sets pointer to the interface this pointer
744 void SetOrigRetPtr(const void *ptr); //!< Sets the original return pointer
745 void SetOverrideRetPtr(void *ptr); //!< Sets the override result pointer
746 bool ShouldContinue(); //!< Returns false if the hook loop should exit
749 * @brief Remove a hook manager. Auto-removes all hooks attached to it from plugin plug.
751 * @param plug The owner of the hook manager
752 * @param pubFunc The hook manager's info function
754 virtual void RemoveHookManager(Plugin plug, HookManagerPubFunc pubFunc);
755 virtual void RemoveHookManager(RemoveHookManInfo info);
757 virtual void DoRecall(); //!< Initiates a recall sequence
758 virtual void *GetOverrideRetPtr(); //!< Returns the pointer set by SetOverrideRetPtr
760 virtual void *SetupHookLoop(META_RES *statusPtr, META_RES *prevResPtr, META_RES *curResPtr,
761 void **ifacePtrPtr, const void *origRetPtr, void *overrideRetPtr);
764 * @brief Add a (VP) hook.
766 * @return non-zero hook id on success, 0 otherwise
768 * @param plug The unique identifier of the plugin that calls this function
769 * @param mode Can be either Hook_Normal or Hook_VP (vtable-wide hook)
770 * @param iface The interface pointer
771 * The representative interface pointer for VP hooks
772 * The vtable pointer for direct VP hooks !!!
773 * @param ifacesize The size of the class iface points to
774 * @param myHookMan A hook manager function that should be capable of handling the function
775 * @param handler A pointer to a FastDelegate containing the hook handler
776 * @param post Set to true if you want a post handler
778 virtual int AddHookNew(Plugin plug, AddHookMode mode, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan,
779 ISHDelegate *handler, bool post);
782 * @brief Remove a VP hook by ID.
784 * @return true on success, false otherwise
786 * @param plug The unique identifier of the plugin that calls this function
787 * @param hookid The hook id (returned by AddHookNew)
789 virtual bool RemoveHookByID(Plugin plug, int hookid);
792 * @brief Makes sure that hooks are going to be ignored on the next call of vfnptr
794 * @param plug The unique identifier of the plugin that calls this function
795 * @param vfnptr The virtual function pointer of the function in question
797 virtual void SetIgnoreHooks(Plugin plug, void *vfnptr);
800 * @brief Reverses SetIgnoreHooks' effect
802 * @param plug The unique identifier of the plugin that calls this function
803 * @param vfnptr The virtual function pointer of the function in question
805 virtual void ResetIgnoreHooks(Plugin plug, void *vfnptr);
808 * @brief Finds the original entry of a virtual function pointer
810 * @param vfnptr The virtual function pointer
811 * @return The original entry if the virtual function pointer has been patched; NULL otherwise.
813 virtual void *GetOrigVfnPtrEntry(void *vfnptr);