1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 #ifndef CustomMatchers_h__
6 #define CustomMatchers_h__
8 #include "MemMoveAnnotation.h"
11 #if CLANG_VERSION_FULL >= 1300
12 // Starting with clang-13 Expr::isRValue has been renamed to Expr::isPRValue
13 #define isRValue isPRValue
17 namespace ast_matchers
{
19 /// This matcher will match any function declaration that is declared as a heap
21 AST_MATCHER(FunctionDecl
, heapAllocator
) {
22 return hasCustomAttribute
<moz_heap_allocator
>(&Node
);
25 /// This matcher will match any declaration that is marked as not accepting
26 /// arithmetic expressions in its arguments.
27 AST_MATCHER(Decl
, noArithmeticExprInArgs
) {
28 return hasCustomAttribute
<moz_no_arith_expr_in_arg
>(&Node
);
31 /// This matcher will match any C++ class that is marked as having a trivial
32 /// constructor and destructor.
33 AST_MATCHER(CXXRecordDecl
, hasTrivialCtorDtor
) {
34 return hasCustomAttribute
<moz_trivial_ctor_dtor
>(&Node
);
37 /// This matcher will match any C++ class that is marked as having a trivial
39 AST_MATCHER(CXXRecordDecl
, hasTrivialDtor
) {
40 return hasCustomAttribute
<moz_trivial_dtor
>(&Node
);
43 AST_MATCHER(CXXConstructExpr
, allowsTemporary
) {
44 return hasCustomAttribute
<moz_allow_temporary
>(Node
.getConstructor());
47 /// This matcher will match lvalue-ref-qualified methods.
48 AST_MATCHER(CXXMethodDecl
, isLValueRefQualified
) {
49 return Node
.getRefQualifier() == RQ_LValue
;
52 /// This matcher will match rvalue-ref-qualified methods.
53 AST_MATCHER(CXXMethodDecl
, isRValueRefQualified
) {
54 return Node
.getRefQualifier() == RQ_RValue
;
57 AST_POLYMORPHIC_MATCHER(isFirstParty
,
58 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl
, Stmt
)) {
59 return !inThirdPartyPath(&Node
, &Finder
->getASTContext()) &&
60 !ASTIsInSystemHeader(Finder
->getASTContext(), Node
);
63 /// This matcher will match temporary expressions.
64 /// We need this matcher for compatibility with clang 3.* (clang 4 and above
65 /// insert a MaterializeTemporaryExpr everywhere).
66 AST_MATCHER(Expr
, isTemporary
) {
67 return Node
.isRValue() || Node
.isXValue() ||
68 isa
<MaterializeTemporaryExpr
>(&Node
);
71 /// This matcher will match any method declaration that is marked as returning
72 /// a pointer deleted by the destructor of the class.
73 AST_MATCHER(CXXMethodDecl
, noDanglingOnTemporaries
) {
74 return hasCustomAttribute
<moz_no_dangling_on_temporaries
>(&Node
);
77 /// This matcher will match any function declaration that is marked to prohibit
78 /// calling AddRef or Release on its return value.
79 AST_MATCHER(FunctionDecl
, hasNoAddRefReleaseOnReturnAttr
) {
80 return hasCustomAttribute
<moz_no_addref_release_on_return
>(&Node
);
83 /// This matcher will match any function declaration that is marked as being
84 /// allowed to run script.
85 AST_MATCHER(FunctionDecl
, hasCanRunScriptAnnotation
) {
86 return hasCustomAttribute
<moz_can_run_script
>(&Node
);
89 /// This matcher will match all arithmetic binary operators.
90 AST_MATCHER(BinaryOperator
, binaryArithmeticOperator
) {
91 BinaryOperatorKind OpCode
= Node
.getOpcode();
92 return OpCode
== BO_Mul
|| OpCode
== BO_Div
|| OpCode
== BO_Rem
||
93 OpCode
== BO_Add
|| OpCode
== BO_Sub
|| OpCode
== BO_Shl
||
94 OpCode
== BO_Shr
|| OpCode
== BO_And
|| OpCode
== BO_Xor
||
95 OpCode
== BO_Or
|| OpCode
== BO_MulAssign
|| OpCode
== BO_DivAssign
||
96 OpCode
== BO_RemAssign
|| OpCode
== BO_AddAssign
||
97 OpCode
== BO_SubAssign
|| OpCode
== BO_ShlAssign
||
98 OpCode
== BO_ShrAssign
|| OpCode
== BO_AndAssign
||
99 OpCode
== BO_XorAssign
|| OpCode
== BO_OrAssign
;
102 /// This matcher will match all arithmetic unary operators.
103 AST_MATCHER(UnaryOperator
, unaryArithmeticOperator
) {
104 UnaryOperatorKind OpCode
= Node
.getOpcode();
105 return OpCode
== UO_PostInc
|| OpCode
== UO_PostDec
|| OpCode
== UO_PreInc
||
106 OpCode
== UO_PreDec
|| OpCode
== UO_Plus
|| OpCode
== UO_Minus
||
110 /// This matcher will match the unary dereference operator
111 AST_MATCHER(UnaryOperator
, unaryDereferenceOperator
) {
112 UnaryOperatorKind OpCode
= Node
.getOpcode();
113 return OpCode
== UO_Deref
;
116 /// This matcher will match == and != binary operators.
117 AST_MATCHER(BinaryOperator
, binaryEqualityOperator
) {
118 BinaryOperatorKind OpCode
= Node
.getOpcode();
119 return OpCode
== BO_EQ
|| OpCode
== BO_NE
;
122 /// This matcher will match comma operator.
123 AST_MATCHER(BinaryOperator
, binaryCommaOperator
) {
124 BinaryOperatorKind OpCode
= Node
.getOpcode();
125 return OpCode
== BO_Comma
;
128 /// This matcher will match floating point types.
129 AST_MATCHER(QualType
, isFloat
) { return Node
->isRealFloatingType(); }
131 /// This matcher will match locations in system headers. This is adopted from
132 /// isExpansionInSystemHeader in newer clangs, but modified in order to work
133 /// with old clangs that we use on infra.
134 AST_POLYMORPHIC_MATCHER(isInSystemHeader
,
135 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl
, Stmt
)) {
136 return ASTIsInSystemHeader(Finder
->getASTContext(), Node
);
139 /// This matcher will match a file "gtest-port.h". The file contains
140 /// known fopen usages that are OK.
141 AST_MATCHER(CallExpr
, isInWhitelistForFopenUsage
) {
142 static const char Whitelist
[] = "gtest-port.h";
143 SourceLocation Loc
= Node
.getBeginLoc();
145 getFilename(Finder
->getASTContext().getSourceManager(), Loc
);
147 return llvm::sys::path::rbegin(FileName
)->equals(Whitelist
);
150 /// This matcher will match a list of files. These files contain
151 /// known NaN-testing expressions which we would like to whitelist.
152 AST_MATCHER(BinaryOperator
, isInWhitelistForNaNExpr
) {
153 const char *whitelist
[] = {"SkScalar.h", "json_writer.cpp", "State.cpp"};
155 SourceLocation Loc
= Node
.getOperatorLoc();
157 getFilename(Finder
->getASTContext().getSourceManager(), Loc
);
158 for (auto itr
= std::begin(whitelist
); itr
!= std::end(whitelist
); itr
++) {
159 if (llvm::sys::path::rbegin(FileName
)->equals(*itr
)) {
167 AST_MATCHER(CallExpr
, isInWhiteListForPrincipalGetUri
) {
168 const auto Whitelist
= {"nsIPrincipal.h", "BasePrincipal.cpp",
169 "ContentPrincipal.cpp"};
170 SourceLocation Loc
= Node
.getBeginLoc();
172 getFilename(Finder
->getASTContext().getSourceManager(), Loc
);
174 for (auto Exclusion
: Whitelist
) {
175 if (Filename
.find(Exclusion
) != std::string::npos
) {
182 /// This matcher will match a list of files which contain NS_NewNamedThread
183 /// code or names of existing threads that we would like to ignore.
184 AST_MATCHER(CallExpr
, isInAllowlistForThreads
) {
186 // Get the source location of the call
187 SourceLocation Loc
= Node
.getRParenLoc();
189 getFilename(Finder
->getASTContext().getSourceManager(), Loc
);
190 for (auto thread_file
: allow_thread_files
) {
191 if (llvm::sys::path::rbegin(FileName
)->equals(thread_file
)) {
196 // Now we get the first arg (the name of the thread) and we check it.
197 const StringLiteral
*nameArg
=
198 dyn_cast
<StringLiteral
>(Node
.getArg(0)->IgnoreImplicit());
200 const StringRef name
= nameArg
->getString();
201 for (auto thread_name
: allow_thread_names
) {
202 if (name
.equals(thread_name
)) {
211 /// This matcher will match all accesses to AddRef or Release methods.
212 AST_MATCHER(MemberExpr
, isAddRefOrRelease
) {
213 ValueDecl
*Member
= Node
.getMemberDecl();
214 CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(Member
);
216 const auto &Name
= getNameChecked(Method
);
217 return Name
== "AddRef" || Name
== "Release";
222 /// This matcher will select classes which are refcounted AND have an mRefCnt
224 AST_MATCHER(CXXRecordDecl
, hasRefCntMember
) {
225 return isClassRefCounted(&Node
) && getClassRefCntMember(&Node
);
228 /// This matcher will select classes which are refcounted.
229 AST_MATCHER(CXXRecordDecl
, isRefCounted
) { return isClassRefCounted(&Node
); }
231 AST_MATCHER(QualType
, hasVTable
) { return typeHasVTable(Node
); }
233 AST_MATCHER(CXXRecordDecl
, hasNeedsNoVTableTypeAttr
) {
234 return hasCustomAttribute
<moz_needs_no_vtable_type
>(&Node
);
237 /// This matcher will select classes which are non-memmovable
238 AST_MATCHER(QualType
, isNonMemMovable
) {
239 return NonMemMovable
.hasEffectiveAnnotation(Node
);
242 /// This matcher will select classes which require a memmovable template arg
243 AST_MATCHER(CXXRecordDecl
, needsMemMovableTemplateArg
) {
244 return hasCustomAttribute
<moz_needs_memmovable_type
>(&Node
);
247 /// This matcher will select classes which require all members to be memmovable
248 AST_MATCHER(CXXRecordDecl
, needsMemMovableMembers
) {
249 return hasCustomAttribute
<moz_needs_memmovable_members
>(&Node
);
252 AST_MATCHER(CXXConstructorDecl
, isInterestingImplicitCtor
) {
253 const CXXConstructorDecl
*Declaration
= Node
.getCanonicalDecl();
255 // Skip constructors in system headers
256 !ASTIsInSystemHeader(Declaration
->getASTContext(), *Declaration
) &&
257 // Skip ignored namespaces and paths
258 !isInIgnoredNamespaceForImplicitCtor(Declaration
) &&
259 !inThirdPartyPath(Declaration
) &&
260 // We only want Converting constructors
261 Declaration
->isConvertingConstructor(false) &&
262 // We don't want copy of move constructors, as those are allowed to be
264 !Declaration
->isCopyOrMoveConstructor() &&
265 // We don't want inheriting constructors, since using declarations can't
267 !Declaration
->isInheritingConstructor() &&
268 // We don't want deleted constructors.
269 !Declaration
->isDeleted();
272 AST_MATCHER_P(Expr
, ignoreTrivials
, internal::Matcher
<Expr
>, InnerMatcher
) {
273 return InnerMatcher
.matches(*IgnoreTrivials(&Node
), Finder
, Builder
);
276 // Takes two matchers: the first one is a condition; the second is a matcher to
277 // be applied once we are done unwrapping trivials. While the condition does
278 // not match and we're looking at a trivial, will keep unwrapping the trivial
279 // and trying again. Once the condition matches, we will go ahead and unwrap all
280 // trivials and apply the inner matcher to the result.
282 // The expected use here is if we want to condition a match on some typecheck
283 // but apply the match to only non-trivials, because there are trivials (e.g.
284 // casts) that can change types.
285 AST_MATCHER_P2(Expr
, ignoreTrivialsConditional
, internal::Matcher
<Expr
>,
286 Condition
, internal::Matcher
<Expr
>, InnerMatcher
) {
287 const Expr
*node
= &Node
;
289 if (Condition
.matches(*node
, Finder
, Builder
)) {
290 return InnerMatcher
.matches(*IgnoreTrivials(node
), Finder
, Builder
);
292 const Expr
*newNode
= MaybeSkipOneTrivial(node
);
293 if (newNode
== node
) {
300 // We can't call this "isImplicit" since it clashes with an existing matcher in
302 AST_MATCHER(CXXConstructorDecl
, isMarkedImplicit
) {
303 return hasCustomAttribute
<moz_implicit
>(&Node
);
306 AST_MATCHER(CXXRecordDecl
, isConcreteClass
) { return !Node
.isAbstract(); }
308 AST_MATCHER(QualType
, autoNonAutoableType
) {
309 if (const AutoType
*T
= Node
->getContainedAutoType()) {
310 if (const CXXRecordDecl
*Rec
= T
->getAsCXXRecordDecl()) {
311 return hasCustomAttribute
<moz_non_autoable
>(Rec
);
317 AST_MATCHER(CXXConstructorDecl
, isExplicitMoveConstructor
) {
318 return Node
.isExplicit() && Node
.isMoveConstructor();
321 AST_MATCHER(CXXConstructorDecl
, isCompilerProvidedCopyConstructor
) {
322 return !Node
.isUserProvided() && Node
.isCopyConstructor();
325 AST_MATCHER(CallExpr
, isAssertAssignmentTestFunc
) {
326 static const std::string AssertName
= "MOZ_AssertAssignmentTest";
327 const FunctionDecl
*Method
= Node
.getDirectCallee();
329 return Method
&& Method
->getDeclName().isIdentifier() &&
330 Method
->getName() == AssertName
;
333 AST_MATCHER(CallExpr
, isSnprintfLikeFunc
) {
334 static const std::string Snprintf
= "snprintf";
335 static const std::string Vsnprintf
= "vsnprintf";
336 const FunctionDecl
*Func
= Node
.getDirectCallee();
338 if (!Func
|| isa
<CXXMethodDecl
>(Func
)) {
342 StringRef Name
= getNameChecked(Func
);
343 if (Name
!= Snprintf
&& Name
!= Vsnprintf
) {
347 return !inThirdPartyPath(Node
.getBeginLoc(),
348 Finder
->getASTContext().getSourceManager()) &&
349 !isIgnoredPathForSprintfLiteral(
350 &Node
, Finder
->getASTContext().getSourceManager());
353 AST_MATCHER(CXXRecordDecl
, isLambdaDecl
) { return Node
.isLambda(); }
355 AST_MATCHER(QualType
, isRefPtr
) { return typeIsRefPtr(Node
); }
357 AST_MATCHER(QualType
, isSmartPtrToRefCounted
) {
358 auto *D
= getNonTemplateSpecializedCXXRecordDecl(Node
);
363 D
= D
->getCanonicalDecl();
365 return D
&& hasCustomAttribute
<moz_is_smartptr_to_refcounted
>(D
);
368 AST_MATCHER(ClassTemplateSpecializationDecl
, isSmartPtrToRefCountedDecl
) {
369 auto *D
= dyn_cast_or_null
<CXXRecordDecl
>(
370 Node
.getSpecializedTemplate()->getTemplatedDecl());
375 D
= D
->getCanonicalDecl();
377 return D
&& hasCustomAttribute
<moz_is_smartptr_to_refcounted
>(D
);
380 AST_MATCHER(CXXRecordDecl
, hasBaseClasses
) {
381 const CXXRecordDecl
*Decl
= Node
.getCanonicalDecl();
383 // Must have definition and should inherit other classes
384 return Decl
&& Decl
->hasDefinition() && Decl
->getNumBases();
387 AST_MATCHER(CXXMethodDecl
, isRequiredBaseMethod
) {
388 const CXXMethodDecl
*Decl
= Node
.getCanonicalDecl();
389 return Decl
&& hasCustomAttribute
<moz_required_base_method
>(Decl
);
392 AST_MATCHER(CXXMethodDecl
, isNonVirtual
) {
393 const CXXMethodDecl
*Decl
= Node
.getCanonicalDecl();
394 return Decl
&& !Decl
->isVirtual();
397 AST_MATCHER(FunctionDecl
, isMozMustReturnFromCaller
) {
398 const FunctionDecl
*Decl
= Node
.getCanonicalDecl();
400 hasCustomAttribute
<moz_must_return_from_caller_if_this_is_arg
>(Decl
);
403 AST_MATCHER(FunctionDecl
, isMozTemporaryLifetimeBound
) {
404 const FunctionDecl
*Decl
= Node
.getCanonicalDecl();
405 return Decl
&& hasCustomAttribute
<moz_lifetime_bound
>(Decl
);
408 /// This matcher will select default args which have nullptr as the value.
409 AST_MATCHER(CXXDefaultArgExpr
, isNullDefaultArg
) {
410 const Expr
*Expr
= Node
.getExpr();
411 return Expr
&& Expr
->isNullPointerConstant(Finder
->getASTContext(),
412 Expr::NPC_NeverValueDependent
);
415 AST_MATCHER(UsingDirectiveDecl
, isUsingNamespaceMozillaJava
) {
416 const NamespaceDecl
*Namespace
= Node
.getNominatedNamespace();
417 const std::string
&FQName
= Namespace
->getQualifiedNameAsString();
419 static const char NAMESPACE
[] = "mozilla::java";
420 static const char PREFIX
[] = "mozilla::java::";
422 // We match both the `mozilla::java` namespace itself as well as any other
423 // namespaces contained within the `mozilla::java` namespace.
424 return !FQName
.compare(NAMESPACE
) ||
425 !FQName
.compare(0, sizeof(PREFIX
) - 1, PREFIX
);
428 AST_MATCHER(MemberExpr
, hasKnownLiveAnnotation
) {
429 ValueDecl
*Member
= Node
.getMemberDecl();
430 FieldDecl
*Field
= dyn_cast
<FieldDecl
>(Member
);
431 return Field
&& hasCustomAttribute
<moz_known_live
>(Field
);
434 } // namespace ast_matchers