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