-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhexrayfucker.py
2779 lines (2431 loc) · 115 KB
/
hexrayfucker.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
import os
import idaapi
from exectools import make_refresh, make_auto_refresh, execfile
refresh_hexrayfucker = make_refresh(os.path.abspath(__file__))
refresh = make_refresh(os.path.abspath(__file__))
# check_for_update = make_auto_refresh(os.path.abspath(__file__))
_import("from columns import MakeColumns")
_import("from underscoretest import _")
_import("from split_paren import *")
_import("from attrdict1 import SimpleAttrDict")
# ```
# Python> sid = idc.get_frame_id(idc.get_func_name(idc.BADADDR, 'sub_5450'))
# Python> print(list(idautils.StructMembers(sid)))
# (offset, name, size)
class FuncArg(object):
"""Docstring for FuncArg """
def __init__(self, type=None, indirections=None, name=None):
"""@todo: to be defined
:type: @todo
:indirections: @todo
:name: @todo
"""
self._type = type or ''
self._indirections = indirections or ''
self._name = name or ''
if not name and not indirections:
self.parse(type)
# https://stackoverflow.com/questions/40828173/how-can-i-make-my-class-pretty-printable-in-python/66250289#66250289
def __pprint_repr__(self, **kwargs):
if isinstance(kwargs, dict):
if 'indent' in kwargs:
_indent = kwargs['indent']
result = {}
props = self.items().items()
for (k, v) in props:
result[k] = v
return result
def items(self):
return {
'type': self._type,
'indirections': self._indirections,
'name': self._name,
}
def parse(self, arg):
arg = arg.strip()
if not arg:
raise ValueError("Empty Argument")
stars = ''
lhs = string_between('', ' ', arg, greedy=1).replace('__struct_ptr', '').replace('__hidden', '').strip()
rhs = string_between('', ' ', arg, greedy=1, repl='').strip()
if rhs and not lhs:
lhs, rhs = rhs, lhs
while rhs and rhs[0] in ('*', '&'):
stars += rhs[0]
rhs = rhs[1:]
while lhs and lhs[-1] in ('*', '&'):
stars += lhs[-1]
lhs = lhs[0:-1]
lhs = lhs.replace('const', '')
lhs = lhs.strip()
rhs = rhs.strip()
# still working on it
# for x, y in zip(["type", "indirection", "name"], [lhs, stars, rhs]):
self._type = lhs
self._indirections = stars
self._name = rhs
return True
class FuncArgs:
regex = r"(.*?) ?(?:(\((?:(?:__[a-z]+ ?)*)\*+[^ )]*\))|(?:(?:__[a-z]+ ?)*)?([^* ]*?))(\(.*\))"
def __init__(self, text=None):
self.returnType = ''
self.fnPtr = ''
self.fnName = 'fn'
self.fnArgs = []
if text:
self.parse(text)
# https://stackoverflow.com/questions/40828173/how-can-i-make-my-class-pretty-printable-in-python/66250289#66250289
def __pprint_repr__(self, **kwargs):
if isinstance(kwargs, dict):
if 'indent' in kwargs:
_indent = kwargs['indent']
result = {}
props = self.items().items()
for (k, v) in props:
result[k] = v
return result
def items(self):
return {
'rtype': self.returnType,
'indirections': self.fnPtr,
'name': self.fnName,
'args': self.fnArgs
}
def parse(self, decl):
re_res = None
for found in re.findall(self.regex, decl):
re_res = found
break
if re_res:
returnType, fnPtr, fnName, fnArgs = re_res
if fnName and not returnType:
fnName, returnType = returnType, fnName
if fnPtr:
print("[FuncArgs::parse] We have a void (__fastcall *name)(__int64 a1, ...) situation: {}".format(re_res))
decl = "{} {}{}".format(returnType, string_between('*', ')', fnPtr).strip('*'), fnArgs)
return
# remove wrapping brackets around args
# .. should we swap the order of these checks?
if fnArgs.endswith('()'):
fnArgs = fnArgs[0:-2]
fnArgs = fnArgs[1:-1]
args = paren_multisplit(fnArgs, ",")
for arg in args:
self.fnArgs.append(FuncArg(arg))
stars = ''
while returnType and returnType[-1] in ('*', '&'):
stars += returnType[-1]
returnType = returnType[0:-1]
self.returnType = FuncArg(returnType, stars)
self.fnName = fnName
first_use = dict()
used_colors = set()
pal_colors = [197, 162, 127, 92, 55, 22, 202, 167, 132, 97, 62, 27, 207, 172, 137, 102, 67, 32, 212, 177, 142, 107, 72, 37, 217, 182, 147, 112, 77, 42, 222, 187, 152, 117, 82, 47, 227, 192, 157, 122, 87]
# pal_colors[24] = 197
# pal_colors[8] = 197
def vt100_color(match, i):
"""
1: ['SCOLOR_DEFAULT', 'Default.'],
2: ['SCOLOR_REGCMT', 'Regular comment.'],
3: ['SCOLOR_RPTCMT', 'Repeatable comment (defined not here)'],
4: ['SCOLOR_AUTOCMT', 'Automatic comment.'],
5: ['SCOLOR_INSN', 'Instruction.'],
6: ['SCOLOR_DATNAME', 'Dummy Data Name.'],
7: ['SCOLOR_DNAME', 'Regular Data Name.'],
8: ['SCOLOR_DEMNAME', 'Demangled Name.'], 8: 'qword_142F133F0'
9: ['SCOLOR_SYMBOL', 'Punctuation.'], 9: '{',
10: ['SCOLOR_CHAR', 'Char constant in instruction.'],
11: ['SCOLOR_STRING', 'String constant in instruction.'],
12: ['SCOLOR_NUMBER', 'Numeric constant in instruction.'], 12: '// \x01\x0cside_comment',
13: ['SCOLOR_VOIDOP', 'Void operand.'], 13: 'v1',
14: ['SCOLOR_CREF', 'Code reference.'],
15: ['SCOLOR_DREF', 'Data reference.'],
16: ['SCOLOR_CREFTAIL', 'Code reference to tail byte.'],
17: ['SCOLOR_DREFTAIL', 'Data reference to tail byte.'],
18: ['SCOLOR_ERROR', 'Error or problem.'], 18: 'JUMPOUT'}
19: ['SCOLOR_PREFIX', 'Line prefix.'],
20: ['SCOLOR_BINPREF', 'Binary line prefix bytes.'],
21: ['SCOLOR_EXTRA', 'Extra line.'],
22: ['SCOLOR_ALTOP', 'Alternative operand.'],
23: ['SCOLOR_HIDNAME', 'Hidden name.'], 23: '_QWORD *' | '__int64 v1',
24: ['SCOLOR_LIBNAME', 'Library function name.'], 24: '[rsp+24h] [rbp+4h]' | 24: 'rbx'
25: ['SCOLOR_LOCNAME', 'Local variable name.'], 25: '"kernel32.dll"'
26: ['SCOLOR_CODNAME', 'Dummy code name.'],
27: ['SCOLOR_ASMDIR', 'Assembler directive.'],
28: ['SCOLOR_MACRO', 'Macro.'],
29: ['SCOLOR_DSTR', 'String constant in data directive.'],
30: ['SCOLOR_DCHAR', 'Char constant in data directive.'],
31: ['SCOLOR_DNUM', 'Numeric constant in data directive.'],
32: ['SCOLOR_KEYWORD', 'Keywords.'], 32: '0i64' | 'if'
33: ['SCOLOR_REG', 'Register name.'], 33: 'void f\x01\t(\x02\tint a\x01\t)\x02\t'
34: ['SCOLOR_IMPNAME', 'Imported name.'], 34: 'LoadLibraryA'
35: ['SCOLOR_SEGNAME', 'Segment name.'],
36: ['SCOLOR_UNKNAME', 'Dummy unknown name.'],
37: ['SCOLOR_CNAME', 'Regular code name.'],
38: ['SCOLOR_UNAME', 'Regular unknown name.'],
39: ['SCOLOR_COLLAPSED', 'Collapsed line.'],
40: ['SCOLOR_ADDR', 'Hidden address mark.'],
"""
scolors = {
1: ['SCOLOR_ON', 'Escape character (ON)'],
2: ['SCOLOR_OFF', 'Escape character (OFF)'],
3: ['SCOLOR_ESC', 'Escape character (Quote next character)'],
4: ['SCOLOR_INV', 'Escape character (Inverse colors)'],
1: ['SCOLOR_DEFAULT', 'Default.'],
2: ['SCOLOR_REGCMT', 'Regular comment.'],
3: ['SCOLOR_RPTCMT', 'Repeatable comment (defined not here)'],
4: ['SCOLOR_AUTOCMT', 'Automatic comment.'],
5: ['SCOLOR_INSN', 'Instruction.'],
6: ['SCOLOR_DATNAME', 'Dummy Data Name.'],
7: ['SCOLOR_DNAME', 'Regular Data Name.'],
8: ['SCOLOR_DEMNAME', 'Demangled Name.'],
9: ['SCOLOR_SYMBOL', 'Punctuation.'],
10: ['SCOLOR_CHAR', 'Char constant in instruction.'],
11: ['SCOLOR_STRING', 'String constant in instruction.'],
12: ['SCOLOR_NUMBER', 'Numeric constant in instruction.'],
13: ['SCOLOR_VOIDOP', 'Void operand.'],
14: ['SCOLOR_CREF', 'Code reference.'],
15: ['SCOLOR_DREF', 'Data reference.'],
16: ['SCOLOR_CREFTAIL', 'Code reference to tail byte.'],
17: ['SCOLOR_DREFTAIL', 'Data reference to tail byte.'],
18: ['SCOLOR_ERROR', 'Error or problem.'],
19: ['SCOLOR_PREFIX', 'Line prefix.'],
20: ['SCOLOR_BINPREF', 'Binary line prefix bytes.'],
21: ['SCOLOR_EXTRA', 'Extra line.'],
22: ['SCOLOR_ALTOP', 'Alternative operand.'],
23: ['SCOLOR_HIDNAME', 'Hidden name.'],
24: ['SCOLOR_LIBNAME', 'Library function name.'],
25: ['SCOLOR_LOCNAME', 'Local variable name.'],
26: ['SCOLOR_CODNAME', 'Dummy code name.'],
27: ['SCOLOR_ASMDIR', 'Assembler directive.'],
28: ['SCOLOR_MACRO', 'Macro.'],
29: ['SCOLOR_DSTR', 'String constant in data directive.'],
30: ['SCOLOR_DCHAR', 'Char constant in data directive.'],
31: ['SCOLOR_DNUM', 'Numeric constant in data directive.'],
32: ['SCOLOR_KEYWORD', 'Keywords.'],
33: ['SCOLOR_REG', 'Register name.'],
34: ['SCOLOR_IMPNAME', 'Imported name.'],
35: ['SCOLOR_SEGNAME', 'Segment name.'],
36: ['SCOLOR_UNKNAME', 'Dummy unknown name.'],
37: ['SCOLOR_CNAME', 'Regular code name.'],
38: ['SCOLOR_UNAME', 'Regular unknown name.'],
39: ['SCOLOR_COLLAPSED', 'Collapsed line.'],
40: ['SCOLOR_ADDR', 'Hidden address mark.'],
}
global used_colors
global first_use
global pal_colors
group = match.groups()
o = ord(group[0][0])
# if o != 9:
used_colors.add(o)
t = _.indexOf(list(used_colors), o)
w = len(used_colors) + 31
t = t + 31
if t > 37:
t += 3
text = group[1]
rest = group[2]
ignore = ''
# if o not in first_use:
# first_use[o] = text
# if o == 12:
# if text.startswith('//'):
# text = text.replace('//', '#')
# if o == 9 and text.startswith((';','{', '}')):
# if text.startswith(';'):
# pass
# else:
# ignore += text
# text = ''
result = ''
if text:
if i == 0 or o in (12, ):
result += "\x1b[38;5;{}m{}\x1b[39m".format(pal_colors[o], text)
elif i == 1:
result += "\x1b[48;5;{};4m{}\x1b[49;24m".format(pal_colors[o], text)
# result += "\x1b[{}m{}\x1b[0m".format(t, text)
if rest:
result += rest
# result += "\x1b[48;5;{}m{}\x1b[0m".format(o, rest)
# result += "\x1b[{};2m{}\x1b[0m".format(w, rest)
if ignore:
result += ignore
return result
# def colorize_sub(s):
# return re.sub(r"\x01(.)(.*?)\x02\1", vt100_color, re.sub(r"\x04\x04|\x01\([0-9a-fA-F]{16}", '', s))
def _process_citems():
cf = vu.cfunc;
# '\x01(0000000000000051\x01\x08EnumProcessModules_0\x02\x08'
# '\x01(0000000000000005\x01\x18kernel32\x02\x18'
# '\x01(0000000000000075\x01\x08sub_1414E78F8\x02\x08'
# '\x01(000000000000003E\x01"GetProcAddress\x02"'
ida_lines.tag_remove( cf.treeitems[81].print1(cf) )
def colorize_sub(s, i=0):
# vu = get_pseudocode_vu(EA(), vu); pc2 = genAsList(vu.cfunc.get_pseudocode()); clear(); print("\n".join([colorize_sub(colorize_sub(x.line), 1) for x in pc2]))
return re.sub(r"\x01(.)(.*?)\x02\1()",
lambda x: vt100_color(x, i),
re.sub(r"\x04\x04", '',
re.sub(r"\x01\([0-9A-F]{16}",
lambda x: "<<{}>>".format(parseHex(x.group(0)[2:])),
s)))
# return re.sub(r"\x01(.)([^\x01-\x02]+)\x02\1([^\x01-\x04]*)", vt100_color, re.sub(r"\x04\x04|\x01\([0-9A-F]{16}", '', s))
def count_indent(s):
return re.sub(r"\u2015( *)", lambda m: "\u2015{}\u2015".format(len(m.group(1))), s)
def colorize(vu):
s = [x.line for x in genAsList(vu.cfunc.get_pseudocode())]
for l in s:
if "__stdcall" in l:
print("Comment: {}".format(bytearray(l.encode('raw_unicode_escape'))))
s = "\n\u2015".join(s)
# s = re.sub(r'\x01\([0-9A-F]{16}', '\x01', s)
# print(s)
# return s
# s = re.sub(r'\x01\x09;\x02\x09(\x01\x28[0-9A-F]\{16})', '', s, re.M)
s = re.sub(r'\x01\t;\x02\t\x01\(.{16}', '', s)
s = re.sub(r'\x01 else\x02 *\x01 if\x02 ', 'elif', s)
s = re.sub(r'\x01 else\x02 *\x01 if\x02 ', 'elif', s)
s = s.replace("\x04\x04\x01\x09}\x02\x09", "") # "\u2016")
s = s.replace(" \x01\x09(\x02\x09 ", " \x01\x09(\x02\x09 ")
s = s.replace(" \x01\x09)\x02\x09 ", " \x01\x09)\x02\x09 ")
# s = s.split("\x04")
# s = "\n".join(s)
s = s.replace("\x01\x0c//", "# ")
s = s.replace("\x02\t //", "\x02\t # ")
s = s.replace("::", ".")
s = s.replace("\x01\t->\x02\t", "\x01\t.\x02\t")
s = s.replace("\x01\t:\x02\t\x01\t:\x02\t", "\x01\t.\x02\t")
s = colorize_sub(colorize_sub(s))
s = count_indent(s)
# \x01\x08VEHICLE::CREATE_VEHICLE_ACTUAL_0\x02\x08
s = re.sub(r'\n\u2015\d+\u2015\{', ':', s)
s = re.sub(r'\u2015(\d+)\u2015', lambda m: ' ' * int(m.group(1)), s)
s = s.split("\n")
s = "\n".join([x for x in s if x.strip()])
s = s.replace("\n\x02\x0c", "\n ")
# s = re.sub(r'\x1b\[\d+m', '', s)
# print(s)
return(s)
def get_min_spd(ea = None):
ea = eax(ea)
minspd_ea = idc.get_min_spd_ea(ea)
if minspd_ea == idc.BADADDR:
return False
return idc.get_spd(minspd_ea)
def GetMinSpdStackCorrection(funcea):
if isinstance(funcea, ida_funcs.func_t):
func = funcea
else:
func = ida_funcs.get_func(funcea)
return (func.frsize + func.frregs + idc.get_spd(idc.get_min_spd_ea(func.start_ea)))
def get_stkoff_from_lvar(lvar, debug=1):
ea = idc.get_item_head(lvar.defea)
func = ida_funcs.get_func(ea)
if not func:
return idc.BADADDR
for n in range(2):
if idc.get_operand_type(ea, n) == idc.o_displ:
offset = idc.get_operand_value(ea, n) + func.frsize - func.fpd
if debug:
lvar_name = lvar.name
sid = idc.get_frame_id(func.start_ea)
frame_name = idc.get_member_name(sid, offset)
print("[debug] offset:0x{:x}, lvar_name:{}, frame_name:{}"
.format(offset, lvar_name, frame_name))
return offset
# resort to other measures, as sometimes .defea points to a condition jmp
return lvar.get_stkoff() + GetMinSpdStackCorrection(func)
def dump_stkvars(ea = None, iteratee=None, stkzero=0, spdoffset=0):
_import("from columns import MakeColumns")
def get_member_tinfo(sid, offset):
s = ida_struct.get_struc(sid)
m = ida_struct.get_member(s, offset)
tif = ida_typeinf.tinfo_t()
try:
if ida_struct.get_member_tinfo(tif, m):
return tif
except TypeError as e:
print("s, m, tif", type(s), type(m), type(tif))
print("Exception: {}".format(pprint.pformat(e)))
return None
ea = eax(ea)
c = MakeColumns()
results = []
sid = idc.get_frame_id(GetFuncStart(here()))
for member in idautils.StructMembers(sid):
o = SimpleAttrDict()
o.offset, o.name, o.size = member
o.offset += spdoffset
o.zeroed = o.offset + stkzero
o.mid = idc.get_member_id(sid, o.offset)
o.name = idc.get_member_name(sid, o.offset)
o.size = idc.get_member_size(sid, o.offset)
o.flags = idc.get_member_flag(sid, o.offset)
# o.strid = idc.get_member_strid(sid, o.offset)
tif = get_member_tinfo(sid, o.offset)
o.tifname = str(tif) if tif else ''
c.addRow(o)
o.sid = sid
if callable(iteratee):
iteratee(o)
results.append(o)
print(c)
return results
def rename_stkvar(src, dst, ea=None):
def fn_rename(o, *args):
if o.name == src:
idc.set_member_name(o.sid, o.offset, dst)
dump_stkvars(ea, fn_rename)
def label_stkvar(offset, name, ea=None, vu=None):
ea = get_ea_by_any(ea or vu)
sid = idc.get_frame_id(ea)
old_name = idc.get_member_name(sid, offset)
if old_name:
if old_name == name:
return old_name
print("[label_stkvar] renaming {} to {}".format(old_name, name))
if idc.set_member_name(sid, offset, name):
return old_name
else:
print("couldn't get name from sid {:x}".format(sid))
# 2. Get the existing variable id.
#
# ```
# Python> var_id = idc.get_member_id(sid, 12)
# ```
#
# If I needed a new variable, I would have used `add_struc_member(sid, 'var_name', var_offset, FF_DATA | FF_BYTE, -1, 1)` first.
#
# 3. Use `apply_type` in order to turn the variable into an array.
#
# ```
# Python> apply_type(var_id, parse_decl('int[2]', 0))
# True
# ```
#
# Somehow `MakeArray` did not work:
#
# ```
# Python> MakeArray(var_id, 2)
# False
# ```
class Pseudocode(object):
def __init__(self, ea):
self.addr = ea
def __enter__(self):
func = idaapi.get_func(self.addr)
if func:
self.vu = idaapi.open_pseudocode(func.start_ea, 0)
return self.vu
raise RuntimeError("Couldn't open_pseudocode")
def __exit__(self, exc_type, exc_value, traceback):
self.vu = None
def _Pseudocode_example():
with Pseudocode(here()) as vu:
arrays = get_lvars(here(), vu=vu, tif_filter=lambda tif: tif.is_array())
for array in arrays:
tif = array.tif
tif.remove_ptr_or_array()
vu.set_lvar_type(array, tif)
def contents(o, types):
"""
A very stupid function that tries to check if the majority of arguments are
of type `types`. All it really manages to do (most times) is check if the
last arg is of type `types`, unless there are actually more of one type,
e.g.: contents([1, 2, 'A', 'B', 3], (int,))==True
"""
return _(A(o)) \
.chain() \
.countBy(lambda x, *a: type(x)) \
.pairs() \
.sortBy(lambda v, *a: v[1]) \
.reverse() \
.first() \
.first() \
.value() in A(types)
# return _.first(_.first(_.reverse(_.sortBy(_.pairs(_.countBy(o, lambda x, *a: type(x))), lambda v, *a: v[1])))) in types
# t = next(iter(A(o)))
# return isinstance(t, types)
def decompile_function_as_cfunc(funcea):
try:
cfunc = idaapi.decompile(funcea, hf=None, flags=idaapi.DECOMP_WARNINGS)
if cfunc:
return cfunc
except idaapi.DecompilationFailure:
pass
logger.warn("IDA failed to decompile function at 0x{:x}".format(funcea))
def get_func_stkoff_delta(funcea):
cfunc = decompile_function_as_cfunc(funcea)
if cfunc:
return cfunc.get_stkoff_delta()
def get_pseudocode_vu(ea, vu=None):
func = idaapi.get_func(ea)
if func:
return idaapi.open_pseudocode(func.start_ea, 0)
def get_lvar_real_stkoff(ea, name='', vu=None):
r = foreach_lvars(ea, vu=vu, iteratee= \
lambda _lvar, _i, _vu, *a: (_lvar, _lvar.get_stkoff() - _vu.cfunc.get_stkoff_delta()))
for _lvar, _offset in r:
print("lvar name: {:32s} offset: 0x{:3x}".format(_lvar.name, _offset))
return r
def get_func_rettype(ea):
cfunc = decompile_function_as_cfunc(ea)
func_tinfo = idaapi.tinfo_t()
cfunc.get_func_type(func_tinfo)
rettype = func_tinfo.get_rettype()
return rettype
def foreach_lvars(ea, iteratee=None, vu=None):
vu = get_pseudocode_vu(ea, vu)
lvars = get_lvars(ea=ea, vu=vu)
if lvars:
if callable(iteratee):
for i, n in enumerate(vu.cfunc.lvars):
# dprint("[foreach_lvars] n, i, vu")
print("[foreach_lvars] n:{}, i:{}, vu:{}".format(n, i, vu))
iteratee(n, i, vu)
return
return [n for n in vu.cfunc.lvars]
return False
# foreach_lvars(EA(), lambda n, i, vu: vu.rename_lvar(n, lvd[i][0], 1), vu=vu)
# foreach_lvars(EA(), lambda n, i, vu: vu.set_lvar_type(n, get_tinfo_by_parse(lvd[i][1])), vu=vu)
# if you want to use an existing view:
# widget = ida_kernwin.find_widget('Pseudocode-AU')
# vu = vu or ida_hexrays.get_widget_vdui(widget)
def get_lvars(ea, tif_filter=None, vu=None):
vu = get_pseudocode_vu(ea, vu)
if vu:
if callable(tif_filter):
return [n for n in vu.cfunc.lvars if tif_filter(n.tif)]
return [n for n in vu.cfunc.lvars]
return False
def group_lvars_by_type(ea=None, vu=None):
return _.groupBy(get_lvars(ea, vu=vu), lambda x, *a: str(x.tif))
def map_lvars_by_type(ea=None, vu=None):
vu = get_pseudocode_vu(ea, vu)
action = list()
g = group_lvars_by_type(ea, vu)
for tname, lvars in g.items():
g2 = _.groupBy(lvars, lambda x, *a: x.get_reg1())
for r, lvars2 in g2.items():
_sorted = _.sortBy(lvars2, lambda x, *a: len(x.name))
_sorted.reverse()
name = _sorted[0].name
for t in lvars2:
if t.name:
print("type: {} reg: {} name: {} - {}".format(tname, t.get_reg1(), t.name, name))
if t.name != name:
action.append([t.name, name])
for x in action:
map_lvar(x[0], x[1], ea=ea, vu=vu)
def retype_lvars_by_type(ea=None, vu=None):
vu = get_pseudocode_vu(ea, vu)
action = list()
g = group_lvars_by_type(ea, vu)
for tname, lvars2 in g.items():
signed = False
name = tname[:]
if name.startswith('unsigned __'):
signed = False
name = name[9:]
if name.startswith('signed __'):
name = name[7:]
signed = True
if name.startswith('__'):
name = name.replace('__', '' if signed else 'u', 1)
if ' ' in name:
name = name.replace(' ', '_t', 1)
else:
name = name + '_t'
if name.startswith('_'):
name = name[1:]
if name == 'int':
name = 'int32_t'
if 'uintptr_t' in name:
name = name.replace('uintptr_t', 'uint64_t')
if 'DWORD' in name:
name = name.replace('DWORD', 'uint32_t')
if 'QWORD' in name:
name = name.replace('QWORD', 'uint64_t')
name = name.replace('unsigned int', 'uint32_t')
for t in lvars2:
if t.name:
print("type: {} name: {} newtype: {}".format(tname, t.name, name))
if tname != name:
action.append([t.name, name])
for x in action:
set_lvar_type(x[0], x[1], ea=ea, vu=vu)
def get_pseudocode_vu(ea, vu):
if vu:
return vu
# dprint("[get_pseudocode_vu] reloading vu")
if debug:
stk = []
for i in range(len(inspect.stack()) - 1, 0, -1):
stk.append(inspect.stack()[i][3])
print((" -> ".join(stk)))
print("[get_pseudocode_vu] reloading vu")
func = idaapi.get_func(eax(ea))
if func:
return idaapi.open_pseudocode(func.start_ea, 0)
def _rename_lvar(old, new, ea, uniq=0, vu=None):
if old is None or new is None:
print("return_if: old is None or new is None")
return
def make_unique_name(name, taken):
if name not in taken:
return name
fmt = "%s_%%i" % name
for i in range(3, 1<<10):
name = fmt % i
if name not in taken:
return name
if isinstance(old, str):
old = old.strip()
new = new.strip()
if old == new:
return True
vu = get_pseudocode_vu(ea, vu)
names = [n.name for n in vu.cfunc.lvars]
if new in names:
if uniq:
return False
new = make_unique_name(new, names)
if isinstance(old, int):
lvars = [vu.cfunc.lvars[old]]
else:
lvars = [n for n in vu.cfunc.lvars if n.name == old]
if lvars:
lvar = lvars[0]
if lvar.is_stk_var():
offset = lvar.get_stkoff() - vu.cfunc.get_stkoff_delta()
old_name = label_stkvar(offset, new, ea=ea, vu=vu)
if old_name:
print("[_rename_lvar] renamed stack variable {} to {}".format(old_name, new))
else:
print("lvar {} is not a stack variable, skipping stack rename".format(lvar.name))
return vu.rename_lvar(lvar, new, 1)
else:
print("[_rename_lvar] couldn't find var '{}'".format(old))
return 0
def get_type_tinfo(t):
type_tuple = idaapi.get_named_type(None, t, 1)
tif = idaapi.tinfo_t()
tif.deserialize(None, type_tuple[1], type_tuple[2])
return tif
def get_lvar_type(src, ea, vu=None):
vu = get_pseudocode_vu(ea, vu)
if vu:
lvars = [n for n in vu.cfunc.lvars if n.name == src]
if len(lvars) == 1:
print("type of {} is {}".format(lvars[0].name, lvars[0].tif))
return str(lvars[0].tif)
else:
print("[get_lvar_type] couldn't find var '{}'".format(src))
return False
def set_lvar_name_type_so(ea, src, name, t, vu=None):
"""
Change the name or type of a local variable
@param ea: address of function
@param src: current name of variable
@param name: new name (or None to leave as is)
@param t: new type (str, tinfo_t, or None to leave as is)
@param v: handle to existing pseudocode window (vdui_t, or None)
@note
Will not work with function arguments or global variables
"""
# m = [ea for ea in [pprev(ea, 1) for ea in l if GetFuncName(ea)] if ea]
def get_tinfo_elegant(name):
ti = ida_typeinf.tinfo_t()
til = ti.get_til()
# get_named_type(self, til, name, decl_type=BTF_TYPEDEF, resolve=True, try_ordinal=True)
if ti.get_named_type(til, name, ida_typeinf.BTF_STRUCT, True, True):
return ti
return None
def get_pseudocode_vu(ea, vu=None):
func = idaapi.get_func(ea)
if func:
return idaapi.open_pseudocode(func.start_ea, 0)
if isinstance(t, str):
tif = get_tinfo_elegant(t)
if not tif:
raise ValueError("Couldn't get tinfo_t for type '{}'".format(t))
t = tif
elif isinstance(t, ida_typeinf.tinfo_t) or t is None:
pass
else:
raise TypeError("Unknown type for t '{}'".format(type(t)))
vu = get_pseudocode_vu(ea, vu)
if vu:
lvars = [n for n in vu.cfunc.lvars if n.name == src]
if len(lvars) == 1:
print("changing name/type of {}/{} to {}/{}".format(lvars[0].name, lvars[0].type(), name, str(t)))
if t:
vu.set_lvar_type(lvars[0], t)
if name:
vu.rename_lvar(lvars[0], name, 1)
else:
print("[set_lvar_name_type] couldn't find var {}".format(src))
return False
def set_lvar_name_type(ea, src, name, t, vu=None):
"""
l = FindInSegments("65 48 8B 04 25 58 00 00 00")
forceAsCode([ea for ea in l if not GetFuncName(ea)])
m = [ea for ea in [pprev(ea, 1) for ea in l if not GetFuncName(ea)] if ea]
retrace_list(m)
m = [ea for ea in l if GetFuncName(ea)]
for ea in m:
list(decompile_function_search(ea, r'\b(v\d+) = TlsIndex', iteratee=lambda ea, m: set_lvar_name_type(ea, m, 'tlsIndex', None)))
"""
# m = [ea for ea in [pprev(ea, 1) for ea in l if GetFuncName(ea)] if ea]
if src is None:
print("return_if: src in None")
return
if isinstance(t, str):
tif = get_tinfo_by_parse(t)
if not tif:
raise ValueError("Couldn't get tinfo for type '{}'".format(t))
t = tif
elif isinstance(t, ida_typeinf.tinfo_t):
pass
elif t is None:
pass
else:
raise TypeError("Unknown type for t '{}'".format(type(t)))
vu = get_pseudocode_vu(ea, vu)
if vu:
lvars = [n for n in vu.cfunc.lvars if n.name == src]
if len(lvars) == 1:
print("changing name/type of {}/{} to {}/{}".format(lvars[0].name, lvars[0].type(), name, str(t)))
if t:
vu.set_lvar_type(lvars[0], t)
vu.rename_lvar(lvars[0], name, 1)
else:
print("[set_lvar_name_type] couldn't find var {}".format(src))
return False
def set_lvar_type(src, t, ea, vu=None):
if t is None or src is None:
print("return_if: t is None or src in None")
return
if isinstance(t, str):
tif = get_tinfo_by_parse(t)
if not tif:
raise ValueError("Couldn't get tinfo for type '{}'".format(t))
t = tif
elif isinstance(t, ida_typeinf.tinfo_t):
pass
else:
raise TypeError("Unknown type for t '{}'".format(type(t)))
vu = get_pseudocode_vu(ea, vu)
if vu:
lvars = [n for n in vu.cfunc.lvars if n.name == src]
if len(lvars) == 1:
print("changing type of {} to {}".format(lvars[0].name, t))
return vu.set_lvar_type(lvars[0], t)
else:
print("[set_lvar_type] couldn't find var {}".format(src))
return False
def map_lvar(src, dst, ea, vu=None):
# t = ('', '\n=\x04#\x86U', '')
# ti = idaapi.tinfo_t()
# ti.deserialize(None, t[0], t[1])
vu = get_pseudocode_vu(ea, vu)
if vu:
lvars1 = [n for n in vu.cfunc.lvars if n.name == src]
lvars2 = [n for n in vu.cfunc.lvars if n.name == dst]
if len(lvars1) == 1 and len(lvars2) == 1:
print("mapping {} to {}".format(lvars1[0].name, lvars2[0].name))
# we might need to change the lvar type?
vu.set_lvar_type(lvars1[0], lvars2[0].type())
return vu.map_lvar(lvars1[0], lvars2[0])
else:
print("couldn't find one of the vars {} or {}".format(src, dst))
return False
# ralf rolles
# It's better to do this directly, without using the user-interface class
# vdui_t. Here's a small function you can call to set the name of a local
# variable, assuming you already have the lvar_t object you want to rename:
def SetLvarName(func_ea,lvar,name):
lsi = ida_hexrays.lvar_saved_info_t()
lsi.ll = lvar
lsi.name = name
ida_hexrays.modify_user_lvar_info(func_ea, ida_hexrays.MLI_NAME, lsi)
# Here's a little harness I wrote to ensure it works. It decompiles some function in my database, finds the lvar_t named "v35", and renames it to "vNewName".
def GetCfunc(ea):
f = idaapi.get_func(ea)
if f is None:
return None
# Decompile the function.
cfunc = None
try:
cfunc = idaapi.decompile(f)
finally:
return cfunc
def SetLvarNameTest():
cfunc = GetCfunc(0x61FE5DDE)
if cfunc:
mba = cfunc.mba
for idx in xrange(mba.vars.size()):
var = mba.vars[idx]
if var.name == "v35":
SetLvarName(cfunc.entry_ea,var,"vNewName")
break
def get_flags_by_size(size):
""" see also ida_bytes.get_flags_by_size """
flags = [ida_bytes.byte_flag(), ida_bytes.word_flag(), ida_bytes.dword_flag(),
ida_bytes.qword_flag(), ida_bytes.oword_flag(), ida_bytes.yword_flag(),
ida_bytes.zword_flag() ]
if (size & (size-1)):
raise ValueError("size is not a power of 2")
flag = flags[log2(size)]
# [(x >> 28) - 0x400 for x in flags] = ['0b0', '0b1', '0b10', '0b11', '0b111', '0b1110', '0b1111']
b = 0
for r in range(log2(size)):
if b & 1: b <<= 1
else: b |= 1
# handle annoying miss in pattern
if b == 6: b += 1
if debug: print("b: {}".format(bin(b)))
flag2 = (b << 28) + (1 << 10)
# dprint("[get_data_flag] size, flag, flag2")
print("[get_data_flag] size:{}, flag:{:x}, flag2:{:x}".format(size, flag, flag2))
def show_lvars_to_stk(ea, vu=None):
vu = get_pseudocode_vu(ea, vu)
func = idaapi.get_func(ea)
# DONE: replace with idc.get_func_attr(ea, idc.FUNCATTR_FRSIZE)
# stkzero = ida_frame.frame_off_retaddr(func) - 8
stkzero = idc.get_func_attr(ea, idc.FUNCATTR_FRSIZE)
# dprint("[sync_lvars_to_stk] stkzero, stkzero2")
# print("[sync_lvars_to_stk] stkzero:{}, stkzero2:{}".format(stkzero, stkzero2))
vu_offset_fix = GetMinSpdStackCorrection(func)
stkvars = _.indexBy(dump_stkvars(ea, stkzero=-stkzero), 'offset')
lvars = []
if vu and func:
# opi = ida_nalt.opinfo_t()
# ida_bytes.get_opinfo(opi, EA(), 1, GetOpType(EA(), 1))
stk_lvars = [(
n.name,
n.tif.get_size(),
n.location.stkoff(), # - func.frregs - func.frsize,
n.location.stkoff() + vu_offset_fix,
) \
for n in vu.cfunc.lvars if n.location.is_stkoff()]
# [ (x.name, x.tif.get_size(), hex( x.location.stkoff() - ida_frame.frame_off_retaddr(func) - 8 ) ) \
# for x in n if x.location.is_stkoff()
# ]
c = MakeColumns()
for name, size, offset1, offset2 in stk_lvars:
o = SimpleAttrDict()
o.update({
'name': name,
'size': size,
'lvar_offset': offset1,
'lvar_offset_fix': offset2
# 'stk_name1': stkvars[-offset1],
# 'stk_name2': stkvars[-offset2],
})
c.addRow(o)
lvars.append(o)
print(c)
lvars = _.indexBy(lvars, 'lvar_offset_fix')
c = MakeColumns()
lvar_offsets = lvars.keys()
for offset in lvar_offsets:
if offset in stkvars:
c.addRow({
'lname': lvars[offset].name,
'sname': stkvars[offset].name,
'lvar_offset': lvars[offset].lvar_offset_fix,
'stk_offset': stkvars[offset].offset,
'zero_offset': stkvars[offset].zeroed,
})
# dprint("[] func.frregs, func.frsize, func.fpd, ida_frame.frame_off_retaddr, ida_frame.frame_off_lvars, ida_frame.frame_off_args, ida_frame.frame_off_savregs")
print("")
print("{:28}: {}\n{:28}: {:3x}\n{:28}: {:3x}\n{:28}: {:3x}\n{:28}: {:3x}\n{:28}: {:3x}\n{:28}: {:3x}\n{:28}: {:3x}\n{:28}: {:3x}\n"
.format(
"func.flags", " | ".join(debug_fflags(func, quiet=1)),
"func.frregs", func.frregs,
"func.frsize", func.frsize,
"func.fpd", func.fpd,
"vu_offset_fix", vu_offset_fix,
"ida_frame.frame_off_retaddr", ida_frame.frame_off_retaddr(func),
"ida_frame.frame_off_lvars", ida_frame.frame_off_lvars(func),
"ida_frame.frame_off_args", ida_frame.frame_off_args(func),
"ida_frame.frame_off_savregs", ida_frame.frame_off_savregs(func),
))
print(c)
# check we have a power of 2
# if size & (size-1) == 0 and size < 32:
# flags = ida_bytes.get_flags_by_size(size)
# ida_frame.define_stkvar(func, name, offset, flags, opi, size)
def sync_lvars_to_stk(ea, vu=None):
vu = get_pseudocode_vu(ea, vu)
func = idaapi.get_func(ea)
# DONE: replace with idc.get_func_attr(ea, idc.FUNCATTR_FRSIZE)
# stkzero = ida_frame.frame_off_retaddr(func) - 8
stkzero = idc.get_func_attr(ea, idc.FUNCATTR_FRSIZE)
# dprint("[sync_lvars_to_stk] stkzero, stkzero2")
# print("[sync_lvars_to_stk] stkzero:{}, stkzero2:{}".format(stkzero, stkzero2))
vu_offset_fix = GetMinSpdStackCorrection(func)
stkvars = _.indexBy(dump_stkvars(ea, stkzero=-stkzero), 'name')
lvars = []
if vu and func:
# opi = ida_nalt.opinfo_t()
# ida_bytes.get_opinfo(opi, EA(), 1, GetOpType(EA(), 1))