This commit is contained in:
2019-11-10 16:02:05 +01:00
parent 37db06f918
commit b279cfc84a
5 changed files with 64 additions and 27 deletions

39
hook.c
View File

@@ -1,21 +1,22 @@
/*
\todo:
What if there's a loop in the function which loops back to an overwritten instruction?
start:
jmp hook_function
bla
jXX start+3
*/
// todo: on weird jump: stop the disassembling there or treat as normal instruction?
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>
#include <Windows.h>
#include <stddef.h>
#ifdef WINDOWS
#include <windows.h>
#else
#include <sys/mman.h>
#include <string.h>
#endif
#include "udis86.h"
#include "list.h"
#include "hook.h"
#include "misc.h"
#define MINIMUM_REQUIRED_FUNCTION_LENGTH_SHORT_HOOK 5
#define MINIMUM_REQUIRED_FUNCTION_LENGTH_LONG_HOOK 16
@@ -93,6 +94,9 @@ int hook(void* function, size_t functionLength, void* replacement, void** trampo
return (int)*trampoline;
printf("Needed for trampoline %p: %d (Found %d)\n", *trampoline, trampolineSizeNeeded, functionLength);
#ifdef WINDOWS
FlushInstructionCache(GetCurrentProcess(), function, needed);
#endif
return SUCCESS;
}
@@ -111,7 +115,7 @@ static void* build_trampoline(void* function, size_t functionSize, size_t* tramp
*trampolineSize = 0;
if(!(trampoline = VirtualAlloc(NULL, PAGE_BOUNDARY, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE)))
if(!(trampoline = alloc_rwx(PAGE_BOUNDARY)))
return (void*)CANT_ALLOC;
printf("trampoline @ %p\n", trampoline);
@@ -136,7 +140,7 @@ static void* build_trampoline(void* function, size_t functionSize, size_t* tramp
// Check for XXX [rip + ?]
const struct ud_operand* op = NULL;
for(int i = 0; op = ud_insn_opr(&ud, i); i++)
for(int i = 0; ; i++, op = ud_insn_opr(&ud, i))
{
if((op->type & UD_OP_REG) == UD_OP_REG)
{
@@ -226,7 +230,7 @@ static int32_t get_rip_delta(ud_t* ud)
const struct ud_operand* op = NULL;
int32_t ret = 0;
for(int i = 0; op = ud_insn_opr(ud, i); i++)
for(int i = 0; ; i++, op = ud_insn_opr(ud, i))
{
// Only the RIP offset is interesting
if((op->type & UD_OP_REG) != UD_OP_REG || op->base != UD_R_RIP)
@@ -271,7 +275,7 @@ static size_t write_jcc_jump(const uint8_t* instruction, void* whereToWrite, voi
static size_t get_jump_offset(ud_t* ud, size_t offsetOfInstr)
{
const struct ud_operand* op = NULL;
for(int i = 0; op = ud_insn_opr(ud, i); i++)
for(int i = 0; ; i++, op = ud_insn_opr(ud, i))
{
if(op->type == UD_OP_JIMM)
{
@@ -360,8 +364,3 @@ static size_t write_x64_jump(unsigned char* where, void* toWhere)
return sizeof(jmpMemTemplate)+sizeof(toWhere);
}
//! fixme:
static bool loops_into_overwritten_code(void* function)
{
return false;
}