Coverage Report

Created: 2021-04-13 08:44

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
Line
Count
Source (jump to first uncovered line)
1
//==-- RetainCountChecker.cpp - Checks for leaks and other issues -*- 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 file defines the methods for RetainCountChecker, which implements
10
//  a reference count checker for Core Foundation and Cocoa on (Mac OS X).
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "RetainCountChecker.h"
15
#include "clang/StaticAnalyzer/Core/Checker.h"
16
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
17
18
using namespace clang;
19
using namespace ento;
20
using namespace retaincountchecker;
21
22
REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
23
24
namespace clang {
25
namespace ento {
26
namespace retaincountchecker {
27
28
58.6k
const RefVal *getRefBinding(ProgramStateRef State, SymbolRef Sym) {
29
58.6k
  return State->get<RefBindings>(Sym);
30
58.6k
}
31
32
} // end namespace retaincountchecker
33
} // end namespace ento
34
} // end namespace clang
35
36
static ProgramStateRef setRefBinding(ProgramStateRef State, SymbolRef Sym,
37
4.13k
                                     RefVal Val) {
38
4.13k
  assert(Sym != nullptr);
39
0
  return State->set<RefBindings>(Sym, Val);
40
4.13k
}
41
42
6.18k
static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
43
6.18k
  return State->remove<RefBindings>(Sym);
44
6.18k
}
45
46
0
void RefVal::print(raw_ostream &Out) const {
47
0
  if (!T.isNull())
48
0
    Out << "Tracked " << T.getAsString() << " | ";
49
50
0
  switch (getKind()) {
51
0
    default: llvm_unreachable("Invalid RefVal kind");
52
0
    case Owned: {
53
0
      Out << "Owned";
54
0
      unsigned cnt = getCount();
55
0
      if (cnt) Out << " (+ " << cnt << ")";
56
0
      break;
57
0
    }
58
59
0
    case NotOwned: {
60
0
      Out << "NotOwned";
61
0
      unsigned cnt = getCount();
62
0
      if (cnt) Out << " (+ " << cnt << ")";
63
0
      break;
64
0
    }
65
66
0
    case ReturnedOwned: {
67
0
      Out << "ReturnedOwned";
68
0
      unsigned cnt = getCount();
69
0
      if (cnt) Out << " (+ " << cnt << ")";
70
0
      break;
71
0
    }
72
73
0
    case ReturnedNotOwned: {
74
0
      Out << "ReturnedNotOwned";
75
0
      unsigned cnt = getCount();
76
0
      if (cnt) Out << " (+ " << cnt << ")";
77
0
      break;
78
0
    }
79
80
0
    case Released:
81
0
      Out << "Released";
82
0
      break;
83
84
0
    case ErrorDeallocNotOwned:
85
0
      Out << "-dealloc (not-owned)";
86
0
      break;
87
88
0
    case ErrorLeak:
89
0
      Out << "Leaked";
90
0
      break;
91
92
0
    case ErrorLeakReturned:
93
0
      Out << "Leaked (Bad naming)";
94
0
      break;
95
96
0
    case ErrorUseAfterRelease:
97
0
      Out << "Use-After-Release [ERROR]";
98
0
      break;
99
100
0
    case ErrorReleaseNotOwned:
101
0
      Out << "Release of Not-Owned [ERROR]";
102
0
      break;
103
104
0
    case RefVal::ErrorOverAutorelease:
105
0
      Out << "Over-autoreleased";
106
0
      break;
107
108
0
    case RefVal::ErrorReturnedNotOwned:
109
0
      Out << "Non-owned object returned instead of owned";
110
0
      break;
111
0
  }
112
113
0
  switch (getIvarAccessHistory()) {
114
0
  case IvarAccessHistory::None:
115
0
    break;
116
0
  case IvarAccessHistory::AccessedDirectly:
117
0
    Out << " [direct ivar access]";
118
0
    break;
119
0
  case IvarAccessHistory::ReleasedAfterDirectAccess:
120
0
    Out << " [released after direct ivar access]";
121
0
  }
122
123
0
  if (ACnt) {
124
0
    Out << " [autorelease -" << ACnt << ']';
125
0
  }
126
0
}
127
128
namespace {
129
class StopTrackingCallback final : public SymbolVisitor {
130
  ProgramStateRef state;
131
public:
132
328
  StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
133
328
  ProgramStateRef getState() const { return state; }
134
135
198
  bool VisitSymbol(SymbolRef sym) override {
136
198
    state = removeRefBinding(state, sym);
137
198
    return true;
138
198
  }
139
};
140
} // end anonymous namespace
141
142
//===----------------------------------------------------------------------===//
143
// Handle statements that may have an effect on refcounts.
144
//===----------------------------------------------------------------------===//
145
146
void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
147
63
                                       CheckerContext &C) const {
148
149
  // Scan the BlockDecRefExprs for any object the retain count checker
150
  // may be tracking.
151
63
  if (!BE->getBlockDecl()->hasCaptures())
152
38
    return;
153
154
25
  ProgramStateRef state = C.getState();
155
25
  auto *R = cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
156
157
25
  BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
158
25
                                            E = R->referenced_vars_end();
159
160
25
  if (I == E)
161
0
    return;
162
163
  // FIXME: For now we invalidate the tracking of all symbols passed to blocks
164
  // via captured variables, even though captured variables result in a copy
165
  // and in implicit increment/decrement of a retain count.
166
25
  SmallVector<const MemRegion*, 10> Regions;
167
25
  const LocationContext *LC = C.getLocationContext();
168
25
  MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
169
170
54
  for ( ; I != E; 
++I29
) {
171
29
    const VarRegion *VR = I.getCapturedRegion();
172
29
    if (VR->getSuperRegion() == R) {
173
19
      VR = MemMgr.getVarRegion(VR->getDecl(), LC);
174
19
    }
175
29
    Regions.push_back(VR);
176
29
  }
177
178
25
  state = state->scanReachableSymbols<StopTrackingCallback>(Regions).getState();
179
25
  C.addTransition(state);
180
25
}
181
182
void RetainCountChecker::checkPostStmt(const CastExpr *CE,
183
10.0k
                                       CheckerContext &C) const {
184
10.0k
  const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
185
10.0k
  if (!BE)
186
10.0k
    return;
187
188
19
  QualType QT = CE->getType();
189
19
  ObjKind K;
190
19
  if (QT->isObjCObjectPointerType()) {
191
10
    K = ObjKind::ObjC;
192
10
  } else {
193
9
    K = ObjKind::CF;
194
9
  }
195
196
19
  ArgEffect AE = ArgEffect(IncRef, K);
197
198
19
  switch (BE->getBridgeKind()) {
199
11
    case OBC_Bridge:
200
      // Do nothing.
201
11
      return;
202
3
    case OBC_BridgeRetained:
203
3
      AE = AE.withKind(IncRef);
204
3
      break;
205
5
    case OBC_BridgeTransfer:
206
5
      AE = AE.withKind(DecRefBridgedTransferred);
207
5
      break;
208
19
  }
209
210
8
  ProgramStateRef state = C.getState();
211
8
  SymbolRef Sym = C.getSVal(CE).getAsLocSymbol();
212
8
  if (!Sym)
213
0
    return;
214
8
  const RefVal* T = getRefBinding(state, Sym);
215
8
  if (!T)
216
3
    return;
217
218
5
  RefVal::Kind hasErr = (RefVal::Kind) 0;
219
5
  state = updateSymbol(state, Sym, *T, AE, hasErr, C);
220
221
5
  if (hasErr) {
222
    // FIXME: If we get an error during a bridge cast, should we report it?
223
0
    return;
224
0
  }
225
226
5
  C.addTransition(state);
227
5
}
228
229
void RetainCountChecker::processObjCLiterals(CheckerContext &C,
230
34
                                             const Expr *Ex) const {
231
34
  ProgramStateRef state = C.getState();
232
34
  const ExplodedNode *pred = C.getPredecessor();
233
34
  for (const Stmt *Child : Ex->children()) {
234
25
    SVal V = pred->getSVal(Child);
235
25
    if (SymbolRef sym = V.getAsSymbol())
236
21
      if (const RefVal* T = getRefBinding(state, sym)) {
237
13
        RefVal::Kind hasErr = (RefVal::Kind) 0;
238
13
        state = updateSymbol(state, sym, *T,
239
13
                             ArgEffect(MayEscape, ObjKind::ObjC), hasErr, C);
240
13
        if (hasErr) {
241
0
          processNonLeakError(state, Child->getSourceRange(), hasErr, sym, C);
242
0
          return;
243
0
        }
244
13
      }
245
25
  }
246
247
  // Return the object as autoreleased.
248
  //  RetEffect RE = RetEffect::MakeNotOwned(ObjKind::ObjC);
249
34
  if (SymbolRef sym =
250
34
        state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
251
34
    QualType ResultTy = Ex->getType();
252
34
    state = setRefBinding(state, sym,
253
34
                          RefVal::makeNotOwned(ObjKind::ObjC, ResultTy));
254
34
  }
255
256
34
  C.addTransition(state);
257
34
}
258
259
void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
260
29
                                       CheckerContext &C) const {
261
  // Apply the 'MayEscape' to all values.
262
29
  processObjCLiterals(C, AL);
263
29
}
264
265
void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
266
5
                                       CheckerContext &C) const {
267
  // Apply the 'MayEscape' to all keys and values.
268
5
  processObjCLiterals(C, DL);
269
5
}
270
271
void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
272
25
                                       CheckerContext &C) const {
273
25
  const ExplodedNode *Pred = C.getPredecessor();
274
25
  ProgramStateRef State = Pred->getState();
275
276
25
  if (SymbolRef Sym = Pred->getSVal(Ex).getAsSymbol()) {
277
25
    QualType ResultTy = Ex->getType();
278
25
    State = setRefBinding(State, Sym,
279
25
                          RefVal::makeNotOwned(ObjKind::ObjC, ResultTy));
280
25
  }
281
282
25
  C.addTransition(State);
283
25
}
284
285
void RetainCountChecker::checkPostStmt(const ObjCIvarRefExpr *IRE,
286
486
                                       CheckerContext &C) const {
287
486
  Optional<Loc> IVarLoc = C.getSVal(IRE).getAs<Loc>();
288
486
  if (!IVarLoc)
289
0
    return;
290
291
486
  ProgramStateRef State = C.getState();
292
486
  SymbolRef Sym = State->getSVal(*IVarLoc).getAsSymbol();
293
486
  if (!Sym || 
!dyn_cast_or_null<ObjCIvarRegion>(Sym->getOriginRegion())425
)
294
89
    return;
295
296
  // Accessing an ivar directly is unusual. If we've done that, be more
297
  // forgiving about what the surrounding code is allowed to do.
298
299
397
  QualType Ty = Sym->getType();
300
397
  ObjKind Kind;
301
397
  if (Ty->isObjCRetainableType())
302
262
    Kind = ObjKind::ObjC;
303
135
  else if (coreFoundation::isCFObjectRef(Ty))
304
15
    Kind = ObjKind::CF;
305
120
  else
306
120
    return;
307
308
  // If the value is already known to be nil, don't bother tracking it.
309
277
  ConstraintManager &CMgr = State->getConstraintManager();
310
277
  if (CMgr.isNull(State, Sym).isConstrainedTrue())
311
16
    return;
312
313
261
  if (const RefVal *RV = getRefBinding(State, Sym)) {
314
    // If we've seen this symbol before, or we're only seeing it now because
315
    // of something the analyzer has synthesized, don't do anything.
316
129
    if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None ||
317
129
        
isSynthesizedAccessor(C.getStackFrame())27
) {
318
120
      return;
319
120
    }
320
321
    // Note that this value has been loaded from an ivar.
322
9
    C.addTransition(setRefBinding(State, Sym, RV->withIvarAccess()));
323
9
    return;
324
129
  }
