1 //=== UndefResultChecker.cpp ------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This defines UndefResultChecker, a builtin check in ExprEngine that
11 // performs checks for undefined results of non-assignment binary operators.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ClangSACheckers.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"
23 
24 using namespace clang;
25 using namespace ento;
26 
27 namespace {
28 class UndefResultChecker
29   : public Checker< check::PostStmt<BinaryOperator> > {
30 
31   mutable std::unique_ptr<BugType> BT;
32 
33 public:
34   void checkPostStmt(const BinaryOperator *B, CheckerContext &C) const;
35 };
36 } // end anonymous namespace
37 
38 static bool isArrayIndexOutOfBounds(CheckerContext &C, const Expr *Ex) {
39   ProgramStateRef state = C.getState();
40 
41   if (!isa<ArraySubscriptExpr>(Ex))
42     return false;
43 
44   SVal Loc = C.getSVal(Ex);
45   if (!Loc.isValid())
46     return false;
47 
48   const MemRegion *MR = Loc.castAs<loc::MemRegionVal>().getRegion();
49   const ElementRegion *ER = dyn_cast<ElementRegion>(MR);
50   if (!ER)
51     return false;
52 
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;
59 }
60 
61 static bool isShiftOverflow(const BinaryOperator *B, CheckerContext &C) {
62   return C.isGreaterOrEqual(
63       B->getRHS(), C.getASTContext().getIntWidth(B->getLHS()->getType()));
64 }
65 
66 void UndefResultChecker::checkPostStmt(const BinaryOperator *B,
67                                        CheckerContext &C) const {
68   if (C.getSVal(B).isUndef()) {
69 
70     // Do not report assignments of uninitialized values inside swap functions.
71     // This should allow to swap partially uninitialized structs
72     // (radar://14129997)
73     if (const FunctionDecl *EnclosingFunctionDecl =
74         dyn_cast<FunctionDecl>(C.getStackFrame()->getDecl()))
75       if (C.getCalleeName(EnclosingFunctionDecl) == "swap")
76         return;
77 
78     // Generate an error node.
79     ExplodedNode *N = C.generateErrorNode();
80     if (!N)
81       return;
82 
83     if (!BT)
84       BT.reset(
85           new BuiltinBug(this, "Result of operation is garbage or undefined"));
86 
87     SmallString<256> sbuf;
88     llvm::raw_svector_ostream OS(sbuf);
89     const Expr *Ex = nullptr;
90     bool isLeft = true;
91 
92     if (C.getSVal(B->getLHS()).isUndef()) {
93       Ex = B->getLHS()->IgnoreParenCasts();
94       isLeft = true;
95     }
96     else if (C.getSVal(B->getRHS()).isUndef()) {
97       Ex = B->getRHS()->IgnoreParenCasts();
98       isLeft = false;
99     }
100 
101     if (Ex) {
102       OS << "The " << (isLeft ? "left" : "right") << " operand of '"
103          << BinaryOperator::getOpcodeStr(B->getOpcode())
104          << "' is a garbage value";
105       if (isArrayIndexOutOfBounds(C, Ex))
106         OS << " due to array index out of bounds";
107     } else {
108       // Neither operand was undefined, but the result is undefined.
109       if ((B->getOpcode() == BinaryOperatorKind::BO_Shl ||
110            B->getOpcode() == BinaryOperatorKind::BO_Shr) &&
111           C.isNegative(B->getRHS())) {
112         OS << "The result of the "
113            << ((B->getOpcode() == BinaryOperatorKind::BO_Shl) ? "left"
114                                                               : "right")
115            << " shift is undefined because the right operand is negative";
116       } else if ((B->getOpcode() == BinaryOperatorKind::BO_Shl ||
117                   B->getOpcode() == BinaryOperatorKind::BO_Shr) &&
118                  isShiftOverflow(B, C)) {
119 
120         OS << "The result of the "
121            << ((B->getOpcode() == BinaryOperatorKind::BO_Shl) ? "left"
122                                                               : "right")
123            << " shift is undefined due to shifting by ";
124 
125         SValBuilder &SB = C.getSValBuilder();
126         const llvm::APSInt *I =
127             SB.getKnownValue(C.getState(), C.getSVal(B->getRHS()));
128         if (!I)
129           OS << "a value that is";
130         else if (I->isUnsigned())
131           OS << '\'' << I->getZExtValue() << "\', which is";
132         else
133           OS << '\'' << I->getSExtValue() << "\', which is";
134 
135         OS << " greater or equal to the width of type '"
136            << B->getLHS()->getType().getAsString() << "'.";
137       } else if (B->getOpcode() == BinaryOperatorKind::BO_Shl &&
138                  C.isNegative(B->getLHS())) {
139         OS << "The result of the left shift is undefined because the left "
140               "operand is negative";
141       } else {
142         OS << "The result of the '"
143            << BinaryOperator::getOpcodeStr(B->getOpcode())
144            << "' expression is undefined";
145       }
146     }
147     auto report = llvm::make_unique<BugReport>(*BT, OS.str(), N);
148     if (Ex) {
149       report->addRange(Ex->getSourceRange());
150       bugreporter::trackNullOrUndefValue(N, Ex, *report);
151     }
152     else
153       bugreporter::trackNullOrUndefValue(N, B, *report);
154 
155     C.emitReport(std::move(report));
156   }
157 }
158 
159 void ento::registerUndefResultChecker(CheckerManager &mgr) {
160   mgr.registerChecker<UndefResultChecker>();
161 }
162