-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGGXrdFasterLoadingTimes.cpp
More file actions
1396 lines (1195 loc) · 52.5 KB
/
GGXrdFasterLoadingTimes.cpp
File metadata and controls
1396 lines (1195 loc) · 52.5 KB
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
#include "pch.h"
// The purpose of this program is to patch GuiltyGearXrd.exe to speed up the
// loading of assets on pre-battle loading screens
#include <iostream>
#include <string>
#ifndef FOR_LINUX
#include "resource.h"
#include "ConsoleEmulator.h"
#include "InjectorCommonOut.h"
#include <commdlg.h>
#else
#include <fstream>
#include <string.h>
#include <sys/stat.h>
#include <stdint.h>
#endif
#include <vector>
#include "Version.h"
#include "YesNoCancel.h"
#ifndef FOR_LINUX
InjectorCommonOut outputObject;
#define CrossPlatformString std::wstring
#define CrossPlatformChar wchar_t
#define CrossPlatformPerror _wperror
#define CrossPlatformText(txt) L##txt
#define CrossPlatformCout outputObject
#define CrossPlatformNumberToString std::to_wstring
extern void GetLine(std::wstring& line);
extern void AskYesNoCancel(const char* prompt, YesNoCancel* result);
#else
void GetLine(std::string& line) { std::getline(std::cin, line); }
void AskYesNoCancel(const char* prompt, YesNoCancel* result) {
std::string line;
while (true) {
std::cout << "Type 'y' to say 'Yes', 'n' to say 'No' and 'c' to 'Cancel', and hit Enter.\n";
std::getline(std::cin, line);
if (strcmp(line.c_str(), "y") == 0 || strcmp(line.c_str(), "Y") == 0) {
*result = YesNoCancel_Yes;
return;
} else if (strcmp(line.c_str(), "n") == 0 || strcmp(line.c_str(), "N") == 0) {
*result = YesNoCancel_No;
return;
} else if (strcmp(line.c_str(), "c") == 0 || strcmp(line.c_str(), "C") == 0) {
*result = YesNoCancel_Cancel;
return;
}
}
}
#define CrossPlatformString std::string
#define CrossPlatformChar char
#define CrossPlatformPerror perror
#define CrossPlatformText(txt) txt
#define CrossPlatformCout std::cout
#define CrossPlatformNumberToString std::to_string
typedef unsigned int DWORD;
// from winnt.h
//
// Based relocation types.
//
#define IMAGE_REL_BASED_ABSOLUTE 0
#define IMAGE_REL_BASED_HIGH 1
#define IMAGE_REL_BASED_LOW 2
#define IMAGE_REL_BASED_HIGHLOW 3
#define IMAGE_REL_BASED_HIGHADJ 4
#define IMAGE_REL_BASED_DIR64 10
#define sprintf_s sprintf
#endif
#ifndef FOR_LINUX
#define PATH_SEPARATOR L'\\'
#else
#define PATH_SEPARATOR '/'
#endif
#ifdef FOR_LINUX
void trim(std::string& str) {
if (str.empty()) return;
auto it = str.end();
--it;
while (true) {
if (*it > 32) break;
if (it == str.begin()) {
str.clear();
return;
}
--it;
}
str.resize(it - str.begin() + 1);
}
#endif
char exeName[] = "\x3d\x6b\x5f\x62\x6a\x6f\x3d\x5b\x57\x68\x4e\x68\x5a\x24\x5b\x6e\x5b\xf6";
int findLast(const CrossPlatformString& str, CrossPlatformChar character) {
if (str.empty() || str.size() > 0xFFFFFFFF) return -1;
auto it = str.cend();
--it;
while (true) {
if (*it == character) return (it - str.cbegin()) & 0xFFFFFFFF;
if (it == str.cbegin()) return -1;
--it;
}
return -1;
}
// Does not include trailing slash
CrossPlatformString getParentDir(const CrossPlatformString& path) {
CrossPlatformString result;
int lastSlashPos = findLast(path, PATH_SEPARATOR);
if (lastSlashPos == -1) return result;
result.insert(result.begin(), path.cbegin(), path.cbegin() + lastSlashPos);
return result;
}
CrossPlatformString getFileName(const CrossPlatformString& path) {
CrossPlatformString result;
int lastSlashPos = findLast(path, PATH_SEPARATOR);
if (lastSlashPos == -1) return path;
result.insert(result.begin(), path.cbegin() + lastSlashPos + 1, path.cend());
return result;
}
bool fileExists(const CrossPlatformString& path) {
#ifndef FOR_LINUX
DWORD fileAtrib = GetFileAttributesW(path.c_str());
if (fileAtrib == INVALID_FILE_ATTRIBUTES) {
return false;
}
return true;
#else
struct stat buf;
int result = stat(path.c_str(), &buf);
if (result == 0) return true;
if (result == ENOENT) return false;
std::cout << "Could not access \"" << path << "\":\n";
perror(nullptr);
return false;
#endif
}
int sigscan(const char* start, const char* end, const char* sig, const char* mask) {
const char* startPtr = start;
const size_t maskLen = strlen(mask);
if ((size_t)(end - start) < maskLen) return -1;
const size_t seekLength = end - start - maskLen + 1;
for (size_t seekCounter = seekLength; seekCounter != 0; --seekCounter) {
const char* stringPtr = startPtr;
const char* sigPtr = sig;
for (const char* maskPtr = mask; true; ++maskPtr) {
const char maskPtrChar = *maskPtr;
if (maskPtrChar != '?') {
if (maskPtrChar == '\0') return (startPtr - start) & 0xFFFFFFFF;
if (*sigPtr != *stringPtr) break;
}
++sigPtr;
++stringPtr;
}
++startPtr;
}
return -1;
}
int sigscanUp(const char* start, const char* startBoundary, int limit, const char* sig, const char* mask) {
const char* const startBoundaryOrig = startBoundary;
if (limit <= 0 || start < startBoundary) return -1;
if ((uintptr_t)start < (uintptr_t)limit - 1) limit = (int)((uintptr_t)start & 0xFFFFFFFF) + 1;
if (start - (limit - 1) > startBoundary) {
startBoundary = start - (limit - 1);
}
const char* startPtr = start;
while (startPtr >= startBoundary) {
const char* stringPtr = startPtr;
const char* sigPtr = sig;
for (const char* maskPtr = mask; true; ++maskPtr) {
const char maskPtrChar = *maskPtr;
if (maskPtrChar != '?') {
if (maskPtrChar == '\0') return (startPtr - startBoundaryOrig) & 0xFFFFFFFF;
if (*sigPtr != *stringPtr) break;
}
++sigPtr;
++stringPtr;
}
--startPtr;
}
return -1;
}
int sigscanForward(const char* start, const char* end, int limit, const char* sig, const char* mask) {
if (end - start < limit) limit = (end - start) & 0xFFFFFFFF;
if (limit <= 0) return -1;
if (end - start > limit) end = start + limit;
return sigscan(start, end, sig, mask);
}
enum SigscanRecursiveResult {
SigscanRecursiveResult_Continue,
SigscanRecursiveResult_Stop
};
int sigscanRecursive(const char* start, const char* end, const char* sig, const char* mask, SigscanRecursiveResult(*callback)(int pos, void* userData), void* userData) {
const char* const startOrig = start;
while (true) {
int pos = sigscan(start, end, sig, mask);
if (pos == -1) return -1;
int posCorrected = pos + (start - startOrig) & 0xFFFFFFFF;
SigscanRecursiveResult result = callback(posCorrected, userData);
if (result == SigscanRecursiveResult_Stop) return posCorrected;
start += pos + 1;
if (start >= end) return -1;
}
}
template<int N>
int sigscanEveryNBytes(const char* start, const char* end, const char* sig) {
if (end - start < N) return -1;
const char* startPtr = start;
const int seekLength = ((end - start) & 0xFFFFFFFF) - N + 1;
for (int seekCounter = seekLength; seekCounter > 0; seekCounter -= N) {
const char* stringPtr = startPtr;
const char* sigPtr = sig;
int n;
for (n = N; n > 0; --n) {
if (*sigPtr != *stringPtr) break;
++sigPtr;
++stringPtr;
}
if (n == 0) return (startPtr - start) & 0xFFFFFFFF;
startPtr += N;
}
return -1;
}
bool readWholeFile(FILE* file, std::vector<char>& wholeFile) {
fseek(file, 0, SEEK_END);
size_t fileSize = ftell(file);
fseek(file, 0, SEEK_SET);
wholeFile.resize(fileSize);
char* wholeFilePtr = &wholeFile.front();
size_t readBytesTotal = 0;
while (true) {
size_t sizeToRead = 1024;
if (fileSize - readBytesTotal < 1024) sizeToRead = fileSize - readBytesTotal;
if (sizeToRead == 0) break;
size_t readBytes = fread(wholeFilePtr, 1, sizeToRead, file);
if (readBytes != sizeToRead) {
if (ferror(file)) {
CrossPlatformPerror(CrossPlatformText("Error reading file"));
return false;
}
// assume feof
break;
}
wholeFilePtr += 1024;
readBytesTotal += 1024;
}
return true;
}
std::string repeatCharNTimes(char charToRepeat, int times) {
std::string result;
result.resize(times, charToRepeat);
return result;
}
int calculateRelativeCall(DWORD callInstructionAddress, DWORD calledAddress) {
return (int)calledAddress - (int)(callInstructionAddress + 5);
}
DWORD followRelativeCall(DWORD callInstructionAddress, const char* callInstructionAddressInRam) {
int offset = *(int*)(callInstructionAddressInRam + 1);
return callInstructionAddress + 5 + offset;
}
struct Section {
std::string name;
// RVA. Virtual address offset relative to the virtual address start of the entire .exe.
// So let's say the whole .exe starts at 0x400000 and RVA is 0x400.
// That means the non-relative VA is 0x400000 + RVA = 0x400400.
// Note that the .exe, although it does specify a base virtual address for itself on the disk,
// may actually be loaded anywhere in the RAM once it's launched, and that RAM location will
// become its base virtual address.
DWORD relativeVirtualAddress = 0;
// VA. Virtual address within the .exe.
// A virtual address is the location of something within the .exe once it's loaded into memory.
// An on-disk, file .exe is usually smaller than when it's loaded so it creates this distinction
// between raw address and virtual address.
DWORD virtualAddress = 0;
// The size in terms of virtual address space.
DWORD virtualSize = 0;
// Actual position of the start of this section's data within the file.
DWORD rawAddress = 0;
// Size of this section's data on disk in the file.
DWORD rawSize = 0;
};
std::vector<Section> readSections(FILE* file, DWORD* imageBase) {
size_t readBytes;
std::vector<Section> result;
DWORD peHeaderStart = 0;
fseek(file, 0x3C, SEEK_SET);
readBytes = fread(&peHeaderStart, 4, 1, file);
unsigned short numberOfSections = 0;
fseek(file, peHeaderStart + 0x6, SEEK_SET);
readBytes = fread(&numberOfSections, 2, 1, file);
DWORD optionalHeaderStart = peHeaderStart + 0x18;
unsigned short optionalHeaderSize = 0;
fseek(file, peHeaderStart + 0x14, SEEK_SET);
readBytes = fread(&optionalHeaderSize, 2, 1, file);
fseek(file, peHeaderStart + 0x34, SEEK_SET);
readBytes = fread(imageBase, 4, 1, file);
DWORD sectionsStart = optionalHeaderStart + optionalHeaderSize;
DWORD sectionStart = sectionsStart;
for (size_t sectionCounter = numberOfSections; sectionCounter != 0; --sectionCounter) {
Section newSection;
fseek(file, sectionStart, SEEK_SET);
newSection.name.resize(8);
readBytes = fread(&newSection.name.front(), 1, 8, file);
newSection.name.resize(strlen(newSection.name.c_str()));
readBytes = fread(&newSection.virtualSize, 4, 1, file);
readBytes = fread(&newSection.relativeVirtualAddress, 4, 1, file);
newSection.virtualAddress = *imageBase + newSection.relativeVirtualAddress;
readBytes = fread(&newSection.rawSize, 4, 1, file);
readBytes = fread(&newSection.rawAddress, 4, 1, file);
result.push_back(newSection);
sectionStart += 40;
}
return result;
}
DWORD rawToVa(const std::vector<Section>& sections, DWORD rawAddr) {
if (sections.empty()) return 0;
auto it = sections.cend();
--it;
while (true) {
const Section& section = *it;
if (rawAddr >= section.rawAddress) {
return rawAddr - section.rawAddress + section.virtualAddress;
}
if (it == sections.cbegin()) break;
--it;
}
return 0;
}
DWORD vaToRaw(const std::vector<Section>& sections, DWORD va) {
if (sections.empty()) return 0;
auto it = sections.cend();
--it;
while (true) {
const Section& section = *it;
if (va >= section.virtualAddress) {
return va - section.virtualAddress + section.rawAddress;
}
if (it == sections.cbegin()) break;
--it;
}
return 0;
}
DWORD vaToRva(DWORD va, DWORD imageBase) {
return va - imageBase;
}
DWORD rvaToVa(DWORD rva, DWORD imageBase) {
return rva + imageBase;
}
DWORD rvaToRaw(const std::vector<Section>& sections, DWORD rva) {
if (sections.empty()) return 0;
auto it = sections.cend();
--it;
while (true) {
const Section& section = *it;
if (rva >= section.relativeVirtualAddress) {
return rva - section.relativeVirtualAddress + section.rawAddress;
}
if (it == sections.cbegin()) break;
--it;
}
return 0;
}
/// <summary>
/// Writes a relocation entry at the current file position.
/// </summary>
/// <param name="relocType">See macros starting with IMAGE_REL_BASED_</param>
/// <param name="va">Virtual address of the place to be relocated by the reloc.</param>
void writeRelocEntry(FILE* file, char relocType, DWORD va) {
DWORD vaMemoryPage = va & 0xFFFFF000;
unsigned short relocEntry = ((DWORD)relocType << 12) | ((va - vaMemoryPage) & 0x0FFF);
fwrite(&relocEntry, 2, 1, file);
}
/// <summary>
/// Specify nameCounter 0 to not use it
/// </summary>
CrossPlatformString generateBackupPath(const CrossPlatformString& parentDir, const CrossPlatformString& fileName, int nameCounter) {
CrossPlatformString result;
int pos = findLast(fileName, CrossPlatformText('.'));
result = parentDir + PATH_SEPARATOR;
if (pos == -1) {
result += fileName + CrossPlatformText("_backup");
if (nameCounter) {
result += CrossPlatformNumberToString(nameCounter);
}
} else {
result.append(fileName.begin(), fileName.begin() + pos);
result += CrossPlatformText("_backup");
if (nameCounter) {
result += CrossPlatformNumberToString(nameCounter);
}
result += fileName.c_str() + pos;
}
return result;
}
bool crossPlatformOpenFile(FILE** file, const CrossPlatformString& path) {
#ifndef FOR_LINUX
errno_t errorCode = _wfopen_s(file, path.c_str(), CrossPlatformText("r+b"));
if (errorCode != 0 || !*file) {
if (errorCode != 0) {
wchar_t buf[1024];
_wcserror_s(buf, errorCode);
CrossPlatformCout << L"Failed to open file: " << buf << L'\n';
} else {
CrossPlatformCout << L"Failed to open file.\n";
}
if (*file) {
fclose(*file);
}
return false;
}
return true;
#else
*file = fopen(path.c_str(), "r+b");
if (!*file) {
perror("Failed to open file");
return false;
}
return true;
#endif
}
#ifdef FOR_LINUX
void copyFileLinux(const std::string& pathSource, const std::string& pathDestination) {
std::ifstream src(pathSource, std::ios::binary);
std::ofstream dst(pathDestination, std::ios::binary);
dst << src.rdbuf();
}
#endif
struct FoundReloc {
char type; // see macros starting with IMAGE_REL_BASED_
DWORD regionVa; // position of the place that the reloc is patching
DWORD relocVa; // position of the reloc entry itself
};
struct FoundRelocBlock {
const char* ptr; // points to the page base member of the block
DWORD pageBaseVa; // page base of all patches that the reloc is responsible for
DWORD relocVa; // position of the reloc block itself. Points to the page base member of the block
DWORD size; // size of the entire block, including the page base and block size and all entries
};
struct RelocBlockIterator {
const char* const relocTableOrig;
const DWORD relocTableVa;
const DWORD imageBase;
DWORD relocTableSize; // remaining size
const char* relocTableNext;
RelocBlockIterator(const char* relocTable, DWORD relocTableVa, DWORD relocTableSize, DWORD imageBase)
:
relocTableOrig(relocTable),
relocTableVa(relocTableVa),
imageBase(imageBase),
relocTableSize(relocTableSize),
relocTableNext(relocTable) { }
bool getNext(FoundRelocBlock& block) {
if (relocTableSize == 0) return false;
const char* relocTable = relocTableNext;
DWORD pageBaseRva = *(DWORD*)relocTable;
DWORD pageBaseVa = rvaToVa(pageBaseRva, imageBase);
DWORD blockSize = *(DWORD*)(relocTable + 4);
relocTableNext += blockSize;
if (relocTableSize <= blockSize) relocTableSize = 0;
else relocTableSize -= blockSize;
block.ptr = relocTable;
block.pageBaseVa = pageBaseVa;
block.relocVa = relocTableVa + ((uintptr_t)(relocTable - relocTableOrig) & 0xFFFFFFFF);
block.size = blockSize;
return true;
}
};
struct RelocEntryIterator {
const DWORD blockVa;
const char* const blockStart;
const char* ptr; // the pointer to the next entry
DWORD blockSize; // the remaining, unconsumed size of the block (we don't actually modify any data, so maybe consume is not the right word)
const DWORD pageBaseVa;
/// <param name="ptr">The address of the start of the whole reloc block, NOT the first member.</param>
/// <param name="blockSize">The size of the entire reloc block, in bytes, including the page base member and the block size member.</param>
/// <param name="pageBaseVa">The page base of the reloc block.</param>
/// <param name="blockVa">The Virtual Address where the reloc block itself is located. Must point to the page base member of the block.</param>
RelocEntryIterator(const char* ptr, DWORD blockSize, DWORD pageBaseVa, DWORD blockVa)
:
ptr(ptr + 8),
blockSize(blockSize <= 8 ? 0 : blockSize - 8),
pageBaseVa(pageBaseVa),
blockStart(ptr),
blockVa(blockVa) { }
RelocEntryIterator(const FoundRelocBlock& block) : RelocEntryIterator(block.ptr, block.size, block.pageBaseVa, block.relocVa) { }
bool getNext(FoundReloc& reloc) {
if (blockSize == 0) return false;
unsigned short entry = *(unsigned short*)ptr;
char blockType = (entry & 0xF000) >> 12;
DWORD entrySize = blockType == IMAGE_REL_BASED_HIGHADJ ? 4 : 2;
reloc.type = blockType;
reloc.regionVa = pageBaseVa | (entry & 0xFFF);
reloc.relocVa = blockVa + ((uintptr_t)(ptr - blockStart) & 0xFFFFFFFF);
if (blockSize <= entrySize) blockSize = 0;
else blockSize -= entrySize;
ptr += entrySize;
return true;
}
};
struct RelocTable {
char* relocTable; // the pointer pointing to the reloc table's start. Typically that'd be the page base member of the first block
DWORD va; // Virtual Address of the reloc table's start
DWORD raw; // the raw position of the reloc table's start
DWORD size; // the size of the whole reloc table
int sizeWhereRaw; // the raw location of the size of the whole reloc table
DWORD imageBase; // the Virtual Address of the base of the image
// Finds the file position of the start of the reloc table and its size
void findRelocTable(char* wholeFileBegin, const std::vector<Section>& sections, DWORD imageBase) {
const char* peHeaderStart = wholeFileBegin + *(DWORD*)(wholeFileBegin + 0x3C);
const char* relocSectionHeader = peHeaderStart + 0xA0;
DWORD relocRva = *(DWORD*)relocSectionHeader;
DWORD* relocSizePtr = (DWORD*)relocSectionHeader + 1;
sizeWhereRaw = (uintptr_t)((const char*)relocSizePtr - wholeFileBegin) & 0xFFFFFFFF;
va = rvaToVa(relocRva, imageBase);
raw = rvaToRaw(sections, relocRva);
relocTable = wholeFileBegin + raw;
size = *relocSizePtr;
this->imageBase = imageBase;
}
// region specified in Virtual Address space
std::vector<FoundReloc> findRelocsInRegion(DWORD regionStart, DWORD regionEnd) const {
std::vector<FoundReloc> result;
RelocBlockIterator blockIterator(relocTable, va, size, imageBase);
FoundRelocBlock block;
while (blockIterator.getNext(block)) {
if (block.pageBaseVa >= regionEnd || (block.pageBaseVa | 0xFFF) + 8 < regionStart) {
continue;
}
RelocEntryIterator entryIterator(block);
FoundReloc reloc;
while (entryIterator.getNext(reloc)) {
if (reloc.type == IMAGE_REL_BASED_ABSOLUTE) continue;
DWORD patchVa = reloc.regionVa;
DWORD patchSize = 4;
switch (reloc.type) {
case IMAGE_REL_BASED_HIGH: patchVa += 2; patchSize = 2; break;
case IMAGE_REL_BASED_LOW: patchSize = 2; break;
case IMAGE_REL_BASED_HIGHLOW: break;
case IMAGE_REL_BASED_HIGHADJ:
patchSize = 2;
break;
case IMAGE_REL_BASED_DIR64: patchSize = 8; break;
}
if (patchVa >= regionEnd || patchVa + patchSize < regionStart) continue;
result.push_back(reloc);
}
}
return result;
}
FoundRelocBlock findLastRelocBlock() const {
RelocBlockIterator blockIterator(relocTable, va, size, imageBase);
FoundRelocBlock block;
while (blockIterator.getNext(block));
return block;
}
// returns empty, unused entries that could potentially be reused for the desired vaToPatch
std::vector<FoundReloc> findReusableRelocEntries(DWORD vaToPatch) const {
std::vector<FoundReloc> result;
RelocBlockIterator blockIterator(relocTable, va, size, imageBase);
FoundRelocBlock block;
while (blockIterator.getNext(block)) {
if (!(
block.pageBaseVa <= vaToPatch && vaToPatch <= (block.pageBaseVa | 0xFFF)
)) {
continue;
}
RelocEntryIterator entryIterator(block);
FoundReloc reloc;
while (entryIterator.getNext(reloc)) {
if (reloc.type == IMAGE_REL_BASED_ABSOLUTE) {
result.push_back(reloc);
}
}
}
return result;
}
template<typename T>
void write(FILE* file, int filePosition, T value) {
fseek(file, filePosition, SEEK_SET);
fwrite(&value, sizeof(T), 1, file);
}
template<typename T, size_t size>
void write(FILE* file, int filePosition, T (&value)[size]) {
fseek(file, filePosition, SEEK_SET);
fwrite(value, sizeof(T), size, file);
}
// Resize the whole reloc table.
// Writes both into the file and into the size member.
void increaseSizeBy(FILE* file, DWORD n) {
DWORD relocSizeRoundUp = (size + 3) & ~3;
size = relocSizeRoundUp + n; // reloc size includes the page base VA and the size of the reloc table entry and of all the entries
// but I still have to round it up to 32 bits
write(file, sizeWhereRaw, size);
}
// Try to:
// 1) Reuse an existing 0000 entry that has a page base from which we can reach the target;
// 2) Try to expand the last block if the target is reachable from its page base;
// 3) Add a new block to the end of the table with that one entry.
void addEntry(FILE* file, DWORD vaToRelocate, char type) {
unsigned short relocEntry = ((unsigned short)type << 12) | (vaToRva(vaToRelocate, imageBase) & 0xFFF);
std::vector<FoundReloc> reusableEntries = findReusableRelocEntries(vaToRelocate);
if (!reusableEntries.empty()) {
const FoundReloc& firstReloc = reusableEntries.front();
write(file, firstReloc.relocVa - va + raw, relocEntry);
*(unsigned short*)(relocTable + firstReloc.relocVa - va) = relocEntry;
CrossPlatformCout << "Reused reloc entry located at va:0x" << std::hex
<< firstReloc.relocVa << " that now relocates va:0x" << vaToRelocate << std::dec << ".\n";
return;
}
const FoundRelocBlock lastBlock = findLastRelocBlock();
if (lastBlock.pageBaseVa <= vaToRelocate && vaToRelocate <= (lastBlock.pageBaseVa | 0xFFF)) {
DWORD newSize = lastBlock.size + 2;
newSize = (newSize + 3) & ~3; // round the size up to 32 bits
DWORD oldTableSize = size;
DWORD sizeIncrease = newSize - lastBlock.size;
increaseSizeBy(file, sizeIncrease);
int pos = lastBlock.relocVa - va + raw;
write(file, pos + 4, newSize);
*(DWORD*)(relocTable + lastBlock.relocVa - va + 4) = newSize;
write(file, pos + lastBlock.size, relocEntry);
unsigned short* newEntryPtr = (unsigned short*)(relocTable + lastBlock.relocVa - va + lastBlock.size);
*newEntryPtr = relocEntry;
if (sizeIncrease > 2) {
unsigned short zeros = 0;
write(file, pos + lastBlock.size + 2, zeros);
*(newEntryPtr + 1) = zeros;
}
CrossPlatformCout << "Expanded reloc block located at va:0x" << std::hex
<< lastBlock.relocVa << " to size 0x" << newSize << ", and whole reloc table expanded to size "
<< size << " (from " << oldTableSize << "), and added a reloc entry located at va:0x" << std::hex
<< lastBlock.relocVa + lastBlock.size << " that now relocates va:0x" << vaToRelocate << std::dec << ".\n";
return;
}
DWORD oldSize = size;
// "Each block must start on a 32-bit boundary." - Microsoft
DWORD oldSizeRoundedUp = (oldSize + 3) & ~3;
// add a new reloc table with one entry
increaseSizeBy(file, 12); // changes 'size'
DWORD rvaToRelocate = vaToRva(vaToRelocate, imageBase);
DWORD newRelocPageBase = rvaToRelocate & 0xFFFFF000;
DWORD tableData[3];
tableData[0] = newRelocPageBase;
tableData[1] = 12; // page base (4) + size of whole block (4) + one entry (2) + padding to make it 32-bit complete (2)
tableData[2] = relocEntry;
write(file, raw + oldSizeRoundedUp, tableData);
memcpy(relocTable + oldSizeRoundedUp, tableData, sizeof tableData);
CrossPlatformCout << "Expanded reloc table from size 0x" << std::hex << oldSize
<< " to size 0x" << size << ", and added a new reloc block, located at va:0x"
<< va + oldSizeRoundedUp << ", and added a new reloc entry into it located at va:0x"
<< va + oldSizeRoundedUp + 8 << " which relocates va:0x" << vaToRelocate << std::dec << ".\n";
}
// fills entry with zeros, diabling it. Does not change the size of either the reloc table or the reloc block
void removeEntry(FILE* file, const FoundReloc& reloc) {
unsigned short zeros = 0;
write(file, reloc.relocVa - va + raw, zeros);
*(unsigned short*)(relocTable + reloc.relocVa - va) = zeros;
CrossPlatformCout << "Removing reloc entry located at va:0x" << std::hex
<< reloc.relocVa << " that relocates va:0x" << reloc.regionVa << std::dec << ".\n";
}
};
// you must use the returned result immediately or copy it somewhere. Do not store it as-is. This function is not thread-safe either
const char* printRelocType(char type) {
static char printRelocTypeBuf[12]; // the maximum possible length of string printed by printf("%d", (int)value), plus null terminating character
switch (type) {
case IMAGE_REL_BASED_HIGH: return "IMAGE_REL_BASED_HIGH";
case IMAGE_REL_BASED_LOW: return "IMAGE_REL_BASED_LOW";
case IMAGE_REL_BASED_HIGHLOW: return "IMAGE_REL_BASED_HIGHLOW";
case IMAGE_REL_BASED_HIGHADJ: return "IMAGE_REL_BASED_HIGHADJ";
case IMAGE_REL_BASED_DIR64: return "IMAGE_REL_BASED_DIR64";
default: sprintf_s(printRelocTypeBuf, "%d", (int)type); return printRelocTypeBuf;
}
}
void printFoundRelocs(const std::vector<FoundReloc>& relocs) {
CrossPlatformCout << '[';
bool isFirst = true;
for (const FoundReloc& reloc : relocs) {
if (!isFirst) CrossPlatformCout << ',';
else isFirst = false;
CrossPlatformCout << "\n\t{\n\t\t\"type\": \""
<< printRelocType(reloc.type)
<< "\",\n"
"\t\t\"relocVa\": \"0x" << std::hex << reloc.relocVa << "\",\n"
"\t\t\"regionVa\": \"0x" << reloc.regionVa << std::dec << "\"\n"
"\t}";
}
if (!isFirst) CrossPlatformCout << '\n';
CrossPlatformCout << ']';
}
bool findExec(const char* name,
const char* wholeFileBegin,
const char* rdataBegin, const char* rdataEnd,
const char* dataBegin, const char* dataEnd,
const std::vector<Section>& sections,
DWORD* va, DWORD* pos) {
std::vector<char> nameAr;
nameAr.resize(strlen(name) + 2);
memcpy(nameAr.data(), name, nameAr.size() - 2);
memset(nameAr.data() + (nameAr.size() - 2), 0, 2);
std::vector<char> maskAr;
maskAr.resize(nameAr.size());
memset(maskAr.data(), 'x', nameAr.size() - 1);
maskAr[nameAr.size() - 1] = '\0';
int strPos = sigscan(rdataBegin, rdataEnd, nameAr.data(), maskAr.data());
if (strPos == -1) {
CrossPlatformCout << "Failed to find " << name << " string.\n";
return false;
}
strPos += (rdataBegin - wholeFileBegin) & 0xFFFFFFFF;
CrossPlatformCout << "Found " << name << " string at file:0x" << std::hex << strPos << std::dec << ".\n";
DWORD strVa = rawToVa(sections, strPos);
int strMentionPos = sigscanEveryNBytes<4>(dataBegin, dataEnd, (const char*)&strVa);
if (strMentionPos == -1) {
CrossPlatformCout << "Failed to find mention of " << name << " string.\n";
return false;
}
strMentionPos += (dataBegin - wholeFileBegin) & 0xFFFFFFFF;
CrossPlatformCout << "Found mention of " << name << " string at file:0x" << std::hex << strMentionPos << std::dec << ".\n";
*va = *(DWORD*)(wholeFileBegin + strMentionPos + 4);
CrossPlatformCout << "Found " << name << " function at va:0x" << std::hex << *va << std::dec << ".\n";
*pos = vaToRaw(sections, *va);
return true;
}
void meatOfTheProgram() {
CrossPlatformString ignoreLine;
#ifndef FOR_LINUX
CrossPlatformCout << CrossPlatformText("Please select a path to your ") << exeName << CrossPlatformText(" file that will be patched...\n");
#else
CrossPlatformCout << CrossPlatformText("Please type in/paste a path to the file, or drag and drop the ")
<< exeName << CrossPlatformText(" file"
" (including the file name and extension) that will be patched...\n");
#endif
#ifndef FOR_LINUX
std::wstring szFile;
szFile.resize(MAX_PATH);
OPENFILENAMEW selectedFiles{ 0 };
selectedFiles.lStructSize = sizeof(OPENFILENAMEW);
selectedFiles.hwndOwner = NULL;
selectedFiles.lpstrFile = &szFile.front();
selectedFiles.lpstrFile[0] = L'\0';
selectedFiles.nMaxFile = (szFile.size() & 0xFFFFFFFF) + 1;
char scramble[] =
"\x4d\xf6\x5f\xf6\x64\xf6\x5a\xf6\x65\xf6\x6d\xf6\x69\xf6\x16\xf6\x3b\xf6"
"\x6e\xf6\x5b\xf6\x59\xf6\x6b\xf6\x6a\xf6\x57\xf6\x58\xf6\x62\xf6\x5b\xf6"
"\xf6\xf6\x20\xf6\x24\xf6\x3b\xf6\x4e\xf6\x3b\xf6\xf6\xf6\xf6\xf6";
wchar_t filter[(sizeof scramble - 1) / sizeof (wchar_t)];
int offset = (int)(
(GetTickCount64() & 0xF000000000000000ULL) >> (63 - 4)
) & 0xFFFFFFFF;
for (int i = 0; i < sizeof scramble - 1; ++i) {
char c = scramble[i] + offset + 10;
((char*)filter)[i] = c;
}
selectedFiles.lpstrFilter = filter;
selectedFiles.nFilterIndex = 1;
selectedFiles.lpstrFileTitle = NULL;
selectedFiles.nMaxFileTitle = 0;
selectedFiles.lpstrInitialDir = NULL;
selectedFiles.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
if (!GetOpenFileNameW(&selectedFiles)) {
DWORD errCode = CommDlgExtendedError();
if (!errCode) {
std::wcout << "The file selection dialog was closed by the user.\n";
} else {
std::wcout << "Error selecting file. Error code: 0x" << std::hex << errCode << std::dec << std::endl;
}
return;
}
szFile.resize(lstrlenW(szFile.c_str()));
#else
std::string szFile;
std::getline(std::cin, szFile);
trim(szFile);
if (!szFile.empty() && (szFile.front() == '\'' || szFile.front() == '"')) {
szFile.erase(szFile.begin());
}
if (!szFile.empty() && (szFile.back() == '\'' || szFile.back() == '"')) {
szFile.erase(szFile.begin() + (szFile.size() - 1));
}
trim(szFile);
if (szFile.empty()) {
std::cout << "Empty path provided. Aborting.\n";
return;
}
#endif
CrossPlatformCout << "Selected file: " << szFile.c_str() << std::endl;
CrossPlatformString fileName = getFileName(szFile);
CrossPlatformString parentDir = getParentDir(szFile);
CrossPlatformCout << "\n";
YesNoCancel askResult = YesNoCancel_Cancel;
const char* askPrompt = "Should the loading screen automatically mash for you so that its animation-only portion gets skipped"
" faster after it finishes loading? Without this, you will either have to mash manually (mash is an overexaggeration,"
" a single button press may be enough) or not mash and let the loading screen play out.\n";
CrossPlatformCout << askPrompt;
AskYesNoCancel(askPrompt, &askResult);
if (askResult == YesNoCancel_Yes) {
CrossPlatformCout << "'Yes' selected. Not implemented yet, patching will continue as if 'No' is selected.\n";
} else if (askResult == YesNoCancel_No) {
CrossPlatformCout << "'No' selected.\n";
} else if (askResult == YesNoCancel_Cancel) {
CrossPlatformCout << "'Cancel' selected. Aborting.\n";
return;
}
CrossPlatformString backupFilePath = generateBackupPath(parentDir, fileName, 0);
int backupNameCounter = 1;
while (fileExists(backupFilePath)) {
backupFilePath = generateBackupPath(parentDir, fileName, backupNameCounter);
++backupNameCounter;
}
CrossPlatformCout << "Will use backup file path: " << backupFilePath.c_str() << std::endl;
#ifndef FOR_LINUX
if (!CopyFileW(szFile.c_str(), backupFilePath.c_str(), true)) {
std::wcout << "Failed to create a backup copy. Do you want to continue anyway? You won't be able to revert the file to the original. Press Enter to agree...\n";
std::getline(std::wcin, ignoreLine);
} else {
std::wcout << "Backup copy created successfully.\n";
}
#else
copyFileLinux(szFile, backupFilePath);
std::wcout << "Backup copy created successfully.\n";
#endif
struct CloseFileOnExit {
~CloseFileOnExit() {
if (file) fclose(file);
}
FILE* file = nullptr;
} fileCloser;
FILE* file = nullptr;
if (!crossPlatformOpenFile(&file, szFile)) return;
fileCloser.file = file;
std::vector<char> wholeFile;
if (!readWholeFile(file, wholeFile)) return;
char* wholeFileBegin = &wholeFile.front();
char* wholeFileEnd = &wholeFile.front() + wholeFile.size();
char* textBegin = nullptr;
char* textEnd = nullptr;
char* rdataBegin = nullptr;
char* rdataEnd = nullptr;
char* dataBegin = nullptr;
char* dataEnd = nullptr;
DWORD imageBase;
std::vector<Section> sections = readSections(file, &imageBase);
if (sections.empty()) {
CrossPlatformCout << "Failed to read sections\n";
return;
}
CrossPlatformCout << "Read sections: [\n";
CrossPlatformCout << std::hex;
bool isFirst = true;
for (const Section& section : sections) {
if (!isFirst) {
CrossPlatformCout << ",\n";
}
isFirst = false;
CrossPlatformCout << "{\n\tname: \"" << section.name.c_str() << "\""
<< ",\n\tvirtualSize: 0x" << section.virtualSize
<< ",\n\tvirtualAddress: 0x" << section.virtualAddress
<< ",\n\trawSize: 0x" << section.rawSize
<< ",\n\trawAddress: 0x" << section.rawAddress