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