OldSchoolHack

Registrieren / Anmelden Deutsch

VMTHook class x86 und AMD64 kompatibel

icon Thema: [Coding] VMTHook class x86 und AMD64 kompatibel

Anmeldungsdatum: Feb 2011

Beiträge: 26

TEXT Code:
  1. #ifndef __VMTHOOK_H__
  2. #define __VMTHOOK_H__
  3.  
  4. #include <Windows.h>
  5.  
  6. class CVMTHook
  7. {
  8. public:
  9. CVMTHook(void* instance);
  10. ~CVMTHook();
  11. void* hookFunction(size_t iIndex, void* pfnHook);
  12. void* getOriginalFunction(size_t iIndex);
  13. void setHookEnabled(bool bEnabled=true);
  14. protected:
  15. size_t m_iNumIndices;
  16. void** m_pOriginalVTable;
  17. void** m_pNewVTable;
  18. void*** m_pInstance;
  19. };
  20.  
  21. #endif //__VMTHOOK_H__

TEXT Code:
  1. #include "VMTHook.h"
  2.  
  3. CVMTHook::CVMTHook(void* instance)
  4. {
  5. HANDLE hProcessHeap;
  6.  
  7. if(instance)
  8. {
  9. m_pInstance = (void***) instance;
  10. m_pOriginalVTable = *m_pInstance;
  11.  
  12. //Count number of Pointers in the table
  13.  
  14. m_iNumIndices = 0;
  15.  
  16. //TODO: check if pointer into .text section
  17. while(m_pOriginalVTable[m_iNumIndices])
  18. {
  19. m_iNumIndices++;
  20. }
  21.  
  22.  
  23. //Allocate memory on the heap for our own copy of the table
  24.  
  25. hProcessHeap = GetProcessHeap();
  26.  
  27. if(hProcessHeap)
  28. {
  29. m_pNewVTable = (void**) HeapAlloc(hProcessHeap, 0, sizeof(void*) * m_iNumIndices);
  30. if(m_pNewVTable)
  31. {
  32. memcpy(m_pNewVTable, m_pOriginalVTable, sizeof(void*) * m_iNumIndices);
  33. setHookEnabled();
  34. }
  35. }
  36. }
  37. }
  38.  
  39. CVMTHook::~CVMTHook()
  40. {
  41. HANDLE hProcessHeap;
  42.  
  43. //Reset the VTable pointer
  44. if(*m_pInstance == m_pNewVTable)
  45. {
  46. *m_pInstance = m_pOriginalVTable;
  47. }
  48.  
  49. //Free our copy of the VTable
  50. hProcessHeap = GetProcessHeap();
  51. if(hProcessHeap)
  52. {
  53.  
  54. HeapFree(hProcessHeap, 0, m_pNewVTable);
  55. }
  56. }
  57.  
  58.  
  59. void* CVMTHook::getOriginalFunction(size_t iIndex)
  60. {
  61. return m_pOriginalVTable[iIndex];
  62. }
  63.  
  64. void* CVMTHook::hookFunction(size_t iIndex, void* pfnHook)
  65. {
  66. //Valid index?
  67. if(iIndex >= m_iNumIndices)
  68. return NULL;
  69.  
  70. //Write new pointer
  71. m_pNewVTable[iIndex]=pfnHook;
  72.  
  73. //And return pointer to original function
  74. return m_pOriginalVTable[iIndex];
  75. }
  76.  
  77. void CVMTHook::setHookEnabled(bool bEnabled)
  78. {
  79. if(bEnabled)
  80. {
  81. //Point to our copy of the VTable
  82. *m_pInstance=m_pNewVTable;
  83. }
  84. else
  85. {
  86. //Point to the original VTable
  87. *m_pInstance=m_pOriginalVTable;
  88. }
  89. }
  90.  

Credits: Inurface, myself and me kk