RetainCountChecker.cpp revision 514f2c9dcb9e04b52929c5b141a6fe88bd68b33f
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 } else if (FName == "dispatch_set_context") { 989 // <rdar://problem/11059275> - The analyzer currently doesn't have 990 // a good way to reason about the finalizer function for libdispatch. 991 // If we pass a context object that is memory managed, stop tracking it. 992 // FIXME: this hack should possibly go away once we can handle 993 // libdispatch finalizers. 994 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking); 995 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); 996 } 997 998 // Did we get a summary? 999 if (S) 1000 break; 1001 1002 // Enable this code once the semantics of NSDeallocateObject are resolved 1003 // for GC. <rdar://problem/6619988> 1004#if 0 1005 // Handle: NSDeallocateObject(id anObject); 1006 // This method does allow 'nil' (although we don't check it now). 1007 if (strcmp(FName, "NSDeallocateObject") == 0) { 1008 return RetTy == Ctx.VoidTy 1009 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc) 1010 : getPersistentStopSummary(); 1011 } 1012#endif 1013 1014 if (RetTy->isPointerType()) { 1015 // For CoreFoundation ('CF') types. 1016 if (cocoa::isRefType(RetTy, "CF", FName)) { 1017 if (isRetain(FD, FName)) 1018 S = getUnarySummary(FT, cfretain); 1019 else if (isMakeCollectable(FD, FName)) 1020 S = getUnarySummary(FT, cfmakecollectable); 1021 else 1022 S = getCFCreateGetRuleSummary(FD); 1023 1024 break; 1025 } 1026 1027 // For CoreGraphics ('CG') types. 1028 if (cocoa::isRefType(RetTy, "CG", FName)) { 1029 if (isRetain(FD, FName)) 1030 S = getUnarySummary(FT, cfretain); 1031 else 1032 S = getCFCreateGetRuleSummary(FD); 1033 1034 break; 1035 } 1036 1037 // For the Disk Arbitration API (DiskArbitration/DADisk.h) 1038 if (cocoa::isRefType(RetTy, "DADisk") || 1039 cocoa::isRefType(RetTy, "DADissenter") || 1040 cocoa::isRefType(RetTy, "DASessionRef")) { 1041 S = getCFCreateGetRuleSummary(FD); 1042 break; 1043 } 1044 1045 break; 1046 } 1047 1048 // Check for release functions, the only kind of functions that we care 1049 // about that don't return a pointer type. 1050 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) { 1051 // Test for 'CGCF'. 1052 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2); 1053 1054 if (isRelease(FD, FName)) 1055 S = getUnarySummary(FT, cfrelease); 1056 else { 1057 assert (ScratchArgs.isEmpty()); 1058 // Remaining CoreFoundation and CoreGraphics functions. 1059 // We use to assume that they all strictly followed the ownership idiom 1060 // and that ownership cannot be transferred. While this is technically 1061 // correct, many methods allow a tracked object to escape. For example: 1062 // 1063 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...); 1064 // CFDictionaryAddValue(y, key, x); 1065 // CFRelease(x); 1066 // ... it is okay to use 'x' since 'y' has a reference to it 1067 // 1068 // We handle this and similar cases with the follow heuristic. If the 1069 // function name contains "InsertValue", "SetValue", "AddValue", 1070 // "AppendValue", or "SetAttribute", then we assume that arguments may 1071 // "escape." This means that something else holds on to the object, 1072 // allowing it be used even after its local retain count drops to 0. 1073 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos|| 1074 StrInStrNoCase(FName, "AddValue") != StringRef::npos || 1075 StrInStrNoCase(FName, "SetValue") != StringRef::npos || 1076 StrInStrNoCase(FName, "AppendValue") != StringRef::npos|| 1077 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos) 1078 ? MayEscape : DoNothing; 1079 1080 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E); 1081 } 1082 } 1083 } 1084 while (0); 1085 1086 // Annotations override defaults. 1087 updateSummaryFromAnnotations(S, FD); 1088 1089 FuncSummaries[FD] = S; 1090 return S; 1091} 1092 1093const RetainSummary * 1094RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) { 1095 if (coreFoundation::followsCreateRule(FD)) 1096 return getCFSummaryCreateRule(FD); 1097 1098 return getCFSummaryGetRule(FD); 1099} 1100 1101const RetainSummary * 1102RetainSummaryManager::getUnarySummary(const FunctionType* FT, 1103 UnaryFuncKind func) { 1104 1105 // Sanity check that this is *really* a unary function. This can 1106 // happen if people do weird things. 1107 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT); 1108 if (!FTP || FTP->getNumArgs() != 1) 1109 return getPersistentStopSummary(); 1110 1111 assert (ScratchArgs.isEmpty()); 1112 1113 ArgEffect Effect; 1114 switch (func) { 1115 case cfretain: Effect = IncRef; break; 1116 case cfrelease: Effect = DecRef; break; 1117 case cfmakecollectable: Effect = MakeCollectable; break; 1118 } 1119 1120 ScratchArgs = AF.add(ScratchArgs, 0, Effect); 1121 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); 1122} 1123 1124const RetainSummary * 1125RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) { 1126 assert (ScratchArgs.isEmpty()); 1127 1128 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true)); 1129} 1130 1131const RetainSummary * 1132RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) { 1133 assert (ScratchArgs.isEmpty()); 1134 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF), 1135 DoNothing, DoNothing); 1136} 1137 1138//===----------------------------------------------------------------------===// 1139// Summary creation for Selectors. 1140//===----------------------------------------------------------------------===// 1141 1142void 1143RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ, 1144 const FunctionDecl *FD) { 1145 if (!FD) 1146 return; 1147 1148 RetainSummaryTemplate Template(Summ, *getDefaultSummary(), *this); 1149 1150 // Effects on the parameters. 1151 unsigned parm_idx = 0; 1152 for (FunctionDecl::param_const_iterator pi = FD->param_begin(), 1153 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) { 1154 const ParmVarDecl *pd = *pi; 1155 if (pd->getAttr<NSConsumedAttr>()) { 1156 if (!GCEnabled) { 1157 Template->addArg(AF, parm_idx, DecRef); 1158 } 1159 } else if (pd->getAttr<CFConsumedAttr>()) { 1160 Template->addArg(AF, parm_idx, DecRef); 1161 } 1162 } 1163 1164 QualType RetTy = FD->getResultType(); 1165 1166 // Determine if there is a special return effect for this method. 1167 if (cocoa::isCocoaObjectRef(RetTy)) { 1168 if (FD->getAttr<NSReturnsRetainedAttr>()) { 1169 Template->setRetEffect(ObjCAllocRetE); 1170 } 1171 else if (FD->getAttr<CFReturnsRetainedAttr>()) { 1172 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true)); 1173 } 1174 else if (FD->getAttr<NSReturnsNotRetainedAttr>()) { 1175 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC)); 1176 } 1177 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) { 1178 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF)); 1179 } 1180 } else if (RetTy->getAs<PointerType>()) { 1181 if (FD->getAttr<CFReturnsRetainedAttr>()) { 1182 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true)); 1183 } 1184 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) { 1185 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF)); 1186 } 1187 } 1188} 1189 1190void 1191RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ, 1192 const ObjCMethodDecl *MD) { 1193 if (!MD) 1194 return; 1195 1196 RetainSummaryTemplate Template(Summ, *getDefaultSummary(), *this); 1197 bool isTrackedLoc = false; 1198 1199 // Effects on the receiver. 1200 if (MD->getAttr<NSConsumesSelfAttr>()) { 1201 if (!GCEnabled) 1202 Template->setReceiverEffect(DecRefMsg); 1203 } 1204 1205 // Effects on the parameters. 1206 unsigned parm_idx = 0; 1207 for (ObjCMethodDecl::param_const_iterator 1208 pi=MD->param_begin(), pe=MD->param_end(); 1209 pi != pe; ++pi, ++parm_idx) { 1210 const ParmVarDecl *pd = *pi; 1211 if (pd->getAttr<NSConsumedAttr>()) { 1212 if (!GCEnabled) 1213 Template->addArg(AF, parm_idx, DecRef); 1214 } 1215 else if(pd->getAttr<CFConsumedAttr>()) { 1216 Template->addArg(AF, parm_idx, DecRef); 1217 } 1218 } 1219 1220 // Determine if there is a special return effect for this method. 1221 if (cocoa::isCocoaObjectRef(MD->getResultType())) { 1222 if (MD->getAttr<NSReturnsRetainedAttr>()) { 1223 Template->setRetEffect(ObjCAllocRetE); 1224 return; 1225 } 1226 if (MD->getAttr<NSReturnsNotRetainedAttr>()) { 1227 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC)); 1228 return; 1229 } 1230 1231 isTrackedLoc = true; 1232 } else { 1233 isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL; 1234 } 1235 1236 if (isTrackedLoc) { 1237 if (MD->getAttr<CFReturnsRetainedAttr>()) 1238 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true)); 1239 else if (MD->getAttr<CFReturnsNotRetainedAttr>()) 1240 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF)); 1241 } 1242} 1243 1244const RetainSummary * 1245RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD, 1246 Selector S, QualType RetTy) { 1247 1248 if (MD) { 1249 // Scan the method decl for 'void*' arguments. These should be treated 1250 // as 'StopTracking' because they are often used with delegates. 1251 // Delegates are a frequent form of false positives with the retain 1252 // count checker. 1253 unsigned i = 0; 1254 for (ObjCMethodDecl::param_const_iterator I = MD->param_begin(), 1255 E = MD->param_end(); I != E; ++I, ++i) 1256 if (const ParmVarDecl *PD = *I) { 1257 QualType Ty = Ctx.getCanonicalType(PD->getType()); 1258 if (Ty.getLocalUnqualifiedType() == Ctx.VoidPtrTy) 1259 ScratchArgs = AF.add(ScratchArgs, i, StopTracking); 1260 } 1261 } 1262 1263 // Any special effects? 1264 ArgEffect ReceiverEff = DoNothing; 1265 RetEffect ResultEff = RetEffect::MakeNoRet(); 1266 1267 // Check the method family, and apply any default annotations. 1268 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) { 1269 case OMF_None: 1270 case OMF_performSelector: 1271 // Assume all Objective-C methods follow Cocoa Memory Management rules. 1272 // FIXME: Does the non-threaded performSelector family really belong here? 1273 // The selector could be, say, @selector(copy). 1274 if (cocoa::isCocoaObjectRef(RetTy)) 1275 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC); 1276 else if (coreFoundation::isCFObjectRef(RetTy)) { 1277 // ObjCMethodDecl currently doesn't consider CF objects as valid return 1278 // values for alloc, new, copy, or mutableCopy, so we have to 1279 // double-check with the selector. This is ugly, but there aren't that 1280 // many Objective-C methods that return CF objects, right? 1281 if (MD) { 1282 switch (S.getMethodFamily()) { 1283 case OMF_alloc: 1284 case OMF_new: 1285 case OMF_copy: 1286 case OMF_mutableCopy: 1287 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true); 1288 break; 1289 default: 1290 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF); 1291 break; 1292 } 1293 } else { 1294 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF); 1295 } 1296 } 1297 break; 1298 case OMF_init: 1299 ResultEff = ObjCInitRetE; 1300 ReceiverEff = DecRefMsg; 1301 break; 1302 case OMF_alloc: 1303 case OMF_new: 1304 case OMF_copy: 1305 case OMF_mutableCopy: 1306 if (cocoa::isCocoaObjectRef(RetTy)) 1307 ResultEff = ObjCAllocRetE; 1308 else if (coreFoundation::isCFObjectRef(RetTy)) 1309 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true); 1310 break; 1311 case OMF_autorelease: 1312 ReceiverEff = Autorelease; 1313 break; 1314 case OMF_retain: 1315 ReceiverEff = IncRefMsg; 1316 break; 1317 case OMF_release: 1318 ReceiverEff = DecRefMsg; 1319 break; 1320 case OMF_dealloc: 1321 ReceiverEff = Dealloc; 1322 break; 1323 case OMF_self: 1324 // -self is handled specially by the ExprEngine to propagate the receiver. 1325 break; 1326 case OMF_retainCount: 1327 case OMF_finalize: 1328 // These methods don't return objects. 1329 break; 1330 } 1331 1332 // If one of the arguments in the selector has the keyword 'delegate' we 1333 // should stop tracking the reference count for the receiver. This is 1334 // because the reference count is quite possibly handled by a delegate 1335 // method. 1336 if (S.isKeywordSelector()) { 1337 const std::string &str = S.getAsString(); 1338 assert(!str.empty()); 1339 if (StrInStrNoCase(str, "delegate:") != StringRef::npos) 1340 ReceiverEff = StopTracking; 1341 } 1342 1343 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing && 1344 ResultEff.getKind() == RetEffect::NoRet) 1345 return getDefaultSummary(); 1346 1347 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape); 1348} 1349 1350const RetainSummary * 1351RetainSummaryManager::getInstanceMethodSummary(const ObjCMessage &msg, 1352 ProgramStateRef state, 1353 const LocationContext *LC) { 1354 1355 // We need the type-information of the tracked receiver object 1356 // Retrieve it from the state. 1357 const Expr *Receiver = msg.getInstanceReceiver(); 1358 const ObjCInterfaceDecl *ID = 0; 1359 1360 // FIXME: Is this really working as expected? There are cases where 1361 // we just use the 'ID' from the message expression. 1362 SVal receiverV; 1363 1364 if (Receiver) { 1365 receiverV = state->getSValAsScalarOrLoc(Receiver, LC); 1366 1367 // FIXME: Eventually replace the use of state->get<RefBindings> with 1368 // a generic API for reasoning about the Objective-C types of symbolic 1369 // objects. 1370 if (SymbolRef Sym = receiverV.getAsLocSymbol()) 1371 if (const RefVal *T = state->get<RefBindings>(Sym)) 1372 if (const ObjCObjectPointerType* PT = 1373 T->getType()->getAs<ObjCObjectPointerType>()) 1374 ID = PT->getInterfaceDecl(); 1375 1376 // FIXME: this is a hack. This may or may not be the actual method 1377 // that is called. 1378 if (!ID) { 1379 if (const ObjCObjectPointerType *PT = 1380 Receiver->getType()->getAs<ObjCObjectPointerType>()) 1381 ID = PT->getInterfaceDecl(); 1382 } 1383 } else { 1384 // FIXME: Hack for 'super'. 1385 ID = msg.getReceiverInterface(); 1386 } 1387 1388 // FIXME: The receiver could be a reference to a class, meaning that 1389 // we should use the class method. 1390 return getInstanceMethodSummary(msg, ID); 1391} 1392 1393const RetainSummary * 1394RetainSummaryManager::getMethodSummary(Selector S, IdentifierInfo *ClsName, 1395 const ObjCInterfaceDecl *ID, 1396 const ObjCMethodDecl *MD, QualType RetTy, 1397 ObjCMethodSummariesTy &CachedSummaries) { 1398 1399 // Look up a summary in our summary cache. 1400 const RetainSummary *Summ = CachedSummaries.find(ID, ClsName, S); 1401 1402 if (!Summ) { 1403 Summ = getStandardMethodSummary(MD, S, RetTy); 1404 1405 // Annotations override defaults. 1406 updateSummaryFromAnnotations(Summ, MD); 1407 1408 // Memoize the summary. 1409 CachedSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ; 1410 } 1411 1412 return Summ; 1413} 1414 1415void RetainSummaryManager::InitializeClassMethodSummaries() { 1416 assert(ScratchArgs.isEmpty()); 1417 // Create the [NSAssertionHandler currentHander] summary. 1418 addClassMethSummary("NSAssertionHandler", "currentHandler", 1419 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC))); 1420 1421 // Create the [NSAutoreleasePool addObject:] summary. 1422 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease); 1423 addClassMethSummary("NSAutoreleasePool", "addObject", 1424 getPersistentSummary(RetEffect::MakeNoRet(), 1425 DoNothing, Autorelease)); 1426 1427 // Create the summaries for [NSObject performSelector...]. We treat 1428 // these as 'stop tracking' for the arguments because they are often 1429 // used for delegates that can release the object. When we have better 1430 // inter-procedural analysis we can potentially do something better. This 1431 // workaround is to remove false positives. 1432 const RetainSummary *Summ = 1433 getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking); 1434 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject"); 1435 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject", 1436 "afterDelay", NULL); 1437 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject", 1438 "afterDelay", "inModes", NULL); 1439 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread", 1440 "withObject", "waitUntilDone", NULL); 1441 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread", 1442 "withObject", "waitUntilDone", "modes", NULL); 1443 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread", 1444 "withObject", "waitUntilDone", NULL); 1445 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread", 1446 "withObject", "waitUntilDone", "modes", NULL); 1447 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground", 1448 "withObject", NULL); 1449} 1450 1451void RetainSummaryManager::InitializeMethodSummaries() { 1452 1453 assert (ScratchArgs.isEmpty()); 1454 1455 // Create the "init" selector. It just acts as a pass-through for the 1456 // receiver. 1457 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg); 1458 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm); 1459 1460 // awakeAfterUsingCoder: behaves basically like an 'init' method. It 1461 // claims the receiver and returns a retained object. 1462 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx), 1463 InitSumm); 1464 1465 // The next methods are allocators. 1466 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE); 1467 const RetainSummary *CFAllocSumm = 1468 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true)); 1469 1470 // Create the "retain" selector. 1471 RetEffect NoRet = RetEffect::MakeNoRet(); 1472 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg); 1473 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ); 1474 1475 // Create the "release" selector. 1476 Summ = getPersistentSummary(NoRet, DecRefMsg); 1477 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ); 1478 1479 // Create the "drain" selector. 1480 Summ = getPersistentSummary(NoRet, isGCEnabled() ? DoNothing : DecRef); 1481 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ); 1482 1483 // Create the -dealloc summary. 1484 Summ = getPersistentSummary(NoRet, Dealloc); 1485 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ); 1486 1487 // Create the "autorelease" selector. 1488 Summ = getPersistentSummary(NoRet, Autorelease); 1489 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ); 1490 1491 // Specially handle NSAutoreleasePool. 1492 addInstMethSummary("NSAutoreleasePool", "init", 1493 getPersistentSummary(NoRet, NewAutoreleasePool)); 1494 1495 // For NSWindow, allocated objects are (initially) self-owned. 1496 // FIXME: For now we opt for false negatives with NSWindow, as these objects 1497 // self-own themselves. However, they only do this once they are displayed. 1498 // Thus, we need to track an NSWindow's display status. 1499 // This is tracked in <rdar://problem/6062711>. 1500 // See also http://llvm.org/bugs/show_bug.cgi?id=3714. 1501 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(), 1502 StopTracking, 1503 StopTracking); 1504 1505 addClassMethSummary("NSWindow", "alloc", NoTrackYet); 1506 1507#if 0 1508 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect", 1509 "styleMask", "backing", "defer", NULL); 1510 1511 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect", 1512 "styleMask", "backing", "defer", "screen", NULL); 1513#endif 1514 1515 // For NSPanel (which subclasses NSWindow), allocated objects are not 1516 // self-owned. 1517 // FIXME: For now we don't track NSPanels. object for the same reason 1518 // as for NSWindow objects. 1519 addClassMethSummary("NSPanel", "alloc", NoTrackYet); 1520 1521#if 0 1522 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect", 1523 "styleMask", "backing", "defer", NULL); 1524 1525 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect", 1526 "styleMask", "backing", "defer", "screen", NULL); 1527#endif 1528 1529 // Don't track allocated autorelease pools yet, as it is okay to prematurely 1530 // exit a method. 1531 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet); 1532 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false); 1533 1534 // Create summaries QCRenderer/QCView -createSnapShotImageOfType: 1535 addInstMethSummary("QCRenderer", AllocSumm, 1536 "createSnapshotImageOfType", NULL); 1537 addInstMethSummary("QCView", AllocSumm, 1538 "createSnapshotImageOfType", NULL); 1539 1540 // Create summaries for CIContext, 'createCGImage' and 1541 // 'createCGLayerWithSize'. These objects are CF objects, and are not 1542 // automatically garbage collected. 1543 addInstMethSummary("CIContext", CFAllocSumm, 1544 "createCGImage", "fromRect", NULL); 1545 addInstMethSummary("CIContext", CFAllocSumm, 1546 "createCGImage", "fromRect", "format", "colorSpace", NULL); 1547 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", 1548 "info", NULL); 1549} 1550 1551//===----------------------------------------------------------------------===// 1552// AutoreleaseBindings - State used to track objects in autorelease pools. 1553//===----------------------------------------------------------------------===// 1554 1555typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts; 1556typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents; 1557typedef llvm::ImmutableList<SymbolRef> ARStack; 1558 1559static int AutoRCIndex = 0; 1560static int AutoRBIndex = 0; 1561 1562namespace { class AutoreleasePoolContents {}; } 1563namespace { class AutoreleaseStack {}; } 1564 1565namespace clang { 1566namespace ento { 1567template<> struct ProgramStateTrait<AutoreleaseStack> 1568 : public ProgramStatePartialTrait<ARStack> { 1569 static inline void *GDMIndex() { return &AutoRBIndex; } 1570}; 1571 1572template<> struct ProgramStateTrait<AutoreleasePoolContents> 1573 : public ProgramStatePartialTrait<ARPoolContents> { 1574 static inline void *GDMIndex() { return &AutoRCIndex; } 1575}; 1576} // end GR namespace 1577} // end clang namespace 1578 1579static SymbolRef GetCurrentAutoreleasePool(ProgramStateRef state) { 1580 ARStack stack = state->get<AutoreleaseStack>(); 1581 return stack.isEmpty() ? SymbolRef() : stack.getHead(); 1582} 1583 1584static ProgramStateRef 1585SendAutorelease(ProgramStateRef state, 1586 ARCounts::Factory &F, 1587 SymbolRef sym) { 1588 SymbolRef pool = GetCurrentAutoreleasePool(state); 1589 const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool); 1590 ARCounts newCnts(0); 1591 1592 if (cnts) { 1593 const unsigned *cnt = (*cnts).lookup(sym); 1594 newCnts = F.add(*cnts, sym, cnt ? *cnt + 1 : 1); 1595 } 1596 else 1597 newCnts = F.add(F.getEmptyMap(), sym, 1); 1598 1599 return state->set<AutoreleasePoolContents>(pool, newCnts); 1600} 1601 1602//===----------------------------------------------------------------------===// 1603// Error reporting. 1604//===----------------------------------------------------------------------===// 1605namespace { 1606 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *> 1607 SummaryLogTy; 1608 1609 //===-------------===// 1610 // Bug Descriptions. // 1611 //===-------------===// 1612 1613 class CFRefBug : public BugType { 1614 protected: 1615 CFRefBug(StringRef name) 1616 : BugType(name, "Memory (Core Foundation/Objective-C)") {} 1617 public: 1618 1619 // FIXME: Eventually remove. 1620 virtual const char *getDescription() const = 0; 1621 1622 virtual bool isLeak() const { return false; } 1623 }; 1624 1625 class UseAfterRelease : public CFRefBug { 1626 public: 1627 UseAfterRelease() : CFRefBug("Use-after-release") {} 1628 1629 const char *getDescription() const { 1630 return "Reference-counted object is used after it is released"; 1631 } 1632 }; 1633 1634 class BadRelease : public CFRefBug { 1635 public: 1636 BadRelease() : CFRefBug("Bad release") {} 1637 1638 const char *getDescription() const { 1639 return "Incorrect decrement of the reference count of an object that is " 1640 "not owned at this point by the caller"; 1641 } 1642 }; 1643 1644 class DeallocGC : public CFRefBug { 1645 public: 1646 DeallocGC() 1647 : CFRefBug("-dealloc called while using garbage collection") {} 1648 1649 const char *getDescription() const { 1650 return "-dealloc called while using garbage collection"; 1651 } 1652 }; 1653 1654 class DeallocNotOwned : public CFRefBug { 1655 public: 1656 DeallocNotOwned() 1657 : CFRefBug("-dealloc sent to non-exclusively owned object") {} 1658 1659 const char *getDescription() const { 1660 return "-dealloc sent to object that may be referenced elsewhere"; 1661 } 1662 }; 1663 1664 class OverAutorelease : public CFRefBug { 1665 public: 1666 OverAutorelease() 1667 : CFRefBug("Object sent -autorelease too many times") {} 1668 1669 const char *getDescription() const { 1670 return "Object sent -autorelease too many times"; 1671 } 1672 }; 1673 1674 class ReturnedNotOwnedForOwned : public CFRefBug { 1675 public: 1676 ReturnedNotOwnedForOwned() 1677 : CFRefBug("Method should return an owned object") {} 1678 1679 const char *getDescription() const { 1680 return "Object with a +0 retain count returned to caller where a +1 " 1681 "(owning) retain count is expected"; 1682 } 1683 }; 1684 1685 class Leak : public CFRefBug { 1686 const bool isReturn; 1687 protected: 1688 Leak(StringRef name, bool isRet) 1689 : CFRefBug(name), isReturn(isRet) { 1690 // Leaks should not be reported if they are post-dominated by a sink. 1691 setSuppressOnSink(true); 1692 } 1693 public: 1694 1695 const char *getDescription() const { return ""; } 1696 1697 bool isLeak() const { return true; } 1698 }; 1699 1700 class LeakAtReturn : public Leak { 1701 public: 1702 LeakAtReturn(StringRef name) 1703 : Leak(name, true) {} 1704 }; 1705 1706 class LeakWithinFunction : public Leak { 1707 public: 1708 LeakWithinFunction(StringRef name) 1709 : Leak(name, false) {} 1710 }; 1711 1712 //===---------===// 1713 // Bug Reports. // 1714 //===---------===// 1715 1716 class CFRefReportVisitor : public BugReporterVisitor { 1717 protected: 1718 SymbolRef Sym; 1719 const SummaryLogTy &SummaryLog; 1720 bool GCEnabled; 1721 1722 public: 1723 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log) 1724 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {} 1725 1726 virtual void Profile(llvm::FoldingSetNodeID &ID) const { 1727 static int x = 0; 1728 ID.AddPointer(&x); 1729 ID.AddPointer(Sym); 1730 } 1731 1732 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N, 1733 const ExplodedNode *PrevN, 1734 BugReporterContext &BRC, 1735 BugReport &BR); 1736 1737 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC, 1738 const ExplodedNode *N, 1739 BugReport &BR); 1740 }; 1741 1742 class CFRefLeakReportVisitor : public CFRefReportVisitor { 1743 public: 1744 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled, 1745 const SummaryLogTy &log) 1746 : CFRefReportVisitor(sym, GCEnabled, log) {} 1747 1748 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC, 1749 const ExplodedNode *N, 1750 BugReport &BR); 1751 }; 1752 1753 class CFRefReport : public BugReport { 1754 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled); 1755 1756 public: 1757 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled, 1758 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym, 1759 bool registerVisitor = true) 1760 : BugReport(D, D.getDescription(), n) { 1761 if (registerVisitor) 1762 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log)); 1763 addGCModeDescription(LOpts, GCEnabled); 1764 } 1765 1766 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled, 1767 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym, 1768 StringRef endText) 1769 : BugReport(D, D.getDescription(), endText, n) { 1770 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log)); 1771 addGCModeDescription(LOpts, GCEnabled); 1772 } 1773 1774 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() { 1775 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType()); 1776 if (!BugTy.isLeak()) 1777 return BugReport::getRanges(); 1778 else 1779 return std::make_pair(ranges_iterator(), ranges_iterator()); 1780 } 1781 }; 1782 1783 class CFRefLeakReport : public CFRefReport { 1784 const MemRegion* AllocBinding; 1785 1786 public: 1787 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled, 1788 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym, 1789 CheckerContext &Ctx); 1790 1791 PathDiagnosticLocation getLocation(const SourceManager &SM) const { 1792 assert(Location.isValid()); 1793 return Location; 1794 } 1795 }; 1796} // end anonymous namespace 1797 1798void CFRefReport::addGCModeDescription(const LangOptions &LOpts, 1799 bool GCEnabled) { 1800 const char *GCModeDescription = 0; 1801 1802 switch (LOpts.getGC()) { 1803 case LangOptions::GCOnly: 1804 assert(GCEnabled); 1805 GCModeDescription = "Code is compiled to only use garbage collection"; 1806 break; 1807 1808 case LangOptions::NonGC: 1809 assert(!GCEnabled); 1810 GCModeDescription = "Code is compiled to use reference counts"; 1811 break; 1812 1813 case LangOptions::HybridGC: 1814 if (GCEnabled) { 1815 GCModeDescription = "Code is compiled to use either garbage collection " 1816 "(GC) or reference counts (non-GC). The bug occurs " 1817 "with GC enabled"; 1818 break; 1819 } else { 1820 GCModeDescription = "Code is compiled to use either garbage collection " 1821 "(GC) or reference counts (non-GC). The bug occurs " 1822 "in non-GC mode"; 1823 break; 1824 } 1825 } 1826 1827 assert(GCModeDescription && "invalid/unknown GC mode"); 1828 addExtraText(GCModeDescription); 1829} 1830 1831// FIXME: This should be a method on SmallVector. 1832static inline bool contains(const SmallVectorImpl<ArgEffect>& V, 1833 ArgEffect X) { 1834 for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end(); 1835 I!=E; ++I) 1836 if (*I == X) return true; 1837 1838 return false; 1839} 1840 1841static bool isPropertyAccess(const Stmt *S, ParentMap &PM) { 1842 unsigned maxDepth = 4; 1843 while (S && maxDepth) { 1844 if (const PseudoObjectExpr *PO = dyn_cast<PseudoObjectExpr>(S)) { 1845 if (!isa<ObjCMessageExpr>(PO->getSyntacticForm())) 1846 return true; 1847 return false; 1848 } 1849 S = PM.getParent(S); 1850 --maxDepth; 1851 } 1852 return false; 1853} 1854 1855PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N, 1856 const ExplodedNode *PrevN, 1857 BugReporterContext &BRC, 1858 BugReport &BR) { 1859 1860 if (!isa<StmtPoint>(N->getLocation())) 1861 return NULL; 1862 1863 // Check if the type state has changed. 1864 ProgramStateRef PrevSt = PrevN->getState(); 1865 ProgramStateRef CurrSt = N->getState(); 1866 const LocationContext *LCtx = N->getLocationContext(); 1867 1868 const RefVal* CurrT = CurrSt->get<RefBindings>(Sym); 1869 if (!CurrT) return NULL; 1870 1871 const RefVal &CurrV = *CurrT; 1872 const RefVal *PrevT = PrevSt->get<RefBindings>(Sym); 1873 1874 // Create a string buffer to constain all the useful things we want 1875 // to tell the user. 1876 std::string sbuf; 1877 llvm::raw_string_ostream os(sbuf); 1878 1879 // This is the allocation site since the previous node had no bindings 1880 // for this symbol. 1881 if (!PrevT) { 1882 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt(); 1883 1884 if (isa<ObjCArrayLiteral>(S)) { 1885 os << "NSArray literal is an object with a +0 retain count"; 1886 } 1887 else if (isa<ObjCDictionaryLiteral>(S)) { 1888 os << "NSDictionary literal is an object with a +0 retain count"; 1889 } 1890 else { 1891 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) { 1892 // Get the name of the callee (if it is available). 1893 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx); 1894 if (const FunctionDecl *FD = X.getAsFunctionDecl()) 1895 os << "Call to function '" << *FD << '\''; 1896 else 1897 os << "function call"; 1898 } 1899 else { 1900 assert(isa<ObjCMessageExpr>(S)); 1901 // The message expression may have between written directly or as 1902 // a property access. Lazily determine which case we are looking at. 1903 os << (isPropertyAccess(S, N->getParentMap()) ? "Property" : "Method"); 1904 } 1905 1906 if (CurrV.getObjKind() == RetEffect::CF) { 1907 os << " returns a Core Foundation object with a "; 1908 } 1909 else { 1910 assert (CurrV.getObjKind() == RetEffect::ObjC); 1911 os << " returns an Objective-C object with a "; 1912 } 1913 1914 if (CurrV.isOwned()) { 1915 os << "+1 retain count"; 1916 1917 if (GCEnabled) { 1918 assert(CurrV.getObjKind() == RetEffect::CF); 1919 os << ". " 1920 "Core Foundation objects are not automatically garbage collected."; 1921 } 1922 } 1923 else { 1924 assert (CurrV.isNotOwned()); 1925 os << "+0 retain count"; 1926 } 1927 } 1928 1929 PathDiagnosticLocation Pos(S, BRC.getSourceManager(), 1930 N->getLocationContext()); 1931 return new PathDiagnosticEventPiece(Pos, os.str()); 1932 } 1933 1934 // Gather up the effects that were performed on the object at this 1935 // program point 1936 SmallVector<ArgEffect, 2> AEffects; 1937 1938 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N); 1939 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) { 1940 // We only have summaries attached to nodes after evaluating CallExpr and 1941 // ObjCMessageExprs. 1942 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt(); 1943 1944 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) { 1945 // Iterate through the parameter expressions and see if the symbol 1946 // was ever passed as an argument. 1947 unsigned i = 0; 1948 1949 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end(); 1950 AI!=AE; ++AI, ++i) { 1951 1952 // Retrieve the value of the argument. Is it the symbol 1953 // we are interested in? 1954 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym) 1955 continue; 1956 1957 // We have an argument. Get the effect! 1958 AEffects.push_back(Summ->getArg(i)); 1959 } 1960 } 1961 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) { 1962 if (const Expr *receiver = ME->getInstanceReceiver()) 1963 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx) 1964 .getAsLocSymbol() == Sym) { 1965 // The symbol we are tracking is the receiver. 1966 AEffects.push_back(Summ->getReceiverEffect()); 1967 } 1968 } 1969 } 1970 1971 do { 1972 // Get the previous type state. 1973 RefVal PrevV = *PrevT; 1974 1975 // Specially handle -dealloc. 1976 if (!GCEnabled && contains(AEffects, Dealloc)) { 1977 // Determine if the object's reference count was pushed to zero. 1978 assert(!(PrevV == CurrV) && "The typestate *must* have changed."); 1979 // We may not have transitioned to 'release' if we hit an error. 1980 // This case is handled elsewhere. 1981 if (CurrV.getKind() == RefVal::Released) { 1982 assert(CurrV.getCombinedCounts() == 0); 1983 os << "Object released by directly sending the '-dealloc' message"; 1984 break; 1985 } 1986 } 1987 1988 // Specially handle CFMakeCollectable and friends. 1989 if (contains(AEffects, MakeCollectable)) { 1990 // Get the name of the function. 1991 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt(); 1992 SVal X = 1993 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx); 1994 const FunctionDecl *FD = X.getAsFunctionDecl(); 1995 1996 if (GCEnabled) { 1997 // Determine if the object's reference count was pushed to zero. 1998 assert(!(PrevV == CurrV) && "The typestate *must* have changed."); 1999 2000 os << "In GC mode a call to '" << *FD 2001 << "' decrements an object's retain count and registers the " 2002 "object with the garbage collector. "; 2003 2004 if (CurrV.getKind() == RefVal::Released) { 2005 assert(CurrV.getCount() == 0); 2006 os << "Since it now has a 0 retain count the object can be " 2007 "automatically collected by the garbage collector."; 2008 } 2009 else 2010 os << "An object must have a 0 retain count to be garbage collected. " 2011 "After this call its retain count is +" << CurrV.getCount() 2012 << '.'; 2013 } 2014 else 2015 os << "When GC is not enabled a call to '" << *FD 2016 << "' has no effect on its argument."; 2017 2018 // Nothing more to say. 2019 break; 2020 } 2021 2022 // Determine if the typestate has changed. 2023 if (!(PrevV == CurrV)) 2024 switch (CurrV.getKind()) { 2025 case RefVal::Owned: 2026 case RefVal::NotOwned: 2027 2028 if (PrevV.getCount() == CurrV.getCount()) { 2029 // Did an autorelease message get sent? 2030 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount()) 2031 return 0; 2032 2033 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount()); 2034 os << "Object sent -autorelease message"; 2035 break; 2036 } 2037 2038 if (PrevV.getCount() > CurrV.getCount()) 2039 os << "Reference count decremented."; 2040 else 2041 os << "Reference count incremented."; 2042 2043 if (unsigned Count = CurrV.getCount()) 2044 os << " The object now has a +" << Count << " retain count."; 2045 2046 if (PrevV.getKind() == RefVal::Released) { 2047 assert(GCEnabled && CurrV.getCount() > 0); 2048 os << " The object is not eligible for garbage collection until " 2049 "the retain count reaches 0 again."; 2050 } 2051 2052 break; 2053 2054 case RefVal::Released: 2055 os << "Object released."; 2056 break; 2057 2058 case RefVal::ReturnedOwned: 2059 // Autoreleases can be applied after marking a node ReturnedOwned. 2060 if (CurrV.getAutoreleaseCount()) 2061 return NULL; 2062 2063 os << "Object returned to caller as an owning reference (single " 2064 "retain count transferred to caller)"; 2065 break; 2066 2067 case RefVal::ReturnedNotOwned: 2068 os << "Object returned to caller with a +0 retain count"; 2069 break; 2070 2071 default: 2072 return NULL; 2073 } 2074 2075 // Emit any remaining diagnostics for the argument effects (if any). 2076 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(), 2077 E=AEffects.end(); I != E; ++I) { 2078 2079 // A bunch of things have alternate behavior under GC. 2080 if (GCEnabled) 2081 switch (*I) { 2082 default: break; 2083 case Autorelease: 2084 os << "In GC mode an 'autorelease' has no effect."; 2085 continue; 2086 case IncRefMsg: 2087 os << "In GC mode the 'retain' message has no effect."; 2088 continue; 2089 case DecRefMsg: 2090 os << "In GC mode the 'release' message has no effect."; 2091 continue; 2092 } 2093 } 2094 } while (0); 2095 2096 if (os.str().empty()) 2097 return 0; // We have nothing to say! 2098 2099 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt(); 2100 PathDiagnosticLocation Pos(S, BRC.getSourceManager(), 2101 N->getLocationContext()); 2102 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str()); 2103 2104 // Add the range by scanning the children of the statement for any bindings 2105 // to Sym. 2106 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end(); 2107 I!=E; ++I) 2108 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I)) 2109 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) { 2110 P->addRange(Exp->getSourceRange()); 2111 break; 2112 } 2113 2114 return P; 2115} 2116 2117// Find the first node in the current function context that referred to the 2118// tracked symbol and the memory location that value was stored to. Note, the 2119// value is only reported if the allocation occurred in the same function as 2120// the leak. 2121static std::pair<const ExplodedNode*,const MemRegion*> 2122GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N, 2123 SymbolRef Sym) { 2124 const ExplodedNode *Last = N; 2125 const MemRegion* FirstBinding = 0; 2126 const LocationContext *LeakContext = N->getLocationContext(); 2127 2128 while (N) { 2129 ProgramStateRef St = N->getState(); 2130 RefBindings B = St->get<RefBindings>(); 2131 2132 if (!B.lookup(Sym)) 2133 break; 2134 2135 StoreManager::FindUniqueBinding FB(Sym); 2136 StateMgr.iterBindings(St, FB); 2137 if (FB) FirstBinding = FB.getRegion(); 2138 2139 // Allocation node, is the last node in the current context in which the 2140 // symbol was tracked. 2141 if (N->getLocationContext() == LeakContext) 2142 Last = N; 2143 2144 N = N->pred_empty() ? NULL : *(N->pred_begin()); 2145 } 2146 2147 // If allocation happened in a function different from the leak node context, 2148 // do not report the binding. 2149 if (N->getLocationContext() != LeakContext) { 2150 FirstBinding = 0; 2151 } 2152 2153 return std::make_pair(Last, FirstBinding); 2154} 2155 2156PathDiagnosticPiece* 2157CFRefReportVisitor::getEndPath(BugReporterContext &BRC, 2158 const ExplodedNode *EndN, 2159 BugReport &BR) { 2160 BR.markInteresting(Sym); 2161 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR); 2162} 2163 2164PathDiagnosticPiece* 2165CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC, 2166 const ExplodedNode *EndN, 2167 BugReport &BR) { 2168 2169 // Tell the BugReporterContext to report cases when the tracked symbol is 2170 // assigned to different variables, etc. 2171 BR.markInteresting(Sym); 2172 2173 // We are reporting a leak. Walk up the graph to get to the first node where 2174 // the symbol appeared, and also get the first VarDecl that tracked object 2175 // is stored to. 2176 const ExplodedNode *AllocNode = 0; 2177 const MemRegion* FirstBinding = 0; 2178 2179 llvm::tie(AllocNode, FirstBinding) = 2180 GetAllocationSite(BRC.getStateManager(), EndN, Sym); 2181 2182 SourceManager& SM = BRC.getSourceManager(); 2183 2184 // Compute an actual location for the leak. Sometimes a leak doesn't 2185 // occur at an actual statement (e.g., transition between blocks; end 2186 // of function) so we need to walk the graph and compute a real location. 2187 const ExplodedNode *LeakN = EndN; 2188 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM); 2189 2190 std::string sbuf; 2191 llvm::raw_string_ostream os(sbuf); 2192 2193 os << "Object leaked: "; 2194 2195 if (FirstBinding) { 2196 os << "object allocated and stored into '" 2197 << FirstBinding->getString() << '\''; 2198 } 2199 else 2200 os << "allocated object"; 2201 2202 // Get the retain count. 2203 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym); 2204 2205 if (RV->getKind() == RefVal::ErrorLeakReturned) { 2206 // FIXME: Per comments in rdar://6320065, "create" only applies to CF 2207 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership 2208 // to the caller for NS objects. 2209 const Decl *D = &EndN->getCodeDecl(); 2210 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 2211 os << " is returned from a method whose name ('" 2212 << MD->getSelector().getAsString() 2213 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'." 2214 " This violates the naming convention rules" 2215 " given in the Memory Management Guide for Cocoa"; 2216 } 2217 else { 2218 const FunctionDecl *FD = cast<FunctionDecl>(D); 2219 os << " is returned from a function whose name ('" 2220 << *FD 2221 << "') does not contain 'Copy' or 'Create'. This violates the naming" 2222 " convention rules given in the Memory Management Guide for Core" 2223 " Foundation"; 2224 } 2225 } 2226 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) { 2227 ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl()); 2228 os << " and returned from method '" << MD.getSelector().getAsString() 2229 << "' is potentially leaked when using garbage collection. Callers " 2230 "of this method do not expect a returned object with a +1 retain " 2231 "count since they expect the object to be managed by the garbage " 2232 "collector"; 2233 } 2234 else 2235 os << " is not referenced later in this execution path and has a retain " 2236 "count of +" << RV->getCount(); 2237 2238 return new PathDiagnosticEventPiece(L, os.str()); 2239} 2240 2241CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, 2242 bool GCEnabled, const SummaryLogTy &Log, 2243 ExplodedNode *n, SymbolRef sym, 2244 CheckerContext &Ctx) 2245: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) { 2246 2247 // Most bug reports are cached at the location where they occurred. 2248 // With leaks, we want to unique them by the location where they were 2249 // allocated, and only report a single path. To do this, we need to find 2250 // the allocation site of a piece of tracked memory, which we do via a 2251 // call to GetAllocationSite. This will walk the ExplodedGraph backwards. 2252 // Note that this is *not* the trimmed graph; we are guaranteed, however, 2253 // that all ancestor nodes that represent the allocation site have the 2254 // same SourceLocation. 2255 const ExplodedNode *AllocNode = 0; 2256 2257 const SourceManager& SMgr = Ctx.getSourceManager(); 2258 2259 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding. 2260 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym); 2261 2262 // Get the SourceLocation for the allocation site. 2263 ProgramPoint P = AllocNode->getLocation(); 2264 const Stmt *AllocStmt = cast<PostStmt>(P).getStmt(); 2265 Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr, 2266 n->getLocationContext()); 2267 // Fill in the description of the bug. 2268 Description.clear(); 2269 llvm::raw_string_ostream os(Description); 2270 os << "Potential leak "; 2271 if (GCEnabled) 2272 os << "(when using garbage collection) "; 2273 os << "of an object"; 2274 2275 // FIXME: AllocBinding doesn't get populated for RegionStore yet. 2276 if (AllocBinding) 2277 os << " stored into '" << AllocBinding->getString() << '\''; 2278 2279 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log)); 2280} 2281 2282//===----------------------------------------------------------------------===// 2283// Main checker logic. 2284//===----------------------------------------------------------------------===// 2285 2286namespace { 2287class RetainCountChecker 2288 : public Checker< check::Bind, 2289 check::DeadSymbols, 2290 check::EndAnalysis, 2291 check::EndPath, 2292 check::PostStmt<BlockExpr>, 2293 check::PostStmt<CastExpr>, 2294 check::PostStmt<CallExpr>, 2295 check::PostStmt<CXXConstructExpr>, 2296 check::PostStmt<ObjCArrayLiteral>, 2297 check::PostStmt<ObjCDictionaryLiteral>, 2298 check::PostObjCMessage, 2299 check::PreStmt<ReturnStmt>, 2300 check::RegionChanges, 2301 eval::Assume, 2302 eval::Call > { 2303 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned; 2304 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned; 2305 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned; 2306 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn; 2307 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC; 2308 2309 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap; 2310 2311 // This map is only used to ensure proper deletion of any allocated tags. 2312 mutable SymbolTagMap DeadSymbolTags; 2313 2314 mutable OwningPtr<RetainSummaryManager> Summaries; 2315 mutable OwningPtr<RetainSummaryManager> SummariesGC; 2316 2317 mutable ARCounts::Factory ARCountFactory; 2318 2319 mutable SummaryLogTy SummaryLog; 2320 mutable bool ShouldResetSummaryLog; 2321 2322public: 2323 RetainCountChecker() : ShouldResetSummaryLog(false) {} 2324 2325 virtual ~RetainCountChecker() { 2326 DeleteContainerSeconds(DeadSymbolTags); 2327 } 2328 2329 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR, 2330 ExprEngine &Eng) const { 2331 // FIXME: This is a hack to make sure the summary log gets cleared between 2332 // analyses of different code bodies. 2333 // 2334 // Why is this necessary? Because a checker's lifetime is tied to a 2335 // translation unit, but an ExplodedGraph's lifetime is just a code body. 2336 // Once in a blue moon, a new ExplodedNode will have the same address as an 2337 // old one with an associated summary, and the bug report visitor gets very 2338 // confused. (To make things worse, the summary lifetime is currently also 2339 // tied to a code body, so we get a crash instead of incorrect results.) 2340 // 2341 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph 2342 // changes, things will start going wrong again. Really the lifetime of this 2343 // log needs to be tied to either the specific nodes in it or the entire 2344 // ExplodedGraph, not to a specific part of the code being analyzed. 2345 // 2346 // (Also, having stateful local data means that the same checker can't be 2347 // used from multiple threads, but a lot of checkers have incorrect 2348 // assumptions about that anyway. So that wasn't a priority at the time of 2349 // this fix.) 2350 // 2351 // This happens at the end of analysis, but bug reports are emitted /after/ 2352 // this point. So we can't just clear the summary log now. Instead, we mark 2353 // that the next time we access the summary log, it should be cleared. 2354 2355 // If we never reset the summary log during /this/ code body analysis, 2356 // there were no new summaries. There might still have been summaries from 2357 // the /last/ analysis, so clear them out to make sure the bug report 2358 // visitors don't get confused. 2359 if (ShouldResetSummaryLog) 2360 SummaryLog.clear(); 2361 2362 ShouldResetSummaryLog = !SummaryLog.empty(); 2363 } 2364 2365 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts, 2366 bool GCEnabled) const { 2367 if (GCEnabled) { 2368 if (!leakWithinFunctionGC) 2369 leakWithinFunctionGC.reset(new LeakWithinFunction("Leak of object when " 2370 "using garbage " 2371 "collection")); 2372 return leakWithinFunctionGC.get(); 2373 } else { 2374 if (!leakWithinFunction) { 2375 if (LOpts.getGC() == LangOptions::HybridGC) { 2376 leakWithinFunction.reset(new LeakWithinFunction("Leak of object when " 2377 "not using garbage " 2378 "collection (GC) in " 2379 "dual GC/non-GC " 2380 "code")); 2381 } else { 2382 leakWithinFunction.reset(new LeakWithinFunction("Leak")); 2383 } 2384 } 2385 return leakWithinFunction.get(); 2386 } 2387 } 2388 2389 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const { 2390 if (GCEnabled) { 2391 if (!leakAtReturnGC) 2392 leakAtReturnGC.reset(new LeakAtReturn("Leak of returned object when " 2393 "using garbage collection")); 2394 return leakAtReturnGC.get(); 2395 } else { 2396 if (!leakAtReturn) { 2397 if (LOpts.getGC() == LangOptions::HybridGC) { 2398 leakAtReturn.reset(new LeakAtReturn("Leak of returned object when " 2399 "not using garbage collection " 2400 "(GC) in dual GC/non-GC code")); 2401 } else { 2402 leakAtReturn.reset(new LeakAtReturn("Leak of returned object")); 2403 } 2404 } 2405 return leakAtReturn.get(); 2406 } 2407 } 2408 2409 RetainSummaryManager &getSummaryManager(ASTContext &Ctx, 2410 bool GCEnabled) const { 2411 // FIXME: We don't support ARC being turned on and off during one analysis. 2412 // (nor, for that matter, do we support changing ASTContexts) 2413 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount; 2414 if (GCEnabled) { 2415 if (!SummariesGC) 2416 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled)); 2417 else 2418 assert(SummariesGC->isARCEnabled() == ARCEnabled); 2419 return *SummariesGC; 2420 } else { 2421 if (!Summaries) 2422 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled)); 2423 else 2424 assert(Summaries->isARCEnabled() == ARCEnabled); 2425 return *Summaries; 2426 } 2427 } 2428 2429 RetainSummaryManager &getSummaryManager(CheckerContext &C) const { 2430 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled()); 2431 } 2432 2433 void printState(raw_ostream &Out, ProgramStateRef State, 2434 const char *NL, const char *Sep) const; 2435 2436 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const; 2437 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const; 2438 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const; 2439 2440 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const; 2441 void checkPostStmt(const CXXConstructExpr *CE, CheckerContext &C) const; 2442 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const; 2443 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const; 2444 void checkPostObjCMessage(const ObjCMessage &Msg, CheckerContext &C) const; 2445 2446 void checkSummary(const RetainSummary &Summ, const CallOrObjCMessage &Call, 2447 CheckerContext &C) const; 2448 2449 bool evalCall(const CallExpr *CE, CheckerContext &C) const; 2450 2451 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond, 2452 bool Assumption) const; 2453 2454 ProgramStateRef 2455 checkRegionChanges(ProgramStateRef state, 2456 const StoreManager::InvalidatedSymbols *invalidated, 2457 ArrayRef<const MemRegion *> ExplicitRegions, 2458 ArrayRef<const MemRegion *> Regions, 2459 const CallOrObjCMessage *Call) const; 2460 2461 bool wantsRegionChangeUpdate(ProgramStateRef state) const { 2462 return true; 2463 } 2464 2465 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const; 2466 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C, 2467 ExplodedNode *Pred, RetEffect RE, RefVal X, 2468 SymbolRef Sym, ProgramStateRef state) const; 2469 2470 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const; 2471 void checkEndPath(CheckerContext &C) const; 2472 2473 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym, 2474 RefVal V, ArgEffect E, RefVal::Kind &hasErr, 2475 CheckerContext &C) const; 2476 2477 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange, 2478 RefVal::Kind ErrorKind, SymbolRef Sym, 2479 CheckerContext &C) const; 2480 2481 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const; 2482 2483 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const; 2484 2485 ProgramStateRef handleSymbolDeath(ProgramStateRef state, 2486 SymbolRef sid, RefVal V, 2487 SmallVectorImpl<SymbolRef> &Leaked) const; 2488 2489 std::pair<ExplodedNode *, ProgramStateRef > 2490 handleAutoreleaseCounts(ProgramStateRef state, 2491 GenericNodeBuilderRefCount Bd, ExplodedNode *Pred, 2492 CheckerContext &Ctx, SymbolRef Sym, RefVal V) const; 2493 2494 ExplodedNode *processLeaks(ProgramStateRef state, 2495 SmallVectorImpl<SymbolRef> &Leaked, 2496 GenericNodeBuilderRefCount &Builder, 2497 CheckerContext &Ctx, 2498 ExplodedNode *Pred = 0) const; 2499}; 2500} // end anonymous namespace 2501 2502namespace { 2503class StopTrackingCallback : public SymbolVisitor { 2504 ProgramStateRef state; 2505public: 2506 StopTrackingCallback(ProgramStateRef st) : state(st) {} 2507 ProgramStateRef getState() const { return state; } 2508 2509 bool VisitSymbol(SymbolRef sym) { 2510 state = state->remove<RefBindings>(sym); 2511 return true; 2512 } 2513}; 2514} // end anonymous namespace 2515 2516//===----------------------------------------------------------------------===// 2517// Handle statements that may have an effect on refcounts. 2518//===----------------------------------------------------------------------===// 2519 2520void RetainCountChecker::checkPostStmt(const BlockExpr *BE, 2521 CheckerContext &C) const { 2522 2523 // Scan the BlockDecRefExprs for any object the retain count checker 2524 // may be tracking. 2525 if (!BE->getBlockDecl()->hasCaptures()) 2526 return; 2527 2528 ProgramStateRef state = C.getState(); 2529 const BlockDataRegion *R = 2530 cast<BlockDataRegion>(state->getSVal(BE, 2531 C.getLocationContext()).getAsRegion()); 2532 2533 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(), 2534 E = R->referenced_vars_end(); 2535 2536 if (I == E) 2537 return; 2538 2539 // FIXME: For now we invalidate the tracking of all symbols passed to blocks 2540 // via captured variables, even though captured variables result in a copy 2541 // and in implicit increment/decrement of a retain count. 2542 SmallVector<const MemRegion*, 10> Regions; 2543 const LocationContext *LC = C.getLocationContext(); 2544 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager(); 2545 2546 for ( ; I != E; ++I) { 2547 const VarRegion *VR = *I; 2548 if (VR->getSuperRegion() == R) { 2549 VR = MemMgr.getVarRegion(VR->getDecl(), LC); 2550 } 2551 Regions.push_back(VR); 2552 } 2553 2554 state = 2555 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(), 2556 Regions.data() + Regions.size()).getState(); 2557 C.addTransition(state); 2558} 2559 2560void RetainCountChecker::checkPostStmt(const CastExpr *CE, 2561 CheckerContext &C) const { 2562 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE); 2563 if (!BE) 2564 return; 2565 2566 ArgEffect AE = IncRef; 2567 2568 switch (BE->getBridgeKind()) { 2569 case clang::OBC_Bridge: 2570 // Do nothing. 2571 return; 2572 case clang::OBC_BridgeRetained: 2573 AE = IncRef; 2574 break; 2575 case clang::OBC_BridgeTransfer: 2576 AE = DecRefBridgedTransfered; 2577 break; 2578 } 2579 2580 ProgramStateRef state = C.getState(); 2581 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol(); 2582 if (!Sym) 2583 return; 2584 const RefVal* T = state->get<RefBindings>(Sym); 2585 if (!T) 2586 return; 2587 2588 RefVal::Kind hasErr = (RefVal::Kind) 0; 2589 state = updateSymbol(state, Sym, *T, AE, hasErr, C); 2590 2591 if (hasErr) { 2592 // FIXME: If we get an error during a bridge cast, should we report it? 2593 // Should we assert that there is no error? 2594 return; 2595 } 2596 2597 C.addTransition(state); 2598} 2599 2600void RetainCountChecker::checkPostStmt(const CallExpr *CE, 2601 CheckerContext &C) const { 2602 if (C.wasInlined) 2603 return; 2604 2605 // Get the callee. 2606 ProgramStateRef state = C.getState(); 2607 const Expr *Callee = CE->getCallee(); 2608 SVal L = state->getSVal(Callee, C.getLocationContext()); 2609 2610 RetainSummaryManager &Summaries = getSummaryManager(C); 2611 const RetainSummary *Summ = 0; 2612 2613 // FIXME: Better support for blocks. For now we stop tracking anything 2614 // that is passed to blocks. 2615 // FIXME: Need to handle variables that are "captured" by the block. 2616 if (dyn_cast_or_null<BlockDataRegion>(L.getAsRegion())) { 2617 Summ = Summaries.getPersistentStopSummary(); 2618 } else if (const FunctionDecl *FD = L.getAsFunctionDecl()) { 2619 Summ = Summaries.getSummary(FD); 2620 } else if (const CXXMemberCallExpr *me = dyn_cast<CXXMemberCallExpr>(CE)) { 2621 if (const CXXMethodDecl *MD = me->getMethodDecl()) 2622 Summ = Summaries.getSummary(MD); 2623 } 2624 2625 if (!Summ) 2626 Summ = Summaries.getDefaultSummary(); 2627 2628 checkSummary(*Summ, CallOrObjCMessage(CE, state, C.getLocationContext()), C); 2629} 2630 2631void RetainCountChecker::checkPostStmt(const CXXConstructExpr *CE, 2632 CheckerContext &C) const { 2633 const CXXConstructorDecl *Ctor = CE->getConstructor(); 2634 if (!Ctor) 2635 return; 2636 2637 RetainSummaryManager &Summaries = getSummaryManager(C); 2638 const RetainSummary *Summ = Summaries.getSummary(Ctor); 2639 2640 // If we didn't get a summary, this constructor doesn't affect retain counts. 2641 if (!Summ) 2642 return; 2643 2644 ProgramStateRef state = C.getState(); 2645 checkSummary(*Summ, CallOrObjCMessage(CE, state, C.getLocationContext()), C); 2646} 2647 2648void RetainCountChecker::processObjCLiterals(CheckerContext &C, 2649 const Expr *Ex) const { 2650 ProgramStateRef state = C.getState(); 2651 const ExplodedNode *pred = C.getPredecessor(); 2652 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ; 2653 it != et ; ++it) { 2654 const Stmt *child = *it; 2655 SVal V = state->getSVal(child, pred->getLocationContext()); 2656 if (SymbolRef sym = V.getAsSymbol()) 2657 if (const RefVal* T = state->get<RefBindings>(sym)) { 2658 RefVal::Kind hasErr = (RefVal::Kind) 0; 2659 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C); 2660 if (hasErr) { 2661 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C); 2662 return; 2663 } 2664 } 2665 } 2666 2667 // Return the object as autoreleased. 2668 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC); 2669 if (SymbolRef sym = 2670 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) { 2671 QualType ResultTy = Ex->getType(); 2672 state = state->set<RefBindings>(sym, RefVal::makeNotOwned(RetEffect::ObjC, 2673 ResultTy)); 2674 } 2675 2676 C.addTransition(state); 2677} 2678 2679void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL, 2680 CheckerContext &C) const { 2681 // Apply the 'MayEscape' to all values. 2682 processObjCLiterals(C, AL); 2683} 2684 2685void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL, 2686 CheckerContext &C) const { 2687 // Apply the 'MayEscape' to all keys and values. 2688 processObjCLiterals(C, DL); 2689} 2690 2691void RetainCountChecker::checkPostObjCMessage(const ObjCMessage &Msg, 2692 CheckerContext &C) const { 2693 ProgramStateRef state = C.getState(); 2694 2695 RetainSummaryManager &Summaries = getSummaryManager(C); 2696 2697 const RetainSummary *Summ; 2698 if (Msg.isInstanceMessage()) { 2699 const LocationContext *LC = C.getLocationContext(); 2700 Summ = Summaries.getInstanceMethodSummary(Msg, state, LC); 2701 } else { 2702 Summ = Summaries.getClassMethodSummary(Msg); 2703 } 2704 2705 // If we didn't get a summary, this message doesn't affect retain counts. 2706 if (!Summ) 2707 return; 2708 2709 checkSummary(*Summ, CallOrObjCMessage(Msg, state, C.getLocationContext()), C); 2710} 2711 2712/// GetReturnType - Used to get the return type of a message expression or 2713/// function call with the intention of affixing that type to a tracked symbol. 2714/// While the the return type can be queried directly from RetEx, when 2715/// invoking class methods we augment to the return type to be that of 2716/// a pointer to the class (as opposed it just being id). 2717// FIXME: We may be able to do this with related result types instead. 2718// This function is probably overestimating. 2719static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) { 2720 QualType RetTy = RetE->getType(); 2721 // If RetE is not a message expression just return its type. 2722 // If RetE is a message expression, return its types if it is something 2723 /// more specific than id. 2724 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE)) 2725 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>()) 2726 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() || 2727 PT->isObjCClassType()) { 2728 // At this point we know the return type of the message expression is 2729 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this 2730 // is a call to a class method whose type we can resolve. In such 2731 // cases, promote the return type to XXX* (where XXX is the class). 2732 const ObjCInterfaceDecl *D = ME->getReceiverInterface(); 2733 return !D ? RetTy : 2734 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D)); 2735 } 2736 2737 return RetTy; 2738} 2739 2740void RetainCountChecker::checkSummary(const RetainSummary &Summ, 2741 const CallOrObjCMessage &CallOrMsg, 2742 CheckerContext &C) const { 2743 ProgramStateRef state = C.getState(); 2744 2745 // Evaluate the effect of the arguments. 2746 RefVal::Kind hasErr = (RefVal::Kind) 0; 2747 SourceRange ErrorRange; 2748 SymbolRef ErrorSym = 0; 2749 2750 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) { 2751 SVal V = CallOrMsg.getArgSVal(idx); 2752 2753 if (SymbolRef Sym = V.getAsLocSymbol()) { 2754 if (RefBindings::data_type *T = state->get<RefBindings>(Sym)) { 2755 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C); 2756 if (hasErr) { 2757 ErrorRange = CallOrMsg.getArgSourceRange(idx); 2758 ErrorSym = Sym; 2759 break; 2760 } 2761 } 2762 } 2763 } 2764 2765 // Evaluate the effect on the message receiver. 2766 bool ReceiverIsTracked = false; 2767 if (!hasErr && CallOrMsg.isObjCMessage()) { 2768 const LocationContext *LC = C.getLocationContext(); 2769 SVal Receiver = CallOrMsg.getInstanceMessageReceiver(LC); 2770 if (SymbolRef Sym = Receiver.getAsLocSymbol()) { 2771 if (const RefVal *T = state->get<RefBindings>(Sym)) { 2772 ReceiverIsTracked = true; 2773 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(), 2774 hasErr, C); 2775 if (hasErr) { 2776 ErrorRange = CallOrMsg.getReceiverSourceRange(); 2777 ErrorSym = Sym; 2778 } 2779 } 2780 } 2781 } 2782 2783 // Process any errors. 2784 if (hasErr) { 2785 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C); 2786 return; 2787 } 2788 2789 // Consult the summary for the return value. 2790 RetEffect RE = Summ.getRetEffect(); 2791 2792 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) { 2793 if (ReceiverIsTracked) 2794 RE = getSummaryManager(C).getObjAllocRetEffect(); 2795 else 2796 RE = RetEffect::MakeNoRet(); 2797 } 2798 2799 switch (RE.getKind()) { 2800 default: 2801 llvm_unreachable("Unhandled RetEffect."); 2802 2803 case RetEffect::NoRet: 2804 // No work necessary. 2805 break; 2806 2807 case RetEffect::OwnedAllocatedSymbol: 2808 case RetEffect::OwnedSymbol: { 2809 SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(), 2810 C.getLocationContext()).getAsSymbol(); 2811 if (!Sym) 2812 break; 2813 2814 // Use the result type from callOrMsg as it automatically adjusts 2815 // for methods/functions that return references. 2816 QualType ResultTy = CallOrMsg.getResultType(C.getASTContext()); 2817 state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(), 2818 ResultTy)); 2819 2820 // FIXME: Add a flag to the checker where allocations are assumed to 2821 // *not* fail. (The code below is out-of-date, though.) 2822#if 0 2823 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) { 2824 bool isFeasible; 2825 state = state.assume(loc::SymbolVal(Sym), true, isFeasible); 2826 assert(isFeasible && "Cannot assume fresh symbol is non-null."); 2827 } 2828#endif 2829 2830 break; 2831 } 2832 2833 case RetEffect::GCNotOwnedSymbol: 2834 case RetEffect::ARCNotOwnedSymbol: 2835 case RetEffect::NotOwnedSymbol: { 2836 const Expr *Ex = CallOrMsg.getOriginExpr(); 2837 SymbolRef Sym = state->getSVal(Ex, C.getLocationContext()).getAsSymbol(); 2838 if (!Sym) 2839 break; 2840 2841 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *. 2842 QualType ResultTy = GetReturnType(Ex, C.getASTContext()); 2843 state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(), 2844 ResultTy)); 2845 break; 2846 } 2847 } 2848 2849 // This check is actually necessary; otherwise the statement builder thinks 2850 // we've hit a previously-found path. 2851 // Normally addTransition takes care of this, but we want the node pointer. 2852 ExplodedNode *NewNode; 2853 if (state == C.getState()) { 2854 NewNode = C.getPredecessor(); 2855 } else { 2856 NewNode = C.addTransition(state); 2857 } 2858 2859 // Annotate the node with summary we used. 2860 if (NewNode) { 2861 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary. 2862 if (ShouldResetSummaryLog) { 2863 SummaryLog.clear(); 2864 ShouldResetSummaryLog = false; 2865 } 2866 SummaryLog[NewNode] = &Summ; 2867 } 2868} 2869 2870 2871ProgramStateRef 2872RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym, 2873 RefVal V, ArgEffect E, RefVal::Kind &hasErr, 2874 CheckerContext &C) const { 2875 // In GC mode [... release] and [... retain] do nothing. 2876 // In ARC mode they shouldn't exist at all, but we just ignore them. 2877 bool IgnoreRetainMsg = C.isObjCGCEnabled(); 2878 if (!IgnoreRetainMsg) 2879 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount; 2880 2881 switch (E) { 2882 default: break; 2883 case IncRefMsg: E = IgnoreRetainMsg ? DoNothing : IncRef; break; 2884 case DecRefMsg: E = IgnoreRetainMsg ? DoNothing : DecRef; break; 2885 case MakeCollectable: E = C.isObjCGCEnabled() ? DecRef : DoNothing; break; 2886 case NewAutoreleasePool: E = C.isObjCGCEnabled() ? DoNothing : 2887 NewAutoreleasePool; break; 2888 } 2889 2890 // Handle all use-after-releases. 2891 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) { 2892 V = V ^ RefVal::ErrorUseAfterRelease; 2893 hasErr = V.getKind(); 2894 return state->set<RefBindings>(sym, V); 2895 } 2896 2897 switch (E) { 2898 case DecRefMsg: 2899 case IncRefMsg: 2900 case MakeCollectable: 2901 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted"); 2902 2903 case Dealloc: 2904 // Any use of -dealloc in GC is *bad*. 2905 if (C.isObjCGCEnabled()) { 2906 V = V ^ RefVal::ErrorDeallocGC; 2907 hasErr = V.getKind(); 2908 break; 2909 } 2910 2911 switch (V.getKind()) { 2912 default: 2913 llvm_unreachable("Invalid RefVal state for an explicit dealloc."); 2914 case RefVal::Owned: 2915 // The object immediately transitions to the released state. 2916 V = V ^ RefVal::Released; 2917 V.clearCounts(); 2918 return state->set<RefBindings>(sym, V); 2919 case RefVal::NotOwned: 2920 V = V ^ RefVal::ErrorDeallocNotOwned; 2921 hasErr = V.getKind(); 2922 break; 2923 } 2924 break; 2925 2926 case NewAutoreleasePool: 2927 assert(!C.isObjCGCEnabled()); 2928 return state->add<AutoreleaseStack>(sym); 2929 2930 case MayEscape: 2931 if (V.getKind() == RefVal::Owned) { 2932 V = V ^ RefVal::NotOwned; 2933 break; 2934 } 2935 2936 // Fall-through. 2937 2938 case DoNothing: 2939 return state; 2940 2941 case Autorelease: 2942 if (C.isObjCGCEnabled()) 2943 return state; 2944 2945 // Update the autorelease counts. 2946 state = SendAutorelease(state, ARCountFactory, sym); 2947 V = V.autorelease(); 2948 break; 2949 2950 case StopTracking: 2951 return state->remove<RefBindings>(sym); 2952 2953 case IncRef: 2954 switch (V.getKind()) { 2955 default: 2956 llvm_unreachable("Invalid RefVal state for a retain."); 2957 case RefVal::Owned: 2958 case RefVal::NotOwned: 2959 V = V + 1; 2960 break; 2961 case RefVal::Released: 2962 // Non-GC cases are handled above. 2963 assert(C.isObjCGCEnabled()); 2964 V = (V ^ RefVal::Owned) + 1; 2965 break; 2966 } 2967 break; 2968 2969 case SelfOwn: 2970 V = V ^ RefVal::NotOwned; 2971 // Fall-through. 2972 case DecRef: 2973 case DecRefBridgedTransfered: 2974 switch (V.getKind()) { 2975 default: 2976 // case 'RefVal::Released' handled above. 2977 llvm_unreachable("Invalid RefVal state for a release."); 2978 2979 case RefVal::Owned: 2980 assert(V.getCount() > 0); 2981 if (V.getCount() == 1) 2982 V = V ^ (E == DecRefBridgedTransfered ? 2983 RefVal::NotOwned : RefVal::Released); 2984 V = V - 1; 2985 break; 2986 2987 case RefVal::NotOwned: 2988 if (V.getCount() > 0) 2989 V = V - 1; 2990 else { 2991 V = V ^ RefVal::ErrorReleaseNotOwned; 2992 hasErr = V.getKind(); 2993 } 2994 break; 2995 2996 case RefVal::Released: 2997 // Non-GC cases are handled above. 2998 assert(C.isObjCGCEnabled()); 2999 V = V ^ RefVal::ErrorUseAfterRelease; 3000 hasErr = V.getKind(); 3001 break; 3002 } 3003 break; 3004 } 3005 return state->set<RefBindings>(sym, V); 3006} 3007 3008void RetainCountChecker::processNonLeakError(ProgramStateRef St, 3009 SourceRange ErrorRange, 3010 RefVal::Kind ErrorKind, 3011 SymbolRef Sym, 3012 CheckerContext &C) const { 3013 ExplodedNode *N = C.generateSink(St); 3014 if (!N) 3015 return; 3016 3017 CFRefBug *BT; 3018 switch (ErrorKind) { 3019 default: 3020 llvm_unreachable("Unhandled error."); 3021 case RefVal::ErrorUseAfterRelease: 3022 if (!useAfterRelease) 3023 useAfterRelease.reset(new UseAfterRelease()); 3024 BT = &*useAfterRelease; 3025 break; 3026 case RefVal::ErrorReleaseNotOwned: 3027 if (!releaseNotOwned) 3028 releaseNotOwned.reset(new BadRelease()); 3029 BT = &*releaseNotOwned; 3030 break; 3031 case RefVal::ErrorDeallocGC: 3032 if (!deallocGC) 3033 deallocGC.reset(new DeallocGC()); 3034 BT = &*deallocGC; 3035 break; 3036 case RefVal::ErrorDeallocNotOwned: 3037 if (!deallocNotOwned) 3038 deallocNotOwned.reset(new DeallocNotOwned()); 3039 BT = &*deallocNotOwned; 3040 break; 3041 } 3042 3043 assert(BT); 3044 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(), 3045 C.isObjCGCEnabled(), SummaryLog, 3046 N, Sym); 3047 report->addRange(ErrorRange); 3048 C.EmitReport(report); 3049} 3050 3051//===----------------------------------------------------------------------===// 3052// Handle the return values of retain-count-related functions. 3053//===----------------------------------------------------------------------===// 3054 3055bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const { 3056 // Get the callee. We're only interested in simple C functions. 3057 ProgramStateRef state = C.getState(); 3058 const FunctionDecl *FD = C.getCalleeDecl(CE); 3059 if (!FD) 3060 return false; 3061 3062 IdentifierInfo *II = FD->getIdentifier(); 3063 if (!II) 3064 return false; 3065 3066 // For now, we're only handling the functions that return aliases of their 3067 // arguments: CFRetain and CFMakeCollectable (and their families). 3068 // Eventually we should add other functions we can model entirely, 3069 // such as CFRelease, which don't invalidate their arguments or globals. 3070 if (CE->getNumArgs() != 1) 3071 return false; 3072 3073 // Get the name of the function. 3074 StringRef FName = II->getName(); 3075 FName = FName.substr(FName.find_first_not_of('_')); 3076 3077 // See if it's one of the specific functions we know how to eval. 3078 bool canEval = false; 3079 3080 QualType ResultTy = CE->getCallReturnType(); 3081 if (ResultTy->isObjCIdType()) { 3082 // Handle: id NSMakeCollectable(CFTypeRef) 3083 canEval = II->isStr("NSMakeCollectable"); 3084 } else if (ResultTy->isPointerType()) { 3085 // Handle: (CF|CG)Retain 3086 // CFMakeCollectable 3087 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist). 3088 if (cocoa::isRefType(ResultTy, "CF", FName) || 3089 cocoa::isRefType(ResultTy, "CG", FName)) { 3090 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName); 3091 } 3092 } 3093 3094 if (!canEval) 3095 return false; 3096 3097 // Bind the return value. 3098 const LocationContext *LCtx = C.getLocationContext(); 3099 SVal RetVal = state->getSVal(CE->getArg(0), LCtx); 3100 if (RetVal.isUnknown()) { 3101 // If the receiver is unknown, conjure a return value. 3102 SValBuilder &SVB = C.getSValBuilder(); 3103 unsigned Count = C.getCurrentBlockCount(); 3104 SVal RetVal = SVB.getConjuredSymbolVal(0, CE, LCtx, ResultTy, Count); 3105 } 3106 state = state->BindExpr(CE, LCtx, RetVal, false); 3107 3108 // FIXME: This should not be necessary, but otherwise the argument seems to be 3109 // considered alive during the next statement. 3110 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) { 3111 // Save the refcount status of the argument. 3112 SymbolRef Sym = RetVal.getAsLocSymbol(); 3113 RefBindings::data_type *Binding = 0; 3114 if (Sym) 3115 Binding = state->get<RefBindings>(Sym); 3116 3117 // Invalidate the argument region. 3118 unsigned Count = C.getCurrentBlockCount(); 3119 state = state->invalidateRegions(ArgRegion, CE, Count, LCtx); 3120 3121 // Restore the refcount status of the argument. 3122 if (Binding) 3123 state = state->set<RefBindings>(Sym, *Binding); 3124 } 3125 3126 C.addTransition(state); 3127 return true; 3128} 3129 3130//===----------------------------------------------------------------------===// 3131// Handle return statements. 3132//===----------------------------------------------------------------------===// 3133 3134// Return true if the current LocationContext has no caller context. 3135static bool inTopFrame(CheckerContext &C) { 3136 const LocationContext *LC = C.getLocationContext(); 3137 return LC->getParent() == 0; 3138} 3139 3140void RetainCountChecker::checkPreStmt(const ReturnStmt *S, 3141 CheckerContext &C) const { 3142 3143 // Only adjust the reference count if this is the top-level call frame, 3144 // and not the result of inlining. In the future, we should do 3145 // better checking even for inlined calls, and see if they match 3146 // with their expected semantics (e.g., the method should return a retained 3147 // object, etc.). 3148 if (!inTopFrame(C)) 3149 return; 3150 3151 const Expr *RetE = S->getRetValue(); 3152 if (!RetE) 3153 return; 3154 3155 ProgramStateRef state = C.getState(); 3156 SymbolRef Sym = 3157 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol(); 3158 if (!Sym) 3159 return; 3160 3161 // Get the reference count binding (if any). 3162 const RefVal *T = state->get<RefBindings>(Sym); 3163 if (!T) 3164 return; 3165 3166 // Change the reference count. 3167 RefVal X = *T; 3168 3169 switch (X.getKind()) { 3170 case RefVal::Owned: { 3171 unsigned cnt = X.getCount(); 3172 assert(cnt > 0); 3173 X.setCount(cnt - 1); 3174 X = X ^ RefVal::ReturnedOwned; 3175 break; 3176 } 3177 3178 case RefVal::NotOwned: { 3179 unsigned cnt = X.getCount(); 3180 if (cnt) { 3181 X.setCount(cnt - 1); 3182 X = X ^ RefVal::ReturnedOwned; 3183 } 3184 else { 3185 X = X ^ RefVal::ReturnedNotOwned; 3186 } 3187 break; 3188 } 3189 3190 default: 3191 return; 3192 } 3193 3194 // Update the binding. 3195 state = state->set<RefBindings>(Sym, X); 3196 ExplodedNode *Pred = C.addTransition(state); 3197 3198 // At this point we have updated the state properly. 3199 // Everything after this is merely checking to see if the return value has 3200 // been over- or under-retained. 3201 3202 // Did we cache out? 3203 if (!Pred) 3204 return; 3205 3206 // Update the autorelease counts. 3207 static SimpleProgramPointTag 3208 AutoreleaseTag("RetainCountChecker : Autorelease"); 3209 GenericNodeBuilderRefCount Bd(C, &AutoreleaseTag); 3210 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C, Sym, X); 3211 3212 // Did we cache out? 3213 if (!Pred) 3214 return; 3215 3216 // Get the updated binding. 3217 T = state->get<RefBindings>(Sym); 3218 assert(T); 3219 X = *T; 3220 3221 // Consult the summary of the enclosing method. 3222 RetainSummaryManager &Summaries = getSummaryManager(C); 3223 const Decl *CD = &Pred->getCodeDecl(); 3224 3225 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) { 3226 // Unlike regular functions, /all/ ObjC methods are assumed to always 3227 // follow Cocoa retain-count conventions, not just those with special 3228 // names or attributes. 3229 const RetainSummary *Summ = Summaries.getMethodSummary(MD); 3230 RetEffect RE = Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet(); 3231 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state); 3232 } 3233 3234 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) { 3235 if (!isa<CXXMethodDecl>(FD)) 3236 if (const RetainSummary *Summ = Summaries.getSummary(FD)) 3237 checkReturnWithRetEffect(S, C, Pred, Summ->getRetEffect(), X, 3238 Sym, state); 3239 } 3240} 3241 3242void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S, 3243 CheckerContext &C, 3244 ExplodedNode *Pred, 3245 RetEffect RE, RefVal X, 3246 SymbolRef Sym, 3247 ProgramStateRef state) const { 3248 // Any leaks or other errors? 3249 if (X.isReturnedOwned() && X.getCount() == 0) { 3250 if (RE.getKind() != RetEffect::NoRet) { 3251 bool hasError = false; 3252 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) { 3253 // Things are more complicated with garbage collection. If the 3254 // returned object is suppose to be an Objective-C object, we have 3255 // a leak (as the caller expects a GC'ed object) because no 3256 // method should return ownership unless it returns a CF object. 3257 hasError = true; 3258 X = X ^ RefVal::ErrorGCLeakReturned; 3259 } 3260 else if (!RE.isOwned()) { 3261 // Either we are using GC and the returned object is a CF type 3262 // or we aren't using GC. In either case, we expect that the 3263 // enclosing method is expected to return ownership. 3264 hasError = true; 3265 X = X ^ RefVal::ErrorLeakReturned; 3266 } 3267 3268 if (hasError) { 3269 // Generate an error node. 3270 state = state->set<RefBindings>(Sym, X); 3271 3272 static SimpleProgramPointTag 3273 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak"); 3274 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag); 3275 if (N) { 3276 const LangOptions &LOpts = C.getASTContext().getLangOpts(); 3277 bool GCEnabled = C.isObjCGCEnabled(); 3278 CFRefReport *report = 3279 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled), 3280 LOpts, GCEnabled, SummaryLog, 3281 N, Sym, C); 3282 C.EmitReport(report); 3283 } 3284 } 3285 } 3286 } else if (X.isReturnedNotOwned()) { 3287 if (RE.isOwned()) { 3288 // Trying to return a not owned object to a caller expecting an 3289 // owned object. 3290 state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned); 3291 3292 static SimpleProgramPointTag 3293 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned"); 3294 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag); 3295 if (N) { 3296 if (!returnNotOwnedForOwned) 3297 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned()); 3298 3299 CFRefReport *report = 3300 new CFRefReport(*returnNotOwnedForOwned, 3301 C.getASTContext().getLangOpts(), 3302 C.isObjCGCEnabled(), SummaryLog, N, Sym); 3303 C.EmitReport(report); 3304 } 3305 } 3306 } 3307} 3308 3309//===----------------------------------------------------------------------===// 3310// Check various ways a symbol can be invalidated. 3311//===----------------------------------------------------------------------===// 3312 3313void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S, 3314 CheckerContext &C) const { 3315 // Are we storing to something that causes the value to "escape"? 3316 bool escapes = true; 3317 3318 // A value escapes in three possible cases (this may change): 3319 // 3320 // (1) we are binding to something that is not a memory region. 3321 // (2) we are binding to a memregion that does not have stack storage 3322 // (3) we are binding to a memregion with stack storage that the store 3323 // does not understand. 3324 ProgramStateRef state = C.getState(); 3325 3326 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) { 3327 escapes = !regionLoc->getRegion()->hasStackStorage(); 3328 3329 if (!escapes) { 3330 // To test (3), generate a new state with the binding added. If it is 3331 // the same state, then it escapes (since the store cannot represent 3332 // the binding). 3333 escapes = (state == (state->bindLoc(*regionLoc, val))); 3334 } 3335 } 3336 3337 // If our store can represent the binding and we aren't storing to something 3338 // that doesn't have local storage then just return and have the simulation 3339 // state continue as is. 3340 if (!escapes) 3341 return; 3342 3343 // Otherwise, find all symbols referenced by 'val' that we are tracking 3344 // and stop tracking them. 3345 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState(); 3346 C.addTransition(state); 3347} 3348 3349ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state, 3350 SVal Cond, 3351 bool Assumption) const { 3352 3353 // FIXME: We may add to the interface of evalAssume the list of symbols 3354 // whose assumptions have changed. For now we just iterate through the 3355 // bindings and check if any of the tracked symbols are NULL. This isn't 3356 // too bad since the number of symbols we will track in practice are 3357 // probably small and evalAssume is only called at branches and a few 3358 // other places. 3359 RefBindings B = state->get<RefBindings>(); 3360 3361 if (B.isEmpty()) 3362 return state; 3363 3364 bool changed = false; 3365 RefBindings::Factory &RefBFactory = state->get_context<RefBindings>(); 3366 3367 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) { 3368 // Check if the symbol is null (or equal to any constant). 3369 // If this is the case, stop tracking the symbol. 3370 if (state->getSymVal(I.getKey())) { 3371 changed = true; 3372 B = RefBFactory.remove(B, I.getKey()); 3373 } 3374 } 3375 3376 if (changed) 3377 state = state->set<RefBindings>(B); 3378 3379 return state; 3380} 3381 3382ProgramStateRef 3383RetainCountChecker::checkRegionChanges(ProgramStateRef state, 3384 const StoreManager::InvalidatedSymbols *invalidated, 3385 ArrayRef<const MemRegion *> ExplicitRegions, 3386 ArrayRef<const MemRegion *> Regions, 3387 const CallOrObjCMessage *Call) const { 3388 if (!invalidated) 3389 return state; 3390 3391 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols; 3392 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(), 3393 E = ExplicitRegions.end(); I != E; ++I) { 3394 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>()) 3395 WhitelistedSymbols.insert(SR->getSymbol()); 3396 } 3397 3398 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(), 3399 E = invalidated->end(); I!=E; ++I) { 3400 SymbolRef sym = *I; 3401 if (WhitelistedSymbols.count(sym)) 3402 continue; 3403 // Remove any existing reference-count binding. 3404 state = state->remove<RefBindings>(sym); 3405 } 3406 return state; 3407} 3408 3409//===----------------------------------------------------------------------===// 3410// Handle dead symbols and end-of-path. 3411//===----------------------------------------------------------------------===// 3412 3413std::pair<ExplodedNode *, ProgramStateRef > 3414RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state, 3415 GenericNodeBuilderRefCount Bd, 3416 ExplodedNode *Pred, 3417 CheckerContext &Ctx, 3418 SymbolRef Sym, RefVal V) const { 3419 unsigned ACnt = V.getAutoreleaseCount(); 3420 3421 // No autorelease counts? Nothing to be done. 3422 if (!ACnt) 3423 return std::make_pair(Pred, state); 3424 3425 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?"); 3426 unsigned Cnt = V.getCount(); 3427 3428 // FIXME: Handle sending 'autorelease' to already released object. 3429 3430 if (V.getKind() == RefVal::ReturnedOwned) 3431 ++Cnt; 3432 3433 if (ACnt <= Cnt) { 3434 if (ACnt == Cnt) { 3435 V.clearCounts(); 3436 if (V.getKind() == RefVal::ReturnedOwned) 3437 V = V ^ RefVal::ReturnedNotOwned; 3438 else 3439 V = V ^ RefVal::NotOwned; 3440 } else { 3441 V.setCount(Cnt - ACnt); 3442 V.setAutoreleaseCount(0); 3443 } 3444 state = state->set<RefBindings>(Sym, V); 3445 ExplodedNode *N = Bd.MakeNode(state, Pred); 3446 if (N == 0) 3447 state = 0; 3448 return std::make_pair(N, state); 3449 } 3450 3451 // Woah! More autorelease counts then retain counts left. 3452 // Emit hard error. 3453 V = V ^ RefVal::ErrorOverAutorelease; 3454 state = state->set<RefBindings>(Sym, V); 3455 3456 if (ExplodedNode *N = Bd.MakeNode(state, Pred, true)) { 3457 SmallString<128> sbuf; 3458 llvm::raw_svector_ostream os(sbuf); 3459 os << "Object over-autoreleased: object was sent -autorelease "; 3460 if (V.getAutoreleaseCount() > 1) 3461 os << V.getAutoreleaseCount() << " times "; 3462 os << "but the object has a +" << V.getCount() << " retain count"; 3463 3464 if (!overAutorelease) 3465 overAutorelease.reset(new OverAutorelease()); 3466 3467 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts(); 3468 CFRefReport *report = 3469 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false, 3470 SummaryLog, N, Sym, os.str()); 3471 Ctx.EmitReport(report); 3472 } 3473 3474 return std::make_pair((ExplodedNode *)0, (ProgramStateRef )0); 3475} 3476 3477ProgramStateRef 3478RetainCountChecker::handleSymbolDeath(ProgramStateRef state, 3479 SymbolRef sid, RefVal V, 3480 SmallVectorImpl<SymbolRef> &Leaked) const { 3481 bool hasLeak = false; 3482 if (V.isOwned()) 3483 hasLeak = true; 3484 else if (V.isNotOwned() || V.isReturnedOwned()) 3485 hasLeak = (V.getCount() > 0); 3486 3487 if (!hasLeak) 3488 return state->remove<RefBindings>(sid); 3489 3490 Leaked.push_back(sid); 3491 return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak); 3492} 3493 3494ExplodedNode * 3495RetainCountChecker::processLeaks(ProgramStateRef state, 3496 SmallVectorImpl<SymbolRef> &Leaked, 3497 GenericNodeBuilderRefCount &Builder, 3498 CheckerContext &Ctx, 3499 ExplodedNode *Pred) const { 3500 if (Leaked.empty()) 3501 return Pred; 3502 3503 // Generate an intermediate node representing the leak point. 3504 ExplodedNode *N = Builder.MakeNode(state, Pred); 3505 3506 if (N) { 3507 for (SmallVectorImpl<SymbolRef>::iterator 3508 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) { 3509 3510 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts(); 3511 bool GCEnabled = Ctx.isObjCGCEnabled(); 3512 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled) 3513 : getLeakAtReturnBug(LOpts, GCEnabled); 3514 assert(BT && "BugType not initialized."); 3515 3516 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled, 3517 SummaryLog, N, *I, Ctx); 3518 Ctx.EmitReport(report); 3519 } 3520 } 3521 3522 return N; 3523} 3524 3525void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const { 3526 ProgramStateRef state = Ctx.getState(); 3527 GenericNodeBuilderRefCount Bd(Ctx); 3528 RefBindings B = state->get<RefBindings>(); 3529 ExplodedNode *Pred = Ctx.getPredecessor(); 3530 3531 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) { 3532 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, Ctx, 3533 I->first, I->second); 3534 if (!state) 3535 return; 3536 } 3537 3538 // If the current LocationContext has a parent, don't check for leaks. 3539 // We will do that later. 3540 // FIXME: we should instead check for imblances of the retain/releases, 3541 // and suggest annotations. 3542 if (Ctx.getLocationContext()->getParent()) 3543 return; 3544 3545 B = state->get<RefBindings>(); 3546 SmallVector<SymbolRef, 10> Leaked; 3547 3548 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) 3549 state = handleSymbolDeath(state, I->first, I->second, Leaked); 3550 3551 processLeaks(state, Leaked, Bd, Ctx, Pred); 3552} 3553 3554const ProgramPointTag * 3555RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const { 3556 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym]; 3557 if (!tag) { 3558 SmallString<64> buf; 3559 llvm::raw_svector_ostream out(buf); 3560 out << "RetainCountChecker : Dead Symbol : "; 3561 sym->dumpToStream(out); 3562 tag = new SimpleProgramPointTag(out.str()); 3563 } 3564 return tag; 3565} 3566 3567void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper, 3568 CheckerContext &C) const { 3569 ExplodedNode *Pred = C.getPredecessor(); 3570 3571 ProgramStateRef state = C.getState(); 3572 RefBindings B = state->get<RefBindings>(); 3573 3574 // Update counts from autorelease pools 3575 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(), 3576 E = SymReaper.dead_end(); I != E; ++I) { 3577 SymbolRef Sym = *I; 3578 if (const RefVal *T = B.lookup(Sym)){ 3579 // Use the symbol as the tag. 3580 // FIXME: This might not be as unique as we would like. 3581 GenericNodeBuilderRefCount Bd(C, getDeadSymbolTag(Sym)); 3582 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C, 3583 Sym, *T); 3584 if (!state) 3585 return; 3586 } 3587 } 3588 3589 B = state->get<RefBindings>(); 3590 SmallVector<SymbolRef, 10> Leaked; 3591 3592 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(), 3593 E = SymReaper.dead_end(); I != E; ++I) { 3594 if (const RefVal *T = B.lookup(*I)) 3595 state = handleSymbolDeath(state, *I, *T, Leaked); 3596 } 3597 3598 { 3599 GenericNodeBuilderRefCount Bd(C, this); 3600 Pred = processLeaks(state, Leaked, Bd, C, Pred); 3601 } 3602 3603 // Did we cache out? 3604 if (!Pred) 3605 return; 3606 3607 // Now generate a new node that nukes the old bindings. 3608 RefBindings::Factory &F = state->get_context<RefBindings>(); 3609 3610 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(), 3611 E = SymReaper.dead_end(); I != E; ++I) 3612 B = F.remove(B, *I); 3613 3614 state = state->set<RefBindings>(B); 3615 C.addTransition(state, Pred); 3616} 3617 3618//===----------------------------------------------------------------------===// 3619// Debug printing of refcount bindings and autorelease pools. 3620//===----------------------------------------------------------------------===// 3621 3622static void PrintPool(raw_ostream &Out, SymbolRef Sym, 3623 ProgramStateRef State) { 3624 Out << ' '; 3625 if (Sym) 3626 Sym->dumpToStream(Out); 3627 else 3628 Out << "<pool>"; 3629 Out << ":{"; 3630 3631 // Get the contents of the pool. 3632 if (const ARCounts *Cnts = State->get<AutoreleasePoolContents>(Sym)) 3633 for (ARCounts::iterator I = Cnts->begin(), E = Cnts->end(); I != E; ++I) 3634 Out << '(' << I.getKey() << ',' << I.getData() << ')'; 3635 3636 Out << '}'; 3637} 3638 3639static bool UsesAutorelease(ProgramStateRef state) { 3640 // A state uses autorelease if it allocated an autorelease pool or if it has 3641 // objects in the caller's autorelease pool. 3642 return !state->get<AutoreleaseStack>().isEmpty() || 3643 state->get<AutoreleasePoolContents>(SymbolRef()); 3644} 3645 3646void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State, 3647 const char *NL, const char *Sep) const { 3648 3649 RefBindings B = State->get<RefBindings>(); 3650 3651 if (!B.isEmpty()) 3652 Out << Sep << NL; 3653 3654 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) { 3655 Out << I->first << " : "; 3656 I->second.print(Out); 3657 Out << NL; 3658 } 3659 3660 // Print the autorelease stack. 3661 if (UsesAutorelease(State)) { 3662 Out << Sep << NL << "AR pool stack:"; 3663 ARStack Stack = State->get<AutoreleaseStack>(); 3664 3665 PrintPool(Out, SymbolRef(), State); // Print the caller's pool. 3666 for (ARStack::iterator I = Stack.begin(), E = Stack.end(); I != E; ++I) 3667 PrintPool(Out, *I, State); 3668 3669 Out << NL; 3670 } 3671} 3672 3673//===----------------------------------------------------------------------===// 3674// Checker registration. 3675//===----------------------------------------------------------------------===// 3676 3677void ento::registerRetainCountChecker(CheckerManager &Mgr) { 3678 Mgr.registerChecker<RetainCountChecker>(); 3679} 3680 3681