VirtualCallChecker.cpp 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. //=======- VirtualCallChecker.cpp --------------------------------*- 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 file defines a checker that checks virtual method calls during
  10. // construction or destruction of C++ objects.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  14. #include "clang/AST/DeclCXX.h"
  15. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  16. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  17. #include "clang/StaticAnalyzer/Core/Checker.h"
  18. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  19. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  20. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  21. #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
  22. using namespace clang;
  23. using namespace ento;
  24. namespace {
  25. enum class ObjectState : bool { CtorCalled, DtorCalled };
  26. } // end namespace
  27. // FIXME: Ascending over StackFrameContext maybe another method.
  28. namespace llvm {
  29. template <> struct FoldingSetTrait<ObjectState> {
  30. static inline void Profile(ObjectState X, FoldingSetNodeID &ID) {
  31. ID.AddInteger(static_cast<int>(X));
  32. }
  33. };
  34. } // end namespace llvm
  35. namespace {
  36. class VirtualCallChecker
  37. : public Checker<check::BeginFunction, check::EndFunction, check::PreCall> {
  38. public:
  39. // These are going to be null if the respective check is disabled.
  40. mutable std::unique_ptr<BugType> BT_Pure, BT_Impure;
  41. void checkBeginFunction(CheckerContext &C) const;
  42. void checkEndFunction(const ReturnStmt *RS, CheckerContext &C) const;
  43. void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
  44. private:
  45. void registerCtorDtorCallInState(bool IsBeginFunction,
  46. CheckerContext &C) const;
  47. };
  48. } // end namespace
  49. // GDM (generic data map) to the memregion of this for the ctor and dtor.
  50. REGISTER_MAP_WITH_PROGRAMSTATE(CtorDtorMap, const MemRegion *, ObjectState)
  51. // The function to check if a callexpr is a virtual method call.
  52. static bool isVirtualCall(const CallExpr *CE) {
  53. bool CallIsNonVirtual = false;
  54. if (const MemberExpr *CME = dyn_cast<MemberExpr>(CE->getCallee())) {
  55. // The member access is fully qualified (i.e., X::F).
  56. // Treat this as a non-virtual call and do not warn.
  57. if (CME->getQualifier())
  58. CallIsNonVirtual = true;
  59. if (const Expr *Base = CME->getBase()) {
  60. // The most derived class is marked final.
  61. if (Base->getBestDynamicClassType()->hasAttr<FinalAttr>())
  62. CallIsNonVirtual = true;
  63. }
  64. }
  65. const CXXMethodDecl *MD =
  66. dyn_cast_or_null<CXXMethodDecl>(CE->getDirectCallee());
  67. if (MD && MD->isVirtual() && !CallIsNonVirtual && !MD->hasAttr<FinalAttr>() &&
  68. !MD->getParent()->hasAttr<FinalAttr>())
  69. return true;
  70. return false;
  71. }
  72. // The BeginFunction callback when enter a constructor or a destructor.
  73. void VirtualCallChecker::checkBeginFunction(CheckerContext &C) const {
  74. registerCtorDtorCallInState(true, C);
  75. }
  76. // The EndFunction callback when leave a constructor or a destructor.
  77. void VirtualCallChecker::checkEndFunction(const ReturnStmt *RS,
  78. CheckerContext &C) const {
  79. registerCtorDtorCallInState(false, C);
  80. }
  81. void VirtualCallChecker::checkPreCall(const CallEvent &Call,
  82. CheckerContext &C) const {
  83. const auto MC = dyn_cast<CXXMemberCall>(&Call);
  84. if (!MC)
  85. return;
  86. const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Call.getDecl());
  87. if (!MD)
  88. return;
  89. ProgramStateRef State = C.getState();
  90. const CallExpr *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
  91. if (!isVirtualCall(CE))
  92. return;
  93. const MemRegion *Reg = MC->getCXXThisVal().getAsRegion();
  94. const ObjectState *ObState = State->get<CtorDtorMap>(Reg);
  95. if (!ObState)
  96. return;
  97. bool IsPure = MD->isPure();
  98. // At this point we're sure that we're calling a virtual method
  99. // during construction or destruction, so we'll emit a report.
  100. SmallString<128> Msg;
  101. llvm::raw_svector_ostream OS(Msg);
  102. OS << "Call to ";
  103. if (IsPure)
  104. OS << "pure ";
  105. OS << "virtual method '" << MD->getParent()->getNameAsString()
  106. << "::" << MD->getNameAsString() << "' during ";
  107. if (*ObState == ObjectState::CtorCalled)
  108. OS << "construction ";
  109. else
  110. OS << "destruction ";
  111. if (IsPure)
  112. OS << "has undefined behavior";
  113. else
  114. OS << "bypasses virtual dispatch";
  115. ExplodedNode *N =
  116. IsPure ? C.generateErrorNode() : C.generateNonFatalErrorNode();
  117. if (!N)
  118. return;
  119. const std::unique_ptr<BugType> &BT = IsPure ? BT_Pure : BT_Impure;
  120. if (!BT) {
  121. // The respective check is disabled.
  122. return;
  123. }
  124. auto Report = std::make_unique<BugReport>(*BT, OS.str(), N);
  125. C.emitReport(std::move(Report));
  126. }
  127. void VirtualCallChecker::registerCtorDtorCallInState(bool IsBeginFunction,
  128. CheckerContext &C) const {
  129. const auto *LCtx = C.getLocationContext();
  130. const auto *MD = dyn_cast_or_null<CXXMethodDecl>(LCtx->getDecl());
  131. if (!MD)
  132. return;
  133. ProgramStateRef State = C.getState();
  134. auto &SVB = C.getSValBuilder();
  135. // Enter a constructor, set the corresponding memregion be true.
  136. if (isa<CXXConstructorDecl>(MD)) {
  137. auto ThiSVal =
  138. State->getSVal(SVB.getCXXThis(MD, LCtx->getStackFrame()));
  139. const MemRegion *Reg = ThiSVal.getAsRegion();
  140. if (IsBeginFunction)
  141. State = State->set<CtorDtorMap>(Reg, ObjectState::CtorCalled);
  142. else
  143. State = State->remove<CtorDtorMap>(Reg);
  144. C.addTransition(State);
  145. return;
  146. }
  147. // Enter a Destructor, set the corresponding memregion be true.
  148. if (isa<CXXDestructorDecl>(MD)) {
  149. auto ThiSVal =
  150. State->getSVal(SVB.getCXXThis(MD, LCtx->getStackFrame()));
  151. const MemRegion *Reg = ThiSVal.getAsRegion();
  152. if (IsBeginFunction)
  153. State = State->set<CtorDtorMap>(Reg, ObjectState::DtorCalled);
  154. else
  155. State = State->remove<CtorDtorMap>(Reg);
  156. C.addTransition(State);
  157. return;
  158. }
  159. }
  160. void ento::registerVirtualCallModeling(CheckerManager &Mgr) {
  161. Mgr.registerChecker<VirtualCallChecker>();
  162. }
  163. void ento::registerPureVirtualCallChecker(CheckerManager &Mgr) {
  164. auto *Chk = Mgr.getChecker<VirtualCallChecker>();
  165. Chk->BT_Pure = std::make_unique<BugType>(
  166. Mgr.getCurrentCheckName(), "Pure virtual method call",
  167. categories::CXXObjectLifecycle);
  168. }
  169. void ento::registerVirtualCallChecker(CheckerManager &Mgr) {
  170. auto *Chk = Mgr.getChecker<VirtualCallChecker>();
  171. if (!Mgr.getAnalyzerOptions().getCheckerBooleanOption(
  172. Mgr.getCurrentCheckName(), "PureOnly")) {
  173. Chk->BT_Impure = std::make_unique<BugType>(
  174. Mgr.getCurrentCheckName(), "Unexpected loss of virtual dispatch",
  175. categories::CXXObjectLifecycle);
  176. }
  177. }
  178. bool ento::shouldRegisterVirtualCallModeling(const LangOptions &LO) {
  179. return LO.CPlusPlus;
  180. }
  181. bool ento::shouldRegisterPureVirtualCallChecker(const LangOptions &LO) {
  182. return LO.CPlusPlus;
  183. }
  184. bool ento::shouldRegisterVirtualCallChecker(const LangOptions &LO) {
  185. return LO.CPlusPlus;
  186. }