blob: f36b4eb1fc48548355f03e44eeb20217a53fe594 [file] [log] [blame]
Chris Lattnerbe1a7a02008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek827f93b2008-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 Greif2224fcb2008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek827f93b2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremeneka7338b42008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenekfe30beb2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekfe4d2312008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremenek827f93b2008-03-06 00:08:09 +000018#include "clang/Analysis/PathSensitive/ValueState.h"
Ted Kremenekdd0126b2008-03-31 18:26:32 +000019#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek827f93b2008-03-06 00:08:09 +000020#include "clang/Analysis/LocalCheckers.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000021#include "clang/Analysis/PathDiagnostic.h"
22#include "clang/Analysis/PathSensitive/BugReporter.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000023#include "clang/AST/DeclObjC.h"
Ted Kremeneka7338b42008-03-11 06:39:11 +000024#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/FoldingSet.h"
26#include "llvm/ADT/ImmutableMap.h"
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000027#include "llvm/ADT/StringExtras.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000028#include "llvm/Support/Compiler.h"
Ted Kremenekd7e26782008-05-16 18:33:44 +000029#include "llvm/ADT/STLExtras.h"
Ted Kremenek3b11f7a2008-03-11 19:44:10 +000030#include <ostream>
Ted Kremeneka8503952008-04-18 04:55:01 +000031#include <sstream>
Ted Kremenek9449ca92008-08-12 20:41:56 +000032#include <stdarg.h>
Ted Kremenek827f93b2008-03-06 00:08:09 +000033
34using namespace clang;
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000035using llvm::CStrInCStrNoCase;
Ted Kremenek827f93b2008-03-06 00:08:09 +000036
Ted Kremenek7d421f32008-04-09 23:49:11 +000037//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +000038// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +000039//===----------------------------------------------------------------------===//
40
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +000041static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +000042 IdentifierInfo* II = &Ctx.Idents.get(name);
43 return Ctx.Selectors.getSelector(0, &II);
44}
45
Ted Kremenek0e344d42008-05-06 00:30:21 +000046static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
47 IdentifierInfo* II = &Ctx.Idents.get(name);
48 return Ctx.Selectors.getSelector(1, &II);
49}
50
Ted Kremenek272aa852008-06-25 21:21:56 +000051//===----------------------------------------------------------------------===//
52// Type querying functions.
53//===----------------------------------------------------------------------===//
54
Ted Kremenek62820d82008-05-07 20:06:41 +000055static bool isCFRefType(QualType T) {
56
57 if (!T->isPointerType())
58 return false;
59
Ted Kremenek272aa852008-06-25 21:21:56 +000060 // Check the typedef for the name "CF" and the substring "Ref".
Ted Kremenek62820d82008-05-07 20:06:41 +000061 TypedefType* TD = dyn_cast<TypedefType>(T.getTypePtr());
62
63 if (!TD)
64 return false;
65
66 const char* TDName = TD->getDecl()->getIdentifier()->getName();
67 assert (TDName);
68
69 if (TDName[0] != 'C' || TDName[1] != 'F')
70 return false;
71
72 if (strstr(TDName, "Ref") == 0)
73 return false;
74
75 return true;
76}
77
Ted Kremenek4c5378c2008-07-15 16:50:12 +000078static bool isCGRefType(QualType T) {
79
80 if (!T->isPointerType())
81 return false;
82
83 // Check the typedef for the name "CG" and the substring "Ref".
84 TypedefType* TD = dyn_cast<TypedefType>(T.getTypePtr());
85
86 if (!TD)
87 return false;
88
89 const char* TDName = TD->getDecl()->getIdentifier()->getName();
90 assert (TDName);
91
92 if (TDName[0] != 'C' || TDName[1] != 'G')
93 return false;
94
95 if (strstr(TDName, "Ref") == 0)
96 return false;
97
98 return true;
99}
100
Ted Kremenek62820d82008-05-07 20:06:41 +0000101static bool isNSType(QualType T) {
102
103 if (!T->isPointerType())
104 return false;
105
106 ObjCInterfaceType* OT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
107
108 if (!OT)
109 return false;
110
111 const char* ClsName = OT->getDecl()->getIdentifier()->getName();
112 assert (ClsName);
113
114 if (ClsName[0] != 'N' || ClsName[1] != 'S')
115 return false;
116
117 return true;
118}
119
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000120//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000121// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000122//===----------------------------------------------------------------------===//
123
Ted Kremenek272aa852008-06-25 21:21:56 +0000124namespace {
125/// ArgEffect is used to summarize a function/method call's effect on a
126/// particular argument.
Ted Kremenekede40b72008-07-09 18:11:16 +0000127enum ArgEffect { IncRef, DecRef, DoNothing, DoNothingByRef,
128 StopTracking, MayEscape, SelfOwn, Autorelease };
Ted Kremenek272aa852008-06-25 21:21:56 +0000129
130/// ArgEffects summarizes the effects of a function/method call on all of
131/// its arguments.
132typedef std::vector<std::pair<unsigned,ArgEffect> > ArgEffects;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000133}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000134
Ted Kremeneka7338b42008-03-11 06:39:11 +0000135namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000136template <> struct FoldingSetTrait<ArgEffects> {
137 static void Profile(const ArgEffects& X, FoldingSetNodeID& ID) {
138 for (ArgEffects::const_iterator I = X.begin(), E = X.end(); I!= E; ++I) {
139 ID.AddInteger(I->first);
140 ID.AddInteger((unsigned) I->second);
141 }
142 }
143};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000144} // end llvm namespace
145
146namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000147
148/// RetEffect is used to summarize a function/method call's behavior with
149/// respect to its return value.
150class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000151public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000152 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
153 NotOwnedSymbol, ReceiverAlias };
Ted Kremenek272aa852008-06-25 21:21:56 +0000154
Ted Kremeneka7338b42008-03-11 06:39:11 +0000155private:
156 unsigned Data;
Ted Kremenek272aa852008-06-25 21:21:56 +0000157 RetEffect(Kind k, unsigned D = 0) { Data = (D << 3) | (unsigned) k; }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000158
Ted Kremeneka7338b42008-03-11 06:39:11 +0000159public:
Ted Kremenek272aa852008-06-25 21:21:56 +0000160
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000161 Kind getKind() const { return (Kind) (Data & 0x7); }
Ted Kremenek272aa852008-06-25 21:21:56 +0000162
163 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000164 assert(getKind() == Alias);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000165 return Data >> 3;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000166 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000167
Ted Kremenek272aa852008-06-25 21:21:56 +0000168 static RetEffect MakeAlias(unsigned Idx) {
169 return RetEffect(Alias, Idx);
170 }
171 static RetEffect MakeReceiverAlias() {
172 return RetEffect(ReceiverAlias);
173 }
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000174 static RetEffect MakeOwned(bool isAllocated = false) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000175 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol);
176 }
177 static RetEffect MakeNotOwned() {
178 return RetEffect(NotOwnedSymbol);
179 }
180 static RetEffect MakeNoRet() {
181 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000182 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000183
Ted Kremenek272aa852008-06-25 21:21:56 +0000184 operator Kind() const {
185 return getKind();
186 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000187
Ted Kremenek272aa852008-06-25 21:21:56 +0000188 void Profile(llvm::FoldingSetNodeID& ID) const {
189 ID.AddInteger(Data);
190 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000191};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000192
Ted Kremenek272aa852008-06-25 21:21:56 +0000193
194class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000195 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
196 /// specifies the argument (starting from 0). This can be sparsely
197 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000198 ArgEffects* Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000199
200 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
201 /// do not have an entry in Args.
202 ArgEffect DefaultArgEffect;
203
Ted Kremenek272aa852008-06-25 21:21:56 +0000204 /// Receiver - If this summary applies to an Objective-C message expression,
205 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000206 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000207
208 /// Ret - The effect on the return value. Used to indicate if the
209 /// function/method call returns a new tracked symbol, returns an
210 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000211 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000212
Ted Kremenekf2717b02008-07-18 17:24:20 +0000213 /// EndPath - Indicates that execution of this method/function should
214 /// terminate the simulation of a path.
215 bool EndPath;
216
Ted Kremeneka7338b42008-03-11 06:39:11 +0000217public:
218
Ted Kremenekbcaff792008-05-06 15:44:25 +0000219 RetainSummary(ArgEffects* A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000220 ArgEffect ReceiverEff, bool endpath = false)
221 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
222 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000223
Ted Kremenek272aa852008-06-25 21:21:56 +0000224 /// getArg - Return the argument effect on the argument specified by
225 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000226 ArgEffect getArg(unsigned idx) const {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000227
Ted Kremenekae855d42008-04-24 17:22:33 +0000228 if (!Args)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000229 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000230
231 // If Args is present, it is likely to contain only 1 element.
232 // Just do a linear search. Do it from the back because functions with
233 // large numbers of arguments will be tail heavy with respect to which
Ted Kremenek272aa852008-06-25 21:21:56 +0000234 // argument they actually modify with respect to the reference count.
Ted Kremenekae855d42008-04-24 17:22:33 +0000235 for (ArgEffects::reverse_iterator I=Args->rbegin(), E=Args->rend();
236 I!=E; ++I) {
237
238 if (idx > I->first)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000239 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000240
241 if (idx == I->first)
242 return I->second;
243 }
244
Ted Kremenekbcaff792008-05-06 15:44:25 +0000245 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000246 }
247
Ted Kremenek272aa852008-06-25 21:21:56 +0000248 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000249 RetEffect getRetEffect() const {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000250 return Ret;
251 }
252
Ted Kremenekf2717b02008-07-18 17:24:20 +0000253 /// isEndPath - Returns true if executing the given method/function should
254 /// terminate the path.
255 bool isEndPath() const { return EndPath; }
256
Ted Kremenek272aa852008-06-25 21:21:56 +0000257 /// getReceiverEffect - Returns the effect on the receiver of the call.
258 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000259 ArgEffect getReceiverEffect() const {
260 return Receiver;
261 }
262
Ted Kremenek2719e982008-06-17 02:43:46 +0000263 typedef ArgEffects::const_iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000264
Ted Kremenek2719e982008-06-17 02:43:46 +0000265 ExprIterator begin_args() const { return Args->begin(); }
266 ExprIterator end_args() const { return Args->end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000267
Ted Kremenek266d8b62008-05-06 02:26:56 +0000268 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects* A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000269 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000270 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000271 ID.AddPointer(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000272 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000273 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000274 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000275 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000276 }
277
278 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000279 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000280 }
281};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000282} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000283
Ted Kremenek272aa852008-06-25 21:21:56 +0000284//===----------------------------------------------------------------------===//
285// Data structures for constructing summaries.
286//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000287
Ted Kremenek272aa852008-06-25 21:21:56 +0000288namespace {
289class VISIBILITY_HIDDEN ObjCSummaryKey {
290 IdentifierInfo* II;
291 Selector S;
292public:
293 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
294 : II(ii), S(s) {}
295
296 ObjCSummaryKey(ObjCInterfaceDecl* d, Selector s)
297 : II(d ? d->getIdentifier() : 0), S(s) {}
298
299 ObjCSummaryKey(Selector s)
300 : II(0), S(s) {}
301
302 IdentifierInfo* getIdentifier() const { return II; }
303 Selector getSelector() const { return S; }
304};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000305}
306
307namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000308template <> struct DenseMapInfo<ObjCSummaryKey> {
309 static inline ObjCSummaryKey getEmptyKey() {
310 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
311 DenseMapInfo<Selector>::getEmptyKey());
312 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000313
Ted Kremenek272aa852008-06-25 21:21:56 +0000314 static inline ObjCSummaryKey getTombstoneKey() {
315 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
316 DenseMapInfo<Selector>::getTombstoneKey());
317 }
318
319 static unsigned getHashValue(const ObjCSummaryKey &V) {
320 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
321 & 0x88888888)
322 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
323 & 0x55555555);
324 }
325
326 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
327 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
328 RHS.getIdentifier()) &&
329 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
330 RHS.getSelector());
331 }
332
333 static bool isPod() {
334 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
335 DenseMapInfo<Selector>::isPod();
336 }
337};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000338} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000339
Ted Kremenek84f010c2008-06-23 23:30:29 +0000340namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000341class VISIBILITY_HIDDEN ObjCSummaryCache {
342 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
343 MapTy M;
344public:
345 ObjCSummaryCache() {}
346
347 typedef MapTy::iterator iterator;
348
349 iterator find(ObjCInterfaceDecl* D, Selector S) {
350
351 // Do a lookup with the (D,S) pair. If we find a match return
352 // the iterator.
353 ObjCSummaryKey K(D, S);
354 MapTy::iterator I = M.find(K);
355
356 if (I != M.end() || !D)
357 return I;
358
359 // Walk the super chain. If we find a hit with a parent, we'll end
360 // up returning that summary. We actually allow that key (null,S), as
361 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
362 // generate initial summaries without having to worry about NSObject
363 // being declared.
364 // FIXME: We may change this at some point.
365 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
366 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
367 break;
368
369 if (!C)
370 return I;
371 }
372
373 // Cache the summary with original key to make the next lookup faster
374 // and return the iterator.
375 M[K] = I->second;
376 return I;
377 }
378
Ted Kremenek9449ca92008-08-12 20:41:56 +0000379
Ted Kremenek272aa852008-06-25 21:21:56 +0000380 iterator find(Expr* Receiver, Selector S) {
381 return find(getReceiverDecl(Receiver), S);
382 }
383
384 iterator find(IdentifierInfo* II, Selector S) {
385 // FIXME: Class method lookup. Right now we dont' have a good way
386 // of going between IdentifierInfo* and the class hierarchy.
387 iterator I = M.find(ObjCSummaryKey(II, S));
388 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
389 }
390
391 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
392
393 const PointerType* PT = E->getType()->getAsPointerType();
394 if (!PT) return 0;
395
396 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
397 if (!OI) return 0;
398
399 return OI ? OI->getDecl() : 0;
400 }
401
402 iterator end() { return M.end(); }
403
404 RetainSummary*& operator[](ObjCMessageExpr* ME) {
405
406 Selector S = ME->getSelector();
407
408 if (Expr* Receiver = ME->getReceiver()) {
409 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
410 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
411 }
412
413 return M[ObjCSummaryKey(ME->getClassName(), S)];
414 }
415
416 RetainSummary*& operator[](ObjCSummaryKey K) {
417 return M[K];
418 }
419
420 RetainSummary*& operator[](Selector S) {
421 return M[ ObjCSummaryKey(S) ];
422 }
423};
424} // end anonymous namespace
425
426//===----------------------------------------------------------------------===//
427// Data structures for managing collections of summaries.
428//===----------------------------------------------------------------------===//
429
430namespace {
431class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000432
433 //==-----------------------------------------------------------------==//
434 // Typedefs.
435 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000436
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000437 typedef llvm::FoldingSet<llvm::FoldingSetNodeWrapper<ArgEffects> >
438 ArgEffectsSetTy;
439
440 typedef llvm::FoldingSet<RetainSummary>
441 SummarySetTy;
442
443 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
444 FuncSummariesTy;
445
Ted Kremenek84f010c2008-06-23 23:30:29 +0000446 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000447
448 //==-----------------------------------------------------------------==//
449 // Data.
450 //==-----------------------------------------------------------------==//
451
Ted Kremenek272aa852008-06-25 21:21:56 +0000452 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000453 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000454
Ted Kremenekede40b72008-07-09 18:11:16 +0000455 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
456 /// "CFDictionaryCreate".
457 IdentifierInfo* CFDictionaryCreateII;
458
Ted Kremenek272aa852008-06-25 21:21:56 +0000459 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000460 const bool GCEnabled;
461
Ted Kremenek272aa852008-06-25 21:21:56 +0000462 /// SummarySet - A FoldingSet of uniqued summaries.
Ted Kremeneka4c74292008-04-10 22:58:08 +0000463 SummarySetTy SummarySet;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000464
Ted Kremenek272aa852008-06-25 21:21:56 +0000465 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000466 FuncSummariesTy FuncSummaries;
467
Ted Kremenek272aa852008-06-25 21:21:56 +0000468 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
469 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000470 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000471
Ted Kremenek272aa852008-06-25 21:21:56 +0000472 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000473 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000474
Ted Kremenek272aa852008-06-25 21:21:56 +0000475 /// ArgEffectsSet - A FoldingSet of uniqued ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000476 ArgEffectsSetTy ArgEffectsSet;
477
Ted Kremenek272aa852008-06-25 21:21:56 +0000478 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
479 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000480 llvm::BumpPtrAllocator BPAlloc;
481
Ted Kremenek272aa852008-06-25 21:21:56 +0000482 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000483 ArgEffects ScratchArgs;
484
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000485 RetainSummary* StopSummary;
486
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000487 //==-----------------------------------------------------------------==//
488 // Methods.
489 //==-----------------------------------------------------------------==//
490
Ted Kremenek272aa852008-06-25 21:21:56 +0000491 /// getArgEffects - Returns a persistent ArgEffects object based on the
492 /// data in ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000493 ArgEffects* getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000494
Ted Kremenek562c1302008-05-05 16:51:50 +0000495 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000496 RetainSummary* getUnarySummary(FunctionDecl* FD, UnaryFuncKind func);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000497
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000498 RetainSummary* getNSSummary(FunctionDecl* FD, const char* FName);
499 RetainSummary* getCFSummary(FunctionDecl* FD, const char* FName);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000500 RetainSummary* getCGSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000501
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000502 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
503 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000504 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000505
Ted Kremenek266d8b62008-05-06 02:26:56 +0000506 RetainSummary* getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000507 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000508 ArgEffect DefaultEff = MayEscape,
509 bool isEndPath = false);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000510
Ted Kremenek266d8b62008-05-06 02:26:56 +0000511 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000512 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000513 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000514 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000515 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000516
Ted Kremenekbcaff792008-05-06 15:44:25 +0000517 RetainSummary* getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000518 if (StopSummary)
519 return StopSummary;
520
521 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
522 StopTracking, StopTracking);
523
524 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000525 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000526
Ted Kremenek272aa852008-06-25 21:21:56 +0000527 RetainSummary* getInitMethodSummary(ObjCMessageExpr* ME);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000528
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000529 void InitializeClassMethodSummaries();
530 void InitializeMethodSummaries();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000531
532 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
533 RetainSummary* Summ) {
534 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
535 }
536
Ted Kremenek272aa852008-06-25 21:21:56 +0000537 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
538 ObjCClassMethodSummaries[S] = Summ;
539 }
540
541 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
542 ObjCMethodSummaries[S] = Summ;
543 }
544
Ted Kremenek45642a42008-08-12 18:48:50 +0000545 void addInstMethSummary(const char* Cls, RetainSummary* Summ, va_list argp) {
Ted Kremenekf2717b02008-07-18 17:24:20 +0000546
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000547 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
548 llvm::SmallVector<IdentifierInfo*, 10> II;
549
550 while (const char* s = va_arg(argp, const char*))
551 II.push_back(&Ctx.Idents.get(s));
552
553 Selector S = Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekf2717b02008-07-18 17:24:20 +0000554 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
555 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000556
557 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
558 va_list argp;
559 va_start(argp, Summ);
560 addInstMethSummary(Cls, Summ, argp);
561 va_end(argp);
562 }
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000563
564 void addPanicSummary(const char* Cls, ...) {
565 RetainSummary* Summ = getPersistentSummary(0, RetEffect::MakeNoRet(),
566 DoNothing, DoNothing, true);
567 va_list argp;
568 va_start (argp, Cls);
Ted Kremenek45642a42008-08-12 18:48:50 +0000569 addInstMethSummary(Cls, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000570 va_end(argp);
571 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000572
Ted Kremeneka7338b42008-03-11 06:39:11 +0000573public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000574
575 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000576 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000577 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenek272aa852008-06-25 21:21:56 +0000578 GCEnabled(gcenabled), StopSummary(0) {
579
580 InitializeClassMethodSummaries();
581 InitializeMethodSummaries();
582 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000583
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000584 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000585
Ted Kremenekd13c1872008-06-24 03:56:45 +0000586 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek272aa852008-06-25 21:21:56 +0000587 RetainSummary* getMethodSummary(ObjCMessageExpr* ME, ObjCInterfaceDecl* ID);
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000588 RetainSummary* getClassMethodSummary(IdentifierInfo* ClsName, Selector S);
Ted Kremenek926abf22008-05-06 04:20:12 +0000589
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000590 bool isGCEnabled() const { return GCEnabled; }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000591};
592
593} // end anonymous namespace
594
595//===----------------------------------------------------------------------===//
596// Implementation of checker data structures.
597//===----------------------------------------------------------------------===//
598
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000599RetainSummaryManager::~RetainSummaryManager() {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000600
601 // FIXME: The ArgEffects could eventually be allocated from BPAlloc,
602 // mitigating the need to do explicit cleanup of the
603 // Argument-Effect summaries.
604
Ted Kremenek42ea0322008-05-05 23:55:01 +0000605 for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(),
606 E = ArgEffectsSet.end(); I!=E; ++I)
Ted Kremeneka7338b42008-03-11 06:39:11 +0000607 I->getValue().~ArgEffects();
Ted Kremenek827f93b2008-03-06 00:08:09 +0000608}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000609
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000610ArgEffects* RetainSummaryManager::getArgEffects() {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000611
Ted Kremenekae855d42008-04-24 17:22:33 +0000612 if (ScratchArgs.empty())
613 return NULL;
614
615 // Compute a profile for a non-empty ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000616 llvm::FoldingSetNodeID profile;
617 profile.Add(ScratchArgs);
618 void* InsertPos;
619
Ted Kremenekae855d42008-04-24 17:22:33 +0000620 // Look up the uniqued copy, or create a new one.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000621 llvm::FoldingSetNodeWrapper<ArgEffects>* E =
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000622 ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000623
Ted Kremenekae855d42008-04-24 17:22:33 +0000624 if (E) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000625 ScratchArgs.clear();
626 return &E->getValue();
627 }
628
629 E = (llvm::FoldingSetNodeWrapper<ArgEffects>*)
Ted Kremenek272aa852008-06-25 21:21:56 +0000630 BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000631
632 new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000633 ArgEffectsSet.InsertNode(E, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000634
635 ScratchArgs.clear();
636 return &E->getValue();
637}
638
Ted Kremenek266d8b62008-05-06 02:26:56 +0000639RetainSummary*
640RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000641 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000642 ArgEffect DefaultEff,
643 bool isEndPath) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000644
Ted Kremenekae855d42008-04-24 17:22:33 +0000645 // Generate a profile for the summary.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000646 llvm::FoldingSetNodeID profile;
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000647 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
648 isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000649
Ted Kremenekae855d42008-04-24 17:22:33 +0000650 // Look up the uniqued summary, or create one if it doesn't exist.
651 void* InsertPos;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000652 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000653
654 if (Summ)
655 return Summ;
656
Ted Kremenekae855d42008-04-24 17:22:33 +0000657 // Create the summary and return it.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000658 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000659 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000660 SummarySet.InsertNode(Summ, InsertPos);
661
662 return Summ;
663}
664
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000665//===----------------------------------------------------------------------===//
666// Summary creation for functions (largely uses of Core Foundation).
667//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000668
Ted Kremenekd13c1872008-06-24 03:56:45 +0000669RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000670
671 SourceLocation Loc = FD->getLocation();
672
673 if (!Loc.isFileID())
674 return NULL;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000675
Ted Kremenekae855d42008-04-24 17:22:33 +0000676 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000677 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekae855d42008-04-24 17:22:33 +0000678
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000679 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000680 return I->second;
681
682 // No summary. Generate one.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000683 const char* FName = FD->getIdentifier()->getName();
684
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000685 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000686
Ted Kremenek62820d82008-05-07 20:06:41 +0000687 FunctionType* FT = dyn_cast<FunctionType>(FD->getType());
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000688
689 do {
690 if (FT) {
691
692 QualType T = FT->getResultType();
693
694 if (isCFRefType(T)) {
695 S = getCFSummary(FD, FName);
696 break;
697 }
698
699 if (isCGRefType(T)) {
700 S = getCGSummary(FD, FName );
701 break;
702 }
703 }
704
705 if (FName[0] == 'C' && FName[1] == 'F')
706 S = getCFSummary(FD, FName);
707 else if (FName[0] == 'N' && FName[1] == 'S')
708 S = getNSSummary(FD, FName);
709 }
710 while (0);
Ted Kremenekae855d42008-04-24 17:22:33 +0000711
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000712 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +0000713 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000714}
715
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000716RetainSummary* RetainSummaryManager::getNSSummary(FunctionDecl* FD,
Ted Kremenek42ea0322008-05-05 23:55:01 +0000717 const char* FName) {
Ted Kremenek562c1302008-05-05 16:51:50 +0000718 FName += 2;
719
720 if (strcmp(FName, "MakeCollectable") == 0)
721 return getUnarySummary(FD, cfmakecollectable);
722
723 return 0;
724}
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000725
726static bool isRetain(FunctionDecl* FD, const char* FName) {
Ted Kremeneka48ea852008-07-15 17:43:41 +0000727 const char* loc = strstr(FName, "Retain");
728 return loc && loc[sizeof("Retain")-1] == '\0';
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000729}
730
731static bool isRelease(FunctionDecl* FD, const char* FName) {
Ted Kremeneka48ea852008-07-15 17:43:41 +0000732 const char* loc = strstr(FName, "Release");
733 return loc && loc[sizeof("Release")-1] == '\0';
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000734}
735
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000736RetainSummary* RetainSummaryManager::getCFSummary(FunctionDecl* FD,
Ted Kremenek42ea0322008-05-05 23:55:01 +0000737 const char* FName) {
Ted Kremenek562c1302008-05-05 16:51:50 +0000738
Ted Kremenek62820d82008-05-07 20:06:41 +0000739 if (FName[0] == 'C' && FName[1] == 'F')
740 FName += 2;
Ted Kremenek562c1302008-05-05 16:51:50 +0000741
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000742 if (isRetain(FD, FName))
Ted Kremenek562c1302008-05-05 16:51:50 +0000743 return getUnarySummary(FD, cfretain);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000744
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000745 if (isRelease(FD, FName))
Ted Kremenek562c1302008-05-05 16:51:50 +0000746 return getUnarySummary(FD, cfrelease);
Ted Kremenekede40b72008-07-09 18:11:16 +0000747
Ted Kremenek562c1302008-05-05 16:51:50 +0000748 if (strcmp(FName, "MakeCollectable") == 0)
749 return getUnarySummary(FD, cfmakecollectable);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000750
751 return getCFCreateGetRuleSummary(FD, FName);
752}
753
754RetainSummary* RetainSummaryManager::getCGSummary(FunctionDecl* FD,
755 const char* FName) {
756
757 if (FName[0] == 'C' && FName[1] == 'G')
758 FName += 2;
759
760 if (isRelease(FD, FName))
761 return getUnarySummary(FD, cfrelease);
762
763 if (isRetain(FD, FName))
764 return getUnarySummary(FD, cfretain);
765
766 return getCFCreateGetRuleSummary(FD, FName);
767}
768
769RetainSummary*
770RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
771 const char* FName) {
772
Ted Kremenek562c1302008-05-05 16:51:50 +0000773 if (strstr(FName, "Create") || strstr(FName, "Copy"))
774 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000775
Ted Kremenek562c1302008-05-05 16:51:50 +0000776 if (strstr(FName, "Get"))
777 return getCFSummaryGetRule(FD);
778
779 return 0;
780}
781
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000782RetainSummary*
783RetainSummaryManager::getUnarySummary(FunctionDecl* FD, UnaryFuncKind func) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000784
785 FunctionTypeProto* FT =
786 dyn_cast<FunctionTypeProto>(FD->getType().getTypePtr());
787
Ted Kremenek562c1302008-05-05 16:51:50 +0000788 if (FT) {
789
790 if (FT->getNumArgs() != 1)
791 return 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000792
Ted Kremenek562c1302008-05-05 16:51:50 +0000793 TypedefType* ArgT = dyn_cast<TypedefType>(FT->getArgType(0).getTypePtr());
794
795 if (!ArgT)
796 return 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000797
Ted Kremenek562c1302008-05-05 16:51:50 +0000798 if (!ArgT->isPointerType())
799 return NULL;
800 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000801
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000802 assert (ScratchArgs.empty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000803
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000804 switch (func) {
805 case cfretain: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000806 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000807 return getPersistentSummary(RetEffect::MakeAlias(0),
808 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000809 }
810
811 case cfrelease: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000812 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000813 return getPersistentSummary(RetEffect::MakeNoRet(),
814 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000815 }
816
817 case cfmakecollectable: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000818 if (GCEnabled)
819 ScratchArgs.push_back(std::make_pair(0, DecRef));
820
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000821 return getPersistentSummary(RetEffect::MakeAlias(0),
822 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000823 }
824
825 default:
Ted Kremenek562c1302008-05-05 16:51:50 +0000826 assert (false && "Not a supported unary function.");
Ted Kremenek9449ca92008-08-12 20:41:56 +0000827 return 0;
Ted Kremenekab2fa2a2008-04-10 23:44:06 +0000828 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000829}
830
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000831RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000832
Ted Kremenek62820d82008-05-07 20:06:41 +0000833 FunctionType* FT =
834 dyn_cast<FunctionType>(FD->getType().getTypePtr());
Ted Kremenek562c1302008-05-05 16:51:50 +0000835
836 if (FT && !isCFRefType(FT->getResultType()))
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000837 return getPersistentSummary(RetEffect::MakeNoRet());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000838
Ted Kremenekae855d42008-04-24 17:22:33 +0000839 assert (ScratchArgs.empty());
Ted Kremenekede40b72008-07-09 18:11:16 +0000840
841 if (FD->getIdentifier() == CFDictionaryCreateII) {
842 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
843 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
844 }
845
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000846 return getPersistentSummary(RetEffect::MakeOwned(true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000847}
848
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000849RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000850
Ted Kremenek62820d82008-05-07 20:06:41 +0000851 FunctionType* FT =
852 dyn_cast<FunctionType>(FD->getType().getTypePtr());
Ted Kremenekd4244d42008-04-11 20:11:19 +0000853
Ted Kremenek562c1302008-05-05 16:51:50 +0000854 if (FT) {
855 QualType RetTy = FT->getResultType();
Ted Kremenekd4244d42008-04-11 20:11:19 +0000856
Ted Kremenek562c1302008-05-05 16:51:50 +0000857 // FIXME: For now we assume that all pointer types returned are referenced
858 // counted. Since this is the "Get" rule, we assume non-ownership, which
859 // works fine for things that are not reference counted. We do this because
860 // some generic data structures return "void*". We need something better
861 // in the future.
862
863 if (!isCFRefType(RetTy) && !RetTy->isPointerType())
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000864 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek562c1302008-05-05 16:51:50 +0000865 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000866
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000867 // FIXME: Add special-cases for functions that retain/release. For now
868 // just handle the default case.
869
Ted Kremenekae855d42008-04-24 17:22:33 +0000870 assert (ScratchArgs.empty());
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000871 return getPersistentSummary(RetEffect::MakeNotOwned(), DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000872}
873
Ted Kremeneka7338b42008-03-11 06:39:11 +0000874//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000875// Summary creation for Selectors.
876//===----------------------------------------------------------------------===//
877
Ted Kremenekbcaff792008-05-06 15:44:25 +0000878RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +0000879RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek42ea0322008-05-05 23:55:01 +0000880 assert(ScratchArgs.empty());
881
882 RetainSummary* Summ =
Ted Kremenek0e344d42008-05-06 00:30:21 +0000883 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremenek42ea0322008-05-05 23:55:01 +0000884
Ted Kremenek272aa852008-06-25 21:21:56 +0000885 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +0000886 return Summ;
887}
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000888
Ted Kremenek272aa852008-06-25 21:21:56 +0000889
Ted Kremenekbcaff792008-05-06 15:44:25 +0000890RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +0000891RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
892 ObjCInterfaceDecl* ID) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000893
894 Selector S = ME->getSelector();
Ted Kremenek42ea0322008-05-05 23:55:01 +0000895
Ted Kremenek272aa852008-06-25 21:21:56 +0000896 // Look up a summary in our summary cache.
897 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000898
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000899 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +0000900 return I->second;
Ted Kremenek272aa852008-06-25 21:21:56 +0000901
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000902 if (!ME->getType()->isPointerType())
903 return 0;
904
Ted Kremenek42ea0322008-05-05 23:55:01 +0000905 // "initXXX": pass-through for receiver.
906
907 const char* s = S.getIdentifierInfoForSlot(0)->getName();
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000908 assert (ScratchArgs.empty());
Ted Kremenek1d3d9562008-05-06 06:09:09 +0000909
Ted Kremenek988c4472008-06-02 17:14:13 +0000910 if (strncmp(s, "init", 4) == 0 || strncmp(s, "_init", 5) == 0)
Ted Kremenek272aa852008-06-25 21:21:56 +0000911 return getInitMethodSummary(ME);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000912
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000913 // "copyXXX", "createXXX", "newXXX": allocators.
Ted Kremenek42ea0322008-05-05 23:55:01 +0000914
Ted Kremenek5496f6d2008-05-07 04:25:59 +0000915 if (!isNSType(ME->getReceiver()->getType()))
916 return 0;
917
Ted Kremenek62820d82008-05-07 20:06:41 +0000918 if (CStrInCStrNoCase(s, "create") || CStrInCStrNoCase(s, "copy") ||
919 CStrInCStrNoCase(s, "new")) {
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000920
921 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000922 : RetEffect::MakeOwned(true);
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000923
924 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenek272aa852008-06-25 21:21:56 +0000925 ObjCMethodSummaries[ME] = Summ;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000926 return Summ;
927 }
Ted Kremenekbcaff792008-05-06 15:44:25 +0000928
Ted Kremenek42ea0322008-05-05 23:55:01 +0000929 return 0;
930}
931
Ted Kremeneka7722b72008-05-06 21:26:51 +0000932RetainSummary*
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000933RetainSummaryManager::getClassMethodSummary(IdentifierInfo* ClsName,
934 Selector S) {
Ted Kremeneka7722b72008-05-06 21:26:51 +0000935
Ted Kremenek272aa852008-06-25 21:21:56 +0000936 // FIXME: Eventually we should properly do class method summaries, but
937 // it requires us being able to walk the type hierarchy. Unfortunately,
938 // we cannot do this with just an IdentifierInfo* for the class name.
939
Ted Kremeneka7722b72008-05-06 21:26:51 +0000940 // Look up a summary in our cache of Selectors -> Summaries.
Ted Kremenek272aa852008-06-25 21:21:56 +0000941 ObjCMethodSummariesTy::iterator I = ObjCClassMethodSummaries.find(ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +0000942
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000943 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +0000944 return I->second;
945
Ted Kremenek4c479322008-05-06 23:07:13 +0000946 return 0;
Ted Kremeneka7722b72008-05-06 21:26:51 +0000947}
948
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000949void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +0000950
951 assert (ScratchArgs.empty());
952
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000953 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
954 : RetEffect::MakeOwned(true);
955
Ted Kremenek0e344d42008-05-06 00:30:21 +0000956 RetainSummary* Summ = getPersistentSummary(E);
957
Ted Kremenek272aa852008-06-25 21:21:56 +0000958 // Create the summaries for "alloc", "new", and "allocWithZone:" for
959 // NSObject and its derivatives.
960 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
961 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
962 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +0000963
964 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000965 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek1ebce742008-07-18 18:14:26 +0000966 GetNullarySelector("currentHandler", Ctx),
Ted Kremenekf2717b02008-07-18 17:24:20 +0000967 getPersistentSummary(RetEffect::MakeNotOwned()));
Ted Kremenek0e344d42008-05-06 00:30:21 +0000968}
969
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000970void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +0000971
972 assert (ScratchArgs.empty());
973
Ted Kremeneka7722b72008-05-06 21:26:51 +0000974 // Create the "init" selector. It just acts as a pass-through for the
975 // receiver.
Ted Kremeneke44927e2008-07-01 17:21:27 +0000976 RetainSummary* InitSumm = getPersistentSummary(RetEffect::MakeReceiverAlias());
977 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +0000978
979 // The next methods are allocators.
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000980 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
981 : RetEffect::MakeOwned(true);
982
Ted Kremeneke44927e2008-07-01 17:21:27 +0000983 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +0000984
985 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +0000986 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
987
Ted Kremenek83b2cde2008-05-06 00:38:54 +0000988 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +0000989 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +0000990
Ted Kremenek266d8b62008-05-06 02:26:56 +0000991 // Create the "retain" selector.
992 E = RetEffect::MakeReceiverAlias();
993 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : IncRef);
Ted Kremenek272aa852008-06-25 21:21:56 +0000994 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000995
996 // Create the "release" selector.
997 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +0000998 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +0000999
1000 // Create the "drain" selector.
1001 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001002 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001003
1004 // Create the "autorelease" selector.
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00001005 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001006 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001007
Ted Kremenek45642a42008-08-12 18:48:50 +00001008 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremeneke44927e2008-07-01 17:21:27 +00001009 RetainSummary *NSWindowSumm =
1010 getPersistentSummary(RetEffect::MakeReceiverAlias(), SelfOwn);
Ted Kremenek45642a42008-08-12 18:48:50 +00001011
1012 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1013 "styleMask", "backing", "defer", NULL);
1014
1015 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1016 "styleMask", "backing", "defer", "screen", NULL);
1017
1018 // For NSPanel (which subclasses NSWindow), allocated objects are not
1019 // self-owned.
1020 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1021 "styleMask", "backing", "defer", NULL);
1022
1023 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1024 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001025
Ted Kremenekf2717b02008-07-18 17:24:20 +00001026 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001027 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1028 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001029
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001030 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1031 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001032}
1033
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001034//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001035// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001036//===----------------------------------------------------------------------===//
1037
Ted Kremeneka7338b42008-03-11 06:39:11 +00001038namespace {
1039
Ted Kremenek7d421f32008-04-09 23:49:11 +00001040class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001041public:
Ted Kremenek0d721572008-03-11 17:48:22 +00001042
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001043 enum Kind {
1044 Owned = 0, // Owning reference.
1045 NotOwned, // Reference is not owned by still valid (not freed).
1046 Released, // Object has been released.
1047 ReturnedOwned, // Returned object passes ownership to caller.
1048 ReturnedNotOwned, // Return object does not pass ownership to caller.
1049 ErrorUseAfterRelease, // Object used after released.
1050 ErrorReleaseNotOwned, // Release of an object that was not owned.
1051 ErrorLeak // A memory leak due to excessive reference counts.
1052 };
Ted Kremenek0d721572008-03-11 17:48:22 +00001053
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001054private:
1055
1056 Kind kind;
1057 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001058 QualType T;
1059
1060 RefVal(Kind k, unsigned cnt, QualType t) : kind(k), Cnt(cnt), T(t) {}
1061 RefVal(Kind k, unsigned cnt = 0) : kind(k), Cnt(cnt) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001062
1063public:
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001064
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001065 Kind getKind() const { return kind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001066
Ted Kremenek272aa852008-06-25 21:21:56 +00001067 unsigned getCount() const { return Cnt; }
1068 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001069
1070 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001071
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001072 static bool isError(Kind k) { return k >= ErrorUseAfterRelease; }
1073
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001074 static bool isLeak(Kind k) { return k == ErrorLeak; }
1075
Ted Kremenekffefc352008-04-11 22:25:11 +00001076 bool isOwned() const {
1077 return getKind() == Owned;
1078 }
1079
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001080 bool isNotOwned() const {
1081 return getKind() == NotOwned;
1082 }
1083
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001084 bool isReturnedOwned() const {
1085 return getKind() == ReturnedOwned;
1086 }
1087
1088 bool isReturnedNotOwned() const {
1089 return getKind() == ReturnedNotOwned;
1090 }
1091
1092 bool isNonLeakError() const {
1093 Kind k = getKind();
1094 return isError(k) && !isLeak(k);
1095 }
1096
1097 // State creation: normal state.
1098
Ted Kremenek272aa852008-06-25 21:21:56 +00001099 static RefVal makeOwned(QualType t, unsigned Count = 1) {
1100 return RefVal(Owned, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001101 }
1102
Ted Kremenek272aa852008-06-25 21:21:56 +00001103 static RefVal makeNotOwned(QualType t, unsigned Count = 0) {
1104 return RefVal(NotOwned, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001105 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001106
1107 static RefVal makeReturnedOwned(unsigned Count) {
1108 return RefVal(ReturnedOwned, Count);
1109 }
1110
1111 static RefVal makeReturnedNotOwned() {
1112 return RefVal(ReturnedNotOwned);
1113 }
1114
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001115 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001116
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001117 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001118 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001119 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001120
Ted Kremenek272aa852008-06-25 21:21:56 +00001121 RefVal operator-(size_t i) const {
1122 return RefVal(getKind(), getCount() - i, getType());
1123 }
1124
1125 RefVal operator+(size_t i) const {
1126 return RefVal(getKind(), getCount() + i, getType());
1127 }
1128
1129 RefVal operator^(Kind k) const {
1130 return RefVal(k, getCount(), getType());
1131 }
1132
1133
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001134 void Profile(llvm::FoldingSetNodeID& ID) const {
1135 ID.AddInteger((unsigned) kind);
1136 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001137 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001138 }
1139
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001140 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001141};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001142
1143void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001144 if (!T.isNull())
1145 Out << "Tracked Type:" << T.getAsString() << '\n';
1146
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001147 switch (getKind()) {
1148 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001149 case Owned: {
1150 Out << "Owned";
1151 unsigned cnt = getCount();
1152 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001153 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001154 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001155
Ted Kremenekc4f81022008-04-10 23:09:18 +00001156 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001157 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001158 unsigned cnt = getCount();
1159 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001160 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001161 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001162
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001163 case ReturnedOwned: {
1164 Out << "ReturnedOwned";
1165 unsigned cnt = getCount();
1166 if (cnt) Out << " (+ " << cnt << ")";
1167 break;
1168 }
1169
1170 case ReturnedNotOwned: {
1171 Out << "ReturnedNotOwned";
1172 unsigned cnt = getCount();
1173 if (cnt) Out << " (+ " << cnt << ")";
1174 break;
1175 }
1176
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001177 case Released:
1178 Out << "Released";
1179 break;
1180
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001181 case ErrorLeak:
1182 Out << "Leaked";
1183 break;
1184
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001185 case ErrorUseAfterRelease:
1186 Out << "Use-After-Release [ERROR]";
1187 break;
1188
1189 case ErrorReleaseNotOwned:
1190 Out << "Release of Not-Owned [ERROR]";
1191 break;
1192 }
1193}
Ted Kremenek0d721572008-03-11 17:48:22 +00001194
Ted Kremenek7aef4842008-04-16 20:40:59 +00001195//===----------------------------------------------------------------------===//
1196// Transfer functions.
1197//===----------------------------------------------------------------------===//
1198
Ted Kremenek7d421f32008-04-09 23:49:11 +00001199class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001200public:
Ted Kremenek272aa852008-06-25 21:21:56 +00001201 // Type definitions.
Ted Kremenek0d721572008-03-11 17:48:22 +00001202 typedef llvm::ImmutableMap<SymbolID, RefVal> RefBindings;
Ted Kremenek272aa852008-06-25 21:21:56 +00001203
Ted Kremeneka7338b42008-03-11 06:39:11 +00001204 typedef RefBindings::Factory RefBFactoryTy;
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001205
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001206 typedef llvm::DenseMap<GRExprEngine::NodeTy*,std::pair<Expr*, SymbolID> >
1207 ReleasesNotOwnedTy;
1208
1209 typedef ReleasesNotOwnedTy UseAfterReleasesTy;
1210
1211 typedef llvm::DenseMap<GRExprEngine::NodeTy*, std::vector<SymbolID>*>
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001212 LeaksTy;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001213
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001214 class BindingsPrinter : public ValueState::CheckerStatePrinter {
1215 public:
1216 virtual void PrintCheckerState(std::ostream& Out, void* State,
1217 const char* nl, const char* sep);
1218 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001219
1220private:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001221 RetainSummaryManager Summaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001222 const LangOptions& LOpts;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001223 RefBFactoryTy RefBFactory;
1224 UseAfterReleasesTy UseAfterReleases;
1225 ReleasesNotOwnedTy ReleasesNotOwned;
1226 LeaksTy Leaks;
1227 BindingsPrinter Printer;
Ted Kremenek1feab292008-04-16 04:28:53 +00001228
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001229public:
1230
Ted Kremenekf22f8682008-07-10 22:03:41 +00001231 static RefBindings GetRefBindings(const ValueState& StImpl) {
1232 return RefBindings((const RefBindings::TreeTy*) StImpl.CheckerState);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001233 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001234
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001235private:
1236
Ted Kremeneka7338b42008-03-11 06:39:11 +00001237 static void SetRefBindings(ValueState& StImpl, RefBindings B) {
1238 StImpl.CheckerState = B.getRoot();
1239 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001240
Ted Kremeneka7338b42008-03-11 06:39:11 +00001241 RefBindings Remove(RefBindings B, SymbolID sym) {
1242 return RefBFactory.Remove(B, sym);
1243 }
1244
Ted Kremenek0d721572008-03-11 17:48:22 +00001245 RefBindings Update(RefBindings B, SymbolID sym, RefVal V, ArgEffect E,
Ted Kremenek1feab292008-04-16 04:28:53 +00001246 RefVal::Kind& hasErr);
1247
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001248 void ProcessNonLeakError(ExplodedNodeSet<ValueState>& Dst,
1249 GRStmtNodeBuilder<ValueState>& Builder,
1250 Expr* NodeExpr, Expr* ErrorExpr,
1251 ExplodedNode<ValueState>* Pred,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001252 const ValueState* St,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001253 RefVal::Kind hasErr, SymbolID Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001254
Ted Kremenekf22f8682008-07-10 22:03:41 +00001255 const ValueState* HandleSymbolDeath(ValueStateManager& VMgr,
1256 const ValueState* St,
1257 SymbolID sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001258
Ted Kremenekf22f8682008-07-10 22:03:41 +00001259 const ValueState* NukeBinding(ValueStateManager& VMgr, const ValueState* St,
1260 SymbolID sid);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001261
1262public:
Ted Kremenek7aef4842008-04-16 20:40:59 +00001263
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001264 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001265 : Summaries(Ctx, gcenabled),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001266 LOpts(lopts) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001267
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001268 virtual ~CFRefCount() {
1269 for (LeaksTy::iterator I = Leaks.begin(), E = Leaks.end(); I!=E; ++I)
1270 delete I->second;
1271 }
Ted Kremenek7d421f32008-04-09 23:49:11 +00001272
1273 virtual void RegisterChecks(GRExprEngine& Eng);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001274
1275 virtual ValueState::CheckerStatePrinter* getCheckerStatePrinter() {
1276 return &Printer;
1277 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001278
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001279 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001280 const LangOptions& getLangOptions() const { return LOpts; }
1281
Ted Kremeneka7338b42008-03-11 06:39:11 +00001282 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001283
1284 void EvalSummary(ExplodedNodeSet<ValueState>& Dst,
1285 GRExprEngine& Eng,
1286 GRStmtNodeBuilder<ValueState>& Builder,
1287 Expr* Ex,
1288 Expr* Receiver,
1289 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001290 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001291 ExplodedNode<ValueState>* Pred);
1292
Ted Kremeneka7338b42008-03-11 06:39:11 +00001293 virtual void EvalCall(ExplodedNodeSet<ValueState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001294 GRExprEngine& Eng,
Ted Kremeneka7338b42008-03-11 06:39:11 +00001295 GRStmtNodeBuilder<ValueState>& Builder,
Ted Kremenek0a6a80b2008-04-23 20:12:28 +00001296 CallExpr* CE, RVal L,
Ted Kremeneka7338b42008-03-11 06:39:11 +00001297 ExplodedNode<ValueState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001298
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001299
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001300 virtual void EvalObjCMessageExpr(ExplodedNodeSet<ValueState>& Dst,
1301 GRExprEngine& Engine,
1302 GRStmtNodeBuilder<ValueState>& Builder,
1303 ObjCMessageExpr* ME,
1304 ExplodedNode<ValueState>* Pred);
1305
1306 bool EvalObjCMessageExprAux(ExplodedNodeSet<ValueState>& Dst,
1307 GRExprEngine& Engine,
1308 GRStmtNodeBuilder<ValueState>& Builder,
1309 ObjCMessageExpr* ME,
1310 ExplodedNode<ValueState>* Pred);
1311
Ted Kremenek7aef4842008-04-16 20:40:59 +00001312 // Stores.
1313
1314 virtual void EvalStore(ExplodedNodeSet<ValueState>& Dst,
1315 GRExprEngine& Engine,
1316 GRStmtNodeBuilder<ValueState>& Builder,
1317 Expr* E, ExplodedNode<ValueState>* Pred,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001318 const ValueState* St, RVal TargetLV, RVal Val);
Ted Kremenekffefc352008-04-11 22:25:11 +00001319 // End-of-path.
1320
1321 virtual void EvalEndPath(GRExprEngine& Engine,
1322 GREndPathNodeBuilder<ValueState>& Builder);
1323
Ted Kremenek541db372008-04-24 23:57:27 +00001324 virtual void EvalDeadSymbols(ExplodedNodeSet<ValueState>& Dst,
1325 GRExprEngine& Engine,
1326 GRStmtNodeBuilder<ValueState>& Builder,
Ted Kremenekac91ce92008-04-25 01:25:15 +00001327 ExplodedNode<ValueState>* Pred,
1328 Stmt* S,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001329 const ValueState* St,
Ted Kremenek541db372008-04-24 23:57:27 +00001330 const ValueStateManager::DeadSymbolsTy& Dead);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001331 // Return statements.
1332
1333 virtual void EvalReturn(ExplodedNodeSet<ValueState>& Dst,
1334 GRExprEngine& Engine,
1335 GRStmtNodeBuilder<ValueState>& Builder,
1336 ReturnStmt* S,
1337 ExplodedNode<ValueState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001338
1339 // Assumptions.
1340
Ted Kremenek76d31662008-07-17 23:33:10 +00001341 virtual const ValueState* EvalAssume(ValueStateManager& VMgr,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001342 const ValueState* St, RVal Cond,
1343 bool Assumption, bool& isFeasible);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001344
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001345 // Error iterators.
1346
1347 typedef UseAfterReleasesTy::iterator use_after_iterator;
1348 typedef ReleasesNotOwnedTy::iterator bad_release_iterator;
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00001349 typedef LeaksTy::iterator leaks_iterator;
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001350
Ted Kremenek7d421f32008-04-09 23:49:11 +00001351 use_after_iterator use_after_begin() { return UseAfterReleases.begin(); }
1352 use_after_iterator use_after_end() { return UseAfterReleases.end(); }
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001353
Ted Kremenek7d421f32008-04-09 23:49:11 +00001354 bad_release_iterator bad_release_begin() { return ReleasesNotOwned.begin(); }
1355 bad_release_iterator bad_release_end() { return ReleasesNotOwned.end(); }
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00001356
1357 leaks_iterator leaks_begin() { return Leaks.begin(); }
1358 leaks_iterator leaks_end() { return Leaks.end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001359};
1360
1361} // end anonymous namespace
1362
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001363
Ted Kremenek7d421f32008-04-09 23:49:11 +00001364
1365
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001366void CFRefCount::BindingsPrinter::PrintCheckerState(std::ostream& Out,
1367 void* State, const char* nl,
1368 const char* sep) {
1369 RefBindings B((RefBindings::TreeTy*) State);
1370
1371 if (State)
1372 Out << sep << nl;
1373
1374 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1375 Out << (*I).first << " : ";
1376 (*I).second.print(Out);
1377 Out << nl;
1378 }
1379}
1380
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001381static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001382 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenek455dd862008-04-11 20:23:24 +00001383}
1384
Ted Kremenek266d8b62008-05-06 02:26:56 +00001385static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1386 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenek455dd862008-04-11 20:23:24 +00001387}
1388
Ted Kremenek227c5372008-05-06 02:41:27 +00001389static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1390 return Summ ? Summ->getReceiverEffect() : DoNothing;
1391}
1392
Ted Kremenekf2717b02008-07-18 17:24:20 +00001393static inline bool IsEndPath(RetainSummary* Summ) {
1394 return Summ ? Summ->isEndPath() : false;
1395}
1396
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001397void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<ValueState>& Dst,
1398 GRStmtNodeBuilder<ValueState>& Builder,
1399 Expr* NodeExpr, Expr* ErrorExpr,
1400 ExplodedNode<ValueState>* Pred,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001401 const ValueState* St,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001402 RefVal::Kind hasErr, SymbolID Sym) {
Ted Kremenek1feab292008-04-16 04:28:53 +00001403 Builder.BuildSinks = true;
1404 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
1405
1406 if (!N) return;
1407
1408 switch (hasErr) {
1409 default: assert(false);
1410 case RefVal::ErrorUseAfterRelease:
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001411 UseAfterReleases[N] = std::make_pair(ErrorExpr, Sym);
Ted Kremenek1feab292008-04-16 04:28:53 +00001412 break;
1413
1414 case RefVal::ErrorReleaseNotOwned:
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001415 ReleasesNotOwned[N] = std::make_pair(ErrorExpr, Sym);
Ted Kremenek1feab292008-04-16 04:28:53 +00001416 break;
1417 }
1418}
1419
Ted Kremenek272aa852008-06-25 21:21:56 +00001420/// GetReturnType - Used to get the return type of a message expression or
1421/// function call with the intention of affixing that type to a tracked symbol.
1422/// While the the return type can be queried directly from RetEx, when
1423/// invoking class methods we augment to the return type to be that of
1424/// a pointer to the class (as opposed it just being id).
1425static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1426
1427 QualType RetTy = RetE->getType();
1428
1429 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00001430 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001431 if (!PT)
1432 return RetTy;
1433
1434 // If RetEx is not a message expression just return its type.
1435 // If RetEx is a message expression, return its types if it is something
1436 /// more specific than id.
1437
1438 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1439
1440 if (!ME || !Ctx.isObjCIdType(PT->getPointeeType()))
1441 return RetTy;
1442
1443 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1444
1445 // At this point we know the return type of the message expression is id.
1446 // If we have an ObjCInterceDecl, we know this is a call to a class method
1447 // whose type we can resolve. In such cases, promote the return type to
1448 // Class*.
1449 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1450}
1451
1452
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001453void CFRefCount::EvalSummary(ExplodedNodeSet<ValueState>& Dst,
1454 GRExprEngine& Eng,
1455 GRStmtNodeBuilder<ValueState>& Builder,
1456 Expr* Ex,
1457 Expr* Receiver,
1458 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001459 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001460 ExplodedNode<ValueState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001461
Ted Kremeneka7338b42008-03-11 06:39:11 +00001462 // Get the state.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001463 ValueStateManager& StateMgr = Eng.getStateManager();
Ted Kremenekf22f8682008-07-10 22:03:41 +00001464 const ValueState* St = Builder.GetState(Pred);
Ted Kremenek227c5372008-05-06 02:41:27 +00001465
1466 // Evaluate the effect of the arguments.
Ted Kremeneka7338b42008-03-11 06:39:11 +00001467 ValueState StVals = *St;
Ted Kremenek1feab292008-04-16 04:28:53 +00001468 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001469 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001470 Expr* ErrorExpr = NULL;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001471 SymbolID ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001472
Ted Kremenek2719e982008-06-17 02:43:46 +00001473 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremeneka7338b42008-03-11 06:39:11 +00001474
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001475 RVal V = StateMgr.GetRVal(St, *I);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001476
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001477 if (isa<lval::SymbolVal>(V)) {
1478 SymbolID Sym = cast<lval::SymbolVal>(V).getSymbol();
Ted Kremenek455dd862008-04-11 20:23:24 +00001479 RefBindings B = GetRefBindings(StVals);
1480
Ted Kremenek6064a362008-07-07 16:21:19 +00001481 if (RefBindings::data_type* T = B.lookup(Sym)) {
1482 B = Update(B, Sym, *T, GetArgE(Summ, idx), hasErr);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001483 SetRefBindings(StVals, B);
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001484
Ted Kremenek1feab292008-04-16 04:28:53 +00001485 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001486 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00001487 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001488 break;
1489 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001490 }
Ted Kremeneke4924202008-04-11 20:51:02 +00001491 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001492 else if (isa<LVal>(V)) {
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001493#if 0
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001494 // Nuke all arguments passed by reference.
Ted Kremenek455dd862008-04-11 20:23:24 +00001495 StateMgr.Unbind(StVals, cast<LVal>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001496#else
Ted Kremenekede40b72008-07-09 18:11:16 +00001497 if (lval::DeclVal* DV = dyn_cast<lval::DeclVal>(&V)) {
1498
1499 if (GetArgE(Summ, idx) == DoNothingByRef)
1500 continue;
1501
1502 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001503
1504 // FIXME: Either this logic should also be replicated in GRSimpleVals
1505 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00001506
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001507 // FIXME: We can have collisions on the conjured symbol if the
1508 // expression *I also creates conjured symbols. We probably want
1509 // to identify conjured symbols by an expression pair: the enclosing
1510 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00001511 // disambiguate conjured symbols.
1512
1513 // Is the invalidated variable something that we were tracking?
1514 RVal X = StateMgr.GetRVal(&StVals, *DV);
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001515
Ted Kremenekede40b72008-07-09 18:11:16 +00001516 if (isa<lval::SymbolVal>(X)) {
1517 SymbolID Sym = cast<lval::SymbolVal>(X).getSymbol();
1518 SetRefBindings(StVals,RefBFactory.Remove(GetRefBindings(StVals),Sym));
1519 }
1520
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001521 // Set the value of the variable to be a conjured symbol.
1522 unsigned Count = Builder.getCurrentBlockCount();
1523 SymbolID NewSym = Eng.getSymbolManager().getConjuredSymbol(*I, Count);
1524
Ted Kremenekf22f8682008-07-10 22:03:41 +00001525 StateMgr.SetRVal(StVals, *DV,
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001526 LVal::IsLValType(DV->getDecl()->getType())
1527 ? cast<RVal>(lval::SymbolVal(NewSym))
1528 : cast<RVal>(nonlval::SymbolVal(NewSym)));
1529 }
1530 else {
1531 // Nuke all other arguments passed by reference.
1532 StateMgr.Unbind(StVals, cast<LVal>(V));
1533 }
1534#endif
Ted Kremeneke4924202008-04-11 20:51:02 +00001535 }
Ted Kremenekbe621292008-04-22 21:39:21 +00001536 else if (isa<nonlval::LValAsInteger>(V))
1537 StateMgr.Unbind(StVals, cast<nonlval::LValAsInteger>(V).getLVal());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001538 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001539
Ted Kremenek272aa852008-06-25 21:21:56 +00001540 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00001541 if (!ErrorExpr && Receiver) {
1542 RVal V = StateMgr.GetRVal(St, Receiver);
1543
1544 if (isa<lval::SymbolVal>(V)) {
1545 SymbolID Sym = cast<lval::SymbolVal>(V).getSymbol();
1546 RefBindings B = GetRefBindings(StVals);
1547
Ted Kremenek6064a362008-07-07 16:21:19 +00001548 if (const RefVal* T = B.lookup(Sym)) {
1549 B = Update(B, Sym, *T, GetReceiverE(Summ), hasErr);
Ted Kremenek227c5372008-05-06 02:41:27 +00001550 SetRefBindings(StVals, B);
1551
1552 if (hasErr) {
1553 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00001554 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00001555 }
1556 }
1557 }
1558 }
1559
Ted Kremenek272aa852008-06-25 21:21:56 +00001560 // Get the persistent state.
Ted Kremenek1feab292008-04-16 04:28:53 +00001561 St = StateMgr.getPersistentState(StVals);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001562
Ted Kremenek272aa852008-06-25 21:21:56 +00001563 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00001564 if (hasErr) {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001565 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, St,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001566 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001567 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00001568 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001569
Ted Kremenekf2717b02008-07-18 17:24:20 +00001570 // Consult the summary for the return value.
Ted Kremenek266d8b62008-05-06 02:26:56 +00001571 RetEffect RE = GetRetEffect(Summ);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001572
1573 switch (RE.getKind()) {
1574 default:
1575 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001576
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001577 case RetEffect::NoRet:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001578
Ted Kremenek455dd862008-04-11 20:23:24 +00001579 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00001580 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
1581 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00001582
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001583 if (Ex->getType() != Eng.getContext().VoidTy) {
Ted Kremenek455dd862008-04-11 20:23:24 +00001584 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001585 SymbolID Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek455dd862008-04-11 20:23:24 +00001586
Ted Kremenek9e2c1ea2008-05-09 23:45:33 +00001587 RVal X = LVal::IsLValType(Ex->getType())
1588 ? cast<RVal>(lval::SymbolVal(Sym))
1589 : cast<RVal>(nonlval::SymbolVal(Sym));
Ted Kremenek455dd862008-04-11 20:23:24 +00001590
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001591 St = StateMgr.SetRVal(St, Ex, X, Eng.getCFG().isBlkExpr(Ex), false);
Ted Kremenek455dd862008-04-11 20:23:24 +00001592 }
1593
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001594 break;
1595
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001596 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00001597 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00001598 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001599 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenek2719e982008-06-17 02:43:46 +00001600 RVal V = StateMgr.GetRVal(St, *(arg_beg+idx));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001601 St = StateMgr.SetRVal(St, Ex, V, Eng.getCFG().isBlkExpr(Ex), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001602 break;
1603 }
1604
Ted Kremenek227c5372008-05-06 02:41:27 +00001605 case RetEffect::ReceiverAlias: {
1606 assert (Receiver);
1607 RVal V = StateMgr.GetRVal(St, Receiver);
1608 St = StateMgr.SetRVal(St, Ex, V, Eng.getCFG().isBlkExpr(Ex), false);
1609 break;
1610 }
1611
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001612 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001613 case RetEffect::OwnedSymbol: {
1614 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001615 SymbolID Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek272aa852008-06-25 21:21:56 +00001616 QualType RetT = GetReturnType(Ex, Eng.getContext());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001617
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001618 ValueState StImpl = *St;
1619 RefBindings B = GetRefBindings(StImpl);
Ted Kremenek272aa852008-06-25 21:21:56 +00001620 SetRefBindings(StImpl, RefBFactory.Add(B, Sym, RefVal::makeOwned(RetT)));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001621
1622 St = StateMgr.SetRVal(StateMgr.getPersistentState(StImpl),
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001623 Ex, lval::SymbolVal(Sym),
1624 Eng.getCFG().isBlkExpr(Ex), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001625
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001626 // FIXME: Add a flag to the checker where allocations are allowed to fail.
1627 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol)
1628 St = StateMgr.AddNE(St, Sym, Eng.getBasicVals().getZeroWithPtrWidth());
1629
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001630 break;
1631 }
1632
1633 case RetEffect::NotOwnedSymbol: {
1634 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001635 SymbolID Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek272aa852008-06-25 21:21:56 +00001636 QualType RetT = GetReturnType(Ex, Eng.getContext());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001637
1638 ValueState StImpl = *St;
1639 RefBindings B = GetRefBindings(StImpl);
Ted Kremenek272aa852008-06-25 21:21:56 +00001640 SetRefBindings(StImpl, RefBFactory.Add(B, Sym,
1641 RefVal::makeNotOwned(RetT)));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001642
1643 St = StateMgr.SetRVal(StateMgr.getPersistentState(StImpl),
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001644 Ex, lval::SymbolVal(Sym),
1645 Eng.getCFG().isBlkExpr(Ex), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001646
1647 break;
1648 }
1649 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001650
Ted Kremenekf2717b02008-07-18 17:24:20 +00001651 // Is this a sink?
1652 if (IsEndPath(Summ))
1653 Builder.MakeSinkNode(Dst, Ex, Pred, St);
1654 else
1655 Builder.MakeNode(Dst, Ex, Pred, St);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001656}
1657
1658
1659void CFRefCount::EvalCall(ExplodedNodeSet<ValueState>& Dst,
1660 GRExprEngine& Eng,
1661 GRStmtNodeBuilder<ValueState>& Builder,
1662 CallExpr* CE, RVal L,
1663 ExplodedNode<ValueState>* Pred) {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001664
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001665 RetainSummary* Summ = !isa<lval::FuncVal>(L) ? 0
1666 : Summaries.getSummary(cast<lval::FuncVal>(L).getDecl());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001667
1668 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
1669 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00001670}
Ted Kremeneka7338b42008-03-11 06:39:11 +00001671
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001672void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<ValueState>& Dst,
1673 GRExprEngine& Eng,
1674 GRStmtNodeBuilder<ValueState>& Builder,
1675 ObjCMessageExpr* ME,
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001676 ExplodedNode<ValueState>* Pred) {
Ted Kremenek926abf22008-05-06 04:20:12 +00001677 RetainSummary* Summ;
Ted Kremenek33661802008-05-01 21:31:50 +00001678
Ted Kremenek272aa852008-06-25 21:21:56 +00001679 if (Expr* Receiver = ME->getReceiver()) {
1680 // We need the type-information of the tracked receiver object
1681 // Retrieve it from the state.
1682 ObjCInterfaceDecl* ID = 0;
1683
1684 // FIXME: Wouldn't it be great if this code could be reduced? It's just
1685 // a chain of lookups.
Ted Kremenekf22f8682008-07-10 22:03:41 +00001686 const ValueState* St = Builder.GetState(Pred);
Ted Kremenek272aa852008-06-25 21:21:56 +00001687 RVal V = Eng.getStateManager().GetRVal(St, Receiver );
1688
1689 if (isa<lval::SymbolVal>(V)) {
1690 SymbolID Sym = cast<lval::SymbolVal>(V).getSymbol();
1691
Ted Kremenek6064a362008-07-07 16:21:19 +00001692 if (const RefVal* T = GetRefBindings(*St).lookup(Sym)) {
1693 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001694
1695 if (const PointerType* PT = Ty->getAsPointerType()) {
1696 QualType PointeeTy = PT->getPointeeType();
1697
1698 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
1699 ID = IT->getDecl();
1700 }
1701 }
1702 }
1703
1704 Summ = Summaries.getMethodSummary(ME, ID);
1705 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001706 else
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001707 Summ = Summaries.getClassMethodSummary(ME->getClassName(),
1708 ME->getSelector());
Ted Kremenek1feab292008-04-16 04:28:53 +00001709
Ted Kremenek926abf22008-05-06 04:20:12 +00001710 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
1711 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001712}
Ted Kremenek926abf22008-05-06 04:20:12 +00001713
Ted Kremenek7aef4842008-04-16 20:40:59 +00001714// Stores.
1715
1716void CFRefCount::EvalStore(ExplodedNodeSet<ValueState>& Dst,
1717 GRExprEngine& Eng,
1718 GRStmtNodeBuilder<ValueState>& Builder,
1719 Expr* E, ExplodedNode<ValueState>* Pred,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001720 const ValueState* St, RVal TargetLV, RVal Val) {
Ted Kremenek7aef4842008-04-16 20:40:59 +00001721
1722 // Check if we have a binding for "Val" and if we are storing it to something
1723 // we don't understand or otherwise the value "escapes" the function.
1724
1725 if (!isa<lval::SymbolVal>(Val))
1726 return;
1727
1728 // Are we storing to something that causes the value to "escape"?
1729
1730 bool escapes = false;
1731
1732 if (!isa<lval::DeclVal>(TargetLV))
1733 escapes = true;
1734 else
1735 escapes = cast<lval::DeclVal>(TargetLV).getDecl()->hasGlobalStorage();
1736
1737 if (!escapes)
1738 return;
1739
1740 SymbolID Sym = cast<lval::SymbolVal>(Val).getSymbol();
Ted Kremenek7aef4842008-04-16 20:40:59 +00001741
Ted Kremenek6064a362008-07-07 16:21:19 +00001742 if (!GetRefBindings(*St).lookup(Sym))
Ted Kremenek7aef4842008-04-16 20:40:59 +00001743 return;
1744
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001745 // Nuke the binding.
1746 St = NukeBinding(Eng.getStateManager(), St, Sym);
Ted Kremenek7aef4842008-04-16 20:40:59 +00001747
1748 // Hand of the remaining logic to the parent implementation.
1749 GRSimpleVals::EvalStore(Dst, Eng, Builder, E, Pred, St, TargetLV, Val);
1750}
1751
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001752
Ted Kremenekf22f8682008-07-10 22:03:41 +00001753const ValueState* CFRefCount::NukeBinding(ValueStateManager& VMgr,
1754 const ValueState* St,
1755 SymbolID sid) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001756 ValueState StImpl = *St;
1757 RefBindings B = GetRefBindings(StImpl);
1758 StImpl.CheckerState = RefBFactory.Remove(B, sid).getRoot();
1759 return VMgr.getPersistentState(StImpl);
1760}
1761
Ted Kremenekffefc352008-04-11 22:25:11 +00001762// End-of-path.
1763
Ted Kremenekf22f8682008-07-10 22:03:41 +00001764const ValueState* CFRefCount::HandleSymbolDeath(ValueStateManager& VMgr,
1765 const ValueState* St, SymbolID sid,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001766 RefVal V, bool& hasLeak) {
1767
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001768 hasLeak = V.isOwned() ||
1769 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001770
1771 if (!hasLeak)
1772 return NukeBinding(VMgr, St, sid);
1773
1774 RefBindings B = GetRefBindings(*St);
Ted Kremenek272aa852008-06-25 21:21:56 +00001775 ValueState StImpl = *St;
1776 StImpl.CheckerState = RefBFactory.Add(B, sid, V^RefVal::ErrorLeak).getRoot();
Ted Kremenek9363fd92008-05-05 17:53:17 +00001777
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001778 return VMgr.getPersistentState(StImpl);
1779}
1780
1781void CFRefCount::EvalEndPath(GRExprEngine& Eng,
Ted Kremenekffefc352008-04-11 22:25:11 +00001782 GREndPathNodeBuilder<ValueState>& Builder) {
1783
Ted Kremenekf22f8682008-07-10 22:03:41 +00001784 const ValueState* St = Builder.getState();
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001785 RefBindings B = GetRefBindings(*St);
Ted Kremenekffefc352008-04-11 22:25:11 +00001786
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001787 llvm::SmallVector<SymbolID, 10> Leaked;
Ted Kremenekffefc352008-04-11 22:25:11 +00001788
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001789 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
1790 bool hasLeak = false;
Ted Kremenekffefc352008-04-11 22:25:11 +00001791
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001792 St = HandleSymbolDeath(Eng.getStateManager(), St,
1793 (*I).first, (*I).second, hasLeak);
1794
1795 if (hasLeak) Leaked.push_back((*I).first);
1796 }
Ted Kremenek541db372008-04-24 23:57:27 +00001797
1798 if (Leaked.empty())
1799 return;
1800
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001801 ExplodedNode<ValueState>* N = Builder.MakeNode(St);
Ted Kremenekcfc909d2008-04-18 16:30:14 +00001802
Ted Kremenek541db372008-04-24 23:57:27 +00001803 if (!N)
Ted Kremenekcfc909d2008-04-18 16:30:14 +00001804 return;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001805
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001806 std::vector<SymbolID>*& LeaksAtNode = Leaks[N];
1807 assert (!LeaksAtNode);
1808 LeaksAtNode = new std::vector<SymbolID>();
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001809
1810 for (llvm::SmallVector<SymbolID, 10>::iterator I=Leaked.begin(),
1811 E = Leaked.end(); I != E; ++I)
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001812 (*LeaksAtNode).push_back(*I);
Ted Kremenekffefc352008-04-11 22:25:11 +00001813}
1814
Ted Kremenek541db372008-04-24 23:57:27 +00001815// Dead symbols.
1816
1817void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<ValueState>& Dst,
1818 GRExprEngine& Eng,
1819 GRStmtNodeBuilder<ValueState>& Builder,
Ted Kremenekac91ce92008-04-25 01:25:15 +00001820 ExplodedNode<ValueState>* Pred,
1821 Stmt* S,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001822 const ValueState* St,
Ted Kremenek541db372008-04-24 23:57:27 +00001823 const ValueStateManager::DeadSymbolsTy& Dead) {
Ted Kremenekac91ce92008-04-25 01:25:15 +00001824
Ted Kremenek541db372008-04-24 23:57:27 +00001825 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
1826
1827 RefBindings B = GetRefBindings(*St);
1828 llvm::SmallVector<SymbolID, 10> Leaked;
1829
1830 for (ValueStateManager::DeadSymbolsTy::const_iterator
1831 I=Dead.begin(), E=Dead.end(); I!=E; ++I) {
1832
Ted Kremenek6064a362008-07-07 16:21:19 +00001833 const RefVal* T = B.lookup(*I);
Ted Kremenek541db372008-04-24 23:57:27 +00001834
1835 if (!T)
1836 continue;
1837
1838 bool hasLeak = false;
1839
Ted Kremenek6064a362008-07-07 16:21:19 +00001840 St = HandleSymbolDeath(Eng.getStateManager(), St, *I, *T, hasLeak);
Ted Kremenek541db372008-04-24 23:57:27 +00001841
Ted Kremenek6064a362008-07-07 16:21:19 +00001842 if (hasLeak)
1843 Leaked.push_back(*I);
Ted Kremenek541db372008-04-24 23:57:27 +00001844 }
1845
1846 if (Leaked.empty())
1847 return;
1848
1849 ExplodedNode<ValueState>* N = Builder.MakeNode(Dst, S, Pred, St);
1850
1851 if (!N)
1852 return;
1853
1854 std::vector<SymbolID>*& LeaksAtNode = Leaks[N];
1855 assert (!LeaksAtNode);
1856 LeaksAtNode = new std::vector<SymbolID>();
1857
1858 for (llvm::SmallVector<SymbolID, 10>::iterator I=Leaked.begin(),
1859 E = Leaked.end(); I != E; ++I)
1860 (*LeaksAtNode).push_back(*I);
1861}
1862
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001863 // Return statements.
1864
1865void CFRefCount::EvalReturn(ExplodedNodeSet<ValueState>& Dst,
1866 GRExprEngine& Eng,
1867 GRStmtNodeBuilder<ValueState>& Builder,
1868 ReturnStmt* S,
1869 ExplodedNode<ValueState>* Pred) {
1870
1871 Expr* RetE = S->getRetValue();
1872 if (!RetE) return;
1873
1874 ValueStateManager& StateMgr = Eng.getStateManager();
Ted Kremenekf22f8682008-07-10 22:03:41 +00001875 const ValueState* St = Builder.GetState(Pred);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001876 RVal V = StateMgr.GetRVal(St, RetE);
1877
1878 if (!isa<lval::SymbolVal>(V))
1879 return;
1880
1881 // Get the reference count binding (if any).
1882 SymbolID Sym = cast<lval::SymbolVal>(V).getSymbol();
1883 RefBindings B = GetRefBindings(*St);
Ted Kremenek6064a362008-07-07 16:21:19 +00001884 const RefVal* T = B.lookup(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001885
1886 if (!T)
1887 return;
1888
1889 // Change the reference count.
1890
Ted Kremenek6064a362008-07-07 16:21:19 +00001891 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001892
1893 switch (X.getKind()) {
1894
1895 case RefVal::Owned: {
1896 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001897 assert (cnt > 0);
1898 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001899 break;
1900 }
1901
1902 case RefVal::NotOwned: {
1903 unsigned cnt = X.getCount();
1904 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
1905 : RefVal::makeReturnedNotOwned();
1906 break;
1907 }
1908
1909 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001910 return;
1911 }
1912
1913 // Update the binding.
1914
1915 ValueState StImpl = *St;
1916 StImpl.CheckerState = RefBFactory.Add(B, Sym, X).getRoot();
1917 Builder.MakeNode(Dst, S, Pred, StateMgr.getPersistentState(StImpl));
1918}
1919
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001920// Assumptions.
1921
Ted Kremenek76d31662008-07-17 23:33:10 +00001922const ValueState* CFRefCount::EvalAssume(ValueStateManager& VMgr,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001923 const ValueState* St,
1924 RVal Cond, bool Assumption,
1925 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001926
1927 // FIXME: We may add to the interface of EvalAssume the list of symbols
1928 // whose assumptions have changed. For now we just iterate through the
1929 // bindings and check if any of the tracked symbols are NULL. This isn't
1930 // too bad since the number of symbols we will track in practice are
1931 // probably small and EvalAssume is only called at branches and a few
1932 // other places.
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001933 RefBindings B = GetRefBindings(*St);
1934
1935 if (B.isEmpty())
1936 return St;
1937
1938 bool changed = false;
1939
1940 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001941 // Check if the symbol is null (or equal to any constant).
1942 // If this is the case, stop tracking the symbol.
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001943 if (St->getSymVal(I.getKey())) {
1944 changed = true;
1945 B = RefBFactory.Remove(B, I.getKey());
1946 }
1947 }
1948
1949 if (!changed)
1950 return St;
1951
1952 ValueState StImpl = *St;
1953 StImpl.CheckerState = B.getRoot();
Ted Kremenek76d31662008-07-17 23:33:10 +00001954 return VMgr.getPersistentState(StImpl);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001955}
Ted Kremeneka7338b42008-03-11 06:39:11 +00001956
1957CFRefCount::RefBindings CFRefCount::Update(RefBindings B, SymbolID sym,
Ted Kremenek0d721572008-03-11 17:48:22 +00001958 RefVal V, ArgEffect E,
Ted Kremenek1feab292008-04-16 04:28:53 +00001959 RefVal::Kind& hasErr) {
Ted Kremeneka7338b42008-03-11 06:39:11 +00001960
Ted Kremenek0d721572008-03-11 17:48:22 +00001961 // FIXME: This dispatch can potentially be sped up by unifiying it into
1962 // a single switch statement. Opt for simplicity for now.
Ted Kremeneka7338b42008-03-11 06:39:11 +00001963
Ted Kremenek0d721572008-03-11 17:48:22 +00001964 switch (E) {
1965 default:
1966 assert (false && "Unhandled CFRef transition.");
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001967
1968 case MayEscape:
1969 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00001970 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001971 break;
1972 }
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001973 // Fall-through.
Ted Kremenekede40b72008-07-09 18:11:16 +00001974 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00001975 case DoNothing:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001976 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
Ted Kremenek272aa852008-06-25 21:21:56 +00001977 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00001978 hasErr = V.getKind();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001979 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001980 }
Ted Kremenek0d721572008-03-11 17:48:22 +00001981 return B;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00001982
Ted Kremenek4e1d22f2008-07-01 00:01:02 +00001983 case Autorelease:
Ted Kremenek227c5372008-05-06 02:41:27 +00001984 case StopTracking:
1985 return RefBFactory.Remove(B, sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001986
Ted Kremenek0d721572008-03-11 17:48:22 +00001987 case IncRef:
1988 switch (V.getKind()) {
1989 default:
1990 assert(false);
1991
1992 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00001993 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00001994 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001995 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00001996 case RefVal::Released:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001997 if (isGCEnabled())
Ted Kremenek272aa852008-06-25 21:21:56 +00001998 V = V ^ RefVal::Owned;
Ted Kremeneke2dd9572008-04-29 05:44:10 +00001999 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00002000 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremeneke2dd9572008-04-29 05:44:10 +00002001 hasErr = V.getKind();
2002 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002003 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002004 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002005 break;
2006
Ted Kremenek272aa852008-06-25 21:21:56 +00002007 case SelfOwn:
2008 V = V ^ RefVal::NotOwned;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002009 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00002010 case DecRef:
2011 switch (V.getKind()) {
2012 default:
2013 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002014
Ted Kremenek272aa852008-06-25 21:21:56 +00002015 case RefVal::Owned:
2016 V = V.getCount() > 1 ? V - 1 : V ^ RefVal::Released;
Ted Kremenek0d721572008-03-11 17:48:22 +00002017 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002018
Ted Kremenek272aa852008-06-25 21:21:56 +00002019 case RefVal::NotOwned:
2020 if (V.getCount() > 0)
2021 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00002022 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00002023 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00002024 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002025 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002026 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002027
2028 case RefVal::Released:
Ted Kremenek272aa852008-06-25 21:21:56 +00002029 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00002030 hasErr = V.getKind();
Ted Kremenek0d721572008-03-11 17:48:22 +00002031 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002032 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002033 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002034 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002035 return RefBFactory.Add(B, sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00002036}
2037
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002038//===----------------------------------------------------------------------===//
Ted Kremenek7d421f32008-04-09 23:49:11 +00002039// Error reporting.
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002040//===----------------------------------------------------------------------===//
2041
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002042namespace {
2043
2044 //===-------------===//
2045 // Bug Descriptions. //
2046 //===-------------===//
2047
Ted Kremeneke3769852008-04-18 20:54:29 +00002048 class VISIBILITY_HIDDEN CFRefBug : public BugTypeCacheLocation {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002049 protected:
2050 CFRefCount& TF;
2051
2052 public:
2053 CFRefBug(CFRefCount& tf) : TF(tf) {}
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002054
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002055 CFRefCount& getTF() { return TF; }
Ted Kremenek0ff3f202008-05-05 23:16:31 +00002056 const CFRefCount& getTF() const { return TF; }
2057
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002058 virtual bool isLeak() const { return false; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002059 };
2060
2061 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2062 public:
2063 UseAfterRelease(CFRefCount& tf) : CFRefBug(tf) {}
2064
2065 virtual const char* getName() const {
Ted Kremenek0ff3f202008-05-05 23:16:31 +00002066 return "Use-After-Release";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002067 }
2068 virtual const char* getDescription() const {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002069 return "Reference-counted object is used after it is released.";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002070 }
2071
2072 virtual void EmitWarnings(BugReporter& BR);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002073 };
2074
2075 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2076 public:
2077 BadRelease(CFRefCount& tf) : CFRefBug(tf) {}
2078
2079 virtual const char* getName() const {
Ted Kremenek0ff3f202008-05-05 23:16:31 +00002080 return "Bad Release";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002081 }
2082 virtual const char* getDescription() const {
2083 return "Incorrect decrement of the reference count of a "
Ted Kremeneka8503952008-04-18 04:55:01 +00002084 "CoreFoundation object: "
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002085 "The object is not owned at this point by the caller.";
2086 }
2087
2088 virtual void EmitWarnings(BugReporter& BR);
2089 };
2090
2091 class VISIBILITY_HIDDEN Leak : public CFRefBug {
2092 public:
2093 Leak(CFRefCount& tf) : CFRefBug(tf) {}
2094
2095 virtual const char* getName() const {
Ted Kremenekb3a44e72008-05-06 18:11:36 +00002096
2097 if (getTF().isGCEnabled())
2098 return "Memory Leak (GC)";
2099
2100 if (getTF().getLangOptions().getGCMode() == LangOptions::HybridGC)
2101 return "Memory Leak (Hybrid MM, non-GC)";
2102
2103 assert (getTF().getLangOptions().getGCMode() == LangOptions::NonGC);
2104 return "Memory Leak";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002105 }
2106
2107 virtual const char* getDescription() const {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002108 return "Object leaked";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002109 }
2110
2111 virtual void EmitWarnings(BugReporter& BR);
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002112 virtual void GetErrorNodes(std::vector<ExplodedNode<ValueState>*>& Nodes);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002113 virtual bool isLeak() const { return true; }
Ted Kremenekd7e26782008-05-16 18:33:44 +00002114 virtual bool isCached(BugReport& R);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002115 };
2116
2117 //===---------===//
2118 // Bug Reports. //
2119 //===---------===//
2120
2121 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
2122 SymbolID Sym;
2123 public:
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002124 CFRefReport(CFRefBug& D, ExplodedNode<ValueState> *n, SymbolID sym)
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002125 : RangedBugReport(D, n), Sym(sym) {}
2126
2127 virtual ~CFRefReport() {}
2128
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002129 CFRefBug& getBugType() {
2130 return (CFRefBug&) RangedBugReport::getBugType();
2131 }
2132 const CFRefBug& getBugType() const {
2133 return (const CFRefBug&) RangedBugReport::getBugType();
2134 }
2135
2136 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2137 const SourceRange*& end) {
2138
Ted Kremenek198cae02008-05-02 20:53:50 +00002139 if (!getBugType().isLeak())
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002140 RangedBugReport::getRanges(BR, beg, end);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002141 else
2142 beg = end = 0;
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002143 }
2144
Ted Kremenekd7e26782008-05-16 18:33:44 +00002145 SymbolID getSymbol() const { return Sym; }
2146
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002147 virtual PathDiagnosticPiece* getEndPath(BugReporter& BR,
2148 ExplodedNode<ValueState>* N);
2149
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002150 virtual std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002151
2152 virtual PathDiagnosticPiece* VisitNode(ExplodedNode<ValueState>* N,
2153 ExplodedNode<ValueState>* PrevN,
2154 ExplodedGraph<ValueState>& G,
2155 BugReporter& BR);
2156 };
2157
2158
2159} // end anonymous namespace
2160
2161void CFRefCount::RegisterChecks(GRExprEngine& Eng) {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002162 Eng.Register(new UseAfterRelease(*this));
2163 Eng.Register(new BadRelease(*this));
2164 Eng.Register(new Leak(*this));
2165}
2166
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002167
2168static const char* Msgs[] = {
2169 "Code is compiled in garbage collection only mode" // GC only
2170 " (the bug occurs with garbage collection enabled).",
2171
2172 "Code is compiled without garbage collection.", // No GC.
2173
2174 "Code is compiled for use with and without garbage collection (GC)."
2175 " The bug occurs with GC enabled.", // Hybrid, with GC.
2176
2177 "Code is compiled for use with and without garbage collection (GC)."
2178 " The bug occurs in non-GC mode." // Hyrbird, without GC/
2179};
2180
2181std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2182 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2183
2184 switch (TF.getLangOptions().getGCMode()) {
2185 default:
2186 assert(false);
Ted Kremenekcb4709402008-05-01 04:02:04 +00002187
2188 case LangOptions::GCOnly:
2189 assert (TF.isGCEnabled());
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002190 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2191
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002192 case LangOptions::NonGC:
2193 assert (!TF.isGCEnabled());
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002194 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2195
2196 case LangOptions::HybridGC:
2197 if (TF.isGCEnabled())
2198 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2199 else
2200 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2201 }
2202}
2203
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002204PathDiagnosticPiece* CFRefReport::VisitNode(ExplodedNode<ValueState>* N,
2205 ExplodedNode<ValueState>* PrevN,
2206 ExplodedGraph<ValueState>& G,
2207 BugReporter& BR) {
2208
2209 // Check if the type state has changed.
2210
Ted Kremenekf22f8682008-07-10 22:03:41 +00002211 const ValueState* PrevSt = PrevN->getState();
2212 const ValueState* CurrSt = N->getState();
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002213
2214 CFRefCount::RefBindings PrevB = CFRefCount::GetRefBindings(*PrevSt);
2215 CFRefCount::RefBindings CurrB = CFRefCount::GetRefBindings(*CurrSt);
2216
Ted Kremenek6064a362008-07-07 16:21:19 +00002217 const RefVal* PrevT = PrevB.lookup(Sym);
2218 const RefVal* CurrT = CurrB.lookup(Sym);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002219
Ted Kremeneka8503952008-04-18 04:55:01 +00002220 if (!CurrT)
2221 return NULL;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002222
Ted Kremeneka8503952008-04-18 04:55:01 +00002223 const char* Msg = NULL;
Ted Kremenek6064a362008-07-07 16:21:19 +00002224 const RefVal& CurrV = *CurrB.lookup(Sym);
Ted Kremenek9363fd92008-05-05 17:53:17 +00002225
Ted Kremeneka8503952008-04-18 04:55:01 +00002226 if (!PrevT) {
2227
Ted Kremenek9363fd92008-05-05 17:53:17 +00002228 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2229
2230 if (CurrV.isOwned()) {
2231
2232 if (isa<CallExpr>(S))
2233 Msg = "Function call returns an object with a +1 retain count"
2234 " (owning reference).";
2235 else {
2236 assert (isa<ObjCMessageExpr>(S));
2237 Msg = "Method returns an object with a +1 retain count"
2238 " (owning reference).";
2239 }
2240 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002241 else {
2242 assert (CurrV.isNotOwned());
Ted Kremenek9363fd92008-05-05 17:53:17 +00002243
2244 if (isa<CallExpr>(S))
2245 Msg = "Function call returns an object with a +0 retain count"
2246 " (non-owning reference).";
2247 else {
2248 assert (isa<ObjCMessageExpr>(S));
2249 Msg = "Method returns an object with a +0 retain count"
2250 " (non-owning reference).";
2251 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002252 }
Ted Kremenek9363fd92008-05-05 17:53:17 +00002253
Ted Kremeneka8503952008-04-18 04:55:01 +00002254 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
2255 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, Msg);
2256
2257 if (Expr* Exp = dyn_cast<Expr>(S))
2258 P->addRange(Exp->getSourceRange());
2259
2260 return P;
2261 }
2262
Ted Kremenek6064a362008-07-07 16:21:19 +00002263 // Determine if the typestate has changed.
2264 RefVal PrevV = *PrevB.lookup(Sym);
Ted Kremeneka8503952008-04-18 04:55:01 +00002265
2266 if (PrevV == CurrV)
2267 return NULL;
2268
2269 // The typestate has changed.
2270
2271 std::ostringstream os;
2272
2273 switch (CurrV.getKind()) {
2274 case RefVal::Owned:
2275 case RefVal::NotOwned:
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002276
2277 if (PrevV.getCount() == CurrV.getCount())
2278 return 0;
Ted Kremeneka8503952008-04-18 04:55:01 +00002279
2280 if (PrevV.getCount() > CurrV.getCount())
2281 os << "Reference count decremented.";
2282 else
2283 os << "Reference count incremented.";
2284
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002285 if (unsigned Count = CurrV.getCount()) {
Ted Kremenek9363fd92008-05-05 17:53:17 +00002286
2287 os << " Object has +" << Count;
Ted Kremenek752b5842008-04-18 05:32:44 +00002288
Ted Kremenek9363fd92008-05-05 17:53:17 +00002289 if (Count > 1)
2290 os << " retain counts.";
Ted Kremenek752b5842008-04-18 05:32:44 +00002291 else
Ted Kremenek9363fd92008-05-05 17:53:17 +00002292 os << " retain count.";
Ted Kremenek752b5842008-04-18 05:32:44 +00002293 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002294
2295 Msg = os.str().c_str();
2296
2297 break;
2298
2299 case RefVal::Released:
2300 Msg = "Object released.";
2301 break;
2302
2303 case RefVal::ReturnedOwned:
Ted Kremenek9363fd92008-05-05 17:53:17 +00002304 Msg = "Object returned to caller as owning reference (single retain count"
2305 " transferred to caller).";
Ted Kremeneka8503952008-04-18 04:55:01 +00002306 break;
2307
2308 case RefVal::ReturnedNotOwned:
Ted Kremenek9363fd92008-05-05 17:53:17 +00002309 Msg = "Object returned to caller with a +0 (non-owning) retain count.";
Ted Kremeneka8503952008-04-18 04:55:01 +00002310 break;
2311
2312 default:
2313 return NULL;
2314 }
2315
2316 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2317 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
2318 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, Msg);
2319
2320 // Add the range by scanning the children of the statement for any bindings
2321 // to Sym.
2322
Ted Kremenekba1c7ed2008-07-02 21:24:01 +00002323 ValueStateManager& VSM = cast<GRBugReporter>(BR).getStateManager();
Ted Kremeneka8503952008-04-18 04:55:01 +00002324
2325 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2326 if (Expr* Exp = dyn_cast_or_null<Expr>(*I)) {
2327 RVal X = VSM.GetRVal(CurrSt, Exp);
2328
2329 if (lval::SymbolVal* SV = dyn_cast<lval::SymbolVal>(&X))
2330 if (SV->getSymbol() == Sym) {
2331 P->addRange(Exp->getSourceRange()); break;
2332 }
2333 }
2334
2335 return P;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002336}
2337
Ted Kremenekd7e26782008-05-16 18:33:44 +00002338static std::pair<ExplodedNode<ValueState>*,VarDecl*>
2339GetAllocationSite(ExplodedNode<ValueState>* N, SymbolID Sym) {
2340
2341 typedef CFRefCount::RefBindings RefBindings;
2342 ExplodedNode<ValueState>* Last = N;
2343
2344 // Find the first node that referred to the tracked symbol. We also
2345 // try and find the first VarDecl the value was stored to.
2346
2347 VarDecl* FirstDecl = 0;
2348
2349 while (N) {
Ted Kremenekf22f8682008-07-10 22:03:41 +00002350 const ValueState* St = N->getState();
Ted Kremenekd7e26782008-05-16 18:33:44 +00002351 RefBindings B = RefBindings((RefBindings::TreeTy*) St->CheckerState);
Ted Kremenekd7e26782008-05-16 18:33:44 +00002352
Ted Kremenek6064a362008-07-07 16:21:19 +00002353 if (!B.lookup(Sym))
Ted Kremenekd7e26782008-05-16 18:33:44 +00002354 break;
2355
2356 VarDecl* VD = 0;
2357
2358 // Determine if there is an LVal binding to the symbol.
2359 for (ValueState::vb_iterator I=St->vb_begin(), E=St->vb_end(); I!=E; ++I) {
2360 if (!isa<lval::SymbolVal>(I->second) // Is the value a symbol?
2361 || cast<lval::SymbolVal>(I->second).getSymbol() != Sym)
2362 continue;
2363
2364 if (VD) { // Multiple decls map to this symbol.
2365 VD = 0;
2366 break;
2367 }
2368
2369 VD = I->first;
2370 }
2371
2372 if (VD) FirstDecl = VD;
2373
2374 Last = N;
2375 N = N->pred_empty() ? NULL : *(N->pred_begin());
2376 }
2377
2378 return std::make_pair(Last, FirstDecl);
2379}
Ted Kremenek4c479322008-05-06 23:07:13 +00002380
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002381PathDiagnosticPiece* CFRefReport::getEndPath(BugReporter& BR,
Ted Kremenekea794e92008-05-05 18:50:19 +00002382 ExplodedNode<ValueState>* EndN) {
Ted Kremenek86953652008-05-22 23:45:19 +00002383
2384 // Tell the BugReporter to report cases when the tracked symbol is
2385 // assigned to different variables, etc.
Ted Kremenekba1c7ed2008-07-02 21:24:01 +00002386 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002387
2388 if (!getBugType().isLeak())
Ted Kremenekea794e92008-05-05 18:50:19 +00002389 return RangedBugReport::getEndPath(BR, EndN);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002390
Ted Kremenek9363fd92008-05-05 17:53:17 +00002391 typedef CFRefCount::RefBindings RefBindings;
2392
2393 // Get the retain count.
Ted Kremenek9363fd92008-05-05 17:53:17 +00002394
Ted Kremenek6064a362008-07-07 16:21:19 +00002395 unsigned long RetCount =
2396 CFRefCount::GetRefBindings(*EndN->getState()).lookup(Sym)->getCount();
2397
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002398 // We are a leak. Walk up the graph to get to the first node where the
Ted Kremenekd7e26782008-05-16 18:33:44 +00002399 // symbol appeared, and also get the first VarDecl that tracked object
2400 // is stored to.
2401
2402 ExplodedNode<ValueState>* AllocNode = 0;
Ted Kremenek198cae02008-05-02 20:53:50 +00002403 VarDecl* FirstDecl = 0;
Ted Kremenekd7e26782008-05-16 18:33:44 +00002404 llvm::tie(AllocNode, FirstDecl) = GetAllocationSite(EndN, Sym);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002405
Ted Kremenekd7e26782008-05-16 18:33:44 +00002406 // Get the allocate site.
2407 assert (AllocNode);
2408 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002409
Ted Kremenekea794e92008-05-05 18:50:19 +00002410 SourceManager& SMgr = BR.getContext().getSourceManager();
2411 unsigned AllocLine = SMgr.getLogicalLineNumber(FirstStmt->getLocStart());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002412
Ted Kremenekea794e92008-05-05 18:50:19 +00002413 // Get the leak site. We may have multiple ExplodedNodes (one with the
2414 // leak) that occur on the same line number; if the node with the leak
2415 // has any immediate predecessor nodes with the same line number, find
2416 // any transitive-successors that have a different statement and use that
2417 // line number instead. This avoids emiting a diagnostic like:
2418 //
2419 // // 'y' is leaked.
2420 // int x = foo(y);
2421 //
2422 // instead we want:
2423 //
2424 // int x = foo(y);
2425 // // 'y' is leaked.
2426
2427 Stmt* S = getStmt(BR); // This is the statement where the leak occured.
2428 assert (S);
2429 unsigned EndLine = SMgr.getLogicalLineNumber(S->getLocStart());
2430
2431 // Look in the *trimmed* graph at the immediate predecessor of EndN. Does
2432 // it occur on the same line?
Ted Kremenek4c479322008-05-06 23:07:13 +00002433
2434 PathDiagnosticPiece::DisplayHint Hint = PathDiagnosticPiece::Above;
Ted Kremenekea794e92008-05-05 18:50:19 +00002435
2436 assert (!EndN->pred_empty()); // Not possible to have 0 predecessors.
Ted Kremenek4c479322008-05-06 23:07:13 +00002437 ExplodedNode<ValueState> *Pred = *(EndN->pred_begin());
2438 ProgramPoint PredPos = Pred->getLocation();
Ted Kremenekea794e92008-05-05 18:50:19 +00002439
Ted Kremenek4c479322008-05-06 23:07:13 +00002440 if (PostStmt* PredPS = dyn_cast<PostStmt>(&PredPos)) {
Ted Kremenekea794e92008-05-05 18:50:19 +00002441
Ted Kremenek4c479322008-05-06 23:07:13 +00002442 Stmt* SPred = PredPS->getStmt();
Ted Kremenekea794e92008-05-05 18:50:19 +00002443
2444 // Predecessor at same line?
Ted Kremenek4c479322008-05-06 23:07:13 +00002445 if (SMgr.getLogicalLineNumber(SPred->getLocStart()) != EndLine) {
2446 Hint = PathDiagnosticPiece::Below;
2447 S = SPred;
2448 }
Ted Kremenekea794e92008-05-05 18:50:19 +00002449 }
Ted Kremenekea794e92008-05-05 18:50:19 +00002450
2451 // Generate the diagnostic.
Ted Kremenek4c479322008-05-06 23:07:13 +00002452 FullSourceLoc L( S->getLocStart(), SMgr);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002453 std::ostringstream os;
Ted Kremenek198cae02008-05-02 20:53:50 +00002454
Ted Kremenekea794e92008-05-05 18:50:19 +00002455 os << "Object allocated on line " << AllocLine;
Ted Kremenek198cae02008-05-02 20:53:50 +00002456
2457 if (FirstDecl)
2458 os << " and stored into '" << FirstDecl->getName() << '\'';
2459
Ted Kremenek9363fd92008-05-05 17:53:17 +00002460 os << " is no longer referenced after this point and has a retain count of +"
2461 << RetCount << " (object leaked).";
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002462
Ted Kremenek4c479322008-05-06 23:07:13 +00002463 return new PathDiagnosticPiece(L, os.str(), Hint);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002464}
2465
Ted Kremenek7d421f32008-04-09 23:49:11 +00002466void UseAfterRelease::EmitWarnings(BugReporter& BR) {
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002467
Ted Kremenek7d421f32008-04-09 23:49:11 +00002468 for (CFRefCount::use_after_iterator I = TF.use_after_begin(),
2469 E = TF.use_after_end(); I != E; ++I) {
2470
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002471 CFRefReport report(*this, I->first, I->second.second);
2472 report.addRange(I->second.first->getSourceRange());
Ted Kremenek270ab7d2008-04-18 01:56:37 +00002473 BR.EmitWarning(report);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002474 }
Ted Kremenek7d421f32008-04-09 23:49:11 +00002475}
2476
2477void BadRelease::EmitWarnings(BugReporter& BR) {
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002478
Ted Kremenek7d421f32008-04-09 23:49:11 +00002479 for (CFRefCount::bad_release_iterator I = TF.bad_release_begin(),
2480 E = TF.bad_release_end(); I != E; ++I) {
2481
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002482 CFRefReport report(*this, I->first, I->second.second);
2483 report.addRange(I->second.first->getSourceRange());
2484 BR.EmitWarning(report);
Ted Kremenek7d421f32008-04-09 23:49:11 +00002485 }
2486}
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002487
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00002488void Leak::EmitWarnings(BugReporter& BR) {
2489
2490 for (CFRefCount::leaks_iterator I = TF.leaks_begin(),
2491 E = TF.leaks_end(); I != E; ++I) {
2492
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002493 std::vector<SymbolID>& SymV = *(I->second);
2494 unsigned n = SymV.size();
2495
2496 for (unsigned i = 0; i < n; ++i) {
2497 CFRefReport report(*this, I->first, SymV[i]);
2498 BR.EmitWarning(report);
2499 }
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00002500 }
2501}
2502
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002503void Leak::GetErrorNodes(std::vector<ExplodedNode<ValueState>*>& Nodes) {
2504 for (CFRefCount::leaks_iterator I=TF.leaks_begin(), E=TF.leaks_end();
2505 I!=E; ++I)
2506 Nodes.push_back(I->first);
2507}
2508
Ted Kremenekd7e26782008-05-16 18:33:44 +00002509bool Leak::isCached(BugReport& R) {
2510
2511 // Most bug reports are cached at the location where they occured.
2512 // With leaks, we want to unique them by the location where they were
2513 // allocated, and only report only a single path.
2514
2515 SymbolID Sym = static_cast<CFRefReport&>(R).getSymbol();
2516
2517 ExplodedNode<ValueState>* AllocNode =
2518 GetAllocationSite(R.getEndNode(), Sym).first;
2519
2520 if (!AllocNode)
2521 return false;
2522
2523 return BugTypeCacheLocation::isCached(AllocNode->getLocation());
2524}
2525
Ted Kremeneka7338b42008-03-11 06:39:11 +00002526//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00002527// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00002528//===----------------------------------------------------------------------===//
2529
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002530GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
2531 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00002532 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00002533}