Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
Line
Count
Source (jump to first uncovered line)
1
// RetainCountDiagnostics.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 diagnostics for RetainCountChecker, which implements
10
//  a reference count checker for Core Foundation and Cocoa on (Mac OS X).
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "RetainCountDiagnostics.h"
15
#include "RetainCountChecker.h"
16
17
using namespace clang;
18
using namespace ento;
19
using namespace retaincountchecker;
20
21
568
StringRef RefCountBug::bugTypeToName(RefCountBug::RefCountBugType BT) {
22
568
  switch (BT) {
23
568
  case UseAfterRelease:
24
71
    return "Use-after-release";
25
568
  case ReleaseNotOwned:
26
71
    return "Bad release";
27
568
  case DeallocNotOwned:
28
71
    return "-dealloc sent to non-exclusively owned object";
29
568
  case FreeNotOwned:
30
71
    return "freeing non-exclusively owned object";
31
568
  case OverAutorelease:
32
71
    return "Object autoreleased too many times";
33
568
  case ReturnNotOwnedForOwned:
34
71
    return "Method should return an owned object";
35
568
  case LeakWithinFunction:
36
71
    return "Leak";
37
568
  case LeakAtReturn:
38
71
    return "Leak of returned object";
39
0
  }
40
0
  llvm_unreachable("Unknown RefCountBugType");
41
0
}
42
43
589
StringRef RefCountBug::getDescription() const {
44
589
  switch (BT) {
45
589
  case UseAfterRelease:
46
60
    return "Reference-counted object is used after it is released";
47
589
  case ReleaseNotOwned:
48
51
    return "Incorrect decrement of the reference count of an object that is "
49
51
           "not owned at this point by the caller";
50
589
  case DeallocNotOwned:
51
0
    return "-dealloc sent to object that may be referenced elsewhere";
52
589
  case FreeNotOwned:
53
1
    return  "'free' called on an object that may be referenced elsewhere";
54
589
  case OverAutorelease:
55
32
    return "Object autoreleased too many times";
56
589
  case ReturnNotOwnedForOwned:
57
25
    return "Object with a +0 retain count returned to caller where a +1 "
58
25
           "(owning) retain count is expected";
59
589
  case LeakWithinFunction:
60
420
  case LeakAtReturn:
61
420
    return "";
62
0
  }
63
0
  llvm_unreachable("Unknown RefCountBugType");
64
0
}
65
66
RefCountBug::RefCountBug(const CheckerBase *Checker, RefCountBugType BT)
67
    : BugType(Checker, bugTypeToName(BT), categories::MemoryRefCount,
68
              /*SuppressOnSink=*/BT == LeakWithinFunction || BT == LeakAtReturn),
69
568
      BT(BT), Checker(Checker) {}
