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