-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindBRUTESymbols.java
More file actions
756 lines (690 loc) · 30.9 KB
/
Copy pathFindBRUTESymbols.java
File metadata and controls
756 lines (690 loc) · 30.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
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import ghidra.app.decompiler.DecompInterface;
import ghidra.app.decompiler.DecompileResults;
import ghidra.app.decompiler.ClangTokenGroup;
import ghidra.app.decompiler.ClangToken;
import ghidra.app.decompiler.ClangStatement;
import ghidra.app.decompiler.DecompiledFunction;
import ghidra.app.decompiler.ClangNode;
import ghidra.program.model.lang.OperandType;
import ghidra.program.model.lang.Register;
import ghidra.program.model.pcode.PcodeOp;
import ghidra.program.model.pcode.Varnode;
import ghidra.app.script.GhidraScript;
import ghidra.program.model.data.StringDataInstance;
import ghidra.program.model.listing.Data;
import ghidra.program.model.listing.Function;
import ghidra.program.model.listing.Listing;
import ghidra.program.model.listing.Instruction;
import ghidra.program.model.listing.FunctionManager;
import ghidra.program.model.symbol.ReferenceManager;
import ghidra.program.model.symbol.ReferenceIterator;
import ghidra.program.model.symbol.Reference;
import ghidra.program.model.symbol.Symbol;
import ghidra.program.model.symbol.SourceType;
import ghidra.program.model.address.Address;
import ghidra.program.model.data.DataUtilities.ClearDataMode;
import ghidra.program.model.data.DataUtilities;
import ghidra.program.model.mem.Memory;
import ghidra.program.util.DefinedDataIterator;
import ghidra.program.model.data.UnicodeDataType;
public class FindBRUTESymbols extends GhidraScript {
private Address clsRegisterAddr = null;
private Function analyzingFunction = null;
private DecompInterface decompInterface = null;
@Override
protected void run() throws Exception {
decompInterface = new DecompInterface();
decompInterface.openProgram(currentProgram);
findStrings();
findClasses();
decompInterface = null;
clsRegisterAddr = null;
analyzingFunction = null;
}
private Function _getFunctionAt(String address) throws Exception {
FunctionManager funman = currentProgram.getFunctionManager();
Address addr = currentProgram.parseAddress(address)[0];
return funman.getFunctionAt(addr);
}
private Function _getFunctionContaining(Address address) throws Exception {
return currentProgram.getFunctionManager().
getFunctionContaining(address);
}
// walk backwards from the branch instruction to find some arguments
// (the "correct" way is to walk through the syntax tree to find what
// was actually assigned to the variables but this is easier)
private Address findArgAddress(Address callAddress, Address minAddress, String operandName) throws Exception {
Address addr = callAddress;
boolean stackTarget = operandName.contains("sp");
while (Address.min(addr, minAddress).equals(minAddress)) {
Instruction instr = currentProgram.getListing().getInstructionAt(addr);
addr = addr.subtract(4);
if (instr == null) {
// instr should never be null given a valid minAddress
continue;
}
if (!instr.getMnemonicString().equals(stackTarget ? "str" : "add")) {
// not interested in this instruction
continue;
}
int opType = instr.getOperandType(0);
if ((opType & OperandType.ADDRESS) == 0) {
// operand must have an address reference
// ...we're looking for an address
continue;
}
if (stackTarget) {
// second operand must be a specific stack pointer offset
String target = instr.getDefaultOperandRepresentation(1);
if (!target.equals(operandName)) {
// different argument
continue;
}
}
else {
// first operand must be a specific register
String reg = instr.getRegister(0).getName();
if (!reg.equals(operandName)) {
// different argument
continue;
}
}
Reference[] refs = instr.getOperandReferences(0);
if (refs == null || refs.length <= 0) {
// this should never happen ?
continue;
}
// we found the address
// (may not be a valid data/function/string, but that's up to the caller to check)
return refs[0].getToAddress();
}
// did not find anything
return null;
}
private Data getDataAtAddr(Address addr, boolean forceUnicode) throws Exception {
if (addr != null) {
Data data = currentProgram.getListing().getDataAt(addr);
if (!forceUnicode) {
return data;
}
if (data != null) {
StringDataInstance sdi = StringDataInstance.getStringDataInstance(data);
if (sdi == null || sdi == StringDataInstance.NULL_INSTANCE) {
// convert data at this address into unicode string data type
int length = 2;
Address iter = addr;
while (currentProgram.getMemory().getShort(iter) != 0) {
iter = iter.add(2);
length += 2;
}
data = DataUtilities.createData(currentProgram,
addr, UnicodeDataType.dataType, length,
DataUtilities.ClearDataMode.CLEAR_ALL_DEFAULT_CONFLICT_DATA);
}
}
return data;
}
return null;
}
public String getStringAtAddr(long addr) throws Exception {
Data data = getDataAtAddr(currentProgram.parseAddress("0x" + Long.toHexString(addr))[0], true);
return getStringFromDataSafe(data);
}
private Data findArgData(Address callAddress, Address minAddress, String registerName,
boolean forceUnicode) throws Exception
{
Address addr = findArgAddress(callAddress, minAddress, registerName);
return getDataAtAddr(addr, forceUnicode);
}
private Function findArgFunction(Address callAddress, Address minAddress, String registerName) throws Exception {
Address addr = findArgAddress(callAddress, minAddress, registerName);
if (addr != null) {
return currentProgram.getFunctionManager().getFunctionAt(addr);
}
return null;
}
private String getStringFromDataSafe(Data data) throws Exception {
if (data != null) {
StringDataInstance sdi = StringDataInstance.getStringDataInstance(data);
if (sdi != null && sdi != StringDataInstance.NULL_INSTANCE) {
return sdi.getStringValue();
}
}
return null;
}
private String findArgString(Address callAddress, Address minAddress, String registerName) throws Exception {
return getStringFromDataSafe(findArgData(callAddress, minAddress,
registerName, true));
}
private void findStrings() throws Exception {
// AllocConstString ==> 7100cc7c10
// BRUTE_Startup_CreateStrings ==> 71002862a0
// Get reference manager
ReferenceManager refman = currentProgram.getReferenceManager();
// Get function manager
FunctionManager funman = currentProgram.getFunctionManager();
// Get listing
Listing listing = currentProgram.getListing();
// String allocator function
Function allocStringFun = _getFunctionAt("0x7100cc7c10");
Address allocStringAddr = allocStringFun.getEntryPoint();
// Very long function called at startup that initializes constant System.String
// objects
Function initStringsFun = _getFunctionAt("0x71002862a0");
Address initStringsAddr = initStringsFun.getEntryPoint();
// Setup progress
ReferenceIterator ri = refman.getReferencesTo(allocStringAddr);
long refCount = 0;
for (Reference r : ri) {
++refCount;
}
monitor.initialize(refCount, "Finding strings...");
ri = refman.getReferencesTo(allocStringAddr);
for (Reference r : ri) {
monitor.checkCancelled();
monitor.increment();
Function from = _getFunctionContaining(r.getFromAddress());
if (from == null || from != initStringsFun) {
// only interested in calls from BRUTE_Startup_CreateStrings
continue;
}
// find unicode string that's being used to allocate this System.String
// e.g.) add x0 => u_--gui_710385eb3a ,x0 ,#0xb3a
Address addr = r.getFromAddress();
Data srcData = findArgData(addr, addr.subtract(36), "x0", true);
String srcStr = getStringFromDataSafe(srcData);
if (srcData == null || srcStr == null) {
continue;
}
// find the location where this System.String instance is placed
// e.g.) str x0 ,[x8 ]=> DAT_7104db7fa8
addr = r.getFromAddress().add(4);
Data targetData = null;
for (int i=0; i<9; ++i) {
Instruction instr = currentProgram.getListing().getInstructionAt(addr);
addr = addr.add(4);
if (instr == null) { // can instr be null?
continue;
}
if (!instr.getMnemonicString().equals("str")) {
continue;
}
//println("add instr");
int opType0 = instr.getOperandType(0);
//println("optype 0 = " + opType0);
if ((opType0 & OperandType.REGISTER) == 0) {
continue;
}
int opType1 = instr.getOperandType(1);
if ((opType1 & OperandType.ADDRESS) == 0) {
continue;
}
String reg = instr.getRegister(0).getName();
if (!reg.equals("x0")) {
continue;
}
Reference[] refs = instr.getOperandReferences(1);
if (refs == null || refs.length <= 0) {
continue;
}
Data data = currentProgram.getListing().getDataAt(refs[0].getToAddress());
if (data == null) {
continue;
}
targetData = data;
break;
}
if (targetData == null) {
continue;
}
println("str: " + srcStr.replaceAll("[\\n\\r]", "\\n"));
targetData.getPrimarySymbol().setName(
"StrObj_" + srcData.getPrimarySymbol().getName(),
SourceType.USER_DEFINED);
}
}
private void findClasses() throws Exception {
// Get reference manager
ReferenceManager refman = currentProgram.getReferenceManager();
// Get function manager
FunctionManager funman = currentProgram.getFunctionManager();
// Get listing
Listing listing = currentProgram.getListing();
// Get class register function
Function clsRegisterFun = _getFunctionAt("0x7100cb7c00");
clsRegisterAddr = clsRegisterFun.getEntryPoint();
ReferenceIterator ri = refman.getReferencesTo(clsRegisterAddr);
// Setup progress
long refCount = 0;
for (Reference r : ri) {
++refCount;
}
monitor.initialize(refCount, "...");
// Iterate over references
ri = refman.getReferencesTo(clsRegisterAddr);
for (Reference r : ri) {
monitor.checkCancelled();
monitor.increment();
Address fa = r.getFromAddress();
//println("from address: " + fa.toString());
Function f = funman.getFunctionContaining(fa);
if (f != null) {
monitor.setMessage(f.getName());
analyzingFunction = f;
DecompileResults res = decompInterface.decompileFunction(f, 0, monitor);
if (!res.decompileCompleted()) {
println("decompile failed: " + res.getErrorMessage());
continue;
}
ClangTokenGroup tokenGroup = res.getCCodeMarkup();
iterateNodes(tokenGroup);
}
}
}
private Function derefFunctionPtr(Address ptr) throws Exception {
FunctionManager funman = currentProgram.getFunctionManager();
Function fun = funman.getFunctionAt(ptr);
if (fun != null) {
return fun;
}
ReferenceManager refman = currentProgram.getReferenceManager();
Reference[] refs = refman.getReferencesFrom(ptr);
if (refs.length > 0) {
return funman.getFunctionAt(refs[0].getToAddress());
}
return null;
}
public void printPublic(String str) {
println(str);
}
public void checkCancelledPublic() throws Exception {
monitor.checkCancelled();
}
// Takes decompiled C code and reconstructs the buffer created by the code
//XXX: there's probably a better way to do this but having this pseudo c interpreter also works
private class InitSimulator {
// negative 64-bit values are used to index into simulator buffers
// positive 64-bit values are used to represent actual addresses within the code
// -3 ==> ArrayBuffer
private HashMap<Long, ByteBuffer> indexBufferMap;
// -3 ==> 0x1000
private HashMap<Long, Integer> indexBufferSizeMap;
// -4 ==> String
private HashMap<Long, String> indexStringMap;
// "puVar1" ==> 0x700212aa34
// "puVar2" ==> -3
private HashMap<String, Long> varValueMap;
// "puVar1" ==> 1 (undefined *)
// "puVar2" ==> 8 (undefined8 *)
// "puVar3" ==> 4 (undefined4 *)
private HashMap<String, Integer> varSizeMap;
private long indexIter;
private long lastBufferIndex;
private FindBRUTESymbols script;
public InitSimulator(FindBRUTESymbols script) {
this.script = script;
indexBufferMap = new HashMap<Long, ByteBuffer>();
varValueMap = new HashMap<String, Long>();
indexStringMap = new HashMap<Long, String>();
varSizeMap = new HashMap<String, Integer>();
indexBufferSizeMap = new HashMap<Long, Integer>();
indexIter = -1L;
lastBufferIndex = 0L;
}
public void simulate(String code) throws Exception {
String[] lines = code.split("[\\r?\\n]");
String line = "";
Pattern declPattern = Pattern.compile("^undefined([0-9]?) (\\*?)([0-9a-zA-Z]+)$");
Pattern allocPattern = Pattern.compile("\\((0?x?)([0-9a-fA-F]+)\\)");
Pattern complexLhsPattern = Pattern.compile("^\\*\\(undefined([0-9]?) \\*\\)\\(((?:\\(long\\))?)([a-zA-Z0-9]+) \\+ (0?x?[0-9a-fA-F]+)\\)$");
Pattern indexLhsPattern = Pattern.compile("^([a-zA-Z0-9]+)\\[(0?x?[0-9a-fA-F]+)\\]$");
for (String _line : lines) {
script.checkCancelledPublic();
if (_line.contains("}") || _line.contains("{")) {
// ignore function start/end
line = "";
continue;
}
line += _line.trim() + " ";
if (!_line.contains(";")) {
// wait until the entire line has been received
continue;
}
line = line.replace(";", "").trim().replaceAll(" +", " ");
//script.printPublic(line);
String[] assignment = line.split("\\=");
if (assignment.length == 1) {
// variable declaration?
// undefined8 *puVar1
Matcher matcher = declPattern.matcher(line);
if (matcher.find()) {
String sizeStr = matcher.group(1);
int size = 1;
if (!matcher.group(2).equals("*")) {
size = 0;
}
else if (sizeStr.length() != 0) {
size = Integer.parseInt(sizeStr, 10);
}
String name = matcher.group(3);
varSizeMap.put(name, size);
}
else if (!line.equals("return")) {
script.printPublic("==> W: decl pattern did not match: " + line);
}
}
else if (assignment.length == 2) while (true) {
assignment[0] = assignment[0].trim();
assignment[1] = assignment[1].trim();
Matcher matcher = allocPattern.matcher(assignment[1]);
if (matcher.find()) {
// allocation
// puVar1 = StandardAlloc(0x10)
String varname = assignment[0].trim();
String sizeStr = matcher.group(2);
long size;
if (matcher.group(1).equals("0x")) {
size = Long.parseLong(sizeStr, 16);
}
else {
size = Long.parseLong(sizeStr, 10);
}
long bufIndex = indexIter--;
varValueMap.put(varname, bufIndex);
ByteBuffer buf = ByteBuffer.allocate((int)size);
lastBufferIndex = bufIndex;
indexBufferSizeMap.put(bufIndex, (int)size);
indexBufferMap.put(bufIndex, buf);
break;
}
long rhsValue;
if (assignment[1].matches("[0-9]+")) {
// constant base10 assignment
// ... = 123
rhsValue = Long.parseLong(assignment[1], 10);
}
else if (assignment[1].matches("0x[0-9a-f]+")) {
// constant base16 assignment
// ... = 0xabc123
rhsValue = Long.decode(assignment[1]);
}
else if (Pattern.compile("_[0-9a-f]+$").matcher(assignment[1]).find()) {
// address/symbol assignment
// ... = FUN_70012abcd
String[] comps = assignment[1].split("_"); //XXX: inefficient
rhsValue = Long.parseLong(comps[comps.length-1], 16);
}
else if (assignment[1].matches("L?\".*\"")) {
// string assignment
// ... = L"IsAlive"
int first = assignment[1].indexOf("\"", 0);
int last = assignment[1].lastIndexOf("\"");
long strIndex = indexIter--;
String val = assignment[1].substring(first+1, last);
indexStringMap.put(strIndex, val);
rhsValue = strIndex;
}
else if (varValueMap.containsKey(assignment[1])) {
// assignment from another variable
// ... = puVar1
rhsValue = varValueMap.get(assignment[1]);
}
else {
script.printPublic("==> W: failed to find rhs: " + line);
break;
}
matcher = complexLhsPattern.matcher(assignment[0]);
long offset;
ByteBuffer buf = null;
int writeSize;
if (matcher.find()) {
// *(undefined8 *)((long)puVar3 + 0xabc) = ...
// 1 2 3 4
String addressVar = matcher.group(3);
if (!varValueMap.containsKey(addressVar)) {
script.printPublic("==> W: invalid addressVar: " + line);
break;
}
long bufIndex = varValueMap.get(addressVar);
if (!indexBufferMap.containsKey(bufIndex)) {
script.printPublic("==> W: invalid buffer index: " + bufIndex);
break;
}
int elemSize;
if (matcher.group(2).length() > 0) {
elemSize = 1;
}
else {
elemSize = varSizeMap.get(addressVar);
}
offset = elemSize * Long.decode(matcher.group(4));
writeSize = (matcher.group(1).length() > 0) ? Integer.parseInt(matcher.group(1)) : 1;
buf = indexBufferMap.get(bufIndex);
break;
}
else {
matcher = indexLhsPattern.matcher(assignment[0]);
String varname = null;
if (matcher.find()) {
// puVar3[0x123] = ...
// 1 2
varname = matcher.group(1);
offset = Long.decode(matcher.group(2));
}
else if (assignment[0].startsWith("*") && varValueMap.containsKey(assignment[0].substring(1))) {
// *puVar3 = ...
varname = assignment[0].substring(1);
offset = 0;
}
else if (varSizeMap.containsKey(assignment[0])) {
// puVar3 = ...
varValueMap.put(assignment[0], rhsValue);
break;
}
else {
script.printPublic("==> W: failed to find lhs: " + line);
break;
}
if (!varValueMap.containsKey(varname)) {
script.printPublic("==> W: invalid varname: " + line);
break;
}
long bufIndex = varValueMap.get(varname);
if (!indexBufferMap.containsKey(bufIndex)) {
script.printPublic("==> W: invalid buffer index: " + bufIndex);
break;
}
writeSize = varSizeMap.get(varname);
offset *= writeSize;
buf = indexBufferMap.get(bufIndex);
}
switch (writeSize) {
case 1: buf.putChar((int)offset, (char)rhsValue); break;
case 2: buf.putShort((int)offset, (short)rhsValue); break;
case 4: buf.putInt((int)offset, (int)rhsValue); break;
case 8: buf.putLong((int)offset, rhsValue); break;
default: script.printPublic("==> W: invalid writesize: " + writeSize);
}
break;
}
else {
script.printPublic("==> W: assignment.length > 2");
}
// reset line
line = "";
}
}
private long getLastBufferIndex() throws Exception {
return lastBufferIndex;
}
private ByteBuffer getBuffer(long index) throws Exception {
if (!indexBufferMap.containsKey(index)) {
return null;
}
return indexBufferMap.get(index);
}
private int getBufferSize(long index) throws Exception {
return indexBufferSizeMap.get(index);
}
private String getString(long index) throws Exception {
if (index > 0) {
return script.getStringAtAddr(index);
}
if (!indexStringMap.containsKey(index)) {
return null;
}
return indexStringMap.get(index);
}
}
private InitSimulator simulateInitFunction(Function fun) throws Exception {
DecompileResults res = decompInterface.decompileFunction(fun, 0, monitor);
if (!res.decompileCompleted()) {
println("decompile failed: " + res.getErrorMessage());
return null;
}
DecompiledFunction dec = res.getDecompiledFunction();
String code = dec.getC();
InitSimulator sim = new InitSimulator(this);
sim.simulate(code);
return sim;
}
private void analyzePropertyInitFunction(Function fun, String className) throws Exception {
//TODO
}
private void analyzeMethodInitFunction(Function fun, String className) throws Exception {
InitSimulator sim = simulateInitFunction(fun);
if (sim == null) {
return;
}
long lastBufIndex = sim.getLastBufferIndex();
if (lastBufIndex == 0L) {
return;
}
// each method is described by a 96 byte-long entry (8 * 12)
// the fields are as follows:
// +0x0 = method name (8 bytes, simulator string index or data address)
// +0x10 = return type getter (8 bytes, function address)
// +0x18 = method implementation (8 bytes, function address)
// +0x38 = parameter list (8 bytes, simulator buffer index)
ByteBuffer buf = sim.getBuffer(lastBufIndex);
int bufSize = sim.getBufferSize(lastBufIndex);
for (int i=0; i<bufSize-95; i += 96) {
String methodName = sim.getString(buf.getLong(i + 0x0));
long implAddr = buf.getLong(i + 0x18);
long paramBufIndex = buf.getLong(i + 0x38);
ByteBuffer paramBuf = sim.getBuffer(paramBufIndex);
if (methodName == null) {
continue;
}
Address implAddrObj = currentProgram.parseAddress("0x" + Long.toHexString(implAddr))[0];
Function implFun = derefFunctionPtr(implAddrObj);
if (implFun == null) {
continue;
}
String fullImplName = className + "$" + methodName;
//println("found method: " + fullImplName);
implFun.setName(fullImplName, SourceType.USER_DEFINED);
if (paramBuf != null) {
// each parameter is described by an 24 byte-long entry (8 * 3)
// the fields are as follows:
// +0x0 = method name (8 bytes, simulator string index or data address)
// +0x8 = type getter (8 bytes, function address)
int paramBufSize = sim.getBufferSize(paramBufIndex);
String[] params = new String[paramBufSize / 24];
for (int j=0; j<paramBufSize-23; j += 24) {
String paramName = sim.getString(paramBuf.getLong(j + 0x0));
if (paramName == null) {
break;
}
params[j/24] = paramName;
//println("param: " + paramName);
}
//TODO: set parameter names
}
}
}
private void analyzeDecoratorInitFunction(Function fun, String className) throws Exception {
//TODO
}
private void parseClangStatement(ClangStatement stmt) throws Exception {
// verify that this is the function call we're interested in
PcodeOp op = stmt.getPcodeOp();
int opcode = op.getOpcode();
if (opcode != PcodeOp.CALL && opcode != PcodeOp.CALLIND) {
return;
}
Varnode[] inputs = op.getInputs();
if (inputs.length != 37) {
return;
}
if (!inputs[0].getAddress().equals(clsRegisterAddr)) {
return;
}
// get method name
Address addr = stmt.getMaxAddress();
Address entryPoint = analyzingFunction.getEntryPoint();
String methodName = findArgString(addr, entryPoint, "x5");
if (methodName == null) {
return;
}
// get normalized method name (is this necessary?)
String normalized = methodName.replaceAll("[^a-zA-Z0-9]", "_");
// rename register function
analyzingFunction.setName("BRUTE_Register_Type_" + normalized, SourceType.USER_DEFINED);
//println("found: " + normalized);
// rename class getter function, if found
Function getTypeFun = derefFunctionPtr(inputs[35].getAddress());
if (getTypeFun != null) {
getTypeFun.setName("BRUTE_Get_Type_" + normalized, SourceType.USER_DEFINED);
}
// arg25 = class property metadata initializer
Function initProperties = findArgFunction(addr, entryPoint, "[sp, #0x80]");
if (initProperties != null) {
initProperties.setName("BRUTE_Init_Properties_" + normalized, SourceType.USER_DEFINED);
analyzePropertyInitFunction(initProperties, normalized);
}
// arg31 = class method metadata initializer (including getters and setters)
Function initMethods = findArgFunction(addr, entryPoint, "[sp, #0xb0]");
if (initMethods != null) {
initMethods.setName("BRUTE_Init_Methods_" + normalized, SourceType.USER_DEFINED);
analyzeMethodInitFunction(initMethods, normalized);
}
// arg33 = class decorator metadata initializer
Function initDecorators = findArgFunction(addr, entryPoint, "[sp, #0xc0]");
if (initDecorators != null) {
initDecorators.setName("BRUTE_Init_Decorators_" + normalized, SourceType.USER_DEFINED);
analyzeDecoratorInitFunction(initDecorators, normalized);
}
}
private void iterateNodes(ClangNode node) throws Exception {
if (node instanceof ClangStatement) {
ClangStatement stmt = (ClangStatement)node;
parseClangStatement(stmt);
}
for (int i=0; i<node.numChildren(); ++i) {
iterateNodes(node.Child(i));
}
}
}