clang-tools 8.0.0

StringConstructorCheck.cpp
Go to the documentation of this file.
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 // Check the literal string constructor with char pointer.
105 // [i.e. string (const char* s);]
106 Finder->addMatcher(
107 cxxConstructExpr(hasDeclaration(cxxMethodDecl(hasName("basic_string"))),
108 hasArgument(0, expr().bind("from-ptr")),
109 hasArgument(1, unless(hasType(isInteger()))))
110 .bind("constructor"),
111 this);
112 }
113
114 void StringConstructorCheck::check(const MatchFinder::MatchResult &Result) {
115 const ASTContext &Ctx = *Result.Context;
116 const auto *E = Result.Nodes.getNodeAs<CXXConstructExpr>("constructor");
117 assert(E && "missing constructor expression");
118 SourceLocation Loc = E->getBeginLoc();
119
120 if (Result.Nodes.getNodeAs<Expr>("swapped-parameter")) {
121 const Expr *P0 = E->getArg(0);
122 const Expr *P1 = E->getArg(1);
123 diag(Loc, "string constructor parameters are probably swapped;"
124 " expecting string(count, character)")
125 << tooling::fixit::createReplacement(*P0, *P1, Ctx)
126 << tooling::fixit::createReplacement(*P1, *P0, Ctx);
127 } else if (Result.Nodes.getNodeAs<Expr>("empty-string")) {
128 diag(Loc, "constructor creating an empty string");
129 } else if (Result.Nodes.getNodeAs<Expr>("negative-length")) {
130 diag(Loc, "negative value used as length parameter");
131 } else if (Result.Nodes.getNodeAs<Expr>("large-length")) {
132 if (WarnOnLargeLength)
133 diag(Loc, "suspicious large length parameter");
134 } else if (Result.Nodes.getNodeAs<Expr>("literal-with-length")) {
135 const auto *Str = Result.Nodes.getNodeAs<StringLiteral>("str");
136 const auto *Lit = Result.Nodes.getNodeAs<IntegerLiteral>("int");
137 if (Lit->getValue().ugt(Str->getLength())) {
138 diag(Loc, "length is bigger then string literal size");
139 }
140 } else if (const auto *Ptr = Result.Nodes.getNodeAs<Expr>("from-ptr")) {
141 Expr::EvalResult ConstPtr;
142 if (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
Loc
SourceLocation Loc
&#39;#&#39; location in the include directive
Definition: IncludeOrderCheck.cpp:37
clang::ast_matchers
Definition: AbseilMatcher.h:15
clang::tidy::OptionsView::store
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Definition: ClangTidy.cpp:473
clang::tidy::bugprone::StringConstructorCheck::registerMatchers
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
Definition: StringConstructorCheck.cpp:38
clang::tidy::ClangTidyCheck::getLangOpts
LangOptions getLangOpts() const
Returns the language options from the context.
Definition: ClangTidy.h:187
clang::tidy::ClangTidyCheck
Base class for all clang-tidy checks.
Definition: ClangTidy.h:127
clang::tidy::ClangTidyCheck::Options
OptionsView Options
Definition: ClangTidy.h:183
Ctx
Context Ctx
Definition: TUScheduler.cpp:224
StringConstructorCheck.h
Name
static constexpr llvm::StringLiteral Name
Definition: UppercaseLiteralSuffixCheck.cpp:28
clang::tidy::ClangTidyOptions::OptionMap
std::map< std::string, std::string > OptionMap
Definition: ClangTidyOptions.h:98
Result
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
Definition: ClangdServer.cpp:60
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ChangeNamespace.cpp:18
clang::ast_matchers::AST_MATCHER_P
AST_MATCHER_P(FunctionDecl, throws, internal::Matcher< Type >, InnerMatcher)
Definition: ExceptionEscapeCheck.cpp:139
clang::tidy::bugprone::StringConstructorCheck::check
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
Definition: StringConstructorCheck.cpp:114
clang::tidy::ClangTidyContext
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
Definition: ClangTidyDiagnosticConsumer.h:100
clang::tidy::bugprone::StringConstructorCheck::storeOptions
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
Definition: StringConstructorCheck.cpp:33
clang::tidy::ClangTidyCheck::diag
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check&#39;s name.
Definition: ClangTidy.cpp:438