70
71
20
static bool isNumericLiteralExpression(const Expr *E) {
72
20
  // FIXME: This set of cases was copied from SemaExprObjC.
73
20
  return isa<IntegerLiteral>(E) ||
74
20
         
isa<CharacterLiteral>(E)12
||
75
20
         
isa<FloatingLiteral>(E)12
||
76
20
         
isa<ObjCBoolLiteralExpr>(E)12
||
77
20
         
isa<CXXBoolLiteralExpr>(E)12
;
78
20
}
79
80
/// If type represents a pointer to CXXRecordDecl,
81
/// and is not a typedef, return the decl name.
82
/// Otherwise, return the serialization of type.
83
276
static std::string getPrettyTypeName(QualType QT) {
84
276
  QualType PT = QT->getPointeeType();
85
276
  if (!PT.isNull() && !QT->getAs<TypedefType>())
86
130
    if (const auto *RD = PT->getAsCXXRecordDecl())
87
44
      return RD->getName();
88
232
  return QT.getAsString();
89
232
}
90
91
/// Write information about the type state change to {@code os},
92
/// return whether the note should be generated.
93
static bool shouldGenerateNote(llvm::raw_string_ostream &os,
94
                               const RefVal *PrevT,
95
                               const RefVal &CurrV,
96
9.70k
                               bool DeallocSent) {
97
9.70k
  // Get the previous type state.
98
9.70k
  RefVal PrevV = *PrevT;
99
9.70k
100
9.70k
  // Specially handle -dealloc.
101
9.70k
  if (DeallocSent) {
102
5
    // Determine if the object's reference count was pushed to zero.
103
5
    assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
104
5
    // We may not have transitioned to 'release' if we hit an error.
105
5
    // This case is handled elsewhere.
106
5
    if (CurrV.getKind() == RefVal::Released) {
107
5
      assert(CurrV.getCombinedCounts() == 0);
108
5
      os << "Object released by directly sending the '-dealloc' message";
109
5
      return true;
110
5
    }
111
9.69k
  }
112
9.69k
113
9.69k
  // Determine if the typestate has changed.
114
9.69k
  if (!PrevV.hasSameState(CurrV))
115
289
    switch (CurrV.getKind()) {
116
289
    case RefVal::Owned:
117
237
    case RefVal::NotOwned:
118
237
      if (PrevV.getCount() == CurrV.getCount()) {
119
96
        // Did an autorelease message get sent?
120
96
        if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
121
22
          return false;
122
74
123
74
        assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
124
74
        os << "Object autoreleased";
125
74
        return true;
126
74
      }
127
141
128
141
      if (PrevV.getCount() > CurrV.getCount())
129
31
        os << "Reference count decremented.";
130
110
      else
131
110
        os << "Reference count incremented.";
132
141
133
141
      if (unsigned Count = CurrV.getCount())
134
133
        os << " The object now has a +" << Count << " retain count.";
135
141
136
141
      return true;
137
141
138
141
    case RefVal::Released:
139
52
      if (CurrV.getIvarAccessHistory() ==
140
52
              RefVal::IvarAccessHistory::ReleasedAfterDirectAccess &&
141
52
          
CurrV.getIvarAccessHistory() != PrevV.getIvarAccessHistory()0
) {
142
0
        os << "Strong instance variable relinquished. ";
143
0
      }
144
52
      os << "Object released.";
145
52
      return true;
146
141
147
141
    case RefVal::ReturnedOwned:
148
0
      // Autoreleases can be applied after marking a node ReturnedOwned.
149
0
      if (CurrV.getAutoreleaseCount())
150
0
        return false;
151
0
152
0
      os << "Object returned to caller as an owning reference (single "
153
0
            "retain count transferred to caller)";
154
0
      return true;
155
0
156
0
    case RefVal::ReturnedNotOwned:
157
0
      os << "Object returned to caller with a +0 retain count";
158
0
      return true;
159
0
160
0
    default:
161
0
      return false;
162
9.40k
    }
163
9.40k
  return true;
164
9.40k
}
165
166
/// Finds argument index of the out paramter in the call {@code S}
167
/// corresponding to the symbol {@code Sym}.
168
/// If none found, returns None.
169
static Optional<unsigned> findArgIdxOfSymbol(ProgramStateRef CurrSt,
170
                                             const LocationContext *LCtx,
171
                                             SymbolRef &Sym,
172
487
                                             Optional<CallEventRef<>> CE) {
173
487
  if (!CE)
174
0
    return None;
175
487
176
1.00k
  
for (unsigned Idx = 0; 487
Idx < (*CE)->getNumArgs();
Idx++513
)
177
529
    if (const MemRegion *MR = (*CE)->getArgSVal(Idx).getAsRegion())
178
237
      if (const auto *TR = dyn_cast<TypedValueRegion>(MR))
179
100
        if (CurrSt->getSVal(MR, TR->getValueType()).getAsSymExpr() == Sym)
180
16
          return Idx;
181
487
182
487
  
return None471
;
183
487
}
184
185
23
static Optional<std::string> findMetaClassAlloc(const Expr *Callee) {
186
23
  if (const auto *ME = dyn_cast<MemberExpr>(Callee)) {
187
3
    if (ME->getMemberDecl()->getNameAsString() != "alloc")
188
2
      return None;
189
1
    const Expr *This = ME->getBase()->IgnoreParenImpCasts();
190
1
    if (const auto *DRE = dyn_cast<DeclRefExpr>(This)) {
191
1
      const ValueDecl *VD = DRE->getDecl();
192
1
      if (VD->getNameAsString() != "metaClass")
193
0
        return None;
194
1
195
1
      if (const auto *RD = dyn_cast<CXXRecordDecl>(VD->getDeclContext()))
196
1
        return RD->getNameAsString();
197
20
198
20
    }
199
1
  }
200
20
  return None;
201
20
}
202
203
32
static std::string findAllocatedObjectName(const Stmt *S, QualType QT) {
204
32
  if (const auto *CE = dyn_cast<CallExpr>(S))
205
23
    if (auto Out = findMetaClassAlloc(CE->getCallee()))
206
1
      return *Out;
207
31
  return getPrettyTypeName(QT);
208
31
}
209
210
static void generateDiagnosticsForCallLike(ProgramStateRef CurrSt,
211
                                           const LocationContext *LCtx,
212
                                           const RefVal &CurrV, SymbolRef &Sym,
213
                                           const Stmt *S,
214
487
                                           llvm::raw_string_ostream &os) {
215
487
  CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
216
487
  if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
217
253
    // Get the name of the callee (if it is available)
218
253
    // from the tracked SVal.
219
253
    SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
220
253
    const FunctionDecl *FD = X.getAsFunctionDecl();
221
253
222
253
    // If failed, try to get it from AST.
223
253
    if (!FD)
224
3
      FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
225
253
226
253
    if (const auto *MD = dyn_cast<CXXMethodDecl>(CE->getCalleeDecl())) {
227
13
      os << "Call to method '" << MD->getQualifiedNameAsString() << '\'';
228
240
    } else if (FD) {
229
240
      os << "Call to function '" << FD->getQualifiedNameAsString() << '\'';
230
240
    } else {
231
0
      os << "function call";
232
0
    }
233
253
  } else 
if (234
isa<CXXNewExpr>(S)234
) {
234
9
    os << "Operator 'new'";
235
225
  } else {
236
225
    assert(isa<ObjCMessageExpr>(S));
237
225
    CallEventRef<ObjCMethodCall> Call =
238
225
        Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
239
225
240
225
    switch (Call->getMessageKind()) {
241
225
    case OCM_Message:
242
213
      os << "Method";
243
213
      break;
244
225
    case OCM_PropertyAccess:
245
6
      os << "Property";
246
6
      break;
247
225
    case OCM_Subscript:
248
6
      os << "Subscript";
249
6
      break;
250
487
    }
251
487
  }
