clang 24.0.0git
ForwardDeclChecker.cpp
Go to the documentation of this file.
1//=======- ForwardDeclChecker.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#include "ASTUtils.h"
10#include "DiagOutputUtils.h"
11#include "PtrTypesSemantics.h"
12#include "clang/AST/Decl.h"
13#include "clang/AST/DeclCXX.h"
22#include "llvm/ADT/DenseSet.h"
23#include "llvm/Support/SaveAndRestore.h"
24
25using namespace clang;
26using namespace ento;
27
28namespace {
29
30class ForwardDeclChecker : public Checker<check::ASTDecl<TranslationUnitDecl>> {
31 BugType Bug;
32 mutable BugReporter *BR = nullptr;
33 mutable RetainTypeChecker RTC;
34 mutable llvm::DenseSet<const Type *> SystemTypes;
35
36public:
37 ForwardDeclChecker()
38 : Bug(this, "Forward declared member or local variable or parameter",
39 "WebKit coding guidelines") {}
40
41 void checkASTDecl(const TranslationUnitDecl *TUD, AnalysisManager &MGR,
42 BugReporter &BRArg) const {
43 BR = &BRArg;
44
45 // The calls to checkAST* from AnalysisConsumer don't
46 // visit template instantiations or lambda classes. We
47 // want to visit those, so we make our own RecursiveASTVisitor.
48 struct LocalVisitor : DynamicRecursiveASTVisitor {
49 const ForwardDeclChecker *Checker;
50 Decl *DeclWithIssue{nullptr};
51
52 explicit LocalVisitor(const ForwardDeclChecker *Checker)
53 : Checker(Checker) {
54 assert(Checker);
55 ShouldVisitTemplateInstantiations = true;
56 ShouldVisitImplicitCode = false;
57 }
58
59 bool VisitTypedefDecl(TypedefDecl *TD) override {
60 Checker->visitTypedef(TD);
61 return true;
62 }
63
64 bool VisitRecordDecl(RecordDecl *RD) override {
65 Checker->visitRecordDecl(RD, DeclWithIssue);
66 return true;
67 }
68
69 bool TraverseDecl(Decl *D) override {
70 llvm::SaveAndRestore SavedDecl(DeclWithIssue);
71 if (D && (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)))
72 DeclWithIssue = D;
74 }
75
76 bool VisitVarDecl(VarDecl *V) override {
77 if (V->isLocalVarDecl())
78 Checker->visitVarDecl(V, DeclWithIssue);
79 return true;
80 }
81
82 bool VisitCallExpr(CallExpr *CE) override {
83 Checker->visitCallExpr(CE, DeclWithIssue);
84 return true;
85 }
86
87 bool VisitCXXConstructExpr(CXXConstructExpr *CE) override {
88 Checker->visitConstructExpr(CE, DeclWithIssue);
89 return true;
90 }
91
92 bool VisitObjCMessageExpr(ObjCMessageExpr *ObjCMsgExpr) override {
93 Checker->visitObjCMessageExpr(ObjCMsgExpr, DeclWithIssue);
94 return true;
95 }
96 };
97
98 LocalVisitor visitor(this);
99 RTC.visitTranslationUnitDecl(TUD);
100 visitor.TraverseDecl(const_cast<TranslationUnitDecl *>(TUD));
101 }
102
103 void visitTypedef(const TypedefDecl *TD) const {
104 RTC.visitTypedef(TD);
105 auto QT = TD->getUnderlyingType().getCanonicalType();
106 assert(BR && "expected nonnull BugReporter");
107 if (BR->getSourceManager().isInSystemHeader(TD->getBeginLoc())) {
108 if (auto *Type = QT.getTypePtrOrNull())
109 SystemTypes.insert(Type);
110 }
111 }
112
113 bool isUnknownType(QualType QT) const {
114 auto *CanonicalType = QT.getCanonicalType().getTypePtrOrNull();
115 if (!CanonicalType)
116 return false;
117 auto PointeeQT = CanonicalType->getPointeeType();
118 auto *PointeeType = PointeeQT.getTypePtrOrNull();
119 if (!PointeeType)
120 return false;
121 auto *R = PointeeType->getAsCXXRecordDecl();
122 if (!R) // Forward declaration of a Objective-C interface is safe.
123 return false;
124 auto Name = R->getName();
125 if (R->hasDefinition())
126 return false;
127 // Find a definition amongst template declarations.
128 if (auto *Specialization = dyn_cast<ClassTemplateSpecializationDecl>(R)) {
129 if (auto *S = Specialization->getSpecializedTemplate()) {
130 for (S = S->getMostRecentDecl(); S; S = S->getPreviousDecl()) {
131 if (S->isThisDeclarationADefinition())
132 return false;
133 }
134 }
135 }
136 return !RTC.isUnretained(QT) && !SystemTypes.contains(CanonicalType) &&
137 !SystemTypes.contains(PointeeType) && !Name.starts_with("Opaque") &&
138 Name != "_NSZone";
139 }
140
141 void visitRecordDecl(const RecordDecl *RD, const Decl *DeclWithIssue) const {
143 return;
144
145 if (RD->isImplicit() || RD->isLambda())
146 return;
147
148 const auto RDLocation = RD->getLocation();
149 if (!RDLocation.isValid())
150 return;
151
152 const auto Kind = RD->getTagKind();
153 if (Kind != TagTypeKind::Struct && Kind != TagTypeKind::Class)
154 return;
155
156 assert(BR && "expected nonnull BugReporter");
157 if (BR->getSourceManager().isInSystemHeader(RDLocation))
158 return;
159
160 // Ref-counted smartpointers actually have raw-pointer to uncounted type as
161 // a member but we trust them to handle it correctly.
162 auto R = llvm::dyn_cast_or_null<CXXRecordDecl>(RD);
163 if (!R || isRefCounted(R) || isCheckedPtr(R) || isRetainPtrOrOSPtr(R))
164 return;
165
166 for (auto *Member : RD->fields()) {
167 auto QT = Member->getType();
168 if (isUnknownType(QT)) {
169 SmallString<100> Buf;
170 llvm::raw_svector_ostream Os(Buf);
171
172 const std::string TypeName = QT.getAsString();
173 Os << "Member variable ";
175 Os << " uses a forward declared type '" << TypeName << "'";
176
177 const SourceLocation SrcLocToReport = Member->getBeginLoc();
178 PathDiagnosticLocation BSLoc(SrcLocToReport, BR->getSourceManager());
179 auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
180 Report->addRange(Member->getSourceRange());
181 Report->setDeclWithIssue(DeclWithIssue);
182 BR->emitReport(std::move(Report));
183 }
184 }
185 }
186
187 void visitVarDecl(const VarDecl *V, const Decl *DeclWithIssue) const {
188 assert(BR && "expected nonnull BugReporter");
189 if (BR->getSourceManager().isInSystemHeader(V->getBeginLoc()))
190 return;
191
192 auto QT = V->getType();
193 if (!isUnknownType(QT))
194 return;
195
196 SmallString<100> Buf;
197 llvm::raw_svector_ostream Os(Buf);
198 Os << "Local variable ";
200
201 reportBug(V->getBeginLoc(), V->getSourceRange(), DeclWithIssue, Os.str(),
202 QT);
203 }
204
205 void visitCallExpr(const CallExpr *CE, const Decl *DeclWithIssue) const {
206 assert(BR && "expected nonnull BugReporter");
207 if (BR->getSourceManager().isInSystemHeader(CE->getExprLoc()))
208 return;
209
210 if (auto *F = CE->getDirectCallee()) {
211 // Skip the first argument for overloaded member operators (e. g. lambda
212 // or std::function call operator).
213 unsigned ArgIdx = isa<CXXOperatorCallExpr>(CE) && isa<CXXMethodDecl>(F);
214
215 for (auto P = F->param_begin();
216 P < F->param_end() && ArgIdx < CE->getNumArgs(); ++P, ++ArgIdx)
217 visitCallArg(CE->getArg(ArgIdx), *P, DeclWithIssue);
218 }
219 }
220
221 void visitConstructExpr(const CXXConstructExpr *CE,
222 const Decl *DeclWithIssue) const {
223 assert(BR && "expected nonnull BugReporter");
224 if (BR->getSourceManager().isInSystemHeader(CE->getExprLoc()))
225 return;
226
227 if (const CXXMethodDecl *F = CE->getConstructor()) {
228 unsigned ArgIdx = 0;
229 for (auto P = F->param_begin();
230 P < F->param_end() && ArgIdx < CE->getNumArgs(); ++P, ++ArgIdx)
231 visitCallArg(CE->getArg(ArgIdx), *P, DeclWithIssue);
232 }
233 }
234
235 void visitObjCMessageExpr(const ObjCMessageExpr *E,
236 const Decl *DeclWithIssue) const {
237 assert(BR && "expected nonnull BugReporter");
238 if (BR->getSourceManager().isInSystemHeader(E->getExprLoc()))
239 return;
240
241 if (auto *Receiver = E->getInstanceReceiver()) {
242 Receiver = Receiver->IgnoreParenCasts();
243 if (isUnknownType(E->getReceiverType()))
244 reportUnknownReceiverType(Receiver, DeclWithIssue);
245 }
246
247 auto *MethodDecl = E->getMethodDecl();
248 if (!MethodDecl)
249 return;
250
251 auto ArgCount = E->getNumArgs();
252 for (unsigned i = 0; i < ArgCount && i < MethodDecl->param_size(); ++i)
253 visitCallArg(E->getArg(i), MethodDecl->getParamDecl(i), DeclWithIssue);
254 }
255
256 void visitCallArg(const Expr *Arg, const ParmVarDecl *Param,
257 const Decl *DeclWithIssue) const {
258 auto *ArgExpr = Arg->IgnoreParenCasts();
259 while (ArgExpr) {
260 ArgExpr = ArgExpr->IgnoreParenCasts();
261 if (auto *InnerCE = dyn_cast<CallExpr>(ArgExpr)) {
262 if (auto *InnerCallee = InnerCE->getDirectCallee()) {
263 if (isStdOrWTFMove(InnerCallee) && InnerCE->getNumArgs() == 1) {
264 ArgExpr = InnerCE->getArg(0);
265 continue;
266 }
267 }
268 }
269 if (auto *UO = dyn_cast<UnaryOperator>(ArgExpr)) {
270 auto OpCode = UO->getOpcode();
271 if (OpCode == UO_Deref || OpCode == UO_AddrOf) {
272 ArgExpr = UO->getSubExpr();
273 continue;
274 }
275 }
276 break;
277 }
278
279 if (auto *MemberCallExpr = dyn_cast<CXXMemberCallExpr>(ArgExpr)) {
280 if (isOwnerPtrType(MemberCallExpr->getObjectType()))
281 return;
282 }
283
284 if (auto *OpCE = dyn_cast<CXXOperatorCallExpr>(ArgExpr)) {
285 auto *Method = dyn_cast_or_null<CXXMethodDecl>(OpCE->getDirectCallee());
286 if (Method && isOwnerPtr(safeGetName(Method->getParent()))) {
287 if (OpCE->getOperator() == OO_Star && OpCE->getNumArgs() == 1)
288 return;
289 }
290 }
291
292 if (isNullPtr(ArgExpr) || isa<IntegerLiteral>(ArgExpr) ||
293 isa<CXXDefaultArgExpr>(ArgExpr))
294 return;
295
296 if (auto *DRE = dyn_cast<DeclRefExpr>(ArgExpr)) {
297 if (auto *ValDecl = DRE->getDecl()) {
298 if (isa<ParmVarDecl>(ValDecl))
299 return;
300 }
301 }
302
303 QualType ArgType = Param->getType();
304 if (!isUnknownType(ArgType))
305 return;
306
307 reportUnknownArgType(Arg, Param, DeclWithIssue);
308 }
309
310 void reportUnknownArgType(const Expr *CA, const ParmVarDecl *Param,
311 const Decl *DeclWithIssue) const {
312 assert(CA);
313
314 SmallString<100> Buf;
315 llvm::raw_svector_ostream Os(Buf);
316
317 const std::string paramName = safeGetName(Param);
318 Os << "Call argument";
319 if (!paramName.empty()) {
320 Os << " for parameter ";
321 printQuotedQualifiedName(Os, Param);
322 }
323
324 reportBug(CA->getExprLoc(), CA->getSourceRange(), DeclWithIssue, Os.str(),
325 Param->getType());
326 }
327
328 void reportUnknownReceiverType(const Expr *Receiver,
329 const Decl *DeclWithIssue) const {
330 assert(Receiver);
331 reportBug(Receiver->getExprLoc(), Receiver->getSourceRange(), DeclWithIssue,
332 "Receiver", Receiver->getType());
333 }
334
335 void reportBug(const SourceLocation &SrcLoc, const SourceRange &SrcRange,
336 const Decl *DeclWithIssue, const StringRef &Description,
337 QualType Type) const {
338 SmallString<100> Buf;
339 llvm::raw_svector_ostream Os(Buf);
340
341 const std::string TypeName = Type.getAsString();
342 Os << Description << " uses a forward declared type '" << TypeName << "'";
343
344 assert(BR && "expected nonnull BugReporter");
345 PathDiagnosticLocation BSLoc(SrcLoc, BR->getSourceManager());
346 auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
347 Report->addRange(SrcRange);
348 Report->setDeclWithIssue(DeclWithIssue);
349 BR->emitReport(std::move(Report));
350 }
351};
352
353} // namespace
354
355void ento::registerForwardDeclChecker(CheckerManager &Mgr) {
356 Mgr.registerChecker<ForwardDeclChecker>();
357}
358
359bool ento::shouldRegisterForwardDeclChecker(const CheckerManager &) {
360 return true;
361}
#define V(N, I)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1696
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1616
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3195
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:603
SourceLocation getLocation() const
Definition DeclBase.h:449
virtual bool TraverseDecl(MaybeConst< Decl > *D)
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3135
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:146
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition ExprObjC.h:1435
Expr * getInstanceReceiver()
Returns the object expression (receiver) for an instance message, or null for a message that is not a...
Definition ExprObjC.h:1300
const ObjCMethodDecl * getMethodDecl() const
Definition ExprObjC.h:1396
QualType getReceiverType() const
Retrieve the receiver type to which this message is being directed.
Definition ExprObjC.cpp:308
unsigned getNumArgs() const
Return the number of actual arguments in this message, not counting the receiver.
Definition ExprObjC.h:1422
QualType getCanonicalType() const
Definition TypeBase.h:8732
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8684
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition Decl.cpp:5368
field_range fields() const
Definition Decl.h:4715
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition Decl.h:4000
TagKind getTagKind() const
Definition Decl.h:4104
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3734
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
QualType getUnderlyingType() const
Definition Decl.h:3804
QualType getType() const
Definition Decl.h:725
CHECKER * registerChecker(AT &&...Args)
Register a single-part checker (derived from Checker): construct its singleton instance,...
Simple checker classes that implement one frontend (i.e.
Definition Checker.h:565
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
void printQuotedQualifiedName(llvm::raw_ostream &Os, const NamedDeclDerivedT &D)
void printQuotedName(llvm::raw_ostream &Os, const NamedDeclDerivedT &D)
bool isOwnerPtr(const std::string &Name)
bool isRefCounted(const CXXRecordDecl *R)
bool isOwnerPtrType(const clang::QualType T)
bool isRetainPtrOrOSPtr(const std::string &Name)
std::string safeGetName(const T *ASTNode)
Definition ASTUtils.h:109
bool isNullPtr(const clang::Expr *E)
Definition ASTUtils.cpp:535
bool isCheckedPtr(const std::string &Name)
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
bool isStdOrWTFMove(const clang::FunctionDecl *F)