1 //===--- CloexecOpenCheck.cpp - clang-tidy---------------------------------===//
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 "CloexecOpenCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 
13 using namespace clang::ast_matchers;
14 
15 namespace clang {
16 namespace tidy {
17 namespace android {
18 
registerMatchers(MatchFinder * Finder)19 void CloexecOpenCheck::registerMatchers(MatchFinder *Finder) {
20   auto CharPointerType = hasType(pointerType(pointee(isAnyCharacter())));
21   registerMatchersImpl(Finder,
22                        functionDecl(isExternC(), returns(isInteger()),
23                                     hasAnyName("open", "open64"),
24                                     hasParameter(0, CharPointerType),
25                                     hasParameter(1, hasType(isInteger()))));
26   registerMatchersImpl(Finder,
27                        functionDecl(isExternC(), returns(isInteger()),
28                                     hasName("openat"),
29                                     hasParameter(0, hasType(isInteger())),
30                                     hasParameter(1, CharPointerType),
31                                     hasParameter(2, hasType(isInteger()))));
32 }
33 
check(const MatchFinder::MatchResult & Result)34 void CloexecOpenCheck::check(const MatchFinder::MatchResult &Result) {
35   const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>(FuncDeclBindingStr);
36   assert(FD->param_size() > 1);
37   int ArgPos = (FD->param_size() > 2) ? 2 : 1;
38   insertMacroFlag(Result, /*MacroFlag=*/"O_CLOEXEC", ArgPos);
39 }
40 
41 } // namespace android
42 } // namespace tidy
43 } // namespace clang
44