clang-tools 6.0.0

DanglingHandleCheck.cpp
Go to the documentation of this file.
1 //===--- DanglingHandleCheck.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 "DanglingHandleCheck.h"
11 #include "../utils/Matchers.h"
12 #include "../utils/OptionsUtils.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/ASTMatchers/ASTMatchFinder.h"
15
16 using namespace clang::ast_matchers;
17 using namespace clang::tidy::matchers;
18
19 namespace clang {
20 namespace tidy {
21 namespace bugprone {
22
23 namespace {
24
25 ast_matchers::internal::BindableMatcher<Stmt>
26 handleFrom(const ast_matchers::internal::Matcher<RecordDecl> &IsAHandle,
27 const ast_matchers::internal::Matcher<Expr> &Arg) {
28 return cxxConstructExpr(hasDeclaration(cxxMethodDecl(ofClass(IsAHandle))),
29 hasArgument(0, Arg));
30 }
31
32 ast_matchers::internal::Matcher<Stmt> handleFromTemporaryValue(
33 const ast_matchers::internal::Matcher<RecordDecl> &IsAHandle) {
34 // If a ternary operator returns a temporary value, then both branches hold a
35 // temporary value. If one of them is not a temporary then it must be copied
36 // into one to satisfy the type of the operator.
37 const auto TemporaryTernary =
38 conditionalOperator(hasTrueExpression(cxxBindTemporaryExpr()),
39 hasFalseExpression(cxxBindTemporaryExpr()));
40
41 return handleFrom(IsAHandle, anyOf(cxxBindTemporaryExpr(), TemporaryTernary));
42 }
43
44 ast_matchers::internal::Matcher<RecordDecl> isASequence() {
45 return hasAnyName("::std::deque", "::std::forward_list", "::std::list",
46 "::std::vector");
47 }
48
49 ast_matchers::internal::Matcher<RecordDecl> isASet() {
50 return hasAnyName("::std::set", "::std::multiset", "::std::unordered_set",
51 "::std::unordered_multiset");
52 }
53
54 ast_matchers::internal::Matcher<RecordDecl> isAMap() {
55 return hasAnyName("::std::map", "::std::multimap", "::std::unordered_map",
56 "::std::unordered_multimap");
57 }
58
59 ast_matchers::internal::BindableMatcher<Stmt> makeContainerMatcher(
60 const ast_matchers::internal::Matcher<RecordDecl> &IsAHandle) {
61 // This matcher could be expanded to detect:
62 // - Constructors: eg. vector<string_view>(3, string("A"));
63 // - emplace*(): This requires a different logic to determine that
64 // the conversion will happen inside the container.
65 // - map's insert: This requires detecting that the pair conversion triggers
66 // the bug. A little more complicated than what we have now.
67 return callExpr(
68 hasAnyArgument(
69 ignoringParenImpCasts(handleFromTemporaryValue(IsAHandle))),
70 anyOf(
71 // For sequences: assign, push_back, resize.
72 cxxMemberCallExpr(
73 callee(functionDecl(hasAnyName("assign", "push_back", "resize"))),
74 on(expr(hasType(hasUnqualifiedDesugaredType(
75 recordType(hasDeclaration(recordDecl(isASequence())))))))),
76 // For sequences and sets: insert.
77 cxxMemberCallExpr(callee(functionDecl(hasName("insert"))),
78 on(expr(hasType(hasUnqualifiedDesugaredType(
79 recordType(hasDeclaration(recordDecl(
80 anyOf(isASequence(), isASet()))))))))),
81 // For maps: operator[].
82 cxxOperatorCallExpr(callee(cxxMethodDecl(ofClass(isAMap()))),
83 hasOverloadedOperatorName("[]"))));
84 }
85
86 } // anonymous namespace
87
88 DanglingHandleCheck::DanglingHandleCheck(StringRef Name,
89 ClangTidyContext *Context)
90 : ClangTidyCheck(Name, Context),
91 HandleClasses(utils::options::parseStringList(Options.get(
92 "HandleClasses",
93 "std::basic_string_view;std::experimental::basic_string_view"))),
94 IsAHandle(cxxRecordDecl(hasAnyName(std::vector<StringRef>(
95 HandleClasses.begin(), HandleClasses.end())))
96 .bind("handle")) {}
97
98 void DanglingHandleCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
99 Options.store(Opts, "HandleClasses",
100 utils::options::serializeStringList(HandleClasses));
101 }
102
103 void DanglingHandleCheck::registerMatchersForVariables(MatchFinder *Finder) {
104 const auto ConvertedHandle = handleFromTemporaryValue(IsAHandle);
105
106 // Find 'Handle foo(ReturnsAValue());'
107 Finder->addMatcher(
108 varDecl(hasType(hasUnqualifiedDesugaredType(
109 recordType(hasDeclaration(cxxRecordDecl(IsAHandle))))),
110 hasInitializer(
111 exprWithCleanups(has(ignoringParenImpCasts(ConvertedHandle)))
112 .bind("bad_stmt"))),
113 this);
114
115 // Find 'Handle foo = ReturnsAValue();'
116 Finder->addMatcher(
117 varDecl(
118 hasType(hasUnqualifiedDesugaredType(
119 recordType(hasDeclaration(cxxRecordDecl(IsAHandle))))),
120 unless(parmVarDecl()),
121 hasInitializer(exprWithCleanups(has(ignoringParenImpCasts(handleFrom(
122 IsAHandle, ConvertedHandle))))
123 .bind("bad_stmt"))),
124 this);
125 // Find 'foo = ReturnsAValue(); // foo is Handle'
126 Finder->addMatcher(
127 cxxOperatorCallExpr(callee(cxxMethodDecl(ofClass(IsAHandle))),
128 hasOverloadedOperatorName("="),
129 hasArgument(1, ConvertedHandle))
130 .bind("bad_stmt"),
131 this);
132
133 // Container insertions that will dangle.
134 Finder->addMatcher(makeContainerMatcher(IsAHandle).bind("bad_stmt"), this);
135 }
136
137 void DanglingHandleCheck::registerMatchersForReturn(MatchFinder *Finder) {
138 // Return a local.
139 Finder->addMatcher(
140 returnStmt(
141 // The AST contains two constructor calls:
142 // 1. Value to Handle conversion.
143 // 2. Handle copy construction.
144 // We have to match both.
145 has(ignoringImplicit(handleFrom(
146 IsAHandle,
147 handleFrom(IsAHandle,
148 declRefExpr(to(varDecl(
149 // Is function scope ...
150 hasAutomaticStorageDuration(),
151 // ... and it is a local array or Value.
152 anyOf(hasType(arrayType()),
153 hasType(hasUnqualifiedDesugaredType(
154 recordType(hasDeclaration(recordDecl(
155 unless(IsAHandle)))))))))))))),
156 // Temporary fix for false positives inside lambdas.
157 unless(hasAncestor(lambdaExpr())))
158 .bind("bad_stmt"),
159 this);
160
161 // Return a temporary.
162 Finder->addMatcher(
163 returnStmt(
164 has(ignoringParenImpCasts(exprWithCleanups(has(ignoringParenImpCasts(
165 handleFrom(IsAHandle, handleFromTemporaryValue(IsAHandle))))))))
166 .bind("bad_stmt"),
167 this);
168 }
169
170 void DanglingHandleCheck::registerMatchers(MatchFinder *Finder) {
171 registerMatchersForVariables(Finder);
172 registerMatchersForReturn(Finder);
173 }
174
175 void DanglingHandleCheck::check(const MatchFinder::MatchResult &Result) {
176 auto *Handle = Result.Nodes.getNodeAs<CXXRecordDecl>("handle");
177 diag(Result.Nodes.getNodeAs<Stmt>("bad_stmt")->getLocStart(),
178 "%0 outlives its value")
179 << Handle->getQualifiedNameAsString();
180 }
181
182 } // namespace bugprone
183 } // namespace tidy
184 } // namespace clang
clang::ast_matchers
Definition: ClangTidyDiagnosticConsumer.h:27
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:449
clang::tidy::bugprone::DanglingHandleCheck::check
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
Definition: DanglingHandleCheck.cpp:175
clang::tidy::utils::options::serializeStringList
std::string serializeStringList(ArrayRef< std::string > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
Definition: OptionsUtils.cpp:31
Name
StringHandle Name
Definition: PreprocessorTracker.cpp:525
clang::tidy::bugprone::DanglingHandleCheck::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: DanglingHandleCheck.cpp:98
clang::tidy::matchers
Definition: Matchers.h:18
clang::tidy::ClangTidyCheck
Base class for all clang-tidy checks.
Definition: ClangTidy.h:127
clang::tidy::utils::options::parseStringList
std::vector< std::string > parseStringList(StringRef Option)
Parse a semicolon separated list of strings.
Definition: OptionsUtils.cpp:19
clang::tidy::ClangTidyCheck::Options
OptionsView Options
Definition: ClangTidy.h:183
clang::tidy::ClangTidyOptions::OptionMap
std::map< std::string, std::string > OptionMap
Definition: ClangTidyOptions.h:99
DanglingHandleCheck.h
clang::tidy::bugprone::DanglingHandleCheck::registerMatchers
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
Definition: DanglingHandleCheck.cpp:170
clang
Definition: AndroidTidyModule.cpp:28
clang::tidy::ClangTidyContext
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
Definition: ClangTidyDiagnosticConsumer.h:104
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:416