下面是我的APIHOOK类的源代码,该源代码是根据J.R的思路重新整理他的源代码来的:
/*HookAPI.h*/
#include "windows.h"
class CAPIHOOK
{
public:
CAPIHOOK(PSTR pszCalleeModName,PSTR pszFuncName,PROC pfnHook,HANDLE prochandle,HMODULE hmod);
"CAPIHOOK();
operator PROC(){return (m_pfnOrig);};
public:
static PVOID sm_pvMaxAppAddr;
static CAPIHOOK* sm_pHead;
CAPIHOOK* m_pNext;
PCSTR m_pszCalleeModName;
PCSTR m_pszFuncName;
PROC m_pfnOrig;
PROC m_pfnHook;
BOOL m_fExcludeAPIHookMod;
HMODULE m_module;
HANDLE m_handle;
private:
pfnOrig,PROC pfnHook,BOOL fExcludeAPIHookMod);
void WINAPI ReplaceIATEntryInOneMod(PCSTR pszCalleeModName,PROC pfnOrig,PROC pfnHook,HMODULE hmodcaller,HANDLE handle);
void WINAPI FixupNewlyLoadedModule(HMODULE hmod,DWORD dwFlags);
FARPROC WINAPI GetProcAddress(HMODULE hmod,PCSTR pszProcName);
};
/*HookApi.cpp*/
#include "hookapi.h"
#include <assert.h>
#include "imagehlp.h"
PVOID CAPIHOOK::sm_pvMaxAppAddr = NULL;
const BYTE cPushOpCode = 0x68;
CAPIHOOK *CAPIHOOK::sm_pHead = NULL;
CAPIHOOK::CAPIHOOK(PSTR pszCalleeModName, PSTR pszFuncName, PROC pfnHook,
HANDLE prochandle, HMODULE hmod)
{
m_handle = prochandle;
if (sm_pvMaxAppAddr == NULL)
{
SYSTEM_INFO si;
GetSystemInfo(&si);
sm_pvMaxAppAddr = si.lpMaximumApplicationAddress;
}
m_pNext = sm_pHead;
sm_pHead = this;
m_pszCalleeModName = pszCalleeModName;
m_pszFuncName = pszFuncName;
m_pfnHook = pfnHook;
m_pfnOrig = ::GetProcAddress(GetModuleHandleA(pszCalleeModName),m_pszFuncName);
assert(m_pfnOrig != NULL);
if (m_pfnOrig == NULL)
{
return;
}
if (m_pfnOrig > sm_pvMaxAppAddr)
{
PBYTE pb = (PBYTE)m_pfnOrig;
if (pb[0] == cPushOpCode)
{
PVOID pv = *(PVOID*) &pb;
m_pfnOrig = (PROC)pv;
}
}
m_module = GetModuleHandle(pszCalleeModName);
ReplaceIATEntryInOneMod(m_pszCalleeModName, m_pfnOrig, m_pfnHook, m_module,prochandle);
}
CAPIHOOK::"CAPIHOOK()
{
ReplaceIATEntryInOneMod(m_pszCalleeModName, m_pfnHook, m_pfnOrig, m_module,m_handle);
CAPIHOOK *p = sm_pHead;
if (p == this)
{
sm_pHead = p->m_pNext;
}
else
{
BOOL fFound = FALSE;
for (; !fFound && (p->m_pNext != NULL); p = p->m_pNext)
{
if (p->m_pNext == this)
{
p->m_pNext = p->m_pNext->m_pNext;
break;
}
}
assert(fFound);
}
}
void WINAPI CAPIHOOK::FixupNewlyLoadedModule(HMODULE hmod, DWORD dwFlags)
{
if ((hmod != NULL) && ((dwFlags &LOAD_LIBRARY_AS_DATAFILE) == 0))
{
for (CAPIHOOK *p = sm_pHead; p != NULL; p = p->m_pNext)
{
ReplaceIATEntryInOneMod(p->m_pszCalleeModName, p->m_pfnOrig, p->m_pfnHook,hmod, m_handle);
}
}
}
FARPROC WINAPI CAPIHOOK::GetProcAddress(HMODULE hmod, PCSTR pszProcName)
{
FARPROC pfn = ::GetProcAddress(hmod, pszProcName);
CAPIHOOK *p = sm_pHead;
for (; (pfn != NULL) && (p != NULL); p = p->m_pNext