-
Notifications
You must be signed in to change notification settings - Fork 8
/
sym_exec.py
2353 lines (2148 loc) · 103 KB
/
sym_exec.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
# !/usr/bin/python3
# -*- coding: utf-8 -*-
"""
The main logic of symbolic execution. Apart from the execution logic, the module
contains some variables to help execution, some class to construct runtime structure.
"""
import math
import z3
import copy
import utils
from random import randint, uniform
from z3.z3util import get_vars
from collections import defaultdict
import emulator
import logger
import number
from global_variables import global_vars
from bug_analyzer import check_block_dependence_old
from bug_analyzer import check_ethereum_delegate_call
from bug_analyzer import check_ethereum_greedy
from bug_analyzer import cur_state_analysis
from bug_analyzer import check_mishandled_exception
from runtime import *
from bug_analyzer import library_function_dict
from bug_analyzer import find_symbolic_in_solver
import pprint
# The variables will be used in exec() function.
path_condition = []
memory_address_symbolic_variable = {}
solver = z3.Solver()
recur_depth = 0
loop_depth_dict = defaultdict(int)
path_abort = False
path_depth = 0
block_number_flag = False
gas_cost = 0
class ModuleInstance:
"""A module instance is the runtime representation of a module. It is created by instantiating a module, and
collects runtime representations of all entities that are imported, defined, or exported by the module.
moduleinst ::= {
types functype∗
funcaddrs funcaddr∗
tableaddrs tableaddr∗
memaddrs memaddr∗
globaladdrs globaladdr∗
exports exportinst∗
}
Attributes:
types: list of function type
funcaddrs: function address of current module
tableaddrs: table address of current module
globaladdrs: global address of current module
exports: the export instance of current module
"""
def __init__(self):
self.types: typing.List[structure.FunctionType] = []
self.funcaddrs: typing.List[int] = []
self.tableaddrs: typing.List[int] = []
self.memaddrs: typing.List[int] = []
self.globaladdrs: typing.List[int] = []
self.exports: typing.List[ExportInstance] = []
def instantiate(
self,
module: structure.Module,
store: Store,
externvals: typing.List[ExternValue] = None
):
self.types = module.types
# [TODO] : z3.If module is not valid, the panic
for e in module.imports:
assert e.kind in bin_format.extern_type
assert len(module.imports) == len(externvals)
for i in range(len(externvals)):
e = externvals[i]
assert e.extern_type in bin_format.extern_type
if e.extern_type == bin_format.extern_func:
a = store.funcs[e.addr]
b = self.types[module.imports[i].desc]
assert a.functype.args == b.args
assert a.functype.rets == b.rets
elif e.extern_type == bin_format.extern_table:
a = store.tables[e.addr]
b = module.imports[i].desc
assert a.elemtype == b.elemtype
assert import_matching_limits(b.limits, a.limits)
elif e.extern_type == bin_format.extern_mem:
a = store.mems[e.addr]
b = module.imports[i].desc
assert import_matching_limits(b, a.limits)
elif e.extern_type == bin_format.extern_global:
a = store.globals[e.addr]
b = module.imports[i].desc
assert a.value.valtype == b.valtype
# Let vals be the vector of global initialization values determined by module and externvaln
auxmod = ModuleInstance()
auxmod.globaladdrs = [e.addr for e in externvals if e.extern_type == bin_format.extern_global]
stack = Stack()
frame = Frame(auxmod, [], 1, -1)
stack.add(frame)
vals = []
for glob in module.globals:
v = exec_expr(store, frame, stack, glob.expr, -1)[0][0]
vals.append(v)
assert isinstance(stack.pop(), Frame)
# Allocation
self.allocate(module, store, externvals, vals)
# Push the frame F to the stack
frame = Frame(self, [], 1, -1)
stack.add(frame)
# For each element segment in module.elem, then do:
for e in module.elem:
offset = exec_expr(store, frame, stack, e.expr, -1)[0][0]
assert offset.valtype == bin_format.i32
t = store.tables[self.tableaddrs[e.tableidx]]
for i, elem in enumerate(e.init):
t.elem[offset.n + i] = elem
# For each data segment in module.data, then do:
for e in module.data:
offset = exec_expr(store, frame, stack, e.expr, -1)[0][0]
assert offset.valtype == bin_format.i32
m = store.mems[self.memaddrs[e.memidx]]
end = offset.n + len(e.init)
assert end <= len(m.data)
m.data[offset.n: offset.n + len(e.init)] = e.init
# store the abi name and its address
global_vars.data_addr_dict[offset.n] = e.init.decode(errors='ignore').split('\00')[0]
# Assert: due to validation, the frame F is now on the top of the stack.
assert isinstance(stack.pop(), Frame)
assert stack.len() == 0
# z3.If the start function module.start is not empty, invoke the function instance.
if module.start:
logger.infoln(f'Running start function {module.start}:')
call(self, module.start, store, stack)
def allocate(
self,
module: structure.Module,
store: Store,
externvals: typing.List[ExternValue],
vals: typing.List[Value]
):
self.types = module.types
# Imports
self.funcaddrs.extend([e.addr for e in externvals if e.extern_type == bin_format.extern_func])
self.tableaddrs.extend([e.addr for e in externvals if e.extern_type == bin_format.extern_table])
self.memaddrs.extend([e.addr for e in externvals if e.extern_type == bin_format.extern_mem])
self.globaladdrs.extend([e.addr for e in externvals if e.extern_type == bin_format.extern_global])
# For each function func in module.funcs, then do:
for func in module.funcs:
functype = self.types[func.typeidx]
funcinst = WasmFunc(functype, self, func)
store.funcs.append(funcinst)
self.funcaddrs.append(len(store.funcs) - 1)
# For each table in module.tables, then do:
for table in module.tables:
tabletype = table.tabletype
elemtype = tabletype.elemtype
tableinst = TableInstance(elemtype, tabletype.limits)
store.tables.append(tableinst)
self.tableaddrs.append(len(store.tables) - 1)
# For each memory module.mems, then do:
for mem in module.mems:
meminst = MemoryInstance(mem.memtype)
store.mems.append(meminst)
self.memaddrs.append(len(store.mems) - 1)
# For each global in module.globals, then do:
for i, glob in enumerate(module.globals):
val = vals[i]
if val.valtype != glob.globaltype.valtype:
raise Exception('Mimatch valtype!')
globalinst = GlobalInstance(val, glob.globaltype.mut)
store.globals.append(globalinst)
self.globaladdrs.append(len(store.globals) - 1)
# For each export in module.exports, then do:
for i, export in enumerate(module.exports):
externval = ExternValue(export.kind, export.desc)
exportinst = ExportInstance(export.name, externval)
# set address of functions
if export.name == 'apply' and export.kind == bin_format.extern_func:
logger.infoln('apply address:', export.desc)
global_vars.set_apply_function_addr(externval.addr)
if export.name == 'main' and export.kind == bin_format.extern_func:
logger.infoln('main address:', export.desc)
global_vars.set_main_function_addr(externval.addr)
self.exports.append(exportinst)
def import_matching_limits(limits1: structure.Limits, limits2: structure.Limits):
"""Check the limits is valid or not.
Args:
limits1: a limit instance
limits2: a limit instance
Returns:
true if the limit is valid else false.
"""
min1 = limits1.minimum
max1 = limits1.maximum
min2 = limits2.minimum
max2 = limits2.maximum
if max2 is None or (max1 is not None and max1 <= max2):
return True
return False
def hostfunc_call(
_: ModuleInstance,
address: int,
store: Store,
stack: Stack
):
"""The function call lib function. It will pop the args from stack
and return the result.
Args:
_: deprecated parameter.
address: the address of function.
store: store the functions.
stack: the current stack.
Returns:
result: the list of result, only one elem.
"""
f: HostFunc = store.funcs[address]
valn = [stack.pop() for _ in f.functype.args][::-1]
ctx = Ctx(store.mems)
r = f.hostcode(ctx, *[e.n for e in valn])
return [Value(f.functype.rets[0], r)]
def fake_hostfunc_call_old(
_: ModuleInstance,
address: int,
store: Store,
stack: Stack,
m
):
"""When the lib function is not exist, the hostfunc_call will crash, so the
fake_hostfunc_call is useful because the analysis tool could not get the lib
function.
Args:
_: deprecated parameter.
address: the address of function.
store: store the functions.
stack: the current stack.
Returns:
result: the list of result, only one elem.
"""
f: HostFunc = store.funcs[address]
valn = [stack.pop() for _ in f.functype.args][::-1]
val0 = []
# [TODO] A good method for return value.
if f.funcname:
logger.infoln(f'call eth.hostfunc : {f.funcname} {address}')
if len(f.functype.rets) <= 0:
if f.funcname == 'getExternalBalance':
global_vars.add_flag_getExternalBalance()
return []
elif f.functype.rets[0] == bin_format.i32:
r = randint(0, 0)
elif f.functype.rets[0] == bin_format.i64:
r = randint(0, 0)
elif f.functype.rets[0] == bin_format.f32:
r = uniform(0, 1)
else:
r = uniform(0, 1)
return [Value(f.functype.rets[0], r)]
def fake_hostfunc_call(
_: ModuleInstance,
address: int,
store: Store,
stack: Stack,
memory: list
):
"""When the lib function is not exist, the hostfunc_call will crash, so the
fake_hostfunc_call is useful because the analysis tool could not get the lib
function.
Args:
_: deprecated parameter.
address: the address of function.
store: store the functions.
stack: the current stack.
Returns:
result: the list of result, only one elem.
"""
f: HostFunc = store.funcs[address]
valn = [stack.pop() for _ in f.functype.args][::-1]
val0 = []
if f.funcname:
logger.infoln(f'call eth.hostfunc : {f.funcname} {address}')
if f.funcname in emulator.realize_list_host:
# [TODO] Pass different parameters according to the situation
r = f.hostcode(valn, solver, memory)
if type(r) == list:
return []
elif len(f.functype.rets) <= 0:
return []
elif f.functype.rets[0] == bin_format.i32:
r = randint(0, 0)
elif f.functype.rets[0] == bin_format.i64:
r = randint(0, 0)
elif f.functype.rets[0] == bin_format.f32:
r = uniform(0, 1)
else:
r = uniform(0, 1)
return [Value(f.functype.rets[0], r)]
def wasmfunc_call(
module: ModuleInstance,
address: int,
store: Store,
stack: Stack
):
"""The function call the internal wasm function.
Args:
module: the current module.
address: the address of function.
store: store the functions.
stack: the current stack.
Returns:
r: the list of result, only one elem.
"""
f: WasmFunc = store.funcs[address]
code = f.code.expr.data
flag_not_print = 0
flag_skip = 0
func_name = list()
if address - global_vars.library_offset > 32:
func_name = list(library_function_dict.keys())[list(library_function_dict.values()).index(address-global_vars.library_offset)]
global_vars.list_func.append(f'{func_name} {address} -> ')
logger.infoln(f'wasmfunc call: {global_vars.list_func} ')
if func_name == '$callvalue':
if len(global_vars.list_func) > 2:
global_vars.flag_getCallValue_in_function = True
else:
global_vars.list_func.append(f' {address} -> ')
logger.infoln(f'wasmfunc call: {global_vars.list_func} ')
pass
valn = [stack.pop() for _ in f.functype.args][::-1]
val0 = []
if func_name in emulator.realize_list_wasm:
r = emulator.wasmfunc_map['ethereum'][func_name](valn, solver, store)
if r:
flag_skip = 1
if len(r) == 4:
store.globals[module.globaladdrs[0]] = r[1]
store.globals[module.globaladdrs[1]] = r[2]
store.globals[module.globaladdrs[2]] = r[3]
r = [r[0]]
for e in f.code.locals:
if e == bin_format.i32:
val0.append(Value.from_i32(0))
elif e == bin_format.i64:
val0.append(Value.from_i64(0))
elif e == bin_format.f32:
val0.append(Value.from_f32(0))
else:
val0.append(Value.from_f64(0))
frame = Frame(module, valn + val0, len(f.functype.rets), len(code))
if flag_skip != 1:
stack.add(frame)
stack.add(Label(len(f.functype.rets), len(code)))
# An expression is evaluated relative to a current frame pointing to its containing module instance.
r, new_stack = exec_expr(store, frame, stack, f.code.expr, -1)
# Exit
while not isinstance(new_stack.pop(), Frame):
if new_stack.len() <= 0:
raise Exception('Signature mismatch in call!')
else:
# r需要仔细斟酌
new_stack = stack
tmp = global_vars.list_func.pop()
logger.infoln(f'return func {tmp}')
logger.infoln(f'{global_vars.list_func}')
flag_skip = 0
if flag_not_print == 1:
flag_not_print = 0
logger.lvl = global_vars.lvl
stack.data[:] = new_stack.data
return r
def fake_wasmfunc_call(
module: ModuleInstance,
address: int,
store: Store,
stack: Stack
):
"""The fake function call the internal wasm function.
Args:
module: the current module.
address: the address of function.
store: store the functions.
stack: the current stack.
Returns:
r: the list of fake result, only one elem at present.
"""
f: WasmFunc = store.funcs[address]
valn = [stack.pop() for _ in f.functype.args][::-1]
if len(f.functype.rets) <= 0:
return []
if f.functype.rets[0] == bin_format.i32:
r = randint(0, 1927)
elif f.functype.rets[0] == bin_format.i64:
r = randint(0, 1927)
elif f.functype.rets[0] == bin_format.f32:
r = uniform(0, 1)
else:
r = uniform(0, 1)
return [Value(f.functype.rets[0], r)]
def call(
module: ModuleInstance,
address: int,
store: Store,
stack: Stack,
init_constraints: list = (),
):
"""The function call the internal wasm function or lib function.
Args:
module: the current module.
address: the address of function.
store: store the functions.
stack: the current stack.
init_constraints: initial function's args constraints.
Returns:
r: the list of result, only one elem.
"""
f = store.funcs[address]
assert len(f.functype.rets) <= 1
for i, t in enumerate(f.functype.args[::-1]):
ia = t
ib = stack.data[-1 - i]
if ia != ib.valtype:
raise Exception('Signature mismatch in call!')
init_variables(init_constraints) # add initial constraints
if isinstance(f, WasmFunc):
return wasmfunc_call(module, address, store, stack)
if isinstance(f, HostFunc):
return hostfunc_call(module, address, store, stack)
def fake_call(
module: ModuleInstance,
address: int,
store: Store,
stack: Stack,
m
):
"""The function call the internal wasm function or lib function.
It does not execute lib function and only return a valid random
result.
Args:
module: the current module.
address: the address of function.
store: store the functions.
stack: the current stack.
Returns:
r: the list of result, only one elem.
"""
f = store.funcs[address]
assert len(f.functype.rets) <= 1
for i, t in enumerate(f.functype.args[::-1]):
ia = t
ib = stack.data[-1 - i]
if ia != ib.valtype:
raise Exception('Signature mismatch in call!')
if isinstance(f, WasmFunc):
if global_vars.detection_mode:
return fake_wasmfunc_call(module, address, store, stack)
r = wasmfunc_call(module, address, store, stack)
return r
if isinstance(f, HostFunc):
return fake_hostfunc_call(module, address, store, stack, m)
# def set_stack_and_global()
# [TODO]
def spec_br(l: int, stack: Stack) -> int:
"""Process branch instruction.
Args:
l: the pc of Label.
stack: the runtime stack.
Returns:
result: the target position of branch instruction.
"""
# Let L be hte l-th label appearing on the stack, starting from the top and counting from zero.
L = [i for i in stack.data if isinstance(i, Label)][::-1][l]
n = L.arity
v = [stack.pop() for _ in range(n)][::-1]
s = 0
while True:
e = stack.pop()
if isinstance(e, Label):
s += 1
if s == l + 1:
break
stack.ext(v)
return L.continuation - 1
def init_variables(init_constraints: list = ()) -> None:
"""Initialize the variables.
"""
global path_condition, memory_address_symbolic_variable, gas_cost, solver, \
recur_depth, loop_depth_dict, path_abort, path_depth, block_number_flag
solver = z3.Solver()
solver.add(init_constraints)
path_condition = list(init_constraints)
memory_address_symbolic_variable = {}
recur_depth = 0
loop_depth_dict = defaultdict(int)
path_abort = False
path_depth = 0
block_number_flag = False
gas_cost = 0
def exec_expr(
store: Store,
frame: Frame,
stack: Stack,
expr: structure.Expression,
pc: int = -1
):
"""An expression is evaluated relative to a current frame pointing to its containing module instance.
1. Jump to the start of the instruction sequence instr∗ of the expression.
2. Execute the instruction sequence.
3. Assert: due to validation, the top of the stack contains a value.
4. Pop the value val from the stack.
Args:
store: the function address of current module
frame: current runtime frame
stack: the stack for current state
expr: the instructions to execute
pc: the program counter
Returns:
stack and executed result
Raises:
AttributeError: if the Label instance is read for getting value
z3Exception: if the symbolic variable is converted
"""
global path_abort, path_depth, recur_depth, loop_depth_dict, block_number_flag, gas_cost, path_condition
branch_res = []
module = frame.module
if not expr.data:
raise Exception('Empty init expr!')
while True:
global_vars.cur_sum_pc += 1
pc += 1
if path_abort or pc >= len(expr.data):
break
# Analysis current state to update some variables and detect vulnerability
if global_vars.detection_mode:
cur_state_analysis(store, frame, stack, expr, pc, solver)
pc = global_vars.pc
i = expr.data[pc]
logger.infoln(f'{str(i) :<18} {stack} {pc} {global_vars.cur_sum_pc}')
# accumulate the gas cost to detect expensive fallback
gas_cost += bin_format.gas_cost.get(i, 0)
global_vars.max_gas_cost = max(global_vars.max_gas_cost, gas_cost)
if logger.lvl >= 2:
ls = [f'{i}: {bin_format.valtype[l.valtype][0]} {l.n}' for i, l in enumerate(frame.locals)]
gs = [f'{i}: {"mut " if g.mut else ""}{bin_format.valtype[g.value.valtype][0]} {g.value.n}' for i, g in
enumerate(store.globals)]
for n, e in (('locals', ls), ('globals', gs)):
logger.verboseln(f'{" " * 18} {str(n) + ":":<8} [{", ".join(e)}]')
opcode = i.code
if bin_format.unreachable <= opcode <= bin_format.call_indirect:
if opcode == bin_format.unreachable:
global_vars.unreachable_count += 1
raise Exception('unreachable')
break
# raise AssertionError('Unreachable opcode!')
if opcode == bin_format.nop:
continue
if opcode == bin_format.block:
arity = int(i.immediate_arguments != bin_format.empty)
stack.add(Label(arity, expr.composition[pc][-1] + 1))
continue
if opcode == bin_format.loop:
stack.add(Label(0, expr.composition[pc][0]))
continue
if opcode == bin_format.if_:
object_c = stack.pop()
c = object_c.n
arity = int(i.immediate_arguments != bin_format.empty)
stack.add(Label(arity, expr.composition[pc][-1] + 1))
if utils.is_all_real(c):
if c != 0:
continue
if len(expr.composition[pc]) > 2:
pc = expr.composition[pc][1]
continue
pc = expr.composition[pc][-1] - 1
continue
else:
solver.push()
solver.add(c != 0)
find_symbolic_in_solver(solver)
check_mishandled_exception(solver, global_vars.cur_sum_pc)
logger.debugln(solver)
logger.infoln(f'left branch ({pc}: {i})')
path_depth += 1
len_list_func = len(global_vars.list_func)
len_path_condition = len(path_condition)
global_vars.len_list_func = len(global_vars.list_func)
if recur_depth > global_vars.BRANCH_DEPTH_LIMIT:
if utils.is_symbolic(c): #and c
logger.debugln(f'recur {recur_depth}')
solver.pop()
# raise Exception('recur')
# 有时候返回数字0回栈顶不是个好的选择,如果if判断的栈顶元素是位向量,且内容为0,那么我们就返回它本身
return [object_c], global_vars.last_stack[-1]
return [], global_vars.last_stack[-1]
global_vars.last_stack.append(stack)
try:
if solver.check() == z3.unsat:
logger.infoln(f'({pc}: {i}) infeasible path detected!')
new_stack = copy.deepcopy(stack)
new_stack.pop()
else:
# Execute the left branch
new_store = copy.deepcopy(store)
new_frame = copy.deepcopy(frame)
new_stack = copy.deepcopy(stack)
new_expr = copy.deepcopy(expr)
new_pc = pc
block_number_flag = id(c) in global_vars.block_number_id_list or block_number_flag # set flag if "c" is associated with the block number
path_condition.append(c != 0)
recur_depth += 1
gas_cost -= bin_format.gas_cost.get(i, 0)
global_vars.sum_pc.append(global_vars.cur_sum_pc)
left_branch_res, new_stack = exec_expr(new_store, new_frame, new_stack, new_expr, new_pc)
logger.infoln(f'leave left branch{pc}')
gas_cost += bin_format.gas_cost.get(i, 0)
recur_depth -= 1
if path_abort:
path_abort = False
new_stack = copy.deepcopy(stack)
else:
branch_res += left_branch_res
if len(left_branch_res) <= 1:
global_vars.add_cond_and_results(path_condition[:], left_branch_res[:])
path_condition = path_condition[:len_path_condition]
except TimeoutError:
logger.infoln('Timeout in path exploration.')
except Exception as e:
logger.infoln(f'Exception: {e}')
global_vars.cur_sum_pc = global_vars.sum_pc.pop()
global_vars.list_func = global_vars.list_func[:len_list_func]
path_condition = path_condition[:len_path_condition]
recur_depth -= 1
m = store.mems[module.memaddrs[0]]
list_solver = solver.units()
vars = get_vars(list_solver[-1])
for var in vars:
if str(var) == 'callDataCopy_0':
if len(global_vars.list_func) == 1:
global_vars.clear_dict_symbolic_address()
path_depth -= 1
solver.pop()
solver.push()
solver.add(c == 0)
find_symbolic_in_solver(solver)
logger.debugln(solver)
logger.infoln(f'right branch ({pc}: {i})')
try:
if solver.check() == z3.unsat:
logger.infoln(f'({pc}: {i}) infeasible path detected!')
new_stack = stack
new_stack.pop()
else:
# Execute the right branch
new_store = copy.deepcopy(store)
new_frame = copy.deepcopy(frame)
new_stack = copy.deepcopy(stack)
new_expr = copy.deepcopy(expr)
new_pc = expr.composition[pc][1] if len(expr.composition[pc]) > 2 else expr.composition[pc][
-1] - 1
block_number_flag = True if id(
c) in global_vars.block_number_id_list else block_number_flag # set flag if "c" is associated with the block number
path_condition.append(c == 0)
recur_depth += 1
gas_cost -= bin_format.gas_cost.get(i, 0)
global_vars.sum_pc.append(global_vars.cur_sum_pc)
right_branch_res, new_stack = exec_expr(new_store, new_frame, new_stack, new_expr, new_pc)
logger.infoln(f'leave right branch {pc}')
logger.debugln(new_stack)
gas_cost += bin_format.gas_cost.get(i, 0)
recur_depth -= 1
if path_abort:
if path_depth <= 0:
temp_stack = Stack()
temp_stack.add(frame)
return branch_res, temp_stack
else:
new_stack = global_vars.last_stack[-1]
else:
branch_res += right_branch_res
if len(right_branch_res) <= 1:
global_vars.add_cond_and_results(path_condition[:], right_branch_res[:])
path_condition = path_condition[:len_path_condition]
except TimeoutError as e:
raise e
except Exception as e:
logger.infoln(f'Exception: {e}')
global_vars.cur_sum_pc = global_vars.sum_pc.pop()
global_vars.list_func = global_vars.list_func[:len_list_func]
path_condition = path_condition[:len_path_condition]
print('line:', e.__traceback__.tb_lineno)
recur_depth -= 1
solver.pop()
if path_depth <= 0:
temp_stack = Stack()
temp_stack.add(frame)
return branch_res, temp_stack
global_vars.last_stack.pop()
return branch_res, new_stack
if opcode == bin_format.else_:
for i in range(len(stack.data)):
i = -1 - i
e = stack.data[i]
if isinstance(e, Label):
pc = e.continuation - 1
logger.debugln(pc)
del stack.data[i]
break
continue
if opcode == bin_format.end:
# label{instr*} val* end -> val*
if stack.status() == Label:
for i in range(len(stack.data)):
i = -1 - i
if isinstance(stack.data[i], Label):
del stack.data[i]
break
continue
# frame{F} val* end -> val*
v = [stack.pop() for _ in range(frame.arity)][::-1]
stack.ext(v)
continue
if opcode == bin_format.br:
# too many loop depth
if loop_depth_dict[i.immediate_arguments] > global_vars.LOOP_DEPTH_LIMIT:
continue
# record the loop depth
loop_depth_dict[i.immediate_arguments] += 1
pc = spec_br(i.immediate_arguments, stack)
continue
if opcode == bin_format.br_if:
c = stack.pop().n
if utils.is_all_real(c):
# too many loop depth
if loop_depth_dict[i.immediate_arguments] > global_vars.LOOP_DEPTH_LIMIT:
continue
if c == 0:
continue
# record the loop depth
loop_depth_dict[i.immediate_arguments] += 1
pc = spec_br(i.immediate_arguments, stack)
continue
else:
solver.push()
solver.add(c == 0)
find_symbolic_in_solver(solver)
logger.infoln(f'left branch ({pc}: {i})')
path_depth += 1
if recur_depth > global_vars.BRANCH_DEPTH_LIMIT:
return branch_res, global_vars.last_stack[-1] if global_vars.last_stack != [] else None
global_vars.last_stack.append(stack)
try:
if solver.check() == z3.unsat:
logger.infoln(f'({pc}: {i}) infeasible path detected!')
new_stack = stack
else:
# Execute the left branch
new_store = copy.deepcopy(store)
new_frame = copy.deepcopy(frame)
new_stack = copy.deepcopy(stack)
new_expr = copy.deepcopy(expr)
new_pc = pc
block_number_flag = id(
c) in global_vars.block_number_id_list or block_number_flag # set flag if "c" is associated with the block number
path_condition.append(c == 0)
recur_depth += 1
gas_cost -= bin_format.gas_cost.get(i, 0)
left_branch_res, new_stack = exec_expr(new_store, new_frame, new_stack, new_expr, new_pc)
gas_cost += bin_format.gas_cost.get(i, 0)
recur_depth -= 1
if path_abort:
path_abort = False
new_stack = copy.deepcopy(stack)
else:
branch_res += left_branch_res
if len(left_branch_res) == 1:
global_vars.add_cond_and_results(path_condition[:], left_branch_res[:])
path_condition.pop()
except TimeoutError:
raise
except Exception as e:
logger.infoln('Exception')
path_depth -= 1
solver.pop()
solver.push()
solver.add(c != 0)
find_symbolic_in_solver(solver)
logger.infoln(f'left branch ({pc}: {i})')
try:
if solver.check() == z3.unsat:
logger.infoln(f'({pc}: {i}) infeasible path detected!')
new_stack = stack
else:
# Execute the right branch
new_store = copy.deepcopy(store)
new_frame = copy.deepcopy(frame)
new_stack = copy.deepcopy(stack)
new_expr = copy.deepcopy(expr)
new_pc = spec_br(i.immediate_arguments, new_stack)
block_number_flag = True if id(
c) in global_vars.block_number_id_list else block_number_flag # set flag if "c" is associated with the block number
path_condition.append(c != 0)
recur_depth += 1
gas_cost -= bin_format.gas_cost.get(i, 0)
right_branch_res, new_stack = exec_expr(new_store, new_frame, new_stack, new_expr, new_pc)
gas_cost += bin_format.gas_cost.get(i, 0)
recur_depth -= 1
if path_abort:
if path_depth <= 0:
temp_stack = Stack()
temp_stack.add(frame)
return branch_res, temp_stack
else:
new_stack = global_vars.last_stack[-1]
else:
branch_res += right_branch_res
if len(right_branch_res) <= 1:
global_vars.add_cond_and_results(path_condition[:], right_branch_res[:])
path_condition.pop()
except TimeoutError:
raise
except Exception as e:
logger.infoln('Exception')
solver.pop()
if path_depth <= 0:
temp_stack = Stack()
temp_stack.add(frame)
return branch_res, temp_stack
global_vars.last_stack.pop()
return branch_res, new_stack
# [TODO] Ready to implement symbolic execution.
if opcode == bin_format.br_table:
a = i.immediate_arguments[0]
l = i.immediate_arguments[1]
c = stack.pop().n
if 0 <= c < len(a):
l = a[c]
pc = spec_br(l, stack)
continue
if opcode == bin_format.return_:
v = [stack.pop() for _ in range(frame.arity)][::-1]
while True:
e = stack.pop()
if isinstance(e, Frame):
stack.add(e)
break
stack.ext(v)
break
if opcode == bin_format.call:
m = store.mems[module.memaddrs[0]]
r = fake_call(module, module.funcaddrs[i.immediate_arguments], store, stack, m)
stack.ext(r)
if global_vars.flag_revert > 0:
global_vars.clear_flag_revert()
raise Exception('call eth.revert')
# store the address of the block number or block prefix
if module.funcaddrs[i.immediate_arguments] in global_vars.tapos_block_function_addr:
global_vars.add_random_number_id(id(r[0]))
# detect the send token call
if module.funcaddrs[i.immediate_arguments] in global_vars.send_token_function_addr:
check_block_dependence_old(block_number_flag)
# detect the ethereum delegate call
if module.funcaddrs[i.immediate_arguments] in global_vars.call_delegate_addr:
check_ethereum_delegate_call(expr.data[pc - 1])
# detect the ethereum greedy bug: is the function called a payable?
check_ethereum_greedy(module.funcaddrs[i.immediate_arguments])
continue
if opcode == bin_format.call_indirect:
if i.immediate_arguments[1] != 0x00:
raise Exception('Zero byte malformed in call_indirect!')
idx = stack.pop().n
tab = store.tables[module.tableaddrs[0]]
while utils.is_symbolic(idx) or idx not in range(len(tab.elem)) or tab.elem[idx] is None:
idx = randint(0, len(tab.elem) - 1)
logger.println('Invalid function index in table.')
if global_vars.location_mode:
# found transfer index!
global_vars.transfer_function_index = idx
raise SystemExit('found transfer function')
r = fake_call(module, tab.elem[idx], store, stack)
stack.ext(r)
# there may exists random number bug, therefore count the function call
if tab.elem[idx] in global_vars.tapos_block_function_addr:
global_vars.add_random_number_id(id(r[0]))
# detect the ethereum greedy bug: is the function called a payable?
check_ethereum_greedy(module.funcaddrs[i.immediate_arguments])
continue
continue
if opcode == bin_format.drop:
stack.pop()
continue