fairly simple shit but i like it, minimalistic <3
hook.h
Code:
#pragma once
#include <Windows.h>
#include <memory>
class malloc_deleter
{
public:
void operator()( void* ptr ) { free( ptr ); }
};
// abstracted vftbl hooking interface
class DynamicHooker
{
public:
DynamicHooker( void* Instance ); // simple ctor to setup the core var. (interface layer)
virtual ~DynamicHooker( ); // avoiding memory leaks if you use inheritance (i may use it in some update lol)
// with pointer to a base class. (ref. virtual keyword before dtor)
// (implementation layer)
public:
void* _1337( unsigned Index, void* Destination ); // do the cool stuff.
protected: // yeah, i may use inheritance XD
std::shared_ptr<void*> m_tableCopy; // where we can do dirty stuff
std::unique_ptr<void*> m_originalTable; // backup for detaching hooks
DWORD ProtectionFlags; // virtualprotect.
};
hook.cpp
Code:
#include "Hook.h"
DynamicHooker::DynamicHooker( void* Instance )
{
m_originalTable = std::make_unique<void*>( *( void** ) ( Instance ) ); // setup the smart ptr (though, it's not really needed here)
unsigned iterator = 0;
while ( m_originalTable.get( ) [ iterator ] )
iterator++; // get function count
//m_tableCopy = std::shared_ptr<void*>( ( void** ) malloc( sizeof( void* ) * iterator ), free );
m_tableCopy = std::shared_ptr<void*>( ( void** ) malloc( sizeof( void* ) * iterator ), malloc_deleter( ) );
VirtualProtect( Instance, sizeof( void* ), PAGE_READWRITE, &ProtectionFlags ); // just to make sure..
*( void*** ) ( Instance ) = m_tableCopy.get( ); // every vftbl access will be redirected to use our copied array.
VirtualProtect( Instance, sizeof( void* ), ProtectionFlags, nullptr );
}
DynamicHooker::~DynamicHooker( )
{
}
void* DynamicHooker::_1337( unsigned Index, void * Destination )
{
VirtualProtect( m_tableCopy.get( ) [ Index ], sizeof( void* ), PAGE_READWRITE, &ProtectionFlags );
m_tableCopy.get( ) [ Index ] = Destination; // ´make daddy happy
VirtualProtect( m_tableCopy.get( ) [ Index ], sizeof( void* ), ProtectionFlags, nullptr );
return m_originalTable.get( ) [ Index ]; // return a backup in case we wanna call this again O.o
}
btw., dont ask why i allocated with malloc instead of with new.