PointerSubChecker.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. ProgramStateRef state = C.getState();
  37. const LocationContext *LCtx = C.getLocationContext();
  38. SVal LV = state->getSVal(B->getLHS(), LCtx);
  39. SVal RV = state->getSVal(B->getRHS(), LCtx);
  40. const MemRegion *LR = LV.getAsRegion();
  41. const MemRegion *RR = RV.getAsRegion();
  42. if (!(LR && RR))
  43. return;
  44. const MemRegion *BaseLR = LR->getBaseRegion();
  45. const MemRegion *BaseRR = RR->getBaseRegion();
  46. if (BaseLR == BaseRR)
  47. return;
  48. // Allow arithmetic on different symbolic regions.
  49. if (isa<SymbolicRegion>(BaseLR) || isa<SymbolicRegion>(BaseRR))
  50. return;
  51. if (ExplodedNode *N = C.addTransition()) {
  52. if (!BT)
  53. BT.reset(
  54. new BuiltinBug(this, "Pointer subtraction",
  55. "Subtraction of two pointers that do not point to "
  56. "the same memory chunk may cause incorrect result."));
  57. auto R = llvm::make_unique<BugReport>(*BT, BT->getDescription(), N);
  58. R->addRange(B->getSourceRange());
  59. C.emitReport(std::move(R));
  60. }
  61. }
  62. void ento::registerPointerSubChecker(CheckerManager &mgr) {
  63. mgr.registerChecker<PointerSubChecker>();
  64. }