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