1 //=======- VirtualCallChecker.cpp --------------------------------*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a checker that checks virtual function calls during
11 // construction or destruction of C++ objects.
13 //===----------------------------------------------------------------------===//
15 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
18 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
19 #include "clang/StaticAnalyzer/Core/Checker.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
25 using namespace clang;
29 enum class ObjectState : bool { CtorCalled, DtorCalled };
31 // FIXME: Ascending over StackFrameContext maybe another method.
34 template <> struct FoldingSetTrait<ObjectState> {
35 static inline void Profile(ObjectState X, FoldingSetNodeID &ID) {
36 ID.AddInteger(static_cast<int>(X));
39 } // end namespace llvm
42 class VirtualCallChecker
43 : public Checker<check::BeginFunction, check::EndFunction, check::PreCall> {
44 mutable std::unique_ptr<BugType> BT;
47 // The flag to determine if pure virtual functions should be issued only.
48 DefaultBool IsPureOnly;
50 void checkBeginFunction(CheckerContext &C) const;
51 void checkEndFunction(const ReturnStmt *RS, CheckerContext &C) const;
52 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
55 void registerCtorDtorCallInState(bool IsBeginFunction,
56 CheckerContext &C) const;
57 void reportBug(StringRef Msg, bool PureError, const MemRegion *Reg,
58 CheckerContext &C) const;
60 class VirtualBugVisitor : public BugReporterVisitor {
62 const MemRegion *ObjectRegion;
66 VirtualBugVisitor(const MemRegion *R) : ObjectRegion(R), Found(false) {}
68 void Profile(llvm::FoldingSetNodeID &ID) const override {
71 ID.AddPointer(ObjectRegion);
74 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
75 BugReporterContext &BRC,
76 BugReport &BR) override;
81 // GDM (generic data map) to the memregion of this for the ctor and dtor.
82 REGISTER_MAP_WITH_PROGRAMSTATE(CtorDtorMap, const MemRegion *, ObjectState)
84 std::shared_ptr<PathDiagnosticPiece>
85 VirtualCallChecker::VirtualBugVisitor::VisitNode(const ExplodedNode *N,
86 BugReporterContext &BRC,
88 // We need the last ctor/dtor which call the virtual function.
89 // The visitor walks the ExplodedGraph backwards.
93 ProgramStateRef State = N->getState();
94 const LocationContext *LCtx = N->getLocationContext();
95 const CXXConstructorDecl *CD =
96 dyn_cast_or_null<CXXConstructorDecl>(LCtx->getDecl());
97 const CXXDestructorDecl *DD =
98 dyn_cast_or_null<CXXDestructorDecl>(LCtx->getDecl());
103 ProgramStateManager &PSM = State->getStateManager();
104 auto &SVB = PSM.getSValBuilder();
105 const auto *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
109 State->getSVal(SVB.getCXXThis(MD, LCtx->getStackFrame()));
110 const MemRegion *Reg = ThiSVal.castAs<loc::MemRegionVal>().getRegion();
113 if (Reg != ObjectRegion)
116 const Stmt *S = PathDiagnosticLocation::getStmt(N);
121 std::string InfoText;
123 InfoText = "This constructor of an object of type '" +
124 CD->getNameAsString() +
125 "' has not returned when the virtual method was called";
127 InfoText = "This destructor of an object of type '" +
128 DD->getNameAsString() +
129 "' has not returned when the virtual method was called";
131 // Generate the extra diagnostic.
132 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
133 N->getLocationContext());
134 return std::make_shared<PathDiagnosticEventPiece>(Pos, InfoText, true);
137 // The function to check if a callexpr is a virtual function.
138 static bool isVirtualCall(const CallExpr *CE) {
139 bool CallIsNonVirtual = false;
141 if (const MemberExpr *CME = dyn_cast<MemberExpr>(CE->getCallee())) {
142 // The member access is fully qualified (i.e., X::F).
143 // Treat this as a non-virtual call and do not warn.
144 if (CME->getQualifier())
145 CallIsNonVirtual = true;
147 if (const Expr *Base = CME->getBase()) {
148 // The most derived class is marked final.
149 if (Base->getBestDynamicClassType()->hasAttr<FinalAttr>())
150 CallIsNonVirtual = true;
154 const CXXMethodDecl *MD =
155 dyn_cast_or_null<CXXMethodDecl>(CE->getDirectCallee());
156 if (MD && MD->isVirtual() && !CallIsNonVirtual && !MD->hasAttr<FinalAttr>() &&
157 !MD->getParent()->hasAttr<FinalAttr>())
162 // The BeginFunction callback when enter a constructor or a destructor.
163 void VirtualCallChecker::checkBeginFunction(CheckerContext &C) const {
164 registerCtorDtorCallInState(true, C);
167 // The EndFunction callback when leave a constructor or a destructor.
168 void VirtualCallChecker::checkEndFunction(const ReturnStmt *RS,
169 CheckerContext &C) const {
170 registerCtorDtorCallInState(false, C);
173 void VirtualCallChecker::checkPreCall(const CallEvent &Call,
174 CheckerContext &C) const {
175 const auto MC = dyn_cast<CXXMemberCall>(&Call);
179 const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Call.getDecl());
182 ProgramStateRef State = C.getState();
183 const CallExpr *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
185 if (IsPureOnly && !MD->isPure())
187 if (!isVirtualCall(CE))
190 const MemRegion *Reg = MC->getCXXThisVal().getAsRegion();
191 const ObjectState *ObState = State->get<CtorDtorMap>(Reg);
194 // Check if a virtual method is called.
195 // The GDM of constructor and destructor should be true.
196 if (*ObState == ObjectState::CtorCalled) {
197 if (IsPureOnly && MD->isPure())
198 reportBug("Call to pure virtual function during construction", true, Reg,
200 else if (!MD->isPure())
201 reportBug("Call to virtual function during construction", false, Reg, C);
203 reportBug("Call to pure virtual function during construction", false, Reg,
207 if (*ObState == ObjectState::DtorCalled) {
208 if (IsPureOnly && MD->isPure())
209 reportBug("Call to pure virtual function during destruction", true, Reg,
211 else if (!MD->isPure())
212 reportBug("Call to virtual function during destruction", false, Reg, C);
214 reportBug("Call to pure virtual function during construction", false, Reg,
219 void VirtualCallChecker::registerCtorDtorCallInState(bool IsBeginFunction,
220 CheckerContext &C) const {
221 const auto *LCtx = C.getLocationContext();
222 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(LCtx->getDecl());
226 ProgramStateRef State = C.getState();
227 auto &SVB = C.getSValBuilder();
229 // Enter a constructor, set the corresponding memregion be true.
230 if (isa<CXXConstructorDecl>(MD)) {
232 State->getSVal(SVB.getCXXThis(MD, LCtx->getStackFrame()));
233 const MemRegion *Reg = ThiSVal.getAsRegion();
235 State = State->set<CtorDtorMap>(Reg, ObjectState::CtorCalled);
237 State = State->remove<CtorDtorMap>(Reg);
239 C.addTransition(State);
243 // Enter a Destructor, set the corresponding memregion be true.
244 if (isa<CXXDestructorDecl>(MD)) {
246 State->getSVal(SVB.getCXXThis(MD, LCtx->getStackFrame()));
247 const MemRegion *Reg = ThiSVal.getAsRegion();
249 State = State->set<CtorDtorMap>(Reg, ObjectState::DtorCalled);
251 State = State->remove<CtorDtorMap>(Reg);
253 C.addTransition(State);
258 void VirtualCallChecker::reportBug(StringRef Msg, bool IsSink,
259 const MemRegion *Reg,
260 CheckerContext &C) const {
263 N = C.generateErrorNode();
265 N = C.generateNonFatalErrorNode();
270 BT.reset(new BugType(
271 this, "Call to virtual function during construction or destruction",
272 "C++ Object Lifecycle"));
274 auto Reporter = llvm::make_unique<BugReport>(*BT, Msg, N);
275 Reporter->addVisitor(llvm::make_unique<VirtualBugVisitor>(Reg));
276 C.emitReport(std::move(Reporter));
279 void ento::registerVirtualCallChecker(CheckerManager &mgr) {
280 VirtualCallChecker *checker = mgr.registerChecker<VirtualCallChecker>();
282 checker->IsPureOnly =
283 mgr.getAnalyzerOptions().getCheckerBooleanOption("PureOnly", false,