Coverage Report

Created: 2023-09-30 09:22

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Checkers/TestAfterDivZeroChecker.cpp
Line
Count
Source (jump to first uncovered line)
1
//== TestAfterDivZeroChecker.cpp - Test after division by zero checker --*--==//
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 TestAfterDivZeroChecker, a builtin check that performs checks
10
//  for division by zero where the division occurs before comparison with zero.
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/PathSensitive/CallEvent.h"
18
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
19
#include "llvm/ADT/FoldingSet.h"
20
#include <optional>
21
22
using namespace clang;
23
using namespace ento;
24
25
namespace {
26
27
class ZeroState {
28
private:
29
  SymbolRef ZeroSymbol;
30
  unsigned BlockID;
31
  const StackFrameContext *SFC;
32
33
public:
34
  ZeroState(SymbolRef S, unsigned B, const StackFrameContext *SFC)
35
446
      : ZeroSymbol(S), BlockID(B), SFC(SFC) {}
36
37
50
  const StackFrameContext *getStackFrameContext() const { return SFC; }
38
39
121
  bool operator==(const ZeroState &X) const {
40
121
    return BlockID == X.BlockID && 
SFC == X.SFC98
&&
ZeroSymbol == X.ZeroSymbol94
;
41
121
  }
42
43
42
  bool operator<(const ZeroState &X) const {
44
42
    if (BlockID != X.BlockID)
45
23
      return BlockID < X.BlockID;
46
19
    if (SFC != X.SFC)
47
4
      return SFC < X.SFC;
48
15
    return ZeroSymbol < X.ZeroSymbol;
49
19
  }
50
51
74
  void Profile(llvm::FoldingSetNodeID &ID) const {
52
74
    ID.AddInteger(BlockID);
53
74
    ID.AddPointer(SFC);
54
74
    ID.AddPointer(ZeroSymbol);
55
74
  }
56
};
57
58
class DivisionBRVisitor : public BugReporterVisitor {
59
private:
60
  SymbolRef ZeroSymbol;
61
  const StackFrameContext *SFC;
62
  bool Satisfied;
63
64
public:
65
  DivisionBRVisitor(SymbolRef ZeroSymbol, const StackFrameContext *SFC)
66
30
      : ZeroSymbol(ZeroSymbol), SFC(SFC), Satisfied(false) {}
67
68
30
  void Profile(llvm::FoldingSetNodeID &ID) const override {
69
30
    ID.Add(ZeroSymbol);
70
30
    ID.Add(SFC);
71
30
  }
72
73
  PathDiagnosticPieceRef VisitNode(const ExplodedNode *Succ,
74
                                   BugReporterContext &BRC,
75
                                   PathSensitiveBugReport &BR) override;
76
};
77
78
class TestAfterDivZeroChecker
79
    : public Checker<check::PreStmt<BinaryOperator>, check::BranchCondition,
80
                     check::EndFunction> {
81
  mutable std::unique_ptr<BugType> DivZeroBug;
82
  void reportBug(SVal Val, CheckerContext &C) const;
83
84
public:
85
  void checkPreStmt(const BinaryOperator *B, CheckerContext &C) const;
86
  void checkBranchCondition(const Stmt *Condition, CheckerContext &C) const;
87
  void checkEndFunction(const ReturnStmt *RS, CheckerContext &C) const;
88
  void setDivZeroMap(SVal Var, CheckerContext &C) const;
89
  bool hasDivZeroMap(SVal Var, const CheckerContext &C) const;
90
  bool isZero(SVal S, CheckerContext &C) const;
91
};
92
} // end anonymous namespace
93
94
REGISTER_SET_WITH_PROGRAMSTATE(DivZeroMap, ZeroState)
95
96
PathDiagnosticPieceRef
97
DivisionBRVisitor::VisitNode(const ExplodedNode *Succ, BugReporterContext &BRC,
98
907
                             PathSensitiveBugReport &BR) {
99
907
  if (Satisfied)
100
422
    return nullptr;
101
102
485
  const Expr *E = nullptr;
103
104
485
  if (std::optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
105
419
    if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>()) {
106
144
      BinaryOperator::Opcode Op = BO->getOpcode();
107
144
      if (Op == BO_Div || 
Op == BO_Rem112
||
Op == BO_DivAssign112
||
108
144
          
Op == BO_RemAssign112
) {
109
32
        E = BO->getRHS();
110
32
      }
111
144
    }
112
113
485
  if (!E)
114
453
    return nullptr;
115
116
32
  SVal S = Succ->getSVal(E);
117
32
  if (ZeroSymbol == S.getAsSymbol() && SFC == Succ->getStackFrame()) {
118
30
    Satisfied = true;
119
120
    // Construct a new PathDiagnosticPiece.
121
30
    ProgramPoint P = Succ->getLocation();
122
30
    PathDiagnosticLocation L =
123
30
        PathDiagnosticLocation::create(P, BRC.getSourceManager());
124
125
30
    if (!L.isValid() || !L.asLocation().isValid())
126
0
      return nullptr;
127
128
30
    return std::make_shared<PathDiagnosticEventPiece>(
129
30
        L, "Division with compared value made here");
130
30
  }
131
132
2
  return nullptr;
133
32
}
134
135
99
bool TestAfterDivZeroChecker::isZero(SVal S, CheckerContext &C) const {
136
99
  std::optional<DefinedSVal> DSV = S.getAs<DefinedSVal>();
137
138
99
  if (!DSV)
139
2
    return false;
140
141
97
  ConstraintManager &CM = C.getConstraintManager();
142
97
  return !CM.assume(C.getState(), *DSV, true);
143
99
}
144
145
93
void TestAfterDivZeroChecker::setDivZeroMap(SVal Var, CheckerContext &C) const {
146
93
  SymbolRef SR = Var.getAsSymbol();
147
93
  if (!SR)
148
25
    return;
149
150
68
  ProgramStateRef State = C.getState();
151
68
  State =
152
68
      State->add<DivZeroMap>(ZeroState(SR, C.getBlockID(), C.getStackFrame()));
153
68
  C.addTransition(State);
154
68
}
155
156
bool TestAfterDivZeroChecker::hasDivZeroMap(SVal Var,
157
1.04k
                                            const CheckerContext &C) const {
158
1.04k
  SymbolRef SR = Var.getAsSymbol();
159
1.04k
  if (!SR)
160
671
    return false;
161
162
378
  ZeroState ZS(SR, C.getBlockID(), C.getStackFrame());
163
378
  return C.getState()->contains<DivZeroMap>(ZS);
164
1.04k
}
165
166
30
void TestAfterDivZeroChecker::reportBug(SVal Val, CheckerContext &C) const {
167
30
  if (ExplodedNode *N = C.generateErrorNode(C.getState())) {
168
30
    if (!DivZeroBug)
169
2
      DivZeroBug.reset(new BugType(this, "Division by zero"));
170
171
30
    auto R = std::make_unique<PathSensitiveBugReport>(
172
30
        *DivZeroBug, "Value being compared against zero has already been used "
173
30
                     "for division",
174
30
        N);
175
176
30
    R->addVisitor(std::make_unique<DivisionBRVisitor>(Val.getAsSymbol(),
177
30
                                                       C.getStackFrame()));
178
30
    C.emitReport(std::move(R));
179
30
  }
180
30
}
181
182
void TestAfterDivZeroChecker::checkEndFunction(const ReturnStmt *,
183
1.76k
                                               CheckerContext &C) const {
184
1.76k
  ProgramStateRef State = C.getState();
185
186
1.76k
  DivZeroMapTy DivZeroes = State->get<DivZeroMap>();
187
1.76k
  if (DivZeroes.isEmpty())
188
1.71k
    return;
189
190
48
  DivZeroMapTy::Factory &F = State->get_context<DivZeroMap>();
191
50
  for (const ZeroState &ZS : DivZeroes) {
192
50
    if (ZS.getStackFrameContext() == C.getStackFrame())
193
46
      DivZeroes = F.remove(DivZeroes, ZS);
194
50
  }
195
48
  C.addTransition(State->set<DivZeroMap>(DivZeroes));
196
48
}
197
198
void TestAfterDivZeroChecker::checkPreStmt(const BinaryOperator *B,
199
2.16k
                                           CheckerContext &C) const {
200
2.16k
  BinaryOperator::Opcode Op = B->getOpcode();
201
2.16k
  if (Op == BO_Div || 
Op == BO_Rem2.09k
||
Op == BO_DivAssign2.08k
||
202
2.16k
      
Op == BO_RemAssign2.07k
) {
203
99
    SVal S = C.getSVal(B->getRHS());
204
205
99
    if (!isZero(S, C))
206
93
      setDivZeroMap(S, C);
207
99
  }
208
2.16k
}
209
210
void TestAfterDivZeroChecker::checkBranchCondition(const Stmt *Condition,
211
1.48k
                                                   CheckerContext &C) const {
212
1.48k
  if (const BinaryOperator *B = dyn_cast<BinaryOperator>(Condition)) {
213
864
    if (B->isComparisonOp()) {
214
842
      const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(B->getRHS());
215
842
      bool LRHS = true;
216
842
      if (!IntLiteral) {
217
550
        IntLiteral = dyn_cast<IntegerLiteral>(B->getLHS());
218
550
        LRHS = false;
219
550
      }
220
221
842
      if (!IntLiteral || 
IntLiteral->getValue() != 0304
)
222
740
        return;
223
224
102
      SVal Val = C.getSVal(LRHS ? 
B->getLHS()90
:
B->getRHS()12
);
225
102
      if (hasDivZeroMap(Val, C))
226
20
        reportBug(Val, C);
227
102
    }
228
864
  } else 
if (const UnaryOperator *624
U624
= dyn_cast<UnaryOperator>(Condition)) {
229
220
    if (U->getOpcode() == UO_LNot) {
230
220
      SVal Val;
231
220
      if (const ImplicitCastExpr *I =
232
220
              dyn_cast<ImplicitCastExpr>(U->getSubExpr()))
233
131
        Val = C.getSVal(I->getSubExpr());
234
235
220
      if (hasDivZeroMap(Val, C))
236
4
        reportBug(Val, C);
237
216
      else {
238
216
        Val = C.getSVal(U->getSubExpr());
239
216
        if (hasDivZeroMap(Val, C))
240
4
          reportBug(Val, C);
241
216
      }
242
220
    }
243
404
  } else if (const ImplicitCastExpr *IE =
244
404
                 dyn_cast<ImplicitCastExpr>(Condition)) {
245
256
    SVal Val = C.getSVal(IE->getSubExpr());
246
247
256
    if (hasDivZeroMap(Val, C))
248
1
      reportBug(Val, C);
249
255
    else {
250
255
      SVal Val = C.getSVal(Condition);
251
252
255
      if (hasDivZeroMap(Val, C))
253
1
        reportBug(Val, C);
254
255
    }
255
256
  }
256
1.48k
}
257
258
76
void ento::registerTestAfterDivZeroChecker(CheckerManager &mgr) {
259
76
  mgr.registerChecker<TestAfterDivZeroChecker>();
260
76
}
261
262
152
bool ento::shouldRegisterTestAfterDivZeroChecker(const CheckerManager &mgr) {
263
152
  return true;
264
152
}