stevemk14ebr / PolyHook

x86/x64 C++ Hooking Library
MIT License
886 stars 172 forks source link

Trampoline memory region doesn't get allocated (x64) #19

Closed no-realm closed 7 years ago

no-realm commented 7 years ago

Hey there,

I am having some issues with PolyHook. When I try hooking a particular function, the trampoline memory region doesn't seem to get allocated. The PolyHook output shows the fixed trampoline, but when I go to the trampoline address, the region isn't allocated. The original function also doesn't get patched.

PolyHook output:

PolyHook x64Detour: Allocation within +-2GB Succeeded Delta:[0.019124 GB] Percent Tolerance Used[3.824848 % out of 2GB]

ORIGINAL:
7FF6A713D010 [5]: 48 89 5C 24 10 mov qword ptr [rsp + 0x10], rbx
7FF6A713D015 [5]: 48 89 74 24 18 mov qword ptr [rsp + 0x18], rsi
7FF6A713D01A [5]: 48 89 7C 24 20 mov qword ptr [rsp + 0x20], rdi
7FF6A713D01F [1]: 55 push rbp

Trampoline:
7FF6A5F00000: 48 89 5C 24 10 mov qword ptr [rsp + 0x10], rbx
7FF6A5F00005: 48 89 74 24 18 mov qword ptr [rsp + 0x18], rsi
7FF6A5F0000A: 48 89 7C 24 20 mov qword ptr [rsp + 0x20], rdi
7FF6A5F0000F: 55 push rbp
7FF6A5F00010: 50 push rax
7FF6A5F00011: 48 B8 20 D0 13 A7 F6 7F 00 00 movabs rax, 0x7ff6a713d020
7FF6A5F0001B: 48 87 04 24 xchg qword ptr [rsp], rax
7FF6A5F0001F: C3 ret

Fixed Trampoline
7FF6A5F00000: 48 89 5C 24 10 mov qword ptr [rsp + 0x10], rbx
7FF6A5F00005: 48 89 74 24 18 mov qword ptr [rsp + 0x18], rsi
7FF6A5F0000A: 48 89 7C 24 20 mov qword ptr [rsp + 0x20], rdi
7FF6A5F0000F: 55 push rbp
7FF6A5F00010: 50 push rax
7FF6A5F00011: 48 B8 20 D0 13 A7 F6 7F 00 00 movabs rax, 0x7ff6a713d020
7FF6A5F0001B: 48 87 04 24 xchg qword ptr [rsp], rax
7FF6A5F0001F: C3 ret
Posted Error [SEVERITY:0]:
PolyHook x64Detour: Relocation can be out of range

Additionally, when I try including "PolyHook.hpp" in more than one file, I get linking errors (something with 'already defined'). This also happens when I put the include in my Includes.h or stdafx.h file.

stevemk14ebr commented 7 years ago

This is because polyhook utilizes trampolines which copy the original bytes of the function that are overwritten by our hook into a newly allocated executable memory region. A pointer to this copy is returned, instead of the "original". It is labeled "getoriginal" because if you execute that copy the execution eventually lands back to the original, performing the operation the user wanted (from a functional point of view). But i see you already figured this out as you closed it yourself.