UndefinedArraySubscriptChecker.cpp 2.4 KB

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