325
326
132
  RefVal PlusZero = RefVal::makeNotOwned(Kind, Ty);
327
328
  // In a synthesized accessor, the effective retain count is +0.
329
132
  if (isSynthesizedAccessor(C.getStackFrame())) {
330
32
    C.addTransition(setRefBinding(State, Sym, PlusZero));
331
32
    return;
332
32
  }
333
334
100
  State = setRefBinding(State, Sym, PlusZero.withIvarAccess());
335
100
  C.addTransition(State);
336
100
}
337
338
4.32k
static bool isReceiverUnconsumedSelf(const CallEvent &Call) {
339
4.32k
  if (const auto *MC = dyn_cast<ObjCMethodCall>(&Call)) {
340
341
    // Check if the message is not consumed, we know it will not be used in
342
    // an assignment, ex: "self = [super init]".
343
2.23k
    return MC->getMethodFamily() == OMF_init && 
MC->isReceiverSelfOrSuper()497
&&
344
2.23k
           !Call.getLocationContext()
345
62
                ->getAnalysisDeclContext()
346
62
                ->getParentMap()
347
62
                .isConsumedExpr(Call.getOriginExpr());
348
2.23k
  }
349
2.08k
  return false;
350
4.32k
}
351
352
const static RetainSummary *getSummary(RetainSummaryManager &Summaries,
353
                                       const CallEvent &Call,
354
4.32k
                                       QualType ReceiverType) {
355
4.32k
  const Expr *CE = Call.getOriginExpr();
356
4.32k
  AnyCall C =
357
4.32k
      CE ? 
*AnyCall::forExpr(CE)4.30k
358
4.32k
         : 
AnyCall(cast<CXXDestructorDecl>(Call.getDecl()))13
;
359
4.32k
  return Summaries.getSummary(C, Call.hasNonZeroCallbackArg(),
360
4.32k
                              isReceiverUnconsumedSelf(Call), ReceiverType);
361
4.32k
}
362
363
void RetainCountChecker::checkPostCall(const CallEvent &Call,
364
4.32k
                                       CheckerContext &C) const {
365
4.32k
  RetainSummaryManager &Summaries = getSummaryManager(C);
366
367
  // Leave null if no receiver.
368
4.32k
  QualType ReceiverType;
369
4.32k
  if (const auto *MC = dyn_cast<ObjCMethodCall>(&Call)) {
370
2.23k
    if (MC->isInstanceMessage()) {
371
1.67k
      SVal ReceiverV = MC->getReceiverSVal();
372
1.67k
      if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
373
1.66k
        if (const RefVal *T = getRefBinding(C.getState(), Sym))
374
1.14k
          ReceiverType = T->getType();
375
1.67k
    }
376
2.23k
  }
377
378
4.32k
  const RetainSummary *Summ = getSummary(Summaries, Call, ReceiverType);
379
380
4.32k
  if (C.wasInlined) {
381
672
    processSummaryOfInlined(*Summ, Call, C);
382
672
    return;
383
672
  }
384
3.65k
  checkSummary(*Summ, Call, C);
385
3.65k
}
386
387
/// GetReturnType - Used to get the return type of a message expression or
388
///  function call with the intention of affixing that type to a tracked symbol.
389
///  While the return type can be queried directly from RetEx, when
390
///  invoking class methods we augment to the return type to be that of
391
///  a pointer to the class (as opposed it just being id).
392
// FIXME: We may be able to do this with related result types instead.
393
// This function is probably overestimating.
394
249
static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
395
249
  QualType RetTy = RetE->getType();
396
  // If RetE is not a message expression just return its type.
397
  // If RetE is a message expression, return its types if it is something
398
  /// more specific than id.
399
249
  if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
400
182
    if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
401
182
      if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
402
182
          
PT->isObjCClassType()103
) {
403
        // At this point we know the return type of the message expression is
404
        // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
405
        // is a call to a class method whose type we can resolve.  In such
406
        // cases, promote the return type to XXX* (where XXX is the class).
407
81
        const ObjCInterfaceDecl *D = ME->getReceiverInterface();
408
81
        return !D ? 
RetTy13
:
409
81
                    
Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D))68
;
410
81
      }
411
412
168
  return RetTy;
