blob: 89b487aa01421415b3b11d3b3e23af3b3b86cdd7 [file] [log] [blame]
George Karpenkov70c2ee32018-08-17 21:41:07 +00001//==-- RetainCountChecker.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 the methods for RetainCountChecker, which implements
11// a reference count checker for Core Foundation and Cocoa on (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
15#include "RetainCountChecker.h"
16
17using namespace clang;
18using namespace ento;
19using namespace objc_retain;
20using namespace retaincountchecker;
21using llvm::StrInStrNoCase;
22
23REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
24
25namespace clang {
26namespace ento {
27namespace retaincountchecker {
28
29const RefVal *getRefBinding(ProgramStateRef State, SymbolRef Sym) {
30 return State->get<RefBindings>(Sym);
31}
32
33ProgramStateRef setRefBinding(ProgramStateRef State, SymbolRef Sym,
34 RefVal Val) {
35 return State->set<RefBindings>(Sym, Val);
36}
37
38ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
39 return State->remove<RefBindings>(Sym);
40}
41
42} // end namespace retaincountchecker
43} // end namespace ento
44} // end namespace clang
45
46void RefVal::print(raw_ostream &Out) const {
47 if (!T.isNull())
48 Out << "Tracked " << T.getAsString() << '/';
49
50 switch (getKind()) {
51 default: llvm_unreachable("Invalid RefVal kind");
52 case Owned: {
53 Out << "Owned";
54 unsigned cnt = getCount();
55 if (cnt) Out << " (+ " << cnt << ")";
56 break;
57 }
58
59 case NotOwned: {
60 Out << "NotOwned";
61 unsigned cnt = getCount();
62 if (cnt) Out << " (+ " << cnt << ")";
63 break;
64 }
65
66 case ReturnedOwned: {
67 Out << "ReturnedOwned";
68 unsigned cnt = getCount();
69 if (cnt) Out << " (+ " << cnt << ")";
70 break;
71 }
72
73 case ReturnedNotOwned: {
74 Out << "ReturnedNotOwned";
75 unsigned cnt = getCount();
76 if (cnt) Out << " (+ " << cnt << ")";
77 break;
78 }
79
80 case Released:
81 Out << "Released";
82 break;
83
84 case ErrorDeallocNotOwned:
85 Out << "-dealloc (not-owned)";
86 break;
87
88 case ErrorLeak:
89 Out << "Leaked";
90 break;
91
92 case ErrorLeakReturned:
93 Out << "Leaked (Bad naming)";
94 break;
95
96 case ErrorUseAfterRelease:
97 Out << "Use-After-Release [ERROR]";
98 break;
99
100 case ErrorReleaseNotOwned:
101 Out << "Release of Not-Owned [ERROR]";
102 break;
103
104 case RefVal::ErrorOverAutorelease:
105 Out << "Over-autoreleased";
106 break;
107
108 case RefVal::ErrorReturnedNotOwned:
109 Out << "Non-owned object returned instead of owned";
110 break;
111 }
112
113 switch (getIvarAccessHistory()) {
114 case IvarAccessHistory::None:
115 break;
116 case IvarAccessHistory::AccessedDirectly:
117 Out << " [direct ivar access]";
118 break;
119 case IvarAccessHistory::ReleasedAfterDirectAccess:
120 Out << " [released after direct ivar access]";
121 }
122
123 if (ACnt) {
124 Out << " [autorelease -" << ACnt << ']';
125 }
126}
127
128namespace {
129class StopTrackingCallback final : public SymbolVisitor {
130 ProgramStateRef state;
131public:
132 StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
133 ProgramStateRef getState() const { return state; }
134
135 bool VisitSymbol(SymbolRef sym) override {
136 state = state->remove<RefBindings>(sym);
137 return true;
138 }
139};
140} // end anonymous namespace
141
142//===----------------------------------------------------------------------===//
143// Handle statements that may have an effect on refcounts.
144//===----------------------------------------------------------------------===//
145
146void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
147 CheckerContext &C) const {
148
149 // Scan the BlockDecRefExprs for any object the retain count checker
150 // may be tracking.
151 if (!BE->getBlockDecl()->hasCaptures())
152 return;
153
154 ProgramStateRef state = C.getState();
155 auto *R = cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
156
157 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
158 E = R->referenced_vars_end();
159
160 if (I == E)
161 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 SmallVector<const MemRegion*, 10> Regions;
167 const LocationContext *LC = C.getLocationContext();
168 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
169
170 for ( ; I != E; ++I) {
171 const VarRegion *VR = I.getCapturedRegion();
172 if (VR->getSuperRegion() == R) {
173 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
174 }
175 Regions.push_back(VR);
176 }
177
178 state =
179 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
180 Regions.data() + Regions.size()).getState();
181 C.addTransition(state);
182}
183
184void RetainCountChecker::checkPostStmt(const CastExpr *CE,
185 CheckerContext &C) const {
186 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
187 if (!BE)
188 return;
189
190 ArgEffect AE = IncRef;
191
192 switch (BE->getBridgeKind()) {
193 case OBC_Bridge:
194 // Do nothing.
195 return;
196 case OBC_BridgeRetained:
197 AE = IncRef;
198 break;
199 case OBC_BridgeTransfer:
200 AE = DecRefBridgedTransferred;
201 break;
202 }
203
204 ProgramStateRef state = C.getState();
205 SymbolRef Sym = C.getSVal(CE).getAsLocSymbol();
206 if (!Sym)
207 return;
208 const RefVal* T = getRefBinding(state, Sym);
209 if (!T)
210 return;
211
212 RefVal::Kind hasErr = (RefVal::Kind) 0;
213 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
214
215 if (hasErr) {
216 // FIXME: If we get an error during a bridge cast, should we report it?
217 return;
218 }
219
220 C.addTransition(state);
221}
222
223void RetainCountChecker::processObjCLiterals(CheckerContext &C,
224 const Expr *Ex) const {
225 ProgramStateRef state = C.getState();
226 const ExplodedNode *pred = C.getPredecessor();
227 for (const Stmt *Child : Ex->children()) {
228 SVal V = pred->getSVal(Child);
229 if (SymbolRef sym = V.getAsSymbol())
230 if (const RefVal* T = getRefBinding(state, sym)) {
231 RefVal::Kind hasErr = (RefVal::Kind) 0;
232 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
233 if (hasErr) {
234 processNonLeakError(state, Child->getSourceRange(), hasErr, sym, C);
235 return;
236 }
237 }
238 }
239
240 // Return the object as autoreleased.
241 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
242 if (SymbolRef sym =
243 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
244 QualType ResultTy = Ex->getType();
245 state = setRefBinding(state, sym,
246 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
247 }
248
249 C.addTransition(state);
250}
251
252void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
253 CheckerContext &C) const {
254 // Apply the 'MayEscape' to all values.
255 processObjCLiterals(C, AL);
256}
257
258void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
259 CheckerContext &C) const {
260 // Apply the 'MayEscape' to all keys and values.
261 processObjCLiterals(C, DL);
262}
263
264void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
265 CheckerContext &C) const {
266 const ExplodedNode *Pred = C.getPredecessor();
267 ProgramStateRef State = Pred->getState();
268
269 if (SymbolRef Sym = Pred->getSVal(Ex).getAsSymbol()) {
270 QualType ResultTy = Ex->getType();
271 State = setRefBinding(State, Sym,
272 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
273 }
274
275 C.addTransition(State);
276}
277
278void RetainCountChecker::checkPostStmt(const ObjCIvarRefExpr *IRE,
279 CheckerContext &C) const {
280 Optional<Loc> IVarLoc = C.getSVal(IRE).getAs<Loc>();
281 if (!IVarLoc)
282 return;
283
284 ProgramStateRef State = C.getState();
285 SymbolRef Sym = State->getSVal(*IVarLoc).getAsSymbol();
286 if (!Sym || !dyn_cast_or_null<ObjCIvarRegion>(Sym->getOriginRegion()))
287 return;
288
289 // Accessing an ivar directly is unusual. If we've done that, be more
290 // forgiving about what the surrounding code is allowed to do.
291
292 QualType Ty = Sym->getType();
293 RetEffect::ObjKind Kind;
294 if (Ty->isObjCRetainableType())
295 Kind = RetEffect::ObjC;
296 else if (coreFoundation::isCFObjectRef(Ty))
297 Kind = RetEffect::CF;
298 else
299 return;
300
301 // If the value is already known to be nil, don't bother tracking it.
302 ConstraintManager &CMgr = State->getConstraintManager();
303 if (CMgr.isNull(State, Sym).isConstrainedTrue())
304 return;
305
306 if (const RefVal *RV = getRefBinding(State, Sym)) {
307 // If we've seen this symbol before, or we're only seeing it now because
308 // of something the analyzer has synthesized, don't do anything.
309 if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None ||
310 isSynthesizedAccessor(C.getStackFrame())) {
311 return;
312 }
313
314 // Note that this value has been loaded from an ivar.
315 C.addTransition(setRefBinding(State, Sym, RV->withIvarAccess()));
316 return;
317 }
318
319 RefVal PlusZero = RefVal::makeNotOwned(Kind, Ty);
320
321 // In a synthesized accessor, the effective retain count is +0.
322 if (isSynthesizedAccessor(C.getStackFrame())) {
323 C.addTransition(setRefBinding(State, Sym, PlusZero));
324 return;
325 }
326
327 State = setRefBinding(State, Sym, PlusZero.withIvarAccess());
328 C.addTransition(State);
329}
330
331void RetainCountChecker::checkPostCall(const CallEvent &Call,
332 CheckerContext &C) const {
333 RetainSummaryManager &Summaries = getSummaryManager(C);
334 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
335
336 if (C.wasInlined) {
337 processSummaryOfInlined(*Summ, Call, C);
338 return;
339 }
340 checkSummary(*Summ, Call, C);
341}
342
343/// GetReturnType - Used to get the return type of a message expression or
344/// function call with the intention of affixing that type to a tracked symbol.
345/// While the return type can be queried directly from RetEx, when
346/// invoking class methods we augment to the return type to be that of
347/// a pointer to the class (as opposed it just being id).
348// FIXME: We may be able to do this with related result types instead.
349// This function is probably overestimating.
350static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
351 QualType RetTy = RetE->getType();
352 // If RetE is not a message expression just return its type.
353 // If RetE is a message expression, return its types if it is something
354 /// more specific than id.
355 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
356 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
357 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
358 PT->isObjCClassType()) {
359 // At this point we know the return type of the message expression is
360 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
361 // is a call to a class method whose type we can resolve. In such
362 // cases, promote the return type to XXX* (where XXX is the class).
363 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
364 return !D ? RetTy :
365 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
366 }
367
368 return RetTy;
369}
370
371// We don't always get the exact modeling of the function with regards to the
372// retain count checker even when the function is inlined. For example, we need
373// to stop tracking the symbols which were marked with StopTrackingHard.
374void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
375 const CallEvent &CallOrMsg,
376 CheckerContext &C) const {
377 ProgramStateRef state = C.getState();
378
379 // Evaluate the effect of the arguments.
380 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
381 if (Summ.getArg(idx) == StopTrackingHard) {
382 SVal V = CallOrMsg.getArgSVal(idx);
383 if (SymbolRef Sym = V.getAsLocSymbol()) {
384 state = removeRefBinding(state, Sym);
385 }
386 }
387 }
388
389 // Evaluate the effect on the message receiver.
390 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
391 if (MsgInvocation) {
392 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
393 if (Summ.getReceiverEffect() == StopTrackingHard) {
394 state = removeRefBinding(state, Sym);
395 }
396 }
397 }
398
399 // Consult the summary for the return value.
400 RetEffect RE = Summ.getRetEffect();
401 if (RE.getKind() == RetEffect::NoRetHard) {
402 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
403 if (Sym)
404 state = removeRefBinding(state, Sym);
405 }
406
407 C.addTransition(state);
408}
409
410static ProgramStateRef updateOutParameter(ProgramStateRef State,
411 SVal ArgVal,
412 ArgEffect Effect) {
413 auto *ArgRegion = dyn_cast_or_null<TypedValueRegion>(ArgVal.getAsRegion());
414 if (!ArgRegion)
415 return State;
416
417 QualType PointeeTy = ArgRegion->getValueType();
418 if (!coreFoundation::isCFObjectRef(PointeeTy))
419 return State;
420
421 SVal PointeeVal = State->getSVal(ArgRegion);
422 SymbolRef Pointee = PointeeVal.getAsLocSymbol();
423 if (!Pointee)
424 return State;
425
426 switch (Effect) {
427 case UnretainedOutParameter:
428 State = setRefBinding(State, Pointee,
429 RefVal::makeNotOwned(RetEffect::CF, PointeeTy));
430 break;
431 case RetainedOutParameter:
432 // Do nothing. Retained out parameters will either point to a +1 reference
433 // or NULL, but the way you check for failure differs depending on the API.
434 // Consequently, we don't have a good way to track them yet.
435 break;
436
437 default:
438 llvm_unreachable("only for out parameters");
439 }
440
441 return State;
442}
443
444void RetainCountChecker::checkSummary(const RetainSummary &Summ,
445 const CallEvent &CallOrMsg,
446 CheckerContext &C) const {
447 ProgramStateRef state = C.getState();
448
449 // Evaluate the effect of the arguments.
450 RefVal::Kind hasErr = (RefVal::Kind) 0;
451 SourceRange ErrorRange;
452 SymbolRef ErrorSym = nullptr;
453
454 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
455 SVal V = CallOrMsg.getArgSVal(idx);
456
457 ArgEffect Effect = Summ.getArg(idx);
458 if (Effect == RetainedOutParameter || Effect == UnretainedOutParameter) {
459 state = updateOutParameter(state, V, Effect);
460 } else if (SymbolRef Sym = V.getAsLocSymbol()) {
461 if (const RefVal *T = getRefBinding(state, Sym)) {
462 state = updateSymbol(state, Sym, *T, Effect, hasErr, C);
463 if (hasErr) {
464 ErrorRange = CallOrMsg.getArgSourceRange(idx);
465 ErrorSym = Sym;
466 break;
467 }
468 }
469 }
470 }
471
472 // Evaluate the effect on the message receiver.
473 bool ReceiverIsTracked = false;
474 if (!hasErr) {
475 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
476 if (MsgInvocation) {
477 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
478 if (const RefVal *T = getRefBinding(state, Sym)) {
479 ReceiverIsTracked = true;
480 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
481 hasErr, C);
482 if (hasErr) {
483 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
484 ErrorSym = Sym;
485 }
486 }
487 }
488 }
489 }
490
491 // Process any errors.
492 if (hasErr) {
493 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
494 return;
495 }
496
497 // Consult the summary for the return value.
498 RetEffect RE = Summ.getRetEffect();
499
500 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
501 if (ReceiverIsTracked)
502 RE = getSummaryManager(C).getObjAllocRetEffect();
503 else
504 RE = RetEffect::MakeNoRet();
505 }
506
507 switch (RE.getKind()) {
508 default:
509 llvm_unreachable("Unhandled RetEffect.");
510
511 case RetEffect::NoRet:
512 case RetEffect::NoRetHard:
513 // No work necessary.
514 break;
515
516 case RetEffect::OwnedSymbol: {
517 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
518 if (!Sym)
519 break;
520
521 // Use the result type from the CallEvent as it automatically adjusts
522 // for methods/functions that return references.
523 QualType ResultTy = CallOrMsg.getResultType();
524 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
525 ResultTy));
526
527 // FIXME: Add a flag to the checker where allocations are assumed to
528 // *not* fail.
529 break;
530 }
531
532 case RetEffect::NotOwnedSymbol: {
533 const Expr *Ex = CallOrMsg.getOriginExpr();
534 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
535 if (!Sym)
536 break;
537 assert(Ex);
538 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
539 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
540 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
541 ResultTy));
542 break;
543 }
544 }
545
546 // This check is actually necessary; otherwise the statement builder thinks
547 // we've hit a previously-found path.
548 // Normally addTransition takes care of this, but we want the node pointer.
549 ExplodedNode *NewNode;
550 if (state == C.getState()) {
551 NewNode = C.getPredecessor();
552 } else {
553 NewNode = C.addTransition(state);
554 }
555
556 // Annotate the node with summary we used.
557 if (NewNode) {
558 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
559 if (ShouldResetSummaryLog) {
560 SummaryLog.clear();
561 ShouldResetSummaryLog = false;
562 }
563 SummaryLog[NewNode] = &Summ;
564 }
565}
566
567ProgramStateRef
568RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
569 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
570 CheckerContext &C) const {
571 bool IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
572 switch (E) {
573 default:
574 break;
575 case IncRefMsg:
576 E = IgnoreRetainMsg ? DoNothing : IncRef;
577 break;
578 case DecRefMsg:
579 E = IgnoreRetainMsg ? DoNothing: DecRef;
580 break;
581 case DecRefMsgAndStopTrackingHard:
582 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
583 break;
George Karpenkovbc0cddf2018-08-17 21:42:59 +0000584 case MakeCollectable:
585 E = DoNothing;
George Karpenkov70c2ee32018-08-17 21:41:07 +0000586 }
587
588 // Handle all use-after-releases.
589 if (V.getKind() == RefVal::Released) {
590 V = V ^ RefVal::ErrorUseAfterRelease;
591 hasErr = V.getKind();
592 return setRefBinding(state, sym, V);
593 }
594
595 switch (E) {
596 case DecRefMsg:
597 case IncRefMsg:
George Karpenkovbc0cddf2018-08-17 21:42:59 +0000598 case MakeCollectable:
George Karpenkov70c2ee32018-08-17 21:41:07 +0000599 case DecRefMsgAndStopTrackingHard:
George Karpenkovbc0cddf2018-08-17 21:42:59 +0000600 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
George Karpenkov70c2ee32018-08-17 21:41:07 +0000601
602 case UnretainedOutParameter:
603 case RetainedOutParameter:
604 llvm_unreachable("Applies to pointer-to-pointer parameters, which should "
605 "not have ref state.");
606
607 case Dealloc:
608 switch (V.getKind()) {
609 default:
610 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
611 case RefVal::Owned:
612 // The object immediately transitions to the released state.
613 V = V ^ RefVal::Released;
614 V.clearCounts();
615 return setRefBinding(state, sym, V);
616 case RefVal::NotOwned:
617 V = V ^ RefVal::ErrorDeallocNotOwned;
618 hasErr = V.getKind();
619 break;
620 }
621 break;
622
623 case MayEscape:
624 if (V.getKind() == RefVal::Owned) {
625 V = V ^ RefVal::NotOwned;
626 break;
627 }
628
629 // Fall-through.
630
631 case DoNothing:
632 return state;
633
634 case Autorelease:
635 // Update the autorelease counts.
636 V = V.autorelease();
637 break;
638
639 case StopTracking:
640 case StopTrackingHard:
641 return removeRefBinding(state, sym);
642
643 case IncRef:
644 switch (V.getKind()) {
645 default:
646 llvm_unreachable("Invalid RefVal state for a retain.");
647 case RefVal::Owned:
648 case RefVal::NotOwned:
649 V = V + 1;
650 break;
651 }
652 break;
653
654 case DecRef:
655 case DecRefBridgedTransferred:
656 case DecRefAndStopTrackingHard:
657 switch (V.getKind()) {
658 default:
659 // case 'RefVal::Released' handled above.
660 llvm_unreachable("Invalid RefVal state for a release.");
661
662 case RefVal::Owned:
663 assert(V.getCount() > 0);
664 if (V.getCount() == 1) {
665 if (E == DecRefBridgedTransferred ||
666 V.getIvarAccessHistory() ==
667 RefVal::IvarAccessHistory::AccessedDirectly)
668 V = V ^ RefVal::NotOwned;
669 else
670 V = V ^ RefVal::Released;
671 } else if (E == DecRefAndStopTrackingHard) {
672 return removeRefBinding(state, sym);
673 }
674
675 V = V - 1;
676 break;
677
678 case RefVal::NotOwned:
679 if (V.getCount() > 0) {
680 if (E == DecRefAndStopTrackingHard)
681 return removeRefBinding(state, sym);
682 V = V - 1;
683 } else if (V.getIvarAccessHistory() ==
684 RefVal::IvarAccessHistory::AccessedDirectly) {
685 // Assume that the instance variable was holding on the object at
686 // +1, and we just didn't know.
687 if (E == DecRefAndStopTrackingHard)
688 return removeRefBinding(state, sym);
689 V = V.releaseViaIvar() ^ RefVal::Released;
690 } else {
691 V = V ^ RefVal::ErrorReleaseNotOwned;
692 hasErr = V.getKind();
693 }
694 break;
695 }
696 break;
697 }
698 return setRefBinding(state, sym, V);
699}
700
701void RetainCountChecker::processNonLeakError(ProgramStateRef St,
702 SourceRange ErrorRange,
703 RefVal::Kind ErrorKind,
704 SymbolRef Sym,
705 CheckerContext &C) const {
706 // HACK: Ignore retain-count issues on values accessed through ivars,
707 // because of cases like this:
708 // [_contentView retain];
709 // [_contentView removeFromSuperview];
710 // [self addSubview:_contentView]; // invalidates 'self'
711 // [_contentView release];
712 if (const RefVal *RV = getRefBinding(St, Sym))
713 if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
714 return;
715
716 ExplodedNode *N = C.generateErrorNode(St);
717 if (!N)
718 return;
719
720 CFRefBug *BT;
721 switch (ErrorKind) {
722 default:
723 llvm_unreachable("Unhandled error.");
724 case RefVal::ErrorUseAfterRelease:
725 if (!useAfterRelease)
726 useAfterRelease.reset(new UseAfterRelease(this));
727 BT = useAfterRelease.get();
728 break;
729 case RefVal::ErrorReleaseNotOwned:
730 if (!releaseNotOwned)
731 releaseNotOwned.reset(new BadRelease(this));
732 BT = releaseNotOwned.get();
733 break;
734 case RefVal::ErrorDeallocNotOwned:
735 if (!deallocNotOwned)
736 deallocNotOwned.reset(new DeallocNotOwned(this));
737 BT = deallocNotOwned.get();
738 break;
739 }
740
741 assert(BT);
742 auto report = std::unique_ptr<BugReport>(
743 new CFRefReport(*BT, C.getASTContext().getLangOpts(),
744 SummaryLog, N, Sym));
745 report->addRange(ErrorRange);
746 C.emitReport(std::move(report));
747}
748
749//===----------------------------------------------------------------------===//
750// Handle the return values of retain-count-related functions.
751//===----------------------------------------------------------------------===//
752
753bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
754 // Get the callee. We're only interested in simple C functions.
755 ProgramStateRef state = C.getState();
756 const FunctionDecl *FD = C.getCalleeDecl(CE);
757 if (!FD)
758 return false;
759
George Karpenkovc4d6b932018-08-17 21:42:05 +0000760 RetainSummaryManager &SmrMgr = getSummaryManager(C);
761 QualType ResultTy = CE->getCallReturnType(C.getASTContext());
George Karpenkov70c2ee32018-08-17 21:41:07 +0000762
George Karpenkov70c2ee32018-08-17 21:41:07 +0000763 // See if the function has 'rc_ownership_trusted_implementation'
764 // annotate attribute. If it does, we will not inline it.
765 bool hasTrustedImplementationAnnotation = false;
766
George Karpenkovc4d6b932018-08-17 21:42:05 +0000767 // See if it's one of the specific functions we know how to eval.
768 bool canEval = SmrMgr.canEval(CE, FD, hasTrustedImplementationAnnotation);
George Karpenkov70c2ee32018-08-17 21:41:07 +0000769
770 if (!canEval)
771 return false;
772
773 // Bind the return value.
774 const LocationContext *LCtx = C.getLocationContext();
775 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
776 if (RetVal.isUnknown() ||
777 (hasTrustedImplementationAnnotation && !ResultTy.isNull())) {
778 // If the receiver is unknown or the function has
779 // 'rc_ownership_trusted_implementation' annotate attribute, conjure a
780 // return value.
781 SValBuilder &SVB = C.getSValBuilder();
782 RetVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, ResultTy, C.blockCount());
783 }
784 state = state->BindExpr(CE, LCtx, RetVal, false);
785
786 // FIXME: This should not be necessary, but otherwise the argument seems to be
787 // considered alive during the next statement.
788 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
789 // Save the refcount status of the argument.
790 SymbolRef Sym = RetVal.getAsLocSymbol();
791 const RefVal *Binding = nullptr;
792 if (Sym)
793 Binding = getRefBinding(state, Sym);
794
795 // Invalidate the argument region.
796 state = state->invalidateRegions(
797 ArgRegion, CE, C.blockCount(), LCtx,
798 /*CausesPointerEscape*/ hasTrustedImplementationAnnotation);
799
800 // Restore the refcount status of the argument.
801 if (Binding)
802 state = setRefBinding(state, Sym, *Binding);
803 }
804
805 C.addTransition(state);
806 return true;
807}
808
809//===----------------------------------------------------------------------===//
810// Handle return statements.
811//===----------------------------------------------------------------------===//
812
813void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
814 CheckerContext &C) const {
815
816 // Only adjust the reference count if this is the top-level call frame,
817 // and not the result of inlining. In the future, we should do
818 // better checking even for inlined calls, and see if they match
819 // with their expected semantics (e.g., the method should return a retained
820 // object, etc.).
821 if (!C.inTopFrame())
822 return;
823
824 const Expr *RetE = S->getRetValue();
825 if (!RetE)
826 return;
827
828 ProgramStateRef state = C.getState();
829 SymbolRef Sym =
830 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
831 if (!Sym)
832 return;
833
834 // Get the reference count binding (if any).
835 const RefVal *T = getRefBinding(state, Sym);
836 if (!T)
837 return;
838
839 // Change the reference count.
840 RefVal X = *T;
841
842 switch (X.getKind()) {
843 case RefVal::Owned: {
844 unsigned cnt = X.getCount();
845 assert(cnt > 0);
846 X.setCount(cnt - 1);
847 X = X ^ RefVal::ReturnedOwned;
848 break;
849 }
850
851 case RefVal::NotOwned: {
852 unsigned cnt = X.getCount();
853 if (cnt) {
854 X.setCount(cnt - 1);
855 X = X ^ RefVal::ReturnedOwned;
856 }
857 else {
858 X = X ^ RefVal::ReturnedNotOwned;
859 }
860 break;
861 }
862
863 default:
864 return;
865 }
866
867 // Update the binding.
868 state = setRefBinding(state, Sym, X);
869 ExplodedNode *Pred = C.addTransition(state);
870
871 // At this point we have updated the state properly.
872 // Everything after this is merely checking to see if the return value has
873 // been over- or under-retained.
874
875 // Did we cache out?
876 if (!Pred)
877 return;
878
879 // Update the autorelease counts.
880 static CheckerProgramPointTag AutoreleaseTag(this, "Autorelease");
881 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
882
883 // Did we cache out?
884 if (!state)
885 return;
886
887 // Get the updated binding.
888 T = getRefBinding(state, Sym);
889 assert(T);
890 X = *T;
891
892 // Consult the summary of the enclosing method.
893 RetainSummaryManager &Summaries = getSummaryManager(C);
894 const Decl *CD = &Pred->getCodeDecl();
895 RetEffect RE = RetEffect::MakeNoRet();
896
897 // FIXME: What is the convention for blocks? Is there one?
898 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
899 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
900 RE = Summ->getRetEffect();
901 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
902 if (!isa<CXXMethodDecl>(FD)) {
903 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
904 RE = Summ->getRetEffect();
905 }
906 }
907
908 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
909}
910
911void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
912 CheckerContext &C,
913 ExplodedNode *Pred,
914 RetEffect RE, RefVal X,
915 SymbolRef Sym,
916 ProgramStateRef state) const {
917 // HACK: Ignore retain-count issues on values accessed through ivars,
918 // because of cases like this:
919 // [_contentView retain];
920 // [_contentView removeFromSuperview];
921 // [self addSubview:_contentView]; // invalidates 'self'
922 // [_contentView release];
923 if (X.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
924 return;
925
926 // Any leaks or other errors?
927 if (X.isReturnedOwned() && X.getCount() == 0) {
928 if (RE.getKind() != RetEffect::NoRet) {
929 bool hasError = false;
930 if (!RE.isOwned()) {
931 // The returning type is a CF, we expect the enclosing method should
932 // return ownership.
933 hasError = true;
934 X = X ^ RefVal::ErrorLeakReturned;
935 }
936
937 if (hasError) {
938 // Generate an error node.
939 state = setRefBinding(state, Sym, X);
940
941 static CheckerProgramPointTag ReturnOwnLeakTag(this, "ReturnsOwnLeak");
942 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
943 if (N) {
944 const LangOptions &LOpts = C.getASTContext().getLangOpts();
945 C.emitReport(std::unique_ptr<BugReport>(new CFRefLeakReport(
946 *getLeakAtReturnBug(LOpts), LOpts,
947 SummaryLog, N, Sym, C, IncludeAllocationLine)));
948 }
949 }
950 }
951 } else if (X.isReturnedNotOwned()) {
952 if (RE.isOwned()) {
953 if (X.getIvarAccessHistory() ==
954 RefVal::IvarAccessHistory::AccessedDirectly) {
955 // Assume the method was trying to transfer a +1 reference from a
956 // strong ivar to the caller.
957 state = setRefBinding(state, Sym,
958 X.releaseViaIvar() ^ RefVal::ReturnedOwned);
959 } else {
960 // Trying to return a not owned object to a caller expecting an
961 // owned object.
962 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
963
964 static CheckerProgramPointTag
965 ReturnNotOwnedTag(this, "ReturnNotOwnedForOwned");
966
967 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
968 if (N) {
969 if (!returnNotOwnedForOwned)
970 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned(this));
971
972 C.emitReport(std::unique_ptr<BugReport>(new CFRefReport(
973 *returnNotOwnedForOwned, C.getASTContext().getLangOpts(),
974 SummaryLog, N, Sym)));
975 }
976 }
977 }
978 }
979}
980
981//===----------------------------------------------------------------------===//
982// Check various ways a symbol can be invalidated.
983//===----------------------------------------------------------------------===//
984
985void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
986 CheckerContext &C) const {
987 // Are we storing to something that causes the value to "escape"?
988 bool escapes = true;
989
990 // A value escapes in three possible cases (this may change):
991 //
992 // (1) we are binding to something that is not a memory region.
993 // (2) we are binding to a memregion that does not have stack storage
994 // (3) we are binding to a memregion with stack storage that the store
995 // does not understand.
996 ProgramStateRef state = C.getState();
997
998 if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
999 escapes = !regionLoc->getRegion()->hasStackStorage();
1000
1001 if (!escapes) {
1002 // To test (3), generate a new state with the binding added. If it is
1003 // the same state, then it escapes (since the store cannot represent
1004 // the binding).
1005 // Do this only if we know that the store is not supposed to generate the
1006 // same state.
1007 SVal StoredVal = state->getSVal(regionLoc->getRegion());
1008 if (StoredVal != val)
1009 escapes = (state == (state->bindLoc(*regionLoc, val, C.getLocationContext())));
1010 }
1011 if (!escapes) {
1012 // Case 4: We do not currently model what happens when a symbol is
1013 // assigned to a struct field, so be conservative here and let the symbol
1014 // go. TODO: This could definitely be improved upon.
1015 escapes = !isa<VarRegion>(regionLoc->getRegion());
1016 }
1017 }
1018
1019 // If we are storing the value into an auto function scope variable annotated
1020 // with (__attribute__((cleanup))), stop tracking the value to avoid leak
1021 // false positives.
1022 if (const VarRegion *LVR = dyn_cast_or_null<VarRegion>(loc.getAsRegion())) {
1023 const VarDecl *VD = LVR->getDecl();
1024 if (VD->hasAttr<CleanupAttr>()) {
1025 escapes = true;
1026 }
1027 }
1028
1029 // If our store can represent the binding and we aren't storing to something
1030 // that doesn't have local storage then just return and have the simulation
1031 // state continue as is.
1032 if (!escapes)
1033 return;
1034
1035 // Otherwise, find all symbols referenced by 'val' that we are tracking
1036 // and stop tracking them.
1037 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1038 C.addTransition(state);
1039}
1040
1041ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
1042 SVal Cond,
1043 bool Assumption) const {
1044 // FIXME: We may add to the interface of evalAssume the list of symbols
1045 // whose assumptions have changed. For now we just iterate through the
1046 // bindings and check if any of the tracked symbols are NULL. This isn't
1047 // too bad since the number of symbols we will track in practice are
1048 // probably small and evalAssume is only called at branches and a few
1049 // other places.
1050 RefBindingsTy B = state->get<RefBindings>();
1051
1052 if (B.isEmpty())
1053 return state;
1054
1055 bool changed = false;
1056 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
1057
1058 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
1059 // Check if the symbol is null stop tracking the symbol.
1060 ConstraintManager &CMgr = state->getConstraintManager();
1061 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1062 if (AllocFailed.isConstrainedTrue()) {
1063 changed = true;
1064 B = RefBFactory.remove(B, I.getKey());
1065 }
1066 }
1067
1068 if (changed)
1069 state = state->set<RefBindings>(B);
1070
1071 return state;
1072}
1073
1074ProgramStateRef
1075RetainCountChecker::checkRegionChanges(ProgramStateRef state,
1076 const InvalidatedSymbols *invalidated,
1077 ArrayRef<const MemRegion *> ExplicitRegions,
1078 ArrayRef<const MemRegion *> Regions,
1079 const LocationContext *LCtx,
1080 const CallEvent *Call) const {
1081 if (!invalidated)
1082 return state;
1083
1084 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
1085 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1086 E = ExplicitRegions.end(); I != E; ++I) {
1087 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
1088 WhitelistedSymbols.insert(SR->getSymbol());
1089 }
1090
1091 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
1092 E = invalidated->end(); I!=E; ++I) {
1093 SymbolRef sym = *I;
1094 if (WhitelistedSymbols.count(sym))
1095 continue;
1096 // Remove any existing reference-count binding.
1097 state = removeRefBinding(state, sym);
1098 }
1099 return state;
1100}
1101
1102//===----------------------------------------------------------------------===//
1103// Handle dead symbols and end-of-path.
1104//===----------------------------------------------------------------------===//
1105
1106ProgramStateRef
1107RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
1108 ExplodedNode *Pred,
1109 const ProgramPointTag *Tag,
1110 CheckerContext &Ctx,
1111 SymbolRef Sym, RefVal V) const {
1112 unsigned ACnt = V.getAutoreleaseCount();
1113
1114 // No autorelease counts? Nothing to be done.
1115 if (!ACnt)
1116 return state;
1117
1118 unsigned Cnt = V.getCount();
1119
1120 // FIXME: Handle sending 'autorelease' to already released object.
1121
1122 if (V.getKind() == RefVal::ReturnedOwned)
1123 ++Cnt;
1124
1125 // If we would over-release here, but we know the value came from an ivar,
1126 // assume it was a strong ivar that's just been relinquished.
1127 if (ACnt > Cnt &&
1128 V.getIvarAccessHistory() == RefVal::IvarAccessHistory::AccessedDirectly) {
1129 V = V.releaseViaIvar();
1130 --ACnt;
1131 }
1132
1133 if (ACnt <= Cnt) {
1134 if (ACnt == Cnt) {
1135 V.clearCounts();
1136 if (V.getKind() == RefVal::ReturnedOwned)
1137 V = V ^ RefVal::ReturnedNotOwned;
1138 else
1139 V = V ^ RefVal::NotOwned;
1140 } else {
1141 V.setCount(V.getCount() - ACnt);
1142 V.setAutoreleaseCount(0);
1143 }
1144 return setRefBinding(state, Sym, V);
1145 }
1146
1147 // HACK: Ignore retain-count issues on values accessed through ivars,
1148 // because of cases like this:
1149 // [_contentView retain];
1150 // [_contentView removeFromSuperview];
1151 // [self addSubview:_contentView]; // invalidates 'self'
1152 // [_contentView release];
1153 if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
1154 return state;
1155
1156 // Woah! More autorelease counts then retain counts left.
1157 // Emit hard error.
1158 V = V ^ RefVal::ErrorOverAutorelease;
1159 state = setRefBinding(state, Sym, V);
1160
1161 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
1162 if (N) {
1163 SmallString<128> sbuf;
1164 llvm::raw_svector_ostream os(sbuf);
1165 os << "Object was autoreleased ";
1166 if (V.getAutoreleaseCount() > 1)
1167 os << V.getAutoreleaseCount() << " times but the object ";
1168 else
1169 os << "but ";
1170 os << "has a +" << V.getCount() << " retain count";
1171
1172 if (!overAutorelease)
1173 overAutorelease.reset(new OverAutorelease(this));
1174
1175 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
1176 Ctx.emitReport(std::unique_ptr<BugReport>(
1177 new CFRefReport(*overAutorelease, LOpts,
1178 SummaryLog, N, Sym, os.str())));
1179 }
1180
1181 return nullptr;
1182}
1183
1184ProgramStateRef
1185RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
1186 SymbolRef sid, RefVal V,
1187 SmallVectorImpl<SymbolRef> &Leaked) const {
1188 bool hasLeak;
1189
1190 // HACK: Ignore retain-count issues on values accessed through ivars,
1191 // because of cases like this:
1192 // [_contentView retain];
1193 // [_contentView removeFromSuperview];
1194 // [self addSubview:_contentView]; // invalidates 'self'
1195 // [_contentView release];
1196 if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
1197 hasLeak = false;
1198 else if (V.isOwned())
1199 hasLeak = true;
1200 else if (V.isNotOwned() || V.isReturnedOwned())
1201 hasLeak = (V.getCount() > 0);
1202 else
1203 hasLeak = false;
1204
1205 if (!hasLeak)
1206 return removeRefBinding(state, sid);
1207
1208 Leaked.push_back(sid);
1209 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
1210}
1211
1212ExplodedNode *
1213RetainCountChecker::processLeaks(ProgramStateRef state,
1214 SmallVectorImpl<SymbolRef> &Leaked,
1215 CheckerContext &Ctx,
1216 ExplodedNode *Pred) const {
1217 // Generate an intermediate node representing the leak point.
1218 ExplodedNode *N = Ctx.addTransition(state, Pred);
1219
1220 if (N) {
1221 for (SmallVectorImpl<SymbolRef>::iterator
1222 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
1223
1224 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
1225 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts)
1226 : getLeakAtReturnBug(LOpts);
1227 assert(BT && "BugType not initialized.");
1228
1229 Ctx.emitReport(std::unique_ptr<BugReport>(
1230 new CFRefLeakReport(*BT, LOpts, SummaryLog, N, *I, Ctx,
1231 IncludeAllocationLine)));
1232 }
1233 }
1234
1235 return N;
1236}
1237
1238static bool isGeneralizedObjectRef(QualType Ty) {
1239 if (Ty.getAsString().substr(0, 4) == "isl_")
1240 return true;
1241 else
1242 return false;
1243}
1244
1245void RetainCountChecker::checkBeginFunction(CheckerContext &Ctx) const {
1246 if (!Ctx.inTopFrame())
1247 return;
1248
George Karpenkovc4d6b932018-08-17 21:42:05 +00001249 RetainSummaryManager &SmrMgr = getSummaryManager(Ctx);
George Karpenkov70c2ee32018-08-17 21:41:07 +00001250 const LocationContext *LCtx = Ctx.getLocationContext();
1251 const FunctionDecl *FD = dyn_cast<FunctionDecl>(LCtx->getDecl());
1252
George Karpenkovc4d6b932018-08-17 21:42:05 +00001253 if (!FD || SmrMgr.isTrustedReferenceCountImplementation(FD))
George Karpenkov70c2ee32018-08-17 21:41:07 +00001254 return;
1255
1256 ProgramStateRef state = Ctx.getState();
George Karpenkovc4d6b932018-08-17 21:42:05 +00001257 const RetainSummary *FunctionSummary = SmrMgr.getFunctionSummary(FD);
George Karpenkov70c2ee32018-08-17 21:41:07 +00001258 ArgEffects CalleeSideArgEffects = FunctionSummary->getArgEffects();
1259
1260 for (unsigned idx = 0, e = FD->getNumParams(); idx != e; ++idx) {
1261 const ParmVarDecl *Param = FD->getParamDecl(idx);
1262 SymbolRef Sym = state->getSVal(state->getRegion(Param, LCtx)).getAsSymbol();
1263
1264 QualType Ty = Param->getType();
1265 const ArgEffect *AE = CalleeSideArgEffects.lookup(idx);
1266 if (AE && *AE == DecRef && isGeneralizedObjectRef(Ty)) {
1267 state = setRefBinding(state, Sym, RefVal::makeOwned(RetEffect::ObjKind::Generalized, Ty));
1268 } else if (isGeneralizedObjectRef(Ty)) {
1269 state = setRefBinding(
1270 state, Sym,
1271 RefVal::makeNotOwned(RetEffect::ObjKind::Generalized, Ty));
1272 }
1273 }
1274
1275 Ctx.addTransition(state);
1276}
1277
1278void RetainCountChecker::checkEndFunction(const ReturnStmt *RS,
1279 CheckerContext &Ctx) const {
1280 ProgramStateRef state = Ctx.getState();
1281 RefBindingsTy B = state->get<RefBindings>();
1282 ExplodedNode *Pred = Ctx.getPredecessor();
1283
1284 // Don't process anything within synthesized bodies.
1285 const LocationContext *LCtx = Pred->getLocationContext();
1286 if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
1287 assert(!LCtx->inTopFrame());
1288 return;
1289 }
1290
1291 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
1292 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/nullptr, Ctx,
1293 I->first, I->second);
1294 if (!state)
1295 return;
1296 }
1297
1298 // If the current LocationContext has a parent, don't check for leaks.
1299 // We will do that later.
1300 // FIXME: we should instead check for imbalances of the retain/releases,
1301 // and suggest annotations.
1302 if (LCtx->getParent())
1303 return;
1304
1305 B = state->get<RefBindings>();
1306 SmallVector<SymbolRef, 10> Leaked;
1307
1308 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
1309 state = handleSymbolDeath(state, I->first, I->second, Leaked);
1310
1311 processLeaks(state, Leaked, Ctx, Pred);
1312}
1313
1314const ProgramPointTag *
1315RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
1316 const CheckerProgramPointTag *&tag = DeadSymbolTags[sym];
1317 if (!tag) {
1318 SmallString<64> buf;
1319 llvm::raw_svector_ostream out(buf);
1320 out << "Dead Symbol : ";
1321 sym->dumpToStream(out);
1322 tag = new CheckerProgramPointTag(this, out.str());
1323 }
1324 return tag;
1325}
1326
1327void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1328 CheckerContext &C) const {
1329 ExplodedNode *Pred = C.getPredecessor();
1330
1331 ProgramStateRef state = C.getState();
1332 RefBindingsTy B = state->get<RefBindings>();
1333 SmallVector<SymbolRef, 10> Leaked;
1334
1335 // Update counts from autorelease pools
1336 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
1337 E = SymReaper.dead_end(); I != E; ++I) {
1338 SymbolRef Sym = *I;
1339 if (const RefVal *T = B.lookup(Sym)){
1340 // Use the symbol as the tag.
1341 // FIXME: This might not be as unique as we would like.
1342 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
1343 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
1344 if (!state)
1345 return;
1346
1347 // Fetch the new reference count from the state, and use it to handle
1348 // this symbol.
1349 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
1350 }
1351 }
1352
1353 if (Leaked.empty()) {
1354 C.addTransition(state);
1355 return;
1356 }
1357
1358 Pred = processLeaks(state, Leaked, C, Pred);
1359
1360 // Did we cache out?
1361 if (!Pred)
1362 return;
1363
1364 // Now generate a new node that nukes the old bindings.
1365 // The only bindings left at this point are the leaked symbols.
1366 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
1367 B = state->get<RefBindings>();
1368
1369 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
1370 E = Leaked.end();
1371 I != E; ++I)
1372 B = F.remove(B, *I);
1373
1374 state = state->set<RefBindings>(B);
1375 C.addTransition(state, Pred);
1376}
1377
1378void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
1379 const char *NL, const char *Sep) const {
1380
1381 RefBindingsTy B = State->get<RefBindings>();
1382
1383 if (B.isEmpty())
1384 return;
1385
1386 Out << Sep << NL;
1387
1388 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
1389 Out << I->first << " : ";
1390 I->second.print(Out);
1391 Out << NL;
1392 }
1393}
1394
1395//===----------------------------------------------------------------------===//
1396// Implementation of the CallEffects API.
1397//===----------------------------------------------------------------------===//
1398
1399namespace clang {
1400namespace ento {
1401namespace objc_retain {
1402
1403// This is a bit gross, but it allows us to populate CallEffects without
1404// creating a bunch of accessors. This kind is very localized, so the
1405// damage of this macro is limited.
1406#define createCallEffect(D, KIND)\
1407 ASTContext &Ctx = D->getASTContext();\
1408 LangOptions L = Ctx.getLangOpts();\
1409 RetainSummaryManager M(Ctx, L.ObjCAutoRefCount);\
1410 const RetainSummary *S = M.get ## KIND ## Summary(D);\
1411 CallEffects CE(S->getRetEffect());\
1412 CE.Receiver = S->getReceiverEffect();\
1413 unsigned N = D->param_size();\
1414 for (unsigned i = 0; i < N; ++i) {\
1415 CE.Args.push_back(S->getArg(i));\
1416 }
1417
1418CallEffects CallEffects::getEffect(const ObjCMethodDecl *MD) {
1419 createCallEffect(MD, Method);
1420 return CE;
1421}
1422
1423CallEffects CallEffects::getEffect(const FunctionDecl *FD) {
1424 createCallEffect(FD, Function);
1425 return CE;
1426}
1427
1428#undef createCallEffect
1429
1430} // end namespace objc_retain
1431} // end namespace ento
1432} // end namespace clang
1433
1434//===----------------------------------------------------------------------===//
1435// Checker registration.
1436//===----------------------------------------------------------------------===//
1437
1438void ento::registerRetainCountChecker(CheckerManager &Mgr) {
1439 Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions());
1440}