252
487
253
487
  Optional<CallEventRef<>> CE = Mgr.getCall(S, CurrSt, LCtx);
254
487
  auto Idx = findArgIdxOfSymbol(CurrSt, LCtx, Sym, CE);
255
487
256
487
  // If index is not found, we assume that the symbol was returned.
257
487
  if (!Idx) {
258
471
    os << " returns ";
259
471
  } else {
260
16
    os << " writes ";
261
16
  }
262
487
263
487
  if (CurrV.getObjKind() == ObjKind::CF) {
264
237
    os << "a Core Foundation object of type '"
265
237
       << Sym->getType().getAsString() << "' with a ";
266
250
  } else if (CurrV.getObjKind() == ObjKind::OS) {
267
32
    os << "an OSObject of type '" << findAllocatedObjectName(S, Sym->getType())
268
32
       << "' with a ";
269
218
  } else if (CurrV.getObjKind() == ObjKind::Generalized) {
270
3
    os << "an object of type '" << Sym->getType().getAsString()
271
3
       << "' with a ";
272
215
  } else {
273
215
    assert(CurrV.getObjKind() == ObjKind::ObjC);
274
215
    QualType T = Sym->getType();
275
215
    if (!isa<ObjCObjectPointerType>(T)) {
276
62
      os << "an Objective-C object with a ";
277
153
    } else {
278
153
      const ObjCObjectPointerType *PT = cast<ObjCObjectPointerType>(T);
279
153
      os << "an instance of " << PT->getPointeeType().getAsString()
280
153
         << " with a ";
281
153
    }
282
215
  }
283
487
284
487
  if (CurrV.isOwned()) {
285
408
    os << "+1 retain count";
286
408
  } else {
287
79
    assert(CurrV.isNotOwned());
288
79
    os << "+0 retain count";
289
79
  }
290
487
291
487
  if (Idx) {
292
16
    os << " into an out parameter '";
293
16
    const ParmVarDecl *PVD = (*CE)->parameters()[*Idx];
294
16
    PVD->getNameForDiagnostic(os, PVD->getASTContext().getPrintingPolicy(),
295
16
                              /*Qualified=*/false);
296
16
    os << "'";
297
16
298
16
    QualType RT = (*CE)->getResultType();
299
16
    if (!RT.isNull() && !RT->isVoidType()) {
300
6
      SVal RV = (*CE)->getReturnValue();
301
6
      if (CurrSt->isNull(RV).isConstrainedTrue()) {
302
2
        os << " (assuming the call returns zero)";
303
4
      } else if (CurrSt->isNonNull(RV).isConstrainedTrue()) {
304
4
        os << " (assuming the call returns non-zero)";
305
4
      }
306
6
307
6
    }
308
16
  }
