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