Coverage Report

Created: 2020-02-25 14:32

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