clang 24.0.0git
CallDescription.cpp
Go to the documentation of this file.
1//===- CallDescription.cpp - function/method call matching --*- 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/// \file This file defines a generic mechanism for matching for function and
10/// method calls of C, C++, and Objective-C languages. Instances of these
11/// classes are frequently used together with the CallEvent classes.
12//
13//===----------------------------------------------------------------------===//
14
17#include "clang/AST/Decl.h"
21#include "llvm/ADT/StringExtras.h"
22#include <iterator>
23#include <optional>
24
25using namespace llvm;
26using namespace clang;
27
28using MaybeCount = std::optional<unsigned>;
29
30// A constructor helper.
32 MaybeCount RequiredParams) {
33 if (RequiredParams)
34 return RequiredParams;
35 if (RequiredArgs)
36 return RequiredArgs;
37 return std::nullopt;
38}
39
41 ArrayRef<StringRef> QualifiedName,
42 MaybeCount RequiredArgs /*= None*/,
43 MaybeCount RequiredParams /*= None*/)
44 : RequiredArgs(RequiredArgs),
45 RequiredParams(readRequiredParams(RequiredArgs, RequiredParams)),
46 MatchAs(MatchAs) {
47 assert(!QualifiedName.empty());
48 this->QualifiedName.reserve(QualifiedName.size());
49 llvm::transform(QualifiedName, std::back_inserter(this->QualifiedName),
50 [](StringRef From) { return From.str(); });
51}
52
53ento::CallDescription::Callee::Callee(const CallEvent &Call) {
54 // FIXME: Add ObjC Message support.
55 if (Call.getKind() == CE_ObjCMessage)
56 return;
57
58 FD = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
59 if (!FD)
60 return;
61
62 ArgCount = Call.getNumArgs();
63 ParamCount = FD->param_size();
64 IsMethod = isa<CXXMethodDecl>(FD);
65}
66
67ento::CallDescription::Callee::Callee(const CallExpr &CE) {
68 FD = dyn_cast_or_null<FunctionDecl>(CE.getCalleeDecl());
69 if (!FD)
70 return;
71
72 ArgCount = CE.getNumArgs();
73 ParamCount = FD->param_size();
74 IsMethod = isa<CXXMethodDecl>(FD);
75}
76
77unsigned ento::CLibraryFunctionInfo::getBuiltinID() {
78 if (!BuiltinID)
79 BuiltinID = FD->getBuiltinID();
80 return *BuiltinID;
81}
82
83StringRef ento::CLibraryFunctionInfo::getBuiltinName() {
84 assert(getBuiltinID() != 0 && "Not a builtin");
85 if (!BuiltinName)
86 BuiltinName = FD->getASTContext().BuiltinInfo.getName(getBuiltinID());
87 return *BuiltinName;
88}
89
90bool ento::CLibraryFunctionInfo::isPredefinedLibFunction() {
91 assert(getBuiltinID() != 0 && "Not a builtin");
92 if (!IsPredefinedLibFunction)
93 IsPredefinedLibFunction =
94 FD->getASTContext().BuiltinInfo.isPredefinedLibFunction(getBuiltinID());
95 return *IsPredefinedLibFunction;
96}
97
98bool ento::CLibraryFunctionInfo::isCLibraryDecl() {
99 if (IsCLibraryDecl)
100 return *IsCLibraryDecl;
101
102 IsCLibraryDecl = false;
103 // If this is a special C++ name without IdentifierInfo, it can't be a
104 // C library function.
105 if (!FD->getIdentifier())
106 return false;
107
108 // C library functions are either declared directly within a TU (the common
109 // case) or they are accessed through the namespace `std` (when they are used
110 // in C++ via headers like <cstdlib>).
111 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
112 if (!(DC->isTranslationUnit() || DC->isStdNamespace()))
113 return false;
114
115 // If this function is not externally visible, it is not a C library function.
116 // Note that we make an exception for inline functions, which may be
117 // declared in header files without external linkage.
118 IsCLibraryDecl = FD->isInlined() || FD->isExternallyVisible();
119 return *IsCLibraryDecl;
120}
121
123 // To avoid false positives (Ex: finding user defined functions with
124 // similar names), only perform fuzzy name matching when it's a builtin.
125 // Using a string compare is slow, we might want to switch on BuiltinID here.
126 if (getBuiltinID() != 0) {
127 if (Name.empty())
128 return true;
129 StringRef BName = getBuiltinName();
130 // Accept exact match.
131 if (BName == Name)
132 return true;
133 // Only perform fuzzy name matching for non-library builtins (e.g.
134 // __builtin_memcpy, __builtin_memcpy_inline), not for distinct predefined
135 // library functions (e.g. objc_read_weak vs read, getlogin_r vs getlogin).
136 if (!isPredefinedLibFunction()) {
137 size_t start = BName.find(Name);
138 if (start != StringRef::npos) {
139 // v-- match starts here
140 // ...xxxxx...
141 // _xxxxx_
142 // ^ ^ lookbehind and lookahead characters
143
144 const auto MatchPredecessor = [&]() -> bool {
145 return start <= 0 || !llvm::isAlpha(BName[start - 1]);
146 };
147 const auto MatchSuccessor = [&]() -> bool {
148 std::size_t LookbehindPlace = start + Name.size();
149 return LookbehindPlace >= BName.size() ||
150 !llvm::isAlpha(BName[LookbehindPlace]);
151 };
152
153 if (MatchPredecessor() && MatchSuccessor())
154 return true;
155 }
156 }
157 }
158
159 if (!isCLibraryDecl())
160 return false;
161
162 if (Name.empty())
163 return true;
164
165 StringRef FName = FD->getName();
166 if (FName == Name)
167 return true;
168
169 if (FName.starts_with("__inline") && FName.contains(Name))
170 return true;
171
172 return false;
173}
174
176 Callee C(Call);
177 CLibraryFunctionInfo CLib(C.FD);
178 return matchesImpl(C, CLib);
179}
180
182 Callee C(CE);
183 CLibraryFunctionInfo CLib(C.FD);
184 return matchesImpl(C, CLib);
185}
186
187bool ento::CallDescription::matchNameOnly(const NamedDecl *ND) const {
188 DeclarationName Name = ND->getDeclName();
189 if (const auto *NameII = Name.getAsIdentifierInfo()) {
190 if (!II)
192
193 return NameII == *II; // Fast case.
194 }
195
196 // Avoid the stringification below where the printed name is known.
197 StringRef FuncName = getFunctionName();
198 switch (Name.getNameKind()) {
200 if (!FuncName.consume_front("~"))
201 return false;
202 [[fallthrough]];
204 // Constructor and destructor names are printed using the record name.
205 if (const auto *RT = Name.getCXXNameType()->getAsCanonical<RecordType>()) {
206 const RecordDecl *RD = RT->getDecl();
207 if (const IdentifierInfo *RecordII = RD->getIdentifier())
208 return RecordII->getName() == FuncName;
209 // An unnamed record with a typedef name for linkage purposes is printed
210 // using the typedef name.
211 if (const TypedefNameDecl *TD = RD->getTypedefNameForAnonDecl())
212 return TD->getIdentifier()->getName() == FuncName;
213 // Other unnamed records are printed with their source location, e.g.
214 // "(lambda at file:line:col)", which no description names.
215 return false;
216 }
217 break;
221 if (!FuncName.starts_with("operator"))
222 return false;
223 break;
224 default:
225 break;
226 }
227
228 // Fall back to printing the name, e.g. for overloaded, literal and conversion
229 // operators.
230 return Name.getAsString() == getFunctionName();
231}
232
233bool ento::CallDescription::matchQualifiedNameParts(const Decl *D) const {
234 const auto FindNextNamespaceOrRecord =
235 [](const DeclContext *Ctx) -> const DeclContext * {
236 while (Ctx && !isa<NamespaceDecl, RecordDecl>(Ctx))
237 Ctx = Ctx->getParent();
238 return Ctx;
239 };
240
241 auto QualifierPartsIt = begin_qualified_name_parts();
242 const auto QualifierPartsEndIt = end_qualified_name_parts();
243
244 // Match namespace and record names. Skip unrelated names if they don't
245 // match.
246 const DeclContext *Ctx = FindNextNamespaceOrRecord(D->getDeclContext());
247 for (; Ctx && QualifierPartsIt != QualifierPartsEndIt;
248 Ctx = FindNextNamespaceOrRecord(Ctx->getParent())) {
249 // If not matched just continue and try matching for the next one.
250 if (cast<NamedDecl>(Ctx)->getName() != *QualifierPartsIt)
251 continue;
252 ++QualifierPartsIt;
253 }
254
255 // We matched if we consumed all expected qualifier segments.
256 return QualifierPartsIt == QualifierPartsEndIt;
257}
258
259bool ento::CallDescription::matchesImpl(const Callee &C,
260 CLibraryFunctionInfo &CLib) const {
261 const FunctionDecl *FD = C.FD;
262 if (!FD)
263 return false;
264
265 if (MatchAs == Mode::SimpleFunc && C.IsMethod)
266 return false;
267
268 if (MatchAs == Mode::CXXMethod && !C.IsMethod)
269 return false;
270
271 const size_t ArgCount = C.ArgCount;
272 const size_t ParamCount = C.ParamCount;
273
274 if (MatchAs == Mode::CLibraryMaybeHardened) {
275 // In addition to accepting FOO() with CLibrary rules, we also want to
276 // accept calls to __FOO_chk() and __builtin___FOO_chk().
278 CLib.isCLibraryFunction(StringRef())) {
279 // Check that the actual argument/parameter counts are greater or equal
280 // to the required counts. (Setting a requirement to std::nullopt matches
281 // anything, so in that case value_or ensures that the value is compared
282 // with itself.)
283 return (RequiredArgs.value_or(ArgCount) <= ArgCount &&
284 RequiredParams.value_or(ParamCount) <= ParamCount);
285 }
286 }
287
288 if (RequiredArgs.value_or(ArgCount) != ArgCount ||
289 RequiredParams.value_or(ParamCount) != ParamCount)
290 return false;
291
292 if (MatchAs == Mode::CLibrary || MatchAs == Mode::CLibraryMaybeHardened)
293 return CLib.isCLibraryFunction(getFunctionName());
294
295 if (!matchNameOnly(FD))
296 return false;
297
298 if (!hasQualifiedNameParts())
299 return true;
300
301 return matchQualifiedNameParts(FD);
302}
303
305 std::initializer_list<CallDescription> &&List) {
306 Impl.LinearMap.reserve(List.size());
307 for (const CallDescription &CD : List)
308 Impl.LinearMap.push_back({CD, /*unused*/ true});
309}
310
312 return static_cast<bool>(Impl.lookup(Call));
313}
314
316 return static_cast<bool>(Impl.lookupAsWritten(CE));
317}
Defines the clang::ASTContext interface.
Defines enum values for all the target-independent builtin functions.
static MaybeCount readRequiredParams(MaybeCount RequiredArgs, MaybeCount RequiredParams)
std::optional< unsigned > MaybeCount
static std::string getFunctionName(const CallEvent &Call)
IdentifierTable & Idents
Definition ASTContext.h:862
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3203
Decl * getCalleeDecl()
Definition Expr.h:3189
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2113
bool isTranslationUnit() const
Definition DeclBase.h:2209
bool isStdNamespace() const
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
DeclContext * getDeclContext()
Definition DeclBase.h:458
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
QualType getCXXNameType() const
If this name is one of the C++ names (of a constructor, destructor, or conversion function),...
NameKind getNameKind() const
Determine what kind of name this is.
One of these records is kept for each identifier that is lexed.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
This represents a decl that may have a name.
Definition Decl.h:276
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
Represents a struct/union/class.
Definition Decl.h:4512
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:4141
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3003
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3749
The properties of a function declaration that determine whether it is a C library function with a giv...
bool isCLibraryFunction(StringRef Name)
Implements CheckerContext::isCLibraryFunction(FD, Name).
CallDescriptionSet(std::initializer_list< CallDescription > &&List)
bool containsAsWritten(const CallExpr &CE) const
When available, always prefer lookup with a CallEvent!
bool contains(const CallEvent &Call) const
A CallDescription is a pattern that can be used to match calls based on the qualified name and the ar...
CallDescription(Mode MatchAs, ArrayRef< StringRef > QualifiedName, MaybeCount RequiredArgs=std::nullopt, MaybeCount RequiredParams=std::nullopt)
Constructs a CallDescription object.
bool matches(const CallEvent &Call) const
Returns true if the CallEvent is a call to a function that matches the CallDescription.
bool matchesAsWritten(const CallExpr &CE) const
Returns true if the CallExpr is a call to a function that matches the CallDescription.
Represents an abstract call to a function or method along a particular path.
Definition CallEvent.h:151
static bool isHardenedVariantOf(const FunctionDecl *FD, StringRef Name)
In builds that use source hardening (-D_FORTIFY_SOURCE), many standard functions are implemented as m...
StringRef getName(const HeaderType T)
Definition HeaderFile.h:38
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
U cast(CodeGen::Address addr)
Definition Address.h:327
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30