PointerSubChecker.cpp 2.6 KB

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