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