1 //===--- CloexecAcceptCheck.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 "CloexecAcceptCheck.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 CloexecAcceptCheck::registerMatchers(MatchFinder *Finder) {
20   auto SockAddrPointerType =
21       hasType(pointsTo(recordDecl(isStruct(), hasName("sockaddr"))));
22   auto SockLenPointerType = hasType(pointsTo(namedDecl(hasName("socklen_t"))));
23 
24   registerMatchersImpl(Finder,
25                        functionDecl(returns(isInteger()), hasName("accept"),
26                                     hasParameter(0, hasType(isInteger())),
27                                     hasParameter(1, SockAddrPointerType),
28                                     hasParameter(2, SockLenPointerType)));
29 }
30 
check(const MatchFinder::MatchResult & Result)31 void CloexecAcceptCheck::check(const MatchFinder::MatchResult &Result) {
32   std::string ReplacementText =
33       (Twine("accept4(") + getSpellingArg(Result, 0) + ", " +
34        getSpellingArg(Result, 1) + ", " + getSpellingArg(Result, 2) +
35        ", SOCK_CLOEXEC)")
36           .str();
37 
38   replaceFunc(
39       Result,
40       "prefer accept4() to accept() because accept4() allows SOCK_CLOEXEC",
41       ReplacementText);
42 }
43 
44 } // namespace android
45 } // namespace tidy
46 } // namespace clang
47