-
Notifications
You must be signed in to change notification settings - Fork 1
/
angr_vexir_diff.patch
1175 lines (1099 loc) · 52.9 KB
/
angr_vexir_diff.patch
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
diff --git a/angr/analyses/decompiler/block_simplifier.py b/angr/analyses/decompiler/block_simplifier.py
index 7a4c229af..1ec140a52 100644
--- a/angr/analyses/decompiler/block_simplifier.py
+++ b/angr/analyses/decompiler/block_simplifier.py
@@ -13,6 +13,7 @@ from ...errors import SimMemoryMissingError
from .. import Analysis, register_analysis
from .peephole_optimizations import STMT_OPTS, EXPR_OPTS, PeepholeOptimizationStmtBase, PeepholeOptimizationExprBase
from .ailblock_walker import AILBlockWalker
+from ... import muqi
if TYPE_CHECKING:
from angr.storage.memory_mixins.paged_memory.pages.multi_values import MultiValues
@@ -264,6 +265,13 @@ class BlockSimplifier(Analysis):
v = False
def _handle_expr(expr_idx: int, expr: Expression, stmt_idx: int, stmt: Statement, block) -> Optional[Expression]:
+
+ temp_rules = [ ]
+ try:
+ with open(muqi.decompiler_read_txt,'r') as muqi_file:
+ temp_rules = muqi_file.readlines()
+ except:
+ pass
old_expr = expr
@@ -271,6 +279,15 @@ class BlockSimplifier(Analysis):
while redo:
redo = False
for expr_opt in expr_opts:
+ #muqi block rules
+ muqi_set = False
+ for i in range(len(temp_rules)) :
+ if expr_opt.NAME in temp_rules[i]:
+ #print(expr_opt.NAME)
+ muqi_set = True
+ if muqi_set:
+ continue
+
if isinstance(expr, expr_opt.expr_classes):
r = expr_opt.optimize(expr)
if r is not None and r is not expr:
@@ -296,6 +313,13 @@ class BlockSimplifier(Analysis):
@staticmethod
def _peephole_optimize_stmts(block, stmt_opts):
+ temp_rules = [ ]
+ try:
+ with open(muqi.decompiler_read_txt,'r') as muqi_file:
+ temp_rules = muqi_file.readlines()
+ except:
+ pass
+
any_update = False
statements = [ ]
@@ -306,6 +330,15 @@ class BlockSimplifier(Analysis):
while redo:
redo = False
for opt in stmt_opts:
+ #muqi block rules
+ muqi_set = False
+ for i in range(len(temp_rules)) :
+ if opt.NAME in temp_rules[i]:
+ #print(opt.NAME)
+ muqi_set = True
+ if muqi_set:
+ continue
+
if isinstance(stmt, opt.stmt_classes):
r = opt.optimize(stmt)
if r is not None and r is not stmt:
diff --git a/angr/analyses/decompiler/decompilation_options.py b/angr/analyses/decompiler/decompilation_options.py
index b6ae4d6fc..57c3c0fe1 100644
--- a/angr/analyses/decompiler/decompilation_options.py
+++ b/angr/analyses/decompiler/decompilation_options.py
@@ -103,7 +103,20 @@ options = [
clears_cache=False,
),
]
-
+options_muqi = [(
+ O(
+ "Aggressively remove dead memdefs",
+ "Allow the decompiler to aggressively remove memory definitions (such as stack variables) that are deemed dead."
+ " Generally, enabling this option will generate cleaner pseudocode; However, due to limitations of static "
+ "analysis, angr may miss certain uses to a memory definition, which may cause the removal of a memory "
+ "definition that is actually in use, and consequently lead to incorrect decompilation output.",
+ bool,
+ "clinic",
+ "remove_dead_memdefs",
+ category="Data flows",
+ default_value=False,
+ ), False)
+]
# NOTE: if you add a codegen option here, please add it to reapply_options
options_by_category = defaultdict(list)
diff --git a/angr/analyses/decompiler/decompiler.py b/angr/analyses/decompiler/decompiler.py
index 315f7e306..9d5de234f 100644
--- a/angr/analyses/decompiler/decompiler.py
+++ b/angr/analyses/decompiler/decompiler.py
@@ -16,6 +16,8 @@ from .ailgraph_walker import AILGraphWalker
from .condition_processor import ConditionProcessor
from .decompilation_options import DecompilationOption
from .decompilation_cache import DecompilationCache
+from .decompilation_options import options_muqi
+from ... import muqi
if TYPE_CHECKING:
from .peephole_optimizations import PeepholeOptimizationStmtBase, PeepholeOptimizationExprBase
@@ -42,10 +44,16 @@ class Decompiler(Analysis):
ite_exprs=None,
decompile=True,
regen_clinic=True,
+ rules_txt=None
):
+ muqi.decompiler_read_txt = rules_txt
self.func = func
self._cfg = cfg
- self._options = options
+ if options is None:
+ self._options = options_muqi
+ else:
+ self._options = options
+
if optimization_passes is None:
self._optimization_passes = get_default_optimization_passes(self.project.arch, self.project.simos.name)
l.debug("Get %d optimization passes for the current binary.", len(self._optimization_passes))
@@ -293,8 +301,24 @@ class Decompiler(Analysis):
"""
d = { }
+ #muqi block rules
+ temp_rules = [ ]
+ try:
+ with open(muqi.decompiler_read_txt,'r') as muqi_file:
+ temp_rules = muqi_file.readlines()
+ except:
+ pass
+
for option, value in options:
d[option.param] = value
+ #muqi block rules
+ muqi_set = False
+ for i in range(len(temp_rules)) :
+ if option.NAME in temp_rules[i]:
+ muqi_set = True
+ if muqi_set:
+ d[option.param] = not value
+
return d
diff --git a/angr/analyses/decompiler/structured_codegen/c.py b/angr/analyses/decompiler/structured_codegen/c.py
index aaf653e0c..b5da592d1 100644
--- a/angr/analyses/decompiler/structured_codegen/c.py
+++ b/angr/analyses/decompiler/structured_codegen/c.py
@@ -17,6 +17,9 @@ from ..region_identifier import MultiNode
from ..structurer import (SequenceNode, CodeNode, ConditionNode, ConditionalBreakNode, LoopNode, BreakNode,
SwitchCaseNode, ContinueNode, CascadingConditionNode)
from .base import BaseStructuredCodeGenerator, InstructionMapping, PositionMapping, PositionMappingElement
+from .... import muqi
+retval_last_muqi = None
+muqi_dict_name_type ={}
if TYPE_CHECKING:
from angr.knowledge_plugins.variables.variable_manager import VariableManagerInternal
@@ -260,6 +263,8 @@ class CFunction(CConstruct): # pylint:disable=abstract-method
yield type_pre_spaces, None
yield name, cvariable
yield type_post, var_type
+ global muqi_dict_name_type
+ muqi_dict_name_type[name] = type_pre + type_post
else:
# multiple types...
for i, var_type in enumerate(set(typ for _, typ in cvar_and_vartypes)):
@@ -328,10 +333,84 @@ class CFunction(CConstruct): # pylint:disable=abstract-method
yield '\n', None
yield indent_str, None
+ #muqi block rules
+ temp_rules = [ ]
+ try:
+ with open(muqi.decompiler_read_txt,'r') as muqi_file:
+ temp_rules = muqi_file.readlines()
+ except:
+ pass
+
+ global muqi_dict_name_type
+ muqi_set = False
+ for i in range(len(temp_rules)) :
+ if "muqi add rule" in temp_rules[i]:
+ muqi_set = True
+ #print(temp_rules)
+ if muqi_set:
+ #added by muqi by determine return type
+ yield "\n/*\n", None
+ for i, (arg_type, arg) in enumerate(zip(self.functy.args, self.arg_list)):
+ if i:
+ yield ", ", None
+
+ if isinstance(arg, CVariable):
+ variable = arg.unified_variable if arg.unified_variable is not None else arg.variable
+ variable_name = variable.name
+ else:
+ variable_name = arg.c_repr()
+ raw_type_str: str = arg_type.c_repr(name=variable_name)
+ # FIXME: Add a .c_repr_chunks() to SimType so that we no longer need to parse the string output
+ assert variable_name in raw_type_str
+ varname_pos = raw_type_str.rfind(variable_name)
+ type_pre, type_post = raw_type_str[:varname_pos], raw_type_str[varname_pos + len(variable_name):]
+ if type_pre.endswith(" "):
+ type_pre_spaces = " " * (len(type_pre) - len(type_pre.rstrip(" ")))
+ type_pre = type_pre.rstrip(" ")
+ else:
+ type_pre_spaces = ""
+
+ yield type_pre, arg_type
+ if type_pre_spaces:
+ yield type_pre_spaces, None
+ yield variable_name, arg
+ yield type_post, arg_type
+ '''
+ print(type_pre)
+ print(arg_type)
+ print(type_post)
+ print(type(type_pre))
+ print(type(arg_type))
+ print(type(type_post))
+ print(variable_name)
+ print(arg)
+ print(type(variable_name))
+ print(type(arg))
+ #global muqi_dict_name_type
+ '''
+ muqi_dict_name_type[variable_name] = type_pre + type_post
+
+ yield from self.variable_list_repr_chunks(indent=indent + INDENT_DELTA)
+ if self.statements is not None:
+ yield from self.statements.c_repr_chunks(indent=indent + INDENT_DELTA)
+ yield "\n*/\n", None
+ if retval_last_muqi :
+ yield retval_last_muqi, None
+ yield " ", None
+ else:
+ # return type
+ yield self.functy.returnty.c_repr(name="").strip(" "), None
+ yield " ", None
+ else:
+ yield self.functy.returnty.c_repr(name="").strip(" "), None
+ yield " ", None
+ '''
+ #this is original return type
# return type
yield self.functy.returnty.c_repr(name="").strip(" "), None
yield " ", None
# function name
+ '''
if self.demangled_name:
normalized_name = get_cpp_function_name(self.demangled_name, specialized=False, qualified=False)
else:
@@ -958,7 +1037,26 @@ class CReturn(CStatement):
yield "return ", self
yield from self.retval.c_repr_chunks()
yield ";\n", self
-
+ '''
+ print(self.retval)
+ print(self.retval.type)
+ print(self.retval.variable)
+ print(self.retval.variable.name)
+ print(type(self.retval.variable.name))
+ print(muqi_dict_name_type)
+ '''
+ global retval_last_muqi
+ if (isinstance( self.retval,CTypeCast)):
+ try:
+ retval_last_muqi = self.retval.type
+ except:
+ pass
+ else:
+ try:
+ retval_last_muqi = muqi_dict_name_type[self.retval.variable.name]
+ except:
+ retval_last_muqi = self.retval.type
+ #print(retval_last_muqi)
class CGoto(CStatement):
diff --git a/angr/analyses/identifier/custom_callable.py b/angr/analyses/identifier/custom_callable.py
index 24ac2ed5d..1a1e72b27 100644
--- a/angr/analyses/identifier/custom_callable.py
+++ b/angr/analyses/identifier/custom_callable.py
@@ -67,7 +67,7 @@ class IdentifierCallable(object):
def get_base_state(self, *args):
prototype = self._cc.guess_prototype(args)
self._base_state.ip = self._addr
- state = self._project.factory.call_state(self._addr, *args,
+ state = self._project.factory.call_state("/tmp/angr_Unknown.txt",self._addr, *args,
prototype=prototype,
cc=self._cc,
base_state=self._base_state,
@@ -79,7 +79,7 @@ class IdentifierCallable(object):
if prototype is None:
prototype = self._cc.guess_prototype(args)
self._base_state.ip = self._addr
- state = self._project.factory.call_state(self._addr, *args,
+ state = self._project.factory.call_state("/tmp/angr_Unknown.txt",self._addr, *args,
cc=self._cc,
prototype=prototype,
base_state=self._base_state,
diff --git a/angr/callable.py b/angr/callable.py
index 8205944a8..9dd1e8338 100644
--- a/angr/callable.py
+++ b/angr/callable.py
@@ -62,7 +62,7 @@ class Callable(object):
def perform_call(self, *args, prototype=None):
prototype = SimCC.guess_prototype(args, prototype or self._func_ty).with_arch(self._project.arch)
- state = self._project.factory.call_state(self._addr, *args,
+ state = self._project.factory.call_state("/tmp/angr_Unknown.txt",self._addr, *args,
prototype=prototype,
cc=self._cc,
base_state=self._base_state,
diff --git a/angr/engines/engine.py b/angr/engines/engine.py
index 87ac525a9..c4ba08e68 100644
--- a/angr/engines/engine.py
+++ b/angr/engines/engine.py
@@ -5,6 +5,8 @@ import threading
from typing import Optional
import angr
+from .. import muqi
+
from archinfo.arch_soot import SootAddressDescriptor
l = logging.getLogger(name=__name__)
@@ -123,6 +125,14 @@ class SuccessorsMixin(SimEngine):
:param force_addr: Force execution to pretend that we're working at this concrete address
:returns: A SimSuccessors object categorizing the execution's successor states
"""
+ #e00038 is the out side address
+ with open(muqi.programe_function_name_txt,'a') as muqi_file:
+ #with open(state.log_filepath_muqi,'a') as muqi_file:
+ if self.successors is None :
+ old_address = 0xe00038
+ else:
+ old_address = self.successors.addr
+
inline = kwargs.pop('inline', False)
force_addr = kwargs.pop('force_addr', None)
@@ -150,10 +160,18 @@ class SuccessorsMixin(SimEngine):
new_state.scratch.executed_pages_set = {addr & ~0xFFF}
self.successors = SimSuccessors(addr, old_state)
-
+
new_state._inspect('engine_process', when=BP_BEFORE, sim_engine=self, sim_successors=self.successors,
address=addr)
self.successors = new_state._inspect_getattr('sim_successors', self.successors)
+
+ with open(muqi.programe_function_name_txt,'a') as muqi_file:
+ if self.successors is None :
+ print('successors transfer:[',hex(old_address),'->','e00038', ']', file=muqi_file)
+ else:
+ print('successors transfer:[',hex(old_address),'->', hex(self.successors.addr) ,']',file=muqi_file)
+ print('parent state is:[', self.state.history.parent,']',file=muqi_file)
+
try:
self.process_successors(self.successors, **kwargs)
except SimException:
diff --git a/angr/engines/successors.py b/angr/engines/successors.py
index b39681d8d..6859c852e 100644
--- a/angr/engines/successors.py
+++ b/angr/engines/successors.py
@@ -155,6 +155,7 @@ class SimSuccessors:
# apply the guard constraint and new program counter to the state
if add_guard:
+ print("add constraints of _preprocess_successor")
state.add_constraints(state.scratch.guard)
# trigger inspect breakpoints here since this statement technically shows up in the IRSB as the "next"
state.regs.ip = state.scratch.target
@@ -249,15 +250,19 @@ class SimSuccessors:
if o.VALIDATE_APPROXIMATIONS in state.options:
if state.satisfiable():
raise Exception('WTF')
+ print("unsat_successors.append(state) 1")
self.unsat_successors.append(state)
elif o.APPROXIMATE_SATISFIABILITY in state.options and not state.solver.satisfiable(exact=False):
if o.VALIDATE_APPROXIMATIONS in state.options:
if state.solver.satisfiable():
raise Exception('WTF')
+ print("unsat_successors.append(state) 2")
self.unsat_successors.append(state)
elif not state.scratch.guard.symbolic and state.solver.is_false(state.scratch.guard):
+ print("unsat_successors.append(state) 3")
self.unsat_successors.append(state)
elif o.LAZY_SOLVES not in state.options and not state.satisfiable():
+ print("unsat_successors.append(state) 4")
self.unsat_successors.append(state)
elif o.NO_SYMBOLIC_JUMP_RESOLUTION in state.options and state.solver.symbolic(target):
self.unconstrained_successors.append(state)
@@ -279,6 +284,7 @@ class SimSuccessors:
if concrete_syscall_nums is not None:
for i, n in enumerate(concrete_syscall_nums):
split_state = state if i == len(concrete_syscall_nums) - 1 else state.copy()
+ print("add constraint of split_state.add_constraints")
split_state.add_constraints(symbolic_syscall_num == n)
if split_state.supports_inspect:
split_state.inspect.downsize()
@@ -292,6 +298,7 @@ class SimSuccessors:
self._fix_syscall_ip(state)
self.flat_successors.append(state)
except (AngrUnsupportedSyscallError, AngrSyscallError):
+ print("unsat_successors.append(state) 5")
self.unsat_successors.append(state)
else:
@@ -338,6 +345,7 @@ class SimSuccessors:
if o.KEEP_IP_SYMBOLIC in split_state.options:
split_state.regs.ip = target
else:
+ print("add constraint of split_state.add_constraints")
split_state.add_constraints(cond, action=True)
split_state.regs.ip = a
if split_state.supports_inspect:
@@ -345,6 +353,7 @@ class SimSuccessors:
self.flat_successors.append(split_state)
self.successors.append(state)
except SimSolverModeError:
+ print("unsat_successors.append(state) 6")
self.unsat_successors.append(state)
return state
diff --git a/angr/engines/vex/heavy/heavy.py b/angr/engines/vex/heavy/heavy.py
index 52560f8ce..a79bfc80a 100644
--- a/angr/engines/vex/heavy/heavy.py
+++ b/angr/engines/vex/heavy/heavy.py
@@ -10,6 +10,7 @@ from ....utils.constants import DEFAULT_STATEMENT
from .... import sim_options as o
from .... import errors
from . import dirty
+from .... import muqi
l = logging.getLogger(__name__)
@@ -146,7 +147,44 @@ class HeavyVEXMixin(SuccessorsMixin, ClaripyDataMixin, SimStateStorageMixin, VEX
successors.artifacts['irsb_default_jumpkind'] = irsb.jumpkind
successors.artifacts['insn_addrs'] = []
-
+ final_statement = irsb.statements[-1]
+ irsb.pp()
+ '''
+ if final_statement.tag == 'Ist_Exit' :
+ exit_jumpkind = irsb.jumpkind if irsb.jumpkind else ""
+ if exit_jumpkind == "Ijk_Boring":
+ '''
+ loop_bound_cond = False
+ muqi_count = 0
+ muqi_count = self.state.br_instruction_set[hex(irsb.instruction_addresses[-1])] if hex(irsb.instruction_addresses[-1]) in self.state.br_instruction_set else 0
+ '''
+ print("muqi_count:"+str(muqi_count))
+ print(successors.all_successors)
+ print(successors.successors)
+ print(successors.flat_successors)
+ print(successors.unsat_successors)
+ print(successors.unconstrained_successors)
+ '''
+ #uncomment following to enable loop bound
+ #'''
+ if muqi_count >= 3:
+ loop_bound_cond = True
+ #'''
+ if loop_bound_cond == True :
+ with open(muqi.programe_function_name_txt,'a') as muqi_file:
+ print("block range:[",hex(self.state.addr), "->", hex(self.state.addr+self.state.project.factory.block(self.state.addr).vex.size),"]",file=muqi_file)
+ print('current state is:[', self.state,']',file=muqi_file)
+ print('In fakeret',file=muqi_file)
+ print('----dump z3 start----',file=muqi_file)
+ print('(_ bv0 64)',file=muqi_file)
+ print('----dump z3 end----',file=muqi_file)
+
+ successors.all_successors=[]
+ successors.successors=[]
+ successors.flat_successors=[]
+ successors.unsat_successors=[]
+ successors.unconstrained_successors=[]
+ break
try:
self.handle_vex_block(irsb)
except errors.SimReliftException as e:
@@ -171,16 +209,100 @@ class HeavyVEXMixin(SuccessorsMixin, ClaripyDataMixin, SimStateStorageMixin, VEX
break
else:
break
-
+ print("==============")
+ print("final_statement is :")
+ print(final_statement)
+ print(final_statement.tag)
+ print(irsb.next)
+ print(irsb.jumpkind)
+ print(type(irsb.jumpkind))
+ print(self.state.regs)
+ irsb.next.pp()
+ print(successors.all_successors)
+ print(successors.successors)
+ print(successors.flat_successors)
+ print(successors.unsat_successors)
+ print(successors.unconstrained_successors)
+ if final_statement.tag == 'Ist_Exit' :
+ exit_jumpkind = irsb.jumpkind if irsb.jumpkind else ""
+ if exit_jumpkind == "Ijk_Boring":
+ if len(list(successors.all_successors)) == 2 and len(list(successors.unsat_successors)) == 0:
+ with open(muqi.programe_function_name_txt,'a') as muqi_file:
+ if irsb.next.con.value == irsb.addr+irsb.size:
+ print('In cbranch',file=muqi_file)
+ print('address added is:[',hex(final_statement.dst.value),']',file=muqi_file)
+ else:
+ print('In cbranch_flip',file=muqi_file)
+ print('address added is:[',hex(irsb.next.con.value),']',file=muqi_file)
+ print('----dump z3 start----',file=muqi_file)
+ print(claripy._backend_z3.z3_expr_to_smtmuqi(claripy._backend_z3.convert(claripy._backend_z3.simplify( self._analyze_vex_stmt_Exit_guard(final_statement.guard)[0]))),file=muqi_file)
+ print('----dump z3 end----',file=muqi_file)
+ elif len(list(successors.all_successors)) == 2 and len(list(successors.unsat_successors)) == 1:
+ with open(muqi.programe_function_name_txt,'a') as muqi_file:
+
+ print('In branch',file=muqi_file)
+ print('current address is:[', hex(irsb.addr),']',file=muqi_file)
+ try:
+ print('address added is:[', hex((successors.successors)[0].addr),']',file=muqi_file)
+ except:
+ print('address added is:[ unknown ]',file=muqi_file)
+
+ for state_succ in list(successors.all_successors):
+ if hex(irsb.instruction_addresses[-1]) in state_succ.br_instruction_set:
+ state_succ.br_instruction_set[hex(irsb.instruction_addresses[-1])] += 1
+
+ else:
+ state_succ.br_instruction_set[hex(irsb.instruction_addresses[-1])] = 1
+
+ exit_jumpkind = irsb.jumpkind if irsb.jumpkind else ""
+ #if final_statement.tag != 'Ist_AbiHint' and final_statement.tag != 'Ist_Exit' :
+ if exit_jumpkind == 'Ijk_Ret' :
+ with open(muqi.programe_function_name_txt,'a') as muqi_file:
+ print('In ret',file=muqi_file)
+ print('----dump z3 start----',file=muqi_file)
+ #print(claripy._backend_z3.z3_expr_to_smtmuqi(claripy._backend_z3.convert(claripy._backend_z3.simplify(self.state.regs.rax))),file=muqi_file)
+ print(claripy._backend_z3.z3_expr_to_smtmuqi(claripy._backend_z3.convert(claripy._backend_z3.simplify(self.state.registers.load(self.state.arch.ret_offset, 8)))),file=muqi_file)
+
+ print('----dump z3 end----',file=muqi_file)
+
+ if exit_jumpkind != 'Ijk_Ret' and exit_jumpkind != 'Ijk_Call' and final_statement.tag != 'Ist_Exit' :
+ with open(muqi.programe_function_name_txt,'a') as muqi_file:
+ print('In branch',file=muqi_file)
+ print('current address is:[', hex(irsb.addr),']',file=muqi_file)
+ try:
+ print('address added is:[', hex(irsb.next.con.value),']',file=muqi_file)
+ #print(irsb.next)
+ #print(type(irsb.next))
+ except:
+ print('address added is:[ unknown ]',file=muqi_file)
+ for state_succ in list(successors.all_successors):
+ if hex(irsb.instruction_addresses[-1]) in state_succ.br_instruction_set:
+ #state_succ.br_instruction_set[final_statement] += 1
+ state_succ.br_instruction_set[hex(irsb.instruction_addresses[-1])] += 1
+
+ else:
+ #state_succ.br_instruction_set[final_statement] = 1
+ state_succ.br_instruction_set[hex(irsb.instruction_addresses[-1])] = 1
# do return emulation and calless stuff
for exit_state in list(successors.all_successors):
exit_jumpkind = exit_state.history.jumpkind if exit_state.history.jumpkind else ""
if o.CALLLESS in self.state.options and exit_jumpkind == "Ijk_Call":
+ '''
exit_state.registers.store(
exit_state.arch.ret_offset,
exit_state.solver.Unconstrained('fake_ret_value', exit_state.arch.bits)
)
+ '''
+ exit_state.registers.store(
+ exit_state.arch.ret_offset,
+ #muqi_change here
+ #make internal/external call return 0.
+ claripy.BVV(0, exit_state.arch.bits),
+ # exit_state.solver.Unconstrained(
+ # "fake_ret_value", exit_state.arch.bits
+ # ),
+ )
exit_state.scratch.target = exit_state.solver.BVV(
successors.addr + irsb.size, exit_state.arch.bits
)
@@ -212,6 +334,8 @@ class HeavyVEXMixin(SuccessorsMixin, ClaripyDataMixin, SimStateStorageMixin, VEX
# statements
def _handle_vex_stmt(self, stmt):
+ print("In _handle_vex_stmt")
+ print(stmt)
self.state.scratch.stmt_idx = self.stmt_idx
super()._handle_vex_stmt(stmt)
@@ -242,39 +366,52 @@ class HeavyVEXMixin(SuccessorsMixin, ClaripyDataMixin, SimStateStorageMixin, VEX
cont_state = None
exit_state = None
guard = guard != 0
+ print("In _perform_vex_stmt_Exit")
if o.COPY_STATES not in self.state.options:
# very special logic to try to minimize copies
# first, check if this branch is impossible
if guard.is_false():
+ print("guard.is_false()")
cont_state = self.state
elif o.LAZY_SOLVES not in self.state.options and not self.state.solver.satisfiable(extra_constraints=(guard,)):
+ print("cont_state = self.state")
cont_state = self.state
# then, check if it's impossible to continue from this branch
elif guard.is_true():
+ print("guard is true")
exit_state = self.state
elif o.LAZY_SOLVES not in self.state.options and not self.state.solver.satisfiable(extra_constraints=(claripy.Not(guard),)):
+ print("exit_state = self.state")
exit_state = self.state
else:
+ print("final else")
exit_state = self.state.copy()
cont_state = self.state
else:
+ print("Copy state in state options")
exit_state = self.state.copy()
cont_state = self.state
if exit_state is not None:
+ print(" exit_state is not None:")
self.successors.add_successor(exit_state, target, guard, jumpkind,
exit_stmt_idx=self.stmt_idx, exit_ins_addr=self.state.scratch.ins_addr)
if cont_state is None:
+ print("cont_state is None:")
raise VEXEarlyExit
+ print("End of _perform_vex_stmt_Exit")
+ print("add constraint of _perform_vex_stmt_Exit")
# Do our bookkeeping on the continuing self.state
cont_condition = ~guard
cont_state.add_constraints(cont_condition)
cont_state.scratch.guard = claripy.And(cont_state.scratch.guard, cont_condition)
+ print((cont_state.scratch.guard))
+ print(claripy._backend_z3.z3_expr_to_smtmuqi(claripy._backend_z3.convert(claripy._backend_z3.simplify( cont_state.scratch.guard))))
def _perform_vex_stmt_Dirty_call(self, func_name, ty, args, func=None):
if func is None:
try:
@@ -282,6 +419,7 @@ class HeavyVEXMixin(SuccessorsMixin, ClaripyDataMixin, SimStateStorageMixin, VEX
except AttributeError as e:
raise errors.UnsupportedDirtyError(f"Unsupported dirty helper {func_name}") from e
retval, retval_constraints = func(self.state, *args)
+ print("add constraint of _perform_vex_stmt_Dirty_call")
self.state.add_constraints(*retval_constraints)
return retval
@@ -294,12 +432,16 @@ class HeavyVEXMixin(SuccessorsMixin, ClaripyDataMixin, SimStateStorageMixin, VEX
if self.state.solver.symbolic(result) and o.CONCRETIZE in self.state.options:
concrete_value = self.state.solver.BVV(self.state.solver.eval(result), len(result))
+ print("add constraint of _instrument_vex_expr")
self.state.add_constraints(result == concrete_value)
result = concrete_value
return super()._instrument_vex_expr(result)
def _perform_vex_expr_Load(self, addr, ty, endness, **kwargs):
+ print("In _perform_vex_expr_Load")
+ print(addr)
+ print(ty)
result = super()._perform_vex_expr_Load(addr, ty, endness, **kwargs)
if o.UNINITIALIZED_ACCESS_AWARENESS in self.state.options:
if getattr(addr._model_vsa, 'uninitialized', False):
diff --git a/angr/engines/vex/light/light.py b/angr/engines/vex/light/light.py
index a52265fc3..0698a93d1 100644
--- a/angr/engines/vex/light/light.py
+++ b/angr/engines/vex/light/light.py
@@ -6,6 +6,11 @@ import pyvex
from ...engine import SimEngineBase
from ....utils.constants import DEFAULT_STATEMENT
+from .... import muqi
+import claripy
+#from claripy import claripy.backends
+from claripy.ast.bv import BV
+
l = logging.getLogger(name=__name__)
#pylint:disable=arguments-differ,unused-argument,no-self-use
@@ -166,7 +171,20 @@ class VEXMixin(SimEngineBase):
pass
def _handle_vex_stmt_AbiHint(self, stmt):
- pass
+ if self.irsb.jumpkind == "Ijk_Ret" :
+ #print("muqi test return")
+ #print(self.state.regs.rax)
+ pass
+ '''
+ with open(muqi.programe_function_name_txt,'a') as muqi_file:
+ print('In ret',file=muqi_file)
+ print('----dump z3 start----',file=muqi_file)
+ print(claripy._backend_z3.z3_expr_to_smtmuqi(claripy._backend_z3.convert(claripy._backend_z3.simplify(self.state.regs.rax))),file=muqi_file)
+ print('----dump z3 end----',file=muqi_file)
+ '''
+ elif self.irsb.jumpkind == "Ijk_Call" :
+ #print("muqi test call")
+ pass
def _handle_vex_stmt_MBE(self, stmt):
pass
@@ -203,6 +221,33 @@ class VEXMixin(SimEngineBase):
def _analyze_vex_stmt_Exit_guard(self, *a, **kw): return self. _handle_vex_expr(*a, **kw)
def _handle_vex_stmt_Exit(self, stmt: pyvex.stmt.Exit):
+ #print("In _handle_vex_stmt_Exit")
+ #print(stmt)
+ if self.irsb.jumpkind == "Ijk_Ret" :
+ pass
+ elif self.irsb.jumpkind == "Ijk_Boring" :
+ '''
+ with open(muqi.programe_function_name_txt,'a') as muqi_file:
+
+ if self.irsb.next.con.value == self.irsb.addr+self.irsb.size:
+ print('In cbranch',file=muqi_file)
+ print('address added is:[',hex(stmt.dst.value),']',file=muqi_file)
+ else:
+ print('In cbranch_flip',file=muqi_file)
+ print('address added is:[',hex(self.irsb.next.con.value),']',file=muqi_file)
+ print('----dump z3 start----',file=muqi_file)
+ print(claripy._backend_z3.z3_expr_to_smtmuqi(claripy._backend_z3.convert(claripy._backend_z3.simplify( self._analyze_vex_stmt_Exit_guard(stmt.guard)[0]))),file=muqi_file)
+ print('----dump z3 end----',file=muqi_file)
+ '''
+ print("cbranch or cbranch_flip")
+ print((stmt.guard))
+ print(claripy._backend_z3.z3_expr_to_smtmuqi(claripy._backend_z3.convert(claripy._backend_z3.simplify( self._analyze_vex_stmt_Exit_guard(stmt.guard)[0]))))
+
+ pass
+ elif self.irsb.jumpkind == "Ijk_Call" :
+ pass
+ else :
+ pass
self._perform_vex_stmt_Exit(
self._analyze_vex_stmt_Exit_guard(stmt.guard),
self._handle_vex_const(stmt.dst),
@@ -441,12 +486,28 @@ class VEXMixin(SimEngineBase):
self.irsb = irsb
self.tmps = [None]*self.irsb.tyenv.types_used
+ with open(muqi.programe_function_name_txt,'a') as muqi_file:
+ #with open(self.state.log_filepath_muqi,'a') as muqi_file:
+ print("block range:[",hex(irsb.addr), "->", hex(irsb.addr +irsb.size),"]",file=muqi_file)
+ print('current state is:[', self.state,']',file=muqi_file)
+
+ final_statement = irsb.statements[-1]
+
for stmt_idx, stmt in enumerate(irsb.statements):
self.stmt_idx = stmt_idx
self._handle_vex_stmt(stmt)
self.stmt_idx = DEFAULT_STATEMENT
self._handle_vex_defaultexit(irsb.next, irsb.jumpkind)
-
+ '''
+ if final_statement.tag != 'Ist_AbiHint' and final_statement.tag != 'Ist_Exit' :
+ with open(muqi.programe_function_name_txt,'a') as muqi_file:
+ print('In branch',file=muqi_file)
+ print('current address is:[', hex(irsb.addr),']',file=muqi_file)
+ try:
+ print('address added is:[', hex(irsb.next.con.value),']',file=muqi_file)
+ except:
+ print('address added is:[ unknown ]',file=muqi_file)
+ '''
def _handle_vex_defaultexit(self, expr: Optional[pyvex.expr.IRExpr], jumpkind: str):
self._perform_vex_defaultexit(
self._analyze_vex_defaultexit(expr) if expr is not None else None,
diff --git a/angr/exploration_techniques/loop_seer.py b/angr/exploration_techniques/loop_seer.py
index db6e41be3..daf66e713 100644
--- a/angr/exploration_techniques/loop_seer.py
+++ b/angr/exploration_techniques/loop_seer.py
@@ -3,7 +3,7 @@ import logging
from . import ExplorationTechnique
from ..knowledge_base import KnowledgeBase
from ..knowledge_plugins.functions import Function
-
+from ..import muqi
l = logging.getLogger(name=__name__)
@@ -157,7 +157,21 @@ class LoopSeer(ExplorationTechnique):
else:
if succ_state.addr in succ_state.loop_data.back_edge_trip_counts:
counts = succ_state.loop_data.back_edge_trip_counts[succ_state.addr][-1]
- if counts > self.bound:
+
+ muqi_count = 0
+ muqi_count_hash = {}
+ for addr in succ_state.history.bbl_addrs:
+ if addr in muqi_count_hash:
+ muqi_count_hash[addr] += 1
+ else:
+ muqi_count_hash[addr] = 1
+ if succ_state.addr in muqi_count_hash:
+ muqi_count_hash[addr] += 1
+ else:
+ muqi_count_hash[addr] = 1
+ muqi_count = max(muqi_count_hash.values())
+
+ if counts > self.bound or muqi_count > self.bound:
if self.bound_reached is not None:
# We want to pass self to modify the LoopSeer state if needed
# Users can modify succ_state in the handler to implement their own logic
@@ -166,6 +180,21 @@ class LoopSeer(ExplorationTechnique):
else:
# Remove the state from the successors object
# This state is going to be filtered by the self.filter function
+ with open(muqi.programe_function_name_txt,'a') as muqi_file:
+ #muqi add fake return node here for branch
+ print('successors transfer:[',hex(state.addr),'->', hex(succ_state.addr) ,']',file=muqi_file)
+ print('parent state is:[', succ_state.history,']',file=muqi_file)
+ print("block range:[",hex(succ_state.addr), "->", hex(succ_state.addr +succ_state.project.factory.block(succ_state.addr).vex.size),"]",file=muqi_file)
+ print('current state is:[', succ_state,']',file=muqi_file)
+ print('In fakeret',file=muqi_file)
+ print('----dump z3 start----',file=muqi_file)
+ print('; benchmark',file=muqi_file)
+ print('(_ bv0 64)',file=muqi_file)
+ print('----dump z3 end----',file=muqi_file)
+
+
+
+
self.cut_succs.append(succ_state)
l.debug("%s back edge based trip counts %s", state, state.loop_data.back_edge_trip_counts)
@@ -190,7 +219,13 @@ class LoopSeer(ExplorationTechnique):
succ_state.loop_data.back_edge_trip_counts[node.addr].append(0)
# save info about current active loop for the succ state
- succ_state.loop_data.header_trip_counts[header].append(1)
+ #succ_state.loop_data.header_trip_counts[header].append(1)
+ #muqi we change here for the new header count method
+ if not succ_state.loop_data.header_trip_counts[header]:
+ succ_state.loop_data.header_trip_counts[header].append(1)
+ else:
+ succ_state.loop_data.header_trip_counts[header][-1] += 1
+
succ_state.loop_data.current_loop.append((loop, exits))
return succs
diff --git a/angr/factory.py b/angr/factory.py
index 0b933232d..d647381dd 100644
--- a/angr/factory.py
+++ b/angr/factory.py
@@ -9,6 +9,7 @@ from .callable import Callable
from .errors import AngrAssemblyError
from .engines import UberEngine, ProcedureEngine, SimEngineConcrete
+from . import muqi
l = logging.getLogger(name=__name__)
@@ -108,7 +109,7 @@ class AngrObjectFactory:
"""
return self.project.simos.state_full_init(**kwargs)
- def call_state(self, addr, *args, **kwargs):
+ def call_state(self, input_txt, addr, *args, **kwargs):
"""
Returns a state object initialized to the start of a given function, as if it were called with given parameters.
@@ -150,6 +151,7 @@ class AngrObjectFactory:
set alloc_base to point to somewhere other than the stack, set grow_like_stack to False so that sequencial
allocations happen at increasing addresses.
"""
+ muqi.programe_function_name_txt = input_txt
return self.project.simos.state_call(addr, *args, **kwargs)
def simulation_manager(self, thing: Optional[Union[List[SimState], SimState]]=None, **kwargs) -> 'SimulationManager':
diff --git a/angr/sim_manager.py b/angr/sim_manager.py
index 2b8a67e9c..5802d83e7 100644
--- a/angr/sim_manager.py
+++ b/angr/sim_manager.py
@@ -15,7 +15,7 @@ from .sim_state import SimState
from .state_hierarchy import StateHierarchy
from .errors import AngrError, SimUnsatError, SimulationManagerError
from .sim_options import LAZY_SOLVES
-
+from . import muqi
l = logging.getLogger(name=__name__)
@@ -79,6 +79,9 @@ class SimulationManager:
**kwargs):
super().__init__()
+ self.jumpout_edge = []
+ self.abort_edge = []
+
self._project = project
self.completion_mode = completion_mode
self._errored = []
@@ -415,12 +418,115 @@ class SimulationManager:
return step_func(self)
return self
+ #jumpout_edge = []
+ def input_jumpout_edge(self, input_jumpout_list):
+ self.jumpout_edge = input_jumpout_list
+ def input_abort_edge(self, input_abort_list):
+ self.abort_edge = input_abort_list
+
def step_state(self, state, successor_func=None, **run_args):
"""
Don't use this function manually - it is meant to interface with exploration techniques.
"""
try:
successors = self.successors(state, successor_func=successor_func, **run_args)
+
+ for exit_state in list(successors.all_successors):
+ exit_jumpkind = exit_state.history.jumpkind
+
+ if exit_jumpkind is None:
+ exit_jumpkind = ""
+
+ cond1 = exit_jumpkind == "Ijk_Boring" and exit_state.addr in self.jumpout_edge
+ #defaultly, we do not need to h
+ cond2 = False
+ if exit_state.scratch.irsb :
+ try:
+ call_address = exit_state.scratch.irsb.next.con.value
+ cond2 = exit_state.scratch.irsb.jumpkind == "Ijk_Call" and call_address in self.abort_edge
+ except:
+ pass
+
+ if cond1==True or cond2 ==True :
+ successors.all_successors.remove(exit_state)
+
+ with open(muqi.programe_function_name_txt,'a') as muqi_file:
+ print('successors transfer:[',hex(state.addr),'->', hex(exit_state.addr) ,']',file=muqi_file)
+ print('parent state is:[', exit_state.history,']',file=muqi_file)
+ if cond1 == True:
+ #muqi, since we use transition_graph in D-helix to identify the node's range, the jmp out address cannot be in this function's transition_graph
+ #hence we give node size as 0
+ print("block range:[",hex(exit_state.addr), "->", hex(exit_state.addr),"]",file=muqi_file)
+ if cond2 == True:
+ #hex(succ_state.addr +succ_state.project.factory.block(succ_state.addr).vex.size)
+ print("block range:[",hex(exit_state.addr), "->", hex(exit_state.addr+exit_state.project.factory.block(exit_state.addr).vex.size),"]",file=muqi_file)
+ print('current state is:[', exit_state,']',file=muqi_file)
+ print('In fakeret',file=muqi_file)
+ print('----dump z3 start----',file=muqi_file)
+ print('(_ bv0 64)',file=muqi_file)
+ print('----dump z3 end----',file=muqi_file)
+
+ for exit_state in list(successors.successors):
+ exit_jumpkind = exit_state.history.jumpkind
+ if exit_jumpkind is None:
+ exit_jumpkind = ""
+ cond1 = exit_jumpkind == "Ijk_Boring" and exit_state.addr in self.jumpout_edge
+ cond2 = False
+ if exit_state.scratch.irsb :
+ try:
+ call_address = exit_state.scratch.irsb.next.con.value
+ cond2 = exit_state.scratch.irsb.jumpkind == "Ijk_Call" and call_address in self.abort_edge
+ except:
+ pass
+ if cond1==True or cond2 ==True :
+ successors.successors.remove(exit_state)
+
+ for exit_state in list(successors.flat_successors):
+ exit_jumpkind = exit_state.history.jumpkind
+ if exit_jumpkind is None:
+ exit_jumpkind = ""
+ cond1 = exit_jumpkind == "Ijk_Boring" and exit_state.addr in self.jumpout_edge
+ cond2 = False
+ if exit_state.scratch.irsb :
+ try:
+ call_address = exit_state.scratch.irsb.next.con.value
+ cond2 = exit_state.scratch.irsb.jumpkind == "Ijk_Call" and call_address in self.abort_edge
+ except:
+ pass
+ if cond1==True or cond2 ==True :
+ successors.flat_successors.remove(exit_state)
+
+ for exit_state in list(successors.unsat_successors):
+ exit_jumpkind = exit_state.history.jumpkind
+ if exit_jumpkind is None:
+ exit_jumpkind = ""
+ cond1 = exit_jumpkind == "Ijk_Boring" and exit_state.addr in self.jumpout_edge
+ cond2 = False
+ if exit_state.scratch.irsb :