我試圖寫一個簡單的掛鉤類,在目標地址安裝一個鉤子返回true和迂迴流入自定義函數。C++ memcpy的,沒有變化
Main.cpp的
#include "SingleHook.h"
#include <iostream>
using namespace std;
void originalFunction()
{
cout << "originalFunction()" << endl;
}
void fakeFunction()
{
cout << "fakeFunction()" << endl;
}
void main()
{
SingleHook sHook((DWORD)originalFunction, (DWORD)fakeFunction);
originalFunction(); //Should call the original function
sHook.InstallHook();
originalFunction(); //Should call the fake function
sHook.UninstallHook();
originalFunction(); //Should again call the original function
cin.get();
}
SingleHook.h
#pragma once
#define HLength 6
#include <windows.h>
class SingleHook {
private:
void* hookTarget;
byte originalBytes[HLength];
byte hookBytes[HLength];
public:
SingleHook(DWORD originalFunction, DWORD targetFunction)
{
//backing up original bytes
::memcpy(originalBytes, &originalFunction, HLength);
//generating hook bytes
hookBytes[0] = 0x68; //push
hookBytes[1] = ((byte*)targetFunction)[0];
hookBytes[2] = ((byte*)targetFunction)[1];
hookBytes[3] = ((byte*)targetFunction)[2];
hookBytes[4] = ((byte*)targetFunction)[3];
hookBytes[5] = 0xC3; //retn
//setting up hook target
hookTarget = &originalFunction;
}
void* InvokeOriginalFunction(...);
void InstallHook();
void UninstallHook();
};
SingleHook.cpp
#include "SingleHook.h"
void* SingleHook::InvokeOriginalFunction(...)
{
UninstallHook();
//TODO INVOKE ORIGINAL SOMEHOW
InstallHook();
return nullptr;
}
void SingleHook::InstallHook()
{
DWORD oldProt;
::VirtualProtect(hookTarget, HLength, PAGE_EXECUTE_READWRITE, &oldProt);
::memcpy(hookTarget, hookBytes, HLength);
::VirtualProtect(hookTarget, HLength, oldProt, nullptr);
}
void SingleHook::UninstallHook()
{
DWORD oldProt;
::VirtualProtect(hookTarget, HLength, PAGE_EXECUTE_READWRITE, &oldProt);
::memcpy(hookTarget, originalBytes, HLength);
::VirtualProtect(hookTarget, HLength, oldProt, nullptr);
}
現在的問題是叔當我安裝鉤子,並嘗試呼叫originalFunction()
它仍然進入原來的功能,並沒有打電話給fakeFunction()
...我仔細檢查了代碼,一切似乎都很好,但必須有一個陷阱。
你的標題是沒有意義的。 'memcpy()'不返回一個布爾值,並且在這段代碼中沒有任何地方可以檢查它返回的結果。 – EJP