-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathida2llvm.py
1692 lines (1516 loc) · 76.7 KB
/
ida2llvm.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 idc
import ida_idaapi
import ida_kernwin
import idautils
import ida_name
import ida_bytes
import ida_ida
import ida_funcs
import ida_typeinf
import ida_segment
import ida_nalt
import ida_hexrays
import itertools
import idaapi
import logging
import struct
import numpy as np
import llvmlite.binding as llvm
from llvmlite import ir
from contextlib import suppress
i8ptr = ir.IntType(8).as_pointer()
ptrsize = 64 if ida_idaapi.get_inf_structure().is_64bit() else 32
ptext = {}
def lift_tif(tif: ida_typeinf.tinfo_t, width = -1) -> ir.Type:
"""
Lifts the given IDA type to corresponding LLVM type.
If IDA type is an array/struct/tif, type lifting is performed recursively.
:param tif: the type to lift, in IDA
:type tif: ida_typeinf.tinfo_t
:raises NotImplementedError: variadic structs
:return: lifted LLVM type
:rtype: ir.Type
"""
if tif.is_func():
ida_rettype = tif.get_rettype()
ida_args = (tif.get_nth_arg(i) for i in range(tif.get_nargs()))
is_vararg = tif.is_vararg_cc()
llvm_rettype = lift_tif(ida_rettype)
llvm_args = (lift_tif(arg) for arg in ida_args)
return ir.FunctionType(i8ptr if isinstance(llvm_rettype, ir.VoidType) else llvm_rettype, llvm_args, var_arg = is_vararg)
elif tif.is_ptr():
child_tif = tif.get_ptrarr_object()
if child_tif.is_void():
return ir.IntType(8).as_pointer()
return lift_tif(child_tif).as_pointer()
elif tif.is_array():
child_tif = tif.get_ptrarr_object()
element = lift_tif(child_tif)
count = tif.get_array_nelems()
if count == 0:
# an array with an indeterminate number of elements = type pointer
tif.convert_array_to_ptr()
return lift_tif(tif)
return ir.ArrayType(element, count)
elif tif.is_void():
return ir.VoidType()
elif tif.is_udt():
udt_data = ida_typeinf.udt_type_data_t()
tif.get_udt_details(udt_data)
type_name = tif.get_type_name()
context = ir.context.global_context
type_name = "struct" if type_name == None else type_name
if type_name not in context.identified_types:
struct_t = context.get_identified_type(type_name)
elementTypes = []
for idx in range(udt_data.size()):
udt_member = udt_data.at(idx)
if udt_member.type.get_type_name() in context.identified_types:
elementTypes.append(context.identified_types[udt_member.type.get_type_name()])
else:
element = lift_tif(udt_member.type)
elementTypes.append(element)
struct_t.set_body(*elementTypes)
return context.get_identified_type(type_name)
elif tif.is_bool():
return ir.IntType(1)
elif tif.is_char():
return ir.IntType(8)
elif tif.is_float():
return ir.FloatType()
elif tif.is_double():
return ir.DoubleType()
# elif tif.is_ldouble():
# return ir.DoubleType()
elif tif.is_decl_int() or tif.is_decl_uint() or tif.is_uint() or tif.is_int():
return ir.IntType(tif.get_size()*8)
elif tif.is_decl_int16() or tif.is_decl_uint16() or tif.is_uint16() or tif.is_int16():
return ir.IntType(tif.get_size()*8)
elif tif.is_decl_int32() or tif.is_decl_uint32() or tif.is_uint32() or tif.is_int32():
return ir.IntType(tif.get_size()*8)
elif tif.is_decl_int64() or tif.is_decl_uint64() or tif.is_uint64() or tif.is_int64():
return ir.IntType(tif.get_size()*8)
elif tif.is_decl_int128() or tif.is_decl_uint128() or tif.is_uint128() or tif.is_int128():
return ir.IntType(tif.get_size()*8)
elif tif.is_ext_arithmetic() or tif.is_arithmetic():
return ir.IntType(tif.get_size()*8)
else:
if width != -1:
return ir.ArrayType(ir.IntType(8), width)
else:
return ir.IntType(ptrsize)
def typecast(src: ir.Value, dst_type: ir.Type, builder: ir.IRBuilder, signed: bool = False) -> ir.Value:
"""
Given some `src`, convert it to type `dst_type`.
Instructions are emitted into `builder`.
:param src: value to convert
:type src: ir.Value
:param dst_type: destination type
:type dst_type: ir.Type
:param builder: builds instructions
:type builder: ir.IRBuilder
:param signed: whether to preserve signness, defaults to True
:type signed: bool, optional
:raises NotImplementedError: type conversion not supported
:return: value after typecast
:rtype: ir.Value
"""
if src.type != dst_type:
if isinstance(src.type, ir.PointerType) and isinstance(dst_type, ir.PointerType):
return builder.bitcast(src, dst_type)
elif isinstance(src.type, ir.PointerType) and isinstance(dst_type, ir.IntType):
return builder.ptrtoint(src, dst_type)
elif isinstance(src.type, ir.IntType) and isinstance(dst_type, ir.PointerType):
return builder.inttoptr(src, dst_type)
elif isinstance(src.type, ir.IntType) and isinstance(dst_type, ir.FloatType):
return builder.uitofp(src, dst_type)
elif isinstance(src.type, ir.FloatType) and isinstance(dst_type, ir.IntType):
if signed == False:
return builder.fptoui(src, dst_type)
else:
return builder.fptosi(src, dst_type)
elif isinstance(src.type, ir.DoubleType) and isinstance(dst_type, ir.IntType):
if signed == False:
return builder.fptoui(src, dst_type)
else:
return builder.fptosi(src, dst_type)
elif isinstance(src.type, ir.FloatType) and isinstance(dst_type, ir.FloatType):
return src
elif isinstance(src.type, ir.IntType) and isinstance(dst_type, ir.IntType) and src.type.width < dst_type.width:
if signed:
return builder.sext(src, dst_type)
else:
return builder.zext(src, dst_type)
elif isinstance(src.type, ir.IntType) and isinstance(dst_type, ir.IntType) and src.type.width > dst_type.width:
return builder.trunc(src, dst_type)
elif isinstance(src.type, ir.IntType) and isinstance(dst_type, ir.DoubleType):
return builder.uitofp(src, dst_type)
elif isinstance(src.type, ir.FloatType) and isinstance(dst_type, ir.DoubleType):
return builder.fpext(src, dst_type)
elif isinstance(src.type, ir.DoubleType) and isinstance(dst_type, ir.FloatType):
return builder.fptrunc(src, dst_type)
elif (isinstance(src.type, ir.DoubleType) or isinstance(src.type, ir.FloatType)) and isinstance(dst_type, ir.PointerType):
if signed == False:
tmp = builder.fptoui(src, ir.IntType(ptrsize))
else:
tmp = builder.fptosi(src, ir.IntType(ptrsize))
return builder.inttoptr(tmp, dst_type)
elif (isinstance(dst_type, ir.DoubleType) or isinstance(dst_type, ir.FloatType)) and isinstance(src.type, ir.PointerType):
tmp = builder.ptrtoint(src, ir.IntType(ptrsize))
return builder.uitofp(tmp, dst_type)
elif isinstance(dst_type, ir.IdentifiedStructType) or isinstance(dst_type, ir.ArrayType):
with builder.goto_entry_block():
tmp = builder.alloca(src.type)
builder.store(src, tmp)
src = builder.load(builder.bitcast(tmp, dst_type.as_pointer()))
elif isinstance(src.type, ir.IdentifiedStructType) or isinstance(src.type, ir.ArrayType):
with builder.goto_entry_block():
tmp = builder.alloca(src.type)
builder.store(src, tmp)
src = builder.load(builder.bitcast(tmp, dst_type.as_pointer()))
else:
return builder.bitcast(src, dst_type)
return src
def storecast(src, dst, builder):
"""
This function cast type of dst into pointer of src.
"""
if dst != None and dst.type != src.type.as_pointer():
dst = typecast(dst, src.type.as_pointer(), builder)
return dst
def get_offset_to(builder: ir.IRBuilder, arg: ir.Value, off: int = 0) -> ir.Value:
"""
A Value can be indexed relative to some offset.
:param arg: value to index from
:type arg: ir.Value
:param off: offset to index, defaults to 0
:type off: int, optional
:return: value after indexing by off
:rtype: ir.Value
"""
if isinstance(arg.type, ir.PointerType) and isinstance(arg.type.pointee, ir.ArrayType):
arr = arg.type.pointee
td = llvm.create_target_data("e")
size = arr.element.get_abi_size(td)
return builder.gep(arg, (ir.Constant(ir.IntType(32), 0), ir.Constant(ir.IntType(32), off // size),))
# elif isinstance(arg.type, ir.PointerType) and isinstance(arg.type.pointee, ir.LiteralStructType):
# return typecast(arg, ir.IntType(8).as_pointer(), builder)
elif isinstance(arg.type, ir.PointerType) and isinstance(arg.type.pointee, ir.IdentifiedStructType):
return typecast(arg, ir.IntType(8).as_pointer(), builder)
elif isinstance(arg.type, ir.PointerType) and off > 0:
td = llvm.create_target_data("e")
size = arg.type.pointee.get_abi_size(td)
return builder.gep(arg, (ir.Constant(ir.IntType(32), off // size),))
else:
return arg
def dedereference(arg: ir.Value) -> ir.Value:
"""
A memory address is deferenced if the memory at the address is loaded.
In LLVM, a LoadInstruction instructs the CPU to perform the dereferencing.
In cases where we wish to retrieve the memory address, we "de-dereference".
- this is needed as IDA microcode treats all LVARS as registers
- whereas during lifting we treat all LVARS as stack variables (in accordance to LLVM SSA)
:param arg: value to de-dereference
:type arg: ir.Value
:raises NotImplementedError: arg is not of type LoadInstr
:return: original memory address
:rtype: ir.Value
"""
if isinstance(arg, ir.LoadInstr):
return arg.operands[0]
elif isinstance(arg.type, ir.PointerType):
return arg
else:
raise NotImplementedError(f"not implemented: get reference for object {arg} of type {arg.type}")
def lift_type_from_address(ea: int, pfunc=None):
if ida_funcs.get_func(ea) != None and ida_segment.segtype(ea) & ida_segment.SEG_XTRN:
# let's assume its a function that returns ONE register and takes in variadic arguments
ida_func_details = ida_typeinf.func_type_data_t()
void = ida_typeinf.tinfo_t()
void.create_simple_type(ida_typeinf.BTF_VOID)
ida_func_details.rettype = void
ida_func_details.cc = ida_typeinf.CM_CC_ELLIPSIS | ida_typeinf.CC_CDECL_OK
function_tinfo = ida_typeinf.tinfo_t()
function_tinfo.create_func(ida_func_details)
return function_tinfo
if ea in ptext:
return ptext[ea].type
tif = ida_typeinf.tinfo_t()
ida_nalt.get_tinfo(tif, ea)
if not ida_nalt.get_tinfo(tif, ea):
ida_typeinf.guess_tinfo(tif, ea)
return tif
def analyze_insn(module, ida_insn, ea):
"""
This function analyze is there mismatch function call.
A call B with 3 arguments but B has 4 arguments.
This typically owing to IDA type propagation, sometimes will be solved by re-decompile.
"""
if ida_insn.opcode == ida_hexrays.m_call:
callnum = len(ida_insn.d.f.args)
if ida_insn.l.t == ida_hexrays.mop_v:
temp_ea = ida_insn.l.g
func_name = ida_name.get_name(temp_ea)
if ((ida_funcs.get_func(temp_ea) is not None)
and (ida_funcs.get_func(temp_ea).flags & ida_funcs.FUNC_THUNK)):
tfunc_ea, ptr = ida_funcs.calc_thunk_func_target(ida_funcs.get_func(temp_ea))
if tfunc_ea != ida_idaapi.BADADDR:
temp_ea = tfunc_ea
func_name = ida_name.get_name(temp_ea)
tif = lift_type_from_address(temp_ea)
if tif.is_func() or tif.is_funcptr():
argnum = tif.get_nargs()
with suppress(KeyError):
if func_name == "":
func_name = f"data_{hex(ea)[2:]}"
if hasattr(module.get_global(func_name
), "args"):
argnum = len(module.get_global(func_name).args)
if callnum != argnum:
ida_hf = ida_hexrays.hexrays_failure_t()
try:
pfunc = ida_hexrays.decompile(temp_ea, ida_hf, ida_hexrays.DECOMP_NO_CACHE)
if pfunc != None:
ptext[temp_ea] = pfunc
except:
pass
try:
pfunc = ida_hexrays.decompile(ea, ida_hf, ida_hexrays.DECOMP_NO_CACHE)
if pfunc != None:
ptext[ea] = pfunc
except:
return
if ida_insn.l.t == ida_hexrays.mop_d:
analyze_insn(module, ida_insn.l.d, ea)
if ida_insn.r.t == ida_hexrays.mop_d:
analyze_insn(module, ida_insn.r.d, ea)
if ida_insn.d.t == ida_hexrays.mop_d:
analyze_insn(module, ida_insn.d.d, ea)
return
def lift_from_address(module: ir.Module, ea: int, typ: ir.Type = None):
if typ is None:
tif = lift_type_from_address(ea)
typ = lift_tif(tif)
return _lift_from_address(module, ea, typ)
def _lift_from_address(module: ir.Module, ea: int, typ: ir.Type):
if isinstance(typ, ir.FunctionType):
func_name = ida_name.get_name(ea)
if func_name == "":
func_name = f"data_{hex(ea)[2:]}"
res = module.get_global(func_name)
res.lvars = dict()
if ea in ptext:
pfunc = ptext[ea]
else:
return res
# refresh function call.
# some functions caller and signature maybe mismatch. refresh with re-decompile.
mba = pfunc.mba
for index in range(mba.qty):
ida_blk = mba.get_mblock(index)
ida_insn = ida_blk.head
while ida_insn is not None:
analyze_insn(module, ida_insn, ea)
ida_insn = ida_insn.next
if ea in ptext:
pfunc = ptext[ea]
else:
return res
mba = pfunc.mba
for index in range(mba.qty):
res.append_basic_block(name = f"@{index}")
ida_func_details = ida_typeinf.func_type_data_t()
tif = lift_type_from_address(ea, pfunc)
tif.get_func_details(ida_func_details)
names = []
builder = ir.IRBuilder(res.entry_basic_block)
with builder.goto_entry_block():
# declare function results as stack variable
if not isinstance(typ.return_type, ir.VoidType):
res.lvars["funcresult"] = builder.alloca(typ.return_type, name = "funcresult")
for lvar in list(pfunc.lvars):
if lvar.is_result_var:
continue
arg_t = lift_tif(lvar.tif)
res.lvars[lvar.name] = builder.alloca(arg_t, name = lvar.name)
if lvar.is_arg_var:
names.append(lvar.name)
# if function is variadic, declare va_start intrinsic
if tif.is_vararg_cc() and typ.var_arg:
ptr = builder.alloca(ir.IntType(8).as_pointer(), name = "ArgList")
res.lvars["ArgList"] = ptr
va_start = module.declare_intrinsic('llvm.va_start', fnty=ir.FunctionType(ir.VoidType(), [ir.IntType(8).as_pointer()]))
ptr = builder.load(ptr)
builder.call(va_start, (ptr, ))
# store stack variables
for arg, arg_n in zip(res.args, names):
arg = typecast(arg, res.lvars[arg_n].type.pointee, builder)
builder.store(arg, res.lvars[arg_n])
with builder.goto_block(res.blocks[-1]):
if isinstance(typ.return_type, ir.VoidType):
builder.ret_void()
else:
builder.ret(builder.load(res.lvars["funcresult"]))
# lift each bblk in cfg
for index, blk in enumerate(res.blocks):
ida_blk = mba.get_mblock(index)
ida_insn = ida_blk.head
while ida_insn is not None:
lift_insn(ida_insn, blk, builder)
ida_insn = ida_insn.next
if not blk.is_terminated and index + 1 < len(res.blocks):
with builder.goto_block(blk):
builder.branch(res.blocks[index + 1])
# if function is variadic, declare va_end intrinsic
if tif.is_vararg_cc() and typ.var_arg:
ptr = res.lvars["ArgList"]
va_end = module.declare_intrinsic('llvm.va_end', fnty=ir.FunctionType(ir.VoidType(), [ir.IntType(8).as_pointer()]))
with builder.goto_block(res.blocks[-1]):
ptr = builder.load(ptr)
builder.call(va_end, (ptr, ))
return res
elif isinstance(typ, ir.IntType):
# should probably check endianness, BOOL type is IntType(1)
r = ida_bytes.get_bytes(ea, 1 if typ.width // 8 < 1 else typ.width // 8)
return typ(0) if r == None else typ(int.from_bytes(r, "little"))
elif isinstance(typ, ir.FloatType):
r = ida_bytes.get_bytes(ea, 4)
value = struct.unpack('f', r)
return typ(np.float32(0)) if r == None else typ(np.float32(value[0]))
elif isinstance(typ, ir.DoubleType):
r = ida_bytes.get_bytes(ea, 8)
value = struct.unpack('d', r)
return typ(np.float64(0)) if r == None else typ(np.float64(value[0]))
elif isinstance(typ, ir.PointerType):
val = ir.Constant(typ, None)
return val
elif isinstance(typ, ir.ArrayType):
td = llvm.create_target_data("e")
subSize = typ.element.get_abi_size(td)
array = [ lift_from_address(module, sub_ea, typ.element)
for sub_ea in range(ea, ea + subSize * typ.count, subSize)
]
return ir.Constant.literal_array(array)
elif isinstance(typ, ir.LiteralStructType) or isinstance(typ, ir.IdentifiedStructType):
td = llvm.create_target_data("e")
structEles = []
for el in typ.elements:
structEle = lift_from_address(module, ea, el)
structEles.append(structEle)
subSize = el.get_abi_size(td)
ea += subSize
return ir.Constant(typ, structEles)
else:
raise NotImplementedError(f"object at {hex(ea)} is of unsupported type {typ}")
def str2size(str_size: str):
"""
Converts a string representing memory size into its size in bits.
:param str_size: string describing size
:type str_size: str
:return: size of string, in bits
:rtype: int
"""
if str_size == "byte":
return 8
elif str_size == "word":
return 16
elif str_size == "dword":
return 32
elif str_size == "qword":
return 64
else:
raise AssertionError("string size must be one of byte/word/dword/qword")
def lift_intrinsic_function(module: ir.Module, func_name: str):
"""
Lifts IDA macros to corresponding LLVM intrinsics.
Hexray's decompiler recognises higher-level functions at the Microcode level.
Such ida_hexrays:mop_t objects are typed as ida_hexrays.mop_h (auxillary function member)
This improves decompiler output, representing operations that cannot be mapped to nice C code
(https://hex-rays.com/blog/igors-tip-of-the-week-67-decompiler-helpers/).
For relevant #define macros, refer to IDA SDK: `defs.h` and `pro.h`.
LLVM intrinsics have well known names and semantics and are required to follow certain restrictions.
:param module: _description_
:type module: ir.Module
:param func_name: _description_
:type func_name: str
:raises NotImplementedError: _description_
:return: _description_
:rtype: _type_
"""
# retrieve intrinsic function if it already exists
with suppress(KeyError):
return module.get_global(func_name)
if func_name == "sadd_overflow":
typ = ir.LiteralStructType((ir.IntType(64), ir.IntType(1)))
return module.declare_intrinsic('sadd_overflow', fnty=ir.FunctionType(typ.as_pointer(), [ir.IntType(64), ir.IntType(64)]))
elif func_name == "__OFSUB__":
return module.declare_intrinsic('__OFSUB__', fnty=ir.FunctionType(ir.IntType(1), [ir.IntType(64), ir.IntType(64)]))
elif func_name == "_mm_cvtsi128_si32":
return module.declare_intrinsic('_mm_cvtsi128_si32', fnty=ir.FunctionType(ir.IntType(32), [ir.IntType(128)]))
elif func_name == "_BitScanReverse":
return module.declare_intrinsic('_BitScanReverse', fnty=ir.FunctionType(i8ptr, [ir.IntType(32), ir.IntType(32)]))
elif func_name == "__FYL2X__":
return module.declare_intrinsic('__FYL2X__', fnty=ir.FunctionType(ir.DoubleType(), [ir.DoubleType(), ir.DoubleType()]))
elif func_name == "__FYL2P__":
return module.declare_intrinsic('__FYL2P__', fnty=ir.FunctionType(ir.DoubleType(), [ir.DoubleType(), ir.DoubleType()]))
elif func_name == "fabs":
return module.declare_intrinsic('fabs', fnty=ir.FunctionType(ir.DoubleType(), [ir.DoubleType()]))
elif func_name == "fabsf":
return module.declare_intrinsic('fabsf', fnty=ir.FunctionType(ir.FloatType(), [ir.FloatType()]))
elif func_name == "fabsl":
return module.declare_intrinsic('fabs', fnty=ir.FunctionType(ir.DoubleType(), [ir.DoubleType()]))
elif func_name == "memcpy":
return module.declare_intrinsic('memcpy', fnty=ir.FunctionType(i8ptr, [i8ptr, i8ptr, ir.IntType(64)]))
elif func_name == "_byteswap_ulong":
return module.declare_intrinsic('_byteswap_ulong', fnty=ir.FunctionType(ir.IntType(32), [ir.IntType(32)]))
elif func_name == "_byteswap_uint64":
return module.declare_intrinsic('_byteswap_uint64', fnty=ir.FunctionType(ir.IntType(64), [ir.IntType(64)]))
elif func_name == "memset":
return module.declare_intrinsic('memset', fnty=ir.FunctionType(i8ptr, [i8ptr, ir.IntType(32), ir.IntType(32)]))
elif func_name == "abs64":
return module.declare_intrinsic('abs64', fnty=ir.FunctionType(ir.IntType(64), [ir.IntType(64)]))
elif func_name == "__PAIR64__":
return module.declare_intrinsic('__PAIR64__', fnty=ir.FunctionType(ir.IntType(64), [ir.IntType(32), ir.IntType(32)]))
elif func_name == "__PAIR128__":
return module.declare_intrinsic('__PAIR128__', fnty=ir.FunctionType(ir.IntType(128), [ir.IntType(64), ir.IntType(64)]))
elif func_name == "__PAIR32__":
return module.declare_intrinsic('__PAIR32__', fnty=ir.FunctionType(ir.IntType(32), [ir.IntType(16), ir.IntType(16)]))
elif func_name == "__PAIR16__":
return module.declare_intrinsic('__PAIR16__', fnty=ir.FunctionType(ir.IntType(16), [ir.IntType(8), ir.IntType(8)]))
elif func_name == "_BitScanReverse64":
return module.declare_intrinsic('_BitScanReverse64', fnty=ir.FunctionType(i8ptr, [ir.IntType(64).as_pointer(), ir.IntType(64)]))
elif func_name == "_BitScanForward64":
return module.declare_intrinsic('_BitScanForward64', fnty=ir.FunctionType(i8ptr, [ir.IntType(64).as_pointer(), ir.IntType(64)]))
elif func_name == "__halt":
fty = ir.FunctionType(ir.VoidType(), [])
f = ir.Function(module, fty, "__halt")
f.append_basic_block()
builder = ir.IRBuilder(f.entry_basic_block)
builder.asm(fty, "hlt", "", (), True)
builder.ret_void()
return f
elif func_name == "is_mul_ok":
is_mul_ok = module.declare_intrinsic('is_mul_ok', fnty=ir.FunctionType(ir.IntType(8), [ir.IntType(64), ir.IntType(64)]))
return is_mul_ok
elif func_name == "va_start":
va_start = module.declare_intrinsic('va_start', fnty=ir.FunctionType(ir.VoidType(), [ir.IntType(8).as_pointer()]))
return va_start
elif func_name == "va_arg":
va_arg = module.declare_intrinsic('va_arg', fnty=ir.FunctionType(ir.IntType(64), [ir.IntType(8).as_pointer()]))
return va_arg
elif func_name == "va_end":
va_arg = module.declare_intrinsic('va_end', fnty=ir.FunctionType(ir.VoidType(), [ir.IntType(8).as_pointer()]))
return va_arg
elif func_name == "_QWORD":
fQWORD = module.declare_intrinsic('IDA_QWORD', fnty=ir.FunctionType(ir.IntType(8).as_pointer(), []))
return fQWORD
elif func_name == "__ROL8__":
f = module.declare_intrinsic('__ROL8__', fnty=ir.FunctionType(ir.IntType(64), [ir.IntType(64), ir.IntType(8)]))
return f
elif func_name == "__ROL4__":
f = module.declare_intrinsic('__ROL4__', fnty=ir.FunctionType(ir.IntType(64), [ir.IntType(64), ir.IntType(8)]))
return f
elif func_name == "__ROR4__":
f = module.declare_intrinsic('__ROR4__', fnty=ir.FunctionType(ir.IntType(64), [ir.IntType(64), ir.IntType(8)]))
return f
elif func_name == "__ROR8__":
f = module.declare_intrinsic('__ROR8__', fnty=ir.FunctionType(ir.IntType(64), [ir.IntType(64), ir.IntType(8)]))
return f
elif func_name.startswith("__readfs"):
_, size = func_name.split("__readfs")
size = str2size(size)
try:
fs_reg = module.get_global("virtual_fs")
except KeyError:
fs_reg_typ = ir.ArrayType(ir.IntType(8), 65536)
fs_reg = ir.GlobalVariable(module, fs_reg_typ, "virtual_fs")
fs_reg.storage_class = "thread_local"
fs_reg.initializer = fs_reg_typ(None)
try:
threadlocal_f = module.get_global('llvm.threadlocal.address')
except KeyError:
f_argty = (i8ptr, )
fnty = ir.FunctionType(i8ptr, f_argty)
threadlocal_f = module.declare_intrinsic('llvm.threadlocal.address', f_argty, fnty)
fty = ir.FunctionType(ir.IntType(size), [ir.IntType(32),])
f = ir.Function(module, fty, func_name)
offset, = f.args
f.append_basic_block()
builder = ir.IRBuilder(f.entry_basic_block)
fs_reg = typecast(fs_reg, ir.IntType(8).as_pointer(), builder)
threadlocal_address = builder.call(threadlocal_f, (fs_reg, ))
pointer = builder.gep(threadlocal_address, (offset,))
pointer = typecast(pointer, ir.IntType(size).as_pointer(), builder)
res = builder.load(pointer)
builder.ret(res)
return f
elif func_name.startswith("__writefs"):
_, size = func_name.split("__writefs")
size = str2size(size)
try:
fs_reg = module.get_global("virtual_fs")
except KeyError:
fs_reg_typ = ir.ArrayType(ir.IntType(8), 65536)
fs_reg = ir.GlobalVariable(module, fs_reg_typ, "virtual_fs")
fs_reg.storage_class = "thread_local"
fs_reg.initializer = fs_reg_typ(None)
try:
threadlocal_f = module.get_global('llvm.threadlocal.address')
except KeyError:
f_argty = (i8ptr, )
fnty = ir.FunctionType(i8ptr, f_argty)
threadlocal_f = module.declare_intrinsic('llvm.threadlocal.address', f_argty, fnty)
fty = ir.FunctionType(ir.VoidType(), [ir.IntType(32), ir.IntType(size)])
f = ir.Function(module, fty, func_name)
offset, value = f.args
f.append_basic_block()
builder = ir.IRBuilder(f.entry_basic_block)
fs_reg = typecast(fs_reg, ir.IntType(8).as_pointer(), builder)
threadlocal_address = builder.call(threadlocal_f, (fs_reg, ))
pointer = builder.gep(threadlocal_address, (offset,))
pointer = typecast(pointer, ir.IntType(size).as_pointer(), builder)
builder.store(value, pointer)
builder.ret_void()
return f
elif func_name.startswith("sys_"):
fty = ir.FunctionType(ir.IntType(64), [], var_arg=True)
f = ir.Function(module, fty, func_name)
return f
elif func_name.startswith("_InterlockedCompareExchange") or func_name.startswith("_InterlockedExchange"):
fty = ir.FunctionType(ir.IntType(64), [], var_arg=True)
f = ir.Function(module, fty, func_name)
return f
else:
raise NotImplementedError(f"NotImplementedError {func_name}")
def lift_function(module: ir.Module, func_name: str, is_declare: bool, ea = None, tif: ida_typeinf.tinfo_t = None):
"""
Declares function given its name.
If `is_declare` is False, also define the function by recursively.
If `tif` is given, enforce function type as given.
lifting its instructions in IDA decompiler output.
Heavylifting is done in `lift_from_address`.
:param module: parent module of function
:type module: ir.Module
:param func_name: name of function to lift
:type func_name: str
:param is_declare: is the function declare only?
:type is_declare: bool
:param tif: function type, defaults to None
:type tif: ida_typeinf.tinfo_t, optional
:return: lifted function
:rtype: ir.Function
"""
if func_name == "":
func_name = f"data_{hex(ea)[2:]}"
with suppress(NotImplementedError):
return lift_intrinsic_function(module, func_name)
with suppress(KeyError):
return module.get_global(func_name)
func_ea = ida_name.get_name_ea(ida_idaapi.BADADDR, func_name)
if ida_segment.segtype(func_ea) & ida_segment.SEG_XTRN:
is_declare = True
if func_ea == ida_idaapi.BADADDR:
func_ea = ea
assert func_ea != ida_idaapi.BADADDR
if tif is None:
tif = lift_type_from_address(func_ea)
typ = lift_tif(tif)
if isinstance(typ, ir.PointerType):
print()
res = ir.Function(module, typ, func_name)
if is_declare:
return res
return lift_from_address(module, func_ea, typ)
def calc_instsize(typ):
"""
This function calculate inst width
"""
if isinstance(typ, ir.PointerType):
return ptrsize
elif isinstance(typ, ir.ArrayType):
return -1
elif isinstance(typ, ir.IdentifiedStructType):
return -1
elif isinstance(typ, ir.FloatType):
return 32
elif isinstance(typ, ir.DoubleType):
return 64
else:
return typ.width
def lift_mop(mop: ida_hexrays.mop_t, blk: ir.Block, builder: ir.IRBuilder, dest = False, knowntyp = None) -> ir.Value:
"""
This function lift mop of microcode into llvm.
"""
builder.position_at_end(blk)
if mop.t == ida_hexrays.mop_r: # register value
return None
elif mop.t == ida_hexrays.mop_n: # immediate value
res = ir.Constant(ir.IntType(mop.size * 8), mop.nnn.value)
res.parent = blk
return res
elif mop.t == ida_hexrays.mop_d: # another instruction
d = lift_insn(mop.d, blk, builder)
if isinstance(d.type, ir.VoidType):
pass
elif mop.size == -1:
pass
elif isinstance(mop, ida_hexrays.mcallarg_t):
lltype = lift_tif(mop.type)
d = typecast(d, lltype, builder, signed=mop.type.is_signed())
elif knowntyp != None:
d = typecast(d, knowntyp, builder)
elif calc_instsize(d.type) != mop.size * 8:
d = typecast(d, ir.IntType(mop.size * 8), builder)
return d
elif mop.t == ida_hexrays.mop_l: # local variables
lvar = mop.l.var()
name = "funcresult" if lvar.is_result_var else lvar.name
off = mop.l.off
func = blk.parent
llvm_arg = func.lvars[name]
llvm_arg = get_offset_to(builder, llvm_arg, off)
if mop.size == -1:
pass
elif knowntyp != None:
llvm_arg = typecast(llvm_arg, knowntyp, builder)
elif calc_instsize(llvm_arg.type.pointee) != mop.size * 8:
llvm_arg = typecast(llvm_arg, ir.IntType(mop.size * 8).as_pointer(), builder)
return llvm_arg if dest else builder.load(llvm_arg)
elif mop.t == ida_hexrays.mop_S: # stack variables
name = "stack"
func = blk.parent
if name not in func.lvars:
with builder.goto_entry_block():
func.lvars[name] = builder.alloca(ir.IntType(ptrsize), name = name)
llvm_arg = func.lvars[name]
llvm_arg = get_offset_to(builder, llvm_arg, mop.s.off)
if mop.size == -1:
pass
elif knowntyp != None:
d = typecast(d, knowntyp, builder)
elif calc_instsize(llvm_arg.type.pointee) != mop.size * 8:
llvm_arg = typecast(llvm_arg, ir.IntType(mop.size * 8).as_pointer(), builder)
return llvm_arg if dest else builder.load(llvm_arg)
if (hasattr(llvm_arg.type.pointee, "width") and llvm_arg.type.pointee.width != mop.size * 8) and mop.size != -1:
llvm_arg = typecast(llvm_arg, ir.IntType(mop.size * 8).as_pointer(), builder)
return llvm_arg if dest else builder.load(llvm_arg)
elif mop.t == ida_hexrays.mop_b: # block number (used in jmp\call instruction)
return blk.parent.blocks[mop.b]
elif mop.t == ida_hexrays.mop_v: # global variable
ea = mop.g
name = ida_name.get_name(ea)
if name == "":
name = f"data_{hex(ea)[2:]}"
tif = lift_type_from_address(ea)
if tif.is_func() or tif.is_funcptr():
with suppress(KeyError):
g = blk.parent.parent.get_global(name)
return g
if tif.is_funcptr():
tif = tif.get_ptrarr_object()
# if function is a thunk function, define the actual function instead
if ((ida_funcs.get_func(ea) is not None)
and (ida_funcs.get_func(ea).flags & ida_funcs.FUNC_THUNK)):
tfunc_ea, ptr = ida_funcs.calc_thunk_func_target(ida_funcs.get_func(ea))
if tfunc_ea != ida_idaapi.BADADDR:
ea = tfunc_ea
name = ida_name.get_name(ea)
if name == "":
name = f"data_{hex(ea)[2:]}"
tif = lift_type_from_address(ea)
# if no function definition,
if ((ida_funcs.get_func(ea) is None)
# or if the function is a library function,
or (ida_funcs.get_func(ea).flags & ida_funcs.FUNC_LIB)
# or if the function is declared in a XTRN segment,
or ida_segment.segtype(ea) & ida_segment.SEG_XTRN):
# return function declaration
g = lift_function(blk.parent.parent, name, True, ea, tif)
else:
g = lift_function(blk.parent.parent, name, False, ea, tif)
return g
else:
if name in blk.parent.parent.globals:
g = blk.parent.parent.get_global(name)
else:
tif = lift_type_from_address(ea)
typ = lift_tif(tif)
g_cmt = lift_from_address(blk.parent.parent, ea, typ)
g = ir.GlobalVariable(blk.parent.parent, g_cmt.type, name = name)
g.initializer = g_cmt
if isinstance(g.type.pointee, ir.IdentifiedStructType) or isinstance(g.type.pointee, ir.ArrayType):
g = builder.gep(g, (ir.Constant(ir.IntType(32), 0), ir.Constant(ir.IntType(32), 0)))
if mop.size == -1:
pass
elif knowntyp != None:
g = typecast(g, knowntyp, builder)
elif calc_instsize(g.type.pointee) != mop.size * 8:
g = typecast(g, ir.IntType(mop.size * 8).as_pointer(), builder)
return g if dest else builder.load(g)
elif mop.t == ida_hexrays.mop_f: # function call information
mcallinfo = mop.f
f_args = []
f_ret = []
for i in range(mcallinfo.retregs.size()):
mopt = mcallinfo.retregs.at(i)
f_ret.append(lift_mop(mopt, blk, builder, dest))
for arg in mcallinfo.args:
typ = lift_tif(arg.type)
f_arg = lift_mop(arg, blk, builder, dest, typ.as_pointer())
if arg.t == ida_hexrays.mop_h and f_arg == None:
f_arg = blk.parent.parent.declare_intrinsic(arg.helper, fnty=ir.FunctionType(typ, []))
if arg.t == ida_hexrays.mop_r and f_arg == None:
name = "fs"
func = blk.parent
if name not in func.lvars:
with builder.goto_entry_block():
func.lvars[name] = builder.alloca(ir.IntType(16), name = name)
llvm_arg = func.lvars[name]
f_arg = llvm_arg if mop.size == -1 else builder.load(llvm_arg)
f_arg = typecast(f_arg, typ, builder)
f_args.append(f_arg)
return f_ret, f_args
elif mop.t == ida_hexrays.mop_a: # operating number address (mop_l\mop_v\mop_S\mop_r)
mop_addr = mop.a
val = lift_mop(mop_addr, blk, builder, True)
if isinstance(mop, ida_hexrays.mcallarg_t):
lltype = lift_tif(mop.type)
val = typecast(val, lltype, builder)
elif isinstance(mop, ida_hexrays.mop_addr_t):
lltype = lift_tif(mop.type)
val = typecast(val, lltype, builder)
elif knowntyp != None:
val = typecast(val, knowntyp, builder)
return val
elif mop.t == ida_hexrays.mop_h: # auxiliary function number
with suppress(NotImplementedError):
return lift_intrinsic_function(blk.parent.parent, mop.helper)
return None
elif mop.t == ida_hexrays.mop_str: # string constant
str_csnt = mop.cstr
strType = ir.ArrayType(ir.IntType(8), len(str_csnt))
g = ir.GlobalVariable(blk.parent.parent, strType, name=f"cstr_{len(blk.parent.parent.globals)}")
g.initializer = ir.Constant(strType, bytearray(str_csnt.encode("utf-8")))
g.linkage = "private"
g.global_constant = True
return typecast(g, ir.IntType(8).as_pointer(), builder)
elif mop.t == ida_hexrays.mop_c: # switch case and target
mcases = {}
for i in range(mop.c.size()):
dst = mop.c.targets[i]
if mop.c.values[i].size() == 0:
mcases["default"] = dst
for j in range(mop.c.values[i].size()):
src = mop.c.values[i][j]
mcases[src] = dst
return mcases
elif mop.t == ida_hexrays.mop_fn:
# IDA get float value may be crash in some cases
try:
fp = mop.fpc.fnum.float
except:
fp = 1.0
if mop.size == 4:
typ = ir.FloatType()
elif mop.size == 8:
typ = ir.DoubleType()
else:
typ = ir.DoubleType()
return ir.Constant(typ, fp)
elif mop.t == ida_hexrays.mop_p:
f = lift_intrinsic_function(blk.parent.parent, f"__PAIR{mop.size*8}__")
l = lift_mop(mop.pair.hop, blk, builder, dest)
r = lift_mop(mop.pair.lop, blk, builder, dest)
l = typecast(l, ir.IntType(mop.size*4), builder)
r = typecast(r, ir.IntType(mop.size*4), builder)
return builder.call(f, (l, r))
elif mop.t == ida_hexrays.mop_sc:
pass
elif mop.t == ida_hexrays.mop_z:
return None
mop_descs = {ida_hexrays.mop_r: "register value",
ida_hexrays.mop_n: "immediate value",
ida_hexrays.mop_d: "another instruction",
ida_hexrays.mop_l: "local variables",
ida_hexrays.mop_S: "stack variables",
ida_hexrays.mop_b: "block number (used in jmp\call instruction)",
ida_hexrays.mop_v: "global variable",
ida_hexrays.mop_f: "function call information",
ida_hexrays.mop_a: "operating number address (mop_l\mop_v\mop_S\mop_r)",
ida_hexrays.mop_h: "auxiliary function number",
ida_hexrays.mop_str: "string constant",
ida_hexrays.mop_c: "switch case and target",
ida_hexrays.mop_fn: "floating points constant",
ida_hexrays.mop_p: "the number of operations is correct",
ida_hexrays.mop_sc: "decentralized operation information"
}
raise NotImplementedError(f"not implemented: {mop.dstr()} of type {mop_descs[mop.t]}")
def _store_as(l: ir.Value, d: ir.Value, blk: ir.Block, builder: ir.IRBuilder, d_typ: ir.Type = None, signed: bool = True):
"""
Private helper function to store value to destination.
"""
if d is None: # destination does not exist
return l
d = dedereference(d)
if d_typ:
d = typecast(d, d_typ, builder, signed)
assert isinstance(d.type, ir.PointerType)
if isinstance(d.type.pointee, ir.ArrayType):
arrtoptr = d.type.pointee.element.as_pointer()
d = typecast(d, arrtoptr.as_pointer(), builder, signed)
if isinstance(l.type, ir.VoidType):
return
with suppress(AttributeError):