blob: f3810e04ff1c702c59fb5dca47fb97578f1bfd87 [file] [log] [blame]
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +00001//== ObjCSelfInitChecker.cpp - Checker for 'self' initialization -*- C++ -*--=//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This defines ObjCSelfInitChecker, a builtin check that checks for uses of
11// 'self' before proper initialization.
12//
13//===----------------------------------------------------------------------===//
14
15// This checks initialization methods to verify that they assign 'self' to the
16// result of an initialization call (e.g. [super init], or [self initWith..])
17// before using 'self' or any instance variable.
18//
19// To perform the required checking, values are tagged wih flags that indicate
20// 1) if the object is the one pointed to by 'self', and 2) if the object
21// is the result of an initializer (e.g. [super init]).
22//
23// Uses of an object that is true for 1) but not 2) trigger a diagnostic.
24// The uses that are currently checked are:
25// - Using instance variables.
26// - Returning the object.
27//
28// Note that we don't check for an invalid 'self' that is the receiver of an
29// obj-c message expression to cut down false positives where logging functions
30// get information from self (like its class) or doing "invalidation" on self
31// when the initialization fails.
32//
33// Because the object that 'self' points to gets invalidated when a call
34// receives a reference to 'self', the checker keeps track and passes the flags
35// for 1) and 2) to the new object that 'self' points to after the call.
36//
37// FIXME (rdar://7937506): In the case of:
38// [super init];
39// return self;
40// Have an extra PathDiagnosticPiece in the path that says "called [super init],
41// but didn't assign the result to self."
42
43//===----------------------------------------------------------------------===//
44
45// FIXME: Somehow stick the link to Apple's documentation about initializing
46// objects in the diagnostics.
47// http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocAllocInit.html
48
Argyrios Kyrtzidis027a6ab2011-02-15 07:42:33 +000049#include "ClangSACheckers.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000050#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerVisitor.h"
51#include "clang/StaticAnalyzer/Core/PathSensitive/GRStateTrait.h"
52#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000053#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
54#include "clang/AST/ParentMap.h"
55
56using namespace clang;
57using namespace ento;
58
59static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND);
60static bool isInitializationMethod(const ObjCMethodDecl *MD);
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +000061static bool isInitMessage(const ObjCMessage &msg);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000062static bool isSelfVar(SVal location, CheckerContext &C);
63
64namespace {
65enum SelfFlagEnum {
66 /// \brief No flag set.
67 SelfFlag_None = 0x0,
68 /// \brief Value came from 'self'.
69 SelfFlag_Self = 0x1,
70 /// \brief Value came from the result of an initializer (e.g. [super init]).
71 SelfFlag_InitRes = 0x2
72};
73}
74
75namespace {
76class ObjCSelfInitChecker : public CheckerVisitor<ObjCSelfInitChecker> {
77 /// \brief A call receiving a reference to 'self' invalidates the object that
78 /// 'self' contains. This field keeps the "self flags" assigned to the 'self'
79 /// object before the call and assign them to the new object that 'self'
80 /// points to after the call.
81 SelfFlagEnum preCallSelfFlags;
82
83public:
84 static void *getTag() { static int tag = 0; return &tag; }
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +000085 void postVisitObjCMessage(CheckerContext &C, ObjCMessage msg);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000086 void PostVisitObjCIvarRefExpr(CheckerContext &C, const ObjCIvarRefExpr *E);
87 void PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S);
88 void PreVisitGenericCall(CheckerContext &C, const CallExpr *CE);
89 void PostVisitGenericCall(CheckerContext &C, const CallExpr *CE);
90 virtual void visitLocation(CheckerContext &C, const Stmt *S, SVal location,
91 bool isLoad);
92};
93} // end anonymous namespace
94
95void ento::registerObjCSelfInitChecker(ExprEngine &Eng) {
96 if (Eng.getContext().getLangOptions().ObjC1)
97 Eng.registerCheck(new ObjCSelfInitChecker());
98}
99
100namespace {
101
102class InitSelfBug : public BugType {
103 const std::string desc;
104public:
Argyrios Kyrtzidis4717f162011-01-26 01:26:41 +0000105 InitSelfBug() : BugType("missing \"self = [(super or self) init...]\"",
106 "missing \"self = [(super or self) init...]\"") {}
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000107};
108
109} // end anonymous namespace
110
111typedef llvm::ImmutableMap<SymbolRef, unsigned> SelfFlag;
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000112namespace { struct CalledInit {}; }
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000113
114namespace clang {
115namespace ento {
116 template<>
117 struct GRStateTrait<SelfFlag> : public GRStatePartialTrait<SelfFlag> {
118 static void* GDMIndex() {
119 static int index = 0;
120 return &index;
121 }
122 };
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000123 template <>
124 struct GRStateTrait<CalledInit> : public GRStatePartialTrait<bool> {
125 static void *GDMIndex() { static int index = 0; return &index; }
126 };
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000127}
128}
129
130static SelfFlagEnum getSelfFlags(SVal val, const GRState *state) {
131 if (SymbolRef sym = val.getAsSymbol())
132 if (const unsigned *attachedFlags = state->get<SelfFlag>(sym))
133 return (SelfFlagEnum)*attachedFlags;
134 return SelfFlag_None;
135}
136
137static SelfFlagEnum getSelfFlags(SVal val, CheckerContext &C) {
138 return getSelfFlags(val, C.getState());
139}
140
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000141static void addSelfFlag(const GRState *state, SVal val,
142 SelfFlagEnum flag, CheckerContext &C) {
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000143 // We tag the symbol that the SVal wraps.
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000144 if (SymbolRef sym = val.getAsSymbol())
145 C.addTransition(state->set<SelfFlag>(sym, getSelfFlags(val, C) | flag));
146}
147
148static bool hasSelfFlag(SVal val, SelfFlagEnum flag, CheckerContext &C) {
149 return getSelfFlags(val, C) & flag;
150}
151
152/// \brief Returns true of the value of the expression is the object that 'self'
153/// points to and is an object that did not come from the result of calling
154/// an initializer.
155static bool isInvalidSelf(const Expr *E, CheckerContext &C) {
156 SVal exprVal = C.getState()->getSVal(E);
157 if (!hasSelfFlag(exprVal, SelfFlag_Self, C))
158 return false; // value did not come from 'self'.
159 if (hasSelfFlag(exprVal, SelfFlag_InitRes, C))
160 return false; // 'self' is properly initialized.
161
162 return true;
163}
164
165static void checkForInvalidSelf(const Expr *E, CheckerContext &C,
166 const char *errorStr) {
167 if (!E)
168 return;
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000169
170 if (!C.getState()->get<CalledInit>())
171 return;
172
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000173 if (!isInvalidSelf(E, C))
174 return;
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000175
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000176 // Generate an error node.
177 ExplodedNode *N = C.generateSink();
178 if (!N)
179 return;
180
181 EnhancedBugReport *report =
182 new EnhancedBugReport(*new InitSelfBug(), errorStr, N);
183 C.EmitReport(report);
184}
185
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +0000186void ObjCSelfInitChecker::postVisitObjCMessage(CheckerContext &C,
187 ObjCMessage msg) {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000188 // When encountering a message that does initialization (init rule),
189 // tag the return value so that we know later on that if self has this value
190 // then it is properly initialized.
191
192 // FIXME: A callback should disable checkers at the start of functions.
193 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
194 C.getCurrentAnalysisContext()->getDecl())))
195 return;
196
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +0000197 if (isInitMessage(msg)) {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000198 // Tag the return value as the result of an initializer.
199 const GRState *state = C.getState();
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000200
201 // FIXME this really should be context sensitive, where we record
202 // the current stack frame (for IPA). Also, we need to clean this
203 // value out when we return from this method.
204 state = state->set<CalledInit>(true);
205
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +0000206 SVal V = state->getSVal(msg.getOriginExpr());
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000207 addSelfFlag(state, V, SelfFlag_InitRes, C);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000208 return;
209 }
210
211 // We don't check for an invalid 'self' in an obj-c message expression to cut
212 // down false positives where logging functions get information from self
213 // (like its class) or doing "invalidation" on self when the initialization
214 // fails.
215}
216
217void ObjCSelfInitChecker::PostVisitObjCIvarRefExpr(CheckerContext &C,
218 const ObjCIvarRefExpr *E) {
219 // FIXME: A callback should disable checkers at the start of functions.
220 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
221 C.getCurrentAnalysisContext()->getDecl())))
222 return;
223
224 checkForInvalidSelf(E->getBase(), C,
Argyrios Kyrtzidisbe29d8d2011-02-01 19:32:55 +0000225 "Instance variable used while 'self' is not set to the result of "
Argyrios Kyrtzidis4717f162011-01-26 01:26:41 +0000226 "'[(super or self) init...]'");
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000227}
228
229void ObjCSelfInitChecker::PreVisitReturnStmt(CheckerContext &C,
230 const ReturnStmt *S) {
231 // FIXME: A callback should disable checkers at the start of functions.
232 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
233 C.getCurrentAnalysisContext()->getDecl())))
234 return;
235
236 checkForInvalidSelf(S->getRetValue(), C,
Argyrios Kyrtzidis63eeade2011-02-01 20:33:05 +0000237 "Returning 'self' while it is not set to the result of "
Argyrios Kyrtzidis4717f162011-01-26 01:26:41 +0000238 "'[(super or self) init...]'");
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000239}
240
241// When a call receives a reference to 'self', [Pre/Post]VisitGenericCall pass
242// the SelfFlags from the object 'self' point to before the call, to the new
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000243// object after the call. This is to avoid invalidation of 'self' by logging
244// functions.
245// Another common pattern in classes with multiple initializers is to put the
246// subclass's common initialization bits into a static function that receives
247// the value of 'self', e.g:
248// @code
249// if (!(self = [super init]))
250// return nil;
251// if (!(self = _commonInit(self)))
252// return nil;
253// @endcode
254// Until we can use inter-procedural analysis, in such a call, transfer the
255// SelfFlags to the result of the call.
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000256
257void ObjCSelfInitChecker::PreVisitGenericCall(CheckerContext &C,
258 const CallExpr *CE) {
259 const GRState *state = C.getState();
260 for (CallExpr::const_arg_iterator
261 I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) {
262 SVal argV = state->getSVal(*I);
263 if (isSelfVar(argV, C)) {
264 preCallSelfFlags = getSelfFlags(state->getSVal(cast<Loc>(argV)), C);
265 return;
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000266 } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
267 preCallSelfFlags = getSelfFlags(argV, C);
268 return;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000269 }
270 }
271}
272
273void ObjCSelfInitChecker::PostVisitGenericCall(CheckerContext &C,
274 const CallExpr *CE) {
275 const GRState *state = C.getState();
276 for (CallExpr::const_arg_iterator
277 I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) {
278 SVal argV = state->getSVal(*I);
279 if (isSelfVar(argV, C)) {
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000280 addSelfFlag(state, state->getSVal(cast<Loc>(argV)), preCallSelfFlags, C);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000281 return;
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000282 } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000283 addSelfFlag(state, state->getSVal(CE), preCallSelfFlags, C);
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000284 return;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000285 }
286 }
287}
288
289void ObjCSelfInitChecker::visitLocation(CheckerContext &C, const Stmt *S,
290 SVal location, bool isLoad) {
291 // Tag the result of a load from 'self' so that we can easily know that the
292 // value is the object that 'self' points to.
293 const GRState *state = C.getState();
294 if (isSelfVar(location, C))
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000295 addSelfFlag(state, state->getSVal(cast<Loc>(location)), SelfFlag_Self, C);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000296}
297
298// FIXME: A callback should disable checkers at the start of functions.
299static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND) {
300 if (!ND)
301 return false;
302
303 const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND);
304 if (!MD)
305 return false;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000306 if (!isInitializationMethod(MD))
307 return false;
308
Argyrios Kyrtzidiseaf969b2011-01-25 23:54:44 +0000309 // self = [super init] applies only to NSObject subclasses.
310 // For instance, NSProxy doesn't implement -init.
311 ASTContext& Ctx = MD->getASTContext();
312 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
313 ObjCInterfaceDecl* ID = MD->getClassInterface()->getSuperClass();
314 for ( ; ID ; ID = ID->getSuperClass()) {
315 IdentifierInfo *II = ID->getIdentifier();
316
317 if (II == NSObjectII)
318 break;
319 }
320 if (!ID)
321 return false;
322
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000323 return true;
324}
325
326/// \brief Returns true if the location is 'self'.
327static bool isSelfVar(SVal location, CheckerContext &C) {
328 AnalysisContext *analCtx = C.getCurrentAnalysisContext();
329 if (!analCtx->getSelfDecl())
330 return false;
331 if (!isa<loc::MemRegionVal>(location))
332 return false;
333
334 loc::MemRegionVal MRV = cast<loc::MemRegionVal>(location);
335 if (const DeclRegion *DR = dyn_cast<DeclRegion>(MRV.getRegion()))
336 return (DR->getDecl() == analCtx->getSelfDecl());
337
338 return false;
339}
340
341static bool isInitializationMethod(const ObjCMethodDecl *MD) {
342 // Init methods with prefix like '-(id)_init' are private and the requirements
343 // are less strict so we don't check those.
344 return MD->isInstanceMethod() &&
345 cocoa::deriveNamingConvention(MD->getSelector(),
346 /*ignorePrefix=*/false) == cocoa::InitRule;
347}
348
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +0000349static bool isInitMessage(const ObjCMessage &msg) {
350 return cocoa::deriveNamingConvention(msg.getSelector()) == cocoa::InitRule;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000351}