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