413
249
}
414
415
static Optional<RefVal> refValFromRetEffect(RetEffect RE,
416
2.35k
                                            QualType ResultTy) {
417
2.35k
  if (RE.isOwned()) {
418
1.29k
    return RefVal::makeOwned(RE.getObjKind(), ResultTy);
419
1.29k
  } else 
if (1.06k
RE.notOwned()1.06k
) {
420
249
    return RefVal::makeNotOwned(RE.getObjKind(), ResultTy);
421
249
  }
422
423
816
  return None;
424
2.35k
}
425
426
39
static bool isPointerToObject(QualType QT) {
427
39
  QualType PT = QT->getPointeeType();
428
39
  if (!PT.isNull())
429
39
    if (PT->getAsCXXRecordDecl())
430
34
      return true;
431
5
  return false;
432
39
}
433
434
/// Whether the tracked value should be escaped on a given call.
435
/// OSObjects are escaped when passed to void * / etc.
436
static bool shouldEscapeOSArgumentOnCall(const CallEvent &CE, unsigned ArgIdx,
437
624
                                       const RefVal *TrackedValue) {
438
624
  if (TrackedValue->getObjKind() != ObjKind::OS)
439
584
    return false;
440
40
  if (ArgIdx >= CE.parameters().size())
441
1
    return false;
442
39
  return !isPointerToObject(CE.parameters()[ArgIdx]->getType());
443
40
}
444
445
// We don't always get the exact modeling of the function with regards to the
446
// retain count checker even when the function is inlined. For example, we need
447
// to stop tracking the symbols which were marked with StopTrackingHard.
448
void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
449
                                                 const CallEvent &CallOrMsg,
450
672
                                                 CheckerContext &C) const {
451
672
  ProgramStateRef state = C.getState();
452
453
  // Evaluate the effect of the arguments.
454
1.08k
  for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; 
++idx410
) {
455
410
    SVal V = CallOrMsg.getArgSVal(idx);
456
457
410
    if (SymbolRef Sym = V.getAsLocSymbol()) {
458
190
      bool ShouldRemoveBinding = Summ.getArg(idx).getKind() == StopTrackingHard;
459
190
      if (const RefVal *T = getRefBinding(state, Sym))
460
62
        if (shouldEscapeOSArgumentOnCall(CallOrMsg, idx, T))
461
1
          ShouldRemoveBinding = true;
462
463
190
      if (ShouldRemoveBinding)
464
7
        state = removeRefBinding(state, Sym);
465
190
    }
466
410
  }
467
468
  // Evaluate the effect on the message receiver.
469
672
  if (const auto *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg)) {
470
309
    if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
471
291
      if (Summ.getReceiverEffect().getKind() == StopTrackingHard) {
472
1
        state = removeRefBinding(state, Sym);
473
1
      }
474
291
    }
475
309
  }
476
477
  // Consult the summary for the return value.
478
672
  RetEffect RE = Summ.getRetEffect();
479
480
672
  if (SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol()) {
481
222
    if (RE.getKind() == RetEffect::NoRetHard)
482
2
      state = removeRefBinding(state, Sym);
483
222
  }
484
485
672
  C.addTransition(state);
486
672
}
487
488
2.15k
static bool isSmartPtrField(const MemRegion *MR) {
489
2.15k
  const auto *TR = dyn_cast<TypedValueRegion>(
490
2.15k
    cast<SubRegion>(MR)->getSuperRegion());
491
2.15k
  return TR && 
RetainSummaryManager::isKnownSmartPointer(TR->getValueType())79
;
492
2.15k
}
493
494
495
/// A value escapes in these possible cases:
496
///
497
/// - binding to something that is not a memory region.
498
/// - binding to a memregion that does not have stack storage
499
/// - binding to a variable that has a destructor attached using CleanupAttr
500
///
501
/// We do not currently model what happens when a symbol is
502
/// assigned to a struct field, unless it is a known smart pointer
503
/// implementation, about which we know that it is inlined.
504
/// FIXME: This could definitely be improved upon.
505
2.15k
static bool shouldEscapeRegion(const MemRegion *R) {
506
2.15k
  if (isSmartPtrField(R))
507
3
    return false;
508
509
2.15k
  const auto *VR = dyn_cast<VarRegion>(R);
510
511
2.15k
  if (!R->hasStackStorage() || 
!VR1.84k
)
512
388
    return true;
513
514
1.76k
  const VarDecl *VD = VR->getDecl();
515
1.76k
  if (!VD->hasAttr<CleanupAttr>())
516
1.75k
    return false; // CleanupAttr attaches destructors, which cause escaping.
517
7
  return true;
518
1.76k
}
519
520
static SmallVector<ProgramStateRef, 2>
521
updateOutParameters(ProgramStateRef State, const RetainSummary &Summ,
522
3.52k
                    const CallEvent &CE) {
523
524
3.52k
  SVal L = CE.getReturnValue();
525
526
  // Splitting is required to support out parameters,
527
  // as out parameters might be created only on the "success" branch.
528
  // We want to avoid eagerly splitting unless out parameters are actually
529
  // needed.
530
3.52k
  bool SplitNecessary = false;
531
3.52k
  for (auto &P : Summ.getArgEffects())
532
1.11k
    if (P.second.getKind() == RetainedOutParameterOnNonZero ||
533
1.11k
        
P.second.getKind() == RetainedOutParameterOnZero1.09k
)
534
16
      SplitNecessary = true;
535
536
3.52k
  ProgramStateRef AssumeNonZeroReturn = State;
537
3.52k
  ProgramStateRef AssumeZeroReturn = State;
538
539
3.52k
  if (SplitNecessary) {
540
14
    if (!CE.getResultType()->isScalarType()) {
541
      // Structures cannot be assumed. This probably deserves
542
      // a compiler warning for invalid annotations.
543
1
      return {State};
544
1
    }
545
13
    if (auto DL = L.getAs<DefinedOrUnknownSVal>()) {
546
13
      AssumeNonZeroReturn = AssumeNonZeroReturn->assume(*DL, true);
547
13
      AssumeZeroReturn = AssumeZeroReturn->assume(*DL, false);
548
13
    }
549
13
  }
550
551
5.99k
  
for (unsigned idx = 0, e = CE.getNumArgs(); 3.52k
idx != e;
++idx2.46k
) {
552
2.46k
    SVal ArgVal = CE.getArgSVal(idx);
553
2.46k
    ArgEffect AE = Summ.getArg(idx);
554
555
2.46k
    auto *ArgRegion = dyn_cast_or_null<TypedValueRegion>(ArgVal.getAsRegion());
556
2.46k
    if (!ArgRegion)
557
2.01k
      continue;
558
559
449
    QualType PointeeTy = ArgRegion->getValueType();
560
449
    SVal PointeeVal = State->getSVal(ArgRegion);
561
449
    SymbolRef Pointee = PointeeVal.getAsLocSymbol();
562
449
    if (!Pointee)
563
302
      continue;
564
565
147
    if (shouldEscapeRegion(ArgRegion))
566
92
      continue;
567
568
55
    auto makeNotOwnedParameter = [&](ProgramStateRef St) {
569
16
      return setRefBinding(St, Pointee,
570
16
                           RefVal::makeNotOwned(AE.getObjKind(), PointeeTy));
571
16
    };
572
55
    auto makeOwnedParameter = [&](ProgramStateRef St) {
573
26
      return setRefBinding(St, Pointee,
574
26
                           RefVal::makeOwned(ObjKind::OS, PointeeTy));
575
26
    };
576
577
55
    switch (AE.getKind()) {
578
8
    case UnretainedOutParameter:
579
8
      AssumeNonZeroReturn = makeNotOwnedParameter(AssumeNonZeroReturn);
580
8
      AssumeZeroReturn = makeNotOwnedParameter(AssumeZeroReturn);
581
8
      break;
582
6
    case RetainedOutParameter:
583
6
      AssumeNonZeroReturn = makeOwnedParameter(AssumeNonZeroReturn);
584
6
      AssumeZeroReturn = makeOwnedParameter(AssumeZeroReturn);
585
6
      break;
586
10
    case RetainedOutParameterOnNonZero:
587
10
      AssumeNonZeroReturn = makeOwnedParameter(AssumeNonZeroReturn);
588
10
      break;
589
4
    case RetainedOutParameterOnZero:
590
4
      AssumeZeroReturn = makeOwnedParameter(AssumeZeroReturn);
591
4
      break;
592
27
    default:
593
27
      break;
594
55
    }
595
55
  }
596
597
3.52k
  if (SplitNecessary) {
598
13
    return {AssumeNonZeroReturn, AssumeZeroReturn};
599
3.51k
  } else {
600
3.51k
    assert(AssumeZeroReturn == AssumeNonZeroReturn);
601
0
    return {AssumeZeroReturn};
602
3.51k
  }
603
3.52k
}
604
605
void RetainCountChecker::checkSummary(const RetainSummary &Summ,
606
                                      const CallEvent &CallOrMsg,
607
3.65k
                                      CheckerContext &C) const {
608
3.65k
  ProgramStateRef state = C.getState();
609
610
  // Evaluate the effect of the arguments.
611
3.65k
  RefVal::Kind hasErr = (RefVal::Kind) 0;
612
3.65k
  SourceRange ErrorRange;
613
3.65k
  SymbolRef ErrorSym = nullptr;
614
615
  // Helper tag for providing diagnostics: indicate whether dealloc was sent
616
  // at this location.
617
3.65k
  bool DeallocSent = false;
618
619
6.13k
  for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; 
++idx2.48k
) {
620
2.54k
    SVal V = CallOrMsg.getArgSVal(idx);
621
622
2.54k
    ArgEffect Effect = Summ.getArg(idx);
623
2.54k
    if (SymbolRef Sym = V.getAsLocSymbol()) {
624
1.06k
      if (const RefVal *T = getRefBinding(state, Sym)) {
625
626
562
        if (shouldEscapeOSArgumentOnCall(CallOrMsg, idx, T))
627
4
          Effect = ArgEffect(StopTrackingHard, ObjKind::OS);
628
629
562
        state = updateSymbol(state, Sym, *T, Effect, hasErr, C);
630
562
        if (hasErr) {
631
59
          ErrorRange = CallOrMsg.getArgSourceRange(idx);
632
59
          ErrorSym = Sym;
633
59
          break;
634
503
        } else if (Effect.getKind() == Dealloc) {
635
0
          DeallocSent = true;
636
0
        }
637
562
      }
638
1.06k
    }
639
2.54k
  }
