Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
Line
Count
Source (jump to first uncovered line)
1
//=== UndefResultChecker.cpp ------------------------------------*- C++ -*-===//
2
//
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
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This defines UndefResultChecker, a builtin check in ExprEngine that
10
// performs checks for undefined results of non-assignment binary operators.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
15
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
16
#include "clang/StaticAnalyzer/Core/Checker.h"
17
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
18
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
19
#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
20
#include "llvm/ADT/SmallString.h"
21
#include "llvm/Support/raw_ostream.h"
22
23
using namespace clang;
24
using namespace ento;
25
26
namespace {
27
class UndefResultChecker
28
  : public Checker< check::PostStmt<BinaryOperator> > {
29
30
  mutable std::unique_ptr<BugType> BT;
31
32
public:
33
  void checkPostStmt(const BinaryOperator *B, CheckerContext &C) const;
34
};
35
} // end anonymous namespace
36
37
39
static bool isArrayIndexOutOfBounds(CheckerContext &C, const Expr *Ex) {
38
39
  ProgramStateRef state = C.getState();
39
39
40
39
  if (!isa<ArraySubscriptExpr>(Ex))
41
34
    return false;
42
5
43
5
  SVal Loc = C.getSVal(Ex);
44
5
  if (!Loc.isValid())
45
0
    return false;
46
5
47
5
  const MemRegion *MR = Loc.castAs<loc::MemRegionVal>().getRegion();
48
5
  const ElementRegion *ER = dyn_cast<ElementRegion>(MR);
49
5
  if (!ER)
50
0
    return false;
51
5
52
5
  DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
53
5
  DefinedOrUnknownSVal NumElements = C.getStoreManager().getSizeInElements(
54
5
      state, ER->getSuperRegion(), ER->getValueType());
55
5
  ProgramStateRef StInBound = state->assumeInBound(Idx, NumElements, true);
56
5
  ProgramStateRef StOutBound = state->assumeInBound(Idx, NumElements, false);
57
5
  return StOutBound && 
!StInBound1
;
58
5
}
59
60
10
static bool isShiftOverflow(const BinaryOperator *B, CheckerContext &C) {
61
10
  return C.isGreaterOrEqual(
62
10
      B->getRHS(), C.getASTContext().getIntWidth(B->getLHS()->getType()));
63
10
}
64
65
static bool isLeftShiftResultUnrepresentable(const BinaryOperator *B,
66
2
                                             CheckerContext &C) {
67
2
  SValBuilder &SB = C.getSValBuilder();
68
2
  ProgramStateRef State = C.getState();
69
2
  const llvm::APSInt *LHS = SB.getKnownValue(State, C.getSVal(B->getLHS()));
70
2
  const llvm::APSInt *RHS = SB.getKnownValue(State, C.getSVal(B->getRHS()));
71
2
  assert(LHS && RHS && "Values unknown, inconsistent state");
72
2
  return (unsigned)RHS->getZExtValue() > LHS->countLeadingZeros();
73
2
}
74
75
void UndefResultChecker::checkPostStmt(const BinaryOperator *B,
76
67.5k
                                       CheckerContext &C) const {
77
67.5k
  if (C.getSVal(B).isUndef()) {
78
54
79
54
    // Do not report assignments of uninitialized values inside swap functions.
80
54
    // This should allow to swap partially uninitialized structs
81
54
    // (radar://14129997)
82
54
    if (const FunctionDecl *EnclosingFunctionDecl =
83
51
        dyn_cast<FunctionDecl>(C.getStackFrame()->getDecl()))
84
51
      if (C.getCalleeName(EnclosingFunctionDecl) == "swap")
85
1
        return;
86
53
87
53
    // Generate an error node.
88
53
    ExplodedNode *N = C.generateErrorNode();
89
53
    if (!N)
90
0
      return;
91
53
92
53
    if (!BT)
93
27
      BT.reset(
94
27
          new BuiltinBug(this, "Result of operation is garbage or undefined"));
95
53
96
53
    SmallString<256> sbuf;
97
53
    llvm::raw_svector_ostream OS(sbuf);
98
53
    const Expr *Ex = nullptr;
99
53
    bool isLeft = true;
100
53
101
53
    if (C.getSVal(B->getLHS()).isUndef()) {
102
32
      Ex = B->getLHS()->IgnoreParenCasts();
103
32
      isLeft = true;
104
32
    }
105
21
    else if (C.getSVal(B->getRHS()).isUndef()) {
106
7
      Ex = B->getRHS()->IgnoreParenCasts();
107
7
      isLeft = false;
108
7
    }
109
53
110
53
    if (Ex) {
111
39
      OS << "The " << (isLeft ? 
"left"32
:
"right"7
) << " operand of '"
112
39
         << BinaryOperator::getOpcodeStr(B->getOpcode())
113
39
         << "' is a garbage value";
114
39
      if (isArrayIndexOutOfBounds(C, Ex))
115
1
        OS << " due to array index out of bounds";
116
39
    } else {
117
14
      // Neither operand was undefined, but the result is undefined.
118
14
      if ((B->getOpcode() == BinaryOperatorKind::BO_Shl ||
119
14
           
B->getOpcode() == BinaryOperatorKind::BO_Shr1
) &&
120
14
          
C.isNegative(B->getRHS())13
) {
121
3
        OS << "The result of the "
122
3
           << ((B->getOpcode() == BinaryOperatorKind::BO_Shl) ? "left"
123
3
                                                              : 
"right"0
)
124
3
           << " shift is undefined because the right operand is negative";
125
3
        Ex = B->getRHS();
126
11
      } else if ((B->getOpcode() == BinaryOperatorKind::BO_Shl ||
127
11
                  
B->getOpcode() == BinaryOperatorKind::BO_Shr1
) &&
128
11
                 
isShiftOverflow(B, C)10
) {
129
6
130
6
        OS << "The result of the "
131
6
           << ((B->getOpcode() == BinaryOperatorKind::BO_Shl) ? "left"
132
6
                                                              : 
"right"0
)
133
6
           << " shift is undefined due to shifting by ";
134
6
        Ex = B->getRHS();
135
6
136
6
        SValBuilder &SB = C.getSValBuilder();
137
6
        const llvm::APSInt *I =
138
6
            SB.getKnownValue(C.getState(), C.getSVal(B->getRHS()));
139
6
        if (!I)
140
0
          OS << "a value that is";
141
6
        else if (I->isUnsigned())
142
0
          OS << '\'' << I->getZExtValue() << "\', which is";
143
6
        else
144
6
          OS << '\'' << I->getSExtValue() << "\', which is";
145
6
146
6
        OS << " greater or equal to the width of type '"
147
6
           << B->getLHS()->getType().getAsString() << "'.";
148
6
      } else 
if (5
B->getOpcode() == BinaryOperatorKind::BO_Shl5
&&
149
5
                 
C.isNegative(B->getLHS())4
) {
150
2
        OS << "The result of the left shift is undefined because the left "
151
2
              "operand is negative";
152
2
        Ex = B->getLHS();
153
3
      } else if (B->getOpcode() == BinaryOperatorKind::BO_Shl &&
154
3
                 
isLeftShiftResultUnrepresentable(B, C)2
) {
155
2
        ProgramStateRef State = C.getState();
156
2
        SValBuilder &SB = C.getSValBuilder();
157
2
        const llvm::APSInt *LHS =
158
2
            SB.getKnownValue(State, C.getSVal(B->getLHS()));
159
2
        const llvm::APSInt *RHS =
160
2
            SB.getKnownValue(State, C.getSVal(B->getRHS()));
161
2
        OS << "The result of the left shift is undefined due to shifting \'"
162
2
           << LHS->getSExtValue() << "\' by \'" << RHS->getZExtValue()
163
2
           << "\', which is unrepresentable in the unsigned version of "
164
2
           << "the return type \'" << B->getLHS()->getType().getAsString()
165
2
           << "\'";
166
2
        Ex = B->getLHS();
167
2
      } else {
168
1
        OS << "The result of the '"
169
1
           << BinaryOperator::getOpcodeStr(B->getOpcode())
170
1
           << "' expression is undefined";
171
1
      }
172
14
    }
173
53
    auto report = llvm::make_unique<BugReport>(*BT, OS.str(), N);
174
53
    if (Ex) {
175
52
      report->addRange(Ex->getSourceRange());
176
52
      bugreporter::trackExpressionValue(N, Ex, *report);
177
52
    }
178
1
    else
179
1
      bugreporter::trackExpressionValue(N, B, *report);
180
53
181
53
    C.emitReport(std::move(report));
182
53
  }
183
67.5k
}
184
185
675
void ento::registerUndefResultChecker(CheckerManager &mgr) {
186
675
  mgr.registerChecker<UndefResultChecker>();
187
675
}
188
189
676
bool ento::shouldRegisterUndefResultChecker(const LangOptions &LO) {
190
676
  return true;
191
676
}