FixedAddressChecker.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //=== FixedAddressChecker.cpp - Fixed address usage checker ----*- C++ -*--===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This files defines FixedAddressChecker, a builtin checker that checks for
  10. // assignment of a fixed address to a pointer.
  11. // This check corresponds to CWE-587.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.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 FixedAddressChecker
  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 FixedAddressChecker::checkPreStmt(const BinaryOperator *B,
  30. CheckerContext &C) const {
  31. // Using a fixed address is not portable because that address will probably
  32. // not be valid in all environments or platforms.
  33. if (B->getOpcode() != BO_Assign)
  34. return;
  35. QualType T = B->getType();
  36. if (!T->isPointerType())
  37. return;
  38. SVal RV = C.getSVal(B->getRHS());
  39. if (!RV.isConstant() || RV.isZeroConstant())
  40. return;
  41. if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
  42. if (!BT)
  43. BT.reset(
  44. new BuiltinBug(this, "Use fixed address",
  45. "Using a fixed address is not portable because that "
  46. "address will probably not be valid in all "
  47. "environments or platforms."));
  48. auto R =
  49. std::make_unique<PathSensitiveBugReport>(*BT, BT->getDescription(), N);
  50. R->addRange(B->getRHS()->getSourceRange());
  51. C.emitReport(std::move(R));
  52. }
  53. }
  54. void ento::registerFixedAddressChecker(CheckerManager &mgr) {
  55. mgr.registerChecker<FixedAddressChecker>();
  56. }
  57. bool ento::shouldRegisterFixedAddressChecker(const CheckerManager &mgr) {
  58. return true;
  59. }