-
Notifications
You must be signed in to change notification settings - Fork 2
/
disassembler.py
1791 lines (1569 loc) · 66.2 KB
/
disassembler.py
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
# This file is part of D-ARM
# Copyright (C) 2023 Yapeng Ye, [email protected]
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>
import copy
import gc
import heapq
import logging
import os
import struct
from collections import defaultdict
from binary import ARMBinary
from capstone import *
from capstone.arm import *
from capstone.arm64 import *
class NodeInst:
def __init__(self, inst=None):
self.inst = inst
self.type = None # A/T
self.size = 0
# self.succr1 = -1
# self.succr2 = -1
self.succr = list()
self.succr_data = list()
self.pred = list()
self.hint = 0
class NodeData:
def __init__(self):
self.type = 0 # default: 0 data; 1 unknown/inst #TODO check: now used for counting overlapped insts
self.accessed_inst = list()
self.hint = 0
class ARMDisassembler:
S_UNCOMMON_OP = -1
S_LIKE_DATA = -1
S_REG_REDEFINE = -10
S_CLOSE_TARGET = -10
S_COMMON_BASIC = 5
S_MOVW_MOVT = 10
S_CMP_CC = 1
HT_CF_CONVERGE = 1.0 / 65535.0
HT_CF_CROSS = 1.0 / 65535.0
HT_REG = 1.0 / 2 # 1.0 / 16.0
T_LSTM_DATA_MIN = 0.02 ## TODO: update
T_LSTM_DATA_AVE = 0.2
ADDR_SUCCR_VALID = 0.1
ADDR_SUCCR_PERFECT = 0.5
ADDR_DATA_VALID = 0.1
ADDR_DATA_PERFECT = 0.5
# TODO: use const from capstone
COMMON_INST_ID_32 = set(
[
75,
82,
2,
214,
17,
215,
413,
23,
13,
62,
205,
412,
93,
8,
423,
414,
424,
408,
15,
1,
225,
34,
425,
117,
68,
14,
11,
211,
92,
22,
227,
122,
91,
417,
84,
83,
21,
173,
202,
416,
241,
422,
421,
70,
242,
3,
259,
222,
261,
206,
407,
418,
59,
80,
231,
63,
81,
203,
60,
97,
10,
]
)
def __init__(self, filepath_binary, aarch=None, output_dir=None, verbose=False):
self.filepath_binary = filepath_binary
self.output_dir = output_dir
self.aarch = aarch
self.verbose = verbose
self.binary = ARMBinary(self.filepath_binary, aarch=self.aarch)
self.aarch = self.binary.aarch
self.sections = dict()
# address: [h, size, successor1, successor2, predecessors, inst]
self.superset = dict()
self.data = dict()
self.aggregated_scores = dict()
# addr: h, cf_convergence, cf_crossing, register def-use
self.hint_scores = dict()
# addr: data, arm, thumb
self.hint_dl = dict()
self.convert_capstone_const()
self.get_sectioninfo()
if self.output_dir:
if not os.path.exists(self.output_dir):
os.makedirs(self.output_dir)
self.filepath_hint_analysis = os.path.join(
self.output_dir, "h_analysis.txt"
)
def convert_capstone_const(self):
# TODO: put const in separate files
if self.aarch == 32:
self.ARM_INS_NOP = ARM_INS_NOP
self.ARM_INS_POP = ARM_INS_POP
self.ARM_INS_B, self.ARM_INS_BX, self.ARM_INS_BL, self.ARM_INS_BLX = (
ARM_INS_B,
ARM_INS_BX,
ARM_INS_BL,
ARM_INS_BLX,
)
self.ARM_INS_IT = ARM_INS_IT
self.ARM_INS_CBZ, self.ARM_INS_CBNZ = ARM_INS_CBZ, ARM_INS_CBNZ
self.ARM_INS_TBB, self.ARM_INS_TBH = ARM_INS_TBB, ARM_INS_TBH
self.ARM_INS_LDR = ARM_INS_LDR
self.ARM_INS_CMP = ARM_INS_CMP
self.ARM_INS_MOV, self.ARM_INS_MOVW, self.ARM_INS_MOVT = (
ARM_INS_MOV,
ARM_INS_MOVW,
ARM_INS_MOVT,
)
self.ARM_INS_BKPT = ARM_INS_BKPT
self.ARM_INS_CPS = ARM_INS_CPS
self.ARM_INS_SETEND = ARM_INS_SETEND
self.ARM_INS_RET = -1
self.ARM_OP_IMM, self.ARM_OP_MEM, self.ARM_OP_REG = (
ARM_OP_IMM,
ARM_OP_MEM,
ARM_OP_REG,
)
self.ARM_REG_PC = ARM_REG_PC
self.ARM_REG_CPSR = ARM_REG_CPSR
self.ARM_REG_SP = ARM_REG_SP
self.ARM_REG_IP = ARM_REG_IP
self.ARM_REG_LR = ARM_REG_LR
self.ARM_REG_ITSTATE = ARM_REG_ITSTATE
self.ARM_GRP_INT, self.ARM_GRP_PRIVILEGE = ARM_GRP_INT, ARM_GRP_PRIVILEGE
self.ARM_GRP_BRANCH_RELATIVE, self.ARM_GRP_JUMP, self.ARM_GRP_CALL = (
ARM_GRP_BRANCH_RELATIVE,
ARM_GRP_JUMP,
ARM_GRP_CALL,
)
self.ARM_CC_HI = ARM_CC_HI
self.ARM_CC_AL = ARM_CC_AL
self.ARM_CC_INVALID = ARM_CC_INVALID
self.dict_ldr_str = {
ARM_INS_LDRBT: 1,
ARM_INS_LDRB: 1,
ARM_INS_LDRD: 8,
ARM_INS_LDREX: 4,
ARM_INS_LDREXB: 1,
ARM_INS_LDREXD: 8,
ARM_INS_LDREXH: 2,
ARM_INS_LDRH: 2,
ARM_INS_LDRHT: 2,
ARM_INS_LDRSB: 1,
ARM_INS_LDRSBT: 1,
ARM_INS_LDRSH: 2,
ARM_INS_LDRSHT: 2,
ARM_INS_LDRT: 4,
ARM_INS_LDR: 4,
ARM_INS_STRBT: 1,
ARM_INS_STRB: 1,
ARM_INS_STRD: 8,
ARM_INS_STREX: 4,
ARM_INS_STREXB: 1,
ARM_INS_STREXD: 8,
ARM_INS_STREXH: 2,
ARM_INS_STRH: 2,
ARM_INS_STRHT: 2,
ARM_INS_STRT: 4,
ARM_INS_STR: 4,
}
self.ldr_str_simd = set(
[
ARM_INS_VLD1,
ARM_INS_VLD2,
ARM_INS_VLD3,
ARM_INS_VLD4,
ARM_INS_VLDMDB,
ARM_INS_VLDMIA,
ARM_INS_VLDR,
ARM_INS_VST1,
ARM_INS_VST2,
ARM_INS_VST3,
ARM_INS_VST4,
ARM_INS_VSTMDB,
ARM_INS_VSTMIA,
ARM_INS_VSTR,
]
)
self.dict_cc_reverse = {
ARM_CC_EQ: ARM_CC_NE,
ARM_CC_HS: ARM_CC_LO,
ARM_CC_MI: ARM_CC_PL,
ARM_CC_VS: ARM_CC_VC,
ARM_CC_HI: ARM_CC_LS,
ARM_CC_GE: ARM_CC_LT,
ARM_CC_GT: ARM_CC_LE,
ARM_CC_NE: ARM_CC_EQ,
ARM_CC_LO: ARM_CC_HS,
ARM_CC_PL: ARM_CC_MI,
ARM_CC_VC: ARM_CC_VS,
ARM_CC_LS: ARM_CC_HI,
ARM_CC_LT: ARM_CC_GE,
ARM_CC_LE: ARM_CC_GT,
}
self.supported_insts = self.COMMON_INST_ID_32 | self.dict_ldr_str.keys() | self.ldr_str_simd
elif self.aarch == 64:
self.ARM_INS_NOP = ARM64_INS_NOP
self.ARM_INS_POP = -1
self.ARM_INS_B, self.ARM_INS_BX, self.ARM_INS_BL, self.ARM_INS_BLX = (
ARM64_INS_B,
-1,
ARM64_INS_BL,
-1,
)
self.ARM_INS_IT = -1
self.ARM_INS_CBZ, self.ARM_INS_CBNZ = ARM64_INS_CBZ, ARM64_INS_CBNZ
self.ARM_INS_TBB, self.ARM_INS_TBH = -1, -1
self.ARM_INS_LDR = ARM64_INS_LDR
self.ARM_INS_CMP = ARM64_INS_CMP
self.ARM_INS_MOV, self.ARM_INS_MOVW, self.ARM_INS_MOVT = (
ARM64_INS_MOV,
-1,
-1,
)
self.ARM_INS_BKPT = -1
self.ARM_INS_CPS = -1
self.ARM_INS_SETEND = -1
self.ARM_INS_RET = ARM64_INS_RET
self.ARM_OP_IMM, self.ARM_OP_MEM, self.ARM_OP_REG = (
ARM64_OP_IMM,
ARM64_OP_MEM,
ARM64_OP_REG,
)
self.ARM_REG_PC = -1
self.ARM_REG_CPSR = -1
self.ARM_REG_SP = ARM64_REG_SP
self.ARM_REG_IP = -1 # TODO: check
self.ARM_REG_LR = ARM64_REG_LR
self.ARM_REG_ITSTATE = -1
self.ARM_GRP_INT, self.ARM_GRP_PRIVILEGE = (
ARM64_GRP_INT,
ARM64_GRP_PRIVILEGE,
)
self.ARM_GRP_BRANCH_RELATIVE, self.ARM_GRP_JUMP, self.ARM_GRP_CALL = (
ARM64_GRP_BRANCH_RELATIVE,
ARM64_GRP_JUMP,
ARM64_GRP_CALL,
)
self.ARM_CC_HI = ARM64_CC_HI
self.ARM_CC_AL = ARM64_CC_AL
self.ARM_CC_INVALID = ARM64_CC_INVALID
self.dict_ldr_str = {
ARM64_INS_LDRB: 1,
ARM64_INS_LDR: 4,
ARM64_INS_LDRH: 2,
ARM64_INS_LDRSB: 1,
ARM64_INS_LDRSH: 2,
ARM64_INS_LDRSW: 4,
ARM64_INS_STRB: 1,
ARM64_INS_STR: 4,
ARM64_INS_STRH: 2,
}
self.ldr_str_simd = set()
self.dict_cc_reverse = {
ARM64_CC_EQ: ARM64_CC_NE,
ARM64_CC_HS: ARM64_CC_LO,
ARM64_CC_MI: ARM64_CC_PL,
ARM64_CC_VS: ARM64_CC_VC,
ARM64_CC_HI: ARM64_CC_LS,
ARM64_CC_GE: ARM64_CC_LT,
ARM64_CC_GT: ARM64_CC_LE,
ARM64_CC_NE: ARM64_CC_EQ,
ARM64_CC_LO: ARM64_CC_HS,
ARM64_CC_PL: ARM64_CC_MI,
ARM64_CC_VC: ARM64_CC_VS,
ARM64_CC_LS: ARM64_CC_HI,
ARM64_CC_LT: ARM64_CC_GE,
ARM64_CC_LE: ARM64_CC_GT,
}
@staticmethod
def addr_decode(addr):
return addr if addr % 2 == 0 else addr - 1
# from capstone/bindings/python/xprint.py
@staticmethod
def to_hex2(s):
"""
if _python3:
r = "".join("{0:02x}".format(c) for c in s) # <-- Python 3 is OK
else:
r = "".join("{0:02x}".format(ord(c)) for c in s)
"""
r = "".join("{0:02x}".format(c) for c in s) # <-- Python 3 is OK
while r[0] == "0":
r = r[1:]
return r
@staticmethod
def to_x(s):
from struct import pack
if not s:
return "0"
x = pack(">q", s)
while x[0] in ("\0", 0):
x = x[1:]
return ARMDisassembler.to_hex2(x)
@staticmethod
def to_x_32(s):
from struct import pack
if not s:
return "0"
x = pack(">i", s)
while x[0] in ("\0", 0):
x = x[1:]
# -print(x)
return ARMDisassembler.to_hex2(x)
def is_addr_in_section(self, addr):
is_valid = False
addr_decode = self.addr_decode(addr)
for sec in self.sections:
if (
addr_decode >= self.sections[sec]["start_addr"]
and addr_decode < self.sections[sec]["end_addr"]
):
is_valid = True
break
return is_valid
def is_addr_in_section_exec(self, addr):
addr_decode = self.addr_decode(addr)
for sec in self.sections_exec:
if addr_decode == self.sections_exec[sec]["start_addr"]:
return 1
elif (
addr_decode >= self.sections_exec[sec]["start_addr"]
and addr_decode < self.sections_exec[sec]["end_addr"]
):
return 0
return -1
def is_addr_in_section_data(self, addr):
addr_decode = self.addr_decode(addr)
for sec in self.sections_data:
if addr_decode == self.sections_data[sec]["start_addr"]:
return 1
elif (
addr_decode >= self.sections_data[sec]["start_addr"]
and addr_decode < self.sections_data[sec]["end_addr"]
):
return 0
return -1
def get_sectioninfo(self):
b = self.binary
b.read_sections()
for sec in b.sections:
self.sections[sec] = {}
self.sections[sec]["content"] = b.sections[sec]["content"]
self.sections[sec]["start_addr"] = b.sections[sec]["start_addr"]
self.sections[sec]["end_addr"] = b.sections[sec]["end_addr"]
self.sections[sec]["index"] = b.sections[sec]["index"]
self.sections[sec]["size"] = b.sections[sec]["size"]
self.sections_exec = b.sections_exec
self.sections_data = b.sections_data
return
def generate_nodeinst(self, inst, inst_type):
node_inst = NodeInst(inst=inst)
node_inst.type = inst_type
node_inst.size = inst.size
node_inst.regs_read, node_inst.regs_write = inst.regs_access()
node_inst.regs_read = set(node_inst.regs_read)
node_inst.regs_write = set(node_inst.regs_write)
# uncommon opcode
# TODO:
# - Improve the hints for more instructions based on distribution
# - Too aggressive for unsupported insts
if self.aarch == 32:
if inst.id not in self.supported_insts:
node_inst.hint = ARMDisassembler.S_UNCOMMON_OP
return node_inst
def superset_disasm(self):
ss = dict()
d = self.binary.disassembler
if len(self.sections) < 1:
self.get_sectioninfo()
## superset
for sec in self.sections.keys():
content = self.sections[sec]["content"]
addr_start = self.sections[sec]["start_addr"]
size = self.sections[sec]["size"]
# disassembly arm
for addr in range(addr_start, addr_start + size, 4):
target_text = content[addr - addr_start : addr - addr_start + 4]
cs_insts = d.disasm_arm_inst(target_text, addr)
if len(cs_insts) == 1:
node_inst = self.generate_nodeinst(cs_insts[0], "A")
ss[addr] = node_inst
continue
assert len(cs_insts) < 1, "Error: superset {}".format(addr)
if self.aarch == 64:
continue
# disassembly thumb
for addr in range(addr_start, addr_start + size, 2):
# 2 bytes
target_text = content[addr - addr_start : addr - addr_start + 2]
cs_insts = d.disasm_thumb_inst(target_text, addr)
if len(cs_insts) == 1:
node_inst = self.generate_nodeinst(cs_insts[0], "T")
ss[addr + 1] = node_inst
continue
assert len(cs_insts) < 1, "Error: superset {}".format(addr)
# else: 4 bytes
target_text = content[addr - addr_start : addr - addr_start + 4]
cs_insts = d.disasm_thumb_inst(target_text, addr)
if len(cs_insts) == 1:
node_inst = self.generate_nodeinst(cs_insts[0], "T")
ss[addr + 1] = node_inst
continue
assert len(cs_insts) < 1, "Error: superset {}".format(addr)
# self.superset = ss
return ss
def initial_data_node(self, ss):
# logging.info("[+] Initial Data Node")
if len(self.sections) < 1:
self.get_sectioninfo()
for sec in self.sections:
for addr in range(
self.sections[sec]["start_addr"], self.sections[sec]["end_addr"]
):
self.data[addr] = NodeData()
return
def update_superset_successor(self, ss):
for addr, node_inst in ss.items():
inst = node_inst.inst
set_bit = (addr - inst.address) & 1
succr1, succr2 = self.get_successor_basic(node_inst, set_bit)
## TODO: change for superset_addr
# node_inst.succr1 = successor1
# node_inst.succr2 = successor2
for succr in [succr1, succr2]:
if succr > -1:
node_inst.succr.append(succr)
return ss
def update_superset_successor_infer(self, ss):
if len(self.sections) < 1:
self.get_sectioninfo()
set_it_invalid = set(
[
self.ARM_INS_IT,
self.ARM_INS_CBZ,
self.ARM_INS_CBNZ,
self.ARM_INS_TBB,
self.ARM_INS_TBH,
self.ARM_INS_CPS,
self.ARM_INS_SETEND,
]
)
for addr, node_inst in ss.items():
inst = node_inst.inst
# set_bit = (addr - inst.address) & 1
# print(node_inst.type, set_bit)
succrs_inst, succrs_data = self.get_successor_infer(inst, addr, ss)
if inst.id == self.ARM_INS_NOP:
node_inst.succr = list()
elif inst.id == self.ARM_INS_MOV:
# if ss[addr].regs_write == ss[addr].regs_read:
## mov rn, rn
if ss[addr].inst.operands[1].type == self.ARM_OP_REG and set(
ss[addr].regs_write
).issuperset(ss[addr].regs_read):
node_inst.succr = list()
if self.ARM_REG_PC in ss[addr].regs_write:
if inst.cc != self.ARM_CC_AL and inst.cc != self.ARM_CC_INVALID:
continue
node_inst.succr = list()
## for it, fix the basic succr of its following insts
elif inst.id == self.ARM_INS_IT:
it = list()
is_valid_it = True
addr_curr = addr
for i in range(1, len(inst.mnemonic)):
cond = inst.mnemonic[i]
if cond != "t" and cond != "e":
break
while True:
addr_curr = addr_curr + ss[addr_curr].size
if addr_curr not in ss:
is_valid_it = False
break
if ss[addr_curr].inst.id != self.ARM_INS_BKPT:
# TODO: also pc
# A branch or any instruction that modifies the PC is only permitted in an IT block if it is the last instruction in the block
if ss[addr_curr].inst.id in set_it_invalid:
is_valid_it = False
if i < len(inst.mnemonic) - 1 and inst.mnemonic[i + 1] in [
"t",
"e",
]:
set_groups = set(ss[addr_curr].inst.groups)
if (
self.ARM_GRP_BRANCH_RELATIVE in set_groups
or self.ARM_GRP_JUMP in set_groups
or self.ARM_GRP_CALL in set_groups
):
is_valid_it = False
# regs_write = ss[addr_curr].inst.regs_access()[1]
regs_write = ss[addr_curr].regs_write
if self.ARM_REG_PC in regs_write:
is_valid_it = False
break
if not is_valid_it:
break
it.append([addr_curr, cond])
if not is_valid_it:
node_inst.hint = -100
continue
# update the succr of each inst in the it block
addr_last_t, addr_last_e = it[0][0], addr
for i in range(1, len(it)):
if it[i][1] != it[i - 1][1]:
if it[i][0] in ss[it[i - 1][0]].succr:
ss[it[i - 1][0]].succr.remove(it[i][0])
addr_last = addr_last_t if it[i][1] == "t" else addr_last_e
ss[addr_last].succr.append(it[i][0])
if it[i][1] == "t":
addr_last_t = it[i][0]
else:
addr_last_e = it[i][0]
# add the first inst after the block as the succr of inst/addr_last_t/addr_last_e
addr_after_it = addr_curr + ss[addr_curr].size
# only "t"
# if addr_after_it not in ss and "e" not in [item[1] for item in it]:
if addr_after_it not in ss:
node_inst.hint = -100
continue
for addr_todo in set([addr, addr_last_t, addr_last_e]):
if addr_todo == addr_curr:
set_groups = set(ss[addr_todo].inst.groups)
if (
self.ARM_GRP_BRANCH_RELATIVE in set_groups
or self.ARM_GRP_JUMP in set_groups
or self.ARM_GRP_CALL in set_groups
):
continue
if addr_after_it not in ss[addr_todo].succr:
ss[addr_todo].succr.append(addr_after_it)
elif inst.id == self.ARM_INS_TBB or inst.id == self.ARM_INS_TBH:
# check cmp/bhi pattern
pattern = list()
for addr_b in [addr - 2, addr - 4]:
if addr_b in ss and ss[addr_b].inst.id == self.ARM_INS_B:
for addr_cmp in [addr_b - 2, addr_b - 4]:
if (
addr_cmp in ss
and ss[addr_cmp].inst.id == self.ARM_INS_CMP
):
pattern.append([addr_cmp, addr_b])
if len(pattern) == 0:
node_inst.hint = -100
continue
elif len(pattern) > 1:
logging.info("tbb/tbh with multiple patterns: {}".format(pattern))
len_byte = 1 if inst.id == self.ARM_INS_TBB else 2
for addr_cmp, addr_b in pattern:
if (
len(ss[addr_cmp].inst.operands) == 2
and ss[addr_cmp].inst.operands[1].type == self.ARM_OP_IMM
):
num_b = ss[addr_cmp].inst.operands[1].imm + 1
else:
continue
if ss[addr_b].inst.cc != self.ARM_CC_HI:
logging.info(
"tbb/tbh unexpected pattern: {} {}".format(addr_cmp, addr_b)
)
continue
# decide succrs_data
for i in range(num_b * len_byte):
addr_d = self.addr_decode(addr) + inst.size + i
succrs_data.append(addr_d)
if inst.id == self.ARM_INS_TBB and num_b % 2 == 1:
succrs_data.append(addr_d + 1)
# decide succrs_inst
# rn needs to be pc
if inst.operands[0].mem.base != self.ARM_REG_PC:
continue
addr_d = self.addr_decode(addr) + inst.size
for sec in self.sections:
if (
addr_d >= self.sections[sec]["start_addr"]
and addr_d < self.sections[sec]["end_addr"]
):
l = addr_d - self.sections[sec]["start_addr"]
r = l + num_b * len_byte
contents = self.sections[sec]["content"][l:r]
for i in range(num_b):
value = contents[i * len_byte : (i + 1) * len_byte]
if len(value) == 1:
offset = value[0]
else:
offset = struct.unpack("<H", value)[0]
succrs_inst.append(addr + 4 + offset * 2)
# print info for check
# for addr_todo in [addr_cmp, addr_b, addr]:
# inst_curr = ss[addr_todo].inst
# print("{} {} {}".format(hex(addr_todo), inst_curr.mnemonic, inst_curr.op_str))
# print(" data: {}".format([hex(a) for a in succrs_data]))
# print(" inst: {}".format([hex(a) for a in succrs_inst]))
elif (
self.ARM_REG_PC in ss[addr].regs_write
and not (inst.cc != self.ARM_CC_AL and inst.cc != self.ARM_CC_INVALID)
and addr + inst.size in node_inst.succr
):
# logging.debug(f"write pc {hex(addr)} {ss[addr].inst.mnemonic} {ss[addr].inst.op_str}")
# if inst.id in set_write_pc:
node_inst.succr.remove(addr + inst.size)
for succr in succrs_inst:
if succr not in node_inst.succr:
node_inst.succr.append(succr)
for succr in succrs_data:
if succr not in node_inst.succr_data and succr in self.data:
node_inst.succr_data.append(succr)
self.data[succr].accessed_inst.append(addr)
return ss
def get_successor_basic(self, node_inst, set_bit):
inst = node_inst.inst
successor1, successor2 = -1, -1
succrs = list()
set_groups = set(inst.groups)
if inst.id == self.ARM_INS_TBB or inst.id == self.ARM_INS_TBH:
## TODO, if rn is pc, not return -1
return -1, -1
elif inst.id == self.ARM_INS_NOP:
return -1, -1
# aarch64
elif inst.id == self.ARM_INS_RET:
return -1, -1
# fix pop successor
# inst.regs_access includes all the implicit & explicit registers
# (regs_read, regs_write) = inst.regs_access()
# inst.regs_write return list of all implicit registers being modified
# error: reg_write is always PC
elif inst.id == self.ARM_INS_POP:
if self.ARM_REG_PC in node_inst.regs_write:
return -1, -1
elif (
self.ARM_GRP_BRANCH_RELATIVE in set_groups
or self.ARM_GRP_JUMP in set_groups
or self.ARM_GRP_CALL in set_groups
):
# cbz/cbnz/conditional branch: the next inst is its succr
if inst.id == self.ARM_INS_CBZ or inst.id == self.ARM_INS_CBNZ:
succrs.append((inst.address + node_inst.size) | set_bit)
elif inst.cc != self.ARM_CC_AL and inst.cc != self.ARM_CC_INVALID:
succrs.append((inst.address + node_inst.size) | set_bit)
# b/bl/blx label
if len(inst.operands) == 1 and inst.operands[0].type == self.ARM_OP_IMM:
target = (
int(ARMDisassembler.to_x_32(inst.operands[0].imm), 16)
if inst.operands[0].imm < 0
else inst.operands[0].imm
)
target = target | set_bit
# fix bx/blx imm successor
if inst.id == self.ARM_INS_BX or inst.id == self.ARM_INS_BLX:
target ^= 1
succrs.append(target)
# cbz/cbnz: the immediate is also its succr
elif len(inst.operands) == 2 and inst.operands[1].type == self.ARM_OP_IMM:
target = (
int(ARMDisassembler.to_x_32(inst.operands[1].imm), 16)
if inst.operands[1].imm < 0
else inst.operands[1].imm
)
target = target | set_bit
succrs.append(target)
if len(succrs) == 1:
successor1 = succrs[0]
elif len(succrs) == 2:
successor1, successor2 = succrs[0], succrs[1]
return successor1, successor2
elif self.ARM_GRP_INT in set_groups or self.ARM_GRP_PRIVILEGE in set_groups:
return -1, -1
successor1 = (inst.address + node_inst.size) | set_bit
return successor1, successor2
def get_successor_infer(self, inst, addr, ss):
succrs_inst, succrs_data = list(), list()
set_groups = set(inst.groups)
set_bit = (addr - inst.address) & 1
if (
self.ARM_GRP_BRANCH_RELATIVE in set_groups
or self.ARM_GRP_JUMP in set_groups
or self.ARM_GRP_CALL in set_groups
):
## consider pc as the target
if len(inst.operands) == 1 and inst.operands[0].type == self.ARM_OP_REG:
if inst.operands[0].reg == self.ARM_REG_PC:
target = inst.address + 4 if set_bit == 1 else inst.address + 8
succrs_inst.append(target)
if inst.id == self.ARM_INS_BL or inst.id == self.ARM_INS_BLX:
pass
# TODO: chec if it returns
# succrs_inst.append((inst.address + inst.size) | set_bit)
elif inst.id == self.ARM_INS_TBB or inst.id == self.ARM_INS_TBH:
pass
elif inst.id in self.dict_ldr_str:
op = inst.operands[1]
# print("LDR/STR: {} {} {} {} {} {} {} {}".format(hex(inst.address), inst.mnemonic, inst.op_str,\
# op.mem.base, op.mem.index, op.mem.scale, op.mem.disp, op.mem.lshift))
if op.type == self.ARM_OP_MEM and op.mem.base == self.ARM_REG_PC:
if op.mem.index == 0 and op.mem.scale == 1 and op.mem.lshift == 0:
if op.mem.base == self.ARM_REG_PC:
target = inst.address + 4 if set_bit == 1 else inst.address + 8
target += op.mem.disp
# if set_bit == 1 and target % 4 != 0:
# target = target - 2
succrs_data.append(target)
# print(" target: {}".format(hex(target)))
elif op.type == self.ARM_OP_IMM:
target = (
int(ARMDisassembler.to_x_32(op.imm), 16)
if op.imm < 0
else op.imm
)
succrs_data.append(target)
# elif inst.id == ARM_INS_IT:
# print(inst.mnemonic, inst.op_str)
return succrs_inst, succrs_data
def update_superset_pred(self, ss):
# logging.info("[+] Update Superset Pred")
for addr, node_inst in ss.items():
for succr in node_inst.succr:
if succr in ss:
ss[succr].pred.append(addr)
return ss
def print_superset_info(self, ss):
for addr in sorted(ss.keys()):
node_inst = ss[addr]
inst = node_inst.inst
bytes = "".join(format(x, "02x") for x in inst.bytes)
print(
"{} {} {:>8} {} {}".format(
hex(addr), node_inst.type, bytes, inst.mnemonic, inst.op_str
)
)
# [hex(a) for a in node_inst.succr]
# [hex(a) for a in node_inst.pred]
# node_inst.hint, self.hint_dl[addr][1], self.hint_scores[addr]
# [hex(a) for a in node_inst.succr_data]
## Hints ##
def static_analysis(self, ss):
for addr in ss:
self.hint_scores[addr] = [1, 0, 0, 0]
self.addr_sorted = sorted(ss.keys())
self.get_cf_converge_hints(ss)
self.get_cf_cross_hints(ss)
# self.get_reg_hints(ss)
# self.get_reg_hints_onepass(ss)
self.get_reg_hints_limited(ss)
return
def get_cf_converge_hints(self, ss):
# get mapping from jump target to jump-site
dst2src = defaultdict(list)
addr_list = self.addr_sorted
for addr in addr_list:
for succr in ss[addr].succr:
if succr == -1 or succr == addr + ss[addr].size:
continue
dst2src[succr].append(addr)
# check converge control flow
for addr, src_list in dst2src.items():
l = len(src_list)
for src in src_list:
self.hint_scores[src][1] += l - 1
return
def get_cf_cross_hints(self, ss):
addr_list = self.addr_sorted
for addr in addr_list:
# check inst is a jump/call instruction
jump_target = -1
for succr in ss[addr].succr:
if succr == -1 or succr == addr + ss[addr].size:
continue
jump_target = succr
# No jump target find
if jump_target == -1:
continue
# check control flow cross
for offset in range(2, 5, 2):
addr_pre = jump_target - offset
# check pre_addr is valid
if addr_pre not in ss or ss[addr_pre].size != offset:
continue
# check pre_inst is jump instruction
is_jump = False
for g in ss[addr_pre].inst.groups:
if g in [
self.ARM_GRP_BRANCH_RELATIVE,
self.ARM_GRP_JUMP,
self.ARM_GRP_CALL,
]: ## TODO: check
is_jump = True
break
if is_jump:
self.hint_scores[addr][2] += 1
self.hint_scores[addr_pre][2] += 1
return
def get_reg_hints(self, ss):
addr_list = self.addr_sorted
for addr in addr_list:
# For each insturction, check registers written by it. Hence, we do not
# need to care instructions which do not write any register.
inst = ss[addr].inst
# regs_write = inst.regs_access()[1]
regs_write = inst.regs_write
if len(regs_write) == 0:
continue
# Collect written register
write_regs = dict()
for r in regs_write:
write_regs[r] = 1
# DFS to gather hints
visited = set()
for succr in ss[addr].succr:
if succr == -1:
continue
self.dfs_get_reg_hints(ss, addr, succr, write_regs, visited)
del write_regs
return
def dfs_get_reg_hints(self, ss, addr_def, addr_cur, write_regs, visited):
# update visitied
visited.add(addr_cur)
# validate address
if addr_cur not in ss:
return
# check use-def chain
inst = ss[addr_cur].inst
# regs_read = inst.regs_access()[0]
regs_read = inst.regs_read
# generate hints and record removed registers
removed_regs = list()
for r in regs_read:
# ignore flags and pc register
if r == self.ARM_REG_CPSR or r == self.ARM_REG_PC: