PointerArithChecker.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //=== PointerArithChecker.cpp - Pointer arithmetic 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 PointerArithChecker, a builtin checker that checks for
  11. // pointer arithmetic on locations other than array elements.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "ClangSACheckers.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 PointerArithChecker
  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 PointerArithChecker::checkPreStmt(const BinaryOperator *B,
  30. CheckerContext &C) const {
  31. if (B->getOpcode() != BO_Sub && B->getOpcode() != BO_Add)
  32. return;
  33. ProgramStateRef state = C.getState();
  34. const LocationContext *LCtx = C.getLocationContext();
  35. SVal LV = state->getSVal(B->getLHS(), LCtx);
  36. SVal RV = state->getSVal(B->getRHS(), LCtx);
  37. const MemRegion *LR = LV.getAsRegion();
  38. if (!LR || !RV.isConstant())
  39. return;
  40. // If pointer arithmetic is done on variables of non-array type, this often
  41. // means behavior rely on memory organization, which is dangerous.
  42. if (isa<VarRegion>(LR) || isa<CodeTextRegion>(LR) ||
  43. isa<CompoundLiteralRegion>(LR)) {
  44. if (ExplodedNode *N = C.addTransition()) {
  45. if (!BT)
  46. BT.reset(
  47. new BuiltinBug(this, "Dangerous pointer arithmetic",
  48. "Pointer arithmetic done on non-array variables "
  49. "means reliance on memory layout, which is "
  50. "dangerous."));
  51. auto R = llvm::make_unique<BugReport>(*BT, BT->getDescription(), N);
  52. R->addRange(B->getSourceRange());
  53. C.emitReport(std::move(R));
  54. }
  55. }
  56. }
  57. void ento::registerPointerArithChecker(CheckerManager &mgr) {
  58. mgr.registerChecker<PointerArithChecker>();
  59. }