-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclassmaker.py
1480 lines (1299 loc) · 60.6 KB
/
classmaker.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 idc import *
import re
import os
import sys
from exectools import _import, _from
# _import("from idarest.idarest_client import IdaRestClient")
file_dir = os.path.dirname(__file__)
sys.path.append(file_dir)
# from loader import import_from
# import fuzzywuzzy
# from fuzzywuzzy import fuzz
# from fuzzywuzzy import process
# BatchMode = _require('BatchMode').BatchMode
__class_maker_struct = []
__class_maker_member_names = []
from exectools import make_refresh
refresh_classmaker = make_refresh(os.path.abspath(__file__))
refresh = make_refresh(os.path.abspath(__file__))
import idaapi
classmaker_info = idaapi.get_inf_structure()
if classmaker_info.is_64bit():
bits = 64
elif classmaker_info.is_32bit():
bits = 32
else:
bits = 16
try:
is_be = classmaker_info.is_be()
except:
is_be = classmaker_info.mf
endian = "big" if is_be else "little"
# print('Processor: {}, {}bit, {} endian'.format(classmaker_info.procName, bits, endian))
# Result: Processor: mipsr, 32bit, big endian
def ptrsize():
return ptrsize.bits >> 3
ptrsize.bits = bits
def getptr(ea=None, bits=None, signed=False):
if bits is None:
bits = ptrsize.bits
result = idc.get_qword(eax(ea)) & ((1 << bits) - 1)
if signed:
result = MakeSigned(result, bits)
return result
def getptr(ea=None, bits=None, signed=False):
if bits is None:
bits = ptrsize.bits
result = idc.get_qword(eax(ea)) & ((1 << bits) - 1)
if signed:
result = MakeSigned(result, bits)
return result
def setptr(ea=None, value=0, bits=None, signed=False):
ea = eax(ea)
if bits is None:
bits = ptrsize.bits
result = (idc.get_qword(ea) & ~((1 << bits) - 1)) | (value & ((1 << bits) - 1))
if signed:
result = MakeSigned(result, bits)
idc.patch_qword(ea, result)
return result
getptr.bits = bits
def copy_vtable():
l = [get_name_by_any(getptr(ea)) for ea in range(ms(), me(), ptrsize())]
# for i, ea in enumerate(range(EA(), EA() + ptrsize() * len(l) + 1, ptrsize())): LabelAddressPlus(getptr(ea), l[i])
print("""
l = [{}]
for i, ea in enumerate(range(EA(), EA() + ptrsize() * len(l) + 1, ptrsize())): LabelAddressPlus(getptr(ea), l[i])
""".format(", ".join(['"{}"'.format(x) for x in l])))
for _annoying in ["PT_REPLACE", "PT_RAWARGS", "PT_NDC"]:
if _annoying not in globals():
globals()[_annoying] = idc.PT_SILENT;
# if 'long' not in globals():
# globals()['long'] = int;
def _hasUserName(ea=None):
"""
_hasUserName
@param ea: linear address
"""
ea = eax(ea)
if not HasUserName(ea):
return False
name = idc.get_name(ea)
if re.match('_sub_[0-9a-fA-F]+$', name):
return False
return True
def GetLocalTypeFixed(ordinal, flags):
"""
Retrieve a local type declaration
@param flags: any of PRTYPE_* constants
@return: local type as a C declaration or ""
"""
rv = get_local_tinfo(ordinal)
if not rv:
return ""
(type, fields) = rv
if type:
name = get_numbered_type_name(ordinal)
return ida_typeinf.idc_print_type(type, fields, name, flags)
return ""
def struct_list_local():
for i in range(1, idc.get_ordinal_qty()):
print(i, GetLocalTypeFixed(i, PRTYPE_TYPE))
def local_struct_names():
for i in range(1, idc.get_ordinal_qty()):
yield idc.get_numbered_type_name(i)
def struct_names():
i = get_first_struc_idx();
while i != BADADDR:
yield idc.get_struc_name(idc.get_struc_by_idx(i))
i = get_next_struc_idx(i)
def get_struc_ordinal(name):
for i in range(1, idc.get_ordinal_qty()+1):
if idc.get_numbered_type_name(i) == name:
return i
return BADADDR
def get_ordinal_by_name(name):
ti = ida_typeinf.get_idati()
return ida_typeinf.get_type_ordinal(ti, name)
def get_struc_idx_re(pattern, flags = 0):
i = get_first_struc_idx();
while i != idc.BADADDR:
name = idc.get_struc_name(idc.get_struc_by_idx(i))
try:
if re.match(pattern, name, flags):
yield (i, name)
except TypeError as e:
print("**EXCEPTION** {}: {} ({}, {})".format(e.__class__.__name__, str(e), pattern, name))
i = get_next_struc_idx(i)
def get_struc_ordinal_re(pattern, flags = 0):
for i in range(1, idc.get_ordinal_qty()):
name = idc.get_numbered_type_name(i)
if name:
try:
if re.match(pattern, name, flags):
yield (i, name)
except TypeError as e:
print("**EXCEPTION** {}: {} ({}, {})".format(e.__class__.__name__, str(e), pattern, name))
def get_all_struc_ordinals_and_tinfo():
idati = ida_typeinf.get_idati()
for ordinal in range(1, ida_typeinf.get_ordinal_qty(idati)+1):
ti = ida_typeinf.tinfo_t()
if ti.get_numbered_type(idati, ordinal):
yield ordinal, ti
def get_ordinal_tinfo_by_name(name):
idati = ida_typeinf.get_idati()
ti = ida_typeinf.tinfo_t()
for ordinal in range(1, ida_typeinf.get_ordinal_qty(idati)+1):
if ti.get_numbered_type(idati, ordinal) and ti.dstr() == name:
return ti
return BADADDR
def does_struc_exist(name):
if idc.get_struc_id(name) == BADADDR and get_struc_ordinal(name) == BADADDR:
return False
return True
def is_struc_synced(name):
return does_struc_exist(name) and idc.get_struc_id(name) == BADADDR
def does_struc_exist_re(pattern, flags):
l = [x for x in get_struc_ordinal_re(pattern, flags)]
l.extend([x for x in get_struc_idx_re(pattern, flags)])
return len(l) > 0
# def get_struc_name_fuzzy(name):
# choices = [x for x in struct_names()]
# choices.extend([x for x in local_struct_names()])
# print("choices", len(choices))
# return process.extract(name, choices, limit = 5)
BAD_FNNAME_PATTERN = re.compile(r'[^a-zA-Z0-9@$%&().?:_\[\]]')
def safe_func_name(name):
if not BAD_FNNAME_PATTERN.findall(name):
return name
return re.sub(BAD_FNNAME_PATTERN, lambda x: "_x{:02x}_".format(ord(x.group(0))), name)
BAD_C_NAME_PATTERN = re.compile('[^a-zA-Z_0-9:<>,]')
def demangled_name_to_c_str(name):
"""
Removes or replaces characters from demangled symbol so that it was possible to create legal C structure from it
-- from HexRaysPyTools
"""
if not BAD_C_NAME_PATTERN.findall(name):
return name
idx = name.find("::operator")
if idx >= 0:
idx += len("::operator")
if idx == len(name) and not BAD_C_NAME_PATTERN.findall(name[idx]):
pass
elif name[idx:idx + 2] == "==":
name = name.replace("operator==", "operator_EQ_")
elif name[idx:idx + 2] == "!=":
name = name.replace("operator!=", "operator_NEQ_")
elif name[idx] == "=":
name = name.replace("operator=", "operator_ASSIGN_")
elif name[idx:idx + 2] == "+=":
name = name.replace("operator+=", "operator_PLUS_ASSIGN_")
elif name[idx:idx + 2] == "-=":
name = name.replace("operator-=", "operator_MINUS_ASSIGN_")
elif name[idx:idx + 2] == "*=":
name = name.replace("operator*=", "operator_MUL_ASSIGN_")
elif name[idx:idx + 2] == "/=":
name = name.replace("operator/=", "operator_DIV_ASSIGN_")
elif name[idx:idx + 2] == "%=":
name = name.replace("operator%=", "operator_MODULO_DIV_ASSIGN_")
elif name[idx:idx + 2] == "|=":
name = name.replace("operator|=", "operator_OR_ASSIGN_")
elif name[idx:idx + 2] == "&=":
name = name.replace("operator&=", "operator_AND_ASSIGN_")
elif name[idx:idx + 2] == "^=":
name = name.replace("operator^=", "operator_XOR_ASSIGN_")
elif name[idx:idx + 3] == "<<=":
name = name.replace("operator<<=", "operator_LEFT_SHIFT_ASSIGN_")
elif name[idx:idx + 3] == ">>=":
name = name.replace("operator>>=", "operator_RIGHT_SHIFT_ASSIGN_")
elif name[idx:idx + 2] == "++":
name = name.replace("operator++", "operator_INC_")
elif name[idx:idx + 2] == "--":
name = name.replace("operator--", "operator_PTR_")
elif name[idx:idx + 2] == "->":
name = name.replace("operator->", "operator_REF_")
elif name[idx:idx + 2] == "[]":
name = name.replace("operator[]", "operator_IDX_")
elif name[idx] == "*":
name = name.replace("operator*", "operator_STAR_")
elif name[idx:idx + 2] == "&&":
name = name.replace("operator&&", "operator_LAND_")
elif name[idx:idx + 2] == "||":
name = name.replace("operator||", "operator_LOR_")
elif name[idx] == "!":
name = name.replace("operator!", "operator_LNOT_")
elif name[idx] == "&":
name = name.replace("operator&", "operator_AND_")
elif name[idx] == "|":
name = name.replace("operator|", "operator_OR_")
elif name[idx] == "^":
name = name.replace("operator^", "operator_XOR_")
elif name[idx:idx + 2] == "<<":
name = name.replace("operator<<", "operator_LEFT_SHIFT_")
elif name[idx:idx + 2] == ">>":
name = name.replace("operator>", "operator_GREATER_")
elif name[idx:idx + 2] == "<=":
name = name.replace("operator<=", "operator_LESS_EQUAL_")
elif name[idx:idx + 2] == ">=":
name = name.replace("operator>>", "operator_RIGHT_SHIFT_")
elif name[idx] == "<":
name = name.replace("operator<", "operator_LESS_")
elif name[idx] == ">":
name = name.replace("operator>=", "operator_GREATER_EQUAL_")
elif name[idx] == "+":
name = name.replace("operator+", "operator_ADD_")
elif name[idx] == "-":
name = name.replace("operator-", "operator_SUB_")
elif name[idx] == "/":
name = name.replace("operator/", "operator_DIV_")
elif name[idx] == "%":
name = name.replace("operator%", "operator_MODULO_DIV_")
elif name[idx:idx + 2] == "()":
name = name.replace("operator()", "operator_CALL_")
elif name[idx: idx + 6] == " new[]":
name = name.replace("operator new[]", "operator_NEW_ARRAY_")
elif name[idx: idx + 9] == " delete[]":
name = name.replace("operator delete[]", "operator_DELETE_ARRAY_")
elif name[idx: idx + 4] == " new":
name = name.replace("operator new", "operator_NEW_")
elif name[idx: idx + 7] == " delete":
name = name.replace("operator delete", "operator_DELETE_")
elif name[idx] == ' ':
pass
else:
raise AssertionError("Replacement of demangled string by c-string for keyword `operatorXXX` is not yet"
"implemented ({}). You can do it by yourself or create an issue".format(name))
name = name.replace("public:", "")
name = name.replace("protected:", "")
name = name.replace("private:", "")
name = name.replace("~", "DESTRUCTOR_")
name = name.replace("*", "_PTR")
# name = name.replace("<", "_t_")
# name = name.replace(">", "_t_")
name = "_".join(filter(len, BAD_C_NAME_PATTERN.split(name)))
return name
def getString(ptr):
s = ''
null_term = False
invalid_char = None
for i in range(128):
c = Byte(ptr + i)
if c == 0:
null_term = True
break
if c > 122 or c < 32:
invalid_char = c
break
s += "%c" % c
if null_term:
return s
if invalid_char:
raise ValueError("Invalid char '%c'" % c)
raise ValueError("String was not null terminated")
def rename_all_generic_methods():
for fn in Functions():
if not HasUserName(fn):
for ea in seg_refs_to(fn, '.rdata'):
# if not _hasUserName(fn):
# print('rename_all_generic_methods: {}'.format(idc.get_name(ea.to)))
rename_generic_methods(ea.frm)
break
def bin_match(ea, pattern):
start_ea = ida_search.find_binary(ea, ea + 32, pattern, 16, SEARCH_CASE | SEARCH_DOWN | SEARCH_NOSHOW)
if start_ea == ea:
print("bin_match: found: {}".format(pattern))
return True
if debug: print("bin_match: didn't find: {}".format(pattern))
return False
def rename_generic_methods(ea=None):
"""
rename_generic_methods
@param ea: linear address
"""
ea = eax(ea)
_type = "__int64 __fastcall function();"
_is_offset = GetDisasm(ea).startswith('offset', 3)
if _is_offset:
deref = getptr(ea) # idc.get_qword(ea)
start_ea = deref # SkipJumps(deref)
if debug: print("_is_offset: {:x} {}".format(start_ea, GetFuncName(start_ea)))
else:
start_ea = ea
with BatchMode(0):
found = True
while isJmpOrObfuJmp(start_ea):
if not isUnconditionalJmp(start_ea):
retrace(start_ea)
new_ea = SkipJumps(start_ea)
if debug: print("{:x} skipjumps {:x}".format(start_ea, new_ea))
if new_ea == start_ea:
break
start_ea = new_ea
# this condition only reached is jumps skipped
if _is_offset and start_ea != deref:
fnName = ''
if HasUserName(deref):
fnName = idc.get_name(deref)
print('HadUserName', fnName)
MakeNameEx(deref, "", idc.SN_AUTO | idc.SN_NOWARN)
# fnNameTmp = idc.get_name(deref)
# print('ChangedUserName', fnNameTmp)
else:
print('!HasUserName', fnName)
idaapi.del_fixup(ea)
idc.patch_qword(ea, start_ea)
if fnName:
LabelAddressPlus(start_ea, fnName, force=1)
# not needed if del_fixup works
# PatchBytes(start_ea, " ".join(["{:02x}".format(x) for x in get_many_bytes(start_ea, 8)]))
# print("[GetJumpTarget]: {:x}".format(ea))
# ea = GetJumpTarget(ea)
# try:
# retrace(ea)
# except AdvanceFailure:
# ZeroFunction(ea)
# retrace(ea)
if bin_match(start_ea, "48 8d 0d ?? ?? ?? ?? 33 d2 e9 ?? ?? ?? ??"):
ptr = mem(start_ea).chain().add(3).rip(4).value()
try:
s = safe_func_name(getString(ptr))
print("{:x} s: {}".format(start_ea, s))
if s:
MyMakeFunction(start_ea)
LabelAddressPlus(start_ea, "joaat_" + s)
except ValueError:
print("ValueError: 0x{:x}".format(start_ea))
# 48 8D 05 19 D2 01 00 lea rax, ??_R0?AV_lamb
# demangle_name(mem(EA()).add(3).rip(4).name(), DEMNAM_NAME)
# "class _lambda_75c0756d4e96e050ce430f299baa3f2b_ `RTTI Type Descriptor'"
elif bin_match(start_ea, "48 8d 05 ?? ?? ?? ?? c3") or \
bin_match(start_ea, "48 8d 05 ?? ?? ?? ?? 48 8d 64 24 08 ff 64 24 f8"):
ptr = mem(start_ea).add(3).rip(4).value()
try:
print("getString(0x{:x})".format(ptr))
s = safe_func_name(getString(ptr))
s = "s_" + s
except ValueError:
if IsDword(ptr):
v = idc.get_wide_dword(ptr)
MyMakeFunction(start_ea)
j = mega.Lookup(v)
if j[1] != 'x':
s = "joaat_" + j
else:
s = "return_dword_" + j
else:
s = safe_func_name(idc.get_name(ptr, GN_DEMANGLED))
if s:
s = "return_" + s
print("{:x} s: {}".format(start_ea, s))
if s:
MyMakeFunction(start_ea)
LabelAddressPlus(start_ea, "s_" + s)
elif bin_match(start_ea, "48 b8 ?? ?? ?? ?? ?? ?? ?? ?? c3"):
s = hex(GetOperandValue(start_ea, 1))
if s:
MyMakeFunction(start_ea)
LabelAddressPlus(start_ea, "return_" + s)
#
# .text:0000000141046364 000 48 8D 81 48 01 00 00 lea rax, [rcx+148h]
# .text:000000014104636B 000 C3 retn
elif bin_match(start_ea, "48 8D 81 ?? ?? ?? ?? c3"):
s = hex(GetOperandValue(start_ea, 1))
if s:
MyMakeFunction(start_ea)
LabelAddressPlus(start_ea, "return_offset_" + s)
# .text:00000001412C3DA0 000 48 8B 81 18 01 00 00 mov rax, [rcx+118h]
# .text:00000001412C3DA7 000 C3 retn
elif bin_match(start_ea, "48 8B 81 ?? ?? ?? ?? c3"):
s = hex(GetOperandValue(start_ea, 1))
if s:
MyMakeFunction(start_ea)
LabelAddressPlus(start_ea, "return_m_" + s)
# .text:00000001413B98EC 000 48 8B 41 08 mov rax, [rcx+8]
# .text:00000001413B98F0 000 C3
elif bin_match(start_ea, "48 8B 41 ??"):
s = hex(GetOperandValue(start_ea, 1))
if s:
MyMakeFunction(start_ea)
LabelAddressPlus(start_ea, "return_m_" + s)
elif bin_match(start_ea, "b8 ?? ?? 00 00 c3"):
s = hex(MakeSigned(Dword(start_ea+1), 32 ))
if s:
MyMakeFunction(start_ea)
LabelAddressPlus(start_ea, "return_" + s)
elif bin_match(start_ea, "b0 ?? c3"):
s = GetOperandValue(start_ea, 1)
if isinstance(s, int):
MyMakeFunction(start_ea)
LabelAddressPlus(start_ea, "return_" + str(s))
# mov eax, [rcx+8]
# retn
elif bin_match(start_ea, "8b 41 ?? c3"):
s = hex(MakeSigned(Byte(start_ea+2), 32 ))
if s:
MyMakeFunction(start_ea)
LabelAddressPlus(start_ea, "return_dw_field_" + s)
# 8B 81 AC 00 00 00 mov eax, [rcx+0ACh]
# C3 retn
elif bin_match(start_ea, "8b 81 ?? ?? ?? ?? c3"):
s = hex(MakeSigned(Dword(start_ea+2), 32 ))
if s:
MyMakeFunction(start_ea)
LabelAddressPlus(start_ea, "return_dw_field_" + s)
elif bin_match(start_ea, "48 83 C8 FF c3"):
MyMakeFunction(start_ea)
LabelAddressPlus(start_ea, "return_minus_1")
# C2 00 00 retn 0
elif bin_match(start_ea, "c2 00 00"):
MyMakeFunction(start_ea)
LabelAddressPlus(start_ea, "nullretn_{:X}".format(start_ea))
elif GetNumChunks(start_ea) == 0:
found = False
dis1 = diida(GetFuncStart(start_ea), GetFuncEnd(start_ea))
if debug: print("dis1: {}".format(dis1))
"""
mov rax, [rcx]
jmp qword [rax+0x10]
"""
if not found:
match = re.match(r'mov rax, \[rcx\]\njmp qword \[rax\+(?:0x)([0-9a-fA-F]+)\]', dis1)
if match:
offset = parseHex(match.group(1)) // ptrsize()
found = True
MyMakeFunction(start_ea)
LabelAddressPlus(start_ea, "return_jump_m_{:x}".format(offset))
_type = "__int64 __fastcall function(void* a1);"
if not found:
match = re.match(r'mov eax, (?:0x)([0-9a-fA-F]+)\nret', dis1)
if match:
offset = parseHex(match.group(1))
found = True
j = mega.Lookup(offset)
if j[1] != 'x':
LabelAddressPlus(start_ea, "joaat_" + j)
else:
LabelAddressPlus(start_ea, "return_dword_" + j)
MyMakeFunction(start_ea)
# LabelAddressPlus(start_ea, "return_0x{:x}".format(offset))
_type = "int __fastcall function();"
if not found:
dis = dis1.split('\n')
if len(dis) == 2 and (dis[1].startswith('retn') or dis[1].endswith('retn')):
if dis[0].startswith('xor'):
lhs = string_between(' ', ',', dis[0])
rhs = string_between(',', '', dis[0]).strip()
if lhs == rhs:
if lhs in ["rax", "eax", "ax", "ah", "al"]:
found = True
MyMakeFunction(start_ea)
if lhs == 'al':
LabelAddressPlus(start_ea, "return_false".format(start_ea))
else:
LabelAddressPlus(start_ea, "return_0".format(start_ea))
else:
found = False
if found:
SetType(start_ea, _type)
def get_class_informer(ea, silent=False):
comment = idc.get_extra_cmt(ea, E_PREV+1)
if comment is not None:
regex = r"; class (.*?): (.*?);\s*?(\[[MI]+\])?\s*?\(#classinformer\)"
for (className, classParents, classFlags) in re.findall(regex, comment):
classHierarchy = classParents.split(", ")
# print("class: {0} {2} parents: {1} ".format(className, classParents, classFlags))
classList = [className]
classList.extend(classHierarchy)
return classList
# fallback for classes with no inheritance
regex = r"; (?:class|struct) (.*?):\s*?(\[[MI]+\])?\s*?\(#classinformer\)"
for (className, classFlags) in re.findall(regex, comment):
# print("class: {0} {2} parents: {1} ".format(className, "none", classFlags))
classList = [className]
return classList
if not silent:
print("0x%x Failed to scan with regex: %s" % (ea, comment))
return None
def find_vtable_start(ref, fixVtables=0):
if SegName(ref) == '.rdata':
addr = ref
while not Name(addr).startswith('??_7') and SegName(addr) == '.rdata' and GetDisasm(addr).startswith(
'dq offset'):
addr = idc.prev_head(addr)
if Name(addr).startswith('??_7'):
refName = Demangle(Name(addr), DEMNAM_FIRST)
if not refName:
refName = "unknown_vftable_0x%x" % addr
functionRefs[target].add(addr)
className = refName.replace("::`vftable'", "")
offsetName = "m_{:x}".format(ref - addr)
if fixVtables:
ClassMakerFamily(ea=addr, redo=1)
def classmaker_get_vtable(ea):
return idc.get_enum_member_name(ea)
def make_code_and_wait(ea, force = False, comment = ""):
"""
make_code_and_wait(ea)
Create an instruction at the specified address, and Wait() afterwards.
@param ea: linear address
@return: 0 - can not create an instruction (no such opcode, the instruction
would overlap with existing items, etc) otherwise returns length of the
instruction in bytes
"""
if idc.get_wide_byte(ea) == 0xcc:
# print("0x%x: %s can't make 0xCC into code" % (ea, comment))
return 0
while idc.is_data(idc.get_full_flags(idc.get_item_head(ea))):
# print("// 0x%012x: make_code_and_wait - FF_DATA - MakeUnknown" % ea)
idc.MakeUnknown(idc.get_item_head(ea), idc.next_not_tail(ea) - idc.get_item_head(ea), 0)
Wait()
if idc.is_tail(idc.get_full_flags(ea)):
idc.MakeUnknown(idc.get_item_head(ea), ea - idc.get_item_head(ea), 0)
for i in range(32):
if not idc.create_insn(ea):
idc.MakeUnknown(ea, i, 0)
insLen = idc.create_insn(ea)
if insLen == 0:
if force:
# print("// 0x%x: %s %s" % (ea, comment, idc.GetDisasm(ea)))
count = 0
# This should work, as long as we are not started mid-stream
while not insLen and count < 16: # and idc.next_head(ea) != idc.next_not_tail(ea):
count += 1
idc.MakeUnknown(idc.get_item_head(ea), count, 0)
Wait()
insLen = make_code_and_wait(ea)
# print("0x%x: make_code_and_wait: making %i unknown bytes (insLen now %i): %s" % (ea, count, insLen, idc.GetDisasm(ea + count)))
if count > 0:
print("// 0x%x: make_code_and_wait: made %i unknown bytes (insLen now %i): %s" % (ea, count, insLen, idc.GetDisasm(ea + count)))
# print("0x%x: make_code_and_wait returning %i" % (ea, count))
Wait()
return insLen
def fix_offset(ea=None):
"""
fix_offset
@param ea: linear address
"""
ea = eax(ea)
if idc.get_full_flags(ea) & 0x30500500 == 0x30500500 and idc.GetDisasm(ea).startswith("dq offset"):
target = getptr(ea)
if SegName(target) != '.text':
return False
if target != idc.get_item_head(getptr(ea)) or not IsFuncHead(target):
if not ForceFunction(target) and retrace(target) != 0:
raise Exception("{:x} Couldn't make function from offset {:x}".format(ea, target))
idc.add_func(target)
return True
def fix_offset_test_loop(ea=None, end_ea=None):
"""
fix_offset_test_loop
@param ea: linear address
"""
ea = eax(ea)
end_ea = end_ea or ea + ptrsize()
ea = ea - ptrsize()
try:
while ea <= end_ea and SegName(ea) == '.rdata':
found = FindText(ea+ptrsize(), SEARCH_DOWN | SEARCH_CASE | SEARCH_REGEX, 0, 0, "dq offset (((unk|loc|qword|dword|word|byte|sub)\w+)|(\w+[+-]))")
ea = ea + ptrsize()
if found == ea:
if not fix_offset(ea):
continue
rename_generic_methods(ea)
SetFuncFlags(Qword(EA()), lambda x: x & ~FUNC_LIB)
except KeyboardInterrupt:
return
def alternate_fn_offset_name(fnName):
# dq offset ?narrow@?$ctype@D@std@@QEBADDD@Z_11; std::ctype<char>::narrow(char,char)
if not re.match(r'(dq offset \w)', fnName):
if re.match(r'(.*; \w)', fnName):
fnName = re.sub(r'(dq offset [^\w][^;]+; (.+))', r'dq offset \2', fnName)
fnName = re.sub(r'[^\w]', '_', fnName).replace('dq_offset_', '')
def class_get_member(ea):
if idc.get_full_flags(ea) & 0x30500500 == 0x30500500 and (idc.GetDisasm(ea).startswith("dq offset") or idc.GetDisasm(ea).startswith("dd offset") ):
if not IsFuncHead(getptr(ea)):
print("fixing offset: 0x{:x}".format(ea))
fix_offset(ea)
disasm = idc.GetDisasm(ea)
if disasm is not None and disasm.startswith("dq offset"):
regex = r"^d[dq] offset ([^; ]+)(.*)"
for (fnName, offsetComment) in re.findall(regex, disasm):
# dprint("[debug] fnName, offsetComment")
print("[debug] fnName:{}, offsetComment:{}".format(fnName, offsetComment))
if not re.match(r'(d[dq] offset \w)', fnName):
fnName = alternate_fn_offset_name(disasm)
if fnName:
fnName = fnName[10:]
rawFnLoc = getptr(ea)
# print("member_function: {0} / {2} comments: {1}".format(fnName, offsetComment, rawFnName))
# print('rename_generic_methods {:x}'.format(rawFnLoc))
rename_generic_methods(rawFnLoc)
idc.auto_wait()
if not fix_offset(rawFnLoc):
print("failed to fix_offset at 0x{:x}".format(rawFnLoc))
return False
idc.auto_wait()
rawFnName = idc.get_name(rawFnLoc) # can't be trusted for much
return rawFnName
return None
def process_usercall_args(test_str):
abi = [['rcx', 'ecx', 'cx', 'ch', 'cl', 'xmm0'],
['rdx', 'edx', 'dx', 'dh', 'dl', 'xmm1'],
['r8', 'r8d', 'r8w', 'r12b', 'r8b', 'xmm2'],
['r9', 'r9d', 'r9w', 'r14b', 'r9b', 'xmm3']]
regex = r"""
(?:(?P<type>[a-zA-Z_][a-zA-Z0-9_ *]+?) (?P<name>\w+) (?:@<(?P<register>[^>]+)>)?) (?# end) (?:, |[)])
"""
args = list([None,None,None,None])
matches = re.finditer(regex, test_str, re.VERBOSE)
for matchNum, match in enumerate(matches, start=1):
(_type, _name, _register) = match.groups()
# print("// {}, {}, {}, {}".format(matchNum, _type, _name, _register))
for position, registers in enumerate(abi):
if _register in registers:
args[position] = _type
while len(args) and args[len(args)-1] is None:
args = args[0:len(args)-1]
result = list()
for count, _type in enumerate(args):
if _type is None:
_type = "void*"
result.append("%s a%i" % (_type.strip(), count + 1))
return result
def remove_usercall(ea, offset=0):
try:
cfunc = idaapi.decompile(ea)
func_def = str(cfunc).split("\n")
decl = [x for x in func_def if len(x) and not x[0] == '/'][0]
if decl is not None:
if ~decl.find("__usercall"):
args = string_between("(", ")", decl, greedy = True, inclusive = True)
fnNameType = decl.replace(args, '').replace('__usercall', '__fastcall')
fnNameType = re.sub(r"@<[^>]+>", "", fnNameType)
decl = "%s(%s)" % (fnNameType, ", ".join(process_usercall_args(args)))
# print("// Attempting to alter __usercall member to: %s" % decl)
idc.SetType(ea, decl)
Wait()
except ida_hexrays.DecompilationFailure:
print("// %s: DecompilationFailure: 0x0%0x" % (fnName, ea))
return make_vfunc_struct_sig("void", "__fastcall", "error_%s_%02x" % (fnName, offset), "void*", offset=offset)
def sanitizedName(className, allowSpaces=True):
# ('Not accepted: {}', 'void __fastcall CTrackedEventInfo__unsigned__int64__::m_8(CTrackedEventInfo<unsigned __int64>* self)')
if isinstance(className, list):
return [sanitizedName(x) for x in className]
elif isinstance(className, str):
# absolutely no spaces between < >
if not allowSpaces:
# className = className.replace(' ', '')
return demangled_name_to_c_str(className)
className = string_between('<', '>', className, greedy=1, inclusive=1, repl=demangled_name_to_c_str) # lambda x: x.replace(' ', ''))
# className = className.replace('<', '__').replace('>','__').replace(',','_') # .replace(' ','')
return className
else:
raise Exception("Unknown type: {}".format(type(className)))
def make_vfunc_struct_sig(returnType, callType, fnName, args, offset=0):
if isinstance(args, str):
joinedArgs = args
else:
joinedArgs = ", ".join(args)
if callType == "__stdcall" or callType is None:
callType = "__fastcall"
if offset == 0 and fnName.endswith('::m_0'):
returnType = 'void'
return " %s (%s *%s)(%s);" % (returnType, callType, fnName, joinedArgs)
def make_vfunc_function_sig(returnType, callType, fnName, args, offset=0):
"""
Garbage In: __int64 (__fastcall *__fastcall CRawClipFileView::m_8(__int64 a1, int a2, char a3))()
Garbage Out: __int64 CRawClipFileView::m_8(CRawClipFileView*__hidden this, int a2, char a3))();
"""
if isinstance(args, str):
joinedArgs = args
else:
joinedArgs = ", ".join(args)
if callType == "__stdcall":
callType = "__fastcall"
if offset == 0 and fnName.endswith('::m_0'):
returnType = 'void'
return "%s %s %s(%s);" % (returnType, callType, fnName, joinedArgs)
def fix_fnName(fnName, offset=0):
# if re.match(r'.*_m_[0-9a-fA-F]+$', fnName)
fnName = TagRemoveSubstring(fnName)
# if fnName.endswith('m_{:x}'.format(offset)):
# return fnName
# fnName += "_m_%x" % offset
fnName = string_between('::', '', fnName, rightmost=1, retn_all_on_fail=1)
return fnName
def make_member_type(decl, memberType = None, fnNameAlt = None, offset=0):
global __class_maker_member_names
if decl:
regex = r"(.*?) ?((?:(?:__array_ptr|__cdecl|__export|__far|__fastcall|__hidden|__huge|__import|__near|__noreturn|__pascal|__pure|__restrict|__return_ptr|__spoils|__stdcall|__struct_ptr|__thiscall|__thread|__unaligned|__usercall|__userpurge) )*)([^* ]*?)\((.*)\)"
for (returnType, callType, fnName, fnArgs) in re.findall(regex, decl):
fnName = TagRemoveSubstring(fnName)
# print('//{:12}|{:10}|{}|{}|{}'.format(returnType, callType, fnName, fnArgs, decl))
if fnNameAlt:
fnName = fnNameAlt
fnName = TagRemoveSubstring(fnName)
args = fnArgs.split(", ")
if memberType and len(args): # and not args[0].endswith("self"):
# print("memberType", memberType, args[0])
args[0] = memberType
fnName = fix_fnName(fnName, offset=offset)
return make_vfunc_struct_sig(returnType, callType, fnName, sanitizedName(args), offset=offset)
print("// Unrecognised function signature: {}".format(decl))
return make_vfunc_struct_sig("void", "__fastcall", "error_%02x" % offset, "void*", offset=offset)
def get_func_def(func_def):
print("[get_func_def] {}".format(func_def))
decl = ""
for x in func_def.split("\n"):
if not x:
break;
if x[0] == '/':
continue
if x[0] == '{':
break
decl += " " + x.lstrip()
# decl = "".join([x for x in func_def if len(x) and not x[0] == '/'])
return decl.lstrip()
def decompile_member(ea, memberType, fnNameAlt = None, offset=0):
global __class_maker_member_names
# dprint("[decompile_member] ea, memberType, fnNameAlt, offset")
print("[decompile_member] ea:{}, memberType:{}, fnNameAlt:{}, offset:{}".format(ahex(ea), memberType, fnNameAlt, offset))
try:
cfunc = idaapi.decompile(ea)
if not cfunc:
ForceFunction(ea)
cfunc = idaapi.decompile(ea)
if not cfunc:
print("idaapi.decompile(0x{:x}) failed".format(ea))
# func_def = str(cfunc).split("\n")
decl = get_func_def(str(cfunc))
# dprint("[decompile_member] func_def")
if decl is not None:
print("decl: %s" % decl)
decl = re.sub("__noreturn", "", decl)
# fix up any __usercall methods
if ~decl.find("__usercall"):
print("// Attempting to alter __usercall member to: %s" % decl)
remove_usercall(ea, offset=offset)
idaapi.decompile(ea)
remove_usercall(ea, offset=offset)
cfunc = idaapi.decompile(ea)
func_def = str(cfunc).split("\n")
decl = [x for x in func_def if len(x) and not x[0] == '/'][0]
regex = r"(.*?) ?(__array_ptr|__cdecl|__export|__far|__fastcall|__hidden|__huge|__import|__near|__noreturn|__pascal|__pure|__restrict|__return_ptr|__spoils|__stdcall|__struct_ptr|__thiscall|__thread|__unaligned|__usercall|__userpurge)? ?([^* ]*?)\((.*)\)"
for (returnType, callType, fnName, fnArgs) in re.findall(regex, decl):
if returnType == "_BOOL8": returnType = "bool"
if fnNameAlt:
fnName = fnNameAlt
args = fnArgs.split(", ")
if not args[0].startswith("void"):
args[0] = memberType
fnName = fix_fnName(fnName, offset=offset)
fnSig = make_vfunc_function_sig(returnType, callType, fnName, (args), offset=offset)
strSig = make_vfunc_struct_sig(returnType, callType, fnName, (args), offset=offset)
if not idc.SetType(ea, fnSig):
# print("Initial type not accepted: {}".format(fnSig))
fnSig = make_vfunc_function_sig(returnType, callType, fnName, (sanitizedName(args)), offset=offset)
strSig = make_vfunc_struct_sig(returnType, callType, fnName, (sanitizedName(args)), offset=offset)
if not idc.SetType(ea, fnSig):
if not idc.SetType(ea, fnSig.replace('))();', ');')):
# if not idc.SetType(ea, "__int64 fn({}* self);".format(memberType)):
print("0x{:x} Final type Not accepted: {}".format(ea, fnSig))
# else:
# print("Final type accepted: {}".format(fnSig))
# const char *(__fastcall *GetName)(CNetGamePlayer *);
return strSig
except KeyboardInterrupt as e:
raise e
except ida_hexrays.DecompilationFailure:
print("// DecompilationFailure: 0x0%0x" % (ea))
return make_vfunc_struct_sig("void", "__fastcall", "error_%0xd" % offset, "", offset=offset)
def ClassMaker(ea, memberType = None, className = None, famList=None, parentTypeName = None, redo = False, vtableOnly = False):
"""
ea should be the location of the vtable line:
; const rage::CSyncDataReader::`vftable'
ClassMaker(idc.get_screen_ea())
or
ClassMaker(idc.get_screen_ea(), "CPed *self")
"""
famList = A(famList)
global __class_maker_member_names
global __class_maker_struct
__class_maker_struct = []
__class_maker_member_names = []
if not className:
# classList = get_class_informer(ea - 8)
if classList is None:
raise Exception("'{:x}' is not a class".format(ea))
# classHierarchy = classList[1:]
# className = classList[0]
try:
ourFamPos = famList.index(className)
print("className: {} famList: {} (ourFamPos: {})\n".format(sanitizedName(className), famList[ourFamPos+1:], ourFamPos))
except ValueError:
ourFamPos = -1
vtable = classmaker_get_vtable(ea)
if vtable is None:
raise Exception("Not a vtable")
# print("// className (pre-processing): %s" % className)
# className = re.sub(r"^.*::", "", className)
# Lets not remove rage::
# className = re.sub(r'rage::', '', className).replace('<', '__').replace('>','__').replace(',','_').replace(' ','')
className = sanitizedName(className)
# print("// className (post-processing): %s" % className)
# return
if not vtableOnly:
defn = ''
vtbl_name = "%s_vtbl" % className
if not does_struc_exist(vtbl_name):
defn += "struct /*VFT*/ %s_vtbl;\n" % className
# if idc.get_struc_id(className) == BADADDR and get_struc_ordinal(className) == BADADDR:
if not does_struc_exist(className):
decls = {}
if False and IdaRestClient.GetTypes(vtbl_name, decls):
defn += decls[vtbl_name]
else:
if parentTypeName is not None:
defn += ("struct __cppobj %s : %s { %s_vtbl* __vftable; };\n" % (className, parentTypeName, className))
else:
defn += ("struct %s { %s_vtbl* __vftable; };\n" % (className, className))
rv = idc.parse_decls(defn, PT_SILENT | PT_REPLACE | PT_RAWARGS | PT_NDC)
if rv:
print("Couldn't parse defn (a):\n\n{}\n".format(defn))
# raise Exception("Couldn't parse")
defn = ''