blob: 324916a6f6eb6149309f6f18e1c4257ba18e3448 [file] [log] [blame]
Shih-wei Liaof8fd82b2010-02-10 11:10:31 -08001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
2//
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//
10// This file defines the methods for CFRefCount, which implements
11// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Basic/LangOptions.h"
16#include "clang/Basic/SourceManager.h"
17#include "clang/Checker/PathSensitive/GRExprEngineBuilders.h"
18#include "clang/Checker/PathSensitive/GRStateTrait.h"
19#include "clang/Checker/BugReporter/PathDiagnostic.h"
20#include "clang/Checker/Checkers/LocalCheckers.h"
21#include "clang/Checker/BugReporter/PathDiagnostic.h"
22#include "clang/Checker/BugReporter/BugReporter.h"
23#include "clang/Checker/PathSensitive/SymbolManager.h"
24#include "clang/Checker/PathSensitive/GRTransferFuncs.h"
25#include "clang/Checker/PathSensitive/CheckerVisitor.h"
26#include "clang/Checker/DomainSpecific/CocoaConventions.h"
27#include "clang/AST/DeclObjC.h"
28#include "clang/AST/StmtVisitor.h"
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/ADT/FoldingSet.h"
31#include "llvm/ADT/ImmutableMap.h"
32#include "llvm/ADT/ImmutableList.h"
33#include "llvm/ADT/StringExtras.h"
34#include "llvm/ADT/STLExtras.h"
35#include <stdarg.h>
36
37using namespace clang;
38using llvm::StringRef;
39using llvm::StrInStrNoCase;
40
41static const ObjCMethodDecl*
42ResolveToInterfaceMethodDecl(const ObjCMethodDecl *MD) {
43 ObjCInterfaceDecl *ID =
44 const_cast<ObjCInterfaceDecl*>(MD->getClassInterface());
45
46 return MD->isInstanceMethod()
47 ? ID->lookupInstanceMethod(MD->getSelector())
48 : ID->lookupClassMethod(MD->getSelector());
49}
50
51namespace {
52class GenericNodeBuilder {
53 GRStmtNodeBuilder *SNB;
54 Stmt *S;
55 const void *tag;
56 GREndPathNodeBuilder *ENB;
57public:
58 GenericNodeBuilder(GRStmtNodeBuilder &snb, Stmt *s,
59 const void *t)
60 : SNB(&snb), S(s), tag(t), ENB(0) {}
61
62 GenericNodeBuilder(GREndPathNodeBuilder &enb)
63 : SNB(0), S(0), tag(0), ENB(&enb) {}
64
65 ExplodedNode *MakeNode(const GRState *state, ExplodedNode *Pred) {
66 if (SNB)
67 return SNB->generateNode(PostStmt(S, Pred->getLocationContext(), tag),
68 state, Pred);
69
70 assert(ENB);
71 return ENB->generateNode(state, Pred);
72 }
73};
74} // end anonymous namespace
75
76//===----------------------------------------------------------------------===//
77// Primitives used for constructing summaries for function/method calls.
78//===----------------------------------------------------------------------===//
79
80/// ArgEffect is used to summarize a function/method call's effect on a
81/// particular argument.
82enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
83 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
84 NewAutoreleasePool, SelfOwn, StopTracking };
85
86namespace llvm {
87template <> struct FoldingSetTrait<ArgEffect> {
88static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
89 ID.AddInteger((unsigned) X);
90}
91};
92} // end llvm namespace
93
94/// ArgEffects summarizes the effects of a function/method call on all of
95/// its arguments.
96typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
97
98namespace {
99
100/// RetEffect is used to summarize a function/method call's behavior with
101/// respect to its return value.
102class RetEffect {
103public:
104 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
105 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias,
106 OwnedWhenTrackedReceiver };
107
108 enum ObjKind { CF, ObjC, AnyObj };
109
110private:
111 Kind K;
112 ObjKind O;
113 unsigned index;
114
115 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
116 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
117
118public:
119 Kind getKind() const { return K; }
120
121 ObjKind getObjKind() const { return O; }
122
123 unsigned getIndex() const {
124 assert(getKind() == Alias);
125 return index;
126 }
127
128 bool isOwned() const {
129 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
130 K == OwnedWhenTrackedReceiver;
131 }
132
133 static RetEffect MakeOwnedWhenTrackedReceiver() {
134 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
135 }
136
137 static RetEffect MakeAlias(unsigned Idx) {
138 return RetEffect(Alias, Idx);
139 }
140 static RetEffect MakeReceiverAlias() {
141 return RetEffect(ReceiverAlias);
142 }
143 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
144 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
145 }
146 static RetEffect MakeNotOwned(ObjKind o) {
147 return RetEffect(NotOwnedSymbol, o);
148 }
149 static RetEffect MakeGCNotOwned() {
150 return RetEffect(GCNotOwnedSymbol, ObjC);
151 }
152
153 static RetEffect MakeNoRet() {
154 return RetEffect(NoRet);
155 }
156
157 void Profile(llvm::FoldingSetNodeID& ID) const {
158 ID.AddInteger((unsigned)K);
159 ID.AddInteger((unsigned)O);
160 ID.AddInteger(index);
161 }
162};
163
164//===----------------------------------------------------------------------===//
165// Reference-counting logic (typestate + counts).
166//===----------------------------------------------------------------------===//
167
168class RefVal {
169public:
170 enum Kind {
171 Owned = 0, // Owning reference.
172 NotOwned, // Reference is not owned by still valid (not freed).
173 Released, // Object has been released.
174 ReturnedOwned, // Returned object passes ownership to caller.
175 ReturnedNotOwned, // Return object does not pass ownership to caller.
176 ERROR_START,
177 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
178 ErrorDeallocGC, // Calling -dealloc with GC enabled.
179 ErrorUseAfterRelease, // Object used after released.
180 ErrorReleaseNotOwned, // Release of an object that was not owned.
181 ERROR_LEAK_START,
182 ErrorLeak, // A memory leak due to excessive reference counts.
183 ErrorLeakReturned, // A memory leak due to the returning method not having
184 // the correct naming conventions.
185 ErrorGCLeakReturned,
186 ErrorOverAutorelease,
187 ErrorReturnedNotOwned
188 };
189
190private:
191 Kind kind;
192 RetEffect::ObjKind okind;
193 unsigned Cnt;
194 unsigned ACnt;
195 QualType T;
196
197 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
198 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
199
200 RefVal(Kind k, unsigned cnt = 0)
201 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
202
203public:
204 Kind getKind() const { return kind; }
205
206 RetEffect::ObjKind getObjKind() const { return okind; }
207
208 unsigned getCount() const { return Cnt; }
209 unsigned getAutoreleaseCount() const { return ACnt; }
210 unsigned getCombinedCounts() const { return Cnt + ACnt; }
211 void clearCounts() { Cnt = 0; ACnt = 0; }
212 void setCount(unsigned i) { Cnt = i; }
213 void setAutoreleaseCount(unsigned i) { ACnt = i; }
214
215 QualType getType() const { return T; }
216
217 // Useful predicates.
218
219 static bool isError(Kind k) { return k >= ERROR_START; }
220
221 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
222
223 bool isOwned() const {
224 return getKind() == Owned;
225 }
226
227 bool isNotOwned() const {
228 return getKind() == NotOwned;
229 }
230
231 bool isReturnedOwned() const {
232 return getKind() == ReturnedOwned;
233 }
234
235 bool isReturnedNotOwned() const {
236 return getKind() == ReturnedNotOwned;
237 }
238
239 bool isNonLeakError() const {
240 Kind k = getKind();
241 return isError(k) && !isLeak(k);
242 }
243
244 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
245 unsigned Count = 1) {
246 return RefVal(Owned, o, Count, 0, t);
247 }
248
249 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
250 unsigned Count = 0) {
251 return RefVal(NotOwned, o, Count, 0, t);
252 }
253
254 // Comparison, profiling, and pretty-printing.
255
256 bool operator==(const RefVal& X) const {
257 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
258 }
259
260 RefVal operator-(size_t i) const {
261 return RefVal(getKind(), getObjKind(), getCount() - i,
262 getAutoreleaseCount(), getType());
263 }
264
265 RefVal operator+(size_t i) const {
266 return RefVal(getKind(), getObjKind(), getCount() + i,
267 getAutoreleaseCount(), getType());
268 }
269
270 RefVal operator^(Kind k) const {
271 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
272 getType());
273 }
274
275 RefVal autorelease() const {
276 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
277 getType());
278 }
279
280 void Profile(llvm::FoldingSetNodeID& ID) const {
281 ID.AddInteger((unsigned) kind);
282 ID.AddInteger(Cnt);
283 ID.AddInteger(ACnt);
284 ID.Add(T);
285 }
286
287 void print(llvm::raw_ostream& Out) const;
288};
289
290void RefVal::print(llvm::raw_ostream& Out) const {
291 if (!T.isNull())
292 Out << "Tracked Type:" << T.getAsString() << '\n';
293
294 switch (getKind()) {
295 default: assert(false);
296 case Owned: {
297 Out << "Owned";
298 unsigned cnt = getCount();
299 if (cnt) Out << " (+ " << cnt << ")";
300 break;
301 }
302
303 case NotOwned: {
304 Out << "NotOwned";
305 unsigned cnt = getCount();
306 if (cnt) Out << " (+ " << cnt << ")";
307 break;
308 }
309
310 case ReturnedOwned: {
311 Out << "ReturnedOwned";
312 unsigned cnt = getCount();
313 if (cnt) Out << " (+ " << cnt << ")";
314 break;
315 }
316
317 case ReturnedNotOwned: {
318 Out << "ReturnedNotOwned";
319 unsigned cnt = getCount();
320 if (cnt) Out << " (+ " << cnt << ")";
321 break;
322 }
323
324 case Released:
325 Out << "Released";
326 break;
327
328 case ErrorDeallocGC:
329 Out << "-dealloc (GC)";
330 break;
331
332 case ErrorDeallocNotOwned:
333 Out << "-dealloc (not-owned)";
334 break;
335
336 case ErrorLeak:
337 Out << "Leaked";
338 break;
339
340 case ErrorLeakReturned:
341 Out << "Leaked (Bad naming)";
342 break;
343
344 case ErrorGCLeakReturned:
345 Out << "Leaked (GC-ed at return)";
346 break;
347
348 case ErrorUseAfterRelease:
349 Out << "Use-After-Release [ERROR]";
350 break;
351
352 case ErrorReleaseNotOwned:
353 Out << "Release of Not-Owned [ERROR]";
354 break;
355
356 case RefVal::ErrorOverAutorelease:
357 Out << "Over autoreleased";
358 break;
359
360 case RefVal::ErrorReturnedNotOwned:
361 Out << "Non-owned object returned instead of owned";
362 break;
363 }
364
365 if (ACnt) {
366 Out << " [ARC +" << ACnt << ']';
367 }
368}
369} //end anonymous namespace
370
371//===----------------------------------------------------------------------===//
372// RefBindings - State used to track object reference counts.
373//===----------------------------------------------------------------------===//
374
375typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
376
377namespace clang {
378 template<>
379 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
380 static void* GDMIndex() {
381 static int RefBIndex = 0;
382 return &RefBIndex;
383 }
384 };
385}
386
387//===----------------------------------------------------------------------===//
388// Summaries
389//===----------------------------------------------------------------------===//
390
391namespace {
392class RetainSummary {
393 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
394 /// specifies the argument (starting from 0). This can be sparsely
395 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
396 ArgEffects Args;
397
398 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
399 /// do not have an entry in Args.
400 ArgEffect DefaultArgEffect;
401
402 /// Receiver - If this summary applies to an Objective-C message expression,
403 /// this is the effect applied to the state of the receiver.
404 ArgEffect Receiver;
405
406 /// Ret - The effect on the return value. Used to indicate if the
407 /// function/method call returns a new tracked symbol, returns an
408 /// alias of one of the arguments in the call, and so on.
409 RetEffect Ret;
410
411 /// EndPath - Indicates that execution of this method/function should
412 /// terminate the simulation of a path.
413 bool EndPath;
414
415public:
416 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
417 ArgEffect ReceiverEff, bool endpath = false)
418 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
419 EndPath(endpath) {}
420
421 /// getArg - Return the argument effect on the argument specified by
422 /// idx (starting from 0).
423 ArgEffect getArg(unsigned idx) const {
424 if (const ArgEffect *AE = Args.lookup(idx))
425 return *AE;
426
427 return DefaultArgEffect;
428 }
429
430 /// setDefaultArgEffect - Set the default argument effect.
431 void setDefaultArgEffect(ArgEffect E) {
432 DefaultArgEffect = E;
433 }
434
435 /// setArg - Set the argument effect on the argument specified by idx.
436 void setArgEffect(ArgEffects::Factory& AF, unsigned idx, ArgEffect E) {
437 Args = AF.Add(Args, idx, E);
438 }
439
440 /// getRetEffect - Returns the effect on the return value of the call.
441 RetEffect getRetEffect() const { return Ret; }
442
443 /// setRetEffect - Set the effect of the return value of the call.
444 void setRetEffect(RetEffect E) { Ret = E; }
445
446 /// isEndPath - Returns true if executing the given method/function should
447 /// terminate the path.
448 bool isEndPath() const { return EndPath; }
449
450 /// getReceiverEffect - Returns the effect on the receiver of the call.
451 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
452 ArgEffect getReceiverEffect() const { return Receiver; }
453
454 /// setReceiverEffect - Set the effect on the receiver of the call.
455 void setReceiverEffect(ArgEffect E) { Receiver = E; }
456
457 typedef ArgEffects::iterator ExprIterator;
458
459 ExprIterator begin_args() const { return Args.begin(); }
460 ExprIterator end_args() const { return Args.end(); }
461
462 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
463 RetEffect RetEff, ArgEffect DefaultEff,
464 ArgEffect ReceiverEff, bool EndPath) {
465 ID.Add(A);
466 ID.Add(RetEff);
467 ID.AddInteger((unsigned) DefaultEff);
468 ID.AddInteger((unsigned) ReceiverEff);
469 ID.AddInteger((unsigned) EndPath);
470 }
471
472 void Profile(llvm::FoldingSetNodeID& ID) const {
473 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
474 }
475};
476} // end anonymous namespace
477
478//===----------------------------------------------------------------------===//
479// Data structures for constructing summaries.
480//===----------------------------------------------------------------------===//
481
482namespace {
483class ObjCSummaryKey {
484 IdentifierInfo* II;
485 Selector S;
486public:
487 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
488 : II(ii), S(s) {}
489
490 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
491 : II(d ? d->getIdentifier() : 0), S(s) {}
492
493 ObjCSummaryKey(const ObjCInterfaceDecl* d, IdentifierInfo *ii, Selector s)
494 : II(d ? d->getIdentifier() : ii), S(s) {}
495
496 ObjCSummaryKey(Selector s)
497 : II(0), S(s) {}
498
499 IdentifierInfo* getIdentifier() const { return II; }
500 Selector getSelector() const { return S; }
501};
502}
503
504namespace llvm {
505template <> struct DenseMapInfo<ObjCSummaryKey> {
506 static inline ObjCSummaryKey getEmptyKey() {
507 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
508 DenseMapInfo<Selector>::getEmptyKey());
509 }
510
511 static inline ObjCSummaryKey getTombstoneKey() {
512 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
513 DenseMapInfo<Selector>::getTombstoneKey());
514 }
515
516 static unsigned getHashValue(const ObjCSummaryKey &V) {
517 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
518 & 0x88888888)
519 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
520 & 0x55555555);
521 }
522
523 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
524 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
525 RHS.getIdentifier()) &&
526 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
527 RHS.getSelector());
528 }
529
530};
531template <>
532struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
533} // end llvm namespace
534
535namespace {
536class ObjCSummaryCache {
537 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
538 MapTy M;
539public:
540 ObjCSummaryCache() {}
541
542 RetainSummary* find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
543 Selector S) {
544 // Lookup the method using the decl for the class @interface. If we
545 // have no decl, lookup using the class name.
546 return D ? find(D, S) : find(ClsName, S);
547 }
548
549 RetainSummary* find(const ObjCInterfaceDecl* D, Selector S) {
550 // Do a lookup with the (D,S) pair. If we find a match return
551 // the iterator.
552 ObjCSummaryKey K(D, S);
553 MapTy::iterator I = M.find(K);
554
555 if (I != M.end() || !D)
556 return I->second;
557
558 // Walk the super chain. If we find a hit with a parent, we'll end
559 // up returning that summary. We actually allow that key (null,S), as
560 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
561 // generate initial summaries without having to worry about NSObject
562 // being declared.
563 // FIXME: We may change this at some point.
564 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
565 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
566 break;
567
568 if (!C)
569 return NULL;
570 }
571
572 // Cache the summary with original key to make the next lookup faster
573 // and return the iterator.
574 RetainSummary *Summ = I->second;
575 M[K] = Summ;
576 return Summ;
577 }
578
579
580 RetainSummary* find(Expr* Receiver, Selector S) {
581 return find(getReceiverDecl(Receiver), S);
582 }
583
584 RetainSummary* find(IdentifierInfo* II, Selector S) {
585 // FIXME: Class method lookup. Right now we dont' have a good way
586 // of going between IdentifierInfo* and the class hierarchy.
587 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
588
589 if (I == M.end())
590 I = M.find(ObjCSummaryKey(S));
591
592 return I == M.end() ? NULL : I->second;
593 }
594
595 const ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
596 if (const ObjCObjectPointerType* PT =
597 E->getType()->getAs<ObjCObjectPointerType>())
598 return PT->getInterfaceDecl();
599
600 return NULL;
601 }
602
603 RetainSummary*& operator[](ObjCMessageExpr* ME) {
604
605 Selector S = ME->getSelector();
606
607 if (Expr* Receiver = ME->getReceiver()) {
608 const ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
609 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
610 }
611
612 return M[ObjCSummaryKey(ME->getClassName(), S)];
613 }
614
615 RetainSummary*& operator[](ObjCSummaryKey K) {
616 return M[K];
617 }
618
619 RetainSummary*& operator[](Selector S) {
620 return M[ ObjCSummaryKey(S) ];
621 }
622};
623} // end anonymous namespace
624
625//===----------------------------------------------------------------------===//
626// Data structures for managing collections of summaries.
627//===----------------------------------------------------------------------===//
628
629namespace {
630class RetainSummaryManager {
631
632 //==-----------------------------------------------------------------==//
633 // Typedefs.
634 //==-----------------------------------------------------------------==//
635
636 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
637 FuncSummariesTy;
638
639 typedef ObjCSummaryCache ObjCMethodSummariesTy;
640
641 //==-----------------------------------------------------------------==//
642 // Data.
643 //==-----------------------------------------------------------------==//
644
645 /// Ctx - The ASTContext object for the analyzed ASTs.
646 ASTContext& Ctx;
647
648 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
649 /// "CFDictionaryCreate".
650 IdentifierInfo* CFDictionaryCreateII;
651
652 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
653 const bool GCEnabled;
654
655 /// FuncSummaries - A map from FunctionDecls to summaries.
656 FuncSummariesTy FuncSummaries;
657
658 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
659 /// to summaries.
660 ObjCMethodSummariesTy ObjCClassMethodSummaries;
661
662 /// ObjCMethodSummaries - A map from selectors to summaries.
663 ObjCMethodSummariesTy ObjCMethodSummaries;
664
665 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
666 /// and all other data used by the checker.
667 llvm::BumpPtrAllocator BPAlloc;
668
669 /// AF - A factory for ArgEffects objects.
670 ArgEffects::Factory AF;
671
672 /// ScratchArgs - A holding buffer for construct ArgEffects.
673 ArgEffects ScratchArgs;
674
675 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
676 /// objects.
677 RetEffect ObjCAllocRetE;
678
679 /// ObjCInitRetE - Default return effect for init methods returning
680 /// Objective-C objects.
681 RetEffect ObjCInitRetE;
682
683 RetainSummary DefaultSummary;
684 RetainSummary* StopSummary;
685
686 //==-----------------------------------------------------------------==//
687 // Methods.
688 //==-----------------------------------------------------------------==//
689
690 /// getArgEffects - Returns a persistent ArgEffects object based on the
691 /// data in ScratchArgs.
692 ArgEffects getArgEffects();
693
694 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
695
696public:
697 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
698
699 RetainSummary *getDefaultSummary() {
700 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
701 return new (Summ) RetainSummary(DefaultSummary);
702 }
703
704 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
705
706 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
707 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
708 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, StringRef FName);
709
710 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
711 ArgEffect ReceiverEff = DoNothing,
712 ArgEffect DefaultEff = MayEscape,
713 bool isEndPath = false);
714
715 RetainSummary* getPersistentSummary(RetEffect RE,
716 ArgEffect ReceiverEff = DoNothing,
717 ArgEffect DefaultEff = MayEscape) {
718 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
719 }
720
721 RetainSummary *getPersistentStopSummary() {
722 if (StopSummary)
723 return StopSummary;
724
725 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
726 StopTracking, StopTracking);
727
728 return StopSummary;
729 }
730
731 RetainSummary *getInitMethodSummary(QualType RetTy);
732
733 void InitializeClassMethodSummaries();
734 void InitializeMethodSummaries();
735private:
736
737 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
738 RetainSummary* Summ) {
739 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
740 }
741
742 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
743 ObjCClassMethodSummaries[S] = Summ;
744 }
745
746 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
747 ObjCMethodSummaries[S] = Summ;
748 }
749
750 void addClassMethSummary(const char* Cls, const char* nullaryName,
751 RetainSummary *Summ) {
752 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
753 Selector S = GetNullarySelector(nullaryName, Ctx);
754 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
755 }
756
757 void addInstMethSummary(const char* Cls, const char* nullaryName,
758 RetainSummary *Summ) {
759 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
760 Selector S = GetNullarySelector(nullaryName, Ctx);
761 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
762 }
763
764 Selector generateSelector(va_list argp) {
765 llvm::SmallVector<IdentifierInfo*, 10> II;
766
767 while (const char* s = va_arg(argp, const char*))
768 II.push_back(&Ctx.Idents.get(s));
769
770 return Ctx.Selectors.getSelector(II.size(), &II[0]);
771 }
772
773 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
774 RetainSummary* Summ, va_list argp) {
775 Selector S = generateSelector(argp);
776 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
777 }
778
779 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
780 va_list argp;
781 va_start(argp, Summ);
782 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
783 va_end(argp);
784 }
785
786 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
787 va_list argp;
788 va_start(argp, Summ);
789 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
790 va_end(argp);
791 }
792
793 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
794 va_list argp;
795 va_start(argp, Summ);
796 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
797 va_end(argp);
798 }
799
800 void addPanicSummary(const char* Cls, ...) {
801 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
802 RetEffect::MakeNoRet(),
803 DoNothing, DoNothing, true);
804 va_list argp;
805 va_start (argp, Cls);
806 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
807 va_end(argp);
808 }
809
810public:
811
812 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
813 : Ctx(ctx),
814 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
815 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
816 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
817 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
818 ObjCInitRetE(gcenabled ? RetEffect::MakeGCNotOwned()
819 : RetEffect::MakeOwnedWhenTrackedReceiver()),
820 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
821 RetEffect::MakeNoRet() /* return effect */,
822 MayEscape, /* default argument effect */
823 DoNothing /* receiver effect */),
824 StopSummary(0) {
825
826 InitializeClassMethodSummaries();
827 InitializeMethodSummaries();
828 }
829
830 ~RetainSummaryManager();
831
832 RetainSummary* getSummary(FunctionDecl* FD);
833
834 RetainSummary *getInstanceMethodSummary(const ObjCMessageExpr *ME,
835 const GRState *state,
836 const LocationContext *LC);
837
838 RetainSummary* getInstanceMethodSummary(const ObjCMessageExpr* ME,
839 const ObjCInterfaceDecl* ID) {
840 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
841 ID, ME->getMethodDecl(), ME->getType());
842 }
843
844 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
845 const ObjCInterfaceDecl* ID,
846 const ObjCMethodDecl *MD,
847 QualType RetTy);
848
849 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
850 const ObjCInterfaceDecl *ID,
851 const ObjCMethodDecl *MD,
852 QualType RetTy);
853
854 RetainSummary *getClassMethodSummary(const ObjCMessageExpr *ME) {
855 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
856 ME->getClassInfo().first,
857 ME->getMethodDecl(), ME->getType());
858 }
859
860 /// getMethodSummary - This version of getMethodSummary is used to query
861 /// the summary for the current method being analyzed.
862 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
863 // FIXME: Eventually this should be unneeded.
864 const ObjCInterfaceDecl *ID = MD->getClassInterface();
865 Selector S = MD->getSelector();
866 IdentifierInfo *ClsName = ID->getIdentifier();
867 QualType ResultTy = MD->getResultType();
868
869 // Resolve the method decl last.
870 if (const ObjCMethodDecl *InterfaceMD = ResolveToInterfaceMethodDecl(MD))
871 MD = InterfaceMD;
872
873 if (MD->isInstanceMethod())
874 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
875 else
876 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
877 }
878
879 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
880 Selector S, QualType RetTy);
881
882 void updateSummaryFromAnnotations(RetainSummary &Summ,
883 const ObjCMethodDecl *MD);
884
885 void updateSummaryFromAnnotations(RetainSummary &Summ,
886 const FunctionDecl *FD);
887
888 bool isGCEnabled() const { return GCEnabled; }
889
890 RetainSummary *copySummary(RetainSummary *OldSumm) {
891 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
892 new (Summ) RetainSummary(*OldSumm);
893 return Summ;
894 }
895};
896
897} // end anonymous namespace
898
899//===----------------------------------------------------------------------===//
900// Implementation of checker data structures.
901//===----------------------------------------------------------------------===//
902
903RetainSummaryManager::~RetainSummaryManager() {}
904
905ArgEffects RetainSummaryManager::getArgEffects() {
906 ArgEffects AE = ScratchArgs;
907 ScratchArgs = AF.GetEmptyMap();
908 return AE;
909}
910
911RetainSummary*
912RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
913 ArgEffect ReceiverEff,
914 ArgEffect DefaultEff,
915 bool isEndPath) {
916 // Create the summary and return it.
917 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
918 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
919 return Summ;
920}
921
922//===----------------------------------------------------------------------===//
923// Summary creation for functions (largely uses of Core Foundation).
924//===----------------------------------------------------------------------===//
925
926static bool isRetain(FunctionDecl* FD, StringRef FName) {
927 return FName.endswith("Retain");
928}
929
930static bool isRelease(FunctionDecl* FD, StringRef FName) {
931 return FName.endswith("Release");
932}
933
934RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
935 // Look up a summary in our cache of FunctionDecls -> Summaries.
936 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
937 if (I != FuncSummaries.end())
938 return I->second;
939
940 // No summary? Generate one.
941 RetainSummary *S = 0;
942
943 do {
944 // We generate "stop" summaries for implicitly defined functions.
945 if (FD->isImplicit()) {
946 S = getPersistentStopSummary();
947 break;
948 }
949
950 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
951 // function's type.
952 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
953 const IdentifierInfo *II = FD->getIdentifier();
954 if (!II)
955 break;
956
957 StringRef FName = II->getName();
958
959 // Strip away preceding '_'. Doing this here will effect all the checks
960 // down below.
961 FName = FName.substr(FName.find_first_not_of('_'));
962
963 // Inspect the result type.
964 QualType RetTy = FT->getResultType();
965
966 // FIXME: This should all be refactored into a chain of "summary lookup"
967 // filters.
968 assert(ScratchArgs.isEmpty());
969
970 if (FName == "pthread_create") {
971 // Part of: <rdar://problem/7299394>. This will be addressed
972 // better with IPA.
973 S = getPersistentStopSummary();
974 } else if (FName == "NSMakeCollectable") {
975 // Handle: id NSMakeCollectable(CFTypeRef)
976 S = (RetTy->isObjCIdType())
977 ? getUnarySummary(FT, cfmakecollectable)
978 : getPersistentStopSummary();
979 } else if (FName == "IOBSDNameMatching" ||
980 FName == "IOServiceMatching" ||
981 FName == "IOServiceNameMatching" ||
982 FName == "IORegistryEntryIDMatching" ||
983 FName == "IOOpenFirmwarePathMatching") {
984 // Part of <rdar://problem/6961230>. (IOKit)
985 // This should be addressed using a API table.
986 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
987 DoNothing, DoNothing);
988 } else if (FName == "IOServiceGetMatchingService" ||
989 FName == "IOServiceGetMatchingServices") {
990 // FIXES: <rdar://problem/6326900>
991 // This should be addressed using a API table. This strcmp is also
992 // a little gross, but there is no need to super optimize here.
993 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
994 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
995 } else if (FName == "IOServiceAddNotification" ||
996 FName == "IOServiceAddMatchingNotification") {
997 // Part of <rdar://problem/6961230>. (IOKit)
998 // This should be addressed using a API table.
999 ScratchArgs = AF.Add(ScratchArgs, 2, DecRef);
1000 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1001 } else if (FName == "CVPixelBufferCreateWithBytes") {
1002 // FIXES: <rdar://problem/7283567>
1003 // Eventually this can be improved by recognizing that the pixel
1004 // buffer passed to CVPixelBufferCreateWithBytes is released via
1005 // a callback and doing full IPA to make sure this is done correctly.
1006 // FIXME: This function has an out parameter that returns an
1007 // allocated object.
1008 ScratchArgs = AF.Add(ScratchArgs, 7, StopTracking);
1009 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1010 } else if (FName == "CGBitmapContextCreateWithData") {
1011 // FIXES: <rdar://problem/7358899>
1012 // Eventually this can be improved by recognizing that 'releaseInfo'
1013 // passed to CGBitmapContextCreateWithData is released via
1014 // a callback and doing full IPA to make sure this is done correctly.
1015 ScratchArgs = AF.Add(ScratchArgs, 8, StopTracking);
1016 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1017 DoNothing, DoNothing);
1018 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1019 // FIXES: <rdar://problem/7283567>
1020 // Eventually this can be improved by recognizing that the pixel
1021 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1022 // via a callback and doing full IPA to make sure this is done
1023 // correctly.
1024 ScratchArgs = AF.Add(ScratchArgs, 12, StopTracking);
1025 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1026 }
1027
1028 // Did we get a summary?
1029 if (S)
1030 break;
1031
1032 // Enable this code once the semantics of NSDeallocateObject are resolved
1033 // for GC. <rdar://problem/6619988>
1034#if 0
1035 // Handle: NSDeallocateObject(id anObject);
1036 // This method does allow 'nil' (although we don't check it now).
1037 if (strcmp(FName, "NSDeallocateObject") == 0) {
1038 return RetTy == Ctx.VoidTy
1039 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
1040 : getPersistentStopSummary();
1041 }
1042#endif
1043
1044 if (RetTy->isPointerType()) {
1045 // For CoreFoundation ('CF') types.
1046 if (cocoa::isRefType(RetTy, "CF", FName)) {
1047 if (isRetain(FD, FName))
1048 S = getUnarySummary(FT, cfretain);
1049 else if (FName.find("MakeCollectable") != StringRef::npos)
1050 S = getUnarySummary(FT, cfmakecollectable);
1051 else
1052 S = getCFCreateGetRuleSummary(FD, FName);
1053
1054 break;
1055 }
1056
1057 // For CoreGraphics ('CG') types.
1058 if (cocoa::isRefType(RetTy, "CG", FName)) {
1059 if (isRetain(FD, FName))
1060 S = getUnarySummary(FT, cfretain);
1061 else
1062 S = getCFCreateGetRuleSummary(FD, FName);
1063
1064 break;
1065 }
1066
1067 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1068 if (cocoa::isRefType(RetTy, "DADisk") ||
1069 cocoa::isRefType(RetTy, "DADissenter") ||
1070 cocoa::isRefType(RetTy, "DASessionRef")) {
1071 S = getCFCreateGetRuleSummary(FD, FName);
1072 break;
1073 }
1074
1075 break;
1076 }
1077
1078 // Check for release functions, the only kind of functions that we care
1079 // about that don't return a pointer type.
1080 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
1081 // Test for 'CGCF'.
1082 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
1083
1084 if (isRelease(FD, FName))
1085 S = getUnarySummary(FT, cfrelease);
1086 else {
1087 assert (ScratchArgs.isEmpty());
1088 // Remaining CoreFoundation and CoreGraphics functions.
1089 // We use to assume that they all strictly followed the ownership idiom
1090 // and that ownership cannot be transferred. While this is technically
1091 // correct, many methods allow a tracked object to escape. For example:
1092 //
1093 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1094 // CFDictionaryAddValue(y, key, x);
1095 // CFRelease(x);
1096 // ... it is okay to use 'x' since 'y' has a reference to it
1097 //
1098 // We handle this and similar cases with the follow heuristic. If the
1099 // function name contains "InsertValue", "SetValue", "AddValue",
1100 // "AppendValue", or "SetAttribute", then we assume that arguments may
1101 // "escape." This means that something else holds on to the object,
1102 // allowing it be used even after its local retain count drops to 0.
1103 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1104 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1105 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1106 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
1107 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
1108 ? MayEscape : DoNothing;
1109
1110 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
1111 }
1112 }
1113 }
1114 while (0);
1115
1116 if (!S)
1117 S = getDefaultSummary();
1118
1119 // Annotations override defaults.
1120 assert(S);
1121 updateSummaryFromAnnotations(*S, FD);
1122
1123 FuncSummaries[FD] = S;
1124 return S;
1125}
1126
1127RetainSummary*
1128RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1129 StringRef FName) {
1130
1131 if (FName.find("Create") != StringRef::npos ||
1132 FName.find("Copy") != StringRef::npos)
1133 return getCFSummaryCreateRule(FD);
1134
1135 if (FName.find("Get") != StringRef::npos)
1136 return getCFSummaryGetRule(FD);
1137
1138 return getDefaultSummary();
1139}
1140
1141RetainSummary*
1142RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1143 UnaryFuncKind func) {
1144
1145 // Sanity check that this is *really* a unary function. This can
1146 // happen if people do weird things.
1147 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
1148 if (!FTP || FTP->getNumArgs() != 1)
1149 return getPersistentStopSummary();
1150
1151 assert (ScratchArgs.isEmpty());
1152
1153 switch (func) {
1154 case cfretain: {
1155 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
1156 return getPersistentSummary(RetEffect::MakeAlias(0),
1157 DoNothing, DoNothing);
1158 }
1159
1160 case cfrelease: {
1161 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
1162 return getPersistentSummary(RetEffect::MakeNoRet(),
1163 DoNothing, DoNothing);
1164 }
1165
1166 case cfmakecollectable: {
1167 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
1168 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
1169 }
1170
1171 default:
1172 assert (false && "Not a supported unary function.");
1173 return getDefaultSummary();
1174 }
1175}
1176
1177RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
1178 assert (ScratchArgs.isEmpty());
1179
1180 if (FD->getIdentifier() == CFDictionaryCreateII) {
1181 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1182 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
1183 }
1184
1185 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
1186}
1187
1188RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
1189 assert (ScratchArgs.isEmpty());
1190 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1191 DoNothing, DoNothing);
1192}
1193
1194//===----------------------------------------------------------------------===//
1195// Summary creation for Selectors.
1196//===----------------------------------------------------------------------===//
1197
1198RetainSummary*
1199RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
1200 assert(ScratchArgs.isEmpty());
1201 // 'init' methods conceptually return a newly allocated object and claim
1202 // the receiver.
1203 if (cocoa::isCocoaObjectRef(RetTy) || cocoa::isCFObjectRef(RetTy))
1204 return getPersistentSummary(ObjCInitRetE, DecRefMsg);
1205
1206 return getDefaultSummary();
1207}
1208
1209void
1210RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1211 const FunctionDecl *FD) {
1212 if (!FD)
1213 return;
1214
1215 QualType RetTy = FD->getResultType();
1216
1217 // Determine if there is a special return effect for this method.
1218 if (cocoa::isCocoaObjectRef(RetTy)) {
1219 if (FD->getAttr<NSReturnsRetainedAttr>()) {
1220 Summ.setRetEffect(ObjCAllocRetE);
1221 }
1222 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
1223 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1224 }
1225 }
1226 else if (RetTy->getAs<PointerType>()) {
1227 if (FD->getAttr<CFReturnsRetainedAttr>()) {
1228 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1229 }
1230 }
1231}
1232
1233void
1234RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1235 const ObjCMethodDecl *MD) {
1236 if (!MD)
1237 return;
1238
1239 bool isTrackedLoc = false;
1240
1241 // Determine if there is a special return effect for this method.
1242 if (cocoa::isCocoaObjectRef(MD->getResultType())) {
1243 if (MD->getAttr<NSReturnsRetainedAttr>()) {
1244 Summ.setRetEffect(ObjCAllocRetE);
1245 return;
1246 }
1247
1248 isTrackedLoc = true;
1249 }
1250
1251 if (!isTrackedLoc)
1252 isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
1253
1254 if (isTrackedLoc && MD->getAttr<CFReturnsRetainedAttr>())
1255 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1256}
1257
1258RetainSummary*
1259RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1260 Selector S, QualType RetTy) {
1261
1262 if (MD) {
1263 // Scan the method decl for 'void*' arguments. These should be treated
1264 // as 'StopTracking' because they are often used with delegates.
1265 // Delegates are a frequent form of false positives with the retain
1266 // count checker.
1267 unsigned i = 0;
1268 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1269 E = MD->param_end(); I != E; ++I, ++i)
1270 if (ParmVarDecl *PD = *I) {
1271 QualType Ty = Ctx.getCanonicalType(PD->getType());
1272 if (Ty.getLocalUnqualifiedType() == Ctx.VoidPtrTy)
1273 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
1274 }
1275 }
1276
1277 // Any special effect for the receiver?
1278 ArgEffect ReceiverEff = DoNothing;
1279
1280 // If one of the arguments in the selector has the keyword 'delegate' we
1281 // should stop tracking the reference count for the receiver. This is
1282 // because the reference count is quite possibly handled by a delegate
1283 // method.
1284 if (S.isKeywordSelector()) {
1285 const std::string &str = S.getAsString();
1286 assert(!str.empty());
1287 if (StrInStrNoCase(str, "delegate:") != StringRef::npos)
1288 ReceiverEff = StopTracking;
1289 }
1290
1291 // Look for methods that return an owned object.
1292 if (cocoa::isCocoaObjectRef(RetTy)) {
1293 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1294 // by instance methods.
1295 RetEffect E = cocoa::followsFundamentalRule(S)
1296 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
1297
1298 return getPersistentSummary(E, ReceiverEff, MayEscape);
1299 }
1300
1301 // Look for methods that return an owned core foundation object.
1302 if (cocoa::isCFObjectRef(RetTy)) {
1303 RetEffect E = cocoa::followsFundamentalRule(S)
1304 ? RetEffect::MakeOwned(RetEffect::CF, true)
1305 : RetEffect::MakeNotOwned(RetEffect::CF);
1306
1307 return getPersistentSummary(E, ReceiverEff, MayEscape);
1308 }
1309
1310 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
1311 return getDefaultSummary();
1312
1313 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
1314}
1315
1316RetainSummary*
1317RetainSummaryManager::getInstanceMethodSummary(const ObjCMessageExpr *ME,
1318 const GRState *state,
1319 const LocationContext *LC) {
1320
1321 // We need the type-information of the tracked receiver object
1322 // Retrieve it from the state.
1323 const Expr *Receiver = ME->getReceiver();
1324 const ObjCInterfaceDecl* ID = 0;
1325
1326 // FIXME: Is this really working as expected? There are cases where
1327 // we just use the 'ID' from the message expression.
1328 SVal receiverV = state->getSValAsScalarOrLoc(Receiver);
1329
1330 // FIXME: Eventually replace the use of state->get<RefBindings> with
1331 // a generic API for reasoning about the Objective-C types of symbolic
1332 // objects.
1333 if (SymbolRef Sym = receiverV.getAsLocSymbol())
1334 if (const RefVal *T = state->get<RefBindings>(Sym))
1335 if (const ObjCObjectPointerType* PT =
1336 T->getType()->getAs<ObjCObjectPointerType>())
1337 ID = PT->getInterfaceDecl();
1338
1339 // FIXME: this is a hack. This may or may not be the actual method
1340 // that is called.
1341 if (!ID) {
1342 if (const ObjCObjectPointerType *PT =
1343 Receiver->getType()->getAs<ObjCObjectPointerType>())
1344 ID = PT->getInterfaceDecl();
1345 }
1346
1347 // FIXME: The receiver could be a reference to a class, meaning that
1348 // we should use the class method.
1349 RetainSummary *Summ = getInstanceMethodSummary(ME, ID);
1350
1351 // Special-case: are we sending a mesage to "self"?
1352 // This is a hack. When we have full-IP this should be removed.
1353 if (isa<ObjCMethodDecl>(LC->getDecl())) {
1354 if (const loc::MemRegionVal *L = dyn_cast<loc::MemRegionVal>(&receiverV)) {
1355 // Get the region associated with 'self'.
1356 if (const ImplicitParamDecl *SelfDecl = LC->getSelfDecl()) {
1357 SVal SelfVal = state->getSVal(state->getRegion(SelfDecl, LC));
1358 if (L->StripCasts() == SelfVal.getAsRegion()) {
1359 // Update the summary to make the default argument effect
1360 // 'StopTracking'.
1361 Summ = copySummary(Summ);
1362 Summ->setDefaultArgEffect(StopTracking);
1363 }
1364 }
1365 }
1366 }
1367
1368 return Summ ? Summ : getDefaultSummary();
1369}
1370
1371RetainSummary*
1372RetainSummaryManager::getInstanceMethodSummary(Selector S,
1373 IdentifierInfo *ClsName,
1374 const ObjCInterfaceDecl* ID,
1375 const ObjCMethodDecl *MD,
1376 QualType RetTy) {
1377
1378 // Look up a summary in our summary cache.
1379 RetainSummary *Summ = ObjCMethodSummaries.find(ID, ClsName, S);
1380
1381 if (!Summ) {
1382 assert(ScratchArgs.isEmpty());
1383
1384 // "initXXX": pass-through for receiver.
1385 if (cocoa::deriveNamingConvention(S) == cocoa::InitRule)
1386 Summ = getInitMethodSummary(RetTy);
1387 else
1388 Summ = getCommonMethodSummary(MD, S, RetTy);
1389
1390 // Annotations override defaults.
1391 updateSummaryFromAnnotations(*Summ, MD);
1392
1393 // Memoize the summary.
1394 ObjCMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
1395 }
1396
1397 return Summ;
1398}
1399
1400RetainSummary*
1401RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
1402 const ObjCInterfaceDecl *ID,
1403 const ObjCMethodDecl *MD,
1404 QualType RetTy) {
1405
1406 assert(ClsName && "Class name must be specified.");
1407 RetainSummary *Summ = ObjCClassMethodSummaries.find(ID, ClsName, S);
1408
1409 if (!Summ) {
1410 Summ = getCommonMethodSummary(MD, S, RetTy);
1411 // Annotations override defaults.
1412 updateSummaryFromAnnotations(*Summ, MD);
1413 // Memoize the summary.
1414 ObjCClassMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
1415 }
1416
1417 return Summ;
1418}
1419
1420void RetainSummaryManager::InitializeClassMethodSummaries() {
1421 assert(ScratchArgs.isEmpty());
1422 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
1423
1424 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1425 // NSObject and its derivatives.
1426 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1427 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1428 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
1429
1430 // Create the [NSAssertionHandler currentHander] summary.
1431 addClassMethSummary("NSAssertionHandler", "currentHandler",
1432 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
1433
1434 // Create the [NSAutoreleasePool addObject:] summary.
1435 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
1436 addClassMethSummary("NSAutoreleasePool", "addObject",
1437 getPersistentSummary(RetEffect::MakeNoRet(),
1438 DoNothing, Autorelease));
1439
1440 // Create a summary for [NSCursor dragCopyCursor].
1441 addClassMethSummary("NSCursor", "dragCopyCursor",
1442 getPersistentSummary(RetEffect::MakeNoRet(), DoNothing,
1443 DoNothing));
1444
1445 // Create the summaries for [NSObject performSelector...]. We treat
1446 // these as 'stop tracking' for the arguments because they are often
1447 // used for delegates that can release the object. When we have better
1448 // inter-procedural analysis we can potentially do something better. This
1449 // workaround is to remove false positives.
1450 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1451 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1452 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1453 "afterDelay", NULL);
1454 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1455 "afterDelay", "inModes", NULL);
1456 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1457 "withObject", "waitUntilDone", NULL);
1458 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1459 "withObject", "waitUntilDone", "modes", NULL);
1460 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1461 "withObject", "waitUntilDone", NULL);
1462 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1463 "withObject", "waitUntilDone", "modes", NULL);
1464 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1465 "withObject", NULL);
1466
1467 // Specially handle NSData.
1468 RetainSummary *dataWithBytesNoCopySumm =
1469 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC), DoNothing,
1470 DoNothing);
1471 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1472 "dataWithBytesNoCopy", "length", NULL);
1473 addClsMethSummary("NSData", dataWithBytesNoCopySumm,
1474 "dataWithBytesNoCopy", "length", "freeWhenDone", NULL);
1475}
1476
1477void RetainSummaryManager::InitializeMethodSummaries() {
1478
1479 assert (ScratchArgs.isEmpty());
1480
1481 // Create the "init" selector. It just acts as a pass-through for the
1482 // receiver.
1483 RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
1484 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1485
1486 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1487 // claims the receiver and returns a retained object.
1488 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1489 InitSumm);
1490
1491 // The next methods are allocators.
1492 RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1493 RetainSummary *CFAllocSumm =
1494 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
1495
1496 // Create the "copy" selector.
1497 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), AllocSumm);
1498
1499 // Create the "mutableCopy" selector.
1500 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), AllocSumm);
1501
1502 // Create the "retain" selector.
1503 RetEffect E = RetEffect::MakeReceiverAlias();
1504 RetainSummary *Summ = getPersistentSummary(E, IncRefMsg);
1505 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
1506
1507 // Create the "release" selector.
1508 Summ = getPersistentSummary(E, DecRefMsg);
1509 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
1510
1511 // Create the "drain" selector.
1512 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
1513 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
1514
1515 // Create the -dealloc summary.
1516 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1517 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
1518
1519 // Create the "autorelease" selector.
1520 Summ = getPersistentSummary(E, Autorelease);
1521 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
1522
1523 // Specially handle NSAutoreleasePool.
1524 addInstMethSummary("NSAutoreleasePool", "init",
1525 getPersistentSummary(RetEffect::MakeReceiverAlias(),
1526 NewAutoreleasePool));
1527
1528 // For NSWindow, allocated objects are (initially) self-owned.
1529 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1530 // self-own themselves. However, they only do this once they are displayed.
1531 // Thus, we need to track an NSWindow's display status.
1532 // This is tracked in <rdar://problem/6062711>.
1533 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
1534 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1535 StopTracking,
1536 StopTracking);
1537
1538 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1539
1540#if 0
1541 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
1542 "styleMask", "backing", "defer", NULL);
1543
1544 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
1545 "styleMask", "backing", "defer", "screen", NULL);
1546#endif
1547
1548 // For NSPanel (which subclasses NSWindow), allocated objects are not
1549 // self-owned.
1550 // FIXME: For now we don't track NSPanels. object for the same reason
1551 // as for NSWindow objects.
1552 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1553
1554#if 0
1555 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
1556 "styleMask", "backing", "defer", NULL);
1557
1558 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
1559 "styleMask", "backing", "defer", "screen", NULL);
1560#endif
1561
1562 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1563 // exit a method.
1564 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
1565
1566 // Create NSAssertionHandler summaries.
1567 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1568 "lineNumber", "description", NULL);
1569
1570 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1571 "file", "lineNumber", "description", NULL);
1572
1573 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1574 addInstMethSummary("QCRenderer", AllocSumm,
1575 "createSnapshotImageOfType", NULL);
1576 addInstMethSummary("QCView", AllocSumm,
1577 "createSnapshotImageOfType", NULL);
1578
1579 // Create summaries for CIContext, 'createCGImage' and
1580 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1581 // automatically garbage collected.
1582 addInstMethSummary("CIContext", CFAllocSumm,
1583 "createCGImage", "fromRect", NULL);
1584 addInstMethSummary("CIContext", CFAllocSumm,
1585 "createCGImage", "fromRect", "format", "colorSpace", NULL);
1586 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
1587 "info", NULL);
1588}
1589
1590//===----------------------------------------------------------------------===//
1591// AutoreleaseBindings - State used to track objects in autorelease pools.
1592//===----------------------------------------------------------------------===//
1593
1594typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1595typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1596typedef llvm::ImmutableList<SymbolRef> ARStack;
1597
1598static int AutoRCIndex = 0;
1599static int AutoRBIndex = 0;
1600
1601namespace { class AutoreleasePoolContents {}; }
1602namespace { class AutoreleaseStack {}; }
1603
1604namespace clang {
1605template<> struct GRStateTrait<AutoreleaseStack>
1606 : public GRStatePartialTrait<ARStack> {
1607 static inline void* GDMIndex() { return &AutoRBIndex; }
1608};
1609
1610template<> struct GRStateTrait<AutoreleasePoolContents>
1611 : public GRStatePartialTrait<ARPoolContents> {
1612 static inline void* GDMIndex() { return &AutoRCIndex; }
1613};
1614} // end clang namespace
1615
1616static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1617 ARStack stack = state->get<AutoreleaseStack>();
1618 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1619}
1620
1621static const GRState * SendAutorelease(const GRState *state,
1622 ARCounts::Factory &F, SymbolRef sym) {
1623
1624 SymbolRef pool = GetCurrentAutoreleasePool(state);
1625 const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool);
1626 ARCounts newCnts(0);
1627
1628 if (cnts) {
1629 const unsigned *cnt = (*cnts).lookup(sym);
1630 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1631 }
1632 else
1633 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1634
1635 return state->set<AutoreleasePoolContents>(pool, newCnts);
1636}
1637
1638//===----------------------------------------------------------------------===//
1639// Transfer functions.
1640//===----------------------------------------------------------------------===//
1641
1642namespace {
1643
1644class CFRefCount : public GRTransferFuncs {
1645public:
1646 class BindingsPrinter : public GRState::Printer {
1647 public:
1648 virtual void Print(llvm::raw_ostream& Out, const GRState* state,
1649 const char* nl, const char* sep);
1650 };
1651
1652private:
1653 typedef llvm::DenseMap<const ExplodedNode*, const RetainSummary*>
1654 SummaryLogTy;
1655
1656 RetainSummaryManager Summaries;
1657 SummaryLogTy SummaryLog;
1658 const LangOptions& LOpts;
1659 ARCounts::Factory ARCountFactory;
1660
1661 BugType *useAfterRelease, *releaseNotOwned;
1662 BugType *deallocGC, *deallocNotOwned;
1663 BugType *leakWithinFunction, *leakAtReturn;
1664 BugType *overAutorelease;
1665 BugType *returnNotOwnedForOwned;
1666 BugReporter *BR;
1667
1668 const GRState * Update(const GRState * state, SymbolRef sym, RefVal V, ArgEffect E,
1669 RefVal::Kind& hasErr);
1670
1671 void ProcessNonLeakError(ExplodedNodeSet& Dst,
1672 GRStmtNodeBuilder& Builder,
1673 Expr* NodeExpr, Expr* ErrorExpr,
1674 ExplodedNode* Pred,
1675 const GRState* St,
1676 RefVal::Kind hasErr, SymbolRef Sym);
1677
1678 const GRState * HandleSymbolDeath(const GRState * state, SymbolRef sid, RefVal V,
1679 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1680
1681 ExplodedNode* ProcessLeaks(const GRState * state,
1682 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1683 GenericNodeBuilder &Builder,
1684 GRExprEngine &Eng,
1685 ExplodedNode *Pred = 0);
1686
1687public:
1688 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
1689 : Summaries(Ctx, gcenabled),
1690 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1691 deallocGC(0), deallocNotOwned(0),
1692 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0),
1693 returnNotOwnedForOwned(0), BR(0) {}
1694
1695 virtual ~CFRefCount() {}
1696
1697 void RegisterChecks(GRExprEngine &Eng);
1698
1699 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1700 Printers.push_back(new BindingsPrinter());
1701 }
1702
1703 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
1704 const LangOptions& getLangOptions() const { return LOpts; }
1705
1706 const RetainSummary *getSummaryOfNode(const ExplodedNode *N) const {
1707 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1708 return I == SummaryLog.end() ? 0 : I->second;
1709 }
1710
1711 // Calls.
1712
1713 void EvalSummary(ExplodedNodeSet& Dst,
1714 GRExprEngine& Eng,
1715 GRStmtNodeBuilder& Builder,
1716 Expr* Ex,
1717 Expr* Receiver,
1718 const RetainSummary& Summ,
1719 const MemRegion *Callee,
1720 ExprIterator arg_beg, ExprIterator arg_end,
1721 ExplodedNode* Pred, const GRState *state);
1722
1723 virtual void EvalCall(ExplodedNodeSet& Dst,
1724 GRExprEngine& Eng,
1725 GRStmtNodeBuilder& Builder,
1726 CallExpr* CE, SVal L,
1727 ExplodedNode* Pred);
1728
1729
1730 virtual void EvalObjCMessageExpr(ExplodedNodeSet& Dst,
1731 GRExprEngine& Engine,
1732 GRStmtNodeBuilder& Builder,
1733 ObjCMessageExpr* ME,
1734 ExplodedNode* Pred,
1735 const GRState *state);
1736
1737 bool EvalObjCMessageExprAux(ExplodedNodeSet& Dst,
1738 GRExprEngine& Engine,
1739 GRStmtNodeBuilder& Builder,
1740 ObjCMessageExpr* ME,
1741 ExplodedNode* Pred);
1742
1743 // Stores.
1744 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1745
1746 // End-of-path.
1747
1748 virtual void EvalEndPath(GRExprEngine& Engine,
1749 GREndPathNodeBuilder& Builder);
1750
1751 virtual void EvalDeadSymbols(ExplodedNodeSet& Dst,
1752 GRExprEngine& Engine,
1753 GRStmtNodeBuilder& Builder,
1754 ExplodedNode* Pred,
1755 Stmt* S, const GRState* state,
1756 SymbolReaper& SymReaper);
1757
1758 std::pair<ExplodedNode*, const GRState *>
1759 HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd,
1760 ExplodedNode* Pred, GRExprEngine &Eng,
1761 SymbolRef Sym, RefVal V, bool &stop);
1762 // Return statements.
1763
1764 virtual void EvalReturn(ExplodedNodeSet& Dst,
1765 GRExprEngine& Engine,
1766 GRStmtNodeBuilder& Builder,
1767 ReturnStmt* S,
1768 ExplodedNode* Pred);
1769
1770 // Assumptions.
1771
1772 virtual const GRState *EvalAssume(const GRState* state, SVal condition,
1773 bool assumption);
1774};
1775
1776} // end anonymous namespace
1777
1778static void PrintPool(llvm::raw_ostream &Out, SymbolRef Sym,
1779 const GRState *state) {
1780 Out << ' ';
1781 if (Sym)
1782 Out << Sym->getSymbolID();
1783 else
1784 Out << "<pool>";
1785 Out << ":{";
1786
1787 // Get the contents of the pool.
1788 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1789 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1790 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1791
1792 Out << '}';
1793}
1794
1795void CFRefCount::BindingsPrinter::Print(llvm::raw_ostream& Out,
1796 const GRState* state,
1797 const char* nl, const char* sep) {
1798
1799 RefBindings B = state->get<RefBindings>();
1800
1801 if (!B.isEmpty())
1802 Out << sep << nl;
1803
1804 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1805 Out << (*I).first << " : ";
1806 (*I).second.print(Out);
1807 Out << nl;
1808 }
1809
1810 // Print the autorelease stack.
1811 Out << sep << nl << "AR pool stack:";
1812 ARStack stack = state->get<AutoreleaseStack>();
1813
1814 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1815 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1816 PrintPool(Out, *I, state);
1817
1818 Out << nl;
1819}
1820
1821//===----------------------------------------------------------------------===//
1822// Error reporting.
1823//===----------------------------------------------------------------------===//
1824
1825namespace {
1826
1827 //===-------------===//
1828 // Bug Descriptions. //
1829 //===-------------===//
1830
1831 class CFRefBug : public BugType {
1832 protected:
1833 CFRefCount& TF;
1834
1835 CFRefBug(CFRefCount* tf, llvm::StringRef name)
1836 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1837 public:
1838
1839 CFRefCount& getTF() { return TF; }
1840 const CFRefCount& getTF() const { return TF; }
1841
1842 // FIXME: Eventually remove.
1843 virtual const char* getDescription() const = 0;
1844
1845 virtual bool isLeak() const { return false; }
1846 };
1847
1848 class UseAfterRelease : public CFRefBug {
1849 public:
1850 UseAfterRelease(CFRefCount* tf)
1851 : CFRefBug(tf, "Use-after-release") {}
1852
1853 const char* getDescription() const {
1854 return "Reference-counted object is used after it is released";
1855 }
1856 };
1857
1858 class BadRelease : public CFRefBug {
1859 public:
1860 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1861
1862 const char* getDescription() const {
1863 return "Incorrect decrement of the reference count of an object that is "
1864 "not owned at this point by the caller";
1865 }
1866 };
1867
1868 class DeallocGC : public CFRefBug {
1869 public:
1870 DeallocGC(CFRefCount *tf)
1871 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
1872
1873 const char *getDescription() const {
1874 return "-dealloc called while using garbage collection";
1875 }
1876 };
1877
1878 class DeallocNotOwned : public CFRefBug {
1879 public:
1880 DeallocNotOwned(CFRefCount *tf)
1881 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
1882
1883 const char *getDescription() const {
1884 return "-dealloc sent to object that may be referenced elsewhere";
1885 }
1886 };
1887
1888 class OverAutorelease : public CFRefBug {
1889 public:
1890 OverAutorelease(CFRefCount *tf) :
1891 CFRefBug(tf, "Object sent -autorelease too many times") {}
1892
1893 const char *getDescription() const {
1894 return "Object sent -autorelease too many times";
1895 }
1896 };
1897
1898 class ReturnedNotOwnedForOwned : public CFRefBug {
1899 public:
1900 ReturnedNotOwnedForOwned(CFRefCount *tf) :
1901 CFRefBug(tf, "Method should return an owned object") {}
1902
1903 const char *getDescription() const {
1904 return "Object with +0 retain counts returned to caller where a +1 "
1905 "(owning) retain count is expected";
1906 }
1907 };
1908
1909 class Leak : public CFRefBug {
1910 const bool isReturn;
1911 protected:
1912 Leak(CFRefCount* tf, llvm::StringRef name, bool isRet)
1913 : CFRefBug(tf, name), isReturn(isRet) {}
1914 public:
1915
1916 const char* getDescription() const { return ""; }
1917
1918 bool isLeak() const { return true; }
1919 };
1920
1921 class LeakAtReturn : public Leak {
1922 public:
1923 LeakAtReturn(CFRefCount* tf, llvm::StringRef name)
1924 : Leak(tf, name, true) {}
1925 };
1926
1927 class LeakWithinFunction : public Leak {
1928 public:
1929 LeakWithinFunction(CFRefCount* tf, llvm::StringRef name)
1930 : Leak(tf, name, false) {}
1931 };
1932
1933 //===---------===//
1934 // Bug Reports. //
1935 //===---------===//
1936
1937 class CFRefReport : public RangedBugReport {
1938 protected:
1939 SymbolRef Sym;
1940 const CFRefCount &TF;
1941 public:
1942 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1943 ExplodedNode *n, SymbolRef sym)
1944 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1945
1946 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1947 ExplodedNode *n, SymbolRef sym, llvm::StringRef endText)
1948 : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {}
1949
1950 virtual ~CFRefReport() {}
1951
1952 CFRefBug& getBugType() {
1953 return (CFRefBug&) RangedBugReport::getBugType();
1954 }
1955 const CFRefBug& getBugType() const {
1956 return (const CFRefBug&) RangedBugReport::getBugType();
1957 }
1958
1959 virtual void getRanges(const SourceRange*& beg, const SourceRange*& end) {
1960 if (!getBugType().isLeak())
1961 RangedBugReport::getRanges(beg, end);
1962 else
1963 beg = end = 0;
1964 }
1965
1966 SymbolRef getSymbol() const { return Sym; }
1967
1968 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
1969 const ExplodedNode* N);
1970
1971 std::pair<const char**,const char**> getExtraDescriptiveText();
1972
1973 PathDiagnosticPiece* VisitNode(const ExplodedNode* N,
1974 const ExplodedNode* PrevN,
1975 BugReporterContext& BRC);
1976 };
1977
1978 class CFRefLeakReport : public CFRefReport {
1979 SourceLocation AllocSite;
1980 const MemRegion* AllocBinding;
1981 public:
1982 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
1983 ExplodedNode *n, SymbolRef sym,
1984 GRExprEngine& Eng);
1985
1986 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
1987 const ExplodedNode* N);
1988
1989 SourceLocation getLocation() const { return AllocSite; }
1990 };
1991} // end anonymous namespace
1992
1993
1994
1995static const char* Msgs[] = {
1996 // GC only
1997 "Code is compiled to only use garbage collection",
1998 // No GC.
1999 "Code is compiled to use reference counts",
2000 // Hybrid, with GC.
2001 "Code is compiled to use either garbage collection (GC) or reference counts"
2002 " (non-GC). The bug occurs with GC enabled",
2003 // Hybrid, without GC
2004 "Code is compiled to use either garbage collection (GC) or reference counts"
2005 " (non-GC). The bug occurs in non-GC mode"
2006};
2007
2008std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2009 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2010
2011 switch (TF.getLangOptions().getGCMode()) {
2012 default:
2013 assert(false);
2014
2015 case LangOptions::GCOnly:
2016 assert (TF.isGCEnabled());
2017 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2018
2019 case LangOptions::NonGC:
2020 assert (!TF.isGCEnabled());
2021 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2022
2023 case LangOptions::HybridGC:
2024 if (TF.isGCEnabled())
2025 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2026 else
2027 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2028 }
2029}
2030
2031static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2032 ArgEffect X) {
2033 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2034 I!=E; ++I)
2035 if (*I == X) return true;
2036
2037 return false;
2038}
2039
2040PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode* N,
2041 const ExplodedNode* PrevN,
2042 BugReporterContext& BRC) {
2043
2044 if (!isa<PostStmt>(N->getLocation()))
2045 return NULL;
2046
2047 // Check if the type state has changed.
2048 const GRState *PrevSt = PrevN->getState();
2049 const GRState *CurrSt = N->getState();
2050
2051 const RefVal* CurrT = CurrSt->get<RefBindings>(Sym);
2052 if (!CurrT) return NULL;
2053
2054 const RefVal &CurrV = *CurrT;
2055 const RefVal *PrevT = PrevSt->get<RefBindings>(Sym);
2056
2057 // Create a string buffer to constain all the useful things we want
2058 // to tell the user.
2059 std::string sbuf;
2060 llvm::raw_string_ostream os(sbuf);
2061
2062 // This is the allocation site since the previous node had no bindings
2063 // for this symbol.
2064 if (!PrevT) {
2065 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2066
2067 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
2068 // Get the name of the callee (if it is available).
2069 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee());
2070 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2071 os << "Call to function '" << FD->getNameAsString() <<'\'';
2072 else
2073 os << "function call";
2074 }
2075 else {
2076 assert (isa<ObjCMessageExpr>(S));
2077 os << "Method";
2078 }
2079
2080 if (CurrV.getObjKind() == RetEffect::CF) {
2081 os << " returns a Core Foundation object with a ";
2082 }
2083 else {
2084 assert (CurrV.getObjKind() == RetEffect::ObjC);
2085 os << " returns an Objective-C object with a ";
2086 }
2087
2088 if (CurrV.isOwned()) {
2089 os << "+1 retain count (owning reference).";
2090
2091 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2092 assert(CurrV.getObjKind() == RetEffect::CF);
2093 os << " "
2094 "Core Foundation objects are not automatically garbage collected.";
2095 }
2096 }
2097 else {
2098 assert (CurrV.isNotOwned());
2099 os << "+0 retain count (non-owning reference).";
2100 }
2101
2102 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
2103 return new PathDiagnosticEventPiece(Pos, os.str());
2104 }
2105
2106 // Gather up the effects that were performed on the object at this
2107 // program point
2108 llvm::SmallVector<ArgEffect, 2> AEffects;
2109
2110 if (const RetainSummary *Summ =
2111 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
2112 // We only have summaries attached to nodes after evaluating CallExpr and
2113 // ObjCMessageExprs.
2114 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2115
2116 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
2117 // Iterate through the parameter expressions and see if the symbol
2118 // was ever passed as an argument.
2119 unsigned i = 0;
2120
2121 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2122 AI!=AE; ++AI, ++i) {
2123
2124 // Retrieve the value of the argument. Is it the symbol
2125 // we are interested in?
2126 if (CurrSt->getSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2127 continue;
2128
2129 // We have an argument. Get the effect!
2130 AEffects.push_back(Summ->getArg(i));
2131 }
2132 }
2133 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2134 if (const Expr *receiver = ME->getReceiver())
2135 if (CurrSt->getSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2136 // The symbol we are tracking is the receiver.
2137 AEffects.push_back(Summ->getReceiverEffect());
2138 }
2139 }
2140 }
2141
2142 do {
2143 // Get the previous type state.
2144 RefVal PrevV = *PrevT;
2145
2146 // Specially handle -dealloc.
2147 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2148 // Determine if the object's reference count was pushed to zero.
2149 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2150 // We may not have transitioned to 'release' if we hit an error.
2151 // This case is handled elsewhere.
2152 if (CurrV.getKind() == RefVal::Released) {
2153 assert(CurrV.getCombinedCounts() == 0);
2154 os << "Object released by directly sending the '-dealloc' message";
2155 break;
2156 }
2157 }
2158
2159 // Specially handle CFMakeCollectable and friends.
2160 if (contains(AEffects, MakeCollectable)) {
2161 // Get the name of the function.
2162 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2163 SVal X = CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2164 const FunctionDecl* FD = X.getAsFunctionDecl();
2165 const std::string& FName = FD->getNameAsString();
2166
2167 if (TF.isGCEnabled()) {
2168 // Determine if the object's reference count was pushed to zero.
2169 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2170
2171 os << "In GC mode a call to '" << FName
2172 << "' decrements an object's retain count and registers the "
2173 "object with the garbage collector. ";
2174
2175 if (CurrV.getKind() == RefVal::Released) {
2176 assert(CurrV.getCount() == 0);
2177 os << "Since it now has a 0 retain count the object can be "
2178 "automatically collected by the garbage collector.";
2179 }
2180 else
2181 os << "An object must have a 0 retain count to be garbage collected. "
2182 "After this call its retain count is +" << CurrV.getCount()
2183 << '.';
2184 }
2185 else
2186 os << "When GC is not enabled a call to '" << FName
2187 << "' has no effect on its argument.";
2188
2189 // Nothing more to say.
2190 break;
2191 }
2192
2193 // Determine if the typestate has changed.
2194 if (!(PrevV == CurrV))
2195 switch (CurrV.getKind()) {
2196 case RefVal::Owned:
2197 case RefVal::NotOwned:
2198
2199 if (PrevV.getCount() == CurrV.getCount()) {
2200 // Did an autorelease message get sent?
2201 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2202 return 0;
2203
2204 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
2205 os << "Object sent -autorelease message";
2206 break;
2207 }
2208
2209 if (PrevV.getCount() > CurrV.getCount())
2210 os << "Reference count decremented.";
2211 else
2212 os << "Reference count incremented.";
2213
2214 if (unsigned Count = CurrV.getCount())
2215 os << " The object now has a +" << Count << " retain count.";
2216
2217 if (PrevV.getKind() == RefVal::Released) {
2218 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2219 os << " The object is not eligible for garbage collection until the "
2220 "retain count reaches 0 again.";
2221 }
2222
2223 break;
2224
2225 case RefVal::Released:
2226 os << "Object released.";
2227 break;
2228
2229 case RefVal::ReturnedOwned:
2230 os << "Object returned to caller as an owning reference (single retain "
2231 "count transferred to caller).";
2232 break;
2233
2234 case RefVal::ReturnedNotOwned:
2235 os << "Object returned to caller with a +0 (non-owning) retain count.";
2236 break;
2237
2238 default:
2239 return NULL;
2240 }
2241
2242 // Emit any remaining diagnostics for the argument effects (if any).
2243 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2244 E=AEffects.end(); I != E; ++I) {
2245
2246 // A bunch of things have alternate behavior under GC.
2247 if (TF.isGCEnabled())
2248 switch (*I) {
2249 default: break;
2250 case Autorelease:
2251 os << "In GC mode an 'autorelease' has no effect.";
2252 continue;
2253 case IncRefMsg:
2254 os << "In GC mode the 'retain' message has no effect.";
2255 continue;
2256 case DecRefMsg:
2257 os << "In GC mode the 'release' message has no effect.";
2258 continue;
2259 }
2260 }
2261 } while (0);
2262
2263 if (os.str().empty())
2264 return 0; // We have nothing to say!
2265
2266 const Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2267 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
2268 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2269
2270 // Add the range by scanning the children of the statement for any bindings
2271 // to Sym.
2272 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
2273 I!=E; ++I)
2274 if (const Expr* Exp = dyn_cast_or_null<Expr>(*I))
2275 if (CurrSt->getSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2276 P->addRange(Exp->getSourceRange());
2277 break;
2278 }
2279
2280 return P;
2281}
2282
2283namespace {
2284 class FindUniqueBinding :
2285 public StoreManager::BindingsHandler {
2286 SymbolRef Sym;
2287 const MemRegion* Binding;
2288 bool First;
2289
2290 public:
2291 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2292
2293 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2294 SVal val) {
2295
2296 SymbolRef SymV = val.getAsSymbol();
2297 if (!SymV || SymV != Sym)
2298 return true;
2299
2300 if (Binding) {
2301 First = false;
2302 return false;
2303 }
2304 else
2305 Binding = R;
2306
2307 return true;
2308 }
2309
2310 operator bool() { return First && Binding; }
2311 const MemRegion* getRegion() { return Binding; }
2312 };
2313}
2314
2315static std::pair<const ExplodedNode*,const MemRegion*>
2316GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode* N,
2317 SymbolRef Sym) {
2318
2319 // Find both first node that referred to the tracked symbol and the
2320 // memory location that value was store to.
2321 const ExplodedNode* Last = N;
2322 const MemRegion* FirstBinding = 0;
2323
2324 while (N) {
2325 const GRState* St = N->getState();
2326 RefBindings B = St->get<RefBindings>();
2327
2328 if (!B.lookup(Sym))
2329 break;
2330
2331 FindUniqueBinding FB(Sym);
2332 StateMgr.iterBindings(St, FB);
2333 if (FB) FirstBinding = FB.getRegion();
2334
2335 Last = N;
2336 N = N->pred_empty() ? NULL : *(N->pred_begin());
2337 }
2338
2339 return std::make_pair(Last, FirstBinding);
2340}
2341
2342PathDiagnosticPiece*
2343CFRefReport::getEndPath(BugReporterContext& BRC,
2344 const ExplodedNode* EndN) {
2345 // Tell the BugReporterContext to report cases when the tracked symbol is
2346 // assigned to different variables, etc.
2347 BRC.addNotableSymbol(Sym);
2348 return RangedBugReport::getEndPath(BRC, EndN);
2349}
2350
2351PathDiagnosticPiece*
2352CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2353 const ExplodedNode* EndN){
2354
2355 // Tell the BugReporterContext to report cases when the tracked symbol is
2356 // assigned to different variables, etc.
2357 BRC.addNotableSymbol(Sym);
2358
2359 // We are reporting a leak. Walk up the graph to get to the first node where
2360 // the symbol appeared, and also get the first VarDecl that tracked object
2361 // is stored to.
2362 const ExplodedNode* AllocNode = 0;
2363 const MemRegion* FirstBinding = 0;
2364
2365 llvm::tie(AllocNode, FirstBinding) =
2366 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
2367
2368 // Get the allocate site.
2369 assert(AllocNode);
2370 const Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2371
2372 SourceManager& SMgr = BRC.getSourceManager();
2373 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2374
2375 // Compute an actual location for the leak. Sometimes a leak doesn't
2376 // occur at an actual statement (e.g., transition between blocks; end
2377 // of function) so we need to walk the graph and compute a real location.
2378 const ExplodedNode* LeakN = EndN;
2379 PathDiagnosticLocation L;
2380
2381 while (LeakN) {
2382 ProgramPoint P = LeakN->getLocation();
2383
2384 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2385 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2386 break;
2387 }
2388 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2389 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2390 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2391 break;
2392 }
2393 }
2394
2395 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2396 }
2397
2398 if (!L.isValid()) {
2399 const Decl &D = EndN->getCodeDecl();
2400 L = PathDiagnosticLocation(D.getBodyRBrace(), SMgr);
2401 }
2402
2403 std::string sbuf;
2404 llvm::raw_string_ostream os(sbuf);
2405
2406 os << "Object allocated on line " << AllocLine;
2407
2408 if (FirstBinding)
2409 os << " and stored into '" << FirstBinding->getString() << '\'';
2410
2411 // Get the retain count.
2412 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2413
2414 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2415 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2416 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2417 // to the caller for NS objects.
2418 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
2419 os << " is returned from a method whose name ('"
2420 << MD.getSelector().getAsString()
2421 << "') does not contain 'copy' or otherwise starts with"
2422 " 'new' or 'alloc'. This violates the naming convention rules given"
2423 " in the Memory Management Guide for Cocoa (object leaked)";
2424 }
2425 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2426 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
2427 os << " and returned from method '" << MD.getSelector().getAsString()
2428 << "' is potentially leaked when using garbage collection. Callers "
2429 "of this method do not expect a returned object with a +1 retain "
2430 "count since they expect the object to be managed by the garbage "
2431 "collector";
2432 }
2433 else
2434 os << " is no longer referenced after this point and has a retain count of"
2435 " +" << RV->getCount() << " (object leaked)";
2436
2437 return new PathDiagnosticEventPiece(L, os.str());
2438}
2439
2440CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2441 ExplodedNode *n,
2442 SymbolRef sym, GRExprEngine& Eng)
2443: CFRefReport(D, tf, n, sym) {
2444
2445 // Most bug reports are cached at the location where they occured.
2446 // With leaks, we want to unique them by the location where they were
2447 // allocated, and only report a single path. To do this, we need to find
2448 // the allocation site of a piece of tracked memory, which we do via a
2449 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2450 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2451 // that all ancestor nodes that represent the allocation site have the
2452 // same SourceLocation.
2453 const ExplodedNode* AllocNode = 0;
2454
2455 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
2456 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
2457
2458 // Get the SourceLocation for the allocation site.
2459 ProgramPoint P = AllocNode->getLocation();
2460 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2461
2462 // Fill in the description of the bug.
2463 Description.clear();
2464 llvm::raw_string_ostream os(Description);
2465 SourceManager& SMgr = Eng.getContext().getSourceManager();
2466 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
2467 os << "Potential leak ";
2468 if (tf.isGCEnabled()) {
2469 os << "(when using garbage collection) ";
2470 }
2471 os << "of an object allocated on line " << AllocLine;
2472
2473 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2474 if (AllocBinding)
2475 os << " and stored into '" << AllocBinding->getString() << '\'';
2476}
2477
2478//===----------------------------------------------------------------------===//
2479// Main checker logic.
2480//===----------------------------------------------------------------------===//
2481
2482/// GetReturnType - Used to get the return type of a message expression or
2483/// function call with the intention of affixing that type to a tracked symbol.
2484/// While the the return type can be queried directly from RetEx, when
2485/// invoking class methods we augment to the return type to be that of
2486/// a pointer to the class (as opposed it just being id).
2487static QualType GetReturnType(const Expr* RetE, ASTContext& Ctx) {
2488 QualType RetTy = RetE->getType();
2489 // If RetE is not a message expression just return its type.
2490 // If RetE is a message expression, return its types if it is something
2491 /// more specific than id.
2492 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2493 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2494 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2495 PT->isObjCClassType()) {
2496 // At this point we know the return type of the message expression is
2497 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2498 // is a call to a class method whose type we can resolve. In such
2499 // cases, promote the return type to XXX* (where XXX is the class).
2500 const ObjCInterfaceDecl *D = ME->getClassInfo().first;
2501 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2502 }
2503
2504 return RetTy;
2505}
2506
2507void CFRefCount::EvalSummary(ExplodedNodeSet& Dst,
2508 GRExprEngine& Eng,
2509 GRStmtNodeBuilder& Builder,
2510 Expr* Ex,
2511 Expr* Receiver,
2512 const RetainSummary& Summ,
2513 const MemRegion *Callee,
2514 ExprIterator arg_beg, ExprIterator arg_end,
2515 ExplodedNode* Pred, const GRState *state) {
2516
2517 // Evaluate the effect of the arguments.
2518 RefVal::Kind hasErr = (RefVal::Kind) 0;
2519 unsigned idx = 0;
2520 Expr* ErrorExpr = NULL;
2521 SymbolRef ErrorSym = 0;
2522
2523 llvm::SmallVector<const MemRegion*, 10> RegionsToInvalidate;
2524
2525 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
2526 SVal V = state->getSValAsScalarOrLoc(*I);
2527 SymbolRef Sym = V.getAsLocSymbol();
2528
2529 if (Sym)
2530 if (RefBindings::data_type* T = state->get<RefBindings>(Sym)) {
2531 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
2532 if (hasErr) {
2533 ErrorExpr = *I;
2534 ErrorSym = Sym;
2535 break;
2536 }
2537 continue;
2538 }
2539
2540 tryAgain:
2541 if (isa<Loc>(V)) {
2542 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
2543 if (Summ.getArg(idx) == DoNothingByRef)
2544 continue;
2545
2546 // Invalidate the value of the variable passed by reference.
2547 const MemRegion *R = MR->getRegion();
2548
2549 // Are we dealing with an ElementRegion? If the element type is
2550 // a basic integer type (e.g., char, int) and the underying region
2551 // is a variable region then strip off the ElementRegion.
2552 // FIXME: We really need to think about this for the general case
2553 // as sometimes we are reasoning about arrays and other times
2554 // about (char*), etc., is just a form of passing raw bytes.
2555 // e.g., void *p = alloca(); foo((char*)p);
2556 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2557 // Checking for 'integral type' is probably too promiscuous, but
2558 // we'll leave it in for now until we have a systematic way of
2559 // handling all of these cases. Eventually we need to come up
2560 // with an interface to StoreManager so that this logic can be
2561 // approriately delegated to the respective StoreManagers while
2562 // still allowing us to do checker-specific logic (e.g.,
2563 // invalidating reference counts), probably via callbacks.
2564 if (ER->getElementType()->isIntegralType()) {
2565 const MemRegion *superReg = ER->getSuperRegion();
2566 if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
2567 isa<ObjCIvarRegion>(superReg))
2568 R = cast<TypedRegion>(superReg);
2569 }
2570 // FIXME: What about layers of ElementRegions?
2571 }
2572
2573 // Mark this region for invalidation. We batch invalidate regions
2574 // below for efficiency.
2575 RegionsToInvalidate.push_back(R);
2576 continue;
2577 }
2578 else {
2579 // Nuke all other arguments passed by reference.
2580 // FIXME: is this necessary or correct? This handles the non-Region
2581 // cases. Is it ever valid to store to these?
2582 state = state->unbindLoc(cast<Loc>(V));
2583 }
2584 }
2585 else if (isa<nonloc::LocAsInteger>(V)) {
2586 // If we are passing a location wrapped as an integer, unwrap it and
2587 // invalidate the values referred by the location.
2588 V = cast<nonloc::LocAsInteger>(V).getLoc();
2589 goto tryAgain;
2590 }
2591 }
2592
2593 // Block calls result in all captured values passed-via-reference to be
2594 // invalidated.
2595 if (const BlockDataRegion *BR = dyn_cast_or_null<BlockDataRegion>(Callee)) {
2596 RegionsToInvalidate.push_back(BR);
2597 }
2598
2599 // Invalidate regions we designed for invalidation use the batch invalidation
2600 // API.
2601 if (!RegionsToInvalidate.empty()) {
2602 // FIXME: We can have collisions on the conjured symbol if the
2603 // expression *I also creates conjured symbols. We probably want
2604 // to identify conjured symbols by an expression pair: the enclosing
2605 // expression (the context) and the expression itself. This should
2606 // disambiguate conjured symbols.
2607 unsigned Count = Builder.getCurrentBlockCount();
2608 StoreManager& StoreMgr = Eng.getStateManager().getStoreManager();
2609
2610
2611 StoreManager::InvalidatedSymbols IS;
2612 Store store = state->getStore();
2613 store = StoreMgr.InvalidateRegions(store, RegionsToInvalidate.data(),
2614 RegionsToInvalidate.data() +
2615 RegionsToInvalidate.size(),
2616 Ex, Count, &IS);
2617 state = state->makeWithStore(store);
2618 for (StoreManager::InvalidatedSymbols::iterator I = IS.begin(),
2619 E = IS.end(); I!=E; ++I) {
2620 // Remove any existing reference-count binding.
2621 state = state->remove<RefBindings>(*I);
2622 }
2623 }
2624
2625 // Evaluate the effect on the message receiver.
2626 if (!ErrorExpr && Receiver) {
2627 SymbolRef Sym = state->getSValAsScalarOrLoc(Receiver).getAsLocSymbol();
2628 if (Sym) {
2629 if (const RefVal* T = state->get<RefBindings>(Sym)) {
2630 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
2631 if (hasErr) {
2632 ErrorExpr = Receiver;
2633 ErrorSym = Sym;
2634 }
2635 }
2636 }
2637 }
2638
2639 // Process any errors.
2640 if (hasErr) {
2641 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
2642 hasErr, ErrorSym);
2643 return;
2644 }
2645
2646 // Consult the summary for the return value.
2647 RetEffect RE = Summ.getRetEffect();
2648
2649 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2650 assert(Receiver);
2651 SVal V = state->getSValAsScalarOrLoc(Receiver);
2652 bool found = false;
2653 if (SymbolRef Sym = V.getAsLocSymbol())
2654 if (state->get<RefBindings>(Sym)) {
2655 found = true;
2656 RE = Summaries.getObjAllocRetEffect();
2657 }
2658
2659 if (!found)
2660 RE = RetEffect::MakeNoRet();
2661 }
2662
2663 switch (RE.getKind()) {
2664 default:
2665 assert (false && "Unhandled RetEffect."); break;
2666
2667 case RetEffect::NoRet: {
2668 // Make up a symbol for the return value (not reference counted).
2669 // FIXME: Most of this logic is not specific to the retain/release
2670 // checker.
2671
2672 // FIXME: We eventually should handle structs and other compound types
2673 // that are returned by value.
2674
2675 QualType T = Ex->getType();
2676
2677 // For CallExpr, use the result type to know if it returns a reference.
2678 if (const CallExpr *CE = dyn_cast<CallExpr>(Ex)) {
2679 const Expr *Callee = CE->getCallee();
2680 if (const FunctionDecl *FD = state->getSVal(Callee).getAsFunctionDecl())
2681 T = FD->getResultType();
2682 }
2683 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
2684 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
2685 T = MD->getResultType();
2686 }
2687
2688 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
2689 unsigned Count = Builder.getCurrentBlockCount();
2690 ValueManager &ValMgr = Eng.getValueManager();
2691 SVal X = ValMgr.getConjuredSymbolVal(NULL, Ex, T, Count);
2692 state = state->BindExpr(Ex, X, false);
2693 }
2694
2695 break;
2696 }
2697
2698 case RetEffect::Alias: {
2699 unsigned idx = RE.getIndex();
2700 assert (arg_end >= arg_beg);
2701 assert (idx < (unsigned) (arg_end - arg_beg));
2702 SVal V = state->getSValAsScalarOrLoc(*(arg_beg+idx));
2703 state = state->BindExpr(Ex, V, false);
2704 break;
2705 }
2706
2707 case RetEffect::ReceiverAlias: {
2708 assert (Receiver);
2709 SVal V = state->getSValAsScalarOrLoc(Receiver);
2710 state = state->BindExpr(Ex, V, false);
2711 break;
2712 }
2713
2714 case RetEffect::OwnedAllocatedSymbol:
2715 case RetEffect::OwnedSymbol: {
2716 unsigned Count = Builder.getCurrentBlockCount();
2717 ValueManager &ValMgr = Eng.getValueManager();
2718 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2719 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2720 state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2721 RetT));
2722 state = state->BindExpr(Ex, ValMgr.makeLoc(Sym), false);
2723
2724 // FIXME: Add a flag to the checker where allocations are assumed to
2725 // *not fail.
2726#if 0
2727 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2728 bool isFeasible;
2729 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2730 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2731 }
2732#endif
2733
2734 break;
2735 }
2736
2737 case RetEffect::GCNotOwnedSymbol:
2738 case RetEffect::NotOwnedSymbol: {
2739 unsigned Count = Builder.getCurrentBlockCount();
2740 ValueManager &ValMgr = Eng.getValueManager();
2741 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2742 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2743 state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2744 RetT));
2745 state = state->BindExpr(Ex, ValMgr.makeLoc(Sym), false);
2746 break;
2747 }
2748 }
2749
2750 // Generate a sink node if we are at the end of a path.
2751 ExplodedNode *NewNode =
2752 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2753 : Builder.MakeNode(Dst, Ex, Pred, state);
2754
2755 // Annotate the edge with summary we used.
2756 if (NewNode) SummaryLog[NewNode] = &Summ;
2757}
2758
2759
2760void CFRefCount::EvalCall(ExplodedNodeSet& Dst,
2761 GRExprEngine& Eng,
2762 GRStmtNodeBuilder& Builder,
2763 CallExpr* CE, SVal L,
2764 ExplodedNode* Pred) {
2765
2766 RetainSummary *Summ = 0;
2767
2768 // FIXME: Better support for blocks. For now we stop tracking anything
2769 // that is passed to blocks.
2770 // FIXME: Need to handle variables that are "captured" by the block.
2771 if (dyn_cast_or_null<BlockDataRegion>(L.getAsRegion())) {
2772 Summ = Summaries.getPersistentStopSummary();
2773 }
2774 else {
2775 const FunctionDecl* FD = L.getAsFunctionDecl();
2776 Summ = !FD ? Summaries.getDefaultSummary() :
2777 Summaries.getSummary(const_cast<FunctionDecl*>(FD));
2778 }
2779
2780 assert(Summ);
2781 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ, L.getAsRegion(),
2782 CE->arg_begin(), CE->arg_end(), Pred, Builder.GetState(Pred));
2783}
2784
2785void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet& Dst,
2786 GRExprEngine& Eng,
2787 GRStmtNodeBuilder& Builder,
2788 ObjCMessageExpr* ME,
2789 ExplodedNode* Pred,
2790 const GRState *state) {
2791 RetainSummary *Summ =
2792 ME->getReceiver()
2793 ? Summaries.getInstanceMethodSummary(ME, state,Pred->getLocationContext())
2794 : Summaries.getClassMethodSummary(ME);
2795
2796 assert(Summ && "RetainSummary is null");
2797 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ, NULL,
2798 ME->arg_begin(), ME->arg_end(), Pred, state);
2799}
2800
2801namespace {
2802class StopTrackingCallback : public SymbolVisitor {
2803 const GRState *state;
2804public:
2805 StopTrackingCallback(const GRState *st) : state(st) {}
2806 const GRState *getState() const { return state; }
2807
2808 bool VisitSymbol(SymbolRef sym) {
2809 state = state->remove<RefBindings>(sym);
2810 return true;
2811 }
2812};
2813} // end anonymous namespace
2814
2815
2816void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
2817 // Are we storing to something that causes the value to "escape"?
2818 bool escapes = false;
2819
2820 // A value escapes in three possible cases (this may change):
2821 //
2822 // (1) we are binding to something that is not a memory region.
2823 // (2) we are binding to a memregion that does not have stack storage
2824 // (3) we are binding to a memregion with stack storage that the store
2825 // does not understand.
2826 const GRState *state = B.getState();
2827
2828 if (!isa<loc::MemRegionVal>(location))
2829 escapes = true;
2830 else {
2831 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2832 escapes = !R->hasStackStorage();
2833
2834 if (!escapes) {
2835 // To test (3), generate a new state with the binding removed. If it is
2836 // the same state, then it escapes (since the store cannot represent
2837 // the binding).
2838 escapes = (state == (state->bindLoc(cast<Loc>(location), UnknownVal())));
2839 }
2840 }
2841
2842 // If our store can represent the binding and we aren't storing to something
2843 // that doesn't have local storage then just return and have the simulation
2844 // state continue as is.
2845 if (!escapes)
2846 return;
2847
2848 // Otherwise, find all symbols referenced by 'val' that we are tracking
2849 // and stop tracking them.
2850 B.MakeNode(state->scanReachableSymbols<StopTrackingCallback>(val).getState());
2851}
2852
2853 // Return statements.
2854
2855void CFRefCount::EvalReturn(ExplodedNodeSet& Dst,
2856 GRExprEngine& Eng,
2857 GRStmtNodeBuilder& Builder,
2858 ReturnStmt* S,
2859 ExplodedNode* Pred) {
2860
2861 Expr* RetE = S->getRetValue();
2862 if (!RetE)
2863 return;
2864
2865 const GRState *state = Builder.GetState(Pred);
2866 SymbolRef Sym = state->getSValAsScalarOrLoc(RetE).getAsLocSymbol();
2867
2868 if (!Sym)
2869 return;
2870
2871 // Get the reference count binding (if any).
2872 const RefVal* T = state->get<RefBindings>(Sym);
2873
2874 if (!T)
2875 return;
2876
2877 // Change the reference count.
2878 RefVal X = *T;
2879
2880 switch (X.getKind()) {
2881 case RefVal::Owned: {
2882 unsigned cnt = X.getCount();
2883 assert (cnt > 0);
2884 X.setCount(cnt - 1);
2885 X = X ^ RefVal::ReturnedOwned;
2886 break;
2887 }
2888
2889 case RefVal::NotOwned: {
2890 unsigned cnt = X.getCount();
2891 if (cnt) {
2892 X.setCount(cnt - 1);
2893 X = X ^ RefVal::ReturnedOwned;
2894 }
2895 else {
2896 X = X ^ RefVal::ReturnedNotOwned;
2897 }
2898 break;
2899 }
2900
2901 default:
2902 return;
2903 }
2904
2905 // Update the binding.
2906 state = state->set<RefBindings>(Sym, X);
2907 Pred = Builder.MakeNode(Dst, S, Pred, state);
2908
2909 // Did we cache out?
2910 if (!Pred)
2911 return;
2912
2913 // Update the autorelease counts.
2914 static unsigned autoreleasetag = 0;
2915 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
2916 bool stop = false;
2917 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
2918 X, stop);
2919
2920 // Did we cache out?
2921 if (!Pred || stop)
2922 return;
2923
2924 // Get the updated binding.
2925 T = state->get<RefBindings>(Sym);
2926 assert(T);
2927 X = *T;
2928
2929 // Any leaks or other errors?
2930 if (X.isReturnedOwned() && X.getCount() == 0) {
2931 Decl const *CD = &Pred->getCodeDecl();
2932 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
2933 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
2934 RetEffect RE = Summ.getRetEffect();
2935 bool hasError = false;
2936
2937 if (RE.getKind() != RetEffect::NoRet) {
2938 if (isGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
2939 // Things are more complicated with garbage collection. If the
2940 // returned object is suppose to be an Objective-C object, we have
2941 // a leak (as the caller expects a GC'ed object) because no
2942 // method should return ownership unless it returns a CF object.
2943 hasError = true;
2944 X = X ^ RefVal::ErrorGCLeakReturned;
2945 }
2946 else if (!RE.isOwned()) {
2947 // Either we are using GC and the returned object is a CF type
2948 // or we aren't using GC. In either case, we expect that the
2949 // enclosing method is expected to return ownership.
2950 hasError = true;
2951 X = X ^ RefVal::ErrorLeakReturned;
2952 }
2953 }
2954
2955 if (hasError) {
2956 // Generate an error node.
2957 static int ReturnOwnLeakTag = 0;
2958 state = state->set<RefBindings>(Sym, X);
2959 ExplodedNode *N =
2960 Builder.generateNode(PostStmt(S, Pred->getLocationContext(),
2961 &ReturnOwnLeakTag), state, Pred);
2962 if (N) {
2963 CFRefReport *report =
2964 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
2965 N, Sym, Eng);
2966 BR->EmitReport(report);
2967 }
2968 }
2969 }
2970 }
2971 else if (X.isReturnedNotOwned()) {
2972 Decl const *CD = &Pred->getCodeDecl();
2973 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
2974 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
2975 if (Summ.getRetEffect().isOwned()) {
2976 // Trying to return a not owned object to a caller expecting an
2977 // owned object.
2978
2979 static int ReturnNotOwnedForOwnedTag = 0;
2980 state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
2981 if (ExplodedNode *N =
2982 Builder.generateNode(PostStmt(S, Pred->getLocationContext(),
2983 &ReturnNotOwnedForOwnedTag),
2984 state, Pred)) {
2985 CFRefReport *report =
2986 new CFRefReport(*static_cast<CFRefBug*>(returnNotOwnedForOwned),
2987 *this, N, Sym);
2988 BR->EmitReport(report);
2989 }
2990 }
2991 }
2992 }
2993}
2994
2995// Assumptions.
2996
2997const GRState* CFRefCount::EvalAssume(const GRState *state,
2998 SVal Cond, bool Assumption) {
2999
3000 // FIXME: We may add to the interface of EvalAssume the list of symbols
3001 // whose assumptions have changed. For now we just iterate through the
3002 // bindings and check if any of the tracked symbols are NULL. This isn't
3003 // too bad since the number of symbols we will track in practice are
3004 // probably small and EvalAssume is only called at branches and a few
3005 // other places.
3006 RefBindings B = state->get<RefBindings>();
3007
3008 if (B.isEmpty())
3009 return state;
3010
3011 bool changed = false;
3012 RefBindings::Factory& RefBFactory = state->get_context<RefBindings>();
3013
3014 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
3015 // Check if the symbol is null (or equal to any constant).
3016 // If this is the case, stop tracking the symbol.
3017 if (state->getSymVal(I.getKey())) {
3018 changed = true;
3019 B = RefBFactory.Remove(B, I.getKey());
3020 }
3021 }
3022
3023 if (changed)
3024 state = state->set<RefBindings>(B);
3025
3026 return state;
3027}
3028
3029const GRState * CFRefCount::Update(const GRState * state, SymbolRef sym,
3030 RefVal V, ArgEffect E,
3031 RefVal::Kind& hasErr) {
3032
3033 // In GC mode [... release] and [... retain] do nothing.
3034 switch (E) {
3035 default: break;
3036 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3037 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
3038 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
3039 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3040 NewAutoreleasePool; break;
3041 }
3042
3043 // Handle all use-after-releases.
3044 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3045 V = V ^ RefVal::ErrorUseAfterRelease;
3046 hasErr = V.getKind();
3047 return state->set<RefBindings>(sym, V);
3048 }
3049
3050 switch (E) {
3051 default:
3052 assert (false && "Unhandled CFRef transition.");
3053
3054 case Dealloc:
3055 // Any use of -dealloc in GC is *bad*.
3056 if (isGCEnabled()) {
3057 V = V ^ RefVal::ErrorDeallocGC;
3058 hasErr = V.getKind();
3059 break;
3060 }
3061
3062 switch (V.getKind()) {
3063 default:
3064 assert(false && "Invalid case.");
3065 case RefVal::Owned:
3066 // The object immediately transitions to the released state.
3067 V = V ^ RefVal::Released;
3068 V.clearCounts();
3069 return state->set<RefBindings>(sym, V);
3070 case RefVal::NotOwned:
3071 V = V ^ RefVal::ErrorDeallocNotOwned;
3072 hasErr = V.getKind();
3073 break;
3074 }
3075 break;
3076
3077 case NewAutoreleasePool:
3078 assert(!isGCEnabled());
3079 return state->add<AutoreleaseStack>(sym);
3080
3081 case MayEscape:
3082 if (V.getKind() == RefVal::Owned) {
3083 V = V ^ RefVal::NotOwned;
3084 break;
3085 }
3086
3087 // Fall-through.
3088
3089 case DoNothingByRef:
3090 case DoNothing:
3091 return state;
3092
3093 case Autorelease:
3094 if (isGCEnabled())
3095 return state;
3096
3097 // Update the autorelease counts.
3098 state = SendAutorelease(state, ARCountFactory, sym);
3099 V = V.autorelease();
3100 break;
3101
3102 case StopTracking:
3103 return state->remove<RefBindings>(sym);
3104
3105 case IncRef:
3106 switch (V.getKind()) {
3107 default:
3108 assert(false);
3109
3110 case RefVal::Owned:
3111 case RefVal::NotOwned:
3112 V = V + 1;
3113 break;
3114 case RefVal::Released:
3115 // Non-GC cases are handled above.
3116 assert(isGCEnabled());
3117 V = (V ^ RefVal::Owned) + 1;
3118 break;
3119 }
3120 break;
3121
3122 case SelfOwn:
3123 V = V ^ RefVal::NotOwned;
3124 // Fall-through.
3125 case DecRef:
3126 switch (V.getKind()) {
3127 default:
3128 // case 'RefVal::Released' handled above.
3129 assert (false);
3130
3131 case RefVal::Owned:
3132 assert(V.getCount() > 0);
3133 if (V.getCount() == 1) V = V ^ RefVal::Released;
3134 V = V - 1;
3135 break;
3136
3137 case RefVal::NotOwned:
3138 if (V.getCount() > 0)
3139 V = V - 1;
3140 else {
3141 V = V ^ RefVal::ErrorReleaseNotOwned;
3142 hasErr = V.getKind();
3143 }
3144 break;
3145
3146 case RefVal::Released:
3147 // Non-GC cases are handled above.
3148 assert(isGCEnabled());
3149 V = V ^ RefVal::ErrorUseAfterRelease;
3150 hasErr = V.getKind();
3151 break;
3152 }
3153 break;
3154 }
3155 return state->set<RefBindings>(sym, V);
3156}
3157
3158//===----------------------------------------------------------------------===//
3159// Handle dead symbols and end-of-path.
3160//===----------------------------------------------------------------------===//
3161
3162std::pair<ExplodedNode*, const GRState *>
3163CFRefCount::HandleAutoreleaseCounts(const GRState * state, GenericNodeBuilder Bd,
3164 ExplodedNode* Pred,
3165 GRExprEngine &Eng,
3166 SymbolRef Sym, RefVal V, bool &stop) {
3167
3168 unsigned ACnt = V.getAutoreleaseCount();
3169 stop = false;
3170
3171 // No autorelease counts? Nothing to be done.
3172 if (!ACnt)
3173 return std::make_pair(Pred, state);
3174
3175 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
3176 unsigned Cnt = V.getCount();
3177
3178 // FIXME: Handle sending 'autorelease' to already released object.
3179
3180 if (V.getKind() == RefVal::ReturnedOwned)
3181 ++Cnt;
3182
3183 if (ACnt <= Cnt) {
3184 if (ACnt == Cnt) {
3185 V.clearCounts();
3186 if (V.getKind() == RefVal::ReturnedOwned)
3187 V = V ^ RefVal::ReturnedNotOwned;
3188 else
3189 V = V ^ RefVal::NotOwned;
3190 }
3191 else {
3192 V.setCount(Cnt - ACnt);
3193 V.setAutoreleaseCount(0);
3194 }
3195 state = state->set<RefBindings>(Sym, V);
3196 ExplodedNode *N = Bd.MakeNode(state, Pred);
3197 stop = (N == 0);
3198 return std::make_pair(N, state);
3199 }
3200
3201 // Woah! More autorelease counts then retain counts left.
3202 // Emit hard error.
3203 stop = true;
3204 V = V ^ RefVal::ErrorOverAutorelease;
3205 state = state->set<RefBindings>(Sym, V);
3206
3207 if (ExplodedNode *N = Bd.MakeNode(state, Pred)) {
3208 N->markAsSink();
3209
3210 std::string sbuf;
3211 llvm::raw_string_ostream os(sbuf);
3212 os << "Object over-autoreleased: object was sent -autorelease";
3213 if (V.getAutoreleaseCount() > 1)
3214 os << V.getAutoreleaseCount() << " times";
3215 os << " but the object has ";
3216 if (V.getCount() == 0)
3217 os << "zero (locally visible)";
3218 else
3219 os << "+" << V.getCount();
3220 os << " retain counts";
3221
3222 CFRefReport *report =
3223 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
3224 *this, N, Sym, os.str());
3225 BR->EmitReport(report);
3226 }
3227
3228 return std::make_pair((ExplodedNode*)0, state);
3229}
3230
3231const GRState *
3232CFRefCount::HandleSymbolDeath(const GRState * state, SymbolRef sid, RefVal V,
3233 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3234
3235 bool hasLeak = V.isOwned() ||
3236 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3237
3238 if (!hasLeak)
3239 return state->remove<RefBindings>(sid);
3240
3241 Leaked.push_back(sid);
3242 return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3243}
3244
3245ExplodedNode*
3246CFRefCount::ProcessLeaks(const GRState * state,
3247 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3248 GenericNodeBuilder &Builder,
3249 GRExprEngine& Eng,
3250 ExplodedNode *Pred) {
3251
3252 if (Leaked.empty())
3253 return Pred;
3254
3255 // Generate an intermediate node representing the leak point.
3256 ExplodedNode *N = Builder.MakeNode(state, Pred);
3257
3258 if (N) {
3259 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3260 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3261
3262 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3263 : leakAtReturn);
3264 assert(BT && "BugType not initialized.");
3265 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3266 BR->EmitReport(report);
3267 }
3268 }
3269
3270 return N;
3271}
3272
3273void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3274 GREndPathNodeBuilder& Builder) {
3275
3276 const GRState *state = Builder.getState();
3277 GenericNodeBuilder Bd(Builder);
3278 RefBindings B = state->get<RefBindings>();
3279 ExplodedNode *Pred = 0;
3280
3281 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3282 bool stop = false;
3283 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3284 (*I).first,
3285 (*I).second, stop);
3286
3287 if (stop)
3288 return;
3289 }
3290
3291 B = state->get<RefBindings>();
3292 llvm::SmallVector<SymbolRef, 10> Leaked;
3293
3294 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3295 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3296
3297 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3298}
3299
3300void CFRefCount::EvalDeadSymbols(ExplodedNodeSet& Dst,
3301 GRExprEngine& Eng,
3302 GRStmtNodeBuilder& Builder,
3303 ExplodedNode* Pred,
3304 Stmt* S,
3305 const GRState* state,
3306 SymbolReaper& SymReaper) {
3307
3308 RefBindings B = state->get<RefBindings>();
3309
3310 // Update counts from autorelease pools
3311 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3312 E = SymReaper.dead_end(); I != E; ++I) {
3313 SymbolRef Sym = *I;
3314 if (const RefVal* T = B.lookup(Sym)){
3315 // Use the symbol as the tag.
3316 // FIXME: This might not be as unique as we would like.
3317 GenericNodeBuilder Bd(Builder, S, Sym);
3318 bool stop = false;
3319 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3320 Sym, *T, stop);
3321 if (stop)
3322 return;
3323 }
3324 }
3325
3326 B = state->get<RefBindings>();
3327 llvm::SmallVector<SymbolRef, 10> Leaked;
3328
3329 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3330 E = SymReaper.dead_end(); I != E; ++I) {
3331 if (const RefVal* T = B.lookup(*I))
3332 state = HandleSymbolDeath(state, *I, *T, Leaked);
3333 }
3334
3335 static unsigned LeakPPTag = 0;
3336 {
3337 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3338 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3339 }
3340
3341 // Did we cache out?
3342 if (!Pred)
3343 return;
3344
3345 // Now generate a new node that nukes the old bindings.
3346 RefBindings::Factory& F = state->get_context<RefBindings>();
3347
3348 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3349 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3350
3351 state = state->set<RefBindings>(B);
3352 Builder.MakeNode(Dst, S, Pred, state);
3353}
3354
3355void CFRefCount::ProcessNonLeakError(ExplodedNodeSet& Dst,
3356 GRStmtNodeBuilder& Builder,
3357 Expr* NodeExpr, Expr* ErrorExpr,
3358 ExplodedNode* Pred,
3359 const GRState* St,
3360 RefVal::Kind hasErr, SymbolRef Sym) {
3361 Builder.BuildSinks = true;
3362 ExplodedNode *N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3363
3364 if (!N)
3365 return;
3366
3367 CFRefBug *BT = 0;
3368
3369 switch (hasErr) {
3370 default:
3371 assert(false && "Unhandled error.");
3372 return;
3373 case RefVal::ErrorUseAfterRelease:
3374 BT = static_cast<CFRefBug*>(useAfterRelease);
3375 break;
3376 case RefVal::ErrorReleaseNotOwned:
3377 BT = static_cast<CFRefBug*>(releaseNotOwned);
3378 break;
3379 case RefVal::ErrorDeallocGC:
3380 BT = static_cast<CFRefBug*>(deallocGC);
3381 break;
3382 case RefVal::ErrorDeallocNotOwned:
3383 BT = static_cast<CFRefBug*>(deallocNotOwned);
3384 break;
3385 }
3386
3387 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
3388 report->addRange(ErrorExpr->getSourceRange());
3389 BR->EmitReport(report);
3390}
3391
3392//===----------------------------------------------------------------------===//
3393// Pieces of the retain/release checker implemented using a CheckerVisitor.
3394// More pieces of the retain/release checker will be migrated to this interface
3395// (ideally, all of it some day).
3396//===----------------------------------------------------------------------===//
3397
3398namespace {
3399class RetainReleaseChecker
3400 : public CheckerVisitor<RetainReleaseChecker> {
3401 CFRefCount *TF;
3402public:
3403 RetainReleaseChecker(CFRefCount *tf) : TF(tf) {}
3404 static void* getTag() { static int x = 0; return &x; }
3405
3406 void PostVisitBlockExpr(CheckerContext &C, const BlockExpr *BE);
3407};
3408} // end anonymous namespace
3409
3410
3411void RetainReleaseChecker::PostVisitBlockExpr(CheckerContext &C,
3412 const BlockExpr *BE) {
3413
3414 // Scan the BlockDecRefExprs for any object the retain/release checker
3415 // may be tracking.
3416 if (!BE->hasBlockDeclRefExprs())
3417 return;
3418
3419 const GRState *state = C.getState();
3420 const BlockDataRegion *R =
3421 cast<BlockDataRegion>(state->getSVal(BE).getAsRegion());
3422
3423 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
3424 E = R->referenced_vars_end();
3425
3426 if (I == E)
3427 return;
3428
3429 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
3430 // via captured variables, even though captured variables result in a copy
3431 // and in implicit increment/decrement of a retain count.
3432 llvm::SmallVector<const MemRegion*, 10> Regions;
3433 const LocationContext *LC = C.getPredecessor()->getLocationContext();
3434 MemRegionManager &MemMgr = C.getValueManager().getRegionManager();
3435
3436 for ( ; I != E; ++I) {
3437 const VarRegion *VR = *I;
3438 if (VR->getSuperRegion() == R) {
3439 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
3440 }
3441 Regions.push_back(VR);
3442 }
3443
3444 state =
3445 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
3446 Regions.data() + Regions.size()).getState();
3447 C.addTransition(state);
3448}
3449
3450//===----------------------------------------------------------------------===//
3451// Transfer function creation for external clients.
3452//===----------------------------------------------------------------------===//
3453
3454void CFRefCount::RegisterChecks(GRExprEngine& Eng) {
3455 BugReporter &BR = Eng.getBugReporter();
3456
3457 useAfterRelease = new UseAfterRelease(this);
3458 BR.Register(useAfterRelease);
3459
3460 releaseNotOwned = new BadRelease(this);
3461 BR.Register(releaseNotOwned);
3462
3463 deallocGC = new DeallocGC(this);
3464 BR.Register(deallocGC);
3465
3466 deallocNotOwned = new DeallocNotOwned(this);
3467 BR.Register(deallocNotOwned);
3468
3469 overAutorelease = new OverAutorelease(this);
3470 BR.Register(overAutorelease);
3471
3472 returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this);
3473 BR.Register(returnNotOwnedForOwned);
3474
3475 // First register "return" leaks.
3476 const char* name = 0;
3477
3478 if (isGCEnabled())
3479 name = "Leak of returned object when using garbage collection";
3480 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
3481 name = "Leak of returned object when not using garbage collection (GC) in "
3482 "dual GC/non-GC code";
3483 else {
3484 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
3485 name = "Leak of returned object";
3486 }
3487
3488 // Leaks should not be reported if they are post-dominated by a sink.
3489 leakAtReturn = new LeakAtReturn(this, name);
3490 leakAtReturn->setSuppressOnSink(true);
3491 BR.Register(leakAtReturn);
3492
3493 // Second, register leaks within a function/method.
3494 if (isGCEnabled())
3495 name = "Leak of object when using garbage collection";
3496 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
3497 name = "Leak of object when not using garbage collection (GC) in "
3498 "dual GC/non-GC code";
3499 else {
3500 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
3501 name = "Leak";
3502 }
3503
3504 // Leaks should not be reported if they are post-dominated by sinks.
3505 leakWithinFunction = new LeakWithinFunction(this, name);
3506 leakWithinFunction->setSuppressOnSink(true);
3507 BR.Register(leakWithinFunction);
3508
3509 // Save the reference to the BugReporter.
3510 this->BR = &BR;
3511
3512 // Register the RetainReleaseChecker with the GRExprEngine object.
3513 // Functionality in CFRefCount will be migrated to RetainReleaseChecker
3514 // over time.
3515 Eng.registerCheck(new RetainReleaseChecker(this));
3516}
3517
3518GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3519 const LangOptions& lopts) {
3520 return new CFRefCount(Ctx, GCEnabled, lopts);
3521}