Bumped all versions.
1 /* ======== SourceHook ========
2 * Copyright (C) 2004-2008 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);
261 void Set(CIter *pOther);
265 ISHDelegate *Handler();
270 CIter *m_pNext; // When stored in m_FreeIters and m_UsedIters
271 CIter *m_pPrev; // Only used when stored in m_UsedIters
275 CIter *m_UsedIters; // The last returned and not-yet-released iter is always m_UsedIters
282 void SetRecallState(); // Sets the list into a state where the next returned
283 // iterator (from GetIter) will be a copy of the last
284 // returned iterator, incremented by one. This is used in Recalls.
285 // The hook resets this state automatically on:
286 // GetIter, ReleaseIter
288 void RQFlagReset() { m_RQFlag = false; m_RelFlag = false; }
289 bool RQFlagGet() { return m_RQFlag; }
290 bool RelFlagGet() { return m_RelFlag; }
292 CHookList(const CHookList &other);
293 virtual ~CHookList();
295 void operator=(const CHookList &other);
298 void ReleaseIter(IIter *pIter);
301 // I know, data hiding... But I'm a lazy bastard!
303 class CIface : public IIface
307 CHookList m_PreHooks;
308 CHookList m_PostHooks;
314 IHookList *GetPreHooks();
315 IHookList *GetPostHooks();
317 bool operator==(void *ptr)
323 class CVfnPtr : public IVfnPtr
326 typedef List<CIface> IfaceList;
327 typedef IfaceList::iterator IfaceListIter;
339 void *GetOrigEntry();
341 virtual IIface *FindIface(void *ptr);
343 bool operator==(void *ptr)
349 class CHookManagerInfo : public IHookManagerInfo
352 typedef List<CVfnPtr> VfnPtrList;
353 typedef VfnPtrList::iterator VfnPtrListIter;
356 HookManagerPubFunc m_Func;
361 void *m_HookfuncVfnptr;
363 VfnPtrList m_VfnPtrs;
365 int m_HookManVersion;
368 virtual ~CHookManagerInfo();
370 IVfnPtr *FindVfnPtr(void *vfnptr);
372 void SetInfo(int vtbl_offs, int vtbl_idx, const char *proto);
373 void SetHookfuncVfnptr(void *hookfunc_vfnptr);
375 void SetVersion(int version);
377 bool operator < (const CHookManagerInfo &other)
379 return m_HookManVersion < other.m_HookManVersion;
384 Descriptor(Plugin pplug, HookManagerPubFunc ppubFunc) : plug(pplug), pubFunc(ppubFunc)
389 HookManagerPubFunc pubFunc;
392 bool operator == (const Descriptor desc)
394 return m_Func == desc.pubFunc && m_Plug == desc.plug;
398 typedef List<CHookManagerInfo> HookManInfoList;
400 class CHookManagerContainer : public HookManInfoList
403 // HMCI (Hook Manager Container Identification)
410 HMCI(const char *proto, int vtbloffs, int vtblidx) :
411 m_Proto(proto), m_VtableOffset(vtbloffs), m_VtableIndex(vtblidx)
418 bool operator==(const HMCI &other) const
421 other.m_VtableIndex == m_VtableIndex &&
422 other.m_Proto == m_Proto &&
423 other.m_VtableOffset == m_VtableOffset;
426 const CProto &GetProto() const
430 int GetVtableOffset() const
432 return m_VtableOffset;
434 int GetVtableIndex() const
436 return m_VtableIndex;
442 CHookManagerContainer(const HMCI &hmci) : m_HCMI(hmci)
445 bool operator == (const HMCI &other) const
447 return m_HCMI == other;
449 void AddHookManager(Plugin plug, const CHookManagerInfo &hookman);
452 class CCallClassImpl : public GenericCallClass
456 typedef SourceHook::CVector<void*> OrigFuncs;
457 typedef SourceHook::THash<int, OrigFuncs> OrigVTables;
459 void *m_Ptr; //!< Pointer to the actual object
460 size_t m_ObjSize; //!< Size of the instance
461 OrigVTables m_VT; //!< Info about vtables & functions
465 CCallClassImpl(void *ptr, size_t size);
466 virtual ~CCallClassImpl();
468 bool operator==(void *other)
470 return m_Ptr == other;
474 void *GetOrigFunc(int vtbloffs, int vtblidx);
476 void ApplyCallClassPatch(int vtbl_offs, int vtbl_idx, void *orig_entry);
477 void RemoveCallClassPatch(int vtbl_offs, int vtbl_idx);
481 * @brief A list of CallClass structures
483 typedef List<CCallClassImpl> Impl_CallClassList;
485 Impl_CallClassList m_CallClasses; //!< A list of already generated callclasses
488 * @brief A list of CHookManagerContainers
490 typedef List<CHookManagerContainer> HookManContList;
492 HookManContList m_HookMans; //!< A list of hook managers
508 META_RES temporaryStatus; //!< Stored during Post1 recall phase
510 RecallType recall; //!< Specifies which kind of recall we're in.
513 const void *pOrigRet;
517 typedef CStack<HookLoopInfo> HookLoopInfoStack;
519 void ApplyCallClassPatches(CCallClassImpl &cc);
520 void ApplyCallClassPatches(void *ifaceptr, int vtbl_offs, int vtbl_idx, void *orig_entry);
521 void RemoveCallClassPatches(void *ifaceptr, int vtbl_offs, int vtbl_idx);
523 void SetPluginPaused(Plugin plug, bool paused);
525 HookLoopInfoStack m_HLIStack;
528 virtual ~CSourceHookImpl();
531 * @brief Returns the interface version
533 int GetIfaceVersion();
536 * @brief Returns the implemnetation version
538 int GetImplVersion();
541 * @brief Make sure that a plugin is not used by any other plugins anymore, and unregister all its hook managers
543 void UnloadPlugin(Plugin plug);
546 * @brief Shut down the whole system, unregister all hook managers
548 void CompleteShutdown();
553 * @return True if the function succeeded, false otherwise
555 * @param plug The unique identifier of the plugin that calls this function
556 * @param iface The interface pointer
557 * @param ifacesize The size of the class iface points to
558 * @param myHookMan A hook manager function that should be capable of handling the function
559 * @param handler A pointer to a FastDelegate containing the hook handler
560 * @param post Set to true if you want a post handler
562 bool AddHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan, ISHDelegate *handler, bool post);
565 * @brief Removes a hook.
567 * @return True if the function succeeded, false otherwise
569 * @param plug The unique identifier of the plugin that calls this function
570 * @param iface The interface pointer
571 * @param thisptr_offs This pointer adjuster
572 * @param myHookMan A hook manager function that should be capable of handling the function
573 * @param handler A pointer to a FastDelegate containing the hook handler
574 * @param post Set to true if you want a post handler
576 bool RemoveHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan, ISHDelegate *handler, bool post);
579 * @brief Removes a hook.
581 * @ return True if the function succeeded, false otherwise
583 * @param info A RemoveHookInfo structure, describing the hook
585 bool RemoveHook(RemoveHookInfo info);
588 * @brief Checks whether a plugin has (a) hook manager(s) that is/are currently used by other plugins
590 * @param plug The unique identifier of the plugin in question
592 bool IsPluginInUse(Plugin plug);
595 * @brief Pauses all hooks of a plugin
597 * @param plug The unique identifier of the plugin
599 void PausePlugin(Plugin plug);
602 * @brief Unpauses all hooks of a plugin
604 * @param plug The unique identifier of the plugin
606 void UnpausePlugin(Plugin plug);
609 * @brief Return a pointer to a callclass. Generate a new one if required.
611 * @param iface The interface pointer
612 * @param size Size of the class instance
614 GenericCallClass *GetCallClass(void *iface, size_t size);
617 * @brief Release a callclass
619 * @param ptr Pointer to the callclass
621 virtual void ReleaseCallClass(GenericCallClass *ptr);
623 virtual void SetRes(META_RES res); //!< Sets the meta result
624 virtual META_RES GetPrevRes(); //!< Gets the meta result of the previously called handler
625 virtual META_RES GetStatus(); //!< Gets the highest meta result
626 virtual const void *GetOrigRet(); //!< Gets the original result. If not in post function, undefined
627 virtual const void *GetOverrideRet(); //!< Gets the override result. If none is specified, NULL
628 virtual void *GetIfacePtr(); //!< Gets the interface pointer
630 //////////////////////////////////////////////////////////////////////////
632 void HookLoopBegin(IIface *pIface); //!< Should be called when a hook loop begins
633 void HookLoopEnd(); //!< Should be called when a hook loop exits
634 void SetCurResPtr(META_RES *mres); //!< Sets pointer to the current meta result
635 void SetPrevResPtr(META_RES *mres); //!< Sets pointer to previous meta result
636 void SetStatusPtr(META_RES *mres); //!< Sets pointer to the status variable
637 void SetIfacePtrPtr(void **pp); //!< Sets pointer to the interface this pointer
638 void SetOrigRetPtr(const void *ptr); //!< Sets the original return pointer
639 void SetOverrideRetPtr(void *ptr); //!< Sets the override result pointer
640 bool ShouldContinue(); //!< Returns false if the hook loop should exit
643 * @brief Remove a hook manager. Auto-removes all hooks attached to it from plugin plug.
645 * @param plug The owner of the hook manager
646 * @param pubFunc The hook manager's info function
648 virtual void RemoveHookManager(Plugin plug, HookManagerPubFunc pubFunc);
649 virtual void RemoveHookManager(RemoveHookManInfo info);
651 virtual void DoRecall(); //!< Initiates a recall sequence
652 virtual void *GetOverrideRetPtr(); //!< Returns the pointer set by SetOverrideRetPtr
654 virtual void *SetupHookLoop(META_RES *statusPtr, META_RES *prevResPtr, META_RES *curResPtr,
655 void **ifacePtrPtr, const void *origRetPtr, void *overrideRetPtr);