PointerArithChecker.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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/Checker.h"
  16. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  17. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  18. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  19. using namespace clang;
  20. using namespace ento;
  21. namespace {
  22. class PointerArithChecker
  23. : public Checker< check::PreStmt<BinaryOperator> > {
  24. mutable llvm::OwningPtr<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. const ProgramState *state = C.getState();
  34. SVal LV = state->getSVal(B->getLHS());
  35. SVal RV = state->getSVal(B->getRHS());
  36. const MemRegion *LR = LV.getAsRegion();
  37. if (!LR || !RV.isConstant())
  38. return;
  39. // If pointer arithmetic is done on variables of non-array type, this often
  40. // means behavior rely on memory organization, which is dangerous.
  41. if (isa<VarRegion>(LR) || isa<CodeTextRegion>(LR) ||
  42. isa<CompoundLiteralRegion>(LR)) {
  43. if (ExplodedNode *N = C.generateNode()) {
  44. if (!BT)
  45. BT.reset(new BuiltinBug("Dangerous pointer arithmetic",
  46. "Pointer arithmetic done on non-array variables "
  47. "means reliance on memory layout, which is "
  48. "dangerous."));
  49. BugReport *R = new BugReport(*BT, BT->getDescription(), N);
  50. R->addRange(B->getSourceRange());
  51. C.EmitReport(R);
  52. }
  53. }
  54. }
  55. void ento::registerPointerArithChecker(CheckerManager &mgr) {
  56. mgr.registerChecker<PointerArithChecker>();
  57. }