blob: bfd4019ed8d72310126f03585752364c5f03fe48 [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"
Devin Coughlin0bd37a12016-10-12 23:57:05 +000037#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
Devin Coughlinad9f53e2016-02-25 21:15:16 +000039#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
41#include "clang/StaticAnalyzer/Core/Checker.h"
42#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
Devin Coughlinad9f53e2016-02-25 21:15:16 +000043#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
44#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
45#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
46#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
47#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Ted Kremenek3f049492008-10-29 04:30:28 +000048#include "llvm/Support/raw_ostream.h"
Ted Kremenek0e7d2522008-07-03 04:29:21 +000049
50using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000051using namespace ento;
Ted Kremenek0e7d2522008-07-03 04:29:21 +000052
Devin Coughlinad9f53e2016-02-25 21:15:16 +000053/// Indicates whether an instance variable is required to be released in
54/// -dealloc.
55enum class ReleaseRequirement {
56 /// The instance variable must be released, either by calling
57 /// -release on it directly or by nilling it out with a property setter.
58 MustRelease,
Devin Coughlin982c42d2016-02-11 22:13:20 +000059
Devin Coughlinad9f53e2016-02-25 21:15:16 +000060 /// The instance variable must not be directly released with -release.
61 MustNotReleaseDirectly,
Mike Stump11289f42009-09-09 15:08:12 +000062
Devin Coughlinad9f53e2016-02-25 21:15:16 +000063 /// The requirement for the instance variable could not be determined.
64 Unknown
65};
Ted Kremenek3f049492008-10-29 04:30:28 +000066
Devin Coughlinad9f53e2016-02-25 21:15:16 +000067/// Returns true if the property implementation is synthesized and the
68/// type of the property is retainable.
Devin Coughlin30751342016-01-27 01:41:58 +000069static bool isSynthesizedRetainableProperty(const ObjCPropertyImplDecl *I,
70 const ObjCIvarDecl **ID,
71 const ObjCPropertyDecl **PD) {
72
73 if (I->getPropertyImplementation() != ObjCPropertyImplDecl::Synthesize)
74 return false;
75
76 (*ID) = I->getPropertyIvarDecl();
77 if (!(*ID))
78 return false;
79
80 QualType T = (*ID)->getType();
81 if (!T->isObjCRetainableType())
82 return false;
83
84 (*PD) = I->getPropertyDecl();
85 // Shouldn't be able to synthesize a property that doesn't exist.
86 assert(*PD);
87
88 return true;
89}
90
Devin Coughlinad9f53e2016-02-25 21:15:16 +000091namespace {
92
93class ObjCDeallocChecker
94 : public Checker<check::ASTDecl<ObjCImplementationDecl>,
95 check::PreObjCMessage, check::PostObjCMessage,
Devin Coughlin09359492016-02-29 23:57:10 +000096 check::PreCall,
Devin Coughlinad9f53e2016-02-25 21:15:16 +000097 check::BeginFunction, check::EndFunction,
Devin Coughlin3fc67e42016-02-29 21:44:08 +000098 eval::Assume,
Devin Coughlinad9f53e2016-02-25 21:15:16 +000099 check::PointerEscape,
100 check::PreStmt<ReturnStmt>> {
101
Devin Coughlin9d5057c2016-06-22 17:03:10 +0000102 mutable IdentifierInfo *NSObjectII, *SenTestCaseII, *XCTestCaseII,
103 *Block_releaseII, *CIFilterII;
104
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000105 mutable Selector DeallocSel, ReleaseSel;
106
107 std::unique_ptr<BugType> MissingReleaseBugType;
108 std::unique_ptr<BugType> ExtraReleaseBugType;
Devin Coughlina6046792016-03-04 18:09:58 +0000109 std::unique_ptr<BugType> MistakenDeallocBugType;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000110
111public:
112 ObjCDeallocChecker();
113
114 void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
115 BugReporter &BR) const;
116 void checkBeginFunction(CheckerContext &Ctx) const;
117 void checkPreObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
Devin Coughlin09359492016-02-29 23:57:10 +0000118 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000119 void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
120
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000121 ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
122 bool Assumption) const;
123
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000124 ProgramStateRef checkPointerEscape(ProgramStateRef State,
125 const InvalidatedSymbols &Escaped,
126 const CallEvent *Call,
127 PointerEscapeKind Kind) const;
128 void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
129 void checkEndFunction(CheckerContext &Ctx) const;
130
131private:
132 void diagnoseMissingReleases(CheckerContext &C) const;
133
134 bool diagnoseExtraRelease(SymbolRef ReleasedValue, const ObjCMethodCall &M,
135 CheckerContext &C) const;
136
Devin Coughlina6046792016-03-04 18:09:58 +0000137 bool diagnoseMistakenDealloc(SymbolRef DeallocedValue,
138 const ObjCMethodCall &M,
139 CheckerContext &C) const;
140
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000141 SymbolRef getValueReleasedByNillingOut(const ObjCMethodCall &M,
142 CheckerContext &C) const;
143
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000144 const ObjCIvarRegion *getIvarRegionForIvarSymbol(SymbolRef IvarSym) const;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000145 SymbolRef getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const;
146
Devin Coughlina6046792016-03-04 18:09:58 +0000147 const ObjCPropertyImplDecl*
148 findPropertyOnDeallocatingInstance(SymbolRef IvarSym,
149 CheckerContext &C) const;
150
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000151 ReleaseRequirement
152 getDeallocReleaseRequirement(const ObjCPropertyImplDecl *PropImpl) const;
153
154 bool isInInstanceDealloc(const CheckerContext &C, SVal &SelfValOut) const;
155 bool isInInstanceDealloc(const CheckerContext &C, const LocationContext *LCtx,
156 SVal &SelfValOut) const;
157 bool instanceDeallocIsOnStack(const CheckerContext &C,
158 SVal &InstanceValOut) const;
159
160 bool isSuperDeallocMessage(const ObjCMethodCall &M) const;
161
162 const ObjCImplDecl *getContainingObjCImpl(const LocationContext *LCtx) const;
163
164 const ObjCPropertyDecl *
165 findShadowedPropertyDecl(const ObjCPropertyImplDecl *PropImpl) const;
166
Devin Coughlin09359492016-02-29 23:57:10 +0000167 void transitionToReleaseValue(CheckerContext &C, SymbolRef Value) const;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000168 ProgramStateRef removeValueRequiringRelease(ProgramStateRef State,
169 SymbolRef InstanceSym,
170 SymbolRef ValueSym) const;
171
172 void initIdentifierInfoAndSelectors(ASTContext &Ctx) const;
173
174 bool classHasSeparateTeardown(const ObjCInterfaceDecl *ID) const;
Devin Coughlinb8076292016-03-25 21:18:22 +0000175
176 bool isReleasedByCIFilterDealloc(const ObjCPropertyImplDecl *PropImpl) const;
Devin Coughlin0bd37a12016-10-12 23:57:05 +0000177 bool isNibLoadedIvarWithoutRetain(const ObjCPropertyImplDecl *PropImpl) const;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000178};
179} // End anonymous namespace.
180
181typedef llvm::ImmutableSet<SymbolRef> SymbolSet;
182
183/// Maps from the symbol for a class instance to the set of
184/// symbols remaining that must be released in -dealloc.
185REGISTER_MAP_WITH_PROGRAMSTATE(UnreleasedIvarMap, SymbolRef, SymbolSet)
186
187namespace clang {
188namespace ento {
189template<> struct ProgramStateTrait<SymbolSet>
190: public ProgramStatePartialTrait<SymbolSet> {
191 static void *GDMIndex() { static int index = 0; return &index; }
192};
193}
Devin Coughlinea02bba2016-02-25 19:13:43 +0000194}
Devin Coughlin30751342016-01-27 01:41:58 +0000195
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000196/// An AST check that diagnose when the class requires a -dealloc method and
197/// is missing one.
198void ObjCDeallocChecker::checkASTDecl(const ObjCImplementationDecl *D,
199 AnalysisManager &Mgr,
200 BugReporter &BR) const {
201 assert(Mgr.getLangOpts().getGC() != LangOptions::GCOnly);
202 assert(!Mgr.getLangOpts().ObjCAutoRefCount);
203 initIdentifierInfoAndSelectors(Mgr.getASTContext());
Ted Kremenek0e7d2522008-07-03 04:29:21 +0000204
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000205 const ObjCInterfaceDecl *ID = D->getClassInterface();
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000206 // If the class is known to have a lifecycle with a separate teardown method
207 // then it may not require a -dealloc method.
208 if (classHasSeparateTeardown(ID))
Devin Coughlin88691c12016-02-25 18:55:24 +0000209 return;
210
Devin Coughlin6d0c8a02016-03-01 00:39:04 +0000211 // Does the class contain any synthesized properties that are retainable?
212 // If not, skip the check entirely.
213 const ObjCPropertyImplDecl *PropImplRequiringRelease = nullptr;
214 bool HasOthers = false;
215 for (const auto *I : D->property_impls()) {
216 if (getDeallocReleaseRequirement(I) == ReleaseRequirement::MustRelease) {
217 if (!PropImplRequiringRelease)
218 PropImplRequiringRelease = I;
219 else {
220 HasOthers = true;
221 break;
222 }
223 }
224 }
225
226 if (!PropImplRequiringRelease)
227 return;
228
Devin Coughlinea02bba2016-02-25 19:13:43 +0000229 const ObjCMethodDecl *MD = nullptr;
230
231 // Scan the instance methods for "dealloc".
232 for (const auto *I : D->instance_methods()) {
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000233 if (I->getSelector() == DeallocSel) {
Devin Coughlinea02bba2016-02-25 19:13:43 +0000234 MD = I;
235 break;
236 }
237 }
238
239 if (!MD) { // No dealloc found.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000240 const char* Name = "Missing -dealloc";
Devin Coughlinea02bba2016-02-25 19:13:43 +0000241
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000242 std::string Buf;
243 llvm::raw_string_ostream OS(Buf);
Devin Coughlin6d0c8a02016-03-01 00:39:04 +0000244 OS << "'" << *D << "' lacks a 'dealloc' instance method but "
245 << "must release '" << *PropImplRequiringRelease->getPropertyIvarDecl()
246 << "'";
Devin Coughlinea02bba2016-02-25 19:13:43 +0000247
Devin Coughlin6d0c8a02016-03-01 00:39:04 +0000248 if (HasOthers)
249 OS << " and others";
Devin Coughlinea02bba2016-02-25 19:13:43 +0000250 PathDiagnosticLocation DLoc =
251 PathDiagnosticLocation::createBegin(D, BR.getSourceManager());
252
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000253 BR.EmitBasicReport(D, this, Name, categories::CoreFoundationObjectiveC,
254 OS.str(), DLoc);
Devin Coughlinea02bba2016-02-25 19:13:43 +0000255 return;
256 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000257}
Devin Coughlinea02bba2016-02-25 19:13:43 +0000258
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000259/// If this is the beginning of -dealloc, mark the values initially stored in
260/// instance variables that must be released by the end of -dealloc
261/// as unreleased in the state.
262void ObjCDeallocChecker::checkBeginFunction(
263 CheckerContext &C) const {
264 initIdentifierInfoAndSelectors(C.getASTContext());
Devin Coughlinea02bba2016-02-25 19:13:43 +0000265
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000266 // Only do this if the current method is -dealloc.
267 SVal SelfVal;
268 if (!isInInstanceDealloc(C, SelfVal))
269 return;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000270
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000271 SymbolRef SelfSymbol = SelfVal.getAsSymbol();
272
273 const LocationContext *LCtx = C.getLocationContext();
274 ProgramStateRef InitialState = C.getState();
275
276 ProgramStateRef State = InitialState;
277
278 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
279
280 // Symbols that must be released by the end of the -dealloc;
281 SymbolSet RequiredReleases = F.getEmptySet();
282
283 // If we're an inlined -dealloc, we should add our symbols to the existing
284 // set from our subclass.
285 if (const SymbolSet *CurrSet = State->get<UnreleasedIvarMap>(SelfSymbol))
286 RequiredReleases = *CurrSet;
287
288 for (auto *PropImpl : getContainingObjCImpl(LCtx)->property_impls()) {
289 ReleaseRequirement Requirement = getDeallocReleaseRequirement(PropImpl);
290 if (Requirement != ReleaseRequirement::MustRelease)
Devin Coughlinea02bba2016-02-25 19:13:43 +0000291 continue;
292
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000293 SVal LVal = State->getLValue(PropImpl->getPropertyIvarDecl(), SelfVal);
294 Optional<Loc> LValLoc = LVal.getAs<Loc>();
295 if (!LValLoc)
296 continue;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000297
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000298 SVal InitialVal = State->getSVal(LValLoc.getValue());
299 SymbolRef Symbol = InitialVal.getAsSymbol();
300 if (!Symbol || !isa<SymbolRegionValue>(Symbol))
301 continue;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000302
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000303 // Mark the value as requiring a release.
304 RequiredReleases = F.add(RequiredReleases, Symbol);
305 }
Devin Coughlinea02bba2016-02-25 19:13:43 +0000306
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000307 if (!RequiredReleases.isEmpty()) {
308 State = State->set<UnreleasedIvarMap>(SelfSymbol, RequiredReleases);
309 }
Devin Coughlinea02bba2016-02-25 19:13:43 +0000310
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000311 if (State != InitialState) {
312 C.addTransition(State);
313 }
314}
Devin Coughlinea02bba2016-02-25 19:13:43 +0000315
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000316/// Given a symbol for an ivar, return the ivar region it was loaded from.
317/// Returns nullptr if the instance symbol cannot be found.
318const ObjCIvarRegion *
319ObjCDeallocChecker::getIvarRegionForIvarSymbol(SymbolRef IvarSym) const {
Artem Dergachev50aece02016-07-13 18:07:26 +0000320 return dyn_cast_or_null<ObjCIvarRegion>(IvarSym->getOriginRegion());
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000321}
322
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000323/// Given a symbol for an ivar, return a symbol for the instance containing
324/// the ivar. Returns nullptr if the instance symbol cannot be found.
325SymbolRef
326ObjCDeallocChecker::getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const {
Devin Coughlinea02bba2016-02-25 19:13:43 +0000327
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000328 const ObjCIvarRegion *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
329 if (!IvarRegion)
330 return nullptr;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000331
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000332 return IvarRegion->getSymbolicBase()->getSymbol();
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000333}
334
335/// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
336/// a release or a nilling-out property setter.
337void ObjCDeallocChecker::checkPreObjCMessage(
338 const ObjCMethodCall &M, CheckerContext &C) const {
339 // Only run if -dealloc is on the stack.
340 SVal DeallocedInstance;
341 if (!instanceDeallocIsOnStack(C, DeallocedInstance))
342 return;
343
Devin Coughlina6046792016-03-04 18:09:58 +0000344 SymbolRef ReleasedValue = nullptr;
345
346 if (M.getSelector() == ReleaseSel) {
347 ReleasedValue = M.getReceiverSVal().getAsSymbol();
348 } else if (M.getSelector() == DeallocSel && !M.isReceiverSelfOrSuper()) {
349 if (diagnoseMistakenDealloc(M.getReceiverSVal().getAsSymbol(), M, C))
350 return;
351 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000352
353 if (ReleasedValue) {
354 // An instance variable symbol was released with -release:
355 // [_property release];
356 if (diagnoseExtraRelease(ReleasedValue,M, C))
357 return;
358 } else {
359 // An instance variable symbol was released nilling out its property:
360 // self.property = nil;
361 ReleasedValue = getValueReleasedByNillingOut(M, C);
362 }
363
364 if (!ReleasedValue)
365 return;
366
Devin Coughlin09359492016-02-29 23:57:10 +0000367 transitionToReleaseValue(C, ReleasedValue);
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000368}
369
Devin Coughlin09359492016-02-29 23:57:10 +0000370/// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
371/// call to Block_release().
372void ObjCDeallocChecker::checkPreCall(const CallEvent &Call,
373 CheckerContext &C) const {
374 const IdentifierInfo *II = Call.getCalleeIdentifier();
375 if (II != Block_releaseII)
376 return;
377
378 if (Call.getNumArgs() != 1)
379 return;
380
381 SymbolRef ReleasedValue = Call.getArgSVal(0).getAsSymbol();
382 if (!ReleasedValue)
383 return;
384
385 transitionToReleaseValue(C, ReleasedValue);
386}
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000387/// If the message was a call to '[super dealloc]', diagnose any missing
388/// releases.
389void ObjCDeallocChecker::checkPostObjCMessage(
390 const ObjCMethodCall &M, CheckerContext &C) const {
391 // We perform this check post-message so that if the super -dealloc
392 // calls a helper method and that this class overrides, any ivars released in
393 // the helper method will be recorded before checking.
394 if (isSuperDeallocMessage(M))
395 diagnoseMissingReleases(C);
396}
397
398/// Check for missing releases even when -dealloc does not call
399/// '[super dealloc]'.
400void ObjCDeallocChecker::checkEndFunction(
401 CheckerContext &C) const {
402 diagnoseMissingReleases(C);
403}
404
405/// Check for missing releases on early return.
406void ObjCDeallocChecker::checkPreStmt(
407 const ReturnStmt *RS, CheckerContext &C) const {
408 diagnoseMissingReleases(C);
409}
410
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000411/// When a symbol is assumed to be nil, remove it from the set of symbols
412/// require to be nil.
413ProgramStateRef ObjCDeallocChecker::evalAssume(ProgramStateRef State, SVal Cond,
414 bool Assumption) const {
415 if (State->get<UnreleasedIvarMap>().isEmpty())
416 return State;
417
418 auto *CondBSE = dyn_cast_or_null<BinarySymExpr>(Cond.getAsSymExpr());
419 if (!CondBSE)
420 return State;
421
422 BinaryOperator::Opcode OpCode = CondBSE->getOpcode();
423 if (Assumption) {
424 if (OpCode != BO_EQ)
425 return State;
426 } else {
427 if (OpCode != BO_NE)
428 return State;
429 }
430
431 SymbolRef NullSymbol = nullptr;
432 if (auto *SIE = dyn_cast<SymIntExpr>(CondBSE)) {
433 const llvm::APInt &RHS = SIE->getRHS();
434 if (RHS != 0)
435 return State;
436 NullSymbol = SIE->getLHS();
437 } else if (auto *SIE = dyn_cast<IntSymExpr>(CondBSE)) {
438 const llvm::APInt &LHS = SIE->getLHS();
439 if (LHS != 0)
440 return State;
441 NullSymbol = SIE->getRHS();
442 } else {
443 return State;
444 }
445
446 SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(NullSymbol);
447 if (!InstanceSymbol)
448 return State;
449
450 State = removeValueRequiringRelease(State, InstanceSymbol, NullSymbol);
451
452 return State;
453}
454
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000455/// If a symbol escapes conservatively assume unseen code released it.
456ProgramStateRef ObjCDeallocChecker::checkPointerEscape(
457 ProgramStateRef State, const InvalidatedSymbols &Escaped,
458 const CallEvent *Call, PointerEscapeKind Kind) const {
459
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000460 if (State->get<UnreleasedIvarMap>().isEmpty())
461 return State;
462
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000463 // Don't treat calls to '[super dealloc]' as escaping for the purposes
464 // of this checker. Because the checker diagnoses missing releases in the
465 // post-message handler for '[super dealloc], escaping here would cause
466 // the checker to never warn.
467 auto *OMC = dyn_cast_or_null<ObjCMethodCall>(Call);
468 if (OMC && isSuperDeallocMessage(*OMC))
469 return State;
470
471 for (const auto &Sym : Escaped) {
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000472 if (!Call || (Call && !Call->isInSystemHeader())) {
473 // If Sym is a symbol for an object with instance variables that
474 // must be released, remove these obligations when the object escapes
475 // unless via a call to a system function. System functions are
476 // very unlikely to release instance variables on objects passed to them,
477 // and are frequently called on 'self' in -dealloc (e.g., to remove
478 // observers) -- we want to avoid false negatives from escaping on
479 // them.
480 State = State->remove<UnreleasedIvarMap>(Sym);
481 }
482
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000483
484 SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(Sym);
485 if (!InstanceSymbol)
486 continue;
487
488 State = removeValueRequiringRelease(State, InstanceSymbol, Sym);
489 }
490
491 return State;
492}
493
494/// Report any unreleased instance variables for the current instance being
495/// dealloced.
496void ObjCDeallocChecker::diagnoseMissingReleases(CheckerContext &C) const {
497 ProgramStateRef State = C.getState();
498
499 SVal SelfVal;
500 if (!isInInstanceDealloc(C, SelfVal))
501 return;
502
503 const MemRegion *SelfRegion = SelfVal.castAs<loc::MemRegionVal>().getRegion();
504 const LocationContext *LCtx = C.getLocationContext();
505
506 ExplodedNode *ErrNode = nullptr;
507
508 SymbolRef SelfSym = SelfVal.getAsSymbol();
509 if (!SelfSym)
510 return;
511
512 const SymbolSet *OldUnreleased = State->get<UnreleasedIvarMap>(SelfSym);
513 if (!OldUnreleased)
514 return;
515
516 SymbolSet NewUnreleased = *OldUnreleased;
517 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
518
519 ProgramStateRef InitialState = State;
520
521 for (auto *IvarSymbol : *OldUnreleased) {
522 const TypedValueRegion *TVR =
523 cast<SymbolRegionValue>(IvarSymbol)->getRegion();
524 const ObjCIvarRegion *IvarRegion = cast<ObjCIvarRegion>(TVR);
525
526 // Don't warn if the ivar is not for this instance.
527 if (SelfRegion != IvarRegion->getSuperRegion())
528 continue;
529
Devin Coughlin5ed2b4b2016-07-28 17:18:33 +0000530 const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000531 // Prevent an inlined call to -dealloc in a super class from warning
532 // about the values the subclass's -dealloc should release.
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000533 if (IvarDecl->getContainingInterface() !=
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000534 cast<ObjCMethodDecl>(LCtx->getDecl())->getClassInterface())
535 continue;
536
537 // Prevents diagnosing multiple times for the same instance variable
Hiroshi Inoueef04f642018-01-26 08:15:52 +0000538 // at, for example, both a return and at the end of the function.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000539 NewUnreleased = F.remove(NewUnreleased, IvarSymbol);
540
541 if (State->getStateManager()
542 .getConstraintManager()
543 .isNull(State, IvarSymbol)
544 .isConstrainedTrue()) {
545 continue;
546 }
547
548 // A missing release manifests as a leak, so treat as a non-fatal error.
549 if (!ErrNode)
550 ErrNode = C.generateNonFatalErrorNode();
551 // If we've already reached this node on another path, return without
552 // diagnosing.
553 if (!ErrNode)
554 return;
555
556 std::string Buf;
557 llvm::raw_string_ostream OS(Buf);
558
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000559 const ObjCInterfaceDecl *Interface = IvarDecl->getContainingInterface();
560 // If the class is known to have a lifecycle with teardown that is
561 // separate from -dealloc, do not warn about missing releases. We
562 // suppress here (rather than not tracking for instance variables in
563 // such classes) because these classes are rare.
564 if (classHasSeparateTeardown(Interface))
565 return;
566
567 ObjCImplDecl *ImplDecl = Interface->getImplementation();
568
569 const ObjCPropertyImplDecl *PropImpl =
570 ImplDecl->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
571
572 const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
573
574 assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Copy ||
575 PropDecl->getSetterKind() == ObjCPropertyDecl::Retain);
576
577 OS << "The '" << *IvarDecl << "' ivar in '" << *ImplDecl
578 << "' was ";
579
580 if (PropDecl->getSetterKind() == ObjCPropertyDecl::Retain)
581 OS << "retained";
582 else
583 OS << "copied";
584
585 OS << " by a synthesized property but not released"
586 " before '[super dealloc]'";
587
588 std::unique_ptr<BugReport> BR(
589 new BugReport(*MissingReleaseBugType, OS.str(), ErrNode));
590
591 C.emitReport(std::move(BR));
592 }
593
594 if (NewUnreleased.isEmpty()) {
595 State = State->remove<UnreleasedIvarMap>(SelfSym);
596 } else {
597 State = State->set<UnreleasedIvarMap>(SelfSym, NewUnreleased);
598 }
599
600 if (ErrNode) {
601 C.addTransition(State, ErrNode);
602 } else if (State != InitialState) {
603 C.addTransition(State);
604 }
605
606 // Make sure that after checking in the top-most frame the list of
607 // tracked ivars is empty. This is intended to detect accidental leaks in
608 // the UnreleasedIvarMap program state.
609 assert(!LCtx->inTopFrame() || State->get<UnreleasedIvarMap>().isEmpty());
610}
611
Devin Coughlina6046792016-03-04 18:09:58 +0000612/// Given a symbol, determine whether the symbol refers to an ivar on
613/// the top-most deallocating instance. If so, find the property for that
614/// ivar, if one exists. Otherwise return null.
615const ObjCPropertyImplDecl *
616ObjCDeallocChecker::findPropertyOnDeallocatingInstance(
617 SymbolRef IvarSym, CheckerContext &C) const {
618 SVal DeallocedInstance;
619 if (!isInInstanceDealloc(C, DeallocedInstance))
620 return nullptr;
621
622 // Try to get the region from which the ivar value was loaded.
623 auto *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
624 if (!IvarRegion)
625 return nullptr;
626
627 // Don't try to find the property if the ivar was not loaded from the
628 // given instance.
629 if (DeallocedInstance.castAs<loc::MemRegionVal>().getRegion() !=
630 IvarRegion->getSuperRegion())
631 return nullptr;
632
633 const LocationContext *LCtx = C.getLocationContext();
634 const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
635
636 const ObjCImplDecl *Container = getContainingObjCImpl(LCtx);
637 const ObjCPropertyImplDecl *PropImpl =
638 Container->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
639 return PropImpl;
640}
641
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000642/// Emits a warning if the current context is -dealloc and ReleasedValue
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000643/// must not be directly released in a -dealloc. Returns true if a diagnostic
644/// was emitted.
645bool ObjCDeallocChecker::diagnoseExtraRelease(SymbolRef ReleasedValue,
646 const ObjCMethodCall &M,
647 CheckerContext &C) const {
Hiroshi Inoue56939f72018-01-22 07:44:38 +0000648 // Try to get the region from which the released value was loaded.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000649 // Note that, unlike diagnosing for missing releases, here we don't track
650 // values that must not be released in the state. This is because even if
651 // these values escape, it is still an error under the rules of MRR to
652 // release them in -dealloc.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000653 const ObjCPropertyImplDecl *PropImpl =
Devin Coughlina6046792016-03-04 18:09:58 +0000654 findPropertyOnDeallocatingInstance(ReleasedValue, C);
655
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000656 if (!PropImpl)
657 return false;
658
Devin Coughlina6046792016-03-04 18:09:58 +0000659 // If the ivar belongs to a property that must not be released directly
660 // in dealloc, emit a warning.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000661 if (getDeallocReleaseRequirement(PropImpl) !=
662 ReleaseRequirement::MustNotReleaseDirectly) {
663 return false;
664 }
665
666 // If the property is readwrite but it shadows a read-only property in its
667 // external interface, treat the property a read-only. If the outside
668 // world cannot write to a property then the internal implementation is free
669 // to make its own convention about whether the value is stored retained
670 // or not. We look up the shadow here rather than in
671 // getDeallocReleaseRequirement() because doing so can be expensive.
672 const ObjCPropertyDecl *PropDecl = findShadowedPropertyDecl(PropImpl);
673 if (PropDecl) {
674 if (PropDecl->isReadOnly())
675 return false;
676 } else {
677 PropDecl = PropImpl->getPropertyDecl();
678 }
679
680 ExplodedNode *ErrNode = C.generateNonFatalErrorNode();
681 if (!ErrNode)
682 return false;
683
684 std::string Buf;
685 llvm::raw_string_ostream OS(Buf);
686
687 assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Weak ||
688 (PropDecl->getSetterKind() == ObjCPropertyDecl::Assign &&
Devin Coughlinb8076292016-03-25 21:18:22 +0000689 !PropDecl->isReadOnly()) ||
690 isReleasedByCIFilterDealloc(PropImpl)
691 );
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000692
Devin Coughlina6046792016-03-04 18:09:58 +0000693 const ObjCImplDecl *Container = getContainingObjCImpl(C.getLocationContext());
Devin Coughlin4fba10c2016-10-16 00:30:08 +0000694 OS << "The '" << *PropImpl->getPropertyIvarDecl()
695 << "' ivar in '" << *Container;
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000696
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000697
Devin Coughlin4fba10c2016-10-16 00:30:08 +0000698 if (isReleasedByCIFilterDealloc(PropImpl)) {
Devin Coughlinb8076292016-03-25 21:18:22 +0000699 OS << "' will be released by '-[CIFilter dealloc]' but also released here";
700 } else {
701 OS << "' was synthesized for ";
702
703 if (PropDecl->getSetterKind() == ObjCPropertyDecl::Weak)
704 OS << "a weak";
705 else
706 OS << "an assign, readwrite";
707
708 OS << " property but was released in 'dealloc'";
709 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000710
711 std::unique_ptr<BugReport> BR(
712 new BugReport(*ExtraReleaseBugType, OS.str(), ErrNode));
713 BR->addRange(M.getOriginExpr()->getSourceRange());
714
715 C.emitReport(std::move(BR));
716
717 return true;
718}
719
Devin Coughlina6046792016-03-04 18:09:58 +0000720/// Emits a warning if the current context is -dealloc and DeallocedValue
721/// must not be directly dealloced in a -dealloc. Returns true if a diagnostic
722/// was emitted.
723bool ObjCDeallocChecker::diagnoseMistakenDealloc(SymbolRef DeallocedValue,
724 const ObjCMethodCall &M,
725 CheckerContext &C) const {
726
727 // Find the property backing the instance variable that M
728 // is dealloc'ing.
729 const ObjCPropertyImplDecl *PropImpl =
730 findPropertyOnDeallocatingInstance(DeallocedValue, C);
731 if (!PropImpl)
732 return false;
733
734 if (getDeallocReleaseRequirement(PropImpl) !=
735 ReleaseRequirement::MustRelease) {
736 return false;
737 }
738
739 ExplodedNode *ErrNode = C.generateErrorNode();
740 if (!ErrNode)
741 return false;
742
743 std::string Buf;
744 llvm::raw_string_ostream OS(Buf);
745
746 OS << "'" << *PropImpl->getPropertyIvarDecl()
747 << "' should be released rather than deallocated";
748
749 std::unique_ptr<BugReport> BR(
750 new BugReport(*MistakenDeallocBugType, OS.str(), ErrNode));
751 BR->addRange(M.getOriginExpr()->getSourceRange());
752
753 C.emitReport(std::move(BR));
754
755 return true;
756}
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000757
Devin Coughlin9d5057c2016-06-22 17:03:10 +0000758ObjCDeallocChecker::ObjCDeallocChecker()
759 : NSObjectII(nullptr), SenTestCaseII(nullptr), XCTestCaseII(nullptr),
760 CIFilterII(nullptr) {
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000761
762 MissingReleaseBugType.reset(
763 new BugType(this, "Missing ivar release (leak)",
764 categories::MemoryCoreFoundationObjectiveC));
765
766 ExtraReleaseBugType.reset(
767 new BugType(this, "Extra ivar release",
768 categories::MemoryCoreFoundationObjectiveC));
Devin Coughlina6046792016-03-04 18:09:58 +0000769
770 MistakenDeallocBugType.reset(
771 new BugType(this, "Mistaken dealloc",
772 categories::MemoryCoreFoundationObjectiveC));
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000773}
774
775void ObjCDeallocChecker::initIdentifierInfoAndSelectors(
776 ASTContext &Ctx) const {
777 if (NSObjectII)
778 return;
779
780 NSObjectII = &Ctx.Idents.get("NSObject");
781 SenTestCaseII = &Ctx.Idents.get("SenTestCase");
Devin Coughlin9d5057c2016-06-22 17:03:10 +0000782 XCTestCaseII = &Ctx.Idents.get("XCTestCase");
Devin Coughlin09359492016-02-29 23:57:10 +0000783 Block_releaseII = &Ctx.Idents.get("_Block_release");
Devin Coughlinb8076292016-03-25 21:18:22 +0000784 CIFilterII = &Ctx.Idents.get("CIFilter");
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000785
786 IdentifierInfo *DeallocII = &Ctx.Idents.get("dealloc");
787 IdentifierInfo *ReleaseII = &Ctx.Idents.get("release");
788 DeallocSel = Ctx.Selectors.getSelector(0, &DeallocII);
789 ReleaseSel = Ctx.Selectors.getSelector(0, &ReleaseII);
790}
791
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000792/// Returns true if M is a call to '[super dealloc]'.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000793bool ObjCDeallocChecker::isSuperDeallocMessage(
794 const ObjCMethodCall &M) const {
795 if (M.getOriginExpr()->getReceiverKind() != ObjCMessageExpr::SuperInstance)
796 return false;
797
798 return M.getSelector() == DeallocSel;
799}
800
NAKAMURA Takumia8aa5f02016-02-26 03:15:13 +0000801/// Returns the ObjCImplDecl containing the method declaration in LCtx.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000802const ObjCImplDecl *
803ObjCDeallocChecker::getContainingObjCImpl(const LocationContext *LCtx) const {
804 auto *MD = cast<ObjCMethodDecl>(LCtx->getDecl());
805 return cast<ObjCImplDecl>(MD->getDeclContext());
806}
807
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000808/// Returns the property that shadowed by PropImpl if one exists and
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000809/// nullptr otherwise.
810const ObjCPropertyDecl *ObjCDeallocChecker::findShadowedPropertyDecl(
811 const ObjCPropertyImplDecl *PropImpl) const {
812 const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
813
814 // Only readwrite properties can shadow.
815 if (PropDecl->isReadOnly())
816 return nullptr;
817
818 auto *CatDecl = dyn_cast<ObjCCategoryDecl>(PropDecl->getDeclContext());
819
820 // Only class extensions can contain shadowing properties.
821 if (!CatDecl || !CatDecl->IsClassExtension())
822 return nullptr;
823
824 IdentifierInfo *ID = PropDecl->getIdentifier();
825 DeclContext::lookup_result R = CatDecl->getClassInterface()->lookup(ID);
826 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
827 auto *ShadowedPropDecl = dyn_cast<ObjCPropertyDecl>(*I);
828 if (!ShadowedPropDecl)
829 continue;
830
831 if (ShadowedPropDecl->isInstanceProperty()) {
832 assert(ShadowedPropDecl->isReadOnly());
833 return ShadowedPropDecl;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000834 }
835 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000836
837 return nullptr;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000838}
839
Devin Coughlin09359492016-02-29 23:57:10 +0000840/// Add a transition noting the release of the given value.
841void ObjCDeallocChecker::transitionToReleaseValue(CheckerContext &C,
842 SymbolRef Value) const {
843 assert(Value);
844 SymbolRef InstanceSym = getInstanceSymbolFromIvarSymbol(Value);
845 if (!InstanceSym)
846 return;
847 ProgramStateRef InitialState = C.getState();
848
849 ProgramStateRef ReleasedState =
850 removeValueRequiringRelease(InitialState, InstanceSym, Value);
851
852 if (ReleasedState != InitialState) {
853 C.addTransition(ReleasedState);
854 }
855}
856
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000857/// Remove the Value requiring a release from the tracked set for
858/// Instance and return the resultant state.
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000859ProgramStateRef ObjCDeallocChecker::removeValueRequiringRelease(
860 ProgramStateRef State, SymbolRef Instance, SymbolRef Value) const {
861 assert(Instance);
862 assert(Value);
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000863 const ObjCIvarRegion *RemovedRegion = getIvarRegionForIvarSymbol(Value);
864 if (!RemovedRegion)
865 return State;
Devin Coughlinea02bba2016-02-25 19:13:43 +0000866
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000867 const SymbolSet *Unreleased = State->get<UnreleasedIvarMap>(Instance);
868 if (!Unreleased)
869 return State;
870
871 // Mark the value as no longer requiring a release.
872 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
Devin Coughlin3fc67e42016-02-29 21:44:08 +0000873 SymbolSet NewUnreleased = *Unreleased;
874 for (auto &Sym : *Unreleased) {
875 const ObjCIvarRegion *UnreleasedRegion = getIvarRegionForIvarSymbol(Sym);
876 assert(UnreleasedRegion);
877 if (RemovedRegion->getDecl() == UnreleasedRegion->getDecl()) {
878 NewUnreleased = F.remove(NewUnreleased, Sym);
879 }
880 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000881
882 if (NewUnreleased.isEmpty()) {
883 return State->remove<UnreleasedIvarMap>(Instance);
Devin Coughlinea02bba2016-02-25 19:13:43 +0000884 }
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000885
886 return State->set<UnreleasedIvarMap>(Instance, NewUnreleased);
Devin Coughlinea02bba2016-02-25 19:13:43 +0000887}
888
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000889/// Determines whether the instance variable for \p PropImpl must or must not be
890/// released in -dealloc or whether it cannot be determined.
891ReleaseRequirement ObjCDeallocChecker::getDeallocReleaseRequirement(
892 const ObjCPropertyImplDecl *PropImpl) const {
893 const ObjCIvarDecl *IvarDecl;
894 const ObjCPropertyDecl *PropDecl;
895 if (!isSynthesizedRetainableProperty(PropImpl, &IvarDecl, &PropDecl))
896 return ReleaseRequirement::Unknown;
897
898 ObjCPropertyDecl::SetterKind SK = PropDecl->getSetterKind();
899
900 switch (SK) {
901 // Retain and copy setters retain/copy their values before storing and so
902 // the value in their instance variables must be released in -dealloc.
903 case ObjCPropertyDecl::Retain:
904 case ObjCPropertyDecl::Copy:
Devin Coughlinb8076292016-03-25 21:18:22 +0000905 if (isReleasedByCIFilterDealloc(PropImpl))
906 return ReleaseRequirement::MustNotReleaseDirectly;
907
Devin Coughlin0bd37a12016-10-12 23:57:05 +0000908 if (isNibLoadedIvarWithoutRetain(PropImpl))
909 return ReleaseRequirement::Unknown;
910
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000911 return ReleaseRequirement::MustRelease;
912
913 case ObjCPropertyDecl::Weak:
914 return ReleaseRequirement::MustNotReleaseDirectly;
915
916 case ObjCPropertyDecl::Assign:
917 // It is common for the ivars for read-only assign properties to
918 // always be stored retained, so their release requirement cannot be
919 // be determined.
920 if (PropDecl->isReadOnly())
921 return ReleaseRequirement::Unknown;
922
923 return ReleaseRequirement::MustNotReleaseDirectly;
924 }
925 llvm_unreachable("Unrecognized setter kind");
926}
927
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000928/// Returns the released value if M is a call a setter that releases
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000929/// and nils out its underlying instance variable.
930SymbolRef
931ObjCDeallocChecker::getValueReleasedByNillingOut(const ObjCMethodCall &M,
932 CheckerContext &C) const {
933 SVal ReceiverVal = M.getReceiverSVal();
934 if (!ReceiverVal.isValid())
935 return nullptr;
936
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000937 if (M.getNumArgs() == 0)
938 return nullptr;
Devin Coughlin578a20a2016-03-03 21:38:39 +0000939
940 if (!M.getArgExpr(0)->getType()->isObjCRetainableType())
941 return nullptr;
942
943 // Is the first argument nil?
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000944 SVal Arg = M.getArgSVal(0);
945 ProgramStateRef notNilState, nilState;
946 std::tie(notNilState, nilState) =
947 M.getState()->assume(Arg.castAs<DefinedOrUnknownSVal>());
948 if (!(nilState && !notNilState))
949 return nullptr;
950
951 const ObjCPropertyDecl *Prop = M.getAccessedProperty();
952 if (!Prop)
953 return nullptr;
954
955 ObjCIvarDecl *PropIvarDecl = Prop->getPropertyIvarDecl();
956 if (!PropIvarDecl)
957 return nullptr;
958
959 ProgramStateRef State = C.getState();
960
961 SVal LVal = State->getLValue(PropIvarDecl, ReceiverVal);
962 Optional<Loc> LValLoc = LVal.getAs<Loc>();
963 if (!LValLoc)
964 return nullptr;
965
966 SVal CurrentValInIvar = State->getSVal(LValLoc.getValue());
967 return CurrentValInIvar.getAsSymbol();
968}
969
970/// Returns true if the current context is a call to -dealloc and false
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000971/// otherwise. If true, it also sets SelfValOut to the value of
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000972/// 'self'.
973bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
974 SVal &SelfValOut) const {
975 return isInInstanceDealloc(C, C.getLocationContext(), SelfValOut);
976}
977
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000978/// Returns true if LCtx is a call to -dealloc and false
979/// otherwise. If true, it also sets SelfValOut to the value of
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000980/// 'self'.
981bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
982 const LocationContext *LCtx,
983 SVal &SelfValOut) const {
984 auto *MD = dyn_cast<ObjCMethodDecl>(LCtx->getDecl());
985 if (!MD || !MD->isInstanceMethod() || MD->getSelector() != DeallocSel)
986 return false;
987
988 const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
989 assert(SelfDecl && "No self in -dealloc?");
990
991 ProgramStateRef State = C.getState();
992 SelfValOut = State->getSVal(State->getRegion(SelfDecl, LCtx));
993 return true;
994}
995
996/// Returns true if there is a call to -dealloc anywhere on the stack and false
Devin Coughlinec6f61c2016-02-26 03:41:31 +0000997/// otherwise. If true, it also sets InstanceValOut to the value of
Devin Coughlinad9f53e2016-02-25 21:15:16 +0000998/// 'self' in the frame for -dealloc.
999bool ObjCDeallocChecker::instanceDeallocIsOnStack(const CheckerContext &C,
1000 SVal &InstanceValOut) const {
1001 const LocationContext *LCtx = C.getLocationContext();
1002
1003 while (LCtx) {
1004 if (isInInstanceDealloc(C, LCtx, InstanceValOut))
1005 return true;
1006
1007 LCtx = LCtx->getParent();
1008 }
1009
1010 return false;
1011}
1012
Devin Coughlinec6f61c2016-02-26 03:41:31 +00001013/// Returns true if the ID is a class in which which is known to have
Devin Coughlinad9f53e2016-02-25 21:15:16 +00001014/// a separate teardown lifecycle. In this case, -dealloc warnings
1015/// about missing releases should be suppressed.
1016bool ObjCDeallocChecker::classHasSeparateTeardown(
1017 const ObjCInterfaceDecl *ID) const {
1018 // Suppress if the class is not a subclass of NSObject.
1019 for ( ; ID ; ID = ID->getSuperClass()) {
1020 IdentifierInfo *II = ID->getIdentifier();
1021
1022 if (II == NSObjectII)
1023 return false;
1024
Devin Coughlin9d5057c2016-06-22 17:03:10 +00001025 // FIXME: For now, ignore classes that subclass SenTestCase and XCTestCase,
1026 // as these don't need to implement -dealloc. They implement tear down in
1027 // another way, which we should try and catch later.
Devin Coughlinad9f53e2016-02-25 21:15:16 +00001028 // http://llvm.org/bugs/show_bug.cgi?id=3187
Devin Coughlin9d5057c2016-06-22 17:03:10 +00001029 if (II == XCTestCaseII || II == SenTestCaseII)
Devin Coughlinad9f53e2016-02-25 21:15:16 +00001030 return true;
1031 }
1032
1033 return true;
1034}
1035
Devin Coughlinb8076292016-03-25 21:18:22 +00001036/// The -dealloc method in CIFilter highly unusual in that is will release
1037/// instance variables belonging to its *subclasses* if the variable name
1038/// starts with "input" or backs a property whose name starts with "input".
1039/// Subclasses should not release these ivars in their own -dealloc method --
1040/// doing so could result in an over release.
1041///
1042/// This method returns true if the property will be released by
1043/// -[CIFilter dealloc].
1044bool ObjCDeallocChecker::isReleasedByCIFilterDealloc(
1045 const ObjCPropertyImplDecl *PropImpl) const {
1046 assert(PropImpl->getPropertyIvarDecl());
1047 StringRef PropName = PropImpl->getPropertyDecl()->getName();
1048 StringRef IvarName = PropImpl->getPropertyIvarDecl()->getName();
1049
1050 const char *ReleasePrefix = "input";
1051 if (!(PropName.startswith(ReleasePrefix) ||
1052 IvarName.startswith(ReleasePrefix))) {
1053 return false;
1054 }
1055
1056 const ObjCInterfaceDecl *ID =
1057 PropImpl->getPropertyIvarDecl()->getContainingInterface();
1058 for ( ; ID ; ID = ID->getSuperClass()) {
1059 IdentifierInfo *II = ID->getIdentifier();
1060 if (II == CIFilterII)
1061 return true;
1062 }
1063
1064 return false;
1065}
1066
Devin Coughlin0bd37a12016-10-12 23:57:05 +00001067/// Returns whether the ivar backing the property is an IBOutlet that
1068/// has its value set by nib loading code without retaining the value.
1069///
1070/// On macOS, if there is no setter, the nib-loading code sets the ivar
1071/// directly, without retaining the value,
1072///
1073/// On iOS and its derivatives, the nib-loading code will call
1074/// -setValue:forKey:, which retains the value before directly setting the ivar.
1075bool ObjCDeallocChecker::isNibLoadedIvarWithoutRetain(
1076 const ObjCPropertyImplDecl *PropImpl) const {
1077 const ObjCIvarDecl *IvarDecl = PropImpl->getPropertyIvarDecl();
1078 if (!IvarDecl->hasAttr<IBOutletAttr>())
1079 return false;
1080
1081 const llvm::Triple &Target =
1082 IvarDecl->getASTContext().getTargetInfo().getTriple();
1083
1084 if (!Target.isMacOSX())
1085 return false;
1086
1087 if (PropImpl->getPropertyDecl()->getSetterMethodDecl())
1088 return false;
1089
1090 return true;
1091}
1092
Devin Coughlinad9f53e2016-02-25 21:15:16 +00001093void ento::registerObjCDeallocChecker(CheckerManager &Mgr) {
1094 const LangOptions &LangOpts = Mgr.getLangOpts();
1095 // These checker only makes sense under MRR.
1096 if (LangOpts.getGC() == LangOptions::GCOnly || LangOpts.ObjCAutoRefCount)
1097 return;
1098
1099 Mgr.registerChecker<ObjCDeallocChecker>();
Argyrios Kyrtzidisaf45aca2011-02-17 21:39:33 +00001100}