Coverage Report

Created: 2019-07-24 05:18

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