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