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