1 //===--- UndefinedArraySubscriptChecker.h ----------------------*- 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 UndefinedArraySubscriptChecker, a builtin check in ExprEngine 11 // that performs checks for undefined array subscripts. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "ClangSACheckers.h" 16 #include "clang/AST/DeclCXX.h" 17 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 18 #include "clang/StaticAnalyzer/Core/Checker.h" 19 #include "clang/StaticAnalyzer/Core/CheckerManager.h" 20 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 21 22 using namespace clang; 23 using namespace ento; 24 25 namespace { 26 class UndefinedArraySubscriptChecker 27 : public Checker< check::PreStmt<ArraySubscriptExpr> > { 28 mutable OwningPtr<BugType> BT; 29 30 public: 31 void checkPreStmt(const ArraySubscriptExpr *A, CheckerContext &C) const; 32 }; 33 } // end anonymous namespace 34 35 void 36 UndefinedArraySubscriptChecker::checkPreStmt(const ArraySubscriptExpr *A, 37 CheckerContext &C) const { 38 const Expr *Index = A->getIdx(); 39 if (!C.getSVal(Index).isUndef()) 40 return; 41 42 // Sema generates anonymous array variables for copying array struct fields. 43 // Don't warn if we're in an implicitly-generated constructor. 44 const Decl *D = C.getLocationContext()->getDecl(); 45 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(D)) 46 if (Ctor->isDefaulted()) 47 return; 48 49 ExplodedNode *N = C.generateSink(); 50 if (!N) 51 return; 52 if (!BT) 53 BT.reset(new BuiltinBug("Array subscript is undefined")); 54 55 // Generate a report for this bug. 56 BugReport *R = new BugReport(*BT, BT->getName(), N); 57 R->addRange(A->getIdx()->getSourceRange()); 58 bugreporter::trackNullOrUndefValue(N, A->getIdx(), *R); 59 C.emitReport(R); 60 } 61 62 void ento::registerUndefinedArraySubscriptChecker(CheckerManager &mgr) { 63 mgr.registerChecker<UndefinedArraySubscriptChecker>(); 64 } 65