TestAfterDivZeroChecker.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  14. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  15. #include "clang/StaticAnalyzer/Core/Checker.h"
  16. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  17. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  18. #include "llvm/ADT/FoldingSet.h"
  19. #include <optional>
  20. using namespace clang;
  21. using namespace ento;
  22. namespace {
  23. class ZeroState {
  24. private:
  25. SymbolRef ZeroSymbol;
  26. unsigned BlockID;
  27. const StackFrameContext *SFC;
  28. public:
  29. ZeroState(SymbolRef S, unsigned B, const StackFrameContext *SFC)
  30. : ZeroSymbol(S), BlockID(B), SFC(SFC) {}
  31. const StackFrameContext *getStackFrameContext() const { return SFC; }
  32. bool operator==(const ZeroState &X) const {
  33. return BlockID == X.BlockID && SFC == X.SFC && ZeroSymbol == X.ZeroSymbol;
  34. }
  35. bool operator<(const ZeroState &X) const {
  36. if (BlockID != X.BlockID)
  37. return BlockID < X.BlockID;
  38. if (SFC != X.SFC)
  39. return SFC < X.SFC;
  40. return ZeroSymbol < X.ZeroSymbol;
  41. }
  42. void Profile(llvm::FoldingSetNodeID &ID) const {
  43. ID.AddInteger(BlockID);
  44. ID.AddPointer(SFC);
  45. ID.AddPointer(ZeroSymbol);
  46. }
  47. };
  48. class DivisionBRVisitor : public BugReporterVisitor {
  49. private:
  50. SymbolRef ZeroSymbol;
  51. const StackFrameContext *SFC;
  52. bool Satisfied;
  53. public:
  54. DivisionBRVisitor(SymbolRef ZeroSymbol, const StackFrameContext *SFC)
  55. : ZeroSymbol(ZeroSymbol), SFC(SFC), Satisfied(false) {}
  56. void Profile(llvm::FoldingSetNodeID &ID) const override {
  57. ID.Add(ZeroSymbol);
  58. ID.Add(SFC);
  59. }
  60. PathDiagnosticPieceRef VisitNode(const ExplodedNode *Succ,
  61. BugReporterContext &BRC,
  62. PathSensitiveBugReport &BR) override;
  63. };
  64. class TestAfterDivZeroChecker
  65. : public Checker<check::PreStmt<BinaryOperator>, check::BranchCondition,
  66. check::EndFunction> {
  67. mutable std::unique_ptr<BuiltinBug> DivZeroBug;
  68. void reportBug(SVal Val, CheckerContext &C) const;
  69. public:
  70. void checkPreStmt(const BinaryOperator *B, CheckerContext &C) const;
  71. void checkBranchCondition(const Stmt *Condition, CheckerContext &C) const;
  72. void checkEndFunction(const ReturnStmt *RS, CheckerContext &C) const;
  73. void setDivZeroMap(SVal Var, CheckerContext &C) const;
  74. bool hasDivZeroMap(SVal Var, const CheckerContext &C) const;
  75. bool isZero(SVal S, CheckerContext &C) const;
  76. };
  77. } // end anonymous namespace
  78. REGISTER_SET_WITH_PROGRAMSTATE(DivZeroMap, ZeroState)
  79. PathDiagnosticPieceRef
  80. DivisionBRVisitor::VisitNode(const ExplodedNode *Succ, BugReporterContext &BRC,
  81. PathSensitiveBugReport &BR) {
  82. if (Satisfied)
  83. return nullptr;
  84. const Expr *E = nullptr;
  85. if (std::optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
  86. if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>()) {
  87. BinaryOperator::Opcode Op = BO->getOpcode();
  88. if (Op == BO_Div || Op == BO_Rem || Op == BO_DivAssign ||
  89. Op == BO_RemAssign) {
  90. E = BO->getRHS();
  91. }
  92. }
  93. if (!E)
  94. return nullptr;
  95. SVal S = Succ->getSVal(E);
  96. if (ZeroSymbol == S.getAsSymbol() && SFC == Succ->getStackFrame()) {
  97. Satisfied = true;
  98. // Construct a new PathDiagnosticPiece.
  99. ProgramPoint P = Succ->getLocation();
  100. PathDiagnosticLocation L =
  101. PathDiagnosticLocation::create(P, BRC.getSourceManager());
  102. if (!L.isValid() || !L.asLocation().isValid())
  103. return nullptr;
  104. return std::make_shared<PathDiagnosticEventPiece>(
  105. L, "Division with compared value made here");
  106. }
  107. return nullptr;
  108. }
  109. bool TestAfterDivZeroChecker::isZero(SVal S, CheckerContext &C) const {
  110. std::optional<DefinedSVal> DSV = S.getAs<DefinedSVal>();
  111. if (!DSV)
  112. return false;
  113. ConstraintManager &CM = C.getConstraintManager();
  114. return !CM.assume(C.getState(), *DSV, true);
  115. }
  116. void TestAfterDivZeroChecker::setDivZeroMap(SVal Var, CheckerContext &C) const {
  117. SymbolRef SR = Var.getAsSymbol();
  118. if (!SR)
  119. return;
  120. ProgramStateRef State = C.getState();
  121. State =
  122. State->add<DivZeroMap>(ZeroState(SR, C.getBlockID(), C.getStackFrame()));
  123. C.addTransition(State);
  124. }
  125. bool TestAfterDivZeroChecker::hasDivZeroMap(SVal Var,
  126. const CheckerContext &C) const {
  127. SymbolRef SR = Var.getAsSymbol();
  128. if (!SR)
  129. return false;
  130. ZeroState ZS(SR, C.getBlockID(), C.getStackFrame());
  131. return C.getState()->contains<DivZeroMap>(ZS);
  132. }
  133. void TestAfterDivZeroChecker::reportBug(SVal Val, CheckerContext &C) const {
  134. if (ExplodedNode *N = C.generateErrorNode(C.getState())) {
  135. if (!DivZeroBug)
  136. DivZeroBug.reset(new BuiltinBug(this, "Division by zero"));
  137. auto R = std::make_unique<PathSensitiveBugReport>(
  138. *DivZeroBug, "Value being compared against zero has already been used "
  139. "for division",
  140. N);
  141. R->addVisitor(std::make_unique<DivisionBRVisitor>(Val.getAsSymbol(),
  142. C.getStackFrame()));
  143. C.emitReport(std::move(R));
  144. }
  145. }
  146. void TestAfterDivZeroChecker::checkEndFunction(const ReturnStmt *,
  147. CheckerContext &C) const {
  148. ProgramStateRef State = C.getState();
  149. DivZeroMapTy DivZeroes = State->get<DivZeroMap>();
  150. if (DivZeroes.isEmpty())
  151. return;
  152. DivZeroMapTy::Factory &F = State->get_context<DivZeroMap>();
  153. for (llvm::ImmutableSet<ZeroState>::iterator I = DivZeroes.begin(),
  154. E = DivZeroes.end();
  155. I != E; ++I) {
  156. ZeroState ZS = *I;
  157. if (ZS.getStackFrameContext() == C.getStackFrame())
  158. DivZeroes = F.remove(DivZeroes, ZS);
  159. }
  160. C.addTransition(State->set<DivZeroMap>(DivZeroes));
  161. }
  162. void TestAfterDivZeroChecker::checkPreStmt(const BinaryOperator *B,
  163. CheckerContext &C) const {
  164. BinaryOperator::Opcode Op = B->getOpcode();
  165. if (Op == BO_Div || Op == BO_Rem || Op == BO_DivAssign ||
  166. Op == BO_RemAssign) {
  167. SVal S = C.getSVal(B->getRHS());
  168. if (!isZero(S, C))
  169. setDivZeroMap(S, C);
  170. }
  171. }
  172. void TestAfterDivZeroChecker::checkBranchCondition(const Stmt *Condition,
  173. CheckerContext &C) const {
  174. if (const BinaryOperator *B = dyn_cast<BinaryOperator>(Condition)) {
  175. if (B->isComparisonOp()) {
  176. const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(B->getRHS());
  177. bool LRHS = true;
  178. if (!IntLiteral) {
  179. IntLiteral = dyn_cast<IntegerLiteral>(B->getLHS());
  180. LRHS = false;
  181. }
  182. if (!IntLiteral || IntLiteral->getValue() != 0)
  183. return;
  184. SVal Val = C.getSVal(LRHS ? B->getLHS() : B->getRHS());
  185. if (hasDivZeroMap(Val, C))
  186. reportBug(Val, C);
  187. }
  188. } else if (const UnaryOperator *U = dyn_cast<UnaryOperator>(Condition)) {
  189. if (U->getOpcode() == UO_LNot) {
  190. SVal Val;
  191. if (const ImplicitCastExpr *I =
  192. dyn_cast<ImplicitCastExpr>(U->getSubExpr()))
  193. Val = C.getSVal(I->getSubExpr());
  194. if (hasDivZeroMap(Val, C))
  195. reportBug(Val, C);
  196. else {
  197. Val = C.getSVal(U->getSubExpr());
  198. if (hasDivZeroMap(Val, C))
  199. reportBug(Val, C);
  200. }
  201. }
  202. } else if (const ImplicitCastExpr *IE =
  203. dyn_cast<ImplicitCastExpr>(Condition)) {
  204. SVal Val = C.getSVal(IE->getSubExpr());
  205. if (hasDivZeroMap(Val, C))
  206. reportBug(Val, C);
  207. else {
  208. SVal Val = C.getSVal(Condition);
  209. if (hasDivZeroMap(Val, C))
  210. reportBug(Val, C);
  211. }
  212. }
  213. }
  214. void ento::registerTestAfterDivZeroChecker(CheckerManager &mgr) {
  215. mgr.registerChecker<TestAfterDivZeroChecker>();
  216. }
  217. bool ento::shouldRegisterTestAfterDivZeroChecker(const CheckerManager &mgr) {
  218. return true;
  219. }