blob: 319318f99075e61b50af0402fad3897c518fbe62 [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"
Ted Kremeneka7338b42008-03-11 06:39:11 +000023#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/FoldingSet.h"
25#include "llvm/ADT/ImmutableMap.h"
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000026#include "llvm/ADT/StringExtras.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000027#include "llvm/Support/Compiler.h"
Ted Kremenekd7e26782008-05-16 18:33:44 +000028#include "llvm/ADT/STLExtras.h"
Ted Kremenek3b11f7a2008-03-11 19:44:10 +000029#include <ostream>
Ted Kremeneka8503952008-04-18 04:55:01 +000030#include <sstream>
Ted Kremenek827f93b2008-03-06 00:08:09 +000031
32using namespace clang;
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000033using llvm::CStrInCStrNoCase;
Ted Kremenek827f93b2008-03-06 00:08:09 +000034
Ted Kremenek7d421f32008-04-09 23:49:11 +000035//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +000036// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +000037//===----------------------------------------------------------------------===//
38
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +000039static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +000040 IdentifierInfo* II = &Ctx.Idents.get(name);
41 return Ctx.Selectors.getSelector(0, &II);
42}
43
Ted Kremenek0e344d42008-05-06 00:30:21 +000044static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
45 IdentifierInfo* II = &Ctx.Idents.get(name);
46 return Ctx.Selectors.getSelector(1, &II);
47}
48
Ted Kremenek272aa852008-06-25 21:21:56 +000049//===----------------------------------------------------------------------===//
50// Type querying functions.
51//===----------------------------------------------------------------------===//
52
Ted Kremenek62820d82008-05-07 20:06:41 +000053static bool isCFRefType(QualType T) {
54
55 if (!T->isPointerType())
56 return false;
57
Ted Kremenek272aa852008-06-25 21:21:56 +000058 // Check the typedef for the name "CF" and the substring "Ref".
Ted Kremenek62820d82008-05-07 20:06:41 +000059 TypedefType* TD = dyn_cast<TypedefType>(T.getTypePtr());
60
61 if (!TD)
62 return false;
63
64 const char* TDName = TD->getDecl()->getIdentifier()->getName();
65 assert (TDName);
66
67 if (TDName[0] != 'C' || TDName[1] != 'F')
68 return false;
69
70 if (strstr(TDName, "Ref") == 0)
71 return false;
72
73 return true;
74}
75
Ted Kremenek4c5378c2008-07-15 16:50:12 +000076static bool isCGRefType(QualType T) {
77
78 if (!T->isPointerType())
79 return false;
80
81 // Check the typedef for the name "CG" and the substring "Ref".
82 TypedefType* TD = dyn_cast<TypedefType>(T.getTypePtr());
83
84 if (!TD)
85 return false;
86
87 const char* TDName = TD->getDecl()->getIdentifier()->getName();
88 assert (TDName);
89
90 if (TDName[0] != 'C' || TDName[1] != 'G')
91 return false;
92
93 if (strstr(TDName, "Ref") == 0)
94 return false;
95
96 return true;
97}
98
Ted Kremenek62820d82008-05-07 20:06:41 +000099static bool isNSType(QualType T) {
100
101 if (!T->isPointerType())
102 return false;
103
104 ObjCInterfaceType* OT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
105
106 if (!OT)
107 return false;
108
109 const char* ClsName = OT->getDecl()->getIdentifier()->getName();
110 assert (ClsName);
111
112 if (ClsName[0] != 'N' || ClsName[1] != 'S')
113 return false;
114
115 return true;
116}
117
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000118//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000119// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000120//===----------------------------------------------------------------------===//
121
Ted Kremenek272aa852008-06-25 21:21:56 +0000122namespace {
123/// ArgEffect is used to summarize a function/method call's effect on a
124/// particular argument.
Ted Kremenekede40b72008-07-09 18:11:16 +0000125enum ArgEffect { IncRef, DecRef, DoNothing, DoNothingByRef,
126 StopTracking, MayEscape, SelfOwn, Autorelease };
Ted Kremenek272aa852008-06-25 21:21:56 +0000127
128/// ArgEffects summarizes the effects of a function/method call on all of
129/// its arguments.
130typedef std::vector<std::pair<unsigned,ArgEffect> > ArgEffects;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000131}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000132
Ted Kremeneka7338b42008-03-11 06:39:11 +0000133namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000134template <> struct FoldingSetTrait<ArgEffects> {
135 static void Profile(const ArgEffects& X, FoldingSetNodeID& ID) {
136 for (ArgEffects::const_iterator I = X.begin(), E = X.end(); I!= E; ++I) {
137 ID.AddInteger(I->first);
138 ID.AddInteger((unsigned) I->second);
139 }
140 }
141};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000142} // end llvm namespace
143
144namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000145
146/// RetEffect is used to summarize a function/method call's behavior with
147/// respect to its return value.
148class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000149public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000150 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
151 NotOwnedSymbol, ReceiverAlias };
Ted Kremenek272aa852008-06-25 21:21:56 +0000152
Ted Kremeneka7338b42008-03-11 06:39:11 +0000153private:
154 unsigned Data;
Ted Kremenek272aa852008-06-25 21:21:56 +0000155 RetEffect(Kind k, unsigned D = 0) { Data = (D << 3) | (unsigned) k; }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000156
Ted Kremeneka7338b42008-03-11 06:39:11 +0000157public:
Ted Kremenek272aa852008-06-25 21:21:56 +0000158
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000159 Kind getKind() const { return (Kind) (Data & 0x7); }
Ted Kremenek272aa852008-06-25 21:21:56 +0000160
161 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000162 assert(getKind() == Alias);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000163 return Data >> 3;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000164 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000165
Ted Kremenek272aa852008-06-25 21:21:56 +0000166 static RetEffect MakeAlias(unsigned Idx) {
167 return RetEffect(Alias, Idx);
168 }
169 static RetEffect MakeReceiverAlias() {
170 return RetEffect(ReceiverAlias);
171 }
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000172 static RetEffect MakeOwned(bool isAllocated = false) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000173 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol);
174 }
175 static RetEffect MakeNotOwned() {
176 return RetEffect(NotOwnedSymbol);
177 }
178 static RetEffect MakeNoRet() {
179 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000180 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000181
Ted Kremenek272aa852008-06-25 21:21:56 +0000182 operator Kind() const {
183 return getKind();
184 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000185
Ted Kremenek272aa852008-06-25 21:21:56 +0000186 void Profile(llvm::FoldingSetNodeID& ID) const {
187 ID.AddInteger(Data);
188 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000189};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000190
Ted Kremenek272aa852008-06-25 21:21:56 +0000191
192class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000193 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
194 /// specifies the argument (starting from 0). This can be sparsely
195 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000196 ArgEffects* Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000197
198 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
199 /// do not have an entry in Args.
200 ArgEffect DefaultArgEffect;
201
Ted Kremenek272aa852008-06-25 21:21:56 +0000202 /// Receiver - If this summary applies to an Objective-C message expression,
203 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000204 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000205
206 /// Ret - The effect on the return value. Used to indicate if the
207 /// function/method call returns a new tracked symbol, returns an
208 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000209 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000210
Ted Kremenekf2717b02008-07-18 17:24:20 +0000211 /// EndPath - Indicates that execution of this method/function should
212 /// terminate the simulation of a path.
213 bool EndPath;
214
Ted Kremeneka7338b42008-03-11 06:39:11 +0000215public:
216
Ted Kremenekbcaff792008-05-06 15:44:25 +0000217 RetainSummary(ArgEffects* A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000218 ArgEffect ReceiverEff, bool endpath = false)
219 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
220 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000221
Ted Kremenek272aa852008-06-25 21:21:56 +0000222 /// getArg - Return the argument effect on the argument specified by
223 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000224 ArgEffect getArg(unsigned idx) const {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000225
Ted Kremenekae855d42008-04-24 17:22:33 +0000226 if (!Args)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000227 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000228
229 // If Args is present, it is likely to contain only 1 element.
230 // Just do a linear search. Do it from the back because functions with
231 // large numbers of arguments will be tail heavy with respect to which
Ted Kremenek272aa852008-06-25 21:21:56 +0000232 // argument they actually modify with respect to the reference count.
Ted Kremenekae855d42008-04-24 17:22:33 +0000233 for (ArgEffects::reverse_iterator I=Args->rbegin(), E=Args->rend();
234 I!=E; ++I) {
235
236 if (idx > I->first)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000237 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000238
239 if (idx == I->first)
240 return I->second;
241 }
242
Ted Kremenekbcaff792008-05-06 15:44:25 +0000243 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000244 }
245
Ted Kremenek272aa852008-06-25 21:21:56 +0000246 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000247 RetEffect getRetEffect() const {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000248 return Ret;
249 }
250
Ted Kremenekf2717b02008-07-18 17:24:20 +0000251 /// isEndPath - Returns true if executing the given method/function should
252 /// terminate the path.
253 bool isEndPath() const { return EndPath; }
254
Ted Kremenek272aa852008-06-25 21:21:56 +0000255 /// getReceiverEffect - Returns the effect on the receiver of the call.
256 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000257 ArgEffect getReceiverEffect() const {
258 return Receiver;
259 }
260
Ted Kremenek2719e982008-06-17 02:43:46 +0000261 typedef ArgEffects::const_iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000262
Ted Kremenek2719e982008-06-17 02:43:46 +0000263 ExprIterator begin_args() const { return Args->begin(); }
264 ExprIterator end_args() const { return Args->end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000265
Ted Kremenek266d8b62008-05-06 02:26:56 +0000266 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects* A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000267 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000268 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000269 ID.AddPointer(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000270 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000271 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000272 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000273 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000274 }
275
276 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000277 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000278 }
279};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000280} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000281
Ted Kremenek272aa852008-06-25 21:21:56 +0000282//===----------------------------------------------------------------------===//
283// Data structures for constructing summaries.
284//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000285
Ted Kremenek272aa852008-06-25 21:21:56 +0000286namespace {
287class VISIBILITY_HIDDEN ObjCSummaryKey {
288 IdentifierInfo* II;
289 Selector S;
290public:
291 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
292 : II(ii), S(s) {}
293
294 ObjCSummaryKey(ObjCInterfaceDecl* d, Selector s)
295 : II(d ? d->getIdentifier() : 0), S(s) {}
296
297 ObjCSummaryKey(Selector s)
298 : II(0), S(s) {}
299
300 IdentifierInfo* getIdentifier() const { return II; }
301 Selector getSelector() const { return S; }
302};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000303}
304
305namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000306template <> struct DenseMapInfo<ObjCSummaryKey> {
307 static inline ObjCSummaryKey getEmptyKey() {
308 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
309 DenseMapInfo<Selector>::getEmptyKey());
310 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000311
Ted Kremenek272aa852008-06-25 21:21:56 +0000312 static inline ObjCSummaryKey getTombstoneKey() {
313 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
314 DenseMapInfo<Selector>::getTombstoneKey());
315 }
316
317 static unsigned getHashValue(const ObjCSummaryKey &V) {
318 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
319 & 0x88888888)
320 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
321 & 0x55555555);
322 }
323
324 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
325 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
326 RHS.getIdentifier()) &&
327 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
328 RHS.getSelector());
329 }
330
331 static bool isPod() {
332 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
333 DenseMapInfo<Selector>::isPod();
334 }
335};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000336} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000337
Ted Kremenek84f010c2008-06-23 23:30:29 +0000338namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000339class VISIBILITY_HIDDEN ObjCSummaryCache {
340 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
341 MapTy M;
342public:
343 ObjCSummaryCache() {}
344
345 typedef MapTy::iterator iterator;
346
347 iterator find(ObjCInterfaceDecl* D, Selector S) {
348
349 // Do a lookup with the (D,S) pair. If we find a match return
350 // the iterator.
351 ObjCSummaryKey K(D, S);
352 MapTy::iterator I = M.find(K);
353
354 if (I != M.end() || !D)
355 return I;
356
357 // Walk the super chain. If we find a hit with a parent, we'll end
358 // up returning that summary. We actually allow that key (null,S), as
359 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
360 // generate initial summaries without having to worry about NSObject
361 // being declared.
362 // FIXME: We may change this at some point.
363 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
364 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
365 break;
366
367 if (!C)
368 return I;
369 }
370
371 // Cache the summary with original key to make the next lookup faster
372 // and return the iterator.
373 M[K] = I->second;
374 return I;
375 }
376
377
378 iterator find(Expr* Receiver, Selector S) {
379 return find(getReceiverDecl(Receiver), S);
380 }
381
382 iterator find(IdentifierInfo* II, Selector S) {
383 // FIXME: Class method lookup. Right now we dont' have a good way
384 // of going between IdentifierInfo* and the class hierarchy.
385 iterator I = M.find(ObjCSummaryKey(II, S));
386 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
387 }
388
389 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
390
391 const PointerType* PT = E->getType()->getAsPointerType();
392 if (!PT) return 0;
393
394 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
395 if (!OI) return 0;
396
397 return OI ? OI->getDecl() : 0;
398 }
399
400 iterator end() { return M.end(); }
401
402 RetainSummary*& operator[](ObjCMessageExpr* ME) {
403
404 Selector S = ME->getSelector();
405
406 if (Expr* Receiver = ME->getReceiver()) {
407 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
408 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
409 }
410
411 return M[ObjCSummaryKey(ME->getClassName(), S)];
412 }
413
414 RetainSummary*& operator[](ObjCSummaryKey K) {
415 return M[K];
416 }
417
418 RetainSummary*& operator[](Selector S) {
419 return M[ ObjCSummaryKey(S) ];
420 }
421};
422} // end anonymous namespace
423
424//===----------------------------------------------------------------------===//
425// Data structures for managing collections of summaries.
426//===----------------------------------------------------------------------===//
427
428namespace {
429class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000430
431 //==-----------------------------------------------------------------==//
432 // Typedefs.
433 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000434
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000435 typedef llvm::FoldingSet<llvm::FoldingSetNodeWrapper<ArgEffects> >
436 ArgEffectsSetTy;
437
438 typedef llvm::FoldingSet<RetainSummary>
439 SummarySetTy;
440
441 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
442 FuncSummariesTy;
443
Ted Kremenek84f010c2008-06-23 23:30:29 +0000444 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000445
446 //==-----------------------------------------------------------------==//
447 // Data.
448 //==-----------------------------------------------------------------==//
449
Ted Kremenek272aa852008-06-25 21:21:56 +0000450 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000451 ASTContext& Ctx;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000452
Ted Kremenek272aa852008-06-25 21:21:56 +0000453 /// NSWindowII - An IdentifierInfo* representing the identifier "NSWindow."
454 IdentifierInfo* NSWindowII;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000455
456 /// NSPanelII - An IdentifierInfo* representing the identifier "NSPanel."
457 IdentifierInfo* NSPanelII;
Ted Kremenek272aa852008-06-25 21:21:56 +0000458
Ted Kremenekf2717b02008-07-18 17:24:20 +0000459 /// NSAssertionHandlerII - An IdentifierInfo* representing the identifier
460 // "NSAssertionHandler".
461 IdentifierInfo* NSAssertionHandlerII;
462
Ted Kremenekede40b72008-07-09 18:11:16 +0000463 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
464 /// "CFDictionaryCreate".
465 IdentifierInfo* CFDictionaryCreateII;
466
Ted Kremenek272aa852008-06-25 21:21:56 +0000467 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000468 const bool GCEnabled;
469
Ted Kremenek272aa852008-06-25 21:21:56 +0000470 /// SummarySet - A FoldingSet of uniqued summaries.
Ted Kremeneka4c74292008-04-10 22:58:08 +0000471 SummarySetTy SummarySet;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000472
Ted Kremenek272aa852008-06-25 21:21:56 +0000473 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000474 FuncSummariesTy FuncSummaries;
475
Ted Kremenek272aa852008-06-25 21:21:56 +0000476 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
477 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000478 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000479
Ted Kremenek272aa852008-06-25 21:21:56 +0000480 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000481 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000482
Ted Kremenek272aa852008-06-25 21:21:56 +0000483 /// ArgEffectsSet - A FoldingSet of uniqued ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000484 ArgEffectsSetTy ArgEffectsSet;
485
Ted Kremenek272aa852008-06-25 21:21:56 +0000486 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
487 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000488 llvm::BumpPtrAllocator BPAlloc;
489
Ted Kremenek272aa852008-06-25 21:21:56 +0000490 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000491 ArgEffects ScratchArgs;
492
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000493 RetainSummary* StopSummary;
494
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000495 //==-----------------------------------------------------------------==//
496 // Methods.
497 //==-----------------------------------------------------------------==//
498
Ted Kremenek272aa852008-06-25 21:21:56 +0000499 /// getArgEffects - Returns a persistent ArgEffects object based on the
500 /// data in ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000501 ArgEffects* getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000502
Ted Kremenek562c1302008-05-05 16:51:50 +0000503 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000504 RetainSummary* getUnarySummary(FunctionDecl* FD, UnaryFuncKind func);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000505
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000506 RetainSummary* getNSSummary(FunctionDecl* FD, const char* FName);
507 RetainSummary* getCFSummary(FunctionDecl* FD, const char* FName);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000508 RetainSummary* getCGSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000509
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000510 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
511 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000512 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000513
Ted Kremenek266d8b62008-05-06 02:26:56 +0000514 RetainSummary* getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000515 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000516 ArgEffect DefaultEff = MayEscape,
517 bool isEndPath = false);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000518
Ted Kremenek0e344d42008-05-06 00:30:21 +0000519
Ted Kremenek266d8b62008-05-06 02:26:56 +0000520 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000521 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000522 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000523 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000524 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000525
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000526
Ted Kremenekbcaff792008-05-06 15:44:25 +0000527 RetainSummary* getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000528 if (StopSummary)
529 return StopSummary;
530
531 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
532 StopTracking, StopTracking);
533
534 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000535 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000536
Ted Kremenek272aa852008-06-25 21:21:56 +0000537 RetainSummary* getInitMethodSummary(ObjCMessageExpr* ME);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000538
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000539 void InitializeClassMethodSummaries();
540 void InitializeMethodSummaries();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000541
542 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
543 RetainSummary* Summ) {
544 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
545 }
546
Ted Kremenek272aa852008-06-25 21:21:56 +0000547 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
548 ObjCClassMethodSummaries[S] = Summ;
549 }
550
551 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
552 ObjCMethodSummaries[S] = Summ;
553 }
554
555 void addNSWindowMethSummary(Selector S, RetainSummary *Summ) {
556 ObjCMethodSummaries[ObjCSummaryKey(NSWindowII, S)] = Summ;
557 }
558
Ted Kremeneke44927e2008-07-01 17:21:27 +0000559 void addNSPanelMethSummary(Selector S, RetainSummary *Summ) {
560 ObjCMethodSummaries[ObjCSummaryKey(NSPanelII, S)] = Summ;
561 }
562
Ted Kremenekf2717b02008-07-18 17:24:20 +0000563 void addPanicSummary(IdentifierInfo* ClsII, Selector S) {
564 RetainSummary* Summ = getPersistentSummary(0, RetEffect::MakeNoRet(),
565 DoNothing, DoNothing, true);
566
567 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
568 }
569
Ted Kremeneka7338b42008-03-11 06:39:11 +0000570public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000571
572 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000573 : Ctx(ctx),
574 NSWindowII(&ctx.Idents.get("NSWindow")),
575 NSPanelII(&ctx.Idents.get("NSPanel")),
Ted Kremenekf2717b02008-07-18 17:24:20 +0000576 NSAssertionHandlerII(&ctx.Idents.get("NSAssertionHandler")),
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 Kremenekab2fa2a2008-04-10 23:44:06 +0000827 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000828}
829
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000830RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000831
Ted Kremenek62820d82008-05-07 20:06:41 +0000832 FunctionType* FT =
833 dyn_cast<FunctionType>(FD->getType().getTypePtr());
Ted Kremenek562c1302008-05-05 16:51:50 +0000834
835 if (FT && !isCFRefType(FT->getResultType()))
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000836 return getPersistentSummary(RetEffect::MakeNoRet());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000837
Ted Kremenekae855d42008-04-24 17:22:33 +0000838 assert (ScratchArgs.empty());
Ted Kremenekede40b72008-07-09 18:11:16 +0000839
840 if (FD->getIdentifier() == CFDictionaryCreateII) {
841 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
842 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
843 }
844
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000845 return getPersistentSummary(RetEffect::MakeOwned(true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000846}
847
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000848RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000849
Ted Kremenek62820d82008-05-07 20:06:41 +0000850 FunctionType* FT =
851 dyn_cast<FunctionType>(FD->getType().getTypePtr());
Ted Kremenekd4244d42008-04-11 20:11:19 +0000852
Ted Kremenek562c1302008-05-05 16:51:50 +0000853 if (FT) {
854 QualType RetTy = FT->getResultType();
Ted Kremenekd4244d42008-04-11 20:11:19 +0000855
Ted Kremenek562c1302008-05-05 16:51:50 +0000856 // FIXME: For now we assume that all pointer types returned are referenced
857 // counted. Since this is the "Get" rule, we assume non-ownership, which
858 // works fine for things that are not reference counted. We do this because
859 // some generic data structures return "void*". We need something better
860 // in the future.
861
862 if (!isCFRefType(RetTy) && !RetTy->isPointerType())
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000863 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek562c1302008-05-05 16:51:50 +0000864 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000865
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000866 // FIXME: Add special-cases for functions that retain/release. For now
867 // just handle the default case.
868
Ted Kremenekae855d42008-04-24 17:22:33 +0000869 assert (ScratchArgs.empty());
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000870 return getPersistentSummary(RetEffect::MakeNotOwned(), DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000871}
872
Ted Kremeneka7338b42008-03-11 06:39:11 +0000873//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000874// Summary creation for Selectors.
875//===----------------------------------------------------------------------===//
876
Ted Kremenekbcaff792008-05-06 15:44:25 +0000877RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +0000878RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek42ea0322008-05-05 23:55:01 +0000879 assert(ScratchArgs.empty());
880
881 RetainSummary* Summ =
Ted Kremenek0e344d42008-05-06 00:30:21 +0000882 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremenek42ea0322008-05-05 23:55:01 +0000883
Ted Kremenek272aa852008-06-25 21:21:56 +0000884 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +0000885 return Summ;
886}
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000887
Ted Kremenek272aa852008-06-25 21:21:56 +0000888
Ted Kremenekbcaff792008-05-06 15:44:25 +0000889RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +0000890RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
891 ObjCInterfaceDecl* ID) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000892
893 Selector S = ME->getSelector();
Ted Kremenek42ea0322008-05-05 23:55:01 +0000894
Ted Kremenek272aa852008-06-25 21:21:56 +0000895 // Look up a summary in our summary cache.
896 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000897
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000898 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +0000899 return I->second;
Ted Kremenek272aa852008-06-25 21:21:56 +0000900
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000901 if (!ME->getType()->isPointerType())
902 return 0;
903
Ted Kremenek42ea0322008-05-05 23:55:01 +0000904 // "initXXX": pass-through for receiver.
905
906 const char* s = S.getIdentifierInfoForSlot(0)->getName();
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000907 assert (ScratchArgs.empty());
Ted Kremenek1d3d9562008-05-06 06:09:09 +0000908
Ted Kremenek988c4472008-06-02 17:14:13 +0000909 if (strncmp(s, "init", 4) == 0 || strncmp(s, "_init", 5) == 0)
Ted Kremenek272aa852008-06-25 21:21:56 +0000910 return getInitMethodSummary(ME);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000911
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000912 // "copyXXX", "createXXX", "newXXX": allocators.
Ted Kremenek42ea0322008-05-05 23:55:01 +0000913
Ted Kremenek5496f6d2008-05-07 04:25:59 +0000914 if (!isNSType(ME->getReceiver()->getType()))
915 return 0;
916
Ted Kremenek62820d82008-05-07 20:06:41 +0000917 if (CStrInCStrNoCase(s, "create") || CStrInCStrNoCase(s, "copy") ||
918 CStrInCStrNoCase(s, "new")) {
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000919
920 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000921 : RetEffect::MakeOwned(true);
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000922
923 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenek272aa852008-06-25 21:21:56 +0000924 ObjCMethodSummaries[ME] = Summ;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000925 return Summ;
926 }
Ted Kremenekbcaff792008-05-06 15:44:25 +0000927
Ted Kremenek42ea0322008-05-05 23:55:01 +0000928 return 0;
929}
930
Ted Kremeneka7722b72008-05-06 21:26:51 +0000931RetainSummary*
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000932RetainSummaryManager::getClassMethodSummary(IdentifierInfo* ClsName,
933 Selector S) {
Ted Kremeneka7722b72008-05-06 21:26:51 +0000934
Ted Kremenek272aa852008-06-25 21:21:56 +0000935 // FIXME: Eventually we should properly do class method summaries, but
936 // it requires us being able to walk the type hierarchy. Unfortunately,
937 // we cannot do this with just an IdentifierInfo* for the class name.
938
Ted Kremeneka7722b72008-05-06 21:26:51 +0000939 // Look up a summary in our cache of Selectors -> Summaries.
Ted Kremenek272aa852008-06-25 21:21:56 +0000940 ObjCMethodSummariesTy::iterator I = ObjCClassMethodSummaries.find(ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +0000941
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000942 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +0000943 return I->second;
944
Ted Kremenek4c479322008-05-06 23:07:13 +0000945 return 0;
Ted Kremeneka7722b72008-05-06 21:26:51 +0000946}
947
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000948void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +0000949
950 assert (ScratchArgs.empty());
951
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000952 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
953 : RetEffect::MakeOwned(true);
954
Ted Kremenek0e344d42008-05-06 00:30:21 +0000955 RetainSummary* Summ = getPersistentSummary(E);
956
Ted Kremenek272aa852008-06-25 21:21:56 +0000957 // Create the summaries for "alloc", "new", and "allocWithZone:" for
958 // NSObject and its derivatives.
959 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
960 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
961 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +0000962
963 // Create the [NSAssertionHandler currentHander] summary.
964 addClsMethSummary(NSAssertionHandlerII,
Ted Kremenek1ebce742008-07-18 18:14:26 +0000965 GetNullarySelector("currentHandler", Ctx),
Ted Kremenekf2717b02008-07-18 17:24:20 +0000966 getPersistentSummary(RetEffect::MakeNotOwned()));
Ted Kremenek0e344d42008-05-06 00:30:21 +0000967}
968
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000969void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +0000970
971 assert (ScratchArgs.empty());
972
Ted Kremeneka7722b72008-05-06 21:26:51 +0000973 // Create the "init" selector. It just acts as a pass-through for the
974 // receiver.
Ted Kremeneke44927e2008-07-01 17:21:27 +0000975 RetainSummary* InitSumm = getPersistentSummary(RetEffect::MakeReceiverAlias());
976 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +0000977
978 // The next methods are allocators.
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000979 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
980 : RetEffect::MakeOwned(true);
981
Ted Kremeneke44927e2008-07-01 17:21:27 +0000982 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +0000983
984 // Create the "copy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +0000985 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
Ted Kremenek83b2cde2008-05-06 00:38:54 +0000986
987 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +0000988 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000989
990 // Create the "retain" selector.
991 E = RetEffect::MakeReceiverAlias();
992 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : IncRef);
Ted Kremenek272aa852008-06-25 21:21:56 +0000993 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000994
995 // Create the "release" selector.
996 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +0000997 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +0000998
999 // Create the "drain" selector.
1000 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001001 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001002
1003 // Create the "autorelease" selector.
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00001004 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001005 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
1006
1007 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremeneke44927e2008-07-01 17:21:27 +00001008 // For NSPanel (which subclasses NSWindow), allocated objects are not
1009 // self-owned.
1010
1011 RetainSummary *NSWindowSumm =
1012 getPersistentSummary(RetEffect::MakeReceiverAlias(), SelfOwn);
Ted Kremenek272aa852008-06-25 21:21:56 +00001013
1014 // Create the "initWithContentRect:styleMask:backing:defer:" selector.
Ted Kremenek6fbecac2008-07-18 17:39:56 +00001015 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenek272aa852008-06-25 21:21:56 +00001016 II.push_back(&Ctx.Idents.get("initWithContentRect"));
1017 II.push_back(&Ctx.Idents.get("styleMask"));
1018 II.push_back(&Ctx.Idents.get("backing"));
1019 II.push_back(&Ctx.Idents.get("defer"));
1020 Selector S = Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremeneke44927e2008-07-01 17:21:27 +00001021 addNSWindowMethSummary(S, NSWindowSumm);
1022 addNSPanelMethSummary(S, InitSumm);
1023
Ted Kremenek272aa852008-06-25 21:21:56 +00001024 // Create the "initWithContentRect:styleMask:backing:defer:screen:" selector.
1025 II.push_back(&Ctx.Idents.get("screen"));
1026 S = Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremeneke44927e2008-07-01 17:21:27 +00001027 addNSWindowMethSummary(S, NSWindowSumm);
1028 addNSPanelMethSummary(S, InitSumm);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001029
1030 // Create NSAssertionHandler summaries.
1031 II.clear();
1032 II.push_back(&Ctx.Idents.get("handleFailureInFunction"));
1033 II.push_back(&Ctx.Idents.get("file"));
1034 II.push_back(&Ctx.Idents.get("lineNumber"));
1035 II.push_back(&Ctx.Idents.get("description"));
1036 S = Ctx.Selectors.getSelector(II.size(), &II[0]);
1037 addPanicSummary(NSAssertionHandlerII, S);
1038
1039 II.clear();
1040 II.push_back(&Ctx.Idents.get("handleFailureInMethod"));
Ted Kremenek65259c92008-07-24 18:47:16 +00001041 II.push_back(&Ctx.Idents.get("object"));
Ted Kremenekf2717b02008-07-18 17:24:20 +00001042 II.push_back(&Ctx.Idents.get("file"));
1043 II.push_back(&Ctx.Idents.get("lineNumber"));
1044 II.push_back(&Ctx.Idents.get("description"));
1045 S = Ctx.Selectors.getSelector(II.size(), &II[0]);
1046 addPanicSummary(NSAssertionHandlerII, S);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001047}
1048
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001049//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001050// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001051//===----------------------------------------------------------------------===//
1052
Ted Kremeneka7338b42008-03-11 06:39:11 +00001053namespace {
1054
Ted Kremenek7d421f32008-04-09 23:49:11 +00001055class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001056public:
Ted Kremenek0d721572008-03-11 17:48:22 +00001057
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001058 enum Kind {
1059 Owned = 0, // Owning reference.
1060 NotOwned, // Reference is not owned by still valid (not freed).
1061 Released, // Object has been released.
1062 ReturnedOwned, // Returned object passes ownership to caller.
1063 ReturnedNotOwned, // Return object does not pass ownership to caller.
1064 ErrorUseAfterRelease, // Object used after released.
1065 ErrorReleaseNotOwned, // Release of an object that was not owned.
1066 ErrorLeak // A memory leak due to excessive reference counts.
1067 };
Ted Kremenek0d721572008-03-11 17:48:22 +00001068
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001069private:
1070
1071 Kind kind;
1072 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001073 QualType T;
1074
1075 RefVal(Kind k, unsigned cnt, QualType t) : kind(k), Cnt(cnt), T(t) {}
1076 RefVal(Kind k, unsigned cnt = 0) : kind(k), Cnt(cnt) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001077
1078public:
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001079
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001080 Kind getKind() const { return kind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001081
Ted Kremenek272aa852008-06-25 21:21:56 +00001082 unsigned getCount() const { return Cnt; }
1083 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001084
1085 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001086
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001087 static bool isError(Kind k) { return k >= ErrorUseAfterRelease; }
1088
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001089 static bool isLeak(Kind k) { return k == ErrorLeak; }
1090
Ted Kremenekffefc352008-04-11 22:25:11 +00001091 bool isOwned() const {
1092 return getKind() == Owned;
1093 }
1094
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001095 bool isNotOwned() const {
1096 return getKind() == NotOwned;
1097 }
1098
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001099 bool isReturnedOwned() const {
1100 return getKind() == ReturnedOwned;
1101 }
1102
1103 bool isReturnedNotOwned() const {
1104 return getKind() == ReturnedNotOwned;
1105 }
1106
1107 bool isNonLeakError() const {
1108 Kind k = getKind();
1109 return isError(k) && !isLeak(k);
1110 }
1111
1112 // State creation: normal state.
1113
Ted Kremenek272aa852008-06-25 21:21:56 +00001114 static RefVal makeOwned(QualType t, unsigned Count = 1) {
1115 return RefVal(Owned, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001116 }
1117
Ted Kremenek272aa852008-06-25 21:21:56 +00001118 static RefVal makeNotOwned(QualType t, unsigned Count = 0) {
1119 return RefVal(NotOwned, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001120 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001121
1122 static RefVal makeReturnedOwned(unsigned Count) {
1123 return RefVal(ReturnedOwned, Count);
1124 }
1125
1126 static RefVal makeReturnedNotOwned() {
1127 return RefVal(ReturnedNotOwned);
1128 }
1129
1130 // State creation: errors.
Ted Kremenek272aa852008-06-25 21:21:56 +00001131
1132#if 0
Ted Kremenek9363fd92008-05-05 17:53:17 +00001133 static RefVal makeLeak(unsigned Count) { return RefVal(ErrorLeak, Count); }
Ted Kremenek0d721572008-03-11 17:48:22 +00001134 static RefVal makeReleased() { return RefVal(Released); }
1135 static RefVal makeUseAfterRelease() { return RefVal(ErrorUseAfterRelease); }
1136 static RefVal makeReleaseNotOwned() { return RefVal(ErrorReleaseNotOwned); }
Ted Kremenek272aa852008-06-25 21:21:56 +00001137#endif
1138
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001139 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001140
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001141 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001142 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001143 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001144
Ted Kremenek272aa852008-06-25 21:21:56 +00001145 RefVal operator-(size_t i) const {
1146 return RefVal(getKind(), getCount() - i, getType());
1147 }
1148
1149 RefVal operator+(size_t i) const {
1150 return RefVal(getKind(), getCount() + i, getType());
1151 }
1152
1153 RefVal operator^(Kind k) const {
1154 return RefVal(k, getCount(), getType());
1155 }
1156
1157
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001158 void Profile(llvm::FoldingSetNodeID& ID) const {
1159 ID.AddInteger((unsigned) kind);
1160 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001161 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001162 }
1163
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001164 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001165};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001166
1167void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001168 if (!T.isNull())
1169 Out << "Tracked Type:" << T.getAsString() << '\n';
1170
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001171 switch (getKind()) {
1172 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001173 case Owned: {
1174 Out << "Owned";
1175 unsigned cnt = getCount();
1176 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001177 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001178 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001179
Ted Kremenekc4f81022008-04-10 23:09:18 +00001180 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001181 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001182 unsigned cnt = getCount();
1183 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001184 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001185 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001186
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001187 case ReturnedOwned: {
1188 Out << "ReturnedOwned";
1189 unsigned cnt = getCount();
1190 if (cnt) Out << " (+ " << cnt << ")";
1191 break;
1192 }
1193
1194 case ReturnedNotOwned: {
1195 Out << "ReturnedNotOwned";
1196 unsigned cnt = getCount();
1197 if (cnt) Out << " (+ " << cnt << ")";
1198 break;
1199 }
1200
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001201 case Released:
1202 Out << "Released";
1203 break;
1204
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001205 case ErrorLeak:
1206 Out << "Leaked";
1207 break;
1208
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001209 case ErrorUseAfterRelease:
1210 Out << "Use-After-Release [ERROR]";
1211 break;
1212
1213 case ErrorReleaseNotOwned:
1214 Out << "Release of Not-Owned [ERROR]";
1215 break;
1216 }
1217}
Ted Kremenek0d721572008-03-11 17:48:22 +00001218
Ted Kremenek7aef4842008-04-16 20:40:59 +00001219//===----------------------------------------------------------------------===//
1220// Transfer functions.
1221//===----------------------------------------------------------------------===//
1222
Ted Kremenek7d421f32008-04-09 23:49:11 +00001223class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001224public:
Ted Kremenek272aa852008-06-25 21:21:56 +00001225 // Type definitions.
Ted Kremenek0d721572008-03-11 17:48:22 +00001226 typedef llvm::ImmutableMap<SymbolID, RefVal> RefBindings;
Ted Kremenek272aa852008-06-25 21:21:56 +00001227
Ted Kremeneka7338b42008-03-11 06:39:11 +00001228 typedef RefBindings::Factory RefBFactoryTy;
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001229
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001230 typedef llvm::DenseMap<GRExprEngine::NodeTy*,std::pair<Expr*, SymbolID> >
1231 ReleasesNotOwnedTy;
1232
1233 typedef ReleasesNotOwnedTy UseAfterReleasesTy;
1234
1235 typedef llvm::DenseMap<GRExprEngine::NodeTy*, std::vector<SymbolID>*>
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001236 LeaksTy;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001237
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001238 class BindingsPrinter : public ValueState::CheckerStatePrinter {
1239 public:
1240 virtual void PrintCheckerState(std::ostream& Out, void* State,
1241 const char* nl, const char* sep);
1242 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001243
1244private:
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001245 // Instance variables.
1246
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001247 RetainSummaryManager Summaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001248 const LangOptions& LOpts;
1249 RefBFactoryTy RefBFactory;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001250
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001251 UseAfterReleasesTy UseAfterReleases;
1252 ReleasesNotOwnedTy ReleasesNotOwned;
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001253 LeaksTy Leaks;
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001254
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001255 BindingsPrinter Printer;
1256
Ted Kremenek1feab292008-04-16 04:28:53 +00001257 Selector RetainSelector;
1258 Selector ReleaseSelector;
Ted Kremenek3281a1f2008-05-01 02:18:37 +00001259 Selector AutoreleaseSelector;
Ted Kremenek1feab292008-04-16 04:28:53 +00001260
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001261public:
1262
Ted Kremenekf22f8682008-07-10 22:03:41 +00001263 static RefBindings GetRefBindings(const ValueState& StImpl) {
1264 return RefBindings((const RefBindings::TreeTy*) StImpl.CheckerState);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001265 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001266
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001267private:
1268
Ted Kremeneka7338b42008-03-11 06:39:11 +00001269 static void SetRefBindings(ValueState& StImpl, RefBindings B) {
1270 StImpl.CheckerState = B.getRoot();
1271 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001272
Ted Kremeneka7338b42008-03-11 06:39:11 +00001273 RefBindings Remove(RefBindings B, SymbolID sym) {
1274 return RefBFactory.Remove(B, sym);
1275 }
1276
Ted Kremenek0d721572008-03-11 17:48:22 +00001277 RefBindings Update(RefBindings B, SymbolID sym, RefVal V, ArgEffect E,
Ted Kremenek1feab292008-04-16 04:28:53 +00001278 RefVal::Kind& hasErr);
1279
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001280 void ProcessNonLeakError(ExplodedNodeSet<ValueState>& Dst,
1281 GRStmtNodeBuilder<ValueState>& Builder,
1282 Expr* NodeExpr, Expr* ErrorExpr,
1283 ExplodedNode<ValueState>* Pred,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001284 const ValueState* St,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001285 RefVal::Kind hasErr, SymbolID Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001286
Ted Kremenekf22f8682008-07-10 22:03:41 +00001287 const ValueState* HandleSymbolDeath(ValueStateManager& VMgr,
1288 const ValueState* St,
1289 SymbolID sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001290
Ted Kremenekf22f8682008-07-10 22:03:41 +00001291 const ValueState* NukeBinding(ValueStateManager& VMgr, const ValueState* St,
1292 SymbolID sid);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001293
1294public:
Ted Kremenek7aef4842008-04-16 20:40:59 +00001295
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001296 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001297 : Summaries(Ctx, gcenabled),
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001298 LOpts(lopts),
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +00001299 RetainSelector(GetNullarySelector("retain", Ctx)),
1300 ReleaseSelector(GetNullarySelector("release", Ctx)),
1301 AutoreleaseSelector(GetNullarySelector("autorelease", Ctx)) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001302
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001303 virtual ~CFRefCount() {
1304 for (LeaksTy::iterator I = Leaks.begin(), E = Leaks.end(); I!=E; ++I)
1305 delete I->second;
1306 }
Ted Kremenek7d421f32008-04-09 23:49:11 +00001307
1308 virtual void RegisterChecks(GRExprEngine& Eng);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001309
1310 virtual ValueState::CheckerStatePrinter* getCheckerStatePrinter() {
1311 return &Printer;
1312 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001313
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001314 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001315 const LangOptions& getLangOptions() const { return LOpts; }
1316
Ted Kremeneka7338b42008-03-11 06:39:11 +00001317 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001318
1319 void EvalSummary(ExplodedNodeSet<ValueState>& Dst,
1320 GRExprEngine& Eng,
1321 GRStmtNodeBuilder<ValueState>& Builder,
1322 Expr* Ex,
1323 Expr* Receiver,
1324 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001325 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001326 ExplodedNode<ValueState>* Pred);
1327
Ted Kremeneka7338b42008-03-11 06:39:11 +00001328 virtual void EvalCall(ExplodedNodeSet<ValueState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001329 GRExprEngine& Eng,
Ted Kremeneka7338b42008-03-11 06:39:11 +00001330 GRStmtNodeBuilder<ValueState>& Builder,
Ted Kremenek0a6a80b2008-04-23 20:12:28 +00001331 CallExpr* CE, RVal L,
Ted Kremeneka7338b42008-03-11 06:39:11 +00001332 ExplodedNode<ValueState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001333
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001334
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001335 virtual void EvalObjCMessageExpr(ExplodedNodeSet<ValueState>& Dst,
1336 GRExprEngine& Engine,
1337 GRStmtNodeBuilder<ValueState>& Builder,
1338 ObjCMessageExpr* ME,
1339 ExplodedNode<ValueState>* Pred);
1340
1341 bool EvalObjCMessageExprAux(ExplodedNodeSet<ValueState>& Dst,
1342 GRExprEngine& Engine,
1343 GRStmtNodeBuilder<ValueState>& Builder,
1344 ObjCMessageExpr* ME,
1345 ExplodedNode<ValueState>* Pred);
1346
Ted Kremenek7aef4842008-04-16 20:40:59 +00001347 // Stores.
1348
1349 virtual void EvalStore(ExplodedNodeSet<ValueState>& Dst,
1350 GRExprEngine& Engine,
1351 GRStmtNodeBuilder<ValueState>& Builder,
1352 Expr* E, ExplodedNode<ValueState>* Pred,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001353 const ValueState* St, RVal TargetLV, RVal Val);
Ted Kremenekffefc352008-04-11 22:25:11 +00001354 // End-of-path.
1355
1356 virtual void EvalEndPath(GRExprEngine& Engine,
1357 GREndPathNodeBuilder<ValueState>& Builder);
1358
Ted Kremenek541db372008-04-24 23:57:27 +00001359 virtual void EvalDeadSymbols(ExplodedNodeSet<ValueState>& Dst,
1360 GRExprEngine& Engine,
1361 GRStmtNodeBuilder<ValueState>& Builder,
Ted Kremenekac91ce92008-04-25 01:25:15 +00001362 ExplodedNode<ValueState>* Pred,
1363 Stmt* S,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001364 const ValueState* St,
Ted Kremenek541db372008-04-24 23:57:27 +00001365 const ValueStateManager::DeadSymbolsTy& Dead);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001366 // Return statements.
1367
1368 virtual void EvalReturn(ExplodedNodeSet<ValueState>& Dst,
1369 GRExprEngine& Engine,
1370 GRStmtNodeBuilder<ValueState>& Builder,
1371 ReturnStmt* S,
1372 ExplodedNode<ValueState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001373
1374 // Assumptions.
1375
Ted Kremenek76d31662008-07-17 23:33:10 +00001376 virtual const ValueState* EvalAssume(ValueStateManager& VMgr,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001377 const ValueState* St, RVal Cond,
1378 bool Assumption, bool& isFeasible);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001379
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001380 // Error iterators.
1381
1382 typedef UseAfterReleasesTy::iterator use_after_iterator;
1383 typedef ReleasesNotOwnedTy::iterator bad_release_iterator;
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00001384 typedef LeaksTy::iterator leaks_iterator;
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001385
Ted Kremenek7d421f32008-04-09 23:49:11 +00001386 use_after_iterator use_after_begin() { return UseAfterReleases.begin(); }
1387 use_after_iterator use_after_end() { return UseAfterReleases.end(); }
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001388
Ted Kremenek7d421f32008-04-09 23:49:11 +00001389 bad_release_iterator bad_release_begin() { return ReleasesNotOwned.begin(); }
1390 bad_release_iterator bad_release_end() { return ReleasesNotOwned.end(); }
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00001391
1392 leaks_iterator leaks_begin() { return Leaks.begin(); }
1393 leaks_iterator leaks_end() { return Leaks.end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001394};
1395
1396} // end anonymous namespace
1397
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001398
Ted Kremenek7d421f32008-04-09 23:49:11 +00001399
1400
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001401void CFRefCount::BindingsPrinter::PrintCheckerState(std::ostream& Out,
1402 void* State, const char* nl,
1403 const char* sep) {
1404 RefBindings B((RefBindings::TreeTy*) State);
1405
1406 if (State)
1407 Out << sep << nl;
1408
1409 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1410 Out << (*I).first << " : ";
1411 (*I).second.print(Out);
1412 Out << nl;
1413 }
1414}
1415
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001416static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001417 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenek455dd862008-04-11 20:23:24 +00001418}
1419
Ted Kremenek266d8b62008-05-06 02:26:56 +00001420static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1421 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenek455dd862008-04-11 20:23:24 +00001422}
1423
Ted Kremenek227c5372008-05-06 02:41:27 +00001424static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1425 return Summ ? Summ->getReceiverEffect() : DoNothing;
1426}
1427
Ted Kremenekf2717b02008-07-18 17:24:20 +00001428static inline bool IsEndPath(RetainSummary* Summ) {
1429 return Summ ? Summ->isEndPath() : false;
1430}
1431
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001432void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<ValueState>& Dst,
1433 GRStmtNodeBuilder<ValueState>& Builder,
1434 Expr* NodeExpr, Expr* ErrorExpr,
1435 ExplodedNode<ValueState>* Pred,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001436 const ValueState* St,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001437 RefVal::Kind hasErr, SymbolID Sym) {
Ted Kremenek1feab292008-04-16 04:28:53 +00001438 Builder.BuildSinks = true;
1439 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
1440
1441 if (!N) return;
1442
1443 switch (hasErr) {
1444 default: assert(false);
1445 case RefVal::ErrorUseAfterRelease:
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001446 UseAfterReleases[N] = std::make_pair(ErrorExpr, Sym);
Ted Kremenek1feab292008-04-16 04:28:53 +00001447 break;
1448
1449 case RefVal::ErrorReleaseNotOwned:
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001450 ReleasesNotOwned[N] = std::make_pair(ErrorExpr, Sym);
Ted Kremenek1feab292008-04-16 04:28:53 +00001451 break;
1452 }
1453}
1454
Ted Kremenek272aa852008-06-25 21:21:56 +00001455/// GetReturnType - Used to get the return type of a message expression or
1456/// function call with the intention of affixing that type to a tracked symbol.
1457/// While the the return type can be queried directly from RetEx, when
1458/// invoking class methods we augment to the return type to be that of
1459/// a pointer to the class (as opposed it just being id).
1460static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1461
1462 QualType RetTy = RetE->getType();
1463
1464 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00001465 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001466 if (!PT)
1467 return RetTy;
1468
1469 // If RetEx is not a message expression just return its type.
1470 // If RetEx is a message expression, return its types if it is something
1471 /// more specific than id.
1472
1473 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1474
1475 if (!ME || !Ctx.isObjCIdType(PT->getPointeeType()))
1476 return RetTy;
1477
1478 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1479
1480 // At this point we know the return type of the message expression is id.
1481 // If we have an ObjCInterceDecl, we know this is a call to a class method
1482 // whose type we can resolve. In such cases, promote the return type to
1483 // Class*.
1484 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1485}
1486
1487
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001488void CFRefCount::EvalSummary(ExplodedNodeSet<ValueState>& Dst,
1489 GRExprEngine& Eng,
1490 GRStmtNodeBuilder<ValueState>& Builder,
1491 Expr* Ex,
1492 Expr* Receiver,
1493 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001494 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001495 ExplodedNode<ValueState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001496
Ted Kremeneka7338b42008-03-11 06:39:11 +00001497 // Get the state.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001498 ValueStateManager& StateMgr = Eng.getStateManager();
Ted Kremenekf22f8682008-07-10 22:03:41 +00001499 const ValueState* St = Builder.GetState(Pred);
Ted Kremenek227c5372008-05-06 02:41:27 +00001500
1501 // Evaluate the effect of the arguments.
Ted Kremeneka7338b42008-03-11 06:39:11 +00001502 ValueState StVals = *St;
Ted Kremenek1feab292008-04-16 04:28:53 +00001503 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001504 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001505 Expr* ErrorExpr = NULL;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001506 SymbolID ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001507
Ted Kremenek2719e982008-06-17 02:43:46 +00001508 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremeneka7338b42008-03-11 06:39:11 +00001509
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001510 RVal V = StateMgr.GetRVal(St, *I);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001511
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001512 if (isa<lval::SymbolVal>(V)) {
1513 SymbolID Sym = cast<lval::SymbolVal>(V).getSymbol();
Ted Kremenek455dd862008-04-11 20:23:24 +00001514 RefBindings B = GetRefBindings(StVals);
1515
Ted Kremenek6064a362008-07-07 16:21:19 +00001516 if (RefBindings::data_type* T = B.lookup(Sym)) {
1517 B = Update(B, Sym, *T, GetArgE(Summ, idx), hasErr);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001518 SetRefBindings(StVals, B);
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001519
Ted Kremenek1feab292008-04-16 04:28:53 +00001520 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001521 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00001522 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001523 break;
1524 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001525 }
Ted Kremeneke4924202008-04-11 20:51:02 +00001526 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001527 else if (isa<LVal>(V)) {
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001528#if 0
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001529 // Nuke all arguments passed by reference.
Ted Kremenek455dd862008-04-11 20:23:24 +00001530 StateMgr.Unbind(StVals, cast<LVal>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001531#else
Ted Kremenekede40b72008-07-09 18:11:16 +00001532 if (lval::DeclVal* DV = dyn_cast<lval::DeclVal>(&V)) {
1533
1534 if (GetArgE(Summ, idx) == DoNothingByRef)
1535 continue;
1536
1537 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001538
1539 // FIXME: Either this logic should also be replicated in GRSimpleVals
1540 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00001541
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001542 // FIXME: We can have collisions on the conjured symbol if the
1543 // expression *I also creates conjured symbols. We probably want
1544 // to identify conjured symbols by an expression pair: the enclosing
1545 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00001546 // disambiguate conjured symbols.
1547
1548 // Is the invalidated variable something that we were tracking?
1549 RVal X = StateMgr.GetRVal(&StVals, *DV);
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001550
Ted Kremenekede40b72008-07-09 18:11:16 +00001551 if (isa<lval::SymbolVal>(X)) {
1552 SymbolID Sym = cast<lval::SymbolVal>(X).getSymbol();
1553 SetRefBindings(StVals,RefBFactory.Remove(GetRefBindings(StVals),Sym));
1554 }
1555
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001556 // Set the value of the variable to be a conjured symbol.
1557 unsigned Count = Builder.getCurrentBlockCount();
1558 SymbolID NewSym = Eng.getSymbolManager().getConjuredSymbol(*I, Count);
1559
Ted Kremenekf22f8682008-07-10 22:03:41 +00001560 StateMgr.SetRVal(StVals, *DV,
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001561 LVal::IsLValType(DV->getDecl()->getType())
1562 ? cast<RVal>(lval::SymbolVal(NewSym))
1563 : cast<RVal>(nonlval::SymbolVal(NewSym)));
1564 }
1565 else {
1566 // Nuke all other arguments passed by reference.
1567 StateMgr.Unbind(StVals, cast<LVal>(V));
1568 }
1569#endif
Ted Kremeneke4924202008-04-11 20:51:02 +00001570 }
Ted Kremenekbe621292008-04-22 21:39:21 +00001571 else if (isa<nonlval::LValAsInteger>(V))
1572 StateMgr.Unbind(StVals, cast<nonlval::LValAsInteger>(V).getLVal());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001573 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001574
Ted Kremenek272aa852008-06-25 21:21:56 +00001575 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00001576 if (!ErrorExpr && Receiver) {
1577 RVal V = StateMgr.GetRVal(St, Receiver);
1578
1579 if (isa<lval::SymbolVal>(V)) {
1580 SymbolID Sym = cast<lval::SymbolVal>(V).getSymbol();
1581 RefBindings B = GetRefBindings(StVals);
1582
Ted Kremenek6064a362008-07-07 16:21:19 +00001583 if (const RefVal* T = B.lookup(Sym)) {
1584 B = Update(B, Sym, *T, GetReceiverE(Summ), hasErr);
Ted Kremenek227c5372008-05-06 02:41:27 +00001585 SetRefBindings(StVals, B);
1586
1587 if (hasErr) {
1588 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00001589 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00001590 }
1591 }
1592 }
1593 }
1594
Ted Kremenek272aa852008-06-25 21:21:56 +00001595 // Get the persistent state.
Ted Kremenek1feab292008-04-16 04:28:53 +00001596 St = StateMgr.getPersistentState(StVals);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001597
Ted Kremenek272aa852008-06-25 21:21:56 +00001598 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00001599 if (hasErr) {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001600 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, St,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001601 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001602 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00001603 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001604
Ted Kremenekf2717b02008-07-18 17:24:20 +00001605 // Consult the summary for the return value.
Ted Kremenek266d8b62008-05-06 02:26:56 +00001606 RetEffect RE = GetRetEffect(Summ);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001607
1608 switch (RE.getKind()) {
1609 default:
1610 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001611
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001612 case RetEffect::NoRet:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001613
Ted Kremenek455dd862008-04-11 20:23:24 +00001614 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00001615 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
1616 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00001617
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001618 if (Ex->getType() != Eng.getContext().VoidTy) {
Ted Kremenek455dd862008-04-11 20:23:24 +00001619 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001620 SymbolID Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek455dd862008-04-11 20:23:24 +00001621
Ted Kremenek9e2c1ea2008-05-09 23:45:33 +00001622 RVal X = LVal::IsLValType(Ex->getType())
1623 ? cast<RVal>(lval::SymbolVal(Sym))
1624 : cast<RVal>(nonlval::SymbolVal(Sym));
Ted Kremenek455dd862008-04-11 20:23:24 +00001625
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001626 St = StateMgr.SetRVal(St, Ex, X, Eng.getCFG().isBlkExpr(Ex), false);
Ted Kremenek455dd862008-04-11 20:23:24 +00001627 }
1628
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001629 break;
1630
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001631 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00001632 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00001633 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001634 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenek2719e982008-06-17 02:43:46 +00001635 RVal V = StateMgr.GetRVal(St, *(arg_beg+idx));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001636 St = StateMgr.SetRVal(St, Ex, V, Eng.getCFG().isBlkExpr(Ex), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001637 break;
1638 }
1639
Ted Kremenek227c5372008-05-06 02:41:27 +00001640 case RetEffect::ReceiverAlias: {
1641 assert (Receiver);
1642 RVal V = StateMgr.GetRVal(St, Receiver);
1643 St = StateMgr.SetRVal(St, Ex, V, Eng.getCFG().isBlkExpr(Ex), false);
1644 break;
1645 }
1646
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001647 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001648 case RetEffect::OwnedSymbol: {
1649 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001650 SymbolID Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek272aa852008-06-25 21:21:56 +00001651 QualType RetT = GetReturnType(Ex, Eng.getContext());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001652
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001653 ValueState StImpl = *St;
1654 RefBindings B = GetRefBindings(StImpl);
Ted Kremenek272aa852008-06-25 21:21:56 +00001655 SetRefBindings(StImpl, RefBFactory.Add(B, Sym, RefVal::makeOwned(RetT)));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001656
1657 St = StateMgr.SetRVal(StateMgr.getPersistentState(StImpl),
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001658 Ex, lval::SymbolVal(Sym),
1659 Eng.getCFG().isBlkExpr(Ex), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001660
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001661 // FIXME: Add a flag to the checker where allocations are allowed to fail.
1662 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol)
1663 St = StateMgr.AddNE(St, Sym, Eng.getBasicVals().getZeroWithPtrWidth());
1664
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001665 break;
1666 }
1667
1668 case RetEffect::NotOwnedSymbol: {
1669 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001670 SymbolID Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek272aa852008-06-25 21:21:56 +00001671 QualType RetT = GetReturnType(Ex, Eng.getContext());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001672
1673 ValueState StImpl = *St;
1674 RefBindings B = GetRefBindings(StImpl);
Ted Kremenek272aa852008-06-25 21:21:56 +00001675 SetRefBindings(StImpl, RefBFactory.Add(B, Sym,
1676 RefVal::makeNotOwned(RetT)));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001677
1678 St = StateMgr.SetRVal(StateMgr.getPersistentState(StImpl),
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001679 Ex, lval::SymbolVal(Sym),
1680 Eng.getCFG().isBlkExpr(Ex), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001681
1682 break;
1683 }
1684 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001685
Ted Kremenekf2717b02008-07-18 17:24:20 +00001686 // Is this a sink?
1687 if (IsEndPath(Summ))
1688 Builder.MakeSinkNode(Dst, Ex, Pred, St);
1689 else
1690 Builder.MakeNode(Dst, Ex, Pred, St);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001691}
1692
1693
1694void CFRefCount::EvalCall(ExplodedNodeSet<ValueState>& Dst,
1695 GRExprEngine& Eng,
1696 GRStmtNodeBuilder<ValueState>& Builder,
1697 CallExpr* CE, RVal L,
1698 ExplodedNode<ValueState>* Pred) {
1699
1700
1701 RetainSummary* Summ = NULL;
1702
1703 // Get the summary.
1704
1705 if (isa<lval::FuncVal>(L)) {
1706 lval::FuncVal FV = cast<lval::FuncVal>(L);
1707 FunctionDecl* FD = FV.getDecl();
Ted Kremenekd13c1872008-06-24 03:56:45 +00001708 Summ = Summaries.getSummary(FD);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001709 }
1710
1711 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
1712 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00001713}
Ted Kremeneka7338b42008-03-11 06:39:11 +00001714
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001715
1716void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<ValueState>& Dst,
1717 GRExprEngine& Eng,
1718 GRStmtNodeBuilder<ValueState>& Builder,
1719 ObjCMessageExpr* ME,
1720 ExplodedNode<ValueState>* Pred) {
1721
Ted Kremenek926abf22008-05-06 04:20:12 +00001722 RetainSummary* Summ;
Ted Kremenek33661802008-05-01 21:31:50 +00001723
Ted Kremenek272aa852008-06-25 21:21:56 +00001724 if (Expr* Receiver = ME->getReceiver()) {
1725 // We need the type-information of the tracked receiver object
1726 // Retrieve it from the state.
1727 ObjCInterfaceDecl* ID = 0;
1728
1729 // FIXME: Wouldn't it be great if this code could be reduced? It's just
1730 // a chain of lookups.
Ted Kremenekf22f8682008-07-10 22:03:41 +00001731 const ValueState* St = Builder.GetState(Pred);
Ted Kremenek272aa852008-06-25 21:21:56 +00001732 RVal V = Eng.getStateManager().GetRVal(St, Receiver );
1733
1734 if (isa<lval::SymbolVal>(V)) {
1735 SymbolID Sym = cast<lval::SymbolVal>(V).getSymbol();
1736
Ted Kremenek6064a362008-07-07 16:21:19 +00001737 if (const RefVal* T = GetRefBindings(*St).lookup(Sym)) {
1738 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001739
1740 if (const PointerType* PT = Ty->getAsPointerType()) {
1741 QualType PointeeTy = PT->getPointeeType();
1742
1743 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
1744 ID = IT->getDecl();
1745 }
1746 }
1747 }
1748
1749 Summ = Summaries.getMethodSummary(ME, ID);
1750 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001751 else
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001752 Summ = Summaries.getClassMethodSummary(ME->getClassName(),
1753 ME->getSelector());
Ted Kremenek1feab292008-04-16 04:28:53 +00001754
Ted Kremenek926abf22008-05-06 04:20:12 +00001755 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
1756 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001757}
Ted Kremenek926abf22008-05-06 04:20:12 +00001758
Ted Kremenek7aef4842008-04-16 20:40:59 +00001759// Stores.
1760
1761void CFRefCount::EvalStore(ExplodedNodeSet<ValueState>& Dst,
1762 GRExprEngine& Eng,
1763 GRStmtNodeBuilder<ValueState>& Builder,
1764 Expr* E, ExplodedNode<ValueState>* Pred,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001765 const ValueState* St, RVal TargetLV, RVal Val) {
Ted Kremenek7aef4842008-04-16 20:40:59 +00001766
1767 // Check if we have a binding for "Val" and if we are storing it to something
1768 // we don't understand or otherwise the value "escapes" the function.
1769
1770 if (!isa<lval::SymbolVal>(Val))
1771 return;
1772
1773 // Are we storing to something that causes the value to "escape"?
1774
1775 bool escapes = false;
1776
1777 if (!isa<lval::DeclVal>(TargetLV))
1778 escapes = true;
1779 else
1780 escapes = cast<lval::DeclVal>(TargetLV).getDecl()->hasGlobalStorage();
1781
1782 if (!escapes)
1783 return;
1784
1785 SymbolID Sym = cast<lval::SymbolVal>(Val).getSymbol();
Ted Kremenek7aef4842008-04-16 20:40:59 +00001786
Ted Kremenek6064a362008-07-07 16:21:19 +00001787 if (!GetRefBindings(*St).lookup(Sym))
Ted Kremenek7aef4842008-04-16 20:40:59 +00001788 return;
1789
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001790 // Nuke the binding.
1791 St = NukeBinding(Eng.getStateManager(), St, Sym);
Ted Kremenek7aef4842008-04-16 20:40:59 +00001792
1793 // Hand of the remaining logic to the parent implementation.
1794 GRSimpleVals::EvalStore(Dst, Eng, Builder, E, Pred, St, TargetLV, Val);
1795}
1796
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001797
Ted Kremenekf22f8682008-07-10 22:03:41 +00001798const ValueState* CFRefCount::NukeBinding(ValueStateManager& VMgr,
1799 const ValueState* St,
1800 SymbolID sid) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001801 ValueState StImpl = *St;
1802 RefBindings B = GetRefBindings(StImpl);
1803 StImpl.CheckerState = RefBFactory.Remove(B, sid).getRoot();
1804 return VMgr.getPersistentState(StImpl);
1805}
1806
Ted Kremenekffefc352008-04-11 22:25:11 +00001807// End-of-path.
1808
Ted Kremenekf22f8682008-07-10 22:03:41 +00001809const ValueState* CFRefCount::HandleSymbolDeath(ValueStateManager& VMgr,
1810 const ValueState* St, SymbolID sid,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001811 RefVal V, bool& hasLeak) {
1812
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001813 hasLeak = V.isOwned() ||
1814 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001815
1816 if (!hasLeak)
1817 return NukeBinding(VMgr, St, sid);
1818
1819 RefBindings B = GetRefBindings(*St);
Ted Kremenek272aa852008-06-25 21:21:56 +00001820 ValueState StImpl = *St;
1821 StImpl.CheckerState = RefBFactory.Add(B, sid, V^RefVal::ErrorLeak).getRoot();
Ted Kremenek9363fd92008-05-05 17:53:17 +00001822
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001823 return VMgr.getPersistentState(StImpl);
1824}
1825
1826void CFRefCount::EvalEndPath(GRExprEngine& Eng,
Ted Kremenekffefc352008-04-11 22:25:11 +00001827 GREndPathNodeBuilder<ValueState>& Builder) {
1828
Ted Kremenekf22f8682008-07-10 22:03:41 +00001829 const ValueState* St = Builder.getState();
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001830 RefBindings B = GetRefBindings(*St);
Ted Kremenekffefc352008-04-11 22:25:11 +00001831
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001832 llvm::SmallVector<SymbolID, 10> Leaked;
Ted Kremenekffefc352008-04-11 22:25:11 +00001833
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001834 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
1835 bool hasLeak = false;
Ted Kremenekffefc352008-04-11 22:25:11 +00001836
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001837 St = HandleSymbolDeath(Eng.getStateManager(), St,
1838 (*I).first, (*I).second, hasLeak);
1839
1840 if (hasLeak) Leaked.push_back((*I).first);
1841 }
Ted Kremenek541db372008-04-24 23:57:27 +00001842
1843 if (Leaked.empty())
1844 return;
1845
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001846 ExplodedNode<ValueState>* N = Builder.MakeNode(St);
Ted Kremenekcfc909d2008-04-18 16:30:14 +00001847
Ted Kremenek541db372008-04-24 23:57:27 +00001848 if (!N)
Ted Kremenekcfc909d2008-04-18 16:30:14 +00001849 return;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001850
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001851 std::vector<SymbolID>*& LeaksAtNode = Leaks[N];
1852 assert (!LeaksAtNode);
1853 LeaksAtNode = new std::vector<SymbolID>();
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001854
1855 for (llvm::SmallVector<SymbolID, 10>::iterator I=Leaked.begin(),
1856 E = Leaked.end(); I != E; ++I)
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001857 (*LeaksAtNode).push_back(*I);
Ted Kremenekffefc352008-04-11 22:25:11 +00001858}
1859
Ted Kremenek541db372008-04-24 23:57:27 +00001860// Dead symbols.
1861
1862void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<ValueState>& Dst,
1863 GRExprEngine& Eng,
1864 GRStmtNodeBuilder<ValueState>& Builder,
Ted Kremenekac91ce92008-04-25 01:25:15 +00001865 ExplodedNode<ValueState>* Pred,
1866 Stmt* S,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001867 const ValueState* St,
Ted Kremenek541db372008-04-24 23:57:27 +00001868 const ValueStateManager::DeadSymbolsTy& Dead) {
Ted Kremenekac91ce92008-04-25 01:25:15 +00001869
Ted Kremenek541db372008-04-24 23:57:27 +00001870 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
1871
1872 RefBindings B = GetRefBindings(*St);
1873 llvm::SmallVector<SymbolID, 10> Leaked;
1874
1875 for (ValueStateManager::DeadSymbolsTy::const_iterator
1876 I=Dead.begin(), E=Dead.end(); I!=E; ++I) {
1877
Ted Kremenek6064a362008-07-07 16:21:19 +00001878 const RefVal* T = B.lookup(*I);
Ted Kremenek541db372008-04-24 23:57:27 +00001879
1880 if (!T)
1881 continue;
1882
1883 bool hasLeak = false;
1884
Ted Kremenek6064a362008-07-07 16:21:19 +00001885 St = HandleSymbolDeath(Eng.getStateManager(), St, *I, *T, hasLeak);
Ted Kremenek541db372008-04-24 23:57:27 +00001886
Ted Kremenek6064a362008-07-07 16:21:19 +00001887 if (hasLeak)
1888 Leaked.push_back(*I);
Ted Kremenek541db372008-04-24 23:57:27 +00001889 }
1890
1891 if (Leaked.empty())
1892 return;
1893
1894 ExplodedNode<ValueState>* N = Builder.MakeNode(Dst, S, Pred, St);
1895
1896 if (!N)
1897 return;
1898
1899 std::vector<SymbolID>*& LeaksAtNode = Leaks[N];
1900 assert (!LeaksAtNode);
1901 LeaksAtNode = new std::vector<SymbolID>();
1902
1903 for (llvm::SmallVector<SymbolID, 10>::iterator I=Leaked.begin(),
1904 E = Leaked.end(); I != E; ++I)
1905 (*LeaksAtNode).push_back(*I);
1906}
1907
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001908 // Return statements.
1909
1910void CFRefCount::EvalReturn(ExplodedNodeSet<ValueState>& Dst,
1911 GRExprEngine& Eng,
1912 GRStmtNodeBuilder<ValueState>& Builder,
1913 ReturnStmt* S,
1914 ExplodedNode<ValueState>* Pred) {
1915
1916 Expr* RetE = S->getRetValue();
1917 if (!RetE) return;
1918
1919 ValueStateManager& StateMgr = Eng.getStateManager();
Ted Kremenekf22f8682008-07-10 22:03:41 +00001920 const ValueState* St = Builder.GetState(Pred);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001921 RVal V = StateMgr.GetRVal(St, RetE);
1922
1923 if (!isa<lval::SymbolVal>(V))
1924 return;
1925
1926 // Get the reference count binding (if any).
1927 SymbolID Sym = cast<lval::SymbolVal>(V).getSymbol();
1928 RefBindings B = GetRefBindings(*St);
Ted Kremenek6064a362008-07-07 16:21:19 +00001929 const RefVal* T = B.lookup(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001930
1931 if (!T)
1932 return;
1933
1934 // Change the reference count.
1935
Ted Kremenek6064a362008-07-07 16:21:19 +00001936 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001937
1938 switch (X.getKind()) {
1939
1940 case RefVal::Owned: {
1941 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001942 assert (cnt > 0);
1943 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001944 break;
1945 }
1946
1947 case RefVal::NotOwned: {
1948 unsigned cnt = X.getCount();
1949 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
1950 : RefVal::makeReturnedNotOwned();
1951 break;
1952 }
1953
1954 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001955 return;
1956 }
1957
1958 // Update the binding.
1959
1960 ValueState StImpl = *St;
1961 StImpl.CheckerState = RefBFactory.Add(B, Sym, X).getRoot();
1962 Builder.MakeNode(Dst, S, Pred, StateMgr.getPersistentState(StImpl));
1963}
1964
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001965// Assumptions.
1966
Ted Kremenek76d31662008-07-17 23:33:10 +00001967const ValueState* CFRefCount::EvalAssume(ValueStateManager& VMgr,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001968 const ValueState* St,
1969 RVal Cond, bool Assumption,
1970 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001971
1972 // FIXME: We may add to the interface of EvalAssume the list of symbols
1973 // whose assumptions have changed. For now we just iterate through the
1974 // bindings and check if any of the tracked symbols are NULL. This isn't
1975 // too bad since the number of symbols we will track in practice are
1976 // probably small and EvalAssume is only called at branches and a few
1977 // other places.
1978
1979 RefBindings B = GetRefBindings(*St);
1980
1981 if (B.isEmpty())
1982 return St;
1983
1984 bool changed = false;
1985
1986 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1987
1988 // Check if the symbol is null (or equal to any constant).
1989 // If this is the case, stop tracking the symbol.
1990
1991 if (St->getSymVal(I.getKey())) {
1992 changed = true;
1993 B = RefBFactory.Remove(B, I.getKey());
1994 }
1995 }
1996
1997 if (!changed)
1998 return St;
1999
2000 ValueState StImpl = *St;
2001 StImpl.CheckerState = B.getRoot();
Ted Kremenek76d31662008-07-17 23:33:10 +00002002 return VMgr.getPersistentState(StImpl);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002003}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002004
2005CFRefCount::RefBindings CFRefCount::Update(RefBindings B, SymbolID sym,
Ted Kremenek0d721572008-03-11 17:48:22 +00002006 RefVal V, ArgEffect E,
Ted Kremenek1feab292008-04-16 04:28:53 +00002007 RefVal::Kind& hasErr) {
Ted Kremeneka7338b42008-03-11 06:39:11 +00002008
Ted Kremenek0d721572008-03-11 17:48:22 +00002009 // FIXME: This dispatch can potentially be sped up by unifiying it into
2010 // a single switch statement. Opt for simplicity for now.
Ted Kremeneka7338b42008-03-11 06:39:11 +00002011
Ted Kremenek0d721572008-03-11 17:48:22 +00002012 switch (E) {
2013 default:
2014 assert (false && "Unhandled CFRef transition.");
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002015
2016 case MayEscape:
2017 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00002018 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002019 break;
2020 }
2021
2022 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00002023
Ted Kremenekede40b72008-07-09 18:11:16 +00002024 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00002025 case DoNothing:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002026 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
Ted Kremenek272aa852008-06-25 21:21:56 +00002027 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00002028 hasErr = V.getKind();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002029 break;
2030 }
2031
Ted Kremenek0d721572008-03-11 17:48:22 +00002032 return B;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00002033
Ted Kremenek4e1d22f2008-07-01 00:01:02 +00002034 case Autorelease:
Ted Kremenek227c5372008-05-06 02:41:27 +00002035 case StopTracking:
2036 return RefBFactory.Remove(B, sym);
2037
Ted Kremenek0d721572008-03-11 17:48:22 +00002038 case IncRef:
2039 switch (V.getKind()) {
2040 default:
2041 assert(false);
2042
2043 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00002044 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00002045 V = V + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00002046 break;
2047
2048 case RefVal::Released:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002049 if (isGCEnabled())
Ted Kremenek272aa852008-06-25 21:21:56 +00002050 V = V ^ RefVal::Owned;
Ted Kremeneke2dd9572008-04-29 05:44:10 +00002051 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00002052 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremeneke2dd9572008-04-29 05:44:10 +00002053 hasErr = V.getKind();
2054 }
2055
Ted Kremenek0d721572008-03-11 17:48:22 +00002056 break;
2057 }
2058
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002059 break;
2060
Ted Kremenek272aa852008-06-25 21:21:56 +00002061 case SelfOwn:
2062 V = V ^ RefVal::NotOwned;
2063
Ted Kremenek0d721572008-03-11 17:48:22 +00002064 case DecRef:
2065 switch (V.getKind()) {
2066 default:
2067 assert (false);
2068
Ted Kremenek272aa852008-06-25 21:21:56 +00002069 case RefVal::Owned:
2070 V = V.getCount() > 1 ? V - 1 : V ^ RefVal::Released;
Ted Kremenek0d721572008-03-11 17:48:22 +00002071 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002072
Ted Kremenek272aa852008-06-25 21:21:56 +00002073 case RefVal::NotOwned:
2074 if (V.getCount() > 0)
2075 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00002076 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00002077 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00002078 hasErr = V.getKind();
Ted Kremenekc4f81022008-04-10 23:09:18 +00002079 }
2080
Ted Kremenek0d721572008-03-11 17:48:22 +00002081 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002082
2083 case RefVal::Released:
Ted Kremenek272aa852008-06-25 21:21:56 +00002084 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00002085 hasErr = V.getKind();
Ted Kremenek0d721572008-03-11 17:48:22 +00002086 break;
2087 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002088
2089 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002090 }
2091
2092 return RefBFactory.Add(B, sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00002093}
2094
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002095
2096//===----------------------------------------------------------------------===//
Ted Kremenek7d421f32008-04-09 23:49:11 +00002097// Error reporting.
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002098//===----------------------------------------------------------------------===//
2099
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002100namespace {
2101
2102 //===-------------===//
2103 // Bug Descriptions. //
2104 //===-------------===//
2105
Ted Kremeneke3769852008-04-18 20:54:29 +00002106 class VISIBILITY_HIDDEN CFRefBug : public BugTypeCacheLocation {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002107 protected:
2108 CFRefCount& TF;
2109
2110 public:
2111 CFRefBug(CFRefCount& tf) : TF(tf) {}
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002112
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002113 CFRefCount& getTF() { return TF; }
Ted Kremenek0ff3f202008-05-05 23:16:31 +00002114 const CFRefCount& getTF() const { return TF; }
2115
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002116 virtual bool isLeak() const { return false; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002117 };
2118
2119 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2120 public:
2121 UseAfterRelease(CFRefCount& tf) : CFRefBug(tf) {}
2122
2123 virtual const char* getName() const {
Ted Kremenek0ff3f202008-05-05 23:16:31 +00002124 return "Use-After-Release";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002125 }
2126 virtual const char* getDescription() const {
Ted Kremeneka8503952008-04-18 04:55:01 +00002127 return "Reference-counted object is used"
2128 " after it is released.";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002129 }
2130
2131 virtual void EmitWarnings(BugReporter& BR);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002132 };
2133
2134 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2135 public:
2136 BadRelease(CFRefCount& tf) : CFRefBug(tf) {}
2137
2138 virtual const char* getName() const {
Ted Kremenek0ff3f202008-05-05 23:16:31 +00002139 return "Bad Release";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002140 }
2141 virtual const char* getDescription() const {
2142 return "Incorrect decrement of the reference count of a "
Ted Kremeneka8503952008-04-18 04:55:01 +00002143 "CoreFoundation object: "
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002144 "The object is not owned at this point by the caller.";
2145 }
2146
2147 virtual void EmitWarnings(BugReporter& BR);
2148 };
2149
2150 class VISIBILITY_HIDDEN Leak : public CFRefBug {
2151 public:
2152 Leak(CFRefCount& tf) : CFRefBug(tf) {}
2153
2154 virtual const char* getName() const {
Ted Kremenekb3a44e72008-05-06 18:11:36 +00002155
2156 if (getTF().isGCEnabled())
2157 return "Memory Leak (GC)";
2158
2159 if (getTF().getLangOptions().getGCMode() == LangOptions::HybridGC)
2160 return "Memory Leak (Hybrid MM, non-GC)";
2161
2162 assert (getTF().getLangOptions().getGCMode() == LangOptions::NonGC);
2163 return "Memory Leak";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002164 }
2165
2166 virtual const char* getDescription() const {
Ted Kremeneka8503952008-04-18 04:55:01 +00002167 return "Object leaked.";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002168 }
2169
2170 virtual void EmitWarnings(BugReporter& BR);
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002171 virtual void GetErrorNodes(std::vector<ExplodedNode<ValueState>*>& Nodes);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002172 virtual bool isLeak() const { return true; }
Ted Kremenekd7e26782008-05-16 18:33:44 +00002173 virtual bool isCached(BugReport& R);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002174 };
2175
2176 //===---------===//
2177 // Bug Reports. //
2178 //===---------===//
2179
2180 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
2181 SymbolID Sym;
2182 public:
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002183 CFRefReport(CFRefBug& D, ExplodedNode<ValueState> *n, SymbolID sym)
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002184 : RangedBugReport(D, n), Sym(sym) {}
2185
2186 virtual ~CFRefReport() {}
2187
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002188 CFRefBug& getBugType() {
2189 return (CFRefBug&) RangedBugReport::getBugType();
2190 }
2191 const CFRefBug& getBugType() const {
2192 return (const CFRefBug&) RangedBugReport::getBugType();
2193 }
2194
2195 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2196 const SourceRange*& end) {
2197
Ted Kremenek198cae02008-05-02 20:53:50 +00002198 if (!getBugType().isLeak())
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002199 RangedBugReport::getRanges(BR, beg, end);
2200 else {
2201 beg = 0;
2202 end = 0;
2203 }
2204 }
2205
Ted Kremenekd7e26782008-05-16 18:33:44 +00002206 SymbolID getSymbol() const { return Sym; }
2207
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002208 virtual PathDiagnosticPiece* getEndPath(BugReporter& BR,
2209 ExplodedNode<ValueState>* N);
2210
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002211 virtual std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002212
2213 virtual PathDiagnosticPiece* VisitNode(ExplodedNode<ValueState>* N,
2214 ExplodedNode<ValueState>* PrevN,
2215 ExplodedGraph<ValueState>& G,
2216 BugReporter& BR);
2217 };
2218
2219
2220} // end anonymous namespace
2221
2222void CFRefCount::RegisterChecks(GRExprEngine& Eng) {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002223 Eng.Register(new UseAfterRelease(*this));
2224 Eng.Register(new BadRelease(*this));
2225 Eng.Register(new Leak(*this));
2226}
2227
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002228
2229static const char* Msgs[] = {
2230 "Code is compiled in garbage collection only mode" // GC only
2231 " (the bug occurs with garbage collection enabled).",
2232
2233 "Code is compiled without garbage collection.", // No GC.
2234
2235 "Code is compiled for use with and without garbage collection (GC)."
2236 " The bug occurs with GC enabled.", // Hybrid, with GC.
2237
2238 "Code is compiled for use with and without garbage collection (GC)."
2239 " The bug occurs in non-GC mode." // Hyrbird, without GC/
2240};
2241
2242std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2243 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2244
2245 switch (TF.getLangOptions().getGCMode()) {
2246 default:
2247 assert(false);
Ted Kremenekcb4709402008-05-01 04:02:04 +00002248
2249 case LangOptions::GCOnly:
2250 assert (TF.isGCEnabled());
2251 return std::make_pair(&Msgs[0], &Msgs[0]+1);
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002252
2253 case LangOptions::NonGC:
2254 assert (!TF.isGCEnabled());
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002255 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2256
2257 case LangOptions::HybridGC:
2258 if (TF.isGCEnabled())
2259 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2260 else
2261 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2262 }
2263}
2264
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002265PathDiagnosticPiece* CFRefReport::VisitNode(ExplodedNode<ValueState>* N,
2266 ExplodedNode<ValueState>* PrevN,
2267 ExplodedGraph<ValueState>& G,
2268 BugReporter& BR) {
2269
2270 // Check if the type state has changed.
2271
Ted Kremenekf22f8682008-07-10 22:03:41 +00002272 const ValueState* PrevSt = PrevN->getState();
2273 const ValueState* CurrSt = N->getState();
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002274
2275 CFRefCount::RefBindings PrevB = CFRefCount::GetRefBindings(*PrevSt);
2276 CFRefCount::RefBindings CurrB = CFRefCount::GetRefBindings(*CurrSt);
2277
Ted Kremenek6064a362008-07-07 16:21:19 +00002278 const RefVal* PrevT = PrevB.lookup(Sym);
2279 const RefVal* CurrT = CurrB.lookup(Sym);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002280
Ted Kremeneka8503952008-04-18 04:55:01 +00002281 if (!CurrT)
2282 return NULL;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002283
Ted Kremeneka8503952008-04-18 04:55:01 +00002284 const char* Msg = NULL;
Ted Kremenek6064a362008-07-07 16:21:19 +00002285 const RefVal& CurrV = *CurrB.lookup(Sym);
Ted Kremenek9363fd92008-05-05 17:53:17 +00002286
Ted Kremeneka8503952008-04-18 04:55:01 +00002287 if (!PrevT) {
2288
Ted Kremenek9363fd92008-05-05 17:53:17 +00002289 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2290
2291 if (CurrV.isOwned()) {
2292
2293 if (isa<CallExpr>(S))
2294 Msg = "Function call returns an object with a +1 retain count"
2295 " (owning reference).";
2296 else {
2297 assert (isa<ObjCMessageExpr>(S));
2298 Msg = "Method returns an object with a +1 retain count"
2299 " (owning reference).";
2300 }
2301 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002302 else {
2303 assert (CurrV.isNotOwned());
Ted Kremenek9363fd92008-05-05 17:53:17 +00002304
2305 if (isa<CallExpr>(S))
2306 Msg = "Function call returns an object with a +0 retain count"
2307 " (non-owning reference).";
2308 else {
2309 assert (isa<ObjCMessageExpr>(S));
2310 Msg = "Method returns an object with a +0 retain count"
2311 " (non-owning reference).";
2312 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002313 }
Ted Kremenek9363fd92008-05-05 17:53:17 +00002314
Ted Kremeneka8503952008-04-18 04:55:01 +00002315 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
2316 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, Msg);
2317
2318 if (Expr* Exp = dyn_cast<Expr>(S))
2319 P->addRange(Exp->getSourceRange());
2320
2321 return P;
2322 }
2323
Ted Kremenek6064a362008-07-07 16:21:19 +00002324 // Determine if the typestate has changed.
2325 RefVal PrevV = *PrevB.lookup(Sym);
Ted Kremeneka8503952008-04-18 04:55:01 +00002326
2327 if (PrevV == CurrV)
2328 return NULL;
2329
2330 // The typestate has changed.
2331
2332 std::ostringstream os;
2333
2334 switch (CurrV.getKind()) {
2335 case RefVal::Owned:
2336 case RefVal::NotOwned:
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002337
2338 if (PrevV.getCount() == CurrV.getCount())
2339 return 0;
Ted Kremeneka8503952008-04-18 04:55:01 +00002340
2341 if (PrevV.getCount() > CurrV.getCount())
2342 os << "Reference count decremented.";
2343 else
2344 os << "Reference count incremented.";
2345
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002346 if (unsigned Count = CurrV.getCount()) {
Ted Kremenek9363fd92008-05-05 17:53:17 +00002347
2348 os << " Object has +" << Count;
Ted Kremenek752b5842008-04-18 05:32:44 +00002349
Ted Kremenek9363fd92008-05-05 17:53:17 +00002350 if (Count > 1)
2351 os << " retain counts.";
Ted Kremenek752b5842008-04-18 05:32:44 +00002352 else
Ted Kremenek9363fd92008-05-05 17:53:17 +00002353 os << " retain count.";
Ted Kremenek752b5842008-04-18 05:32:44 +00002354 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002355
2356 Msg = os.str().c_str();
2357
2358 break;
2359
2360 case RefVal::Released:
2361 Msg = "Object released.";
2362 break;
2363
2364 case RefVal::ReturnedOwned:
Ted Kremenek9363fd92008-05-05 17:53:17 +00002365 Msg = "Object returned to caller as owning reference (single retain count"
2366 " transferred to caller).";
Ted Kremeneka8503952008-04-18 04:55:01 +00002367 break;
2368
2369 case RefVal::ReturnedNotOwned:
Ted Kremenek9363fd92008-05-05 17:53:17 +00002370 Msg = "Object returned to caller with a +0 (non-owning) retain count.";
Ted Kremeneka8503952008-04-18 04:55:01 +00002371 break;
2372
2373 default:
2374 return NULL;
2375 }
2376
2377 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2378 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
2379 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, Msg);
2380
2381 // Add the range by scanning the children of the statement for any bindings
2382 // to Sym.
2383
Ted Kremenekba1c7ed2008-07-02 21:24:01 +00002384 ValueStateManager& VSM = cast<GRBugReporter>(BR).getStateManager();
Ted Kremeneka8503952008-04-18 04:55:01 +00002385
2386 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2387 if (Expr* Exp = dyn_cast_or_null<Expr>(*I)) {
2388 RVal X = VSM.GetRVal(CurrSt, Exp);
2389
2390 if (lval::SymbolVal* SV = dyn_cast<lval::SymbolVal>(&X))
2391 if (SV->getSymbol() == Sym) {
2392 P->addRange(Exp->getSourceRange()); break;
2393 }
2394 }
2395
2396 return P;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002397}
2398
Ted Kremenekd7e26782008-05-16 18:33:44 +00002399static std::pair<ExplodedNode<ValueState>*,VarDecl*>
2400GetAllocationSite(ExplodedNode<ValueState>* N, SymbolID Sym) {
2401
2402 typedef CFRefCount::RefBindings RefBindings;
2403 ExplodedNode<ValueState>* Last = N;
2404
2405 // Find the first node that referred to the tracked symbol. We also
2406 // try and find the first VarDecl the value was stored to.
2407
2408 VarDecl* FirstDecl = 0;
2409
2410 while (N) {
Ted Kremenekf22f8682008-07-10 22:03:41 +00002411 const ValueState* St = N->getState();
Ted Kremenekd7e26782008-05-16 18:33:44 +00002412 RefBindings B = RefBindings((RefBindings::TreeTy*) St->CheckerState);
Ted Kremenekd7e26782008-05-16 18:33:44 +00002413
Ted Kremenek6064a362008-07-07 16:21:19 +00002414 if (!B.lookup(Sym))
Ted Kremenekd7e26782008-05-16 18:33:44 +00002415 break;
2416
2417 VarDecl* VD = 0;
2418
2419 // Determine if there is an LVal binding to the symbol.
2420 for (ValueState::vb_iterator I=St->vb_begin(), E=St->vb_end(); I!=E; ++I) {
2421 if (!isa<lval::SymbolVal>(I->second) // Is the value a symbol?
2422 || cast<lval::SymbolVal>(I->second).getSymbol() != Sym)
2423 continue;
2424
2425 if (VD) { // Multiple decls map to this symbol.
2426 VD = 0;
2427 break;
2428 }
2429
2430 VD = I->first;
2431 }
2432
2433 if (VD) FirstDecl = VD;
2434
2435 Last = N;
2436 N = N->pred_empty() ? NULL : *(N->pred_begin());
2437 }
2438
2439 return std::make_pair(Last, FirstDecl);
2440}
Ted Kremenek4c479322008-05-06 23:07:13 +00002441
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002442PathDiagnosticPiece* CFRefReport::getEndPath(BugReporter& BR,
Ted Kremenekea794e92008-05-05 18:50:19 +00002443 ExplodedNode<ValueState>* EndN) {
Ted Kremenek86953652008-05-22 23:45:19 +00002444
2445 // Tell the BugReporter to report cases when the tracked symbol is
2446 // assigned to different variables, etc.
Ted Kremenekba1c7ed2008-07-02 21:24:01 +00002447 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002448
2449 if (!getBugType().isLeak())
Ted Kremenekea794e92008-05-05 18:50:19 +00002450 return RangedBugReport::getEndPath(BR, EndN);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002451
Ted Kremenek9363fd92008-05-05 17:53:17 +00002452 typedef CFRefCount::RefBindings RefBindings;
2453
2454 // Get the retain count.
Ted Kremenek9363fd92008-05-05 17:53:17 +00002455
Ted Kremenek6064a362008-07-07 16:21:19 +00002456 unsigned long RetCount =
2457 CFRefCount::GetRefBindings(*EndN->getState()).lookup(Sym)->getCount();
2458
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002459 // We are a leak. Walk up the graph to get to the first node where the
Ted Kremenekd7e26782008-05-16 18:33:44 +00002460 // symbol appeared, and also get the first VarDecl that tracked object
2461 // is stored to.
2462
2463 ExplodedNode<ValueState>* AllocNode = 0;
Ted Kremenek198cae02008-05-02 20:53:50 +00002464 VarDecl* FirstDecl = 0;
Ted Kremenekd7e26782008-05-16 18:33:44 +00002465 llvm::tie(AllocNode, FirstDecl) = GetAllocationSite(EndN, Sym);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002466
Ted Kremenekd7e26782008-05-16 18:33:44 +00002467 // Get the allocate site.
2468 assert (AllocNode);
2469 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002470
Ted Kremenekea794e92008-05-05 18:50:19 +00002471 SourceManager& SMgr = BR.getContext().getSourceManager();
2472 unsigned AllocLine = SMgr.getLogicalLineNumber(FirstStmt->getLocStart());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002473
Ted Kremenekea794e92008-05-05 18:50:19 +00002474 // Get the leak site. We may have multiple ExplodedNodes (one with the
2475 // leak) that occur on the same line number; if the node with the leak
2476 // has any immediate predecessor nodes with the same line number, find
2477 // any transitive-successors that have a different statement and use that
2478 // line number instead. This avoids emiting a diagnostic like:
2479 //
2480 // // 'y' is leaked.
2481 // int x = foo(y);
2482 //
2483 // instead we want:
2484 //
2485 // int x = foo(y);
2486 // // 'y' is leaked.
2487
2488 Stmt* S = getStmt(BR); // This is the statement where the leak occured.
2489 assert (S);
2490 unsigned EndLine = SMgr.getLogicalLineNumber(S->getLocStart());
2491
2492 // Look in the *trimmed* graph at the immediate predecessor of EndN. Does
2493 // it occur on the same line?
Ted Kremenek4c479322008-05-06 23:07:13 +00002494
2495 PathDiagnosticPiece::DisplayHint Hint = PathDiagnosticPiece::Above;
Ted Kremenekea794e92008-05-05 18:50:19 +00002496
2497 assert (!EndN->pred_empty()); // Not possible to have 0 predecessors.
Ted Kremenek4c479322008-05-06 23:07:13 +00002498 ExplodedNode<ValueState> *Pred = *(EndN->pred_begin());
2499 ProgramPoint PredPos = Pred->getLocation();
Ted Kremenekea794e92008-05-05 18:50:19 +00002500
Ted Kremenek4c479322008-05-06 23:07:13 +00002501 if (PostStmt* PredPS = dyn_cast<PostStmt>(&PredPos)) {
Ted Kremenekea794e92008-05-05 18:50:19 +00002502
Ted Kremenek4c479322008-05-06 23:07:13 +00002503 Stmt* SPred = PredPS->getStmt();
Ted Kremenekea794e92008-05-05 18:50:19 +00002504
2505 // Predecessor at same line?
Ted Kremenek4c479322008-05-06 23:07:13 +00002506 if (SMgr.getLogicalLineNumber(SPred->getLocStart()) != EndLine) {
2507 Hint = PathDiagnosticPiece::Below;
2508 S = SPred;
2509 }
Ted Kremenekea794e92008-05-05 18:50:19 +00002510 }
Ted Kremenekea794e92008-05-05 18:50:19 +00002511
2512 // Generate the diagnostic.
Ted Kremenek4c479322008-05-06 23:07:13 +00002513 FullSourceLoc L( S->getLocStart(), SMgr);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002514 std::ostringstream os;
Ted Kremenek198cae02008-05-02 20:53:50 +00002515
Ted Kremenekea794e92008-05-05 18:50:19 +00002516 os << "Object allocated on line " << AllocLine;
Ted Kremenek198cae02008-05-02 20:53:50 +00002517
2518 if (FirstDecl)
2519 os << " and stored into '" << FirstDecl->getName() << '\'';
2520
Ted Kremenek9363fd92008-05-05 17:53:17 +00002521 os << " is no longer referenced after this point and has a retain count of +"
2522 << RetCount << " (object leaked).";
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002523
Ted Kremenek4c479322008-05-06 23:07:13 +00002524 return new PathDiagnosticPiece(L, os.str(), Hint);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002525}
2526
Ted Kremenek7d421f32008-04-09 23:49:11 +00002527void UseAfterRelease::EmitWarnings(BugReporter& BR) {
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002528
Ted Kremenek7d421f32008-04-09 23:49:11 +00002529 for (CFRefCount::use_after_iterator I = TF.use_after_begin(),
2530 E = TF.use_after_end(); I != E; ++I) {
2531
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002532 CFRefReport report(*this, I->first, I->second.second);
2533 report.addRange(I->second.first->getSourceRange());
Ted Kremenek270ab7d2008-04-18 01:56:37 +00002534 BR.EmitWarning(report);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002535 }
Ted Kremenek7d421f32008-04-09 23:49:11 +00002536}
2537
2538void BadRelease::EmitWarnings(BugReporter& BR) {
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002539
Ted Kremenek7d421f32008-04-09 23:49:11 +00002540 for (CFRefCount::bad_release_iterator I = TF.bad_release_begin(),
2541 E = TF.bad_release_end(); I != E; ++I) {
2542
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002543 CFRefReport report(*this, I->first, I->second.second);
2544 report.addRange(I->second.first->getSourceRange());
2545 BR.EmitWarning(report);
Ted Kremenek7d421f32008-04-09 23:49:11 +00002546 }
2547}
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002548
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00002549void Leak::EmitWarnings(BugReporter& BR) {
2550
2551 for (CFRefCount::leaks_iterator I = TF.leaks_begin(),
2552 E = TF.leaks_end(); I != E; ++I) {
2553
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002554 std::vector<SymbolID>& SymV = *(I->second);
2555 unsigned n = SymV.size();
2556
2557 for (unsigned i = 0; i < n; ++i) {
2558 CFRefReport report(*this, I->first, SymV[i]);
2559 BR.EmitWarning(report);
2560 }
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00002561 }
2562}
2563
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002564void Leak::GetErrorNodes(std::vector<ExplodedNode<ValueState>*>& Nodes) {
2565 for (CFRefCount::leaks_iterator I=TF.leaks_begin(), E=TF.leaks_end();
2566 I!=E; ++I)
2567 Nodes.push_back(I->first);
2568}
2569
Ted Kremenekd7e26782008-05-16 18:33:44 +00002570bool Leak::isCached(BugReport& R) {
2571
2572 // Most bug reports are cached at the location where they occured.
2573 // With leaks, we want to unique them by the location where they were
2574 // allocated, and only report only a single path.
2575
2576 SymbolID Sym = static_cast<CFRefReport&>(R).getSymbol();
2577
2578 ExplodedNode<ValueState>* AllocNode =
2579 GetAllocationSite(R.getEndNode(), Sym).first;
2580
2581 if (!AllocNode)
2582 return false;
2583
2584 return BugTypeCacheLocation::isCached(AllocNode->getLocation());
2585}
2586
Ted Kremeneka7338b42008-03-11 06:39:11 +00002587//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00002588// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00002589//===----------------------------------------------------------------------===//
2590
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002591GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
2592 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00002593 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00002594}