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