blob: 87727305b68ce249d57e85d5d850e5cd7b3299f0 [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"
Ted Kremenek9b663712011-02-10 01:03:03 +000054#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000055#include "clang/AST/ParentMap.h"
56
57using namespace clang;
58using namespace ento;
59
60static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND);
61static bool isInitializationMethod(const ObjCMethodDecl *MD);
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +000062static bool isInitMessage(const ObjCMessage &msg);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000063static bool isSelfVar(SVal location, CheckerContext &C);
64
65namespace {
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000066class ObjCSelfInitChecker : public Checker<
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +000067 check::PostObjCMessage,
68 check::PostStmt<ObjCIvarRefExpr>,
69 check::PreStmt<ReturnStmt>,
70 check::PreStmt<CallExpr>,
71 check::PostStmt<CallExpr>,
72 check::Location > {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000073public:
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +000074 void checkPostObjCMessage(ObjCMessage msg, CheckerContext &C) const;
75 void checkPostStmt(const ObjCIvarRefExpr *E, CheckerContext &C) const;
76 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
77 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
78 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
79 void checkLocation(SVal location, bool isLoad, CheckerContext &C) const;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000080};
81} // end anonymous namespace
82
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000083namespace {
84
85class InitSelfBug : public BugType {
86 const std::string desc;
87public:
Argyrios Kyrtzidis4717f162011-01-26 01:26:41 +000088 InitSelfBug() : BugType("missing \"self = [(super or self) init...]\"",
89 "missing \"self = [(super or self) init...]\"") {}
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000090};
91
92} // end anonymous namespace
93
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +000094namespace {
95enum SelfFlagEnum {
96 /// \brief No flag set.
97 SelfFlag_None = 0x0,
98 /// \brief Value came from 'self'.
99 SelfFlag_Self = 0x1,
100 /// \brief Value came from the result of an initializer (e.g. [super init]).
101 SelfFlag_InitRes = 0x2
102};
103}
104
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000105typedef llvm::ImmutableMap<SymbolRef, unsigned> SelfFlag;
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000106namespace { struct CalledInit {}; }
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000107namespace { struct PreCallSelfFlags {}; }
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000108
109namespace clang {
110namespace ento {
111 template<>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000112 struct ProgramStateTrait<SelfFlag> : public ProgramStatePartialTrait<SelfFlag> {
Ted Kremenek9c378f72011-08-12 23:37:29 +0000113 static void *GDMIndex() { static int index = 0; return &index; }
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000114 };
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000115 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000116 struct ProgramStateTrait<CalledInit> : public ProgramStatePartialTrait<bool> {
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000117 static void *GDMIndex() { static int index = 0; return &index; }
118 };
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000119
120 /// \brief A call receiving a reference to 'self' invalidates the object that
121 /// 'self' contains. This keeps the "self flags" assigned to the 'self'
122 /// object before the call so we can assign them to the new object that 'self'
123 /// points to after the call.
124 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000125 struct ProgramStateTrait<PreCallSelfFlags> : public ProgramStatePartialTrait<unsigned> {
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000126 static void *GDMIndex() { static int index = 0; return &index; }
127 };
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000128}
129}
130
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000131static SelfFlagEnum getSelfFlags(SVal val, const ProgramState *state) {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000132 if (SymbolRef sym = val.getAsSymbol())
133 if (const unsigned *attachedFlags = state->get<SelfFlag>(sym))
134 return (SelfFlagEnum)*attachedFlags;
135 return SelfFlag_None;
136}
137
138static SelfFlagEnum getSelfFlags(SVal val, CheckerContext &C) {
139 return getSelfFlags(val, C.getState());
140}
141
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000142static void addSelfFlag(const ProgramState *state, SVal val,
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000143 SelfFlagEnum flag, CheckerContext &C) {
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000144 // We tag the symbol that the SVal wraps.
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000145 if (SymbolRef sym = val.getAsSymbol())
146 C.addTransition(state->set<SelfFlag>(sym, getSelfFlags(val, C) | flag));
147}
148
149static bool hasSelfFlag(SVal val, SelfFlagEnum flag, CheckerContext &C) {
150 return getSelfFlags(val, C) & flag;
151}
152
153/// \brief Returns true of the value of the expression is the object that 'self'
154/// points to and is an object that did not come from the result of calling
155/// an initializer.
156static bool isInvalidSelf(const Expr *E, CheckerContext &C) {
157 SVal exprVal = C.getState()->getSVal(E);
158 if (!hasSelfFlag(exprVal, SelfFlag_Self, C))
159 return false; // value did not come from 'self'.
160 if (hasSelfFlag(exprVal, SelfFlag_InitRes, C))
161 return false; // 'self' is properly initialized.
162
163 return true;
164}
165
166static void checkForInvalidSelf(const Expr *E, CheckerContext &C,
167 const char *errorStr) {
168 if (!E)
169 return;
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000170
171 if (!C.getState()->get<CalledInit>())
172 return;
173
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000174 if (!isInvalidSelf(E, C))
175 return;
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000176
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000177 // Generate an error node.
178 ExplodedNode *N = C.generateSink();
179 if (!N)
180 return;
181
Anna Zakse172e8b2011-08-17 23:00:25 +0000182 BugReport *report =
183 new BugReport(*new InitSelfBug(), errorStr, N);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000184 C.EmitReport(report);
185}
186
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000187void ObjCSelfInitChecker::checkPostObjCMessage(ObjCMessage msg,
188 CheckerContext &C) const {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000189 // When encountering a message that does initialization (init rule),
190 // tag the return value so that we know later on that if self has this value
191 // then it is properly initialized.
192
193 // FIXME: A callback should disable checkers at the start of functions.
194 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
195 C.getCurrentAnalysisContext()->getDecl())))
196 return;
197
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +0000198 if (isInitMessage(msg)) {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000199 // Tag the return value as the result of an initializer.
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000200 const ProgramState *state = C.getState();
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000201
202 // FIXME this really should be context sensitive, where we record
203 // the current stack frame (for IPA). Also, we need to clean this
204 // value out when we return from this method.
205 state = state->set<CalledInit>(true);
206
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +0000207 SVal V = state->getSVal(msg.getOriginExpr());
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000208 addSelfFlag(state, V, SelfFlag_InitRes, C);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000209 return;
210 }
211
212 // We don't check for an invalid 'self' in an obj-c message expression to cut
213 // down false positives where logging functions get information from self
214 // (like its class) or doing "invalidation" on self when the initialization
215 // fails.
216}
217
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000218void ObjCSelfInitChecker::checkPostStmt(const ObjCIvarRefExpr *E,
219 CheckerContext &C) const {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000220 // FIXME: A callback should disable checkers at the start of functions.
221 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
222 C.getCurrentAnalysisContext()->getDecl())))
223 return;
224
225 checkForInvalidSelf(E->getBase(), C,
Argyrios Kyrtzidisbe29d8d2011-02-01 19:32:55 +0000226 "Instance variable used while 'self' is not set to the result of "
Argyrios Kyrtzidis4717f162011-01-26 01:26:41 +0000227 "'[(super or self) init...]'");
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000228}
229
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000230void ObjCSelfInitChecker::checkPreStmt(const ReturnStmt *S,
231 CheckerContext &C) const {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000232 // FIXME: A callback should disable checkers at the start of functions.
233 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
234 C.getCurrentAnalysisContext()->getDecl())))
235 return;
236
237 checkForInvalidSelf(S->getRetValue(), C,
Argyrios Kyrtzidis63eeade2011-02-01 20:33:05 +0000238 "Returning 'self' while it is not set to the result of "
Argyrios Kyrtzidis4717f162011-01-26 01:26:41 +0000239 "'[(super or self) init...]'");
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000240}
241
242// When a call receives a reference to 'self', [Pre/Post]VisitGenericCall pass
243// the SelfFlags from the object 'self' point to before the call, to the new
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000244// object after the call. This is to avoid invalidation of 'self' by logging
245// functions.
246// Another common pattern in classes with multiple initializers is to put the
247// subclass's common initialization bits into a static function that receives
248// the value of 'self', e.g:
249// @code
250// if (!(self = [super init]))
251// return nil;
252// if (!(self = _commonInit(self)))
253// return nil;
254// @endcode
255// Until we can use inter-procedural analysis, in such a call, transfer the
256// SelfFlags to the result of the call.
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000257
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000258void ObjCSelfInitChecker::checkPreStmt(const CallExpr *CE,
259 CheckerContext &C) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000260 const ProgramState *state = C.getState();
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000261 for (CallExpr::const_arg_iterator
262 I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) {
263 SVal argV = state->getSVal(*I);
264 if (isSelfVar(argV, C)) {
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000265 unsigned selfFlags = getSelfFlags(state->getSVal(cast<Loc>(argV)), C);
266 C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000267 return;
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000268 } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000269 unsigned selfFlags = getSelfFlags(argV, C);
270 C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000271 return;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000272 }
273 }
274}
275
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000276void ObjCSelfInitChecker::checkPostStmt(const CallExpr *CE,
277 CheckerContext &C) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000278 const ProgramState *state = C.getState();
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000279 for (CallExpr::const_arg_iterator
280 I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) {
281 SVal argV = state->getSVal(*I);
282 if (isSelfVar(argV, C)) {
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000283 SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>();
284 state = state->remove<PreCallSelfFlags>();
285 addSelfFlag(state, state->getSVal(cast<Loc>(argV)), prevFlags, C);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000286 return;
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000287 } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000288 SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>();
289 state = state->remove<PreCallSelfFlags>();
290 addSelfFlag(state, state->getSVal(CE), prevFlags, C);
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000291 return;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000292 }
293 }
294}
295
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000296void ObjCSelfInitChecker::checkLocation(SVal location, bool isLoad,
297 CheckerContext &C) const {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000298 // Tag the result of a load from 'self' so that we can easily know that the
299 // value is the object that 'self' points to.
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000300 const ProgramState *state = C.getState();
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000301 if (isSelfVar(location, C))
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000302 addSelfFlag(state, state->getSVal(cast<Loc>(location)), SelfFlag_Self, C);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000303}
304
305// FIXME: A callback should disable checkers at the start of functions.
306static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND) {
307 if (!ND)
308 return false;
309
310 const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND);
311 if (!MD)
312 return false;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000313 if (!isInitializationMethod(MD))
314 return false;
315
Argyrios Kyrtzidiseaf969b2011-01-25 23:54:44 +0000316 // self = [super init] applies only to NSObject subclasses.
317 // For instance, NSProxy doesn't implement -init.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000318 ASTContext &Ctx = MD->getASTContext();
Argyrios Kyrtzidiseaf969b2011-01-25 23:54:44 +0000319 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
Ted Kremenek9c378f72011-08-12 23:37:29 +0000320 ObjCInterfaceDecl *ID = MD->getClassInterface()->getSuperClass();
Argyrios Kyrtzidiseaf969b2011-01-25 23:54:44 +0000321 for ( ; ID ; ID = ID->getSuperClass()) {
322 IdentifierInfo *II = ID->getIdentifier();
323
324 if (II == NSObjectII)
325 break;
326 }
327 if (!ID)
328 return false;
329
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000330 return true;
331}
332
333/// \brief Returns true if the location is 'self'.
334static bool isSelfVar(SVal location, CheckerContext &C) {
335 AnalysisContext *analCtx = C.getCurrentAnalysisContext();
336 if (!analCtx->getSelfDecl())
337 return false;
338 if (!isa<loc::MemRegionVal>(location))
339 return false;
340
341 loc::MemRegionVal MRV = cast<loc::MemRegionVal>(location);
342 if (const DeclRegion *DR = dyn_cast<DeclRegion>(MRV.getRegion()))
343 return (DR->getDecl() == analCtx->getSelfDecl());
344
345 return false;
346}
347
348static bool isInitializationMethod(const ObjCMethodDecl *MD) {
John McCall85f3d762011-03-02 01:50:55 +0000349 return MD->getMethodFamily() == OMF_init;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000350}
351
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +0000352static bool isInitMessage(const ObjCMessage &msg) {
John McCall85f3d762011-03-02 01:50:55 +0000353 return msg.getMethodFamily() == OMF_init;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000354}
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000355
356//===----------------------------------------------------------------------===//
357// Registration.
358//===----------------------------------------------------------------------===//
359
360void ento::registerObjCSelfInitChecker(CheckerManager &mgr) {
361 mgr.registerChecker<ObjCSelfInitChecker>();
362}