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