ObjCMissingSuperCallChecker.cpp
9.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
//==- ObjCMissingSuperCallChecker.cpp - Check missing super-calls in ObjC --==//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines a ObjCMissingSuperCallChecker, a checker that
// analyzes a UIViewController implementation to determine if it
// correctly calls super in the methods where this is mandatory.
//
//===----------------------------------------------------------------------===//
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
#include "clang/Analysis/PathDiagnostic.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
using namespace ento;
namespace {
struct SelectorDescriptor {
const char *SelectorName;
unsigned ArgumentCount;
};
//===----------------------------------------------------------------------===//
// FindSuperCallVisitor - Identify specific calls to the superclass.
//===----------------------------------------------------------------------===//
class FindSuperCallVisitor : public RecursiveASTVisitor<FindSuperCallVisitor> {
public:
explicit FindSuperCallVisitor(Selector S) : DoesCallSuper(false), Sel(S) {}
bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
if (E->getSelector() == Sel)
if (E->getReceiverKind() == ObjCMessageExpr::SuperInstance)
DoesCallSuper = true;
// Recurse if we didn't find the super call yet.
return !DoesCallSuper;
}
bool DoesCallSuper;
private:
Selector Sel;
};
//===----------------------------------------------------------------------===//
// ObjCSuperCallChecker
//===----------------------------------------------------------------------===//
class ObjCSuperCallChecker : public Checker<
check::ASTDecl<ObjCImplementationDecl> > {
public:
ObjCSuperCallChecker() : IsInitialized(false) {}
void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager &Mgr,
BugReporter &BR) const;
private:
bool isCheckableClass(const ObjCImplementationDecl *D,
StringRef &SuperclassName) const;
void initializeSelectors(ASTContext &Ctx) const;
void fillSelectors(ASTContext &Ctx, ArrayRef<SelectorDescriptor> Sel,
StringRef ClassName) const;
mutable llvm::StringMap<llvm::SmallSet<Selector, 16> > SelectorsForClass;
mutable bool IsInitialized;
};
}
/// Determine whether the given class has a superclass that we want
/// to check. The name of the found superclass is stored in SuperclassName.
///
/// \param D The declaration to check for superclasses.
/// \param[out] SuperclassName On return, the found superclass name.
bool ObjCSuperCallChecker::isCheckableClass(const ObjCImplementationDecl *D,
StringRef &SuperclassName) const {
const ObjCInterfaceDecl *ID = D->getClassInterface()->getSuperClass();
for ( ; ID ; ID = ID->getSuperClass())
{
SuperclassName = ID->getIdentifier()->getName();
if (SelectorsForClass.count(SuperclassName))
return true;
}
return false;
}
void ObjCSuperCallChecker::fillSelectors(ASTContext &Ctx,
ArrayRef<SelectorDescriptor> Sel,
StringRef ClassName) const {
llvm::SmallSet<Selector, 16> &ClassSelectors = SelectorsForClass[ClassName];
// Fill the Selectors SmallSet with all selectors we want to check.
for (ArrayRef<SelectorDescriptor>::iterator I = Sel.begin(), E = Sel.end();
I != E; ++I) {
SelectorDescriptor Descriptor = *I;
assert(Descriptor.ArgumentCount <= 1); // No multi-argument selectors yet.
// Get the selector.
IdentifierInfo *II = &Ctx.Idents.get(Descriptor.SelectorName);
Selector Sel = Ctx.Selectors.getSelector(Descriptor.ArgumentCount, &II);
ClassSelectors.insert(Sel);
}
}
void ObjCSuperCallChecker::initializeSelectors(ASTContext &Ctx) const {
{ // Initialize selectors for: UIViewController
const SelectorDescriptor Selectors[] = {
{ "addChildViewController", 1 },
{ "viewDidAppear", 1 },
{ "viewDidDisappear", 1 },
{ "viewWillAppear", 1 },
{ "viewWillDisappear", 1 },
{ "removeFromParentViewController", 0 },
{ "didReceiveMemoryWarning", 0 },
{ "viewDidUnload", 0 },
{ "viewDidLoad", 0 },
{ "viewWillUnload", 0 },
{ "updateViewConstraints", 0 },
{ "encodeRestorableStateWithCoder", 1 },
{ "restoreStateWithCoder", 1 }};
fillSelectors(Ctx, Selectors, "UIViewController");
}
{ // Initialize selectors for: UIResponder
const SelectorDescriptor Selectors[] = {
{ "resignFirstResponder", 0 }};
fillSelectors(Ctx, Selectors, "UIResponder");
}
{ // Initialize selectors for: NSResponder
const SelectorDescriptor Selectors[] = {
{ "encodeRestorableStateWithCoder", 1 },
{ "restoreStateWithCoder", 1 }};
fillSelectors(Ctx, Selectors, "NSResponder");
}
{ // Initialize selectors for: NSDocument
const SelectorDescriptor Selectors[] = {
{ "encodeRestorableStateWithCoder", 1 },
{ "restoreStateWithCoder", 1 }};
fillSelectors(Ctx, Selectors, "NSDocument");
}
IsInitialized = true;
}
void ObjCSuperCallChecker::checkASTDecl(const ObjCImplementationDecl *D,
AnalysisManager &Mgr,
BugReporter &BR) const {
ASTContext &Ctx = BR.getContext();
// We need to initialize the selector table once.
if (!IsInitialized)
initializeSelectors(Ctx);
// Find out whether this class has a superclass that we are supposed to check.
StringRef SuperclassName;
if (!isCheckableClass(D, SuperclassName))
return;
// Iterate over all instance methods.
for (auto *MD : D->instance_methods()) {
Selector S = MD->getSelector();
// Find out whether this is a selector that we want to check.
if (!SelectorsForClass[SuperclassName].count(S))
continue;
// Check if the method calls its superclass implementation.
if (MD->getBody())
{
FindSuperCallVisitor Visitor(S);
Visitor.TraverseDecl(MD);
// It doesn't call super, emit a diagnostic.
if (!Visitor.DoesCallSuper) {
PathDiagnosticLocation DLoc =
PathDiagnosticLocation::createEnd(MD->getBody(),
BR.getSourceManager(),
Mgr.getAnalysisDeclContext(D));
const char *Name = "Missing call to superclass";
SmallString<320> Buf;
llvm::raw_svector_ostream os(Buf);
os << "The '" << S.getAsString()
<< "' instance method in " << SuperclassName.str() << " subclass '"
<< *D << "' is missing a [super " << S.getAsString() << "] call";
BR.EmitBasicReport(MD, this, Name, categories::CoreFoundationObjectiveC,
os.str(), DLoc);
}
}
}
}
//===----------------------------------------------------------------------===//
// Check registration.
//===----------------------------------------------------------------------===//
void ento::registerObjCSuperCallChecker(CheckerManager &Mgr) {
Mgr.registerChecker<ObjCSuperCallChecker>();
}
bool ento::shouldRegisterObjCSuperCallChecker(const CheckerManager &mgr) {
return true;
}
/*
ToDo list for expanding this check in the future, the list is not exhaustive.
There are also cases where calling super is suggested but not "mandatory".
In addition to be able to check the classes and methods below, architectural
improvements like being able to allow for the super-call to be done in a called
method would be good too.
UIDocument subclasses
- finishedHandlingError:recovered: (is multi-arg)
- finishedHandlingError:recovered: (is multi-arg)
UIViewController subclasses
- loadView (should *never* call super)
- transitionFromViewController:toViewController:
duration:options:animations:completion: (is multi-arg)
UICollectionViewController subclasses
- loadView (take care because UIViewController subclasses should NOT call super
in loadView, but UICollectionViewController subclasses should)
NSObject subclasses
- doesNotRecognizeSelector (it only has to call super if it doesn't throw)
UIPopoverBackgroundView subclasses (some of those are class methods)
- arrowDirection (should *never* call super)
- arrowOffset (should *never* call super)
- arrowBase (should *never* call super)
- arrowHeight (should *never* call super)
- contentViewInsets (should *never* call super)
UITextSelectionRect subclasses (some of those are properties)
- rect (should *never* call super)
- range (should *never* call super)
- writingDirection (should *never* call super)
- isVertical (should *never* call super)
- containsStart (should *never* call super)
- containsEnd (should *never* call super)
*/