C++完成修正函數代碼HOOK的封裝辦法。本站提示廣大學習愛好者:(C++完成修正函數代碼HOOK的封裝辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C++完成修正函數代碼HOOK的封裝辦法正文
本文實例講述了C++完成修正函數代碼HOOK的封裝辦法,分享給年夜家供年夜家參考。詳細完成辦法以下:
1、對外的接口以下:
1. 類初始化時對函數HOOK
2. 撤消掛鉤:
void UnHook();
3. 從新掛鉤:
void ReHook();
在初始化時HOOK的代碼:
*(DWORD*)(m_btNewBytes+1) = (DWORD)pfnHook;
8個字節的代碼地址 0xB8, 0x00, 0x00,0x40,0x00,0xFF,0xE0,0x00 只需把第二位和第三位的數據改成函數的地址,挪用本來的函數時就會調到自界說的函數履行.
2、完成辦法:
.h頭文件以下:
#ifndef _ULHOOK_H__
#define _ULHOOK_H__
#include <Windows.h>
#pragma once
class CULHook
{
public:
CULHook(LPSTR lpszModName, LPSTR lpszFuncNme, PROC pfnHook);
~CULHook(void);
//撤消掛鉤
void UnHook();
//從新掛鉤
void ReHook();
protected:
PROC m_pfnOrig;
BYTE m_btNewBytes[8];
BYTE m_btOldBytes[8];
HMODULE m_hModule;
};
#endif
.cpp源文件以下:
#include "ULHook.h"
CULHook::CULHook(LPSTR lpszModName, LPSTR lpszFuncNme, PROC pfnHook)
{
BYTE btNewBytes[] = {0xB8, 0x00, 0x00,0x40,0x00,0xFF,0xE0,0x00};
memcpy(m_btNewBytes, btNewBytes, 8);
*(DWORD*)(m_btNewBytes+1) = (DWORD)pfnHook;
m_hModule = ::LoadLibraryA(lpszModName);
if (NULL == m_hModule)
{
m_pfnOrig = NULL;
return;
}
m_pfnOrig = (PROC)::GetProcAddress(m_hModule, lpszFuncNme);
if (NULL != m_pfnOrig)
{
MEMORY_BASIC_INFORMATION mbi = {0};
DWORD dwOldProtect;
::VirtualQuery(m_pfnOrig, &mbi, sizeof(mbi));
::VirtualProtect(m_pfnOrig, 8, PAGE_READWRITE, &dwOldProtect);
memcpy(m_btOldBytes, m_pfnOrig, 8);
::WriteProcessMemory(GetCurrentProcess(), (VOID*)m_pfnOrig, m_btNewBytes, 8, NULL);
::VirtualProtect(m_pfnOrig, 8, dwOldProtect, NULL);
}
}
CULHook::~CULHook(void)
{
UnHook();
if (m_hModule!=NULL)
{
::FreeLibrary(m_hModule);
}
}
void CULHook::UnHook()
{
if (m_pfnOrig != NULL)
{
MEMORY_BASIC_INFORMATION mbi = {0};
DWORD dwOldProtect;
::VirtualQuery(m_pfnOrig, &mbi, sizeof(mbi));
::VirtualProtect(m_pfnOrig, 8, PAGE_READWRITE, &dwOldProtect);
::WriteProcessMemory(GetCurrentProcess(), (VOID*)m_pfnOrig, m_btOldBytes, 8, NULL);
::VirtualProtect(m_pfnOrig, 8, dwOldProtect, NULL);
}
}
void CULHook::ReHook()
{
if (m_pfnOrig != NULL)
{
MEMORY_BASIC_INFORMATION mbi = {0};
DWORD dwOldProtect;
::VirtualQuery(m_pfnOrig, &mbi, sizeof(mbi));
::VirtualProtect(m_pfnOrig, 8, PAGE_READWRITE, &dwOldProtect);
::WriteProcessMemory(GetCurrentProcess(), (VOID*)m_pfnOrig, m_btNewBytes, 8, NULL);
::VirtualProtect(m_pfnOrig, 8, dwOldProtect, NULL);
}
}
願望本文所述對年夜家的C++法式設計有所贊助。