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