1 /* ======== SourceHook ========
3 * No warranties of any kind
4 * ============================
9 * @brief Contains the implementation of the SourceHook API
13 #include "sourcehook_impl.h"
15 #if SH_SYS == SH_SYS_WIN32
17 #elif SH_SYS == SH_SYS_LINUX
18 # include <sys/mman.h>
19 # include <sys/limits.h>
22 # define PAGESIZE 4096
26 #if SH_RUNTIME_CODEGEN == 1
27 # if SH_COMP == SH_COMP_GCC
28 # define SH_CCC_CODESIZE 15
30 //void SH_CCC_MakeGate(void *origthisptr, unsigned char* &ptr, void *origvtable, int i)
33 # elif SH_COMP == SH_COMP_MSVC
34 # define SH_CCC_CODESIZE 19
35 void SH_CCC_MakeGate(void *origthisptr, void *ccthisptr, unsigned char* ptr, void *origfunc)
37 // --Subtract old this pointer to get the offset
38 // 00417EDF 81 E9 A1 7B 33 01 sub ecx,1337BA1h
41 *reinterpret_cast<void**>(ptr) = ccthisptr;
43 // --Add it to the new this pointer
44 // 00417EE5 81 C1 37 13 37 13 add ecx,13371337h
47 *reinterpret_cast<void**>(ptr) = origthisptr;
50 // 00417EEB B8 EF BE AD DE mov eax,0DEADBEEFh
52 *reinterpret_cast<void**>(ptr) = origfunc;
55 // 00417EF0 FF E0 jmp eax
65 CSourceHookImpl::CSourceHookImpl()
68 #if SH_SYS == SH_SYS_WIN32
70 GetSystemInfo(&sysinfo);
71 m_PageSize = sysinfo.dwPageSize;
72 #elif SH_SYS == SH_SYS_LINUX
73 m_PageSize = PAGESIZE;
75 # error Unsupported system
79 CSourceHookImpl::~CSourceHookImpl()
84 bool CSourceHookImpl::IsPluginInUse(Plugin plug)
86 // Iterate through all hookers which are in this plugin
87 // Iterate through their hooks
88 // If a hook from an other plugin is found, return true
89 // Return false otherwise
91 for (HookerInfoList::iterator iter = m_Hookers.begin(); iter != m_Hookers.end(); ++iter)
93 if (iter->plug == plug && !iter->ifaces.empty())
95 for (std::list<HookerInfo::Iface>::iterator iter2 = iter->ifaces.begin(); iter2 != iter->ifaces.end(); ++iter2)
97 std::list<HookerInfo::Iface::Hook>::iterator iter3;
98 for (iter3 = iter2->hooks_pre.begin(); iter3 != iter2->hooks_pre.end(); ++iter3)
99 if (iter3->plug == plug)
101 for (iter3 = iter2->hooks_post.begin(); iter3 != iter2->hooks_post.end(); ++iter3)
102 if (iter3->plug == plug)
110 void CSourceHookImpl::UnloadPlugin(Plugin plug)
112 // Get a list of hookers that are in this plugin and are used by other plugins
114 HookerInfoList tmphookers;
116 for (HookerInfoList::iterator iter = m_Hookers.begin(); iter != m_Hookers.end();
117 erase ? iter=m_Hookers.erase(iter) : ++iter)
119 if (iter->plug == plug && !iter->ifaces.empty())
122 for (std::list<HookerInfo::Iface>::iterator iter2 = iter->ifaces.begin();
123 iter2 != iter->ifaces.end(); ++iter2)
125 for (std::list<HookerInfo::Iface::Hook>::iterator iter3 = iter2->hooks_pre.begin();
126 iter3 != iter2->hooks_pre.end(); ++iter3)
128 if (iter3->plug != plug)
134 for (iter3 = iter2->hooks_post.begin(); iter3 != iter2->hooks_post.end(); ++iter3)
136 if (iter3->plug != plug)
144 tmphookers.push_back(*iter);
155 for (HookerInfoList::iterator iter = tmphookers.begin(); iter != tmphookers.end(); ++iter)
157 // Shutdown all ifaces and remove the hooks from this plugin from their lists
158 for (std::list<HookerInfo::Iface>::iterator iter2 = iter->ifaces.begin(); iter2 != iter->ifaces.end();
159 erase ? iter2 = iter->ifaces.erase(iter2) : ++iter2)
161 *(reinterpret_cast<void**>(reinterpret_cast<char*>(iter2->ptr) + iter->vtbl_offs)
162 + iter->vtbl_idx) = iter2->orig_entry;
164 for (std::list<HookerInfo::Iface::Hook>::iterator iter3 = iter2->hooks_pre.begin(); iter3 != iter2->hooks_pre.end();
165 iter3->plug == plug ? iter3=iter2->hooks_pre.erase(iter3) : ++iter3) {}
166 for (std::list<HookerInfo::Iface::Hook>::iterator iter3 = iter2->hooks_post.begin(); iter3 != iter2->hooks_post.end();
167 iter3->plug == plug ? iter3=iter2->hooks_post.erase(iter3) : ++iter3) {}
169 erase = iter2->hooks_pre.empty() && iter2->hooks_post.empty();
172 if (iter->ifaces.empty())
174 // Nothing more to do; no more ifaces to re-register
178 // 2) Find a suitable hooker in an other plugin
179 HookerInfoList::iterator newHooker = FindHooker(m_Hookers.begin(), m_Hookers.end(),
180 iter->proto, iter->vtbl_offs, iter->vtbl_idx, iter->thisptr_offs);
181 if (newHooker == m_Hookers.end())
183 // This should _never_ happen.
184 // If there is a hook from an other plugin, the plugin must have provided a hooker as well.
188 // AddHook should make sure that every plugin only has _one_ hooker for _one_ proto/vi/vo
189 SH_ASSERT(newHooker->plug != plug);
192 newHooker->func(HA_Register, &(*iter));
193 for (std::list<HookerInfo::Iface>::iterator iter2 = iter->ifaces.begin(); iter2 != iter->ifaces.end();
196 reinterpret_cast<void**>(reinterpret_cast<char*>(iter2->ptr) + iter->vtbl_offs)[iter->vtbl_idx] =
197 reinterpret_cast<void**>(reinterpret_cast<char*>(iter->hookfunc_inst) + iter->hookfunc_vtbl_offs)[iter->hookfunc_vtbl_idx];
202 void CSourceHookImpl::CompleteShutdown()
204 // Go through all hookers and shut down all interfaces
205 for (HookerInfoList::iterator iter = m_Hookers.begin(); iter != m_Hookers.end(); ++iter)
207 for (std::list<HookerInfo::Iface>::iterator iter2 = iter->ifaces.begin(); iter2 != iter->ifaces.end(); ++iter2)
209 // Note that we can pass iter->func as "myHooker" because it is only used
211 for (std::list<HookerInfo::Iface::Hook>::iterator iter3 = iter2->hooks_pre.begin(); iter3 != iter2->hooks_pre.end(); ++iter3)
212 RemoveHook(iter3->plug, iter2->ptr, iter->func, iter3->handler, false);
213 for (std::list<HookerInfo::Iface::Hook>::iterator iter3 = iter2->hooks_post.begin(); iter3 != iter2->hooks_post.end(); ++iter3)
214 RemoveHook(iter3->plug, iter2->ptr, iter->func, iter3->handler, true);
219 bool CSourceHookImpl::AddHook(Plugin plug, void *iface, int ifacesize, Hooker myHooker, ISHDelegate *handler, bool post)
221 // 1) Get info about the hooker
223 if (myHooker(HA_GetInfo, &tmp) != 0)
226 // Add the proposed hooker to the _end_ of the list if the plugin doesn't have a hooker with this proto/vo/vi registered
227 HookerInfoList::iterator hookeriter;
228 for (hookeriter = m_Hookers.begin(); hookeriter != m_Hookers.end(); ++hookeriter)
230 if (hookeriter->plug == plug && strcmp(hookeriter->proto, tmp.proto) == 0 &&
231 hookeriter->vtbl_offs == tmp.vtbl_offs && hookeriter->vtbl_idx == tmp.vtbl_idx &&
232 hookeriter->thisptr_offs == tmp.thisptr_offs)
235 if (hookeriter == m_Hookers.end())
237 // No such hooker from this plugin yet, add it!
240 m_Hookers.push_back(tmp);
243 // Then, search for a suitable hooker (from the beginning)
244 HookerInfoList::iterator hooker = FindHooker(m_Hookers.begin(), m_Hookers.end(), tmp.proto, tmp.vtbl_offs, tmp.vtbl_idx, tmp.thisptr_offs);
245 SH_ASSERT(hooker != m_Hookers.end());
247 // Tell it to store the pointer if it's not already active
248 if (hooker->ifaces.empty())
249 hooker->func(HA_Register, &(*hooker));
251 std::list<HookerInfo::Iface>::iterator ifsiter = std::find(hooker->ifaces.begin(), hooker->ifaces.end(), iface);
253 if (ifsiter == hooker->ifaces.end())
255 HookerInfo::Iface ifs;
257 ifs.callclass = GetCallClass(iface, ifacesize);
258 void *vtableptr = *reinterpret_cast<void**>(reinterpret_cast<char*>(iface) + hooker->vtbl_offs);
259 SetMemAccess(vtableptr, sizeof(void*) * hooker->vtbl_idx, SH_MEM_READ | SH_MEM_WRITE);
260 ifs.orig_entry = (*reinterpret_cast<void***>(reinterpret_cast<char*>(iface) + hooker->vtbl_offs))[hooker->vtbl_idx];
261 (*reinterpret_cast<void***>(reinterpret_cast<char*>(iface) + hooker->vtbl_offs))[hooker->vtbl_idx] =
262 (*reinterpret_cast<void***>(reinterpret_cast<char*>(hooker->hookfunc_inst) + hooker->hookfunc_vtbl_offs))[hooker->hookfunc_vtbl_idx];
263 hooker->ifaces.push_back(ifs);
264 ifsiter = hooker->ifaces.end();
267 HookerInfo::Iface::Hook hookinfo;
268 hookinfo.handler = handler;
269 hookinfo.plug = plug;
271 ifsiter->hooks_post.push_back(hookinfo);
273 ifsiter->hooks_pre.push_back(hookinfo);
276 // Now that it is done, check whether we have to update any callclasses
277 for (Impl_CallClassList::iterator cciter = m_CallClasses.begin(); cciter != m_CallClasses.end(); ++cciter)
279 if (cciter->iface == iface)
281 ApplyCallClassPatch(*cciter, tmp.vtbl_offs, tmp.vtbl_idx, ifsiter->orig_entry);
283 // We can assume that there is no more callclass with the same iface
291 bool CSourceHookImpl::RemoveHook(Plugin plug, void *iface, Hooker myHooker, ISHDelegate *handler, bool post)
294 if (myHooker(HA_GetInfo, &tmp) != 0)
297 // Find the hooker and the hook
298 HookerInfoList::iterator hooker = FindHooker(m_Hookers.begin(), m_Hookers.end(),
299 tmp.proto, tmp.vtbl_offs, tmp.vtbl_idx, tmp.thisptr_offs);
300 if (hooker == m_Hookers.end())
303 for (std::list<HookerInfo::Iface>::iterator ifaceiter = hooker->ifaces.begin(); ifaceiter != hooker->ifaces.end(); ++ifaceiter)
305 if (ifaceiter->ptr == iface)
307 std::list<HookerInfo::Iface::Hook> &hooks = post ? ifaceiter->hooks_post : ifaceiter->hooks_pre;
309 for (std::list<HookerInfo::Iface::Hook>::iterator hookiter = hooks.begin();
310 hookiter != hooks.end(); erase ? hookiter = hooks.erase(hookiter) : ++hookiter)
312 erase = hookiter->plug == plug && hookiter->handler->IsEqual(handler);
314 hookiter->handler->DeleteThis(); // Make the _plugin_ delete the handler object
316 if (ifaceiter->hooks_post.empty() && ifaceiter->hooks_pre.empty())
318 // Deactivate the hook
319 (*reinterpret_cast<void***>(reinterpret_cast<char*>(ifaceiter->ptr) +
320 hooker->vtbl_offs))[hooker->vtbl_idx]= ifaceiter->orig_entry;
322 // Release the callclass
323 ReleaseCallClass(ifaceiter->callclass);
325 // Remove the iface info
326 hooker->ifaces.erase(ifaceiter);
328 if (hooker->ifaces.empty())
329 hooker->func(HA_Unregister, NULL);
331 // :TODO: Better return value? Or none?
338 void *CSourceHookImpl::GetCallClass(void *iface, size_t size)
340 for (Impl_CallClassList::iterator cciter = m_CallClasses.begin(); cciter != m_CallClasses.end(); ++cciter)
342 if (cciter->iface == iface)
344 ++cciter->refcounter;
349 // The layout of callclasses is:
350 // Copy of the class; vtable entries pointing to gates
351 // Pointer to the corresponding CallClass object
352 // Copy of the class; vtable entries pointing to original functions
355 char *ptr = new char[size * 2 + sizeof(void*)];
356 tmp.ptr = reinterpret_cast<void*>(ptr);
357 memcpy(reinterpret_cast<void*>(ptr), iface, size);
358 memcpy(reinterpret_cast<void*>(ptr + size + sizeof(void*)), iface, size);
363 // Go through _all_ hooks and apply any needed patches
364 for (HookerInfoList::iterator hooker = m_Hookers.begin(); hooker != m_Hookers.end(); ++hooker)
366 for (std::list<HookerInfo::Iface>::iterator ifaceiter = hooker->ifaces.begin(); ifaceiter != hooker->ifaces.end(); ++ifaceiter)
368 if (ifaceiter->ptr == iface)
370 if (!ApplyCallClassPatch(tmp, hooker->vtbl_offs, hooker->vtbl_idx, ifaceiter->orig_entry))
378 m_CallClasses.push_back(tmp);
379 // The object has to be followed by the pointer to the vtable info object
380 *reinterpret_cast<void**>(ptr + size) = &m_CallClasses.back();
384 void CSourceHookImpl::ReleaseCallClass(void *ptr)
386 Impl_CallClassList::iterator iter = std::find(m_CallClasses.begin(), m_CallClasses.end(), ptr);
387 if (iter == m_CallClasses.end())
390 if (iter->refcounter < 1)
392 FreeCallClass(*iter);
393 m_CallClasses.erase(iter);
397 void CSourceHookImpl::FreeCallClass(CallClass &cc)
399 for (CallClass::VTableList::iterator vtbliter = cc.vtables.begin(); vtbliter != cc.vtables.end(); ++vtbliter)
401 #if SH_RUNTIME_CODEGEN == 1
402 // Delete generated callgates
403 for (std::list<int>::iterator cgiter = vtbliter->patches.begin(); cgiter != vtbliter->patches.end(); ++cgiter)
405 char *cgptr = reinterpret_cast<char**>(vtbliter->ptr)[*cgiter];
409 delete [] reinterpret_cast<char*>(vtbliter->ptr);
411 delete [] reinterpret_cast<char*>(cc.ptr);
414 bool CSourceHookImpl::ApplyCallClassPatch(CallClass &cc, int vtbl_offs, int vtbl_idx, void *orig_entry)
416 char *ptr = reinterpret_cast<char*>(cc.ptr);
417 void *vtable = *reinterpret_cast<void**>(ptr + vtbl_offs);
419 // Check whether we already know that vtable
420 CallClass::VTableList::iterator vtbliter = std::find(cc.vtables.begin(),
421 cc.vtables.end(), reinterpret_cast<void*>(vtable));
422 int actvtablesize=MAX_VTABLE_LEN;
423 if (vtbliter == cc.vtables.end())
425 CallClass::VTable newvtableinfo;
426 int pagesnum = (MAX_VTABLE_LEN % m_PageSize == 0) ? MAX_VTABLE_LEN / m_PageSize : MAX_VTABLE_LEN / m_PageSize + 1;
427 // Set all pages in the range to readwrite
429 char *pagebegin = reinterpret_cast<char*>(vtable) - (reinterpret_cast<int>(vtable) % m_PageSize);
430 for (int ipage = 0; ipage < pagesnum; ++ipage)
432 if (!SetMemAccess(reinterpret_cast<void*>(pagebegin + ipage * m_PageSize), 1,
433 SH_MEM_READ | SH_MEM_WRITE))
435 // We can't go here anymore
436 actvtablesize = static_cast<int>((pagebegin + ipage * m_PageSize) - reinterpret_cast<char*>(vtable));
440 if (actvtablesize < 1)
442 // We can't access the vtable -> Quit
445 // Create a new vtable
446 newvtableinfo.ptr = reinterpret_cast<void*>(new char[actvtablesize]);
447 // Fill it with the information from the old vtable
448 memcpy(newvtableinfo.ptr, vtable, actvtablesize);
449 newvtableinfo.actsize = actvtablesize;
450 // Set the pointer in the object and add it to the list of already known vtables
451 *reinterpret_cast<void**>(ptr + vtbl_offs) = newvtableinfo.ptr;
452 cc.vtables.push_back(newvtableinfo);
454 vtbliter = cc.vtables.end();
456 // :TODO: When not codegen, patch the other vtable?
459 // Check whether we already have this patch
460 if (std::find(vtbliter->patches.begin(), vtbliter->patches.end(), vtbl_idx) == vtbliter->patches.end())
465 void *callgate = NULL;
466 #if SH_RUNTIME_CODEGEN == 1
467 unsigned char *cggen = new unsigned char[SH_CCC_CODESIZE];
468 SH_CCC_MakeGate(cc.iface, cc.ptr, cggen, orig_entry);
469 callgate = (void*)cggen;
470 SetMemAccess(callgate, SH_CCC_CODESIZE, SH_MEM_READ | SH_MEM_WRITE | SH_MEM_EXEC);
473 #error Not supported yet!
475 vtbliter->patches.push_back(vtbl_idx);
476 reinterpret_cast<void**>(vtbliter->ptr)[vtbl_idx] = callgate;
482 CSourceHookImpl::HookerInfoList::iterator CSourceHookImpl::FindHooker(HookerInfoList::iterator begin,
483 HookerInfoList::iterator end, const char *proto, int vtblofs, int vtblidx, int thisptrofs)
485 for (HookerInfoList::iterator hookeriter = m_Hookers.begin(); hookeriter != m_Hookers.end(); ++hookeriter)
487 if (strcmp(hookeriter->proto, proto) == 0 && hookeriter->vtbl_offs == vtblofs && hookeriter->vtbl_idx == vtblidx &&
488 hookeriter->thisptr_offs == thisptrofs)
495 void CSourceHookImpl::SetRes(META_RES res)
500 META_RES CSourceHookImpl::GetPrevRes()
505 META_RES CSourceHookImpl::GetStatus()
510 const void *CSourceHookImpl::GetOrigRet()
515 const void *CSourceHookImpl::GetOverrideRet()
517 return m_OverrideRet;
520 META_RES &CSourceHookImpl::GetCurResRef()
525 META_RES &CSourceHookImpl::GetPrevResRef()
530 META_RES &CSourceHookImpl::GetStatusRef()
535 void CSourceHookImpl::SetOrigRet(const void *ptr)
540 void CSourceHookImpl::SetOverrideRet(const void *ptr)
545 void CSourceHookImpl::SetIfacePtr(void *ptr)
549 void *CSourceHookImpl::GetIfacePtr()