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/Checker.h"
  17. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  18. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  19. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  20. using namespace clang;
  21. using namespace ento;
  22. namespace {
  23. class PointerSubChecker
  24. : public Checker< check::PreStmt<BinaryOperator> > {
  25. mutable llvm::OwningPtr<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. const ProgramState *state = C.getState();
  37. SVal LV = state->getSVal(B->getLHS());
  38. SVal RV = state->getSVal(B->getRHS());
  39. const MemRegion *LR = LV.getAsRegion();
  40. const MemRegion *RR = RV.getAsRegion();
  41. if (!(LR && RR))
  42. return;
  43. const MemRegion *BaseLR = LR->getBaseRegion();
  44. const MemRegion *BaseRR = RR->getBaseRegion();
  45. if (BaseLR == BaseRR)
  46. return;
  47. // Allow arithmetic on different symbolic regions.
  48. if (isa<SymbolicRegion>(BaseLR) || isa<SymbolicRegion>(BaseRR))
  49. return;
  50. if (ExplodedNode *N = C.generateNode()) {
  51. if (!BT)
  52. BT.reset(new BuiltinBug("Pointer subtraction",
  53. "Subtraction of two pointers that do not point to "
  54. "the same memory chunk may cause incorrect result."));
  55. BugReport *R = new BugReport(*BT, BT->getDescription(), N);
  56. R->addRange(B->getSourceRange());
  57. C.EmitReport(R);
  58. }
  59. }
  60. void ento::registerPointerSubChecker(CheckerManager &mgr) {
  61. mgr.registerChecker<PointerSubChecker>();
  62. }