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