forked from geode-sdk/bindings
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSyncBromaScript.java
More file actions
1527 lines (1392 loc) · 69.9 KB
/
SyncBromaScript.java
File metadata and controls
1527 lines (1392 loc) · 69.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
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
// Sync your RE'd addresses to & from GeometryDash.bro
// @author HJfod
// @category GeodeSDK
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
import docking.DockingWindowManager;
import docking.widgets.dialogs.InputWithChoicesDialog;
import docking.widgets.dialogs.MultiLineMessageDialog;
import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.Address;
import ghidra.program.model.data.AbstractFloatDataType;
import ghidra.program.model.data.Category;
import ghidra.program.model.data.CategoryPath;
import ghidra.program.model.data.Composite;
import ghidra.program.model.data.DataTypeConflictHandler;
import ghidra.program.model.data.DataTypePath;
import ghidra.program.model.data.DefaultDataType;
import ghidra.program.model.data.DoubleDataType;
import ghidra.program.model.data.EnumDataType;
import ghidra.program.model.data.FloatDataType;
import ghidra.program.model.data.FunctionDefinition;
import ghidra.program.model.data.Pointer;
import ghidra.program.model.data.PointerDataType;
import ghidra.program.model.data.Structure;
import ghidra.program.model.data.StructureDataType;
import ghidra.program.model.data.TypeDef;
import ghidra.program.model.data.Undefined;
import ghidra.program.model.data.VoidDataType;
import ghidra.program.model.listing.Function.FunctionUpdateType;
import ghidra.program.model.listing.Parameter;
import ghidra.program.model.listing.ParameterImpl;
import ghidra.program.model.listing.Variable;
import ghidra.program.model.listing.VariableStorage;
import ghidra.program.model.symbol.SourceType;
import ghidra.program.model.symbol.SymbolType;
import ghidra.util.Swing;
import ghidra.util.exception.CancelledException;
public class SyncBromaScript extends GhidraScript {
class Args extends InputParameters {
Platform platform;
List<Path> bromaFiles;
String gameVersion;
boolean importFromBroma;
boolean exportToBroma;
boolean setOptcall;
boolean syncMembers;
boolean syncEnums;
boolean fillStandardTypes;
public Args(ScriptWrapper wrapper, Path bindingsDir) throws Exception {
this.run(wrapper, bindingsDir);
}
@Override
protected String title() {
return "Sync Bindings to/from Broma";
}
@Override
protected String description() {
return
"Import addresses & signatures from Broma, and add new ones " +
"from the current project to it.\n\n" +
"Note that it is recommended to save your Ghidra project before " +
"running the script, so if it messes something up you can safely " +
"undo the mistake.\n\n" +
"You will need to manually git pull / push your local copy of the " +
"bindings repository!\n\n" +
"See the README for detailed explanations of all the options.";
}
@Override
protected void doAsk(Object... args) throws Exception {
var bindingsDir = (Path)args[0];
// Get all available bindings versions from the bindings directory
List<String> versions = new ArrayList<String>();
for (var file : Files.list(bindingsDir).toArray(Path[]::new)) {
if (Files.isDirectory(file)) {
var filename = file.getFileName().toString();
if (!filename.equals("include")) {
versions.add(filename);
}
}
}
// Put latest version at the top
Collections.reverse(versions);
var bromaFiles = new ArrayList<String>();
final var platforms = Arrays.asList(Platform.values()).stream().map(p -> p.getLongName()).toList();
var platform = wrapper.autoDetectPlatform().orElse(null).getLongName();
var isWindows = platform != null && platform.equals(Platform.WINDOWS32.getLongName());
this.choice("Target platform", platforms, platform, p -> this.platform = Platform.fromLongName(p));
this.choice("Game version", versions, v -> this.gameVersion = v);
this.bool("Import from Broma", b -> this.importFromBroma = b);
this.bool("Export to Broma", false, b -> this.exportToBroma = b);
this.bool("Set optcall & membercall", isWindows, b -> this.setOptcall = b);
this.bool("Sync members", b -> this.syncMembers = b);
this.bool("Sync enums", b -> this.syncEnums = b);
this.bool("Fill standard types", b -> this.fillStandardTypes = b);
this.waitForAnswers();
bromaFiles.add("Cocos2d.bro");
bromaFiles.add("Extras.bro");
bromaFiles.add("GeometryDash.bro");
if (this.platform == Platform.IOS) {
bromaFiles.add("FMOD.bro");
}
if (this.platform == Platform.MAC_ARM || this.platform == Platform.MAC_INTEL || this.platform == Platform.IOS) {
bromaFiles.add("Kazmath.bro");
}
this.bromaFiles = bromaFiles.stream()
.map(f -> Paths.get(bindingsDir.toString(), this.gameVersion, f))
.filter(Files::exists)
.toList();
if (!this.importFromBroma && !this.exportToBroma && !this.syncMembers && !this.syncEnums) {
throw new Error("Either importing from Broma, exporting to Broma, syncing members, or syncing enums has to be checked!");
}
}
}
ScriptWrapper wrapper;
Args args;
List<Broma> bromas = new ArrayList<Broma>();
public void run() throws Exception {
this.wrapper = new ScriptWrapper(this);
this.args = new Args(wrapper, wrapper.bindingsDir);
boolean useFunctions = (this.args.importFromBroma || this.args.exportToBroma) && (
this.args.platform == Platform.MAC_ARM || this.args.platform == Platform.MAC_INTEL || this.args.platform == Platform.IOS
);
for (var bro : this.args.bromaFiles) {
this.bromas.add(new Broma(bro, args.platform, useFunctions));
}
wrapper.fillStandardTypes = this.args.fillStandardTypes;
// Read classes
wrapper.classes.addAll(this.bromas.stream()
.map(b -> b.classes.stream().map(c -> c.name.value).toList())
.flatMap(List::stream)
.toList());
wrapper.printfmt("Found {0} classes in Broma", wrapper.classes.size());
if (useFunctions) {
// Read functions
wrapper.functions.addAll(this.bromas.stream()
.map(b -> b.functions.stream().map(f -> f.getName()).toList())
.flatMap(List::stream)
.toList());
wrapper.printfmt("Found {0} functions in Broma", wrapper.functions.size());
}
// Read enums
var enumPath = Paths.get(wrapper.bindingsDir.toString(), "include", "Geode", "Enums.hpp");
if (Files.exists(enumPath)) {
for (var line : Files.readAllLines(enumPath)) {
if (line.startsWith("enum class")) {
wrapper.enums.add(line.split(" ")[2]);
}
}
}
wrapper.printfmt("Found {0} enums in Broma", wrapper.enums.size());
wrapper.updateTypeDatabase(args.platform);
// Do the imports and exports and members
if (this.args.importFromBroma) {
this.handleImport();
}
if (this.args.syncMembers) {
this.handleImportMembers();
}
if (this.args.syncEnums) {
this.handleImportEnums();
}
if (this.args.exportToBroma) {
this.handleExport();
if (this.args.syncMembers) {
this.handleExportMembers();
}
// Save results
wrapper.printfmt("Saving Broma files...");
for (var bro : this.bromas) {
bro.save();
}
}
}
enum SignatureImport {
NOCHANGES,
ADDED_MERGED,
UPDATED,
ADDED;
public SignatureImport promoted(SignatureImport to) {
if (this.ordinal() < to.ordinal()) {
return to;
}
else {
return this;
}
}
}
boolean overwriteAll = false;
ArrayList<String> overwriteList = new ArrayList<String>();
boolean mergeAll = false;
ArrayList<String> mergeList = new ArrayList<String>();
private SignatureImport importSignatureFromBroma(Address addr, Broma.Function fun, boolean skipTodo) throws Exception {
final var name = fun.getName();
final var className = fun.parent != null ? fun.parent.name.value : null;
final var fullName = className != null ? className + "::" + name : name;
final var listing = currentProgram.getListing();
var status = SignatureImport.NOCHANGES;
// Get the function defined at the address, or create one
var data = listing.getFunctionAt(addr);
if (data == null) {
status = status.promoted(SignatureImport.ADDED);
data = createFunction(addr, name);
if (data == null) {
throw new Error(MessageFormat.format(
"Unable to create a function at address {0} (offset 0x{1}, function {2})",
addr, fun.platformOffset.get().value, fullName
));
}
if (className != null) {
data.setParentNamespace(wrapper.addOrGetNamespace(className));
}
}
// Check if function already has an user-provided name - in this case, it might be merged
if (
data.getSymbol().getSource() == SourceType.USER_DEFINED &&
!data.getName(true).equals(fullName) &&
!(data.getComment() != null && data.getComment().contains("NOTE: Merged with " + fullName))
) {
if (overwriteAll) {
overwriteList.add(fullName);
}
else {
int choice = mergeAll ? 0 : askContinueConflict(
"Function has a different name",
List.of("Add to merged functions list", "Overwrite Ghidra name", "Overwrite all", "Merge all"),
"The function {0} at {1} from Broma already has the name " +
"{2} in Ghidra - is this function merged with that?",
fullName, Long.toHexString(addr.getOffset()), data.getName(true)
);
if (choice == 3) {
choice = 0;
mergeAll = true;
}
if (choice == 0) {
data.setComment(
(data.getComment() != null ? (data.getComment() + "\n") : "") +
"NOTE: Merged with " + fullName
);
wrapper.printfmt("Added {0} to merged function list for {1}", fullName, data.getName(true));
if (mergeAll) mergeList.add(fullName);
return SignatureImport.ADDED_MERGED;
}
overwriteAll = choice == 2;
}
}
if (data.getSymbol().getSource() != SourceType.USER_DEFINED) {
status = status.promoted(SignatureImport.ADDED);
}
if (currentProgram.getSymbolTable().getSymbol(name, addr, data.getParentNamespace()) == null) {
data.getSymbol().setName(name, SourceType.USER_DEFINED);
}
if (className != null) {
try {
data.setParentNamespace(wrapper.addOrGetNamespace(className));
}
catch (Exception e) {}
}
// Get the calling convention
final var conv = fun.getCallingConvention(args.platform);
final var bromaSig = wrapper.getBromaSignature(fun, args.platform, false);
// Check for mismatches between the Broma and Ghidra signatures
var signatureConflict = false;
for (var i = 0; i < data.getParameterCount(); i += 1) {
var param = data.getParameter(i);
// We only care about mismatches against user-defined params
if (param.getSource() != SourceType.USER_DEFINED) {
continue;
}
// More params in Ghidra is automatic signature mismatch
if (i >= bromaSig.parameters.size()) {
signatureConflict = true;
}
else {
var bromaParam = bromaSig.parameters.get(i);
if (
!param.getDataType().isEquivalent(bromaParam.getDataType()) ||
(
param.getName() != null && bromaParam.getName() != null &&
!param.getName().equals(bromaParam.getName())
)
) {
signatureConflict = true;
}
// Keep existing Ghidra name for args without names in Broma (Making sure to not include any duplicates)
else if (
bromaParam.getName() == null && param.getName() != null &&
!bromaSig.parameters.subList(0, i).stream().anyMatch(p -> p.getName() != null && p.getName().equals(param.getName()))
) {
bromaParam.setName(param.getName(), SourceType.USER_DEFINED);
}
}
}
if (data.getReturn().getSource() == SourceType.USER_DEFINED && bromaSig.returnType.isPresent()) {
if (!data.getReturnType().isEquivalent(bromaSig.returnType.get().getDataType())) {
signatureConflict = true;
}
}
// Destructor signatures are weird
if (fun.destructor != null) {
signatureConflict = false;
}
if (signatureConflict) {
if (!askContinueConflict(
"Signature doesn't match",
"Ghidra has a function signature {0} that doesn't match Broma's signature {1} - do you want to override it?",
new Signature(data.getReturn(), Arrays.asList(data.getParameters())),
bromaSig
)) {
return status;
}
status = status.promoted(SignatureImport.UPDATED);
}
var shouldReorderParams =
(conv == CConv.MEMBERCALL || conv == CConv.OPTCALL) &&
// Only do manual storage if there's actually a need for it
bromaSig.parameters.stream().anyMatch(p ->
p.getDataType() instanceof Composite ||
p.getDataType() instanceof FloatDataType
);
FunctionUpdateType updateType;
// Manual storage for custom calling conventions
if (shouldReorderParams) {
if (!this.args.setOptcall) {
updateType = FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS;
wrapper.printfmt(
"Warning: not handling optcall/membercall for {0} - " +
"parameter order / registers will be wrong!",
fullName
);
}
else {
updateType = FunctionUpdateType.CUSTOM_STORAGE;
var reorderedParams = new ArrayList<Variable>(bromaSig.parameters);
// Thanks stable sort <3
reorderedParams.sort((a, b) -> {
final var aIs = a.getDataType() instanceof Composite;
final var bIs = b.getDataType() instanceof Composite;
if (aIs && bIs) return 0;
if (aIs) return 1;
if (bIs) return -1;
return 0;
});
// First stack offset is 0x4 (0x0 is for return address)
var stackOffset = 0x4;
for (var i = 0; i < bromaSig.parameters.size(); i += 1) {
var param = reorderedParams.get(i);
final var type = param.getDataType();
VariableStorage storage;
if (i < 4 && type instanceof AbstractFloatDataType) {
// (p)rocessor (reg)ister
String preg = null;
if (type instanceof FloatDataType) {
preg = "XMM" + i + "_Da";
}
else if (type instanceof DoubleDataType) {
preg = "XMM" + i + "_Qa";
}
else {
throw new Error(
"Parameter has type " + type.toString() +
", which is floating-point type but has an unknown register location"
);
}
storage = new VariableStorage(currentProgram, currentProgram.getRegister(preg));
}
else {
if (i == 0 && !(type instanceof Composite)) {
storage = new VariableStorage(currentProgram, currentProgram.getRegister("ECX"));
}
else if (conv == CConv.OPTCALL && i == 1 && !(type instanceof Composite)) {
storage = new VariableStorage(currentProgram, currentProgram.getRegister("EDX"));
}
else {
if (type.isNotYetDefined()) {
wrapper.printfmt(
"Warning: function {0} has parameter {1} of an undefined " +
"struct type - you will need to manually fix this later!",
fullName, param.getName()
);
}
storage = new VariableStorage(currentProgram, stackOffset, type.getLength());
// https://github.com/geode-sdk/TulipHook/blob/main/src/convention/WindowsConvention.cpp#L69-L70
stackOffset += (type.getLength() + 3) / 4 * 4;
}
}
param.setDataType(type, storage, true, SourceType.USER_DEFINED);
}
}
}
// Use dynamic storage for calling conventions Ghidra knows
else {
updateType = FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS;
}
// Check for already-existing parameter names
for (var existingParam : data.getParameters()) {
for (var bromaParam : bromaSig.parameters) {
if (!existingParam.isAutoParameter() && existingParam.getName() != null && existingParam.getName().equals(bromaParam.getName())) {
existingParam.setName(null, SourceType.USER_DEFINED);
}
}
}
var conventionName = conv.getGhidraName();
if (bromaSig.returnsStruct && bromaSig.memberFunction && (args.platform == Platform.ANDROID32 || args.platform == Platform.MAC_INTEL)) {
conventionName = args.platform == Platform.MAC_INTEL ? "__stdcall" : "__cdecl";
}
else if (bromaSig.memberFunction && wrapper.offsets.get(addr.getOffset()) != null) {
conventionName = "__fastcall";
}
// Apply new signature
Variable returnType = bromaSig.returnType.orElse(null);
if (skipTodo && fun.returnType.isPresent() && fun.returnType.get().name.value.contains("TodoReturn")) returnType = data.getReturn();
try {
data.updateFunction(
conventionName,
returnType,
updateType,
true,
SourceType.USER_DEFINED,
bromaSig.parameters.toArray(Variable[]::new)
);
} catch (Exception e) {
throw new Error("Died on: " + fullName + " with " + e.getMessage());
}
// Fix the this parameter for member functions
if (bromaSig.memberFunction && wrapper.offsets.get(addr.getOffset()) == null) {
var firstParam = data.getParameter(0);
var firstType = firstParam.getDataType();
if (firstParam.getName().equals("this") && firstType instanceof Pointer && ((Pointer)firstType).getDataType() instanceof VoidDataType) {
var newConvention = "__cdecl";
if (args.platform == Platform.WINDOWS32 || args.platform == Platform.WINDOWS64) {
newConvention = "__fastcall";
}
else if (args.platform == Platform.MAC_INTEL) {
newConvention = "__stdcall";
}
try {
data.updateFunction(
newConvention,
returnType,
updateType,
true,
SourceType.USER_DEFINED,
bromaSig.parameters.toArray(Variable[]::new)
);
} catch (Exception e) {
throw new Error("Died on: " + fullName + " with " + e.getMessage());
}
}
}
// Set struct return storage for ARM64
if (bromaSig.returnsStruct && (args.platform == Platform.ANDROID64 || args.platform == Platform.MAC_ARM || args.platform == Platform.IOS)) {
var newParams = new ArrayList<Parameter>(List.of(data.getParameters()));
var foundReturn = newParams.stream().filter(p -> p.getName() != null && p.getName().equals("__return")).findFirst();
if (foundReturn.isPresent()) {
foundReturn.get().setName(null, SourceType.USER_DEFINED);
}
newParams.add(0, new ParameterImpl(
"__return",
data.getReturnType(),
new VariableStorage(currentProgram, currentProgram.getRegister("x8")),
currentProgram,
SourceType.USER_DEFINED
));
try {
data.updateFunction(
"__cdecl",
returnType,
FunctionUpdateType.CUSTOM_STORAGE,
true,
SourceType.USER_DEFINED,
newParams.toArray(Variable[]::new)
);
} catch (Exception e) {
throw new Error("Died on: " + fullName + " with " + e.getMessage());
}
data.setReturn(data.getReturnType(), new VariableStorage(currentProgram, currentProgram.getRegister("x0")), SourceType.USER_DEFINED);
}
// Set return type storage for custom cconvs
if (shouldReorderParams && bromaSig.returnType.isPresent()) {
var ret = bromaSig.returnType.get();
final var type = ret.getDataType();
VariableStorage storage;
if (type instanceof AbstractFloatDataType) {
// (p)rocessor (reg)ister
String preg = null;
if (type instanceof FloatDataType) {
preg = "XMM0_Da";
}
else if (type instanceof DoubleDataType) {
preg = "XMM0_Qa";
}
else {
throw new Error(
"Parameter has type " + type.toString() +
", which is floating-point type but has an unknown register location"
);
}
storage = new VariableStorage(currentProgram, currentProgram.getRegister(preg));
}
else {
if (ret instanceof VoidDataType) {
storage = VariableStorage.VOID_STORAGE;
}
else {
storage = new VariableStorage(currentProgram, currentProgram.getRegister("EAX"));
}
}
data.setReturn(type, storage, SourceType.USER_DEFINED);
}
return status;
}
private void handleImport() throws Exception {
wrapper.printfmt("Loading addresses from Bindings...");
var importedAddCount = 0;
var importedUpdateCount = 0;
var symbolTable = currentProgram.getSymbolTable();
var pointerSize = currentProgram.getDataTypeManager().getDataOrganization().getPointerSize();
for (var bro : bromas) {
wrapper.printfmt("Reading {0}...", bro.path.getFileName());
for (var cls : bro.classes) {
// CCLightning is in the Geometry Dash binary, but it is only in Cocos2d.bro
if (
(args.platform == Platform.WINDOWS32 || args.platform == Platform.WINDOWS64) &&
((cls.name.value.startsWith("cocos2d::") && !cls.name.value.equals("cocos2d::CCLightning")) || cls.name.value.startsWith("pugi::"))
) {
continue;
}
// Get class adjustments
if (args.platform == Platform.WINDOWS32 || args.platform == Platform.WINDOWS64) {
for (var metaPtr : symbolTable.getSymbols("vftable_meta_ptr", wrapper.addOrGetNamespace(cls.name.value))) {
var objectLocator = args.platform == Platform.WINDOWS64 ? getLong(metaPtr.getAddress()) : getInt(metaPtr.getAddress());
var offset = getInt(toAddr(objectLocator + 4));
var vftableData = currentProgram.getListing().getDataAt(metaPtr.getAddress().add(8));
var vftableType = vftableData != null ? vftableData.getDataType() : null;
if (vftableType != null && offset > 0) {
for (var i = 0; i < vftableType.getLength(); i += pointerSize) {
var address = metaPtr.getAddress().add(i + 8);
wrapper.offsets.put(args.platform == Platform.WINDOWS64 ? getLong(address) : getInt(address), offset);
}
}
}
}
for (var fun : cls.functions) {
var name = fun.getName();
var className = cls.name.value;
var fullName = className + "::" + name;
// Only add functions that have an offset on this platform
if (fun.platformOffset.isEmpty()) {
continue;
}
var offset = Long.parseLong(fun.platformOffset.get().value, 16);
if (offset == Broma.PLACEHOLDER_ADDR) {
continue;
}
var addr = currentProgram.getImageBase().add(offset);
switch (importSignatureFromBroma(addr, fun, false)) {
case ADDED: {
importedAddCount += 1;
wrapper.printfmt("Added {0} at {1}", fullName, Long.toHexString(addr.getOffset()));
} break;
case UPDATED: {
importedUpdateCount += 1;
wrapper.printfmt("Updated {0} at {1}", fullName, Long.toHexString(addr.getOffset()));
} break;
default: break;
}
}
wrapper.offsets.clear();
}
for (var fun : bro.functions) {
// Only add functions that have an offset on this platform
if (fun.platformOffset.isEmpty()) {
continue;
}
var offset = Long.parseLong(fun.platformOffset.get().value, 16);
if (offset == Broma.PLACEHOLDER_ADDR) {
continue;
}
var addr = currentProgram.getImageBase().add(offset);
switch (importSignatureFromBroma(addr, fun, false)) {
case ADDED: {
importedAddCount += 1;
wrapper.printfmt("Added {0} at {1}", fun.getName(), Long.toHexString(addr.getOffset()));
} break;
case UPDATED: {
importedUpdateCount += 1;
wrapper.printfmt("Updated {0} at {1}", fun.getName(), Long.toHexString(addr.getOffset()));
} break;
default: break;
}
}
}
wrapper.printfmt("Added {0} functions & updated {1} functions from Broma", importedAddCount, importedUpdateCount);
if (overwriteList.size() > 0) {
DockingWindowManager.showDialog(null, new MultiLineMessageDialog(
"Overwrite Summary",
"There were " + overwriteList.size() + " functions overwritten automatically.",
String.join("\n", overwriteList),
MultiLineMessageDialog.INFORMATION_MESSAGE,
false
));
}
else if (mergeList.size() > 0) {
DockingWindowManager.showDialog(null, new MultiLineMessageDialog(
"Merge Summary",
"There were " + mergeList.size() + " functions merged automatically.",
String.join("\n", mergeList),
MultiLineMessageDialog.INFORMATION_MESSAGE,
false
));
}
}
private void handleExport() throws Exception {
wrapper.printfmt("Adding new addresses to Bindings...");
var exportedAddrCount = 0;
var exportedTypeCount = 0;
final var table = currentProgram.getSymbolTable();
var clsIter = table.getClassNamespaces();
while (clsIter.hasNext()) {
var cls = clsIter.next();
// Skip imported classes
if (cls.isExternal() || cls.isLibrary()) {
continue;
}
// Skip any non-GD or non-Cocos classes
if (cls.getName(true).matches(".*(switch|llvm|tinyxml2|<|__|fmt|std::|pugi|typeinfo).*")) {
continue;
}
var bromaClass = this.getTargetClassInBroma(cls.getName(true));
if (bromaClass == null) {
continue;
}
Broma broma = bromaClass.broma;
for (var child : table.getChildren(cls.getSymbol())) {
// Skip non-functions
if (child.getSymbolType() != SymbolType.FUNCTION) {
continue;
}
final var fun = currentProgram.getListing().getFunctionAt(child.getAddress());
final var ghidraOffset = child.getProgramLocation().getAddress()
.subtract(currentProgram.getImageBase());
final var fullName = child.getName(true);
final var name = child.getName();
/*if(fullName.contains("~")) {
continue;
}*/
var bromaFuns = bromaClass.getFunctions(name);
if (bromaFuns.isEmpty()) {
wrapper.printfmt("Warning: function {0} not found", fullName);
continue;
}
Broma.Function bromaFun = null;
if (bromaFuns.size() > 1) {
// Try to auto-detect overload
// For this to be possible, every arg must match type exactly
tryMatchFun:
for (var tryMatch : bromaFuns) {
var sig = wrapper.getBromaSignature(tryMatch, args.platform, false);
var paramCount = fun.getParameterCount();
if (paramCount != sig.parameters.size()) {
continue tryMatchFun;
}
for (var i = 0; i < paramCount; i += 1) {
var param = fun.getParameter(i);
var ghidraDataType = param.getDataType();
var ghidraPointerDataType = ghidraDataType;
if (ghidraDataType instanceof Pointer) {
ghidraPointerDataType = ((Pointer)ghidraDataType).getDataType();
}
if (ghidraDataType instanceof TypeDef) {
ghidraDataType = ((TypeDef)ghidraDataType).getBaseDataType();
}
var bromaDataType = sig.parameters.get(i).getDataType();
if (
!ghidraDataType.isEquivalent(bromaDataType) &&
!ghidraPointerDataType.isEquivalent(bromaDataType)
) {
wrapper.printfmt(
"types {0} and {1} are not equal ({2} != {3})",
ghidraDataType.getDisplayName(),
bromaDataType.getDisplayName(),
ghidraDataType.getClass().getName(),
bromaDataType.getClass().getName()
);
continue tryMatchFun;
}
}
// Found a match!
bromaFun = tryMatch;
break;
}
// If no match found, ask for manual resolution
if (bromaFun == null) {
bromaFun = bromaFuns.get(askChoiceBetter(
"Select overload",
bromaFuns.stream()
.map(f -> f.getName() + "(" +
String.join(
", ", f.params.stream()
.map(p -> p.toString())
.toArray(String[]::new)
) +
")"
)
.toList(),
"Function <code>{0}</code> has multiple overloads, and the correct one couldn''t be " +
"inferred from the Ghidra arguments. Please select the correct one for " +
"address {1}." +
"<br><b>Signature at address</b>: {2}" +
"<br><em>If you need to cancel the script to check, make sure to manually set the " +
"parameter types so next time the overload is automatically detected!</em>",
fullName, fun.getEntryPoint(),
new Signature(fun.getReturn(), List.of(fun.getParameters()))
));
}
}
else {
bromaFun = bromaFuns.get(0);
}
// Update return type if Ghidra has an user-defined type and
// Broma has TodoReturn
if (
bromaFun.returnType.isPresent() && bromaFun.returnType.get().name.value.contains("TodoReturn") &&
fun.getReturn().getSource() == SourceType.USER_DEFINED
) {
broma.addPatch(bromaFun.returnType.get().range, fun.getReturnType().getDisplayName());
exportedTypeCount += 1;
}
// Get the function signature from Broma
importSignatureFromBroma(child.getAddress(), bromaFun, true);
// Export parameter names
int skipCount = 0;
for (var i = 0; i < fun.getParameterCount() && (i - skipCount) < bromaFun.params.size(); i += 1) {
var param = fun.getParameter(i);
if (param.getName() != null && param.getName().matches("(this|__return)") || param.isAutoParameter()) {
skipCount += 1;
continue;
}
var bromaParam = bromaFun.params.get(i - skipCount);
if (
param.getName() != null &&
!param.getName().matches("(param_[0-9]+|int|float|bool|void|char|const)") &&
bromaParam.nameInsertionPoint.isPresent()
) {
broma.addPatch(bromaParam.nameInsertionPoint.get().range, " " + param.getName());
}
}
// Add address
if (bromaFun.platformOffset.isPresent()) {
var bromaOffset = Long.parseLong(bromaFun.platformOffset.get().value, 16);
if (bromaOffset != Broma.PLACEHOLDER_ADDR && bromaOffset != ghidraOffset) {
if (!askContinueConflict(
"Address mismatch",
"Function {0} has the address 0x{1} in the Broma but the address 0x{2} in Ghidra - do you want to override the Broma's address?",
fullName, Long.toHexString(bromaOffset), Long.toHexString(ghidraOffset)
)) {
continue;
}
exportedAddrCount += 1;
broma.addPatch(bromaFun.platformOffset.get().range, String.format("%x", ghidraOffset));
}
}
else if (bromaFun.platformOffsetAddPoint.isPresent()) {
broma.addPatch(
bromaFun.platformOffsetAddPoint.get(),
String.format(", %s 0x%x", args.platform.getShortName(), ghidraOffset)
);
exportedAddrCount += 1;
}
else if (bromaFun.platformOffsetInsertPoint.isPresent()) {
broma.addPatch(
bromaFun.platformOffsetInsertPoint.get().range,
String.format(" = %s 0x%x", args.platform.getShortName(), ghidraOffset)
);
exportedAddrCount += 1;
}
else {
wrapper.printfmt("Warning: function {0} is inlined in Broma - refusing to add address", fullName);
}
}
}
wrapper.printfmt("Exported {0} addresses & {1} return types to Broma", exportedAddrCount, exportedTypeCount);
}
HashMap<String, List<String>> basesMap = new HashMap<>();
HashMap<String, Broma.Class> classCache = new HashMap<>();
HashSet<String> visitedClasses = new HashSet<>();
HashMap<String, Integer> classPads = new HashMap<>();
int globalOverwriteStatus = 0;
private void importClass(Broma.Class cls) throws Exception {
if (cls == null) return;
final var fullName = cls.name.value;
if (visitedClasses.contains(fullName)) return;
visitedClasses.add(fullName);
var basesString = cls.bases.isPresent() ? cls.bases.get().value.substring(1) : "";
if (fullName.equals("UILayer")) basesString += ", cocos2d::CCKeyboardDelegate";
var basesList = Arrays.stream(basesString.split(",")).map(String::trim).toList();
var firstBase = basesList.size() > 0 ? basesList.get(0) : "";
var needsClear = (!fullName.startsWith("cocos2d::") || fullName.equals("cocos2d::CCLightning")) &&
basesList.size() == 1 && firstBase.startsWith("cocos2d::");
basesMap.put(fullName, basesList);
if (!firstBase.isEmpty() && !visitedClasses.contains(firstBase)) {
importClass(classCache.get(firstBase));
}
var isBaseless = cls.bases.isEmpty() && !cls.functions.stream().anyMatch(f -> {
return f.dispatch.isPresent() && f.dispatch.get().value.equals("virtual");
});
final var manager = currentProgram.getDataTypeManager();
final var pointerSize = manager.getDataOrganization().getPointerSize();
var category = new CategoryPath("/ClassDataTypes");
String name = null;
for (var part : fullName.split("::")) {
category = category.extend(part);
name = part;
}
// Make sure the category exists
wrapper.createCategoryAll(category);
if (!cls.members.isEmpty()) {
final var classDataTypePath = new DataTypePath(category, name + (isBaseless ? "" : "_data"));
var classMembers = manager.getDataType(classDataTypePath);
if (classMembers == null || !(classMembers instanceof Structure)) {
// Create data members struct
classMembers = manager.getCategory(category).addDataType(
new StructureDataType(name + (isBaseless ? "" : "_data"), 0),
classMembers == null ? DataTypeConflictHandler.DEFAULT_HANDLER : DataTypeConflictHandler.REPLACE_HANDLER
);
}
wrapper.printfmt("Importing {0} members for {1}", cls.members.size(), fullName);
var classDataMembers = (Structure)classMembers;
// Disable packing
classDataMembers.setPackingEnabled(false);
if (needsClear) {
classDataMembers.setLength(0);
}
// Delete any padding at the end of the struct
// (so if the struct has shrunk in broma, we refit it properly)
while (!classDataMembers.isZeroLength()) {
var comp = classDataMembers.getComponent(classDataMembers.getNumComponents() - 1);
if (comp.getDataType() instanceof DefaultDataType) {
classDataMembers.delete(classDataMembers.getNumComponents() - 1);
}
else {
break;
}
}
var initialOffset = 0;
if (args.platform != Platform.WINDOWS32 && args.platform != Platform.WINDOWS64 && !firstBase.isEmpty() && classCache.containsKey(firstBase)) {
var firstBaseCategory = new CategoryPath("/ClassDataTypes");
String firstBaseData = null;
for (var part : firstBase.split("::")) {
firstBaseCategory = firstBaseCategory.extend(part);
firstBaseData = part;
}
var firstBaseType = manager.getDataType(new DataTypePath(firstBaseCategory, firstBaseData + "_data"));
if (firstBaseType != null) {
initialOffset = (firstBaseType.getLength() - classPads.getOrDefault(firstBase, 0)) % pointerSize;
classPads.put(fullName, initialOffset);
if (classDataMembers.getNumComponents() > 0) {
var componentOffset = classDataMembers.getComponent(0).getOffset();
if (componentOffset < initialOffset) {
var missingArea = initialOffset - componentOffset;
for (int i = 0; i < missingArea; i++) {
classDataMembers.insertAtOffset(componentOffset, DefaultDataType.dataType, 1);
}
}
}
}
}
var offset = initialOffset;
var overwriteStatus = globalOverwriteStatus;
for (var mem : cls.members) {
int length;
var memName = mem.name.isPresent() ? mem.name.get().value : null;
if (memName != null) {
// Placeholder member for a doubly inherited virtual table
if (fullName.equals("UILayer") && memName.equals("m_stupidDelegate")) {
continue;
}
final var memType = wrapper.addOrGetType(mem.type.get(), args.platform);
boolean isPointer = memType instanceof Pointer || memType instanceof FunctionDefinition;
if (memType instanceof Structure) {
var typeName = memType.getName();
if (classCache.containsKey(typeName) && !visitedClasses.contains(typeName)) {
importClass(classCache.get(typeName));
}
}
length = isPointer ? pointerSize : memType.getLength();
int alignment = isPointer ? length : memType.getAlignment();
if (memType instanceof FunctionDefinition && args.platform != Platform.WINDOWS32 && args.platform != Platform.WINDOWS64) {
length *= 2;
}
offset = (offset + alignment - 1) / alignment * alignment;
}
else {
if (mem.paddings.containsKey(args.platform)) {
length = mem.paddings.get(args.platform);
}
else {
length = 0;
}
}
int classLength = classDataMembers.isZeroLength() ? 0 : classDataMembers.getLength();
if (offset + length > classLength) {
classDataMembers.growStructure(offset + length - classLength);
}