sourcehook/sourcehook_impl.h
author Christian Hammacher <bmasterc@gmail.com>
Wed Oct 10 21:48:44 2007 +0000 (2007-10-10)
changeset 411 7c1526f514b3
parent 386 08583103ba6f
child 418 109309ff6350
permissions -rw-r--r--
updating installer for OrangeBox compatibility
     1 /* ======== SourceHook ========
     2 * Copyright (C) 2004-2007 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 #include "sh_listcat.h"
    20 
    21 /*
    22 
    23 IMPLEMENTATION INFO
    24 
    25 ---------------------------------------
    26  :TODO: update ???
    27 
    28 Protos ("Prototypes")
    29 	The purpose of protos is to provide the amount of type information about a function
    30 	which is required to be able to execute a function call without corrupting the stack.
    31 	Our protos do not fully do this, but they provide the size of the return value, the number of
    32 	parameters, and the size of each parameter, which is enough for most situations.
    33 
    34 	There are two version of protos:
    35 	OLD:
    36 		C-Style strings.
    37 
    38 		0_void:
    39 		"attrib"
    40 		1_void:
    41 		"attrib|param1_type"
    42 		2_void:
    43 		"attrib|param1_type|param2_type
    44 		0:
    45 		"attrib|ret_type"
    46 		1:
    47 		"attrib|ret_type|param1_type"
    48 		2:
    49 		"attrib|ret_type|param2_type"
    50 
    51 		Old protos are deprecated.
    52 
    53 	NEW:
    54 		New protos are in fact pointers to the ProtoInfo structure (see sourcehook.h)
    55 
    56 	Old protos begin with a non-zero byte, new protos begin with a zero byte.
    57 
    58 	Protos are usually stored in a CProto instance.
    59 
    60 ---------------------------------------
    61 Hook managers and hook manager containers
    62 	Each hookman container is tied to _one_ proto/vtable index/vtable offset info.
    63 	Hookman containers then contain a list of hook managers provided by plugins, sorted by version.
    64 	(higher versions come first)
    65 
    66 	Duplicate hook managers are ignored (ie. hook managers where proto, vtable index, vtable offset,
    67 	plugin, version are the same as in an already exisiting hook manager)
    68 
    69 	A new hook manager is always added to the end of the version group in the corresponding
    70 	hook container. 
    71 
    72 	If the new hook manager was added to the beginning of the container (which only happens if
    73 	it is the first one or if it has a higher version than the previously first hook manager),
    74 	the now second hook manager is shut down and the new hook manager takes its job.
    75 
    76 	A "hook manager container id" (HMCI) consits of three values: proto, vtbl index, vtbl offset.
    77 ---------------------------------------
    78 Hooks 
    79 	When adding a hook, first the proposed hook manager is added to the corresponding
    80 	hook manager container as described above.
    81 
    82 	Then the first hook manager in the the manhook container is chosen to handle the function.
    83 
    84 	Removing a hook does not neccessarily unreigster the plugin's hook manager. In order to do this,
    85 	use RemoveHookManager or UnloadPlugin/
    86 
    87 	Hooks can be paused - they remain in memory but they are not called. In SH, the hook iterator
    88 	classes handle pausing transparently.
    89 
    90 	The hook loop is supposed to call ShouldContinue before each iteration. This makes hook handlers
    91 	able to remove themselves.
    92 
    93 ---------------------------------------
    94 Call classes
    95 
    96 	!! deprecated !!   - see below (new SH_CALL)
    97 
    98 	Call classes are identified by a this pointer and an instance size
    99 
   100 	We use the instance size because a derived class instance and a base class instance could
   101 	have the same this pointers, and we want to avoid that the derived class
   102 	(which could be bigger) gets the same callclass as the base class (mainly if the
   103 	base class' callclass was requested first).
   104 
   105 	Call classes are reference counted.
   106 
   107 	The original function pointers are stored in a vector (in order to allow fast random access).
   108 	These vectors are stored as the value type of a hash. The key type is int and represents the
   109 	vtable offset.
   110 
   111 	If the hash key doesn't exist or the vtblidx is out of range or the corresponding element in the
   112 	vector is NULL, there is no hook on that function.
   113 
   114 ---------------------------------------
   115 Recalls
   116 	Recalls are used for the META_RETURN_(VALUE_)NEWPARAMS macros, ie. to change the parameters
   117 	in the hook loop on the fly.
   118 	
   119 	First, the macro calls DoRecall(), then it calls the function the hook is attached to -> it 
   120 	calls the hookfunc. SourceHook makes sure that the newly invoked hook loop starts where the last
   121 	one left off and that status variables like status, previous result, override return are kept.
   122 	When this recurisvely called hookfunc returns, the macro returns what it returned
   123 	(using MRES_SUPERCEDE). CSourceHookImpl returns false from ShouldContinue so the original hook loop
   124 	is abandonned.
   125 
   126 Post Recalls
   127 	People wanted to be able to use META_RETURN_(VALUE_)NEWPARAMS from post hooks as well. Crazy people!
   128 	Anyway, for this, we have to know where a hook handler is. Is it executing pre or post hooks at the moment?
   129 	The only way we can know this is watching when it calls CHookList::GetIter(). So CHookList gets a new variable:
   130 	m_RequestedFlag. It also gets two new functions: RQFlagReset() and RQFlagGet().
   131 	HookLoopBegin() calls RQFlagReset on both hooklists of the iface; then DoRecall() checks whether the postlist's 
   132 	RQ flag is set. if yes, the hook loop is in post mode.
   133 
   134 	So, what a about a recall in post mode? The first ShouldContinue returns false and sets Status to supercede. 
   135 	This way the pre hooks and the function call will be skipped. Then, then next ShouldContinue returns true, so we get
   136 	into the post hooks. HA!
   137 
   138 Return Values in Post Recalls
   139 	The easy case is when we already have an override return value. In this case, the status register gets transferred,
   140 	and so does the override return pointer. So, basically, everything is ok.
   141 
   142 	However, what happens if we don't? ie. the status register is on MRES_IGNORED? In this case we'd have to transfer the
   143 	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.
   144 	So, we emulate it. GetOrigRet will return the orig ret pointer from the old hook loop. If still no one overrides it,
   145 	we'd have to return it. BUT! HOW TO DO THIS? Check out SH_RETURN(). First calls HookLoopEnd(), then decides whether
   146 	to return the override retval or the orig retval. But it doesn't ask for a new override return. So we give the function
   147 	the last orig return value as its new override return value; but leave status where it is so everything works, and in
   148 	HookLoopEnd we make sure that status is high enough so that the override return will be returned. crazy.
   149 
   150 	All this stuff could be much less complicated if I didn't try to preserve binary compatibility :)
   151 
   152 VP Hooks
   153 	VP hooks are hooks which are called on a vfnptr, regardless of the this pointer with which it was called. They are
   154 	implemented as a special CIface instance with m_Ptr = NULL. All Hook Lists have a new "ListCatIterator" which
   155 	virtually concatenates the NULL-interface-hook-list with their normal hook list.
   156 
   157 
   158 	I'm afraid that with the addition of Recalls and VP Hooks, SourceHook is now a pretty complex and hacked-together
   159 	binary compatible beast which is pretty hard to maintain unless you've written it :)
   160 
   161 New SH_CALL
   162 	The addition of VP hooks messed up the Call Classes concept (see above) - call classes are bound to an
   163 	instance pointer; they only work on one of the hooked instances. But VP hooks are called on all instances.
   164 	
   165 	That's why now, SH_CALL takes an instance pointer instead of a callclass pointer. It basically does this:
   166 	1) call SH_GLOB_PTR->SetIgnoreHooks(vfnptr)
   167 	2) call this->*mfp
   168 	3) call SH_GLOB_PTR->ResetIgnoreHooks(vfnptr)
   169 
   170 	SourceHook stroes the "ignored vfnptr" and makes CVfnPtr::FindIface return NULL if the CVfnPtr instance
   171 	corresponds to the ignored vfnptr. This way the hook manager thinks that the instance isn't hooked, and calls
   172 	the original function. Everything works fine. This works even for VP hooks.
   173 */
   174 
   175 #include "sourcehook_impl_cproto.h"
   176 #include "sourcehook_impl_chook.h"
   177 #include "sourcehook_impl_ciface.h"
   178 #include "sourcehook_impl_cvfnptr.h"
   179 #include "sourcehook_impl_chookmaninfo.h"
   180 #include "sourcehook_impl_chookmancont.h"
   181 #include "sourcehook_impl_chookidman.h"
   182 
   183 namespace SourceHook
   184 {
   185 	/**
   186 	*	@brief The SourceHook implementation
   187 	*/
   188 
   189 	namespace Impl
   190 	{
   191 
   192 		class CHookManContainerList : public List<CHookManagerContainer>
   193 		{
   194 		public:
   195 			CHookManagerContainer &GetContainer(int vtbloffs, int vtblidx, const CProto &proto);
   196 			void RemoveHookMans(Plugin plug);
   197 			void RemoveHookMans(Plugin plug, HookManagerPubFunc pubFunc);
   198 		};
   199 
   200 		struct CHookContext : IHookContext
   201 		{
   202 			enum State
   203 			{
   204 				State_Born,
   205 				State_Pre,
   206 				State_PreVP,
   207 				State_Post,
   208 				State_PostVP,
   209 				State_OrigCall,
   210 				State_Dead,
   211 
   212 				// Special
   213 				State_Ignore,
   214 				State_Recall_Pre,
   215 				State_Recall_PreVP,
   216 				State_Recall_Post,
   217 				State_Recall_PostVP
   218 			};
   219 
   220 			int m_State;
   221 			List<CHook>::iterator m_Iter;
   222 
   223 			CVfnPtr *pVfnPtr;
   224 			CIface *pIface;
   225 			
   226 			META_RES *pStatus;
   227 			META_RES *pPrevRes;
   228 			META_RES *pCurRes;
   229 
   230 			void *pThisPtr;
   231 			const void *pOrigRet;
   232 			void *pOverrideRet;
   233 			void *pIfacePtr;
   234 
   235 			bool m_CallOrig;
   236 
   237 			void SkipPaused(List<CHook>::iterator &iter, List<CHook> &list)
   238 			{
   239 				while (iter != list.end() && iter->IsPaused())
   240 					++iter;
   241 			}
   242 		public:
   243 			void HookRemoved(List<CHook>::iterator oldhookiter, List<CHook>::iterator nexthookiter);
   244 			void IfaceRemoved(CIface *iface);
   245 			void VfnPtrRemoved(CVfnPtr *vfnptr);
   246 
   247 			ISHDelegate *GetNext();
   248 			void *GetOverrideRetPtr();
   249 			const void *GetOrigRetPtr();
   250 			bool ShouldCallOrig();
   251 		};
   252 
   253 		typedef CStack<CHookContext> HookContextStack;
   254 
   255 		class CSourceHookImpl : public ISourceHook
   256 		{
   257 		private:
   258 			CHookManContainerList m_HookManContainers;
   259 			CHookIDManager m_HookIDMan;
   260 			HookContextStack m_ContextStack;
   261 
   262 			bool SetHookPaused(int hookid, bool paused);
   263 		public:
   264 			CSourceHookImpl();
   265 			virtual ~CSourceHookImpl();
   266 
   267 			/**
   268 			*	@brief Returns the interface version
   269 			*/
   270 			int GetIfaceVersion();
   271 
   272 			/**
   273 			*	@brief Returns the implemnetation version
   274 			*/
   275 			int GetImplVersion();
   276 
   277 			int AddHook(Plugin plug, AddHookMode mode, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan,
   278 				ISHDelegate *handler, bool post);
   279 
   280 			bool RemoveHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan,
   281 				ISHDelegate *handler, bool post);
   282 
   283 			bool RemoveHookByID(int hookid);
   284 
   285 			bool PauseHookByID(int hookid);
   286 			bool UnpauseHookByID(int hookid);
   287 
   288 			void SetRes(META_RES res);				//!< Sets the meta result
   289 			META_RES GetPrevRes();					//!< Gets the meta result of the
   290 													//!<  previously calledhandler
   291 			META_RES GetStatus();					//!< Gets the highest meta result
   292 			const void *GetOrigRet();				//!< Gets the original result.
   293 													//!<  If not in post function, undefined
   294 			const void *GetOverrideRet();			//!< Gets the override result.
   295 													//!<  If none is specified, NULL
   296 			void *GetIfacePtr();					//!< Gets the interface pointer
   297 
   298 			void *GetOverrideRetPtr();				//!< Used for setting the override return value
   299 
   300 			/**
   301 			*	@brief Make sure that a plugin is not used by any other plugins anymore, and unregister all its hook managers
   302 			*/
   303 			void UnloadPlugin(Plugin plug);
   304 
   305 			void RemoveHookManager(Plugin plug, HookManagerPubFunc pubFunc);
   306 
   307 			void SetIgnoreHooks(void *vfnptr);
   308 			void ResetIgnoreHooks(void *vfnptr);
   309 
   310 			void DoRecall();
   311 
   312 			IHookContext *SetupHookLoop(IHookManagerInfo *hi, void *vfnptr, void *thisptr, void **origentry, META_RES *statusPtr,
   313 				META_RES *prevResPtr, META_RES *curResPtr, const void *origRetPtr, void *overrideRetPtr);
   314 
   315 			void EndContext(IHookContext *pCtx);
   316 
   317 			void *GetOrigVfnPtrEntry(void *vfnptr);
   318 
   319 			/**
   320 			*	@brief Shut down the whole system, unregister all hook managers
   321 			*/
   322 			void CompleteShutdown();
   323 
   324 			/**
   325 			*	@brief Pauses all hooks of a plugin
   326 			*
   327 			*	@param plug The unique identifier of the plugin
   328 			*/
   329 			void PausePlugin(Plugin plug);
   330 
   331 			/**
   332 			*	@brief Unpauses all hooks of a plugin
   333 			*
   334 			*	@param plug The unique identifier of the plugin
   335 			*/
   336 			void UnpausePlugin(Plugin plug);
   337 		};
   338 	}
   339 }
   340 
   341 #endif