1 //===-- IteratorModeling.cpp --------------------------------------*- C++ -*--//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // Defines a modeling-checker for modeling STL iterator-like iterators.
11 //===----------------------------------------------------------------------===//
13 // In the code, iterator can be represented as a:
14 // * type-I: typedef-ed pointer. Operations over such iterator, such as
15 // comparisons or increments, are modeled straightforwardly by the
17 // * type-II: structure with its method bodies available. Operations over such
18 // iterator are inlined by the analyzer, and results of modeling
19 // these operations are exposing implementation details of the
20 // iterators, which is not necessarily helping.
21 // * type-III: completely opaque structure. Operations over such iterator are
22 // modeled conservatively, producing conjured symbols everywhere.
24 // To handle all these types in a common way we introduce a structure called
25 // IteratorPosition which is an abstraction of the position the iterator
26 // represents using symbolic expressions. The checker handles all the
27 // operations on this structure.
29 // Additionally, depending on the circumstances, operators of types II and III
30 // can be represented as:
31 // * type-IIa, type-IIIa: conjured structure symbols - when returned by value
32 // from conservatively evaluated methods such as
34 // * type-IIb, type-IIIb: memory regions of iterator-typed objects, such as
35 // variables or temporaries, when the iterator object is
36 // currently treated as an lvalue.
37 // * type-IIc, type-IIIc: compound values of iterator-typed objects, when the
38 // iterator object is treated as an rvalue taken of a
39 // particular lvalue, eg. a copy of "type-a" iterator
40 // object, or an iterator that existed before the
41 // analysis has started.
43 // To handle any of these three different representations stored in an SVal we
44 // use setter and getters functions which separate the three cases. To store
45 // them we use a pointer union of symbol and memory region.
47 // The checker works the following way: We record the begin and the
48 // past-end iterator for all containers whenever their `.begin()` and `.end()`
49 // are called. Since the Constraint Manager cannot handle such SVals we need
50 // to take over its role. We post-check equality and non-equality comparisons
51 // and record that the two sides are equal if we are in the 'equal' branch
52 // (true-branch for `==` and false-branch for `!=`).
54 // In case of type-I or type-II iterators we get a concrete integer as a result
55 // of the comparison (1 or 0) but in case of type-III we only get a Symbol. In
56 // this latter case we record the symbol and reload it in evalAssume() and do
57 // the propagation there. We also handle (maybe double) negated comparisons
58 // which are represented in the form of (x == 0 or x != 0) where x is the
61 // Since `SimpleConstraintManager` cannot handle complex symbolic expressions
62 // we only use expressions of the format S, S+n or S-n for iterator positions
63 // where S is a conjured symbol and n is an unsigned concrete integer. When
64 // making an assumption e.g. `S1 + n == S2 + m` we store `S1 - S2 == m - n` as
65 // a constraint which we later retrieve when doing an actual comparison.
67 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
68 #include "clang/AST/DeclTemplate.h"
69 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
70 #include "clang/StaticAnalyzer/Core/Checker.h"
71 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
72 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
73 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h"
79 using namespace clang;
81 using namespace iterator;
85 class IteratorModeling
86 : public Checker<check::PostCall, check::PostStmt<UnaryOperator>,
87 check::PostStmt<BinaryOperator>,
88 check::PostStmt<MaterializeTemporaryExpr>,
89 check::Bind, check::LiveSymbols, check::DeadSymbols> {
91 using AdvanceFn = void (IteratorModeling::*)(CheckerContext &, const Expr *,
92 SVal, SVal, SVal) const;
94 void handleOverloadedOperator(CheckerContext &C, const CallEvent &Call,
95 OverloadedOperatorKind Op) const;
96 void handleAdvanceLikeFunction(CheckerContext &C, const CallEvent &Call,
98 const AdvanceFn *Handler) const;
100 void handleComparison(CheckerContext &C, const Expr *CE, SVal RetVal,
101 const SVal &LVal, const SVal &RVal,
102 OverloadedOperatorKind Op) const;
103 void processComparison(CheckerContext &C, ProgramStateRef State,
104 SymbolRef Sym1, SymbolRef Sym2, const SVal &RetVal,
105 OverloadedOperatorKind Op) const;
106 void handleIncrement(CheckerContext &C, const SVal &RetVal, const SVal &Iter,
108 void handleDecrement(CheckerContext &C, const SVal &RetVal, const SVal &Iter,
110 void handleRandomIncrOrDecr(CheckerContext &C, const Expr *CE,
111 OverloadedOperatorKind Op, const SVal &RetVal,
112 const SVal &LHS, const SVal &RHS) const;
113 void handlePtrIncrOrDecr(CheckerContext &C, const Expr *Iterator,
114 OverloadedOperatorKind OK, SVal Offset) const;
115 void handleAdvance(CheckerContext &C, const Expr *CE, SVal RetVal, SVal Iter,
117 void handlePrev(CheckerContext &C, const Expr *CE, SVal RetVal, SVal Iter,
119 void handleNext(CheckerContext &C, const Expr *CE, SVal RetVal, SVal Iter,
121 void assignToContainer(CheckerContext &C, const Expr *CE, const SVal &RetVal,
122 const MemRegion *Cont) const;
123 bool noChangeInAdvance(CheckerContext &C, SVal Iter, const Expr *CE) const;
124 void printState(raw_ostream &Out, ProgramStateRef State, const char *NL,
125 const char *Sep) const override;
127 // std::advance, std::prev & std::next
128 CallDescriptionMap<AdvanceFn> AdvanceLikeFunctions = {
129 // template<class InputIt, class Distance>
130 // void advance(InputIt& it, Distance n);
131 {{{"std", "advance"}, 2}, &IteratorModeling::handleAdvance},
133 // template<class BidirIt>
136 // typename std::iterator_traits<BidirIt>::difference_type n = 1);
137 {{{"std", "prev"}, 2}, &IteratorModeling::handlePrev},
139 // template<class ForwardIt>
142 // typename std::iterator_traits<ForwardIt>::difference_type n = 1);
143 {{{"std", "next"}, 2}, &IteratorModeling::handleNext},
147 IteratorModeling() = default;
149 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
150 void checkBind(SVal Loc, SVal Val, const Stmt *S, CheckerContext &C) const;
151 void checkPostStmt(const UnaryOperator *UO, CheckerContext &C) const;
152 void checkPostStmt(const BinaryOperator *BO, CheckerContext &C) const;
153 void checkPostStmt(const CXXConstructExpr *CCE, CheckerContext &C) const;
154 void checkPostStmt(const DeclStmt *DS, CheckerContext &C) const;
155 void checkPostStmt(const MaterializeTemporaryExpr *MTE,
156 CheckerContext &C) const;
157 void checkLiveSymbols(ProgramStateRef State, SymbolReaper &SR) const;
158 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
161 bool isSimpleComparisonOperator(OverloadedOperatorKind OK);
162 bool isSimpleComparisonOperator(BinaryOperatorKind OK);
163 ProgramStateRef removeIteratorPosition(ProgramStateRef State, const SVal &Val);
164 ProgramStateRef relateSymbols(ProgramStateRef State, SymbolRef Sym1,
165 SymbolRef Sym2, bool Equal);
166 bool isBoundThroughLazyCompoundVal(const Environment &Env,
167 const MemRegion *Reg);
168 const ExplodedNode *findCallEnter(const ExplodedNode *Node, const Expr *Call);
172 void IteratorModeling::checkPostCall(const CallEvent &Call,
173 CheckerContext &C) const {
174 // Record new iterator positions and iterator position changes
175 const auto *Func = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
179 if (Func->isOverloadedOperator()) {
180 const auto Op = Func->getOverloadedOperator();
181 handleOverloadedOperator(C, Call, Op);
185 const auto *OrigExpr = Call.getOriginExpr();
189 const AdvanceFn *Handler = AdvanceLikeFunctions.lookup(Call);
191 handleAdvanceLikeFunction(C, Call, OrigExpr, Handler);
195 if (!isIteratorType(Call.getResultType()))
198 auto State = C.getState();
200 // Already bound to container?
201 if (getIteratorPosition(State, Call.getReturnValue()))
204 // Copy-like and move constructors
205 if (isa<CXXConstructorCall>(&Call) && Call.getNumArgs() == 1) {
206 if (const auto *Pos = getIteratorPosition(State, Call.getArgSVal(0))) {
207 State = setIteratorPosition(State, Call.getReturnValue(), *Pos);
208 if (cast<CXXConstructorDecl>(Func)->isMoveConstructor()) {
209 State = removeIteratorPosition(State, Call.getArgSVal(0));
211 C.addTransition(State);
216 // Assumption: if return value is an iterator which is not yet bound to a
217 // container, then look for the first iterator argument of the
218 // same type as the return value and bind the return value to
219 // the same container. This approach works for STL algorithms.
220 // FIXME: Add a more conservative mode
221 for (unsigned i = 0; i < Call.getNumArgs(); ++i) {
222 if (isIteratorType(Call.getArgExpr(i)->getType()) &&
223 Call.getArgExpr(i)->getType().getNonReferenceType().getDesugaredType(
224 C.getASTContext()).getTypePtr() ==
225 Call.getResultType().getDesugaredType(C.getASTContext()).getTypePtr()) {
226 if (const auto *Pos = getIteratorPosition(State, Call.getArgSVal(i))) {
227 assignToContainer(C, OrigExpr, Call.getReturnValue(),
228 Pos->getContainer());
235 void IteratorModeling::checkBind(SVal Loc, SVal Val, const Stmt *S,
236 CheckerContext &C) const {
237 auto State = C.getState();
238 const auto *Pos = getIteratorPosition(State, Val);
240 State = setIteratorPosition(State, Loc, *Pos);
241 C.addTransition(State);
243 const auto *OldPos = getIteratorPosition(State, Loc);
245 State = removeIteratorPosition(State, Loc);
246 C.addTransition(State);
251 void IteratorModeling::checkPostStmt(const UnaryOperator *UO,
252 CheckerContext &C) const {
253 UnaryOperatorKind OK = UO->getOpcode();
254 if (!isIncrementOperator(OK) && !isDecrementOperator(OK))
257 auto &SVB = C.getSValBuilder();
258 handlePtrIncrOrDecr(C, UO->getSubExpr(),
259 isIncrementOperator(OK) ? OO_Plus : OO_Minus,
260 SVB.makeArrayIndex(1));
263 void IteratorModeling::checkPostStmt(const BinaryOperator *BO,
264 CheckerContext &C) const {
265 ProgramStateRef State = C.getState();
266 BinaryOperatorKind OK = BO->getOpcode();
267 SVal RVal = State->getSVal(BO->getRHS(), C.getLocationContext());
269 if (isSimpleComparisonOperator(BO->getOpcode())) {
270 SVal LVal = State->getSVal(BO->getLHS(), C.getLocationContext());
271 SVal Result = State->getSVal(BO, C.getLocationContext());
272 handleComparison(C, BO, Result, LVal, RVal,
273 BinaryOperator::getOverloadedOperator(OK));
274 } else if (isRandomIncrOrDecrOperator(OK)) {
275 handlePtrIncrOrDecr(C, BO->getLHS(),
276 BinaryOperator::getOverloadedOperator(OK), RVal);
280 void IteratorModeling::checkPostStmt(const MaterializeTemporaryExpr *MTE,
281 CheckerContext &C) const {
282 /* Transfer iterator state to temporary objects */
283 auto State = C.getState();
284 const auto *Pos = getIteratorPosition(State, C.getSVal(MTE->getSubExpr()));
287 State = setIteratorPosition(State, C.getSVal(MTE), *Pos);
288 C.addTransition(State);
291 void IteratorModeling::checkLiveSymbols(ProgramStateRef State,
292 SymbolReaper &SR) const {
293 // Keep symbolic expressions of iterator positions alive
294 auto RegionMap = State->get<IteratorRegionMap>();
295 for (const auto &Reg : RegionMap) {
296 const auto Offset = Reg.second.getOffset();
297 for (auto i = Offset->symbol_begin(); i != Offset->symbol_end(); ++i)
298 if (isa<SymbolData>(*i))
302 auto SymbolMap = State->get<IteratorSymbolMap>();
303 for (const auto &Sym : SymbolMap) {
304 const auto Offset = Sym.second.getOffset();
305 for (auto i = Offset->symbol_begin(); i != Offset->symbol_end(); ++i)
306 if (isa<SymbolData>(*i))
312 void IteratorModeling::checkDeadSymbols(SymbolReaper &SR,
313 CheckerContext &C) const {
315 auto State = C.getState();
317 auto RegionMap = State->get<IteratorRegionMap>();
318 for (const auto &Reg : RegionMap) {
319 if (!SR.isLiveRegion(Reg.first)) {
320 // The region behind the `LazyCompoundVal` is often cleaned up before
321 // the `LazyCompoundVal` itself. If there are iterator positions keyed
322 // by these regions their cleanup must be deferred.
323 if (!isBoundThroughLazyCompoundVal(State->getEnvironment(), Reg.first)) {
324 State = State->remove<IteratorRegionMap>(Reg.first);
329 auto SymbolMap = State->get<IteratorSymbolMap>();
330 for (const auto &Sym : SymbolMap) {
331 if (!SR.isLive(Sym.first)) {
332 State = State->remove<IteratorSymbolMap>(Sym.first);
336 C.addTransition(State);
340 IteratorModeling::handleOverloadedOperator(CheckerContext &C,
341 const CallEvent &Call,
342 OverloadedOperatorKind Op) const {
343 if (isSimpleComparisonOperator(Op)) {
344 const auto *OrigExpr = Call.getOriginExpr();
348 if (const auto *InstCall = dyn_cast<CXXInstanceCall>(&Call)) {
349 handleComparison(C, OrigExpr, Call.getReturnValue(),
350 InstCall->getCXXThisVal(), Call.getArgSVal(0), Op);
354 handleComparison(C, OrigExpr, Call.getReturnValue(), Call.getArgSVal(0),
355 Call.getArgSVal(1), Op);
357 } else if (isRandomIncrOrDecrOperator(Op)) {
358 const auto *OrigExpr = Call.getOriginExpr();
362 if (const auto *InstCall = dyn_cast<CXXInstanceCall>(&Call)) {
363 if (Call.getNumArgs() >= 1 &&
364 Call.getArgExpr(0)->getType()->isIntegralOrEnumerationType()) {
365 handleRandomIncrOrDecr(C, OrigExpr, Op, Call.getReturnValue(),
366 InstCall->getCXXThisVal(), Call.getArgSVal(0));
370 if (Call.getNumArgs() >= 2 &&
371 Call.getArgExpr(1)->getType()->isIntegralOrEnumerationType()) {
372 handleRandomIncrOrDecr(C, OrigExpr, Op, Call.getReturnValue(),
373 Call.getArgSVal(0), Call.getArgSVal(1));
377 } else if (isIncrementOperator(Op)) {
378 if (const auto *InstCall = dyn_cast<CXXInstanceCall>(&Call)) {
379 handleIncrement(C, Call.getReturnValue(), InstCall->getCXXThisVal(),
384 handleIncrement(C, Call.getReturnValue(), Call.getArgSVal(0),
387 } else if (isDecrementOperator(Op)) {
388 if (const auto *InstCall = dyn_cast<CXXInstanceCall>(&Call)) {
389 handleDecrement(C, Call.getReturnValue(), InstCall->getCXXThisVal(),
394 handleDecrement(C, Call.getReturnValue(), Call.getArgSVal(0),
401 IteratorModeling::handleAdvanceLikeFunction(CheckerContext &C,
402 const CallEvent &Call,
403 const Expr *OrigExpr,
404 const AdvanceFn *Handler) const {
406 (this->**Handler)(C, OrigExpr, Call.getReturnValue(),
407 Call.getArgSVal(0), Call.getArgSVal(1));
411 // If std::advance() was inlined, but a non-standard function it calls inside
412 // was not, then we have to model it explicitly
413 const auto *IdInfo = cast<FunctionDecl>(Call.getDecl())->getIdentifier();
415 if (IdInfo->getName() == "advance") {
416 if (noChangeInAdvance(C, Call.getArgSVal(0), OrigExpr)) {
417 (this->**Handler)(C, OrigExpr, Call.getReturnValue(),
418 Call.getArgSVal(0), Call.getArgSVal(1));
424 void IteratorModeling::handleComparison(CheckerContext &C, const Expr *CE,
425 SVal RetVal, const SVal &LVal,
427 OverloadedOperatorKind Op) const {
428 // Record the operands and the operator of the comparison for the next
429 // evalAssume, if the result is a symbolic expression. If it is a concrete
430 // value (only one branch is possible), then transfer the state between
431 // the operands according to the operator and the result
432 auto State = C.getState();
433 const auto *LPos = getIteratorPosition(State, LVal);
434 const auto *RPos = getIteratorPosition(State, RVal);
435 const MemRegion *Cont = nullptr;
437 Cont = LPos->getContainer();
439 Cont = RPos->getContainer();
444 // At least one of the iterators has recorded positions. If one of them does
445 // not then create a new symbol for the offset.
447 if (!LPos || !RPos) {
448 auto &SymMgr = C.getSymbolManager();
449 Sym = SymMgr.conjureSymbol(CE, C.getLocationContext(),
450 C.getASTContext().LongTy, C.blockCount());
451 State = assumeNoOverflow(State, Sym, 4);
455 State = setIteratorPosition(State, LVal,
456 IteratorPosition::getPosition(Cont, Sym));
457 LPos = getIteratorPosition(State, LVal);
459 State = setIteratorPosition(State, RVal,
460 IteratorPosition::getPosition(Cont, Sym));
461 RPos = getIteratorPosition(State, RVal);
464 // We cannot make assumptions on `UnknownVal`. Let us conjure a symbol
466 if (RetVal.isUnknown()) {
467 auto &SymMgr = C.getSymbolManager();
468 auto *LCtx = C.getLocationContext();
469 RetVal = nonloc::SymbolVal(SymMgr.conjureSymbol(
470 CE, LCtx, C.getASTContext().BoolTy, C.blockCount()));
471 State = State->BindExpr(CE, LCtx, RetVal);
474 processComparison(C, State, LPos->getOffset(), RPos->getOffset(), RetVal, Op);
477 void IteratorModeling::processComparison(CheckerContext &C,
478 ProgramStateRef State, SymbolRef Sym1,
479 SymbolRef Sym2, const SVal &RetVal,
480 OverloadedOperatorKind Op) const {
481 if (const auto TruthVal = RetVal.getAs<nonloc::ConcreteInt>()) {
482 if ((State = relateSymbols(State, Sym1, Sym2,
483 (Op == OO_EqualEqual) ==
484 (TruthVal->getValue() != 0)))) {
485 C.addTransition(State);
487 C.generateSink(State, C.getPredecessor());
492 const auto ConditionVal = RetVal.getAs<DefinedSVal>();
496 if (auto StateTrue = relateSymbols(State, Sym1, Sym2, Op == OO_EqualEqual)) {
497 StateTrue = StateTrue->assume(*ConditionVal, true);
498 C.addTransition(StateTrue);
501 if (auto StateFalse = relateSymbols(State, Sym1, Sym2, Op != OO_EqualEqual)) {
502 StateFalse = StateFalse->assume(*ConditionVal, false);
503 C.addTransition(StateFalse);
507 void IteratorModeling::handleIncrement(CheckerContext &C, const SVal &RetVal,
508 const SVal &Iter, bool Postfix) const {
509 // Increment the symbolic expressions which represents the position of the
511 auto State = C.getState();
512 auto &BVF = C.getSymbolManager().getBasicVals();
514 const auto *Pos = getIteratorPosition(State, Iter);
519 advancePosition(State, Iter, OO_Plus,
520 nonloc::ConcreteInt(BVF.getValue(llvm::APSInt::get(1))));
522 "Advancing position by concrete int should always be successful");
524 const auto *NewPos = getIteratorPosition(NewState, Iter);
526 "Iterator should have position after successful advancement");
528 State = setIteratorPosition(State, Iter, *NewPos);
529 State = setIteratorPosition(State, RetVal, Postfix ? *Pos : *NewPos);
530 C.addTransition(State);
533 void IteratorModeling::handleDecrement(CheckerContext &C, const SVal &RetVal,
534 const SVal &Iter, bool Postfix) const {
535 // Decrement the symbolic expressions which represents the position of the
537 auto State = C.getState();
538 auto &BVF = C.getSymbolManager().getBasicVals();
540 const auto *Pos = getIteratorPosition(State, Iter);
545 advancePosition(State, Iter, OO_Minus,
546 nonloc::ConcreteInt(BVF.getValue(llvm::APSInt::get(1))));
548 "Advancing position by concrete int should always be successful");
550 const auto *NewPos = getIteratorPosition(NewState, Iter);
552 "Iterator should have position after successful advancement");
554 State = setIteratorPosition(State, Iter, *NewPos);
555 State = setIteratorPosition(State, RetVal, Postfix ? *Pos : *NewPos);
556 C.addTransition(State);
559 void IteratorModeling::handleRandomIncrOrDecr(CheckerContext &C,
561 OverloadedOperatorKind Op,
564 const SVal &RHS) const {
565 // Increment or decrement the symbolic expressions which represents the
566 // position of the iterator
567 auto State = C.getState();
569 const auto *Pos = getIteratorPosition(State, LHS);
573 const auto *value = &RHS;
575 if (auto loc = RHS.getAs<Loc>()) {
576 val = State->getRawSVal(*loc);
580 auto &TgtVal = (Op == OO_PlusEqual || Op == OO_MinusEqual) ? LHS : RetVal;
582 // `AdvancedState` is a state where the position of `LHS` is advanced. We
583 // only need this state to retrieve the new position, but we do not want
584 // to change the position of `LHS` (in every case).
585 auto AdvancedState = advancePosition(State, LHS, Op, *value);
587 const auto *NewPos = getIteratorPosition(AdvancedState, LHS);
589 "Iterator should have position after successful advancement");
591 State = setIteratorPosition(State, TgtVal, *NewPos);
592 C.addTransition(State);
594 assignToContainer(C, CE, TgtVal, Pos->getContainer());
598 void IteratorModeling::handlePtrIncrOrDecr(CheckerContext &C,
599 const Expr *Iterator,
600 OverloadedOperatorKind OK,
602 QualType PtrType = Iterator->getType();
603 if (!PtrType->isPointerType())
605 QualType ElementType = PtrType->getPointeeType();
607 ProgramStateRef State = C.getState();
608 SVal OldVal = State->getSVal(Iterator, C.getLocationContext());
610 const IteratorPosition *OldPos = getIteratorPosition(State, OldVal);
615 if (OK == OO_Plus || OK == OO_PlusEqual)
616 NewVal = State->getLValue(ElementType, Offset, OldVal);
618 const llvm::APSInt &OffsetInt =
619 Offset.castAs<nonloc::ConcreteInt>().getValue();
620 auto &BVF = C.getSymbolManager().getBasicVals();
621 SVal NegatedOffset = nonloc::ConcreteInt(BVF.getValue(-OffsetInt));
622 NewVal = State->getLValue(ElementType, NegatedOffset, OldVal);
625 // `AdvancedState` is a state where the position of `Old` is advanced. We
626 // only need this state to retrieve the new position, but we do not want
627 // ever to change the position of `OldVal`.
628 auto AdvancedState = advancePosition(State, OldVal, OK, Offset);
630 const IteratorPosition *NewPos = getIteratorPosition(AdvancedState, OldVal);
632 "Iterator should have position after successful advancement");
634 ProgramStateRef NewState = setIteratorPosition(State, NewVal, *NewPos);
635 C.addTransition(NewState);
637 assignToContainer(C, Iterator, NewVal, OldPos->getContainer());
641 void IteratorModeling::handleAdvance(CheckerContext &C, const Expr *CE,
642 SVal RetVal, SVal Iter,
644 handleRandomIncrOrDecr(C, CE, OO_PlusEqual, RetVal, Iter, Amount);
647 void IteratorModeling::handlePrev(CheckerContext &C, const Expr *CE,
648 SVal RetVal, SVal Iter, SVal Amount) const {
649 handleRandomIncrOrDecr(C, CE, OO_Minus, RetVal, Iter, Amount);
652 void IteratorModeling::handleNext(CheckerContext &C, const Expr *CE,
653 SVal RetVal, SVal Iter, SVal Amount) const {
654 handleRandomIncrOrDecr(C, CE, OO_Plus, RetVal, Iter, Amount);
657 void IteratorModeling::assignToContainer(CheckerContext &C, const Expr *CE,
659 const MemRegion *Cont) const {
660 Cont = Cont->getMostDerivedObjectRegion();
662 auto State = C.getState();
663 const auto *LCtx = C.getLocationContext();
664 State = createIteratorPosition(State, RetVal, Cont, CE, LCtx, C.blockCount());
666 C.addTransition(State);
669 bool IteratorModeling::noChangeInAdvance(CheckerContext &C, SVal Iter,
670 const Expr *CE) const {
671 // Compare the iterator position before and after the call. (To be called
672 // from `checkPostCall()`.)
673 const auto StateAfter = C.getState();
675 const auto *PosAfter = getIteratorPosition(StateAfter, Iter);
676 // If we have no position after the call of `std::advance`, then we are not
677 // interested. (Modeling of an inlined `std::advance()` should not remove the
678 // position in any case.)
682 const ExplodedNode *N = findCallEnter(C.getPredecessor(), CE);
683 assert(N && "Any call should have a `CallEnter` node.");
685 const auto StateBefore = N->getState();
686 const auto *PosBefore = getIteratorPosition(StateBefore, Iter);
688 assert(PosBefore && "`std::advance() should not create new iterator "
689 "position but change existing ones");
691 return PosBefore->getOffset() == PosAfter->getOffset();
694 void IteratorModeling::printState(raw_ostream &Out, ProgramStateRef State,
695 const char *NL, const char *Sep) const {
696 auto SymbolMap = State->get<IteratorSymbolMap>();
697 auto RegionMap = State->get<IteratorRegionMap>();
698 // Use a counter to add newlines before every line except the first one.
701 if (!SymbolMap.isEmpty() || !RegionMap.isEmpty()) {
702 Out << Sep << "Iterator Positions :" << NL;
703 for (const auto &Sym : SymbolMap) {
707 Sym.first->dumpToStream(Out);
709 const auto Pos = Sym.second;
710 Out << (Pos.isValid() ? "Valid" : "Invalid") << " ; Container == ";
711 Pos.getContainer()->dumpToStream(Out);
712 Out<<" ; Offset == ";
713 Pos.getOffset()->dumpToStream(Out);
716 for (const auto &Reg : RegionMap) {
720 Reg.first->dumpToStream(Out);
722 const auto Pos = Reg.second;
723 Out << (Pos.isValid() ? "Valid" : "Invalid") << " ; Container == ";
724 Pos.getContainer()->dumpToStream(Out);
725 Out<<" ; Offset == ";
726 Pos.getOffset()->dumpToStream(Out);
733 bool isSimpleComparisonOperator(OverloadedOperatorKind OK) {
734 return OK == OO_EqualEqual || OK == OO_ExclaimEqual;
737 bool isSimpleComparisonOperator(BinaryOperatorKind OK) {
738 return OK == BO_EQ || OK == BO_NE;
741 ProgramStateRef removeIteratorPosition(ProgramStateRef State, const SVal &Val) {
742 if (auto Reg = Val.getAsRegion()) {
743 Reg = Reg->getMostDerivedObjectRegion();
744 return State->remove<IteratorRegionMap>(Reg);
745 } else if (const auto Sym = Val.getAsSymbol()) {
746 return State->remove<IteratorSymbolMap>(Sym);
747 } else if (const auto LCVal = Val.getAs<nonloc::LazyCompoundVal>()) {
748 return State->remove<IteratorRegionMap>(LCVal->getRegion());
753 ProgramStateRef relateSymbols(ProgramStateRef State, SymbolRef Sym1,
754 SymbolRef Sym2, bool Equal) {
755 auto &SVB = State->getStateManager().getSValBuilder();
757 // FIXME: This code should be reworked as follows:
758 // 1. Subtract the operands using evalBinOp().
759 // 2. Assume that the result doesn't overflow.
760 // 3. Compare the result to 0.
761 // 4. Assume the result of the comparison.
762 const auto comparison =
763 SVB.evalBinOp(State, BO_EQ, nonloc::SymbolVal(Sym1),
764 nonloc::SymbolVal(Sym2), SVB.getConditionType());
766 assert(comparison.getAs<DefinedSVal>() &&
767 "Symbol comparison must be a `DefinedSVal`");
769 auto NewState = State->assume(comparison.castAs<DefinedSVal>(), Equal);
773 if (const auto CompSym = comparison.getAsSymbol()) {
774 assert(isa<SymIntExpr>(CompSym) &&
775 "Symbol comparison must be a `SymIntExpr`");
776 assert(BinaryOperator::isComparisonOp(
777 cast<SymIntExpr>(CompSym)->getOpcode()) &&
778 "Symbol comparison must be a comparison");
779 return assumeNoOverflow(NewState, cast<SymIntExpr>(CompSym)->getLHS(), 2);
785 bool isBoundThroughLazyCompoundVal(const Environment &Env,
786 const MemRegion *Reg) {
787 for (const auto &Binding : Env) {
788 if (const auto LCVal = Binding.second.getAs<nonloc::LazyCompoundVal>()) {
789 if (LCVal->getRegion() == Reg)
797 const ExplodedNode *findCallEnter(const ExplodedNode *Node, const Expr *Call) {
799 ProgramPoint PP = Node->getLocation();
800 if (auto Enter = PP.getAs<CallEnter>()) {
801 if (Enter->getCallExpr() == Call)
805 Node = Node->getFirstPred();
813 void ento::registerIteratorModeling(CheckerManager &mgr) {
814 mgr.registerChecker<IteratorModeling>();
817 bool ento::shouldRegisterIteratorModeling(const CheckerManager &mgr) {