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