clang  6.0.0svn
DeleteWithNonVirtualDtorChecker.cpp
Go to the documentation of this file.
1 //===-- DeleteWithNonVirtualDtorChecker.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 // Defines a checker for the OOP52-CPP CERT rule: Do not delete a polymorphic
11 // object without a virtual destructor.
12 //
13 // Diagnostic flags -Wnon-virtual-dtor and -Wdelete-non-virtual-dtor report if
14 // an object with a virtual function but a non-virtual destructor exists or is
15 // deleted, respectively.
16 //
17 // This check exceeds them by comparing the dynamic and static types of the
18 // object at the point of destruction and only warns if it happens through a
19 // pointer to a base type without a virtual destructor. The check places a note
20 // at the last point where the conversion from derived to base happened.
21 //
22 //===----------------------------------------------------------------------===//
23 
24 #include "ClangSACheckers.h"
33 
34 using namespace clang;
35 using namespace ento;
36 
37 namespace {
38 class DeleteWithNonVirtualDtorChecker
39  : public Checker<check::PreStmt<CXXDeleteExpr>> {
40  mutable std::unique_ptr<BugType> BT;
41 
42  class DeleteBugVisitor : public BugReporterVisitorImpl<DeleteBugVisitor> {
43  public:
44  DeleteBugVisitor() : Satisfied(false) {}
45  void Profile(llvm::FoldingSetNodeID &ID) const override {
46  static int X = 0;
47  ID.AddPointer(&X);
48  }
49  std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
50  const ExplodedNode *PrevN,
51  BugReporterContext &BRC,
52  BugReport &BR) override;
53 
54  private:
55  bool Satisfied;
56  };
57 
58 public:
59  void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
60 };
61 } // end anonymous namespace
62 
63 void DeleteWithNonVirtualDtorChecker::checkPreStmt(const CXXDeleteExpr *DE,
64  CheckerContext &C) const {
65  const Expr *DeletedObj = DE->getArgument();
66  const MemRegion *MR = C.getSVal(DeletedObj).getAsRegion();
67  if (!MR)
68  return;
69 
70  const auto *BaseClassRegion = MR->getAs<TypedValueRegion>();
71  const auto *DerivedClassRegion = MR->getBaseRegion()->getAs<SymbolicRegion>();
72  if (!BaseClassRegion || !DerivedClassRegion)
73  return;
74 
75  const auto *BaseClass = BaseClassRegion->getValueType()->getAsCXXRecordDecl();
76  const auto *DerivedClass =
77  DerivedClassRegion->getSymbol()->getType()->getPointeeCXXRecordDecl();
78  if (!BaseClass || !DerivedClass)
79  return;
80 
81  if (!BaseClass->hasDefinition() || !DerivedClass->hasDefinition())
82  return;
83 
84  if (BaseClass->getDestructor()->isVirtual())
85  return;
86 
87  if (!DerivedClass->isDerivedFrom(BaseClass))
88  return;
89 
90  if (!BT)
91  BT.reset(new BugType(this,
92  "Destruction of a polymorphic object with no "
93  "virtual destructor",
94  "Logic error"));
95 
97  auto R = llvm::make_unique<BugReport>(*BT, BT->getName(), N);
98 
99  // Mark region of problematic base class for later use in the BugVisitor.
100  R->markInteresting(BaseClassRegion);
101  R->addVisitor(llvm::make_unique<DeleteBugVisitor>());
102  C.emitReport(std::move(R));
103 }
104 
105 std::shared_ptr<PathDiagnosticPiece>
106 DeleteWithNonVirtualDtorChecker::DeleteBugVisitor::VisitNode(
107  const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC,
108  BugReport &BR) {
109  // Stop traversal after the first conversion was found on a path.
110  if (Satisfied)
111  return nullptr;
112 
114  const LocationContext *LC = N->getLocationContext();
116  if (!S)
117  return nullptr;
118 
119  const auto *CastE = dyn_cast<CastExpr>(S);
120  if (!CastE)
121  return nullptr;
122 
123  // Only interested in DerivedToBase implicit casts.
124  // Explicit casts can have different CastKinds.
125  if (const auto *ImplCastE = dyn_cast<ImplicitCastExpr>(CastE)) {
126  if (ImplCastE->getCastKind() != CK_DerivedToBase)
127  return nullptr;
128  }
129 
130  // Region associated with the current cast expression.
131  const MemRegion *M = State->getSVal(CastE, LC).getAsRegion();
132  if (!M)
133  return nullptr;
134 
135  // Check if target region was marked as problematic previously.
136  if (!BR.isInteresting(M))
137  return nullptr;
138 
139  // Stop traversal on this path.
140  Satisfied = true;
141 
142  SmallString<256> Buf;
143  llvm::raw_svector_ostream OS(Buf);
144  OS << "Conversion from derived to base happened here";
146  N->getLocationContext());
147  return std::make_shared<PathDiagnosticEventPiece>(Pos, OS.str(), true,
148  nullptr);
149 }
150 
151 void ento::registerDeleteWithNonVirtualDtorChecker(CheckerManager &mgr) {
152  mgr.registerChecker<DeleteWithNonVirtualDtorChecker>();
153 }
TypedValueRegion - An abstract class representing regions having a typed value.
Definition: MemRegion.h:511
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:79
bool isInteresting(SymbolRef sym)
Stmt - This represents one statement.
Definition: Stmt.h:66
const ProgramStateRef & getState() const
SVal getSVal(const Stmt *S) const
Get the value of arbitrary expressions at this point in the path.
LineState State
This class provides a convenience implementation for clone() using the Curiously-Recurring Template P...
const LocationContext * getLocationContext() const
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2710
const RegionTy * getAs() const
Definition: MemRegion.h:1174
SymbolicRegion - A special, "non-concrete" region.
Definition: MemRegion.h:742
Expr - This represents one expression.
Definition: Expr.h:106
ExplodedNode * generateNonFatalErrorNode(ProgramStateRef State=nullptr, const ProgramPointTag *Tag=nullptr)
Generate a transition to a node that will be used to report an error.
void emitReport(std::unique_ptr< BugReport > R)
Emit the diagnostics report.
static const Stmt * getStmt(const ExplodedNode *N)
Given an exploded node, retrieve the statement that should be used for the diagnostic location...
Expr * getArgument()
Definition: ExprCXX.h:2125
#define false
Definition: stdbool.h:33
CHECKER * registerChecker()
Used to register checkers.
const MemRegion * getAsRegion() const
Definition: SVals.cpp:140
Dataflow Directional Tag Classes.
Represents a delete expression for memory deallocation and destructor calls, e.g. ...
Definition: ExprCXX.h:2071
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:13010
const MemRegion * getBaseRegion() const
Definition: MemRegion.cpp:1093
This class provides an interface through which checkers can create individual bug reports...
Definition: BugReporter.h:55
SourceManager & getSourceManager()
Definition: BugReporter.h:565