CXXSelfAssignmentChecker.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //=== CXXSelfAssignmentChecker.cpp -----------------------------*- 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 file defines CXXSelfAssignmentChecker, which tests all custom defined
  11. // copy and move assignment operators for the case of self assignment, thus
  12. // where the parameter refers to the same location where the this pointer
  13. // points to. The checker itself does not do any checks at all, but it
  14. // causes the analyzer to check every copy and move assignment operator twice:
  15. // once for when 'this' aliases with the parameter and once for when it may not.
  16. // It is the task of the other enabled checkers to find the bugs in these two
  17. // different cases.
  18. //
  19. //===----------------------------------------------------------------------===//
  20. #include "ClangSACheckers.h"
  21. #include "clang/StaticAnalyzer/Core/Checker.h"
  22. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  23. using namespace clang;
  24. using namespace ento;
  25. namespace {
  26. class CXXSelfAssignmentChecker : public Checker<check::BeginFunction> {
  27. public:
  28. CXXSelfAssignmentChecker();
  29. void checkBeginFunction(CheckerContext &C) const;
  30. };
  31. }
  32. CXXSelfAssignmentChecker::CXXSelfAssignmentChecker() {}
  33. void CXXSelfAssignmentChecker::checkBeginFunction(CheckerContext &C) const {
  34. if (!C.inTopFrame())
  35. return;
  36. const auto *LCtx = C.getLocationContext();
  37. const auto *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
  38. if (!MD)
  39. return;
  40. if (!MD->isCopyAssignmentOperator() && !MD->isMoveAssignmentOperator())
  41. return;
  42. auto &State = C.getState();
  43. auto &SVB = C.getSValBuilder();
  44. auto ThisVal =
  45. State->getSVal(SVB.getCXXThis(MD, LCtx->getCurrentStackFrame()));
  46. auto Param = SVB.makeLoc(State->getRegion(MD->getParamDecl(0), LCtx));
  47. auto ParamVal = State->getSVal(Param);
  48. ProgramStateRef SelfAssignState = State->bindLoc(Param, ThisVal, LCtx);
  49. C.addTransition(SelfAssignState);
  50. ProgramStateRef NonSelfAssignState = State->bindLoc(Param, ParamVal, LCtx);
  51. C.addTransition(NonSelfAssignState);
  52. }
  53. void ento::registerCXXSelfAssignmentChecker(CheckerManager &Mgr) {
  54. Mgr.registerChecker<CXXSelfAssignmentChecker>();
  55. }