• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //== DivZeroChecker.cpp - Division by zero checker --------------*- C++ -*--==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This defines DivZeroChecker, a builtin check in ExprEngine that performs
11 // checks for division by zeros.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ClangSACheckers.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/BugReporter/BugType.h"
20 
21 using namespace clang;
22 using namespace ento;
23 
24 namespace {
25 class DivZeroChecker : public Checker< check::PreStmt<BinaryOperator> > {
26   mutable llvm::OwningPtr<BuiltinBug> BT;
27 public:
28   void checkPreStmt(const BinaryOperator *B, CheckerContext &C) const;
29 };
30 } // end anonymous namespace
31 
checkPreStmt(const BinaryOperator * B,CheckerContext & C) const32 void DivZeroChecker::checkPreStmt(const BinaryOperator *B,
33                                   CheckerContext &C) const {
34   BinaryOperator::Opcode Op = B->getOpcode();
35   if (Op != BO_Div &&
36       Op != BO_Rem &&
37       Op != BO_DivAssign &&
38       Op != BO_RemAssign)
39     return;
40 
41   if (!B->getRHS()->getType()->isIntegerType() ||
42       !B->getRHS()->getType()->isScalarType())
43     return;
44 
45   SVal Denom = C.getState()->getSVal(B->getRHS());
46   const DefinedSVal *DV = dyn_cast<DefinedSVal>(&Denom);
47 
48   // Divide-by-undefined handled in the generic checking for uses of
49   // undefined values.
50   if (!DV)
51     return;
52 
53   // Check for divide by zero.
54   ConstraintManager &CM = C.getConstraintManager();
55   const GRState *stateNotZero, *stateZero;
56   llvm::tie(stateNotZero, stateZero) = CM.assumeDual(C.getState(), *DV);
57 
58   if (stateZero && !stateNotZero) {
59     if (ExplodedNode *N = C.generateSink(stateZero)) {
60       if (!BT)
61         BT.reset(new BuiltinBug("Division by zero"));
62 
63       EnhancedBugReport *R =
64         new EnhancedBugReport(*BT, BT->getDescription(), N);
65 
66       R->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue,
67                            bugreporter::GetDenomExpr(N));
68 
69       C.EmitReport(R);
70     }
71     return;
72   }
73 
74   // If we get here, then the denom should not be zero. We abandon the implicit
75   // zero denom case for now.
76   C.addTransition(stateNotZero);
77 }
78 
registerDivZeroChecker(CheckerManager & mgr)79 void ento::registerDivZeroChecker(CheckerManager &mgr) {
80   mgr.registerChecker<DivZeroChecker>();
81 }
82