BlackBone
Windows memory hacking library
 All Classes Functions
Thunk.hpp
1 #include "../Config.h"
2 #include <stdint.h>
3 #include <winnt.h>
4 
5 // Thunk code
6 #pragma pack(push, 1)
7 struct ThunkData
8 {
9 #ifndef USE64
10  /*
11  mov eax, pInstance
12  mov fs:[0x14], eax
13  mov eax, pMethod
14  jmp eax
15  */
16  uint8_t mov1 = 0xB8;
17  void* pInst = nullptr;
18  uint16_t fs1 = '\x64\xA3';
19  uint8_t fs2 = FIELD_OFFSET( NT_TIB, ArbitraryUserPointer );
20  uint8_t fs3 = 0;
21  uint16_t fs4 = 0;
22  uint8_t mov2 = 0xB8;
23  void* pFn = nullptr;
24  uint16_t jmp1 = '\xFF\xE0';
25 #else
26  /*
27  mov rax, pInstance
28  mov gs:[0x28], rax
29  mov rax, pMethod
30  jmp rax
31  */
32  uint16_t mov1 = '\x48\xB8';
33  void* pInst = nullptr;
34  uint32_t fs1 = '\x65\x48\x89\x04';
35  uint8_t fs2 = 0x25;
36  uint8_t fs3 = FIELD_OFFSET( NT_TIB, ArbitraryUserPointer );
37  uint8_t fs4 = 0;
38  uint16_t fs5 = 0;
39  uint16_t mov2 = '\x48\xB8';
40  void* pFn = nullptr;
41  uint16_t jmp1 = '\xFF\xE0';
42 #endif
43 
44  void setup( void* pInstance, void* pMethod )
45  {
46  pInst = pInstance;
47  pFn = pMethod;
48  }
49 };
50 #pragma pack(pop)
51 
52 
53 template<typename fn, typename C>
54 class Win32Thunk;
55 
56 template<typename R, typename... Args, typename C>
57 class Win32Thunk < R( __stdcall* )(Args...), C >
58 {
59 public:
60  typedef R( C::*TypeMember )(Args...);
61  typedef R( __stdcall* TypeFree )(Args...);
62 
63 public:
64  Win32Thunk( TypeMember pfn, C* pInstance )
65  : _pMethod( pfn )
66  , _pInstance( pInstance )
67  {
68  DWORD dwOld = 0;
69  VirtualProtect( &_thunk, sizeof( _thunk ), PAGE_EXECUTE_READWRITE, &dwOld );
70  _thunk.setup( this, &Win32Thunk::WrapHandler );
71  }
72 
78  static R __stdcall WrapHandler( Args... args )
79  {
80  auto _this = reinterpret_cast<Win32Thunk*>(((PNT_TIB)NtCurrentTeb())->ArbitraryUserPointer);
81  return (_this->_pInstance->*_this->_pMethod)(args...);
82  }
83 
88  TypeFree GetThunk()
89  {
90  return reinterpret_cast<TypeFree>(&_thunk);
91  }
92 
93 private:
94  TypeMember _pMethod = nullptr; // Member function to call
95  C* _pInstance = nullptr; // Bound instance
96  ThunkData _thunk; // Thunk code
97 };
Definition: Thunk.hpp:7
Definition: Thunk.hpp:54
static R __stdcall WrapHandler(Args...args)
Redirect call
Definition: Thunk.hpp:78
TypeFree GetThunk()
Get thunk
Definition: Thunk.hpp:88