-
Notifications
You must be signed in to change notification settings - Fork 6
/
fusebmc.py
executable file
·3046 lines (2750 loc) · 134 KB
/
fusebmc.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/env python3
import os
import sys
import os.path
import xml.etree.ElementTree as ET # To parse XML
import shlex
import subprocess
import signal
import time
import resource
import re
import shutil
import glob
#from time import process_time
#from time import process_time_ns
from datetime import datetime
from random import randrange
import random
from fusebmc_util.util import *
from fusebmc_util.consts import *
from fusebmc_util.tcolors import TColors
from fusebmc_util.goaltype import GoalType
from fusebmc_util.goalinfo import GoalInfo
#from fusebmc_util.goalsorting import GoalSorting
from fusebmc_util.inputtype import InputType
from fusebmc_util.nonblockingstreamreader import NonBlockingStreamReader
from fusebmc_util.assumptions import AssumptionHolder, AssumptionParser, MetadataParser
from fusebmc_util.graph import Vertex, Graph,shortest,dijkstra
from fusebmc_util.testcov import *
from fusebmc_ml.Feature import Feature
#os.system('clear')
FUSEBMC_VERSION = 'v.4.1.14'
# This must be the first statement before other statements.
# You may only put a quoted or triple quoted string,
# Python comments, other future statements, or blank lines before the __future__ line.
'''
try:
import __builtin__
except ImportError:
#Python 3
import builtins as __builtin__
def print(*args, **kwargs):
"""My custom print() function."""
__builtin__.print('My overridden print() function!')
return __builtin__.print(*args, **kwargs)
'''
# Start time for this script
start_time = time.time()
#start_time=process_time()
property_file_content = ""
category_property = 0
#benchmark=''
property_file=''
witness_file_name=''
toWorkSourceFile=''
infinteWhileNum = 0
isConcurrency = False
map2checkWitnessFile='' # will be set later in the wrapper output
#time_out_s = 890 # 890 seconds
time_for_zipping_s = 3 # the required time for zipping folder; Can Zero ??
remaining_time_s = 0
goals_count = 0
hasInputInTestcase = False
lastInputInTestcaseCount = 0
runNumber = 1
fuSeBMC_run_id =''
#important_outs_by_ESBMC=["Chosen solver doesn\'t support floating-point numbers"]
lineNumberForNonDetCallsLst = None
funcDeclInfoLst = None
funcCallInfoLst = None
mainFuncID = -1
callGraph = None
selectiveInputsLst = None
isSelectiveInputsFromMain = True
stdCFuncsLst = []
#lineNumberForNonDetCallsLst_Map2check = None
lstAllTestcases, lstFuzzerSeeds, lstFuzzerSeeds2 = [], [], [] # [(goal_id1,assumptioLst1),(goal_id2,assumptionLst2)]
lstFuSeBMC_GoalTracerGoals, lstFuSeBMC_FuzzerGoals = [], []
nRepeatedTCs = 0
feature : Feature = None
FuSeBMCFuzzerLib_CoverBranches_Input_Covered_Goals_File = ''
FuSeBMCFuzzerLib_CoverBranches_Output_Covered_Goals_File = ''
FuSeBMCFuzzerLib_CoverBranches_Done = False
FuSeBMCFuzzerLib_CoverBranches_Max_Testcase_Size_Btyes = -1
important_outs_by_ESBMC=["Timed out","Out of memory","Chosen solver doesn\'t support floating-point numbers",
"dereference failure: forgotten memory","dereference failure: invalid pointer",
"dereference failure: Access to object out of bounds", "dereference failure: NULL pointer",
"dereference failure: invalidated dynamic object", "dereference failure: invalidated dynamic object freed",
"dereference failure: invalid pointer freed","dereference failure: free() of non-dynamic memory","array bounds violated",
"Operand of free must have zero pointer offset", "VERIFICATION FAILED", "unwinding assertion loop",
" Verifier error called", "VERIFICATION SUCCESSFUL"]
def timeOutSigHandler(signum, frame):
print(TColors.FAIL,'Timeout signal recieved',TColors.ENDC)
with open (FuSeBMCParams.WRAPPER_Output_Dir + '/.timeout.txt','w') as f:
f.write('TIME OUT...... Ha')
exit(0)
current_process_name = ''
def limit_virtual_memory():
global current_process_name
#print('pid in limit_virtual_memory =',os.getpid())
# The tuple below is of the form (soft limit, hard limit). Limit only
# the soft part so that the limit can be increased later (setting also
# the hard limit would prevent that).
# When the limit cannot be changed, setrlimit() raises ValueError.
if current_process_name == FuSeBMCProcessName.Tracer_EXE:
mem_limit = FuSeBMC_GoalTracer_MEM_LIMIT * 1024 * 1024 *1024
elif current_process_name == FuSeBMCProcessName.SeedGen:
mem_limit = FuSeBMCFuzzerLib_ERRORCALL_SEEDGEN_MEM_LIMIT * 1024 * 1024 *1024
else:
mem_limit = 5 * 1024 *1024 * 1024
try:
resource.setrlimit(resource.RLIMIT_AS, (mem_limit, resource.RLIM_INFINITY))
except: pass
try:
resource.setrlimit(resource.RLIMIT_CORE, (0 ,resource.RLIM_INFINITY))
resource.setrlimit(resource.RLIMIT_CORE, (0 ,0))
except: pass
try:
os.system('ulimit -c 0')
except: pass
#maxRSS = 0
def IsTimeOut(must_throw_ex = False):
global start_time
global remaining_time_s
#global maxRSS
#global lasttime
if FuSeBMCParams.is_ctrl_c is True: raise KeyboardInterrupt()
if FuSeBMCParams.forceStop: raise KeyboardInterrupt()
if IS_TIME_OUT_ENABLED == False: return False
#curr_gp_times = os.times()
#user=curr_gp_times[0]
#system=curr_gp_times[1]
#children_user=curr_gp_times[2]
#children_system=curr_gp_times[3]
#exec_time_s = int(user + system + children_user + children_system)
#if(exec_time_s != lasttime):
# lasttime=exec_time_s
# logText('exec_time_s=' + str(exec_time_s) + ' FuSeBMCParams.time_out_s:' + str(FuSeBMCParams.time_out_s) + '\n')
end_time = time.time()
wall_exec_time_s=(end_time - start_time)
wall_remaining_time_s= FuSeBMCParams.time_out_s - wall_exec_time_s
remaining_time_s = wall_remaining_time_s
isWallTimeout = False
if(wall_exec_time_s >= FuSeBMCParams.time_out_s):
isWallTimeout = True
if must_throw_ex:
raise MyTimeOutException()
#RUSAGE_CHILDREN
ruSelf = resource.getrusage(resource.RUSAGE_SELF)
rChild = resource.getrusage(resource.RUSAGE_CHILDREN)
cpu_exec_time_s = (ruSelf.ru_utime + ruSelf.ru_stime + rChild.ru_utime + rChild.ru_stime)
#current_RSS = ruSelf.ru_maxrss + rChild.ru_maxrss
#if(current_RSS > maxRSS):
# maxRSS = current_RSS
# print(TColors.OKGREEN,'maxRSS:',maxRSS,TColors.ENDC)
#print('cpu_exec_time_s',cpu_exec_time_s)
cpu_remaining_time_s = FuSeBMCParams.time_out_s - cpu_exec_time_s
if cpu_remaining_time_s < remaining_time_s :
remaining_time_s = cpu_remaining_time_s
isCpuTimeout = False
if(cpu_exec_time_s >= FuSeBMCParams.time_out_s):
isCpuTimeout = True
if must_throw_ex:
raise MyTimeOutException()
return isWallTimeout or isCpuTimeout
def WriteMetaDataFromWrapper():
now = datetime.now()
Meta_Data_File = FuSeBMCParams.TestSuite_Dir + '/metadata.xml'
with open(Meta_Data_File, 'w') as meta_f:
meta_f.write('<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE test-metadata PUBLIC "+//IDN sosy-lab.org//DTD test-format test-metadata 1.0//EN" "https://sosy-lab.org/test-format/test-metadata-1.0.dtd">')
meta_f.write('<test-metadata>')
meta_f.write('<entryfunction>main</entryfunction>')
meta_f.write('<specification>'+property_file_content.strip()+'</specification>')
meta_f.write('<sourcecodelang>'+'C'+'</sourcecodelang>')
_arch ='32bit'
if FuSeBMCParams.arch == 64: _arch='64bit'
meta_f.write('<architecture>'+_arch+'</architecture>')
#meta_f.write('<creationtime>2020-07-27T21:33:51.462605</creationtime>')
meta_f.write('<creationtime>'+now.strftime("%Y-%m-%dT%H:%M:%S.%f")+'</creationtime>')
meta_f.write('<programhash>'+GetSH1ForFile(FuSeBMCParams.benchmark)+'</programhash>')
meta_f.write('<producer>FuSeBMC ' + FUSEBMC_VERSION + '</producer>')
meta_f.write('<programfile>'+FuSeBMCParams.benchmark+'</programfile>')
meta_f.write('</test-metadata>')
class NonDeterministicCall(object):
def __init__(self,value):
"""
Default constructor.
Parameters
----------
value : str
String containing value from input
"""
self.inputType = InputType.unkonwn
assert(len(value) > 0)
self.value = value
def __str__(self):
return "NonDeterministicCall: VALUE: {0}".format(self.value)
@staticmethod
def extract_byte_little_endian(value):
"""
Converts an byte_extract_little_endian(%d, %d) into an value
Parameters
----------
value : str
Nondeterministic assumption
"""
PATTERN = 'byte_extract_little_endian\((.+), (.+)\)'
INT_BYTE_SIZE = 4
match = re.search(PATTERN, value)
if match == None:
return value
number = match.group(1)
index = match.group(2)
byte_value = (int(number)).to_bytes(INT_BYTE_SIZE, byteorder='little', signed=False)
return str(byte_value[int(index)])
@staticmethod
def fromAssumptionHolder(pAssumptionHolder, isFromMap2Check = False):
"""
Converts an Assumption (that is nondet, this function will not verify this) into a NonDetermisticCall
Parameters
----------
pAssumptionHolder : AssumptionHolder
Nondeterministic assumption
"""
#value = NonDeterministicCall.extract_byte_little_endian(pAssumptionHolder.varVal)
#return NonDeterministicCall(value)
if isFromMap2Check:
#assum_l,assum_r= assumption.split(' == ')
#if assum_l.find('\\')== 0: assum_l = assum_l.replace('\\','',1)
try:
_,val = pAssumptionHolder.assumption.split(' == ')
except Exception as ex:
if IS_DEBUG:
print(TColors.FAIL+ ' Error in File (fromAssumptionHolder,isFromMap2Check):'+ TColors.ENDC, FuSeBMCParams.benchmark)
val = '0'
else:
#assum_l,assum_r= assumption.split('=')
#assum_r = assum_r.replace(';','',1)
#if assum_r[-1] == "f" or assum_r[-1] == "l":
# assum_r = assum_r[:-1]
#TODO: handle f and l
#_, right = pAssumptionHolder.assumption.split("=")
#assum_l = assum_l.strip()
#assum_r = assum_r.strip()
#TODO: copy this
try:
_,val = pAssumptionHolder.assumption.split("=")
val,_ = val.split(';')
if val[-1] == "f" or val[-1] == "l":
val = val[:-1]
except Exception as ex:
if IS_DEBUG:
print(TColors.FAIL+ ' Error in File (fromAssumptionHolder):'+ TColors.ENDC, FuSeBMCParams.benchmark)
val = '0'
#return None
pass
value = NonDeterministicCall.extract_byte_little_endian(val.strip())
nonDeterministicCall = NonDeterministicCall(value)
lineNumberForNonDetCallsLst_tmp = []
if lineNumberForNonDetCallsLst is not None:
for (line,funcName) in lineNumberForNonDetCallsLst:
if pAssumptionHolder.line == line:
lineNumberForNonDetCallsLst_tmp.append((line,funcName))
lineNumberForNonDetCallsLst_tmp_len = len(lineNumberForNonDetCallsLst_tmp)
if lineNumberForNonDetCallsLst_tmp_len == 1:
(_,funcName) = lineNumberForNonDetCallsLst_tmp [0]
nonDeterministicCall.inputType = InputType.GetInputTypeForNonDetFunc(funcName)
elif lineNumberForNonDetCallsLst_tmp_len > 1:
(_,funcName) = lineNumberForNonDetCallsLst_tmp [0]
isAllEqqual = True
for (_,funcName_loop) in lineNumberForNonDetCallsLst_tmp:
if funcName != funcName_loop :
isAllEqqual = False
break
if isAllEqqual:
nonDeterministicCall.inputType = InputType.GetInputTypeForNonDetFunc(funcName)
#else:
#TODO: hanle if many nonDetFuncs in the same line; Now as unkown
return nonDeterministicCall
def debugInfo(self):
print("Nondet call: {0}".format(self.value))
class SourceCodeChecker(object):
"""
This class will read the original source file and checks if lines from assumptions contains nondeterministic calls
"""
__lines__ = None
def __init__(self, source, plstAssumptionHolder,pIsFromMap2Check = False):
"""
Default constructor.
Parameters
----------
source : str
Path to source code file (absolute/relative)
plstAssumptionHolder : [AssumptionHolder]
List containing all lstAssumptionHolder of the witness
"""
assert(os.path.isfile(source))
assert(plstAssumptionHolder is not None)
self.source = source
self.lstAssumptionHolder = plstAssumptionHolder
#self.__lines__ = None
self.isFromMap2Check = pIsFromMap2Check
@staticmethod
def loadSourceFromFile(pFile):
SourceCodeChecker.__lines__ = open(pFile, "r").readlines()
def __openfile__(self):
"""Open file in READ mode"""
SourceCodeChecker.__lines__ = open(self.source, "r").readlines()
def __is_not_repeated__(self, i):
if self.isFromMap2Check : return True
x_AssumptionHolder = self.lstAssumptionHolder[i]
y_AssumptionHolder = self.lstAssumptionHolder[i+1]
if x_AssumptionHolder.line != y_AssumptionHolder.line:
return True
try:
_, x_right = x_AssumptionHolder.assumption.split("=")
_, y_right = y_AssumptionHolder.assumption.split("=")
return x_right != y_right
except Exception as ex:
if IS_DEBUG:
print(TColors.FAIL+ 'Error in File (__is_not_repeated__):'+TColors.ENDC , FuSeBMCParams.benchmark)
return True
def __isNonDet__(self, p_AssumptionHolder):
global lineNumberForNonDetCallsLst
#global lineNumberForNonDetCallsLst_Map2check
"""
Checks if p_AssumptionHolder is nondet by checking if line contains __VERIFIER_nondet
"""
#if self.isFromMap2Check : return True
if p_AssumptionHolder is None: return False
if "=" in p_AssumptionHolder.assumption:
check_cast = p_AssumptionHolder.assumption.split("=")
if len(check_cast) > 1:
if check_cast[1].startswith(" ( struct "):
return False
if lineNumberForNonDetCallsLst is not None:
for (line,_) in lineNumberForNonDetCallsLst:
if p_AssumptionHolder.line == line: return True
return False
#print('We must not hier')
#exit(0)
if SourceCodeChecker.__lines__ is None:
self.__openfile__()
lineContent = ''
try:
lineContent = SourceCodeChecker.__lines__[p_AssumptionHolder.line - 1]
except:
pass
# At first we do not care about variable name or nondet type
# TODO: Add support to variable name
# TODO: Add support to nondet type
#print('LiNE', lineContent)
#index = lineContent.find('__VERIFIER_nondet_')
#if index >= 0:
# lineContent=lineContent.replace(';', ',')
#lineLst =[' unsigned int i', ' n=__VERIFIER_nondet_uint()', ' sn=0', '\n']
#lineLst [' unsigned long pat_len = __VERIFIER_nondet_ulong()', ' a_len = __VERIFIER_nondet_ulong()', '\n']
#lineLst=lineContent.split(',')
#print('lineLst', lineLst)
#for stmt in lineLst:
# if stmt.find('__VERIFIER_nondet_') >=0 :
# left,right = stmt.split('=');
# left = left.strip()
# left_lst = left.split(' ')
# left=left_lst[:-1]
# print('LLLLLEEEFT',left)
# return p_AssumptionHolder.varName == left
result = lineContent.split("__VERIFIER_nondet_")
return len(result) > 1
#return False
# return right != ""
"""
return list of NonDeterministicCall objects.
"""
def getNonDetAssumptions(self):
filtered_assumptions = list()
#print('self.lstAssumptionHolder',self.lstAssumptionHolder)
#if len(self.lstAssumptionHolder)==0 :
# return []
for i in range(len(self.lstAssumptionHolder)-1):
if self.__is_not_repeated__(i):
filtered_assumptions.append(self.lstAssumptionHolder[i])
if len(self.lstAssumptionHolder)>0:
filtered_assumptions.append(self.lstAssumptionHolder[-1])
return [NonDeterministicCall.fromAssumptionHolder(x,self.isFromMap2Check) for x in filtered_assumptions if not x is None and self.__isNonDet__(x)]
def debugInfo(self):
for x in self.getNonDetAssumptions(): x.debugInfo()
def __getNonDetAssumptions__(witness, source, isFromMap2Check = False):
"""
return list of NonDeterministicCall objects.
"""
assumptionParser = AssumptionParser(witness,isFromMap2Check)
assumptionParser.parse()
assumptions = assumptionParser.assumptions
return SourceCodeChecker(source, assumptions,isFromMap2Check).getNonDetAssumptions()
# error-call
def createTestFile(witness, source,testCaseFileName,isFromMap2Check = False):
global hasInputInTestcase
global lastInputInTestcaseCount
if not os.path.isfile(witness) : return
assumptions = __getNonDetAssumptions__(witness, source,isFromMap2Check)
#print('WE HAVE', len(assumptions))
assumptionsLen = len(assumptions)
if(assumptionsLen > 0):
if FuSeBMCParams.FuSeBMCFuzzerLib_ERRORCALL_ENABLED:
AddToFuzzerSeedsLst_ErrorCall(os.path.basename(testCaseFileName), assumptions)
generate_testcase_from_assumption_ErrorCall(testCaseFileName,assumptions)
#
hasInputInTestcase=True
if assumptionsLen > lastInputInTestcaseCount: lastInputInTestcaseCount = assumptionsLen
def CompileFile(fil, include_dir = '.'):
fil=os.path.abspath(fil)
if not os.path.isfile(fil):
print('FILE:',fil, 'not exists')
exit(0)
out_obj = FuSeBMCParams.WRAPPER_Output_Dir +os.sep+GenerateRondomFileName()+'.o'
cmd=[C_COMPILER,'-c',fil , '-o', out_obj,'-I'+include_dir]
runWithoutTimeoutEnabled(' '.join(cmd), FuSeBMCParams.WRAPPER_Output_Dir, True)
if not os.path.isfile(out_obj):
print('Cannot compile: ',fil)
exit(0)
def run_without_output(cmd_line, pCwd = None):
if(FuSeBMCParams.SHOW_ME_OUTPUT): print(cmd_line)
the_args = shlex.split(cmd_line)
if not pCwd is None:
_ = subprocess.run(the_args, stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,cwd=pCwd)
else:
_ = subprocess.run(the_args, stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
#p.communicate()
# Function to run esbmc
def run(cmd_line):
global category_property
global important_outs_by_ESBMC
mustReturnImportantOutput = not (category_property == Property.cover_branches or \
category_property == Property.cover_error_call)
mustSendToDevNull = mustReturnImportantOutput == False and FuSeBMCParams.SHOW_ME_OUTPUT == False
#print('mustReturnImportantOutput',mustReturnImportantOutput)
#print('mustSendToDevNull',mustSendToDevNull)
if(FuSeBMCParams.SHOW_ME_OUTPUT): print (TColors.BOLD,'\nCommand:\n', cmd_line, TColors.ENDC)
if mustReturnImportantOutput:
outs=['' for _ in range(MAX_NUM_OF_LINES_OUT)]
errs=['' for _ in range(MAX_NUM_OF_LINES_ERRS)]
important_outs=[]
important_errs=[]
index=-1;
index_err=-1
the_args = shlex.split(cmd_line)
p = None
try:
if mustSendToDevNull:
p = subprocess.Popen(the_args,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
else:
if mustReturnImportantOutput:
p = subprocess.Popen(the_args,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
else:
p = subprocess.Popen(the_args,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
#print('pid',p.pid)
if mustSendToDevNull:
while True:
IsTimeOut(True)
chpid, status, rusage = os.wait4(p.pid, os.WNOHANG)
if chpid == p.pid: break
time.sleep(1)
else:
nbsr_out = NonBlockingStreamReader(p.stdout)
if mustReturnImportantOutput:
nbsr_err = NonBlockingStreamReader(p.stderr)
while nbsr_out.hasMore():
IsTimeOut(True)
output = nbsr_out.readline(1)
if output:
try:os.wait4(p.pid, os.WNOHANG)
except ChildProcessError as cpe_ex: pass
if(FuSeBMCParams.SHOW_ME_OUTPUT):
print(output)
sys.stdout.flush()
if mustReturnImportantOutput:
index =(index + 1) % MAX_NUM_OF_LINES_OUT
isAddedToImportant=False
for out_by_ESBMC in important_outs_by_ESBMC:
if out_by_ESBMC in output:
important_outs.append(output)
isAddedToImportant=True
break
if not isAddedToImportant : outs[index]= output
else:
#IsTimeOut(True)
#time.sleep(0.1)
pass
if mustReturnImportantOutput:
while nbsr_err.hasMore():
IsTimeOut(True)
err = nbsr_err.readline(1)
if err:
try:os.wait4(p.pid, os.WNOHANG)
except ChildProcessError as cpe_ex: pass
if(FuSeBMCParams.SHOW_ME_OUTPUT): print(err)
index_err =(index_err + 1) % MAX_NUM_OF_LINES_ERRS
isAddedToImportant=False
for out_by_ESBMC in important_outs_by_ESBMC:
if out_by_ESBMC in err:
important_errs.append(err)
isAddedToImportant=True
break
if not isAddedToImportant : errs[index_err]= err
else:
#IsTimeOut(True)
#time.sleep(0.1)
pass
#(stdout, stderr) = p.communicate()
#print (stdout.decode(), stderr.decode())
#return stdout.decode()
except MyTimeOutException as e:
if p is not None:
try:
p.kill()
except Exception: pass
raise e
except KeyboardInterrupt:
FuSeBMCParams.is_ctrl_c = True
except Exception as ex: HandleException(ex,cmd_line)
#exit(0)
#getTime(p.pid)
# Kill ESBMC When Timeout (maybe)
if p is not None:
try:
p.kill()
except Exception: pass
out_str=''
if mustReturnImportantOutput:
for imp in important_errs:
out_str += imp
#Part 1
for loop in range(index_err,MAX_NUM_OF_LINES_ERRS):
out_str += errs[loop]
#part 02
for loop in range(0,index_err+1):
out_str += errs[loop]
for imp in important_outs:
out_str += imp
#Part 1
for loop in range(index,MAX_NUM_OF_LINES_OUT):
out_str += outs[loop]
#part 02
for loop in range(0,index+1):
out_str += outs[loop]
return out_str
def runWithTimeoutEnabled(cmd_line,pCwd=None,p_process_name=None):
if(FuSeBMCParams.SHOW_ME_OUTPUT): print (TColors.BOLD, '\nCommand:\n', cmd_line ,TColors.ENDC)
the_args = shlex.split(cmd_line)
p = None
is_time_out_local = False
try:
#os.system('ulimit -Sv 1400000')
#stderr=subprocess.PIPE
p = subprocess.Popen(the_args,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,cwd=pCwd,shell=False,preexec_fn=limit_virtual_memory)
#p = subprocess.Popen(' '.join(the_args),stdout=subprocess.PIPE,stderr=subprocess.STDOUT,cwd=pCwd,shell=True,preexec_fn=limit_virtual_memory)
nbsr_out = NonBlockingStreamReader(p.stdout)
#nbsr_err = NonBlockingStreamReader(p.stderr)
while nbsr_out.hasMore():
IsTimeOut(True)
output = nbsr_out.readline(1) # second 0.01
# 0.1 secs to let the shell output the result
if output:
try:os.wait4(p.pid, os.WNOHANG)
except ChildProcessError as cpe_ex: pass
if(FuSeBMCParams.SHOW_ME_OUTPUT):
print(output)
sys.stdout.flush()
else:
IsTimeOut(True)
#time.sleep(0.1)
#while nbsr_err.hasMore():
# IsTimeOut(True)
# err = nbsr_err.readline(1)
# if err:
# try:os.wait4(p.pid, os.WNOHANG)
# except ChildProcessError as cpe_ex: pass
# if(FuSeBMCParams.SHOW_ME_OUTPUT): print(err)
# else:
# IsTimeOut(True)
#time.sleep(0.1)
except MyTimeOutException: is_time_out_local = True
except KeyboardInterrupt: FuSeBMCParams.is_ctrl_c = True
except Exception as ex: HandleException(ex,cmd_line)
#print('CTRLLLLLLLLLL')
# Kill ESBMC When Timeout (maybe)
if p is not None:
try:
#if p.poll() is None: # proc still working
#os.killpg(os.getpgid(p.pid), signal.SIGTERM)
#os.killpg(os.getpgid(p.pid), signal.SIGKILL)
p.terminate()
time.sleep(0.5)
p.kill()
#print('Killed......')
except:
#print('EXXXXXXXX')
#print(ex)
pass
if is_time_out_local :
if IS_DEBUG: print('is_time_out_local is True')
raise MyTimeOutException()
def runWithoutTimeoutEnabled(cmd_line,pCwd=None,forceOutput = False):
if(forceOutput or FuSeBMCParams.SHOW_ME_OUTPUT): print (TColors.BOLD, '\nCommand:\n', cmd_line ,TColors.ENDC)
the_args = shlex.split(cmd_line)
p = None
nbsr_out = None
#nbsr_err = None
try:
#stderr=subprocess.PIPE
p = subprocess.Popen(the_args,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,cwd=pCwd,shell=False,preexec_fn=limit_virtual_memory) #bufsize=1
nbsr_out = NonBlockingStreamReader(p.stdout)
#nbsr_err = NonBlockingStreamReader(p.stderr)
while nbsr_out.hasMore():
output = nbsr_out.readline(1) # second 0.01
if output:
#try:os.wait4(p.pid, os.WNOHANG)
#except ChildProcessError as cpe_ex: pass
if(forceOutput or FuSeBMCParams.SHOW_ME_OUTPUT):
print(output)
sys.stdout.flush()
#while nbsr_err.hasMore():
# err = nbsr_err.readline(1) # 0.01
# if err:
# #try:os.wait4(p.pid, os.WNOHANG)
# #except ChildProcessError as cpe_ex: pass
# if(forceOutput or FuSeBMCParams.SHOW_ME_OUTPUT): print(err)
except KeyboardInterrupt: FuSeBMCParams.is_ctrl_c = True
if p is not None:
try:
#if p.poll() is None: # proc still working
#os.killpg(os.getpgid(p.pid), signal.SIGTERM)
#os.killpg(os.getpgid(p.pid), signal.SIGKILL)
p.terminate()
#p.send_signal(signal.CTRL_C_EVENT)
#p.send_signal(signal.SIGINT)
#p.kill()
#print('Killed......')
while nbsr_out is not None and nbsr_out.hasMore():
output = nbsr_out.readline(1) # second 0.01
if output:
if(forceOutput or FuSeBMCParams.SHOW_ME_OUTPUT): print(output)
#while nbsr_err is not None and nbsr_err.hasMore():
# err = nbsr_err.readline(1) # 0.01
# if err:
# if(forceOutput or FuSeBMCParams.SHOW_ME_OUTPUT): print(err)
except:
#print('EXXXXXXXX')
pass
def get_command_line_svcomp(strat, prop, arch, benchmark, fp_mode):
global stdCFuncsLst, isConcurrency
if prop == Property.memcleanup:
command_line = ESBMC_CONCURRENCY_EXE + ' '
else:
command_line = ESBMC_SVCOMP + ' '
FuSeBMCParams.esbmc_dargs = f"--{FuSeBMCParams.solver} --{FuSeBMCParams.encoding} --no-div-by-zero-check --force-malloc-success --state-hashing "
FuSeBMCParams.esbmc_dargs += f"--no-align-check --k-step {FuSeBMCParams.k_step} "
#added by Machine Learning
#FuSeBMCParams.esbmc_dargs += f"--unwind {FuSeBMCParams.UNWIND} "
if FuSeBMCParams.addSymexValueSets:
FuSeBMCParams.esbmc_dargs += "--add-symex-value-sets "
if FuSeBMCParams.MAX_K_STEP == -1:
FuSeBMCParams.esbmc_dargs += "--unlimited-k-steps "
else:
FuSeBMCParams.esbmc_dargs += f"--max-k-step {FuSeBMCParams.MAX_K_STEP} "
if FuSeBMCParams.UNWIND != -1:
FuSeBMCParams.esbmc_dargs += f"--unwind {FuSeBMCParams.UNWIND} "
command_line += FuSeBMCParams.esbmc_dargs
command_line += benchmark + " --quiet "
if arch == 32: command_line += "--32 "
else: command_line += "--64 "
concurrency = (category_property == Property.unreach_call) and \
(isConcurrency or len(stdCFuncsLst) > 0 )
if concurrency:
command_line += f" --no-por --context-bound {FuSeBMCParams.contextBound} --no-goto-merge "
# Special case for termination, it runs regardless of the strategy
if prop == Property.termination:
command_line += "--no-pointer-check --no-bounds-check --no-assertions "
command_line += f"--termination --max-inductive-step {FuSeBMCParams.maxInductiveStep} "
return command_line
if prop == Property.overflow:
command_line += "--no-pointer-check --no-bounds-check --overflow-check --no-assertions "
elif prop == Property.memsafety:
command_line += "--memory-leak-check --no-assertions "
#strat = "incr"
elif prop == Property.memcleanup:
command_line += "--no-pointer-check --no-bounds-check --memory-leak-check --memory-cleanup-check --no-assertions "
#strat = "incr"
elif prop == Property.unreach_call:
if concurrency:
command_line += "--no-pointer-check --no-bounds-check "
else:
command_line += "--no-pointer-check --no-bounds-check --interval-analysis --error-label ERROR --goto-unwind --unlimited-goto-unwind "
else:
print("Unknown property")
exit(1)
# Add strategy
if concurrency: # Concurrency only works with incremental
command_line += "--incremental-bmc "
elif strat == "fixed":
command_line += f"--k-induction --max-inductive-step {FuSeBMCParams.maxInductiveStep} "
elif strat == "kinduction":
command_line += f"--k-induction --max-inductive-step {FuSeBMCParams.maxInductiveStep} "
elif strat == "falsi":
command_line += "--falsification "
elif strat == "incr":
command_line += "--incremental-bmc "
else:
print("Unknown strategy")
exit(1)
return command_line
def get_command_line(strat, prop, arch, benchmark, fp_mode):
global goals_count
global runNumber
global stdCFuncsLst, isConcurrency
#if FuSeBMCParams.ML == Feature.PredicateParams or FuSeBMCParams.ML == Feature.ExtractFeaturesOnly:
strat= FuSeBMCParams.strategy
if category_property in [Property.memsafety ,Property.overflow,
Property.unreach_call,Property.termination, Property.memcleanup]:
return get_command_line_svcomp(strat, prop, arch, benchmark, fp_mode)
if isConcurrency or len(stdCFuncsLst) > 0 :
command_line = ESBMC_CONCURRENCY_EXE + ' '
else:
command_line = ESBMC_EXE + ' '
FuSeBMCParams.esbmc_dargs = f"--{FuSeBMCParams.solver} --{FuSeBMCParams.encoding} --no-div-by-zero-check --force-malloc-success --state-hashing "
FuSeBMCParams.esbmc_dargs += f"--no-align-check --k-step {FuSeBMCParams.k_step} "
FuSeBMCParams.esbmc_dargs += f"--context-bound {FuSeBMCParams.contextBound} "
FuSeBMCParams.esbmc_dargs += "--show-cex "
#FuSeBMCParams.esbmc_dargs += " --overflow-check "
command_line += FuSeBMCParams.esbmc_dargs
command_line += benchmark + " --quiet "
if arch == 32: command_line += "--32 "
else: command_line += "--64 "
if prop == Property.cover_branches:
if FuSeBMCParams.UNWIND != -1:
command_line += f"--unwind {FuSeBMCParams.UNWIND} "
if FuSeBMCParams.MAX_K_STEP == -2: #default
if(goals_count>100):
if (goals_count<250):
command_line += f"--max-k-step 30 --no-pointer-check --no-bounds-check --no-slice "
else:
command_line += f"--max-k-step 10 --no-pointer-check --no-bounds-check --no-slice "
else:#(goals_count<100)
command_line += f"--unlimited-k-steps --no-pointer-check --no-bounds-check --no-slice "
elif FuSeBMCParams.MAX_K_STEP == -1: #unlimited
command_line += f"--unlimited-k-steps --no-pointer-check --no-bounds-check --no-slice "
else:
command_line += f"--max-k-step {FuSeBMCParams.MAX_K_STEP} --no-pointer-check --no-bounds-check --no-slice "
if isConcurrency or len(stdCFuncsLst) > 0:
pass
else:
command_line += "--interval-analysis "
#20.05.2020 + #03.06.2020 kaled: adding the option "--unlimited-k-steps" for coverage_error_call .... --max-k-step 5
elif prop == Property.cover_error_call:
#kaled : 03.06.2020 --unwind 10 --partial-loops
if FuSeBMCParams.ERRORCALL_RUNTWICE_ENABLED and runNumber ==1:
command_line += "--partial-loops --no-pointer-check --no-bounds-check --no-slice "
else:
if FuSeBMCParams.MAX_K_STEP == -2 or FuSeBMCParams.MAX_K_STEP == -1 : #-2:default, -1 unlimited
command_line += "--unlimited-k-steps --no-pointer-check --no-bounds-check --no-slice "
else:
command_line += f"--max-k-step {FuSeBMCParams.MAX_K_STEP} --no-pointer-check --no-bounds-check --no-slice "
if isConcurrency or len(stdCFuncsLst) > 0:
pass
else:
command_line += "--interval-analysis "
else:
print ("Unknown property")
exit(1)
# Add strategy
if isConcurrency: # Concurrency only works with incremental
command_line += "--incremental-bmc "
elif strat == "fixed":
command_line += f"--k-induction --max-inductive-step {FuSeBMCParams.maxInductiveStep} "
elif strat == "kinduction":
#TODO: Check this
#command_line += "--bidirectional "
command_line += f"--k-induction --max-inductive-step {FuSeBMCParams.maxInductiveStep} "
elif strat == "falsi":
command_line += "--falsification "
elif strat == "incr":
command_line += "--incremental-bmc "
else:
print ("Unknown strategy")
exit(1)
#END
# if we're running in FP mode, use MathSAT
if fp_mode:
command_line += "--mathsat "
return command_line
def generate_testcase_from_assumption_ErrorCall(p_test_case_file_full,p_inst_assumptions):
inst_len = len(p_inst_assumptions)
if (inst_len > 0 ) : print(' Generate Testcase ...')
with open(p_test_case_file_full, 'w') as testcase_file:
testcase_file.write('<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n')
testcase_file.write('<!DOCTYPE testcase PUBLIC "+//IDN sosy-lab.org//DTD test-format testcase 1.0//EN" "https://sosy-lab.org/test-format/testcase-1.0.dtd">\n')
testcase_file.write('<testcase>\n')
for nonDeterministicCall in p_inst_assumptions:
cType =''
if nonDeterministicCall.inputType != InputType.unkonwn:
cType = ' type="'+InputType.GetAs_C_DataType(nonDeterministicCall.inputType)+'"'
testcase_file.write('<input'+cType+'>'+nonDeterministicCall.value +'</input>\n')
testcase_file.write('</testcase>')
#
def generate_testcase_from_assumption_CoverBranches(p_test_case_file_full,p_inst_assumptions, p_isSelectiveFuzzer = False):
#if(arch == 32)if(arch == 32)
# sys.byteorder 'little' or 'big'
inst_len = len(p_inst_assumptions)
if (inst_len > 0 ) : print(' Generate Testcase ...')
#if(inst_len > FuSeBMCFuzzerLib_CoverBranches_Max_Testcase_Size_Btyes): FuSeBMCFuzzerLib_CoverBranches_Max_Testcase_Size_Btyes = inst_len
with open(p_test_case_file_full, 'w') as testcase_file:
testcase_file.write('<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n')
testcase_file.write('<!DOCTYPE testcase PUBLIC "+//IDN sosy-lab.org//DTD test-format testcase 1.0//EN" "https://sosy-lab.org/test-format/testcase-1.0.dtd">\n')
testcase_file.write('<testcase>\n')
for nonDeterministicCall in p_inst_assumptions:
# if you want to print to std
#print(nonDeterministicCall)
cType =''
if nonDeterministicCall.inputType != InputType.unkonwn:
cType = ' type="'+InputType.GetAs_C_DataType(nonDeterministicCall.inputType)+'"'
testcase_file.write('<input'+cType+'>'+nonDeterministicCall.value +'</input>\n')
if p_isSelectiveFuzzer == False:
tracer_testcase_file = FuSeBMCParams.WRAPPER_Output_Dir + '/tracer_testcase.txt'
if(os.path.isfile(tracer_testcase_file)):
if IS_DEBUG: testcase_file.write('<!-- FuSeBMC_Tracer -->\n')
with open(tracer_testcase_file, 'r') as tracer_testcase_f:
for line in tracer_testcase_f:
testcase_file.write(line)
RemoveFileIfExists(tracer_testcase_file)
print(' Testcase is completed by FuSeBMC_Tracer...')
testcase_file.write('</testcase>')
#replace GOAL_1: with fuseGoalCalled(1);
def ReplaceGoalLabelWithFuseGoalCalledMethod(src_file, dest_file):
goalRegex = re.compile('GOAL_([0-9]+):')
with open(dest_file,'w') as fout:
if FuSeBMCParams.FuSeBMCFuzzerLib_COVERBRANCHES_ENABLED:
fout.write('unsigned int fuSeBMC_category = 2 ;\n')
#fout.write('extern void fuSeBMC_return(int code);\n')
fout.write('char * fuSeBMC_run_id = "'+fuSeBMC_run_id+'";\n')
fout.write('extern void fuseGoalCalled(int goal);\n')
fout.write('extern char * fuSeBMC_bitset_arr;\n')
fout.write('extern void fuSeBMC_init();\n')
#fout.write('extern void fuSeBMC_log_error (char * format, ...);\n')
with open(src_file,'r') as fin:
for line in fin:
if(line == '//fuSeBMC_init\n'):
line = 'fuSeBMC_init();\n'
else:
regex_result = goalRegex.match(line)
if regex_result is not None:
gl = regex_result.group(1)
#print(regex_result.string,regex_result.group(1))
line = line.replace(regex_result.string,'fuseGoalCalled('+gl+');\n')
#line = line.replace(regex_result.string, 'if(((fuSeBMC_bitset_arr)['+gl+'/8] >> '+gl+'%8) & (char)1 == (char)0)fuseGoalCalled('+gl+');\n')
#line = line.replace(regex_result.string, 'if(!((fuSeBMC_bitset_arr['+gl+'/8]) & (char)(1<<('+gl+'%8))))fuseGoalCalled('+gl+');\n')
#This
#line = line.replace(regex_result.string, 'if(fuSeBMC_bitset_arr['+gl+']==0)fuseGoalCalled('+gl+');\n')
#line = line.replace(regex_result.string,'fuSeBMC_log_error("gl=%u,val=%d\\n",'+gl+',(fuSeBMC_bitset_arr['+gl+'/8]) & (char)(1<<('+gl+'%8)));')
fout.write(line)
def getFullLibName(p_lib, p_arch, p_isConcurrency):
con = '_c' if p_isConcurrency == True else '';
return '-l'+p_lib+con+'_'+str(p_arch)
def RunAFLForCoverBranches(instrumented_afl_file):
'''
@Return lstFuSeBMC_FuzzerGoals : list of goals covered by Fuzzer.
'''
global FuSeBMCFuzzerLib_CoverBranches_Input_Covered_Goals_File ,FuSeBMCFuzzerLib_CoverBranches_Output_Covered_Goals_File
global FuSeBMCFuzzerLib_CoverBranches_Done
global lstFuzzerSeeds
global FuSeBMCFuzzerLib_CoverBranches_Max_Testcase_Size_Btyes
global lstFuSeBMC_GoalTracerGoals
global remaining_time_s
global goals_count, infinteWhileNum, selectiveInputsLst
global stdCFuncsLst, isConcurrency
FuSeBMCFuzzerLib_CoverBranches_Seed_Dir = os.path.abspath(os.path.join(FuSeBMCParams.WRAPPER_Output_Dir, 'seeds'))
MakeFolderEmptyORCreate(FuSeBMCFuzzerLib_CoverBranches_Seed_Dir)
l_seed_dir = FuSeBMCFuzzerLib_CoverBranches_Seed_Dir