forked from enzymefinance/oyente
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsymExec.py
executable file
·1568 lines (1457 loc) · 61.4 KB
/
symExec.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from z3 import *
from vargenerator import *
import tokenize
import signal
from tokenize import NUMBER, NAME, NEWLINE
from basicblock import BasicBlock
from analysis import *
from utils import *
from math import *
import time
from global_params import *
import sys
import atexit
import logging
results = {}
if len(sys.argv) >= 12:
IGNORE_EXCEPTIONS = int(sys.argv[2])
REPORT_MODE = int(sys.argv[3])
PRINT_MODE = int(sys.argv[4])
DATA_FLOW = int(sys.argv[5])
DEBUG_MODE = int(sys.argv[6])
CHECK_CONCURRENCY_FP = int(sys.argv[7])
TIMEOUT = int(sys.argv[8])
UNIT_TEST = int(sys.argv[9])
GLOBAL_TIMEOUT = int(sys.argv[10])
PRINT_PATHS = int(sys.argv[11])
if REPORT_MODE:
report_file = sys.argv[1] + '.report'
rfile = open(report_file, 'w')
count_unresolved_jumps = 0
gen = Generator() # to generate names for symbolic variables
end_ins_dict = {} # capturing the last statement of each basic block
instructions = {} # capturing all the instructions, keys are corresponding addresses
jump_type = {} # capturing the "jump type" of each basic block
vertices = {}
edges = {}
money_flow_all_paths = []
reentrancy_all_paths =[]
data_flow_all_paths = [[], []] # store all storage addresses
path_conditions = [] # store the path condition corresponding to each path in money_flow_all_paths
all_gs = [] # store global variables, e.g. storage, balance of all paths
total_no_of_paths = 0
c_name = sys.argv[1]
if(len(c_name) > 5):
c_name = c_name[4:]
set_cur_file(c_name)
# Z3 solver
solver = Solver()
solver.set("timeout", TIMEOUT)
CONSTANT_ONES_159 = BitVecVal((1 << 160) - 1, 256)
if UNIT_TEST == 1:
try:
result_file = open(sys.argv[13], 'r')
except:
if PRINT_MODE: print "Could not open result file for unit test"
exit()
log_file = open(sys.argv[1] + '.log', "w")
# A simple function to compare the end stack with the expected stack
# configurations specified in a test file
def compare_stack_unit_test(stack):
try:
size = int(result_file.readline())
content = result_file.readline().strip('\n')
if size == len(stack) and str(stack) == content:
if PRINT_MODE: print "PASSED UNIT-TEST"
else:
if PRINT_MODE: print "FAILED UNIT-TEST"
if PRINT_MODE: print "Expected size %d, Resulted size %d" % (size, len(stack))
if PRINT_MODE: print "Expected content %s \nResulted content %s" % (content, str(stack))
except Exception as e:
if PRINT_MODE: print "FAILED UNIT-TEST"
if PRINT_MODE: print e.message
def compare_storage_unit_test(global_state):
with open('result', 'w') as result_file:
key = global_state['Ia'].keys()[0]
value = str(global_state['Ia'][key])
try:
key = str(long(key))
value = str(long(value))
result_file.write(key);
result_file.write('\n')
result_file.write(value)
except:
logging.exception("Storage key or value is not a number")
exit(1)
finally:
result_file.close()
def handler(signum, frame):
raise Exception("timeout")
def main():
start = time.time()
signal.signal(signal.SIGALRM, handler)
signal.alarm(GLOBAL_TIMEOUT)
print "Running, please wait..."
print "\t============ Results ==========="
if PRINT_MODE:
print "Checking for Callstack attack..."
run_callstack_attack()
try:
build_cfg_and_analyze()
if PRINT_MODE:
print "Done Symbolic execution"
except Exception as e:
raise
print "Exception - "+str(e)
print "Time out"
signal.alarm(0)
if REPORT_MODE:
rfile.write(str(total_no_of_paths) + "\n")
detect_money_concurrency()
detect_time_dependency()
stop = time.time()
if REPORT_MODE:
rfile.write(str(stop-start))
rfile.close()
if DATA_FLOW:
detect_data_concurrency()
detect_data_money_concurrency()
if PRINT_MODE:
print "Results for Reentrancy Bug: " + str(reentrancy_all_paths)
reentrancy_bug_found = any([v for sublist in reentrancy_all_paths for v in sublist])
print "\t Reentrancy bug exists: %s" % str(reentrancy_bug_found)
results['reentrancy'] = reentrancy_bug_found
def closing_message():
print "\t====== Analysis Completed ======"
if len(sys.argv) > 12:
with open(sys.argv[12], 'w') as of:
of.write(json.dumps(results,indent=1))
print "Wrote results to %s." % sys.argv[12]
atexit.register(closing_message)
def build_cfg_and_analyze():
with open(sys.argv[1], 'r') as disasm_file:
disasm_file.readline() # Remove first line
tokens = tokenize.generate_tokens(disasm_file.readline)
collect_vertices(tokens)
construct_bb()
construct_static_edges()
full_sym_exec() # jump targets are constructed on the fly
# Detect if a money flow depends on the timestamp
def detect_time_dependency():
TIMESTAMP_VAR = "IH_s"
is_dependant = False
index = 0
if PRINT_PATHS:
print "ALL PATH CONDITIONS"
for cond in path_conditions:
index += 1
if PRINT_PATHS:
print "PATH " + str(index) + ": " + str(cond)
list_vars = []
for expr in cond:
if is_expr(expr):
list_vars += get_vars(expr)
set_vars = set(i.decl().name() for i in list_vars)
if TIMESTAMP_VAR in set_vars:
is_dependant = True
break
print "\t Time Dependency: \t %s" % is_dependant
results['time_dependency'] = is_dependant
if REPORT_MODE:
file_name = sys.argv[1].split("/")[len(sys.argv[1].split("/"))-1].split(".")[0]
report_file = file_name + '.report'
with open(report_file, 'w') as rfile:
if is_dependant:
rfile.write("yes\n")
else:
rfile.write("no\n")
# detect if two paths send money to different people
def detect_money_concurrency():
n = len(money_flow_all_paths)
for i in range(n):
if PRINT_MODE: print "Path " + str(i) + ": " + str(money_flow_all_paths[i])
if PRINT_MODE: print all_gs[i]
i = 0
false_positive = []
concurrency_paths = []
for flow in money_flow_all_paths:
i += 1
if len(flow) == 1:
continue # pass all flows which do not do anything with money
for j in range(i, n):
jflow = money_flow_all_paths[j]
if len(jflow) == 1:
continue
if is_diff(flow, jflow):
concurrency_paths.append([i-1, j])
if CHECK_CONCURRENCY_FP and \
is_false_positive(i-1, j, all_gs, path_conditions) and \
is_false_positive(j, i-1, all_gs, path_conditions):
false_positive.append([i-1, j])
# if PRINT_MODE: print "All false positive cases: ", false_positive
if PRINT_MODE: print "Concurrency in paths: ", concurrency_paths
if len(concurrency_paths) > 0:
print "\t Concurrency found in paths: %s" + str(concurrency_paths)
results['concurrency'] = True
else:
print "\t Concurrency Bug: \t False"
results['concurrency'] = False
if REPORT_MODE:
rfile.write("number of path: " + str(n) + "\n")
# number of FP detected
rfile.write(str(len(false_positive)) + "\n")
rfile.write(str(false_positive) + "\n")
# number of total races
rfile.write(str(len(concurrency_paths)) + "\n")
# all the races
rfile.write(str(concurrency_paths) + "\n")
# Detect if there is data concurrency in two different flows.
# e.g. if a flow modifies a value stored in the storage address and
# the other one reads that value in its execution
def detect_data_concurrency():
sload_flows = data_flow_all_paths[0]
sstore_flows = data_flow_all_paths[1]
concurrency_addr = []
for sflow in sstore_flows:
for addr in sflow:
for lflow in sload_flows:
if addr in lflow:
if not addr in concurrency_addr:
concurrency_addr.append(addr)
break
if PRINT_MODE: print "data conccureny in storage " + str(concurrency_addr)
# Detect if any change in a storage address will result in a different
# flow of money. Currently I implement this detection by
# considering if a path condition contains
# a variable which is a storage address.
def detect_data_money_concurrency():
n = len(money_flow_all_paths)
sstore_flows = data_flow_all_paths[1]
concurrency_addr = []
for i in range(n):
cond = path_conditions[i]
list_vars = []
for expr in cond:
list_vars += get_vars(expr)
set_vars = set(i.decl().name() for i in list_vars)
for sflow in sstore_flows:
for addr in sflow:
var_name = gen.gen_owner_store_var(addr)
if var_name in set_vars:
concurrency_addr.append(var_name)
if PRINT_MODE: print "Concurrency in data that affects money flow: " + str(set(concurrency_addr))
def print_cfg():
for block in vertices.values():
block.display()
if PRINT_MODE: print str(edges)
# 1. Parse the disassembled file
# 2. Then identify each basic block (i.e. one-in, one-out)
# 3. Store them in vertices
def collect_vertices(tokens):
current_ins_address = 0
last_ins_address = 0
is_new_line = True
current_block = 0
current_line_content = ""
wait_for_push = False
is_new_block = False
for tok_type, tok_string, (srow, scol), _, line_number in tokens:
if wait_for_push is True:
push_val = ""
for ptok_type, ptok_string, _, _, _ in tokens:
if ptok_type == NEWLINE:
is_new_line = True
current_line_content += push_val + ' '
instructions[current_ins_address] = current_line_content
if PRINT_MODE: print current_line_content
current_line_content = ""
wait_for_push = False
break
try:
int(ptok_string, 16)
push_val += ptok_string
except ValueError:
pass
continue
elif is_new_line is True and tok_type == NUMBER: # looking for a line number
last_ins_address = current_ins_address
try:
current_ins_address = int(tok_string)
except ValueError:
if PRINT_MODE: print "ERROR when parsing row %d col %d" % (srow, scol)
quit()
is_new_line = False
if is_new_block:
current_block = current_ins_address
is_new_block = False
continue
elif tok_type == NEWLINE:
is_new_line = True
if PRINT_MODE: print current_line_content
instructions[current_ins_address] = current_line_content
current_line_content = ""
continue
elif tok_type == NAME:
if tok_string == "JUMPDEST":
if not (last_ins_address in end_ins_dict):
end_ins_dict[current_block] = last_ins_address
current_block = current_ins_address
is_new_block = False
elif tok_string == "STOP" or tok_string == "RETURN" or tok_string == "SUICIDE":
jump_type[current_block] = "terminal"
end_ins_dict[current_block] = current_ins_address
elif tok_string == "JUMP":
jump_type[current_block] = "unconditional"
end_ins_dict[current_block] = current_ins_address
is_new_block = True
elif tok_string == "JUMPI":
jump_type[current_block] = "conditional"
end_ins_dict[current_block] = current_ins_address
is_new_block = True
elif tok_string.startswith('PUSH', 0):
wait_for_push = True
is_new_line = False
if tok_string != "=" and tok_string != ">":
current_line_content += tok_string + " "
if current_block not in end_ins_dict:
if PRINT_MODE: print "current block: %d" % current_block
if PRINT_MODE: print "last line: %d" % current_ins_address
end_ins_dict[current_block] = current_ins_address
if current_block not in jump_type:
jump_type[current_block] = "terminal"
for key in end_ins_dict:
if key not in jump_type:
jump_type[key] = "falls_to"
def construct_bb():
sorted_addresses = sorted(instructions.keys())
size = len(sorted_addresses)
for key in end_ins_dict:
end_address = end_ins_dict[key]
block = BasicBlock(key, end_address)
if key not in instructions: continue
block.add_instruction(instructions[key])
i = sorted_addresses.index(key) + 1
while i < size and sorted_addresses[i] <= end_address:
block.add_instruction(instructions[sorted_addresses[i]])
i += 1
block.set_block_type(jump_type[key])
vertices[key] = block
edges[key] = []
def construct_static_edges():
add_falls_to() # these edges are static
def add_falls_to():
key_list = sorted(jump_type.keys())
length = len(key_list)
for i, key in enumerate(key_list):
if jump_type[key] != "terminal" and jump_type[key] != "unconditional" and i+1 < length:
target = key_list[i+1]
edges[key].append(target)
vertices[key].set_falls_to(target)
def get_init_global_state(path_conditions_and_vars):
global_state = { "balance" : {} }
for new_var_name in ("Is", "Ia"):
if new_var_name not in path_conditions_and_vars:
new_var = BitVec(new_var_name, 256)
path_conditions_and_vars[new_var_name] = new_var
deposited_value = BitVec("Iv", 256)
path_conditions_and_vars["Iv"] = deposited_value
init_is = BitVec("init_Is", 256)
init_ia = BitVec("init_Ia", 256)
constraint = (deposited_value >= BitVecVal(0, 256))
path_conditions_and_vars["path_condition"].append(constraint)
constraint = (init_is >= deposited_value)
path_conditions_and_vars["path_condition"].append(constraint)
constraint = (init_ia >= BitVecVal(0, 256))
path_conditions_and_vars["path_condition"].append(constraint)
# update the balances of the "caller" and "callee"
global_state["balance"]["Is"] = (init_is - deposited_value)
global_state["balance"]["Ia"] = (init_ia + deposited_value)
# the state of the current current contract
global_state["Ia"] = {}
global_state["miu_i"] = 0
return global_state
def full_sym_exec():
# executing, starting from beginning
stack = []
path_conditions_and_vars = {"path_condition" : []}
visited = []
mem = {}
global_state = get_init_global_state(path_conditions_and_vars) # this is init global state for this particular execution
analysis = init_analysis()
return sym_exec_block(0, visited, stack, mem, global_state, path_conditions_and_vars, analysis)
# Symbolically executing a block from the start address
def sym_exec_block(start, visited, stack, mem, global_state, path_conditions_and_vars, analysis):
if start < 0:
if PRINT_MODE: print "ERROR: UNKNOWN JUMP ADDRESS. TERMINATING THIS PATH"
return ["ERROR"]
if PRINT_MODE: print "\nDEBUG: Reach block address %d \n" % start
if PRINT_MODE: print "STACK: " + str(stack)
if start in visited:
if PRINT_MODE: print "Seeing a loop. Terminating this path ... "
return stack
# Execute every instruction, one at a time
try:
block_ins = vertices[start].get_instructions()
except KeyError:
if PRINT_MODE: print "This path results in an exception, possibly an invalid jump address"
return ["ERROR"]
for instr in block_ins:
sym_exec_ins(start, instr, stack, mem, global_state, path_conditions_and_vars, analysis)
# Mark that this basic block in the visited blocks
visited.append(start)
# Go to next Basic Block(s)
if jump_type[start] == "terminal":
if PRINT_MODE: print "TERMINATING A PATH ..."
display_analysis(analysis)
global total_no_of_paths
total_no_of_paths += 1
reentrancy_all_paths.append(analysis["reentrancy_bug"])
if analysis["money_flow"] not in money_flow_all_paths:
money_flow_all_paths.append(analysis["money_flow"])
path_conditions.append(path_conditions_and_vars["path_condition"])
all_gs.append(copy_global_values(global_state))
if DATA_FLOW:
if analysis["sload"] not in data_flow_all_paths[0]:
data_flow_all_paths[0].append(analysis["sload"])
if analysis["sstore"] not in data_flow_all_paths[1]:
data_flow_all_paths[1].append(analysis["sstore"])
if UNIT_TEST == 1: compare_stack_unit_test(stack)
if UNIT_TEST == 2: compare_storage_unit_test(global_state)
elif jump_type[start] == "unconditional": # executing "JUMP"
successor = vertices[start].get_jump_target()
stack1 = list(stack)
mem1 = dict(mem)
global_state1 = my_copy_dict(global_state)
visited1 = list(visited)
path_conditions_and_vars1 = my_copy_dict(path_conditions_and_vars)
analysis1 = my_copy_dict(analysis)
sym_exec_block(successor, visited1, stack1, mem1, global_state1, path_conditions_and_vars1, analysis1)
elif jump_type[start] == "falls_to": # just follow to the next basic block
successor = vertices[start].get_falls_to()
stack1 = list(stack)
mem1 = dict(mem)
global_state1 = my_copy_dict(global_state)
visited1 = list(visited)
path_conditions_and_vars1 = my_copy_dict(path_conditions_and_vars)
analysis1 = my_copy_dict(analysis)
sym_exec_block(successor, visited1, stack1, mem1, global_state1, path_conditions_and_vars1, analysis1)
elif jump_type[start] == "conditional": # executing "JUMPI"
# A choice point, we proceed with depth first search
branch_expression = vertices[start].get_branch_expression()
if PRINT_MODE: print "Branch expression: " + str(branch_expression)
solver.push() # SET A BOUNDARY FOR SOLVER
solver.add(branch_expression)
try:
if solver.check() == unsat:
if PRINT_MODE: print "INFEASIBLE PATH DETECTED"
else:
left_branch = vertices[start].get_jump_target()
stack1 = list(stack)
mem1 = dict(mem)
global_state1 = my_copy_dict(global_state)
visited1 = list(visited)
path_conditions_and_vars1 = my_copy_dict(path_conditions_and_vars)
path_conditions_and_vars1["path_condition"].append(branch_expression)
analysis1 = my_copy_dict(analysis)
sym_exec_block(left_branch, visited1, stack1, mem1, global_state1, path_conditions_and_vars1, analysis1)
except Exception as e:
log_file.write(str(e))
print "Exception - "+str(e)
if not IGNORE_EXCEPTIONS:
if str(e) == "timeout":
raise e
solver.pop() # POP SOLVER CONTEXT
solver.push() # SET A BOUNDARY FOR SOLVER
negated_branch_expression = Not(branch_expression)
solver.add(negated_branch_expression)
if PRINT_MODE: print "Negated branch expression: " + str(negated_branch_expression)
try:
if solver.check() == unsat:
# Note that this check can be optimized. I.e. if the previous check succeeds,
# no need to check for the negated condition, but we can immediately go into
# the else branch
if PRINT_MODE: print "INFEASIBLE PATH DETECTED"
else:
right_branch = vertices[start].get_falls_to()
stack1 = list(stack)
mem1 = dict(mem)
global_state1 = my_copy_dict(global_state)
visited1 = list(visited)
path_conditions_and_vars1 = my_copy_dict(path_conditions_and_vars)
path_conditions_and_vars1["path_condition"].append(negated_branch_expression)
analysis1 = my_copy_dict(analysis)
sym_exec_block(right_branch, visited1, stack1, mem1, global_state1, path_conditions_and_vars1, analysis1)
except Exception as e:
log_file.write(str(e))
if str(e) == "timeout":
raise e
solver.pop() # POP SOLVER CONTEXT
else:
raise Exception('Unknown Jump-Type')
# Symbolically executing an instruction
def sym_exec_ins(start, instr, stack, mem, global_state, path_conditions_and_vars, analysis):
instr_parts = str.split(instr, ' ')
# collecting the analysis result by calling this skeletal function
# this should be done before symbolically executing the instruction,
# since SE will modify the stack and mem
update_analysis(analysis, instr_parts[0], stack, mem, global_state, path_conditions_and_vars)
if PRINT_MODE: print "=============================="
if PRINT_MODE: print "EXECUTING: " + instr
#
# 0s: Stop and Arithmetic Operations
#
if instr_parts[0] == "STOP":
return
elif instr_parts[0] == "ADD":
if len(stack) > 1:
first = stack.pop(0)
second = stack.pop(0)
# Type conversion is needed when they are mismatched
if isinstance(first, (int, long)) and not isinstance(second, (int, long)):
first = BitVecVal(first, 256)
elif not isinstance(first, (int, long)) and isinstance(second, (int, long)):
second = BitVecVal(second, 256)
computed = first + second
stack.insert(0, computed)
else:
raise ValueError('STACK underflow')
elif instr_parts[0] == "MUL":
if len(stack) > 1:
first = stack.pop(0)
second = stack.pop(0)
if isinstance(first, (int, long)) and not isinstance(second, (int, long)):
first = BitVecVal(first, 256)
elif not isinstance(first, (int, long)) and isinstance(second, (int, long)):
second = BitVecVal(second, 256)
computed = first * second
stack.insert(0, computed)
else:
raise ValueError('STACK underflow')
elif instr_parts[0] == "SUB":
if len(stack) > 1:
first = stack.pop(0)
second = stack.pop(0)
if isinstance(first, (int, long)) and not isinstance(second, (int, long)):
first = BitVecVal(first, 256)
elif not isinstance(first, (int, long)) and isinstance(second, (int, long)):
second = BitVecVal(second, 256)
computed = first - second
stack.insert(0, computed)
else:
raise ValueError('STACK underflow')
elif instr_parts[0] == "DIV":
if len(stack) > 1:
first = stack.pop(0)
second = stack.pop(0)
if isinstance(second, (int, long)):
if second == 0:
computed = 0
else:
if not isinstance(first, (int, long)):
second = BitVecVal(second, 256)
computed = first / second
else:
solver.push()
solver.add(Not(second == 0))
if solver.check() == unsat:
# it is provable that second is indeed equal to zero
computed = 0
else:
if isinstance(first, (int, long)):
first = BitVecVal(first, 256)
computed = first / second
solver.pop()
stack.insert(0, computed)
else:
raise ValueError('STACK underflow')
elif instr_parts[1] == "SDIV":
minInt = -2 ** 255
if len(stack) > 1:
first = stack.pop(0)
second = stack.pop(0)
if isinstance(second, (int, long)):
# second is not symbolic
if second == 0:
computed = 0
else:
if isinstance(first, (int, long)):
# both are not symbolic
if first == minInt and second == -1:
computed = minInt
else:
computed = first / second
else:
# first is symbolic and second is not symbolic
solver.push()
solver.add(Not(first == minInt))
if solver.check() == unsat:
# it is provable that second is indeed equal to -1
if second == -1:
computed = minInt
else:
second = BitVecVal(second, 256)
computed = first / second
else:
second = BitVecVal(second, 256)
computed = first / second
solver.pop()
else:
# second is symbolic
solver.push()
solver.add(Not(second == 0))
if solver.check() == unsat:
# it is provable that second is indeed equal to zero
computed = 0
else:
solver.push()
solver.add(Not(second == -1))
if solver.check() == unsat:
if isinstance(first, (int, long)):
# first is not symbolic and second is symbolic
if first == minInt:
computed = minInt
else:
first = BitVecVal(first, 256)
computed = first / second
else:
# both are symbolic
solver.push()
solver.add(Not(first == minInt))
if solver.check() == unsat:
computed == minInt
else:
computed = first / second
solver.pop()
else:
if isinstance(first, (int, long)):
first = BitVecVal(first, 256)
computed = first / second
solver.pop()
solver.pop()
stack.insert(0, computed)
else:
raise ValueError('STACK underflow')
elif instr_parts[0] == "MOD":
if len(stack) > 1:
first = stack.pop(0)
second = stack.pop(0)
if isinstance(second, (int, long)):
if second == 0:
computed = 0
else:
if not isinstance(first, (int, long)):
second = BitVecVal(second, 256) # Make second a bitvector
computed = first % second
else:
solver.push()
solver.add(Not(second == 0))
if solver.check() == unsat:
# it is provable that second is indeed equal to zero
computed = 0
else:
if isinstance(first, (int, long)):
first = BitVecVal(first, 256) # Make first a bitvector
computed = first % second
solver.pop()
stack.insert(0, computed)
else:
raise ValueError('STACK underflow')
elif instr_parts[0] == "SMOD":
if len(stack) > 1:
first = stack.pop(0)
second = stack.pop(0)
if isinstance(second, (int, long)):
if second == 0:
computed = 0
else:
if not isinstance(first, (int, long)):
second = BitVecVal(second, 256) # Make second a bitvector
computed = first % second # This is not yet faithful
else:
solver.push()
solver.add(Not(second == 0))
if solver.check() == unsat:
# it is provable that second is indeed equal to zero
computed = 0
else:
if isinstance(first, (int, long)):
first = BitVecVal(first, 256) # Make first a bitvector
computed = first % second # This is not yet faithful
solver.pop()
stack.insert(0, computed)
else:
raise ValueError('STACK underflow')
elif instr_parts[0] == "ADDMOD":
if len(stack) > 2:
first = stack.pop(0)
second = stack.pop(0)
third = stack.pop(0)
if isinstance(third, (int, long)):
if third == 0:
computed = 0
else:
if not (isinstance(first, (int, long)) and isinstance(second, (int, long))):
# there is one guy that is a symbolic expression
third = BitVecVal(third, 256)
if isinstance(first, (int, long)):
first = BitVecVal(first, 256)
if isinstance(second, (int, long)):
second = BitVecVal(second, 256)
computed = (first + second) % third
else:
solver.push()
solver.add(Not(third == 0))
if solver.check() == unsat:
# it is provable that second is indeed equal to zero
computed = 0
else:
if isinstance(first, (int, long)):
first = BitVecVal(first, 256)
if isinstance(second, (int, long)):
second = BitVecVal(second, 256)
computed = (first + second) % third
solver.pop()
stack.insert(0, computed)
else:
raise ValueError('STACK underflow')
elif instr_parts[0] == "MULMOD":
if len(stack) > 2:
first = stack.pop(0)
second = stack.pop(0)
third = stack.pop(0)
if isinstance(third, (int, long)):
if third == 0:
computed = 0
else:
if not (isinstance(first, (int, long)) and isinstance(second, (int, long))):
# there is one guy that is a symbolic expression
third = BitVecVal(third, 256)
if isinstance(first, (int, long)):
first = BitVecVal(first, 256)
if isinstance(second, (int, long)):
second = BitVecVal(second, 256)
computed = (first * second) % third
else:
solver.push()
solver.add(Not(third == 0))
if solver.check() == unsat:
# it is provable that second is indeed equal to zero
computed = 0
else:
if isinstance(first, (int, long)):
first = BitVecVal(first, 256)
if isinstance(second, (int, long)):
second = BitVecVal(second, 256)
computed = (first * second) % third
solver.pop()
stack.insert(0, computed)
else:
raise ValueError('STACK underflow')
elif instr_parts[0] == "EXP":
if len(stack) > 1:
base = stack.pop(0)
exponent = stack.pop(0)
# Type conversion is needed when they are mismatched
if isinstance(base, (int, long)) and isinstance(exponent, (int, long)):
computed = base ** exponent
else:
# The computed value is unknown, this is because power is
# not supported in bit-vector theory
new_var_name = gen.gen_arbitrary_var()
computed = BitVec(new_var_name, 256)
stack.insert(0, computed)
else:
raise ValueError('STACK underflow')
elif instr_parts[0] == "SIGNEXTEND":
if len(stack) > 1:
index = stack.pop(0)
content = stack.pop(0)
new_var_name = gen.gen_arbitrary_var()
new_var = BitVec(new_var_name, 256)
path_conditions_and_vars[new_var_name] = new_var
stack.insert(0, new_var)
'''
if isinstance(index, (int, long)):
t = 256 - 8 * (index + 1)
if isinstance(content, (int, long)):
# TODO
else:
for i in range(0, 255):
else:
# DON'T KNOW WHAT could be the resulting value
# we then create a new symbolic variable
'''
else:
raise ValueError('STACK underflow')
#
# 10s: Comparison and Bitwise Logic Operations
#
elif instr_parts[0] == "LT":
if len(stack) > 1:
first = stack.pop(0)
second = stack.pop(0)
if isinstance(first, (int, long)) and isinstance(second, (int, long)):
if first < second:
stack.insert(0, 1)
else:
stack.insert(0, 0)
else:
sym_expression = If(ULT(first, second), BitVecVal(1, 256), BitVecVal(0, 256))
stack.insert(0, sym_expression)
else:
raise ValueError('STACK underflow')
elif instr_parts[0] == "GT":
if len(stack) > 1:
first = stack.pop(0)
second = stack.pop(0)
if isinstance(first, (int, long)) and isinstance(second, (int, long)):
if first > second:
stack.insert(0, 1)
else:
stack.insert(0, 0)
else:
sym_expression = If(UGT(first, second), BitVecVal(1, 256), BitVecVal(0, 256))
stack.insert(0, sym_expression)
else:
raise ValueError('STACK underflow')
elif instr_parts[0] == "SLT": # Not fully faithful to signed comparison
if len(stack) > 1:
first = stack.pop(0)
second = stack.pop(0)
if isinstance(first, (int, long)) and isinstance(second, (int, long)):
if first < second:
stack.insert(0, 1)
else:
stack.insert(0, 0)
else:
sym_expression = If(first < second, BitVecVal(1, 256), BitVecVal(0, 256))
stack.insert(0, sym_expression)
else:
raise ValueError('STACK underflow')
elif instr_parts[0] == "SGT": # Not fully faithful to signed comparison
if len(stack) > 1:
first = stack.pop(0)
second = stack.pop(0)
if isinstance(first, (int, long)) and isinstance(second, (int, long)):
if first > second:
stack.insert(0, 1)
else:
stack.insert(0, 0)
else:
sym_expression = If(first > second, BitVecVal(1, 256), BitVecVal(0, 256))
stack.insert(0, sym_expression)
else:
raise ValueError('STACK underflow')
elif instr_parts[0] == "EQ":
if len(stack) > 1:
first = stack.pop(0)
second = stack.pop(0)
if isinstance(first, (int, long)) and isinstance(second, (int, long)):
if first == second:
stack.insert(0, 1)
else:
stack.insert(0, 0)
else:
sym_expression = If(first == second, BitVecVal(1, 256), BitVecVal(0, 256))
stack.insert(0, sym_expression)
else:
raise ValueError('STACK underflow')
elif instr_parts[0] == "ISZERO":
# Tricky: this instruction works on both boolean and integer,
# when we have a symbolic expression, type error might occur
# Currently handled by try and catch
if len(stack) > 0:
first = stack.pop(0)
if isinstance(first, (int, long)):
if first == 0:
stack.insert(0, 1)
else:
stack.insert(0, 0)
else:
sym_expression = If(first == 0, BitVecVal(1, 256), BitVecVal(0, 256))
stack.insert(0, sym_expression)
else:
raise ValueError('STACK underflow')
elif instr_parts[0] == "AND":
if len(stack) > 1:
first = stack.pop(0)
second = stack.pop(0)
computed = first & second
stack.insert(0, computed)
else:
raise ValueError('STACK underflow')
elif instr_parts[0] == "OR":
if len(stack) > 1:
first = stack.pop(0)
second = stack.pop(0)
computed = first | second
stack.insert(0, computed)
else:
raise ValueError('STACK underflow')
elif instr_parts[0] == "XOR":
if len(stack) > 1:
first = stack.pop(0)
second = stack.pop(0)
computed = first ^ second
stack.insert(0, computed)
else:
raise ValueError('STACK underflow')
elif instr_parts[0] == "NOT":
if len(stack) > 0:
first = stack.pop(0)
if isinstance(first, (int, long)):
complement = -1 - first
stack.insert(0, complement)
else:
sym_expression = (~ first)
stack.insert(0, sym_expression)