-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathIL2CPPDumpImporter.java
More file actions
945 lines (809 loc) · 31.9 KB
/
IL2CPPDumpImporter.java
File metadata and controls
945 lines (809 loc) · 31.9 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
//Imports SDK dumps generated by REFramework and uses it to annotate the program.
//@author Fexty
//@category Annotation
//@keybinding
//@menupath
//@toolbar
import ghidra.app.script.GhidraScript;
import ghidra.app.services.DataTypeManagerService;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressFactory;
import ghidra.program.model.data.*;
import ghidra.program.model.listing.*;
import ghidra.program.model.symbol.Namespace;
import ghidra.program.model.symbol.SourceType;
import ghidra.program.model.symbol.SymbolTable;
import ghidra.util.exception.CancelledException;
import ghidra.util.exception.UsrException;
import org.json.*;
import java.io.BufferedWriter;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Set;
import java.util.stream.Collectors;
public class IL2CPPDumpImporter extends GhidraScript {
static public FunctionManager functionManager;
static public DataTypeManager typeManager;
static public DataTypeManager builtinTypeManager;
static public AddressFactory addressFactory;
static public SymbolTable symbolTable;
static public CategoryPath category = new CategoryPath("/IL2CPP_Types");
static public HashMap<String, DataType> primitiveTypes;
private int classesAdded;
private int classesToAdd;
private String classFilter;
private BufferedWriter logWriter;
private boolean exitOnError;
private JSONObject il2cppDump;
private HashMap<String, RETypeDefinition> typeMap;
@Override
protected void run() throws ExitException, Exception {
initialize();
importIL2CPPDump();
}
private void initialize() throws Exception {
// Fix for MHR Versions >= 16.0.0, which have ASLR enabled.
var imageBase = askString("Image Base", "Enter the image base of the executable", "0x140000000");
currentProgram.setImageBase(toAddr(imageBase), true);
functionManager = currentProgram.getFunctionManager();
builtinTypeManager = state.getTool().getService(DataTypeManagerService.class).getBuiltInDataTypesManager();
addressFactory = currentProgram.getAddressFactory();
symbolTable = currentProgram.getSymbolTable();
typeMap = new HashMap<>();
typeManager = currentProgram.getDataTypeManager();
if (typeManager == null) {
throw new Exception("failed to find typemanager");
}
// exitOnError = askYesNo("Exit on Error", "Should the script cancel when it
// encounters an error?");
try {
var logFile = askFile("Select Log File", "Open");
logWriter = Files.newBufferedWriter(logFile.toPath(), StandardCharsets.UTF_8);
} catch (CancelledException e) {
println("No log file selected. Logging exceptions to console.");
logWriter = null;
}
final var uint8_t = typeManager.addDataType(
new TypedefDataType("uint8_t", builtinTypeManager.getDataType("/uchar")),
DataTypeConflictHandler.REPLACE_HANDLER);
final var int8_t = typeManager.addDataType(
new TypedefDataType("int8_t", builtinTypeManager.getDataType("/char")),
DataTypeConflictHandler.REPLACE_HANDLER);
final var uint16_t = typeManager.addDataType(
new TypedefDataType("uint16_t", builtinTypeManager.getDataType("/ushort")),
DataTypeConflictHandler.REPLACE_HANDLER);
final var int16_t = typeManager.addDataType(
new TypedefDataType("int16_t", builtinTypeManager.getDataType("/short")),
DataTypeConflictHandler.REPLACE_HANDLER);
final var uint32_t = typeManager.addDataType(
new TypedefDataType("uint32_t", builtinTypeManager.getDataType("/uint")),
DataTypeConflictHandler.REPLACE_HANDLER);
final var int32_t = typeManager.addDataType(
new TypedefDataType("int32_t", builtinTypeManager.getDataType("/int")),
DataTypeConflictHandler.REPLACE_HANDLER);
final var uint64_t = typeManager.addDataType(
new TypedefDataType("uint64_t", builtinTypeManager.getDataType("/ulonglong")),
DataTypeConflictHandler.REPLACE_HANDLER);
final var int64_t = typeManager.addDataType(
new TypedefDataType("int64_t", builtinTypeManager.getDataType("/longlong")),
DataTypeConflictHandler.REPLACE_HANDLER);
final var uintptr_t = typeManager.addDataType(
new TypedefDataType("uintptr_t", builtinTypeManager.getDataType("/ulonglong")),
DataTypeConflictHandler.REPLACE_HANDLER);
final var intptr_t = typeManager.addDataType(
new TypedefDataType("intptr_t", builtinTypeManager.getDataType("/ulonglong")),
DataTypeConflictHandler.REPLACE_HANDLER);
typeManager.addDataType(builtinTypeManager.getDataType("/void"), DataTypeConflictHandler.DEFAULT_HANDLER);
typeManager.addDataType(new PointerDataType(typeManager.getDataType("/void")),
DataTypeConflictHandler.DEFAULT_HANDLER);
// Terminology:
// - ValueType: A type that inherits (directly or indirectly) from
// System.ValueType or System.Enum
// - Primitive Type: A ValueType with size <= sizeof(void*). Hardcoded here for
// simplicity.
// - Reference Type: A type that is not a ValueType. All Reference Types are
// stored on the heap and are only accessed via pointers.
primitiveTypes = new HashMap<>();
primitiveTypes.put("System.Single", builtinTypeManager.getDataType("/float"));
primitiveTypes.put("System.Double", builtinTypeManager.getDataType("/double"));
primitiveTypes.put("System.Void", builtinTypeManager.getDataType("/void"));
primitiveTypes.put("System.UInt8", uint8_t);
primitiveTypes.put("System.UInt16", uint16_t);
primitiveTypes.put("System.UInt32", uint32_t);
primitiveTypes.put("System.UInt64", uint64_t);
primitiveTypes.put("System.Int8", int8_t);
primitiveTypes.put("System.Int16", int16_t);
primitiveTypes.put("System.Int32", int32_t);
primitiveTypes.put("System.Int64", int64_t);
primitiveTypes.put("System.SByte", builtinTypeManager.getDataType("/byte"));
primitiveTypes.put("System.Byte", builtinTypeManager.getDataType("/byte"));
primitiveTypes.put("System.UByte", builtinTypeManager.getDataType("/uchar"));
primitiveTypes.put("System.UIntPtr", uintptr_t);
primitiveTypes.put("System.IntPtr", intptr_t);
primitiveTypes.put("System.Char", builtinTypeManager.getDataType("/char"));
primitiveTypes.put("System.UChar", builtinTypeManager.getDataType("/uchar"));
primitiveTypes.put("System.Void*", typeManager.getDataType("/void *"));
primitiveTypes.put("System.Boolean", builtinTypeManager.getDataType("/bool"));
primitiveTypes.put("System.TypeCode", builtinTypeManager.getDataType("/int"));
primitiveTypes.put("System.DateTime", uint64_t);
primitiveTypes.put("System.TimeSpan", int64_t);
primitiveTypes.put("s8", int8_t);
primitiveTypes.put("u8", uint8_t);
primitiveTypes.put("s16", int16_t);
primitiveTypes.put("u16", uint16_t);
primitiveTypes.put("s32", int32_t);
primitiveTypes.put("u32", uint32_t);
primitiveTypes.put("s64", int64_t);
primitiveTypes.put("u64", uint64_t);
primitiveTypes.put("via.Color", uint32_t);
}
private void importIL2CPPDump() throws Exception {
boolean runDisassemble = false;
if (!askYesNo("Close archive",
"Do not forget to collapse the exe type archive or ghidra will freeze during a large import\nContinue ?")) {
return;
}
if (askYesNo("Auto-Disassemble",
"Do you want to automatically run the post import disassemble script after importing?")) {
runDisassemble = true;
}
File file = askFile("Select IL2CPP Dump", "Open");
var reader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8);
il2cppDump = new JSONObject(new JSONTokener(reader));
reader.close();
println("JSON Loaded");
monitor.initialize(il2cppDump.length(), "Parsing IL2CPP Dump");
int count = il2cppDump.length();
int i = 0;
for (var key : il2cppDump.keySet()) {
typeMap.put(key, new RETypeDefinition(key, il2cppDump.getJSONObject(key)));
println(String.format("parsed (%d/%d)", i++, count));
monitor.incrementProgress(1);
}
println("JSON parsed");
monitor.checkCancelled();
il2cppDump.clear();
System.gc();
classFilter = askString("Filter", "Select Class Filter", "app");
var keys = typeMap.keySet();
if (classFilter == null || classFilter.isEmpty()) {
classesToAdd = keys.size();
// Add all types + Methods to ghidra
for (var key : keys) {
parseClass(key);
}
} else {
Set<String> filtered = keys
.stream()
.filter((name) -> name.startsWith(classFilter))
.collect(Collectors.toSet());
classesToAdd = filtered.size();
monitor.initialize(classesToAdd, "Importing IL2CPP Dump");
for (var key : filtered) {
parseClass(key);
}
}
System.gc();
if (runDisassemble) {
runScript("PostImportDisassemble.java", state);
}
}
public boolean isPrimitiveType(String name) {
return primitiveTypes.containsKey(name);
}
public DataType getPrimitiveType(String objectName) {
return primitiveTypes.get(objectName);
}
private DataType getValueTypeOrType(String name) throws ExitException {
// Top-level types start with a '/', should only occur for built-in types.
if (name.charAt(0) == '/') {
var dt = typeManager.getDataType(name);
if (dt == null) {
println("Failed to find datatype:" + name);
}
return dt;
}
if (primitiveTypes.containsKey(name)) {
return primitiveTypes.get(name);
}
// Type is not a ValueType
RETypeDefinition type = typeMap.getOrDefault(name, null);
if (type != null) {
parseClass(name);
var dt = typeMap.get(name).dataType;
if (dt == null) {
// Should only happen in case an Exception is thrown in parseClass
println("dt is null for " + name + " after parsing");
}
return dt;
}
return null;
}
private DataType getPassingType(String name, boolean forField) throws ExitException {
// Primitive types are always used in their value form and are never passed by
// reference, unless a parameters explicitly has a ByRef/In/Out flag,
// in which case the caller is responsible for handling that.
if (isPrimitiveType(name)) {
return getPrimitiveType(name);
}
DataType type = getValueTypeOrType(name);
var typedef = typeMap.get(name);
if (forField) {
// ValueType and Enum fields are always stored in their value form, even if they
// are larger than 8 bytes.
if (typedef != null && (typedef.isEnum || typedef.isValueType)) {
return type;
}
} else {
// If the type is a ValueType and its size is greater than 8 bytes, it is passed
// as a pointer.
if (typedef != null && (typedef.isValueType || typedef.isEnum) && type.getLength() <= 8) {
return type;
}
}
if (typedef == null) {
return type;
}
return typedef.pointerTo;
}
private boolean isReturnAsOutParameter(String name, DataType type) {
var typedef = typeMap.get(name);
return typedef != null && typedef.isValueType && type.getLength() > 8;
}
private DataType getPassingType(String name) throws ExitException {
return getPassingType(name, false);
}
private Namespace getOrCreateNamespace(String name) throws ExitException {
// Edge case that I honestly cba to handle because it's pretty rare. So just log
// and move on.
if (name.contains("[[")) {
logError("Could not create namespace for: " + name);
return null;
}
// Packed into a function because I hate java's enforced exception handling or
// continued propagating.
try {
return symbolTable.getOrCreateNameSpace(currentProgram.getGlobalNamespace(), name, SourceType.IMPORTED);
} catch (Exception e) {
logException("Failed to get/create namespace", e);
return null;
}
}
private void parseClass(String name) throws ExitException {
if (!typeMap.containsKey(name)) {
return;
}
RETypeDefinition definition = typeMap.get(name);
if (definition.dataType != null) {
return;
}
// `name` here is still in its raw form. Some types are assembly-qualified, and
// we don't want that as part of our type- or namespace names.
// Importantly tho, the typeMap still refers to this type by its raw name.
var realName = definition.name;
// Not actually an accurate display of progress if a filter is used but at least
// gives me an idea of how much was already completed lol.
println(String.format("(%d/%d) Parsing class %s", classesAdded, classesToAdd, name));
classesAdded++;
monitor.incrementProgress(1);
if (!name.startsWith(classFilter)) {
classesToAdd++;
monitor.setMaximum(classesToAdd);
}
// Create TypeInfo label
try {
if (definition.address != null) {
createLabel(definition.address, "TypeInfo", getOrCreateNamespace(realName), false, SourceType.IMPORTED);
}
} catch (Exception e) {
logException("error creating TypeInfo label for " + name, e);
}
if (definition.isValueType && !definition.isEnum) {
parseValueType(realName, definition);
} else {
parseReferenceType(realName, definition);
}
}
private void parseReferenceType(String name, RETypeDefinition definition) throws ExitException {
// Create ghidra type from type definition
DataType type = new StructureDataType(name, definition.size);
// Enum types should be added as an actual enum, not a structure. They DO have a
// structure representation however it is only very rarely used so I don't see
// the point of adding that.
// Also, this 'if' is inside the hasParent 'if' because enums always have
// System.Enum as parent
if (definition.isEnum) {
var enumType = new EnumDataType(name, getPrimitiveType(definition.underlyingType).getLength());
for (var field : definition.fields) {
if (!field.isStatic()) {
continue;
}
try {
enumType.add(field.name, field.defaultValue);
} catch (IllegalArgumentException e) {
println(e.getMessage());
println(e.getStackTrace()[0].toString());
}
}
definition.size = enumType.getLength();
// Overwrite ghidra type of type definition
type = enumType;
}
// Register in archive before doing any new recursive parsing
definition.dataType = typeManager.addDataType(type, DataTypeConflictHandler.REPLACE_HANDLER);
definition.pointerTo = typeManager.addDataType(new PointerDataType(definition.dataType),
DataTypeConflictHandler.REPLACE_HANDLER);
// Parse parent class before parsing current class
if (definition.hasParent()) {
parseClass(definition.parent);
}
// Add all fields to the class
if (definition.dataType instanceof Structure) {
if (definition.isArray) {
addFieldsToArrayType(definition, (Structure) definition.dataType);
} else {
addFieldsOfClassToType(definition, (Structure) definition.dataType, false);
}
}
// Add all methods
if (!definition.methods.isEmpty()) {
for (var method : definition.methods) {
parseMethod(method, definition);
}
}
}
private void parseValueType(String name, RETypeDefinition definition) throws ExitException {
var valueTypeSize = definition.size - typeMap.get("System.Object").size;
if (valueTypeSize <= 0) {
logError("Value type size is less than or equal to 0: " + name);
// We still need to register the type so just parse it as a reference type
parseReferenceType(name, definition);
return;
}
// For value types we create both a structure for the value type itself and a
// structure for its boxed form (i.e. when converted to a System.Object)
DataType boxedType = new StructureDataType("Box<" + name + ">", definition.size);
DataType valueType = new StructureDataType(name, definition.size - typeMap.get("System.Object").size);
// Register in archive before doing any new recursive parsing
definition.dataType = typeManager.addDataType(valueType, DataTypeConflictHandler.REPLACE_HANDLER);
definition.pointerTo = typeManager.addDataType(new PointerDataType(definition.dataType),
DataTypeConflictHandler.REPLACE_HANDLER);
var boxedGhidraType = typeManager.addDataType(boxedType, DataTypeConflictHandler.REPLACE_HANDLER);
typeManager.addDataType(new PointerDataType(boxedGhidraType), DataTypeConflictHandler.REPLACE_HANDLER);
// Parse parent class before parsing current class
if (definition.hasParent()) {
parseClass(definition.parent);
}
// Add all fields to the class
addFieldsOfClassToType(definition, (Structure) boxedGhidraType, false);
addFieldsOfClassToType(definition, (Structure) definition.dataType, true);
// Add all methods
if (!definition.methods.isEmpty()) {
for (var method : definition.methods) {
parseMethod(method, definition);
}
}
}
private void handleStaticGetter(RETypeDefinition parent, REMethod method) throws ExitException {
try {
var fieldName = method.name.substring(4);
var fieldType = getPassingType(method.returnType);
disassemble(toAddr(method.address));
var instruction = getInstructionAt(toAddr(method.address));
if (instruction == null) {
return;
}
if (!instruction.getMnemonicString().equals("MOV")) {
return;
}
if (!instruction.getNext().getMnemonicString().equals("RET")) {
return;
}
var addr = (Address) instruction.getOpObjects(1)[0];
if (addr == null) {
return;
}
createLabel(addr, fieldName, getOrCreateNamespace(parent.name), false, SourceType.IMPORTED);
createData(addr, fieldType);
} catch (ClassCastException e) {
// Not a real problem so just log and continue
logError(String.format("Could not create data for static getter: %s", e.getMessage()));
return;
} catch (Exception e) {
logException("Failed to parse static getter: " + method.name, e);
}
}
private void parseMethod(REMethod method, RETypeDefinition parent) throws ExitException {
if (method.address == 0) {
return;
}
if (method.flags.contains("Static") && method.name.startsWith("get_")) {
handleStaticGetter(parent, method);
}
// If there are already symbols here, there are 2 possibilities:
// 1. This is a generic function and we don't actually want to have a typed
// function,
// remove the function if it's there and add labels and a generic function to
// mark it's been acknowledged
// 2. There is a symbol that was placed there automatically by ghidra
// (SourceType.DEFAULT),
// in this case we can just overwrite it with our function.
var address = addressFactory.getAddress(method.addressString);
var symbol = getSymbolAt(address);
var symbolSource = symbol != null ? symbol.getSource() : SourceType.DEFAULT;
if (symbol != null && symbolSource != SourceType.DEFAULT) {
try {
Function existing = functionManager.getFunctionAt(address);
if (existing != null && existing.getParentNamespace() != currentProgram.getGlobalNamespace()) {
createLabel(address, existing.getName(), existing.getParentNamespace(), false,
SourceType.USER_DEFINED);
functionManager.removeFunction(address);
var name = String.format("GenericFunction_%x", address.getOffset());
if (existing.getName().equals(method.name)) {
name = method.name;
}
createFunction(address, name);
}
createLabel(address, method.name, getOrCreateNamespace(parent.name), false,
SourceType.USER_DEFINED);
} catch (Exception e) {
logException("error creating label for generic function: " + method.name, e);
}
return;
}
Function function;
// If the function does not yet exist then we try to create it and then rename
// it.
try {
if (symbol != null && symbolSource != SourceType.USER_DEFINED && symbolSource != SourceType.IMPORTED) {
symbol.delete();
}
function = createFunction(address, method.name);
if (function != null) {
function.setParentNamespace(getOrCreateNamespace(parent.name));
// Set the source type to IMPORTED so if, in recursive calls, this function is
// encountered again, it knows not to delete it and to add a label instead.
function.getSymbol().setSource(SourceType.IMPORTED);
} else {
logError("Failed to create function: " + parent.name + "." + method.name);
return;
}
// That could be useful, but it's not worth the huge slowdown it causes
// function.setComment(String.format("flags: %s\nimpl flags: %s", method.flags,
// method.implFlags));
} catch (Exception e) {
logException("error creating function: " + method.name, e);
return;
}
// Add all parameters to the function. Code is not complete because there are a
// million exceptions to consider where certain parameters do not exist or
// others exist even tho the dump does not specify them.
// As a general rule tho:
// - The engine conforms to the x64 calling convention so parameters are RCX,
// RDX, R8, R9, Stack...
// - (Basically) all methods take a thread context as their first argument in
// RCX (or RDX, exception below)
// - If a method has the 'HasThis' flag, then it takes a 'this' parameter in RDX
// (or R8, ...)
// - All parameters listed by the dump follow after these 2 in R8/R9 and then on
// the stack starting at 0x28
// - The size of an argument on the stack is at most 8 bytes. Types with size
// greater 8 are passed as a
// pointer.
// - Stack arguments are always 8 byte aligned regardless of the size of the
// type. So +0x28, +0x30, +0x38...
// - If a function has a return type which is a ValueType and its size is
// greater than sizeof(void*) then
// this parameter is passed as a pointer in RCX *always*. It is also returned as
// a pointer
// I believe there are also some types that aren't explicitly ValueTypes but
// still adhere to this behavior.
// - There might be some more intricacies that I have missed...
var params = method.parameters;
var funcParams = new ArrayList<ParameterImpl>();
try {
// Get the return type
var retType = getPassingType(method.returnType);
if (isReturnAsOutParameter(method.returnType, retType)) {
funcParams.add(new ParameterImpl("ret", retType, currentProgram));
}
var ret = new ReturnParameterImpl(retType, currentProgram);
// Methods always take the thread context as their first parameter
funcParams.add(new ParameterImpl("vmctx", getValueTypeOrType("/void *"), currentProgram));
if (method.implFlags.contains("HasThis")) {
funcParams.add(new ParameterImpl("this", parent.dataType, currentProgram));
}
for (var param : params) {
funcParams.add(new ParameterImpl(param.name, getValueTypeOrType(param.type), currentProgram));
}
// Using this function because Function.addParameter is deprecated. This also
// makes things easier as ghidra tries to determine Register and stack offset by
// itself.
function.updateFunction("__fastcall", ret, funcParams,
Function.FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS, true, SourceType.IMPORTED);
} catch (ConcurrentModificationException e) {
// This happens if a recursive call deleted the current function because they're
// at the same address. This is safe to ignore because these edge cases are
// already handled above.
return;
} catch (Exception e) {
logException("error parsing function signature for " + parent.name + "." + method.name, e);
}
}
private void addFieldsToArrayType(RETypeDefinition definition, Structure type) throws ExitException {
type.deleteAll();
type.growStructure(0x20);
type.replaceAtOffset(0x0, getValueTypeOrType("/void *"), 8, "object_info", "");
type.replaceAtOffset(0x8, getPrimitiveType("System.Int32"), 4, "ref_count", "");
type.replaceAtOffset(0x10, getValueTypeOrType("/void *"), 8, "contained_type", "");
type.replaceAtOffset(0x18, getPrimitiveType("System.Int32"), 4, "_n", "");
type.replaceAtOffset(0x1C, getPrimitiveType("System.Int32"), 4, "Count", "");
String containedType = definition.name.replace("[]", "");
var containedDataType = getPassingType(containedType, true);
if (containedDataType == null) {
containedDataType = getValueTypeOrType("/void *");
}
type.growStructure(containedDataType.getLength());
type.replaceAtOffset(0x20,
new ArrayDataType(containedDataType, 1, containedDataType.getLength()),
containedDataType.getLength(), "Elements", "");
}
private void addFieldsOfClassToType(RETypeDefinition definition, Structure type, boolean isValueType)
throws ExitException {
if (definition == null) {
return;
}
if (definition.size == 0) {
return;
}
type.setDescription(String.format("%s:0x%x -> ", definition.name, definition.size) + type.getDescription());
if (definition.hasFields()) {
try {
// Add parent fields before child fields
if (definition.hasParent()) {
addFieldsOfClassToType(typeMap.get(definition.parent), type, isValueType);
}
addFieldsToType(definition.fields, type, isValueType);
} catch (Exception e) {
logException("error adding fields to type: " + definition.name, e);
}
}
}
private void addFieldsToType(ArrayList<REField> fields, Structure type, boolean isValueType) throws Exception {
for (var field : fields) {
if (!field.isStatic()) {
String typeName = field.type;
RETypeDefinition fieldType = typeMap.getOrDefault(typeName, null);
if (fieldType == null) {
continue;
}
var offset = isValueType ? field.offsetFromFieldPtr : field.offsetFromBase;
var existingField = type.getDataTypeAt(offset);
if (existingField != null && existingField.getFieldName() != null
&& existingField.getDataType() != null) {
// If a field already exists at this offset we skip it. This can happen for
// union types.
logError(String.format("Field %s cannot be added to %s because there is already a field at 0x%X",
field.name, type.getName(), offset));
continue;
}
var fieldDataType = getPassingType(typeName, true);
type.replaceAtOffset(
offset,
fieldDataType,
fieldDataType.getLength(),
field.name,
field.flags);
}
}
}
private void logError(String message) {
if (logWriter == null) {
println("Encountered Error: ");
println(message);
} else {
try {
logWriter.write("Encountered Error: ");
logWriter.newLine();
logWriter.write(message);
logWriter.newLine();
} catch (Exception e) {
println("error writing to log file: " + e.getMessage());
}
}
}
private void logException(String message, Exception e) throws ExitException {
// Propagate ExitException without logging
if (e instanceof ExitException) {
throw (ExitException) e;
}
if (logWriter == null) {
println("Encountered Exception: ");
println(message);
println(e.getMessage());
println(e.getStackTrace()[0].toString());
} else {
try {
logWriter.write("Encountered Exception: ");
logWriter.newLine();
logWriter.write(message);
logWriter.newLine();
logWriter.write(e.getMessage());
logWriter.newLine();
logWriter.write(e.getStackTrace()[0].toString());
logWriter.newLine();
} catch (Exception ex) {
println("error writing to log file: " + ex.getMessage());
}
}
if (exitOnError) {
throw new ExitException(message, e);
}
}
private static class REMethod {
public static class Parameter {
public String name;
public String type;
public Parameter(String n, String t) {
name = n;
type = t;
}
}
public String name;
public String flags;
public long address;
public String addressString;
public int id;
public int invokeId;
public String implFlags;
public ArrayList<Parameter> parameters;
public String returnType;
REMethod(String name, JSONObject method) {
flags = method.has("flags") ? method.getString("flags") : "";
addressString = method.getString("function");
address = Long.parseLong(addressString, 16);
id = method.getInt("id");
invokeId = method.getInt("invoke_id");
if (method.has("impl_flags")) {
implFlags = method.getString("impl_flags");
} else {
implFlags = "";
}
// Since method names are stored with [Name][ID] we remove the ID to avoid
// confusing names in ghidra.
// Also constructor names always start with a '.' so we remove that also to
// avoid 'Namespace::.Name'
this.name = (name.startsWith(".") ? name.substring(1) : name).substring(0,
name.indexOf(Integer.toString(id)));
parameters = new ArrayList<>();
if (method.has("params")) {
var params = method.getJSONArray("params");
for (int i = 0; i < params.length(); i++) {
var param = params.getJSONObject(i);
parameters.add(new Parameter(param.getString("name"), param.getString("type")));
}
}
returnType = method.getJSONObject("returns").getString("type");
}
}
private static Address toAddress(String address) {
return addressFactory.getAddress(address);
}
private static class REField {
public String flags;
public int id;
public int offsetFromBase;
public int offsetFromFieldPtr;
public String type;
public String name;
public int defaultValue;
public REField(String name, JSONObject field) {
flags = field.has("flags") ? field.getString("flags") : "";
id = field.getInt("id");
offsetFromBase = Integer.parseInt(field.getString("offset_from_base").substring(2), 16);
// Only ever used for ValueTypes, can ignore for the most part. Kept it here for
// completeness' sake.
offsetFromFieldPtr = Integer.parseInt(field.getString("offset_from_fieldptr").substring(2), 16);
type = field.getString("type");
// Only really used for enum members
defaultValue = field.optInt("default", 0);
this.name = name;
if (this.name.matches("<(.+)>k__BackingField")) {
this.name = "__" + this.name.substring(1, this.name.length() - 16);
this.flags += " | BackingField";
}
}
public boolean isStatic() {
return flags.contains("Static");
}
}
private static class RETypeDefinition {
public String name;
public int size;
public String parent;
public Address address;
public ArrayList<REField> fields;
public ArrayList<REMethod> methods;
public boolean isValueType;
public boolean isEnum;
public boolean isArray;
public String underlyingType;
public DataType dataType;
public DataType pointerTo;
public RETypeDefinition(String className, JSONObject object) {
name = className;
if (object.has("size"))
size = Integer.parseInt(object.getString("size"), 16);
parent = object.has("parent") ? object.getString("parent") : "";
address = object.has("address") ? toAddress(object.getString("address")) : null;
fields = new ArrayList<>();
methods = new ArrayList<>();
if (parent.equals("System.ValueType")) {
isValueType = true;
isEnum = false;
} else if (parent.equals("System.Enum")) {
isValueType = false;
isEnum = true;
} else {
isValueType = false;
isEnum = false;
}
isArray = parent.equals("System.Array");
if (isEnum) {
// Get the enums underlying type
if (object.has("reflection_properties")) {
underlyingType = object.getJSONObject("reflection_properties").getJSONObject("value__")
.getString("type");
} else {
underlyingType = object.getJSONObject("fields").getJSONObject("value__").getString("type");
}
} else {
underlyingType = "";
}
if (object.has("fields")) {
var classFields = object.getJSONObject("fields");
for (var fieldName : classFields.keySet()) {
fields.add(new REField(fieldName, classFields.getJSONObject(fieldName)));
}
}
// Ensure fields are added in order of id, in case there are multiple fields
// with the same offset (i.e. union types)
fields.sort((a, b) -> Integer.compare(a.id, b.id));
if (object.has("methods")) {
var classMethods = object.getJSONObject("methods");
for (var methodName : classMethods.keySet()) {
REMethod method = new REMethod(methodName, classMethods.getJSONObject(methodName));
methods.add(method);
}
}
// This is for types that are assembly-qualified, which will not produce a valid
// namespace name.
// If the passed dump doesn't yet have the "element_type_name" attributes we
// could try to parse it ourselves but like... That's a pain so I'll just ignore
// that for now.
if (object.has("element_type_name")) {
name = object.getString("element_type_name");
// The element_type_name doesn't contain the '[]' for arrays so we add it
// manually
if (isArray) {
name += "[]";
}
}
}
public boolean hasFields() {
return !fields.isEmpty();
}
public boolean hasParent() {
return !parent.isEmpty();
}
}
private class ExitException extends UsrException {
public ExitException(String msg, Throwable cause) {
super("Script was cancelled because of an error: " + msg, cause);
}
}
}