Fixed MetamodVersionInfo::GetGameDir always returning NULL or garbage.
1 /* ======== SourceHook ========
2 * vim: set ts=4 sw=4 tw=99 noet:
3 * Copyright (C) 2004-2010 Metamod:Source Development Team
4 * No warranties of any kind
8 * Author(s): Pavol "PM OnoTo" Marko
9 * Contributors: Scott "Damaged Soul" Ehlert
10 * ============================
14 * @file sourcehook.cpp
15 * @brief Contains the implementation of the SourceHook API
22 #include "sourcehook_impl.h"
27 int HashFunction<int>(const int & k)
32 int Compare<int>(const int & k1, const int & k2)
45 //////////////////////////////////////////////////////////////////////////
47 //////////////////////////////////////////////////////////////////////////
49 CVfnPtr *CVfnPtrList::GetVfnPtr(void *vfnptr)
51 iterator iter = find(vfnptr);
54 // No vfnptr info object found
55 // --> create a new one
56 CVfnPtr newVfnPtr(vfnptr);
65 // Initialization failed.
75 //////////////////////////////////////////////////////////////////////////
77 //////////////////////////////////////////////////////////////////////////
80 CSourceHookImpl::CSourceHookImpl()
83 CSourceHookImpl::~CSourceHookImpl()
88 int CSourceHookImpl::GetIfaceVersion()
90 return SH_IFACE_VERSION;
93 int CSourceHookImpl::GetImplVersion()
95 return SH_IMPL_VERSION;
98 int CSourceHookImpl::AddHook(Plugin plug, AddHookMode mode, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan,
99 ISHDelegate *handler, bool post)
101 if (mode != Hook_Normal && mode != Hook_VP && mode != Hook_DVP)
104 // Get info about hook manager
105 CHookManager hookManager(plug, myHookMan);
109 void *adjustediface = NULL;
110 void **cur_vtptr = NULL;
111 void *cur_vfnptr = NULL;
117 adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface) + thisptr_offs);
119 cur_vtptr = *reinterpret_cast<void***>(
120 reinterpret_cast<char*>(adjustediface) + hookManager.GetVtblOffs());
121 cur_vfnptr = reinterpret_cast<void*>(cur_vtptr + hookManager.GetVtblIdx());
126 adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface) + thisptr_offs);
128 cur_vtptr = *reinterpret_cast<void***>(
129 reinterpret_cast<char*>(adjustediface) + hookManager.GetVtblOffs());
130 cur_vfnptr = reinterpret_cast<void*>(cur_vtptr + hookManager.GetVtblIdx());
132 adjustediface = NULL;
136 adjustediface = NULL;
138 cur_vtptr = reinterpret_cast<void**>(iface);
139 cur_vfnptr = cur_vtptr + hookManager.GetVtblIdx();
144 CVfnPtr *vfnPtr = m_VfnPtrs.GetVfnPtr(cur_vfnptr);
147 // Could not create the vfnptr info object.
148 // This could be because a thunk generation on GCC
149 // has failed. See sourcehook_impl_cvfnptr.cpp
154 vfnPtr->AddHookMan(m_HookManList.GetHookMan(hookManager));
155 CIface &ifaceinst = vfnPtr->GetIface(adjustediface);
158 CHook hook(plug, thisptr_offs, handler,
160 m_HookIDMan.New(hookManager.GetProto(), hookManager.GetVtblOffs(), hookManager.GetVtblIdx(),
161 cur_vfnptr, adjustediface, plug, thisptr_offs, handler, post)
166 ifaceinst.GetPostHookList().push_back(hook);
168 ifaceinst.GetPreHookList().push_back(hook);
173 bool CSourceHookImpl::RemoveHook(Plugin plug, void *iface, int thisptr_offs, HookManagerPubFunc myHookMan,
174 ISHDelegate *handler, bool post)
176 // Get info about hook manager and compute adjustediface
177 CHookManager tmpHookMan(plug, myHookMan);
179 void *adjustediface = reinterpret_cast<void*>(reinterpret_cast<char*>(iface)+thisptr_offs);
181 // Loop through all hooks and remove those which match:
182 // hookman, vfnptr, iface, plug, adjusted iface, this ptr offs, handler, post
183 CVector<int> removehooks;
184 m_HookIDMan.FindAllHooks(removehooks, tmpHookMan.GetProto(), tmpHookMan.GetVtblOffs(), tmpHookMan.GetVtblIdx(),
185 adjustediface, plug, thisptr_offs, handler, post);
187 if (removehooks.empty())
192 for (CVector<int>::iterator iter = removehooks.begin(); iter != removehooks.end(); ++iter)
194 if (RemoveHookByID(*iter))
200 bool CSourceHookImpl::RemoveHookByID(int hookid)
202 const CHookIDManager::Entry *hentry;
204 hentry = m_HookIDMan.QueryHook(hookid);
207 // hookid doesn't exist !
212 List<CVfnPtr>::iterator vfnptr_iter = m_VfnPtrs.find(hentry->vfnptr);
213 if (vfnptr_iter == m_VfnPtrs.end())
217 List<CIface>::iterator iface_iter = vfnptr_iter->GetIfaceList().find(hentry->adjustediface);
218 if (iface_iter == vfnptr_iter->GetIfaceList().end())
222 List<CHook> &hooks = hentry->post ? iface_iter->GetPostHookList() : iface_iter->GetPreHookList();
223 List<CHook>::iterator hook_iter = hooks.find(hookid);
224 if (hook_iter == hooks.end())
227 hook_iter->GetHandler()->DeleteThis();
230 List<CHook>::iterator oldhookiter = hook_iter;
231 hook_iter = hooks.erase(hook_iter);
233 for (CStack<CHookContext>::iterator ctx_iter = m_ContextStack.begin();
234 ctx_iter != m_ContextStack.end(); ++ctx_iter)
236 ctx_iter->HookRemoved(oldhookiter, hook_iter);
239 if (iface_iter->GetPreHookList().empty() && iface_iter->GetPostHookList().empty())
241 // -> Kill all contexts that use it!
242 for (CStack<CHookContext>::iterator ctx_iter = m_ContextStack.begin();
243 ctx_iter != m_ContextStack.end(); ++ctx_iter)
245 ctx_iter->IfaceRemoved(&(*iface_iter));
248 // There are no hooks on this iface anymore...
249 iface_iter = vfnptr_iter->GetIfaceList().erase(iface_iter);
251 if (vfnptr_iter->GetIfaceList().empty())
253 // No ifaces at all -> Deactivate the hook
255 for (CStack<CHookContext>::iterator ctx_iter = m_ContextStack.begin();
256 ctx_iter != m_ContextStack.end(); ++ctx_iter)
258 ctx_iter->VfnPtrRemoved(&(*vfnptr_iter));
261 RevertAndRemoveVfnPtr(vfnptr_iter);
265 m_HookIDMan.Remove(hookid);
269 List<CVfnPtr>::iterator CSourceHookImpl::RevertAndRemoveVfnPtr(List<CVfnPtr>::iterator vfnptr_iter)
271 ICleanupTask *cleanupTask = vfnptr_iter->GetCleanupTask();
273 // Some vfnptrs require cleanup.
274 // Concrete case: on GCC, when the original vtable entry is not even
275 // we generate an even-aligned thunk to call the original function.
276 // If the vfnptr is being removed from a pre hook on the vfnptr
277 // we have to delay the cleanup of this thunk until the hook loop is done
278 // (because the orig function call mechanism is going to use the thunk).
280 if (cleanupTask != NULL)
282 // If this vfnptr is in use in one of the hook loops running at the moment
283 // Schedule it for removal on the DEEPEST hook loop.
285 size_t numOfContexts = m_ContextStack.size();
286 // m_ContextStack.at(0) is the deepest hook context
287 // m_ContextStack.at(size-1) = m_ContextStack.front is the uppermost
289 bool cleanupImmedieately = true;
291 CVfnPtr *vfnPtrObjAddr = &(*vfnptr_iter);
292 for (size_t i = 0; i < numOfContexts; ++i)
294 CHookContext &context = m_ContextStack.at(i);
295 if (context.pVfnPtr == vfnPtrObjAddr)
297 // Found a hook context using this vfnptr at the moment.
298 context.m_CleanupTask = cleanupTask;
299 cleanupImmedieately = false; // Delay the cleanup
304 if (cleanupImmedieately)
306 cleanupTask->CleanupAndDeleteThis();
311 vfnptr_iter->Revert();
312 return m_VfnPtrs.erase(vfnptr_iter);
315 void CSourceHookImpl::SetRes(META_RES res)
317 *m_ContextStack.front().pCurRes = res;
320 META_RES CSourceHookImpl::GetPrevRes()
322 return *m_ContextStack.front().pPrevRes;
325 META_RES CSourceHookImpl::GetStatus()
327 return *m_ContextStack.front().pStatus;
331 const void *CSourceHookImpl::GetOrigRet()
333 return m_ContextStack.front().pOrigRet;
336 const void *CSourceHookImpl::GetOverrideRet()
338 return (*m_ContextStack.front().pStatus < MRES_OVERRIDE) ?
339 NULL : m_ContextStack.front().pOverrideRet;
342 void *CSourceHookImpl::GetIfacePtr()
344 // If in recall: return last one
345 if (m_ContextStack.front().m_State >= CHookContext::State_Recall_Pre &&
346 m_ContextStack.front().m_State <= CHookContext::State_Recall_PostVP)
348 return m_ContextStack.second().pIfacePtr;
352 return m_ContextStack.front().pIfacePtr;
356 void *CSourceHookImpl::GetOverrideRetPtr()
358 return m_ContextStack.front().pOverrideRet;
361 void CSourceHookImpl::UnloadPlugin(Plugin plug, UnloadListener *listener)
363 // 1) Remove all hooks by this plugin
365 CVector<int> removehooks;
366 m_HookIDMan.FindAllHooks(removehooks, plug);
368 for (CVector<int>::iterator iter = removehooks.begin(); iter != removehooks.end(); ++iter)
369 RemoveHookByID(*iter);
371 // 2) Remove all hook managers
372 for (CHookManList::iterator iter = m_HookManList.begin(); iter != m_HookManList.end(); )
374 if (iter->GetOwnerPlugin() == plug)
375 iter = RemoveHookManager(iter);
380 // Fix for bug 5034. It's pretty tricky to find whether hookmanagers owned by this
381 // plugin are active. We could change how hook managers are tracked in SH, and lazily
382 // free them as the context stack drops to 0, or we could change the pubfunc API to
383 // know whether it's active or not. Rather than deal with this extra complexity, we
384 // just conservatively wait until the context stack hits 0 before unloading.
385 if (m_ContextStack.size() == 0)
387 listener->ReadyToUnload(plug);
391 m_PendingUnloads.push_back(new PendingUnload(listener, plug));
395 CHookManList::iterator CSourceHookImpl::RemoveHookManager(CHookManList::iterator hookman_iter)
398 for (CVfnPtrList::iterator vfnptr_iter = m_VfnPtrs.begin();
399 vfnptr_iter != m_VfnPtrs.end();)
401 if (!vfnptr_iter->HookManRemoved(&(*hookman_iter)))
403 // This vfnptr has no more hook managers
404 // and asks to be removed.
406 m_HookIDMan.RemoveAll(vfnptr_iter->GetPtr());
408 vfnptr_iter = RevertAndRemoveVfnPtr(vfnptr_iter);
416 return m_HookManList.erase(hookman_iter);
419 void CSourceHookImpl::RemoveHookManager(Plugin plug, HookManagerPubFunc pubFunc)
421 // Find the hook manager
422 CHookManList::iterator hookman_iter = m_HookManList.find(CHookManager::Descriptor(plug, pubFunc));
424 if (hookman_iter != m_HookManList.end())
426 RemoveHookManager(hookman_iter);
430 void CSourceHookImpl::SetIgnoreHooks(void *vfnptr)
433 ctx.m_State = CHookContext::State_Ignore;
434 m_ContextStack.push(ctx);
437 void CSourceHookImpl::ResetIgnoreHooks(void *vfnptr)
439 if (!m_ContextStack.empty() && m_ContextStack.front().m_State == CHookContext::State_Ignore)
441 // Actually use EndContext
442 // instead of m_ContextStack.pop directly
443 // because it runs the cleanup task if neccesary
444 EndContext(&(m_ContextStack.front()));
448 void *CSourceHookImpl::GetOrigVfnPtrEntry(void *vfnptr)
450 for (CVfnPtrList::iterator vfnptr_iter = m_VfnPtrs.begin(); vfnptr_iter != m_VfnPtrs.end(); ++vfnptr_iter)
452 if (vfnptr_iter->GetPtr() == vfnptr)
453 return vfnptr_iter->GetOrigEntry();
458 void CSourceHookImpl::DoRecall()
461 CHookContext &curCtx = m_ContextStack.front();
464 newCtx.m_State = curCtx.m_State + (CHookContext::State_Recall_Pre - CHookContext::State_Pre);
465 if (newCtx.m_State == CHookContext::State_Recall_Post || newCtx.m_State == CHookContext::State_Recall_PostVP)
467 // Also save orig ret
468 newCtx.pOrigRet = curCtx.pOrigRet;
471 // The hookfunc usually does this, but it won't have a chance to see it,
472 // so for recalls, we update status here if it's required
473 if (*curCtx.pCurRes > *curCtx.pStatus)
474 *curCtx.pStatus = *curCtx.pCurRes;
476 newCtx.pStatus = curCtx.pStatus;
477 newCtx.pOverrideRet = curCtx.pOverrideRet;
478 newCtx.pPrevRes = curCtx.pPrevRes;
479 newCtx.m_Iter = curCtx.m_Iter;
481 // Take this with us!
482 newCtx.pCurRes = curCtx.pCurRes;
484 m_ContextStack.push(newCtx);
485 curCtx.m_State = CHookContext::State_Dead;
488 IHookContext *CSourceHookImpl::SetupHookLoop(IHookManagerInfo *hi, void *vfnptr, void *thisptr, void **origCallAddr, META_RES *statusPtr,
489 META_RES *prevResPtr, META_RES *curResPtr, const void *origRetPtr, void *overrideRetPtr)
491 CHookContext *pCtx = NULL;
492 CHookContext *oldctx = m_ContextStack.empty() ? NULL : &m_ContextStack.front();
496 if (oldctx->m_State == CHookContext::State_Ignore)
498 *statusPtr = MRES_IGNORED;
499 oldctx->m_CallOrig = true;
500 oldctx->m_State = CHookContext::State_Dead;
502 List<CVfnPtr*> &vfnptr_list = static_cast<CHookManager*>(hi)->GetVfnPtrList();
503 List<CVfnPtr*>::iterator vfnptr_iter;
504 for (vfnptr_iter = vfnptr_list.begin();
505 vfnptr_iter != vfnptr_list.end(); ++vfnptr_iter)
507 if (**vfnptr_iter == vfnptr)
510 if (vfnptr_iter == vfnptr_list.end())
512 SH_ASSERT(false, ("How can a hook exist on a vfnptr which we don't have in our db?!"));
516 *origCallAddr = (*vfnptr_iter)->GetOrigCallAddr();
517 oldctx->pVfnPtr = *vfnptr_iter;
520 oldctx->pOrigRet = origRetPtr;
524 else if (oldctx->m_State >= CHookContext::State_Recall_Pre &&
525 oldctx->m_State <= CHookContext::State_Recall_PostVP)
529 *statusPtr = *(oldctx->pStatus);
530 *prevResPtr = *(oldctx->pPrevRes);
532 pCtx->m_Iter = oldctx->m_Iter;
534 // Only have possibility of calling the orig func in pre recall mode
535 pCtx->m_CallOrig = (oldctx->m_State == CHookContext::State_Recall_Pre ||
536 oldctx->m_State == CHookContext::State_Recall_PreVP);
538 overrideRetPtr = pCtx->pOverrideRet;
540 // When the status is low so there's no override return value and we're in a post recall,
541 // give it the orig return value as override return value.
542 if (pCtx->m_State == CHookContext::State_Recall_Post ||
543 pCtx->m_State == CHookContext::State_Recall_PostVP)
545 origRetPtr = oldctx->pOrigRet;
546 if (*statusPtr < MRES_OVERRIDE)
547 overrideRetPtr = const_cast<void*>(pCtx->pOrigRet);
553 pCtx = m_ContextStack.make_next();
554 pCtx->m_State = CHookContext::State_Born;
555 pCtx->m_CallOrig = true;
560 List<CVfnPtr*> &vfnptr_list = static_cast<CHookManager*>(hi)->GetVfnPtrList();
561 List<CVfnPtr*>::iterator vfnptr_iter;
562 for (vfnptr_iter = vfnptr_list.begin();
563 vfnptr_iter != vfnptr_list.end(); ++vfnptr_iter)
565 if (**vfnptr_iter == vfnptr)
568 if (vfnptr_iter == vfnptr_list.end())
570 pCtx->m_State = CHookContext::State_Dead;
574 pCtx->pVfnPtr = *vfnptr_iter;
575 *origCallAddr = pCtx->pVfnPtr->GetOrigCallAddr();
576 pCtx->pIface = pCtx->pVfnPtr->FindIface(thisptr);
579 pCtx->pStatus = statusPtr;
580 pCtx->pPrevRes = prevResPtr;
581 pCtx->pCurRes = curResPtr;
582 pCtx->pThisPtr = thisptr;
583 pCtx->pOverrideRet = overrideRetPtr;
584 pCtx->pOrigRet = origRetPtr;
589 void CSourceHookImpl::ResolvePendingUnloads(bool force)
591 List<PendingUnload *>::iterator iter = m_PendingUnloads.begin();
592 while (iter != m_PendingUnloads.end())
594 PendingUnload *unload = *iter;
596 if (!force && !unload->deactivated())
598 // Unless being forced, wait one drop of the context stack
599 // before actually unloading. Otherwise, we'll still return
600 // to unloaded memory.
601 unload->deactivate();
606 unload->listener()->ReadyToUnload(unload->plugin());
608 iter = m_PendingUnloads.erase(iter);
613 void CSourceHookImpl::EndContext(IHookContext *pCtx)
615 // Do clean up task, if any is associated with this context
616 m_ContextStack.front().DoCleanupTaskAndDeleteIt();
618 m_ContextStack.pop();
620 // If we've reached 0 contexts and there are pending unloads,
622 if (m_ContextStack.size() == 0 && m_PendingUnloads.size() != 0)
623 ResolvePendingUnloads();
626 void CSourceHookImpl::CompleteShutdown()
628 CVector<int> removehooks;
629 m_HookIDMan.FindAllHooks(removehooks);
631 for (CVector<int>::iterator iter = removehooks.begin(); iter != removehooks.end(); ++iter)
632 RemoveHookByID(*iter);
635 void CSourceHookImpl::PausePlugin(Plugin plug)
637 CVector<int> pausehooks;
638 m_HookIDMan.FindAllHooks(pausehooks, plug);
640 for (CVector<int>::iterator iter = pausehooks.begin(); iter != pausehooks.end(); ++iter)
641 PauseHookByID(*iter);
644 void CSourceHookImpl::UnpausePlugin(Plugin plug)
646 CVector<int> unpausehooks;
647 m_HookIDMan.FindAllHooks(unpausehooks, plug);
649 for (CVector<int>::iterator iter = unpausehooks.begin(); iter != unpausehooks.end(); ++iter)
650 UnpauseHookByID(*iter);
653 bool CSourceHookImpl::PauseHookByID(int hookid)
655 return SetHookPaused(hookid, true);
658 bool CSourceHookImpl::UnpauseHookByID(int hookid)
660 return SetHookPaused(hookid, false);
663 bool CSourceHookImpl::SetHookPaused(int hookid, bool paused)
665 const CHookIDManager::Entry *hentry;
667 hentry = m_HookIDMan.QueryHook(hookid);
670 // hookid doesn't exist !
675 List<CVfnPtr>::iterator vfnptr_iter = m_VfnPtrs.find(hentry->vfnptr);
676 if (vfnptr_iter == m_VfnPtrs.end())
680 List<CIface>::iterator iface_iter = vfnptr_iter->GetIfaceList().find(hentry->adjustediface);
681 if (iface_iter == vfnptr_iter->GetIfaceList().end())
685 List<CHook> &hooks = hentry->post ? iface_iter->GetPostHookList() : iface_iter->GetPreHookList();
686 List<CHook>::iterator hook_iter = hooks.find(hookid);
687 if (hook_iter == hooks.end())
690 hook_iter->SetPaused(paused);
694 //////////////////////////////////////////////////////////////////////////
696 //////////////////////////////////////////////////////////////////////////
697 ISHDelegate *CHookContext::GetNext()
706 m_Iter = List<CHook>::iterator();
710 case State_Recall_Pre:
716 m_Iter = pIface->GetPreHookList().begin();
719 SkipPaused(m_Iter, pIface->GetPreHookList());
721 if (m_Iter != pIface->GetPreHookList().end())
723 pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
724 return m_Iter->GetHandler();
728 // end of normal hooks -> VP
730 m_State = State_PreVP;
731 m_Iter = List<CHook>::iterator();
734 case State_Recall_PreVP:
735 m_State = State_PreVP;
737 pVPIface = pVfnPtr->FindIface(NULL);
741 m_Iter = pVPIface->GetPreHookList().begin();
744 SkipPaused(m_Iter, pVPIface->GetPreHookList());
746 if (m_Iter != pVPIface->GetPreHookList())
748 pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
749 return m_Iter->GetHandler();
753 // end VP hooks -> orig call
755 m_State = State_OrigCall;
759 m_Iter = List<CHook>::iterator();
760 m_State = State_Post;
767 m_Iter = pIface->GetPostHookList().begin();
770 SkipPaused(m_Iter, pIface->GetPostHookList());
772 if (m_Iter != pIface->GetPostHookList().end())
774 pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
775 return m_Iter->GetHandler();
778 // end of normal hooks -> VP
780 m_State = State_PostVP;
781 m_Iter = List<CHook>::iterator();
785 pVPIface = pVfnPtr->FindIface(NULL);
789 m_Iter = pVPIface->GetPostHookList().begin();
792 SkipPaused(m_Iter, pVPIface->GetPostHookList());
794 if (m_Iter != pVPIface->GetPostHookList())
796 pIfacePtr = reinterpret_cast<void*>(reinterpret_cast<char*>(pThisPtr) - m_Iter->GetThisPointerOffset());
797 return m_Iter->GetHandler();
801 // end VP hooks -> done
803 m_State = State_Dead;
806 case State_Recall_Post:
807 // Skip pre hooks _and_ orig call
808 m_State = State_Post;
811 case State_Recall_PostVP:
812 // Skip pre hooks _and_ orig call
813 m_State = State_PostVP;
819 void *CHookContext::GetOverrideRetPtr()
824 const void *CHookContext::GetOrigRetPtr()
829 bool CHookContext::ShouldCallOrig()
834 void CHookContext::HookRemoved(List<CHook>::iterator oldhookiter, List<CHook>::iterator nexthookiter)
836 if (m_Iter == oldhookiter)
838 m_Iter = nexthookiter;
843 void CHookContext::IfaceRemoved(CIface *iface)
849 void CHookContext::VfnPtrRemoved(CVfnPtr *vfnptr)
851 if (pVfnPtr == vfnptr)
853 // Don't set pVfnPtr = NULL here!
854 // It may be used still.
855 // RevertAndRemoveVfnPtr uses it to find the hook context
856 // to which to attach the cleanup task of the vfnptr.
859 m_State = State_Dead;
863 void CHookContext::DoCleanupTaskAndDeleteIt()
865 if (m_CleanupTask != NULL)
867 m_CleanupTask->CleanupAndDeleteThis();