11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchers.h"
13 #include "clang/Lex/Lexer.h"
15 using namespace clang::ast_matchers;
21 void TwineLocalCheck::registerMatchers(MatchFinder *
Finder) {
23 qualType(hasDeclaration(recordDecl(hasName(
"::llvm::Twine"))));
24 Finder->addMatcher(varDecl(hasType(TwineType)).bind(
"variable"),
this);
27 void TwineLocalCheck::check(
const MatchFinder::MatchResult &Result) {
28 const auto *VD = Result.Nodes.getNodeAs<VarDecl>(
"variable");
29 auto Diag = diag(VD->getLocation(),
30 "twine variables are prone to use-after-free bugs");
36 const Expr *C = VD->getInit()->IgnoreImplicit();
38 while (isa<CXXConstructExpr>(C)) {
39 if (cast<CXXConstructExpr>(C)->getNumArgs() == 0)
41 C = cast<CXXConstructExpr>(C)->getArg(0)->IgnoreParenImpCasts();
44 SourceRange TypeRange =
45 VD->getTypeSourceInfo()->getTypeLoc().getSourceRange();
48 if (VD->getType()->getCanonicalTypeUnqualified() ==
49 C->getType()->getCanonicalTypeUnqualified()) {
50 SourceLocation EndLoc = Lexer::getLocForEndOfToken(
51 VD->getInit()->getLocEnd(), 0, *Result.SourceManager, getLangOpts());
52 Diag << FixItHint::CreateReplacement(TypeRange,
"std::string")
53 << FixItHint::CreateInsertion(VD->getInit()->getLocStart(),
"(")
54 << FixItHint::CreateInsertion(EndLoc,
").str()");
57 Diag << FixItHint::CreateReplacement(
59 C->getType().getAsString(Result.Context->getPrintingPolicy()));
std::unique_ptr< ast_matchers::MatchFinder > Finder