640
641
  // Evaluate the effect on the message receiver / `this` argument.
642
3.65k
  bool ReceiverIsTracked = false;
643
3.65k
  if (!hasErr) {
644
3.59k
    if (const auto *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg)) {
645
1.92k
      if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
646
1.37k
        if (const RefVal *T = getRefBinding(state, Sym)) {
647
1.09k
          ReceiverIsTracked = true;
648
1.09k
          state = updateSymbol(state, Sym, *T,
649
1.09k
                               Summ.getReceiverEffect(), hasErr, C);
650
1.09k
          if (hasErr) {
651
57
            ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
652
57
            ErrorSym = Sym;
653
1.03k
          } else if (Summ.getReceiverEffect().getKind() == Dealloc) {
654
8
            DeallocSent = true;
655
8
          }
656
1.09k
        }
657
1.37k
      }
658
1.92k
    } else 
if (const auto *1.66k
MCall1.66k
= dyn_cast<CXXMemberCall>(&CallOrMsg)) {
659
105
      if (SymbolRef Sym = MCall->getCXXThisVal().getAsLocSymbol()) {
660
103
        if (const RefVal *T = getRefBinding(state, Sym)) {
661
83
          state = updateSymbol(state, Sym, *T, Summ.getThisEffect(),
662
83
                               hasErr, C);
663
83
          if (hasErr) {
664
7
            ErrorRange = MCall->getOriginExpr()->getSourceRange();
665
7
            ErrorSym = Sym;
666
7
          }
667
83
        }
668
103
      }
669
105
    }
670
3.59k
  }
671
672
  // Process any errors.
673
3.65k
  if (hasErr) {
674
123
    processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
675
123
    return;
676
123
  }
677
678
  // Consult the summary for the return value.
679
3.52k
  RetEffect RE = Summ.getRetEffect();
680
681
3.52k
  if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
682
425
    if (ReceiverIsTracked)
683
381
      RE = getSummaryManager(C).getObjAllocRetEffect();
684
44
    else
685
44
      RE = RetEffect::MakeNoRet();
686
425
  }
687
688
3.52k
  if (SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol()) {
689
2.35k
    QualType ResultTy = CallOrMsg.getResultType();
690
2.35k
    if (RE.notOwned()) {
691
249
      const Expr *Ex = CallOrMsg.getOriginExpr();
692
249
      assert(Ex);
693
0
      ResultTy = GetReturnType(Ex, C.getASTContext());
694
249
    }
695
2.35k
    if (Optional<RefVal> updatedRefVal = refValFromRetEffect(RE, ResultTy))
696
1.54k
      state = setRefBinding(state, Sym, *updatedRefVal);
697
2.35k
  }
698
699
0
  SmallVector<ProgramStateRef, 2> Out =
700
3.52k
      updateOutParameters(state, Summ, CallOrMsg);
701
702
3.54k
  for (ProgramStateRef St : Out) {
703
3.54k
    if (DeallocSent) {
704
8
      C.addTransition(St, C.getPredecessor(), &getDeallocSentTag());
705
3.53k
    } else {
706
3.53k
      C.addTransition(St);
707
3.53k
    }
708
3.54k
  }
