Oh, triggering a build.
1 /* ======== SourceHook ========
2 * Copyright (C) 2004-2010 Metamod:Source Development Team
3 * No warranties of any kind
7 * Author(s): Pavol "PM OnoTo" Marko
8 * Contributors: Scott "Damaged Soul" Ehlert
9 * ============================
13 * @file sourcehook.cpp
14 * @brief Contains the implementation of the SourceHook API
21 #include "sourcehook_impl.h"
26 int HashFunction<int>(const int & k)
31 int Compare<int>(const int & k1, const int & k2)
44 //////////////////////////////////////////////////////////////////////////
46 //////////////////////////////////////////////////////////////////////////
48 CVfnPtr *CVfnPtrList::GetVfnPtr(void *vfnptr)
50 iterator iter = find(vfnptr);
53 // No vfnptr info object found
54 // --> create a new one
55 CVfnPtr newVfnPtr(vfnptr);
64 // Initialization failed.
74 //////////////////////////////////////////////////////////////////////////
76 //////////////////////////////////////////////////////////////////////////
79 CSourceHookImpl::CSourceHookImpl()
82 CSourceHookImpl::~CSourceHookImpl()
87 int CSourceHookImpl::GetIfaceVersion()
89 return SH_IFACE_VERSION;
92 int CSourceHookImpl::GetImplVersion()
94 return SH_IMPL_VERSION;
97 int CSourceHookImpl::AddHook(Plugin plug, AddHookMode mode, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan,
98 ISHDelegate *handler, bool post)
100 if (mode != Hook_Normal && mode != Hook_VP && mode != Hook_DVP)
103 // Get info about hook manager
104 CHookManager hookManager(plug, myHookMan);
108 void *adjustediface = NULL;
109 void **cur_vtptr = NULL;
110 void *cur_vfnptr = NULL;
116 adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface) + thisptr_offs);
118 cur_vtptr = *reinterpret_cast<void***>(
119 reinterpret_cast<char*>(adjustediface) + hookManager.GetVtblOffs());
120 cur_vfnptr = reinterpret_cast<void*>(cur_vtptr + hookManager.GetVtblIdx());
125 adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface) + thisptr_offs);
127 cur_vtptr = *reinterpret_cast<void***>(
128 reinterpret_cast<char*>(adjustediface) + hookManager.GetVtblOffs());
129 cur_vfnptr = reinterpret_cast<void*>(cur_vtptr + hookManager.GetVtblIdx());
131 adjustediface = NULL;
135 adjustediface = NULL;
137 cur_vtptr = reinterpret_cast<void**>(iface);
138 cur_vfnptr = cur_vtptr + hookManager.GetVtblIdx();
143 CVfnPtr *vfnPtr = m_VfnPtrs.GetVfnPtr(cur_vfnptr);
146 // Could not create the vfnptr info object.
147 // This could be because a thunk generation on GCC
148 // has failed. See sourcehook_impl_cvfnptr.cpp
153 vfnPtr->AddHookMan(m_HookManList.GetHookMan(hookManager));
154 CIface &ifaceinst = vfnPtr->GetIface(adjustediface);
157 CHook hook(plug, thisptr_offs, handler,
159 m_HookIDMan.New(hookManager.GetProto(), hookManager.GetVtblOffs(), hookManager.GetVtblIdx(),
160 cur_vfnptr, adjustediface, plug, thisptr_offs, handler, post)
165 ifaceinst.GetPostHookList().push_back(hook);
167 ifaceinst.GetPreHookList().push_back(hook);
172 bool CSourceHookImpl::RemoveHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan,
173 ISHDelegate *handler, bool post)
175 // Get info about hook manager and compute adjustediface
176 CHookManager tmpHookMan(plug, myHookMan);
178 void *adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface)+thisptr_offs);
180 // Loop through all hooks and remove those which match:
181 // hookman, vfnptr, iface, plug, adjusted iface, this ptr offs, handler, post
182 CVector<int> removehooks;
183 m_HookIDMan.FindAllHooks(removehooks, tmpHookMan.GetProto(), tmpHookMan.GetVtblOffs(), tmpHookMan.GetVtblIdx(),
184 adjustediface, plug, thisptr_offs, handler, post);
186 if (removehooks.empty())
191 for (CVector<int>::iterator iter = removehooks.begin(); iter != removehooks.end(); ++iter)
193 if (RemoveHookByID(*iter))
199 bool CSourceHookImpl::RemoveHookByID(int hookid)
201 const CHookIDManager::Entry *hentry;
203 hentry = m_HookIDMan.QueryHook(hookid);
206 // hookid doesn't exist !
211 List<CVfnPtr>::iterator vfnptr_iter = m_VfnPtrs.find(hentry->vfnptr);
212 if (vfnptr_iter == m_VfnPtrs.end())
216 List<CIface>::iterator iface_iter = vfnptr_iter->GetIfaceList().find(hentry->adjustediface);
217 if (iface_iter == vfnptr_iter->GetIfaceList().end())
221 List<CHook> &hooks = hentry->post ? iface_iter->GetPostHookList() : iface_iter->GetPreHookList();
222 List<CHook>::iterator hook_iter = hooks.find(hookid);
223 if (hook_iter == hooks.end())
226 hook_iter->GetHandler()->DeleteThis();
229 List<CHook>::iterator oldhookiter = hook_iter;
230 hook_iter = hooks.erase(hook_iter);
232 for (CStack<CHookContext>::iterator ctx_iter = m_ContextStack.begin();
233 ctx_iter != m_ContextStack.end(); ++ctx_iter)
235 ctx_iter->HookRemoved(oldhookiter, hook_iter);
238 if (iface_iter->GetPreHookList().empty() && iface_iter->GetPostHookList().empty())
240 // -> Kill all contexts that use it!
241 for (CStack<CHookContext>::iterator ctx_iter = m_ContextStack.begin();
242 ctx_iter != m_ContextStack.end(); ++ctx_iter)
244 ctx_iter->IfaceRemoved(&(*iface_iter));
247 // There are no hooks on this iface anymore...
248 iface_iter = vfnptr_iter->GetIfaceList().erase(iface_iter);
250 if (vfnptr_iter->GetIfaceList().empty())
252 // No ifaces at all -> Deactivate the hook
254 for (CStack<CHookContext>::iterator ctx_iter = m_ContextStack.begin();
255 ctx_iter != m_ContextStack.end(); ++ctx_iter)
257 ctx_iter->VfnPtrRemoved(&(*vfnptr_iter));
260 RevertAndRemoveVfnPtr(vfnptr_iter);
264 m_HookIDMan.Remove(hookid);
268 List<CVfnPtr>::iterator CSourceHookImpl::RevertAndRemoveVfnPtr(List<CVfnPtr>::iterator vfnptr_iter)
270 ICleanupTask *cleanupTask = vfnptr_iter->GetCleanupTask();
272 // Some vfnptrs require cleanup.
273 // Concrete case: on GCC, when the original vtable entry is not even
274 // we generate an even-aligned thunk to call the original function.
275 // If the vfnptr is being removed from a pre hook on the vfnptr
276 // we have to delay the cleanup of this thunk until the hook loop is done
277 // (because the orig function call mechanism is going to use the thunk).
279 if (cleanupTask != NULL)
281 // If this vfnptr is in use in one of the hook loops running at the moment
282 // Schedule it for removal on the DEEPEST hook loop.
284 size_t numOfContexts = m_ContextStack.size();
285 // m_ContextStack.at(0) is the deepest hook context
286 // m_ContextStack.at(size-1) = m_ContextStack.front is the uppermost
288 bool cleanupImmedieately = true;
290 CVfnPtr *vfnPtrObjAddr = &(*vfnptr_iter);
291 for (size_t i = 0; i < numOfContexts; ++i)
293 CHookContext &context = m_ContextStack.at(i);
294 if (context.pVfnPtr == vfnPtrObjAddr)
296 // Found a hook context using this vfnptr at the moment.
297 context.m_CleanupTask = cleanupTask;
298 cleanupImmedieately = false; // Delay the cleanup
303 if (cleanupImmedieately)
305 cleanupTask->CleanupAndDeleteThis();
310 vfnptr_iter->Revert();
311 return m_VfnPtrs.erase(vfnptr_iter);
314 void CSourceHookImpl::SetRes(META_RES res)
316 *m_ContextStack.front().pCurRes = res;
319 META_RES CSourceHookImpl::GetPrevRes()
321 return *m_ContextStack.front().pPrevRes;
324 META_RES CSourceHookImpl::GetStatus()
326 return *m_ContextStack.front().pStatus;
330 const void *CSourceHookImpl::GetOrigRet()
332 return m_ContextStack.front().pOrigRet;
335 const void *CSourceHookImpl::GetOverrideRet()
337 return (*m_ContextStack.front().pStatus < MRES_OVERRIDE) ?
338 NULL : m_ContextStack.front().pOverrideRet;
341 void *CSourceHookImpl::GetIfacePtr()
343 // If in recall: return last one
344 if (m_ContextStack.front().m_State >= CHookContext::State_Recall_Pre &&
345 m_ContextStack.front().m_State <= CHookContext::State_Recall_PostVP)
347 return m_ContextStack.second().pIfacePtr;
351 return m_ContextStack.front().pIfacePtr;
355 void *CSourceHookImpl::GetOverrideRetPtr()
357 return m_ContextStack.front().pOverrideRet;
360 void CSourceHookImpl::UnloadPlugin(Plugin plug)
362 // 1) Remove all hooks by this plugin
364 CVector<int> removehooks;
365 m_HookIDMan.FindAllHooks(removehooks, plug);
367 for (CVector<int>::iterator iter = removehooks.begin(); iter != removehooks.end(); ++iter)
368 RemoveHookByID(*iter);
370 // 2) Remove all hook managers
371 for (CHookManList::iterator iter = m_HookManList.begin(); iter != m_HookManList.end(); )
373 if (iter->GetOwnerPlugin() == plug)
374 iter = RemoveHookManager(iter);
380 CHookManList::iterator CSourceHookImpl::RemoveHookManager(CHookManList::iterator hookman_iter)
383 for (CVfnPtrList::iterator vfnptr_iter = m_VfnPtrs.begin();
384 vfnptr_iter != m_VfnPtrs.end();)
386 if (!vfnptr_iter->HookManRemoved(&(*hookman_iter)))
388 // This vfnptr has no more hook managers
389 // and asks to be removed.
391 m_HookIDMan.RemoveAll(vfnptr_iter->GetPtr());
393 vfnptr_iter = RevertAndRemoveVfnPtr(vfnptr_iter);
401 return m_HookManList.erase(hookman_iter);
404 void CSourceHookImpl::RemoveHookManager(Plugin plug, HookManagerPubFunc pubFunc)
406 // Find the hook manager
407 CHookManList::iterator hookman_iter = m_HookManList.find(CHookManager::Descriptor(plug, pubFunc));
409 if (hookman_iter != m_HookManList.end())
411 RemoveHookManager(hookman_iter);
415 void CSourceHookImpl::SetIgnoreHooks(void *vfnptr)
418 ctx.m_State = CHookContext::State_Ignore;
419 m_ContextStack.push(ctx);
422 void CSourceHookImpl::ResetIgnoreHooks(void *vfnptr)
424 if (!m_ContextStack.empty() && m_ContextStack.front().m_State == CHookContext::State_Ignore)
426 // Actually use EndContext
427 // instead of m_ContextStack.pop directly
428 // because it runs the cleanup task if neccesary
429 EndContext(&(m_ContextStack.front()));
433 void *CSourceHookImpl::GetOrigVfnPtrEntry(void *vfnptr)
435 for (CVfnPtrList::iterator vfnptr_iter = m_VfnPtrs.begin(); vfnptr_iter != m_VfnPtrs.end(); ++vfnptr_iter)
437 if (vfnptr_iter->GetPtr() == vfnptr)
438 return vfnptr_iter->GetOrigEntry();
443 void CSourceHookImpl::DoRecall()
446 CHookContext &curCtx = m_ContextStack.front();
449 newCtx.m_State = curCtx.m_State + (CHookContext::State_Recall_Pre - CHookContext::State_Pre);
450 if (newCtx.m_State == CHookContext::State_Recall_Post || newCtx.m_State == CHookContext::State_Recall_PostVP)
452 // Also save orig ret
453 newCtx.pOrigRet = curCtx.pOrigRet;
456 // The hookfunc usually does this, but it won't have a chance to see it,
457 // so for recalls, we update status here if it's required
458 if (*curCtx.pCurRes > *curCtx.pStatus)
459 *curCtx.pStatus = *curCtx.pCurRes;
461 newCtx.pStatus = curCtx.pStatus;
462 newCtx.pOverrideRet = curCtx.pOverrideRet;
463 newCtx.pPrevRes = curCtx.pPrevRes;
464 newCtx.m_Iter = curCtx.m_Iter;
466 // Take this with us!
467 newCtx.pCurRes = curCtx.pCurRes;
469 m_ContextStack.push(newCtx);
470 curCtx.m_State = CHookContext::State_Dead;
473 IHookContext *CSourceHookImpl::SetupHookLoop(IHookManagerInfo *hi, void *vfnptr, void *thisptr, void **origCallAddr, META_RES *statusPtr,
474 META_RES *prevResPtr, META_RES *curResPtr, const void *origRetPtr, void *overrideRetPtr)
476 CHookContext *pCtx = NULL;
477 CHookContext *oldctx = m_ContextStack.empty() ? NULL : &m_ContextStack.front();
481 if (oldctx->m_State == CHookContext::State_Ignore)
483 *statusPtr = MRES_IGNORED;
484 oldctx->m_CallOrig = true;
485 oldctx->m_State = CHookContext::State_Dead;
487 List<CVfnPtr*> &vfnptr_list = static_cast<CHookManager*>(hi)->GetVfnPtrList();
488 List<CVfnPtr*>::iterator vfnptr_iter;
489 for (vfnptr_iter = vfnptr_list.begin();
490 vfnptr_iter != vfnptr_list.end(); ++vfnptr_iter)
492 if (**vfnptr_iter == vfnptr)
495 if (vfnptr_iter == vfnptr_list.end())
497 SH_ASSERT(false, ("How can a hook exist on a vfnptr which we don't have in our db?!"));
501 *origCallAddr = (*vfnptr_iter)->GetOrigCallAddr();
502 oldctx->pVfnPtr = *vfnptr_iter;
505 oldctx->pOrigRet = origRetPtr;
509 else if (oldctx->m_State >= CHookContext::State_Recall_Pre &&
510 oldctx->m_State <= CHookContext::State_Recall_PostVP)
514 *statusPtr = *(oldctx->pStatus);
515 *prevResPtr = *(oldctx->pPrevRes);
517 pCtx->m_Iter = oldctx->m_Iter;
519 // Only have possibility of calling the orig func in pre recall mode
520 pCtx->m_CallOrig = (oldctx->m_State == CHookContext::State_Recall_Pre ||
521 oldctx->m_State == CHookContext::State_Recall_PreVP);
523 overrideRetPtr = pCtx->pOverrideRet;
525 // When the status is low so there's no override return value and we're in a post recall,
526 // give it the orig return value as override return value.
527 if (pCtx->m_State == CHookContext::State_Recall_Post ||
528 pCtx->m_State == CHookContext::State_Recall_PostVP)
530 origRetPtr = oldctx->pOrigRet;
531 if (*statusPtr < MRES_OVERRIDE)
532 overrideRetPtr = const_cast<void*>(pCtx->pOrigRet);
538 pCtx = m_ContextStack.make_next();
539 pCtx->m_State = CHookContext::State_Born;
540 pCtx->m_CallOrig = true;
545 List<CVfnPtr*> &vfnptr_list = static_cast<CHookManager*>(hi)->GetVfnPtrList();
546 List<CVfnPtr*>::iterator vfnptr_iter;
547 for (vfnptr_iter = vfnptr_list.begin();
548 vfnptr_iter != vfnptr_list.end(); ++vfnptr_iter)
550 if (**vfnptr_iter == vfnptr)
553 if (vfnptr_iter == vfnptr_list.end())
555 pCtx->m_State = CHookContext::State_Dead;
559 pCtx->pVfnPtr = *vfnptr_iter;
560 *origCallAddr = pCtx->pVfnPtr->GetOrigCallAddr();
561 pCtx->pIface = pCtx->pVfnPtr->FindIface(thisptr);
564 pCtx->pStatus = statusPtr;
565 pCtx->pPrevRes = prevResPtr;
566 pCtx->pCurRes = curResPtr;
567 pCtx->pThisPtr = thisptr;
568 pCtx->pOverrideRet = overrideRetPtr;
569 pCtx->pOrigRet = origRetPtr;
574 void CSourceHookImpl::EndContext(IHookContext *pCtx)
576 // Do clean up task, if any is associated with this context
577 m_ContextStack.front().DoCleanupTaskAndDeleteIt();
579 m_ContextStack.pop();
582 void CSourceHookImpl::CompleteShutdown()
584 CVector<int> removehooks;
585 m_HookIDMan.FindAllHooks(removehooks);
587 for (CVector<int>::iterator iter = removehooks.begin(); iter != removehooks.end(); ++iter)
588 RemoveHookByID(*iter);
591 void CSourceHookImpl::PausePlugin(Plugin plug)
593 CVector<int> pausehooks;
594 m_HookIDMan.FindAllHooks(pausehooks, plug);
596 for (CVector<int>::iterator iter = pausehooks.begin(); iter != pausehooks.end(); ++iter)
597 PauseHookByID(*iter);
600 void CSourceHookImpl::UnpausePlugin(Plugin plug)
602 CVector<int> unpausehooks;
603 m_HookIDMan.FindAllHooks(unpausehooks, plug);
605 for (CVector<int>::iterator iter = unpausehooks.begin(); iter != unpausehooks.end(); ++iter)
606 UnpauseHookByID(*iter);
609 bool CSourceHookImpl::PauseHookByID(int hookid)
611 return SetHookPaused(hookid, true);
614 bool CSourceHookImpl::UnpauseHookByID(int hookid)
616 return SetHookPaused(hookid, false);
619 bool CSourceHookImpl::SetHookPaused(int hookid, bool paused)
621 const CHookIDManager::Entry *hentry;
623 hentry = m_HookIDMan.QueryHook(hookid);
626 // hookid doesn't exist !
631 List<CVfnPtr>::iterator vfnptr_iter = m_VfnPtrs.find(hentry->vfnptr);
632 if (vfnptr_iter == m_VfnPtrs.end())
636 List<CIface>::iterator iface_iter = vfnptr_iter->GetIfaceList().find(hentry->adjustediface);
637 if (iface_iter == vfnptr_iter->GetIfaceList().end())
641 List<CHook> &hooks = hentry->post ? iface_iter->GetPostHookList() : iface_iter->GetPreHookList();
642 List<CHook>::iterator hook_iter = hooks.find(hookid);
643 if (hook_iter == hooks.end())
646 hook_iter->SetPaused(paused);
650 //////////////////////////////////////////////////////////////////////////
652 //////////////////////////////////////////////////////////////////////////
653 ISHDelegate *CHookContext::GetNext()
662 m_Iter = List<CHook>::iterator();
666 case State_Recall_Pre:
672 m_Iter = pIface->GetPreHookList().begin();
675 SkipPaused(m_Iter, pIface->GetPreHookList());
677 if (m_Iter != pIface->GetPreHookList().end())
679 pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
680 return m_Iter->GetHandler();
684 // end of normal hooks -> VP
686 m_State = State_PreVP;
687 m_Iter = List<CHook>::iterator();
690 case State_Recall_PreVP:
691 m_State = State_PreVP;
693 pVPIface = pVfnPtr->FindIface(NULL);
697 m_Iter = pVPIface->GetPreHookList().begin();
700 SkipPaused(m_Iter, pVPIface->GetPreHookList());
702 if (m_Iter != pVPIface->GetPreHookList())
704 pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
705 return m_Iter->GetHandler();
709 // end VP hooks -> orig call
711 m_State = State_OrigCall;
715 m_Iter = List<CHook>::iterator();
716 m_State = State_Post;
723 m_Iter = pIface->GetPostHookList().begin();
726 SkipPaused(m_Iter, pIface->GetPostHookList());
728 if (m_Iter != pIface->GetPostHookList().end())
730 pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
731 return m_Iter->GetHandler();
734 // end of normal hooks -> VP
736 m_State = State_PostVP;
737 m_Iter = List<CHook>::iterator();
741 pVPIface = pVfnPtr->FindIface(NULL);
745 m_Iter = pVPIface->GetPostHookList().begin();
748 SkipPaused(m_Iter, pVPIface->GetPostHookList());
750 if (m_Iter != pVPIface->GetPostHookList())
752 pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
753 return m_Iter->GetHandler();
757 // end VP hooks -> done
759 m_State = State_Dead;
762 case State_Recall_Post:
763 // Skip pre hooks _and_ orig call
764 m_State = State_Post;
767 case State_Recall_PostVP:
768 // Skip pre hooks _and_ orig call
769 m_State = State_PostVP;
775 void *CHookContext::GetOverrideRetPtr()
780 const void *CHookContext::GetOrigRetPtr()
785 bool CHookContext::ShouldCallOrig()
790 void CHookContext::HookRemoved(List<CHook>::iterator oldhookiter, List<CHook>::iterator nexthookiter)
792 if (m_Iter == oldhookiter)
794 m_Iter = nexthookiter;
799 void CHookContext::IfaceRemoved(CIface *iface)
805 void CHookContext::VfnPtrRemoved(CVfnPtr *vfnptr)
807 if (pVfnPtr == vfnptr)
809 // Don't set pVfnPtr = NULL here!
810 // It may be used still.
811 // RevertAndRemoveVfnPtr uses it to find the hook context
812 // to which to attach the cleanup task of the vfnptr.
815 m_State = State_Dead;
819 void CHookContext::DoCleanupTaskAndDeleteIt()
821 if (m_CleanupTask != NULL)
823 m_CleanupTask->CleanupAndDeleteThis();