-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmemcury.h
1208 lines (984 loc) · 38.4 KB
/
memcury.h
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
#pragma once
/*
Memcury is a single-header file library for memory manipulation in C++.
Containers:
-PE::Address: A pointer container.
-PE::Section: Portable executable section container for internal usage.
Modules:
-Scanner:
-Constructors:
-Default: Takes a pointer to start the scanning from.
-FindPattern: Finds a pattern in memory.
-FindStringRef: Finds a string reference in memory, supports all types of strings.
-Functions:
-SetTargetModule: Sets the target module for the scanner.
-ScanFor: Scans for a byte(s) near the current address.
-FindFunctionBoundary: Finds the boundary of a function near the current address.
-RelativeOffset: Gets the relative offset of the current address.
-AbsoluteOffset: Gets the absolute offset of the current address.
-GetAs: Gets the current address as a type.
-Get: Gets the current address as an int64.
-TrampolineHook:
-Constructors:
-Default: Takes a pointer pointer to the target function and a pointer to the hook function.
-Functions:
-Commit: Commits the hook.
-Revert: Reverts the hook.
-Toggle: Toggles the hook on\off.
-VEHHook:
-Functions:
-Init: Initializes the VEH Hook system.
-AddHook: Adds a hook to the VEH Hook system.
-RemoveHook: Removes a hook from the VEH Hook system.
*/
#include <string>
#include <format>
#include <vector>
#include <stdexcept>
#include <type_traits>
#include <intrin.h>
#include <Windows.h>
#include <source_location>
#include <DbgHelp.h>
#pragma comment(lib, "Dbghelp.lib")
#define MemcuryAssert(cond) \
if (!(cond)) \
{ \
MessageBoxA(nullptr, #cond, __FUNCTION__, MB_ICONERROR | MB_OK); \
Memcury::Safety::FreezeCurrentThread(); \
}
#define MemcuryAssertM(cond, msg) \
if (!(cond)) \
{ \
MessageBoxA(nullptr, msg, __FUNCTION__, MB_ICONERROR | MB_OK); \
Memcury::Safety::FreezeCurrentThread(); \
}
#define MemcuryThrow(msg) \
MessageBoxA(nullptr, msg, __FUNCTION__, MB_ICONERROR | MB_OK); \
Memcury::Safety::FreezeCurrentThread();
namespace Memcury
{
extern "C" IMAGE_DOS_HEADER __ImageBase;
inline auto GetCurrentModule() -> HMODULE
{
return reinterpret_cast<HMODULE>(&__ImageBase);
}
namespace Util
{
template <typename T>
constexpr static auto IsInRange(T value, T min, T max) -> bool
{
return value >= min && value < max;
}
constexpr auto StrHash(const char* str, int h = 0) -> unsigned int
{
return !str[h] ? 5381 : (StrHash(str, h + 1) * 33) ^ str[h];
}
inline auto IsSamePage(void* A, void* B) -> bool
{
MEMORY_BASIC_INFORMATION InfoA;
if (!VirtualQuery(A, &InfoA, sizeof(InfoA)))
{
return true;
}
MEMORY_BASIC_INFORMATION InfoB;
if (!VirtualQuery(B, &InfoB, sizeof(InfoB)))
{
return true;
}
return InfoA.BaseAddress == InfoB.BaseAddress;
}
inline auto GetModuleStartAndEnd() -> std::pair<uintptr_t, uintptr_t>
{
auto HModule = GetCurrentModule();
auto NTHeaders = reinterpret_cast<PIMAGE_NT_HEADERS>((uintptr_t)HModule + reinterpret_cast<PIMAGE_DOS_HEADER>((uintptr_t)HModule)->e_lfanew);
uintptr_t dllStart = (uintptr_t)HModule;
uintptr_t dllEnd = (uintptr_t)HModule + NTHeaders->OptionalHeader.SizeOfImage;
return { dllStart, dllEnd };
}
inline auto CopyToClipboard(std::string str)
{
auto mem = GlobalAlloc(GMEM_FIXED, str.size() + 1);
memcpy(mem, str.c_str(), str.size() + 1);
OpenClipboard(nullptr);
EmptyClipboard();
SetClipboardData(CF_TEXT, mem);
CloseClipboard();
GlobalFree(mem);
}
}
namespace Safety
{
enum class ExceptionMode
{
None,
CatchDllExceptionsOnly,
CatchAllExceptions
};
static auto FreezeCurrentThread() -> void
{
SuspendThread(GetCurrentThread());
}
static auto PrintStack(CONTEXT* ctx) -> void
{
STACKFRAME64 stack;
memset(&stack, 0, sizeof(STACKFRAME64));
auto process = GetCurrentProcess();
auto thread = GetCurrentThread();
SymInitialize(process, NULL, TRUE);
bool result;
DWORD64 displacement = 0;
char buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)] { 0 };
char name[256] { 0 };
char module[256] { 0 };
PSYMBOL_INFO symbolInfo = (PSYMBOL_INFO)buffer;
for (ULONG frame = 0;; frame++)
{
result = StackWalk64(
IMAGE_FILE_MACHINE_AMD64,
process,
thread,
&stack,
ctx,
NULL,
SymFunctionTableAccess64,
SymGetModuleBase64,
NULL);
if (!result)
break;
symbolInfo->SizeOfStruct = sizeof(SYMBOL_INFO);
symbolInfo->MaxNameLen = MAX_SYM_NAME;
SymFromAddr(process, (ULONG64)stack.AddrPC.Offset, &displacement, symbolInfo);
HMODULE hModule = NULL;
lstrcpyA(module, "");
GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (const wchar_t*)(stack.AddrPC.Offset), &hModule);
if (hModule != NULL)
GetModuleFileNameA(hModule, module, 256);
printf("[%lu] Name: %s - Address: %p - Module: %s\n", frame, symbolInfo->Name, (void*)symbolInfo->Address, module);
}
}
template <ExceptionMode mode>
auto MemcuryGlobalHandler(EXCEPTION_POINTERS* ExceptionInfo) -> long
{
auto [dllStart, dllEnd] = Util::GetModuleStartAndEnd();
if constexpr (mode == ExceptionMode::CatchDllExceptionsOnly)
{
if (!Util::IsInRange(ExceptionInfo->ContextRecord->Rip, dllStart, dllEnd))
{
return EXCEPTION_CONTINUE_SEARCH;
}
}
auto message = std::format("Memcury caught an exception at [{:x}]\nPress Yes if you want the address to be copied to your clipboard", ExceptionInfo->ContextRecord->Rip);
if (MessageBoxA(nullptr, message.c_str(), "Error", MB_ICONERROR | MB_YESNO) == IDYES)
{
std::string clip = std::format("{:x}", ExceptionInfo->ContextRecord->Rip);
Util::CopyToClipboard(clip);
}
PrintStack(ExceptionInfo->ContextRecord);
FreezeCurrentThread();
return EXCEPTION_EXECUTE_HANDLER;
}
template <ExceptionMode mode>
static auto SetExceptionMode() -> void
{
SetUnhandledExceptionFilter(MemcuryGlobalHandler<mode>);
}
}
namespace Globals
{
constexpr const bool bLogging = true;
inline const char* moduleName = nullptr;
}
namespace ASM
{
//@todo: this whole namespace needs a rework, should somehow make this more modern and less ugly.
enum MNEMONIC : uint8_t
{
JMP_REL8 = 0xEB,
JMP_REL32 = 0xE9,
JMP_EAX = 0xE0,
CALL = 0xE8,
LEA = 0x8D,
CDQ = 0x99,
CMOVL = 0x4C,
CMOVS = 0x48,
CMOVNS = 0x49,
NOP = 0x90,
INT3 = 0xCC,
RETN_REL8 = 0xC2,
RETN = 0xC3,
NONE = 0x00
};
constexpr int SIZE_OF_JMP_RELATIVE_INSTRUCTION = 5;
constexpr int SIZE_OF_JMP_ABSLOUTE_INSTRUCTION = 13;
constexpr auto MnemonicToString(MNEMONIC e) -> const char*
{
switch (e)
{
case JMP_REL8:
return "JMP_REL8";
case JMP_REL32:
return "JMP_REL32";
case JMP_EAX:
return "JMP_EAX";
case CALL:
return "CALL";
case LEA:
return "LEA";
case CDQ:
return "CDQ";
case CMOVL:
return "CMOVL";
case CMOVS:
return "CMOVS";
case CMOVNS:
return "CMOVNS";
case NOP:
return "NOP";
case INT3:
return "INT3";
case RETN_REL8:
return "RETN_REL8";
case RETN:
return "RETN";
case NONE:
return "NONE";
default:
return "UNKNOWN";
}
}
constexpr auto Mnemonic(const char* s) -> MNEMONIC
{
switch (Util::StrHash(s))
{
case Util::StrHash("JMP_REL8"):
return JMP_REL8;
case Util::StrHash("JMP_REL32"):
return JMP_REL32;
case Util::StrHash("JMP_EAX"):
return JMP_EAX;
case Util::StrHash("CALL"):
return CALL;
case Util::StrHash("LEA"):
return LEA;
case Util::StrHash("CDQ"):
return CDQ;
case Util::StrHash("CMOVL"):
return CMOVL;
case Util::StrHash("CMOVS"):
return CMOVS;
case Util::StrHash("CMOVNS"):
return CMOVNS;
case Util::StrHash("NOP"):
return NOP;
case Util::StrHash("INT3"):
return INT3;
case Util::StrHash("RETN_REL8"):
return RETN_REL8;
case Util::StrHash("RETN"):
return RETN;
default:
return NONE;
}
}
inline auto byteIsA(uint8_t byte, MNEMONIC opcode) -> bool
{
return byte == opcode;
}
inline auto byteIsAscii(uint8_t byte) -> bool
{
static constexpr bool isAscii[0x100] = {
false, false, false, false, false, false, false, false, false, true, true, false, false, true, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false
};
return isAscii[byte];
}
inline bool isJump(uint8_t byte)
{
return byte >= 0x70 && byte <= 0x7F;
}
static auto pattern2bytes(const char* pattern) -> std::vector<int>
{
auto bytes = std::vector<int> {};
const auto start = const_cast<char*>(pattern);
const auto end = const_cast<char*>(pattern) + strlen(pattern);
for (auto current = start; current < end; ++current)
{
if (*current == '?')
{
++current;
if (*current == '?')
++current;
bytes.push_back(-1);
}
else
{
bytes.push_back(strtoul(current, ¤t, 16));
}
}
return bytes;
}
}
namespace PE
{
inline auto SetCurrentModule(const char* moduleName) -> void
{
Globals::moduleName = moduleName;
}
inline auto GetModuleBase() -> uintptr_t
{
return reinterpret_cast<uintptr_t>(GetModuleHandleA(Globals::moduleName));
}
inline auto GetDOSHeader() -> PIMAGE_DOS_HEADER
{
return reinterpret_cast<PIMAGE_DOS_HEADER>(GetModuleBase());
}
inline auto GetNTHeaders() -> PIMAGE_NT_HEADERS
{
return reinterpret_cast<PIMAGE_NT_HEADERS>(GetModuleBase() + GetDOSHeader()->e_lfanew);
}
class Address
{
uintptr_t _address;
public:
Address()
{
_address = 0;
}
Address(uintptr_t address)
: _address(address)
{
}
Address(void* address)
: _address(reinterpret_cast<uintptr_t>(address))
{
}
auto operator=(uintptr_t address) -> Address
{
_address = address;
return *this;
}
auto operator=(void* address) -> Address
{
_address = reinterpret_cast<uintptr_t>(address);
return *this;
}
auto operator+(uintptr_t offset) -> Address
{
return Address(_address + offset);
}
bool operator>(uintptr_t offset)
{
return _address > offset;
}
bool operator>(Address address)
{
return _address > address._address;
}
bool operator<(uintptr_t offset)
{
return _address < offset;
}
bool operator<(Address address)
{
return _address < address._address;
}
bool operator>=(uintptr_t offset)
{
return _address >= offset;
}
bool operator>=(Address address)
{
return _address >= address._address;
}
bool operator<=(uintptr_t offset)
{
return _address <= offset;
}
bool operator<=(Address address)
{
return _address <= address._address;
}
bool operator==(uintptr_t offset)
{
return _address == offset;
}
bool operator==(Address address)
{
return _address == address._address;
}
bool operator!=(uintptr_t offset)
{
return _address != offset;
}
bool operator!=(Address address)
{
return _address != address._address;
}
auto RelativeOffset(uint32_t offset) -> Address
{
_address = ((_address + offset + 4) + *(int32_t*)(_address + offset));
return *this;
}
auto AbsoluteOffset(uint32_t offset) -> Address
{
_address = _address + offset;
return *this;
}
auto Jump() -> Address
{
if (ASM::isJump(*reinterpret_cast<UINT8*>(_address)))
{
UINT8 toSkip = *reinterpret_cast<UINT8*>(_address + 1);
_address = _address + 2 + toSkip;
}
return *this;
}
auto Get() -> uintptr_t
{
return _address;
}
template <typename T>
auto GetAs() -> T
{
return reinterpret_cast<T>(_address);
}
auto IsValid() -> bool
{
return _address != 0;
}
};
class Section
{
public:
std::string sectionName;
IMAGE_SECTION_HEADER rawSection;
static auto GetAllSections() -> std::vector<Section>
{
std::vector<Section> sections;
auto sectionsSize = GetNTHeaders()->FileHeader.NumberOfSections;
auto section = IMAGE_FIRST_SECTION(GetNTHeaders());
for (WORD i = 0; i < sectionsSize; i++, section++)
{
auto secName = std::string((char*)section->Name);
sections.push_back({ secName, *section });
}
return sections;
}
static auto GetSection(std::string sectionName) -> Section
{
for (auto& section : GetAllSections())
{
if (section.sectionName == sectionName)
{
return section;
}
}
MemcuryThrow("Section not found");
return Section {};
}
auto GetSectionSize() -> uint32_t
{
return rawSection.Misc.VirtualSize;
}
auto GetSectionStart() -> Address
{
return Address(GetModuleBase() + rawSection.VirtualAddress);
}
auto GetSectionEnd() -> Address
{
return Address(GetSectionStart() + GetSectionSize());
}
auto isInSection(Address address) -> bool
{
return address >= GetSectionStart() && address < GetSectionEnd();
}
};
}
class Scanner
{
PE::Address _address;
public:
Scanner(PE::Address address)
: _address(address)
{
}
static auto SetTargetModule(const char* moduleName) -> void
{
PE::SetCurrentModule(moduleName);
}
static auto FindPatternEx(HANDLE handle, const char* pattern, const char* mask, uint64_t begin, uint64_t end) -> Scanner
{
auto scan = [](const char* pattern, const char* mask, char* begin, unsigned int size) -> char*
{
size_t patternLen = strlen(mask);
for (unsigned int i = 0; i < size - patternLen; i++)
{
bool found = true;
for (unsigned int j = 0; j < patternLen; j++)
{
if (mask[j] != '?' && pattern[j] != *(begin + i + j))
{
found = false;
break;
}
}
if (found)
return (begin + i);
}
return nullptr;
};
uint64_t match = NULL;
SIZE_T bytesRead;
char* buffer = nullptr;
MEMORY_BASIC_INFORMATION mbi = { 0 };
uint64_t curr = begin;
for (uint64_t curr = begin; curr < end; curr += mbi.RegionSize)
{
if (!VirtualQueryEx(handle, (void*)curr, &mbi, sizeof(mbi)))
continue;
if (mbi.State != MEM_COMMIT || mbi.Protect == PAGE_NOACCESS)
continue;
buffer = new char[mbi.RegionSize];
if (ReadProcessMemory(handle, mbi.BaseAddress, buffer, mbi.RegionSize, &bytesRead))
{
char* internalAddr = scan(pattern, mask, buffer, (unsigned int)bytesRead);
if (internalAddr != nullptr)
{
match = curr + (uint64_t)(internalAddr - buffer);
break;
}
}
}
delete[] buffer;
MemcuryAssertM(match != 0, "FindPatternEx return nullptr");
return Scanner(match);
}
static auto FindPatternEx(HANDLE handle, const char* sig) -> Scanner
{
char pattern[100];
char mask[100];
char lastChar = ' ';
unsigned int j = 0;
for (unsigned int i = 0; i < strlen(sig); i++)
{
if ((sig[i] == '?' || sig[i] == '*') && (lastChar != '?' && lastChar != '*'))
{
pattern[j] = mask[j] = '?';
j++;
}
else if (isspace(lastChar))
{
pattern[j] = lastChar = (char)strtol(&sig[i], 0, 16);
mask[j] = 'x';
j++;
}
lastChar = sig[i];
}
pattern[j] = mask[j] = '\0';
auto module = (uint64_t)GetModuleHandle(nullptr);
return FindPatternEx(handle, pattern, mask, module, module + Memcury::PE::GetNTHeaders()->OptionalHeader.SizeOfImage);
}
static auto FindPattern(const char* signature) -> Scanner
{
PE::Address add { nullptr };
const auto sizeOfImage = PE::GetNTHeaders()->OptionalHeader.SizeOfImage;
auto patternBytes = ASM::pattern2bytes(signature);
const auto scanBytes = reinterpret_cast<std::uint8_t*>(PE::GetModuleBase());
const auto s = patternBytes.size();
const auto d = patternBytes.data();
for (auto i = 0ul; i < sizeOfImage - s; ++i)
{
bool found = true;
for (auto j = 0ul; j < s; ++j)
{
if (scanBytes[i + j] != d[j] && d[j] != -1)
{
found = false;
break;
}
}
if (found)
{
add = reinterpret_cast<uintptr_t>(&scanBytes[i]);
break;
}
}
MemcuryAssertM(add != 0, "FindPattern return nullptr");
return Scanner(add);
}
// Supports wide and normal strings both std and pointers
template <typename T = const wchar_t*>
static auto FindStringRef(T string, bool find_first = false) -> Scanner
{
PE::Address add { nullptr };
constexpr auto bIsWide = std::is_same<T, const wchar_t*>::value;
constexpr auto bIsChar = std::is_same<T, const char*>::value;
constexpr auto bIsPtr = bIsWide || bIsChar;
auto textSection = PE::Section::GetSection(".text");
auto rdataSection = PE::Section::GetSection(".rdata");
const auto scanBytes = reinterpret_cast<std::uint8_t*>(textSection.GetSectionStart().Get());
// scan only text section
for (DWORD i = 0x0; i < textSection.GetSectionSize(); i++)
{
if ((scanBytes[i] == ASM::CMOVL || scanBytes[i] == ASM::CMOVS) && scanBytes[i + 1] == ASM::LEA)
{
auto stringAdd = PE::Address(&scanBytes[i]).RelativeOffset(3);
// Check if the string is in the .rdata section
if (rdataSection.isInSection(stringAdd))
{
auto strBytes = stringAdd.GetAs<std::uint8_t*>();
// Check if the first char is printable
if (ASM::byteIsAscii(strBytes[0]))
{
if constexpr (!bIsPtr)
{
typedef T::value_type char_type;
auto lea = stringAdd.GetAs<char_type*>();
T leaT(lea);
if (leaT == string)
{
add = PE::Address(&scanBytes[i]);
if(find_first)
break;
}
}
else
{
auto lea = stringAdd.GetAs<T>();
if constexpr (bIsWide)
{
if (wcscmp(string, lea) == 0)
{
add = PE::Address(&scanBytes[i]);
if(find_first)
break;
}
}
else
{
if (strcmp(string, lea) == 0)
{
add = PE::Address(&scanBytes[i]);
if(find_first)
break;
}
}
}
}
}
}
}
MemcuryAssertM(add != 0, "FindStringRef return nullptr");
return Scanner(add);
}
auto Jump() -> Scanner
{
_address.Jump();
return *this;
}
auto ScanFor(std::vector<uint8_t> opcodesToFind, bool forward = true, int toSkip = 0) -> Scanner
{
const auto scanBytes = _address.GetAs<std::uint8_t*>();
for (auto i = (forward ? 1 : -1); forward ? (i < 2048) : (i > -2048); forward ? i++ : i--)
{
bool found = true;
for (int k = 0; k < opcodesToFind.size() && found; k++)
{
if (opcodesToFind[k] == -1)
continue;
found = opcodesToFind[k] == scanBytes[i + k];
}
if (found)
{
_address = &scanBytes[i];
if (toSkip != 0)
{
return ScanFor(opcodesToFind, forward, toSkip - 1);
}
break;
}
}
return *this;
}
auto FindFunctionBoundary(bool forward = false) -> Scanner
{
const auto scanBytes = _address.GetAs<std::uint8_t*>();
for (auto i = (forward ? 1 : -1); forward ? (i < 2048) : (i > -2048); forward ? i++ : i--)
{
if ( // ASM::byteIsA(scanBytes[i], ASM::MNEMONIC::JMP_REL8) ||
// ASM::byteIsA(scanBytes[i], ASM::MNEMONIC::JMP_REL32) ||
// ASM::byteIsA(scanBytes[i], ASM::MNEMONIC::JMP_EAX) ||
ASM::byteIsA(scanBytes[i], ASM::MNEMONIC::RETN_REL8) || ASM::byteIsA(scanBytes[i], ASM::MNEMONIC::RETN) || ASM::byteIsA(scanBytes[i], ASM::MNEMONIC::INT3))
{
_address = (uintptr_t)&scanBytes[i + 1];
break;
}
}
return *this;
}
auto RelativeOffset(uint32_t offset) -> Scanner
{
_address.RelativeOffset(offset);
return *this;
}
auto AbsoluteOffset(uint32_t offset) -> Scanner
{
_address.AbsoluteOffset(offset);
return *this;
}
template <typename T>
auto GetAs() -> T
{
return _address.GetAs<T>();
}
auto Get() -> uintptr_t
{
return _address.Get();
}
auto IsValid() -> bool
{
return _address.IsValid();
}
};
/* Bad don't use it tbh... */
class TrampolineHook
{
void** originalFunctionPtr;
PE::Address originalFunction;
PE::Address hookFunction;
PE::Address allocatedPage;
std::vector<uint8_t> restore;
void PointToCodeIfNot(PE::Address& ptr)
{
auto bytes = ptr.GetAs<std::uint8_t*>();
if (ASM::byteIsA(bytes[0], ASM::MNEMONIC::JMP_REL32))
{
ptr = bytes + 5 + *(int32_t*)&bytes[1];
}
}
void* AllocatePageNearAddress(void* targetAddr)
{
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
const uint64_t PAGE_SIZE = sysInfo.dwPageSize;
uint64_t startAddr = (uint64_t(targetAddr) & ~(PAGE_SIZE - 1)); // round down to nearest page boundary
uint64_t minAddr = min(startAddr - 0x7FFFFF00, (uint64_t)sysInfo.lpMinimumApplicationAddress);
uint64_t maxAddr = max(startAddr + 0x7FFFFF00, (uint64_t)sysInfo.lpMaximumApplicationAddress);
uint64_t startPage = (startAddr - (startAddr % PAGE_SIZE));
for (uint64_t pageOffset = 1; pageOffset; pageOffset++)
{
uint64_t byteOffset = pageOffset * PAGE_SIZE;
uint64_t highAddr = startPage + byteOffset;
uint64_t lowAddr = (startPage > byteOffset) ? startPage - byteOffset : 0;
bool needsExit = highAddr > maxAddr && lowAddr < minAddr;
if (highAddr < maxAddr)
{
void* outAddr = VirtualAlloc((void*)highAddr, PAGE_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (outAddr)
return outAddr;
}
if (lowAddr > minAddr)
{
void* outAddr = VirtualAlloc((void*)lowAddr, PAGE_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (outAddr != nullptr)
return outAddr;
}
if (needsExit)
{
break;
}
}
return nullptr;
}
void WriteAbsoluteJump(void* jumpLocation, void* destination)
{
uint8_t absJumpInstructions[] = {
ASM::Mnemonic("CMOVNS"), 0xBA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov r10, addr
0x41, 0xFF, 0xE2 // jmp r10
};
auto destination64 = (uint64_t)destination;
memcpy(&absJumpInstructions[2], &destination64, sizeof(destination64));
memcpy(jumpLocation, absJumpInstructions, sizeof(absJumpInstructions));
}
uintptr_t PrepareRestore()
{
/*
This is not a correct way to do it at all, since not all functions sub from the stack
This needs so much more tests, but it works for now.
*/
Scanner scanner(originalFunction);
scanner.ScanFor({ 0x48, 0x83, 0xEC }); // sub rsp
auto restoreSize = scanner.Get() - originalFunction.Get();
MemcuryAssert(restoreSize > 0 && restoreSize < 0x100);