309
487
}
310
311
namespace clang {
312
namespace ento {
313
namespace retaincountchecker {
314
315
class RefCountReportVisitor : public BugReporterVisitor {
316
protected:
317
  SymbolRef Sym;
318
319
public:
320
589
  RefCountReportVisitor(SymbolRef sym) : Sym(sym) {}
321
322
589
  void Profile(llvm::FoldingSetNodeID &ID) const override {
323
589
    static int x = 0;
324
589
    ID.AddPointer(&x);
325
589
    ID.AddPointer(Sym);
326
589
  }
327
328
  std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
329
                                                 BugReporterContext &BRC,
330
                                                 BugReport &BR) override;
331
332
  std::shared_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
333
                                                  const ExplodedNode *N,
334
                                                  BugReport &BR) override;
335
};
336
337
class RefLeakReportVisitor : public RefCountReportVisitor {
338
public:
339
420
  RefLeakReportVisitor(SymbolRef sym) : RefCountReportVisitor(sym) {}
340
341
  std::shared_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
342
                                                  const ExplodedNode *N,
343
                                                  BugReport &BR) override;
344
};
345
346
} // end namespace retaincountchecker
347
} // end namespace ento
348
} // end namespace clang
349
350
351
/// Find the first node with the parent stack frame.
352
108
static const ExplodedNode *getCalleeNode(const ExplodedNode *Pred) {
353
108
  const StackFrameContext *SC = Pred->getStackFrame();
354
108
  if (SC->inTopFrame())
355
0
    return nullptr;
356
108
  const StackFrameContext *PC = SC->getParent()->getStackFrame();
357
108
  if (!PC)
358
0
    return nullptr;
359
108
360
108
  const ExplodedNode *N = Pred;
361
2.23k
  while (N && N->getStackFrame() != PC) {
362
2.13k
    N = N->getFirstPred();
363
2.13k
  }
364
108
  return N;
365
108
}
366
367
368
/// Insert a diagnostic piece at function exit
369
/// if a function parameter is annotated as "os_consumed",
370
/// but it does not actually consume the reference.
371
static std::shared_ptr<PathDiagnosticEventPiece>
372
annotateConsumedSummaryMismatch(const ExplodedNode *N,
373
                                CallExitBegin &CallExitLoc,
374
                                const SourceManager &SM,
375
108
                                CallEventManager &CEMgr) {
376
108
377
108
  const ExplodedNode *CN = getCalleeNode(N);
378
108
  if (!CN)
379
0
    return nullptr;
380
108
381
108
  CallEventRef<> Call = CEMgr.getCaller(N->getStackFrame(), N->getState());
382
108
383
108
  std::string sbuf;
384
108
  llvm::raw_string_ostream os(sbuf);
385
108
  ArrayRef<const ParmVarDecl *> Parameters = Call->parameters();
386
161
  for (unsigned I=0; I < Call->getNumArgs() && 
I < Parameters.size()53
;
++I53
) {
387
53
    const ParmVarDecl *PVD = Parameters[I];
388
53
389
53
    if (!PVD->hasAttr<OSConsumedAttr>())
390
51
      continue;
391
2
392
2
    if (SymbolRef SR = Call->getArgSVal(I).getAsLocSymbol()) {
393
2
      const RefVal *CountBeforeCall = getRefBinding(CN->getState(), SR);
394
2
      const RefVal *CountAtExit = getRefBinding(N->getState(), SR);
395
2
396
2
      if (!CountBeforeCall || !CountAtExit)
397
0
        continue;
398
2
399
2
      unsigned CountBefore = CountBeforeCall->getCount();
400
2
      unsigned CountAfter = CountAtExit->getCount();
401
2
402
2
      bool AsExpected = CountBefore > 0 && CountAfter == CountBefore - 1;
403
2
      if (!AsExpected) {
404
2
        os << "Parameter '";
405
2
        PVD->getNameForDiagnostic(os, PVD->getASTContext().getPrintingPolicy(),
406
2
                                  /*Qualified=*/false);
407
2
        os << "' is marked as consuming, but the function did not consume "
408
2
           << "the reference\n";
409
2
      }
410
2
    }
411
2
  }
412
108
413
108
  if (os.str().empty())
414
106
    return nullptr;
415
2
416
2
  PathDiagnosticLocation L = PathDiagnosticLocation::create(CallExitLoc, SM);
417
2
  return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
418
2
}
419
420
/// Annotate the parameter at the analysis entry point.
421
static std::shared_ptr<PathDiagnosticEventPiece>
422
annotateStartParameter(const ExplodedNode *N, SymbolRef Sym,
423
24.7k
                       const SourceManager &SM) {
424
24.7k
  auto PP = N->getLocationAs<BlockEdge>();
425
24.7k
  if (!PP)
426
24.0k
    return nullptr;
427
726
428
726
  const CFGBlock *Src = PP->getSrc();
429
726
  const RefVal *CurrT = getRefBinding(N->getState(), Sym);
430
726
431
726
  if (&Src->getParent()->getEntry() != Src || 
!CurrT161
||
432
726
      
getRefBinding(N->getFirstPred()->getState(), Sym)78
)
433
713
    return nullptr;
434
13
435
13
  const auto *VR = cast<VarRegion>(cast<SymbolRegionValue>(Sym)->getRegion());
436
13
  const auto *PVD = cast<ParmVarDecl>(VR->getDecl());
437
13
  PathDiagnosticLocation L = PathDiagnosticLocation(PVD, SM);
438
13
439
13
  std::string s;
440
13
  llvm::raw_string_ostream os(s);
441
13
  os << "Parameter '" << PVD->getNameAsString() << "' starts at +";
442
13
  if (CurrT->getCount() == 1) {
443
5
    os << "1, as it is marked as consuming";
444
8
  } else {
445
8
    assert(CurrT->getCount() == 0);
446
8
    os << "0";
447
8
  }
448
13
  return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
449
13
}
450
451
std::shared_ptr<PathDiagnosticPiece>
452
RefCountReportVisitor::VisitNode(const ExplodedNode *N,
453
24.7k
                              BugReporterContext &BRC, BugReport &BR) {
454
24.7k
455
24.7k
  const auto &BT = static_cast<const RefCountBug&>(BR.getBugType());
456
24.7k
  const auto *Checker =
457
24.7k
      static_cast<const RetainCountChecker *>(BT.getChecker());
458
24.7k
459
24.7k
  bool IsFreeUnowned = BT.getBugType() == RefCountBug::FreeNotOwned ||
460
24.7k
                       
BT.getBugType() == RefCountBug::DeallocNotOwned24.6k
;
461
24.7k
462
24.7k
  const SourceManager &SM = BRC.getSourceManager();
463
24.7k
  CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
464
24.7k
  if (auto CE = N->getLocationAs<CallExitBegin>())
465
108
    if (auto PD = annotateConsumedSummaryMismatch(N, *CE, SM, CEMgr))
466
2
      return PD;
467
24.7k
468
24.7k
  if (auto PD = annotateStartParameter(N, Sym, SM))
469
13
    return PD;
470
24.7k
471
24.7k
  // FIXME: We will eventually need to handle non-statement-based events
472
24.7k
  // (__attribute__((cleanup))).
473
24.7k
  if (!N->getLocation().getAs<StmtPoint>())
474
1.98k
    return nullptr;
475
22.7k
476
22.7k
  // Check if the type state has changed.
477
22.7k
  const ExplodedNode *PrevNode = N->getFirstPred();
478
22.7k
  ProgramStateRef PrevSt = PrevNode->getState();
479
22.7k
  ProgramStateRef CurrSt = N->getState();
480
22.7k
  const LocationContext *LCtx = N->getLocationContext();
481
22.7k
482
22.7k
  const RefVal* CurrT = getRefBinding(CurrSt, Sym);
483
22.7k
  if (!CurrT)
484
12.5k
    return nullptr;
485
10.2k
486
10.2k
  const RefVal &CurrV = *CurrT;
487
10.2k
  const RefVal *PrevT = getRefBinding(PrevSt, Sym);
488
10.2k
489
10.2k
  // Create a string buffer to constain all the useful things we want
490
10.2k
  // to tell the user.
491
10.2k
  std::string sbuf;
492
10.2k
  llvm::raw_string_ostream os(sbuf);
493
10.2k
494
10.2k
  if (PrevT && 
IsFreeUnowned9.70k
&&
CurrV.isNotOwned()31
&&
PrevT->isOwned()9
) {
495
1
    os << "Object is now not exclusively owned";
496
1
    auto Pos = PathDiagnosticLocation::create(N->getLocation(), SM);
497
1
    return std::make_shared<PathDiagnosticEventPiece>(Pos, os.str());
498
1
  }
499
10.2k
500
10.2k
  // This is the allocation site since the previous node had no bindings
501
10.2k
  // for this symbol.
502
10.2k
  if (!PrevT) {
503
523
    const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
504
523
505
523
    if (isa<ObjCIvarRefExpr>(S) &&
506
523
        
isSynthesizedAccessor(LCtx->getStackFrame())6
) {
507
6
      S = LCtx->getStackFrame()->getCallSite();
508
6
    }
509
523
510
523
    if (isa<ObjCArrayLiteral>(S)) {
511
11
      os << "NSArray literal is an object with a +0 retain count";
512
512
    } else if (isa<ObjCDictionaryLiteral>(S)) {
513
5
      os << "NSDictionary literal is an object with a +0 retain count";
514
507
    } else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
515
20
      if (isNumericLiteralExpression(BL->getSubExpr()))
516
8
        os << "NSNumber literal is an object with a +0 retain count";
517
12
      else {
518
12
        const ObjCInterfaceDecl *BoxClass = nullptr;
519
12
        if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
520
12
          BoxClass = Method->getClassInterface();
521
12
522
12
        // We should always be able to find the boxing class interface,
523
12
        // but consider this future-proofing.
524
12
        if (BoxClass) {
525
12
          os << *BoxClass << " b";
526
12
        } else {
527
0
          os << "B";
528
0
        }
529
12
530
12
        os << "oxed expression produces an object with a +0 retain count";
531
12
      }
532
487
    } else if (isa<ObjCIvarRefExpr>(S)) {
533
0
      os << "Object loaded from instance variable";
534
487
    } else {
535
487
      generateDiagnosticsForCallLike(CurrSt, LCtx, CurrV, Sym, S, os);
536
487
    }
537
523
538
523
    PathDiagnosticLocation Pos(S, SM, N->getLocationContext());
539
523
    return std::make_shared<PathDiagnosticEventPiece>(Pos, os.str());
540
523
  }
