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