blob: bee9deadd07f71a098a0be862fafed5989e53673 [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 Coughlinb8076292016-03-25 21:18:22 +0000101 mutable IdentifierInfo *NSObjectII, *SenTestCaseII, *Block_releaseII,
102 *CIFilterII;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000103 mutable Selector DeallocSel, ReleaseSel;
104
105 std::unique_ptr<BugType> MissingReleaseBugType;
106 std::unique_ptr<BugType> ExtraReleaseBugType;
Devin Coughlina6046792016-03-04 18:09:58 +0000107 std::unique_ptr<BugType> MistakenDeallocBugType;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000108
109public:
110 ObjCDeallocChecker();
111
112 void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
113 BugReporter &BR) const;
114 void checkBeginFunction(CheckerContext &Ctx) const;
115 void checkPreObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
Devin Coughlin09359492016-02-29 23:57:10 +0000116 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000117 void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
118
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000119 ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
120 bool Assumption) const;
121
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000122 ProgramStateRef checkPointerEscape(ProgramStateRef State,
123 const InvalidatedSymbols &Escaped,
124 const CallEvent *Call,
125 PointerEscapeKind Kind) const;
126 void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
127 void checkEndFunction(CheckerContext &Ctx) const;
128
129private:
130 void diagnoseMissingReleases(CheckerContext &C) const;
131
132 bool diagnoseExtraRelease(SymbolRef ReleasedValue, const ObjCMethodCall &M,
133 CheckerContext &C) const;
134
Devin Coughlina6046792016-03-04 18:09:58 +0000135 bool diagnoseMistakenDealloc(SymbolRef DeallocedValue,
136 const ObjCMethodCall &M,
137 CheckerContext &C) const;
138
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000139 SymbolRef getValueReleasedByNillingOut(const ObjCMethodCall &M,
140 CheckerContext &C) const;
141
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000142 const ObjCIvarRegion *getIvarRegionForIvarSymbol(SymbolRef IvarSym) const;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000143 SymbolRef getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const;
144
Devin Coughlina6046792016-03-04 18:09:58 +0000145 const ObjCPropertyImplDecl*
146 findPropertyOnDeallocatingInstance(SymbolRef IvarSym,
147 CheckerContext &C) const;
148
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000149 ReleaseRequirement
150 getDeallocReleaseRequirement(const ObjCPropertyImplDecl *PropImpl) const;
151
152 bool isInInstanceDealloc(const CheckerContext &C, SVal &SelfValOut) const;
153 bool isInInstanceDealloc(const CheckerContext &C, const LocationContext *LCtx,
154 SVal &SelfValOut) const;
155 bool instanceDeallocIsOnStack(const CheckerContext &C,
156 SVal &InstanceValOut) const;
157
158 bool isSuperDeallocMessage(const ObjCMethodCall &M) const;
159
160 const ObjCImplDecl *getContainingObjCImpl(const LocationContext *LCtx) const;
161
162 const ObjCPropertyDecl *
163 findShadowedPropertyDecl(const ObjCPropertyImplDecl *PropImpl) const;
164
Devin Coughlin09359492016-02-29 23:57:10 +0000165 void transitionToReleaseValue(CheckerContext &C, SymbolRef Value) const;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000166 ProgramStateRef removeValueRequiringRelease(ProgramStateRef State,
167 SymbolRef InstanceSym,
168 SymbolRef ValueSym) const;
169
170 void initIdentifierInfoAndSelectors(ASTContext &Ctx) const;
171
172 bool classHasSeparateTeardown(const ObjCInterfaceDecl *ID) const;
Devin Coughlinb8076292016-03-25 21:18:22 +0000173
174 bool isReleasedByCIFilterDealloc(const ObjCPropertyImplDecl *PropImpl) const;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000175};
176} // End anonymous namespace.
177
178typedef llvm::ImmutableSet<SymbolRef> SymbolSet;
179
180/// Maps from the symbol for a class instance to the set of
181/// symbols remaining that must be released in -dealloc.
182REGISTER_MAP_WITH_PROGRAMSTATE(UnreleasedIvarMap, SymbolRef, SymbolSet)
183
184namespace clang {
185namespace ento {
186template<> struct ProgramStateTrait<SymbolSet>
187: public ProgramStatePartialTrait<SymbolSet> {
188 static void *GDMIndex() { static int index = 0; return &index; }
189};
190}
Devin Coughlinea02bba2016-02-25 19:13:43 +0000191}
Devin Coughlin30751342016-01-27 01:41:58 +0000192
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000193/// An AST check that diagnose when the class requires a -dealloc method and
194/// is missing one.
195void ObjCDeallocChecker::checkASTDecl(const ObjCImplementationDecl *D,
196 AnalysisManager &Mgr,
197 BugReporter &BR) const {
198 assert(Mgr.getLangOpts().getGC() != LangOptions::GCOnly);
199 assert(!Mgr.getLangOpts().ObjCAutoRefCount);
200 initIdentifierInfoAndSelectors(Mgr.getASTContext());
Ted Kremenek0e7d2522008-07-03 04:29:21 +0000201
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000202 const ObjCInterfaceDecl *ID = D->getClassInterface();
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000203 // If the class is known to have a lifecycle with a separate teardown method
204 // then it may not require a -dealloc method.
205 if (classHasSeparateTeardown(ID))
Devin Coughlin88691c12016-02-25 18:55:24 +0000206 return;
207
Devin Coughlin6d0c8a02016-03-01 00:39:04 +0000208 // Does the class contain any synthesized properties that are retainable?
209 // If not, skip the check entirely.
210 const ObjCPropertyImplDecl *PropImplRequiringRelease = nullptr;
211 bool HasOthers = false;
212 for (const auto *I : D->property_impls()) {
213 if (getDeallocReleaseRequirement(I) == ReleaseRequirement::MustRelease) {
214 if (!PropImplRequiringRelease)
215 PropImplRequiringRelease = I;
216 else {
217 HasOthers = true;
218 break;
219 }
220 }
221 }
222
223 if (!PropImplRequiringRelease)
224 return;
225
Devin Coughlinea02bba2016-02-25 19:13:43 +0000226 const ObjCMethodDecl *MD = nullptr;
227
228 // Scan the instance methods for "dealloc".
229 for (const auto *I : D->instance_methods()) {
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000230 if (I->getSelector() == DeallocSel) {
Devin Coughlinea02bba2016-02-25 19:13:43 +0000231 MD = I;
232 break;
233 }
234 }
235
236 if (!MD) { // No dealloc found.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000237 const char* Name = "Missing -dealloc";
Devin Coughlinea02bba2016-02-25 19:13:43 +0000238
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000239 std::string Buf;
240 llvm::raw_string_ostream OS(Buf);
Devin Coughlin6d0c8a02016-03-01 00:39:04 +0000241 OS << "'" << *D << "' lacks a 'dealloc' instance method but "
242 << "must release '" << *PropImplRequiringRelease->getPropertyIvarDecl()
243 << "'";
Devin Coughlinea02bba2016-02-25 19:13:43 +0000244
Devin Coughlin6d0c8a02016-03-01 00:39:04 +0000245 if (HasOthers)
246 OS << " and others";
Devin Coughlinea02bba2016-02-25 19:13:43 +0000247 PathDiagnosticLocation DLoc =
248 PathDiagnosticLocation::createBegin(D, BR.getSourceManager());
249
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000250 BR.EmitBasicReport(D, this, Name, categories::CoreFoundationObjectiveC,
251 OS.str(), DLoc);
Devin Coughlinea02bba2016-02-25 19:13:43 +0000252 return;
253 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000254}
Devin Coughlinea02bba2016-02-25 19:13:43 +0000255
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000256/// If this is the beginning of -dealloc, mark the values initially stored in
257/// instance variables that must be released by the end of -dealloc
258/// as unreleased in the state.
259void ObjCDeallocChecker::checkBeginFunction(
260 CheckerContext &C) const {
261 initIdentifierInfoAndSelectors(C.getASTContext());
Devin Coughlinea02bba2016-02-25 19:13:43 +0000262
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000263 // Only do this if the current method is -dealloc.
264 SVal SelfVal;
265 if (!isInInstanceDealloc(C, SelfVal))
266 return;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000267
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000268 SymbolRef SelfSymbol = SelfVal.getAsSymbol();
269
270 const LocationContext *LCtx = C.getLocationContext();
271 ProgramStateRef InitialState = C.getState();
272
273 ProgramStateRef State = InitialState;
274
275 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
276
277 // Symbols that must be released by the end of the -dealloc;
278 SymbolSet RequiredReleases = F.getEmptySet();
279
280 // If we're an inlined -dealloc, we should add our symbols to the existing
281 // set from our subclass.
282 if (const SymbolSet *CurrSet = State->get<UnreleasedIvarMap>(SelfSymbol))
283 RequiredReleases = *CurrSet;
284
285 for (auto *PropImpl : getContainingObjCImpl(LCtx)->property_impls()) {
286 ReleaseRequirement Requirement = getDeallocReleaseRequirement(PropImpl);
287 if (Requirement != ReleaseRequirement::MustRelease)
Devin Coughlinea02bba2016-02-25 19:13:43 +0000288 continue;
289
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000290 SVal LVal = State->getLValue(PropImpl->getPropertyIvarDecl(), SelfVal);
291 Optional<Loc> LValLoc = LVal.getAs<Loc>();
292 if (!LValLoc)
293 continue;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000294
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000295 SVal InitialVal = State->getSVal(LValLoc.getValue());
296 SymbolRef Symbol = InitialVal.getAsSymbol();
297 if (!Symbol || !isa<SymbolRegionValue>(Symbol))
298 continue;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000299
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000300 // Mark the value as requiring a release.
301 RequiredReleases = F.add(RequiredReleases, Symbol);
302 }
Devin Coughlinea02bba2016-02-25 19:13:43 +0000303
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000304 if (!RequiredReleases.isEmpty()) {
305 State = State->set<UnreleasedIvarMap>(SelfSymbol, RequiredReleases);
306 }
Devin Coughlinea02bba2016-02-25 19:13:43 +0000307
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000308 if (State != InitialState) {
309 C.addTransition(State);
310 }
311}
Devin Coughlinea02bba2016-02-25 19:13:43 +0000312
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000313/// Given a symbol for an ivar, return the ivar region it was loaded from.
314/// Returns nullptr if the instance symbol cannot be found.
315const ObjCIvarRegion *
316ObjCDeallocChecker::getIvarRegionForIvarSymbol(SymbolRef IvarSym) const {
317 const MemRegion *RegionLoadedFrom = nullptr;
318 if (auto *DerivedSym = dyn_cast<SymbolDerived>(IvarSym))
319 RegionLoadedFrom = DerivedSym->getRegion();
320 else if (auto *RegionSym = dyn_cast<SymbolRegionValue>(IvarSym))
321 RegionLoadedFrom = RegionSym->getRegion();
322 else
323 return nullptr;
324
325 return dyn_cast<ObjCIvarRegion>(RegionLoadedFrom);
326}
327
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000328/// Given a symbol for an ivar, return a symbol for the instance containing
329/// the ivar. Returns nullptr if the instance symbol cannot be found.
330SymbolRef
331ObjCDeallocChecker::getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const {
Devin Coughlinea02bba2016-02-25 19:13:43 +0000332
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000333 const ObjCIvarRegion *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
334 if (!IvarRegion)
335 return nullptr;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000336
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000337 return IvarRegion->getSymbolicBase()->getSymbol();
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000338}
339
340/// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
341/// a release or a nilling-out property setter.
342void ObjCDeallocChecker::checkPreObjCMessage(
343 const ObjCMethodCall &M, CheckerContext &C) const {
344 // Only run if -dealloc is on the stack.
345 SVal DeallocedInstance;
346 if (!instanceDeallocIsOnStack(C, DeallocedInstance))
347 return;
348
Devin Coughlina6046792016-03-04 18:09:58 +0000349 SymbolRef ReleasedValue = nullptr;
350
351 if (M.getSelector() == ReleaseSel) {
352 ReleasedValue = M.getReceiverSVal().getAsSymbol();
353 } else if (M.getSelector() == DeallocSel && !M.isReceiverSelfOrSuper()) {
354 if (diagnoseMistakenDealloc(M.getReceiverSVal().getAsSymbol(), M, C))
355 return;
356 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000357
358 if (ReleasedValue) {
359 // An instance variable symbol was released with -release:
360 // [_property release];
361 if (diagnoseExtraRelease(ReleasedValue,M, C))
362 return;
363 } else {
364 // An instance variable symbol was released nilling out its property:
365 // self.property = nil;
366 ReleasedValue = getValueReleasedByNillingOut(M, C);
367 }
368
369 if (!ReleasedValue)
370 return;
371
Devin Coughlin09359492016-02-29 23:57:10 +0000372 transitionToReleaseValue(C, ReleasedValue);
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000373}
374
Devin Coughlin09359492016-02-29 23:57:10 +0000375/// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
376/// call to Block_release().
377void ObjCDeallocChecker::checkPreCall(const CallEvent &Call,
378 CheckerContext &C) const {
379 const IdentifierInfo *II = Call.getCalleeIdentifier();
380 if (II != Block_releaseII)
381 return;
382
383 if (Call.getNumArgs() != 1)
384 return;
385
386 SymbolRef ReleasedValue = Call.getArgSVal(0).getAsSymbol();
387 if (!ReleasedValue)
388 return;
389
390 transitionToReleaseValue(C, ReleasedValue);
391}
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000392/// If the message was a call to '[super dealloc]', diagnose any missing
393/// releases.
394void ObjCDeallocChecker::checkPostObjCMessage(
395 const ObjCMethodCall &M, CheckerContext &C) const {
396 // We perform this check post-message so that if the super -dealloc
397 // calls a helper method and that this class overrides, any ivars released in
398 // the helper method will be recorded before checking.
399 if (isSuperDeallocMessage(M))
400 diagnoseMissingReleases(C);
401}
402
403/// Check for missing releases even when -dealloc does not call
404/// '[super dealloc]'.
405void ObjCDeallocChecker::checkEndFunction(
406 CheckerContext &C) const {
407 diagnoseMissingReleases(C);
408}
409
410/// Check for missing releases on early return.
411void ObjCDeallocChecker::checkPreStmt(
412 const ReturnStmt *RS, CheckerContext &C) const {
413 diagnoseMissingReleases(C);
414}
415
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000416/// When a symbol is assumed to be nil, remove it from the set of symbols
417/// require to be nil.
418ProgramStateRef ObjCDeallocChecker::evalAssume(ProgramStateRef State, SVal Cond,
419 bool Assumption) const {
420 if (State->get<UnreleasedIvarMap>().isEmpty())
421 return State;
422
423 auto *CondBSE = dyn_cast_or_null<BinarySymExpr>(Cond.getAsSymExpr());
424 if (!CondBSE)
425 return State;
426
427 BinaryOperator::Opcode OpCode = CondBSE->getOpcode();
428 if (Assumption) {
429 if (OpCode != BO_EQ)
430 return State;
431 } else {
432 if (OpCode != BO_NE)
433 return State;
434 }
435
436 SymbolRef NullSymbol = nullptr;
437 if (auto *SIE = dyn_cast<SymIntExpr>(CondBSE)) {
438 const llvm::APInt &RHS = SIE->getRHS();
439 if (RHS != 0)
440 return State;
441 NullSymbol = SIE->getLHS();
442 } else if (auto *SIE = dyn_cast<IntSymExpr>(CondBSE)) {
443 const llvm::APInt &LHS = SIE->getLHS();
444 if (LHS != 0)
445 return State;
446 NullSymbol = SIE->getRHS();
447 } else {
448 return State;
449 }
450
451 SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(NullSymbol);
452 if (!InstanceSymbol)
453 return State;
454
455 State = removeValueRequiringRelease(State, InstanceSymbol, NullSymbol);
456
457 return State;
458}
459
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000460/// If a symbol escapes conservatively assume unseen code released it.
461ProgramStateRef ObjCDeallocChecker::checkPointerEscape(
462 ProgramStateRef State, const InvalidatedSymbols &Escaped,
463 const CallEvent *Call, PointerEscapeKind Kind) const {
464
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000465 if (State->get<UnreleasedIvarMap>().isEmpty())
466 return State;
467
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000468 // Don't treat calls to '[super dealloc]' as escaping for the purposes
469 // of this checker. Because the checker diagnoses missing releases in the
470 // post-message handler for '[super dealloc], escaping here would cause
471 // the checker to never warn.
472 auto *OMC = dyn_cast_or_null<ObjCMethodCall>(Call);
473 if (OMC && isSuperDeallocMessage(*OMC))
474 return State;
475
476 for (const auto &Sym : Escaped) {
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000477 if (!Call || (Call && !Call->isInSystemHeader())) {
478 // If Sym is a symbol for an object with instance variables that
479 // must be released, remove these obligations when the object escapes
480 // unless via a call to a system function. System functions are
481 // very unlikely to release instance variables on objects passed to them,
482 // and are frequently called on 'self' in -dealloc (e.g., to remove
483 // observers) -- we want to avoid false negatives from escaping on
484 // them.
485 State = State->remove<UnreleasedIvarMap>(Sym);
486 }
487
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000488
489 SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(Sym);
490 if (!InstanceSymbol)
491 continue;
492
493 State = removeValueRequiringRelease(State, InstanceSymbol, Sym);
494 }
495
496 return State;
497}
498
499/// Report any unreleased instance variables for the current instance being
500/// dealloced.
501void ObjCDeallocChecker::diagnoseMissingReleases(CheckerContext &C) const {
502 ProgramStateRef State = C.getState();
503
504 SVal SelfVal;
505 if (!isInInstanceDealloc(C, SelfVal))
506 return;
507
508 const MemRegion *SelfRegion = SelfVal.castAs<loc::MemRegionVal>().getRegion();
509 const LocationContext *LCtx = C.getLocationContext();
510
511 ExplodedNode *ErrNode = nullptr;
512
513 SymbolRef SelfSym = SelfVal.getAsSymbol();
514 if (!SelfSym)
515 return;
516
517 const SymbolSet *OldUnreleased = State->get<UnreleasedIvarMap>(SelfSym);
518 if (!OldUnreleased)
519 return;
520
521 SymbolSet NewUnreleased = *OldUnreleased;
522 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
523
524 ProgramStateRef InitialState = State;
525
526 for (auto *IvarSymbol : *OldUnreleased) {
527 const TypedValueRegion *TVR =
528 cast<SymbolRegionValue>(IvarSymbol)->getRegion();
529 const ObjCIvarRegion *IvarRegion = cast<ObjCIvarRegion>(TVR);
530
531 // Don't warn if the ivar is not for this instance.
532 if (SelfRegion != IvarRegion->getSuperRegion())
533 continue;
534
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000535 const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000536 // Prevent an inlined call to -dealloc in a super class from warning
537 // about the values the subclass's -dealloc should release.
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000538 if (IvarDecl->getContainingInterface() !=
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000539 cast<ObjCMethodDecl>(LCtx->getDecl())->getClassInterface())
540 continue;
541
542 // Prevents diagnosing multiple times for the same instance variable
543 // at, for example, both a return and at the end of of the function.
544 NewUnreleased = F.remove(NewUnreleased, IvarSymbol);
545
546 if (State->getStateManager()
547 .getConstraintManager()
548 .isNull(State, IvarSymbol)
549 .isConstrainedTrue()) {
550 continue;
551 }
552
553 // A missing release manifests as a leak, so treat as a non-fatal error.
554 if (!ErrNode)
555 ErrNode = C.generateNonFatalErrorNode();
556 // If we've already reached this node on another path, return without
557 // diagnosing.
558 if (!ErrNode)
559 return;
560
561 std::string Buf;
562 llvm::raw_string_ostream OS(Buf);
563
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000564 const ObjCInterfaceDecl *Interface = IvarDecl->getContainingInterface();
565 // If the class is known to have a lifecycle with teardown that is
566 // separate from -dealloc, do not warn about missing releases. We
567 // suppress here (rather than not tracking for instance variables in
568 // such classes) because these classes are rare.
569 if (classHasSeparateTeardown(Interface))
570 return;
571
572 ObjCImplDecl *ImplDecl = Interface->getImplementation();
573
574 const ObjCPropertyImplDecl *PropImpl =
575 ImplDecl->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
576
577 const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
578
579 assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Copy ||
580 PropDecl->getSetterKind() == ObjCPropertyDecl::Retain);
581
582 OS << "The '" << *IvarDecl << "' ivar in '" << *ImplDecl
583 << "' was ";
584
585 if (PropDecl->getSetterKind() == ObjCPropertyDecl::Retain)
586 OS << "retained";
587 else
588 OS << "copied";
589
590 OS << " by a synthesized property but not released"
591 " before '[super dealloc]'";
592
593 std::unique_ptr<BugReport> BR(
594 new BugReport(*MissingReleaseBugType, OS.str(), ErrNode));
595
596 C.emitReport(std::move(BR));
597 }
598
599 if (NewUnreleased.isEmpty()) {
600 State = State->remove<UnreleasedIvarMap>(SelfSym);
601 } else {
602 State = State->set<UnreleasedIvarMap>(SelfSym, NewUnreleased);
603 }
604
605 if (ErrNode) {
606 C.addTransition(State, ErrNode);
607 } else if (State != InitialState) {
608 C.addTransition(State);
609 }
610
611 // Make sure that after checking in the top-most frame the list of
612 // tracked ivars is empty. This is intended to detect accidental leaks in
613 // the UnreleasedIvarMap program state.
614 assert(!LCtx->inTopFrame() || State->get<UnreleasedIvarMap>().isEmpty());
615}
616
Devin Coughlina6046792016-03-04 18:09:58 +0000617/// Given a symbol, determine whether the symbol refers to an ivar on
618/// the top-most deallocating instance. If so, find the property for that
619/// ivar, if one exists. Otherwise return null.
620const ObjCPropertyImplDecl *
621ObjCDeallocChecker::findPropertyOnDeallocatingInstance(
622 SymbolRef IvarSym, CheckerContext &C) const {
623 SVal DeallocedInstance;
624 if (!isInInstanceDealloc(C, DeallocedInstance))
625 return nullptr;
626
627 // Try to get the region from which the ivar value was loaded.
628 auto *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
629 if (!IvarRegion)
630 return nullptr;
631
632 // Don't try to find the property if the ivar was not loaded from the
633 // given instance.
634 if (DeallocedInstance.castAs<loc::MemRegionVal>().getRegion() !=
635 IvarRegion->getSuperRegion())
636 return nullptr;
637
638 const LocationContext *LCtx = C.getLocationContext();
639 const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
640
641 const ObjCImplDecl *Container = getContainingObjCImpl(LCtx);
642 const ObjCPropertyImplDecl *PropImpl =
643 Container->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
644 return PropImpl;
645}
646
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000647/// Emits a warning if the current context is -dealloc and ReleasedValue
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000648/// must not be directly released in a -dealloc. Returns true if a diagnostic
649/// was emitted.
650bool ObjCDeallocChecker::diagnoseExtraRelease(SymbolRef ReleasedValue,
651 const ObjCMethodCall &M,
652 CheckerContext &C) const {
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000653 // Try to get the region from which the the released value was loaded.
654 // Note that, unlike diagnosing for missing releases, here we don't track
655 // values that must not be released in the state. This is because even if
656 // these values escape, it is still an error under the rules of MRR to
657 // release them in -dealloc.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000658 const ObjCPropertyImplDecl *PropImpl =
Devin Coughlina6046792016-03-04 18:09:58 +0000659 findPropertyOnDeallocatingInstance(ReleasedValue, C);
660
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000661 if (!PropImpl)
662 return false;
663
Devin Coughlina6046792016-03-04 18:09:58 +0000664 // If the ivar belongs to a property that must not be released directly
665 // in dealloc, emit a warning.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000666 if (getDeallocReleaseRequirement(PropImpl) !=
667 ReleaseRequirement::MustNotReleaseDirectly) {
668 return false;
669 }
670
671 // If the property is readwrite but it shadows a read-only property in its
672 // external interface, treat the property a read-only. If the outside
673 // world cannot write to a property then the internal implementation is free
674 // to make its own convention about whether the value is stored retained
675 // or not. We look up the shadow here rather than in
676 // getDeallocReleaseRequirement() because doing so can be expensive.
677 const ObjCPropertyDecl *PropDecl = findShadowedPropertyDecl(PropImpl);
678 if (PropDecl) {
679 if (PropDecl->isReadOnly())
680 return false;
681 } else {
682 PropDecl = PropImpl->getPropertyDecl();
683 }
684
685 ExplodedNode *ErrNode = C.generateNonFatalErrorNode();
686 if (!ErrNode)
687 return false;
688
689 std::string Buf;
690 llvm::raw_string_ostream OS(Buf);
691
692 assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Weak ||
693 (PropDecl->getSetterKind() == ObjCPropertyDecl::Assign &&
Devin Coughlinb8076292016-03-25 21:18:22 +0000694 !PropDecl->isReadOnly()) ||
695 isReleasedByCIFilterDealloc(PropImpl)
696 );
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000697
Devin Coughlina6046792016-03-04 18:09:58 +0000698 const ObjCImplDecl *Container = getContainingObjCImpl(C.getLocationContext());
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000699 OS << "The '" << *PropImpl->getPropertyIvarDecl()
Devin Coughlinb8076292016-03-25 21:18:22 +0000700 << "' ivar in '" << *Container;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000701
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000702
Devin Coughlinb8076292016-03-25 21:18:22 +0000703 if (isReleasedByCIFilterDealloc(PropImpl)) {
704 OS << "' will be released by '-[CIFilter dealloc]' but also released here";
705 } else {
706 OS << "' was synthesized for ";
707
708 if (PropDecl->getSetterKind() == ObjCPropertyDecl::Weak)
709 OS << "a weak";
710 else
711 OS << "an assign, readwrite";
712
713 OS << " property but was released in 'dealloc'";
714 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000715
716 std::unique_ptr<BugReport> BR(
717 new BugReport(*ExtraReleaseBugType, OS.str(), ErrNode));
718 BR->addRange(M.getOriginExpr()->getSourceRange());
719
720 C.emitReport(std::move(BR));
721
722 return true;
723}
724
Devin Coughlina6046792016-03-04 18:09:58 +0000725/// Emits a warning if the current context is -dealloc and DeallocedValue
726/// must not be directly dealloced in a -dealloc. Returns true if a diagnostic
727/// was emitted.
728bool ObjCDeallocChecker::diagnoseMistakenDealloc(SymbolRef DeallocedValue,
729 const ObjCMethodCall &M,
730 CheckerContext &C) const {
731
732 // Find the property backing the instance variable that M
733 // is dealloc'ing.
734 const ObjCPropertyImplDecl *PropImpl =
735 findPropertyOnDeallocatingInstance(DeallocedValue, C);
736 if (!PropImpl)
737 return false;
738
739 if (getDeallocReleaseRequirement(PropImpl) !=
740 ReleaseRequirement::MustRelease) {
741 return false;
742 }
743
744 ExplodedNode *ErrNode = C.generateErrorNode();
745 if (!ErrNode)
746 return false;
747
748 std::string Buf;
749 llvm::raw_string_ostream OS(Buf);
750
751 OS << "'" << *PropImpl->getPropertyIvarDecl()
752 << "' should be released rather than deallocated";
753
754 std::unique_ptr<BugReport> BR(
755 new BugReport(*MistakenDeallocBugType, OS.str(), ErrNode));
756 BR->addRange(M.getOriginExpr()->getSourceRange());
757
758 C.emitReport(std::move(BR));
759
760 return true;
761}
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000762
763ObjCDeallocChecker::
764 ObjCDeallocChecker()
Devin Coughlinb8076292016-03-25 21:18:22 +0000765 : NSObjectII(nullptr), SenTestCaseII(nullptr), CIFilterII(nullptr) {
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000766
767 MissingReleaseBugType.reset(
768 new BugType(this, "Missing ivar release (leak)",
769 categories::MemoryCoreFoundationObjectiveC));
770
771 ExtraReleaseBugType.reset(
772 new BugType(this, "Extra ivar release",
773 categories::MemoryCoreFoundationObjectiveC));
Devin Coughlina6046792016-03-04 18:09:58 +0000774
775 MistakenDeallocBugType.reset(
776 new BugType(this, "Mistaken dealloc",
777 categories::MemoryCoreFoundationObjectiveC));
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000778}
779
780void ObjCDeallocChecker::initIdentifierInfoAndSelectors(
781 ASTContext &Ctx) const {
782 if (NSObjectII)
783 return;
784
785 NSObjectII = &Ctx.Idents.get("NSObject");
786 SenTestCaseII = &Ctx.Idents.get("SenTestCase");
Devin Coughlin09359492016-02-29 23:57:10 +0000787 Block_releaseII = &Ctx.Idents.get("_Block_release");
Devin Coughlinb8076292016-03-25 21:18:22 +0000788 CIFilterII = &Ctx.Idents.get("CIFilter");
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000789
790 IdentifierInfo *DeallocII = &Ctx.Idents.get("dealloc");
791 IdentifierInfo *ReleaseII = &Ctx.Idents.get("release");
792 DeallocSel = Ctx.Selectors.getSelector(0, &DeallocII);
793 ReleaseSel = Ctx.Selectors.getSelector(0, &ReleaseII);
794}
795
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000796/// Returns true if M is a call to '[super dealloc]'.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000797bool ObjCDeallocChecker::isSuperDeallocMessage(
798 const ObjCMethodCall &M) const {
799 if (M.getOriginExpr()->getReceiverKind() != ObjCMessageExpr::SuperInstance)
800 return false;
801
802 return M.getSelector() == DeallocSel;
803}
804
NAKAMURA Takumia8aa5f02016-02-26 03:15:13 +0000805/// Returns the ObjCImplDecl containing the method declaration in LCtx.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000806const ObjCImplDecl *
807ObjCDeallocChecker::getContainingObjCImpl(const LocationContext *LCtx) const {
808 auto *MD = cast<ObjCMethodDecl>(LCtx->getDecl());
809 return cast<ObjCImplDecl>(MD->getDeclContext());
810}
811
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000812/// Returns the property that shadowed by PropImpl if one exists and
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000813/// nullptr otherwise.
814const ObjCPropertyDecl *ObjCDeallocChecker::findShadowedPropertyDecl(
815 const ObjCPropertyImplDecl *PropImpl) const {
816 const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
817
818 // Only readwrite properties can shadow.
819 if (PropDecl->isReadOnly())
820 return nullptr;
821
822 auto *CatDecl = dyn_cast<ObjCCategoryDecl>(PropDecl->getDeclContext());
823
824 // Only class extensions can contain shadowing properties.
825 if (!CatDecl || !CatDecl->IsClassExtension())
826 return nullptr;
827
828 IdentifierInfo *ID = PropDecl->getIdentifier();
829 DeclContext::lookup_result R = CatDecl->getClassInterface()->lookup(ID);
830 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
831 auto *ShadowedPropDecl = dyn_cast<ObjCPropertyDecl>(*I);
832 if (!ShadowedPropDecl)
833 continue;
834
835 if (ShadowedPropDecl->isInstanceProperty()) {
836 assert(ShadowedPropDecl->isReadOnly());
837 return ShadowedPropDecl;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000838 }
839 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000840
841 return nullptr;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000842}
843
Devin Coughlin09359492016-02-29 23:57:10 +0000844/// Add a transition noting the release of the given value.
845void ObjCDeallocChecker::transitionToReleaseValue(CheckerContext &C,
846 SymbolRef Value) const {
847 assert(Value);
848 SymbolRef InstanceSym = getInstanceSymbolFromIvarSymbol(Value);
849 if (!InstanceSym)
850 return;
851 ProgramStateRef InitialState = C.getState();
852
853 ProgramStateRef ReleasedState =
854 removeValueRequiringRelease(InitialState, InstanceSym, Value);
855
856 if (ReleasedState != InitialState) {
857 C.addTransition(ReleasedState);
858 }
859}
860
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000861/// Remove the Value requiring a release from the tracked set for
862/// Instance and return the resultant state.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000863ProgramStateRef ObjCDeallocChecker::removeValueRequiringRelease(
864 ProgramStateRef State, SymbolRef Instance, SymbolRef Value) const {
865 assert(Instance);
866 assert(Value);
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000867 const ObjCIvarRegion *RemovedRegion = getIvarRegionForIvarSymbol(Value);
868 if (!RemovedRegion)
869 return State;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000870
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000871 const SymbolSet *Unreleased = State->get<UnreleasedIvarMap>(Instance);
872 if (!Unreleased)
873 return State;
874
875 // Mark the value as no longer requiring a release.
876 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000877 SymbolSet NewUnreleased = *Unreleased;
878 for (auto &Sym : *Unreleased) {
879 const ObjCIvarRegion *UnreleasedRegion = getIvarRegionForIvarSymbol(Sym);
880 assert(UnreleasedRegion);
881 if (RemovedRegion->getDecl() == UnreleasedRegion->getDecl()) {
882 NewUnreleased = F.remove(NewUnreleased, Sym);
883 }
884 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000885
886 if (NewUnreleased.isEmpty()) {
887 return State->remove<UnreleasedIvarMap>(Instance);
Devin Coughlinea02bba2016-02-25 19:13:43 +0000888 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000889
890 return State->set<UnreleasedIvarMap>(Instance, NewUnreleased);
Devin Coughlinea02bba2016-02-25 19:13:43 +0000891}
892
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000893/// Determines whether the instance variable for \p PropImpl must or must not be
894/// released in -dealloc or whether it cannot be determined.
895ReleaseRequirement ObjCDeallocChecker::getDeallocReleaseRequirement(
896 const ObjCPropertyImplDecl *PropImpl) const {
897 const ObjCIvarDecl *IvarDecl;
898 const ObjCPropertyDecl *PropDecl;
899 if (!isSynthesizedRetainableProperty(PropImpl, &IvarDecl, &PropDecl))
900 return ReleaseRequirement::Unknown;
901
902 ObjCPropertyDecl::SetterKind SK = PropDecl->getSetterKind();
903
904 switch (SK) {
905 // Retain and copy setters retain/copy their values before storing and so
906 // the value in their instance variables must be released in -dealloc.
907 case ObjCPropertyDecl::Retain:
908 case ObjCPropertyDecl::Copy:
Devin Coughlinb8076292016-03-25 21:18:22 +0000909 if (isReleasedByCIFilterDealloc(PropImpl))
910 return ReleaseRequirement::MustNotReleaseDirectly;
911
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000912 return ReleaseRequirement::MustRelease;
913
914 case ObjCPropertyDecl::Weak:
915 return ReleaseRequirement::MustNotReleaseDirectly;
916
917 case ObjCPropertyDecl::Assign:
918 // It is common for the ivars for read-only assign properties to
919 // always be stored retained, so their release requirement cannot be
920 // be determined.
921 if (PropDecl->isReadOnly())
922 return ReleaseRequirement::Unknown;
923
924 return ReleaseRequirement::MustNotReleaseDirectly;
925 }
926 llvm_unreachable("Unrecognized setter kind");
927}
928
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000929/// Returns the released value if M is a call a setter that releases
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000930/// and nils out its underlying instance variable.
931SymbolRef
932ObjCDeallocChecker::getValueReleasedByNillingOut(const ObjCMethodCall &M,
933 CheckerContext &C) const {
934 SVal ReceiverVal = M.getReceiverSVal();
935 if (!ReceiverVal.isValid())
936 return nullptr;
937
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000938 if (M.getNumArgs() == 0)
939 return nullptr;
Devin Coughlin578a20a2016-03-03 21:38:39 +0000940
941 if (!M.getArgExpr(0)->getType()->isObjCRetainableType())
942 return nullptr;
943
944 // Is the first argument nil?
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000945 SVal Arg = M.getArgSVal(0);
946 ProgramStateRef notNilState, nilState;
947 std::tie(notNilState, nilState) =
948 M.getState()->assume(Arg.castAs<DefinedOrUnknownSVal>());
949 if (!(nilState && !notNilState))
950 return nullptr;
951
952 const ObjCPropertyDecl *Prop = M.getAccessedProperty();
953 if (!Prop)
954 return nullptr;
955
956 ObjCIvarDecl *PropIvarDecl = Prop->getPropertyIvarDecl();
957 if (!PropIvarDecl)
958 return nullptr;
959
960 ProgramStateRef State = C.getState();
961
962 SVal LVal = State->getLValue(PropIvarDecl, ReceiverVal);
963 Optional<Loc> LValLoc = LVal.getAs<Loc>();
964 if (!LValLoc)
965 return nullptr;
966
967 SVal CurrentValInIvar = State->getSVal(LValLoc.getValue());
968 return CurrentValInIvar.getAsSymbol();
969}
970
971/// Returns true if the current context is a call to -dealloc and false
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000972/// otherwise. If true, it also sets SelfValOut to the value of
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000973/// 'self'.
974bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
975 SVal &SelfValOut) const {
976 return isInInstanceDealloc(C, C.getLocationContext(), SelfValOut);
977}
978
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000979/// Returns true if LCtx is a call to -dealloc and false
980/// otherwise. If true, it also sets SelfValOut to the value of
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000981/// 'self'.
982bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
983 const LocationContext *LCtx,
984 SVal &SelfValOut) const {
985 auto *MD = dyn_cast<ObjCMethodDecl>(LCtx->getDecl());
986 if (!MD || !MD->isInstanceMethod() || MD->getSelector() != DeallocSel)
987 return false;
988
989 const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
990 assert(SelfDecl && "No self in -dealloc?");
991
992 ProgramStateRef State = C.getState();
993 SelfValOut = State->getSVal(State->getRegion(SelfDecl, LCtx));
994 return true;
995}
996
997/// Returns true if there is a call to -dealloc anywhere on the stack and false
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000998/// otherwise. If true, it also sets InstanceValOut to the value of
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000999/// 'self' in the frame for -dealloc.
1000bool ObjCDeallocChecker::instanceDeallocIsOnStack(const CheckerContext &C,
1001 SVal &InstanceValOut) const {
1002 const LocationContext *LCtx = C.getLocationContext();
1003
1004 while (LCtx) {
1005 if (isInInstanceDealloc(C, LCtx, InstanceValOut))
1006 return true;
1007
1008 LCtx = LCtx->getParent();
1009 }
1010
1011 return false;
1012}
1013
Devin Coughlinec6f61c2016-02-26 03:41:31 +00001014/// Returns true if the ID is a class in which which is known to have
Devin Coughlinad9f53e2016-02-25 21:15:16 +00001015/// a separate teardown lifecycle. In this case, -dealloc warnings
1016/// about missing releases should be suppressed.
1017bool ObjCDeallocChecker::classHasSeparateTeardown(
1018 const ObjCInterfaceDecl *ID) const {
1019 // Suppress if the class is not a subclass of NSObject.
1020 for ( ; ID ; ID = ID->getSuperClass()) {
1021 IdentifierInfo *II = ID->getIdentifier();
1022
1023 if (II == NSObjectII)
1024 return false;
1025
1026 // FIXME: For now, ignore classes that subclass SenTestCase, as these don't
1027 // need to implement -dealloc. They implement tear down in another way,
1028 // which we should try and catch later.
1029 // http://llvm.org/bugs/show_bug.cgi?id=3187
1030 if (II == SenTestCaseII)
1031 return true;
1032 }
1033
1034 return true;
1035}
1036
Devin Coughlinb8076292016-03-25 21:18:22 +00001037/// The -dealloc method in CIFilter highly unusual in that is will release
1038/// instance variables belonging to its *subclasses* if the variable name
1039/// starts with "input" or backs a property whose name starts with "input".
1040/// Subclasses should not release these ivars in their own -dealloc method --
1041/// doing so could result in an over release.
1042///
1043/// This method returns true if the property will be released by
1044/// -[CIFilter dealloc].
1045bool ObjCDeallocChecker::isReleasedByCIFilterDealloc(
1046 const ObjCPropertyImplDecl *PropImpl) const {
1047 assert(PropImpl->getPropertyIvarDecl());
1048 StringRef PropName = PropImpl->getPropertyDecl()->getName();
1049 StringRef IvarName = PropImpl->getPropertyIvarDecl()->getName();
1050
1051 const char *ReleasePrefix = "input";
1052 if (!(PropName.startswith(ReleasePrefix) ||
1053 IvarName.startswith(ReleasePrefix))) {
1054 return false;
1055 }
1056
1057 const ObjCInterfaceDecl *ID =
1058 PropImpl->getPropertyIvarDecl()->getContainingInterface();
1059 for ( ; ID ; ID = ID->getSuperClass()) {
1060 IdentifierInfo *II = ID->getIdentifier();
1061 if (II == CIFilterII)
1062 return true;
1063 }
1064
1065 return false;
1066}
1067
Devin Coughlinad9f53e2016-02-25 21:15:16 +00001068void ento::registerObjCDeallocChecker(CheckerManager &Mgr) {
1069 const LangOptions &LangOpts = Mgr.getLangOpts();
1070 // These checker only makes sense under MRR.
1071 if (LangOpts.getGC() == LangOptions::GCOnly || LangOpts.ObjCAutoRefCount)
1072 return;
1073
1074 Mgr.registerChecker<ObjCDeallocChecker>();
Argyrios Kyrtzidisaf45aca2011-02-17 21:39:33 +00001075}