ObjCSelfInitChecker.cpp revision 55fc873017f10f6f566b182b70f6fc22aefa3464
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
49using namespace clang;
50using namespace ento;
51
52static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND);
53static bool isInitializationMethod(const ObjCMethodDecl *MD);
54static bool isInitMessage(const ObjCMethodCall &Msg);
55static bool isSelfVar(SVal location, CheckerContext &C);
56
57namespace {
58class ObjCSelfInitChecker : public Checker<  check::PostObjCMessage,
59                                             check::PostStmt<ObjCIvarRefExpr>,
60                                             check::PreStmt<ReturnStmt>,
61                                             check::PreCall,
62                                             check::PostCall,
63                                             check::Location,
64                                             check::Bind > {
65public:
66  void checkPostObjCMessage(const ObjCMethodCall &Msg, CheckerContext &C) const;
67  void checkPostStmt(const ObjCIvarRefExpr *E, CheckerContext &C) const;
68  void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
69  void checkLocation(SVal location, bool isLoad, const Stmt *S,
70                     CheckerContext &C) const;
71  void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
72
73  void checkPreCall(const CallEvent &CE, CheckerContext &C) const;
74  void checkPostCall(const CallEvent &CE, CheckerContext &C) const;
75
76  void printState(raw_ostream &Out, ProgramStateRef State,
77                  const char *NL, const char *Sep) const;
78};
79} // end anonymous namespace
80
81namespace {
82
83class InitSelfBug : public BugType {
84  const std::string desc;
85public:
86  InitSelfBug() : BugType("Missing \"self = [(super or self) init...]\"",
87                          categories::CoreFoundationObjectiveC) {}
88};
89
90} // end anonymous namespace
91
92namespace {
93enum SelfFlagEnum {
94  /// \brief No flag set.
95  SelfFlag_None = 0x0,
96  /// \brief Value came from 'self'.
97  SelfFlag_Self    = 0x1,
98  /// \brief Value came from the result of an initializer (e.g. [super init]).
99  SelfFlag_InitRes = 0x2
100};
101}
102
103REGISTER_MAP_WITH_PROGRAMSTATE(SelfFlag, SymbolRef, unsigned)
104REGISTER_TRAIT_WITH_PROGRAMSTATE(CalledInit, bool)
105
106/// \brief A call receiving a reference to 'self' invalidates the object that
107/// 'self' contains. This keeps the "self flags" assigned to the 'self'
108/// object before the call so we can assign them to the new object that 'self'
109/// points to after the call.
110REGISTER_TRAIT_WITH_PROGRAMSTATE(PreCallSelfFlags, unsigned)
111
112static SelfFlagEnum getSelfFlags(SVal val, ProgramStateRef state) {
113  if (SymbolRef sym = val.getAsSymbol())
114    if (const unsigned *attachedFlags = state->get<SelfFlag>(sym))
115      return (SelfFlagEnum)*attachedFlags;
116  return SelfFlag_None;
117}
118
119static SelfFlagEnum getSelfFlags(SVal val, CheckerContext &C) {
120  return getSelfFlags(val, C.getState());
121}
122
123static void addSelfFlag(ProgramStateRef state, SVal val,
124                        SelfFlagEnum flag, CheckerContext &C) {
125  // We tag the symbol that the SVal wraps.
126  if (SymbolRef sym = val.getAsSymbol())
127    state = state->set<SelfFlag>(sym, getSelfFlags(val, state) | flag);
128  C.addTransition(state);
129}
130
131static bool hasSelfFlag(SVal val, SelfFlagEnum flag, CheckerContext &C) {
132  return getSelfFlags(val, C) & flag;
133}
134
135/// \brief Returns true of the value of the expression is the object that 'self'
136/// points to and is an object that did not come from the result of calling
137/// an initializer.
138static bool isInvalidSelf(const Expr *E, CheckerContext &C) {
139  SVal exprVal = C.getState()->getSVal(E, C.getLocationContext());
140  if (!hasSelfFlag(exprVal, SelfFlag_Self, C))
141    return false; // value did not come from 'self'.
142  if (hasSelfFlag(exprVal, SelfFlag_InitRes, C))
143    return false; // 'self' is properly initialized.
144
145  return true;
146}
147
148static void checkForInvalidSelf(const Expr *E, CheckerContext &C,
149                                const char *errorStr) {
150  if (!E)
151    return;
152
153  if (!C.getState()->get<CalledInit>())
154    return;
155
156  if (!isInvalidSelf(E, C))
157    return;
158
159  // Generate an error node.
160  ExplodedNode *N = C.generateSink();
161  if (!N)
162    return;
163
164  BugReport *report =
165    new BugReport(*new InitSelfBug(), errorStr, N);
166  C.emitReport(report);
167}
168
169void ObjCSelfInitChecker::checkPostObjCMessage(const ObjCMethodCall &Msg,
170                                               CheckerContext &C) const {
171  // When encountering a message that does initialization (init rule),
172  // tag the return value so that we know later on that if self has this value
173  // then it is properly initialized.
174
175  // FIXME: A callback should disable checkers at the start of functions.
176  if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
177                                C.getCurrentAnalysisDeclContext()->getDecl())))
178    return;
179
180  if (isInitMessage(Msg)) {
181    // Tag the return value as the result of an initializer.
182    ProgramStateRef state = C.getState();
183
184    // FIXME this really should be context sensitive, where we record
185    // the current stack frame (for IPA).  Also, we need to clean this
186    // value out when we return from this method.
187    state = state->set<CalledInit>(true);
188
189    SVal V = state->getSVal(Msg.getOriginExpr(), C.getLocationContext());
190    addSelfFlag(state, V, SelfFlag_InitRes, C);
191    return;
192  }
193
194  // We don't check for an invalid 'self' in an obj-c message expression to cut
195  // down false positives where logging functions get information from self
196  // (like its class) or doing "invalidation" on self when the initialization
197  // fails.
198}
199
200void ObjCSelfInitChecker::checkPostStmt(const ObjCIvarRefExpr *E,
201                                        CheckerContext &C) const {
202  // FIXME: A callback should disable checkers at the start of functions.
203  if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
204                                 C.getCurrentAnalysisDeclContext()->getDecl())))
205    return;
206
207  checkForInvalidSelf(E->getBase(), C,
208    "Instance variable used while 'self' is not set to the result of "
209                                                 "'[(super or self) init...]'");
210}
211
212void ObjCSelfInitChecker::checkPreStmt(const ReturnStmt *S,
213                                       CheckerContext &C) const {
214  // FIXME: A callback should disable checkers at the start of functions.
215  if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
216                                 C.getCurrentAnalysisDeclContext()->getDecl())))
217    return;
218
219  checkForInvalidSelf(S->getRetValue(), C,
220    "Returning 'self' while it is not set to the result of "
221                                                 "'[(super or self) init...]'");
222}
223
224// When a call receives a reference to 'self', [Pre/Post]Call pass
225// the SelfFlags from the object 'self' points to before the call to the new
226// object after the call. This is to avoid invalidation of 'self' by logging
227// functions.
228// Another common pattern in classes with multiple initializers is to put the
229// subclass's common initialization bits into a static function that receives
230// the value of 'self', e.g:
231// @code
232//   if (!(self = [super init]))
233//     return nil;
234//   if (!(self = _commonInit(self)))
235//     return nil;
236// @endcode
237// Until we can use inter-procedural analysis, in such a call, transfer the
238// SelfFlags to the result of the call.
239
240void ObjCSelfInitChecker::checkPreCall(const CallEvent &CE,
241                                       CheckerContext &C) const {
242  // FIXME: A callback should disable checkers at the start of functions.
243  if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
244                                 C.getCurrentAnalysisDeclContext()->getDecl())))
245    return;
246
247  ProgramStateRef state = C.getState();
248  unsigned NumArgs = CE.getNumArgs();
249  // If we passed 'self' as and argument to the call, record it in the state
250  // to be propagated after the call.
251  // Note, we could have just given up, but try to be more optimistic here and
252  // assume that the functions are going to continue initialization or will not
253  // modify self.
254  for (unsigned i = 0; i < NumArgs; ++i) {
255    SVal argV = CE.getArgSVal(i);
256    if (isSelfVar(argV, C)) {
257      unsigned selfFlags = getSelfFlags(state->getSVal(cast<Loc>(argV)), C);
258      C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
259      return;
260    } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
261      unsigned selfFlags = getSelfFlags(argV, C);
262      C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
263      return;
264    }
265  }
266}
267
268void ObjCSelfInitChecker::checkPostCall(const CallEvent &CE,
269                                        CheckerContext &C) const {
270  // FIXME: A callback should disable checkers at the start of functions.
271  if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
272                                 C.getCurrentAnalysisDeclContext()->getDecl())))
273    return;
274
275  ProgramStateRef state = C.getState();
276  SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>();
277  if (!prevFlags)
278    return;
279  state = state->remove<PreCallSelfFlags>();
280
281  unsigned NumArgs = CE.getNumArgs();
282  for (unsigned i = 0; i < NumArgs; ++i) {
283    SVal argV = CE.getArgSVal(i);
284    if (isSelfVar(argV, C)) {
285      // If the address of 'self' is being passed to the call, assume that the
286      // 'self' after the call will have the same flags.
287      // EX: log(&self)
288      addSelfFlag(state, state->getSVal(cast<Loc>(argV)), prevFlags, C);
289      return;
290    } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
291      // If 'self' is passed to the call by value, assume that the function
292      // returns 'self'. So assign the flags, which were set on 'self' to the
293      // return value.
294      // EX: self = performMoreInitialization(self)
295      addSelfFlag(state, CE.getReturnValue(), prevFlags, C);
296      return;
297    }
298  }
299
300  C.addTransition(state);
301}
302
303void 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
314void 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
335void 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.
383static 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'.
411static 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
425static bool isInitializationMethod(const ObjCMethodDecl *MD) {
426  return MD->getMethodFamily() == OMF_init;
427}
428
429static bool isInitMessage(const ObjCMethodCall &Call) {
430  return Call.getMethodFamily() == OMF_init;
431}
432
433//===----------------------------------------------------------------------===//
434// Registration.
435//===----------------------------------------------------------------------===//
436
437void ento::registerObjCSelfInitChecker(CheckerManager &mgr) {
438  mgr.registerChecker<ObjCSelfInitChecker>();
439}
440