interception_win.cc [plain text]
#ifdef _WIN32
#include "interception.h"
#include <windows.h>
namespace __interception {
bool GetRealFunctionAddress(const char *func_name, uptr *func_addr) {
const char *DLLS[] = {
"msvcr80.dll",
"msvcr90.dll",
"kernel32.dll",
NULL
};
*func_addr = 0;
for (size_t i = 0; *func_addr == 0 && DLLS[i]; ++i) {
*func_addr = (uptr)GetProcAddress(GetModuleHandleA(DLLS[i]), func_name);
}
return (*func_addr != 0);
}
static void _memset(void *p, int value, size_t sz) {
for (size_t i = 0; i < sz; ++i)
((char*)p)[i] = (char)value;
}
static void _memcpy(void *dst, void *src, size_t sz) {
char *dst_c = (char*)dst,
*src_c = (char*)src;
for (size_t i = 0; i < sz; ++i)
dst_c[i] = src_c[i];
}
static void WriteJumpInstruction(char *jmp_from, char *to) {
ptrdiff_t offset = to - jmp_from - 5;
*jmp_from = '\xE9';
*(ptrdiff_t*)(jmp_from + 1) = offset;
}
bool OverrideFunction(uptr old_func, uptr new_func, uptr *orig_old_func) {
#ifdef _WIN64
# error OverrideFunction was not tested on x64
#endif
const int POOL_SIZE = 1024;
static char *pool = NULL;
static size_t pool_used = 0;
if (pool == NULL) {
pool = (char*)VirtualAlloc(NULL, POOL_SIZE,
MEM_RESERVE | MEM_COMMIT,
PAGE_EXECUTE_READWRITE);
if (pool == NULL)
return false;
_memset(pool, 0xCC , POOL_SIZE);
}
char* old_bytes = (char*)old_func;
char* trampoline = pool + pool_used;
size_t head = 0;
while (head < 5) {
switch (old_bytes[head]) {
case '\x55': case '\x56': case '\x57': head++;
continue;
}
switch (*(unsigned short*)(old_bytes + head)) { case 0xFF8B: case 0xEC8B: case 0xC033: head += 2;
continue;
case 0xEC83: head += 3;
continue;
case 0xC1F7: head += 6;
continue;
}
switch (0x00FFFFFF & *(unsigned int*)(old_bytes + head)) {
case 0x24448A: case 0x244C8B: case 0x24548B: case 0x247C8B: head += 4;
continue;
}
return false;
}
if (pool_used + head + 5 > POOL_SIZE)
return false;
DWORD old_prot, unused_prot;
if (!VirtualProtect((void*)old_func, head, PAGE_EXECUTE_READWRITE,
&old_prot))
return false;
_memcpy(trampoline, old_bytes, head);
WriteJumpInstruction(trampoline + head, old_bytes + head);
*orig_old_func = (uptr)trampoline;
pool_used += head + 5;
WriteJumpInstruction(old_bytes, (char*)new_func);
_memset(old_bytes + 5, 0xCC , head - 5);
if (!VirtualProtect((void*)old_func, head, old_prot, &unused_prot))
return false;
return true;
}
}
#endif // _WIN32