sourcehook/sourcehook.cpp
author Pavol Marko <pavolmarko@gmail.com>
Sun Oct 07 23:00:38 2007 +0000 (2007-10-07)
changeset 386 08583103ba6f
parent 380 f9e21a2ac558
child 387 093c72464b35
permissions -rw-r--r--
Added SH_GET_ORIG_VFNPTR_ENTRY
     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 #include "sh_memory.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 		// CProto
    47 		//////////////////////////////////////////////////////////////////////////
    48 		ProtoInfo *CProto::DupProto(const ProtoInfo *src)
    49 		{
    50 			if (src == NULL)
    51 				return NULL;
    52 
    53 			PassInfo *newParamsPassInfo = new PassInfo[src->numOfParams + 1];
    54 			for (int i = 0; i <= src->numOfParams; ++i)
    55 				newParamsPassInfo[i] = src->paramsPassInfo[i];
    56 
    57 			ProtoInfo *newProto = new ProtoInfo;
    58 			newProto->retPassInfo = src->retPassInfo;
    59 			newProto->paramsPassInfo = newParamsPassInfo;
    60 			newProto->numOfParams = src->numOfParams;
    61 			newProto->convention = src->convention;
    62 
    63 			return newProto;
    64 		}
    65 
    66 		void CProto::FreeProto(ProtoInfo *prot)
    67 		{
    68 			if (!prot)
    69 				return;
    70 
    71 			delete [] prot->paramsPassInfo;
    72 			delete prot;
    73 		}
    74 
    75 		bool CProto::Equal(const ProtoInfo *p1, const ProtoInfo *p2)
    76 		{
    77 			if (!p1 || !p2)
    78 				return false;
    79 
    80 			if (p1->numOfParams != p2->numOfParams)
    81 				return false;
    82 
    83 			if (p1->convention != ProtoInfo::CallConv_Unknown && p2->convention != ProtoInfo::CallConv_Unknown &&
    84 				p1->convention != p2->convention)
    85 				return false;
    86 
    87 			if (p1->retPassInfo.size != p2->retPassInfo.size)
    88 				return false;
    89 
    90 			// Skip params[0] : dummy
    91 			for (int i = 1; i <= p1->numOfParams; ++i)
    92 			{
    93 				if (p1->paramsPassInfo[i].size != p2->paramsPassInfo[i].size)
    94 					return false;
    95 				if (p1->paramsPassInfo[i].type != PassInfo::PassType_Unknown && p2->paramsPassInfo[i].type != PassInfo::PassType_Unknown)
    96 				{
    97 					if (p1->paramsPassInfo[i].type != p2->paramsPassInfo[i].type)
    98 						return false;
    99 					if (p1->paramsPassInfo[i].flags != p2->paramsPassInfo[i].flags)
   100 						return false;
   101 				}
   102 			}
   103 
   104 			return true;
   105 		}
   106 
   107 
   108 		//////////////////////////////////////////////////////////////////////////
   109 		// CHookManContainerList
   110 		//////////////////////////////////////////////////////////////////////////
   111 		CHookManagerContainer &CHookManContainerList::GetContainer(int vtbloffs, int vtblidx, const CProto &proto)
   112 		{
   113 			iterator iter = find(CHookManagerContainer::Descriptor(vtbloffs, vtblidx, proto));
   114 			if (iter == end())
   115 			{
   116 				CHookManagerContainer newCont(vtbloffs, vtblidx, proto);
   117 				push_back(newCont);
   118 				return back();
   119 			}
   120 			else
   121 			{
   122 				return *iter;
   123 			}
   124 		}
   125 
   126 		void CHookManContainerList::RemoveHookMans(Plugin plug)
   127 		{
   128 			for (iterator iter = begin(); iter != end(); ++iter)
   129 				iter->RemoveHookMans(plug);
   130 		}
   131 
   132 		void CHookManContainerList::RemoveHookMans(Plugin plug, HookManagerPubFunc pubFunc)
   133 		{
   134 			for (iterator iter = begin(); iter != end(); ++iter)
   135 				iter->RemoveHookMans(plug, pubFunc);
   136 		}
   137 
   138 		//////////////////////////////////////////////////////////////////////////
   139 		// CHookManagerContainer
   140 		//////////////////////////////////////////////////////////////////////////
   141 		
   142 		bool CHookManagerContainer::AddHookManager(const CHookManager &hookMan)
   143 		{
   144 			iterator iter;
   145 
   146 			// Don't accept invalid hook managers
   147 			if (!hookMan)
   148 				return false;
   149 
   150 			// Check whether such a hook manager already exists; if yes, ignore.
   151 			iter = find(hookMan);
   152 			if (iter != end())
   153 			{
   154 				// but make sure that it's activated (ms_HI stored)
   155 				iter->Register();
   156 				return true;
   157 			}
   158 
   159 			// It doesn't -> add it. Add it to the end of its version group.
   160 			for (iter = begin(); iter != end(); ++iter)
   161 			{
   162 				if (iter->GetVersion() < hookMan.GetVersion())
   163 					break;
   164 			}
   165 
   166 			bool isBeginning = iter == begin();
   167 
   168 			insert(iter, hookMan);
   169 
   170 			if (isBeginning)
   171 			{
   172 				iter = begin();
   173 
   174 				if (size() > 1)
   175 				{
   176 					// If the next hookman isn't empty (there were hooks before, but this hookman is better)
   177 					// transfer its vfnptrs and deactivate it
   178 
   179 					iterator second = iter;
   180 					++second;
   181 
   182 					if (!second->GetVfnPtrList().empty())
   183 					{
   184 						// Move the vfnptrs from the old hook manager to the new one
   185 						iter->GetVfnPtrList() = second->GetVfnPtrList();
   186 						second->GetVfnPtrList().clear();
   187 
   188 						// Unregister the old one, register the new one
   189 						second->Unregister();
   190 
   191 						// Go through all vfnptrs in this hookman and patch them to point to the new manager's handler!
   192 						// :TODO: change this to something like for_all :X
   193 						for (List<CVfnPtr>::iterator vfnptr_iter = iter->GetVfnPtrList().begin();
   194 							vfnptr_iter != iter->GetVfnPtrList().end(); ++vfnptr_iter)
   195 						{
   196 							vfnptr_iter->Patch(iter->GetHookFunc());
   197 						}
   198 					}
   199 				}
   200 
   201 				// activate the new active hookman
   202 				iter->Register();
   203 			}
   204 			
   205 			return true;
   206 		}
   207 
   208 		void CHookManagerContainer::RemoveHookMans(Plugin plug, HookManagerPubFunc pubFunc)
   209 		{
   210 			bool erasethis = false;
   211 
   212 			for (iterator iter = begin(); iter != end(); erasethis ? (iter = erase(iter)) : ++iter)
   213 			{
   214 				erasethis = false;
   215 				if (iter->GetOwnerPlugin() == plug
   216 					&& (pubFunc == NULL ? true : (iter->GetPubFunc() == pubFunc)))
   217 				{
   218 					if (iter == begin() && !iter->GetVfnPtrList().empty())
   219 					{
   220 						// The hook manager is active
   221 						// -> Transfer its hooks to the next hook manager (which _has_ to exist)
   222 						SH_ASSERT(size() > 1, ("No more hook managers!?"));
   223 
   224 						iterator second = iter;
   225 						++second;
   226 
   227 						SH_ASSERT(second->GetOwnerPlugin() != plug, ("New hook manager from same plugin!"));
   228 
   229 						second->GetVfnPtrList() = iter->GetVfnPtrList();
   230 						iter->GetVfnPtrList().clear();
   231 
   232 						second->Register();
   233 						iter->Unregister();
   234 
   235 						// Go through all vfnptrs in this hookman and patch them to point to the new manager's handler!
   236 						// :TODO: change this to something like for_all :X
   237 						for (List<CVfnPtr>::iterator vfnptr_iter = second->GetVfnPtrList().begin();
   238 							vfnptr_iter != second->GetVfnPtrList().end(); ++vfnptr_iter)
   239 						{
   240 							vfnptr_iter->Patch(second->GetHookFunc());
   241 						}
   242 					}
   243 					erasethis = true;
   244 				}
   245 			}
   246 		}
   247 		
   248 		//////////////////////////////////////////////////////////////////////////
   249 		// CHookManager
   250 		//////////////////////////////////////////////////////////////////////////
   251 		void CHookManager::SetInfo(int hookman_version, int vtbloffs, int vtblidx,
   252 			ProtoInfo *proto, void *hookfunc_vfnptr)
   253 		{
   254 			m_Version = hookman_version;
   255 			m_VtblOffs = vtbloffs;
   256 			m_VtblIdx = vtblidx;
   257 			m_Proto = proto;
   258 			m_HookfuncVfnptr = hookfunc_vfnptr;
   259 		}
   260 
   261 		CVfnPtr &CHookManager::GetVfnPtr(void *vfnptr)
   262 		{
   263 			List<CVfnPtr>::iterator iter = m_VfnPtrList.find(vfnptr);
   264 			if (iter == m_VfnPtrList.end())
   265 			{
   266 				CVfnPtr newVfnPtr(vfnptr);
   267 				m_VfnPtrList.push_back(newVfnPtr);
   268 
   269 				newVfnPtr.Patch(GetHookFunc());
   270 
   271 				return m_VfnPtrList.back();
   272 			}
   273 			else
   274 			{
   275 				return *iter;
   276 			}
   277 		}
   278 
   279 		//////////////////////////////////////////////////////////////////////////
   280 		// CVfnPtr
   281 		//////////////////////////////////////////////////////////////////////////
   282 		
   283 		bool CVfnPtr::Patch(void *newValue)
   284 		{
   285 			if (!SetMemAccess(m_Ptr, sizeof(void*), SH_MEM_READ | SH_MEM_WRITE))
   286 				return false;
   287 
   288 			*reinterpret_cast<void**>(m_Ptr) = newValue;
   289 
   290 			return true;
   291 		}
   292 
   293 		CIface &CVfnPtr::GetIface(void *iface)
   294 		{
   295 			List<CIface>::iterator iter = m_IfaceList.find(iface);
   296 			if (iter == m_IfaceList.end())
   297 			{
   298 				CIface newIface(iface);
   299 				if (iface == NULL)
   300 				{
   301 					m_IfaceList.push_front(newIface);
   302 					return m_IfaceList.front();
   303 				}
   304 				else
   305 				{
   306 					m_IfaceList.push_back(newIface);
   307 					return m_IfaceList.back();
   308 				}
   309 			}
   310 			else
   311 			{
   312 				return *iter;
   313 			}
   314 		}
   315 
   316 		//////////////////////////////////////////////////////////////////////////
   317 		// CHookIdManager
   318 		//////////////////////////////////////////////////////////////////////////
   319 		CHookIDManager::CHookIDManager()
   320 		{
   321 		}
   322 
   323 		int CHookIDManager::New(const CProto &proto, int vtbl_offs, int vtbl_idx, void *vfnptr,
   324 			void *adjustediface, Plugin plug, int thisptr_offs, ISHDelegate *handler, bool post)
   325 		{
   326 			Entry tmp(proto, vtbl_offs, vtbl_idx, vfnptr, adjustediface, plug, thisptr_offs, handler, post);
   327 
   328 			size_t cursize = m_Entries.size();
   329 			for (size_t i = 0; i < cursize; ++i)
   330 			{
   331 				if (m_Entries[i].isfree)
   332 				{
   333 					m_Entries[i] = tmp;
   334 					return static_cast<int>(i) + 1;
   335 				}
   336 			}
   337 
   338 			m_Entries.push_back(tmp);
   339 			return static_cast<int>(m_Entries.size());		// return size() because hookid = id+1 anyway
   340 		}
   341 
   342 		bool CHookIDManager::Remove(int hookid)
   343 		{
   344 			int realid = hookid - 1;
   345 			if (realid < 0 || realid >= static_cast<int>(m_Entries.size()) || m_Entries[realid].isfree)
   346 				return false;
   347 
   348 			m_Entries[realid].isfree = true;
   349 
   350 			// :TODO: remove free ids from back sometimes ??
   351 
   352 			return true;
   353 		}
   354 
   355 		const CHookIDManager::Entry * CHookIDManager::QueryHook(int hookid)
   356 		{
   357 			int realid = hookid - 1;
   358 			if (realid < 0 || realid >= static_cast<int>(m_Entries.size()) || m_Entries[realid].isfree)
   359 				return NULL;
   360 
   361 			return &m_Entries[realid];
   362 		}
   363 
   364 		void CHookIDManager::FindAllHooks(CVector<int> &output, const CProto &proto, int vtbl_offs,
   365 			int vtbl_idx, void *adjustediface, Plugin plug, int thisptr_offs, ISHDelegate *handler, bool post)
   366 		{
   367 			// oh my god, a lot of parameters...
   368 			size_t cursize = m_Entries.size();
   369 			for (size_t i = 0; i < cursize; ++i)
   370 			{
   371 				if (!m_Entries[i].isfree && m_Entries[i].proto == proto && m_Entries[i].vtbl_offs == vtbl_offs &&
   372 					m_Entries[i].vtbl_idx == vtbl_idx && m_Entries[i].adjustediface == adjustediface && m_Entries[i].plug == plug &&
   373 					m_Entries[i].thisptr_offs == thisptr_offs && m_Entries[i].handler->IsEqual(handler) && m_Entries[i].post == post)
   374 				{
   375 					output.push_back(static_cast<int>(i) + 1);
   376 				}
   377 			}
   378 		}
   379 
   380 		void CHookIDManager::FindAllHooks(CVector<int> &output)
   381 		{
   382 			size_t cursize = m_Entries.size();
   383 			for (size_t i = 0; i < cursize; ++i)
   384 			{
   385 				if (!m_Entries[i].isfree)
   386 					output.push_back(static_cast<int>(i) + 1);
   387 			}
   388 		}
   389 
   390 		void CHookIDManager::FindAllHooks(CVector<int> &output, Plugin plug)
   391 		{
   392 			size_t cursize = m_Entries.size();
   393 			for (size_t i = 0; i < cursize; ++i)
   394 			{
   395 				if (!m_Entries[i].isfree && m_Entries[i].plug == plug)
   396 					output.push_back(static_cast<int>(i) + 1);
   397 			}
   398 		}
   399 
   400 
   401 		//////////////////////////////////////////////////////////////////////////
   402 		// CSourceHookImpl
   403 		//////////////////////////////////////////////////////////////////////////
   404 		
   405 
   406 		CSourceHookImpl::CSourceHookImpl()
   407 		{
   408 		}
   409 		CSourceHookImpl::~CSourceHookImpl()
   410 		{
   411 		}
   412 
   413 		int CSourceHookImpl::GetIfaceVersion()
   414 		{
   415 			return SH_IFACE_VERSION;
   416 		}
   417 
   418 		int CSourceHookImpl::GetImplVersion()
   419 		{
   420 			return SH_IMPL_VERSION;
   421 		}
   422 
   423 		int CSourceHookImpl::AddHook(Plugin plug, AddHookMode mode, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan,
   424 			ISHDelegate *handler, bool post)
   425 		{
   426 			if (mode != Hook_Normal && mode != Hook_VP && mode != Hook_DVP)
   427 				return 0;
   428 
   429 			// Get info about hook manager
   430 			CHookManager hookManager(plug, myHookMan);
   431 			if (!hookManager)
   432 				return 0;
   433 
   434 			// Make sure that the container exists
   435 			CHookManagerContainer &container = m_HookManContainers.GetContainer(hookManager.GetVtblOffs(),
   436 				hookManager.GetVtblIdx(), hookManager.GetProto());
   437 
   438 			container.AddHookManager(hookManager);
   439 
   440 			if (!container)
   441 			{
   442 				// For some weird reason, the container is empty!
   443 				SH_ASSERT(0, ("No hookman found - but we've just added one!"));
   444 				return 0;
   445 			}
   446 
   447 			CHookManager &hookMan = container.GetActiveHookManager();
   448 
   449 			void *adjustediface = NULL;
   450 			void **cur_vtptr = NULL;
   451 			void *cur_vfnptr = NULL;
   452 
   453 			// find vfnptr
   454 			switch (mode)
   455 			{
   456 			case Hook_Normal:
   457 				adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface) + thisptr_offs);
   458 
   459 				cur_vtptr = *reinterpret_cast<void***>(
   460 					reinterpret_cast<char*>(adjustediface) + hookMan.GetVtblOffs());
   461 				cur_vfnptr = reinterpret_cast<void*>(cur_vtptr + hookMan.GetVtblIdx());
   462 				break;
   463 
   464 			case Hook_VP:
   465 
   466 				adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface) + thisptr_offs);
   467 
   468 				cur_vtptr = *reinterpret_cast<void***>(
   469 					reinterpret_cast<char*>(adjustediface) + hookMan.GetVtblOffs());
   470 				cur_vfnptr = reinterpret_cast<void*>(cur_vtptr + hookMan.GetVtblIdx());
   471 
   472 				adjustediface = NULL;
   473 				break;
   474 
   475 			case Hook_DVP:
   476 				adjustediface = NULL;
   477 
   478 				cur_vtptr = reinterpret_cast<void**>(iface);
   479 				cur_vfnptr = cur_vtptr + hookMan.GetVtblIdx();
   480 
   481 				break;
   482 			}
   483 
   484 			CVfnPtr &vfnPtr = hookMan.GetVfnPtr(cur_vfnptr);
   485 			CIface &ifaceinst = vfnPtr.GetIface(adjustediface);
   486 
   487 			// Add the hook
   488 			CHook hook(plug, thisptr_offs, handler, 
   489 
   490 				m_HookIDMan.New(hookMan.GetProto(), hookMan.GetVtblOffs(), hookMan.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 hookman
   542 			CHookManContainerList::iterator hmcl_iter = m_HookManContainers.find(
   543 				CHookManagerContainer::Descriptor(hentry->vtbl_offs, hentry->vtbl_idx, hentry->proto));
   544 
   545 			if (hmcl_iter == m_HookManContainers.end() || !(*hmcl_iter))
   546 				return false;
   547 
   548 			CHookManager &hookman = hmcl_iter->GetActiveHookManager();
   549 
   550 			// find vfnptr
   551 			List<CVfnPtr>::iterator vfnptr_iter = hookman.GetVfnPtrList().find(hentry->vfnptr);
   552 			if (vfnptr_iter == hookman.GetVfnPtrList().end())
   553 				return false;
   554 
   555 			// find iface
   556 			List<CIface>::iterator iface_iter = vfnptr_iter->GetIfaceList().find(hentry->adjustediface);
   557 			if (iface_iter == vfnptr_iter->GetIfaceList().end())
   558 				return false;
   559 
   560 			// find hook
   561 			List<CHook> &hooks = hentry->post ? iface_iter->GetPostHookList() : iface_iter->GetPreHookList();
   562 			List<CHook>::iterator hook_iter = hooks.find(hookid);
   563 			if (hook_iter == hooks.end())
   564 				return false;
   565 
   566 			hook_iter->GetHandler()->DeleteThis();
   567 
   568 			// Iterator movage!
   569 			List<CHook>::iterator oldhookiter = hook_iter;
   570 			hook_iter = hooks.erase(hook_iter);
   571 
   572 			for (CStack<CHookContext>::iterator ctx_iter = m_ContextStack.begin();
   573 				ctx_iter != m_ContextStack.end(); ++ctx_iter)
   574 			{
   575 				ctx_iter->HookRemoved(oldhookiter, hook_iter);
   576 			}
   577 
   578 			if (iface_iter->GetPreHookList().empty() && iface_iter->GetPostHookList().empty())
   579 			{
   580 				// -> Kill all contexts that use it!
   581 				for (CStack<CHookContext>::iterator ctx_iter = m_ContextStack.begin();
   582 					ctx_iter != m_ContextStack.end(); ++ctx_iter)
   583 				{
   584 					ctx_iter->IfaceRemoved(&(*iface_iter));
   585 				}
   586 
   587 				// There are no hooks on this iface anymore...
   588 				iface_iter = vfnptr_iter->GetIfaceList().erase(iface_iter);
   589 
   590 				if (vfnptr_iter->GetIfaceList().empty())
   591 				{
   592 					// No ifaces at all -> Deactivate the hook
   593 
   594 					for (CStack<CHookContext>::iterator ctx_iter = m_ContextStack.begin();
   595 						ctx_iter != m_ContextStack.end(); ++ctx_iter)
   596 					{
   597 						ctx_iter->VfnPtrRemoved(&(*vfnptr_iter));
   598 					}
   599 
   600 					// Only patch the vfnptr back if the module is still in memory
   601 					// If it's not, do not remove stuff like we did before
   602 					// First off we did it wrong (shutdown the whole hookman, uh..) and secondly applications may be
   603 					// confused by RemoveHook returning false then (yeah, I know, I made this one up, no one checks for RemoveHook error)
   604 					if (ModuleInMemory(reinterpret_cast<char*>(vfnptr_iter->GetPtr()), SH_PTRSIZE))
   605 					{
   606 						vfnptr_iter->Revert();
   607 					}
   608 
   609 					hookman.GetVfnPtrList().erase(vfnptr_iter);
   610 
   611 					if (hookman.GetVfnPtrList().empty())
   612 					{
   613 						// Unregister the hook manager
   614 						hookman.Unregister();
   615 					}
   616 				}
   617 			}
   618 
   619 			m_HookIDMan.Remove(hookid);
   620 			return true;
   621 		}
   622 
   623 		void CSourceHookImpl::SetRes(META_RES res)
   624 		{
   625 			*m_ContextStack.front().pCurRes = res;
   626 		}
   627 
   628 		META_RES CSourceHookImpl::GetPrevRes()
   629 		{
   630 			return *m_ContextStack.front().pPrevRes;
   631 		}
   632 
   633 		META_RES CSourceHookImpl::GetStatus()
   634 		{
   635 			return *m_ContextStack.front().pStatus;
   636 
   637 		}
   638 
   639 		const void *CSourceHookImpl::GetOrigRet()
   640 		{
   641 			return m_ContextStack.front().pOrigRet;
   642 		}
   643 
   644 		const void *CSourceHookImpl::GetOverrideRet()
   645 		{
   646 			return (*m_ContextStack.front().pStatus < MRES_OVERRIDE) ?
   647 				NULL : m_ContextStack.front().pOverrideRet;
   648 		}
   649 
   650 		void *CSourceHookImpl::GetIfacePtr()
   651 		{
   652 			// If in recall: return last one
   653 			if (m_ContextStack.front().m_State >= CHookContext::State_Recall_Pre &&
   654 				m_ContextStack.front().m_State <= CHookContext::State_Recall_PostVP)
   655 			{
   656 				return m_ContextStack.second().pIfacePtr;
   657 			}
   658 			else
   659 			{
   660 				return m_ContextStack.front().pIfacePtr;
   661 			}
   662 		}
   663 
   664 		void *CSourceHookImpl::GetOverrideRetPtr()
   665 		{
   666 			return m_ContextStack.front().pOverrideRet;
   667 		}
   668 
   669 		void CSourceHookImpl::UnloadPlugin(Plugin plug)
   670 		{
   671 			// 1) Remove all hooks by this plugin
   672 
   673 			CVector<int> removehooks;
   674 			m_HookIDMan.FindAllHooks(removehooks, plug);
   675 
   676 			for (CVector<int>::iterator iter = removehooks.begin(); iter != removehooks.end(); ++iter)
   677 				RemoveHookByID(*iter);
   678 
   679 			// 2) Remove all hook managers
   680 			m_HookManContainers.RemoveHookMans(plug);
   681 		}
   682 
   683 		void CSourceHookImpl::RemoveHookManager(Plugin plug, HookManagerPubFunc pubFunc)
   684 		{
   685 			// 1) Remove all its hooks
   686 			CVector<int> removehooks;
   687 
   688 			// Get info about hook manager
   689 			CHookManager hookManager(plug, pubFunc);
   690 			if (!hookManager)
   691 				return;
   692 
   693 			// Make sure that the container exists
   694 			CHookManagerContainer &container = m_HookManContainers.GetContainer(hookManager.GetVtblOffs(),
   695 				hookManager.GetVtblIdx(), hookManager.GetProto());
   696 
   697 			CHookManagerContainer::iterator cont_iter = container.find(CHookManager::Descriptor(plug, pubFunc));
   698 
   699 			for (List<CVfnPtr>::iterator vfnptr_iter = cont_iter->GetVfnPtrList().begin();
   700 				vfnptr_iter != cont_iter->GetVfnPtrList().end(); ++vfnptr_iter)
   701 			{
   702 				for (List<CIface>::iterator iface_iter = vfnptr_iter->GetIfaceList().begin();
   703 					iface_iter != vfnptr_iter->GetIfaceList().end(); ++iface_iter)
   704 				{
   705 					List<CHook>::iterator hook_iter;
   706 					for (hook_iter = iface_iter->GetPreHookList().begin();
   707 						hook_iter != iface_iter->GetPreHookList().end(); ++hook_iter)
   708 						removehooks.push_back(hook_iter->GetID());
   709 
   710 					for (hook_iter = iface_iter->GetPostHookList().begin();
   711 						hook_iter != iface_iter->GetPostHookList().end(); ++hook_iter)
   712 						removehooks.push_back(hook_iter->GetID());
   713 				}
   714 			}
   715 
   716 			for (CVector<int>::iterator iter = removehooks.begin(); iter != removehooks.end(); ++iter)
   717 				RemoveHookByID(*iter);
   718 
   719 			// 2) Remove it
   720 			container.RemoveHookMans(plug, pubFunc);
   721 		}
   722 
   723 		void CSourceHookImpl::SetIgnoreHooks(void *vfnptr)
   724 		{
   725 			CHookContext ctx;
   726 			ctx.m_State = CHookContext::State_Ignore;
   727 			m_ContextStack.push(ctx);
   728 		}
   729 
   730 		void CSourceHookImpl::ResetIgnoreHooks(void *vfnptr)
   731 		{
   732 			if (!m_ContextStack.empty() && m_ContextStack.front().m_State == CHookContext::State_Ignore)
   733 				m_ContextStack.pop();
   734 		}
   735 
   736 		void *CSourceHookImpl::GetOrigVfnPtrEntry(void *vfnptr)
   737 		{
   738 			for (CHookManContainerList::iterator hmcl_iter = m_HookManContainers.begin();
   739 				hmcl_iter != m_HookManContainers.end(); ++hmcl_iter)
   740 			{
   741 				for (CHookManagerContainer::iterator hookmaniter = hmcl_iter->begin();
   742 					hookmaniter != hmcl_iter->end(); ++hookmaniter)
   743 				{
   744 					for (List<CVfnPtr>::iterator vfnptr_iter = hookmaniter->GetVfnPtrList().begin();
   745 						vfnptr_iter != hookmaniter->GetVfnPtrList().end(); ++vfnptr_iter)
   746 					{
   747 						if (vfnptr_iter->GetPtr() == vfnptr)
   748 							return vfnptr_iter->GetOrigEntry();
   749 					}
   750 				}
   751 			}
   752 			return NULL;
   753 		}
   754 
   755 		void CSourceHookImpl::DoRecall()
   756 		{
   757 			CHookContext newCtx;
   758 			CHookContext &curCtx = m_ContextStack.front();
   759 
   760 
   761 			newCtx.m_State = curCtx.m_State + (CHookContext::State_Recall_Pre - CHookContext::State_Pre);
   762 			if (newCtx.m_State == CHookContext::State_Recall_Post || newCtx.m_State == CHookContext::State_Recall_PostVP)
   763 			{
   764 				// Also save orig ret
   765 				newCtx.pOrigRet = curCtx.pOrigRet;
   766 			}
   767 
   768 			// The hookfunc usually does this, but it won't have a chance to see it, 
   769 			// so for recalls, we update status here if it's required
   770 			if (*curCtx.pCurRes > *curCtx.pStatus) 
   771 				*curCtx.pStatus = *curCtx.pCurRes;
   772 
   773 			newCtx.pStatus = curCtx.pStatus;
   774 			newCtx.pOverrideRet = curCtx.pOverrideRet;
   775 			newCtx.pPrevRes = curCtx.pPrevRes;
   776 			newCtx.m_Iter = curCtx.m_Iter;
   777 
   778 			// Take this with us!
   779 			newCtx.pCurRes = curCtx.pCurRes;
   780 
   781 			m_ContextStack.push(newCtx);
   782 			curCtx.m_State = CHookContext::State_Dead;
   783 		}
   784 
   785 		IHookContext *CSourceHookImpl::SetupHookLoop(IHookManagerInfo *hi, void *vfnptr, void *thisptr, void **origentry, META_RES *statusPtr,
   786 			META_RES *prevResPtr, META_RES *curResPtr, const void *origRetPtr, void *overrideRetPtr)
   787 		{
   788 			CHookContext *pCtx = NULL;
   789 			CHookContext *oldctx = m_ContextStack.empty() ? NULL : &m_ContextStack.front();
   790 			if (oldctx)
   791 			{
   792 				// SH_CALL
   793 				if (oldctx->m_State == CHookContext::State_Ignore)
   794 				{
   795 					*statusPtr = MRES_IGNORED;
   796 					oldctx->m_State = CHookContext::State_Dead;
   797 
   798 					List<CVfnPtr> &vfnptrList = static_cast<CHookManager*>(hi)->GetVfnPtrList();
   799 					List<CVfnPtr>::iterator vfnptr_iter = vfnptrList.find(vfnptr);
   800 					if (vfnptr_iter == vfnptrList.end())
   801 					{
   802 						// :TODO: what??
   803 					}
   804 					else
   805 					{
   806 						*origentry = vfnptr_iter->GetOrigEntry();
   807 					}
   808 
   809 					oldctx->pOrigRet = origRetPtr;
   810 					return oldctx;
   811 				}
   812 				// Recall
   813 				else if (oldctx->m_State >= CHookContext::State_Recall_Pre &&
   814 					oldctx->m_State <= CHookContext::State_Recall_PostVP)
   815 				{
   816 					pCtx = oldctx;
   817 
   818 					*statusPtr = *(oldctx->pStatus);
   819 					*prevResPtr = *(oldctx->pPrevRes);
   820 
   821 					pCtx->m_Iter = oldctx->m_Iter;
   822 
   823 					// Only have possibility of calling the orig func in pre recall mode
   824 					pCtx->m_CallOrig = (oldctx->m_State == CHookContext::State_Recall_Pre || 
   825 						oldctx->m_State == CHookContext::State_Recall_PreVP);
   826 
   827 					overrideRetPtr = pCtx->pOverrideRet;
   828 
   829 					// When the status is low so there's no override return value and we're in a post recall,
   830 					// give it the orig return value as override return value.
   831 					if (pCtx->m_State == CHookContext::State_Recall_Post ||
   832 						pCtx->m_State == CHookContext::State_Recall_PostVP)
   833 					{
   834 						origRetPtr = oldctx->pOrigRet;
   835 						if (*statusPtr < MRES_OVERRIDE)
   836 							overrideRetPtr = const_cast<void*>(pCtx->pOrigRet);
   837 					}
   838 				}
   839 			}
   840 			if (!pCtx)
   841 			{
   842 				pCtx = m_ContextStack.make_next();
   843 				pCtx->m_State = CHookContext::State_Born;
   844 				pCtx->m_CallOrig = true;
   845 			}
   846 
   847 			pCtx->pIface = NULL;
   848 
   849 			List<CVfnPtr> &vfnptrList = static_cast<CHookManager*>(hi)->GetVfnPtrList();
   850 			List<CVfnPtr>::iterator vfnptr_iter = vfnptrList.find(vfnptr);
   851 			if (vfnptr_iter == vfnptrList.end())
   852 			{
   853 				pCtx->m_State = CHookContext::State_Dead;
   854 			}
   855 			else
   856 			{
   857 				pCtx->pVfnPtr = &(*vfnptr_iter);
   858 				*origentry = vfnptr_iter->GetOrigEntry();
   859 				pCtx->pIface = vfnptr_iter->FindIface(thisptr);
   860 			}
   861 
   862 			pCtx->pStatus = statusPtr;
   863 			pCtx->pPrevRes = prevResPtr;
   864 			pCtx->pCurRes = curResPtr;
   865 			pCtx->pThisPtr = thisptr;
   866 			pCtx->pOverrideRet = overrideRetPtr;
   867 			pCtx->pOrigRet = origRetPtr;
   868 
   869 			return pCtx;
   870 		}
   871 
   872 		void CSourceHookImpl::EndContext(IHookContext *pCtx)
   873 		{
   874 			m_ContextStack.pop();
   875 		}
   876 
   877 		void CSourceHookImpl::CompleteShutdown()
   878 		{
   879 			CVector<int> removehooks;
   880 			m_HookIDMan.FindAllHooks(removehooks);
   881 
   882 			for (CVector<int>::iterator iter = removehooks.begin(); iter != removehooks.end(); ++iter)
   883 				RemoveHookByID(*iter);
   884 		}
   885 
   886 		void CSourceHookImpl::PausePlugin(Plugin plug)
   887 		{
   888 			CVector<int> pausehooks;
   889 			m_HookIDMan.FindAllHooks(pausehooks, plug);
   890 
   891 			for (CVector<int>::iterator iter = pausehooks.begin(); iter != pausehooks.end(); ++iter)
   892 				PauseHookByID(*iter);
   893 		}
   894 
   895 		void CSourceHookImpl::UnpausePlugin(Plugin plug)
   896 		{
   897 			CVector<int> unpausehooks;
   898 			m_HookIDMan.FindAllHooks(unpausehooks, plug);
   899 
   900 			for (CVector<int>::iterator iter = unpausehooks.begin(); iter != unpausehooks.end(); ++iter)
   901 				UnpauseHookByID(*iter);
   902 		}
   903 
   904 		bool CSourceHookImpl::PauseHookByID(int hookid)
   905 		{
   906 			return SetHookPaused(hookid, true);
   907 		}
   908 
   909 		bool CSourceHookImpl::UnpauseHookByID(int hookid)
   910 		{
   911 			return SetHookPaused(hookid, false);
   912 		}
   913 
   914 		bool CSourceHookImpl::SetHookPaused(int hookid, bool paused)
   915 		{
   916 			const CHookIDManager::Entry *hentry;
   917 
   918 			hentry = m_HookIDMan.QueryHook(hookid);
   919 			if (!hentry)
   920 			{
   921 				// hookid doesn't exist !
   922 				return false;
   923 			}
   924 
   925 			// find hookman
   926 			CHookManContainerList::iterator hmcl_iter = m_HookManContainers.find(
   927 				CHookManagerContainer::Descriptor(hentry->vtbl_offs, hentry->vtbl_idx, hentry->proto));
   928 
   929 			if (hmcl_iter == m_HookManContainers.end() || !(*hmcl_iter))
   930 				return false;
   931 
   932 			CHookManager &hookman = hmcl_iter->GetActiveHookManager();
   933 
   934 			// find vfnptr
   935 			List<CVfnPtr>::iterator vfnptr_iter = hookman.GetVfnPtrList().find(hentry->vfnptr);
   936 			if (vfnptr_iter == hookman.GetVfnPtrList().end())
   937 				return false;
   938 
   939 			// find iface
   940 			List<CIface>::iterator iface_iter = vfnptr_iter->GetIfaceList().find(hentry->adjustediface);
   941 			if (iface_iter == vfnptr_iter->GetIfaceList().end())
   942 				return false;
   943 
   944 			// find hook
   945 			List<CHook> &hooks = hentry->post ? iface_iter->GetPostHookList() : iface_iter->GetPreHookList();
   946 			List<CHook>::iterator hook_iter = hooks.find(hookid);
   947 			if (hook_iter == hooks.end())
   948 				return false;
   949 
   950 			hook_iter->SetPaused(paused);
   951 			return true;
   952 		}
   953 
   954 		//////////////////////////////////////////////////////////////////////////
   955 		// CHookContext
   956 		//////////////////////////////////////////////////////////////////////////
   957 		ISHDelegate *CHookContext::GetNext()
   958 		{
   959 			CIface *pVPIface;
   960 
   961 			switch (m_State)
   962 			{
   963 			case State_Dead:
   964 				return NULL;
   965 
   966 			case State_Born:
   967 				m_Iter = List<CHook>::iterator();
   968 				m_State = State_Pre;
   969 
   970 				// fall-through
   971 			case State_Recall_Pre:
   972 				m_State = State_Pre;
   973 			case State_Pre:
   974 				if (pIface)
   975 				{
   976 					if (!m_Iter)
   977 						m_Iter = pIface->GetPreHookList().begin();
   978 					else
   979 						++m_Iter;
   980 					SkipPaused(m_Iter, pIface->GetPreHookList());
   981 
   982 					if (m_Iter != pIface->GetPreHookList().end())
   983 					{
   984 						pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
   985 						return m_Iter->GetHandler();
   986 					}
   987 				}
   988 
   989 				// end of normal hooks -> VP
   990 				
   991 				m_State = State_PreVP;
   992 				m_Iter = List<CHook>::iterator();
   993 
   994 				// fall-through
   995 			case State_Recall_PreVP:
   996 				m_State = State_PreVP;
   997 			case State_PreVP:
   998 				pVPIface = pVfnPtr->FindIface(NULL);
   999 				if (pVPIface)
  1000 				{
  1001 					if (!m_Iter)
  1002 						m_Iter = pVPIface->GetPreHookList().begin();
  1003 					else
  1004 						++m_Iter;
  1005 					SkipPaused(m_Iter, pVPIface->GetPreHookList());
  1006 
  1007 					if (m_Iter != pVPIface->GetPreHookList())
  1008 					{
  1009 						pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
  1010 						return m_Iter->GetHandler();
  1011 					}
  1012 				}
  1013 
  1014 				// end VP hooks -> orig call
  1015 
  1016 				m_State = State_OrigCall;
  1017 				return NULL;
  1018 				
  1019 			case State_OrigCall:
  1020 				m_Iter = List<CHook>::iterator();
  1021 				m_State = State_Post;
  1022 
  1023 				// fall-through
  1024 			case State_Post:
  1025 				if (pIface)
  1026 				{
  1027 					if (!m_Iter)
  1028 						m_Iter = pIface->GetPostHookList().begin();
  1029 					else
  1030 						++m_Iter;
  1031 					SkipPaused(m_Iter, pIface->GetPostHookList());
  1032 
  1033 					if (m_Iter != pIface->GetPostHookList().end())
  1034 					{
  1035 						pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
  1036 						return m_Iter->GetHandler();
  1037 					}
  1038 				}
  1039 				// end of normal hooks -> VP
  1040 
  1041 				m_State = State_PostVP;
  1042 				m_Iter = List<CHook>::iterator();
  1043 
  1044 				// fall-through
  1045 			case State_PostVP:
  1046 				pVPIface = pVfnPtr->FindIface(NULL);
  1047 				if (pVPIface)
  1048 				{
  1049 					if (!m_Iter)
  1050 						m_Iter = pVPIface->GetPostHookList().begin();
  1051 					else
  1052 						++m_Iter;
  1053 					SkipPaused(m_Iter, pVPIface->GetPostHookList());
  1054 
  1055 					if (m_Iter != pVPIface->GetPostHookList())
  1056 					{
  1057 						pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
  1058 						return m_Iter->GetHandler();
  1059 					}
  1060 				}
  1061 
  1062 				// end VP hooks -> done
  1063 
  1064 				m_State = State_Dead;
  1065 				return NULL;
  1066 
  1067 			case State_Recall_Post:
  1068 				// Skip pre hooks _and_ orig call
  1069 				m_State = State_Post;
  1070 				return NULL;
  1071 
  1072 			case State_Recall_PostVP:
  1073 				// Skip pre hooks _and_ orig call
  1074 				m_State = State_PostVP;
  1075 				return NULL;
  1076 			}
  1077 			return NULL;
  1078 		}
  1079 
  1080 		void *CHookContext::GetOverrideRetPtr()
  1081 		{
  1082 			return pOverrideRet;
  1083 		}
  1084 
  1085 		const void *CHookContext::GetOrigRetPtr()
  1086 		{
  1087 			return pOrigRet;
  1088 		}
  1089 
  1090 		bool CHookContext::ShouldCallOrig()
  1091 		{
  1092 			return m_CallOrig;
  1093 		}
  1094 
  1095 		void CHookContext::HookRemoved(List<CHook>::iterator oldhookiter, List<CHook>::iterator nexthookiter)
  1096 		{
  1097 			if (m_Iter == oldhookiter)
  1098 			{
  1099 				m_Iter = nexthookiter;
  1100 				--m_Iter;
  1101 			}
  1102 		}
  1103 
  1104 		void CHookContext::IfaceRemoved(CIface *iface)
  1105 		{
  1106 			if (pIface == iface)
  1107 				pIface = NULL;
  1108 		}
  1109 
  1110 		void CHookContext::VfnPtrRemoved(CVfnPtr *vfnptr)
  1111 		{
  1112 			if (pVfnPtr == vfnptr)
  1113 			{
  1114 				pVfnPtr = NULL;
  1115 				m_State = State_Dead;
  1116 			}
  1117 		}
  1118 	}
  1119 }