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