709
3.52k
}
710
711
ProgramStateRef RetainCountChecker::updateSymbol(ProgramStateRef state,
712
                                                 SymbolRef sym, RefVal V,
713
                                                 ArgEffect AE,
714
                                                 RefVal::Kind &hasErr,
715
1.75k
                                                 CheckerContext &C) const {
716
1.75k
  bool IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
717
1.75k
  if (AE.getObjKind() == ObjKind::ObjC && 
IgnoreRetainMsg1.11k
) {
718
27
    switch (AE.getKind()) {
719
14
    default:
720
14
      break;
721
14
    case IncRef:
722
0
      AE = AE.withKind(DoNothing);
723
0
      break;
724
13
    case DecRef:
725
13
      AE = AE.withKind(DoNothing);
726
13
      break;
727
0
    case DecRefAndStopTrackingHard:
728
0
      AE = AE.withKind(StopTracking);
729
0
      break;
730
27
    }
731
27
  }
732
733
  // Handle all use-after-releases.
734
1.75k
  if (V.getKind() == RefVal::Released) {
735
71
    V = V ^ RefVal::ErrorUseAfterRelease;
736
71
    hasErr = V.getKind();
737
71
    return setRefBinding(state, sym, V);
738
71
  }
739
740
1.68k
  switch (AE.getKind()) {
741
0
    case UnretainedOutParameter:
742
0
    case RetainedOutParameter:
743
0
    case RetainedOutParameterOnZero:
744
0
    case RetainedOutParameterOnNonZero:
745
0
      llvm_unreachable("Applies to pointer-to-pointer parameters, which should "
746
0
                       "not have ref state.");
747
748
11
    case Dealloc: // NB. we only need to add a note in a non-error case.
749
11
      switch (V.getKind()) {
750
0
        default:
751
0
          llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
752
10
        case RefVal::Owned:
753
          // The object immediately transitions to the released state.
754
10
          V = V ^ RefVal::Released;
755
10
          V.clearCounts();
756
10
          return setRefBinding(state, sym, V);
757
1
        case RefVal::NotOwned:
758
1
          V = V ^ RefVal::ErrorDeallocNotOwned;
759
1
          hasErr = V.getKind();
760
1
          break;
761
11
      }
762
1
      break;
763
764
151
    case MayEscape:
765
151
      if (V.getKind() == RefVal::Owned) {
766
83
        V = V ^ RefVal::NotOwned;
767
83
        break;
768
83
      }
769
770
151
      
LLVM_FALLTHROUGH68
;68
771
772
283
    case DoNothing:
773
283
      return state;
774
775
159
    case Autorelease:
776
      // Update the autorelease counts.
777
159
      V = V.autorelease();
778
159
      break;
779
780
16
    case StopTracking:
781
52
    case StopTrackingHard:
782
52
      return removeRefBinding(state, sym);
783
784
226
    case IncRef:
785
226
      switch (V.getKind()) {
786
0
        default:
787
0
          llvm_unreachable("Invalid RefVal state for a retain.");
788
87
        case RefVal::Owned:
789
226
        case RefVal::NotOwned:
790
226
          V = V + 1;
791
226
          break;
792
226
      }
793
226
      break;
794
795
851
    case DecRef:
796
855
    case DecRefBridgedTransferred:
797
870
    case DecRefAndStopTrackingHard:
798
870
      switch (V.getKind()) {
799
0
        default:
800
          // case 'RefVal::Released' handled above.
801
0
          llvm_unreachable("Invalid RefVal state for a release.");
802
803
657
        case RefVal::Owned:
804
657
          assert(V.getCount() > 0);
805
657
          if (V.getCount() == 1) {
806
617
            if (AE.getKind() == DecRefBridgedTransferred ||
807
617
                V.getIvarAccessHistory() ==
808
613
                  RefVal::IvarAccessHistory::AccessedDirectly)
809
4
              V = V ^ RefVal::NotOwned;
810
613
            else
811
613
              V = V ^ RefVal::Released;
812
617
          } else 
if (40
AE.getKind() == DecRefAndStopTrackingHard40
) {
813
0
            return removeRefBinding(state, sym);
814
0
          }
815
816
657
          V = V - 1;
817
657
          break;
818
819
213
        case RefVal::NotOwned:
820
213
          if (V.getCount() > 0) {
821
124
            if (AE.getKind() == DecRefAndStopTrackingHard)
822
6
              return removeRefBinding(state, sym);
823
118
            V = V - 1;
824
118
          } else 
if (89
V.getIvarAccessHistory() ==
825
89
                       RefVal::IvarAccessHistory::AccessedDirectly) {
826
            // Assume that the instance variable was holding on the object at
827
            // +1, and we just didn't know.
828
38
            if (AE.getKind() == DecRefAndStopTrackingHard)
829
0
              return removeRefBinding(state, sym);
830
38
            V = V.releaseViaIvar() ^ RefVal::Released;
831
51
          } else {
832
51
            V = V ^ RefVal::ErrorReleaseNotOwned;
833
51
            hasErr = V.getKind();
834
51
          }
835
207
          break;
836
870
      }
837
864
      break;
838
1.68k
  }
839
1.33k
  return setRefBinding(state, sym, V);
840
1.68k
}
841
842
const RefCountBug &
843
RetainCountChecker::errorKindToBugKind(RefVal::Kind ErrorKind,
844
111
                                       SymbolRef Sym) const {
845
111
  switch (ErrorKind) {
846
59
    case RefVal::ErrorUseAfterRelease:
847
59
      return *UseAfterRelease;
848
51
    case RefVal::ErrorReleaseNotOwned:
849
51
      return *ReleaseNotOwned;
850
1
    case RefVal::ErrorDeallocNotOwned:
851
1
      if (Sym->getType()->getPointeeCXXRecordDecl())
852
1
        return *FreeNotOwned;
853
0
      return *DeallocNotOwned;
854
0
    default:
855
0
      llvm_unreachable("Unhandled error.");
856
111
  }
857
111
}
858
859
void RetainCountChecker::processNonLeakError(ProgramStateRef St,
860
                                             SourceRange ErrorRange,
861
                                             RefVal::Kind ErrorKind,
862
                                             SymbolRef Sym,
863
123
                                             CheckerContext &C) const {
864
  // HACK: Ignore retain-count issues on values accessed through ivars,
865
  // because of cases like this:
866
  //   [_contentView retain];
867
  //   [_contentView removeFromSuperview];
868
  //   [self addSubview:_contentView]; // invalidates 'self'
869
  //   [_contentView release];
870
123
  if (const RefVal *RV = getRefBinding(St, Sym))
871
123
    if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
872
12
      return;
873
874
111
  ExplodedNode *N = C.generateErrorNode(St);
875
111
  if (!N)
876
0
    return;
877
878
111
  auto report = std::make_unique<RefCountReport>(
879
111
      errorKindToBugKind(ErrorKind, Sym),
880
111
      C.getASTContext().getLangOpts(), N, Sym);
881
111
  report->addRange(ErrorRange);
882
111
  C.emitReport(std::move(report));
883
111
}
884
885
//===----------------------------------------------------------------------===//
886
// Handle the return values of retain-count-related functions.
887
//===----------------------------------------------------------------------===//
888
889
bool RetainCountChecker::evalCall(const CallEvent &Call,
890
1.98k
                                  CheckerContext &C) const {
891
1.98k
  ProgramStateRef state = C.getState();
892
1.98k
  const auto *FD = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
893
1.98k
  if (!FD)
894
39
    return false;
895
896
1.94k
  const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
897
1.94k
  if (!CE)
898
84
    return false;
899
900
1.86k
  RetainSummaryManager &SmrMgr = getSummaryManager(C);
901
1.86k
  QualType ResultTy = Call.getResultType();
902
903
  // See if the function has 'rc_ownership_trusted_implementation'
904
  // annotate attribute. If it does, we will not inline it.
905
1.86k
  bool hasTrustedImplementationAnnotation = false;
906
907
1.86k
  const LocationContext *LCtx = C.getLocationContext();
908
909
1.86k
  using BehaviorSummary = RetainSummaryManager::BehaviorSummary;
910
1.86k
  Optional<BehaviorSummary> BSmr =
911
1.86k
      SmrMgr.canEval(CE, FD, hasTrustedImplementationAnnotation);
912
913
  // See if it's one of the specific functions we know how to eval.
914
1.86k
  if (!BSmr)
915
1.65k
    return false;
916
917
  // Bind the return value.
918
214
  if (BSmr == BehaviorSummary::Identity ||
919
214
      
BSmr == BehaviorSummary::IdentityOrZero65
||
920
214
      
BSmr == BehaviorSummary::IdentityThis58
) {
921
922
157
    const Expr *BindReturnTo =
923
157
        (BSmr == BehaviorSummary::IdentityThis)
924
157
            ? 
cast<CXXMemberCallExpr>(CE)->getImplicitObjectArgument()1
925
157
            : 
CE->getArg(0)156
;
926
157
    SVal RetVal = state->getSVal(BindReturnTo, LCtx);
927
928
    // If the receiver is unknown or the function has
929
    // 'rc_ownership_trusted_implementation' annotate attribute, conjure a
930
    // return value.
931
    // FIXME: this branch is very strange.
932
157
    if (RetVal.isUnknown() ||
933
157
        (hasTrustedImplementationAnnotation && 
!ResultTy.isNull()10
)) {
934
10
      SValBuilder &SVB = C.getSValBuilder();
935
10
      RetVal =
936
10
          SVB.conjureSymbolVal(nullptr, CE, LCtx, ResultTy, C.blockCount());
937
10
    }
938
939
    // Bind the value.
940
157
    state = state->BindExpr(CE, LCtx, RetVal, /*Invalidate=*/false);
941
942
157
    if (BSmr == BehaviorSummary::IdentityOrZero) {
943
      // Add a branch where the output is zero.
944
7
      ProgramStateRef NullOutputState = C.getState();
945
946
      // Assume that output is zero on the other branch.
947
7
      NullOutputState = NullOutputState->BindExpr(
948
7
          CE, LCtx, C.getSValBuilder().makeNull(), /*Invalidate=*/false);
949
7
      C.addTransition(NullOutputState, &getCastFailTag());
950
951
      // And on the original branch assume that both input and
952
      // output are non-zero.
953
7
      if (auto L = RetVal.getAs<DefinedOrUnknownSVal>())
954
7
        state = state->assume(*L, /*assumption=*/true);
955
956
7
    }
957
157
  }
958
959
214
  C.addTransition(state);
960
214
  return true;
961
1.86k
}
962
963
ExplodedNode * RetainCountChecker::processReturn(const ReturnStmt *S,
964
2.06k
                                                 CheckerContext &C) const {
965
2.06k
  ExplodedNode *Pred = C.getPredecessor();
966
967
  // Only adjust the reference count if this is the top-level call frame,
968
  // and not the result of inlining.  In the future, we should do
969
  // better checking even for inlined calls, and see if they match
970
  // with their expected semantics (e.g., the method should return a retained
971
  // object, etc.).
972
2.06k
  if (!C.inTopFrame())
973
672
    return Pred;
974
975
1.39k
  if (!S)
976
853
    return Pred;
977
978
542
  const Expr *RetE = S->getRetValue();
979
542
  if (!RetE)
980
58
    return Pred;
981
982
484
  ProgramStateRef state = C.getState();
983
  // We need to dig down to the symbolic base here because various
984
  // custom allocators do sometimes return the symbol with an offset.
985
484
  SymbolRef Sym = state->getSValAsScalarOrLoc(RetE, C.getLocationContext())
986
484
                      .getAsLocSymbol(/*IncludeBaseRegions=*/true);
987
484
  if (!Sym)
988
159
    return Pred;
989
990
  // Get the reference count binding (if any).
991
325
  const RefVal *T = getRefBinding(state, Sym);
992
325
  if (!T)
993
79
    return Pred;
994
995
  // Change the reference count.
996
246
  RefVal X = *T;
997
998
246
  switch (X.getKind()) {
999
192
    case RefVal::Owned: {
1000
192
      unsigned cnt = X.getCount();
1001
192
      assert(cnt > 0);
1002
0
      X.setCount(cnt - 1);
1003
192
      X = X ^ RefVal::ReturnedOwned;
1004
192
      break;
1005
0
    }
1006
1007
51
    case RefVal::NotOwned: {
1008
51
      unsigned cnt = X.getCount();
1009
51
      if (cnt) {
1010
7
        X.setCount(cnt - 1);
1011
7
        X = X ^ RefVal::ReturnedOwned;
1012
44
      } else {
1013
44
        X = X ^ RefVal::ReturnedNotOwned;
1014
44
      }
1015
51
      break;
1016
0
    }
1017
1018
3
    default:
1019
3
      return Pred;
1020
246
  }
1021
1022
  // Update the binding.
1023
243
  state = setRefBinding(state, Sym, X);
1024
243
  Pred = C.addTransition(state);
1025
1026
  // At this point we have updated the state properly.
1027
  // Everything after this is merely checking to see if the return value has
1028
  // been over- or under-retained.
1029
1030
  // Did we cache out?
1031
243
  if (!Pred)
1032
0
    return nullptr;
1033
1034
  // Update the autorelease counts.
1035
243
  static CheckerProgramPointTag AutoreleaseTag(this, "Autorelease");
1036
243
  state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X, S);
