• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- TwineLocalCheck.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 "TwineLocalCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchers.h"
12 #include "clang/Lex/Lexer.h"
13 
14 using namespace clang::ast_matchers;
15 
16 namespace clang {
17 namespace tidy {
18 namespace llvm_check {
19 
registerMatchers(MatchFinder * Finder)20 void TwineLocalCheck::registerMatchers(MatchFinder *Finder) {
21   auto TwineType =
22       qualType(hasDeclaration(cxxRecordDecl(hasName("::llvm::Twine"))));
23   Finder->addMatcher(
24       varDecl(unless(parmVarDecl()), hasType(TwineType)).bind("variable"),
25       this);
26 }
27 
check(const MatchFinder::MatchResult & Result)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");
32 
33   // If this VarDecl has an initializer try to fix it.
34   if (VD->hasInit()) {
35     // Peel away implicit constructors and casts so we can see the actual type
36     // of the initializer.
37     const Expr *C = VD->getInit()->IgnoreImplicit();
38 
39     while (isa<CXXConstructExpr>(C)) {
40       if (cast<CXXConstructExpr>(C)->getNumArgs() == 0)
41         break;
42       C = cast<CXXConstructExpr>(C)->getArg(0)->IgnoreParenImpCasts();
43     }
44 
45     SourceRange TypeRange =
46         VD->getTypeSourceInfo()->getTypeLoc().getSourceRange();
47 
48     // A real Twine, turn it into a std::string.
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()");
56     } else {
57       // Just an implicit conversion. Insert the real type.
58       Diag << FixItHint::CreateReplacement(
59           TypeRange,
60           C->getType().getAsString(Result.Context->getPrintingPolicy()));
61     }
62   }
63 }
64 
65 } // namespace llvm_check
66 } // namespace tidy
67 } // namespace clang
68