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