clang 24.0.0git
CallDescription.h
Go to the documentation of this file.
1//===- CallDescription.h - 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
15#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLDESCRIPTION_H
16#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLDESCRIPTION_H
17
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/Support/Compiler.h"
21#include <optional>
22#include <vector>
23
24namespace clang {
25class IdentifierInfo;
26} // namespace clang
27
28namespace clang {
29namespace ento {
30/// The properties of a function declaration that determine whether it is a C
31/// library function with a given name. They are computed on first use, so
32/// matching a function against many names computes each at most once.
34 const FunctionDecl *const FD;
35 std::optional<unsigned> BuiltinID;
36 std::optional<std::string> BuiltinName;
37 std::optional<bool> IsPredefinedLibFunction;
38 std::optional<bool> IsCLibraryDecl;
39
40 unsigned getBuiltinID();
41 /// Must only be called if getBuiltinID() is not 0.
42 StringRef getBuiltinName();
43 /// Returns true if the builtin is a predefined library function (e.g.
44 /// getlogin_r). Must only be called if getBuiltinID() is not 0.
45 bool isPredefinedLibFunction();
46 /// Returns true if the function has an identifier, it is in the top-level
47 /// or the \c std namespace, and it is externally visible or inline.
48 bool isCLibraryDecl();
49
50public:
51 explicit CLibraryFunctionInfo(const FunctionDecl *FD) : FD(FD) {}
52
53 /// Implements CheckerContext::isCLibraryFunction(FD, Name).
54 bool isCLibraryFunction(StringRef Name);
55};
56
57/// A `CallDescription` is a pattern that can be used to _match_ calls
58/// based on the qualified name and the argument/parameter counts.
60public:
61 enum class Mode {
62 /// Match calls to functions from the C standard library. This also
63 /// recognizes builtin variants whose name is derived by adding
64 /// "__builtin", "__inline" or similar prefixes or suffixes; but only
65 /// matches functions that are externally visible and are declared either
66 /// directly within a TU or in the namespace 'std'.
67 /// For the exact heuristics, see CheckerContext::isCLibraryFunction().
69
70 /// An extended version of the `CLibrary` mode that also matches the
71 /// hardened variants like __FOO_chk() and __builtin__FOO_chk() that take
72 /// additional arguments compared to the "regular" function FOO().
73 /// This is not the default behavior of `CLibrary` because in this case the
74 /// checker code must be prepared to handle the different parametrization.
75 /// For the exact heuristics, see CheckerContext::isHardenedVariantOf().
77
78 /// Matches "simple" functions that are not methods. (Static methods are
79 /// methods.)
81
82 /// Matches a C++ method (may be static, may be virtual, may be an
83 /// overloaded operator, a constructor or a destructor).
85
86 /// Match any CallEvent that is not an ObjCMethodCall. This should not be
87 /// used when the checker looks for a concrete function (and knows whether
88 /// it is a method); but GenericTaintChecker uses this mode to match
89 /// functions whose name was configured by the user.
91
92 /// FIXME: Add support for ObjCMethodCall events (I'm not adding it because
93 /// I'm not familiar with Objective-C). Note that currently an early return
94 /// in `bool matches(const CallEvent &Call) const;` discards all
95 /// Objective-C method calls.
96 };
97
98private:
99 friend class CallEvent;
100 using MaybeCount = std::optional<unsigned>;
101
102 mutable std::optional<const IdentifierInfo *> II;
103 // The list of the qualified names used to identify the specified CallEvent,
104 // e.g. "{a, b}" represent the qualified names, like "a::b".
105 std::vector<std::string> QualifiedName;
106 MaybeCount RequiredArgs;
107 MaybeCount RequiredParams;
108 Mode MatchAs;
109
110 template <typename T> friend class CallDescriptionMap;
111
112 /// The properties of a call that are needed for matching it. They are
113 /// computed once when a call is matched against many CallDescriptions, to
114 /// avoid repeated virtual calls like CallEvent::getDecl().
115 struct Callee {
116 const FunctionDecl *FD = nullptr;
117 size_t ArgCount = 0;
118 size_t ParamCount = 0;
119 bool IsMethod = false;
120
121 explicit Callee(const CallEvent &Call);
122 explicit Callee(const CallExpr &CE);
123 };
124
125public:
126 /// Constructs a CallDescription object.
127 ///
128 /// @param MatchAs Specifies the kind of the call that should be matched.
129 ///
130 /// @param QualifiedName The list of the name qualifiers of the function that
131 /// will be matched. The user is allowed to skip any of the qualifiers.
132 /// For example, {"std", "basic_string", "c_str"} would match both
133 /// std::basic_string<...>::c_str() and std::__1::basic_string<...>::c_str().
134 ///
135 /// @param RequiredArgs The expected number of arguments that are passed to
136 /// the function. Omit this parameter (or pass std::nullopt) to match every
137 /// occurrence without checking the argument count in the call.
138 ///
139 /// @param RequiredParams The expected number of parameters in the function
140 /// definition that is called. Omit this parameter to match every occurrence
141 /// without checking the parameter count in the definition.
142 CallDescription(Mode MatchAs, ArrayRef<StringRef> QualifiedName,
143 MaybeCount RequiredArgs = std::nullopt,
144 MaybeCount RequiredParams = std::nullopt);
145
146 /// Get the name of the function that this object matches.
147 StringRef getFunctionName() const { return QualifiedName.back(); }
148
149 /// Get the qualified name parts in reversed order.
150 /// E.g. { "std", "vector", "data" } -> "vector", "std"
152 return std::next(QualifiedName.rbegin());
153 }
154 auto end_qualified_name_parts() const { return QualifiedName.rend(); }
155
156 /// It's false, if and only if we expect a single identifier, such as
157 /// `getenv`. It's true for `std::swap`, or `my::detail::container::data`.
158 bool hasQualifiedNameParts() const { return QualifiedName.size() > 1; }
159
160 /// @name Matching CallDescriptions against a CallEvent
161 /// @{
162
163 /// Returns true if the CallEvent is a call to a function that matches
164 /// the CallDescription.
165 ///
166 /// \note This function is not intended to be used to match Obj-C method
167 /// calls.
168 bool matches(const CallEvent &Call) const;
169
170 /// Returns true whether the CallEvent matches on any of the CallDescriptions
171 /// supplied.
172 ///
173 /// \note This function is not intended to be used to match Obj-C method
174 /// calls.
175 friend bool matchesAny(const CallEvent &Call, const CallDescription &CD1) {
176 return CD1.matches(Call);
177 }
178
179 /// \copydoc clang::ento::CallDescription::matchesAny(const CallEvent &, const CallDescription &)
180 template <typename... Ts>
181 friend bool matchesAny(const CallEvent &Call, const CallDescription &CD1,
182 const Ts &...CDs) {
183 return CD1.matches(Call) || matchesAny(Call, CDs...);
184 }
185 /// @}
186
187 /// @name Matching CallDescriptions against a CallExpr
188 /// @{
189
190 /// Returns true if the CallExpr is a call to a function that matches the
191 /// CallDescription.
192 ///
193 /// When available, always prefer matching with a CallEvent! This function
194 /// exists only when that is not available, for example, when _only_
195 /// syntactic check is done on a piece of code.
196 ///
197 /// Also, StdLibraryFunctionsChecker::Signature is likely a better candidate
198 /// for syntactic only matching if you are writing a new checker. This is
199 /// handy if a CallDescriptionMap is already there.
200 ///
201 /// The function is imprecise because CallEvent may know path sensitive
202 /// information, such as the precise argument count (see comments for
203 /// CallEvent::getNumArgs), the called function if it was called through a
204 /// function pointer, and other information not available syntactically.
205 bool matchesAsWritten(const CallExpr &CE) const;
206
207 /// Returns true whether the CallExpr matches on any of the CallDescriptions
208 /// supplied.
209 ///
210 /// \note This function is not intended to be used to match Obj-C method
211 /// calls.
212 friend bool matchesAnyAsWritten(const CallExpr &CE,
213 const CallDescription &CD1) {
214 return CD1.matchesAsWritten(CE);
215 }
216
217 /// \copydoc clang::ento::CallDescription::matchesAnyAsWritten(const CallExpr &, const CallDescription &)
218 template <typename... Ts>
219 friend bool matchesAnyAsWritten(const CallExpr &CE,
220 const CallDescription &CD1,
221 const Ts &...CDs) {
222 return CD1.matchesAsWritten(CE) || matchesAnyAsWritten(CE, CDs...);
223 }
224 /// @}
225
226private:
227 bool matchesImpl(const Callee &C, CLibraryFunctionInfo &CLib) const;
228
229 bool matchNameOnly(const NamedDecl *ND) const;
230 bool matchQualifiedNameParts(const Decl *D) const;
231};
232
233/// An immutable map from CallDescriptions to arbitrary data. Provides a unified
234/// way for checkers to react on function calls.
235template <typename T> class CallDescriptionMap {
236 friend class CallDescriptionSet;
237
238 // Some call descriptions aren't easily hashable (eg., the ones with qualified
239 // names in which some sections are omitted), so let's put them
240 // in a simple vector and use linear lookup.
241 // TODO: Implement an actual map for fast lookup for "hashable" call
242 // descriptions (eg., the ones for C functions that just match the name).
243 std::vector<std::pair<CallDescription, T>> LinearMap;
244
245public:
247 std::initializer_list<std::pair<CallDescription, T>> &&List)
248 : LinearMap(List) {}
249
250 template <typename InputIt>
251 CallDescriptionMap(InputIt First, InputIt Last) : LinearMap(First, Last) {}
252
254
255 // These maps are usually stored once per checker, so let's make sure
256 // we don't do redundant copies.
259
262
263 [[nodiscard]] const T *lookup(const CallEvent &Call) const {
264 return lookupImpl(CallDescription::Callee(Call));
265 }
266
267 /// When available, always prefer lookup with a CallEvent! This function
268 /// exists only when that is not available, for example, when _only_
269 /// syntactic check is done on a piece of code.
270 ///
271 /// Also, StdLibraryFunctionsChecker::Signature is likely a better candidate
272 /// for syntactic only matching if you are writing a new checker. This is
273 /// handy if a CallDescriptionMap is already there.
274 ///
275 /// The function is imprecise because CallEvent may know path sensitive
276 /// information, such as the precise argument count (see comments for
277 /// CallEvent::getNumArgs), the called function if it was called through a
278 /// function pointer, and other information not available syntactically.
279 [[nodiscard]] const T *lookupAsWritten(const CallExpr &Call) const {
280 return lookupImpl(CallDescription::Callee(Call));
281 }
282
283private:
284 const T *lookupImpl(const CallDescription::Callee &C) const {
285 // Null for ObjC messages, blocks and calls of unknown function pointers.
286 if (!C.FD)
287 return nullptr;
288
289 CLibraryFunctionInfo CLib(C.FD);
290 // Slow path: linear lookup.
291 // TODO: Implement some sort of fast path.
292 for (const std::pair<CallDescription, T> &I : LinearMap)
293 if (I.first.matchesImpl(C, CLib))
294 return &I.second;
295
296 return nullptr;
297 }
298};
299
300/// Enumerators of this enum class are used to construct CallDescription
301/// objects; in that context the fully qualified name is needlessly verbose.
303
304/// An immutable set of CallDescriptions.
305/// Checkers can efficiently decide if a given CallEvent matches any
306/// CallDescription in the set.
308 CallDescriptionMap<bool /*unused*/> Impl = {};
309
310public:
311 CallDescriptionSet(std::initializer_list<CallDescription> &&List);
312
315
316 [[nodiscard]] bool contains(const CallEvent &Call) const;
317
318 /// When available, always prefer lookup with a CallEvent! This function
319 /// exists only when that is not available, for example, when _only_
320 /// syntactic check is done on a piece of code.
321 ///
322 /// Also, StdLibraryFunctionsChecker::Signature is likely a better candidate
323 /// for syntactic only matching if you are writing a new checker. This is
324 /// handy if a CallDescriptionMap is already there.
325 ///
326 /// The function is imprecise because CallEvent may know path sensitive
327 /// information, such as the precise argument count (see comments for
328 /// CallEvent::getNumArgs), the called function if it was called through a
329 /// function pointer, and other information not available syntactically.
330 [[nodiscard]] bool containsAsWritten(const CallExpr &CE) const;
331};
332
333} // namespace ento
334} // namespace clang
335
336#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLDESCRIPTION_H
std::optional< unsigned > MaybeCount
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Represents a function declaration or definition.
Definition Decl.h:2082
One of these records is kept for each identifier that is lexed.
This represents a decl that may have a name.
Definition Decl.h:276
The properties of a function declaration that determine whether it is a C library function with a giv...
CLibraryFunctionInfo(const FunctionDecl *FD)
bool isCLibraryFunction(StringRef Name)
Implements CheckerContext::isCLibraryFunction(FD, Name).
An immutable map from CallDescriptions to arbitrary data.
CallDescriptionMap(InputIt First, InputIt Last)
const T * lookup(const CallEvent &Call) const
CallDescriptionMap(CallDescriptionMap &&)=default
CallDescriptionMap(std::initializer_list< std::pair< CallDescription, T > > &&List)
CallDescriptionMap(const CallDescriptionMap &)=delete
CallDescriptionMap & operator=(CallDescriptionMap &&)=default
const T * lookupAsWritten(const CallExpr &Call) const
When available, always prefer lookup with a CallEvent!
CallDescriptionMap & operator=(const CallDescription &)=delete
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
CallDescriptionSet & operator=(const CallDescription &)=delete
CallDescriptionSet(const CallDescriptionSet &)=delete
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 hasQualifiedNameParts() const
It's false, if and only if we expect a single identifier, such as getenv.
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.
StringRef getFunctionName() const
Get the name of the function that this object matches.
friend bool matchesAny(const CallEvent &Call, const CallDescription &CD1, const Ts &...CDs)
Returns true whether the CallEvent matches on any of the CallDescriptions supplied.
friend bool matchesAnyAsWritten(const CallExpr &CE, const CallDescription &CD1, const Ts &...CDs)
Returns true whether the CallExpr matches on any of the CallDescriptions supplied.
auto begin_qualified_name_parts() const
Get the qualified name parts in reversed order.
friend bool matchesAny(const CallEvent &Call, const CallDescription &CD1)
Returns true whether the CallEvent matches on any of the CallDescriptions supplied.
@ CLibrary
Match calls to functions from the C standard library.
@ Unspecified
Match any CallEvent that is not an ObjCMethodCall.
@ CLibraryMaybeHardened
An extended version of the CLibrary mode that also matches the hardened variants like __FOO_chk() and...
@ CXXMethod
Matches a C++ method (may be static, may be virtual, may be an overloaded operator,...
@ SimpleFunc
Matches "simple" functions that are not methods.
friend bool matchesAnyAsWritten(const CallExpr &CE, const CallDescription &CD1)
Returns true whether the CallExpr matches on any of the CallDescriptions supplied.
Represents an abstract call to a function or method along a particular path.
Definition CallEvent.h:151
CallDescription::Mode CDM
Enumerators of this enum class are used to construct CallDescription objects; in that context the ful...
Top level wrappers for InstallAPI frontend operations.