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