clang-tools 23.0.0git
ThrowByValueCatchByReferenceCheck.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
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12
13using namespace clang::ast_matchers;
14
15namespace clang::tidy::misc {
16
18 StringRef Name, ClangTidyContext *Context)
19 : ClangTidyCheck(Name, Context),
20 CheckAnonymousTemporaries(Options.get("CheckThrowTemporaries", true)),
21 WarnOnLargeObject(Options.get("WarnOnLargeObject", false)),
22 // Cannot access `ASTContext` from here so set it to an extremal value.
23 MaxSizeOptions(
24 Options.get("MaxSize", std::numeric_limits<uint64_t>::max())),
25 MaxSize(MaxSizeOptions) {}
26
28 Finder->addMatcher(cxxThrowExpr().bind("throw"), this);
29 Finder->addMatcher(cxxCatchStmt().bind("catch"), this);
30}
31
34 Options.store(Opts, "CheckThrowTemporaries", CheckAnonymousTemporaries);
35 Options.store(Opts, "WarnOnLargeObject", WarnOnLargeObject);
36 Options.store(Opts, "MaxSize", MaxSizeOptions);
37}
38
40 const MatchFinder::MatchResult &Result) {
41 diagnoseThrowLocations(Result.Nodes.getNodeAs<CXXThrowExpr>("throw"));
42 diagnoseCatchLocations(Result.Nodes.getNodeAs<CXXCatchStmt>("catch"),
43 *Result.Context);
44}
45
46bool ThrowByValueCatchByReferenceCheck::isFunctionParameter(
47 const DeclRefExpr *DeclRefExpr) {
48 return isa<ParmVarDecl>(DeclRefExpr->getDecl());
49}
50
51bool ThrowByValueCatchByReferenceCheck::isCatchVariable(
52 const DeclRefExpr *DeclRefExpr) {
53 auto *ValueDecl = DeclRefExpr->getDecl();
54 if (auto *Var = dyn_cast<VarDecl>(ValueDecl))
55 return Var->isExceptionVariable();
56 return false;
57}
58
59bool ThrowByValueCatchByReferenceCheck::isFunctionOrCatchVar(
60 const DeclRefExpr *DeclRefExpr) {
61 return isFunctionParameter(DeclRefExpr) || isCatchVariable(DeclRefExpr);
62}
63
64void ThrowByValueCatchByReferenceCheck::diagnoseThrowLocations(
65 const CXXThrowExpr *ThrowExpr) {
66 if (!ThrowExpr)
67 return;
68 auto *SubExpr = ThrowExpr->getSubExpr();
69 if (!SubExpr)
70 return;
71 auto QualType = SubExpr->getType();
72 if (QualType->isPointerType()) {
73 // The code is throwing a pointer.
74 // In case it is string literal, it is safe and we return.
75 auto *Inner = SubExpr->IgnoreParenImpCasts();
76 if (isa<StringLiteral>(Inner))
77 return;
78 // If it's a variable from a catch statement, we return as well.
79 auto *DeclRef = dyn_cast<DeclRefExpr>(Inner);
80 if (DeclRef && isCatchVariable(DeclRef))
81 return;
82 diag(SubExpr->getBeginLoc(), "throw expression throws a pointer; it should "
83 "throw a non-pointer value instead");
84 }
85 // If the throw statement does not throw by pointer then it throws by value
86 // which is ok.
87 // There are addition checks that emit diagnosis messages if the thrown value
88 // is not an RValue. This behavior can be influenced by an option.
89
90 // If we encounter a CXXThrowExpr, we move through all casts until you either
91 // encounter a DeclRefExpr or a CXXConstructExpr.
92 // If it's a DeclRefExpr, we emit a message if the referenced variable is not
93 // a catch variable or function parameter.
94 // When encountering a CopyOrMoveConstructor: emit message if after casts,
95 // the expression is a LValue
96 if (CheckAnonymousTemporaries) {
97 bool Emit = false;
98 auto *CurrentSubExpr = SubExpr->IgnoreImpCasts();
99 const auto *VariableReference = dyn_cast<DeclRefExpr>(CurrentSubExpr);
100 const auto *ConstructorCall = dyn_cast<CXXConstructExpr>(CurrentSubExpr);
101 // If we have a DeclRefExpr, we flag for emitting a diagnosis message in
102 // case the referenced variable is neither a function parameter nor a
103 // variable declared in the catch statement.
104 if (VariableReference) {
105 Emit = !isFunctionOrCatchVar(VariableReference);
106 } else if (ConstructorCall &&
107 ConstructorCall->getConstructor()->isCopyOrMoveConstructor()) {
108 // If we have a copy / move construction, we emit a diagnosis message if
109 // the object that we copy construct from is neither a function parameter
110 // nor a variable declared in a catch statement
111 auto ArgIter =
112 ConstructorCall
113 ->arg_begin(); // there's only one for copy constructors
114 auto *CurrentSubExpr = (*ArgIter)->IgnoreImpCasts();
115 if (CurrentSubExpr->isLValue()) {
116 if (auto *Tmp = dyn_cast<DeclRefExpr>(CurrentSubExpr))
117 Emit = !isFunctionOrCatchVar(Tmp);
118 else if (isa<CallExpr>(CurrentSubExpr))
119 Emit = true;
120 }
121 }
122 if (Emit)
123 diag(SubExpr->getBeginLoc(),
124 "throw expression should throw anonymous temporary values instead");
125 }
126}
127
128void ThrowByValueCatchByReferenceCheck::diagnoseCatchLocations(
129 const CXXCatchStmt *CatchStmt, ASTContext &Context) {
130 if (!CatchStmt)
131 return;
132 auto CaughtType = CatchStmt->getCaughtType();
133 if (CaughtType.isNull())
134 return;
135 auto *VarDecl = CatchStmt->getExceptionDecl();
136 if (const auto *PT = CaughtType.getCanonicalType()->getAs<PointerType>()) {
137 const char *DiagMsgCatchReference =
138 "catch handler catches a pointer value; "
139 "should throw a non-pointer value and "
140 "catch by reference instead";
141 // We do not diagnose when catching pointer to strings since we also allow
142 // throwing string literals.
143 if (!PT->getPointeeType()->isAnyCharacterType())
144 diag(VarDecl->getBeginLoc(), DiagMsgCatchReference);
145 } else if (!CaughtType->isReferenceType()) {
146 const char *DiagMsgCatchReference = "catch handler catches by value; "
147 "should catch by reference instead";
148 // If it's not a pointer and not a reference then it must be caught "by
149 // value". In this case we should emit a diagnosis message unless the type
150 // is trivial.
151 if (!CaughtType.isTrivialType(Context)) {
152 diag(VarDecl->getBeginLoc(), DiagMsgCatchReference);
153 } else if (WarnOnLargeObject) {
154 // If the type is trivial, then catching it by reference is not dangerous.
155 // However, catching large objects by value decreases the performance.
156
157 // We can now access `ASTContext` so if `MaxSize` is an extremal value
158 // then set it to the size of `size_t`.
159 if (MaxSize == std::numeric_limits<uint64_t>::max())
160 MaxSize = Context.getTypeSize(Context.getSizeType());
161 if (Context.getTypeSize(CaughtType) > MaxSize)
162 diag(VarDecl->getBeginLoc(), DiagMsgCatchReference);
163 }
164 }
165}
166
167} // namespace clang::tidy::misc
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
ThrowByValueCatchByReferenceCheck(StringRef Name, ClangTidyContext *Context)
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
llvm::StringMap< ClangTidyValue > OptionMap