-
Notifications
You must be signed in to change notification settings - Fork 1
/
slowtrace2.py
5355 lines (4767 loc) · 263 KB
/
slowtrace2.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
from __future__ import print_function
import colorsys
import idc
import re
from static_vars import static_vars
from queue import Queue
import traceback
import inspect
import subprocess
import textwrap
from static_vars import static_vars
from superglobals import *
from attrdict1 import SimpleAttrDict
# _import("progress")
# _import("from rle import RunLengthList")
from rle import RunLengthList
# # from sets import set
# from circularlist import CircularList
if not idc:
# import obfu
# from di import *
# from helpers import *
# from membrick import *
# from nasm import *
# from obfu_helpers import *
# from ranger import GenericRanger
# from sfcommon import *
# from sftools import fix_links_to_reloc, SmartAddChunkImpl, smartadder, MyMakeUnkn, MyMakeUnknown, MyMakeFunction, \
# analyze, dinjasm
# from slowtrace2_helpers import isSegmentInXrefsTo, opTypeAsName, traceBackwards, ForceFunction, forgeAheadWithCode, \
# cleanLine, ShowAppendFchunk, EndOfContig, ExndOfFlow, remake_func, fix_non_func, reloc_name, hex_to_colorsys_rgb, \
# colorsys_rgb_to_rgb, rgb_to_int
# from slowtrace_helpers import ZeroFunction, IsFunc_, IsFuncHead, IsSameFunc, GetChunkOwner, GetChunkEnd, InsnLen, \
# InsnRange, SetSpDiffEx, IsChunked, GetFuncSize, SetSpd, isAnyJmp, isCall
# from start import *
# from string_between import string_between_repl
from test import *
if six.PY2:
itertools.zip_longest = itertools.izip_longest
# from commenter import Commenter
# def refresh(filepath = __file__, _globals = None, _locals = None):
# print("Reading {}...".format(filepath))
# if _globals is None:
# _globals = globals()
# _globals.update({
# "__file__": filepath,
# "__name__": "__main__",
# })
# with open(filepath, 'rb') as file:
# exec(compile(file.read(), filepath, 'exec'), _globals, _locals)
def is_healed_col(c): return is_hldchk_col(c) & c >> 16 in (1, 0x14)
def is_checkd_col(c): return is_hldchk_col(c) & c >> 16 in (1, 0x28)
def is_hldchk_col(c): return is_hldchk_msk(c) & c >> 16 == 1
def is_hldchk_msk(c): return c & 0xc2ffff == 0x000128
get_byte = idc.get_wide_byte
# with open(os.path.dirname(__file__) + os.sep + 'refresh.py', 'r') as f: exec (
# compile(f.read().replace('__BASE__', os.path.basename(__file__).replace('.py', '')).replace('__FILE__', __file__),
# __file__, 'exec'))
from exectools import execfile, make_refresh
_refresh_slowtrace2 = make_refresh(os.path.abspath(__file__))
_refresh_slowtrace_helpers = make_refresh(os.path.abspath(__file__.replace('2', '_helpers')))
def refresh_slowtrace2():
_refresh_slowtrace_helpers()
_refresh_slowtrace2()
refresh_func_tails()
refresh_circular()
if False:
if not hasglobal('_called_fix_jmp_loc_ret'):
refresh_slowtrace_helpers()
FixJmpLocRet()
if debug: setglobal('_called_fix_jmp_loc_ret', True)
if False:
if not hasglobal('_called_fix_common_obfu_5'):
debug=0
l = [x for x in FunctionsPdata() if not IsNiceFunc(x)]
UnpatchUnused()
# for ea in FindInSegments('55 48 8d 2d ?? ?? ?? ?? 48 87 2c 24'):
# for ea in FindInSegments('55 48 8d 2d ?? ?? ?? ?? 48'):
for ea in FindInSegments('55 48 8d 2d'):
if IsCode_(ea):
EaseCode(ea, forceStart=1)
count = 10
while obfu._patch(ea) and count > 0:
count -= 1
if debug: setglobal('_called_fix_common_obfu_5', True)
check_for_update_1 = make_auto_refresh(os.path.abspath(__file__.replace('2', '_helpers')))
check_for_update_2 = make_auto_refresh(os.path.abspath(__file__))
check_for_update = lambda: (check_for_update_1(), check_for_update_2())
def auto_refresh(fn):
check = make_auto_refresh(fn)
def decorate(func):
check()
return func
return decorate
re_version = re.compile(r'gta(s[ct]).*?[^0-9](\d{3,4})[^0-9]')
if 'get_idb_path' not in globals():
_source = 'sc'
_build = '2372'
else:
for __source, __build in re.findall(re_version, get_idb_path()):
_source = __source
_build = __build
class SlowtraceSingleStep(Exception):
"""ChunkFailure.
"""
pass
sprint = print
def indent(n, s, skipEmpty=True, splitWith='\n', joinWith='\n', n2plus=None, skipFirst=False, stripLeft=False, width=70, indentString=' ', firstIndent=None):
if firstIndent is None:
firstIndent = n
if isString(s):
s = s.replace('\r', '').split(splitWith)
if width and width - n > 0:
assert isinstance(width, int)
r = []
if skipFirst:
r.append(s[0][0:width])
s[0] = s[0][width:]
if not s[0]:
s.pop(0)
r.extend([textwrap.wrap(line, width=width - n) for line in s])
s = _.flatten(r)
result = []
for i, line in enumerate(s):
if i == 1 and n2plus is not None:
n = n2plus
if isinstance(line, list):
print("[indent] line: {}".format(line))
continue
if stripLeft:
line = line.lstrip()
if skipFirst and not i:
result.append(line)
continue
if firstIndent is not None and not i:
result.append(indentString * firstIndent + line)
continue
if not skipEmpty or line.rstrip():
if isinstance(n, str):
result.append(n + line)
elif isinstance(n, int):
result.append(indentString * n + line)
if joinWith:
return joinWith.join(result)
return result
debug = getglobal('debug', 0)
emu_stacks_fail = getglobal('emu_stacks_fail', type, set)
def itypes(pattern):
keys = [k for k in ida_allins.__dict__ if re.match(r'(?:NN_)?' + pattern, k, re.I)]
return [getattr(ida_allins, k, -1) for k in keys]
def IsStackOperand(ea, ignoreLeaDisplacement=0):
if isinstance(ea, ida_ua.insn_t):
insn = ea
else:
insn = ida_ua.insn_t()
inslen = ida_ua.decode_insn(insn, get_ea_by_any(ea))
if inslen == 0:
return None
# lea rsp, [rbp+80h]
if ignoreLeaDisplacement:
if insn.itype == 0x5c: # lea
if insn.ops[0].type == ida_ua.o_reg and \
insn.ops[1].type == ida_ua.o_displ:
return False
# if insn.itype in itypes(r'(push|pop)'): return True
if insn.itype in [0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x2c2]:
# printi(hex(ea), 'insn.itype', get_itype_string(insn.itype))
return True
# xxx rsp, x
if insn.ops[0].type == ida_ua.o_reg and insn.ops[0].reg == 4:
if insn.ops[1].type == ida_ua.o_imm and insn.itype in [ida_allins.NN_test]:
Commenter(ea).add("Warning: stack-alignment obfu")
return False
return True
return False
def vimlike(ea=None, **kwargs):
"""
open de-chunked asm listing in vim
@param ea: linear address
"""
ea = GetFuncStart(eax(ea))
return slowtrace2(ea, removeFuncs=1, noObfu=1, silent=1, vim=-1, modify=0, ignoreStack=1, ignoreExtraStack=1, fatalStack=0, **kwargs)
def vim(ea=None, **kwargs):
"""
open de-chunked asm listing in vim
@param ea: linear address
"""
ea = GetFuncStart(eax(ea))
slowtrace2(ea, removeFuncs=1, noObfu=1, silent=1, vim=1, modify=0, ignoreStack=1, ignoreExtraStack=1, fatalStack=0, **kwargs)
def vimr(ea=BADADDR):
if ea == BADADDR:
ea = ScreenEA()
slowtrace2(ea, removeFuncs=1, noObfu=1, silent=1, vim=1, modify=0, reloc=1, force=1)
# idaapi.add_hotkey("Shift-Alt-S", smartadder)
def remake(ea):
return remake_func(ea)
# def MakeFunction(start, end=ida_idaapi.BADADDR):
# return ida_funcs.add_func(start, end)
def retrace_noexcept(address=0, live=False):
if address == 0:
address = ScreenEA()
if not IsFunc_(address) and not add_func(address) and not ForceFunction(address):
return
ea = address
while True:
slowtrace2(ea, color="#224", removeFuncs=1, silent=1, live=live)
ida_auto.auto_wait()
slowtrace2(address, color="#224", removeFuncs=1, silent=1, live=live)
ida_auto.auto_wait()
break
def reloc(address=0, live=False, force=False, color="#224"):
if address == 0:
address = ScreenEA()
if not ForceFunction(address):
printi("[warn] reloc: couldn't force function at {:x}".format(address))
return
ea = address
count = -1
while True:
try:
count += 1
if force and count > 0:
return
# idc.set_color(address, CIC_ITEM, ~idc.get_color(address, CIC_ITEM) & 0xffffff)
slowtrace2(ea, cursor=1, color=color, removeFuncs=1, silent=1, live=live, reloc=1, force=force, modify=count)
ida_auto.auto_wait()
break
except RelocationPatchedError as e:
pass
except RelocationStackError as e:
if count > 1:
return
except RelocationInvalidStackError as e:
if count > 1:
return
except KeyboardInterrupt as e:
printi("******* KEYTHINGY!! ********")
raise e
except:
if count > 1:
return
ida_auto.auto_wait()
def follow_call_thunks(ea = 0):
if ea == 0:
ea = idc.get_screen_ea()
count = 0
while idc.get_wide_byte(ea) == 0xe8:
ea = ea + 5 + MakeSigned(idc.get_wide_dword(ea + 1), 32)
count += 1
return ea, count
def stopped():
return os.path.exists('e:/git/ida/stop')
@static_vars(history=[])
@perf_timed()
def retrace_list(address, pre=None, post=None, recolor=0, func=0, color="#280c01", spd=0, tails=0, dual=0, jump=0, zero=0, unpatch=0, chunk=False, *args, **kwargs):
global later
# if address == later:
# for ea in [x for x in later if isJmp(x)]: later.remove(ea)
if address is None:
return
if stopped():
printi("*** STOP ***")
return
skipped = list()
retrace_list.history = []
TraceDepth._depth = 0
def fail(ea, post):
if post:
post = list(post)
for _post in post:
if callable(_post):
_post(ea)
def success(ea, post):
return fail(ea, post)
def color_thunks():
if ea not in skipped:
l = ''
if HasUserName(ea):
l = GetTrueName(ea)
skipped.append((ea, l))
retrace_list_thunk_colors = gradient("#280c01", "#643700", len(skipped))
for i, x in enumerate(skipped):
addr, label = x
Wait()
if func:
if addr == ea:
r = MyMakeFunction(addr)
else:
r = MyMakeFunction(addr, IdaGetInsnLen(addr))
if not r:
printi("{} MyMakeFunction(0x{:x}) returned {}".format(i, addr, r))
if IsFuncHead(addr):
idc.set_color(addr, CIC_FUNC, hex_to_rgb_dword(retrace_list_thunk_colors[i]))
else:
idc.set_color(addr, CIC_ITEM, hex_to_rgb_dword(retrace_list_thunk_colors[i]))
LabelAddressPlus(addr, label)
def skip(x):
if not IsValidEA(x):
return
l = ''
if HasUserName(x):
l = GetTrueName(x)
skipped.append((x, l))
if 0:
if not recolor:
ZeroFunction(x, 1)
# retrace_list_thunk_colors = gradient("#280c01", "#662222", 6)
if not recolor:
p = ProgressBar(len(address), len(address))
p.always_print = True
good = 0
bad = 0
for i, ea in enumerate([x for x in list(address) if IsValidEA(x)]):
if not recolor:
p.update(good, bad)
if len(retrace_list.history) <= i:
retrace_list.history.append(ea)
else:
retrace_list.history[i] = ea
rv = None
pre_tried = []
if pre is not None:
_unchanged_hash_count = 0
_new_hash = None
_last_hash = None
pre = list(pre)
for _pre in pre:
if callable(_pre):
pre_tried.append(_pre.__name__)
if _new_hash is not None:
if _new_hash == _last_hash:
_unchanged_hash_count += 1
else:
_unchanged_hash_count = 0
_last_hash = _new_hash
try:
printi("*****")
printi("** pre: [{}] {}-{} for {}".format(_pre.__name__, _unchanged_hash_count, hex(_last_hash), idc.get_name(ea, ida_name.GN_VISIBLE)))
_pre(ea)
printi("*****")
try:
rv = retrace(SkipJumps(ea), chunk=chunk, **kwargs)
_new_hash = GetFuncHash(ea)
if rv == 0:
printi("********** SOLVED {} **********".format(idc.get_name(ea), ida_name.GN_VISIBLE))
printi("********** SOLVED {} **********".format(idc.get_name(ea), ida_name.GN_VISIBLE))
printi("********** SOLVED {} **********".format(idc.get_name(ea), ida_name.GN_VISIBLE))
printi("********** SOLVED {} **********".format(idc.get_name(ea), ida_name.GN_VISIBLE))
printi("pre_tried: {}".format(", ".join(pre_tried)))
address.remove(ea)
break
except Exception as e:
printi("**** pre inner: Exception: {}: {}".format(e.__class__.__name__, str(e)))
except Exception as e:
printi("** pre: Exception: {}: {}".format(e.__class__.__name__, str(e)))
_new_hash = GetFuncHash(ea)
if pre is not None:
if rv != 0:
fail(ea, post)
printi("########## FAILED {} ##########".format(idc.get_name(ea), ida_name.GN_VISIBLE))
printi("########## FAILED {} ##########".format(idc.get_name(ea), ida_name.GN_VISIBLE))
printi("########## FAILED {} ##########".format(idc.get_name(ea), ida_name.GN_VISIBLE))
printi("########## FAILED {} ##########".format(idc.get_name(ea), ida_name.GN_VISIBLE))
if rv == 0:
success(ea, post)
continue
try:
skipped.clear()
except AttributeError:
# py2
del skipped[:]
# if not recolor:
# p.update_good(good)
# p.update_bad(bad)
# p.update(i)
try:
# sk = SkipJumps(ea, skipShort=0, skipCalls=0, iteratee=lambda x, *a: skip(x))
# ValidateEA(sk)
sk = ea
except AdvanceFailure as e:
printi("AdvanceFailure: {}".format(str(e)))
raise
# printi("[retrace_list] SkipJumps::AdvanceFailure {}".format('\n'.join(e.args)))
# if 'unpatch_func2' in globals():
# skipped.reverse()
# for x in skipped:
# unpatch_func2(x[0], unpatch=1)
# return
try:
# printi("num: {}".format(i))
# if idc.get_segm_name(ea) == '.text' and idc.get_func_attr(ea, idc.FUNCATTR_FLAGS) & FUNC_LIB == 0:
if jump:
idc.jumpto(sk)
if unpatch:
# UnpatchFunc(sk)
unpatch_func(sk)
if zero:
ZeroFunction(sk)
if not recolor:
MyMakeFunction(sk)
if not recolor:
rv = retrace(sk, chunk=chunk, **kwargs)
# msg = ("retrace returned {} for {:x}".format(hex(rv), sk))
# printi(msg)
# if chunk:
# yield msg
if rv != 0:
fail(ea, post)
if rv == 0:
success(ea, post)
if recolor or rv == 0:
# printi("*** GOOD *** {:x}".format(sk))
if ea in address:
address.remove(ea)
good += 1
if recolor and skipped:
skipped.reverse()
color_thunks()
if func:
MyMakeFunction(sk)
if tails:
func_tails(sk, externalTargets=externalTargets, extra_args=kwargs)
if spd:
_fix_spd_auto(sk)
continue
else:
pass
# if not recolor:
# if dual:
# for addr in Chunks(sk):
# fix_dualowned_chunk(addr[0])
# ZeroFunction(ea)
except RelocationDupeError:
continue
except RelocationStackError as e:
if ~str(e).find('incorrect SpDiff 0x0'):
for addr in Chunks(sk):
fix_dualowned_chunk(addr[0])
else:
fail(ea, post)
continue
# ZeroFunction(sk)
except AdvanceFailure as e:
printi("AdvanceFailure: {}".format(str(e)))
fail(ea, post)
raise
except AttributeError as e:
raise
# except Exception as e:
# printi("* pre outer: Exception: {}: {}".format(e.__class__.__name__, str(e)))
# fail(ea, post)
# pass
bad += 1
def iter_retrace_list(address, recolor=0, func=0, color="#280c01", spd=0, tails=0, dual=0, jump=0, zero=0, unpatch=0, chunk=False, *args, **kwargs):
if address is None:
return
skipped = list()
def skip(x):
l = ''
if HasUserName(x):
l = GetTrueName(x)
skipped.append((x, l))
if 0:
if not recolor:
ZeroFunction(x, 1)
# retrace_list_thunk_colors = gradient("#280c01", "#662222", 6)
good = 0
bad = 0
for i, ea in enumerate([x for x in list(address) if IsValidEA(x)]):
# for ea in address[0:]:
try:
skipped.clear()
except AttributeError:
# py2
del skipped[:]
try:
sk = SkipJumps(ea, skipShort=0, iteratee=lambda x, *a: skip(x))
ValidateEA(sk)
except AdvanceFailure as e:
print("[retrace_list] SkipJumps::AdvanceFailure {}".format('\n'.join(e.args)))
if 'unpatch_func2' in globals():
skipped.reverse()
for x in skipped:
unpatch_func2(x[0], unpatch=1)
try:
# printi("num: {}".format(i))
# if idc.get_segm_name(ea) == '.text' and idc.get_func_attr(ea, idc.FUNCATTR_FLAGS) & FUNC_LIB == 0:
if jump:
idc.jumpto(sk)
if unpatch:
UnpatchFunc(sk)
if zero:
ZeroFunction(sk)
MyMakeFunction(sk)
output = []
rv = retrace(sk, output=output, **kwargs)
msg = ("retrace returned {} for {:x}".format(hex(rv), sk))
yield [msg] + output
except RelocationStackError as e:
if ~str(e).find('incorrect SpDiff 0x0'):
for addr in Chunks(sk):
fix_dualowned_chunk(addr[0])
else:
continue
# ZeroFunction(sk)
except AdvanceFailure as e:
printi("AdvanceFailure: {}".format(str(e)))
pass
bad += 1
def RecreateFunctionThunks(ea=None):
"""
RecreateFunctionThunks
@param ea: linear address
"""
if isinstance(ea, list):
return [RecreateFunctionThunks(x) for x in ea]
def helper(x, *a):
if IsFunc_(x):
unpatch_func2(x, unpatch=1)
idc.del_func(x)
idc.auto_wait()
UnpatchUntilChunk(x)
# ForceFunction(x)
ea = eax(ea)
jumps = SkipJumps(ea, returnJumps=1)
target = SkipJumps(ea)
jumps = _.uniq(jumps)
print("[RecreateFunctionThunks] jumps: {} target: {:x}".format(hex(jumps), target))
for addr in jumps:
helper(addr)
for addr in jumps:
retrace(addr, thunk=1)
if isJmp(addr):
jumps.append(GetTarget(addr))
def retrace_add_chunks(ea=None, **kwargs):
return retrace_list(ea, removeFuncs=1, noObfu=1, modify=0, adjustStack=1, appendChunks=1, once=1, **kwargs)
def retrace_skip_jumps(ea=None, **kwargs):
return retrace_list(ea, removeFuncs=1, noObfu=1, modify=0, adjustStack=1, applySkipJumps=1, once=1, **kwargs)
def retrace_unpatch(address, **kwargs):
clear();
# refresh_slowtrace2();
retrace_list(address, applySkipJumps=0, forceRemoveChunks=0, once=1, pre=[GetFuncName, unpatch_func2, unpatch_func, ida_retrace, ZeroFunction, unpatch_func2, unpatch_func, ZeroFunction, unpatch_func2, unpatch_func, ZeroFunction], **kwargs)
def retrace(*args, **kwargs):
rv = _retrace(*args, **kwargs)
if rv == 0:
ea = eax(_.first(args, default=None))
done2.add(ea)
return rv
def _retrace(address=None, color="#280c01", no_hash=False, _ida_retrace=False, no_func_tails=False, retails=False, redux=False, unpatchFirst=False, unpatch=False, once=False, recreate=False, chunk=False, noFixChunks=False, **kwargs):
if isinstance(address, list):
return [retrace(x, **kwargs) for x in address]
externalTargets = defaultglobal('externalTargets', set())
global warn
# dprint("[retrace] args, kwargs")
if idc.batch(0):
printi("*** Batch Was enabled ***")
if debug: printi("retrace called for {}".format(ahex(address)))
# TODO: check calling stack, and reset depth if we were called from the command "line"
address = eax(address)
if IsValidEA(address):
tried2.add(address)
start_address = address
with TraceDepth() as _depth:
# printi("[retrace] args:{}, kwargs:{}".format(args, kwargs))
funcea = GetFuncStart(address)
# dprint("[retrace] funcea")
if debug: print("[retrace] funcea: {:#x}".format(funcea))
if funcea != idc.BADADDR:
address = funcea
# dprint("[retrace] address")
if debug: print("[retrace] address: {:#x}".format(address))
applySkipJumps = kwargs.get('applySkipJumps', False)
skipJumps = kwargs.get('skipJumps', True)
if skipJumps:
address = SkipJumps(address, skipNops=1, skipObfu=1, skipCalls=False, includeStart=True, includeEnd=False, apply=applySkipJumps, iteratee=lambda ea, i, *a: MakeThunk(ea))
# elif ea + IdaGetInsnLen(ea) < GetFuncEnd(ea):
# mnem = IdaGetMnem(ea)
# if mnem and mnem.startswith('jmp'):
# target = GetTarget(ea)
# if not IsSameChunk(target, ea):
# # printi(["FixThunks", hex(ea), GetFuncName(ea)])
# SetFuncEnd(ea, ea + MyGetInstructionLength(ea))
start_address = address
# depth = kwargs.get('depth', 0)
#
# what has this done for us lately
# if not 'last_retrace' in globals() or isinstance(globals()['last_retrace'], int):
# globals()['last_retrace'] = [hex(address)]
# else:
# globals()['last_retrace'].insert(0, indent(_depth, ' ', hex(address)))
if not IsFuncHead(address) and not ForceFunction(address) and not IsFuncHead(address):
printi("[retrace] return [warn] couldn't force function at {:x}".format(address))
return -1
if _ida_retrace:
ida_retrace(address, calls=0, **kwargs)
# if IsNiceFunc(address) and not func_tails(address, quiet=1, returnErrorObjects=1, **(_.pick(kwargs, 'ignoreInt'))):
# # insn_match(ea, idaapi.NN_xchg, (idc.o_reg, 5), (idc.o_phrase, 4), comment='xchg [rsp], rbp')
# return 0
if recreate:
RecreateFunction(funcea)
rv = None
funcea_ori = funcea
if retails or redux:
funcea = SkipJumps(funcea, skipCalls=False)
if retails:
output = None
ft = func_tails(funcea, quiet=1, output=output, externalTargets=externalTargets, extra_args=kwargs, **(_.pick(kwargs, 'ignoreInt')))
if ft:
printi('\n'.join(ft))
RecreateFunction(funcea)
ft = func_tails(funcea, quiet=1, output=output, externalTargets=externalTargets, extra_args=kwargs, **(_.pick(kwargs, 'ignoreInt')))
if ft:
printi('\n'.join(ft))
if not ft:
if not redux:
rv = _fix_spd_auto(funcea)
return rv
if redux:
try:
if (retails and rv == 0) or retrace(funcea, vimlike=1, once=1, **kwargs) == 0:
printi("{:x} vimlike retrace: {}".format(funcea, 0))
_fix_spd_auto(funcea)
if IsFuncSpdBalanced:
printi("{:x} SpdBalanced: {}".format(funcea, 'ok'))
ft = func_tails(funcea, quiet=1, externalTargets=externalTargets, extra_args=kwargs, **(_.pick(kwargs, 'ignoreInt')))
if ft:
printi("{:x} func_tails: {}".format(funcea, "\n".join(ft)))
else:
printi("{:x} func_tails: {}".format(funcea, 'clean'))
return 0
except AdvanceFailure as e:
printi("{:x} AdvanceFailure: {}".format(funcea, e))
locs = SkipJumps(start_address, returnJumps=1, skipCalls=False)
locs.append(SkipJumps(start_address))
for ea in locs:
idc.del_func(ea)
UnpatchUn()
SkipJumps(start_address, skipCalls=False, iteratee=lambda x, *a: idc.add_func(x, EaseCode(x)))
if unpatchFirst:
unpatch_func2(funcea, unpatch=1)
ZeroFunction(funcea)
if idc.get_func_flags(funcea) & idc.FUNC_FAR:
# printi("[info] removed FUNC_FAR from {:x}".format(funcea))
SetFuncFlags(funcea, lambda f: f & ~(idc.FUNC_FAR | idc.FUNC_USERFAR))
ea = address
count = -1
rv = 0
count_limit = 3
last_hash = None
_hash = None
patchResults = []
last_error = None
extra_args = dict()
extra_args.update(kwargs)
while count < count_limit:
address = SkipJumps(address, skipCalls=False, includeStart=True, includeEnd=False, apply=applySkipJumps, iteratee=lambda ea, *a: MakeThunk(ea))
num_chunks = GetNumChunks(address)
if num_chunks > 100:
kwargs['noResume'] = True
if patchResults: # patches or rv != last_rv:
if count_limit < 50:
if (count_limit - count) < 3:
count_limit = count + 3
patchResults = []
count += 1
try:
if os.path.exists('e:/git/ida/stop'):
printi("*** STOP ***")
return
last_rv = rv
last_hash = _hash
if not noFixChunks:
if debug: print("calling FixChunks #1 at {:#x}".format(ea))
FixChunks(ea, leave=ea)
warn = 0
traceOutput = []
patches = 0
# slvars.rsp_diff was none
if not no_hash:
_old_hash = GetFuncHash(ea)
patchResults = []
spdList = []
if debug: setglobal('spdList', spdList)
try:
# print("count #{}/{}".format(count, count_limit))
spdList = []
if debug: setglobal('spdList', spdList)
rv = slowtrace2(ea, color=color, returnPatches=patchResults, returnOutput=traceOutput, spdList=spdList, **kwargs)
except AdvanceReverse as e:
raise
spdList = []
if debug: setglobal('spdList', spdList)
rv = slowtrace2(e.args[0], color=color, returnPatches=patchResults, returnOutput=traceOutput, spdList=spdList, **kwargs)
_new_hash = GetFuncHash(ea)
if not no_hash and _old_hash == _new_hash:
# printi("hash stayed at {:x}".format(_new_hash))
if not patchResults:
# printi("no patches")
if rv == 0:
if spdList:
# spd = _fix_spd_auto(SkipJumps(ea)) != 0
addresses = set()
last_addresses = set()
for r in range(1000):
if r > 9 and r % 10 == 0:
if len(last_addresses) and len(last_addresses.union(addresses)) == len(last_addresses.intersection(addresses)):
printi("_fix_spd might be in an endless loop")
break
last_addresses = addresses.copy()
printi("_fix_spd(spdList) attempt {}".format(r))
if not _fix_spd(spdList, addresses):
# printi("_fix_spd(spdList) failed")
break
if not HasUserName(ea):
LabelAddressPlus(ea, "_{}".format(ean(ea)))
else:
if not once:
if kwargs.get('noSti', None):
printi("trying without noSti")
spdList = []
if debug: setglobal('spdList', spdList)
rv = slowtrace2(ea, color=color, returnPatches=patchResults, returnOutput=traceOutput, spdList=spdList, **(_.omit(extra_args, 'noSti')))
if rv != 0 and kwargs.get('noObfu', None):
printi("trying without noSti/noObfu")
spdList = []
if debug: setglobal('spdList', spdList)
rv = slowtrace2(ea, color=color, returnPatches=patchResults, returnOutput=traceOutput, spdList=spdList, **(_.omit(extra_args, 'noSti', 'noObfu')))
# return rv
if once:
if rv != 0 and unpatch:
UnpatchFunc(ea)
return retrace(ea, once=once, **kwargs)
if rv == 0:
if spdList:
# spd = _fix_spd_auto(SkipJumps(ea)) != 0
addresses = set()
last_addresses = set()
for r in range(1000):
if r > 9 and r % 10 == 0:
if len(last_addresses) and len(last_addresses.union(addresses)) == len(last_addresses.intersection(addresses)):
printi("_fix_spd might be in an endless loop")
break
last_addresses = addresses.copy()
printi("_fix_spd(spdList) attempt {}".format(r))
if not _fix_spd(spdList, addresses):
break
return rv
for r in patchResults:
# pp(r)
patches += 1
for r in traceOutput:
if re.match(r""".*(slvars.rsp_diff|couldn't create instruction|\[warn]|unexpected stack change)""", r):
# pp(r)
patches += 1
if rv != 0: printi("slowtrace returned 0x{:x}".format(rv))
ft_patches = 0
if not no_func_tails:
ft = func_tails(funcea, returnErrorObjects=1, quiet=1, externalTargets=externalTargets, **(_.pick(extra_args, 'ignoreInt')))
if ft: printi("func_tails returned {}".format(len(ft)))
if ft:
# ft = func_tails(ft)
printi("fix_func_tails({}, {})".format(pph(_.pluck(ft, '__str__')), _.pick(extra_args, 'ignoreInt')))
fft_ret = fix_func_tails(ft, extra_args)
if isinstance(fft_ret, int):
ft_patches += fft_ret
printi("fix_func_tails returned: {}".format(fft_ret))
if fft_ret == "int":
printi("[retrace] return fix_func_tails return 'int'")
return rv
if (no_hash or _old_hash == _new_hash) and rv != 0:
if rv != 0 and unpatch:
UnpatchFunc(ea)
printi("[retrace] return finishing as hash stayed at {:x}".format(_new_hash))
return rv
if ft_patches:
printi("***** RERUNNING DUE TO FIX_FUNC_TAILS *****")
if patches:
printi("***** RERUNNING DUE TO PATCHES|WARNING MESSAGES *****")
if ft_patches or patches:
count += 1
continue
if rv == 0 and (no_hash or _old_hash == _new_hash):
# if last_rv == 0:
# if warn:
# if count < count_limit - 1:
# printi("***** RERUNNING DUE TO WARNING MESSAGES *****")
# count = count_limit - 1
# continue
# # ft = func_tails(funcea, returnErrorObjects=1, quiet=1, externalTargets=externalTargets)
# if not no_func_tails and ft:
# if not IsFunc_(funcea):
# printi("0x{:x} is no longer a function, switching to 0x{:x}".format(funcea, address))
# funcea = address
# ft = func_tails(funcea, returnErrorObjects=0, quiet=1, externalTargets=externalTargets, extra_args=extra_args)
# if not no_func_tails and ft:
# printi('\n'.join([str(x) for x in ft]))
# printi('returning -1')
# return -1
if spdList:
# spd = _fix_spd_auto(SkipJumps(ea)) != 0
addresses = set()
last_addresses = set()
for r in range(1000):
if r > 9 and r % 10 == 0:
if len(last_addresses) and len(last_addresses.union(addresses)) == len(last_addresses.intersection(addresses)):
printi("_fix_spd might be in an endless loop")
break
last_addresses = addresses.copy()
printi("_fix_spd(spdList) attempt {}".format(r))
if not _fix_spd(spdList, addresses):
break
printi("[retrace] return hash eq")
return rv
except RelocationUnpatchRequest as e:
printi("[retrace] return slowtrace threw {} {}".format(e.__class__.__name__, str(e)))
# UnpatchFunc(ea)
return -1
pass
# except AdvanceFailure as e:
# printi("retrace caught {} {}".format(e.__class__.__name__, str(e)))
# dontraise = True
# sb = string_between('advance past ', '', str(e)) or \
# string_between('create instruction at ', '', str(e))
# if sb:
# sbi = int(sb, 16)
# for x in range(sbi, sbi+8):
# if idc.get_wide_dword(x) == 0:
# dontraise = True
# printi("would have reverted dword at 0x{:x}".format(x))
# # UnPatch(sbi, x+4)
#
#
# if '0xffffffffffffffff' in str(e):
# dontraise=1
# if not dontraise:
# printi("not dontraise")
# raise
#
# tb = traceback.format_exc()
# printi("traceback: {}".format(tb))
# if type(last_error) == type(e):
# printi("returning -2")
# return -2
# unpatch_func2(ea, unpatch=1)
# UnpatchUn()
# last_error = None
# else:
# last_error = e
# # self.exc_info = sys.exc_info()
# pass
except RelocationStackError as e:
printi("[retrace] slowtrace threw {}: {}".format(e.__class__.__name__, str(e)))
if once:
return -1
# unconditional jmp to another sub 0x143abfbe2, retn rsp of 88
# dprint("[debug] type(e.args)")
# m = re.search(r"unconditional jmp to another sub ([^,]+), retn rsp of ([-0-9a-f]+)", e.args[0])
m = re.search(r"\((0x[0-9a-fA-F]+)\) which has no stack", str(e))
if m:
if count == 0:
printi("checking offending function")
retrace(eax(m.group(1)), once=1, forceRemoveChunks=1, **kwargs)
# if re.search(r"isRealFunc: jmpRef: more than 1 ref", str(e)):
# if count == 0:
# TruncateThunks()
# tb = traceback.format_exc()
# printi(tb)
pass
except RelocationInvalidStackError as e:
printi("[retrace] return slowtrace threw {}: {}".format(e.__class__.__name__, str(e)))
return -1
except RelocationTerminalError as e:
printi("[retrace] slowtrace threw {}: {}".format(e.__class__.__name__, str(e)))
tb = traceback.format_exc()
printi("traceback: {}".format(tb))
if debug: print("calling FixChunks #2")
FixChunks(ea, leave=ea)
# ZeroFunction(ea)
pass
except RelocationPatchedError as e:
printi("[retrace] slowtrace threw {}: {}".format(e.__class__.__name__, str(e)))
tb = traceback.format_exc()
printi("traceback: {}".format(tb))
count_limit = min(10, count_limit + 1)