1 //=== UndefResultChecker.cpp ------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This defines UndefResultChecker, a builtin check in ExprEngine that
11 // performs checks for undefined results of non-assignment binary operators.
13 //===----------------------------------------------------------------------===//
15 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
16 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
17 #include "clang/StaticAnalyzer/Core/Checker.h"
18 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/Support/raw_ostream.h"
24 using namespace clang;
28 class UndefResultChecker
29 : public Checker< check::PostStmt<BinaryOperator> > {
31 mutable std::unique_ptr<BugType> BT;
34 void checkPostStmt(const BinaryOperator *B, CheckerContext &C) const;
36 } // end anonymous namespace
38 static bool isArrayIndexOutOfBounds(CheckerContext &C, const Expr *Ex) {
39 ProgramStateRef state = C.getState();
41 if (!isa<ArraySubscriptExpr>(Ex))
44 SVal Loc = C.getSVal(Ex);
48 const MemRegion *MR = Loc.castAs<loc::MemRegionVal>().getRegion();
49 const ElementRegion *ER = dyn_cast<ElementRegion>(MR);
53 DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
54 DefinedOrUnknownSVal NumElements = C.getStoreManager().getSizeInElements(
55 state, ER->getSuperRegion(), ER->getValueType());
56 ProgramStateRef StInBound = state->assumeInBound(Idx, NumElements, true);
57 ProgramStateRef StOutBound = state->assumeInBound(Idx, NumElements, false);
58 return StOutBound && !StInBound;
61 static bool isShiftOverflow(const BinaryOperator *B, CheckerContext &C) {
62 return C.isGreaterOrEqual(
63 B->getRHS(), C.getASTContext().getIntWidth(B->getLHS()->getType()));
66 static bool isLeftShiftResultUnrepresentable(const BinaryOperator *B,
68 SValBuilder &SB = C.getSValBuilder();
69 ProgramStateRef State = C.getState();
70 const llvm::APSInt *LHS = SB.getKnownValue(State, C.getSVal(B->getLHS()));
71 const llvm::APSInt *RHS = SB.getKnownValue(State, C.getSVal(B->getRHS()));
72 assert(LHS && RHS && "Values unknown, inconsistent state");
73 return (unsigned)RHS->getZExtValue() > LHS->countLeadingZeros();
76 void UndefResultChecker::checkPostStmt(const BinaryOperator *B,
77 CheckerContext &C) const {
78 if (C.getSVal(B).isUndef()) {
80 // Do not report assignments of uninitialized values inside swap functions.
81 // This should allow to swap partially uninitialized structs
83 if (const FunctionDecl *EnclosingFunctionDecl =
84 dyn_cast<FunctionDecl>(C.getStackFrame()->getDecl()))
85 if (C.getCalleeName(EnclosingFunctionDecl) == "swap")
88 // Generate an error node.
89 ExplodedNode *N = C.generateErrorNode();
95 new BuiltinBug(this, "Result of operation is garbage or undefined"));
97 SmallString<256> sbuf;
98 llvm::raw_svector_ostream OS(sbuf);
99 const Expr *Ex = nullptr;
102 if (C.getSVal(B->getLHS()).isUndef()) {
103 Ex = B->getLHS()->IgnoreParenCasts();
106 else if (C.getSVal(B->getRHS()).isUndef()) {
107 Ex = B->getRHS()->IgnoreParenCasts();
112 OS << "The " << (isLeft ? "left" : "right") << " operand of '"
113 << BinaryOperator::getOpcodeStr(B->getOpcode())
114 << "' is a garbage value";
115 if (isArrayIndexOutOfBounds(C, Ex))
116 OS << " due to array index out of bounds";
118 // Neither operand was undefined, but the result is undefined.
119 if ((B->getOpcode() == BinaryOperatorKind::BO_Shl ||
120 B->getOpcode() == BinaryOperatorKind::BO_Shr) &&
121 C.isNegative(B->getRHS())) {
122 OS << "The result of the "
123 << ((B->getOpcode() == BinaryOperatorKind::BO_Shl) ? "left"
125 << " shift is undefined because the right operand is negative";
127 } else if ((B->getOpcode() == BinaryOperatorKind::BO_Shl ||
128 B->getOpcode() == BinaryOperatorKind::BO_Shr) &&
129 isShiftOverflow(B, C)) {
131 OS << "The result of the "
132 << ((B->getOpcode() == BinaryOperatorKind::BO_Shl) ? "left"
134 << " shift is undefined due to shifting by ";
137 SValBuilder &SB = C.getSValBuilder();
138 const llvm::APSInt *I =
139 SB.getKnownValue(C.getState(), C.getSVal(B->getRHS()));
141 OS << "a value that is";
142 else if (I->isUnsigned())
143 OS << '\'' << I->getZExtValue() << "\', which is";
145 OS << '\'' << I->getSExtValue() << "\', which is";
147 OS << " greater or equal to the width of type '"
148 << B->getLHS()->getType().getAsString() << "'.";
149 } else if (B->getOpcode() == BinaryOperatorKind::BO_Shl &&
150 C.isNegative(B->getLHS())) {
151 OS << "The result of the left shift is undefined because the left "
152 "operand is negative";
154 } else if (B->getOpcode() == BinaryOperatorKind::BO_Shl &&
155 isLeftShiftResultUnrepresentable(B, C)) {
156 ProgramStateRef State = C.getState();
157 SValBuilder &SB = C.getSValBuilder();
158 const llvm::APSInt *LHS =
159 SB.getKnownValue(State, C.getSVal(B->getLHS()));
160 const llvm::APSInt *RHS =
161 SB.getKnownValue(State, C.getSVal(B->getRHS()));
162 OS << "The result of the left shift is undefined due to shifting \'"
163 << LHS->getSExtValue() << "\' by \'" << RHS->getZExtValue()
164 << "\', which is unrepresentable in the unsigned version of "
165 << "the return type \'" << B->getLHS()->getType().getAsString()
169 OS << "The result of the '"
170 << BinaryOperator::getOpcodeStr(B->getOpcode())
171 << "' expression is undefined";
174 auto report = llvm::make_unique<BugReport>(*BT, OS.str(), N);
176 report->addRange(Ex->getSourceRange());
177 bugreporter::trackExpressionValue(N, Ex, *report);
180 bugreporter::trackExpressionValue(N, B, *report);
182 C.emitReport(std::move(report));
186 void ento::registerUndefResultChecker(CheckerManager &mgr) {
187 mgr.registerChecker<UndefResultChecker>();