core/sourcehook/sourcehook.cpp
author David Anderson <dvander@alliedmods.net>
Mon Nov 18 09:46:46 2013 -0800 (2013-11-18)
changeset 870 004b1437bd14
parent 768 e6394d70ced0
permissions -rw-r--r--
Upgrade build scripts to AMBuild 2 (bug 5970, r=ds).
     1 /* ======== SourceHook ========
     2 * vim: set ts=4 sw=4 tw=99 noet:
     3 * Copyright (C) 2004-2010 Metamod:Source Development Team
     4 * No warranties of any kind
     5 *
     6 * License: zlib/libpng
     7 *
     8 * Author(s): Pavol "PM OnoTo" Marko
     9 * Contributors: Scott "Damaged Soul" Ehlert
    10 * ============================
    11 */
    12 
    13 /**
    14  * @file sourcehook.cpp
    15  * @brief Contains the implementation of the SourceHook API
    16 */
    17 
    18 #if defined __GNUC__
    19 #include <stdint.h>
    20 #endif
    21 
    22 #include "sourcehook_impl.h"
    23 
    24 namespace SourceHook
    25 {
    26 	template<>
    27 	int HashFunction<int>(const int & k)
    28 	{
    29 		return k;
    30 	}
    31 	template<>
    32 	int Compare<int>(const int & k1, const int & k2)
    33 	{
    34 		if (k1 == k2)
    35 			return 0;
    36 		if (k1 > k2)
    37 			return 1;
    38 		if (k1 < k2)
    39 			return -1;
    40 		return 0;
    41 	}
    42 
    43 	namespace Impl
    44 	{
    45 		//////////////////////////////////////////////////////////////////////////
    46 		// CVfnPtrList
    47 		//////////////////////////////////////////////////////////////////////////
    48 
    49 		CVfnPtr *CVfnPtrList::GetVfnPtr(void *vfnptr)
    50 		{
    51 			iterator iter = find(vfnptr);
    52 			if (iter == end())
    53 			{
    54 				// No vfnptr info object found
    55 				// --> create a new one
    56 				CVfnPtr newVfnPtr(vfnptr);
    57 				if (newVfnPtr.Init())
    58 				{
    59 					push_back(newVfnPtr);
    60 
    61 					return &(back());
    62 				}
    63 				else
    64 				{
    65 					// Initialization failed.
    66 					return NULL;
    67 				}
    68 			}
    69 			else
    70 			{
    71 				return &(*iter);
    72 			}
    73 		}
    74 
    75 		//////////////////////////////////////////////////////////////////////////
    76 		// CSourceHookImpl
    77 		//////////////////////////////////////////////////////////////////////////
    78 		
    79 
    80 		CSourceHookImpl::CSourceHookImpl()
    81 		{
    82 		}
    83 		CSourceHookImpl::~CSourceHookImpl()
    84 		{
    85 			CompleteShutdown();
    86 		}
    87 
    88 		int CSourceHookImpl::GetIfaceVersion()
    89 		{
    90 			return SH_IFACE_VERSION;
    91 		}
    92 
    93 		int CSourceHookImpl::GetImplVersion()
    94 		{
    95 			return SH_IMPL_VERSION;
    96 		}
    97 
    98 		int CSourceHookImpl::AddHook(Plugin plug, AddHookMode mode, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan,
    99 			ISHDelegate *handler, bool post)
   100 		{
   101 			if (mode != Hook_Normal && mode != Hook_VP && mode != Hook_DVP)
   102 				return 0;
   103 
   104 			// Get info about hook manager
   105 			CHookManager hookManager(plug, myHookMan);
   106 			if (!hookManager)
   107 				return 0;
   108 
   109 			void *adjustediface = NULL;
   110 			void **cur_vtptr = NULL;
   111 			void *cur_vfnptr = NULL;
   112 
   113 			// find vfnptr
   114 			switch (mode)
   115 			{
   116 			case Hook_Normal:
   117 				adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface) + thisptr_offs);
   118 
   119 				cur_vtptr = *reinterpret_cast<void***>(
   120 					reinterpret_cast<char*>(adjustediface) + hookManager.GetVtblOffs());
   121 				cur_vfnptr = reinterpret_cast<void*>(cur_vtptr + hookManager.GetVtblIdx());
   122 				break;
   123 
   124 			case Hook_VP:
   125 
   126 				adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface) + thisptr_offs);
   127 
   128 				cur_vtptr = *reinterpret_cast<void***>(
   129 					reinterpret_cast<char*>(adjustediface) + hookManager.GetVtblOffs());
   130 				cur_vfnptr = reinterpret_cast<void*>(cur_vtptr + hookManager.GetVtblIdx());
   131 
   132 				adjustediface = NULL;
   133 				break;
   134 
   135 			case Hook_DVP:
   136 				adjustediface = NULL;
   137 
   138 				cur_vtptr = reinterpret_cast<void**>(iface);
   139 				cur_vfnptr = cur_vtptr + hookManager.GetVtblIdx();
   140 
   141 				break;
   142 			}
   143 
   144 			CVfnPtr *vfnPtr = m_VfnPtrs.GetVfnPtr(cur_vfnptr);
   145 			if (!vfnPtr)
   146 			{
   147 				// Could not create the vfnptr info object.
   148 				// This could be because a thunk generation on GCC
   149 				// has failed. See sourcehook_impl_cvfnptr.cpp
   150 				// for details.
   151 				return false;
   152 			}
   153 
   154 			vfnPtr->AddHookMan(m_HookManList.GetHookMan(hookManager));
   155 			CIface &ifaceinst = vfnPtr->GetIface(adjustediface);
   156 
   157 			// Add the hook
   158 			CHook hook(plug, thisptr_offs, handler, 
   159 
   160 				m_HookIDMan.New(hookManager.GetProto(), hookManager.GetVtblOffs(), hookManager.GetVtblIdx(),
   161 					cur_vfnptr, adjustediface, plug, thisptr_offs, handler, post)
   162 
   163 				);
   164 
   165 			if (post)
   166 				ifaceinst.GetPostHookList().push_back(hook);
   167 			else
   168 				ifaceinst.GetPreHookList().push_back(hook);
   169 
   170 			return hook.GetID();
   171 		}
   172 
   173 		bool CSourceHookImpl::RemoveHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan,
   174 			ISHDelegate *handler, bool post)
   175 		{
   176 			// Get info about hook manager and compute adjustediface
   177 			CHookManager tmpHookMan(plug, myHookMan);
   178 
   179 			void *adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface)+thisptr_offs);
   180 
   181 			// Loop through all hooks and remove those which match:
   182 			//  hookman, vfnptr, iface, plug, adjusted iface, this ptr offs, handler, post
   183 			CVector<int> removehooks;
   184 			m_HookIDMan.FindAllHooks(removehooks, tmpHookMan.GetProto(), tmpHookMan.GetVtblOffs(), tmpHookMan.GetVtblIdx(),
   185 				adjustediface, plug, thisptr_offs, handler, post);
   186 
   187 			if (removehooks.empty())
   188 				return false;
   189 
   190 			bool status = false;
   191 
   192 			for (CVector<int>::iterator iter = removehooks.begin(); iter != removehooks.end(); ++iter)
   193 			{
   194 				if (RemoveHookByID(*iter))
   195 					status = true;
   196 			}
   197 			return status; 
   198 		}
   199 
   200 		bool CSourceHookImpl::RemoveHookByID(int hookid)
   201 		{
   202 			const CHookIDManager::Entry *hentry;
   203 
   204 			hentry = m_HookIDMan.QueryHook(hookid);
   205 			if (!hentry)
   206 			{
   207 				// hookid doesn't exist !
   208 				return false;
   209 			}
   210 
   211 			// find vfnptr
   212 			List<CVfnPtr>::iterator vfnptr_iter = m_VfnPtrs.find(hentry->vfnptr);
   213 			if (vfnptr_iter == m_VfnPtrs.end())
   214 				return false;
   215 
   216 			// find iface
   217 			List<CIface>::iterator iface_iter = vfnptr_iter->GetIfaceList().find(hentry->adjustediface);
   218 			if (iface_iter == vfnptr_iter->GetIfaceList().end())
   219 				return false;
   220 
   221 			// find hook
   222 			List<CHook> &hooks = hentry->post ? iface_iter->GetPostHookList() : iface_iter->GetPreHookList();
   223 			List<CHook>::iterator hook_iter = hooks.find(hookid);
   224 			if (hook_iter == hooks.end())
   225 				return false;
   226 
   227 			hook_iter->GetHandler()->DeleteThis();
   228 
   229 			// Iterator movage!
   230 			List<CHook>::iterator oldhookiter = hook_iter;
   231 			hook_iter = hooks.erase(hook_iter);
   232 
   233 			for (CStack<CHookContext>::iterator ctx_iter = m_ContextStack.begin();
   234 				ctx_iter != m_ContextStack.end(); ++ctx_iter)
   235 			{
   236 				ctx_iter->HookRemoved(oldhookiter, hook_iter);
   237 			}
   238 
   239 			if (iface_iter->GetPreHookList().empty() && iface_iter->GetPostHookList().empty())
   240 			{
   241 				// -> Kill all contexts that use it!
   242 				for (CStack<CHookContext>::iterator ctx_iter = m_ContextStack.begin();
   243 					ctx_iter != m_ContextStack.end(); ++ctx_iter)
   244 				{
   245 					ctx_iter->IfaceRemoved(&(*iface_iter));
   246 				}
   247 
   248 				// There are no hooks on this iface anymore...
   249 				iface_iter = vfnptr_iter->GetIfaceList().erase(iface_iter);
   250 
   251 				if (vfnptr_iter->GetIfaceList().empty())
   252 				{
   253 					// No ifaces at all -> Deactivate the hook
   254 
   255 					for (CStack<CHookContext>::iterator ctx_iter = m_ContextStack.begin();
   256 						ctx_iter != m_ContextStack.end(); ++ctx_iter)
   257 					{
   258 						ctx_iter->VfnPtrRemoved(&(*vfnptr_iter));
   259 					}
   260 
   261 					RevertAndRemoveVfnPtr(vfnptr_iter);
   262 				}
   263 			}
   264 
   265 			m_HookIDMan.Remove(hookid);
   266 			return true;
   267 		}
   268 
   269 		List<CVfnPtr>::iterator CSourceHookImpl::RevertAndRemoveVfnPtr(List<CVfnPtr>::iterator vfnptr_iter)
   270 		{
   271 			ICleanupTask *cleanupTask = vfnptr_iter->GetCleanupTask();
   272 
   273 			// Some vfnptrs require cleanup.
   274 			// Concrete case: on GCC, when the original vtable entry is not even
   275 			// we generate an even-aligned thunk to call the original function.
   276 			// If the vfnptr is being removed from a pre hook on the vfnptr
   277 			// we have to delay the cleanup of this thunk until the hook loop is done
   278 			// (because the orig function call mechanism is going to use the thunk).
   279 
   280 			if (cleanupTask != NULL)
   281 			{
   282 				// If this vfnptr is in use in one of the hook loops running at the moment
   283 				// Schedule it for removal on the DEEPEST hook loop.
   284 
   285 				size_t numOfContexts = m_ContextStack.size();
   286 				// m_ContextStack.at(0) is the deepest hook context
   287 				// m_ContextStack.at(size-1) = m_ContextStack.front is the uppermost
   288 
   289 				bool cleanupImmedieately = true;
   290 
   291 				CVfnPtr *vfnPtrObjAddr = &(*vfnptr_iter);
   292 				for (size_t i = 0; i < numOfContexts; ++i)
   293 				{
   294 					CHookContext &context = m_ContextStack.at(i);
   295 					if (context.pVfnPtr == vfnPtrObjAddr)
   296 					{
   297 						// Found a hook context using this vfnptr at the moment.
   298 						context.m_CleanupTask = cleanupTask;
   299 						cleanupImmedieately = false;			// Delay the cleanup
   300 						break;
   301 					}
   302 				}
   303 
   304 				if (cleanupImmedieately)
   305 				{
   306 					cleanupTask->CleanupAndDeleteThis();
   307 				}
   308 			}
   309 
   310 			// Do the work
   311 			vfnptr_iter->Revert();
   312 			return m_VfnPtrs.erase(vfnptr_iter);
   313 		}
   314 
   315 		void CSourceHookImpl::SetRes(META_RES res)
   316 		{
   317 			*m_ContextStack.front().pCurRes = res;
   318 		}
   319 
   320 		META_RES CSourceHookImpl::GetPrevRes()
   321 		{
   322 			return *m_ContextStack.front().pPrevRes;
   323 		}
   324 
   325 		META_RES CSourceHookImpl::GetStatus()
   326 		{
   327 			return *m_ContextStack.front().pStatus;
   328 
   329 		}
   330 
   331 		const void *CSourceHookImpl::GetOrigRet()
   332 		{
   333 			return m_ContextStack.front().pOrigRet;
   334 		}
   335 
   336 		const void *CSourceHookImpl::GetOverrideRet()
   337 		{
   338 			return (*m_ContextStack.front().pStatus < MRES_OVERRIDE) ?
   339 				NULL : m_ContextStack.front().pOverrideRet;
   340 		}
   341 
   342 		void *CSourceHookImpl::GetIfacePtr()
   343 		{
   344 			// If in recall: return last one
   345 			if (m_ContextStack.front().m_State >= CHookContext::State_Recall_Pre &&
   346 				m_ContextStack.front().m_State <= CHookContext::State_Recall_PostVP)
   347 			{
   348 				return m_ContextStack.second().pIfacePtr;
   349 			}
   350 			else
   351 			{
   352 				return m_ContextStack.front().pIfacePtr;
   353 			}
   354 		}
   355 
   356 		void *CSourceHookImpl::GetOverrideRetPtr()
   357 		{
   358 			return m_ContextStack.front().pOverrideRet;
   359 		}
   360 
   361 		void CSourceHookImpl::UnloadPlugin(Plugin plug, UnloadListener *listener)
   362 		{
   363 			// 1) Remove all hooks by this plugin
   364 
   365 			CVector<int> removehooks;
   366 			m_HookIDMan.FindAllHooks(removehooks, plug);
   367 
   368 			for (CVector<int>::iterator iter = removehooks.begin(); iter != removehooks.end(); ++iter)
   369 				RemoveHookByID(*iter);
   370 
   371 			// 2) Remove all hook managers
   372 			for (CHookManList::iterator iter = m_HookManList.begin(); iter != m_HookManList.end(); )
   373 			{
   374 				if (iter->GetOwnerPlugin() == plug)
   375 					iter = RemoveHookManager(iter);
   376 				else
   377 					++iter;
   378 			}
   379 
   380 			// Fix for bug 5034. It's pretty tricky to find whether hookmanagers owned by this
   381 			// plugin are active. We could change how hook managers are tracked in SH, and lazily
   382 			// free them as the context stack drops to 0, or we could change the pubfunc API to
   383 			// know whether it's active or not. Rather than deal with this extra complexity, we
   384 			// just conservatively wait until the context stack hits 0 before unloading.
   385 			if (m_ContextStack.size() == 0)
   386 			{
   387 				listener->ReadyToUnload(plug);
   388 			}
   389 			else
   390 			{
   391 				m_PendingUnloads.push_back(new PendingUnload(listener, plug));
   392 			}
   393 		}
   394 
   395 		CHookManList::iterator CSourceHookImpl::RemoveHookManager(CHookManList::iterator hookman_iter)
   396 		{
   397 			// 2) Remove it
   398 			for (CVfnPtrList::iterator vfnptr_iter = m_VfnPtrs.begin();
   399 				vfnptr_iter != m_VfnPtrs.end();)
   400 			{
   401 				if (!vfnptr_iter->HookManRemoved(&(*hookman_iter)))
   402 				{
   403 					// This vfnptr has no more hook managers
   404 					// and asks to be removed.
   405 
   406 					m_HookIDMan.RemoveAll(vfnptr_iter->GetPtr());
   407 
   408 					vfnptr_iter = RevertAndRemoveVfnPtr(vfnptr_iter);
   409 				}
   410 				else
   411 				{
   412 					++vfnptr_iter;
   413 				}
   414 			}
   415 
   416 			return m_HookManList.erase(hookman_iter);
   417 		}
   418 
   419 		void CSourceHookImpl::RemoveHookManager(Plugin plug, HookManagerPubFunc pubFunc)
   420 		{
   421 			// Find the hook manager
   422 			CHookManList::iterator hookman_iter = m_HookManList.find(CHookManager::Descriptor(plug, pubFunc));
   423 
   424 			if (hookman_iter != m_HookManList.end())
   425 			{
   426 				RemoveHookManager(hookman_iter);
   427 			}
   428 		}
   429 
   430 		void CSourceHookImpl::SetIgnoreHooks(void *vfnptr)
   431 		{
   432 			CHookContext ctx;
   433 			ctx.m_State = CHookContext::State_Ignore;
   434 			m_ContextStack.push(ctx);
   435 		}
   436 
   437 		void CSourceHookImpl::ResetIgnoreHooks(void *vfnptr)
   438 		{
   439 			if (!m_ContextStack.empty() && m_ContextStack.front().m_State == CHookContext::State_Ignore)
   440 			{
   441 				// Actually use EndContext
   442 				// instead of m_ContextStack.pop directly
   443 				// because it runs the cleanup task if neccesary
   444 				EndContext(&(m_ContextStack.front()));
   445 			}
   446 		}
   447 
   448 		void *CSourceHookImpl::GetOrigVfnPtrEntry(void *vfnptr)
   449 		{
   450 			for (CVfnPtrList::iterator vfnptr_iter = m_VfnPtrs.begin(); vfnptr_iter != m_VfnPtrs.end(); ++vfnptr_iter)
   451 			{
   452 				if (vfnptr_iter->GetPtr() == vfnptr)
   453 					return vfnptr_iter->GetOrigEntry();
   454 			}
   455 			return NULL;
   456 		}
   457 
   458 		void CSourceHookImpl::DoRecall()
   459 		{
   460 			CHookContext newCtx;
   461 			CHookContext &curCtx = m_ContextStack.front();
   462 
   463 
   464 			newCtx.m_State = curCtx.m_State + (CHookContext::State_Recall_Pre - CHookContext::State_Pre);
   465 			if (newCtx.m_State == CHookContext::State_Recall_Post || newCtx.m_State == CHookContext::State_Recall_PostVP)
   466 			{
   467 				// Also save orig ret
   468 				newCtx.pOrigRet = curCtx.pOrigRet;
   469 			}
   470 
   471 			// The hookfunc usually does this, but it won't have a chance to see it, 
   472 			// so for recalls, we update status here if it's required
   473 			if (*curCtx.pCurRes > *curCtx.pStatus) 
   474 				*curCtx.pStatus = *curCtx.pCurRes;
   475 
   476 			newCtx.pStatus = curCtx.pStatus;
   477 			newCtx.pOverrideRet = curCtx.pOverrideRet;
   478 			newCtx.pPrevRes = curCtx.pPrevRes;
   479 			newCtx.m_Iter = curCtx.m_Iter;
   480 
   481 			// Take this with us!
   482 			newCtx.pCurRes = curCtx.pCurRes;
   483 
   484 			m_ContextStack.push(newCtx);
   485 			curCtx.m_State = CHookContext::State_Dead;
   486 		}
   487 
   488 		IHookContext *CSourceHookImpl::SetupHookLoop(IHookManagerInfo *hi, void *vfnptr, void *thisptr, void **origCallAddr, META_RES *statusPtr,
   489 			META_RES *prevResPtr, META_RES *curResPtr, const void *origRetPtr, void *overrideRetPtr)
   490 		{
   491 			CHookContext *pCtx = NULL;
   492 			CHookContext *oldctx = m_ContextStack.empty() ? NULL : &m_ContextStack.front();
   493 			if (oldctx)
   494 			{
   495 				// SH_CALL
   496 				if (oldctx->m_State == CHookContext::State_Ignore)
   497 				{
   498 					*statusPtr = MRES_IGNORED;
   499 					oldctx->m_CallOrig = true;
   500 					oldctx->m_State = CHookContext::State_Dead;
   501 
   502 					List<CVfnPtr*> &vfnptr_list = static_cast<CHookManager*>(hi)->GetVfnPtrList();
   503 					List<CVfnPtr*>::iterator vfnptr_iter;
   504 					for (vfnptr_iter = vfnptr_list.begin();
   505 						vfnptr_iter != vfnptr_list.end(); ++vfnptr_iter)
   506 					{
   507 						if (**vfnptr_iter == vfnptr)
   508 							break;
   509 					}
   510 					if (vfnptr_iter == vfnptr_list.end())
   511 					{
   512 						SH_ASSERT(false, ("How can a hook exist on a vfnptr which we don't have in our db?!"));
   513 					}
   514 					else
   515 					{
   516 						*origCallAddr = (*vfnptr_iter)->GetOrigCallAddr();
   517 						oldctx->pVfnPtr = *vfnptr_iter;
   518 					}
   519 
   520 					oldctx->pOrigRet = origRetPtr;
   521 					return oldctx;
   522 				}
   523 				// Recall
   524 				else if (oldctx->m_State >= CHookContext::State_Recall_Pre &&
   525 					oldctx->m_State <= CHookContext::State_Recall_PostVP)
   526 				{
   527 					pCtx = oldctx;
   528 
   529 					*statusPtr = *(oldctx->pStatus);
   530 					*prevResPtr = *(oldctx->pPrevRes);
   531 
   532 					pCtx->m_Iter = oldctx->m_Iter;
   533 
   534 					// Only have possibility of calling the orig func in pre recall mode
   535 					pCtx->m_CallOrig = (oldctx->m_State == CHookContext::State_Recall_Pre || 
   536 						oldctx->m_State == CHookContext::State_Recall_PreVP);
   537 
   538 					overrideRetPtr = pCtx->pOverrideRet;
   539 
   540 					// When the status is low so there's no override return value and we're in a post recall,
   541 					// give it the orig return value as override return value.
   542 					if (pCtx->m_State == CHookContext::State_Recall_Post ||
   543 						pCtx->m_State == CHookContext::State_Recall_PostVP)
   544 					{
   545 						origRetPtr = oldctx->pOrigRet;
   546 						if (*statusPtr < MRES_OVERRIDE)
   547 							overrideRetPtr = const_cast<void*>(pCtx->pOrigRet);
   548 					}
   549 				}
   550 			}
   551 			if (!pCtx)
   552 			{
   553 				pCtx = m_ContextStack.make_next();
   554 				pCtx->m_State = CHookContext::State_Born;
   555 				pCtx->m_CallOrig = true;
   556 			}
   557 
   558 			pCtx->pIface = NULL;
   559 
   560 			List<CVfnPtr*> &vfnptr_list = static_cast<CHookManager*>(hi)->GetVfnPtrList();
   561 			List<CVfnPtr*>::iterator vfnptr_iter; 
   562 			for (vfnptr_iter = vfnptr_list.begin();
   563 				vfnptr_iter != vfnptr_list.end(); ++vfnptr_iter)
   564 			{
   565 				if (**vfnptr_iter == vfnptr)
   566 					break;
   567 			}
   568 			if (vfnptr_iter == vfnptr_list.end())
   569 			{
   570 				pCtx->m_State = CHookContext::State_Dead;
   571 			}
   572 			else
   573 			{
   574 				pCtx->pVfnPtr = *vfnptr_iter;
   575 				*origCallAddr = pCtx->pVfnPtr->GetOrigCallAddr();
   576 				pCtx->pIface = pCtx->pVfnPtr->FindIface(thisptr);
   577 			}
   578 
   579 			pCtx->pStatus = statusPtr;
   580 			pCtx->pPrevRes = prevResPtr;
   581 			pCtx->pCurRes = curResPtr;
   582 			pCtx->pThisPtr = thisptr;
   583 			pCtx->pOverrideRet = overrideRetPtr;
   584 			pCtx->pOrigRet = origRetPtr;
   585 
   586 			return pCtx;
   587 		}
   588 
   589 		void CSourceHookImpl::ResolvePendingUnloads(bool force)
   590 		{
   591 			List<PendingUnload *>::iterator iter = m_PendingUnloads.begin();
   592 			while (iter != m_PendingUnloads.end())
   593 			{
   594 				PendingUnload *unload = *iter;
   595 
   596 				if (!force && !unload->deactivated())
   597 				{
   598 					// Unless being forced, wait one drop of the context stack
   599 					// before actually unloading. Otherwise, we'll still return
   600 					// to unloaded memory.
   601 					unload->deactivate();
   602 					iter++;
   603 				}
   604 				else
   605 				{
   606 					unload->listener()->ReadyToUnload(unload->plugin());
   607 					delete unload;
   608 					iter = m_PendingUnloads.erase(iter);
   609 				}
   610 			}
   611 		}
   612 
   613 		void CSourceHookImpl::EndContext(IHookContext *pCtx)
   614 		{
   615 			// Do clean up task, if any is associated with this context
   616 			m_ContextStack.front().DoCleanupTaskAndDeleteIt();
   617 			// Then remove it
   618 			m_ContextStack.pop();
   619 
   620 			// If we've reached 0 contexts and there are pending unloads,
   621 			// resolve them now.
   622 			if (m_ContextStack.size() == 0 && m_PendingUnloads.size() != 0)
   623 				ResolvePendingUnloads();
   624 		}
   625 
   626 		void CSourceHookImpl::CompleteShutdown()
   627 		{
   628 			CVector<int> removehooks;
   629 			m_HookIDMan.FindAllHooks(removehooks);
   630 
   631 			for (CVector<int>::iterator iter = removehooks.begin(); iter != removehooks.end(); ++iter)
   632 				RemoveHookByID(*iter);
   633 		}
   634 
   635 		void CSourceHookImpl::PausePlugin(Plugin plug)
   636 		{
   637 			CVector<int> pausehooks;
   638 			m_HookIDMan.FindAllHooks(pausehooks, plug);
   639 
   640 			for (CVector<int>::iterator iter = pausehooks.begin(); iter != pausehooks.end(); ++iter)
   641 				PauseHookByID(*iter);
   642 		}
   643 
   644 		void CSourceHookImpl::UnpausePlugin(Plugin plug)
   645 		{
   646 			CVector<int> unpausehooks;
   647 			m_HookIDMan.FindAllHooks(unpausehooks, plug);
   648 
   649 			for (CVector<int>::iterator iter = unpausehooks.begin(); iter != unpausehooks.end(); ++iter)
   650 				UnpauseHookByID(*iter);
   651 		}
   652 
   653 		bool CSourceHookImpl::PauseHookByID(int hookid)
   654 		{
   655 			return SetHookPaused(hookid, true);
   656 		}
   657 
   658 		bool CSourceHookImpl::UnpauseHookByID(int hookid)
   659 		{
   660 			return SetHookPaused(hookid, false);
   661 		}
   662 
   663 		bool CSourceHookImpl::SetHookPaused(int hookid, bool paused)
   664 		{
   665 			const CHookIDManager::Entry *hentry;
   666 
   667 			hentry = m_HookIDMan.QueryHook(hookid);
   668 			if (!hentry)
   669 			{
   670 				// hookid doesn't exist !
   671 				return false;
   672 			}
   673 
   674 			// find vfnptr
   675 			List<CVfnPtr>::iterator vfnptr_iter = m_VfnPtrs.find(hentry->vfnptr);
   676 			if (vfnptr_iter == m_VfnPtrs.end())
   677 				return false;
   678 
   679 			// find iface
   680 			List<CIface>::iterator iface_iter = vfnptr_iter->GetIfaceList().find(hentry->adjustediface);
   681 			if (iface_iter == vfnptr_iter->GetIfaceList().end())
   682 				return false;
   683 
   684 			// find hook
   685 			List<CHook> &hooks = hentry->post ? iface_iter->GetPostHookList() : iface_iter->GetPreHookList();
   686 			List<CHook>::iterator hook_iter = hooks.find(hookid);
   687 			if (hook_iter == hooks.end())
   688 				return false;
   689 
   690 			hook_iter->SetPaused(paused);
   691 			return true;
   692 		}
   693 
   694 		//////////////////////////////////////////////////////////////////////////
   695 		// CHookContext
   696 		//////////////////////////////////////////////////////////////////////////
   697 		ISHDelegate *CHookContext::GetNext()
   698 		{
   699 			CIface *pVPIface;
   700 			switch (m_State)
   701 			{
   702 			case State_Dead:
   703 				return NULL;
   704 
   705 			case State_Born:
   706 				m_Iter = List<CHook>::iterator();
   707 				m_State = State_Pre;
   708 
   709 				// fall-through
   710 			case State_Recall_Pre:
   711 				m_State = State_Pre;
   712 			case State_Pre:
   713 				if (pIface)
   714 				{
   715 					if (!m_Iter)
   716 						m_Iter = pIface->GetPreHookList().begin();
   717 					else
   718 						++m_Iter;
   719 					SkipPaused(m_Iter, pIface->GetPreHookList());
   720 
   721 					if (m_Iter != pIface->GetPreHookList().end())
   722 					{
   723 						pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
   724 						return m_Iter->GetHandler();
   725 					}
   726 				}
   727 
   728 				// end of normal hooks -> VP
   729 				
   730 				m_State = State_PreVP;
   731 				m_Iter = List<CHook>::iterator();
   732 
   733 				// fall-through
   734 			case State_Recall_PreVP:
   735 				m_State = State_PreVP;
   736 			case State_PreVP:
   737 				pVPIface = pVfnPtr->FindIface(NULL);
   738 				if (pVPIface)
   739 				{
   740 					if (!m_Iter)
   741 						m_Iter = pVPIface->GetPreHookList().begin();
   742 					else
   743 						++m_Iter;
   744 					SkipPaused(m_Iter, pVPIface->GetPreHookList());
   745 
   746 					if (m_Iter != pVPIface->GetPreHookList())
   747 					{
   748 						pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
   749 						return m_Iter->GetHandler();
   750 					}
   751 				}
   752 
   753 				// end VP hooks -> orig call
   754 
   755 				m_State = State_OrigCall;
   756 				return NULL;
   757 				
   758 			case State_OrigCall:
   759 				m_Iter = List<CHook>::iterator();
   760 				m_State = State_Post;
   761 
   762 				// fall-through
   763 			case State_Post:
   764 				if (pIface)
   765 				{
   766 					if (!m_Iter)
   767 						m_Iter = pIface->GetPostHookList().begin();
   768 					else
   769 						++m_Iter;
   770 					SkipPaused(m_Iter, pIface->GetPostHookList());
   771 
   772 					if (m_Iter != pIface->GetPostHookList().end())
   773 					{
   774 						pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
   775 						return m_Iter->GetHandler();
   776 					}
   777 				}
   778 				// end of normal hooks -> VP
   779 
   780 				m_State = State_PostVP;
   781 				m_Iter = List<CHook>::iterator();
   782 
   783 				// fall-through
   784 			case State_PostVP:
   785 				pVPIface = pVfnPtr->FindIface(NULL);
   786 				if (pVPIface)
   787 				{
   788 					if (!m_Iter)
   789 						m_Iter = pVPIface->GetPostHookList().begin();
   790 					else
   791 						++m_Iter;
   792 					SkipPaused(m_Iter, pVPIface->GetPostHookList());
   793 
   794 					if (m_Iter != pVPIface->GetPostHookList())
   795 					{
   796 						pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
   797 						return m_Iter->GetHandler();
   798 					}
   799 				}
   800 
   801 				// end VP hooks -> done
   802 
   803 				m_State = State_Dead;
   804 				return NULL;
   805 
   806 			case State_Recall_Post:
   807 				// Skip pre hooks _and_ orig call
   808 				m_State = State_Post;
   809 				return NULL;
   810 
   811 			case State_Recall_PostVP:
   812 				// Skip pre hooks _and_ orig call
   813 				m_State = State_PostVP;
   814 				return NULL;
   815 			}
   816 			return NULL;
   817 		}
   818 
   819 		void *CHookContext::GetOverrideRetPtr()
   820 		{
   821 			return pOverrideRet;
   822 		}
   823 
   824 		const void *CHookContext::GetOrigRetPtr()
   825 		{
   826 			return pOrigRet;
   827 		}
   828 
   829 		bool CHookContext::ShouldCallOrig()
   830 		{
   831 			return m_CallOrig;
   832 		}
   833 
   834 		void CHookContext::HookRemoved(List<CHook>::iterator oldhookiter, List<CHook>::iterator nexthookiter)
   835 		{
   836 			if (m_Iter == oldhookiter)
   837 			{
   838 				m_Iter = nexthookiter;
   839 				--m_Iter;
   840 			}
   841 		}
   842 
   843 		void CHookContext::IfaceRemoved(CIface *iface)
   844 		{
   845 			if (pIface == iface)
   846 				pIface = NULL;
   847 		}
   848 
   849 		void CHookContext::VfnPtrRemoved(CVfnPtr *vfnptr)
   850 		{
   851 			if (pVfnPtr == vfnptr)
   852 			{
   853 				// Don't set pVfnPtr = NULL here!
   854 				// It may be used still.
   855 				// RevertAndRemoveVfnPtr uses it to find the hook context
   856 				// to which to attach the cleanup task of the vfnptr.
   857 
   858 				//pVfnPtr = NULL;
   859 				m_State = State_Dead;
   860 			}
   861 		}
   862 
   863 		void CHookContext::DoCleanupTaskAndDeleteIt()
   864 		{
   865 			if (m_CleanupTask != NULL)
   866 			{
   867 				m_CleanupTask->CleanupAndDeleteThis();
   868 			}
   869 		}
   870 	}
   871 }