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