clang 18.0.0git
TestAfterDivZeroChecker.cpp
Go to the documentation of this file.
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
19#include "llvm/ADT/FoldingSet.h"
20#include <optional>
21
22using namespace clang;
23using namespace ento;
24
25namespace {
26
27class ZeroState {
28private:
29 SymbolRef ZeroSymbol;
30 unsigned BlockID;
31 const StackFrameContext *SFC;
32
33public:
34 ZeroState(SymbolRef S, unsigned B, const StackFrameContext *SFC)
35 : ZeroSymbol(S), BlockID(B), SFC(SFC) {}
36
37 const StackFrameContext *getStackFrameContext() const { return SFC; }
38
39 bool operator==(const ZeroState &X) const {
40 return BlockID == X.BlockID && SFC == X.SFC && ZeroSymbol == X.ZeroSymbol;
41 }
42
43 bool operator<(const ZeroState &X) const {
44 if (BlockID != X.BlockID)
45 return BlockID < X.BlockID;
46 if (SFC != X.SFC)
47 return SFC < X.SFC;
48 return ZeroSymbol < X.ZeroSymbol;
49 }
50
51 void Profile(llvm::FoldingSetNodeID &ID) const {
52 ID.AddInteger(BlockID);
53 ID.AddPointer(SFC);
54 ID.AddPointer(ZeroSymbol);
55 }
56};
57
58class DivisionBRVisitor : public BugReporterVisitor {
59private:
60 SymbolRef ZeroSymbol;
61 const StackFrameContext *SFC;
62 bool Satisfied;
63
64public:
65 DivisionBRVisitor(SymbolRef ZeroSymbol, const StackFrameContext *SFC)
66 : ZeroSymbol(ZeroSymbol), SFC(SFC), Satisfied(false) {}
67
68 void Profile(llvm::FoldingSetNodeID &ID) const override {
69 ID.Add(ZeroSymbol);
70 ID.Add(SFC);
71 }
72
75 PathSensitiveBugReport &BR) override;
76};
77
78class 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
84public:
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
94REGISTER_SET_WITH_PROGRAMSTATE(DivZeroMap, ZeroState)
95
97DivisionBRVisitor::VisitNode(const ExplodedNode *Succ, BugReporterContext &BRC,
99 if (Satisfied)
100 return nullptr;
101
102 const Expr *E = nullptr;
103
104 if (std::optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
105 if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>()) {
106 BinaryOperator::Opcode Op = BO->getOpcode();
107 if (Op == BO_Div || Op == BO_Rem || Op == BO_DivAssign ||
108 Op == BO_RemAssign) {
109 E = BO->getRHS();
110 }
111 }
112
113 if (!E)
114 return nullptr;
115
116 SVal S = Succ->getSVal(E);
117 if (ZeroSymbol == S.getAsSymbol() && SFC == Succ->getStackFrame()) {
118 Satisfied = true;
119
120 // Construct a new PathDiagnosticPiece.
121 ProgramPoint P = Succ->getLocation();
124
125 if (!L.isValid() || !L.asLocation().isValid())
126 return nullptr;
127
128 return std::make_shared<PathDiagnosticEventPiece>(
129 L, "Division with compared value made here");
130 }
131
132 return nullptr;
133}
134
135bool TestAfterDivZeroChecker::isZero(SVal S, CheckerContext &C) const {
136 std::optional<DefinedSVal> DSV = S.getAs<DefinedSVal>();
137
138 if (!DSV)
139 return false;
140
141 ConstraintManager &CM = C.getConstraintManager();
142 return !CM.assume(C.getState(), *DSV, true);
143}
144
145void TestAfterDivZeroChecker::setDivZeroMap(SVal Var, CheckerContext &C) const {
146 SymbolRef SR = Var.getAsSymbol();
147 if (!SR)
148 return;
149
150 ProgramStateRef State = C.getState();
151 State =
152 State->add<DivZeroMap>(ZeroState(SR, C.getBlockID(), C.getStackFrame()));
153 C.addTransition(State);
154}
155
156bool TestAfterDivZeroChecker::hasDivZeroMap(SVal Var,
157 const CheckerContext &C) const {
158 SymbolRef SR = Var.getAsSymbol();
159 if (!SR)
160 return false;
161
162 ZeroState ZS(SR, C.getBlockID(), C.getStackFrame());
163 return C.getState()->contains<DivZeroMap>(ZS);
164}
165
166void TestAfterDivZeroChecker::reportBug(SVal Val, CheckerContext &C) const {
167 if (ExplodedNode *N = C.generateErrorNode(C.getState())) {
168 if (!DivZeroBug)
169 DivZeroBug.reset(new BugType(this, "Division by zero"));
170
171 auto R = std::make_unique<PathSensitiveBugReport>(
172 *DivZeroBug, "Value being compared against zero has already been used "
173 "for division",
174 N);
175
176 R->addVisitor(std::make_unique<DivisionBRVisitor>(Val.getAsSymbol(),
177 C.getStackFrame()));
178 C.emitReport(std::move(R));
179 }
180}
181
182void TestAfterDivZeroChecker::checkEndFunction(const ReturnStmt *,
183 CheckerContext &C) const {
184 ProgramStateRef State = C.getState();
185
186 DivZeroMapTy DivZeroes = State->get<DivZeroMap>();
187 if (DivZeroes.isEmpty())
188 return;
189
190 DivZeroMapTy::Factory &F = State->get_context<DivZeroMap>();
191 for (const ZeroState &ZS : DivZeroes) {
192 if (ZS.getStackFrameContext() == C.getStackFrame())
193 DivZeroes = F.remove(DivZeroes, ZS);
194 }
195 C.addTransition(State->set<DivZeroMap>(DivZeroes));
196}
197
198void TestAfterDivZeroChecker::checkPreStmt(const BinaryOperator *B,
199 CheckerContext &C) const {
201 if (Op == BO_Div || Op == BO_Rem || Op == BO_DivAssign ||
202 Op == BO_RemAssign) {
203 SVal S = C.getSVal(B->getRHS());
204
205 if (!isZero(S, C))
206 setDivZeroMap(S, C);
207 }
208}
209
210void TestAfterDivZeroChecker::checkBranchCondition(const Stmt *Condition,
211 CheckerContext &C) const {
212 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(Condition)) {
213 if (B->isComparisonOp()) {
214 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(B->getRHS());
215 bool LRHS = true;
216 if (!IntLiteral) {
217 IntLiteral = dyn_cast<IntegerLiteral>(B->getLHS());
218 LRHS = false;
219 }
220
221 if (!IntLiteral || IntLiteral->getValue() != 0)
222 return;
223
224 SVal Val = C.getSVal(LRHS ? B->getLHS() : B->getRHS());
225 if (hasDivZeroMap(Val, C))
226 reportBug(Val, C);
227 }
228 } else if (const UnaryOperator *U = dyn_cast<UnaryOperator>(Condition)) {
229 if (U->getOpcode() == UO_LNot) {
230 SVal Val;
231 if (const ImplicitCastExpr *I =
232 dyn_cast<ImplicitCastExpr>(U->getSubExpr()))
233 Val = C.getSVal(I->getSubExpr());
234
235 if (hasDivZeroMap(Val, C))
236 reportBug(Val, C);
237 else {
238 Val = C.getSVal(U->getSubExpr());
239 if (hasDivZeroMap(Val, C))
240 reportBug(Val, C);
241 }
242 }
243 } else if (const ImplicitCastExpr *IE =
244 dyn_cast<ImplicitCastExpr>(Condition)) {
245 SVal Val = C.getSVal(IE->getSubExpr());
246
247 if (hasDivZeroMap(Val, C))
248 reportBug(Val, C);
249 else {
250 SVal Val = C.getSVal(Condition);
251
252 if (hasDivZeroMap(Val, C))
253 reportBug(Val, C);
254 }
255 }
256}
257
258void ento::registerTestAfterDivZeroChecker(CheckerManager &mgr) {
259 mgr.registerChecker<TestAfterDivZeroChecker>();
260}
261
262bool ento::shouldRegisterTestAfterDivZeroChecker(const CheckerManager &mgr) {
263 return true;
264}
StringRef P
#define X(type, name)
Definition: Value.h:142
#define REGISTER_SET_WITH_PROGRAMSTATE(Name, Elem)
Declares an immutable set of type NameTy, suitable for placement into the ProgramState.
llvm::APInt getValue() const
Definition: Expr.h:1517
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3862
Expr * getLHS() const
Definition: Expr.h:3911
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:3961
Expr * getRHS() const
Definition: Expr.h:3913
Opcode getOpcode() const
Definition: Expr.h:3906
This represents one expression.
Definition: Expr.h:110
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3677
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3013
bool isValid() const
Return true if this is a valid SourceLocation object.
It represents a stack frame of the call stack (based on CallEvent).
Stmt - This represents one statement.
Definition: Stmt.h:84
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2210
const SourceManager & getSourceManager() const
Definition: BugReporter.h:721
BugReporterVisitors are used to add custom diagnostics along a path.
virtual void Profile(llvm::FoldingSetNodeID &ID) const =0
virtual PathDiagnosticPieceRef VisitNode(const ExplodedNode *Succ, BugReporterContext &BRC, PathSensitiveBugReport &BR)=0
Return a diagnostic piece which should be associated with the given node.
CHECKER * registerChecker(AT &&... Args)
Used to register checkers.
ProgramStateRef assume(ProgramStateRef state, DefinedSVal Cond, bool Assumption)
ProgramPoint getLocation() const
getLocation - Returns the edge associated with the given node.
const StackFrameContext * getStackFrame() const
SVal getSVal(const Stmt *S) const
Get the value of an arbitrary expression at this node.
std::optional< T > getLocationAs() const &
static PathDiagnosticLocation create(const Decl *D, const SourceManager &SM)
Create a location corresponding to the given declaration.
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition: SVals.h:55
SymbolRef getAsSymbol(bool IncludeBaseRegions=false) const
If this SVal wraps a symbol return that SymbolRef.
Definition: SVals.cpp:104
Symbolic value.
Definition: SymExpr.h:30
BlockID
The various types of blocks that can occur within a API notes file.
std::shared_ptr< PathDiagnosticPiece > PathDiagnosticPieceRef
BinaryOperatorKind
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition: CallGraph.h:207
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
#define false
Definition: stdbool.h:22