core-legacy/sourcehook/sourcehook.cpp
author David Anderson <dvander@alliedmods.net>
Wed Feb 25 20:26:19 2009 -0500 (2009-02-25)
changeset 649 a0e24af92af0
parent 545 07e5df11f9fc
child 659 b35a5fdbc654
permissions -rw-r--r--
Bumped all versions.
     1 /* ======== SourceHook ========
     2 * Copyright (C) 2004-2008 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()
    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 	bool CSourceHookImpl::AddHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan, ISHDelegate *handler, bool post)
   281 	{
   282 		void *adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface) + thisptr_offs);
   283 
   284 		// 1) Get info about the hook manager
   285 		CHookManagerInfo tmp;
   286 		if (myHookMan(HA_GetInfo, &tmp) != 0)
   287 			return false;
   288 
   289 		tmp.m_Func = myHookMan;
   290 		tmp.m_Plug = plug;
   291 
   292 		CHookManagerContainer::HMCI hmci(tmp.m_Proto, tmp.m_VtblOffs, tmp.m_VtblIdx);
   293 
   294 		void **cur_vtptr = *reinterpret_cast<void***>(
   295 			reinterpret_cast<char*>(adjustediface) + tmp.m_VtblOffs);
   296 		void *cur_vfnptr = reinterpret_cast<void*>(cur_vtptr + tmp.m_VtblIdx);
   297 
   298 		// Add the container if not already added
   299 		HookManContList::iterator hmcl_iter = m_HookMans.find(hmci);
   300 		if (hmcl_iter == m_HookMans.end())
   301 		{
   302 			m_HookMans.push_back(CHookManagerContainer(hmci));
   303 			hmcl_iter = m_HookMans.end();
   304 			--hmcl_iter;
   305 		}
   306 
   307 		hmcl_iter->AddHookManager(plug, tmp);
   308 
   309 		CHookManagerContainer::iterator hookman = hmcl_iter->begin();
   310 		SH_ASSERT(hookman != hmcl_iter->end(), ("No hookman found - but we've just added one!"));
   311 
   312 		// Check whether any other container holds a hook manager which holds this vfnptr
   313 		// If yes, it means that the two are incompatible, so return false.
   314 		for (HookManContList::iterator hmcl_iter2 = m_HookMans.begin();
   315 			hmcl_iter2 != m_HookMans.end(); ++hmcl_iter2)
   316 		{
   317 			if (hmcl_iter2 != hmcl_iter)
   318 			{
   319 				for (CHookManagerContainer::iterator hmil_iter = hmcl_iter2->begin();
   320 					hmil_iter != hmcl_iter2->end(); ++hmil_iter)
   321 				{
   322 					if (hmil_iter->m_VfnPtrs.find(cur_vfnptr) != hmil_iter->m_VfnPtrs.end())
   323 						return false;
   324 				}
   325 			}
   326 		}
   327 
   328 		// Tell it to store the pointer if it's not already active
   329 		if (hookman->m_VfnPtrs.empty())
   330 			hookman->m_Func(HA_Register, &(*hookman));
   331 
   332 		CHookManagerInfo::VfnPtrListIter vfnptr_iter = hookman->m_VfnPtrs.find(cur_vfnptr);
   333 
   334 		if (vfnptr_iter == hookman->m_VfnPtrs.end())
   335 		{
   336 			// Add a new one
   337 			CVfnPtr vfp(cur_vfnptr);
   338 
   339 			// Alter vtable entry
   340 			if (!SetMemAccess(cur_vtptr, sizeof(void*) * (tmp.m_VtblIdx + 1), SH_MEM_READ | SH_MEM_WRITE))
   341 				return false;
   342 
   343 			*reinterpret_cast<void**>(cur_vfnptr) = *reinterpret_cast<void**>(hookman->m_HookfuncVfnptr);
   344 
   345 			hookman->m_VfnPtrs.push_back(vfp);
   346 
   347 			// Make vfnptr_iter point to the new element
   348 			vfnptr_iter = hookman->m_VfnPtrs.end();
   349 			--vfnptr_iter;
   350 
   351 			// Now that it is done, check whether we have to update any callclasses
   352 			ApplyCallClassPatches(adjustediface, tmp.m_VtblOffs, tmp.m_VtblIdx, vfp.m_OrigEntry);
   353 		}
   354 
   355 		CVfnPtr::IfaceListIter iface_iter = vfnptr_iter->m_Ifaces.find(adjustediface);
   356 		if (iface_iter == vfnptr_iter->m_Ifaces.end())
   357 		{
   358 			// Add a new one
   359 			vfnptr_iter->m_Ifaces.push_back(CIface(adjustediface));
   360 
   361 			// Make iface_iter point to the new element
   362 			iface_iter = vfnptr_iter->m_Ifaces.end();
   363 			--iface_iter;
   364 		}
   365 
   366 		// Add the hook
   367 		HookInfo hookinfo;
   368 		hookinfo.handler = handler;
   369 		hookinfo.plug = plug;
   370 		hookinfo.paused = false;
   371 		hookinfo.thisptr_offs = thisptr_offs;
   372 		if (post)
   373 			iface_iter->m_PostHooks.m_List.push_back(hookinfo);
   374 		else
   375 			iface_iter->m_PreHooks.m_List.push_back(hookinfo);
   376 
   377 		return true;
   378 	}
   379 
   380 	bool CSourceHookImpl::RemoveHook(RemoveHookInfo info)
   381 	{
   382 		return RemoveHook(info.plug, info.iface, info.thisptr_offs, info.hookman, info.handler, info.post);
   383 	}
   384 
   385 	bool CSourceHookImpl::RemoveHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan, ISHDelegate *handler, bool post)
   386 	{
   387 		void *adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface)+thisptr_offs);
   388 		CHookManagerInfo tmp;
   389 		if (myHookMan(HA_GetInfo, &tmp) != 0)
   390 			return false;
   391 
   392 		// Find the hook manager and the hook
   393 
   394 		HookManContList::iterator hmcl_iter = m_HookMans.find(
   395 			CHookManagerContainer::HMCI(tmp.m_Proto, tmp.m_VtblOffs, tmp.m_VtblIdx));
   396 		if (hmcl_iter == m_HookMans.end() || hmcl_iter->empty())
   397 			return false;
   398 		
   399 		CHookManagerContainer::iterator hookman = hmcl_iter->begin();
   400 
   401 		if (!ModuleInMemory(reinterpret_cast<char*>(adjustediface) + tmp.m_VtblOffs,
   402 			sizeof(void*) * (tmp.m_VtblIdx + 1)))
   403 		{
   404 			// The module the vtable was in is already unloaded.
   405 			hookman->m_VfnPtrs.clear();
   406 			hookman->m_Func(HA_Unregister, NULL);
   407 			return true;
   408 		}
   409 
   410 		void **cur_vtptr = *reinterpret_cast<void***>(
   411 			reinterpret_cast<char*>(adjustediface) + tmp.m_VtblOffs);
   412 		void *cur_vfnptr = reinterpret_cast<void*>(cur_vtptr + tmp.m_VtblIdx);
   413 
   414 		CHookManagerInfo::VfnPtrListIter vfnptr_iter = hookman->m_VfnPtrs.find(cur_vfnptr);
   415 
   416 		if (vfnptr_iter == hookman->m_VfnPtrs.end())
   417 			return false;
   418 
   419 		for (CVfnPtr::IfaceListIter iface_iter = vfnptr_iter->m_Ifaces.begin();
   420 			iface_iter != vfnptr_iter->m_Ifaces.end();)
   421 		{
   422 			if (iface_iter->m_Ptr != adjustediface)
   423 			{
   424 				iface_iter++;
   425 				continue;
   426 			}
   427 			List<HookInfo> &hooks =
   428 				post ? iface_iter->m_PostHooks.m_List : iface_iter->m_PreHooks.m_List;
   429 
   430 			bool erase;
   431 			for (List<HookInfo>::iterator hookiter = hooks.begin();
   432 				hookiter != hooks.end(); )
   433 			{
   434 				erase = hookiter->plug == plug && hookiter->handler->IsEqual(handler) &&
   435 					hookiter->thisptr_offs == thisptr_offs;
   436 				if (erase)
   437 				{
   438 					hookiter->handler->DeleteThis();			// Make the _plugin_ delete the handler object
   439 
   440 					// Move all iterators pointing at this
   441 					List<HookInfo>::iterator oldhookiter = hookiter;
   442 					hookiter = hooks.erase(hookiter);
   443 					List<HookInfo>::iterator newhookiter = hookiter;
   444 					--newhookiter; // The hook loop will ++ it then
   445 					CHookList::CIter *pItIter;
   446 					for (pItIter = iface_iter->m_PreHooks.m_UsedIters; pItIter; pItIter = pItIter->m_pNext)
   447 						if (pItIter->m_Iter == oldhookiter)
   448 							pItIter->m_Iter = newhookiter;
   449 				}
   450 				else
   451 					++hookiter;
   452 			}
   453 			if (iface_iter->m_PostHooks.m_List.empty() && iface_iter->m_PreHooks.m_List.empty())
   454 			{
   455 				// There are no hooks on this iface anymore...
   456 				for (HookLoopInfoStack::iterator hli_iter = m_HLIStack.begin();
   457 					hli_iter != m_HLIStack.end(); ++hli_iter)
   458 				{
   459 					if (hli_iter->pCurIface == static_cast<IIface*>(&(*iface_iter)))
   460 						hli_iter->shouldContinue = false;
   461 				}
   462 
   463 				iface_iter = vfnptr_iter->m_Ifaces.erase(iface_iter);
   464 				if (vfnptr_iter->m_Ifaces.empty())
   465 				{
   466 					// No ifaces at all -> Deactivate the hook
   467 					*reinterpret_cast<void**>(vfnptr_iter->m_Ptr) = vfnptr_iter->m_OrigEntry;
   468 
   469 					hookman->m_VfnPtrs.erase(vfnptr_iter);
   470 
   471 					// Remove callclass patch
   472 					for (Impl_CallClassList::iterator cciter = m_CallClasses.begin(); cciter != m_CallClasses.end(); ++cciter)
   473 						if (cciter->m_Ptr == adjustediface)
   474 							cciter->RemoveCallClassPatch(tmp.m_VtblOffs, tmp.m_VtblIdx);
   475 
   476 					if (hookman->m_VfnPtrs.empty())
   477 					{
   478 						// Unregister the hook manager
   479 						hookman->m_Func(HA_Unregister, NULL);
   480 					}
   481 
   482 					// Don't try to continue looping through ifaces
   483 					// - the list is already invalid
   484 					return true;
   485 				}
   486 			}
   487 			else
   488 				++iface_iter;
   489 		}
   490 		return true;
   491 	}
   492 
   493 	GenericCallClass *CSourceHookImpl::GetCallClass(void *iface, size_t size)
   494 	{
   495 		for (Impl_CallClassList::iterator cciter = m_CallClasses.begin(); cciter != m_CallClasses.end(); ++cciter)
   496 		{
   497 			if (cciter->m_Ptr == iface && cciter->m_ObjSize == size)
   498 			{
   499 				++cciter->m_RefCounter;
   500 				return &(*cciter);
   501 			}
   502 		}
   503 
   504 		// Make a new one
   505 
   506 		CCallClassImpl tmp(iface, size);
   507 		ApplyCallClassPatches(tmp);
   508 		m_CallClasses.push_back(tmp);
   509 		return &m_CallClasses.back();
   510 	}
   511 
   512 	void CSourceHookImpl::ReleaseCallClass(GenericCallClass *ptr)
   513 	{
   514 		Impl_CallClassList::iterator iter = m_CallClasses.find(ptr);
   515 		if (iter == m_CallClasses.end())
   516 			return;
   517 		--iter->m_RefCounter;
   518 		if (iter->m_RefCounter < 1)
   519 			m_CallClasses.erase(iter);
   520 	}
   521 
   522 	void CSourceHookImpl::ApplyCallClassPatches(CCallClassImpl &cc)
   523 	{
   524 		for (HookManContList::iterator hmcl_iter = m_HookMans.begin();
   525 			hmcl_iter != m_HookMans.end(); ++hmcl_iter)
   526 		{
   527 			for (CHookManagerContainer::iterator hookman = hmcl_iter->begin();
   528 				hookman != hmcl_iter->end(); ++hookman)
   529 			{
   530 				for (CHookManagerInfo::VfnPtrListIter vfnptr_iter = hookman->m_VfnPtrs.begin();
   531 					vfnptr_iter != hookman->m_VfnPtrs.end(); ++vfnptr_iter)
   532 				{
   533 					for (CVfnPtr::IfaceListIter iface_iter = vfnptr_iter->m_Ifaces.begin();
   534 						iface_iter != vfnptr_iter->m_Ifaces.end(); ++iface_iter)
   535 					{
   536 						if (iface_iter->m_Ptr >= cc.m_Ptr &&
   537 							iface_iter->m_Ptr < (reinterpret_cast<char*>(cc.m_Ptr) + cc.m_ObjSize))
   538 						{
   539 							cc.ApplyCallClassPatch(static_cast<int>(reinterpret_cast<char*>(iface_iter->m_Ptr) -
   540 								reinterpret_cast<char*>(cc.m_Ptr)) + hookman->m_VtblOffs,
   541 								hookman->m_VtblIdx, vfnptr_iter->m_OrigEntry);
   542 						}
   543 					}
   544 				}
   545 			}
   546 		}
   547 	}
   548 
   549 	void CSourceHookImpl::ApplyCallClassPatches(void *ifaceptr, int vtbl_offs, int vtbl_idx, void *orig_entry)
   550 	{
   551 		for (Impl_CallClassList::iterator cc_iter = m_CallClasses.begin(); cc_iter != m_CallClasses.end();
   552 			++cc_iter)
   553 		{
   554 			if (ifaceptr >= cc_iter->m_Ptr &&
   555 				ifaceptr < (reinterpret_cast<char*>(cc_iter->m_Ptr) + cc_iter->m_ObjSize))
   556 			{
   557 				cc_iter->ApplyCallClassPatch(static_cast<int>(reinterpret_cast<char*>(ifaceptr) -
   558 					reinterpret_cast<char*>(cc_iter->m_Ptr)) + vtbl_offs, vtbl_idx, orig_entry);
   559 			}
   560 		}
   561 	}
   562 
   563 	void CSourceHookImpl::RemoveCallClassPatches(void *ifaceptr, int vtbl_offs, int vtbl_idx)
   564 	{
   565 		for (Impl_CallClassList::iterator cc_iter = m_CallClasses.begin(); cc_iter != m_CallClasses.end();
   566 			++cc_iter)
   567 		{
   568 			if (ifaceptr >= cc_iter->m_Ptr &&
   569 				ifaceptr < (reinterpret_cast<char*>(cc_iter->m_Ptr) + cc_iter->m_ObjSize))
   570 			{
   571 				cc_iter->RemoveCallClassPatch(vtbl_offs, vtbl_idx);
   572 			}
   573 		}
   574 	}
   575 
   576 	void CSourceHookImpl::SetPluginPaused(Plugin plug, bool paused)
   577 	{
   578 		// Go through all hook managers, all interfaces, and set the status of all hooks of this plugin to paused
   579 		for (HookManContList::iterator hmcl_iter = m_HookMans.begin();
   580 			hmcl_iter != m_HookMans.end(); ++hmcl_iter)
   581 		{
   582 			for (CHookManagerContainer::iterator hookmaniter = hmcl_iter->begin();
   583 				hookmaniter != hmcl_iter->end(); ++hookmaniter)
   584 			{
   585 				for (CHookManagerInfo::VfnPtrListIter vfnptr_iter = hookmaniter->m_VfnPtrs.begin();
   586 					vfnptr_iter != hookmaniter->m_VfnPtrs.end(); ++vfnptr_iter)
   587 				{
   588 					for (CVfnPtr::IfaceListIter ifaceiter = vfnptr_iter->m_Ifaces.begin();
   589 						ifaceiter != vfnptr_iter->m_Ifaces.end(); ++ifaceiter)
   590 					{
   591 						for (List<HookInfo>::iterator hookiter = ifaceiter->m_PreHooks.m_List.begin();
   592 							hookiter != ifaceiter->m_PreHooks.m_List.end(); ++hookiter)
   593 							if (plug == hookiter->plug)
   594 								hookiter->paused = paused;
   595 
   596 						for (List<HookInfo>::iterator hookiter = ifaceiter->m_PostHooks.m_List.begin();
   597 							hookiter != ifaceiter->m_PostHooks.m_List.end(); ++hookiter)
   598 							if (plug == hookiter->plug)
   599 								hookiter->paused = paused;
   600 					}
   601 				}
   602 			}
   603 		}
   604 	}
   605 	void CSourceHookImpl::PausePlugin(Plugin plug)
   606 	{
   607 		SetPluginPaused(plug, true);
   608 	}
   609 
   610 	void CSourceHookImpl::UnpausePlugin(Plugin plug)
   611 	{
   612 		SetPluginPaused(plug, false);
   613 	}
   614 
   615 	void CSourceHookImpl::HookLoopBegin(IIface *pIface)
   616 	{
   617 		HookLoopInfo hli;
   618 		hli.pCurIface = pIface;
   619 		hli.shouldContinue = true;
   620 		hli.recall = HookLoopInfo::Recall_No;
   621 
   622 		static_cast<CIface*>(pIface)->m_PreHooks.RQFlagReset();
   623 		static_cast<CIface*>(pIface)->m_PostHooks.RQFlagReset();
   624 
   625 		m_HLIStack.push(hli);
   626 	}
   627 
   628 	void CSourceHookImpl::HookLoopEnd()
   629 	{
   630 		// When in a post recall... make sure status is high enough so that it returns the orig ret.
   631 		if (m_HLIStack.size() > 1 && m_HLIStack.second().recall == HookLoopInfo::Recall_Post2)
   632 			*m_HLIStack.front().pStatus = MRES_SUPERCEDE;			// THAT'LL TEACH THEM!
   633 		m_HLIStack.pop();
   634 	}
   635 
   636 	void CSourceHookImpl::SetRes(META_RES res)
   637 	{
   638 		*m_HLIStack.front().pCurRes = res;
   639 	}
   640 
   641 	META_RES CSourceHookImpl::GetPrevRes()
   642 	{
   643 		return *m_HLIStack.front().pPrevRes;
   644 	}
   645 
   646 	META_RES CSourceHookImpl::GetStatus()
   647 	{
   648 		return *m_HLIStack.front().pStatus;
   649 	}
   650 
   651 	const void *CSourceHookImpl::GetOrigRet()
   652 	{
   653 		// When in a post recall... return the orig ret of the previous hookloop.
   654 		if (m_HLIStack.size() > 1 && m_HLIStack.second().recall == HookLoopInfo::Recall_Post2)
   655 			return m_HLIStack.second().pOrigRet;
   656 
   657 		return m_HLIStack.front().pOrigRet;
   658 	}
   659 
   660 	const void *CSourceHookImpl::GetOverrideRet()
   661 	{
   662 		// pOverrideRet is always set since recalls were introduced
   663 		// GetOverrideRetPtr was added; a function which always returns pOverrideRet
   664 		// so that RETURN_META_VALUE_NEWPARAMS can provide an override result
   665 
   666 		// This means that we have to filter GetOverrideRet:
   667 		//  If the status variable is < MRES_OVERRIDE, return NULL.
   668 
   669 		return (*m_HLIStack.front().pStatus < MRES_OVERRIDE) ?
   670 			NULL : m_HLIStack.front().pOverrideRet;
   671 	}
   672 
   673 	void *CSourceHookImpl::GetOverrideRetPtr()
   674 	{
   675 		// As described in the comment above: always return pOverrideRet
   676 		return m_HLIStack.front().pOverrideRet;
   677 	}
   678 
   679 	void *CSourceHookImpl::GetIfacePtr()
   680 	{
   681 		return *m_HLIStack.front().pIfacePtrPtr;
   682 	}
   683 
   684 	void CSourceHookImpl::SetCurResPtr(META_RES *mres)
   685 	{
   686 		m_HLIStack.front().pCurRes = mres;
   687 	}
   688 
   689 	void CSourceHookImpl::SetPrevResPtr(META_RES *mres)
   690 	{
   691 		m_HLIStack.front().pPrevRes = mres;
   692 
   693 		// If we're recalling, drag the previous mres value to the new hookfunc
   694 		if (m_HLIStack.size() > 1 && m_HLIStack.second().recall)
   695 			*mres = *m_HLIStack.second().pPrevRes;
   696 	}
   697 
   698 	void CSourceHookImpl::SetStatusPtr(META_RES *mres)
   699 	{
   700 		m_HLIStack.front().pStatus = mres;
   701 
   702 		// If we're recalling, drag the previous mres value to the new hookfunc
   703 		if (m_HLIStack.size() > 1 && m_HLIStack.second().recall)
   704 			*mres = *m_HLIStack.second().pStatus;
   705 	}
   706 
   707 	void CSourceHookImpl::SetIfacePtrPtr(void **pp)
   708 	{
   709 		m_HLIStack.front().pIfacePtrPtr = pp;
   710 	}
   711 
   712 	void CSourceHookImpl::SetOrigRetPtr(const void *ptr)
   713 	{
   714 		m_HLIStack.front().pOrigRet = ptr;
   715 	}
   716 	void CSourceHookImpl::SetOverrideRetPtr(void *ptr)
   717 	{
   718 		m_HLIStack.front().pOverrideRet = ptr;
   719 	}
   720 
   721 	// New function which does all of the above + more :)
   722 	void *CSourceHookImpl::SetupHookLoop(META_RES *statusPtr, META_RES *prevResPtr, META_RES *curResPtr,
   723 		void **ifacePtrPtr, const void *origRetPtr, void *overrideRetPtr)
   724 	{
   725 		HookLoopInfo &hli = m_HLIStack.front();
   726 		hli.pStatus = statusPtr;
   727 		hli.pPrevRes = prevResPtr;
   728 		hli.pCurRes = curResPtr;
   729 		hli.pIfacePtrPtr = ifacePtrPtr;
   730 		hli.pOrigRet = origRetPtr;
   731 
   732 		// Handle some recall stuff
   733 		if (m_HLIStack.size() > 1 && m_HLIStack.second().recall)
   734 		{
   735 			HookLoopInfo &other = m_HLIStack.second();
   736 			*statusPtr = *other.pStatus;
   737 			*prevResPtr = *other.pStatus;
   738 
   739 			// When the status is low so there's no override return value and we're in a post recall,
   740 			// give it the orig return value as override return value.
   741 			if (*statusPtr < MRES_OVERRIDE && other.recall == HookLoopInfo::Recall_Post1)
   742 				hli.pOverrideRet = const_cast<void*>(other.pOrigRet);
   743 			else	// Otherwise, transfer override ret normally
   744 				hli.pOverrideRet = other.pOverrideRet;
   745 		}
   746 		else
   747 			hli.pOverrideRet = overrideRetPtr;
   748 
   749 		// Tell the hook func which override ret ptr to use
   750 		return hli.pOverrideRet;
   751 	}
   752 
   753 	bool CSourceHookImpl::ShouldContinue()
   754 	{
   755 		// Post-recalls:
   756 		//  The second element on the stack has recall set to Recall_Post1.
   757 		//  This means that we want to skip this part and the original function calling thing, so
   758 		//  we store the status mres value, set status to MRES_SUPERCEDE, and return false.
   759 		//  We also set the recall flag to Recall_Post2, so the next time the thing calls us, we
   760 		//  can return true (so that the thing goes into post hooks).
   761 		if (m_HLIStack.size() > 1)
   762 		{
   763 			if (m_HLIStack.second().recall == HookLoopInfo::Recall_Post1)
   764 			{
   765 				m_HLIStack.front().temporaryStatus = *m_HLIStack.front().pStatus;
   766 				*m_HLIStack.front().pStatus = MRES_SUPERCEDE;
   767 				m_HLIStack.second().recall = HookLoopInfo::Recall_Post2;
   768 				return false;
   769 			}
   770 			else if (m_HLIStack.second().recall == HookLoopInfo::Recall_Post2)
   771 			{
   772 				*m_HLIStack.front().pStatus = m_HLIStack.front().temporaryStatus;
   773 				return m_HLIStack.front().shouldContinue;
   774 			}
   775 		}
   776 
   777 		// 16.01.2008: We used to return false for recalls here.
   778 		// This caused the hook funcs to think that the whole iface has been destroyed
   779 		// (the original purpose of shouldcontinue was to notify the hookfuncs that everything has been
   780 		// invalidated by RemoveHook) so they did not release their iterator. -> Leaks
   781 		// Now, GetIter sets the iterator to END so it still gets released but the hooks don't continue.
   782 		
   783 		// But: we have to return false in the post phase of pre recalls (ie. a pre hook made a recall).
   784 		if (m_HLIStack.front().recall == HookLoopInfo::Recall_Pre &&
   785 			static_cast<CIface*>(m_HLIStack.front().pCurIface)->m_PreHooks.RelFlagGet())
   786 		{
   787 			return false;
   788 		}
   789 
   790 		return m_HLIStack.front().shouldContinue;
   791 	}
   792 
   793 	void CSourceHookImpl::DoRecall()
   794 	{
   795 		if (!m_HLIStack.empty())
   796 		{
   797 			// Also watch out for post recalls! Described at the beginning of sourcehook_impl.h
   798 			m_HLIStack.front().recall =
   799 				static_cast<CIface*>(m_HLIStack.front().pCurIface)->m_PostHooks.RQFlagGet() ?
   800 				HookLoopInfo::Recall_Post1 : HookLoopInfo::Recall_Pre;
   801 			
   802 			CHookList *mlist = static_cast<CHookList*>(m_HLIStack.front().recall == HookLoopInfo::Recall_Pre ? 
   803 				m_HLIStack.front().pCurIface->GetPreHooks() : m_HLIStack.front().pCurIface->GetPostHooks());
   804 			mlist->m_Recall = true;
   805 
   806 			// The hookfunc usually does this, but it won't have a chance to see it, 
   807 			// so for recalls, we update status here if it's required
   808 			if (*m_HLIStack.front().pCurRes > *m_HLIStack.front().pStatus) 
   809 				*m_HLIStack.front().pStatus = *m_HLIStack.front().pCurRes;
   810 
   811 		}
   812 	}
   813 
   814 	////////////////////////////
   815 	// CCallClassImpl
   816 	////////////////////////////
   817 	CSourceHookImpl::CCallClassImpl::CCallClassImpl(void *ptr, size_t size)
   818 		: m_Ptr(ptr), m_ObjSize(size), m_RefCounter(1)
   819 	{
   820 	}
   821 	CSourceHookImpl::CCallClassImpl::~CCallClassImpl()
   822 	{
   823 	}
   824 
   825 	void *CSourceHookImpl::CCallClassImpl::GetThisPtr()
   826 	{
   827 		return m_Ptr;
   828 	}
   829 	void *CSourceHookImpl::CCallClassImpl::GetOrigFunc(int vtbloffs, int vtblidx)
   830 	{
   831 		OrigVTables::iterator iter = m_VT.find(vtbloffs);
   832 		if (iter != m_VT.end() && iter->val.size() > (size_t)vtblidx)
   833 		{
   834 			return iter->val[vtblidx];
   835 		}
   836 		return NULL;
   837 	}
   838 
   839 	void CSourceHookImpl::CCallClassImpl::ApplyCallClassPatch(int vtbl_offs, int vtbl_idx, void *orig_entry)
   840 	{
   841 		OrigFuncs &tmpvec = m_VT[vtbl_offs];
   842 		if (tmpvec.size() <= (size_t)vtbl_idx)
   843 			tmpvec.resize(vtbl_idx+1, NULL);
   844 		tmpvec[vtbl_idx] = orig_entry;
   845 	}
   846 	void CSourceHookImpl::CCallClassImpl::RemoveCallClassPatch(int vtbl_offs, int vtbl_idx)
   847 	{
   848 		OrigVTables::iterator iter = m_VT.find(vtbl_offs);
   849 		if (iter != m_VT.end())
   850 		{
   851 			if (iter->val.size() > (size_t)vtbl_idx)
   852 			{
   853 				iter->val[vtbl_idx] = 0;
   854 
   855 				OrigFuncs &of = iter->val;
   856 				OrigFuncs::iterator lastused = of.end();
   857 				for (OrigFuncs::iterator viter = of.begin(); viter != of.end(); ++viter)
   858 				{
   859 					if (*viter)
   860 						lastused = viter;
   861 				}
   862 				if (lastused == of.end())
   863 				{
   864 					// No used element => Remove the whole vector
   865 					m_VT.erase(iter);
   866 					return;
   867 				}
   868 				of.resize(lastused - of.begin() + 1);
   869 			}
   870 		}
   871 	}
   872 
   873 	////////////////////////////
   874 	// CHookManagerInfo
   875 	////////////////////////////
   876 	CSourceHookImpl::CHookManagerInfo::CHookManagerInfo() : m_HookManVersion(0)
   877 	{
   878 	}
   879 	CSourceHookImpl::CHookManagerInfo::~CHookManagerInfo()
   880 	{
   881 	}
   882 
   883 	IVfnPtr *CSourceHookImpl::CHookManagerInfo::FindVfnPtr(void *vfnptr)
   884 	{
   885 		VfnPtrListIter iter = m_VfnPtrs.find(vfnptr);
   886 		return iter == m_VfnPtrs.end() ? NULL : &(*iter);
   887 	}
   888 	void CSourceHookImpl::CHookManagerInfo::SetInfo(int vtbl_offs, int vtbl_idx, const char *proto)
   889 	{
   890 		m_VtblOffs = vtbl_offs;
   891 		m_VtblIdx = vtbl_idx;
   892 		m_Proto = proto;
   893 	}
   894 	void CSourceHookImpl::CHookManagerInfo::SetHookfuncVfnptr(void *hookfunc_vfnptr)
   895 	{
   896 		m_HookfuncVfnptr = hookfunc_vfnptr;
   897 	}
   898 	void CSourceHookImpl::CHookManagerInfo::SetVersion(int version)
   899 	{
   900 		m_HookManVersion = version;
   901 	}
   902 	////////////////////////////
   903 	// CVfnPtr
   904 	////////////////////////////
   905 
   906 
   907 	// If you get a crash here, the ptr passed is invalid
   908 	// This usually means a SH_DECL_MANUALHOOK* with wrong thisptroffs/vtbloffs/vtblidx
   909 	CSourceHookImpl::CVfnPtr::CVfnPtr(void *ptr) : m_Ptr(ptr), m_OrigEntry(*reinterpret_cast<void**>(ptr))
   910 	{
   911 	}
   912 	CSourceHookImpl::CVfnPtr::~CVfnPtr()
   913 	{
   914 	}
   915 
   916 	void *CSourceHookImpl::CVfnPtr::GetVfnPtr()
   917 	{
   918 		return m_Ptr;
   919 	}
   920 
   921 	void *CSourceHookImpl::CVfnPtr::GetOrigEntry()
   922 	{
   923 		return m_OrigEntry;
   924 	}
   925 
   926 	IIface *CSourceHookImpl::CVfnPtr::FindIface(void *ptr)
   927 	{
   928 		IfaceListIter iter = m_Ifaces.find(ptr);
   929 		return iter == m_Ifaces.end() ? NULL : &(*iter);
   930 	}
   931 
   932 	////////////////////////////
   933 	// CIface
   934 	////////////////////////////
   935 	CSourceHookImpl::CIface::CIface(void *ptr) : m_Ptr(ptr)
   936 	{
   937 	}
   938 	CSourceHookImpl::CIface::~CIface()
   939 	{
   940 	}
   941 
   942 	void *CSourceHookImpl::CIface::GetPtr()
   943 	{
   944 		return m_Ptr;
   945 	}
   946 
   947 	IHookList *CSourceHookImpl::CIface::GetPreHooks()
   948 	{
   949 		return &m_PreHooks;
   950 	}
   951 	IHookList *CSourceHookImpl::CIface::GetPostHooks()
   952 	{
   953 		return &m_PostHooks;
   954 	}
   955 
   956 	////////////////////////////
   957 	// CHookList
   958 	////////////////////////////
   959 
   960 	CSourceHookImpl::CHookList::CHookList() : m_FreeIters(NULL), m_UsedIters(NULL),
   961 		m_Recall(false)
   962 	{
   963 	}
   964 	CSourceHookImpl::CHookList::CHookList(const CHookList &other) : m_List(other.m_List),
   965 		m_FreeIters(NULL), m_UsedIters(NULL), m_Recall(false)
   966 	{
   967 	}
   968 
   969 	CSourceHookImpl::CHookList::~CHookList()
   970 	{
   971 		while (m_FreeIters)
   972 		{
   973 			CIter *iter = m_FreeIters->m_pNext;
   974 			delete m_FreeIters;
   975 			m_FreeIters = iter;
   976 		}
   977 		while (m_UsedIters)
   978 		{
   979 			CIter *iter = m_UsedIters->m_pNext;
   980 			delete m_UsedIters;
   981 			m_UsedIters = iter;
   982 		}
   983 	}
   984 	IHookList::IIter *CSourceHookImpl::CHookList::GetIter()
   985 	{
   986 		m_RQFlag = true;
   987 
   988 		CIter *ret;
   989 		if (m_FreeIters)
   990 		{
   991 			ret = m_FreeIters;
   992 			m_FreeIters = ret->m_pNext;
   993 			ret->GoToBegin();
   994 		}
   995 		else
   996 		{
   997 			ret = new CIter(this);
   998 		}
   999 		
  1000 		// Muuuh, if we're recalling, it shall be a copy of the last iterator, incremented by one
  1001 		if (m_Recall && m_UsedIters)
  1002 		{
  1003 			ret->Set(m_UsedIters);		// m_UsedIters is the last returned and not released iterator
  1004 			ret->Next();				// Use next instead of directly incrementing its m_Iter:
  1005 										// skips paused plugins
  1006 
  1007 			// Set the last iterator to END!
  1008 			m_UsedIters->GoToEnd();
  1009 		}
  1010 
  1011 		ret->m_pNext = m_UsedIters;
  1012 		ret->m_pPrev = NULL;
  1013 		if (m_UsedIters)
  1014 			m_UsedIters->m_pPrev = ret;
  1015 		m_UsedIters = ret;
  1016 
  1017 		m_Recall = false;
  1018 
  1019 		return ret;
  1020 	}
  1021 	void CSourceHookImpl::CHookList::ReleaseIter(IIter *pIter)
  1022 	{
  1023 		m_RelFlag = true;
  1024 
  1025 		CIter *pIter2 = static_cast<CIter*>(pIter);
  1026 
  1027 		// Unlink from m_UsedIters
  1028 
  1029 		if (pIter2->m_pNext)
  1030 			pIter2->m_pNext->m_pPrev = pIter2->m_pPrev;
  1031 		if (pIter2->m_pPrev)
  1032 			pIter2->m_pPrev->m_pNext = pIter2->m_pNext;
  1033 		if (pIter2 == m_UsedIters)
  1034 			m_UsedIters = m_UsedIters->m_pNext;
  1035 
  1036 		// Link to m_FreeIters
  1037 
  1038 		pIter2->m_pNext = m_FreeIters;
  1039 
  1040 		m_FreeIters = pIter2;
  1041 
  1042 		// Reset recall state.
  1043 		m_Recall = false;
  1044 	}
  1045 
  1046 	CSourceHookImpl::CHookList::CIter::CIter(CHookList *pList) : m_pList(pList), m_pNext(NULL)
  1047 	{
  1048 		GoToBegin();
  1049 	}
  1050 	CSourceHookImpl::CHookList::CIter::~CIter()
  1051 	{
  1052 	}
  1053 
  1054 	void CSourceHookImpl::CHookList::CIter::Set(CIter *pOther)
  1055 	{
  1056 		m_Iter = pOther->m_Iter;
  1057 	}
  1058 
  1059 	void CSourceHookImpl::CHookList::CIter::GoToBegin()
  1060 	{
  1061 		m_Iter = m_pList->m_List.begin();
  1062 		SkipPaused();
  1063 	}
  1064 
  1065 	void CSourceHookImpl::CHookList::CIter::GoToEnd()
  1066 	{
  1067 		m_Iter = m_pList->m_List.end();
  1068 	}
  1069 
  1070 	bool CSourceHookImpl::CHookList::CIter::End()
  1071 	{
  1072 		if (!m_pList)
  1073 			return false;
  1074 		return m_Iter == m_pList->m_List.end();
  1075 	}
  1076 	void CSourceHookImpl::CHookList::CIter::Next()
  1077 	{
  1078 		if (!m_pList || m_Iter == m_pList->m_List.end())
  1079 			return;
  1080 		++m_Iter;
  1081 		SkipPaused();
  1082 	}
  1083 	void CSourceHookImpl::CHookList::CIter::Clear()
  1084 	{
  1085 		m_pList = NULL;
  1086 	}
  1087 	void CSourceHookImpl::CHookList::CIter::SkipPaused()
  1088 	{
  1089 		while (m_Iter != m_pList->m_List.end() && m_Iter->paused)
  1090 			++m_Iter;
  1091 	}
  1092 
  1093 	ISHDelegate *CSourceHookImpl::CHookList::CIter::Handler()
  1094 	{
  1095 		return m_Iter->handler;
  1096 	}
  1097 	int CSourceHookImpl::CHookList::CIter::ThisPtrOffs()
  1098 	{
  1099 		return m_Iter->thisptr_offs;
  1100 	}
  1101 
  1102 	//////////////////////////////////////////////////////////////////////////
  1103 	// CProto
  1104 	//////////////////////////////////////////////////////////////////////////
  1105 	char *CSourceHookImpl::CProto::DupProto(const char *p)
  1106 	{
  1107 		char *newproto;
  1108 		if (*p)
  1109 		{
  1110 			size_t len = strlen(p);
  1111 			newproto = new char[len+1];
  1112 			memcpy(newproto, p, len+1);
  1113 		} else {
  1114 			const ProtoInfo *pi1 = reinterpret_cast<const ProtoInfo *>(p);
  1115 			int *ar_copy = new int[pi1->numOfParams + 1];
  1116 			for (int i = 0; i <= pi1->numOfParams; i++)
  1117 				ar_copy[i] = pi1->params[i];
  1118 			ProtoInfo *copy = new ProtoInfo(pi1->retTypeSize, pi1->numOfParams, ar_copy);
  1119 			newproto = reinterpret_cast<char *>(copy);
  1120 		}
  1121 
  1122 		return newproto;
  1123 	}
  1124 
  1125 	void CSourceHookImpl::CProto::FreeProto(char *prot)
  1126 	{
  1127 		if (*prot)
  1128 		{
  1129 			delete [] prot;
  1130 		} else {
  1131 			ProtoInfo *pi = reinterpret_cast<ProtoInfo *>(prot);
  1132 			delete [] pi->params;
  1133 			delete pi;
  1134 		}
  1135 	}
  1136 
  1137 	bool CSourceHookImpl::CProto::Equal(const char *p1, const char *p2)
  1138 	{
  1139 		if (*p1 && *p2)			// Case1: Both old
  1140 		{
  1141 			// As in old versions
  1142 			return strcmp(p1, p2) == 0;
  1143 		}
  1144 		else if (!*p1 && !*p2)	// Case2: Both new
  1145 		{
  1146 			const ProtoInfo *pi1 = reinterpret_cast<const ProtoInfo*>(p1);
  1147 			const ProtoInfo *pi2 = reinterpret_cast<const ProtoInfo*>(p2);
  1148 
  1149 			if (pi1->retTypeSize == pi2->retTypeSize &&
  1150 				pi1->numOfParams == pi2->numOfParams)
  1151 			{
  1152 				// params[0] is 0 for "normal" functions and -1 for vararg functions
  1153 				// params[1] is size of first parameter
  1154 				// params[2] is size of second parameter ...
  1155 				for (int i = 0; i <= pi1->numOfParams; ++i)
  1156 				{
  1157 					if (pi1->params[i] != pi2->params[i])
  1158 						return false;
  1159 				}
  1160 				return true;
  1161 			}
  1162 			else
  1163 			{
  1164 				return false;
  1165 			}
  1166 		}
  1167 		else					// Case3: Mixed old/new
  1168 		{
  1169 			// Trust the user
  1170 			return true;
  1171 		}
  1172 	}
  1173 
  1174 
  1175 	//////////////////////////////////////////////////////////////////////////
  1176 	// CHookManagerContainer
  1177 	//////////////////////////////////////////////////////////////////////////
  1178 	void CSourceHookImpl::CHookManagerContainer::AddHookManager(Plugin plug, const CHookManagerInfo &hookman)
  1179 	{
  1180 		iterator iter;
  1181 		// Check whether such a hook manager already exists; if yes, ignore.
  1182 		for (iter = begin(); iter != end(); ++iter)
  1183 		{
  1184 			if (iter->m_Plug == plug && iter->m_Func == hookman.m_Func)
  1185 				return;
  1186 		}
  1187 
  1188 		// It doesn't -> add it. Add it to the end of its version group.
  1189 		for (iter = begin(); iter != end(); ++iter)
  1190 		{
  1191 			if (iter->m_HookManVersion < hookman.m_HookManVersion)
  1192 				break;
  1193 		}
  1194 
  1195 		bool isBeginning = iter == begin();
  1196 
  1197 		insert(iter, hookman);
  1198 
  1199 		// If we inserted it at the beginning and if the dam breaks open many years too soon
  1200 		// and if there is more than one hookman and if the second one isn't empty, transfer
  1201 		// hooks from second to first
  1202 
  1203 		if (isBeginning && size() > 1)
  1204 		{
  1205 			iter = begin();
  1206 			iterator second = iter;
  1207 			++second;
  1208 
  1209 			if (!second->m_VfnPtrs.empty())
  1210 			{
  1211 				// Move the vfnptrs from the old hook manager to the new one
  1212 				iter->m_VfnPtrs = second->m_VfnPtrs;
  1213 				second->m_VfnPtrs.clear();
  1214 
  1215 				// Unregister the old one, register the new one
  1216 				second->m_Func(HA_Unregister, NULL);
  1217 				iter->m_Func(HA_Register, &(*iter));
  1218 
  1219 				// Go through all vfnptrs in this hookman and patch them to point to the new manager's handler!
  1220 				// or whatever
  1221 				for (CHookManagerInfo::VfnPtrListIter vfnptr_iter = iter->m_VfnPtrs.begin();
  1222 					vfnptr_iter != iter->m_VfnPtrs.end(); ++vfnptr_iter)
  1223 				{
  1224 					// And DEREFERENCE newHookMan->m_HookfuncVfnptr!
  1225 					// otherwise it will be executing the vtable... had to find out the hard way
  1226 					*reinterpret_cast<void**>(vfnptr_iter->m_Ptr) = *reinterpret_cast<void**>(iter->m_HookfuncVfnptr);
  1227 				}
  1228 			}
  1229 		}
  1230 	}
  1231 }