blob: 30d4dd1bd8a91f377f39f76dcddc29b4f082e935 [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.
George Karpenkov6e9fd132018-08-22 01:17:09 +0000412 if (const auto *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg)) {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000413 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
414 if (Summ.getReceiverEffect() == StopTrackingHard) {
415 state = removeRefBinding(state, Sym);
416 }
417 }
418 }
419
420 // Consult the summary for the return value.
421 RetEffect RE = Summ.getRetEffect();
422 if (RE.getKind() == RetEffect::NoRetHard) {
423 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
424 if (Sym)
425 state = removeRefBinding(state, Sym);
426 }
427
428 C.addTransition(state);
429}
430
431static ProgramStateRef updateOutParameter(ProgramStateRef State,
432 SVal ArgVal,
433 ArgEffect Effect) {
434 auto *ArgRegion = dyn_cast_or_null<TypedValueRegion>(ArgVal.getAsRegion());
435 if (!ArgRegion)
436 return State;
437
438 QualType PointeeTy = ArgRegion->getValueType();
439 if (!coreFoundation::isCFObjectRef(PointeeTy))
440 return State;
441
442 SVal PointeeVal = State->getSVal(ArgRegion);
443 SymbolRef Pointee = PointeeVal.getAsLocSymbol();
444 if (!Pointee)
445 return State;
446
447 switch (Effect) {
448 case UnretainedOutParameter:
449 State = setRefBinding(State, Pointee,
450 RefVal::makeNotOwned(RetEffect::CF, PointeeTy));
451 break;
452 case RetainedOutParameter:
453 // Do nothing. Retained out parameters will either point to a +1 reference
454 // or NULL, but the way you check for failure differs depending on the API.
455 // Consequently, we don't have a good way to track them yet.
456 break;
457
458 default:
459 llvm_unreachable("only for out parameters");
460 }
461
462 return State;
463}
464
465void RetainCountChecker::checkSummary(const RetainSummary &Summ,
466 const CallEvent &CallOrMsg,
467 CheckerContext &C) const {
468 ProgramStateRef state = C.getState();
469
470 // Evaluate the effect of the arguments.
471 RefVal::Kind hasErr = (RefVal::Kind) 0;
472 SourceRange ErrorRange;
473 SymbolRef ErrorSym = nullptr;
474
475 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
476 SVal V = CallOrMsg.getArgSVal(idx);
477
478 ArgEffect Effect = Summ.getArg(idx);
479 if (Effect == RetainedOutParameter || Effect == UnretainedOutParameter) {
480 state = updateOutParameter(state, V, Effect);
481 } else if (SymbolRef Sym = V.getAsLocSymbol()) {
482 if (const RefVal *T = getRefBinding(state, Sym)) {
483 state = updateSymbol(state, Sym, *T, Effect, hasErr, C);
484 if (hasErr) {
485 ErrorRange = CallOrMsg.getArgSourceRange(idx);
486 ErrorSym = Sym;
487 break;
488 }
489 }
490 }
491 }
492
493 // Evaluate the effect on the message receiver.
494 bool ReceiverIsTracked = false;
495 if (!hasErr) {
496 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
497 if (MsgInvocation) {
498 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
499 if (const RefVal *T = getRefBinding(state, Sym)) {
500 ReceiverIsTracked = true;
501 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
502 hasErr, C);
503 if (hasErr) {
504 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
505 ErrorSym = Sym;
506 }
507 }
508 }
509 }
510 }
511
512 // Process any errors.
513 if (hasErr) {
514 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
515 return;
516 }
517
518 // Consult the summary for the return value.
519 RetEffect RE = Summ.getRetEffect();
520
521 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
522 if (ReceiverIsTracked)
523 RE = getSummaryManager(C).getObjAllocRetEffect();
524 else
525 RE = RetEffect::MakeNoRet();
526 }
527
George Karpenkov80c9e782018-08-22 01:16:49 +0000528 if (SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol()) {
529 QualType ResultTy = CallOrMsg.getResultType();
530 if (RE.notOwned()) {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000531 const Expr *Ex = CallOrMsg.getOriginExpr();
George Karpenkov70c2ee32018-08-17 21:41:07 +0000532 assert(Ex);
George Karpenkov80c9e782018-08-22 01:16:49 +0000533 ResultTy = GetReturnType(Ex, C.getASTContext());
George Karpenkov70c2ee32018-08-17 21:41:07 +0000534 }
George Karpenkov80c9e782018-08-22 01:16:49 +0000535 if (Optional<RefVal> updatedRefVal = refValFromRetEffect(RE, ResultTy))
536 state = setRefBinding(state, Sym, *updatedRefVal);
George Karpenkov70c2ee32018-08-17 21:41:07 +0000537 }
538
539 // This check is actually necessary; otherwise the statement builder thinks
540 // we've hit a previously-found path.
541 // Normally addTransition takes care of this, but we want the node pointer.
542 ExplodedNode *NewNode;
543 if (state == C.getState()) {
544 NewNode = C.getPredecessor();
545 } else {
546 NewNode = C.addTransition(state);
547 }
548
549 // Annotate the node with summary we used.
550 if (NewNode) {
551 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
552 if (ShouldResetSummaryLog) {
553 SummaryLog.clear();
554 ShouldResetSummaryLog = false;
555 }
556 SummaryLog[NewNode] = &Summ;
557 }
558}
559
560ProgramStateRef
561RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
562 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
563 CheckerContext &C) const {
564 bool IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
565 switch (E) {
566 default:
567 break;
568 case IncRefMsg:
569 E = IgnoreRetainMsg ? DoNothing : IncRef;
570 break;
571 case DecRefMsg:
572 E = IgnoreRetainMsg ? DoNothing: DecRef;
573 break;
574 case DecRefMsgAndStopTrackingHard:
575 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
576 break;
George Karpenkovbc0cddf2018-08-17 21:42:59 +0000577 case MakeCollectable:
578 E = DoNothing;
George Karpenkov70c2ee32018-08-17 21:41:07 +0000579 }
580
581 // Handle all use-after-releases.
582 if (V.getKind() == RefVal::Released) {
583 V = V ^ RefVal::ErrorUseAfterRelease;
584 hasErr = V.getKind();
585 return setRefBinding(state, sym, V);
586 }
587
588 switch (E) {
589 case DecRefMsg:
590 case IncRefMsg:
George Karpenkovbc0cddf2018-08-17 21:42:59 +0000591 case MakeCollectable:
George Karpenkov70c2ee32018-08-17 21:41:07 +0000592 case DecRefMsgAndStopTrackingHard:
George Karpenkovbc0cddf2018-08-17 21:42:59 +0000593 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
George Karpenkov70c2ee32018-08-17 21:41:07 +0000594
595 case UnretainedOutParameter:
596 case RetainedOutParameter:
597 llvm_unreachable("Applies to pointer-to-pointer parameters, which should "
598 "not have ref state.");
599
600 case Dealloc:
601 switch (V.getKind()) {
602 default:
603 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
604 case RefVal::Owned:
605 // The object immediately transitions to the released state.
606 V = V ^ RefVal::Released;
607 V.clearCounts();
608 return setRefBinding(state, sym, V);
609 case RefVal::NotOwned:
610 V = V ^ RefVal::ErrorDeallocNotOwned;
611 hasErr = V.getKind();
612 break;
613 }
614 break;
615
616 case MayEscape:
617 if (V.getKind() == RefVal::Owned) {
618 V = V ^ RefVal::NotOwned;
619 break;
620 }
621
622 // Fall-through.
623
624 case DoNothing:
625 return state;
626
627 case Autorelease:
628 // Update the autorelease counts.
629 V = V.autorelease();
630 break;
631
632 case StopTracking:
633 case StopTrackingHard:
634 return removeRefBinding(state, sym);
635
636 case IncRef:
637 switch (V.getKind()) {
638 default:
639 llvm_unreachable("Invalid RefVal state for a retain.");
640 case RefVal::Owned:
641 case RefVal::NotOwned:
642 V = V + 1;
643 break;
644 }
645 break;
646
647 case DecRef:
648 case DecRefBridgedTransferred:
649 case DecRefAndStopTrackingHard:
650 switch (V.getKind()) {
651 default:
652 // case 'RefVal::Released' handled above.
653 llvm_unreachable("Invalid RefVal state for a release.");
654
655 case RefVal::Owned:
656 assert(V.getCount() > 0);
657 if (V.getCount() == 1) {
658 if (E == DecRefBridgedTransferred ||
659 V.getIvarAccessHistory() ==
660 RefVal::IvarAccessHistory::AccessedDirectly)
661 V = V ^ RefVal::NotOwned;
662 else
663 V = V ^ RefVal::Released;
664 } else if (E == DecRefAndStopTrackingHard) {
665 return removeRefBinding(state, sym);
666 }
667
668 V = V - 1;
669 break;
670
671 case RefVal::NotOwned:
672 if (V.getCount() > 0) {
673 if (E == DecRefAndStopTrackingHard)
674 return removeRefBinding(state, sym);
675 V = V - 1;
676 } else if (V.getIvarAccessHistory() ==
677 RefVal::IvarAccessHistory::AccessedDirectly) {
678 // Assume that the instance variable was holding on the object at
679 // +1, and we just didn't know.
680 if (E == DecRefAndStopTrackingHard)
681 return removeRefBinding(state, sym);
682 V = V.releaseViaIvar() ^ RefVal::Released;
683 } else {
684 V = V ^ RefVal::ErrorReleaseNotOwned;
685 hasErr = V.getKind();
686 }
687 break;
688 }
689 break;
690 }
691 return setRefBinding(state, sym, V);
692}
693
694void RetainCountChecker::processNonLeakError(ProgramStateRef St,
695 SourceRange ErrorRange,
696 RefVal::Kind ErrorKind,
697 SymbolRef Sym,
698 CheckerContext &C) const {
699 // HACK: Ignore retain-count issues on values accessed through ivars,
700 // because of cases like this:
701 // [_contentView retain];
702 // [_contentView removeFromSuperview];
703 // [self addSubview:_contentView]; // invalidates 'self'
704 // [_contentView release];
705 if (const RefVal *RV = getRefBinding(St, Sym))
706 if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
707 return;
708
709 ExplodedNode *N = C.generateErrorNode(St);
710 if (!N)
711 return;
712
713 CFRefBug *BT;
714 switch (ErrorKind) {
715 default:
716 llvm_unreachable("Unhandled error.");
717 case RefVal::ErrorUseAfterRelease:
718 if (!useAfterRelease)
719 useAfterRelease.reset(new UseAfterRelease(this));
720 BT = useAfterRelease.get();
721 break;
722 case RefVal::ErrorReleaseNotOwned:
723 if (!releaseNotOwned)
724 releaseNotOwned.reset(new BadRelease(this));
725 BT = releaseNotOwned.get();
726 break;
727 case RefVal::ErrorDeallocNotOwned:
728 if (!deallocNotOwned)
729 deallocNotOwned.reset(new DeallocNotOwned(this));
730 BT = deallocNotOwned.get();
731 break;
732 }
733
734 assert(BT);
735 auto report = std::unique_ptr<BugReport>(
736 new CFRefReport(*BT, C.getASTContext().getLangOpts(),
737 SummaryLog, N, Sym));
738 report->addRange(ErrorRange);
739 C.emitReport(std::move(report));
740}
741
742//===----------------------------------------------------------------------===//
743// Handle the return values of retain-count-related functions.
744//===----------------------------------------------------------------------===//
745
746bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
747 // Get the callee. We're only interested in simple C functions.
748 ProgramStateRef state = C.getState();
749 const FunctionDecl *FD = C.getCalleeDecl(CE);
750 if (!FD)
751 return false;
752
George Karpenkovc4d6b932018-08-17 21:42:05 +0000753 RetainSummaryManager &SmrMgr = getSummaryManager(C);
754 QualType ResultTy = CE->getCallReturnType(C.getASTContext());
George Karpenkov70c2ee32018-08-17 21:41:07 +0000755
George Karpenkov70c2ee32018-08-17 21:41:07 +0000756 // See if the function has 'rc_ownership_trusted_implementation'
757 // annotate attribute. If it does, we will not inline it.
758 bool hasTrustedImplementationAnnotation = false;
759
George Karpenkovc4d6b932018-08-17 21:42:05 +0000760 // See if it's one of the specific functions we know how to eval.
George Karpenkovb1b791b2018-08-17 21:43:27 +0000761 if (!SmrMgr.canEval(CE, FD, hasTrustedImplementationAnnotation))
George Karpenkov70c2ee32018-08-17 21:41:07 +0000762 return false;
763
764 // Bind the return value.
765 const LocationContext *LCtx = C.getLocationContext();
766 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
767 if (RetVal.isUnknown() ||
768 (hasTrustedImplementationAnnotation && !ResultTy.isNull())) {
769 // If the receiver is unknown or the function has
770 // 'rc_ownership_trusted_implementation' annotate attribute, conjure a
771 // return value.
772 SValBuilder &SVB = C.getSValBuilder();
773 RetVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, ResultTy, C.blockCount());
774 }
775 state = state->BindExpr(CE, LCtx, RetVal, false);
776
777 // FIXME: This should not be necessary, but otherwise the argument seems to be
778 // considered alive during the next statement.
779 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
780 // Save the refcount status of the argument.
781 SymbolRef Sym = RetVal.getAsLocSymbol();
782 const RefVal *Binding = nullptr;
783 if (Sym)
784 Binding = getRefBinding(state, Sym);
785
786 // Invalidate the argument region.
787 state = state->invalidateRegions(
788 ArgRegion, CE, C.blockCount(), LCtx,
789 /*CausesPointerEscape*/ hasTrustedImplementationAnnotation);
790
791 // Restore the refcount status of the argument.
792 if (Binding)
793 state = setRefBinding(state, Sym, *Binding);
794 }
795
796 C.addTransition(state);
797 return true;
798}
799
800//===----------------------------------------------------------------------===//
801// Handle return statements.
802//===----------------------------------------------------------------------===//
803
804void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
805 CheckerContext &C) const {
806
807 // Only adjust the reference count if this is the top-level call frame,
808 // and not the result of inlining. In the future, we should do
809 // better checking even for inlined calls, and see if they match
810 // with their expected semantics (e.g., the method should return a retained
811 // object, etc.).
812 if (!C.inTopFrame())
813 return;
814
815 const Expr *RetE = S->getRetValue();
816 if (!RetE)
817 return;
818
819 ProgramStateRef state = C.getState();
820 SymbolRef Sym =
821 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
822 if (!Sym)
823 return;
824
825 // Get the reference count binding (if any).
826 const RefVal *T = getRefBinding(state, Sym);
827 if (!T)
828 return;
829
830 // Change the reference count.
831 RefVal X = *T;
832
833 switch (X.getKind()) {
834 case RefVal::Owned: {
835 unsigned cnt = X.getCount();
836 assert(cnt > 0);
837 X.setCount(cnt - 1);
838 X = X ^ RefVal::ReturnedOwned;
839 break;
840 }
841
842 case RefVal::NotOwned: {
843 unsigned cnt = X.getCount();
844 if (cnt) {
845 X.setCount(cnt - 1);
846 X = X ^ RefVal::ReturnedOwned;
847 }
848 else {
849 X = X ^ RefVal::ReturnedNotOwned;
850 }
851 break;
852 }
853
854 default:
855 return;
856 }
857
858 // Update the binding.
859 state = setRefBinding(state, Sym, X);
860 ExplodedNode *Pred = C.addTransition(state);
861
862 // At this point we have updated the state properly.
863 // Everything after this is merely checking to see if the return value has
864 // been over- or under-retained.
865
866 // Did we cache out?
867 if (!Pred)
868 return;
869
870 // Update the autorelease counts.
871 static CheckerProgramPointTag AutoreleaseTag(this, "Autorelease");
872 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
873
874 // Did we cache out?
875 if (!state)
876 return;
877
878 // Get the updated binding.
879 T = getRefBinding(state, Sym);
880 assert(T);
881 X = *T;
882
883 // Consult the summary of the enclosing method.
884 RetainSummaryManager &Summaries = getSummaryManager(C);
885 const Decl *CD = &Pred->getCodeDecl();
886 RetEffect RE = RetEffect::MakeNoRet();
887
888 // FIXME: What is the convention for blocks? Is there one?
889 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
890 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
891 RE = Summ->getRetEffect();
892 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
893 if (!isa<CXXMethodDecl>(FD)) {
894 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
895 RE = Summ->getRetEffect();
896 }
897 }
898
899 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
900}
901
902void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
903 CheckerContext &C,
904 ExplodedNode *Pred,
905 RetEffect RE, RefVal X,
906 SymbolRef Sym,
907 ProgramStateRef state) const {
908 // HACK: Ignore retain-count issues on values accessed through ivars,
909 // because of cases like this:
910 // [_contentView retain];
911 // [_contentView removeFromSuperview];
912 // [self addSubview:_contentView]; // invalidates 'self'
913 // [_contentView release];
914 if (X.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
915 return;
916
917 // Any leaks or other errors?
918 if (X.isReturnedOwned() && X.getCount() == 0) {
919 if (RE.getKind() != RetEffect::NoRet) {
920 bool hasError = false;
921 if (!RE.isOwned()) {
922 // The returning type is a CF, we expect the enclosing method should
923 // return ownership.
924 hasError = true;
925 X = X ^ RefVal::ErrorLeakReturned;
926 }
927
928 if (hasError) {
929 // Generate an error node.
930 state = setRefBinding(state, Sym, X);
931
932 static CheckerProgramPointTag ReturnOwnLeakTag(this, "ReturnsOwnLeak");
933 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
934 if (N) {
935 const LangOptions &LOpts = C.getASTContext().getLangOpts();
936 C.emitReport(std::unique_ptr<BugReport>(new CFRefLeakReport(
937 *getLeakAtReturnBug(LOpts), LOpts,
938 SummaryLog, N, Sym, C, IncludeAllocationLine)));
939 }
940 }
941 }
942 } else if (X.isReturnedNotOwned()) {
943 if (RE.isOwned()) {
944 if (X.getIvarAccessHistory() ==
945 RefVal::IvarAccessHistory::AccessedDirectly) {
946 // Assume the method was trying to transfer a +1 reference from a
947 // strong ivar to the caller.
948 state = setRefBinding(state, Sym,
949 X.releaseViaIvar() ^ RefVal::ReturnedOwned);
950 } else {
951 // Trying to return a not owned object to a caller expecting an
952 // owned object.
953 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
954
955 static CheckerProgramPointTag
956 ReturnNotOwnedTag(this, "ReturnNotOwnedForOwned");
957
958 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
959 if (N) {
960 if (!returnNotOwnedForOwned)
961 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned(this));
962
963 C.emitReport(std::unique_ptr<BugReport>(new CFRefReport(
964 *returnNotOwnedForOwned, C.getASTContext().getLangOpts(),
965 SummaryLog, N, Sym)));
966 }
967 }
968 }
969 }
970}
971
972//===----------------------------------------------------------------------===//
973// Check various ways a symbol can be invalidated.
974//===----------------------------------------------------------------------===//
975
976void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
977 CheckerContext &C) const {
978 // Are we storing to something that causes the value to "escape"?
979 bool escapes = true;
980
981 // A value escapes in three possible cases (this may change):
982 //
983 // (1) we are binding to something that is not a memory region.
984 // (2) we are binding to a memregion that does not have stack storage
985 // (3) we are binding to a memregion with stack storage that the store
986 // does not understand.
987 ProgramStateRef state = C.getState();
988
George Karpenkov6e9fd132018-08-22 01:17:09 +0000989 if (auto regionLoc = loc.getAs<loc::MemRegionVal>()) {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000990 escapes = !regionLoc->getRegion()->hasStackStorage();
991
992 if (!escapes) {
993 // To test (3), generate a new state with the binding added. If it is
994 // the same state, then it escapes (since the store cannot represent
995 // the binding).
996 // Do this only if we know that the store is not supposed to generate the
997 // same state.
998 SVal StoredVal = state->getSVal(regionLoc->getRegion());
999 if (StoredVal != val)
1000 escapes = (state == (state->bindLoc(*regionLoc, val, C.getLocationContext())));
1001 }
1002 if (!escapes) {
1003 // Case 4: We do not currently model what happens when a symbol is
1004 // assigned to a struct field, so be conservative here and let the symbol
1005 // go. TODO: This could definitely be improved upon.
1006 escapes = !isa<VarRegion>(regionLoc->getRegion());
1007 }
1008 }
1009
1010 // If we are storing the value into an auto function scope variable annotated
1011 // with (__attribute__((cleanup))), stop tracking the value to avoid leak
1012 // false positives.
George Karpenkov6e9fd132018-08-22 01:17:09 +00001013 if (const auto *LVR = dyn_cast_or_null<VarRegion>(loc.getAsRegion())) {
George Karpenkov70c2ee32018-08-17 21:41:07 +00001014 const VarDecl *VD = LVR->getDecl();
1015 if (VD->hasAttr<CleanupAttr>()) {
1016 escapes = true;
1017 }
1018 }
1019
1020 // If our store can represent the binding and we aren't storing to something
1021 // that doesn't have local storage then just return and have the simulation
1022 // state continue as is.
1023 if (!escapes)
1024 return;
1025
1026 // Otherwise, find all symbols referenced by 'val' that we are tracking
1027 // and stop tracking them.
1028 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1029 C.addTransition(state);
1030}
1031
1032ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
George Karpenkov6e9fd132018-08-22 01:17:09 +00001033 SVal Cond,
1034 bool Assumption) const {
George Karpenkov70c2ee32018-08-17 21:41:07 +00001035 // FIXME: We may add to the interface of evalAssume the list of symbols
1036 // whose assumptions have changed. For now we just iterate through the
1037 // bindings and check if any of the tracked symbols are NULL. This isn't
1038 // too bad since the number of symbols we will track in practice are
1039 // probably small and evalAssume is only called at branches and a few
1040 // other places.
1041 RefBindingsTy B = state->get<RefBindings>();
1042
1043 if (B.isEmpty())
1044 return state;
1045
1046 bool changed = false;
1047 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
1048
1049 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
1050 // Check if the symbol is null stop tracking the symbol.
1051 ConstraintManager &CMgr = state->getConstraintManager();
1052 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1053 if (AllocFailed.isConstrainedTrue()) {
1054 changed = true;
1055 B = RefBFactory.remove(B, I.getKey());
1056 }
1057 }
1058
1059 if (changed)
1060 state = state->set<RefBindings>(B);
1061
1062 return state;
1063}
1064
1065ProgramStateRef
1066RetainCountChecker::checkRegionChanges(ProgramStateRef state,
1067 const InvalidatedSymbols *invalidated,
1068 ArrayRef<const MemRegion *> ExplicitRegions,
1069 ArrayRef<const MemRegion *> Regions,
1070 const LocationContext *LCtx,
1071 const CallEvent *Call) const {
1072 if (!invalidated)
1073 return state;
1074
1075 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
1076 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1077 E = ExplicitRegions.end(); I != E; ++I) {
1078 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
1079 WhitelistedSymbols.insert(SR->getSymbol());
1080 }
1081
1082 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
1083 E = invalidated->end(); I!=E; ++I) {
1084 SymbolRef sym = *I;
1085 if (WhitelistedSymbols.count(sym))
1086 continue;
1087 // Remove any existing reference-count binding.
1088 state = removeRefBinding(state, sym);
1089 }
1090 return state;
1091}
1092
1093//===----------------------------------------------------------------------===//
1094// Handle dead symbols and end-of-path.
1095//===----------------------------------------------------------------------===//
1096
1097ProgramStateRef
1098RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
1099 ExplodedNode *Pred,
1100 const ProgramPointTag *Tag,
1101 CheckerContext &Ctx,
1102 SymbolRef Sym, RefVal V) const {
1103 unsigned ACnt = V.getAutoreleaseCount();
1104
1105 // No autorelease counts? Nothing to be done.
1106 if (!ACnt)
1107 return state;
1108
1109 unsigned Cnt = V.getCount();
1110
1111 // FIXME: Handle sending 'autorelease' to already released object.
1112
1113 if (V.getKind() == RefVal::ReturnedOwned)
1114 ++Cnt;
1115
1116 // If we would over-release here, but we know the value came from an ivar,
1117 // assume it was a strong ivar that's just been relinquished.
1118 if (ACnt > Cnt &&
1119 V.getIvarAccessHistory() == RefVal::IvarAccessHistory::AccessedDirectly) {
1120 V = V.releaseViaIvar();
1121 --ACnt;
1122 }
1123
1124 if (ACnt <= Cnt) {
1125 if (ACnt == Cnt) {
1126 V.clearCounts();
1127 if (V.getKind() == RefVal::ReturnedOwned)
1128 V = V ^ RefVal::ReturnedNotOwned;
1129 else
1130 V = V ^ RefVal::NotOwned;
1131 } else {
1132 V.setCount(V.getCount() - ACnt);
1133 V.setAutoreleaseCount(0);
1134 }
1135 return setRefBinding(state, Sym, V);
1136 }
1137
1138 // HACK: Ignore retain-count issues on values accessed through ivars,
1139 // because of cases like this:
1140 // [_contentView retain];
1141 // [_contentView removeFromSuperview];
1142 // [self addSubview:_contentView]; // invalidates 'self'
1143 // [_contentView release];
1144 if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
1145 return state;
1146
1147 // Woah! More autorelease counts then retain counts left.
1148 // Emit hard error.
1149 V = V ^ RefVal::ErrorOverAutorelease;
1150 state = setRefBinding(state, Sym, V);
1151
1152 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
1153 if (N) {
1154 SmallString<128> sbuf;
1155 llvm::raw_svector_ostream os(sbuf);
1156 os << "Object was autoreleased ";
1157 if (V.getAutoreleaseCount() > 1)
1158 os << V.getAutoreleaseCount() << " times but the object ";
1159 else
1160 os << "but ";
1161 os << "has a +" << V.getCount() << " retain count";
1162
1163 if (!overAutorelease)
1164 overAutorelease.reset(new OverAutorelease(this));
1165
1166 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
1167 Ctx.emitReport(std::unique_ptr<BugReport>(
1168 new CFRefReport(*overAutorelease, LOpts,
1169 SummaryLog, N, Sym, os.str())));
1170 }
1171
1172 return nullptr;
1173}
1174
1175ProgramStateRef
1176RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
1177 SymbolRef sid, RefVal V,
1178 SmallVectorImpl<SymbolRef> &Leaked) const {
1179 bool hasLeak;
1180
1181 // HACK: Ignore retain-count issues on values accessed through ivars,
1182 // because of cases like this:
1183 // [_contentView retain];
1184 // [_contentView removeFromSuperview];
1185 // [self addSubview:_contentView]; // invalidates 'self'
1186 // [_contentView release];
1187 if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
1188 hasLeak = false;
1189 else if (V.isOwned())
1190 hasLeak = true;
1191 else if (V.isNotOwned() || V.isReturnedOwned())
1192 hasLeak = (V.getCount() > 0);
1193 else
1194 hasLeak = false;
1195
1196 if (!hasLeak)
1197 return removeRefBinding(state, sid);
1198
1199 Leaked.push_back(sid);
1200 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
1201}
1202
1203ExplodedNode *
1204RetainCountChecker::processLeaks(ProgramStateRef state,
1205 SmallVectorImpl<SymbolRef> &Leaked,
1206 CheckerContext &Ctx,
1207 ExplodedNode *Pred) const {
1208 // Generate an intermediate node representing the leak point.
1209 ExplodedNode *N = Ctx.addTransition(state, Pred);
1210
1211 if (N) {
1212 for (SmallVectorImpl<SymbolRef>::iterator
1213 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
1214
1215 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
1216 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts)
1217 : getLeakAtReturnBug(LOpts);
1218 assert(BT && "BugType not initialized.");
1219
1220 Ctx.emitReport(std::unique_ptr<BugReport>(
1221 new CFRefLeakReport(*BT, LOpts, SummaryLog, N, *I, Ctx,
1222 IncludeAllocationLine)));
1223 }
1224 }
1225
1226 return N;
1227}
1228
George Karpenkovb1b791b2018-08-17 21:43:27 +00001229static bool isISLObjectRef(QualType Ty) {
1230 return StringRef(Ty.getAsString()).startswith("isl_");
George Karpenkov70c2ee32018-08-17 21:41:07 +00001231}
1232
1233void RetainCountChecker::checkBeginFunction(CheckerContext &Ctx) const {
1234 if (!Ctx.inTopFrame())
1235 return;
1236
George Karpenkovc4d6b932018-08-17 21:42:05 +00001237 RetainSummaryManager &SmrMgr = getSummaryManager(Ctx);
George Karpenkov70c2ee32018-08-17 21:41:07 +00001238 const LocationContext *LCtx = Ctx.getLocationContext();
1239 const FunctionDecl *FD = dyn_cast<FunctionDecl>(LCtx->getDecl());
1240
George Karpenkovc4d6b932018-08-17 21:42:05 +00001241 if (!FD || SmrMgr.isTrustedReferenceCountImplementation(FD))
George Karpenkov70c2ee32018-08-17 21:41:07 +00001242 return;
1243
1244 ProgramStateRef state = Ctx.getState();
George Karpenkovc4d6b932018-08-17 21:42:05 +00001245 const RetainSummary *FunctionSummary = SmrMgr.getFunctionSummary(FD);
George Karpenkov70c2ee32018-08-17 21:41:07 +00001246 ArgEffects CalleeSideArgEffects = FunctionSummary->getArgEffects();
1247
1248 for (unsigned idx = 0, e = FD->getNumParams(); idx != e; ++idx) {
1249 const ParmVarDecl *Param = FD->getParamDecl(idx);
1250 SymbolRef Sym = state->getSVal(state->getRegion(Param, LCtx)).getAsSymbol();
1251
1252 QualType Ty = Param->getType();
1253 const ArgEffect *AE = CalleeSideArgEffects.lookup(idx);
George Karpenkovb1b791b2018-08-17 21:43:27 +00001254 if (AE && *AE == DecRef && isISLObjectRef(Ty)) {
George Karpenkov6e9fd132018-08-22 01:17:09 +00001255 state = setRefBinding(
1256 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}