1037
1038
  // Have we generated a sink node?
1039
243
  if (!state)
1040
12
    return nullptr;
1041
1042
  // Get the updated binding.
1043
231
  T = getRefBinding(state, Sym);
1044
231
  assert(T);
1045
0
  X = *T;
1046
1047
  // Consult the summary of the enclosing method.
1048
231
  RetainSummaryManager &Summaries = getSummaryManager(C);
1049
231
  const Decl *CD = &Pred->getCodeDecl();
1050
231
  RetEffect RE = RetEffect::MakeNoRet();
1051
1052
  // FIXME: What is the convention for blocks? Is there one?
1053
231
  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
1054
131
    const RetainSummary *Summ = Summaries.getSummary(AnyCall(MD));
1055
131
    RE = Summ->getRetEffect();
1056
131
  } else 
if (const FunctionDecl *100
FD100
= dyn_cast<FunctionDecl>(CD)) {
1057
100
    if (!isa<CXXMethodDecl>(FD)) {
1058
99
      const RetainSummary *Summ = Summaries.getSummary(AnyCall(FD));
1059
99
      RE = Summ->getRetEffect();
1060
99
    }
1061
100
  }
1062
1063
231
  return checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
1064
243
}
1065
1066
ExplodedNode * RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
1067
                                                  CheckerContext &C,
1068
                                                  ExplodedNode *Pred,
1069
                                                  RetEffect RE, RefVal X,
1070
                                                  SymbolRef Sym,
1071
231
                                                  ProgramStateRef state) const {
1072
  // HACK: Ignore retain-count issues on values accessed through ivars,
1073
  // because of cases like this:
1074
  //   [_contentView retain];
1075
  //   [_contentView removeFromSuperview];
1076
  //   [self addSubview:_contentView]; // invalidates 'self'
1077
  //   [_contentView release];
1078
231
  if (X.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
1079
14
    return Pred;
1080
1081
  // Any leaks or other errors?
1082
217
  if (X.isReturnedOwned() && 
X.getCount() == 0150
) {
1083
140
    if (RE.getKind() != RetEffect::NoRet) {
1084
125
      if (!RE.isOwned()) {
1085
1086
        // The returning type is a CF, we expect the enclosing method should
1087
        // return ownership.
1088
53
        X = X ^ RefVal::ErrorLeakReturned;
1089
1090
        // Generate an error node.
1091
53
        state = setRefBinding(state, Sym, X);
1092
1093
53
        static CheckerProgramPointTag ReturnOwnLeakTag(this, "ReturnsOwnLeak");
1094
53
        ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
1095
53
        if (N) {
1096
53
          const LangOptions &LOpts = C.getASTContext().getLangOpts();
1097
53
          auto R =
1098
53
              std::make_unique<RefLeakReport>(*LeakAtReturn, LOpts, N, Sym, C);
1099
53
          C.emitReport(std::move(R));
1100
53
        }
1101
53
        return N;
1102
53
      }
1103
125
    }
1104
140
  } else 
if (77
X.isReturnedNotOwned()77
) {
1105
67
    if (RE.isOwned()) {
1106
25
      if (X.getIvarAccessHistory() ==
1107
25
            RefVal::IvarAccessHistory::AccessedDirectly) {
1108
        // Assume the method was trying to transfer a +1 reference from a
1109
        // strong ivar to the caller.
1110
0
        state = setRefBinding(state, Sym,
1111
0
                              X.releaseViaIvar() ^ RefVal::ReturnedOwned);
1112
25
      } else {
1113
        // Trying to return a not owned object to a caller expecting an
1114
        // owned object.
1115
25
        state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
1116
1117
25
        static CheckerProgramPointTag
1118
25
            ReturnNotOwnedTag(this, "ReturnNotOwnedForOwned");
1119
1120
25
        ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
1121
25
        if (N) {
1122
25
          auto R = std::make_unique<RefCountReport>(
1123
25
              *ReturnNotOwnedForOwned, C.getASTContext().getLangOpts(), N, Sym);
1124
25
          C.emitReport(std::move(R));
1125
25
        }
1126
25
        return N;
1127
25
      }
1128
25
    }
1129
67
  }
1130
139
  return Pred;
1131
217
}
1132
1133
//===----------------------------------------------------------------------===//
1134
// Check various ways a symbol can be invalidated.
1135
//===----------------------------------------------------------------------===//
1136
1137
void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
1138
2.00k
                                   CheckerContext &C) const {
1139
2.00k
  ProgramStateRef state = C.getState();
1140
2.00k
  const MemRegion *MR = loc.getAsRegion();
1141
1142
  // Find all symbols referenced by 'val' that we are tracking
1143
  // and stop tracking them.
1144
2.00k
  if (MR && shouldEscapeRegion(MR)) {
1145
303
    state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1146
303
    C.addTransition(state);
1147
303
  }
1148
2.00k
}
1149
1150
ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
1151
                                               SVal Cond,
1152
13.3k
                                               bool Assumption) const {
1153
  // FIXME: We may add to the interface of evalAssume the list of symbols
1154
  //  whose assumptions have changed.  For now we just iterate through the
1155
  //  bindings and check if any of the tracked symbols are NULL.  This isn't
1156
  //  too bad since the number of symbols we will track in practice are
1157
  //  probably small and evalAssume is only called at branches and a few
1158
  //  other places.
1159
13.3k
  RefBindingsTy B = state->get<RefBindings>();
1160
1161
13.3k
  if (B.isEmpty())
1162
6.31k
    return state;
1163
1164
7.02k
  bool changed = false;
1165
7.02k
  RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
1166
7.02k
  ConstraintManager &CMgr = state->getConstraintManager();
1167
1168
8.83k
  for (auto &I : B) {
1169
    // Check if the symbol is null stop tracking the symbol.
1170
8.83k
    ConditionTruthVal AllocFailed = CMgr.isNull(state, I.first);
1171
8.83k
    if (AllocFailed.isConstrainedTrue()) {
1172
1.08k
      changed = true;
1173
1.08k
      B = RefBFactory.remove(B, I.first);
1174
1.08k
    }
1175
8.83k
  }
1176
1177
7.02k
  if (changed)
1178
1.08k
    state = state->set<RefBindings>(B);
1179
1180
7.02k
  return state;
1181
13.3k
}
1182
1183
ProgramStateRef RetainCountChecker::checkRegionChanges(
1184
    ProgramStateRef state, const InvalidatedSymbols *invalidated,
1185
    ArrayRef<const MemRegion *> ExplicitRegions,
1186
    ArrayRef<const MemRegion *> Regions, const LocationContext *LCtx,
1187
5.71k
    const CallEvent *Call) const {
1188
5.71k
  if (!invalidated)
1189
2.47k
    return state;
1190
1191
3.23k
  llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
1192
1193
3.23k
  for (const MemRegion *I : ExplicitRegions)
1194
2.72k
    if (const SymbolicRegion *SR = I->StripCasts()->getAs<SymbolicRegion>())
1195
2.29k
      WhitelistedSymbols.insert(SR->getSymbol());
1196
1197
6.99k
  for (SymbolRef sym : *invalidated) {
1198
6.99k
    if (WhitelistedSymbols.count(sym))
1199
2.28k
      continue;
1200
    // Remove any existing reference-count binding.
1201
4.70k
    state = removeRefBinding(state, sym);
1202
4.70k
  }
1203
3.23k
  return state;
1204
5.71k
}
1205
1206
ProgramStateRef
1207
RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
1208
                                            ExplodedNode *Pred,
