1*67e74705SXin Li //==- CheckObjCDealloc.cpp - Check ObjC -dealloc implementation --*- C++ -*-==//
2*67e74705SXin Li //
3*67e74705SXin Li // The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li // This checker analyzes Objective-C -dealloc methods and their callees
11*67e74705SXin Li // to warn about improper releasing of instance variables that back synthesized
12*67e74705SXin Li // properties. It warns about missing releases in the following cases:
13*67e74705SXin Li // - When a class has a synthesized instance variable for a 'retain' or 'copy'
14*67e74705SXin Li // property and lacks a -dealloc method in its implementation.
15*67e74705SXin Li // - When a class has a synthesized instance variable for a 'retain'/'copy'
16*67e74705SXin Li // property but the ivar is not released in -dealloc by either -release
17*67e74705SXin Li // or by nilling out the property.
18*67e74705SXin Li //
19*67e74705SXin Li // It warns about extra releases in -dealloc (but not in callees) when a
20*67e74705SXin Li // synthesized instance variable is released in the following cases:
21*67e74705SXin Li // - When the property is 'assign' and is not 'readonly'.
22*67e74705SXin Li // - When the property is 'weak'.
23*67e74705SXin Li //
24*67e74705SXin Li // This checker only warns for instance variables synthesized to back
25*67e74705SXin Li // properties. Handling the more general case would require inferring whether
26*67e74705SXin Li // an instance variable is stored retained or not. For synthesized properties,
27*67e74705SXin Li // this is specified in the property declaration itself.
28*67e74705SXin Li //
29*67e74705SXin Li //===----------------------------------------------------------------------===//
30*67e74705SXin Li
31*67e74705SXin Li #include "ClangSACheckers.h"
32*67e74705SXin Li #include "clang/AST/Attr.h"
33*67e74705SXin Li #include "clang/AST/DeclObjC.h"
34*67e74705SXin Li #include "clang/AST/Expr.h"
35*67e74705SXin Li #include "clang/AST/ExprObjC.h"
36*67e74705SXin Li #include "clang/Basic/LangOptions.h"
37*67e74705SXin Li #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
38*67e74705SXin Li #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
39*67e74705SXin Li #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
40*67e74705SXin Li #include "clang/StaticAnalyzer/Core/Checker.h"
41*67e74705SXin Li #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
42*67e74705SXin Li #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
43*67e74705SXin Li #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
44*67e74705SXin Li #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
45*67e74705SXin Li #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
46*67e74705SXin Li #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
47*67e74705SXin Li #include "llvm/Support/raw_ostream.h"
48*67e74705SXin Li
49*67e74705SXin Li using namespace clang;
50*67e74705SXin Li using namespace ento;
51*67e74705SXin Li
52*67e74705SXin Li /// Indicates whether an instance variable is required to be released in
53*67e74705SXin Li /// -dealloc.
54*67e74705SXin Li enum class ReleaseRequirement {
55*67e74705SXin Li /// The instance variable must be released, either by calling
56*67e74705SXin Li /// -release on it directly or by nilling it out with a property setter.
57*67e74705SXin Li MustRelease,
58*67e74705SXin Li
59*67e74705SXin Li /// The instance variable must not be directly released with -release.
60*67e74705SXin Li MustNotReleaseDirectly,
61*67e74705SXin Li
62*67e74705SXin Li /// The requirement for the instance variable could not be determined.
63*67e74705SXin Li Unknown
64*67e74705SXin Li };
65*67e74705SXin Li
66*67e74705SXin Li /// Returns true if the property implementation is synthesized and the
67*67e74705SXin Li /// type of the property is retainable.
isSynthesizedRetainableProperty(const ObjCPropertyImplDecl * I,const ObjCIvarDecl ** ID,const ObjCPropertyDecl ** PD)68*67e74705SXin Li static bool isSynthesizedRetainableProperty(const ObjCPropertyImplDecl *I,
69*67e74705SXin Li const ObjCIvarDecl **ID,
70*67e74705SXin Li const ObjCPropertyDecl **PD) {
71*67e74705SXin Li
72*67e74705SXin Li if (I->getPropertyImplementation() != ObjCPropertyImplDecl::Synthesize)
73*67e74705SXin Li return false;
74*67e74705SXin Li
75*67e74705SXin Li (*ID) = I->getPropertyIvarDecl();
76*67e74705SXin Li if (!(*ID))
77*67e74705SXin Li return false;
78*67e74705SXin Li
79*67e74705SXin Li QualType T = (*ID)->getType();
80*67e74705SXin Li if (!T->isObjCRetainableType())
81*67e74705SXin Li return false;
82*67e74705SXin Li
83*67e74705SXin Li (*PD) = I->getPropertyDecl();
84*67e74705SXin Li // Shouldn't be able to synthesize a property that doesn't exist.
85*67e74705SXin Li assert(*PD);
86*67e74705SXin Li
87*67e74705SXin Li return true;
88*67e74705SXin Li }
89*67e74705SXin Li
90*67e74705SXin Li namespace {
91*67e74705SXin Li
92*67e74705SXin Li class ObjCDeallocChecker
93*67e74705SXin Li : public Checker<check::ASTDecl<ObjCImplementationDecl>,
94*67e74705SXin Li check::PreObjCMessage, check::PostObjCMessage,
95*67e74705SXin Li check::PreCall,
96*67e74705SXin Li check::BeginFunction, check::EndFunction,
97*67e74705SXin Li eval::Assume,
98*67e74705SXin Li check::PointerEscape,
99*67e74705SXin Li check::PreStmt<ReturnStmt>> {
100*67e74705SXin Li
101*67e74705SXin Li mutable IdentifierInfo *NSObjectII, *SenTestCaseII, *XCTestCaseII,
102*67e74705SXin Li *Block_releaseII, *CIFilterII;
103*67e74705SXin Li
104*67e74705SXin Li mutable Selector DeallocSel, ReleaseSel;
105*67e74705SXin Li
106*67e74705SXin Li std::unique_ptr<BugType> MissingReleaseBugType;
107*67e74705SXin Li std::unique_ptr<BugType> ExtraReleaseBugType;
108*67e74705SXin Li std::unique_ptr<BugType> MistakenDeallocBugType;
109*67e74705SXin Li
110*67e74705SXin Li public:
111*67e74705SXin Li ObjCDeallocChecker();
112*67e74705SXin Li
113*67e74705SXin Li void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
114*67e74705SXin Li BugReporter &BR) const;
115*67e74705SXin Li void checkBeginFunction(CheckerContext &Ctx) const;
116*67e74705SXin Li void checkPreObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
117*67e74705SXin Li void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
118*67e74705SXin Li void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
119*67e74705SXin Li
120*67e74705SXin Li ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
121*67e74705SXin Li bool Assumption) const;
122*67e74705SXin Li
123*67e74705SXin Li ProgramStateRef checkPointerEscape(ProgramStateRef State,
124*67e74705SXin Li const InvalidatedSymbols &Escaped,
125*67e74705SXin Li const CallEvent *Call,
126*67e74705SXin Li PointerEscapeKind Kind) const;
127*67e74705SXin Li void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
128*67e74705SXin Li void checkEndFunction(CheckerContext &Ctx) const;
129*67e74705SXin Li
130*67e74705SXin Li private:
131*67e74705SXin Li void diagnoseMissingReleases(CheckerContext &C) const;
132*67e74705SXin Li
133*67e74705SXin Li bool diagnoseExtraRelease(SymbolRef ReleasedValue, const ObjCMethodCall &M,
134*67e74705SXin Li CheckerContext &C) const;
135*67e74705SXin Li
136*67e74705SXin Li bool diagnoseMistakenDealloc(SymbolRef DeallocedValue,
137*67e74705SXin Li const ObjCMethodCall &M,
138*67e74705SXin Li CheckerContext &C) const;
139*67e74705SXin Li
140*67e74705SXin Li SymbolRef getValueReleasedByNillingOut(const ObjCMethodCall &M,
141*67e74705SXin Li CheckerContext &C) const;
142*67e74705SXin Li
143*67e74705SXin Li const ObjCIvarRegion *getIvarRegionForIvarSymbol(SymbolRef IvarSym) const;
144*67e74705SXin Li SymbolRef getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const;
145*67e74705SXin Li
146*67e74705SXin Li const ObjCPropertyImplDecl*
147*67e74705SXin Li findPropertyOnDeallocatingInstance(SymbolRef IvarSym,
148*67e74705SXin Li CheckerContext &C) const;
149*67e74705SXin Li
150*67e74705SXin Li ReleaseRequirement
151*67e74705SXin Li getDeallocReleaseRequirement(const ObjCPropertyImplDecl *PropImpl) const;
152*67e74705SXin Li
153*67e74705SXin Li bool isInInstanceDealloc(const CheckerContext &C, SVal &SelfValOut) const;
154*67e74705SXin Li bool isInInstanceDealloc(const CheckerContext &C, const LocationContext *LCtx,
155*67e74705SXin Li SVal &SelfValOut) const;
156*67e74705SXin Li bool instanceDeallocIsOnStack(const CheckerContext &C,
157*67e74705SXin Li SVal &InstanceValOut) const;
158*67e74705SXin Li
159*67e74705SXin Li bool isSuperDeallocMessage(const ObjCMethodCall &M) const;
160*67e74705SXin Li
161*67e74705SXin Li const ObjCImplDecl *getContainingObjCImpl(const LocationContext *LCtx) const;
162*67e74705SXin Li
163*67e74705SXin Li const ObjCPropertyDecl *
164*67e74705SXin Li findShadowedPropertyDecl(const ObjCPropertyImplDecl *PropImpl) const;
165*67e74705SXin Li
166*67e74705SXin Li void transitionToReleaseValue(CheckerContext &C, SymbolRef Value) const;
167*67e74705SXin Li ProgramStateRef removeValueRequiringRelease(ProgramStateRef State,
168*67e74705SXin Li SymbolRef InstanceSym,
169*67e74705SXin Li SymbolRef ValueSym) const;
170*67e74705SXin Li
171*67e74705SXin Li void initIdentifierInfoAndSelectors(ASTContext &Ctx) const;
172*67e74705SXin Li
173*67e74705SXin Li bool classHasSeparateTeardown(const ObjCInterfaceDecl *ID) const;
174*67e74705SXin Li
175*67e74705SXin Li bool isReleasedByCIFilterDealloc(const ObjCPropertyImplDecl *PropImpl) const;
176*67e74705SXin Li };
177*67e74705SXin Li } // End anonymous namespace.
178*67e74705SXin Li
179*67e74705SXin Li typedef llvm::ImmutableSet<SymbolRef> SymbolSet;
180*67e74705SXin Li
181*67e74705SXin Li /// Maps from the symbol for a class instance to the set of
182*67e74705SXin Li /// symbols remaining that must be released in -dealloc.
183*67e74705SXin Li REGISTER_MAP_WITH_PROGRAMSTATE(UnreleasedIvarMap, SymbolRef, SymbolSet)
184*67e74705SXin Li
185*67e74705SXin Li namespace clang {
186*67e74705SXin Li namespace ento {
187*67e74705SXin Li template<> struct ProgramStateTrait<SymbolSet>
188*67e74705SXin Li : public ProgramStatePartialTrait<SymbolSet> {
GDMIndexclang::ento::ProgramStateTrait189*67e74705SXin Li static void *GDMIndex() { static int index = 0; return &index; }
190*67e74705SXin Li };
191*67e74705SXin Li }
192*67e74705SXin Li }
193*67e74705SXin Li
194*67e74705SXin Li /// An AST check that diagnose when the class requires a -dealloc method and
195*67e74705SXin Li /// is missing one.
checkASTDecl(const ObjCImplementationDecl * D,AnalysisManager & Mgr,BugReporter & BR) const196*67e74705SXin Li void ObjCDeallocChecker::checkASTDecl(const ObjCImplementationDecl *D,
197*67e74705SXin Li AnalysisManager &Mgr,
198*67e74705SXin Li BugReporter &BR) const {
199*67e74705SXin Li assert(Mgr.getLangOpts().getGC() != LangOptions::GCOnly);
200*67e74705SXin Li assert(!Mgr.getLangOpts().ObjCAutoRefCount);
201*67e74705SXin Li initIdentifierInfoAndSelectors(Mgr.getASTContext());
202*67e74705SXin Li
203*67e74705SXin Li const ObjCInterfaceDecl *ID = D->getClassInterface();
204*67e74705SXin Li // If the class is known to have a lifecycle with a separate teardown method
205*67e74705SXin Li // then it may not require a -dealloc method.
206*67e74705SXin Li if (classHasSeparateTeardown(ID))
207*67e74705SXin Li return;
208*67e74705SXin Li
209*67e74705SXin Li // Does the class contain any synthesized properties that are retainable?
210*67e74705SXin Li // If not, skip the check entirely.
211*67e74705SXin Li const ObjCPropertyImplDecl *PropImplRequiringRelease = nullptr;
212*67e74705SXin Li bool HasOthers = false;
213*67e74705SXin Li for (const auto *I : D->property_impls()) {
214*67e74705SXin Li if (getDeallocReleaseRequirement(I) == ReleaseRequirement::MustRelease) {
215*67e74705SXin Li if (!PropImplRequiringRelease)
216*67e74705SXin Li PropImplRequiringRelease = I;
217*67e74705SXin Li else {
218*67e74705SXin Li HasOthers = true;
219*67e74705SXin Li break;
220*67e74705SXin Li }
221*67e74705SXin Li }
222*67e74705SXin Li }
223*67e74705SXin Li
224*67e74705SXin Li if (!PropImplRequiringRelease)
225*67e74705SXin Li return;
226*67e74705SXin Li
227*67e74705SXin Li const ObjCMethodDecl *MD = nullptr;
228*67e74705SXin Li
229*67e74705SXin Li // Scan the instance methods for "dealloc".
230*67e74705SXin Li for (const auto *I : D->instance_methods()) {
231*67e74705SXin Li if (I->getSelector() == DeallocSel) {
232*67e74705SXin Li MD = I;
233*67e74705SXin Li break;
234*67e74705SXin Li }
235*67e74705SXin Li }
236*67e74705SXin Li
237*67e74705SXin Li if (!MD) { // No dealloc found.
238*67e74705SXin Li const char* Name = "Missing -dealloc";
239*67e74705SXin Li
240*67e74705SXin Li std::string Buf;
241*67e74705SXin Li llvm::raw_string_ostream OS(Buf);
242*67e74705SXin Li OS << "'" << *D << "' lacks a 'dealloc' instance method but "
243*67e74705SXin Li << "must release '" << *PropImplRequiringRelease->getPropertyIvarDecl()
244*67e74705SXin Li << "'";
245*67e74705SXin Li
246*67e74705SXin Li if (HasOthers)
247*67e74705SXin Li OS << " and others";
248*67e74705SXin Li PathDiagnosticLocation DLoc =
249*67e74705SXin Li PathDiagnosticLocation::createBegin(D, BR.getSourceManager());
250*67e74705SXin Li
251*67e74705SXin Li BR.EmitBasicReport(D, this, Name, categories::CoreFoundationObjectiveC,
252*67e74705SXin Li OS.str(), DLoc);
253*67e74705SXin Li return;
254*67e74705SXin Li }
255*67e74705SXin Li }
256*67e74705SXin Li
257*67e74705SXin Li /// If this is the beginning of -dealloc, mark the values initially stored in
258*67e74705SXin Li /// instance variables that must be released by the end of -dealloc
259*67e74705SXin Li /// as unreleased in the state.
checkBeginFunction(CheckerContext & C) const260*67e74705SXin Li void ObjCDeallocChecker::checkBeginFunction(
261*67e74705SXin Li CheckerContext &C) const {
262*67e74705SXin Li initIdentifierInfoAndSelectors(C.getASTContext());
263*67e74705SXin Li
264*67e74705SXin Li // Only do this if the current method is -dealloc.
265*67e74705SXin Li SVal SelfVal;
266*67e74705SXin Li if (!isInInstanceDealloc(C, SelfVal))
267*67e74705SXin Li return;
268*67e74705SXin Li
269*67e74705SXin Li SymbolRef SelfSymbol = SelfVal.getAsSymbol();
270*67e74705SXin Li
271*67e74705SXin Li const LocationContext *LCtx = C.getLocationContext();
272*67e74705SXin Li ProgramStateRef InitialState = C.getState();
273*67e74705SXin Li
274*67e74705SXin Li ProgramStateRef State = InitialState;
275*67e74705SXin Li
276*67e74705SXin Li SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
277*67e74705SXin Li
278*67e74705SXin Li // Symbols that must be released by the end of the -dealloc;
279*67e74705SXin Li SymbolSet RequiredReleases = F.getEmptySet();
280*67e74705SXin Li
281*67e74705SXin Li // If we're an inlined -dealloc, we should add our symbols to the existing
282*67e74705SXin Li // set from our subclass.
283*67e74705SXin Li if (const SymbolSet *CurrSet = State->get<UnreleasedIvarMap>(SelfSymbol))
284*67e74705SXin Li RequiredReleases = *CurrSet;
285*67e74705SXin Li
286*67e74705SXin Li for (auto *PropImpl : getContainingObjCImpl(LCtx)->property_impls()) {
287*67e74705SXin Li ReleaseRequirement Requirement = getDeallocReleaseRequirement(PropImpl);
288*67e74705SXin Li if (Requirement != ReleaseRequirement::MustRelease)
289*67e74705SXin Li continue;
290*67e74705SXin Li
291*67e74705SXin Li SVal LVal = State->getLValue(PropImpl->getPropertyIvarDecl(), SelfVal);
292*67e74705SXin Li Optional<Loc> LValLoc = LVal.getAs<Loc>();
293*67e74705SXin Li if (!LValLoc)
294*67e74705SXin Li continue;
295*67e74705SXin Li
296*67e74705SXin Li SVal InitialVal = State->getSVal(LValLoc.getValue());
297*67e74705SXin Li SymbolRef Symbol = InitialVal.getAsSymbol();
298*67e74705SXin Li if (!Symbol || !isa<SymbolRegionValue>(Symbol))
299*67e74705SXin Li continue;
300*67e74705SXin Li
301*67e74705SXin Li // Mark the value as requiring a release.
302*67e74705SXin Li RequiredReleases = F.add(RequiredReleases, Symbol);
303*67e74705SXin Li }
304*67e74705SXin Li
305*67e74705SXin Li if (!RequiredReleases.isEmpty()) {
306*67e74705SXin Li State = State->set<UnreleasedIvarMap>(SelfSymbol, RequiredReleases);
307*67e74705SXin Li }
308*67e74705SXin Li
309*67e74705SXin Li if (State != InitialState) {
310*67e74705SXin Li C.addTransition(State);
311*67e74705SXin Li }
312*67e74705SXin Li }
313*67e74705SXin Li
314*67e74705SXin Li /// Given a symbol for an ivar, return the ivar region it was loaded from.
315*67e74705SXin Li /// Returns nullptr if the instance symbol cannot be found.
316*67e74705SXin Li const ObjCIvarRegion *
getIvarRegionForIvarSymbol(SymbolRef IvarSym) const317*67e74705SXin Li ObjCDeallocChecker::getIvarRegionForIvarSymbol(SymbolRef IvarSym) const {
318*67e74705SXin Li return dyn_cast_or_null<ObjCIvarRegion>(IvarSym->getOriginRegion());
319*67e74705SXin Li }
320*67e74705SXin Li
321*67e74705SXin Li /// Given a symbol for an ivar, return a symbol for the instance containing
322*67e74705SXin Li /// the ivar. Returns nullptr if the instance symbol cannot be found.
323*67e74705SXin Li SymbolRef
getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const324*67e74705SXin Li ObjCDeallocChecker::getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const {
325*67e74705SXin Li
326*67e74705SXin Li const ObjCIvarRegion *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
327*67e74705SXin Li if (!IvarRegion)
328*67e74705SXin Li return nullptr;
329*67e74705SXin Li
330*67e74705SXin Li return IvarRegion->getSymbolicBase()->getSymbol();
331*67e74705SXin Li }
332*67e74705SXin Li
333*67e74705SXin Li /// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
334*67e74705SXin Li /// a release or a nilling-out property setter.
checkPreObjCMessage(const ObjCMethodCall & M,CheckerContext & C) const335*67e74705SXin Li void ObjCDeallocChecker::checkPreObjCMessage(
336*67e74705SXin Li const ObjCMethodCall &M, CheckerContext &C) const {
337*67e74705SXin Li // Only run if -dealloc is on the stack.
338*67e74705SXin Li SVal DeallocedInstance;
339*67e74705SXin Li if (!instanceDeallocIsOnStack(C, DeallocedInstance))
340*67e74705SXin Li return;
341*67e74705SXin Li
342*67e74705SXin Li SymbolRef ReleasedValue = nullptr;
343*67e74705SXin Li
344*67e74705SXin Li if (M.getSelector() == ReleaseSel) {
345*67e74705SXin Li ReleasedValue = M.getReceiverSVal().getAsSymbol();
346*67e74705SXin Li } else if (M.getSelector() == DeallocSel && !M.isReceiverSelfOrSuper()) {
347*67e74705SXin Li if (diagnoseMistakenDealloc(M.getReceiverSVal().getAsSymbol(), M, C))
348*67e74705SXin Li return;
349*67e74705SXin Li }
350*67e74705SXin Li
351*67e74705SXin Li if (ReleasedValue) {
352*67e74705SXin Li // An instance variable symbol was released with -release:
353*67e74705SXin Li // [_property release];
354*67e74705SXin Li if (diagnoseExtraRelease(ReleasedValue,M, C))
355*67e74705SXin Li return;
356*67e74705SXin Li } else {
357*67e74705SXin Li // An instance variable symbol was released nilling out its property:
358*67e74705SXin Li // self.property = nil;
359*67e74705SXin Li ReleasedValue = getValueReleasedByNillingOut(M, C);
360*67e74705SXin Li }
361*67e74705SXin Li
362*67e74705SXin Li if (!ReleasedValue)
363*67e74705SXin Li return;
364*67e74705SXin Li
365*67e74705SXin Li transitionToReleaseValue(C, ReleasedValue);
366*67e74705SXin Li }
367*67e74705SXin Li
368*67e74705SXin Li /// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
369*67e74705SXin Li /// call to Block_release().
checkPreCall(const CallEvent & Call,CheckerContext & C) const370*67e74705SXin Li void ObjCDeallocChecker::checkPreCall(const CallEvent &Call,
371*67e74705SXin Li CheckerContext &C) const {
372*67e74705SXin Li const IdentifierInfo *II = Call.getCalleeIdentifier();
373*67e74705SXin Li if (II != Block_releaseII)
374*67e74705SXin Li return;
375*67e74705SXin Li
376*67e74705SXin Li if (Call.getNumArgs() != 1)
377*67e74705SXin Li return;
378*67e74705SXin Li
379*67e74705SXin Li SymbolRef ReleasedValue = Call.getArgSVal(0).getAsSymbol();
380*67e74705SXin Li if (!ReleasedValue)
381*67e74705SXin Li return;
382*67e74705SXin Li
383*67e74705SXin Li transitionToReleaseValue(C, ReleasedValue);
384*67e74705SXin Li }
385*67e74705SXin Li /// If the message was a call to '[super dealloc]', diagnose any missing
386*67e74705SXin Li /// releases.
checkPostObjCMessage(const ObjCMethodCall & M,CheckerContext & C) const387*67e74705SXin Li void ObjCDeallocChecker::checkPostObjCMessage(
388*67e74705SXin Li const ObjCMethodCall &M, CheckerContext &C) const {
389*67e74705SXin Li // We perform this check post-message so that if the super -dealloc
390*67e74705SXin Li // calls a helper method and that this class overrides, any ivars released in
391*67e74705SXin Li // the helper method will be recorded before checking.
392*67e74705SXin Li if (isSuperDeallocMessage(M))
393*67e74705SXin Li diagnoseMissingReleases(C);
394*67e74705SXin Li }
395*67e74705SXin Li
396*67e74705SXin Li /// Check for missing releases even when -dealloc does not call
397*67e74705SXin Li /// '[super dealloc]'.
checkEndFunction(CheckerContext & C) const398*67e74705SXin Li void ObjCDeallocChecker::checkEndFunction(
399*67e74705SXin Li CheckerContext &C) const {
400*67e74705SXin Li diagnoseMissingReleases(C);
401*67e74705SXin Li }
402*67e74705SXin Li
403*67e74705SXin Li /// Check for missing releases on early return.
checkPreStmt(const ReturnStmt * RS,CheckerContext & C) const404*67e74705SXin Li void ObjCDeallocChecker::checkPreStmt(
405*67e74705SXin Li const ReturnStmt *RS, CheckerContext &C) const {
406*67e74705SXin Li diagnoseMissingReleases(C);
407*67e74705SXin Li }
408*67e74705SXin Li
409*67e74705SXin Li /// When a symbol is assumed to be nil, remove it from the set of symbols
410*67e74705SXin Li /// require to be nil.
evalAssume(ProgramStateRef State,SVal Cond,bool Assumption) const411*67e74705SXin Li ProgramStateRef ObjCDeallocChecker::evalAssume(ProgramStateRef State, SVal Cond,
412*67e74705SXin Li bool Assumption) const {
413*67e74705SXin Li if (State->get<UnreleasedIvarMap>().isEmpty())
414*67e74705SXin Li return State;
415*67e74705SXin Li
416*67e74705SXin Li auto *CondBSE = dyn_cast_or_null<BinarySymExpr>(Cond.getAsSymExpr());
417*67e74705SXin Li if (!CondBSE)
418*67e74705SXin Li return State;
419*67e74705SXin Li
420*67e74705SXin Li BinaryOperator::Opcode OpCode = CondBSE->getOpcode();
421*67e74705SXin Li if (Assumption) {
422*67e74705SXin Li if (OpCode != BO_EQ)
423*67e74705SXin Li return State;
424*67e74705SXin Li } else {
425*67e74705SXin Li if (OpCode != BO_NE)
426*67e74705SXin Li return State;
427*67e74705SXin Li }
428*67e74705SXin Li
429*67e74705SXin Li SymbolRef NullSymbol = nullptr;
430*67e74705SXin Li if (auto *SIE = dyn_cast<SymIntExpr>(CondBSE)) {
431*67e74705SXin Li const llvm::APInt &RHS = SIE->getRHS();
432*67e74705SXin Li if (RHS != 0)
433*67e74705SXin Li return State;
434*67e74705SXin Li NullSymbol = SIE->getLHS();
435*67e74705SXin Li } else if (auto *SIE = dyn_cast<IntSymExpr>(CondBSE)) {
436*67e74705SXin Li const llvm::APInt &LHS = SIE->getLHS();
437*67e74705SXin Li if (LHS != 0)
438*67e74705SXin Li return State;
439*67e74705SXin Li NullSymbol = SIE->getRHS();
440*67e74705SXin Li } else {
441*67e74705SXin Li return State;
442*67e74705SXin Li }
443*67e74705SXin Li
444*67e74705SXin Li SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(NullSymbol);
445*67e74705SXin Li if (!InstanceSymbol)
446*67e74705SXin Li return State;
447*67e74705SXin Li
448*67e74705SXin Li State = removeValueRequiringRelease(State, InstanceSymbol, NullSymbol);
449*67e74705SXin Li
450*67e74705SXin Li return State;
451*67e74705SXin Li }
452*67e74705SXin Li
453*67e74705SXin Li /// If a symbol escapes conservatively assume unseen code released it.
checkPointerEscape(ProgramStateRef State,const InvalidatedSymbols & Escaped,const CallEvent * Call,PointerEscapeKind Kind) const454*67e74705SXin Li ProgramStateRef ObjCDeallocChecker::checkPointerEscape(
455*67e74705SXin Li ProgramStateRef State, const InvalidatedSymbols &Escaped,
456*67e74705SXin Li const CallEvent *Call, PointerEscapeKind Kind) const {
457*67e74705SXin Li
458*67e74705SXin Li if (State->get<UnreleasedIvarMap>().isEmpty())
459*67e74705SXin Li return State;
460*67e74705SXin Li
461*67e74705SXin Li // Don't treat calls to '[super dealloc]' as escaping for the purposes
462*67e74705SXin Li // of this checker. Because the checker diagnoses missing releases in the
463*67e74705SXin Li // post-message handler for '[super dealloc], escaping here would cause
464*67e74705SXin Li // the checker to never warn.
465*67e74705SXin Li auto *OMC = dyn_cast_or_null<ObjCMethodCall>(Call);
466*67e74705SXin Li if (OMC && isSuperDeallocMessage(*OMC))
467*67e74705SXin Li return State;
468*67e74705SXin Li
469*67e74705SXin Li for (const auto &Sym : Escaped) {
470*67e74705SXin Li if (!Call || (Call && !Call->isInSystemHeader())) {
471*67e74705SXin Li // If Sym is a symbol for an object with instance variables that
472*67e74705SXin Li // must be released, remove these obligations when the object escapes
473*67e74705SXin Li // unless via a call to a system function. System functions are
474*67e74705SXin Li // very unlikely to release instance variables on objects passed to them,
475*67e74705SXin Li // and are frequently called on 'self' in -dealloc (e.g., to remove
476*67e74705SXin Li // observers) -- we want to avoid false negatives from escaping on
477*67e74705SXin Li // them.
478*67e74705SXin Li State = State->remove<UnreleasedIvarMap>(Sym);
479*67e74705SXin Li }
480*67e74705SXin Li
481*67e74705SXin Li
482*67e74705SXin Li SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(Sym);
483*67e74705SXin Li if (!InstanceSymbol)
484*67e74705SXin Li continue;
485*67e74705SXin Li
486*67e74705SXin Li State = removeValueRequiringRelease(State, InstanceSymbol, Sym);
487*67e74705SXin Li }
488*67e74705SXin Li
489*67e74705SXin Li return State;
490*67e74705SXin Li }
491*67e74705SXin Li
492*67e74705SXin Li /// Report any unreleased instance variables for the current instance being
493*67e74705SXin Li /// dealloced.
diagnoseMissingReleases(CheckerContext & C) const494*67e74705SXin Li void ObjCDeallocChecker::diagnoseMissingReleases(CheckerContext &C) const {
495*67e74705SXin Li ProgramStateRef State = C.getState();
496*67e74705SXin Li
497*67e74705SXin Li SVal SelfVal;
498*67e74705SXin Li if (!isInInstanceDealloc(C, SelfVal))
499*67e74705SXin Li return;
500*67e74705SXin Li
501*67e74705SXin Li const MemRegion *SelfRegion = SelfVal.castAs<loc::MemRegionVal>().getRegion();
502*67e74705SXin Li const LocationContext *LCtx = C.getLocationContext();
503*67e74705SXin Li
504*67e74705SXin Li ExplodedNode *ErrNode = nullptr;
505*67e74705SXin Li
506*67e74705SXin Li SymbolRef SelfSym = SelfVal.getAsSymbol();
507*67e74705SXin Li if (!SelfSym)
508*67e74705SXin Li return;
509*67e74705SXin Li
510*67e74705SXin Li const SymbolSet *OldUnreleased = State->get<UnreleasedIvarMap>(SelfSym);
511*67e74705SXin Li if (!OldUnreleased)
512*67e74705SXin Li return;
513*67e74705SXin Li
514*67e74705SXin Li SymbolSet NewUnreleased = *OldUnreleased;
515*67e74705SXin Li SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
516*67e74705SXin Li
517*67e74705SXin Li ProgramStateRef InitialState = State;
518*67e74705SXin Li
519*67e74705SXin Li for (auto *IvarSymbol : *OldUnreleased) {
520*67e74705SXin Li const TypedValueRegion *TVR =
521*67e74705SXin Li cast<SymbolRegionValue>(IvarSymbol)->getRegion();
522*67e74705SXin Li const ObjCIvarRegion *IvarRegion = cast<ObjCIvarRegion>(TVR);
523*67e74705SXin Li
524*67e74705SXin Li // Don't warn if the ivar is not for this instance.
525*67e74705SXin Li if (SelfRegion != IvarRegion->getSuperRegion())
526*67e74705SXin Li continue;
527*67e74705SXin Li
528*67e74705SXin Li const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
529*67e74705SXin Li // Prevent an inlined call to -dealloc in a super class from warning
530*67e74705SXin Li // about the values the subclass's -dealloc should release.
531*67e74705SXin Li if (IvarDecl->getContainingInterface() !=
532*67e74705SXin Li cast<ObjCMethodDecl>(LCtx->getDecl())->getClassInterface())
533*67e74705SXin Li continue;
534*67e74705SXin Li
535*67e74705SXin Li // Prevents diagnosing multiple times for the same instance variable
536*67e74705SXin Li // at, for example, both a return and at the end of of the function.
537*67e74705SXin Li NewUnreleased = F.remove(NewUnreleased, IvarSymbol);
538*67e74705SXin Li
539*67e74705SXin Li if (State->getStateManager()
540*67e74705SXin Li .getConstraintManager()
541*67e74705SXin Li .isNull(State, IvarSymbol)
542*67e74705SXin Li .isConstrainedTrue()) {
543*67e74705SXin Li continue;
544*67e74705SXin Li }
545*67e74705SXin Li
546*67e74705SXin Li // A missing release manifests as a leak, so treat as a non-fatal error.
547*67e74705SXin Li if (!ErrNode)
548*67e74705SXin Li ErrNode = C.generateNonFatalErrorNode();
549*67e74705SXin Li // If we've already reached this node on another path, return without
550*67e74705SXin Li // diagnosing.
551*67e74705SXin Li if (!ErrNode)
552*67e74705SXin Li return;
553*67e74705SXin Li
554*67e74705SXin Li std::string Buf;
555*67e74705SXin Li llvm::raw_string_ostream OS(Buf);
556*67e74705SXin Li
557*67e74705SXin Li const ObjCInterfaceDecl *Interface = IvarDecl->getContainingInterface();
558*67e74705SXin Li // If the class is known to have a lifecycle with teardown that is
559*67e74705SXin Li // separate from -dealloc, do not warn about missing releases. We
560*67e74705SXin Li // suppress here (rather than not tracking for instance variables in
561*67e74705SXin Li // such classes) because these classes are rare.
562*67e74705SXin Li if (classHasSeparateTeardown(Interface))
563*67e74705SXin Li return;
564*67e74705SXin Li
565*67e74705SXin Li ObjCImplDecl *ImplDecl = Interface->getImplementation();
566*67e74705SXin Li
567*67e74705SXin Li const ObjCPropertyImplDecl *PropImpl =
568*67e74705SXin Li ImplDecl->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
569*67e74705SXin Li
570*67e74705SXin Li const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
571*67e74705SXin Li
572*67e74705SXin Li assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Copy ||
573*67e74705SXin Li PropDecl->getSetterKind() == ObjCPropertyDecl::Retain);
574*67e74705SXin Li
575*67e74705SXin Li OS << "The '" << *IvarDecl << "' ivar in '" << *ImplDecl
576*67e74705SXin Li << "' was ";
577*67e74705SXin Li
578*67e74705SXin Li if (PropDecl->getSetterKind() == ObjCPropertyDecl::Retain)
579*67e74705SXin Li OS << "retained";
580*67e74705SXin Li else
581*67e74705SXin Li OS << "copied";
582*67e74705SXin Li
583*67e74705SXin Li OS << " by a synthesized property but not released"
584*67e74705SXin Li " before '[super dealloc]'";
585*67e74705SXin Li
586*67e74705SXin Li std::unique_ptr<BugReport> BR(
587*67e74705SXin Li new BugReport(*MissingReleaseBugType, OS.str(), ErrNode));
588*67e74705SXin Li
589*67e74705SXin Li C.emitReport(std::move(BR));
590*67e74705SXin Li }
591*67e74705SXin Li
592*67e74705SXin Li if (NewUnreleased.isEmpty()) {
593*67e74705SXin Li State = State->remove<UnreleasedIvarMap>(SelfSym);
594*67e74705SXin Li } else {
595*67e74705SXin Li State = State->set<UnreleasedIvarMap>(SelfSym, NewUnreleased);
596*67e74705SXin Li }
597*67e74705SXin Li
598*67e74705SXin Li if (ErrNode) {
599*67e74705SXin Li C.addTransition(State, ErrNode);
600*67e74705SXin Li } else if (State != InitialState) {
601*67e74705SXin Li C.addTransition(State);
602*67e74705SXin Li }
603*67e74705SXin Li
604*67e74705SXin Li // Make sure that after checking in the top-most frame the list of
605*67e74705SXin Li // tracked ivars is empty. This is intended to detect accidental leaks in
606*67e74705SXin Li // the UnreleasedIvarMap program state.
607*67e74705SXin Li assert(!LCtx->inTopFrame() || State->get<UnreleasedIvarMap>().isEmpty());
608*67e74705SXin Li }
609*67e74705SXin Li
610*67e74705SXin Li /// Given a symbol, determine whether the symbol refers to an ivar on
611*67e74705SXin Li /// the top-most deallocating instance. If so, find the property for that
612*67e74705SXin Li /// ivar, if one exists. Otherwise return null.
613*67e74705SXin Li const ObjCPropertyImplDecl *
findPropertyOnDeallocatingInstance(SymbolRef IvarSym,CheckerContext & C) const614*67e74705SXin Li ObjCDeallocChecker::findPropertyOnDeallocatingInstance(
615*67e74705SXin Li SymbolRef IvarSym, CheckerContext &C) const {
616*67e74705SXin Li SVal DeallocedInstance;
617*67e74705SXin Li if (!isInInstanceDealloc(C, DeallocedInstance))
618*67e74705SXin Li return nullptr;
619*67e74705SXin Li
620*67e74705SXin Li // Try to get the region from which the ivar value was loaded.
621*67e74705SXin Li auto *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
622*67e74705SXin Li if (!IvarRegion)
623*67e74705SXin Li return nullptr;
624*67e74705SXin Li
625*67e74705SXin Li // Don't try to find the property if the ivar was not loaded from the
626*67e74705SXin Li // given instance.
627*67e74705SXin Li if (DeallocedInstance.castAs<loc::MemRegionVal>().getRegion() !=
628*67e74705SXin Li IvarRegion->getSuperRegion())
629*67e74705SXin Li return nullptr;
630*67e74705SXin Li
631*67e74705SXin Li const LocationContext *LCtx = C.getLocationContext();
632*67e74705SXin Li const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
633*67e74705SXin Li
634*67e74705SXin Li const ObjCImplDecl *Container = getContainingObjCImpl(LCtx);
635*67e74705SXin Li const ObjCPropertyImplDecl *PropImpl =
636*67e74705SXin Li Container->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
637*67e74705SXin Li return PropImpl;
638*67e74705SXin Li }
639*67e74705SXin Li
640*67e74705SXin Li /// Emits a warning if the current context is -dealloc and ReleasedValue
641*67e74705SXin Li /// must not be directly released in a -dealloc. Returns true if a diagnostic
642*67e74705SXin Li /// was emitted.
diagnoseExtraRelease(SymbolRef ReleasedValue,const ObjCMethodCall & M,CheckerContext & C) const643*67e74705SXin Li bool ObjCDeallocChecker::diagnoseExtraRelease(SymbolRef ReleasedValue,
644*67e74705SXin Li const ObjCMethodCall &M,
645*67e74705SXin Li CheckerContext &C) const {
646*67e74705SXin Li // Try to get the region from which the the released value was loaded.
647*67e74705SXin Li // Note that, unlike diagnosing for missing releases, here we don't track
648*67e74705SXin Li // values that must not be released in the state. This is because even if
649*67e74705SXin Li // these values escape, it is still an error under the rules of MRR to
650*67e74705SXin Li // release them in -dealloc.
651*67e74705SXin Li const ObjCPropertyImplDecl *PropImpl =
652*67e74705SXin Li findPropertyOnDeallocatingInstance(ReleasedValue, C);
653*67e74705SXin Li
654*67e74705SXin Li if (!PropImpl)
655*67e74705SXin Li return false;
656*67e74705SXin Li
657*67e74705SXin Li // If the ivar belongs to a property that must not be released directly
658*67e74705SXin Li // in dealloc, emit a warning.
659*67e74705SXin Li if (getDeallocReleaseRequirement(PropImpl) !=
660*67e74705SXin Li ReleaseRequirement::MustNotReleaseDirectly) {
661*67e74705SXin Li return false;
662*67e74705SXin Li }
663*67e74705SXin Li
664*67e74705SXin Li // If the property is readwrite but it shadows a read-only property in its
665*67e74705SXin Li // external interface, treat the property a read-only. If the outside
666*67e74705SXin Li // world cannot write to a property then the internal implementation is free
667*67e74705SXin Li // to make its own convention about whether the value is stored retained
668*67e74705SXin Li // or not. We look up the shadow here rather than in
669*67e74705SXin Li // getDeallocReleaseRequirement() because doing so can be expensive.
670*67e74705SXin Li const ObjCPropertyDecl *PropDecl = findShadowedPropertyDecl(PropImpl);
671*67e74705SXin Li if (PropDecl) {
672*67e74705SXin Li if (PropDecl->isReadOnly())
673*67e74705SXin Li return false;
674*67e74705SXin Li } else {
675*67e74705SXin Li PropDecl = PropImpl->getPropertyDecl();
676*67e74705SXin Li }
677*67e74705SXin Li
678*67e74705SXin Li ExplodedNode *ErrNode = C.generateNonFatalErrorNode();
679*67e74705SXin Li if (!ErrNode)
680*67e74705SXin Li return false;
681*67e74705SXin Li
682*67e74705SXin Li std::string Buf;
683*67e74705SXin Li llvm::raw_string_ostream OS(Buf);
684*67e74705SXin Li
685*67e74705SXin Li assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Weak ||
686*67e74705SXin Li (PropDecl->getSetterKind() == ObjCPropertyDecl::Assign &&
687*67e74705SXin Li !PropDecl->isReadOnly()) ||
688*67e74705SXin Li isReleasedByCIFilterDealloc(PropImpl)
689*67e74705SXin Li );
690*67e74705SXin Li
691*67e74705SXin Li const ObjCImplDecl *Container = getContainingObjCImpl(C.getLocationContext());
692*67e74705SXin Li OS << "The '" << *PropImpl->getPropertyIvarDecl()
693*67e74705SXin Li << "' ivar in '" << *Container;
694*67e74705SXin Li
695*67e74705SXin Li
696*67e74705SXin Li if (isReleasedByCIFilterDealloc(PropImpl)) {
697*67e74705SXin Li OS << "' will be released by '-[CIFilter dealloc]' but also released here";
698*67e74705SXin Li } else {
699*67e74705SXin Li OS << "' was synthesized for ";
700*67e74705SXin Li
701*67e74705SXin Li if (PropDecl->getSetterKind() == ObjCPropertyDecl::Weak)
702*67e74705SXin Li OS << "a weak";
703*67e74705SXin Li else
704*67e74705SXin Li OS << "an assign, readwrite";
705*67e74705SXin Li
706*67e74705SXin Li OS << " property but was released in 'dealloc'";
707*67e74705SXin Li }
708*67e74705SXin Li
709*67e74705SXin Li std::unique_ptr<BugReport> BR(
710*67e74705SXin Li new BugReport(*ExtraReleaseBugType, OS.str(), ErrNode));
711*67e74705SXin Li BR->addRange(M.getOriginExpr()->getSourceRange());
712*67e74705SXin Li
713*67e74705SXin Li C.emitReport(std::move(BR));
714*67e74705SXin Li
715*67e74705SXin Li return true;
716*67e74705SXin Li }
717*67e74705SXin Li
718*67e74705SXin Li /// Emits a warning if the current context is -dealloc and DeallocedValue
719*67e74705SXin Li /// must not be directly dealloced in a -dealloc. Returns true if a diagnostic
720*67e74705SXin Li /// was emitted.
diagnoseMistakenDealloc(SymbolRef DeallocedValue,const ObjCMethodCall & M,CheckerContext & C) const721*67e74705SXin Li bool ObjCDeallocChecker::diagnoseMistakenDealloc(SymbolRef DeallocedValue,
722*67e74705SXin Li const ObjCMethodCall &M,
723*67e74705SXin Li CheckerContext &C) const {
724*67e74705SXin Li
725*67e74705SXin Li // Find the property backing the instance variable that M
726*67e74705SXin Li // is dealloc'ing.
727*67e74705SXin Li const ObjCPropertyImplDecl *PropImpl =
728*67e74705SXin Li findPropertyOnDeallocatingInstance(DeallocedValue, C);
729*67e74705SXin Li if (!PropImpl)
730*67e74705SXin Li return false;
731*67e74705SXin Li
732*67e74705SXin Li if (getDeallocReleaseRequirement(PropImpl) !=
733*67e74705SXin Li ReleaseRequirement::MustRelease) {
734*67e74705SXin Li return false;
735*67e74705SXin Li }
736*67e74705SXin Li
737*67e74705SXin Li ExplodedNode *ErrNode = C.generateErrorNode();
738*67e74705SXin Li if (!ErrNode)
739*67e74705SXin Li return false;
740*67e74705SXin Li
741*67e74705SXin Li std::string Buf;
742*67e74705SXin Li llvm::raw_string_ostream OS(Buf);
743*67e74705SXin Li
744*67e74705SXin Li OS << "'" << *PropImpl->getPropertyIvarDecl()
745*67e74705SXin Li << "' should be released rather than deallocated";
746*67e74705SXin Li
747*67e74705SXin Li std::unique_ptr<BugReport> BR(
748*67e74705SXin Li new BugReport(*MistakenDeallocBugType, OS.str(), ErrNode));
749*67e74705SXin Li BR->addRange(M.getOriginExpr()->getSourceRange());
750*67e74705SXin Li
751*67e74705SXin Li C.emitReport(std::move(BR));
752*67e74705SXin Li
753*67e74705SXin Li return true;
754*67e74705SXin Li }
755*67e74705SXin Li
ObjCDeallocChecker()756*67e74705SXin Li ObjCDeallocChecker::ObjCDeallocChecker()
757*67e74705SXin Li : NSObjectII(nullptr), SenTestCaseII(nullptr), XCTestCaseII(nullptr),
758*67e74705SXin Li CIFilterII(nullptr) {
759*67e74705SXin Li
760*67e74705SXin Li MissingReleaseBugType.reset(
761*67e74705SXin Li new BugType(this, "Missing ivar release (leak)",
762*67e74705SXin Li categories::MemoryCoreFoundationObjectiveC));
763*67e74705SXin Li
764*67e74705SXin Li ExtraReleaseBugType.reset(
765*67e74705SXin Li new BugType(this, "Extra ivar release",
766*67e74705SXin Li categories::MemoryCoreFoundationObjectiveC));
767*67e74705SXin Li
768*67e74705SXin Li MistakenDeallocBugType.reset(
769*67e74705SXin Li new BugType(this, "Mistaken dealloc",
770*67e74705SXin Li categories::MemoryCoreFoundationObjectiveC));
771*67e74705SXin Li }
772*67e74705SXin Li
initIdentifierInfoAndSelectors(ASTContext & Ctx) const773*67e74705SXin Li void ObjCDeallocChecker::initIdentifierInfoAndSelectors(
774*67e74705SXin Li ASTContext &Ctx) const {
775*67e74705SXin Li if (NSObjectII)
776*67e74705SXin Li return;
777*67e74705SXin Li
778*67e74705SXin Li NSObjectII = &Ctx.Idents.get("NSObject");
779*67e74705SXin Li SenTestCaseII = &Ctx.Idents.get("SenTestCase");
780*67e74705SXin Li XCTestCaseII = &Ctx.Idents.get("XCTestCase");
781*67e74705SXin Li Block_releaseII = &Ctx.Idents.get("_Block_release");
782*67e74705SXin Li CIFilterII = &Ctx.Idents.get("CIFilter");
783*67e74705SXin Li
784*67e74705SXin Li IdentifierInfo *DeallocII = &Ctx.Idents.get("dealloc");
785*67e74705SXin Li IdentifierInfo *ReleaseII = &Ctx.Idents.get("release");
786*67e74705SXin Li DeallocSel = Ctx.Selectors.getSelector(0, &DeallocII);
787*67e74705SXin Li ReleaseSel = Ctx.Selectors.getSelector(0, &ReleaseII);
788*67e74705SXin Li }
789*67e74705SXin Li
790*67e74705SXin Li /// Returns true if M is a call to '[super dealloc]'.
isSuperDeallocMessage(const ObjCMethodCall & M) const791*67e74705SXin Li bool ObjCDeallocChecker::isSuperDeallocMessage(
792*67e74705SXin Li const ObjCMethodCall &M) const {
793*67e74705SXin Li if (M.getOriginExpr()->getReceiverKind() != ObjCMessageExpr::SuperInstance)
794*67e74705SXin Li return false;
795*67e74705SXin Li
796*67e74705SXin Li return M.getSelector() == DeallocSel;
797*67e74705SXin Li }
798*67e74705SXin Li
799*67e74705SXin Li /// Returns the ObjCImplDecl containing the method declaration in LCtx.
800*67e74705SXin Li const ObjCImplDecl *
getContainingObjCImpl(const LocationContext * LCtx) const801*67e74705SXin Li ObjCDeallocChecker::getContainingObjCImpl(const LocationContext *LCtx) const {
802*67e74705SXin Li auto *MD = cast<ObjCMethodDecl>(LCtx->getDecl());
803*67e74705SXin Li return cast<ObjCImplDecl>(MD->getDeclContext());
804*67e74705SXin Li }
805*67e74705SXin Li
806*67e74705SXin Li /// Returns the property that shadowed by PropImpl if one exists and
807*67e74705SXin Li /// nullptr otherwise.
findShadowedPropertyDecl(const ObjCPropertyImplDecl * PropImpl) const808*67e74705SXin Li const ObjCPropertyDecl *ObjCDeallocChecker::findShadowedPropertyDecl(
809*67e74705SXin Li const ObjCPropertyImplDecl *PropImpl) const {
810*67e74705SXin Li const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
811*67e74705SXin Li
812*67e74705SXin Li // Only readwrite properties can shadow.
813*67e74705SXin Li if (PropDecl->isReadOnly())
814*67e74705SXin Li return nullptr;
815*67e74705SXin Li
816*67e74705SXin Li auto *CatDecl = dyn_cast<ObjCCategoryDecl>(PropDecl->getDeclContext());
817*67e74705SXin Li
818*67e74705SXin Li // Only class extensions can contain shadowing properties.
819*67e74705SXin Li if (!CatDecl || !CatDecl->IsClassExtension())
820*67e74705SXin Li return nullptr;
821*67e74705SXin Li
822*67e74705SXin Li IdentifierInfo *ID = PropDecl->getIdentifier();
823*67e74705SXin Li DeclContext::lookup_result R = CatDecl->getClassInterface()->lookup(ID);
824*67e74705SXin Li for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
825*67e74705SXin Li auto *ShadowedPropDecl = dyn_cast<ObjCPropertyDecl>(*I);
826*67e74705SXin Li if (!ShadowedPropDecl)
827*67e74705SXin Li continue;
828*67e74705SXin Li
829*67e74705SXin Li if (ShadowedPropDecl->isInstanceProperty()) {
830*67e74705SXin Li assert(ShadowedPropDecl->isReadOnly());
831*67e74705SXin Li return ShadowedPropDecl;
832*67e74705SXin Li }
833*67e74705SXin Li }
834*67e74705SXin Li
835*67e74705SXin Li return nullptr;
836*67e74705SXin Li }
837*67e74705SXin Li
838*67e74705SXin Li /// Add a transition noting the release of the given value.
transitionToReleaseValue(CheckerContext & C,SymbolRef Value) const839*67e74705SXin Li void ObjCDeallocChecker::transitionToReleaseValue(CheckerContext &C,
840*67e74705SXin Li SymbolRef Value) const {
841*67e74705SXin Li assert(Value);
842*67e74705SXin Li SymbolRef InstanceSym = getInstanceSymbolFromIvarSymbol(Value);
843*67e74705SXin Li if (!InstanceSym)
844*67e74705SXin Li return;
845*67e74705SXin Li ProgramStateRef InitialState = C.getState();
846*67e74705SXin Li
847*67e74705SXin Li ProgramStateRef ReleasedState =
848*67e74705SXin Li removeValueRequiringRelease(InitialState, InstanceSym, Value);
849*67e74705SXin Li
850*67e74705SXin Li if (ReleasedState != InitialState) {
851*67e74705SXin Li C.addTransition(ReleasedState);
852*67e74705SXin Li }
853*67e74705SXin Li }
854*67e74705SXin Li
855*67e74705SXin Li /// Remove the Value requiring a release from the tracked set for
856*67e74705SXin Li /// Instance and return the resultant state.
removeValueRequiringRelease(ProgramStateRef State,SymbolRef Instance,SymbolRef Value) const857*67e74705SXin Li ProgramStateRef ObjCDeallocChecker::removeValueRequiringRelease(
858*67e74705SXin Li ProgramStateRef State, SymbolRef Instance, SymbolRef Value) const {
859*67e74705SXin Li assert(Instance);
860*67e74705SXin Li assert(Value);
861*67e74705SXin Li const ObjCIvarRegion *RemovedRegion = getIvarRegionForIvarSymbol(Value);
862*67e74705SXin Li if (!RemovedRegion)
863*67e74705SXin Li return State;
864*67e74705SXin Li
865*67e74705SXin Li const SymbolSet *Unreleased = State->get<UnreleasedIvarMap>(Instance);
866*67e74705SXin Li if (!Unreleased)
867*67e74705SXin Li return State;
868*67e74705SXin Li
869*67e74705SXin Li // Mark the value as no longer requiring a release.
870*67e74705SXin Li SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
871*67e74705SXin Li SymbolSet NewUnreleased = *Unreleased;
872*67e74705SXin Li for (auto &Sym : *Unreleased) {
873*67e74705SXin Li const ObjCIvarRegion *UnreleasedRegion = getIvarRegionForIvarSymbol(Sym);
874*67e74705SXin Li assert(UnreleasedRegion);
875*67e74705SXin Li if (RemovedRegion->getDecl() == UnreleasedRegion->getDecl()) {
876*67e74705SXin Li NewUnreleased = F.remove(NewUnreleased, Sym);
877*67e74705SXin Li }
878*67e74705SXin Li }
879*67e74705SXin Li
880*67e74705SXin Li if (NewUnreleased.isEmpty()) {
881*67e74705SXin Li return State->remove<UnreleasedIvarMap>(Instance);
882*67e74705SXin Li }
883*67e74705SXin Li
884*67e74705SXin Li return State->set<UnreleasedIvarMap>(Instance, NewUnreleased);
885*67e74705SXin Li }
886*67e74705SXin Li
887*67e74705SXin Li /// Determines whether the instance variable for \p PropImpl must or must not be
888*67e74705SXin Li /// released in -dealloc or whether it cannot be determined.
getDeallocReleaseRequirement(const ObjCPropertyImplDecl * PropImpl) const889*67e74705SXin Li ReleaseRequirement ObjCDeallocChecker::getDeallocReleaseRequirement(
890*67e74705SXin Li const ObjCPropertyImplDecl *PropImpl) const {
891*67e74705SXin Li const ObjCIvarDecl *IvarDecl;
892*67e74705SXin Li const ObjCPropertyDecl *PropDecl;
893*67e74705SXin Li if (!isSynthesizedRetainableProperty(PropImpl, &IvarDecl, &PropDecl))
894*67e74705SXin Li return ReleaseRequirement::Unknown;
895*67e74705SXin Li
896*67e74705SXin Li ObjCPropertyDecl::SetterKind SK = PropDecl->getSetterKind();
897*67e74705SXin Li
898*67e74705SXin Li switch (SK) {
899*67e74705SXin Li // Retain and copy setters retain/copy their values before storing and so
900*67e74705SXin Li // the value in their instance variables must be released in -dealloc.
901*67e74705SXin Li case ObjCPropertyDecl::Retain:
902*67e74705SXin Li case ObjCPropertyDecl::Copy:
903*67e74705SXin Li if (isReleasedByCIFilterDealloc(PropImpl))
904*67e74705SXin Li return ReleaseRequirement::MustNotReleaseDirectly;
905*67e74705SXin Li
906*67e74705SXin Li return ReleaseRequirement::MustRelease;
907*67e74705SXin Li
908*67e74705SXin Li case ObjCPropertyDecl::Weak:
909*67e74705SXin Li return ReleaseRequirement::MustNotReleaseDirectly;
910*67e74705SXin Li
911*67e74705SXin Li case ObjCPropertyDecl::Assign:
912*67e74705SXin Li // It is common for the ivars for read-only assign properties to
913*67e74705SXin Li // always be stored retained, so their release requirement cannot be
914*67e74705SXin Li // be determined.
915*67e74705SXin Li if (PropDecl->isReadOnly())
916*67e74705SXin Li return ReleaseRequirement::Unknown;
917*67e74705SXin Li
918*67e74705SXin Li return ReleaseRequirement::MustNotReleaseDirectly;
919*67e74705SXin Li }
920*67e74705SXin Li llvm_unreachable("Unrecognized setter kind");
921*67e74705SXin Li }
922*67e74705SXin Li
923*67e74705SXin Li /// Returns the released value if M is a call a setter that releases
924*67e74705SXin Li /// and nils out its underlying instance variable.
925*67e74705SXin Li SymbolRef
getValueReleasedByNillingOut(const ObjCMethodCall & M,CheckerContext & C) const926*67e74705SXin Li ObjCDeallocChecker::getValueReleasedByNillingOut(const ObjCMethodCall &M,
927*67e74705SXin Li CheckerContext &C) const {
928*67e74705SXin Li SVal ReceiverVal = M.getReceiverSVal();
929*67e74705SXin Li if (!ReceiverVal.isValid())
930*67e74705SXin Li return nullptr;
931*67e74705SXin Li
932*67e74705SXin Li if (M.getNumArgs() == 0)
933*67e74705SXin Li return nullptr;
934*67e74705SXin Li
935*67e74705SXin Li if (!M.getArgExpr(0)->getType()->isObjCRetainableType())
936*67e74705SXin Li return nullptr;
937*67e74705SXin Li
938*67e74705SXin Li // Is the first argument nil?
939*67e74705SXin Li SVal Arg = M.getArgSVal(0);
940*67e74705SXin Li ProgramStateRef notNilState, nilState;
941*67e74705SXin Li std::tie(notNilState, nilState) =
942*67e74705SXin Li M.getState()->assume(Arg.castAs<DefinedOrUnknownSVal>());
943*67e74705SXin Li if (!(nilState && !notNilState))
944*67e74705SXin Li return nullptr;
945*67e74705SXin Li
946*67e74705SXin Li const ObjCPropertyDecl *Prop = M.getAccessedProperty();
947*67e74705SXin Li if (!Prop)
948*67e74705SXin Li return nullptr;
949*67e74705SXin Li
950*67e74705SXin Li ObjCIvarDecl *PropIvarDecl = Prop->getPropertyIvarDecl();
951*67e74705SXin Li if (!PropIvarDecl)
952*67e74705SXin Li return nullptr;
953*67e74705SXin Li
954*67e74705SXin Li ProgramStateRef State = C.getState();
955*67e74705SXin Li
956*67e74705SXin Li SVal LVal = State->getLValue(PropIvarDecl, ReceiverVal);
957*67e74705SXin Li Optional<Loc> LValLoc = LVal.getAs<Loc>();
958*67e74705SXin Li if (!LValLoc)
959*67e74705SXin Li return nullptr;
960*67e74705SXin Li
961*67e74705SXin Li SVal CurrentValInIvar = State->getSVal(LValLoc.getValue());
962*67e74705SXin Li return CurrentValInIvar.getAsSymbol();
963*67e74705SXin Li }
964*67e74705SXin Li
965*67e74705SXin Li /// Returns true if the current context is a call to -dealloc and false
966*67e74705SXin Li /// otherwise. If true, it also sets SelfValOut to the value of
967*67e74705SXin Li /// 'self'.
isInInstanceDealloc(const CheckerContext & C,SVal & SelfValOut) const968*67e74705SXin Li bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
969*67e74705SXin Li SVal &SelfValOut) const {
970*67e74705SXin Li return isInInstanceDealloc(C, C.getLocationContext(), SelfValOut);
971*67e74705SXin Li }
972*67e74705SXin Li
973*67e74705SXin Li /// Returns true if LCtx is a call to -dealloc and false
974*67e74705SXin Li /// otherwise. If true, it also sets SelfValOut to the value of
975*67e74705SXin Li /// 'self'.
isInInstanceDealloc(const CheckerContext & C,const LocationContext * LCtx,SVal & SelfValOut) const976*67e74705SXin Li bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
977*67e74705SXin Li const LocationContext *LCtx,
978*67e74705SXin Li SVal &SelfValOut) const {
979*67e74705SXin Li auto *MD = dyn_cast<ObjCMethodDecl>(LCtx->getDecl());
980*67e74705SXin Li if (!MD || !MD->isInstanceMethod() || MD->getSelector() != DeallocSel)
981*67e74705SXin Li return false;
982*67e74705SXin Li
983*67e74705SXin Li const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
984*67e74705SXin Li assert(SelfDecl && "No self in -dealloc?");
985*67e74705SXin Li
986*67e74705SXin Li ProgramStateRef State = C.getState();
987*67e74705SXin Li SelfValOut = State->getSVal(State->getRegion(SelfDecl, LCtx));
988*67e74705SXin Li return true;
989*67e74705SXin Li }
990*67e74705SXin Li
991*67e74705SXin Li /// Returns true if there is a call to -dealloc anywhere on the stack and false
992*67e74705SXin Li /// otherwise. If true, it also sets InstanceValOut to the value of
993*67e74705SXin Li /// 'self' in the frame for -dealloc.
instanceDeallocIsOnStack(const CheckerContext & C,SVal & InstanceValOut) const994*67e74705SXin Li bool ObjCDeallocChecker::instanceDeallocIsOnStack(const CheckerContext &C,
995*67e74705SXin Li SVal &InstanceValOut) const {
996*67e74705SXin Li const LocationContext *LCtx = C.getLocationContext();
997*67e74705SXin Li
998*67e74705SXin Li while (LCtx) {
999*67e74705SXin Li if (isInInstanceDealloc(C, LCtx, InstanceValOut))
1000*67e74705SXin Li return true;
1001*67e74705SXin Li
1002*67e74705SXin Li LCtx = LCtx->getParent();
1003*67e74705SXin Li }
1004*67e74705SXin Li
1005*67e74705SXin Li return false;
1006*67e74705SXin Li }
1007*67e74705SXin Li
1008*67e74705SXin Li /// Returns true if the ID is a class in which which is known to have
1009*67e74705SXin Li /// a separate teardown lifecycle. In this case, -dealloc warnings
1010*67e74705SXin Li /// about missing releases should be suppressed.
classHasSeparateTeardown(const ObjCInterfaceDecl * ID) const1011*67e74705SXin Li bool ObjCDeallocChecker::classHasSeparateTeardown(
1012*67e74705SXin Li const ObjCInterfaceDecl *ID) const {
1013*67e74705SXin Li // Suppress if the class is not a subclass of NSObject.
1014*67e74705SXin Li for ( ; ID ; ID = ID->getSuperClass()) {
1015*67e74705SXin Li IdentifierInfo *II = ID->getIdentifier();
1016*67e74705SXin Li
1017*67e74705SXin Li if (II == NSObjectII)
1018*67e74705SXin Li return false;
1019*67e74705SXin Li
1020*67e74705SXin Li // FIXME: For now, ignore classes that subclass SenTestCase and XCTestCase,
1021*67e74705SXin Li // as these don't need to implement -dealloc. They implement tear down in
1022*67e74705SXin Li // another way, which we should try and catch later.
1023*67e74705SXin Li // http://llvm.org/bugs/show_bug.cgi?id=3187
1024*67e74705SXin Li if (II == XCTestCaseII || II == SenTestCaseII)
1025*67e74705SXin Li return true;
1026*67e74705SXin Li }
1027*67e74705SXin Li
1028*67e74705SXin Li return true;
1029*67e74705SXin Li }
1030*67e74705SXin Li
1031*67e74705SXin Li /// The -dealloc method in CIFilter highly unusual in that is will release
1032*67e74705SXin Li /// instance variables belonging to its *subclasses* if the variable name
1033*67e74705SXin Li /// starts with "input" or backs a property whose name starts with "input".
1034*67e74705SXin Li /// Subclasses should not release these ivars in their own -dealloc method --
1035*67e74705SXin Li /// doing so could result in an over release.
1036*67e74705SXin Li ///
1037*67e74705SXin Li /// This method returns true if the property will be released by
1038*67e74705SXin Li /// -[CIFilter dealloc].
isReleasedByCIFilterDealloc(const ObjCPropertyImplDecl * PropImpl) const1039*67e74705SXin Li bool ObjCDeallocChecker::isReleasedByCIFilterDealloc(
1040*67e74705SXin Li const ObjCPropertyImplDecl *PropImpl) const {
1041*67e74705SXin Li assert(PropImpl->getPropertyIvarDecl());
1042*67e74705SXin Li StringRef PropName = PropImpl->getPropertyDecl()->getName();
1043*67e74705SXin Li StringRef IvarName = PropImpl->getPropertyIvarDecl()->getName();
1044*67e74705SXin Li
1045*67e74705SXin Li const char *ReleasePrefix = "input";
1046*67e74705SXin Li if (!(PropName.startswith(ReleasePrefix) ||
1047*67e74705SXin Li IvarName.startswith(ReleasePrefix))) {
1048*67e74705SXin Li return false;
1049*67e74705SXin Li }
1050*67e74705SXin Li
1051*67e74705SXin Li const ObjCInterfaceDecl *ID =
1052*67e74705SXin Li PropImpl->getPropertyIvarDecl()->getContainingInterface();
1053*67e74705SXin Li for ( ; ID ; ID = ID->getSuperClass()) {
1054*67e74705SXin Li IdentifierInfo *II = ID->getIdentifier();
1055*67e74705SXin Li if (II == CIFilterII)
1056*67e74705SXin Li return true;
1057*67e74705SXin Li }
1058*67e74705SXin Li
1059*67e74705SXin Li return false;
1060*67e74705SXin Li }
1061*67e74705SXin Li
registerObjCDeallocChecker(CheckerManager & Mgr)1062*67e74705SXin Li void ento::registerObjCDeallocChecker(CheckerManager &Mgr) {
1063*67e74705SXin Li const LangOptions &LangOpts = Mgr.getLangOpts();
1064*67e74705SXin Li // These checker only makes sense under MRR.
1065*67e74705SXin Li if (LangOpts.getGC() == LangOptions::GCOnly || LangOpts.ObjCAutoRefCount)
1066*67e74705SXin Li return;
1067*67e74705SXin Li
1068*67e74705SXin Li Mgr.registerChecker<ObjCDeallocChecker>();
1069*67e74705SXin Li }
1070