blob: 50915f399a16d7c67fef9ccdf658055b039df624 [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 Coughlin9d5057c2016-06-22 17:03:10 +0000101 mutable IdentifierInfo *NSObjectII, *SenTestCaseII, *XCTestCaseII,
102 *Block_releaseII, *CIFilterII;
103
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000104 mutable Selector DeallocSel, ReleaseSel;
105
106 std::unique_ptr<BugType> MissingReleaseBugType;
107 std::unique_ptr<BugType> ExtraReleaseBugType;
Devin Coughlina6046792016-03-04 18:09:58 +0000108 std::unique_ptr<BugType> MistakenDeallocBugType;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000109
110public:
111 ObjCDeallocChecker();
112
113 void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
114 BugReporter &BR) const;
115 void checkBeginFunction(CheckerContext &Ctx) const;
116 void checkPreObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
Devin Coughlin09359492016-02-29 23:57:10 +0000117 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000118 void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
119
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000120 ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
121 bool Assumption) const;
122
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000123 ProgramStateRef checkPointerEscape(ProgramStateRef State,
124 const InvalidatedSymbols &Escaped,
125 const CallEvent *Call,
126 PointerEscapeKind Kind) const;
127 void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
128 void checkEndFunction(CheckerContext &Ctx) const;
129
130private:
131 void diagnoseMissingReleases(CheckerContext &C) const;
132
133 bool diagnoseExtraRelease(SymbolRef ReleasedValue, const ObjCMethodCall &M,
134 CheckerContext &C) const;
135
Devin Coughlina6046792016-03-04 18:09:58 +0000136 bool diagnoseMistakenDealloc(SymbolRef DeallocedValue,
137 const ObjCMethodCall &M,
138 CheckerContext &C) const;
139
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000140 SymbolRef getValueReleasedByNillingOut(const ObjCMethodCall &M,
141 CheckerContext &C) const;
142
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000143 const ObjCIvarRegion *getIvarRegionForIvarSymbol(SymbolRef IvarSym) const;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000144 SymbolRef getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const;
145
Devin Coughlina6046792016-03-04 18:09:58 +0000146 const ObjCPropertyImplDecl*
147 findPropertyOnDeallocatingInstance(SymbolRef IvarSym,
148 CheckerContext &C) const;
149
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000150 ReleaseRequirement
151 getDeallocReleaseRequirement(const ObjCPropertyImplDecl *PropImpl) const;
152
153 bool isInInstanceDealloc(const CheckerContext &C, SVal &SelfValOut) const;
154 bool isInInstanceDealloc(const CheckerContext &C, const LocationContext *LCtx,
155 SVal &SelfValOut) const;
156 bool instanceDeallocIsOnStack(const CheckerContext &C,
157 SVal &InstanceValOut) const;
158
159 bool isSuperDeallocMessage(const ObjCMethodCall &M) const;
160
161 const ObjCImplDecl *getContainingObjCImpl(const LocationContext *LCtx) const;
162
163 const ObjCPropertyDecl *
164 findShadowedPropertyDecl(const ObjCPropertyImplDecl *PropImpl) const;
165
Devin Coughlin09359492016-02-29 23:57:10 +0000166 void transitionToReleaseValue(CheckerContext &C, SymbolRef Value) const;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000167 ProgramStateRef removeValueRequiringRelease(ProgramStateRef State,
168 SymbolRef InstanceSym,
169 SymbolRef ValueSym) const;
170
171 void initIdentifierInfoAndSelectors(ASTContext &Ctx) const;
172
173 bool classHasSeparateTeardown(const ObjCInterfaceDecl *ID) const;
Devin Coughlinb8076292016-03-25 21:18:22 +0000174
175 bool isReleasedByCIFilterDealloc(const ObjCPropertyImplDecl *PropImpl) const;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000176};
177} // End anonymous namespace.
178
179typedef llvm::ImmutableSet<SymbolRef> SymbolSet;
180
181/// Maps from the symbol for a class instance to the set of
182/// symbols remaining that must be released in -dealloc.
183REGISTER_MAP_WITH_PROGRAMSTATE(UnreleasedIvarMap, SymbolRef, SymbolSet)
184
185namespace clang {
186namespace ento {
187template<> struct ProgramStateTrait<SymbolSet>
188: public ProgramStatePartialTrait<SymbolSet> {
189 static void *GDMIndex() { static int index = 0; return &index; }
190};
191}
Devin Coughlinea02bba2016-02-25 19:13:43 +0000192}
Devin Coughlin30751342016-01-27 01:41:58 +0000193
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000194/// An AST check that diagnose when the class requires a -dealloc method and
195/// is missing one.
196void ObjCDeallocChecker::checkASTDecl(const ObjCImplementationDecl *D,
197 AnalysisManager &Mgr,
198 BugReporter &BR) const {
199 assert(Mgr.getLangOpts().getGC() != LangOptions::GCOnly);
200 assert(!Mgr.getLangOpts().ObjCAutoRefCount);
201 initIdentifierInfoAndSelectors(Mgr.getASTContext());
Ted Kremenek0e7d2522008-07-03 04:29:21 +0000202
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000203 const ObjCInterfaceDecl *ID = D->getClassInterface();
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000204 // If the class is known to have a lifecycle with a separate teardown method
205 // then it may not require a -dealloc method.
206 if (classHasSeparateTeardown(ID))
Devin Coughlin88691c12016-02-25 18:55:24 +0000207 return;
208
Devin Coughlin6d0c8a02016-03-01 00:39:04 +0000209 // Does the class contain any synthesized properties that are retainable?
210 // If not, skip the check entirely.
211 const ObjCPropertyImplDecl *PropImplRequiringRelease = nullptr;
212 bool HasOthers = false;
213 for (const auto *I : D->property_impls()) {
214 if (getDeallocReleaseRequirement(I) == ReleaseRequirement::MustRelease) {
215 if (!PropImplRequiringRelease)
216 PropImplRequiringRelease = I;
217 else {
218 HasOthers = true;
219 break;
220 }
221 }
222 }
223
224 if (!PropImplRequiringRelease)
225 return;
226
Devin Coughlinea02bba2016-02-25 19:13:43 +0000227 const ObjCMethodDecl *MD = nullptr;
228
229 // Scan the instance methods for "dealloc".
230 for (const auto *I : D->instance_methods()) {
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000231 if (I->getSelector() == DeallocSel) {
Devin Coughlinea02bba2016-02-25 19:13:43 +0000232 MD = I;
233 break;
234 }
235 }
236
237 if (!MD) { // No dealloc found.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000238 const char* Name = "Missing -dealloc";
Devin Coughlinea02bba2016-02-25 19:13:43 +0000239
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000240 std::string Buf;
241 llvm::raw_string_ostream OS(Buf);
Devin Coughlin6d0c8a02016-03-01 00:39:04 +0000242 OS << "'" << *D << "' lacks a 'dealloc' instance method but "
243 << "must release '" << *PropImplRequiringRelease->getPropertyIvarDecl()
244 << "'";
Devin Coughlinea02bba2016-02-25 19:13:43 +0000245
Devin Coughlin6d0c8a02016-03-01 00:39:04 +0000246 if (HasOthers)
247 OS << " and others";
Devin Coughlinea02bba2016-02-25 19:13:43 +0000248 PathDiagnosticLocation DLoc =
249 PathDiagnosticLocation::createBegin(D, BR.getSourceManager());
250
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000251 BR.EmitBasicReport(D, this, Name, categories::CoreFoundationObjectiveC,
252 OS.str(), DLoc);
Devin Coughlinea02bba2016-02-25 19:13:43 +0000253 return;
254 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000255}
Devin Coughlinea02bba2016-02-25 19:13:43 +0000256
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000257/// If this is the beginning of -dealloc, mark the values initially stored in
258/// instance variables that must be released by the end of -dealloc
259/// as unreleased in the state.
260void ObjCDeallocChecker::checkBeginFunction(
261 CheckerContext &C) const {
262 initIdentifierInfoAndSelectors(C.getASTContext());
Devin Coughlinea02bba2016-02-25 19:13:43 +0000263
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000264 // Only do this if the current method is -dealloc.
265 SVal SelfVal;
266 if (!isInInstanceDealloc(C, SelfVal))
267 return;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000268
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000269 SymbolRef SelfSymbol = SelfVal.getAsSymbol();
270
271 const LocationContext *LCtx = C.getLocationContext();
272 ProgramStateRef InitialState = C.getState();
273
274 ProgramStateRef State = InitialState;
275
276 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
277
278 // Symbols that must be released by the end of the -dealloc;
279 SymbolSet RequiredReleases = F.getEmptySet();
280
281 // If we're an inlined -dealloc, we should add our symbols to the existing
282 // set from our subclass.
283 if (const SymbolSet *CurrSet = State->get<UnreleasedIvarMap>(SelfSymbol))
284 RequiredReleases = *CurrSet;
285
286 for (auto *PropImpl : getContainingObjCImpl(LCtx)->property_impls()) {
287 ReleaseRequirement Requirement = getDeallocReleaseRequirement(PropImpl);
288 if (Requirement != ReleaseRequirement::MustRelease)
Devin Coughlinea02bba2016-02-25 19:13:43 +0000289 continue;
290
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000291 SVal LVal = State->getLValue(PropImpl->getPropertyIvarDecl(), SelfVal);
292 Optional<Loc> LValLoc = LVal.getAs<Loc>();
293 if (!LValLoc)
294 continue;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000295
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000296 SVal InitialVal = State->getSVal(LValLoc.getValue());
297 SymbolRef Symbol = InitialVal.getAsSymbol();
298 if (!Symbol || !isa<SymbolRegionValue>(Symbol))
299 continue;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000300
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000301 // Mark the value as requiring a release.
302 RequiredReleases = F.add(RequiredReleases, Symbol);
303 }
Devin Coughlinea02bba2016-02-25 19:13:43 +0000304
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000305 if (!RequiredReleases.isEmpty()) {
306 State = State->set<UnreleasedIvarMap>(SelfSymbol, RequiredReleases);
307 }
Devin Coughlinea02bba2016-02-25 19:13:43 +0000308
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000309 if (State != InitialState) {
310 C.addTransition(State);
311 }
312}
Devin Coughlinea02bba2016-02-25 19:13:43 +0000313
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000314/// Given a symbol for an ivar, return the ivar region it was loaded from.
315/// Returns nullptr if the instance symbol cannot be found.
316const ObjCIvarRegion *
317ObjCDeallocChecker::getIvarRegionForIvarSymbol(SymbolRef IvarSym) const {
318 const MemRegion *RegionLoadedFrom = nullptr;
319 if (auto *DerivedSym = dyn_cast<SymbolDerived>(IvarSym))
320 RegionLoadedFrom = DerivedSym->getRegion();
321 else if (auto *RegionSym = dyn_cast<SymbolRegionValue>(IvarSym))
322 RegionLoadedFrom = RegionSym->getRegion();
323 else
324 return nullptr;
325
326 return dyn_cast<ObjCIvarRegion>(RegionLoadedFrom);
327}
328
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000329/// Given a symbol for an ivar, return a symbol for the instance containing
330/// the ivar. Returns nullptr if the instance symbol cannot be found.
331SymbolRef
332ObjCDeallocChecker::getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const {
Devin Coughlinea02bba2016-02-25 19:13:43 +0000333
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000334 const ObjCIvarRegion *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
335 if (!IvarRegion)
336 return nullptr;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000337
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000338 return IvarRegion->getSymbolicBase()->getSymbol();
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000339}
340
341/// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
342/// a release or a nilling-out property setter.
343void ObjCDeallocChecker::checkPreObjCMessage(
344 const ObjCMethodCall &M, CheckerContext &C) const {
345 // Only run if -dealloc is on the stack.
346 SVal DeallocedInstance;
347 if (!instanceDeallocIsOnStack(C, DeallocedInstance))
348 return;
349
Devin Coughlina6046792016-03-04 18:09:58 +0000350 SymbolRef ReleasedValue = nullptr;
351
352 if (M.getSelector() == ReleaseSel) {
353 ReleasedValue = M.getReceiverSVal().getAsSymbol();
354 } else if (M.getSelector() == DeallocSel && !M.isReceiverSelfOrSuper()) {
355 if (diagnoseMistakenDealloc(M.getReceiverSVal().getAsSymbol(), M, C))
356 return;
357 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000358
359 if (ReleasedValue) {
360 // An instance variable symbol was released with -release:
361 // [_property release];
362 if (diagnoseExtraRelease(ReleasedValue,M, C))
363 return;
364 } else {
365 // An instance variable symbol was released nilling out its property:
366 // self.property = nil;
367 ReleasedValue = getValueReleasedByNillingOut(M, C);
368 }
369
370 if (!ReleasedValue)
371 return;
372
Devin Coughlin09359492016-02-29 23:57:10 +0000373 transitionToReleaseValue(C, ReleasedValue);
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000374}
375
Devin Coughlin09359492016-02-29 23:57:10 +0000376/// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
377/// call to Block_release().
378void ObjCDeallocChecker::checkPreCall(const CallEvent &Call,
379 CheckerContext &C) const {
380 const IdentifierInfo *II = Call.getCalleeIdentifier();
381 if (II != Block_releaseII)
382 return;
383
384 if (Call.getNumArgs() != 1)
385 return;
386
387 SymbolRef ReleasedValue = Call.getArgSVal(0).getAsSymbol();
388 if (!ReleasedValue)
389 return;
390
391 transitionToReleaseValue(C, ReleasedValue);
392}
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000393/// If the message was a call to '[super dealloc]', diagnose any missing
394/// releases.
395void ObjCDeallocChecker::checkPostObjCMessage(
396 const ObjCMethodCall &M, CheckerContext &C) const {
397 // We perform this check post-message so that if the super -dealloc
398 // calls a helper method and that this class overrides, any ivars released in
399 // the helper method will be recorded before checking.
400 if (isSuperDeallocMessage(M))
401 diagnoseMissingReleases(C);
402}
403
404/// Check for missing releases even when -dealloc does not call
405/// '[super dealloc]'.
406void ObjCDeallocChecker::checkEndFunction(
407 CheckerContext &C) const {
408 diagnoseMissingReleases(C);
409}
410
411/// Check for missing releases on early return.
412void ObjCDeallocChecker::checkPreStmt(
413 const ReturnStmt *RS, CheckerContext &C) const {
414 diagnoseMissingReleases(C);
415}
416
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000417/// When a symbol is assumed to be nil, remove it from the set of symbols
418/// require to be nil.
419ProgramStateRef ObjCDeallocChecker::evalAssume(ProgramStateRef State, SVal Cond,
420 bool Assumption) const {
421 if (State->get<UnreleasedIvarMap>().isEmpty())
422 return State;
423
424 auto *CondBSE = dyn_cast_or_null<BinarySymExpr>(Cond.getAsSymExpr());
425 if (!CondBSE)
426 return State;
427
428 BinaryOperator::Opcode OpCode = CondBSE->getOpcode();
429 if (Assumption) {
430 if (OpCode != BO_EQ)
431 return State;
432 } else {
433 if (OpCode != BO_NE)
434 return State;
435 }
436
437 SymbolRef NullSymbol = nullptr;
438 if (auto *SIE = dyn_cast<SymIntExpr>(CondBSE)) {
439 const llvm::APInt &RHS = SIE->getRHS();
440 if (RHS != 0)
441 return State;
442 NullSymbol = SIE->getLHS();
443 } else if (auto *SIE = dyn_cast<IntSymExpr>(CondBSE)) {
444 const llvm::APInt &LHS = SIE->getLHS();
445 if (LHS != 0)
446 return State;
447 NullSymbol = SIE->getRHS();
448 } else {
449 return State;
450 }
451
452 SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(NullSymbol);
453 if (!InstanceSymbol)
454 return State;
455
456 State = removeValueRequiringRelease(State, InstanceSymbol, NullSymbol);
457
458 return State;
459}
460
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000461/// If a symbol escapes conservatively assume unseen code released it.
462ProgramStateRef ObjCDeallocChecker::checkPointerEscape(
463 ProgramStateRef State, const InvalidatedSymbols &Escaped,
464 const CallEvent *Call, PointerEscapeKind Kind) const {
465
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000466 if (State->get<UnreleasedIvarMap>().isEmpty())
467 return State;
468
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000469 // Don't treat calls to '[super dealloc]' as escaping for the purposes
470 // of this checker. Because the checker diagnoses missing releases in the
471 // post-message handler for '[super dealloc], escaping here would cause
472 // the checker to never warn.
473 auto *OMC = dyn_cast_or_null<ObjCMethodCall>(Call);
474 if (OMC && isSuperDeallocMessage(*OMC))
475 return State;
476
477 for (const auto &Sym : Escaped) {
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000478 if (!Call || (Call && !Call->isInSystemHeader())) {
479 // If Sym is a symbol for an object with instance variables that
480 // must be released, remove these obligations when the object escapes
481 // unless via a call to a system function. System functions are
482 // very unlikely to release instance variables on objects passed to them,
483 // and are frequently called on 'self' in -dealloc (e.g., to remove
484 // observers) -- we want to avoid false negatives from escaping on
485 // them.
486 State = State->remove<UnreleasedIvarMap>(Sym);
487 }
488
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000489
490 SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(Sym);
491 if (!InstanceSymbol)
492 continue;
493
494 State = removeValueRequiringRelease(State, InstanceSymbol, Sym);
495 }
496
497 return State;
498}
499
500/// Report any unreleased instance variables for the current instance being
501/// dealloced.
502void ObjCDeallocChecker::diagnoseMissingReleases(CheckerContext &C) const {
503 ProgramStateRef State = C.getState();
504
505 SVal SelfVal;
506 if (!isInInstanceDealloc(C, SelfVal))
507 return;
508
509 const MemRegion *SelfRegion = SelfVal.castAs<loc::MemRegionVal>().getRegion();
510 const LocationContext *LCtx = C.getLocationContext();
511
512 ExplodedNode *ErrNode = nullptr;
513
514 SymbolRef SelfSym = SelfVal.getAsSymbol();
515 if (!SelfSym)
516 return;
517
518 const SymbolSet *OldUnreleased = State->get<UnreleasedIvarMap>(SelfSym);
519 if (!OldUnreleased)
520 return;
521
522 SymbolSet NewUnreleased = *OldUnreleased;
523 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
524
525 ProgramStateRef InitialState = State;
526
527 for (auto *IvarSymbol : *OldUnreleased) {
528 const TypedValueRegion *TVR =
529 cast<SymbolRegionValue>(IvarSymbol)->getRegion();
530 const ObjCIvarRegion *IvarRegion = cast<ObjCIvarRegion>(TVR);
531
532 // Don't warn if the ivar is not for this instance.
533 if (SelfRegion != IvarRegion->getSuperRegion())
534 continue;
535
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000536 const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000537 // Prevent an inlined call to -dealloc in a super class from warning
538 // about the values the subclass's -dealloc should release.
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000539 if (IvarDecl->getContainingInterface() !=
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000540 cast<ObjCMethodDecl>(LCtx->getDecl())->getClassInterface())
541 continue;
542
543 // Prevents diagnosing multiple times for the same instance variable
544 // at, for example, both a return and at the end of of the function.
545 NewUnreleased = F.remove(NewUnreleased, IvarSymbol);
546
547 if (State->getStateManager()
548 .getConstraintManager()
549 .isNull(State, IvarSymbol)
550 .isConstrainedTrue()) {
551 continue;
552 }
553
554 // A missing release manifests as a leak, so treat as a non-fatal error.
555 if (!ErrNode)
556 ErrNode = C.generateNonFatalErrorNode();
557 // If we've already reached this node on another path, return without
558 // diagnosing.
559 if (!ErrNode)
560 return;
561
562 std::string Buf;
563 llvm::raw_string_ostream OS(Buf);
564
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000565 const ObjCInterfaceDecl *Interface = IvarDecl->getContainingInterface();
566 // If the class is known to have a lifecycle with teardown that is
567 // separate from -dealloc, do not warn about missing releases. We
568 // suppress here (rather than not tracking for instance variables in
569 // such classes) because these classes are rare.
570 if (classHasSeparateTeardown(Interface))
571 return;
572
573 ObjCImplDecl *ImplDecl = Interface->getImplementation();
574
575 const ObjCPropertyImplDecl *PropImpl =
576 ImplDecl->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
577
578 const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
579
580 assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Copy ||
581 PropDecl->getSetterKind() == ObjCPropertyDecl::Retain);
582
583 OS << "The '" << *IvarDecl << "' ivar in '" << *ImplDecl
584 << "' was ";
585
586 if (PropDecl->getSetterKind() == ObjCPropertyDecl::Retain)
587 OS << "retained";
588 else
589 OS << "copied";
590
591 OS << " by a synthesized property but not released"
592 " before '[super dealloc]'";
593
594 std::unique_ptr<BugReport> BR(
595 new BugReport(*MissingReleaseBugType, OS.str(), ErrNode));
596
597 C.emitReport(std::move(BR));
598 }
599
600 if (NewUnreleased.isEmpty()) {
601 State = State->remove<UnreleasedIvarMap>(SelfSym);
602 } else {
603 State = State->set<UnreleasedIvarMap>(SelfSym, NewUnreleased);
604 }
605
606 if (ErrNode) {
607 C.addTransition(State, ErrNode);
608 } else if (State != InitialState) {
609 C.addTransition(State);
610 }
611
612 // Make sure that after checking in the top-most frame the list of
613 // tracked ivars is empty. This is intended to detect accidental leaks in
614 // the UnreleasedIvarMap program state.
615 assert(!LCtx->inTopFrame() || State->get<UnreleasedIvarMap>().isEmpty());
616}
617
Devin Coughlina6046792016-03-04 18:09:58 +0000618/// Given a symbol, determine whether the symbol refers to an ivar on
619/// the top-most deallocating instance. If so, find the property for that
620/// ivar, if one exists. Otherwise return null.
621const ObjCPropertyImplDecl *
622ObjCDeallocChecker::findPropertyOnDeallocatingInstance(
623 SymbolRef IvarSym, CheckerContext &C) const {
624 SVal DeallocedInstance;
625 if (!isInInstanceDealloc(C, DeallocedInstance))
626 return nullptr;
627
628 // Try to get the region from which the ivar value was loaded.
629 auto *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
630 if (!IvarRegion)
631 return nullptr;
632
633 // Don't try to find the property if the ivar was not loaded from the
634 // given instance.
635 if (DeallocedInstance.castAs<loc::MemRegionVal>().getRegion() !=
636 IvarRegion->getSuperRegion())
637 return nullptr;
638
639 const LocationContext *LCtx = C.getLocationContext();
640 const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
641
642 const ObjCImplDecl *Container = getContainingObjCImpl(LCtx);
643 const ObjCPropertyImplDecl *PropImpl =
644 Container->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
645 return PropImpl;
646}
647
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000648/// Emits a warning if the current context is -dealloc and ReleasedValue
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000649/// must not be directly released in a -dealloc. Returns true if a diagnostic
650/// was emitted.
651bool ObjCDeallocChecker::diagnoseExtraRelease(SymbolRef ReleasedValue,
652 const ObjCMethodCall &M,
653 CheckerContext &C) const {
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000654 // Try to get the region from which the the released value was loaded.
655 // Note that, unlike diagnosing for missing releases, here we don't track
656 // values that must not be released in the state. This is because even if
657 // these values escape, it is still an error under the rules of MRR to
658 // release them in -dealloc.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000659 const ObjCPropertyImplDecl *PropImpl =
Devin Coughlina6046792016-03-04 18:09:58 +0000660 findPropertyOnDeallocatingInstance(ReleasedValue, C);
661
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000662 if (!PropImpl)
663 return false;
664
Devin Coughlina6046792016-03-04 18:09:58 +0000665 // If the ivar belongs to a property that must not be released directly
666 // in dealloc, emit a warning.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000667 if (getDeallocReleaseRequirement(PropImpl) !=
668 ReleaseRequirement::MustNotReleaseDirectly) {
669 return false;
670 }
671
672 // If the property is readwrite but it shadows a read-only property in its
673 // external interface, treat the property a read-only. If the outside
674 // world cannot write to a property then the internal implementation is free
675 // to make its own convention about whether the value is stored retained
676 // or not. We look up the shadow here rather than in
677 // getDeallocReleaseRequirement() because doing so can be expensive.
678 const ObjCPropertyDecl *PropDecl = findShadowedPropertyDecl(PropImpl);
679 if (PropDecl) {
680 if (PropDecl->isReadOnly())
681 return false;
682 } else {
683 PropDecl = PropImpl->getPropertyDecl();
684 }
685
686 ExplodedNode *ErrNode = C.generateNonFatalErrorNode();
687 if (!ErrNode)
688 return false;
689
690 std::string Buf;
691 llvm::raw_string_ostream OS(Buf);
692
693 assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Weak ||
694 (PropDecl->getSetterKind() == ObjCPropertyDecl::Assign &&
Devin Coughlinb8076292016-03-25 21:18:22 +0000695 !PropDecl->isReadOnly()) ||
696 isReleasedByCIFilterDealloc(PropImpl)
697 );
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000698
Devin Coughlina6046792016-03-04 18:09:58 +0000699 const ObjCImplDecl *Container = getContainingObjCImpl(C.getLocationContext());
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000700 OS << "The '" << *PropImpl->getPropertyIvarDecl()
Devin Coughlinb8076292016-03-25 21:18:22 +0000701 << "' ivar in '" << *Container;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000702
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000703
Devin Coughlinb8076292016-03-25 21:18:22 +0000704 if (isReleasedByCIFilterDealloc(PropImpl)) {
705 OS << "' will be released by '-[CIFilter dealloc]' but also released here";
706 } else {
707 OS << "' was synthesized for ";
708
709 if (PropDecl->getSetterKind() == ObjCPropertyDecl::Weak)
710 OS << "a weak";
711 else
712 OS << "an assign, readwrite";
713
714 OS << " property but was released in 'dealloc'";
715 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000716
717 std::unique_ptr<BugReport> BR(
718 new BugReport(*ExtraReleaseBugType, OS.str(), ErrNode));
719 BR->addRange(M.getOriginExpr()->getSourceRange());
720
721 C.emitReport(std::move(BR));
722
723 return true;
724}
725
Devin Coughlina6046792016-03-04 18:09:58 +0000726/// Emits a warning if the current context is -dealloc and DeallocedValue
727/// must not be directly dealloced in a -dealloc. Returns true if a diagnostic
728/// was emitted.
729bool ObjCDeallocChecker::diagnoseMistakenDealloc(SymbolRef DeallocedValue,
730 const ObjCMethodCall &M,
731 CheckerContext &C) const {
732
733 // Find the property backing the instance variable that M
734 // is dealloc'ing.
735 const ObjCPropertyImplDecl *PropImpl =
736 findPropertyOnDeallocatingInstance(DeallocedValue, C);
737 if (!PropImpl)
738 return false;
739
740 if (getDeallocReleaseRequirement(PropImpl) !=
741 ReleaseRequirement::MustRelease) {
742 return false;
743 }
744
745 ExplodedNode *ErrNode = C.generateErrorNode();
746 if (!ErrNode)
747 return false;
748
749 std::string Buf;
750 llvm::raw_string_ostream OS(Buf);
751
752 OS << "'" << *PropImpl->getPropertyIvarDecl()
753 << "' should be released rather than deallocated";
754
755 std::unique_ptr<BugReport> BR(
756 new BugReport(*MistakenDeallocBugType, OS.str(), ErrNode));
757 BR->addRange(M.getOriginExpr()->getSourceRange());
758
759 C.emitReport(std::move(BR));
760
761 return true;
762}
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000763
Devin Coughlin9d5057c2016-06-22 17:03:10 +0000764ObjCDeallocChecker::ObjCDeallocChecker()
765 : NSObjectII(nullptr), SenTestCaseII(nullptr), XCTestCaseII(nullptr),
766 CIFilterII(nullptr) {
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000767
768 MissingReleaseBugType.reset(
769 new BugType(this, "Missing ivar release (leak)",
770 categories::MemoryCoreFoundationObjectiveC));
771
772 ExtraReleaseBugType.reset(
773 new BugType(this, "Extra ivar release",
774 categories::MemoryCoreFoundationObjectiveC));
Devin Coughlina6046792016-03-04 18:09:58 +0000775
776 MistakenDeallocBugType.reset(
777 new BugType(this, "Mistaken dealloc",
778 categories::MemoryCoreFoundationObjectiveC));
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000779}
780
781void ObjCDeallocChecker::initIdentifierInfoAndSelectors(
782 ASTContext &Ctx) const {
783 if (NSObjectII)
784 return;
785
786 NSObjectII = &Ctx.Idents.get("NSObject");
787 SenTestCaseII = &Ctx.Idents.get("SenTestCase");
Devin Coughlin9d5057c2016-06-22 17:03:10 +0000788 XCTestCaseII = &Ctx.Idents.get("XCTestCase");
Devin Coughlin09359492016-02-29 23:57:10 +0000789 Block_releaseII = &Ctx.Idents.get("_Block_release");
Devin Coughlinb8076292016-03-25 21:18:22 +0000790 CIFilterII = &Ctx.Idents.get("CIFilter");
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000791
792 IdentifierInfo *DeallocII = &Ctx.Idents.get("dealloc");
793 IdentifierInfo *ReleaseII = &Ctx.Idents.get("release");
794 DeallocSel = Ctx.Selectors.getSelector(0, &DeallocII);
795 ReleaseSel = Ctx.Selectors.getSelector(0, &ReleaseII);
796}
797
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000798/// Returns true if M is a call to '[super dealloc]'.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000799bool ObjCDeallocChecker::isSuperDeallocMessage(
800 const ObjCMethodCall &M) const {
801 if (M.getOriginExpr()->getReceiverKind() != ObjCMessageExpr::SuperInstance)
802 return false;
803
804 return M.getSelector() == DeallocSel;
805}
806
NAKAMURA Takumia8aa5f02016-02-26 03:15:13 +0000807/// Returns the ObjCImplDecl containing the method declaration in LCtx.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000808const ObjCImplDecl *
809ObjCDeallocChecker::getContainingObjCImpl(const LocationContext *LCtx) const {
810 auto *MD = cast<ObjCMethodDecl>(LCtx->getDecl());
811 return cast<ObjCImplDecl>(MD->getDeclContext());
812}
813
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000814/// Returns the property that shadowed by PropImpl if one exists and
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000815/// nullptr otherwise.
816const ObjCPropertyDecl *ObjCDeallocChecker::findShadowedPropertyDecl(
817 const ObjCPropertyImplDecl *PropImpl) const {
818 const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
819
820 // Only readwrite properties can shadow.
821 if (PropDecl->isReadOnly())
822 return nullptr;
823
824 auto *CatDecl = dyn_cast<ObjCCategoryDecl>(PropDecl->getDeclContext());
825
826 // Only class extensions can contain shadowing properties.
827 if (!CatDecl || !CatDecl->IsClassExtension())
828 return nullptr;
829
830 IdentifierInfo *ID = PropDecl->getIdentifier();
831 DeclContext::lookup_result R = CatDecl->getClassInterface()->lookup(ID);
832 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
833 auto *ShadowedPropDecl = dyn_cast<ObjCPropertyDecl>(*I);
834 if (!ShadowedPropDecl)
835 continue;
836
837 if (ShadowedPropDecl->isInstanceProperty()) {
838 assert(ShadowedPropDecl->isReadOnly());
839 return ShadowedPropDecl;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000840 }
841 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000842
843 return nullptr;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000844}
845
Devin Coughlin09359492016-02-29 23:57:10 +0000846/// Add a transition noting the release of the given value.
847void ObjCDeallocChecker::transitionToReleaseValue(CheckerContext &C,
848 SymbolRef Value) const {
849 assert(Value);
850 SymbolRef InstanceSym = getInstanceSymbolFromIvarSymbol(Value);
851 if (!InstanceSym)
852 return;
853 ProgramStateRef InitialState = C.getState();
854
855 ProgramStateRef ReleasedState =
856 removeValueRequiringRelease(InitialState, InstanceSym, Value);
857
858 if (ReleasedState != InitialState) {
859 C.addTransition(ReleasedState);
860 }
861}
862
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000863/// Remove the Value requiring a release from the tracked set for
864/// Instance and return the resultant state.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000865ProgramStateRef ObjCDeallocChecker::removeValueRequiringRelease(
866 ProgramStateRef State, SymbolRef Instance, SymbolRef Value) const {
867 assert(Instance);
868 assert(Value);
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000869 const ObjCIvarRegion *RemovedRegion = getIvarRegionForIvarSymbol(Value);
870 if (!RemovedRegion)
871 return State;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000872
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000873 const SymbolSet *Unreleased = State->get<UnreleasedIvarMap>(Instance);
874 if (!Unreleased)
875 return State;
876
877 // Mark the value as no longer requiring a release.
878 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000879 SymbolSet NewUnreleased = *Unreleased;
880 for (auto &Sym : *Unreleased) {
881 const ObjCIvarRegion *UnreleasedRegion = getIvarRegionForIvarSymbol(Sym);
882 assert(UnreleasedRegion);
883 if (RemovedRegion->getDecl() == UnreleasedRegion->getDecl()) {
884 NewUnreleased = F.remove(NewUnreleased, Sym);
885 }
886 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000887
888 if (NewUnreleased.isEmpty()) {
889 return State->remove<UnreleasedIvarMap>(Instance);
Devin Coughlinea02bba2016-02-25 19:13:43 +0000890 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000891
892 return State->set<UnreleasedIvarMap>(Instance, NewUnreleased);
Devin Coughlinea02bba2016-02-25 19:13:43 +0000893}
894
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000895/// Determines whether the instance variable for \p PropImpl must or must not be
896/// released in -dealloc or whether it cannot be determined.
897ReleaseRequirement ObjCDeallocChecker::getDeallocReleaseRequirement(
898 const ObjCPropertyImplDecl *PropImpl) const {
899 const ObjCIvarDecl *IvarDecl;
900 const ObjCPropertyDecl *PropDecl;
901 if (!isSynthesizedRetainableProperty(PropImpl, &IvarDecl, &PropDecl))
902 return ReleaseRequirement::Unknown;
903
904 ObjCPropertyDecl::SetterKind SK = PropDecl->getSetterKind();
905
906 switch (SK) {
907 // Retain and copy setters retain/copy their values before storing and so
908 // the value in their instance variables must be released in -dealloc.
909 case ObjCPropertyDecl::Retain:
910 case ObjCPropertyDecl::Copy:
Devin Coughlinb8076292016-03-25 21:18:22 +0000911 if (isReleasedByCIFilterDealloc(PropImpl))
912 return ReleaseRequirement::MustNotReleaseDirectly;
913
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000914 return ReleaseRequirement::MustRelease;
915
916 case ObjCPropertyDecl::Weak:
917 return ReleaseRequirement::MustNotReleaseDirectly;
918
919 case ObjCPropertyDecl::Assign:
920 // It is common for the ivars for read-only assign properties to
921 // always be stored retained, so their release requirement cannot be
922 // be determined.
923 if (PropDecl->isReadOnly())
924 return ReleaseRequirement::Unknown;
925
926 return ReleaseRequirement::MustNotReleaseDirectly;
927 }
928 llvm_unreachable("Unrecognized setter kind");
929}
930
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000931/// Returns the released value if M is a call a setter that releases
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000932/// and nils out its underlying instance variable.
933SymbolRef
934ObjCDeallocChecker::getValueReleasedByNillingOut(const ObjCMethodCall &M,
935 CheckerContext &C) const {
936 SVal ReceiverVal = M.getReceiverSVal();
937 if (!ReceiverVal.isValid())
938 return nullptr;
939
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000940 if (M.getNumArgs() == 0)
941 return nullptr;
Devin Coughlin578a20a2016-03-03 21:38:39 +0000942
943 if (!M.getArgExpr(0)->getType()->isObjCRetainableType())
944 return nullptr;
945
946 // Is the first argument nil?
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000947 SVal Arg = M.getArgSVal(0);
948 ProgramStateRef notNilState, nilState;
949 std::tie(notNilState, nilState) =
950 M.getState()->assume(Arg.castAs<DefinedOrUnknownSVal>());
951 if (!(nilState && !notNilState))
952 return nullptr;
953
954 const ObjCPropertyDecl *Prop = M.getAccessedProperty();
955 if (!Prop)
956 return nullptr;
957
958 ObjCIvarDecl *PropIvarDecl = Prop->getPropertyIvarDecl();
959 if (!PropIvarDecl)
960 return nullptr;
961
962 ProgramStateRef State = C.getState();
963
964 SVal LVal = State->getLValue(PropIvarDecl, ReceiverVal);
965 Optional<Loc> LValLoc = LVal.getAs<Loc>();
966 if (!LValLoc)
967 return nullptr;
968
969 SVal CurrentValInIvar = State->getSVal(LValLoc.getValue());
970 return CurrentValInIvar.getAsSymbol();
971}
972
973/// Returns true if the current context is a call to -dealloc and false
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000974/// otherwise. If true, it also sets SelfValOut to the value of
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000975/// 'self'.
976bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
977 SVal &SelfValOut) const {
978 return isInInstanceDealloc(C, C.getLocationContext(), SelfValOut);
979}
980
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000981/// Returns true if LCtx is a call to -dealloc and false
982/// otherwise. If true, it also sets SelfValOut to the value of
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000983/// 'self'.
984bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
985 const LocationContext *LCtx,
986 SVal &SelfValOut) const {
987 auto *MD = dyn_cast<ObjCMethodDecl>(LCtx->getDecl());
988 if (!MD || !MD->isInstanceMethod() || MD->getSelector() != DeallocSel)
989 return false;
990
991 const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
992 assert(SelfDecl && "No self in -dealloc?");
993
994 ProgramStateRef State = C.getState();
995 SelfValOut = State->getSVal(State->getRegion(SelfDecl, LCtx));
996 return true;
997}
998
999/// Returns true if there is a call to -dealloc anywhere on the stack and false
Devin Coughlinec6f61c2016-02-26 03:41:31 +00001000/// otherwise. If true, it also sets InstanceValOut to the value of
Devin Coughlinad9f53e2016-02-25 21:15:16 +00001001/// 'self' in the frame for -dealloc.
1002bool ObjCDeallocChecker::instanceDeallocIsOnStack(const CheckerContext &C,
1003 SVal &InstanceValOut) const {
1004 const LocationContext *LCtx = C.getLocationContext();
1005
1006 while (LCtx) {
1007 if (isInInstanceDealloc(C, LCtx, InstanceValOut))
1008 return true;
1009
1010 LCtx = LCtx->getParent();
1011 }
1012
1013 return false;
1014}
1015
Devin Coughlinec6f61c2016-02-26 03:41:31 +00001016/// Returns true if the ID is a class in which which is known to have
Devin Coughlinad9f53e2016-02-25 21:15:16 +00001017/// a separate teardown lifecycle. In this case, -dealloc warnings
1018/// about missing releases should be suppressed.
1019bool ObjCDeallocChecker::classHasSeparateTeardown(
1020 const ObjCInterfaceDecl *ID) const {
1021 // Suppress if the class is not a subclass of NSObject.
1022 for ( ; ID ; ID = ID->getSuperClass()) {
1023 IdentifierInfo *II = ID->getIdentifier();
1024
1025 if (II == NSObjectII)
1026 return false;
1027
Devin Coughlin9d5057c2016-06-22 17:03:10 +00001028 // FIXME: For now, ignore classes that subclass SenTestCase and XCTestCase,
1029 // as these don't need to implement -dealloc. They implement tear down in
1030 // another way, which we should try and catch later.
Devin Coughlinad9f53e2016-02-25 21:15:16 +00001031 // http://llvm.org/bugs/show_bug.cgi?id=3187
Devin Coughlin9d5057c2016-06-22 17:03:10 +00001032 if (II == XCTestCaseII || II == SenTestCaseII)
Devin Coughlinad9f53e2016-02-25 21:15:16 +00001033 return true;
1034 }
1035
1036 return true;
1037}
1038
Devin Coughlinb8076292016-03-25 21:18:22 +00001039/// The -dealloc method in CIFilter highly unusual in that is will release
1040/// instance variables belonging to its *subclasses* if the variable name
1041/// starts with "input" or backs a property whose name starts with "input".
1042/// Subclasses should not release these ivars in their own -dealloc method --
1043/// doing so could result in an over release.
1044///
1045/// This method returns true if the property will be released by
1046/// -[CIFilter dealloc].
1047bool ObjCDeallocChecker::isReleasedByCIFilterDealloc(
1048 const ObjCPropertyImplDecl *PropImpl) const {
1049 assert(PropImpl->getPropertyIvarDecl());
1050 StringRef PropName = PropImpl->getPropertyDecl()->getName();
1051 StringRef IvarName = PropImpl->getPropertyIvarDecl()->getName();
1052
1053 const char *ReleasePrefix = "input";
1054 if (!(PropName.startswith(ReleasePrefix) ||
1055 IvarName.startswith(ReleasePrefix))) {
1056 return false;
1057 }
1058
1059 const ObjCInterfaceDecl *ID =
1060 PropImpl->getPropertyIvarDecl()->getContainingInterface();
1061 for ( ; ID ; ID = ID->getSuperClass()) {
1062 IdentifierInfo *II = ID->getIdentifier();
1063 if (II == CIFilterII)
1064 return true;
1065 }
1066
1067 return false;
1068}
1069
Devin Coughlinad9f53e2016-02-25 21:15:16 +00001070void ento::registerObjCDeallocChecker(CheckerManager &Mgr) {
1071 const LangOptions &LangOpts = Mgr.getLangOpts();
1072 // These checker only makes sense under MRR.
1073 if (LangOpts.getGC() == LangOptions::GCOnly || LangOpts.ObjCAutoRefCount)
1074 return;
1075
1076 Mgr.registerChecker<ObjCDeallocChecker>();
Argyrios Kyrtzidisaf45aca2011-02-17 21:39:33 +00001077}