10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchers.h"
12 #include "clang/Lex/Lexer.h"
18 namespace llvm_check {
20 void TwineLocalCheck::registerMatchers(MatchFinder *Finder) {
22 qualType(hasDeclaration(cxxRecordDecl(hasName(
"::llvm::Twine"))));
24 varDecl(unless(parmVarDecl()), hasType(TwineType)).bind(
"variable"),
28 void TwineLocalCheck::check(
const MatchFinder::MatchResult &Result) {
29 const auto *VD = Result.Nodes.getNodeAs<VarDecl>(
"variable");
30 auto Diag = diag(VD->getLocation(),
31 "twine variables are prone to use-after-free bugs");
37 const Expr *C = VD->getInit()->IgnoreImplicit();
39 while (isa<CXXConstructExpr>(C)) {
40 if (cast<CXXConstructExpr>(C)->getNumArgs() == 0)
42 C = cast<CXXConstructExpr>(C)->getArg(0)->IgnoreParenImpCasts();
45 SourceRange TypeRange =
46 VD->getTypeSourceInfo()->getTypeLoc().getSourceRange();
49 if (VD->getType()->getCanonicalTypeUnqualified() ==
50 C->getType()->getCanonicalTypeUnqualified()) {
51 SourceLocation EndLoc = Lexer::getLocForEndOfToken(
52 VD->getInit()->getEndLoc(), 0, *Result.SourceManager, getLangOpts());
53 Diag << FixItHint::CreateReplacement(TypeRange,
"std::string")
54 << FixItHint::CreateInsertion(VD->getInit()->getBeginLoc(),
"(")
55 << FixItHint::CreateInsertion(EndLoc,
").str()");
58 Diag << FixItHint::CreateReplacement(
60 C->getType().getAsString(Result.Context->getPrintingPolicy()));