1 //===--- UnhandledSelfAssignmentCheck.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 "UnhandledSelfAssignmentCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12
13 using namespace clang::ast_matchers;
14
15 namespace clang {
16 namespace tidy {
17 namespace bugprone {
18
UnhandledSelfAssignmentCheck(StringRef Name,ClangTidyContext * Context)19 UnhandledSelfAssignmentCheck::UnhandledSelfAssignmentCheck(
20 StringRef Name, ClangTidyContext *Context)
21 : ClangTidyCheck(Name, Context),
22 WarnOnlyIfThisHasSuspiciousField(
23 Options.get("WarnOnlyIfThisHasSuspiciousField", true)) {}
24
storeOptions(ClangTidyOptions::OptionMap & Opts)25 void UnhandledSelfAssignmentCheck::storeOptions(
26 ClangTidyOptions::OptionMap &Opts) {
27 Options.store(Opts, "WarnOnlyIfThisHasSuspiciousField",
28 WarnOnlyIfThisHasSuspiciousField);
29 }
30
registerMatchers(MatchFinder * Finder)31 void UnhandledSelfAssignmentCheck::registerMatchers(MatchFinder *Finder) {
32 // We don't care about deleted, default or implicit operator implementations.
33 const auto IsUserDefined = cxxMethodDecl(
34 isDefinition(), unless(anyOf(isDeleted(), isImplicit(), isDefaulted())));
35
36 // We don't need to worry when a copy assignment operator gets the other
37 // object by value.
38 const auto HasReferenceParam =
39 cxxMethodDecl(hasParameter(0, parmVarDecl(hasType(referenceType()))));
40
41 // Self-check: Code compares something with 'this' pointer. We don't check
42 // whether it is actually the parameter what we compare.
43 const auto HasNoSelfCheck = cxxMethodDecl(unless(hasDescendant(
44 binaryOperation(hasAnyOperatorName("==", "!="),
45 hasEitherOperand(ignoringParenCasts(cxxThisExpr()))))));
46
47 // Both copy-and-swap and copy-and-move method creates a copy first and
48 // assign it to 'this' with swap or move.
49 // In the non-template case, we can search for the copy constructor call.
50 const auto HasNonTemplateSelfCopy = cxxMethodDecl(
51 ofClass(cxxRecordDecl(unless(hasAncestor(classTemplateDecl())))),
52 traverse(TK_AsIs,
53 hasDescendant(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
54 isCopyConstructor(), ofClass(equalsBoundNode("class"))))))));
55
56 // In the template case, we need to handle two separate cases: 1) a local
57 // variable is created with the copy, 2) copy is created only as a temporary
58 // object.
59 const auto HasTemplateSelfCopy = cxxMethodDecl(
60 ofClass(cxxRecordDecl(hasAncestor(classTemplateDecl()))),
61 anyOf(hasDescendant(
62 varDecl(hasType(cxxRecordDecl(equalsBoundNode("class"))),
63 hasDescendant(parenListExpr()))),
64 hasDescendant(cxxUnresolvedConstructExpr(hasDescendant(declRefExpr(
65 hasType(cxxRecordDecl(equalsBoundNode("class")))))))));
66
67 // If inside the copy assignment operator another assignment operator is
68 // called on 'this' we assume that self-check might be handled inside
69 // this nested operator.
70 const auto HasNoNestedSelfAssign =
71 cxxMethodDecl(unless(hasDescendant(cxxMemberCallExpr(callee(cxxMethodDecl(
72 hasName("operator="), ofClass(equalsBoundNode("class"))))))));
73
74 DeclarationMatcher AdditionalMatcher = cxxMethodDecl();
75 if (WarnOnlyIfThisHasSuspiciousField) {
76 // Matcher for standard smart pointers.
77 const auto SmartPointerType = qualType(hasUnqualifiedDesugaredType(
78 recordType(hasDeclaration(classTemplateSpecializationDecl(
79 hasAnyName("::std::shared_ptr", "::std::unique_ptr",
80 "::std::weak_ptr", "::std::auto_ptr"),
81 templateArgumentCountIs(1))))));
82
83 // We will warn only if the class has a pointer or a C array field which
84 // probably causes a problem during self-assignment (e.g. first resetting
85 // the pointer member, then trying to access the object pointed by the
86 // pointer, or memcpy overlapping arrays).
87 AdditionalMatcher = cxxMethodDecl(ofClass(cxxRecordDecl(
88 has(fieldDecl(anyOf(hasType(pointerType()), hasType(SmartPointerType),
89 hasType(arrayType())))))));
90 }
91
92 Finder->addMatcher(cxxMethodDecl(ofClass(cxxRecordDecl().bind("class")),
93 isCopyAssignmentOperator(), IsUserDefined,
94 HasReferenceParam, HasNoSelfCheck,
95 unless(HasNonTemplateSelfCopy),
96 unless(HasTemplateSelfCopy),
97 HasNoNestedSelfAssign, AdditionalMatcher)
98 .bind("copyAssignmentOperator"),
99 this);
100 }
101
check(const MatchFinder::MatchResult & Result)102 void UnhandledSelfAssignmentCheck::check(
103 const MatchFinder::MatchResult &Result) {
104 const auto *MatchedDecl =
105 Result.Nodes.getNodeAs<CXXMethodDecl>("copyAssignmentOperator");
106 diag(MatchedDecl->getLocation(),
107 "operator=() does not handle self-assignment properly");
108 }
109
110 } // namespace bugprone
111 } // namespace tidy
112 } // namespace clang
113