blob: b4f58b55a3ecb53e39be8df3d6dacfc1b7aadc6a [file] [log] [blame]
George Karpenkov70c2ee32018-08-17 21:41:07 +00001// RetainCountDiagnostics.cpp - Checks for leaks and other issues -*- C++ -*--//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines diagnostics for RetainCountChecker, which implements
11// a reference count checker for Core Foundation and Cocoa on (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
15#include "RetainCountDiagnostics.h"
16#include "RetainCountChecker.h"
17
18using namespace clang;
19using namespace ento;
20using namespace retaincountchecker;
21
22static bool isNumericLiteralExpression(const Expr *E) {
23 // FIXME: This set of cases was copied from SemaExprObjC.
24 return isa<IntegerLiteral>(E) ||
25 isa<CharacterLiteral>(E) ||
26 isa<FloatingLiteral>(E) ||
27 isa<ObjCBoolLiteralExpr>(E) ||
28 isa<CXXBoolLiteralExpr>(E);
29}
30
George Karpenkovf893ea12018-11-30 02:17:44 +000031/// If type represents a pointer to CXXRecordDecl,
32/// and is not a typedef, return the decl name.
33/// Otherwise, return the serialization of type.
Haojian Wuceff7302018-11-30 09:23:01 +000034static std::string getPrettyTypeName(QualType QT) {
George Karpenkovf893ea12018-11-30 02:17:44 +000035 QualType PT = QT->getPointeeType();
36 if (!PT.isNull() && !QT->getAs<TypedefType>())
37 if (const auto *RD = PT->getAsCXXRecordDecl())
38 return RD->getName();
39 return QT.getAsString();
40}
41
George Karpenkovb3303d72018-11-30 02:17:05 +000042/// Write information about the type state change to {@code os},
43/// return whether the note should be generated.
44static bool shouldGenerateNote(llvm::raw_string_ostream &os,
45 const RefVal *PrevT, const RefVal &CurrV,
George Karpenkov717c4c02019-01-10 18:15:17 +000046 bool DeallocSent) {
George Karpenkovb3303d72018-11-30 02:17:05 +000047 // Get the previous type state.
48 RefVal PrevV = *PrevT;
49
50 // Specially handle -dealloc.
George Karpenkov717c4c02019-01-10 18:15:17 +000051 if (DeallocSent) {
George Karpenkovb3303d72018-11-30 02:17:05 +000052 // Determine if the object's reference count was pushed to zero.
53 assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
54 // We may not have transitioned to 'release' if we hit an error.
55 // This case is handled elsewhere.
56 if (CurrV.getKind() == RefVal::Released) {
57 assert(CurrV.getCombinedCounts() == 0);
58 os << "Object released by directly sending the '-dealloc' message";
59 return true;
60 }
61 }
62
63 // Determine if the typestate has changed.
64 if (!PrevV.hasSameState(CurrV))
65 switch (CurrV.getKind()) {
66 case RefVal::Owned:
67 case RefVal::NotOwned:
68 if (PrevV.getCount() == CurrV.getCount()) {
69 // Did an autorelease message get sent?
70 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
71 return false;
72
73 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
74 os << "Object autoreleased";
75 return true;
76 }
77
78 if (PrevV.getCount() > CurrV.getCount())
79 os << "Reference count decremented.";
80 else
81 os << "Reference count incremented.";
82
83 if (unsigned Count = CurrV.getCount())
84 os << " The object now has a +" << Count << " retain count.";
85
86 return true;
87
88 case RefVal::Released:
89 if (CurrV.getIvarAccessHistory() ==
90 RefVal::IvarAccessHistory::ReleasedAfterDirectAccess &&
91 CurrV.getIvarAccessHistory() != PrevV.getIvarAccessHistory()) {
92 os << "Strong instance variable relinquished. ";
93 }
94 os << "Object released.";
95 return true;
96
97 case RefVal::ReturnedOwned:
98 // Autoreleases can be applied after marking a node ReturnedOwned.
99 if (CurrV.getAutoreleaseCount())
100 return false;
101
102 os << "Object returned to caller as an owning reference (single "
103 "retain count transferred to caller)";
104 return true;
105
106 case RefVal::ReturnedNotOwned:
107 os << "Object returned to caller with a +0 retain count";
108 return true;
109
110 default:
111 return false;
112 }
113 return true;
114}
115
George Karpenkovff014862018-12-11 01:13:40 +0000116static void generateDiagnosticsForCallLike(ProgramStateRef CurrSt,
117 const LocationContext *LCtx,
118 const RefVal &CurrV, SymbolRef &Sym,
119 const Stmt *S,
120 llvm::raw_string_ostream &os) {
George Karpenkov62db8862018-11-30 02:18:23 +0000121 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
122 // Get the name of the callee (if it is available)
123 // from the tracked SVal.
124 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
125 const FunctionDecl *FD = X.getAsFunctionDecl();
126
127 // If failed, try to get it from AST.
128 if (!FD)
129 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
130
131 if (const auto *MD = dyn_cast<CXXMethodDecl>(CE->getCalleeDecl())) {
132 os << "Call to method '" << MD->getQualifiedNameAsString() << '\'';
133 } else if (FD) {
134 os << "Call to function '" << FD->getQualifiedNameAsString() << '\'';
135 } else {
136 os << "function call";
137 }
George Karpenkovff014862018-12-11 01:13:40 +0000138 } else if (isa<CXXNewExpr>(S)) {
139 os << "Operator 'new'";
George Karpenkov62db8862018-11-30 02:18:23 +0000140 } else {
141 assert(isa<ObjCMessageExpr>(S));
142 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
143 CallEventRef<ObjCMethodCall> Call =
144 Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
145
146 switch (Call->getMessageKind()) {
147 case OCM_Message:
148 os << "Method";
149 break;
150 case OCM_PropertyAccess:
151 os << "Property";
152 break;
153 case OCM_Subscript:
154 os << "Subscript";
155 break;
156 }
157 }
158
George Karpenkov7e3016d2019-01-10 18:13:46 +0000159 if (CurrV.getObjKind() == ObjKind::CF) {
George Karpenkov4f64b382019-01-10 18:15:57 +0000160 os << " a Core Foundation object of type '"
161 << Sym->getType().getAsString() << "' with a ";
George Karpenkov7e3016d2019-01-10 18:13:46 +0000162 } else if (CurrV.getObjKind() == ObjKind::OS) {
George Karpenkov4f64b382019-01-10 18:15:57 +0000163 os << " an OSObject of type '" << getPrettyTypeName(Sym->getType())
164 << "' with a ";
George Karpenkov7e3016d2019-01-10 18:13:46 +0000165 } else if (CurrV.getObjKind() == ObjKind::Generalized) {
George Karpenkov4f64b382019-01-10 18:15:57 +0000166 os << " an object of type '" << Sym->getType().getAsString()
167 << "' with a ";
George Karpenkov62db8862018-11-30 02:18:23 +0000168 } else {
George Karpenkov7e3016d2019-01-10 18:13:46 +0000169 assert(CurrV.getObjKind() == ObjKind::ObjC);
George Karpenkov62db8862018-11-30 02:18:23 +0000170 QualType T = Sym->getType();
171 if (!isa<ObjCObjectPointerType>(T)) {
172 os << " returns an Objective-C object with a ";
173 } else {
174 const ObjCObjectPointerType *PT = cast<ObjCObjectPointerType>(T);
175 os << " returns an instance of " << PT->getPointeeType().getAsString()
176 << " with a ";
177 }
178 }
179
180 if (CurrV.isOwned()) {
181 os << "+1 retain count";
182 } else {
183 assert(CurrV.isNotOwned());
184 os << "+0 retain count";
185 }
186}
187
188namespace clang {
189namespace ento {
190namespace retaincountchecker {
191
George Karpenkov0bb17c42019-01-10 18:16:25 +0000192class RefCountReportVisitor : public BugReporterVisitor {
George Karpenkov62db8862018-11-30 02:18:23 +0000193protected:
194 SymbolRef Sym;
George Karpenkov62db8862018-11-30 02:18:23 +0000195
196public:
George Karpenkov0bb17c42019-01-10 18:16:25 +0000197 RefCountReportVisitor(SymbolRef sym) : Sym(sym) {}
George Karpenkov62db8862018-11-30 02:18:23 +0000198
199 void Profile(llvm::FoldingSetNodeID &ID) const override {
200 static int x = 0;
201 ID.AddPointer(&x);
202 ID.AddPointer(Sym);
203 }
204
205 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
206 BugReporterContext &BRC,
207 BugReport &BR) override;
208
209 std::shared_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
210 const ExplodedNode *N,
211 BugReport &BR) override;
212};
213
George Karpenkov0bb17c42019-01-10 18:16:25 +0000214class RefLeakReportVisitor : public RefCountReportVisitor {
George Karpenkov62db8862018-11-30 02:18:23 +0000215public:
George Karpenkov0bb17c42019-01-10 18:16:25 +0000216 RefLeakReportVisitor(SymbolRef sym) : RefCountReportVisitor(sym) {}
George Karpenkov62db8862018-11-30 02:18:23 +0000217
218 std::shared_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
219 const ExplodedNode *N,
220 BugReport &BR) override;
221};
222
223} // end namespace retaincountchecker
224} // end namespace ento
225} // end namespace clang
226
George Karpenkovff014862018-12-11 01:13:40 +0000227
228/// Find the first node with the parent stack frame.
229static const ExplodedNode *getCalleeNode(const ExplodedNode *Pred) {
230 const StackFrameContext *SC = Pred->getStackFrame();
231 if (SC->inTopFrame())
232 return nullptr;
233 const StackFrameContext *PC = SC->getParent()->getStackFrame();
234 if (!PC)
235 return nullptr;
236
237 const ExplodedNode *N = Pred;
238 while (N && N->getStackFrame() != PC) {
239 N = N->getFirstPred();
240 }
241 return N;
242}
243
244
245/// Insert a diagnostic piece at function exit
246/// if a function parameter is annotated as "os_consumed",
247/// but it does not actually consume the reference.
248static std::shared_ptr<PathDiagnosticEventPiece>
249annotateConsumedSummaryMismatch(const ExplodedNode *N,
250 CallExitBegin &CallExitLoc,
251 const SourceManager &SM,
252 CallEventManager &CEMgr) {
253
254 const ExplodedNode *CN = getCalleeNode(N);
255 if (!CN)
256 return nullptr;
257
258 CallEventRef<> Call = CEMgr.getCaller(N->getStackFrame(), N->getState());
259
260 std::string sbuf;
261 llvm::raw_string_ostream os(sbuf);
262 ArrayRef<const ParmVarDecl *> Parameters = Call->parameters();
263 for (unsigned I=0; I < Call->getNumArgs() && I < Parameters.size(); ++I) {
264 const ParmVarDecl *PVD = Parameters[I];
265
266 if (!PVD->hasAttr<OSConsumedAttr>())
George Karpenkovf5085322018-12-21 02:16:23 +0000267 continue;
George Karpenkovff014862018-12-11 01:13:40 +0000268
269 if (SymbolRef SR = Call->getArgSVal(I).getAsLocSymbol()) {
270 const RefVal *CountBeforeCall = getRefBinding(CN->getState(), SR);
271 const RefVal *CountAtExit = getRefBinding(N->getState(), SR);
272
273 if (!CountBeforeCall || !CountAtExit)
274 continue;
275
276 unsigned CountBefore = CountBeforeCall->getCount();
277 unsigned CountAfter = CountAtExit->getCount();
278
279 bool AsExpected = CountBefore > 0 && CountAfter == CountBefore - 1;
280 if (!AsExpected) {
281 os << "Parameter '";
282 PVD->getNameForDiagnostic(os, PVD->getASTContext().getPrintingPolicy(),
283 /*Qualified=*/false);
George Karpenkov79f03402018-12-21 19:13:28 +0000284 os << "' is marked as consuming, but the function did not consume "
George Karpenkovff014862018-12-11 01:13:40 +0000285 << "the reference\n";
286 }
287 }
288 }
289
290 if (os.str().empty())
291 return nullptr;
292
293 // FIXME: remove the code duplication with NoStoreFuncVisitor.
294 PathDiagnosticLocation L;
295 if (const ReturnStmt *RS = CallExitLoc.getReturnStmt()) {
296 L = PathDiagnosticLocation::createBegin(RS, SM, N->getLocationContext());
297 } else {
298 L = PathDiagnosticLocation(
299 Call->getRuntimeDefinition().getDecl()->getSourceRange().getEnd(), SM);
300 }
301
302 return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
303}
304
George Karpenkov70c2ee32018-08-17 21:41:07 +0000305std::shared_ptr<PathDiagnosticPiece>
George Karpenkov0bb17c42019-01-10 18:16:25 +0000306RefCountReportVisitor::VisitNode(const ExplodedNode *N,
George Karpenkov70c2ee32018-08-17 21:41:07 +0000307 BugReporterContext &BRC, BugReport &BR) {
George Karpenkov717c4c02019-01-10 18:15:17 +0000308
George Karpenkovff014862018-12-11 01:13:40 +0000309 const SourceManager &SM = BRC.getSourceManager();
310 CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
George Karpenkovf5085322018-12-21 02:16:23 +0000311 if (auto CE = N->getLocationAs<CallExitBegin>())
George Karpenkovff014862018-12-11 01:13:40 +0000312 if (auto PD = annotateConsumedSummaryMismatch(N, *CE, SM, CEMgr))
313 return PD;
George Karpenkovff014862018-12-11 01:13:40 +0000314
George Karpenkov70c2ee32018-08-17 21:41:07 +0000315 // FIXME: We will eventually need to handle non-statement-based events
316 // (__attribute__((cleanup))).
317 if (!N->getLocation().getAs<StmtPoint>())
318 return nullptr;
319
320 // Check if the type state has changed.
George Karpenkov62db8862018-11-30 02:18:23 +0000321 const ExplodedNode *PrevNode = N->getFirstPred();
322 ProgramStateRef PrevSt = PrevNode->getState();
George Karpenkov70c2ee32018-08-17 21:41:07 +0000323 ProgramStateRef CurrSt = N->getState();
324 const LocationContext *LCtx = N->getLocationContext();
325
326 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
327 if (!CurrT) return nullptr;
328
329 const RefVal &CurrV = *CurrT;
330 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
331
332 // Create a string buffer to constain all the useful things we want
333 // to tell the user.
334 std::string sbuf;
335 llvm::raw_string_ostream os(sbuf);
336
337 // This is the allocation site since the previous node had no bindings
338 // for this symbol.
339 if (!PrevT) {
340 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
341
342 if (isa<ObjCIvarRefExpr>(S) &&
343 isSynthesizedAccessor(LCtx->getStackFrame())) {
344 S = LCtx->getStackFrame()->getCallSite();
345 }
346
347 if (isa<ObjCArrayLiteral>(S)) {
348 os << "NSArray literal is an object with a +0 retain count";
George Karpenkovb3303d72018-11-30 02:17:05 +0000349 } else if (isa<ObjCDictionaryLiteral>(S)) {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000350 os << "NSDictionary literal is an object with a +0 retain count";
George Karpenkovb3303d72018-11-30 02:17:05 +0000351 } else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000352 if (isNumericLiteralExpression(BL->getSubExpr()))
353 os << "NSNumber literal is an object with a +0 retain count";
354 else {
355 const ObjCInterfaceDecl *BoxClass = nullptr;
356 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
357 BoxClass = Method->getClassInterface();
358
359 // We should always be able to find the boxing class interface,
360 // but consider this future-proofing.
George Karpenkovb3303d72018-11-30 02:17:05 +0000361 if (BoxClass) {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000362 os << *BoxClass << " b";
George Karpenkovb3303d72018-11-30 02:17:05 +0000363 } else {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000364 os << "B";
George Karpenkovb3303d72018-11-30 02:17:05 +0000365 }
George Karpenkov70c2ee32018-08-17 21:41:07 +0000366
367 os << "oxed expression produces an object with a +0 retain count";
368 }
George Karpenkovb3303d72018-11-30 02:17:05 +0000369 } else if (isa<ObjCIvarRefExpr>(S)) {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000370 os << "Object loaded from instance variable";
George Karpenkovb3303d72018-11-30 02:17:05 +0000371 } else {
George Karpenkov62db8862018-11-30 02:18:23 +0000372 generateDiagnosticsForCallLike(CurrSt, LCtx, CurrV, Sym, S, os);
George Karpenkov70c2ee32018-08-17 21:41:07 +0000373 }
374
George Karpenkovff014862018-12-11 01:13:40 +0000375 PathDiagnosticLocation Pos(S, SM, N->getLocationContext());
George Karpenkov70c2ee32018-08-17 21:41:07 +0000376 return std::make_shared<PathDiagnosticEventPiece>(Pos, os.str());
377 }
378
379 // Gather up the effects that were performed on the object at this
380 // program point
George Karpenkov717c4c02019-01-10 18:15:17 +0000381 bool DeallocSent = false;
382
383 if (N->getLocation().getTag() &&
384 N->getLocation().getTag()->getTagDescription().contains(
385 RetainCountChecker::DeallocTagDescription)) {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000386 // We only have summaries attached to nodes after evaluating CallExpr and
387 // ObjCMessageExprs.
388 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
389
390 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
391 // Iterate through the parameter expressions and see if the symbol
392 // was ever passed as an argument.
393 unsigned i = 0;
394
George Karpenkovb3303d72018-11-30 02:17:05 +0000395 for (auto AI=CE->arg_begin(), AE=CE->arg_end(); AI!=AE; ++AI, ++i) {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000396
397 // Retrieve the value of the argument. Is it the symbol
398 // we are interested in?
399 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
400 continue;
401
402 // We have an argument. Get the effect!
George Karpenkov717c4c02019-01-10 18:15:17 +0000403 DeallocSent = true;
George Karpenkov70c2ee32018-08-17 21:41:07 +0000404 }
405 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
406 if (const Expr *receiver = ME->getInstanceReceiver()) {
407 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
408 .getAsLocSymbol() == Sym) {
409 // The symbol we are tracking is the receiver.
George Karpenkov717c4c02019-01-10 18:15:17 +0000410 DeallocSent = true;
George Karpenkov70c2ee32018-08-17 21:41:07 +0000411 }
412 }
413 }
414 }
415
George Karpenkov717c4c02019-01-10 18:15:17 +0000416 if (!shouldGenerateNote(os, PrevT, CurrV, DeallocSent))
George Karpenkovb3303d72018-11-30 02:17:05 +0000417 return nullptr;
George Karpenkov70c2ee32018-08-17 21:41:07 +0000418
419 if (os.str().empty())
420 return nullptr; // We have nothing to say!
421
422 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
423 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
424 N->getLocationContext());
425 auto P = std::make_shared<PathDiagnosticEventPiece>(Pos, os.str());
426
427 // Add the range by scanning the children of the statement for any bindings
428 // to Sym.
429 for (const Stmt *Child : S->children())
430 if (const Expr *Exp = dyn_cast_or_null<Expr>(Child))
431 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
432 P->addRange(Exp->getSourceRange());
433 break;
434 }
435
436 return std::move(P);
437}
438
439static Optional<std::string> describeRegion(const MemRegion *MR) {
440 if (const auto *VR = dyn_cast_or_null<VarRegion>(MR))
441 return std::string(VR->getDecl()->getName());
442 // Once we support more storage locations for bindings,
443 // this would need to be improved.
444 return None;
445}
446
447namespace {
448// Find the first node in the current function context that referred to the
449// tracked symbol and the memory location that value was stored to. Note, the
450// value is only reported if the allocation occurred in the same function as
451// the leak. The function can also return a location context, which should be
452// treated as interesting.
453struct AllocationInfo {
454 const ExplodedNode* N;
455 const MemRegion *R;
456 const LocationContext *InterestingMethodContext;
457 AllocationInfo(const ExplodedNode *InN,
458 const MemRegion *InR,
459 const LocationContext *InInterestingMethodContext) :
460 N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
461};
462} // end anonymous namespace
463
George Karpenkova1c3bb82018-11-30 02:17:31 +0000464static AllocationInfo GetAllocationSite(ProgramStateManager &StateMgr,
465 const ExplodedNode *N, SymbolRef Sym) {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000466 const ExplodedNode *AllocationNode = N;
467 const ExplodedNode *AllocationNodeInCurrentOrParentContext = N;
468 const MemRegion *FirstBinding = nullptr;
469 const LocationContext *LeakContext = N->getLocationContext();
470
471 // The location context of the init method called on the leaked object, if
472 // available.
473 const LocationContext *InitMethodContext = nullptr;
474
475 while (N) {
476 ProgramStateRef St = N->getState();
477 const LocationContext *NContext = N->getLocationContext();
478
479 if (!getRefBinding(St, Sym))
480 break;
481
482 StoreManager::FindUniqueBinding FB(Sym);
483 StateMgr.iterBindings(St, FB);
484
485 if (FB) {
486 const MemRegion *R = FB.getRegion();
George Karpenkov70c2ee32018-08-17 21:41:07 +0000487 // Do not show local variables belonging to a function other than
488 // where the error is reported.
George Karpenkov79ed11c2018-12-11 01:13:20 +0000489 if (auto MR = dyn_cast<StackSpaceRegion>(R->getMemorySpace()))
490 if (MR->getStackFrame() == LeakContext->getStackFrame())
491 FirstBinding = R;
George Karpenkov70c2ee32018-08-17 21:41:07 +0000492 }
493
494 // AllocationNode is the last node in which the symbol was tracked.
495 AllocationNode = N;
496
497 // AllocationNodeInCurrentContext, is the last node in the current or
498 // parent context in which the symbol was tracked.
499 //
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000500 // Note that the allocation site might be in the parent context. For example,
George Karpenkov70c2ee32018-08-17 21:41:07 +0000501 // the case where an allocation happens in a block that captures a reference
502 // to it and that reference is overwritten/dropped by another call to
503 // the block.
504 if (NContext == LeakContext || NContext->isParentOf(LeakContext))
505 AllocationNodeInCurrentOrParentContext = N;
506
507 // Find the last init that was called on the given symbol and store the
508 // init method's location context.
509 if (!InitMethodContext)
George Karpenkova1c3bb82018-11-30 02:17:31 +0000510 if (auto CEP = N->getLocation().getAs<CallEnter>()) {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000511 const Stmt *CE = CEP->getCallExpr();
George Karpenkova1c3bb82018-11-30 02:17:31 +0000512 if (const auto *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000513 const Stmt *RecExpr = ME->getInstanceReceiver();
514 if (RecExpr) {
515 SVal RecV = St->getSVal(RecExpr, NContext);
516 if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
517 InitMethodContext = CEP->getCalleeContext();
518 }
519 }
520 }
521
George Karpenkova1c3bb82018-11-30 02:17:31 +0000522 N = N->getFirstPred();
George Karpenkov70c2ee32018-08-17 21:41:07 +0000523 }
524
525 // If we are reporting a leak of the object that was allocated with alloc,
526 // mark its init method as interesting.
527 const LocationContext *InterestingMethodContext = nullptr;
528 if (InitMethodContext) {
529 const ProgramPoint AllocPP = AllocationNode->getLocation();
530 if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
531 if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
532 if (ME->getMethodFamily() == OMF_alloc)
533 InterestingMethodContext = InitMethodContext;
534 }
535
536 // If allocation happened in a function different from the leak node context,
537 // do not report the binding.
538 assert(N && "Could not find allocation node");
George Karpenkova1c3bb82018-11-30 02:17:31 +0000539
540 if (AllocationNodeInCurrentOrParentContext &&
541 AllocationNodeInCurrentOrParentContext->getLocationContext() !=
542 LeakContext)
George Karpenkov70c2ee32018-08-17 21:41:07 +0000543 FirstBinding = nullptr;
George Karpenkov70c2ee32018-08-17 21:41:07 +0000544
545 return AllocationInfo(AllocationNodeInCurrentOrParentContext,
546 FirstBinding,
547 InterestingMethodContext);
548}
549
550std::shared_ptr<PathDiagnosticPiece>
George Karpenkov0bb17c42019-01-10 18:16:25 +0000551RefCountReportVisitor::getEndPath(BugReporterContext &BRC,
George Karpenkov70c2ee32018-08-17 21:41:07 +0000552 const ExplodedNode *EndN, BugReport &BR) {
553 BR.markInteresting(Sym);
554 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
555}
556
557std::shared_ptr<PathDiagnosticPiece>
George Karpenkov0bb17c42019-01-10 18:16:25 +0000558RefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
George Karpenkov70c2ee32018-08-17 21:41:07 +0000559 const ExplodedNode *EndN, BugReport &BR) {
560
561 // Tell the BugReporterContext to report cases when the tracked symbol is
562 // assigned to different variables, etc.
563 BR.markInteresting(Sym);
564
565 // We are reporting a leak. Walk up the graph to get to the first node where
566 // the symbol appeared, and also get the first VarDecl that tracked object
567 // is stored to.
George Karpenkova1c3bb82018-11-30 02:17:31 +0000568 AllocationInfo AllocI = GetAllocationSite(BRC.getStateManager(), EndN, Sym);
George Karpenkov70c2ee32018-08-17 21:41:07 +0000569
570 const MemRegion* FirstBinding = AllocI.R;
571 BR.markInteresting(AllocI.InterestingMethodContext);
572
573 SourceManager& SM = BRC.getSourceManager();
574
575 // Compute an actual location for the leak. Sometimes a leak doesn't
576 // occur at an actual statement (e.g., transition between blocks; end
577 // of function) so we need to walk the graph and compute a real location.
578 const ExplodedNode *LeakN = EndN;
579 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
580
581 std::string sbuf;
582 llvm::raw_string_ostream os(sbuf);
583
584 os << "Object leaked: ";
585
586 Optional<std::string> RegionDescription = describeRegion(FirstBinding);
587 if (RegionDescription) {
588 os << "object allocated and stored into '" << *RegionDescription << '\'';
George Karpenkovb3303d72018-11-30 02:17:05 +0000589 } else {
George Karpenkov4f64b382019-01-10 18:15:57 +0000590 os << "allocated object of type '" << getPrettyTypeName(Sym->getType())
591 << "'";
George Karpenkovb3303d72018-11-30 02:17:05 +0000592 }
George Karpenkov70c2ee32018-08-17 21:41:07 +0000593
594 // Get the retain count.
595 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
596 assert(RV);
597
598 if (RV->getKind() == RefVal::ErrorLeakReturned) {
599 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
600 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
601 // to the caller for NS objects.
602 const Decl *D = &EndN->getCodeDecl();
603
604 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
605 : " is returned from a function ");
606
George Karpenkova1c3bb82018-11-30 02:17:31 +0000607 if (D->hasAttr<CFReturnsNotRetainedAttr>()) {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000608 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
George Karpenkova1c3bb82018-11-30 02:17:31 +0000609 } else if (D->hasAttr<NSReturnsNotRetainedAttr>()) {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000610 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
George Karpenkovb43772d2018-11-30 02:18:50 +0000611 } else if (D->hasAttr<OSReturnsNotRetainedAttr>()) {
612 os << "that is annotated as OS_RETURNS_NOT_RETAINED";
George Karpenkova1c3bb82018-11-30 02:17:31 +0000613 } else {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000614 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
615 if (BRC.getASTContext().getLangOpts().ObjCAutoRefCount) {
616 os << "managed by Automatic Reference Counting";
617 } else {
618 os << "whose name ('" << MD->getSelector().getAsString()
619 << "') does not start with "
620 "'copy', 'mutableCopy', 'alloc' or 'new'."
621 " This violates the naming convention rules"
622 " given in the Memory Management Guide for Cocoa";
623 }
George Karpenkov6e9fd132018-08-22 01:17:09 +0000624 } else {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000625 const FunctionDecl *FD = cast<FunctionDecl>(D);
626 os << "whose name ('" << *FD
627 << "') does not contain 'Copy' or 'Create'. This violates the naming"
628 " convention rules given in the Memory Management Guide for Core"
629 " Foundation";
630 }
631 }
George Karpenkovf893ea12018-11-30 02:17:44 +0000632 } else {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000633 os << " is not referenced later in this execution path and has a retain "
634 "count of +" << RV->getCount();
George Karpenkovf893ea12018-11-30 02:17:44 +0000635 }
George Karpenkov70c2ee32018-08-17 21:41:07 +0000636
637 return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
638}
639
George Karpenkov0bb17c42019-01-10 18:16:25 +0000640RefCountReport::RefCountReport(RefCountBug &D, const LangOptions &LOpts,
641 ExplodedNode *n, SymbolRef sym,
642 bool registerVisitor)
George Karpenkov62db8862018-11-30 02:18:23 +0000643 : BugReport(D, D.getDescription(), n), Sym(sym) {
644 if (registerVisitor)
George Karpenkov0bb17c42019-01-10 18:16:25 +0000645 addVisitor(llvm::make_unique<RefCountReportVisitor>(sym));
George Karpenkov62db8862018-11-30 02:18:23 +0000646}
647
George Karpenkov0bb17c42019-01-10 18:16:25 +0000648RefCountReport::RefCountReport(RefCountBug &D, const LangOptions &LOpts,
649 ExplodedNode *n, SymbolRef sym,
650 StringRef endText)
George Karpenkov62db8862018-11-30 02:18:23 +0000651 : BugReport(D, D.getDescription(), endText, n) {
652
George Karpenkov0bb17c42019-01-10 18:16:25 +0000653 addVisitor(llvm::make_unique<RefCountReportVisitor>(sym));
George Karpenkov62db8862018-11-30 02:18:23 +0000654}
655
George Karpenkov0bb17c42019-01-10 18:16:25 +0000656void RefLeakReport::deriveParamLocation(CheckerContext &Ctx, SymbolRef sym) {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000657 const SourceManager& SMgr = Ctx.getSourceManager();
658
659 if (!sym->getOriginRegion())
660 return;
661
662 auto *Region = dyn_cast<DeclRegion>(sym->getOriginRegion());
663 if (Region) {
664 const Decl *PDecl = Region->getDecl();
665 if (PDecl && isa<ParmVarDecl>(PDecl)) {
George Karpenkov717c4c02019-01-10 18:15:17 +0000666 PathDiagnosticLocation ParamLocation =
667 PathDiagnosticLocation::create(PDecl, SMgr);
George Karpenkov70c2ee32018-08-17 21:41:07 +0000668 Location = ParamLocation;
669 UniqueingLocation = ParamLocation;
670 UniqueingDecl = Ctx.getLocationContext()->getDecl();
671 }
672 }
673}
674
George Karpenkov0bb17c42019-01-10 18:16:25 +0000675void RefLeakReport::deriveAllocLocation(CheckerContext &Ctx,
George Karpenkova1c3bb82018-11-30 02:17:31 +0000676 SymbolRef sym) {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000677 // Most bug reports are cached at the location where they occurred.
678 // With leaks, we want to unique them by the location where they were
679 // allocated, and only report a single path. To do this, we need to find
680 // the allocation site of a piece of tracked memory, which we do via a
681 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
682 // Note that this is *not* the trimmed graph; we are guaranteed, however,
683 // that all ancestor nodes that represent the allocation site have the
684 // same SourceLocation.
685 const ExplodedNode *AllocNode = nullptr;
686
687 const SourceManager& SMgr = Ctx.getSourceManager();
688
689 AllocationInfo AllocI =
George Karpenkova1c3bb82018-11-30 02:17:31 +0000690 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
George Karpenkov70c2ee32018-08-17 21:41:07 +0000691
692 AllocNode = AllocI.N;
693 AllocBinding = AllocI.R;
694 markInteresting(AllocI.InterestingMethodContext);
695
696 // Get the SourceLocation for the allocation site.
697 // FIXME: This will crash the analyzer if an allocation comes from an
698 // implicit call (ex: a destructor call).
699 // (Currently there are no such allocations in Cocoa, though.)
700 AllocStmt = PathDiagnosticLocation::getStmt(AllocNode);
701
702 if (!AllocStmt) {
703 AllocBinding = nullptr;
704 return;
705 }
706
707 PathDiagnosticLocation AllocLocation =
708 PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
709 AllocNode->getLocationContext());
710 Location = AllocLocation;
711
712 // Set uniqieing info, which will be used for unique the bug reports. The
713 // leaks should be uniqued on the allocation site.
714 UniqueingLocation = AllocLocation;
715 UniqueingDecl = AllocNode->getLocationContext()->getDecl();
716}
717
George Karpenkov0bb17c42019-01-10 18:16:25 +0000718void RefLeakReport::createDescription(CheckerContext &Ctx) {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000719 assert(Location.isValid() && UniqueingDecl && UniqueingLocation.isValid());
720 Description.clear();
721 llvm::raw_string_ostream os(Description);
722 os << "Potential leak of an object";
723
724 Optional<std::string> RegionDescription = describeRegion(AllocBinding);
725 if (RegionDescription) {
726 os << " stored into '" << *RegionDescription << '\'';
George Karpenkovf893ea12018-11-30 02:17:44 +0000727 } else {
728
729 // If we can't figure out the name, just supply the type information.
George Karpenkov4f64b382019-01-10 18:15:57 +0000730 os << " of type '" << getPrettyTypeName(Sym->getType()) << "'";
George Karpenkov70c2ee32018-08-17 21:41:07 +0000731 }
732}
733
George Karpenkov0bb17c42019-01-10 18:16:25 +0000734RefLeakReport::RefLeakReport(RefCountBug &D, const LangOptions &LOpts,
735 ExplodedNode *n, SymbolRef sym,
736 CheckerContext &Ctx)
737 : RefCountReport(D, LOpts, n, sym, false) {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000738
739 deriveAllocLocation(Ctx, sym);
740 if (!AllocBinding)
741 deriveParamLocation(Ctx, sym);
742
George Karpenkov936a9c92018-12-07 20:21:37 +0000743 createDescription(Ctx);
George Karpenkov70c2ee32018-08-17 21:41:07 +0000744
George Karpenkov0bb17c42019-01-10 18:16:25 +0000745 addVisitor(llvm::make_unique<RefLeakReportVisitor>(sym));
George Karpenkov70c2ee32018-08-17 21:41:07 +0000746}