blob: 7b1f7eafe1ebf54b8a6143cea1be5f5c423d7cf4 [file] [log] [blame]
Aaron Ballmanfd78cc82015-10-09 20:42:44 +00001//===--- ThrowByValueCatchByReferenceCheck.cpp - clang-tidy----------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Aaron Ballmanfd78cc82015-10-09 20:42:44 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "ThrowByValueCatchByReferenceCheck.h"
10#include "clang/AST/ASTContext.h"
Aaron Ballmanfd78cc82015-10-09 20:42:44 +000011#include "clang/AST/OperationKinds.h"
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000012#include "clang/ASTMatchers/ASTMatchFinder.h"
Aaron Ballmanfd78cc82015-10-09 20:42:44 +000013
14using namespace clang::ast_matchers;
15
16namespace clang {
17namespace tidy {
Kirill Bobyrev11cea452016-08-01 12:06:18 +000018namespace misc {
Aaron Ballmanfd78cc82015-10-09 20:42:44 +000019
20ThrowByValueCatchByReferenceCheck::ThrowByValueCatchByReferenceCheck(
21 StringRef Name, ClangTidyContext *Context)
22 : ClangTidyCheck(Name, Context),
Adam Balogh5f3deb92019-05-21 07:25:06 +000023 CheckAnonymousTemporaries(Options.get("CheckThrowTemporaries", true)),
24 WarnOnLargeObject(Options.get("WarnOnLargeObject", false)),
25 // Cannot access `ASTContext` from here so set it to an extremal value.
26 MaxSize(Options.get("MaxSize", std::numeric_limits<uint64_t>::max())) {}
Aaron Ballmanfd78cc82015-10-09 20:42:44 +000027
28void ThrowByValueCatchByReferenceCheck::registerMatchers(MatchFinder *Finder) {
29 // This is a C++ only check thus we register the matchers only for C++
30 if (!getLangOpts().CPlusPlus)
31 return;
32
33 Finder->addMatcher(cxxThrowExpr().bind("throw"), this);
34 Finder->addMatcher(cxxCatchStmt().bind("catch"), this);
35}
36
37void ThrowByValueCatchByReferenceCheck::storeOptions(
38 ClangTidyOptions::OptionMap &Opts) {
39 Options.store(Opts, "CheckThrowTemporaries", true);
40}
41
42void ThrowByValueCatchByReferenceCheck::check(
43 const MatchFinder::MatchResult &Result) {
44 diagnoseThrowLocations(Result.Nodes.getNodeAs<CXXThrowExpr>("throw"));
45 diagnoseCatchLocations(Result.Nodes.getNodeAs<CXXCatchStmt>("catch"),
46 *Result.Context);
47}
48
49bool ThrowByValueCatchByReferenceCheck::isFunctionParameter(
50 const DeclRefExpr *declRefExpr) {
51 return isa<ParmVarDecl>(declRefExpr->getDecl());
52}
53
54bool ThrowByValueCatchByReferenceCheck::isCatchVariable(
55 const DeclRefExpr *declRefExpr) {
56 auto *valueDecl = declRefExpr->getDecl();
57 if (auto *varDecl = dyn_cast<VarDecl>(valueDecl))
58 return varDecl->isExceptionVariable();
59 return false;
60}
61
62bool ThrowByValueCatchByReferenceCheck::isFunctionOrCatchVar(
63 const DeclRefExpr *declRefExpr) {
64 return isFunctionParameter(declRefExpr) || isCatchVariable(declRefExpr);
65}
66
67void ThrowByValueCatchByReferenceCheck::diagnoseThrowLocations(
68 const CXXThrowExpr *throwExpr) {
69 if (!throwExpr)
70 return;
71 auto *subExpr = throwExpr->getSubExpr();
72 if (!subExpr)
73 return;
74 auto qualType = subExpr->getType();
75 if (qualType->isPointerType()) {
76 // The code is throwing a pointer.
77 // In case it is strng literal, it is safe and we return.
78 auto *inner = subExpr->IgnoreParenImpCasts();
79 if (isa<StringLiteral>(inner))
80 return;
81 // If it's a variable from a catch statement, we return as well.
82 auto *declRef = dyn_cast<DeclRefExpr>(inner);
83 if (declRef && isCatchVariable(declRef)) {
84 return;
85 }
Stephen Kelly43465bf2018-08-09 22:42:26 +000086 diag(subExpr->getBeginLoc(), "throw expression throws a pointer; it should "
Aaron Ballmanfd78cc82015-10-09 20:42:44 +000087 "throw a non-pointer value instead");
88 }
89 // If the throw statement does not throw by pointer then it throws by value
90 // which is ok.
91 // There are addition checks that emit diagnosis messages if the thrown value
92 // is not an RValue. See:
93 // https://www.securecoding.cert.org/confluence/display/cplusplus/ERR09-CPP.+Throw+anonymous+temporaries
94 // This behavior can be influenced by an option.
95
96 // If we encounter a CXXThrowExpr, we move through all casts until you either
97 // encounter a DeclRefExpr or a CXXConstructExpr.
98 // If it's a DeclRefExpr, we emit a message if the referenced variable is not
99 // a catch variable or function parameter.
100 // When encountering a CopyOrMoveConstructor: emit message if after casts,
101 // the expression is a LValue
102 if (CheckAnonymousTemporaries) {
103 bool emit = false;
104 auto *currentSubExpr = subExpr->IgnoreImpCasts();
Piotr Padlewski08124b12016-12-14 15:29:23 +0000105 const auto *variableReference = dyn_cast<DeclRefExpr>(currentSubExpr);
106 const auto *constructorCall = dyn_cast<CXXConstructExpr>(currentSubExpr);
Aaron Ballmanfd78cc82015-10-09 20:42:44 +0000107 // If we have a DeclRefExpr, we flag for emitting a diagnosis message in
108 // case the referenced variable is neither a function parameter nor a
109 // variable declared in the catch statement.
110 if (variableReference)
111 emit = !isFunctionOrCatchVar(variableReference);
112 else if (constructorCall &&
113 constructorCall->getConstructor()->isCopyOrMoveConstructor()) {
114 // If we have a copy / move construction, we emit a diagnosis message if
115 // the object that we copy construct from is neither a function parameter
116 // nor a variable declared in a catch statement
117 auto argIter =
118 constructorCall
119 ->arg_begin(); // there's only one for copy constructors
120 auto *currentSubExpr = (*argIter)->IgnoreImpCasts();
121 if (currentSubExpr->isLValue()) {
122 if (auto *tmp = dyn_cast<DeclRefExpr>(currentSubExpr))
123 emit = !isFunctionOrCatchVar(tmp);
124 else if (isa<CallExpr>(currentSubExpr))
125 emit = true;
126 }
127 }
128 if (emit)
Stephen Kelly43465bf2018-08-09 22:42:26 +0000129 diag(subExpr->getBeginLoc(),
Aaron Ballmanfd78cc82015-10-09 20:42:44 +0000130 "throw expression should throw anonymous temporary values instead");
131 }
132}
133
134void ThrowByValueCatchByReferenceCheck::diagnoseCatchLocations(
135 const CXXCatchStmt *catchStmt, ASTContext &context) {
Aaron Ballmanfd78cc82015-10-09 20:42:44 +0000136 if (!catchStmt)
137 return;
138 auto caughtType = catchStmt->getCaughtType();
139 if (caughtType.isNull())
140 return;
141 auto *varDecl = catchStmt->getExceptionDecl();
142 if (const auto *PT = caughtType.getCanonicalType()->getAs<PointerType>()) {
Alexander Kornienko5816a8b2017-03-23 15:17:44 +0000143 const char *diagMsgCatchReference = "catch handler catches a pointer value; "
144 "should throw a non-pointer value and "
145 "catch by reference instead";
Aaron Ballmanfd78cc82015-10-09 20:42:44 +0000146 // We do not diagnose when catching pointer to strings since we also allow
147 // throwing string literals.
148 if (!PT->getPointeeType()->isAnyCharacterType())
Stephen Kelly43465bf2018-08-09 22:42:26 +0000149 diag(varDecl->getBeginLoc(), diagMsgCatchReference);
Aaron Ballmanfd78cc82015-10-09 20:42:44 +0000150 } else if (!caughtType->isReferenceType()) {
Alexander Kornienko5816a8b2017-03-23 15:17:44 +0000151 const char *diagMsgCatchReference = "catch handler catches by value; "
152 "should catch by reference instead";
153 // If it's not a pointer and not a reference then it must be caught "by
Aaron Ballmanfd78cc82015-10-09 20:42:44 +0000154 // value". In this case we should emit a diagnosis message unless the type
155 // is trivial.
Adam Balogh5f3deb92019-05-21 07:25:06 +0000156 if (!caughtType.isTrivialType(context)) {
Stephen Kelly43465bf2018-08-09 22:42:26 +0000157 diag(varDecl->getBeginLoc(), diagMsgCatchReference);
Adam Balogh5f3deb92019-05-21 07:25:06 +0000158 } else if (WarnOnLargeObject) {
159 // If the type is trivial, then catching it by reference is not dangerous.
160 // However, catching large objects by value decreases the performance.
161
162 // We can now access `ASTContext` so if `MaxSize` is an extremal value
163 // then set it to the size of `size_t`.
164 if (MaxSize == std::numeric_limits<uint64_t>::max())
165 MaxSize = context.getTypeSize(context.getSizeType());
166 if (context.getTypeSize(caughtType) > MaxSize)
167 diag(varDecl->getBeginLoc(), diagMsgCatchReference);
168 }
Aaron Ballmanfd78cc82015-10-09 20:42:44 +0000169 }
170}
171
Etienne Bergeron456177b2016-05-02 18:00:29 +0000172} // namespace misc
Aaron Ballmanfd78cc82015-10-09 20:42:44 +0000173} // namespace tidy
174} // namespace clang