core/sourcehook/sourcehook.cpp
author Scott Ehlert <ds@alliedmods.net>
Thu Dec 10 00:59:50 2009 -0600 (2009-12-10)
changeset 689 4065ba5e9155
parent 539 db914129ae01
child 733 2365240861a2
permissions -rw-r--r--
Rewrote user message caching code to always use IServerGameDLL::GetUserMessageInfo (bug 4117, r=dvander).

Games where the above function can crash are handled by detouring tier0's Error() function and jumping back to our own code. So in theory this should work on all games now.
     1 /* ======== SourceHook ========
     2 * Copyright (C) 2004-2008 Metamod:Source Development Team
     3 * No warranties of any kind
     4 *
     5 * License: zlib/libpng
     6 *
     7 * Author(s): Pavol "PM OnoTo" Marko
     8 * Contributors: Scott "Damaged Soul" Ehlert
     9 * ============================
    10 */
    11 
    12 /**
    13  * @file sourcehook.cpp
    14  * @brief Contains the implementation of the SourceHook API
    15 */
    16 
    17 #if defined __GNUC__
    18 #include <stdint.h>
    19 #endif
    20 
    21 #include "sourcehook_impl.h"
    22 
    23 namespace SourceHook
    24 {
    25 	template<>
    26 	int HashFunction<int>(const int & k)
    27 	{
    28 		return k;
    29 	}
    30 	template<>
    31 	int Compare<int>(const int & k1, const int & k2)
    32 	{
    33 		if (k1 == k2)
    34 			return 0;
    35 		if (k1 > k2)
    36 			return 1;
    37 		if (k1 < k2)
    38 			return -1;
    39 		return 0;
    40 	}
    41 
    42 	namespace Impl
    43 	{
    44 		//////////////////////////////////////////////////////////////////////////
    45 		// CProto
    46 		//////////////////////////////////////////////////////////////////////////
    47 		void CProto::Fill(const ProtoInfo *pProto)
    48 		{
    49 			if (pProto == NULL)
    50 				m_Version = -1;
    51 
    52 			m_ParamsPassInfo.clear();
    53 
    54 			if (pProto->paramsPassInfo[0].size == 0)
    55 			{
    56 				// Version 1
    57 				m_Version = 0;
    58 				m_Convention = pProto->convention;
    59 				m_NumOfParams = pProto->numOfParams;
    60 
    61 				m_RetPassInfo.size = pProto->retPassInfo.size;
    62 				m_RetPassInfo.type = pProto->retPassInfo.type;
    63 				m_RetPassInfo.flags = GetRealFlags(pProto->retPassInfo);
    64 
    65 				m_RetPassInfo.pNormalCtor = NULL;
    66 				m_RetPassInfo.pCopyCtor = NULL;
    67 				m_RetPassInfo.pDtor = NULL;
    68 				m_RetPassInfo.pAssignOperator = NULL;
    69 
    70 				
    71 				m_ParamsPassInfo.resize(pProto->numOfParams);
    72 
    73 				for (int i = 1; i <= pProto->numOfParams; ++i)
    74 				{
    75 					m_ParamsPassInfo[i-1].size = pProto->paramsPassInfo[i].size;
    76 					m_ParamsPassInfo[i-1].type = pProto->paramsPassInfo[i].type;
    77 					m_ParamsPassInfo[i-1].flags = GetRealFlags(pProto->paramsPassInfo[i]);
    78 
    79 					m_ParamsPassInfo[i-1].pNormalCtor = NULL;
    80 					m_ParamsPassInfo[i-1].pCopyCtor = NULL;
    81 					m_ParamsPassInfo[i-1].pDtor = NULL;
    82 					m_ParamsPassInfo[i-1].pAssignOperator = NULL;
    83 				}
    84 			}
    85 			else if (pProto->paramsPassInfo[0].size == 1)
    86 			{
    87 				// Version 2
    88 				m_Version = 1;
    89 				m_Convention = pProto->convention;
    90 				m_NumOfParams = pProto->numOfParams;
    91 
    92 				m_RetPassInfo.size = pProto->retPassInfo.size;
    93 				m_RetPassInfo.type = pProto->retPassInfo.type;
    94 				m_RetPassInfo.flags = pProto->retPassInfo.flags;
    95 
    96 				m_RetPassInfo.pNormalCtor = pProto->retPassInfo2.pNormalCtor;
    97 				m_RetPassInfo.pCopyCtor = pProto->retPassInfo2.pCopyCtor;
    98 				m_RetPassInfo.pDtor = pProto->retPassInfo2.pDtor;
    99 				m_RetPassInfo.pAssignOperator = pProto->retPassInfo2.pAssignOperator;
   100 
   101 				m_ParamsPassInfo.resize(pProto->numOfParams);
   102 
   103 				for (int i = 1; i <= pProto->numOfParams; ++i)
   104 				{
   105 					m_ParamsPassInfo[i-1].size = pProto->paramsPassInfo[i].size;
   106 					m_ParamsPassInfo[i-1].type = pProto->paramsPassInfo[i].type;
   107 					m_ParamsPassInfo[i-1].flags = pProto->paramsPassInfo[i].flags;
   108 
   109 					m_ParamsPassInfo[i-1].pNormalCtor = pProto->paramsPassInfo2[i].pNormalCtor;
   110 					m_ParamsPassInfo[i-1].pCopyCtor = pProto->paramsPassInfo2[i].pCopyCtor;
   111 					m_ParamsPassInfo[i-1].pDtor = pProto->paramsPassInfo2[i].pDtor;
   112 					m_ParamsPassInfo[i-1].pAssignOperator = pProto->paramsPassInfo2[i].pAssignOperator;
   113 				}
   114 			}
   115 			else
   116 			{
   117 				// Unknown
   118 				m_Version = -1;
   119 			}
   120 		}
   121 
   122 		// Basic compat test
   123 		// Other than this, we assume that the plugins know what they're doing
   124 		bool CProto::operator == (const CProto &other) const
   125 		{
   126 			if (m_Version < 0 || other.GetVersion() < 0)
   127 				return false;
   128 
   129 			if (m_NumOfParams != other.GetNumOfParams())
   130 				return false;
   131 
   132 			if (m_Convention != ProtoInfo::CallConv_Unknown && other.GetConvention() != ProtoInfo::CallConv_Unknown &&
   133 				m_Convention != other.GetConvention())
   134 				return false;
   135 
   136 			if (GetRealSize(GetRet()) != GetRealSize(other.GetRet()))
   137 				return false;
   138 
   139 			for (int i = 0; i < m_NumOfParams; ++i)
   140 			{
   141 				if (GetRealSize(GetParam(i)) != GetRealSize(other.GetParam(i)))
   142 					return false;
   143 				if (GetParam(i).type != PassInfo::PassType_Unknown && other.GetParam(i).type != PassInfo::PassType_Unknown)
   144 				{
   145 					if (GetParam(i).type != other.GetParam(i).type)
   146 						return false;
   147 					if (GetParam(i).flags != other.GetParam(i).flags)
   148 						return false;
   149 				}
   150 			}
   151 
   152 			return true;
   153 		}
   154 
   155 		bool CProto::ExactlyEqual(const CProto &other) const
   156 		{
   157 			if (m_Version != other.m_Version ||
   158 				m_NumOfParams != other.m_NumOfParams ||
   159 				m_Convention != other.m_Convention ||
   160 				GetRet() != other.GetRet())
   161 			{
   162 				return false;
   163 			}
   164 
   165 			for (int i = 0; i < m_NumOfParams; ++i)
   166 			{
   167 				if(GetParam(i) != other.GetParam(i))
   168 					return false;
   169 			}
   170 
   171 			return true;
   172 		}
   173 		
   174 		//////////////////////////////////////////////////////////////////////////
   175 		// CHookManager
   176 		//////////////////////////////////////////////////////////////////////////
   177 		void CHookManager::SetInfo(int hookman_version, int vtbloffs, int vtblidx,
   178 			ProtoInfo *proto, void *hookfunc_vfnptr)
   179 		{
   180 			m_Version = hookman_version;
   181 			m_VtblOffs = vtbloffs;
   182 			m_VtblIdx = vtblidx;
   183 			m_Proto = proto;
   184 			m_HookfuncVfnptr = hookfunc_vfnptr;
   185 		}
   186 
   187 		//////////////////////////////////////////////////////////////////////////
   188 		// CVfnPtrList
   189 		//////////////////////////////////////////////////////////////////////////
   190 
   191 		CVfnPtr &CVfnPtrList::GetVfnPtr(void *vfnptr)
   192 		{
   193 			iterator iter = find(vfnptr);
   194 			if (iter == end())
   195 			{
   196 				CVfnPtr newVfnPtr(vfnptr);
   197 				push_back(newVfnPtr);
   198 
   199 				return back();
   200 			}
   201 			else
   202 			{
   203 				return *iter;
   204 			}
   205 		}
   206 		//////////////////////////////////////////////////////////////////////////
   207 		// CVfnPtr
   208 		//////////////////////////////////////////////////////////////////////////
   209 		
   210 		void CVfnPtr::AddHookMan(CHookManager *pHookMan)
   211 		{
   212 			List<CHookManager*>::iterator iter;
   213 
   214 			// Don't accept invalid hook managers
   215 			if (!*pHookMan)
   216 				return;
   217 
   218 			// Check whether this hook manager already exists; if yes, ignore.
   219 			iter = m_HookMans.find(pHookMan);
   220 			if (iter != m_HookMans.end())
   221 				return;
   222 
   223 			// It doesn't -> add it. Add it to the end of its version group.
   224 			for (iter = m_HookMans.begin(); iter != m_HookMans.end(); ++iter)
   225 			{
   226 				if ((*iter)->GetVersion() < pHookMan->GetVersion())
   227 					break;
   228 			}
   229 
   230 			bool isBeginning = iter == m_HookMans.begin();
   231 
   232 			m_HookMans.insert(iter, pHookMan);
   233 
   234 			if (isBeginning)
   235 			{
   236 				pHookMan->IncrRef(this);
   237 				if (m_HookMans.size() > 1)
   238 				{
   239 					// If another hookman was used until now but this one is better
   240 					// (which it is because it's the first -> it has a higher version)
   241 					// -> switch!
   242 
   243 					List<CHookManager*>::iterator second = m_HookMans.begin();
   244 					++second;
   245 
   246 					(*second)->DecrRef(this);
   247 				}
   248 
   249 				// Make sure that this vfnptr points at it
   250 				Patch(pHookMan->GetHookFunc());
   251 			}
   252 		}
   253 
   254 		bool CVfnPtr::HookManRemoved(CHookManager *pHookMan)
   255 		{
   256 			// Don't accept invalid hook managers
   257 			if (!*pHookMan)
   258 				return true;
   259 
   260 			List<CHookManager*>::iterator iter = m_HookMans.find(pHookMan);
   261 			if (iter == m_HookMans.end())
   262 				return true;							// Didn't exist here anyway
   263 
   264 			if (iter == m_HookMans.begin())
   265 			{
   266 				// It is the first one!
   267 				pHookMan->DecrRef(this);
   268 				m_HookMans.erase(iter);
   269 
   270 				if (m_HookMans.empty())
   271 					return false;				// No more hookmans -> let SH delete us
   272 
   273 				// Activate second -> now first hookman
   274 				m_HookMans.front()->IncrRef(this);
   275 				Patch(m_HookMans.front()->GetHookFunc());
   276 			}
   277 			else
   278 			{
   279 				m_HookMans.erase(iter);
   280 			}
   281 			return true;
   282 		}
   283 
   284 		bool CVfnPtr::Patch(void *newValue)
   285 		{
   286 			if (!SetMemAccess(m_Ptr, sizeof(void*), SH_MEM_READ | SH_MEM_WRITE))
   287 			{
   288 				return false;
   289 			}
   290 
   291 			*reinterpret_cast<void**>(m_Ptr) = newValue;
   292 
   293 			return true;
   294 		}
   295 
   296 		CIface &CVfnPtr::GetIface(void *iface)
   297 		{
   298 			List<CIface>::iterator iter = m_IfaceList.find(iface);
   299 			if (iter == m_IfaceList.end())
   300 			{
   301 				CIface newIface(iface);
   302 				if (iface == NULL)
   303 				{
   304 					m_IfaceList.push_front(newIface);
   305 					return m_IfaceList.front();
   306 				}
   307 				else
   308 				{
   309 					m_IfaceList.push_back(newIface);
   310 					return m_IfaceList.back();
   311 				}
   312 			}
   313 			else
   314 			{
   315 				return *iter;
   316 			}
   317 		}
   318 
   319 		//////////////////////////////////////////////////////////////////////////
   320 		// CHookIdManager
   321 		//////////////////////////////////////////////////////////////////////////
   322 		CHookIDManager::CHookIDManager()
   323 		{
   324 		}
   325 
   326 		int CHookIDManager::New(const CProto &proto, int vtbl_offs, int vtbl_idx, void *vfnptr,
   327 			void *adjustediface, Plugin plug, int thisptr_offs, ISHDelegate *handler, bool post)
   328 		{
   329 			Entry tmp(proto, vtbl_offs, vtbl_idx, vfnptr, adjustediface, plug, thisptr_offs, handler, post);
   330 
   331 			size_t cursize = m_Entries.size();
   332 			for (size_t i = 0; i < cursize; ++i)
   333 			{
   334 				if (m_Entries[i].isfree)
   335 				{
   336 					m_Entries[i] = tmp;
   337 					return static_cast<int>(i) + 1;
   338 				}
   339 			}
   340 
   341 			m_Entries.push_back(tmp);
   342 			return static_cast<int>(m_Entries.size());		// return size() because hookid = id+1 anyway
   343 		}
   344 
   345 		bool CHookIDManager::Remove(int hookid)
   346 		{
   347 			int realid = hookid - 1;
   348 			if (realid < 0 || realid >= static_cast<int>(m_Entries.size()) || m_Entries[realid].isfree)
   349 				return false;
   350 
   351 			m_Entries[realid].isfree = true;
   352 
   353 			// :TODO: remove free ids from back sometimes ??
   354 
   355 			return true;
   356 		}
   357 
   358 		const CHookIDManager::Entry * CHookIDManager::QueryHook(int hookid)
   359 		{
   360 			int realid = hookid - 1;
   361 			if (realid < 0 || realid >= static_cast<int>(m_Entries.size()) || m_Entries[realid].isfree)
   362 				return NULL;
   363 
   364 			return &m_Entries[realid];
   365 		}
   366 
   367 		void CHookIDManager::FindAllHooks(CVector<int> &output, const CProto &proto, int vtbl_offs,
   368 			int vtbl_idx, void *adjustediface, Plugin plug, int thisptr_offs, ISHDelegate *handler, bool post)
   369 		{
   370 			// oh my god, a lot of parameters...
   371 			size_t cursize = m_Entries.size();
   372 			for (size_t i = 0; i < cursize; ++i)
   373 			{
   374 				if (!m_Entries[i].isfree && m_Entries[i].proto == proto && m_Entries[i].vtbl_offs == vtbl_offs &&
   375 					m_Entries[i].vtbl_idx == vtbl_idx && m_Entries[i].adjustediface == adjustediface && m_Entries[i].plug == plug &&
   376 					m_Entries[i].thisptr_offs == thisptr_offs && m_Entries[i].handler->IsEqual(handler) && m_Entries[i].post == post)
   377 				{
   378 					output.push_back(static_cast<int>(i) + 1);
   379 				}
   380 			}
   381 		}
   382 
   383 		void CHookIDManager::FindAllHooks(CVector<int> &output)
   384 		{
   385 			size_t cursize = m_Entries.size();
   386 			for (size_t i = 0; i < cursize; ++i)
   387 			{
   388 				if (!m_Entries[i].isfree)
   389 					output.push_back(static_cast<int>(i) + 1);
   390 			}
   391 		}
   392 
   393 		void CHookIDManager::FindAllHooks(CVector<int> &output, Plugin plug)
   394 		{
   395 			size_t cursize = m_Entries.size();
   396 			for (size_t i = 0; i < cursize; ++i)
   397 			{
   398 				if (!m_Entries[i].isfree && m_Entries[i].plug == plug)
   399 					output.push_back(static_cast<int>(i) + 1);
   400 			}
   401 		}
   402 
   403 
   404 		void CHookIDManager::RemoveAll(void *vfnptr)
   405 		{
   406 			size_t cursize = m_Entries.size();
   407 			for (size_t i = 0; i < cursize; ++i)
   408 			{
   409 				if (!m_Entries[i].isfree && m_Entries[i].vfnptr == vfnptr)
   410 					m_Entries[i].isfree = true;
   411 			}
   412 		}
   413 
   414 		//////////////////////////////////////////////////////////////////////////
   415 		// CSourceHookImpl
   416 		//////////////////////////////////////////////////////////////////////////
   417 		
   418 
   419 		CSourceHookImpl::CSourceHookImpl()
   420 		{
   421 		}
   422 		CSourceHookImpl::~CSourceHookImpl()
   423 		{
   424 			CompleteShutdown();
   425 		}
   426 
   427 		int CSourceHookImpl::GetIfaceVersion()
   428 		{
   429 			return SH_IFACE_VERSION;
   430 		}
   431 
   432 		int CSourceHookImpl::GetImplVersion()
   433 		{
   434 			return SH_IMPL_VERSION;
   435 		}
   436 
   437 		int CSourceHookImpl::AddHook(Plugin plug, AddHookMode mode, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan,
   438 			ISHDelegate *handler, bool post)
   439 		{
   440 			if (mode != Hook_Normal && mode != Hook_VP && mode != Hook_DVP)
   441 				return 0;
   442 
   443 			// Get info about hook manager
   444 			CHookManager hookManager(plug, myHookMan);
   445 			if (!hookManager)
   446 				return 0;
   447 
   448 			void *adjustediface = NULL;
   449 			void **cur_vtptr = NULL;
   450 			void *cur_vfnptr = NULL;
   451 
   452 			// find vfnptr
   453 			switch (mode)
   454 			{
   455 			case Hook_Normal:
   456 				adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface) + thisptr_offs);
   457 
   458 				cur_vtptr = *reinterpret_cast<void***>(
   459 					reinterpret_cast<char*>(adjustediface) + hookManager.GetVtblOffs());
   460 				cur_vfnptr = reinterpret_cast<void*>(cur_vtptr + hookManager.GetVtblIdx());
   461 				break;
   462 
   463 			case Hook_VP:
   464 
   465 				adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface) + thisptr_offs);
   466 
   467 				cur_vtptr = *reinterpret_cast<void***>(
   468 					reinterpret_cast<char*>(adjustediface) + hookManager.GetVtblOffs());
   469 				cur_vfnptr = reinterpret_cast<void*>(cur_vtptr + hookManager.GetVtblIdx());
   470 
   471 				adjustediface = NULL;
   472 				break;
   473 
   474 			case Hook_DVP:
   475 				adjustediface = NULL;
   476 
   477 				cur_vtptr = reinterpret_cast<void**>(iface);
   478 				cur_vfnptr = cur_vtptr + hookManager.GetVtblIdx();
   479 
   480 				break;
   481 			}
   482 
   483 			CVfnPtr &vfnPtr = m_VfnPtrs.GetVfnPtr(cur_vfnptr);
   484 			vfnPtr.AddHookMan(m_HookManList.GetHookMan(hookManager));
   485 			CIface &ifaceinst = vfnPtr.GetIface(adjustediface);
   486 
   487 			// Add the hook
   488 			CHook hook(plug, thisptr_offs, handler, 
   489 
   490 				m_HookIDMan.New(hookManager.GetProto(), hookManager.GetVtblOffs(), hookManager.GetVtblIdx(),
   491 					cur_vfnptr, adjustediface, plug, thisptr_offs, handler, post)
   492 
   493 				);
   494 
   495 			if (post)
   496 				ifaceinst.GetPostHookList().push_back(hook);
   497 			else
   498 				ifaceinst.GetPreHookList().push_back(hook);
   499 
   500 			return hook.GetID();
   501 		}
   502 
   503 		bool CSourceHookImpl::RemoveHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan,
   504 			ISHDelegate *handler, bool post)
   505 		{
   506 			// Get info about hook manager and compute adjustediface
   507 			CHookManager tmpHookMan(plug, myHookMan);
   508 
   509 			void *adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface)+thisptr_offs);
   510 
   511 			// Loop through all hooks and remove those which match:
   512 			//  hookman, vfnptr, iface, plug, adjusted iface, this ptr offs, handler, post
   513 			CVector<int> removehooks;
   514 			m_HookIDMan.FindAllHooks(removehooks, tmpHookMan.GetProto(), tmpHookMan.GetVtblOffs(), tmpHookMan.GetVtblIdx(),
   515 				adjustediface, plug, thisptr_offs, handler, post);
   516 
   517 			if (removehooks.empty())
   518 				return false;
   519 
   520 			bool status = false;
   521 
   522 			for (CVector<int>::iterator iter = removehooks.begin(); iter != removehooks.end(); ++iter)
   523 			{
   524 				if (RemoveHookByID(*iter))
   525 					status = true;
   526 			}
   527 			return status; 
   528 		}
   529 
   530 		bool CSourceHookImpl::RemoveHookByID(int hookid)
   531 		{
   532 			const CHookIDManager::Entry *hentry;
   533 
   534 			hentry = m_HookIDMan.QueryHook(hookid);
   535 			if (!hentry)
   536 			{
   537 				// hookid doesn't exist !
   538 				return false;
   539 			}
   540 
   541 			// find vfnptr
   542 			List<CVfnPtr>::iterator vfnptr_iter = m_VfnPtrs.find(hentry->vfnptr);
   543 			if (vfnptr_iter == m_VfnPtrs.end())
   544 				return false;
   545 
   546 			// find iface
   547 			List<CIface>::iterator iface_iter = vfnptr_iter->GetIfaceList().find(hentry->adjustediface);
   548 			if (iface_iter == vfnptr_iter->GetIfaceList().end())
   549 				return false;
   550 
   551 			// find hook
   552 			List<CHook> &hooks = hentry->post ? iface_iter->GetPostHookList() : iface_iter->GetPreHookList();
   553 			List<CHook>::iterator hook_iter = hooks.find(hookid);
   554 			if (hook_iter == hooks.end())
   555 				return false;
   556 
   557 			hook_iter->GetHandler()->DeleteThis();
   558 
   559 			// Iterator movage!
   560 			List<CHook>::iterator oldhookiter = hook_iter;
   561 			hook_iter = hooks.erase(hook_iter);
   562 
   563 			for (CStack<CHookContext>::iterator ctx_iter = m_ContextStack.begin();
   564 				ctx_iter != m_ContextStack.end(); ++ctx_iter)
   565 			{
   566 				ctx_iter->HookRemoved(oldhookiter, hook_iter);
   567 			}
   568 
   569 			if (iface_iter->GetPreHookList().empty() && iface_iter->GetPostHookList().empty())
   570 			{
   571 				// -> Kill all contexts that use it!
   572 				for (CStack<CHookContext>::iterator ctx_iter = m_ContextStack.begin();
   573 					ctx_iter != m_ContextStack.end(); ++ctx_iter)
   574 				{
   575 					ctx_iter->IfaceRemoved(&(*iface_iter));
   576 				}
   577 
   578 				// There are no hooks on this iface anymore...
   579 				iface_iter = vfnptr_iter->GetIfaceList().erase(iface_iter);
   580 
   581 				if (vfnptr_iter->GetIfaceList().empty())
   582 				{
   583 					// No ifaces at all -> Deactivate the hook
   584 
   585 					for (CStack<CHookContext>::iterator ctx_iter = m_ContextStack.begin();
   586 						ctx_iter != m_ContextStack.end(); ++ctx_iter)
   587 					{
   588 						ctx_iter->VfnPtrRemoved(&(*vfnptr_iter));
   589 					}
   590 
   591 					vfnptr_iter->Revert();
   592 
   593 					m_VfnPtrs.erase(vfnptr_iter);
   594 				}
   595 			}
   596 
   597 			m_HookIDMan.Remove(hookid);
   598 			return true;
   599 		}
   600 
   601 		void CSourceHookImpl::SetRes(META_RES res)
   602 		{
   603 			*m_ContextStack.front().pCurRes = res;
   604 		}
   605 
   606 		META_RES CSourceHookImpl::GetPrevRes()
   607 		{
   608 			return *m_ContextStack.front().pPrevRes;
   609 		}
   610 
   611 		META_RES CSourceHookImpl::GetStatus()
   612 		{
   613 			return *m_ContextStack.front().pStatus;
   614 
   615 		}
   616 
   617 		const void *CSourceHookImpl::GetOrigRet()
   618 		{
   619 			return m_ContextStack.front().pOrigRet;
   620 		}
   621 
   622 		const void *CSourceHookImpl::GetOverrideRet()
   623 		{
   624 			return (*m_ContextStack.front().pStatus < MRES_OVERRIDE) ?
   625 				NULL : m_ContextStack.front().pOverrideRet;
   626 		}
   627 
   628 		void *CSourceHookImpl::GetIfacePtr()
   629 		{
   630 			// If in recall: return last one
   631 			if (m_ContextStack.front().m_State >= CHookContext::State_Recall_Pre &&
   632 				m_ContextStack.front().m_State <= CHookContext::State_Recall_PostVP)
   633 			{
   634 				return m_ContextStack.second().pIfacePtr;
   635 			}
   636 			else
   637 			{
   638 				return m_ContextStack.front().pIfacePtr;
   639 			}
   640 		}
   641 
   642 		void *CSourceHookImpl::GetOverrideRetPtr()
   643 		{
   644 			return m_ContextStack.front().pOverrideRet;
   645 		}
   646 
   647 		void CSourceHookImpl::UnloadPlugin(Plugin plug)
   648 		{
   649 			// 1) Remove all hooks by this plugin
   650 
   651 			CVector<int> removehooks;
   652 			m_HookIDMan.FindAllHooks(removehooks, plug);
   653 
   654 			for (CVector<int>::iterator iter = removehooks.begin(); iter != removehooks.end(); ++iter)
   655 				RemoveHookByID(*iter);
   656 
   657 			// 2) Remove all hook managers
   658 			for (CHookManList::iterator iter = m_HookManList.begin(); iter != m_HookManList.end(); )
   659 			{
   660 				if (iter->GetOwnerPlugin() == plug)
   661 					iter = RemoveHookManager(iter);
   662 				else
   663 					++iter;
   664 			}
   665 		}
   666 
   667 		CHookManList::iterator CSourceHookImpl::RemoveHookManager(CHookManList::iterator hookman_iter)
   668 		{
   669 			// 2) Remove it
   670 			for (CVfnPtrList::iterator vfnptr_iter = m_VfnPtrs.begin();
   671 				vfnptr_iter != m_VfnPtrs.end();)
   672 			{
   673 				if (!vfnptr_iter->HookManRemoved(&(*hookman_iter)))
   674 				{
   675 					// This vfnptr has no more hook managers
   676 					// and asks to be removed.
   677 
   678 					vfnptr_iter->Revert();
   679 
   680 					m_HookIDMan.RemoveAll(vfnptr_iter->GetPtr());
   681 					vfnptr_iter = m_VfnPtrs.erase(vfnptr_iter);
   682 				}
   683 				else
   684 				{
   685 					++vfnptr_iter;
   686 				}
   687 			}
   688 
   689 			return m_HookManList.erase(hookman_iter);
   690 		}
   691 
   692 		void CSourceHookImpl::RemoveHookManager(Plugin plug, HookManagerPubFunc pubFunc)
   693 		{
   694 			// Find the hook manager
   695 			CHookManList::iterator hookman_iter = m_HookManList.find(CHookManager::Descriptor(plug, pubFunc));
   696 
   697 			if (hookman_iter != m_HookManList.end())
   698 			{
   699 				RemoveHookManager(hookman_iter);
   700 			}
   701 		}
   702 
   703 		void CSourceHookImpl::SetIgnoreHooks(void *vfnptr)
   704 		{
   705 			CHookContext ctx;
   706 			ctx.m_State = CHookContext::State_Ignore;
   707 			m_ContextStack.push(ctx);
   708 		}
   709 
   710 		void CSourceHookImpl::ResetIgnoreHooks(void *vfnptr)
   711 		{
   712 			if (!m_ContextStack.empty() && m_ContextStack.front().m_State == CHookContext::State_Ignore)
   713 				m_ContextStack.pop();
   714 		}
   715 
   716 		void *CSourceHookImpl::GetOrigVfnPtrEntry(void *vfnptr)
   717 		{
   718 			for (CVfnPtrList::iterator vfnptr_iter = m_VfnPtrs.begin(); vfnptr_iter != m_VfnPtrs.end(); ++vfnptr_iter)
   719 			{
   720 				if (vfnptr_iter->GetPtr() == vfnptr)
   721 					return vfnptr_iter->GetOrigEntry();
   722 			}
   723 			return NULL;
   724 		}
   725 
   726 		void CSourceHookImpl::DoRecall()
   727 		{
   728 			CHookContext newCtx;
   729 			CHookContext &curCtx = m_ContextStack.front();
   730 
   731 
   732 			newCtx.m_State = curCtx.m_State + (CHookContext::State_Recall_Pre - CHookContext::State_Pre);
   733 			if (newCtx.m_State == CHookContext::State_Recall_Post || newCtx.m_State == CHookContext::State_Recall_PostVP)
   734 			{
   735 				// Also save orig ret
   736 				newCtx.pOrigRet = curCtx.pOrigRet;
   737 			}
   738 
   739 			// The hookfunc usually does this, but it won't have a chance to see it, 
   740 			// so for recalls, we update status here if it's required
   741 			if (*curCtx.pCurRes > *curCtx.pStatus) 
   742 				*curCtx.pStatus = *curCtx.pCurRes;
   743 
   744 			newCtx.pStatus = curCtx.pStatus;
   745 			newCtx.pOverrideRet = curCtx.pOverrideRet;
   746 			newCtx.pPrevRes = curCtx.pPrevRes;
   747 			newCtx.m_Iter = curCtx.m_Iter;
   748 
   749 			// Take this with us!
   750 			newCtx.pCurRes = curCtx.pCurRes;
   751 
   752 			m_ContextStack.push(newCtx);
   753 			curCtx.m_State = CHookContext::State_Dead;
   754 		}
   755 
   756 		IHookContext *CSourceHookImpl::SetupHookLoop(IHookManagerInfo *hi, void *vfnptr, void *thisptr, void **origentry, META_RES *statusPtr,
   757 			META_RES *prevResPtr, META_RES *curResPtr, const void *origRetPtr, void *overrideRetPtr)
   758 		{
   759 			CHookContext *pCtx = NULL;
   760 			CHookContext *oldctx = m_ContextStack.empty() ? NULL : &m_ContextStack.front();
   761 			if (oldctx)
   762 			{
   763 				// SH_CALL
   764 				if (oldctx->m_State == CHookContext::State_Ignore)
   765 				{
   766 					*statusPtr = MRES_IGNORED;
   767 					oldctx->m_CallOrig = true;
   768 					oldctx->m_State = CHookContext::State_Dead;
   769 
   770 					List<CVfnPtr*> &vfnptr_list = static_cast<CHookManager*>(hi)->GetVfnPtrList();
   771 					List<CVfnPtr*>::iterator vfnptr_iter;
   772 					for (vfnptr_iter = vfnptr_list.begin();
   773 						vfnptr_iter != vfnptr_list.end(); ++vfnptr_iter)
   774 					{
   775 						if (**vfnptr_iter == vfnptr)
   776 							break;
   777 					}
   778 					if (vfnptr_iter == vfnptr_list.end())
   779 					{
   780 						SH_ASSERT(false, ("How can a hook exist on a vfnptr which we don't have in our db?!"));
   781 					}
   782 					else
   783 					{
   784 						*origentry = (*vfnptr_iter)->GetOrigEntry();
   785 					}
   786 
   787 					oldctx->pOrigRet = origRetPtr;
   788 					return oldctx;
   789 				}
   790 				// Recall
   791 				else if (oldctx->m_State >= CHookContext::State_Recall_Pre &&
   792 					oldctx->m_State <= CHookContext::State_Recall_PostVP)
   793 				{
   794 					pCtx = oldctx;
   795 
   796 					*statusPtr = *(oldctx->pStatus);
   797 					*prevResPtr = *(oldctx->pPrevRes);
   798 
   799 					pCtx->m_Iter = oldctx->m_Iter;
   800 
   801 					// Only have possibility of calling the orig func in pre recall mode
   802 					pCtx->m_CallOrig = (oldctx->m_State == CHookContext::State_Recall_Pre || 
   803 						oldctx->m_State == CHookContext::State_Recall_PreVP);
   804 
   805 					overrideRetPtr = pCtx->pOverrideRet;
   806 
   807 					// When the status is low so there's no override return value and we're in a post recall,
   808 					// give it the orig return value as override return value.
   809 					if (pCtx->m_State == CHookContext::State_Recall_Post ||
   810 						pCtx->m_State == CHookContext::State_Recall_PostVP)
   811 					{
   812 						origRetPtr = oldctx->pOrigRet;
   813 						if (*statusPtr < MRES_OVERRIDE)
   814 							overrideRetPtr = const_cast<void*>(pCtx->pOrigRet);
   815 					}
   816 				}
   817 			}
   818 			if (!pCtx)
   819 			{
   820 				pCtx = m_ContextStack.make_next();
   821 				pCtx->m_State = CHookContext::State_Born;
   822 				pCtx->m_CallOrig = true;
   823 			}
   824 
   825 			pCtx->pIface = NULL;
   826 
   827 			List<CVfnPtr*> &vfnptr_list = static_cast<CHookManager*>(hi)->GetVfnPtrList();
   828 			List<CVfnPtr*>::iterator vfnptr_iter; 
   829 			for (vfnptr_iter = vfnptr_list.begin();
   830 				vfnptr_iter != vfnptr_list.end(); ++vfnptr_iter)
   831 			{
   832 				if (**vfnptr_iter == vfnptr)
   833 					break;
   834 			}
   835 			if (vfnptr_iter == vfnptr_list.end())
   836 			{
   837 				pCtx->m_State = CHookContext::State_Dead;
   838 			}
   839 			else
   840 			{
   841 				pCtx->pVfnPtr = *vfnptr_iter;
   842 				*origentry = pCtx->pVfnPtr->GetOrigEntry();
   843 				pCtx->pIface = pCtx->pVfnPtr->FindIface(thisptr);
   844 			}
   845 
   846 			pCtx->pStatus = statusPtr;
   847 			pCtx->pPrevRes = prevResPtr;
   848 			pCtx->pCurRes = curResPtr;
   849 			pCtx->pThisPtr = thisptr;
   850 			pCtx->pOverrideRet = overrideRetPtr;
   851 			pCtx->pOrigRet = origRetPtr;
   852 
   853 			return pCtx;
   854 		}
   855 
   856 		void CSourceHookImpl::EndContext(IHookContext *pCtx)
   857 		{
   858 			m_ContextStack.pop();
   859 		}
   860 
   861 		void CSourceHookImpl::CompleteShutdown()
   862 		{
   863 			CVector<int> removehooks;
   864 			m_HookIDMan.FindAllHooks(removehooks);
   865 
   866 			for (CVector<int>::iterator iter = removehooks.begin(); iter != removehooks.end(); ++iter)
   867 				RemoveHookByID(*iter);
   868 		}
   869 
   870 		void CSourceHookImpl::PausePlugin(Plugin plug)
   871 		{
   872 			CVector<int> pausehooks;
   873 			m_HookIDMan.FindAllHooks(pausehooks, plug);
   874 
   875 			for (CVector<int>::iterator iter = pausehooks.begin(); iter != pausehooks.end(); ++iter)
   876 				PauseHookByID(*iter);
   877 		}
   878 
   879 		void CSourceHookImpl::UnpausePlugin(Plugin plug)
   880 		{
   881 			CVector<int> unpausehooks;
   882 			m_HookIDMan.FindAllHooks(unpausehooks, plug);
   883 
   884 			for (CVector<int>::iterator iter = unpausehooks.begin(); iter != unpausehooks.end(); ++iter)
   885 				UnpauseHookByID(*iter);
   886 		}
   887 
   888 		bool CSourceHookImpl::PauseHookByID(int hookid)
   889 		{
   890 			return SetHookPaused(hookid, true);
   891 		}
   892 
   893 		bool CSourceHookImpl::UnpauseHookByID(int hookid)
   894 		{
   895 			return SetHookPaused(hookid, false);
   896 		}
   897 
   898 		bool CSourceHookImpl::SetHookPaused(int hookid, bool paused)
   899 		{
   900 			const CHookIDManager::Entry *hentry;
   901 
   902 			hentry = m_HookIDMan.QueryHook(hookid);
   903 			if (!hentry)
   904 			{
   905 				// hookid doesn't exist !
   906 				return false;
   907 			}
   908 
   909 			// find vfnptr
   910 			List<CVfnPtr>::iterator vfnptr_iter = m_VfnPtrs.find(hentry->vfnptr);
   911 			if (vfnptr_iter == m_VfnPtrs.end())
   912 				return false;
   913 
   914 			// find iface
   915 			List<CIface>::iterator iface_iter = vfnptr_iter->GetIfaceList().find(hentry->adjustediface);
   916 			if (iface_iter == vfnptr_iter->GetIfaceList().end())
   917 				return false;
   918 
   919 			// find hook
   920 			List<CHook> &hooks = hentry->post ? iface_iter->GetPostHookList() : iface_iter->GetPreHookList();
   921 			List<CHook>::iterator hook_iter = hooks.find(hookid);
   922 			if (hook_iter == hooks.end())
   923 				return false;
   924 
   925 			hook_iter->SetPaused(paused);
   926 			return true;
   927 		}
   928 
   929 		//////////////////////////////////////////////////////////////////////////
   930 		// CHookContext
   931 		//////////////////////////////////////////////////////////////////////////
   932 		ISHDelegate *CHookContext::GetNext()
   933 		{
   934 			CIface *pVPIface;
   935 			switch (m_State)
   936 			{
   937 			case State_Dead:
   938 				return NULL;
   939 
   940 			case State_Born:
   941 				m_Iter = List<CHook>::iterator();
   942 				m_State = State_Pre;
   943 
   944 				// fall-through
   945 			case State_Recall_Pre:
   946 				m_State = State_Pre;
   947 			case State_Pre:
   948 				if (pIface)
   949 				{
   950 					if (!m_Iter)
   951 						m_Iter = pIface->GetPreHookList().begin();
   952 					else
   953 						++m_Iter;
   954 					SkipPaused(m_Iter, pIface->GetPreHookList());
   955 
   956 					if (m_Iter != pIface->GetPreHookList().end())
   957 					{
   958 						pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
   959 						return m_Iter->GetHandler();
   960 					}
   961 				}
   962 
   963 				// end of normal hooks -> VP
   964 				
   965 				m_State = State_PreVP;
   966 				m_Iter = List<CHook>::iterator();
   967 
   968 				// fall-through
   969 			case State_Recall_PreVP:
   970 				m_State = State_PreVP;
   971 			case State_PreVP:
   972 				pVPIface = pVfnPtr->FindIface(NULL);
   973 				if (pVPIface)
   974 				{
   975 					if (!m_Iter)
   976 						m_Iter = pVPIface->GetPreHookList().begin();
   977 					else
   978 						++m_Iter;
   979 					SkipPaused(m_Iter, pVPIface->GetPreHookList());
   980 
   981 					if (m_Iter != pVPIface->GetPreHookList())
   982 					{
   983 						pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
   984 						return m_Iter->GetHandler();
   985 					}
   986 				}
   987 
   988 				// end VP hooks -> orig call
   989 
   990 				m_State = State_OrigCall;
   991 				return NULL;
   992 				
   993 			case State_OrigCall:
   994 				m_Iter = List<CHook>::iterator();
   995 				m_State = State_Post;
   996 
   997 				// fall-through
   998 			case State_Post:
   999 				if (pIface)
  1000 				{
  1001 					if (!m_Iter)
  1002 						m_Iter = pIface->GetPostHookList().begin();
  1003 					else
  1004 						++m_Iter;
  1005 					SkipPaused(m_Iter, pIface->GetPostHookList());
  1006 
  1007 					if (m_Iter != pIface->GetPostHookList().end())
  1008 					{
  1009 						pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
  1010 						return m_Iter->GetHandler();
  1011 					}
  1012 				}
  1013 				// end of normal hooks -> VP
  1014 
  1015 				m_State = State_PostVP;
  1016 				m_Iter = List<CHook>::iterator();
  1017 
  1018 				// fall-through
  1019 			case State_PostVP:
  1020 				pVPIface = pVfnPtr->FindIface(NULL);
  1021 				if (pVPIface)
  1022 				{
  1023 					if (!m_Iter)
  1024 						m_Iter = pVPIface->GetPostHookList().begin();
  1025 					else
  1026 						++m_Iter;
  1027 					SkipPaused(m_Iter, pVPIface->GetPostHookList());
  1028 
  1029 					if (m_Iter != pVPIface->GetPostHookList())
  1030 					{
  1031 						pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
  1032 						return m_Iter->GetHandler();
  1033 					}
  1034 				}
  1035 
  1036 				// end VP hooks -> done
  1037 
  1038 				m_State = State_Dead;
  1039 				return NULL;
  1040 
  1041 			case State_Recall_Post:
  1042 				// Skip pre hooks _and_ orig call
  1043 				m_State = State_Post;
  1044 				return NULL;
  1045 
  1046 			case State_Recall_PostVP:
  1047 				// Skip pre hooks _and_ orig call
  1048 				m_State = State_PostVP;
  1049 				return NULL;
  1050 			}
  1051 			return NULL;
  1052 		}
  1053 
  1054 		void *CHookContext::GetOverrideRetPtr()
  1055 		{
  1056 			return pOverrideRet;
  1057 		}
  1058 
  1059 		const void *CHookContext::GetOrigRetPtr()
  1060 		{
  1061 			return pOrigRet;
  1062 		}
  1063 
  1064 		bool CHookContext::ShouldCallOrig()
  1065 		{
  1066 			return m_CallOrig;
  1067 		}
  1068 
  1069 		void CHookContext::HookRemoved(List<CHook>::iterator oldhookiter, List<CHook>::iterator nexthookiter)
  1070 		{
  1071 			if (m_Iter == oldhookiter)
  1072 			{
  1073 				m_Iter = nexthookiter;
  1074 				--m_Iter;
  1075 			}
  1076 		}
  1077 
  1078 		void CHookContext::IfaceRemoved(CIface *iface)
  1079 		{
  1080 			if (pIface == iface)
  1081 				pIface = NULL;
  1082 		}
  1083 
  1084 		void CHookContext::VfnPtrRemoved(CVfnPtr *vfnptr)
  1085 		{
  1086 			if (pVfnPtr == vfnptr)
  1087 			{
  1088 				pVfnPtr = NULL;
  1089 				m_State = State_Dead;
  1090 			}
  1091 		}
  1092 	}
  1093 }