UndefinedArraySubscriptChecker.cpp 2.2 KB

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