clang 19.0.0git
UncountedCallArgsChecker.cpp
Go to the documentation of this file.
1//=======- UncountedCallArgsChecker.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"
13#include "clang/AST/Decl.h"
14#include "clang/AST/DeclCXX.h"
21#include <optional>
22
23using namespace clang;
24using namespace ento;
25
26namespace {
27
28class UncountedCallArgsChecker
29 : public Checker<check::ASTDecl<TranslationUnitDecl>> {
30 BugType Bug{this,
31 "Uncounted call argument for a raw pointer/reference parameter",
32 "WebKit coding guidelines"};
33 mutable BugReporter *BR;
34
36
37public:
38
39 void checkASTDecl(const TranslationUnitDecl *TUD, AnalysisManager &MGR,
40 BugReporter &BRArg) const {
41 BR = &BRArg;
42
43 // The calls to checkAST* from AnalysisConsumer don't
44 // visit template instantiations or lambda classes. We
45 // want to visit those, so we make our own RecursiveASTVisitor.
46 struct LocalVisitor : public RecursiveASTVisitor<LocalVisitor> {
47 const UncountedCallArgsChecker *Checker;
48 explicit LocalVisitor(const UncountedCallArgsChecker *Checker)
49 : Checker(Checker) {
50 assert(Checker);
51 }
52
53 bool shouldVisitTemplateInstantiations() const { return true; }
54 bool shouldVisitImplicitCode() const { return false; }
55
56 bool VisitCallExpr(const CallExpr *CE) {
57 Checker->visitCallExpr(CE);
58 return true;
59 }
60 };
61
62 LocalVisitor visitor(this);
63 visitor.TraverseDecl(const_cast<TranslationUnitDecl *>(TUD));
64 }
65
66 void visitCallExpr(const CallExpr *CE) const {
67 if (shouldSkipCall(CE))
68 return;
69
70 if (auto *F = CE->getDirectCallee()) {
71 // Skip the first argument for overloaded member operators (e. g. lambda
72 // or std::function call operator).
73 unsigned ArgIdx = isa<CXXOperatorCallExpr>(CE) && isa_and_nonnull<CXXMethodDecl>(F);
74
75 if (auto *MemberCallExpr = dyn_cast<CXXMemberCallExpr>(CE)) {
76 if (auto *MD = MemberCallExpr->getMethodDecl()) {
77 auto name = safeGetName(MD);
78 if (name == "ref" || name == "deref")
79 return;
80 }
81 auto *E = MemberCallExpr->getImplicitObjectArgument();
82 QualType ArgType = MemberCallExpr->getObjectType();
83 std::optional<bool> IsUncounted =
85 if (IsUncounted && *IsUncounted && !isPtrOriginSafe(E))
86 reportBugOnThis(E);
87 }
88
89 for (auto P = F->param_begin();
90 // FIXME: Also check variadic function parameters.
91 // FIXME: Also check default function arguments. Probably a different
92 // checker. In case there are default arguments the call can have
93 // fewer arguments than the callee has parameters.
94 P < F->param_end() && ArgIdx < CE->getNumArgs(); ++P, ++ArgIdx) {
95 // TODO: attributes.
96 // if ((*P)->hasAttr<SafeRefCntblRawPtrAttr>())
97 // continue;
98
99 const auto *ArgType = (*P)->getType().getTypePtrOrNull();
100 if (!ArgType)
101 continue; // FIXME? Should we bail?
102
103 // FIXME: more complex types (arrays, references to raw pointers, etc)
104 std::optional<bool> IsUncounted = isUncountedPtr(ArgType);
105 if (!IsUncounted || !(*IsUncounted))
106 continue;
107
108 const auto *Arg = CE->getArg(ArgIdx);
109
110 if (auto *defaultArg = dyn_cast<CXXDefaultArgExpr>(Arg))
111 Arg = defaultArg->getExpr();
112
113 if (isPtrOriginSafe(Arg))
114 continue;
115
116 reportBug(Arg, *P);
117 }
118 }
119 }
120
121 bool isPtrOriginSafe(const Expr *Arg) const {
122 std::pair<const clang::Expr *, bool> ArgOrigin =
123 tryToFindPtrOrigin(Arg, true);
124
125 // Temporary ref-counted object created as part of the call argument
126 // would outlive the call.
127 if (ArgOrigin.second)
128 return true;
129
130 if (isa<CXXNullPtrLiteralExpr>(ArgOrigin.first)) {
131 // foo(nullptr)
132 return true;
133 }
134 if (isa<IntegerLiteral>(ArgOrigin.first)) {
135 // FIXME: Check the value.
136 // foo(NULL)
137 return true;
138 }
139
140 return isASafeCallArg(ArgOrigin.first);
141 }
142
143 bool shouldSkipCall(const CallExpr *CE) const {
144 const auto *Callee = CE->getDirectCallee();
145
146 if (Callee && TFA.isTrivial(Callee))
147 return true;
148
149 if (CE->getNumArgs() == 0)
150 return false;
151
152 // If an assignment is problematic we should warn about the sole existence
153 // of object on LHS.
154 if (auto *MemberOp = dyn_cast<CXXOperatorCallExpr>(CE)) {
155 // Note: assignemnt to built-in type isn't derived from CallExpr.
156 if (MemberOp->getOperator() ==
157 OO_Equal) { // Ignore assignment to Ref/RefPtr.
158 auto *callee = MemberOp->getDirectCallee();
159 if (auto *calleeDecl = dyn_cast<CXXMethodDecl>(callee)) {
160 if (const CXXRecordDecl *classDecl = calleeDecl->getParent()) {
161 if (isRefCounted(classDecl))
162 return true;
163 }
164 }
165 }
166 if (MemberOp->isAssignmentOp())
167 return false;
168 }
169
170 if (!Callee)
171 return false;
172
173 if (isMethodOnWTFContainerType(Callee))
174 return true;
175
176 auto overloadedOperatorType = Callee->getOverloadedOperator();
177 if (overloadedOperatorType == OO_EqualEqual ||
178 overloadedOperatorType == OO_ExclaimEqual ||
179 overloadedOperatorType == OO_LessEqual ||
180 overloadedOperatorType == OO_GreaterEqual ||
181 overloadedOperatorType == OO_Spaceship ||
182 overloadedOperatorType == OO_AmpAmp ||
183 overloadedOperatorType == OO_PipePipe)
184 return true;
185
186 if (isCtorOfRefCounted(Callee))
187 return true;
188
189 auto name = safeGetName(Callee);
190 if (name == "adoptRef" || name == "getPtr" || name == "WeakPtr" ||
191 name == "dynamicDowncast" || name == "downcast" ||
192 name == "checkedDowncast" || name == "uncheckedDowncast" ||
193 name == "bitwise_cast" || name == "is" || name == "equal" ||
194 name == "hash" || name == "isType" ||
195 // FIXME: Most/all of these should be implemented via attributes.
196 name == "equalIgnoringASCIICase" ||
197 name == "equalIgnoringASCIICaseCommon" ||
198 name == "equalIgnoringNullity" || name == "toString")
199 return true;
200
201 return false;
202 }
203
204 bool isMethodOnWTFContainerType(const FunctionDecl *Decl) const {
205 if (!isa<CXXMethodDecl>(Decl))
206 return false;
207 auto *ClassDecl = Decl->getParent();
208 if (!ClassDecl || !isa<CXXRecordDecl>(ClassDecl))
209 return false;
210
211 auto *NsDecl = ClassDecl->getParent();
212 if (!NsDecl || !isa<NamespaceDecl>(NsDecl))
213 return false;
214
215 auto MethodName = safeGetName(Decl);
216 auto ClsNameStr = safeGetName(ClassDecl);
217 StringRef ClsName = ClsNameStr; // FIXME: Make safeGetName return StringRef.
218 auto NamespaceName = safeGetName(NsDecl);
219 // FIXME: These should be implemented via attributes.
220 return NamespaceName == "WTF" &&
221 (MethodName == "find" || MethodName == "findIf" ||
222 MethodName == "reverseFind" || MethodName == "reverseFindIf" ||
223 MethodName == "get" || MethodName == "inlineGet" ||
224 MethodName == "contains" || MethodName == "containsIf") &&
225 (ClsName.ends_with("Vector") || ClsName.ends_with("Set") ||
226 ClsName.ends_with("Map"));
227 }
228
229 void reportBug(const Expr *CallArg, const ParmVarDecl *Param) const {
230 assert(CallArg);
231
233 llvm::raw_svector_ostream Os(Buf);
234
235 const std::string paramName = safeGetName(Param);
236 Os << "Call argument";
237 if (!paramName.empty()) {
238 Os << " for parameter ";
239 printQuotedQualifiedName(Os, Param);
240 }
241 Os << " is uncounted and unsafe.";
242
243 const SourceLocation SrcLocToReport =
244 isa<CXXDefaultArgExpr>(CallArg) ? Param->getDefaultArg()->getExprLoc()
245 : CallArg->getSourceRange().getBegin();
246
247 PathDiagnosticLocation BSLoc(SrcLocToReport, BR->getSourceManager());
248 auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
249 Report->addRange(CallArg->getSourceRange());
250 BR->emitReport(std::move(Report));
251 }
252
253 void reportBugOnThis(const Expr *CallArg) const {
254 assert(CallArg);
255
256 const SourceLocation SrcLocToReport = CallArg->getSourceRange().getBegin();
257
258 PathDiagnosticLocation BSLoc(SrcLocToReport, BR->getSourceManager());
259 auto Report = std::make_unique<BasicBugReport>(
260 Bug, "Call argument for 'this' parameter is uncounted and unsafe.",
261 BSLoc);
262 Report->addRange(CallArg->getSourceRange());
263 BR->emitReport(std::move(Report));
264 }
265};
266} // namespace
267
268void ento::registerUncountedCallArgsChecker(CheckerManager &Mgr) {
269 Mgr.registerChecker<UncountedCallArgsChecker>();
270}
271
272bool ento::shouldRegisterUncountedCallArgsChecker(const CheckerManager &) {
273 return true;
274}
StringRef P
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::SourceLocation class and associated facilities.
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2820
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3011
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2990
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2998
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2076
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
This represents one expression.
Definition: Expr.h:110
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
Represents a function declaration or definition.
Definition: Decl.h:1959
Represents a parameter to a function.
Definition: Decl.h:1749
Expr * getDefaultArg()
Definition: Decl.cpp:2968
A (possibly-)qualified type.
Definition: Type.h:738
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
Encodes a location in the source.
SourceLocation getBegin() const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
The top declaration context.
Definition: Decl.h:84
An inter-procedural analysis facility that detects functions with "trivial" behavior with respect to ...
bool isTrivial(const Decl *D) const
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1862
BugReporter is a utility class for generating PathDiagnostics for analysis.
Definition: BugReporter.h:585
const SourceManager & getSourceManager()
Definition: BugReporter.h:623
virtual void emitReport(std::unique_ptr< BugReport > R)
Add the given report to the set of reports tracked by BugReporter.
CHECKER * registerChecker(AT &&... Args)
Used to register checkers.
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
The JSON file list parser is used to communicate input to InstallAPI.
std::optional< bool > isUncountedPtr(const Type *T)
bool isCtorOfRefCounted(const clang::FunctionDecl *F)
std::optional< bool > isUncounted(const CXXRecordDecl *Class)
std::pair< const Expr *, bool > tryToFindPtrOrigin(const Expr *E, bool StopAtFirstRefCountedObj)
This function de-facto defines a set of transformations that we consider safe (in heuristical sense).
Definition: ASTUtils.cpp:20
void printQuotedQualifiedName(llvm::raw_ostream &Os, const NamedDeclDerivedT &D)
bool isASafeCallArg(const Expr *E)
For E referring to a ref-countable/-counted pointer/reference we return whether it's a safe call argu...
Definition: ASTUtils.cpp:97
bool isRefCounted(const CXXRecordDecl *R)
std::string safeGetName(const T *ASTNode)
Definition: ASTUtils.h:65