1 //===--- CloexecFopenCheck.cpp - clang-tidy--------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. // 7 //===----------------------------------------------------------------------===// 8 9 #include "CloexecFopenCheck.h" 10 #include "clang/AST/ASTContext.h" 11 #include "clang/AST/Type.h" 12 #include "clang/ASTMatchers/ASTMatchFinder.h" 13 #include "clang/Lex/Lexer.h" 14 15 using namespace clang::ast_matchers; 16 17 namespace clang { 18 namespace tidy { 19 namespace android { 20 21 namespace { 22 static const char MODE = 'e'; 23 24 // Build the replace text. If it's string constant, add 'e' directly in the end 25 // of the string. Else, add "e". 26 std::string BuildReplaceText(const Expr *Arg, const SourceManager &SM, 27 const LangOptions &LangOpts) { 28 if (Arg->getLocStart().isMacroID()) 29 return (Lexer::getSourceText( 30 CharSourceRange::getTokenRange(Arg->getSourceRange()), SM, 31 LangOpts) + 32 " \"" + Twine(MODE) + "\"") 33 .str(); 34 35 StringRef SR = cast<StringLiteral>(Arg->IgnoreParenCasts())->getString(); 36 return ("\"" + SR + Twine(MODE) + "\"").str(); 37 } 38 } // namespace 39 40 void CloexecFopenCheck::registerMatchers(MatchFinder *Finder) { 41 auto CharPointerType = hasType(pointerType(pointee(isAnyCharacter()))); 42 43 Finder->addMatcher( 44 callExpr(callee(functionDecl(isExternC(), returns(asString("FILE *")), 45 hasName("fopen"), 46 hasParameter(0, CharPointerType), 47 hasParameter(1, CharPointerType)) 48 .bind("funcDecl"))) 49 .bind("fopenFn"), 50 this); 51 } 52 53 void CloexecFopenCheck::check(const MatchFinder::MatchResult &Result) { 54 const auto *MatchedCall = Result.Nodes.getNodeAs<CallExpr>("fopenFn"); 55 const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>("funcDecl"); 56 const Expr *ModeArg = MatchedCall->getArg(1); 57 58 // Check if the 'e' may be in the mode string. 59 const auto *ModeStr = dyn_cast<StringLiteral>(ModeArg->IgnoreParenCasts()); 60 if (!ModeStr || (ModeStr->getString().find(MODE) != StringRef::npos)) 61 return; 62 63 const std::string &ReplacementText = BuildReplaceText( 64 ModeArg, *Result.SourceManager, Result.Context->getLangOpts()); 65 66 diag(ModeArg->getLocStart(), "use %0 mode 'e' to set O_CLOEXEC") 67 << FD 68 << FixItHint::CreateReplacement(ModeArg->getSourceRange(), 69 ReplacementText); 70 } 71 72 } // namespace android 73 } // namespace tidy 74 } // namespace clang 75