sourcehook/sourcehook.cpp
author Pavol Marko <pavolmarko@gmail.com>
Sat Dec 10 22:37:53 2005 +0000 (2005-12-10)
changeset 157 064f77cac7ab
parent 151 1667580b0c91
child 162 a95db73792e5
permissions -rw-r--r--
Added manual hooks. I hope that I haven't broken binary compatibility - someone might want to test it.
     1 /* ======== SourceHook ========
     2 * Copyright (C) 2004-2005 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 SourceHook::HashFunction<int>(const int & k)
    28 	{
    29 		return k;
    30 	}
    31 	template<>
    32 	int SourceHook::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 (HookManInfoList::iterator hmil_iter = m_HookMans.begin(); hmil_iter != m_HookMans.end(); ++hmil_iter)
    71 		{
    72 			if (hmil_iter->m_Plug != plug)
    73 				continue;
    74 			for (CHookManagerInfo::VfnPtrListIter vfnptr_iter = hmil_iter->m_VfnPtrs.begin();
    75 				vfnptr_iter != hmil_iter->m_VfnPtrs.end(); ++vfnptr_iter)
    76 			{
    77 				for (CVfnPtr::IfaceListIter iface_iter = vfnptr_iter->m_Ifaces.begin();
    78 					iface_iter != vfnptr_iter->m_Ifaces.end(); ++iface_iter)
    79 				{
    80 					List<HookInfo>::iterator hook_iter;
    81 					TMP_CHECK_LIST(m_PreHooks);
    82 					TMP_CHECK_LIST(m_PostHooks);
    83 				}
    84 			}
    85 		}
    86 #undef TMP_CHECK_LIST
    87 		return false;
    88 	}
    89 
    90 	void CSourceHookImpl::UnloadPlugin(Plugin plug)
    91 	{
    92 		// 1) Manually remove all hooks by this plugin
    93 		List<RemoveHookInfo> hookstoremove;
    94 		HookManInfoList::iterator hmil_iter;
    95 
    96 #define TMP_CHECK_LIST(name, ispost) \
    97 	for (hook_iter = iface_iter->name.m_List.begin(); hook_iter != iface_iter->name.m_List.end(); ++hook_iter) \
    98 		if (hook_iter->plug == plug) \
    99 			hookstoremove.push_back(RemoveHookInfo(hook_iter->plug, iface_iter->m_Ptr, \
   100 			hook_iter->thisptr_offs, hmil_iter->m_Func, hook_iter->handler, ispost))
   101 
   102 		for (hmil_iter = m_HookMans.begin(); hmil_iter != m_HookMans.end(); ++hmil_iter)
   103 		{
   104 			for (CHookManagerInfo::VfnPtrListIter vfnptr_iter = hmil_iter->m_VfnPtrs.begin();
   105 				vfnptr_iter != hmil_iter->m_VfnPtrs.end(); ++vfnptr_iter)
   106 			{
   107 				for (CVfnPtr::IfaceListIter iface_iter = vfnptr_iter->m_Ifaces.begin();
   108 					iface_iter != vfnptr_iter->m_Ifaces.end(); ++iface_iter)
   109 				{
   110 					List<HookInfo>::iterator hook_iter;
   111 					TMP_CHECK_LIST(m_PreHooks, false);
   112 					TMP_CHECK_LIST(m_PostHooks, true);
   113 				}
   114 			}
   115 		}
   116 #undef TMP_CHECK_LIST
   117 
   118 		for (List<RemoveHookInfo>::iterator rmiter = hookstoremove.begin(); rmiter != hookstoremove.end(); ++rmiter)
   119 			RemoveHook(*rmiter);
   120 
   121 		// 2) Other plugins may use hook managers in this plugin.
   122 		// Get a list of hook managers that are in this plugin and are used by other plugins
   123 		// Delete all hook managers that are in this plugin
   124 
   125 		HookManInfoList tmphookmans;
   126 		bool erase = false;
   127 		for (hmil_iter = m_HookMans.begin(); hmil_iter != m_HookMans.end();
   128 			erase ? hmil_iter=m_HookMans.erase(hmil_iter) : ++hmil_iter)
   129 		{
   130 			if (hmil_iter->m_Plug == plug)
   131 			{
   132 				if (!hmil_iter->m_VfnPtrs.empty())
   133 				{
   134 					// All hooks by this plugin are already removed
   135 					// So if there is a vfnptr, it has to be used by an other plugin
   136 					tmphookmans.push_back(*hmil_iter);
   137 				}
   138 				erase = true;
   139 			}
   140 			else
   141 				erase = false;
   142 		}
   143 
   144 		// For each hook manager that is used in an other plugin:
   145 		for (hmil_iter = tmphookmans.begin(); hmil_iter != tmphookmans.end(); ++hmil_iter)
   146 		{
   147 			// Find a suitable hook manager in an other plugin
   148 			HookManInfoList::iterator newHookMan = FindHookMan(m_HookMans.begin(), m_HookMans.end(),
   149 				hmil_iter->m_Proto, hmil_iter->m_VtblOffs, hmil_iter->m_VtblIdx);
   150 
   151 			// This should _never_ happen.
   152 			// If there is a hook from an other plugin, the plugin must have provided a hook manager as well.
   153 			SH_ASSERT(newHookMan != m_HookMans.end(),
   154 				("Could not find a suitable hook manager in an other plugin!"));
   155 
   156 			// AddHook should make sure that every plugin only has _one_ hook manager for _one_ proto/vi/vo
   157 			SH_ASSERT(newHookMan->m_Plug != plug, ("New hook manager from same plugin!"));
   158 
   159 			// The first hook manager should be always used - so the new hook manager has to be empty
   160 			SH_ASSERT(newHookMan->m_VfnPtrs.empty(), ("New hook manager not empty!"));
   161 
   162 			// Move the vfnptrs from the old hook manager to the new one
   163 			newHookMan->m_VfnPtrs = hmil_iter->m_VfnPtrs;
   164 
   165 			// Unregister the old one, register the new one
   166 			hmil_iter->m_Func(HA_Unregister, NULL);
   167 			newHookMan->m_Func(HA_Register, &(*newHookMan));
   168 
   169 			// zOMG BAIL, here is part of what you wanted:
   170 
   171 			// Go through all vfnptrs in this hookman and patch them to point to the new manager's handler!
   172 			// or whatever
   173 			for (CHookManagerInfo::VfnPtrListIter vfnptr_iter = newHookMan->m_VfnPtrs.begin();
   174 				vfnptr_iter != newHookMan->m_VfnPtrs.end(); ++vfnptr_iter)
   175 			{
   176 				// And DEREFERENCE newHookMan->m_HookfuncVfnptr!
   177 				// otherwise it will be executing the vtable... had to find out the hard way
   178 				*reinterpret_cast<void**>(vfnptr_iter->m_Ptr) = *reinterpret_cast<void**>(newHookMan->m_HookfuncVfnptr);
   179 			}
   180 
   181 			// That should fix it, bail!
   182 		}
   183 	}
   184 
   185 	void CSourceHookImpl::RemoveHookManager(Plugin plug, HookManagerPubFunc pubFunc)
   186 	{
   187 		// Moo!
   188 
   189 		CHookManagerInfo tmp;
   190 		if (pubFunc(HA_GetInfo, &tmp) != 0)
   191 			return;
   192 
   193 		HookManInfoList::iterator hmil_iter = FindHookMan(m_HookMans.begin(), m_HookMans.end(),
   194 			tmp.m_Proto, tmp.m_VtblOffs, tmp.m_VtblIdx);
   195 
   196 		if (hmil_iter == m_HookMans.end())
   197 		{
   198 			 // Moo ?
   199 			return;
   200 		}
   201 
   202 		bool stillInUse = false;
   203 		List<RemoveHookInfo> hookstoremove;
   204 
   205 		// Iterate through all of the hook manager's hooks. Remove all hooks from the hookman's plugin.
   206 #define TMP_CHECK_LIST(name, ispost) \
   207 	for (hook_iter = iface_iter->name.m_List.begin(); hook_iter != iface_iter->name.m_List.end(); ++hook_iter) \
   208 		if (hook_iter->plug == plug) \
   209 			hookstoremove.push_back(RemoveHookInfo(hook_iter->plug, iface_iter->m_Ptr, \
   210 			hook_iter->thisptr_offs, hmil_iter->m_Func, hook_iter->handler, ispost)); \
   211 		else \
   212 			stillInUse = true; \
   213 
   214 		for (CHookManagerInfo::VfnPtrListIter vfnptr_iter = hmil_iter->m_VfnPtrs.begin();
   215 			vfnptr_iter != hmil_iter->m_VfnPtrs.end(); ++vfnptr_iter)
   216 		{
   217 			for (CVfnPtr::IfaceListIter iface_iter = vfnptr_iter->m_Ifaces.begin();
   218 				iface_iter != vfnptr_iter->m_Ifaces.end(); ++iface_iter)
   219 			{
   220 				List<HookInfo>::iterator hook_iter;
   221 				TMP_CHECK_LIST(m_PreHooks, false);
   222 				TMP_CHECK_LIST(m_PostHooks, true);
   223 			}
   224 		}
   225 #undef TMP_CHECK_LIST
   226 
   227 		for (List<RemoveHookInfo>::iterator rmiter = hookstoremove.begin(); rmiter != hookstoremove.end(); ++rmiter)
   228 			RemoveHook(*rmiter);
   229 
   230 		CHookManagerInfo info = *hmil_iter;
   231 
   232 		// Unlink the hook manager from the list
   233 		m_HookMans.erase(hmil_iter);
   234 
   235 		// If there were any hooks from other plugins, find a new suitable hook manager.
   236 		if (stillInUse)
   237 		{
   238 			// Find a suitable hook manager in an other plugin
   239 			HookManInfoList::iterator newHookMan = FindHookMan(m_HookMans.begin(), m_HookMans.end(),
   240 				info.m_Proto, info.m_VtblOffs, info.m_VtblIdx);
   241 
   242 			// This should _never_ happen.
   243 			// If there is a hook from an other plugin, the plugin must have provided a hook manager as well.
   244 			SH_ASSERT(newHookMan != m_HookMans.end(),
   245 				("Could not find a suitable hook manager in an other plugin!"));
   246 
   247 			// AddHook should make sure that every plugin only has _one_ hook manager for _one_ proto/vi/vo
   248 			SH_ASSERT(newHookMan->m_Plug != plug, ("New hook manager from same plugin!"));
   249 
   250 			// The first hook manager should be always used - so the new hook manager has to be empty
   251 			SH_ASSERT(newHookMan->m_VfnPtrs.empty(), ("New hook manager not empty!"));
   252 
   253 			// Move the vfnptrs from the old hook manager to the new one
   254 			newHookMan->m_VfnPtrs = info.m_VfnPtrs;
   255 
   256 			// Unregister the old one, register the new one
   257 			info.m_Func(HA_Unregister, NULL);
   258 			newHookMan->m_Func(HA_Register, &(*newHookMan));
   259 
   260 			// Go through all vfnptrs in this hookman and patch them to point to the new manager's handler!
   261 			// or whatever
   262 			for (CHookManagerInfo::VfnPtrListIter vfnptr_iter = newHookMan->m_VfnPtrs.begin();
   263 				vfnptr_iter != newHookMan->m_VfnPtrs.end(); ++vfnptr_iter)
   264 			{
   265 				// And DEREFERENCE newHookMan->m_HookfuncVfnptr!
   266 				// otherwise it will be executing the vtable... had to find out the hard way
   267 				*reinterpret_cast<void**>(vfnptr_iter->m_Ptr) = *reinterpret_cast<void**>(newHookMan->m_HookfuncVfnptr);
   268 			}
   269 		}
   270 	}
   271 
   272 	void CSourceHookImpl::CompleteShutdown()
   273 	{
   274 		List<RemoveHookInfo> hookstoremove;
   275 #define TMP_CHECK_LIST(name, ispost) \
   276 	for (hook_iter = iface_iter->name.m_List.begin(); hook_iter != iface_iter->name.m_List.end(); ++hook_iter) \
   277 		hookstoremove.push_back(RemoveHookInfo(hook_iter->plug, iface_iter->m_Ptr, \
   278 			hook_iter->thisptr_offs, hmil_iter->m_Func, hook_iter->handler, ispost))
   279 		for (HookManInfoList::iterator hmil_iter = m_HookMans.begin(); hmil_iter != m_HookMans.end(); ++hmil_iter)
   280 		{
   281 			for (CHookManagerInfo::VfnPtrListIter vfnptr_iter = hmil_iter->m_VfnPtrs.begin();
   282 				vfnptr_iter != hmil_iter->m_VfnPtrs.end(); ++vfnptr_iter)
   283 			{
   284 				for (CVfnPtr::IfaceListIter iface_iter = vfnptr_iter->m_Ifaces.begin();
   285 					iface_iter != vfnptr_iter->m_Ifaces.end(); ++iface_iter)
   286 				{
   287 					List<HookInfo>::iterator hook_iter;
   288 					TMP_CHECK_LIST(m_PreHooks, false);
   289 					TMP_CHECK_LIST(m_PostHooks, true);
   290 				}
   291 			}
   292 		}
   293 #undef TMP_CHECK_LIST
   294 
   295 		for (List<RemoveHookInfo>::iterator rmiter = hookstoremove.begin(); rmiter != hookstoremove.end(); ++rmiter)
   296 			RemoveHook(*rmiter);
   297 
   298 		m_HookMans.clear();
   299 	}
   300 
   301 	bool CSourceHookImpl::AddHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan, ISHDelegate *handler, bool post)
   302 	{
   303 		void *adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface) + thisptr_offs);
   304 
   305 		// 1) Get info about the hook manager
   306 		CHookManagerInfo tmp;
   307 		if (myHookMan(HA_GetInfo, &tmp) != 0)
   308 			return false;
   309 
   310 		void **cur_vtptr = *reinterpret_cast<void***>(
   311 			reinterpret_cast<char*>(adjustediface) + tmp.m_VtblOffs);
   312 		void *cur_vfnptr = reinterpret_cast<void*>(cur_vtptr + tmp.m_VtblIdx);
   313 
   314 		// Add the proposed hook manager to the _end_ of the list if the plugin doesn't have a hook manager
   315 		// with this proto/vo/vi registered
   316 		HookManInfoList::iterator hkmi_iter;
   317 		for (hkmi_iter = m_HookMans.begin(); hkmi_iter != m_HookMans.end(); ++hkmi_iter)
   318 		{
   319 			if (hkmi_iter->m_Plug == plug && ProtosEquiv(hkmi_iter->m_Proto, tmp.m_Proto) &&
   320 				hkmi_iter->m_VtblOffs == tmp.m_VtblOffs && hkmi_iter->m_VtblIdx == tmp.m_VtblIdx)
   321 				break;
   322 		}
   323 		if (hkmi_iter == m_HookMans.end())
   324 		{
   325 			// No such hook manager from this plugin yet, add it!
   326 			tmp.m_Func = myHookMan;
   327 			tmp.m_Plug = plug;
   328 			m_HookMans.push_back(tmp);
   329 		}
   330 
   331 		// Then, search for a suitable hook manager (from the beginning)
   332 		HookManInfoList::iterator hookman = FindHookMan(m_HookMans.begin(), m_HookMans.end(), tmp.m_Proto,
   333 			tmp.m_VtblOffs, tmp.m_VtblIdx);
   334 		SH_ASSERT(hookman != m_HookMans.end(), ("No hookman found - but if there was none, we've just added one!"));
   335 
   336 		// Check whether there is already an other hook manager for the same vfnptr but with other values before
   337 		// If yes, it means that the two are incompatible, so return false.
   338 		for (hkmi_iter = m_HookMans.begin(); hkmi_iter != m_HookMans.end(); ++hkmi_iter)
   339 		{
   340 			if (hkmi_iter != hookman)
   341 			{
   342 				if (hkmi_iter->m_VfnPtrs.find(cur_vfnptr) != hkmi_iter->m_VfnPtrs.end())
   343 					return false;
   344 			}
   345 		}
   346 
   347 		// Tell it to store the pointer if it's not already active
   348 		if (hookman->m_VfnPtrs.empty())
   349 			hookman->m_Func(HA_Register, &(*hookman));
   350 
   351 		CHookManagerInfo::VfnPtrListIter vfnptr_iter = hookman->m_VfnPtrs.find(cur_vfnptr);
   352 
   353 		if (vfnptr_iter == hookman->m_VfnPtrs.end())
   354 		{
   355 			// Add a new one
   356 			CVfnPtr vfp(cur_vfnptr);
   357 
   358 			// Alter vtable entry
   359 			if (!SetMemAccess(cur_vtptr, sizeof(void*) * (tmp.m_VtblIdx + 1), SH_MEM_READ | SH_MEM_WRITE))
   360 				return false;
   361 
   362 			*reinterpret_cast<void**>(cur_vfnptr) = *reinterpret_cast<void**>(hookman->m_HookfuncVfnptr);
   363 
   364 			hookman->m_VfnPtrs.push_back(vfp);
   365 
   366 			// Make vfnptr_iter point to the new element
   367 			vfnptr_iter = hookman->m_VfnPtrs.end();
   368 			--vfnptr_iter;
   369 
   370 			// Now that it is done, check whether we have to update any callclasses
   371 			ApplyCallClassPatches(adjustediface, tmp.m_VtblOffs, tmp.m_VtblIdx, vfp.m_OrigEntry);
   372 		}
   373 
   374 		CVfnPtr::IfaceListIter iface_iter = vfnptr_iter->m_Ifaces.find(adjustediface);
   375 		if (iface_iter == vfnptr_iter->m_Ifaces.end())
   376 		{
   377 			// Add a new one
   378 			vfnptr_iter->m_Ifaces.push_back(CIface(adjustediface));
   379 
   380 			// Make iface_iter point to the new element
   381 			iface_iter = vfnptr_iter->m_Ifaces.end();
   382 			--iface_iter;
   383 		}
   384 
   385 		// Add the hook
   386 		HookInfo hookinfo;
   387 		hookinfo.handler = handler;
   388 		hookinfo.plug = plug;
   389 		hookinfo.paused = false;
   390 		hookinfo.thisptr_offs = thisptr_offs;
   391 		if (post)
   392 			iface_iter->m_PostHooks.m_List.push_back(hookinfo);
   393 		else
   394 			iface_iter->m_PreHooks.m_List.push_back(hookinfo);
   395 
   396 		return true;
   397 	}
   398 
   399 	bool CSourceHookImpl::RemoveHook(RemoveHookInfo info)
   400 	{
   401 		return RemoveHook(info.plug, info.iface, info.thisptr_offs, info.hookman, info.handler, info.post);
   402 	}
   403 
   404 	bool CSourceHookImpl::RemoveHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan, ISHDelegate *handler, bool post)
   405 	{
   406 		void *adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface)+thisptr_offs);
   407 		CHookManagerInfo tmp;
   408 		if (myHookMan(HA_GetInfo, &tmp) != 0)
   409 			return false;
   410 
   411 		// Find the hook manager and the hook
   412 		HookManInfoList::iterator hookman = FindHookMan(m_HookMans.begin(), m_HookMans.end(),
   413 			tmp.m_Proto, tmp.m_VtblOffs, tmp.m_VtblIdx);
   414 		if (hookman == m_HookMans.end())
   415 			return false;
   416 
   417 		if (!ModuleInMemory(reinterpret_cast<char*>(adjustediface) + tmp.m_VtblOffs,
   418 			sizeof(void*) * (tmp.m_VtblIdx + 1)))
   419 		{
   420 			// The module the vtable was in is already unloaded.
   421 			hookman->m_VfnPtrs.clear();
   422 			hookman->m_Func(HA_Unregister, NULL);
   423 			return true;
   424 		}
   425 
   426 		void **cur_vtptr = *reinterpret_cast<void***>(
   427 			reinterpret_cast<char*>(adjustediface) + tmp.m_VtblOffs);
   428 		void *cur_vfnptr = reinterpret_cast<void*>(cur_vtptr + tmp.m_VtblIdx);
   429 
   430 		CHookManagerInfo::VfnPtrListIter vfnptr_iter = hookman->m_VfnPtrs.find(cur_vfnptr);
   431 
   432 		if (vfnptr_iter == hookman->m_VfnPtrs.end())
   433 			return false;
   434 
   435 		for (CVfnPtr::IfaceListIter iface_iter = vfnptr_iter->m_Ifaces.begin();
   436 			iface_iter != vfnptr_iter->m_Ifaces.end();)
   437 		{
   438 			List<HookInfo> &hooks =
   439 				post ? iface_iter->m_PostHooks.m_List : iface_iter->m_PreHooks.m_List;
   440 
   441 			bool erase;
   442 			for (List<HookInfo>::iterator hookiter = hooks.begin();
   443 				hookiter != hooks.end(); )
   444 			{
   445 				erase = hookiter->plug == plug && hookiter->handler->IsEqual(handler) &&
   446 					hookiter->thisptr_offs == thisptr_offs;
   447 				if (erase)
   448 				{
   449 					hookiter->handler->DeleteThis();			// Make the _plugin_ delete the handler object
   450 
   451 					// Move all iterators pointing at this
   452 					List<HookInfo>::iterator oldhookiter = hookiter;
   453 					hookiter = hooks.erase(hookiter);
   454 					List<HookInfo>::iterator newhookiter = hookiter;
   455 					--newhookiter; // The hook loop will ++ it then
   456 					CHookList::CIter *pItIter;
   457 					for (pItIter = iface_iter->m_PreHooks.m_UsedIters; pItIter; pItIter = pItIter->m_pNext)
   458 						if (pItIter->m_Iter == oldhookiter)
   459 							pItIter->m_Iter = newhookiter;
   460 				}
   461 				else
   462 					++hookiter;
   463 			}
   464 			if (iface_iter->m_PostHooks.m_List.empty() && iface_iter->m_PreHooks.m_List.empty())
   465 			{
   466 				// There are no hooks on this iface anymore...
   467 				for (HookLoopInfoStack::iterator hli_iter = m_HLIStack.begin();
   468 					hli_iter != m_HLIStack.end(); ++hli_iter)
   469 				{
   470 					if (hli_iter->pCurIface == static_cast<IIface*>(&(*iface_iter)))
   471 						hli_iter->shouldContinue = false;
   472 				}
   473 
   474 				iface_iter = vfnptr_iter->m_Ifaces.erase(iface_iter);
   475 				if (vfnptr_iter->m_Ifaces.empty())
   476 				{
   477 					// No ifaces at all -> Deactivate the hook
   478 					*reinterpret_cast<void**>(vfnptr_iter->m_Ptr) = vfnptr_iter->m_OrigEntry;
   479 
   480 					hookman->m_VfnPtrs.erase(vfnptr_iter);
   481 
   482 					// Remove callclass patch
   483 					for (Impl_CallClassList::iterator cciter = m_CallClasses.begin(); cciter != m_CallClasses.end(); ++cciter)
   484 						if (cciter->m_Ptr == adjustediface)
   485 							cciter->RemoveCallClassPatch(tmp.m_VtblOffs, tmp.m_VtblIdx);
   486 
   487 					if (hookman->m_VfnPtrs.empty())
   488 					{
   489 						// Unregister the hook manager
   490 						hookman->m_Func(HA_Unregister, NULL);
   491 					}
   492 
   493 					// Don't try to continue looping through ifaces
   494 					// - the list is already invalid
   495 					return true;
   496 				}
   497 			}
   498 			else
   499 				++iface_iter;
   500 		}
   501 		return true;
   502 	}
   503 
   504 	GenericCallClass *CSourceHookImpl::GetCallClass(void *iface, size_t size)
   505 	{
   506 		for (Impl_CallClassList::iterator cciter = m_CallClasses.begin(); cciter != m_CallClasses.end(); ++cciter)
   507 		{
   508 			if (cciter->m_Ptr == iface && cciter->m_ObjSize == size)
   509 			{
   510 				++cciter->m_RefCounter;
   511 				return &(*cciter);
   512 			}
   513 		}
   514 
   515 		// Make a new one
   516 
   517 		CCallClassImpl tmp(iface, size);
   518 		ApplyCallClassPatches(tmp);
   519 		m_CallClasses.push_back(tmp);
   520 		return &m_CallClasses.back();
   521 	}
   522 
   523 	void CSourceHookImpl::ReleaseCallClass(GenericCallClass *ptr)
   524 	{
   525 		Impl_CallClassList::iterator iter = m_CallClasses.find(ptr);
   526 		if (iter == m_CallClasses.end())
   527 			return;
   528 		--iter->m_RefCounter;
   529 		if (iter->m_RefCounter < 1)
   530 			m_CallClasses.erase(iter);
   531 	}
   532 
   533 	void CSourceHookImpl::ApplyCallClassPatches(CCallClassImpl &cc)
   534 	{
   535 		for (HookManInfoList::iterator hookman = m_HookMans.begin(); hookman != m_HookMans.end(); ++hookman)
   536 		{
   537 			for (CHookManagerInfo::VfnPtrListIter vfnptr_iter = hookman->m_VfnPtrs.begin();
   538 				vfnptr_iter != hookman->m_VfnPtrs.end(); ++vfnptr_iter)
   539 			{
   540 				for (CVfnPtr::IfaceListIter iface_iter = vfnptr_iter->m_Ifaces.begin();
   541 					iface_iter != vfnptr_iter->m_Ifaces.end(); ++iface_iter)
   542 				{
   543 					if (iface_iter->m_Ptr >= cc.m_Ptr &&
   544 						iface_iter->m_Ptr < (reinterpret_cast<char*>(cc.m_Ptr) + cc.m_ObjSize))
   545 					{
   546 						cc.ApplyCallClassPatch(static_cast<int>(reinterpret_cast<char*>(iface_iter->m_Ptr) -
   547 							reinterpret_cast<char*>(cc.m_Ptr)) + hookman->m_VtblOffs,
   548 							hookman->m_VtblIdx, vfnptr_iter->m_OrigEntry);
   549 					}
   550 				}
   551 			}
   552 		}
   553 	}
   554 
   555 	void CSourceHookImpl::ApplyCallClassPatches(void *ifaceptr, int vtbl_offs, int vtbl_idx, void *orig_entry)
   556 	{
   557 		for (Impl_CallClassList::iterator cc_iter = m_CallClasses.begin(); cc_iter != m_CallClasses.end();
   558 			++cc_iter)
   559 		{
   560 			if (ifaceptr >= cc_iter->m_Ptr &&
   561 				ifaceptr < (reinterpret_cast<char*>(cc_iter->m_Ptr) + cc_iter->m_ObjSize))
   562 			{
   563 				cc_iter->ApplyCallClassPatch(static_cast<int>(reinterpret_cast<char*>(ifaceptr) -
   564 					reinterpret_cast<char*>(cc_iter->m_Ptr)) + vtbl_offs, vtbl_idx, orig_entry);
   565 			}
   566 		}
   567 	}
   568 
   569 	void CSourceHookImpl::RemoveCallClassPatches(void *ifaceptr, int vtbl_offs, int vtbl_idx)
   570 	{
   571 		for (Impl_CallClassList::iterator cc_iter = m_CallClasses.begin(); cc_iter != m_CallClasses.end();
   572 			++cc_iter)
   573 		{
   574 			if (ifaceptr >= cc_iter->m_Ptr &&
   575 				ifaceptr < (reinterpret_cast<char*>(cc_iter->m_Ptr) + cc_iter->m_ObjSize))
   576 			{
   577 				cc_iter->RemoveCallClassPatch(vtbl_offs, vtbl_idx);
   578 			}
   579 		}
   580 	}
   581 
   582 	CSourceHookImpl::HookManInfoList::iterator CSourceHookImpl::FindHookMan(HookManInfoList::iterator begin,
   583 		HookManInfoList::iterator end, const char *proto, int vtblofs, int vtblidx)
   584 	{
   585 		HookManInfoList::iterator hookmaniter;
   586 		for (hookmaniter = m_HookMans.begin(); hookmaniter != m_HookMans.end(); ++hookmaniter)
   587 		{
   588 			if (ProtosEquiv(hookmaniter->m_Proto, proto) && hookmaniter->m_VtblOffs == vtblofs &&
   589 				hookmaniter->m_VtblIdx == vtblidx)
   590 				break;
   591 		}
   592 		return hookmaniter;
   593 	}
   594 
   595 	void CSourceHookImpl::SetPluginPaused(Plugin plug, bool paused)
   596 	{
   597 		// Go through all hook managers, all interfaces, and set the status of all hooks of this plugin to paused
   598 		for (HookManInfoList::iterator hookmaniter = m_HookMans.begin(); hookmaniter != m_HookMans.end(); ++hookmaniter)
   599 			for (CHookManagerInfo::VfnPtrListIter vfnptr_iter = hookmaniter->m_VfnPtrs.begin();
   600 				vfnptr_iter != hookmaniter->m_VfnPtrs.end(); ++vfnptr_iter)
   601 				for (CVfnPtr::IfaceListIter ifaceiter = vfnptr_iter->m_Ifaces.begin();
   602 					ifaceiter != vfnptr_iter->m_Ifaces.end(); ++ifaceiter)
   603 				{
   604 					for (List<HookInfo>::iterator hookiter = ifaceiter->m_PreHooks.m_List.begin();
   605 						hookiter != ifaceiter->m_PreHooks.m_List.end(); ++hookiter)
   606 						if (plug == hookiter->plug)
   607 							hookiter->paused = paused;
   608 
   609 					for (List<HookInfo>::iterator hookiter = ifaceiter->m_PostHooks.m_List.begin();
   610 						hookiter != ifaceiter->m_PostHooks.m_List.end(); ++hookiter)
   611 						if (plug == hookiter->plug)
   612 							hookiter->paused = paused;
   613 				}
   614 	}
   615 	void CSourceHookImpl::PausePlugin(Plugin plug)
   616 	{
   617 		SetPluginPaused(plug, true);
   618 	}
   619 
   620 	void CSourceHookImpl::UnpausePlugin(Plugin plug)
   621 	{
   622 		SetPluginPaused(plug, false);
   623 	}
   624 
   625 	void CSourceHookImpl::HookLoopBegin(IIface *pIface)
   626 	{
   627 		HookLoopInfo hli;
   628 		hli.pCurIface = pIface;
   629 		hli.shouldContinue = true;
   630 		m_HLIStack.push(hli);
   631 	}
   632 
   633 	void CSourceHookImpl::HookLoopEnd()
   634 	{
   635 		m_HLIStack.pop();
   636 	}
   637 
   638 	void CSourceHookImpl::SetRes(META_RES res)
   639 	{
   640 		*m_HLIStack.front().pCurRes = res;
   641 	}
   642 
   643 	META_RES CSourceHookImpl::GetPrevRes()
   644 	{
   645 		return *m_HLIStack.front().pPrevRes;
   646 	}
   647 
   648 	META_RES CSourceHookImpl::GetStatus()
   649 	{
   650 		return *m_HLIStack.front().pStatus;
   651 	}
   652 
   653 	const void *CSourceHookImpl::GetOrigRet()
   654 	{
   655 		return m_HLIStack.front().pOrigRet;
   656 	}
   657 
   658 	const void *CSourceHookImpl::GetOverrideRet()
   659 	{
   660 		return m_HLIStack.front().pOverrideRet;
   661 	}
   662 
   663 	void *CSourceHookImpl::GetIfacePtr()
   664 	{
   665 		return *m_HLIStack.front().pIfacePtrPtr;
   666 	}
   667 
   668 	void CSourceHookImpl::SetCurResPtr(META_RES *mres)
   669 	{
   670 		m_HLIStack.front().pCurRes = mres;
   671 	}
   672 
   673 	void CSourceHookImpl::SetPrevResPtr(META_RES *mres)
   674 	{
   675 		m_HLIStack.front().pPrevRes = mres;
   676 	}
   677 
   678 	void CSourceHookImpl::SetStatusPtr(META_RES *mres)
   679 	{
   680 		m_HLIStack.front().pStatus = mres;
   681 	}
   682 
   683 	void CSourceHookImpl::SetIfacePtrPtr(void **pp)
   684 	{
   685 		m_HLIStack.front().pIfacePtrPtr = pp;
   686 	}
   687 
   688 	void CSourceHookImpl::SetOrigRetPtr(const void *ptr)
   689 	{
   690 		m_HLIStack.front().pOrigRet = ptr;
   691 	}
   692 	void CSourceHookImpl::SetOverrideRetPtr(const void *ptr)
   693 	{
   694 		m_HLIStack.front().pOverrideRet = ptr;
   695 	}
   696 	bool CSourceHookImpl::ShouldContinue()
   697 	{
   698 		return m_HLIStack.front().shouldContinue;
   699 	}
   700 
   701 	////////////////////////////
   702 	// CCallClassImpl
   703 	////////////////////////////
   704 	CSourceHookImpl::CCallClassImpl::CCallClassImpl(void *ptr, size_t size)
   705 		: m_Ptr(ptr), m_ObjSize(size), m_RefCounter(1)
   706 	{
   707 	}
   708 	CSourceHookImpl::CCallClassImpl::~CCallClassImpl()
   709 	{
   710 	}
   711 
   712 	void *CSourceHookImpl::CCallClassImpl::GetThisPtr()
   713 	{
   714 		return m_Ptr;
   715 	}
   716 	void *CSourceHookImpl::CCallClassImpl::GetOrigFunc(int vtbloffs, int vtblidx)
   717 	{
   718 		OrigVTables::iterator iter = m_VT.find(vtbloffs);
   719 		if (iter != m_VT.end() && iter->val.size() > (size_t)vtblidx)
   720 		{
   721 			return iter->val[vtblidx];
   722 		}
   723 		return NULL;
   724 	}
   725 
   726 	void CSourceHookImpl::CCallClassImpl::ApplyCallClassPatch(int vtbl_offs, int vtbl_idx, void *orig_entry)
   727 	{
   728 		OrigFuncs &tmpvec = m_VT[vtbl_offs];
   729 		if (tmpvec.size() <= (size_t)vtbl_idx)
   730 			tmpvec.resize(vtbl_idx+1);
   731 		tmpvec[vtbl_idx] = orig_entry;
   732 	}
   733 	void CSourceHookImpl::CCallClassImpl::RemoveCallClassPatch(int vtbl_offs, int vtbl_idx)
   734 	{
   735 		OrigVTables::iterator iter = m_VT.find(vtbl_offs);
   736 		if (iter != m_VT.end())
   737 		{
   738 			if (iter->val.size() > (size_t)vtbl_idx)
   739 			{
   740 				iter->val[vtbl_idx] = 0;
   741 
   742 				OrigFuncs &of = iter->val;
   743 				OrigFuncs::iterator lastused = of.end();
   744 				for (OrigFuncs::iterator viter = of.begin(); viter != of.end(); ++viter)
   745 				{
   746 					if (*viter)
   747 						lastused = viter;
   748 				}
   749 				if (lastused == of.end())
   750 				{
   751 					// No used element => Remove the whole vector
   752 					m_VT.erase(iter);
   753 					return;
   754 				}
   755 				of.resize(lastused - of.begin() + 1);
   756 			}
   757 		}
   758 	}
   759 
   760 	bool CSourceHookImpl::ProtosEquiv(const char *p1, const char *p2)
   761 	{
   762 		/*
   763 		 Old protos look like this:
   764 
   765 		 0_void:
   766 			"attrib"
   767 		 1_void:
   768 			"attrib|param1_type"
   769 		 2_void:
   770 			"attrib|param1_type|param2_type
   771 		 0:
   772 			"attrib|ret_type"
   773 		 1:
   774 			"attrib|ret_type|param1_type"
   775 		 2:
   776 			"attrib|ret_type|param2_type"
   777 
   778 		New protos are in fact pointers to the ProtoInfo sturcture (see sourcehook.h for details)
   779 
   780 		 Old protos _never_ begin with a null character
   781 		 New protos _always_ begin with a null character
   782 		*/
   783 
   784 		if (*p1 && *p2)			// Case1: Both old
   785 		{
   786 			// As in old versions
   787 			return strcmp(p1, p2) == 0;
   788 		}
   789 		else if (!*p1 && !*p2)	// Case2: Both new
   790 		{
   791 			const ProtoInfo *pi1 = reinterpret_cast<const ProtoInfo*>(p1);
   792 			const ProtoInfo *pi2 = reinterpret_cast<const ProtoInfo*>(p2);
   793 
   794 			if (pi1->retTypeSize == pi2->retTypeSize &&
   795 				pi1->numOfParams == pi2->numOfParams)
   796 			{
   797 				// params[0] is 0 for "normal" functions and -1 for vararg functions
   798 				// params[1] is size of first parameter
   799 				// params[2] is size of second parameter ...
   800 				for (int i = 0; i <= pi1->numOfParams; ++i)
   801 				{
   802 					if (pi1->params[i] != pi2->params[i])
   803 						return false;
   804 				}
   805 				return true;
   806 			}
   807 			else
   808 			{
   809 				return false;
   810 			}
   811 		}
   812 		else					// Case3: Mixed old/new
   813 		{
   814 			// Trust the user
   815 			return true;
   816 		}
   817 	}
   818 
   819 	////////////////////////////
   820 	// CHookManagerInfo
   821 	////////////////////////////
   822 	CSourceHookImpl::CHookManagerInfo::~CHookManagerInfo()
   823 	{
   824 	}
   825 
   826 	IVfnPtr *CSourceHookImpl::CHookManagerInfo::FindVfnPtr(void *vfnptr)
   827 	{
   828 		VfnPtrListIter iter = m_VfnPtrs.find(vfnptr);
   829 		return iter == m_VfnPtrs.end() ? NULL : &(*iter);
   830 	}
   831 	void CSourceHookImpl::CHookManagerInfo::SetInfo(int vtbl_offs, int vtbl_idx, const char *proto)
   832 	{
   833 		m_VtblOffs = vtbl_offs;
   834 		m_VtblIdx = vtbl_idx;
   835 		m_Proto = proto;
   836 	}
   837 	void CSourceHookImpl::CHookManagerInfo::SetHookfuncVfnptr(void *hookfunc_vfnptr)
   838 	{
   839 		m_HookfuncVfnptr = hookfunc_vfnptr;
   840 	}
   841 
   842 	////////////////////////////
   843 	// CVfnPtr
   844 	////////////////////////////
   845 
   846 
   847 	// If you get a crash here, the ptr passed is invalid
   848 	// This usually means a SH_DECL_MANUALHOOK* with wrong thisptroffs/vtbloffs/vtblidx
   849 	CSourceHookImpl::CVfnPtr::CVfnPtr(void *ptr) : m_Ptr(ptr), m_OrigEntry(*reinterpret_cast<void**>(ptr))
   850 	{
   851 	}
   852 	CSourceHookImpl::CVfnPtr::~CVfnPtr()
   853 	{
   854 	}
   855 
   856 	void *CSourceHookImpl::CVfnPtr::GetVfnPtr()
   857 	{
   858 		return m_Ptr;
   859 	}
   860 
   861 	void *CSourceHookImpl::CVfnPtr::GetOrigEntry()
   862 	{
   863 		return m_OrigEntry;
   864 	}
   865 
   866 	IIface *CSourceHookImpl::CVfnPtr::FindIface(void *ptr)
   867 	{
   868 		IfaceListIter iter = m_Ifaces.find(ptr);
   869 		return iter == m_Ifaces.end() ? NULL : &(*iter);
   870 	}
   871 
   872 	////////////////////////////
   873 	// CIface
   874 	////////////////////////////
   875 	CSourceHookImpl::CIface::CIface(void *ptr) : m_Ptr(ptr)
   876 	{
   877 	}
   878 	CSourceHookImpl::CIface::~CIface()
   879 	{
   880 	}
   881 
   882 	void *CSourceHookImpl::CIface::GetPtr()
   883 	{
   884 		return m_Ptr;
   885 	}
   886 
   887 	IHookList *CSourceHookImpl::CIface::GetPreHooks()
   888 	{
   889 		return &m_PreHooks;
   890 	}
   891 	IHookList *CSourceHookImpl::CIface::GetPostHooks()
   892 	{
   893 		return &m_PostHooks;
   894 	}
   895 
   896 	////////////////////////////
   897 	// CHookList
   898 	////////////////////////////
   899 
   900 	CSourceHookImpl::CHookList::CHookList() : m_FreeIters(NULL), m_UsedIters(NULL)
   901 	{
   902 	}
   903 	CSourceHookImpl::CHookList::CHookList(const CHookList &other) : m_List(other.m_List), m_FreeIters(NULL), m_UsedIters(NULL)
   904 	{
   905 	}
   906 	CSourceHookImpl::CHookList::~CHookList()
   907 	{
   908 		while (m_FreeIters)
   909 		{
   910 			CIter *iter = m_FreeIters->m_pNext;
   911 			delete m_FreeIters;
   912 			m_FreeIters = iter;
   913 		}
   914 		while (m_UsedIters)
   915 		{
   916 			CIter *iter = m_UsedIters->m_pNext;
   917 			delete m_UsedIters;
   918 			m_UsedIters = iter;
   919 		}
   920 	}
   921 	IHookList::IIter *CSourceHookImpl::CHookList::GetIter()
   922 	{
   923 		CIter *ret;
   924 		if (m_FreeIters)
   925 		{
   926 			ret = m_FreeIters;
   927 			m_FreeIters = ret->m_pNext;
   928 			ret->GoToBegin();
   929 		}
   930 		else
   931 		{
   932 			ret = new CIter(this);
   933 		}
   934 		
   935 		ret->m_pNext = m_UsedIters;
   936 		ret->m_pPrev = NULL;
   937 		if (m_UsedIters)
   938 			m_UsedIters->m_pPrev = ret;
   939 		m_UsedIters = ret;
   940 
   941 		return ret;
   942 	}
   943 	void CSourceHookImpl::CHookList::ReleaseIter(IIter *pIter)
   944 	{
   945 		CIter *pIter2 = static_cast<CIter*>(pIter);
   946 
   947 		// Unlink from m_UsedIters
   948 
   949 		if (pIter2->m_pNext)
   950 			pIter2->m_pNext->m_pPrev = pIter2->m_pPrev;
   951 		if (pIter2->m_pPrev)
   952 			pIter2->m_pPrev->m_pNext = pIter2->m_pNext;
   953 		if (pIter2 == m_UsedIters)
   954 			m_UsedIters = NULL;
   955 
   956 		// Link to m_FreeIters
   957 
   958 		pIter2->m_pNext = m_FreeIters;
   959 
   960 		m_FreeIters = pIter2;
   961 	}
   962 
   963 	CSourceHookImpl::CHookList::CIter::CIter(CHookList *pList) : m_pList(pList), m_pNext(NULL)
   964 	{
   965 		GoToBegin();
   966 	}
   967 	CSourceHookImpl::CHookList::CIter::~CIter()
   968 	{
   969 	}
   970 
   971 	void CSourceHookImpl::CHookList::CIter::GoToBegin()
   972 	{
   973 		m_Iter = m_pList->m_List.begin();
   974 		SkipPaused();
   975 	}
   976 
   977 	bool CSourceHookImpl::CHookList::CIter::End()
   978 	{
   979 		if (!m_pList)
   980 			return false;
   981 		return m_Iter == m_pList->m_List.end();
   982 	}
   983 	void CSourceHookImpl::CHookList::CIter::Next()
   984 	{
   985 		if (!m_pList)
   986 			return;
   987 		++m_Iter;
   988 		SkipPaused();
   989 	}
   990 	void CSourceHookImpl::CHookList::CIter::Clear()
   991 	{
   992 		m_pList = NULL;
   993 	}
   994 	void CSourceHookImpl::CHookList::CIter::SkipPaused()
   995 	{
   996 		while (m_Iter != m_pList->m_List.end() && m_Iter->paused)
   997 			++m_Iter;
   998 	}
   999 
  1000 	ISHDelegate *CSourceHookImpl::CHookList::CIter::Handler()
  1001 	{
  1002 		return m_Iter->handler;
  1003 	}
  1004 	int CSourceHookImpl::CHookList::CIter::ThisPtrOffs()
  1005 	{
  1006 		return m_Iter->thisptr_offs;
  1007 	}
  1008 }