FixedAddressChecker.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. //=== FixedAddressChecker.cpp - Fixed address usage 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 FixedAddressChecker, a builtin checker that checks for
  11. // assignment of a fixed address to a pointer.
  12. // This check corresponds to CWE-587.
  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 FixedAddressChecker
  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 FixedAddressChecker::checkPreStmt(const BinaryOperator *B,
  31. CheckerContext &C) const {
  32. // Using a fixed address is not portable because that address will probably
  33. // not be valid in all environments or platforms.
  34. if (B->getOpcode() != BO_Assign)
  35. return;
  36. QualType T = B->getType();
  37. if (!T->isPointerType())
  38. return;
  39. ProgramStateRef state = C.getState();
  40. SVal RV = state->getSVal(B->getRHS(), C.getLocationContext());
  41. if (!RV.isConstant() || RV.isZeroConstant())
  42. return;
  43. if (ExplodedNode *N = C.addTransition()) {
  44. if (!BT)
  45. BT.reset(
  46. new BuiltinBug(this, "Use fixed address",
  47. "Using a fixed address is not portable because that "
  48. "address will probably not be valid in all "
  49. "environments or platforms."));
  50. auto R = llvm::make_unique<BugReport>(*BT, BT->getDescription(), N);
  51. R->addRange(B->getRHS()->getSourceRange());
  52. C.emitReport(std::move(R));
  53. }
  54. }
  55. void ento::registerFixedAddressChecker(CheckerManager &mgr) {
  56. mgr.registerChecker<FixedAddressChecker>();
  57. }