1//=======- NoDeleteChecker.cpp -----------------------------------*- C++ -*-==//
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 "DiagOutputUtils.h"
10#include "PtrTypesSemantics.h"
11#include "clang/AST/CXXInheritance.h"
12#include "clang/AST/Decl.h"
13#include "clang/AST/DeclCXX.h"
14#include "clang/AST/DynamicRecursiveASTVisitor.h"
15#include "clang/AST/QualTypeNames.h"
16#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
17#include "clang/Basic/SourceLocation.h"
18#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
19#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
20#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
21#include "clang/StaticAnalyzer/Core/Checker.h"
22
23using namespace clang;
24using namespace ento;
25
26namespace {
27
28class NoDeleteChecker : public Checker<check::ASTDecl<TranslationUnitDecl>> {
29 BugType Bug;
30 mutable BugReporter *BR = nullptr;
31 mutable TrivialFunctionAnalysis TFA;
32
33public:
34 NoDeleteChecker()
35 : Bug(this,
36 "Incorrect [[clang::annotate_type(\"webkit.nodelete\")]] "
37 "annotation",
38 "WebKit coding guidelines") {}
39
40 void checkASTDecl(const TranslationUnitDecl *TUD, AnalysisManager &MGR,
41 BugReporter &BRArg) const {
42 BR = &BRArg;
43
44 // The calls to checkAST* from AnalysisConsumer don't
45 // visit template instantiations or lambda classes. We
46 // want to visit those, so we make our own visitor.
47 struct LocalVisitor final : public ConstDynamicRecursiveASTVisitor {
48 const NoDeleteChecker *Checker;
49 Decl *DeclWithIssue{nullptr};
50
51 explicit LocalVisitor(const NoDeleteChecker *Checker) : Checker(Checker) {
52 assert(Checker);
53 ShouldVisitTemplateInstantiations = true;
54 ShouldWalkTypesOfTypeLocs = true;
55 ShouldVisitImplicitCode = false;
56 ShouldVisitLambdaBody = true;
57 }
58
59 bool VisitFunctionDecl(const FunctionDecl *FD) override {
60 Checker->visitFunctionDecl(FD);
61 return true;
62 }
63 };
64
65 LocalVisitor visitor(this);
66 visitor.TraverseDecl(D: const_cast<TranslationUnitDecl *>(TUD));
67 }
68
69 void visitFunctionDecl(const FunctionDecl *FD) const {
70 if (!FD->doesThisDeclarationHaveABody() || FD->isDependentContext())
71 return;
72
73 if (!isNoDeleteFunction(F: FD))
74 return;
75
76 auto Body = FD->getBody();
77 if (!Body)
78 return;
79
80 NamedDecl *ParamDecl = nullptr;
81 for (auto *D : FD->parameters()) {
82 if (!TFA.hasTrivialDtor(VD: D)) {
83 ParamDecl = D;
84 break;
85 }
86 }
87
88 const FieldDecl *Field = nullptr;
89 const Stmt *OffendingInit = nullptr;
90 bool IsCtor = false;
91 bool IsDtor = false;
92 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
93 IsCtor = true;
94 // A delegating constructor doesn't construct any member variable itself;
95 // the target constructor does, and the call to it is in inits().
96 if (!Ctor->isDelegatingConstructor())
97 Field = TFA.fieldWithNonTrivialCtor(RD: Ctor->getParent());
98 if (!Field) {
99 for (auto *CtorInit : Ctor->inits()) {
100 auto *Init = CtorInit->getInit();
101 if (!TFA.isTrivial(S: Init)) {
102 OffendingInit = Init;
103 break;
104 }
105 }
106 }
107 } else if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: FD)) {
108 IsDtor = true;
109 Field = TFA.fieldWithNonTrivialDtor(RD: Dtor->getParent());
110 }
111
112 if (!ParamDecl && !Field && !OffendingInit && TFA.isTrivial(S: Body))
113 return;
114
115 SmallString<100> Buf;
116 llvm::raw_svector_ostream Os(Buf);
117
118 if (IsCtor)
119 Os << "A constructor ";
120 else if (IsDtor)
121 Os << "A destructor ";
122 else
123 Os << "A function ";
124 printQuotedName(Os, D: FD);
125 // FIXME: Update this to say clang::annotate("webkit.nodelete").
126 Os << " has [[clang::annotate_type(\"webkit.nodelete\")]] but it ";
127 if (IsCtor && Field)
128 Os << "constructs ";
129 else if (IsDtor && Field)
130 Os << "destructs ";
131 else
132 Os << "contains ";
133 SourceLocation SrcLocToReport;
134 SourceRange Range;
135 NonTrivialityReason Reason;
136 if (ParamDecl) {
137 Os << "a parameter ";
138 printQuotedName(Os, D: ParamDecl);
139 Os << " which could destruct an object.";
140 SrcLocToReport = FD->getBeginLoc();
141 Range = ParamDecl->getSourceRange();
142 } else if (Field && !OffendingInit) {
143 Os << "a member variable ";
144 printQuotedName(Os, D: Field);
145 Os << " that could destruct an object.";
146 SrcLocToReport = FD->getBeginLoc();
147 Range = Field->getSourceRange();
148 } else {
149 Reason = TrivialFunctionAnalysis::computeReason(
150 S: OffendingInit ? OffendingInit : Body);
151 Os << "code that could destruct an object.";
152 const Stmt *Offender = Reason.OffendingStmt;
153 SrcLocToReport = Offender ? Offender->getBeginLoc() : FD->getBeginLoc();
154 Range = Offender ? Offender->getSourceRange() : FD->getSourceRange();
155 }
156
157 PathDiagnosticLocation BSLoc(SrcLocToReport, BR->getSourceManager());
158 auto Report = std::make_unique<BasicBugReport>(args: Bug, args: Os.str(), args&: BSLoc);
159 Report->addRange(R: Range);
160 Report->setDeclWithIssue(FD);
161 addCallStackNotes(Report&: *Report, Reason);
162 BR->emitReport(R: std::move(Report));
163 }
164
165 static const FunctionDecl *getDirectCallee(const Stmt *S) {
166 if (const auto *CE = dyn_cast_or_null<CallExpr>(Val: S))
167 return CE->getDirectCallee();
168 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(Val: S))
169 return CE->getConstructor();
170 return nullptr;
171 }
172
173 // The offending statement is often just the nearest call to a function that
174 // is itself unsafe several levels down. Walk the whole chain of calls, one
175 // note per function, down to the code that destructs an object or the
176 // function without a visible definition, since that is where the fix belongs.
177 void addCallStackNotes(BasicBugReport &Report,
178 const NonTrivialityReason &Reason) const {
179 ArrayRef<NonTrivialityReason::Frame> CallStack = Reason.CallStack;
180 if (CallStack.empty())
181 return;
182
183 // Nothing to add when the offending statement is the call to a function
184 // that is opaque or rejected outright; a note would only point back at its
185 // declaration, which the primary diagnostic already names.
186 const auto &First = CallStack.front();
187 const FunctionDecl *Callee = getDirectCallee(S: Reason.OffendingStmt);
188 if (CallStack.size() == 1 && !First.OffendingStmt && Callee &&
189 Callee->getCanonicalDecl() == First.Callee->getCanonicalDecl())
190 return;
191
192 for (size_t I = 0; I < CallStack.size(); ++I) {
193 const FunctionDecl *Fn = CallStack[I].Callee;
194 const Stmt *Offender = CallStack[I].OffendingStmt;
195 // Implicit special members have nothing worth pointing at.
196 if (!Offender && !Fn->getLocation().isValid())
197 continue;
198
199 SmallString<100> Buf;
200 llvm::raw_svector_ostream Os(Buf);
201 // Each note sits on the line it describes, which already spells out the
202 // enclosing function and the callee, so name only the callee: naming
203 // both would repeat every function in the chain twice.
204 if (I + 1 < CallStack.size()) {
205 Os << "Calling ";
206 printQuotedName(Os, D: CallStack[I + 1].Callee);
207 } else if (Fn->doesThisDeclarationHaveABody()) {
208 Os << "Could destruct an object";
209 } else {
210 printQuotedName(Os, D: Fn);
211 Os << " has no visible definition here, so it is assumed to destruct "
212 "an object. Annotate it with "
213 "[[clang::annotate_type(\"webkit.nodelete\")]] if it does not.";
214 }
215
216 SourceLocation Loc =
217 Offender ? Offender->getBeginLoc() : Fn->getLocation();
218 SourceRange Range =
219 Offender ? Offender->getSourceRange() : Fn->getSourceRange();
220 Report.addNote(
221 Msg: Os.str(), Pos: PathDiagnosticLocation(Loc, BR->getSourceManager()), Ranges: Range);
222 }
223 }
224};
225
226} // namespace
227
228void ento::registerNoDeleteChecker(CheckerManager &Mgr) {
229 Mgr.registerChecker<NoDeleteChecker>();
230}
231
232bool ento::shouldRegisterNoDeleteChecker(const CheckerManager &) {
233 return true;
234}
235