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