RetainCountChecker.cpp revision 06911d4e88b1a6ca7ec3b2d8e234e679a4c09ff9
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 // Get the callee. 2603 ProgramStateRef state = C.getState(); 2604 const Expr *Callee = CE->getCallee(); 2605 SVal L = state->getSVal(Callee, C.getLocationContext()); 2606 2607 RetainSummaryManager &Summaries = getSummaryManager(C); 2608 const RetainSummary *Summ = 0; 2609 2610 // FIXME: Better support for blocks. For now we stop tracking anything 2611 // that is passed to blocks. 2612 // FIXME: Need to handle variables that are "captured" by the block. 2613 if (dyn_cast_or_null<BlockDataRegion>(L.getAsRegion())) { 2614 Summ = Summaries.getPersistentStopSummary(); 2615 } else if (const FunctionDecl *FD = L.getAsFunctionDecl()) { 2616 Summ = Summaries.getSummary(FD); 2617 } else if (const CXXMemberCallExpr *me = dyn_cast<CXXMemberCallExpr>(CE)) { 2618 if (const CXXMethodDecl *MD = me->getMethodDecl()) 2619 Summ = Summaries.getSummary(MD); 2620 } 2621 2622 if (!Summ) 2623 Summ = Summaries.getDefaultSummary(); 2624 2625 checkSummary(*Summ, CallOrObjCMessage(CE, state, C.getLocationContext()), C); 2626} 2627 2628void RetainCountChecker::checkPostStmt(const CXXConstructExpr *CE, 2629 CheckerContext &C) const { 2630 const CXXConstructorDecl *Ctor = CE->getConstructor(); 2631 if (!Ctor) 2632 return; 2633 2634 RetainSummaryManager &Summaries = getSummaryManager(C); 2635 const RetainSummary *Summ = Summaries.getSummary(Ctor); 2636 2637 // If we didn't get a summary, this constructor doesn't affect retain counts. 2638 if (!Summ) 2639 return; 2640 2641 ProgramStateRef state = C.getState(); 2642 checkSummary(*Summ, CallOrObjCMessage(CE, state, C.getLocationContext()), C); 2643} 2644 2645void RetainCountChecker::processObjCLiterals(CheckerContext &C, 2646 const Expr *Ex) const { 2647 ProgramStateRef state = C.getState(); 2648 const ExplodedNode *pred = C.getPredecessor(); 2649 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ; 2650 it != et ; ++it) { 2651 const Stmt *child = *it; 2652 SVal V = state->getSVal(child, pred->getLocationContext()); 2653 if (SymbolRef sym = V.getAsSymbol()) 2654 if (const RefVal* T = state->get<RefBindings>(sym)) { 2655 RefVal::Kind hasErr = (RefVal::Kind) 0; 2656 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C); 2657 if (hasErr) { 2658 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C); 2659 return; 2660 } 2661 } 2662 } 2663 2664 // Return the object as autoreleased. 2665 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC); 2666 if (SymbolRef sym = 2667 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) { 2668 QualType ResultTy = Ex->getType(); 2669 state = state->set<RefBindings>(sym, RefVal::makeNotOwned(RetEffect::ObjC, 2670 ResultTy)); 2671 } 2672 2673 C.addTransition(state); 2674} 2675 2676void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL, 2677 CheckerContext &C) const { 2678 // Apply the 'MayEscape' to all values. 2679 processObjCLiterals(C, AL); 2680} 2681 2682void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL, 2683 CheckerContext &C) const { 2684 // Apply the 'MayEscape' to all keys and values. 2685 processObjCLiterals(C, DL); 2686} 2687 2688void RetainCountChecker::checkPostObjCMessage(const ObjCMessage &Msg, 2689 CheckerContext &C) const { 2690 ProgramStateRef state = C.getState(); 2691 2692 RetainSummaryManager &Summaries = getSummaryManager(C); 2693 2694 const RetainSummary *Summ; 2695 if (Msg.isInstanceMessage()) { 2696 const LocationContext *LC = C.getLocationContext(); 2697 Summ = Summaries.getInstanceMethodSummary(Msg, state, LC); 2698 } else { 2699 Summ = Summaries.getClassMethodSummary(Msg); 2700 } 2701 2702 // If we didn't get a summary, this message doesn't affect retain counts. 2703 if (!Summ) 2704 return; 2705 2706 checkSummary(*Summ, CallOrObjCMessage(Msg, state, C.getLocationContext()), C); 2707} 2708 2709/// GetReturnType - Used to get the return type of a message expression or 2710/// function call with the intention of affixing that type to a tracked symbol. 2711/// While the the return type can be queried directly from RetEx, when 2712/// invoking class methods we augment to the return type to be that of 2713/// a pointer to the class (as opposed it just being id). 2714// FIXME: We may be able to do this with related result types instead. 2715// This function is probably overestimating. 2716static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) { 2717 QualType RetTy = RetE->getType(); 2718 // If RetE is not a message expression just return its type. 2719 // If RetE is a message expression, return its types if it is something 2720 /// more specific than id. 2721 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE)) 2722 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>()) 2723 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() || 2724 PT->isObjCClassType()) { 2725 // At this point we know the return type of the message expression is 2726 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this 2727 // is a call to a class method whose type we can resolve. In such 2728 // cases, promote the return type to XXX* (where XXX is the class). 2729 const ObjCInterfaceDecl *D = ME->getReceiverInterface(); 2730 return !D ? RetTy : 2731 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D)); 2732 } 2733 2734 return RetTy; 2735} 2736 2737void RetainCountChecker::checkSummary(const RetainSummary &Summ, 2738 const CallOrObjCMessage &CallOrMsg, 2739 CheckerContext &C) const { 2740 ProgramStateRef state = C.getState(); 2741 2742 // Evaluate the effect of the arguments. 2743 RefVal::Kind hasErr = (RefVal::Kind) 0; 2744 SourceRange ErrorRange; 2745 SymbolRef ErrorSym = 0; 2746 2747 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) { 2748 SVal V = CallOrMsg.getArgSVal(idx); 2749 2750 if (SymbolRef Sym = V.getAsLocSymbol()) { 2751 if (RefBindings::data_type *T = state->get<RefBindings>(Sym)) { 2752 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C); 2753 if (hasErr) { 2754 ErrorRange = CallOrMsg.getArgSourceRange(idx); 2755 ErrorSym = Sym; 2756 break; 2757 } 2758 } 2759 } 2760 } 2761 2762 // Evaluate the effect on the message receiver. 2763 bool ReceiverIsTracked = false; 2764 if (!hasErr && CallOrMsg.isObjCMessage()) { 2765 const LocationContext *LC = C.getLocationContext(); 2766 SVal Receiver = CallOrMsg.getInstanceMessageReceiver(LC); 2767 if (SymbolRef Sym = Receiver.getAsLocSymbol()) { 2768 if (const RefVal *T = state->get<RefBindings>(Sym)) { 2769 ReceiverIsTracked = true; 2770 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(), 2771 hasErr, C); 2772 if (hasErr) { 2773 ErrorRange = CallOrMsg.getReceiverSourceRange(); 2774 ErrorSym = Sym; 2775 } 2776 } 2777 } 2778 } 2779 2780 // Process any errors. 2781 if (hasErr) { 2782 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C); 2783 return; 2784 } 2785 2786 // Consult the summary for the return value. 2787 RetEffect RE = Summ.getRetEffect(); 2788 2789 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) { 2790 if (ReceiverIsTracked) 2791 RE = getSummaryManager(C).getObjAllocRetEffect(); 2792 else 2793 RE = RetEffect::MakeNoRet(); 2794 } 2795 2796 switch (RE.getKind()) { 2797 default: 2798 llvm_unreachable("Unhandled RetEffect."); 2799 2800 case RetEffect::NoRet: 2801 // No work necessary. 2802 break; 2803 2804 case RetEffect::OwnedAllocatedSymbol: 2805 case RetEffect::OwnedSymbol: { 2806 SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(), 2807 C.getLocationContext()).getAsSymbol(); 2808 if (!Sym) 2809 break; 2810 2811 // Use the result type from callOrMsg as it automatically adjusts 2812 // for methods/functions that return references. 2813 QualType ResultTy = CallOrMsg.getResultType(C.getASTContext()); 2814 state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(), 2815 ResultTy)); 2816 2817 // FIXME: Add a flag to the checker where allocations are assumed to 2818 // *not* fail. (The code below is out-of-date, though.) 2819#if 0 2820 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) { 2821 bool isFeasible; 2822 state = state.assume(loc::SymbolVal(Sym), true, isFeasible); 2823 assert(isFeasible && "Cannot assume fresh symbol is non-null."); 2824 } 2825#endif 2826 2827 break; 2828 } 2829 2830 case RetEffect::GCNotOwnedSymbol: 2831 case RetEffect::ARCNotOwnedSymbol: 2832 case RetEffect::NotOwnedSymbol: { 2833 const Expr *Ex = CallOrMsg.getOriginExpr(); 2834 SymbolRef Sym = state->getSVal(Ex, C.getLocationContext()).getAsSymbol(); 2835 if (!Sym) 2836 break; 2837 2838 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *. 2839 QualType ResultTy = GetReturnType(Ex, C.getASTContext()); 2840 state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(), 2841 ResultTy)); 2842 break; 2843 } 2844 } 2845 2846 // This check is actually necessary; otherwise the statement builder thinks 2847 // we've hit a previously-found path. 2848 // Normally addTransition takes care of this, but we want the node pointer. 2849 ExplodedNode *NewNode; 2850 if (state == C.getState()) { 2851 NewNode = C.getPredecessor(); 2852 } else { 2853 NewNode = C.addTransition(state); 2854 } 2855 2856 // Annotate the node with summary we used. 2857 if (NewNode) { 2858 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary. 2859 if (ShouldResetSummaryLog) { 2860 SummaryLog.clear(); 2861 ShouldResetSummaryLog = false; 2862 } 2863 SummaryLog[NewNode] = &Summ; 2864 } 2865} 2866 2867 2868ProgramStateRef 2869RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym, 2870 RefVal V, ArgEffect E, RefVal::Kind &hasErr, 2871 CheckerContext &C) const { 2872 // In GC mode [... release] and [... retain] do nothing. 2873 // In ARC mode they shouldn't exist at all, but we just ignore them. 2874 bool IgnoreRetainMsg = C.isObjCGCEnabled(); 2875 if (!IgnoreRetainMsg) 2876 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount; 2877 2878 switch (E) { 2879 default: break; 2880 case IncRefMsg: E = IgnoreRetainMsg ? DoNothing : IncRef; break; 2881 case DecRefMsg: E = IgnoreRetainMsg ? DoNothing : DecRef; break; 2882 case MakeCollectable: E = C.isObjCGCEnabled() ? DecRef : DoNothing; break; 2883 case NewAutoreleasePool: E = C.isObjCGCEnabled() ? DoNothing : 2884 NewAutoreleasePool; break; 2885 } 2886 2887 // Handle all use-after-releases. 2888 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) { 2889 V = V ^ RefVal::ErrorUseAfterRelease; 2890 hasErr = V.getKind(); 2891 return state->set<RefBindings>(sym, V); 2892 } 2893 2894 switch (E) { 2895 case DecRefMsg: 2896 case IncRefMsg: 2897 case MakeCollectable: 2898 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted"); 2899 2900 case Dealloc: 2901 // Any use of -dealloc in GC is *bad*. 2902 if (C.isObjCGCEnabled()) { 2903 V = V ^ RefVal::ErrorDeallocGC; 2904 hasErr = V.getKind(); 2905 break; 2906 } 2907 2908 switch (V.getKind()) { 2909 default: 2910 llvm_unreachable("Invalid RefVal state for an explicit dealloc."); 2911 case RefVal::Owned: 2912 // The object immediately transitions to the released state. 2913 V = V ^ RefVal::Released; 2914 V.clearCounts(); 2915 return state->set<RefBindings>(sym, V); 2916 case RefVal::NotOwned: 2917 V = V ^ RefVal::ErrorDeallocNotOwned; 2918 hasErr = V.getKind(); 2919 break; 2920 } 2921 break; 2922 2923 case NewAutoreleasePool: 2924 assert(!C.isObjCGCEnabled()); 2925 return state->add<AutoreleaseStack>(sym); 2926 2927 case MayEscape: 2928 if (V.getKind() == RefVal::Owned) { 2929 V = V ^ RefVal::NotOwned; 2930 break; 2931 } 2932 2933 // Fall-through. 2934 2935 case DoNothing: 2936 return state; 2937 2938 case Autorelease: 2939 if (C.isObjCGCEnabled()) 2940 return state; 2941 2942 // Update the autorelease counts. 2943 state = SendAutorelease(state, ARCountFactory, sym); 2944 V = V.autorelease(); 2945 break; 2946 2947 case StopTracking: 2948 return state->remove<RefBindings>(sym); 2949 2950 case IncRef: 2951 switch (V.getKind()) { 2952 default: 2953 llvm_unreachable("Invalid RefVal state for a retain."); 2954 case RefVal::Owned: 2955 case RefVal::NotOwned: 2956 V = V + 1; 2957 break; 2958 case RefVal::Released: 2959 // Non-GC cases are handled above. 2960 assert(C.isObjCGCEnabled()); 2961 V = (V ^ RefVal::Owned) + 1; 2962 break; 2963 } 2964 break; 2965 2966 case SelfOwn: 2967 V = V ^ RefVal::NotOwned; 2968 // Fall-through. 2969 case DecRef: 2970 case DecRefBridgedTransfered: 2971 switch (V.getKind()) { 2972 default: 2973 // case 'RefVal::Released' handled above. 2974 llvm_unreachable("Invalid RefVal state for a release."); 2975 2976 case RefVal::Owned: 2977 assert(V.getCount() > 0); 2978 if (V.getCount() == 1) 2979 V = V ^ (E == DecRefBridgedTransfered ? 2980 RefVal::NotOwned : RefVal::Released); 2981 V = V - 1; 2982 break; 2983 2984 case RefVal::NotOwned: 2985 if (V.getCount() > 0) 2986 V = V - 1; 2987 else { 2988 V = V ^ RefVal::ErrorReleaseNotOwned; 2989 hasErr = V.getKind(); 2990 } 2991 break; 2992 2993 case RefVal::Released: 2994 // Non-GC cases are handled above. 2995 assert(C.isObjCGCEnabled()); 2996 V = V ^ RefVal::ErrorUseAfterRelease; 2997 hasErr = V.getKind(); 2998 break; 2999 } 3000 break; 3001 } 3002 return state->set<RefBindings>(sym, V); 3003} 3004 3005void RetainCountChecker::processNonLeakError(ProgramStateRef St, 3006 SourceRange ErrorRange, 3007 RefVal::Kind ErrorKind, 3008 SymbolRef Sym, 3009 CheckerContext &C) const { 3010 ExplodedNode *N = C.generateSink(St); 3011 if (!N) 3012 return; 3013 3014 CFRefBug *BT; 3015 switch (ErrorKind) { 3016 default: 3017 llvm_unreachable("Unhandled error."); 3018 case RefVal::ErrorUseAfterRelease: 3019 if (!useAfterRelease) 3020 useAfterRelease.reset(new UseAfterRelease()); 3021 BT = &*useAfterRelease; 3022 break; 3023 case RefVal::ErrorReleaseNotOwned: 3024 if (!releaseNotOwned) 3025 releaseNotOwned.reset(new BadRelease()); 3026 BT = &*releaseNotOwned; 3027 break; 3028 case RefVal::ErrorDeallocGC: 3029 if (!deallocGC) 3030 deallocGC.reset(new DeallocGC()); 3031 BT = &*deallocGC; 3032 break; 3033 case RefVal::ErrorDeallocNotOwned: 3034 if (!deallocNotOwned) 3035 deallocNotOwned.reset(new DeallocNotOwned()); 3036 BT = &*deallocNotOwned; 3037 break; 3038 } 3039 3040 assert(BT); 3041 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(), 3042 C.isObjCGCEnabled(), SummaryLog, 3043 N, Sym); 3044 report->addRange(ErrorRange); 3045 C.EmitReport(report); 3046} 3047 3048//===----------------------------------------------------------------------===// 3049// Handle the return values of retain-count-related functions. 3050//===----------------------------------------------------------------------===// 3051 3052bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const { 3053 // Get the callee. We're only interested in simple C functions. 3054 ProgramStateRef state = C.getState(); 3055 const FunctionDecl *FD = C.getCalleeDecl(CE); 3056 if (!FD) 3057 return false; 3058 3059 IdentifierInfo *II = FD->getIdentifier(); 3060 if (!II) 3061 return false; 3062 3063 // For now, we're only handling the functions that return aliases of their 3064 // arguments: CFRetain and CFMakeCollectable (and their families). 3065 // Eventually we should add other functions we can model entirely, 3066 // such as CFRelease, which don't invalidate their arguments or globals. 3067 if (CE->getNumArgs() != 1) 3068 return false; 3069 3070 // Get the name of the function. 3071 StringRef FName = II->getName(); 3072 FName = FName.substr(FName.find_first_not_of('_')); 3073 3074 // See if it's one of the specific functions we know how to eval. 3075 bool canEval = false; 3076 3077 QualType ResultTy = CE->getCallReturnType(); 3078 if (ResultTy->isObjCIdType()) { 3079 // Handle: id NSMakeCollectable(CFTypeRef) 3080 canEval = II->isStr("NSMakeCollectable"); 3081 } else if (ResultTy->isPointerType()) { 3082 // Handle: (CF|CG)Retain 3083 // CFMakeCollectable 3084 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist). 3085 if (cocoa::isRefType(ResultTy, "CF", FName) || 3086 cocoa::isRefType(ResultTy, "CG", FName)) { 3087 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName); 3088 } 3089 } 3090 3091 if (!canEval) 3092 return false; 3093 3094 // Bind the return value. 3095 const LocationContext *LCtx = C.getLocationContext(); 3096 SVal RetVal = state->getSVal(CE->getArg(0), LCtx); 3097 if (RetVal.isUnknown()) { 3098 // If the receiver is unknown, conjure a return value. 3099 SValBuilder &SVB = C.getSValBuilder(); 3100 unsigned Count = C.getCurrentBlockCount(); 3101 SVal RetVal = SVB.getConjuredSymbolVal(0, CE, LCtx, ResultTy, Count); 3102 } 3103 state = state->BindExpr(CE, LCtx, RetVal, false); 3104 3105 // FIXME: This should not be necessary, but otherwise the argument seems to be 3106 // considered alive during the next statement. 3107 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) { 3108 // Save the refcount status of the argument. 3109 SymbolRef Sym = RetVal.getAsLocSymbol(); 3110 RefBindings::data_type *Binding = 0; 3111 if (Sym) 3112 Binding = state->get<RefBindings>(Sym); 3113 3114 // Invalidate the argument region. 3115 unsigned Count = C.getCurrentBlockCount(); 3116 state = state->invalidateRegions(ArgRegion, CE, Count, LCtx); 3117 3118 // Restore the refcount status of the argument. 3119 if (Binding) 3120 state = state->set<RefBindings>(Sym, *Binding); 3121 } 3122 3123 C.addTransition(state); 3124 return true; 3125} 3126 3127//===----------------------------------------------------------------------===// 3128// Handle return statements. 3129//===----------------------------------------------------------------------===// 3130 3131// Return true if the current LocationContext has no caller context. 3132static bool inTopFrame(CheckerContext &C) { 3133 const LocationContext *LC = C.getLocationContext(); 3134 return LC->getParent() == 0; 3135} 3136 3137void RetainCountChecker::checkPreStmt(const ReturnStmt *S, 3138 CheckerContext &C) const { 3139 3140 // Only adjust the reference count if this is the top-level call frame, 3141 // and not the result of inlining. In the future, we should do 3142 // better checking even for inlined calls, and see if they match 3143 // with their expected semantics (e.g., the method should return a retained 3144 // object, etc.). 3145 if (!inTopFrame(C)) 3146 return; 3147 3148 const Expr *RetE = S->getRetValue(); 3149 if (!RetE) 3150 return; 3151 3152 ProgramStateRef state = C.getState(); 3153 SymbolRef Sym = 3154 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol(); 3155 if (!Sym) 3156 return; 3157 3158 // Get the reference count binding (if any). 3159 const RefVal *T = state->get<RefBindings>(Sym); 3160 if (!T) 3161 return; 3162 3163 // Change the reference count. 3164 RefVal X = *T; 3165 3166 switch (X.getKind()) { 3167 case RefVal::Owned: { 3168 unsigned cnt = X.getCount(); 3169 assert(cnt > 0); 3170 X.setCount(cnt - 1); 3171 X = X ^ RefVal::ReturnedOwned; 3172 break; 3173 } 3174 3175 case RefVal::NotOwned: { 3176 unsigned cnt = X.getCount(); 3177 if (cnt) { 3178 X.setCount(cnt - 1); 3179 X = X ^ RefVal::ReturnedOwned; 3180 } 3181 else { 3182 X = X ^ RefVal::ReturnedNotOwned; 3183 } 3184 break; 3185 } 3186 3187 default: 3188 return; 3189 } 3190 3191 // Update the binding. 3192 state = state->set<RefBindings>(Sym, X); 3193 ExplodedNode *Pred = C.addTransition(state); 3194 3195 // At this point we have updated the state properly. 3196 // Everything after this is merely checking to see if the return value has 3197 // been over- or under-retained. 3198 3199 // Did we cache out? 3200 if (!Pred) 3201 return; 3202 3203 // Update the autorelease counts. 3204 static SimpleProgramPointTag 3205 AutoreleaseTag("RetainCountChecker : Autorelease"); 3206 GenericNodeBuilderRefCount Bd(C, &AutoreleaseTag); 3207 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C, Sym, X); 3208 3209 // Did we cache out? 3210 if (!Pred) 3211 return; 3212 3213 // Get the updated binding. 3214 T = state->get<RefBindings>(Sym); 3215 assert(T); 3216 X = *T; 3217 3218 // Consult the summary of the enclosing method. 3219 RetainSummaryManager &Summaries = getSummaryManager(C); 3220 const Decl *CD = &Pred->getCodeDecl(); 3221 3222 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) { 3223 // Unlike regular functions, /all/ ObjC methods are assumed to always 3224 // follow Cocoa retain-count conventions, not just those with special 3225 // names or attributes. 3226 const RetainSummary *Summ = Summaries.getMethodSummary(MD); 3227 RetEffect RE = Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet(); 3228 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state); 3229 } 3230 3231 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) { 3232 if (!isa<CXXMethodDecl>(FD)) 3233 if (const RetainSummary *Summ = Summaries.getSummary(FD)) 3234 checkReturnWithRetEffect(S, C, Pred, Summ->getRetEffect(), X, 3235 Sym, state); 3236 } 3237} 3238 3239void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S, 3240 CheckerContext &C, 3241 ExplodedNode *Pred, 3242 RetEffect RE, RefVal X, 3243 SymbolRef Sym, 3244 ProgramStateRef state) const { 3245 // Any leaks or other errors? 3246 if (X.isReturnedOwned() && X.getCount() == 0) { 3247 if (RE.getKind() != RetEffect::NoRet) { 3248 bool hasError = false; 3249 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) { 3250 // Things are more complicated with garbage collection. If the 3251 // returned object is suppose to be an Objective-C object, we have 3252 // a leak (as the caller expects a GC'ed object) because no 3253 // method should return ownership unless it returns a CF object. 3254 hasError = true; 3255 X = X ^ RefVal::ErrorGCLeakReturned; 3256 } 3257 else if (!RE.isOwned()) { 3258 // Either we are using GC and the returned object is a CF type 3259 // or we aren't using GC. In either case, we expect that the 3260 // enclosing method is expected to return ownership. 3261 hasError = true; 3262 X = X ^ RefVal::ErrorLeakReturned; 3263 } 3264 3265 if (hasError) { 3266 // Generate an error node. 3267 state = state->set<RefBindings>(Sym, X); 3268 3269 static SimpleProgramPointTag 3270 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak"); 3271 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag); 3272 if (N) { 3273 const LangOptions &LOpts = C.getASTContext().getLangOpts(); 3274 bool GCEnabled = C.isObjCGCEnabled(); 3275 CFRefReport *report = 3276 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled), 3277 LOpts, GCEnabled, SummaryLog, 3278 N, Sym, C); 3279 C.EmitReport(report); 3280 } 3281 } 3282 } 3283 } else if (X.isReturnedNotOwned()) { 3284 if (RE.isOwned()) { 3285 // Trying to return a not owned object to a caller expecting an 3286 // owned object. 3287 state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned); 3288 3289 static SimpleProgramPointTag 3290 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned"); 3291 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag); 3292 if (N) { 3293 if (!returnNotOwnedForOwned) 3294 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned()); 3295 3296 CFRefReport *report = 3297 new CFRefReport(*returnNotOwnedForOwned, 3298 C.getASTContext().getLangOpts(), 3299 C.isObjCGCEnabled(), SummaryLog, N, Sym); 3300 C.EmitReport(report); 3301 } 3302 } 3303 } 3304} 3305 3306//===----------------------------------------------------------------------===// 3307// Check various ways a symbol can be invalidated. 3308//===----------------------------------------------------------------------===// 3309 3310void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S, 3311 CheckerContext &C) const { 3312 // Are we storing to something that causes the value to "escape"? 3313 bool escapes = true; 3314 3315 // A value escapes in three possible cases (this may change): 3316 // 3317 // (1) we are binding to something that is not a memory region. 3318 // (2) we are binding to a memregion that does not have stack storage 3319 // (3) we are binding to a memregion with stack storage that the store 3320 // does not understand. 3321 ProgramStateRef state = C.getState(); 3322 3323 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) { 3324 escapes = !regionLoc->getRegion()->hasStackStorage(); 3325 3326 if (!escapes) { 3327 // To test (3), generate a new state with the binding added. If it is 3328 // the same state, then it escapes (since the store cannot represent 3329 // the binding). 3330 escapes = (state == (state->bindLoc(*regionLoc, val))); 3331 } 3332 } 3333 3334 // If our store can represent the binding and we aren't storing to something 3335 // that doesn't have local storage then just return and have the simulation 3336 // state continue as is. 3337 if (!escapes) 3338 return; 3339 3340 // Otherwise, find all symbols referenced by 'val' that we are tracking 3341 // and stop tracking them. 3342 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState(); 3343 C.addTransition(state); 3344} 3345 3346ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state, 3347 SVal Cond, 3348 bool Assumption) const { 3349 3350 // FIXME: We may add to the interface of evalAssume the list of symbols 3351 // whose assumptions have changed. For now we just iterate through the 3352 // bindings and check if any of the tracked symbols are NULL. This isn't 3353 // too bad since the number of symbols we will track in practice are 3354 // probably small and evalAssume is only called at branches and a few 3355 // other places. 3356 RefBindings B = state->get<RefBindings>(); 3357 3358 if (B.isEmpty()) 3359 return state; 3360 3361 bool changed = false; 3362 RefBindings::Factory &RefBFactory = state->get_context<RefBindings>(); 3363 3364 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) { 3365 // Check if the symbol is null (or equal to any constant). 3366 // If this is the case, stop tracking the symbol. 3367 if (state->getSymVal(I.getKey())) { 3368 changed = true; 3369 B = RefBFactory.remove(B, I.getKey()); 3370 } 3371 } 3372 3373 if (changed) 3374 state = state->set<RefBindings>(B); 3375 3376 return state; 3377} 3378 3379ProgramStateRef 3380RetainCountChecker::checkRegionChanges(ProgramStateRef state, 3381 const StoreManager::InvalidatedSymbols *invalidated, 3382 ArrayRef<const MemRegion *> ExplicitRegions, 3383 ArrayRef<const MemRegion *> Regions, 3384 const CallOrObjCMessage *Call) const { 3385 if (!invalidated) 3386 return state; 3387 3388 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols; 3389 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(), 3390 E = ExplicitRegions.end(); I != E; ++I) { 3391 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>()) 3392 WhitelistedSymbols.insert(SR->getSymbol()); 3393 } 3394 3395 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(), 3396 E = invalidated->end(); I!=E; ++I) { 3397 SymbolRef sym = *I; 3398 if (WhitelistedSymbols.count(sym)) 3399 continue; 3400 // Remove any existing reference-count binding. 3401 state = state->remove<RefBindings>(sym); 3402 } 3403 return state; 3404} 3405 3406//===----------------------------------------------------------------------===// 3407// Handle dead symbols and end-of-path. 3408//===----------------------------------------------------------------------===// 3409 3410std::pair<ExplodedNode *, ProgramStateRef > 3411RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state, 3412 GenericNodeBuilderRefCount Bd, 3413 ExplodedNode *Pred, 3414 CheckerContext &Ctx, 3415 SymbolRef Sym, RefVal V) const { 3416 unsigned ACnt = V.getAutoreleaseCount(); 3417 3418 // No autorelease counts? Nothing to be done. 3419 if (!ACnt) 3420 return std::make_pair(Pred, state); 3421 3422 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?"); 3423 unsigned Cnt = V.getCount(); 3424 3425 // FIXME: Handle sending 'autorelease' to already released object. 3426 3427 if (V.getKind() == RefVal::ReturnedOwned) 3428 ++Cnt; 3429 3430 if (ACnt <= Cnt) { 3431 if (ACnt == Cnt) { 3432 V.clearCounts(); 3433 if (V.getKind() == RefVal::ReturnedOwned) 3434 V = V ^ RefVal::ReturnedNotOwned; 3435 else 3436 V = V ^ RefVal::NotOwned; 3437 } else { 3438 V.setCount(Cnt - ACnt); 3439 V.setAutoreleaseCount(0); 3440 } 3441 state = state->set<RefBindings>(Sym, V); 3442 ExplodedNode *N = Bd.MakeNode(state, Pred); 3443 if (N == 0) 3444 state = 0; 3445 return std::make_pair(N, state); 3446 } 3447 3448 // Woah! More autorelease counts then retain counts left. 3449 // Emit hard error. 3450 V = V ^ RefVal::ErrorOverAutorelease; 3451 state = state->set<RefBindings>(Sym, V); 3452 3453 if (ExplodedNode *N = Bd.MakeNode(state, Pred, true)) { 3454 SmallString<128> sbuf; 3455 llvm::raw_svector_ostream os(sbuf); 3456 os << "Object over-autoreleased: object was sent -autorelease "; 3457 if (V.getAutoreleaseCount() > 1) 3458 os << V.getAutoreleaseCount() << " times "; 3459 os << "but the object has a +" << V.getCount() << " retain count"; 3460 3461 if (!overAutorelease) 3462 overAutorelease.reset(new OverAutorelease()); 3463 3464 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts(); 3465 CFRefReport *report = 3466 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false, 3467 SummaryLog, N, Sym, os.str()); 3468 Ctx.EmitReport(report); 3469 } 3470 3471 return std::make_pair((ExplodedNode *)0, (ProgramStateRef )0); 3472} 3473 3474ProgramStateRef 3475RetainCountChecker::handleSymbolDeath(ProgramStateRef state, 3476 SymbolRef sid, RefVal V, 3477 SmallVectorImpl<SymbolRef> &Leaked) const { 3478 bool hasLeak = false; 3479 if (V.isOwned()) 3480 hasLeak = true; 3481 else if (V.isNotOwned() || V.isReturnedOwned()) 3482 hasLeak = (V.getCount() > 0); 3483 3484 if (!hasLeak) 3485 return state->remove<RefBindings>(sid); 3486 3487 Leaked.push_back(sid); 3488 return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak); 3489} 3490 3491ExplodedNode * 3492RetainCountChecker::processLeaks(ProgramStateRef state, 3493 SmallVectorImpl<SymbolRef> &Leaked, 3494 GenericNodeBuilderRefCount &Builder, 3495 CheckerContext &Ctx, 3496 ExplodedNode *Pred) const { 3497 if (Leaked.empty()) 3498 return Pred; 3499 3500 // Generate an intermediate node representing the leak point. 3501 ExplodedNode *N = Builder.MakeNode(state, Pred); 3502 3503 if (N) { 3504 for (SmallVectorImpl<SymbolRef>::iterator 3505 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) { 3506 3507 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts(); 3508 bool GCEnabled = Ctx.isObjCGCEnabled(); 3509 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled) 3510 : getLeakAtReturnBug(LOpts, GCEnabled); 3511 assert(BT && "BugType not initialized."); 3512 3513 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled, 3514 SummaryLog, N, *I, Ctx); 3515 Ctx.EmitReport(report); 3516 } 3517 } 3518 3519 return N; 3520} 3521 3522void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const { 3523 ProgramStateRef state = Ctx.getState(); 3524 GenericNodeBuilderRefCount Bd(Ctx); 3525 RefBindings B = state->get<RefBindings>(); 3526 ExplodedNode *Pred = Ctx.getPredecessor(); 3527 3528 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) { 3529 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, Ctx, 3530 I->first, I->second); 3531 if (!state) 3532 return; 3533 } 3534 3535 // If the current LocationContext has a parent, don't check for leaks. 3536 // We will do that later. 3537 // FIXME: we should instead check for imblances of the retain/releases, 3538 // and suggest annotations. 3539 if (Ctx.getLocationContext()->getParent()) 3540 return; 3541 3542 B = state->get<RefBindings>(); 3543 SmallVector<SymbolRef, 10> Leaked; 3544 3545 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) 3546 state = handleSymbolDeath(state, I->first, I->second, Leaked); 3547 3548 processLeaks(state, Leaked, Bd, Ctx, Pred); 3549} 3550 3551const ProgramPointTag * 3552RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const { 3553 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym]; 3554 if (!tag) { 3555 SmallString<64> buf; 3556 llvm::raw_svector_ostream out(buf); 3557 out << "RetainCountChecker : Dead Symbol : "; 3558 sym->dumpToStream(out); 3559 tag = new SimpleProgramPointTag(out.str()); 3560 } 3561 return tag; 3562} 3563 3564void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper, 3565 CheckerContext &C) const { 3566 ExplodedNode *Pred = C.getPredecessor(); 3567 3568 ProgramStateRef state = C.getState(); 3569 RefBindings B = state->get<RefBindings>(); 3570 3571 // Update counts from autorelease pools 3572 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(), 3573 E = SymReaper.dead_end(); I != E; ++I) { 3574 SymbolRef Sym = *I; 3575 if (const RefVal *T = B.lookup(Sym)){ 3576 // Use the symbol as the tag. 3577 // FIXME: This might not be as unique as we would like. 3578 GenericNodeBuilderRefCount Bd(C, getDeadSymbolTag(Sym)); 3579 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C, 3580 Sym, *T); 3581 if (!state) 3582 return; 3583 } 3584 } 3585 3586 B = state->get<RefBindings>(); 3587 SmallVector<SymbolRef, 10> Leaked; 3588 3589 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(), 3590 E = SymReaper.dead_end(); I != E; ++I) { 3591 if (const RefVal *T = B.lookup(*I)) 3592 state = handleSymbolDeath(state, *I, *T, Leaked); 3593 } 3594 3595 { 3596 GenericNodeBuilderRefCount Bd(C, this); 3597 Pred = processLeaks(state, Leaked, Bd, C, Pred); 3598 } 3599 3600 // Did we cache out? 3601 if (!Pred) 3602 return; 3603 3604 // Now generate a new node that nukes the old bindings. 3605 RefBindings::Factory &F = state->get_context<RefBindings>(); 3606 3607 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(), 3608 E = SymReaper.dead_end(); I != E; ++I) 3609 B = F.remove(B, *I); 3610 3611 state = state->set<RefBindings>(B); 3612 C.addTransition(state, Pred); 3613} 3614 3615//===----------------------------------------------------------------------===// 3616// Debug printing of refcount bindings and autorelease pools. 3617//===----------------------------------------------------------------------===// 3618 3619static void PrintPool(raw_ostream &Out, SymbolRef Sym, 3620 ProgramStateRef State) { 3621 Out << ' '; 3622 if (Sym) 3623 Sym->dumpToStream(Out); 3624 else 3625 Out << "<pool>"; 3626 Out << ":{"; 3627 3628 // Get the contents of the pool. 3629 if (const ARCounts *Cnts = State->get<AutoreleasePoolContents>(Sym)) 3630 for (ARCounts::iterator I = Cnts->begin(), E = Cnts->end(); I != E; ++I) 3631 Out << '(' << I.getKey() << ',' << I.getData() << ')'; 3632 3633 Out << '}'; 3634} 3635 3636static bool UsesAutorelease(ProgramStateRef state) { 3637 // A state uses autorelease if it allocated an autorelease pool or if it has 3638 // objects in the caller's autorelease pool. 3639 return !state->get<AutoreleaseStack>().isEmpty() || 3640 state->get<AutoreleasePoolContents>(SymbolRef()); 3641} 3642 3643void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State, 3644 const char *NL, const char *Sep) const { 3645 3646 RefBindings B = State->get<RefBindings>(); 3647 3648 if (!B.isEmpty()) 3649 Out << Sep << NL; 3650 3651 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) { 3652 Out << I->first << " : "; 3653 I->second.print(Out); 3654 Out << NL; 3655 } 3656 3657 // Print the autorelease stack. 3658 if (UsesAutorelease(State)) { 3659 Out << Sep << NL << "AR pool stack:"; 3660 ARStack Stack = State->get<AutoreleaseStack>(); 3661 3662 PrintPool(Out, SymbolRef(), State); // Print the caller's pool. 3663 for (ARStack::iterator I = Stack.begin(), E = Stack.end(); I != E; ++I) 3664 PrintPool(Out, *I, State); 3665 3666 Out << NL; 3667 } 3668} 3669 3670//===----------------------------------------------------------------------===// 3671// Checker registration. 3672//===----------------------------------------------------------------------===// 3673 3674void ento::registerRetainCountChecker(CheckerManager &Mgr) { 3675 Mgr.registerChecker<RetainCountChecker>(); 3676} 3677 3678