541
9.70k
542
9.70k
  // Gather up the effects that were performed on the object at this
543
9.70k
  // program point
544
9.70k
  bool DeallocSent = false;
545
9.70k
546
9.70k
  const ProgramPointTag *Tag = N->getLocation().getTag();
547
9.70k
548
9.70k
  if (Tag == &Checker->getCastFailTag()) {
549
2
    os << "Assuming dynamic cast returns null due to type mismatch";
550
2
  }
551
9.70k
552
9.70k
  if (Tag == &Checker->getDeallocSentTag()) {
553
5
    // We only have summaries attached to nodes after evaluating CallExpr and
554
5
    // ObjCMessageExprs.
555
5
    const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
556
5
557
5
    if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
558
0
      // Iterate through the parameter expressions and see if the symbol
559
0
      // was ever passed as an argument.
560
0
      unsigned i = 0;
561
0
562
0
      for (auto AI=CE->arg_begin(), AE=CE->arg_end(); AI!=AE; ++AI, ++i) {
563
0
564
0
        // Retrieve the value of the argument.  Is it the symbol
565
0
        // we are interested in?
566
0
        if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
567
0
          continue;
568
0
569
0
        // We have an argument.  Get the effect!
570
0
        DeallocSent = true;
571
0
      }
572
5
    } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
573
5
      if (const Expr *receiver = ME->getInstanceReceiver()) {
574
5
        if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
575
5
              .getAsLocSymbol() == Sym) {
576
5
          // The symbol we are tracking is the receiver.
577
5
          DeallocSent = true;
578
5
        }
579
5
      }
580
5
    }
581
5
  }
582
9.70k
583
9.70k
  if (!shouldGenerateNote(os, PrevT, CurrV, DeallocSent))
584
22
    return nullptr;
585
9.67k
586
9.67k
  if (os.str().empty())
587
9.40k
    return nullptr; // We have nothing to say!
588
274
589
274
  const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
590
274
  PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
591
274
                                N->getLocationContext());
