blob: 58642bf2a775a4f4dd918c8527f9a09c505066cc [file] [log] [blame]
Chris Lattner7a513132008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenekea6507f2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Gabor Greif3a8edd82008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenekea6507f2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekb0f87c42008-04-30 23:47:44 +000015#include "clang/Basic/LangOptions.h"
Ted Kremenek1097b4c2008-05-01 23:13:35 +000016#include "clang/Basic/SourceManager.h"
Ted Kremeneke68c0fc2009-02-14 01:43:44 +000017#include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h"
Ted Kremenek87aab6c2008-08-17 03:20:02 +000018#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenekc27815c2008-03-31 18:26:32 +000019#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenekea6507f2008-03-06 00:08:09 +000020#include "clang/Analysis/LocalCheckers.h"
Ted Kremenekce8e8812008-04-09 01:10:13 +000021#include "clang/Analysis/PathDiagnostic.h"
22#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek4e9d4b52009-02-14 03:16:10 +000023#include "clang/Analysis/PathSensitive/SymbolManager.h"
Ted Kremenek1642bda2009-06-26 00:05:51 +000024#include "clang/Analysis/PathSensitive/GRTransferFuncs.h"
Mike Stump11289f42009-09-09 15:08:12 +000025#include "clang/AST/DeclObjC.h"
Ted Kremenek819e9b62008-03-11 06:39:11 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/ImmutableMap.h"
Ted Kremenek0747e7e2008-10-21 15:53:15 +000029#include "llvm/ADT/ImmutableList.h"
Ted Kremenekb6cbf282008-05-07 18:36:45 +000030#include "llvm/ADT/StringExtras.h"
Ted Kremenekce8e8812008-04-09 01:10:13 +000031#include "llvm/Support/Compiler.h"
Ted Kremenekc812b232008-05-16 18:33:44 +000032#include "llvm/ADT/STLExtras.h"
Ted Kremenek9551ab62008-08-12 20:41:56 +000033#include <stdarg.h>
Ted Kremenekea6507f2008-03-06 00:08:09 +000034
35using namespace clang;
Ted Kremenek01acb622008-10-24 21:18:08 +000036
37//===----------------------------------------------------------------------===//
38// Utility functions.
39//===----------------------------------------------------------------------===//
40
Ted Kremenek01acb622008-10-24 21:18:08 +000041// The "fundamental rule" for naming conventions of methods:
42// (url broken into two lines)
43// http://developer.apple.com/documentation/Cocoa/Conceptual/
44// MemoryMgmt/Tasks/MemoryManagementRules.html
45//
46// "You take ownership of an object if you create it using a method whose name
Mike Stump11289f42009-09-09 15:08:12 +000047// begins with "alloc" or "new" or contains "copy" (for example, alloc,
Ted Kremenek01acb622008-10-24 21:18:08 +000048// newObject, or mutableCopy), or if you send it a retain message. You are
49// responsible for relinquishing ownership of objects you own using release
50// or autorelease. Any other time you receive an object, you must
51// not release it."
52//
Ted Kremenek8a73c712009-02-21 05:13:43 +000053
54using llvm::CStrInCStrNoCase;
Ted Kremenek97ad7b62009-02-21 18:26:02 +000055using llvm::StringsEqualNoCase;
Ted Kremenek8a73c712009-02-21 05:13:43 +000056
57enum NamingConvention { NoConvention, CreateRule, InitRule };
58
59static inline bool isWordEnd(char ch, char prev, char next) {
60 return ch == '\0'
61 || (islower(prev) && isupper(ch)) // xxxC
62 || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate
63 || !isalpha(ch);
64}
Mike Stump11289f42009-09-09 15:08:12 +000065
66static inline const char* parseWord(const char* s) {
Ted Kremenek8a73c712009-02-21 05:13:43 +000067 char ch = *s, prev = '\0';
68 assert(ch != '\0');
69 char next = *(s+1);
70 while (!isWordEnd(ch, prev, next)) {
71 prev = ch;
72 ch = next;
73 next = *((++s)+1);
74 }
75 return s;
76}
77
Ted Kremenek32819772009-05-15 15:49:00 +000078static NamingConvention deriveNamingConvention(Selector S) {
79 IdentifierInfo *II = S.getIdentifierInfoForSlot(0);
Mike Stump11289f42009-09-09 15:08:12 +000080
Ted Kremenek32819772009-05-15 15:49:00 +000081 if (!II)
82 return NoConvention;
Mike Stump11289f42009-09-09 15:08:12 +000083
Daniel Dunbar9d9aa162009-10-17 18:12:45 +000084 const char *s = II->getNameStart();
Mike Stump11289f42009-09-09 15:08:12 +000085
Ted Kremenek8a73c712009-02-21 05:13:43 +000086 // A method/function name may contain a prefix. We don't know it is there,
87 // however, until we encounter the first '_'.
88 bool InPossiblePrefix = true;
89 bool AtBeginning = true;
90 NamingConvention C = NoConvention;
Mike Stump11289f42009-09-09 15:08:12 +000091
Ted Kremenek8a73c712009-02-21 05:13:43 +000092 while (*s != '\0') {
93 // Skip '_'.
94 if (*s == '_') {
95 if (InPossiblePrefix) {
Ted Kremenek90c953e2009-10-20 00:13:00 +000096 // If we already have a convention, return it. Otherwise, skip
97 // the prefix as if it wasn't there.
98 if (C != NoConvention)
99 break;
100
Ted Kremenek8a73c712009-02-21 05:13:43 +0000101 InPossiblePrefix = false;
102 AtBeginning = true;
Ted Kremenek90c953e2009-10-20 00:13:00 +0000103 assert(C == NoConvention);
Ted Kremenek8a73c712009-02-21 05:13:43 +0000104 }
105 ++s;
106 continue;
107 }
Mike Stump11289f42009-09-09 15:08:12 +0000108
Ted Kremenek8a73c712009-02-21 05:13:43 +0000109 // Skip numbers, ':', etc.
110 if (!isalpha(*s)) {
111 ++s;
112 continue;
113 }
Mike Stump11289f42009-09-09 15:08:12 +0000114
Ted Kremenek8a73c712009-02-21 05:13:43 +0000115 const char *wordEnd = parseWord(s);
116 assert(wordEnd > s);
117 unsigned len = wordEnd - s;
Mike Stump11289f42009-09-09 15:08:12 +0000118
Ted Kremenek8a73c712009-02-21 05:13:43 +0000119 switch (len) {
120 default:
121 break;
122 case 3:
123 // Methods starting with 'new' follow the create rule.
Ted Kremenek97ad7b62009-02-21 18:26:02 +0000124 if (AtBeginning && StringsEqualNoCase("new", s, len))
Mike Stump11289f42009-09-09 15:08:12 +0000125 C = CreateRule;
Ted Kremenek8a73c712009-02-21 05:13:43 +0000126 break;
127 case 4:
128 // Methods starting with 'alloc' or contain 'copy' follow the
129 // create rule
Ted Kremenek340fd2d2009-03-13 20:27:06 +0000130 if (C == NoConvention && StringsEqualNoCase("copy", s, len))
Ted Kremenek8a73c712009-02-21 05:13:43 +0000131 C = CreateRule;
132 else // Methods starting with 'init' follow the init rule.
Ted Kremenek97ad7b62009-02-21 18:26:02 +0000133 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek340fd2d2009-03-13 20:27:06 +0000134 C = InitRule;
135 break;
136 case 5:
137 if (AtBeginning && StringsEqualNoCase("alloc", s, len))
138 C = CreateRule;
Ted Kremenek8a73c712009-02-21 05:13:43 +0000139 break;
140 }
Mike Stump11289f42009-09-09 15:08:12 +0000141
Ted Kremenek8a73c712009-02-21 05:13:43 +0000142 // If we aren't in the prefix and have a derived convention then just
143 // return it now.
144 if (!InPossiblePrefix && C != NoConvention)
145 return C;
146
147 AtBeginning = false;
148 s = wordEnd;
149 }
150
151 // We will get here if there wasn't more than one word
152 // after the prefix.
153 return C;
154}
155
Ted Kremenek32819772009-05-15 15:49:00 +0000156static bool followsFundamentalRule(Selector S) {
157 return deriveNamingConvention(S) == CreateRule;
Ted Kremenek2855a932008-11-05 16:54:44 +0000158}
159
Ted Kremenek223a7d52009-04-29 23:03:22 +0000160static const ObjCMethodDecl*
Mike Stump11289f42009-09-09 15:08:12 +0000161ResolveToInterfaceMethodDecl(const ObjCMethodDecl *MD) {
Ted Kremenek223a7d52009-04-29 23:03:22 +0000162 ObjCInterfaceDecl *ID =
163 const_cast<ObjCInterfaceDecl*>(MD->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000164
Ted Kremenek223a7d52009-04-29 23:03:22 +0000165 return MD->isInstanceMethod()
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000166 ? ID->lookupInstanceMethod(MD->getSelector())
167 : ID->lookupClassMethod(MD->getSelector());
Ted Kremenek2855a932008-11-05 16:54:44 +0000168}
Ted Kremenek01acb622008-10-24 21:18:08 +0000169
Ted Kremenek884a8992009-05-08 23:09:42 +0000170namespace {
171class VISIBILITY_HIDDEN GenericNodeBuilder {
Zhongxing Xu107f7592009-08-06 12:48:26 +0000172 GRStmtNodeBuilder *SNB;
Ted Kremenek884a8992009-05-08 23:09:42 +0000173 Stmt *S;
174 const void *tag;
Zhongxing Xu107f7592009-08-06 12:48:26 +0000175 GREndPathNodeBuilder *ENB;
Ted Kremenek884a8992009-05-08 23:09:42 +0000176public:
Zhongxing Xu107f7592009-08-06 12:48:26 +0000177 GenericNodeBuilder(GRStmtNodeBuilder &snb, Stmt *s,
Ted Kremenek884a8992009-05-08 23:09:42 +0000178 const void *t)
179 : SNB(&snb), S(s), tag(t), ENB(0) {}
Zhongxing Xu107f7592009-08-06 12:48:26 +0000180
181 GenericNodeBuilder(GREndPathNodeBuilder &enb)
Ted Kremenek884a8992009-05-08 23:09:42 +0000182 : SNB(0), S(0), tag(0), ENB(&enb) {}
Mike Stump11289f42009-09-09 15:08:12 +0000183
Zhongxing Xu107f7592009-08-06 12:48:26 +0000184 ExplodedNode *MakeNode(const GRState *state, ExplodedNode *Pred) {
Ted Kremenek884a8992009-05-08 23:09:42 +0000185 if (SNB)
Mike Stump11289f42009-09-09 15:08:12 +0000186 return SNB->generateNode(PostStmt(S, Pred->getLocationContext(), tag),
Zhongxing Xue1190f72009-08-15 03:17:38 +0000187 state, Pred);
Mike Stump11289f42009-09-09 15:08:12 +0000188
Ted Kremenek884a8992009-05-08 23:09:42 +0000189 assert(ENB);
Ted Kremenek9ec08aa2009-05-09 00:44:07 +0000190 return ENB->generateNode(state, Pred);
Ted Kremenek884a8992009-05-08 23:09:42 +0000191 }
192};
193} // end anonymous namespace
194
Ted Kremenekc8bef6a2008-04-09 23:49:11 +0000195//===----------------------------------------------------------------------===//
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000196// Type querying functions.
197//===----------------------------------------------------------------------===//
198
Ted Kremenek7e904222009-01-12 21:45:02 +0000199static bool isRefType(QualType RetTy, const char* prefix,
200 ASTContext* Ctx = 0, const char* name = 0) {
Mike Stump11289f42009-09-09 15:08:12 +0000201
Ted Kremenek95d18192009-05-12 04:53:03 +0000202 // Recursively walk the typedef stack, allowing typedefs of reference types.
Daniel Dunbaracb5a4b2009-10-17 18:12:53 +0000203 while (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
Daniel Dunbar07d07852009-10-18 21:17:35 +0000204 llvm::StringRef TDName = TD->getDecl()->getIdentifier()->getName();
Daniel Dunbaracb5a4b2009-10-17 18:12:53 +0000205 if (TDName.startswith(prefix) && TDName.endswith("Ref"))
206 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000207
Daniel Dunbaracb5a4b2009-10-17 18:12:53 +0000208 RetTy = TD->getDecl()->getUnderlyingType();
Ted Kremenek7e904222009-01-12 21:45:02 +0000209 }
210
211 if (!Ctx || !name)
Ted Kremenekfa89e2f2008-07-15 16:50:12 +0000212 return false;
Ted Kremenek7e904222009-01-12 21:45:02 +0000213
214 // Is the type void*?
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000215 const PointerType* PT = RetTy->getAs<PointerType>();
Ted Kremenek7e904222009-01-12 21:45:02 +0000216 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenekfa89e2f2008-07-15 16:50:12 +0000217 return false;
Ted Kremenek7e904222009-01-12 21:45:02 +0000218
219 // Does the name start with the prefix?
Daniel Dunbar9d9aa162009-10-17 18:12:45 +0000220 return llvm::StringRef(name).startswith(prefix);
Ted Kremenekfa89e2f2008-07-15 16:50:12 +0000221}
222
Ted Kremeneka506fec2008-04-17 18:12:53 +0000223//===----------------------------------------------------------------------===//
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000224// Primitives used for constructing summaries for function/method calls.
Ted Kremenekc8bef6a2008-04-09 23:49:11 +0000225//===----------------------------------------------------------------------===//
226
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000227/// ArgEffect is used to summarize a function/method call's effect on a
228/// particular argument.
Ted Kremenekea072e32009-03-17 19:42:23 +0000229enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
230 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
231 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000232
Ted Kremenek819e9b62008-03-11 06:39:11 +0000233namespace llvm {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000234template <> struct FoldingSetTrait<ArgEffect> {
235static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
236 ID.AddInteger((unsigned) X);
237}
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000238};
Ted Kremenek819e9b62008-03-11 06:39:11 +0000239} // end llvm namespace
240
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000241/// ArgEffects summarizes the effects of a function/method call on all of
242/// its arguments.
243typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
244
Ted Kremenek819e9b62008-03-11 06:39:11 +0000245namespace {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000246
247/// RetEffect is used to summarize a function/method call's behavior with
Mike Stump11289f42009-09-09 15:08:12 +0000248/// respect to its return value.
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000249class VISIBILITY_HIDDEN RetEffect {
Ted Kremenek819e9b62008-03-11 06:39:11 +0000250public:
Ted Kremenekab4a8b52008-06-23 18:02:52 +0000251 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremenek1272f702009-05-12 20:06:54 +0000252 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias,
253 OwnedWhenTrackedReceiver };
Mike Stump11289f42009-09-09 15:08:12 +0000254
255 enum ObjKind { CF, ObjC, AnyObj };
Ted Kremenekaeb115f2009-01-28 05:56:51 +0000256
Ted Kremenek819e9b62008-03-11 06:39:11 +0000257private:
Ted Kremenekaeb115f2009-01-28 05:56:51 +0000258 Kind K;
259 ObjKind O;
260 unsigned index;
261
262 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
263 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Mike Stump11289f42009-09-09 15:08:12 +0000264
Ted Kremenek819e9b62008-03-11 06:39:11 +0000265public:
Ted Kremenekaeb115f2009-01-28 05:56:51 +0000266 Kind getKind() const { return K; }
267
268 ObjKind getObjKind() const { return O; }
Mike Stump11289f42009-09-09 15:08:12 +0000269
270 unsigned getIndex() const {
Ted Kremenek819e9b62008-03-11 06:39:11 +0000271 assert(getKind() == Alias);
Ted Kremenekaeb115f2009-01-28 05:56:51 +0000272 return index;
Ted Kremenek819e9b62008-03-11 06:39:11 +0000273 }
Mike Stump11289f42009-09-09 15:08:12 +0000274
Ted Kremenek223a7d52009-04-29 23:03:22 +0000275 bool isOwned() const {
Ted Kremenek1272f702009-05-12 20:06:54 +0000276 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
277 K == OwnedWhenTrackedReceiver;
Ted Kremenek223a7d52009-04-29 23:03:22 +0000278 }
Mike Stump11289f42009-09-09 15:08:12 +0000279
Ted Kremenek1272f702009-05-12 20:06:54 +0000280 static RetEffect MakeOwnedWhenTrackedReceiver() {
281 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
282 }
Mike Stump11289f42009-09-09 15:08:12 +0000283
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000284 static RetEffect MakeAlias(unsigned Idx) {
285 return RetEffect(Alias, Idx);
286 }
287 static RetEffect MakeReceiverAlias() {
288 return RetEffect(ReceiverAlias);
Mike Stump11289f42009-09-09 15:08:12 +0000289 }
Ted Kremenekaeb115f2009-01-28 05:56:51 +0000290 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
291 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Mike Stump11289f42009-09-09 15:08:12 +0000292 }
Ted Kremenekaeb115f2009-01-28 05:56:51 +0000293 static RetEffect MakeNotOwned(ObjKind o) {
294 return RetEffect(NotOwnedSymbol, o);
Ted Kremeneke6633562009-04-27 19:14:45 +0000295 }
296 static RetEffect MakeGCNotOwned() {
297 return RetEffect(GCNotOwnedSymbol, ObjC);
298 }
Mike Stump11289f42009-09-09 15:08:12 +0000299
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000300 static RetEffect MakeNoRet() {
301 return RetEffect(NoRet);
Ted Kremenekab4a8b52008-06-23 18:02:52 +0000302 }
Mike Stump11289f42009-09-09 15:08:12 +0000303
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000304 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenekaeb115f2009-01-28 05:56:51 +0000305 ID.AddInteger((unsigned)K);
306 ID.AddInteger((unsigned)O);
307 ID.AddInteger(index);
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000308 }
Ted Kremenek819e9b62008-03-11 06:39:11 +0000309};
Mike Stump11289f42009-09-09 15:08:12 +0000310
Ted Kremeneka2968e52009-11-13 01:54:21 +0000311//===----------------------------------------------------------------------===//
312// Reference-counting logic (typestate + counts).
313//===----------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000314
Ted Kremeneka2968e52009-11-13 01:54:21 +0000315class VISIBILITY_HIDDEN RefVal {
316public:
317 enum Kind {
318 Owned = 0, // Owning reference.
319 NotOwned, // Reference is not owned by still valid (not freed).
320 Released, // Object has been released.
321 ReturnedOwned, // Returned object passes ownership to caller.
322 ReturnedNotOwned, // Return object does not pass ownership to caller.
323 ERROR_START,
324 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
325 ErrorDeallocGC, // Calling -dealloc with GC enabled.
326 ErrorUseAfterRelease, // Object used after released.
327 ErrorReleaseNotOwned, // Release of an object that was not owned.
328 ERROR_LEAK_START,
329 ErrorLeak, // A memory leak due to excessive reference counts.
330 ErrorLeakReturned, // A memory leak due to the returning method not having
331 // the correct naming conventions.
332 ErrorGCLeakReturned,
333 ErrorOverAutorelease,
334 ErrorReturnedNotOwned
335 };
336
337private:
338 Kind kind;
339 RetEffect::ObjKind okind;
340 unsigned Cnt;
341 unsigned ACnt;
342 QualType T;
343
344 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
345 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
346
347 RefVal(Kind k, unsigned cnt = 0)
348 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
349
350public:
351 Kind getKind() const { return kind; }
352
353 RetEffect::ObjKind getObjKind() const { return okind; }
354
355 unsigned getCount() const { return Cnt; }
356 unsigned getAutoreleaseCount() const { return ACnt; }
357 unsigned getCombinedCounts() const { return Cnt + ACnt; }
358 void clearCounts() { Cnt = 0; ACnt = 0; }
359 void setCount(unsigned i) { Cnt = i; }
360 void setAutoreleaseCount(unsigned i) { ACnt = i; }
361
362 QualType getType() const { return T; }
363
364 // Useful predicates.
365
366 static bool isError(Kind k) { return k >= ERROR_START; }
367
368 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
369
370 bool isOwned() const {
371 return getKind() == Owned;
372 }
373
374 bool isNotOwned() const {
375 return getKind() == NotOwned;
376 }
377
378 bool isReturnedOwned() const {
379 return getKind() == ReturnedOwned;
380 }
381
382 bool isReturnedNotOwned() const {
383 return getKind() == ReturnedNotOwned;
384 }
385
386 bool isNonLeakError() const {
387 Kind k = getKind();
388 return isError(k) && !isLeak(k);
389 }
390
391 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
392 unsigned Count = 1) {
393 return RefVal(Owned, o, Count, 0, t);
394 }
395
396 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
397 unsigned Count = 0) {
398 return RefVal(NotOwned, o, Count, 0, t);
399 }
400
401 // Comparison, profiling, and pretty-printing.
402
403 bool operator==(const RefVal& X) const {
404 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
405 }
406
407 RefVal operator-(size_t i) const {
408 return RefVal(getKind(), getObjKind(), getCount() - i,
409 getAutoreleaseCount(), getType());
410 }
411
412 RefVal operator+(size_t i) const {
413 return RefVal(getKind(), getObjKind(), getCount() + i,
414 getAutoreleaseCount(), getType());
415 }
416
417 RefVal operator^(Kind k) const {
418 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
419 getType());
420 }
421
422 RefVal autorelease() const {
423 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
424 getType());
425 }
426
427 void Profile(llvm::FoldingSetNodeID& ID) const {
428 ID.AddInteger((unsigned) kind);
429 ID.AddInteger(Cnt);
430 ID.AddInteger(ACnt);
431 ID.Add(T);
432 }
433
434 void print(llvm::raw_ostream& Out) const;
435};
436
437void RefVal::print(llvm::raw_ostream& Out) const {
438 if (!T.isNull())
439 Out << "Tracked Type:" << T.getAsString() << '\n';
440
441 switch (getKind()) {
442 default: assert(false);
443 case Owned: {
444 Out << "Owned";
445 unsigned cnt = getCount();
446 if (cnt) Out << " (+ " << cnt << ")";
447 break;
448 }
449
450 case NotOwned: {
451 Out << "NotOwned";
452 unsigned cnt = getCount();
453 if (cnt) Out << " (+ " << cnt << ")";
454 break;
455 }
456
457 case ReturnedOwned: {
458 Out << "ReturnedOwned";
459 unsigned cnt = getCount();
460 if (cnt) Out << " (+ " << cnt << ")";
461 break;
462 }
463
464 case ReturnedNotOwned: {
465 Out << "ReturnedNotOwned";
466 unsigned cnt = getCount();
467 if (cnt) Out << " (+ " << cnt << ")";
468 break;
469 }
470
471 case Released:
472 Out << "Released";
473 break;
474
475 case ErrorDeallocGC:
476 Out << "-dealloc (GC)";
477 break;
478
479 case ErrorDeallocNotOwned:
480 Out << "-dealloc (not-owned)";
481 break;
482
483 case ErrorLeak:
484 Out << "Leaked";
485 break;
486
487 case ErrorLeakReturned:
488 Out << "Leaked (Bad naming)";
489 break;
490
491 case ErrorGCLeakReturned:
492 Out << "Leaked (GC-ed at return)";
493 break;
494
495 case ErrorUseAfterRelease:
496 Out << "Use-After-Release [ERROR]";
497 break;
498
499 case ErrorReleaseNotOwned:
500 Out << "Release of Not-Owned [ERROR]";
501 break;
502
503 case RefVal::ErrorOverAutorelease:
504 Out << "Over autoreleased";
505 break;
506
507 case RefVal::ErrorReturnedNotOwned:
508 Out << "Non-owned object returned instead of owned";
509 break;
510 }
511
512 if (ACnt) {
513 Out << " [ARC +" << ACnt << ']';
514 }
515}
516} //end anonymous namespace
517
518//===----------------------------------------------------------------------===//
519// RefBindings - State used to track object reference counts.
520//===----------------------------------------------------------------------===//
521
522typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
523static int RefBIndex = 0;
524
525namespace clang {
526 template<>
527 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
528 static inline void* GDMIndex() { return &RefBIndex; }
529 };
530}
531
532//===----------------------------------------------------------------------===//
533// Summaries
534//===----------------------------------------------------------------------===//
535
536namespace {
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000537class VISIBILITY_HIDDEN RetainSummary {
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000538 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
539 /// specifies the argument (starting from 0). This can be sparsely
540 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000541 ArgEffects Args;
Mike Stump11289f42009-09-09 15:08:12 +0000542
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000543 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
544 /// do not have an entry in Args.
545 ArgEffect DefaultArgEffect;
Mike Stump11289f42009-09-09 15:08:12 +0000546
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000547 /// Receiver - If this summary applies to an Objective-C message expression,
548 /// this is the effect applied to the state of the receiver.
Ted Kremenekb0862dc2008-05-06 02:26:56 +0000549 ArgEffect Receiver;
Mike Stump11289f42009-09-09 15:08:12 +0000550
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000551 /// Ret - The effect on the return value. Used to indicate if the
552 /// function/method call returns a new tracked symbol, returns an
553 /// alias of one of the arguments in the call, and so on.
Ted Kremenek819e9b62008-03-11 06:39:11 +0000554 RetEffect Ret;
Mike Stump11289f42009-09-09 15:08:12 +0000555
Ted Kremenek3b2294c2008-07-18 17:24:20 +0000556 /// EndPath - Indicates that execution of this method/function should
557 /// terminate the simulation of a path.
558 bool EndPath;
Mike Stump11289f42009-09-09 15:08:12 +0000559
Ted Kremenek819e9b62008-03-11 06:39:11 +0000560public:
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000561 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Ted Kremenek3b2294c2008-07-18 17:24:20 +0000562 ArgEffect ReceiverEff, bool endpath = false)
563 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
Mike Stump11289f42009-09-09 15:08:12 +0000564 EndPath(endpath) {}
565
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000566 /// getArg - Return the argument effect on the argument specified by
567 /// idx (starting from 0).
Ted Kremenekbf9d8042008-03-11 17:48:22 +0000568 ArgEffect getArg(unsigned idx) const {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000569 if (const ArgEffect *AE = Args.lookup(idx))
570 return *AE;
Mike Stump11289f42009-09-09 15:08:12 +0000571
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000572 return DefaultArgEffect;
Ted Kremenekbf9d8042008-03-11 17:48:22 +0000573 }
Mike Stump11289f42009-09-09 15:08:12 +0000574
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000575 /// setDefaultArgEffect - Set the default argument effect.
576 void setDefaultArgEffect(ArgEffect E) {
577 DefaultArgEffect = E;
578 }
Mike Stump11289f42009-09-09 15:08:12 +0000579
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000580 /// setArg - Set the argument effect on the argument specified by idx.
581 void setArgEffect(ArgEffects::Factory& AF, unsigned idx, ArgEffect E) {
582 Args = AF.Add(Args, idx, E);
583 }
Mike Stump11289f42009-09-09 15:08:12 +0000584
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000585 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000586 RetEffect getRetEffect() const { return Ret; }
Mike Stump11289f42009-09-09 15:08:12 +0000587
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000588 /// setRetEffect - Set the effect of the return value of the call.
589 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump11289f42009-09-09 15:08:12 +0000590
Ted Kremenek3b2294c2008-07-18 17:24:20 +0000591 /// isEndPath - Returns true if executing the given method/function should
592 /// terminate the path.
593 bool isEndPath() const { return EndPath; }
Mike Stump11289f42009-09-09 15:08:12 +0000594
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000595 /// getReceiverEffect - Returns the effect on the receiver of the call.
596 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000597 ArgEffect getReceiverEffect() const { return Receiver; }
Mike Stump11289f42009-09-09 15:08:12 +0000598
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000599 /// setReceiverEffect - Set the effect on the receiver of the call.
600 void setReceiverEffect(ArgEffect E) { Receiver = E; }
Mike Stump11289f42009-09-09 15:08:12 +0000601
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000602 typedef ArgEffects::iterator ExprIterator;
Mike Stump11289f42009-09-09 15:08:12 +0000603
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000604 ExprIterator begin_args() const { return Args.begin(); }
605 ExprIterator end_args() const { return Args.end(); }
Mike Stump11289f42009-09-09 15:08:12 +0000606
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000607 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000608 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenekf7faa422008-07-18 17:39:56 +0000609 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000610 ID.Add(A);
Ted Kremenekb0862dc2008-05-06 02:26:56 +0000611 ID.Add(RetEff);
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000612 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenekb0862dc2008-05-06 02:26:56 +0000613 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenekf7faa422008-07-18 17:39:56 +0000614 ID.AddInteger((unsigned) EndPath);
Ted Kremenek819e9b62008-03-11 06:39:11 +0000615 }
Mike Stump11289f42009-09-09 15:08:12 +0000616
Ted Kremenek819e9b62008-03-11 06:39:11 +0000617 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenekf7faa422008-07-18 17:39:56 +0000618 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremenek819e9b62008-03-11 06:39:11 +0000619 }
620};
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000621} // end anonymous namespace
Ted Kremenek819e9b62008-03-11 06:39:11 +0000622
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000623//===----------------------------------------------------------------------===//
624// Data structures for constructing summaries.
625//===----------------------------------------------------------------------===//
Ted Kremenekb1d13292008-06-24 03:49:48 +0000626
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000627namespace {
628class VISIBILITY_HIDDEN ObjCSummaryKey {
629 IdentifierInfo* II;
630 Selector S;
Mike Stump11289f42009-09-09 15:08:12 +0000631public:
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000632 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
633 : II(ii), S(s) {}
634
Ted Kremenek223a7d52009-04-29 23:03:22 +0000635 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000636 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek5801f652009-05-13 18:16:01 +0000637
638 ObjCSummaryKey(const ObjCInterfaceDecl* d, IdentifierInfo *ii, Selector s)
639 : II(d ? d->getIdentifier() : ii), S(s) {}
Mike Stump11289f42009-09-09 15:08:12 +0000640
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000641 ObjCSummaryKey(Selector s)
642 : II(0), S(s) {}
Mike Stump11289f42009-09-09 15:08:12 +0000643
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000644 IdentifierInfo* getIdentifier() const { return II; }
645 Selector getSelector() const { return S; }
646};
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000647}
648
649namespace llvm {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000650template <> struct DenseMapInfo<ObjCSummaryKey> {
651 static inline ObjCSummaryKey getEmptyKey() {
652 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
653 DenseMapInfo<Selector>::getEmptyKey());
654 }
Mike Stump11289f42009-09-09 15:08:12 +0000655
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000656 static inline ObjCSummaryKey getTombstoneKey() {
657 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump11289f42009-09-09 15:08:12 +0000658 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000659 }
Mike Stump11289f42009-09-09 15:08:12 +0000660
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000661 static unsigned getHashValue(const ObjCSummaryKey &V) {
662 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000663 & 0x88888888)
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000664 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
665 & 0x55555555);
666 }
Mike Stump11289f42009-09-09 15:08:12 +0000667
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000668 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
669 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
670 RHS.getIdentifier()) &&
671 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
672 RHS.getSelector());
673 }
Mike Stump11289f42009-09-09 15:08:12 +0000674
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000675 static bool isPod() {
676 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
677 DenseMapInfo<Selector>::isPod();
678 }
679};
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000680} // end llvm namespace
Mike Stump11289f42009-09-09 15:08:12 +0000681
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000682namespace {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000683class VISIBILITY_HIDDEN ObjCSummaryCache {
684 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
685 MapTy M;
686public:
687 ObjCSummaryCache() {}
Mike Stump11289f42009-09-09 15:08:12 +0000688
Ted Kremenek8be51382009-07-21 23:27:57 +0000689 RetainSummary* find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
Ted Kremenek223a7d52009-04-29 23:03:22 +0000690 Selector S) {
Ted Kremenek0b50fb12009-04-29 05:04:30 +0000691 // Lookup the method using the decl for the class @interface. If we
692 // have no decl, lookup using the class name.
693 return D ? find(D, S) : find(ClsName, S);
694 }
Mike Stump11289f42009-09-09 15:08:12 +0000695
696 RetainSummary* find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000697 // Do a lookup with the (D,S) pair. If we find a match return
698 // the iterator.
699 ObjCSummaryKey K(D, S);
700 MapTy::iterator I = M.find(K);
Mike Stump11289f42009-09-09 15:08:12 +0000701
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000702 if (I != M.end() || !D)
Ted Kremenek8be51382009-07-21 23:27:57 +0000703 return I->second;
Mike Stump11289f42009-09-09 15:08:12 +0000704
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000705 // Walk the super chain. If we find a hit with a parent, we'll end
706 // up returning that summary. We actually allow that key (null,S), as
707 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
708 // generate initial summaries without having to worry about NSObject
709 // being declared.
710 // FIXME: We may change this at some point.
711 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
712 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
713 break;
Mike Stump11289f42009-09-09 15:08:12 +0000714
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000715 if (!C)
Ted Kremenek8be51382009-07-21 23:27:57 +0000716 return NULL;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000717 }
Mike Stump11289f42009-09-09 15:08:12 +0000718
719 // Cache the summary with original key to make the next lookup faster
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000720 // and return the iterator.
Ted Kremenek8be51382009-07-21 23:27:57 +0000721 RetainSummary *Summ = I->second;
722 M[K] = Summ;
723 return Summ;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000724 }
Mike Stump11289f42009-09-09 15:08:12 +0000725
Ted Kremenek9551ab62008-08-12 20:41:56 +0000726
Ted Kremenek8be51382009-07-21 23:27:57 +0000727 RetainSummary* find(Expr* Receiver, Selector S) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000728 return find(getReceiverDecl(Receiver), S);
729 }
Mike Stump11289f42009-09-09 15:08:12 +0000730
Ted Kremenek8be51382009-07-21 23:27:57 +0000731 RetainSummary* find(IdentifierInfo* II, Selector S) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000732 // FIXME: Class method lookup. Right now we dont' have a good way
733 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek8be51382009-07-21 23:27:57 +0000734 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump11289f42009-09-09 15:08:12 +0000735
Ted Kremenek8be51382009-07-21 23:27:57 +0000736 if (I == M.end())
737 I = M.find(ObjCSummaryKey(S));
Mike Stump11289f42009-09-09 15:08:12 +0000738
Ted Kremenek8be51382009-07-21 23:27:57 +0000739 return I == M.end() ? NULL : I->second;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000740 }
Mike Stump11289f42009-09-09 15:08:12 +0000741
742 const ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
Steve Naroff7cae42b2009-07-10 23:34:53 +0000743 if (const ObjCObjectPointerType* PT =
John McCall9dd450b2009-09-21 23:43:11 +0000744 E->getType()->getAs<ObjCObjectPointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +0000745 return PT->getInterfaceDecl();
746
747 return NULL;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000748 }
Mike Stump11289f42009-09-09 15:08:12 +0000749
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000750 RetainSummary*& operator[](ObjCMessageExpr* ME) {
Mike Stump11289f42009-09-09 15:08:12 +0000751
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000752 Selector S = ME->getSelector();
Mike Stump11289f42009-09-09 15:08:12 +0000753
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000754 if (Expr* Receiver = ME->getReceiver()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +0000755 const ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000756 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
757 }
Mike Stump11289f42009-09-09 15:08:12 +0000758
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000759 return M[ObjCSummaryKey(ME->getClassName(), S)];
760 }
Mike Stump11289f42009-09-09 15:08:12 +0000761
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000762 RetainSummary*& operator[](ObjCSummaryKey K) {
763 return M[K];
764 }
Mike Stump11289f42009-09-09 15:08:12 +0000765
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000766 RetainSummary*& operator[](Selector S) {
767 return M[ ObjCSummaryKey(S) ];
768 }
Mike Stump11289f42009-09-09 15:08:12 +0000769};
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000770} // end anonymous namespace
771
772//===----------------------------------------------------------------------===//
773// Data structures for managing collections of summaries.
774//===----------------------------------------------------------------------===//
775
776namespace {
777class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremenek00daccd2008-05-05 22:11:16 +0000778
779 //==-----------------------------------------------------------------==//
780 // Typedefs.
781 //==-----------------------------------------------------------------==//
Mike Stump11289f42009-09-09 15:08:12 +0000782
Ted Kremenek00daccd2008-05-05 22:11:16 +0000783 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
784 FuncSummariesTy;
Mike Stump11289f42009-09-09 15:08:12 +0000785
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000786 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump11289f42009-09-09 15:08:12 +0000787
Ted Kremenek00daccd2008-05-05 22:11:16 +0000788 //==-----------------------------------------------------------------==//
789 // Data.
790 //==-----------------------------------------------------------------==//
Mike Stump11289f42009-09-09 15:08:12 +0000791
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000792 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek4b7ca772008-04-29 05:33:51 +0000793 ASTContext& Ctx;
Ted Kremenekab54e512008-07-01 17:21:27 +0000794
Ted Kremenekae529272008-07-09 18:11:16 +0000795 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
796 /// "CFDictionaryCreate".
797 IdentifierInfo* CFDictionaryCreateII;
Mike Stump11289f42009-09-09 15:08:12 +0000798
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000799 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek4b7ca772008-04-29 05:33:51 +0000800 const bool GCEnabled;
Mike Stump11289f42009-09-09 15:08:12 +0000801
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000802 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump11289f42009-09-09 15:08:12 +0000803 FuncSummariesTy FuncSummaries;
804
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000805 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
806 /// to summaries.
Ted Kremenekea736c52008-06-23 22:21:20 +0000807 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenek00daccd2008-05-05 22:11:16 +0000808
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000809 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenekea736c52008-06-23 22:21:20 +0000810 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenek00daccd2008-05-05 22:11:16 +0000811
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000812 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
813 /// and all other data used by the checker.
Ted Kremenek00daccd2008-05-05 22:11:16 +0000814 llvm::BumpPtrAllocator BPAlloc;
Mike Stump11289f42009-09-09 15:08:12 +0000815
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000816 /// AF - A factory for ArgEffects objects.
Mike Stump11289f42009-09-09 15:08:12 +0000817 ArgEffects::Factory AF;
818
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000819 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek00daccd2008-05-05 22:11:16 +0000820 ArgEffects ScratchArgs;
Mike Stump11289f42009-09-09 15:08:12 +0000821
Ted Kremenek9157fbb2009-05-07 23:40:42 +0000822 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
823 /// objects.
824 RetEffect ObjCAllocRetE;
Ted Kremeneka03705c2009-06-05 23:18:01 +0000825
Mike Stump11289f42009-09-09 15:08:12 +0000826 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenek815fbb62009-08-20 05:13:36 +0000827 /// Objective-C objects.
Ted Kremeneka03705c2009-06-05 23:18:01 +0000828 RetEffect ObjCInitRetE;
Mike Stump11289f42009-09-09 15:08:12 +0000829
Ted Kremenekff606a12009-05-04 04:57:00 +0000830 RetainSummary DefaultSummary;
Ted Kremenek10427bd2008-05-06 18:11:36 +0000831 RetainSummary* StopSummary;
Mike Stump11289f42009-09-09 15:08:12 +0000832
Ted Kremenek00daccd2008-05-05 22:11:16 +0000833 //==-----------------------------------------------------------------==//
834 // Methods.
835 //==-----------------------------------------------------------------==//
Mike Stump11289f42009-09-09 15:08:12 +0000836
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000837 /// getArgEffects - Returns a persistent ArgEffects object based on the
838 /// data in ScratchArgs.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000839 ArgEffects getArgEffects();
Ted Kremenek819e9b62008-03-11 06:39:11 +0000840
Mike Stump11289f42009-09-09 15:08:12 +0000841 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
842
Ted Kremenekcc3d1882008-10-23 01:56:15 +0000843public:
Ted Kremenek1272f702009-05-12 20:06:54 +0000844 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
845
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000846 RetainSummary *getDefaultSummary() {
847 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
848 return new (Summ) RetainSummary(DefaultSummary);
849 }
Mike Stump11289f42009-09-09 15:08:12 +0000850
Ted Kremenek82157a12009-02-23 16:51:39 +0000851 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Mike Stump11289f42009-09-09 15:08:12 +0000852
Ted Kremenek00daccd2008-05-05 22:11:16 +0000853 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
Mike Stump11289f42009-09-09 15:08:12 +0000854 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek7e904222009-01-12 21:45:02 +0000855 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Mike Stump11289f42009-09-09 15:08:12 +0000856
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000857 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000858 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek3b2294c2008-07-18 17:24:20 +0000859 ArgEffect DefaultEff = MayEscape,
860 bool isEndPath = false);
Ted Kremenek3700b762008-10-29 04:07:07 +0000861
Ted Kremenekb0862dc2008-05-06 02:26:56 +0000862 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000863 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek1df2f3a2008-05-22 17:31:13 +0000864 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000865 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0806f912008-05-06 00:30:21 +0000866 }
Mike Stump11289f42009-09-09 15:08:12 +0000867
Ted Kremenek0b50fb12009-04-29 05:04:30 +0000868 RetainSummary *getPersistentStopSummary() {
Ted Kremenek10427bd2008-05-06 18:11:36 +0000869 if (StopSummary)
870 return StopSummary;
Mike Stump11289f42009-09-09 15:08:12 +0000871
Ted Kremenek10427bd2008-05-06 18:11:36 +0000872 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
873 StopTracking, StopTracking);
Ted Kremenek3700b762008-10-29 04:07:07 +0000874
Ted Kremenek10427bd2008-05-06 18:11:36 +0000875 return StopSummary;
Mike Stump11289f42009-09-09 15:08:12 +0000876 }
Ted Kremenek015c3562008-05-06 04:20:12 +0000877
Ted Kremenek0b50fb12009-04-29 05:04:30 +0000878 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek3d1e9722008-05-05 23:55:01 +0000879
Ted Kremenekea736c52008-06-23 22:21:20 +0000880 void InitializeClassMethodSummaries();
881 void InitializeMethodSummaries();
Mike Stump11289f42009-09-09 15:08:12 +0000882
Ted Kremenekb4cf4a52009-05-03 04:42:10 +0000883 bool isTrackedObjCObjectType(QualType T);
Ted Kremenek4b59ccb2009-05-03 06:08:32 +0000884 bool isTrackedCFObjectType(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000885
Ted Kremenekcc3d1882008-10-23 01:56:15 +0000886private:
Mike Stump11289f42009-09-09 15:08:12 +0000887
Ted Kremenek3b2294c2008-07-18 17:24:20 +0000888 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
889 RetainSummary* Summ) {
890 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
891 }
Mike Stump11289f42009-09-09 15:08:12 +0000892
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000893 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
894 ObjCClassMethodSummaries[S] = Summ;
895 }
Mike Stump11289f42009-09-09 15:08:12 +0000896
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000897 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
898 ObjCMethodSummaries[S] = Summ;
899 }
Ted Kremenek00dfe302009-03-04 23:30:42 +0000900
901 void addClassMethSummary(const char* Cls, const char* nullaryName,
902 RetainSummary *Summ) {
903 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
904 Selector S = GetNullarySelector(nullaryName, Ctx);
905 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
906 }
Mike Stump11289f42009-09-09 15:08:12 +0000907
Ted Kremenekdce78462009-02-25 02:54:57 +0000908 void addInstMethSummary(const char* Cls, const char* nullaryName,
909 RetainSummary *Summ) {
910 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
911 Selector S = GetNullarySelector(nullaryName, Ctx);
912 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
913 }
Mike Stump11289f42009-09-09 15:08:12 +0000914
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000915 Selector generateSelector(va_list argp) {
Ted Kremenek050b91c2008-08-12 18:30:56 +0000916 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000917
Ted Kremenek050b91c2008-08-12 18:30:56 +0000918 while (const char* s = va_arg(argp, const char*))
919 II.push_back(&Ctx.Idents.get(s));
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000920
Mike Stump11289f42009-09-09 15:08:12 +0000921 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000922 }
Mike Stump11289f42009-09-09 15:08:12 +0000923
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000924 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
925 RetainSummary* Summ, va_list argp) {
926 Selector S = generateSelector(argp);
927 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek3b2294c2008-07-18 17:24:20 +0000928 }
Mike Stump11289f42009-09-09 15:08:12 +0000929
Ted Kremenek3f13f592008-08-12 18:48:50 +0000930 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
931 va_list argp;
932 va_start(argp, Summ);
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000933 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump11289f42009-09-09 15:08:12 +0000934 va_end(argp);
Ted Kremenek3f13f592008-08-12 18:48:50 +0000935 }
Mike Stump11289f42009-09-09 15:08:12 +0000936
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000937 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
938 va_list argp;
939 va_start(argp, Summ);
940 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
941 va_end(argp);
942 }
Mike Stump11289f42009-09-09 15:08:12 +0000943
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000944 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
945 va_list argp;
946 va_start(argp, Summ);
947 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
948 va_end(argp);
949 }
950
Ted Kremenek050b91c2008-08-12 18:30:56 +0000951 void addPanicSummary(const char* Cls, ...) {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000952 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
953 RetEffect::MakeNoRet(),
Ted Kremenek050b91c2008-08-12 18:30:56 +0000954 DoNothing, DoNothing, true);
955 va_list argp;
956 va_start (argp, Cls);
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000957 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek050b91c2008-08-12 18:30:56 +0000958 va_end(argp);
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000959 }
Mike Stump11289f42009-09-09 15:08:12 +0000960
Ted Kremenek819e9b62008-03-11 06:39:11 +0000961public:
Mike Stump11289f42009-09-09 15:08:12 +0000962
Ted Kremenek00daccd2008-05-05 22:11:16 +0000963 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremenekab54e512008-07-01 17:21:27 +0000964 : Ctx(ctx),
Ted Kremenekae529272008-07-09 18:11:16 +0000965 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000966 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenek9157fbb2009-05-07 23:40:42 +0000967 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
968 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenekea675cf2009-06-11 18:17:24 +0000969 ObjCInitRetE(gcenabled ? RetEffect::MakeGCNotOwned()
970 : RetEffect::MakeOwnedWhenTrackedReceiver()),
Ted Kremenekff606a12009-05-04 04:57:00 +0000971 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
972 RetEffect::MakeNoRet() /* return effect */,
Ted Kremenekd0e3ab22009-05-11 18:30:24 +0000973 MayEscape, /* default argument effect */
974 DoNothing /* receiver effect */),
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000975 StopSummary(0) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000976
977 InitializeClassMethodSummaries();
978 InitializeMethodSummaries();
979 }
Mike Stump11289f42009-09-09 15:08:12 +0000980
Ted Kremenek00daccd2008-05-05 22:11:16 +0000981 ~RetainSummaryManager();
Mike Stump11289f42009-09-09 15:08:12 +0000982
983 RetainSummary* getSummary(FunctionDecl* FD);
984
Ted Kremeneka2968e52009-11-13 01:54:21 +0000985 RetainSummary *getInstanceMethodSummary(const ObjCMessageExpr *ME,
986 const GRState *state,
987 const LocationContext *LC);
988
989 RetainSummary* getInstanceMethodSummary(const ObjCMessageExpr* ME,
Ted Kremenek223a7d52009-04-29 23:03:22 +0000990 const ObjCInterfaceDecl* ID) {
Ted Kremenek38724302009-04-29 17:09:14 +0000991 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Mike Stump11289f42009-09-09 15:08:12 +0000992 ID, ME->getMethodDecl(), ME->getType());
Ted Kremenek0b50fb12009-04-29 05:04:30 +0000993 }
Mike Stump11289f42009-09-09 15:08:12 +0000994
Ted Kremenek38724302009-04-29 17:09:14 +0000995 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek223a7d52009-04-29 23:03:22 +0000996 const ObjCInterfaceDecl* ID,
997 const ObjCMethodDecl *MD,
998 QualType RetTy);
Ted Kremenek7686ffa2009-04-29 00:42:39 +0000999
1000 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek223a7d52009-04-29 23:03:22 +00001001 const ObjCInterfaceDecl *ID,
1002 const ObjCMethodDecl *MD,
1003 QualType RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00001004
Ted Kremeneka2968e52009-11-13 01:54:21 +00001005 RetainSummary *getClassMethodSummary(const ObjCMessageExpr *ME) {
Ted Kremenek7686ffa2009-04-29 00:42:39 +00001006 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
1007 ME->getClassInfo().first,
1008 ME->getMethodDecl(), ME->getType());
1009 }
Ted Kremenek99fe1692009-04-29 17:17:48 +00001010
1011 /// getMethodSummary - This version of getMethodSummary is used to query
1012 /// the summary for the current method being analyzed.
Ted Kremenek223a7d52009-04-29 23:03:22 +00001013 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
1014 // FIXME: Eventually this should be unneeded.
Ted Kremenek223a7d52009-04-29 23:03:22 +00001015 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenekb2a143f2009-04-30 05:41:14 +00001016 Selector S = MD->getSelector();
Ted Kremenek99fe1692009-04-29 17:17:48 +00001017 IdentifierInfo *ClsName = ID->getIdentifier();
1018 QualType ResultTy = MD->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00001019
1020 // Resolve the method decl last.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001021 if (const ObjCMethodDecl *InterfaceMD = ResolveToInterfaceMethodDecl(MD))
Ted Kremenek497df912009-04-30 05:47:23 +00001022 MD = InterfaceMD;
Mike Stump11289f42009-09-09 15:08:12 +00001023
Ted Kremenek99fe1692009-04-29 17:17:48 +00001024 if (MD->isInstanceMethod())
1025 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
1026 else
1027 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
1028 }
Mike Stump11289f42009-09-09 15:08:12 +00001029
Ted Kremenek223a7d52009-04-29 23:03:22 +00001030 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
1031 Selector S, QualType RetTy);
1032
Ted Kremenekc2de7272009-05-09 02:58:13 +00001033 void updateSummaryFromAnnotations(RetainSummary &Summ,
1034 const ObjCMethodDecl *MD);
1035
1036 void updateSummaryFromAnnotations(RetainSummary &Summ,
1037 const FunctionDecl *FD);
1038
Ted Kremenek00daccd2008-05-05 22:11:16 +00001039 bool isGCEnabled() const { return GCEnabled; }
Mike Stump11289f42009-09-09 15:08:12 +00001040
Ted Kremenek1d9a2672009-05-04 05:31:22 +00001041 RetainSummary *copySummary(RetainSummary *OldSumm) {
1042 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
1043 new (Summ) RetainSummary(*OldSumm);
1044 return Summ;
Mike Stump11289f42009-09-09 15:08:12 +00001045 }
Ted Kremenek819e9b62008-03-11 06:39:11 +00001046};
Mike Stump11289f42009-09-09 15:08:12 +00001047
Ted Kremenek819e9b62008-03-11 06:39:11 +00001048} // end anonymous namespace
1049
1050//===----------------------------------------------------------------------===//
1051// Implementation of checker data structures.
1052//===----------------------------------------------------------------------===//
1053
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001054RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremenek819e9b62008-03-11 06:39:11 +00001055
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001056ArgEffects RetainSummaryManager::getArgEffects() {
1057 ArgEffects AE = ScratchArgs;
1058 ScratchArgs = AF.GetEmptyMap();
1059 return AE;
Ted Kremenek68d73d12008-03-12 01:21:45 +00001060}
1061
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001062RetainSummary*
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001063RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekcb2e6362008-05-06 15:44:25 +00001064 ArgEffect ReceiverEff,
Ted Kremenek3b2294c2008-07-18 17:24:20 +00001065 ArgEffect DefaultEff,
Mike Stump11289f42009-09-09 15:08:12 +00001066 bool isEndPath) {
Ted Kremenekf7141592008-04-24 17:22:33 +00001067 // Create the summary and return it.
Ted Kremenek1bff64e2009-05-04 04:30:18 +00001068 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenek3b2294c2008-07-18 17:24:20 +00001069 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenek68d73d12008-03-12 01:21:45 +00001070 return Summ;
1071}
1072
Ted Kremenek00daccd2008-05-05 22:11:16 +00001073//===----------------------------------------------------------------------===//
Ted Kremenek1d92d2c2009-01-07 00:39:56 +00001074// Predicates.
1075//===----------------------------------------------------------------------===//
1076
Ted Kremenekb4cf4a52009-05-03 04:42:10 +00001077bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Steve Naroff79d12152009-07-16 15:41:00 +00001078 if (!Ty->isObjCObjectPointerType())
Ted Kremenek1d92d2c2009-01-07 00:39:56 +00001079 return false;
1080
John McCall9dd450b2009-09-21 23:43:11 +00001081 const ObjCObjectPointerType *PT = Ty->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001082
Steve Naroff7cae42b2009-07-10 23:34:53 +00001083 // Can be true for objects with the 'NSObject' attribute.
1084 if (!PT)
Ted Kremenek37467812009-04-23 22:11:07 +00001085 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001086
Steve Naroff7cae42b2009-07-10 23:34:53 +00001087 // We assume that id<..>, id, and "Class" all represent tracked objects.
1088 if (PT->isObjCIdType() || PT->isObjCQualifiedIdType() ||
1089 PT->isObjCClassType())
1090 return true;
Ted Kremenek1d92d2c2009-01-07 00:39:56 +00001091
Mike Stump11289f42009-09-09 15:08:12 +00001092 // Does the interface subclass NSObject?
1093 // FIXME: We can memoize here if this gets too expensive.
1094 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
Ted Kremenek1d92d2c2009-01-07 00:39:56 +00001095
Ted Kremeneke4302ee2009-05-16 01:38:01 +00001096 // Assume that anything declared with a forward declaration and no
1097 // @interface subclasses NSObject.
1098 if (ID->isForwardDecl())
1099 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001100
Ted Kremeneke4302ee2009-05-16 01:38:01 +00001101 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
1102
Ted Kremenek1d92d2c2009-01-07 00:39:56 +00001103 for ( ; ID ; ID = ID->getSuperClass())
1104 if (ID->getIdentifier() == NSObjectII)
1105 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001106
Ted Kremenek1d92d2c2009-01-07 00:39:56 +00001107 return false;
1108}
1109
Ted Kremenek4b59ccb2009-05-03 06:08:32 +00001110bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
1111 return isRefType(T, "CF") || // Core Foundation.
1112 isRefType(T, "CG") || // Core Graphics.
1113 isRefType(T, "DADisk") || // Disk Arbitration API.
1114 isRefType(T, "DADissenter") ||
1115 isRefType(T, "DASessionRef");
1116}
1117
Ted Kremenek1d92d2c2009-01-07 00:39:56 +00001118//===----------------------------------------------------------------------===//
Ted Kremenek00daccd2008-05-05 22:11:16 +00001119// Summary creation for functions (largely uses of Core Foundation).
1120//===----------------------------------------------------------------------===//
Ted Kremenek68d73d12008-03-12 01:21:45 +00001121
Ted Kremenek7e904222009-01-12 21:45:02 +00001122static bool isRetain(FunctionDecl* FD, const char* FName) {
1123 const char* loc = strstr(FName, "Retain");
1124 return loc && loc[sizeof("Retain")-1] == '\0';
1125}
1126
1127static bool isRelease(FunctionDecl* FD, const char* FName) {
1128 const char* loc = strstr(FName, "Release");
1129 return loc && loc[sizeof("Release")-1] == '\0';
1130}
1131
Ted Kremenekf890bfe2008-06-24 03:56:45 +00001132RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekf7141592008-04-24 17:22:33 +00001133 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenek00daccd2008-05-05 22:11:16 +00001134 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenek00daccd2008-05-05 22:11:16 +00001135 if (I != FuncSummaries.end())
Ted Kremenekf7141592008-04-24 17:22:33 +00001136 return I->second;
1137
Ted Kremenekdf76e6d2009-05-04 15:34:07 +00001138 // No summary? Generate one.
Ted Kremenek7e904222009-01-12 21:45:02 +00001139 RetainSummary *S = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001140
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001141 do {
Ted Kremenek7e904222009-01-12 21:45:02 +00001142 // We generate "stop" summaries for implicitly defined functions.
1143 if (FD->isImplicit()) {
1144 S = getPersistentStopSummary();
1145 break;
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001146 }
Mike Stump11289f42009-09-09 15:08:12 +00001147
John McCall9dd450b2009-09-21 23:43:11 +00001148 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek86afde32009-01-16 18:40:33 +00001149 // function's type.
John McCall9dd450b2009-09-21 23:43:11 +00001150 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001151 const char* FName = FD->getIdentifier()->getNameStart();
Mike Stump11289f42009-09-09 15:08:12 +00001152
Ted Kremenek5f968932009-03-05 22:11:14 +00001153 // Strip away preceding '_'. Doing this here will effect all the checks
1154 // down below.
1155 while (*FName == '_') ++FName;
Mike Stump11289f42009-09-09 15:08:12 +00001156
Ted Kremenek7e904222009-01-12 21:45:02 +00001157 // Inspect the result type.
1158 QualType RetTy = FT->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00001159
Ted Kremenek7e904222009-01-12 21:45:02 +00001160 // FIXME: This should all be refactored into a chain of "summary lookup"
1161 // filters.
Ted Kremenekb4ec3fc2009-10-14 00:27:24 +00001162 assert(ScratchArgs.isEmpty());
1163
Ted Kremenekea675cf2009-06-11 18:17:24 +00001164 switch (strlen(FName)) {
1165 default: break;
Ted Kremenek80816ac2009-10-13 22:55:33 +00001166 case 14:
1167 if (!memcmp(FName, "pthread_create", 14)) {
1168 // Part of: <rdar://problem/7299394>. This will be addressed
1169 // better with IPA.
1170 S = getPersistentStopSummary();
1171 }
1172 break;
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001173
Ted Kremenekea675cf2009-06-11 18:17:24 +00001174 case 17:
1175 // Handle: id NSMakeCollectable(CFTypeRef)
1176 if (!memcmp(FName, "NSMakeCollectable", 17)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001177 S = (RetTy->isObjCIdType())
Ted Kremenekea675cf2009-06-11 18:17:24 +00001178 ? getUnarySummary(FT, cfmakecollectable)
1179 : getPersistentStopSummary();
1180 }
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001181 else if (!memcmp(FName, "IOBSDNameMatching", 17) ||
1182 !memcmp(FName, "IOServiceMatching", 17)) {
1183 // Part of <rdar://problem/6961230>. (IOKit)
1184 // This should be addressed using a API table.
1185 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1186 DoNothing, DoNothing);
1187 }
Ted Kremenekea675cf2009-06-11 18:17:24 +00001188 break;
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001189
1190 case 21:
1191 if (!memcmp(FName, "IOServiceNameMatching", 21)) {
1192 // Part of <rdar://problem/6961230>. (IOKit)
1193 // This should be addressed using a API table.
1194 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1195 DoNothing, DoNothing);
1196 }
1197 break;
1198
1199 case 24:
1200 if (!memcmp(FName, "IOServiceAddNotification", 24)) {
1201 // Part of <rdar://problem/6961230>. (IOKit)
1202 // This should be addressed using a API table.
1203 ScratchArgs = AF.Add(ScratchArgs, 2, DecRef);
Ted Kremenek55adb822009-10-15 22:25:12 +00001204 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing,DoNothing);
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001205 }
1206 break;
Mike Stump11289f42009-09-09 15:08:12 +00001207
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001208 case 25:
1209 if (!memcmp(FName, "IORegistryEntryIDMatching", 25)) {
1210 // Part of <rdar://problem/6961230>. (IOKit)
1211 // This should be addressed using a API table.
1212 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1213 DoNothing, DoNothing);
1214 }
1215 break;
Mike Stump11289f42009-09-09 15:08:12 +00001216
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001217 case 26:
1218 if (!memcmp(FName, "IOOpenFirmwarePathMatching", 26)) {
1219 // Part of <rdar://problem/6961230>. (IOKit)
1220 // This should be addressed using a API table.
1221 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
Mike Stump11289f42009-09-09 15:08:12 +00001222 DoNothing, DoNothing);
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001223 }
1224 break;
1225
Ted Kremenekea675cf2009-06-11 18:17:24 +00001226 case 27:
1227 if (!memcmp(FName, "IOServiceGetMatchingService", 27)) {
1228 // Part of <rdar://problem/6961230>.
1229 // This should be addressed using a API table.
Ted Kremenekea675cf2009-06-11 18:17:24 +00001230 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Mike Stump11289f42009-09-09 15:08:12 +00001231 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekea675cf2009-06-11 18:17:24 +00001232 }
1233 break;
1234
1235 case 28:
1236 if (!memcmp(FName, "IOServiceGetMatchingServices", 28)) {
1237 // FIXES: <rdar://problem/6326900>
1238 // This should be addressed using a API table. This strcmp is also
1239 // a little gross, but there is no need to super optimize here.
Ted Kremenekea675cf2009-06-11 18:17:24 +00001240 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenekb4ec3fc2009-10-14 00:27:24 +00001241 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing,
1242 DoNothing);
1243 }
1244 else if (!memcmp(FName, "CVPixelBufferCreateWithBytes", 28)) {
1245 // FIXES: <rdar://problem/7283567>
1246 // Eventually this can be improved by recognizing that the pixel
1247 // buffer passed to CVPixelBufferCreateWithBytes is released via
1248 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek43edaa82009-11-03 05:39:12 +00001249 // FIXME: This function has an out parameter that returns an
1250 // allocated object.
Ted Kremenekb4ec3fc2009-10-14 00:27:24 +00001251 ScratchArgs = AF.Add(ScratchArgs, 7, StopTracking);
1252 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing,
1253 DoNothing);
Ted Kremenekea675cf2009-06-11 18:17:24 +00001254 }
1255 break;
Ted Kremenekd1b67db2009-11-03 05:34:07 +00001256
1257 case 29:
1258 if (!memcmp(FName, "CGBitmapContextCreateWithData", 29)) {
1259 // FIXES: <rdar://problem/7358899>
1260 // Eventually this can be improved by recognizing that 'releaseInfo'
1261 // passed to CGBitmapContextCreateWithData is released via
1262 // a callback and doing full IPA to make sure this is done correctly.
1263 ScratchArgs = AF.Add(ScratchArgs, 8, StopTracking);
Ted Kremenek43edaa82009-11-03 05:39:12 +00001264 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1265 DoNothing,DoNothing);
Ted Kremenekd1b67db2009-11-03 05:34:07 +00001266 }
1267 break;
Mike Stump11289f42009-09-09 15:08:12 +00001268
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001269 case 32:
1270 if (!memcmp(FName, "IOServiceAddMatchingNotification", 32)) {
1271 // Part of <rdar://problem/6961230>.
1272 // This should be addressed using a API table.
1273 ScratchArgs = AF.Add(ScratchArgs, 2, DecRef);
Mike Stump11289f42009-09-09 15:08:12 +00001274 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001275 }
1276 break;
Ted Kremenekb4ec3fc2009-10-14 00:27:24 +00001277
1278 case 34:
1279 if (!memcmp(FName, "CVPixelBufferCreateWithPlanarBytes", 34)) {
1280 // FIXES: <rdar://problem/7283567>
1281 // Eventually this can be improved by recognizing that the pixel
1282 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1283 // via a callback and doing full IPA to make sure this is done
1284 // correctly.
1285 ScratchArgs = AF.Add(ScratchArgs, 12, StopTracking);
1286 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing,
1287 DoNothing);
1288 }
1289 break;
Ted Kremenekea675cf2009-06-11 18:17:24 +00001290 }
Mike Stump11289f42009-09-09 15:08:12 +00001291
Ted Kremenekea675cf2009-06-11 18:17:24 +00001292 // Did we get a summary?
1293 if (S)
1294 break;
Ted Kremenek211094d2009-03-17 22:43:44 +00001295
1296 // Enable this code once the semantics of NSDeallocateObject are resolved
1297 // for GC. <rdar://problem/6619988>
1298#if 0
1299 // Handle: NSDeallocateObject(id anObject);
1300 // This method does allow 'nil' (although we don't check it now).
Mike Stump11289f42009-09-09 15:08:12 +00001301 if (strcmp(FName, "NSDeallocateObject") == 0) {
Ted Kremenek211094d2009-03-17 22:43:44 +00001302 return RetTy == Ctx.VoidTy
1303 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
1304 : getPersistentStopSummary();
1305 }
1306#endif
Ted Kremenek7e904222009-01-12 21:45:02 +00001307
1308 if (RetTy->isPointerType()) {
1309 // For CoreFoundation ('CF') types.
1310 if (isRefType(RetTy, "CF", &Ctx, FName)) {
1311 if (isRetain(FD, FName))
1312 S = getUnarySummary(FT, cfretain);
1313 else if (strstr(FName, "MakeCollectable"))
1314 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump11289f42009-09-09 15:08:12 +00001315 else
Ted Kremenek7e904222009-01-12 21:45:02 +00001316 S = getCFCreateGetRuleSummary(FD, FName);
1317
1318 break;
1319 }
1320
1321 // For CoreGraphics ('CG') types.
1322 if (isRefType(RetTy, "CG", &Ctx, FName)) {
1323 if (isRetain(FD, FName))
1324 S = getUnarySummary(FT, cfretain);
1325 else
1326 S = getCFCreateGetRuleSummary(FD, FName);
1327
1328 break;
1329 }
1330
1331 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1332 if (isRefType(RetTy, "DADisk") ||
1333 isRefType(RetTy, "DADissenter") ||
1334 isRefType(RetTy, "DASessionRef")) {
1335 S = getCFCreateGetRuleSummary(FD, FName);
1336 break;
1337 }
Mike Stump11289f42009-09-09 15:08:12 +00001338
Ted Kremenek7e904222009-01-12 21:45:02 +00001339 break;
1340 }
1341
1342 // Check for release functions, the only kind of functions that we care
1343 // about that don't return a pointer type.
1344 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek5f968932009-03-05 22:11:14 +00001345 // Test for 'CGCF'.
1346 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1347 FName += 4;
1348 else
1349 FName += 2;
Mike Stump11289f42009-09-09 15:08:12 +00001350
Ted Kremenek5f968932009-03-05 22:11:14 +00001351 if (isRelease(FD, FName))
Ted Kremenek7e904222009-01-12 21:45:02 +00001352 S = getUnarySummary(FT, cfrelease);
1353 else {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001354 assert (ScratchArgs.isEmpty());
Ted Kremeneked90de42009-01-29 22:45:13 +00001355 // Remaining CoreFoundation and CoreGraphics functions.
1356 // We use to assume that they all strictly followed the ownership idiom
1357 // and that ownership cannot be transferred. While this is technically
1358 // correct, many methods allow a tracked object to escape. For example:
1359 //
Mike Stump11289f42009-09-09 15:08:12 +00001360 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremeneked90de42009-01-29 22:45:13 +00001361 // CFDictionaryAddValue(y, key, x);
Mike Stump11289f42009-09-09 15:08:12 +00001362 // CFRelease(x);
Ted Kremeneked90de42009-01-29 22:45:13 +00001363 // ... it is okay to use 'x' since 'y' has a reference to it
1364 //
1365 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekd982f002009-08-20 00:57:22 +00001366 // function name contains "InsertValue", "SetValue", "AddValue",
1367 // "AppendValue", or "SetAttribute", then we assume that arguments may
1368 // "escape." This means that something else holds on to the object,
1369 // allowing it be used even after its local retain count drops to 0.
Ted Kremeneked90de42009-01-29 22:45:13 +00001370 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1371 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenek0ca23d32009-02-05 22:34:53 +00001372 CStrInCStrNoCase(FName, "SetValue") ||
Ted Kremenekd982f002009-08-20 00:57:22 +00001373 CStrInCStrNoCase(FName, "AppendValue") ||
1374 CStrInCStrNoCase(FName, "SetAttribute"))
Ted Kremeneked90de42009-01-29 22:45:13 +00001375 ? MayEscape : DoNothing;
Mike Stump11289f42009-09-09 15:08:12 +00001376
Ted Kremeneked90de42009-01-29 22:45:13 +00001377 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek7e904222009-01-12 21:45:02 +00001378 }
1379 }
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001380 }
1381 while (0);
Mike Stump11289f42009-09-09 15:08:12 +00001382
Ted Kremenek1d9a2672009-05-04 05:31:22 +00001383 if (!S)
1384 S = getDefaultSummary();
Ted Kremenekf7141592008-04-24 17:22:33 +00001385
Ted Kremenekc2de7272009-05-09 02:58:13 +00001386 // Annotations override defaults.
1387 assert(S);
1388 updateSummaryFromAnnotations(*S, FD);
Mike Stump11289f42009-09-09 15:08:12 +00001389
Ted Kremenek00daccd2008-05-05 22:11:16 +00001390 FuncSummaries[FD] = S;
Mike Stump11289f42009-09-09 15:08:12 +00001391 return S;
Ted Kremenekea6507f2008-03-06 00:08:09 +00001392}
1393
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001394RetainSummary*
1395RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1396 const char* FName) {
Mike Stump11289f42009-09-09 15:08:12 +00001397
Ted Kremenek875db812008-05-05 16:51:50 +00001398 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1399 return getCFSummaryCreateRule(FD);
Mike Stump11289f42009-09-09 15:08:12 +00001400
Ted Kremenek875db812008-05-05 16:51:50 +00001401 if (strstr(FName, "Get"))
1402 return getCFSummaryGetRule(FD);
Mike Stump11289f42009-09-09 15:08:12 +00001403
Ted Kremenekff606a12009-05-04 04:57:00 +00001404 return getDefaultSummary();
Ted Kremenek875db812008-05-05 16:51:50 +00001405}
1406
Ted Kremenek00daccd2008-05-05 22:11:16 +00001407RetainSummary*
Ted Kremenek82157a12009-02-23 16:51:39 +00001408RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1409 UnaryFuncKind func) {
1410
Ted Kremenek7e904222009-01-12 21:45:02 +00001411 // Sanity check that this is *really* a unary function. This can
1412 // happen if people do weird things.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001413 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek7e904222009-01-12 21:45:02 +00001414 if (!FTP || FTP->getNumArgs() != 1)
1415 return getPersistentStopSummary();
Mike Stump11289f42009-09-09 15:08:12 +00001416
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001417 assert (ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001418
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001419 switch (func) {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001420 case cfretain: {
1421 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremenek1df2f3a2008-05-22 17:31:13 +00001422 return getPersistentSummary(RetEffect::MakeAlias(0),
1423 DoNothing, DoNothing);
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001424 }
Mike Stump11289f42009-09-09 15:08:12 +00001425
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001426 case cfrelease: {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001427 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremenek1df2f3a2008-05-22 17:31:13 +00001428 return getPersistentSummary(RetEffect::MakeNoRet(),
1429 DoNothing, DoNothing);
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001430 }
Mike Stump11289f42009-09-09 15:08:12 +00001431
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001432 case cfmakecollectable: {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001433 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Mike Stump11289f42009-09-09 15:08:12 +00001434 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001435 }
Mike Stump11289f42009-09-09 15:08:12 +00001436
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001437 default:
Ted Kremenek875db812008-05-05 16:51:50 +00001438 assert (false && "Not a supported unary function.");
Ted Kremenekff606a12009-05-04 04:57:00 +00001439 return getDefaultSummary();
Ted Kremenek4b772092008-04-10 23:44:06 +00001440 }
Ted Kremenek68d73d12008-03-12 01:21:45 +00001441}
1442
Ted Kremenek00daccd2008-05-05 22:11:16 +00001443RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001444 assert (ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001445
Ted Kremenekae529272008-07-09 18:11:16 +00001446 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001447 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1448 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekae529272008-07-09 18:11:16 +00001449 }
Mike Stump11289f42009-09-09 15:08:12 +00001450
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001451 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek68d73d12008-03-12 01:21:45 +00001452}
1453
Ted Kremenek00daccd2008-05-05 22:11:16 +00001454RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Mike Stump11289f42009-09-09 15:08:12 +00001455 assert (ScratchArgs.isEmpty());
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001456 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1457 DoNothing, DoNothing);
Ted Kremenek68d73d12008-03-12 01:21:45 +00001458}
1459
Ted Kremenek819e9b62008-03-11 06:39:11 +00001460//===----------------------------------------------------------------------===//
Ted Kremenek00daccd2008-05-05 22:11:16 +00001461// Summary creation for Selectors.
1462//===----------------------------------------------------------------------===//
1463
Ted Kremenekcb2e6362008-05-06 15:44:25 +00001464RetainSummary*
Ted Kremenek0b50fb12009-04-29 05:04:30 +00001465RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Mike Stump11289f42009-09-09 15:08:12 +00001466 assert(ScratchArgs.isEmpty());
Ted Kremenek1272f702009-05-12 20:06:54 +00001467 // 'init' methods conceptually return a newly allocated object and claim
Mike Stump11289f42009-09-09 15:08:12 +00001468 // the receiver.
Ted Kremenek1272f702009-05-12 20:06:54 +00001469 if (isTrackedObjCObjectType(RetTy) || isTrackedCFObjectType(RetTy))
Ted Kremeneka03705c2009-06-05 23:18:01 +00001470 return getPersistentSummary(ObjCInitRetE, DecRefMsg);
Mike Stump11289f42009-09-09 15:08:12 +00001471
Ted Kremenek1272f702009-05-12 20:06:54 +00001472 return getDefaultSummary();
Ted Kremenek3d1e9722008-05-05 23:55:01 +00001473}
Ted Kremenekc2de7272009-05-09 02:58:13 +00001474
1475void
1476RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1477 const FunctionDecl *FD) {
1478 if (!FD)
1479 return;
1480
Ted Kremenekea675cf2009-06-11 18:17:24 +00001481 QualType RetTy = FD->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00001482
Ted Kremenekc2de7272009-05-09 02:58:13 +00001483 // Determine if there is a special return effect for this method.
Ted Kremenekea1c2212009-06-05 23:00:33 +00001484 if (isTrackedObjCObjectType(RetTy)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001485 if (FD->getAttr<NSReturnsRetainedAttr>()) {
Ted Kremenekc2de7272009-05-09 02:58:13 +00001486 Summ.setRetEffect(ObjCAllocRetE);
1487 }
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001488 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
Ted Kremenekea1c2212009-06-05 23:00:33 +00001489 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekea675cf2009-06-11 18:17:24 +00001490 }
1491 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001492 else if (RetTy->getAs<PointerType>()) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001493 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Ted Kremenekc2de7272009-05-09 02:58:13 +00001494 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1495 }
1496 }
1497}
1498
1499void
1500RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1501 const ObjCMethodDecl *MD) {
1502 if (!MD)
1503 return;
1504
Ted Kremenek0578e432009-07-06 18:30:43 +00001505 bool isTrackedLoc = false;
Mike Stump11289f42009-09-09 15:08:12 +00001506
Ted Kremenekc2de7272009-05-09 02:58:13 +00001507 // Determine if there is a special return effect for this method.
1508 if (isTrackedObjCObjectType(MD->getResultType())) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001509 if (MD->getAttr<NSReturnsRetainedAttr>()) {
Ted Kremenekc2de7272009-05-09 02:58:13 +00001510 Summ.setRetEffect(ObjCAllocRetE);
Ted Kremenek0578e432009-07-06 18:30:43 +00001511 return;
Ted Kremenekc2de7272009-05-09 02:58:13 +00001512 }
Mike Stump11289f42009-09-09 15:08:12 +00001513
Ted Kremenek0578e432009-07-06 18:30:43 +00001514 isTrackedLoc = true;
Ted Kremenekc2de7272009-05-09 02:58:13 +00001515 }
Mike Stump11289f42009-09-09 15:08:12 +00001516
Ted Kremenek0578e432009-07-06 18:30:43 +00001517 if (!isTrackedLoc)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001518 isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
Mike Stump11289f42009-09-09 15:08:12 +00001519
Ted Kremenek0578e432009-07-06 18:30:43 +00001520 if (isTrackedLoc && MD->getAttr<CFReturnsRetainedAttr>())
1521 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekc2de7272009-05-09 02:58:13 +00001522}
1523
Ted Kremenekcb2e6362008-05-06 15:44:25 +00001524RetainSummary*
Ted Kremenek223a7d52009-04-29 23:03:22 +00001525RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1526 Selector S, QualType RetTy) {
Ted Kremenek6a966b22009-04-24 21:56:17 +00001527
Ted Kremenek7686ffa2009-04-29 00:42:39 +00001528 if (MD) {
Ted Kremenek6e86caf2009-04-24 18:00:17 +00001529 // Scan the method decl for 'void*' arguments. These should be treated
1530 // as 'StopTracking' because they are often used with delegates.
1531 // Delegates are a frequent form of false positives with the retain
1532 // count checker.
1533 unsigned i = 0;
1534 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1535 E = MD->param_end(); I != E; ++I, ++i)
1536 if (ParmVarDecl *PD = *I) {
1537 QualType Ty = Ctx.getCanonicalType(PD->getType());
1538 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001539 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek6e86caf2009-04-24 18:00:17 +00001540 }
1541 }
Mike Stump11289f42009-09-09 15:08:12 +00001542
Ted Kremenek6a966b22009-04-24 21:56:17 +00001543 // Any special effect for the receiver?
1544 ArgEffect ReceiverEff = DoNothing;
Mike Stump11289f42009-09-09 15:08:12 +00001545
Ted Kremenek6a966b22009-04-24 21:56:17 +00001546 // If one of the arguments in the selector has the keyword 'delegate' we
1547 // should stop tracking the reference count for the receiver. This is
1548 // because the reference count is quite possibly handled by a delegate
1549 // method.
1550 if (S.isKeywordSelector()) {
1551 const std::string &str = S.getAsString();
1552 assert(!str.empty());
1553 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1554 }
Mike Stump11289f42009-09-09 15:08:12 +00001555
Ted Kremenek60746a02009-04-23 23:08:22 +00001556 // Look for methods that return an owned object.
Mike Stump11289f42009-09-09 15:08:12 +00001557 if (isTrackedObjCObjectType(RetTy)) {
Ted Kremenek4b59ccb2009-05-03 06:08:32 +00001558 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1559 // by instance methods.
Ted Kremenek32819772009-05-15 15:49:00 +00001560 RetEffect E = followsFundamentalRule(S)
1561 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Mike Stump11289f42009-09-09 15:08:12 +00001562
1563 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek6e86caf2009-04-24 18:00:17 +00001564 }
Mike Stump11289f42009-09-09 15:08:12 +00001565
Ted Kremenek4b59ccb2009-05-03 06:08:32 +00001566 // Look for methods that return an owned core foundation object.
1567 if (isTrackedCFObjectType(RetTy)) {
Ted Kremenek32819772009-05-15 15:49:00 +00001568 RetEffect E = followsFundamentalRule(S)
1569 ? RetEffect::MakeOwned(RetEffect::CF, true)
1570 : RetEffect::MakeNotOwned(RetEffect::CF);
Mike Stump11289f42009-09-09 15:08:12 +00001571
Ted Kremenek4b59ccb2009-05-03 06:08:32 +00001572 return getPersistentSummary(E, ReceiverEff, MayEscape);
1573 }
Mike Stump11289f42009-09-09 15:08:12 +00001574
Ted Kremenek4b59ccb2009-05-03 06:08:32 +00001575 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenekff606a12009-05-04 04:57:00 +00001576 return getDefaultSummary();
Mike Stump11289f42009-09-09 15:08:12 +00001577
Ted Kremenek1d9a2672009-05-04 05:31:22 +00001578 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek60746a02009-04-23 23:08:22 +00001579}
1580
1581RetainSummary*
Ted Kremeneka2968e52009-11-13 01:54:21 +00001582RetainSummaryManager::getInstanceMethodSummary(const ObjCMessageExpr *ME,
1583 const GRState *state,
1584 const LocationContext *LC) {
1585
1586 // We need the type-information of the tracked receiver object
1587 // Retrieve it from the state.
1588 const Expr *Receiver = ME->getReceiver();
1589 const ObjCInterfaceDecl* ID = 0;
1590
1591 // FIXME: Is this really working as expected? There are cases where
1592 // we just use the 'ID' from the message expression.
1593 SVal receiverV = state->getSValAsScalarOrLoc(Receiver);
1594
1595 // FIXME: Eventually replace the use of state->get<RefBindings> with
1596 // a generic API for reasoning about the Objective-C types of symbolic
1597 // objects.
1598 if (SymbolRef Sym = receiverV.getAsLocSymbol())
1599 if (const RefVal *T = state->get<RefBindings>(Sym))
1600 if (const ObjCObjectPointerType* PT =
1601 T->getType()->getAs<ObjCObjectPointerType>())
1602 ID = PT->getInterfaceDecl();
1603
1604 // FIXME: this is a hack. This may or may not be the actual method
1605 // that is called.
1606 if (!ID) {
1607 if (const ObjCObjectPointerType *PT =
1608 Receiver->getType()->getAs<ObjCObjectPointerType>())
1609 ID = PT->getInterfaceDecl();
1610 }
1611
1612 // FIXME: The receiver could be a reference to a class, meaning that
1613 // we should use the class method.
1614 RetainSummary *Summ = getInstanceMethodSummary(ME, ID);
1615
1616 // Special-case: are we sending a mesage to "self"?
1617 // This is a hack. When we have full-IP this should be removed.
1618 if (isa<ObjCMethodDecl>(LC->getDecl())) {
1619 if (const loc::MemRegionVal *L = dyn_cast<loc::MemRegionVal>(&receiverV)) {
1620 // Get the region associated with 'self'.
1621 if (const ImplicitParamDecl *SelfDecl = LC->getSelfDecl()) {
1622 SVal SelfVal = state->getSVal(state->getRegion(SelfDecl, LC));
1623 if (L->StripCasts() == SelfVal.getAsRegion()) {
1624 // Update the summary to make the default argument effect
1625 // 'StopTracking'.
1626 Summ = copySummary(Summ);
1627 Summ->setDefaultArgEffect(StopTracking);
1628 }
1629 }
1630 }
1631 }
1632
1633 return Summ ? Summ : getDefaultSummary();
1634}
1635
1636RetainSummary*
Ted Kremenek38724302009-04-29 17:09:14 +00001637RetainSummaryManager::getInstanceMethodSummary(Selector S,
1638 IdentifierInfo *ClsName,
Ted Kremenek223a7d52009-04-29 23:03:22 +00001639 const ObjCInterfaceDecl* ID,
1640 const ObjCMethodDecl *MD,
Ted Kremenek38724302009-04-29 17:09:14 +00001641 QualType RetTy) {
Ted Kremenekcb2e6362008-05-06 15:44:25 +00001642
Ted Kremenek0b50fb12009-04-29 05:04:30 +00001643 // Look up a summary in our summary cache.
Ted Kremenek8be51382009-07-21 23:27:57 +00001644 RetainSummary *Summ = ObjCMethodSummaries.find(ID, ClsName, S);
Mike Stump11289f42009-09-09 15:08:12 +00001645
Ted Kremenek8be51382009-07-21 23:27:57 +00001646 if (!Summ) {
1647 assert(ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001648
Ted Kremenek8be51382009-07-21 23:27:57 +00001649 // "initXXX": pass-through for receiver.
1650 if (deriveNamingConvention(S) == InitRule)
1651 Summ = getInitMethodSummary(RetTy);
1652 else
1653 Summ = getCommonMethodSummary(MD, S, RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00001654
Ted Kremenek8be51382009-07-21 23:27:57 +00001655 // Annotations override defaults.
1656 updateSummaryFromAnnotations(*Summ, MD);
Mike Stump11289f42009-09-09 15:08:12 +00001657
Ted Kremenek8be51382009-07-21 23:27:57 +00001658 // Memoize the summary.
1659 ObjCMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
1660 }
Mike Stump11289f42009-09-09 15:08:12 +00001661
Ted Kremenekf27110f2009-04-23 19:11:35 +00001662 return Summ;
Ted Kremenek3d1e9722008-05-05 23:55:01 +00001663}
1664
Ted Kremenek767d0742008-05-06 21:26:51 +00001665RetainSummary*
Ted Kremenek7686ffa2009-04-29 00:42:39 +00001666RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek223a7d52009-04-29 23:03:22 +00001667 const ObjCInterfaceDecl *ID,
1668 const ObjCMethodDecl *MD,
1669 QualType RetTy) {
Ted Kremenek8a5ad392009-04-24 17:50:11 +00001670
Ted Kremenek7686ffa2009-04-29 00:42:39 +00001671 assert(ClsName && "Class name must be specified.");
Mike Stump11289f42009-09-09 15:08:12 +00001672 RetainSummary *Summ = ObjCClassMethodSummaries.find(ID, ClsName, S);
1673
Ted Kremenek8be51382009-07-21 23:27:57 +00001674 if (!Summ) {
1675 Summ = getCommonMethodSummary(MD, S, RetTy);
1676 // Annotations override defaults.
1677 updateSummaryFromAnnotations(*Summ, MD);
1678 // Memoize the summary.
1679 ObjCClassMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
1680 }
Mike Stump11289f42009-09-09 15:08:12 +00001681
Ted Kremenekf27110f2009-04-23 19:11:35 +00001682 return Summ;
Ted Kremenek767d0742008-05-06 21:26:51 +00001683}
1684
Mike Stump11289f42009-09-09 15:08:12 +00001685void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek9157fbb2009-05-07 23:40:42 +00001686 assert(ScratchArgs.isEmpty());
1687 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Mike Stump11289f42009-09-09 15:08:12 +00001688
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001689 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1690 // NSObject and its derivatives.
1691 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1692 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1693 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001694
1695 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek55adb822009-10-15 22:25:12 +00001696 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001697 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump11289f42009-09-09 15:08:12 +00001698
Ted Kremenek0747e7e2008-10-21 15:53:15 +00001699 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001700 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek55adb822009-10-15 22:25:12 +00001701 addClassMethSummary("NSAutoreleasePool", "addObject",
1702 getPersistentSummary(RetEffect::MakeNoRet(),
1703 DoNothing, Autorelease));
Mike Stump11289f42009-09-09 15:08:12 +00001704
Ted Kremenek4e45d802009-10-15 22:26:21 +00001705 // Create a summary for [NSCursor dragCopyCursor].
1706 addClassMethSummary("NSCursor", "dragCopyCursor",
1707 getPersistentSummary(RetEffect::MakeNoRet(), DoNothing,
1708 DoNothing));
1709
Ted Kremenek8a5ad392009-04-24 17:50:11 +00001710 // Create the summaries for [NSObject performSelector...]. We treat
1711 // these as 'stop tracking' for the arguments because they are often
1712 // used for delegates that can release the object. When we have better
1713 // inter-procedural analysis we can potentially do something better. This
1714 // workaround is to remove false positives.
1715 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1716 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1717 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1718 "afterDelay", NULL);
1719 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1720 "afterDelay", "inModes", NULL);
1721 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1722 "withObject", "waitUntilDone", NULL);
1723 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1724 "withObject", "waitUntilDone", "modes", NULL);
1725 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1726 "withObject", "waitUntilDone", NULL);
1727 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1728 "withObject", "waitUntilDone", "modes", NULL);
1729 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1730 "withObject", NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001731
Ted Kremenekf9fa3cb2009-05-14 21:29:16 +00001732 // Specially handle NSData.
1733 RetainSummary *dataWithBytesNoCopySumm =
1734 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC), DoNothing,
1735 DoNothing);
1736 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1737 "dataWithBytesNoCopy", "length", NULL);
1738 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1739 "dataWithBytesNoCopy", "length", "freeWhenDone", NULL);
Ted Kremenek0806f912008-05-06 00:30:21 +00001740}
1741
Ted Kremenekea736c52008-06-23 22:21:20 +00001742void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump11289f42009-09-09 15:08:12 +00001743
1744 assert (ScratchArgs.isEmpty());
1745
Ted Kremenek767d0742008-05-06 21:26:51 +00001746 // Create the "init" selector. It just acts as a pass-through for the
1747 // receiver.
Mike Stump11289f42009-09-09 15:08:12 +00001748 RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenek815fbb62009-08-20 05:13:36 +00001749 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1750
1751 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1752 // claims the receiver and returns a retained object.
1753 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1754 InitSumm);
Mike Stump11289f42009-09-09 15:08:12 +00001755
Ted Kremenek767d0742008-05-06 21:26:51 +00001756 // The next methods are allocators.
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001757 RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
Mike Stump11289f42009-09-09 15:08:12 +00001758 RetainSummary *CFAllocSumm =
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001759 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump11289f42009-09-09 15:08:12 +00001760
1761 // Create the "copy" selector.
1762 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), AllocSumm);
Ted Kremenek9551ab62008-08-12 20:41:56 +00001763
Ted Kremenekbe7c56e2008-05-06 00:38:54 +00001764 // Create the "mutableCopy" selector.
Ted Kremenek10369122009-05-20 22:39:57 +00001765 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), AllocSumm);
Mike Stump11289f42009-09-09 15:08:12 +00001766
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001767 // Create the "retain" selector.
Ted Kremenek9157fbb2009-05-07 23:40:42 +00001768 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek10369122009-05-20 22:39:57 +00001769 RetainSummary *Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001770 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001771
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001772 // Create the "release" selector.
Ted Kremenekf68490a2009-02-18 18:54:33 +00001773 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001774 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001775
Ted Kremenekbcdb4682008-05-07 21:17:39 +00001776 // Create the "drain" selector.
1777 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001778 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001779
Ted Kremenekea072e32009-03-17 19:42:23 +00001780 // Create the -dealloc summary.
1781 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1782 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001783
1784 // Create the "autorelease" selector.
Ted Kremenekc7832092009-01-28 21:44:40 +00001785 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001786 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001787
Ted Kremenek50db3d02009-02-23 17:45:03 +00001788 // Specially handle NSAutoreleasePool.
Ted Kremenekdce78462009-02-25 02:54:57 +00001789 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenek50db3d02009-02-23 17:45:03 +00001790 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenekdce78462009-02-25 02:54:57 +00001791 NewAutoreleasePool));
Mike Stump11289f42009-09-09 15:08:12 +00001792
1793 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremeneke73f2822009-02-23 02:51:29 +00001794 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1795 // self-own themselves. However, they only do this once they are displayed.
1796 // Thus, we need to track an NSWindow's display status.
1797 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek00dfe302009-03-04 23:30:42 +00001798 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek1272f702009-05-12 20:06:54 +00001799 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1800 StopTracking,
1801 StopTracking);
Mike Stump11289f42009-09-09 15:08:12 +00001802
Ted Kremenek751e7e32009-04-03 19:02:51 +00001803 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1804
Ted Kremenek00dfe302009-03-04 23:30:42 +00001805#if 0
Ted Kremenek1272f702009-05-12 20:06:54 +00001806 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek3f13f592008-08-12 18:48:50 +00001807 "styleMask", "backing", "defer", NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001808
Ted Kremenek1272f702009-05-12 20:06:54 +00001809 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenek3f13f592008-08-12 18:48:50 +00001810 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek00dfe302009-03-04 23:30:42 +00001811#endif
Mike Stump11289f42009-09-09 15:08:12 +00001812
Ted Kremenek3f13f592008-08-12 18:48:50 +00001813 // For NSPanel (which subclasses NSWindow), allocated objects are not
1814 // self-owned.
Ted Kremenek751e7e32009-04-03 19:02:51 +00001815 // FIXME: For now we don't track NSPanels. object for the same reason
1816 // as for NSWindow objects.
1817 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump11289f42009-09-09 15:08:12 +00001818
Ted Kremenek1272f702009-05-12 20:06:54 +00001819#if 0
1820 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek3f13f592008-08-12 18:48:50 +00001821 "styleMask", "backing", "defer", NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001822
Ted Kremenek1272f702009-05-12 20:06:54 +00001823 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenek3f13f592008-08-12 18:48:50 +00001824 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek1272f702009-05-12 20:06:54 +00001825#endif
Mike Stump11289f42009-09-09 15:08:12 +00001826
Ted Kremenek501ba032009-05-18 23:14:34 +00001827 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1828 // exit a method.
1829 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001830
Ted Kremenek3b2294c2008-07-18 17:24:20 +00001831 // Create NSAssertionHandler summaries.
Ted Kremenek050b91c2008-08-12 18:30:56 +00001832 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
Mike Stump11289f42009-09-09 15:08:12 +00001833 "lineNumber", "description", NULL);
1834
Ted Kremenek050b91c2008-08-12 18:30:56 +00001835 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1836 "file", "lineNumber", "description", NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001837
Ted Kremenek10369122009-05-20 22:39:57 +00001838 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1839 addInstMethSummary("QCRenderer", AllocSumm,
1840 "createSnapshotImageOfType", NULL);
1841 addInstMethSummary("QCView", AllocSumm,
1842 "createSnapshotImageOfType", NULL);
1843
Ted Kremenek96aa1462009-06-15 20:58:58 +00001844 // Create summaries for CIContext, 'createCGImage' and
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001845 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1846 // automatically garbage collected.
1847 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek10369122009-05-20 22:39:57 +00001848 "createCGImage", "fromRect", NULL);
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001849 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump11289f42009-09-09 15:08:12 +00001850 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001851 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek96aa1462009-06-15 20:58:58 +00001852 "info", NULL);
Ted Kremenekbe7c56e2008-05-06 00:38:54 +00001853}
1854
Ted Kremenek00daccd2008-05-05 22:11:16 +00001855//===----------------------------------------------------------------------===//
Ted Kremenekc52f9392009-02-24 19:15:11 +00001856// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek0747e7e2008-10-21 15:53:15 +00001857//===----------------------------------------------------------------------===//
1858
Ted Kremenekc52f9392009-02-24 19:15:11 +00001859typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1860typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1861typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenek50db3d02009-02-23 17:45:03 +00001862
Ted Kremenekc52f9392009-02-24 19:15:11 +00001863static int AutoRCIndex = 0;
Ted Kremenek0747e7e2008-10-21 15:53:15 +00001864static int AutoRBIndex = 0;
1865
Ted Kremenekc52f9392009-02-24 19:15:11 +00001866namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenekdce78462009-02-25 02:54:57 +00001867namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekc52f9392009-02-24 19:15:11 +00001868
Ted Kremenek0747e7e2008-10-21 15:53:15 +00001869namespace clang {
Ted Kremenekdce78462009-02-25 02:54:57 +00001870template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekc52f9392009-02-24 19:15:11 +00001871 : public GRStatePartialTrait<ARStack> {
Mike Stump11289f42009-09-09 15:08:12 +00001872 static inline void* GDMIndex() { return &AutoRBIndex; }
Ted Kremenekc52f9392009-02-24 19:15:11 +00001873};
1874
1875template<> struct GRStateTrait<AutoreleasePoolContents>
1876 : public GRStatePartialTrait<ARPoolContents> {
Mike Stump11289f42009-09-09 15:08:12 +00001877 static inline void* GDMIndex() { return &AutoRCIndex; }
Ted Kremenekc52f9392009-02-24 19:15:11 +00001878};
1879} // end clang namespace
Ted Kremenek0747e7e2008-10-21 15:53:15 +00001880
Ted Kremenek8c3f0042009-03-20 17:34:15 +00001881static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1882 ARStack stack = state->get<AutoreleaseStack>();
1883 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1884}
1885
Ted Kremenekd93c6e32009-06-18 01:23:53 +00001886static const GRState * SendAutorelease(const GRState *state,
1887 ARCounts::Factory &F, SymbolRef sym) {
Ted Kremenek8c3f0042009-03-20 17:34:15 +00001888
1889 SymbolRef pool = GetCurrentAutoreleasePool(state);
Ted Kremenekd93c6e32009-06-18 01:23:53 +00001890 const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool);
Ted Kremenek8c3f0042009-03-20 17:34:15 +00001891 ARCounts newCnts(0);
Mike Stump11289f42009-09-09 15:08:12 +00001892
Ted Kremenek8c3f0042009-03-20 17:34:15 +00001893 if (cnts) {
1894 const unsigned *cnt = (*cnts).lookup(sym);
1895 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1896 }
1897 else
1898 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001899
Ted Kremenekd93c6e32009-06-18 01:23:53 +00001900 return state->set<AutoreleasePoolContents>(pool, newCnts);
Ted Kremenek8c3f0042009-03-20 17:34:15 +00001901}
1902
Ted Kremenek71454892008-04-16 20:40:59 +00001903//===----------------------------------------------------------------------===//
1904// Transfer functions.
1905//===----------------------------------------------------------------------===//
1906
Ted Kremenekdb7dd9c2008-08-14 21:16:54 +00001907namespace {
Mike Stump11289f42009-09-09 15:08:12 +00001908
Ted Kremenek1642bda2009-06-26 00:05:51 +00001909class VISIBILITY_HIDDEN CFRefCount : public GRTransferFuncs {
Ted Kremenek396f4362008-04-18 03:39:05 +00001910public:
Ted Kremenek16306102008-08-13 21:24:49 +00001911 class BindingsPrinter : public GRState::Printer {
Ted Kremenek2a723e62008-03-11 19:44:10 +00001912 public:
Ted Kremenek799bb6e2009-06-24 23:06:47 +00001913 virtual void Print(llvm::raw_ostream& Out, const GRState* state,
Ted Kremenek16306102008-08-13 21:24:49 +00001914 const char* nl, const char* sep);
Ted Kremenek2a723e62008-03-11 19:44:10 +00001915 };
Ted Kremenek396f4362008-04-18 03:39:05 +00001916
1917private:
Zhongxing Xu107f7592009-08-06 12:48:26 +00001918 typedef llvm::DenseMap<const ExplodedNode*, const RetainSummary*>
Mike Stump11289f42009-09-09 15:08:12 +00001919 SummaryLogTy;
Ted Kremenek48d16452009-02-18 03:48:14 +00001920
Mike Stump11289f42009-09-09 15:08:12 +00001921 RetainSummaryManager Summaries;
Ted Kremenek48d16452009-02-18 03:48:14 +00001922 SummaryLogTy SummaryLog;
Ted Kremenek00daccd2008-05-05 22:11:16 +00001923 const LangOptions& LOpts;
Ted Kremenekc52f9392009-02-24 19:15:11 +00001924 ARCounts::Factory ARCountFactory;
Ted Kremenek87aab6c2008-08-17 03:20:02 +00001925
Ted Kremenek400aae72009-02-05 06:50:21 +00001926 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenekea072e32009-03-17 19:42:23 +00001927 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek400aae72009-02-05 06:50:21 +00001928 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenekd35272f2009-05-09 00:10:05 +00001929 BugType *overAutorelease;
Ted Kremenekdee56e32009-05-10 06:25:57 +00001930 BugType *returnNotOwnedForOwned;
Ted Kremenek400aae72009-02-05 06:50:21 +00001931 BugReporter *BR;
Mike Stump11289f42009-09-09 15:08:12 +00001932
Ted Kremenekd93c6e32009-06-18 01:23:53 +00001933 const GRState * Update(const GRState * state, SymbolRef sym, RefVal V, ArgEffect E,
Ted Kremenekc52f9392009-02-24 19:15:11 +00001934 RefVal::Kind& hasErr);
1935
Zhongxing Xu20227f72009-08-06 01:32:16 +00001936 void ProcessNonLeakError(ExplodedNodeSet& Dst,
Zhongxing Xu107f7592009-08-06 12:48:26 +00001937 GRStmtNodeBuilder& Builder,
Zhongxing Xu08a2ede2009-05-12 10:10:00 +00001938 Expr* NodeExpr, Expr* ErrorExpr,
Zhongxing Xu20227f72009-08-06 01:32:16 +00001939 ExplodedNode* Pred,
Ted Kremenek5ab5a1b2008-08-13 04:27:00 +00001940 const GRState* St,
Ted Kremenekd8242f12008-12-05 02:27:51 +00001941 RefVal::Kind hasErr, SymbolRef Sym);
Mike Stump11289f42009-09-09 15:08:12 +00001942
Ted Kremenekd93c6e32009-06-18 01:23:53 +00001943 const GRState * HandleSymbolDeath(const GRState * state, SymbolRef sid, RefVal V,
Ted Kremenek884a8992009-05-08 23:09:42 +00001944 llvm::SmallVectorImpl<SymbolRef> &Leaked);
Mike Stump11289f42009-09-09 15:08:12 +00001945
Zhongxing Xu20227f72009-08-06 01:32:16 +00001946 ExplodedNode* ProcessLeaks(const GRState * state,
Ted Kremenek884a8992009-05-08 23:09:42 +00001947 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1948 GenericNodeBuilder &Builder,
1949 GRExprEngine &Eng,
Zhongxing Xu20227f72009-08-06 01:32:16 +00001950 ExplodedNode *Pred = 0);
Mike Stump11289f42009-09-09 15:08:12 +00001951
1952public:
Ted Kremenek1f352db2008-07-22 16:21:24 +00001953 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001954 : Summaries(Ctx, gcenabled),
Ted Kremenekea072e32009-03-17 19:42:23 +00001955 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1956 deallocGC(0), deallocNotOwned(0),
Ted Kremenekdee56e32009-05-10 06:25:57 +00001957 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0),
1958 returnNotOwnedForOwned(0), BR(0) {}
Mike Stump11289f42009-09-09 15:08:12 +00001959
Ted Kremenek400aae72009-02-05 06:50:21 +00001960 virtual ~CFRefCount() {}
Mike Stump11289f42009-09-09 15:08:12 +00001961
Ted Kremenek0fbbb082009-11-03 23:30:34 +00001962 void RegisterChecks(GRExprEngine &Eng);
Mike Stump11289f42009-09-09 15:08:12 +00001963
Ted Kremenekceba6ea2008-08-16 00:49:49 +00001964 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1965 Printers.push_back(new BindingsPrinter());
Ted Kremenek2a723e62008-03-11 19:44:10 +00001966 }
Mike Stump11289f42009-09-09 15:08:12 +00001967
Ted Kremenek00daccd2008-05-05 22:11:16 +00001968 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekb0f87c42008-04-30 23:47:44 +00001969 const LangOptions& getLangOptions() const { return LOpts; }
Mike Stump11289f42009-09-09 15:08:12 +00001970
Zhongxing Xu20227f72009-08-06 01:32:16 +00001971 const RetainSummary *getSummaryOfNode(const ExplodedNode *N) const {
Ted Kremenek48d16452009-02-18 03:48:14 +00001972 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1973 return I == SummaryLog.end() ? 0 : I->second;
1974 }
Mike Stump11289f42009-09-09 15:08:12 +00001975
Ted Kremenek819e9b62008-03-11 06:39:11 +00001976 // Calls.
Ted Kremenek00daccd2008-05-05 22:11:16 +00001977
Zhongxing Xu20227f72009-08-06 01:32:16 +00001978 void EvalSummary(ExplodedNodeSet& Dst,
Ted Kremenek00daccd2008-05-05 22:11:16 +00001979 GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00001980 GRStmtNodeBuilder& Builder,
Ted Kremenek00daccd2008-05-05 22:11:16 +00001981 Expr* Ex,
1982 Expr* Receiver,
Ted Kremenekff606a12009-05-04 04:57:00 +00001983 const RetainSummary& Summ,
Zhongxing Xu08a2ede2009-05-12 10:10:00 +00001984 ExprIterator arg_beg, ExprIterator arg_end,
Zhongxing Xu20227f72009-08-06 01:32:16 +00001985 ExplodedNode* Pred);
Mike Stump11289f42009-09-09 15:08:12 +00001986
Zhongxing Xu20227f72009-08-06 01:32:16 +00001987 virtual void EvalCall(ExplodedNodeSet& Dst,
Ted Kremenek626bd2d2008-03-12 21:06:49 +00001988 GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00001989 GRStmtNodeBuilder& Builder,
Zhongxing Xu27f17422008-10-17 05:57:07 +00001990 CallExpr* CE, SVal L,
Mike Stump11289f42009-09-09 15:08:12 +00001991 ExplodedNode* Pred);
1992
1993
Zhongxing Xu20227f72009-08-06 01:32:16 +00001994 virtual void EvalObjCMessageExpr(ExplodedNodeSet& Dst,
Ted Kremenek748c7ce2008-04-15 23:44:31 +00001995 GRExprEngine& Engine,
Zhongxing Xu107f7592009-08-06 12:48:26 +00001996 GRStmtNodeBuilder& Builder,
Ted Kremenek748c7ce2008-04-15 23:44:31 +00001997 ObjCMessageExpr* ME,
Zhongxing Xu20227f72009-08-06 01:32:16 +00001998 ExplodedNode* Pred);
Mike Stump11289f42009-09-09 15:08:12 +00001999
Zhongxing Xu20227f72009-08-06 01:32:16 +00002000 bool EvalObjCMessageExprAux(ExplodedNodeSet& Dst,
Ted Kremenek748c7ce2008-04-15 23:44:31 +00002001 GRExprEngine& Engine,
Zhongxing Xu107f7592009-08-06 12:48:26 +00002002 GRStmtNodeBuilder& Builder,
Ted Kremenek748c7ce2008-04-15 23:44:31 +00002003 ObjCMessageExpr* ME,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002004 ExplodedNode* Pred);
Ted Kremenek748c7ce2008-04-15 23:44:31 +00002005
Mike Stump11289f42009-09-09 15:08:12 +00002006 // Stores.
Ted Kremeneke68c0fc2009-02-14 01:43:44 +00002007 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
2008
Ted Kremenek8784a7c2008-04-11 22:25:11 +00002009 // End-of-path.
Mike Stump11289f42009-09-09 15:08:12 +00002010
Ted Kremenek8784a7c2008-04-11 22:25:11 +00002011 virtual void EvalEndPath(GRExprEngine& Engine,
Zhongxing Xu107f7592009-08-06 12:48:26 +00002012 GREndPathNodeBuilder& Builder);
Mike Stump11289f42009-09-09 15:08:12 +00002013
Zhongxing Xu20227f72009-08-06 01:32:16 +00002014 virtual void EvalDeadSymbols(ExplodedNodeSet& Dst,
Ted Kremenekb0daf2f2008-04-24 23:57:27 +00002015 GRExprEngine& Engine,
Zhongxing Xu107f7592009-08-06 12:48:26 +00002016 GRStmtNodeBuilder& Builder,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002017 ExplodedNode* Pred,
Ted Kremenek16fbfe62009-01-21 22:26:05 +00002018 Stmt* S, const GRState* state,
2019 SymbolReaper& SymReaper);
Mike Stump11289f42009-09-09 15:08:12 +00002020
Zhongxing Xu20227f72009-08-06 01:32:16 +00002021 std::pair<ExplodedNode*, const GRState *>
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002022 HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002023 ExplodedNode* Pred, GRExprEngine &Eng,
Ted Kremenekd35272f2009-05-09 00:10:05 +00002024 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremeneka506fec2008-04-17 18:12:53 +00002025 // Return statements.
Mike Stump11289f42009-09-09 15:08:12 +00002026
Zhongxing Xu20227f72009-08-06 01:32:16 +00002027 virtual void EvalReturn(ExplodedNodeSet& Dst,
Ted Kremeneka506fec2008-04-17 18:12:53 +00002028 GRExprEngine& Engine,
Zhongxing Xu107f7592009-08-06 12:48:26 +00002029 GRStmtNodeBuilder& Builder,
Ted Kremeneka506fec2008-04-17 18:12:53 +00002030 ReturnStmt* S,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002031 ExplodedNode* Pred);
Ted Kremenek4d837282008-04-18 19:23:43 +00002032
2033 // Assumptions.
2034
Ted Kremenekf9906842009-06-18 22:57:13 +00002035 virtual const GRState *EvalAssume(const GRState* state, SVal condition,
2036 bool assumption);
Ted Kremenek819e9b62008-03-11 06:39:11 +00002037};
2038
2039} // end anonymous namespace
2040
Ted Kremenek799bb6e2009-06-24 23:06:47 +00002041static void PrintPool(llvm::raw_ostream &Out, SymbolRef Sym,
2042 const GRState *state) {
Ted Kremenek8c3f0042009-03-20 17:34:15 +00002043 Out << ' ';
Ted Kremenek3e31c262009-03-26 03:35:11 +00002044 if (Sym)
2045 Out << Sym->getSymbolID();
Ted Kremenek8c3f0042009-03-20 17:34:15 +00002046 else
2047 Out << "<pool>";
2048 Out << ":{";
Mike Stump11289f42009-09-09 15:08:12 +00002049
Ted Kremenek8c3f0042009-03-20 17:34:15 +00002050 // Get the contents of the pool.
2051 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
2052 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
2053 Out << '(' << J.getKey() << ',' << J.getData() << ')';
2054
Mike Stump11289f42009-09-09 15:08:12 +00002055 Out << '}';
Ted Kremenek8c3f0042009-03-20 17:34:15 +00002056}
Ted Kremenek396f4362008-04-18 03:39:05 +00002057
Ted Kremenek799bb6e2009-06-24 23:06:47 +00002058void CFRefCount::BindingsPrinter::Print(llvm::raw_ostream& Out,
2059 const GRState* state,
Ted Kremenek16306102008-08-13 21:24:49 +00002060 const char* nl, const char* sep) {
Mike Stump11289f42009-09-09 15:08:12 +00002061
Ted Kremenekdb7dd9c2008-08-14 21:16:54 +00002062 RefBindings B = state->get<RefBindings>();
Mike Stump11289f42009-09-09 15:08:12 +00002063
Ted Kremenek16306102008-08-13 21:24:49 +00002064 if (!B.isEmpty())
Ted Kremenek2a723e62008-03-11 19:44:10 +00002065 Out << sep << nl;
Mike Stump11289f42009-09-09 15:08:12 +00002066
Ted Kremenek2a723e62008-03-11 19:44:10 +00002067 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
2068 Out << (*I).first << " : ";
2069 (*I).second.print(Out);
2070 Out << nl;
2071 }
Mike Stump11289f42009-09-09 15:08:12 +00002072
Ted Kremenekdce78462009-02-25 02:54:57 +00002073 // Print the autorelease stack.
Ted Kremenek8c3f0042009-03-20 17:34:15 +00002074 Out << sep << nl << "AR pool stack:";
Ted Kremenekdce78462009-02-25 02:54:57 +00002075 ARStack stack = state->get<AutoreleaseStack>();
Mike Stump11289f42009-09-09 15:08:12 +00002076
Ted Kremenek8c3f0042009-03-20 17:34:15 +00002077 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
2078 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
2079 PrintPool(Out, *I, state);
2080
2081 Out << nl;
Ted Kremenek2a723e62008-03-11 19:44:10 +00002082}
2083
Ted Kremenek6bd78702009-04-29 18:50:19 +00002084//===----------------------------------------------------------------------===//
2085// Error reporting.
2086//===----------------------------------------------------------------------===//
2087
2088namespace {
Mike Stump11289f42009-09-09 15:08:12 +00002089
Ted Kremenek6bd78702009-04-29 18:50:19 +00002090 //===-------------===//
2091 // Bug Descriptions. //
Mike Stump11289f42009-09-09 15:08:12 +00002092 //===-------------===//
2093
Ted Kremenek6bd78702009-04-29 18:50:19 +00002094 class VISIBILITY_HIDDEN CFRefBug : public BugType {
2095 protected:
2096 CFRefCount& TF;
Mike Stump11289f42009-09-09 15:08:12 +00002097
2098 CFRefBug(CFRefCount* tf, const char* name)
2099 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
Ted Kremenek6bd78702009-04-29 18:50:19 +00002100 public:
Mike Stump11289f42009-09-09 15:08:12 +00002101
Ted Kremenek6bd78702009-04-29 18:50:19 +00002102 CFRefCount& getTF() { return TF; }
2103 const CFRefCount& getTF() const { return TF; }
Mike Stump11289f42009-09-09 15:08:12 +00002104
Ted Kremenek6bd78702009-04-29 18:50:19 +00002105 // FIXME: Eventually remove.
2106 virtual const char* getDescription() const = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002107
Ted Kremenek6bd78702009-04-29 18:50:19 +00002108 virtual bool isLeak() const { return false; }
2109 };
Mike Stump11289f42009-09-09 15:08:12 +00002110
Ted Kremenek6bd78702009-04-29 18:50:19 +00002111 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2112 public:
2113 UseAfterRelease(CFRefCount* tf)
2114 : CFRefBug(tf, "Use-after-release") {}
Mike Stump11289f42009-09-09 15:08:12 +00002115
Ted Kremenek6bd78702009-04-29 18:50:19 +00002116 const char* getDescription() const {
2117 return "Reference-counted object is used after it is released";
Mike Stump11289f42009-09-09 15:08:12 +00002118 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002119 };
Mike Stump11289f42009-09-09 15:08:12 +00002120
Ted Kremenek6bd78702009-04-29 18:50:19 +00002121 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2122 public:
2123 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
Mike Stump11289f42009-09-09 15:08:12 +00002124
Ted Kremenek6bd78702009-04-29 18:50:19 +00002125 const char* getDescription() const {
Ted Kremenek5c22e112009-10-01 17:31:50 +00002126 return "Incorrect decrement of the reference count of an object that is "
2127 "not owned at this point by the caller";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002128 }
2129 };
Mike Stump11289f42009-09-09 15:08:12 +00002130
Ted Kremenek6bd78702009-04-29 18:50:19 +00002131 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
2132 public:
Ted Kremenekd35272f2009-05-09 00:10:05 +00002133 DeallocGC(CFRefCount *tf)
2134 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Mike Stump11289f42009-09-09 15:08:12 +00002135
Ted Kremenek6bd78702009-04-29 18:50:19 +00002136 const char *getDescription() const {
Ted Kremenekd35272f2009-05-09 00:10:05 +00002137 return "-dealloc called while using garbage collection";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002138 }
2139 };
Mike Stump11289f42009-09-09 15:08:12 +00002140
Ted Kremenek6bd78702009-04-29 18:50:19 +00002141 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
2142 public:
Ted Kremenekd35272f2009-05-09 00:10:05 +00002143 DeallocNotOwned(CFRefCount *tf)
2144 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Mike Stump11289f42009-09-09 15:08:12 +00002145
Ted Kremenek6bd78702009-04-29 18:50:19 +00002146 const char *getDescription() const {
2147 return "-dealloc sent to object that may be referenced elsewhere";
2148 }
Mike Stump11289f42009-09-09 15:08:12 +00002149 };
2150
Ted Kremenekd35272f2009-05-09 00:10:05 +00002151 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
2152 public:
Mike Stump11289f42009-09-09 15:08:12 +00002153 OverAutorelease(CFRefCount *tf) :
Ted Kremenekd35272f2009-05-09 00:10:05 +00002154 CFRefBug(tf, "Object sent -autorelease too many times") {}
Mike Stump11289f42009-09-09 15:08:12 +00002155
Ted Kremenekd35272f2009-05-09 00:10:05 +00002156 const char *getDescription() const {
Ted Kremenek3978f792009-05-10 05:11:21 +00002157 return "Object sent -autorelease too many times";
Ted Kremenekd35272f2009-05-09 00:10:05 +00002158 }
2159 };
Mike Stump11289f42009-09-09 15:08:12 +00002160
Ted Kremenekdee56e32009-05-10 06:25:57 +00002161 class VISIBILITY_HIDDEN ReturnedNotOwnedForOwned : public CFRefBug {
2162 public:
2163 ReturnedNotOwnedForOwned(CFRefCount *tf) :
2164 CFRefBug(tf, "Method should return an owned object") {}
Mike Stump11289f42009-09-09 15:08:12 +00002165
Ted Kremenekdee56e32009-05-10 06:25:57 +00002166 const char *getDescription() const {
2167 return "Object with +0 retain counts returned to caller where a +1 "
2168 "(owning) retain count is expected";
2169 }
2170 };
Mike Stump11289f42009-09-09 15:08:12 +00002171
Ted Kremenek6bd78702009-04-29 18:50:19 +00002172 class VISIBILITY_HIDDEN Leak : public CFRefBug {
2173 const bool isReturn;
2174 protected:
2175 Leak(CFRefCount* tf, const char* name, bool isRet)
2176 : CFRefBug(tf, name), isReturn(isRet) {}
2177 public:
Mike Stump11289f42009-09-09 15:08:12 +00002178
Ted Kremenek6bd78702009-04-29 18:50:19 +00002179 const char* getDescription() const { return ""; }
Mike Stump11289f42009-09-09 15:08:12 +00002180
Ted Kremenek6bd78702009-04-29 18:50:19 +00002181 bool isLeak() const { return true; }
2182 };
Mike Stump11289f42009-09-09 15:08:12 +00002183
Ted Kremenek6bd78702009-04-29 18:50:19 +00002184 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2185 public:
2186 LeakAtReturn(CFRefCount* tf, const char* name)
2187 : Leak(tf, name, true) {}
2188 };
Mike Stump11289f42009-09-09 15:08:12 +00002189
Ted Kremenek6bd78702009-04-29 18:50:19 +00002190 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2191 public:
2192 LeakWithinFunction(CFRefCount* tf, const char* name)
2193 : Leak(tf, name, false) {}
Mike Stump11289f42009-09-09 15:08:12 +00002194 };
2195
Ted Kremenek6bd78702009-04-29 18:50:19 +00002196 //===---------===//
2197 // Bug Reports. //
2198 //===---------===//
Mike Stump11289f42009-09-09 15:08:12 +00002199
Ted Kremenek6bd78702009-04-29 18:50:19 +00002200 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
2201 protected:
2202 SymbolRef Sym;
2203 const CFRefCount &TF;
2204 public:
2205 CFRefReport(CFRefBug& D, const CFRefCount &tf,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002206 ExplodedNode *n, SymbolRef sym)
Ted Kremenek3978f792009-05-10 05:11:21 +00002207 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
2208
2209 CFRefReport(CFRefBug& D, const CFRefCount &tf,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002210 ExplodedNode *n, SymbolRef sym, const char* endText)
Zhongxing Xu08a2ede2009-05-12 10:10:00 +00002211 : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {}
Mike Stump11289f42009-09-09 15:08:12 +00002212
Ted Kremenek6bd78702009-04-29 18:50:19 +00002213 virtual ~CFRefReport() {}
Mike Stump11289f42009-09-09 15:08:12 +00002214
Ted Kremenek6bd78702009-04-29 18:50:19 +00002215 CFRefBug& getBugType() {
2216 return (CFRefBug&) RangedBugReport::getBugType();
2217 }
2218 const CFRefBug& getBugType() const {
2219 return (const CFRefBug&) RangedBugReport::getBugType();
2220 }
Mike Stump11289f42009-09-09 15:08:12 +00002221
Zhongxing Xu7864b9ea2009-08-18 08:58:41 +00002222 virtual void getRanges(const SourceRange*& beg, const SourceRange*& end) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002223 if (!getBugType().isLeak())
Zhongxing Xu7864b9ea2009-08-18 08:58:41 +00002224 RangedBugReport::getRanges(beg, end);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002225 else
2226 beg = end = 0;
2227 }
Mike Stump11289f42009-09-09 15:08:12 +00002228
Ted Kremenek6bd78702009-04-29 18:50:19 +00002229 SymbolRef getSymbol() const { return Sym; }
Mike Stump11289f42009-09-09 15:08:12 +00002230
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002231 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002232 const ExplodedNode* N);
Mike Stump11289f42009-09-09 15:08:12 +00002233
Ted Kremenek6bd78702009-04-29 18:50:19 +00002234 std::pair<const char**,const char**> getExtraDescriptiveText();
Mike Stump11289f42009-09-09 15:08:12 +00002235
Zhongxing Xu20227f72009-08-06 01:32:16 +00002236 PathDiagnosticPiece* VisitNode(const ExplodedNode* N,
2237 const ExplodedNode* PrevN,
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002238 BugReporterContext& BRC);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002239 };
Ted Kremenek3978f792009-05-10 05:11:21 +00002240
Ted Kremenek6bd78702009-04-29 18:50:19 +00002241 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
2242 SourceLocation AllocSite;
2243 const MemRegion* AllocBinding;
2244 public:
2245 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002246 ExplodedNode *n, SymbolRef sym,
Ted Kremenek6bd78702009-04-29 18:50:19 +00002247 GRExprEngine& Eng);
Mike Stump11289f42009-09-09 15:08:12 +00002248
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002249 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002250 const ExplodedNode* N);
Mike Stump11289f42009-09-09 15:08:12 +00002251
Ted Kremenek6bd78702009-04-29 18:50:19 +00002252 SourceLocation getLocation() const { return AllocSite; }
Mike Stump11289f42009-09-09 15:08:12 +00002253 };
Ted Kremenek6bd78702009-04-29 18:50:19 +00002254} // end anonymous namespace
2255
Ted Kremenek0fbbb082009-11-03 23:30:34 +00002256void CFRefCount::RegisterChecks(GRExprEngine& Eng) {
2257 BugReporter &BR = Eng.getBugReporter();
2258
Ted Kremenek6bd78702009-04-29 18:50:19 +00002259 useAfterRelease = new UseAfterRelease(this);
2260 BR.Register(useAfterRelease);
Mike Stump11289f42009-09-09 15:08:12 +00002261
Ted Kremenek6bd78702009-04-29 18:50:19 +00002262 releaseNotOwned = new BadRelease(this);
2263 BR.Register(releaseNotOwned);
Mike Stump11289f42009-09-09 15:08:12 +00002264
Ted Kremenek6bd78702009-04-29 18:50:19 +00002265 deallocGC = new DeallocGC(this);
2266 BR.Register(deallocGC);
Mike Stump11289f42009-09-09 15:08:12 +00002267
Ted Kremenek6bd78702009-04-29 18:50:19 +00002268 deallocNotOwned = new DeallocNotOwned(this);
2269 BR.Register(deallocNotOwned);
Mike Stump11289f42009-09-09 15:08:12 +00002270
Ted Kremenekd35272f2009-05-09 00:10:05 +00002271 overAutorelease = new OverAutorelease(this);
2272 BR.Register(overAutorelease);
Mike Stump11289f42009-09-09 15:08:12 +00002273
Ted Kremenekdee56e32009-05-10 06:25:57 +00002274 returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this);
2275 BR.Register(returnNotOwnedForOwned);
Mike Stump11289f42009-09-09 15:08:12 +00002276
Ted Kremenek6bd78702009-04-29 18:50:19 +00002277 // First register "return" leaks.
2278 const char* name = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002279
Ted Kremenek6bd78702009-04-29 18:50:19 +00002280 if (isGCEnabled())
2281 name = "Leak of returned object when using garbage collection";
2282 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2283 name = "Leak of returned object when not using garbage collection (GC) in "
2284 "dual GC/non-GC code";
2285 else {
2286 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2287 name = "Leak of returned object";
2288 }
Mike Stump11289f42009-09-09 15:08:12 +00002289
Ted Kremenek41129692009-09-14 22:01:32 +00002290 // Leaks should not be reported if they are post-dominated by a sink.
Ted Kremenek6bd78702009-04-29 18:50:19 +00002291 leakAtReturn = new LeakAtReturn(this, name);
Ted Kremenek41129692009-09-14 22:01:32 +00002292 leakAtReturn->setSuppressOnSink(true);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002293 BR.Register(leakAtReturn);
Mike Stump11289f42009-09-09 15:08:12 +00002294
Ted Kremenek6bd78702009-04-29 18:50:19 +00002295 // Second, register leaks within a function/method.
2296 if (isGCEnabled())
Mike Stump11289f42009-09-09 15:08:12 +00002297 name = "Leak of object when using garbage collection";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002298 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2299 name = "Leak of object when not using garbage collection (GC) in "
2300 "dual GC/non-GC code";
2301 else {
2302 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2303 name = "Leak";
2304 }
Mike Stump11289f42009-09-09 15:08:12 +00002305
Ted Kremenek41129692009-09-14 22:01:32 +00002306 // Leaks should not be reported if they are post-dominated by sinks.
Ted Kremenek6bd78702009-04-29 18:50:19 +00002307 leakWithinFunction = new LeakWithinFunction(this, name);
Ted Kremenek41129692009-09-14 22:01:32 +00002308 leakWithinFunction->setSuppressOnSink(true);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002309 BR.Register(leakWithinFunction);
Mike Stump11289f42009-09-09 15:08:12 +00002310
Ted Kremenek6bd78702009-04-29 18:50:19 +00002311 // Save the reference to the BugReporter.
2312 this->BR = &BR;
2313}
2314
2315static const char* Msgs[] = {
2316 // GC only
Mike Stump11289f42009-09-09 15:08:12 +00002317 "Code is compiled to only use garbage collection",
Ted Kremenek6bd78702009-04-29 18:50:19 +00002318 // No GC.
2319 "Code is compiled to use reference counts",
2320 // Hybrid, with GC.
2321 "Code is compiled to use either garbage collection (GC) or reference counts"
Mike Stump11289f42009-09-09 15:08:12 +00002322 " (non-GC). The bug occurs with GC enabled",
Ted Kremenek6bd78702009-04-29 18:50:19 +00002323 // Hybrid, without GC
2324 "Code is compiled to use either garbage collection (GC) or reference counts"
2325 " (non-GC). The bug occurs in non-GC mode"
2326};
2327
2328std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2329 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
Mike Stump11289f42009-09-09 15:08:12 +00002330
Ted Kremenek6bd78702009-04-29 18:50:19 +00002331 switch (TF.getLangOptions().getGCMode()) {
2332 default:
2333 assert(false);
Mike Stump11289f42009-09-09 15:08:12 +00002334
Ted Kremenek6bd78702009-04-29 18:50:19 +00002335 case LangOptions::GCOnly:
2336 assert (TF.isGCEnabled());
Mike Stump11289f42009-09-09 15:08:12 +00002337 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2338
Ted Kremenek6bd78702009-04-29 18:50:19 +00002339 case LangOptions::NonGC:
2340 assert (!TF.isGCEnabled());
2341 return std::make_pair(&Msgs[1], &Msgs[1]+1);
Mike Stump11289f42009-09-09 15:08:12 +00002342
Ted Kremenek6bd78702009-04-29 18:50:19 +00002343 case LangOptions::HybridGC:
2344 if (TF.isGCEnabled())
2345 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2346 else
2347 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2348 }
2349}
2350
2351static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2352 ArgEffect X) {
2353 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2354 I!=E; ++I)
2355 if (*I == X) return true;
Mike Stump11289f42009-09-09 15:08:12 +00002356
Ted Kremenek6bd78702009-04-29 18:50:19 +00002357 return false;
2358}
2359
Zhongxing Xu20227f72009-08-06 01:32:16 +00002360PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode* N,
2361 const ExplodedNode* PrevN,
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002362 BugReporterContext& BRC) {
Mike Stump11289f42009-09-09 15:08:12 +00002363
Ted Kremenek051a03d2009-05-13 07:12:33 +00002364 if (!isa<PostStmt>(N->getLocation()))
2365 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002366
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002367 // Check if the type state has changed.
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002368 const GRState *PrevSt = PrevN->getState();
2369 const GRState *CurrSt = N->getState();
Mike Stump11289f42009-09-09 15:08:12 +00002370
2371 const RefVal* CurrT = CurrSt->get<RefBindings>(Sym);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002372 if (!CurrT) return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002373
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002374 const RefVal &CurrV = *CurrT;
2375 const RefVal *PrevT = PrevSt->get<RefBindings>(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002376
Ted Kremenek6bd78702009-04-29 18:50:19 +00002377 // Create a string buffer to constain all the useful things we want
2378 // to tell the user.
2379 std::string sbuf;
2380 llvm::raw_string_ostream os(sbuf);
Mike Stump11289f42009-09-09 15:08:12 +00002381
Ted Kremenek6bd78702009-04-29 18:50:19 +00002382 // This is the allocation site since the previous node had no bindings
2383 // for this symbol.
2384 if (!PrevT) {
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002385 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00002386
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002387 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002388 // Get the name of the callee (if it is available).
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002389 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002390 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2391 os << "Call to function '" << FD->getNameAsString() <<'\'';
2392 else
Mike Stump11289f42009-09-09 15:08:12 +00002393 os << "function call";
2394 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002395 else {
2396 assert (isa<ObjCMessageExpr>(S));
2397 os << "Method";
2398 }
Mike Stump11289f42009-09-09 15:08:12 +00002399
Ted Kremenek6bd78702009-04-29 18:50:19 +00002400 if (CurrV.getObjKind() == RetEffect::CF) {
2401 os << " returns a Core Foundation object with a ";
2402 }
2403 else {
2404 assert (CurrV.getObjKind() == RetEffect::ObjC);
2405 os << " returns an Objective-C object with a ";
2406 }
Mike Stump11289f42009-09-09 15:08:12 +00002407
Ted Kremenek6bd78702009-04-29 18:50:19 +00002408 if (CurrV.isOwned()) {
2409 os << "+1 retain count (owning reference).";
Mike Stump11289f42009-09-09 15:08:12 +00002410
Ted Kremenek6bd78702009-04-29 18:50:19 +00002411 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2412 assert(CurrV.getObjKind() == RetEffect::CF);
2413 os << " "
2414 "Core Foundation objects are not automatically garbage collected.";
2415 }
2416 }
2417 else {
2418 assert (CurrV.isNotOwned());
2419 os << "+0 retain count (non-owning reference).";
2420 }
Mike Stump11289f42009-09-09 15:08:12 +00002421
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002422 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002423 return new PathDiagnosticEventPiece(Pos, os.str());
2424 }
Mike Stump11289f42009-09-09 15:08:12 +00002425
Ted Kremenek6bd78702009-04-29 18:50:19 +00002426 // Gather up the effects that were performed on the object at this
2427 // program point
2428 llvm::SmallVector<ArgEffect, 2> AEffects;
Mike Stump11289f42009-09-09 15:08:12 +00002429
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002430 if (const RetainSummary *Summ =
2431 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002432 // We only have summaries attached to nodes after evaluating CallExpr and
2433 // ObjCMessageExprs.
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002434 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00002435
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002436 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002437 // Iterate through the parameter expressions and see if the symbol
2438 // was ever passed as an argument.
2439 unsigned i = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002440
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002441 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenek6bd78702009-04-29 18:50:19 +00002442 AI!=AE; ++AI, ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002443
Ted Kremenek6bd78702009-04-29 18:50:19 +00002444 // Retrieve the value of the argument. Is it the symbol
2445 // we are interested in?
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002446 if (CurrSt->getSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
Ted Kremenek6bd78702009-04-29 18:50:19 +00002447 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002448
Ted Kremenek6bd78702009-04-29 18:50:19 +00002449 // We have an argument. Get the effect!
2450 AEffects.push_back(Summ->getArg(i));
2451 }
2452 }
Mike Stump11289f42009-09-09 15:08:12 +00002453 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002454 if (const Expr *receiver = ME->getReceiver())
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002455 if (CurrSt->getSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002456 // The symbol we are tracking is the receiver.
2457 AEffects.push_back(Summ->getReceiverEffect());
2458 }
2459 }
2460 }
Mike Stump11289f42009-09-09 15:08:12 +00002461
Ted Kremenek6bd78702009-04-29 18:50:19 +00002462 do {
2463 // Get the previous type state.
2464 RefVal PrevV = *PrevT;
Mike Stump11289f42009-09-09 15:08:12 +00002465
Ted Kremenek6bd78702009-04-29 18:50:19 +00002466 // Specially handle -dealloc.
2467 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2468 // Determine if the object's reference count was pushed to zero.
2469 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2470 // We may not have transitioned to 'release' if we hit an error.
2471 // This case is handled elsewhere.
2472 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek3a0516b2009-05-08 20:01:42 +00002473 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002474 os << "Object released by directly sending the '-dealloc' message";
2475 break;
2476 }
2477 }
Mike Stump11289f42009-09-09 15:08:12 +00002478
Ted Kremenek6bd78702009-04-29 18:50:19 +00002479 // Specially handle CFMakeCollectable and friends.
2480 if (contains(AEffects, MakeCollectable)) {
2481 // Get the name of the function.
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002482 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002483 SVal X = CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002484 const FunctionDecl* FD = X.getAsFunctionDecl();
2485 const std::string& FName = FD->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00002486
Ted Kremenek6bd78702009-04-29 18:50:19 +00002487 if (TF.isGCEnabled()) {
2488 // Determine if the object's reference count was pushed to zero.
2489 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump11289f42009-09-09 15:08:12 +00002490
Ted Kremenek6bd78702009-04-29 18:50:19 +00002491 os << "In GC mode a call to '" << FName
2492 << "' decrements an object's retain count and registers the "
2493 "object with the garbage collector. ";
Mike Stump11289f42009-09-09 15:08:12 +00002494
Ted Kremenek6bd78702009-04-29 18:50:19 +00002495 if (CurrV.getKind() == RefVal::Released) {
2496 assert(CurrV.getCount() == 0);
2497 os << "Since it now has a 0 retain count the object can be "
2498 "automatically collected by the garbage collector.";
2499 }
2500 else
2501 os << "An object must have a 0 retain count to be garbage collected. "
2502 "After this call its retain count is +" << CurrV.getCount()
2503 << '.';
2504 }
Mike Stump11289f42009-09-09 15:08:12 +00002505 else
Ted Kremenek6bd78702009-04-29 18:50:19 +00002506 os << "When GC is not enabled a call to '" << FName
2507 << "' has no effect on its argument.";
Mike Stump11289f42009-09-09 15:08:12 +00002508
Ted Kremenek6bd78702009-04-29 18:50:19 +00002509 // Nothing more to say.
2510 break;
2511 }
Mike Stump11289f42009-09-09 15:08:12 +00002512
2513 // Determine if the typestate has changed.
Ted Kremenek6bd78702009-04-29 18:50:19 +00002514 if (!(PrevV == CurrV))
2515 switch (CurrV.getKind()) {
2516 case RefVal::Owned:
2517 case RefVal::NotOwned:
Mike Stump11289f42009-09-09 15:08:12 +00002518
Ted Kremenek3a0516b2009-05-08 20:01:42 +00002519 if (PrevV.getCount() == CurrV.getCount()) {
2520 // Did an autorelease message get sent?
2521 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2522 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002523
Zhongxing Xu08a2ede2009-05-12 10:10:00 +00002524 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenek3978f792009-05-10 05:11:21 +00002525 os << "Object sent -autorelease message";
Ted Kremenek3a0516b2009-05-08 20:01:42 +00002526 break;
2527 }
Mike Stump11289f42009-09-09 15:08:12 +00002528
Ted Kremenek6bd78702009-04-29 18:50:19 +00002529 if (PrevV.getCount() > CurrV.getCount())
2530 os << "Reference count decremented.";
2531 else
2532 os << "Reference count incremented.";
Mike Stump11289f42009-09-09 15:08:12 +00002533
Ted Kremenek6bd78702009-04-29 18:50:19 +00002534 if (unsigned Count = CurrV.getCount())
2535 os << " The object now has a +" << Count << " retain count.";
Mike Stump11289f42009-09-09 15:08:12 +00002536
Ted Kremenek6bd78702009-04-29 18:50:19 +00002537 if (PrevV.getKind() == RefVal::Released) {
2538 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2539 os << " The object is not eligible for garbage collection until the "
2540 "retain count reaches 0 again.";
2541 }
Mike Stump11289f42009-09-09 15:08:12 +00002542
Ted Kremenek6bd78702009-04-29 18:50:19 +00002543 break;
Mike Stump11289f42009-09-09 15:08:12 +00002544
Ted Kremenek6bd78702009-04-29 18:50:19 +00002545 case RefVal::Released:
2546 os << "Object released.";
2547 break;
Mike Stump11289f42009-09-09 15:08:12 +00002548
Ted Kremenek6bd78702009-04-29 18:50:19 +00002549 case RefVal::ReturnedOwned:
2550 os << "Object returned to caller as an owning reference (single retain "
2551 "count transferred to caller).";
2552 break;
Mike Stump11289f42009-09-09 15:08:12 +00002553
Ted Kremenek6bd78702009-04-29 18:50:19 +00002554 case RefVal::ReturnedNotOwned:
2555 os << "Object returned to caller with a +0 (non-owning) retain count.";
2556 break;
Mike Stump11289f42009-09-09 15:08:12 +00002557
Ted Kremenek6bd78702009-04-29 18:50:19 +00002558 default:
2559 return NULL;
2560 }
Mike Stump11289f42009-09-09 15:08:12 +00002561
Ted Kremenek6bd78702009-04-29 18:50:19 +00002562 // Emit any remaining diagnostics for the argument effects (if any).
2563 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2564 E=AEffects.end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002565
Ted Kremenek6bd78702009-04-29 18:50:19 +00002566 // A bunch of things have alternate behavior under GC.
2567 if (TF.isGCEnabled())
2568 switch (*I) {
2569 default: break;
2570 case Autorelease:
2571 os << "In GC mode an 'autorelease' has no effect.";
2572 continue;
2573 case IncRefMsg:
2574 os << "In GC mode the 'retain' message has no effect.";
2575 continue;
2576 case DecRefMsg:
2577 os << "In GC mode the 'release' message has no effect.";
2578 continue;
2579 }
2580 }
Mike Stump11289f42009-09-09 15:08:12 +00002581 } while (0);
2582
Ted Kremenek6bd78702009-04-29 18:50:19 +00002583 if (os.str().empty())
2584 return 0; // We have nothing to say!
Ted Kremenek051a03d2009-05-13 07:12:33 +00002585
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002586 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002587 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002588 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump11289f42009-09-09 15:08:12 +00002589
Ted Kremenek6bd78702009-04-29 18:50:19 +00002590 // Add the range by scanning the children of the statement for any bindings
2591 // to Sym.
Mike Stump11289f42009-09-09 15:08:12 +00002592 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002593 I!=E; ++I)
2594 if (const Expr* Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002595 if (CurrSt->getSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002596 P->addRange(Exp->getSourceRange());
2597 break;
2598 }
Mike Stump11289f42009-09-09 15:08:12 +00002599
Ted Kremenek6bd78702009-04-29 18:50:19 +00002600 return P;
2601}
2602
2603namespace {
2604 class VISIBILITY_HIDDEN FindUniqueBinding :
2605 public StoreManager::BindingsHandler {
2606 SymbolRef Sym;
2607 const MemRegion* Binding;
2608 bool First;
Mike Stump11289f42009-09-09 15:08:12 +00002609
Ted Kremenek6bd78702009-04-29 18:50:19 +00002610 public:
2611 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
Mike Stump11289f42009-09-09 15:08:12 +00002612
Ted Kremenek6bd78702009-04-29 18:50:19 +00002613 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2614 SVal val) {
Mike Stump11289f42009-09-09 15:08:12 +00002615
2616 SymbolRef SymV = val.getAsSymbol();
Ted Kremenek6bd78702009-04-29 18:50:19 +00002617 if (!SymV || SymV != Sym)
2618 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002619
Ted Kremenek6bd78702009-04-29 18:50:19 +00002620 if (Binding) {
2621 First = false;
2622 return false;
2623 }
2624 else
2625 Binding = R;
Mike Stump11289f42009-09-09 15:08:12 +00002626
2627 return true;
Ted Kremenek6bd78702009-04-29 18:50:19 +00002628 }
Mike Stump11289f42009-09-09 15:08:12 +00002629
Ted Kremenek6bd78702009-04-29 18:50:19 +00002630 operator bool() { return First && Binding; }
2631 const MemRegion* getRegion() { return Binding; }
Mike Stump11289f42009-09-09 15:08:12 +00002632 };
Ted Kremenek6bd78702009-04-29 18:50:19 +00002633}
2634
Zhongxing Xu20227f72009-08-06 01:32:16 +00002635static std::pair<const ExplodedNode*,const MemRegion*>
2636GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode* N,
Ted Kremenek6bd78702009-04-29 18:50:19 +00002637 SymbolRef Sym) {
Mike Stump11289f42009-09-09 15:08:12 +00002638
Ted Kremenek6bd78702009-04-29 18:50:19 +00002639 // Find both first node that referred to the tracked symbol and the
2640 // memory location that value was store to.
Zhongxing Xu20227f72009-08-06 01:32:16 +00002641 const ExplodedNode* Last = N;
Mike Stump11289f42009-09-09 15:08:12 +00002642 const MemRegion* FirstBinding = 0;
2643
Ted Kremenek6bd78702009-04-29 18:50:19 +00002644 while (N) {
2645 const GRState* St = N->getState();
2646 RefBindings B = St->get<RefBindings>();
Mike Stump11289f42009-09-09 15:08:12 +00002647
Ted Kremenek6bd78702009-04-29 18:50:19 +00002648 if (!B.lookup(Sym))
2649 break;
Mike Stump11289f42009-09-09 15:08:12 +00002650
Ted Kremenek6bd78702009-04-29 18:50:19 +00002651 FindUniqueBinding FB(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002652 StateMgr.iterBindings(St, FB);
2653 if (FB) FirstBinding = FB.getRegion();
2654
Ted Kremenek6bd78702009-04-29 18:50:19 +00002655 Last = N;
Mike Stump11289f42009-09-09 15:08:12 +00002656 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002657 }
Mike Stump11289f42009-09-09 15:08:12 +00002658
Ted Kremenek6bd78702009-04-29 18:50:19 +00002659 return std::make_pair(Last, FirstBinding);
2660}
2661
2662PathDiagnosticPiece*
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002663CFRefReport::getEndPath(BugReporterContext& BRC,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002664 const ExplodedNode* EndN) {
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002665 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek6bd78702009-04-29 18:50:19 +00002666 // assigned to different variables, etc.
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002667 BRC.addNotableSymbol(Sym);
2668 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002669}
2670
2671PathDiagnosticPiece*
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002672CFRefLeakReport::getEndPath(BugReporterContext& BRC,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002673 const ExplodedNode* EndN){
Mike Stump11289f42009-09-09 15:08:12 +00002674
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002675 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek6bd78702009-04-29 18:50:19 +00002676 // assigned to different variables, etc.
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002677 BRC.addNotableSymbol(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002678
Ted Kremenek6bd78702009-04-29 18:50:19 +00002679 // We are reporting a leak. Walk up the graph to get to the first node where
2680 // the symbol appeared, and also get the first VarDecl that tracked object
2681 // is stored to.
Zhongxing Xu20227f72009-08-06 01:32:16 +00002682 const ExplodedNode* AllocNode = 0;
Ted Kremenek6bd78702009-04-29 18:50:19 +00002683 const MemRegion* FirstBinding = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002684
Ted Kremenek6bd78702009-04-29 18:50:19 +00002685 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenek8c8fb482009-05-08 23:32:51 +00002686 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002687
2688 // Get the allocate site.
Ted Kremenek6bd78702009-04-29 18:50:19 +00002689 assert(AllocNode);
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002690 const Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00002691
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002692 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenek6bd78702009-04-29 18:50:19 +00002693 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002694
Ted Kremenek6bd78702009-04-29 18:50:19 +00002695 // Compute an actual location for the leak. Sometimes a leak doesn't
2696 // occur at an actual statement (e.g., transition between blocks; end
2697 // of function) so we need to walk the graph and compute a real location.
Zhongxing Xu20227f72009-08-06 01:32:16 +00002698 const ExplodedNode* LeakN = EndN;
Ted Kremenek6bd78702009-04-29 18:50:19 +00002699 PathDiagnosticLocation L;
Mike Stump11289f42009-09-09 15:08:12 +00002700
Ted Kremenek6bd78702009-04-29 18:50:19 +00002701 while (LeakN) {
2702 ProgramPoint P = LeakN->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00002703
Ted Kremenek6bd78702009-04-29 18:50:19 +00002704 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2705 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2706 break;
2707 }
2708 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2709 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2710 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2711 break;
2712 }
2713 }
Mike Stump11289f42009-09-09 15:08:12 +00002714
Ted Kremenek6bd78702009-04-29 18:50:19 +00002715 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2716 }
Mike Stump11289f42009-09-09 15:08:12 +00002717
Ted Kremenek6bd78702009-04-29 18:50:19 +00002718 if (!L.isValid()) {
Zhongxing Xu7e3431b2009-09-10 05:44:00 +00002719 const Decl &D = EndN->getCodeDecl();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002720 L = PathDiagnosticLocation(D.getBodyRBrace(), SMgr);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002721 }
Mike Stump11289f42009-09-09 15:08:12 +00002722
Ted Kremenek6bd78702009-04-29 18:50:19 +00002723 std::string sbuf;
2724 llvm::raw_string_ostream os(sbuf);
Mike Stump11289f42009-09-09 15:08:12 +00002725
Ted Kremenek6bd78702009-04-29 18:50:19 +00002726 os << "Object allocated on line " << AllocLine;
Mike Stump11289f42009-09-09 15:08:12 +00002727
Ted Kremenek6bd78702009-04-29 18:50:19 +00002728 if (FirstBinding)
Mike Stump11289f42009-09-09 15:08:12 +00002729 os << " and stored into '" << FirstBinding->getString() << '\'';
2730
Ted Kremenek6bd78702009-04-29 18:50:19 +00002731 // Get the retain count.
2732 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002733
Ted Kremenek6bd78702009-04-29 18:50:19 +00002734 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2735 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2736 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2737 // to the caller for NS objects.
Zhongxing Xu7e3431b2009-09-10 05:44:00 +00002738 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002739 os << " is returned from a method whose name ('"
Ted Kremenek223a7d52009-04-29 23:03:22 +00002740 << MD.getSelector().getAsString()
Ted Kremenek6bd78702009-04-29 18:50:19 +00002741 << "') does not contain 'copy' or otherwise starts with"
2742 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenekd6bef2e2009-04-29 22:25:52 +00002743 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002744 }
Ted Kremenekdee56e32009-05-10 06:25:57 +00002745 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
Zhongxing Xu7e3431b2009-09-10 05:44:00 +00002746 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremenekdee56e32009-05-10 06:25:57 +00002747 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek1f8e4342009-05-10 16:52:15 +00002748 << "' is potentially leaked when using garbage collection. Callers "
2749 "of this method do not expect a returned object with a +1 retain "
2750 "count since they expect the object to be managed by the garbage "
2751 "collector";
Ted Kremenekdee56e32009-05-10 06:25:57 +00002752 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002753 else
2754 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenekd6bef2e2009-04-29 22:25:52 +00002755 " +" << RV->getCount() << " (object leaked)";
Mike Stump11289f42009-09-09 15:08:12 +00002756
Ted Kremenek6bd78702009-04-29 18:50:19 +00002757 return new PathDiagnosticEventPiece(L, os.str());
2758}
2759
Ted Kremenek6bd78702009-04-29 18:50:19 +00002760CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002761 ExplodedNode *n,
Ted Kremenek6bd78702009-04-29 18:50:19 +00002762 SymbolRef sym, GRExprEngine& Eng)
Mike Stump11289f42009-09-09 15:08:12 +00002763: CFRefReport(D, tf, n, sym) {
2764
Ted Kremenek6bd78702009-04-29 18:50:19 +00002765 // Most bug reports are cached at the location where they occured.
2766 // With leaks, we want to unique them by the location where they were
2767 // allocated, and only report a single path. To do this, we need to find
2768 // the allocation site of a piece of tracked memory, which we do via a
2769 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2770 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2771 // that all ancestor nodes that represent the allocation site have the
2772 // same SourceLocation.
Zhongxing Xu20227f72009-08-06 01:32:16 +00002773 const ExplodedNode* AllocNode = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002774
Ted Kremenek6bd78702009-04-29 18:50:19 +00002775 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenek8c8fb482009-05-08 23:32:51 +00002776 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Mike Stump11289f42009-09-09 15:08:12 +00002777
Ted Kremenek6bd78702009-04-29 18:50:19 +00002778 // Get the SourceLocation for the allocation site.
2779 ProgramPoint P = AllocNode->getLocation();
2780 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00002781
Ted Kremenek6bd78702009-04-29 18:50:19 +00002782 // Fill in the description of the bug.
2783 Description.clear();
2784 llvm::raw_string_ostream os(Description);
2785 SourceManager& SMgr = Eng.getContext().getSourceManager();
2786 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenekf1e76672009-05-02 19:05:19 +00002787 os << "Potential leak ";
2788 if (tf.isGCEnabled()) {
2789 os << "(when using garbage collection) ";
Mike Stump11289f42009-09-09 15:08:12 +00002790 }
Ted Kremenekf1e76672009-05-02 19:05:19 +00002791 os << "of an object allocated on line " << AllocLine;
Mike Stump11289f42009-09-09 15:08:12 +00002792
Ted Kremenek6bd78702009-04-29 18:50:19 +00002793 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2794 if (AllocBinding)
2795 os << " and stored into '" << AllocBinding->getString() << '\'';
2796}
2797
2798//===----------------------------------------------------------------------===//
2799// Main checker logic.
2800//===----------------------------------------------------------------------===//
2801
Ted Kremenek3185c9c2008-06-25 21:21:56 +00002802/// GetReturnType - Used to get the return type of a message expression or
2803/// function call with the intention of affixing that type to a tracked symbol.
2804/// While the the return type can be queried directly from RetEx, when
2805/// invoking class methods we augment to the return type to be that of
2806/// a pointer to the class (as opposed it just being id).
Steve Naroff7cae42b2009-07-10 23:34:53 +00002807static QualType GetReturnType(const Expr* RetE, ASTContext& Ctx) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +00002808 QualType RetTy = RetE->getType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002809 // If RetE is not a message expression just return its type.
2810 // If RetE is a message expression, return its types if it is something
Ted Kremenek3185c9c2008-06-25 21:21:56 +00002811 /// more specific than id.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002812 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
John McCall9dd450b2009-09-21 23:43:11 +00002813 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00002814 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002815 PT->isObjCClassType()) {
2816 // At this point we know the return type of the message expression is
2817 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2818 // is a call to a class method whose type we can resolve. In such
2819 // cases, promote the return type to XXX* (where XXX is the class).
Mike Stump11289f42009-09-09 15:08:12 +00002820 const ObjCInterfaceDecl *D = ME->getClassInfo().first;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002821 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2822 }
Mike Stump11289f42009-09-09 15:08:12 +00002823
Steve Naroff7cae42b2009-07-10 23:34:53 +00002824 return RetTy;
Ted Kremenek3185c9c2008-06-25 21:21:56 +00002825}
2826
Zhongxing Xu20227f72009-08-06 01:32:16 +00002827void CFRefCount::EvalSummary(ExplodedNodeSet& Dst,
Ted Kremenek00daccd2008-05-05 22:11:16 +00002828 GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00002829 GRStmtNodeBuilder& Builder,
Ted Kremenek00daccd2008-05-05 22:11:16 +00002830 Expr* Ex,
2831 Expr* Receiver,
Ted Kremenekff606a12009-05-04 04:57:00 +00002832 const RetainSummary& Summ,
Zhongxing Xuac129432009-04-20 05:24:46 +00002833 ExprIterator arg_beg, ExprIterator arg_end,
Zhongxing Xu20227f72009-08-06 01:32:16 +00002834 ExplodedNode* Pred) {
Mike Stump11289f42009-09-09 15:08:12 +00002835
Ted Kremenek819e9b62008-03-11 06:39:11 +00002836 // Get the state.
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002837 const GRState *state = Builder.GetState(Pred);
Ted Kremenek821537e2008-05-06 02:41:27 +00002838
2839 // Evaluate the effect of the arguments.
Ted Kremenek8cb96e92008-04-16 04:28:53 +00002840 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenek68d73d12008-03-12 01:21:45 +00002841 unsigned idx = 0;
Ted Kremenek988990f2008-04-11 18:40:51 +00002842 Expr* ErrorExpr = NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002843 SymbolRef ErrorSym = 0;
2844
2845 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
2846 SVal V = state->getSValAsScalarOrLoc(*I);
Ted Kremenekc9747dd2009-03-03 22:06:47 +00002847 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek804fc232009-03-04 00:13:50 +00002848
Ted Kremenek3e31c262009-03-26 03:35:11 +00002849 if (Sym)
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002850 if (RefBindings::data_type* T = state->get<RefBindings>(Sym)) {
Ted Kremenekff606a12009-05-04 04:57:00 +00002851 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekc52f9392009-02-24 19:15:11 +00002852 if (hasErr) {
Ted Kremenek988990f2008-04-11 18:40:51 +00002853 ErrorExpr = *I;
Ted Kremenek4963d112008-07-07 16:21:19 +00002854 ErrorSym = Sym;
Ted Kremenek988990f2008-04-11 18:40:51 +00002855 break;
Mike Stump11289f42009-09-09 15:08:12 +00002856 }
Ted Kremenekc9747dd2009-03-03 22:06:47 +00002857 continue;
Ted Kremenekc52f9392009-02-24 19:15:11 +00002858 }
Ted Kremenekae529272008-07-09 18:11:16 +00002859
Ted Kremenekf9539d02009-09-22 04:48:39 +00002860 tryAgain:
Ted Kremenekc9747dd2009-03-03 22:06:47 +00002861 if (isa<Loc>(V)) {
2862 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenekff606a12009-05-04 04:57:00 +00002863 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekae529272008-07-09 18:11:16 +00002864 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002865
2866 // Invalidate the value of the variable passed by reference.
2867
Ted Kremenek4d851462008-07-03 23:26:32 +00002868 // FIXME: We can have collisions on the conjured symbol if the
2869 // expression *I also creates conjured symbols. We probably want
2870 // to identify conjured symbols by an expression pair: the enclosing
2871 // expression (the context) and the expression itself. This should
Mike Stump11289f42009-09-09 15:08:12 +00002872 // disambiguate conjured symbols.
Zhongxing Xu4744d562009-06-29 06:43:40 +00002873 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xue1a3ace2009-07-06 06:01:24 +00002874 StoreManager& StoreMgr = Eng.getStateManager().getStoreManager();
Ted Kremenek97f75f82009-05-11 22:55:17 +00002875
Zhongxing Xue1a3ace2009-07-06 06:01:24 +00002876 const MemRegion *R = MR->getRegion();
2877 // Are we dealing with an ElementRegion? If the element type is
2878 // a basic integer type (e.g., char, int) and the underying region
2879 // is a variable region then strip off the ElementRegion.
2880 // FIXME: We really need to think about this for the general case
2881 // as sometimes we are reasoning about arrays and other times
2882 // about (char*), etc., is just a form of passing raw bytes.
2883 // e.g., void *p = alloca(); foo((char*)p);
2884 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2885 // Checking for 'integral type' is probably too promiscuous, but
2886 // we'll leave it in for now until we have a systematic way of
2887 // handling all of these cases. Eventually we need to come up
2888 // with an interface to StoreManager so that this logic can be
2889 // approriately delegated to the respective StoreManagers while
2890 // still allowing us to do checker-specific logic (e.g.,
2891 // invalidating reference counts), probably via callbacks.
2892 if (ER->getElementType()->isIntegralType()) {
2893 const MemRegion *superReg = ER->getSuperRegion();
2894 if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
2895 isa<ObjCIvarRegion>(superReg))
2896 R = cast<TypedRegion>(superReg);
Ted Kremenek0626df42009-05-06 18:19:24 +00002897 }
Zhongxing Xue1a3ace2009-07-06 06:01:24 +00002898 // FIXME: What about layers of ElementRegions?
2899 }
Zhongxing Xu4744d562009-06-29 06:43:40 +00002900
Ted Kremenek1eb68092009-10-16 00:30:49 +00002901 StoreManager::InvalidatedSymbols IS;
2902 state = StoreMgr.InvalidateRegion(state, R, *I, Count, &IS);
2903 for (StoreManager::InvalidatedSymbols::iterator I = IS.begin(),
2904 E = IS.end(); I!=E; ++I) {
2905 // Remove any existing reference-count binding.
2906 state = state->remove<RefBindings>(*I);
2907 }
Ted Kremenek4d851462008-07-03 23:26:32 +00002908 }
2909 else {
2910 // Nuke all other arguments passed by reference.
Ted Kremenekf9539d02009-09-22 04:48:39 +00002911 // FIXME: is this necessary or correct? This handles the non-Region
2912 // cases. Is it ever valid to store to these?
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002913 state = state->unbindLoc(cast<Loc>(V));
Ted Kremenek4d851462008-07-03 23:26:32 +00002914 }
Ted Kremenek0a86fdb2008-04-11 20:51:02 +00002915 }
Ted Kremenekf9539d02009-09-22 04:48:39 +00002916 else if (isa<nonloc::LocAsInteger>(V)) {
2917 // If we are passing a location wrapped as an integer, unwrap it and
2918 // invalidate the values referred by the location.
2919 V = cast<nonloc::LocAsInteger>(V).getLoc();
2920 goto tryAgain;
2921 }
Mike Stump11289f42009-09-09 15:08:12 +00002922 }
2923
2924 // Evaluate the effect on the message receiver.
Ted Kremenek821537e2008-05-06 02:41:27 +00002925 if (!ErrorExpr && Receiver) {
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002926 SymbolRef Sym = state->getSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek3e31c262009-03-26 03:35:11 +00002927 if (Sym) {
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002928 if (const RefVal* T = state->get<RefBindings>(Sym)) {
Ted Kremenekff606a12009-05-04 04:57:00 +00002929 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekc52f9392009-02-24 19:15:11 +00002930 if (hasErr) {
Ted Kremenek821537e2008-05-06 02:41:27 +00002931 ErrorExpr = Receiver;
Ted Kremenek4963d112008-07-07 16:21:19 +00002932 ErrorSym = Sym;
Ted Kremenek821537e2008-05-06 02:41:27 +00002933 }
Ted Kremenekc52f9392009-02-24 19:15:11 +00002934 }
Ted Kremenek821537e2008-05-06 02:41:27 +00002935 }
2936 }
Mike Stump11289f42009-09-09 15:08:12 +00002937
2938 // Process any errors.
Ted Kremenek8cb96e92008-04-16 04:28:53 +00002939 if (hasErr) {
Ted Kremenekdb7dd9c2008-08-14 21:16:54 +00002940 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek396f4362008-04-18 03:39:05 +00002941 hasErr, ErrorSym);
Ted Kremenek68d73d12008-03-12 01:21:45 +00002942 return;
Ted Kremenekbf9d8042008-03-11 17:48:22 +00002943 }
Mike Stump11289f42009-09-09 15:08:12 +00002944
2945 // Consult the summary for the return value.
Ted Kremenekff606a12009-05-04 04:57:00 +00002946 RetEffect RE = Summ.getRetEffect();
Mike Stump11289f42009-09-09 15:08:12 +00002947
Ted Kremenek1272f702009-05-12 20:06:54 +00002948 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2949 assert(Receiver);
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002950 SVal V = state->getSValAsScalarOrLoc(Receiver);
Ted Kremenek1272f702009-05-12 20:06:54 +00002951 bool found = false;
2952 if (SymbolRef Sym = V.getAsLocSymbol())
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002953 if (state->get<RefBindings>(Sym)) {
Ted Kremenek1272f702009-05-12 20:06:54 +00002954 found = true;
2955 RE = Summaries.getObjAllocRetEffect();
2956 }
2957
2958 if (!found)
2959 RE = RetEffect::MakeNoRet();
Mike Stump11289f42009-09-09 15:08:12 +00002960 }
2961
Ted Kremenek68d73d12008-03-12 01:21:45 +00002962 switch (RE.getKind()) {
2963 default:
2964 assert (false && "Unhandled RetEffect."); break;
Mike Stump11289f42009-09-09 15:08:12 +00002965
2966 case RetEffect::NoRet: {
Ted Kremenek831f3272008-04-11 20:23:24 +00002967 // Make up a symbol for the return value (not reference counted).
Ted Kremenek1642bda2009-06-26 00:05:51 +00002968 // FIXME: Most of this logic is not specific to the retain/release
2969 // checker.
Mike Stump11289f42009-09-09 15:08:12 +00002970
Ted Kremenek21387322008-10-17 22:23:12 +00002971 // FIXME: We eventually should handle structs and other compound types
2972 // that are returned by value.
Mike Stump11289f42009-09-09 15:08:12 +00002973
Ted Kremenek21387322008-10-17 22:23:12 +00002974 QualType T = Ex->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002975
Ted Kremenek16866d62008-11-13 06:10:40 +00002976 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek831f3272008-04-11 20:23:24 +00002977 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekf2489ea2009-04-09 22:22:44 +00002978 ValueManager &ValMgr = Eng.getValueManager();
Ted Kremeneke41b81e2009-09-27 20:45:21 +00002979 SVal X = ValMgr.getConjuredSymbolVal(NULL, Ex, T, Count);
Ted Kremenek1d5f2f32009-08-27 22:17:37 +00002980 state = state->BindExpr(Ex, X, false);
Mike Stump11289f42009-09-09 15:08:12 +00002981 }
2982
Ted Kremenek4b772092008-04-10 23:44:06 +00002983 break;
Ted Kremenek21387322008-10-17 22:23:12 +00002984 }
Mike Stump11289f42009-09-09 15:08:12 +00002985
Ted Kremenek68d73d12008-03-12 01:21:45 +00002986 case RetEffect::Alias: {
Ted Kremenek3185c9c2008-06-25 21:21:56 +00002987 unsigned idx = RE.getIndex();
Ted Kremenek08e17112008-06-17 02:43:46 +00002988 assert (arg_end >= arg_beg);
Ted Kremenek00daccd2008-05-05 22:11:16 +00002989 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002990 SVal V = state->getSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek1d5f2f32009-08-27 22:17:37 +00002991 state = state->BindExpr(Ex, V, false);
Ted Kremenek68d73d12008-03-12 01:21:45 +00002992 break;
2993 }
Mike Stump11289f42009-09-09 15:08:12 +00002994
Ted Kremenek821537e2008-05-06 02:41:27 +00002995 case RetEffect::ReceiverAlias: {
2996 assert (Receiver);
Ted Kremenekd93c6e32009-06-18 01:23:53 +00002997 SVal V = state->getSValAsScalarOrLoc(Receiver);
Ted Kremenek1d5f2f32009-08-27 22:17:37 +00002998 state = state->BindExpr(Ex, V, false);
Ted Kremenek821537e2008-05-06 02:41:27 +00002999 break;
3000 }
Mike Stump11289f42009-09-09 15:08:12 +00003001
Ted Kremenekab4a8b52008-06-23 18:02:52 +00003002 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenek68d73d12008-03-12 01:21:45 +00003003 case RetEffect::OwnedSymbol: {
3004 unsigned Count = Builder.getCurrentBlockCount();
Mike Stump11289f42009-09-09 15:08:12 +00003005 ValueManager &ValMgr = Eng.getValueManager();
Ted Kremenekaa4cfc22009-04-09 16:13:17 +00003006 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
Mike Stump11289f42009-09-09 15:08:12 +00003007 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003008 state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
Ted Kremenekaa4cfc22009-04-09 16:13:17 +00003009 RetT));
Ted Kremenek1d5f2f32009-08-27 22:17:37 +00003010 state = state->BindExpr(Ex, ValMgr.makeLoc(Sym), false);
Ted Kremenek0b891a32009-03-09 22:46:49 +00003011
3012 // FIXME: Add a flag to the checker where allocations are assumed to
3013 // *not fail.
3014#if 0
Ted Kremenek2e561dd2009-01-28 22:27:59 +00003015 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
3016 bool isFeasible;
3017 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
Mike Stump11289f42009-09-09 15:08:12 +00003018 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
Ted Kremenek2e561dd2009-01-28 22:27:59 +00003019 }
Ted Kremenek0b891a32009-03-09 22:46:49 +00003020#endif
Mike Stump11289f42009-09-09 15:08:12 +00003021
Ted Kremenek68d73d12008-03-12 01:21:45 +00003022 break;
3023 }
Mike Stump11289f42009-09-09 15:08:12 +00003024
Ted Kremeneke6633562009-04-27 19:14:45 +00003025 case RetEffect::GCNotOwnedSymbol:
Ted Kremenek68d73d12008-03-12 01:21:45 +00003026 case RetEffect::NotOwnedSymbol: {
3027 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekaa4cfc22009-04-09 16:13:17 +00003028 ValueManager &ValMgr = Eng.getValueManager();
3029 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
Mike Stump11289f42009-09-09 15:08:12 +00003030 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003031 state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
Ted Kremenekaa4cfc22009-04-09 16:13:17 +00003032 RetT));
Ted Kremenek1d5f2f32009-08-27 22:17:37 +00003033 state = state->BindExpr(Ex, ValMgr.makeLoc(Sym), false);
Ted Kremenek68d73d12008-03-12 01:21:45 +00003034 break;
3035 }
3036 }
Mike Stump11289f42009-09-09 15:08:12 +00003037
Ted Kremenekd84fff62009-02-18 02:00:25 +00003038 // Generate a sink node if we are at the end of a path.
Zhongxing Xu107f7592009-08-06 12:48:26 +00003039 ExplodedNode *NewNode =
Ted Kremenekff606a12009-05-04 04:57:00 +00003040 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
3041 : Builder.MakeNode(Dst, Ex, Pred, state);
Mike Stump11289f42009-09-09 15:08:12 +00003042
Ted Kremenekd84fff62009-02-18 02:00:25 +00003043 // Annotate the edge with summary we used.
Ted Kremenekff606a12009-05-04 04:57:00 +00003044 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremenek00daccd2008-05-05 22:11:16 +00003045}
3046
3047
Zhongxing Xu20227f72009-08-06 01:32:16 +00003048void CFRefCount::EvalCall(ExplodedNodeSet& Dst,
Ted Kremenek00daccd2008-05-05 22:11:16 +00003049 GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00003050 GRStmtNodeBuilder& Builder,
Zhongxing Xu27f17422008-10-17 05:57:07 +00003051 CallExpr* CE, SVal L,
Zhongxing Xu20227f72009-08-06 01:32:16 +00003052 ExplodedNode* Pred) {
Zhongxing Xuac129432009-04-20 05:24:46 +00003053 const FunctionDecl* FD = L.getAsFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003054 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xuac129432009-04-20 05:24:46 +00003055 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Mike Stump11289f42009-09-09 15:08:12 +00003056
Ted Kremenekff606a12009-05-04 04:57:00 +00003057 assert(Summ);
3058 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremenek00daccd2008-05-05 22:11:16 +00003059 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenekea6507f2008-03-06 00:08:09 +00003060}
Ted Kremenek819e9b62008-03-11 06:39:11 +00003061
Zhongxing Xu20227f72009-08-06 01:32:16 +00003062void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet& Dst,
Ted Kremenek748c7ce2008-04-15 23:44:31 +00003063 GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00003064 GRStmtNodeBuilder& Builder,
Ted Kremenek748c7ce2008-04-15 23:44:31 +00003065 ObjCMessageExpr* ME,
Mike Stump11289f42009-09-09 15:08:12 +00003066 ExplodedNode* Pred) {
Ted Kremeneka2968e52009-11-13 01:54:21 +00003067
3068 RetainSummary *Summ =
3069 ME->getReceiver()
3070 ? Summaries.getInstanceMethodSummary(ME, Builder.GetState(Pred),
3071 Pred->getLocationContext())
3072 : Summaries.getClassMethodSummary(ME);
Mike Stump11289f42009-09-09 15:08:12 +00003073
Ted Kremeneka2968e52009-11-13 01:54:21 +00003074 assert(Summ && "RetainSummary is null");
Ted Kremenekff606a12009-05-04 04:57:00 +00003075 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek015c3562008-05-06 04:20:12 +00003076 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek748c7ce2008-04-15 23:44:31 +00003077}
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003078
3079namespace {
3080class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
Ted Kremenek89a303c2009-06-18 00:49:02 +00003081 const GRState *state;
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003082public:
Ted Kremenek89a303c2009-06-18 00:49:02 +00003083 StopTrackingCallback(const GRState *st) : state(st) {}
3084 const GRState *getState() const { return state; }
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003085
3086 bool VisitSymbol(SymbolRef sym) {
Ted Kremenek89a303c2009-06-18 00:49:02 +00003087 state = state->remove<RefBindings>(sym);
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003088 return true;
3089 }
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003090};
3091} // end anonymous namespace
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003092
Mike Stump11289f42009-09-09 15:08:12 +00003093
3094void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
3095 // Are we storing to something that causes the value to "escape"?
Ted Kremenek71454892008-04-16 20:40:59 +00003096 bool escapes = false;
Mike Stump11289f42009-09-09 15:08:12 +00003097
Ted Kremeneke86755e2008-10-18 03:49:51 +00003098 // A value escapes in three possible cases (this may change):
3099 //
3100 // (1) we are binding to something that is not a memory region.
3101 // (2) we are binding to a memregion that does not have stack storage
3102 // (3) we are binding to a memregion with stack storage that the store
Mike Stump11289f42009-09-09 15:08:12 +00003103 // does not understand.
Ted Kremenek89a303c2009-06-18 00:49:02 +00003104 const GRState *state = B.getState();
Ted Kremeneke86755e2008-10-18 03:49:51 +00003105
Ted Kremeneke68c0fc2009-02-14 01:43:44 +00003106 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek71454892008-04-16 20:40:59 +00003107 escapes = true;
Ted Kremenek5ca90a22008-10-04 05:50:14 +00003108 else {
Ted Kremeneke68c0fc2009-02-14 01:43:44 +00003109 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
Ted Kremenek404b1322009-06-23 18:05:21 +00003110 escapes = !R->hasStackStorage();
Mike Stump11289f42009-09-09 15:08:12 +00003111
Ted Kremeneke86755e2008-10-18 03:49:51 +00003112 if (!escapes) {
3113 // To test (3), generate a new state with the binding removed. If it is
3114 // the same state, then it escapes (since the store cannot represent
3115 // the binding).
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003116 escapes = (state == (state->bindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremeneke86755e2008-10-18 03:49:51 +00003117 }
Ted Kremenek5ca90a22008-10-04 05:50:14 +00003118 }
Ted Kremeneke68c0fc2009-02-14 01:43:44 +00003119
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003120 // If our store can represent the binding and we aren't storing to something
3121 // that doesn't have local storage then just return and have the simulation
3122 // state continue as is.
3123 if (!escapes)
3124 return;
Ted Kremeneke86755e2008-10-18 03:49:51 +00003125
Ted Kremenek4e9d4b52009-02-14 03:16:10 +00003126 // Otherwise, find all symbols referenced by 'val' that we are tracking
3127 // and stop tracking them.
Ted Kremenek89a303c2009-06-18 00:49:02 +00003128 B.MakeNode(state->scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenekcbf4c612008-04-16 22:32:20 +00003129}
3130
Ted Kremeneka506fec2008-04-17 18:12:53 +00003131 // Return statements.
3132
Zhongxing Xu20227f72009-08-06 01:32:16 +00003133void CFRefCount::EvalReturn(ExplodedNodeSet& Dst,
Ted Kremeneka506fec2008-04-17 18:12:53 +00003134 GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00003135 GRStmtNodeBuilder& Builder,
Ted Kremeneka506fec2008-04-17 18:12:53 +00003136 ReturnStmt* S,
Zhongxing Xu20227f72009-08-06 01:32:16 +00003137 ExplodedNode* Pred) {
Mike Stump11289f42009-09-09 15:08:12 +00003138
Ted Kremeneka506fec2008-04-17 18:12:53 +00003139 Expr* RetE = S->getRetValue();
Ted Kremenekc9747dd2009-03-03 22:06:47 +00003140 if (!RetE)
Ted Kremeneka506fec2008-04-17 18:12:53 +00003141 return;
Mike Stump11289f42009-09-09 15:08:12 +00003142
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003143 const GRState *state = Builder.GetState(Pred);
3144 SymbolRef Sym = state->getSValAsScalarOrLoc(RetE).getAsLocSymbol();
Mike Stump11289f42009-09-09 15:08:12 +00003145
Ted Kremenek3e31c262009-03-26 03:35:11 +00003146 if (!Sym)
Ted Kremenekc9747dd2009-03-03 22:06:47 +00003147 return;
Mike Stump11289f42009-09-09 15:08:12 +00003148
Ted Kremeneka506fec2008-04-17 18:12:53 +00003149 // Get the reference count binding (if any).
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003150 const RefVal* T = state->get<RefBindings>(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00003151
Ted Kremeneka506fec2008-04-17 18:12:53 +00003152 if (!T)
3153 return;
Mike Stump11289f42009-09-09 15:08:12 +00003154
3155 // Change the reference count.
3156 RefVal X = *T;
3157
3158 switch (X.getKind()) {
3159 case RefVal::Owned: {
Ted Kremeneka506fec2008-04-17 18:12:53 +00003160 unsigned cnt = X.getCount();
Ted Kremenek1df2f3a2008-05-22 17:31:13 +00003161 assert (cnt > 0);
Ted Kremenek3978f792009-05-10 05:11:21 +00003162 X.setCount(cnt - 1);
3163 X = X ^ RefVal::ReturnedOwned;
Ted Kremeneka506fec2008-04-17 18:12:53 +00003164 break;
3165 }
Mike Stump11289f42009-09-09 15:08:12 +00003166
Ted Kremeneka506fec2008-04-17 18:12:53 +00003167 case RefVal::NotOwned: {
3168 unsigned cnt = X.getCount();
Ted Kremenek3978f792009-05-10 05:11:21 +00003169 if (cnt) {
3170 X.setCount(cnt - 1);
3171 X = X ^ RefVal::ReturnedOwned;
3172 }
3173 else {
3174 X = X ^ RefVal::ReturnedNotOwned;
3175 }
Ted Kremeneka506fec2008-04-17 18:12:53 +00003176 break;
3177 }
Mike Stump11289f42009-09-09 15:08:12 +00003178
3179 default:
Ted Kremeneka506fec2008-04-17 18:12:53 +00003180 return;
3181 }
Mike Stump11289f42009-09-09 15:08:12 +00003182
Ted Kremeneka506fec2008-04-17 18:12:53 +00003183 // Update the binding.
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003184 state = state->set<RefBindings>(Sym, X);
Ted Kremenek6bd78702009-04-29 18:50:19 +00003185 Pred = Builder.MakeNode(Dst, S, Pred, state);
Mike Stump11289f42009-09-09 15:08:12 +00003186
Ted Kremenekb4e27a12009-04-30 05:51:50 +00003187 // Did we cache out?
3188 if (!Pred)
3189 return;
Mike Stump11289f42009-09-09 15:08:12 +00003190
Ted Kremenek3978f792009-05-10 05:11:21 +00003191 // Update the autorelease counts.
3192 static unsigned autoreleasetag = 0;
3193 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
3194 bool stop = false;
3195 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
3196 X, stop);
Mike Stump11289f42009-09-09 15:08:12 +00003197
Ted Kremenek3978f792009-05-10 05:11:21 +00003198 // Did we cache out?
3199 if (!Pred || stop)
3200 return;
Mike Stump11289f42009-09-09 15:08:12 +00003201
Ted Kremenek3978f792009-05-10 05:11:21 +00003202 // Get the updated binding.
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003203 T = state->get<RefBindings>(Sym);
Ted Kremenek3978f792009-05-10 05:11:21 +00003204 assert(T);
3205 X = *T;
Mike Stump11289f42009-09-09 15:08:12 +00003206
Ted Kremenek6bd78702009-04-29 18:50:19 +00003207 // Any leaks or other errors?
3208 if (X.isReturnedOwned() && X.getCount() == 0) {
Zhongxing Xu7e3431b2009-09-10 05:44:00 +00003209 Decl const *CD = &Pred->getCodeDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003210 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenekff606a12009-05-04 04:57:00 +00003211 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
Ted Kremenekdee56e32009-05-10 06:25:57 +00003212 RetEffect RE = Summ.getRetEffect();
3213 bool hasError = false;
3214
Ted Kremeneke4302ee2009-05-16 01:38:01 +00003215 if (RE.getKind() != RetEffect::NoRet) {
3216 if (isGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3217 // Things are more complicated with garbage collection. If the
3218 // returned object is suppose to be an Objective-C object, we have
3219 // a leak (as the caller expects a GC'ed object) because no
3220 // method should return ownership unless it returns a CF object.
Ted Kremeneke4302ee2009-05-16 01:38:01 +00003221 hasError = true;
Ted Kremenek8070b822009-10-14 23:58:34 +00003222 X = X ^ RefVal::ErrorGCLeakReturned;
Ted Kremeneke4302ee2009-05-16 01:38:01 +00003223 }
3224 else if (!RE.isOwned()) {
3225 // Either we are using GC and the returned object is a CF type
3226 // or we aren't using GC. In either case, we expect that the
Mike Stump11289f42009-09-09 15:08:12 +00003227 // enclosing method is expected to return ownership.
Ted Kremeneke4302ee2009-05-16 01:38:01 +00003228 hasError = true;
3229 X = X ^ RefVal::ErrorLeakReturned;
3230 }
Ted Kremenekdee56e32009-05-10 06:25:57 +00003231 }
Mike Stump11289f42009-09-09 15:08:12 +00003232
3233 if (hasError) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00003234 // Generate an error node.
Ted Kremenekdee56e32009-05-10 06:25:57 +00003235 static int ReturnOwnLeakTag = 0;
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003236 state = state->set<RefBindings>(Sym, X);
Zhongxing Xu20227f72009-08-06 01:32:16 +00003237 ExplodedNode *N =
Zhongxing Xue1190f72009-08-15 03:17:38 +00003238 Builder.generateNode(PostStmt(S, Pred->getLocationContext(),
3239 &ReturnOwnLeakTag), state, Pred);
Ted Kremenekdee56e32009-05-10 06:25:57 +00003240 if (N) {
3241 CFRefReport *report =
Ted Kremenekb4e27a12009-04-30 05:51:50 +00003242 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3243 N, Sym, Eng);
3244 BR->EmitReport(report);
3245 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00003246 }
Mike Stump11289f42009-09-09 15:08:12 +00003247 }
Ted Kremenekdee56e32009-05-10 06:25:57 +00003248 }
3249 else if (X.isReturnedNotOwned()) {
Zhongxing Xu7e3431b2009-09-10 05:44:00 +00003250 Decl const *CD = &Pred->getCodeDecl();
Ted Kremenekdee56e32009-05-10 06:25:57 +00003251 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
3252 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3253 if (Summ.getRetEffect().isOwned()) {
3254 // Trying to return a not owned object to a caller expecting an
3255 // owned object.
Mike Stump11289f42009-09-09 15:08:12 +00003256
Ted Kremenekdee56e32009-05-10 06:25:57 +00003257 static int ReturnNotOwnedForOwnedTag = 0;
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003258 state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
Zhongxing Xu20227f72009-08-06 01:32:16 +00003259 if (ExplodedNode *N =
Zhongxing Xue1190f72009-08-15 03:17:38 +00003260 Builder.generateNode(PostStmt(S, Pred->getLocationContext(),
3261 &ReturnNotOwnedForOwnedTag),
3262 state, Pred)) {
Ted Kremenekdee56e32009-05-10 06:25:57 +00003263 CFRefReport *report =
3264 new CFRefReport(*static_cast<CFRefBug*>(returnNotOwnedForOwned),
3265 *this, N, Sym);
3266 BR->EmitReport(report);
3267 }
3268 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00003269 }
3270 }
Ted Kremeneka506fec2008-04-17 18:12:53 +00003271}
3272
Ted Kremenek4d837282008-04-18 19:23:43 +00003273// Assumptions.
3274
Ted Kremenekf9906842009-06-18 22:57:13 +00003275const GRState* CFRefCount::EvalAssume(const GRState *state,
3276 SVal Cond, bool Assumption) {
Ted Kremenek4d837282008-04-18 19:23:43 +00003277
3278 // FIXME: We may add to the interface of EvalAssume the list of symbols
3279 // whose assumptions have changed. For now we just iterate through the
3280 // bindings and check if any of the tracked symbols are NULL. This isn't
Mike Stump11289f42009-09-09 15:08:12 +00003281 // too bad since the number of symbols we will track in practice are
Ted Kremenek4d837282008-04-18 19:23:43 +00003282 // probably small and EvalAssume is only called at branches and a few
3283 // other places.
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003284 RefBindings B = state->get<RefBindings>();
Mike Stump11289f42009-09-09 15:08:12 +00003285
Ted Kremenek4d837282008-04-18 19:23:43 +00003286 if (B.isEmpty())
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003287 return state;
Mike Stump11289f42009-09-09 15:08:12 +00003288
3289 bool changed = false;
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003290 RefBindings::Factory& RefBFactory = state->get_context<RefBindings>();
Ted Kremenek4d837282008-04-18 19:23:43 +00003291
Mike Stump11289f42009-09-09 15:08:12 +00003292 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenek4d837282008-04-18 19:23:43 +00003293 // Check if the symbol is null (or equal to any constant).
3294 // If this is the case, stop tracking the symbol.
Ted Kremenekf9906842009-06-18 22:57:13 +00003295 if (state->getSymVal(I.getKey())) {
Ted Kremenek4d837282008-04-18 19:23:43 +00003296 changed = true;
3297 B = RefBFactory.Remove(B, I.getKey());
3298 }
3299 }
Mike Stump11289f42009-09-09 15:08:12 +00003300
Ted Kremenek87aab6c2008-08-17 03:20:02 +00003301 if (changed)
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003302 state = state->set<RefBindings>(B);
Mike Stump11289f42009-09-09 15:08:12 +00003303
Ted Kremenekdb7dd9c2008-08-14 21:16:54 +00003304 return state;
Ted Kremenek4d837282008-04-18 19:23:43 +00003305}
Ted Kremenek819e9b62008-03-11 06:39:11 +00003306
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003307const GRState * CFRefCount::Update(const GRState * state, SymbolRef sym,
Ted Kremenekc52f9392009-02-24 19:15:11 +00003308 RefVal V, ArgEffect E,
3309 RefVal::Kind& hasErr) {
Ted Kremenekf68490a2009-02-18 18:54:33 +00003310
3311 // In GC mode [... release] and [... retain] do nothing.
3312 switch (E) {
3313 default: break;
3314 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3315 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek10452892009-02-18 21:57:45 +00003316 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Mike Stump11289f42009-09-09 15:08:12 +00003317 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
Ted Kremenek50db3d02009-02-23 17:45:03 +00003318 NewAutoreleasePool; break;
Ted Kremenekf68490a2009-02-18 18:54:33 +00003319 }
Mike Stump11289f42009-09-09 15:08:12 +00003320
Ted Kremenekea072e32009-03-17 19:42:23 +00003321 // Handle all use-after-releases.
3322 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3323 V = V ^ RefVal::ErrorUseAfterRelease;
3324 hasErr = V.getKind();
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003325 return state->set<RefBindings>(sym, V);
Mike Stump11289f42009-09-09 15:08:12 +00003326 }
3327
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003328 switch (E) {
3329 default:
3330 assert (false && "Unhandled CFRef transition.");
Mike Stump11289f42009-09-09 15:08:12 +00003331
Ted Kremenekea072e32009-03-17 19:42:23 +00003332 case Dealloc:
3333 // Any use of -dealloc in GC is *bad*.
3334 if (isGCEnabled()) {
3335 V = V ^ RefVal::ErrorDeallocGC;
3336 hasErr = V.getKind();
3337 break;
3338 }
Mike Stump11289f42009-09-09 15:08:12 +00003339
Ted Kremenekea072e32009-03-17 19:42:23 +00003340 switch (V.getKind()) {
3341 default:
3342 assert(false && "Invalid case.");
3343 case RefVal::Owned:
3344 // The object immediately transitions to the released state.
3345 V = V ^ RefVal::Released;
3346 V.clearCounts();
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003347 return state->set<RefBindings>(sym, V);
Ted Kremenekea072e32009-03-17 19:42:23 +00003348 case RefVal::NotOwned:
3349 V = V ^ RefVal::ErrorDeallocNotOwned;
3350 hasErr = V.getKind();
3351 break;
Mike Stump11289f42009-09-09 15:08:12 +00003352 }
Ted Kremenekea072e32009-03-17 19:42:23 +00003353 break;
Ted Kremenek1df2f3a2008-05-22 17:31:13 +00003354
Ted Kremenek8ec8cf02009-02-25 23:11:49 +00003355 case NewAutoreleasePool:
3356 assert(!isGCEnabled());
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003357 return state->add<AutoreleaseStack>(sym);
Mike Stump11289f42009-09-09 15:08:12 +00003358
Ted Kremenek1df2f3a2008-05-22 17:31:13 +00003359 case MayEscape:
3360 if (V.getKind() == RefVal::Owned) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +00003361 V = V ^ RefVal::NotOwned;
Ted Kremenek1df2f3a2008-05-22 17:31:13 +00003362 break;
3363 }
Ted Kremenekea072e32009-03-17 19:42:23 +00003364
Ted Kremenek1df2f3a2008-05-22 17:31:13 +00003365 // Fall-through.
Mike Stump11289f42009-09-09 15:08:12 +00003366
Ted Kremenekae529272008-07-09 18:11:16 +00003367 case DoNothingByRef:
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003368 case DoNothing:
Ted Kremenekc52f9392009-02-24 19:15:11 +00003369 return state;
Ted Kremeneka0e071c2008-06-30 16:57:41 +00003370
Ted Kremenekc7832092009-01-28 21:44:40 +00003371 case Autorelease:
Ted Kremenekea072e32009-03-17 19:42:23 +00003372 if (isGCEnabled())
3373 return state;
Mike Stump11289f42009-09-09 15:08:12 +00003374
Ted Kremenek8c3f0042009-03-20 17:34:15 +00003375 // Update the autorelease counts.
3376 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek3a0516b2009-05-08 20:01:42 +00003377 V = V.autorelease();
Ted Kremenek2d0ff622009-05-09 01:50:57 +00003378 break;
Ted Kremenekd35272f2009-05-09 00:10:05 +00003379
Ted Kremenek821537e2008-05-06 02:41:27 +00003380 case StopTracking:
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003381 return state->remove<RefBindings>(sym);
Ted Kremenek050b91c2008-08-12 18:30:56 +00003382
Mike Stump11289f42009-09-09 15:08:12 +00003383 case IncRef:
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003384 switch (V.getKind()) {
3385 default:
3386 assert(false);
3387
3388 case RefVal::Owned:
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003389 case RefVal::NotOwned:
Ted Kremenek3185c9c2008-06-25 21:21:56 +00003390 V = V + 1;
Mike Stump11289f42009-09-09 15:08:12 +00003391 break;
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003392 case RefVal::Released:
Ted Kremenekea072e32009-03-17 19:42:23 +00003393 // Non-GC cases are handled above.
3394 assert(isGCEnabled());
3395 V = (V ^ RefVal::Owned) + 1;
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003396 break;
Mike Stump11289f42009-09-09 15:08:12 +00003397 }
Ted Kremenek4b772092008-04-10 23:44:06 +00003398 break;
Mike Stump11289f42009-09-09 15:08:12 +00003399
Ted Kremenek3185c9c2008-06-25 21:21:56 +00003400 case SelfOwn:
3401 V = V ^ RefVal::NotOwned;
Ted Kremenekf68490a2009-02-18 18:54:33 +00003402 // Fall-through.
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003403 case DecRef:
3404 switch (V.getKind()) {
3405 default:
Ted Kremenekea072e32009-03-17 19:42:23 +00003406 // case 'RefVal::Released' handled above.
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003407 assert (false);
Ted Kremenek050b91c2008-08-12 18:30:56 +00003408
Ted Kremenek3185c9c2008-06-25 21:21:56 +00003409 case RefVal::Owned:
Ted Kremenek551747f2009-02-18 22:57:22 +00003410 assert(V.getCount() > 0);
3411 if (V.getCount() == 1) V = V ^ RefVal::Released;
3412 V = V - 1;
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003413 break;
Mike Stump11289f42009-09-09 15:08:12 +00003414
Ted Kremenek3185c9c2008-06-25 21:21:56 +00003415 case RefVal::NotOwned:
3416 if (V.getCount() > 0)
3417 V = V - 1;
Ted Kremenek3c03d522008-04-10 23:09:18 +00003418 else {
Ted Kremenek3185c9c2008-06-25 21:21:56 +00003419 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek8cb96e92008-04-16 04:28:53 +00003420 hasErr = V.getKind();
Mike Stump11289f42009-09-09 15:08:12 +00003421 }
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003422 break;
Mike Stump11289f42009-09-09 15:08:12 +00003423
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003424 case RefVal::Released:
Ted Kremenekea072e32009-03-17 19:42:23 +00003425 // Non-GC cases are handled above.
3426 assert(isGCEnabled());
Ted Kremenek3185c9c2008-06-25 21:21:56 +00003427 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek8cb96e92008-04-16 04:28:53 +00003428 hasErr = V.getKind();
Mike Stump11289f42009-09-09 15:08:12 +00003429 break;
3430 }
Ted Kremenek4b772092008-04-10 23:44:06 +00003431 break;
Ted Kremenekbf9d8042008-03-11 17:48:22 +00003432 }
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003433 return state->set<RefBindings>(sym, V);
Ted Kremenek819e9b62008-03-11 06:39:11 +00003434}
3435
Ted Kremenekce8e8812008-04-09 01:10:13 +00003436//===----------------------------------------------------------------------===//
Ted Kremenek400aae72009-02-05 06:50:21 +00003437// Handle dead symbols and end-of-path.
3438//===----------------------------------------------------------------------===//
3439
Zhongxing Xu20227f72009-08-06 01:32:16 +00003440std::pair<ExplodedNode*, const GRState *>
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003441CFRefCount::HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd,
Zhongxing Xu20227f72009-08-06 01:32:16 +00003442 ExplodedNode* Pred,
Ted Kremenekd35272f2009-05-09 00:10:05 +00003443 GRExprEngine &Eng,
3444 SymbolRef Sym, RefVal V, bool &stop) {
Mike Stump11289f42009-09-09 15:08:12 +00003445
Ted Kremenekd35272f2009-05-09 00:10:05 +00003446 unsigned ACnt = V.getAutoreleaseCount();
3447 stop = false;
3448
3449 // No autorelease counts? Nothing to be done.
3450 if (!ACnt)
3451 return std::make_pair(Pred, state);
Mike Stump11289f42009-09-09 15:08:12 +00003452
3453 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
Ted Kremenekd35272f2009-05-09 00:10:05 +00003454 unsigned Cnt = V.getCount();
Mike Stump11289f42009-09-09 15:08:12 +00003455
Ted Kremenekdc7853c2009-05-11 15:26:06 +00003456 // FIXME: Handle sending 'autorelease' to already released object.
3457
3458 if (V.getKind() == RefVal::ReturnedOwned)
3459 ++Cnt;
Mike Stump11289f42009-09-09 15:08:12 +00003460
Ted Kremenekd35272f2009-05-09 00:10:05 +00003461 if (ACnt <= Cnt) {
Ted Kremenek9ec08aa2009-05-09 00:44:07 +00003462 if (ACnt == Cnt) {
3463 V.clearCounts();
Ted Kremenekdc7853c2009-05-11 15:26:06 +00003464 if (V.getKind() == RefVal::ReturnedOwned)
3465 V = V ^ RefVal::ReturnedNotOwned;
3466 else
3467 V = V ^ RefVal::NotOwned;
Ted Kremenek9ec08aa2009-05-09 00:44:07 +00003468 }
Ted Kremenekdc7853c2009-05-11 15:26:06 +00003469 else {
Ted Kremenek9ec08aa2009-05-09 00:44:07 +00003470 V.setCount(Cnt - ACnt);
3471 V.setAutoreleaseCount(0);
3472 }
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003473 state = state->set<RefBindings>(Sym, V);
Zhongxing Xu20227f72009-08-06 01:32:16 +00003474 ExplodedNode *N = Bd.MakeNode(state, Pred);
Ted Kremenekd35272f2009-05-09 00:10:05 +00003475 stop = (N == 0);
3476 return std::make_pair(N, state);
Mike Stump11289f42009-09-09 15:08:12 +00003477 }
Ted Kremenekd35272f2009-05-09 00:10:05 +00003478
3479 // Woah! More autorelease counts then retain counts left.
3480 // Emit hard error.
3481 stop = true;
3482 V = V ^ RefVal::ErrorOverAutorelease;
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003483 state = state->set<RefBindings>(Sym, V);
Ted Kremenekd35272f2009-05-09 00:10:05 +00003484
Zhongxing Xu20227f72009-08-06 01:32:16 +00003485 if (ExplodedNode *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek9ec08aa2009-05-09 00:44:07 +00003486 N->markAsSink();
Mike Stump11289f42009-09-09 15:08:12 +00003487
Ted Kremenek3978f792009-05-10 05:11:21 +00003488 std::string sbuf;
3489 llvm::raw_string_ostream os(sbuf);
Ted Kremenek4785e412009-05-15 06:02:08 +00003490 os << "Object over-autoreleased: object was sent -autorelease";
Ted Kremenek3978f792009-05-10 05:11:21 +00003491 if (V.getAutoreleaseCount() > 1)
3492 os << V.getAutoreleaseCount() << " times";
3493 os << " but the object has ";
3494 if (V.getCount() == 0)
3495 os << "zero (locally visible)";
3496 else
3497 os << "+" << V.getCount();
3498 os << " retain counts";
Mike Stump11289f42009-09-09 15:08:12 +00003499
Ted Kremenekd35272f2009-05-09 00:10:05 +00003500 CFRefReport *report =
3501 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
Ted Kremenek3978f792009-05-10 05:11:21 +00003502 *this, N, Sym, os.str().c_str());
Ted Kremenekd35272f2009-05-09 00:10:05 +00003503 BR->EmitReport(report);
3504 }
Mike Stump11289f42009-09-09 15:08:12 +00003505
Zhongxing Xu20227f72009-08-06 01:32:16 +00003506 return std::make_pair((ExplodedNode*)0, state);
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003507}
Ted Kremenek884a8992009-05-08 23:09:42 +00003508
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003509const GRState *
3510CFRefCount::HandleSymbolDeath(const GRState * state, SymbolRef sid, RefVal V,
Ted Kremenek884a8992009-05-08 23:09:42 +00003511 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
Mike Stump11289f42009-09-09 15:08:12 +00003512
3513 bool hasLeak = V.isOwned() ||
Ted Kremenek884a8992009-05-08 23:09:42 +00003514 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Mike Stump11289f42009-09-09 15:08:12 +00003515
Ted Kremenek884a8992009-05-08 23:09:42 +00003516 if (!hasLeak)
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003517 return state->remove<RefBindings>(sid);
Mike Stump11289f42009-09-09 15:08:12 +00003518
Ted Kremenek884a8992009-05-08 23:09:42 +00003519 Leaked.push_back(sid);
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003520 return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
Ted Kremenek884a8992009-05-08 23:09:42 +00003521}
3522
Zhongxing Xu20227f72009-08-06 01:32:16 +00003523ExplodedNode*
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003524CFRefCount::ProcessLeaks(const GRState * state,
Ted Kremenek884a8992009-05-08 23:09:42 +00003525 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3526 GenericNodeBuilder &Builder,
3527 GRExprEngine& Eng,
Zhongxing Xu20227f72009-08-06 01:32:16 +00003528 ExplodedNode *Pred) {
Mike Stump11289f42009-09-09 15:08:12 +00003529
Ted Kremenek884a8992009-05-08 23:09:42 +00003530 if (Leaked.empty())
3531 return Pred;
Mike Stump11289f42009-09-09 15:08:12 +00003532
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003533 // Generate an intermediate node representing the leak point.
Zhongxing Xu20227f72009-08-06 01:32:16 +00003534 ExplodedNode *N = Builder.MakeNode(state, Pred);
Mike Stump11289f42009-09-09 15:08:12 +00003535
Ted Kremenek884a8992009-05-08 23:09:42 +00003536 if (N) {
3537 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3538 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00003539
3540 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
Ted Kremenek884a8992009-05-08 23:09:42 +00003541 : leakAtReturn);
3542 assert(BT && "BugType not initialized.");
3543 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3544 BR->EmitReport(report);
3545 }
3546 }
Mike Stump11289f42009-09-09 15:08:12 +00003547
Ted Kremenek884a8992009-05-08 23:09:42 +00003548 return N;
3549}
3550
Ted Kremenek400aae72009-02-05 06:50:21 +00003551void CFRefCount::EvalEndPath(GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00003552 GREndPathNodeBuilder& Builder) {
Mike Stump11289f42009-09-09 15:08:12 +00003553
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003554 const GRState *state = Builder.getState();
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003555 GenericNodeBuilder Bd(Builder);
Mike Stump11289f42009-09-09 15:08:12 +00003556 RefBindings B = state->get<RefBindings>();
Zhongxing Xu20227f72009-08-06 01:32:16 +00003557 ExplodedNode *Pred = 0;
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003558
3559 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenekd35272f2009-05-09 00:10:05 +00003560 bool stop = false;
3561 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3562 (*I).first,
Mike Stump11289f42009-09-09 15:08:12 +00003563 (*I).second, stop);
Ted Kremenekd35272f2009-05-09 00:10:05 +00003564
3565 if (stop)
3566 return;
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003567 }
Mike Stump11289f42009-09-09 15:08:12 +00003568
3569 B = state->get<RefBindings>();
3570 llvm::SmallVector<SymbolRef, 10> Leaked;
3571
Ted Kremenek884a8992009-05-08 23:09:42 +00003572 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3573 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3574
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003575 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenek400aae72009-02-05 06:50:21 +00003576}
3577
Zhongxing Xu20227f72009-08-06 01:32:16 +00003578void CFRefCount::EvalDeadSymbols(ExplodedNodeSet& Dst,
Ted Kremenek400aae72009-02-05 06:50:21 +00003579 GRExprEngine& Eng,
Zhongxing Xu107f7592009-08-06 12:48:26 +00003580 GRStmtNodeBuilder& Builder,
Zhongxing Xu20227f72009-08-06 01:32:16 +00003581 ExplodedNode* Pred,
Ted Kremenek400aae72009-02-05 06:50:21 +00003582 Stmt* S,
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003583 const GRState* state,
Ted Kremenek400aae72009-02-05 06:50:21 +00003584 SymbolReaper& SymReaper) {
Ted Kremenek884a8992009-05-08 23:09:42 +00003585
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003586 RefBindings B = state->get<RefBindings>();
Mike Stump11289f42009-09-09 15:08:12 +00003587
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003588 // Update counts from autorelease pools
3589 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3590 E = SymReaper.dead_end(); I != E; ++I) {
3591 SymbolRef Sym = *I;
3592 if (const RefVal* T = B.lookup(Sym)){
3593 // Use the symbol as the tag.
3594 // FIXME: This might not be as unique as we would like.
3595 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenekd35272f2009-05-09 00:10:05 +00003596 bool stop = false;
3597 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3598 Sym, *T, stop);
3599 if (stop)
3600 return;
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003601 }
3602 }
Mike Stump11289f42009-09-09 15:08:12 +00003603
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003604 B = state->get<RefBindings>();
Ted Kremenek884a8992009-05-08 23:09:42 +00003605 llvm::SmallVector<SymbolRef, 10> Leaked;
Mike Stump11289f42009-09-09 15:08:12 +00003606
Ted Kremenek400aae72009-02-05 06:50:21 +00003607 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00003608 E = SymReaper.dead_end(); I != E; ++I) {
Ted Kremenek884a8992009-05-08 23:09:42 +00003609 if (const RefVal* T = B.lookup(*I))
3610 state = HandleSymbolDeath(state, *I, *T, Leaked);
Mike Stump11289f42009-09-09 15:08:12 +00003611 }
3612
Ted Kremenek884a8992009-05-08 23:09:42 +00003613 static unsigned LeakPPTag = 0;
Ted Kremenek8c8fb482009-05-08 23:32:51 +00003614 {
3615 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3616 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3617 }
Mike Stump11289f42009-09-09 15:08:12 +00003618
Ted Kremenek884a8992009-05-08 23:09:42 +00003619 // Did we cache out?
3620 if (!Pred)
3621 return;
Mike Stump11289f42009-09-09 15:08:12 +00003622
Ted Kremenek68abaa92009-02-19 23:47:02 +00003623 // Now generate a new node that nukes the old bindings.
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003624 RefBindings::Factory& F = state->get_context<RefBindings>();
Mike Stump11289f42009-09-09 15:08:12 +00003625
Ted Kremenek68abaa92009-02-19 23:47:02 +00003626 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek884a8992009-05-08 23:09:42 +00003627 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
Mike Stump11289f42009-09-09 15:08:12 +00003628
Ted Kremenekd93c6e32009-06-18 01:23:53 +00003629 state = state->set<RefBindings>(B);
Ted Kremenek68abaa92009-02-19 23:47:02 +00003630 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek400aae72009-02-05 06:50:21 +00003631}
3632
Zhongxing Xu20227f72009-08-06 01:32:16 +00003633void CFRefCount::ProcessNonLeakError(ExplodedNodeSet& Dst,
Zhongxing Xu107f7592009-08-06 12:48:26 +00003634 GRStmtNodeBuilder& Builder,
Zhongxing Xu20227f72009-08-06 01:32:16 +00003635 Expr* NodeExpr, Expr* ErrorExpr,
3636 ExplodedNode* Pred,
Ted Kremenek400aae72009-02-05 06:50:21 +00003637 const GRState* St,
3638 RefVal::Kind hasErr, SymbolRef Sym) {
3639 Builder.BuildSinks = true;
Zhongxing Xu107f7592009-08-06 12:48:26 +00003640 ExplodedNode *N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
Mike Stump11289f42009-09-09 15:08:12 +00003641
Ted Kremenek2d0ff622009-05-09 01:50:57 +00003642 if (!N)
3643 return;
Mike Stump11289f42009-09-09 15:08:12 +00003644
Ted Kremenek400aae72009-02-05 06:50:21 +00003645 CFRefBug *BT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003646
Ted Kremenekea072e32009-03-17 19:42:23 +00003647 switch (hasErr) {
3648 default:
3649 assert(false && "Unhandled error.");
3650 return;
3651 case RefVal::ErrorUseAfterRelease:
3652 BT = static_cast<CFRefBug*>(useAfterRelease);
Mike Stump11289f42009-09-09 15:08:12 +00003653 break;
Ted Kremenekea072e32009-03-17 19:42:23 +00003654 case RefVal::ErrorReleaseNotOwned:
3655 BT = static_cast<CFRefBug*>(releaseNotOwned);
3656 break;
3657 case RefVal::ErrorDeallocGC:
3658 BT = static_cast<CFRefBug*>(deallocGC);
3659 break;
3660 case RefVal::ErrorDeallocNotOwned:
3661 BT = static_cast<CFRefBug*>(deallocNotOwned);
3662 break;
Ted Kremenek400aae72009-02-05 06:50:21 +00003663 }
Mike Stump11289f42009-09-09 15:08:12 +00003664
Ted Kremenek48d16452009-02-18 03:48:14 +00003665 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek400aae72009-02-05 06:50:21 +00003666 report->addRange(ErrorExpr->getSourceRange());
3667 BR->EmitReport(report);
3668}
3669
3670//===----------------------------------------------------------------------===//
Ted Kremenek4a78c3a2008-04-10 22:16:52 +00003671// Transfer function creation for external clients.
Ted Kremenek819e9b62008-03-11 06:39:11 +00003672//===----------------------------------------------------------------------===//
3673
Ted Kremenekb0f87c42008-04-30 23:47:44 +00003674GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3675 const LangOptions& lopts) {
Ted Kremenek1f352db2008-07-22 16:21:24 +00003676 return new CFRefCount(Ctx, GCEnabled, lopts);
Mike Stump11289f42009-09-09 15:08:12 +00003677}