1209
                                            const ProgramPointTag *Tag,
1210
                                            CheckerContext &Ctx,
1211
                                            SymbolRef Sym,
1212
                                            RefVal V,
1213
2.15k
                                            const ReturnStmt *S) const {
1214
2.15k
  unsigned ACnt = V.getAutoreleaseCount();
1215
1216
  // No autorelease counts?  Nothing to be done.
1217
2.15k
  if (!ACnt)
1218
1.98k
    return state;
1219
1220
166
  unsigned Cnt = V.getCount();
1221
1222
  // FIXME: Handle sending 'autorelease' to already released object.
1223
1224
166
  if (V.getKind() == RefVal::ReturnedOwned)
1225
86
    ++Cnt;
1226
1227
  // If we would over-release here, but we know the value came from an ivar,
1228
  // assume it was a strong ivar that's just been relinquished.
1229
166
  if (ACnt > Cnt &&
1230
166
      
V.getIvarAccessHistory() == RefVal::IvarAccessHistory::AccessedDirectly42
) {
1231
10
    V = V.releaseViaIvar();
1232
10
    --ACnt;
1233
10
  }
1234
1235
166
  if (ACnt <= Cnt) {
1236
128
    if (ACnt == Cnt) {
1237
108
      V.clearCounts();
1238
108
      if (V.getKind() == RefVal::ReturnedOwned) {
1239
75
        V = V ^ RefVal::ReturnedNotOwned;
1240
75
      } else {
1241
33
        V = V ^ RefVal::NotOwned;
1242
33
      }
1243
108
    } else {
1244
20
      V.setCount(V.getCount() - ACnt);
1245
20
      V.setAutoreleaseCount(0);
1246
20
    }
1247
128
    return setRefBinding(state, Sym, V);
1248
128
  }
1249
1250
  // HACK: Ignore retain-count issues on values accessed through ivars,
1251
  // because of cases like this:
1252
  //   [_contentView retain];
1253
  //   [_contentView removeFromSuperview];
1254
  //   [self addSubview:_contentView]; // invalidates 'self'
1255
  //   [_contentView release];
1256
38
  if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
1257
6
    return state;
1258
1259
  // Woah!  More autorelease counts then retain counts left.
1260
  // Emit hard error.
1261
32
  V = V ^ RefVal::ErrorOverAutorelease;
1262
32
  state = setRefBinding(state, Sym, V);
1263
1264
32
  ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
1265
32
  if (N) {
1266
32
    SmallString<128> sbuf;
1267
32
    llvm::raw_svector_ostream os(sbuf);
1268
32
    os << "Object was autoreleased ";
1269
32
    if (V.getAutoreleaseCount() > 1)
1270
17
      os << V.getAutoreleaseCount() << " times but the object ";
1271
15
    else
1272
15
      os << "but ";
1273
32
    os << "has a +" << V.getCount() << " retain count";
1274
1275
32
    const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
1276
32
    auto R = std::make_unique<RefCountReport>(*OverAutorelease, LOpts, N, Sym,
1277
32
                                              os.str());
1278
32
    Ctx.emitReport(std::move(R));
1279
32
  }
1280
1281
32
  return nullptr;
1282
38
}
1283
1284
ProgramStateRef
1285
RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
1286
                                      SymbolRef sid, RefVal V,
1287
1.58k
                                    SmallVectorImpl<SymbolRef> &Leaked) const {
1288
1.58k
  bool hasLeak;
1289
1290
  // HACK: Ignore retain-count issues on values accessed through ivars,
1291
  // because of cases like this:
1292
  //   [_contentView retain];
1293
  //   [_contentView removeFromSuperview];
1294
  //   [self addSubview:_contentView]; // invalidates 'self'
1295
  //   [_contentView release];
1296
1.58k
  if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
1297
112
    hasLeak = false;
1298
1.47k
  else if (V.isOwned())
1299
295
    hasLeak = true;
1300
1.17k
  else if (V.isNotOwned() || 
V.isReturnedOwned()793
)
1301
483
    hasLeak = (V.getCount() > 0);
1302
696
  else
1303
696
    hasLeak = false;
1304
1305
1.58k
  if (!hasLeak)
1306
1.21k
    return removeRefBinding(state, sid);
1307
1308
371
  Leaked.push_back(sid);
1309
371
  return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
1310
1.58k
}
1311
1312
ExplodedNode *
1313
RetainCountChecker::processLeaks(ProgramStateRef state,
1314
                                 SmallVectorImpl<SymbolRef> &Leaked,
1315
                                 CheckerContext &Ctx,
1316
1.73k
                                 ExplodedNode *Pred) const {
1317
  // Generate an intermediate node representing the leak point.
1318
1.73k
  ExplodedNode *N = Ctx.addTransition(state, Pred);
1319
1.73k
  const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
1320
1321
1.73k
  if (N) {
1322
1.73k
    for (SymbolRef L : Leaked) {
1323
371
      const RefCountBug &BT = Pred ? *LeakWithinFunction : 
*LeakAtReturn0
;
1324
371
      Ctx.emitReport(std::make_unique<RefLeakReport>(BT, LOpts, N, L, Ctx));
1325
371
    }
1326
1.73k
  }
1327
1328
1.73k
  return N;
1329
1.73k
}
1330
1331
2.04k
void RetainCountChecker::checkBeginFunction(CheckerContext &Ctx) const {
1332
2.04k
  if (!Ctx.inTopFrame())
1333
614
    return;
1334
1335
1.43k
  RetainSummaryManager &SmrMgr = getSummaryManager(Ctx);
1336
1.43k
  const LocationContext *LCtx = Ctx.getLocationContext();
1337
1.43k
  const Decl *D = LCtx->getDecl();
1338
1.43k
  Optional<AnyCall> C = AnyCall::forDecl(D);
1339
1340
1.43k
  if (!C || 
SmrMgr.isTrustedReferenceCountImplementation(D)1.39k
)
1341
39
    return;
1342
1343
1.39k
  ProgramStateRef state = Ctx.getState();
1344
1.39k
  const RetainSummary *FunctionSummary = SmrMgr.getSummary(*C);
1345
1.39k
  ArgEffects CalleeSideArgEffects = FunctionSummary->getArgEffects();
1346
1347
2.21k
  for (unsigned idx = 0, e = C->param_size(); idx != e; 
++idx819
) {
1348
819
    const ParmVarDecl *Param = C->parameters()[idx];
1349
819
    SymbolRef Sym = state->getSVal(state->getRegion(Param, LCtx)).getAsSymbol();
1350
1351
819
    QualType Ty = Param->getType();
1352
819
    const ArgEffect *AE = CalleeSideArgEffects.lookup(idx);
1353
819
    if (AE) {
1354
325
      ObjKind K = AE->getObjKind();
1355
325
      if (K == ObjKind::Generalized || 
K == ObjKind::OS311
||
1356
325
          
(287
TrackNSCFStartParam287
&&
(43
K == ObjKind::ObjC43
||
K == ObjKind::CF27
))) {
1357
81
        RefVal NewVal = AE->getKind() == DecRef ? 
RefVal::makeOwned(K, Ty)15
1358
81
                                                : 
RefVal::makeNotOwned(K, Ty)66
;
1359
81
        state = setRefBinding(state, Sym, NewVal);
1360
81
      }
1361
325
    }
1362
819
  }
1363
1364
1.39k
  Ctx.addTransition(state);
1365
1.39k
}
1366
1367
void RetainCountChecker::checkEndFunction(const ReturnStmt *RS,
1368
2.06k
                                          CheckerContext &Ctx) const {
1369
2.06k
  ExplodedNode *Pred = processReturn(RS, Ctx);
1370
1371
  // Created state cached out.
1372
2.06k
  if (!Pred) {
1373
12
    return;
1374
12
  }
1375
1376
2.05k
  ProgramStateRef state = Pred->getState();
1377
2.05k
  RefBindingsTy B = state->get<RefBindings>();
1378
1379
  // Don't process anything within synthesized bodies.
1380
2.05k
  const LocationContext *LCtx = Pred->getLocationContext();
1381
2.05k
  if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
1382
254
    assert(!LCtx->inTopFrame());
1383
0
    return;
1384
254
  }
