sourcehook/sourcehook.cpp
author David Anderson <dvander@alliedmods.net>
Wed Oct 10 01:20:36 2007 +0000 (2007-10-10)
changeset 406 d159cb02b2bb
parent 399 3cd3255adb76
child 412 43098e572d24
permissions -rw-r--r--
added new typedef for normal load function
     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 			{
   287 				return false;
   288 			}
   289 
   290 			*reinterpret_cast<void**>(m_Ptr) = newValue;
   291 
   292 			return true;
   293 		}
   294 
   295 		CIface &CVfnPtr::GetIface(void *iface)
   296 		{
   297 			List<CIface>::iterator iter = m_IfaceList.find(iface);
   298 			if (iter == m_IfaceList.end())
   299 			{
   300 				CIface newIface(iface);
   301 				if (iface == NULL)
   302 				{
   303 					m_IfaceList.push_front(newIface);
   304 					return m_IfaceList.front();
   305 				}
   306 				else
   307 				{
   308 					m_IfaceList.push_back(newIface);
   309 					return m_IfaceList.back();
   310 				}
   311 			}
   312 			else
   313 			{
   314 				return *iter;
   315 			}
   316 		}
   317 
   318 		//////////////////////////////////////////////////////////////////////////
   319 		// CHookIdManager
   320 		//////////////////////////////////////////////////////////////////////////
   321 		CHookIDManager::CHookIDManager()
   322 		{
   323 		}
   324 
   325 		int CHookIDManager::New(const CProto &proto, int vtbl_offs, int vtbl_idx, void *vfnptr,
   326 			void *adjustediface, Plugin plug, int thisptr_offs, ISHDelegate *handler, bool post)
   327 		{
   328 			Entry tmp(proto, vtbl_offs, vtbl_idx, vfnptr, adjustediface, plug, thisptr_offs, handler, post);
   329 
   330 			size_t cursize = m_Entries.size();
   331 			for (size_t i = 0; i < cursize; ++i)
   332 			{
   333 				if (m_Entries[i].isfree)
   334 				{
   335 					m_Entries[i] = tmp;
   336 					return static_cast<int>(i) + 1;
   337 				}
   338 			}
   339 
   340 			m_Entries.push_back(tmp);
   341 			return static_cast<int>(m_Entries.size());		// return size() because hookid = id+1 anyway
   342 		}
   343 
   344 		bool CHookIDManager::Remove(int hookid)
   345 		{
   346 			int realid = hookid - 1;
   347 			if (realid < 0 || realid >= static_cast<int>(m_Entries.size()) || m_Entries[realid].isfree)
   348 				return false;
   349 
   350 			m_Entries[realid].isfree = true;
   351 
   352 			// :TODO: remove free ids from back sometimes ??
   353 
   354 			return true;
   355 		}
   356 
   357 		const CHookIDManager::Entry * CHookIDManager::QueryHook(int hookid)
   358 		{
   359 			int realid = hookid - 1;
   360 			if (realid < 0 || realid >= static_cast<int>(m_Entries.size()) || m_Entries[realid].isfree)
   361 				return NULL;
   362 
   363 			return &m_Entries[realid];
   364 		}
   365 
   366 		void CHookIDManager::FindAllHooks(CVector<int> &output, const CProto &proto, int vtbl_offs,
   367 			int vtbl_idx, void *adjustediface, Plugin plug, int thisptr_offs, ISHDelegate *handler, bool post)
   368 		{
   369 			// oh my god, a lot of parameters...
   370 			size_t cursize = m_Entries.size();
   371 			for (size_t i = 0; i < cursize; ++i)
   372 			{
   373 				if (!m_Entries[i].isfree && m_Entries[i].proto == proto && m_Entries[i].vtbl_offs == vtbl_offs &&
   374 					m_Entries[i].vtbl_idx == vtbl_idx && m_Entries[i].adjustediface == adjustediface && m_Entries[i].plug == plug &&
   375 					m_Entries[i].thisptr_offs == thisptr_offs && m_Entries[i].handler->IsEqual(handler) && m_Entries[i].post == post)
   376 				{
   377 					output.push_back(static_cast<int>(i) + 1);
   378 				}
   379 			}
   380 		}
   381 
   382 		void CHookIDManager::FindAllHooks(CVector<int> &output)
   383 		{
   384 			size_t cursize = m_Entries.size();
   385 			for (size_t i = 0; i < cursize; ++i)
   386 			{
   387 				if (!m_Entries[i].isfree)
   388 					output.push_back(static_cast<int>(i) + 1);
   389 			}
   390 		}
   391 
   392 		void CHookIDManager::FindAllHooks(CVector<int> &output, Plugin plug)
   393 		{
   394 			size_t cursize = m_Entries.size();
   395 			for (size_t i = 0; i < cursize; ++i)
   396 			{
   397 				if (!m_Entries[i].isfree && m_Entries[i].plug == plug)
   398 					output.push_back(static_cast<int>(i) + 1);
   399 			}
   400 		}
   401 
   402 
   403 		//////////////////////////////////////////////////////////////////////////
   404 		// CSourceHookImpl
   405 		//////////////////////////////////////////////////////////////////////////
   406 		
   407 
   408 		CSourceHookImpl::CSourceHookImpl()
   409 		{
   410 		}
   411 		CSourceHookImpl::~CSourceHookImpl()
   412 		{
   413 		}
   414 
   415 		int CSourceHookImpl::GetIfaceVersion()
   416 		{
   417 			return SH_IFACE_VERSION;
   418 		}
   419 
   420 		int CSourceHookImpl::GetImplVersion()
   421 		{
   422 			return SH_IMPL_VERSION;
   423 		}
   424 
   425 		int CSourceHookImpl::AddHook(Plugin plug, AddHookMode mode, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan,
   426 			ISHDelegate *handler, bool post)
   427 		{
   428 			if (mode != Hook_Normal && mode != Hook_VP && mode != Hook_DVP)
   429 				return 0;
   430 
   431 			// Get info about hook manager
   432 			CHookManager hookManager(plug, myHookMan);
   433 			if (!hookManager)
   434 				return 0;
   435 
   436 			// Make sure that the container exists
   437 			CHookManagerContainer &container = m_HookManContainers.GetContainer(hookManager.GetVtblOffs(),
   438 				hookManager.GetVtblIdx(), hookManager.GetProto());
   439 
   440 			container.AddHookManager(hookManager);
   441 
   442 			if (!container)
   443 			{
   444 				// For some weird reason, the container is empty!
   445 				SH_ASSERT(0, ("No hookman found - but we've just added one!"));
   446 				return 0;
   447 			}
   448 
   449 			CHookManager &hookMan = container.GetActiveHookManager();
   450 
   451 			void *adjustediface = NULL;
   452 			void **cur_vtptr = NULL;
   453 			void *cur_vfnptr = NULL;
   454 
   455 			// find vfnptr
   456 			switch (mode)
   457 			{
   458 			case Hook_Normal:
   459 				adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface) + thisptr_offs);
   460 
   461 				cur_vtptr = *reinterpret_cast<void***>(
   462 					reinterpret_cast<char*>(adjustediface) + hookMan.GetVtblOffs());
   463 				cur_vfnptr = reinterpret_cast<void*>(cur_vtptr + hookMan.GetVtblIdx());
   464 				break;
   465 
   466 			case Hook_VP:
   467 
   468 				adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface) + thisptr_offs);
   469 
   470 				cur_vtptr = *reinterpret_cast<void***>(
   471 					reinterpret_cast<char*>(adjustediface) + hookMan.GetVtblOffs());
   472 				cur_vfnptr = reinterpret_cast<void*>(cur_vtptr + hookMan.GetVtblIdx());
   473 
   474 				adjustediface = NULL;
   475 				break;
   476 
   477 			case Hook_DVP:
   478 				adjustediface = NULL;
   479 
   480 				cur_vtptr = reinterpret_cast<void**>(iface);
   481 				cur_vfnptr = cur_vtptr + hookMan.GetVtblIdx();
   482 
   483 				break;
   484 			}
   485 
   486 			CVfnPtr &vfnPtr = hookMan.GetVfnPtr(cur_vfnptr);
   487 			CIface &ifaceinst = vfnPtr.GetIface(adjustediface);
   488 
   489 			// Add the hook
   490 			CHook hook(plug, thisptr_offs, handler, 
   491 
   492 				m_HookIDMan.New(hookMan.GetProto(), hookMan.GetVtblOffs(), hookMan.GetVtblIdx(),
   493 					cur_vfnptr, adjustediface, plug, thisptr_offs, handler, post)
   494 
   495 				);
   496 
   497 			if (post)
   498 				ifaceinst.GetPostHookList().push_back(hook);
   499 			else
   500 				ifaceinst.GetPreHookList().push_back(hook);
   501 
   502 			return hook.GetID();
   503 		}
   504 
   505 		bool CSourceHookImpl::RemoveHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan,
   506 			ISHDelegate *handler, bool post)
   507 		{
   508 			// Get info about hook manager and compute adjustediface
   509 			CHookManager tmpHookMan(plug, myHookMan);
   510 
   511 			void *adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface)+thisptr_offs);
   512 
   513 			// Loop through all hooks and remove those which match:
   514 			//  hookman, vfnptr, iface, plug, adjusted iface, this ptr offs, handler, post
   515 			CVector<int> removehooks;
   516 			m_HookIDMan.FindAllHooks(removehooks, tmpHookMan.GetProto(), tmpHookMan.GetVtblOffs(), tmpHookMan.GetVtblIdx(),
   517 				adjustediface, plug, thisptr_offs, handler, post);
   518 
   519 			if (removehooks.empty())
   520 				return false;
   521 
   522 			bool status = false;
   523 
   524 			for (CVector<int>::iterator iter = removehooks.begin(); iter != removehooks.end(); ++iter)
   525 			{
   526 				if (RemoveHookByID(*iter))
   527 					status = true;
   528 			}
   529 			return status; 
   530 		}
   531 
   532 		bool CSourceHookImpl::RemoveHookByID(int hookid)
   533 		{
   534 			const CHookIDManager::Entry *hentry;
   535 
   536 			hentry = m_HookIDMan.QueryHook(hookid);
   537 			if (!hentry)
   538 			{
   539 				// hookid doesn't exist !
   540 				return false;
   541 			}
   542 
   543 			// find hookman
   544 			CHookManContainerList::iterator hmcl_iter = m_HookManContainers.find(
   545 				CHookManagerContainer::Descriptor(hentry->vtbl_offs, hentry->vtbl_idx, hentry->proto));
   546 
   547 			if (hmcl_iter == m_HookManContainers.end() || !(*hmcl_iter))
   548 				return false;
   549 
   550 			CHookManager &hookman = hmcl_iter->GetActiveHookManager();
   551 
   552 			// find vfnptr
   553 			List<CVfnPtr>::iterator vfnptr_iter = hookman.GetVfnPtrList().find(hentry->vfnptr);
   554 			if (vfnptr_iter == hookman.GetVfnPtrList().end())
   555 				return false;
   556 
   557 			// find iface
   558 			List<CIface>::iterator iface_iter = vfnptr_iter->GetIfaceList().find(hentry->adjustediface);
   559 			if (iface_iter == vfnptr_iter->GetIfaceList().end())
   560 				return false;
   561 
   562 			// find hook
   563 			List<CHook> &hooks = hentry->post ? iface_iter->GetPostHookList() : iface_iter->GetPreHookList();
   564 			List<CHook>::iterator hook_iter = hooks.find(hookid);
   565 			if (hook_iter == hooks.end())
   566 				return false;
   567 
   568 			hook_iter->GetHandler()->DeleteThis();
   569 
   570 			// Iterator movage!
   571 			List<CHook>::iterator oldhookiter = hook_iter;
   572 			hook_iter = hooks.erase(hook_iter);
   573 
   574 			for (CStack<CHookContext>::iterator ctx_iter = m_ContextStack.begin();
   575 				ctx_iter != m_ContextStack.end(); ++ctx_iter)
   576 			{
   577 				ctx_iter->HookRemoved(oldhookiter, hook_iter);
   578 			}
   579 
   580 			if (iface_iter->GetPreHookList().empty() && iface_iter->GetPostHookList().empty())
   581 			{
   582 				// -> Kill all contexts that use it!
   583 				for (CStack<CHookContext>::iterator ctx_iter = m_ContextStack.begin();
   584 					ctx_iter != m_ContextStack.end(); ++ctx_iter)
   585 				{
   586 					ctx_iter->IfaceRemoved(&(*iface_iter));
   587 				}
   588 
   589 				// There are no hooks on this iface anymore...
   590 				iface_iter = vfnptr_iter->GetIfaceList().erase(iface_iter);
   591 
   592 				if (vfnptr_iter->GetIfaceList().empty())
   593 				{
   594 					// No ifaces at all -> Deactivate the hook
   595 
   596 					for (CStack<CHookContext>::iterator ctx_iter = m_ContextStack.begin();
   597 						ctx_iter != m_ContextStack.end(); ++ctx_iter)
   598 					{
   599 						ctx_iter->VfnPtrRemoved(&(*vfnptr_iter));
   600 					}
   601 
   602 					// Only patch the vfnptr back if the module is still in memory
   603 					// If it's not, do not remove stuff like we did before
   604 					// First off we did it wrong (shutdown the whole hookman, uh..) and secondly applications may be
   605 					// confused by RemoveHook returning false then (yeah, I know, I made this one up, no one checks for RemoveHook error)
   606 					if (ModuleInMemory(reinterpret_cast<char*>(vfnptr_iter->GetPtr()), SH_PTRSIZE))
   607 					{
   608 						vfnptr_iter->Revert();
   609 					}
   610 
   611 					hookman.GetVfnPtrList().erase(vfnptr_iter);
   612 
   613 					if (hookman.GetVfnPtrList().empty())
   614 					{
   615 						// Unregister the hook manager
   616 						hookman.Unregister();
   617 					}
   618 				}
   619 			}
   620 
   621 			m_HookIDMan.Remove(hookid);
   622 			return true;
   623 		}
   624 
   625 		void CSourceHookImpl::SetRes(META_RES res)
   626 		{
   627 			*m_ContextStack.front().pCurRes = res;
   628 		}
   629 
   630 		META_RES CSourceHookImpl::GetPrevRes()
   631 		{
   632 			return *m_ContextStack.front().pPrevRes;
   633 		}
   634 
   635 		META_RES CSourceHookImpl::GetStatus()
   636 		{
   637 			return *m_ContextStack.front().pStatus;
   638 
   639 		}
   640 
   641 		const void *CSourceHookImpl::GetOrigRet()
   642 		{
   643 			return m_ContextStack.front().pOrigRet;
   644 		}
   645 
   646 		const void *CSourceHookImpl::GetOverrideRet()
   647 		{
   648 			return (*m_ContextStack.front().pStatus < MRES_OVERRIDE) ?
   649 				NULL : m_ContextStack.front().pOverrideRet;
   650 		}
   651 
   652 		void *CSourceHookImpl::GetIfacePtr()
   653 		{
   654 			// If in recall: return last one
   655 			if (m_ContextStack.front().m_State >= CHookContext::State_Recall_Pre &&
   656 				m_ContextStack.front().m_State <= CHookContext::State_Recall_PostVP)
   657 			{
   658 				return m_ContextStack.second().pIfacePtr;
   659 			}
   660 			else
   661 			{
   662 				return m_ContextStack.front().pIfacePtr;
   663 			}
   664 		}
   665 
   666 		void *CSourceHookImpl::GetOverrideRetPtr()
   667 		{
   668 			return m_ContextStack.front().pOverrideRet;
   669 		}
   670 
   671 		void CSourceHookImpl::UnloadPlugin(Plugin plug)
   672 		{
   673 			// 1) Remove all hooks by this plugin
   674 
   675 			CVector<int> removehooks;
   676 			m_HookIDMan.FindAllHooks(removehooks, plug);
   677 
   678 			for (CVector<int>::iterator iter = removehooks.begin(); iter != removehooks.end(); ++iter)
   679 				RemoveHookByID(*iter);
   680 
   681 			// 2) Remove all hook managers
   682 			m_HookManContainers.RemoveHookMans(plug);
   683 		}
   684 
   685 		void CSourceHookImpl::RemoveHookManager(Plugin plug, HookManagerPubFunc pubFunc)
   686 		{
   687 			// 1) Remove all its hooks
   688 			CVector<int> removehooks;
   689 
   690 			// Get info about hook manager
   691 			CHookManager hookManager(plug, pubFunc);
   692 			if (!hookManager)
   693 				return;
   694 
   695 			// Make sure that the container exists
   696 			CHookManagerContainer &container = m_HookManContainers.GetContainer(hookManager.GetVtblOffs(),
   697 				hookManager.GetVtblIdx(), hookManager.GetProto());
   698 
   699 			CHookManagerContainer::iterator hookman_iter = container.find(CHookManager::Descriptor(plug, pubFunc));
   700 
   701 			if (hookman_iter != container.end())
   702 			{
   703 				for (List<CVfnPtr>::iterator vfnptr_iter = hookman_iter->GetVfnPtrList().begin();
   704 					vfnptr_iter != hookman_iter->GetVfnPtrList().end(); ++vfnptr_iter)
   705 				{
   706 					for (List<CIface>::iterator iface_iter = vfnptr_iter->GetIfaceList().begin();
   707 						iface_iter != vfnptr_iter->GetIfaceList().end(); ++iface_iter)
   708 					{
   709 						List<CHook>::iterator hook_iter;
   710 						for (hook_iter = iface_iter->GetPreHookList().begin();
   711 							hook_iter != iface_iter->GetPreHookList().end(); ++hook_iter)
   712 							removehooks.push_back(hook_iter->GetID());
   713 	
   714 						for (hook_iter = iface_iter->GetPostHookList().begin();
   715 							hook_iter != iface_iter->GetPostHookList().end(); ++hook_iter)
   716 							removehooks.push_back(hook_iter->GetID());
   717 					}
   718 				}
   719 			}
   720 
   721 			for (CVector<int>::iterator iter = removehooks.begin(); iter != removehooks.end(); ++iter)
   722 				RemoveHookByID(*iter);
   723 
   724 			// 2) Remove it
   725 			container.RemoveHookMans(plug, pubFunc);
   726 		}
   727 
   728 		void CSourceHookImpl::SetIgnoreHooks(void *vfnptr)
   729 		{
   730 			CHookContext ctx;
   731 			ctx.m_State = CHookContext::State_Ignore;
   732 			m_ContextStack.push(ctx);
   733 		}
   734 
   735 		void CSourceHookImpl::ResetIgnoreHooks(void *vfnptr)
   736 		{
   737 			if (!m_ContextStack.empty() && m_ContextStack.front().m_State == CHookContext::State_Ignore)
   738 				m_ContextStack.pop();
   739 		}
   740 
   741 		void *CSourceHookImpl::GetOrigVfnPtrEntry(void *vfnptr)
   742 		{
   743 			for (CHookManContainerList::iterator hmcl_iter = m_HookManContainers.begin();
   744 				hmcl_iter != m_HookManContainers.end(); ++hmcl_iter)
   745 			{
   746 				for (CHookManagerContainer::iterator hookmaniter = hmcl_iter->begin();
   747 					hookmaniter != hmcl_iter->end(); ++hookmaniter)
   748 				{
   749 					for (List<CVfnPtr>::iterator vfnptr_iter = hookmaniter->GetVfnPtrList().begin();
   750 						vfnptr_iter != hookmaniter->GetVfnPtrList().end(); ++vfnptr_iter)
   751 					{
   752 						if (vfnptr_iter->GetPtr() == vfnptr)
   753 							return vfnptr_iter->GetOrigEntry();
   754 					}
   755 				}
   756 			}
   757 			return NULL;
   758 		}
   759 
   760 		void CSourceHookImpl::DoRecall()
   761 		{
   762 			CHookContext newCtx;
   763 			CHookContext &curCtx = m_ContextStack.front();
   764 
   765 
   766 			newCtx.m_State = curCtx.m_State + (CHookContext::State_Recall_Pre - CHookContext::State_Pre);
   767 			if (newCtx.m_State == CHookContext::State_Recall_Post || newCtx.m_State == CHookContext::State_Recall_PostVP)
   768 			{
   769 				// Also save orig ret
   770 				newCtx.pOrigRet = curCtx.pOrigRet;
   771 			}
   772 
   773 			// The hookfunc usually does this, but it won't have a chance to see it, 
   774 			// so for recalls, we update status here if it's required
   775 			if (*curCtx.pCurRes > *curCtx.pStatus) 
   776 				*curCtx.pStatus = *curCtx.pCurRes;
   777 
   778 			newCtx.pStatus = curCtx.pStatus;
   779 			newCtx.pOverrideRet = curCtx.pOverrideRet;
   780 			newCtx.pPrevRes = curCtx.pPrevRes;
   781 			newCtx.m_Iter = curCtx.m_Iter;
   782 
   783 			// Take this with us!
   784 			newCtx.pCurRes = curCtx.pCurRes;
   785 
   786 			m_ContextStack.push(newCtx);
   787 			curCtx.m_State = CHookContext::State_Dead;
   788 		}
   789 
   790 		IHookContext *CSourceHookImpl::SetupHookLoop(IHookManagerInfo *hi, void *vfnptr, void *thisptr, void **origentry, META_RES *statusPtr,
   791 			META_RES *prevResPtr, META_RES *curResPtr, const void *origRetPtr, void *overrideRetPtr)
   792 		{
   793 			CHookContext *pCtx = NULL;
   794 			CHookContext *oldctx = m_ContextStack.empty() ? NULL : &m_ContextStack.front();
   795 			if (oldctx)
   796 			{
   797 				// SH_CALL
   798 				if (oldctx->m_State == CHookContext::State_Ignore)
   799 				{
   800 					*statusPtr = MRES_IGNORED;
   801 					oldctx->m_CallOrig = true;
   802 					oldctx->m_State = CHookContext::State_Dead;
   803 
   804 					List<CVfnPtr> &vfnptrList = static_cast<CHookManager*>(hi)->GetVfnPtrList();
   805 					List<CVfnPtr>::iterator vfnptr_iter = vfnptrList.find(vfnptr);
   806 					if (vfnptr_iter == vfnptrList.end())
   807 					{
   808 						// :TODO: what??
   809 					}
   810 					else
   811 					{
   812 						*origentry = vfnptr_iter->GetOrigEntry();
   813 					}
   814 
   815 					oldctx->pOrigRet = origRetPtr;
   816 					return oldctx;
   817 				}
   818 				// Recall
   819 				else if (oldctx->m_State >= CHookContext::State_Recall_Pre &&
   820 					oldctx->m_State <= CHookContext::State_Recall_PostVP)
   821 				{
   822 					pCtx = oldctx;
   823 
   824 					*statusPtr = *(oldctx->pStatus);
   825 					*prevResPtr = *(oldctx->pPrevRes);
   826 
   827 					pCtx->m_Iter = oldctx->m_Iter;
   828 
   829 					// Only have possibility of calling the orig func in pre recall mode
   830 					pCtx->m_CallOrig = (oldctx->m_State == CHookContext::State_Recall_Pre || 
   831 						oldctx->m_State == CHookContext::State_Recall_PreVP);
   832 
   833 					overrideRetPtr = pCtx->pOverrideRet;
   834 
   835 					// When the status is low so there's no override return value and we're in a post recall,
   836 					// give it the orig return value as override return value.
   837 					if (pCtx->m_State == CHookContext::State_Recall_Post ||
   838 						pCtx->m_State == CHookContext::State_Recall_PostVP)
   839 					{
   840 						origRetPtr = oldctx->pOrigRet;
   841 						if (*statusPtr < MRES_OVERRIDE)
   842 							overrideRetPtr = const_cast<void*>(pCtx->pOrigRet);
   843 					}
   844 				}
   845 			}
   846 			if (!pCtx)
   847 			{
   848 				pCtx = m_ContextStack.make_next();
   849 				pCtx->m_State = CHookContext::State_Born;
   850 				pCtx->m_CallOrig = true;
   851 			}
   852 
   853 			pCtx->pIface = NULL;
   854 
   855 			List<CVfnPtr> &vfnptrList = static_cast<CHookManager*>(hi)->GetVfnPtrList();
   856 			List<CVfnPtr>::iterator vfnptr_iter = vfnptrList.find(vfnptr);
   857 			if (vfnptr_iter == vfnptrList.end())
   858 			{
   859 				pCtx->m_State = CHookContext::State_Dead;
   860 			}
   861 			else
   862 			{
   863 				pCtx->pVfnPtr = &(*vfnptr_iter);
   864 				*origentry = vfnptr_iter->GetOrigEntry();
   865 				pCtx->pIface = vfnptr_iter->FindIface(thisptr);
   866 			}
   867 
   868 			pCtx->pStatus = statusPtr;
   869 			pCtx->pPrevRes = prevResPtr;
   870 			pCtx->pCurRes = curResPtr;
   871 			pCtx->pThisPtr = thisptr;
   872 			pCtx->pOverrideRet = overrideRetPtr;
   873 			pCtx->pOrigRet = origRetPtr;
   874 
   875 			return pCtx;
   876 		}
   877 
   878 		void CSourceHookImpl::EndContext(IHookContext *pCtx)
   879 		{
   880 			m_ContextStack.pop();
   881 		}
   882 
   883 		void CSourceHookImpl::CompleteShutdown()
   884 		{
   885 			CVector<int> removehooks;
   886 			m_HookIDMan.FindAllHooks(removehooks);
   887 
   888 			for (CVector<int>::iterator iter = removehooks.begin(); iter != removehooks.end(); ++iter)
   889 				RemoveHookByID(*iter);
   890 		}
   891 
   892 		void CSourceHookImpl::PausePlugin(Plugin plug)
   893 		{
   894 			CVector<int> pausehooks;
   895 			m_HookIDMan.FindAllHooks(pausehooks, plug);
   896 
   897 			for (CVector<int>::iterator iter = pausehooks.begin(); iter != pausehooks.end(); ++iter)
   898 				PauseHookByID(*iter);
   899 		}
   900 
   901 		void CSourceHookImpl::UnpausePlugin(Plugin plug)
   902 		{
   903 			CVector<int> unpausehooks;
   904 			m_HookIDMan.FindAllHooks(unpausehooks, plug);
   905 
   906 			for (CVector<int>::iterator iter = unpausehooks.begin(); iter != unpausehooks.end(); ++iter)
   907 				UnpauseHookByID(*iter);
   908 		}
   909 
   910 		bool CSourceHookImpl::PauseHookByID(int hookid)
   911 		{
   912 			return SetHookPaused(hookid, true);
   913 		}
   914 
   915 		bool CSourceHookImpl::UnpauseHookByID(int hookid)
   916 		{
   917 			return SetHookPaused(hookid, false);
   918 		}
   919 
   920 		bool CSourceHookImpl::SetHookPaused(int hookid, bool paused)
   921 		{
   922 			const CHookIDManager::Entry *hentry;
   923 
   924 			hentry = m_HookIDMan.QueryHook(hookid);
   925 			if (!hentry)
   926 			{
   927 				// hookid doesn't exist !
   928 				return false;
   929 			}
   930 
   931 			// find hookman
   932 			CHookManContainerList::iterator hmcl_iter = m_HookManContainers.find(
   933 				CHookManagerContainer::Descriptor(hentry->vtbl_offs, hentry->vtbl_idx, hentry->proto));
   934 
   935 			if (hmcl_iter == m_HookManContainers.end() || !(*hmcl_iter))
   936 				return false;
   937 
   938 			CHookManager &hookman = hmcl_iter->GetActiveHookManager();
   939 
   940 			// find vfnptr
   941 			List<CVfnPtr>::iterator vfnptr_iter = hookman.GetVfnPtrList().find(hentry->vfnptr);
   942 			if (vfnptr_iter == hookman.GetVfnPtrList().end())
   943 				return false;
   944 
   945 			// find iface
   946 			List<CIface>::iterator iface_iter = vfnptr_iter->GetIfaceList().find(hentry->adjustediface);
   947 			if (iface_iter == vfnptr_iter->GetIfaceList().end())
   948 				return false;
   949 
   950 			// find hook
   951 			List<CHook> &hooks = hentry->post ? iface_iter->GetPostHookList() : iface_iter->GetPreHookList();
   952 			List<CHook>::iterator hook_iter = hooks.find(hookid);
   953 			if (hook_iter == hooks.end())
   954 				return false;
   955 
   956 			hook_iter->SetPaused(paused);
   957 			return true;
   958 		}
   959 
   960 		//////////////////////////////////////////////////////////////////////////
   961 		// CHookContext
   962 		//////////////////////////////////////////////////////////////////////////
   963 		ISHDelegate *CHookContext::GetNext()
   964 		{
   965 			CIface *pVPIface;
   966 			switch (m_State)
   967 			{
   968 			case State_Dead:
   969 				return NULL;
   970 
   971 			case State_Born:
   972 				m_Iter = List<CHook>::iterator();
   973 				m_State = State_Pre;
   974 
   975 				// fall-through
   976 			case State_Recall_Pre:
   977 				m_State = State_Pre;
   978 			case State_Pre:
   979 				if (pIface)
   980 				{
   981 					if (!m_Iter)
   982 						m_Iter = pIface->GetPreHookList().begin();
   983 					else
   984 						++m_Iter;
   985 					SkipPaused(m_Iter, pIface->GetPreHookList());
   986 
   987 					if (m_Iter != pIface->GetPreHookList().end())
   988 					{
   989 						pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
   990 						return m_Iter->GetHandler();
   991 					}
   992 				}
   993 
   994 				// end of normal hooks -> VP
   995 				
   996 				m_State = State_PreVP;
   997 				m_Iter = List<CHook>::iterator();
   998 
   999 				// fall-through
  1000 			case State_Recall_PreVP:
  1001 				m_State = State_PreVP;
  1002 			case State_PreVP:
  1003 				pVPIface = pVfnPtr->FindIface(NULL);
  1004 				if (pVPIface)
  1005 				{
  1006 					if (!m_Iter)
  1007 						m_Iter = pVPIface->GetPreHookList().begin();
  1008 					else
  1009 						++m_Iter;
  1010 					SkipPaused(m_Iter, pVPIface->GetPreHookList());
  1011 
  1012 					if (m_Iter != pVPIface->GetPreHookList())
  1013 					{
  1014 						pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
  1015 						return m_Iter->GetHandler();
  1016 					}
  1017 				}
  1018 
  1019 				// end VP hooks -> orig call
  1020 
  1021 				m_State = State_OrigCall;
  1022 				return NULL;
  1023 				
  1024 			case State_OrigCall:
  1025 				m_Iter = List<CHook>::iterator();
  1026 				m_State = State_Post;
  1027 
  1028 				// fall-through
  1029 			case State_Post:
  1030 				if (pIface)
  1031 				{
  1032 					if (!m_Iter)
  1033 						m_Iter = pIface->GetPostHookList().begin();
  1034 					else
  1035 						++m_Iter;
  1036 					SkipPaused(m_Iter, pIface->GetPostHookList());
  1037 
  1038 					if (m_Iter != pIface->GetPostHookList().end())
  1039 					{
  1040 						pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
  1041 						return m_Iter->GetHandler();
  1042 					}
  1043 				}
  1044 				// end of normal hooks -> VP
  1045 
  1046 				m_State = State_PostVP;
  1047 				m_Iter = List<CHook>::iterator();
  1048 
  1049 				// fall-through
  1050 			case State_PostVP:
  1051 				pVPIface = pVfnPtr->FindIface(NULL);
  1052 				if (pVPIface)
  1053 				{
  1054 					if (!m_Iter)
  1055 						m_Iter = pVPIface->GetPostHookList().begin();
  1056 					else
  1057 						++m_Iter;
  1058 					SkipPaused(m_Iter, pVPIface->GetPostHookList());
  1059 
  1060 					if (m_Iter != pVPIface->GetPostHookList())
  1061 					{
  1062 						pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
  1063 						return m_Iter->GetHandler();
  1064 					}
  1065 				}
  1066 
  1067 				// end VP hooks -> done
  1068 
  1069 				m_State = State_Dead;
  1070 				return NULL;
  1071 
  1072 			case State_Recall_Post:
  1073 				// Skip pre hooks _and_ orig call
  1074 				m_State = State_Post;
  1075 				return NULL;
  1076 
  1077 			case State_Recall_PostVP:
  1078 				// Skip pre hooks _and_ orig call
  1079 				m_State = State_PostVP;
  1080 				return NULL;
  1081 			}
  1082 			return NULL;
  1083 		}
  1084 
  1085 		void *CHookContext::GetOverrideRetPtr()
  1086 		{
  1087 			return pOverrideRet;
  1088 		}
  1089 
  1090 		const void *CHookContext::GetOrigRetPtr()
  1091 		{
  1092 			return pOrigRet;
  1093 		}
  1094 
  1095 		bool CHookContext::ShouldCallOrig()
  1096 		{
  1097 			return m_CallOrig;
  1098 		}
  1099 
  1100 		void CHookContext::HookRemoved(List<CHook>::iterator oldhookiter, List<CHook>::iterator nexthookiter)
  1101 		{
  1102 			if (m_Iter == oldhookiter)
  1103 			{
  1104 				m_Iter = nexthookiter;
  1105 				--m_Iter;
  1106 			}
  1107 		}
  1108 
  1109 		void CHookContext::IfaceRemoved(CIface *iface)
  1110 		{
  1111 			if (pIface == iface)
  1112 				pIface = NULL;
  1113 		}
  1114 
  1115 		void CHookContext::VfnPtrRemoved(CVfnPtr *vfnptr)
  1116 		{
  1117 			if (pVfnPtr == vfnptr)
  1118 			{
  1119 				pVfnPtr = NULL;
  1120 				m_State = State_Dead;
  1121 			}
  1122 		}
  1123 	}
  1124 }