PointerSubChecker.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //=== PointerSubChecker.cpp - Pointer subtraction 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 files defines PointerSubChecker, a builtin checker that checks for
  11. // pointer subtractions on two pointers pointing to different memory chunks.
  12. // This check corresponds to CWE-469.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "ClangSACheckers.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 PointerSubChecker
  24. : public Checker< check::PreStmt<BinaryOperator> > {
  25. mutable std::unique_ptr<BuiltinBug> BT;
  26. public:
  27. void checkPreStmt(const BinaryOperator *B, CheckerContext &C) const;
  28. };
  29. }
  30. void PointerSubChecker::checkPreStmt(const BinaryOperator *B,
  31. CheckerContext &C) const {
  32. // When doing pointer subtraction, if the two pointers do not point to the
  33. // same memory chunk, emit a warning.
  34. if (B->getOpcode() != BO_Sub)
  35. return;
  36. SVal LV = C.getSVal(B->getLHS());
  37. SVal RV = C.getSVal(B->getRHS());
  38. const MemRegion *LR = LV.getAsRegion();
  39. const MemRegion *RR = RV.getAsRegion();
  40. if (!(LR && RR))
  41. return;
  42. const MemRegion *BaseLR = LR->getBaseRegion();
  43. const MemRegion *BaseRR = RR->getBaseRegion();
  44. if (BaseLR == BaseRR)
  45. return;
  46. // Allow arithmetic on different symbolic regions.
  47. if (isa<SymbolicRegion>(BaseLR) || isa<SymbolicRegion>(BaseRR))
  48. return;
  49. if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
  50. if (!BT)
  51. BT.reset(
  52. new BuiltinBug(this, "Pointer subtraction",
  53. "Subtraction of two pointers that do not point to "
  54. "the same memory chunk may cause incorrect result."));
  55. auto R = llvm::make_unique<BugReport>(*BT, BT->getDescription(), N);
  56. R->addRange(B->getSourceRange());
  57. C.emitReport(std::move(R));
  58. }
  59. }
  60. void ento::registerPointerSubChecker(CheckerManager &mgr) {
  61. mgr.registerChecker<PointerSubChecker>();
  62. }