Skip to content

2.6 Hook: VTable Swap

DK edited this page Sep 20, 2023 · 3 revisions

VTable Swap

API

Swaps a virtual method table function with target function

  • vtbl : pointer to virtual method table (base address of class object)
  • index : index of the virtual function in the virtual method table
  • funcInfo : FUNC_INFO wrapped function
  • patch : prolog patch before detouring to target function
VMTHookHandle AddVMTHook(
    void* a_vtbl,
    std::uint16_t a_index,
    FuncInfo a_funcInfo,
    Patch* a_patch
) noexcept

Example

using namespace DKUtil::Alias;

class Dummy
{
public:
    void MsgA() { INFO("Called MsgA"sv); } // 0
    void MsgB() { INFO("Called MsgB"sv); } // 1
};

// target dummy vtbl
Dummy* dummy = new Dummy();

// target function signature
using MsgFunc = std::add_pointer_t<void(Dummy*)>;
MsgFunc oldMsgA;
MsgFunc oldMsgB;

// swap function
void MsgC(Dummy* a_this) { 
    // call original function
    oldMsgA(a_this);
    oldMsgB(a_this);
}

auto _Hook_MsgA = DKUtil::Hook::AddVMTHook(dummy, 0, FUNC_INFO(MsgC));
auto _Hook_MsgB = DKUtil::Hook::AddVMTHook(dummy, 1, FUNC_INFO(MsgC));

// save original function
oldMsgA = reinterpret_cast<MsgFunc>(_Hook_MsgA->OldAddress);
oldMsgB = reinterpret_cast<MsgFunc>(_Hook_MsgB->OldAddress);

_Hook_MsgA->Enable();
_Hook_MsgB->Enable();