#pragma once namespace detail { class protect_guard { public: protect_guard(void* base, size_t len, uint32_t flags) { _base = base; _length = len; if (!win_api::virtual_protect(base, len, flags, reinterpret_cast(&_old))) { log_info_("failed to protect virtual memory."); EXIT_PROCESS(NULL); } } ~protect_guard() { win_api::virtual_protect(_base, _length, _old, reinterpret_cast(&_old)); } private: void* _base; size_t _length; uint32_t _old{}; }; } class c_vfunc_hook { public: bool setup(void* base); size_t estimate_vftbl_length(std::uintptr_t* vftbl_start); template void hook_index(const int index, T fun) { new_vftb1[index + 1] = reinterpret_cast(fun); } void unhook_index(const int index) const { new_vftb1[index] = old_vftbl[index]; } void unhook_all() { if (old_vftbl != nullptr) { auto guard = detail::protect_guard{ class_base, sizeof(uintptr_t), PAGE_READWRITE }; *static_cast(class_base) = old_vftbl; old_vftbl = nullptr; } } template T get_original(const int index) { return reinterpret_cast(old_vftbl[index]); } private: void* class_base; size_t vftbl_len; uintptr_t* new_vftb1; uintptr_t* old_vftbl; LPCVOID search_base = nullptr; bool wasAllocated = false; };