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