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