sourcehook/sourcehook_impl.h
author Pavol Marko <pavolmarko@gmail.com>
Fri Dec 23 23:32:21 2005 +0000 (2005-12-23)
changeset 165 76da01197c4c
parent 163 377bdd31c28d
child 179 3ade923f508b
permissions -rw-r--r--
Uh.
     1 /* ======== SourceHook ========
     2 * Copyright (C) 2004-2005 Metamod:Source Development Team
     3 * No warranties of any kind
     4 *
     5 * License: zlib/libpng
     6 *
     7 * Author(s): Pavol "PM OnoTo" Marko
     8 * ============================
     9 */
    10 
    11 #ifndef __SOURCEHOOK_IMPL_H__
    12 #define __SOURCEHOOK_IMPL_H__
    13 
    14 #include "sourcehook.h"
    15 #include "sh_list.h"
    16 #include "sh_vector.h"
    17 #include "sh_tinyhash.h"
    18 #include "sh_stack.h"
    19 
    20 /*
    21 
    22 IMPLEMENTATION INFO
    23 
    24 ---------------------------------------
    25 Protos ("Prototypes")
    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 amount of
    29 	parameters, and the size of each parameter, which is enough for most situations,
    30 
    31 	There are two version of protos:
    32 	OLD:
    33 		C-Style strings.
    34 
    35 		0_void:
    36 		"attrib"
    37 		1_void:
    38 		"attrib|param1_type"
    39 		2_void:
    40 		"attrib|param1_type|param2_type
    41 		0:
    42 		"attrib|ret_type"
    43 		1:
    44 		"attrib|ret_type|param1_type"
    45 		2:
    46 		"attrib|ret_type|param2_type"
    47 
    48 		Old protos are deprecated.
    49 
    50 	NEW:
    51 		New protos are in fact pointers to the ProtoInfo structure (see sourcehook.h)
    52 
    53 	Old protos begin with a non-zero byte, new protos begin with a zero byte.
    54 
    55 	Protos are usually stored in a CProto instance.
    56 
    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)
    62 
    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)
    65 
    66 	A new hook manager is always added to the end of the version group in the corresponding
    67 	hook container. 
    68 
    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.
    72 
    73 	A "hook manager container id" (HMCI) consits of three values: proto, vtbl index, vtbl offset.
    74 ---------------------------------------
    75 Hooks 
    76 	When adding a hook, first the proposed hook manager is added to the corresponding
    77 	hook manager container as described above.
    78 
    79 	Then the first hook manager in the the manhook container is chosen to handle the function.
    80 
    81 	Removing a hook does not neccessarily unreigster the plugin's hook manager. In order to do this,
    82 	use RemoveHookManager or UnloadPlugin/
    83 
    84 	Hooks can be paused - they remain in memory but they are not called. In SH, the hook iterator
    85 	classes handle pausing transparently.
    86 
    87 	The hook loop is supposed to call ShouldContinue before each iteration. This makes hook handlers
    88 	able to remove themselves.
    89 
    90 ---------------------------------------
    91 Call classes
    92 	Call classes are identified by a this pointer and an instance size
    93 
    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).
    98 
    99 	Call classes are reference counted.
   100 
   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
   103 	vtable offset.
   104 
   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.
   107 
   108 ---------------------------------------
   109 Recalls
   110 	Recalls are used for the META_RETURN_(VALUE_)NEWPARAMS macros, ie. to change the parameters
   111 	in the hook loop on the fly.
   112 	
   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
   118 	is abandonned.
   119 */
   120 
   121 namespace SourceHook
   122 {
   123 	/**
   124 	*	@brief The SourceHook implementation class
   125 	*/
   126 	class CSourceHookImpl : public ISourceHook
   127 	{
   128 	private:
   129 		class CProto
   130 		{
   131 			const char *m_Proto;
   132 
   133 			static bool Equal(const char *p1, const char *p2);
   134 		public:
   135 			CProto(const char *szProto) : m_Proto(szProto)
   136 			{
   137 			}
   138 
   139 			CProto(const CProto &other) : m_Proto(other.m_Proto)
   140 			{
   141 			}
   142 
   143 			void operator = (const char *szProto)
   144 			{
   145 				m_Proto = szProto;
   146 			}
   147 			void operator = (const CProto &other)
   148 			{
   149 				m_Proto = other.m_Proto;
   150 			}
   151 
   152 			bool operator == (const char *szProto) const
   153 			{
   154 				return Equal(szProto, m_Proto);
   155 			}
   156 			bool operator == (const CProto &other) const
   157 			{
   158 				return Equal(other.m_Proto, m_Proto);
   159 			}
   160 		};
   161 
   162 
   163 		/**
   164 		*	@brief A hook can be removed if you have this information
   165 		*/
   166 		struct RemoveHookInfo
   167 		{
   168 			RemoveHookInfo(Plugin pplug, void *piface, int tpo, HookManagerPubFunc phookman,
   169 				ISHDelegate *phandler, bool ppost)
   170 				: plug(pplug), iface(piface), thisptr_offs(tpo),
   171 				hookman(phookman), handler(phandler), post(ppost)
   172 			{
   173 			}
   174 
   175 			Plugin plug;
   176 			void *iface;
   177 			int thisptr_offs;
   178 			HookManagerPubFunc hookman;
   179 			ISHDelegate *handler;
   180 			bool post;
   181 		};
   182 
   183 		struct RemoveHookManInfo
   184 		{
   185 			RemoveHookManInfo(Plugin pplug, HookManagerPubFunc phookman)
   186 				: plug(pplug), hookman(phookman)
   187 			{
   188 			}
   189 
   190 			Plugin plug;
   191 			HookManagerPubFunc hookman;
   192 		};
   193 
   194 		struct HookInfo
   195 		{
   196 			ISHDelegate *handler;			//!< Pointer to the handler
   197 			bool paused;					//!< If true, the hook should not be executed
   198 			Plugin plug;					//!< The owner plugin
   199 			int thisptr_offs;				//!< This pointer offset
   200 		};
   201 
   202 		class CHookList : public IHookList
   203 		{
   204 		public:
   205 			List<HookInfo> m_List;
   206 
   207 			friend class CIter;
   208 
   209 			class CIter : public IHookList::IIter
   210 			{
   211 				friend class CHookList;
   212 
   213 				CHookList *m_pList;
   214 
   215 				void SkipPaused();
   216 			public:
   217 
   218 				List<HookInfo>::iterator m_Iter;
   219 
   220 				CIter(CHookList *pList);
   221 
   222 				virtual ~CIter();
   223 
   224 				void GoToBegin();
   225 				void Set(CIter *pOther);
   226 
   227 				bool End();
   228 				void Next();
   229 				ISHDelegate *Handler();
   230 				int ThisPtrOffs();
   231 
   232 				void Clear();
   233 
   234 				CIter *m_pNext;		// When stored in m_FreeIters and m_UsedIters
   235 				CIter *m_pPrev;		// Only used when stored in m_UsedIters
   236 			};
   237 
   238 			CIter *m_FreeIters;
   239 			CIter *m_UsedIters;		// The last returned and not-yet-released iter is always m_UsedIters
   240 
   241 			// For recalls
   242 			bool m_Recall;
   243 
   244 			void SetRecallState();	// Sets the list into a state where the next returned
   245 									// iterator (from GetIter) will be a copy of the last
   246 									// returned iterator, incremented by one. This is used in Recalls.
   247 									// The hook resets this state automatically on:
   248 									// GetIter, ReleaseIter
   249 
   250 			CHookList();
   251 			CHookList(const CHookList &other);
   252 			virtual ~CHookList();
   253 
   254 			void operator=(const CHookList &other);
   255 
   256 			IIter *GetIter();
   257 			void ReleaseIter(IIter *pIter);
   258 		};
   259 
   260 		// I know, data hiding... But I'm a lazy bastard!
   261 
   262 		class CIface : public IIface
   263 		{
   264 		public:
   265 			void *m_Ptr;
   266 			CHookList m_PreHooks;
   267 			CHookList m_PostHooks;
   268 		public:
   269 			CIface(void *ptr);
   270 			virtual ~CIface();
   271 
   272 			void *GetPtr();
   273 			IHookList *GetPreHooks();
   274 			IHookList *GetPostHooks();
   275 
   276 			bool operator==(void *ptr)
   277 			{
   278 				return m_Ptr == ptr;
   279 			}
   280 		};
   281 
   282 		class CVfnPtr : public IVfnPtr
   283 		{
   284 		public:
   285 			typedef List<CIface> IfaceList;
   286 			typedef IfaceList::iterator IfaceListIter;
   287 
   288 			void *m_Ptr;
   289 			void *m_OrigEntry;
   290 
   291 			IfaceList m_Ifaces;
   292 
   293 		public:
   294 			CVfnPtr(void *ptr);
   295 			virtual ~CVfnPtr();
   296 
   297 			void *GetVfnPtr();
   298 			void *GetOrigEntry();
   299 
   300 			virtual IIface *FindIface(void *ptr);
   301 
   302 			bool operator==(void *ptr)
   303 			{
   304 				return m_Ptr == ptr;
   305 			}
   306 		};
   307 
   308 		class CHookManagerInfo : public IHookManagerInfo
   309 		{
   310 		public:
   311 			typedef List<CVfnPtr> VfnPtrList;
   312 			typedef VfnPtrList::iterator VfnPtrListIter;
   313 
   314 			Plugin m_Plug;
   315 			HookManagerPubFunc m_Func;
   316 
   317 			int m_VtblOffs;
   318 			int m_VtblIdx;
   319 			const char *m_Proto;
   320 			void *m_HookfuncVfnptr;
   321 
   322 			VfnPtrList m_VfnPtrs;
   323 
   324 			int m_HookManVersion;
   325 		public:
   326 			CHookManagerInfo();
   327 			virtual ~CHookManagerInfo();
   328 
   329 			IVfnPtr *FindVfnPtr(void *vfnptr);
   330 
   331 			void SetInfo(int vtbl_offs, int vtbl_idx, const char *proto);
   332 			void SetHookfuncVfnptr(void *hookfunc_vfnptr);
   333 
   334 			void SetVersion(int version);
   335 
   336 			bool operator < (const CHookManagerInfo &other)
   337 			{
   338 				return m_HookManVersion < other.m_HookManVersion;
   339 			}
   340 
   341 			struct Descriptor
   342 			{
   343 				Descriptor(Plugin pplug, HookManagerPubFunc ppubFunc) : plug(pplug), pubFunc(ppubFunc)
   344 				{
   345 				}
   346 
   347 				Plugin plug;
   348 				HookManagerPubFunc pubFunc;
   349 			};
   350 
   351 			bool operator == (const Descriptor desc)
   352 			{
   353 				return m_Func == desc.pubFunc && m_Plug == desc.plug;
   354 			}
   355 		};
   356 
   357 		typedef List<CHookManagerInfo> HookManInfoList;
   358 
   359 		class CHookManagerContainer : public HookManInfoList
   360 		{
   361 		public:
   362 			// HMCI (Hook Manager Container Identification)
   363 			class HMCI
   364 			{
   365 				CProto m_Proto;
   366 				int m_VtableOffset;
   367 				int m_VtableIndex;
   368 			public:
   369 				HMCI(const char *proto, int vtbloffs, int vtblidx) :
   370 				  m_Proto(proto), m_VtableOffset(vtbloffs), m_VtableIndex(vtblidx)
   371 				  {
   372 				  }
   373 				  ~HMCI()
   374 				  {
   375 				  }
   376 
   377 				  bool operator==(const HMCI &other) const
   378 				  {
   379 					  return
   380 						  other.m_VtableIndex == m_VtableIndex &&
   381 						  other.m_Proto == m_Proto &&
   382 						  other.m_VtableOffset == m_VtableOffset;
   383 				  }
   384 
   385 				  const CProto &GetProto() const
   386 				  {
   387 					  return m_Proto;
   388 				  }
   389 				  int GetVtableOffset() const
   390 				  {
   391 					  return m_VtableOffset;
   392 				  }
   393 				  int GetVtableIndex() const
   394 				  {
   395 					  return m_VtableIndex;
   396 				  }
   397 			};
   398 			HMCI m_HCMI;
   399 
   400 		public:
   401 			CHookManagerContainer(const HMCI &hmci) : m_HCMI(hmci)
   402 			{
   403 			}
   404 			bool operator == (const HMCI &other) const
   405 			{
   406 				return m_HCMI == other;
   407 			}
   408 			void AddHookManager(Plugin plug, const CHookManagerInfo &hookman);
   409 		};
   410 
   411 		class CCallClassImpl : public GenericCallClass
   412 		{
   413 		public:
   414 
   415 			typedef SourceHook::CVector<void*> OrigFuncs;
   416 			typedef SourceHook::THash<int, OrigFuncs> OrigVTables;
   417 
   418 			void *m_Ptr;			//!< Pointer to the actual object
   419 			size_t m_ObjSize;		//!< Size of the instance
   420 			OrigVTables m_VT;		//!< Info about vtables & functions
   421 
   422 			int m_RefCounter;
   423 
   424 			CCallClassImpl(void *ptr, size_t size);
   425 			virtual ~CCallClassImpl();
   426 
   427 			bool operator==(void *other)
   428 			{
   429 				return m_Ptr == other;
   430 			}
   431 
   432 			void *GetThisPtr();
   433 			void *GetOrigFunc(int vtbloffs, int vtblidx);
   434 
   435 			void ApplyCallClassPatch(int vtbl_offs, int vtbl_idx, void *orig_entry);
   436 			void RemoveCallClassPatch(int vtbl_offs, int vtbl_idx);
   437 		};
   438 
   439 		/**
   440 		*	@brief A list of CallClass structures
   441 		*/
   442 		typedef List<CCallClassImpl> Impl_CallClassList;
   443 
   444 		Impl_CallClassList m_CallClasses;			//!< A list of already generated callclasses
   445 
   446 		/**
   447 		*	@brief A list of CHookManagerContainers
   448 		*/
   449 		typedef List<CHookManagerContainer> HookManContList;
   450 
   451 		HookManContList m_HookMans;					//!< A list of hook managers
   452 
   453 		struct HookLoopInfo
   454 		{
   455 			META_RES *pStatus;
   456 			META_RES *pPrevRes;
   457 			META_RES *pCurRes;
   458 
   459 			bool shouldContinue;
   460 			bool recall;							//!< True if we're in a recall, eh.
   461 
   462 			IIface *pCurIface;
   463 			const void *pOrigRet;
   464 			void *pOverrideRet;
   465 			void **pIfacePtrPtr;
   466 		};
   467 		typedef CStack<HookLoopInfo> HookLoopInfoStack;
   468 
   469 		void ApplyCallClassPatches(CCallClassImpl &cc);
   470 		void ApplyCallClassPatches(void *ifaceptr, int vtbl_offs, int vtbl_idx, void *orig_entry);
   471 		void RemoveCallClassPatches(void *ifaceptr, int vtbl_offs, int vtbl_idx);
   472 
   473 		void SetPluginPaused(Plugin plug, bool paused);
   474 
   475 		HookLoopInfoStack m_HLIStack;
   476 	public:
   477 		CSourceHookImpl();
   478 		virtual ~CSourceHookImpl();
   479 
   480 		/**
   481 		*	@brief Returns the interface version
   482 		*/
   483 		int GetIfaceVersion();
   484 
   485 		/**
   486 		*	@brief Returns the implemnetation version
   487 		*/
   488 		int GetImplVersion();
   489 
   490 		/**
   491 		*	@brief Make sure that a plugin is not used by any other plugins anymore, and unregister all its hook managers
   492 		*/
   493 		void UnloadPlugin(Plugin plug);
   494 
   495 		/**
   496 		*	@brief Shut down the whole system, unregister all hook managers
   497 		*/
   498 		void CompleteShutdown();
   499 
   500 		/**
   501 		*	@brief Add a hook.
   502 		*
   503 		*	@return True if the function succeeded, false otherwise
   504 		*
   505 		*	@param plug The unique identifier of the plugin that calls this function
   506 		*	@param iface The interface pointer
   507 		*	@param ifacesize The size of the class iface points to
   508 		*	@param myHookMan A hook manager function that should be capable of handling the function
   509 		*	@param handler A pointer to a FastDelegate containing the hook handler
   510 		*	@param post Set to true if you want a post handler
   511 		*/
   512 		bool AddHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan, ISHDelegate *handler, bool post);
   513 
   514 		/**
   515 		*	@brief Removes a hook.
   516 		*
   517 		*	@return True if the function succeeded, false otherwise
   518 		*
   519 		*	@param plug The unique identifier of the plugin that calls this function
   520 		*	@param iface The interface pointer
   521 		*	@param thisptr_offs This pointer adjuster
   522 		*	@param myHookMan A hook manager function that should be capable of handling the function
   523 		*	@param handler A pointer to a FastDelegate containing the hook handler
   524 		*	@param post Set to true if you want a post handler
   525 		*/
   526 		bool RemoveHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan, ISHDelegate *handler, bool post);
   527 
   528 		/**
   529 		*	@brief Removes a hook.
   530 		*
   531 		*	@ return True if the function succeeded, false otherwise
   532 		*
   533 		*	@param info A RemoveHookInfo structure, describing the hook
   534 		*/
   535 		bool RemoveHook(RemoveHookInfo info);
   536 
   537 		/**
   538 		*	@brief Checks whether a plugin has (a) hook manager(s) that is/are currently used by other plugins
   539 		*
   540 		*	@param plug The unique identifier of the plugin in question
   541 		*/
   542 		bool IsPluginInUse(Plugin plug);
   543 
   544 		/**
   545 		*	@brief Pauses all hooks of a plugin
   546 		*
   547 		*	@param plug The unique identifier of the plugin
   548 		*/
   549 		void PausePlugin(Plugin plug);
   550 
   551 		/**
   552 		*	@brief Unpauses all hooks of a plugin
   553 		*
   554 		*	@param plug The unique identifier of the plugin
   555 		*/
   556 		void UnpausePlugin(Plugin plug);
   557 
   558 		/**
   559 		*	@brief Return a pointer to a callclass. Generate a new one if required.
   560 		*
   561 		*	@param iface The interface pointer
   562 		*	@param size Size of the class instance
   563 		*/
   564 		GenericCallClass *GetCallClass(void *iface, size_t size);
   565 
   566 		/**
   567 		*	@brief Release a callclass
   568 		*
   569 		*	@param ptr Pointer to the callclass
   570 		*/
   571 		virtual void ReleaseCallClass(GenericCallClass *ptr);
   572 
   573 		virtual void SetRes(META_RES res);				//!< Sets the meta result
   574 		virtual META_RES GetPrevRes();					//!< Gets the meta result of the previously called handler
   575 		virtual META_RES GetStatus();					//!< Gets the highest meta result
   576 		virtual const void *GetOrigRet();				//!< Gets the original result. If not in post function, undefined
   577 		virtual const void *GetOverrideRet();			//!< Gets the override result. If none is specified, NULL
   578 		virtual void *GetIfacePtr();					//!< Gets the interface pointer
   579 
   580 		//////////////////////////////////////////////////////////////////////////
   581 		// For hook managers
   582 		void HookLoopBegin(IIface *pIface);			//!< Should be called when a hook loop begins
   583 		void HookLoopEnd();							//!< Should be called when a hook loop exits
   584 		void SetCurResPtr(META_RES *mres);			//!< Sets pointer to the current meta result
   585 		void SetPrevResPtr(META_RES *mres);			//!< Sets pointer to previous meta result
   586 		void SetStatusPtr(META_RES *mres);			//!< Sets pointer to the status variable
   587 		void SetIfacePtrPtr(void **pp);				//!< Sets pointer to the interface this pointer
   588 		void SetOrigRetPtr(const void *ptr);		//!< Sets the original return pointer
   589 		void SetOverrideRetPtr(void *ptr);			//!< Sets the override result pointer
   590 		bool ShouldContinue();						//!< Returns false if the hook loop should exit
   591 
   592 		/**
   593 		*	@brief Remove a hook manager. Auto-removes all hooks attached to it from plugin plug.
   594 		*
   595 		*	@param plug The owner of the hook manager
   596 		*   @param pubFunc The hook manager's info function
   597 		*/
   598 		virtual void RemoveHookManager(Plugin plug, HookManagerPubFunc pubFunc);
   599 		virtual void RemoveHookManager(RemoveHookManInfo info);
   600 
   601 		virtual void DoRecall();					//!< Initiates a recall sequence
   602 		virtual void *GetOverrideRetPtr();			//!< Returns the pointer set by SetOverrideRetPtr
   603 
   604 		virtual void *SetupHookLoop(META_RES *statusPtr, META_RES *prevResPtr, META_RES *curResPtr,
   605 			void **ifacePtrPtr, const void *origRetPtr, void *overrideRetPtr);
   606 	};
   607 }
   608 
   609 #endif
   610