VirtualCallChecker.cpp 8.1 KB

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