-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathfunctioninliner.py
2734 lines (2041 loc) · 87.3 KB
/
functioninliner.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 collections
import contextlib
import functools
import itertools
import logging
import pickle
import re
import struct
import time
import types
import ida_auto
import ida_bytes
import ida_funcs
import ida_frame
import ida_idaapi
import ida_idp
import ida_kernwin
import ida_segment
import ida_ua
import ida_xref
import idc
import keypatch
import netnode
import parse
import sark
import tqdm
import wrapt
# DEFINITIONS
INLINED_FUNCTION_PREFIX = "inlined_"
CLONE_NAME_FMT = "inlined_0x{func_ea:x}_for_0x{src_ea:x}"
TRACE = False
# LOGGING
class LoggerWithTrace(logging.getLoggerClass()):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if TRACE:
# add TRACE level
logging.TRACE = 5
logging.addLevelName(logging.TRACE, "TRACE")
def trace(self, msg, *args, **kwargs):
if TRACE:
self.log(logging.TRACE, msg, *args, **kwargs)
logger = LoggerWithTrace("FunctionInliner")
# EXCEPTIONS
class FunctionInlinerException(Exception):
pass
class FunctionInlinerUnsupportedException(FunctionInlinerException):
pass
class FunctionInlinerUnknownFlowException(FunctionInlinerException):
pass
# HELPERS
@contextlib.contextmanager
def autoanalysis(enabled):
ida_auto.enable_auto(enabled)
try:
yield None
finally:
ida_auto.enable_auto(not enabled)
def with_autoanalysis(enabled):
@wrapt.decorator
def decorator(wrapped, instance, args, kwargs):
with autoanalysis(enabled):
return wrapped(*args, **kwargs)
return decorator
@contextlib.contextmanager
def wait_box(msg, hide_cancel=False):
prefix = "HIDECANCEL\n" if hide_cancel else ""
ida_kernwin.show_wait_box(prefix + msg)
try:
yield None
finally:
ida_kernwin.hide_wait_box()
def get_function_under_cursor():
line = sark.Line()
# abort on unmapped addresses
if not ida_bytes.is_mapped(line.ea):
return None
# if we're on a call -> return its target
for xref in line.xrefs_from:
if xref.type.is_jump or xref.type.is_call:
try:
f = sark.Function(xref.to)
if xref.to == f.ea:
return f
except sark.exceptions.SarkNoFunction:
return None
# if we're on the start of a function -> return it
try:
func = sark.Function()
if func.start_ea == line.ea:
return func
except sark.exceptions.SarkNoFunction:
return None
return None
def align_downwards(ea, alignment):
return ea & ~(alignment - 1)
def align_upwards(ea, alignment):
return align_downwards(ea + (alignment - 1), alignment)
def reanalyze_line(line):
ida_auto.plan_range(line.ea, line.end_ea)
def reanalyze_program():
""" we used to not reanalyze the entire program, but for some reason when we surgically marked
for reanalysis only the stuff that we've changed, sometimes the auto analysis didn't recursively
go through to everything """
ida_auto.plan_range(0, ida_idaapi.BADADDR)
def is_conditional_insn(insn):
# is having a condition suffix
return insn._insn.segpref != 0xe # see module/arm/arm.hpp in the IDA SDK
def is_chunked_function(func):
return len(list(function_chunk_eas(func))) > 1
def function_chunk_eas(func):
ea = idc.first_func_chunk(func.ea)
while ea != ida_idaapi.BADADDR:
yield ea
ea = idc.next_func_chunk(func.ea, ea)
def function_chunk_lines(ea):
start_ea = idc.get_fchunk_attr(ea, idc.FUNCATTR_START)
end_ea = idc.get_fchunk_attr(ea, idc.FUNCATTR_END)
ea = start_ea
l = sark.Line(start_ea)
while l.ea < end_ea:
yield l
l = l.next
def function_chunk_crefs(ea, ret_ea=None):
start_ea = idc.get_fchunk_attr(ea, idc.FUNCATTR_START)
end_ea = idc.get_fchunk_attr(ea, idc.FUNCATTR_END)
for l in function_chunk_lines(ea):
try:
if l.insn.mnem == "RET" and ret_ea is not None:
external_cref_eas = (ret_ea,)
else:
external_cref_eas = (c for c in l.crefs_from if c < start_ea or c >= end_ea)
for target_ea in external_cref_eas:
yield (l.ea - start_ea, target_ea)
except sark.exceptions.SarkNoInstruction:
if not list(l.crefs_to):
pass # some times there's non-code inside function chunks, e.g. jumptables
else:
raise # but if there's a flow cref into it, this is bad
def function_chunk_parent_eas(ea):
fchunk = ida_funcs.get_fchunk(ea)
fpi = ida_funcs.func_parent_iterator_t(fchunk)
if not fpi.first():
return
while True:
yield fpi.parent()
if not fpi.next():
break
def containing_funcs(line):
funcs = set()
for parent_ea in function_chunk_parent_eas(line.ea):
try:
funcs.add(sark.Function(parent_ea))
except sark.exceptions.SarkNoFunction:
pass
try:
funcs.add(sark.Function(line.ea))
except sark.exceptions.SarkNoFunction:
pass
return funcs
def unreachable_function_chunks_eas(func):
# map all chunks in our function
remaining_chunks = set()
for start_ea in function_chunk_eas(func):
end_ea = idc.get_fchunk_attr(start_ea, idc.FUNCATTR_END)
remaining_chunks.add((start_ea, end_ea))
if len(remaining_chunks) == 1:
return
# discard reachable chunks
def discard_reachable_chunks(chunk):
remaining_chunks.discard(chunk)
for src_off, target in function_chunk_crefs(chunk[0]):
for other_chunk in remaining_chunks:
start_ea, end_ea = other_chunk
if start_ea <= target < end_ea:
discard_reachable_chunks(other_chunk)
break
if not remaining_chunks:
break
main_chunk = (func.start_ea, func.end_ea)
assert main_chunk in remaining_chunks
discard_reachable_chunks(main_chunk)
yield from (c[0] for c in remaining_chunks)
def function_crefs(func, ret_ea=None):
chunk_eas = list(function_chunk_eas(func))
for chunk_ea in chunk_eas:
for off, target_ea in function_chunk_crefs(chunk_ea, ret_ea):
if ida_funcs.func_contains(func._func, target_ea):
continue
src_ea = chunk_ea + off
src = sark.Line(src_ea)
if src.insn.mnem == "BL" and target_ea == src.end_ea:
# we have a flow xref going from a BL which is the last instruction of a function
# chunk. this can be one of two cases:
# 1. IDA didn't recognize that the target function is a NORET function, hence there
# shouldn't be a flow-xref from the BL
# 2. after BL-ing, the source function implicitly tail-calls to the next instruction
# which should be another function
# because we cannot know which of the cases is the right one, and in case it's (1),
# the next line might be data, we'll let a heuristic decide
if is_data_heuristic(sark.Line(target_ea)):
continue
yield src_ea, target_ea
def has_function_flow_xref(line):
for xref in line.xrefs_to:
# we're only interested in flow xrefs
if not xref.type.is_flow:
continue
# sometimes there are useless NOPs before real code, so we discard xrefs from code
# which isn't in a function
try:
sark.Function(xref.frm)
except sark.exceptions.SarkNoFunction:
continue
return True
return False
def external_callers(line, functions_only=False, include_flow=False):
funcs = containing_funcs(line)
for xref in line.xrefs_to:
caller = sark.Line(xref.frm)
# skip non-code xrefs
if not xref.type.is_code:
continue
# skip flow xrefs
if not include_flow and xref.type.is_flow:
continue
# skip recursive calls
caller_funcs = containing_funcs(caller)
if funcs and caller_funcs == funcs:
continue
elif not caller_funcs and functions_only:
continue
yield caller
def linegroups(n):
iters = [sark.lines() for _ in range(n)]
for i, it in enumerate(iters):
for _ in range(i):
next(it)
return zip(*iters)
def register_parts(r):
w = r[0]
n = r[1:]
families = (
("W", "X"),
("B", "H", "S", "D", "Q")
)
for f in families:
if w in f:
return (ww + n for ww in f)
else:
raise FunctionInlinerException(f"encountered unknown register: {r}")
def add_comment(line, cmt, prepend=True):
if line.comments.regular is None:
line.comments.regular = cmt
elif prepend:
line.comments.regular = cmt + "\n" + line.comments.regular
else:
line.comments.regular = line.comments.regular + "\n" + cmt
def get_branch_target_ea(line):
crefs_from = set()
for xref in line.xrefs_from:
if not xref.iscode:
continue
if xref.type.is_flow:
continue
crefs_from.add(xref.to)
assert len(crefs_from) == 1
return crefs_from.pop()
def drefs_from_eas(line):
# IDA marks enum refs as drefs with top address byte set to 0xff, so we filter out
# drefs that are not actually mapped
return (ea for ea in line.drefs_from if ida_bytes.is_mapped(ea))
# NETNODE
class PickleNetnode(netnode.Netnode):
@staticmethod
def _encode(data):
return pickle.dumps(data)
@staticmethod
def _decode(data):
return pickle.loads(data)
class RenamesStorage(PickleNetnode):
NETNODE = "$ FunctionInliner.renames"
RenameInfo = collections.namedtuple("RenameInfo", ("orig_name", "new_name"))
def __init__(self):
super().__init__(self.NETNODE)
def __setitem__(self, func_ea, rename_info):
if not isinstance(rename_info, RenamesStorage.RenameInfo):
raise ValueError("value must be of type RenamesStorage.RenameInfo")
super().__setitem__(func_ea, tuple(rename_info))
def __getitem__(self, func_ea):
v = super().__getitem__(func_ea)
return RenamesStorage.RenameInfo(*v)
class SingletonUserDict(type(collections.UserDict)):
_instance = None
def __call__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(SingletonUserDict, cls).__call__(*args, **kwargs)
return cls._instance
class ClonesStorage(collections.UserDict, metaclass=SingletonUserDict):
NETNODE = "$ functioninliner.clones"
CloneInfo = collections.namedtuple("CloneInfo", ("clone_ea", "orig_bytes"))
class InlinedFunctionInfo(collections.UserDict):
def __init__(self, update_callback):
super().__init__()
self._update_callback = update_callback
def __setitem__(self, src_ea, clone):
if not isinstance(clone, ClonesStorage.CloneInfo):
raise ValueError("value must be of type ClonesStorage.CloneInfo")
self.data[src_ea] = clone
self._update_callback(self, src_ea)
def __delitem__(self, src_ea):
del self.data[src_ea]
self._update_callback(self, src_ea)
def __init__(self):
super().__init__()
self.netnode = PickleNetnode(self.NETNODE)
self.update_from_storage()
def update_from_storage(self):
self.data.clear()
for k, v in self.netnode.items():
parts = ClonesStorage.parse_storage_key(k)
if not parts:
continue
func_ea = parts["func_ea"]
src_ea = parts["src_ea"]
func_storage = self[func_ea]
clone_info = ClonesStorage.CloneInfo(*v)
func_storage[src_ea] = clone_info
@staticmethod
def storage_key(func_ea, src_ea):
return CLONE_NAME_FMT.format(func_ea=func_ea, src_ea=src_ea)
@staticmethod
def parse_storage_key(k):
return parse.parse(CLONE_NAME_FMT, k)
def write_to_storage(self, func_ea, func_storage, src_ea):
key = ClonesStorage.storage_key(func_ea, src_ea)
clone_info = func_storage.get(src_ea, None)
if clone_info is None: # delete
del self.netnode[key]
# if there are no more outlined
if not func_storage and func_ea in self.data:
del self.data[func_ea]
else: # set
self.netnode[key] = tuple(clone_info)
self.data[func_ea] = func_storage
def __getitem__(self, func_ea):
if func_ea in self.data:
return self.data[func_ea]
else:
update_callback = functools.partial(self.write_to_storage, func_ea)
func_storage = ClonesStorage.InlinedFunctionInfo(update_callback)
return func_storage
def __setitem__(self, k, v):
raise RuntimeError("Do not try setting a value directly, but rather get its value as with "
"a defaultdict")
def __delitem__(self, func_ea):
for src_ea, _ in self[func_ea].items():
key = ClonesStorage.storage_key(func_ea, src_ea)
del self.netnode[key]
if func_ea in self.data:
del self.data[func_ea]
# FUNCTION INLINING
def get_cloned_function(ea):
seg = sark.Segment(ea)
if not seg.name:
return None
parts = parse.parse(CLONE_NAME_FMT, seg.name)
if not parts:
return None
return sark.Function(parts["func_ea"])
def is_originally_chunked_function(func):
for chunk_ea in function_chunk_eas(func):
# dismiss the "main" chunk
if chunk_ea == func.ea:
continue
# dismiss chunks which are inlined clones of outlined functions
if get_cloned_function(chunk_ea):
continue
# we found a "real" chunk
return True
return False
def create_code_segment(name, size, close_to=None, page_align=False):
if page_align:
alignment = 0x1000
else:
alignment = 0x4
size = align_upwards(size, alignment)
segs = list(sorted(sark.segments(), key=lambda s: s.ea))
# delete a previously cloned segment if such exists
for s in segs:
if s.name == name:
ida_segment.del_segm(s.start_ea, ida_segment.SEGMOD_KILL)
# map the holes between existing segments
holes = []
holes.append((0, segs[0].start_ea))
for s, next_s in zip(segs, segs[1:]):
holes.append((s.end_ea, next_s.start_ea))
holes.append((segs[-1].end_ea, ida_idaapi.BADADDR))
# align the start and end of each hole
holes = [(align_upwards(h[0], alignment), align_downwards(h[1], alignment)) for h in holes]
# filter-out holes which are too small
holes = [h for h in holes if h[1] - h[0] >= size]
# find the hole nearest to our caller
if close_to is None:
hole = holes[-1]
else:
def hole_dist(h):
start, end = h
if start > close_to:
return start - close_to
else:
return close_to - end - size
hole = min(holes, key=hole_dist)
# create the segment
if hole[0] > close_to:
start_ea = hole[0]
end_ea = hole[0] + size
else:
start_ea = hole[1] - size
end_ea = hole[1]
seg_t = ida_segment.segment_t()
seg_t.start_ea = start_ea
seg_t.end_ea = end_ea
seg_t.align = ida_segment.saRelDble
seg_t.comb = ida_segment.scPub
seg_t.perm = ida_segment.SEGPERM_EXEC | ida_segment.SEGPERM_READ
seg_t.bitness = 2 # 64 bits
seg_t.sel = ida_segment.setup_selector(0)
seg_t.type = ida_segment.SEG_CODE
seg_t.color = idc.DEFCOLOR
flags = ida_segment.ADDSEG_NOSREG | ida_segment.ADDSEG_QUIET | ida_segment.ADDSEG_NOAA
ida_segment.add_segm_ex(seg_t, name, "CODE", flags)
return sark.Segment(start_ea)
def validate_branch_displacements(func, src_ea, clone_ea, ret_ea):
# we only go over the first function chunk since that's the one we're cloning
max_b_displ = 0x8000000
def b_displ(src, target):
return abs(target - (src + 4))
# this isn't the most accurate condition since the clone offsets may move because of
# our translation, but we discard that. if anything, the assembly later will fail
clone_cref_displs = (b_displ(clone_ea + src_off, target_ea) for src_off, target_ea in
function_chunk_crefs(func.ea, ret_ea))
if b_displ(src_ea, clone_ea) >= max_b_displ or \
any(displ >= max_b_displ for displ in clone_cref_displs):
# TBH we were greedy when choosing when to create our segment, but we don't expect
# this to fail with +-128MB of max displacement, so we didn't bother implementing
# a better algorithm
raise FunctionInlinerException("created clone segment is not close enough to its "
"caller or one of its call targets")
def fix_outlined_function_call(src, clone_ea, clone_end_ea, func_ea, kp_asm=None):
if kp_asm is None:
kp_asm = keypatch.Keypatch_Asm()
# unfortunately, we've seen cases where IDA creates a function out of our clone instead of a
# function chunk, and this also happens sometimes when calling auto_apply_tail.
# therefore, we first ida_funcs.append_func_tail and only then patch and plan to reanalyze the
# caller
ida_funcs.append_func_tail(ida_funcs.get_func(src.ea), clone_ea, clone_end_ea)
# replace the source instruction with a B to our clone
mnem = src.insn.mnem
if mnem == "BL":
asm = f"B #{clone_ea:#x}" # we drop PAC flags
code = bytes(kp_asm.assemble(asm, src.ea)[0])
assert len(code) == src.size
ida_bytes.patch_bytes(src.ea, code)
else: # is_jump
fix_cloned_branch(kp_asm, src.ea, func_ea, clone_ea)
reanalyze_line(src)
# delete the original xref
ida_xref.del_cref(src.ea, func_ea, 0)
# wait for analysis of the source instruction and the clone
assert ida_auto.auto_wait_range(src.ea, src.end_ea) >= 0
assert ida_auto.auto_wait_range(clone_ea, clone_end_ea) >= 0
# recalculate SP delta for the instructions in the clone. we do it for every instruction in
# case the clone contains more than one basic block
pfn = ida_funcs.get_func(src.ea)
ea = clone_ea
while ea < clone_end_ea:
ida_frame.recalc_spd_for_basic_block(pfn, ea)
ea += ida_bytes.get_item_size(ea)
def inline_function_call(src, func, kp_asm=None):
storage = ClonesStorage()
func_storage = storage[func.ea]
if kp_asm is None:
kp_asm = keypatch.Keypatch_Asm()
# verify that the function isn't chunked
if is_chunked_function(func):
raise FunctionInlinerUnsupportedException("chunked functions are currently unsupported")
# clone and inline the function for each of its callers
size = func.end_ea - func.start_ea
# create a segment for the cloned function
seg_size = size * 2 # we put a factor of 2 here for our ADR->ADRP+ADD fixups
seg_name = CLONE_NAME_FMT.format(func_ea=func.ea, src_ea=src.ea)
seg = create_code_segment(seg_name, seg_size, src.ea)
clone_ea = seg.ea
try:
# analyze the caller
if src.insn.mnem == "B" and not is_conditional_insn(src.insn): # tail-call
ret_ea = None
elif src.insn.mnem in ("B", "BL", "CBNZ", "CBZ", "TBNZ", "TBZ"):
ret_ea = src.end_ea
else:
raise FunctionInlinerException(f"unexpected call opcode: {src.insn.mnem}")
# validate that the created segment is close enough for the required branches
validate_branch_displacements(func, src.ea, clone_ea, ret_ea)
# clone the function
logger.debug(f"cloning to {clone_ea:#x}")
clone_end_ea = clone_function(func, clone_ea, ret_ea, kp_asm)
# replace the source opcode with a branch to our clone
orig_bytes = src.bytes
fix_outlined_function_call(src, clone_ea, clone_end_ea, func.ea, kp_asm)
# add clone info to storage
clone_info = ClonesStorage.CloneInfo(clone_ea, orig_bytes)
func_storage[src.ea] = clone_info
except: # noqa: E722
# remove from storage if it's already been added
func_storage.pop(clone_ea, None)
# undo the source patch if it's already been done
ida_bytes.patch_bytes(src.ea, src.bytes)
reanalyze_line(src)
# remove the created segment
ida_segment.del_segm(clone_ea, ida_segment.SEGMOD_KILL)
logger.error(f"unhandled exception was raised while inlining call to {func.name} from {src.ea:#x}")
raise
return clone_ea
def function_chunk_inlined_functions(ea):
start_ea = idc.get_fchunk_attr(ea, idc.FUNCATTR_START)
for off, target_ea in function_chunk_crefs(ea):
func = get_cloned_function(target_ea)
if func:
src = sark.Line(start_ea + off)
yield (src, func)
def rename_outlined_function(func):
storage = RenamesStorage()
rename_info = storage.get(func.ea)
if rename_info and func.name == rename_info.new_name:
return
new_name = f"outlined_{func.name}"
rename_info = RenamesStorage.RenameInfo(func.name, new_name)
func.name = new_name
storage[func.ea] = rename_info
def undo_rename_outlined_function(func):
storage = RenamesStorage()
rename_info = storage.get(func.ea)
if not rename_info:
return
if func.name == rename_info.new_name:
func.name = rename_info.orig_name
del storage[func.ea]
def inline_function(func, kp_asm=None):
# verify that the function doesn't have any chunks which aren't inlined clones of outlined
# functions
if is_originally_chunked_function(func):
raise FunctionInlinerUnsupportedException("chunked functions are currently unsupported")
# find functions that we've inlined into this function
inlined_function_calls = list(function_chunk_inlined_functions(func.ea))
# temporarily undo inlining into our function
for src, inlined_func in inlined_function_calls:
logger.debug(f"temporarily undoing inlining of {inlined_func.name} into {src.ea:#x}")
undo_inline_function_call(src, inlined_func)
# wait for analysis of our function
assert ida_auto.auto_wait_range(func.ea, func.end_ea) >= 0
# assert that the function is now unchunked
assert not is_chunked_function(func)
func_has_outgoing_crefs = bool(list(function_chunk_crefs(func.ea)))
# inline our function into its callers
for src in external_callers(func):
logger.debug(f"inlining call to {func.name} from {src.ea:#x}")
clone_ea = inline_function_call(src, func, kp_asm)
# wait for analysis of our clone (optimization: only if needed)
# this is both for the case we need to redo inlining into it in a bit, and also for the case
# we're inlining all outlined functions in the IDB and we want the clones' outgoing crefs to
# be indexed as well
if func_has_outgoing_crefs:
seg = sark.Segment(clone_ea)
assert ida_auto.auto_wait_range(seg.start_ea, seg.end_ea) >= 0
# redo inlining into our function clones
for _, inlined_func in inlined_function_calls:
logger.debug(f"redoing inlining of {inlined_func.name} into the cloned functions")
inline_function(inlined_func)
# if there are no more xrefs to this function, rename it
if not list(external_callers(func)):
rename_outlined_function(func)
@with_autoanalysis(False)
def inline_all_functions(extra=False):
logger.info("inlining all outlined functions...")
failed_analysis = 0
inlined = 0
skipped = 0
erroronous = 0
kp_asm = keypatch.Keypatch_Asm()
all_funcs = list(sark.functions())
with wait_box("finding outlined functions..."):
outlined_funcs = []
for func in tqdm.tqdm(all_funcs, desc="analyzing", ncols=80, unit="func"):
ida_auto.show_auto(func.ea)
if ida_kernwin.user_cancelled():
return False
logger.debug(f"analyzing {func.name}")
try:
if is_function_outlined(func, extra=extra):
outlined_funcs.append(func)
except Exception:
logger.exception(f"unhandled exception raised when trying to analyze {func.name}:")
failed_analysis += 1
logger.info(f"found {len(outlined_funcs)} outlined functions")
if failed_analysis:
logger.error(f"failed analysing {failed_analysis} functions")
retval = True
with wait_box("inlining all outlined functions... (this may take a few minutes)"):
start_time = time.time()
for func in tqdm.tqdm(outlined_funcs, desc="inlining", ncols=80, unit="func"):
ida_auto.show_auto(func.ea)
if ida_kernwin.user_cancelled():
retval = False
break
logger.debug(f"inlining {func.name}")
try:
inline_function(func, kp_asm)
inlined += 1
except FunctionInlinerUnsupportedException:
skipped += 1 # skip functions that we can't inline
except Exception:
logger.exception(f"unhandled exception raised when trying to inline {func.name}:")
erroronous += 1
elapsed_time = int(time.time() - start_time)
logger.info(f"inlined a total of {inlined} functions in {elapsed_time} seconds")
if skipped:
logger.warning(f"skipped {skipped} unsupported functions")
if erroronous:
logger.error(f"failed inlining {erroronous} functions")
return retval
def clone_insn_ret(kp_asm, line, dst_ea, ret_ea):
assert line.insn.mnem == "RET" and not is_conditional_insn(line.insn)
asm = f"B #{ret_ea:#x}" # we drop PAC flags
code = bytes(kp_asm.assemble(asm, dst_ea)[0])
logger.trace(f" translated to: {asm}")
return code
def clone_insn_branch(kp_asm, line, dst_ea, func, ret_ea):
mnem = line.insn.mnem
# resolve the the branch target
if mnem == "BR":
target_ea = None
else:
target_ea = get_branch_target_ea(line)
if target_ea and func.start_ea <= target_ea < func.end_ea: # local target -> copy as-is
logger.trace(" local target -> copied as-is")
return line.bytes, target_ea - func.ea
else: # external target -> fix it
if is_conditional_insn(line.insn):
raise FunctionInlinerUnsupportedException("translating conditioned tail-calls is "
"currently unsupported")
if mnem == "BR":
# target is the first arg even if it's an authenticated BR
target_reg = line.insn.operands[0].text
asm = f"BLR {target_reg}" # we drop PAC flags
else:
assert mnem in ("BL", "B")
asm = f"BL #{target_ea:#x}" # we drop PAC flags
if mnem in ("B", "BR"): # tail-call -> also add a following B back or RET
if ret_ea:
asm += f"\nB #{ret_ea:#x}"
else:
asm += "\nRET"
code = bytes(kp_asm.assemble(asm, dst_ea)[0])
logger.trace(f" translated to: {asm}")
return code, None
def clone_insn_mem(kp_asm, line, dst_ea):
drefs_from = set(drefs_from_eas(line))
insn = line.insn
if len(drefs_from) == 1:
target_ea = drefs_from.pop()
else: # this may happen with LDR when the target contains another address
assert len(drefs_from) == 2 and insn.mnem == "LDR"
xref = [x for x in line.xrefs_from if x.type.is_read][0]
target_ea = xref.to
target_page = target_ea & ~0xfff
target_offset = target_ea & 0xfff
if is_conditional_insn(line.insn):
raise FunctionInlinerUnsupportedException("translating conditional mem instructions is "
"currently unsupported")
# full_mnem should be the same as insn.mnem, but compare the full one just to be on the safe side
full_mnem = ida_ua.print_insn_mnem(line.ea)
if full_mnem in ("ADR", "ADRL"):
# usually ADR is followed by NOP, because the compiler doesn't know if it'll be ADR or
# ADRP + ADD (ADRL), but we don't want to rely on it so we'll translate both alternatives
# with two instructions
reg = line.insn.regs.pop()
asm = f"""
ADRP {reg}, #{target_page:#x}
ADD {reg}, {reg}, #{target_offset:#x}
"""
code = bytes(kp_asm.assemble(asm, dst_ea)[0])
logger.trace(f" {full_mnem} -> translated to: {asm}")
return code
elif full_mnem == "ADRP":
reg = line.insn.regs.pop()
asm = f"ADRP {reg}, #{target_page:#x}"
code = bytes(kp_asm.assemble(asm, dst_ea)[0])
logger.trace(f" ADRP -> translated to: {asm}")
return code
elif full_mnem == "MOV":
logger.trace(" MOV -> copied as-is")
return line.bytes
else:
# we expect the rest to be e.g. LDR/STR/ADD using an address or a PAGEOFF
# IDA won't always show "@PAGEOFF" in the disassembly, so we have to check for this case
# manually
found_displ = 0
for op in line.insn.operands:
if op.type.is_mem:
found_displ = -1
break
if op.type.is_displ:
found_displ += 1
pageoff_flow = found_displ == 1
if pageoff_flow:
# the PAGEOFF shouldn't change, so we can copy as-is
logger.trace(" PAGEOFF -> copied as-is")
return line.bytes
else: # direct memory access flow
# try finding and replacing the target operand with the fixed one
new_ops = []
ops_fixed = 0
for op in insn.operands:
if op.type.is_mem and op.addr == target_ea:
new_ops.append(f"#{target_ea:#x}")
ops_fixed += 1
else:
new_ops.append(op.text)
assert ops_fixed == 1
# recreate the instruction
asm = full_mnem + " " + ", ".join(new_ops)
code = bytes(kp_asm.assemble(asm, dst_ea)[0])
logger.trace(f" direct memory reference -> translated to: {asm}")
return code
def fix_cloned_branch(kp_asm, src_ea, current_target_ea, fixed_target_ea):
# analyze this single instruction
idc.set_flag(idc.INF_AF, idc.AF_CODE, 0)
ida_ua.create_insn(src_ea)