xref: /minix3/external/bsd/llvm/dist/clang/lib/StaticAnalyzer/Checkers/ObjCSelfInitChecker.cpp (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
1f4a2713aSLionel Sambuc //== ObjCSelfInitChecker.cpp - Checker for 'self' initialization -*- C++ -*--=//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc //                     The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // This defines ObjCSelfInitChecker, a builtin check that checks for uses of
11f4a2713aSLionel Sambuc // 'self' before proper initialization.
12f4a2713aSLionel Sambuc //
13f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
14f4a2713aSLionel Sambuc 
15f4a2713aSLionel Sambuc // This checks initialization methods to verify that they assign 'self' to the
16f4a2713aSLionel Sambuc // result of an initialization call (e.g. [super init], or [self initWith..])
17f4a2713aSLionel Sambuc // before using 'self' or any instance variable.
18f4a2713aSLionel Sambuc //
19f4a2713aSLionel Sambuc // To perform the required checking, values are tagged with flags that indicate
20f4a2713aSLionel Sambuc // 1) if the object is the one pointed to by 'self', and 2) if the object
21f4a2713aSLionel Sambuc // is the result of an initializer (e.g. [super init]).
22f4a2713aSLionel Sambuc //
23f4a2713aSLionel Sambuc // Uses of an object that is true for 1) but not 2) trigger a diagnostic.
24f4a2713aSLionel Sambuc // The uses that are currently checked are:
25f4a2713aSLionel Sambuc //  - Using instance variables.
26f4a2713aSLionel Sambuc //  - Returning the object.
27f4a2713aSLionel Sambuc //
28f4a2713aSLionel Sambuc // Note that we don't check for an invalid 'self' that is the receiver of an
29f4a2713aSLionel Sambuc // obj-c message expression to cut down false positives where logging functions
30f4a2713aSLionel Sambuc // get information from self (like its class) or doing "invalidation" on self
31f4a2713aSLionel Sambuc // when the initialization fails.
32f4a2713aSLionel Sambuc //
33f4a2713aSLionel Sambuc // Because the object that 'self' points to gets invalidated when a call
34f4a2713aSLionel Sambuc // receives a reference to 'self', the checker keeps track and passes the flags
35f4a2713aSLionel Sambuc // for 1) and 2) to the new object that 'self' points to after the call.
36f4a2713aSLionel Sambuc //
37f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
38f4a2713aSLionel Sambuc 
39f4a2713aSLionel Sambuc #include "ClangSACheckers.h"
40f4a2713aSLionel Sambuc #include "clang/AST/ParentMap.h"
41f4a2713aSLionel Sambuc #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
42f4a2713aSLionel Sambuc #include "clang/StaticAnalyzer/Core/Checker.h"
43f4a2713aSLionel Sambuc #include "clang/StaticAnalyzer/Core/CheckerManager.h"
44f4a2713aSLionel Sambuc #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
45f4a2713aSLionel Sambuc #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
46f4a2713aSLionel Sambuc #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
47f4a2713aSLionel Sambuc #include "llvm/Support/raw_ostream.h"
48f4a2713aSLionel Sambuc 
49f4a2713aSLionel Sambuc using namespace clang;
50f4a2713aSLionel Sambuc using namespace ento;
51f4a2713aSLionel Sambuc 
52f4a2713aSLionel Sambuc static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND);
53f4a2713aSLionel Sambuc static bool isInitializationMethod(const ObjCMethodDecl *MD);
54f4a2713aSLionel Sambuc static bool isInitMessage(const ObjCMethodCall &Msg);
55f4a2713aSLionel Sambuc static bool isSelfVar(SVal location, CheckerContext &C);
56f4a2713aSLionel Sambuc 
57f4a2713aSLionel Sambuc namespace {
58f4a2713aSLionel Sambuc class ObjCSelfInitChecker : public Checker<  check::PostObjCMessage,
59f4a2713aSLionel Sambuc                                              check::PostStmt<ObjCIvarRefExpr>,
60f4a2713aSLionel Sambuc                                              check::PreStmt<ReturnStmt>,
61f4a2713aSLionel Sambuc                                              check::PreCall,
62f4a2713aSLionel Sambuc                                              check::PostCall,
63f4a2713aSLionel Sambuc                                              check::Location,
64f4a2713aSLionel Sambuc                                              check::Bind > {
65*0a6a1f1dSLionel Sambuc   mutable std::unique_ptr<BugType> BT;
66*0a6a1f1dSLionel Sambuc 
67*0a6a1f1dSLionel Sambuc   void checkForInvalidSelf(const Expr *E, CheckerContext &C,
68*0a6a1f1dSLionel Sambuc                            const char *errorStr) const;
69*0a6a1f1dSLionel Sambuc 
70f4a2713aSLionel Sambuc public:
ObjCSelfInitChecker()71*0a6a1f1dSLionel Sambuc   ObjCSelfInitChecker() {}
72f4a2713aSLionel Sambuc   void checkPostObjCMessage(const ObjCMethodCall &Msg, CheckerContext &C) const;
73f4a2713aSLionel Sambuc   void checkPostStmt(const ObjCIvarRefExpr *E, CheckerContext &C) const;
74f4a2713aSLionel Sambuc   void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
75f4a2713aSLionel Sambuc   void checkLocation(SVal location, bool isLoad, const Stmt *S,
76f4a2713aSLionel Sambuc                      CheckerContext &C) const;
77f4a2713aSLionel Sambuc   void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
78f4a2713aSLionel Sambuc 
79f4a2713aSLionel Sambuc   void checkPreCall(const CallEvent &CE, CheckerContext &C) const;
80f4a2713aSLionel Sambuc   void checkPostCall(const CallEvent &CE, CheckerContext &C) const;
81f4a2713aSLionel Sambuc 
82f4a2713aSLionel Sambuc   void printState(raw_ostream &Out, ProgramStateRef State,
83*0a6a1f1dSLionel Sambuc                   const char *NL, const char *Sep) const override;
84f4a2713aSLionel Sambuc };
85f4a2713aSLionel Sambuc } // end anonymous namespace
86f4a2713aSLionel Sambuc 
87f4a2713aSLionel Sambuc namespace {
88f4a2713aSLionel Sambuc enum SelfFlagEnum {
89f4a2713aSLionel Sambuc   /// \brief No flag set.
90f4a2713aSLionel Sambuc   SelfFlag_None = 0x0,
91f4a2713aSLionel Sambuc   /// \brief Value came from 'self'.
92f4a2713aSLionel Sambuc   SelfFlag_Self    = 0x1,
93f4a2713aSLionel Sambuc   /// \brief Value came from the result of an initializer (e.g. [super init]).
94f4a2713aSLionel Sambuc   SelfFlag_InitRes = 0x2
95f4a2713aSLionel Sambuc };
96f4a2713aSLionel Sambuc }
97f4a2713aSLionel Sambuc 
REGISTER_MAP_WITH_PROGRAMSTATE(SelfFlag,SymbolRef,unsigned)98f4a2713aSLionel Sambuc REGISTER_MAP_WITH_PROGRAMSTATE(SelfFlag, SymbolRef, unsigned)
99f4a2713aSLionel Sambuc REGISTER_TRAIT_WITH_PROGRAMSTATE(CalledInit, bool)
100f4a2713aSLionel Sambuc 
101f4a2713aSLionel Sambuc /// \brief A call receiving a reference to 'self' invalidates the object that
102f4a2713aSLionel Sambuc /// 'self' contains. This keeps the "self flags" assigned to the 'self'
103f4a2713aSLionel Sambuc /// object before the call so we can assign them to the new object that 'self'
104f4a2713aSLionel Sambuc /// points to after the call.
105f4a2713aSLionel Sambuc REGISTER_TRAIT_WITH_PROGRAMSTATE(PreCallSelfFlags, unsigned)
106f4a2713aSLionel Sambuc 
107f4a2713aSLionel Sambuc static SelfFlagEnum getSelfFlags(SVal val, ProgramStateRef state) {
108f4a2713aSLionel Sambuc   if (SymbolRef sym = val.getAsSymbol())
109f4a2713aSLionel Sambuc     if (const unsigned *attachedFlags = state->get<SelfFlag>(sym))
110f4a2713aSLionel Sambuc       return (SelfFlagEnum)*attachedFlags;
111f4a2713aSLionel Sambuc   return SelfFlag_None;
112f4a2713aSLionel Sambuc }
113f4a2713aSLionel Sambuc 
getSelfFlags(SVal val,CheckerContext & C)114f4a2713aSLionel Sambuc static SelfFlagEnum getSelfFlags(SVal val, CheckerContext &C) {
115f4a2713aSLionel Sambuc   return getSelfFlags(val, C.getState());
116f4a2713aSLionel Sambuc }
117f4a2713aSLionel Sambuc 
addSelfFlag(ProgramStateRef state,SVal val,SelfFlagEnum flag,CheckerContext & C)118f4a2713aSLionel Sambuc static void addSelfFlag(ProgramStateRef state, SVal val,
119f4a2713aSLionel Sambuc                         SelfFlagEnum flag, CheckerContext &C) {
120f4a2713aSLionel Sambuc   // We tag the symbol that the SVal wraps.
121f4a2713aSLionel Sambuc   if (SymbolRef sym = val.getAsSymbol()) {
122f4a2713aSLionel Sambuc     state = state->set<SelfFlag>(sym, getSelfFlags(val, state) | flag);
123f4a2713aSLionel Sambuc     C.addTransition(state);
124f4a2713aSLionel Sambuc   }
125f4a2713aSLionel Sambuc }
126f4a2713aSLionel Sambuc 
hasSelfFlag(SVal val,SelfFlagEnum flag,CheckerContext & C)127f4a2713aSLionel Sambuc static bool hasSelfFlag(SVal val, SelfFlagEnum flag, CheckerContext &C) {
128f4a2713aSLionel Sambuc   return getSelfFlags(val, C) & flag;
129f4a2713aSLionel Sambuc }
130f4a2713aSLionel Sambuc 
131f4a2713aSLionel Sambuc /// \brief Returns true of the value of the expression is the object that 'self'
132f4a2713aSLionel Sambuc /// points to and is an object that did not come from the result of calling
133f4a2713aSLionel Sambuc /// an initializer.
isInvalidSelf(const Expr * E,CheckerContext & C)134f4a2713aSLionel Sambuc static bool isInvalidSelf(const Expr *E, CheckerContext &C) {
135f4a2713aSLionel Sambuc   SVal exprVal = C.getState()->getSVal(E, C.getLocationContext());
136f4a2713aSLionel Sambuc   if (!hasSelfFlag(exprVal, SelfFlag_Self, C))
137f4a2713aSLionel Sambuc     return false; // value did not come from 'self'.
138f4a2713aSLionel Sambuc   if (hasSelfFlag(exprVal, SelfFlag_InitRes, C))
139f4a2713aSLionel Sambuc     return false; // 'self' is properly initialized.
140f4a2713aSLionel Sambuc 
141f4a2713aSLionel Sambuc   return true;
142f4a2713aSLionel Sambuc }
143f4a2713aSLionel Sambuc 
checkForInvalidSelf(const Expr * E,CheckerContext & C,const char * errorStr) const144*0a6a1f1dSLionel Sambuc void ObjCSelfInitChecker::checkForInvalidSelf(const Expr *E, CheckerContext &C,
145*0a6a1f1dSLionel Sambuc                                               const char *errorStr) const {
146f4a2713aSLionel Sambuc   if (!E)
147f4a2713aSLionel Sambuc     return;
148f4a2713aSLionel Sambuc 
149f4a2713aSLionel Sambuc   if (!C.getState()->get<CalledInit>())
150f4a2713aSLionel Sambuc     return;
151f4a2713aSLionel Sambuc 
152f4a2713aSLionel Sambuc   if (!isInvalidSelf(E, C))
153f4a2713aSLionel Sambuc     return;
154f4a2713aSLionel Sambuc 
155f4a2713aSLionel Sambuc   // Generate an error node.
156f4a2713aSLionel Sambuc   ExplodedNode *N = C.generateSink();
157f4a2713aSLionel Sambuc   if (!N)
158f4a2713aSLionel Sambuc     return;
159f4a2713aSLionel Sambuc 
160*0a6a1f1dSLionel Sambuc   if (!BT)
161*0a6a1f1dSLionel Sambuc     BT.reset(new BugType(this, "Missing \"self = [(super or self) init...]\"",
162*0a6a1f1dSLionel Sambuc                          categories::CoreFoundationObjectiveC));
163*0a6a1f1dSLionel Sambuc   BugReport *report = new BugReport(*BT, errorStr, N);
164f4a2713aSLionel Sambuc   C.emitReport(report);
165f4a2713aSLionel Sambuc }
166f4a2713aSLionel Sambuc 
checkPostObjCMessage(const ObjCMethodCall & Msg,CheckerContext & C) const167f4a2713aSLionel Sambuc void ObjCSelfInitChecker::checkPostObjCMessage(const ObjCMethodCall &Msg,
168f4a2713aSLionel Sambuc                                                CheckerContext &C) const {
169f4a2713aSLionel Sambuc   // When encountering a message that does initialization (init rule),
170f4a2713aSLionel Sambuc   // tag the return value so that we know later on that if self has this value
171f4a2713aSLionel Sambuc   // then it is properly initialized.
172f4a2713aSLionel Sambuc 
173f4a2713aSLionel Sambuc   // FIXME: A callback should disable checkers at the start of functions.
174f4a2713aSLionel Sambuc   if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
175f4a2713aSLionel Sambuc                                 C.getCurrentAnalysisDeclContext()->getDecl())))
176f4a2713aSLionel Sambuc     return;
177f4a2713aSLionel Sambuc 
178f4a2713aSLionel Sambuc   if (isInitMessage(Msg)) {
179f4a2713aSLionel Sambuc     // Tag the return value as the result of an initializer.
180f4a2713aSLionel Sambuc     ProgramStateRef state = C.getState();
181f4a2713aSLionel Sambuc 
182f4a2713aSLionel Sambuc     // FIXME this really should be context sensitive, where we record
183f4a2713aSLionel Sambuc     // the current stack frame (for IPA).  Also, we need to clean this
184f4a2713aSLionel Sambuc     // value out when we return from this method.
185f4a2713aSLionel Sambuc     state = state->set<CalledInit>(true);
186f4a2713aSLionel Sambuc 
187f4a2713aSLionel Sambuc     SVal V = state->getSVal(Msg.getOriginExpr(), C.getLocationContext());
188f4a2713aSLionel Sambuc     addSelfFlag(state, V, SelfFlag_InitRes, C);
189f4a2713aSLionel Sambuc     return;
190f4a2713aSLionel Sambuc   }
191f4a2713aSLionel Sambuc 
192f4a2713aSLionel Sambuc   // We don't check for an invalid 'self' in an obj-c message expression to cut
193f4a2713aSLionel Sambuc   // down false positives where logging functions get information from self
194f4a2713aSLionel Sambuc   // (like its class) or doing "invalidation" on self when the initialization
195f4a2713aSLionel Sambuc   // fails.
196f4a2713aSLionel Sambuc }
197f4a2713aSLionel Sambuc 
checkPostStmt(const ObjCIvarRefExpr * E,CheckerContext & C) const198f4a2713aSLionel Sambuc void ObjCSelfInitChecker::checkPostStmt(const ObjCIvarRefExpr *E,
199f4a2713aSLionel Sambuc                                         CheckerContext &C) const {
200f4a2713aSLionel Sambuc   // FIXME: A callback should disable checkers at the start of functions.
201f4a2713aSLionel Sambuc   if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
202f4a2713aSLionel Sambuc                                  C.getCurrentAnalysisDeclContext()->getDecl())))
203f4a2713aSLionel Sambuc     return;
204f4a2713aSLionel Sambuc 
205*0a6a1f1dSLionel Sambuc   checkForInvalidSelf(
206*0a6a1f1dSLionel Sambuc       E->getBase(), C,
207f4a2713aSLionel Sambuc       "Instance variable used while 'self' is not set to the result of "
208f4a2713aSLionel Sambuc       "'[(super or self) init...]'");
209f4a2713aSLionel Sambuc }
210f4a2713aSLionel Sambuc 
checkPreStmt(const ReturnStmt * S,CheckerContext & C) const211f4a2713aSLionel Sambuc void ObjCSelfInitChecker::checkPreStmt(const ReturnStmt *S,
212f4a2713aSLionel Sambuc                                        CheckerContext &C) const {
213f4a2713aSLionel Sambuc   // FIXME: A callback should disable checkers at the start of functions.
214f4a2713aSLionel Sambuc   if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
215f4a2713aSLionel Sambuc                                  C.getCurrentAnalysisDeclContext()->getDecl())))
216f4a2713aSLionel Sambuc     return;
217f4a2713aSLionel Sambuc 
218f4a2713aSLionel Sambuc   checkForInvalidSelf(S->getRetValue(), C,
219f4a2713aSLionel Sambuc                       "Returning 'self' while it is not set to the result of "
220f4a2713aSLionel Sambuc                       "'[(super or self) init...]'");
221f4a2713aSLionel Sambuc }
222f4a2713aSLionel Sambuc 
223f4a2713aSLionel Sambuc // When a call receives a reference to 'self', [Pre/Post]Call pass
224f4a2713aSLionel Sambuc // the SelfFlags from the object 'self' points to before the call to the new
225f4a2713aSLionel Sambuc // object after the call. This is to avoid invalidation of 'self' by logging
226f4a2713aSLionel Sambuc // functions.
227f4a2713aSLionel Sambuc // Another common pattern in classes with multiple initializers is to put the
228f4a2713aSLionel Sambuc // subclass's common initialization bits into a static function that receives
229f4a2713aSLionel Sambuc // the value of 'self', e.g:
230f4a2713aSLionel Sambuc // @code
231f4a2713aSLionel Sambuc //   if (!(self = [super init]))
232f4a2713aSLionel Sambuc //     return nil;
233f4a2713aSLionel Sambuc //   if (!(self = _commonInit(self)))
234f4a2713aSLionel Sambuc //     return nil;
235f4a2713aSLionel Sambuc // @endcode
236f4a2713aSLionel Sambuc // Until we can use inter-procedural analysis, in such a call, transfer the
237f4a2713aSLionel Sambuc // SelfFlags to the result of the call.
238f4a2713aSLionel Sambuc 
checkPreCall(const CallEvent & CE,CheckerContext & C) const239f4a2713aSLionel Sambuc void ObjCSelfInitChecker::checkPreCall(const CallEvent &CE,
240f4a2713aSLionel Sambuc                                        CheckerContext &C) const {
241f4a2713aSLionel Sambuc   // FIXME: A callback should disable checkers at the start of functions.
242f4a2713aSLionel Sambuc   if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
243f4a2713aSLionel Sambuc                                  C.getCurrentAnalysisDeclContext()->getDecl())))
244f4a2713aSLionel Sambuc     return;
245f4a2713aSLionel Sambuc 
246f4a2713aSLionel Sambuc   ProgramStateRef state = C.getState();
247f4a2713aSLionel Sambuc   unsigned NumArgs = CE.getNumArgs();
248f4a2713aSLionel Sambuc   // If we passed 'self' as and argument to the call, record it in the state
249f4a2713aSLionel Sambuc   // to be propagated after the call.
250f4a2713aSLionel Sambuc   // Note, we could have just given up, but try to be more optimistic here and
251f4a2713aSLionel Sambuc   // assume that the functions are going to continue initialization or will not
252f4a2713aSLionel Sambuc   // modify self.
253f4a2713aSLionel Sambuc   for (unsigned i = 0; i < NumArgs; ++i) {
254f4a2713aSLionel Sambuc     SVal argV = CE.getArgSVal(i);
255f4a2713aSLionel Sambuc     if (isSelfVar(argV, C)) {
256f4a2713aSLionel Sambuc       unsigned selfFlags = getSelfFlags(state->getSVal(argV.castAs<Loc>()), C);
257f4a2713aSLionel Sambuc       C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
258f4a2713aSLionel Sambuc       return;
259f4a2713aSLionel Sambuc     } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
260f4a2713aSLionel Sambuc       unsigned selfFlags = getSelfFlags(argV, C);
261f4a2713aSLionel Sambuc       C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
262f4a2713aSLionel Sambuc       return;
263f4a2713aSLionel Sambuc     }
264f4a2713aSLionel Sambuc   }
265f4a2713aSLionel Sambuc }
266f4a2713aSLionel Sambuc 
checkPostCall(const CallEvent & CE,CheckerContext & C) const267f4a2713aSLionel Sambuc void ObjCSelfInitChecker::checkPostCall(const CallEvent &CE,
268f4a2713aSLionel Sambuc                                         CheckerContext &C) const {
269f4a2713aSLionel Sambuc   // FIXME: A callback should disable checkers at the start of functions.
270f4a2713aSLionel Sambuc   if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
271f4a2713aSLionel Sambuc                                  C.getCurrentAnalysisDeclContext()->getDecl())))
272f4a2713aSLionel Sambuc     return;
273f4a2713aSLionel Sambuc 
274f4a2713aSLionel Sambuc   ProgramStateRef state = C.getState();
275f4a2713aSLionel Sambuc   SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>();
276f4a2713aSLionel Sambuc   if (!prevFlags)
277f4a2713aSLionel Sambuc     return;
278f4a2713aSLionel Sambuc   state = state->remove<PreCallSelfFlags>();
279f4a2713aSLionel Sambuc 
280f4a2713aSLionel Sambuc   unsigned NumArgs = CE.getNumArgs();
281f4a2713aSLionel Sambuc   for (unsigned i = 0; i < NumArgs; ++i) {
282f4a2713aSLionel Sambuc     SVal argV = CE.getArgSVal(i);
283f4a2713aSLionel Sambuc     if (isSelfVar(argV, C)) {
284f4a2713aSLionel Sambuc       // If the address of 'self' is being passed to the call, assume that the
285f4a2713aSLionel Sambuc       // 'self' after the call will have the same flags.
286f4a2713aSLionel Sambuc       // EX: log(&self)
287f4a2713aSLionel Sambuc       addSelfFlag(state, state->getSVal(argV.castAs<Loc>()), prevFlags, C);
288f4a2713aSLionel Sambuc       return;
289f4a2713aSLionel Sambuc     } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
290f4a2713aSLionel Sambuc       // If 'self' is passed to the call by value, assume that the function
291f4a2713aSLionel Sambuc       // returns 'self'. So assign the flags, which were set on 'self' to the
292f4a2713aSLionel Sambuc       // return value.
293f4a2713aSLionel Sambuc       // EX: self = performMoreInitialization(self)
294f4a2713aSLionel Sambuc       addSelfFlag(state, CE.getReturnValue(), prevFlags, C);
295f4a2713aSLionel Sambuc       return;
296f4a2713aSLionel Sambuc     }
297f4a2713aSLionel Sambuc   }
298f4a2713aSLionel Sambuc 
299f4a2713aSLionel Sambuc   C.addTransition(state);
300f4a2713aSLionel Sambuc }
301f4a2713aSLionel Sambuc 
checkLocation(SVal location,bool isLoad,const Stmt * S,CheckerContext & C) const302f4a2713aSLionel Sambuc void ObjCSelfInitChecker::checkLocation(SVal location, bool isLoad,
303f4a2713aSLionel Sambuc                                         const Stmt *S,
304f4a2713aSLionel Sambuc                                         CheckerContext &C) const {
305f4a2713aSLionel Sambuc   if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
306f4a2713aSLionel Sambuc         C.getCurrentAnalysisDeclContext()->getDecl())))
307f4a2713aSLionel Sambuc     return;
308f4a2713aSLionel Sambuc 
309f4a2713aSLionel Sambuc   // Tag the result of a load from 'self' so that we can easily know that the
310f4a2713aSLionel Sambuc   // value is the object that 'self' points to.
311f4a2713aSLionel Sambuc   ProgramStateRef state = C.getState();
312f4a2713aSLionel Sambuc   if (isSelfVar(location, C))
313f4a2713aSLionel Sambuc     addSelfFlag(state, state->getSVal(location.castAs<Loc>()), SelfFlag_Self,
314f4a2713aSLionel Sambuc                 C);
315f4a2713aSLionel Sambuc }
316f4a2713aSLionel Sambuc 
317f4a2713aSLionel Sambuc 
checkBind(SVal loc,SVal val,const Stmt * S,CheckerContext & C) const318f4a2713aSLionel Sambuc void ObjCSelfInitChecker::checkBind(SVal loc, SVal val, const Stmt *S,
319f4a2713aSLionel Sambuc                                     CheckerContext &C) const {
320f4a2713aSLionel Sambuc   // Allow assignment of anything to self. Self is a local variable in the
321f4a2713aSLionel Sambuc   // initializer, so it is legal to assign anything to it, like results of
322f4a2713aSLionel Sambuc   // static functions/method calls. After self is assigned something we cannot
323f4a2713aSLionel Sambuc   // reason about, stop enforcing the rules.
324f4a2713aSLionel Sambuc   // (Only continue checking if the assigned value should be treated as self.)
325f4a2713aSLionel Sambuc   if ((isSelfVar(loc, C)) &&
326f4a2713aSLionel Sambuc       !hasSelfFlag(val, SelfFlag_InitRes, C) &&
327f4a2713aSLionel Sambuc       !hasSelfFlag(val, SelfFlag_Self, C) &&
328f4a2713aSLionel Sambuc       !isSelfVar(val, C)) {
329f4a2713aSLionel Sambuc 
330f4a2713aSLionel Sambuc     // Stop tracking the checker-specific state in the state.
331f4a2713aSLionel Sambuc     ProgramStateRef State = C.getState();
332f4a2713aSLionel Sambuc     State = State->remove<CalledInit>();
333f4a2713aSLionel Sambuc     if (SymbolRef sym = loc.getAsSymbol())
334f4a2713aSLionel Sambuc       State = State->remove<SelfFlag>(sym);
335f4a2713aSLionel Sambuc     C.addTransition(State);
336f4a2713aSLionel Sambuc   }
337f4a2713aSLionel Sambuc }
338f4a2713aSLionel Sambuc 
printState(raw_ostream & Out,ProgramStateRef State,const char * NL,const char * Sep) const339f4a2713aSLionel Sambuc void ObjCSelfInitChecker::printState(raw_ostream &Out, ProgramStateRef State,
340f4a2713aSLionel Sambuc                                      const char *NL, const char *Sep) const {
341f4a2713aSLionel Sambuc   SelfFlagTy FlagMap = State->get<SelfFlag>();
342f4a2713aSLionel Sambuc   bool DidCallInit = State->get<CalledInit>();
343f4a2713aSLionel Sambuc   SelfFlagEnum PreCallFlags = (SelfFlagEnum)State->get<PreCallSelfFlags>();
344f4a2713aSLionel Sambuc 
345f4a2713aSLionel Sambuc   if (FlagMap.isEmpty() && !DidCallInit && !PreCallFlags)
346f4a2713aSLionel Sambuc     return;
347f4a2713aSLionel Sambuc 
348*0a6a1f1dSLionel Sambuc   Out << Sep << NL << *this << " :" << NL;
349f4a2713aSLionel Sambuc 
350f4a2713aSLionel Sambuc   if (DidCallInit)
351f4a2713aSLionel Sambuc     Out << "  An init method has been called." << NL;
352f4a2713aSLionel Sambuc 
353f4a2713aSLionel Sambuc   if (PreCallFlags != SelfFlag_None) {
354f4a2713aSLionel Sambuc     if (PreCallFlags & SelfFlag_Self) {
355f4a2713aSLionel Sambuc       Out << "  An argument of the current call came from the 'self' variable."
356f4a2713aSLionel Sambuc           << NL;
357f4a2713aSLionel Sambuc     }
358f4a2713aSLionel Sambuc     if (PreCallFlags & SelfFlag_InitRes) {
359f4a2713aSLionel Sambuc       Out << "  An argument of the current call came from an init method."
360f4a2713aSLionel Sambuc           << NL;
361f4a2713aSLionel Sambuc     }
362f4a2713aSLionel Sambuc   }
363f4a2713aSLionel Sambuc 
364f4a2713aSLionel Sambuc   Out << NL;
365f4a2713aSLionel Sambuc   for (SelfFlagTy::iterator I = FlagMap.begin(), E = FlagMap.end();
366f4a2713aSLionel Sambuc        I != E; ++I) {
367f4a2713aSLionel Sambuc     Out << I->first << " : ";
368f4a2713aSLionel Sambuc 
369f4a2713aSLionel Sambuc     if (I->second == SelfFlag_None)
370f4a2713aSLionel Sambuc       Out << "none";
371f4a2713aSLionel Sambuc 
372f4a2713aSLionel Sambuc     if (I->second & SelfFlag_Self)
373f4a2713aSLionel Sambuc       Out << "self variable";
374f4a2713aSLionel Sambuc 
375f4a2713aSLionel Sambuc     if (I->second & SelfFlag_InitRes) {
376f4a2713aSLionel Sambuc       if (I->second != SelfFlag_InitRes)
377f4a2713aSLionel Sambuc         Out << " | ";
378f4a2713aSLionel Sambuc       Out << "result of init method";
379f4a2713aSLionel Sambuc     }
380f4a2713aSLionel Sambuc 
381f4a2713aSLionel Sambuc     Out << NL;
382f4a2713aSLionel Sambuc   }
383f4a2713aSLionel Sambuc }
384f4a2713aSLionel Sambuc 
385f4a2713aSLionel Sambuc 
386f4a2713aSLionel Sambuc // FIXME: A callback should disable checkers at the start of functions.
shouldRunOnFunctionOrMethod(const NamedDecl * ND)387f4a2713aSLionel Sambuc static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND) {
388f4a2713aSLionel Sambuc   if (!ND)
389f4a2713aSLionel Sambuc     return false;
390f4a2713aSLionel Sambuc 
391f4a2713aSLionel Sambuc   const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND);
392f4a2713aSLionel Sambuc   if (!MD)
393f4a2713aSLionel Sambuc     return false;
394f4a2713aSLionel Sambuc   if (!isInitializationMethod(MD))
395f4a2713aSLionel Sambuc     return false;
396f4a2713aSLionel Sambuc 
397f4a2713aSLionel Sambuc   // self = [super init] applies only to NSObject subclasses.
398f4a2713aSLionel Sambuc   // For instance, NSProxy doesn't implement -init.
399f4a2713aSLionel Sambuc   ASTContext &Ctx = MD->getASTContext();
400f4a2713aSLionel Sambuc   IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
401f4a2713aSLionel Sambuc   ObjCInterfaceDecl *ID = MD->getClassInterface()->getSuperClass();
402f4a2713aSLionel Sambuc   for ( ; ID ; ID = ID->getSuperClass()) {
403f4a2713aSLionel Sambuc     IdentifierInfo *II = ID->getIdentifier();
404f4a2713aSLionel Sambuc 
405f4a2713aSLionel Sambuc     if (II == NSObjectII)
406f4a2713aSLionel Sambuc       break;
407f4a2713aSLionel Sambuc   }
408f4a2713aSLionel Sambuc   if (!ID)
409f4a2713aSLionel Sambuc     return false;
410f4a2713aSLionel Sambuc 
411f4a2713aSLionel Sambuc   return true;
412f4a2713aSLionel Sambuc }
413f4a2713aSLionel Sambuc 
414f4a2713aSLionel Sambuc /// \brief Returns true if the location is 'self'.
isSelfVar(SVal location,CheckerContext & C)415f4a2713aSLionel Sambuc static bool isSelfVar(SVal location, CheckerContext &C) {
416f4a2713aSLionel Sambuc   AnalysisDeclContext *analCtx = C.getCurrentAnalysisDeclContext();
417f4a2713aSLionel Sambuc   if (!analCtx->getSelfDecl())
418f4a2713aSLionel Sambuc     return false;
419f4a2713aSLionel Sambuc   if (!location.getAs<loc::MemRegionVal>())
420f4a2713aSLionel Sambuc     return false;
421f4a2713aSLionel Sambuc 
422f4a2713aSLionel Sambuc   loc::MemRegionVal MRV = location.castAs<loc::MemRegionVal>();
423f4a2713aSLionel Sambuc   if (const DeclRegion *DR = dyn_cast<DeclRegion>(MRV.stripCasts()))
424f4a2713aSLionel Sambuc     return (DR->getDecl() == analCtx->getSelfDecl());
425f4a2713aSLionel Sambuc 
426f4a2713aSLionel Sambuc   return false;
427f4a2713aSLionel Sambuc }
428f4a2713aSLionel Sambuc 
isInitializationMethod(const ObjCMethodDecl * MD)429f4a2713aSLionel Sambuc static bool isInitializationMethod(const ObjCMethodDecl *MD) {
430f4a2713aSLionel Sambuc   return MD->getMethodFamily() == OMF_init;
431f4a2713aSLionel Sambuc }
432f4a2713aSLionel Sambuc 
isInitMessage(const ObjCMethodCall & Call)433f4a2713aSLionel Sambuc static bool isInitMessage(const ObjCMethodCall &Call) {
434f4a2713aSLionel Sambuc   return Call.getMethodFamily() == OMF_init;
435f4a2713aSLionel Sambuc }
436f4a2713aSLionel Sambuc 
437f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
438f4a2713aSLionel Sambuc // Registration.
439f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
440f4a2713aSLionel Sambuc 
registerObjCSelfInitChecker(CheckerManager & mgr)441f4a2713aSLionel Sambuc void ento::registerObjCSelfInitChecker(CheckerManager &mgr) {
442f4a2713aSLionel Sambuc   mgr.registerChecker<ObjCSelfInitChecker>();
443f4a2713aSLionel Sambuc }
444