After a some googling I found a way to modify the VTable of a Class, but in my case I just have a pointer to my class as well as an interface to cast it to. I need to redirect one of those functions (in a DLL; no source code) to one of my functions. Problem is I don't know on which index the function is on, so in order to find it I tried scanning the VTable for the pointer to that function.
Is there any way to do this?
Here is my code so far:
typedef DWORD (__thiscall *CW_FUNC)();
class ClassWriter
{
public:
PVOID m_hObj;
PVOID *__vfptr;
PVOID m_old[256];
void SetObj(PVOID hObj)
{
m_hObj = hObj;
__vfptr = *(PVOID **)hObj;
}
void AddOverride(int offset, PVOID newfunc)
{
DWORD dwNull;
m_old[offset] = __vfptr[offset];
VirtualProtect(__vfptr + offset * 4, 4, PAGE_EXECUTE_READWRITE, &dwNull);
__vfptr[offset] = newfunc;
}
int GetOffset(PVOID func)
{
for (int i = 0; __vfptr[i] != NULL; i++)
{
if (func == __vfptr[i]) return i;
}
}
CW_FUNC GetFunc(int offset)
{
return (CW_FUNC)m_old[offset];
}
};
void WINAPI ChangeFunc()
{
ClassWriter cw;
HMODULE hMod = GetModuleHandle("dll_to_change.dll");
IMyInterface *myObj = (IMyInterface*)GetProcAddress(hMod, "GetMyClass")();
cw.SetObj(myObj);
int d = cw.GetOffset(myObj->MyFunction);
cw.AddOverride(d, OverrideFunction);
}