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