592
274
  auto P = std::make_shared<PathDiagnosticEventPiece>(Pos, os.str());
593
274
594
274
  // Add the range by scanning the children of the statement for any bindings
595
274
  // to Sym.
596
274
  for (const Stmt *Child : S->children())
597
382
    if (const Expr *Exp = dyn_cast_or_null<Expr>(Child))
598
382
      if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
599
259
        P->addRange(Exp->getSourceRange());
600
259
        break;
601
259
      }
602
274
603
274
  return std::move(P);
604
274
}
605
606
790
static Optional<std::string> describeRegion(const MemRegion *MR) {
607
790
  if (const auto *VR = dyn_cast_or_null<VarRegion>(MR))
608
545
    return std::string(VR->getDecl()->getName());
609
245
  // Once we support more storage locations for bindings,
610
245
  // this would need to be improved.
611
245
  return None;
612
245
}
613
614
namespace {
615
// Find the first node in the current function context that referred to the
616
// tracked symbol and the memory location that value was stored to. Note, the
617
// value is only reported if the allocation occurred in the same function as
618
// the leak. The function can also return a location context, which should be
619
// treated as interesting.
620
struct AllocationInfo {
621
  const ExplodedNode* N;
622
  const MemRegion *R;
623
  const LocationContext *InterestingMethodContext;
624
  AllocationInfo(const ExplodedNode *InN,
625
                 const MemRegion *InR,
626
                 const LocationContext *InInterestingMethodContext) :
627
790
    N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
628
};
629
} // end anonymous namespace
630
631
static AllocationInfo GetAllocationSite(ProgramStateManager &StateMgr,
632
790
                                        const ExplodedNode *N, SymbolRef Sym) {
633
790
  const ExplodedNode *AllocationNode = N;
634
790
  const ExplodedNode *AllocationNodeInCurrentOrParentContext = N;
635
790
  const MemRegion *FirstBinding = nullptr;
636
790
  const LocationContext *LeakContext = N->getLocationContext();
637
790
638
790
  // The location context of the init method called on the leaked object, if
639
790
  // available.
640
790
  const LocationContext *InitMethodContext = nullptr;
641
790
642
17.4k
  while (N) {
643
17.4k
    ProgramStateRef St = N->getState();
644
17.4k
    const LocationContext *NContext = N->getLocationContext();
645
17.4k
646
17.4k
    if (!getRefBinding(St, Sym))
647
790
      break;
648
16.6k
649
16.6k
    StoreManager::FindUniqueBinding FB(Sym);
650
16.6k
    StateMgr.iterBindings(St, FB);
651
16.6k
652
16.6k
    if (FB) {
653
9.07k
      const MemRegion *R = FB.getRegion();
654
9.07k
      // Do not show local variables belonging to a function other than
655
9.07k
      // where the error is reported.
656
9.07k
      if (auto MR = dyn_cast<StackSpaceRegion>(R->getMemorySpace()))
657
9.07k
        if (MR->getStackFrame() == LeakContext->getStackFrame())
658
7.99k
          FirstBinding = R;
659
9.07k
    }
660
16.6k
661
16.6k
    // AllocationNode is the last node in which the symbol was tracked.
662
16.6k
    AllocationNode = N;
663
16.6k
664
16.6k
    // AllocationNodeInCurrentContext, is the last node in the current or
665
16.6k
    // parent context in which the symbol was tracked.
666
16.6k
    //
667
16.6k
    // Note that the allocation site might be in the parent context. For example,
668
16.6k
    // the case where an allocation happens in a block that captures a reference
669
16.6k
    // to it and that reference is overwritten/dropped by another call to
670
16.6k
    // the block.
671
16.6k
    if (NContext == LeakContext || 
NContext->isParentOf(LeakContext)2.53k
)
672
14.2k
      AllocationNodeInCurrentOrParentContext = N;
673
16.6k
674
16.6k
    // Find the last init that was called on the given symbol and store the
675
16.6k
    // init method's location context.
676
16.6k
    if (!InitMethodContext)
677
16.5k
      if (auto CEP = N->getLocation().getAs<CallEnter>()) {
678
98
        const Stmt *CE = CEP->getCallExpr();
679
98
        if (const auto *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
680
12
          const Stmt *RecExpr = ME->getInstanceReceiver();
681
12
          if (RecExpr) {
682
12
            SVal RecV = St->getSVal(RecExpr, NContext);
683
12
            if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
684
12
              InitMethodContext = CEP->getCalleeContext();
685
12
          }
686
12
        }
687
98
      }
688
16.6k
689
16.6k
    N = N->getFirstPred();
690
16.6k
  }
691
790
692
790
  // If we are reporting a leak of the object that was allocated with alloc,
693
790
  // mark its init method as interesting.
694
790
  const LocationContext *InterestingMethodContext = nullptr;
695
790
  if (InitMethodContext) {
696
12
    const ProgramPoint AllocPP = AllocationNode->getLocation();
697
12
    if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
698
12
      if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
699
12
        if (ME->getMethodFamily() == OMF_alloc)
700
12
          InterestingMethodContext = InitMethodContext;
701
12
  }
702
790
703
790
  // If allocation happened in a function different from the leak node context,
704
790
  // do not report the binding.
705
790
  assert(N && "Could not find allocation node");
706
790
707
790
  if (AllocationNodeInCurrentOrParentContext &&
708
790
      AllocationNodeInCurrentOrParentContext->getLocationContext() !=
709
790
      LeakContext)
710
4
    FirstBinding = nullptr;
711
790
712
790
  return AllocationInfo(AllocationNodeInCurrentOrParentContext,
713
790
                        FirstBinding,
714
790
                        InterestingMethodContext);
715
790
}
716
717
std::shared_ptr<PathDiagnosticPiece>
718
RefCountReportVisitor::getEndPath(BugReporterContext &BRC,
719
166
                               const ExplodedNode *EndN, BugReport &BR) {
720
166
  BR.markInteresting(Sym);
721
166
  return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
722
166
}
723
724
std::shared_ptr<PathDiagnosticPiece>
725
RefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
726
370
                                   const ExplodedNode *EndN, BugReport &BR) {
727
370
728
370
  // Tell the BugReporterContext to report cases when the tracked symbol is
729
370
  // assigned to different variables, etc.
730
370
  BR.markInteresting(Sym);
731
370
732
370
  // We are reporting a leak.  Walk up the graph to get to the first node where
733
370
  // the symbol appeared, and also get the first VarDecl that tracked object
734
370
  // is stored to.
735
370
  AllocationInfo AllocI = GetAllocationSite(BRC.getStateManager(), EndN, Sym);
736
370
737
370
  const MemRegion* FirstBinding = AllocI.R;
738
370
  BR.markInteresting(AllocI.InterestingMethodContext);
739
370
740
370
  SourceManager& SM = BRC.getSourceManager();
741
370
742
370
  // Compute an actual location for the leak.  Sometimes a leak doesn't
743
370
  // occur at an actual statement (e.g., transition between blocks; end
744
370
  // of function) so we need to walk the graph and compute a real location.
745
370
  const ExplodedNode *LeakN = EndN;
746
370
  PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
747
370
748
370
  std::string sbuf;
749
370
  llvm::raw_string_ostream os(sbuf);
750
370
751
370
  os << "Object leaked: ";
752
370
753
370
  Optional<std::string> RegionDescription = describeRegion(FirstBinding);
754
370
  if (RegionDescription) {
755
248
    os << "object allocated and stored into '" << *RegionDescription << '\'';
756
248
  } else {
757
122
    os << "allocated object of type '" << getPrettyTypeName(Sym->getType())
758
122
       << "'";
759
122
  }
760
370
761
370
  // Get the retain count.
762
370
  const RefVal* RV = getRefBinding(EndN->getState(), Sym);
763
370
  assert(RV);
764
370
765
370
  if (RV->getKind() == RefVal::ErrorLeakReturned) {
766
53
    // FIXME: Per comments in rdar://6320065, "create" only applies to CF
767
53
    // objects.  Only "copy", "alloc", "retain" and "new" transfer ownership
768
53
    // to the caller for NS objects.
769
53
    const Decl *D = &EndN->getCodeDecl();
770
53
771
53
    os << (isa<ObjCMethodDecl>(D) ? 
" is returned from a method "32
772
53
                                  : 
" is returned from a function "21
);
773
53
774
53
    if (D->hasAttr<CFReturnsNotRetainedAttr>()) {
775
1
      os << "that is annotated as CF_RETURNS_NOT_RETAINED";
776
52
    } else if (D->hasAttr<NSReturnsNotRetainedAttr>()) {
777
3
      os << "that is annotated as NS_RETURNS_NOT_RETAINED";
778
49
    } else if (D->hasAttr<OSReturnsNotRetainedAttr>()) {
779
0
      os << "that is annotated as OS_RETURNS_NOT_RETAINED";
780
49
    } else {
781
49
      if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
782
29
        if (BRC.getASTContext().getLangOpts().ObjCAutoRefCount) {
783
1
          os << "managed by Automatic Reference Counting";
784
28
        } else {
785
28
          os << "whose name ('" << MD->getSelector().getAsString()
786
28
             << "') does not start with "
787
28
                "'copy', 'mutableCopy', 'alloc' or 'new'."
788
28
                "  This violates the naming convention rules"
789
28
                " given in the Memory Management Guide for Cocoa";
790
28
        }
791
29
      } else {
792
20
        const FunctionDecl *FD = cast<FunctionDecl>(D);
793
20
        ObjKind K = RV->getObjKind();
794
20
        if (K == ObjKind::ObjC || K == ObjKind::CF) {
795
19
          os << "whose name ('" << *FD
796
19
             << "') does not contain 'Copy' or 'Create'.  This violates the "
797
19
                "naming"
798
19
                " convention rules given in the Memory Management Guide for "
799
19
                "Core"
800
19
                " Foundation";
801
19
        } else 
if (1
RV->getObjKind() == ObjKind::OS1
) {
802
1
          std::string FuncName = FD->getNameAsString();
803
1
          os << "whose name ('" << FuncName
804
1
            << "') starts with '" << StringRef(FuncName).substr(0, 3) << "'";
805
1
        }
806
20
      }
807
49
    }
808
317
  } else {
809
317
    os << " is not referenced later in this execution path and has a retain "
810
317
          "count of +" << RV->getCount();
811
317
  }
