clang 20.0.0git
CXXDeleteChecker.cpp
Go to the documentation of this file.
1//=== CXXDeleteChecker.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 the following new checkers for C++ delete expressions:
10//
11// * DeleteWithNonVirtualDtorChecker
12// Defines a checker for the OOP52-CPP CERT rule: Do not delete a
13// polymorphic object without a virtual destructor.
14//
15// Diagnostic flags -Wnon-virtual-dtor and -Wdelete-non-virtual-dtor
16// report if an object with a virtual function but a non-virtual
17// destructor exists or is deleted, respectively.
18//
19// This check exceeds them by comparing the dynamic and static types of
20// the object at the point of destruction and only warns if it happens
21// through a pointer to a base type without a virtual destructor. The
22// check places a note at the last point where the conversion from
23// derived to base happened.
24//
25// * CXXArrayDeleteChecker
26// Defines a checker for the EXP51-CPP CERT rule: Do not delete an array
27// through a pointer of the incorrect type.
28//
29//===----------------------------------------------------------------------===//
30
41
42using namespace clang;
43using namespace ento;
44
45namespace {
46class CXXDeleteChecker : public Checker<check::PreStmt<CXXDeleteExpr>> {
47protected:
48 class PtrCastVisitor : public BugReporterVisitor {
49 public:
50 void Profile(llvm::FoldingSetNodeID &ID) const override {
51 static int X = 0;
52 ID.AddPointer(&X);
53 }
54 PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
56 PathSensitiveBugReport &BR) override;
57 };
58
59 virtual void
60 checkTypedDeleteExpr(const CXXDeleteExpr *DE, CheckerContext &C,
61 const TypedValueRegion *BaseClassRegion,
62 const SymbolicRegion *DerivedClassRegion) const = 0;
63
64public:
65 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
66};
67
68class DeleteWithNonVirtualDtorChecker : public CXXDeleteChecker {
69 const BugType BT{
70 this, "Destruction of a polymorphic object with no virtual destructor"};
71
72 void
73 checkTypedDeleteExpr(const CXXDeleteExpr *DE, CheckerContext &C,
74 const TypedValueRegion *BaseClassRegion,
75 const SymbolicRegion *DerivedClassRegion) const override;
76};
77
78class CXXArrayDeleteChecker : public CXXDeleteChecker {
79 const BugType BT{this,
80 "Deleting an array of polymorphic objects is undefined"};
81
82 void
83 checkTypedDeleteExpr(const CXXDeleteExpr *DE, CheckerContext &C,
84 const TypedValueRegion *BaseClassRegion,
85 const SymbolicRegion *DerivedClassRegion) const override;
86};
87} // namespace
88
89void CXXDeleteChecker::checkPreStmt(const CXXDeleteExpr *DE,
90 CheckerContext &C) const {
91 const Expr *DeletedObj = DE->getArgument();
92 const MemRegion *MR = C.getSVal(DeletedObj).getAsRegion();
93 if (!MR)
94 return;
95
96 OverloadedOperatorKind DeleteKind =
98
99 if (DeleteKind != OO_Delete && DeleteKind != OO_Array_Delete)
100 return;
101
102 const auto *BaseClassRegion = MR->getAs<TypedValueRegion>();
103 const auto *DerivedClassRegion = MR->getBaseRegion()->getAs<SymbolicRegion>();
104 if (!BaseClassRegion || !DerivedClassRegion)
105 return;
106
107 checkTypedDeleteExpr(DE, C, BaseClassRegion, DerivedClassRegion);
108}
109
110void DeleteWithNonVirtualDtorChecker::checkTypedDeleteExpr(
111 const CXXDeleteExpr *DE, CheckerContext &C,
112 const TypedValueRegion *BaseClassRegion,
113 const SymbolicRegion *DerivedClassRegion) const {
114 const auto *BaseClass = BaseClassRegion->getValueType()->getAsCXXRecordDecl();
115 const auto *DerivedClass =
116 DerivedClassRegion->getSymbol()->getType()->getPointeeCXXRecordDecl();
117 if (!BaseClass || !DerivedClass)
118 return;
119
120 if (!BaseClass->hasDefinition() || !DerivedClass->hasDefinition())
121 return;
122
123 if (BaseClass->getDestructor()->isVirtual())
124 return;
125
126 if (!DerivedClass->isDerivedFrom(BaseClass))
127 return;
128
129 ExplodedNode *N = C.generateNonFatalErrorNode();
130 if (!N)
131 return;
132 auto R = std::make_unique<PathSensitiveBugReport>(BT, BT.getDescription(), N);
133
134 // Mark region of problematic base class for later use in the BugVisitor.
135 R->markInteresting(BaseClassRegion);
136 R->addVisitor<PtrCastVisitor>();
137 C.emitReport(std::move(R));
138}
139
140void CXXArrayDeleteChecker::checkTypedDeleteExpr(
141 const CXXDeleteExpr *DE, CheckerContext &C,
142 const TypedValueRegion *BaseClassRegion,
143 const SymbolicRegion *DerivedClassRegion) const {
144 const auto *BaseClass = BaseClassRegion->getValueType()->getAsCXXRecordDecl();
145 const auto *DerivedClass =
146 DerivedClassRegion->getSymbol()->getType()->getPointeeCXXRecordDecl();
147 if (!BaseClass || !DerivedClass)
148 return;
149
150 if (!BaseClass->hasDefinition() || !DerivedClass->hasDefinition())
151 return;
152
153 if (DE->getOperatorDelete()->getOverloadedOperator() != OO_Array_Delete)
154 return;
155
156 if (!DerivedClass->isDerivedFrom(BaseClass))
157 return;
158
159 ExplodedNode *N = C.generateNonFatalErrorNode();
160 if (!N)
161 return;
162
164 llvm::raw_svector_ostream OS(Buf);
165
166 QualType SourceType = BaseClassRegion->getValueType();
167 QualType TargetType =
168 DerivedClassRegion->getSymbol()->getType()->getPointeeType();
169
170 OS << "Deleting an array of '" << TargetType.getAsString()
171 << "' objects as their base class '"
172 << SourceType.getAsString(C.getASTContext().getPrintingPolicy())
173 << "' is undefined";
174
175 auto R = std::make_unique<PathSensitiveBugReport>(BT, OS.str(), N);
176
177 // Mark region of problematic base class for later use in the BugVisitor.
178 R->markInteresting(BaseClassRegion);
179 R->addVisitor<PtrCastVisitor>();
180 C.emitReport(std::move(R));
181}
182
184CXXDeleteChecker::PtrCastVisitor::VisitNode(const ExplodedNode *N,
187 const Stmt *S = N->getStmtForDiagnostics();
188 if (!S)
189 return nullptr;
190
191 const auto *CastE = dyn_cast<CastExpr>(S);
192 if (!CastE)
193 return nullptr;
194
195 // FIXME: This way of getting base types does not support reference types.
196 QualType SourceType = CastE->getSubExpr()->getType()->getPointeeType();
197 QualType TargetType = CastE->getType()->getPointeeType();
198
199 if (SourceType.isNull() || TargetType.isNull() || SourceType == TargetType)
200 return nullptr;
201
202 // Region associated with the current cast expression.
203 const MemRegion *M = N->getSVal(CastE).getAsRegion();
204 if (!M)
205 return nullptr;
206
207 // Check if target region was marked as problematic previously.
208 if (!BR.isInteresting(M))
209 return nullptr;
210
212 llvm::raw_svector_ostream OS(Buf);
213
214 OS << "Casting from '" << SourceType.getAsString() << "' to '"
215 << TargetType.getAsString() << "' here";
216
218 N->getLocationContext());
219 return std::make_shared<PathDiagnosticEventPiece>(Pos, OS.str(),
220 /*addPosRange=*/true);
221}
222
223void ento::registerArrayDeleteChecker(CheckerManager &mgr) {
224 mgr.registerChecker<CXXArrayDeleteChecker>();
225}
226
227bool ento::shouldRegisterArrayDeleteChecker(const CheckerManager &mgr) {
228 return true;
229}
230
231void ento::registerDeleteWithNonVirtualDtorChecker(CheckerManager &mgr) {
232 mgr.registerChecker<DeleteWithNonVirtualDtorChecker>();
233}
234
235bool ento::shouldRegisterDeleteWithNonVirtualDtorChecker(
236 const CheckerManager &mgr) {
237 return true;
238}
#define X(type, name)
Definition: Value.h:143
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition: ExprCXX.h:2498
FunctionDecl * getOperatorDelete() const
Definition: ExprCXX.h:2537
Expr * getArgument()
Definition: ExprCXX.h:2539
This represents one expression.
Definition: Expr.h:110
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3965
A (possibly-)qualified type.
Definition: Type.h:941
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1339
Stmt - This represents one statement.
Definition: Stmt.h:84
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition: Type.cpp:1867
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
const SourceManager & getSourceManager() const
Definition: BugReporter.h:737
BugReporterVisitors are used to add custom diagnostics along a path.
CHECKER * registerChecker(AT &&... Args)
Used to register checkers.
const Stmt * getStmtForDiagnostics() const
If the node's program point corresponds to a statement, retrieve that statement.
SVal getSVal(const Stmt *S) const
Get the value of an arbitrary expression at this node.
const LocationContext * getLocationContext() const
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:97
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getBaseRegion() const
Definition: MemRegion.cpp:1354
const RegionTy * getAs() const
Definition: MemRegion.h:1388
bool isInteresting(SymbolRef sym) const
const MemRegion * getAsRegion() const
Definition: SVals.cpp:120
virtual QualType getType() const =0
SymbolicRegion - A special, "non-concrete" region.
Definition: MemRegion.h:780
SymbolRef getSymbol() const
It might return null.
Definition: MemRegion.h:799
TypedValueRegion - An abstract class representing regions having a typed value.
Definition: MemRegion.h:535
virtual QualType getValueType() const =0
std::shared_ptr< PathDiagnosticPiece > PathDiagnosticPieceRef
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21