10 #include "../utils/ASTUtils.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/Lex/Lexer.h"
23 std::string buildFixMsgForStringFlag(
const Expr *Arg,
const SourceManager &SM,
24 const LangOptions &
LangOpts,
char Mode) {
25 if (Arg->getBeginLoc().isMacroID())
27 CharSourceRange::getTokenRange(Arg->getSourceRange()), SM,
29 " \"" + Twine(Mode) +
"\"")
32 StringRef SR = cast<StringLiteral>(Arg->IgnoreParenCasts())->getString();
33 return (
"\"" + SR + Twine(Mode) +
"\"").str();
37 const char *CloexecCheck::FuncDeclBindingStr =
"funcDecl";
39 const char *CloexecCheck::FuncBindingStr =
"func";
41 void CloexecCheck::registerMatchersImpl(
42 MatchFinder *Finder, internal::Matcher<FunctionDecl> Function) {
46 callee(functionDecl(isExternC(), Function).bind(FuncDeclBindingStr)))
47 .bind(FuncBindingStr),
51 void CloexecCheck::insertMacroFlag(
const MatchFinder::MatchResult &Result,
52 StringRef MacroFlag,
int ArgPos) {
53 const auto *MatchedCall = Result.Nodes.getNodeAs<CallExpr>(FuncBindingStr);
54 const auto *FlagArg = MatchedCall->getArg(ArgPos);
55 const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>(FuncDeclBindingStr);
56 SourceManager &SM = *Result.SourceManager;
59 Result.Context->getLangOpts(),
63 SourceLocation EndLoc =
64 Lexer::getLocForEndOfToken(SM.getFileLoc(FlagArg->getEndLoc()), 0, SM,
65 Result.Context->getLangOpts());
67 diag(EndLoc,
"%0 should use %1 where possible")
69 << FixItHint::CreateInsertion(EndLoc, (Twine(
" | ") + MacroFlag).str());
72 void CloexecCheck::replaceFunc(
const MatchFinder::MatchResult &Result,
73 StringRef WarningMsg, StringRef FixMsg) {
74 const auto *MatchedCall = Result.Nodes.getNodeAs<CallExpr>(FuncBindingStr);
75 diag(MatchedCall->getBeginLoc(), WarningMsg)
76 << FixItHint::CreateReplacement(MatchedCall->getSourceRange(), FixMsg);
79 void CloexecCheck::insertStringFlag(
80 const ast_matchers::MatchFinder::MatchResult &Result,
const char Mode,
82 const auto *MatchedCall = Result.Nodes.getNodeAs<CallExpr>(FuncBindingStr);
83 const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>(FuncDeclBindingStr);
84 const auto *ModeArg = MatchedCall->getArg(ArgPos);
87 const auto *ModeStr = dyn_cast<StringLiteral>(ModeArg->IgnoreParenCasts());
88 if (!ModeStr || ModeStr->getString().contains(Mode))
91 std::string ReplacementText = buildFixMsgForStringFlag(
92 ModeArg, *Result.SourceManager, Result.Context->getLangOpts(), Mode);
94 diag(ModeArg->getBeginLoc(),
"use %0 mode '%1' to set O_CLOEXEC")
95 << FD << std::string(1, Mode)
96 << FixItHint::CreateReplacement(ModeArg->getSourceRange(),
100 StringRef CloexecCheck::getSpellingArg(
const MatchFinder::MatchResult &Result,
102 const auto *MatchedCall = Result.Nodes.getNodeAs<CallExpr>(FuncBindingStr);
103 const SourceManager &SM = *Result.SourceManager;
105 CharSourceRange::getTokenRange(MatchedCall->getArg(N)->getSourceRange()),
106 SM, Result.Context->getLangOpts());