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