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