ObjCSelfInitChecker.cpp revision 04291a7c76e16a2dc5433c80c3d13c826bf372dc
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 "InternalChecks.h"
50#include "clang/StaticAnalyzer/PathSensitive/CheckerVisitor.h"
51#include "clang/StaticAnalyzer/PathSensitive/GRStateTrait.h"
52#include "clang/StaticAnalyzer/BugReporter/BugType.h"
53#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
54#include "clang/AST/ParentMap.h"
55
56using namespace clang;
57using namespace ento;
58
59static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND);
60static bool isInitializationMethod(const ObjCMethodDecl *MD);
61static bool isInitMessage(const ObjCMessage &msg);
62static bool isSelfVar(SVal location, CheckerContext &C);
63
64namespace {
65enum 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
75namespace {
76class 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
83public:
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
95void ento::registerObjCSelfInitChecker(ExprEngine &Eng) {
96  if (Eng.getContext().getLangOptions().ObjC1)
97    Eng.registerCheck(new ObjCSelfInitChecker());
98}
99
100namespace {
101
102class InitSelfBug : public BugType {
103  const std::string desc;
104public:
105  InitSelfBug() : BugType("missing \"self = [(super or self) init...]\"",
106                          "missing \"self = [(super or self) init...]\"") {}
107};
108
109} // end anonymous namespace
110
111typedef llvm::ImmutableMap<SymbolRef, unsigned> SelfFlag;
112
113namespace clang {
114namespace ento {
115  template<>
116  struct GRStateTrait<SelfFlag> : public GRStatePartialTrait<SelfFlag> {
117    static void* GDMIndex() {
118      static int index = 0;
119      return &index;
120    }
121  };
122}
123}
124
125static SelfFlagEnum getSelfFlags(SVal val, const GRState *state) {
126  if (SymbolRef sym = val.getAsSymbol())
127    if (const unsigned *attachedFlags = state->get<SelfFlag>(sym))
128      return (SelfFlagEnum)*attachedFlags;
129  return SelfFlag_None;
130}
131
132static SelfFlagEnum getSelfFlags(SVal val, CheckerContext &C) {
133  return getSelfFlags(val, C.getState());
134}
135
136static void addSelfFlag(SVal val, SelfFlagEnum flag, CheckerContext &C) {
137  const GRState *state = C.getState();
138  // We tag the symbol that the SVal wraps.
139  if (SymbolRef sym = val.getAsSymbol())
140    C.addTransition(state->set<SelfFlag>(sym, getSelfFlags(val, C) | flag));
141}
142
143static bool hasSelfFlag(SVal val, SelfFlagEnum flag, CheckerContext &C) {
144  return getSelfFlags(val, C) & flag;
145}
146
147/// \brief Returns true of the value of the expression is the object that 'self'
148/// points to and is an object that did not come from the result of calling
149/// an initializer.
150static bool isInvalidSelf(const Expr *E, CheckerContext &C) {
151  SVal exprVal = C.getState()->getSVal(E);
152  if (!hasSelfFlag(exprVal, SelfFlag_Self, C))
153    return false; // value did not come from 'self'.
154  if (hasSelfFlag(exprVal, SelfFlag_InitRes, C))
155    return false; // 'self' is properly initialized.
156
157  return true;
158}
159
160static void checkForInvalidSelf(const Expr *E, CheckerContext &C,
161                                const char *errorStr) {
162  if (!E)
163    return;
164  if (!isInvalidSelf(E, C))
165    return;
166
167  // Generate an error node.
168  ExplodedNode *N = C.generateSink();
169  if (!N)
170    return;
171
172  EnhancedBugReport *report =
173    new EnhancedBugReport(*new InitSelfBug(), errorStr, N);
174  C.EmitReport(report);
175}
176
177void ObjCSelfInitChecker::postVisitObjCMessage(CheckerContext &C,
178                                               ObjCMessage msg) {
179  // When encountering a message that does initialization (init rule),
180  // tag the return value so that we know later on that if self has this value
181  // then it is properly initialized.
182
183  // FIXME: A callback should disable checkers at the start of functions.
184  if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
185                                     C.getCurrentAnalysisContext()->getDecl())))
186    return;
187
188  if (isInitMessage(msg)) {
189    // Tag the return value as the result of an initializer.
190    const GRState *state = C.getState();
191    SVal V = state->getSVal(msg.getOriginExpr());
192    addSelfFlag(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
202void ObjCSelfInitChecker::PostVisitObjCIvarRefExpr(CheckerContext &C,
203                                                   const ObjCIvarRefExpr *E) {
204  // FIXME: A callback should disable checkers at the start of functions.
205  if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
206                                     C.getCurrentAnalysisContext()->getDecl())))
207    return;
208
209  checkForInvalidSelf(E->getBase(), C,
210    "Instance variable used while 'self' is not set to the result of "
211                                                 "'[(super or self) init...]'");
212}
213
214void ObjCSelfInitChecker::PreVisitReturnStmt(CheckerContext &C,
215                                             const ReturnStmt *S) {
216  // FIXME: A callback should disable checkers at the start of functions.
217  if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
218                                     C.getCurrentAnalysisContext()->getDecl())))
219    return;
220
221  checkForInvalidSelf(S->getRetValue(), C,
222    "Returning 'self' while it is not set to the result of "
223                                                 "'[(super or self) init...]'");
224}
225
226// When a call receives a reference to 'self', [Pre/Post]VisitGenericCall pass
227// the SelfFlags from the object 'self' point to before the call, to the new
228// object after the call. This is to avoid invalidation of 'self' by logging
229// functions.
230// Another common pattern in classes with multiple initializers is to put the
231// subclass's common initialization bits into a static function that receives
232// the value of 'self', e.g:
233// @code
234//   if (!(self = [super init]))
235//     return nil;
236//   if (!(self = _commonInit(self)))
237//     return nil;
238// @endcode
239// Until we can use inter-procedural analysis, in such a call, transfer the
240// SelfFlags to the result of the call.
241
242void ObjCSelfInitChecker::PreVisitGenericCall(CheckerContext &C,
243                                              const CallExpr *CE) {
244  const GRState *state = C.getState();
245  for (CallExpr::const_arg_iterator
246         I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) {
247    SVal argV = state->getSVal(*I);
248    if (isSelfVar(argV, C)) {
249      preCallSelfFlags = getSelfFlags(state->getSVal(cast<Loc>(argV)), C);
250      return;
251    } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
252      preCallSelfFlags = getSelfFlags(argV, C);
253      return;
254    }
255  }
256}
257
258void ObjCSelfInitChecker::PostVisitGenericCall(CheckerContext &C,
259                                               const CallExpr *CE) {
260  const GRState *state = C.getState();
261  for (CallExpr::const_arg_iterator
262         I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) {
263    SVal argV = state->getSVal(*I);
264    if (isSelfVar(argV, C)) {
265      addSelfFlag(state->getSVal(cast<Loc>(argV)), preCallSelfFlags, C);
266      return;
267    } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
268      addSelfFlag(state->getSVal(CE), preCallSelfFlags, C);
269      return;
270    }
271  }
272}
273
274void ObjCSelfInitChecker::visitLocation(CheckerContext &C, const Stmt *S,
275                                        SVal location, bool isLoad) {
276  // Tag the result of a load from 'self' so that we can easily know that the
277  // value is the object that 'self' points to.
278  const GRState *state = C.getState();
279  if (isSelfVar(location, C))
280    addSelfFlag(state->getSVal(cast<Loc>(location)), SelfFlag_Self, C);
281}
282
283// FIXME: A callback should disable checkers at the start of functions.
284static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND) {
285  if (!ND)
286    return false;
287
288  const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND);
289  if (!MD)
290    return false;
291  if (!isInitializationMethod(MD))
292    return false;
293
294  // self = [super init] applies only to NSObject subclasses.
295  // For instance, NSProxy doesn't implement -init.
296  ASTContext& Ctx = MD->getASTContext();
297  IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
298  ObjCInterfaceDecl* ID = MD->getClassInterface()->getSuperClass();
299  for ( ; ID ; ID = ID->getSuperClass()) {
300    IdentifierInfo *II = ID->getIdentifier();
301
302    if (II == NSObjectII)
303      break;
304  }
305  if (!ID)
306    return false;
307
308  return true;
309}
310
311/// \brief Returns true if the location is 'self'.
312static bool isSelfVar(SVal location, CheckerContext &C) {
313  AnalysisContext *analCtx = C.getCurrentAnalysisContext();
314  if (!analCtx->getSelfDecl())
315    return false;
316  if (!isa<loc::MemRegionVal>(location))
317    return false;
318
319  loc::MemRegionVal MRV = cast<loc::MemRegionVal>(location);
320  if (const DeclRegion *DR = dyn_cast<DeclRegion>(MRV.getRegion()))
321    return (DR->getDecl() == analCtx->getSelfDecl());
322
323  return false;
324}
325
326static bool isInitializationMethod(const ObjCMethodDecl *MD) {
327  // Init methods with prefix like '-(id)_init' are private and the requirements
328  // are less strict so we don't check those.
329  return MD->isInstanceMethod() &&
330      cocoa::deriveNamingConvention(MD->getSelector(),
331                                    /*ignorePrefix=*/false) == cocoa::InitRule;
332}
333
334static bool isInitMessage(const ObjCMessage &msg) {
335  return cocoa::deriveNamingConvention(msg.getSelector()) == cocoa::InitRule;
336}
337