blob: 84856bd6dcd53e35e1b1d7cf33516234570a2c03 [file] [log] [blame]
Ted Kremenek0e7d2522008-07-03 04:29:21 +00001//==- CheckObjCDealloc.cpp - Check ObjC -dealloc implementation --*- 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//
Devin Coughlinad9f53e2016-02-25 21:15:16 +000010// This checker analyzes Objective-C -dealloc methods and their callees
11// to warn about improper releasing of instance variables that back synthesized
12// properties. It warns about missing releases in the following cases:
13// - When a class has a synthesized instance variable for a 'retain' or 'copy'
14// property and lacks a -dealloc method in its implementation.
15// - When a class has a synthesized instance variable for a 'retain'/'copy'
16// property but the ivar is not released in -dealloc by either -release
17// or by nilling out the property.
18//
19// It warns about extra releases in -dealloc (but not in callees) when a
20// synthesized instance variable is released in the following cases:
21// - When the property is 'assign' and is not 'readonly'.
22// - When the property is 'weak'.
23//
24// This checker only warns for instance variables synthesized to back
25// properties. Handling the more general case would require inferring whether
26// an instance variable is stored retained or not. For synthesized properties,
27// this is specified in the property declaration itself.
Ted Kremenek0e7d2522008-07-03 04:29:21 +000028//
29//===----------------------------------------------------------------------===//
30
Argyrios Kyrtzidisaf45aca2011-02-17 21:39:33 +000031#include "ClangSACheckers.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000032#include "clang/AST/Attr.h"
Ted Kremenek0e7d2522008-07-03 04:29:21 +000033#include "clang/AST/DeclObjC.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000034#include "clang/AST/Expr.h"
35#include "clang/AST/ExprObjC.h"
Ted Kremeneke66ca6f2008-07-03 14:35:01 +000036#include "clang/Basic/LangOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
Devin Coughlinad9f53e2016-02-25 21:15:16 +000038#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
40#include "clang/StaticAnalyzer/Core/Checker.h"
41#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
Devin Coughlinad9f53e2016-02-25 21:15:16 +000042#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
43#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
44#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
45#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
46#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Ted Kremenek3f049492008-10-29 04:30:28 +000047#include "llvm/Support/raw_ostream.h"
Ted Kremenek0e7d2522008-07-03 04:29:21 +000048
49using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000050using namespace ento;
Ted Kremenek0e7d2522008-07-03 04:29:21 +000051
Devin Coughlinad9f53e2016-02-25 21:15:16 +000052/// Indicates whether an instance variable is required to be released in
53/// -dealloc.
54enum class ReleaseRequirement {
55 /// The instance variable must be released, either by calling
56 /// -release on it directly or by nilling it out with a property setter.
57 MustRelease,
Devin Coughlin982c42d2016-02-11 22:13:20 +000058
Devin Coughlinad9f53e2016-02-25 21:15:16 +000059 /// The instance variable must not be directly released with -release.
60 MustNotReleaseDirectly,
Mike Stump11289f42009-09-09 15:08:12 +000061
Devin Coughlinad9f53e2016-02-25 21:15:16 +000062 /// The requirement for the instance variable could not be determined.
63 Unknown
64};
Ted Kremenek3f049492008-10-29 04:30:28 +000065
Devin Coughlinad9f53e2016-02-25 21:15:16 +000066/// Returns true if the property implementation is synthesized and the
67/// type of the property is retainable.
Devin Coughlin30751342016-01-27 01:41:58 +000068static bool isSynthesizedRetainableProperty(const ObjCPropertyImplDecl *I,
69 const ObjCIvarDecl **ID,
70 const ObjCPropertyDecl **PD) {
71
72 if (I->getPropertyImplementation() != ObjCPropertyImplDecl::Synthesize)
73 return false;
74
75 (*ID) = I->getPropertyIvarDecl();
76 if (!(*ID))
77 return false;
78
79 QualType T = (*ID)->getType();
80 if (!T->isObjCRetainableType())
81 return false;
82
83 (*PD) = I->getPropertyDecl();
84 // Shouldn't be able to synthesize a property that doesn't exist.
85 assert(*PD);
86
87 return true;
88}
89
Devin Coughlinad9f53e2016-02-25 21:15:16 +000090namespace {
91
92class ObjCDeallocChecker
93 : public Checker<check::ASTDecl<ObjCImplementationDecl>,
94 check::PreObjCMessage, check::PostObjCMessage,
Devin Coughlin09359492016-02-29 23:57:10 +000095 check::PreCall,
Devin Coughlinad9f53e2016-02-25 21:15:16 +000096 check::BeginFunction, check::EndFunction,
Devin Coughlin3fc67e42016-02-29 21:44:08 +000097 eval::Assume,
Devin Coughlinad9f53e2016-02-25 21:15:16 +000098 check::PointerEscape,
99 check::PreStmt<ReturnStmt>> {
100
Devin Coughlin09359492016-02-29 23:57:10 +0000101 mutable IdentifierInfo *NSObjectII, *SenTestCaseII, *Block_releaseII;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000102 mutable Selector DeallocSel, ReleaseSel;
103
104 std::unique_ptr<BugType> MissingReleaseBugType;
105 std::unique_ptr<BugType> ExtraReleaseBugType;
Devin Coughlina6046792016-03-04 18:09:58 +0000106 std::unique_ptr<BugType> MistakenDeallocBugType;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000107
108public:
109 ObjCDeallocChecker();
110
111 void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
112 BugReporter &BR) const;
113 void checkBeginFunction(CheckerContext &Ctx) const;
114 void checkPreObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
Devin Coughlin09359492016-02-29 23:57:10 +0000115 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000116 void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
117
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000118 ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
119 bool Assumption) const;
120
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000121 ProgramStateRef checkPointerEscape(ProgramStateRef State,
122 const InvalidatedSymbols &Escaped,
123 const CallEvent *Call,
124 PointerEscapeKind Kind) const;
125 void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
126 void checkEndFunction(CheckerContext &Ctx) const;
127
128private:
129 void diagnoseMissingReleases(CheckerContext &C) const;
130
131 bool diagnoseExtraRelease(SymbolRef ReleasedValue, const ObjCMethodCall &M,
132 CheckerContext &C) const;
133
Devin Coughlina6046792016-03-04 18:09:58 +0000134 bool diagnoseMistakenDealloc(SymbolRef DeallocedValue,
135 const ObjCMethodCall &M,
136 CheckerContext &C) const;
137
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000138 SymbolRef getValueReleasedByNillingOut(const ObjCMethodCall &M,
139 CheckerContext &C) const;
140
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000141 const ObjCIvarRegion *getIvarRegionForIvarSymbol(SymbolRef IvarSym) const;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000142 SymbolRef getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const;
143
Devin Coughlina6046792016-03-04 18:09:58 +0000144 const ObjCPropertyImplDecl*
145 findPropertyOnDeallocatingInstance(SymbolRef IvarSym,
146 CheckerContext &C) const;
147
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000148 ReleaseRequirement
149 getDeallocReleaseRequirement(const ObjCPropertyImplDecl *PropImpl) const;
150
151 bool isInInstanceDealloc(const CheckerContext &C, SVal &SelfValOut) const;
152 bool isInInstanceDealloc(const CheckerContext &C, const LocationContext *LCtx,
153 SVal &SelfValOut) const;
154 bool instanceDeallocIsOnStack(const CheckerContext &C,
155 SVal &InstanceValOut) const;
156
157 bool isSuperDeallocMessage(const ObjCMethodCall &M) const;
158
159 const ObjCImplDecl *getContainingObjCImpl(const LocationContext *LCtx) const;
160
161 const ObjCPropertyDecl *
162 findShadowedPropertyDecl(const ObjCPropertyImplDecl *PropImpl) const;
163
Devin Coughlin09359492016-02-29 23:57:10 +0000164 void transitionToReleaseValue(CheckerContext &C, SymbolRef Value) const;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000165 ProgramStateRef removeValueRequiringRelease(ProgramStateRef State,
166 SymbolRef InstanceSym,
167 SymbolRef ValueSym) const;
168
169 void initIdentifierInfoAndSelectors(ASTContext &Ctx) const;
170
171 bool classHasSeparateTeardown(const ObjCInterfaceDecl *ID) const;
172};
173} // End anonymous namespace.
174
175typedef llvm::ImmutableSet<SymbolRef> SymbolSet;
176
177/// Maps from the symbol for a class instance to the set of
178/// symbols remaining that must be released in -dealloc.
179REGISTER_MAP_WITH_PROGRAMSTATE(UnreleasedIvarMap, SymbolRef, SymbolSet)
180
181namespace clang {
182namespace ento {
183template<> struct ProgramStateTrait<SymbolSet>
184: public ProgramStatePartialTrait<SymbolSet> {
185 static void *GDMIndex() { static int index = 0; return &index; }
186};
187}
Devin Coughlinea02bba2016-02-25 19:13:43 +0000188}
Devin Coughlin30751342016-01-27 01:41:58 +0000189
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000190/// An AST check that diagnose when the class requires a -dealloc method and
191/// is missing one.
192void ObjCDeallocChecker::checkASTDecl(const ObjCImplementationDecl *D,
193 AnalysisManager &Mgr,
194 BugReporter &BR) const {
195 assert(Mgr.getLangOpts().getGC() != LangOptions::GCOnly);
196 assert(!Mgr.getLangOpts().ObjCAutoRefCount);
197 initIdentifierInfoAndSelectors(Mgr.getASTContext());
Ted Kremenek0e7d2522008-07-03 04:29:21 +0000198
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000199 const ObjCInterfaceDecl *ID = D->getClassInterface();
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000200 // If the class is known to have a lifecycle with a separate teardown method
201 // then it may not require a -dealloc method.
202 if (classHasSeparateTeardown(ID))
Devin Coughlin88691c12016-02-25 18:55:24 +0000203 return;
204
Devin Coughlin6d0c8a02016-03-01 00:39:04 +0000205 // Does the class contain any synthesized properties that are retainable?
206 // If not, skip the check entirely.
207 const ObjCPropertyImplDecl *PropImplRequiringRelease = nullptr;
208 bool HasOthers = false;
209 for (const auto *I : D->property_impls()) {
210 if (getDeallocReleaseRequirement(I) == ReleaseRequirement::MustRelease) {
211 if (!PropImplRequiringRelease)
212 PropImplRequiringRelease = I;
213 else {
214 HasOthers = true;
215 break;
216 }
217 }
218 }
219
220 if (!PropImplRequiringRelease)
221 return;
222
Devin Coughlinea02bba2016-02-25 19:13:43 +0000223 const ObjCMethodDecl *MD = nullptr;
224
225 // Scan the instance methods for "dealloc".
226 for (const auto *I : D->instance_methods()) {
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000227 if (I->getSelector() == DeallocSel) {
Devin Coughlinea02bba2016-02-25 19:13:43 +0000228 MD = I;
229 break;
230 }
231 }
232
233 if (!MD) { // No dealloc found.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000234 const char* Name = "Missing -dealloc";
Devin Coughlinea02bba2016-02-25 19:13:43 +0000235
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000236 std::string Buf;
237 llvm::raw_string_ostream OS(Buf);
Devin Coughlin6d0c8a02016-03-01 00:39:04 +0000238 OS << "'" << *D << "' lacks a 'dealloc' instance method but "
239 << "must release '" << *PropImplRequiringRelease->getPropertyIvarDecl()
240 << "'";
Devin Coughlinea02bba2016-02-25 19:13:43 +0000241
Devin Coughlin6d0c8a02016-03-01 00:39:04 +0000242 if (HasOthers)
243 OS << " and others";
Devin Coughlinea02bba2016-02-25 19:13:43 +0000244 PathDiagnosticLocation DLoc =
245 PathDiagnosticLocation::createBegin(D, BR.getSourceManager());
246
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000247 BR.EmitBasicReport(D, this, Name, categories::CoreFoundationObjectiveC,
248 OS.str(), DLoc);
Devin Coughlinea02bba2016-02-25 19:13:43 +0000249 return;
250 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000251}
Devin Coughlinea02bba2016-02-25 19:13:43 +0000252
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000253/// If this is the beginning of -dealloc, mark the values initially stored in
254/// instance variables that must be released by the end of -dealloc
255/// as unreleased in the state.
256void ObjCDeallocChecker::checkBeginFunction(
257 CheckerContext &C) const {
258 initIdentifierInfoAndSelectors(C.getASTContext());
Devin Coughlinea02bba2016-02-25 19:13:43 +0000259
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000260 // Only do this if the current method is -dealloc.
261 SVal SelfVal;
262 if (!isInInstanceDealloc(C, SelfVal))
263 return;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000264
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000265 SymbolRef SelfSymbol = SelfVal.getAsSymbol();
266
267 const LocationContext *LCtx = C.getLocationContext();
268 ProgramStateRef InitialState = C.getState();
269
270 ProgramStateRef State = InitialState;
271
272 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
273
274 // Symbols that must be released by the end of the -dealloc;
275 SymbolSet RequiredReleases = F.getEmptySet();
276
277 // If we're an inlined -dealloc, we should add our symbols to the existing
278 // set from our subclass.
279 if (const SymbolSet *CurrSet = State->get<UnreleasedIvarMap>(SelfSymbol))
280 RequiredReleases = *CurrSet;
281
282 for (auto *PropImpl : getContainingObjCImpl(LCtx)->property_impls()) {
283 ReleaseRequirement Requirement = getDeallocReleaseRequirement(PropImpl);
284 if (Requirement != ReleaseRequirement::MustRelease)
Devin Coughlinea02bba2016-02-25 19:13:43 +0000285 continue;
286
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000287 SVal LVal = State->getLValue(PropImpl->getPropertyIvarDecl(), SelfVal);
288 Optional<Loc> LValLoc = LVal.getAs<Loc>();
289 if (!LValLoc)
290 continue;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000291
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000292 SVal InitialVal = State->getSVal(LValLoc.getValue());
293 SymbolRef Symbol = InitialVal.getAsSymbol();
294 if (!Symbol || !isa<SymbolRegionValue>(Symbol))
295 continue;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000296
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000297 // Mark the value as requiring a release.
298 RequiredReleases = F.add(RequiredReleases, Symbol);
299 }
Devin Coughlinea02bba2016-02-25 19:13:43 +0000300
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000301 if (!RequiredReleases.isEmpty()) {
302 State = State->set<UnreleasedIvarMap>(SelfSymbol, RequiredReleases);
303 }
Devin Coughlinea02bba2016-02-25 19:13:43 +0000304
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000305 if (State != InitialState) {
306 C.addTransition(State);
307 }
308}
Devin Coughlinea02bba2016-02-25 19:13:43 +0000309
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000310/// Given a symbol for an ivar, return the ivar region it was loaded from.
311/// Returns nullptr if the instance symbol cannot be found.
312const ObjCIvarRegion *
313ObjCDeallocChecker::getIvarRegionForIvarSymbol(SymbolRef IvarSym) const {
314 const MemRegion *RegionLoadedFrom = nullptr;
315 if (auto *DerivedSym = dyn_cast<SymbolDerived>(IvarSym))
316 RegionLoadedFrom = DerivedSym->getRegion();
317 else if (auto *RegionSym = dyn_cast<SymbolRegionValue>(IvarSym))
318 RegionLoadedFrom = RegionSym->getRegion();
319 else
320 return nullptr;
321
322 return dyn_cast<ObjCIvarRegion>(RegionLoadedFrom);
323}
324
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000325/// Given a symbol for an ivar, return a symbol for the instance containing
326/// the ivar. Returns nullptr if the instance symbol cannot be found.
327SymbolRef
328ObjCDeallocChecker::getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const {
Devin Coughlinea02bba2016-02-25 19:13:43 +0000329
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000330 const ObjCIvarRegion *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
331 if (!IvarRegion)
332 return nullptr;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000333
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000334 return IvarRegion->getSymbolicBase()->getSymbol();
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000335}
336
337/// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
338/// a release or a nilling-out property setter.
339void ObjCDeallocChecker::checkPreObjCMessage(
340 const ObjCMethodCall &M, CheckerContext &C) const {
341 // Only run if -dealloc is on the stack.
342 SVal DeallocedInstance;
343 if (!instanceDeallocIsOnStack(C, DeallocedInstance))
344 return;
345
Devin Coughlina6046792016-03-04 18:09:58 +0000346 SymbolRef ReleasedValue = nullptr;
347
348 if (M.getSelector() == ReleaseSel) {
349 ReleasedValue = M.getReceiverSVal().getAsSymbol();
350 } else if (M.getSelector() == DeallocSel && !M.isReceiverSelfOrSuper()) {
351 if (diagnoseMistakenDealloc(M.getReceiverSVal().getAsSymbol(), M, C))
352 return;
353 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000354
355 if (ReleasedValue) {
356 // An instance variable symbol was released with -release:
357 // [_property release];
358 if (diagnoseExtraRelease(ReleasedValue,M, C))
359 return;
360 } else {
361 // An instance variable symbol was released nilling out its property:
362 // self.property = nil;
363 ReleasedValue = getValueReleasedByNillingOut(M, C);
364 }
365
366 if (!ReleasedValue)
367 return;
368
Devin Coughlin09359492016-02-29 23:57:10 +0000369 transitionToReleaseValue(C, ReleasedValue);
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000370}
371
Devin Coughlin09359492016-02-29 23:57:10 +0000372/// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
373/// call to Block_release().
374void ObjCDeallocChecker::checkPreCall(const CallEvent &Call,
375 CheckerContext &C) const {
376 const IdentifierInfo *II = Call.getCalleeIdentifier();
377 if (II != Block_releaseII)
378 return;
379
380 if (Call.getNumArgs() != 1)
381 return;
382
383 SymbolRef ReleasedValue = Call.getArgSVal(0).getAsSymbol();
384 if (!ReleasedValue)
385 return;
386
387 transitionToReleaseValue(C, ReleasedValue);
388}
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000389/// If the message was a call to '[super dealloc]', diagnose any missing
390/// releases.
391void ObjCDeallocChecker::checkPostObjCMessage(
392 const ObjCMethodCall &M, CheckerContext &C) const {
393 // We perform this check post-message so that if the super -dealloc
394 // calls a helper method and that this class overrides, any ivars released in
395 // the helper method will be recorded before checking.
396 if (isSuperDeallocMessage(M))
397 diagnoseMissingReleases(C);
398}
399
400/// Check for missing releases even when -dealloc does not call
401/// '[super dealloc]'.
402void ObjCDeallocChecker::checkEndFunction(
403 CheckerContext &C) const {
404 diagnoseMissingReleases(C);
405}
406
407/// Check for missing releases on early return.
408void ObjCDeallocChecker::checkPreStmt(
409 const ReturnStmt *RS, CheckerContext &C) const {
410 diagnoseMissingReleases(C);
411}
412
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000413/// When a symbol is assumed to be nil, remove it from the set of symbols
414/// require to be nil.
415ProgramStateRef ObjCDeallocChecker::evalAssume(ProgramStateRef State, SVal Cond,
416 bool Assumption) const {
417 if (State->get<UnreleasedIvarMap>().isEmpty())
418 return State;
419
420 auto *CondBSE = dyn_cast_or_null<BinarySymExpr>(Cond.getAsSymExpr());
421 if (!CondBSE)
422 return State;
423
424 BinaryOperator::Opcode OpCode = CondBSE->getOpcode();
425 if (Assumption) {
426 if (OpCode != BO_EQ)
427 return State;
428 } else {
429 if (OpCode != BO_NE)
430 return State;
431 }
432
433 SymbolRef NullSymbol = nullptr;
434 if (auto *SIE = dyn_cast<SymIntExpr>(CondBSE)) {
435 const llvm::APInt &RHS = SIE->getRHS();
436 if (RHS != 0)
437 return State;
438 NullSymbol = SIE->getLHS();
439 } else if (auto *SIE = dyn_cast<IntSymExpr>(CondBSE)) {
440 const llvm::APInt &LHS = SIE->getLHS();
441 if (LHS != 0)
442 return State;
443 NullSymbol = SIE->getRHS();
444 } else {
445 return State;
446 }
447
448 SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(NullSymbol);
449 if (!InstanceSymbol)
450 return State;
451
452 State = removeValueRequiringRelease(State, InstanceSymbol, NullSymbol);
453
454 return State;
455}
456
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000457/// If a symbol escapes conservatively assume unseen code released it.
458ProgramStateRef ObjCDeallocChecker::checkPointerEscape(
459 ProgramStateRef State, const InvalidatedSymbols &Escaped,
460 const CallEvent *Call, PointerEscapeKind Kind) const {
461
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000462 if (State->get<UnreleasedIvarMap>().isEmpty())
463 return State;
464
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000465 // Don't treat calls to '[super dealloc]' as escaping for the purposes
466 // of this checker. Because the checker diagnoses missing releases in the
467 // post-message handler for '[super dealloc], escaping here would cause
468 // the checker to never warn.
469 auto *OMC = dyn_cast_or_null<ObjCMethodCall>(Call);
470 if (OMC && isSuperDeallocMessage(*OMC))
471 return State;
472
473 for (const auto &Sym : Escaped) {
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000474 if (!Call || (Call && !Call->isInSystemHeader())) {
475 // If Sym is a symbol for an object with instance variables that
476 // must be released, remove these obligations when the object escapes
477 // unless via a call to a system function. System functions are
478 // very unlikely to release instance variables on objects passed to them,
479 // and are frequently called on 'self' in -dealloc (e.g., to remove
480 // observers) -- we want to avoid false negatives from escaping on
481 // them.
482 State = State->remove<UnreleasedIvarMap>(Sym);
483 }
484
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000485
486 SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(Sym);
487 if (!InstanceSymbol)
488 continue;
489
490 State = removeValueRequiringRelease(State, InstanceSymbol, Sym);
491 }
492
493 return State;
494}
495
496/// Report any unreleased instance variables for the current instance being
497/// dealloced.
498void ObjCDeallocChecker::diagnoseMissingReleases(CheckerContext &C) const {
499 ProgramStateRef State = C.getState();
500
501 SVal SelfVal;
502 if (!isInInstanceDealloc(C, SelfVal))
503 return;
504
505 const MemRegion *SelfRegion = SelfVal.castAs<loc::MemRegionVal>().getRegion();
506 const LocationContext *LCtx = C.getLocationContext();
507
508 ExplodedNode *ErrNode = nullptr;
509
510 SymbolRef SelfSym = SelfVal.getAsSymbol();
511 if (!SelfSym)
512 return;
513
514 const SymbolSet *OldUnreleased = State->get<UnreleasedIvarMap>(SelfSym);
515 if (!OldUnreleased)
516 return;
517
518 SymbolSet NewUnreleased = *OldUnreleased;
519 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
520
521 ProgramStateRef InitialState = State;
522
523 for (auto *IvarSymbol : *OldUnreleased) {
524 const TypedValueRegion *TVR =
525 cast<SymbolRegionValue>(IvarSymbol)->getRegion();
526 const ObjCIvarRegion *IvarRegion = cast<ObjCIvarRegion>(TVR);
527
528 // Don't warn if the ivar is not for this instance.
529 if (SelfRegion != IvarRegion->getSuperRegion())
530 continue;
531
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000532 const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000533 // Prevent an inlined call to -dealloc in a super class from warning
534 // about the values the subclass's -dealloc should release.
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000535 if (IvarDecl->getContainingInterface() !=
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000536 cast<ObjCMethodDecl>(LCtx->getDecl())->getClassInterface())
537 continue;
538
539 // Prevents diagnosing multiple times for the same instance variable
540 // at, for example, both a return and at the end of of the function.
541 NewUnreleased = F.remove(NewUnreleased, IvarSymbol);
542
543 if (State->getStateManager()
544 .getConstraintManager()
545 .isNull(State, IvarSymbol)
546 .isConstrainedTrue()) {
547 continue;
548 }
549
550 // A missing release manifests as a leak, so treat as a non-fatal error.
551 if (!ErrNode)
552 ErrNode = C.generateNonFatalErrorNode();
553 // If we've already reached this node on another path, return without
554 // diagnosing.
555 if (!ErrNode)
556 return;
557
558 std::string Buf;
559 llvm::raw_string_ostream OS(Buf);
560
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000561 const ObjCInterfaceDecl *Interface = IvarDecl->getContainingInterface();
562 // If the class is known to have a lifecycle with teardown that is
563 // separate from -dealloc, do not warn about missing releases. We
564 // suppress here (rather than not tracking for instance variables in
565 // such classes) because these classes are rare.
566 if (classHasSeparateTeardown(Interface))
567 return;
568
569 ObjCImplDecl *ImplDecl = Interface->getImplementation();
570
571 const ObjCPropertyImplDecl *PropImpl =
572 ImplDecl->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
573
574 const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
575
576 assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Copy ||
577 PropDecl->getSetterKind() == ObjCPropertyDecl::Retain);
578
579 OS << "The '" << *IvarDecl << "' ivar in '" << *ImplDecl
580 << "' was ";
581
582 if (PropDecl->getSetterKind() == ObjCPropertyDecl::Retain)
583 OS << "retained";
584 else
585 OS << "copied";
586
587 OS << " by a synthesized property but not released"
588 " before '[super dealloc]'";
589
590 std::unique_ptr<BugReport> BR(
591 new BugReport(*MissingReleaseBugType, OS.str(), ErrNode));
592
593 C.emitReport(std::move(BR));
594 }
595
596 if (NewUnreleased.isEmpty()) {
597 State = State->remove<UnreleasedIvarMap>(SelfSym);
598 } else {
599 State = State->set<UnreleasedIvarMap>(SelfSym, NewUnreleased);
600 }
601
602 if (ErrNode) {
603 C.addTransition(State, ErrNode);
604 } else if (State != InitialState) {
605 C.addTransition(State);
606 }
607
608 // Make sure that after checking in the top-most frame the list of
609 // tracked ivars is empty. This is intended to detect accidental leaks in
610 // the UnreleasedIvarMap program state.
611 assert(!LCtx->inTopFrame() || State->get<UnreleasedIvarMap>().isEmpty());
612}
613
Devin Coughlina6046792016-03-04 18:09:58 +0000614/// Given a symbol, determine whether the symbol refers to an ivar on
615/// the top-most deallocating instance. If so, find the property for that
616/// ivar, if one exists. Otherwise return null.
617const ObjCPropertyImplDecl *
618ObjCDeallocChecker::findPropertyOnDeallocatingInstance(
619 SymbolRef IvarSym, CheckerContext &C) const {
620 SVal DeallocedInstance;
621 if (!isInInstanceDealloc(C, DeallocedInstance))
622 return nullptr;
623
624 // Try to get the region from which the ivar value was loaded.
625 auto *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
626 if (!IvarRegion)
627 return nullptr;
628
629 // Don't try to find the property if the ivar was not loaded from the
630 // given instance.
631 if (DeallocedInstance.castAs<loc::MemRegionVal>().getRegion() !=
632 IvarRegion->getSuperRegion())
633 return nullptr;
634
635 const LocationContext *LCtx = C.getLocationContext();
636 const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
637
638 const ObjCImplDecl *Container = getContainingObjCImpl(LCtx);
639 const ObjCPropertyImplDecl *PropImpl =
640 Container->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
641 return PropImpl;
642}
643
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000644/// Emits a warning if the current context is -dealloc and ReleasedValue
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000645/// must not be directly released in a -dealloc. Returns true if a diagnostic
646/// was emitted.
647bool ObjCDeallocChecker::diagnoseExtraRelease(SymbolRef ReleasedValue,
648 const ObjCMethodCall &M,
649 CheckerContext &C) const {
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000650 // Try to get the region from which the the released value was loaded.
651 // Note that, unlike diagnosing for missing releases, here we don't track
652 // values that must not be released in the state. This is because even if
653 // these values escape, it is still an error under the rules of MRR to
654 // release them in -dealloc.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000655 const ObjCPropertyImplDecl *PropImpl =
Devin Coughlina6046792016-03-04 18:09:58 +0000656 findPropertyOnDeallocatingInstance(ReleasedValue, C);
657
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000658 if (!PropImpl)
659 return false;
660
Devin Coughlina6046792016-03-04 18:09:58 +0000661 // If the ivar belongs to a property that must not be released directly
662 // in dealloc, emit a warning.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000663 if (getDeallocReleaseRequirement(PropImpl) !=
664 ReleaseRequirement::MustNotReleaseDirectly) {
665 return false;
666 }
667
668 // If the property is readwrite but it shadows a read-only property in its
669 // external interface, treat the property a read-only. If the outside
670 // world cannot write to a property then the internal implementation is free
671 // to make its own convention about whether the value is stored retained
672 // or not. We look up the shadow here rather than in
673 // getDeallocReleaseRequirement() because doing so can be expensive.
674 const ObjCPropertyDecl *PropDecl = findShadowedPropertyDecl(PropImpl);
675 if (PropDecl) {
676 if (PropDecl->isReadOnly())
677 return false;
678 } else {
679 PropDecl = PropImpl->getPropertyDecl();
680 }
681
682 ExplodedNode *ErrNode = C.generateNonFatalErrorNode();
683 if (!ErrNode)
684 return false;
685
686 std::string Buf;
687 llvm::raw_string_ostream OS(Buf);
688
689 assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Weak ||
690 (PropDecl->getSetterKind() == ObjCPropertyDecl::Assign &&
691 !PropDecl->isReadOnly()));
692
Devin Coughlina6046792016-03-04 18:09:58 +0000693 const ObjCImplDecl *Container = getContainingObjCImpl(C.getLocationContext());
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000694 OS << "The '" << *PropImpl->getPropertyIvarDecl()
695 << "' ivar in '" << *Container
696 << "' was synthesized for ";
697
698 if (PropDecl->getSetterKind() == ObjCPropertyDecl::Weak)
699 OS << "a weak";
700 else
701 OS << "an assign, readwrite";
702
703 OS << " property but was released in 'dealloc'";
704
705 std::unique_ptr<BugReport> BR(
706 new BugReport(*ExtraReleaseBugType, OS.str(), ErrNode));
707 BR->addRange(M.getOriginExpr()->getSourceRange());
708
709 C.emitReport(std::move(BR));
710
711 return true;
712}
713
Devin Coughlina6046792016-03-04 18:09:58 +0000714/// Emits a warning if the current context is -dealloc and DeallocedValue
715/// must not be directly dealloced in a -dealloc. Returns true if a diagnostic
716/// was emitted.
717bool ObjCDeallocChecker::diagnoseMistakenDealloc(SymbolRef DeallocedValue,
718 const ObjCMethodCall &M,
719 CheckerContext &C) const {
720
721 // Find the property backing the instance variable that M
722 // is dealloc'ing.
723 const ObjCPropertyImplDecl *PropImpl =
724 findPropertyOnDeallocatingInstance(DeallocedValue, C);
725 if (!PropImpl)
726 return false;
727
728 if (getDeallocReleaseRequirement(PropImpl) !=
729 ReleaseRequirement::MustRelease) {
730 return false;
731 }
732
733 ExplodedNode *ErrNode = C.generateErrorNode();
734 if (!ErrNode)
735 return false;
736
737 std::string Buf;
738 llvm::raw_string_ostream OS(Buf);
739
740 OS << "'" << *PropImpl->getPropertyIvarDecl()
741 << "' should be released rather than deallocated";
742
743 std::unique_ptr<BugReport> BR(
744 new BugReport(*MistakenDeallocBugType, OS.str(), ErrNode));
745 BR->addRange(M.getOriginExpr()->getSourceRange());
746
747 C.emitReport(std::move(BR));
748
749 return true;
750}
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000751
752ObjCDeallocChecker::
753 ObjCDeallocChecker()
754 : NSObjectII(nullptr), SenTestCaseII(nullptr) {
755
756 MissingReleaseBugType.reset(
757 new BugType(this, "Missing ivar release (leak)",
758 categories::MemoryCoreFoundationObjectiveC));
759
760 ExtraReleaseBugType.reset(
761 new BugType(this, "Extra ivar release",
762 categories::MemoryCoreFoundationObjectiveC));
Devin Coughlina6046792016-03-04 18:09:58 +0000763
764 MistakenDeallocBugType.reset(
765 new BugType(this, "Mistaken dealloc",
766 categories::MemoryCoreFoundationObjectiveC));
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000767}
768
769void ObjCDeallocChecker::initIdentifierInfoAndSelectors(
770 ASTContext &Ctx) const {
771 if (NSObjectII)
772 return;
773
774 NSObjectII = &Ctx.Idents.get("NSObject");
775 SenTestCaseII = &Ctx.Idents.get("SenTestCase");
Devin Coughlin09359492016-02-29 23:57:10 +0000776 Block_releaseII = &Ctx.Idents.get("_Block_release");
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000777
778 IdentifierInfo *DeallocII = &Ctx.Idents.get("dealloc");
779 IdentifierInfo *ReleaseII = &Ctx.Idents.get("release");
780 DeallocSel = Ctx.Selectors.getSelector(0, &DeallocII);
781 ReleaseSel = Ctx.Selectors.getSelector(0, &ReleaseII);
782}
783
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000784/// Returns true if M is a call to '[super dealloc]'.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000785bool ObjCDeallocChecker::isSuperDeallocMessage(
786 const ObjCMethodCall &M) const {
787 if (M.getOriginExpr()->getReceiverKind() != ObjCMessageExpr::SuperInstance)
788 return false;
789
790 return M.getSelector() == DeallocSel;
791}
792
NAKAMURA Takumia8aa5f02016-02-26 03:15:13 +0000793/// Returns the ObjCImplDecl containing the method declaration in LCtx.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000794const ObjCImplDecl *
795ObjCDeallocChecker::getContainingObjCImpl(const LocationContext *LCtx) const {
796 auto *MD = cast<ObjCMethodDecl>(LCtx->getDecl());
797 return cast<ObjCImplDecl>(MD->getDeclContext());
798}
799
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000800/// Returns the property that shadowed by PropImpl if one exists and
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000801/// nullptr otherwise.
802const ObjCPropertyDecl *ObjCDeallocChecker::findShadowedPropertyDecl(
803 const ObjCPropertyImplDecl *PropImpl) const {
804 const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
805
806 // Only readwrite properties can shadow.
807 if (PropDecl->isReadOnly())
808 return nullptr;
809
810 auto *CatDecl = dyn_cast<ObjCCategoryDecl>(PropDecl->getDeclContext());
811
812 // Only class extensions can contain shadowing properties.
813 if (!CatDecl || !CatDecl->IsClassExtension())
814 return nullptr;
815
816 IdentifierInfo *ID = PropDecl->getIdentifier();
817 DeclContext::lookup_result R = CatDecl->getClassInterface()->lookup(ID);
818 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
819 auto *ShadowedPropDecl = dyn_cast<ObjCPropertyDecl>(*I);
820 if (!ShadowedPropDecl)
821 continue;
822
823 if (ShadowedPropDecl->isInstanceProperty()) {
824 assert(ShadowedPropDecl->isReadOnly());
825 return ShadowedPropDecl;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000826 }
827 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000828
829 return nullptr;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000830}
831
Devin Coughlin09359492016-02-29 23:57:10 +0000832/// Add a transition noting the release of the given value.
833void ObjCDeallocChecker::transitionToReleaseValue(CheckerContext &C,
834 SymbolRef Value) const {
835 assert(Value);
836 SymbolRef InstanceSym = getInstanceSymbolFromIvarSymbol(Value);
837 if (!InstanceSym)
838 return;
839 ProgramStateRef InitialState = C.getState();
840
841 ProgramStateRef ReleasedState =
842 removeValueRequiringRelease(InitialState, InstanceSym, Value);
843
844 if (ReleasedState != InitialState) {
845 C.addTransition(ReleasedState);
846 }
847}
848
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000849/// Remove the Value requiring a release from the tracked set for
850/// Instance and return the resultant state.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000851ProgramStateRef ObjCDeallocChecker::removeValueRequiringRelease(
852 ProgramStateRef State, SymbolRef Instance, SymbolRef Value) const {
853 assert(Instance);
854 assert(Value);
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000855 const ObjCIvarRegion *RemovedRegion = getIvarRegionForIvarSymbol(Value);
856 if (!RemovedRegion)
857 return State;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000858
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000859 const SymbolSet *Unreleased = State->get<UnreleasedIvarMap>(Instance);
860 if (!Unreleased)
861 return State;
862
863 // Mark the value as no longer requiring a release.
864 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000865 SymbolSet NewUnreleased = *Unreleased;
866 for (auto &Sym : *Unreleased) {
867 const ObjCIvarRegion *UnreleasedRegion = getIvarRegionForIvarSymbol(Sym);
868 assert(UnreleasedRegion);
869 if (RemovedRegion->getDecl() == UnreleasedRegion->getDecl()) {
870 NewUnreleased = F.remove(NewUnreleased, Sym);
871 }
872 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000873
874 if (NewUnreleased.isEmpty()) {
875 return State->remove<UnreleasedIvarMap>(Instance);
Devin Coughlinea02bba2016-02-25 19:13:43 +0000876 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000877
878 return State->set<UnreleasedIvarMap>(Instance, NewUnreleased);
Devin Coughlinea02bba2016-02-25 19:13:43 +0000879}
880
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000881/// Determines whether the instance variable for \p PropImpl must or must not be
882/// released in -dealloc or whether it cannot be determined.
883ReleaseRequirement ObjCDeallocChecker::getDeallocReleaseRequirement(
884 const ObjCPropertyImplDecl *PropImpl) const {
885 const ObjCIvarDecl *IvarDecl;
886 const ObjCPropertyDecl *PropDecl;
887 if (!isSynthesizedRetainableProperty(PropImpl, &IvarDecl, &PropDecl))
888 return ReleaseRequirement::Unknown;
889
890 ObjCPropertyDecl::SetterKind SK = PropDecl->getSetterKind();
891
892 switch (SK) {
893 // Retain and copy setters retain/copy their values before storing and so
894 // the value in their instance variables must be released in -dealloc.
895 case ObjCPropertyDecl::Retain:
896 case ObjCPropertyDecl::Copy:
897 return ReleaseRequirement::MustRelease;
898
899 case ObjCPropertyDecl::Weak:
900 return ReleaseRequirement::MustNotReleaseDirectly;
901
902 case ObjCPropertyDecl::Assign:
903 // It is common for the ivars for read-only assign properties to
904 // always be stored retained, so their release requirement cannot be
905 // be determined.
906 if (PropDecl->isReadOnly())
907 return ReleaseRequirement::Unknown;
908
909 return ReleaseRequirement::MustNotReleaseDirectly;
910 }
911 llvm_unreachable("Unrecognized setter kind");
912}
913
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000914/// Returns the released value if M is a call a setter that releases
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000915/// and nils out its underlying instance variable.
916SymbolRef
917ObjCDeallocChecker::getValueReleasedByNillingOut(const ObjCMethodCall &M,
918 CheckerContext &C) const {
919 SVal ReceiverVal = M.getReceiverSVal();
920 if (!ReceiverVal.isValid())
921 return nullptr;
922
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000923 if (M.getNumArgs() == 0)
924 return nullptr;
Devin Coughlin578a20a2016-03-03 21:38:39 +0000925
926 if (!M.getArgExpr(0)->getType()->isObjCRetainableType())
927 return nullptr;
928
929 // Is the first argument nil?
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000930 SVal Arg = M.getArgSVal(0);
931 ProgramStateRef notNilState, nilState;
932 std::tie(notNilState, nilState) =
933 M.getState()->assume(Arg.castAs<DefinedOrUnknownSVal>());
934 if (!(nilState && !notNilState))
935 return nullptr;
936
937 const ObjCPropertyDecl *Prop = M.getAccessedProperty();
938 if (!Prop)
939 return nullptr;
940
941 ObjCIvarDecl *PropIvarDecl = Prop->getPropertyIvarDecl();
942 if (!PropIvarDecl)
943 return nullptr;
944
945 ProgramStateRef State = C.getState();
946
947 SVal LVal = State->getLValue(PropIvarDecl, ReceiverVal);
948 Optional<Loc> LValLoc = LVal.getAs<Loc>();
949 if (!LValLoc)
950 return nullptr;
951
952 SVal CurrentValInIvar = State->getSVal(LValLoc.getValue());
953 return CurrentValInIvar.getAsSymbol();
954}
955
956/// Returns true if the current context is a call to -dealloc and false
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000957/// otherwise. If true, it also sets SelfValOut to the value of
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000958/// 'self'.
959bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
960 SVal &SelfValOut) const {
961 return isInInstanceDealloc(C, C.getLocationContext(), SelfValOut);
962}
963
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000964/// Returns true if LCtx is a call to -dealloc and false
965/// otherwise. If true, it also sets SelfValOut to the value of
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000966/// 'self'.
967bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
968 const LocationContext *LCtx,
969 SVal &SelfValOut) const {
970 auto *MD = dyn_cast<ObjCMethodDecl>(LCtx->getDecl());
971 if (!MD || !MD->isInstanceMethod() || MD->getSelector() != DeallocSel)
972 return false;
973
974 const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
975 assert(SelfDecl && "No self in -dealloc?");
976
977 ProgramStateRef State = C.getState();
978 SelfValOut = State->getSVal(State->getRegion(SelfDecl, LCtx));
979 return true;
980}
981
982/// Returns true if there is a call to -dealloc anywhere on the stack and false
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000983/// otherwise. If true, it also sets InstanceValOut to the value of
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000984/// 'self' in the frame for -dealloc.
985bool ObjCDeallocChecker::instanceDeallocIsOnStack(const CheckerContext &C,
986 SVal &InstanceValOut) const {
987 const LocationContext *LCtx = C.getLocationContext();
988
989 while (LCtx) {
990 if (isInInstanceDealloc(C, LCtx, InstanceValOut))
991 return true;
992
993 LCtx = LCtx->getParent();
994 }
995
996 return false;
997}
998
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000999/// Returns true if the ID is a class in which which is known to have
Devin Coughlinad9f53e2016-02-25 21:15:16 +00001000/// a separate teardown lifecycle. In this case, -dealloc warnings
1001/// about missing releases should be suppressed.
1002bool ObjCDeallocChecker::classHasSeparateTeardown(
1003 const ObjCInterfaceDecl *ID) const {
1004 // Suppress if the class is not a subclass of NSObject.
1005 for ( ; ID ; ID = ID->getSuperClass()) {
1006 IdentifierInfo *II = ID->getIdentifier();
1007
1008 if (II == NSObjectII)
1009 return false;
1010
1011 // FIXME: For now, ignore classes that subclass SenTestCase, as these don't
1012 // need to implement -dealloc. They implement tear down in another way,
1013 // which we should try and catch later.
1014 // http://llvm.org/bugs/show_bug.cgi?id=3187
1015 if (II == SenTestCaseII)
1016 return true;
1017 }
1018
1019 return true;
1020}
1021
1022void ento::registerObjCDeallocChecker(CheckerManager &Mgr) {
1023 const LangOptions &LangOpts = Mgr.getLangOpts();
1024 // These checker only makes sense under MRR.
1025 if (LangOpts.getGC() == LangOptions::GCOnly || LangOpts.ObjCAutoRefCount)
1026 return;
1027
1028 Mgr.registerChecker<ObjCDeallocChecker>();
Argyrios Kyrtzidisaf45aca2011-02-17 21:39:33 +00001029}