1385
1386
1.80k
  for (auto &I : B) {
1387
545
    state = handleAutoreleaseCounts(state, Pred, /*Tag=*/nullptr, Ctx,
1388
545
                                    I.first, I.second);
1389
545
    if (!state)
1390
0
      return;
1391
545
  }
1392
1393
  // If the current LocationContext has a parent, don't check for leaks.
1394
  // We will do that later.
1395
  // FIXME: we should instead check for imbalances of the retain/releases,
1396
  // and suggest annotations.
1397
1.80k
  if (LCtx->getParent())
1398
418
    return;
1399
1400
1.38k
  B = state->get<RefBindings>();
1401
1.38k
  SmallVector<SymbolRef, 10> Leaked;
1402
1403
1.38k
  for (auto &I : B)
1404
243
    state = handleSymbolDeath(state, I.first, I.second, Leaked);
1405
1406
1.38k
  processLeaks(state, Leaked, Ctx, Pred);
1407
1.38k
}
1408
1409
void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1410
12.6k
                                          CheckerContext &C) const {
1411
12.6k
  ExplodedNode *Pred = C.getPredecessor();
1412
1413
12.6k
  ProgramStateRef state = C.getState();
1414
12.6k
  SmallVector<SymbolRef, 10> Leaked;
1415
1416
  // Update counts from autorelease pools
1417
12.6k
  for (const auto &I: state->get<RefBindings>()) {
1418
7.51k
    SymbolRef Sym = I.first;
1419
7.51k
    if (SymReaper.isDead(Sym)) {
1420
1.36k
      static CheckerProgramPointTag Tag(this, "DeadSymbolAutorelease");
1421
1.36k
      const RefVal &V = I.second;
1422
1.36k
      state = handleAutoreleaseCounts(state, Pred, &Tag, C, Sym, V);
1423
1.36k
      if (!state)
1424
20
        return;
1425
1426
      // Fetch the new reference count from the state, and use it to handle
1427
      // this symbol.
1428
1.34k
      state = handleSymbolDeath(state, Sym, *getRefBinding(state, Sym), Leaked);
1429
1.34k
    }
1430
7.51k
  }
1431
1432
12.6k
  if (Leaked.empty()) {
1433
12.2k
    C.addTransition(state);
1434
12.2k
    return;
1435
12.2k
  }
1436
1437
350
  Pred = processLeaks(state, Leaked, C, Pred);
1438
1439
  // Did we cache out?
1440
350
  if (!Pred)
1441
0
    return;
1442
1443
  // Now generate a new node that nukes the old bindings.
1444
  // The only bindings left at this point are the leaked symbols.
1445
350
  RefBindingsTy::Factory &F = state->get_context<RefBindings>();
1446
350
  RefBindingsTy B = state->get<RefBindings>();
1447
1448
350
  for (SymbolRef L : Leaked)
1449
360
    B = F.remove(B, L);
1450
1451
350
  state = state->set<RefBindings>(B);
1452
350
  C.addTransition(state, Pred);
1453
350
}
1454
1455
void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
1456
0
                                    const char *NL, const char *Sep) const {
1457
1458
0
  RefBindingsTy B = State->get<RefBindings>();
1459
1460
0
  if (B.isEmpty())
1461
0
    return;
1462
1463
0
  Out << Sep << NL;
1464
1465
0
  for (auto &I : B) {
1466
0
    Out << I.first << " : ";
1467
0
    I.second.print(Out);
1468
0
    Out << NL;
1469
0
  }
1470
0
}
1471
1472
//===----------------------------------------------------------------------===//
1473
// Checker registration.
1474
//===----------------------------------------------------------------------===//
1475
1476
std::unique_ptr<CheckerProgramPointTag> RetainCountChecker::DeallocSentTag;
1477
std::unique_ptr<CheckerProgramPointTag> RetainCountChecker::CastFailTag;
1478
1479
85
void ento::registerRetainCountBase(CheckerManager &Mgr) {
1480
85
  auto *Chk = Mgr.registerChecker<RetainCountChecker>();
1481
85
  Chk->DeallocSentTag =
1482
85
      std::make_unique<CheckerProgramPointTag>(Chk, "DeallocSent");
1483
85
  Chk->CastFailTag =
1484
85
      std::make_unique<CheckerProgramPointTag>(Chk, "DynamicCastFail");
1485
85
}
1486
1487
316
bool ento::shouldRegisterRetainCountBase(const CheckerManager &mgr) {
1488
316
  return true;
1489
316
}
1490
84
void ento::registerRetainCountChecker(CheckerManager &Mgr) {
1491
84
  auto *Chk = Mgr.getChecker<RetainCountChecker>();
1492
84
  Chk->TrackObjCAndCFObjects = true;
1493
84
  Chk->TrackNSCFStartParam = Mgr.getAnalyzerOptions().getCheckerBooleanOption(
1494
84
      Mgr.getCurrentCheckerName(), "TrackNSCFStartParam");
1495
1496
84
#define INIT_BUGTYPE(KIND)                                                     \
1497
672
  Chk->KIND = std::make_unique<RefCountBug>(Mgr.getCurrentCheckerName(),       \
1498
672
                                            RefCountBug::KIND);
1499
  // TODO: Ideally, we should have a checker for each of these bug types.
1500
84
  INIT_BUGTYPE(UseAfterRelease)
1501
84
  INIT_BUGTYPE(ReleaseNotOwned)
1502
84
  INIT_BUGTYPE(DeallocNotOwned)
1503
84
  INIT_BUGTYPE(FreeNotOwned)
1504
84
  INIT_BUGTYPE(OverAutorelease)
1505
84
  INIT_BUGTYPE(ReturnNotOwnedForOwned)
1506
84
  INIT_BUGTYPE(LeakWithinFunction)
1507
84
  INIT_BUGTYPE(LeakAtReturn)
1508
84
#undef INIT_BUGTYPE
1509
84
}
1510
1511
172
bool ento::shouldRegisterRetainCountChecker(const CheckerManager &mgr) {
1512
172
  return true;
1513
172
}
1514
1515
36
void ento::registerOSObjectRetainCountChecker(CheckerManager &Mgr) {
1516
36
  auto *Chk = Mgr.getChecker<RetainCountChecker>();
1517
36
  Chk->TrackOSObjects = true;
1518
1519
  // FIXME: We want bug reports to always have the same checker name associated
1520
  // with them, yet here, if RetainCountChecker is disabled but
1521
  // OSObjectRetainCountChecker is enabled, the checker names will be different.
1522
  // This hack will make it so that the checker name depends on which checker is
1523
  // enabled rather than on the registration order.
1524
  // For the most part, we want **non-hidden checkers** to be associated with
1525
  // diagnostics, and **hidden checker options** with the fine-tuning of
1526
  // modeling. Following this logic, OSObjectRetainCountChecker should be the
1527
  // latter, but we can't just remove it for backward compatibility reasons.
1528
36
#define LAZY_INIT_BUGTYPE(KIND)                                                \
1529
288
  if (!Chk->KIND)                                                              \
1530
288
    Chk->KIND = std::make_unique<RefCountBug>(Mgr.getCurrentCheckerName(),     \
1531
288
                                              RefCountBug::KIND);
1532
36
  LAZY_INIT_BUGTYPE(UseAfterRelease)
1533
36
  LAZY_INIT_BUGTYPE(ReleaseNotOwned)
1534
36
  LAZY_INIT_BUGTYPE(DeallocNotOwned)
1535
36
  LAZY_INIT_BUGTYPE(FreeNotOwned)
1536
36
  LAZY_INIT_BUGTYPE(OverAutorelease)
1537
36
  LAZY_INIT_BUGTYPE(ReturnNotOwnedForOwned)
1538
36
  LAZY_INIT_BUGTYPE(LeakWithinFunction)
1539
36
  LAZY_INIT_BUGTYPE(LeakAtReturn)
1540
36
#undef LAZY_INIT_BUGTYPE
1541
36
}
1542
1543
72
bool ento::shouldRegisterOSObjectRetainCountChecker(const CheckerManager &mgr) {
1544
72
  return true;
1545
72
}