812
370
813
370
  return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
814
370
}
815
816
RefCountReport::RefCountReport(const RefCountBug &D, const LangOptions &LOpts,
817
                               ExplodedNode *n, SymbolRef sym,
818
                               bool isLeak)
819
557
    : BugReport(D, D.getDescription(), n), Sym(sym), isLeak(isLeak) {
820
557
  if (!isLeak)
821
137
    addVisitor(llvm::make_unique<RefCountReportVisitor>(sym));
822
557
}
823
824
RefCountReport::RefCountReport(const RefCountBug &D, const LangOptions &LOpts,
825
                               ExplodedNode *n, SymbolRef sym,
826
                               StringRef endText)
827
32
    : BugReport(D, D.getDescription(), endText, n) {
828
32
829
32
  addVisitor(llvm::make_unique<RefCountReportVisitor>(sym));
830
32
}
831
832
121
void RefLeakReport::deriveParamLocation(CheckerContext &Ctx, SymbolRef sym) {
833
121
  const SourceManager& SMgr = Ctx.getSourceManager();
834
121
835
121
  if (!sym->getOriginRegion())
836
113
    return;
837
8
838
8
  auto *Region = dyn_cast<DeclRegion>(sym->getOriginRegion());
839
8
  if (Region) {
840
8
    const Decl *PDecl = Region->getDecl();
841
8
    if (PDecl && isa<ParmVarDecl>(PDecl)) {
842
8
      PathDiagnosticLocation ParamLocation =
843
8
          PathDiagnosticLocation::create(PDecl, SMgr);
844
8
      Location = ParamLocation;
845
8
      UniqueingLocation = ParamLocation;
846
8
      UniqueingDecl = Ctx.getLocationContext()->getDecl();
847
8
    }
848
8
  }
849
8
}
850
851
void RefLeakReport::deriveAllocLocation(CheckerContext &Ctx,
852
420
                                          SymbolRef sym) {
853
420
  // Most bug reports are cached at the location where they occurred.
854
420
  // With leaks, we want to unique them by the location where they were
855
420
  // allocated, and only report a single path.  To do this, we need to find
856
420
  // the allocation site of a piece of tracked memory, which we do via a
857
420
  // call to GetAllocationSite.  This will walk the ExplodedGraph backwards.
858
420
  // Note that this is *not* the trimmed graph; we are guaranteed, however,
859
420
  // that all ancestor nodes that represent the allocation site have the
860
420
  // same SourceLocation.
861
420
  const ExplodedNode *AllocNode = nullptr;
862
420
863
420
  const SourceManager& SMgr = Ctx.getSourceManager();
864
420
865
420
  AllocationInfo AllocI =
866
420
      GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
867
420
868
420
  AllocNode = AllocI.N;
869
420
  AllocBinding = AllocI.R;
870
420
  markInteresting(AllocI.InterestingMethodContext);
871
420
872
420
  // Get the SourceLocation for the allocation site.
873
420
  // FIXME: This will crash the analyzer if an allocation comes from an
874
420
  // implicit call (ex: a destructor call).
875
420
  // (Currently there are no such allocations in Cocoa, though.)
876
420
  AllocStmt = PathDiagnosticLocation::getStmt(AllocNode);
877
420
878
420
  if (!AllocStmt) {
879
8
    AllocBinding = nullptr;
880
8
    return;
881
8
  }
882
412
883
412
  PathDiagnosticLocation AllocLocation =
884
412
    PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
885
412
                                        AllocNode->getLocationContext());
