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"
14#include "clang/AST/RecursiveASTVisitor.h"
15#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
16#include "clang/Basic/SourceLocation.h"
17#include "clang/Basic/SourceManager.h"
18#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
19#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
20#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
21#include "clang/StaticAnalyzer/Core/Checker.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 : public RecursiveASTVisitor<LocalVisitor> {
49 using Base = RecursiveASTVisitor<LocalVisitor>;
50
51 const ForwardDeclChecker *Checker;
52 Decl *DeclWithIssue{nullptr};
53
54 explicit LocalVisitor(const ForwardDeclChecker *Checker)
55 : Checker(Checker) {
56 assert(Checker);
57 }
58
59 bool shouldVisitTemplateInstantiations() const { return true; }
60 bool shouldVisitImplicitCode() const { return false; }
61
62 bool VisitTypedefDecl(TypedefDecl *TD) {
63 Checker->visitTypedef(TD);
64 return true;
65 }
66
67 bool VisitRecordDecl(const RecordDecl *RD) {
68 Checker->visitRecordDecl(RD, DeclWithIssue);
69 return true;
70 }
71
72 bool TraverseDecl(Decl *D) {
73 llvm::SaveAndRestore SavedDecl(DeclWithIssue);
74 if (D && (isa<FunctionDecl>(Val: D) || isa<ObjCMethodDecl>(Val: D)))
75 DeclWithIssue = D;
76 return Base::TraverseDecl(D);
77 }
78
79 bool VisitVarDecl(VarDecl *V) {
80 if (V->isLocalVarDecl())
81 Checker->visitVarDecl(V, DeclWithIssue);
82 return true;
83 }
84
85 bool VisitCallExpr(const CallExpr *CE) {
86 Checker->visitCallExpr(CE, DeclWithIssue);
87 return true;
88 }
89
90 bool VisitCXXConstructExpr(const CXXConstructExpr *CE) {
91 Checker->visitConstructExpr(CE, DeclWithIssue);
92 return true;
93 }
94
95 bool VisitObjCMessageExpr(const ObjCMessageExpr *ObjCMsgExpr) {
96 Checker->visitObjCMessageExpr(E: ObjCMsgExpr, DeclWithIssue);
97 return true;
98 }
99 };
100
101 LocalVisitor visitor(this);
102 RTC.visitTranslationUnitDecl(TUD);
103 visitor.TraverseDecl(D: const_cast<TranslationUnitDecl *>(TUD));
104 }
105
106 void visitTypedef(const TypedefDecl *TD) const {
107 RTC.visitTypedef(TD);
108 auto QT = TD->getUnderlyingType().getCanonicalType();
109 assert(BR && "expected nonnull BugReporter");
110 if (BR->getSourceManager().isInSystemHeader(Loc: TD->getBeginLoc())) {
111 if (auto *Type = QT.getTypePtrOrNull())
112 SystemTypes.insert(V: Type);
113 }
114 }
115
116 bool isUnknownType(QualType QT) const {
117 auto *CanonicalType = QT.getCanonicalType().getTypePtrOrNull();
118 if (!CanonicalType)
119 return false;
120 auto PointeeQT = CanonicalType->getPointeeType();
121 auto *PointeeType = PointeeQT.getTypePtrOrNull();
122 if (!PointeeType)
123 return false;
124 auto *R = PointeeType->getAsCXXRecordDecl();
125 if (!R) // Forward declaration of a Objective-C interface is safe.
126 return false;
127 auto Name = R->getName();
128 if (R->hasDefinition())
129 return false;
130 // Find a definition amongst template declarations.
131 if (auto *Specialization = dyn_cast<ClassTemplateSpecializationDecl>(Val: R)) {
132 if (auto *S = Specialization->getSpecializedTemplate()) {
133 for (S = S->getMostRecentDecl(); S; S = S->getPreviousDecl()) {
134 if (S->isThisDeclarationADefinition())
135 return false;
136 }
137 }
138 }
139 return !RTC.isUnretained(QT) && !SystemTypes.contains(V: CanonicalType) &&
140 !SystemTypes.contains(V: PointeeType) && !Name.starts_with(Prefix: "Opaque") &&
141 Name != "_NSZone";
142 }
143
144 void visitRecordDecl(const RecordDecl *RD, const Decl *DeclWithIssue) const {
145 if (!RD->isThisDeclarationADefinition())
146 return;
147
148 if (RD->isImplicit() || RD->isLambda())
149 return;
150
151 const auto RDLocation = RD->getLocation();
152 if (!RDLocation.isValid())
153 return;
154
155 const auto Kind = RD->getTagKind();
156 if (Kind != TagTypeKind::Struct && Kind != TagTypeKind::Class)
157 return;
158
159 assert(BR && "expected nonnull BugReporter");
160 if (BR->getSourceManager().isInSystemHeader(Loc: RDLocation))
161 return;
162
163 // Ref-counted smartpointers actually have raw-pointer to uncounted type as
164 // a member but we trust them to handle it correctly.
165 auto R = llvm::dyn_cast_or_null<CXXRecordDecl>(Val: RD);
166 if (!R || isRefCounted(Class: R) || isCheckedPtr(Class: R) || isRetainPtrOrOSPtr(Class: R))
167 return;
168
169 for (auto *Member : RD->fields()) {
170 auto QT = Member->getType();
171 if (isUnknownType(QT)) {
172 SmallString<100> Buf;
173 llvm::raw_svector_ostream Os(Buf);
174
175 const std::string TypeName = QT.getAsString();
176 Os << "Member variable ";
177 printQuotedName(Os, D: Member);
178 Os << " uses a forward declared type '" << TypeName << "'";
179
180 const SourceLocation SrcLocToReport = Member->getBeginLoc();
181 PathDiagnosticLocation BSLoc(SrcLocToReport, BR->getSourceManager());
182 auto Report = std::make_unique<BasicBugReport>(args: Bug, args: Os.str(), args&: BSLoc);
183 Report->addRange(R: Member->getSourceRange());
184 Report->setDeclWithIssue(DeclWithIssue);
185 BR->emitReport(R: std::move(Report));
186 }
187 }
188 }
189
190 void visitVarDecl(const VarDecl *V, const Decl *DeclWithIssue) const {
191 assert(BR && "expected nonnull BugReporter");
192 if (BR->getSourceManager().isInSystemHeader(Loc: V->getBeginLoc()))
193 return;
194
195 auto QT = V->getType();
196 if (!isUnknownType(QT))
197 return;
198
199 SmallString<100> Buf;
200 llvm::raw_svector_ostream Os(Buf);
201 Os << "Local variable ";
202 printQuotedQualifiedName(Os, D: V);
203
204 reportBug(SrcLoc: V->getBeginLoc(), SrcRange: V->getSourceRange(), DeclWithIssue, Description: Os.str(),
205 Type: QT);
206 }
207
208 void visitCallExpr(const CallExpr *CE, const Decl *DeclWithIssue) const {
209 assert(BR && "expected nonnull BugReporter");
210 if (BR->getSourceManager().isInSystemHeader(Loc: CE->getExprLoc()))
211 return;
212
213 if (auto *F = CE->getDirectCallee()) {
214 // Skip the first argument for overloaded member operators (e. g. lambda
215 // or std::function call operator).
216 unsigned ArgIdx = isa<CXXOperatorCallExpr>(Val: CE) && isa<CXXMethodDecl>(Val: F);
217
218 for (auto P = F->param_begin();
219 P < F->param_end() && ArgIdx < CE->getNumArgs(); ++P, ++ArgIdx)
220 visitCallArg(Arg: CE->getArg(Arg: ArgIdx), Param: *P, DeclWithIssue);
221 }
222 }
223
224 void visitConstructExpr(const CXXConstructExpr *CE,
225 const Decl *DeclWithIssue) const {
226 assert(BR && "expected nonnull BugReporter");
227 if (BR->getSourceManager().isInSystemHeader(Loc: CE->getExprLoc()))
228 return;
229
230 if (const CXXMethodDecl *F = CE->getConstructor()) {
231 unsigned ArgIdx = 0;
232 for (auto P = F->param_begin();
233 P < F->param_end() && ArgIdx < CE->getNumArgs(); ++P, ++ArgIdx)
234 visitCallArg(Arg: CE->getArg(Arg: ArgIdx), Param: *P, DeclWithIssue);
235 }
236 }
237
238 void visitObjCMessageExpr(const ObjCMessageExpr *E,
239 const Decl *DeclWithIssue) const {
240 assert(BR && "expected nonnull BugReporter");
241 if (BR->getSourceManager().isInSystemHeader(Loc: E->getExprLoc()))
242 return;
243
244 if (auto *Receiver = E->getInstanceReceiver()) {
245 Receiver = Receiver->IgnoreParenCasts();
246 if (isUnknownType(QT: E->getReceiverType()))
247 reportUnknownReceiverType(Receiver, DeclWithIssue);
248 }
249
250 auto *MethodDecl = E->getMethodDecl();
251 if (!MethodDecl)
252 return;
253
254 auto ArgCount = E->getNumArgs();
255 for (unsigned i = 0; i < ArgCount && i < MethodDecl->param_size(); ++i)
256 visitCallArg(Arg: E->getArg(Arg: i), Param: MethodDecl->getParamDecl(Idx: i), DeclWithIssue);
257 }
258
259 void visitCallArg(const Expr *Arg, const ParmVarDecl *Param,
260 const Decl *DeclWithIssue) const {
261 auto *ArgExpr = Arg->IgnoreParenCasts();
262 while (ArgExpr) {
263 ArgExpr = ArgExpr->IgnoreParenCasts();
264 if (auto *InnerCE = dyn_cast<CallExpr>(Val: ArgExpr)) {
265 if (auto *InnerCallee = InnerCE->getDirectCallee()) {
266 if (isStdOrWTFMove(F: InnerCallee) && InnerCE->getNumArgs() == 1) {
267 ArgExpr = InnerCE->getArg(Arg: 0);
268 continue;
269 }
270 }
271 }
272 if (auto *UO = dyn_cast<UnaryOperator>(Val: ArgExpr)) {
273 auto OpCode = UO->getOpcode();
274 if (OpCode == UO_Deref || OpCode == UO_AddrOf) {
275 ArgExpr = UO->getSubExpr();
276 continue;
277 }
278 }
279 break;
280 }
281
282 if (auto *MemberCallExpr = dyn_cast<CXXMemberCallExpr>(Val: ArgExpr)) {
283 if (isOwnerPtrType(T: MemberCallExpr->getObjectType()))
284 return;
285 }
286
287 if (auto *OpCE = dyn_cast<CXXOperatorCallExpr>(Val: ArgExpr)) {
288 auto *Method = dyn_cast_or_null<CXXMethodDecl>(Val: OpCE->getDirectCallee());
289 if (Method && isOwnerPtr(Name: safeGetName(ASTNode: Method->getParent()))) {
290 if (OpCE->getOperator() == OO_Star && OpCE->getNumArgs() == 1)
291 return;
292 }
293 }
294
295 if (isNullPtr(E: ArgExpr) || isa<IntegerLiteral>(Val: ArgExpr) ||
296 isa<CXXDefaultArgExpr>(Val: ArgExpr))
297 return;
298
299 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: ArgExpr)) {
300 if (auto *ValDecl = DRE->getDecl()) {
301 if (isa<ParmVarDecl>(Val: ValDecl))
302 return;
303 }
304 }
305
306 QualType ArgType = Param->getType();
307 if (!isUnknownType(QT: ArgType))
308 return;
309
310 reportUnknownArgType(CA: Arg, Param, DeclWithIssue);
311 }
312
313 void reportUnknownArgType(const Expr *CA, const ParmVarDecl *Param,
314 const Decl *DeclWithIssue) const {
315 assert(CA);
316
317 SmallString<100> Buf;
318 llvm::raw_svector_ostream Os(Buf);
319
320 const std::string paramName = safeGetName(ASTNode: Param);
321 Os << "Call argument";
322 if (!paramName.empty()) {
323 Os << " for parameter ";
324 printQuotedQualifiedName(Os, D: Param);
325 }
326
327 reportBug(SrcLoc: CA->getExprLoc(), SrcRange: CA->getSourceRange(), DeclWithIssue, Description: Os.str(),
328 Type: Param->getType());
329 }
330
331 void reportUnknownReceiverType(const Expr *Receiver,
332 const Decl *DeclWithIssue) const {
333 assert(Receiver);
334 reportBug(SrcLoc: Receiver->getExprLoc(), SrcRange: Receiver->getSourceRange(), DeclWithIssue,
335 Description: "Receiver", Type: Receiver->getType());
336 }
337
338 void reportBug(const SourceLocation &SrcLoc, const SourceRange &SrcRange,
339 const Decl *DeclWithIssue, const StringRef &Description,
340 QualType Type) const {
341 SmallString<100> Buf;
342 llvm::raw_svector_ostream Os(Buf);
343
344 const std::string TypeName = Type.getAsString();
345 Os << Description << " uses a forward declared type '" << TypeName << "'";
346
347 assert(BR && "expected nonnull BugReporter");
348 PathDiagnosticLocation BSLoc(SrcLoc, BR->getSourceManager());
349 auto Report = std::make_unique<BasicBugReport>(args: Bug, args: Os.str(), args&: BSLoc);
350 Report->addRange(R: SrcRange);
351 Report->setDeclWithIssue(DeclWithIssue);
352 BR->emitReport(R: std::move(Report));
353 }
354};
355
356} // namespace
357
358void ento::registerForwardDeclChecker(CheckerManager &Mgr) {
359 Mgr.registerChecker<ForwardDeclChecker>();
360}
361
362bool ento::shouldRegisterForwardDeclChecker(const CheckerManager &) {
363 return true;
364}
365