blob: c25da874051aecd5427648da650c071e36ce820c [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"
Jordan Rose55037cd2012-07-02 19:27:46 +000042#include "clang/StaticAnalyzer/Core/PathSensitive/Calls.h"
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +000043#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000044#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Jordy Rosed1e5a892011-09-02 08:02:59 +000045#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000046#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000047#include "clang/AST/ParentMap.h"
48
49using namespace clang;
50using namespace ento;
51
52static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND);
53static bool isInitializationMethod(const ObjCMethodDecl *MD);
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +000054static bool isInitMessage(const ObjCMessage &msg);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000055static bool isSelfVar(SVal location, CheckerContext &C);
56
57namespace {
Anna Zaksf420fe32012-03-05 18:58:25 +000058class ObjCSelfInitChecker : public Checker< check::PreObjCMessage,
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +000059 check::PostObjCMessage,
60 check::PostStmt<ObjCIvarRefExpr>,
61 check::PreStmt<ReturnStmt>,
62 check::PreStmt<CallExpr>,
63 check::PostStmt<CallExpr>,
Anna Zaks6a2a1862012-05-08 21:19:21 +000064 check::Location,
65 check::Bind > {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000066public:
Anna Zaksf420fe32012-03-05 18:58:25 +000067 void checkPreObjCMessage(ObjCMessage msg, CheckerContext &C) const;
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +000068 void checkPostObjCMessage(ObjCMessage msg, CheckerContext &C) const;
69 void checkPostStmt(const ObjCIvarRefExpr *E, CheckerContext &C) const;
70 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
71 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
72 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anna Zaks390909c2011-10-06 00:43:15 +000073 void checkLocation(SVal location, bool isLoad, const Stmt *S,
74 CheckerContext &C) const;
Anna Zaks6a2a1862012-05-08 21:19:21 +000075 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Anna Zaksf420fe32012-03-05 18:58:25 +000076
Jordan Rose55037cd2012-07-02 19:27:46 +000077 void checkPreStmt(const CallEvent &CE, CheckerContext &C) const;
78 void checkPostStmt(const CallEvent &CE, CheckerContext &C) const;
Anna Zaksf420fe32012-03-05 18:58:25 +000079
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:
Anna Zaks1efcc422012-02-04 02:31:37 +000088 InitSelfBug() : BugType("Missing \"self = [(super or self) init...]\"",
Ted Kremenek6fd45052012-04-05 20:43:28 +000089 categories::CoreFoundationObjectiveC) {}
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 Kremenek8bef8232012-01-26 21:29:00 +0000131static SelfFlagEnum getSelfFlags(SVal val, ProgramStateRef 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 Kremenek8bef8232012-01-26 21:29:00 +0000142static void addSelfFlag(ProgramStateRef 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())
Anna Zaks0bd6b112011-10-26 21:06:34 +0000146 C.addTransition(state->set<SelfFlag>(sym, getSelfFlags(val, C) | flag));
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000147}
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) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000157 SVal exprVal = C.getState()->getSVal(E, C.getLocationContext());
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000158 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>(
Anna Zaks1efcc422012-02-04 02:31:37 +0000195 C.getCurrentAnalysisDeclContext()->getDecl())))
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000196 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 Kremenek8bef8232012-01-26 21:29:00 +0000200 ProgramStateRef 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
Ted Kremenekb673a412012-02-18 20:53:30 +0000207 SVal V = state->getSVal(msg.getMessageExpr(), C.getLocationContext());
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
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000212 // FIXME: ObjCMessage is going away.
213 ObjCMessageSend MsgWrapper(msg.getMessageExpr(), C.getState(),
214 C.getLocationContext());
Anna Zaks9a70cdd2012-04-16 21:51:09 +0000215 checkPostStmt(MsgWrapper, C);
216
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000217 // We don't check for an invalid 'self' in an obj-c message expression to cut
218 // down false positives where logging functions get information from self
219 // (like its class) or doing "invalidation" on self when the initialization
220 // fails.
221}
222
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000223void ObjCSelfInitChecker::checkPostStmt(const ObjCIvarRefExpr *E,
224 CheckerContext &C) const {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000225 // FIXME: A callback should disable checkers at the start of functions.
226 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
Anna Zaks1efcc422012-02-04 02:31:37 +0000227 C.getCurrentAnalysisDeclContext()->getDecl())))
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000228 return;
229
230 checkForInvalidSelf(E->getBase(), C,
Argyrios Kyrtzidisbe29d8d2011-02-01 19:32:55 +0000231 "Instance variable used while 'self' is not set to the result of "
Argyrios Kyrtzidis4717f162011-01-26 01:26:41 +0000232 "'[(super or self) init...]'");
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000233}
234
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000235void ObjCSelfInitChecker::checkPreStmt(const ReturnStmt *S,
236 CheckerContext &C) const {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000237 // FIXME: A callback should disable checkers at the start of functions.
238 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
Anna Zaks1efcc422012-02-04 02:31:37 +0000239 C.getCurrentAnalysisDeclContext()->getDecl())))
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000240 return;
241
242 checkForInvalidSelf(S->getRetValue(), C,
Argyrios Kyrtzidis63eeade2011-02-01 20:33:05 +0000243 "Returning 'self' while it is not set to the result of "
Argyrios Kyrtzidis4717f162011-01-26 01:26:41 +0000244 "'[(super or self) init...]'");
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000245}
246
247// When a call receives a reference to 'self', [Pre/Post]VisitGenericCall pass
248// the SelfFlags from the object 'self' point to before the call, to the new
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000249// object after the call. This is to avoid invalidation of 'self' by logging
250// functions.
251// Another common pattern in classes with multiple initializers is to put the
252// subclass's common initialization bits into a static function that receives
253// the value of 'self', e.g:
254// @code
255// if (!(self = [super init]))
256// return nil;
257// if (!(self = _commonInit(self)))
258// return nil;
259// @endcode
260// Until we can use inter-procedural analysis, in such a call, transfer the
261// SelfFlags to the result of the call.
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000262
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000263void ObjCSelfInitChecker::checkPreStmt(const CallExpr *CE,
264 CheckerContext &C) const {
Jordan Rose55037cd2012-07-02 19:27:46 +0000265 // FIXME: This tree of switching can go away if/when we add a check::postCall.
266 const Expr *Callee = CE->getCallee()->IgnoreParens();
267 ProgramStateRef State = C.getState();
268 const LocationContext *LCtx = C.getLocationContext();
269 SVal L = State->getSVal(Callee, LCtx);
270
271 if (dyn_cast_or_null<BlockDataRegion>(L.getAsRegion())) {
272 BlockCall Call(CE, State, LCtx);
273 checkPreStmt(Call, C);
274 } else if (const CXXMemberCallExpr *me = dyn_cast<CXXMemberCallExpr>(CE)) {
275 CXXMemberCall Call(me, State, LCtx);
276 checkPreStmt(Call, C);
277 } else {
278 FunctionCall Call(CE, State, LCtx);
279 checkPreStmt(Call, C);
280 }
Anna Zaksf420fe32012-03-05 18:58:25 +0000281}
282
283void ObjCSelfInitChecker::checkPostStmt(const CallExpr *CE,
284 CheckerContext &C) const {
Jordan Rose55037cd2012-07-02 19:27:46 +0000285 // FIXME: This tree of switching can go away if/when we add a check::postCall.
286 const Expr *Callee = CE->getCallee()->IgnoreParens();
287 ProgramStateRef State = C.getState();
288 const LocationContext *LCtx = C.getLocationContext();
289 SVal L = State->getSVal(Callee, LCtx);
290
291 if (dyn_cast_or_null<BlockDataRegion>(L.getAsRegion())) {
292 BlockCall Call(CE, State, LCtx);
293 checkPostStmt(Call, C);
294 } else if (const CXXMemberCallExpr *me = dyn_cast<CXXMemberCallExpr>(CE)) {
295 CXXMemberCall Call(me, State, LCtx);
296 checkPostStmt(Call, C);
297 } else {
298 FunctionCall Call(CE, State, LCtx);
299 checkPostStmt(Call, C);
300 }
Anna Zaksf420fe32012-03-05 18:58:25 +0000301}
302
303void ObjCSelfInitChecker::checkPreObjCMessage(ObjCMessage Msg,
304 CheckerContext &C) const {
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000305 // FIXME: ObjCMessage is going away.
306 ObjCMessageSend MsgWrapper(Msg.getMessageExpr(), C.getState(),
307 C.getLocationContext());
Anna Zaksf420fe32012-03-05 18:58:25 +0000308 checkPreStmt(MsgWrapper, C);
309}
310
Jordan Rose55037cd2012-07-02 19:27:46 +0000311void ObjCSelfInitChecker::checkPreStmt(const CallEvent &CE,
Anna Zaksf420fe32012-03-05 18:58:25 +0000312 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000313 ProgramStateRef state = C.getState();
Anna Zaksf420fe32012-03-05 18:58:25 +0000314 unsigned NumArgs = CE.getNumArgs();
Anna Zaks9a70cdd2012-04-16 21:51:09 +0000315 // If we passed 'self' as and argument to the call, record it in the state
316 // to be propagated after the call.
317 // Note, we could have just given up, but try to be more optimistic here and
318 // assume that the functions are going to continue initialization or will not
319 // modify self.
Anna Zaksf420fe32012-03-05 18:58:25 +0000320 for (unsigned i = 0; i < NumArgs; ++i) {
321 SVal argV = CE.getArgSVal(i);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000322 if (isSelfVar(argV, C)) {
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000323 unsigned selfFlags = getSelfFlags(state->getSVal(cast<Loc>(argV)), C);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000324 C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000325 return;
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000326 } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000327 unsigned selfFlags = getSelfFlags(argV, C);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000328 C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000329 return;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000330 }
331 }
332}
333
Jordan Rose55037cd2012-07-02 19:27:46 +0000334void ObjCSelfInitChecker::checkPostStmt(const CallEvent &CE,
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000335 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000336 ProgramStateRef state = C.getState();
Anna Zaksf420fe32012-03-05 18:58:25 +0000337 unsigned NumArgs = CE.getNumArgs();
338 for (unsigned i = 0; i < NumArgs; ++i) {
339 SVal argV = CE.getArgSVal(i);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000340 if (isSelfVar(argV, C)) {
Anna Zaks9a70cdd2012-04-16 21:51:09 +0000341 // If the address of 'self' is being passed to the call, assume that the
342 // 'self' after the call will have the same flags.
343 // EX: log(&self)
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000344 SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>();
345 state = state->remove<PreCallSelfFlags>();
346 addSelfFlag(state, state->getSVal(cast<Loc>(argV)), prevFlags, C);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000347 return;
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000348 } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
Anna Zaks9a70cdd2012-04-16 21:51:09 +0000349 // If 'self' is passed to the call by value, assume that the function
350 // returns 'self'. So assign the flags, which were set on 'self' to the
351 // return value.
352 // EX: self = performMoreInitialization(self)
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000353 SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>();
354 state = state->remove<PreCallSelfFlags>();
Anna Zaks9a70cdd2012-04-16 21:51:09 +0000355 const Expr *CallExpr = CE.getOriginExpr();
356 if (CallExpr)
357 addSelfFlag(state, state->getSVal(CallExpr, C.getLocationContext()),
358 prevFlags, C);
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000359 return;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000360 }
361 }
362}
363
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000364void ObjCSelfInitChecker::checkLocation(SVal location, bool isLoad,
Anna Zaks390909c2011-10-06 00:43:15 +0000365 const Stmt *S,
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000366 CheckerContext &C) const {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000367 // Tag the result of a load from 'self' so that we can easily know that the
368 // value is the object that 'self' points to.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000369 ProgramStateRef state = C.getState();
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000370 if (isSelfVar(location, C))
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000371 addSelfFlag(state, state->getSVal(cast<Loc>(location)), SelfFlag_Self, C);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000372}
373
Anna Zaks6a2a1862012-05-08 21:19:21 +0000374
375void ObjCSelfInitChecker::checkBind(SVal loc, SVal val, const Stmt *S,
376 CheckerContext &C) const {
377 // Allow assignment of anything to self. Self is a local variable in the
378 // initializer, so it is legal to assign anything to it, like results of
379 // static functions/method calls. After self is assigned something we cannot
380 // reason about, stop enforcing the rules.
381 // (Only continue checking if the assigned value should be treated as self.)
382 if ((isSelfVar(loc, C)) &&
383 !hasSelfFlag(val, SelfFlag_InitRes, C) &&
384 !hasSelfFlag(val, SelfFlag_Self, C) &&
385 !isSelfVar(val, C)) {
386
387 // Stop tracking the checker-specific state in the state.
388 ProgramStateRef State = C.getState();
389 State = State->remove<CalledInit>();
390 if (SymbolRef sym = loc.getAsSymbol())
391 State = State->remove<SelfFlag>(sym);
392 C.addTransition(State);
393 }
394}
395
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000396// FIXME: A callback should disable checkers at the start of functions.
397static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND) {
398 if (!ND)
399 return false;
400
401 const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND);
402 if (!MD)
403 return false;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000404 if (!isInitializationMethod(MD))
405 return false;
406
Argyrios Kyrtzidiseaf969b2011-01-25 23:54:44 +0000407 // self = [super init] applies only to NSObject subclasses.
408 // For instance, NSProxy doesn't implement -init.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000409 ASTContext &Ctx = MD->getASTContext();
Argyrios Kyrtzidiseaf969b2011-01-25 23:54:44 +0000410 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
Ted Kremenek9c378f72011-08-12 23:37:29 +0000411 ObjCInterfaceDecl *ID = MD->getClassInterface()->getSuperClass();
Argyrios Kyrtzidiseaf969b2011-01-25 23:54:44 +0000412 for ( ; ID ; ID = ID->getSuperClass()) {
413 IdentifierInfo *II = ID->getIdentifier();
414
415 if (II == NSObjectII)
416 break;
417 }
418 if (!ID)
419 return false;
420
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000421 return true;
422}
423
424/// \brief Returns true if the location is 'self'.
425static bool isSelfVar(SVal location, CheckerContext &C) {
Ted Kremenek1d26f482011-10-24 01:32:45 +0000426 AnalysisDeclContext *analCtx = C.getCurrentAnalysisDeclContext();
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000427 if (!analCtx->getSelfDecl())
428 return false;
429 if (!isa<loc::MemRegionVal>(location))
430 return false;
431
432 loc::MemRegionVal MRV = cast<loc::MemRegionVal>(location);
Anna Zaks9a70cdd2012-04-16 21:51:09 +0000433 if (const DeclRegion *DR = dyn_cast<DeclRegion>(MRV.stripCasts()))
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000434 return (DR->getDecl() == analCtx->getSelfDecl());
435
436 return false;
437}
438
439static bool isInitializationMethod(const ObjCMethodDecl *MD) {
John McCall85f3d762011-03-02 01:50:55 +0000440 return MD->getMethodFamily() == OMF_init;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000441}
442
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +0000443static bool isInitMessage(const ObjCMessage &msg) {
John McCall85f3d762011-03-02 01:50:55 +0000444 return msg.getMethodFamily() == OMF_init;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000445}
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000446
447//===----------------------------------------------------------------------===//
448// Registration.
449//===----------------------------------------------------------------------===//
450
451void ento::registerObjCSelfInitChecker(CheckerManager &mgr) {
452 mgr.registerChecker<ObjCSelfInitChecker>();
453}