#include "stdafx.h"
#include <map>
#include <vector>
#include <detours.h>
#pragma comment(lib, "detours.lib")
BOOL is_jcc_instruction(PBYTE pb)
{
if (!pb)
return FALSE;
if (0x70 <= pb[0] && pb[0] <= 0x7F)
{
return TRUE;
}
else if (pb[0] == 0xE3)
{
return TRUE;
}
else if (pb[0] == 0xE9 || pb[0] == 0xEA || pb[0] == 0xEB)
{
return TRUE;
}
else if (pb[0] == 0x0F && (0x80 <= pb[1] && pb[1] <= 0x8F))
{
return TRUE;
}
return FALSE;
}
BOOL is_jmp_instruction(PBYTE pb)
{
if (!pb)
return FALSE;
if (pb[0] == 0xE9 || pb[0] == 0xEA || pb[0] == 0xEB)
{
return TRUE;
}
else if (pb[0] == 0xFF && pb[1] == 0x25)
{
return TRUE;
}
return FALSE;
}
int main()
{
HMODULE hModule;
LPVOID lpvFunction;
hModule = GetModuleHandle(_T("KERNELBASE"));
if (hModule == NULL)
{
printf("baka\n");
return 1;
}
lpvFunction = GetProcAddress(hModule, "CreateFileA");
if (!lpvFunction)
{
printf("baka\n");
return 1;
}
BYTE bDst[256];
PVOID pDstPool;
PVOID pSrc, pSrcNext;
PVOID pTarget;
LONG lExtra;
UINT uSize;
std::vector<PVOID> vpTarget;
std::map<PVOID, BOOL> mpTarget;
pSrc = lpvFunction;
pDstPool = &bDst[256];
do
{
lExtra = 0;
pTarget = NULL;
pSrcNext = DetourCopyInstruction(bDst, &pDstPool, pSrc, &pTarget, &lExtra);
uSize = PBYTE(pSrcNext) - PBYTE(pSrc);
pSrc = pSrcNext;
if (pTarget)
{
if (is_jcc_instruction(bDst))
{
printf("jump if condition is met - target = %p\n", pTarget);
vpTarget.push_back(pTarget);
mpTarget[pTarget] = TRUE;
}
else if (bDst[0] == 0xFF)
{
if (bDst[1] == 0x15)
{
printf("call dword ptr [] - target = %p\n", pTarget);
}
else if (bDst[1] == 0x25)
{
printf("jmp dword ptr [] - target = %p\n", pTarget);
}
}
}
if (bDst[0] == 0xCC)
{
break;
}
else if (bDst[0] == 0xC2 || bDst[0] == 0xC3)
{
auto it = mpTarget.find(pSrcNext);
if (it == mpTarget.end())
{
break;
}
}
else if (is_jmp_instruction(bDst))
{
auto it = mpTarget.find(pSrcNext);
if (it == mpTarget.end())
{
break;
}
}
} while (TRUE);
printf("start = %p, end = %p, size = %d\n", lpvFunction, pSrcNext, PBYTE(pSrcNext) - PBYTE(lpvFunction));
return 0;
}