VirtualCallChecker.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. bool ShowFixIts = false;
  42. void checkBeginFunction(CheckerContext &C) const;
  43. void checkEndFunction(const ReturnStmt *RS, CheckerContext &C) const;
  44. void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
  45. private:
  46. void registerCtorDtorCallInState(bool IsBeginFunction,
  47. CheckerContext &C) const;
  48. };
  49. } // end namespace
  50. // GDM (generic data map) to the memregion of this for the ctor and dtor.
  51. REGISTER_MAP_WITH_PROGRAMSTATE(CtorDtorMap, const MemRegion *, ObjectState)
  52. // The function to check if a callexpr is a virtual method call.
  53. static bool isVirtualCall(const CallExpr *CE) {
  54. bool CallIsNonVirtual = false;
  55. if (const MemberExpr *CME = dyn_cast<MemberExpr>(CE->getCallee())) {
  56. // The member access is fully qualified (i.e., X::F).
  57. // Treat this as a non-virtual call and do not warn.
  58. if (CME->getQualifier())
  59. CallIsNonVirtual = true;
  60. if (const Expr *Base = CME->getBase()) {
  61. // The most derived class is marked final.
  62. if (Base->getBestDynamicClassType()->hasAttr<FinalAttr>())
  63. CallIsNonVirtual = true;
  64. }
  65. }
  66. const CXXMethodDecl *MD =
  67. dyn_cast_or_null<CXXMethodDecl>(CE->getDirectCallee());
  68. if (MD && MD->isVirtual() && !CallIsNonVirtual && !MD->hasAttr<FinalAttr>() &&
  69. !MD->getParent()->hasAttr<FinalAttr>())
  70. return true;
  71. return false;
  72. }
  73. // The BeginFunction callback when enter a constructor or a destructor.
  74. void VirtualCallChecker::checkBeginFunction(CheckerContext &C) const {
  75. registerCtorDtorCallInState(true, C);
  76. }
  77. // The EndFunction callback when leave a constructor or a destructor.
  78. void VirtualCallChecker::checkEndFunction(const ReturnStmt *RS,
  79. CheckerContext &C) const {
  80. registerCtorDtorCallInState(false, C);
  81. }
  82. void VirtualCallChecker::checkPreCall(const CallEvent &Call,
  83. CheckerContext &C) const {
  84. const auto MC = dyn_cast<CXXMemberCall>(&Call);
  85. if (!MC)
  86. return;
  87. const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Call.getDecl());
  88. if (!MD)
  89. return;
  90. ProgramStateRef State = C.getState();
  91. // Member calls are always represented by a call-expression.
  92. const auto *CE = cast<CallExpr>(Call.getOriginExpr());
  93. if (!isVirtualCall(CE))
  94. return;
  95. const MemRegion *Reg = MC->getCXXThisVal().getAsRegion();
  96. const ObjectState *ObState = State->get<CtorDtorMap>(Reg);
  97. if (!ObState)
  98. return;
  99. bool IsPure = MD->isPure();
  100. // At this point we're sure that we're calling a virtual method
  101. // during construction or destruction, so we'll emit a report.
  102. SmallString<128> Msg;
  103. llvm::raw_svector_ostream OS(Msg);
  104. OS << "Call to ";
  105. if (IsPure)
  106. OS << "pure ";
  107. OS << "virtual method '" << MD->getParent()->getNameAsString()
  108. << "::" << MD->getNameAsString() << "' during ";
  109. if (*ObState == ObjectState::CtorCalled)
  110. OS << "construction ";
  111. else
  112. OS << "destruction ";
  113. if (IsPure)
  114. OS << "has undefined behavior";
  115. else
  116. OS << "bypasses virtual dispatch";
  117. ExplodedNode *N =
  118. IsPure ? C.generateErrorNode() : C.generateNonFatalErrorNode();
  119. if (!N)
  120. return;
  121. const std::unique_ptr<BugType> &BT = IsPure ? BT_Pure : BT_Impure;
  122. if (!BT) {
  123. // The respective check is disabled.
  124. return;
  125. }
  126. auto Report = std::make_unique<PathSensitiveBugReport>(*BT, OS.str(), N);
  127. if (ShowFixIts && !IsPure) {
  128. // FIXME: These hints are valid only when the virtual call is made
  129. // directly from the constructor/destructor. Otherwise the dispatch
  130. // will work just fine from other callees, and the fix may break
  131. // the otherwise correct program.
  132. FixItHint Fixit = FixItHint::CreateInsertion(
  133. CE->getBeginLoc(), MD->getParent()->getNameAsString() + "::");
  134. Report->addFixItHint(Fixit);
  135. }
  136. C.emitReport(std::move(Report));
  137. }
  138. void VirtualCallChecker::registerCtorDtorCallInState(bool IsBeginFunction,
  139. CheckerContext &C) const {
  140. const auto *LCtx = C.getLocationContext();
  141. const auto *MD = dyn_cast_or_null<CXXMethodDecl>(LCtx->getDecl());
  142. if (!MD)
  143. return;
  144. ProgramStateRef State = C.getState();
  145. auto &SVB = C.getSValBuilder();
  146. // Enter a constructor, set the corresponding memregion be true.
  147. if (isa<CXXConstructorDecl>(MD)) {
  148. auto ThiSVal =
  149. State->getSVal(SVB.getCXXThis(MD, LCtx->getStackFrame()));
  150. const MemRegion *Reg = ThiSVal.getAsRegion();
  151. if (IsBeginFunction)
  152. State = State->set<CtorDtorMap>(Reg, ObjectState::CtorCalled);
  153. else
  154. State = State->remove<CtorDtorMap>(Reg);
  155. C.addTransition(State);
  156. return;
  157. }
  158. // Enter a Destructor, set the corresponding memregion be true.
  159. if (isa<CXXDestructorDecl>(MD)) {
  160. auto ThiSVal =
  161. State->getSVal(SVB.getCXXThis(MD, LCtx->getStackFrame()));
  162. const MemRegion *Reg = ThiSVal.getAsRegion();
  163. if (IsBeginFunction)
  164. State = State->set<CtorDtorMap>(Reg, ObjectState::DtorCalled);
  165. else
  166. State = State->remove<CtorDtorMap>(Reg);
  167. C.addTransition(State);
  168. return;
  169. }
  170. }
  171. void ento::registerVirtualCallModeling(CheckerManager &Mgr) {
  172. Mgr.registerChecker<VirtualCallChecker>();
  173. }
  174. void ento::registerPureVirtualCallChecker(CheckerManager &Mgr) {
  175. auto *Chk = Mgr.getChecker<VirtualCallChecker>();
  176. Chk->BT_Pure = std::make_unique<BugType>(Mgr.getCurrentCheckerName(),
  177. "Pure virtual method call",
  178. categories::CXXObjectLifecycle);
  179. }
  180. void ento::registerVirtualCallChecker(CheckerManager &Mgr) {
  181. auto *Chk = Mgr.getChecker<VirtualCallChecker>();
  182. if (!Mgr.getAnalyzerOptions().getCheckerBooleanOption(
  183. Mgr.getCurrentCheckerName(), "PureOnly")) {
  184. Chk->BT_Impure = std::make_unique<BugType>(
  185. Mgr.getCurrentCheckerName(), "Unexpected loss of virtual dispatch",
  186. categories::CXXObjectLifecycle);
  187. Chk->ShowFixIts = Mgr.getAnalyzerOptions().getCheckerBooleanOption(
  188. Mgr.getCurrentCheckerName(), "ShowFixIts");
  189. }
  190. }
  191. bool ento::shouldRegisterVirtualCallModeling(const LangOptions &LO) {
  192. return LO.CPlusPlus;
  193. }
  194. bool ento::shouldRegisterPureVirtualCallChecker(const LangOptions &LO) {
  195. return LO.CPlusPlus;
  196. }
  197. bool ento::shouldRegisterVirtualCallChecker(const LangOptions &LO) {
  198. return LO.CPlusPlus;
  199. }