写得很不错的文章,国人用英语写的,还有代码。8 l! V( R9 P5 y7 H& `1 z( P: _
Hooking Direct3d) S7 t9 _ n% }
By Jijun Wang
& F$ V' x) ?0 B! |6 S0 I6 y7 CIntroduction
6 r: f- j' s& K6 BIn the field of hooking technologies, hooking COM based applications is a big challenging because you can’t know their member functions’ real addresses previously. There are many papers on the Internet that talk about how to hook (somebody call it hijack) an application. However, seldom of them mention how to hook COM. Since I have seen some people asked questions about this topic and nobody answered their questions clearly, I decide to write this paper to share my experience with the guys who are interested in hooking COM. % \3 q3 D2 g/ {2 o# R1 \
3 S$ O. U# `9 t( ^& fIn this paper, I use direct3d, which is widely used in current games, as an example of COM. At first I will briefly introduce the hooking technologies and explain why I select Detours to hook direct3d. Then more details and examples of Detours will be presented and I will discus virtual functions and find the way to hook direct3d.
4 n4 N* J5 T7 R. n% E5 T9 B2 l, }* EHooking Technologies
5 m+ |0 p2 v7 r" z! fThe basic idea of hooking is injecting your code into a piece of code. When the target code executes your code will be invoked. To do this, you need to at first attach your code into the target process. And then inject your code into the target process’ code. The ways to attach your code into another thread or process include / [; ?% |3 x% p" b% n( R% ]
1) Register your DLL to the registry table. 1 b# B3 J; W" ?
This method registers your DLL to the key: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Windows\AppInit_DLLs and the dll will be loaded when user32.dll initializes itself. It is a safe method. But it only works for the applications that use user32.dll. And it’s not convenient to activate/deactivate your DLL. * O# @; R0 _- i: R
2) System-wide Windows Hooks
C4 S5 e/ ~' l% [1 U% ]% dThis method use SetWindowsHookEx(),CallNextHookEx() and UnhookWindowsHookEx() winapis to monitor the system’s message traffic and attach your code into the processes that fit the hook filter. Since it is system-wide message monitor, the system’s performance will be significantly affected. " e2 M+ m% C0 G! G
3) Create Remote Thread) o" t9 `7 C6 R- f7 ?( e
This method use CreateRemoteThread()to inject your DLL into another thread (the to-be-hooked thread). It’s a very effective method. But there is one thing we need to consider. You must make sure you have enough privileges to access the to-be-hooked thread. 5 H( e4 b* y$ ?! }0 a" `/ A
$ `: t: ^/ W0 L9 ]9 U: nTo inject your code into another process’ code, we could use:$ S$ C0 a; a: e1 q; h, Z
1) Proxy DLL. \. Y, q0 ~* R: m7 K" Z' S* Y( a
This method writes a new DLL to replace the to-be-hooked DLL. The new DLL must have the same name, exported functions and variables as the old one. For example, the GLtrace is a replacement of the opengl32.dll. It is used to trace OpenGL. Although you could use function forward to reduce the time spent in rewriting functions, it’s a tedious work in some cases. . r: F" [; v7 M+ c& [ Y& [
2) Altering of the IAT (Import Address Table)& N7 m( k& ]) S6 n2 ?5 p& K
This is a wildly used hooking method. Windows use IAT to find the functions’ addresses. Through changing the data of IAT, you could use your own function to replace the to-be-hooked function. The method is robust and easy to implement. However, it only works for statically linked API calls. And sometimes you may miss API calls since you must patch every module in the target application.1 S$ l |2 ?. E' p/ Z5 |. @+ E- U
3) Code Overwriting
, z' y& z. I( W% TThe basic idea is to overwrite the API’s binary code in memory. We could save and replace the first several codes of a function call to a JUMP code to jump to your codes and then go back to the original position and restore the saved codes. It’s very hard to implement. However, once you have mastered it, it’s really a good hooking method.
- \' r' S$ @+ n' r. _/ t6 \: D* K3 e: j
For more details about hooking technologies you can read the wonderful paper “API hooking revealed” written by Ivo Ivanov and madshi’s discussion about hooking methods. There are some libraries or tools that wrap the hooking methods. "Detours" is a library developed by a Microsoft’s research term. It uses code overwriting technology. “madCodeHook” is a library built by madshi. It’s also based on code overwriting. “hookapi” is another tool can help you develop your hooking applications. Since Detours is free for research purpose and it’s stable and effective, I will use it to hook direct3d.! j" ^; J+ ]) g
Detours! v0 g; [+ _0 b, M7 }6 {
“Detours” is originally built for change a standalone system to distributed system. It can inject your code into another win32 function. Some utilities that attach your codes to another process are also provided in this library. The typical case you may need Detours is that you need to modify an application’s behavior without knowing its source code. For more details please visit Detours’ web site: http://www.research.microsoft.com/sn/detours/
" i$ B5 X( H, |
6 D5 m# ?0 n3 j: _* JAs an example of how to use Detours, we will try to catch the function “SetTimer()”. Then change the elapse time to a big number. So for the applications use SetTimer(), you can steal time by hooking this function. The first step is to create TRAMPOLINE. It changes SetTimer()’s binary code and lets it jump to the Real_SetTimer() function.: E( x0 b: w, d7 |- B1 |: v7 V0 j
: h. o8 s& ]5 D- bDETOUR_TRAMPOLINE(4 ^/ r- k- b. |4 Y7 p4 l0 Y
UINT WINAPI Real_SetTimer(HWND hWnd, // handle of window for timer messages. S* Z5 x' S U( |0 V
UINT nIDEvent, // timer identifier
1 Z V9 j. Y) U UINT uElapse, // time-out value
$ O" r, c3 z# M1 T' q6 o9 u% C( B TIMERPROC lpTimerFunc), // address of timer procedure4 t+ X6 ]8 y1 A( }3 E& i$ \# i
SetTimer);1 D9 `. v& h; Z/ P9 z7 o8 n
( o I, ^ G* t1 a! x: I/ N% u, wThen we write our own SetTimer function.2 T8 ~) V+ s# g, J+ K
UINT WINAPI Mine_SetTimer(" {0 ^1 }( Q; P _+ T7 h
HWND hWnd, // handle of window for timer messages
% L* z) Q/ i! @- @' w UINT nIDEvent, // timer identifier
. }# f$ B4 n J UINT uElapse, // time-out value: A' `. E3 ]3 s+ i A! s" G0 |% h
TIMERPROC lpTimerFunc // address of timer procedure' M; y/ L( z0 N& b& j+ M% s
); t O6 ?; h, M1 S9 S3 y$ O
{
3 @5 M. l/ f0 n" \. r* m7 Y* U1 ^ uElapse=10* uElapse;
+ k- {% }2 }, D; _: j3 K" I# I return Real_SetTimer(hWnd,nIDEvent,uElapse,lpTimerFunc);
, L' t' A; a4 G5 H# W# L2 v}/ J/ e, |" U1 ~8 U( x; o6 G
, a/ Z& u1 M$ D: U) T9 |3 PThen write the functions to intercept the Real_SetTimer() function to your own Mine_SetTimer() function and the function that removes the interception.8 J# e0 z- O# T& L" X+ U( a
7 Y0 w" y, i5 B( B5 I. D
BOOL TrampolineWith(VOID)
' R. q0 h1 Z3 [& `5 {6 B{- N- Z/ I; i8 |1 c6 ~- f; K
DetourFunctionWithTrampoline((PBYTE)Real_SetTimer,
6 l4 D! w( m# f/ ?1 e6 T (PBYTE)Mine_SetTimer);+ A7 k& J& L4 F# W: q( j
return TURE;
" K7 I/ w2 Q* a- h" L1 p}/ g+ ?* b2 K" x# _! P) S J
4 G) |8 z }: I5 }; w
BOOL TrampolineRemove(VOID)8 y4 {& R7 e- \, u- p$ m, A9 t
{
# J& z: b( b6 [* H- R5 _1 X DetourRemove((PBYTE)Real_SetTimer,& [3 g, K: b: x/ @
(PBYTE)Mine_SetTimer);
0 [8 m4 R: k0 t/ ~4 ]0 a' i return TRUE;
+ @7 @9 I3 r. e8 Q4 Y2 m& |7 B}6 u* k4 B% }; S6 x6 u. h! O9 a3 `
" W4 Z4 [* Z2 v
At last, we write the DLLmain function./ H5 \. T2 q2 J' I$ i# a& Y, b2 l
( z* ~! N; S8 |# D: \; }& l5 u
BOOL APIENTRY DllMain(HINSTANCE hModule, DWORD dwReason, PVOID lpReserved)! h. s! H2 o3 B5 z5 s# G
{
# C0 Z) o+ t% v2 w6 a switch (dwReason) {5 s8 [) ^: t' q I9 S
case DLL_PROCESS_ATTACH:
, G0 C+ U, ^8 W9 b8 E' E return TrampolineWith();
0 }. g2 j/ h3 g9 r5 I) j% e case DLL_PROCESS_DETACH:
- d' d/ W7 o2 _' P$ p3 n2 M return TrampolineRemove();
/ t2 C0 D" R/ Y" q3 i4 p/ Q) w case DLL_THREAD_ATTACH:; t9 o* `! L, A- b3 l# ^2 I
return TrampolineWith();% {4 S) Y5 b* K6 A7 H
case DLL_THREAD_DETACH:
5 o1 C* L: a& r return TrampolineRemove();
' t+ e7 X' z0 O. p7 r5 ?( k }4 [5 d; x+ i* \3 \
return TRUE;3 u+ H3 v( [( R- w1 }
}- E8 T. g/ D: K
: l3 |) L- a/ C! A6 m6 v4 ~
By including the “detours.h” file and linking the “detours.lib”, you can build this DLL (let’s say it is myTest.dll). Then you can write your own application to attach the DLL into another application, or use the “withdll.exe”, which is included in Detours 1.5’s samples, to attach it. If you place the DLL file, withdll.exe and winmine.exe in the same directory, then play the Mine game use command “withdll.exe –d:myTest.dll winmine.exe”, you will get a very high score.1 r8 ~2 ]6 }! p1 t8 ^1 E) J
% V) N$ d/ |1 L( V: t3 Q
This is the simplest case of using Detours. If you want to hook a member function of a class, you need to write your own class and your member function. You can find an example of hooking member function in Detours 1.5’s samples. & n7 j( c0 T9 E. w6 Y
* ^# M) G3 L# K# ?# j5 A& X& RTo hook direct3d, you may create a class, write your own member functions, for example CreateDevice(), Present(), and then detour direct3d’s member function to your own functions. Unfortunately this doesn’t work. The reason is that Directx is COM based, it uses virtual functions. When you detour the member functions, you will use the virtual function’s address not the real implement function’s address. So the key of hooking direct3d is finding out the real function address. To do this we need to know how virtual function works.) f, S4 F' ^) a# J
Understanding Virtual Functions and Hooking Direct3d
0 n ]7 J: y- ~Virtual function is used for reusable and polymorphic purposes. It is runtime bound to the real implement function. For more details about how virtual functions work, please read Shivesh V.’s paper “Virtual Functions and their implementation in C”. 5 q6 ?% h {, T( x) `* u) t: ]& M! E9 ?
8 c& }7 m! _& X! Y1 V
Basically, after you call the Direct3DCreate8() function (let’s assume we use directx8), you will get a pointer to the created IDirect3D8 object. In the pointer is the address of the vtable, a structure that contains all the member functions’ addresses. The address in the vtable is the real implement function’s address. So if we want to build a benchmark application to test the frame update rate, we could do it in the following steps:
% s \7 z* R0 G/ T3 s% |- f1) Catch Direct3DCreate8() to get the IDirect3D8 object6 N& p( u% i6 o. b& Q; Q1 V% [+ U1 _
2) Use the pointer of IDirect3D8 object, catch the CreateDevice() function to get the IDirect3DDevice8 object.3 Q9 F+ G% ~$ c' X/ @! S3 ~( Q/ z
3) Use the pointer of IDirect3DDevice8 object, catch Present() function.7 w" F8 I7 K; T
4) In the Present() function calculates the frame rate.
1 B T+ U; w/ b9 P6 T* o. |) E8 r' F s9 z
However, to catch the member function, there is a very important parameter we need to know. It’s the address data in the vtable that contain the to-be-hooked function’s address. There is no general way to know the offset in the vtable. For direct3d, you could use the d3d8.h file to figure out the offset. Or you can debug a direct3d application and get the offset by read the disassembly code. The following is a piece code of the directx 8.1 SDK’s Text3D sample code. The comments of the disassembly code are added by the author.
# o/ f0 ?% }# q
9 y5 D n) j, T* |873: // Create the device
' E+ |$ F6 n/ [- d0 _5 l874: hr = m_pD3D->CreateDevice( m_dwAdapter, pDeviceInfo->DeviceType,
2 n( A' F2 X8 i& Z( q$ L875: m_hWndFocus, pModeInfo->dwBehavior, &m_d3dpp,
4 m/ n! {$ p; {9 k+ @876: &m_pd3dDevice );% m& H4 B) f; q! T# H+ V2 t8 f
00403114 mov eax,dword ptr [this]
$ |3 i1 w) E5 _00403117 add eax,2A4A8h
( F! T9 y4 ?9 ]; {9 H' Z1 `0040311C push eax // push the sixth parameter &m_pd3dDevice1 X( f3 @$ K8 Q: c, g
0040311D mov ecx,dword ptr [this]; r$ g& N$ k* n1 t7 M
00403120 add ecx,2A464h: {( e0 Q. N) C9 T3 b9 ^9 f
00403126 push ecx //push the fifth parameter &m_d3dp
# a% u5 H5 z2 r, d4 o00403127 mov edx,dword ptr [pModeInfo]
9 x& g5 R" {. X9 u1 [6 p% Z; P0040312A mov eax,dword ptr [edx+0Ch]' t' S. M2 c1 r* h( _
0040312D push eax //push the fourth parameter pModeInfo->dwBehavior4 W( L7 x& B% i- A. x8 ~
0040312E mov ecx,dword ptr [this]
, y7 s( m" {# G) y9 R2 e00403131 mov edx,dword ptr [ecx+2A49Ch]
2 h' v7 c' n9 \+ S# v2 I00403137 push edx //push the third parameter m_hWndFocus
2 J3 J0 c$ F$ K. L00403138 mov eax,dword ptr [pDeviceInfo]) [/ o' q( v$ Y: m- ~
0040313B mov ecx,dword ptr [eax]+ S/ B) I0 I9 y( Q/ k! s+ ~( M/ U6 u
0040313D push ecx //push the second parameter pDeviceInfo->DeviceType% n4 O2 K$ y3 c
0040313E mov edx,dword ptr [this]4 U1 B+ S% @0 X* u, G
00403141 mov eax,dword ptr [edx+2A448h]( c5 q, }3 l' p+ v3 Q$ ?
00403147 push eax //push the first parameter m_dwAdapter
2 P5 f7 @, u( v00403148 mov ecx,dword ptr [this]4 \0 k8 I" Z) ^7 V6 l' Z
0040314B mov edx,dword ptr [ecx+2A4A4h] //calculate the return address2 v8 F* _9 T- W6 |8 ^
00403151 mov eax,dword ptr [this]
& F+ I! m' m1 t1 }0 V% w; z00403154 mov ecx,dword ptr [eax+2A4A4h]$ j- k0 C2 U" U3 O2 L
0040315A mov eax,dword ptr [ecx] //calculate the vtable address. It’s the value
& M. }/ l3 E% C8 S# S3 b( U7 s. P( d //stored in ecx register. $ }# |" E+ ]& R( [% s) i0 o
0040315C push edx //push the return address5 L b& q+ G+ G8 Z
0040315D call dword ptr [eax+3Ch] //call the CreateDevice() function 0 l" e X# L! o$ u3 M$ |. f
00403160 mov dword ptr ,eax
- ^, a- Y4 |3 F, B( ?2 i: H5 E; T! t
From the assembler code, it’s obvious that the offset is 0x3ch. You can do the same thing for the Present() function. And the offset happen is also 0x3ch.
! v. e7 `5 N. l$ r( L
$ K9 |+ x& h6 X7 u0 z# A0 c" nThe sample code can be found at http://usl.sis.pitt.edu/wjj/UTClient/direct3d8.zip. To compile it you need Directx 8.1 SDK. Please note that the method of display frame count is not every effective. If you remove the displaying code, you will find Detours has almost no effect to the frame rate.) j- n9 r6 J U" P* Y
Reference:) t/ }9 k' H9 ~
[1] “API hooking revealed”, Ivo Ivanov1 }8 S' `. [. q' L( I
[2] “madCodeHook”, madshi
; c5 K* _$ B$ `1 G& F M[3] "Detours", Galen Hunt and Doug Brubacher# c4 p+ F) ~ U. p# y
[4] “Virtual Functions and their implementation in C”, Shivesh V.
$ U$ l6 x' F+ a, a[5] “Pointers to C++ Member Functions”, Michael D. Crawford |