add Hooking

This commit is contained in:
mii443
2024-11-01 16:26:24 +09:00
parent dc65dd07f0
commit 1d5f93f881
2 changed files with 88 additions and 0 deletions

22
src/Hooking.cpp Normal file
View File

@ -0,0 +1,22 @@
#include "Hooking.hpp"
std::map<std::string, IHook *> IHook::hooks;
bool IHook::Exists(const std::string &name) {
return hooks.find(name) != hooks.end();
}
void IHook::Register(IHook *hook) {
hooks[hook->name] = hook;
}
void IHook::Unregister(IHook *hook) {
hooks.erase(hook->name);
}
void IHook::DestroyAll() {
for (auto &hook : hooks) {
hook.second->Destroy();
}
hooks.clear();
}

66
src/Hooking.hpp Normal file
View File

@ -0,0 +1,66 @@
// Refer to https://github.com/pushrax/OpenVR-SpaceCalibrator/blob/master/OpenVR-SpaceCalibratorDriver/Hooking.h
#pragma once
#include <MinHook.h>
#include <map>
#include <string>
class IHook {
public:
const std::string name;
IHook(const std::string &name) : name(name) { }
virtual ~IHook() { }
virtual void Destroy() = 0;
static bool Exists(const std::string &name);
static void Register(IHook *hook);
static void Unregister(IHook *hook);
static void DestroyAll();
private:
static std::map<std::string, IHook *> hooks;
};
template<class FuncType> class Hook : public IHook {
public:
FuncType originalFunc = nullptr;
Hook(const std::string &name) : IHook(name) { }
bool CreateHookInObjectVTable(void *object, int vtableOffset, void *detourFunction) {
void **vtable = *((void ***)object);
targetFunc = vtable[vtableOffset];
auto err = MH_CreateHook(targetFunc, detourFunction, (LPVOID *)&originalFunc);
if (err != MH_OK) {
vr::VRDriverLog()->Log("Failed to create hook.".c_str());
return false;
}
err = MH_EnableHook(targetFunc);
if (err != MH_OK) {
vr::VRDriverLog()->Log("Failed to enable hook.".c_str());
MH_RemoveHook(targetFunc);
return false;
}
vr::VRDriverLog()->Log("Hook enabled.".c_str());
enabled = true;
return true;
}
void Destroy() {
if (enabled) {
MH_RemoveHook(targetFunc);
enabled = false;
}
}
private:
bool enabled = false;
void* targetFunc = nullptr;
};