C++实现修改函数代码HOOK的封装方法
本文实例讲述了C++实现修改函数代码HOOK的封装方法,分享给大家供大家参考。具体实现方法如下:
一、对外的接口如下:
1.类初始化时对函数HOOK
2.取消挂钩:
voidUnHook();
3.重新挂钩:
voidReHook();
在初始化时HOOK的代码:
*(DWORD*)(m_btNewBytes+1)=(DWORD)pfnHook;
8个字节的代码地址0xB8,0x00,0x00,0x40,0x00,0xFF,0xE0,0x00 只要把第二位和第三位的数据改成函数的地址,调用原先的函数时就会调到自定义的函数执行.
二、实现方法:
.h头文件如下:
#ifndef _ULHOOK_H__ #define_ULHOOK_H__ #include<Windows.h> #pragmaonce classCULHook { public: CULHook(LPSTRlpszModName,LPSTRlpszFuncNme,PROCpfnHook); ~CULHook(void); //取消挂钩 voidUnHook(); //重新挂钩 voidReHook(); protected: PROCm_pfnOrig; BYTEm_btNewBytes[8]; BYTEm_btOldBytes[8]; HMODULEm_hModule; }; #endif
.cpp源文件如下:
#include"ULHook.h" CULHook::CULHook(LPSTRlpszModName,LPSTRlpszFuncNme,PROCpfnHook) { BYTEbtNewBytes[]={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_INFORMATIONmbi={0}; DWORDdwOldProtect; ::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); } } voidCULHook::UnHook() { if(m_pfnOrig!=NULL) { MEMORY_BASIC_INFORMATIONmbi={0}; DWORDdwOldProtect; ::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); } } voidCULHook::ReHook() { if(m_pfnOrig!=NULL) { MEMORY_BASIC_INFORMATIONmbi={0}; DWORDdwOldProtect; ::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++程序设计有所帮助。