-
Notifications
You must be signed in to change notification settings - Fork 6k
/
Copy pathCHC.cpp
2487 lines (2103 loc) · 84.2 KB
/
CHC.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/CHC.h>
#include <libsolidity/formal/ArraySlicePredicate.h>
#include <libsolidity/formal/EldaricaCHCSmtLib2Interface.h>
#include <libsolidity/formal/Invariants.h>
#include <libsolidity/formal/ModelChecker.h>
#include <libsolidity/formal/PredicateInstance.h>
#include <libsolidity/formal/PredicateSort.h>
#include <libsolidity/formal/SymbolicTypes.h>
#include <libsolidity/formal/Z3CHCSmtLib2Interface.h>
#include <libsolidity/ast/TypeProvider.h>
#include <libsmtutil/CHCSmtLib2Interface.h>
#include <liblangutil/CharStreamProvider.h>
#include <libsolutil/Algorithms.h>
#include <libsolutil/StringUtils.h>
#include <boost/algorithm/string.hpp>
#include <range/v3/algorithm/for_each.hpp>
#include <range/v3/view.hpp>
#include <range/v3/view/enumerate.hpp>
#include <range/v3/view/reverse.hpp>
#include <charconv>
#include <queue>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::smtutil;
using namespace solidity::frontend;
using namespace solidity::frontend::smt;
CHC::CHC(
EncodingContext& _context,
UniqueErrorReporter& _errorReporter,
UniqueErrorReporter& _unsupportedErrorReporter,
ErrorReporter& _provedSafeReporter,
std::map<util::h256, std::string> const& _smtlib2Responses,
ReadCallback::Callback const& _smtCallback,
ModelCheckerSettings _settings,
CharStreamProvider const& _charStreamProvider
):
SMTEncoder(_context, _settings, _errorReporter, _unsupportedErrorReporter, _provedSafeReporter, _charStreamProvider),
m_smtlib2Responses(_smtlib2Responses),
m_smtCallback(_smtCallback)
{
solAssert(!_settings.printQuery || _settings.solvers == smtutil::SMTSolverChoice::SMTLIB2(), "Only SMTLib2 solver can be enabled to print queries");
}
void CHC::analyze(SourceUnit const& _source)
{
// At this point every enabled solver is available.
if (!m_settings.solvers.eld && !m_settings.solvers.smtlib2 && !m_settings.solvers.z3)
{
m_errorReporter.warning(
7649_error,
SourceLocation(),
"CHC analysis was not possible since no Horn solver was found and enabled."
" The accepted solvers for CHC are Eldarica and z3."
);
return;
}
if (m_settings.solvers.eld && m_settings.solvers.z3)
m_errorReporter.warning(
5798_error,
SourceLocation(),
"Multiple Horn solvers were selected for CHC."
" CHC only supports one solver at a time, therefore only z3 will be used."
" If you wish to use Eldarica, please enable Eldarica only."
);
if (!shouldAnalyze(_source))
return;
resetSourceAnalysis();
auto sources = sourceDependencies(_source);
collectFreeFunctions(sources);
createFreeConstants(sources);
state().prepareForSourceUnit(_source, encodeExternalCallsAsTrusted());
for (auto const* source: sources)
defineInterfacesAndSummaries(*source);
for (auto const* source: sources)
source->accept(*this);
checkVerificationTargets();
bool ranSolver = true;
// If ranSolver is true here it's because an SMT solver callback was
// actually given and the queries were solved,
// or Eldarica was chosen and was present in the system.
if (auto const* smtLibInterface = dynamic_cast<CHCSmtLib2Interface const*>(m_interface.get()))
ranSolver = smtLibInterface->unhandledQueries().empty();
if (!ranSolver)
m_errorReporter.warning(
3996_error,
SourceLocation(),
"CHC analysis was not possible. No Horn solver was available."
" None of the installed solvers was enabled."
);
}
std::vector<std::string> CHC::unhandledQueries() const
{
if (auto smtlib2 = dynamic_cast<CHCSmtLib2Interface const*>(m_interface.get()))
return smtlib2->unhandledQueries();
return {};
}
bool CHC::visit(ContractDefinition const& _contract)
{
if (!shouldAnalyze(_contract))
return false;
// Raises UnimplementedFeatureError in the presence of transient storage variables
TransientDataLocationChecker checker(_contract);
resetContractAnalysis();
initContract(_contract);
clearIndices(&_contract);
m_scopes.push_back(&_contract);
m_stateVariables = SMTEncoder::stateVariablesIncludingInheritedAndPrivate(_contract);
solAssert(m_currentContract, "");
SMTEncoder::visit(_contract);
return false;
}
void CHC::endVisit(ContractDefinition const& _contract)
{
if (!shouldAnalyze(_contract))
return;
for (auto base: _contract.annotation().linearizedBaseContracts)
{
if (auto constructor = base->constructor())
constructor->accept(*this);
defineContractInitializer(*base, _contract);
}
auto const& entry = *createConstructorBlock(_contract, "implicit_constructor_entry");
// In case constructors use uninitialized state variables,
// they need to be zeroed.
// This is not part of `initialConstraints` because it's only true here,
// at the beginning of the deployment routine.
smtutil::Expression zeroes(true);
for (auto var: stateVariablesIncludingInheritedAndPrivate(_contract))
zeroes = zeroes && currentValue(*var) == smt::zeroValue(var->type());
smtutil::Expression newAddress = encodeExternalCallsAsTrusted() ?
!state().addressActive(state().thisAddress()) :
smtutil::Expression(true);
// The contract's address might already have funds before deployment,
// so the balance must be at least `msg.value`, but not equals.
auto initialBalanceConstraint = state().balance(state().thisAddress()) >= state().txMember("msg.value");
addRule(smtutil::Expression::implies(
initialConstraints(_contract) && zeroes && newAddress && initialBalanceConstraint,
predicate(entry)
), entry.functor().name);
setCurrentBlock(entry);
if (encodeExternalCallsAsTrusted())
{
auto const& entryAfterAddress = *createConstructorBlock(_contract, "implicit_constructor_entry_after_address");
state().setAddressActive(state().thisAddress(), true);
connectBlocks(m_currentBlock, predicate(entryAfterAddress));
setCurrentBlock(entryAfterAddress);
}
solAssert(!m_errorDest, "");
m_errorDest = m_constructorSummaries.at(&_contract);
// We need to evaluate the base constructor calls (arguments) from derived -> base
auto baseArgs = baseArguments(_contract);
for (auto base: _contract.annotation().linearizedBaseContracts)
if (base != &_contract)
{
m_callGraph[&_contract].insert(base);
auto baseConstructor = base->constructor();
if (baseConstructor && baseArgs.count(base))
{
std::vector<ASTPointer<Expression>> const& args = baseArgs.at(base);
auto const& params = baseConstructor->parameters();
solAssert(params.size() == args.size(), "");
for (unsigned i = 0; i < params.size(); ++i)
{
args.at(i)->accept(*this);
if (params.at(i))
{
solAssert(m_context.knownVariable(*params.at(i)), "");
m_context.addAssertion(currentValue(*params.at(i)) == expr(*args.at(i), params.at(i)->type()));
}
}
}
}
m_errorDest = nullptr;
// Then call initializer_Base from base -> derived
for (auto base: _contract.annotation().linearizedBaseContracts | ranges::views::reverse)
{
errorFlag().increaseIndex();
m_context.addAssertion(smt::constructorCall(*m_contractInitializers.at(&_contract).at(base), m_context));
connectBlocks(m_currentBlock, summary(_contract), errorFlag().currentValue() > 0);
m_context.addAssertion(errorFlag().currentValue() == 0);
}
if (encodeExternalCallsAsTrusted())
state().writeStateVars(_contract, state().thisAddress());
connectBlocks(m_currentBlock, summary(_contract));
setCurrentBlock(*m_constructorSummaries.at(&_contract));
solAssert(&_contract == m_currentContract, "");
if (shouldAnalyze(_contract))
{
auto constructor = _contract.constructor();
auto txConstraints = state().txTypeConstraints();
if (!constructor || !constructor->isPayable())
txConstraints = txConstraints && state().txNonPayableConstraint();
m_queryPlaceholders[&_contract].push_back({txConstraints, errorFlag().currentValue(), m_currentBlock});
connectBlocks(m_currentBlock, interface(), txConstraints && errorFlag().currentValue() == 0);
}
solAssert(m_scopes.back() == &_contract, "");
m_scopes.pop_back();
SMTEncoder::endVisit(_contract);
}
bool CHC::visit(FunctionDefinition const& _function)
{
// Free functions need to be visited in the context of a contract.
if (!m_currentContract)
return false;
if (
!_function.isImplemented() ||
abstractAsNondet(_function)
)
{
smtutil::Expression conj(true);
if (
_function.stateMutability() == StateMutability::Pure ||
_function.stateMutability() == StateMutability::View
)
conj = conj && currentEqualInitialVarsConstraints(stateVariablesIncludingInheritedAndPrivate(_function));
conj = conj && errorFlag().currentValue() == 0;
addRule(smtutil::Expression::implies(conj, summary(_function)), "summary_function_" + std::to_string(_function.id()));
return false;
}
// No inlining.
solAssert(!m_currentFunction, "Function inlining should not happen in CHC.");
m_currentFunction = &_function;
m_scopes.push_back(&_function);
initFunction(_function);
auto functionEntryBlock = createBlock(m_currentFunction, PredicateType::FunctionBlock);
auto bodyBlock = createBlock(&m_currentFunction->body(), PredicateType::FunctionBlock);
auto functionPred = predicate(*functionEntryBlock);
auto bodyPred = predicate(*bodyBlock);
addRule(functionPred, functionPred.name);
solAssert(m_currentContract, "");
m_context.addAssertion(initialConstraints(*m_currentContract, &_function));
connectBlocks(functionPred, bodyPred);
setCurrentBlock(*bodyBlock);
solAssert(!m_errorDest, "");
m_errorDest = m_summaries.at(m_currentContract).at(&_function);
SMTEncoder::visit(*m_currentFunction);
m_errorDest = nullptr;
return false;
}
void CHC::endVisit(FunctionDefinition const& _function)
{
// Free functions need to be visited in the context of a contract.
if (!m_currentContract)
return;
if (
!_function.isImplemented() ||
abstractAsNondet(_function)
)
return;
solAssert(m_currentFunction && m_currentContract, "");
// No inlining.
solAssert(m_currentFunction == &_function, "");
solAssert(m_scopes.back() == &_function, "");
m_scopes.pop_back();
connectBlocks(m_currentBlock, summary(_function));
setCurrentBlock(*m_summaries.at(m_currentContract).at(&_function));
// Query placeholders for constructors are not created here because
// of contracts without constructors.
// Instead, those are created in endVisit(ContractDefinition).
if (
!_function.isConstructor() &&
_function.isPublic() &&
contractFunctions(*m_currentContract).count(&_function) &&
shouldAnalyze(*m_currentContract)
)
{
defineExternalFunctionInterface(_function, *m_currentContract);
setCurrentBlock(*m_interfaces.at(m_currentContract));
// Create the rule
// interface \land externalFunctionEntry => interface'
auto ifacePre = smt::interfacePre(*m_interfaces.at(m_currentContract), *m_currentContract, m_context);
auto sum = externalSummary(_function);
m_queryPlaceholders[&_function].push_back({sum, errorFlag().currentValue(), ifacePre});
connectBlocks(ifacePre, interface(), sum && errorFlag().currentValue() == 0);
}
m_currentFunction = nullptr;
SMTEncoder::endVisit(_function);
}
bool CHC::visit(Block const& _block)
{
m_scopes.push_back(&_block);
return SMTEncoder::visit(_block);
}
void CHC::endVisit(Block const& _block)
{
solAssert(m_scopes.back() == &_block, "");
m_scopes.pop_back();
SMTEncoder::endVisit(_block);
}
bool CHC::visit(IfStatement const& _if)
{
solAssert(m_currentFunction, "");
bool unknownFunctionCallWasSeen = m_unknownFunctionCallSeen;
m_unknownFunctionCallSeen = false;
solAssert(m_currentFunction, "");
auto const& functionBody = m_currentFunction->body();
auto ifHeaderBlock = createBlock(&_if, PredicateType::FunctionBlock, "if_header_");
auto trueBlock = createBlock(&_if.trueStatement(), PredicateType::FunctionBlock, "if_true_");
auto falseBlock = _if.falseStatement() ? createBlock(_if.falseStatement(), PredicateType::FunctionBlock, "if_false_") : nullptr;
auto afterIfBlock = createBlock(&functionBody, PredicateType::FunctionBlock);
connectBlocks(m_currentBlock, predicate(*ifHeaderBlock));
setCurrentBlock(*ifHeaderBlock);
_if.condition().accept(*this);
auto condition = expr(_if.condition());
connectBlocks(m_currentBlock, predicate(*trueBlock), condition);
if (_if.falseStatement())
connectBlocks(m_currentBlock, predicate(*falseBlock), !condition);
else
connectBlocks(m_currentBlock, predicate(*afterIfBlock), !condition);
setCurrentBlock(*trueBlock);
_if.trueStatement().accept(*this);
connectBlocks(m_currentBlock, predicate(*afterIfBlock));
if (_if.falseStatement())
{
setCurrentBlock(*falseBlock);
_if.falseStatement()->accept(*this);
connectBlocks(m_currentBlock, predicate(*afterIfBlock));
}
setCurrentBlock(*afterIfBlock);
if (m_unknownFunctionCallSeen)
eraseKnowledge();
m_unknownFunctionCallSeen = unknownFunctionCallWasSeen;
return false;
}
bool CHC::visit(WhileStatement const& _while)
{
bool unknownFunctionCallWasSeen = m_unknownFunctionCallSeen;
m_unknownFunctionCallSeen = false;
solAssert(m_currentFunction, "");
auto const& functionBody = m_currentFunction->body();
auto namePrefix = std::string(_while.isDoWhile() ? "do_" : "") + "while";
auto loopHeaderBlock = createBlock(&_while, PredicateType::FunctionBlock, namePrefix + "_header_");
auto loopBodyBlock = createBlock(&_while.body(), PredicateType::FunctionBlock, namePrefix + "_body_");
auto afterLoopBlock = createBlock(&functionBody, PredicateType::FunctionBlock);
auto outerBreakDest = m_breakDest;
auto outerContinueDest = m_continueDest;
m_breakDest = afterLoopBlock;
m_continueDest = loopHeaderBlock;
if (_while.isDoWhile())
_while.body().accept(*this);
connectBlocks(m_currentBlock, predicate(*loopHeaderBlock));
setCurrentBlock(*loopHeaderBlock);
_while.condition().accept(*this);
auto condition = expr(_while.condition());
connectBlocks(m_currentBlock, predicate(*loopBodyBlock), condition);
connectBlocks(m_currentBlock, predicate(*afterLoopBlock), !condition);
// Loop body visit.
setCurrentBlock(*loopBodyBlock);
_while.body().accept(*this);
m_breakDest = outerBreakDest;
m_continueDest = outerContinueDest;
// Back edge.
connectBlocks(m_currentBlock, predicate(*loopHeaderBlock));
setCurrentBlock(*afterLoopBlock);
if (m_unknownFunctionCallSeen)
eraseKnowledge();
m_unknownFunctionCallSeen = unknownFunctionCallWasSeen;
return false;
}
bool CHC::visit(ForStatement const& _for)
{
m_scopes.push_back(&_for);
bool unknownFunctionCallWasSeen = m_unknownFunctionCallSeen;
m_unknownFunctionCallSeen = false;
solAssert(m_currentFunction, "");
auto const& functionBody = m_currentFunction->body();
auto loopHeaderBlock = createBlock(&_for, PredicateType::FunctionBlock, "for_header_");
auto loopBodyBlock = createBlock(&_for.body(), PredicateType::FunctionBlock, "for_body_");
auto afterLoopBlock = createBlock(&functionBody, PredicateType::FunctionBlock);
auto postLoop = _for.loopExpression();
auto postLoopBlock = postLoop ? createBlock(postLoop, PredicateType::FunctionBlock, "for_post_") : nullptr;
auto outerBreakDest = m_breakDest;
auto outerContinueDest = m_continueDest;
m_breakDest = afterLoopBlock;
m_continueDest = postLoop ? postLoopBlock : loopHeaderBlock;
if (auto init = _for.initializationExpression())
init->accept(*this);
connectBlocks(m_currentBlock, predicate(*loopHeaderBlock));
setCurrentBlock(*loopHeaderBlock);
auto condition = smtutil::Expression(true);
if (auto forCondition = _for.condition())
{
forCondition->accept(*this);
condition = expr(*forCondition);
}
connectBlocks(m_currentBlock, predicate(*loopBodyBlock), condition);
connectBlocks(m_currentBlock, predicate(*afterLoopBlock), !condition);
// Loop body visit.
setCurrentBlock(*loopBodyBlock);
_for.body().accept(*this);
if (postLoop)
{
connectBlocks(m_currentBlock, predicate(*postLoopBlock));
setCurrentBlock(*postLoopBlock);
postLoop->accept(*this);
}
m_breakDest = outerBreakDest;
m_continueDest = outerContinueDest;
// Back edge.
connectBlocks(m_currentBlock, predicate(*loopHeaderBlock));
setCurrentBlock(*afterLoopBlock);
if (m_unknownFunctionCallSeen)
eraseKnowledge();
m_unknownFunctionCallSeen = unknownFunctionCallWasSeen;
return false;
}
void CHC::endVisit(ForStatement const& _for)
{
solAssert(m_scopes.back() == &_for, "");
m_scopes.pop_back();
}
void CHC::endVisit(UnaryOperation const& _op)
{
SMTEncoder::endVisit(_op);
if (auto funDef = *_op.annotation().userDefinedFunction)
{
std::vector<Expression const*> arguments;
arguments.push_back(&_op.subExpression());
internalFunctionCall(funDef, std::nullopt, _op.userDefinedFunctionType(), arguments, state().thisAddress());
createReturnedExpressions(funDef, _op);
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))
{
auto const* intType = dynamic_cast<IntegerType const*>(_op.annotation().type);
if (!intType)
intType = TypeProvider::uint256();
verificationTargetEncountered(&_op, VerificationTargetType::Underflow, expr(_op) < intType->minValue());
verificationTargetEncountered(&_op, VerificationTargetType::Overflow, expr(_op) > intType->maxValue());
}
}
void CHC::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());
internalFunctionCall(funDef, std::nullopt, _op.userDefinedFunctionType(), arguments, state().thisAddress());
createReturnedExpressions(funDef, _op);
}
}
void CHC::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::Internal:
internalFunctionCall(_funCall);
break;
case FunctionType::Kind::External:
case FunctionType::Kind::BareStaticCall:
case FunctionType::Kind::BareCall:
externalFunctionCall(_funCall);
SMTEncoder::endVisit(_funCall);
break;
case FunctionType::Kind::Creation:
visitDeployment(_funCall);
break;
case FunctionType::Kind::DelegateCall:
case FunctionType::Kind::BareCallCode:
case FunctionType::Kind::BareDelegateCall:
SMTEncoder::endVisit(_funCall);
unknownFunctionCall(_funCall);
break;
case FunctionType::Kind::Send:
case FunctionType::Kind::Transfer:
{
auto value = _funCall.arguments().front();
solAssert(value, "");
smtutil::Expression thisBalance = state().balance();
verificationTargetEncountered(
&_funCall,
VerificationTargetType::Balance,
thisBalance < expr(*value)
);
SMTEncoder::endVisit(_funCall);
break;
}
case FunctionType::Kind::KECCAK256:
case FunctionType::Kind::ECRecover:
case FunctionType::Kind::SHA256:
case FunctionType::Kind::RIPEMD160:
case FunctionType::Kind::BlobHash:
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;
}
auto funDef = functionCallToDefinition(_funCall, currentScopeContract(), m_currentContract);
createReturnedExpressions(funDef, _funCall);
}
void CHC::endVisit(Break const& _break)
{
solAssert(m_breakDest, "");
connectBlocks(m_currentBlock, predicate(*m_breakDest));
// Add an unreachable ghost node to collect unreachable statements after a break.
auto breakGhost = createBlock(&_break, PredicateType::FunctionBlock, "break_ghost_");
m_currentBlock = predicate(*breakGhost);
}
void CHC::endVisit(Continue const& _continue)
{
solAssert(m_continueDest, "");
connectBlocks(m_currentBlock, predicate(*m_continueDest));
// Add an unreachable ghost node to collect unreachable statements after a continue.
auto continueGhost = createBlock(&_continue, PredicateType::FunctionBlock, "continue_ghost_");
m_currentBlock = predicate(*continueGhost);
}
void CHC::endVisit(IndexRangeAccess const& _range)
{
createExpr(_range);
auto baseArray = std::dynamic_pointer_cast<SymbolicArrayVariable>(m_context.expression(_range.baseExpression()));
auto sliceArray = std::dynamic_pointer_cast<SymbolicArrayVariable>(m_context.expression(_range));
solAssert(baseArray && sliceArray, "");
auto const& sliceData = ArraySlicePredicate::create(sliceArray->sort(), m_context);
if (!sliceData.first)
{
for (auto pred: sliceData.second.predicates)
m_interface->registerRelation(pred->functor());
for (auto const& rule: sliceData.second.rules)
addRule(rule, "");
}
auto start = _range.startExpression() ? expr(*_range.startExpression()) : 0;
auto end = _range.endExpression() ? expr(*_range.endExpression()) : baseArray->length();
auto slicePred = (*sliceData.second.predicates.at(0))({
baseArray->elements(),
sliceArray->elements(),
start,
end
});
m_context.addAssertion(slicePred);
m_context.addAssertion(sliceArray->length() == end - start);
}
void CHC::endVisit(Return const& _return)
{
SMTEncoder::endVisit(_return);
connectBlocks(m_currentBlock, predicate(*m_returnDests.back()));
// Add an unreachable ghost node to collect unreachable statements after a return.
auto returnGhost = createBlock(&_return, PredicateType::FunctionBlock, "return_ghost_");
m_currentBlock = predicate(*returnGhost);
}
bool CHC::visit(TryCatchClause const& _tryStatement)
{
m_scopes.push_back(&_tryStatement);
return SMTEncoder::visit(_tryStatement);
}
void CHC::endVisit(TryCatchClause const& _tryStatement)
{
solAssert(m_scopes.back() == &_tryStatement, "");
m_scopes.pop_back();
}
bool CHC::visit(TryStatement const& _tryStatement)
{
FunctionCall const* externalCall = dynamic_cast<FunctionCall const*>(&_tryStatement.externalCall());
solAssert(externalCall && externalCall->annotation().tryCall, "");
solAssert(m_currentFunction, "");
auto tryHeaderBlock = createBlock(&_tryStatement, PredicateType::FunctionBlock, "try_header_");
auto afterTryBlock = createBlock(&m_currentFunction->body(), PredicateType::FunctionBlock);
auto const& clauses = _tryStatement.clauses();
solAssert(clauses[0].get() == _tryStatement.successClause(), "First clause of TryStatement should be the success clause");
auto clauseBlocks = applyMap(clauses, [this](ASTPointer<TryCatchClause> clause) {
return createBlock(clause.get(), PredicateType::FunctionBlock, "try_clause_" + std::to_string(clause->id()));
});
connectBlocks(m_currentBlock, predicate(*tryHeaderBlock));
setCurrentBlock(*tryHeaderBlock);
// Visit everything, except the actual external call.
externalCall->expression().accept(*this);
ASTNode::listAccept(externalCall->arguments(), *this);
// Branch directly to all catch clauses, since in these cases, any effects of the external call are reverted.
for (size_t i = 1; i < clauseBlocks.size(); ++i)
connectBlocks(m_currentBlock, predicate(*clauseBlocks[i]));
// Only now visit the actual call to record its effects and connect to the success clause.
endVisit(*externalCall);
if (_tryStatement.successClause()->parameters())
expressionToTupleAssignment(_tryStatement.successClause()->parameters()->parameters(), *externalCall);
connectBlocks(m_currentBlock, predicate(*clauseBlocks[0]));
for (size_t i = 0; i < clauses.size(); ++i)
{
setCurrentBlock(*clauseBlocks[i]);
clauses[i]->accept(*this);
connectBlocks(m_currentBlock, predicate(*afterTryBlock));
}
setCurrentBlock(*afterTryBlock);
return false;
}
void CHC::pushInlineFrame(CallableDeclaration const& _callable)
{
m_returnDests.push_back(createBlock(&_callable, PredicateType::FunctionBlock, "return_"));
}
void CHC::popInlineFrame(CallableDeclaration const& _callable)
{
solAssert(!m_returnDests.empty(), "");
auto const& ret = *m_returnDests.back();
solAssert(ret.programNode() == &_callable, "");
connectBlocks(m_currentBlock, predicate(ret));
setCurrentBlock(ret);
m_returnDests.pop_back();
}
void CHC::visitAssert(FunctionCall const& _funCall)
{
auto const& args = _funCall.arguments();
solAssert(args.size() == 1, "");
solAssert(args.front()->annotation().type->category() == Type::Category::Bool, "");
solAssert(m_currentContract, "");
solAssert(m_currentFunction, "");
auto errorCondition = !m_context.expression(*args.front())->currentValue();
verificationTargetEncountered(&_funCall, VerificationTargetType::Assert, errorCondition);
}
void CHC::visitPublicGetter(FunctionCall const& _funCall)
{
createExpr(_funCall);
if (encodeExternalCallsAsTrusted())
{
auto const& access = dynamic_cast<MemberAccess const&>(_funCall.expression());
auto const& contractType = dynamic_cast<ContractType const&>(*access.expression().annotation().type);
state().writeStateVars(*m_currentContract, state().thisAddress());
state().readStateVars(contractType.contractDefinition(), expr(access.expression()));
}
SMTEncoder::visitPublicGetter(_funCall);
}
void CHC::visitAddMulMod(FunctionCall const& _funCall)
{
solAssert(_funCall.arguments().at(2), "");
verificationTargetEncountered(&_funCall, VerificationTargetType::DivByZero, expr(*_funCall.arguments().at(2)) == 0);
SMTEncoder::visitAddMulMod(_funCall);
}
void CHC::visitDeployment(FunctionCall const& _funCall)
{
if (!encodeExternalCallsAsTrusted())
{
SMTEncoder::endVisit(_funCall);
unknownFunctionCall(_funCall);
return;
}
auto [callExpr, callOptions] = functionCallExpression(_funCall);
auto funType = dynamic_cast<FunctionType const*>(callExpr->annotation().type);
ContractDefinition const* contract =
&dynamic_cast<ContractType const&>(*funType->returnParameterTypes().front()).contractDefinition();
// copy state variables from m_currentContract to state.storage.
state().writeStateVars(*m_currentContract, state().thisAddress());
errorFlag().increaseIndex();
Expression const* value = valueOption(callOptions);
if (value)
decreaseBalanceFromOptionsValue(*value);
auto originalTx = state().tx();
newTxConstraints(value);
auto prevThisAddr = state().thisAddress();
auto newAddr = state().newThisAddress();
if (auto constructor = contract->constructor())
{
auto const& args = _funCall.sortedArguments();
auto const& params = constructor->parameters();
solAssert(args.size() == params.size(), "");
for (auto [arg, param]: ranges::zip_view(args, params))
m_context.addAssertion(expr(*arg) == m_context.variable(*param)->currentValue());
}
for (auto var: stateVariablesIncludingInheritedAndPrivate(*contract))
m_context.variable(*var)->increaseIndex();
Predicate const& constructorSummary = *m_constructorSummaries.at(contract);
m_context.addAssertion(smt::constructorCall(constructorSummary, m_context, false));
solAssert(m_errorDest, "");
connectBlocks(
m_currentBlock,
predicate(*m_errorDest),
errorFlag().currentValue() > 0
);
m_context.addAssertion(errorFlag().currentValue() == 0);
m_context.addAssertion(state().newThisAddress() == prevThisAddr);
// copy state variables from state.storage to m_currentContract.
state().readStateVars(*m_currentContract, state().thisAddress());
state().newTx();
m_context.addAssertion(originalTx == state().tx());
defineExpr(_funCall, newAddr);
}
void CHC::internalFunctionCall(
FunctionDefinition const* _funDef,
std::optional<Expression const*> _boundArgumentCall,
FunctionType const* _funType,
std::vector<Expression const*> const& _arguments,
smtutil::Expression _contractAddressValue
)
{
solAssert(m_currentContract, "");
solAssert(_funType, "");
if (_funDef)
{
if (m_currentFunction && !m_currentFunction->isConstructor())
m_callGraph[m_currentFunction].insert(_funDef);
else
m_callGraph[m_currentContract].insert(_funDef);
}
m_context.addAssertion(predicate(_funDef, _boundArgumentCall, _funType, _arguments, _contractAddressValue));
solAssert(m_errorDest, "");
connectBlocks(
m_currentBlock,
predicate(*m_errorDest),
errorFlag().currentValue() > 0 && currentPathConditions()
);
m_context.addAssertion(smtutil::Expression::implies(currentPathConditions(), errorFlag().currentValue() == 0));
m_context.addAssertion(errorFlag().increaseIndex() == 0);
}
void CHC::internalFunctionCall(FunctionCall const& _funCall)
{
solAssert(m_currentContract, "");
auto funDef = functionCallToDefinition(_funCall, currentScopeContract(), m_currentContract);
if (funDef)
{
if (m_currentFunction && !m_currentFunction->isConstructor())
m_callGraph[m_currentFunction].insert(funDef);
else
m_callGraph[m_currentContract].insert(funDef);
}
Expression const* calledExpr = &_funCall.expression();
auto funType = dynamic_cast<FunctionType const*>(calledExpr->annotation().type);
auto contractAddressValue = [this](FunctionCall const& _f) {
auto [callExpr, callOptions] = functionCallExpression(_f);
FunctionType const& funType = dynamic_cast<FunctionType const&>(*callExpr->annotation().type);
if (funType.kind() == FunctionType::Kind::Internal)
return state().thisAddress();
if (MemberAccess const* callBase = dynamic_cast<MemberAccess const*>(callExpr))
return expr(callBase->expression());
solAssert(false, "Unreachable!");
};
std::vector<Expression const*> arguments;
for (auto& arg: _funCall.sortedArguments())
arguments.push_back(&(*arg));
std::optional<Expression const*> boundArgumentCall =
funType->hasBoundFirstArgument() ? std::make_optional(calledExpr) : std::nullopt;
internalFunctionCall(funDef, boundArgumentCall, funType, arguments, contractAddressValue(_funCall));
}
void CHC::addNondetCalls(ContractDefinition const& _contract)
{
for (auto var: _contract.stateVariables())
if (auto contractType = dynamic_cast<ContractType const*>(var->type()))
{
auto const& symbVar = m_context.variable(*var);
m_context.addAssertion(symbVar->currentValue() == symbVar->valueAtIndex(0));
nondetCall(contractType->contractDefinition(), *var);
}
}
void CHC::nondetCall(ContractDefinition const& _contract, VariableDeclaration const& _var)
{
auto address = m_context.variable(_var)->currentValue();
// Load the called contract's state variables from the global state.
state().readStateVars(_contract, address);
m_context.addAssertion(state().state() == state().state(0));
auto preCallState = std::vector<smtutil::Expression>{state().state()} + currentStateVariables(_contract);
state().newState();
for (auto const* var: _contract.stateVariables())
m_context.variable(*var)->increaseIndex();
Predicate const& callPredicate = *createSymbolicBlock(
nondetInterfaceSort(_contract, state()),
"nondet_call_" + uniquePrefix(),
PredicateType::FunctionSummary,
&_var,
m_currentContract
);
auto postCallState = std::vector<smtutil::Expression>{state().state()} + currentStateVariables(_contract);
std::vector<smtutil::Expression> stateExprs = commonStateExpressions(errorFlag().increaseIndex(), address);
auto nondet = (*m_nondetInterfaces.at(&_contract))(stateExprs + preCallState + postCallState);
auto nondetCall = callPredicate(stateExprs + preCallState + postCallState);
addRule(smtutil::Expression::implies(nondet, nondetCall), nondetCall.name);
m_context.addAssertion(nondetCall);
// Load the called contract's state variables into the global state.
state().writeStateVars(_contract, address);
}
void CHC::externalFunctionCall(FunctionCall const& _funCall)
{
/// In external function calls we do not add a "predicate call"
/// because we do not trust their function body anyway,
/// so we just add the nondet_interface predicate.