RetainCountChecker.cpp revision ef94588752babc1b7c46b955e57945fc4c183db2
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 "ClangSACheckers.h" 16#include "clang/AST/DeclObjC.h" 17#include "clang/AST/DeclCXX.h" 18#include "clang/Basic/LangOptions.h" 19#include "clang/Basic/SourceManager.h" 20#include "clang/Analysis/DomainSpecific/CocoaConventions.h" 21#include "clang/AST/ParentMap.h" 22#include "clang/StaticAnalyzer/Core/Checker.h" 23#include "clang/StaticAnalyzer/Core/CheckerManager.h" 24#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 25#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" 26#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 27#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" 28#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h" 29#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h" 30#include "llvm/ADT/DenseMap.h" 31#include "llvm/ADT/FoldingSet.h" 32#include "llvm/ADT/ImmutableList.h" 33#include "llvm/ADT/ImmutableMap.h" 34#include "llvm/ADT/SmallString.h" 35#include "llvm/ADT/STLExtras.h" 36#include "llvm/ADT/StringExtras.h" 37#include <cstdarg> 38 39using namespace clang; 40using namespace ento; 41using llvm::StrInStrNoCase; 42 43namespace { 44/// Wrapper around different kinds of node builder, so that helper functions 45/// can have a common interface. 46class GenericNodeBuilderRefCount { 47 CheckerContext *C; 48 const ProgramPointTag *tag; 49public: 50 GenericNodeBuilderRefCount(CheckerContext &c, 51 const ProgramPointTag *t = 0) 52 : C(&c), tag(t){} 53 54 ExplodedNode *MakeNode(ProgramStateRef state, ExplodedNode *Pred, 55 bool MarkAsSink = false) { 56 return C->addTransition(state, Pred, tag, MarkAsSink); 57 } 58}; 59} // end anonymous namespace 60 61//===----------------------------------------------------------------------===// 62// Primitives used for constructing summaries for function/method calls. 63//===----------------------------------------------------------------------===// 64 65/// ArgEffect is used to summarize a function/method call's effect on a 66/// particular argument. 67enum ArgEffect { DoNothing, Autorelease, Dealloc, DecRef, DecRefMsg, 68 DecRefBridgedTransfered, 69 IncRefMsg, IncRef, MakeCollectable, MayEscape, 70 NewAutoreleasePool, SelfOwn, StopTracking }; 71 72namespace llvm { 73template <> struct FoldingSetTrait<ArgEffect> { 74static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) { 75 ID.AddInteger((unsigned) X); 76} 77}; 78} // end llvm namespace 79 80/// ArgEffects summarizes the effects of a function/method call on all of 81/// its arguments. 82typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects; 83 84namespace { 85 86/// RetEffect is used to summarize a function/method call's behavior with 87/// respect to its return value. 88class RetEffect { 89public: 90 enum Kind { NoRet, OwnedSymbol, OwnedAllocatedSymbol, 91 NotOwnedSymbol, GCNotOwnedSymbol, ARCNotOwnedSymbol, 92 OwnedWhenTrackedReceiver }; 93 94 enum ObjKind { CF, ObjC, AnyObj }; 95 96private: 97 Kind K; 98 ObjKind O; 99 100 RetEffect(Kind k, ObjKind o = AnyObj) : K(k), O(o) {} 101 102public: 103 Kind getKind() const { return K; } 104 105 ObjKind getObjKind() const { return O; } 106 107 bool isOwned() const { 108 return K == OwnedSymbol || K == OwnedAllocatedSymbol || 109 K == OwnedWhenTrackedReceiver; 110 } 111 112 bool operator==(const RetEffect &Other) const { 113 return K == Other.K && O == Other.O; 114 } 115 116 static RetEffect MakeOwnedWhenTrackedReceiver() { 117 return RetEffect(OwnedWhenTrackedReceiver, ObjC); 118 } 119 120 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) { 121 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o); 122 } 123 static RetEffect MakeNotOwned(ObjKind o) { 124 return RetEffect(NotOwnedSymbol, o); 125 } 126 static RetEffect MakeGCNotOwned() { 127 return RetEffect(GCNotOwnedSymbol, ObjC); 128 } 129 static RetEffect MakeARCNotOwned() { 130 return RetEffect(ARCNotOwnedSymbol, ObjC); 131 } 132 static RetEffect MakeNoRet() { 133 return RetEffect(NoRet); 134 } 135 136 void Profile(llvm::FoldingSetNodeID& ID) const { 137 ID.AddInteger((unsigned) K); 138 ID.AddInteger((unsigned) O); 139 } 140}; 141 142//===----------------------------------------------------------------------===// 143// Reference-counting logic (typestate + counts). 144//===----------------------------------------------------------------------===// 145 146class RefVal { 147public: 148 enum Kind { 149 Owned = 0, // Owning reference. 150 NotOwned, // Reference is not owned by still valid (not freed). 151 Released, // Object has been released. 152 ReturnedOwned, // Returned object passes ownership to caller. 153 ReturnedNotOwned, // Return object does not pass ownership to caller. 154 ERROR_START, 155 ErrorDeallocNotOwned, // -dealloc called on non-owned object. 156 ErrorDeallocGC, // Calling -dealloc with GC enabled. 157 ErrorUseAfterRelease, // Object used after released. 158 ErrorReleaseNotOwned, // Release of an object that was not owned. 159 ERROR_LEAK_START, 160 ErrorLeak, // A memory leak due to excessive reference counts. 161 ErrorLeakReturned, // A memory leak due to the returning method not having 162 // the correct naming conventions. 163 ErrorGCLeakReturned, 164 ErrorOverAutorelease, 165 ErrorReturnedNotOwned 166 }; 167 168private: 169 Kind kind; 170 RetEffect::ObjKind okind; 171 unsigned Cnt; 172 unsigned ACnt; 173 QualType T; 174 175 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t) 176 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {} 177 178public: 179 Kind getKind() const { return kind; } 180 181 RetEffect::ObjKind getObjKind() const { return okind; } 182 183 unsigned getCount() const { return Cnt; } 184 unsigned getAutoreleaseCount() const { return ACnt; } 185 unsigned getCombinedCounts() const { return Cnt + ACnt; } 186 void clearCounts() { Cnt = 0; ACnt = 0; } 187 void setCount(unsigned i) { Cnt = i; } 188 void setAutoreleaseCount(unsigned i) { ACnt = i; } 189 190 QualType getType() const { return T; } 191 192 bool isOwned() const { 193 return getKind() == Owned; 194 } 195 196 bool isNotOwned() const { 197 return getKind() == NotOwned; 198 } 199 200 bool isReturnedOwned() const { 201 return getKind() == ReturnedOwned; 202 } 203 204 bool isReturnedNotOwned() const { 205 return getKind() == ReturnedNotOwned; 206 } 207 208 static RefVal makeOwned(RetEffect::ObjKind o, QualType t, 209 unsigned Count = 1) { 210 return RefVal(Owned, o, Count, 0, t); 211 } 212 213 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t, 214 unsigned Count = 0) { 215 return RefVal(NotOwned, o, Count, 0, t); 216 } 217 218 // Comparison, profiling, and pretty-printing. 219 220 bool operator==(const RefVal& X) const { 221 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt; 222 } 223 224 RefVal operator-(size_t i) const { 225 return RefVal(getKind(), getObjKind(), getCount() - i, 226 getAutoreleaseCount(), getType()); 227 } 228 229 RefVal operator+(size_t i) const { 230 return RefVal(getKind(), getObjKind(), getCount() + i, 231 getAutoreleaseCount(), getType()); 232 } 233 234 RefVal operator^(Kind k) const { 235 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(), 236 getType()); 237 } 238 239 RefVal autorelease() const { 240 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1, 241 getType()); 242 } 243 244 void Profile(llvm::FoldingSetNodeID& ID) const { 245 ID.AddInteger((unsigned) kind); 246 ID.AddInteger(Cnt); 247 ID.AddInteger(ACnt); 248 ID.Add(T); 249 } 250 251 void print(raw_ostream &Out) const; 252}; 253 254void RefVal::print(raw_ostream &Out) const { 255 if (!T.isNull()) 256 Out << "Tracked " << T.getAsString() << '/'; 257 258 switch (getKind()) { 259 default: llvm_unreachable("Invalid RefVal kind"); 260 case Owned: { 261 Out << "Owned"; 262 unsigned cnt = getCount(); 263 if (cnt) Out << " (+ " << cnt << ")"; 264 break; 265 } 266 267 case NotOwned: { 268 Out << "NotOwned"; 269 unsigned cnt = getCount(); 270 if (cnt) Out << " (+ " << cnt << ")"; 271 break; 272 } 273 274 case ReturnedOwned: { 275 Out << "ReturnedOwned"; 276 unsigned cnt = getCount(); 277 if (cnt) Out << " (+ " << cnt << ")"; 278 break; 279 } 280 281 case ReturnedNotOwned: { 282 Out << "ReturnedNotOwned"; 283 unsigned cnt = getCount(); 284 if (cnt) Out << " (+ " << cnt << ")"; 285 break; 286 } 287 288 case Released: 289 Out << "Released"; 290 break; 291 292 case ErrorDeallocGC: 293 Out << "-dealloc (GC)"; 294 break; 295 296 case ErrorDeallocNotOwned: 297 Out << "-dealloc (not-owned)"; 298 break; 299 300 case ErrorLeak: 301 Out << "Leaked"; 302 break; 303 304 case ErrorLeakReturned: 305 Out << "Leaked (Bad naming)"; 306 break; 307 308 case ErrorGCLeakReturned: 309 Out << "Leaked (GC-ed at return)"; 310 break; 311 312 case ErrorUseAfterRelease: 313 Out << "Use-After-Release [ERROR]"; 314 break; 315 316 case ErrorReleaseNotOwned: 317 Out << "Release of Not-Owned [ERROR]"; 318 break; 319 320 case RefVal::ErrorOverAutorelease: 321 Out << "Over autoreleased"; 322 break; 323 324 case RefVal::ErrorReturnedNotOwned: 325 Out << "Non-owned object returned instead of owned"; 326 break; 327 } 328 329 if (ACnt) { 330 Out << " [ARC +" << ACnt << ']'; 331 } 332} 333} //end anonymous namespace 334 335//===----------------------------------------------------------------------===// 336// RefBindings - State used to track object reference counts. 337//===----------------------------------------------------------------------===// 338 339typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings; 340 341namespace clang { 342namespace ento { 343template<> 344struct ProgramStateTrait<RefBindings> 345 : public ProgramStatePartialTrait<RefBindings> { 346 static void *GDMIndex() { 347 static int RefBIndex = 0; 348 return &RefBIndex; 349 } 350}; 351} 352} 353 354//===----------------------------------------------------------------------===// 355// Function/Method behavior summaries. 356//===----------------------------------------------------------------------===// 357 358namespace { 359class RetainSummary { 360 /// Args - a map of (index, ArgEffect) pairs, where index 361 /// specifies the argument (starting from 0). This can be sparsely 362 /// populated; arguments with no entry in Args use 'DefaultArgEffect'. 363 ArgEffects Args; 364 365 /// DefaultArgEffect - The default ArgEffect to apply to arguments that 366 /// do not have an entry in Args. 367 ArgEffect DefaultArgEffect; 368 369 /// Receiver - If this summary applies to an Objective-C message expression, 370 /// this is the effect applied to the state of the receiver. 371 ArgEffect Receiver; 372 373 /// Ret - The effect on the return value. Used to indicate if the 374 /// function/method call returns a new tracked symbol. 375 RetEffect Ret; 376 377public: 378 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff, 379 ArgEffect ReceiverEff) 380 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {} 381 382 /// getArg - Return the argument effect on the argument specified by 383 /// idx (starting from 0). 384 ArgEffect getArg(unsigned idx) const { 385 if (const ArgEffect *AE = Args.lookup(idx)) 386 return *AE; 387 388 return DefaultArgEffect; 389 } 390 391 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) { 392 Args = af.add(Args, idx, e); 393 } 394 395 /// setDefaultArgEffect - Set the default argument effect. 396 void setDefaultArgEffect(ArgEffect E) { 397 DefaultArgEffect = E; 398 } 399 400 /// getRetEffect - Returns the effect on the return value of the call. 401 RetEffect getRetEffect() const { return Ret; } 402 403 /// setRetEffect - Set the effect of the return value of the call. 404 void setRetEffect(RetEffect E) { Ret = E; } 405 406 407 /// Sets the effect on the receiver of the message. 408 void setReceiverEffect(ArgEffect e) { Receiver = e; } 409 410 /// getReceiverEffect - Returns the effect on the receiver of the call. 411 /// This is only meaningful if the summary applies to an ObjCMessageExpr*. 412 ArgEffect getReceiverEffect() const { return Receiver; } 413 414 /// Test if two retain summaries are identical. Note that merely equivalent 415 /// summaries are not necessarily identical (for example, if an explicit 416 /// argument effect matches the default effect). 417 bool operator==(const RetainSummary &Other) const { 418 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect && 419 Receiver == Other.Receiver && Ret == Other.Ret; 420 } 421 422 /// Profile this summary for inclusion in a FoldingSet. 423 void Profile(llvm::FoldingSetNodeID& ID) const { 424 ID.Add(Args); 425 ID.Add(DefaultArgEffect); 426 ID.Add(Receiver); 427 ID.Add(Ret); 428 } 429 430 /// A retain summary is simple if it has no ArgEffects other than the default. 431 bool isSimple() const { 432 return Args.isEmpty(); 433 } 434}; 435} // end anonymous namespace 436 437//===----------------------------------------------------------------------===// 438// Data structures for constructing summaries. 439//===----------------------------------------------------------------------===// 440 441namespace { 442class ObjCSummaryKey { 443 IdentifierInfo* II; 444 Selector S; 445public: 446 ObjCSummaryKey(IdentifierInfo* ii, Selector s) 447 : II(ii), S(s) {} 448 449 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s) 450 : II(d ? d->getIdentifier() : 0), S(s) {} 451 452 ObjCSummaryKey(const ObjCInterfaceDecl *d, IdentifierInfo *ii, Selector s) 453 : II(d ? d->getIdentifier() : ii), S(s) {} 454 455 ObjCSummaryKey(Selector s) 456 : II(0), S(s) {} 457 458 IdentifierInfo *getIdentifier() const { return II; } 459 Selector getSelector() const { return S; } 460}; 461} 462 463namespace llvm { 464template <> struct DenseMapInfo<ObjCSummaryKey> { 465 static inline ObjCSummaryKey getEmptyKey() { 466 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(), 467 DenseMapInfo<Selector>::getEmptyKey()); 468 } 469 470 static inline ObjCSummaryKey getTombstoneKey() { 471 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(), 472 DenseMapInfo<Selector>::getTombstoneKey()); 473 } 474 475 static unsigned getHashValue(const ObjCSummaryKey &V) { 476 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier()) 477 & 0x88888888) 478 | (DenseMapInfo<Selector>::getHashValue(V.getSelector()) 479 & 0x55555555); 480 } 481 482 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) { 483 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(), 484 RHS.getIdentifier()) && 485 DenseMapInfo<Selector>::isEqual(LHS.getSelector(), 486 RHS.getSelector()); 487 } 488 489}; 490template <> 491struct isPodLike<ObjCSummaryKey> { static const bool value = true; }; 492} // end llvm namespace 493 494namespace { 495class ObjCSummaryCache { 496 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy; 497 MapTy M; 498public: 499 ObjCSummaryCache() {} 500 501 const RetainSummary * find(const ObjCInterfaceDecl *D, IdentifierInfo *ClsName, 502 Selector S) { 503 // Lookup the method using the decl for the class @interface. If we 504 // have no decl, lookup using the class name. 505 return D ? find(D, S) : find(ClsName, S); 506 } 507 508 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) { 509 // Do a lookup with the (D,S) pair. If we find a match return 510 // the iterator. 511 ObjCSummaryKey K(D, S); 512 MapTy::iterator I = M.find(K); 513 514 if (I != M.end() || !D) 515 return I->second; 516 517 // Walk the super chain. If we find a hit with a parent, we'll end 518 // up returning that summary. We actually allow that key (null,S), as 519 // we cache summaries for the null ObjCInterfaceDecl* to allow us to 520 // generate initial summaries without having to worry about NSObject 521 // being declared. 522 // FIXME: We may change this at some point. 523 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) { 524 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end()) 525 break; 526 527 if (!C) 528 return NULL; 529 } 530 531 // Cache the summary with original key to make the next lookup faster 532 // and return the iterator. 533 const RetainSummary *Summ = I->second; 534 M[K] = Summ; 535 return Summ; 536 } 537 538 const RetainSummary *find(IdentifierInfo* II, Selector S) { 539 // FIXME: Class method lookup. Right now we dont' have a good way 540 // of going between IdentifierInfo* and the class hierarchy. 541 MapTy::iterator I = M.find(ObjCSummaryKey(II, S)); 542 543 if (I == M.end()) 544 I = M.find(ObjCSummaryKey(S)); 545 546 return I == M.end() ? NULL : I->second; 547 } 548 549 const RetainSummary *& operator[](ObjCSummaryKey K) { 550 return M[K]; 551 } 552 553 const RetainSummary *& operator[](Selector S) { 554 return M[ ObjCSummaryKey(S) ]; 555 } 556}; 557} // end anonymous namespace 558 559//===----------------------------------------------------------------------===// 560// Data structures for managing collections of summaries. 561//===----------------------------------------------------------------------===// 562 563namespace { 564class RetainSummaryManager { 565 566 //==-----------------------------------------------------------------==// 567 // Typedefs. 568 //==-----------------------------------------------------------------==// 569 570 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *> 571 FuncSummariesTy; 572 573 typedef ObjCSummaryCache ObjCMethodSummariesTy; 574 575 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode; 576 577 //==-----------------------------------------------------------------==// 578 // Data. 579 //==-----------------------------------------------------------------==// 580 581 /// Ctx - The ASTContext object for the analyzed ASTs. 582 ASTContext &Ctx; 583 584 /// GCEnabled - Records whether or not the analyzed code runs in GC mode. 585 const bool GCEnabled; 586 587 /// Records whether or not the analyzed code runs in ARC mode. 588 const bool ARCEnabled; 589 590 /// FuncSummaries - A map from FunctionDecls to summaries. 591 FuncSummariesTy FuncSummaries; 592 593 /// ObjCClassMethodSummaries - A map from selectors (for instance methods) 594 /// to summaries. 595 ObjCMethodSummariesTy ObjCClassMethodSummaries; 596 597 /// ObjCMethodSummaries - A map from selectors to summaries. 598 ObjCMethodSummariesTy ObjCMethodSummaries; 599 600 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects, 601 /// and all other data used by the checker. 602 llvm::BumpPtrAllocator BPAlloc; 603 604 /// AF - A factory for ArgEffects objects. 605 ArgEffects::Factory AF; 606 607 /// ScratchArgs - A holding buffer for construct ArgEffects. 608 ArgEffects ScratchArgs; 609 610 /// ObjCAllocRetE - Default return effect for methods returning Objective-C 611 /// objects. 612 RetEffect ObjCAllocRetE; 613 614 /// ObjCInitRetE - Default return effect for init methods returning 615 /// Objective-C objects. 616 RetEffect ObjCInitRetE; 617 618 /// SimpleSummaries - Used for uniquing summaries that don't have special 619 /// effects. 620 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries; 621 622 //==-----------------------------------------------------------------==// 623 // Methods. 624 //==-----------------------------------------------------------------==// 625 626 /// getArgEffects - Returns a persistent ArgEffects object based on the 627 /// data in ScratchArgs. 628 ArgEffects getArgEffects(); 629 630 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable }; 631 632public: 633 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; } 634 635 const RetainSummary *getUnarySummary(const FunctionType* FT, 636 UnaryFuncKind func); 637 638 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD); 639 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD); 640 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD); 641 642 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm); 643 644 const RetainSummary *getPersistentSummary(RetEffect RetEff, 645 ArgEffect ReceiverEff = DoNothing, 646 ArgEffect DefaultEff = MayEscape) { 647 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff); 648 return getPersistentSummary(Summ); 649 } 650 651 const RetainSummary *getDefaultSummary() { 652 return getPersistentSummary(RetEffect::MakeNoRet(), 653 DoNothing, MayEscape); 654 } 655 656 const RetainSummary *getPersistentStopSummary() { 657 return getPersistentSummary(RetEffect::MakeNoRet(), 658 StopTracking, StopTracking); 659 } 660 661 void InitializeClassMethodSummaries(); 662 void InitializeMethodSummaries(); 663private: 664 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) { 665 ObjCClassMethodSummaries[S] = Summ; 666 } 667 668 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) { 669 ObjCMethodSummaries[S] = Summ; 670 } 671 672 void addClassMethSummary(const char* Cls, const char* name, 673 const RetainSummary *Summ, bool isNullary = true) { 674 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls); 675 Selector S = isNullary ? GetNullarySelector(name, Ctx) 676 : GetUnarySelector(name, Ctx); 677 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ; 678 } 679 680 void addInstMethSummary(const char* Cls, const char* nullaryName, 681 const RetainSummary *Summ) { 682 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls); 683 Selector S = GetNullarySelector(nullaryName, Ctx); 684 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ; 685 } 686 687 Selector generateSelector(va_list argp) { 688 SmallVector<IdentifierInfo*, 10> II; 689 690 while (const char* s = va_arg(argp, const char*)) 691 II.push_back(&Ctx.Idents.get(s)); 692 693 return Ctx.Selectors.getSelector(II.size(), &II[0]); 694 } 695 696 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries, 697 const RetainSummary * Summ, va_list argp) { 698 Selector S = generateSelector(argp); 699 Summaries[ObjCSummaryKey(ClsII, S)] = Summ; 700 } 701 702 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) { 703 va_list argp; 704 va_start(argp, Summ); 705 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp); 706 va_end(argp); 707 } 708 709 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) { 710 va_list argp; 711 va_start(argp, Summ); 712 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp); 713 va_end(argp); 714 } 715 716 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) { 717 va_list argp; 718 va_start(argp, Summ); 719 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp); 720 va_end(argp); 721 } 722 723public: 724 725 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC) 726 : Ctx(ctx), 727 GCEnabled(gcenabled), 728 ARCEnabled(usesARC), 729 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()), 730 ObjCAllocRetE(gcenabled 731 ? RetEffect::MakeGCNotOwned() 732 : (usesARC ? RetEffect::MakeARCNotOwned() 733 : RetEffect::MakeOwned(RetEffect::ObjC, true))), 734 ObjCInitRetE(gcenabled 735 ? RetEffect::MakeGCNotOwned() 736 : (usesARC ? RetEffect::MakeARCNotOwned() 737 : RetEffect::MakeOwnedWhenTrackedReceiver())) { 738 InitializeClassMethodSummaries(); 739 InitializeMethodSummaries(); 740 } 741 742 const RetainSummary *getSummary(const FunctionDecl *FD); 743 744 const RetainSummary *getMethodSummary(Selector S, IdentifierInfo *ClsName, 745 const ObjCInterfaceDecl *ID, 746 const ObjCMethodDecl *MD, 747 QualType RetTy, 748 ObjCMethodSummariesTy &CachedSummaries); 749 750 const RetainSummary *getInstanceMethodSummary(const ObjCMessage &msg, 751 ProgramStateRef state, 752 const LocationContext *LC); 753 754 const RetainSummary *getInstanceMethodSummary(const ObjCMessage &msg, 755 const ObjCInterfaceDecl *ID) { 756 return getMethodSummary(msg.getSelector(), 0, ID, msg.getMethodDecl(), 757 msg.getType(Ctx), ObjCMethodSummaries); 758 } 759 760 const RetainSummary *getClassMethodSummary(const ObjCMessage &msg) { 761 const ObjCInterfaceDecl *Class = 0; 762 if (!msg.isInstanceMessage()) 763 Class = msg.getReceiverInterface(); 764 765 return getMethodSummary(msg.getSelector(), Class->getIdentifier(), 766 Class, msg.getMethodDecl(), msg.getType(Ctx), 767 ObjCClassMethodSummaries); 768 } 769 770 /// getMethodSummary - This version of getMethodSummary is used to query 771 /// the summary for the current method being analyzed. 772 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) { 773 // FIXME: Eventually this should be unneeded. 774 const ObjCInterfaceDecl *ID = MD->getClassInterface(); 775 Selector S = MD->getSelector(); 776 IdentifierInfo *ClsName = ID->getIdentifier(); 777 QualType ResultTy = MD->getResultType(); 778 779 ObjCMethodSummariesTy *CachedSummaries; 780 if (MD->isInstanceMethod()) 781 CachedSummaries = &ObjCMethodSummaries; 782 else 783 CachedSummaries = &ObjCClassMethodSummaries; 784 785 return getMethodSummary(S, ClsName, ID, MD, ResultTy, *CachedSummaries); 786 } 787 788 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD, 789 Selector S, QualType RetTy); 790 791 void updateSummaryFromAnnotations(const RetainSummary *&Summ, 792 const ObjCMethodDecl *MD); 793 794 void updateSummaryFromAnnotations(const RetainSummary *&Summ, 795 const FunctionDecl *FD); 796 797 bool isGCEnabled() const { return GCEnabled; } 798 799 bool isARCEnabled() const { return ARCEnabled; } 800 801 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; } 802}; 803 804// Used to avoid allocating long-term (BPAlloc'd) memory for default retain 805// summaries. If a function or method looks like it has a default summary, but 806// it has annotations, the annotations are added to the stack-based template 807// and then copied into managed memory. 808class RetainSummaryTemplate { 809 RetainSummaryManager &Manager; 810 const RetainSummary *&RealSummary; 811 RetainSummary ScratchSummary; 812 bool Accessed; 813public: 814 RetainSummaryTemplate(const RetainSummary *&real, const RetainSummary &base, 815 RetainSummaryManager &mgr) 816 : Manager(mgr), RealSummary(real), ScratchSummary(real ? *real : base), 817 Accessed(false) {} 818 819 ~RetainSummaryTemplate() { 820 if (Accessed) 821 RealSummary = Manager.getPersistentSummary(ScratchSummary); 822 } 823 824 RetainSummary &operator*() { 825 Accessed = true; 826 return ScratchSummary; 827 } 828 829 RetainSummary *operator->() { 830 Accessed = true; 831 return &ScratchSummary; 832 } 833}; 834 835} // end anonymous namespace 836 837//===----------------------------------------------------------------------===// 838// Implementation of checker data structures. 839//===----------------------------------------------------------------------===// 840 841ArgEffects RetainSummaryManager::getArgEffects() { 842 ArgEffects AE = ScratchArgs; 843 ScratchArgs = AF.getEmptyMap(); 844 return AE; 845} 846 847const RetainSummary * 848RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) { 849 // Unique "simple" summaries -- those without ArgEffects. 850 if (OldSumm.isSimple()) { 851 llvm::FoldingSetNodeID ID; 852 OldSumm.Profile(ID); 853 854 void *Pos; 855 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos); 856 857 if (!N) { 858 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>(); 859 new (N) CachedSummaryNode(OldSumm); 860 SimpleSummaries.InsertNode(N, Pos); 861 } 862 863 return &N->getValue(); 864 } 865 866 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>(); 867 new (Summ) RetainSummary(OldSumm); 868 return Summ; 869} 870 871//===----------------------------------------------------------------------===// 872// Summary creation for functions (largely uses of Core Foundation). 873//===----------------------------------------------------------------------===// 874 875static bool isRetain(const FunctionDecl *FD, StringRef FName) { 876 return FName.endswith("Retain"); 877} 878 879static bool isRelease(const FunctionDecl *FD, StringRef FName) { 880 return FName.endswith("Release"); 881} 882 883static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) { 884 // FIXME: Remove FunctionDecl parameter. 885 // FIXME: Is it really okay if MakeCollectable isn't a suffix? 886 return FName.find("MakeCollectable") != StringRef::npos; 887} 888 889const RetainSummary * RetainSummaryManager::getSummary(const FunctionDecl *FD) { 890 // Look up a summary in our cache of FunctionDecls -> Summaries. 891 FuncSummariesTy::iterator I = FuncSummaries.find(FD); 892 if (I != FuncSummaries.end()) 893 return I->second; 894 895 // No summary? Generate one. 896 const RetainSummary *S = 0; 897 898 do { 899 // We generate "stop" summaries for implicitly defined functions. 900 if (FD->isImplicit()) { 901 S = getPersistentStopSummary(); 902 break; 903 } 904 // For C++ methods, generate an implicit "stop" summary as well. We 905 // can relax this once we have a clear policy for C++ methods and 906 // ownership attributes. 907 if (isa<CXXMethodDecl>(FD)) { 908 S = getPersistentStopSummary(); 909 break; 910 } 911 912 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the 913 // function's type. 914 const FunctionType* FT = FD->getType()->getAs<FunctionType>(); 915 const IdentifierInfo *II = FD->getIdentifier(); 916 if (!II) 917 break; 918 919 StringRef FName = II->getName(); 920 921 // Strip away preceding '_'. Doing this here will effect all the checks 922 // down below. 923 FName = FName.substr(FName.find_first_not_of('_')); 924 925 // Inspect the result type. 926 QualType RetTy = FT->getResultType(); 927 928 // FIXME: This should all be refactored into a chain of "summary lookup" 929 // filters. 930 assert(ScratchArgs.isEmpty()); 931 932 if (FName == "pthread_create") { 933 // Part of: <rdar://problem/7299394>. This will be addressed 934 // better with IPA. 935 S = getPersistentStopSummary(); 936 } else if (FName == "NSMakeCollectable") { 937 // Handle: id NSMakeCollectable(CFTypeRef) 938 S = (RetTy->isObjCIdType()) 939 ? getUnarySummary(FT, cfmakecollectable) 940 : getPersistentStopSummary(); 941 } else if (FName == "IOBSDNameMatching" || 942 FName == "IOServiceMatching" || 943 FName == "IOServiceNameMatching" || 944 FName == "IORegistryEntryIDMatching" || 945 FName == "IOOpenFirmwarePathMatching") { 946 // Part of <rdar://problem/6961230>. (IOKit) 947 // This should be addressed using a API table. 948 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true), 949 DoNothing, DoNothing); 950 } else if (FName == "IOServiceGetMatchingService" || 951 FName == "IOServiceGetMatchingServices") { 952 // FIXES: <rdar://problem/6326900> 953 // This should be addressed using a API table. This strcmp is also 954 // a little gross, but there is no need to super optimize here. 955 ScratchArgs = AF.add(ScratchArgs, 1, DecRef); 956 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); 957 } else if (FName == "IOServiceAddNotification" || 958 FName == "IOServiceAddMatchingNotification") { 959 // Part of <rdar://problem/6961230>. (IOKit) 960 // This should be addressed using a API table. 961 ScratchArgs = AF.add(ScratchArgs, 2, DecRef); 962 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); 963 } else if (FName == "CVPixelBufferCreateWithBytes") { 964 // FIXES: <rdar://problem/7283567> 965 // Eventually this can be improved by recognizing that the pixel 966 // buffer passed to CVPixelBufferCreateWithBytes is released via 967 // a callback and doing full IPA to make sure this is done correctly. 968 // FIXME: This function has an out parameter that returns an 969 // allocated object. 970 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking); 971 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); 972 } else if (FName == "CGBitmapContextCreateWithData") { 973 // FIXES: <rdar://problem/7358899> 974 // Eventually this can be improved by recognizing that 'releaseInfo' 975 // passed to CGBitmapContextCreateWithData is released via 976 // a callback and doing full IPA to make sure this is done correctly. 977 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking); 978 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true), 979 DoNothing, DoNothing); 980 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") { 981 // FIXES: <rdar://problem/7283567> 982 // Eventually this can be improved by recognizing that the pixel 983 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released 984 // via a callback and doing full IPA to make sure this is done 985 // correctly. 986 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking); 987 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); 988 } 989 990 // Did we get a summary? 991 if (S) 992 break; 993 994 // Enable this code once the semantics of NSDeallocateObject are resolved 995 // for GC. <rdar://problem/6619988> 996#if 0 997 // Handle: NSDeallocateObject(id anObject); 998 // This method does allow 'nil' (although we don't check it now). 999 if (strcmp(FName, "NSDeallocateObject") == 0) { 1000 return RetTy == Ctx.VoidTy 1001 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc) 1002 : getPersistentStopSummary(); 1003 } 1004#endif 1005 1006 if (RetTy->isPointerType()) { 1007 // For CoreFoundation ('CF') types. 1008 if (cocoa::isRefType(RetTy, "CF", FName)) { 1009 if (isRetain(FD, FName)) 1010 S = getUnarySummary(FT, cfretain); 1011 else if (isMakeCollectable(FD, FName)) 1012 S = getUnarySummary(FT, cfmakecollectable); 1013 else 1014 S = getCFCreateGetRuleSummary(FD); 1015 1016 break; 1017 } 1018 1019 // For CoreGraphics ('CG') types. 1020 if (cocoa::isRefType(RetTy, "CG", FName)) { 1021 if (isRetain(FD, FName)) 1022 S = getUnarySummary(FT, cfretain); 1023 else 1024 S = getCFCreateGetRuleSummary(FD); 1025 1026 break; 1027 } 1028 1029 // For the Disk Arbitration API (DiskArbitration/DADisk.h) 1030 if (cocoa::isRefType(RetTy, "DADisk") || 1031 cocoa::isRefType(RetTy, "DADissenter") || 1032 cocoa::isRefType(RetTy, "DASessionRef")) { 1033 S = getCFCreateGetRuleSummary(FD); 1034 break; 1035 } 1036 1037 break; 1038 } 1039 1040 // Check for release functions, the only kind of functions that we care 1041 // about that don't return a pointer type. 1042 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) { 1043 // Test for 'CGCF'. 1044 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2); 1045 1046 if (isRelease(FD, FName)) 1047 S = getUnarySummary(FT, cfrelease); 1048 else { 1049 assert (ScratchArgs.isEmpty()); 1050 // Remaining CoreFoundation and CoreGraphics functions. 1051 // We use to assume that they all strictly followed the ownership idiom 1052 // and that ownership cannot be transferred. While this is technically 1053 // correct, many methods allow a tracked object to escape. For example: 1054 // 1055 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...); 1056 // CFDictionaryAddValue(y, key, x); 1057 // CFRelease(x); 1058 // ... it is okay to use 'x' since 'y' has a reference to it 1059 // 1060 // We handle this and similar cases with the follow heuristic. If the 1061 // function name contains "InsertValue", "SetValue", "AddValue", 1062 // "AppendValue", or "SetAttribute", then we assume that arguments may 1063 // "escape." This means that something else holds on to the object, 1064 // allowing it be used even after its local retain count drops to 0. 1065 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos|| 1066 StrInStrNoCase(FName, "AddValue") != StringRef::npos || 1067 StrInStrNoCase(FName, "SetValue") != StringRef::npos || 1068 StrInStrNoCase(FName, "AppendValue") != StringRef::npos|| 1069 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos) 1070 ? MayEscape : DoNothing; 1071 1072 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E); 1073 } 1074 } 1075 } 1076 while (0); 1077 1078 // Annotations override defaults. 1079 updateSummaryFromAnnotations(S, FD); 1080 1081 FuncSummaries[FD] = S; 1082 return S; 1083} 1084 1085const RetainSummary * 1086RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) { 1087 if (coreFoundation::followsCreateRule(FD)) 1088 return getCFSummaryCreateRule(FD); 1089 1090 return getCFSummaryGetRule(FD); 1091} 1092 1093const RetainSummary * 1094RetainSummaryManager::getUnarySummary(const FunctionType* FT, 1095 UnaryFuncKind func) { 1096 1097 // Sanity check that this is *really* a unary function. This can 1098 // happen if people do weird things. 1099 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT); 1100 if (!FTP || FTP->getNumArgs() != 1) 1101 return getPersistentStopSummary(); 1102 1103 assert (ScratchArgs.isEmpty()); 1104 1105 ArgEffect Effect; 1106 switch (func) { 1107 case cfretain: Effect = IncRef; break; 1108 case cfrelease: Effect = DecRef; break; 1109 case cfmakecollectable: Effect = MakeCollectable; break; 1110 } 1111 1112 ScratchArgs = AF.add(ScratchArgs, 0, Effect); 1113 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); 1114} 1115 1116const RetainSummary * 1117RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) { 1118 assert (ScratchArgs.isEmpty()); 1119 1120 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true)); 1121} 1122 1123const RetainSummary * 1124RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) { 1125 assert (ScratchArgs.isEmpty()); 1126 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF), 1127 DoNothing, DoNothing); 1128} 1129 1130//===----------------------------------------------------------------------===// 1131// Summary creation for Selectors. 1132//===----------------------------------------------------------------------===// 1133 1134void 1135RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ, 1136 const FunctionDecl *FD) { 1137 if (!FD) 1138 return; 1139 1140 RetainSummaryTemplate Template(Summ, *getDefaultSummary(), *this); 1141 1142 // Effects on the parameters. 1143 unsigned parm_idx = 0; 1144 for (FunctionDecl::param_const_iterator pi = FD->param_begin(), 1145 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) { 1146 const ParmVarDecl *pd = *pi; 1147 if (pd->getAttr<NSConsumedAttr>()) { 1148 if (!GCEnabled) { 1149 Template->addArg(AF, parm_idx, DecRef); 1150 } 1151 } else if (pd->getAttr<CFConsumedAttr>()) { 1152 Template->addArg(AF, parm_idx, DecRef); 1153 } 1154 } 1155 1156 QualType RetTy = FD->getResultType(); 1157 1158 // Determine if there is a special return effect for this method. 1159 if (cocoa::isCocoaObjectRef(RetTy)) { 1160 if (FD->getAttr<NSReturnsRetainedAttr>()) { 1161 Template->setRetEffect(ObjCAllocRetE); 1162 } 1163 else if (FD->getAttr<CFReturnsRetainedAttr>()) { 1164 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true)); 1165 } 1166 else if (FD->getAttr<NSReturnsNotRetainedAttr>()) { 1167 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC)); 1168 } 1169 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) { 1170 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF)); 1171 } 1172 } else if (RetTy->getAs<PointerType>()) { 1173 if (FD->getAttr<CFReturnsRetainedAttr>()) { 1174 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true)); 1175 } 1176 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) { 1177 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF)); 1178 } 1179 } 1180} 1181 1182void 1183RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ, 1184 const ObjCMethodDecl *MD) { 1185 if (!MD) 1186 return; 1187 1188 RetainSummaryTemplate Template(Summ, *getDefaultSummary(), *this); 1189 bool isTrackedLoc = false; 1190 1191 // Effects on the receiver. 1192 if (MD->getAttr<NSConsumesSelfAttr>()) { 1193 if (!GCEnabled) 1194 Template->setReceiverEffect(DecRefMsg); 1195 } 1196 1197 // Effects on the parameters. 1198 unsigned parm_idx = 0; 1199 for (ObjCMethodDecl::param_const_iterator 1200 pi=MD->param_begin(), pe=MD->param_end(); 1201 pi != pe; ++pi, ++parm_idx) { 1202 const ParmVarDecl *pd = *pi; 1203 if (pd->getAttr<NSConsumedAttr>()) { 1204 if (!GCEnabled) 1205 Template->addArg(AF, parm_idx, DecRef); 1206 } 1207 else if(pd->getAttr<CFConsumedAttr>()) { 1208 Template->addArg(AF, parm_idx, DecRef); 1209 } 1210 } 1211 1212 // Determine if there is a special return effect for this method. 1213 if (cocoa::isCocoaObjectRef(MD->getResultType())) { 1214 if (MD->getAttr<NSReturnsRetainedAttr>()) { 1215 Template->setRetEffect(ObjCAllocRetE); 1216 return; 1217 } 1218 if (MD->getAttr<NSReturnsNotRetainedAttr>()) { 1219 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC)); 1220 return; 1221 } 1222 1223 isTrackedLoc = true; 1224 } else { 1225 isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL; 1226 } 1227 1228 if (isTrackedLoc) { 1229 if (MD->getAttr<CFReturnsRetainedAttr>()) 1230 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true)); 1231 else if (MD->getAttr<CFReturnsNotRetainedAttr>()) 1232 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF)); 1233 } 1234} 1235 1236const RetainSummary * 1237RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD, 1238 Selector S, QualType RetTy) { 1239 1240 if (MD) { 1241 // Scan the method decl for 'void*' arguments. These should be treated 1242 // as 'StopTracking' because they are often used with delegates. 1243 // Delegates are a frequent form of false positives with the retain 1244 // count checker. 1245 unsigned i = 0; 1246 for (ObjCMethodDecl::param_const_iterator I = MD->param_begin(), 1247 E = MD->param_end(); I != E; ++I, ++i) 1248 if (const ParmVarDecl *PD = *I) { 1249 QualType Ty = Ctx.getCanonicalType(PD->getType()); 1250 if (Ty.getLocalUnqualifiedType() == Ctx.VoidPtrTy) 1251 ScratchArgs = AF.add(ScratchArgs, i, StopTracking); 1252 } 1253 } 1254 1255 // Any special effects? 1256 ArgEffect ReceiverEff = DoNothing; 1257 RetEffect ResultEff = RetEffect::MakeNoRet(); 1258 1259 // Check the method family, and apply any default annotations. 1260 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) { 1261 case OMF_None: 1262 case OMF_performSelector: 1263 // Assume all Objective-C methods follow Cocoa Memory Management rules. 1264 // FIXME: Does the non-threaded performSelector family really belong here? 1265 // The selector could be, say, @selector(copy). 1266 if (cocoa::isCocoaObjectRef(RetTy)) 1267 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC); 1268 else if (coreFoundation::isCFObjectRef(RetTy)) { 1269 // ObjCMethodDecl currently doesn't consider CF objects as valid return 1270 // values for alloc, new, copy, or mutableCopy, so we have to 1271 // double-check with the selector. This is ugly, but there aren't that 1272 // many Objective-C methods that return CF objects, right? 1273 if (MD) { 1274 switch (S.getMethodFamily()) { 1275 case OMF_alloc: 1276 case OMF_new: 1277 case OMF_copy: 1278 case OMF_mutableCopy: 1279 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true); 1280 break; 1281 default: 1282 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF); 1283 break; 1284 } 1285 } else { 1286 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF); 1287 } 1288 } 1289 break; 1290 case OMF_init: 1291 ResultEff = ObjCInitRetE; 1292 ReceiverEff = DecRefMsg; 1293 break; 1294 case OMF_alloc: 1295 case OMF_new: 1296 case OMF_copy: 1297 case OMF_mutableCopy: 1298 if (cocoa::isCocoaObjectRef(RetTy)) 1299 ResultEff = ObjCAllocRetE; 1300 else if (coreFoundation::isCFObjectRef(RetTy)) 1301 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true); 1302 break; 1303 case OMF_autorelease: 1304 ReceiverEff = Autorelease; 1305 break; 1306 case OMF_retain: 1307 ReceiverEff = IncRefMsg; 1308 break; 1309 case OMF_release: 1310 ReceiverEff = DecRefMsg; 1311 break; 1312 case OMF_dealloc: 1313 ReceiverEff = Dealloc; 1314 break; 1315 case OMF_self: 1316 // -self is handled specially by the ExprEngine to propagate the receiver. 1317 break; 1318 case OMF_retainCount: 1319 case OMF_finalize: 1320 // These methods don't return objects. 1321 break; 1322 } 1323 1324 // If one of the arguments in the selector has the keyword 'delegate' we 1325 // should stop tracking the reference count for the receiver. This is 1326 // because the reference count is quite possibly handled by a delegate 1327 // method. 1328 if (S.isKeywordSelector()) { 1329 const std::string &str = S.getAsString(); 1330 assert(!str.empty()); 1331 if (StrInStrNoCase(str, "delegate:") != StringRef::npos) 1332 ReceiverEff = StopTracking; 1333 } 1334 1335 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing && 1336 ResultEff.getKind() == RetEffect::NoRet) 1337 return getDefaultSummary(); 1338 1339 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape); 1340} 1341 1342const RetainSummary * 1343RetainSummaryManager::getInstanceMethodSummary(const ObjCMessage &msg, 1344 ProgramStateRef state, 1345 const LocationContext *LC) { 1346 1347 // We need the type-information of the tracked receiver object 1348 // Retrieve it from the state. 1349 const Expr *Receiver = msg.getInstanceReceiver(); 1350 const ObjCInterfaceDecl *ID = 0; 1351 1352 // FIXME: Is this really working as expected? There are cases where 1353 // we just use the 'ID' from the message expression. 1354 SVal receiverV; 1355 1356 if (Receiver) { 1357 receiverV = state->getSValAsScalarOrLoc(Receiver, LC); 1358 1359 // FIXME: Eventually replace the use of state->get<RefBindings> with 1360 // a generic API for reasoning about the Objective-C types of symbolic 1361 // objects. 1362 if (SymbolRef Sym = receiverV.getAsLocSymbol()) 1363 if (const RefVal *T = state->get<RefBindings>(Sym)) 1364 if (const ObjCObjectPointerType* PT = 1365 T->getType()->getAs<ObjCObjectPointerType>()) 1366 ID = PT->getInterfaceDecl(); 1367 1368 // FIXME: this is a hack. This may or may not be the actual method 1369 // that is called. 1370 if (!ID) { 1371 if (const ObjCObjectPointerType *PT = 1372 Receiver->getType()->getAs<ObjCObjectPointerType>()) 1373 ID = PT->getInterfaceDecl(); 1374 } 1375 } else { 1376 // FIXME: Hack for 'super'. 1377 ID = msg.getReceiverInterface(); 1378 } 1379 1380 // FIXME: The receiver could be a reference to a class, meaning that 1381 // we should use the class method. 1382 return getInstanceMethodSummary(msg, ID); 1383} 1384 1385const RetainSummary * 1386RetainSummaryManager::getMethodSummary(Selector S, IdentifierInfo *ClsName, 1387 const ObjCInterfaceDecl *ID, 1388 const ObjCMethodDecl *MD, QualType RetTy, 1389 ObjCMethodSummariesTy &CachedSummaries) { 1390 1391 // Look up a summary in our summary cache. 1392 const RetainSummary *Summ = CachedSummaries.find(ID, ClsName, S); 1393 1394 if (!Summ) { 1395 Summ = getStandardMethodSummary(MD, S, RetTy); 1396 1397 // Annotations override defaults. 1398 updateSummaryFromAnnotations(Summ, MD); 1399 1400 // Memoize the summary. 1401 CachedSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ; 1402 } 1403 1404 return Summ; 1405} 1406 1407void RetainSummaryManager::InitializeClassMethodSummaries() { 1408 assert(ScratchArgs.isEmpty()); 1409 // Create the [NSAssertionHandler currentHander] summary. 1410 addClassMethSummary("NSAssertionHandler", "currentHandler", 1411 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC))); 1412 1413 // Create the [NSAutoreleasePool addObject:] summary. 1414 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease); 1415 addClassMethSummary("NSAutoreleasePool", "addObject", 1416 getPersistentSummary(RetEffect::MakeNoRet(), 1417 DoNothing, Autorelease)); 1418 1419 // Create the summaries for [NSObject performSelector...]. We treat 1420 // these as 'stop tracking' for the arguments because they are often 1421 // used for delegates that can release the object. When we have better 1422 // inter-procedural analysis we can potentially do something better. This 1423 // workaround is to remove false positives. 1424 const RetainSummary *Summ = 1425 getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking); 1426 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject"); 1427 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject", 1428 "afterDelay", NULL); 1429 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject", 1430 "afterDelay", "inModes", NULL); 1431 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread", 1432 "withObject", "waitUntilDone", NULL); 1433 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread", 1434 "withObject", "waitUntilDone", "modes", NULL); 1435 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread", 1436 "withObject", "waitUntilDone", NULL); 1437 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread", 1438 "withObject", "waitUntilDone", "modes", NULL); 1439 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground", 1440 "withObject", NULL); 1441} 1442 1443void RetainSummaryManager::InitializeMethodSummaries() { 1444 1445 assert (ScratchArgs.isEmpty()); 1446 1447 // Create the "init" selector. It just acts as a pass-through for the 1448 // receiver. 1449 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg); 1450 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm); 1451 1452 // awakeAfterUsingCoder: behaves basically like an 'init' method. It 1453 // claims the receiver and returns a retained object. 1454 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx), 1455 InitSumm); 1456 1457 // The next methods are allocators. 1458 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE); 1459 const RetainSummary *CFAllocSumm = 1460 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true)); 1461 1462 // Create the "retain" selector. 1463 RetEffect NoRet = RetEffect::MakeNoRet(); 1464 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg); 1465 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ); 1466 1467 // Create the "release" selector. 1468 Summ = getPersistentSummary(NoRet, DecRefMsg); 1469 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ); 1470 1471 // Create the "drain" selector. 1472 Summ = getPersistentSummary(NoRet, isGCEnabled() ? DoNothing : DecRef); 1473 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ); 1474 1475 // Create the -dealloc summary. 1476 Summ = getPersistentSummary(NoRet, Dealloc); 1477 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ); 1478 1479 // Create the "autorelease" selector. 1480 Summ = getPersistentSummary(NoRet, Autorelease); 1481 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ); 1482 1483 // Specially handle NSAutoreleasePool. 1484 addInstMethSummary("NSAutoreleasePool", "init", 1485 getPersistentSummary(NoRet, NewAutoreleasePool)); 1486 1487 // For NSWindow, allocated objects are (initially) self-owned. 1488 // FIXME: For now we opt for false negatives with NSWindow, as these objects 1489 // self-own themselves. However, they only do this once they are displayed. 1490 // Thus, we need to track an NSWindow's display status. 1491 // This is tracked in <rdar://problem/6062711>. 1492 // See also http://llvm.org/bugs/show_bug.cgi?id=3714. 1493 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(), 1494 StopTracking, 1495 StopTracking); 1496 1497 addClassMethSummary("NSWindow", "alloc", NoTrackYet); 1498 1499#if 0 1500 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect", 1501 "styleMask", "backing", "defer", NULL); 1502 1503 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect", 1504 "styleMask", "backing", "defer", "screen", NULL); 1505#endif 1506 1507 // For NSPanel (which subclasses NSWindow), allocated objects are not 1508 // self-owned. 1509 // FIXME: For now we don't track NSPanels. object for the same reason 1510 // as for NSWindow objects. 1511 addClassMethSummary("NSPanel", "alloc", NoTrackYet); 1512 1513#if 0 1514 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect", 1515 "styleMask", "backing", "defer", NULL); 1516 1517 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect", 1518 "styleMask", "backing", "defer", "screen", NULL); 1519#endif 1520 1521 // Don't track allocated autorelease pools yet, as it is okay to prematurely 1522 // exit a method. 1523 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet); 1524 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false); 1525 1526 // Create summaries QCRenderer/QCView -createSnapShotImageOfType: 1527 addInstMethSummary("QCRenderer", AllocSumm, 1528 "createSnapshotImageOfType", NULL); 1529 addInstMethSummary("QCView", AllocSumm, 1530 "createSnapshotImageOfType", NULL); 1531 1532 // Create summaries for CIContext, 'createCGImage' and 1533 // 'createCGLayerWithSize'. These objects are CF objects, and are not 1534 // automatically garbage collected. 1535 addInstMethSummary("CIContext", CFAllocSumm, 1536 "createCGImage", "fromRect", NULL); 1537 addInstMethSummary("CIContext", CFAllocSumm, 1538 "createCGImage", "fromRect", "format", "colorSpace", NULL); 1539 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", 1540 "info", NULL); 1541} 1542 1543//===----------------------------------------------------------------------===// 1544// AutoreleaseBindings - State used to track objects in autorelease pools. 1545//===----------------------------------------------------------------------===// 1546 1547typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts; 1548typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents; 1549typedef llvm::ImmutableList<SymbolRef> ARStack; 1550 1551static int AutoRCIndex = 0; 1552static int AutoRBIndex = 0; 1553 1554namespace { class AutoreleasePoolContents {}; } 1555namespace { class AutoreleaseStack {}; } 1556 1557namespace clang { 1558namespace ento { 1559template<> struct ProgramStateTrait<AutoreleaseStack> 1560 : public ProgramStatePartialTrait<ARStack> { 1561 static inline void *GDMIndex() { return &AutoRBIndex; } 1562}; 1563 1564template<> struct ProgramStateTrait<AutoreleasePoolContents> 1565 : public ProgramStatePartialTrait<ARPoolContents> { 1566 static inline void *GDMIndex() { return &AutoRCIndex; } 1567}; 1568} // end GR namespace 1569} // end clang namespace 1570 1571static SymbolRef GetCurrentAutoreleasePool(ProgramStateRef state) { 1572 ARStack stack = state->get<AutoreleaseStack>(); 1573 return stack.isEmpty() ? SymbolRef() : stack.getHead(); 1574} 1575 1576static ProgramStateRef 1577SendAutorelease(ProgramStateRef state, 1578 ARCounts::Factory &F, 1579 SymbolRef sym) { 1580 SymbolRef pool = GetCurrentAutoreleasePool(state); 1581 const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool); 1582 ARCounts newCnts(0); 1583 1584 if (cnts) { 1585 const unsigned *cnt = (*cnts).lookup(sym); 1586 newCnts = F.add(*cnts, sym, cnt ? *cnt + 1 : 1); 1587 } 1588 else 1589 newCnts = F.add(F.getEmptyMap(), sym, 1); 1590 1591 return state->set<AutoreleasePoolContents>(pool, newCnts); 1592} 1593 1594//===----------------------------------------------------------------------===// 1595// Error reporting. 1596//===----------------------------------------------------------------------===// 1597namespace { 1598 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *> 1599 SummaryLogTy; 1600 1601 //===-------------===// 1602 // Bug Descriptions. // 1603 //===-------------===// 1604 1605 class CFRefBug : public BugType { 1606 protected: 1607 CFRefBug(StringRef name) 1608 : BugType(name, "Memory (Core Foundation/Objective-C)") {} 1609 public: 1610 1611 // FIXME: Eventually remove. 1612 virtual const char *getDescription() const = 0; 1613 1614 virtual bool isLeak() const { return false; } 1615 }; 1616 1617 class UseAfterRelease : public CFRefBug { 1618 public: 1619 UseAfterRelease() : CFRefBug("Use-after-release") {} 1620 1621 const char *getDescription() const { 1622 return "Reference-counted object is used after it is released"; 1623 } 1624 }; 1625 1626 class BadRelease : public CFRefBug { 1627 public: 1628 BadRelease() : CFRefBug("Bad release") {} 1629 1630 const char *getDescription() const { 1631 return "Incorrect decrement of the reference count of an object that is " 1632 "not owned at this point by the caller"; 1633 } 1634 }; 1635 1636 class DeallocGC : public CFRefBug { 1637 public: 1638 DeallocGC() 1639 : CFRefBug("-dealloc called while using garbage collection") {} 1640 1641 const char *getDescription() const { 1642 return "-dealloc called while using garbage collection"; 1643 } 1644 }; 1645 1646 class DeallocNotOwned : public CFRefBug { 1647 public: 1648 DeallocNotOwned() 1649 : CFRefBug("-dealloc sent to non-exclusively owned object") {} 1650 1651 const char *getDescription() const { 1652 return "-dealloc sent to object that may be referenced elsewhere"; 1653 } 1654 }; 1655 1656 class OverAutorelease : public CFRefBug { 1657 public: 1658 OverAutorelease() 1659 : CFRefBug("Object sent -autorelease too many times") {} 1660 1661 const char *getDescription() const { 1662 return "Object sent -autorelease too many times"; 1663 } 1664 }; 1665 1666 class ReturnedNotOwnedForOwned : public CFRefBug { 1667 public: 1668 ReturnedNotOwnedForOwned() 1669 : CFRefBug("Method should return an owned object") {} 1670 1671 const char *getDescription() const { 1672 return "Object with a +0 retain count returned to caller where a +1 " 1673 "(owning) retain count is expected"; 1674 } 1675 }; 1676 1677 class Leak : public CFRefBug { 1678 const bool isReturn; 1679 protected: 1680 Leak(StringRef name, bool isRet) 1681 : CFRefBug(name), isReturn(isRet) { 1682 // Leaks should not be reported if they are post-dominated by a sink. 1683 setSuppressOnSink(true); 1684 } 1685 public: 1686 1687 const char *getDescription() const { return ""; } 1688 1689 bool isLeak() const { return true; } 1690 }; 1691 1692 class LeakAtReturn : public Leak { 1693 public: 1694 LeakAtReturn(StringRef name) 1695 : Leak(name, true) {} 1696 }; 1697 1698 class LeakWithinFunction : public Leak { 1699 public: 1700 LeakWithinFunction(StringRef name) 1701 : Leak(name, false) {} 1702 }; 1703 1704 //===---------===// 1705 // Bug Reports. // 1706 //===---------===// 1707 1708 class CFRefReportVisitor : public BugReporterVisitor { 1709 protected: 1710 SymbolRef Sym; 1711 const SummaryLogTy &SummaryLog; 1712 bool GCEnabled; 1713 1714 public: 1715 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log) 1716 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {} 1717 1718 virtual void Profile(llvm::FoldingSetNodeID &ID) const { 1719 static int x = 0; 1720 ID.AddPointer(&x); 1721 ID.AddPointer(Sym); 1722 } 1723 1724 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N, 1725 const ExplodedNode *PrevN, 1726 BugReporterContext &BRC, 1727 BugReport &BR); 1728 1729 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC, 1730 const ExplodedNode *N, 1731 BugReport &BR); 1732 }; 1733 1734 class CFRefLeakReportVisitor : public CFRefReportVisitor { 1735 public: 1736 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled, 1737 const SummaryLogTy &log) 1738 : CFRefReportVisitor(sym, GCEnabled, log) {} 1739 1740 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC, 1741 const ExplodedNode *N, 1742 BugReport &BR); 1743 }; 1744 1745 class CFRefReport : public BugReport { 1746 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled); 1747 1748 public: 1749 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled, 1750 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym, 1751 bool registerVisitor = true) 1752 : BugReport(D, D.getDescription(), n) { 1753 if (registerVisitor) 1754 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log)); 1755 addGCModeDescription(LOpts, GCEnabled); 1756 } 1757 1758 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled, 1759 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym, 1760 StringRef endText) 1761 : BugReport(D, D.getDescription(), endText, n) { 1762 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log)); 1763 addGCModeDescription(LOpts, GCEnabled); 1764 } 1765 1766 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() { 1767 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType()); 1768 if (!BugTy.isLeak()) 1769 return BugReport::getRanges(); 1770 else 1771 return std::make_pair(ranges_iterator(), ranges_iterator()); 1772 } 1773 }; 1774 1775 class CFRefLeakReport : public CFRefReport { 1776 const MemRegion* AllocBinding; 1777 1778 public: 1779 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled, 1780 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym, 1781 CheckerContext &Ctx); 1782 1783 PathDiagnosticLocation getLocation(const SourceManager &SM) const { 1784 assert(Location.isValid()); 1785 return Location; 1786 } 1787 }; 1788} // end anonymous namespace 1789 1790void CFRefReport::addGCModeDescription(const LangOptions &LOpts, 1791 bool GCEnabled) { 1792 const char *GCModeDescription = 0; 1793 1794 switch (LOpts.getGC()) { 1795 case LangOptions::GCOnly: 1796 assert(GCEnabled); 1797 GCModeDescription = "Code is compiled to only use garbage collection"; 1798 break; 1799 1800 case LangOptions::NonGC: 1801 assert(!GCEnabled); 1802 GCModeDescription = "Code is compiled to use reference counts"; 1803 break; 1804 1805 case LangOptions::HybridGC: 1806 if (GCEnabled) { 1807 GCModeDescription = "Code is compiled to use either garbage collection " 1808 "(GC) or reference counts (non-GC). The bug occurs " 1809 "with GC enabled"; 1810 break; 1811 } else { 1812 GCModeDescription = "Code is compiled to use either garbage collection " 1813 "(GC) or reference counts (non-GC). The bug occurs " 1814 "in non-GC mode"; 1815 break; 1816 } 1817 } 1818 1819 assert(GCModeDescription && "invalid/unknown GC mode"); 1820 addExtraText(GCModeDescription); 1821} 1822 1823// FIXME: This should be a method on SmallVector. 1824static inline bool contains(const SmallVectorImpl<ArgEffect>& V, 1825 ArgEffect X) { 1826 for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end(); 1827 I!=E; ++I) 1828 if (*I == X) return true; 1829 1830 return false; 1831} 1832 1833static bool isPropertyAccess(const Stmt *S, ParentMap &PM) { 1834 unsigned maxDepth = 4; 1835 while (S && maxDepth) { 1836 if (const PseudoObjectExpr *PO = dyn_cast<PseudoObjectExpr>(S)) { 1837 if (!isa<ObjCMessageExpr>(PO->getSyntacticForm())) 1838 return true; 1839 return false; 1840 } 1841 S = PM.getParent(S); 1842 --maxDepth; 1843 } 1844 return false; 1845} 1846 1847PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N, 1848 const ExplodedNode *PrevN, 1849 BugReporterContext &BRC, 1850 BugReport &BR) { 1851 1852 if (!isa<StmtPoint>(N->getLocation())) 1853 return NULL; 1854 1855 // Check if the type state has changed. 1856 ProgramStateRef PrevSt = PrevN->getState(); 1857 ProgramStateRef CurrSt = N->getState(); 1858 const LocationContext *LCtx = N->getLocationContext(); 1859 1860 const RefVal* CurrT = CurrSt->get<RefBindings>(Sym); 1861 if (!CurrT) return NULL; 1862 1863 const RefVal &CurrV = *CurrT; 1864 const RefVal *PrevT = PrevSt->get<RefBindings>(Sym); 1865 1866 // Create a string buffer to constain all the useful things we want 1867 // to tell the user. 1868 std::string sbuf; 1869 llvm::raw_string_ostream os(sbuf); 1870 1871 // This is the allocation site since the previous node had no bindings 1872 // for this symbol. 1873 if (!PrevT) { 1874 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt(); 1875 1876 if (isa<ObjCArrayLiteral>(S)) { 1877 os << "NSArray literal is an object with a +0 retain count"; 1878 } 1879 else if (isa<ObjCDictionaryLiteral>(S)) { 1880 os << "NSDictionary literal is an object with a +0 retain count"; 1881 } 1882 else { 1883 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) { 1884 // Get the name of the callee (if it is available). 1885 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx); 1886 if (const FunctionDecl *FD = X.getAsFunctionDecl()) 1887 os << "Call to function '" << *FD << '\''; 1888 else 1889 os << "function call"; 1890 } 1891 else { 1892 assert(isa<ObjCMessageExpr>(S)); 1893 // The message expression may have between written directly or as 1894 // a property access. Lazily determine which case we are looking at. 1895 os << (isPropertyAccess(S, N->getParentMap()) ? "Property" : "Method"); 1896 } 1897 1898 if (CurrV.getObjKind() == RetEffect::CF) { 1899 os << " returns a Core Foundation object with a "; 1900 } 1901 else { 1902 assert (CurrV.getObjKind() == RetEffect::ObjC); 1903 os << " returns an Objective-C object with a "; 1904 } 1905 1906 if (CurrV.isOwned()) { 1907 os << "+1 retain count"; 1908 1909 if (GCEnabled) { 1910 assert(CurrV.getObjKind() == RetEffect::CF); 1911 os << ". " 1912 "Core Foundation objects are not automatically garbage collected."; 1913 } 1914 } 1915 else { 1916 assert (CurrV.isNotOwned()); 1917 os << "+0 retain count"; 1918 } 1919 } 1920 1921 PathDiagnosticLocation Pos(S, BRC.getSourceManager(), 1922 N->getLocationContext()); 1923 return new PathDiagnosticEventPiece(Pos, os.str()); 1924 } 1925 1926 // Gather up the effects that were performed on the object at this 1927 // program point 1928 SmallVector<ArgEffect, 2> AEffects; 1929 1930 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N); 1931 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) { 1932 // We only have summaries attached to nodes after evaluating CallExpr and 1933 // ObjCMessageExprs. 1934 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt(); 1935 1936 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) { 1937 // Iterate through the parameter expressions and see if the symbol 1938 // was ever passed as an argument. 1939 unsigned i = 0; 1940 1941 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end(); 1942 AI!=AE; ++AI, ++i) { 1943 1944 // Retrieve the value of the argument. Is it the symbol 1945 // we are interested in? 1946 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym) 1947 continue; 1948 1949 // We have an argument. Get the effect! 1950 AEffects.push_back(Summ->getArg(i)); 1951 } 1952 } 1953 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) { 1954 if (const Expr *receiver = ME->getInstanceReceiver()) 1955 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx) 1956 .getAsLocSymbol() == Sym) { 1957 // The symbol we are tracking is the receiver. 1958 AEffects.push_back(Summ->getReceiverEffect()); 1959 } 1960 } 1961 } 1962 1963 do { 1964 // Get the previous type state. 1965 RefVal PrevV = *PrevT; 1966 1967 // Specially handle -dealloc. 1968 if (!GCEnabled && contains(AEffects, Dealloc)) { 1969 // Determine if the object's reference count was pushed to zero. 1970 assert(!(PrevV == CurrV) && "The typestate *must* have changed."); 1971 // We may not have transitioned to 'release' if we hit an error. 1972 // This case is handled elsewhere. 1973 if (CurrV.getKind() == RefVal::Released) { 1974 assert(CurrV.getCombinedCounts() == 0); 1975 os << "Object released by directly sending the '-dealloc' message"; 1976 break; 1977 } 1978 } 1979 1980 // Specially handle CFMakeCollectable and friends. 1981 if (contains(AEffects, MakeCollectable)) { 1982 // Get the name of the function. 1983 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt(); 1984 SVal X = 1985 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx); 1986 const FunctionDecl *FD = X.getAsFunctionDecl(); 1987 1988 if (GCEnabled) { 1989 // Determine if the object's reference count was pushed to zero. 1990 assert(!(PrevV == CurrV) && "The typestate *must* have changed."); 1991 1992 os << "In GC mode a call to '" << *FD 1993 << "' decrements an object's retain count and registers the " 1994 "object with the garbage collector. "; 1995 1996 if (CurrV.getKind() == RefVal::Released) { 1997 assert(CurrV.getCount() == 0); 1998 os << "Since it now has a 0 retain count the object can be " 1999 "automatically collected by the garbage collector."; 2000 } 2001 else 2002 os << "An object must have a 0 retain count to be garbage collected. " 2003 "After this call its retain count is +" << CurrV.getCount() 2004 << '.'; 2005 } 2006 else 2007 os << "When GC is not enabled a call to '" << *FD 2008 << "' has no effect on its argument."; 2009 2010 // Nothing more to say. 2011 break; 2012 } 2013 2014 // Determine if the typestate has changed. 2015 if (!(PrevV == CurrV)) 2016 switch (CurrV.getKind()) { 2017 case RefVal::Owned: 2018 case RefVal::NotOwned: 2019 2020 if (PrevV.getCount() == CurrV.getCount()) { 2021 // Did an autorelease message get sent? 2022 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount()) 2023 return 0; 2024 2025 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount()); 2026 os << "Object sent -autorelease message"; 2027 break; 2028 } 2029 2030 if (PrevV.getCount() > CurrV.getCount()) 2031 os << "Reference count decremented."; 2032 else 2033 os << "Reference count incremented."; 2034 2035 if (unsigned Count = CurrV.getCount()) 2036 os << " The object now has a +" << Count << " retain count."; 2037 2038 if (PrevV.getKind() == RefVal::Released) { 2039 assert(GCEnabled && CurrV.getCount() > 0); 2040 os << " The object is not eligible for garbage collection until " 2041 "the retain count reaches 0 again."; 2042 } 2043 2044 break; 2045 2046 case RefVal::Released: 2047 os << "Object released."; 2048 break; 2049 2050 case RefVal::ReturnedOwned: 2051 // Autoreleases can be applied after marking a node ReturnedOwned. 2052 if (CurrV.getAutoreleaseCount()) 2053 return NULL; 2054 2055 os << "Object returned to caller as an owning reference (single " 2056 "retain count transferred to caller)"; 2057 break; 2058 2059 case RefVal::ReturnedNotOwned: 2060 os << "Object returned to caller with a +0 retain count"; 2061 break; 2062 2063 default: 2064 return NULL; 2065 } 2066 2067 // Emit any remaining diagnostics for the argument effects (if any). 2068 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(), 2069 E=AEffects.end(); I != E; ++I) { 2070 2071 // A bunch of things have alternate behavior under GC. 2072 if (GCEnabled) 2073 switch (*I) { 2074 default: break; 2075 case Autorelease: 2076 os << "In GC mode an 'autorelease' has no effect."; 2077 continue; 2078 case IncRefMsg: 2079 os << "In GC mode the 'retain' message has no effect."; 2080 continue; 2081 case DecRefMsg: 2082 os << "In GC mode the 'release' message has no effect."; 2083 continue; 2084 } 2085 } 2086 } while (0); 2087 2088 if (os.str().empty()) 2089 return 0; // We have nothing to say! 2090 2091 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt(); 2092 PathDiagnosticLocation Pos(S, BRC.getSourceManager(), 2093 N->getLocationContext()); 2094 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str()); 2095 2096 // Add the range by scanning the children of the statement for any bindings 2097 // to Sym. 2098 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end(); 2099 I!=E; ++I) 2100 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I)) 2101 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) { 2102 P->addRange(Exp->getSourceRange()); 2103 break; 2104 } 2105 2106 return P; 2107} 2108 2109namespace { 2110 class FindUniqueBinding : 2111 public StoreManager::BindingsHandler { 2112 SymbolRef Sym; 2113 const MemRegion* Binding; 2114 bool First; 2115 2116 public: 2117 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {} 2118 2119 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R, 2120 SVal val) { 2121 2122 SymbolRef SymV = val.getAsSymbol(); 2123 if (!SymV || SymV != Sym) 2124 return true; 2125 2126 if (Binding) { 2127 First = false; 2128 return false; 2129 } 2130 else 2131 Binding = R; 2132 2133 return true; 2134 } 2135 2136 operator bool() { return First && Binding; } 2137 const MemRegion *getRegion() { return Binding; } 2138 }; 2139} 2140 2141// Find the first node in the current function context that referred to the 2142// tracked symbol and the memory location that value was stored to. Note, the 2143// value is only reported if the allocation occurred in the same function as 2144// the leak. 2145static std::pair<const ExplodedNode*,const MemRegion*> 2146GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N, 2147 SymbolRef Sym) { 2148 const ExplodedNode *Last = N; 2149 const MemRegion* FirstBinding = 0; 2150 const LocationContext *LeakContext = N->getLocationContext(); 2151 2152 while (N) { 2153 ProgramStateRef St = N->getState(); 2154 RefBindings B = St->get<RefBindings>(); 2155 2156 if (!B.lookup(Sym)) 2157 break; 2158 2159 FindUniqueBinding FB(Sym); 2160 StateMgr.iterBindings(St, FB); 2161 if (FB) FirstBinding = FB.getRegion(); 2162 2163 // Allocation node, is the last node in the current context in which the 2164 // symbol was tracked. 2165 if (N->getLocationContext() == LeakContext) 2166 Last = N; 2167 2168 N = N->pred_empty() ? NULL : *(N->pred_begin()); 2169 } 2170 2171 // If allocation happened in a function different from the leak node context, 2172 // do not report the binding. 2173 if (N->getLocationContext() != LeakContext) { 2174 FirstBinding = 0; 2175 } 2176 2177 return std::make_pair(Last, FirstBinding); 2178} 2179 2180PathDiagnosticPiece* 2181CFRefReportVisitor::getEndPath(BugReporterContext &BRC, 2182 const ExplodedNode *EndN, 2183 BugReport &BR) { 2184 BR.markInteresting(Sym); 2185 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR); 2186} 2187 2188PathDiagnosticPiece* 2189CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC, 2190 const ExplodedNode *EndN, 2191 BugReport &BR) { 2192 2193 // Tell the BugReporterContext to report cases when the tracked symbol is 2194 // assigned to different variables, etc. 2195 BR.markInteresting(Sym); 2196 2197 // We are reporting a leak. Walk up the graph to get to the first node where 2198 // the symbol appeared, and also get the first VarDecl that tracked object 2199 // is stored to. 2200 const ExplodedNode *AllocNode = 0; 2201 const MemRegion* FirstBinding = 0; 2202 2203 llvm::tie(AllocNode, FirstBinding) = 2204 GetAllocationSite(BRC.getStateManager(), EndN, Sym); 2205 2206 SourceManager& SM = BRC.getSourceManager(); 2207 2208 // Compute an actual location for the leak. Sometimes a leak doesn't 2209 // occur at an actual statement (e.g., transition between blocks; end 2210 // of function) so we need to walk the graph and compute a real location. 2211 const ExplodedNode *LeakN = EndN; 2212 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM); 2213 2214 std::string sbuf; 2215 llvm::raw_string_ostream os(sbuf); 2216 2217 os << "Object leaked: "; 2218 2219 if (FirstBinding) { 2220 os << "object allocated and stored into '" 2221 << FirstBinding->getString() << '\''; 2222 } 2223 else 2224 os << "allocated object"; 2225 2226 // Get the retain count. 2227 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym); 2228 2229 if (RV->getKind() == RefVal::ErrorLeakReturned) { 2230 // FIXME: Per comments in rdar://6320065, "create" only applies to CF 2231 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership 2232 // to the caller for NS objects. 2233 const Decl *D = &EndN->getCodeDecl(); 2234 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 2235 os << " is returned from a method whose name ('" 2236 << MD->getSelector().getAsString() 2237 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'." 2238 " This violates the naming convention rules" 2239 " given in the Memory Management Guide for Cocoa"; 2240 } 2241 else { 2242 const FunctionDecl *FD = cast<FunctionDecl>(D); 2243 os << " is returned from a function whose name ('" 2244 << *FD 2245 << "') does not contain 'Copy' or 'Create'. This violates the naming" 2246 " convention rules given in the Memory Management Guide for Core" 2247 " Foundation"; 2248 } 2249 } 2250 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) { 2251 ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl()); 2252 os << " and returned from method '" << MD.getSelector().getAsString() 2253 << "' is potentially leaked when using garbage collection. Callers " 2254 "of this method do not expect a returned object with a +1 retain " 2255 "count since they expect the object to be managed by the garbage " 2256 "collector"; 2257 } 2258 else 2259 os << " is not referenced later in this execution path and has a retain " 2260 "count of +" << RV->getCount(); 2261 2262 return new PathDiagnosticEventPiece(L, os.str()); 2263} 2264 2265CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, 2266 bool GCEnabled, const SummaryLogTy &Log, 2267 ExplodedNode *n, SymbolRef sym, 2268 CheckerContext &Ctx) 2269: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) { 2270 2271 // Most bug reports are cached at the location where they occurred. 2272 // With leaks, we want to unique them by the location where they were 2273 // allocated, and only report a single path. To do this, we need to find 2274 // the allocation site of a piece of tracked memory, which we do via a 2275 // call to GetAllocationSite. This will walk the ExplodedGraph backwards. 2276 // Note that this is *not* the trimmed graph; we are guaranteed, however, 2277 // that all ancestor nodes that represent the allocation site have the 2278 // same SourceLocation. 2279 const ExplodedNode *AllocNode = 0; 2280 2281 const SourceManager& SMgr = Ctx.getSourceManager(); 2282 2283 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding. 2284 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym); 2285 2286 // Get the SourceLocation for the allocation site. 2287 ProgramPoint P = AllocNode->getLocation(); 2288 const Stmt *AllocStmt = cast<PostStmt>(P).getStmt(); 2289 Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr, 2290 n->getLocationContext()); 2291 // Fill in the description of the bug. 2292 Description.clear(); 2293 llvm::raw_string_ostream os(Description); 2294 os << "Potential leak "; 2295 if (GCEnabled) 2296 os << "(when using garbage collection) "; 2297 os << "of an object"; 2298 2299 // FIXME: AllocBinding doesn't get populated for RegionStore yet. 2300 if (AllocBinding) 2301 os << " stored into '" << AllocBinding->getString() << '\''; 2302 2303 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log)); 2304} 2305 2306//===----------------------------------------------------------------------===// 2307// Main checker logic. 2308//===----------------------------------------------------------------------===// 2309 2310namespace { 2311class RetainCountChecker 2312 : public Checker< check::Bind, 2313 check::DeadSymbols, 2314 check::EndAnalysis, 2315 check::EndPath, 2316 check::PostStmt<BlockExpr>, 2317 check::PostStmt<CastExpr>, 2318 check::PostStmt<CallExpr>, 2319 check::PostStmt<CXXConstructExpr>, 2320 check::PostStmt<ObjCArrayLiteral>, 2321 check::PostStmt<ObjCDictionaryLiteral>, 2322 check::PostObjCMessage, 2323 check::PreStmt<ReturnStmt>, 2324 check::RegionChanges, 2325 eval::Assume, 2326 eval::Call > { 2327 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned; 2328 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned; 2329 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned; 2330 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn; 2331 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC; 2332 2333 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap; 2334 2335 // This map is only used to ensure proper deletion of any allocated tags. 2336 mutable SymbolTagMap DeadSymbolTags; 2337 2338 mutable OwningPtr<RetainSummaryManager> Summaries; 2339 mutable OwningPtr<RetainSummaryManager> SummariesGC; 2340 2341 mutable ARCounts::Factory ARCountFactory; 2342 2343 mutable SummaryLogTy SummaryLog; 2344 mutable bool ShouldResetSummaryLog; 2345 2346public: 2347 RetainCountChecker() : ShouldResetSummaryLog(false) {} 2348 2349 virtual ~RetainCountChecker() { 2350 DeleteContainerSeconds(DeadSymbolTags); 2351 } 2352 2353 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR, 2354 ExprEngine &Eng) const { 2355 // FIXME: This is a hack to make sure the summary log gets cleared between 2356 // analyses of different code bodies. 2357 // 2358 // Why is this necessary? Because a checker's lifetime is tied to a 2359 // translation unit, but an ExplodedGraph's lifetime is just a code body. 2360 // Once in a blue moon, a new ExplodedNode will have the same address as an 2361 // old one with an associated summary, and the bug report visitor gets very 2362 // confused. (To make things worse, the summary lifetime is currently also 2363 // tied to a code body, so we get a crash instead of incorrect results.) 2364 // 2365 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph 2366 // changes, things will start going wrong again. Really the lifetime of this 2367 // log needs to be tied to either the specific nodes in it or the entire 2368 // ExplodedGraph, not to a specific part of the code being analyzed. 2369 // 2370 // (Also, having stateful local data means that the same checker can't be 2371 // used from multiple threads, but a lot of checkers have incorrect 2372 // assumptions about that anyway. So that wasn't a priority at the time of 2373 // this fix.) 2374 // 2375 // This happens at the end of analysis, but bug reports are emitted /after/ 2376 // this point. So we can't just clear the summary log now. Instead, we mark 2377 // that the next time we access the summary log, it should be cleared. 2378 2379 // If we never reset the summary log during /this/ code body analysis, 2380 // there were no new summaries. There might still have been summaries from 2381 // the /last/ analysis, so clear them out to make sure the bug report 2382 // visitors don't get confused. 2383 if (ShouldResetSummaryLog) 2384 SummaryLog.clear(); 2385 2386 ShouldResetSummaryLog = !SummaryLog.empty(); 2387 } 2388 2389 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts, 2390 bool GCEnabled) const { 2391 if (GCEnabled) { 2392 if (!leakWithinFunctionGC) 2393 leakWithinFunctionGC.reset(new LeakWithinFunction("Leak of object when " 2394 "using garbage " 2395 "collection")); 2396 return leakWithinFunctionGC.get(); 2397 } else { 2398 if (!leakWithinFunction) { 2399 if (LOpts.getGC() == LangOptions::HybridGC) { 2400 leakWithinFunction.reset(new LeakWithinFunction("Leak of object when " 2401 "not using garbage " 2402 "collection (GC) in " 2403 "dual GC/non-GC " 2404 "code")); 2405 } else { 2406 leakWithinFunction.reset(new LeakWithinFunction("Leak")); 2407 } 2408 } 2409 return leakWithinFunction.get(); 2410 } 2411 } 2412 2413 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const { 2414 if (GCEnabled) { 2415 if (!leakAtReturnGC) 2416 leakAtReturnGC.reset(new LeakAtReturn("Leak of returned object when " 2417 "using garbage collection")); 2418 return leakAtReturnGC.get(); 2419 } else { 2420 if (!leakAtReturn) { 2421 if (LOpts.getGC() == LangOptions::HybridGC) { 2422 leakAtReturn.reset(new LeakAtReturn("Leak of returned object when " 2423 "not using garbage collection " 2424 "(GC) in dual GC/non-GC code")); 2425 } else { 2426 leakAtReturn.reset(new LeakAtReturn("Leak of returned object")); 2427 } 2428 } 2429 return leakAtReturn.get(); 2430 } 2431 } 2432 2433 RetainSummaryManager &getSummaryManager(ASTContext &Ctx, 2434 bool GCEnabled) const { 2435 // FIXME: We don't support ARC being turned on and off during one analysis. 2436 // (nor, for that matter, do we support changing ASTContexts) 2437 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount; 2438 if (GCEnabled) { 2439 if (!SummariesGC) 2440 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled)); 2441 else 2442 assert(SummariesGC->isARCEnabled() == ARCEnabled); 2443 return *SummariesGC; 2444 } else { 2445 if (!Summaries) 2446 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled)); 2447 else 2448 assert(Summaries->isARCEnabled() == ARCEnabled); 2449 return *Summaries; 2450 } 2451 } 2452 2453 RetainSummaryManager &getSummaryManager(CheckerContext &C) const { 2454 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled()); 2455 } 2456 2457 void printState(raw_ostream &Out, ProgramStateRef State, 2458 const char *NL, const char *Sep) const; 2459 2460 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const; 2461 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const; 2462 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const; 2463 2464 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const; 2465 void checkPostStmt(const CXXConstructExpr *CE, CheckerContext &C) const; 2466 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const; 2467 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const; 2468 void checkPostObjCMessage(const ObjCMessage &Msg, CheckerContext &C) const; 2469 2470 void checkSummary(const RetainSummary &Summ, const CallOrObjCMessage &Call, 2471 CheckerContext &C) const; 2472 2473 bool evalCall(const CallExpr *CE, CheckerContext &C) const; 2474 2475 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond, 2476 bool Assumption) const; 2477 2478 ProgramStateRef 2479 checkRegionChanges(ProgramStateRef state, 2480 const StoreManager::InvalidatedSymbols *invalidated, 2481 ArrayRef<const MemRegion *> ExplicitRegions, 2482 ArrayRef<const MemRegion *> Regions, 2483 const CallOrObjCMessage *Call) const; 2484 2485 bool wantsRegionChangeUpdate(ProgramStateRef state) const { 2486 return true; 2487 } 2488 2489 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const; 2490 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C, 2491 ExplodedNode *Pred, RetEffect RE, RefVal X, 2492 SymbolRef Sym, ProgramStateRef state) const; 2493 2494 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const; 2495 void checkEndPath(CheckerContext &C) const; 2496 2497 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym, 2498 RefVal V, ArgEffect E, RefVal::Kind &hasErr, 2499 CheckerContext &C) const; 2500 2501 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange, 2502 RefVal::Kind ErrorKind, SymbolRef Sym, 2503 CheckerContext &C) const; 2504 2505 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const; 2506 2507 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const; 2508 2509 ProgramStateRef handleSymbolDeath(ProgramStateRef state, 2510 SymbolRef sid, RefVal V, 2511 SmallVectorImpl<SymbolRef> &Leaked) const; 2512 2513 std::pair<ExplodedNode *, ProgramStateRef > 2514 handleAutoreleaseCounts(ProgramStateRef state, 2515 GenericNodeBuilderRefCount Bd, ExplodedNode *Pred, 2516 CheckerContext &Ctx, SymbolRef Sym, RefVal V) const; 2517 2518 ExplodedNode *processLeaks(ProgramStateRef state, 2519 SmallVectorImpl<SymbolRef> &Leaked, 2520 GenericNodeBuilderRefCount &Builder, 2521 CheckerContext &Ctx, 2522 ExplodedNode *Pred = 0) const; 2523}; 2524} // end anonymous namespace 2525 2526namespace { 2527class StopTrackingCallback : public SymbolVisitor { 2528 ProgramStateRef state; 2529public: 2530 StopTrackingCallback(ProgramStateRef st) : state(st) {} 2531 ProgramStateRef getState() const { return state; } 2532 2533 bool VisitSymbol(SymbolRef sym) { 2534 state = state->remove<RefBindings>(sym); 2535 return true; 2536 } 2537}; 2538} // end anonymous namespace 2539 2540//===----------------------------------------------------------------------===// 2541// Handle statements that may have an effect on refcounts. 2542//===----------------------------------------------------------------------===// 2543 2544void RetainCountChecker::checkPostStmt(const BlockExpr *BE, 2545 CheckerContext &C) const { 2546 2547 // Scan the BlockDecRefExprs for any object the retain count checker 2548 // may be tracking. 2549 if (!BE->getBlockDecl()->hasCaptures()) 2550 return; 2551 2552 ProgramStateRef state = C.getState(); 2553 const BlockDataRegion *R = 2554 cast<BlockDataRegion>(state->getSVal(BE, 2555 C.getLocationContext()).getAsRegion()); 2556 2557 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(), 2558 E = R->referenced_vars_end(); 2559 2560 if (I == E) 2561 return; 2562 2563 // FIXME: For now we invalidate the tracking of all symbols passed to blocks 2564 // via captured variables, even though captured variables result in a copy 2565 // and in implicit increment/decrement of a retain count. 2566 SmallVector<const MemRegion*, 10> Regions; 2567 const LocationContext *LC = C.getLocationContext(); 2568 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager(); 2569 2570 for ( ; I != E; ++I) { 2571 const VarRegion *VR = *I; 2572 if (VR->getSuperRegion() == R) { 2573 VR = MemMgr.getVarRegion(VR->getDecl(), LC); 2574 } 2575 Regions.push_back(VR); 2576 } 2577 2578 state = 2579 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(), 2580 Regions.data() + Regions.size()).getState(); 2581 C.addTransition(state); 2582} 2583 2584void RetainCountChecker::checkPostStmt(const CastExpr *CE, 2585 CheckerContext &C) const { 2586 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE); 2587 if (!BE) 2588 return; 2589 2590 ArgEffect AE = IncRef; 2591 2592 switch (BE->getBridgeKind()) { 2593 case clang::OBC_Bridge: 2594 // Do nothing. 2595 return; 2596 case clang::OBC_BridgeRetained: 2597 AE = IncRef; 2598 break; 2599 case clang::OBC_BridgeTransfer: 2600 AE = DecRefBridgedTransfered; 2601 break; 2602 } 2603 2604 ProgramStateRef state = C.getState(); 2605 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol(); 2606 if (!Sym) 2607 return; 2608 const RefVal* T = state->get<RefBindings>(Sym); 2609 if (!T) 2610 return; 2611 2612 RefVal::Kind hasErr = (RefVal::Kind) 0; 2613 state = updateSymbol(state, Sym, *T, AE, hasErr, C); 2614 2615 if (hasErr) { 2616 // FIXME: If we get an error during a bridge cast, should we report it? 2617 // Should we assert that there is no error? 2618 return; 2619 } 2620 2621 C.addTransition(state); 2622} 2623 2624void RetainCountChecker::checkPostStmt(const CallExpr *CE, 2625 CheckerContext &C) const { 2626 // Get the callee. 2627 ProgramStateRef state = C.getState(); 2628 const Expr *Callee = CE->getCallee(); 2629 SVal L = state->getSVal(Callee, C.getLocationContext()); 2630 2631 RetainSummaryManager &Summaries = getSummaryManager(C); 2632 const RetainSummary *Summ = 0; 2633 2634 // FIXME: Better support for blocks. For now we stop tracking anything 2635 // that is passed to blocks. 2636 // FIXME: Need to handle variables that are "captured" by the block. 2637 if (dyn_cast_or_null<BlockDataRegion>(L.getAsRegion())) { 2638 Summ = Summaries.getPersistentStopSummary(); 2639 } else if (const FunctionDecl *FD = L.getAsFunctionDecl()) { 2640 Summ = Summaries.getSummary(FD); 2641 } else if (const CXXMemberCallExpr *me = dyn_cast<CXXMemberCallExpr>(CE)) { 2642 if (const CXXMethodDecl *MD = me->getMethodDecl()) 2643 Summ = Summaries.getSummary(MD); 2644 } 2645 2646 if (!Summ) 2647 Summ = Summaries.getDefaultSummary(); 2648 2649 checkSummary(*Summ, CallOrObjCMessage(CE, state, C.getLocationContext()), C); 2650} 2651 2652void RetainCountChecker::checkPostStmt(const CXXConstructExpr *CE, 2653 CheckerContext &C) const { 2654 const CXXConstructorDecl *Ctor = CE->getConstructor(); 2655 if (!Ctor) 2656 return; 2657 2658 RetainSummaryManager &Summaries = getSummaryManager(C); 2659 const RetainSummary *Summ = Summaries.getSummary(Ctor); 2660 2661 // If we didn't get a summary, this constructor doesn't affect retain counts. 2662 if (!Summ) 2663 return; 2664 2665 ProgramStateRef state = C.getState(); 2666 checkSummary(*Summ, CallOrObjCMessage(CE, state, C.getLocationContext()), C); 2667} 2668 2669void RetainCountChecker::processObjCLiterals(CheckerContext &C, 2670 const Expr *Ex) const { 2671 ProgramStateRef state = C.getState(); 2672 const ExplodedNode *pred = C.getPredecessor(); 2673 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ; 2674 it != et ; ++it) { 2675 const Stmt *child = *it; 2676 SVal V = state->getSVal(child, pred->getLocationContext()); 2677 if (SymbolRef sym = V.getAsSymbol()) 2678 if (const RefVal* T = state->get<RefBindings>(sym)) { 2679 RefVal::Kind hasErr = (RefVal::Kind) 0; 2680 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C); 2681 if (hasErr) { 2682 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C); 2683 return; 2684 } 2685 } 2686 } 2687 2688 // Return the object as autoreleased. 2689 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC); 2690 if (SymbolRef sym = 2691 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) { 2692 QualType ResultTy = Ex->getType(); 2693 state = state->set<RefBindings>(sym, RefVal::makeNotOwned(RetEffect::ObjC, 2694 ResultTy)); 2695 } 2696 2697 C.addTransition(state); 2698} 2699 2700void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL, 2701 CheckerContext &C) const { 2702 // Apply the 'MayEscape' to all values. 2703 processObjCLiterals(C, AL); 2704} 2705 2706void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL, 2707 CheckerContext &C) const { 2708 // Apply the 'MayEscape' to all keys and values. 2709 processObjCLiterals(C, DL); 2710} 2711 2712void RetainCountChecker::checkPostObjCMessage(const ObjCMessage &Msg, 2713 CheckerContext &C) const { 2714 ProgramStateRef state = C.getState(); 2715 2716 RetainSummaryManager &Summaries = getSummaryManager(C); 2717 2718 const RetainSummary *Summ; 2719 if (Msg.isInstanceMessage()) { 2720 const LocationContext *LC = C.getLocationContext(); 2721 Summ = Summaries.getInstanceMethodSummary(Msg, state, LC); 2722 } else { 2723 Summ = Summaries.getClassMethodSummary(Msg); 2724 } 2725 2726 // If we didn't get a summary, this message doesn't affect retain counts. 2727 if (!Summ) 2728 return; 2729 2730 checkSummary(*Summ, CallOrObjCMessage(Msg, state, C.getLocationContext()), C); 2731} 2732 2733/// GetReturnType - Used to get the return type of a message expression or 2734/// function call with the intention of affixing that type to a tracked symbol. 2735/// While the the return type can be queried directly from RetEx, when 2736/// invoking class methods we augment to the return type to be that of 2737/// a pointer to the class (as opposed it just being id). 2738// FIXME: We may be able to do this with related result types instead. 2739// This function is probably overestimating. 2740static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) { 2741 QualType RetTy = RetE->getType(); 2742 // If RetE is not a message expression just return its type. 2743 // If RetE is a message expression, return its types if it is something 2744 /// more specific than id. 2745 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE)) 2746 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>()) 2747 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() || 2748 PT->isObjCClassType()) { 2749 // At this point we know the return type of the message expression is 2750 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this 2751 // is a call to a class method whose type we can resolve. In such 2752 // cases, promote the return type to XXX* (where XXX is the class). 2753 const ObjCInterfaceDecl *D = ME->getReceiverInterface(); 2754 return !D ? RetTy : 2755 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D)); 2756 } 2757 2758 return RetTy; 2759} 2760 2761void RetainCountChecker::checkSummary(const RetainSummary &Summ, 2762 const CallOrObjCMessage &CallOrMsg, 2763 CheckerContext &C) const { 2764 ProgramStateRef state = C.getState(); 2765 2766 // Evaluate the effect of the arguments. 2767 RefVal::Kind hasErr = (RefVal::Kind) 0; 2768 SourceRange ErrorRange; 2769 SymbolRef ErrorSym = 0; 2770 2771 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) { 2772 SVal V = CallOrMsg.getArgSVal(idx); 2773 2774 if (SymbolRef Sym = V.getAsLocSymbol()) { 2775 if (RefBindings::data_type *T = state->get<RefBindings>(Sym)) { 2776 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C); 2777 if (hasErr) { 2778 ErrorRange = CallOrMsg.getArgSourceRange(idx); 2779 ErrorSym = Sym; 2780 break; 2781 } 2782 } 2783 } 2784 } 2785 2786 // Evaluate the effect on the message receiver. 2787 bool ReceiverIsTracked = false; 2788 if (!hasErr && CallOrMsg.isObjCMessage()) { 2789 const LocationContext *LC = C.getLocationContext(); 2790 SVal Receiver = CallOrMsg.getInstanceMessageReceiver(LC); 2791 if (SymbolRef Sym = Receiver.getAsLocSymbol()) { 2792 if (const RefVal *T = state->get<RefBindings>(Sym)) { 2793 ReceiverIsTracked = true; 2794 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(), 2795 hasErr, C); 2796 if (hasErr) { 2797 ErrorRange = CallOrMsg.getReceiverSourceRange(); 2798 ErrorSym = Sym; 2799 } 2800 } 2801 } 2802 } 2803 2804 // Process any errors. 2805 if (hasErr) { 2806 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C); 2807 return; 2808 } 2809 2810 // Consult the summary for the return value. 2811 RetEffect RE = Summ.getRetEffect(); 2812 2813 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) { 2814 if (ReceiverIsTracked) 2815 RE = getSummaryManager(C).getObjAllocRetEffect(); 2816 else 2817 RE = RetEffect::MakeNoRet(); 2818 } 2819 2820 switch (RE.getKind()) { 2821 default: 2822 llvm_unreachable("Unhandled RetEffect."); 2823 2824 case RetEffect::NoRet: 2825 // No work necessary. 2826 break; 2827 2828 case RetEffect::OwnedAllocatedSymbol: 2829 case RetEffect::OwnedSymbol: { 2830 SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(), 2831 C.getLocationContext()).getAsSymbol(); 2832 if (!Sym) 2833 break; 2834 2835 // Use the result type from callOrMsg as it automatically adjusts 2836 // for methods/functions that return references. 2837 QualType ResultTy = CallOrMsg.getResultType(C.getASTContext()); 2838 state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(), 2839 ResultTy)); 2840 2841 // FIXME: Add a flag to the checker where allocations are assumed to 2842 // *not* fail. (The code below is out-of-date, though.) 2843#if 0 2844 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) { 2845 bool isFeasible; 2846 state = state.assume(loc::SymbolVal(Sym), true, isFeasible); 2847 assert(isFeasible && "Cannot assume fresh symbol is non-null."); 2848 } 2849#endif 2850 2851 break; 2852 } 2853 2854 case RetEffect::GCNotOwnedSymbol: 2855 case RetEffect::ARCNotOwnedSymbol: 2856 case RetEffect::NotOwnedSymbol: { 2857 const Expr *Ex = CallOrMsg.getOriginExpr(); 2858 SymbolRef Sym = state->getSVal(Ex, C.getLocationContext()).getAsSymbol(); 2859 if (!Sym) 2860 break; 2861 2862 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *. 2863 QualType ResultTy = GetReturnType(Ex, C.getASTContext()); 2864 state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(), 2865 ResultTy)); 2866 break; 2867 } 2868 } 2869 2870 // This check is actually necessary; otherwise the statement builder thinks 2871 // we've hit a previously-found path. 2872 // Normally addTransition takes care of this, but we want the node pointer. 2873 ExplodedNode *NewNode; 2874 if (state == C.getState()) { 2875 NewNode = C.getPredecessor(); 2876 } else { 2877 NewNode = C.addTransition(state); 2878 } 2879 2880 // Annotate the node with summary we used. 2881 if (NewNode) { 2882 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary. 2883 if (ShouldResetSummaryLog) { 2884 SummaryLog.clear(); 2885 ShouldResetSummaryLog = false; 2886 } 2887 SummaryLog[NewNode] = &Summ; 2888 } 2889} 2890 2891 2892ProgramStateRef 2893RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym, 2894 RefVal V, ArgEffect E, RefVal::Kind &hasErr, 2895 CheckerContext &C) const { 2896 // In GC mode [... release] and [... retain] do nothing. 2897 // In ARC mode they shouldn't exist at all, but we just ignore them. 2898 bool IgnoreRetainMsg = C.isObjCGCEnabled(); 2899 if (!IgnoreRetainMsg) 2900 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount; 2901 2902 switch (E) { 2903 default: break; 2904 case IncRefMsg: E = IgnoreRetainMsg ? DoNothing : IncRef; break; 2905 case DecRefMsg: E = IgnoreRetainMsg ? DoNothing : DecRef; break; 2906 case MakeCollectable: E = C.isObjCGCEnabled() ? DecRef : DoNothing; break; 2907 case NewAutoreleasePool: E = C.isObjCGCEnabled() ? DoNothing : 2908 NewAutoreleasePool; break; 2909 } 2910 2911 // Handle all use-after-releases. 2912 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) { 2913 V = V ^ RefVal::ErrorUseAfterRelease; 2914 hasErr = V.getKind(); 2915 return state->set<RefBindings>(sym, V); 2916 } 2917 2918 switch (E) { 2919 case DecRefMsg: 2920 case IncRefMsg: 2921 case MakeCollectable: 2922 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted"); 2923 2924 case Dealloc: 2925 // Any use of -dealloc in GC is *bad*. 2926 if (C.isObjCGCEnabled()) { 2927 V = V ^ RefVal::ErrorDeallocGC; 2928 hasErr = V.getKind(); 2929 break; 2930 } 2931 2932 switch (V.getKind()) { 2933 default: 2934 llvm_unreachable("Invalid RefVal state for an explicit dealloc."); 2935 case RefVal::Owned: 2936 // The object immediately transitions to the released state. 2937 V = V ^ RefVal::Released; 2938 V.clearCounts(); 2939 return state->set<RefBindings>(sym, V); 2940 case RefVal::NotOwned: 2941 V = V ^ RefVal::ErrorDeallocNotOwned; 2942 hasErr = V.getKind(); 2943 break; 2944 } 2945 break; 2946 2947 case NewAutoreleasePool: 2948 assert(!C.isObjCGCEnabled()); 2949 return state->add<AutoreleaseStack>(sym); 2950 2951 case MayEscape: 2952 if (V.getKind() == RefVal::Owned) { 2953 V = V ^ RefVal::NotOwned; 2954 break; 2955 } 2956 2957 // Fall-through. 2958 2959 case DoNothing: 2960 return state; 2961 2962 case Autorelease: 2963 if (C.isObjCGCEnabled()) 2964 return state; 2965 2966 // Update the autorelease counts. 2967 state = SendAutorelease(state, ARCountFactory, sym); 2968 V = V.autorelease(); 2969 break; 2970 2971 case StopTracking: 2972 return state->remove<RefBindings>(sym); 2973 2974 case IncRef: 2975 switch (V.getKind()) { 2976 default: 2977 llvm_unreachable("Invalid RefVal state for a retain."); 2978 case RefVal::Owned: 2979 case RefVal::NotOwned: 2980 V = V + 1; 2981 break; 2982 case RefVal::Released: 2983 // Non-GC cases are handled above. 2984 assert(C.isObjCGCEnabled()); 2985 V = (V ^ RefVal::Owned) + 1; 2986 break; 2987 } 2988 break; 2989 2990 case SelfOwn: 2991 V = V ^ RefVal::NotOwned; 2992 // Fall-through. 2993 case DecRef: 2994 case DecRefBridgedTransfered: 2995 switch (V.getKind()) { 2996 default: 2997 // case 'RefVal::Released' handled above. 2998 llvm_unreachable("Invalid RefVal state for a release."); 2999 3000 case RefVal::Owned: 3001 assert(V.getCount() > 0); 3002 if (V.getCount() == 1) 3003 V = V ^ (E == DecRefBridgedTransfered ? 3004 RefVal::NotOwned : RefVal::Released); 3005 V = V - 1; 3006 break; 3007 3008 case RefVal::NotOwned: 3009 if (V.getCount() > 0) 3010 V = V - 1; 3011 else { 3012 V = V ^ RefVal::ErrorReleaseNotOwned; 3013 hasErr = V.getKind(); 3014 } 3015 break; 3016 3017 case RefVal::Released: 3018 // Non-GC cases are handled above. 3019 assert(C.isObjCGCEnabled()); 3020 V = V ^ RefVal::ErrorUseAfterRelease; 3021 hasErr = V.getKind(); 3022 break; 3023 } 3024 break; 3025 } 3026 return state->set<RefBindings>(sym, V); 3027} 3028 3029void RetainCountChecker::processNonLeakError(ProgramStateRef St, 3030 SourceRange ErrorRange, 3031 RefVal::Kind ErrorKind, 3032 SymbolRef Sym, 3033 CheckerContext &C) const { 3034 ExplodedNode *N = C.generateSink(St); 3035 if (!N) 3036 return; 3037 3038 CFRefBug *BT; 3039 switch (ErrorKind) { 3040 default: 3041 llvm_unreachable("Unhandled error."); 3042 case RefVal::ErrorUseAfterRelease: 3043 if (!useAfterRelease) 3044 useAfterRelease.reset(new UseAfterRelease()); 3045 BT = &*useAfterRelease; 3046 break; 3047 case RefVal::ErrorReleaseNotOwned: 3048 if (!releaseNotOwned) 3049 releaseNotOwned.reset(new BadRelease()); 3050 BT = &*releaseNotOwned; 3051 break; 3052 case RefVal::ErrorDeallocGC: 3053 if (!deallocGC) 3054 deallocGC.reset(new DeallocGC()); 3055 BT = &*deallocGC; 3056 break; 3057 case RefVal::ErrorDeallocNotOwned: 3058 if (!deallocNotOwned) 3059 deallocNotOwned.reset(new DeallocNotOwned()); 3060 BT = &*deallocNotOwned; 3061 break; 3062 } 3063 3064 assert(BT); 3065 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(), 3066 C.isObjCGCEnabled(), SummaryLog, 3067 N, Sym); 3068 report->addRange(ErrorRange); 3069 C.EmitReport(report); 3070} 3071 3072//===----------------------------------------------------------------------===// 3073// Handle the return values of retain-count-related functions. 3074//===----------------------------------------------------------------------===// 3075 3076bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const { 3077 // Get the callee. We're only interested in simple C functions. 3078 ProgramStateRef state = C.getState(); 3079 const FunctionDecl *FD = C.getCalleeDecl(CE); 3080 if (!FD) 3081 return false; 3082 3083 IdentifierInfo *II = FD->getIdentifier(); 3084 if (!II) 3085 return false; 3086 3087 // For now, we're only handling the functions that return aliases of their 3088 // arguments: CFRetain and CFMakeCollectable (and their families). 3089 // Eventually we should add other functions we can model entirely, 3090 // such as CFRelease, which don't invalidate their arguments or globals. 3091 if (CE->getNumArgs() != 1) 3092 return false; 3093 3094 // Get the name of the function. 3095 StringRef FName = II->getName(); 3096 FName = FName.substr(FName.find_first_not_of('_')); 3097 3098 // See if it's one of the specific functions we know how to eval. 3099 bool canEval = false; 3100 3101 QualType ResultTy = CE->getCallReturnType(); 3102 if (ResultTy->isObjCIdType()) { 3103 // Handle: id NSMakeCollectable(CFTypeRef) 3104 canEval = II->isStr("NSMakeCollectable"); 3105 } else if (ResultTy->isPointerType()) { 3106 // Handle: (CF|CG)Retain 3107 // CFMakeCollectable 3108 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist). 3109 if (cocoa::isRefType(ResultTy, "CF", FName) || 3110 cocoa::isRefType(ResultTy, "CG", FName)) { 3111 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName); 3112 } 3113 } 3114 3115 if (!canEval) 3116 return false; 3117 3118 // Bind the return value. 3119 const LocationContext *LCtx = C.getLocationContext(); 3120 SVal RetVal = state->getSVal(CE->getArg(0), LCtx); 3121 if (RetVal.isUnknown()) { 3122 // If the receiver is unknown, conjure a return value. 3123 SValBuilder &SVB = C.getSValBuilder(); 3124 unsigned Count = C.getCurrentBlockCount(); 3125 SVal RetVal = SVB.getConjuredSymbolVal(0, CE, LCtx, ResultTy, Count); 3126 } 3127 state = state->BindExpr(CE, LCtx, RetVal, false); 3128 3129 // FIXME: This should not be necessary, but otherwise the argument seems to be 3130 // considered alive during the next statement. 3131 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) { 3132 // Save the refcount status of the argument. 3133 SymbolRef Sym = RetVal.getAsLocSymbol(); 3134 RefBindings::data_type *Binding = 0; 3135 if (Sym) 3136 Binding = state->get<RefBindings>(Sym); 3137 3138 // Invalidate the argument region. 3139 unsigned Count = C.getCurrentBlockCount(); 3140 state = state->invalidateRegions(ArgRegion, CE, Count, LCtx); 3141 3142 // Restore the refcount status of the argument. 3143 if (Binding) 3144 state = state->set<RefBindings>(Sym, *Binding); 3145 } 3146 3147 C.addTransition(state); 3148 return true; 3149} 3150 3151//===----------------------------------------------------------------------===// 3152// Handle return statements. 3153//===----------------------------------------------------------------------===// 3154 3155// Return true if the current LocationContext has no caller context. 3156static bool inTopFrame(CheckerContext &C) { 3157 const LocationContext *LC = C.getLocationContext(); 3158 return LC->getParent() == 0; 3159} 3160 3161void RetainCountChecker::checkPreStmt(const ReturnStmt *S, 3162 CheckerContext &C) const { 3163 3164 // Only adjust the reference count if this is the top-level call frame, 3165 // and not the result of inlining. In the future, we should do 3166 // better checking even for inlined calls, and see if they match 3167 // with their expected semantics (e.g., the method should return a retained 3168 // object, etc.). 3169 if (!inTopFrame(C)) 3170 return; 3171 3172 const Expr *RetE = S->getRetValue(); 3173 if (!RetE) 3174 return; 3175 3176 ProgramStateRef state = C.getState(); 3177 SymbolRef Sym = 3178 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol(); 3179 if (!Sym) 3180 return; 3181 3182 // Get the reference count binding (if any). 3183 const RefVal *T = state->get<RefBindings>(Sym); 3184 if (!T) 3185 return; 3186 3187 // Change the reference count. 3188 RefVal X = *T; 3189 3190 switch (X.getKind()) { 3191 case RefVal::Owned: { 3192 unsigned cnt = X.getCount(); 3193 assert(cnt > 0); 3194 X.setCount(cnt - 1); 3195 X = X ^ RefVal::ReturnedOwned; 3196 break; 3197 } 3198 3199 case RefVal::NotOwned: { 3200 unsigned cnt = X.getCount(); 3201 if (cnt) { 3202 X.setCount(cnt - 1); 3203 X = X ^ RefVal::ReturnedOwned; 3204 } 3205 else { 3206 X = X ^ RefVal::ReturnedNotOwned; 3207 } 3208 break; 3209 } 3210 3211 default: 3212 return; 3213 } 3214 3215 // Update the binding. 3216 state = state->set<RefBindings>(Sym, X); 3217 ExplodedNode *Pred = C.addTransition(state); 3218 3219 // At this point we have updated the state properly. 3220 // Everything after this is merely checking to see if the return value has 3221 // been over- or under-retained. 3222 3223 // Did we cache out? 3224 if (!Pred) 3225 return; 3226 3227 // Update the autorelease counts. 3228 static SimpleProgramPointTag 3229 AutoreleaseTag("RetainCountChecker : Autorelease"); 3230 GenericNodeBuilderRefCount Bd(C, &AutoreleaseTag); 3231 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C, Sym, X); 3232 3233 // Did we cache out? 3234 if (!Pred) 3235 return; 3236 3237 // Get the updated binding. 3238 T = state->get<RefBindings>(Sym); 3239 assert(T); 3240 X = *T; 3241 3242 // Consult the summary of the enclosing method. 3243 RetainSummaryManager &Summaries = getSummaryManager(C); 3244 const Decl *CD = &Pred->getCodeDecl(); 3245 3246 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) { 3247 // Unlike regular functions, /all/ ObjC methods are assumed to always 3248 // follow Cocoa retain-count conventions, not just those with special 3249 // names or attributes. 3250 const RetainSummary *Summ = Summaries.getMethodSummary(MD); 3251 RetEffect RE = Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet(); 3252 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state); 3253 } 3254 3255 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) { 3256 if (!isa<CXXMethodDecl>(FD)) 3257 if (const RetainSummary *Summ = Summaries.getSummary(FD)) 3258 checkReturnWithRetEffect(S, C, Pred, Summ->getRetEffect(), X, 3259 Sym, state); 3260 } 3261} 3262 3263void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S, 3264 CheckerContext &C, 3265 ExplodedNode *Pred, 3266 RetEffect RE, RefVal X, 3267 SymbolRef Sym, 3268 ProgramStateRef state) const { 3269 // Any leaks or other errors? 3270 if (X.isReturnedOwned() && X.getCount() == 0) { 3271 if (RE.getKind() != RetEffect::NoRet) { 3272 bool hasError = false; 3273 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) { 3274 // Things are more complicated with garbage collection. If the 3275 // returned object is suppose to be an Objective-C object, we have 3276 // a leak (as the caller expects a GC'ed object) because no 3277 // method should return ownership unless it returns a CF object. 3278 hasError = true; 3279 X = X ^ RefVal::ErrorGCLeakReturned; 3280 } 3281 else if (!RE.isOwned()) { 3282 // Either we are using GC and the returned object is a CF type 3283 // or we aren't using GC. In either case, we expect that the 3284 // enclosing method is expected to return ownership. 3285 hasError = true; 3286 X = X ^ RefVal::ErrorLeakReturned; 3287 } 3288 3289 if (hasError) { 3290 // Generate an error node. 3291 state = state->set<RefBindings>(Sym, X); 3292 3293 static SimpleProgramPointTag 3294 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak"); 3295 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag); 3296 if (N) { 3297 const LangOptions &LOpts = C.getASTContext().getLangOpts(); 3298 bool GCEnabled = C.isObjCGCEnabled(); 3299 CFRefReport *report = 3300 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled), 3301 LOpts, GCEnabled, SummaryLog, 3302 N, Sym, C); 3303 C.EmitReport(report); 3304 } 3305 } 3306 } 3307 } else if (X.isReturnedNotOwned()) { 3308 if (RE.isOwned()) { 3309 // Trying to return a not owned object to a caller expecting an 3310 // owned object. 3311 state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned); 3312 3313 static SimpleProgramPointTag 3314 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned"); 3315 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag); 3316 if (N) { 3317 if (!returnNotOwnedForOwned) 3318 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned()); 3319 3320 CFRefReport *report = 3321 new CFRefReport(*returnNotOwnedForOwned, 3322 C.getASTContext().getLangOpts(), 3323 C.isObjCGCEnabled(), SummaryLog, N, Sym); 3324 C.EmitReport(report); 3325 } 3326 } 3327 } 3328} 3329 3330//===----------------------------------------------------------------------===// 3331// Check various ways a symbol can be invalidated. 3332//===----------------------------------------------------------------------===// 3333 3334void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S, 3335 CheckerContext &C) const { 3336 // Are we storing to something that causes the value to "escape"? 3337 bool escapes = true; 3338 3339 // A value escapes in three possible cases (this may change): 3340 // 3341 // (1) we are binding to something that is not a memory region. 3342 // (2) we are binding to a memregion that does not have stack storage 3343 // (3) we are binding to a memregion with stack storage that the store 3344 // does not understand. 3345 ProgramStateRef state = C.getState(); 3346 3347 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) { 3348 escapes = !regionLoc->getRegion()->hasStackStorage(); 3349 3350 if (!escapes) { 3351 // To test (3), generate a new state with the binding added. If it is 3352 // the same state, then it escapes (since the store cannot represent 3353 // the binding). 3354 escapes = (state == (state->bindLoc(*regionLoc, val))); 3355 } 3356 } 3357 3358 // If our store can represent the binding and we aren't storing to something 3359 // that doesn't have local storage then just return and have the simulation 3360 // state continue as is. 3361 if (!escapes) 3362 return; 3363 3364 // Otherwise, find all symbols referenced by 'val' that we are tracking 3365 // and stop tracking them. 3366 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState(); 3367 C.addTransition(state); 3368} 3369 3370ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state, 3371 SVal Cond, 3372 bool Assumption) const { 3373 3374 // FIXME: We may add to the interface of evalAssume the list of symbols 3375 // whose assumptions have changed. For now we just iterate through the 3376 // bindings and check if any of the tracked symbols are NULL. This isn't 3377 // too bad since the number of symbols we will track in practice are 3378 // probably small and evalAssume is only called at branches and a few 3379 // other places. 3380 RefBindings B = state->get<RefBindings>(); 3381 3382 if (B.isEmpty()) 3383 return state; 3384 3385 bool changed = false; 3386 RefBindings::Factory &RefBFactory = state->get_context<RefBindings>(); 3387 3388 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) { 3389 // Check if the symbol is null (or equal to any constant). 3390 // If this is the case, stop tracking the symbol. 3391 if (state->getSymVal(I.getKey())) { 3392 changed = true; 3393 B = RefBFactory.remove(B, I.getKey()); 3394 } 3395 } 3396 3397 if (changed) 3398 state = state->set<RefBindings>(B); 3399 3400 return state; 3401} 3402 3403ProgramStateRef 3404RetainCountChecker::checkRegionChanges(ProgramStateRef state, 3405 const StoreManager::InvalidatedSymbols *invalidated, 3406 ArrayRef<const MemRegion *> ExplicitRegions, 3407 ArrayRef<const MemRegion *> Regions, 3408 const CallOrObjCMessage *Call) const { 3409 if (!invalidated) 3410 return state; 3411 3412 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols; 3413 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(), 3414 E = ExplicitRegions.end(); I != E; ++I) { 3415 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>()) 3416 WhitelistedSymbols.insert(SR->getSymbol()); 3417 } 3418 3419 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(), 3420 E = invalidated->end(); I!=E; ++I) { 3421 SymbolRef sym = *I; 3422 if (WhitelistedSymbols.count(sym)) 3423 continue; 3424 // Remove any existing reference-count binding. 3425 state = state->remove<RefBindings>(sym); 3426 } 3427 return state; 3428} 3429 3430//===----------------------------------------------------------------------===// 3431// Handle dead symbols and end-of-path. 3432//===----------------------------------------------------------------------===// 3433 3434std::pair<ExplodedNode *, ProgramStateRef > 3435RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state, 3436 GenericNodeBuilderRefCount Bd, 3437 ExplodedNode *Pred, 3438 CheckerContext &Ctx, 3439 SymbolRef Sym, RefVal V) const { 3440 unsigned ACnt = V.getAutoreleaseCount(); 3441 3442 // No autorelease counts? Nothing to be done. 3443 if (!ACnt) 3444 return std::make_pair(Pred, state); 3445 3446 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?"); 3447 unsigned Cnt = V.getCount(); 3448 3449 // FIXME: Handle sending 'autorelease' to already released object. 3450 3451 if (V.getKind() == RefVal::ReturnedOwned) 3452 ++Cnt; 3453 3454 if (ACnt <= Cnt) { 3455 if (ACnt == Cnt) { 3456 V.clearCounts(); 3457 if (V.getKind() == RefVal::ReturnedOwned) 3458 V = V ^ RefVal::ReturnedNotOwned; 3459 else 3460 V = V ^ RefVal::NotOwned; 3461 } else { 3462 V.setCount(Cnt - ACnt); 3463 V.setAutoreleaseCount(0); 3464 } 3465 state = state->set<RefBindings>(Sym, V); 3466 ExplodedNode *N = Bd.MakeNode(state, Pred); 3467 if (N == 0) 3468 state = 0; 3469 return std::make_pair(N, state); 3470 } 3471 3472 // Woah! More autorelease counts then retain counts left. 3473 // Emit hard error. 3474 V = V ^ RefVal::ErrorOverAutorelease; 3475 state = state->set<RefBindings>(Sym, V); 3476 3477 if (ExplodedNode *N = Bd.MakeNode(state, Pred, true)) { 3478 SmallString<128> sbuf; 3479 llvm::raw_svector_ostream os(sbuf); 3480 os << "Object over-autoreleased: object was sent -autorelease "; 3481 if (V.getAutoreleaseCount() > 1) 3482 os << V.getAutoreleaseCount() << " times "; 3483 os << "but the object has a +" << V.getCount() << " retain count"; 3484 3485 if (!overAutorelease) 3486 overAutorelease.reset(new OverAutorelease()); 3487 3488 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts(); 3489 CFRefReport *report = 3490 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false, 3491 SummaryLog, N, Sym, os.str()); 3492 Ctx.EmitReport(report); 3493 } 3494 3495 return std::make_pair((ExplodedNode *)0, (ProgramStateRef )0); 3496} 3497 3498ProgramStateRef 3499RetainCountChecker::handleSymbolDeath(ProgramStateRef state, 3500 SymbolRef sid, RefVal V, 3501 SmallVectorImpl<SymbolRef> &Leaked) const { 3502 bool hasLeak = false; 3503 if (V.isOwned()) 3504 hasLeak = true; 3505 else if (V.isNotOwned() || V.isReturnedOwned()) 3506 hasLeak = (V.getCount() > 0); 3507 3508 if (!hasLeak) 3509 return state->remove<RefBindings>(sid); 3510 3511 Leaked.push_back(sid); 3512 return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak); 3513} 3514 3515ExplodedNode * 3516RetainCountChecker::processLeaks(ProgramStateRef state, 3517 SmallVectorImpl<SymbolRef> &Leaked, 3518 GenericNodeBuilderRefCount &Builder, 3519 CheckerContext &Ctx, 3520 ExplodedNode *Pred) const { 3521 if (Leaked.empty()) 3522 return Pred; 3523 3524 // Generate an intermediate node representing the leak point. 3525 ExplodedNode *N = Builder.MakeNode(state, Pred); 3526 3527 if (N) { 3528 for (SmallVectorImpl<SymbolRef>::iterator 3529 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) { 3530 3531 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts(); 3532 bool GCEnabled = Ctx.isObjCGCEnabled(); 3533 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled) 3534 : getLeakAtReturnBug(LOpts, GCEnabled); 3535 assert(BT && "BugType not initialized."); 3536 3537 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled, 3538 SummaryLog, N, *I, Ctx); 3539 Ctx.EmitReport(report); 3540 } 3541 } 3542 3543 return N; 3544} 3545 3546void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const { 3547 ProgramStateRef state = Ctx.getState(); 3548 GenericNodeBuilderRefCount Bd(Ctx); 3549 RefBindings B = state->get<RefBindings>(); 3550 ExplodedNode *Pred = Ctx.getPredecessor(); 3551 3552 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) { 3553 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, Ctx, 3554 I->first, I->second); 3555 if (!state) 3556 return; 3557 } 3558 3559 // If the current LocationContext has a parent, don't check for leaks. 3560 // We will do that later. 3561 // FIXME: we should instead check for imblances of the retain/releases, 3562 // and suggest annotations. 3563 if (Ctx.getLocationContext()->getParent()) 3564 return; 3565 3566 B = state->get<RefBindings>(); 3567 SmallVector<SymbolRef, 10> Leaked; 3568 3569 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) 3570 state = handleSymbolDeath(state, I->first, I->second, Leaked); 3571 3572 processLeaks(state, Leaked, Bd, Ctx, Pred); 3573} 3574 3575const ProgramPointTag * 3576RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const { 3577 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym]; 3578 if (!tag) { 3579 SmallString<64> buf; 3580 llvm::raw_svector_ostream out(buf); 3581 out << "RetainCountChecker : Dead Symbol : "; 3582 sym->dumpToStream(out); 3583 tag = new SimpleProgramPointTag(out.str()); 3584 } 3585 return tag; 3586} 3587 3588void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper, 3589 CheckerContext &C) const { 3590 ExplodedNode *Pred = C.getPredecessor(); 3591 3592 ProgramStateRef state = C.getState(); 3593 RefBindings B = state->get<RefBindings>(); 3594 3595 // Update counts from autorelease pools 3596 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(), 3597 E = SymReaper.dead_end(); I != E; ++I) { 3598 SymbolRef Sym = *I; 3599 if (const RefVal *T = B.lookup(Sym)){ 3600 // Use the symbol as the tag. 3601 // FIXME: This might not be as unique as we would like. 3602 GenericNodeBuilderRefCount Bd(C, getDeadSymbolTag(Sym)); 3603 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C, 3604 Sym, *T); 3605 if (!state) 3606 return; 3607 } 3608 } 3609 3610 B = state->get<RefBindings>(); 3611 SmallVector<SymbolRef, 10> Leaked; 3612 3613 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(), 3614 E = SymReaper.dead_end(); I != E; ++I) { 3615 if (const RefVal *T = B.lookup(*I)) 3616 state = handleSymbolDeath(state, *I, *T, Leaked); 3617 } 3618 3619 { 3620 GenericNodeBuilderRefCount Bd(C, this); 3621 Pred = processLeaks(state, Leaked, Bd, C, Pred); 3622 } 3623 3624 // Did we cache out? 3625 if (!Pred) 3626 return; 3627 3628 // Now generate a new node that nukes the old bindings. 3629 RefBindings::Factory &F = state->get_context<RefBindings>(); 3630 3631 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(), 3632 E = SymReaper.dead_end(); I != E; ++I) 3633 B = F.remove(B, *I); 3634 3635 state = state->set<RefBindings>(B); 3636 C.addTransition(state, Pred); 3637} 3638 3639//===----------------------------------------------------------------------===// 3640// Debug printing of refcount bindings and autorelease pools. 3641//===----------------------------------------------------------------------===// 3642 3643static void PrintPool(raw_ostream &Out, SymbolRef Sym, 3644 ProgramStateRef State) { 3645 Out << ' '; 3646 if (Sym) 3647 Sym->dumpToStream(Out); 3648 else 3649 Out << "<pool>"; 3650 Out << ":{"; 3651 3652 // Get the contents of the pool. 3653 if (const ARCounts *Cnts = State->get<AutoreleasePoolContents>(Sym)) 3654 for (ARCounts::iterator I = Cnts->begin(), E = Cnts->end(); I != E; ++I) 3655 Out << '(' << I.getKey() << ',' << I.getData() << ')'; 3656 3657 Out << '}'; 3658} 3659 3660static bool UsesAutorelease(ProgramStateRef state) { 3661 // A state uses autorelease if it allocated an autorelease pool or if it has 3662 // objects in the caller's autorelease pool. 3663 return !state->get<AutoreleaseStack>().isEmpty() || 3664 state->get<AutoreleasePoolContents>(SymbolRef()); 3665} 3666 3667void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State, 3668 const char *NL, const char *Sep) const { 3669 3670 RefBindings B = State->get<RefBindings>(); 3671 3672 if (!B.isEmpty()) 3673 Out << Sep << NL; 3674 3675 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) { 3676 Out << I->first << " : "; 3677 I->second.print(Out); 3678 Out << NL; 3679 } 3680 3681 // Print the autorelease stack. 3682 if (UsesAutorelease(State)) { 3683 Out << Sep << NL << "AR pool stack:"; 3684 ARStack Stack = State->get<AutoreleaseStack>(); 3685 3686 PrintPool(Out, SymbolRef(), State); // Print the caller's pool. 3687 for (ARStack::iterator I = Stack.begin(), E = Stack.end(); I != E; ++I) 3688 PrintPool(Out, *I, State); 3689 3690 Out << NL; 3691 } 3692} 3693 3694//===----------------------------------------------------------------------===// 3695// Checker registration. 3696//===----------------------------------------------------------------------===// 3697 3698void ento::registerRetainCountChecker(CheckerManager &Mgr) { 3699 Mgr.registerChecker<RetainCountChecker>(); 3700} 3701 3702