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