-
Notifications
You must be signed in to change notification settings - Fork 11
/
solver.py
2214 lines (1995 loc) · 67.8 KB
/
solver.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
#
# Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)
#
# SPDX-License-Identifier: BSD-2-Clause
#
# code and classes for controlling SMT solvers, including 'fast' solvers,
# which support SMTLIB2 push/pop and are controlled by pipe, and heavyweight
# 'slow' solvers which are run once per problem on static input files.
import signal
solverlist_missing = """
This tool requires the use of an SMT solver.
This tool searches for the file '.solverlist' in the current directory and
in every parent directory up to the filesystem root.
"""
solverlist_format = """
The .solverlist format is one solver per line, e.g.
# SONOLAR is the strongest offline solver in our experiments.
SONOLAR: offline: /home/tsewell/bin/sonolar --input-format=smtlib2
# CVC4 is useful in online and offline mode.
CVC4: online: /home/tsewell/bin/cvc4 --incremental --lang smt --tlimit=5000
CVC4: offline: /home/tsewell/bin/cvc4 --lang smt
# Z3 is a useful online solver. Use of Z3 in offline mode is not recommended,
# because it produces incompatible models.
Z3 4.3: online: /home/tsewell/dev/z3-dist/build/z3 -t:2 -smt2 -in
# Z3 4.3: offline: /home/tsewell/dev/z3-dist/build/z3 -smt2 -in
N.B. only ONE online solver is needed, so Z3 is redundant in the above.
Each non-comment line is ':' separated, with this pattern:
name : online/offline/fast/slow : command
The name is used to identify the solver. The second token specifies
the solver mode. Solvers in "fast" or "online" mode must support all
interactive SMTLIB2 features including push/pop. With "slow" or "offline" mode
the solver will be executed once per query, and push/pop will not be used.
The remainder of each line is a shell command that executes the solver in
SMTLIB2 mode. For online solvers it is typically worth setting a resource
limit, after which the offline solver will be run.
The first online solver will be used. The offline solvers will be used in
parallel, by default. The set to be used in parallel can be controlled with
a strategy line e.g.:
strategy: SONOLAR all, SONOLAR hyp, CVC4 hyp
This specifies that SONOLAR and CVC4 should both be run on each hypothesis. In
addition SONOLAR will be applied to try to solve all related hypotheses at
once, which may be faster than solving them one at a time.
"""
solverlist_file = ['.solverlist']
class SolverImpl:
def __init__ (self, name, fast, args, timeout):
self.fast = fast
self.args = args
self.timeout = timeout
self.origname = name
self.mem_mode = None
if self.fast:
self.name = name + ' (online)'
else:
self.name = name + ' (offline)'
def __repr__ (self):
return 'SolverImpl (%r, %r, %r, %r)' % (self.name,
self.fast, self.args, self.timeout)
def parse_solver (bits):
import os
import sys
mode_set = ['fast', 'slow', 'online', 'offline']
if len (bits) < 3 or bits[1].lower () not in mode_set:
print 'solver.py: solver list could not be parsed'
print ' in %s' % solverlist_file[0]
print ' reading %r' % bits
print solverlist_format
sys.exit (1)
name = bits[0]
fast = (bits[1].lower () in ['fast', 'online'])
args = bits[2].split ()
assert os.path.exists (args[0]), (args[0], bits)
if not fast:
timeout = 6000
else:
timeout = 30
return SolverImpl (name, fast, args, timeout)
def find_solverlist_file ():
import os
import sys
path = os.path.abspath (os.getcwd ())
while not os.path.exists (os.path.join (path, '.solverlist')):
(parent, _) = os.path.split (path)
if parent == path:
print "solver.py: '.solverlist' missing"
print solverlist_missing
print solverlist_format
sys.exit (1)
path = parent
fname = os.path.join (path, '.solverlist')
solverlist_file[0] = fname
return fname
def get_solver_set ():
solvers = []
strategy = None
for line in open (find_solverlist_file ()):
line = line.strip ()
if not line or line.startswith ('#'):
continue
bits = [bit.strip () for bit in line.split (':', 2)]
if bits[0] == 'strategy':
[_, strat] = bits
strategy = parse_strategy (strat)
elif bits[0] == 'config':
[_, config] = bits
assert solvers
parse_config_change (config, solvers[-1])
else:
solvers.append (parse_solver (bits))
return (solvers, strategy)
def parse_strategy (strat):
solvs = strat.split (',')
strategy = []
for solv in solvs:
bits = solv.split ()
if len (bits) != 2 or bits[1] not in ['all', 'hyp']:
print "solver.py: strategy element %r" % bits
print "found in .solverlist strategy line"
print "should be [solvername, 'all' or 'hyp']"
sys.exit (1)
strategy.append (tuple (bits))
return strategy
def parse_config_change (config, solver):
for assign in config.split (','):
bits = assign.split ('=')
assert len (bits) == 2, bits
[lhs, rhs] = bits
lhs = lhs.strip ().lower ()
rhs = rhs.strip ().lower ()
if lhs == 'mem_mode':
assert rhs in ['8', '32']
solver.mem_mode = rhs
else:
assert not 'config understood', assign
def load_solver_set ():
import sys
(solvers, strategy) = get_solver_set ()
fast_solvers = [sv for sv in solvers if sv.fast]
slow_solvers = [sv for sv in solvers if not sv.fast]
slow_dict = dict ([(sv.origname, sv) for sv in slow_solvers])
if strategy == None:
strategy = [(nm, strat) for nm in slow_dict
for strat in ['all', 'hyp']]
for (nm, strat) in strategy:
if nm not in slow_dict:
print "solver.py: strategy option %r" % nm
print "found in .solverlist strategy line"
print "not an offline solver (required for parallel use)"
print "(known offline solvers %s)" % slow_dict.keys ()
sys.exit (1)
strategy = [(slow_dict[nm], strat) for (nm, strat) in strategy]
assert fast_solvers, solvers
assert slow_solvers, solvers
return (fast_solvers[0], slow_solvers[0], strategy, slow_dict.values ())
(fast_solver, slow_solver, strategy, model_strategy) = load_solver_set ()
from syntax import (Expr, fresh_name, builtinTs, true_term, false_term,
foldr1, mk_or, boolT, word32T, word8T, mk_implies, Type, get_global_wrapper)
from target_objects import structs, rodata, sections, trace, printout
from logic import mk_align_valid_ineq, pvalid_assertion1, pvalid_assertion2
import syntax
import subprocess
import sys
import resource
import re
import random
import time
import tempfile
import os
last_solver = [None]
last_10_models = []
last_satisfiable_hyps = [None]
last_hyps = [None]
last_check_model_state = [None]
inconsistent_hyps = []
active_solvers = []
max_active_solvers = [5]
random_name = random.randrange (1, 10 ** 9)
count = [0]
save_solv_example_time = [-1]
def save_solv_example (solv, last_msgs, comments = []):
count[0] += 1
name = 'ex_%d_%d' % (random_name, count[0])
f = open ('smt_examples/' + name, 'w')
for msg in comments:
f.write ('; ' + msg + '\n')
solv.write_solv_script (f, last_msgs)
f.close ()
def write_last_solv_script (solv, fname):
f = open (fname, 'w')
hyps = last_hyps[0]
cmds = ['(assert %s)' % hyp for (hyp, _) in hyps] + ['(check-sat)']
solv.write_solv_script (f, cmds)
f.close ()
def run_time (elapsed, proc):
user = None
sys = None
try:
import psutil
ps = psutil.Process (proc.pid)
ps_time = ps.cpu_times ()
user = ps_time.user
sys = ps_time.system
if elapsed == None:
elapsed = time.time () - ps.create_time ()
except ImportError, e:
return '(cannot import psutil, cannot time solver)'
except Exception, e:
pass
times = ['%.2fs %s' % (t, msg)
for (t, msg) in zip ([elapsed, user, sys],
['elapsed', 'user', 'sys'])
if t != None]
if not times:
return '(unknown time)'
else:
return '(%s)' % ', '.join (times)
def smt_typ (typ):
if typ.kind == 'Word':
return '(_ BitVec %d)' % typ.num
elif typ.kind == 'WordArray':
return '(Array (_ BitVec %d) (_ BitVec %d))' % tuple (typ.nums)
elif typ.kind == 'TokenWords':
return '(Array (_ BitVec %d) (_ BitVec %d))' % (
token_smt_typ.num, typ.num)
return smt_typ_builtins[typ.name]
token_smt_typ = syntax.word64T
smt_typ_builtins = {'Bool':'Bool', 'Mem':'{MemSort}', 'Dom':'{MemDomSort}',
'Token': smt_typ (token_smt_typ)}
smt_typs_omitted = set ([builtinTs['HTD'], builtinTs['PMS']])
smt_ops = dict (syntax.ops_to_smt)
# these additional smt ops aren't used as keywords in the syntax
more_smt_ops = {
'TokenWordsAccess': 'select', 'TokenWordsUpdate': 'store'
}
smt_ops.update (more_smt_ops)
def smt_num (num, bits):
if num < 0:
return '(bvneg %s)' % smt_num (- num, bits)
if bits % 4 == 0:
digs = bits / 4
rep = '%x' % num
prefix = '#x'
else:
digs = bits
rep = '{x:b}'.format (x = num)
prefix = '#b'
rep = rep[-digs:]
rep = ('0' * (digs - len(rep))) + rep
assert len (rep) == digs
return prefix + rep
def smt_num_t (num, typ):
assert typ.kind == 'Word', typ
return smt_num (num, typ.num)
def mk_smt_expr (smt_expr, typ):
return Expr ('SMTExpr', typ, val = smt_expr)
class EnvMiss (Exception):
def __init__ (self, name, typ):
self.name = name
self.typ = typ
cheat_mem_doms = [True]
tokens = {}
def smt_expr (expr, env, solv):
if expr.is_op (['WordCast', 'WordCastSigned']):
[v] = expr.vals
assert v.typ.kind == 'Word' and expr.typ.kind == 'Word'
ex = smt_expr (v, env, solv)
if expr.typ == v.typ:
return ex
elif expr.typ.num < v.typ.num:
return '((_ extract %d 0) %s)' % (expr.typ.num - 1, ex)
else:
if expr.name == 'WordCast':
return '((_ zero_extend %d) %s)' % (
expr.typ.num - v.typ.num, ex)
else:
return '((_ sign_extend %d) %s)' % (
expr.typ.num - v.typ.num, ex)
elif expr.is_op (['ToFloatingPoint', 'ToFloatingPointSigned',
'ToFloatingPointUnsigned', 'FloatingPointCast']):
ks = [v.typ.kind for v in expr.vals]
expected_ks = {'ToFloatingPoint': ['Word'],
'ToFloatingPointSigned': ['Builtin', 'Word'],
'ToFloatingPointUnsigned': ['Builtin', 'Word'],
'FloatingPointCast': ['FloatingPoint']}
expected_ks = expected_ks[expr.name]
assert ks == expected_ks, (ks, expected_ks)
oname = 'to_fp'
if expr.name == 'ToFloatingPointUnsigned':
expr.name == 'to_fp_unsigned'
op = '(_ %s %d %d)' % tuple ([oname + expr.typ.nums])
vs = [smt_expr (v, env, solv) for v in expr.vals]
return '(%s %s)' % (op, ' '.join (vs))
elif expr.is_op (['CountLeadingZeroes', 'WordReverse']):
[v] = expr.vals
assert expr.typ.kind == 'Word' and expr.typ == v.typ
v = smt_expr (v, env, solv)
oper = solv.get_smt_derived_oper (expr.name, expr.typ.num)
return '(%s %s)' % (oper, v)
elif expr.is_op ('CountTrailingZeroes'):
[v] = expr.vals
expr = syntax.mk_clz (syntax.mk_word_reverse (v))
return smt_expr (expr, env, solv)
elif expr.is_op (['PValid', 'PGlobalValid',
'PWeakValid', 'PArrayValid']):
if expr.name == 'PArrayValid':
[htd, typ_expr, p, num] = expr.vals
num = to_smt_expr (num, env, solv)
else:
[htd, typ_expr, p] = expr.vals
assert typ_expr.kind == 'Type'
typ = typ_expr.val
if expr.name == 'PGlobalValid':
typ = get_global_wrapper (typ)
if expr.name == 'PArrayValid':
typ = ('Array', typ, num)
else:
typ = ('Type', typ)
assert htd.kind == 'Var'
htd_s = env[(htd.name, htd.typ)]
p_s = smt_expr (p, env, solv)
var = solv.add_pvalids (htd_s, typ, p_s, expr.name)
return var
elif expr.is_op ('MemDom'):
[p, dom] = [smt_expr (e, env, solv) for e in expr.vals]
md = '(%s %s %s)' % (smt_ops[expr.name], p, dom)
solv.note_mem_dom (p, dom, md)
if cheat_mem_doms:
return 'true'
return md
elif expr.is_op ('MemUpdate'):
[m, p, v] = expr.vals
assert v.typ.kind == 'Word'
m_s = smt_expr (m, env, solv)
p_s = smt_expr (p, env, solv)
v_s = smt_expr (v, env, solv)
return smt_expr_memupd (m_s, p_s, v_s, v.typ, solv)
elif expr.is_op ('MemAcc'):
[m, p] = expr.vals
assert expr.typ.kind == 'Word'
m_s = smt_expr (m, env, solv)
p_s = smt_expr (p, env, solv)
return smt_expr_memacc (m_s, p_s, expr.typ, solv)
elif expr.is_op ('Equals') and expr.vals[0].typ == builtinTs['Mem']:
(x, y) = [smt_expr (e, env, solv) for e in expr.vals]
if x[0] == 'SplitMem' or y[0] == 'SplitMem':
assert not 'mem equality involving split possible', (
x, y, expr)
sexp = '(mem-eq %s %s)' % (x, y)
solv.note_model_expr (sexp, boolT)
return sexp
elif expr.is_op ('Equals') and expr.vals[0].typ == word32T:
(x, y) = [smt_expr (e, env, solv) for e in expr.vals]
sexp = '(word32-eq %s %s)' % (x, y)
return sexp
elif expr.is_op ('StackEqualsImplies'):
[sp1, st1, sp2, st2] = [smt_expr (e, env, solv)
for e in expr.vals]
if sp1 == sp2 and st1 == st2:
return 'true'
assert st2[0] == 'SplitMem', (expr.vals, st2)
[_, split2, top2, bot2] = st2
if split2 != sp2:
res = solv.check_hyp_raw ('(= %s %s)' % (split2, sp2))
assert res == 'unsat', (split2, sp2, expr.vals)
eq = solv.get_stack_eq_implies (split2, top2, st1)
return '(and (= %s %s) %s)' % (sp1, sp2, eq)
elif expr.is_op ('ImpliesStackEquals'):
[sp1, st1, sp2, st2] = expr.vals
eq = solv.add_implies_stack_eq (sp1, st1, st2, env)
sp1 = smt_expr (sp1, env, solv)
sp2 = smt_expr (sp2, env, solv)
return '(and (= %s %s) %s)' % (sp1, sp2, eq)
elif expr.is_op ('IfThenElse'):
(sw, x, y) = [smt_expr (e, env, solv) for e in expr.vals]
return smt_ifthenelse (sw, x, y, solv)
elif expr.is_op ('HTDUpdate'):
var = solv.add_var ('updated_htd', expr.typ)
return var
elif expr.kind == 'Op':
vals = [smt_expr (e, env, solv) for e in expr.vals]
if vals:
sexp = '(%s %s)' % (smt_ops[expr.name], ' '.join(vals))
else:
sexp = smt_ops[expr.name]
maybe_note_model_expr (sexp, expr.typ, expr.vals, solv)
return sexp
elif expr.kind == 'Num':
return smt_num_t (expr.val, expr.typ)
elif expr.kind == 'Var':
if (expr.name, expr.typ) not in env:
trace ('Env miss for %s in smt_expr' % expr.name)
trace ('Environment is %s' % env)
raise EnvMiss (expr.name, expr.typ)
val = env[(expr.name, expr.typ)]
assert val[0] == 'SplitMem' or type(val) == str
return val
elif expr.kind == 'Invent':
var = solv.add_var ('invented', expr.typ)
return var
elif expr.kind == 'SMTExpr':
return expr.val
elif expr.kind == 'Token':
return solv.get_token (expr.name)
else:
assert not 'handled expr', expr
def smt_expr_memacc (m, p, typ, solv):
if m[0] == 'SplitMem':
p = solv.cache_large_expr (p, 'memacc_pointer', syntax.word32T)
(_, split, top, bot) = m
top_acc = smt_expr_memacc (top, p, typ, solv)
bot_acc = smt_expr_memacc (bot, p, typ, solv)
return '(ite (bvule %s %s) %s %s)' % (split, p, top_acc, bot_acc)
if typ.num in [8, 32, 64]:
sexp = '(load-word%d %s %s)' % (typ.num, m, p)
else:
assert not 'word load type supported', typ
solv.note_model_expr (p, syntax.word32T)
solv.note_model_expr (sexp, typ)
return sexp
def smt_expr_memupd (m, p, v, typ, solv):
if m[0] == 'SplitMem':
p = solv.cache_large_expr (p, 'memupd_pointer', syntax.word32T)
v = solv.cache_large_expr (v, 'memupd_val', typ)
(_, split, top, bot) = m
memT = syntax.builtinTs['Mem']
top = solv.cache_large_expr (top, 'split_mem_top', memT)
top_upd = smt_expr_memupd (top, p, v, typ, solv)
bot = solv.cache_large_expr (bot, 'split_mem_bot', memT)
bot_upd = smt_expr_memupd (bot, p, v, typ, solv)
top = '(ite (bvule %s %s) %s %s)' % (split, p, top_upd, top)
bot = '(ite (bvule %s %s) %s %s)' % (split, p, bot, bot_upd)
return ('SplitMem', split, top, bot)
elif typ.num == 8:
p = solv.cache_large_expr (p, 'memupd_pointer', syntax.word32T)
p_align = '(bvand %s #xfffffffd)' % p
solv.note_model_expr (p_align, syntax.word32T)
solv.note_model_expr ('(load-word32 %s %s)' % (m, p_align),
syntax.word32T)
return '(store-word8 %s %s %s)' % (m, p, v)
elif typ.num in [32, 64]:
solv.note_model_expr ('(load-word%d %s %s)' % (typ.num, m, p),
typ)
solv.note_model_expr (p, syntax.word32T)
return '(store-word%d %s %s %s)' % (typ.num, m, p, v)
else:
assert not 'MemUpdate word width supported', typ
def smt_ifthenelse (sw, x, y, solv):
if x[0] != 'SplitMem' and y[0] != 'SplitMem':
return '(ite %s %s %s)' % (sw, x, y)
zero = '#x00000000'
if x[0] != 'SplitMem':
(x_split, x_top, x_bot) = (zero, x, x)
else:
(_, x_split, x_top, x_bot) = x
if y[0] != 'SplitMem':
(y_split, y_top, y_bot) = (zero, y, y)
else:
(_, y_split, y_top, y_bot) = y
if x_split != y_split:
split = '(ite %s %s %s)' % (sw, x_split, y_split)
else:
split = x_split
return ('SplitMem', split,
'(ite %s %s %s)' % (sw, x_top, y_top),
'(ite %s %s %s)' % (sw, x_bot, y_bot))
def to_smt_expr (expr, env, solv):
if expr.typ == builtinTs['RelWrapper']:
vals = [to_smt_expr (v, env, solv) for v in expr.vals]
return syntax.adjust_op_vals (expr, vals)
s = smt_expr (expr, env, solv)
return mk_smt_expr (s, expr.typ)
def typ_representable (typ):
return (typ.kind == 'Word' or typ == builtinTs['Bool']
or typ == builtinTs['Token'])
def maybe_note_model_expr (sexpr, typ, subexprs, solv):
"""note this expression if values of its type can be represented
but one of the subexpression values can't be.
e.g. note (= x y) where the type of x/y is an SMT array."""
if not typ_representable (typ):
return
if all ([typ_representable (v.typ) for v in subexprs]):
return
assert solv, (sexpr, typ)
solv.note_model_expr (sexpr, typ)
def split_hyp_sexpr (hyp, accum):
if hyp[0] == 'and':
for h in hyp[1:]:
split_hyp_sexpr (h, accum)
elif hyp[0] == 'not' and hyp[1][0] == '=>':
(_, p, q) = hyp[1]
split_hyp_sexpr (p, accum)
split_hyp_sexpr (('not', q), accum)
elif hyp[0] == 'not' and hyp[1][0] == 'or':
for h in hyp[1][1:]:
split_hyp_sexpr (('not', h), accum)
elif hyp[0] == 'not' and hyp[1][0] == 'not':
split_hyp_sexpr (hyp[1][1], accum)
elif hyp[:1] + hyp[2:] == ('=>', 'false'):
split_hyp_sexpr (('not', hyp[1]), accum)
elif hyp[:1] == ('=', ) and ('true' in hyp or 'false' in hyp):
(_, p, q) = hyp
if q in ['true', 'false']:
(p, q) = (q, p)
if p == 'true':
split_hyp_sexpr (q, accum)
else:
split_hyp_sexpr (('not', q), accum)
else:
accum.append (hyp)
return accum
def split_hyp (hyp):
if (hyp.startswith ('(and ') or hyp.startswith ('(not (=> ')
or hyp.startswith ('(not (or ')
or hyp.startswith ('(not (not ')):
return [flat_s_expression (h) for h in
split_hyp_sexpr (parse_s_expression (hyp), [])]
else:
return [hyp]
mem_word8_preamble = [
'''(define-fun load-word32 ((m {MemSort}) (p (_ BitVec 32)))
(_ BitVec 32)
(concat (concat (select m (bvadd p #x00000003)) (select m (bvadd p #x00000002)))
(concat (select m (bvadd p #x00000001)) (select m p))))
''',
'''(define-fun load-word64 ((m {MemSort}) (p (_ BitVec 32)))
(_ BitVec 64)
(bvor ((_ zero_extend 32) (load-word32 m p))
(bvshl ((_ zero_extend 32)
(load-word32 m (bvadd p #x00000004))) #x0000000000000020)))''',
'''(define-fun store-word32 ((m {MemSort}) (p (_ BitVec 32))
(v (_ BitVec 32))) {MemSort}
(store (store (store (store m p ((_ extract 7 0) v))
(bvadd p #x00000001) ((_ extract 15 8) v))
(bvadd p #x00000002) ((_ extract 23 16) v))
(bvadd p #x00000003) ((_ extract 31 24) v))
) ''',
'''(define-fun store-word64 ((m {MemSort}) (p (_ BitVec 32)) (v (_ BitVec 64)))
{MemSort}
(store-word32 (store-word32 m p ((_ extract 31 0) v))
(bvadd p #x00000004) ((_ extract 63 32) v)))''',
'''(define-fun load-word8 ((m {MemSort}) (p (_ BitVec 32))) (_ BitVec 8)
(select m p))''',
'''(define-fun store-word8 ((m {MemSort}) (p (_ BitVec 32)) (v (_ BitVec 8)))
{MemSort}
(store m p v))''',
'''(define-fun mem-dom ((p (_ BitVec 32)) (d {MemDomSort})) Bool
(not (= (select d p) #b0)))''',
'''(define-fun mem-eq ((x {MemSort}) (y {MemSort})) Bool (= x y))''',
'''(define-fun word32-eq ((x (_ BitVec 32)) (y (_ BitVec 32)))
Bool (= x y))''',
'''(define-fun word2-xor-scramble ((a (_ BitVec 2)) (x (_ BitVec 2))
(b (_ BitVec 2)) (c (_ BitVec 2)) (y (_ BitVec 2)) (d (_ BitVec 2))) Bool
(bvult (bvadd (bvxor a x) b) (bvadd (bvxor c y) d)))''',
'''(declare-fun unspecified-precond () Bool)''',
]
mem_word32_preamble = [
'''(define-fun load-word32 ((m {MemSort}) (p (_ BitVec 32)))
(_ BitVec 32)
(select m ((_ extract 31 2) p)))''',
'''(define-fun store-word32 ((m {MemSort}) (p (_ BitVec 32)) (v (_ BitVec 32)))
{MemSort}
(store m ((_ extract 31 2) p) v))''',
'''(define-fun load-word64 ((m {MemSort}) (p (_ BitVec 32)))
(_ BitVec 64)
(bvor ((_ zero_extend 32) (load-word32 m p))
(bvshl ((_ zero_extend 32)
(load-word32 m (bvadd p #x00000004))) #x0000000000000020)))''',
'''(define-fun store-word64 ((m {MemSort}) (p (_ BitVec 32)) (v (_ BitVec 64)))
{MemSort}
(store-word32 (store-word32 m p ((_ extract 31 0) v))
(bvadd p #x00000004) ((_ extract 63 32) v)))''',
'''(define-fun word8-shift ((p (_ BitVec 32))) (_ BitVec 32)
(bvshl ((_ zero_extend 30) ((_ extract 1 0) p)) #x00000003))''',
'''(define-fun word8-get ((p (_ BitVec 32)) (x (_ BitVec 32))) (_ BitVec 8)
((_ extract 7 0) (bvlshr x (word8-shift p))))''',
'''(define-fun load-word8 ((m {MemSort}) (p (_ BitVec 32))) (_ BitVec 8)
(word8-get p (load-word32 m p)))''',
'''(define-fun word8-put ((p (_ BitVec 32)) (x (_ BitVec 32)) (y (_ BitVec 8)))
(_ BitVec 32) (bvor (bvshl ((_ zero_extend 24) y) (word8-shift p))
(bvand x (bvnot (bvshl #x000000FF (word8-shift p))))))''',
'''(define-fun store-word8 ((m {MemSort}) (p (_ BitVec 32)) (v (_ BitVec 8)))
{MemSort}
(store-word32 m p (word8-put p (load-word32 m p) v)))''',
'''(define-fun mem-dom ((p (_ BitVec 32)) (d {MemDomSort})) Bool
(not (= (select d p) #b0)))''',
'''(define-fun mem-eq ((x {MemSort}) (y {MemSort})) Bool (= x y))''',
'''(define-fun word32-eq ((x (_ BitVec 32)) (y (_ BitVec 32)))
Bool (= x y))''',
'''(define-fun word2-xor-scramble ((a (_ BitVec 2)) (x (_ BitVec 2))
(b (_ BitVec 2)) (c (_ BitVec 2)) (y (_ BitVec 2)) (d (_ BitVec 2))) Bool
(bvult (bvadd (bvxor a x) b) (bvadd (bvxor c y) d)))''',
'''(declare-fun unspecified-precond () Bool)'''
]
word32_smt_convs = {'MemSort': '(Array (_ BitVec 30) (_ BitVec 32))',
'MemDomSort': '(Array (_ BitVec 32) (_ BitVec 1))'}
word8_smt_convs = {'MemSort': '(Array (_ BitVec 32) (_ BitVec 8))',
'MemDomSort': '(Array (_ BitVec 32) (_ BitVec 1))'}
def preexec (timeout):
def ret ():
# setting the session ID on a fork allows us to clean up
# the resulting process group, useful if running multiple
# solvers in parallel.
os.setsid ()
if timeout != None:
resource.setrlimit(resource.RLIMIT_CPU,
(timeout, timeout))
return ret
class ConversationProblem (Exception):
def __init__ (self, prompt, response):
self.prompt = prompt
self.response = response
def get_s_expression (stream, prompt):
try:
return get_s_expression_inner (stream, prompt)
except IOError, e:
raise ConversationProblem (prompt, 'IOError')
def get_s_expression_inner (stdout, prompt):
"""retreives responses from a solver until parens match"""
responses = [stdout.readline ().strip ()]
if not responses[0].startswith ('('):
bits = responses[0].split ()
if len (bits) != 1:
raise ConversationProblem (prompt, responses[0])
return bits[0]
lpars = responses[0].count ('(')
rpars = responses[0].count (')')
emps = 0
while rpars < lpars:
r = stdout.readline ().strip ()
responses.append (r)
lpars += r.count ('(')
rpars += r.count (')')
if r == '':
emps += 1
if emps >= 3:
raise ConversationProblem (prompt, responses)
else:
emps = 0
return parse_s_expressions (responses)
class SolverFailure (Exception):
def __init__ (self, msg):
self.msg = msg
def __str__ (self):
return 'SolverFailure (%r)' % self.msg
class Solver:
def __init__ (self, produce_unsat_cores = False):
self.replayable = []
self.unsat_cores = produce_unsat_cores
self.online_solver = None
self.parallel_solvers = {}
self.parallel_model_states = {}
self.names_used = {}
self.names_used_order = []
self.external_names = {}
self.name_ext = ''
self.pvalids = {}
self.ptrs = {}
self.cached_exprs = {}
self.defs = {}
self.doms = set ()
self.model_vars = set ()
self.model_exprs = {}
self.arbitrary_vars = {}
self.stack_eqs = {}
self.mem_naming = {}
self.tokens = {}
self.smt_derived_ops = {}
self.num_hyps = 0
self.last_model_acc_hyps = (None, None)
self.pvalid_doms = None
self.assertions = []
self.fast_solver = fast_solver
self.slow_solver = slow_solver
self.strategy = strategy
self.model_strategy = model_strategy
self.add_rodata_def ()
last_solver[0] = self
def preamble (self, solver_impl):
preamble = []
if solver_impl.fast:
preamble += ['(set-option :print-success true)']
preamble += [ '(set-option :produce-models true)',
'(set-logic QF_AUFBV)', ]
if self.unsat_cores:
preamble += ['(set-option :produce-unsat-cores true)']
if solver_impl.mem_mode == '8':
preamble.extend (mem_word8_preamble)
else:
preamble.extend (mem_word32_preamble)
return preamble
def startup_solver (self, use_this_solver = None):
if self not in active_solvers:
active_solvers.append (self)
while len (active_solvers) > max_active_solvers[0]:
solv = active_solvers.pop (0)
solv.close ('active solver limit')
if use_this_solver:
solver = use_this_solver
else:
solver = self.fast_solver
devnull = open (os.devnull, 'w')
self.online_solver = subprocess.Popen (solver.args,
stdin = subprocess.PIPE, stdout = subprocess.PIPE,
stderr = devnull, preexec_fn = preexec (solver.timeout))
devnull.close ()
for msg in self.preamble (solver):
self.send (msg, replay=False)
for (msg, _) in self.replayable:
self.send (msg, replay=False)
def close (self, reason = '?'):
self.close_parallel_solvers (reason = 'self.close (%s)'
% reason)
self.close_online_solver ()
def close_online_solver (self):
if self.online_solver:
self.online_solver.stdin.close()
self.online_solver.stdout.close()
self.online_solver = None
def __del__ (self):
self.close ('__del__')
def smt_name (self, name, kind = ('Var', None),
ignore_external_names = False):
name = name.replace("'", "_").replace("#", "_").replace('"', "_")
if not ignore_external_names:
name = fresh_name (name, self.external_names)
name = fresh_name (name, self.names_used, kind)
self.names_used_order.append (name)
return name
def write (self, msg):
self.online_solver.stdin.write (msg + '\n')
self.online_solver.stdin.flush()
def send_inner (self, msg, replay = True, is_model = True):
if self.online_solver == None:
self.startup_solver ()
msg = msg.format (** word32_smt_convs)
try:
self.write (msg)
response = self.online_solver.stdout.readline().strip()
except IOError, e:
raise ConversationProblem (msg, 'IOError')
if response != 'success':
raise ConversationProblem (msg, response)
def solver_loop (self, attempt):
err = None
for i in range (5):
if self.online_solver == None:
self.startup_solver ()
try:
return attempt ()
except ConversationProblem, e:
trace ('SMT conversation problem (attempt %d)'
% (i + 1))
trace ('I sent %s' % repr (e.prompt))
trace ('I got %s' % repr (e.response))
trace ('restarting solver')
self.online_solver = None
err = (e.prompt, e.response)
trace ('Repeated SMT failure, giving up.')
raise ConversationProblem (err[0], err[1])
def send (self, msg, replay = True, is_model = True):
self.solver_loop (lambda: self.send_inner (msg,
replay = replay, is_model = is_model))
if replay:
self.replayable.append ((msg, is_model))
def get_s_expression (self, prompt):
return get_s_expression (self.online_solver.stdout, prompt)
def prompt_s_expression_inner (self, prompt):
try:
self.write (prompt)
return self.get_s_expression (prompt)
except IOError, e:
raise ConversationProblem (prompt, 'IOError')
def prompt_s_expression (self, prompt):
return self.solver_loop (lambda:
self.prompt_s_expression_inner (prompt))
def hyps_sat_raw_inner (self, hyps, model, unsat_core,
recursion = False):
self.send_inner ('(push 1)', replay = False)
for hyp in hyps:
self.send_inner ('(assert %s)' % hyp, replay = False,
is_model = False)
response = self.prompt_s_expression_inner ('(check-sat)')
if response not in set (['sat', 'unknown', 'unsat', '']):
raise ConversationProblem ('(check-sat)', response)
all_ok = True
m = {}
ucs = []
if response == 'sat' and model:
all_ok = self.fetch_model (m)
if response == 'unsat' and unsat_core:
ucs = self.get_unsat_core ()
all_ok = ucs != None
self.send_inner ('(pop 1)', replay = False)
return (response, m, ucs, all_ok)
def add_var (self, name, typ, kind = 'Var',
mem_name = None,
ignore_external_names = False):
if typ in smt_typs_omitted:
# skipped. not supported by all solvers
name = self.smt_name (name, ('Ghost', typ),
ignore_external_names = ignore_external_names)
return name
name = self.smt_name (name, kind = (kind, typ),
ignore_external_names = ignore_external_names)
self.send ('(declare-fun %s () %s)' % (name, smt_typ(typ)))
if typ_representable (typ) and kind != 'Aux':
self.model_vars.add (name)
if typ == builtinTs['Mem'] and mem_name != None:
if type (mem_name) == str:
self.mem_naming[name] = mem_name
else:
(nm, prev) = mem_name
if prev[0] == 'SplitMem':
prev = 'SplitMem'
prev = parse_s_expression (prev)
self.mem_naming[name] = (nm, prev)
return name
def add_var_restr (self, name, typ, mem_name = None):
name = self.add_var (name, typ, mem_name = mem_name)
return name
def add_def (self, name, val, env, ignore_external_names = False):
kind = 'Var'
if val.typ in smt_typs_omitted:
kind = 'Ghost'
smt = smt_expr (val, env, self)
if smt[0] == 'SplitMem':
(_, split, top, bot) = smt
def add (nm, typ, smt):
val = mk_smt_expr (smt, typ)
return self.add_def (name + '_' + nm, val, {},
ignore_external_names = ignore_external_names)
split = add ('split', syntax.word32T, split)
top = add ('top', val.typ, top)
bot = add ('bot', val.typ, bot)
return ('SplitMem', split, top, bot)
name = self.smt_name (name, kind = (kind, val.typ),
ignore_external_names = ignore_external_names)
if kind == 'Ghost':
# skipped. not supported by all solvers
return name
if val.kind == 'Var':
trace ('WARNING: redef of var %r to name %s' % (val, name))
typ = smt_typ (val.typ)
self.send ('(define-fun %s () %s %s)' % (name, typ, smt))
self.defs[name] = parse_s_expression (smt)
if typ_representable (val.typ):
self.model_vars.add (name)
return name
def add_rodata_def (self):
ro_name = self.smt_name ('rodata', kind = 'Fun')
imp_ro_name = self.smt_name ('implies-rodata', kind = 'Fun')
assert ro_name == 'rodata', repr (ro_name)
assert imp_ro_name == 'implies-rodata', repr (imp_ro_name)
[rodata_data, rodata_ranges, rodata_ptrs] = rodata
if not rodata_ptrs:
assert not rodata_data
ro_def = 'true'
imp_ro_def = 'true'
else:
ro_witness = self.add_var ('rodata-witness', word32T)
ro_witness_val = self.add_var ('rodata-witness-val', word32T)
assert ro_witness == 'rodata-witness'
assert ro_witness_val == 'rodata-witness-val'
eq_vs = [(smt_num (p, 32), smt_num (v, 32))
for (p, v) in rodata_data.iteritems ()]
eq_vs.append ((ro_witness, ro_witness_val))
eqs = ['(= (load-word32 m %s) %s)' % v for v in eq_vs]
ro_def = '(and %s)' % ' \n '.join (eqs)
ro_ineqs = ['(and (bvule %s %s) (bvule %s %s))'
% (smt_num (start, 32), ro_witness,
ro_witness, smt_num (end, 32))
for (start, end) in rodata_ranges]
assns = ['(or %s)' % ' '.join (ro_ineqs),
'(= (bvand rodata-witness #x00000003) #x00000000)']
for assn in assns:
self.assert_fact_smt (assn)
imp_ro_def = eqs[-1]
self.send ('(define-fun rodata ((m %s)) Bool %s)' % (
smt_typ (builtinTs['Mem']), ro_def))
self.send ('(define-fun implies-rodata ((m %s)) Bool %s)' % (
smt_typ (builtinTs['Mem']), imp_ro_def))
def get_eq_rodata_witness (self, v):
# depends on assertion above, should probably fix this
ro_witness = mk_smt_expr ('rodata-witness', word32T)
return syntax.mk_eq (ro_witness, v)
def check_hyp_raw (self, hyp, model = None, force_solv = False,
hyp_name = None):
return self.hyps_sat_raw ([('(not %s)' % hyp, None)],
model = model, unsat_core = None,
force_solv = force_solv, hyps_name = hyp_name)
def next_hyp (self, (hyp, tag), hyp_dict):
self.num_hyps += 1
name = 'hyp%d' % self.num_hyps
hyp_dict[name] = tag
return '(! %s :named %s)' % (hyp, name)
def hyps_sat_raw (self, hyps, model = None, unsat_core = None,
force_solv = False, recursion = False,
slow_solver = None, hyps_name = None):
assert self.unsat_cores or unsat_core == None
hyp_dict = {}
raw_hyps = [(hyp2, tag) for (hyp, tag) in hyps
for hyp2 in split_hyp (hyp)]
last_hyps[0] = list (raw_hyps)