1 //===--- StringConstructorCheck.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 
10 #include "StringConstructorCheck.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/Tooling/FixIt.h"
14 
15 using namespace clang::ast_matchers;
16 
17 namespace clang {
18 namespace tidy {
19 namespace bugprone {
20 
21 namespace {
22 AST_MATCHER_P(IntegerLiteral, isBiggerThan, unsigned, N) {
23   return Node.getValue().getZExtValue() > N;
24 }
25 } // namespace
26 
27 StringConstructorCheck::StringConstructorCheck(StringRef Name,
28                                                ClangTidyContext *Context)
29     : ClangTidyCheck(Name, Context),
30       WarnOnLargeLength(Options.get("WarnOnLargeLength", 1) != 0),
31       LargeLengthThreshold(Options.get("LargeLengthThreshold", 0x800000)) {}
32 
33 void StringConstructorCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
34   Options.store(Opts, "WarnOnLargeLength", WarnOnLargeLength);
35   Options.store(Opts, "LargeLengthThreshold", LargeLengthThreshold);
36 }
37 
38 void StringConstructorCheck::registerMatchers(MatchFinder *Finder) {
39   if (!getLangOpts().CPlusPlus)
40     return;
41 
42   const auto ZeroExpr = expr(ignoringParenImpCasts(integerLiteral(equals(0))));
43   const auto CharExpr = expr(ignoringParenImpCasts(characterLiteral()));
44   const auto NegativeExpr = expr(ignoringParenImpCasts(
45       unaryOperator(hasOperatorName("-"),
46                     hasUnaryOperand(integerLiteral(unless(equals(0)))))));
47   const auto LargeLengthExpr = expr(ignoringParenImpCasts(
48       integerLiteral(isBiggerThan(LargeLengthThreshold))));
49   const auto CharPtrType = type(anyOf(pointerType(), arrayType()));
50 
51   // Match a string-literal; even through a declaration with initializer.
52   const auto BoundStringLiteral = stringLiteral().bind("str");
53   const auto ConstStrLiteralDecl = varDecl(
54       isDefinition(), hasType(constantArrayType()), hasType(isConstQualified()),
55       hasInitializer(ignoringParenImpCasts(BoundStringLiteral)));
56   const auto ConstPtrStrLiteralDecl = varDecl(
57       isDefinition(),
58       hasType(pointerType(pointee(isAnyCharacter(), isConstQualified()))),
59       hasInitializer(ignoringParenImpCasts(BoundStringLiteral)));
60   const auto ConstStrLiteral = expr(ignoringParenImpCasts(anyOf(
61       BoundStringLiteral, declRefExpr(hasDeclaration(anyOf(
62                               ConstPtrStrLiteralDecl, ConstStrLiteralDecl))))));
63 
64   // Check the fill constructor. Fills the string with n consecutive copies of
65   // character c. [i.e string(size_t n, char c);].
66   Finder->addMatcher(
67       cxxConstructExpr(
68           hasDeclaration(cxxMethodDecl(hasName("basic_string"))),
69           hasArgument(0, hasType(qualType(isInteger()))),
70           hasArgument(1, hasType(qualType(isInteger()))),
71           anyOf(
72               // Detect the expression: string('x', 40);
73               hasArgument(0, CharExpr.bind("swapped-parameter")),
74               // Detect the expression: string(0, ...);
75               hasArgument(0, ZeroExpr.bind("empty-string")),
76               // Detect the expression: string(-4, ...);
77               hasArgument(0, NegativeExpr.bind("negative-length")),
78               // Detect the expression: string(0x1234567, ...);
79               hasArgument(0, LargeLengthExpr.bind("large-length"))))
80           .bind("constructor"),
81       this);
82 
83   // Check the literal string constructor with char pointer and length
84   // parameters. [i.e. string (const char* s, size_t n);]
85   Finder->addMatcher(
86       cxxConstructExpr(
87           hasDeclaration(cxxMethodDecl(hasName("basic_string"))),
88           hasArgument(0, hasType(CharPtrType)),
89           hasArgument(1, hasType(isInteger())),
90           anyOf(
91               // Detect the expression: string("...", 0);
92               hasArgument(1, ZeroExpr.bind("empty-string")),
93               // Detect the expression: string("...", -4);
94               hasArgument(1, NegativeExpr.bind("negative-length")),
95               // Detect the expression: string("lit", 0x1234567);
96               hasArgument(1, LargeLengthExpr.bind("large-length")),
97               // Detect the expression: string("lit", 5)
98               allOf(hasArgument(0, ConstStrLiteral.bind("literal-with-length")),
99                     hasArgument(1, ignoringParenImpCasts(
100                                        integerLiteral().bind("int"))))))
101           .bind("constructor"),
102       this);
103 }
104 
105 void StringConstructorCheck::check(const MatchFinder::MatchResult &Result) {
106   const ASTContext &Ctx = *Result.Context;
107   const auto *E = Result.Nodes.getNodeAs<CXXConstructExpr>("constructor");
108   assert(E && "missing constructor expression");
109   SourceLocation Loc = E->getLocStart();
110 
111   if (Result.Nodes.getNodeAs<Expr>("swapped-parameter")) {
112     const Expr *P0 = E->getArg(0);
113     const Expr *P1 = E->getArg(1);
114     diag(Loc, "string constructor parameters are probably swapped;"
115               " expecting string(count, character)")
116         << tooling::fixit::createReplacement(*P0, *P1, Ctx)
117         << tooling::fixit::createReplacement(*P1, *P0, Ctx);
118   } else if (Result.Nodes.getNodeAs<Expr>("empty-string")) {
119     diag(Loc, "constructor creating an empty string");
120   } else if (Result.Nodes.getNodeAs<Expr>("negative-length")) {
121     diag(Loc, "negative value used as length parameter");
122   } else if (Result.Nodes.getNodeAs<Expr>("large-length")) {
123     if (WarnOnLargeLength)
124       diag(Loc, "suspicious large length parameter");
125   } else if (Result.Nodes.getNodeAs<Expr>("literal-with-length")) {
126     const auto *Str = Result.Nodes.getNodeAs<StringLiteral>("str");
127     const auto *Lit = Result.Nodes.getNodeAs<IntegerLiteral>("int");
128     if (Lit->getValue().ugt(Str->getLength())) {
129       diag(Loc, "length is bigger then string literal size");
130     }
131   }
132 }
133 
134 } // namespace bugprone
135 } // namespace tidy
136 } // namespace clang
137