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