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