886
412
  Location = AllocLocation;
887
412
888
412
  // Set uniqieing info, which will be used for unique the bug reports. The
889
412
  // leaks should be uniqued on the allocation site.
890
412
  UniqueingLocation = AllocLocation;
891
412
  UniqueingDecl = AllocNode->getLocationContext()->getDecl();
892
412
}
893
894
420
void RefLeakReport::createDescription(CheckerContext &Ctx) {
895
420
  assert(Location.isValid() && UniqueingDecl && UniqueingLocation.isValid());
896
420
  Description.clear();
897
420
  llvm::raw_string_ostream os(Description);
898
420
  os << "Potential leak of an object";
899
420
900
420
  Optional<std::string> RegionDescription = describeRegion(AllocBinding);
901
420
  if (RegionDescription) {
902
297
    os << " stored into '" << *RegionDescription << '\'';
903
297
  } else {
904
123
905
123
    // If we can't figure out the name, just supply the type information.
906
123
    os << " of type '" << getPrettyTypeName(Sym->getType()) << "'";
907
123
  }
908
420
}
909
910
RefLeakReport::RefLeakReport(const RefCountBug &D, const LangOptions &LOpts,
911
                             ExplodedNode *n, SymbolRef sym,
912
                             CheckerContext &Ctx)
913
420
    : RefCountReport(D, LOpts, n, sym, /*isLeak=*/true) {
914
420
915
420
  deriveAllocLocation(Ctx, sym);
916
420
  if (!AllocBinding)
917
121
    deriveParamLocation(Ctx, sym);
918
420
919
420
  createDescription(Ctx);
920
420
921
420
  addVisitor(llvm::make_unique<RefLeakReportVisitor>(sym));
922
420
}