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"
24 ---------------------------------------
26 The purpose of protos is to provide the amount of type information about a function
27 which is required to be able to execute a function call without corrupting the stack.
28 Our protos do not fully do this, but they provide the size of the return value, the number of
29 parameters, and the size of each parameter, which is enough for most situations.
31 There are two version of protos:
40 "attrib|param1_type|param2_type
44 "attrib|ret_type|param1_type"
46 "attrib|ret_type|param2_type"
48 Old protos are deprecated.
51 New protos are in fact pointers to the ProtoInfo structure (see sourcehook.h)
53 Old protos begin with a non-zero byte, new protos begin with a zero byte.
55 Protos are usually stored in a CProto instance.
57 ---------------------------------------
58 Hook managers and hook manager containers
59 Each hookman container is tied to _one_ proto/vtable index/vtable offset info.
60 Hookman containers then contain a list of hook managers provided by plugins, sorted by version.
61 (higher versions come first)
63 Duplicate hook managers are ignored (ie. hook managers where proto, vtable index, vtable offset,
64 plugin, version are the same as in an already exisiting hook manager)
66 A new hook manager is always added to the end of the version group in the corresponding
69 If the new hook manager was added to the beginning of the container (which only happens if
70 it is the first one or if it has a higher version than the previously first hook manager),
71 the now second hook manager is shut down and the new hook manager takes its job.
73 A "hook manager container id" (HMCI) consits of three values: proto, vtbl index, vtbl offset.
74 ---------------------------------------
76 When adding a hook, first the proposed hook manager is added to the corresponding
77 hook manager container as described above.
79 Then the first hook manager in the the manhook container is chosen to handle the function.
81 Removing a hook does not neccessarily unreigster the plugin's hook manager. In order to do this,
82 use RemoveHookManager or UnloadPlugin/
84 Hooks can be paused - they remain in memory but they are not called. In SH, the hook iterator
85 classes handle pausing transparently.
87 The hook loop is supposed to call ShouldContinue before each iteration. This makes hook handlers
88 able to remove themselves.
90 ---------------------------------------
92 Call classes are identified by a this pointer and an instance size
94 We use the instance size because a derived class instance and a base class instance could
95 have the same this pointers, and we want to avoid that the derived class
96 (which could be bigger) gets the same callclass as the base class (mainly if the
97 base class' callclass was requested first).
99 Call classes are reference counted.
101 The original function pointers are stored in a vector (in order to allow fast random access).
102 These vectors are stored as the value type of a hash. The key type is int and represents the
105 If the hash key doesn't exist or the vtblidx is out of range or the corresponding element in the
106 vector is NULL, there is no hook on that function.
108 ---------------------------------------
110 Recalls are used for the META_RETURN_(VALUE_)NEWPARAMS macros, ie. to change the parameters
111 in the hook loop on the fly.
113 First, the macro calls DoRecall(), then it calls the function the hook is attached to -> it
114 calls the hookfunc. SourceHook makes sure that the newly invoked hook loop starts where the last
115 one left off and that status variables like status, previous result, override return are kept.
116 When this recurisvely called hookfunc returns, the macro returns what it returned
117 (using MRES_SUPERCEDE). CSourceHookImpl returns false from ShouldContinue so the original hook loop
121 People wanted to be able to use META_RETURN_(VALUE_)NEWPARAMS from post hooks as well. Crazy people!
122 Anyway, for this, we have to know where a hook handler is. Is it executing pre or post hooks at the moment?
123 The only way we can know this is watching when it calls CHookList::GetIter(). So CHookList gets a new variable:
124 m_RequestedFlag. It also gets two new functions: RQFlagReset() and RQFlagGet().
125 HookLoopBegin() calls RQFlagReset on both hooklists of the iface; then DoRecall() checks whether the postlist's
126 RQ flag is set. if yes, the hook loop is in post mode.
128 So, what a about a recall in post mode? The first ShouldContinue returns false and sets Status to supercede.
129 This way the pre hooks and the function call will be skipped. Then, then next ShouldContinue returns true, so we get
130 into the post hooks. HA!
132 Return Values in Post Recalls
133 The easy case is when we already have an override return value. In this case, the status register gets transferred,
134 and so does the override return pointer. So, basically, everything is ok.
136 However, what happens if we don't? ie. the status register is on MRES_IGNORED? In this case we'd have to transfer the
137 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.
138 So, we emulate it. GetOrigRet will return the orig ret pointer from the old hook loop. If still no one overrides it,
139 we'd have to return it. BUT! HOW TO DO THIS? Check out SH_RETURN(). First calls HookLoopEnd(), then decides whether
140 to return the override retval or the orig retval. But it doesn't ask for a new override return. So we give the function
141 the last orig return value as its new override return value; but leave status where it is so everything works, and in
142 HookLoopEnd we make sure that status is high enough so that the override return will be returned. crazy.
144 All this stuff could be much less complicated if I didn't try to preserve binary compatibility :)
150 * @brief The SourceHook implementation class
152 class CSourceHookImpl : public ISourceHook
159 static bool Equal(const char *p1, const char *p2);
160 char *DupProto(const char *src);
161 void FreeProto(char *prot);
163 CProto(const char *szProto) : m_Proto(DupProto(szProto))
167 CProto(const CProto &other) : m_Proto(DupProto(other.m_Proto))
177 void operator = (const char *szProto)
179 m_Proto = DupProto(szProto);
182 void operator = (const CProto &other)
184 m_Proto = DupProto(other.m_Proto);
187 bool operator == (const char *szProto) const
189 return Equal(szProto, m_Proto);
191 bool operator == (const CProto &other) const
193 return Equal(other.m_Proto, m_Proto);
199 * @brief A hook can be removed if you have this information
201 struct RemoveHookInfo
203 RemoveHookInfo(Plugin pplug, void *piface, int tpo, HookManagerPubFunc phookman,
204 ISHDelegate *phandler, bool ppost)
205 : plug(pplug), iface(piface), thisptr_offs(tpo),
206 hookman(phookman), handler(phandler), post(ppost)
213 HookManagerPubFunc hookman;
214 ISHDelegate *handler;
218 struct RemoveHookManInfo
220 RemoveHookManInfo(Plugin pplug, HookManagerPubFunc phookman)
221 : plug(pplug), hookman(phookman)
226 HookManagerPubFunc hookman;
231 ISHDelegate *handler; //!< Pointer to the handler
232 bool paused; //!< If true, the hook should not be executed
233 Plugin plug; //!< The owner plugin
234 int thisptr_offs; //!< This pointer offset
237 class CHookList : public IHookList
240 List<HookInfo> m_List;
244 class CIter : public IHookList::IIter
246 friend class CHookList;
253 List<HookInfo>::iterator m_Iter;
255 CIter(CHookList *pList);
260 void Set(CIter *pOther);
264 ISHDelegate *Handler();
269 CIter *m_pNext; // When stored in m_FreeIters and m_UsedIters
270 CIter *m_pPrev; // Only used when stored in m_UsedIters
274 CIter *m_UsedIters; // The last returned and not-yet-released iter is always m_UsedIters
280 void SetRecallState(); // Sets the list into a state where the next returned
281 // iterator (from GetIter) will be a copy of the last
282 // returned iterator, incremented by one. This is used in Recalls.
283 // The hook resets this state automatically on:
284 // GetIter, ReleaseIter
286 void RQFlagReset() { m_RQFlag = false; }
287 bool RQFlagGet() { return m_RQFlag; }
289 CHookList(const CHookList &other);
290 virtual ~CHookList();
292 void operator=(const CHookList &other);
295 void ReleaseIter(IIter *pIter);
298 // I know, data hiding... But I'm a lazy bastard!
300 class CIface : public IIface
304 CHookList m_PreHooks;
305 CHookList m_PostHooks;
311 IHookList *GetPreHooks();
312 IHookList *GetPostHooks();
314 bool operator==(void *ptr)
320 class CVfnPtr : public IVfnPtr
323 typedef List<CIface> IfaceList;
324 typedef IfaceList::iterator IfaceListIter;
336 void *GetOrigEntry();
338 virtual IIface *FindIface(void *ptr);
340 bool operator==(void *ptr)
346 class CHookManagerInfo : public IHookManagerInfo
349 typedef List<CVfnPtr> VfnPtrList;
350 typedef VfnPtrList::iterator VfnPtrListIter;
353 HookManagerPubFunc m_Func;
358 void *m_HookfuncVfnptr;
360 VfnPtrList m_VfnPtrs;
362 int m_HookManVersion;
365 virtual ~CHookManagerInfo();
367 IVfnPtr *FindVfnPtr(void *vfnptr);
369 void SetInfo(int vtbl_offs, int vtbl_idx, const char *proto);
370 void SetHookfuncVfnptr(void *hookfunc_vfnptr);
372 void SetVersion(int version);
374 bool operator < (const CHookManagerInfo &other)
376 return m_HookManVersion < other.m_HookManVersion;
381 Descriptor(Plugin pplug, HookManagerPubFunc ppubFunc) : plug(pplug), pubFunc(ppubFunc)
386 HookManagerPubFunc pubFunc;
389 bool operator == (const Descriptor desc)
391 return m_Func == desc.pubFunc && m_Plug == desc.plug;
395 typedef List<CHookManagerInfo> HookManInfoList;
397 class CHookManagerContainer : public HookManInfoList
400 // HMCI (Hook Manager Container Identification)
407 HMCI(const char *proto, int vtbloffs, int vtblidx) :
408 m_Proto(proto), m_VtableOffset(vtbloffs), m_VtableIndex(vtblidx)
415 bool operator==(const HMCI &other) const
418 other.m_VtableIndex == m_VtableIndex &&
419 other.m_Proto == m_Proto &&
420 other.m_VtableOffset == m_VtableOffset;
423 const CProto &GetProto() const
427 int GetVtableOffset() const
429 return m_VtableOffset;
431 int GetVtableIndex() const
433 return m_VtableIndex;
439 CHookManagerContainer(const HMCI &hmci) : m_HCMI(hmci)
442 bool operator == (const HMCI &other) const
444 return m_HCMI == other;
446 void AddHookManager(Plugin plug, const CHookManagerInfo &hookman);
449 class CCallClassImpl : public GenericCallClass
453 typedef SourceHook::CVector<void*> OrigFuncs;
454 typedef SourceHook::THash<int, OrigFuncs> OrigVTables;
456 void *m_Ptr; //!< Pointer to the actual object
457 size_t m_ObjSize; //!< Size of the instance
458 OrigVTables m_VT; //!< Info about vtables & functions
462 CCallClassImpl(void *ptr, size_t size);
463 virtual ~CCallClassImpl();
465 bool operator==(void *other)
467 return m_Ptr == other;
471 void *GetOrigFunc(int vtbloffs, int vtblidx);
473 void ApplyCallClassPatch(int vtbl_offs, int vtbl_idx, void *orig_entry);
474 void RemoveCallClassPatch(int vtbl_offs, int vtbl_idx);
478 * @brief A list of CallClass structures
480 typedef List<CCallClassImpl> Impl_CallClassList;
482 Impl_CallClassList m_CallClasses; //!< A list of already generated callclasses
485 * @brief A list of CHookManagerContainers
487 typedef List<CHookManagerContainer> HookManContList;
489 HookManContList m_HookMans; //!< A list of hook managers
505 META_RES temporaryStatus; //!< Stored during Post1 recall phase
507 RecallType recall; //!< Specifies which kind of recall we're in.
510 const void *pOrigRet;
514 typedef CStack<HookLoopInfo> HookLoopInfoStack;
516 void ApplyCallClassPatches(CCallClassImpl &cc);
517 void ApplyCallClassPatches(void *ifaceptr, int vtbl_offs, int vtbl_idx, void *orig_entry);
518 void RemoveCallClassPatches(void *ifaceptr, int vtbl_offs, int vtbl_idx);
520 void SetPluginPaused(Plugin plug, bool paused);
522 HookLoopInfoStack m_HLIStack;
525 virtual ~CSourceHookImpl();
528 * @brief Returns the interface version
530 int GetIfaceVersion();
533 * @brief Returns the implemnetation version
535 int GetImplVersion();
538 * @brief Make sure that a plugin is not used by any other plugins anymore, and unregister all its hook managers
540 void UnloadPlugin(Plugin plug);
543 * @brief Shut down the whole system, unregister all hook managers
545 void CompleteShutdown();
550 * @return True if the function succeeded, false otherwise
552 * @param plug The unique identifier of the plugin that calls this function
553 * @param iface The interface pointer
554 * @param ifacesize The size of the class iface points to
555 * @param myHookMan A hook manager function that should be capable of handling the function
556 * @param handler A pointer to a FastDelegate containing the hook handler
557 * @param post Set to true if you want a post handler
559 bool AddHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan, ISHDelegate *handler, bool post);
562 * @brief Removes a hook.
564 * @return True if the function succeeded, false otherwise
566 * @param plug The unique identifier of the plugin that calls this function
567 * @param iface The interface pointer
568 * @param thisptr_offs This pointer adjuster
569 * @param myHookMan A hook manager function that should be capable of handling the function
570 * @param handler A pointer to a FastDelegate containing the hook handler
571 * @param post Set to true if you want a post handler
573 bool RemoveHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan, ISHDelegate *handler, bool post);
576 * @brief Removes a hook.
578 * @ return True if the function succeeded, false otherwise
580 * @param info A RemoveHookInfo structure, describing the hook
582 bool RemoveHook(RemoveHookInfo info);
585 * @brief Checks whether a plugin has (a) hook manager(s) that is/are currently used by other plugins
587 * @param plug The unique identifier of the plugin in question
589 bool IsPluginInUse(Plugin plug);
592 * @brief Pauses all hooks of a plugin
594 * @param plug The unique identifier of the plugin
596 void PausePlugin(Plugin plug);
599 * @brief Unpauses all hooks of a plugin
601 * @param plug The unique identifier of the plugin
603 void UnpausePlugin(Plugin plug);
606 * @brief Return a pointer to a callclass. Generate a new one if required.
608 * @param iface The interface pointer
609 * @param size Size of the class instance
611 GenericCallClass *GetCallClass(void *iface, size_t size);
614 * @brief Release a callclass
616 * @param ptr Pointer to the callclass
618 virtual void ReleaseCallClass(GenericCallClass *ptr);
620 virtual void SetRes(META_RES res); //!< Sets the meta result
621 virtual META_RES GetPrevRes(); //!< Gets the meta result of the previously called handler
622 virtual META_RES GetStatus(); //!< Gets the highest meta result
623 virtual const void *GetOrigRet(); //!< Gets the original result. If not in post function, undefined
624 virtual const void *GetOverrideRet(); //!< Gets the override result. If none is specified, NULL
625 virtual void *GetIfacePtr(); //!< Gets the interface pointer
627 //////////////////////////////////////////////////////////////////////////
629 void HookLoopBegin(IIface *pIface); //!< Should be called when a hook loop begins
630 void HookLoopEnd(); //!< Should be called when a hook loop exits
631 void SetCurResPtr(META_RES *mres); //!< Sets pointer to the current meta result
632 void SetPrevResPtr(META_RES *mres); //!< Sets pointer to previous meta result
633 void SetStatusPtr(META_RES *mres); //!< Sets pointer to the status variable
634 void SetIfacePtrPtr(void **pp); //!< Sets pointer to the interface this pointer
635 void SetOrigRetPtr(const void *ptr); //!< Sets the original return pointer
636 void SetOverrideRetPtr(void *ptr); //!< Sets the override result pointer
637 bool ShouldContinue(); //!< Returns false if the hook loop should exit
640 * @brief Remove a hook manager. Auto-removes all hooks attached to it from plugin plug.
642 * @param plug The owner of the hook manager
643 * @param pubFunc The hook manager's info function
645 virtual void RemoveHookManager(Plugin plug, HookManagerPubFunc pubFunc);
646 virtual void RemoveHookManager(RemoveHookManInfo info);
648 virtual void DoRecall(); //!< Initiates a recall sequence
649 virtual void *GetOverrideRetPtr(); //!< Returns the pointer set by SetOverrideRetPtr
651 virtual void *SetupHookLoop(META_RES *statusPtr, META_RES *prevResPtr, META_RES *curResPtr,
652 void **ifacePtrPtr, const void *origRetPtr, void *overrideRetPtr);