blob: 40eb381999219556c003766fd52e5af445ffe9f6 [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"
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);
Jordan Rosede507ea2012-07-02 19:28:04 +000053static bool isInitMessage(const ObjCMethodCall &Msg);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000054static bool isSelfVar(SVal location, CheckerContext &C);
55
56namespace {
Anna Zaksf420fe32012-03-05 18:58:25 +000057class ObjCSelfInitChecker : public Checker< check::PreObjCMessage,
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>,
Anna Zaks6a2a1862012-05-08 21:19:21 +000063 check::Location,
64 check::Bind > {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000065public:
Jordan Rosede507ea2012-07-02 19:28:04 +000066 void checkPreObjCMessage(const ObjCMethodCall &Msg, CheckerContext &C) const;
67 void checkPostObjCMessage(const ObjCMethodCall &Msg, CheckerContext &C) const;
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +000068 void checkPostStmt(const ObjCIvarRefExpr *E, CheckerContext &C) const;
69 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
70 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
71 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anna Zaks390909c2011-10-06 00:43:15 +000072 void checkLocation(SVal location, bool isLoad, const Stmt *S,
73 CheckerContext &C) const;
Anna Zaks6a2a1862012-05-08 21:19:21 +000074 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Anna Zaksf420fe32012-03-05 18:58:25 +000075
Jordan Rose55037cd2012-07-02 19:27:46 +000076 void checkPreStmt(const CallEvent &CE, CheckerContext &C) const;
77 void checkPostStmt(const CallEvent &CE, CheckerContext &C) const;
Anna Zaksf420fe32012-03-05 18:58:25 +000078
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000079};
80} // end anonymous namespace
81
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000082namespace {
83
84class InitSelfBug : public BugType {
85 const std::string desc;
86public:
Anna Zaks1efcc422012-02-04 02:31:37 +000087 InitSelfBug() : BugType("Missing \"self = [(super or self) init...]\"",
Ted Kremenek6fd45052012-04-05 20:43:28 +000088 categories::CoreFoundationObjectiveC) {}
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +000089};
90
91} // end anonymous namespace
92
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +000093namespace {
94enum SelfFlagEnum {
95 /// \brief No flag set.
96 SelfFlag_None = 0x0,
97 /// \brief Value came from 'self'.
98 SelfFlag_Self = 0x1,
99 /// \brief Value came from the result of an initializer (e.g. [super init]).
100 SelfFlag_InitRes = 0x2
101};
102}
103
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000104typedef llvm::ImmutableMap<SymbolRef, unsigned> SelfFlag;
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000105namespace { struct CalledInit {}; }
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000106namespace { struct PreCallSelfFlags {}; }
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000107
108namespace clang {
109namespace ento {
110 template<>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000111 struct ProgramStateTrait<SelfFlag> : public ProgramStatePartialTrait<SelfFlag> {
Ted Kremenek9c378f72011-08-12 23:37:29 +0000112 static void *GDMIndex() { static int index = 0; return &index; }
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000113 };
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000114 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000115 struct ProgramStateTrait<CalledInit> : public ProgramStatePartialTrait<bool> {
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000116 static void *GDMIndex() { static int index = 0; return &index; }
117 };
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000118
119 /// \brief A call receiving a reference to 'self' invalidates the object that
120 /// 'self' contains. This keeps the "self flags" assigned to the 'self'
121 /// object before the call so we can assign them to the new object that 'self'
122 /// points to after the call.
123 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000124 struct ProgramStateTrait<PreCallSelfFlags> : public ProgramStatePartialTrait<unsigned> {
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000125 static void *GDMIndex() { static int index = 0; return &index; }
126 };
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000127}
128}
129
Ted Kremenek8bef8232012-01-26 21:29:00 +0000130static SelfFlagEnum getSelfFlags(SVal val, ProgramStateRef state) {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000131 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 Kremenek8bef8232012-01-26 21:29:00 +0000141static void addSelfFlag(ProgramStateRef state, SVal val,
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000142 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())
Anna Zaks0bd6b112011-10-26 21:06:34 +0000145 C.addTransition(state->set<SelfFlag>(sym, getSelfFlags(val, C) | flag));
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000146}
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) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000156 SVal exprVal = C.getState()->getSVal(E, C.getLocationContext());
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000157 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
Anna Zakse172e8b2011-08-17 23:00:25 +0000181 BugReport *report =
182 new BugReport(*new InitSelfBug(), errorStr, N);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000183 C.EmitReport(report);
184}
185
Jordan Rosede507ea2012-07-02 19:28:04 +0000186void ObjCSelfInitChecker::checkPostObjCMessage(const ObjCMethodCall &Msg,
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000187 CheckerContext &C) const {
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>(
Anna Zaks1efcc422012-02-04 02:31:37 +0000194 C.getCurrentAnalysisDeclContext()->getDecl())))
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000195 return;
196
Jordan Rosede507ea2012-07-02 19:28:04 +0000197 if (isInitMessage(Msg)) {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000198 // Tag the return value as the result of an initializer.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000199 ProgramStateRef 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
Jordan Rosede507ea2012-07-02 19:28:04 +0000206 SVal V = state->getSVal(Msg.getOriginExpr(), C.getLocationContext());
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
Jordan Rosede507ea2012-07-02 19:28:04 +0000211 checkPostStmt(Msg, C);
Anna Zaks9a70cdd2012-04-16 21:51:09 +0000212
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000213 // We don't check for an invalid 'self' in an obj-c message expression to cut
214 // down false positives where logging functions get information from self
215 // (like its class) or doing "invalidation" on self when the initialization
216 // fails.
217}
218
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000219void ObjCSelfInitChecker::checkPostStmt(const ObjCIvarRefExpr *E,
220 CheckerContext &C) const {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000221 // FIXME: A callback should disable checkers at the start of functions.
222 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
Anna Zaks1efcc422012-02-04 02:31:37 +0000223 C.getCurrentAnalysisDeclContext()->getDecl())))
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000224 return;
225
226 checkForInvalidSelf(E->getBase(), C,
Argyrios Kyrtzidisbe29d8d2011-02-01 19:32:55 +0000227 "Instance variable used while 'self' is not set to the result of "
Argyrios Kyrtzidis4717f162011-01-26 01:26:41 +0000228 "'[(super or self) init...]'");
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000229}
230
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000231void ObjCSelfInitChecker::checkPreStmt(const ReturnStmt *S,
232 CheckerContext &C) const {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000233 // FIXME: A callback should disable checkers at the start of functions.
234 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
Anna Zaks1efcc422012-02-04 02:31:37 +0000235 C.getCurrentAnalysisDeclContext()->getDecl())))
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000236 return;
237
238 checkForInvalidSelf(S->getRetValue(), C,
Argyrios Kyrtzidis63eeade2011-02-01 20:33:05 +0000239 "Returning 'self' while it is not set to the result of "
Argyrios Kyrtzidis4717f162011-01-26 01:26:41 +0000240 "'[(super or self) init...]'");
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000241}
242
243// When a call receives a reference to 'self', [Pre/Post]VisitGenericCall pass
244// the SelfFlags from the object 'self' point to before the call, to the new
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000245// object after the call. This is to avoid invalidation of 'self' by logging
246// functions.
247// Another common pattern in classes with multiple initializers is to put the
248// subclass's common initialization bits into a static function that receives
249// the value of 'self', e.g:
250// @code
251// if (!(self = [super init]))
252// return nil;
253// if (!(self = _commonInit(self)))
254// return nil;
255// @endcode
256// Until we can use inter-procedural analysis, in such a call, transfer the
257// SelfFlags to the result of the call.
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000258
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000259void ObjCSelfInitChecker::checkPreStmt(const CallExpr *CE,
260 CheckerContext &C) const {
Jordan Rose55037cd2012-07-02 19:27:46 +0000261 // FIXME: This tree of switching can go away if/when we add a check::postCall.
262 const Expr *Callee = CE->getCallee()->IgnoreParens();
263 ProgramStateRef State = C.getState();
264 const LocationContext *LCtx = C.getLocationContext();
265 SVal L = State->getSVal(Callee, LCtx);
266
267 if (dyn_cast_or_null<BlockDataRegion>(L.getAsRegion())) {
268 BlockCall Call(CE, State, LCtx);
269 checkPreStmt(Call, C);
270 } else if (const CXXMemberCallExpr *me = dyn_cast<CXXMemberCallExpr>(CE)) {
271 CXXMemberCall Call(me, State, LCtx);
272 checkPreStmt(Call, C);
273 } else {
274 FunctionCall Call(CE, State, LCtx);
275 checkPreStmt(Call, C);
276 }
Anna Zaksf420fe32012-03-05 18:58:25 +0000277}
278
279void ObjCSelfInitChecker::checkPostStmt(const CallExpr *CE,
280 CheckerContext &C) const {
Jordan Rose55037cd2012-07-02 19:27:46 +0000281 // FIXME: This tree of switching can go away if/when we add a check::postCall.
282 const Expr *Callee = CE->getCallee()->IgnoreParens();
283 ProgramStateRef State = C.getState();
284 const LocationContext *LCtx = C.getLocationContext();
285 SVal L = State->getSVal(Callee, LCtx);
286
287 if (dyn_cast_or_null<BlockDataRegion>(L.getAsRegion())) {
288 BlockCall Call(CE, State, LCtx);
289 checkPostStmt(Call, C);
290 } else if (const CXXMemberCallExpr *me = dyn_cast<CXXMemberCallExpr>(CE)) {
291 CXXMemberCall Call(me, State, LCtx);
292 checkPostStmt(Call, C);
293 } else {
294 FunctionCall Call(CE, State, LCtx);
295 checkPostStmt(Call, C);
296 }
Anna Zaksf420fe32012-03-05 18:58:25 +0000297}
298
Jordan Rosede507ea2012-07-02 19:28:04 +0000299void ObjCSelfInitChecker::checkPreObjCMessage(const ObjCMethodCall &Msg,
Anna Zaksf420fe32012-03-05 18:58:25 +0000300 CheckerContext &C) const {
Jordan Rosede507ea2012-07-02 19:28:04 +0000301 checkPreStmt(Msg, C);
Anna Zaksf420fe32012-03-05 18:58:25 +0000302}
303
Jordan Rose55037cd2012-07-02 19:27:46 +0000304void ObjCSelfInitChecker::checkPreStmt(const CallEvent &CE,
Anna Zaksf420fe32012-03-05 18:58:25 +0000305 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000306 ProgramStateRef state = C.getState();
Anna Zaksf420fe32012-03-05 18:58:25 +0000307 unsigned NumArgs = CE.getNumArgs();
Anna Zaks9a70cdd2012-04-16 21:51:09 +0000308 // If we passed 'self' as and argument to the call, record it in the state
309 // to be propagated after the call.
310 // Note, we could have just given up, but try to be more optimistic here and
311 // assume that the functions are going to continue initialization or will not
312 // modify self.
Anna Zaksf420fe32012-03-05 18:58:25 +0000313 for (unsigned i = 0; i < NumArgs; ++i) {
314 SVal argV = CE.getArgSVal(i);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000315 if (isSelfVar(argV, C)) {
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000316 unsigned selfFlags = getSelfFlags(state->getSVal(cast<Loc>(argV)), C);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000317 C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000318 return;
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000319 } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000320 unsigned selfFlags = getSelfFlags(argV, C);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000321 C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000322 return;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000323 }
324 }
325}
326
Jordan Rose55037cd2012-07-02 19:27:46 +0000327void ObjCSelfInitChecker::checkPostStmt(const CallEvent &CE,
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000328 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000329 ProgramStateRef state = C.getState();
Anna Zaksf420fe32012-03-05 18:58:25 +0000330 unsigned NumArgs = CE.getNumArgs();
331 for (unsigned i = 0; i < NumArgs; ++i) {
332 SVal argV = CE.getArgSVal(i);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000333 if (isSelfVar(argV, C)) {
Anna Zaks9a70cdd2012-04-16 21:51:09 +0000334 // If the address of 'self' is being passed to the call, assume that the
335 // 'self' after the call will have the same flags.
336 // EX: log(&self)
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000337 SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>();
338 state = state->remove<PreCallSelfFlags>();
339 addSelfFlag(state, state->getSVal(cast<Loc>(argV)), prevFlags, C);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000340 return;
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000341 } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
Anna Zaks9a70cdd2012-04-16 21:51:09 +0000342 // If 'self' is passed to the call by value, assume that the function
343 // returns 'self'. So assign the flags, which were set on 'self' to the
344 // return value.
345 // EX: self = performMoreInitialization(self)
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000346 SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>();
347 state = state->remove<PreCallSelfFlags>();
Anna Zaks9a70cdd2012-04-16 21:51:09 +0000348 const Expr *CallExpr = CE.getOriginExpr();
349 if (CallExpr)
350 addSelfFlag(state, state->getSVal(CallExpr, C.getLocationContext()),
351 prevFlags, C);
Argyrios Kyrtzidis0ca10402011-02-05 05:54:53 +0000352 return;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000353 }
354 }
355}
356
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000357void ObjCSelfInitChecker::checkLocation(SVal location, bool isLoad,
Anna Zaks390909c2011-10-06 00:43:15 +0000358 const Stmt *S,
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000359 CheckerContext &C) const {
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000360 // Tag the result of a load from 'self' so that we can easily know that the
361 // value is the object that 'self' points to.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000362 ProgramStateRef state = C.getState();
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000363 if (isSelfVar(location, C))
Ted Kremenekb715a7c2011-02-12 03:03:54 +0000364 addSelfFlag(state, state->getSVal(cast<Loc>(location)), SelfFlag_Self, C);
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000365}
366
Anna Zaks6a2a1862012-05-08 21:19:21 +0000367
368void ObjCSelfInitChecker::checkBind(SVal loc, SVal val, const Stmt *S,
369 CheckerContext &C) const {
370 // Allow assignment of anything to self. Self is a local variable in the
371 // initializer, so it is legal to assign anything to it, like results of
372 // static functions/method calls. After self is assigned something we cannot
373 // reason about, stop enforcing the rules.
374 // (Only continue checking if the assigned value should be treated as self.)
375 if ((isSelfVar(loc, C)) &&
376 !hasSelfFlag(val, SelfFlag_InitRes, C) &&
377 !hasSelfFlag(val, SelfFlag_Self, C) &&
378 !isSelfVar(val, C)) {
379
380 // Stop tracking the checker-specific state in the state.
381 ProgramStateRef State = C.getState();
382 State = State->remove<CalledInit>();
383 if (SymbolRef sym = loc.getAsSymbol())
384 State = State->remove<SelfFlag>(sym);
385 C.addTransition(State);
386 }
387}
388
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000389// FIXME: A callback should disable checkers at the start of functions.
390static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND) {
391 if (!ND)
392 return false;
393
394 const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND);
395 if (!MD)
396 return false;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000397 if (!isInitializationMethod(MD))
398 return false;
399
Argyrios Kyrtzidiseaf969b2011-01-25 23:54:44 +0000400 // self = [super init] applies only to NSObject subclasses.
401 // For instance, NSProxy doesn't implement -init.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000402 ASTContext &Ctx = MD->getASTContext();
Argyrios Kyrtzidiseaf969b2011-01-25 23:54:44 +0000403 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
Ted Kremenek9c378f72011-08-12 23:37:29 +0000404 ObjCInterfaceDecl *ID = MD->getClassInterface()->getSuperClass();
Argyrios Kyrtzidiseaf969b2011-01-25 23:54:44 +0000405 for ( ; ID ; ID = ID->getSuperClass()) {
406 IdentifierInfo *II = ID->getIdentifier();
407
408 if (II == NSObjectII)
409 break;
410 }
411 if (!ID)
412 return false;
413
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000414 return true;
415}
416
417/// \brief Returns true if the location is 'self'.
418static bool isSelfVar(SVal location, CheckerContext &C) {
Ted Kremenek1d26f482011-10-24 01:32:45 +0000419 AnalysisDeclContext *analCtx = C.getCurrentAnalysisDeclContext();
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000420 if (!analCtx->getSelfDecl())
421 return false;
422 if (!isa<loc::MemRegionVal>(location))
423 return false;
424
425 loc::MemRegionVal MRV = cast<loc::MemRegionVal>(location);
Anna Zaks9a70cdd2012-04-16 21:51:09 +0000426 if (const DeclRegion *DR = dyn_cast<DeclRegion>(MRV.stripCasts()))
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000427 return (DR->getDecl() == analCtx->getSelfDecl());
428
429 return false;
430}
431
432static bool isInitializationMethod(const ObjCMethodDecl *MD) {
John McCall85f3d762011-03-02 01:50:55 +0000433 return MD->getMethodFamily() == OMF_init;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000434}
435
Jordan Rosede507ea2012-07-02 19:28:04 +0000436static bool isInitMessage(const ObjCMethodCall &Call) {
437 return Call.getMethodFamily() == OMF_init;
Argyrios Kyrtzidisd7a31ba2011-01-11 19:45:25 +0000438}
Argyrios Kyrtzidis769ce3e2011-02-22 17:30:38 +0000439
440//===----------------------------------------------------------------------===//
441// Registration.
442//===----------------------------------------------------------------------===//
443
444void ento::registerObjCSelfInitChecker(CheckerManager &mgr) {
445 mgr.registerChecker<ObjCSelfInitChecker>();
446}