blob: 0c8aa8d48154566187c88107598df18f0b64121a [file] [log] [blame]
Chris Lattnerbe1a7a02008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek827f93b2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Gabor Greif2224fcb2008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek827f93b2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremeneka7338b42008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenekfe30beb2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekfe4d2312008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremenek827f93b2008-03-06 00:08:09 +000018#include "clang/Analysis/PathSensitive/ValueState.h"
Ted Kremenekdd0126b2008-03-31 18:26:32 +000019#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek827f93b2008-03-06 00:08:09 +000020#include "clang/Analysis/LocalCheckers.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000021#include "clang/Analysis/PathDiagnostic.h"
22#include "clang/Analysis/PathSensitive/BugReporter.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000023#include "clang/AST/DeclObjC.h"
Ted Kremeneka7338b42008-03-11 06:39:11 +000024#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/FoldingSet.h"
26#include "llvm/ADT/ImmutableMap.h"
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000027#include "llvm/ADT/StringExtras.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000028#include "llvm/Support/Compiler.h"
Ted Kremenekd7e26782008-05-16 18:33:44 +000029#include "llvm/ADT/STLExtras.h"
Ted Kremenek3b11f7a2008-03-11 19:44:10 +000030#include <ostream>
Ted Kremeneka8503952008-04-18 04:55:01 +000031#include <sstream>
Ted Kremenek827f93b2008-03-06 00:08:09 +000032
33using namespace clang;
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000034using llvm::CStrInCStrNoCase;
Ted Kremenek827f93b2008-03-06 00:08:09 +000035
Ted Kremenek7d421f32008-04-09 23:49:11 +000036//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +000037// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +000038//===----------------------------------------------------------------------===//
39
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +000040static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +000041 IdentifierInfo* II = &Ctx.Idents.get(name);
42 return Ctx.Selectors.getSelector(0, &II);
43}
44
Ted Kremenek0e344d42008-05-06 00:30:21 +000045static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
46 IdentifierInfo* II = &Ctx.Idents.get(name);
47 return Ctx.Selectors.getSelector(1, &II);
48}
49
Ted Kremenek272aa852008-06-25 21:21:56 +000050//===----------------------------------------------------------------------===//
51// Type querying functions.
52//===----------------------------------------------------------------------===//
53
Ted Kremenek62820d82008-05-07 20:06:41 +000054static bool isCFRefType(QualType T) {
55
56 if (!T->isPointerType())
57 return false;
58
Ted Kremenek272aa852008-06-25 21:21:56 +000059 // Check the typedef for the name "CF" and the substring "Ref".
Ted Kremenek62820d82008-05-07 20:06:41 +000060 TypedefType* TD = dyn_cast<TypedefType>(T.getTypePtr());
61
62 if (!TD)
63 return false;
64
65 const char* TDName = TD->getDecl()->getIdentifier()->getName();
66 assert (TDName);
67
68 if (TDName[0] != 'C' || TDName[1] != 'F')
69 return false;
70
71 if (strstr(TDName, "Ref") == 0)
72 return false;
73
74 return true;
75}
76
Ted Kremenek4c5378c2008-07-15 16:50:12 +000077static bool isCGRefType(QualType T) {
78
79 if (!T->isPointerType())
80 return false;
81
82 // Check the typedef for the name "CG" and the substring "Ref".
83 TypedefType* TD = dyn_cast<TypedefType>(T.getTypePtr());
84
85 if (!TD)
86 return false;
87
88 const char* TDName = TD->getDecl()->getIdentifier()->getName();
89 assert (TDName);
90
91 if (TDName[0] != 'C' || TDName[1] != 'G')
92 return false;
93
94 if (strstr(TDName, "Ref") == 0)
95 return false;
96
97 return true;
98}
99
Ted Kremenek62820d82008-05-07 20:06:41 +0000100static bool isNSType(QualType T) {
101
102 if (!T->isPointerType())
103 return false;
104
105 ObjCInterfaceType* OT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
106
107 if (!OT)
108 return false;
109
110 const char* ClsName = OT->getDecl()->getIdentifier()->getName();
111 assert (ClsName);
112
113 if (ClsName[0] != 'N' || ClsName[1] != 'S')
114 return false;
115
116 return true;
117}
118
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000119//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000120// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000121//===----------------------------------------------------------------------===//
122
Ted Kremenek272aa852008-06-25 21:21:56 +0000123namespace {
124/// ArgEffect is used to summarize a function/method call's effect on a
125/// particular argument.
Ted Kremenekede40b72008-07-09 18:11:16 +0000126enum ArgEffect { IncRef, DecRef, DoNothing, DoNothingByRef,
127 StopTracking, MayEscape, SelfOwn, Autorelease };
Ted Kremenek272aa852008-06-25 21:21:56 +0000128
129/// ArgEffects summarizes the effects of a function/method call on all of
130/// its arguments.
131typedef std::vector<std::pair<unsigned,ArgEffect> > ArgEffects;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000132}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000133
Ted Kremeneka7338b42008-03-11 06:39:11 +0000134namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000135template <> struct FoldingSetTrait<ArgEffects> {
136 static void Profile(const ArgEffects& X, FoldingSetNodeID& ID) {
137 for (ArgEffects::const_iterator I = X.begin(), E = X.end(); I!= E; ++I) {
138 ID.AddInteger(I->first);
139 ID.AddInteger((unsigned) I->second);
140 }
141 }
142};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000143} // end llvm namespace
144
145namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000146
147/// RetEffect is used to summarize a function/method call's behavior with
148/// respect to its return value.
149class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000150public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000151 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
152 NotOwnedSymbol, ReceiverAlias };
Ted Kremenek272aa852008-06-25 21:21:56 +0000153
Ted Kremeneka7338b42008-03-11 06:39:11 +0000154private:
155 unsigned Data;
Ted Kremenek272aa852008-06-25 21:21:56 +0000156 RetEffect(Kind k, unsigned D = 0) { Data = (D << 3) | (unsigned) k; }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000157
Ted Kremeneka7338b42008-03-11 06:39:11 +0000158public:
Ted Kremenek272aa852008-06-25 21:21:56 +0000159
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000160 Kind getKind() const { return (Kind) (Data & 0x7); }
Ted Kremenek272aa852008-06-25 21:21:56 +0000161
162 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000163 assert(getKind() == Alias);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000164 return Data >> 3;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000165 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000166
Ted Kremenek272aa852008-06-25 21:21:56 +0000167 static RetEffect MakeAlias(unsigned Idx) {
168 return RetEffect(Alias, Idx);
169 }
170 static RetEffect MakeReceiverAlias() {
171 return RetEffect(ReceiverAlias);
172 }
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000173 static RetEffect MakeOwned(bool isAllocated = false) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000174 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol);
175 }
176 static RetEffect MakeNotOwned() {
177 return RetEffect(NotOwnedSymbol);
178 }
179 static RetEffect MakeNoRet() {
180 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000181 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000182
Ted Kremenek272aa852008-06-25 21:21:56 +0000183 operator Kind() const {
184 return getKind();
185 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000186
Ted Kremenek272aa852008-06-25 21:21:56 +0000187 void Profile(llvm::FoldingSetNodeID& ID) const {
188 ID.AddInteger(Data);
189 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000190};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000191
Ted Kremenek272aa852008-06-25 21:21:56 +0000192
193class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000194 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
195 /// specifies the argument (starting from 0). This can be sparsely
196 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000197 ArgEffects* Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000198
199 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
200 /// do not have an entry in Args.
201 ArgEffect DefaultArgEffect;
202
Ted Kremenek272aa852008-06-25 21:21:56 +0000203 /// Receiver - If this summary applies to an Objective-C message expression,
204 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000205 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000206
207 /// Ret - The effect on the return value. Used to indicate if the
208 /// function/method call returns a new tracked symbol, returns an
209 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000210 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000211
Ted Kremenekf2717b02008-07-18 17:24:20 +0000212 /// EndPath - Indicates that execution of this method/function should
213 /// terminate the simulation of a path.
214 bool EndPath;
215
Ted Kremeneka7338b42008-03-11 06:39:11 +0000216public:
217
Ted Kremenekbcaff792008-05-06 15:44:25 +0000218 RetainSummary(ArgEffects* A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000219 ArgEffect ReceiverEff, bool endpath = false)
220 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
221 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000222
Ted Kremenek272aa852008-06-25 21:21:56 +0000223 /// getArg - Return the argument effect on the argument specified by
224 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000225 ArgEffect getArg(unsigned idx) const {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000226
Ted Kremenekae855d42008-04-24 17:22:33 +0000227 if (!Args)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000228 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000229
230 // If Args is present, it is likely to contain only 1 element.
231 // Just do a linear search. Do it from the back because functions with
232 // large numbers of arguments will be tail heavy with respect to which
Ted Kremenek272aa852008-06-25 21:21:56 +0000233 // argument they actually modify with respect to the reference count.
Ted Kremenekae855d42008-04-24 17:22:33 +0000234 for (ArgEffects::reverse_iterator I=Args->rbegin(), E=Args->rend();
235 I!=E; ++I) {
236
237 if (idx > I->first)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000238 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000239
240 if (idx == I->first)
241 return I->second;
242 }
243
Ted Kremenekbcaff792008-05-06 15:44:25 +0000244 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000245 }
246
Ted Kremenek272aa852008-06-25 21:21:56 +0000247 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000248 RetEffect getRetEffect() const {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000249 return Ret;
250 }
251
Ted Kremenekf2717b02008-07-18 17:24:20 +0000252 /// isEndPath - Returns true if executing the given method/function should
253 /// terminate the path.
254 bool isEndPath() const { return EndPath; }
255
Ted Kremenek272aa852008-06-25 21:21:56 +0000256 /// getReceiverEffect - Returns the effect on the receiver of the call.
257 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000258 ArgEffect getReceiverEffect() const {
259 return Receiver;
260 }
261
Ted Kremenek2719e982008-06-17 02:43:46 +0000262 typedef ArgEffects::const_iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000263
Ted Kremenek2719e982008-06-17 02:43:46 +0000264 ExprIterator begin_args() const { return Args->begin(); }
265 ExprIterator end_args() const { return Args->end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000266
Ted Kremenek266d8b62008-05-06 02:26:56 +0000267 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects* A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000268 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000269 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000270 ID.AddPointer(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000271 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000272 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000273 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000274 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000275 }
276
277 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000278 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000279 }
280};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000281} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000282
Ted Kremenek272aa852008-06-25 21:21:56 +0000283//===----------------------------------------------------------------------===//
284// Data structures for constructing summaries.
285//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000286
Ted Kremenek272aa852008-06-25 21:21:56 +0000287namespace {
288class VISIBILITY_HIDDEN ObjCSummaryKey {
289 IdentifierInfo* II;
290 Selector S;
291public:
292 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
293 : II(ii), S(s) {}
294
295 ObjCSummaryKey(ObjCInterfaceDecl* d, Selector s)
296 : II(d ? d->getIdentifier() : 0), S(s) {}
297
298 ObjCSummaryKey(Selector s)
299 : II(0), S(s) {}
300
301 IdentifierInfo* getIdentifier() const { return II; }
302 Selector getSelector() const { return S; }
303};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000304}
305
306namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000307template <> struct DenseMapInfo<ObjCSummaryKey> {
308 static inline ObjCSummaryKey getEmptyKey() {
309 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
310 DenseMapInfo<Selector>::getEmptyKey());
311 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000312
Ted Kremenek272aa852008-06-25 21:21:56 +0000313 static inline ObjCSummaryKey getTombstoneKey() {
314 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
315 DenseMapInfo<Selector>::getTombstoneKey());
316 }
317
318 static unsigned getHashValue(const ObjCSummaryKey &V) {
319 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
320 & 0x88888888)
321 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
322 & 0x55555555);
323 }
324
325 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
326 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
327 RHS.getIdentifier()) &&
328 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
329 RHS.getSelector());
330 }
331
332 static bool isPod() {
333 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
334 DenseMapInfo<Selector>::isPod();
335 }
336};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000337} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000338
Ted Kremenek84f010c2008-06-23 23:30:29 +0000339namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000340class VISIBILITY_HIDDEN ObjCSummaryCache {
341 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
342 MapTy M;
343public:
344 ObjCSummaryCache() {}
345
346 typedef MapTy::iterator iterator;
347
348 iterator find(ObjCInterfaceDecl* D, Selector S) {
349
350 // Do a lookup with the (D,S) pair. If we find a match return
351 // the iterator.
352 ObjCSummaryKey K(D, S);
353 MapTy::iterator I = M.find(K);
354
355 if (I != M.end() || !D)
356 return I;
357
358 // Walk the super chain. If we find a hit with a parent, we'll end
359 // up returning that summary. We actually allow that key (null,S), as
360 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
361 // generate initial summaries without having to worry about NSObject
362 // being declared.
363 // FIXME: We may change this at some point.
364 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
365 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
366 break;
367
368 if (!C)
369 return I;
370 }
371
372 // Cache the summary with original key to make the next lookup faster
373 // and return the iterator.
374 M[K] = I->second;
375 return I;
376 }
377
378
379 iterator find(Expr* Receiver, Selector S) {
380 return find(getReceiverDecl(Receiver), S);
381 }
382
383 iterator find(IdentifierInfo* II, Selector S) {
384 // FIXME: Class method lookup. Right now we dont' have a good way
385 // of going between IdentifierInfo* and the class hierarchy.
386 iterator I = M.find(ObjCSummaryKey(II, S));
387 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
388 }
389
390 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
391
392 const PointerType* PT = E->getType()->getAsPointerType();
393 if (!PT) return 0;
394
395 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
396 if (!OI) return 0;
397
398 return OI ? OI->getDecl() : 0;
399 }
400
401 iterator end() { return M.end(); }
402
403 RetainSummary*& operator[](ObjCMessageExpr* ME) {
404
405 Selector S = ME->getSelector();
406
407 if (Expr* Receiver = ME->getReceiver()) {
408 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
409 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
410 }
411
412 return M[ObjCSummaryKey(ME->getClassName(), S)];
413 }
414
415 RetainSummary*& operator[](ObjCSummaryKey K) {
416 return M[K];
417 }
418
419 RetainSummary*& operator[](Selector S) {
420 return M[ ObjCSummaryKey(S) ];
421 }
422};
423} // end anonymous namespace
424
425//===----------------------------------------------------------------------===//
426// Data structures for managing collections of summaries.
427//===----------------------------------------------------------------------===//
428
429namespace {
430class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000431
432 //==-----------------------------------------------------------------==//
433 // Typedefs.
434 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000435
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000436 typedef llvm::FoldingSet<llvm::FoldingSetNodeWrapper<ArgEffects> >
437 ArgEffectsSetTy;
438
439 typedef llvm::FoldingSet<RetainSummary>
440 SummarySetTy;
441
442 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
443 FuncSummariesTy;
444
Ted Kremenek84f010c2008-06-23 23:30:29 +0000445 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000446
447 //==-----------------------------------------------------------------==//
448 // Data.
449 //==-----------------------------------------------------------------==//
450
Ted Kremenek272aa852008-06-25 21:21:56 +0000451 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000452 ASTContext& Ctx;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000453
Ted Kremenek272aa852008-06-25 21:21:56 +0000454 /// NSWindowII - An IdentifierInfo* representing the identifier "NSWindow."
455 IdentifierInfo* NSWindowII;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000456
457 /// NSPanelII - An IdentifierInfo* representing the identifier "NSPanel."
458 IdentifierInfo* NSPanelII;
Ted Kremenek272aa852008-06-25 21:21:56 +0000459
Ted Kremenekede40b72008-07-09 18:11:16 +0000460 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
461 /// "CFDictionaryCreate".
462 IdentifierInfo* CFDictionaryCreateII;
463
Ted Kremenek272aa852008-06-25 21:21:56 +0000464 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000465 const bool GCEnabled;
466
Ted Kremenek272aa852008-06-25 21:21:56 +0000467 /// SummarySet - A FoldingSet of uniqued summaries.
Ted Kremeneka4c74292008-04-10 22:58:08 +0000468 SummarySetTy SummarySet;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000469
Ted Kremenek272aa852008-06-25 21:21:56 +0000470 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000471 FuncSummariesTy FuncSummaries;
472
Ted Kremenek272aa852008-06-25 21:21:56 +0000473 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
474 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000475 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000476
Ted Kremenek272aa852008-06-25 21:21:56 +0000477 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000478 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000479
Ted Kremenek272aa852008-06-25 21:21:56 +0000480 /// ArgEffectsSet - A FoldingSet of uniqued ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000481 ArgEffectsSetTy ArgEffectsSet;
482
Ted Kremenek272aa852008-06-25 21:21:56 +0000483 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
484 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000485 llvm::BumpPtrAllocator BPAlloc;
486
Ted Kremenek272aa852008-06-25 21:21:56 +0000487 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000488 ArgEffects ScratchArgs;
489
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000490 RetainSummary* StopSummary;
491
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000492 //==-----------------------------------------------------------------==//
493 // Methods.
494 //==-----------------------------------------------------------------==//
495
Ted Kremenek272aa852008-06-25 21:21:56 +0000496 /// getArgEffects - Returns a persistent ArgEffects object based on the
497 /// data in ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000498 ArgEffects* getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000499
Ted Kremenek562c1302008-05-05 16:51:50 +0000500 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000501 RetainSummary* getUnarySummary(FunctionDecl* FD, UnaryFuncKind func);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000502
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000503 RetainSummary* getNSSummary(FunctionDecl* FD, const char* FName);
504 RetainSummary* getCFSummary(FunctionDecl* FD, const char* FName);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000505 RetainSummary* getCGSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000506
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000507 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
508 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000509 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000510
Ted Kremenek266d8b62008-05-06 02:26:56 +0000511 RetainSummary* getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000512 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000513 ArgEffect DefaultEff = MayEscape,
514 bool isEndPath = false);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000515
Ted Kremenek0e344d42008-05-06 00:30:21 +0000516
Ted Kremenek266d8b62008-05-06 02:26:56 +0000517 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000518 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000519 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000520 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000521 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000522
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000523
Ted Kremenekbcaff792008-05-06 15:44:25 +0000524 RetainSummary* getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000525 if (StopSummary)
526 return StopSummary;
527
528 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
529 StopTracking, StopTracking);
530
531 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000532 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000533
Ted Kremenek272aa852008-06-25 21:21:56 +0000534 RetainSummary* getInitMethodSummary(ObjCMessageExpr* ME);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000535
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000536 void InitializeClassMethodSummaries();
537 void InitializeMethodSummaries();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000538
539 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
540 RetainSummary* Summ) {
541 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
542 }
543
Ted Kremenek272aa852008-06-25 21:21:56 +0000544 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
545 ObjCClassMethodSummaries[S] = Summ;
546 }
547
548 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
549 ObjCMethodSummaries[S] = Summ;
550 }
551
552 void addNSWindowMethSummary(Selector S, RetainSummary *Summ) {
553 ObjCMethodSummaries[ObjCSummaryKey(NSWindowII, S)] = Summ;
554 }
555
Ted Kremeneke44927e2008-07-01 17:21:27 +0000556 void addNSPanelMethSummary(Selector S, RetainSummary *Summ) {
557 ObjCMethodSummaries[ObjCSummaryKey(NSPanelII, S)] = Summ;
558 }
559
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000560 void addInstMethSummary(RetainSummary* Summ, const char* Cls, va_list argp) {
Ted Kremenekf2717b02008-07-18 17:24:20 +0000561
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000562 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
563 llvm::SmallVector<IdentifierInfo*, 10> II;
564
565 while (const char* s = va_arg(argp, const char*))
566 II.push_back(&Ctx.Idents.get(s));
567
568 Selector S = Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekf2717b02008-07-18 17:24:20 +0000569 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
570 }
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000571
572 void addPanicSummary(const char* Cls, ...) {
573 RetainSummary* Summ = getPersistentSummary(0, RetEffect::MakeNoRet(),
574 DoNothing, DoNothing, true);
575 va_list argp;
576 va_start (argp, Cls);
577 addInstMethSummary(Summ, Cls, argp);
578 va_end(argp);
579 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000580
Ted Kremeneka7338b42008-03-11 06:39:11 +0000581public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000582
583 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000584 : Ctx(ctx),
585 NSWindowII(&ctx.Idents.get("NSWindow")),
586 NSPanelII(&ctx.Idents.get("NSPanel")),
Ted Kremenekede40b72008-07-09 18:11:16 +0000587 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenek272aa852008-06-25 21:21:56 +0000588 GCEnabled(gcenabled), StopSummary(0) {
589
590 InitializeClassMethodSummaries();
591 InitializeMethodSummaries();
592 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000593
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000594 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000595
Ted Kremenekd13c1872008-06-24 03:56:45 +0000596 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek272aa852008-06-25 21:21:56 +0000597 RetainSummary* getMethodSummary(ObjCMessageExpr* ME, ObjCInterfaceDecl* ID);
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000598 RetainSummary* getClassMethodSummary(IdentifierInfo* ClsName, Selector S);
Ted Kremenek926abf22008-05-06 04:20:12 +0000599
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000600 bool isGCEnabled() const { return GCEnabled; }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000601};
602
603} // end anonymous namespace
604
605//===----------------------------------------------------------------------===//
606// Implementation of checker data structures.
607//===----------------------------------------------------------------------===//
608
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000609RetainSummaryManager::~RetainSummaryManager() {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000610
611 // FIXME: The ArgEffects could eventually be allocated from BPAlloc,
612 // mitigating the need to do explicit cleanup of the
613 // Argument-Effect summaries.
614
Ted Kremenek42ea0322008-05-05 23:55:01 +0000615 for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(),
616 E = ArgEffectsSet.end(); I!=E; ++I)
Ted Kremeneka7338b42008-03-11 06:39:11 +0000617 I->getValue().~ArgEffects();
Ted Kremenek827f93b2008-03-06 00:08:09 +0000618}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000619
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000620ArgEffects* RetainSummaryManager::getArgEffects() {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000621
Ted Kremenekae855d42008-04-24 17:22:33 +0000622 if (ScratchArgs.empty())
623 return NULL;
624
625 // Compute a profile for a non-empty ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000626 llvm::FoldingSetNodeID profile;
627 profile.Add(ScratchArgs);
628 void* InsertPos;
629
Ted Kremenekae855d42008-04-24 17:22:33 +0000630 // Look up the uniqued copy, or create a new one.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000631 llvm::FoldingSetNodeWrapper<ArgEffects>* E =
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000632 ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000633
Ted Kremenekae855d42008-04-24 17:22:33 +0000634 if (E) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000635 ScratchArgs.clear();
636 return &E->getValue();
637 }
638
639 E = (llvm::FoldingSetNodeWrapper<ArgEffects>*)
Ted Kremenek272aa852008-06-25 21:21:56 +0000640 BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000641
642 new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000643 ArgEffectsSet.InsertNode(E, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000644
645 ScratchArgs.clear();
646 return &E->getValue();
647}
648
Ted Kremenek266d8b62008-05-06 02:26:56 +0000649RetainSummary*
650RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000651 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000652 ArgEffect DefaultEff,
653 bool isEndPath) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000654
Ted Kremenekae855d42008-04-24 17:22:33 +0000655 // Generate a profile for the summary.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000656 llvm::FoldingSetNodeID profile;
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000657 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
658 isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000659
Ted Kremenekae855d42008-04-24 17:22:33 +0000660 // Look up the uniqued summary, or create one if it doesn't exist.
661 void* InsertPos;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000662 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000663
664 if (Summ)
665 return Summ;
666
Ted Kremenekae855d42008-04-24 17:22:33 +0000667 // Create the summary and return it.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000668 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000669 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000670 SummarySet.InsertNode(Summ, InsertPos);
671
672 return Summ;
673}
674
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000675//===----------------------------------------------------------------------===//
676// Summary creation for functions (largely uses of Core Foundation).
677//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000678
Ted Kremenekd13c1872008-06-24 03:56:45 +0000679RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000680
681 SourceLocation Loc = FD->getLocation();
682
683 if (!Loc.isFileID())
684 return NULL;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000685
Ted Kremenekae855d42008-04-24 17:22:33 +0000686 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000687 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekae855d42008-04-24 17:22:33 +0000688
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000689 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000690 return I->second;
691
692 // No summary. Generate one.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000693 const char* FName = FD->getIdentifier()->getName();
694
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000695 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000696
Ted Kremenek62820d82008-05-07 20:06:41 +0000697 FunctionType* FT = dyn_cast<FunctionType>(FD->getType());
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000698
699 do {
700 if (FT) {
701
702 QualType T = FT->getResultType();
703
704 if (isCFRefType(T)) {
705 S = getCFSummary(FD, FName);
706 break;
707 }
708
709 if (isCGRefType(T)) {
710 S = getCGSummary(FD, FName );
711 break;
712 }
713 }
714
715 if (FName[0] == 'C' && FName[1] == 'F')
716 S = getCFSummary(FD, FName);
717 else if (FName[0] == 'N' && FName[1] == 'S')
718 S = getNSSummary(FD, FName);
719 }
720 while (0);
Ted Kremenekae855d42008-04-24 17:22:33 +0000721
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000722 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +0000723 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000724}
725
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000726RetainSummary* RetainSummaryManager::getNSSummary(FunctionDecl* FD,
Ted Kremenek42ea0322008-05-05 23:55:01 +0000727 const char* FName) {
Ted Kremenek562c1302008-05-05 16:51:50 +0000728 FName += 2;
729
730 if (strcmp(FName, "MakeCollectable") == 0)
731 return getUnarySummary(FD, cfmakecollectable);
732
733 return 0;
734}
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000735
736static bool isRetain(FunctionDecl* FD, const char* FName) {
Ted Kremeneka48ea852008-07-15 17:43:41 +0000737 const char* loc = strstr(FName, "Retain");
738 return loc && loc[sizeof("Retain")-1] == '\0';
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000739}
740
741static bool isRelease(FunctionDecl* FD, const char* FName) {
Ted Kremeneka48ea852008-07-15 17:43:41 +0000742 const char* loc = strstr(FName, "Release");
743 return loc && loc[sizeof("Release")-1] == '\0';
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000744}
745
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000746RetainSummary* RetainSummaryManager::getCFSummary(FunctionDecl* FD,
Ted Kremenek42ea0322008-05-05 23:55:01 +0000747 const char* FName) {
Ted Kremenek562c1302008-05-05 16:51:50 +0000748
Ted Kremenek62820d82008-05-07 20:06:41 +0000749 if (FName[0] == 'C' && FName[1] == 'F')
750 FName += 2;
Ted Kremenek562c1302008-05-05 16:51:50 +0000751
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000752 if (isRetain(FD, FName))
Ted Kremenek562c1302008-05-05 16:51:50 +0000753 return getUnarySummary(FD, cfretain);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000754
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000755 if (isRelease(FD, FName))
Ted Kremenek562c1302008-05-05 16:51:50 +0000756 return getUnarySummary(FD, cfrelease);
Ted Kremenekede40b72008-07-09 18:11:16 +0000757
Ted Kremenek562c1302008-05-05 16:51:50 +0000758 if (strcmp(FName, "MakeCollectable") == 0)
759 return getUnarySummary(FD, cfmakecollectable);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000760
761 return getCFCreateGetRuleSummary(FD, FName);
762}
763
764RetainSummary* RetainSummaryManager::getCGSummary(FunctionDecl* FD,
765 const char* FName) {
766
767 if (FName[0] == 'C' && FName[1] == 'G')
768 FName += 2;
769
770 if (isRelease(FD, FName))
771 return getUnarySummary(FD, cfrelease);
772
773 if (isRetain(FD, FName))
774 return getUnarySummary(FD, cfretain);
775
776 return getCFCreateGetRuleSummary(FD, FName);
777}
778
779RetainSummary*
780RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
781 const char* FName) {
782
Ted Kremenek562c1302008-05-05 16:51:50 +0000783 if (strstr(FName, "Create") || strstr(FName, "Copy"))
784 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000785
Ted Kremenek562c1302008-05-05 16:51:50 +0000786 if (strstr(FName, "Get"))
787 return getCFSummaryGetRule(FD);
788
789 return 0;
790}
791
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000792RetainSummary*
793RetainSummaryManager::getUnarySummary(FunctionDecl* FD, UnaryFuncKind func) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000794
795 FunctionTypeProto* FT =
796 dyn_cast<FunctionTypeProto>(FD->getType().getTypePtr());
797
Ted Kremenek562c1302008-05-05 16:51:50 +0000798 if (FT) {
799
800 if (FT->getNumArgs() != 1)
801 return 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000802
Ted Kremenek562c1302008-05-05 16:51:50 +0000803 TypedefType* ArgT = dyn_cast<TypedefType>(FT->getArgType(0).getTypePtr());
804
805 if (!ArgT)
806 return 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000807
Ted Kremenek562c1302008-05-05 16:51:50 +0000808 if (!ArgT->isPointerType())
809 return NULL;
810 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000811
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000812 assert (ScratchArgs.empty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000813
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000814 switch (func) {
815 case cfretain: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000816 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000817 return getPersistentSummary(RetEffect::MakeAlias(0),
818 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000819 }
820
821 case cfrelease: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000822 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000823 return getPersistentSummary(RetEffect::MakeNoRet(),
824 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000825 }
826
827 case cfmakecollectable: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000828 if (GCEnabled)
829 ScratchArgs.push_back(std::make_pair(0, DecRef));
830
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000831 return getPersistentSummary(RetEffect::MakeAlias(0),
832 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000833 }
834
835 default:
Ted Kremenek562c1302008-05-05 16:51:50 +0000836 assert (false && "Not a supported unary function.");
Ted Kremenekab2fa2a2008-04-10 23:44:06 +0000837 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000838}
839
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000840RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000841
Ted Kremenek62820d82008-05-07 20:06:41 +0000842 FunctionType* FT =
843 dyn_cast<FunctionType>(FD->getType().getTypePtr());
Ted Kremenek562c1302008-05-05 16:51:50 +0000844
845 if (FT && !isCFRefType(FT->getResultType()))
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000846 return getPersistentSummary(RetEffect::MakeNoRet());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000847
Ted Kremenekae855d42008-04-24 17:22:33 +0000848 assert (ScratchArgs.empty());
Ted Kremenekede40b72008-07-09 18:11:16 +0000849
850 if (FD->getIdentifier() == CFDictionaryCreateII) {
851 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
852 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
853 }
854
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000855 return getPersistentSummary(RetEffect::MakeOwned(true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000856}
857
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000858RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000859
Ted Kremenek62820d82008-05-07 20:06:41 +0000860 FunctionType* FT =
861 dyn_cast<FunctionType>(FD->getType().getTypePtr());
Ted Kremenekd4244d42008-04-11 20:11:19 +0000862
Ted Kremenek562c1302008-05-05 16:51:50 +0000863 if (FT) {
864 QualType RetTy = FT->getResultType();
Ted Kremenekd4244d42008-04-11 20:11:19 +0000865
Ted Kremenek562c1302008-05-05 16:51:50 +0000866 // FIXME: For now we assume that all pointer types returned are referenced
867 // counted. Since this is the "Get" rule, we assume non-ownership, which
868 // works fine for things that are not reference counted. We do this because
869 // some generic data structures return "void*". We need something better
870 // in the future.
871
872 if (!isCFRefType(RetTy) && !RetTy->isPointerType())
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000873 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek562c1302008-05-05 16:51:50 +0000874 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000875
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000876 // FIXME: Add special-cases for functions that retain/release. For now
877 // just handle the default case.
878
Ted Kremenekae855d42008-04-24 17:22:33 +0000879 assert (ScratchArgs.empty());
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000880 return getPersistentSummary(RetEffect::MakeNotOwned(), DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000881}
882
Ted Kremeneka7338b42008-03-11 06:39:11 +0000883//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000884// Summary creation for Selectors.
885//===----------------------------------------------------------------------===//
886
Ted Kremenekbcaff792008-05-06 15:44:25 +0000887RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +0000888RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek42ea0322008-05-05 23:55:01 +0000889 assert(ScratchArgs.empty());
890
891 RetainSummary* Summ =
Ted Kremenek0e344d42008-05-06 00:30:21 +0000892 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremenek42ea0322008-05-05 23:55:01 +0000893
Ted Kremenek272aa852008-06-25 21:21:56 +0000894 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +0000895 return Summ;
896}
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000897
Ted Kremenek272aa852008-06-25 21:21:56 +0000898
Ted Kremenekbcaff792008-05-06 15:44:25 +0000899RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +0000900RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
901 ObjCInterfaceDecl* ID) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000902
903 Selector S = ME->getSelector();
Ted Kremenek42ea0322008-05-05 23:55:01 +0000904
Ted Kremenek272aa852008-06-25 21:21:56 +0000905 // Look up a summary in our summary cache.
906 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000907
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000908 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +0000909 return I->second;
Ted Kremenek272aa852008-06-25 21:21:56 +0000910
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000911 if (!ME->getType()->isPointerType())
912 return 0;
913
Ted Kremenek42ea0322008-05-05 23:55:01 +0000914 // "initXXX": pass-through for receiver.
915
916 const char* s = S.getIdentifierInfoForSlot(0)->getName();
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000917 assert (ScratchArgs.empty());
Ted Kremenek1d3d9562008-05-06 06:09:09 +0000918
Ted Kremenek988c4472008-06-02 17:14:13 +0000919 if (strncmp(s, "init", 4) == 0 || strncmp(s, "_init", 5) == 0)
Ted Kremenek272aa852008-06-25 21:21:56 +0000920 return getInitMethodSummary(ME);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000921
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000922 // "copyXXX", "createXXX", "newXXX": allocators.
Ted Kremenek42ea0322008-05-05 23:55:01 +0000923
Ted Kremenek5496f6d2008-05-07 04:25:59 +0000924 if (!isNSType(ME->getReceiver()->getType()))
925 return 0;
926
Ted Kremenek62820d82008-05-07 20:06:41 +0000927 if (CStrInCStrNoCase(s, "create") || CStrInCStrNoCase(s, "copy") ||
928 CStrInCStrNoCase(s, "new")) {
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000929
930 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000931 : RetEffect::MakeOwned(true);
Ted Kremenek48b6d9e2008-05-07 03:45:05 +0000932
933 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenek272aa852008-06-25 21:21:56 +0000934 ObjCMethodSummaries[ME] = Summ;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000935 return Summ;
936 }
Ted Kremenekbcaff792008-05-06 15:44:25 +0000937
Ted Kremenek42ea0322008-05-05 23:55:01 +0000938 return 0;
939}
940
Ted Kremeneka7722b72008-05-06 21:26:51 +0000941RetainSummary*
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000942RetainSummaryManager::getClassMethodSummary(IdentifierInfo* ClsName,
943 Selector S) {
Ted Kremeneka7722b72008-05-06 21:26:51 +0000944
Ted Kremenek272aa852008-06-25 21:21:56 +0000945 // FIXME: Eventually we should properly do class method summaries, but
946 // it requires us being able to walk the type hierarchy. Unfortunately,
947 // we cannot do this with just an IdentifierInfo* for the class name.
948
Ted Kremeneka7722b72008-05-06 21:26:51 +0000949 // Look up a summary in our cache of Selectors -> Summaries.
Ted Kremenek272aa852008-06-25 21:21:56 +0000950 ObjCMethodSummariesTy::iterator I = ObjCClassMethodSummaries.find(ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +0000951
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000952 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +0000953 return I->second;
954
Ted Kremenek4c479322008-05-06 23:07:13 +0000955 return 0;
Ted Kremeneka7722b72008-05-06 21:26:51 +0000956}
957
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000958void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +0000959
960 assert (ScratchArgs.empty());
961
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000962 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
963 : RetEffect::MakeOwned(true);
964
Ted Kremenek0e344d42008-05-06 00:30:21 +0000965 RetainSummary* Summ = getPersistentSummary(E);
966
Ted Kremenek272aa852008-06-25 21:21:56 +0000967 // Create the summaries for "alloc", "new", and "allocWithZone:" for
968 // NSObject and its derivatives.
969 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
970 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
971 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +0000972
973 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000974 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek1ebce742008-07-18 18:14:26 +0000975 GetNullarySelector("currentHandler", Ctx),
Ted Kremenekf2717b02008-07-18 17:24:20 +0000976 getPersistentSummary(RetEffect::MakeNotOwned()));
Ted Kremenek0e344d42008-05-06 00:30:21 +0000977}
978
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000979void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +0000980
981 assert (ScratchArgs.empty());
982
Ted Kremeneka7722b72008-05-06 21:26:51 +0000983 // Create the "init" selector. It just acts as a pass-through for the
984 // receiver.
Ted Kremeneke44927e2008-07-01 17:21:27 +0000985 RetainSummary* InitSumm = getPersistentSummary(RetEffect::MakeReceiverAlias());
986 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +0000987
988 // The next methods are allocators.
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000989 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
990 : RetEffect::MakeOwned(true);
991
Ted Kremeneke44927e2008-07-01 17:21:27 +0000992 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +0000993
994 // Create the "copy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +0000995 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
Ted Kremenek83b2cde2008-05-06 00:38:54 +0000996
997 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +0000998 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000999
1000 // Create the "retain" selector.
1001 E = RetEffect::MakeReceiverAlias();
1002 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : IncRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001003 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001004
1005 // Create the "release" selector.
1006 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001007 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001008
1009 // Create the "drain" selector.
1010 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001011 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001012
1013 // Create the "autorelease" selector.
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00001014 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001015 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
1016
1017 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremeneke44927e2008-07-01 17:21:27 +00001018 // For NSPanel (which subclasses NSWindow), allocated objects are not
1019 // self-owned.
1020
1021 RetainSummary *NSWindowSumm =
1022 getPersistentSummary(RetEffect::MakeReceiverAlias(), SelfOwn);
Ted Kremenek272aa852008-06-25 21:21:56 +00001023
1024 // Create the "initWithContentRect:styleMask:backing:defer:" selector.
Ted Kremenek6fbecac2008-07-18 17:39:56 +00001025 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenek272aa852008-06-25 21:21:56 +00001026 II.push_back(&Ctx.Idents.get("initWithContentRect"));
1027 II.push_back(&Ctx.Idents.get("styleMask"));
1028 II.push_back(&Ctx.Idents.get("backing"));
1029 II.push_back(&Ctx.Idents.get("defer"));
1030 Selector S = Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremeneke44927e2008-07-01 17:21:27 +00001031 addNSWindowMethSummary(S, NSWindowSumm);
1032 addNSPanelMethSummary(S, InitSumm);
1033
Ted Kremenek272aa852008-06-25 21:21:56 +00001034 // Create the "initWithContentRect:styleMask:backing:defer:screen:" selector.
1035 II.push_back(&Ctx.Idents.get("screen"));
1036 S = Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremeneke44927e2008-07-01 17:21:27 +00001037 addNSWindowMethSummary(S, NSWindowSumm);
1038 addNSPanelMethSummary(S, InitSumm);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001039
1040 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001041 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1042 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001043
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001044 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1045 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001046}
1047
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001048//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001049// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001050//===----------------------------------------------------------------------===//
1051
Ted Kremeneka7338b42008-03-11 06:39:11 +00001052namespace {
1053
Ted Kremenek7d421f32008-04-09 23:49:11 +00001054class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001055public:
Ted Kremenek0d721572008-03-11 17:48:22 +00001056
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001057 enum Kind {
1058 Owned = 0, // Owning reference.
1059 NotOwned, // Reference is not owned by still valid (not freed).
1060 Released, // Object has been released.
1061 ReturnedOwned, // Returned object passes ownership to caller.
1062 ReturnedNotOwned, // Return object does not pass ownership to caller.
1063 ErrorUseAfterRelease, // Object used after released.
1064 ErrorReleaseNotOwned, // Release of an object that was not owned.
1065 ErrorLeak // A memory leak due to excessive reference counts.
1066 };
Ted Kremenek0d721572008-03-11 17:48:22 +00001067
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001068private:
1069
1070 Kind kind;
1071 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001072 QualType T;
1073
1074 RefVal(Kind k, unsigned cnt, QualType t) : kind(k), Cnt(cnt), T(t) {}
1075 RefVal(Kind k, unsigned cnt = 0) : kind(k), Cnt(cnt) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001076
1077public:
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001078
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001079 Kind getKind() const { return kind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001080
Ted Kremenek272aa852008-06-25 21:21:56 +00001081 unsigned getCount() const { return Cnt; }
1082 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001083
1084 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001085
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001086 static bool isError(Kind k) { return k >= ErrorUseAfterRelease; }
1087
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001088 static bool isLeak(Kind k) { return k == ErrorLeak; }
1089
Ted Kremenekffefc352008-04-11 22:25:11 +00001090 bool isOwned() const {
1091 return getKind() == Owned;
1092 }
1093
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001094 bool isNotOwned() const {
1095 return getKind() == NotOwned;
1096 }
1097
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001098 bool isReturnedOwned() const {
1099 return getKind() == ReturnedOwned;
1100 }
1101
1102 bool isReturnedNotOwned() const {
1103 return getKind() == ReturnedNotOwned;
1104 }
1105
1106 bool isNonLeakError() const {
1107 Kind k = getKind();
1108 return isError(k) && !isLeak(k);
1109 }
1110
1111 // State creation: normal state.
1112
Ted Kremenek272aa852008-06-25 21:21:56 +00001113 static RefVal makeOwned(QualType t, unsigned Count = 1) {
1114 return RefVal(Owned, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001115 }
1116
Ted Kremenek272aa852008-06-25 21:21:56 +00001117 static RefVal makeNotOwned(QualType t, unsigned Count = 0) {
1118 return RefVal(NotOwned, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001119 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001120
1121 static RefVal makeReturnedOwned(unsigned Count) {
1122 return RefVal(ReturnedOwned, Count);
1123 }
1124
1125 static RefVal makeReturnedNotOwned() {
1126 return RefVal(ReturnedNotOwned);
1127 }
1128
1129 // State creation: errors.
Ted Kremenek272aa852008-06-25 21:21:56 +00001130
1131#if 0
Ted Kremenek9363fd92008-05-05 17:53:17 +00001132 static RefVal makeLeak(unsigned Count) { return RefVal(ErrorLeak, Count); }
Ted Kremenek0d721572008-03-11 17:48:22 +00001133 static RefVal makeReleased() { return RefVal(Released); }
1134 static RefVal makeUseAfterRelease() { return RefVal(ErrorUseAfterRelease); }
1135 static RefVal makeReleaseNotOwned() { return RefVal(ErrorReleaseNotOwned); }
Ted Kremenek272aa852008-06-25 21:21:56 +00001136#endif
1137
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001138 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001139
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001140 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001141 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001142 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001143
Ted Kremenek272aa852008-06-25 21:21:56 +00001144 RefVal operator-(size_t i) const {
1145 return RefVal(getKind(), getCount() - i, getType());
1146 }
1147
1148 RefVal operator+(size_t i) const {
1149 return RefVal(getKind(), getCount() + i, getType());
1150 }
1151
1152 RefVal operator^(Kind k) const {
1153 return RefVal(k, getCount(), getType());
1154 }
1155
1156
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001157 void Profile(llvm::FoldingSetNodeID& ID) const {
1158 ID.AddInteger((unsigned) kind);
1159 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001160 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001161 }
1162
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001163 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001164};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001165
1166void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001167 if (!T.isNull())
1168 Out << "Tracked Type:" << T.getAsString() << '\n';
1169
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001170 switch (getKind()) {
1171 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001172 case Owned: {
1173 Out << "Owned";
1174 unsigned cnt = getCount();
1175 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001176 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001177 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001178
Ted Kremenekc4f81022008-04-10 23:09:18 +00001179 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001180 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001181 unsigned cnt = getCount();
1182 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001183 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001184 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001185
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001186 case ReturnedOwned: {
1187 Out << "ReturnedOwned";
1188 unsigned cnt = getCount();
1189 if (cnt) Out << " (+ " << cnt << ")";
1190 break;
1191 }
1192
1193 case ReturnedNotOwned: {
1194 Out << "ReturnedNotOwned";
1195 unsigned cnt = getCount();
1196 if (cnt) Out << " (+ " << cnt << ")";
1197 break;
1198 }
1199
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001200 case Released:
1201 Out << "Released";
1202 break;
1203
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001204 case ErrorLeak:
1205 Out << "Leaked";
1206 break;
1207
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001208 case ErrorUseAfterRelease:
1209 Out << "Use-After-Release [ERROR]";
1210 break;
1211
1212 case ErrorReleaseNotOwned:
1213 Out << "Release of Not-Owned [ERROR]";
1214 break;
1215 }
1216}
Ted Kremenek0d721572008-03-11 17:48:22 +00001217
Ted Kremenek7aef4842008-04-16 20:40:59 +00001218//===----------------------------------------------------------------------===//
1219// Transfer functions.
1220//===----------------------------------------------------------------------===//
1221
Ted Kremenek7d421f32008-04-09 23:49:11 +00001222class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001223public:
Ted Kremenek272aa852008-06-25 21:21:56 +00001224 // Type definitions.
Ted Kremenek0d721572008-03-11 17:48:22 +00001225 typedef llvm::ImmutableMap<SymbolID, RefVal> RefBindings;
Ted Kremenek272aa852008-06-25 21:21:56 +00001226
Ted Kremeneka7338b42008-03-11 06:39:11 +00001227 typedef RefBindings::Factory RefBFactoryTy;
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001228
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001229 typedef llvm::DenseMap<GRExprEngine::NodeTy*,std::pair<Expr*, SymbolID> >
1230 ReleasesNotOwnedTy;
1231
1232 typedef ReleasesNotOwnedTy UseAfterReleasesTy;
1233
1234 typedef llvm::DenseMap<GRExprEngine::NodeTy*, std::vector<SymbolID>*>
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001235 LeaksTy;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001236
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001237 class BindingsPrinter : public ValueState::CheckerStatePrinter {
1238 public:
1239 virtual void PrintCheckerState(std::ostream& Out, void* State,
1240 const char* nl, const char* sep);
1241 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001242
1243private:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001244 RetainSummaryManager Summaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001245 const LangOptions& LOpts;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001246 RefBFactoryTy RefBFactory;
1247 UseAfterReleasesTy UseAfterReleases;
1248 ReleasesNotOwnedTy ReleasesNotOwned;
1249 LeaksTy Leaks;
1250 BindingsPrinter Printer;
Ted Kremenek1feab292008-04-16 04:28:53 +00001251
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001252public:
1253
Ted Kremenekf22f8682008-07-10 22:03:41 +00001254 static RefBindings GetRefBindings(const ValueState& StImpl) {
1255 return RefBindings((const RefBindings::TreeTy*) StImpl.CheckerState);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001256 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001257
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001258private:
1259
Ted Kremeneka7338b42008-03-11 06:39:11 +00001260 static void SetRefBindings(ValueState& StImpl, RefBindings B) {
1261 StImpl.CheckerState = B.getRoot();
1262 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001263
Ted Kremeneka7338b42008-03-11 06:39:11 +00001264 RefBindings Remove(RefBindings B, SymbolID sym) {
1265 return RefBFactory.Remove(B, sym);
1266 }
1267
Ted Kremenek0d721572008-03-11 17:48:22 +00001268 RefBindings Update(RefBindings B, SymbolID sym, RefVal V, ArgEffect E,
Ted Kremenek1feab292008-04-16 04:28:53 +00001269 RefVal::Kind& hasErr);
1270
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001271 void ProcessNonLeakError(ExplodedNodeSet<ValueState>& Dst,
1272 GRStmtNodeBuilder<ValueState>& Builder,
1273 Expr* NodeExpr, Expr* ErrorExpr,
1274 ExplodedNode<ValueState>* Pred,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001275 const ValueState* St,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001276 RefVal::Kind hasErr, SymbolID Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001277
Ted Kremenekf22f8682008-07-10 22:03:41 +00001278 const ValueState* HandleSymbolDeath(ValueStateManager& VMgr,
1279 const ValueState* St,
1280 SymbolID sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001281
Ted Kremenekf22f8682008-07-10 22:03:41 +00001282 const ValueState* NukeBinding(ValueStateManager& VMgr, const ValueState* St,
1283 SymbolID sid);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001284
1285public:
Ted Kremenek7aef4842008-04-16 20:40:59 +00001286
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001287 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001288 : Summaries(Ctx, gcenabled),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001289 LOpts(lopts) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001290
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001291 virtual ~CFRefCount() {
1292 for (LeaksTy::iterator I = Leaks.begin(), E = Leaks.end(); I!=E; ++I)
1293 delete I->second;
1294 }
Ted Kremenek7d421f32008-04-09 23:49:11 +00001295
1296 virtual void RegisterChecks(GRExprEngine& Eng);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001297
1298 virtual ValueState::CheckerStatePrinter* getCheckerStatePrinter() {
1299 return &Printer;
1300 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001301
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001302 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001303 const LangOptions& getLangOptions() const { return LOpts; }
1304
Ted Kremeneka7338b42008-03-11 06:39:11 +00001305 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001306
1307 void EvalSummary(ExplodedNodeSet<ValueState>& Dst,
1308 GRExprEngine& Eng,
1309 GRStmtNodeBuilder<ValueState>& Builder,
1310 Expr* Ex,
1311 Expr* Receiver,
1312 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001313 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001314 ExplodedNode<ValueState>* Pred);
1315
Ted Kremeneka7338b42008-03-11 06:39:11 +00001316 virtual void EvalCall(ExplodedNodeSet<ValueState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001317 GRExprEngine& Eng,
Ted Kremeneka7338b42008-03-11 06:39:11 +00001318 GRStmtNodeBuilder<ValueState>& Builder,
Ted Kremenek0a6a80b2008-04-23 20:12:28 +00001319 CallExpr* CE, RVal L,
Ted Kremeneka7338b42008-03-11 06:39:11 +00001320 ExplodedNode<ValueState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001321
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001322
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001323 virtual void EvalObjCMessageExpr(ExplodedNodeSet<ValueState>& Dst,
1324 GRExprEngine& Engine,
1325 GRStmtNodeBuilder<ValueState>& Builder,
1326 ObjCMessageExpr* ME,
1327 ExplodedNode<ValueState>* Pred);
1328
1329 bool EvalObjCMessageExprAux(ExplodedNodeSet<ValueState>& Dst,
1330 GRExprEngine& Engine,
1331 GRStmtNodeBuilder<ValueState>& Builder,
1332 ObjCMessageExpr* ME,
1333 ExplodedNode<ValueState>* Pred);
1334
Ted Kremenek7aef4842008-04-16 20:40:59 +00001335 // Stores.
1336
1337 virtual void EvalStore(ExplodedNodeSet<ValueState>& Dst,
1338 GRExprEngine& Engine,
1339 GRStmtNodeBuilder<ValueState>& Builder,
1340 Expr* E, ExplodedNode<ValueState>* Pred,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001341 const ValueState* St, RVal TargetLV, RVal Val);
Ted Kremenekffefc352008-04-11 22:25:11 +00001342 // End-of-path.
1343
1344 virtual void EvalEndPath(GRExprEngine& Engine,
1345 GREndPathNodeBuilder<ValueState>& Builder);
1346
Ted Kremenek541db372008-04-24 23:57:27 +00001347 virtual void EvalDeadSymbols(ExplodedNodeSet<ValueState>& Dst,
1348 GRExprEngine& Engine,
1349 GRStmtNodeBuilder<ValueState>& Builder,
Ted Kremenekac91ce92008-04-25 01:25:15 +00001350 ExplodedNode<ValueState>* Pred,
1351 Stmt* S,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001352 const ValueState* St,
Ted Kremenek541db372008-04-24 23:57:27 +00001353 const ValueStateManager::DeadSymbolsTy& Dead);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001354 // Return statements.
1355
1356 virtual void EvalReturn(ExplodedNodeSet<ValueState>& Dst,
1357 GRExprEngine& Engine,
1358 GRStmtNodeBuilder<ValueState>& Builder,
1359 ReturnStmt* S,
1360 ExplodedNode<ValueState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001361
1362 // Assumptions.
1363
Ted Kremenek76d31662008-07-17 23:33:10 +00001364 virtual const ValueState* EvalAssume(ValueStateManager& VMgr,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001365 const ValueState* St, RVal Cond,
1366 bool Assumption, bool& isFeasible);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001367
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001368 // Error iterators.
1369
1370 typedef UseAfterReleasesTy::iterator use_after_iterator;
1371 typedef ReleasesNotOwnedTy::iterator bad_release_iterator;
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00001372 typedef LeaksTy::iterator leaks_iterator;
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001373
Ted Kremenek7d421f32008-04-09 23:49:11 +00001374 use_after_iterator use_after_begin() { return UseAfterReleases.begin(); }
1375 use_after_iterator use_after_end() { return UseAfterReleases.end(); }
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001376
Ted Kremenek7d421f32008-04-09 23:49:11 +00001377 bad_release_iterator bad_release_begin() { return ReleasesNotOwned.begin(); }
1378 bad_release_iterator bad_release_end() { return ReleasesNotOwned.end(); }
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00001379
1380 leaks_iterator leaks_begin() { return Leaks.begin(); }
1381 leaks_iterator leaks_end() { return Leaks.end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001382};
1383
1384} // end anonymous namespace
1385
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001386
Ted Kremenek7d421f32008-04-09 23:49:11 +00001387
1388
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001389void CFRefCount::BindingsPrinter::PrintCheckerState(std::ostream& Out,
1390 void* State, const char* nl,
1391 const char* sep) {
1392 RefBindings B((RefBindings::TreeTy*) State);
1393
1394 if (State)
1395 Out << sep << nl;
1396
1397 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1398 Out << (*I).first << " : ";
1399 (*I).second.print(Out);
1400 Out << nl;
1401 }
1402}
1403
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001404static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001405 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenek455dd862008-04-11 20:23:24 +00001406}
1407
Ted Kremenek266d8b62008-05-06 02:26:56 +00001408static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1409 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenek455dd862008-04-11 20:23:24 +00001410}
1411
Ted Kremenek227c5372008-05-06 02:41:27 +00001412static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1413 return Summ ? Summ->getReceiverEffect() : DoNothing;
1414}
1415
Ted Kremenekf2717b02008-07-18 17:24:20 +00001416static inline bool IsEndPath(RetainSummary* Summ) {
1417 return Summ ? Summ->isEndPath() : false;
1418}
1419
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001420void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<ValueState>& Dst,
1421 GRStmtNodeBuilder<ValueState>& Builder,
1422 Expr* NodeExpr, Expr* ErrorExpr,
1423 ExplodedNode<ValueState>* Pred,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001424 const ValueState* St,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001425 RefVal::Kind hasErr, SymbolID Sym) {
Ted Kremenek1feab292008-04-16 04:28:53 +00001426 Builder.BuildSinks = true;
1427 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
1428
1429 if (!N) return;
1430
1431 switch (hasErr) {
1432 default: assert(false);
1433 case RefVal::ErrorUseAfterRelease:
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001434 UseAfterReleases[N] = std::make_pair(ErrorExpr, Sym);
Ted Kremenek1feab292008-04-16 04:28:53 +00001435 break;
1436
1437 case RefVal::ErrorReleaseNotOwned:
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001438 ReleasesNotOwned[N] = std::make_pair(ErrorExpr, Sym);
Ted Kremenek1feab292008-04-16 04:28:53 +00001439 break;
1440 }
1441}
1442
Ted Kremenek272aa852008-06-25 21:21:56 +00001443/// GetReturnType - Used to get the return type of a message expression or
1444/// function call with the intention of affixing that type to a tracked symbol.
1445/// While the the return type can be queried directly from RetEx, when
1446/// invoking class methods we augment to the return type to be that of
1447/// a pointer to the class (as opposed it just being id).
1448static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1449
1450 QualType RetTy = RetE->getType();
1451
1452 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00001453 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001454 if (!PT)
1455 return RetTy;
1456
1457 // If RetEx is not a message expression just return its type.
1458 // If RetEx is a message expression, return its types if it is something
1459 /// more specific than id.
1460
1461 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1462
1463 if (!ME || !Ctx.isObjCIdType(PT->getPointeeType()))
1464 return RetTy;
1465
1466 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1467
1468 // At this point we know the return type of the message expression is id.
1469 // If we have an ObjCInterceDecl, we know this is a call to a class method
1470 // whose type we can resolve. In such cases, promote the return type to
1471 // Class*.
1472 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1473}
1474
1475
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001476void CFRefCount::EvalSummary(ExplodedNodeSet<ValueState>& Dst,
1477 GRExprEngine& Eng,
1478 GRStmtNodeBuilder<ValueState>& Builder,
1479 Expr* Ex,
1480 Expr* Receiver,
1481 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001482 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001483 ExplodedNode<ValueState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001484
Ted Kremeneka7338b42008-03-11 06:39:11 +00001485 // Get the state.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001486 ValueStateManager& StateMgr = Eng.getStateManager();
Ted Kremenekf22f8682008-07-10 22:03:41 +00001487 const ValueState* St = Builder.GetState(Pred);
Ted Kremenek227c5372008-05-06 02:41:27 +00001488
1489 // Evaluate the effect of the arguments.
Ted Kremeneka7338b42008-03-11 06:39:11 +00001490 ValueState StVals = *St;
Ted Kremenek1feab292008-04-16 04:28:53 +00001491 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001492 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001493 Expr* ErrorExpr = NULL;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001494 SymbolID ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001495
Ted Kremenek2719e982008-06-17 02:43:46 +00001496 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremeneka7338b42008-03-11 06:39:11 +00001497
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001498 RVal V = StateMgr.GetRVal(St, *I);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001499
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001500 if (isa<lval::SymbolVal>(V)) {
1501 SymbolID Sym = cast<lval::SymbolVal>(V).getSymbol();
Ted Kremenek455dd862008-04-11 20:23:24 +00001502 RefBindings B = GetRefBindings(StVals);
1503
Ted Kremenek6064a362008-07-07 16:21:19 +00001504 if (RefBindings::data_type* T = B.lookup(Sym)) {
1505 B = Update(B, Sym, *T, GetArgE(Summ, idx), hasErr);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001506 SetRefBindings(StVals, B);
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001507
Ted Kremenek1feab292008-04-16 04:28:53 +00001508 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001509 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00001510 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001511 break;
1512 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001513 }
Ted Kremeneke4924202008-04-11 20:51:02 +00001514 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001515 else if (isa<LVal>(V)) {
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001516#if 0
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001517 // Nuke all arguments passed by reference.
Ted Kremenek455dd862008-04-11 20:23:24 +00001518 StateMgr.Unbind(StVals, cast<LVal>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001519#else
Ted Kremenekede40b72008-07-09 18:11:16 +00001520 if (lval::DeclVal* DV = dyn_cast<lval::DeclVal>(&V)) {
1521
1522 if (GetArgE(Summ, idx) == DoNothingByRef)
1523 continue;
1524
1525 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001526
1527 // FIXME: Either this logic should also be replicated in GRSimpleVals
1528 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00001529
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001530 // FIXME: We can have collisions on the conjured symbol if the
1531 // expression *I also creates conjured symbols. We probably want
1532 // to identify conjured symbols by an expression pair: the enclosing
1533 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00001534 // disambiguate conjured symbols.
1535
1536 // Is the invalidated variable something that we were tracking?
1537 RVal X = StateMgr.GetRVal(&StVals, *DV);
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001538
Ted Kremenekede40b72008-07-09 18:11:16 +00001539 if (isa<lval::SymbolVal>(X)) {
1540 SymbolID Sym = cast<lval::SymbolVal>(X).getSymbol();
1541 SetRefBindings(StVals,RefBFactory.Remove(GetRefBindings(StVals),Sym));
1542 }
1543
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001544 // Set the value of the variable to be a conjured symbol.
1545 unsigned Count = Builder.getCurrentBlockCount();
1546 SymbolID NewSym = Eng.getSymbolManager().getConjuredSymbol(*I, Count);
1547
Ted Kremenekf22f8682008-07-10 22:03:41 +00001548 StateMgr.SetRVal(StVals, *DV,
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001549 LVal::IsLValType(DV->getDecl()->getType())
1550 ? cast<RVal>(lval::SymbolVal(NewSym))
1551 : cast<RVal>(nonlval::SymbolVal(NewSym)));
1552 }
1553 else {
1554 // Nuke all other arguments passed by reference.
1555 StateMgr.Unbind(StVals, cast<LVal>(V));
1556 }
1557#endif
Ted Kremeneke4924202008-04-11 20:51:02 +00001558 }
Ted Kremenekbe621292008-04-22 21:39:21 +00001559 else if (isa<nonlval::LValAsInteger>(V))
1560 StateMgr.Unbind(StVals, cast<nonlval::LValAsInteger>(V).getLVal());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001561 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001562
Ted Kremenek272aa852008-06-25 21:21:56 +00001563 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00001564 if (!ErrorExpr && Receiver) {
1565 RVal V = StateMgr.GetRVal(St, Receiver);
1566
1567 if (isa<lval::SymbolVal>(V)) {
1568 SymbolID Sym = cast<lval::SymbolVal>(V).getSymbol();
1569 RefBindings B = GetRefBindings(StVals);
1570
Ted Kremenek6064a362008-07-07 16:21:19 +00001571 if (const RefVal* T = B.lookup(Sym)) {
1572 B = Update(B, Sym, *T, GetReceiverE(Summ), hasErr);
Ted Kremenek227c5372008-05-06 02:41:27 +00001573 SetRefBindings(StVals, B);
1574
1575 if (hasErr) {
1576 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00001577 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00001578 }
1579 }
1580 }
1581 }
1582
Ted Kremenek272aa852008-06-25 21:21:56 +00001583 // Get the persistent state.
Ted Kremenek1feab292008-04-16 04:28:53 +00001584 St = StateMgr.getPersistentState(StVals);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001585
Ted Kremenek272aa852008-06-25 21:21:56 +00001586 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00001587 if (hasErr) {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001588 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, St,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001589 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001590 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00001591 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001592
Ted Kremenekf2717b02008-07-18 17:24:20 +00001593 // Consult the summary for the return value.
Ted Kremenek266d8b62008-05-06 02:26:56 +00001594 RetEffect RE = GetRetEffect(Summ);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001595
1596 switch (RE.getKind()) {
1597 default:
1598 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001599
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001600 case RetEffect::NoRet:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001601
Ted Kremenek455dd862008-04-11 20:23:24 +00001602 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00001603 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
1604 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00001605
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001606 if (Ex->getType() != Eng.getContext().VoidTy) {
Ted Kremenek455dd862008-04-11 20:23:24 +00001607 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001608 SymbolID Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek455dd862008-04-11 20:23:24 +00001609
Ted Kremenek9e2c1ea2008-05-09 23:45:33 +00001610 RVal X = LVal::IsLValType(Ex->getType())
1611 ? cast<RVal>(lval::SymbolVal(Sym))
1612 : cast<RVal>(nonlval::SymbolVal(Sym));
Ted Kremenek455dd862008-04-11 20:23:24 +00001613
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001614 St = StateMgr.SetRVal(St, Ex, X, Eng.getCFG().isBlkExpr(Ex), false);
Ted Kremenek455dd862008-04-11 20:23:24 +00001615 }
1616
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001617 break;
1618
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001619 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00001620 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00001621 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001622 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenek2719e982008-06-17 02:43:46 +00001623 RVal V = StateMgr.GetRVal(St, *(arg_beg+idx));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001624 St = StateMgr.SetRVal(St, Ex, V, Eng.getCFG().isBlkExpr(Ex), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001625 break;
1626 }
1627
Ted Kremenek227c5372008-05-06 02:41:27 +00001628 case RetEffect::ReceiverAlias: {
1629 assert (Receiver);
1630 RVal V = StateMgr.GetRVal(St, Receiver);
1631 St = StateMgr.SetRVal(St, Ex, V, Eng.getCFG().isBlkExpr(Ex), false);
1632 break;
1633 }
1634
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001635 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001636 case RetEffect::OwnedSymbol: {
1637 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001638 SymbolID Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek272aa852008-06-25 21:21:56 +00001639 QualType RetT = GetReturnType(Ex, Eng.getContext());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001640
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001641 ValueState StImpl = *St;
1642 RefBindings B = GetRefBindings(StImpl);
Ted Kremenek272aa852008-06-25 21:21:56 +00001643 SetRefBindings(StImpl, RefBFactory.Add(B, Sym, RefVal::makeOwned(RetT)));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001644
1645 St = StateMgr.SetRVal(StateMgr.getPersistentState(StImpl),
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001646 Ex, lval::SymbolVal(Sym),
1647 Eng.getCFG().isBlkExpr(Ex), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001648
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001649 // FIXME: Add a flag to the checker where allocations are allowed to fail.
1650 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol)
1651 St = StateMgr.AddNE(St, Sym, Eng.getBasicVals().getZeroWithPtrWidth());
1652
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001653 break;
1654 }
1655
1656 case RetEffect::NotOwnedSymbol: {
1657 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001658 SymbolID Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek272aa852008-06-25 21:21:56 +00001659 QualType RetT = GetReturnType(Ex, Eng.getContext());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001660
1661 ValueState StImpl = *St;
1662 RefBindings B = GetRefBindings(StImpl);
Ted Kremenek272aa852008-06-25 21:21:56 +00001663 SetRefBindings(StImpl, RefBFactory.Add(B, Sym,
1664 RefVal::makeNotOwned(RetT)));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001665
1666 St = StateMgr.SetRVal(StateMgr.getPersistentState(StImpl),
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001667 Ex, lval::SymbolVal(Sym),
1668 Eng.getCFG().isBlkExpr(Ex), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001669
1670 break;
1671 }
1672 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001673
Ted Kremenekf2717b02008-07-18 17:24:20 +00001674 // Is this a sink?
1675 if (IsEndPath(Summ))
1676 Builder.MakeSinkNode(Dst, Ex, Pred, St);
1677 else
1678 Builder.MakeNode(Dst, Ex, Pred, St);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001679}
1680
1681
1682void CFRefCount::EvalCall(ExplodedNodeSet<ValueState>& Dst,
1683 GRExprEngine& Eng,
1684 GRStmtNodeBuilder<ValueState>& Builder,
1685 CallExpr* CE, RVal L,
1686 ExplodedNode<ValueState>* Pred) {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001687
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001688 RetainSummary* Summ = !isa<lval::FuncVal>(L) ? 0
1689 : Summaries.getSummary(cast<lval::FuncVal>(L).getDecl());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001690
1691 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
1692 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00001693}
Ted Kremeneka7338b42008-03-11 06:39:11 +00001694
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001695void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<ValueState>& Dst,
1696 GRExprEngine& Eng,
1697 GRStmtNodeBuilder<ValueState>& Builder,
1698 ObjCMessageExpr* ME,
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001699 ExplodedNode<ValueState>* Pred) {
Ted Kremenek926abf22008-05-06 04:20:12 +00001700 RetainSummary* Summ;
Ted Kremenek33661802008-05-01 21:31:50 +00001701
Ted Kremenek272aa852008-06-25 21:21:56 +00001702 if (Expr* Receiver = ME->getReceiver()) {
1703 // We need the type-information of the tracked receiver object
1704 // Retrieve it from the state.
1705 ObjCInterfaceDecl* ID = 0;
1706
1707 // FIXME: Wouldn't it be great if this code could be reduced? It's just
1708 // a chain of lookups.
Ted Kremenekf22f8682008-07-10 22:03:41 +00001709 const ValueState* St = Builder.GetState(Pred);
Ted Kremenek272aa852008-06-25 21:21:56 +00001710 RVal V = Eng.getStateManager().GetRVal(St, Receiver );
1711
1712 if (isa<lval::SymbolVal>(V)) {
1713 SymbolID Sym = cast<lval::SymbolVal>(V).getSymbol();
1714
Ted Kremenek6064a362008-07-07 16:21:19 +00001715 if (const RefVal* T = GetRefBindings(*St).lookup(Sym)) {
1716 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001717
1718 if (const PointerType* PT = Ty->getAsPointerType()) {
1719 QualType PointeeTy = PT->getPointeeType();
1720
1721 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
1722 ID = IT->getDecl();
1723 }
1724 }
1725 }
1726
1727 Summ = Summaries.getMethodSummary(ME, ID);
1728 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001729 else
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001730 Summ = Summaries.getClassMethodSummary(ME->getClassName(),
1731 ME->getSelector());
Ted Kremenek1feab292008-04-16 04:28:53 +00001732
Ted Kremenek926abf22008-05-06 04:20:12 +00001733 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
1734 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001735}
Ted Kremenek926abf22008-05-06 04:20:12 +00001736
Ted Kremenek7aef4842008-04-16 20:40:59 +00001737// Stores.
1738
1739void CFRefCount::EvalStore(ExplodedNodeSet<ValueState>& Dst,
1740 GRExprEngine& Eng,
1741 GRStmtNodeBuilder<ValueState>& Builder,
1742 Expr* E, ExplodedNode<ValueState>* Pred,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001743 const ValueState* St, RVal TargetLV, RVal Val) {
Ted Kremenek7aef4842008-04-16 20:40:59 +00001744
1745 // Check if we have a binding for "Val" and if we are storing it to something
1746 // we don't understand or otherwise the value "escapes" the function.
1747
1748 if (!isa<lval::SymbolVal>(Val))
1749 return;
1750
1751 // Are we storing to something that causes the value to "escape"?
1752
1753 bool escapes = false;
1754
1755 if (!isa<lval::DeclVal>(TargetLV))
1756 escapes = true;
1757 else
1758 escapes = cast<lval::DeclVal>(TargetLV).getDecl()->hasGlobalStorage();
1759
1760 if (!escapes)
1761 return;
1762
1763 SymbolID Sym = cast<lval::SymbolVal>(Val).getSymbol();
Ted Kremenek7aef4842008-04-16 20:40:59 +00001764
Ted Kremenek6064a362008-07-07 16:21:19 +00001765 if (!GetRefBindings(*St).lookup(Sym))
Ted Kremenek7aef4842008-04-16 20:40:59 +00001766 return;
1767
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001768 // Nuke the binding.
1769 St = NukeBinding(Eng.getStateManager(), St, Sym);
Ted Kremenek7aef4842008-04-16 20:40:59 +00001770
1771 // Hand of the remaining logic to the parent implementation.
1772 GRSimpleVals::EvalStore(Dst, Eng, Builder, E, Pred, St, TargetLV, Val);
1773}
1774
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001775
Ted Kremenekf22f8682008-07-10 22:03:41 +00001776const ValueState* CFRefCount::NukeBinding(ValueStateManager& VMgr,
1777 const ValueState* St,
1778 SymbolID sid) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001779 ValueState StImpl = *St;
1780 RefBindings B = GetRefBindings(StImpl);
1781 StImpl.CheckerState = RefBFactory.Remove(B, sid).getRoot();
1782 return VMgr.getPersistentState(StImpl);
1783}
1784
Ted Kremenekffefc352008-04-11 22:25:11 +00001785// End-of-path.
1786
Ted Kremenekf22f8682008-07-10 22:03:41 +00001787const ValueState* CFRefCount::HandleSymbolDeath(ValueStateManager& VMgr,
1788 const ValueState* St, SymbolID sid,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001789 RefVal V, bool& hasLeak) {
1790
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001791 hasLeak = V.isOwned() ||
1792 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001793
1794 if (!hasLeak)
1795 return NukeBinding(VMgr, St, sid);
1796
1797 RefBindings B = GetRefBindings(*St);
Ted Kremenek272aa852008-06-25 21:21:56 +00001798 ValueState StImpl = *St;
1799 StImpl.CheckerState = RefBFactory.Add(B, sid, V^RefVal::ErrorLeak).getRoot();
Ted Kremenek9363fd92008-05-05 17:53:17 +00001800
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001801 return VMgr.getPersistentState(StImpl);
1802}
1803
1804void CFRefCount::EvalEndPath(GRExprEngine& Eng,
Ted Kremenekffefc352008-04-11 22:25:11 +00001805 GREndPathNodeBuilder<ValueState>& Builder) {
1806
Ted Kremenekf22f8682008-07-10 22:03:41 +00001807 const ValueState* St = Builder.getState();
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001808 RefBindings B = GetRefBindings(*St);
Ted Kremenekffefc352008-04-11 22:25:11 +00001809
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001810 llvm::SmallVector<SymbolID, 10> Leaked;
Ted Kremenekffefc352008-04-11 22:25:11 +00001811
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001812 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
1813 bool hasLeak = false;
Ted Kremenekffefc352008-04-11 22:25:11 +00001814
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001815 St = HandleSymbolDeath(Eng.getStateManager(), St,
1816 (*I).first, (*I).second, hasLeak);
1817
1818 if (hasLeak) Leaked.push_back((*I).first);
1819 }
Ted Kremenek541db372008-04-24 23:57:27 +00001820
1821 if (Leaked.empty())
1822 return;
1823
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001824 ExplodedNode<ValueState>* N = Builder.MakeNode(St);
Ted Kremenekcfc909d2008-04-18 16:30:14 +00001825
Ted Kremenek541db372008-04-24 23:57:27 +00001826 if (!N)
Ted Kremenekcfc909d2008-04-18 16:30:14 +00001827 return;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001828
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001829 std::vector<SymbolID>*& LeaksAtNode = Leaks[N];
1830 assert (!LeaksAtNode);
1831 LeaksAtNode = new std::vector<SymbolID>();
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001832
1833 for (llvm::SmallVector<SymbolID, 10>::iterator I=Leaked.begin(),
1834 E = Leaked.end(); I != E; ++I)
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001835 (*LeaksAtNode).push_back(*I);
Ted Kremenekffefc352008-04-11 22:25:11 +00001836}
1837
Ted Kremenek541db372008-04-24 23:57:27 +00001838// Dead symbols.
1839
1840void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<ValueState>& Dst,
1841 GRExprEngine& Eng,
1842 GRStmtNodeBuilder<ValueState>& Builder,
Ted Kremenekac91ce92008-04-25 01:25:15 +00001843 ExplodedNode<ValueState>* Pred,
1844 Stmt* S,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001845 const ValueState* St,
Ted Kremenek541db372008-04-24 23:57:27 +00001846 const ValueStateManager::DeadSymbolsTy& Dead) {
Ted Kremenekac91ce92008-04-25 01:25:15 +00001847
Ted Kremenek541db372008-04-24 23:57:27 +00001848 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
1849
1850 RefBindings B = GetRefBindings(*St);
1851 llvm::SmallVector<SymbolID, 10> Leaked;
1852
1853 for (ValueStateManager::DeadSymbolsTy::const_iterator
1854 I=Dead.begin(), E=Dead.end(); I!=E; ++I) {
1855
Ted Kremenek6064a362008-07-07 16:21:19 +00001856 const RefVal* T = B.lookup(*I);
Ted Kremenek541db372008-04-24 23:57:27 +00001857
1858 if (!T)
1859 continue;
1860
1861 bool hasLeak = false;
1862
Ted Kremenek6064a362008-07-07 16:21:19 +00001863 St = HandleSymbolDeath(Eng.getStateManager(), St, *I, *T, hasLeak);
Ted Kremenek541db372008-04-24 23:57:27 +00001864
Ted Kremenek6064a362008-07-07 16:21:19 +00001865 if (hasLeak)
1866 Leaked.push_back(*I);
Ted Kremenek541db372008-04-24 23:57:27 +00001867 }
1868
1869 if (Leaked.empty())
1870 return;
1871
1872 ExplodedNode<ValueState>* N = Builder.MakeNode(Dst, S, Pred, St);
1873
1874 if (!N)
1875 return;
1876
1877 std::vector<SymbolID>*& LeaksAtNode = Leaks[N];
1878 assert (!LeaksAtNode);
1879 LeaksAtNode = new std::vector<SymbolID>();
1880
1881 for (llvm::SmallVector<SymbolID, 10>::iterator I=Leaked.begin(),
1882 E = Leaked.end(); I != E; ++I)
1883 (*LeaksAtNode).push_back(*I);
1884}
1885
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001886 // Return statements.
1887
1888void CFRefCount::EvalReturn(ExplodedNodeSet<ValueState>& Dst,
1889 GRExprEngine& Eng,
1890 GRStmtNodeBuilder<ValueState>& Builder,
1891 ReturnStmt* S,
1892 ExplodedNode<ValueState>* Pred) {
1893
1894 Expr* RetE = S->getRetValue();
1895 if (!RetE) return;
1896
1897 ValueStateManager& StateMgr = Eng.getStateManager();
Ted Kremenekf22f8682008-07-10 22:03:41 +00001898 const ValueState* St = Builder.GetState(Pred);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001899 RVal V = StateMgr.GetRVal(St, RetE);
1900
1901 if (!isa<lval::SymbolVal>(V))
1902 return;
1903
1904 // Get the reference count binding (if any).
1905 SymbolID Sym = cast<lval::SymbolVal>(V).getSymbol();
1906 RefBindings B = GetRefBindings(*St);
Ted Kremenek6064a362008-07-07 16:21:19 +00001907 const RefVal* T = B.lookup(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001908
1909 if (!T)
1910 return;
1911
1912 // Change the reference count.
1913
Ted Kremenek6064a362008-07-07 16:21:19 +00001914 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001915
1916 switch (X.getKind()) {
1917
1918 case RefVal::Owned: {
1919 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001920 assert (cnt > 0);
1921 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001922 break;
1923 }
1924
1925 case RefVal::NotOwned: {
1926 unsigned cnt = X.getCount();
1927 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
1928 : RefVal::makeReturnedNotOwned();
1929 break;
1930 }
1931
1932 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001933 return;
1934 }
1935
1936 // Update the binding.
1937
1938 ValueState StImpl = *St;
1939 StImpl.CheckerState = RefBFactory.Add(B, Sym, X).getRoot();
1940 Builder.MakeNode(Dst, S, Pred, StateMgr.getPersistentState(StImpl));
1941}
1942
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001943// Assumptions.
1944
Ted Kremenek76d31662008-07-17 23:33:10 +00001945const ValueState* CFRefCount::EvalAssume(ValueStateManager& VMgr,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001946 const ValueState* St,
1947 RVal Cond, bool Assumption,
1948 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001949
1950 // FIXME: We may add to the interface of EvalAssume the list of symbols
1951 // whose assumptions have changed. For now we just iterate through the
1952 // bindings and check if any of the tracked symbols are NULL. This isn't
1953 // too bad since the number of symbols we will track in practice are
1954 // probably small and EvalAssume is only called at branches and a few
1955 // other places.
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001956 RefBindings B = GetRefBindings(*St);
1957
1958 if (B.isEmpty())
1959 return St;
1960
1961 bool changed = false;
1962
1963 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001964 // Check if the symbol is null (or equal to any constant).
1965 // If this is the case, stop tracking the symbol.
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001966 if (St->getSymVal(I.getKey())) {
1967 changed = true;
1968 B = RefBFactory.Remove(B, I.getKey());
1969 }
1970 }
1971
1972 if (!changed)
1973 return St;
1974
1975 ValueState StImpl = *St;
1976 StImpl.CheckerState = B.getRoot();
Ted Kremenek76d31662008-07-17 23:33:10 +00001977 return VMgr.getPersistentState(StImpl);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001978}
Ted Kremeneka7338b42008-03-11 06:39:11 +00001979
1980CFRefCount::RefBindings CFRefCount::Update(RefBindings B, SymbolID sym,
Ted Kremenek0d721572008-03-11 17:48:22 +00001981 RefVal V, ArgEffect E,
Ted Kremenek1feab292008-04-16 04:28:53 +00001982 RefVal::Kind& hasErr) {
Ted Kremeneka7338b42008-03-11 06:39:11 +00001983
Ted Kremenek0d721572008-03-11 17:48:22 +00001984 // FIXME: This dispatch can potentially be sped up by unifiying it into
1985 // a single switch statement. Opt for simplicity for now.
Ted Kremeneka7338b42008-03-11 06:39:11 +00001986
Ted Kremenek0d721572008-03-11 17:48:22 +00001987 switch (E) {
1988 default:
1989 assert (false && "Unhandled CFRef transition.");
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001990
1991 case MayEscape:
1992 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00001993 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001994 break;
1995 }
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001996 // Fall-through.
Ted Kremenekede40b72008-07-09 18:11:16 +00001997 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00001998 case DoNothing:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001999 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
Ted Kremenek272aa852008-06-25 21:21:56 +00002000 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00002001 hasErr = V.getKind();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002002 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002003 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002004 return B;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00002005
Ted Kremenek4e1d22f2008-07-01 00:01:02 +00002006 case Autorelease:
Ted Kremenek227c5372008-05-06 02:41:27 +00002007 case StopTracking:
2008 return RefBFactory.Remove(B, sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002009
Ted Kremenek0d721572008-03-11 17:48:22 +00002010 case IncRef:
2011 switch (V.getKind()) {
2012 default:
2013 assert(false);
2014
2015 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00002016 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00002017 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002018 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002019 case RefVal::Released:
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002020 if (isGCEnabled())
Ted Kremenek272aa852008-06-25 21:21:56 +00002021 V = V ^ RefVal::Owned;
Ted Kremeneke2dd9572008-04-29 05:44:10 +00002022 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00002023 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremeneke2dd9572008-04-29 05:44:10 +00002024 hasErr = V.getKind();
2025 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002026 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002027 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002028 break;
2029
Ted Kremenek272aa852008-06-25 21:21:56 +00002030 case SelfOwn:
2031 V = V ^ RefVal::NotOwned;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002032 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00002033 case DecRef:
2034 switch (V.getKind()) {
2035 default:
2036 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002037
Ted Kremenek272aa852008-06-25 21:21:56 +00002038 case RefVal::Owned:
2039 V = V.getCount() > 1 ? V - 1 : V ^ RefVal::Released;
Ted Kremenek0d721572008-03-11 17:48:22 +00002040 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002041
Ted Kremenek272aa852008-06-25 21:21:56 +00002042 case RefVal::NotOwned:
2043 if (V.getCount() > 0)
2044 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00002045 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00002046 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00002047 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002048 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002049 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002050
2051 case RefVal::Released:
Ted Kremenek272aa852008-06-25 21:21:56 +00002052 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00002053 hasErr = V.getKind();
Ted Kremenek0d721572008-03-11 17:48:22 +00002054 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002055 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002056 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002057 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002058 return RefBFactory.Add(B, sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00002059}
2060
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002061//===----------------------------------------------------------------------===//
Ted Kremenek7d421f32008-04-09 23:49:11 +00002062// Error reporting.
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002063//===----------------------------------------------------------------------===//
2064
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002065namespace {
2066
2067 //===-------------===//
2068 // Bug Descriptions. //
2069 //===-------------===//
2070
Ted Kremeneke3769852008-04-18 20:54:29 +00002071 class VISIBILITY_HIDDEN CFRefBug : public BugTypeCacheLocation {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002072 protected:
2073 CFRefCount& TF;
2074
2075 public:
2076 CFRefBug(CFRefCount& tf) : TF(tf) {}
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002077
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002078 CFRefCount& getTF() { return TF; }
Ted Kremenek0ff3f202008-05-05 23:16:31 +00002079 const CFRefCount& getTF() const { return TF; }
2080
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002081 virtual bool isLeak() const { return false; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002082 };
2083
2084 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2085 public:
2086 UseAfterRelease(CFRefCount& tf) : CFRefBug(tf) {}
2087
2088 virtual const char* getName() const {
Ted Kremenek0ff3f202008-05-05 23:16:31 +00002089 return "Use-After-Release";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002090 }
2091 virtual const char* getDescription() const {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002092 return "Reference-counted object is used after it is released.";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002093 }
2094
2095 virtual void EmitWarnings(BugReporter& BR);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002096 };
2097
2098 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2099 public:
2100 BadRelease(CFRefCount& tf) : CFRefBug(tf) {}
2101
2102 virtual const char* getName() const {
Ted Kremenek0ff3f202008-05-05 23:16:31 +00002103 return "Bad Release";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002104 }
2105 virtual const char* getDescription() const {
2106 return "Incorrect decrement of the reference count of a "
Ted Kremeneka8503952008-04-18 04:55:01 +00002107 "CoreFoundation object: "
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002108 "The object is not owned at this point by the caller.";
2109 }
2110
2111 virtual void EmitWarnings(BugReporter& BR);
2112 };
2113
2114 class VISIBILITY_HIDDEN Leak : public CFRefBug {
2115 public:
2116 Leak(CFRefCount& tf) : CFRefBug(tf) {}
2117
2118 virtual const char* getName() const {
Ted Kremenekb3a44e72008-05-06 18:11:36 +00002119
2120 if (getTF().isGCEnabled())
2121 return "Memory Leak (GC)";
2122
2123 if (getTF().getLangOptions().getGCMode() == LangOptions::HybridGC)
2124 return "Memory Leak (Hybrid MM, non-GC)";
2125
2126 assert (getTF().getLangOptions().getGCMode() == LangOptions::NonGC);
2127 return "Memory Leak";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002128 }
2129
2130 virtual const char* getDescription() const {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002131 return "Object leaked";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002132 }
2133
2134 virtual void EmitWarnings(BugReporter& BR);
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002135 virtual void GetErrorNodes(std::vector<ExplodedNode<ValueState>*>& Nodes);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002136 virtual bool isLeak() const { return true; }
Ted Kremenekd7e26782008-05-16 18:33:44 +00002137 virtual bool isCached(BugReport& R);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002138 };
2139
2140 //===---------===//
2141 // Bug Reports. //
2142 //===---------===//
2143
2144 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
2145 SymbolID Sym;
2146 public:
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002147 CFRefReport(CFRefBug& D, ExplodedNode<ValueState> *n, SymbolID sym)
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002148 : RangedBugReport(D, n), Sym(sym) {}
2149
2150 virtual ~CFRefReport() {}
2151
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002152 CFRefBug& getBugType() {
2153 return (CFRefBug&) RangedBugReport::getBugType();
2154 }
2155 const CFRefBug& getBugType() const {
2156 return (const CFRefBug&) RangedBugReport::getBugType();
2157 }
2158
2159 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2160 const SourceRange*& end) {
2161
Ted Kremenek198cae02008-05-02 20:53:50 +00002162 if (!getBugType().isLeak())
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002163 RangedBugReport::getRanges(BR, beg, end);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002164 else
2165 beg = end = 0;
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002166 }
2167
Ted Kremenekd7e26782008-05-16 18:33:44 +00002168 SymbolID getSymbol() const { return Sym; }
2169
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002170 virtual PathDiagnosticPiece* getEndPath(BugReporter& BR,
2171 ExplodedNode<ValueState>* N);
2172
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002173 virtual std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002174
2175 virtual PathDiagnosticPiece* VisitNode(ExplodedNode<ValueState>* N,
2176 ExplodedNode<ValueState>* PrevN,
2177 ExplodedGraph<ValueState>& G,
2178 BugReporter& BR);
2179 };
2180
2181
2182} // end anonymous namespace
2183
2184void CFRefCount::RegisterChecks(GRExprEngine& Eng) {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002185 Eng.Register(new UseAfterRelease(*this));
2186 Eng.Register(new BadRelease(*this));
2187 Eng.Register(new Leak(*this));
2188}
2189
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002190
2191static const char* Msgs[] = {
2192 "Code is compiled in garbage collection only mode" // GC only
2193 " (the bug occurs with garbage collection enabled).",
2194
2195 "Code is compiled without garbage collection.", // No GC.
2196
2197 "Code is compiled for use with and without garbage collection (GC)."
2198 " The bug occurs with GC enabled.", // Hybrid, with GC.
2199
2200 "Code is compiled for use with and without garbage collection (GC)."
2201 " The bug occurs in non-GC mode." // Hyrbird, without GC/
2202};
2203
2204std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2205 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2206
2207 switch (TF.getLangOptions().getGCMode()) {
2208 default:
2209 assert(false);
Ted Kremenekcb4709402008-05-01 04:02:04 +00002210
2211 case LangOptions::GCOnly:
2212 assert (TF.isGCEnabled());
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002213 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2214
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002215 case LangOptions::NonGC:
2216 assert (!TF.isGCEnabled());
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002217 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2218
2219 case LangOptions::HybridGC:
2220 if (TF.isGCEnabled())
2221 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2222 else
2223 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2224 }
2225}
2226
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002227PathDiagnosticPiece* CFRefReport::VisitNode(ExplodedNode<ValueState>* N,
2228 ExplodedNode<ValueState>* PrevN,
2229 ExplodedGraph<ValueState>& G,
2230 BugReporter& BR) {
2231
2232 // Check if the type state has changed.
2233
Ted Kremenekf22f8682008-07-10 22:03:41 +00002234 const ValueState* PrevSt = PrevN->getState();
2235 const ValueState* CurrSt = N->getState();
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002236
2237 CFRefCount::RefBindings PrevB = CFRefCount::GetRefBindings(*PrevSt);
2238 CFRefCount::RefBindings CurrB = CFRefCount::GetRefBindings(*CurrSt);
2239
Ted Kremenek6064a362008-07-07 16:21:19 +00002240 const RefVal* PrevT = PrevB.lookup(Sym);
2241 const RefVal* CurrT = CurrB.lookup(Sym);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002242
Ted Kremeneka8503952008-04-18 04:55:01 +00002243 if (!CurrT)
2244 return NULL;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002245
Ted Kremeneka8503952008-04-18 04:55:01 +00002246 const char* Msg = NULL;
Ted Kremenek6064a362008-07-07 16:21:19 +00002247 const RefVal& CurrV = *CurrB.lookup(Sym);
Ted Kremenek9363fd92008-05-05 17:53:17 +00002248
Ted Kremeneka8503952008-04-18 04:55:01 +00002249 if (!PrevT) {
2250
Ted Kremenek9363fd92008-05-05 17:53:17 +00002251 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2252
2253 if (CurrV.isOwned()) {
2254
2255 if (isa<CallExpr>(S))
2256 Msg = "Function call returns an object with a +1 retain count"
2257 " (owning reference).";
2258 else {
2259 assert (isa<ObjCMessageExpr>(S));
2260 Msg = "Method returns an object with a +1 retain count"
2261 " (owning reference).";
2262 }
2263 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002264 else {
2265 assert (CurrV.isNotOwned());
Ted Kremenek9363fd92008-05-05 17:53:17 +00002266
2267 if (isa<CallExpr>(S))
2268 Msg = "Function call returns an object with a +0 retain count"
2269 " (non-owning reference).";
2270 else {
2271 assert (isa<ObjCMessageExpr>(S));
2272 Msg = "Method returns an object with a +0 retain count"
2273 " (non-owning reference).";
2274 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002275 }
Ted Kremenek9363fd92008-05-05 17:53:17 +00002276
Ted Kremeneka8503952008-04-18 04:55:01 +00002277 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
2278 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, Msg);
2279
2280 if (Expr* Exp = dyn_cast<Expr>(S))
2281 P->addRange(Exp->getSourceRange());
2282
2283 return P;
2284 }
2285
Ted Kremenek6064a362008-07-07 16:21:19 +00002286 // Determine if the typestate has changed.
2287 RefVal PrevV = *PrevB.lookup(Sym);
Ted Kremeneka8503952008-04-18 04:55:01 +00002288
2289 if (PrevV == CurrV)
2290 return NULL;
2291
2292 // The typestate has changed.
2293
2294 std::ostringstream os;
2295
2296 switch (CurrV.getKind()) {
2297 case RefVal::Owned:
2298 case RefVal::NotOwned:
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002299
2300 if (PrevV.getCount() == CurrV.getCount())
2301 return 0;
Ted Kremeneka8503952008-04-18 04:55:01 +00002302
2303 if (PrevV.getCount() > CurrV.getCount())
2304 os << "Reference count decremented.";
2305 else
2306 os << "Reference count incremented.";
2307
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002308 if (unsigned Count = CurrV.getCount()) {
Ted Kremenek9363fd92008-05-05 17:53:17 +00002309
2310 os << " Object has +" << Count;
Ted Kremenek752b5842008-04-18 05:32:44 +00002311
Ted Kremenek9363fd92008-05-05 17:53:17 +00002312 if (Count > 1)
2313 os << " retain counts.";
Ted Kremenek752b5842008-04-18 05:32:44 +00002314 else
Ted Kremenek9363fd92008-05-05 17:53:17 +00002315 os << " retain count.";
Ted Kremenek752b5842008-04-18 05:32:44 +00002316 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002317
2318 Msg = os.str().c_str();
2319
2320 break;
2321
2322 case RefVal::Released:
2323 Msg = "Object released.";
2324 break;
2325
2326 case RefVal::ReturnedOwned:
Ted Kremenek9363fd92008-05-05 17:53:17 +00002327 Msg = "Object returned to caller as owning reference (single retain count"
2328 " transferred to caller).";
Ted Kremeneka8503952008-04-18 04:55:01 +00002329 break;
2330
2331 case RefVal::ReturnedNotOwned:
Ted Kremenek9363fd92008-05-05 17:53:17 +00002332 Msg = "Object returned to caller with a +0 (non-owning) retain count.";
Ted Kremeneka8503952008-04-18 04:55:01 +00002333 break;
2334
2335 default:
2336 return NULL;
2337 }
2338
2339 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2340 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
2341 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, Msg);
2342
2343 // Add the range by scanning the children of the statement for any bindings
2344 // to Sym.
2345
Ted Kremenekba1c7ed2008-07-02 21:24:01 +00002346 ValueStateManager& VSM = cast<GRBugReporter>(BR).getStateManager();
Ted Kremeneka8503952008-04-18 04:55:01 +00002347
2348 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2349 if (Expr* Exp = dyn_cast_or_null<Expr>(*I)) {
2350 RVal X = VSM.GetRVal(CurrSt, Exp);
2351
2352 if (lval::SymbolVal* SV = dyn_cast<lval::SymbolVal>(&X))
2353 if (SV->getSymbol() == Sym) {
2354 P->addRange(Exp->getSourceRange()); break;
2355 }
2356 }
2357
2358 return P;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002359}
2360
Ted Kremenekd7e26782008-05-16 18:33:44 +00002361static std::pair<ExplodedNode<ValueState>*,VarDecl*>
2362GetAllocationSite(ExplodedNode<ValueState>* N, SymbolID Sym) {
2363
2364 typedef CFRefCount::RefBindings RefBindings;
2365 ExplodedNode<ValueState>* Last = N;
2366
2367 // Find the first node that referred to the tracked symbol. We also
2368 // try and find the first VarDecl the value was stored to.
2369
2370 VarDecl* FirstDecl = 0;
2371
2372 while (N) {
Ted Kremenekf22f8682008-07-10 22:03:41 +00002373 const ValueState* St = N->getState();
Ted Kremenekd7e26782008-05-16 18:33:44 +00002374 RefBindings B = RefBindings((RefBindings::TreeTy*) St->CheckerState);
Ted Kremenekd7e26782008-05-16 18:33:44 +00002375
Ted Kremenek6064a362008-07-07 16:21:19 +00002376 if (!B.lookup(Sym))
Ted Kremenekd7e26782008-05-16 18:33:44 +00002377 break;
2378
2379 VarDecl* VD = 0;
2380
2381 // Determine if there is an LVal binding to the symbol.
2382 for (ValueState::vb_iterator I=St->vb_begin(), E=St->vb_end(); I!=E; ++I) {
2383 if (!isa<lval::SymbolVal>(I->second) // Is the value a symbol?
2384 || cast<lval::SymbolVal>(I->second).getSymbol() != Sym)
2385 continue;
2386
2387 if (VD) { // Multiple decls map to this symbol.
2388 VD = 0;
2389 break;
2390 }
2391
2392 VD = I->first;
2393 }
2394
2395 if (VD) FirstDecl = VD;
2396
2397 Last = N;
2398 N = N->pred_empty() ? NULL : *(N->pred_begin());
2399 }
2400
2401 return std::make_pair(Last, FirstDecl);
2402}
Ted Kremenek4c479322008-05-06 23:07:13 +00002403
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002404PathDiagnosticPiece* CFRefReport::getEndPath(BugReporter& BR,
Ted Kremenekea794e92008-05-05 18:50:19 +00002405 ExplodedNode<ValueState>* EndN) {
Ted Kremenek86953652008-05-22 23:45:19 +00002406
2407 // Tell the BugReporter to report cases when the tracked symbol is
2408 // assigned to different variables, etc.
Ted Kremenekba1c7ed2008-07-02 21:24:01 +00002409 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002410
2411 if (!getBugType().isLeak())
Ted Kremenekea794e92008-05-05 18:50:19 +00002412 return RangedBugReport::getEndPath(BR, EndN);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002413
Ted Kremenek9363fd92008-05-05 17:53:17 +00002414 typedef CFRefCount::RefBindings RefBindings;
2415
2416 // Get the retain count.
Ted Kremenek9363fd92008-05-05 17:53:17 +00002417
Ted Kremenek6064a362008-07-07 16:21:19 +00002418 unsigned long RetCount =
2419 CFRefCount::GetRefBindings(*EndN->getState()).lookup(Sym)->getCount();
2420
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002421 // We are a leak. Walk up the graph to get to the first node where the
Ted Kremenekd7e26782008-05-16 18:33:44 +00002422 // symbol appeared, and also get the first VarDecl that tracked object
2423 // is stored to.
2424
2425 ExplodedNode<ValueState>* AllocNode = 0;
Ted Kremenek198cae02008-05-02 20:53:50 +00002426 VarDecl* FirstDecl = 0;
Ted Kremenekd7e26782008-05-16 18:33:44 +00002427 llvm::tie(AllocNode, FirstDecl) = GetAllocationSite(EndN, Sym);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002428
Ted Kremenekd7e26782008-05-16 18:33:44 +00002429 // Get the allocate site.
2430 assert (AllocNode);
2431 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002432
Ted Kremenekea794e92008-05-05 18:50:19 +00002433 SourceManager& SMgr = BR.getContext().getSourceManager();
2434 unsigned AllocLine = SMgr.getLogicalLineNumber(FirstStmt->getLocStart());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002435
Ted Kremenekea794e92008-05-05 18:50:19 +00002436 // Get the leak site. We may have multiple ExplodedNodes (one with the
2437 // leak) that occur on the same line number; if the node with the leak
2438 // has any immediate predecessor nodes with the same line number, find
2439 // any transitive-successors that have a different statement and use that
2440 // line number instead. This avoids emiting a diagnostic like:
2441 //
2442 // // 'y' is leaked.
2443 // int x = foo(y);
2444 //
2445 // instead we want:
2446 //
2447 // int x = foo(y);
2448 // // 'y' is leaked.
2449
2450 Stmt* S = getStmt(BR); // This is the statement where the leak occured.
2451 assert (S);
2452 unsigned EndLine = SMgr.getLogicalLineNumber(S->getLocStart());
2453
2454 // Look in the *trimmed* graph at the immediate predecessor of EndN. Does
2455 // it occur on the same line?
Ted Kremenek4c479322008-05-06 23:07:13 +00002456
2457 PathDiagnosticPiece::DisplayHint Hint = PathDiagnosticPiece::Above;
Ted Kremenekea794e92008-05-05 18:50:19 +00002458
2459 assert (!EndN->pred_empty()); // Not possible to have 0 predecessors.
Ted Kremenek4c479322008-05-06 23:07:13 +00002460 ExplodedNode<ValueState> *Pred = *(EndN->pred_begin());
2461 ProgramPoint PredPos = Pred->getLocation();
Ted Kremenekea794e92008-05-05 18:50:19 +00002462
Ted Kremenek4c479322008-05-06 23:07:13 +00002463 if (PostStmt* PredPS = dyn_cast<PostStmt>(&PredPos)) {
Ted Kremenekea794e92008-05-05 18:50:19 +00002464
Ted Kremenek4c479322008-05-06 23:07:13 +00002465 Stmt* SPred = PredPS->getStmt();
Ted Kremenekea794e92008-05-05 18:50:19 +00002466
2467 // Predecessor at same line?
Ted Kremenek4c479322008-05-06 23:07:13 +00002468 if (SMgr.getLogicalLineNumber(SPred->getLocStart()) != EndLine) {
2469 Hint = PathDiagnosticPiece::Below;
2470 S = SPred;
2471 }
Ted Kremenekea794e92008-05-05 18:50:19 +00002472 }
Ted Kremenekea794e92008-05-05 18:50:19 +00002473
2474 // Generate the diagnostic.
Ted Kremenek4c479322008-05-06 23:07:13 +00002475 FullSourceLoc L( S->getLocStart(), SMgr);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002476 std::ostringstream os;
Ted Kremenek198cae02008-05-02 20:53:50 +00002477
Ted Kremenekea794e92008-05-05 18:50:19 +00002478 os << "Object allocated on line " << AllocLine;
Ted Kremenek198cae02008-05-02 20:53:50 +00002479
2480 if (FirstDecl)
2481 os << " and stored into '" << FirstDecl->getName() << '\'';
2482
Ted Kremenek9363fd92008-05-05 17:53:17 +00002483 os << " is no longer referenced after this point and has a retain count of +"
2484 << RetCount << " (object leaked).";
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002485
Ted Kremenek4c479322008-05-06 23:07:13 +00002486 return new PathDiagnosticPiece(L, os.str(), Hint);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002487}
2488
Ted Kremenek7d421f32008-04-09 23:49:11 +00002489void UseAfterRelease::EmitWarnings(BugReporter& BR) {
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002490
Ted Kremenek7d421f32008-04-09 23:49:11 +00002491 for (CFRefCount::use_after_iterator I = TF.use_after_begin(),
2492 E = TF.use_after_end(); I != E; ++I) {
2493
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002494 CFRefReport report(*this, I->first, I->second.second);
2495 report.addRange(I->second.first->getSourceRange());
Ted Kremenek270ab7d2008-04-18 01:56:37 +00002496 BR.EmitWarning(report);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002497 }
Ted Kremenek7d421f32008-04-09 23:49:11 +00002498}
2499
2500void BadRelease::EmitWarnings(BugReporter& BR) {
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002501
Ted Kremenek7d421f32008-04-09 23:49:11 +00002502 for (CFRefCount::bad_release_iterator I = TF.bad_release_begin(),
2503 E = TF.bad_release_end(); I != E; ++I) {
2504
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002505 CFRefReport report(*this, I->first, I->second.second);
2506 report.addRange(I->second.first->getSourceRange());
2507 BR.EmitWarning(report);
Ted Kremenek7d421f32008-04-09 23:49:11 +00002508 }
2509}
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002510
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00002511void Leak::EmitWarnings(BugReporter& BR) {
2512
2513 for (CFRefCount::leaks_iterator I = TF.leaks_begin(),
2514 E = TF.leaks_end(); I != E; ++I) {
2515
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002516 std::vector<SymbolID>& SymV = *(I->second);
2517 unsigned n = SymV.size();
2518
2519 for (unsigned i = 0; i < n; ++i) {
2520 CFRefReport report(*this, I->first, SymV[i]);
2521 BR.EmitWarning(report);
2522 }
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00002523 }
2524}
2525
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002526void Leak::GetErrorNodes(std::vector<ExplodedNode<ValueState>*>& Nodes) {
2527 for (CFRefCount::leaks_iterator I=TF.leaks_begin(), E=TF.leaks_end();
2528 I!=E; ++I)
2529 Nodes.push_back(I->first);
2530}
2531
Ted Kremenekd7e26782008-05-16 18:33:44 +00002532bool Leak::isCached(BugReport& R) {
2533
2534 // Most bug reports are cached at the location where they occured.
2535 // With leaks, we want to unique them by the location where they were
2536 // allocated, and only report only a single path.
2537
2538 SymbolID Sym = static_cast<CFRefReport&>(R).getSymbol();
2539
2540 ExplodedNode<ValueState>* AllocNode =
2541 GetAllocationSite(R.getEndNode(), Sym).first;
2542
2543 if (!AllocNode)
2544 return false;
2545
2546 return BugTypeCacheLocation::isCached(AllocNode->getLocation());
2547}
2548
Ted Kremeneka7338b42008-03-11 06:39:11 +00002549//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00002550// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00002551//===----------------------------------------------------------------------===//
2552
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002553GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
2554 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00002555 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00002556}