clang-tools 22.0.0git
StringConstructorCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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
11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/Tooling/FixIt.h"
14
15using namespace clang::ast_matchers;
16
17namespace clang::tidy::bugprone {
18
19namespace {
20AST_MATCHER_P(IntegerLiteral, isBiggerThan, unsigned, N) {
21 return Node.getValue().getZExtValue() > N;
22}
23} // namespace
24
25static const char DefaultStringNames[] =
26 "::std::basic_string;::std::basic_string_view";
27
28static std::vector<StringRef>
29removeNamespaces(const std::vector<StringRef> &Names) {
30 std::vector<StringRef> Result;
31 Result.reserve(Names.size());
32 for (StringRef Name : Names) {
33 std::string::size_type ColonPos = Name.rfind(':');
34 Result.push_back(
35 Name.substr(ColonPos == std::string::npos ? 0 : ColonPos + 1));
36 }
37 return Result;
38}
39
41 ClangTidyContext *Context)
42 : ClangTidyCheck(Name, Context),
43 IsStringviewNullptrCheckEnabled(
44 Context->isCheckEnabled("bugprone-stringview-nullptr")),
45 WarnOnLargeLength(Options.get("WarnOnLargeLength", true)),
46 LargeLengthThreshold(Options.get("LargeLengthThreshold", 0x800000)),
47 StringNames(utils::options::parseStringList(
48 Options.get("StringNames", DefaultStringNames))) {}
49
51 Options.store(Opts, "WarnOnLargeLength", WarnOnLargeLength);
52 Options.store(Opts, "LargeLengthThreshold", LargeLengthThreshold);
53 Options.store(Opts, "StringNames", DefaultStringNames);
54}
55
57 const auto ZeroExpr = expr(ignoringParenImpCasts(integerLiteral(equals(0))));
58 const auto CharExpr = expr(ignoringParenImpCasts(characterLiteral()));
59 const auto NegativeExpr = expr(ignoringParenImpCasts(
60 unaryOperator(hasOperatorName("-"),
61 hasUnaryOperand(integerLiteral(unless(equals(0)))))));
62 const auto LargeLengthExpr = expr(ignoringParenImpCasts(
63 integerLiteral(isBiggerThan(LargeLengthThreshold))));
64 const auto CharPtrType = type(anyOf(pointerType(), arrayType()));
65
66 // Match a string-literal; even through a declaration with initializer.
67 const auto BoundStringLiteral = stringLiteral().bind("str");
68 const auto ConstStrLiteralDecl = varDecl(
69 isDefinition(), hasType(constantArrayType()), hasType(isConstQualified()),
70 hasInitializer(ignoringParenImpCasts(BoundStringLiteral)));
71 const auto ConstPtrStrLiteralDecl = varDecl(
72 isDefinition(),
73 hasType(pointerType(pointee(isAnyCharacter(), isConstQualified()))),
74 hasInitializer(ignoringParenImpCasts(BoundStringLiteral)));
75 const auto ConstStrLiteral = expr(ignoringParenImpCasts(anyOf(
76 BoundStringLiteral, declRefExpr(hasDeclaration(anyOf(
77 ConstPtrStrLiteralDecl, ConstStrLiteralDecl))))));
78
79 // Check the fill constructor. Fills the string with n consecutive copies of
80 // character c. [i.e string(size_t n, char c);].
81 Finder->addMatcher(
82 cxxConstructExpr(
83 hasDeclaration(cxxMethodDecl(hasName("basic_string"))),
84 argumentCountIs(2), hasArgument(0, hasType(qualType(isInteger()))),
85 hasArgument(1, hasType(qualType(isInteger()))),
86 anyOf(
87 // Detect the expression: string('x', 40);
88 hasArgument(0, CharExpr.bind("swapped-parameter")),
89 // Detect the expression: string(0, ...);
90 hasArgument(0, ZeroExpr.bind("empty-string")),
91 // Detect the expression: string(-4, ...);
92 hasArgument(0, NegativeExpr.bind("negative-length")),
93 // Detect the expression: string(0x1234567, ...);
94 hasArgument(0, LargeLengthExpr.bind("large-length"))))
95 .bind("constructor"),
96 this);
97
98 // Check the literal string constructor with char pointer and length
99 // parameters. [i.e. string (const char* s, size_t n);]
100 Finder->addMatcher(
101 cxxConstructExpr(
102 hasDeclaration(cxxConstructorDecl(ofClass(
103 cxxRecordDecl(hasAnyName(removeNamespaces(StringNames)))))),
104 argumentCountIs(2), hasArgument(0, hasType(CharPtrType)),
105 hasArgument(1, hasType(isInteger())),
106 anyOf(
107 // Detect the expression: string("...", 0);
108 hasArgument(1, ZeroExpr.bind("empty-string")),
109 // Detect the expression: string("...", -4);
110 hasArgument(1, NegativeExpr.bind("negative-length")),
111 // Detect the expression: string("lit", 0x1234567);
112 hasArgument(1, LargeLengthExpr.bind("large-length")),
113 // Detect the expression: string("lit", 5)
114 allOf(hasArgument(0, ConstStrLiteral.bind("literal-with-length")),
115 hasArgument(1, ignoringParenImpCasts(
116 integerLiteral().bind("length"))))))
117 .bind("constructor"),
118 this);
119
120 // Check the literal string constructor with char pointer, start position and
121 // length parameters. [i.e. string (const char* s, size_t pos, size_t count);]
122 Finder->addMatcher(
123 cxxConstructExpr(
124 hasDeclaration(cxxConstructorDecl(ofClass(
125 cxxRecordDecl(hasAnyName(removeNamespaces(StringNames)))))),
126 argumentCountIs(3), hasArgument(0, hasType(CharPtrType)),
127 hasArgument(1, hasType(qualType(isInteger()))),
128 hasArgument(2, hasType(qualType(isInteger()))),
129 anyOf(
130 // Detect the expression: string("...", 1, 0);
131 hasArgument(2, ZeroExpr.bind("empty-string")),
132 // Detect the expression: string("...", -4, 1);
133 hasArgument(1, NegativeExpr.bind("negative-pos")),
134 // Detect the expression: string("...", 0, -4);
135 hasArgument(2, NegativeExpr.bind("negative-length")),
136 // Detect the expression: string("lit", 0, 0x1234567);
137 hasArgument(2, LargeLengthExpr.bind("large-length")),
138 // Detect the expression: string("lit", 1, 5)
139 allOf(hasArgument(0, ConstStrLiteral.bind("literal-with-length")),
140 hasArgument(
141 1, ignoringParenImpCasts(integerLiteral().bind("pos"))),
142 hasArgument(2, ignoringParenImpCasts(
143 integerLiteral().bind("length"))))))
144 .bind("constructor"),
145 this);
146
147 // Check the literal string constructor with char pointer.
148 // [i.e. string (const char* s);]
149 Finder->addMatcher(
150 traverse(
151 TK_AsIs,
152 cxxConstructExpr(
153 hasDeclaration(cxxConstructorDecl(ofClass(anyOf(
154 cxxRecordDecl(hasName("basic_string_view"))
155 .bind("basic_string_view_decl"),
156 cxxRecordDecl(hasAnyName(removeNamespaces(StringNames))))))),
157 hasArgument(0, expr().bind("from-ptr")),
158 // do not match std::string(ptr, int)
159 // match std::string(ptr, alloc)
160 // match std::string(ptr)
161 anyOf(hasArgument(1, unless(hasType(isInteger()))),
162 argumentCountIs(1)))
163 .bind("constructor")),
164 this);
165}
166
167void StringConstructorCheck::check(const MatchFinder::MatchResult &Result) {
168 const ASTContext &Ctx = *Result.Context;
169 const auto *E = Result.Nodes.getNodeAs<CXXConstructExpr>("constructor");
170 assert(E && "missing constructor expression");
171 SourceLocation Loc = E->getBeginLoc();
172
173 if (Result.Nodes.getNodeAs<Expr>("swapped-parameter")) {
174 const Expr *P0 = E->getArg(0);
175 const Expr *P1 = E->getArg(1);
176 diag(Loc, "string constructor parameters are probably swapped;"
177 " expecting string(count, character)")
178 << tooling::fixit::createReplacement(*P0, *P1, Ctx)
179 << tooling::fixit::createReplacement(*P1, *P0, Ctx);
180 } else if (Result.Nodes.getNodeAs<Expr>("empty-string")) {
181 diag(Loc, "constructor creating an empty string");
182 } else if (Result.Nodes.getNodeAs<Expr>("negative-length")) {
183 diag(Loc, "negative value used as length parameter");
184 } else if (Result.Nodes.getNodeAs<Expr>("negative-pos")) {
185 diag(Loc, "negative value used as position of the "
186 "first character parameter");
187 } else if (Result.Nodes.getNodeAs<Expr>("large-length")) {
188 if (WarnOnLargeLength)
189 diag(Loc, "suspicious large length parameter");
190 } else if (Result.Nodes.getNodeAs<Expr>("literal-with-length")) {
191 const auto *Str = Result.Nodes.getNodeAs<StringLiteral>("str");
192 const auto *Length = Result.Nodes.getNodeAs<IntegerLiteral>("length");
193 if (Length->getValue().ugt(Str->getLength())) {
194 diag(Loc, "length is bigger than string literal size");
195 return;
196 }
197 if (const auto *Pos = Result.Nodes.getNodeAs<IntegerLiteral>("pos")) {
198 if (Pos->getValue().uge(Str->getLength())) {
199 diag(Loc, "position of the first character parameter is bigger than "
200 "string literal character range");
201 } else if (Length->getValue().ugt(
202 (Str->getLength() - Pos->getValue()).getZExtValue())) {
203 diag(Loc, "length is bigger than remaining string literal size");
204 }
205 }
206 } else if (const auto *Ptr = Result.Nodes.getNodeAs<Expr>("from-ptr")) {
207 Expr::EvalResult ConstPtr;
208 if (!Ptr->isInstantiationDependent() &&
209 Ptr->EvaluateAsRValue(ConstPtr, Ctx) &&
210 ((ConstPtr.Val.isInt() && ConstPtr.Val.getInt().isZero()) ||
211 (ConstPtr.Val.isLValue() && ConstPtr.Val.isNullPointer()))) {
212 if (IsStringviewNullptrCheckEnabled &&
213 Result.Nodes.getNodeAs<CXXRecordDecl>("basic_string_view_decl")) {
214 // Filter out `basic_string_view` to avoid conflicts with
215 // `bugprone-stringview-nullptr`
216 return;
217 }
218 diag(Loc, "constructing string from nullptr is undefined behaviour");
219 }
220 }
221}
222
223} // namespace clang::tidy::bugprone
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
StringConstructorCheck(StringRef Name, ClangTidyContext *Context)
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
static std::vector< StringRef > removeNamespaces(const std::vector< StringRef > &Names)
static const char DefaultStringNames[]
AST_MATCHER_P(Stmt, isStatementIdenticalToBoundNode, std::string, ID)
llvm::StringMap< ClangTidyValue > OptionMap