-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathOffsetRecoveryFramework.java
More file actions
1855 lines (1619 loc) · 69.3 KB
/
Copy pathOffsetRecoveryFramework.java
File metadata and controls
1855 lines (1619 loc) · 69.3 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
// Ghidra script: recover update-prone static offsets from semantic recipes.
// @category GameHelper2
// @author Arsenic
import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.Address;
import ghidra.program.model.listing.BookmarkType;
import ghidra.program.model.listing.Data;
import ghidra.program.model.listing.DataIterator;
import ghidra.program.model.listing.Function;
import ghidra.program.model.listing.Instruction;
import ghidra.program.model.listing.InstructionIterator;
import ghidra.program.model.mem.MemoryBlock;
import ghidra.program.model.mem.MemoryAccessException;
import ghidra.program.model.symbol.Reference;
import ghidra.program.model.symbol.RefType;
import ghidra.program.model.symbol.SourceType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class OffsetRecoveryFramework extends GhidraScript {
private static final boolean VERBOSE = false;
private static final int HIGH_CONFIDENCE = 85;
private static final int MAX_GAME_STATES_PROVIDER_SCAN_BYTES = 0x180;
private static final int MAX_FILE_ROOT_FINDER_SCAN_BYTES = 0x180;
private static final int MAX_AREA_COUNTER_SCAN_BYTES = 0x300;
private static final int MAX_UNIQUE_PATTERN_BYTES = 0x80;
private final List<StringHit> stringCache = new ArrayList<>();
private final RecoverySummary summary = new RecoverySummary();
@Override
public void run() throws Exception {
println("GameHelper2 Offset Recovery Framework");
println("Program: " + currentProgram.getName());
println("");
cacheDefinedStrings();
for (OffsetRecipe recipe : Arrays.asList(
new GameStatesRecipe(),
new FileRootRecipe(),
new AreaChangeCounterRecipe(),
new TerrainRotatorHelperRecipe(),
new TerrainRotationSelectorRecipe(),
new GameCullSizeRecipe()
)) {
runRecipe(recipe);
println("");
}
summary.print();
}
private void runRecipe(OffsetRecipe recipe) {
println("== " + recipe.name() + " ==");
try {
List<RecoveryResult> candidates = recipe.recoverCandidates();
sortCandidates(candidates);
if (candidates.isEmpty()) {
println("FAILED: " + recipe.failureReason());
summary.addFailure(recipe.name(), recipe.failureReason());
return;
}
RecoveryResult best = candidates.get(0);
finalizeOutputPattern(best);
if (best.match.patternMatchCount != 1) {
String reason = "output pattern is not unique in executable memory; matches="
+ best.match.patternMatchCount;
println("FAILED: " + reason);
summary.addFailure(recipe.name(), reason);
return;
}
printResult(best);
annotate(best);
summary.addSuccess(best, candidates.size());
}
catch (Exception e) {
String reason = e.getClass().getSimpleName() + ": " + e.getMessage();
println("FAILED: " + reason);
summary.addFailure(recipe.name(), reason);
}
}
private void sortCandidates(List<RecoveryResult> candidates) {
Collections.sort(candidates, new Comparator<RecoveryResult>() {
@Override
public int compare(RecoveryResult left, RecoveryResult right) {
return Integer.compare(right.score, left.score);
}
});
}
private void printResult(RecoveryResult result) {
println("Anchor string : " + result.anchor.address + " \"" + result.anchor.value + "\"");
println("String reference : " + result.stringReferenceAddress);
println("XREF function : " + formatFunction(result.xrefFunction));
println("Source function : " + formatFunction(result.sourceFunction));
if (result.callDepth >= 0) {
println("Call depth : " + result.callDepth);
}
println("Match start : " + result.match.matchAddress);
println("Target instruction : " + result.match.instructionAddress + " " + result.match.matchKind);
println("Resolved address : " + result.match.resolvedAddress);
println("Output pattern : " + result.match.outputPattern);
println("BytesToSkip : " + result.match.bytesToSkip);
println("Pattern matches : " + result.match.patternMatchCount);
println("Confidence : " + confidenceLabel(result.score) + " (" + result.score + "/100)");
if (VERBOSE) {
printList("Score reasons", result.scoreReasons);
printList("Validations", result.validations);
}
}
private void finalizeOutputPattern(RecoveryResult result) throws MemoryAccessException {
if (result.match.patternMatchCount == 1) {
return;
}
UniquePattern uniquePattern = makeBestUniquePattern(result.match);
result.match.matchAddress = uniquePattern.start;
result.match.outputPattern = uniquePattern.pattern;
result.match.bytesToSkip = uniquePattern.bytesToSkip;
result.match.patternMatchCount = uniquePattern.matchCount;
result.validations.add("SigMaker pass ran on selected candidate only");
if (uniquePattern.matchCount == 1) {
result.score = Math.min(100, result.score + 5);
result.validations.add("output pattern is unique in executable memory");
}
else {
result.score = 0;
result.validations.add("output pattern match count: " + uniquePattern.matchCount);
}
}
private UniquePattern makeBestUniquePattern(OffsetMatch match) throws MemoryAccessException {
int minimumLength = parsePattern(match.outputPattern).bytes.length;
int originalInstructionOffset = (int)match.instructionAddress.subtract(match.matchAddress);
int displacementOffsetInInstruction = match.bytesToSkip - originalInstructionOffset;
int originalTailLength = minimumLength - originalInstructionOffset;
UniquePattern best = null;
for (Address start : uniquePatternStartCandidates(match)) {
if (start == null || start.compareTo(match.instructionAddress) > 0) {
continue;
}
int instructionOffset = (int)match.instructionAddress.subtract(start);
int bytesToSkip = instructionOffset + displacementOffsetInInstruction;
int candidateMinimumLength = Math.max(instructionOffset + originalTailLength, bytesToSkip + 4);
if (bytesToSkip < 0 || candidateMinimumLength > MAX_UNIQUE_PATTERN_BYTES) {
continue;
}
UniquePattern candidate = makeUniquePattern(start, candidateMinimumLength, bytesToSkip);
if (best == null || candidate.isBetterThan(best)) {
best = candidate;
}
if (candidate.matchCount == 1 && candidate.byteLength <= minimumLength) {
return candidate;
}
}
if (best != null) {
return best;
}
return makeUniquePattern(match.matchAddress, minimumLength, match.bytesToSkip);
}
private List<Address> uniquePatternStartCandidates(OffsetMatch match) {
List<Address> starts = new ArrayList<>();
Set<Address> seen = new HashSet<>();
addUniqueStart(starts, seen, match.matchAddress);
addUniqueStart(starts, seen, match.instructionAddress);
Function function = getFunctionContaining(match.instructionAddress);
Instruction instruction = getInstructionBefore(match.instructionAddress);
int count = 0;
while (instruction != null
&& count < 16
&& match.instructionAddress.subtract(instruction.getAddress()) <= 0x60
&& (function == null || function.getBody().contains(instruction.getAddress()))) {
addUniqueStart(starts, seen, instruction.getAddress());
instruction = getInstructionBefore(instruction);
count++;
}
if (function != null && hasInstructionBody(function)) {
addUniqueStart(starts, seen, function.getEntryPoint());
}
return starts;
}
private void addUniqueStart(List<Address> starts, Set<Address> seen, Address address) {
if (address != null && !seen.contains(address)) {
starts.add(address);
seen.add(address);
}
}
private void printList(String title, List<String> values) {
if (values.isEmpty()) {
return;
}
println(title + " :");
for (String value : values) {
println(" - " + value);
}
}
private String formatFunction(Function function) {
if (function == null) {
return "<none>";
}
return function.getName() + " @ " + function.getEntryPoint();
}
private void annotate(RecoveryResult result) {
String comment = "Recovered " + result.offsetName + " candidate: "
+ result.match.resolvedAddress + " via " + result.match.matchKind + ".";
setEOLComment(result.match.instructionAddress, comment);
createBookmark(result.anchor.address, BookmarkType.ANALYSIS,
"GameHelper2 Offset: " + result.offsetName + " anchor string.");
createBookmark(result.stringReferenceAddress, BookmarkType.ANALYSIS,
"GameHelper2 Offset: " + result.offsetName + " anchor XREF.");
createBookmark(result.match.instructionAddress, BookmarkType.ANALYSIS, "GameHelper2 Offset: " + comment);
createBookmark(result.match.resolvedAddress, BookmarkType.ANALYSIS,
"GameHelper2 Offset: " + result.offsetName + " static candidate.");
if (result.score >= HIGH_CONFIDENCE) {
createLabelIfMissing(result.match.resolvedAddress, result.staticLabel);
if (result.sourceFunction != null && result.sourceLabel != null) {
createLabelIfMissing(result.sourceFunction.getEntryPoint(), result.sourceLabel);
}
}
}
private void createLabelIfMissing(Address address, String label) {
if (address == null || label == null || label.length() == 0) {
return;
}
try {
createLabel(address, label, false, SourceType.USER_DEFINED);
}
catch (Exception e) {
println("WARN: could not create label " + label + " at " + address + ": " + e.getMessage());
}
}
private void cacheDefinedStrings() {
stringCache.clear();
DataIterator iterator = currentProgram.getListing().getDefinedData(true);
while (iterator.hasNext() && !monitor.isCancelled()) {
Data data = iterator.next();
Object value = data.getValue();
if (value instanceof String) {
stringCache.add(new StringHit((String)value, data.getAddress()));
}
}
println("Cached defined strings: " + stringCache.size());
println("");
}
private List<StringHit> findAnchors(AnchorSpec... anchors) {
List<StringHit> hits = new ArrayList<>();
Set<Address> seen = new HashSet<>();
for (AnchorSpec anchor : anchors) {
for (StringHit hit : stringCache) {
if (seen.contains(hit.address)) {
continue;
}
if (anchor.matches(hit.value)) {
hits.add(hit);
seen.add(hit.address);
}
}
}
return hits;
}
private List<Reference> referencesTo(Address address) {
return Arrays.asList(getReferencesTo(address));
}
private List<Function> directCalls(Function function) {
return directCallsBefore(function, null);
}
private List<Function> directCallsBefore(Function function, Address beforeAddress) {
List<Function> calls = new ArrayList<>();
if (!hasInstructionBody(function)) {
return calls;
}
Set<Address> seenEntries = new HashSet<>();
InstructionIterator instructions = currentProgram.getListing().getInstructions(function.getBody(), true);
while (instructions.hasNext()) {
Instruction instruction = instructions.next();
if (beforeAddress != null && instruction.getAddress().compareTo(beforeAddress) >= 0) {
break;
}
if (!"CALL".equals(instruction.getMnemonicString())) {
continue;
}
for (Reference reference : getReferencesFrom(instruction.getAddress())) {
RefType type = reference.getReferenceType();
if (!type.isCall()) {
continue;
}
Function called = getFunctionAt(reference.getToAddress());
if (hasInstructionBody(called) && seenEntries.add(called.getEntryPoint())) {
calls.add(called);
}
}
}
return calls;
}
private List<Function> directCallsToDepth(Function root, int maxDepth) {
List<Function> result = new ArrayList<>();
if (!hasInstructionBody(root)) {
return result;
}
Set<Address> seenEntries = new HashSet<>();
List<FunctionDepth> frontier = new ArrayList<>();
frontier.add(new FunctionDepth(root, 0));
for (int i = 0; i < frontier.size(); i++) {
FunctionDepth current = frontier.get(i);
if (current.depth >= maxDepth) {
continue;
}
for (Function called : directCalls(current.function)) {
if (seenEntries.add(called.getEntryPoint())) {
result.add(called);
frontier.add(new FunctionDepth(called, current.depth + 1));
}
}
}
return result;
}
private int callDepth(Function root, Function target, int maxDepth) {
if (!hasInstructionBody(root) || target == null) {
return -1;
}
if (root.getEntryPoint().equals(target.getEntryPoint())) {
return 0;
}
Set<Address> seenEntries = new HashSet<>();
List<FunctionDepth> frontier = new ArrayList<>();
frontier.add(new FunctionDepth(root, 0));
for (int i = 0; i < frontier.size(); i++) {
FunctionDepth current = frontier.get(i);
if (current.depth >= maxDepth) {
continue;
}
for (Function called : directCalls(current.function)) {
if (called.getEntryPoint().equals(target.getEntryPoint())) {
return current.depth + 1;
}
if (seenEntries.add(called.getEntryPoint())) {
frontier.add(new FunctionDepth(called, current.depth + 1));
}
}
}
return -1;
}
private int callerCount(Function function) {
if (function == null) {
return 0;
}
int count = 0;
for (Reference reference : getReferencesTo(function.getEntryPoint())) {
if (reference.getReferenceType().isCall()) {
count++;
}
}
return count;
}
private List<Instruction> instructionsInWindow(Function function, Address start, int maxBytes) {
List<Instruction> result = new ArrayList<>();
if (!hasInstructionBody(function) || start == null) {
return result;
}
Address functionEnd = function.getBody().getMaxAddress();
if (functionEnd == null) {
return result;
}
Address end;
try {
end = start.addNoWrap(maxBytes);
}
catch (Exception e) {
end = functionEnd;
}
if (end.compareTo(functionEnd) > 0) {
end = functionEnd;
}
Instruction instruction = getInstructionAt(start);
if (instruction == null) {
instruction = getInstructionAfter(start);
}
while (instruction != null
&& instruction.getAddress().compareTo(end) <= 0
&& function.getBody().contains(instruction.getAddress())) {
result.add(instruction);
instruction = getInstructionAfter(instruction);
}
return result;
}
private boolean hasInstructionBody(Function function) {
return function != null
&& !function.isExternal()
&& function.getEntryPoint() != null
&& function.getBody() != null
&& !function.getBody().isEmpty();
}
private OffsetMatch findStaticQwordNullCheck(Function function) throws Exception {
for (Instruction instruction : instructionsInWindow(
function,
function.getEntryPoint(),
MAX_GAME_STATES_PROVIDER_SCAN_BYTES
)) {
Address address = instruction.getAddress();
if (isStaticQwordNullCheck(instruction)) {
boolean hasPrologueContext = hasPreviousInstructionText(function, address, "XOR EBP,EBP");
return ripRelativeMatchThroughBranch(
function,
instruction,
3,
"static qword null-check",
hasPrologueContext ? "provider-prologue" : null
);
}
}
return null;
}
private OffsetMatch findStaticQwordReturn(Function function) throws Exception {
for (Instruction instruction : instructionsInWindow(
function,
function.getEntryPoint(),
MAX_FILE_ROOT_FINDER_SCAN_BYTES
)) {
Address address = instruction.getAddress();
if (!isStaticMovIntoRax(instruction) || !hasNearbyRet(address, 0x18)) {
continue;
}
boolean hasTlsInitContext = hasThreadLocalSetupNearEntry(function)
&& address.subtract(function.getEntryPoint()) < 0x80;
if (!hasTlsInitContext) {
continue;
}
return ripRelativeMatch(
address,
instruction,
3,
"static qword return",
hasTlsInitContext ? "tls-init-context" : null
);
}
return null;
}
private OffsetMatch findDwordIncrementAfter(Function function, Address anchorReference) throws Exception {
for (Instruction instruction : instructionsInWindow(function, anchorReference, MAX_AREA_COUNTER_SCAN_BYTES)) {
Address address = instruction.getAddress();
if (!isStaticDwordIncrement(instruction)) {
continue;
}
boolean hasTlsContext = hasAreaChangeTlsContext(function, address);
return ripRelativeMatch(
address,
instruction,
2,
"static dword increment",
hasTlsContext ? "tls-init-context" : null
);
}
return null;
}
private List<OffsetMatch> findGameCullSizeShapeMatches() throws Exception {
List<OffsetMatch> matches = new ArrayList<>();
InstructionIterator instructions = currentProgram.getListing().getInstructions(
currentProgram.getMemory().getExecuteSet(),
true
);
while (instructions.hasNext() && !monitor.isCancelled()) {
Instruction instruction = instructions.next();
Address address = instruction.getAddress();
if (!isStaticSubFromEax(instruction)) {
continue;
}
Address staticReference = firstMemoryReferenceFrom(instruction);
if (staticReference == null || !hasCallBefore(address, 0x80) || !hasVectorZeroAfter(address, 0x40)) {
continue;
}
matches.add(ripRelativeMatch(
address,
instruction,
2,
"game cull size subtract from FOO result",
"call-before",
"vector-zero-after"
));
}
return matches;
}
private boolean isStaticQwordNullCheck(Instruction instruction) {
if (!"CMP".equals(instruction.getMnemonicString()) || firstMemoryReferenceFrom(instruction) == null) {
return false;
}
String text = instruction.toString().toUpperCase();
return text.indexOf("QWORD PTR") >= 0
&& (text.endsWith(",RBP") || text.endsWith(",0X0") || text.endsWith(",0"));
}
private boolean isStaticMovIntoRax(Instruction instruction) {
if (!"MOV".equals(instruction.getMnemonicString()) || firstMemoryReferenceFrom(instruction) == null) {
return false;
}
return instruction.toString().toUpperCase().startsWith("MOV RAX,");
}
private boolean isStaticDwordIncrement(Instruction instruction) {
if (!"INC".equals(instruction.getMnemonicString()) || firstMemoryReferenceFrom(instruction) == null) {
return false;
}
return instruction.toString().toUpperCase().indexOf("DWORD PTR") >= 0;
}
private boolean isStaticSubFromEax(Instruction instruction) {
if (!"SUB".equals(instruction.getMnemonicString())) {
return false;
}
String text = instruction.toString().toUpperCase();
return text.startsWith("SUB EAX,") && firstMemoryReferenceFrom(instruction) != null;
}
private OffsetMatch ripRelativeMatch(Address matchStart, Instruction instruction, int displacementOffset,
String matchKind, String... traits) throws Exception {
int patternLength = (int)instruction.getAddress().subtract(matchStart) + instruction.getLength();
return ripRelativeMatch(matchStart, instruction, displacementOffset, patternLength, matchKind, traits);
}
private OffsetMatch ripRelativeMatch(Address matchStart, Instruction instruction, int displacementOffset,
int patternLength, String matchKind, String... traits) throws Exception {
Address instructionAddress = instruction.getAddress();
Address resolved = firstMemoryReferenceFrom(instruction);
if (resolved == null) {
resolved = resolveRipRelative(instructionAddress, instruction.getLength(), displacementOffset);
}
int bytesToSkip = (int)instructionAddress.subtract(matchStart) + displacementOffset;
return new OffsetMatch(
matchStart,
instructionAddress,
resolved,
ripPattern(matchStart, patternLength, bytesToSkip, 4),
bytesToSkip,
matchKind,
0,
traits
);
}
private OffsetMatch ripRelativeMatchThroughBranch(Function function, Instruction instruction, int displacementOffset,
String matchKind, String... traits) throws Exception {
int length = instruction.getLength();
Instruction next = getInstructionAfter(instruction);
if (next != null
&& function.getBody().contains(next.getAddress())
&& next.getFlowType().isConditional()) {
length += next.getLength();
}
return ripRelativeMatch(instruction.getAddress(), instruction, displacementOffset, length, matchKind, traits);
}
private UniquePattern makeUniquePattern(Address start, int minimumLength, int bytesToSkip)
throws MemoryAccessException {
Function function = getFunctionContaining(start);
int length = alignPatternLengthToInstruction(start, minimumLength, function);
UniquePattern best = null;
while (length <= MAX_UNIQUE_PATTERN_BYTES) {
String pattern = ripPattern(start, length, bytesToSkip, 4);
PatternBytes parsed = parsePattern(pattern);
int matchCount = countExecutableMatches(parsed, 2);
UniquePattern candidate = new UniquePattern(
pattern,
matchCount,
start,
bytesToSkip,
parsed.bytes.length,
parsed.fixedByteCount
);
if (best == null || candidate.isBetterThan(best)) {
best = candidate;
}
if (matchCount == 1) {
return candidate;
}
int nextLength = nextInstructionAlignedLength(start, length, function);
if (nextLength <= length) {
break;
}
length = nextLength;
}
if (best != null) {
return best;
}
String pattern = ripPattern(start, minimumLength, bytesToSkip, 4);
PatternBytes parsed = parsePattern(pattern);
return new UniquePattern(
pattern,
countExecutableMatches(parsed, 2),
start,
bytesToSkip,
parsed.bytes.length,
parsed.fixedByteCount
);
}
private int alignPatternLengthToInstruction(Address start, int minimumLength, Function function) {
int alignedLength = 0;
Instruction instruction = getInstructionAt(start);
if (instruction == null) {
instruction = getInstructionAfter(start);
}
while (instruction != null
&& instruction.getAddress().compareTo(start) >= 0
&& (function == null || function.getBody().contains(instruction.getAddress()))
&& alignedLength < minimumLength) {
alignedLength = (int)instruction.getAddress().subtract(start) + instruction.getLength();
instruction = getInstructionAfter(instruction);
}
return Math.max(minimumLength, alignedLength);
}
private int nextInstructionAlignedLength(Address start, int currentLength, Function function) {
Address currentEnd = start.add(currentLength - 1);
Instruction instruction = getInstructionAfter(currentEnd);
if (instruction == null || (function != null && !function.getBody().contains(instruction.getAddress()))) {
return -1;
}
return (int)instruction.getAddress().subtract(start) + instruction.getLength();
}
private String ripPattern(Address start, int length, int displacementOffset, int displacementLength)
throws MemoryAccessException {
boolean[] wildcard = new boolean[length];
markWildcard(wildcard, displacementOffset, displacementLength);
markReferencedDisplacements(start, length, wildcard);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i > 0) {
builder.append(' ');
}
if (i == displacementOffset) {
builder.append("^ ");
}
if (wildcard[i]) {
builder.append("??");
}
else {
builder.append(String.format("%02X", u8(start.add(i))));
}
}
return builder.toString();
}
private void markReferencedDisplacements(Address start, int length, boolean[] wildcard)
throws MemoryAccessException {
Address end = start.add(length - 1);
Instruction instruction = getInstructionAt(start);
if (instruction == null) {
instruction = getInstructionAfter(start);
}
while (instruction != null
&& instruction.getAddress().compareTo(end) <= 0
&& instruction.getAddress().compareTo(start) >= 0) {
for (Reference reference : getReferencesFrom(instruction.getAddress())) {
Address toAddress = reference.getToAddress();
if (isRelocatableReference(reference)
&& toAddress != null
&& currentProgram.getMemory().contains(toAddress)) {
markDisplacementBytes(start, instruction, toAddress, wildcard);
}
}
instruction = getInstructionAfter(instruction);
}
}
private boolean isRelocatableReference(Reference reference) {
if (reference.isMemoryReference()) {
return true;
}
RefType type = reference.getReferenceType();
return type.isCall() || type.isJump() || type.isFlow();
}
private void markDisplacementBytes(Address patternStart, Instruction instruction, Address target, boolean[] wildcard)
throws MemoryAccessException {
long nextInstructionOffset = instruction.getAddress().getOffset() + instruction.getLength();
int displacement = (int)(target.getOffset() - nextInstructionOffset);
int instructionOffset = (int)instruction.getAddress().subtract(patternStart);
for (int i = 0; i <= instruction.getLength() - 4; i++) {
if (u8(instruction.getAddress().add(i)) == (displacement & 0xff)
&& u8(instruction.getAddress().add(i + 1)) == ((displacement >>> 8) & 0xff)
&& u8(instruction.getAddress().add(i + 2)) == ((displacement >>> 16) & 0xff)
&& u8(instruction.getAddress().add(i + 3)) == ((displacement >>> 24) & 0xff)) {
markWildcard(wildcard, instructionOffset + i, 4);
return;
}
}
}
private void markWildcard(boolean[] wildcard, int offset, int length) {
for (int i = Math.max(0, offset); i < offset + length && i < wildcard.length; i++) {
wildcard[i] = true;
}
}
private PatternBytes parsePattern(String pattern) {
String[] parts = pattern.replace("^", "").trim().split("\\s+");
byte[] bytes = new byte[parts.length];
boolean[] mask = new boolean[parts.length];
for (int i = 0; i < parts.length; i++) {
if (parts[i].startsWith("?")) {
bytes[i] = 0;
mask[i] = false;
}
else {
bytes[i] = (byte)Integer.parseInt(parts[i], 16);
mask[i] = true;
}
}
return new PatternBytes(bytes, mask);
}
private int countExecutableMatches(PatternBytes pattern, int stopAfter) throws MemoryAccessException {
if (pattern.firstMaskedIndex < 0) {
return stopAfter;
}
int count = 0;
byte[] searchMask = searchMask(pattern.mask);
for (MemoryBlock block : currentProgram.getMemory().getBlocks()) {
if (!block.isExecute() || !block.isInitialized() || block.getSize() < pattern.bytes.length) {
continue;
}
Address cursor = block.getStart();
Address lastStart = block.getStart().add(block.getSize() - pattern.bytes.length);
while (cursor.compareTo(lastStart) <= 0 && !monitor.isCancelled()) {
Address found = currentProgram.getMemory().findBytes(
cursor,
block.getEnd(),
pattern.bytes,
searchMask,
true,
monitor
);
if (found == null || found.compareTo(lastStart) > 0) {
break;
}
count++;
if (count >= stopAfter) {
return count;
}
cursor = found.add(1);
}
}
return count;
}
private byte[] searchMask(boolean[] fixedBytes) {
byte[] mask = new byte[fixedBytes.length];
for (int i = 0; i < fixedBytes.length; i++) {
if (fixedBytes[i]) {
mask[i] = (byte)0xff;
}
}
return mask;
}
private Address firstMemoryReferenceFrom(Instruction instruction) {
for (Reference reference : getReferencesFrom(instruction.getAddress())) {
Address toAddress = reference.getToAddress();
if (reference.isMemoryReference()
&& toAddress != null
&& currentProgram.getMemory().contains(toAddress)) {
return toAddress;
}
}
return null;
}
private boolean hasCallBefore(Address address, int maxBytes) {
Function function = getFunctionContaining(address);
if (!hasInstructionBody(function)) {
return false;
}
InstructionIterator instructions = currentProgram.getListing().getInstructions(function.getBody(), true);
while (instructions.hasNext()) {
Instruction instruction = instructions.next();
Address instructionAddress = instruction.getAddress();
if (instructionAddress.compareTo(address) >= 0) {
break;
}
if ("CALL".equals(instruction.getMnemonicString()) && address.subtract(instructionAddress) <= maxBytes) {
return true;
}
}
return false;
}
private boolean hasPreviousInstructionText(Function function, Address address, String expectedText) {
Instruction instruction = getInstructionBefore(address);
return instruction != null
&& function.getBody().contains(instruction.getAddress())
&& instruction.toString().toUpperCase().equals(expectedText);
}
private boolean hasVectorZeroAfter(Address address, int maxBytes) {
Instruction instruction = getInstructionAfter(address);
while (instruction != null && instruction.getAddress().subtract(address) <= maxBytes) {
String mnemonic = instruction.getMnemonicString();
String text = instruction.toString().toUpperCase();
if (("XORPS".equals(mnemonic) || "PXOR".equals(mnemonic) || "XORPD".equals(mnemonic))
&& text.indexOf("XMM") >= 0) {
return true;
}
instruction = getInstructionAfter(instruction);
}
return false;
}
private List<OffsetMatch> findTerrainRotatorHelperShapeMatches() throws Exception {
return findTerrainRotationShapeMatches(false);
}
private List<OffsetMatch> findTerrainRotationSelectorShapeMatches() throws Exception {
return findTerrainRotationShapeMatches(true);
}
private List<OffsetMatch> findTerrainRotationShapeMatches(boolean selector) throws Exception {
List<OffsetMatch> matches = new ArrayList<>();
for (Function function : currentProgram.getFunctionManager().getFunctions(true)) {
if (!hasInstructionBody(function)) {
continue;
}
OffsetMatch match = inspectTerrainRotationShape(function, selector);
if (match != null) {
matches.add(match);
}
}
return matches;
}
private OffsetMatch inspectTerrainRotationShape(Function function, boolean selector) throws Exception {
List<Instruction> instructions = instructionsInWindow(function, function.getEntryPoint(), 0xc0);
if (instructions.size() < 40 || instructions.size() > 80) {
return null;
}
Address entry = function.getEntryPoint();
if (!hasTerrainHelperEntryShape(instructions)) {
return null;
}
Instruction tableLea = null;
Instruction rotatorLea = null;
boolean hasClampEight = false;
boolean hasTileSizeConstant = false;
boolean hasScaleByThree = false;
boolean hasBoundsCheck = false;
boolean hasTerrainReadCall = false;
for (Instruction instruction : instructions) {
Address address = instruction.getAddress();
String text = instruction.toString().toUpperCase();
if (isStaticLeaInto(instruction, "RCX")) {
tableLea = instruction;
}
if (isStaticLeaInto(instruction, "RAX")) {
rotatorLea = instruction;
}
if ("MOV EAX,0X8".equals(text) || "CMP R8D,EAX".equals(text)) {
hasClampEight = true;
}
if ("MOV EDX,0X16".equals(text)) {
hasTileSizeConstant = true;
}
if ("LEA".equals(instruction.getMnemonicString())
&& text.startsWith("LEA R8,")
&& text.indexOf("R8*0X2") >= 0) {
hasScaleByThree = true;
}
if (text.indexOf("0X17") >= 0) {
hasBoundsCheck = true;
}
if ("CALL".equals(instruction.getMnemonicString()) && address.subtract(entry) > 0x80) {
hasTerrainReadCall = true;
}
}
if (tableLea == null || rotatorLea == null || !hasClampEight || !hasTileSizeConstant
|| !hasScaleByThree || !hasBoundsCheck || !hasTerrainReadCall) {
return null;
}
if (selector) {
return ripRelativeMatch(
entry,
tableLea,
3,
"terrain rotation selector function shape"
);
}
return ripRelativeMatch(
entry,
rotatorLea,
3,
"terrain rotator helper function shape"
);
}
private boolean hasTerrainHelperEntryShape(List<Instruction> instructions) {
if (instructions.size() < 4) {
return false;
}
return instructionTextEquals(instructions.get(0), "SUB RSP,0x38")
&& instructionTextEquals(instructions.get(1), "MOVZX EAX,R8B")
&& instructionTextEquals(instructions.get(2), "MOV R10,RCX")
&& instructionTextEquals(instructions.get(3), "MOV R9,RDX");
}
private boolean isStaticLeaInto(Instruction instruction, String register) {
if (!"LEA".equals(instruction.getMnemonicString()) || firstMemoryReferenceFrom(instruction) == null) {
return false;
}