blob: b190ac20dfbd5ffedeb7485d4caceb6602467a84 [file] [log] [blame]
Chris Lattnerbda0b622008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek2fff37e2008-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 Greif843e9342008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek2fff37e2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenek072192b2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekc9fa2f72008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremenek2fff37e2008-03-06 00:08:09 +000018#include "clang/Analysis/PathSensitive/ValueState.h"
Ted Kremenek4dc41cc2008-03-31 18:26:32 +000019#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek2fff37e2008-03-06 00:08:09 +000020#include "clang/Analysis/LocalCheckers.h"
Ted Kremenekfa34b332008-04-09 01:10:13 +000021#include "clang/Analysis/PathDiagnostic.h"
22#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000023#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/FoldingSet.h"
25#include "llvm/ADT/ImmutableMap.h"
Ted Kremenek900a2d72008-05-07 18:36:45 +000026#include "llvm/ADT/StringExtras.h"
Ted Kremenekfa34b332008-04-09 01:10:13 +000027#include "llvm/Support/Compiler.h"
Ted Kremenek6ed9afc2008-05-16 18:33:44 +000028#include "llvm/ADT/STLExtras.h"
Ted Kremenekf3948042008-03-11 19:44:10 +000029#include <ostream>
Ted Kremenek2cf943a2008-04-18 04:55:01 +000030#include <sstream>
Ted Kremenek2fff37e2008-03-06 00:08:09 +000031
32using namespace clang;
Ted Kremenek900a2d72008-05-07 18:36:45 +000033using llvm::CStrInCStrNoCase;
Ted Kremenek2fff37e2008-03-06 00:08:09 +000034
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000035//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +000036// Selector creation functions.
Ted Kremenek4fd88972008-04-17 18:12:53 +000037//===----------------------------------------------------------------------===//
38
Ted Kremenekb83e02e2008-05-01 18:31:44 +000039static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenek4fd88972008-04-17 18:12:53 +000040 IdentifierInfo* II = &Ctx.Idents.get(name);
41 return Ctx.Selectors.getSelector(0, &II);
42}
43
Ted Kremenek9c32d082008-05-06 00:30:21 +000044static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
45 IdentifierInfo* II = &Ctx.Idents.get(name);
46 return Ctx.Selectors.getSelector(1, &II);
47}
48
Ted Kremenek553cf182008-06-25 21:21:56 +000049//===----------------------------------------------------------------------===//
50// Type querying functions.
51//===----------------------------------------------------------------------===//
52
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +000053static bool isCFRefType(QualType T) {
54
55 if (!T->isPointerType())
56 return false;
57
Ted Kremenek553cf182008-06-25 21:21:56 +000058 // Check the typedef for the name "CF" and the substring "Ref".
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +000059 TypedefType* TD = dyn_cast<TypedefType>(T.getTypePtr());
60
61 if (!TD)
62 return false;
63
64 const char* TDName = TD->getDecl()->getIdentifier()->getName();
65 assert (TDName);
66
67 if (TDName[0] != 'C' || TDName[1] != 'F')
68 return false;
69
70 if (strstr(TDName, "Ref") == 0)
71 return false;
72
73 return true;
74}
75
76static bool isNSType(QualType T) {
77
78 if (!T->isPointerType())
79 return false;
80
81 ObjCInterfaceType* OT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
82
83 if (!OT)
84 return false;
85
86 const char* ClsName = OT->getDecl()->getIdentifier()->getName();
87 assert (ClsName);
88
89 if (ClsName[0] != 'N' || ClsName[1] != 'S')
90 return false;
91
92 return true;
93}
94
Ted Kremenek4fd88972008-04-17 18:12:53 +000095//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +000096// Primitives used for constructing summaries for function/method calls.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000097//===----------------------------------------------------------------------===//
98
Ted Kremenek553cf182008-06-25 21:21:56 +000099namespace {
100/// ArgEffect is used to summarize a function/method call's effect on a
101/// particular argument.
102enum ArgEffect { IncRef, DecRef, DoNothing, StopTracking, MayEscape,
Ted Kremeneke19f4492008-06-30 16:57:41 +0000103 SelfOwn, Autorelease };
Ted Kremenek553cf182008-06-25 21:21:56 +0000104
105/// ArgEffects summarizes the effects of a function/method call on all of
106/// its arguments.
107typedef std::vector<std::pair<unsigned,ArgEffect> > ArgEffects;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000108}
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000109
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000110namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000111template <> struct FoldingSetTrait<ArgEffects> {
112 static void Profile(const ArgEffects& X, FoldingSetNodeID& ID) {
113 for (ArgEffects::const_iterator I = X.begin(), E = X.end(); I!= E; ++I) {
114 ID.AddInteger(I->first);
115 ID.AddInteger((unsigned) I->second);
116 }
117 }
118};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000119} // end llvm namespace
120
121namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +0000122
123/// RetEffect is used to summarize a function/method call's behavior with
124/// respect to its return value.
125class VISIBILITY_HIDDEN RetEffect {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000126public:
Ted Kremeneka7344702008-06-23 18:02:52 +0000127 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
128 NotOwnedSymbol, ReceiverAlias };
Ted Kremenek553cf182008-06-25 21:21:56 +0000129
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000130private:
131 unsigned Data;
Ted Kremenek553cf182008-06-25 21:21:56 +0000132 RetEffect(Kind k, unsigned D = 0) { Data = (D << 3) | (unsigned) k; }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000133
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000134public:
Ted Kremenek553cf182008-06-25 21:21:56 +0000135
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000136 Kind getKind() const { return (Kind) (Data & 0x7); }
Ted Kremenek553cf182008-06-25 21:21:56 +0000137
138 unsigned getIndex() const {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000139 assert(getKind() == Alias);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000140 return Data >> 3;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000141 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000142
Ted Kremenek553cf182008-06-25 21:21:56 +0000143 static RetEffect MakeAlias(unsigned Idx) {
144 return RetEffect(Alias, Idx);
145 }
146 static RetEffect MakeReceiverAlias() {
147 return RetEffect(ReceiverAlias);
148 }
Ted Kremeneka7344702008-06-23 18:02:52 +0000149 static RetEffect MakeOwned(bool isAllocated = false) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000150 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol);
151 }
152 static RetEffect MakeNotOwned() {
153 return RetEffect(NotOwnedSymbol);
154 }
155 static RetEffect MakeNoRet() {
156 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000157 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000158
Ted Kremenek553cf182008-06-25 21:21:56 +0000159 operator Kind() const {
160 return getKind();
161 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000162
Ted Kremenek553cf182008-06-25 21:21:56 +0000163 void Profile(llvm::FoldingSetNodeID& ID) const {
164 ID.AddInteger(Data);
165 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000166};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000167
Ted Kremenek553cf182008-06-25 21:21:56 +0000168
169class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000170 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
171 /// specifies the argument (starting from 0). This can be sparsely
172 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000173 ArgEffects* Args;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000174
175 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
176 /// do not have an entry in Args.
177 ArgEffect DefaultArgEffect;
178
Ted Kremenek553cf182008-06-25 21:21:56 +0000179 /// Receiver - If this summary applies to an Objective-C message expression,
180 /// this is the effect applied to the state of the receiver.
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000181 ArgEffect Receiver;
Ted Kremenek553cf182008-06-25 21:21:56 +0000182
183 /// Ret - The effect on the return value. Used to indicate if the
184 /// function/method call returns a new tracked symbol, returns an
185 /// alias of one of the arguments in the call, and so on.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000186 RetEffect Ret;
Ted Kremenek553cf182008-06-25 21:21:56 +0000187
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000188public:
189
Ted Kremenek1bffd742008-05-06 15:44:25 +0000190 RetainSummary(ArgEffects* A, RetEffect R, ArgEffect defaultEff,
191 ArgEffect ReceiverEff)
192 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000193
Ted Kremenek553cf182008-06-25 21:21:56 +0000194 /// getArg - Return the argument effect on the argument specified by
195 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000196 ArgEffect getArg(unsigned idx) const {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000197
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000198 if (!Args)
Ted Kremenek1bffd742008-05-06 15:44:25 +0000199 return DefaultArgEffect;
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000200
201 // If Args is present, it is likely to contain only 1 element.
202 // Just do a linear search. Do it from the back because functions with
203 // large numbers of arguments will be tail heavy with respect to which
Ted Kremenek553cf182008-06-25 21:21:56 +0000204 // argument they actually modify with respect to the reference count.
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000205 for (ArgEffects::reverse_iterator I=Args->rbegin(), E=Args->rend();
206 I!=E; ++I) {
207
208 if (idx > I->first)
Ted Kremenek1bffd742008-05-06 15:44:25 +0000209 return DefaultArgEffect;
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000210
211 if (idx == I->first)
212 return I->second;
213 }
214
Ted Kremenek1bffd742008-05-06 15:44:25 +0000215 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000216 }
217
Ted Kremenek553cf182008-06-25 21:21:56 +0000218 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000219 RetEffect getRetEffect() const {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000220 return Ret;
221 }
222
Ted Kremenek553cf182008-06-25 21:21:56 +0000223 /// getReceiverEffect - Returns the effect on the receiver of the call.
224 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000225 ArgEffect getReceiverEffect() const {
226 return Receiver;
227 }
228
Ted Kremenek55499762008-06-17 02:43:46 +0000229 typedef ArgEffects::const_iterator ExprIterator;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000230
Ted Kremenek55499762008-06-17 02:43:46 +0000231 ExprIterator begin_args() const { return Args->begin(); }
232 ExprIterator end_args() const { return Args->end(); }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000233
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000234 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects* A,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000235 RetEffect RetEff, ArgEffect DefaultEff,
236 ArgEffect ReceiverEff) {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000237 ID.AddPointer(A);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000238 ID.Add(RetEff);
Ted Kremenek1bffd742008-05-06 15:44:25 +0000239 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000240 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000241 }
242
243 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000244 Profile(ID, Args, Ret, DefaultArgEffect, Receiver);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000245 }
246};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000247} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000248
Ted Kremenek553cf182008-06-25 21:21:56 +0000249//===----------------------------------------------------------------------===//
250// Data structures for constructing summaries.
251//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000252
Ted Kremenek553cf182008-06-25 21:21:56 +0000253namespace {
254class VISIBILITY_HIDDEN ObjCSummaryKey {
255 IdentifierInfo* II;
256 Selector S;
257public:
258 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
259 : II(ii), S(s) {}
260
261 ObjCSummaryKey(ObjCInterfaceDecl* d, Selector s)
262 : II(d ? d->getIdentifier() : 0), S(s) {}
263
264 ObjCSummaryKey(Selector s)
265 : II(0), S(s) {}
266
267 IdentifierInfo* getIdentifier() const { return II; }
268 Selector getSelector() const { return S; }
269};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000270}
271
272namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000273template <> struct DenseMapInfo<ObjCSummaryKey> {
274 static inline ObjCSummaryKey getEmptyKey() {
275 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
276 DenseMapInfo<Selector>::getEmptyKey());
277 }
Ted Kremenek4f22a782008-06-23 23:30:29 +0000278
Ted Kremenek553cf182008-06-25 21:21:56 +0000279 static inline ObjCSummaryKey getTombstoneKey() {
280 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
281 DenseMapInfo<Selector>::getTombstoneKey());
282 }
283
284 static unsigned getHashValue(const ObjCSummaryKey &V) {
285 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
286 & 0x88888888)
287 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
288 & 0x55555555);
289 }
290
291 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
292 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
293 RHS.getIdentifier()) &&
294 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
295 RHS.getSelector());
296 }
297
298 static bool isPod() {
299 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
300 DenseMapInfo<Selector>::isPod();
301 }
302};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000303} // end llvm namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000304
Ted Kremenek4f22a782008-06-23 23:30:29 +0000305namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +0000306class VISIBILITY_HIDDEN ObjCSummaryCache {
307 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
308 MapTy M;
309public:
310 ObjCSummaryCache() {}
311
312 typedef MapTy::iterator iterator;
313
314 iterator find(ObjCInterfaceDecl* D, Selector S) {
315
316 // Do a lookup with the (D,S) pair. If we find a match return
317 // the iterator.
318 ObjCSummaryKey K(D, S);
319 MapTy::iterator I = M.find(K);
320
321 if (I != M.end() || !D)
322 return I;
323
324 // Walk the super chain. If we find a hit with a parent, we'll end
325 // up returning that summary. We actually allow that key (null,S), as
326 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
327 // generate initial summaries without having to worry about NSObject
328 // being declared.
329 // FIXME: We may change this at some point.
330 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
331 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
332 break;
333
334 if (!C)
335 return I;
336 }
337
338 // Cache the summary with original key to make the next lookup faster
339 // and return the iterator.
340 M[K] = I->second;
341 return I;
342 }
343
344
345 iterator find(Expr* Receiver, Selector S) {
346 return find(getReceiverDecl(Receiver), S);
347 }
348
349 iterator find(IdentifierInfo* II, Selector S) {
350 // FIXME: Class method lookup. Right now we dont' have a good way
351 // of going between IdentifierInfo* and the class hierarchy.
352 iterator I = M.find(ObjCSummaryKey(II, S));
353 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
354 }
355
356 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
357
358 const PointerType* PT = E->getType()->getAsPointerType();
359 if (!PT) return 0;
360
361 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
362 if (!OI) return 0;
363
364 return OI ? OI->getDecl() : 0;
365 }
366
367 iterator end() { return M.end(); }
368
369 RetainSummary*& operator[](ObjCMessageExpr* ME) {
370
371 Selector S = ME->getSelector();
372
373 if (Expr* Receiver = ME->getReceiver()) {
374 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
375 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
376 }
377
378 return M[ObjCSummaryKey(ME->getClassName(), S)];
379 }
380
381 RetainSummary*& operator[](ObjCSummaryKey K) {
382 return M[K];
383 }
384
385 RetainSummary*& operator[](Selector S) {
386 return M[ ObjCSummaryKey(S) ];
387 }
388};
389} // end anonymous namespace
390
391//===----------------------------------------------------------------------===//
392// Data structures for managing collections of summaries.
393//===----------------------------------------------------------------------===//
394
395namespace {
396class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000397
398 //==-----------------------------------------------------------------==//
399 // Typedefs.
400 //==-----------------------------------------------------------------==//
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000401
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000402 typedef llvm::FoldingSet<llvm::FoldingSetNodeWrapper<ArgEffects> >
403 ArgEffectsSetTy;
404
405 typedef llvm::FoldingSet<RetainSummary>
406 SummarySetTy;
407
408 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
409 FuncSummariesTy;
410
Ted Kremenek4f22a782008-06-23 23:30:29 +0000411 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000412
413 //==-----------------------------------------------------------------==//
414 // Data.
415 //==-----------------------------------------------------------------==//
416
Ted Kremenek553cf182008-06-25 21:21:56 +0000417 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek377e2302008-04-29 05:33:51 +0000418 ASTContext& Ctx;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000419
Ted Kremenek553cf182008-06-25 21:21:56 +0000420 /// NSWindowII - An IdentifierInfo* representing the identifier "NSWindow."
421 IdentifierInfo* NSWindowII;
Ted Kremenek179064e2008-07-01 17:21:27 +0000422
423 /// NSPanelII - An IdentifierInfo* representing the identifier "NSPanel."
424 IdentifierInfo* NSPanelII;
Ted Kremenek553cf182008-06-25 21:21:56 +0000425
426 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000427 const bool GCEnabled;
428
Ted Kremenek553cf182008-06-25 21:21:56 +0000429 /// SummarySet - A FoldingSet of uniqued summaries.
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +0000430 SummarySetTy SummarySet;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000431
Ted Kremenek553cf182008-06-25 21:21:56 +0000432 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000433 FuncSummariesTy FuncSummaries;
434
Ted Kremenek553cf182008-06-25 21:21:56 +0000435 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
436 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000437 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000438
Ted Kremenek553cf182008-06-25 21:21:56 +0000439 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000440 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000441
Ted Kremenek553cf182008-06-25 21:21:56 +0000442 /// ArgEffectsSet - A FoldingSet of uniqued ArgEffects.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000443 ArgEffectsSetTy ArgEffectsSet;
444
Ted Kremenek553cf182008-06-25 21:21:56 +0000445 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
446 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000447 llvm::BumpPtrAllocator BPAlloc;
448
Ted Kremenek553cf182008-06-25 21:21:56 +0000449 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000450 ArgEffects ScratchArgs;
451
Ted Kremenek432af592008-05-06 18:11:36 +0000452 RetainSummary* StopSummary;
453
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000454 //==-----------------------------------------------------------------==//
455 // Methods.
456 //==-----------------------------------------------------------------==//
457
Ted Kremenek553cf182008-06-25 21:21:56 +0000458 /// getArgEffects - Returns a persistent ArgEffects object based on the
459 /// data in ScratchArgs.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000460 ArgEffects* getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000461
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000462 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000463 RetainSummary* getUnarySummary(FunctionDecl* FD, UnaryFuncKind func);
Ted Kremenek377e2302008-04-29 05:33:51 +0000464
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000465 RetainSummary* getNSSummary(FunctionDecl* FD, const char* FName);
466 RetainSummary* getCFSummary(FunctionDecl* FD, const char* FName);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000467
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000468 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
469 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000470
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000471 RetainSummary* getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000472 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000473 ArgEffect DefaultEff = MayEscape);
Ted Kremenek1bffd742008-05-06 15:44:25 +0000474
Ted Kremenek9c32d082008-05-06 00:30:21 +0000475
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000476 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000477 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000478 ArgEffect DefaultEff = MayEscape) {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000479 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000480 }
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000481
Ted Kremenek432af592008-05-06 18:11:36 +0000482
Ted Kremenek1bffd742008-05-06 15:44:25 +0000483 RetainSummary* getPersistentStopSummary() {
Ted Kremenek432af592008-05-06 18:11:36 +0000484 if (StopSummary)
485 return StopSummary;
486
487 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
488 StopTracking, StopTracking);
489
490 return StopSummary;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000491 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000492
Ted Kremenek553cf182008-06-25 21:21:56 +0000493 RetainSummary* getInitMethodSummary(ObjCMessageExpr* ME);
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000494
Ted Kremenek1f180c32008-06-23 22:21:20 +0000495 void InitializeClassMethodSummaries();
496 void InitializeMethodSummaries();
Ted Kremenek9c32d082008-05-06 00:30:21 +0000497
Ted Kremenek553cf182008-06-25 21:21:56 +0000498 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
499 ObjCClassMethodSummaries[S] = Summ;
500 }
501
502 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
503 ObjCMethodSummaries[S] = Summ;
504 }
505
506 void addNSWindowMethSummary(Selector S, RetainSummary *Summ) {
507 ObjCMethodSummaries[ObjCSummaryKey(NSWindowII, S)] = Summ;
508 }
509
Ted Kremenek179064e2008-07-01 17:21:27 +0000510 void addNSPanelMethSummary(Selector S, RetainSummary *Summ) {
511 ObjCMethodSummaries[ObjCSummaryKey(NSPanelII, S)] = Summ;
512 }
513
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000514public:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000515
516 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremenek179064e2008-07-01 17:21:27 +0000517 : Ctx(ctx),
518 NSWindowII(&ctx.Idents.get("NSWindow")),
519 NSPanelII(&ctx.Idents.get("NSPanel")),
Ted Kremenek553cf182008-06-25 21:21:56 +0000520 GCEnabled(gcenabled), StopSummary(0) {
521
522 InitializeClassMethodSummaries();
523 InitializeMethodSummaries();
524 }
Ted Kremenek377e2302008-04-29 05:33:51 +0000525
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000526 ~RetainSummaryManager();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000527
Ted Kremenekab592272008-06-24 03:56:45 +0000528 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek553cf182008-06-25 21:21:56 +0000529 RetainSummary* getMethodSummary(ObjCMessageExpr* ME, ObjCInterfaceDecl* ID);
Ted Kremenek1f180c32008-06-23 22:21:20 +0000530 RetainSummary* getClassMethodSummary(IdentifierInfo* ClsName, Selector S);
Ted Kremenekb3095252008-05-06 04:20:12 +0000531
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000532 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000533};
534
535} // end anonymous namespace
536
537//===----------------------------------------------------------------------===//
538// Implementation of checker data structures.
539//===----------------------------------------------------------------------===//
540
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000541RetainSummaryManager::~RetainSummaryManager() {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000542
543 // FIXME: The ArgEffects could eventually be allocated from BPAlloc,
544 // mitigating the need to do explicit cleanup of the
545 // Argument-Effect summaries.
546
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000547 for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(),
548 E = ArgEffectsSet.end(); I!=E; ++I)
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000549 I->getValue().~ArgEffects();
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000550}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000551
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000552ArgEffects* RetainSummaryManager::getArgEffects() {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000553
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000554 if (ScratchArgs.empty())
555 return NULL;
556
557 // Compute a profile for a non-empty ScratchArgs.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000558 llvm::FoldingSetNodeID profile;
559 profile.Add(ScratchArgs);
560 void* InsertPos;
561
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000562 // Look up the uniqued copy, or create a new one.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000563 llvm::FoldingSetNodeWrapper<ArgEffects>* E =
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000564 ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000565
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000566 if (E) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000567 ScratchArgs.clear();
568 return &E->getValue();
569 }
570
571 E = (llvm::FoldingSetNodeWrapper<ArgEffects>*)
Ted Kremenek553cf182008-06-25 21:21:56 +0000572 BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000573
574 new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000575 ArgEffectsSet.InsertNode(E, InsertPos);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000576
577 ScratchArgs.clear();
578 return &E->getValue();
579}
580
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000581RetainSummary*
582RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000583 ArgEffect ReceiverEff,
584 ArgEffect DefaultEff) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000585
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000586 // Generate a profile for the summary.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000587 llvm::FoldingSetNodeID profile;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000588 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000589
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000590 // Look up the uniqued summary, or create one if it doesn't exist.
591 void* InsertPos;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000592 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000593
594 if (Summ)
595 return Summ;
596
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000597 // Create the summary and return it.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000598 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenek1bffd742008-05-06 15:44:25 +0000599 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000600 SummarySet.InsertNode(Summ, InsertPos);
601
602 return Summ;
603}
604
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000605//===----------------------------------------------------------------------===//
606// Summary creation for functions (largely uses of Core Foundation).
607//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000608
Ted Kremenekab592272008-06-24 03:56:45 +0000609RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000610
611 SourceLocation Loc = FD->getLocation();
612
613 if (!Loc.isFileID())
614 return NULL;
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000615
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000616 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000617 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000618
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000619 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000620 return I->second;
621
622 // No summary. Generate one.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000623 const char* FName = FD->getIdentifier()->getName();
624
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000625 RetainSummary *S = 0;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000626
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000627 FunctionType* FT = dyn_cast<FunctionType>(FD->getType());
628
629 if (FT && isCFRefType(FT->getResultType()))
630 S = getCFSummary(FD, FName);
631 else if (FName[0] == 'C' && FName[1] == 'F')
632 S = getCFSummary(FD, FName);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000633 else if (FName[0] == 'N' && FName[1] == 'S')
634 S = getNSSummary(FD, FName);
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000635
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000636 FuncSummaries[FD] = S;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000637 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000638}
639
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000640RetainSummary* RetainSummaryManager::getNSSummary(FunctionDecl* FD,
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000641 const char* FName) {
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000642 FName += 2;
643
644 if (strcmp(FName, "MakeCollectable") == 0)
645 return getUnarySummary(FD, cfmakecollectable);
646
647 return 0;
648}
649
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000650RetainSummary* RetainSummaryManager::getCFSummary(FunctionDecl* FD,
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000651 const char* FName) {
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000652
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000653 if (FName[0] == 'C' && FName[1] == 'F')
654 FName += 2;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000655
656 if (strcmp(FName, "Retain") == 0)
657 return getUnarySummary(FD, cfretain);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000658
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000659 if (strcmp(FName, "Release") == 0)
660 return getUnarySummary(FD, cfrelease);
661
662 if (strcmp(FName, "MakeCollectable") == 0)
663 return getUnarySummary(FD, cfmakecollectable);
664
665 if (strstr(FName, "Create") || strstr(FName, "Copy"))
666 return getCFSummaryCreateRule(FD);
667
668 if (strstr(FName, "Get"))
669 return getCFSummaryGetRule(FD);
670
671 return 0;
672}
673
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000674RetainSummary*
675RetainSummaryManager::getUnarySummary(FunctionDecl* FD, UnaryFuncKind func) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000676
677 FunctionTypeProto* FT =
678 dyn_cast<FunctionTypeProto>(FD->getType().getTypePtr());
679
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000680 if (FT) {
681
682 if (FT->getNumArgs() != 1)
683 return 0;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000684
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000685 TypedefType* ArgT = dyn_cast<TypedefType>(FT->getArgType(0).getTypePtr());
686
687 if (!ArgT)
688 return 0;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000689
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000690 if (!ArgT->isPointerType())
691 return NULL;
692 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000693
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000694 assert (ScratchArgs.empty());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000695
Ted Kremenek377e2302008-04-29 05:33:51 +0000696 switch (func) {
697 case cfretain: {
Ted Kremenek377e2302008-04-29 05:33:51 +0000698 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000699 return getPersistentSummary(RetEffect::MakeAlias(0),
700 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000701 }
702
703 case cfrelease: {
Ted Kremenek377e2302008-04-29 05:33:51 +0000704 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000705 return getPersistentSummary(RetEffect::MakeNoRet(),
706 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000707 }
708
709 case cfmakecollectable: {
Ted Kremenek377e2302008-04-29 05:33:51 +0000710 if (GCEnabled)
711 ScratchArgs.push_back(std::make_pair(0, DecRef));
712
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000713 return getPersistentSummary(RetEffect::MakeAlias(0),
714 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000715 }
716
717 default:
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000718 assert (false && "Not a supported unary function.");
Ted Kremenek940b1d82008-04-10 23:44:06 +0000719 }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000720}
721
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000722RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000723
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000724 FunctionType* FT =
725 dyn_cast<FunctionType>(FD->getType().getTypePtr());
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000726
727 if (FT && !isCFRefType(FT->getResultType()))
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000728 return getPersistentSummary(RetEffect::MakeNoRet());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000729
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000730 // FIXME: Add special-cases for functions that retain/release. For now
731 // just handle the default case.
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000732
733 assert (ScratchArgs.empty());
Ted Kremeneka7344702008-06-23 18:02:52 +0000734 return getPersistentSummary(RetEffect::MakeOwned(true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000735}
736
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000737RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000738
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000739 FunctionType* FT =
740 dyn_cast<FunctionType>(FD->getType().getTypePtr());
Ted Kremeneka0df99f2008-04-11 20:11:19 +0000741
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000742 if (FT) {
743 QualType RetTy = FT->getResultType();
Ted Kremeneka0df99f2008-04-11 20:11:19 +0000744
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000745 // FIXME: For now we assume that all pointer types returned are referenced
746 // counted. Since this is the "Get" rule, we assume non-ownership, which
747 // works fine for things that are not reference counted. We do this because
748 // some generic data structures return "void*". We need something better
749 // in the future.
750
751 if (!isCFRefType(RetTy) && !RetTy->isPointerType())
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000752 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000753 }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000754
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000755 // FIXME: Add special-cases for functions that retain/release. For now
756 // just handle the default case.
757
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000758 assert (ScratchArgs.empty());
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000759 return getPersistentSummary(RetEffect::MakeNotOwned(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000760}
761
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000762//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000763// Summary creation for Selectors.
764//===----------------------------------------------------------------------===//
765
Ted Kremenek1bffd742008-05-06 15:44:25 +0000766RetainSummary*
Ted Kremenek553cf182008-06-25 21:21:56 +0000767RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000768 assert(ScratchArgs.empty());
769
770 RetainSummary* Summ =
Ted Kremenek9c32d082008-05-06 00:30:21 +0000771 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000772
Ted Kremenek553cf182008-06-25 21:21:56 +0000773 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000774 return Summ;
775}
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000776
Ted Kremenek553cf182008-06-25 21:21:56 +0000777
Ted Kremenek1bffd742008-05-06 15:44:25 +0000778RetainSummary*
Ted Kremenek553cf182008-06-25 21:21:56 +0000779RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
780 ObjCInterfaceDecl* ID) {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000781
782 Selector S = ME->getSelector();
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000783
Ted Kremenek553cf182008-06-25 21:21:56 +0000784 // Look up a summary in our summary cache.
785 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000786
Ted Kremenek1f180c32008-06-23 22:21:20 +0000787 if (I != ObjCMethodSummaries.end())
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000788 return I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000789
Ted Kremeneka4b695a2008-05-07 03:45:05 +0000790 if (!ME->getType()->isPointerType())
791 return 0;
792
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000793 // "initXXX": pass-through for receiver.
794
795 const char* s = S.getIdentifierInfoForSlot(0)->getName();
Ted Kremeneka4b695a2008-05-07 03:45:05 +0000796 assert (ScratchArgs.empty());
Ted Kremenekaee9e572008-05-06 06:09:09 +0000797
Ted Kremenek0327f772008-06-02 17:14:13 +0000798 if (strncmp(s, "init", 4) == 0 || strncmp(s, "_init", 5) == 0)
Ted Kremenek553cf182008-06-25 21:21:56 +0000799 return getInitMethodSummary(ME);
Ted Kremenek1bffd742008-05-06 15:44:25 +0000800
Ted Kremeneka4b695a2008-05-07 03:45:05 +0000801 // "copyXXX", "createXXX", "newXXX": allocators.
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000802
Ted Kremenek84060db2008-05-07 04:25:59 +0000803 if (!isNSType(ME->getReceiver()->getType()))
804 return 0;
805
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000806 if (CStrInCStrNoCase(s, "create") || CStrInCStrNoCase(s, "copy") ||
807 CStrInCStrNoCase(s, "new")) {
Ted Kremeneka4b695a2008-05-07 03:45:05 +0000808
809 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremeneka7344702008-06-23 18:02:52 +0000810 : RetEffect::MakeOwned(true);
Ted Kremeneka4b695a2008-05-07 03:45:05 +0000811
812 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenek553cf182008-06-25 21:21:56 +0000813 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000814 return Summ;
815 }
Ted Kremenek1bffd742008-05-06 15:44:25 +0000816
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000817 return 0;
818}
819
Ted Kremenekc8395602008-05-06 21:26:51 +0000820RetainSummary*
Ted Kremenek1f180c32008-06-23 22:21:20 +0000821RetainSummaryManager::getClassMethodSummary(IdentifierInfo* ClsName,
822 Selector S) {
Ted Kremenekc8395602008-05-06 21:26:51 +0000823
Ted Kremenek553cf182008-06-25 21:21:56 +0000824 // FIXME: Eventually we should properly do class method summaries, but
825 // it requires us being able to walk the type hierarchy. Unfortunately,
826 // we cannot do this with just an IdentifierInfo* for the class name.
827
Ted Kremenekc8395602008-05-06 21:26:51 +0000828 // Look up a summary in our cache of Selectors -> Summaries.
Ted Kremenek553cf182008-06-25 21:21:56 +0000829 ObjCMethodSummariesTy::iterator I = ObjCClassMethodSummaries.find(ClsName, S);
Ted Kremenekc8395602008-05-06 21:26:51 +0000830
Ted Kremenek1f180c32008-06-23 22:21:20 +0000831 if (I != ObjCClassMethodSummaries.end())
Ted Kremenekc8395602008-05-06 21:26:51 +0000832 return I->second;
833
Ted Kremeneka22cc2f2008-05-06 23:07:13 +0000834 return 0;
Ted Kremenekc8395602008-05-06 21:26:51 +0000835}
836
Ted Kremenek1f180c32008-06-23 22:21:20 +0000837void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek9c32d082008-05-06 00:30:21 +0000838
839 assert (ScratchArgs.empty());
840
Ted Kremeneka7344702008-06-23 18:02:52 +0000841 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
842 : RetEffect::MakeOwned(true);
843
Ted Kremenek9c32d082008-05-06 00:30:21 +0000844 RetainSummary* Summ = getPersistentSummary(E);
845
Ted Kremenek553cf182008-06-25 21:21:56 +0000846 // Create the summaries for "alloc", "new", and "allocWithZone:" for
847 // NSObject and its derivatives.
848 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
849 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
850 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000851}
852
Ted Kremenek1f180c32008-06-23 22:21:20 +0000853void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenekb3c3c282008-05-06 00:38:54 +0000854
855 assert (ScratchArgs.empty());
856
Ted Kremenekc8395602008-05-06 21:26:51 +0000857 // Create the "init" selector. It just acts as a pass-through for the
858 // receiver.
Ted Kremenek179064e2008-07-01 17:21:27 +0000859 RetainSummary* InitSumm = getPersistentSummary(RetEffect::MakeReceiverAlias());
860 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremenekc8395602008-05-06 21:26:51 +0000861
862 // The next methods are allocators.
Ted Kremeneka7344702008-06-23 18:02:52 +0000863 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
864 : RetEffect::MakeOwned(true);
865
Ted Kremenek179064e2008-07-01 17:21:27 +0000866 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenekc8395602008-05-06 21:26:51 +0000867
868 // Create the "copy" selector.
Ted Kremenek553cf182008-06-25 21:21:56 +0000869 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
Ted Kremenekb3c3c282008-05-06 00:38:54 +0000870
871 // Create the "mutableCopy" selector.
Ted Kremenek553cf182008-06-25 21:21:56 +0000872 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000873
874 // Create the "retain" selector.
875 E = RetEffect::MakeReceiverAlias();
876 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : IncRef);
Ted Kremenek553cf182008-06-25 21:21:56 +0000877 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000878
879 // Create the "release" selector.
880 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +0000881 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenek299e8152008-05-07 21:17:39 +0000882
883 // Create the "drain" selector.
884 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +0000885 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000886
887 // Create the "autorelease" selector.
Ted Kremeneke19f4492008-06-30 16:57:41 +0000888 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +0000889 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
890
891 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek179064e2008-07-01 17:21:27 +0000892 // For NSPanel (which subclasses NSWindow), allocated objects are not
893 // self-owned.
894
895 RetainSummary *NSWindowSumm =
896 getPersistentSummary(RetEffect::MakeReceiverAlias(), SelfOwn);
Ted Kremenek553cf182008-06-25 21:21:56 +0000897
898 // Create the "initWithContentRect:styleMask:backing:defer:" selector.
899 llvm::SmallVector<IdentifierInfo*, 5> II;
900 II.push_back(&Ctx.Idents.get("initWithContentRect"));
901 II.push_back(&Ctx.Idents.get("styleMask"));
902 II.push_back(&Ctx.Idents.get("backing"));
903 II.push_back(&Ctx.Idents.get("defer"));
904 Selector S = Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenek179064e2008-07-01 17:21:27 +0000905 addNSWindowMethSummary(S, NSWindowSumm);
906 addNSPanelMethSummary(S, InitSumm);
907
Ted Kremenek553cf182008-06-25 21:21:56 +0000908 // Create the "initWithContentRect:styleMask:backing:defer:screen:" selector.
909 II.push_back(&Ctx.Idents.get("screen"));
910 S = Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenek179064e2008-07-01 17:21:27 +0000911 addNSWindowMethSummary(S, NSWindowSumm);
912 addNSPanelMethSummary(S, InitSumm);
Ted Kremenekb3c3c282008-05-06 00:38:54 +0000913}
914
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000915//===----------------------------------------------------------------------===//
Ted Kremenek13922612008-04-16 20:40:59 +0000916// Reference-counting logic (typestate + counts).
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000917//===----------------------------------------------------------------------===//
918
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000919namespace {
920
Ted Kremenek05cbe1a2008-04-09 23:49:11 +0000921class VISIBILITY_HIDDEN RefVal {
Ted Kremenek4fd88972008-04-17 18:12:53 +0000922public:
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000923
Ted Kremenek4fd88972008-04-17 18:12:53 +0000924 enum Kind {
925 Owned = 0, // Owning reference.
926 NotOwned, // Reference is not owned by still valid (not freed).
927 Released, // Object has been released.
928 ReturnedOwned, // Returned object passes ownership to caller.
929 ReturnedNotOwned, // Return object does not pass ownership to caller.
930 ErrorUseAfterRelease, // Object used after released.
931 ErrorReleaseNotOwned, // Release of an object that was not owned.
932 ErrorLeak // A memory leak due to excessive reference counts.
933 };
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000934
Ted Kremenek4fd88972008-04-17 18:12:53 +0000935private:
936
937 Kind kind;
938 unsigned Cnt;
Ted Kremenek553cf182008-06-25 21:21:56 +0000939 QualType T;
940
941 RefVal(Kind k, unsigned cnt, QualType t) : kind(k), Cnt(cnt), T(t) {}
942 RefVal(Kind k, unsigned cnt = 0) : kind(k), Cnt(cnt) {}
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000943
944public:
Ted Kremenekdb863712008-04-16 22:32:20 +0000945
Ted Kremenek4fd88972008-04-17 18:12:53 +0000946 Kind getKind() const { return kind; }
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000947
Ted Kremenek553cf182008-06-25 21:21:56 +0000948 unsigned getCount() const { return Cnt; }
949 QualType getType() const { return T; }
Ted Kremenek4fd88972008-04-17 18:12:53 +0000950
951 // Useful predicates.
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000952
Ted Kremenek73c750b2008-03-11 18:14:09 +0000953 static bool isError(Kind k) { return k >= ErrorUseAfterRelease; }
954
Ted Kremenekdb863712008-04-16 22:32:20 +0000955 static bool isLeak(Kind k) { return k == ErrorLeak; }
956
Ted Kremeneke7bd9c22008-04-11 22:25:11 +0000957 bool isOwned() const {
958 return getKind() == Owned;
959 }
960
Ted Kremenekdb863712008-04-16 22:32:20 +0000961 bool isNotOwned() const {
962 return getKind() == NotOwned;
963 }
964
Ted Kremenek4fd88972008-04-17 18:12:53 +0000965 bool isReturnedOwned() const {
966 return getKind() == ReturnedOwned;
967 }
968
969 bool isReturnedNotOwned() const {
970 return getKind() == ReturnedNotOwned;
971 }
972
973 bool isNonLeakError() const {
974 Kind k = getKind();
975 return isError(k) && !isLeak(k);
976 }
977
978 // State creation: normal state.
979
Ted Kremenek553cf182008-06-25 21:21:56 +0000980 static RefVal makeOwned(QualType t, unsigned Count = 1) {
981 return RefVal(Owned, Count, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +0000982 }
983
Ted Kremenek553cf182008-06-25 21:21:56 +0000984 static RefVal makeNotOwned(QualType t, unsigned Count = 0) {
985 return RefVal(NotOwned, Count, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +0000986 }
Ted Kremenek4fd88972008-04-17 18:12:53 +0000987
988 static RefVal makeReturnedOwned(unsigned Count) {
989 return RefVal(ReturnedOwned, Count);
990 }
991
992 static RefVal makeReturnedNotOwned() {
993 return RefVal(ReturnedNotOwned);
994 }
995
996 // State creation: errors.
Ted Kremenek553cf182008-06-25 21:21:56 +0000997
998#if 0
Ted Kremenekce48e002008-05-05 17:53:17 +0000999 static RefVal makeLeak(unsigned Count) { return RefVal(ErrorLeak, Count); }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001000 static RefVal makeReleased() { return RefVal(Released); }
1001 static RefVal makeUseAfterRelease() { return RefVal(ErrorUseAfterRelease); }
1002 static RefVal makeReleaseNotOwned() { return RefVal(ErrorReleaseNotOwned); }
Ted Kremenek553cf182008-06-25 21:21:56 +00001003#endif
1004
Ted Kremenek4fd88972008-04-17 18:12:53 +00001005 // Comparison, profiling, and pretty-printing.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001006
Ted Kremenek4fd88972008-04-17 18:12:53 +00001007 bool operator==(const RefVal& X) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001008 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001009 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001010
Ted Kremenek553cf182008-06-25 21:21:56 +00001011 RefVal operator-(size_t i) const {
1012 return RefVal(getKind(), getCount() - i, getType());
1013 }
1014
1015 RefVal operator+(size_t i) const {
1016 return RefVal(getKind(), getCount() + i, getType());
1017 }
1018
1019 RefVal operator^(Kind k) const {
1020 return RefVal(k, getCount(), getType());
1021 }
1022
1023
Ted Kremenek4fd88972008-04-17 18:12:53 +00001024 void Profile(llvm::FoldingSetNodeID& ID) const {
1025 ID.AddInteger((unsigned) kind);
1026 ID.AddInteger(Cnt);
Ted Kremenek553cf182008-06-25 21:21:56 +00001027 ID.Add(T);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001028 }
1029
Ted Kremenekf3948042008-03-11 19:44:10 +00001030 void print(std::ostream& Out) const;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001031};
Ted Kremenekf3948042008-03-11 19:44:10 +00001032
1033void RefVal::print(std::ostream& Out) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001034 if (!T.isNull())
1035 Out << "Tracked Type:" << T.getAsString() << '\n';
1036
Ted Kremenekf3948042008-03-11 19:44:10 +00001037 switch (getKind()) {
1038 default: assert(false);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001039 case Owned: {
1040 Out << "Owned";
1041 unsigned cnt = getCount();
1042 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001043 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001044 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001045
Ted Kremenek61b9f872008-04-10 23:09:18 +00001046 case NotOwned: {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001047 Out << "NotOwned";
Ted Kremenek61b9f872008-04-10 23:09:18 +00001048 unsigned cnt = getCount();
1049 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001050 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001051 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001052
Ted Kremenek4fd88972008-04-17 18:12:53 +00001053 case ReturnedOwned: {
1054 Out << "ReturnedOwned";
1055 unsigned cnt = getCount();
1056 if (cnt) Out << " (+ " << cnt << ")";
1057 break;
1058 }
1059
1060 case ReturnedNotOwned: {
1061 Out << "ReturnedNotOwned";
1062 unsigned cnt = getCount();
1063 if (cnt) Out << " (+ " << cnt << ")";
1064 break;
1065 }
1066
Ted Kremenekf3948042008-03-11 19:44:10 +00001067 case Released:
1068 Out << "Released";
1069 break;
1070
Ted Kremenekdb863712008-04-16 22:32:20 +00001071 case ErrorLeak:
1072 Out << "Leaked";
1073 break;
1074
Ted Kremenekf3948042008-03-11 19:44:10 +00001075 case ErrorUseAfterRelease:
1076 Out << "Use-After-Release [ERROR]";
1077 break;
1078
1079 case ErrorReleaseNotOwned:
1080 Out << "Release of Not-Owned [ERROR]";
1081 break;
1082 }
1083}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001084
Ted Kremenek13922612008-04-16 20:40:59 +00001085//===----------------------------------------------------------------------===//
1086// Transfer functions.
1087//===----------------------------------------------------------------------===//
1088
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001089class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek8dd56462008-04-18 03:39:05 +00001090public:
Ted Kremenek553cf182008-06-25 21:21:56 +00001091 // Type definitions.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001092 typedef llvm::ImmutableMap<SymbolID, RefVal> RefBindings;
Ted Kremenek553cf182008-06-25 21:21:56 +00001093
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001094 typedef RefBindings::Factory RefBFactoryTy;
Ted Kremenek73c750b2008-03-11 18:14:09 +00001095
Ted Kremenek8dd56462008-04-18 03:39:05 +00001096 typedef llvm::DenseMap<GRExprEngine::NodeTy*,std::pair<Expr*, SymbolID> >
1097 ReleasesNotOwnedTy;
1098
1099 typedef ReleasesNotOwnedTy UseAfterReleasesTy;
1100
1101 typedef llvm::DenseMap<GRExprEngine::NodeTy*, std::vector<SymbolID>*>
Ted Kremenekdb863712008-04-16 22:32:20 +00001102 LeaksTy;
Ted Kremenek8dd56462008-04-18 03:39:05 +00001103
Ted Kremenekf3948042008-03-11 19:44:10 +00001104 class BindingsPrinter : public ValueState::CheckerStatePrinter {
1105 public:
1106 virtual void PrintCheckerState(std::ostream& Out, void* State,
1107 const char* nl, const char* sep);
1108 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00001109
1110private:
Ted Kremenekf3948042008-03-11 19:44:10 +00001111 // Instance variables.
1112
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001113 RetainSummaryManager Summaries;
1114 const bool EmitStandardWarnings;
1115 const LangOptions& LOpts;
1116 RefBFactoryTy RefBFactory;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001117
Ted Kremenek73c750b2008-03-11 18:14:09 +00001118 UseAfterReleasesTy UseAfterReleases;
1119 ReleasesNotOwnedTy ReleasesNotOwned;
Ted Kremenekdb863712008-04-16 22:32:20 +00001120 LeaksTy Leaks;
Ted Kremenek73c750b2008-03-11 18:14:09 +00001121
Ted Kremenekf3948042008-03-11 19:44:10 +00001122 BindingsPrinter Printer;
1123
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001124 Selector RetainSelector;
1125 Selector ReleaseSelector;
Ted Kremenek5934cee2008-05-01 02:18:37 +00001126 Selector AutoreleaseSelector;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001127
Ted Kremenek8dd56462008-04-18 03:39:05 +00001128public:
1129
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001130 static RefBindings GetRefBindings(ValueState& StImpl) {
1131 return RefBindings((RefBindings::TreeTy*) StImpl.CheckerState);
1132 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001133
Ted Kremenek8dd56462008-04-18 03:39:05 +00001134private:
1135
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001136 static void SetRefBindings(ValueState& StImpl, RefBindings B) {
1137 StImpl.CheckerState = B.getRoot();
1138 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001139
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001140 RefBindings Remove(RefBindings B, SymbolID sym) {
1141 return RefBFactory.Remove(B, sym);
1142 }
1143
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001144 RefBindings Update(RefBindings B, SymbolID sym, RefVal V, ArgEffect E,
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001145 RefVal::Kind& hasErr);
1146
Ted Kremenekdb863712008-04-16 22:32:20 +00001147 void ProcessNonLeakError(ExplodedNodeSet<ValueState>& Dst,
1148 GRStmtNodeBuilder<ValueState>& Builder,
1149 Expr* NodeExpr, Expr* ErrorExpr,
1150 ExplodedNode<ValueState>* Pred,
1151 ValueState* St,
Ted Kremenek8dd56462008-04-18 03:39:05 +00001152 RefVal::Kind hasErr, SymbolID Sym);
Ted Kremenekdb863712008-04-16 22:32:20 +00001153
1154 ValueState* HandleSymbolDeath(ValueStateManager& VMgr, ValueState* St,
1155 SymbolID sid, RefVal V, bool& hasLeak);
1156
1157 ValueState* NukeBinding(ValueStateManager& VMgr, ValueState* St,
1158 SymbolID sid);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001159
1160public:
Ted Kremenek13922612008-04-16 20:40:59 +00001161
Ted Kremenek9f741612008-05-02 18:01:49 +00001162 CFRefCount(ASTContext& Ctx, bool gcenabled, bool StandardWarnings,
1163 const LangOptions& lopts)
Ted Kremenek377e2302008-04-29 05:33:51 +00001164 : Summaries(Ctx, gcenabled),
Ted Kremenek9f741612008-05-02 18:01:49 +00001165 EmitStandardWarnings(StandardWarnings),
Ted Kremenek072192b2008-04-30 23:47:44 +00001166 LOpts(lopts),
Ted Kremenekb83e02e2008-05-01 18:31:44 +00001167 RetainSelector(GetNullarySelector("retain", Ctx)),
1168 ReleaseSelector(GetNullarySelector("release", Ctx)),
1169 AutoreleaseSelector(GetNullarySelector("autorelease", Ctx)) {}
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001170
Ted Kremenek8dd56462008-04-18 03:39:05 +00001171 virtual ~CFRefCount() {
1172 for (LeaksTy::iterator I = Leaks.begin(), E = Leaks.end(); I!=E; ++I)
1173 delete I->second;
1174 }
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001175
1176 virtual void RegisterChecks(GRExprEngine& Eng);
Ted Kremenekf3948042008-03-11 19:44:10 +00001177
1178 virtual ValueState::CheckerStatePrinter* getCheckerStatePrinter() {
1179 return &Printer;
1180 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001181
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001182 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenek072192b2008-04-30 23:47:44 +00001183 const LangOptions& getLangOptions() const { return LOpts; }
1184
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001185 // Calls.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001186
1187 void EvalSummary(ExplodedNodeSet<ValueState>& Dst,
1188 GRExprEngine& Eng,
1189 GRStmtNodeBuilder<ValueState>& Builder,
1190 Expr* Ex,
1191 Expr* Receiver,
1192 RetainSummary* Summ,
Ted Kremenek55499762008-06-17 02:43:46 +00001193 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001194 ExplodedNode<ValueState>* Pred);
1195
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001196 virtual void EvalCall(ExplodedNodeSet<ValueState>& Dst,
Ted Kremenek199e1a02008-03-12 21:06:49 +00001197 GRExprEngine& Eng,
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001198 GRStmtNodeBuilder<ValueState>& Builder,
Ted Kremenek186350f2008-04-23 20:12:28 +00001199 CallExpr* CE, RVal L,
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001200 ExplodedNode<ValueState>* Pred);
Ted Kremenekfa34b332008-04-09 01:10:13 +00001201
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001202
Ted Kremenek85348202008-04-15 23:44:31 +00001203 virtual void EvalObjCMessageExpr(ExplodedNodeSet<ValueState>& Dst,
1204 GRExprEngine& Engine,
1205 GRStmtNodeBuilder<ValueState>& Builder,
1206 ObjCMessageExpr* ME,
1207 ExplodedNode<ValueState>* Pred);
1208
1209 bool EvalObjCMessageExprAux(ExplodedNodeSet<ValueState>& Dst,
1210 GRExprEngine& Engine,
1211 GRStmtNodeBuilder<ValueState>& Builder,
1212 ObjCMessageExpr* ME,
1213 ExplodedNode<ValueState>* Pred);
1214
Ted Kremenek13922612008-04-16 20:40:59 +00001215 // Stores.
1216
1217 virtual void EvalStore(ExplodedNodeSet<ValueState>& Dst,
1218 GRExprEngine& Engine,
1219 GRStmtNodeBuilder<ValueState>& Builder,
1220 Expr* E, ExplodedNode<ValueState>* Pred,
1221 ValueState* St, RVal TargetLV, RVal Val);
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001222 // End-of-path.
1223
1224 virtual void EvalEndPath(GRExprEngine& Engine,
1225 GREndPathNodeBuilder<ValueState>& Builder);
1226
Ted Kremenek652adc62008-04-24 23:57:27 +00001227 virtual void EvalDeadSymbols(ExplodedNodeSet<ValueState>& Dst,
1228 GRExprEngine& Engine,
1229 GRStmtNodeBuilder<ValueState>& Builder,
Ted Kremenek910e9992008-04-25 01:25:15 +00001230 ExplodedNode<ValueState>* Pred,
1231 Stmt* S,
Ted Kremenek652adc62008-04-24 23:57:27 +00001232 ValueState* St,
1233 const ValueStateManager::DeadSymbolsTy& Dead);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001234 // Return statements.
1235
1236 virtual void EvalReturn(ExplodedNodeSet<ValueState>& Dst,
1237 GRExprEngine& Engine,
1238 GRStmtNodeBuilder<ValueState>& Builder,
1239 ReturnStmt* S,
1240 ExplodedNode<ValueState>* Pred);
Ted Kremenekcb612922008-04-18 19:23:43 +00001241
1242 // Assumptions.
1243
1244 virtual ValueState* EvalAssume(GRExprEngine& Engine, ValueState* St,
1245 RVal Cond, bool Assumption, bool& isFeasible);
1246
Ted Kremenekfa34b332008-04-09 01:10:13 +00001247 // Error iterators.
1248
1249 typedef UseAfterReleasesTy::iterator use_after_iterator;
1250 typedef ReleasesNotOwnedTy::iterator bad_release_iterator;
Ted Kremenek989d5192008-04-17 23:43:50 +00001251 typedef LeaksTy::iterator leaks_iterator;
Ted Kremenekfa34b332008-04-09 01:10:13 +00001252
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001253 use_after_iterator use_after_begin() { return UseAfterReleases.begin(); }
1254 use_after_iterator use_after_end() { return UseAfterReleases.end(); }
Ted Kremenekfa34b332008-04-09 01:10:13 +00001255
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001256 bad_release_iterator bad_release_begin() { return ReleasesNotOwned.begin(); }
1257 bad_release_iterator bad_release_end() { return ReleasesNotOwned.end(); }
Ted Kremenek989d5192008-04-17 23:43:50 +00001258
1259 leaks_iterator leaks_begin() { return Leaks.begin(); }
1260 leaks_iterator leaks_end() { return Leaks.end(); }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001261};
1262
1263} // end anonymous namespace
1264
Ted Kremenek8dd56462008-04-18 03:39:05 +00001265
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001266
1267
Ted Kremenekf3948042008-03-11 19:44:10 +00001268void CFRefCount::BindingsPrinter::PrintCheckerState(std::ostream& Out,
1269 void* State, const char* nl,
1270 const char* sep) {
1271 RefBindings B((RefBindings::TreeTy*) State);
1272
1273 if (State)
1274 Out << sep << nl;
1275
1276 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1277 Out << (*I).first << " : ";
1278 (*I).second.print(Out);
1279 Out << nl;
1280 }
1281}
1282
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001283static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001284 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenekf9561e52008-04-11 20:23:24 +00001285}
1286
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001287static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1288 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenekf9561e52008-04-11 20:23:24 +00001289}
1290
Ted Kremenek14993892008-05-06 02:41:27 +00001291static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1292 return Summ ? Summ->getReceiverEffect() : DoNothing;
1293}
1294
Ted Kremenekdb863712008-04-16 22:32:20 +00001295void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<ValueState>& Dst,
1296 GRStmtNodeBuilder<ValueState>& Builder,
1297 Expr* NodeExpr, Expr* ErrorExpr,
1298 ExplodedNode<ValueState>* Pred,
1299 ValueState* St,
Ted Kremenek8dd56462008-04-18 03:39:05 +00001300 RefVal::Kind hasErr, SymbolID Sym) {
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001301 Builder.BuildSinks = true;
1302 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
1303
1304 if (!N) return;
1305
1306 switch (hasErr) {
1307 default: assert(false);
1308 case RefVal::ErrorUseAfterRelease:
Ted Kremenek8dd56462008-04-18 03:39:05 +00001309 UseAfterReleases[N] = std::make_pair(ErrorExpr, Sym);
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001310 break;
1311
1312 case RefVal::ErrorReleaseNotOwned:
Ted Kremenek8dd56462008-04-18 03:39:05 +00001313 ReleasesNotOwned[N] = std::make_pair(ErrorExpr, Sym);
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001314 break;
1315 }
1316}
1317
Ted Kremenek553cf182008-06-25 21:21:56 +00001318/// GetReturnType - Used to get the return type of a message expression or
1319/// function call with the intention of affixing that type to a tracked symbol.
1320/// While the the return type can be queried directly from RetEx, when
1321/// invoking class methods we augment to the return type to be that of
1322/// a pointer to the class (as opposed it just being id).
1323static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1324
1325 QualType RetTy = RetE->getType();
1326
1327 // FIXME: We aren't handling id<...>.
1328 const PointerType* PT = RetTy.getCanonicalType()->getAsPointerType();
1329
1330 if (!PT)
1331 return RetTy;
1332
1333 // If RetEx is not a message expression just return its type.
1334 // If RetEx is a message expression, return its types if it is something
1335 /// more specific than id.
1336
1337 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1338
1339 if (!ME || !Ctx.isObjCIdType(PT->getPointeeType()))
1340 return RetTy;
1341
1342 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1343
1344 // At this point we know the return type of the message expression is id.
1345 // If we have an ObjCInterceDecl, we know this is a call to a class method
1346 // whose type we can resolve. In such cases, promote the return type to
1347 // Class*.
1348 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1349}
1350
1351
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001352void CFRefCount::EvalSummary(ExplodedNodeSet<ValueState>& Dst,
1353 GRExprEngine& Eng,
1354 GRStmtNodeBuilder<ValueState>& Builder,
1355 Expr* Ex,
1356 Expr* Receiver,
1357 RetainSummary* Summ,
Ted Kremenek55499762008-06-17 02:43:46 +00001358 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001359 ExplodedNode<ValueState>* Pred) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001360
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001361 // Get the state.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001362 ValueStateManager& StateMgr = Eng.getStateManager();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001363 ValueState* St = Builder.GetState(Pred);
Ted Kremenek14993892008-05-06 02:41:27 +00001364
1365 // Evaluate the effect of the arguments.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001366 ValueState StVals = *St;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001367 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001368 unsigned idx = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001369 Expr* ErrorExpr = NULL;
Ted Kremenek8dd56462008-04-18 03:39:05 +00001370 SymbolID ErrorSym = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001371
Ted Kremenek55499762008-06-17 02:43:46 +00001372 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001373
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001374 RVal V = StateMgr.GetRVal(St, *I);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001375
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001376 if (isa<lval::SymbolVal>(V)) {
1377 SymbolID Sym = cast<lval::SymbolVal>(V).getSymbol();
Ted Kremenekf9561e52008-04-11 20:23:24 +00001378 RefBindings B = GetRefBindings(StVals);
1379
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001380 if (RefBindings::TreeTy* T = B.SlimFind(Sym)) {
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001381 B = Update(B, Sym, T->getValue().second, GetArgE(Summ, idx), hasErr);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001382 SetRefBindings(StVals, B);
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001383
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001384 if (hasErr) {
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001385 ErrorExpr = *I;
Ted Kremenek8dd56462008-04-18 03:39:05 +00001386 ErrorSym = T->getValue().first;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001387 break;
1388 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001389 }
Ted Kremenekb8873552008-04-11 20:51:02 +00001390 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001391 else if (isa<LVal>(V)) {
1392 // Nuke all arguments passed by reference.
Ted Kremenekf9561e52008-04-11 20:23:24 +00001393 StateMgr.Unbind(StVals, cast<LVal>(V));
Ted Kremenekb8873552008-04-11 20:51:02 +00001394 }
Ted Kremeneka5488462008-04-22 21:39:21 +00001395 else if (isa<nonlval::LValAsInteger>(V))
1396 StateMgr.Unbind(StVals, cast<nonlval::LValAsInteger>(V).getLVal());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001397 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001398
Ted Kremenek553cf182008-06-25 21:21:56 +00001399 // Evaluate the effect on the message receiver.
Ted Kremenek14993892008-05-06 02:41:27 +00001400 if (!ErrorExpr && Receiver) {
1401 RVal V = StateMgr.GetRVal(St, Receiver);
1402
1403 if (isa<lval::SymbolVal>(V)) {
1404 SymbolID Sym = cast<lval::SymbolVal>(V).getSymbol();
1405 RefBindings B = GetRefBindings(StVals);
1406
1407 if (RefBindings::TreeTy* T = B.SlimFind(Sym)) {
1408 B = Update(B, Sym, T->getValue().second, GetReceiverE(Summ), hasErr);
1409 SetRefBindings(StVals, B);
1410
1411 if (hasErr) {
1412 ErrorExpr = Receiver;
1413 ErrorSym = T->getValue().first;
1414 }
1415 }
1416 }
1417 }
1418
Ted Kremenek553cf182008-06-25 21:21:56 +00001419 // Get the persistent state.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001420 St = StateMgr.getPersistentState(StVals);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001421
Ted Kremenek553cf182008-06-25 21:21:56 +00001422 // Process any errors.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001423 if (hasErr) {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001424 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, St,
Ted Kremenek8dd56462008-04-18 03:39:05 +00001425 hasErr, ErrorSym);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001426 return;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001427 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001428
Ted Kremenek553cf182008-06-25 21:21:56 +00001429 // Finally, consult the summary for the return value.
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001430 RetEffect RE = GetRetEffect(Summ);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001431
1432 switch (RE.getKind()) {
1433 default:
1434 assert (false && "Unhandled RetEffect."); break;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001435
Ted Kremenek940b1d82008-04-10 23:44:06 +00001436 case RetEffect::NoRet:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001437
Ted Kremenekf9561e52008-04-11 20:23:24 +00001438 // Make up a symbol for the return value (not reference counted).
Ted Kremenekb8873552008-04-11 20:51:02 +00001439 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
1440 // should compose behavior, not copy it.
Ted Kremenekf9561e52008-04-11 20:23:24 +00001441
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001442 if (Ex->getType() != Eng.getContext().VoidTy) {
Ted Kremenekf9561e52008-04-11 20:23:24 +00001443 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001444 SymbolID Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenekf9561e52008-04-11 20:23:24 +00001445
Ted Kremenek0e470a52008-05-09 23:45:33 +00001446 RVal X = LVal::IsLValType(Ex->getType())
1447 ? cast<RVal>(lval::SymbolVal(Sym))
1448 : cast<RVal>(nonlval::SymbolVal(Sym));
Ted Kremenekf9561e52008-04-11 20:23:24 +00001449
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001450 St = StateMgr.SetRVal(St, Ex, X, Eng.getCFG().isBlkExpr(Ex), false);
Ted Kremenekf9561e52008-04-11 20:23:24 +00001451 }
1452
Ted Kremenek940b1d82008-04-10 23:44:06 +00001453 break;
1454
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001455 case RetEffect::Alias: {
Ted Kremenek553cf182008-06-25 21:21:56 +00001456 unsigned idx = RE.getIndex();
Ted Kremenek55499762008-06-17 02:43:46 +00001457 assert (arg_end >= arg_beg);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001458 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenek55499762008-06-17 02:43:46 +00001459 RVal V = StateMgr.GetRVal(St, *(arg_beg+idx));
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001460 St = StateMgr.SetRVal(St, Ex, V, Eng.getCFG().isBlkExpr(Ex), false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001461 break;
1462 }
1463
Ted Kremenek14993892008-05-06 02:41:27 +00001464 case RetEffect::ReceiverAlias: {
1465 assert (Receiver);
1466 RVal V = StateMgr.GetRVal(St, Receiver);
1467 St = StateMgr.SetRVal(St, Ex, V, Eng.getCFG().isBlkExpr(Ex), false);
1468 break;
1469 }
1470
Ted Kremeneka7344702008-06-23 18:02:52 +00001471 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001472 case RetEffect::OwnedSymbol: {
1473 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001474 SymbolID Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek553cf182008-06-25 21:21:56 +00001475 QualType RetT = GetReturnType(Ex, Eng.getContext());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001476
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001477 ValueState StImpl = *St;
1478 RefBindings B = GetRefBindings(StImpl);
Ted Kremenek553cf182008-06-25 21:21:56 +00001479 SetRefBindings(StImpl, RefBFactory.Add(B, Sym, RefVal::makeOwned(RetT)));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001480
1481 St = StateMgr.SetRVal(StateMgr.getPersistentState(StImpl),
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001482 Ex, lval::SymbolVal(Sym),
1483 Eng.getCFG().isBlkExpr(Ex), false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001484
Ted Kremeneka7344702008-06-23 18:02:52 +00001485 // FIXME: Add a flag to the checker where allocations are allowed to fail.
1486 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol)
1487 St = StateMgr.AddNE(St, Sym, Eng.getBasicVals().getZeroWithPtrWidth());
1488
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001489 break;
1490 }
1491
1492 case RetEffect::NotOwnedSymbol: {
1493 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001494 SymbolID Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek553cf182008-06-25 21:21:56 +00001495 QualType RetT = GetReturnType(Ex, Eng.getContext());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001496
1497 ValueState StImpl = *St;
1498 RefBindings B = GetRefBindings(StImpl);
Ted Kremenek553cf182008-06-25 21:21:56 +00001499 SetRefBindings(StImpl, RefBFactory.Add(B, Sym,
1500 RefVal::makeNotOwned(RetT)));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001501
1502 St = StateMgr.SetRVal(StateMgr.getPersistentState(StImpl),
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001503 Ex, lval::SymbolVal(Sym),
1504 Eng.getCFG().isBlkExpr(Ex), false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001505
1506 break;
1507 }
1508 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001509
1510 Builder.MakeNode(Dst, Ex, Pred, St);
1511}
1512
1513
1514void CFRefCount::EvalCall(ExplodedNodeSet<ValueState>& Dst,
1515 GRExprEngine& Eng,
1516 GRStmtNodeBuilder<ValueState>& Builder,
1517 CallExpr* CE, RVal L,
1518 ExplodedNode<ValueState>* Pred) {
1519
1520
1521 RetainSummary* Summ = NULL;
1522
1523 // Get the summary.
1524
1525 if (isa<lval::FuncVal>(L)) {
1526 lval::FuncVal FV = cast<lval::FuncVal>(L);
1527 FunctionDecl* FD = FV.getDecl();
Ted Kremenekab592272008-06-24 03:56:45 +00001528 Summ = Summaries.getSummary(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001529 }
1530
1531 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
1532 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001533}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001534
Ted Kremenek85348202008-04-15 23:44:31 +00001535
1536void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<ValueState>& Dst,
1537 GRExprEngine& Eng,
1538 GRStmtNodeBuilder<ValueState>& Builder,
1539 ObjCMessageExpr* ME,
1540 ExplodedNode<ValueState>* Pred) {
1541
Ted Kremenekb3095252008-05-06 04:20:12 +00001542 RetainSummary* Summ;
Ted Kremenek9040c652008-05-01 21:31:50 +00001543
Ted Kremenek553cf182008-06-25 21:21:56 +00001544 if (Expr* Receiver = ME->getReceiver()) {
1545 // We need the type-information of the tracked receiver object
1546 // Retrieve it from the state.
1547 ObjCInterfaceDecl* ID = 0;
1548
1549 // FIXME: Wouldn't it be great if this code could be reduced? It's just
1550 // a chain of lookups.
1551 ValueState* St = Builder.GetState(Pred);
1552 RVal V = Eng.getStateManager().GetRVal(St, Receiver );
1553
1554 if (isa<lval::SymbolVal>(V)) {
1555 SymbolID Sym = cast<lval::SymbolVal>(V).getSymbol();
1556
1557 if (RefBindings::TreeTy* T = GetRefBindings(*St).SlimFind(Sym)) {
1558 QualType Ty = T->getValue().second.getType();
1559
1560 if (const PointerType* PT = Ty->getAsPointerType()) {
1561 QualType PointeeTy = PT->getPointeeType();
1562
1563 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
1564 ID = IT->getDecl();
1565 }
1566 }
1567 }
1568
1569 Summ = Summaries.getMethodSummary(ME, ID);
1570 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001571 else
Ted Kremenek1f180c32008-06-23 22:21:20 +00001572 Summ = Summaries.getClassMethodSummary(ME->getClassName(),
1573 ME->getSelector());
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001574
Ted Kremenekb3095252008-05-06 04:20:12 +00001575 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
1576 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001577}
Ted Kremenekb3095252008-05-06 04:20:12 +00001578
Ted Kremenek13922612008-04-16 20:40:59 +00001579// Stores.
1580
1581void CFRefCount::EvalStore(ExplodedNodeSet<ValueState>& Dst,
1582 GRExprEngine& Eng,
1583 GRStmtNodeBuilder<ValueState>& Builder,
1584 Expr* E, ExplodedNode<ValueState>* Pred,
1585 ValueState* St, RVal TargetLV, RVal Val) {
1586
1587 // Check if we have a binding for "Val" and if we are storing it to something
1588 // we don't understand or otherwise the value "escapes" the function.
1589
1590 if (!isa<lval::SymbolVal>(Val))
1591 return;
1592
1593 // Are we storing to something that causes the value to "escape"?
1594
1595 bool escapes = false;
1596
1597 if (!isa<lval::DeclVal>(TargetLV))
1598 escapes = true;
1599 else
1600 escapes = cast<lval::DeclVal>(TargetLV).getDecl()->hasGlobalStorage();
1601
1602 if (!escapes)
1603 return;
1604
1605 SymbolID Sym = cast<lval::SymbolVal>(Val).getSymbol();
1606 RefBindings B = GetRefBindings(*St);
1607 RefBindings::TreeTy* T = B.SlimFind(Sym);
1608
1609 if (!T)
1610 return;
1611
Ted Kremenekdb863712008-04-16 22:32:20 +00001612 // Nuke the binding.
1613 St = NukeBinding(Eng.getStateManager(), St, Sym);
Ted Kremenek13922612008-04-16 20:40:59 +00001614
1615 // Hand of the remaining logic to the parent implementation.
1616 GRSimpleVals::EvalStore(Dst, Eng, Builder, E, Pred, St, TargetLV, Val);
1617}
1618
Ted Kremenekdb863712008-04-16 22:32:20 +00001619
1620ValueState* CFRefCount::NukeBinding(ValueStateManager& VMgr, ValueState* St,
1621 SymbolID sid) {
1622 ValueState StImpl = *St;
1623 RefBindings B = GetRefBindings(StImpl);
1624 StImpl.CheckerState = RefBFactory.Remove(B, sid).getRoot();
1625 return VMgr.getPersistentState(StImpl);
1626}
1627
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001628// End-of-path.
1629
Ted Kremenekdb863712008-04-16 22:32:20 +00001630ValueState* CFRefCount::HandleSymbolDeath(ValueStateManager& VMgr,
1631 ValueState* St, SymbolID sid,
1632 RefVal V, bool& hasLeak) {
1633
Ted Kremenek4fd88972008-04-17 18:12:53 +00001634 hasLeak = V.isOwned() ||
1635 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenekdb863712008-04-16 22:32:20 +00001636
1637 if (!hasLeak)
1638 return NukeBinding(VMgr, St, sid);
1639
1640 RefBindings B = GetRefBindings(*St);
Ted Kremenek553cf182008-06-25 21:21:56 +00001641 ValueState StImpl = *St;
1642 StImpl.CheckerState = RefBFactory.Add(B, sid, V^RefVal::ErrorLeak).getRoot();
Ted Kremenekce48e002008-05-05 17:53:17 +00001643
Ted Kremenekdb863712008-04-16 22:32:20 +00001644 return VMgr.getPersistentState(StImpl);
1645}
1646
1647void CFRefCount::EvalEndPath(GRExprEngine& Eng,
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001648 GREndPathNodeBuilder<ValueState>& Builder) {
1649
Ted Kremenekdb863712008-04-16 22:32:20 +00001650 ValueState* St = Builder.getState();
1651 RefBindings B = GetRefBindings(*St);
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001652
Ted Kremenekdb863712008-04-16 22:32:20 +00001653 llvm::SmallVector<SymbolID, 10> Leaked;
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001654
Ted Kremenekdb863712008-04-16 22:32:20 +00001655 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
1656 bool hasLeak = false;
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001657
Ted Kremenekdb863712008-04-16 22:32:20 +00001658 St = HandleSymbolDeath(Eng.getStateManager(), St,
1659 (*I).first, (*I).second, hasLeak);
1660
1661 if (hasLeak) Leaked.push_back((*I).first);
1662 }
Ted Kremenek652adc62008-04-24 23:57:27 +00001663
1664 if (Leaked.empty())
1665 return;
1666
Ted Kremenek8dd56462008-04-18 03:39:05 +00001667 ExplodedNode<ValueState>* N = Builder.MakeNode(St);
Ted Kremenek4f285152008-04-18 16:30:14 +00001668
Ted Kremenek652adc62008-04-24 23:57:27 +00001669 if (!N)
Ted Kremenek4f285152008-04-18 16:30:14 +00001670 return;
Ted Kremenekcb612922008-04-18 19:23:43 +00001671
Ted Kremenek8dd56462008-04-18 03:39:05 +00001672 std::vector<SymbolID>*& LeaksAtNode = Leaks[N];
1673 assert (!LeaksAtNode);
1674 LeaksAtNode = new std::vector<SymbolID>();
Ted Kremenekdb863712008-04-16 22:32:20 +00001675
1676 for (llvm::SmallVector<SymbolID, 10>::iterator I=Leaked.begin(),
1677 E = Leaked.end(); I != E; ++I)
Ted Kremenek8dd56462008-04-18 03:39:05 +00001678 (*LeaksAtNode).push_back(*I);
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001679}
1680
Ted Kremenek652adc62008-04-24 23:57:27 +00001681// Dead symbols.
1682
1683void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<ValueState>& Dst,
1684 GRExprEngine& Eng,
1685 GRStmtNodeBuilder<ValueState>& Builder,
Ted Kremenek910e9992008-04-25 01:25:15 +00001686 ExplodedNode<ValueState>* Pred,
1687 Stmt* S,
Ted Kremenek652adc62008-04-24 23:57:27 +00001688 ValueState* St,
1689 const ValueStateManager::DeadSymbolsTy& Dead) {
Ted Kremenek910e9992008-04-25 01:25:15 +00001690
Ted Kremenek652adc62008-04-24 23:57:27 +00001691 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
1692
1693 RefBindings B = GetRefBindings(*St);
1694 llvm::SmallVector<SymbolID, 10> Leaked;
1695
1696 for (ValueStateManager::DeadSymbolsTy::const_iterator
1697 I=Dead.begin(), E=Dead.end(); I!=E; ++I) {
1698
1699 RefBindings::TreeTy* T = B.SlimFind(*I);
1700
1701 if (!T)
1702 continue;
1703
1704 bool hasLeak = false;
1705
1706 St = HandleSymbolDeath(Eng.getStateManager(), St,
1707 *I, T->getValue().second, hasLeak);
1708
1709 if (hasLeak) Leaked.push_back(*I);
1710 }
1711
1712 if (Leaked.empty())
1713 return;
1714
1715 ExplodedNode<ValueState>* N = Builder.MakeNode(Dst, S, Pred, St);
1716
1717 if (!N)
1718 return;
1719
1720 std::vector<SymbolID>*& LeaksAtNode = Leaks[N];
1721 assert (!LeaksAtNode);
1722 LeaksAtNode = new std::vector<SymbolID>();
1723
1724 for (llvm::SmallVector<SymbolID, 10>::iterator I=Leaked.begin(),
1725 E = Leaked.end(); I != E; ++I)
1726 (*LeaksAtNode).push_back(*I);
1727}
1728
Ted Kremenek4fd88972008-04-17 18:12:53 +00001729 // Return statements.
1730
1731void CFRefCount::EvalReturn(ExplodedNodeSet<ValueState>& Dst,
1732 GRExprEngine& Eng,
1733 GRStmtNodeBuilder<ValueState>& Builder,
1734 ReturnStmt* S,
1735 ExplodedNode<ValueState>* Pred) {
1736
1737 Expr* RetE = S->getRetValue();
1738 if (!RetE) return;
1739
1740 ValueStateManager& StateMgr = Eng.getStateManager();
1741 ValueState* St = Builder.GetState(Pred);
1742 RVal V = StateMgr.GetRVal(St, RetE);
1743
1744 if (!isa<lval::SymbolVal>(V))
1745 return;
1746
1747 // Get the reference count binding (if any).
1748 SymbolID Sym = cast<lval::SymbolVal>(V).getSymbol();
1749 RefBindings B = GetRefBindings(*St);
1750 RefBindings::TreeTy* T = B.SlimFind(Sym);
1751
1752 if (!T)
1753 return;
1754
1755 // Change the reference count.
1756
1757 RefVal X = T->getValue().second;
1758
1759 switch (X.getKind()) {
1760
1761 case RefVal::Owned: {
1762 unsigned cnt = X.getCount();
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001763 assert (cnt > 0);
1764 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001765 break;
1766 }
1767
1768 case RefVal::NotOwned: {
1769 unsigned cnt = X.getCount();
1770 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
1771 : RefVal::makeReturnedNotOwned();
1772 break;
1773 }
1774
1775 default:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001776 return;
1777 }
1778
1779 // Update the binding.
1780
1781 ValueState StImpl = *St;
1782 StImpl.CheckerState = RefBFactory.Add(B, Sym, X).getRoot();
1783 Builder.MakeNode(Dst, S, Pred, StateMgr.getPersistentState(StImpl));
1784}
1785
Ted Kremenekcb612922008-04-18 19:23:43 +00001786// Assumptions.
1787
1788ValueState* CFRefCount::EvalAssume(GRExprEngine& Eng, ValueState* St,
1789 RVal Cond, bool Assumption,
1790 bool& isFeasible) {
1791
1792 // FIXME: We may add to the interface of EvalAssume the list of symbols
1793 // whose assumptions have changed. For now we just iterate through the
1794 // bindings and check if any of the tracked symbols are NULL. This isn't
1795 // too bad since the number of symbols we will track in practice are
1796 // probably small and EvalAssume is only called at branches and a few
1797 // other places.
1798
1799 RefBindings B = GetRefBindings(*St);
1800
1801 if (B.isEmpty())
1802 return St;
1803
1804 bool changed = false;
1805
1806 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1807
1808 // Check if the symbol is null (or equal to any constant).
1809 // If this is the case, stop tracking the symbol.
1810
1811 if (St->getSymVal(I.getKey())) {
1812 changed = true;
1813 B = RefBFactory.Remove(B, I.getKey());
1814 }
1815 }
1816
1817 if (!changed)
1818 return St;
1819
1820 ValueState StImpl = *St;
1821 StImpl.CheckerState = B.getRoot();
1822 return Eng.getStateManager().getPersistentState(StImpl);
1823}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001824
1825CFRefCount::RefBindings CFRefCount::Update(RefBindings B, SymbolID sym,
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001826 RefVal V, ArgEffect E,
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001827 RefVal::Kind& hasErr) {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001828
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001829 // FIXME: This dispatch can potentially be sped up by unifiying it into
1830 // a single switch statement. Opt for simplicity for now.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001831
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001832 switch (E) {
1833 default:
1834 assert (false && "Unhandled CFRef transition.");
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001835
1836 case MayEscape:
1837 if (V.getKind() == RefVal::Owned) {
Ted Kremenek553cf182008-06-25 21:21:56 +00001838 V = V ^ RefVal::NotOwned;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001839 break;
1840 }
1841
1842 // Fall-through.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001843
1844 case DoNothing:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001845 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
Ted Kremenek553cf182008-06-25 21:21:56 +00001846 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001847 hasErr = V.getKind();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001848 break;
1849 }
1850
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001851 return B;
Ted Kremeneke19f4492008-06-30 16:57:41 +00001852
Ted Kremenek80d753f2008-07-01 00:01:02 +00001853 case Autorelease:
Ted Kremenek14993892008-05-06 02:41:27 +00001854 case StopTracking:
1855 return RefBFactory.Remove(B, sym);
1856
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001857 case IncRef:
1858 switch (V.getKind()) {
1859 default:
1860 assert(false);
1861
1862 case RefVal::Owned:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001863 case RefVal::NotOwned:
Ted Kremenek553cf182008-06-25 21:21:56 +00001864 V = V + 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001865 break;
1866
1867 case RefVal::Released:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001868 if (isGCEnabled())
Ted Kremenek553cf182008-06-25 21:21:56 +00001869 V = V ^ RefVal::Owned;
Ted Kremenek65c91652008-04-29 05:44:10 +00001870 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00001871 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek65c91652008-04-29 05:44:10 +00001872 hasErr = V.getKind();
1873 }
1874
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001875 break;
1876 }
1877
Ted Kremenek940b1d82008-04-10 23:44:06 +00001878 break;
1879
Ted Kremenek553cf182008-06-25 21:21:56 +00001880 case SelfOwn:
1881 V = V ^ RefVal::NotOwned;
1882
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001883 case DecRef:
1884 switch (V.getKind()) {
1885 default:
1886 assert (false);
1887
Ted Kremenek553cf182008-06-25 21:21:56 +00001888 case RefVal::Owned:
1889 V = V.getCount() > 1 ? V - 1 : V ^ RefVal::Released;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001890 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001891
Ted Kremenek553cf182008-06-25 21:21:56 +00001892 case RefVal::NotOwned:
1893 if (V.getCount() > 0)
1894 V = V - 1;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001895 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00001896 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001897 hasErr = V.getKind();
Ted Kremenek61b9f872008-04-10 23:09:18 +00001898 }
1899
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001900 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001901
1902 case RefVal::Released:
Ted Kremenek553cf182008-06-25 21:21:56 +00001903 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001904 hasErr = V.getKind();
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001905 break;
1906 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00001907
1908 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001909 }
1910
1911 return RefBFactory.Add(B, sym, V);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001912}
1913
Ted Kremenekfa34b332008-04-09 01:10:13 +00001914
1915//===----------------------------------------------------------------------===//
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001916// Error reporting.
Ted Kremenekfa34b332008-04-09 01:10:13 +00001917//===----------------------------------------------------------------------===//
1918
Ted Kremenek8dd56462008-04-18 03:39:05 +00001919namespace {
1920
1921 //===-------------===//
1922 // Bug Descriptions. //
1923 //===-------------===//
1924
Ted Kremenek95cc1ba2008-04-18 20:54:29 +00001925 class VISIBILITY_HIDDEN CFRefBug : public BugTypeCacheLocation {
Ted Kremenek8dd56462008-04-18 03:39:05 +00001926 protected:
1927 CFRefCount& TF;
1928
1929 public:
1930 CFRefBug(CFRefCount& tf) : TF(tf) {}
Ted Kremenek072192b2008-04-30 23:47:44 +00001931
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001932 CFRefCount& getTF() { return TF; }
Ted Kremenek789deac2008-05-05 23:16:31 +00001933 const CFRefCount& getTF() const { return TF; }
1934
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00001935 virtual bool isLeak() const { return false; }
Ted Kremenek8dd56462008-04-18 03:39:05 +00001936 };
1937
1938 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1939 public:
1940 UseAfterRelease(CFRefCount& tf) : CFRefBug(tf) {}
1941
1942 virtual const char* getName() const {
Ted Kremenek789deac2008-05-05 23:16:31 +00001943 return "Use-After-Release";
Ted Kremenek8dd56462008-04-18 03:39:05 +00001944 }
1945 virtual const char* getDescription() const {
Ted Kremenek2cf943a2008-04-18 04:55:01 +00001946 return "Reference-counted object is used"
1947 " after it is released.";
Ted Kremenek8dd56462008-04-18 03:39:05 +00001948 }
1949
1950 virtual void EmitWarnings(BugReporter& BR);
Ted Kremenek8dd56462008-04-18 03:39:05 +00001951 };
1952
1953 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1954 public:
1955 BadRelease(CFRefCount& tf) : CFRefBug(tf) {}
1956
1957 virtual const char* getName() const {
Ted Kremenek789deac2008-05-05 23:16:31 +00001958 return "Bad Release";
Ted Kremenek8dd56462008-04-18 03:39:05 +00001959 }
1960 virtual const char* getDescription() const {
1961 return "Incorrect decrement of the reference count of a "
Ted Kremenek2cf943a2008-04-18 04:55:01 +00001962 "CoreFoundation object: "
Ted Kremenek8dd56462008-04-18 03:39:05 +00001963 "The object is not owned at this point by the caller.";
1964 }
1965
1966 virtual void EmitWarnings(BugReporter& BR);
1967 };
1968
1969 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1970 public:
1971 Leak(CFRefCount& tf) : CFRefBug(tf) {}
1972
1973 virtual const char* getName() const {
Ted Kremenek432af592008-05-06 18:11:36 +00001974
1975 if (getTF().isGCEnabled())
1976 return "Memory Leak (GC)";
1977
1978 if (getTF().getLangOptions().getGCMode() == LangOptions::HybridGC)
1979 return "Memory Leak (Hybrid MM, non-GC)";
1980
1981 assert (getTF().getLangOptions().getGCMode() == LangOptions::NonGC);
1982 return "Memory Leak";
Ted Kremenek8dd56462008-04-18 03:39:05 +00001983 }
1984
1985 virtual const char* getDescription() const {
Ted Kremenek2cf943a2008-04-18 04:55:01 +00001986 return "Object leaked.";
Ted Kremenek8dd56462008-04-18 03:39:05 +00001987 }
1988
1989 virtual void EmitWarnings(BugReporter& BR);
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001990 virtual void GetErrorNodes(std::vector<ExplodedNode<ValueState>*>& Nodes);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00001991 virtual bool isLeak() const { return true; }
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00001992 virtual bool isCached(BugReport& R);
Ted Kremenek8dd56462008-04-18 03:39:05 +00001993 };
1994
1995 //===---------===//
1996 // Bug Reports. //
1997 //===---------===//
1998
1999 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
2000 SymbolID Sym;
2001 public:
Ted Kremenek072192b2008-04-30 23:47:44 +00002002 CFRefReport(CFRefBug& D, ExplodedNode<ValueState> *n, SymbolID sym)
Ted Kremenek8dd56462008-04-18 03:39:05 +00002003 : RangedBugReport(D, n), Sym(sym) {}
2004
2005 virtual ~CFRefReport() {}
2006
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002007 CFRefBug& getBugType() {
2008 return (CFRefBug&) RangedBugReport::getBugType();
2009 }
2010 const CFRefBug& getBugType() const {
2011 return (const CFRefBug&) RangedBugReport::getBugType();
2012 }
2013
2014 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2015 const SourceRange*& end) {
2016
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002017 if (!getBugType().isLeak())
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002018 RangedBugReport::getRanges(BR, beg, end);
2019 else {
2020 beg = 0;
2021 end = 0;
2022 }
2023 }
2024
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002025 SymbolID getSymbol() const { return Sym; }
2026
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002027 virtual PathDiagnosticPiece* getEndPath(BugReporter& BR,
2028 ExplodedNode<ValueState>* N);
2029
Ted Kremenek072192b2008-04-30 23:47:44 +00002030 virtual std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek8dd56462008-04-18 03:39:05 +00002031
2032 virtual PathDiagnosticPiece* VisitNode(ExplodedNode<ValueState>* N,
2033 ExplodedNode<ValueState>* PrevN,
2034 ExplodedGraph<ValueState>& G,
2035 BugReporter& BR);
2036 };
2037
2038
2039} // end anonymous namespace
2040
2041void CFRefCount::RegisterChecks(GRExprEngine& Eng) {
Ted Kremenek9f741612008-05-02 18:01:49 +00002042 if (EmitStandardWarnings) GRSimpleVals::RegisterChecks(Eng);
Ted Kremenek8dd56462008-04-18 03:39:05 +00002043 Eng.Register(new UseAfterRelease(*this));
2044 Eng.Register(new BadRelease(*this));
2045 Eng.Register(new Leak(*this));
2046}
2047
Ted Kremenek072192b2008-04-30 23:47:44 +00002048
2049static const char* Msgs[] = {
2050 "Code is compiled in garbage collection only mode" // GC only
2051 " (the bug occurs with garbage collection enabled).",
2052
2053 "Code is compiled without garbage collection.", // No GC.
2054
2055 "Code is compiled for use with and without garbage collection (GC)."
2056 " The bug occurs with GC enabled.", // Hybrid, with GC.
2057
2058 "Code is compiled for use with and without garbage collection (GC)."
2059 " The bug occurs in non-GC mode." // Hyrbird, without GC/
2060};
2061
2062std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2063 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2064
2065 switch (TF.getLangOptions().getGCMode()) {
2066 default:
2067 assert(false);
Ted Kremenek31593ac2008-05-01 04:02:04 +00002068
2069 case LangOptions::GCOnly:
2070 assert (TF.isGCEnabled());
2071 return std::make_pair(&Msgs[0], &Msgs[0]+1);
Ted Kremenek072192b2008-04-30 23:47:44 +00002072
2073 case LangOptions::NonGC:
2074 assert (!TF.isGCEnabled());
Ted Kremenek072192b2008-04-30 23:47:44 +00002075 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2076
2077 case LangOptions::HybridGC:
2078 if (TF.isGCEnabled())
2079 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2080 else
2081 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2082 }
2083}
2084
Ted Kremenek8dd56462008-04-18 03:39:05 +00002085PathDiagnosticPiece* CFRefReport::VisitNode(ExplodedNode<ValueState>* N,
2086 ExplodedNode<ValueState>* PrevN,
2087 ExplodedGraph<ValueState>& G,
2088 BugReporter& BR) {
2089
2090 // Check if the type state has changed.
2091
2092 ValueState* PrevSt = PrevN->getState();
2093 ValueState* CurrSt = N->getState();
2094
2095 CFRefCount::RefBindings PrevB = CFRefCount::GetRefBindings(*PrevSt);
2096 CFRefCount::RefBindings CurrB = CFRefCount::GetRefBindings(*CurrSt);
2097
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002098 CFRefCount::RefBindings::TreeTy* PrevT = PrevB.SlimFind(Sym);
2099 CFRefCount::RefBindings::TreeTy* CurrT = CurrB.SlimFind(Sym);
Ted Kremenek8dd56462008-04-18 03:39:05 +00002100
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002101 if (!CurrT)
2102 return NULL;
Ted Kremenek8dd56462008-04-18 03:39:05 +00002103
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002104 const char* Msg = NULL;
2105 RefVal CurrV = CurrB.SlimFind(Sym)->getValue().second;
Ted Kremenekce48e002008-05-05 17:53:17 +00002106
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002107 if (!PrevT) {
2108
Ted Kremenekce48e002008-05-05 17:53:17 +00002109 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2110
2111 if (CurrV.isOwned()) {
2112
2113 if (isa<CallExpr>(S))
2114 Msg = "Function call returns an object with a +1 retain count"
2115 " (owning reference).";
2116 else {
2117 assert (isa<ObjCMessageExpr>(S));
2118 Msg = "Method returns an object with a +1 retain count"
2119 " (owning reference).";
2120 }
2121 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002122 else {
2123 assert (CurrV.isNotOwned());
Ted Kremenekce48e002008-05-05 17:53:17 +00002124
2125 if (isa<CallExpr>(S))
2126 Msg = "Function call returns an object with a +0 retain count"
2127 " (non-owning reference).";
2128 else {
2129 assert (isa<ObjCMessageExpr>(S));
2130 Msg = "Method returns an object with a +0 retain count"
2131 " (non-owning reference).";
2132 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002133 }
Ted Kremenekce48e002008-05-05 17:53:17 +00002134
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002135 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
2136 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, Msg);
2137
2138 if (Expr* Exp = dyn_cast<Expr>(S))
2139 P->addRange(Exp->getSourceRange());
2140
2141 return P;
2142 }
2143
2144 // Determine if the typestate has changed.
2145
2146 RefVal PrevV = PrevB.SlimFind(Sym)->getValue().second;
2147
2148 if (PrevV == CurrV)
2149 return NULL;
2150
2151 // The typestate has changed.
2152
2153 std::ostringstream os;
2154
2155 switch (CurrV.getKind()) {
2156 case RefVal::Owned:
2157 case RefVal::NotOwned:
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002158
2159 if (PrevV.getCount() == CurrV.getCount())
2160 return 0;
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002161
2162 if (PrevV.getCount() > CurrV.getCount())
2163 os << "Reference count decremented.";
2164 else
2165 os << "Reference count incremented.";
2166
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002167 if (unsigned Count = CurrV.getCount()) {
Ted Kremenekce48e002008-05-05 17:53:17 +00002168
2169 os << " Object has +" << Count;
Ted Kremenek79c140b2008-04-18 05:32:44 +00002170
Ted Kremenekce48e002008-05-05 17:53:17 +00002171 if (Count > 1)
2172 os << " retain counts.";
Ted Kremenek79c140b2008-04-18 05:32:44 +00002173 else
Ted Kremenekce48e002008-05-05 17:53:17 +00002174 os << " retain count.";
Ted Kremenek79c140b2008-04-18 05:32:44 +00002175 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002176
2177 Msg = os.str().c_str();
2178
2179 break;
2180
2181 case RefVal::Released:
2182 Msg = "Object released.";
2183 break;
2184
2185 case RefVal::ReturnedOwned:
Ted Kremenekce48e002008-05-05 17:53:17 +00002186 Msg = "Object returned to caller as owning reference (single retain count"
2187 " transferred to caller).";
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002188 break;
2189
2190 case RefVal::ReturnedNotOwned:
Ted Kremenekce48e002008-05-05 17:53:17 +00002191 Msg = "Object returned to caller with a +0 (non-owning) retain count.";
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002192 break;
2193
2194 default:
2195 return NULL;
2196 }
2197
2198 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2199 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
2200 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, Msg);
2201
2202 // Add the range by scanning the children of the statement for any bindings
2203 // to Sym.
2204
2205 ValueStateManager& VSM = BR.getEngine().getStateManager();
2206
2207 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2208 if (Expr* Exp = dyn_cast_or_null<Expr>(*I)) {
2209 RVal X = VSM.GetRVal(CurrSt, Exp);
2210
2211 if (lval::SymbolVal* SV = dyn_cast<lval::SymbolVal>(&X))
2212 if (SV->getSymbol() == Sym) {
2213 P->addRange(Exp->getSourceRange()); break;
2214 }
2215 }
2216
2217 return P;
Ted Kremenek8dd56462008-04-18 03:39:05 +00002218}
2219
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002220static std::pair<ExplodedNode<ValueState>*,VarDecl*>
2221GetAllocationSite(ExplodedNode<ValueState>* N, SymbolID Sym) {
2222
2223 typedef CFRefCount::RefBindings RefBindings;
2224 ExplodedNode<ValueState>* Last = N;
2225
2226 // Find the first node that referred to the tracked symbol. We also
2227 // try and find the first VarDecl the value was stored to.
2228
2229 VarDecl* FirstDecl = 0;
2230
2231 while (N) {
2232 ValueState* St = N->getState();
2233 RefBindings B = RefBindings((RefBindings::TreeTy*) St->CheckerState);
2234 RefBindings::TreeTy* T = B.SlimFind(Sym);
2235
2236 if (!T)
2237 break;
2238
2239 VarDecl* VD = 0;
2240
2241 // Determine if there is an LVal binding to the symbol.
2242 for (ValueState::vb_iterator I=St->vb_begin(), E=St->vb_end(); I!=E; ++I) {
2243 if (!isa<lval::SymbolVal>(I->second) // Is the value a symbol?
2244 || cast<lval::SymbolVal>(I->second).getSymbol() != Sym)
2245 continue;
2246
2247 if (VD) { // Multiple decls map to this symbol.
2248 VD = 0;
2249 break;
2250 }
2251
2252 VD = I->first;
2253 }
2254
2255 if (VD) FirstDecl = VD;
2256
2257 Last = N;
2258 N = N->pred_empty() ? NULL : *(N->pred_begin());
2259 }
2260
2261 return std::make_pair(Last, FirstDecl);
2262}
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002263
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002264PathDiagnosticPiece* CFRefReport::getEndPath(BugReporter& BR,
Ted Kremeneke28565b2008-05-05 18:50:19 +00002265 ExplodedNode<ValueState>* EndN) {
Ted Kremenek1aa44c72008-05-22 23:45:19 +00002266
2267 // Tell the BugReporter to report cases when the tracked symbol is
2268 // assigned to different variables, etc.
2269 BR.addNotableSymbol(Sym);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002270
2271 if (!getBugType().isLeak())
Ted Kremeneke28565b2008-05-05 18:50:19 +00002272 return RangedBugReport::getEndPath(BR, EndN);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002273
Ted Kremenekce48e002008-05-05 17:53:17 +00002274 typedef CFRefCount::RefBindings RefBindings;
2275
2276 // Get the retain count.
2277 unsigned long RetCount = 0;
2278
2279 {
Ted Kremeneke28565b2008-05-05 18:50:19 +00002280 ValueState* St = EndN->getState();
Ted Kremenekce48e002008-05-05 17:53:17 +00002281 RefBindings B = RefBindings((RefBindings::TreeTy*) St->CheckerState);
2282 RefBindings::TreeTy* T = B.SlimFind(Sym);
2283 assert (T);
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002284 RetCount = T->getValue().second.getCount();
Ted Kremenekce48e002008-05-05 17:53:17 +00002285 }
2286
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002287 // We are a leak. Walk up the graph to get to the first node where the
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002288 // symbol appeared, and also get the first VarDecl that tracked object
2289 // is stored to.
2290
2291 ExplodedNode<ValueState>* AllocNode = 0;
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002292 VarDecl* FirstDecl = 0;
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002293 llvm::tie(AllocNode, FirstDecl) = GetAllocationSite(EndN, Sym);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002294
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002295 // Get the allocate site.
2296 assert (AllocNode);
2297 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002298
Ted Kremeneke28565b2008-05-05 18:50:19 +00002299 SourceManager& SMgr = BR.getContext().getSourceManager();
2300 unsigned AllocLine = SMgr.getLogicalLineNumber(FirstStmt->getLocStart());
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002301
Ted Kremeneke28565b2008-05-05 18:50:19 +00002302 // Get the leak site. We may have multiple ExplodedNodes (one with the
2303 // leak) that occur on the same line number; if the node with the leak
2304 // has any immediate predecessor nodes with the same line number, find
2305 // any transitive-successors that have a different statement and use that
2306 // line number instead. This avoids emiting a diagnostic like:
2307 //
2308 // // 'y' is leaked.
2309 // int x = foo(y);
2310 //
2311 // instead we want:
2312 //
2313 // int x = foo(y);
2314 // // 'y' is leaked.
2315
2316 Stmt* S = getStmt(BR); // This is the statement where the leak occured.
2317 assert (S);
2318 unsigned EndLine = SMgr.getLogicalLineNumber(S->getLocStart());
2319
2320 // Look in the *trimmed* graph at the immediate predecessor of EndN. Does
2321 // it occur on the same line?
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002322
2323 PathDiagnosticPiece::DisplayHint Hint = PathDiagnosticPiece::Above;
Ted Kremeneke28565b2008-05-05 18:50:19 +00002324
2325 assert (!EndN->pred_empty()); // Not possible to have 0 predecessors.
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002326 ExplodedNode<ValueState> *Pred = *(EndN->pred_begin());
2327 ProgramPoint PredPos = Pred->getLocation();
Ted Kremeneke28565b2008-05-05 18:50:19 +00002328
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002329 if (PostStmt* PredPS = dyn_cast<PostStmt>(&PredPos)) {
Ted Kremeneke28565b2008-05-05 18:50:19 +00002330
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002331 Stmt* SPred = PredPS->getStmt();
Ted Kremeneke28565b2008-05-05 18:50:19 +00002332
2333 // Predecessor at same line?
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002334 if (SMgr.getLogicalLineNumber(SPred->getLocStart()) != EndLine) {
2335 Hint = PathDiagnosticPiece::Below;
2336 S = SPred;
2337 }
Ted Kremeneke28565b2008-05-05 18:50:19 +00002338 }
Ted Kremeneke28565b2008-05-05 18:50:19 +00002339
2340 // Generate the diagnostic.
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002341 FullSourceLoc L( S->getLocStart(), SMgr);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002342 std::ostringstream os;
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002343
Ted Kremeneke28565b2008-05-05 18:50:19 +00002344 os << "Object allocated on line " << AllocLine;
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002345
2346 if (FirstDecl)
2347 os << " and stored into '" << FirstDecl->getName() << '\'';
2348
Ted Kremenekce48e002008-05-05 17:53:17 +00002349 os << " is no longer referenced after this point and has a retain count of +"
2350 << RetCount << " (object leaked).";
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002351
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002352 return new PathDiagnosticPiece(L, os.str(), Hint);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002353}
2354
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00002355void UseAfterRelease::EmitWarnings(BugReporter& BR) {
Ted Kremenekfa34b332008-04-09 01:10:13 +00002356
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00002357 for (CFRefCount::use_after_iterator I = TF.use_after_begin(),
2358 E = TF.use_after_end(); I != E; ++I) {
2359
Ted Kremenek8dd56462008-04-18 03:39:05 +00002360 CFRefReport report(*this, I->first, I->second.second);
2361 report.addRange(I->second.first->getSourceRange());
Ted Kremenek75840e12008-04-18 01:56:37 +00002362 BR.EmitWarning(report);
Ted Kremenekfa34b332008-04-09 01:10:13 +00002363 }
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00002364}
2365
2366void BadRelease::EmitWarnings(BugReporter& BR) {
Ted Kremenekfa34b332008-04-09 01:10:13 +00002367
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00002368 for (CFRefCount::bad_release_iterator I = TF.bad_release_begin(),
2369 E = TF.bad_release_end(); I != E; ++I) {
2370
Ted Kremenek8dd56462008-04-18 03:39:05 +00002371 CFRefReport report(*this, I->first, I->second.second);
2372 report.addRange(I->second.first->getSourceRange());
2373 BR.EmitWarning(report);
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00002374 }
2375}
Ted Kremenekfa34b332008-04-09 01:10:13 +00002376
Ted Kremenek989d5192008-04-17 23:43:50 +00002377void Leak::EmitWarnings(BugReporter& BR) {
2378
2379 for (CFRefCount::leaks_iterator I = TF.leaks_begin(),
2380 E = TF.leaks_end(); I != E; ++I) {
2381
Ted Kremenek8dd56462008-04-18 03:39:05 +00002382 std::vector<SymbolID>& SymV = *(I->second);
2383 unsigned n = SymV.size();
2384
2385 for (unsigned i = 0; i < n; ++i) {
2386 CFRefReport report(*this, I->first, SymV[i]);
2387 BR.EmitWarning(report);
2388 }
Ted Kremenek989d5192008-04-17 23:43:50 +00002389 }
2390}
2391
Ted Kremenekcb612922008-04-18 19:23:43 +00002392void Leak::GetErrorNodes(std::vector<ExplodedNode<ValueState>*>& Nodes) {
2393 for (CFRefCount::leaks_iterator I=TF.leaks_begin(), E=TF.leaks_end();
2394 I!=E; ++I)
2395 Nodes.push_back(I->first);
2396}
2397
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002398bool Leak::isCached(BugReport& R) {
2399
2400 // Most bug reports are cached at the location where they occured.
2401 // With leaks, we want to unique them by the location where they were
2402 // allocated, and only report only a single path.
2403
2404 SymbolID Sym = static_cast<CFRefReport&>(R).getSymbol();
2405
2406 ExplodedNode<ValueState>* AllocNode =
2407 GetAllocationSite(R.getEndNode(), Sym).first;
2408
2409 if (!AllocNode)
2410 return false;
2411
2412 return BugTypeCacheLocation::isCached(AllocNode->getLocation());
2413}
2414
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002415//===----------------------------------------------------------------------===//
Ted Kremenekd71ed262008-04-10 22:16:52 +00002416// Transfer function creation for external clients.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002417//===----------------------------------------------------------------------===//
2418
Ted Kremenek072192b2008-04-30 23:47:44 +00002419GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
Ted Kremenek9f741612008-05-02 18:01:49 +00002420 bool StandardWarnings,
Ted Kremenek072192b2008-04-30 23:47:44 +00002421 const LangOptions& lopts) {
Ted Kremenek9f741612008-05-02 18:01:49 +00002422 return new CFRefCount(Ctx, GCEnabled, StandardWarnings, lopts);
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +00002423}