sourcehook/sourcehook.cpp
author Pavol Marko <pavolmarko@gmail.com>
Sat May 12 19:05:16 2007 +0000 (2007-05-12)
changeset 332 030b917a8dcc
parent 331 40467046ea05
child 333 3813f1ac0cfe
permissions -rw-r--r--
Better treatement of deprecated callclasses
     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 	CSourceHookImpl::CSourceHookImpl() : m_OneIgnore(NULL), m_IgnoreActive(false)
    43 	{
    44 	}
    45 	CSourceHookImpl::~CSourceHookImpl()
    46 	{
    47 	}
    48 
    49 	int CSourceHookImpl::GetIfaceVersion()
    50 	{
    51 		return SH_IFACE_VERSION;
    52 	}
    53 
    54 	int CSourceHookImpl::GetImplVersion()
    55 	{
    56 		return SH_IMPL_VERSION;
    57 	}
    58 
    59 	bool CSourceHookImpl::IsPluginInUse(Plugin plug)
    60 	{
    61 		// Iterate through all hook managers which are in this plugin
    62 		// Iterate through their vfnptrs, ifaces, hooks
    63 		// If a hook from an other plugin is found, return true
    64 		// Return false otherwise
    65 #define TMP_CHECK_LIST(name) \
    66 	for (hook_iter = iface_iter->name.m_List.begin(); hook_iter != iface_iter->name.m_List.end(); ++hook_iter) \
    67 		if (hook_iter->plug == plug) \
    68 			return true;
    69 
    70 		for (HookManContList::iterator hmcl_iter = m_HookMans.begin();
    71 			hmcl_iter != m_HookMans.end(); ++hmcl_iter)
    72 		{
    73 			for (CHookManagerContainer::iterator hmil_iter = hmcl_iter->begin();
    74 				hmil_iter != hmcl_iter->end(); ++hmil_iter)
    75 			{
    76 				if (hmil_iter->m_Plug != plug)
    77 					continue;
    78 				for (CHookManagerInfo::VfnPtrListIter vfnptr_iter = hmil_iter->m_VfnPtrs.begin();
    79 					vfnptr_iter != hmil_iter->m_VfnPtrs.end(); ++vfnptr_iter)
    80 				{
    81 					for (CVfnPtr::IfaceListIter iface_iter = vfnptr_iter->m_Ifaces.begin();
    82 						iface_iter != vfnptr_iter->m_Ifaces.end(); ++iface_iter)
    83 					{
    84 						List<HookInfo>::iterator hook_iter;
    85 						TMP_CHECK_LIST(m_PreHooks);
    86 						TMP_CHECK_LIST(m_PostHooks);
    87 					}
    88 				}
    89 			}
    90 		}
    91 		
    92 #undef TMP_CHECK_LIST
    93 		return false;
    94 	}
    95 
    96 	void CSourceHookImpl::UnloadPlugin(Plugin plug)
    97 	{
    98 		// 1) Manually remove all hooks by this plugin
    99 		// 2) Manually remove all hook mans by this plugin
   100 
   101 		List<RemoveHookInfo> hookstoremove;
   102 		List<RemoveHookManInfo> hookmanstoremove;
   103 		HookManInfoList::iterator hmil_iter;
   104 
   105 #define TMP_CHECK_LIST(name, ispost) \
   106 	for (hook_iter = iface_iter->name.m_List.begin(); hook_iter != iface_iter->name.m_List.end(); ++hook_iter) \
   107 		if (hook_iter->plug == plug) \
   108 			hookstoremove.push_back(RemoveHookInfo(hook_iter->plug, iface_iter->m_Ptr, \
   109 			hook_iter->thisptr_offs, hmil_iter->m_Func, hook_iter->handler, ispost)); \
   110 
   111 		for (HookManContList::iterator hmcl_iter = m_HookMans.begin();
   112 			hmcl_iter != m_HookMans.end(); ++hmcl_iter)
   113 		{
   114 			for (CHookManagerContainer::iterator hmil_iter = hmcl_iter->begin();
   115 				hmil_iter != hmcl_iter->end(); ++hmil_iter)
   116 			{
   117 				if (hmil_iter->m_Plug == plug)
   118 					hookmanstoremove.push_back(RemoveHookManInfo(plug, hmil_iter->m_Func));
   119 
   120 				for (CHookManagerInfo::VfnPtrListIter vfnptr_iter = hmil_iter->m_VfnPtrs.begin();
   121 					vfnptr_iter != hmil_iter->m_VfnPtrs.end(); ++vfnptr_iter)
   122 				{
   123 					for (CVfnPtr::IfaceListIter iface_iter = vfnptr_iter->m_Ifaces.begin();
   124 						iface_iter != vfnptr_iter->m_Ifaces.end(); ++iface_iter)
   125 					{
   126 						List<HookInfo>::iterator hook_iter;
   127 						TMP_CHECK_LIST(m_PreHooks, false);
   128 						TMP_CHECK_LIST(m_PostHooks, true);
   129 					}
   130 				}
   131 			}
   132 		}
   133 #undef TMP_CHECK_LIST
   134 
   135 		for (List<RemoveHookInfo>::iterator rmiter = hookstoremove.begin(); rmiter != hookstoremove.end(); ++rmiter)
   136 			RemoveHook(*rmiter);
   137 
   138 		for (List<RemoveHookManInfo>::iterator rmiter = hookmanstoremove.begin(); rmiter != hookmanstoremove.end(); ++rmiter)
   139 			RemoveHookManager(*rmiter);
   140 	}
   141 
   142 	void CSourceHookImpl::RemoveHookManager(Plugin plug, HookManagerPubFunc pubFunc)
   143 	{
   144 		// Moo!
   145 
   146 		CHookManagerInfo tmp;
   147 		if (pubFunc(HA_GetInfo, &tmp) != 0)
   148 			return;
   149 
   150 		
   151 		HookManContList::iterator hmcl_iter = m_HookMans.find(
   152 			CHookManagerContainer::HMCI(tmp.m_Proto, tmp.m_VtblOffs, tmp.m_VtblIdx));
   153 
   154 		if (hmcl_iter == m_HookMans.end())
   155 		{
   156 			// Moo?
   157 			return;
   158 		}
   159 
   160 		CHookManagerContainer::iterator hmil_iter = hmcl_iter->find(
   161 			CHookManagerInfo::Descriptor(plug, pubFunc));
   162 
   163 		if (hmil_iter == hmcl_iter->end())
   164 		{
   165 			// Moo?
   166 			return;
   167 		}
   168 
   169 		bool stillInUse = false;
   170 		List<RemoveHookInfo> hookstoremove;
   171 
   172 		// Iterate through all of the hook manager's hooks. Remove all hooks from the hookman's plugin.
   173 #define TMP_CHECK_LIST(name, ispost) \
   174 	for (hook_iter = iface_iter->name.m_List.begin(); hook_iter != iface_iter->name.m_List.end(); ++hook_iter) \
   175 		if (hook_iter->plug == plug) \
   176 			hookstoremove.push_back(RemoveHookInfo(hook_iter->plug, iface_iter->m_Ptr, \
   177 			hook_iter->thisptr_offs, hmil_iter->m_Func, hook_iter->handler, ispost)); \
   178 		else \
   179 			stillInUse = true; \
   180 
   181 		for (CHookManagerInfo::VfnPtrListIter vfnptr_iter = hmil_iter->m_VfnPtrs.begin();
   182 			vfnptr_iter != hmil_iter->m_VfnPtrs.end(); ++vfnptr_iter)
   183 		{
   184 			for (CVfnPtr::IfaceListIter iface_iter = vfnptr_iter->m_Ifaces.begin();
   185 				iface_iter != vfnptr_iter->m_Ifaces.end(); ++iface_iter)
   186 			{
   187 				List<HookInfo>::iterator hook_iter;
   188 				TMP_CHECK_LIST(m_PreHooks, false);
   189 				TMP_CHECK_LIST(m_PostHooks, true);
   190 			}
   191 		}
   192 #undef TMP_CHECK_LIST
   193 
   194 		for (List<RemoveHookInfo>::iterator rmiter = hookstoremove.begin(); rmiter != hookstoremove.end(); ++rmiter)
   195 			RemoveHook(*rmiter);
   196 
   197 		CHookManagerInfo info = *hmil_iter;
   198 
   199 		// Unlink the hook manager from the list
   200 		hmcl_iter->erase(hmil_iter);
   201 
   202 		// If there were any hooks from other plugins, find a new suitable hook manager.
   203 		if (stillInUse)
   204 		{
   205 			// Find a suitable hook manager in an other plugin
   206 			hmil_iter = hmcl_iter->begin();
   207 
   208 			// This should _never_ happen.
   209 			// If there is a hook from an other plugin, the plugin must have provided a hook manager as well.
   210 			SH_ASSERT(hmil_iter != hmcl_iter->end(),
   211 				("Could not find a suitable hook manager in an other plugin!"));
   212 
   213 			// AddHook should make sure that every plugin only has _one_ hook manager for _one_ proto/vi/vo
   214 			SH_ASSERT(hmil_iter->m_Plug != plug, ("New hook manager from same plugin!"));
   215 
   216 			// The first hook manager should be always used - so the new hook manager has to be empty
   217 			SH_ASSERT(hmil_iter->m_VfnPtrs.empty(), ("New hook manager not empty!"));
   218 
   219 			// Move the vfnptrs from the old hook manager to the new one
   220 			hmil_iter->m_VfnPtrs = info.m_VfnPtrs;
   221 
   222 			// Unregister the old one, register the new one
   223 			info.m_Func(HA_Unregister, NULL);
   224 			hmil_iter->m_Func(HA_Register, &(*hmil_iter));
   225 
   226 			// Go through all vfnptrs in this hookman and patch them to point to the new manager's handler!
   227 			// or whatever
   228 			for (CHookManagerInfo::VfnPtrListIter vfnptr_iter = hmil_iter->m_VfnPtrs.begin();
   229 				vfnptr_iter != hmil_iter->m_VfnPtrs.end(); ++vfnptr_iter)
   230 			{
   231 				// And DEREFERENCE newHookMan->m_HookfuncVfnptr!
   232 				// otherwise it will be executing the vtable... had to find out the hard way
   233 				*reinterpret_cast<void**>(vfnptr_iter->m_Ptr) = *reinterpret_cast<void**>(hmil_iter->m_HookfuncVfnptr);
   234 			}
   235 		}
   236 	}
   237 
   238 	void CSourceHookImpl::RemoveHookManager(RemoveHookManInfo info)
   239 	{
   240 		RemoveHookManager(info.plug, info.hookman);
   241 	}
   242 
   243 	void CSourceHookImpl::CompleteShutdown()
   244 	{
   245 		// Remove all hooks
   246 
   247 		List<RemoveHookInfo> hookstoremove;
   248 
   249 #define TMP_CHECK_LIST(name, ispost) \
   250 	for (hook_iter = iface_iter->name.m_List.begin(); hook_iter != iface_iter->name.m_List.end(); ++hook_iter) \
   251 		hookstoremove.push_back(RemoveHookInfo(hook_iter->plug, iface_iter->m_Ptr, \
   252 			hook_iter->thisptr_offs, hmil_iter->m_Func, hook_iter->handler, ispost))
   253 		for (HookManContList::iterator hmcl_iter = m_HookMans.begin();
   254 			hmcl_iter != m_HookMans.end(); ++hmcl_iter)
   255 		{
   256 			for (CHookManagerContainer::iterator hmil_iter = hmcl_iter->begin();
   257 				hmil_iter != hmcl_iter->end(); ++hmil_iter)
   258 			{
   259 				for (CHookManagerInfo::VfnPtrListIter vfnptr_iter = hmil_iter->m_VfnPtrs.begin();
   260 					vfnptr_iter != hmil_iter->m_VfnPtrs.end(); ++vfnptr_iter)
   261 				{
   262 					for (CVfnPtr::IfaceListIter iface_iter = vfnptr_iter->m_Ifaces.begin();
   263 						iface_iter != vfnptr_iter->m_Ifaces.end(); ++iface_iter)
   264 					{
   265 						List<HookInfo>::iterator hook_iter;
   266 						TMP_CHECK_LIST(m_PreHooks, false);
   267 						TMP_CHECK_LIST(m_PostHooks, true);
   268 					}
   269 				}
   270 			}
   271 		}
   272 #undef TMP_CHECK_LIST
   273 
   274 		for (List<RemoveHookInfo>::iterator rmiter = hookstoremove.begin(); rmiter != hookstoremove.end(); ++rmiter)
   275 			RemoveHook(*rmiter);
   276 
   277 		m_HookMans.clear();
   278 	}
   279 
   280 
   281 	bool CSourceHookImpl::AddHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan, ISHDelegate *handler, bool post)
   282 	{
   283 		return AddHookNew(plug, Hook_Normal, iface, thisptr_offs, myHookMan, handler, post) != 0 ? true : false;
   284 	}
   285 
   286 	int CSourceHookImpl::AddHookNew(Plugin plug, AddHookMode mode, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan,
   287 		ISHDelegate *handler, bool post)
   288 	{
   289 		void *adjustediface = NULL;
   290 		void **cur_vtptr = NULL;
   291 		void *cur_vfnptr = NULL;
   292 
   293 		if (mode != Hook_Normal && mode != Hook_VP && mode != Hook_DVP)
   294 			return 0;
   295 
   296 		// 1) Get info about the hook manager
   297 		CHookManagerInfo tmp;
   298 		if (myHookMan(HA_GetInfo, &tmp) != 0)
   299 			return 0;
   300 
   301 		tmp.m_Func = myHookMan;
   302 		tmp.m_Plug = plug;
   303 
   304 		CHookManagerContainer::HMCI hmci(tmp.m_Proto, tmp.m_VtblOffs, tmp.m_VtblIdx);
   305 
   306 		// Add the container if not already added
   307 		HookManContList::iterator hmcl_iter = m_HookMans.find(hmci);
   308 		if (hmcl_iter == m_HookMans.end())
   309 		{
   310 			m_HookMans.push_back(CHookManagerContainer(hmci));
   311 			hmcl_iter = m_HookMans.end();
   312 			--hmcl_iter;
   313 		}
   314 
   315 		hmcl_iter->AddHookManager(plug, tmp);
   316 
   317 		CHookManagerContainer::iterator hookman = hmcl_iter->begin();
   318 		SH_ASSERT(hookman != hmcl_iter->end(), ("No hookman found - but we've just added one!"));
   319 
   320 		// Check whether any other container holds a hook manager which holds this vfnptr
   321 		// If yes, it means that the two are incompatible, so return false.
   322 		for (HookManContList::iterator hmcl_iter2 = m_HookMans.begin();
   323 			hmcl_iter2 != m_HookMans.end(); ++hmcl_iter2)
   324 		{
   325 			if (hmcl_iter2 != hmcl_iter)
   326 			{
   327 				for (CHookManagerContainer::iterator hmil_iter = hmcl_iter2->begin();
   328 					hmil_iter != hmcl_iter2->end(); ++hmil_iter)
   329 				{
   330 					if (hmil_iter->m_VfnPtrs.find(cur_vfnptr) != hmil_iter->m_VfnPtrs.end())
   331 						return 0;
   332 				}
   333 			}
   334 		}
   335 
   336 		// Tell it to store the pointer if it's not already active
   337 		if (hookman->m_VfnPtrs.empty())
   338 			hookman->m_Func(HA_Register, &(*hookman));
   339 
   340 
   341 		// find vfnptr
   342 		if (mode == Hook_Normal || mode == Hook_VP)
   343 		{
   344 			adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface) + thisptr_offs);
   345 
   346 			cur_vtptr = *reinterpret_cast<void***>(
   347 				reinterpret_cast<char*>(adjustediface) + tmp.m_VtblOffs);
   348 			cur_vfnptr = reinterpret_cast<void*>(cur_vtptr + tmp.m_VtblIdx);
   349 
   350 			// For Hook_VP, adjustediface will be set to NULL later
   351 			// because we first have to patch callclasses (callclasses are deprecated but left in for backwards compat)
   352 		}
   353 		else if (mode == Hook_DVP)
   354 		{
   355 			adjustediface = NULL;
   356 
   357 			cur_vtptr = reinterpret_cast<void**>(iface);
   358 			cur_vfnptr = cur_vtptr + tmp.m_VtblIdx;
   359 		}
   360 
   361 		CHookManagerInfo::VfnPtrListIter vfnptr_iter = hookman->m_VfnPtrs.find(cur_vfnptr);
   362 
   363 		if (vfnptr_iter == hookman->m_VfnPtrs.end())
   364 		{
   365 			// Add a new one
   366 			CVfnPtr vfp(cur_vfnptr, &m_OneIgnore);
   367 
   368 			// Alter vtable entry
   369 			if (!SetMemAccess(cur_vtptr, sizeof(void*) * (tmp.m_VtblIdx + 1), SH_MEM_READ | SH_MEM_WRITE))
   370 				return 0;
   371 
   372 			*reinterpret_cast<void**>(cur_vfnptr) = *reinterpret_cast<void**>(hookman->m_HookfuncVfnptr);
   373 
   374 			hookman->m_VfnPtrs.push_back(vfp);
   375 
   376 			// Make vfnptr_iter point to the new element
   377 			vfnptr_iter = hookman->m_VfnPtrs.end();
   378 			--vfnptr_iter;
   379 
   380 			// Now that it is done, check whether we have to update any callclasses
   381 			ApplyCallClassPatches(adjustediface, tmp.m_VtblOffs, tmp.m_VtblIdx, vfp.m_OrigEntry);
   382 		}
   383 
   384 		// If it's a VP hook, set adjustediface to NULL now ( see the comments at the beginning of sourcehook_impl.h )
   385 		if (mode == Hook_VP)
   386 			adjustediface = NULL;
   387 
   388 		CVfnPtr::IfaceListIter iface_iter = vfnptr_iter->m_Ifaces.find(adjustediface);
   389 		if (iface_iter == vfnptr_iter->m_Ifaces.end())
   390 		{
   391 			// Add a new one
   392 			vfnptr_iter->m_Ifaces.push_back(CIface(adjustediface));
   393 
   394 			// Make iface_iter point to the new element
   395 			iface_iter = vfnptr_iter->m_Ifaces.end();
   396 			--iface_iter;
   397 
   398 			// If this is a VP-Hook-NULL interface, go through all other interfaces of this vfnptr and tell them!
   399 			if (adjustediface == NULL)
   400 			{
   401 				for (CVfnPtr::IfaceListIter iface_iter2 = vfnptr_iter->m_Ifaces.begin();
   402 					iface_iter2 != vfnptr_iter->m_Ifaces.end(); ++iface_iter2)
   403 				{
   404 					if (*iface_iter2 != NULL)
   405 					{
   406 						iface_iter2->m_PreHooks.SetVPList(&iface_iter->m_PreHooks.m_List);
   407 						iface_iter2->m_PostHooks.SetVPList(&iface_iter->m_PostHooks.m_List);
   408 					}
   409 				}
   410 			}
   411 			else
   412 			{
   413 				// If this is a new non-VP-Hook-NULL interface, look for a non-VP-Hook-NULL interface!
   414 				for (CVfnPtr::IfaceListIter iface_iter2 = vfnptr_iter->m_Ifaces.begin();
   415 					iface_iter2 != vfnptr_iter->m_Ifaces.end(); ++iface_iter2)
   416 				{
   417 					if (*iface_iter2 == NULL)
   418 					{
   419 						iface_iter->m_PreHooks.SetVPList(&iface_iter2->m_PreHooks.m_List);
   420 						iface_iter->m_PostHooks.SetVPList(&iface_iter2->m_PostHooks.m_List);
   421 						break;	// There can only be one!
   422 					}
   423 				}
   424 			}
   425 		}
   426 
   427 		// Add the hook
   428 		HookInfo hookinfo;
   429 		hookinfo.handler = handler;
   430 		hookinfo.plug = plug;
   431 		hookinfo.paused = false;
   432 		hookinfo.thisptr_offs = thisptr_offs;
   433 		hookinfo.hookid = m_HookIDMan.New(tmp.m_Proto, tmp.m_VtblOffs, tmp.m_VtblIdx, cur_vfnptr,
   434 			adjustediface, plug, thisptr_offs, handler, post);
   435 
   436 		if (post)
   437 			iface_iter->m_PostHooks.m_List.push_back(hookinfo);
   438 		else
   439 			iface_iter->m_PreHooks.m_List.push_back(hookinfo);
   440 
   441 		return hookinfo.hookid;
   442 	}
   443 
   444 	bool CSourceHookImpl::RemoveHookByID(Plugin plug, int hookid)
   445 	{
   446 		const CHookIDManager::Entry *hentry;
   447 
   448 		hentry = m_HookIDMan.QueryHook(hookid);
   449 		if (!hentry)
   450 		{
   451 			// hookid doesn't exist !
   452 			return false;
   453 		}
   454 
   455 		HookManContList::iterator hmcl_iter = m_HookMans.find(
   456 			CHookManagerContainer::HMCI(hentry->proto.GetProto(), hentry->vtbl_offs, hentry->vtbl_idx));
   457 		if (hmcl_iter == m_HookMans.end() || hmcl_iter->empty())
   458 			return false;
   459 		CHookManagerContainer::iterator hookman = hmcl_iter->begin();
   460 
   461 		// Find vfnptr
   462 		CHookManagerInfo::VfnPtrListIter vfnptr_iter = hookman->m_VfnPtrs.find(hentry->vfnptr);
   463 		if (vfnptr_iter == hookman->m_VfnPtrs.end())
   464 			return false;
   465 
   466 		// Find iface
   467 		CVfnPtr::IfaceListIter iface_iter = vfnptr_iter->m_Ifaces.find(hentry->adjustediface);
   468 		if (iface_iter == vfnptr_iter->m_Ifaces.end())
   469 			return false;
   470 
   471 		// Find hook
   472 		List<HookInfo> &hooks = hentry->post ? iface_iter->m_PostHooks.m_List : iface_iter->m_PreHooks.m_List;
   473 
   474 		List<HookInfo>::iterator hookiter = hooks.find(hookid);
   475 		if (hookiter == hooks.end())
   476 			return false;
   477 
   478 		hookiter->handler->DeleteThis();
   479 
   480 		// Move all iterators pointing at this
   481 		List<HookInfo>::iterator oldhookiter = hookiter;
   482 		hookiter = hooks.erase(hookiter);
   483 		List<HookInfo>::iterator newhookiter = hookiter;
   484 		--newhookiter; // The hook loop will ++ it then
   485 		CHookList::CIter *pItIter;
   486 		
   487 		for (pItIter = iface_iter->m_PreHooks.m_UsedIters; pItIter; pItIter = pItIter->m_pNext)
   488 			if (pItIter->m_Iter == oldhookiter)
   489 				pItIter->m_Iter = newhookiter;
   490 
   491 		// If this is VP-Hook-NULL interface, also check all other interfaces of this vfnptr
   492 		if (*iface_iter == NULL)
   493 		{
   494 			for (CVfnPtr::IfaceListIter iface_iter2 = vfnptr_iter->m_Ifaces.begin();
   495 				iface_iter2 != vfnptr_iter->m_Ifaces.end(); ++iface_iter2)
   496 			{
   497 				if (*iface_iter2 != NULL)
   498 				{
   499 					for (pItIter = iface_iter2->m_PreHooks.m_UsedIters; pItIter; pItIter = pItIter->m_pNext)
   500 						if (pItIter->m_Iter == oldhookiter)
   501 							pItIter->m_Iter = newhookiter;
   502 				}
   503 			}
   504 		}
   505 
   506 		if (iface_iter->m_PostHooks.m_List.empty() && iface_iter->m_PreHooks.m_List.empty())
   507 		{
   508 			// If this is a VP-Hook-NULL interface, go through all other interfaces of this vfnptr and tell them!
   509 			if (*iface_iter == NULL)
   510 			{
   511 				for (CVfnPtr::IfaceListIter iface_iter2 = vfnptr_iter->m_Ifaces.begin();
   512 					iface_iter2 != vfnptr_iter->m_Ifaces.end(); ++iface_iter2)
   513 				{
   514 					if (iface_iter2->m_Ptr != NULL)
   515 					{
   516 						iface_iter2->m_PreHooks.ClearVPList();
   517 						iface_iter2->m_PostHooks.ClearVPList();
   518 					}
   519 				}
   520 			}
   521 
   522 
   523 			// There are no hooks on this iface anymore...
   524 			for (HookLoopInfoStack::iterator hli_iter = m_HLIStack.begin();
   525 				hli_iter != m_HLIStack.end(); ++hli_iter)
   526 			{
   527 				if (hli_iter->pCurIface == static_cast<IIface*>(&(*iface_iter)))
   528 					hli_iter->shouldContinue = false;
   529 			}
   530 
   531 			iface_iter = vfnptr_iter->m_Ifaces.erase(iface_iter);
   532 			if (vfnptr_iter->m_Ifaces.empty())
   533 			{
   534 				// No ifaces at all -> Deactivate the hook
   535 
   536 				// Only patch the vfnptr back if the module is still in memory
   537 				// If it's not, do not remove stuff like we did before
   538 				// First off we did it wrong (shutdown the whole hookman, uh..) and secondly applications may be
   539 				// confused by RemoveHook returning false then (yeah, I know, I made this one up, no one checks for RemoveHook error)
   540 				if (ModuleInMemory(reinterpret_cast<char*>(vfnptr_iter->m_Ptr), SH_PTRSIZE))
   541 				{
   542 					*reinterpret_cast<void**>(vfnptr_iter->m_Ptr) = vfnptr_iter->m_OrigEntry;
   543 				}
   544 
   545 				hookman->m_VfnPtrs.erase(vfnptr_iter);
   546 
   547 				// Remove callclass patch
   548 				for (Impl_CallClassList::iterator cciter = m_CallClasses.begin(); cciter != m_CallClasses.end(); ++cciter)
   549 					if (cciter->m_Ptr == hentry->adjustediface)
   550 						cciter->RemoveCallClassPatch(hentry->vtbl_offs, hentry->vtbl_idx);
   551 
   552 				if (hookman->m_VfnPtrs.empty())
   553 				{
   554 					// Unregister the hook manager
   555 					hookman->m_Func(HA_Unregister, NULL);
   556 				}
   557 			}
   558 		}
   559 
   560 		// Don't forget to remove the hookid from m_HookIDMan
   561 		m_HookIDMan.Remove(hookid);
   562 
   563 		return true;
   564 	}
   565 
   566 	bool CSourceHookImpl::RemoveHook(RemoveHookInfo info)
   567 	{
   568 		return RemoveHook(info.plug, info.iface, info.thisptr_offs, info.hookman, info.handler, info.post);
   569 	}
   570 
   571 	bool CSourceHookImpl::RemoveHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan, ISHDelegate *handler, bool post)
   572 	{
   573 		// Get info about hook manager and compute adjustediface
   574 		CHookManagerInfo tmp;
   575 		if (myHookMan(HA_GetInfo, &tmp) != 0)
   576 			return false;
   577 
   578 		void *adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface)+thisptr_offs);
   579 
   580 		// Loop through all hooks and remove those which match:
   581 		//  hookman, vfnptr, iface, plug, adjusted iface, this ptr offs, handler, post
   582 		CVector<int> removehooks;
   583 		m_HookIDMan.FindAllHooks(removehooks, tmp.m_Proto, tmp.m_VtblOffs, tmp.m_VtblIdx, adjustediface, plug, thisptr_offs, handler, post);
   584 
   585 		if (removehooks.empty())
   586 			return false;
   587 
   588 		bool status = false;
   589 
   590 		for (CVector<int>::iterator iter = removehooks.begin(); iter != removehooks.end(); ++iter)
   591 		{
   592 			if (RemoveHookByID(plug, *iter))
   593 				status = true;
   594 		}
   595 		return status; 
   596 	}
   597 
   598 	DeprecatedCallClass<void> *CSourceHookImpl::GetCallClass(void *iface, size_t size)
   599 	{
   600 		for (Impl_CallClassList::iterator cciter = m_CallClasses.begin(); cciter != m_CallClasses.end(); ++cciter)
   601 		{
   602 			if (cciter->m_Ptr == iface && cciter->m_ObjSize == size)
   603 			{
   604 				++cciter->m_RefCounter;
   605 				return &(*cciter);
   606 			}
   607 		}
   608 
   609 		// Make a new one
   610 
   611 		CCallClassImpl tmp(iface, size);
   612 		ApplyCallClassPatches(tmp);
   613 		m_CallClasses.push_back(tmp);
   614 		return &m_CallClasses.back();
   615 	}
   616 
   617 	void CSourceHookImpl::ReleaseCallClass(DeprecatedCallClass<void> *ptr)
   618 	{
   619 		Impl_CallClassList::iterator iter = m_CallClasses.find(ptr);
   620 		if (iter == m_CallClasses.end())
   621 			return;
   622 		--iter->m_RefCounter;
   623 		if (iter->m_RefCounter < 1)
   624 			m_CallClasses.erase(iter);
   625 	}
   626 
   627 	void CSourceHookImpl::ApplyCallClassPatches(CCallClassImpl &cc)
   628 	{
   629 		for (HookManContList::iterator hmcl_iter = m_HookMans.begin();
   630 			hmcl_iter != m_HookMans.end(); ++hmcl_iter)
   631 		{
   632 			for (CHookManagerContainer::iterator hookman = hmcl_iter->begin();
   633 				hookman != hmcl_iter->end(); ++hookman)
   634 			{
   635 				for (CHookManagerInfo::VfnPtrListIter vfnptr_iter = hookman->m_VfnPtrs.begin();
   636 					vfnptr_iter != hookman->m_VfnPtrs.end(); ++vfnptr_iter)
   637 				{
   638 					for (CVfnPtr::IfaceListIter iface_iter = vfnptr_iter->m_Ifaces.begin();
   639 						iface_iter != vfnptr_iter->m_Ifaces.end(); ++iface_iter)
   640 					{
   641 						if (iface_iter->m_Ptr >= cc.m_Ptr &&
   642 							iface_iter->m_Ptr < (reinterpret_cast<char*>(cc.m_Ptr) + cc.m_ObjSize))
   643 						{
   644 							cc.ApplyCallClassPatch(static_cast<int>(reinterpret_cast<char*>(iface_iter->m_Ptr) -
   645 								reinterpret_cast<char*>(cc.m_Ptr)) + hookman->m_VtblOffs,
   646 								hookman->m_VtblIdx, vfnptr_iter->m_OrigEntry);
   647 						}
   648 					}
   649 				}
   650 			}
   651 		}
   652 	}
   653 
   654 	void CSourceHookImpl::ApplyCallClassPatches(void *ifaceptr, int vtbl_offs, int vtbl_idx, void *orig_entry)
   655 	{
   656 		for (Impl_CallClassList::iterator cc_iter = m_CallClasses.begin(); cc_iter != m_CallClasses.end();
   657 			++cc_iter)
   658 		{
   659 			if (ifaceptr >= cc_iter->m_Ptr &&
   660 				ifaceptr < (reinterpret_cast<char*>(cc_iter->m_Ptr) + cc_iter->m_ObjSize))
   661 			{
   662 				cc_iter->ApplyCallClassPatch(static_cast<int>(reinterpret_cast<char*>(ifaceptr) -
   663 					reinterpret_cast<char*>(cc_iter->m_Ptr)) + vtbl_offs, vtbl_idx, orig_entry);
   664 			}
   665 		}
   666 	}
   667 
   668 	void CSourceHookImpl::RemoveCallClassPatches(void *ifaceptr, int vtbl_offs, int vtbl_idx)
   669 	{
   670 		for (Impl_CallClassList::iterator cc_iter = m_CallClasses.begin(); cc_iter != m_CallClasses.end();
   671 			++cc_iter)
   672 		{
   673 			if (ifaceptr >= cc_iter->m_Ptr &&
   674 				ifaceptr < (reinterpret_cast<char*>(cc_iter->m_Ptr) + cc_iter->m_ObjSize))
   675 			{
   676 				cc_iter->RemoveCallClassPatch(vtbl_offs, vtbl_idx);
   677 			}
   678 		}
   679 	}
   680 
   681 	void CSourceHookImpl::SetPluginPaused(Plugin plug, bool paused)
   682 	{
   683 		// Go through all hook managers, all interfaces, and set the status of all hooks of this plugin to paused
   684 		for (HookManContList::iterator hmcl_iter = m_HookMans.begin();
   685 			hmcl_iter != m_HookMans.end(); ++hmcl_iter)
   686 		{
   687 			for (CHookManagerContainer::iterator hookmaniter = hmcl_iter->begin();
   688 				hookmaniter != hmcl_iter->end(); ++hookmaniter)
   689 			{
   690 				for (CHookManagerInfo::VfnPtrListIter vfnptr_iter = hookmaniter->m_VfnPtrs.begin();
   691 					vfnptr_iter != hookmaniter->m_VfnPtrs.end(); ++vfnptr_iter)
   692 				{
   693 					for (CVfnPtr::IfaceListIter ifaceiter = vfnptr_iter->m_Ifaces.begin();
   694 						ifaceiter != vfnptr_iter->m_Ifaces.end(); ++ifaceiter)
   695 					{
   696 						for (List<HookInfo>::iterator hookiter = ifaceiter->m_PreHooks.m_List.begin();
   697 							hookiter != ifaceiter->m_PreHooks.m_List.end(); ++hookiter)
   698 							if (plug == hookiter->plug)
   699 								hookiter->paused = paused;
   700 
   701 						for (List<HookInfo>::iterator hookiter = ifaceiter->m_PostHooks.m_List.begin();
   702 							hookiter != ifaceiter->m_PostHooks.m_List.end(); ++hookiter)
   703 							if (plug == hookiter->plug)
   704 								hookiter->paused = paused;
   705 					}
   706 				}
   707 			}
   708 		}
   709 	}
   710 	void CSourceHookImpl::PausePlugin(Plugin plug)
   711 	{
   712 		SetPluginPaused(plug, true);
   713 	}
   714 
   715 	void CSourceHookImpl::UnpausePlugin(Plugin plug)
   716 	{
   717 		SetPluginPaused(plug, false);
   718 	}
   719 
   720 	void CSourceHookImpl::HookLoopBegin(IIface *pIface)
   721 	{
   722 		HookLoopInfo hli = {0};
   723 		hli.pCurIface = pIface;
   724 		hli.shouldContinue = true;
   725 		hli.recall = HookLoopInfo::Recall_No;
   726 
   727 		static_cast<CIface*>(pIface)->m_PreHooks.RQFlagReset();
   728 		static_cast<CIface*>(pIface)->m_PostHooks.RQFlagReset();
   729 
   730 		m_HLIStack.push(hli);
   731 	}
   732 
   733 	void CSourceHookImpl::HookLoopEnd()
   734 	{
   735 		// When in a post recall... make sure status is high enough so that it returns the orig ret.
   736 		if (m_HLIStack.size() > 1 && m_HLIStack.second().recall == HookLoopInfo::Recall_Post2)
   737 			*m_HLIStack.front().pStatus = MRES_SUPERCEDE;			// THAT'LL TEACH THEM!
   738 		m_HLIStack.pop();
   739 	}
   740 
   741 	void CSourceHookImpl::SetRes(META_RES res)
   742 	{
   743 		*m_HLIStack.front().pCurRes = res;
   744 	}
   745 
   746 	META_RES CSourceHookImpl::GetPrevRes()
   747 	{
   748 		return *m_HLIStack.front().pPrevRes;
   749 	}
   750 
   751 	META_RES CSourceHookImpl::GetStatus()
   752 	{
   753 		return *m_HLIStack.front().pStatus;
   754 	}
   755 
   756 	const void *CSourceHookImpl::GetOrigRet()
   757 	{
   758 		// When in a post recall... return the orig ret of the previous hookloop.
   759 		if (m_HLIStack.size() > 1 && m_HLIStack.second().recall == HookLoopInfo::Recall_Post2)
   760 			return m_HLIStack.second().pOrigRet;
   761 
   762 		return m_HLIStack.front().pOrigRet;
   763 	}
   764 
   765 	const void *CSourceHookImpl::GetOverrideRet()
   766 	{
   767 		// pOverrideRet is always set since recalls were introduced
   768 		// GetOverrideRetPtr was added; a function which always returns pOverrideRet
   769 		// so that RETURN_META_VALUE_NEWPARAMS can provide an override result
   770 
   771 		// This means that we have to filter GetOverrideRet:
   772 		//  If the status variable is < MRES_OVERRIDE, return NULL.
   773 
   774 		return (*m_HLIStack.front().pStatus < MRES_OVERRIDE) ?
   775 			NULL : m_HLIStack.front().pOverrideRet;
   776 	}
   777 
   778 	void *CSourceHookImpl::GetOverrideRetPtr()
   779 	{
   780 		// As described in the comment above: always return pOverrideRet
   781 		return m_HLIStack.front().pOverrideRet;
   782 	}
   783 
   784 	void *CSourceHookImpl::GetIfacePtr()
   785 	{
   786 		return *m_HLIStack.front().pIfacePtrPtr;
   787 	}
   788 
   789 	void CSourceHookImpl::SetCurResPtr(META_RES *mres)
   790 	{
   791 		m_HLIStack.front().pCurRes = mres;
   792 	}
   793 
   794 	void CSourceHookImpl::SetPrevResPtr(META_RES *mres)
   795 	{
   796 		m_HLIStack.front().pPrevRes = mres;
   797 
   798 		// If we're recalling, drag the previous mres value to the new hookfunc
   799 		if (m_HLIStack.size() > 1 && m_HLIStack.second().recall)
   800 			*mres = *m_HLIStack.second().pPrevRes;
   801 	}
   802 
   803 	void CSourceHookImpl::SetStatusPtr(META_RES *mres)
   804 	{
   805 		m_HLIStack.front().pStatus = mres;
   806 
   807 		// If we're recalling, drag the previous mres value to the new hookfunc
   808 		if (m_HLIStack.size() > 1 && m_HLIStack.second().recall)
   809 			*mres = *m_HLIStack.second().pStatus;
   810 	}
   811 
   812 	void CSourceHookImpl::SetIfacePtrPtr(void **pp)
   813 	{
   814 		m_HLIStack.front().pIfacePtrPtr = pp;
   815 	}
   816 
   817 	void CSourceHookImpl::SetOrigRetPtr(const void *ptr)
   818 	{
   819 		m_HLIStack.front().pOrigRet = ptr;
   820 	}
   821 	void CSourceHookImpl::SetOverrideRetPtr(void *ptr)
   822 	{
   823 		m_HLIStack.front().pOverrideRet = ptr;
   824 	}
   825 
   826 	// New function which does all of the above + more :)
   827 	void *CSourceHookImpl::SetupHookLoop(META_RES *statusPtr, META_RES *prevResPtr, META_RES *curResPtr,
   828 		void **ifacePtrPtr, const void *origRetPtr, void *overrideRetPtr)
   829 	{
   830 		HookLoopInfo &hli = m_HLIStack.front();
   831 		hli.pStatus = statusPtr;
   832 		hli.pPrevRes = prevResPtr;
   833 		hli.pCurRes = curResPtr;
   834 		hli.pIfacePtrPtr = ifacePtrPtr;
   835 		hli.pOrigRet = origRetPtr;
   836 
   837 		// Handle some recall stuff
   838 		if (m_HLIStack.size() > 1 && m_HLIStack.second().recall)
   839 		{
   840 			HookLoopInfo &other = m_HLIStack.second();
   841 			*statusPtr = *other.pStatus;
   842 			*prevResPtr = *other.pStatus;
   843 
   844 			// When the status is low so there's no override return value and we're in a post recall,
   845 			// give it the orig return value as override return value.
   846 			if (*statusPtr < MRES_OVERRIDE && other.recall == HookLoopInfo::Recall_Post1)
   847 				hli.pOverrideRet = const_cast<void*>(other.pOrigRet);
   848 			else	// Otherwise, transfer override ret normally
   849 				hli.pOverrideRet = other.pOverrideRet;
   850 		}
   851 		else
   852 			hli.pOverrideRet = overrideRetPtr;
   853 
   854 		// Tell the hook func which override ret ptr to use
   855 		return hli.pOverrideRet;
   856 	}
   857 
   858 	bool CSourceHookImpl::ShouldContinue()
   859 	{
   860 		// If recall is true, we shall not continue either.
   861 		// This is because, if it's true and ShouldContinue is called, it suggests that the
   862 		// actual recall is done and that we are back in the original handler which shall return
   863 		// immediately.
   864 
   865 		// Post-recalls:
   866 		//  The second element on the stack has recall set to Recall_Post1.
   867 		//  This means that we want to skip this part and the original function calling thing, so
   868 		//  we store the status mres value, set status to MRES_SUPERCEDE, and return false.
   869 		//  We also set the recall flag to Recall_Post2, so the next time the thing calls us, we
   870 		//  can return true (so that the thing goes into post hooks).
   871 		if (m_HLIStack.size() > 1)
   872 		{
   873 			if (m_HLIStack.second().recall == HookLoopInfo::Recall_Post1)
   874 			{
   875 				m_HLIStack.front().temporaryStatus = *m_HLIStack.front().pStatus;
   876 				*m_HLIStack.front().pStatus = MRES_SUPERCEDE;
   877 				m_HLIStack.second().recall = HookLoopInfo::Recall_Post2;
   878 				return false;
   879 			}
   880 			else if (m_HLIStack.second().recall == HookLoopInfo::Recall_Post2)
   881 			{
   882 				*m_HLIStack.front().pStatus = m_HLIStack.front().temporaryStatus;
   883 				return m_HLIStack.front().shouldContinue;
   884 			}
   885 		}
   886 		return m_HLIStack.front().shouldContinue && !m_HLIStack.front().recall;
   887 	}
   888 
   889 	void CSourceHookImpl::DoRecall()
   890 	{
   891 		if (!m_HLIStack.empty())
   892 		{
   893 			// Also watch out for post recalls! Described at the beginning of sourcehook_impl.h
   894 			m_HLIStack.front().recall =
   895 				static_cast<CIface*>(m_HLIStack.front().pCurIface)->m_PostHooks.RQFlagGet() ?
   896 				HookLoopInfo::Recall_Post1 : HookLoopInfo::Recall_Pre;
   897 			
   898 			CHookList *mlist = static_cast<CHookList*>(m_HLIStack.front().recall == HookLoopInfo::Recall_Pre ? 
   899 				m_HLIStack.front().pCurIface->GetPreHooks() : m_HLIStack.front().pCurIface->GetPostHooks());
   900 			mlist->m_Recall = true;
   901 
   902 			// The hookfunc usually does this, but it won't have a chance to see it, 
   903 			// so for recalls, we update status here if it's required
   904 			if (*m_HLIStack.front().pCurRes > *m_HLIStack.front().pStatus) 
   905 				*m_HLIStack.front().pStatus = *m_HLIStack.front().pCurRes;
   906 
   907 		}
   908 	}
   909 
   910 	void CSourceHookImpl::SetIgnoreHooks(Plugin plug, void *vfnptr)
   911 	{
   912 		m_OneIgnore = vfnptr;
   913 	}
   914 
   915 	void CSourceHookImpl::ResetIgnoreHooks(Plugin plug, void *vfnptr)
   916 	{
   917 		m_OneIgnore = NULL;
   918 	}
   919 
   920 	////////////////////////////
   921 	// CCallClassImpl
   922 	////////////////////////////
   923 	CSourceHookImpl::CCallClassImpl::CCallClassImpl(void *ptr, size_t size)
   924 		: m_Ptr(ptr), m_ObjSize(size), m_RefCounter(1)
   925 	{
   926 	}
   927 	CSourceHookImpl::CCallClassImpl::~CCallClassImpl()
   928 	{
   929 	}
   930 
   931 	void *CSourceHookImpl::CCallClassImpl::GetThisPtr()
   932 	{
   933 		return m_Ptr;
   934 	}
   935 	void *CSourceHookImpl::CCallClassImpl::GetOrigFunc(int vtbloffs, int vtblidx)
   936 	{
   937 		OrigVTables::iterator iter = m_VT.find(vtbloffs);
   938 		if (iter != m_VT.end() && iter->val.size() > (size_t)vtblidx)
   939 		{
   940 			return iter->val[vtblidx];
   941 		}
   942 		return NULL;
   943 	}
   944 
   945 	void CSourceHookImpl::CCallClassImpl::ApplyCallClassPatch(int vtbl_offs, int vtbl_idx, void *orig_entry)
   946 	{
   947 		OrigFuncs &tmpvec = m_VT[vtbl_offs];
   948 		if (tmpvec.size() <= (size_t)vtbl_idx)
   949 			tmpvec.resize(vtbl_idx+1, NULL);
   950 		tmpvec[vtbl_idx] = orig_entry;
   951 	}
   952 	void CSourceHookImpl::CCallClassImpl::RemoveCallClassPatch(int vtbl_offs, int vtbl_idx)
   953 	{
   954 		OrigVTables::iterator iter = m_VT.find(vtbl_offs);
   955 		if (iter != m_VT.end())
   956 		{
   957 			if (iter->val.size() > (size_t)vtbl_idx)
   958 			{
   959 				iter->val[vtbl_idx] = 0;
   960 
   961 				OrigFuncs &of = iter->val;
   962 				OrigFuncs::iterator lastused = of.end();
   963 				for (OrigFuncs::iterator viter = of.begin(); viter != of.end(); ++viter)
   964 				{
   965 					if (*viter)
   966 						lastused = viter;
   967 				}
   968 				if (lastused == of.end())
   969 				{
   970 					// No used element => Remove the whole vector
   971 					m_VT.erase(iter);
   972 					return;
   973 				}
   974 				of.resize(lastused - of.begin() + 1);
   975 			}
   976 		}
   977 	}
   978 
   979 	////////////////////////////
   980 	// CHookManagerInfo
   981 	////////////////////////////
   982 	CSourceHookImpl::CHookManagerInfo::CHookManagerInfo() : m_HookManVersion(0)
   983 	{
   984 	}
   985 	CSourceHookImpl::CHookManagerInfo::~CHookManagerInfo()
   986 	{
   987 	}
   988 
   989 	IVfnPtr *CSourceHookImpl::CHookManagerInfo::FindVfnPtr(void *vfnptr)
   990 	{
   991 		VfnPtrListIter iter = m_VfnPtrs.find(vfnptr);
   992 		return iter == m_VfnPtrs.end() ? NULL : &(*iter);
   993 	}
   994 	void CSourceHookImpl::CHookManagerInfo::SetInfo(int vtbl_offs, int vtbl_idx, const char *proto)
   995 	{
   996 		m_VtblOffs = vtbl_offs;
   997 		m_VtblIdx = vtbl_idx;
   998 		m_Proto = proto;
   999 	}
  1000 	void CSourceHookImpl::CHookManagerInfo::SetHookfuncVfnptr(void *hookfunc_vfnptr)
  1001 	{
  1002 		m_HookfuncVfnptr = hookfunc_vfnptr;
  1003 	}
  1004 	void CSourceHookImpl::CHookManagerInfo::SetVersion(int version)
  1005 	{
  1006 		m_HookManVersion = version;
  1007 	}
  1008 	////////////////////////////
  1009 	// CVfnPtr
  1010 	////////////////////////////
  1011 
  1012 
  1013 	// If you get a crash here, the ptr passed is invalid
  1014 	// This usually means a SH_DECL_MANUALHOOK* with wrong thisptroffs/vtbloffs/vtblidx
  1015 	CSourceHookImpl::CVfnPtr::CVfnPtr(void *ptr, void **pOneIgnore) : m_Ptr(ptr), 
  1016 		m_OrigEntry(*reinterpret_cast<void**>(ptr)), m_pOneIgnore(pOneIgnore)
  1017 	{
  1018 	}
  1019 	CSourceHookImpl::CVfnPtr::~CVfnPtr()
  1020 	{
  1021 	}
  1022 
  1023 	void *CSourceHookImpl::CVfnPtr::GetVfnPtr()
  1024 	{
  1025 		return m_Ptr;
  1026 	}
  1027 
  1028 	void *CSourceHookImpl::CVfnPtr::GetOrigEntry()
  1029 	{
  1030 		return m_OrigEntry;
  1031 	}
  1032 
  1033 	IIface *CSourceHookImpl::CVfnPtr::FindIface(void *ptr)
  1034 	{
  1035 		if (m_Ptr == *m_pOneIgnore)
  1036 		{
  1037 			*m_pOneIgnore = NULL;		// Only once!
  1038 			return NULL;
  1039 		}
  1040 
  1041 		IfaceListIter iter = m_Ifaces.find(ptr);
  1042 		
  1043 		// If nothing is found, check for a NULL-interface (VP hooks only)
  1044 		if (iter == m_Ifaces.end())
  1045 		{
  1046 			iter = m_Ifaces.find((void*)0);
  1047 			return iter == m_Ifaces.end() ? NULL : &(*iter);
  1048 		}
  1049 		else
  1050 		{
  1051 			return &(*iter);
  1052 		}
  1053 	}
  1054 
  1055 	////////////////////////////
  1056 	// CIface
  1057 	////////////////////////////
  1058 	CSourceHookImpl::CIface::CIface(void *ptr) : m_Ptr(ptr)
  1059 	{
  1060 	}
  1061 	CSourceHookImpl::CIface::~CIface()
  1062 	{
  1063 	}
  1064 
  1065 	void *CSourceHookImpl::CIface::GetPtr()
  1066 	{
  1067 		return m_Ptr;
  1068 	}
  1069 
  1070 	IHookList *CSourceHookImpl::CIface::GetPreHooks()
  1071 	{
  1072 		return &m_PreHooks;
  1073 	}
  1074 	IHookList *CSourceHookImpl::CIface::GetPostHooks()
  1075 	{
  1076 		return &m_PostHooks;
  1077 	}
  1078 
  1079 	////////////////////////////
  1080 	// CHookList
  1081 	////////////////////////////
  1082 
  1083 	CSourceHookImpl::CHookList::CHookList() : m_VPList(NULL), m_FreeIters(NULL), m_UsedIters(NULL),
  1084 		m_Recall(false)
  1085 	{
  1086 	}
  1087 	CSourceHookImpl::CHookList::CHookList(const CHookList &other) : m_VPList(other.m_VPList), m_List(other.m_List),
  1088 		m_FreeIters(NULL), m_UsedIters(NULL), m_Recall(false)
  1089 	{
  1090 	}
  1091 
  1092 	CSourceHookImpl::CHookList::~CHookList()
  1093 	{
  1094 		while (m_FreeIters)
  1095 		{
  1096 			CIter *iter = m_FreeIters->m_pNext;
  1097 			delete m_FreeIters;
  1098 			m_FreeIters = iter;
  1099 		}
  1100 		while (m_UsedIters)
  1101 		{
  1102 			CIter *iter = m_UsedIters->m_pNext;
  1103 			delete m_UsedIters;
  1104 			m_UsedIters = iter;
  1105 		}
  1106 	}
  1107 	IHookList::IIter *CSourceHookImpl::CHookList::GetIter()
  1108 	{
  1109 		m_RQFlag = true;
  1110 
  1111 		CIter *ret;
  1112 		if (m_FreeIters)
  1113 		{
  1114 			ret = m_FreeIters;
  1115 			m_FreeIters = ret->m_pNext;
  1116 			ret->GoToBegin();
  1117 		}
  1118 		else
  1119 		{
  1120 			ret = new CIter(this);
  1121 		}
  1122 		
  1123 		// Muuuh, if we're recalling, it shall be a copy of the last iterator, incremented by one
  1124 		if (m_Recall && m_UsedIters)
  1125 		{
  1126 			ret->Set(m_UsedIters);		// m_UsedIters is the last returned and not released iterator
  1127 			ret->Next();				// Use next instead of directly incrementing its m_Iter:
  1128 										// skips paused plugins
  1129 		}
  1130 
  1131 		ret->m_pNext = m_UsedIters;
  1132 		ret->m_pPrev = NULL;
  1133 		if (m_UsedIters)
  1134 			m_UsedIters->m_pPrev = ret;
  1135 		m_UsedIters = ret;
  1136 
  1137 		m_Recall = false;
  1138 
  1139 		return ret;
  1140 	}
  1141 	void CSourceHookImpl::CHookList::ReleaseIter(IIter *pIter)
  1142 	{
  1143 		CIter *pIter2 = static_cast<CIter*>(pIter);
  1144 
  1145 		// Unlink from m_UsedIters
  1146 
  1147 		if (pIter2->m_pNext)
  1148 			pIter2->m_pNext->m_pPrev = pIter2->m_pPrev;
  1149 		if (pIter2->m_pPrev)
  1150 			pIter2->m_pPrev->m_pNext = pIter2->m_pNext;
  1151 		if (pIter2 == m_UsedIters)
  1152 			m_UsedIters = NULL;
  1153 
  1154 		// Link to m_FreeIters
  1155 
  1156 		pIter2->m_pNext = m_FreeIters;
  1157 
  1158 		m_FreeIters = pIter2;
  1159 
  1160 		// Reset recall state.
  1161 		m_Recall = false;
  1162 	}
  1163 
  1164 	void CSourceHookImpl::CHookList::SetVPList(List<HookInfo> *newList)
  1165 	{
  1166 		m_VPList = newList;
  1167 
  1168 		// Update cached CIter objects
  1169 
  1170 		CIter *pTmp;
  1171 		pTmp = m_FreeIters;
  1172 		while (pTmp)
  1173 		{
  1174 			pTmp->m_Iter.SetListLeft(m_VPList);
  1175 			pTmp = pTmp->m_pNext;
  1176 		}
  1177 
  1178 		pTmp = m_UsedIters;
  1179 		while (pTmp)
  1180 		{
  1181 			pTmp->m_Iter.SetListLeft(m_VPList);
  1182 			pTmp = pTmp->m_pNext;
  1183 		}
  1184 	}
  1185 
  1186 	void CSourceHookImpl::CHookList::ClearVPList()
  1187 	{
  1188 		SetVPList(NULL);
  1189 	}
  1190 
  1191 	CSourceHookImpl::CHookList::CIter::CIter(CHookList *pList) : m_pList(pList), 
  1192 		m_Iter(pList->m_VPList, &m_pList->m_List), m_pNext(NULL)
  1193 	{
  1194 	}
  1195 	CSourceHookImpl::CHookList::CIter::~CIter()
  1196 	{
  1197 	}
  1198 
  1199 	void CSourceHookImpl::CHookList::CIter::Set(CIter *pOther)
  1200 	{
  1201 		m_Iter = pOther->m_Iter;
  1202 	}
  1203 
  1204 	void CSourceHookImpl::CHookList::CIter::GoToBegin()
  1205 	{
  1206 		m_Iter.GoToBegin();
  1207 		SkipPaused();
  1208 	}
  1209 
  1210 	bool CSourceHookImpl::CHookList::CIter::End()
  1211 	{
  1212 		if (!m_pList)
  1213 			return false;
  1214 		return m_Iter.End();;
  1215 	}
  1216 	void CSourceHookImpl::CHookList::CIter::Next()
  1217 	{
  1218 		if (!m_pList)
  1219 			return;
  1220 		++m_Iter;
  1221 		SkipPaused();
  1222 	}
  1223 	void CSourceHookImpl::CHookList::CIter::Clear()
  1224 	{
  1225 		m_pList = NULL;
  1226 	}
  1227 	void CSourceHookImpl::CHookList::CIter::SkipPaused()
  1228 	{
  1229 		while (!m_Iter.End() && m_Iter->paused)
  1230 			++m_Iter;
  1231 	}
  1232 
  1233 	ISHDelegate *CSourceHookImpl::CHookList::CIter::Handler()
  1234 	{
  1235 		return m_Iter->handler;
  1236 	}
  1237 	int CSourceHookImpl::CHookList::CIter::ThisPtrOffs()
  1238 	{
  1239 		return m_Iter->thisptr_offs;
  1240 	}
  1241 
  1242 	//////////////////////////////////////////////////////////////////////////
  1243 	// CProto
  1244 	//////////////////////////////////////////////////////////////////////////
  1245 	char *CSourceHookImpl::CProto::DupProto(const char *p)
  1246 	{
  1247 		if (!p)
  1248 			return NULL;
  1249 
  1250 		char *newproto;
  1251 		if (*p)
  1252 		{
  1253 			size_t len = strlen(p);
  1254 			newproto = new char[len+1];
  1255 			memcpy(newproto, p, len+1);
  1256 		} else {
  1257 			const ProtoInfo *pi1 = reinterpret_cast<const ProtoInfo *>(p);
  1258 			int *ar_copy = new int[pi1->numOfParams + 1];
  1259 			for (int i = 0; i <= pi1->numOfParams; i++)
  1260 				ar_copy[i] = pi1->params[i];
  1261 			ProtoInfo *copy = new ProtoInfo(pi1->retTypeSize, pi1->numOfParams, ar_copy);
  1262 			newproto = reinterpret_cast<char *>(copy);
  1263 		}
  1264 
  1265 		return newproto;
  1266 	}
  1267 
  1268 	void CSourceHookImpl::CProto::FreeProto(char *prot)
  1269 	{
  1270 		if (!prot)
  1271 			return;
  1272 
  1273 		if (*prot)
  1274 		{
  1275 			delete [] prot;
  1276 		} else {
  1277 			ProtoInfo *pi = reinterpret_cast<ProtoInfo *>(prot);
  1278 			delete [] pi->params;
  1279 			delete pi;
  1280 		}
  1281 	}
  1282 
  1283 	bool CSourceHookImpl::CProto::Equal(const char *p1, const char *p2)
  1284 	{
  1285 		if (!p1 || !p2)
  1286 			return false;
  1287 
  1288 		if (*p1 && *p2)			// Case1: Both old
  1289 		{
  1290 			// As in old versions
  1291 			return strcmp(p1, p2) == 0;
  1292 		}
  1293 		else if (!*p1 && !*p2)	// Case2: Both new
  1294 		{
  1295 			const ProtoInfo *pi1 = reinterpret_cast<const ProtoInfo*>(p1);
  1296 			const ProtoInfo *pi2 = reinterpret_cast<const ProtoInfo*>(p2);
  1297 
  1298 			if (pi1->retTypeSize == pi2->retTypeSize &&
  1299 				pi1->numOfParams == pi2->numOfParams)
  1300 			{
  1301 				// params[0] is 0 for "normal" functions and -1 for vararg functions
  1302 				// params[1] is size of first parameter
  1303 				// params[2] is size of second parameter ...
  1304 				for (int i = 0; i <= pi1->numOfParams; ++i)
  1305 				{
  1306 					if (pi1->params[i] != pi2->params[i])
  1307 						return false;
  1308 				}
  1309 				return true;
  1310 			}
  1311 			else
  1312 			{
  1313 				return false;
  1314 			}
  1315 		}
  1316 		else					// Case3: Mixed old/new
  1317 		{
  1318 			// Trust the user
  1319 			return true;
  1320 		}
  1321 	}
  1322 
  1323 
  1324 	//////////////////////////////////////////////////////////////////////////
  1325 	// CHookManagerContainer
  1326 	//////////////////////////////////////////////////////////////////////////
  1327 	void CSourceHookImpl::CHookManagerContainer::AddHookManager(Plugin plug, const CHookManagerInfo &hookman)
  1328 	{
  1329 		iterator iter;
  1330 		// Check whether such a hook manager already exists; if yes, ignore.
  1331 		for (iter = begin(); iter != end(); ++iter)
  1332 		{
  1333 			if (iter->m_Plug == plug && iter->m_Func == hookman.m_Func)
  1334 				return;
  1335 		}
  1336 
  1337 		// It doesn't -> add it. Add it to the end of its version group.
  1338 		for (iter = begin(); iter != end(); ++iter)
  1339 		{
  1340 			if (iter->m_HookManVersion < hookman.m_HookManVersion)
  1341 				break;
  1342 		}
  1343 
  1344 		bool isBeginning = iter == begin();
  1345 
  1346 		insert(iter, hookman);
  1347 
  1348 		// If we inserted it at the beginning and if the dam breaks open many years too soon
  1349 		// and if there is more than one hookman and if the second one isn't empty, transfer
  1350 		// hooks from second to first
  1351 
  1352 		if (isBeginning && size() > 1)
  1353 		{
  1354 			iter = begin();
  1355 			iterator second = iter;
  1356 			++second;
  1357 
  1358 			if (!second->m_VfnPtrs.empty())
  1359 			{
  1360 				// Move the vfnptrs from the old hook manager to the new one
  1361 				iter->m_VfnPtrs = second->m_VfnPtrs;
  1362 				second->m_VfnPtrs.clear();
  1363 
  1364 				// Unregister the old one, register the new one
  1365 				second->m_Func(HA_Unregister, NULL);
  1366 				iter->m_Func(HA_Register, &(*iter));
  1367 
  1368 				// Go through all vfnptrs in this hookman and patch them to point to the new manager's handler!
  1369 				// or whatever
  1370 				for (CHookManagerInfo::VfnPtrListIter vfnptr_iter = iter->m_VfnPtrs.begin();
  1371 					vfnptr_iter != iter->m_VfnPtrs.end(); ++vfnptr_iter)
  1372 				{
  1373 					// And DEREFERENCE newHookMan->m_HookfuncVfnptr!
  1374 					// otherwise it will be executing the vtable... had to find out the hard way
  1375 					*reinterpret_cast<void**>(vfnptr_iter->m_Ptr) = *reinterpret_cast<void**>(iter->m_HookfuncVfnptr);
  1376 				}
  1377 			}
  1378 		}
  1379 	}
  1380 
  1381 	//////////////////////////////////////////////////////////////////////////
  1382 	// CHookIDManager
  1383 	//////////////////////////////////////////////////////////////////////////
  1384 	CSourceHookImpl::CHookIDManager::CHookIDManager()
  1385 	{
  1386 	}
  1387 
  1388 	int CSourceHookImpl::CHookIDManager::New(const CProto &proto, int vtbl_offs, int vtbl_idx, void *vfnptr,
  1389 		void *adjustediface, Plugin plug, int thisptr_offs, ISHDelegate *handler, bool post)
  1390 	{
  1391 		Entry tmp(proto, vtbl_offs, vtbl_idx, vfnptr, adjustediface, plug, thisptr_offs, handler, post);
  1392 
  1393 		size_t cursize = m_Entries.size();
  1394 		for (size_t i = 0; i < cursize; ++i)
  1395 		{
  1396 			if (m_Entries[i].isfree)
  1397 			{
  1398 				m_Entries[i] = tmp;
  1399 				return static_cast<int>(i) + 1;
  1400 			}
  1401 		}
  1402 
  1403 		m_Entries.push_back(tmp);
  1404 		return static_cast<int>(m_Entries.size());		// return size() because hookid = id+1 anyway
  1405 	}
  1406 
  1407 	bool CSourceHookImpl::CHookIDManager::Remove(int hookid)
  1408 	{
  1409 		int realid = hookid - 1;
  1410 		if (realid < 0 || realid >= static_cast<int>(m_Entries.size()) || m_Entries[realid].isfree)
  1411 			return false;
  1412 
  1413 		m_Entries[realid].isfree = true;
  1414 
  1415 		// :TODO: remove free ids from back sometimes ??
  1416 
  1417 		return true;
  1418 	}
  1419 
  1420 	const CSourceHookImpl::CHookIDManager::Entry * CSourceHookImpl::CHookIDManager::QueryHook(int hookid)
  1421 	{
  1422 		int realid = hookid - 1;
  1423 		if (realid < 0 || realid >= static_cast<int>(m_Entries.size()) || m_Entries[realid].isfree)
  1424 			return NULL;
  1425 
  1426 		return &m_Entries[realid];
  1427 	}
  1428 
  1429 	void CSourceHookImpl::CHookIDManager::FindAllHooks(CVector<int> &output, const CProto &proto, int vtbl_offs,
  1430 		int vtbl_idx, void *adjustediface, Plugin plug, int thisptr_offs, ISHDelegate *handler, bool post)
  1431 	{
  1432 		// oh my god, a lot of parameters...
  1433 		size_t cursize = m_Entries.size();
  1434 		for (size_t i = 0; i < cursize; ++i)
  1435 		{
  1436 			if (!m_Entries[i].isfree && m_Entries[i].proto == proto && m_Entries[i].vtbl_offs == vtbl_offs &&
  1437 				m_Entries[i].vtbl_idx == vtbl_idx && m_Entries[i].adjustediface == adjustediface && m_Entries[i].plug == plug &&
  1438 				m_Entries[i].thisptr_offs == thisptr_offs && m_Entries[i].handler->IsEqual(handler) && m_Entries[i].post == post)
  1439 			{
  1440 				output.push_back(static_cast<int>(i) + 1);
  1441 			}
  1442 		}
  1443 	} 
  1444 }