-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathinjectee_iat.cpp
1655 lines (1358 loc) · 53.6 KB
/
injectee_iat.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Code for the DLL that will be injected in the target process.
*
* The injected DLL will manipulate the import tables to hook the
* modules/functions of interest.
*
* See also:
* - http://www.codeproject.com/KB/system/api_spying_hack.aspx
* - http://www.codeproject.com/KB/threads/APIHooking.aspx
* - http://msdn.microsoft.com/en-us/magazine/cc301808.aspx
*/
#define NOMINMAX
//#define __STDC_WANT_LIB_EXT1__ 1
//#define _NO_CRT_STDIO_INLINE 1
#include <tchar.h>
#include <winsock2.h>
#include <assert.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <algorithm>
#include <set>
#include <map>
#include <functional>
#include <iterator>
#include <windows.h>
#include <tlhelp32.h>
//#include <delayimp.h>
#include "inject.h"
#include <atomic>
#include <mutex>
#include <d3d11.h>
#include <d3d11_1.h>
#include <d3d11_2.h>
#include <d3d11_3.h>
#include <d3d11_4.h>
#include <dxgi.h>
#include <dxgi1_2.h>
#include <dxgi1_3.h>
extern HRESULT WrappedD3D11CreateDevice(
IDXGIAdapter * pAdapter,
D3D_DRIVER_TYPE DriverType,
HMODULE Software,
UINT Flags,
const D3D_FEATURE_LEVEL * pFeatureLevels,
UINT FeatureLevels,
UINT SDKVersion,
ID3D11Device ** ppDevice,
D3D_FEATURE_LEVEL * pFeatureLevel,
ID3D11DeviceContext ** ppImmediateContext
);
extern HRESULT WrappedD3D11CreateDeviceAndSwapChain(
IDXGIAdapter * pAdapter,
D3D_DRIVER_TYPE DriverType,
HMODULE Software,
UINT Flags,
const D3D_FEATURE_LEVEL * pFeatureLevels,
UINT FeatureLevels,
UINT SDKVersion,
const DXGI_SWAP_CHAIN_DESC * pSwapChainDesc,
IDXGISwapChain ** ppSwapChain,
ID3D11Device ** ppDevice,
D3D_FEATURE_LEVEL * pFeatureLevel,
ID3D11DeviceContext ** ppImmediateContext
);
extern HRESULT WrappedCreateDXGIFactory(
const IID & riid,
void ** ppFactory
);
extern HRESULT WrappedCreateDXGIFactory1(
const IID & riid,
void ** ppFactory
);
extern HRESULT WrappedCreateDXGIFactory2(
UINT Flags,
const IID & riid,
void ** ppFactory
);
static int VERBOSITY = 0;
#define NOOP 0
static CRITICAL_SECTION g_Mutex;
static HMODULE g_hThisModule = NULL;
static HMODULE g_hHookModule = NULL;
static void
debugPrintf(const char *format, ...)
{
char buf[512];
va_list ap;
va_start(ap, format);
_vsnprintf_s(buf, sizeof buf, format, ap);
va_end(ap);
OutputDebugStringA(buf);
}
#define ARRAY_COUNT(x) (sizeof(x)/sizeof(x[0]))
#define VERBOSE_DEBUG_HOOK OPTION_OFF
using std::vector;
using std::map;
using std::string;
using std::wstring;
char toclower(char c)
{
return (char)tolower(c);
}
wstring strlower(const wstring &str)
{
wstring newstr(str);
transform(newstr.begin(), newstr.end(), newstr.begin(), towlower);
return newstr;
}
string strlower(const string &str)
{
string newstr(str);
transform(newstr.begin(), newstr.end(), newstr.begin(), toclower);
return newstr;
}
struct LibraryHook;
typedef std::function<void(void *)> FunctionLoadCallback;
struct FunctionHook
{
FunctionHook() : orig(NULL), hook(NULL) {}
FunctionHook(const char *f, void **o, void *d) : function(f), orig(o), hook(d) {}
bool operator<(const FunctionHook &h) const { return function < h.function; }
std::string function;
void **orig;
void *hook;
};
class LibraryHooks
{
public:
// generic, implemented in hooks.cpp to iterate over all registered libraries
static void RegisterHooks();
static void OptionsUpdated();
// platform specific implementations
// Removes hooks (where possible) and restores everything to an un-hooked state
static void RemoveHooks();
// refreshes hooks, useful on android where hooking can be unreliable
static void Refresh();
// Ignore this library - i.e. do not hook any calls it makes. Useful in the case where a library
// might call in to hooked APIs but we want to treat it as a black box.
static void IgnoreLibrary(const char *libraryName);
// register a library for hooking, providing an optional callback to be called the first time the
// library has been loaded and all functions in it hooked.
static void RegisterLibraryHook(const char *libraryName, FunctionLoadCallback loadedCallback);
// registers a function to be hooked, and an optional location of where to store the original
// onward function pointer
static void RegisterFunctionHook(const char *libraryName, const FunctionHook &hook);
// detect if an identifier is present in the current process - used as a marker to indicate
// replay-type programs.
static bool Detect(const char *identifier);
private:
static void BeginHookRegistration();
static void EndHookRegistration();
};
// defines the interface that a library hooking class will implement.
struct LibraryHook
{
LibraryHook();
virtual void RegisterHooks() = 0;
virtual void OptionsUpdated() {}
private:
friend class LibraryHooks;
};
#if _WIN64
#define BIT_SPECIFIC_DLL(dll32, dll64) dll64
#else
#define BIT_SPECIFIC_DLL(dll32, dll64) dll32
#endif
template <typename FuncType>
class HookedFunction
{
public:
HookedFunction() { orig_funcptr = NULL; }
~HookedFunction() {}
FuncType operator()() { return (FuncType)orig_funcptr; }
void SetFuncPtr(void *ptr) { orig_funcptr = ptr; }
void Register(const char *module_name, const char *function, void *destination_function_ptr)
{
LibraryHooks::RegisterFunctionHook(
module_name, FunctionHook(function, &orig_funcptr, destination_function_ptr));
}
private:
void *orig_funcptr;
};
class D3D11Hook : LibraryHook
{
public:
D3D11Hook() {}
void RegisterHooks()
{
// also require d3dcompiler_??.dll
/*if (GetD3DCompiler() == NULL)
{
RDCERR("Failed to load d3dcompiler_??.dll - not inserting D3D11 hooks.");
return;
}*/
LibraryHooks::RegisterLibraryHook("d3d11.dll", NULL);
CreateDevice.Register("d3d11.dll", "D3D11CreateDevice", WrappedD3D11CreateDevice);
CreateDeviceAndSwapChain.Register("d3d11.dll", "D3D11CreateDeviceAndSwapChain",
WrappedD3D11CreateDeviceAndSwapChain);
}
private:
HookedFunction<PFN_D3D11_CREATE_DEVICE_AND_SWAP_CHAIN> CreateDeviceAndSwapChain;
HookedFunction<PFN_D3D11_CREATE_DEVICE> CreateDevice;
static D3D11Hook d3d11hooks;
};
D3D11Hook D3D11Hook::d3d11hooks;
typedef HRESULT(WINAPI *PFN_CREATE_DXGI_FACTORY)(REFIID, void **);
typedef HRESULT(WINAPI *PFN_CREATE_DXGI_FACTORY2)(UINT, REFIID, void **);
typedef HRESULT(WINAPI *PFN_GET_DEBUG_INTERFACE)(REFIID, void **);
typedef HRESULT(WINAPI *PFN_GET_DEBUG_INTERFACE1)(UINT, REFIID, void **);
class DXGIHook : LibraryHook
{
public:
void RegisterHooks()
{
LibraryHooks::RegisterLibraryHook("dxgi.dll", NULL);
CreateDXGIFactory.Register("dxgi.dll", "CreateDXGIFactory", WrappedCreateDXGIFactory);
CreateDXGIFactory1.Register("dxgi.dll", "CreateDXGIFactory1", WrappedCreateDXGIFactory1);
CreateDXGIFactory2.Register("dxgi.dll", "CreateDXGIFactory2", WrappedCreateDXGIFactory2);
//GetDebugInterface.Register("dxgi.dll", "DXGIGetDebugInterface", WrappedDXGIGetDebugInterface);
//GetDebugInterface1.Register("dxgi.dll", "DXGIGetDebugInterface1", WrappedDXGIGetDebugInterface1);
}
private:
static DXGIHook dxgihooks;
HookedFunction<PFN_CREATE_DXGI_FACTORY> CreateDXGIFactory;
HookedFunction<PFN_CREATE_DXGI_FACTORY> CreateDXGIFactory1;
HookedFunction<PFN_CREATE_DXGI_FACTORY2> CreateDXGIFactory2;
//HookedFunction<PFN_GET_DEBUG_INTERFACE> GetDebugInterface;
//HookedFunction<PFN_GET_DEBUG_INTERFACE1> GetDebugInterface1;
};
DXGIHook DXGIHook::dxgihooks;
static std::vector<LibraryHook *> &LibList()
{
static std::vector<LibraryHook *> libs;
return libs;
}
LibraryHook::LibraryHook()
{
LibList().push_back(this);
}
void LibraryHooks::RegisterHooks()
{
BeginHookRegistration();
for (LibraryHook *lib : LibList())
lib->RegisterHooks();
EndHookRegistration();
}
void LibraryHooks::OptionsUpdated()
{
for (LibraryHook *lib : LibList())
lib->OptionsUpdated();
}
// map from address of IAT entry, to original contents
map<void **, void *> s_InstalledHooks;
std::mutex installedLock;
#define SCOPED_LOCK(m) std::lock_guard<std::mutex> gggggAAAAA(m)
bool ApplyHook(FunctionHook &hook, void **IATentry, bool &already)
{
DWORD oldProtection = PAGE_EXECUTE;
if (*IATentry == hook.hook)
{
already = true;
return true;
}
#if VERBOSE_DEBUG_HOOK
debugPrintf("Patching IAT for %s: %p to %p", function.c_str(), IATentry, hookptr);
#endif
{
SCOPED_LOCK(installedLock);
if (s_InstalledHooks.find(IATentry) == s_InstalledHooks.end())
s_InstalledHooks[IATentry] = *IATentry;
}
BOOL success = TRUE;
success = VirtualProtect(IATentry, sizeof(void *), PAGE_READWRITE, &oldProtection);
if (!success)
{
debugPrintf("Failed to make IAT entry writeable 0x%p", IATentry);
return false;
}
*IATentry = hook.hook;
success = VirtualProtect(IATentry, sizeof(void *), oldProtection, &oldProtection);
if (!success)
{
debugPrintf("Failed to restore IAT entry protection 0x%p", IATentry);
return false;
}
return true;
}
struct DllHookset
{
HMODULE module = NULL;
bool hooksfetched = false;
// if we have multiple copies of the dll loaded (unlikely), the other module handles will be
// stored here
vector<HMODULE> altmodules;
vector<FunctionHook> FunctionHooks;
DWORD OrdinalBase = 0;
vector<string> OrdinalNames;
std::vector<FunctionLoadCallback> Callbacks;
std::mutex ordinallock;
void FetchOrdinalNames()
{
SCOPED_LOCK(ordinallock);
// return if we already fetched the ordinals
if (!OrdinalNames.empty())
return;
byte *baseAddress = (byte *)module;
#if VERBOSE_DEBUG_HOOK
debugPrintf("FetchOrdinalNames");
#endif
PIMAGE_DOS_HEADER dosheader = (PIMAGE_DOS_HEADER)baseAddress;
if (dosheader->e_magic != 0x5a4d)
return;
char *PE00 = (char *)(baseAddress + dosheader->e_lfanew);
PIMAGE_FILE_HEADER fileHeader = (PIMAGE_FILE_HEADER)(PE00 + 4);
PIMAGE_OPTIONAL_HEADER optHeader =
(PIMAGE_OPTIONAL_HEADER)((BYTE *)fileHeader + sizeof(IMAGE_FILE_HEADER));
DWORD eatOffset = optHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
IMAGE_EXPORT_DIRECTORY *exportDesc = (IMAGE_EXPORT_DIRECTORY *)(baseAddress + eatOffset);
WORD *ordinals = (WORD *)(baseAddress + exportDesc->AddressOfNameOrdinals);
DWORD *names = (DWORD *)(baseAddress + exportDesc->AddressOfNames);
DWORD count = std::min(exportDesc->NumberOfFunctions, exportDesc->NumberOfNames);
WORD maxOrdinal = 0;
for (DWORD i = 0; i < count; i++)
maxOrdinal = std::max(maxOrdinal, ordinals[i]);
OrdinalBase = exportDesc->Base;
OrdinalNames.resize(maxOrdinal + 1);
for (DWORD i = 0; i < count; i++)
{
OrdinalNames[ordinals[i]] = (char *)(baseAddress + names[i]);
#if VERBOSE_DEBUG_HOOK
debugPrintf("ordinal found: '%s' %u", OrdinalNames[ordinals[i]].c_str(), (uint32_t)ordinals[i]);
#endif
}
}
};
struct CachedHookData
{
CachedHookData()
{
ownmodule = NULL;
missedOrdinals = false;
memset(&lowername, 0, sizeof(lowername));
}
map<string, DllHookset> DllHooks;
HMODULE ownmodule;
std::mutex lock;
char lowername[512];
std::set<std::string> ignores;
bool missedOrdinals;
std::atomic<int32_t> posthooking = 0;
void ApplyHooks(const char *modName, HMODULE module)
{
{
size_t i = 0;
while (modName[i])
{
lowername[i] = (char)tolower(modName[i]);
i++;
}
lowername[i] = 0;
}
if (strstr(lowername, "injectee_iat.dll") == lowername)
return;
#if VERBOSE_DEBUG_HOOK
debugPrintf("=== ApplyHooks(%s, %p)", modName, module);
#endif
// set module pointer if we are hooking exports from this module
for (auto it = DllHooks.begin(); it != DllHooks.end(); ++it)
{
if (!_stricmp(it->first.c_str(), modName))
{
if (it->second.module == NULL)
{
it->second.module = module;
it->second.hooksfetched = true;
// fetch all function hooks here, since we want to fill out the original function pointer
// even in case nothing imports from that function (which means it would not get filled
// out through FunctionHook::ApplyHook)
for (FunctionHook &hook : it->second.FunctionHooks)
{
if (hook.orig && *hook.orig == NULL)
*hook.orig = GetProcAddress(module, hook.function.c_str());
}
it->second.FetchOrdinalNames();
}
else if (it->second.module != module)
{
// if it's already in altmodules, bail
bool already = false;
for (size_t i = 0; i < it->second.altmodules.size(); i++)
{
if (it->second.altmodules[i] == module)
{
already = true;
break;
}
}
if (already)
break;
// check if the previous module is still valid
SetLastError(0);
char filename[MAX_PATH] = {};
GetModuleFileNameA(it->second.module, filename, MAX_PATH - 1);
DWORD err = GetLastError();
char *slash = strrchr(filename, L'\\');
string basename = slash ? strlower(string(slash + 1)) : "";
if (err == 0 && basename == it->first)
{
// previous module is still loaded, add this to the alt modules list
it->second.altmodules.push_back(module);
}
else
{
// previous module is no longer loaded or there's a new file there now, add this as the
// new location
it->second.module = module;
}
}
}
}
// for safety (and because we don't need to), ignore these modules
if (!_stricmp(modName, "kernel32.dll") || !_stricmp(modName, "powrprof.dll") ||
!_stricmp(modName, "CoreMessaging.dll") || !_stricmp(modName, "opengl32.dll") ||
!_stricmp(modName, "gdi32.dll") || !_stricmp(modName, "gdi32full.dll") ||
!_stricmp(modName, "nvoglv32.dll") || !_stricmp(modName, "nvoglv64.dll") ||
!_stricmp(modName, "nvcuda.dll") || strstr(lowername, "cudart") == lowername ||
strstr(lowername, "msvcr") == lowername || strstr(lowername, "msvcp") == lowername ||
strstr(lowername, "nv-vk") == lowername || strstr(lowername, "amdvlk") == lowername ||
strstr(lowername, "igvk") == lowername || strstr(lowername, "nvopencl") == lowername ||
strstr(lowername, "nvapi") == lowername)
return;
if (ignores.find(lowername) != ignores.end())
return;
byte *baseAddress = (byte *)module;
// the module could have been unloaded after our toolhelp snapshot, especially if we spent a
// long time
// dealing with a previous module (like adding our hooks).
wchar_t modpath[1024] = { 0 };
GetModuleFileNameW(module, modpath, 1023);
if (modpath[0] == 0)
return;
// increment the module reference count, so it doesn't disappear while we're processing it
// there's a very small race condition here between if GetModuleFileName returns, the module is
// unloaded then we load it again. The only way around that is inserting very scary locks
// between here
// and FreeLibrary that I want to avoid. Worst case, we load a dll, hook it, then unload it
// again.
HMODULE refcountModHandle = LoadLibraryW(modpath);
PIMAGE_DOS_HEADER dosheader = (PIMAGE_DOS_HEADER)baseAddress;
if (dosheader->e_magic != 0x5a4d)
{
debugPrintf("Ignoring module %s, since magic is 0x%04x not 0x%04x", modName,
(uint32_t)dosheader->e_magic, 0x5a4dU);
FreeLibrary(refcountModHandle);
return;
}
char *PE00 = (char *)(baseAddress + dosheader->e_lfanew);
PIMAGE_FILE_HEADER fileHeader = (PIMAGE_FILE_HEADER)(PE00 + 4);
PIMAGE_OPTIONAL_HEADER optHeader =
(PIMAGE_OPTIONAL_HEADER)((BYTE *)fileHeader + sizeof(IMAGE_FILE_HEADER));
DWORD iatOffset = optHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
IMAGE_IMPORT_DESCRIPTOR *importDesc = (IMAGE_IMPORT_DESCRIPTOR *)(baseAddress + iatOffset);
#if VERBOSE_DEBUG_HOOK
debugPrintf("=== import descriptors:");
#endif
while (iatOffset && importDesc->FirstThunk)
{
const char *dllName = (const char *)(baseAddress + importDesc->Name);
#if VERBOSE_DEBUG_HOOK
debugPrintf("found IAT for %s", dllName);
#endif
DllHookset *hookset = NULL;
for (auto it = DllHooks.begin(); it != DllHooks.end(); ++it)
if (!_stricmp(it->first.c_str(), dllName))
hookset = &it->second;
if (hookset && importDesc->OriginalFirstThunk > 0 && importDesc->FirstThunk > 0)
{
IMAGE_THUNK_DATA *origFirst =
(IMAGE_THUNK_DATA *)(baseAddress + importDesc->OriginalFirstThunk);
IMAGE_THUNK_DATA *first = (IMAGE_THUNK_DATA *)(baseAddress + importDesc->FirstThunk);
#if VERBOSE_DEBUG_HOOK
debugPrintf("Hooking imports for %s", dllName);
#endif
while (origFirst->u1.AddressOfData)
{
void **IATentry = (void **)&first->u1.AddressOfData;
struct hook_find
{
bool operator()(const FunctionHook &a, const char *b)
{
return _stricmp(a.function.c_str(), b) < 0;
}
};
#if _WIN64
if (IMAGE_SNAP_BY_ORDINAL64(origFirst->u1.AddressOfData))
#else
if (IMAGE_SNAP_BY_ORDINAL32(origFirst->u1.AddressOfData))
#endif
{
// low bits of origFirst->u1.AddressOfData contain an ordinal
WORD ordinal = IMAGE_ORDINAL64(origFirst->u1.AddressOfData);
#if VERBOSE_DEBUG_HOOK
debugPrintf("Found ordinal import %u", (uint32_t)ordinal);
#endif
if (!hookset->OrdinalNames.empty())
{
if (ordinal >= hookset->OrdinalBase)
{
// rebase into OrdinalNames index
DWORD nameIndex = ordinal - hookset->OrdinalBase;
// it's perfectly valid to have more functions than names, we only
// list those with names - so ignore any others
if (nameIndex < hookset->OrdinalNames.size())
{
const char *importName = (const char *)hookset->OrdinalNames[nameIndex].c_str();
#if VERBOSE_DEBUG_HOOK
debugPrintf("Located ordinal %u as %s", (uint32_t)ordinal, importName);
#endif
auto found =
std::lower_bound(hookset->FunctionHooks.begin(), hookset->FunctionHooks.end(),
importName, hook_find());
if (found != hookset->FunctionHooks.end() &&
!_stricmp(found->function.c_str(), importName) && ownmodule != module)
{
bool already = false;
bool applied;
{
SCOPED_LOCK(lock);
applied = ApplyHook(*found, IATentry, already);
}
// if we failed, or if it's already set and we're not doing a missedOrdinals
// second pass, then just bail out immediately as we've already hooked this
// module and there's no point wasting time re-hooking nothing
if (!applied || (already && !missedOrdinals))
{
#if VERBOSE_DEBUG_HOOK
debugPrintf("Stopping hooking module, %d %d %d", (int)applied, (int)already,
(int)missedOrdinals);
#endif
FreeLibrary(refcountModHandle);
return;
}
}
}
}
else
{
debugPrintf("Import ordinal is below ordinal base in %s importing module %s", modName,
dllName);
}
}
else
{
#if VERBOSE_DEBUG_HOOK
debugPrintf("missed ordinals, will try again");
#endif
// the very first time we try to apply hooks, we might apply them to a module
// before we've looked up the ordinal names for the one it's linking against.
// Subsequent times we're only loading one new module - and since it can't
// link to itself we will have all ordinal names loaded.
//
// Setting this flag causes us to do a second pass right at the start
missedOrdinals = true;
}
// continue
origFirst++;
first++;
continue;
}
IMAGE_IMPORT_BY_NAME *import =
(IMAGE_IMPORT_BY_NAME *)(baseAddress + origFirst->u1.AddressOfData);
const char *importName = (const char *)import->Name;
#if VERBOSE_DEBUG_HOOK
debugPrintf("Found normal import %s", importName);
#endif
auto found = std::lower_bound(hookset->FunctionHooks.begin(),
hookset->FunctionHooks.end(), importName, hook_find());
if (found != hookset->FunctionHooks.end() &&
!_stricmp(found->function.c_str(), importName) && ownmodule != module)
{
bool already = false;
bool applied;
{
SCOPED_LOCK(lock);
applied = ApplyHook(*found, IATentry, already);
}
// if we failed, or if it's already set and we're not doing a missedOrdinals
// second pass, then just bail out immediately as we've already hooked this
// module and there's no point wasting time re-hooking nothing
if (!applied || (already && !missedOrdinals))
{
#if VERBOSE_DEBUG_HOOK
debugPrintf("Stopping hooking module, %d %d %d", (int)applied, (int)already,
(int)missedOrdinals);
#endif
FreeLibrary(refcountModHandle);
return;
}
}
origFirst++;
first++;
}
}
else
{
if (hookset)
{
#if VERBOSE_DEBUG_HOOK
debugPrintf("!! Invalid IAT found for %s! %u %u", dllName, importDesc->OriginalFirstThunk,
importDesc->FirstThunk);
#endif
}
}
importDesc++;
}
FreeLibrary(refcountModHandle);
}
};
static CachedHookData *s_HookData = NULL;
#ifdef UNICODE
#undef MODULEENTRY32
#undef Module32First
#undef Module32Next
#endif
static void ForAllModules(std::function<void(const MODULEENTRY32 &me32)> callback)
{
HANDLE hModuleSnap = INVALID_HANDLE_VALUE;
// up to 10 retries
for (int i = 0; i < 10; i++)
{
hModuleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId());
if (hModuleSnap == INVALID_HANDLE_VALUE)
{
DWORD err = GetLastError();
debugPrintf("CreateToolhelp32Snapshot() -> 0x%08x", err);
// retry if error is ERROR_BAD_LENGTH
if (err == ERROR_BAD_LENGTH)
continue;
}
// didn't retry, or succeeded
break;
}
if (hModuleSnap == INVALID_HANDLE_VALUE)
{
debugPrintf("Couldn't create toolhelp dump of modules in process");
return;
}
MODULEENTRY32 me32;
memset(&me32, 0, sizeof(me32));
me32.dwSize = sizeof(MODULEENTRY32);
BOOL success = Module32First(hModuleSnap, &me32);
if (success == FALSE)
{
DWORD err = GetLastError();
debugPrintf("Couldn't get first module in process: 0x%08x", err);
CloseHandle(hModuleSnap);
return;
}
uintptr_t ret = 0;
do
{
callback(me32);
} while (ret == 0 && Module32Next(hModuleSnap, &me32));
CloseHandle(hModuleSnap);
}
static void HookAllModules()
{
ForAllModules(
[](const MODULEENTRY32 &me32) { s_HookData->ApplyHooks(me32.szModule, me32.hModule); });
// check if we're already in this section of code, and if so don't go in again.
int32_t prev = (int32_t)InterlockedCompareExchange((volatile LONG *)&s_HookData->posthooking, 0, 1);
if (prev != 0)
return;
// for all loaded modules, call callbacks now
for (auto it = s_HookData->DllHooks.begin(); it != s_HookData->DllHooks.end(); ++it)
{
if (it->second.module == NULL)
continue;
if (!it->second.hooksfetched)
{
it->second.hooksfetched = true;
// fetch all function hooks here, if we didn't above (perhaps because this library was
// late-loaded)
for (FunctionHook &hook : it->second.FunctionHooks)
{
if (hook.orig && *hook.orig == NULL)
*hook.orig = GetProcAddress(it->second.module, hook.function.c_str());
}
}
std::vector<FunctionLoadCallback> callbacks;
// don't call callbacks next time
callbacks.swap(it->second.Callbacks);
for (FunctionLoadCallback cb : callbacks)
if (cb)
cb(it->second.module);
}
(int32_t)InterlockedCompareExchange((volatile LONG *)&s_HookData->posthooking, 1, 0);
}
static bool IsAPISet(const wchar_t *filename)
{
if (wcschr(filename, L'/') != 0 || wcschr(filename, L'\\') != 0)
return false;
wchar_t match[] = L"api-ms-win";
if (wcslen(filename) < ARRAY_COUNT(match) - 1)
return false;
for (size_t i = 0; i < ARRAY_COUNT(match) - 1; i++)
if (towlower(filename[i]) != match[i])
return false;
return true;
}
static bool IsAPISet(const char *filename)
{
std::wstring wfn;
// assume ASCII not UTF, just upcast plainly to wchar_t
while (*filename)
wfn.push_back(wchar_t(*filename++));
return IsAPISet(wfn.c_str());
}
HMODULE WINAPI Hooked_LoadLibraryExA(LPCSTR lpLibFileName, HANDLE fileHandle, DWORD flags)
{
bool dohook = true;
if (flags == 0 && GetModuleHandleA(lpLibFileName))
dohook = false;
SetLastError(S_OK);
// we can use the function naked, as when setting up the hook for LoadLibraryExA, our own module
// was excluded from IAT patching
HMODULE mod = LoadLibraryExA(lpLibFileName, fileHandle, flags);
#if VERBOSE_DEBUG_HOOK
debugPrintf("LoadLibraryA(%s)", lpLibFileName);
#endif
DWORD err = GetLastError();
if (dohook && mod && !IsAPISet(lpLibFileName))
HookAllModules();
SetLastError(err);
return mod;
}
HMODULE WINAPI Hooked_LoadLibraryExW(LPCWSTR lpLibFileName, HANDLE fileHandle, DWORD flags)
{
bool dohook = true;
if (flags == 0 && GetModuleHandleW(lpLibFileName))
dohook = false;
SetLastError(S_OK);
#if VERBOSE_DEBUG_HOOK
debugPrintf("LoadLibraryW(%ls)", lpLibFileName);
#endif
// we can use the function naked, as when setting up the hook for LoadLibraryExA, our own module
// was excluded from IAT patching
HMODULE mod = LoadLibraryExW(lpLibFileName, fileHandle, flags);
DWORD err = GetLastError();
if (dohook && mod && !IsAPISet(lpLibFileName))
HookAllModules();
SetLastError(err);
return mod;
}
HMODULE WINAPI Hooked_LoadLibraryA(LPCSTR lpLibFileName)
{
return Hooked_LoadLibraryExA(lpLibFileName, NULL, 0);
}
HMODULE WINAPI Hooked_LoadLibraryW(LPCWSTR lpLibFileName)
{
return Hooked_LoadLibraryExW(lpLibFileName, NULL, 0);
}
static bool OrdinalAsString(void *func)
{
return uint64_t(func) <= 0xffff;
}
FARPROC WINAPI Hooked_GetProcAddress(HMODULE mod, LPCSTR func)
{
if (mod == NULL || func == NULL)
return (FARPROC)NULL;
if (mod == s_HookData->ownmodule)
return GetProcAddress(mod, func);
#if VERBOSE_DEBUG_HOOK
if (OrdinalAsString((void *)func))
debugPrintf("Hooked_GetProcAddress(%p, %p)", mod, func);
else
debugPrintf("Hooked_GetProcAddress(%p, %s)", mod, func);
#endif
for (auto it = s_HookData->DllHooks.begin(); it != s_HookData->DllHooks.end(); ++it)
{
if (it->second.module == NULL)
{
it->second.module = GetModuleHandleA(it->first.c_str());
if (it->second.module)
{
// fetch all function hooks here, since we want to fill out the original function pointer
// even in case nothing imports from that function (which means it would not get filled
// out through FunctionHook::ApplyHook)
for (FunctionHook &hook : it->second.FunctionHooks)
{
if (hook.orig && *hook.orig == NULL)
*hook.orig = GetProcAddress(it->second.module, hook.function.c_str());
}
it->second.FetchOrdinalNames();
}
}
bool match = (mod == it->second.module);