blob: 8b29a20dc625fcab89227aff882460be9a5b9e7a [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//
Chris Lattnerfc8f0e12011-04-15 05:22:18 +000019// To perform the required checking, values are tagged with flags that indicate
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000020// 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"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000050#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis695fb502011-02-17 21:39:17 +000051#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +000052#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000053#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Jordy Rosed1e5a892011-09-02 08:02:59 +000054#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000055#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000056#include "clang/AST/ParentMap.h"
57
58using namespace clang;
59using namespace ento;
60
61static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND);
62static bool isInitializationMethod(const ObjCMethodDecl *MD);
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +000063static bool isInitMessage(const ObjCMessage &msg);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000064static bool isSelfVar(SVal location, CheckerContext &C);
65
66namespace {
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000067class ObjCSelfInitChecker : public Checker<
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +000068 check::PostObjCMessage,
69 check::PostStmt<ObjCIvarRefExpr>,
70 check::PreStmt<ReturnStmt>,
71 check::PreStmt<CallExpr>,
72 check::PostStmt<CallExpr>,
73 check::Location > {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000074public:
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +000075 void checkPostObjCMessage(ObjCMessage msg, CheckerContext &C) const;
76 void checkPostStmt(const ObjCIvarRefExpr *E, CheckerContext &C) const;
77 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
78 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
79 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anna Zaks390909c2011-10-06 00:43:15 +000080 void checkLocation(SVal location, bool isLoad, const Stmt *S,
81 CheckerContext &C) const;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000082};
83} // end anonymous namespace
84
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000085namespace {
86
87class InitSelfBug : public BugType {
88 const std::string desc;
89public:
Argyrios Kyrtzidis4717f162011-01-26 01:26:41 +000090 InitSelfBug() : BugType("missing \"self = [(super or self) init...]\"",
91 "missing \"self = [(super or self) init...]\"") {}
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000092};
93
94} // end anonymous namespace
95
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +000096namespace {
97enum SelfFlagEnum {
98 /// \brief No flag set.
99 SelfFlag_None = 0x0,
100 /// \brief Value came from 'self'.
101 SelfFlag_Self = 0x1,
102 /// \brief Value came from the result of an initializer (e.g. [super init]).
103 SelfFlag_InitRes = 0x2
104};
105}
106
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000107typedef llvm::ImmutableMap<SymbolRef, unsigned> SelfFlag;
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000108namespace { struct CalledInit {}; }
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000109namespace { struct PreCallSelfFlags {}; }
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000110
111namespace clang {
112namespace ento {
113 template<>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000114 struct ProgramStateTrait<SelfFlag> : public ProgramStatePartialTrait<SelfFlag> {
Ted Kremenek9c378f72011-08-12 23:37:29 +0000115 static void *GDMIndex() { static int index = 0; return &index; }
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000116 };
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000117 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000118 struct ProgramStateTrait<CalledInit> : public ProgramStatePartialTrait<bool> {
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000119 static void *GDMIndex() { static int index = 0; return &index; }
120 };
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000121
122 /// \brief A call receiving a reference to 'self' invalidates the object that
123 /// 'self' contains. This keeps the "self flags" assigned to the 'self'
124 /// object before the call so we can assign them to the new object that 'self'
125 /// points to after the call.
126 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000127 struct ProgramStateTrait<PreCallSelfFlags> : public ProgramStatePartialTrait<unsigned> {
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000128 static void *GDMIndex() { static int index = 0; return &index; }
129 };
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000130}
131}
132
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000133static SelfFlagEnum getSelfFlags(SVal val, const ProgramState *state) {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000134 if (SymbolRef sym = val.getAsSymbol())
135 if (const unsigned *attachedFlags = state->get<SelfFlag>(sym))
136 return (SelfFlagEnum)*attachedFlags;
137 return SelfFlag_None;
138}
139
140static SelfFlagEnum getSelfFlags(SVal val, CheckerContext &C) {
141 return getSelfFlags(val, C.getState());
142}
143
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000144static void addSelfFlag(const ProgramState *state, SVal val,
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000145 SelfFlagEnum flag, CheckerContext &C) {
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000146 // We tag the symbol that the SVal wraps.
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000147 if (SymbolRef sym = val.getAsSymbol())
Anna Zaks0bd6b112011-10-26 21:06:34 +0000148 C.addTransition(state->set<SelfFlag>(sym, getSelfFlags(val, C) | flag));
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000149}
150
151static bool hasSelfFlag(SVal val, SelfFlagEnum flag, CheckerContext &C) {
152 return getSelfFlags(val, C) & flag;
153}
154
155/// \brief Returns true of the value of the expression is the object that 'self'
156/// points to and is an object that did not come from the result of calling
157/// an initializer.
158static bool isInvalidSelf(const Expr *E, CheckerContext &C) {
159 SVal exprVal = C.getState()->getSVal(E);
160 if (!hasSelfFlag(exprVal, SelfFlag_Self, C))
161 return false; // value did not come from 'self'.
162 if (hasSelfFlag(exprVal, SelfFlag_InitRes, C))
163 return false; // 'self' is properly initialized.
164
165 return true;
166}
167
168static void checkForInvalidSelf(const Expr *E, CheckerContext &C,
169 const char *errorStr) {
170 if (!E)
171 return;
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000172
173 if (!C.getState()->get<CalledInit>())
174 return;
175
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000176 if (!isInvalidSelf(E, C))
177 return;
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000178
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000179 // Generate an error node.
180 ExplodedNode *N = C.generateSink();
181 if (!N)
182 return;
183
Anna Zakse172e8b2011-08-17 23:00:25 +0000184 BugReport *report =
185 new BugReport(*new InitSelfBug(), errorStr, N);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000186 C.EmitReport(report);
187}
188
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000189void ObjCSelfInitChecker::checkPostObjCMessage(ObjCMessage msg,
190 CheckerContext &C) const {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000191 // When encountering a message that does initialization (init rule),
192 // tag the return value so that we know later on that if self has this value
193 // then it is properly initialized.
194
195 // FIXME: A callback should disable checkers at the start of functions.
196 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
Ted Kremenek1d26f482011-10-24 01:32:45 +0000197 C.getCurrentAnalysisDeclContext()->getDecl())))
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000198 return;
199
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +0000200 if (isInitMessage(msg)) {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000201 // Tag the return value as the result of an initializer.
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000202 const ProgramState *state = C.getState();
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000203
204 // FIXME this really should be context sensitive, where we record
205 // the current stack frame (for IPA). Also, we need to clean this
206 // value out when we return from this method.
207 state = state->set<CalledInit>(true);
208
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +0000209 SVal V = state->getSVal(msg.getOriginExpr());
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000210 addSelfFlag(state, V, SelfFlag_InitRes, C);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000211 return;
212 }
213
214 // We don't check for an invalid 'self' in an obj-c message expression to cut
215 // down false positives where logging functions get information from self
216 // (like its class) or doing "invalidation" on self when the initialization
217 // fails.
218}
219
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000220void ObjCSelfInitChecker::checkPostStmt(const ObjCIvarRefExpr *E,
221 CheckerContext &C) const {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000222 // FIXME: A callback should disable checkers at the start of functions.
223 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
Ted Kremenek1d26f482011-10-24 01:32:45 +0000224 C.getCurrentAnalysisDeclContext()->getDecl())))
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000225 return;
226
227 checkForInvalidSelf(E->getBase(), C,
Argyrios Kyrtzidisbe29d8d2011-02-01 19:32:55 +0000228 "Instance variable used while 'self' is not set to the result of "
Argyrios Kyrtzidis4717f162011-01-26 01:26:41 +0000229 "'[(super or self) init...]'");
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000230}
231
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000232void ObjCSelfInitChecker::checkPreStmt(const ReturnStmt *S,
233 CheckerContext &C) const {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000234 // FIXME: A callback should disable checkers at the start of functions.
235 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
Ted Kremenek1d26f482011-10-24 01:32:45 +0000236 C.getCurrentAnalysisDeclContext()->getDecl())))
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000237 return;
238
239 checkForInvalidSelf(S->getRetValue(), C,
Argyrios Kyrtzidis63eeade2011-02-01 20:33:05 +0000240 "Returning 'self' while it is not set to the result of "
Argyrios Kyrtzidis4717f162011-01-26 01:26:41 +0000241 "'[(super or self) init...]'");
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000242}
243
244// When a call receives a reference to 'self', [Pre/Post]VisitGenericCall pass
245// the SelfFlags from the object 'self' point to before the call, to the new
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000246// object after the call. This is to avoid invalidation of 'self' by logging
247// functions.
248// Another common pattern in classes with multiple initializers is to put the
249// subclass's common initialization bits into a static function that receives
250// the value of 'self', e.g:
251// @code
252// if (!(self = [super init]))
253// return nil;
254// if (!(self = _commonInit(self)))
255// return nil;
256// @endcode
257// Until we can use inter-procedural analysis, in such a call, transfer the
258// SelfFlags to the result of the call.
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000259
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000260void ObjCSelfInitChecker::checkPreStmt(const CallExpr *CE,
261 CheckerContext &C) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000262 const ProgramState *state = C.getState();
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000263 for (CallExpr::const_arg_iterator
264 I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) {
265 SVal argV = state->getSVal(*I);
266 if (isSelfVar(argV, C)) {
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000267 unsigned selfFlags = getSelfFlags(state->getSVal(cast<Loc>(argV)), C);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000268 C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000269 return;
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000270 } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000271 unsigned selfFlags = getSelfFlags(argV, C);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000272 C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000273 return;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000274 }
275 }
276}
277
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000278void ObjCSelfInitChecker::checkPostStmt(const CallExpr *CE,
279 CheckerContext &C) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000280 const ProgramState *state = C.getState();
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000281 for (CallExpr::const_arg_iterator
282 I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) {
283 SVal argV = state->getSVal(*I);
284 if (isSelfVar(argV, C)) {
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000285 SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>();
286 state = state->remove<PreCallSelfFlags>();
287 addSelfFlag(state, state->getSVal(cast<Loc>(argV)), prevFlags, C);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000288 return;
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000289 } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000290 SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>();
291 state = state->remove<PreCallSelfFlags>();
292 addSelfFlag(state, state->getSVal(CE), prevFlags, C);
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000293 return;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000294 }
295 }
296}
297
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000298void ObjCSelfInitChecker::checkLocation(SVal location, bool isLoad,
Anna Zaks390909c2011-10-06 00:43:15 +0000299 const Stmt *S,
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000300 CheckerContext &C) const {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000301 // Tag the result of a load from 'self' so that we can easily know that the
302 // value is the object that 'self' points to.
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000303 const ProgramState *state = C.getState();
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000304 if (isSelfVar(location, C))
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000305 addSelfFlag(state, state->getSVal(cast<Loc>(location)), SelfFlag_Self, C);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000306}
307
308// FIXME: A callback should disable checkers at the start of functions.
309static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND) {
310 if (!ND)
311 return false;
312
313 const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND);
314 if (!MD)
315 return false;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000316 if (!isInitializationMethod(MD))
317 return false;
318
Argyrios Kyrtzidiseaf969b2011-01-25 23:54:44 +0000319 // self = [super init] applies only to NSObject subclasses.
320 // For instance, NSProxy doesn't implement -init.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000321 ASTContext &Ctx = MD->getASTContext();
Argyrios Kyrtzidiseaf969b2011-01-25 23:54:44 +0000322 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
Ted Kremenek9c378f72011-08-12 23:37:29 +0000323 ObjCInterfaceDecl *ID = MD->getClassInterface()->getSuperClass();
Argyrios Kyrtzidiseaf969b2011-01-25 23:54:44 +0000324 for ( ; ID ; ID = ID->getSuperClass()) {
325 IdentifierInfo *II = ID->getIdentifier();
326
327 if (II == NSObjectII)
328 break;
329 }
330 if (!ID)
331 return false;
332
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000333 return true;
334}
335
336/// \brief Returns true if the location is 'self'.
337static bool isSelfVar(SVal location, CheckerContext &C) {
Ted Kremenek1d26f482011-10-24 01:32:45 +0000338 AnalysisDeclContext *analCtx = C.getCurrentAnalysisDeclContext();
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000339 if (!analCtx->getSelfDecl())
340 return false;
341 if (!isa<loc::MemRegionVal>(location))
342 return false;
343
344 loc::MemRegionVal MRV = cast<loc::MemRegionVal>(location);
345 if (const DeclRegion *DR = dyn_cast<DeclRegion>(MRV.getRegion()))
346 return (DR->getDecl() == analCtx->getSelfDecl());
347
348 return false;
349}
350
351static bool isInitializationMethod(const ObjCMethodDecl *MD) {
John McCall85f3d762011-03-02 01:50:55 +0000352 return MD->getMethodFamily() == OMF_init;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000353}
354
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +0000355static bool isInitMessage(const ObjCMessage &msg) {
John McCall85f3d762011-03-02 01:50:55 +0000356 return msg.getMethodFamily() == OMF_init;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000357}
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000358
359//===----------------------------------------------------------------------===//
360// Registration.
361//===----------------------------------------------------------------------===//
362
363void ento::registerObjCSelfInitChecker(CheckerManager &mgr) {
364 mgr.registerChecker<ObjCSelfInitChecker>();
365}