xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/ObjCSelfInitChecker.cpp (revision a6d04d541d9fae480b62cdbb0503f67b8d5b1bae)
1 //== 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 //
19 // To perform the required checking, values are tagged wih flags that indicate
20 // 1) if the object is the one pointed to by 'self', and 2) if the object
21 // is the result of an initializer (e.g. [super init]).
22 //
23 // Uses of an object that is true for 1) but not 2) trigger a diagnostic.
24 // The uses that are currently checked are:
25 //  - Using instance variables.
26 //  - Returning the object.
27 //
28 // Note that we don't check for an invalid 'self' that is the receiver of an
29 // obj-c message expression to cut down false positives where logging functions
30 // get information from self (like its class) or doing "invalidation" on self
31 // when the initialization fails.
32 //
33 // Because the object that 'self' points to gets invalidated when a call
34 // receives a reference to 'self', the checker keeps track and passes the flags
35 // for 1) and 2) to the new object that 'self' points to after the call.
36 //
37 // FIXME (rdar://7937506): In the case of:
38 //   [super init];
39 //   return self;
40 // Have an extra PathDiagnosticPiece in the path that says "called [super init],
41 // but didn't assign the result to self."
42 
43 //===----------------------------------------------------------------------===//
44 
45 // FIXME: Somehow stick the link to Apple's documentation about initializing
46 // objects in the diagnostics.
47 // http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocAllocInit.html
48 
49 #include "ClangSACheckers.h"
50 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerVisitor.h"
51 #include "clang/StaticAnalyzer/Core/PathSensitive/GRStateTrait.h"
52 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
53 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
54 #include "clang/AST/ParentMap.h"
55 
56 using namespace clang;
57 using namespace ento;
58 
59 static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND);
60 static bool isInitializationMethod(const ObjCMethodDecl *MD);
61 static bool isInitMessage(const ObjCMessage &msg);
62 static bool isSelfVar(SVal location, CheckerContext &C);
63 
64 namespace {
65 enum SelfFlagEnum {
66   /// \brief No flag set.
67   SelfFlag_None = 0x0,
68   /// \brief Value came from 'self'.
69   SelfFlag_Self    = 0x1,
70   /// \brief Value came from the result of an initializer (e.g. [super init]).
71   SelfFlag_InitRes = 0x2
72 };
73 }
74 
75 namespace {
76 class ObjCSelfInitChecker : public CheckerVisitor<ObjCSelfInitChecker> {
77   /// \brief A call receiving a reference to 'self' invalidates the object that
78   /// 'self' contains. This field keeps the "self flags" assigned to the 'self'
79   /// object before the call and assign them to the new object that 'self'
80   /// points to after the call.
81   SelfFlagEnum preCallSelfFlags;
82 
83 public:
84   static void *getTag() { static int tag = 0; return &tag; }
85   void postVisitObjCMessage(CheckerContext &C, ObjCMessage msg);
86   void PostVisitObjCIvarRefExpr(CheckerContext &C, const ObjCIvarRefExpr *E);
87   void PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S);
88   void PreVisitGenericCall(CheckerContext &C, const CallExpr *CE);
89   void PostVisitGenericCall(CheckerContext &C, const CallExpr *CE);
90   virtual void visitLocation(CheckerContext &C, const Stmt *S, SVal location,
91                              bool isLoad);
92 };
93 } // end anonymous namespace
94 
95 void ento::registerObjCSelfInitChecker(ExprEngine &Eng) {
96   if (Eng.getContext().getLangOptions().ObjC1)
97     Eng.registerCheck(new ObjCSelfInitChecker());
98 }
99 
100 namespace {
101 
102 class InitSelfBug : public BugType {
103   const std::string desc;
104 public:
105   InitSelfBug() : BugType("missing \"self = [(super or self) init...]\"",
106                           "missing \"self = [(super or self) init...]\"") {}
107 };
108 
109 } // end anonymous namespace
110 
111 typedef llvm::ImmutableMap<SymbolRef, unsigned> SelfFlag;
112 namespace { struct CalledInit {}; }
113 
114 namespace clang {
115 namespace ento {
116   template<>
117   struct GRStateTrait<SelfFlag> : public GRStatePartialTrait<SelfFlag> {
118     static void* GDMIndex() {
119       static int index = 0;
120       return &index;
121     }
122   };
123   template <>
124   struct GRStateTrait<CalledInit> : public GRStatePartialTrait<bool> {
125     static void *GDMIndex() { static int index = 0; return &index; }
126   };
127 }
128 }
129 
130 static SelfFlagEnum getSelfFlags(SVal val, const GRState *state) {
131   if (SymbolRef sym = val.getAsSymbol())
132     if (const unsigned *attachedFlags = state->get<SelfFlag>(sym))
133       return (SelfFlagEnum)*attachedFlags;
134   return SelfFlag_None;
135 }
136 
137 static SelfFlagEnum getSelfFlags(SVal val, CheckerContext &C) {
138   return getSelfFlags(val, C.getState());
139 }
140 
141 static void addSelfFlag(const GRState *state, SVal val,
142                         SelfFlagEnum flag, CheckerContext &C) {
143   // We tag the symbol that the SVal wraps.
144   if (SymbolRef sym = val.getAsSymbol())
145     C.addTransition(state->set<SelfFlag>(sym, getSelfFlags(val, C) | flag));
146 }
147 
148 static 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.
155 static bool isInvalidSelf(const Expr *E, CheckerContext &C) {
156   SVal exprVal = C.getState()->getSVal(E);
157   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 
165 static void checkForInvalidSelf(const Expr *E, CheckerContext &C,
166                                 const char *errorStr) {
167   if (!E)
168     return;
169 
170   if (!C.getState()->get<CalledInit>())
171     return;
172 
173   if (!isInvalidSelf(E, C))
174     return;
175 
176   // Generate an error node.
177   ExplodedNode *N = C.generateSink();
178   if (!N)
179     return;
180 
181   EnhancedBugReport *report =
182     new EnhancedBugReport(*new InitSelfBug(), errorStr, N);
183   C.EmitReport(report);
184 }
185 
186 void ObjCSelfInitChecker::postVisitObjCMessage(CheckerContext &C,
187                                                ObjCMessage msg) {
188   // 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>(
194                                      C.getCurrentAnalysisContext()->getDecl())))
195     return;
196 
197   if (isInitMessage(msg)) {
198     // Tag the return value as the result of an initializer.
199     const GRState *state = C.getState();
200 
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 
206     SVal V = state->getSVal(msg.getOriginExpr());
207     addSelfFlag(state, V, SelfFlag_InitRes, C);
208     return;
209   }
210 
211   // We don't check for an invalid 'self' in an obj-c message expression to cut
212   // down false positives where logging functions get information from self
213   // (like its class) or doing "invalidation" on self when the initialization
214   // fails.
215 }
216 
217 void ObjCSelfInitChecker::PostVisitObjCIvarRefExpr(CheckerContext &C,
218                                                    const ObjCIvarRefExpr *E) {
219   // FIXME: A callback should disable checkers at the start of functions.
220   if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
221                                      C.getCurrentAnalysisContext()->getDecl())))
222     return;
223 
224   checkForInvalidSelf(E->getBase(), C,
225     "Instance variable used while 'self' is not set to the result of "
226                                                  "'[(super or self) init...]'");
227 }
228 
229 void ObjCSelfInitChecker::PreVisitReturnStmt(CheckerContext &C,
230                                              const ReturnStmt *S) {
231   // FIXME: A callback should disable checkers at the start of functions.
232   if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
233                                      C.getCurrentAnalysisContext()->getDecl())))
234     return;
235 
236   checkForInvalidSelf(S->getRetValue(), C,
237     "Returning 'self' while it is not set to the result of "
238                                                  "'[(super or self) init...]'");
239 }
240 
241 // When a call receives a reference to 'self', [Pre/Post]VisitGenericCall pass
242 // the SelfFlags from the object 'self' point to before the call, to the new
243 // object after the call. This is to avoid invalidation of 'self' by logging
244 // functions.
245 // Another common pattern in classes with multiple initializers is to put the
246 // subclass's common initialization bits into a static function that receives
247 // the value of 'self', e.g:
248 // @code
249 //   if (!(self = [super init]))
250 //     return nil;
251 //   if (!(self = _commonInit(self)))
252 //     return nil;
253 // @endcode
254 // Until we can use inter-procedural analysis, in such a call, transfer the
255 // SelfFlags to the result of the call.
256 
257 void ObjCSelfInitChecker::PreVisitGenericCall(CheckerContext &C,
258                                               const CallExpr *CE) {
259   const GRState *state = C.getState();
260   for (CallExpr::const_arg_iterator
261          I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) {
262     SVal argV = state->getSVal(*I);
263     if (isSelfVar(argV, C)) {
264       preCallSelfFlags = getSelfFlags(state->getSVal(cast<Loc>(argV)), C);
265       return;
266     } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
267       preCallSelfFlags = getSelfFlags(argV, C);
268       return;
269     }
270   }
271 }
272 
273 void ObjCSelfInitChecker::PostVisitGenericCall(CheckerContext &C,
274                                                const CallExpr *CE) {
275   const GRState *state = C.getState();
276   for (CallExpr::const_arg_iterator
277          I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) {
278     SVal argV = state->getSVal(*I);
279     if (isSelfVar(argV, C)) {
280       addSelfFlag(state, state->getSVal(cast<Loc>(argV)), preCallSelfFlags, C);
281       return;
282     } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
283       addSelfFlag(state, state->getSVal(CE), preCallSelfFlags, C);
284       return;
285     }
286   }
287 }
288 
289 void ObjCSelfInitChecker::visitLocation(CheckerContext &C, const Stmt *S,
290                                         SVal location, bool isLoad) {
291   // Tag the result of a load from 'self' so that we can easily know that the
292   // value is the object that 'self' points to.
293   const GRState *state = C.getState();
294   if (isSelfVar(location, C))
295     addSelfFlag(state, state->getSVal(cast<Loc>(location)), SelfFlag_Self, C);
296 }
297 
298 // FIXME: A callback should disable checkers at the start of functions.
299 static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND) {
300   if (!ND)
301     return false;
302 
303   const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND);
304   if (!MD)
305     return false;
306   if (!isInitializationMethod(MD))
307     return false;
308 
309   // self = [super init] applies only to NSObject subclasses.
310   // For instance, NSProxy doesn't implement -init.
311   ASTContext& Ctx = MD->getASTContext();
312   IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
313   ObjCInterfaceDecl* ID = MD->getClassInterface()->getSuperClass();
314   for ( ; ID ; ID = ID->getSuperClass()) {
315     IdentifierInfo *II = ID->getIdentifier();
316 
317     if (II == NSObjectII)
318       break;
319   }
320   if (!ID)
321     return false;
322 
323   return true;
324 }
325 
326 /// \brief Returns true if the location is 'self'.
327 static bool isSelfVar(SVal location, CheckerContext &C) {
328   AnalysisContext *analCtx = C.getCurrentAnalysisContext();
329   if (!analCtx->getSelfDecl())
330     return false;
331   if (!isa<loc::MemRegionVal>(location))
332     return false;
333 
334   loc::MemRegionVal MRV = cast<loc::MemRegionVal>(location);
335   if (const DeclRegion *DR = dyn_cast<DeclRegion>(MRV.getRegion()))
336     return (DR->getDecl() == analCtx->getSelfDecl());
337 
338   return false;
339 }
340 
341 static bool isInitializationMethod(const ObjCMethodDecl *MD) {
342   // Init methods with prefix like '-(id)_init' are private and the requirements
343   // are less strict so we don't check those.
344   return MD->isInstanceMethod() &&
345       cocoa::deriveNamingConvention(MD->getSelector(),
346                                     /*ignorePrefix=*/false) == cocoa::InitRule;
347 }
348 
349 static bool isInitMessage(const ObjCMessage &msg) {
350   return cocoa::deriveNamingConvention(msg.getSelector()) == cocoa::InitRule;
351 }
352