-
Notifications
You must be signed in to change notification settings - Fork 6k
/
Copy pathBMC.cpp
1319 lines (1170 loc) · 38.4 KB
/
BMC.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
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libsolidity/formal/BMC.h>
#include <libsolidity/formal/Cvc5SMTLib2Interface.h>
#include <libsolidity/formal/SymbolicTypes.h>
#include <libsolidity/formal/Z3SMTLib2Interface.h>
#include <libsmtutil/SMTLib2Interface.h>
#include <libsmtutil/SMTPortfolio.h>
#include <liblangutil/CharStream.h>
#include <liblangutil/CharStreamProvider.h>
#include <utility>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::frontend;
using namespace solidity::frontend::smt;
using namespace solidity::smtutil;
BMC::BMC(
smt::EncodingContext& _context,
UniqueErrorReporter& _errorReporter,
UniqueErrorReporter& _unsupportedErrorReporter,
ErrorReporter& _provedSafeReporter,
std::map<h256, std::string> const& _smtlib2Responses,
ReadCallback::Callback const& _smtCallback,
ModelCheckerSettings _settings,
CharStreamProvider const& _charStreamProvider
):
SMTEncoder(_context, _settings, _errorReporter, _unsupportedErrorReporter, _provedSafeReporter, _charStreamProvider)
{
solAssert(!_settings.printQuery || _settings.solvers == SMTSolverChoice::SMTLIB2(), "Only SMTLib2 solver can be enabled to print queries");
std::vector<std::unique_ptr<BMCSolverInterface>> solvers;
if (_settings.solvers.smtlib2)
solvers.emplace_back(std::make_unique<SMTLib2Interface>(_smtlib2Responses, _smtCallback, _settings.timeout));
if (_settings.solvers.cvc5)
solvers.emplace_back(std::make_unique<Cvc5SMTLib2Interface>(_smtCallback, _settings.timeout));
if (_settings.solvers.z3 )
solvers.emplace_back(std::make_unique<Z3SMTLib2Interface>(_smtCallback, _settings.timeout));
m_interface = std::make_unique<SMTPortfolio>(std::move(solvers), _settings.timeout);
#if defined (HAVE_Z3)
if (m_settings.solvers.z3)
if (!_smtlib2Responses.empty())
m_errorReporter.warning(
5622_error,
"SMT-LIB2 query responses were given in the auxiliary input, "
"but this Solidity binary uses an SMT solver Z3 directly."
"These responses will be ignored."
"Consider disabling Z3 at compilation time in order to use SMT-LIB2 responses."
);
#endif
}
void BMC::analyze(SourceUnit const& _source, std::map<ASTNode const*, std::set<VerificationTargetType>, smt::EncodingContext::IdCompare> _solvedTargets)
{
// At this point every enabled solver is available.
if (!m_settings.solvers.cvc5 && !m_settings.solvers.smtlib2 && !m_settings.solvers.z3)
{
m_errorReporter.warning(
7710_error,
SourceLocation(),
"BMC analysis was not possible since no SMT solver was found and enabled."
" The accepted solvers for BMC are cvc5 and z3."
);
return;
}
SMTEncoder::resetSourceAnalysis();
state().prepareForSourceUnit(_source, false);
m_solvedTargets = std::move(_solvedTargets);
m_context.setSolver(m_interface.get());
m_context.reset();
m_context.setAssertionAccumulation(true);
m_variableUsage.setFunctionInlining(shouldInlineFunctionCall);
auto const& sources = sourceDependencies(_source);
createFreeConstants(sources);
createStateVariables(sources);
m_unprovedAmt = 0;
_source.accept(*this);
if (m_unprovedAmt > 0 && !m_settings.showUnproved)
m_errorReporter.warning(
2788_error,
{},
"BMC: " +
std::to_string(m_unprovedAmt) +
" verification condition(s) could not be proved." +
" Enable the model checker option \"show unproved\" to see all of them." +
" Consider choosing a specific contract to be verified in order to reduce the solving problems." +
" Consider increasing the timeout per query."
);
if (!m_settings.showProvedSafe && !m_safeTargets.empty())
{
std::size_t provedSafeNum = 0;
for (auto&& [_, targets]: m_safeTargets)
provedSafeNum += targets.size();
m_errorReporter.info(
6002_error,
"BMC: " +
std::to_string(provedSafeNum) +
" verification condition(s) proved safe!" +
" Enable the model checker option \"show proved safe\" to see all of them."
);
}
else if (m_settings.showProvedSafe)
for (auto const& [node, targets]: m_safeTargets)
for (auto const& target: targets)
m_provedSafeReporter.info(
2961_error,
node->location(),
"BMC: " +
targetDescription(target) +
" check is safe!"
);
// If this check is true, Z3 and cvc5 are not available
// and the query answers were not provided, since SMTPortfolio
// guarantees that SmtLib2Interface is the first solver, if enabled.
if (
!m_interface->unhandledQueries().empty() &&
m_interface->solvers() == 1 &&
m_settings.solvers.smtlib2
)
m_errorReporter.warning(
8084_error,
SourceLocation(),
"BMC analysis was not possible. No SMT solver (Z3 or cvc5) was available."
" None of the installed solvers was enabled."
);
}
bool BMC::shouldInlineFunctionCall(
FunctionCall const& _funCall,
ContractDefinition const* _scopeContract,
ContractDefinition const* _contextContract
)
{
auto funDef = functionCallToDefinition(_funCall, _scopeContract, _contextContract);
if (!funDef || !funDef->isImplemented())
return false;
FunctionType const& funType = dynamic_cast<FunctionType const&>(*_funCall.expression().annotation().type);
if (funType.kind() == FunctionType::Kind::External)
return isExternalCallToThis(&_funCall.expression());
else if (funType.kind() != FunctionType::Kind::Internal)
return false;
return true;
}
/// AST visitors.
bool BMC::visit(ContractDefinition const& _contract)
{
// Raises UnimplementedFeatureError in the presence of transient storage variables
TransientDataLocationChecker checker(_contract);
initContract(_contract);
SMTEncoder::visit(_contract);
return false;
}
void BMC::endVisit(ContractDefinition const& _contract)
{
if (auto constructor = _contract.constructor())
constructor->accept(*this);
else
{
/// Visiting implicit constructor - we need a dummy callstack frame
pushCallStack({nullptr, nullptr});
inlineConstructorHierarchy(_contract);
popCallStack();
/// Check targets created by state variable initialization.
checkVerificationTargets();
m_verificationTargets.clear();
}
SMTEncoder::endVisit(_contract);
}
bool BMC::visit(FunctionDefinition const& _function)
{
// Free functions need to be visited in the context of a contract.
if (!m_currentContract)
return false;
auto contract = dynamic_cast<ContractDefinition const*>(_function.scope());
auto const& hierarchy = m_currentContract->annotation().linearizedBaseContracts;
if (contract && find(hierarchy.begin(), hierarchy.end(), contract) == hierarchy.end())
createStateVariables(*contract);
if (m_callStack.empty())
{
reset();
initFunction(_function);
if (_function.isConstructor() || _function.isPublic())
m_context.addAssertion(state().txTypeConstraints() && state().txFunctionConstraints(_function));
resetStateVariables();
}
if (_function.isConstructor())
{
solAssert(contract, "");
inlineConstructorHierarchy(*contract);
}
/// Already visits the children.
SMTEncoder::visit(_function);
return false;
}
void BMC::endVisit(FunctionDefinition const& _function)
{
// Free functions need to be visited in the context of a contract.
if (!m_currentContract)
return;
if (isRootFunction())
{
checkVerificationTargets();
m_verificationTargets.clear();
m_pathConditions.clear();
}
SMTEncoder::endVisit(_function);
}
bool BMC::visit(IfStatement const& _node)
{
auto indicesBeforePush = copyVariableIndices();
// This check needs to be done in its own context otherwise
// constraints from the If body might influence it.
m_context.pushSolver();
_node.condition().accept(*this);
// We ignore called functions here because they have
// specific input values.
if (isRootFunction() && !isInsideLoop())
addVerificationTarget(
VerificationTargetType::ConstantCondition,
expr(_node.condition()),
&_node.condition()
);
m_context.popSolver();
resetVariableIndices(std::move(indicesBeforePush));
_node.condition().accept(*this);
auto conditionExpr = expr(_node.condition());
// visit true branch
auto [indicesEndTrue, trueEndPathCondition] = visitBranch(&_node.trueStatement(), conditionExpr);
// visit false branch
decltype(indicesEndTrue) indicesEndFalse;
auto falseEndPathCondition = currentPathConditions() && !conditionExpr;
if (_node.falseStatement())
std::tie(indicesEndFalse, falseEndPathCondition) = visitBranch(_node.falseStatement(), !conditionExpr);
else
indicesEndFalse = copyVariableIndices();
// merge the information from branches
setPathCondition(trueEndPathCondition || falseEndPathCondition);
mergeVariables(expr(_node.condition()), indicesEndTrue, indicesEndFalse);
return false;
}
bool BMC::visit(Conditional const& _op)
{
auto indicesBeforePush = copyVariableIndices();
m_context.pushSolver();
_op.condition().accept(*this);
if (isRootFunction() && !isInsideLoop())
addVerificationTarget(
VerificationTargetType::ConstantCondition,
expr(_op.condition()),
&_op.condition()
);
m_context.popSolver();
resetVariableIndices(std::move(indicesBeforePush));
SMTEncoder::visit(_op);
return false;
}
// Unrolls while or do-while loop
bool BMC::visit(WhileStatement const& _node)
{
unsigned int bmcLoopIterations = m_settings.bmcLoopIterations.value_or(1);
smtutil::Expression broke(false);
smtutil::Expression loopCondition(true);
if (_node.isDoWhile())
{
for (unsigned int i = 0; i < bmcLoopIterations; ++i)
{
m_loopCheckpoints.emplace();
auto indicesBefore = copyVariableIndices();
_node.body().accept(*this);
auto brokeInCurrentIteration = mergeVariablesFromLoopCheckpoints();
auto indicesBreak = copyVariableIndices();
_node.condition().accept(*this);
mergeVariables(
!brokeInCurrentIteration,
copyVariableIndices(),
indicesBreak
);
mergeVariables(
broke || !loopCondition,
indicesBefore,
copyVariableIndices()
);
loopCondition = loopCondition && expr(_node.condition());
broke = broke || brokeInCurrentIteration;
m_loopCheckpoints.pop();
}
if (bmcLoopIterations > 0)
m_context.addAssertion(!loopCondition || broke);
}
else {
smtutil::Expression loopConditionOnPreviousIterations(true);
for (unsigned int i = 0; i < bmcLoopIterations; ++i)
{
m_loopCheckpoints.emplace();
auto indicesBefore = copyVariableIndices();
_node.condition().accept(*this);
loopCondition = expr(_node.condition());
auto indicesAfterCondition = copyVariableIndices();
pushPathCondition(loopCondition);
_node.body().accept(*this);
popPathCondition();
auto brokeInCurrentIteration = mergeVariablesFromLoopCheckpoints();
// merges indices modified when accepting loop condition that no longer holds
mergeVariables(
!loopCondition,
indicesAfterCondition,
copyVariableIndices()
);
// handles breaks in previous iterations
// breaks in current iterations are handled when traversing loop checkpoints
// handles case when the loop condition no longer holds but bmc loop iterations still unrolls the loop
mergeVariables(
broke || !loopConditionOnPreviousIterations,
indicesBefore,
copyVariableIndices()
);
m_loopCheckpoints.pop();
broke = broke || brokeInCurrentIteration;
loopConditionOnPreviousIterations = loopConditionOnPreviousIterations && loopCondition;
}
if (bmcLoopIterations > 0)
{
//after loop iterations are done, we check the loop condition last final time
auto indices = copyVariableIndices();
_node.condition().accept(*this);
loopCondition = expr(_node.condition());
// assert that the loop is complete
m_context.addAssertion(!loopCondition || broke || !loopConditionOnPreviousIterations);
mergeVariables(
broke || !loopConditionOnPreviousIterations,
indices,
copyVariableIndices()
);
}
}
m_loopExecutionHappened = true;
return false;
}
// Unrolls for loop
bool BMC::visit(ForStatement const& _node)
{
if (_node.initializationExpression())
_node.initializationExpression()->accept(*this);
smtutil::Expression broke(false);
smtutil::Expression forCondition(true);
smtutil::Expression forConditionOnPreviousIterations(true);
unsigned int bmcLoopIterations = m_settings.bmcLoopIterations.value_or(1);
for (unsigned int i = 0; i < bmcLoopIterations; ++i)
{
auto indicesBefore = copyVariableIndices();
if (_node.condition())
{
_node.condition()->accept(*this);
// values in loop condition might change during loop iteration
forCondition = expr(*_node.condition());
}
m_loopCheckpoints.emplace();
auto indicesAfterCondition = copyVariableIndices();
pushPathCondition(forCondition);
_node.body().accept(*this);
auto brokeInCurrentIteration = mergeVariablesFromLoopCheckpoints();
// accept loop expression if there was no break
if (_node.loopExpression())
{
auto indicesBreak = copyVariableIndices();
_node.loopExpression()->accept(*this);
mergeVariables(
!brokeInCurrentIteration,
copyVariableIndices(),
indicesBreak
);
}
popPathCondition();
// merges indices modified when accepting loop condition that does no longer hold
mergeVariables(
!forCondition,
indicesAfterCondition,
copyVariableIndices()
);
// handles breaks in previous iterations
// breaks in current iterations are handled when traversing loop checkpoints
// handles case when the loop condition no longer holds but bmc loop iterations still unrolls the loop
mergeVariables(
broke || !forConditionOnPreviousIterations,
indicesBefore,
copyVariableIndices()
);
m_loopCheckpoints.pop();
broke = broke || brokeInCurrentIteration;
forConditionOnPreviousIterations = forConditionOnPreviousIterations && forCondition;
}
if (bmcLoopIterations > 0)
{
//after loop iterations are done, we check the loop condition last final time
auto indices = copyVariableIndices();
if (_node.condition())
{
_node.condition()->accept(*this);
forCondition = expr(*_node.condition());
}
// asseert that the loop is complete
m_context.addAssertion(!forCondition || broke || !forConditionOnPreviousIterations);
mergeVariables(
broke || !forConditionOnPreviousIterations,
indices,
copyVariableIndices()
);
}
m_loopExecutionHappened = true;
return false;
}
// merges variables based on loop control statements
// returns expression indicating whether there was a break in current loop unroll iteration
smtutil::Expression BMC::mergeVariablesFromLoopCheckpoints()
{
smtutil::Expression continues(false);
smtutil::Expression brokeInCurrentIteration(false);
for (auto const& loopControl: m_loopCheckpoints.top())
{
// use SSAs associated with this break statement only if
// loop didn't break or continue earlier in the iteration
// loop condition is included in break path conditions
mergeVariables(
!brokeInCurrentIteration && !continues && loopControl.pathConditions,
loopControl.variableIndices,
copyVariableIndices()
);
if (loopControl.kind == LoopControlKind::Break)
brokeInCurrentIteration =
brokeInCurrentIteration || loopControl.pathConditions;
else if (loopControl.kind == LoopControlKind::Continue)
continues = continues || loopControl.pathConditions;
}
return brokeInCurrentIteration;
}
bool BMC::visit(TryStatement const& _tryStatement)
{
FunctionCall const* externalCall = dynamic_cast<FunctionCall const*>(&_tryStatement.externalCall());
solAssert(externalCall && externalCall->annotation().tryCall, "");
externalCall->accept(*this);
if (_tryStatement.successClause()->parameters())
expressionToTupleAssignment(_tryStatement.successClause()->parameters()->parameters(), *externalCall);
smtutil::Expression clauseId = m_context.newVariable("clause_choice_" + std::to_string(m_context.newUniqueId()), smtutil::SortProvider::uintSort);
auto const& clauses = _tryStatement.clauses();
m_context.addAssertion(clauseId >= 0 && clauseId < clauses.size());
solAssert(clauses[0].get() == _tryStatement.successClause(), "First clause of TryStatement should be the success clause");
std::vector<std::pair<VariableIndices, smtutil::Expression>> clausesVisitResults;
for (size_t i = 0; i < clauses.size(); ++i)
clausesVisitResults.push_back(visitBranch(clauses[i].get()));
// merge the information from all clauses
smtutil::Expression pathCondition = clausesVisitResults.front().second;
auto currentIndices = clausesVisitResults[0].first;
for (size_t i = 1; i < clauses.size(); ++i)
{
mergeVariables(clauseId == i, clausesVisitResults[i].first, currentIndices);
currentIndices = copyVariableIndices();
pathCondition = pathCondition || clausesVisitResults[i].second;
}
setPathCondition(pathCondition);
return false;
}
bool BMC::visit(Break const&)
{
LoopControl control = {
LoopControlKind::Break,
currentPathConditions(),
copyVariableIndices()
};
m_loopCheckpoints.top().emplace_back(control);
return false;
}
bool BMC::visit(Continue const&)
{
LoopControl control = {
LoopControlKind::Continue,
currentPathConditions(),
copyVariableIndices()
};
m_loopCheckpoints.top().emplace_back(control);
return false;
}
void BMC::endVisit(UnaryOperation const& _op)
{
SMTEncoder::endVisit(_op);
// User-defined operators are essentially function calls.
if (auto funDef = *_op.annotation().userDefinedFunction)
{
std::vector<Expression const*> arguments;
arguments.push_back(&_op.subExpression());
// pushCallStack and defineExpr inside createReturnedExpression should be called on the expression
// in case of a user-defined operator call
inlineFunctionCall(funDef, _op, std::nullopt, arguments);
return;
}
if (
_op.annotation().type->category() == Type::Category::RationalNumber ||
_op.annotation().type->category() == Type::Category::FixedPoint
)
return;
if (_op.getOperator() == Token::Sub && smt::isInteger(*_op.annotation().type))
{
addVerificationTarget(
VerificationTargetType::Underflow,
expr(_op),
&_op
);
addVerificationTarget(
VerificationTargetType::Overflow,
expr(_op),
&_op
);
}
}
void BMC::endVisit(BinaryOperation const& _op)
{
SMTEncoder::endVisit(_op);
if (auto funDef = *_op.annotation().userDefinedFunction)
{
std::vector<Expression const*> arguments;
arguments.push_back(&_op.leftExpression());
arguments.push_back(&_op.rightExpression());
// pushCallStack and defineExpr inside createReturnedExpression should be called on the expression
// in case of a user-defined operator call
inlineFunctionCall(funDef, _op, std::nullopt, arguments);
}
}
void BMC::endVisit(FunctionCall const& _funCall)
{
auto functionCallKind = *_funCall.annotation().kind;
if (functionCallKind != FunctionCallKind::FunctionCall)
{
SMTEncoder::endVisit(_funCall);
return;
}
FunctionType const& funType = dynamic_cast<FunctionType const&>(*_funCall.expression().annotation().type);
switch (funType.kind())
{
case FunctionType::Kind::Assert:
visitAssert(_funCall);
SMTEncoder::endVisit(_funCall);
break;
case FunctionType::Kind::Require:
visitRequire(_funCall);
SMTEncoder::endVisit(_funCall);
break;
case FunctionType::Kind::Internal:
case FunctionType::Kind::External:
case FunctionType::Kind::DelegateCall:
case FunctionType::Kind::BareCall:
case FunctionType::Kind::BareCallCode:
case FunctionType::Kind::BareDelegateCall:
case FunctionType::Kind::BareStaticCall:
case FunctionType::Kind::Creation:
SMTEncoder::endVisit(_funCall);
internalOrExternalFunctionCall(_funCall);
break;
case FunctionType::Kind::Send:
case FunctionType::Kind::Transfer:
{
auto value = _funCall.arguments().front();
solAssert(value, "");
smtutil::Expression thisBalance = state().balance();
addVerificationTarget(
VerificationTargetType::Balance,
thisBalance < expr(*value),
&_funCall
);
SMTEncoder::endVisit(_funCall);
break;
}
case FunctionType::Kind::KECCAK256:
case FunctionType::Kind::ECRecover:
case FunctionType::Kind::SHA256:
case FunctionType::Kind::RIPEMD160:
case FunctionType::Kind::BlockHash:
case FunctionType::Kind::AddMod:
case FunctionType::Kind::MulMod:
case FunctionType::Kind::Unwrap:
case FunctionType::Kind::Wrap:
[[fallthrough]];
default:
SMTEncoder::endVisit(_funCall);
break;
}
}
void BMC::endVisit(Return const& _return)
{
SMTEncoder::endVisit(_return);
setPathCondition(smtutil::Expression(false));
}
/// Visitor helpers.
void BMC::visitAssert(FunctionCall const& _funCall)
{
auto const& args = _funCall.arguments();
solAssert(args.size() == 1, "");
solAssert(args.front()->annotation().type->category() == Type::Category::Bool, "");
addVerificationTarget(
VerificationTargetType::Assert,
expr(*args.front()),
&_funCall
);
}
void BMC::visitRequire(FunctionCall const& _funCall)
{
auto const& args = _funCall.arguments();
solAssert(args.size() >= 1, "");
solAssert(args.front()->annotation().type->category() == Type::Category::Bool, "");
if (isRootFunction() && !isInsideLoop())
addVerificationTarget(
VerificationTargetType::ConstantCondition,
expr(*args.front()),
args.front().get()
);
}
void BMC::visitAddMulMod(FunctionCall const& _funCall)
{
solAssert(_funCall.arguments().at(2), "");
addVerificationTarget(
VerificationTargetType::DivByZero,
expr(*_funCall.arguments().at(2)),
&_funCall
);
SMTEncoder::visitAddMulMod(_funCall);
}
void BMC::inlineFunctionCall(
FunctionDefinition const* _funDef,
Expression const& _callStackExpr,
std::optional<Expression const*> _boundArgumentCall,
std::vector<Expression const*> const& _arguments
)
{
solAssert(_funDef, "");
if (visitedFunction(_funDef))
{
auto const& returnParams = _funDef->returnParameters();
for (auto param: returnParams)
{
m_context.newValue(*param);
m_context.setUnknownValue(*param);
}
}
else
{
initializeFunctionCallParameters(*_funDef, symbolicArguments(_funDef->parameters(), _arguments, _boundArgumentCall));
// The reason why we need to pushCallStack here instead of visit(FunctionDefinition)
// is that there we don't have `_callStackExpr`.
pushCallStack({_funDef, &_callStackExpr});
pushPathCondition(currentPathConditions());
auto oldChecked = std::exchange(m_checked, true);
_funDef->accept(*this);
m_checked = oldChecked;
popPathCondition();
}
createReturnedExpressions(_funDef, _callStackExpr);
}
void BMC::inlineFunctionCall(FunctionCall const& _funCall)
{
solAssert(shouldInlineFunctionCall(_funCall, currentScopeContract(), m_currentContract), "");
auto funDef = functionCallToDefinition(_funCall, currentScopeContract(), m_currentContract);
Expression const* expr = &_funCall.expression();
auto funType = dynamic_cast<FunctionType const*>(expr->annotation().type);
std::optional<Expression const*> boundArgumentCall =
funType->hasBoundFirstArgument() ? std::make_optional(expr) : std::nullopt;
std::vector<Expression const*> arguments;
for (auto& arg: _funCall.sortedArguments())
arguments.push_back(&(*arg));
// pushCallStack and defineExpr inside createReturnedExpression should be called
// on the FunctionCall object for the normal function call case
inlineFunctionCall(funDef, _funCall, boundArgumentCall, arguments);
}
void BMC::internalOrExternalFunctionCall(FunctionCall const& _funCall)
{
auto const& funType = dynamic_cast<FunctionType const&>(*_funCall.expression().annotation().type);
if (shouldInlineFunctionCall(_funCall, currentScopeContract(), m_currentContract))
inlineFunctionCall(_funCall);
else if (publicGetter(_funCall.expression()))
{
// Do nothing here.
// The processing happens in SMT Encoder, but we need to prevent the resetting of the state variables.
}
else if (funType.kind() == FunctionType::Kind::Internal)
m_unsupportedErrors.warning(
5729_error,
_funCall.location(),
"BMC does not yet implement this type of function call."
);
else if (funType.kind() == FunctionType::Kind::BareStaticCall)
{
// Do nothing here.
// Neither storage nor balances should be modified.
}
else
{
m_externalFunctionCallHappened = true;
resetStorageVariables();
resetBalances();
}
}
std::pair<smtutil::Expression, smtutil::Expression> BMC::arithmeticOperation(
Token _op,
smtutil::Expression const& _left,
smtutil::Expression const& _right,
Type const* _commonType,
Expression const& _expression
)
{
// Unchecked does not disable div by 0 checks.
if (_op == Token::Div || _op == Token::Mod)
addVerificationTarget(
VerificationTargetType::DivByZero,
_right,
&_expression
);
auto values = SMTEncoder::arithmeticOperation(_op, _left, _right, _commonType, _expression);
if (!m_checked)
return values;
auto const* intType = dynamic_cast<IntegerType const*>(_commonType);
if (!intType)
intType = TypeProvider::uint256();
// Mod does not need underflow/overflow checks.
if (_op == Token::Mod)
return values;
// The order matters here:
// If _op is Div and intType is signed, we only care about overflow.
if (_op == Token::Div)
{
if (intType->isSigned())
// Signed division can only overflow.
addVerificationTarget(VerificationTargetType::Overflow, values.second, &_expression);
else
// Unsigned division cannot underflow/overflow.
return values;
}
else if (intType->isSigned())
{
addVerificationTarget(VerificationTargetType::Overflow, values.second, &_expression);
addVerificationTarget(VerificationTargetType::Underflow, values.second, &_expression);
}
else if (_op == Token::Sub)
addVerificationTarget(VerificationTargetType::Underflow, values.second, &_expression);
else if (_op == Token::Add || _op == Token::Mul)
addVerificationTarget(VerificationTargetType::Overflow, values.second, &_expression);
else
solAssert(false, "");
return values;
}
void BMC::reset()
{
m_externalFunctionCallHappened = false;
m_loopExecutionHappened = false;
}
std::pair<std::vector<smtutil::Expression>, std::vector<std::string>> BMC::modelExpressions()
{
std::vector<smtutil::Expression> expressionsToEvaluate;
std::vector<std::string> expressionNames;
for (auto const& var: m_context.variables())
if (var.first->type()->isValueType())
{
expressionsToEvaluate.emplace_back(currentValue(*var.first));
expressionNames.push_back(var.first->name());
}
for (auto const& var: m_context.globalSymbols())
{
auto const& type = var.second->type();
if (
type->isValueType() &&
smt::smtKind(*type) != smtutil::Kind::Function
)
{
expressionsToEvaluate.emplace_back(var.second->currentValue());
expressionNames.push_back(var.first);
}
}
for (auto const& uf: m_uninterpretedTerms)
if (uf->annotation().type->isValueType())
{
expressionsToEvaluate.emplace_back(expr(*uf));
std::string expressionName;
if (uf->location().hasText())
expressionName = m_charStreamProvider.charStream(*uf->location().sourceName).text(
uf->location()
);
expressionNames.push_back(std::move(expressionName));
}
return {expressionsToEvaluate, expressionNames};
}
/// Verification targets.
std::string BMC::targetDescription(BMCVerificationTarget const& _target)
{
if (
_target.type == VerificationTargetType::Underflow ||
_target.type == VerificationTargetType::Overflow
)
{
auto const* intType = dynamic_cast<IntegerType const*>(_target.expression->annotation().type);
if (!intType)
intType = TypeProvider::uint256();
if (_target.type == VerificationTargetType::Underflow)
return "Underflow (resulting value less than " + formatNumberReadable(intType->minValue()) + ")";
return "Overflow (resulting value larger than " + formatNumberReadable(intType->maxValue()) + ")";
}
else if (_target.type == VerificationTargetType::DivByZero)
return "Division by zero";
else if (_target.type == VerificationTargetType::Assert)
return "Assertion violation";
else if (_target.type == VerificationTargetType::Balance)
return "Insufficient funds";
solAssert(false);
}
void BMC::checkVerificationTargets()
{
for (auto& target: m_verificationTargets)
checkVerificationTarget(target);
}
void BMC::checkVerificationTarget(BMCVerificationTarget& _target)
{
if (
m_solvedTargets.count(_target.expression) &&
m_solvedTargets.at(_target.expression).count(_target.type)
)
return;
switch (_target.type)
{
case VerificationTargetType::ConstantCondition:
checkConstantCondition(_target);
break;
case VerificationTargetType::Underflow:
checkUnderflow(_target);
break;
case VerificationTargetType::Overflow:
checkOverflow(_target);
break;
case VerificationTargetType::DivByZero:
checkDivByZero(_target);
break;
case VerificationTargetType::Balance:
checkBalance(_target);
break;
case VerificationTargetType::Assert:
checkAssert(_target);
break;
default:
solAssert(false, "");
}
}
void BMC::checkConstantCondition(BMCVerificationTarget& _target)
{
checkBooleanNotConstant(
*_target.expression,
_target.constraints,
_target.value,
_target.callStack
);
}
void BMC::checkUnderflow(BMCVerificationTarget& _target)
{
solAssert(
_target.type == VerificationTargetType::Underflow,
""
);
auto const* intType = dynamic_cast<IntegerType const*>(_target.expression->annotation().type);
if (!intType)
intType = TypeProvider::uint256();
checkCondition(
_target,
_target.constraints && _target.value < smt::minValue(*intType),
_target.callStack,
_target.modelExpressions,
_target.expression->location(),
4144_error,
8312_error,
"<result>",
&_target.value