Coverage Report

Created: 2017-10-03 07:32

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