forked from diffblue/cbmc
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstring_refinement.cpp
2051 lines (1881 loc) · 69.8 KB
/
string_refinement.cpp
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
/*******************************************************************\
Module: String support via creating string constraints and progressively
instantiating the universal constraints as needed.
The procedure is described in the PASS paper at HVC'13:
"PASS: String Solving with Parameterized Array and Interval Automaton"
by Guodong Li and Indradeep Ghosh.
Author: Alberto Griggio, [email protected]
\*******************************************************************/
/// \file
/// String support via creating string constraints and progressively
/// instantiating the universal constraints as needed. The procedure is
/// described in the PASS paper at HVC'13: "PASS: String Solving with
/// Parameterized Array and Interval Automaton" by Guodong Li and Indradeep
/// Ghosh.
#include "string_refinement.h"
#include <solvers/sat/satcheck.h>
#include <stack>
#include <unordered_set>
#include <util/expr_iterator.h>
#include <util/expr_util.h>
#include <util/format_type.h>
#include <util/magic.h>
#include <util/range.h>
#include <util/simplify_expr.h>
#include "equation_symbol_mapping.h"
#include "string_constraint_instantiation.h"
#include "string_dependencies.h"
#include "string_refinement_invariant.h"
static bool is_valid_string_constraint(
messaget::mstreamt &stream,
const namespacet &ns,
const string_constraintt &constraint);
static std::optional<exprt> find_counter_example(
const namespacet &ns,
const exprt &axiom,
const symbol_exprt &var,
message_handlert &message_handler);
/// Check axioms takes the model given by the underlying solver and answers
/// whether it satisfies the string constraints.
///
/// For each string_constraint `a`:
/// * the negation of `a` is an existential formula `b`;
/// * we substituted symbols in `b` by their values found in `get`;
/// * arrays are concretized, meaning we attribute a value for characters that
/// are unknown to get, for details see substitute_array_access;
/// * `b` is simplified and array accesses are replaced by expressions
/// without arrays;
/// * we give lemma `b` to a fresh solver;
/// * if no counter-example to `b` is found, this means the constraint `a`
/// is satisfied by the valuation given by get.
/// \return `true` if the current model satisfies all the axioms, `false`
/// otherwise with a list of lemmas which are obtained by instantiating
/// constraints at indexes given by counter-examples.
static std::pair<bool, std::vector<exprt>> check_axioms(
const string_axiomst &axioms,
string_constraint_generatort &generator,
const std::function<exprt(const exprt &)> &get,
messaget::mstreamt &stream,
const namespacet &ns,
bool use_counter_example,
const union_find_replacet &symbol_resolve,
const std::unordered_map<string_not_contains_constraintt, symbol_exprt>
¬_contain_witnesses);
static void initial_index_set(
index_set_pairt &index_set,
const namespacet &ns,
const string_constraintt &axiom);
static void initial_index_set(
index_set_pairt &index_set,
const namespacet &ns,
const string_not_contains_constraintt &axiom);
static void initial_index_set(
index_set_pairt &index_set,
const namespacet &ns,
const string_axiomst &axioms);
exprt simplify_sum(const exprt &f);
static void update_index_set(
index_set_pairt &index_set,
const namespacet &ns,
const std::vector<exprt> ¤t_constraints);
static void update_index_set(
index_set_pairt &index_set,
const namespacet &ns,
const exprt &formula);
static std::vector<exprt> instantiate(
const string_not_contains_constraintt &axiom,
const index_set_pairt &index_set,
const std::unordered_map<string_not_contains_constraintt, symbol_exprt>
&witnesses);
static std::optional<exprt> get_array(
const std::function<exprt(const exprt &)> &super_get,
const namespacet &ns,
messaget::mstreamt &stream,
const array_string_exprt &arr,
const array_poolt &array_pool);
static std::optional<exprt> substitute_array_access(
const index_exprt &index_expr,
symbol_generatort &symbol_generator,
const bool left_propagate);
/// Convert index-value map to a vector of values. If a value for an
/// index is not defined, set it to the value referenced by the next higher
/// index.
/// The length of the resulting vector is the key of the map's
/// last element + 1
/// \param index_value: map containing values of specific vector cells
/// \return Vector containing values as described in the map
template <typename T>
static std::vector<T>
fill_in_map_as_vector(const std::map<std::size_t, T> &index_value)
{
std::vector<T> result;
if(!index_value.empty())
{
result.resize(index_value.rbegin()->first + 1);
for(auto it = index_value.rbegin(); it != index_value.rend(); ++it)
{
const std::size_t index = it->first;
const T &value = it->second;
const auto next = std::next(it);
const std::size_t leftmost_index_to_pad =
next != index_value.rend() ? next->first + 1 : 0;
for(std::size_t j = leftmost_index_to_pad; j <= index; j++)
result[j] = value;
}
}
return result;
}
static bool validate(const string_refinementt::infot &info)
{
PRECONDITION(info.ns);
PRECONDITION(info.prop);
return true;
}
string_refinementt::string_refinementt(const infot &info, bool)
: supert(info),
config_(info),
loop_bound_(info.refinement_bound),
generator(*info.ns, *info.message_handler)
{
}
string_refinementt::string_refinementt(const infot &info)
: string_refinementt(info, validate(info))
{
}
/// Write index set to the given stream, use for debugging
static void
display_index_set(messaget::mstreamt &stream, const index_set_pairt &index_set)
{
std::size_t count = 0;
std::size_t count_current = 0;
for(const auto &i : index_set.cumulative)
{
const exprt &s = i.first;
stream << "IS(" << format(s) << ")=={" << messaget::eom;
for(const auto &j : i.second)
{
const auto it = index_set.current.find(i.first);
if(
it != index_set.current.end() && it->second.find(j) != it->second.end())
{
count_current++;
stream << "**";
}
stream << " " << format(j) << ";" << messaget::eom;
count++;
}
stream << "}" << messaget::eom;
}
stream << count << " elements in index set (" << count_current
<< " newly added)" << messaget::eom;
}
/// Instantiation of all constraints
///
/// The string refinement decision procedure works with two types of quantified
/// axioms, which are of the form \f$\forall x.\ P(x)\f$ (`string_constraintt`)
/// or of the form
/// \f$\forall x. P(x) \Rightarrow \exists y .s_0[x+y] \ne s_1[y] \f$
/// (`string_not_contains_constraintt`).
/// They are instantiated in a way which depends on their form:
/// * For formulas of the form \f$\forall x.\ P(x)\f$ if string `str`
/// appears in `P` indexed by some `f(x)` and `val` is in
/// the index set of `str` we find `y` such that `f(y)=val` and
/// add lemma `P(y)`.
/// (See <tt>instantiate(messaget::mstreamt&, const string_constraintt&,
/// const exprt &, const exprt&)</tt> for details.)
/// * For formulas of the form
/// \f$\forall x. P(x) \Rightarrow \exists y .s_0[x+y] \ne s_1[y]) \f$ we
/// need to look at the index set of both `s_0` and `s_1`.
/// (See <tt>instantiate(const string_not_contains_constraintt&,
/// const index_set_pairt&,
/// const std::map<string_not_contains_constraintt, symbol_exprt>&)</tt>
/// for details.)
static std::vector<exprt> generate_instantiations(
const index_set_pairt &index_set,
const string_axiomst &axioms,
const std::unordered_map<string_not_contains_constraintt, symbol_exprt>
¬_contain_witnesses)
{
std::vector<exprt> lemmas;
for(const auto &i : index_set.current)
{
for(const auto &univ_axiom : axioms.universal)
{
for(const auto &j : i.second)
lemmas.push_back(instantiate(univ_axiom, i.first, j));
}
}
for(const auto &nc_axiom : axioms.not_contains)
{
for(const auto &instance :
instantiate(nc_axiom, index_set, not_contain_witnesses))
lemmas.push_back(instance);
}
return lemmas;
}
/// If \p expr is an equation whose right-hand-side is a
/// associate_array_to_pointer call, add the correspondence and replace the call
/// by an expression representing its result.
static void make_char_array_pointer_associations(
string_constraint_generatort &generator,
exprt &expr)
{
if(const auto equal_expr = expr_try_dynamic_cast<equal_exprt>(expr))
{
if(
const auto fun_app = expr_try_dynamic_cast<function_application_exprt>(
as_const(equal_expr->rhs())))
{
const auto new_equation =
generator.make_array_pointer_association(equal_expr->lhs(), *fun_app);
if(new_equation)
{
expr =
equal_exprt{from_integer(true, new_equation->type()), *new_equation};
}
}
}
}
/// Substitute sub-expressions in equation by representative elements of
/// `symbol_resolve` whenever possible.
/// Similar to `symbol_resolve.replace_expr` but doesn't mutate the expression
/// and returns the transformed expression instead.
static exprt
replace_expr_copy(const union_find_replacet &symbol_resolve, exprt expr)
{
symbol_resolve.replace_expr(expr);
return expr;
}
/// Record the constraints to ensure that the expression is true when
/// the boolean is true and false otherwise.
/// \param expr: an expression of type `bool`
/// \param value: the boolean value to set it to
void string_refinementt::set_to(const exprt &expr, bool value)
{
PRECONDITION(expr.is_boolean());
PRECONDITION(equality_propagation);
if(!value)
equations.push_back(not_exprt{expr});
else
equations.push_back(expr);
}
/// Add association for each char pointer in the equation
/// \param [in,out] symbol_solver: a union_find_replacet object to keep track of
/// char pointer equations. Char pointers that have been set equal by an
/// equation are associated to the same element.
/// \param equations: vector of equations
/// \param ns: namespace
/// \param stream: output stream
static void add_equations_for_symbol_resolution(
union_find_replacet &symbol_solver,
const std::vector<exprt> &equations,
const namespacet &ns,
messaget::mstreamt &stream)
{
const std::string log_message =
"WARNING string_refinement.cpp generate_symbol_resolution_from_equations:";
auto equalities = make_range(equations).filter(
[&](const exprt &e) { return can_cast_expr<equal_exprt>(e); });
for(const exprt &e : equalities)
{
const equal_exprt &eq = to_equal_expr(e);
const exprt &lhs = to_equal_expr(eq).lhs();
const exprt &rhs = to_equal_expr(eq).rhs();
if(lhs.id() != ID_symbol)
{
stream << log_message << "non symbol lhs: " << format(lhs)
<< " with rhs: " << format(rhs) << messaget::eom;
continue;
}
if(lhs.type() != rhs.type())
{
stream << log_message << "non equal types lhs: " << format(lhs)
<< "\n####################### rhs: " << format(rhs)
<< messaget::eom;
continue;
}
if(is_char_pointer_type(rhs.type()))
{
symbol_solver.make_union(lhs, simplify_expr(rhs, ns));
}
else if(rhs.id() == ID_function_application)
{
// function applications can be ignored because they will be replaced
// in the convert_function_application step of dec_solve
}
else if(
lhs.type().id() != ID_pointer && has_char_pointer_subtype(lhs.type(), ns))
{
if(rhs.type().id() == ID_struct || rhs.type().id() == ID_struct_tag)
{
const struct_typet &struct_type =
rhs.type().id() == ID_struct_tag
? ns.follow_tag(to_struct_tag_type(rhs.type()))
: to_struct_type(rhs.type());
for(const auto &comp : struct_type.components())
{
if(is_char_pointer_type(comp.type()))
{
const member_exprt lhs_data(lhs, comp.get_name(), comp.type());
const exprt rhs_data = simplify_expr(
member_exprt(rhs, comp.get_name(), comp.type()), ns);
symbol_solver.make_union(lhs_data, rhs_data);
}
}
}
else
{
stream << log_message << "non struct with char pointer subexpr "
<< format(rhs) << "\n * of type " << format(rhs.type())
<< messaget::eom;
}
}
}
}
/// This is meant to be used on the lhs of an equation with string subtype.
/// \param lhs: expression which is either of string type, or a symbol
/// representing a struct with some string members
/// \param ns: namespace to resolve type tags
/// \return if lhs is a string return this string, if it is a struct return the
/// members of the expression that have string type.
static std::vector<exprt>
extract_strings_from_lhs(const exprt &lhs, const namespacet &ns)
{
std::vector<exprt> result;
if(lhs.type() == string_typet())
result.push_back(lhs);
else if(lhs.type().id() == ID_struct || lhs.type().id() == ID_struct_tag)
{
const struct_typet &struct_type =
lhs.type().id() == ID_struct_tag
? ns.follow_tag(to_struct_tag_type(lhs.type()))
: to_struct_type(lhs.type());
for(const auto &comp : struct_type.components())
{
const std::vector<exprt> strings_in_comp = extract_strings_from_lhs(
member_exprt(lhs, comp.get_name(), comp.type()), ns);
result.insert(
result.end(), strings_in_comp.begin(), strings_in_comp.end());
}
}
return result;
}
/// \param expr: an expression
/// \param ns: namespace to resolve type tags
/// \return all subexpressions of type string which are not if_exprt expressions
/// this includes expressions of the form `e.x` if e is a symbol subexpression
/// with a field `x` of type string
static std::vector<exprt>
extract_strings(const exprt &expr, const namespacet &ns)
{
std::vector<exprt> result;
for(auto it = expr.depth_begin(); it != expr.depth_end();)
{
if(it->type() == string_typet() && it->id() != ID_if)
{
result.push_back(*it);
it.next_sibling_or_parent();
}
else if(it->id() == ID_symbol)
{
for(const exprt &e : extract_strings_from_lhs(*it, ns))
result.push_back(e);
it.next_sibling_or_parent();
}
else
++it;
}
return result;
}
/// Given an equation on strings, mark these strings as belonging to the same
/// set in the `symbol_resolve` structure. The lhs and rhs of the equation,
/// should have string type or be struct with string members.
/// \param eq: equation to add
/// \param symbol_resolve: structure to which the equation will be added
/// \param ns: namespace
static void add_string_equation_to_symbol_resolution(
const equal_exprt &eq,
union_find_replacet &symbol_resolve,
const namespacet &ns)
{
if(eq.rhs().type() == string_typet())
{
symbol_resolve.make_union(eq.lhs(), simplify_expr(eq.rhs(), ns));
}
else if(has_subtype(eq.lhs().type(), ID_string, ns))
{
if(
eq.rhs().type().id() == ID_struct ||
eq.rhs().type().id() == ID_struct_tag)
{
const struct_typet &struct_type =
eq.rhs().type().id() == ID_struct_tag
? ns.follow_tag(to_struct_tag_type(eq.rhs().type()))
: to_struct_type(eq.rhs().type());
for(const auto &comp : struct_type.components())
{
const member_exprt lhs_data(eq.lhs(), comp.get_name(), comp.type());
const exprt rhs_data = simplify_expr(
member_exprt(eq.rhs(), comp.get_name(), comp.type()), ns);
add_string_equation_to_symbol_resolution(
equal_exprt(lhs_data, rhs_data), symbol_resolve, ns);
}
}
}
}
/// Symbol resolution for expressions of type string typet.
/// We record equality between these expressions in the output if one of the
/// function calls depends on them.
/// \param equations: list of equations
/// \param ns: namespace
/// \param stream: output stream
/// \return union_find_replacet structure containing the correspondences.
union_find_replacet string_identifiers_resolution_from_equations(
const std::vector<equal_exprt> &equations,
const namespacet &ns,
messaget::mstreamt &stream)
{
const std::string log_message =
"WARNING string_refinement.cpp "
"string_identifiers_resolution_from_equations:";
equation_symbol_mappingt equation_map;
// Indexes of equations that need to be added to the result
std::unordered_set<size_t> required_equations;
std::stack<size_t> equations_to_treat;
for(std::size_t i = 0; i < equations.size(); ++i)
{
const equal_exprt &eq = equations[i];
if(eq.rhs().id() == ID_function_application)
{
if(required_equations.insert(i).second)
equations_to_treat.push(i);
std::vector<exprt> rhs_strings = extract_strings(eq.rhs(), ns);
for(const auto &expr : rhs_strings)
equation_map.add(i, expr);
}
else if(
eq.lhs().type().id() != ID_pointer &&
has_subtype(eq.lhs().type(), ID_string, ns))
{
std::vector<exprt> lhs_strings = extract_strings_from_lhs(eq.lhs(), ns);
for(const auto &expr : lhs_strings)
equation_map.add(i, expr);
if(lhs_strings.empty())
{
stream << log_message << "non struct with string subtype "
<< format(eq.lhs()) << "\n * of type "
<< format(eq.lhs().type()) << messaget::eom;
}
for(const exprt &expr : extract_strings(eq.rhs(), ns))
equation_map.add(i, expr);
}
}
// transitively add all equations which depend on the equations to treat
while(!equations_to_treat.empty())
{
const std::size_t i = equations_to_treat.top();
equations_to_treat.pop();
for(const exprt &string : equation_map.find_expressions(i))
{
for(const std::size_t j : equation_map.find_equations(string))
{
if(required_equations.insert(j).second)
equations_to_treat.push(j);
}
}
}
union_find_replacet result;
for(const std::size_t i : required_equations)
add_string_equation_to_symbol_resolution(equations[i], result, ns);
return result;
}
#ifdef DEBUG
/// Output a vector of equations to the given stream, used for debugging.
static void
output_equations(std::ostream &output, const std::vector<exprt> &equations)
{
for(std::size_t i = 0; i < equations.size(); ++i)
output << " [" << i << "] " << format(equations[i]) << std::endl;
}
#endif
/// Main decision procedure of the solver. Looks for a valuation of variables
/// compatible with the constraints that have been given to `set_to` so far.
///
/// The decision procedure initiated by string_refinementt::dec_solve is
/// composed of several steps detailed below.
///
/// ## Symbol resolution
/// Pointer symbols which are set to be equal by constraints, are replaced by
/// an single symbol in the solver. The `symbol_solvert` object used for this
/// substitution is constructed by
// NOLINTNEXTLINE
/// `generate_symbol_resolution_from_equations(const std::vector<equal_exprt>&,const namespacet&,messaget::mstreamt&)`.
/// All these symbols are then replaced using
// NOLINTNEXTLINE
/// `replace_symbols_in_equations(const union_find_replacet &, std::vector<equal_exprt> &)`.
///
/// ## Conversion to first order formulas:
/// Each string primitive is converted to a list of first order formulas by the
// NOLINTNEXTLINE
/// function `substitute_function_applications_in_equations(std::vector<equal_exprt>&,string_constraint_generatort&)`.
/// These formulas should be unquantified or be either a `string_constraintt`
/// or a `string_not_contains_constraintt`.
/// The constraints corresponding to each primitive can be found by following
/// the links in section \ref primitives.
///
/// Since only arrays appear in the string constraints, during the conversion to
/// first order formulas, pointers are associated to arrays.
/// The `string_constraint_generatort` object keeps track of this association.
/// It can either be set manually using the primitives
/// `cprover_associate_array_to_pointer` or a fresh array is created.
///
/// ## Refinement loop
/// We use `super_dec_solve` and `super_get` to denote the methods of the
/// underlying solver (`bv_refinementt` by default).
/// The refinement loop relies on functions `string_refinementt::check_axioms`
/// which returns true when the set of quantified constraints `q` is satisfied
/// by the valuation given by`super_get` and
/// `string_refinementt::instantiate` which gives propositional formulas
/// implied by a string constraint.
/// If the following algorithm returns `SAT` or `UNSAT`, the given constraints
/// are `SAT` or `UNSAT` respectively:
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// is_SAT(unquantified_constraints uq, quantified_constraints q)
/// {
/// cur <- uq;
/// while(limit--) > 0
/// {
/// if(super_dec_solve(cur)==SAT)
/// {
/// if(check_axioms(q, super_get))
/// else
/// for(axiom in q)
/// cur.add(instantiate(axiom));
/// return SAT;
/// }
/// else
/// return UNSAT;
/// }
/// return ERROR;
/// }
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// \return `resultt::D_SATISFIABLE` if the constraints are satisfiable,
/// `resultt::D_UNSATISFIABLE` if they are unsatisfiable,
/// `resultt::D_ERROR` if the limit of iteration was reached.
decision_proceduret::resultt
string_refinementt::dec_solve(const exprt &assumption)
{
#ifdef DEBUG
log.debug() << "dec_solve: Initial set of equations" << messaget::eom;
output_equations(log.debug(), equations);
#endif
log.debug() << "dec_solve: Build symbol solver from equations"
<< messaget::eom;
// symbol_resolve is used by get and is kept between calls to dec_solve,
// that's why we use a class member here
add_equations_for_symbol_resolution(
symbol_resolve, equations, ns, log.debug());
#ifdef DEBUG
log.debug() << "symbol resolve:" << messaget::eom;
for(const auto &pair : symbol_resolve.to_vector())
log.debug() << format(pair.first) << " --> " << format(pair.second)
<< messaget::eom;
#endif
const union_find_replacet string_id_symbol_resolve =
string_identifiers_resolution_from_equations(
[&] {
std::vector<equal_exprt> equalities;
for(const auto &eq : equations)
{
if(auto equal_expr = expr_try_dynamic_cast<equal_exprt>(eq))
equalities.push_back(*equal_expr);
}
return equalities;
}(),
ns,
log.debug());
#ifdef DEBUG
log.debug() << "symbol resolve string:" << messaget::eom;
for(const auto &pair : string_id_symbol_resolve.to_vector())
{
log.debug() << format(pair.first) << " --> " << format(pair.second)
<< messaget::eom;
}
#endif
log.debug() << "dec_solve: Replacing string ids and simplifying arguments"
" in function applications"
<< messaget::eom;
for(exprt &expr : equations)
{
auto it = expr.depth_begin();
while(it != expr.depth_end())
{
if(can_cast_expr<function_application_exprt>(*it))
{
// Simplification is required because the array pool may not realize
// that an expression like
// `(unsignedbv[16]*)((signedbv[8]*)&constarray[0] + 0)` is the
// same pointer as `&constarray[0]
simplify(it.mutate(), ns);
string_id_symbol_resolve.replace_expr(it.mutate());
it.next_sibling_or_parent();
}
else
++it;
}
}
// Constraints start clear at each `dec_solve` call.
string_constraintst constraints;
for(auto &expr : equations)
make_char_array_pointer_associations(generator, expr);
#ifdef DEBUG
output_equations(log.debug(), equations);
#endif
log.debug() << "dec_solve: compute dependency graph and remove function "
<< "applications captured by the dependencies:" << messaget::eom;
std::vector<exprt> local_equations;
for(const exprt &eq : equations)
{
// Ensures that arrays that are equal, are associated to the same nodes
// in the graph.
const exprt eq_with_char_array_replaced_with_representative_elements =
replace_expr_copy(symbol_resolve, eq);
const std::optional<exprt> new_equation = add_node(
dependencies,
eq_with_char_array_replaced_with_representative_elements,
generator.array_pool,
generator.fresh_symbol);
if(new_equation)
local_equations.push_back(*new_equation);
else
local_equations.push_back(eq);
}
equations.clear();
#ifdef DEBUG
dependencies.output_dot(log.debug());
#endif
log.debug() << "dec_solve: add constraints" << messaget::eom;
merge(
constraints,
dependencies.add_constraints(generator, log.get_message_handler()));
#ifdef DEBUG
output_equations(log.debug(), equations);
#endif
#ifdef DEBUG
log.debug() << "dec_solve: arrays_of_pointers:" << messaget::eom;
for(auto pair : generator.array_pool.get_arrays_of_pointers())
{
log.debug() << " * " << format(pair.first) << "\t--> "
<< format(pair.second) << " : " << format(pair.second.type())
<< messaget::eom;
}
#endif
for(const auto &eq : local_equations)
{
#ifdef DEBUG
log.debug() << "dec_solve: set_to " << format(eq) << messaget::eom;
#endif
supert::set_to(eq, true);
}
std::transform(
constraints.universal.begin(),
constraints.universal.end(),
std::back_inserter(axioms.universal),
[&](string_constraintt constraint) {
constraint.replace_expr(symbol_resolve);
DATA_INVARIANT(
is_valid_string_constraint(log.error(), ns, constraint),
string_refinement_invariantt(
"string constraints satisfy their invariant"));
return constraint;
});
std::transform(
constraints.not_contains.begin(),
constraints.not_contains.end(),
std::back_inserter(axioms.not_contains),
[&](string_not_contains_constraintt axiom) {
replace(symbol_resolve, axiom);
return axiom;
});
// Used to store information about witnesses for not_contains constraints
std::unordered_map<string_not_contains_constraintt, symbol_exprt>
not_contain_witnesses;
for(const auto &nc_axiom : axioms.not_contains)
{
const auto &witness_type = [&] {
const auto &rtype = to_array_type(nc_axiom.s0.type());
const typet &index_type = rtype.size().type();
return array_typet(index_type, infinity_exprt(index_type));
}();
not_contain_witnesses.emplace(
nc_axiom, generator.fresh_symbol("not_contains_witness", witness_type));
}
for(const exprt &lemma : constraints.existential)
{
add_lemma(substitute_array_access(lemma, generator.fresh_symbol, true));
}
// All generated strings should have non-negative length
for(const auto &pair : generator.array_pool.created_strings())
{
exprt length = generator.array_pool.get_or_create_length(pair.first);
add_lemma(
binary_relation_exprt{length, ID_ge, from_integer(0, length.type())});
}
// Initial try without index set
const auto get = [this](const exprt &expr) { return this->get(expr); };
dependencies.clean_cache();
const decision_proceduret::resultt initial_result =
supert::dec_solve(nil_exprt());
if(initial_result == resultt::D_SATISFIABLE)
{
bool satisfied;
std::vector<exprt> counter_examples;
std::tie(satisfied, counter_examples) = check_axioms(
axioms,
generator,
get,
log.debug(),
ns,
config_.use_counter_example,
symbol_resolve,
not_contain_witnesses);
if(satisfied)
{
log.debug() << "check_SAT: the model is correct" << messaget::eom;
return resultt::D_SATISFIABLE;
}
log.debug() << "check_SAT: got SAT but the model is not correct"
<< messaget::eom;
}
else
{
log.debug() << "check_SAT: got UNSAT or ERROR" << messaget::eom;
return initial_result;
}
initial_index_set(index_sets, ns, axioms);
update_index_set(index_sets, ns, current_constraints);
current_constraints.clear();
const auto initial_instances =
generate_instantiations(index_sets, axioms, not_contain_witnesses);
for(const auto &instance : initial_instances)
{
add_lemma(substitute_array_access(instance, generator.fresh_symbol, true));
}
while((loop_bound_--) > 0)
{
dependencies.clean_cache();
const decision_proceduret::resultt refined_result =
supert::dec_solve(nil_exprt());
if(refined_result == resultt::D_SATISFIABLE)
{
bool satisfied;
std::vector<exprt> counter_examples;
std::tie(satisfied, counter_examples) = check_axioms(
axioms,
generator,
get,
log.debug(),
ns,
config_.use_counter_example,
symbol_resolve,
not_contain_witnesses);
if(satisfied)
{
log.debug() << "check_SAT: the model is correct" << messaget::eom;
return resultt::D_SATISFIABLE;
}
log.debug()
<< "check_SAT: got SAT but the model is not correct, refining..."
<< messaget::eom;
// Since the model is not correct although we got SAT, we need to refine
// the property we are checking by adding more indices to the index set,
// and instantiating universal formulas with this indices.
// We will then relaunch the solver with these added lemmas.
index_sets.current.clear();
update_index_set(index_sets, ns, current_constraints);
display_index_set(log.debug(), index_sets);
if(index_sets.current.empty())
{
if(axioms.not_contains.empty())
{
log.error() << "dec_solve: current index set is empty, "
<< "this should not happen" << messaget::eom;
return resultt::D_ERROR;
}
else
{
log.debug() << "dec_solve: current index set is empty, "
<< "adding counter examples" << messaget::eom;
for(const auto &counter : counter_examples)
add_lemma(counter);
}
}
current_constraints.clear();
const auto instances =
generate_instantiations(index_sets, axioms, not_contain_witnesses);
for(const auto &instance : instances)
add_lemma(
substitute_array_access(instance, generator.fresh_symbol, true));
}
else
{
log.debug() << "check_SAT: default return "
<< static_cast<int>(refined_result) << messaget::eom;
return refined_result;
}
}
log.debug() << "string_refinementt::dec_solve reached the maximum number"
<< "of steps allowed" << messaget::eom;
return resultt::D_ERROR;
}
/// Add the given lemma to the solver.
/// \param lemma: a Boolean expression
/// \param simplify_lemma: whether the lemma should be simplified before being
/// given to the underlying solver.
void string_refinementt::add_lemma(
const exprt &lemma,
const bool simplify_lemma)
{
if(!seen_instances.insert(lemma).second)
return;
current_constraints.push_back(lemma);
exprt simple_lemma = lemma;
if(simplify_lemma)
{
simplify(simple_lemma, ns);
}
if(simple_lemma.is_true())
{
#if 0
log.debug() << "string_refinementt::add_lemma : tautology" << messaget::eom;
#endif
return;
}
symbol_resolve.replace_expr(simple_lemma);
// Replace empty arrays with array_of expression because the solver cannot
// handle empty arrays.
for(auto it = simple_lemma.depth_begin(); it != simple_lemma.depth_end();)
{
if(it->id() == ID_array && it->operands().empty())
{
it.mutate() = array_of_exprt(
from_integer(
CHARACTER_FOR_UNKNOWN, to_array_type(it->type()).element_type()),
to_array_type(it->type()));
it.next_sibling_or_parent();
}
else
++it;
}
log.debug() << "adding lemma " << format(simple_lemma) << messaget::eom;
prop.l_set_to_true(convert(simple_lemma));
}
/// Get a model of the size of the input string.
/// First ask the solver for a size value. If the solver has no value, get the
/// size directly from the type. This is the case for string literals that are
/// not part of the decision procedure (e.g. literals in return values).
/// If the size value is not a constant or not a valid integer (size_t),
/// return no value.
/// \param super_get: function returning the valuation of an expression
/// in a model
/// \param ns: namespace
/// \param stream: output stream for warning messages
/// \param arr: expression of type array representing a string
/// \param array_pool: pool of arrays representing strings
/// \return an optional expression representing the size of the array that can
/// be cast to size_t
static std::optional<exprt> get_valid_array_size(
const std::function<exprt(const exprt &)> &super_get,
const namespacet &ns,
messaget::mstreamt &stream,
const array_string_exprt &arr,
const array_poolt &array_pool)
{
const auto &size_from_pool = array_pool.get_length_if_exists(arr);
exprt size_val;
if(size_from_pool.has_value())
{
const exprt size = size_from_pool.value();
size_val = simplify_expr(super_get(size), ns);
if(!size_val.is_constant())
{
stream << "(sr::get_valid_array_size) string of unknown size: "
<< format(size_val) << messaget::eom;
return {};
}
}
else if(to_array_type(arr.type()).size().is_constant())
size_val = simplify_expr(to_array_type(arr.type()).size(), ns);
else
return {};
auto n_opt = numeric_cast<std::size_t>(size_val);
if(!n_opt)
{
stream << "(sr::get_valid_array_size) size is not valid" << messaget::eom;
return {};
}
return size_val;