Advertisement
vovan333

Best VMT hooking class ever

Nov 14th, 2017
376
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #pragma once
  2. #include "Include.h"
  3.  
  4. class VMTHook
  5. {
  6.     static int Unprotect(void* region)
  7.     {
  8.         MEMORY_BASIC_INFORMATION mbi;
  9.         VirtualQuery((LPCVOID)region, &mbi, sizeof(mbi));
  10.         VirtualProtect(mbi.BaseAddress, mbi.RegionSize, PAGE_READWRITE, &mbi.Protect);
  11.         return mbi.Protect;
  12.     }
  13.  
  14.     static void Protect(void* region, int protection)
  15.     {
  16.         MEMORY_BASIC_INFORMATION mbi;
  17.         VirtualQuery((LPCVOID)region, &mbi, sizeof(mbi));
  18.         VirtualProtect(mbi.BaseAddress, mbi.RegionSize, protection, &mbi.Protect);
  19.     }
  20.  
  21.     public:
  22.  
  23.     /*
  24.     * pObjectInstance: pointer to an pObjectInstance of a class
  25.     * hookFn: function to overwrite with
  26.     * methodOffset: 0 = method 1, 1 = method 2 etc...
  27.     * return: original function
  28.     */
  29.  
  30.     static void* Install(void* pObjectInstance, void* hookFn, int methodOffset)
  31.     {
  32.         intptr_t vtable = *((intptr_t*)pObjectInstance);
  33.         intptr_t entry = vtable + sizeof(intptr_t) * methodOffset;
  34.         intptr_t original = *((intptr_t*)entry);
  35.  
  36.         int originalProtection = Unprotect((void*)entry);
  37.         *((intptr_t*)entry) = (intptr_t)hookFn;
  38.         Protect((void*)entry, originalProtection);
  39.  
  40.         return (void*)original;
  41.     }
  42. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement