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