-
Notifications
You must be signed in to change notification settings - Fork 1
/
func_tails.py
1896 lines (1559 loc) · 63 KB
/
func_tails.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
# For making a quick copy of a function
# func_tails(ea, dict)
# for k, v in dict.items():
# ida_bytes.patch_bytes(int(k), v)
# forceCode(int(k), len(v))
# from exectools import make_refresh
import os
import re
import sys
import ida_funcs, idc, ida_bytes, idautils
from collections import defaultdict
from collections import deque
if not idc:
from idb.idapython import idautils
from di import diida
from exectools import make_refresh
# from function_address_export import _node_format
from helpers import UnPatch
from python3.idc_bc695 import GetFunctionName
from sfcommon import GetFuncStart, forceCode
from sfida.sf_is_flags import IsFlow
from sfida.sf_string_between import string_between
from sftools import eax
from slowtrace_helpers import GetInsnLen, isConditionalJmp, isAnyJmp, GetTarget, isNop, isRet, isCall, \
GetChunkOwners, CreateInsns
from underscoretest import _
refresh_func_tails = make_refresh(os.path.abspath(__file__))
refresh = make_refresh(os.path.abspath(__file__))
class recursion_depth:
def __init__(self, limit):
self.limit = limit
self.default_limit = sys.getrecursionlimit()
def __enter__(self):
sys.setrecursionlimit(self.limit)
def __exit__(self, type, value, traceback):
sys.setrecursionlimit(self.default_limit)
def _node_format(ea):
if isinstance(ea, int):
if HasUserName(ea):
return idc.get_name(ea, idc.calc_gtn_flags(ea, ea))
return hex(ea).replace('0x', '')
return ea
# check_for_update = make_auto_refresh(os.path.abspath(__file__.replace('2', '_helpers')))
def skip_first(gen):
for i, n in enumerate(gen):
if i == 0:
continue
yield n
class FuncTailsError(object):
def __init__(self):
pass
def __str__(self):
return "{}: {}".format(
self.__class__.__name__,
", ".join(
["{}: {}".format(k, ahex(getattr(self, k))) for k in dir(self) if str(k)[0] != '_']
))
# https://stackoverflow.com/questions/40828173/how-can-i-make-my-class-pretty-printable-in-python/66250289#66250289
def __pprint_repr__(self, *args, **kwargs):
if isinstance(kwargs, dict):
if 'indent' in kwargs:
_indent = kwargs['indent']
if _indent:
return self.__str__()
# if _indent: return self._toText()
# return long form output
result = {}
props = [x for x in dir(self) if not x.startswith('_')]
for k in props:
result[k] = getattr(self, k)
return result
class FuncTailsJump(FuncTailsError):
"""External Jump"""
def __init__(self, conditional, frm, to):
self.conditional = conditional
self.frm = frm
self.to = to
class FuncTailsUnusedChunk(FuncTailsError):
"""Unused Chunk"""
def __init__(self, chunk_ea):
self.ea = chunk_ea
class FuncTailsNoppedChunk(FuncTailsError):
"""Unused Chunk"""
def __init__(self, chunk_ea):
self.ea = chunk_ea
class FuncTailsBadTail(FuncTailsError):
"""Unused Chunk"""
def __init__(self, chunk_ea, tail_ea=None):
self.ea = chunk_ea
self.tail_ea = tail_ea
class FuncTailsAdditionalChunkOwners(FuncTailsError):
def __init__(self, chunk_ea, owners):
self.ea = chunk_ea
self.owners = owners
class FuncTailsInvalidTarget(FuncTailsError):
def __init__(self, ea):
self.ea = ea
class FuncTailsNoFunc(FuncTailsError):
def __init__(self, ea):
self.ea = ea
class AdvanceInsnList(object):
"""Docstring for AdvanceInsnList """
def __init__(self, ea, insns=None, insn_count=None, byte_count=None, results=None, refs_from=None, refs_to=None,
flow_refs_from=None, flow_refs_to=None, start_ea=None, end_ea=None):
"""@todo: to be defined
ea
insns
insn_count
byte_count
results
refs_from
refs_to
flow_refs_from
flow_refs_to
start_ea
end_ea
"""
insns = A(insns)
results = A(results)
refs_from = S(refs_from)
refs_to = S(refs_to)
flow_refs_from = S(flow_refs_from)
flow_refs_to = S(flow_refs_to)
# if refs_from is None: refs_from = {}
# if refs_to is None: refs_to = {}
# if flow_refs_from is None: flow_refs_from = {}
# if flow_refs_to is None: flow_refs_to = {}
if isinstance(ea, GenericRange) or isinstance(ea, tuple) and len(ea) == 2:
_s, _e = ea[0], ea[-1]
# print("AdvanceInsnList: {:x} - {:x}".format(_s, _e))
if _e < _s:
_e += _s
insns=[FuncTailsInsn(x) for x in idautils.Heads(_s, _e)]
ea = start_ea = _s
self._list_insns = insns
self._list_insn_count = insn_count
self._list_byte_count = byte_count
self._list_results = results
self._list_refs_from = refs_from
self._list_refs_to = refs_to
self._list_flow_refs_from = flow_refs_from
self._list_flow_refs_to = flow_refs_to
self._list_start_ea = start_ea
self._list_end_ea = end_ea
self._list_ea = ea
self._list_prev_list = None
self._list_next_list = None
self._list_parents = set()
self._list_children = set()
if ea.__class__.__name__ == self.__class__.__name__:
props = [x for x in dir(self) if x.startswith('_list')]
for k in props:
setattr(self, k, getattr(ea, k, None))
@property
def prev(self):
"""
returns self._list_prev_list
"""
return self._list_prev_list
@prev.setter
def prev(self, value):
""" New style classes requires setters for @property methods
"""
self._list_prev_list = value
return self._list_prev_list
@property
def next(self):
"""
returns self._list_next_list
"""
return self._list_next_list
@next.setter
def next(self, value):
""" New style classes requires setters for @property methods
"""
self._list_next_list = value
return self._list_next_list
def addChild(self, value):
""" New style classes requires setters for @property methods
"""
value._list_parents.add(self)
self._list_children.add(value)
return value
def removeChild(self, value):
if value in self._list_children:
self._list_children.remove(value)
value._list_parents.remove(self)
return value
def getChildren(self):
return list(self._list_children)
def getParents(self):
return list(self._list_parents)
@property
def insns(self):
return self._list_insns
@property
def insn_count(self):
return self._list_insn_count
@property
def byte_count(self):
return self._list_byte_count
@property
def results(self):
return self._list_results
@property
def refs_from(self):
return self._list_refs_from
@property
def refs_to(self):
return self._list_refs_to
@property
def flow_refs_from(self):
return self._list_flow_refs_from
@property
def flow_refs_to(self):
return self._list_flow_refs_to
@property
def start_ea(self):
return self._list_start_ea
@property
def start(self):
return self.ea
@property
def end_ea(self):
return self._list_end_ea
@property
def ea(self):
return self._list_ea
@property
def target(self):
return self._list_insns[-1].target
@property
def targets(self):
return list(filter(lambda v, *a: IsValidEA(v), [GetTarget(i.ea) for i in self._list_insns]))
@property
def bytes(self):
return b''.join([insn.bytes for insn in self._list_insns])
def __pprint_repr__(self, *args, **kwargs):
if isinstance(kwargs, dict):
if 'indent' in kwargs:
_indent = kwargs['indent']
if _indent:
return str(self.generic_range())
# if _indent: return self._toText()
# return long form output
result = {}
props = [x for x in dir(self) if x.startswith('_list')]
for k in props:
result[k[6:]] = getattr(self, k)
if self._list_insns:
result['range'] = GenericRange(start=self._list_insns[0].ea, trend=self._list_insns[-1].ea + len(self._list_insns[-1]))
return result
def join(self, visited=None):
if visited is None: visited = set()
def unvisited(ea):
if not isinstance(ea, int):
ea = ea.ea
if ea not in visited:
if debug: print("adding chunk {:#x} to queue".format(ea))
visited.add(ea)
return True
else:
if debug: print("not adding chunk {:#x} to queue".format(ea))
return False
x = self
# yield "loc_{:X}:".format(x.ea)
# print('yielding initial insns')
for i in x.insns:
if unvisited(i):
yield i
if True:
_queue = [child for child in x.getChildren() if unvisited(child)]
while _queue:
item = _queue.pop(0)
for i in item.insns:
if True or i.ea not in visited:
if debug: print("adding insn {:#x} to queue".format(i.ea))
# visited.add(i.ea)
yield i
else:
if debug: print("not adding insn {:#x} to queue".format(i.ea))
_queue = [child for child in item.getChildren() if unvisited(child)] + _queue
else:
if isinstance(x.next, set):
_queue = list(x.next)
while _queue:
item = _queue.pop(0)
for i in item.insns:
if True or i.ea not in visited:
# visited.add(i.ea)
yield i
if item.next:
# print('join: appending {}'.format(item.next))
for x in item.next:
_queue.append(x)
else:
while x.next:
for i in x.next.insns:
if i.ea not in visited:
visited.add(i.ea)
yield i
x = x.next
# def errors(self): return self._list_errors
# __contains__(self, key, /)
# __delitem__(self, key, /)
# __eq__(self, value, /)
# __ge__(self, value, /)
# __getattribute__(self, name, /)
# __getitem__(...)
# __gt__(self, value, /)
# __init__(self, /, *args, **kwargs)
# __iter__(self, /)
# __le__(self, value, /)
# __len__(self, /)
# __lt__(self, value, /)
# __ne__(self, value, /)
# __repr__(self, /)
# __setitem__(self, key, value, /)
### ---
def __len__(self):
return self._list_insns.__len__()
def __getitem__(self, key):
return self._list_insns.__getitem__(key)
def __setitem__(self, key, value):
self._list_insns.__setitem__(key, value)
def __delitem__(self, key):
self._list_insns.__delitem__(key)
def __iter__(self):
return self._list_insns.__iter__()
def __reversed__(self):
return self._list_insns.__reversed__()
def __contains__(self, item):
return self._list_insns.__contains__(item)
def append(self, object):
self._list_insns.append(object)
def clear(self):
self._list_insns.clear()
def copy(self):
return (type(self))(self._list_insns.copy())
def count(self):
return self._list_insns.count()
def extend(self, iterable):
for item in iterable:
self.append(item)
def index(self, value, start=0, stop=9223372036854775807):
self._list_insns.index(value, start, stop)
def insert(self):
self._list_insns.insert()
def pop(self):
self._list_insns.pop()
def remove(self):
self._list_insns.remove()
def reverse(self):
self._list_insns.reverse()
def sort(self):
self._list_insns.sort()
def insert(self, index, object):
self._list_insns.insert(index, object)
def pop(self, index=-1):
return self._list_insns.pop(index)
def remove(self, value):
self._list_insns.remove(value)
### ---
def items(self):
for o in self._list_insns:
yield o.ea, o.insn
def values(self):
return [o.insn for o in self._list_insns]
def keys(self):
return [o.ea for o in self._list_insns]
def labeled_values(self):
return [o.labeled_value for o in self._list_insns]
def generic_range(self):
if not self._list_insns:
return None
return GenericRange(start=self._list_insns[0].ea, trend=self._list_insns[-1].ea + len(self._list_insns[-1]))
def range(self):
if not self._list_insns:
return None
return range(self._list_insns[0].ea, self._list_insns[-1].ea + len(self._list_insns[-1]))
class FuncTailsInsn(object):
"""Docstring for FuncTailsInsn """
def __init__(self, insn=None, ea=None, text=None, size=None, code=None, mnemonic=None, operands=None, comments=None, sp=None, spd=None, warnings=None,
errors=None, chunkhead=None, labels=None,
refs_from=None, refs_to=None, flow_refs_from=None, flow_refs_to=None):
"""@todo: to be defined
:insn_text: @todo
:insn_ea: @todo
:insn_di: @todo
:insn_sp: @todo
:insn_comments: @todo
:insn_warnings: @todo
:insn_errors: @todo
"""
labels = A(labels)
if insn is None or isinstance(insn, int):
if ea is None:
ea = insn
insn=diida(ea)
text=insn
size=MyGetInstructionLength(ea)
# refs_to=set(xrefs_to(ea, filter=lambda x, *a: x.type != fl_F))
if not labels and HasAnyName(ea):
labels.append(idc.get_name(ea))
self._insn_text = text
self._insn_ea = ea
self._insn_sp = sp
self._insn_spd = spd
self._insn_comments = comments
self._insn_warnings = warnings
self._insn_errors = errors
self._insn_code = code
self._insn_operands = operands
self._insn_mnemonic = mnemonic
self._insn_chunkhead = chunkhead
self._insn_labels = labels
self._insn_insn = insn
self._insn_size = size
self._insn_refs_from = S(refs_from)
self._insn_refs_to = S(refs_to)
self._insn_flow_refs_from = S(flow_refs_from)
self._insn_flow_refs_to = S(flow_refs_to)
self._insn_target = None
self._insn_skip = False
self._insn_hide_label = False
self._insn_hide_insn = False
# self._insn_target = GetTarget(ea, failnone=True)
if (isAnyJmpOrCall(ea)):
self._insn_target = GetTarget(ea)
if insn_match(ea, idaapi.NN_mov, idc.o_reg, idc.o_imm):
self._insn_target = GetTarget(ea, failnone=True)
def __str__(self):
return self._insn_text
@property
def bytes(self):
return ida_bytes.get_bytes(self.ea, len(self))
# def __eq__(self, other):
# if isinstance(other, str):
# return self._insn_text == other
def __add__(self, *args, **kwargs):
return str(self).__add__(*args, **kwargs)
def __contains__(self, *args, **kwargs):
return str(self).__contains__(*args, **kwargs)
def __eq__(self, *args, **kwargs):
return str(self).__eq__(*args, **kwargs)
def __format__(self, *args, **kwargs):
return str(self).__format__(*args, **kwargs)
def __ge__(self, *args, **kwargs):
return str(self).__ge__(*args, **kwargs)
# def __getattribute__(self, *args, **kwargs):
# return str(self).__getattribute__(*args, **kwargs)
#
# def __getitem__(self, *args, **kwargs):
# return str(self).__getitem__(*args, **kwargs)
#
def __gt__(self, *args, **kwargs):
return str(self).__gt__(*args, **kwargs)
def __hash__(self, *args, **kwargs):
return str(self).__hash__(*args, **kwargs)
def __iter__(self, *args, **kwargs):
return str(self).__iter__(*args, **kwargs)
def __le__(self, *args, **kwargs):
return str(self).__le__(*args, **kwargs)
# def __len__(self, *args, **kwargs):
# return str(self).__len__(*args, **kwargs)
def __lt__(self, *args, **kwargs):
return str(self).__lt__(*args, **kwargs)
def __mod__(self, *args, **kwargs):
return str(self).__mod__(*args, **kwargs)
def __mul__(self, *args, **kwargs):
return str(self).__mul__(*args, **kwargs)
def __ne__(self, *args, **kwargs):
return str(self).__ne__(*args, **kwargs)
def __repr__(self, *args, **kwargs):
return str(self).__repr__(*args, **kwargs)
def __rmod__(self, *args, **kwargs):
return str(self).__rmod__(*args, **kwargs)
def __rmul__(self, *args, **kwargs):
return str(self).__rmul__(*args, **kwargs)
def capitalize(self, *args, **kwargs):
return str(self).capitalize(*args, **kwargs)
def casefold(self, *args, **kwargs):
return str(self).casefold(*args, **kwargs)
def center(self, *args, **kwargs):
return str(self).center(*args, **kwargs)
def count(self, *args, **kwargs):
return str(self).count(*args, **kwargs)
def encode(self, *args, **kwargs):
return str(self).encode(*args, **kwargs)
def endswith(self, *args, **kwargs):
return str(self).endswith(*args, **kwargs)
def expandtabs(self, *args, **kwargs):
return str(self).expandtabs(*args, **kwargs)
def find(self, *args, **kwargs):
return str(self).find(*args, **kwargs)
def format(self, *args, **kwargs):
return str(self).format(*args, **kwargs)
def format_map(self, *args, **kwargs):
return str(self).format_map(*args, **kwargs)
def index(self, *args, **kwargs):
return str(self).index(*args, **kwargs)
def ljust(self, *args, **kwargs):
return str(self).ljust(*args, **kwargs)
def lower(self, *args, **kwargs):
return str(self).lower(*args, **kwargs)
def lstrip(self, *args, **kwargs):
return str(self).lstrip(*args, **kwargs)
def partition(self, *args, **kwargs):
return str(self).partition(*args, **kwargs)
def replace(self, *args, **kwargs):
return str(self).replace(*args, **kwargs)
def rfind(self, *args, **kwargs):
return str(self).rfind(*args, **kwargs)
def rindex(self, *args, **kwargs):
return str(self).rindex(*args, **kwargs)
def rjust(self, *args, **kwargs):
return str(self).rjust(*args, **kwargs)
def rpartition(self, *args, **kwargs):
return str(self).rpartition(*args, **kwargs)
def rsplit(self, *args, **kwargs):
return str(self).rsplit(*args, **kwargs)
def rstrip(self, *args, **kwargs):
return str(self).rstrip(*args, **kwargs)
def split(self, *args, **kwargs):
return str(self).split(*args, **kwargs)
def splitlines(self, *args, **kwargs):
return str(self).splitlines(*args, **kwargs)
def startswith(self, *args, **kwargs):
return str(self).startswith(*args, **kwargs)
def strip(self, *args, **kwargs):
return str(self).strip(*args, **kwargs)
def swapcase(self, *args, **kwargs):
return str(self).swapcase(*args, **kwargs)
def title(self, *args, **kwargs):
return str(self).title(*args, **kwargs)
def translate(self, *args, **kwargs):
return str(self).translate(*args, **kwargs)
def upper(self, *args, **kwargs):
return str(self).upper(*args, **kwargs)
def zfill(self, *args, **kwargs):
return str(self).zfill(*args, **kwargs)
@property
def text(self):
return self._insn_text
@property
def ea(self):
return self._insn_ea
@property
def sp(self):
return self._insn_sp
@property
def spd(self):
return self._insn_spd
@property
def comments(self):
return self._insn_comments
@property
def warnings(self):
return self._insn_warnings
@property
def errors(self):
return self._insn_errors
@property
def chunkhead(self):
return self._insn_chunkhead
@property
def operands(self):
return self._insn_operands
@property
def code(self):
return self._insn_code
@property
def mnemonic(self):
return self._insn_mnemonic
@property
def labels(self):
return self._insn_labels
@property
def insn(self):
return self._insn_insn
def __len__(self):
return self._insn_size
def add_label(self, label):
self._insn_labels.append(label)
def settext(self, text):
self._insn_text = text
@property
def refs_from(self):
return self._insn_refs_from
@property
def refs_to(self):
return self._insn_refs_to
@property
def flow_refs_from(self):
return self._insn_flow_refs_from
@property
def flow_refs_to(self):
return self._insn_flow_refs_to
@property
def target(self):
return self._insn_target
@property
def label(self):
if self.labels:
return self.labels[-1]
return ''
@property
def skip(self):
"""
returns self._insn_skip
"""
return self.hide_label and self.hide_insn
@skip.setter
def skip(self, value):
""" New style classes requires setters for @property methods
"""
self.hide_label = self.hide_insn = value
@property
def hide_label(self):
"""
returns self._insn_hide_label
"""
return self._insn_hide_label
@hide_label.setter
def hide_label(self, value):
""" New style classes requires setters for @property methods
"""
self._insn_hide_label = value
return self._insn_hide_label
@property
def hide_insn(self):
"""
returns self._insn_hide_insn
"""
return self._insn_hide_insn
@hide_insn.setter
def hide_insn(self, value):
""" New style classes requires setters for @property methods
"""
self._insn_hide_insn = value
return self._insn_hide_insn
@property
def force_labeled_value(self):
_label = None
if self._insn_labels:
_label = self._insn_labels[0]
if not _label:
_label = ean(self._insn_ea)
if not _label:
_label = "lab_{:X}".format(self._insn_ea)
return "{}: {}".format(_label, self._insn_insn)
@property
def force_labeled_indented(self):
_label = None
if self._insn_labels:
_label = self._insn_labels[0]
if not _label:
_label = ean(self._insn_ea)
if not _label:
_label = "lab_{:X}".format(self._insn_ea)
return "{}:\n {}".format(_label, self._insn_insn)
@property
def labeled_value(self):
if len(self._insn_refs_to) or len(self._insn_labels):
_label = None
if self._insn_labels:
_label = self._insn_labels[0]
if not _label:
_label = ean(self._insn_ea)
return "{}: {}".format(_label, self._insn_insn)
return "{}".format(self._insn_insn)
@property
def labeled_indented(self):
if len(self._insn_refs_to) or len(self._insn_labels):
_label = None
if self._insn_labels:
_label = self._insn_labels[0]
if not _label:
_label = ean(self._insn_ea)
return "{}:\n {}".format(_label, self._insn_insn)
return " {}".format(self._insn_insn)
@property
def indented(self):
result = []
if self.skip:
return ''
if not self.hide_label and self.label:
result.append("{}:".format(self.label))
if not self.hide_insn:
result.append(" {}".format(self._insn_insn))
return '\n'.join(result)
@property
def unlabeled_indented(self):
return " {}".format(self._insn_insn)
# https://stackoverflow.com/questions/40828173/how-can-i-make-my-class-pretty-printable-in-python/66250289#66250289
def __pprint_repr__(self, *args, **kwargs):
if isinstance(kwargs, dict):
if 'indent' in kwargs:
_indent = kwargs['indent']
if _indent:
return self.labeled_value
# if _indent: return self._toText()
# return long form output
result = {}
props = [x for x in dir(self) if x.startswith('_insn')]
for k in props:
result[k[6:]] = getattr(self, k)
result['labeled_value'] = self.labeled_value
return result
def func_tails(funcea=None, returnErrorObjects=False, returnOutput=False, returnPretty=False,
code=True, patches=None, dead=False, showEa=False,
showUnused=False, ignoreInt=False, showNops=False, output=None,
quiet=False, removeLabels=True, disasm=False, externalTargets=None,
returnAddrs=False, returnFormat=None, fmt=None, fmtLabel=None,
showComments=True, **kwargs):
"""
func_tails
@param funcea: any address in the function
@param dead: dead code removal
"""
# check_for_update()
funcea = eax(funcea)
func = ida_funcs.get_func(funcea)
if not func:
return [FuncTailsNoFunc(funcea)] if returnErrorObjects else ["[error] nofunc at 0x{:x}".format(funcea)]
else:
funcea = func.start_ea
if fmt is None:
fmt = ' {}'
if fmtLabel is None:
fmt_label = '{}:'
else:
fmt_label = fmtLabel
errors = []
errorObjects = []
decompiled = []
pretty = []
decompiled_heads = defaultdict(list)
relabel = dict()
# decompiled_insns = []
def relabel_line(line):
for search, replace in relabel.items():
# dprint("[outi] search, replace")
# print("[outi] search: {}, replace: {}".format(search, replace))
line = line.replace(search, replace)
return line
def outi(line):
r = []
if line:
for l in line.split('\n'):
if l.strip().startswith('nop'):
continue
r.append(relabel_line(l))
if returnPretty:
pretty.extend(r)
else:
[printi(x) for x in r]
def out(line, head=None, ft_insn=None):
if head:
if ft_insn:
ft_insn.settext(line)
decompiled_heads[head].append(ft_insn if ft_insn else line)
else:
if not quiet:
pass
if isListlike(decompiled):
pass
# decompiled.append(line)
# decompiled_insns.append(line)
l = string_between('; [', '', line)
if l and output:
output.append("[" + l)
return line
def remove_labels(decompiled):
labels = []
if isListlike(decompiled):
tmp = "\n".join(decompiled)
globals()['decompiled'] = tmp