Skip to content

Commit 28c1279

Browse files
authored
[clang-tidy] Add bugprone-suspicious-stringview-data-usage check (#83716)
This check identifies suspicious usages of std::string_view::data() that could lead to reading out-of-bounds data due to inadequate or incorrect string null termination. Closes #80854
1 parent 0a40f5d commit 28c1279

File tree

9 files changed

+268
-0
lines changed

9 files changed

+268
-0
lines changed

clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp

+3
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@
7373
#include "SuspiciousReallocUsageCheck.h"
7474
#include "SuspiciousSemicolonCheck.h"
7575
#include "SuspiciousStringCompareCheck.h"
76+
#include "SuspiciousStringviewDataUsageCheck.h"
7677
#include "SwappedArgumentsCheck.h"
7778
#include "SwitchMissingDefaultCaseCheck.h"
7879
#include "TerminatingContinueCheck.h"
@@ -218,6 +219,8 @@ class BugproneModule : public ClangTidyModule {
218219
"bugprone-suspicious-semicolon");
219220
CheckFactories.registerCheck<SuspiciousStringCompareCheck>(
220221
"bugprone-suspicious-string-compare");
222+
CheckFactories.registerCheck<SuspiciousStringviewDataUsageCheck>(
223+
"bugprone-suspicious-stringview-data-usage");
221224
CheckFactories.registerCheck<SwappedArgumentsCheck>(
222225
"bugprone-swapped-arguments");
223226
CheckFactories.registerCheck<TerminatingContinueCheck>(

clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ add_clang_library(clangTidyBugproneModule
2626
ImplicitWideningOfMultiplicationResultCheck.cpp
2727
InaccurateEraseCheck.cpp
2828
IncorrectEnableIfCheck.cpp
29+
SuspiciousStringviewDataUsageCheck.cpp
2930
SwitchMissingDefaultCaseCheck.cpp
3031
IncDecInConditionsCheck.cpp
3132
IncorrectRoundingsCheck.cpp
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
//===--- SuspiciousStringviewDataUsageCheck.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 "SuspiciousStringviewDataUsageCheck.h"
10+
#include "../utils/Matchers.h"
11+
#include "../utils/OptionsUtils.h"
12+
#include "clang/AST/ASTContext.h"
13+
#include "clang/ASTMatchers/ASTMatchFinder.h"
14+
15+
using namespace clang::ast_matchers;
16+
17+
namespace clang::tidy::bugprone {
18+
19+
SuspiciousStringviewDataUsageCheck::SuspiciousStringviewDataUsageCheck(
20+
StringRef Name, ClangTidyContext *Context)
21+
: ClangTidyCheck(Name, Context),
22+
StringViewTypes(utils::options::parseStringList(Options.get(
23+
"StringViewTypes", "::std::basic_string_view;::llvm::StringRef"))),
24+
AllowedCallees(
25+
utils::options::parseStringList(Options.get("AllowedCallees", ""))) {}
26+
27+
void SuspiciousStringviewDataUsageCheck::storeOptions(
28+
ClangTidyOptions::OptionMap &Opts) {
29+
Options.store(Opts, "StringViewTypes",
30+
utils::options::serializeStringList(StringViewTypes));
31+
Options.store(Opts, "AllowedCallees",
32+
utils::options::serializeStringList(AllowedCallees));
33+
}
34+
35+
bool SuspiciousStringviewDataUsageCheck::isLanguageVersionSupported(
36+
const LangOptions &LangOpts) const {
37+
return LangOpts.CPlusPlus;
38+
}
39+
40+
std::optional<TraversalKind>
41+
SuspiciousStringviewDataUsageCheck::getCheckTraversalKind() const {
42+
return TK_AsIs;
43+
}
44+
45+
void SuspiciousStringviewDataUsageCheck::registerMatchers(MatchFinder *Finder) {
46+
47+
auto AncestorCall = anyOf(
48+
cxxConstructExpr(), callExpr(unless(cxxOperatorCallExpr())), lambdaExpr(),
49+
initListExpr(
50+
hasType(qualType(hasCanonicalType(hasDeclaration(recordDecl()))))));
51+
52+
auto DataMethod =
53+
cxxMethodDecl(hasName("data"),
54+
ofClass(matchers::matchesAnyListedName(StringViewTypes)));
55+
56+
auto SizeCall = cxxMemberCallExpr(
57+
callee(cxxMethodDecl(hasAnyName("size", "length"))),
58+
on(ignoringParenImpCasts(
59+
matchers::isStatementIdenticalToBoundNode("self"))));
60+
61+
auto DescendantSizeCall = expr(hasDescendant(
62+
expr(SizeCall, hasAncestor(expr(AncestorCall).bind("ancestor-size")),
63+
hasAncestor(expr(equalsBoundNode("parent"),
64+
equalsBoundNode("ancestor-size"))))));
65+
66+
Finder->addMatcher(
67+
cxxMemberCallExpr(
68+
on(ignoringParenImpCasts(expr().bind("self"))), callee(DataMethod),
69+
expr().bind("data-call"),
70+
hasParent(expr(anyOf(
71+
invocation(
72+
expr().bind("parent"), unless(cxxOperatorCallExpr()),
73+
hasAnyArgument(
74+
ignoringParenImpCasts(equalsBoundNode("data-call"))),
75+
unless(hasAnyArgument(ignoringParenImpCasts(SizeCall))),
76+
unless(hasAnyArgument(DescendantSizeCall)),
77+
hasDeclaration(namedDecl(
78+
unless(matchers::matchesAnyListedName(AllowedCallees))))),
79+
initListExpr(expr().bind("parent"),
80+
hasType(qualType(hasCanonicalType(hasDeclaration(
81+
recordDecl(unless(matchers::matchesAnyListedName(
82+
AllowedCallees))))))),
83+
unless(DescendantSizeCall)))))),
84+
this);
85+
}
86+
87+
void SuspiciousStringviewDataUsageCheck::check(
88+
const MatchFinder::MatchResult &Result) {
89+
const auto *DataCallExpr =
90+
Result.Nodes.getNodeAs<CXXMemberCallExpr>("data-call");
91+
diag(DataCallExpr->getExprLoc(),
92+
"result of a `data()` call may not be null terminated, provide size "
93+
"information to the callee to prevent potential issues")
94+
<< DataCallExpr->getCallee()->getSourceRange();
95+
}
96+
97+
} // namespace clang::tidy::bugprone
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
//===--- SuspiciousStringviewDataUsageCheck.h - clang-tidy -------//C++ -*-===//
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+
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_SUSPICIOUSSTRINGVIEWDATAUSAGECHECK_H
10+
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_SUSPICIOUSSTRINGVIEWDATAUSAGECHECK_H
11+
12+
#include "../ClangTidyCheck.h"
13+
14+
namespace clang::tidy::bugprone {
15+
16+
/// Identifies suspicious usages of std::string_view::data() that could lead to
17+
/// reading out-of-bounds data due to inadequate or incorrect string null
18+
/// termination.
19+
///
20+
/// For the user-facing documentation see:
21+
/// http://clang.llvm.org/extra/clang-tidy/checks/bugprone/suspicious-stringview-data-usage.html
22+
class SuspiciousStringviewDataUsageCheck : public ClangTidyCheck {
23+
public:
24+
SuspiciousStringviewDataUsageCheck(StringRef Name, ClangTidyContext *Context);
25+
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
26+
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
27+
void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
28+
bool isLanguageVersionSupported(const LangOptions &LangOpts) const override;
29+
std::optional<TraversalKind> getCheckTraversalKind() const override;
30+
31+
private:
32+
std::vector<llvm::StringRef> StringViewTypes;
33+
std::vector<llvm::StringRef> AllowedCallees;
34+
};
35+
36+
} // namespace clang::tidy::bugprone
37+
38+
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_SUSPICIOUSSTRINGVIEWDATAUSAGECHECK_H

clang-tools-extra/docs/ReleaseNotes.rst

+7
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,13 @@ New checks
110110
Detects error-prone Curiously Recurring Template Pattern usage, when the CRTP
111111
can be constructed outside itself and the derived class.
112112

113+
- New :doc:`bugprone-suspicious-stringview-data-usage
114+
<clang-tidy/checks/bugprone/suspicious-stringview-data-usage>` check.
115+
116+
Identifies suspicious usages of ``std::string_view::data()`` that could lead
117+
to reading out-of-bounds data due to inadequate or incorrect string null
118+
termination.
119+
113120
- New :doc:`modernize-use-designated-initializers
114121
<clang-tidy/checks/modernize/use-designated-initializers>` check.
115122

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
.. title:: clang-tidy - bugprone-suspicious-stringview-data-usage
2+
3+
bugprone-suspicious-stringview-data-usage
4+
=========================================
5+
6+
Identifies suspicious usages of ``std::string_view::data()`` that could lead to
7+
reading out-of-bounds data due to inadequate or incorrect string null
8+
termination.
9+
10+
It warns when the result of ``data()`` is passed to a constructor or function
11+
without also passing the corresponding result of ``size()`` or ``length()``
12+
member function. Such usage can lead to unintended behavior, particularly when
13+
assuming the data pointed to by ``data()`` is null-terminated.
14+
15+
The absence of a ``c_str()`` method in ``std::string_view`` often leads
16+
developers to use ``data()`` as a substitute, especially when interfacing with
17+
C APIs that expect null-terminated strings. However, since ``data()`` does not
18+
guarantee null termination, this can result in unintended behavior if the API
19+
relies on proper null termination for correct string interpretation.
20+
21+
In today's programming landscape, this scenario can occur when implicitly
22+
converting an ``std::string_view`` to an ``std::string``. Since the constructor
23+
in ``std::string`` designed for string-view-like objects is ``explicit``,
24+
attempting to pass an ``std::string_view`` to a function expecting an
25+
``std::string`` will result in a compilation error. As a workaround, developers
26+
may be tempted to utilize the ``.data()`` method to achieve compilation,
27+
introducing potential risks.
28+
29+
For instance:
30+
31+
.. code-block:: c++
32+
33+
void printString(const std::string& str) {
34+
std::cout << "String: " << str << std::endl;
35+
}
36+
37+
void something(std::string_view sv) {
38+
printString(sv.data());
39+
}
40+
41+
In this example, directly passing ``sv`` to the ``printString`` function would
42+
lead to a compilation error due to the explicit nature of the ``std::string``
43+
constructor. Consequently, developers might opt for ``sv.data()`` to resolve the
44+
compilation error, albeit introducing potential hazards as discussed.
45+
46+
.. option:: StringViewTypes
47+
48+
Option allows users to specify custom string view-like types for analysis. It
49+
accepts a semicolon-separated list of type names or regular expressions
50+
matching these types. Default value is:
51+
`::std::basic_string_view;::llvm::StringRef`.
52+
53+
.. option:: AllowedCallees
54+
55+
Specifies methods, functions, or classes where the result of ``.data()`` is
56+
passed to. Allows to exclude such calls from the analysis. Accepts a
57+
semicolon-separated list of names or regular expressions matching these
58+
entities. Default value is: empty string.

clang-tools-extra/docs/clang-tidy/checks/list.rst

+1
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ Clang-Tidy Checks
139139
:doc:`bugprone-suspicious-realloc-usage <bugprone/suspicious-realloc-usage>`,
140140
:doc:`bugprone-suspicious-semicolon <bugprone/suspicious-semicolon>`, "Yes"
141141
:doc:`bugprone-suspicious-string-compare <bugprone/suspicious-string-compare>`, "Yes"
142+
:doc:`bugprone-suspicious-stringview-data-usage <bugprone/suspicious-stringview-data-usage>`,
142143
:doc:`bugprone-swapped-arguments <bugprone/swapped-arguments>`, "Yes"
143144
:doc:`bugprone-switch-missing-default-case <bugprone/switch-missing-default-case>`,
144145
:doc:`bugprone-terminating-continue <bugprone/terminating-continue>`, "Yes"

clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/string

+7
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ struct basic_string {
2424
basic_string();
2525
basic_string(const C *p, const A &a = A());
2626
basic_string(const C *p, size_type count);
27+
basic_string(const C *b, const C *e);
2728

2829
~basic_string();
2930

@@ -85,6 +86,12 @@ struct basic_string_view {
8586
const C *str;
8687
constexpr basic_string_view(const C* s) : str(s) {}
8788

89+
const C *data() const;
90+
91+
bool empty() const;
92+
size_type size() const;
93+
size_type length() const;
94+
8895
size_type find(_Type v, size_type pos = 0) const;
8996
size_type find(C ch, size_type pos = 0) const;
9097
size_type find(const C* s, size_type pos, size_type count) const;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// RUN: %check_clang_tidy -std=c++17-or-later %s bugprone-suspicious-stringview-data-usage %t -- -- -isystem %clang_tidy_headers
2+
#include <string>
3+
4+
struct View {
5+
const char* str;
6+
};
7+
8+
struct Pair {
9+
const char* begin;
10+
const char* end;
11+
};
12+
13+
struct ViewWithSize {
14+
const char* str;
15+
std::string_view::size_type size;
16+
};
17+
18+
void something(const char*);
19+
void something(const char*, unsigned);
20+
void something(const char*, unsigned, const char*);
21+
void something_str(std::string, unsigned);
22+
23+
void invalid(std::string_view sv, std::string_view sv2) {
24+
std::string s(sv.data());
25+
// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: result of a `data()` call may not be null terminated, provide size information to the callee to prevent potential issues
26+
std::string si{sv.data()};
27+
// CHECK-MESSAGES: :[[@LINE-1]]:21: warning: result of a `data()` call may not be null terminated, provide size information to the callee to prevent potential issues
28+
std::string_view s2(sv.data());
29+
// CHECK-MESSAGES: :[[@LINE-1]]:26: warning: result of a `data()` call may not be null terminated, provide size information to the callee to prevent potential issues
30+
something(sv.data());
31+
// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: result of a `data()` call may not be null terminated, provide size information to the callee to prevent potential issues
32+
something(sv.data(), sv.size(), sv2.data());
33+
// CHECK-MESSAGES: :[[@LINE-1]]:39: warning: result of a `data()` call may not be null terminated, provide size information to the callee to prevent potential issues
34+
something_str(sv.data(), sv.size());
35+
// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: result of a `data()` call may not be null terminated, provide size information to the callee to prevent potential issues
36+
View view{sv.data()};
37+
// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: result of a `data()` call may not be null terminated, provide size information to the callee to prevent potential issues
38+
}
39+
40+
void valid(std::string_view sv) {
41+
std::string s1(sv.data(), sv.data() + sv.size());
42+
std::string s2(sv.data(), sv.data() + sv.length());
43+
std::string s3(sv.data(), sv.size() + sv.data());
44+
std::string s4(sv.data(), sv.length() + sv.data());
45+
std::string s5(sv.data(), sv.size());
46+
std::string s6(sv.data(), sv.length());
47+
something(sv.data(), sv.size());
48+
something(sv.data(), sv.length());
49+
ViewWithSize view1{sv.data(), sv.size()};
50+
ViewWithSize view2{sv.data(), sv.length()};
51+
Pair view3{sv.data(), sv.data() + sv.size()};
52+
Pair view4{sv.data(), sv.data() + sv.length()};
53+
Pair view5{sv.data(), sv.size() + sv.data()};
54+
Pair view6{sv.data(), sv.length() + sv.data()};
55+
const char* str{sv.data()};
56+
}

0 commit comments

Comments
 (0)