forked from lifting-bits/mcsema
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_cfg.py
executable file
·2515 lines (1998 loc) · 79.8 KB
/
get_cfg.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
#!/usr/bin/env python
##
## Instructions:
## 1) Install python-protobuf for your IDAPython installation. This probably means
## downloading it from https://protobuf.googlecode.com/files/protobuf-2.5.0.tar.gz
## and manually running setup.py
## 2) This script should be run via IDA's batch mode. See the output
## of --help for more details on the command line options.
##
import idautils
import idaapi
import idc
import sys
from os import path
import os
import argparse
import struct
#import syslog
import traceback
import collections
import itertools
#hack for IDAPython to see google protobuf lib
if os.path.isdir('/usr/lib/python2.7/dist-packages'):
sys.path.append('/usr/lib/python2.7/dist-packages')
if os.path.isdir('/usr/local/lib/python2.7/dist-packages'):
sys.path.append('/usr/local/lib/python2.7/dist-packages')
tools_disass_ida_dir = os.path.dirname(__file__)
tools_disass_dir = os.path.dirname(tools_disass_ida_dir)
# Note: The bootstrap file will copy CFG_pb2.py into this dir!!
import CFG_pb2
_DEBUG = False
_DEBUG_FILE = sys.stderr
EXTERNALS = set()
DATA_SEGMENTS = {}
RECOVERED_EAS = set()
ACCESSED_VIA_JMP = set()
EMAP = {}
EMAP_DATA = {}
PIE_MODE = False
OFFSET_TABLES = {}
SPECIAL_REP_HANDLING = [
[0xC3],
]
TRAPS = [
idaapi.NN_int3,
idaapi.NN_icebp,
]
CALLS = [
idaapi.NN_call,
idaapi.NN_callfi,
idaapi.NN_callni]
RETS = [
idaapi.NN_retf,
idaapi.NN_retfd,
idaapi.NN_retfq,
idaapi.NN_retfw,
idaapi.NN_retn,
idaapi.NN_retnd,
idaapi.NN_retnq,
idaapi.NN_retnw]
COND_BRANCHES = [\
idaapi.NN_ja,\
idaapi.NN_jae,\
idaapi.NN_jb,\
idaapi.NN_jbe,\
idaapi.NN_jc,\
idaapi.NN_jcxz,\
idaapi.NN_je,\
idaapi.NN_jecxz,\
idaapi.NN_jg,\
idaapi.NN_jge,\
idaapi.NN_jl,\
idaapi.NN_jle,\
idaapi.NN_jna,\
idaapi.NN_jnae,\
idaapi.NN_jnb,\
idaapi.NN_jnbe,\
idaapi.NN_jnc,\
idaapi.NN_jne,\
idaapi.NN_jng,\
idaapi.NN_jnge,\
idaapi.NN_jnl,\
idaapi.NN_jnle,\
idaapi.NN_jno,\
idaapi.NN_jnp,\
idaapi.NN_jns,\
idaapi.NN_jnz,\
idaapi.NN_jo,\
idaapi.NN_jp,\
idaapi.NN_jpe,\
idaapi.NN_jpo,\
idaapi.NN_jrcxz,\
idaapi.NN_js,\
idaapi.NN_jz,]
UCOND_BRANCHES = [\
idaapi.NN_jmp,\
idaapi.NN_jmpfi,\
idaapi.NN_jmpni,\
idaapi.NN_jmpshort]
EXTERNAL_NAMES = [
"@@GLIBC_",\
]
EXTERNAL_DATA_COMMENTS = [
"Copy of shared data",
]
def DEBUG(s):
global _DEBUG, _DEBUG_FILE
if _DEBUG:
_DEBUG_FILE.write("{}\n".format(str(s)))
_PREFIX_ITYPES = (idaapi.NN_lock, idaapi.NN_rep,
idaapi.NN_repe, idaapi.NN_repne)
def _decode_instruction(ea):
"""Read the bytes of an x86/amd64 instruction. This handles things like
combining the bytes of an instruction with its prefix. IDA Pro sometimes
treats these as separate."""
global _PREFIX_ITYPES
decoded_inst = idautils.DecodeInstruction(ea)
if not decoded_inst:
return None, tuple()
assert decoded_inst.ea == ea
end_ea = ea + decoded_inst.size
decoded_bytes = "".join(chr(idc.Byte(byte_ea)) for byte_ea in range(ea, end_ea))
# We've got an instruction with a prefix, but the prefix is treated as
# independent.
if 1 == decoded_inst.size and decoded_inst.itype in _PREFIX_ITYPES:
decoded_inst, extra_bytes = _decode_instruction(end_ea)
DEBUG("Extended instruction at {:08x} by {} bytes".format(
ea, len(extra_bytes)))
decoded_bytes.extend(extra_bytes)
return decoded_inst, decoded_bytes
# Python 2.7's xrange doesn't work with `long`s.
def xrange(begin, end=None, step=1):
if end:
return iter(itertools.count(begin, step).next, end)
else:
return iter(itertools.count().next, begin)
def hasExternalDataComment(ea):
cmt = idc.GetCommentEx(ea, 0)
return cmt in EXTERNAL_DATA_COMMENTS
def ReftypeString(rt):
if rt == CFG_pb2.Instruction.DataRef:
return "DATA"
elif rt == CFG_pb2.Instruction.CodeRef:
return "CODE"
else:
return "UNKNOWN!"
def readByte(ea):
byte = readBytesSlowly(ea, ea+1)
byte = ord(byte)
return byte
def readDword(ea):
bytestr = readBytesSlowly(ea, ea+4)
dword = struct.unpack("<L", bytestr)[0]
return dword
def readQword(ea):
bytestr = readBytesSlowly(ea, ea+8)
qword = struct.unpack("<Q", bytestr)[0]
return qword
def isElf():
return idc.GetLongPrm(idc.INF_FILETYPE) == idc.FT_ELF
def isLinkedElf():
return idc.GetLongPrm(idc.INF_FILETYPE) == idc.FT_ELF and \
idc.BeginEA() not in [0xffffffffL, 0xffffffffffffffffL]
def IsString(ea):
return idc.isASCII(idaapi.getFlags(ea))
def IsStruct(ea):
return idc.isStruct(idaapi.getFlags(ea))
def fixExternalName(fn):
if fn in EMAP:
return fn
if fn in EMAP_DATA:
return fn
if not isLinkedElf() and fn[0] == '_':
return fn[1:]
if fn.endswith("_0"):
newfn = fn[:-2]
if newfn in EMAP:
return newfn
for en in EXTERNAL_NAMES:
if en in fn:
fn = fn[:fn.find(en)]
break
return fn
def nameInMap(themap, fn):
return fixExternalName(fn) in themap
def getFromEMAP(fname):
fixname = fixExternalName(fname)
return EMAP[fixname]
def doesNotReturn(fname):
try:
args, conv, ret, sign = getFromEMAP(fname)
if ret == "Y":
return True
except KeyError, ke:
raise Exception("Unknown external: " + fname)
return False
def isHlt(insn_t):
return insn_t.itype == idaapi.NN_hlt
def isJmpTable(ea):
insn_t, _ = _decode_instruction(ea)
is_jmp = insn_t.itype in [idaapi.NN_jmp,
idaapi.NN_jmpfi,
idaapi.NN_jmpni]
if not is_jmp: return False
if idaapi.get_switch_info_ex(ea):
return True
return False
def addFunction(M, ep):
F = M.internal_funcs.add()
F.entry_address = ep
F.symbol_name = getFunctionName(ep)
return F
def entryPointHandler(M, ep, name, args_from_stddef=False):
EP = M.entries.add()
EP.entry_name = name
EP.entry_address = ep
have_edata = False
# should we get argument count
# calling convention, and return type from std_defs?
if args_from_stddef:
try:
(argc, conv, ret, sign) = getFromEMAP(name)
have_edata = True
except KeyError as ke:
pass
if not have_edata:
(argc, conv, ret) = getExportType(name, ep)
EP.entry_extra.entry_argc = argc
EP.entry_extra.entry_cconv = conv
if ret == 'Y':
EP.entry_extra.does_return = False
else:
EP.entry_extra.does_return = True
F = addFunction(M, ep)
DEBUG("At EP {0}:{1:x}".format(name,ep))
return F
def basicBlockHandler(F, block, blockset, processed_blocks):
B = F.blocks.add()
B.base_address = block.startEA
DEBUG("BB: {0:x}".format(block.startEA))
B.block_follows.extend(block.succs)
if _DEBUG:
str_l = ["{0:x}".format(i) for i in block.succs]
if len(str_l) > 0:
DEBUG("Successors: {0}".format(", ".join(str_l)))
return B
def readInstructionBytes(inst):
_, decoded_bytes = _decode_instruction(inst)
return decoded_bytes
def isInternalCode(ea):
pf = idc.GetFlags(ea)
if idc.isCode(pf) and not idc.isData(pf):
return True
# find stray 0x90 (NOP) bytes in .text that IDA
# thinks are data items
if readByte(ea) == 0x90:
seg = idc.SegStart(ea)
segtype = idc.GetSegmentAttr(seg, idc.SEGATTR_TYPE)
if segtype == idc.SEG_CODE:
mark_as_code(ea)
return True
return False
def isNotCode(ea):
pf = idc.GetFlags(ea)
return not idc.isCode(pf)
def isExternalReference(ea):
# see if this is in an internal or external code ref
DEBUG("Testing {0:x} for externality".format(ea))
ext_types = [idc.SEG_XTRN]
seg = idc.SegStart(ea)
if seg == idc.BADADDR:
DEBUG("WARNING: Could not get segment addr for: {0:x}".format(ea))
return False
segtype = idc.GetSegmentAttr(seg, idc.SEGATTR_TYPE)
if segtype in ext_types:
return True
if isLinkedElf():
fn = getFunctionName(ea)
for extsign in EXTERNAL_NAMES:
if extsign in fn:
DEBUG("Assuming external reference because: {} in {}".format(extsign, fn))
return True
if isExternalData(fn):
if hasExternalDataComment(ea):
return True
else:
DEBUG("WARNING: May have missed external data ref {} at {:x}".format(fn, ea))
return False
def getFunctionName(ea):
return idc.GetTrueNameEx(ea,ea)
def addInst(block, addr, insn_t, inst_bytes, true_target=None, false_target=None):
# check if there is a lock prefix:
inst = block.insts.add()
inst.inst_addr = addr
str_val = inst_bytes
inst.inst_bytes = str_val
inst.inst_len = len(inst_bytes)
if true_target != None: inst.true_target = true_target
if false_target != None: inst.false_target = false_target
return inst
PERSONALITY_INVALID = 0
PERSONALITY_DIRECT_JUMP = 1
PERSONALITY_INDIRECT_JUMP = 2
PERSONALITY_DIRECT_CALL = 3
PERSONALITY_INDIRECT_CALL = 4
PERSONALITY_RETURN = 5
PERSONALITY_SYSTEM_CALL = 6
PERSONALITY_SYSTEM_RETURN = 7
PERSONALITY_CONDITIONAL_BRANCH = 8
PERSONALITY_TERMINATOR = 9
PERSONALITY_FALL_THROUGH = 10
PERSONALITY_FALL_THROUGH_TERMINATOR = 11
_PERSONALITIES = collections.defaultdict(int)
_PERSONALITIES.update({
idaapi.NN_call: PERSONALITY_DIRECT_CALL,
idaapi.NN_callfi: PERSONALITY_INDIRECT_CALL,
idaapi.NN_callni: PERSONALITY_INDIRECT_CALL,
idaapi.NN_retf: PERSONALITY_RETURN,
idaapi.NN_retfd: PERSONALITY_RETURN,
idaapi.NN_retfq: PERSONALITY_RETURN,
idaapi.NN_retfw: PERSONALITY_RETURN,
idaapi.NN_retn: PERSONALITY_RETURN,
idaapi.NN_retnd: PERSONALITY_RETURN,
idaapi.NN_retnq: PERSONALITY_RETURN,
idaapi.NN_retnw: PERSONALITY_RETURN,
idaapi.NN_jmp: PERSONALITY_DIRECT_JUMP,
idaapi.NN_jmpshort: PERSONALITY_DIRECT_JUMP,
idaapi.NN_jmpfi: PERSONALITY_INDIRECT_JUMP,
idaapi.NN_jmpni: PERSONALITY_INDIRECT_JUMP,
idaapi.NN_int: PERSONALITY_SYSTEM_CALL,
idaapi.NN_into: PERSONALITY_SYSTEM_CALL,
idaapi.NN_int3: PERSONALITY_SYSTEM_CALL,
idaapi.NN_bound: PERSONALITY_SYSTEM_CALL,
idaapi.NN_syscall: PERSONALITY_SYSTEM_CALL,
idaapi.NN_sysenter: PERSONALITY_SYSTEM_CALL,
idaapi.NN_iretw: PERSONALITY_SYSTEM_RETURN,
idaapi.NN_iret: PERSONALITY_SYSTEM_RETURN,
idaapi.NN_iretd: PERSONALITY_SYSTEM_RETURN,
idaapi.NN_iretq: PERSONALITY_SYSTEM_RETURN,
idaapi.NN_sysret: PERSONALITY_SYSTEM_RETURN,
idaapi.NN_sysexit: PERSONALITY_SYSTEM_RETURN,
idaapi.NN_hlt: PERSONALITY_TERMINATOR,
idaapi.NN_ud2: PERSONALITY_TERMINATOR,
idaapi.NN_icebp: PERSONALITY_TERMINATOR,
idaapi.NN_ja: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jae: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jb: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jbe: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jc: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jcxz: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_je: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jecxz: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jg: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jge: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jl: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jle: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jna: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jnae: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jnb: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jnbe: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jnc: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jne: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jng: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jnge: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jnl: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jnle: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jno: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jnp: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jns: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jnz: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jo: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jp: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jpe: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jpo: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jrcxz: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_js: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_jz: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_xbegin: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_loopw: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_loop: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_loopd: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_loopq: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_loopwe: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_loope: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_loopde: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_loopqe: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_loopwne: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_loopne: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_loopdne: PERSONALITY_CONDITIONAL_BRANCH,
idaapi.NN_loopqne: PERSONALITY_CONDITIONAL_BRANCH,
})
def isConditionalJump(insn_t):
return _PERSONALITIES[insn_t.itype] == PERSONALITY_CONDITIONAL_BRANCH
def isUnconditionalJump(insn_t):
return _PERSONALITIES[insn_t.itype] in (PERSONALITY_DIRECT_JUMP, PERSONALITY_INDIRECT_JUMP)
def isCall(insn_t):
return _PERSONALITIES[insn_t.itype] in (PERSONALITY_DIRECT_CALL, PERSONALITY_INDIRECT_CALL)
def isRet(insn_t):
return _PERSONALITIES[insn_t.itype] == PERSONALITY_RETURN
def isTrap(insn_t):
return insn_t.itype in TRAPS
def findRelocOffset(ea, size):
for i in xrange(ea,ea+size):
if idc.GetFixupTgtOff(i) != -1:
return i-ea
return -1
def handleExternalRef(fn):
# Don't mangle symbols for fully linked ELFs... yet
in_a_map = fn in EMAP or fn in EMAP_DATA
if not isLinkedElf():
if fn.startswith("__imp_"):
fn = fn[6:]
if fn.endswith("_0"):
fn = fn[:-2]
# name could have been modified by the above tests
in_a_map = fn in EMAP or fn in EMAP_DATA
if fn.startswith("_") and not in_a_map:
fn = fn[1:]
if fn.startswith("@") and not in_a_map:
fn = fn[1:]
if isElf() and '@' in fn:
fn = fn[:fn.find('@')]
fixfn = fixExternalName(fn)
EXTERNALS.add(fixfn)
return fixfn
def isInData(start_ea, end_ea):
for (start,end) in DATA_SEGMENTS.values():
if start_ea >= start and start_ea < end:
DEBUG("Data Range: {0:x} <= {1:x} < {2:x}".format(start, start_ea, end))
DEBUG("Data Range: {:x} - {:x}".format(start_ea, end_ea))
if end_ea <= end:
return True
else:
DEBUG("{0:x} NOT <= {1:x}".format(end_ea, end))
DEBUG("{0:x}-{1:x} overlaps with: {2:x}-{3:x}".format(start_ea, end_ea, start, end))
raise Exception("Overlapping data segments!")
else:
if end_ea > start and end_ea <= end:
DEBUG("Overlaps with: {0:x}-{1:x}".format(start, end))
raise Exception("Overlapping data segments!")
return False
def isExternalData(fn):
indata = fn in EMAP_DATA
incode = fn in EMAP
if indata and not incode:
return True
elif indata and incode:
raise Exception("Symbol "+fn+" defined as both code and data!")
else:
return False
def sanityCheckJumpTableSize(table_ea, ecount):
""" IDA doesn't correctly calculate some jump table sizes. Fix them.
This will look for the following jump tables:
----
cmp eax, num_entries
ja bad_entry
fall_through:
mov rax, qword [index * ptr_size + table_base_address]
jmp rax
bad_entry:
----
IDA will detect these as jump tables, but it sometimes
does not correctly calculate the "num_entries" properly,
which leads us to missing jump table cases.
Attempt to identify where 'num_entries' is compared, and
sanity check it vs. what IDA found.
"""
if not isLinkedElf():
return ecount
if getBitness() != 64:
return ecount
table_insn = idautils.DecodeInstruction(table_ea)
if table_insn is None:
DEBUG("Could not decode instruction at {:x}".format(table_insn))
return ecount
# This code is only reached if we *already know this is a jump table
# The goal is to sanity check the size
# First, Check to make sure that this is a "jmp reg" instruction.
if table_insn.Operands[0].type != idc.o_reg:
return ecount
DEBUG("Sanity checking table at {:x}".format(table_ea))
# get register we jump with
jmp_reg = table_insn.Operands[0].value
inst_ea = table_ea
# This will walk back up to 5 instructions looking for a 'cmp' against
# the jump register, and use the immediate value from the cmp as
# the true jump table case count.
# This strategy has the potential for false positives, since it
# does not strictly check for the exact format of jump table instructions.
# For now that is intentional to allow some flexibility, because we are
# uncertain what the compiler will emit.
#TODO(artem): Make this loop strict check for the instructions we expect,
# if we find the current lax check causing false positives
for i in xrange(5):
# walk back a few instructions until we find a cmp
inst_ea = idc.PrevHead(inst_ea)
if inst_ea == idc.BADADDR:
return ecount
inst = idautils.DecodeInstruction(inst_ea)
if inst is None:
return ecount
if inst.itype == idaapi.NN_cmp and inst.Operands[0].type == idc.o_reg:
# check if reg in cmp == reg we jump with
if jmp_reg == inst.Operands[0].value:
# check if the CMP is with an immediate
if inst.Operands[1].type == idc.o_imm:
# the immediate is our new count
# the comparison is vs the max case#, but the cases start at 0, so add 1
# to get case count
new_count = 1 + inst.Operands[1].value
# compare to ecount. Take the bigger value.
if new_count > ecount:
DEBUG("Overriding old JMP count of {} with {} for table at {:x}".format(ecount, new_count, table_ea))
return new_count
return ecount
return ecount
def handleJmpTable(I, inst, new_eas):
si = idaapi.get_switch_info_ex(inst)
jsize = si.get_jtable_element_size()
jstart = si.jumps
# accept 32-bit jump tables in 64-bit, for now
valid_sizes = [4, getBitness()/8]
readers = { 4: readDword,
8: readQword }
if jsize not in valid_sizes:
raise Exception("Jump table is not a valid size: {}".format(jsize))
return
DEBUG("\tJMPTable Start: {0:x}".format(jstart))
seg_start = idc.SegStart(jstart)
if seg_start != idc.BADADDR:
I.jump_table.offset_from_data = jstart - seg_start
DEBUG("\tJMPTable offset from data: {:x}".format(I.jump_table.offset_from_data))
I.jump_table.zero_offset = 0
i = 0
entries = si.get_jtable_size()
entries = sanityCheckJumpTableSize(inst, entries)
for i in xrange(entries):
je = readers[jsize](jstart+i*jsize)
# check if this is an offset based jump table
if si.flags & idaapi.SWI_ELBASE == idaapi.SWI_ELBASE:
# adjust jump target based on offset in table
# we only ever see these as 32-bit offsets, even
# when looking at 64-bit applications
je = 0xFFFFFFFF & (je + si.elbase)
I.jump_table.table_entries.append(je)
if je not in RECOVERED_EAS and isStartOfFunction(je):
new_eas.add(je)
DEBUG("\t\tAdding JMPTable {0}: {1:x}".format(i, je))
#je = idc.GetFixupTgtOff(jstart+i*jsize)
#while je != -1:
# I.jump_table.table_entries.append(je)
# if je not in RECOVERED_EAS:
# new_eas.add(je)
# DEBUG("\t\tAdding JMPTable {0}: {1:x}".format( i, je))
# i += 1
# je = idc.GetFixupTgtOff(jstart+i*jsize)
def isElfThunk(ea):
if not isLinkedElf():
return False, None
insn_t, _ = _decode_instruction(ea)
if isUnconditionalJump(insn_t):
real_ext_ref = None
for cref in idautils.CodeRefsFrom(ea, 0):
if isExternalReference(cref):
real_ext_ref = cref
break
if real_ext_ref is None:
for dref in idautils.DataRefsFrom(ea):
if idc.SegName(dref) in [".got.plt"]:
# this is an external call after all
for extref in idautils.DataRefsFrom(dref):
if isExternalReference(extref):
real_ext_ref = extref
if real_ext_ref is not None:
fn = getFunctionName(real_ext_ref)
return True, fn
return False, None
def manualRelocOffset(I, inst, dref):
insn_t = idautils.DecodeInstruction(inst)
if insn_t is None:
return None
# check for immediates first
# TODO(artem) special case things like 0x0 that see in COFF objects?
for (idx, op) in enumerate(insn_t.Operands):
if op.value == dref:
# IDA will do stupid things like say an immediate operand is a memory operand
# if it references memory. Try to work around this issue
# its the first operand (probably a destination) and IDA thinks its o_mem
# in this case, IDA is probably right; don't mark it as an immediate
if idx == 0 and op.type == idaapi.o_mem:
continue
if op.type in [idaapi.o_imm, idaapi.o_mem, idaapi.o_near, idaapi.o_far]:
# we aren't sure what we have, but it use a register... probably not
# an immediate but instead a memory reference
if op.reg > 0:
I.mem_reloc_offset = op.offb
return "MEM"
I.imm_reloc_offset = op.offb
return "IMM"
for op in insn_t.Operands:
if op.type in [idaapi.o_displ, idaapi.o_phrase]:
I.mem_reloc_offset = op.offb
return "MEM"
return "MEM"
def opAtOffset(insn_t, off):
if insn_t is None:
return None
for op in insn_t.Operands:
if op.offb == off:
if op.type in [idaapi.o_displ, idaapi.o_phrase]:
return "MEM"
if op.type in [idaapi.o_imm, idaapi.o_mem, idaapi.o_near, idaapi.o_far]:
return "IMM"
DEBUG("ERROR: Unknown op type {}, assuming MEM".format(op.type))
return "MEM"
return None
def setReference(I, optype, reftype, ref):
if "IMM" == optype:
I.imm_reference = ref
I.imm_ref_type = reftype
elif "MEM" == optype:
I.mem_reference = ref
I.mem_ref_type = reftype
else:
DEBUG("ERROR: Unknown ref type: {}".format(optype))
def addDataReference(M, I, inst, dref, new_eas):
if inValidSegment(dref):
if isExternalReference(dref):
fn = getFunctionName(dref)
fn = handleExternalRef(fn)
if isExternalData(fn):
I.ext_data_name = fn
DEBUG("EXTERNAL DATA REF FROM {0:x} to {1}".format(inst, fn))
else:
I.ext_call_name = fn
DEBUG("EXTERNAL CODE REF FROM {0:x} to {1}".format(inst, fn))
return
which_op = manualRelocOffset(I, inst, dref)
if which_op is None:
DEBUG("ERROR: could not decode instruction at {:x}".format(inst))
return
ref = None
reftype = None
if isInternalCode(dref):
ref = dref
reftype = CFG_pb2.Instruction.CodeRef
if dref not in RECOVERED_EAS:
new_eas.add(dref)
else:
dref_size = idc.ItemSize(dref)
DEBUG("\t\tData Ref: {0:x}, size: {1}".format(
dref, dref_size))
ref = handleDataRelocation(M, dref, new_eas)
reftype = CFG_pb2.Instruction.DataRef
DEBUG("\t\tSetting {} ref at {:x}: to {:x} type: {}".format(
which_op, inst, ref, ReftypeString(reftype)))
setReference(I, which_op, reftype, ref)
else:
DEBUG("WARNING: Data not in valid segment {0:x}".format(dref))
def instructionHandler(M, B, addr, new_eas):
insn_t, inst_bytes = _decode_instruction(addr)
if not insn_t:
# handle jumps after noreturn functions
if idc.Byte(addr) == 0xCC:
I = addInst(B, addr, insn_t, inst_bytes)
return I, True
else:
raise Exception("Cannot read instruction at: {0:x}".format(addr))
# skip HLTs -- they are privileged, and are used in ELFs after a noreturn call
if isHlt(insn_t):
return None, False
#DEBUG("\t\tinst: {0}".format(idc.GetDisasm(addr)))
#DEBUG("\t\tBytes: {0}".format(inst_bytes))
I = addInst(B, addr, insn_t, inst_bytes)
if isJmpTable(addr):
DEBUG("Its a jump table")
handleJmpTable(I, addr, new_eas)
return I, False
# mark that this is an offset table
if PIE_MODE and addr in OFFSET_TABLES:
table_va = OFFSET_TABLES[addr].start_addr
DEBUG("JMP at {:08x} has offset table {:08x}".format(addr, table_va))
I.offset_table_addr = table_va
crefs_from_here = idautils.CodeRefsFrom(addr, 0)
#check for code refs from here
crefs = []
# pull code refs from generator into a list
for cref_i in crefs_from_here:
crefs.append(cref_i)
is_call = isCall(insn_t)
isize = len(inst_bytes)
next_ea = addr+isize
had_refs = False
# this is a call $+5, needs special handling
if insn_t.itype == idaapi.NN_call and insn_t.Op1.addr == next_ea:
selfCallEA = next_ea
DEBUG("INTERNAL CALL to next instruction: {0:x}".format(selfCallEA))
DEBUG("LOCAL NORETURN CALL!")
I.local_noreturn = True
if selfCallEA not in RECOVERED_EAS:
DEBUG("Adding new EA: {0:x}".format(selfCallEA))
new_eas.add(selfCallEA)
I.mem_reference = selfCallEA
I.mem_ref_type = CFG_pb2.Instruction.CodeRef
return I, True
for cref in crefs:
DEBUG("Checking code ref {:x}".format(cref))
had_refs = True
fn = getFunctionName(cref)
if is_call:
elfy, fn_replace = isElfThunk(cref)
if elfy:
fn = fn_replace
DEBUG("Found external call via ELF thunk {:x} => {}".format(cref, fn_replace))
if isExternalReference(cref) or elfy:
fn = handleExternalRef(fn)
I.ext_call_name = fn
DEBUG("EXTERNAL CALL: {0}".format(fn))
if doesNotReturn(fn):
return I, True
else:
which_op = manualRelocOffset(I, addr, cref);
setReference(I, which_op, CFG_pb2.Instruction.CodeRef, cref)
if cref not in RECOVERED_EAS:
new_eas.add(cref)
DEBUG("INTERNAL CALL: {0}".format(fn))
elif isUnconditionalJump(insn_t):
if isExternalReference(cref):
fn = handleExternalRef(fn)
I.ext_call_name = fn
DEBUG("EXTERNAL JMP: {0}".format(fn))
if doesNotReturn(fn):
DEBUG("Nonreturn JMP")
return I, True
else:
DEBUG("INTERNAL JMP: {0:x}".format(cref))
I.true_target = cref
#true: jump to where we have a code-ref
#false: continue as we were
if isConditionalJump(insn_t):
I.true_target = crefs[0]
I.false_target = addr+len(inst_bytes)
return I, False
if is_call and isNotCode(next_ea):
DEBUG("LOCAL NORETURN CALL!")
I.local_noreturn = True
return I, True
relo_off = findRelocOffset(addr, len(inst_bytes))
# don't re-set reloc offset if we already set it somewhere
if relo_off != -1:
# check which operand this would be the offset for
which_op = opAtOffset(insn_t, relo_off)
# don't overwrite an offset set by other means
if "IMM" == which_op and not I.HasField("imm_reloc_offset"):
DEBUG("findRelocOffset setting imm reloc offset at {0:x} to {1:x}".format(addr, relo_off))
I.imm_reloc_offset = relo_off
if "MEM" == which_op and not I.HasField("mem_reloc_offset"):
DEBUG("findRelocOffset setting mem reloc offset at {0:x} to {1:x}".format(addr, relo_off))
I.mem_reloc_offset = relo_off
drefs_from_here = idautils.DataRefsFrom(addr)
for dref in drefs_from_here:
had_refs = True
if dref in crefs:
continue
DEBUG("Adding reference because of data refs from {:x}".format(addr))
addDataReference(M, I, addr, dref, new_eas)
if isUnconditionalJump(insn_t):
xdrefs = idautils.DataRefsFrom(dref)
for xref in xdrefs:
DEBUG("xref : {0:x}".format(xref))
# check if it refers to come instructions; link Control flow
if isExternalReference(xref):
fn = getFunctionName(xref)
fn = handleExternalRef(fn)
I.ext_call_name = fn
DEBUG("EXTERNAL CALL : {0}".format(fn))
if isLinkedElf() and not PIE_MODE:
for op in insn_t.Operands:
if op.type == idc.o_imm:
if op.value in drefs_from_here:
continue
# we have an immediate.. check if its in a code or data section
begin_a = op.value
end_a = begin_a + idc.ItemSize(begin_a)
if isInData(begin_a, end_a):
# add data reference
DEBUG("Adding reference because we fixed IMM value")
addDataReference(M, I, addr, begin_a, new_eas)
#elif isInCode(begin_a, end_a):
# add code ref