blob: 165dff5b107f5ffaa917cb9e1acb33f830fb0b69 [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//
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000037//===----------------------------------------------------------------------===//
38
Argyrios Kyrtzidis027a6ab2011-02-15 07:42:33 +000039#include "ClangSACheckers.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000040#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis695fb502011-02-17 21:39:17 +000041#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +000042#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000043#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Jordy Rosed1e5a892011-09-02 08:02:59 +000044#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000045#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000046#include "clang/AST/ParentMap.h"
47
48using namespace clang;
49using namespace ento;
50
51static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND);
52static bool isInitializationMethod(const ObjCMethodDecl *MD);
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +000053static bool isInitMessage(const ObjCMessage &msg);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000054static bool isSelfVar(SVal location, CheckerContext &C);
55
56namespace {
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000057class ObjCSelfInitChecker : public Checker<
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +000058 check::PostObjCMessage,
59 check::PostStmt<ObjCIvarRefExpr>,
60 check::PreStmt<ReturnStmt>,
61 check::PreStmt<CallExpr>,
62 check::PostStmt<CallExpr>,
63 check::Location > {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000064public:
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +000065 void checkPostObjCMessage(ObjCMessage msg, CheckerContext &C) const;
66 void checkPostStmt(const ObjCIvarRefExpr *E, CheckerContext &C) const;
67 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
68 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
69 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anna Zaks390909c2011-10-06 00:43:15 +000070 void checkLocation(SVal location, bool isLoad, const Stmt *S,
71 CheckerContext &C) const;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000072};
73} // end anonymous namespace
74
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000075namespace {
76
77class InitSelfBug : public BugType {
78 const std::string desc;
79public:
Anna Zaks1efcc422012-02-04 02:31:37 +000080 InitSelfBug() : BugType("Missing \"self = [(super or self) init...]\"",
81 "Core Foundation/Objective-C") {}
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000082};
83
84} // end anonymous namespace
85
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +000086namespace {
87enum SelfFlagEnum {
88 /// \brief No flag set.
89 SelfFlag_None = 0x0,
90 /// \brief Value came from 'self'.
91 SelfFlag_Self = 0x1,
92 /// \brief Value came from the result of an initializer (e.g. [super init]).
93 SelfFlag_InitRes = 0x2
94};
95}
96
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000097typedef llvm::ImmutableMap<SymbolRef, unsigned> SelfFlag;
Ted Kremenekb715a7c2011-02-12 03:03:54 +000098namespace { struct CalledInit {}; }
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +000099namespace { struct PreCallSelfFlags {}; }
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000100
101namespace clang {
102namespace ento {
103 template<>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000104 struct ProgramStateTrait<SelfFlag> : public ProgramStatePartialTrait<SelfFlag> {
Ted Kremenek9c378f72011-08-12 23:37:29 +0000105 static void *GDMIndex() { static int index = 0; return &index; }
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000106 };
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000107 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000108 struct ProgramStateTrait<CalledInit> : public ProgramStatePartialTrait<bool> {
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000109 static void *GDMIndex() { static int index = 0; return &index; }
110 };
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000111
112 /// \brief A call receiving a reference to 'self' invalidates the object that
113 /// 'self' contains. This keeps the "self flags" assigned to the 'self'
114 /// object before the call so we can assign them to the new object that 'self'
115 /// points to after the call.
116 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000117 struct ProgramStateTrait<PreCallSelfFlags> : public ProgramStatePartialTrait<unsigned> {
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000118 static void *GDMIndex() { static int index = 0; return &index; }
119 };
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000120}
121}
122
Ted Kremenek8bef8232012-01-26 21:29:00 +0000123static SelfFlagEnum getSelfFlags(SVal val, ProgramStateRef state) {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000124 if (SymbolRef sym = val.getAsSymbol())
125 if (const unsigned *attachedFlags = state->get<SelfFlag>(sym))
126 return (SelfFlagEnum)*attachedFlags;
127 return SelfFlag_None;
128}
129
130static SelfFlagEnum getSelfFlags(SVal val, CheckerContext &C) {
131 return getSelfFlags(val, C.getState());
132}
133
Ted Kremenek8bef8232012-01-26 21:29:00 +0000134static void addSelfFlag(ProgramStateRef state, SVal val,
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000135 SelfFlagEnum flag, CheckerContext &C) {
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000136 // We tag the symbol that the SVal wraps.
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000137 if (SymbolRef sym = val.getAsSymbol())
Anna Zaks0bd6b112011-10-26 21:06:34 +0000138 C.addTransition(state->set<SelfFlag>(sym, getSelfFlags(val, C) | flag));
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000139}
140
141static bool hasSelfFlag(SVal val, SelfFlagEnum flag, CheckerContext &C) {
142 return getSelfFlags(val, C) & flag;
143}
144
145/// \brief Returns true of the value of the expression is the object that 'self'
146/// points to and is an object that did not come from the result of calling
147/// an initializer.
148static bool isInvalidSelf(const Expr *E, CheckerContext &C) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000149 SVal exprVal = C.getState()->getSVal(E, C.getLocationContext());
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000150 if (!hasSelfFlag(exprVal, SelfFlag_Self, C))
151 return false; // value did not come from 'self'.
152 if (hasSelfFlag(exprVal, SelfFlag_InitRes, C))
153 return false; // 'self' is properly initialized.
154
155 return true;
156}
157
158static void checkForInvalidSelf(const Expr *E, CheckerContext &C,
159 const char *errorStr) {
160 if (!E)
161 return;
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000162
163 if (!C.getState()->get<CalledInit>())
164 return;
165
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000166 if (!isInvalidSelf(E, C))
167 return;
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000168
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000169 // Generate an error node.
170 ExplodedNode *N = C.generateSink();
171 if (!N)
172 return;
173
Anna Zakse172e8b2011-08-17 23:00:25 +0000174 BugReport *report =
175 new BugReport(*new InitSelfBug(), errorStr, N);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000176 C.EmitReport(report);
177}
178
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000179void ObjCSelfInitChecker::checkPostObjCMessage(ObjCMessage msg,
180 CheckerContext &C) const {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000181 // When encountering a message that does initialization (init rule),
182 // tag the return value so that we know later on that if self has this value
183 // then it is properly initialized.
184
185 // FIXME: A callback should disable checkers at the start of functions.
186 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
Anna Zaks1efcc422012-02-04 02:31:37 +0000187 C.getCurrentAnalysisDeclContext()->getDecl())))
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000188 return;
189
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +0000190 if (isInitMessage(msg)) {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000191 // Tag the return value as the result of an initializer.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000192 ProgramStateRef state = C.getState();
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000193
194 // FIXME this really should be context sensitive, where we record
195 // the current stack frame (for IPA). Also, we need to clean this
196 // value out when we return from this method.
197 state = state->set<CalledInit>(true);
198
Ted Kremenekb673a412012-02-18 20:53:30 +0000199 SVal V = state->getSVal(msg.getMessageExpr(), C.getLocationContext());
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000200 addSelfFlag(state, V, SelfFlag_InitRes, C);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000201 return;
202 }
203
204 // We don't check for an invalid 'self' in an obj-c message expression to cut
205 // down false positives where logging functions get information from self
206 // (like its class) or doing "invalidation" on self when the initialization
207 // fails.
208}
209
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000210void ObjCSelfInitChecker::checkPostStmt(const ObjCIvarRefExpr *E,
211 CheckerContext &C) const {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000212 // FIXME: A callback should disable checkers at the start of functions.
213 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
Anna Zaks1efcc422012-02-04 02:31:37 +0000214 C.getCurrentAnalysisDeclContext()->getDecl())))
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000215 return;
216
217 checkForInvalidSelf(E->getBase(), C,
Argyrios Kyrtzidisbe29d8d2011-02-01 19:32:55 +0000218 "Instance variable used while 'self' is not set to the result of "
Argyrios Kyrtzidis4717f162011-01-26 01:26:41 +0000219 "'[(super or self) init...]'");
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000220}
221
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000222void ObjCSelfInitChecker::checkPreStmt(const ReturnStmt *S,
223 CheckerContext &C) const {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000224 // FIXME: A callback should disable checkers at the start of functions.
225 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
Anna Zaks1efcc422012-02-04 02:31:37 +0000226 C.getCurrentAnalysisDeclContext()->getDecl())))
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000227 return;
228
229 checkForInvalidSelf(S->getRetValue(), C,
Argyrios Kyrtzidis63eeade2011-02-01 20:33:05 +0000230 "Returning 'self' while it is not set to the result of "
Argyrios Kyrtzidis4717f162011-01-26 01:26:41 +0000231 "'[(super or self) init...]'");
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000232}
233
234// When a call receives a reference to 'self', [Pre/Post]VisitGenericCall pass
235// the SelfFlags from the object 'self' point to before the call, to the new
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000236// object after the call. This is to avoid invalidation of 'self' by logging
237// functions.
238// Another common pattern in classes with multiple initializers is to put the
239// subclass's common initialization bits into a static function that receives
240// the value of 'self', e.g:
241// @code
242// if (!(self = [super init]))
243// return nil;
244// if (!(self = _commonInit(self)))
245// return nil;
246// @endcode
247// Until we can use inter-procedural analysis, in such a call, transfer the
248// SelfFlags to the result of the call.
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000249
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000250void ObjCSelfInitChecker::checkPreStmt(const CallExpr *CE,
251 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000252 ProgramStateRef state = C.getState();
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000253 for (CallExpr::const_arg_iterator
254 I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000255 SVal argV = state->getSVal(*I, C.getLocationContext());
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000256 if (isSelfVar(argV, C)) {
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000257 unsigned selfFlags = getSelfFlags(state->getSVal(cast<Loc>(argV)), C);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000258 C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000259 return;
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000260 } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000261 unsigned selfFlags = getSelfFlags(argV, C);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000262 C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000263 return;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000264 }
265 }
266}
267
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000268void ObjCSelfInitChecker::checkPostStmt(const CallExpr *CE,
269 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000270 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000271 const LocationContext *LCtx = C.getLocationContext();
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000272 for (CallExpr::const_arg_iterator
273 I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000274 SVal argV = state->getSVal(*I, LCtx);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000275 if (isSelfVar(argV, C)) {
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000276 SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>();
277 state = state->remove<PreCallSelfFlags>();
278 addSelfFlag(state, state->getSVal(cast<Loc>(argV)), prevFlags, C);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000279 return;
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000280 } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000281 SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>();
282 state = state->remove<PreCallSelfFlags>();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000283 addSelfFlag(state, state->getSVal(CE, LCtx), prevFlags, C);
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000284 return;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000285 }
286 }
287}
288
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000289void ObjCSelfInitChecker::checkLocation(SVal location, bool isLoad,
Anna Zaks390909c2011-10-06 00:43:15 +0000290 const Stmt *S,
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000291 CheckerContext &C) const {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000292 // Tag the result of a load from 'self' so that we can easily know that the
293 // value is the object that 'self' points to.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000294 ProgramStateRef state = C.getState();
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000295 if (isSelfVar(location, C))
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000296 addSelfFlag(state, state->getSVal(cast<Loc>(location)), SelfFlag_Self, C);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000297}
298
299// FIXME: A callback should disable checkers at the start of functions.
300static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND) {
301 if (!ND)
302 return false;
303
304 const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND);
305 if (!MD)
306 return false;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000307 if (!isInitializationMethod(MD))
308 return false;
309
Argyrios Kyrtzidiseaf969b2011-01-25 23:54:44 +0000310 // self = [super init] applies only to NSObject subclasses.
311 // For instance, NSProxy doesn't implement -init.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000312 ASTContext &Ctx = MD->getASTContext();
Argyrios Kyrtzidiseaf969b2011-01-25 23:54:44 +0000313 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
Ted Kremenek9c378f72011-08-12 23:37:29 +0000314 ObjCInterfaceDecl *ID = MD->getClassInterface()->getSuperClass();
Argyrios Kyrtzidiseaf969b2011-01-25 23:54:44 +0000315 for ( ; ID ; ID = ID->getSuperClass()) {
316 IdentifierInfo *II = ID->getIdentifier();
317
318 if (II == NSObjectII)
319 break;
320 }
321 if (!ID)
322 return false;
323
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000324 return true;
325}
326
327/// \brief Returns true if the location is 'self'.
328static bool isSelfVar(SVal location, CheckerContext &C) {
Ted Kremenek1d26f482011-10-24 01:32:45 +0000329 AnalysisDeclContext *analCtx = C.getCurrentAnalysisDeclContext();
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000330 if (!analCtx->getSelfDecl())
331 return false;
332 if (!isa<loc::MemRegionVal>(location))
333 return false;
334
335 loc::MemRegionVal MRV = cast<loc::MemRegionVal>(location);
336 if (const DeclRegion *DR = dyn_cast<DeclRegion>(MRV.getRegion()))
337 return (DR->getDecl() == analCtx->getSelfDecl());
338
339 return false;
340}
341
342static bool isInitializationMethod(const ObjCMethodDecl *MD) {
John McCall85f3d762011-03-02 01:50:55 +0000343 return MD->getMethodFamily() == OMF_init;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000344}
345
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +0000346static bool isInitMessage(const ObjCMessage &msg) {
John McCall85f3d762011-03-02 01:50:55 +0000347 return msg.getMethodFamily() == OMF_init;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000348}
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000349
350//===----------------------------------------------------------------------===//
351// Registration.
352//===----------------------------------------------------------------------===//
353
354void ento::registerObjCSelfInitChecker(CheckerManager &mgr) {
355 mgr.registerChecker<ObjCSelfInitChecker>();
356}