1d99bd55aSTed Kremenek //==- CheckObjCDealloc.cpp - Check ObjC -dealloc implementation --*- C++ -*-==//
2d99bd55aSTed Kremenek //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6d99bd55aSTed Kremenek //
7d99bd55aSTed Kremenek //===----------------------------------------------------------------------===//
8d99bd55aSTed Kremenek //
9ad9f53e9SDevin Coughlin //  This checker analyzes Objective-C -dealloc methods and their callees
10ad9f53e9SDevin Coughlin //  to warn about improper releasing of instance variables that back synthesized
11ad9f53e9SDevin Coughlin // properties. It warns about missing releases in the following cases:
12ad9f53e9SDevin Coughlin //  - When a class has a synthesized instance variable for a 'retain' or 'copy'
13ad9f53e9SDevin Coughlin //    property and lacks a -dealloc method in its implementation.
14ad9f53e9SDevin Coughlin //  - When a class has a synthesized instance variable for a 'retain'/'copy'
15ad9f53e9SDevin Coughlin //   property but the ivar is not released in -dealloc by either -release
16ad9f53e9SDevin Coughlin //   or by nilling out the property.
17ad9f53e9SDevin Coughlin //
18ad9f53e9SDevin Coughlin //  It warns about extra releases in -dealloc (but not in callees) when a
19ad9f53e9SDevin Coughlin //  synthesized instance variable is released in the following cases:
20ad9f53e9SDevin Coughlin //  - When the property is 'assign' and is not 'readonly'.
21ad9f53e9SDevin Coughlin //  - When the property is 'weak'.
22ad9f53e9SDevin Coughlin //
23ad9f53e9SDevin Coughlin //  This checker only warns for instance variables synthesized to back
24ad9f53e9SDevin Coughlin //  properties. Handling the more general case would require inferring whether
25ad9f53e9SDevin Coughlin //  an instance variable is stored retained or not. For synthesized properties,
26ad9f53e9SDevin Coughlin //  this is specified in the property declaration itself.
27d99bd55aSTed Kremenek //
28d99bd55aSTed Kremenek //===----------------------------------------------------------------------===//
29d99bd55aSTed Kremenek 
3076a21502SKristof Umann #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
31f0bb45faSArtem Dergachev #include "clang/Analysis/PathDiagnostic.h"
32ea70eb30SBenjamin Kramer #include "clang/AST/Attr.h"
33d99bd55aSTed Kremenek #include "clang/AST/DeclObjC.h"
34ea70eb30SBenjamin Kramer #include "clang/AST/Expr.h"
35ea70eb30SBenjamin Kramer #include "clang/AST/ExprObjC.h"
36d99bd55aSTed Kremenek #include "clang/Basic/LangOptions.h"
370bd37a1aSDevin Coughlin #include "clang/Basic/TargetInfo.h"
383a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
39ad9f53e9SDevin Coughlin #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
403a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/Checker.h"
413a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
42ad9f53e9SDevin Coughlin #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
43ad9f53e9SDevin Coughlin #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
44ad9f53e9SDevin Coughlin #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
45ad9f53e9SDevin Coughlin #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
46ad9f53e9SDevin Coughlin #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
47d99bd55aSTed Kremenek #include "llvm/Support/raw_ostream.h"
48d99bd55aSTed Kremenek 
49d99bd55aSTed Kremenek using namespace clang;
50d99bd55aSTed Kremenek using namespace ento;
51d99bd55aSTed Kremenek 
52ad9f53e9SDevin Coughlin /// Indicates whether an instance variable is required to be released in
53ad9f53e9SDevin Coughlin /// -dealloc.
54ad9f53e9SDevin Coughlin enum class ReleaseRequirement {
55ad9f53e9SDevin Coughlin   /// The instance variable must be released, either by calling
56ad9f53e9SDevin Coughlin   /// -release on it directly or by nilling it out with a property setter.
57ad9f53e9SDevin Coughlin   MustRelease,
58982c42daSDevin Coughlin 
59ad9f53e9SDevin Coughlin   /// The instance variable must not be directly released with -release.
60ad9f53e9SDevin Coughlin   MustNotReleaseDirectly,
61d99bd55aSTed Kremenek 
62ad9f53e9SDevin Coughlin   /// The requirement for the instance variable could not be determined.
63ad9f53e9SDevin Coughlin   Unknown
64ad9f53e9SDevin Coughlin };
65d99bd55aSTed Kremenek 
66ad9f53e9SDevin Coughlin /// Returns true if the property implementation is synthesized and the
67ad9f53e9SDevin Coughlin /// type of the property is retainable.
isSynthesizedRetainableProperty(const ObjCPropertyImplDecl * I,const ObjCIvarDecl ** ID,const ObjCPropertyDecl ** PD)6830751347SDevin Coughlin static bool isSynthesizedRetainableProperty(const ObjCPropertyImplDecl *I,
6930751347SDevin Coughlin                                             const ObjCIvarDecl **ID,
7030751347SDevin Coughlin                                             const ObjCPropertyDecl **PD) {
7130751347SDevin Coughlin 
7230751347SDevin Coughlin   if (I->getPropertyImplementation() != ObjCPropertyImplDecl::Synthesize)
7330751347SDevin Coughlin     return false;
7430751347SDevin Coughlin 
7530751347SDevin Coughlin   (*ID) = I->getPropertyIvarDecl();
7630751347SDevin Coughlin   if (!(*ID))
7730751347SDevin Coughlin     return false;
7830751347SDevin Coughlin 
7930751347SDevin Coughlin   QualType T = (*ID)->getType();
8030751347SDevin Coughlin   if (!T->isObjCRetainableType())
8130751347SDevin Coughlin     return false;
8230751347SDevin Coughlin 
8330751347SDevin Coughlin   (*PD) = I->getPropertyDecl();
8430751347SDevin Coughlin   // Shouldn't be able to synthesize a property that doesn't exist.
8530751347SDevin Coughlin   assert(*PD);
8630751347SDevin Coughlin 
8730751347SDevin Coughlin   return true;
8830751347SDevin Coughlin }
8930751347SDevin Coughlin 
90ad9f53e9SDevin Coughlin namespace {
91ad9f53e9SDevin Coughlin 
92ad9f53e9SDevin Coughlin class ObjCDeallocChecker
93ad9f53e9SDevin Coughlin     : public Checker<check::ASTDecl<ObjCImplementationDecl>,
94ad9f53e9SDevin Coughlin                      check::PreObjCMessage, check::PostObjCMessage,
9509359493SDevin Coughlin                      check::PreCall,
96ad9f53e9SDevin Coughlin                      check::BeginFunction, check::EndFunction,
973fc67e47SDevin Coughlin                      eval::Assume,
98ad9f53e9SDevin Coughlin                      check::PointerEscape,
99ad9f53e9SDevin Coughlin                      check::PreStmt<ReturnStmt>> {
100ad9f53e9SDevin Coughlin 
1019d5057ccSDevin Coughlin   mutable IdentifierInfo *NSObjectII, *SenTestCaseII, *XCTestCaseII,
1029d5057ccSDevin Coughlin       *Block_releaseII, *CIFilterII;
1039d5057ccSDevin Coughlin 
104ad9f53e9SDevin Coughlin   mutable Selector DeallocSel, ReleaseSel;
105ad9f53e9SDevin Coughlin 
106ad9f53e9SDevin Coughlin   std::unique_ptr<BugType> MissingReleaseBugType;
107ad9f53e9SDevin Coughlin   std::unique_ptr<BugType> ExtraReleaseBugType;
108a6046798SDevin Coughlin   std::unique_ptr<BugType> MistakenDeallocBugType;
109ad9f53e9SDevin Coughlin 
110ad9f53e9SDevin Coughlin public:
111ad9f53e9SDevin Coughlin   ObjCDeallocChecker();
112ad9f53e9SDevin Coughlin 
113ad9f53e9SDevin Coughlin   void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
114ad9f53e9SDevin Coughlin                     BugReporter &BR) const;
115ad9f53e9SDevin Coughlin   void checkBeginFunction(CheckerContext &Ctx) const;
116ad9f53e9SDevin Coughlin   void checkPreObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
11709359493SDevin Coughlin   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
118ad9f53e9SDevin Coughlin   void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
119ad9f53e9SDevin Coughlin 
1203fc67e47SDevin Coughlin   ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
1213fc67e47SDevin Coughlin                              bool Assumption) const;
1223fc67e47SDevin Coughlin 
123ad9f53e9SDevin Coughlin   ProgramStateRef checkPointerEscape(ProgramStateRef State,
124ad9f53e9SDevin Coughlin                                      const InvalidatedSymbols &Escaped,
125ad9f53e9SDevin Coughlin                                      const CallEvent *Call,
126ad9f53e9SDevin Coughlin                                      PointerEscapeKind Kind) const;
127ad9f53e9SDevin Coughlin   void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
128ed8c05ccSReka Kovacs   void checkEndFunction(const ReturnStmt *RS, CheckerContext &Ctx) const;
129ad9f53e9SDevin Coughlin 
130ad9f53e9SDevin Coughlin private:
131ad9f53e9SDevin Coughlin   void diagnoseMissingReleases(CheckerContext &C) const;
132ad9f53e9SDevin Coughlin 
133ad9f53e9SDevin Coughlin   bool diagnoseExtraRelease(SymbolRef ReleasedValue, const ObjCMethodCall &M,
134ad9f53e9SDevin Coughlin                             CheckerContext &C) const;
135ad9f53e9SDevin Coughlin 
136a6046798SDevin Coughlin   bool diagnoseMistakenDealloc(SymbolRef DeallocedValue,
137a6046798SDevin Coughlin                                const ObjCMethodCall &M,
138ad9f53e9SDevin Coughlin                                CheckerContext &C) const;
139a6046798SDevin Coughlin 
140ad9f53e9SDevin Coughlin   SymbolRef getValueReleasedByNillingOut(const ObjCMethodCall &M,
141ad9f53e9SDevin Coughlin                                          CheckerContext &C) const;
142ad9f53e9SDevin Coughlin 
1433fc67e47SDevin Coughlin   const ObjCIvarRegion *getIvarRegionForIvarSymbol(SymbolRef IvarSym) const;
144ad9f53e9SDevin Coughlin   SymbolRef getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const;
145ad9f53e9SDevin Coughlin 
146a6046798SDevin Coughlin   const ObjCPropertyImplDecl*
147a6046798SDevin Coughlin   findPropertyOnDeallocatingInstance(SymbolRef IvarSym,
148a6046798SDevin Coughlin                                      CheckerContext &C) const;
149a6046798SDevin Coughlin 
150ad9f53e9SDevin Coughlin   ReleaseRequirement
151ad9f53e9SDevin Coughlin   getDeallocReleaseRequirement(const ObjCPropertyImplDecl *PropImpl) const;
152ad9f53e9SDevin Coughlin 
153ad9f53e9SDevin Coughlin   bool isInInstanceDealloc(const CheckerContext &C, SVal &SelfValOut) const;
154ad9f53e9SDevin Coughlin   bool isInInstanceDealloc(const CheckerContext &C, const LocationContext *LCtx,
155ad9f53e9SDevin Coughlin                            SVal &SelfValOut) const;
156ad9f53e9SDevin Coughlin   bool instanceDeallocIsOnStack(const CheckerContext &C,
157ad9f53e9SDevin Coughlin                                 SVal &InstanceValOut) const;
158ad9f53e9SDevin Coughlin 
159ad9f53e9SDevin Coughlin   bool isSuperDeallocMessage(const ObjCMethodCall &M) const;
160ad9f53e9SDevin Coughlin 
161ad9f53e9SDevin Coughlin   const ObjCImplDecl *getContainingObjCImpl(const LocationContext *LCtx) const;
162ad9f53e9SDevin Coughlin 
163ad9f53e9SDevin Coughlin   const ObjCPropertyDecl *
164ad9f53e9SDevin Coughlin   findShadowedPropertyDecl(const ObjCPropertyImplDecl *PropImpl) const;
165ad9f53e9SDevin Coughlin 
16609359493SDevin Coughlin   void transitionToReleaseValue(CheckerContext &C, SymbolRef Value) const;
167ad9f53e9SDevin Coughlin   ProgramStateRef removeValueRequiringRelease(ProgramStateRef State,
168ad9f53e9SDevin Coughlin                                               SymbolRef InstanceSym,
169ad9f53e9SDevin Coughlin                                               SymbolRef ValueSym) const;
170ad9f53e9SDevin Coughlin 
171ad9f53e9SDevin Coughlin   void initIdentifierInfoAndSelectors(ASTContext &Ctx) const;
172ad9f53e9SDevin Coughlin 
173ad9f53e9SDevin Coughlin   bool classHasSeparateTeardown(const ObjCInterfaceDecl *ID) const;
174b8076292SDevin Coughlin 
175b8076292SDevin Coughlin   bool isReleasedByCIFilterDealloc(const ObjCPropertyImplDecl *PropImpl) const;
1760bd37a1aSDevin Coughlin   bool isNibLoadedIvarWithoutRetain(const ObjCPropertyImplDecl *PropImpl) const;
177ad9f53e9SDevin Coughlin };
178ad9f53e9SDevin Coughlin } // End anonymous namespace.
179ad9f53e9SDevin Coughlin 
180ad9f53e9SDevin Coughlin 
181ad9f53e9SDevin Coughlin /// Maps from the symbol for a class instance to the set of
182ad9f53e9SDevin Coughlin /// symbols remaining that must be released in -dealloc.
REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(SymbolSet,SymbolRef)183579cf903SArtem Dergachev REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(SymbolSet, SymbolRef)
184ad9f53e9SDevin Coughlin REGISTER_MAP_WITH_PROGRAMSTATE(UnreleasedIvarMap, SymbolRef, SymbolSet)
185ad9f53e9SDevin Coughlin 
18630751347SDevin Coughlin 
187ad9f53e9SDevin Coughlin /// An AST check that diagnose when the class requires a -dealloc method and
188ad9f53e9SDevin Coughlin /// is missing one.
189ad9f53e9SDevin Coughlin void ObjCDeallocChecker::checkASTDecl(const ObjCImplementationDecl *D,
190ad9f53e9SDevin Coughlin                                       AnalysisManager &Mgr,
191ad9f53e9SDevin Coughlin                                       BugReporter &BR) const {
192ad9f53e9SDevin Coughlin   assert(Mgr.getLangOpts().getGC() != LangOptions::GCOnly);
193ad9f53e9SDevin Coughlin   assert(!Mgr.getLangOpts().ObjCAutoRefCount);
194ad9f53e9SDevin Coughlin   initIdentifierInfoAndSelectors(Mgr.getASTContext());
195d99bd55aSTed Kremenek 
196d99bd55aSTed Kremenek   const ObjCInterfaceDecl *ID = D->getClassInterface();
197ad9f53e9SDevin Coughlin   // If the class is known to have a lifecycle with a separate teardown method
198ad9f53e9SDevin Coughlin   // then it may not require a -dealloc method.
199ad9f53e9SDevin Coughlin   if (classHasSeparateTeardown(ID))
20088691c1fSDevin Coughlin     return;
20188691c1fSDevin Coughlin 
2026d0c8a03SDevin Coughlin   // Does the class contain any synthesized properties that are retainable?
2036d0c8a03SDevin Coughlin   // If not, skip the check entirely.
2046d0c8a03SDevin Coughlin   const ObjCPropertyImplDecl *PropImplRequiringRelease = nullptr;
2056d0c8a03SDevin Coughlin   bool HasOthers = false;
2066d0c8a03SDevin Coughlin   for (const auto *I : D->property_impls()) {
2076d0c8a03SDevin Coughlin     if (getDeallocReleaseRequirement(I) == ReleaseRequirement::MustRelease) {
2086d0c8a03SDevin Coughlin       if (!PropImplRequiringRelease)
2096d0c8a03SDevin Coughlin         PropImplRequiringRelease = I;
2106d0c8a03SDevin Coughlin       else {
2116d0c8a03SDevin Coughlin         HasOthers = true;
2126d0c8a03SDevin Coughlin         break;
2136d0c8a03SDevin Coughlin       }
2146d0c8a03SDevin Coughlin     }
2156d0c8a03SDevin Coughlin   }
2166d0c8a03SDevin Coughlin 
2176d0c8a03SDevin Coughlin   if (!PropImplRequiringRelease)
2186d0c8a03SDevin Coughlin     return;
2196d0c8a03SDevin Coughlin 
220ea02bba5SDevin Coughlin   const ObjCMethodDecl *MD = nullptr;
221ea02bba5SDevin Coughlin 
222ea02bba5SDevin Coughlin   // Scan the instance methods for "dealloc".
223ea02bba5SDevin Coughlin   for (const auto *I : D->instance_methods()) {
224ad9f53e9SDevin Coughlin     if (I->getSelector() == DeallocSel) {
225ea02bba5SDevin Coughlin       MD = I;
226ea02bba5SDevin Coughlin       break;
227ea02bba5SDevin Coughlin     }
228ea02bba5SDevin Coughlin   }
229ea02bba5SDevin Coughlin 
230ea02bba5SDevin Coughlin   if (!MD) { // No dealloc found.
231ad9f53e9SDevin Coughlin     const char* Name = "Missing -dealloc";
232ea02bba5SDevin Coughlin 
233ad9f53e9SDevin Coughlin     std::string Buf;
234ad9f53e9SDevin Coughlin     llvm::raw_string_ostream OS(Buf);
2356d0c8a03SDevin Coughlin     OS << "'" << *D << "' lacks a 'dealloc' instance method but "
2366d0c8a03SDevin Coughlin        << "must release '" << *PropImplRequiringRelease->getPropertyIvarDecl()
2376d0c8a03SDevin Coughlin        << "'";
238ea02bba5SDevin Coughlin 
2396d0c8a03SDevin Coughlin     if (HasOthers)
2406d0c8a03SDevin Coughlin       OS << " and others";
241ea02bba5SDevin Coughlin     PathDiagnosticLocation DLoc =
242ea02bba5SDevin Coughlin         PathDiagnosticLocation::createBegin(D, BR.getSourceManager());
243ea02bba5SDevin Coughlin 
244ad9f53e9SDevin Coughlin     BR.EmitBasicReport(D, this, Name, categories::CoreFoundationObjectiveC,
245ad9f53e9SDevin Coughlin                        OS.str(), DLoc);
246ea02bba5SDevin Coughlin     return;
247ea02bba5SDevin Coughlin   }
248ad9f53e9SDevin Coughlin }
249ea02bba5SDevin Coughlin 
250ad9f53e9SDevin Coughlin /// If this is the beginning of -dealloc, mark the values initially stored in
251ad9f53e9SDevin Coughlin /// instance variables that must be released by the end of -dealloc
252ad9f53e9SDevin Coughlin /// as unreleased in the state.
checkBeginFunction(CheckerContext & C) const253ad9f53e9SDevin Coughlin void ObjCDeallocChecker::checkBeginFunction(
254ad9f53e9SDevin Coughlin     CheckerContext &C) const {
255ad9f53e9SDevin Coughlin   initIdentifierInfoAndSelectors(C.getASTContext());
256ea02bba5SDevin Coughlin 
257ad9f53e9SDevin Coughlin   // Only do this if the current method is -dealloc.
258ad9f53e9SDevin Coughlin   SVal SelfVal;
259ad9f53e9SDevin Coughlin   if (!isInInstanceDealloc(C, SelfVal))
260ad9f53e9SDevin Coughlin     return;
261ea02bba5SDevin Coughlin 
262ad9f53e9SDevin Coughlin   SymbolRef SelfSymbol = SelfVal.getAsSymbol();
263ad9f53e9SDevin Coughlin 
264ad9f53e9SDevin Coughlin   const LocationContext *LCtx = C.getLocationContext();
265ad9f53e9SDevin Coughlin   ProgramStateRef InitialState = C.getState();
266ad9f53e9SDevin Coughlin 
267ad9f53e9SDevin Coughlin   ProgramStateRef State = InitialState;
268ad9f53e9SDevin Coughlin 
269ad9f53e9SDevin Coughlin   SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
270ad9f53e9SDevin Coughlin 
271ad9f53e9SDevin Coughlin   // Symbols that must be released by the end of the -dealloc;
272ad9f53e9SDevin Coughlin   SymbolSet RequiredReleases = F.getEmptySet();
273ad9f53e9SDevin Coughlin 
274ad9f53e9SDevin Coughlin   // If we're an inlined -dealloc, we should add our symbols to the existing
275ad9f53e9SDevin Coughlin   // set from our subclass.
276ad9f53e9SDevin Coughlin   if (const SymbolSet *CurrSet = State->get<UnreleasedIvarMap>(SelfSymbol))
277ad9f53e9SDevin Coughlin     RequiredReleases = *CurrSet;
278ad9f53e9SDevin Coughlin 
279ad9f53e9SDevin Coughlin   for (auto *PropImpl : getContainingObjCImpl(LCtx)->property_impls()) {
280ad9f53e9SDevin Coughlin     ReleaseRequirement Requirement = getDeallocReleaseRequirement(PropImpl);
281ad9f53e9SDevin Coughlin     if (Requirement != ReleaseRequirement::MustRelease)
282ea02bba5SDevin Coughlin       continue;
283ea02bba5SDevin Coughlin 
284ad9f53e9SDevin Coughlin     SVal LVal = State->getLValue(PropImpl->getPropertyIvarDecl(), SelfVal);
285ad9f53e9SDevin Coughlin     Optional<Loc> LValLoc = LVal.getAs<Loc>();
286ad9f53e9SDevin Coughlin     if (!LValLoc)
287ad9f53e9SDevin Coughlin       continue;
288ea02bba5SDevin Coughlin 
289*ca4af13eSKazu Hirata     SVal InitialVal = State->getSVal(*LValLoc);
290ad9f53e9SDevin Coughlin     SymbolRef Symbol = InitialVal.getAsSymbol();
291ad9f53e9SDevin Coughlin     if (!Symbol || !isa<SymbolRegionValue>(Symbol))
292ad9f53e9SDevin Coughlin       continue;
293ea02bba5SDevin Coughlin 
294ad9f53e9SDevin Coughlin     // Mark the value as requiring a release.
295ad9f53e9SDevin Coughlin     RequiredReleases = F.add(RequiredReleases, Symbol);
296ad9f53e9SDevin Coughlin   }
297ad9f53e9SDevin Coughlin 
298ad9f53e9SDevin Coughlin   if (!RequiredReleases.isEmpty()) {
299ad9f53e9SDevin Coughlin     State = State->set<UnreleasedIvarMap>(SelfSymbol, RequiredReleases);
300ad9f53e9SDevin Coughlin   }
301ad9f53e9SDevin Coughlin 
302ad9f53e9SDevin Coughlin   if (State != InitialState) {
303ad9f53e9SDevin Coughlin     C.addTransition(State);
304ad9f53e9SDevin Coughlin   }
305ad9f53e9SDevin Coughlin }
306ad9f53e9SDevin Coughlin 
3073fc67e47SDevin Coughlin /// Given a symbol for an ivar, return the ivar region it was loaded from.
3083fc67e47SDevin Coughlin /// Returns nullptr if the instance symbol cannot be found.
3093fc67e47SDevin Coughlin const ObjCIvarRegion *
getIvarRegionForIvarSymbol(SymbolRef IvarSym) const3103fc67e47SDevin Coughlin ObjCDeallocChecker::getIvarRegionForIvarSymbol(SymbolRef IvarSym) const {
31150aece03SArtem Dergachev   return dyn_cast_or_null<ObjCIvarRegion>(IvarSym->getOriginRegion());
3123fc67e47SDevin Coughlin }
3133fc67e47SDevin Coughlin 
314ad9f53e9SDevin Coughlin /// Given a symbol for an ivar, return a symbol for the instance containing
315ad9f53e9SDevin Coughlin /// the ivar. Returns nullptr if the instance symbol cannot be found.
316ad9f53e9SDevin Coughlin SymbolRef
getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const317ad9f53e9SDevin Coughlin ObjCDeallocChecker::getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const {
3183fc67e47SDevin Coughlin 
3193fc67e47SDevin Coughlin   const ObjCIvarRegion *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
320ad9f53e9SDevin Coughlin   if (!IvarRegion)
321ad9f53e9SDevin Coughlin     return nullptr;
322ad9f53e9SDevin Coughlin 
323ad9f53e9SDevin Coughlin   return IvarRegion->getSymbolicBase()->getSymbol();
324ad9f53e9SDevin Coughlin }
325ad9f53e9SDevin Coughlin 
326ad9f53e9SDevin Coughlin /// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
327ad9f53e9SDevin Coughlin /// a release or a nilling-out property setter.
checkPreObjCMessage(const ObjCMethodCall & M,CheckerContext & C) const328ad9f53e9SDevin Coughlin void ObjCDeallocChecker::checkPreObjCMessage(
329ad9f53e9SDevin Coughlin     const ObjCMethodCall &M, CheckerContext &C) const {
330ad9f53e9SDevin Coughlin   // Only run if -dealloc is on the stack.
331ad9f53e9SDevin Coughlin   SVal DeallocedInstance;
332ad9f53e9SDevin Coughlin   if (!instanceDeallocIsOnStack(C, DeallocedInstance))
333ad9f53e9SDevin Coughlin     return;
334ad9f53e9SDevin Coughlin 
335a6046798SDevin Coughlin   SymbolRef ReleasedValue = nullptr;
336a6046798SDevin Coughlin 
337a6046798SDevin Coughlin   if (M.getSelector() == ReleaseSel) {
338a6046798SDevin Coughlin     ReleasedValue = M.getReceiverSVal().getAsSymbol();
339a6046798SDevin Coughlin   } else if (M.getSelector() == DeallocSel && !M.isReceiverSelfOrSuper()) {
340a6046798SDevin Coughlin     if (diagnoseMistakenDealloc(M.getReceiverSVal().getAsSymbol(), M, C))
341a6046798SDevin Coughlin       return;
342a6046798SDevin Coughlin   }
343ad9f53e9SDevin Coughlin 
344ad9f53e9SDevin Coughlin   if (ReleasedValue) {
345ad9f53e9SDevin Coughlin     // An instance variable symbol was released with -release:
346ad9f53e9SDevin Coughlin     //    [_property release];
347ad9f53e9SDevin Coughlin     if (diagnoseExtraRelease(ReleasedValue,M, C))
348ad9f53e9SDevin Coughlin       return;
349ea02bba5SDevin Coughlin   } else {
350ad9f53e9SDevin Coughlin     // An instance variable symbol was released nilling out its property:
351ad9f53e9SDevin Coughlin     //    self.property = nil;
352ad9f53e9SDevin Coughlin     ReleasedValue = getValueReleasedByNillingOut(M, C);
353ad9f53e9SDevin Coughlin   }
354ad9f53e9SDevin Coughlin 
355ad9f53e9SDevin Coughlin   if (!ReleasedValue)
356ad9f53e9SDevin Coughlin     return;
357ad9f53e9SDevin Coughlin 
35809359493SDevin Coughlin   transitionToReleaseValue(C, ReleasedValue);
35909359493SDevin Coughlin }
36009359493SDevin Coughlin 
36109359493SDevin Coughlin /// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
36209359493SDevin Coughlin /// call to Block_release().
checkPreCall(const CallEvent & Call,CheckerContext & C) const36309359493SDevin Coughlin void ObjCDeallocChecker::checkPreCall(const CallEvent &Call,
36409359493SDevin Coughlin                                       CheckerContext &C) const {
36509359493SDevin Coughlin   const IdentifierInfo *II = Call.getCalleeIdentifier();
36609359493SDevin Coughlin   if (II != Block_releaseII)
367ad9f53e9SDevin Coughlin     return;
368ad9f53e9SDevin Coughlin 
36909359493SDevin Coughlin   if (Call.getNumArgs() != 1)
37009359493SDevin Coughlin     return;
371ad9f53e9SDevin Coughlin 
37209359493SDevin Coughlin   SymbolRef ReleasedValue = Call.getArgSVal(0).getAsSymbol();
37309359493SDevin Coughlin   if (!ReleasedValue)
37409359493SDevin Coughlin     return;
37509359493SDevin Coughlin 
37609359493SDevin Coughlin   transitionToReleaseValue(C, ReleasedValue);
377ad9f53e9SDevin Coughlin }
378ad9f53e9SDevin Coughlin /// If the message was a call to '[super dealloc]', diagnose any missing
379ad9f53e9SDevin Coughlin /// releases.
checkPostObjCMessage(const ObjCMethodCall & M,CheckerContext & C) const380ad9f53e9SDevin Coughlin void ObjCDeallocChecker::checkPostObjCMessage(
381ad9f53e9SDevin Coughlin     const ObjCMethodCall &M, CheckerContext &C) const {
382ad9f53e9SDevin Coughlin   // We perform this check post-message so that if the super -dealloc
383ad9f53e9SDevin Coughlin   // calls a helper method and that this class overrides, any ivars released in
384ad9f53e9SDevin Coughlin   // the helper method will be recorded before checking.
385ad9f53e9SDevin Coughlin   if (isSuperDeallocMessage(M))
386ad9f53e9SDevin Coughlin     diagnoseMissingReleases(C);
387ad9f53e9SDevin Coughlin }
388ad9f53e9SDevin Coughlin 
389ad9f53e9SDevin Coughlin /// Check for missing releases even when -dealloc does not call
390ad9f53e9SDevin Coughlin /// '[super dealloc]'.
checkEndFunction(const ReturnStmt * RS,CheckerContext & C) const391ad9f53e9SDevin Coughlin void ObjCDeallocChecker::checkEndFunction(
392ed8c05ccSReka Kovacs     const ReturnStmt *RS, CheckerContext &C) const {
393ad9f53e9SDevin Coughlin   diagnoseMissingReleases(C);
394ad9f53e9SDevin Coughlin }
395ad9f53e9SDevin Coughlin 
396ad9f53e9SDevin Coughlin /// Check for missing releases on early return.
checkPreStmt(const ReturnStmt * RS,CheckerContext & C) const397ad9f53e9SDevin Coughlin void ObjCDeallocChecker::checkPreStmt(
398ad9f53e9SDevin Coughlin     const ReturnStmt *RS, CheckerContext &C) const {
399ad9f53e9SDevin Coughlin   diagnoseMissingReleases(C);
400ad9f53e9SDevin Coughlin }
401ad9f53e9SDevin Coughlin 
4023fc67e47SDevin Coughlin /// When a symbol is assumed to be nil, remove it from the set of symbols
4033fc67e47SDevin Coughlin /// require to be nil.
evalAssume(ProgramStateRef State,SVal Cond,bool Assumption) const4043fc67e47SDevin Coughlin ProgramStateRef ObjCDeallocChecker::evalAssume(ProgramStateRef State, SVal Cond,
4053fc67e47SDevin Coughlin                                                bool Assumption) const {
4063fc67e47SDevin Coughlin   if (State->get<UnreleasedIvarMap>().isEmpty())
4073fc67e47SDevin Coughlin     return State;
4083fc67e47SDevin Coughlin 
40986e1b735SDenys Petrov   auto *CondBSE = dyn_cast_or_null<BinarySymExpr>(Cond.getAsSymbol());
4103fc67e47SDevin Coughlin   if (!CondBSE)
4113fc67e47SDevin Coughlin     return State;
4123fc67e47SDevin Coughlin 
4133fc67e47SDevin Coughlin   BinaryOperator::Opcode OpCode = CondBSE->getOpcode();
4143fc67e47SDevin Coughlin   if (Assumption) {
4153fc67e47SDevin Coughlin     if (OpCode != BO_EQ)
4163fc67e47SDevin Coughlin       return State;
4173fc67e47SDevin Coughlin   } else {
4183fc67e47SDevin Coughlin     if (OpCode != BO_NE)
4193fc67e47SDevin Coughlin       return State;
4203fc67e47SDevin Coughlin   }
4213fc67e47SDevin Coughlin 
4223fc67e47SDevin Coughlin   SymbolRef NullSymbol = nullptr;
4233fc67e47SDevin Coughlin   if (auto *SIE = dyn_cast<SymIntExpr>(CondBSE)) {
4243fc67e47SDevin Coughlin     const llvm::APInt &RHS = SIE->getRHS();
4253fc67e47SDevin Coughlin     if (RHS != 0)
4263fc67e47SDevin Coughlin       return State;
4273fc67e47SDevin Coughlin     NullSymbol = SIE->getLHS();
4283fc67e47SDevin Coughlin   } else if (auto *SIE = dyn_cast<IntSymExpr>(CondBSE)) {
4293fc67e47SDevin Coughlin     const llvm::APInt &LHS = SIE->getLHS();
4303fc67e47SDevin Coughlin     if (LHS != 0)
4313fc67e47SDevin Coughlin       return State;
4323fc67e47SDevin Coughlin     NullSymbol = SIE->getRHS();
4333fc67e47SDevin Coughlin   } else {
4343fc67e47SDevin Coughlin     return State;
4353fc67e47SDevin Coughlin   }
4363fc67e47SDevin Coughlin 
4373fc67e47SDevin Coughlin   SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(NullSymbol);
4383fc67e47SDevin Coughlin   if (!InstanceSymbol)
4393fc67e47SDevin Coughlin     return State;
4403fc67e47SDevin Coughlin 
4413fc67e47SDevin Coughlin   State = removeValueRequiringRelease(State, InstanceSymbol, NullSymbol);
4423fc67e47SDevin Coughlin 
4433fc67e47SDevin Coughlin   return State;
4443fc67e47SDevin Coughlin }
4453fc67e47SDevin Coughlin 
446ad9f53e9SDevin Coughlin /// If a symbol escapes conservatively assume unseen code released it.
checkPointerEscape(ProgramStateRef State,const InvalidatedSymbols & Escaped,const CallEvent * Call,PointerEscapeKind Kind) const447ad9f53e9SDevin Coughlin ProgramStateRef ObjCDeallocChecker::checkPointerEscape(
448ad9f53e9SDevin Coughlin     ProgramStateRef State, const InvalidatedSymbols &Escaped,
449ad9f53e9SDevin Coughlin     const CallEvent *Call, PointerEscapeKind Kind) const {
450ad9f53e9SDevin Coughlin 
4513fc67e47SDevin Coughlin   if (State->get<UnreleasedIvarMap>().isEmpty())
4523fc67e47SDevin Coughlin     return State;
4533fc67e47SDevin Coughlin 
454ad9f53e9SDevin Coughlin   // Don't treat calls to '[super dealloc]' as escaping for the purposes
455ad9f53e9SDevin Coughlin   // of this checker. Because the checker diagnoses missing releases in the
456ad9f53e9SDevin Coughlin   // post-message handler for '[super dealloc], escaping here would cause
457ad9f53e9SDevin Coughlin   // the checker to never warn.
458ad9f53e9SDevin Coughlin   auto *OMC = dyn_cast_or_null<ObjCMethodCall>(Call);
459ad9f53e9SDevin Coughlin   if (OMC && isSuperDeallocMessage(*OMC))
460ad9f53e9SDevin Coughlin     return State;
461ad9f53e9SDevin Coughlin 
462ad9f53e9SDevin Coughlin   for (const auto &Sym : Escaped) {
4633fc67e47SDevin Coughlin     if (!Call || (Call && !Call->isInSystemHeader())) {
4643fc67e47SDevin Coughlin       // If Sym is a symbol for an object with instance variables that
4653fc67e47SDevin Coughlin       // must be released, remove these obligations when the object escapes
4663fc67e47SDevin Coughlin       // unless via a call to a system function. System functions are
4673fc67e47SDevin Coughlin       // very unlikely to release instance variables on objects passed to them,
4683fc67e47SDevin Coughlin       // and are frequently called on 'self' in -dealloc (e.g., to remove
4693fc67e47SDevin Coughlin       // observers) -- we want to avoid false negatives from escaping on
4703fc67e47SDevin Coughlin       // them.
471ad9f53e9SDevin Coughlin       State = State->remove<UnreleasedIvarMap>(Sym);
4723fc67e47SDevin Coughlin     }
4733fc67e47SDevin Coughlin 
474ad9f53e9SDevin Coughlin 
475ad9f53e9SDevin Coughlin     SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(Sym);
476ad9f53e9SDevin Coughlin     if (!InstanceSymbol)
477ea02bba5SDevin Coughlin       continue;
478ea02bba5SDevin Coughlin 
479ad9f53e9SDevin Coughlin     State = removeValueRequiringRelease(State, InstanceSymbol, Sym);
480ea02bba5SDevin Coughlin   }
481ea02bba5SDevin Coughlin 
482ad9f53e9SDevin Coughlin   return State;
483ea02bba5SDevin Coughlin }
484ea02bba5SDevin Coughlin 
485ad9f53e9SDevin Coughlin /// Report any unreleased instance variables for the current instance being
486ad9f53e9SDevin Coughlin /// dealloced.
diagnoseMissingReleases(CheckerContext & C) const487ad9f53e9SDevin Coughlin void ObjCDeallocChecker::diagnoseMissingReleases(CheckerContext &C) const {
488ad9f53e9SDevin Coughlin   ProgramStateRef State = C.getState();
489ea02bba5SDevin Coughlin 
490ad9f53e9SDevin Coughlin   SVal SelfVal;
491ad9f53e9SDevin Coughlin   if (!isInInstanceDealloc(C, SelfVal))
492ea02bba5SDevin Coughlin     return;
493ad9f53e9SDevin Coughlin 
494ad9f53e9SDevin Coughlin   const MemRegion *SelfRegion = SelfVal.castAs<loc::MemRegionVal>().getRegion();
495ad9f53e9SDevin Coughlin   const LocationContext *LCtx = C.getLocationContext();
496ad9f53e9SDevin Coughlin 
497ad9f53e9SDevin Coughlin   ExplodedNode *ErrNode = nullptr;
498ad9f53e9SDevin Coughlin 
499ad9f53e9SDevin Coughlin   SymbolRef SelfSym = SelfVal.getAsSymbol();
500ad9f53e9SDevin Coughlin   if (!SelfSym)
501ad9f53e9SDevin Coughlin     return;
502ad9f53e9SDevin Coughlin 
503ad9f53e9SDevin Coughlin   const SymbolSet *OldUnreleased = State->get<UnreleasedIvarMap>(SelfSym);
504ad9f53e9SDevin Coughlin   if (!OldUnreleased)
505ad9f53e9SDevin Coughlin     return;
506ad9f53e9SDevin Coughlin 
507ad9f53e9SDevin Coughlin   SymbolSet NewUnreleased = *OldUnreleased;
508ad9f53e9SDevin Coughlin   SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
509ad9f53e9SDevin Coughlin 
510ad9f53e9SDevin Coughlin   ProgramStateRef InitialState = State;
511ad9f53e9SDevin Coughlin 
512ad9f53e9SDevin Coughlin   for (auto *IvarSymbol : *OldUnreleased) {
513ad9f53e9SDevin Coughlin     const TypedValueRegion *TVR =
514ad9f53e9SDevin Coughlin         cast<SymbolRegionValue>(IvarSymbol)->getRegion();
515ad9f53e9SDevin Coughlin     const ObjCIvarRegion *IvarRegion = cast<ObjCIvarRegion>(TVR);
516ad9f53e9SDevin Coughlin 
517ad9f53e9SDevin Coughlin     // Don't warn if the ivar is not for this instance.
518ad9f53e9SDevin Coughlin     if (SelfRegion != IvarRegion->getSuperRegion())
519ad9f53e9SDevin Coughlin       continue;
520ad9f53e9SDevin Coughlin 
5213fc67e47SDevin Coughlin     const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
522ad9f53e9SDevin Coughlin     // Prevent an inlined call to -dealloc in a super class from warning
523ad9f53e9SDevin Coughlin     // about the values the subclass's -dealloc should release.
5243fc67e47SDevin Coughlin     if (IvarDecl->getContainingInterface() !=
525ad9f53e9SDevin Coughlin         cast<ObjCMethodDecl>(LCtx->getDecl())->getClassInterface())
526ad9f53e9SDevin Coughlin       continue;
527ad9f53e9SDevin Coughlin 
528ad9f53e9SDevin Coughlin     // Prevents diagnosing multiple times for the same instance variable
529ef04f640SHiroshi Inoue     // at, for example, both a return and at the end of the function.
530ad9f53e9SDevin Coughlin     NewUnreleased = F.remove(NewUnreleased, IvarSymbol);
531ad9f53e9SDevin Coughlin 
532ad9f53e9SDevin Coughlin     if (State->getStateManager()
533ad9f53e9SDevin Coughlin             .getConstraintManager()
534ad9f53e9SDevin Coughlin             .isNull(State, IvarSymbol)
535ad9f53e9SDevin Coughlin             .isConstrainedTrue()) {
536ad9f53e9SDevin Coughlin       continue;
537ea02bba5SDevin Coughlin     }
538ea02bba5SDevin Coughlin 
539ad9f53e9SDevin Coughlin     // A missing release manifests as a leak, so treat as a non-fatal error.
540ad9f53e9SDevin Coughlin     if (!ErrNode)
541ad9f53e9SDevin Coughlin       ErrNode = C.generateNonFatalErrorNode();
542ad9f53e9SDevin Coughlin     // If we've already reached this node on another path, return without
543ad9f53e9SDevin Coughlin     // diagnosing.
544ad9f53e9SDevin Coughlin     if (!ErrNode)
545ad9f53e9SDevin Coughlin       return;
546ad9f53e9SDevin Coughlin 
547ad9f53e9SDevin Coughlin     std::string Buf;
548ad9f53e9SDevin Coughlin     llvm::raw_string_ostream OS(Buf);
549ad9f53e9SDevin Coughlin 
550ad9f53e9SDevin Coughlin     const ObjCInterfaceDecl *Interface = IvarDecl->getContainingInterface();
551ad9f53e9SDevin Coughlin     // If the class is known to have a lifecycle with teardown that is
552ad9f53e9SDevin Coughlin     // separate from -dealloc, do not warn about missing releases. We
553ad9f53e9SDevin Coughlin     // suppress here (rather than not tracking for instance variables in
554ad9f53e9SDevin Coughlin     // such classes) because these classes are rare.
555ad9f53e9SDevin Coughlin     if (classHasSeparateTeardown(Interface))
556ad9f53e9SDevin Coughlin       return;
557ad9f53e9SDevin Coughlin 
558ad9f53e9SDevin Coughlin     ObjCImplDecl *ImplDecl = Interface->getImplementation();
559ad9f53e9SDevin Coughlin 
560ad9f53e9SDevin Coughlin     const ObjCPropertyImplDecl *PropImpl =
561ad9f53e9SDevin Coughlin         ImplDecl->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
562ad9f53e9SDevin Coughlin 
563ad9f53e9SDevin Coughlin     const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
564ad9f53e9SDevin Coughlin 
565ad9f53e9SDevin Coughlin     assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Copy ||
566ad9f53e9SDevin Coughlin            PropDecl->getSetterKind() == ObjCPropertyDecl::Retain);
567ad9f53e9SDevin Coughlin 
568ad9f53e9SDevin Coughlin     OS << "The '" << *IvarDecl << "' ivar in '" << *ImplDecl
569ad9f53e9SDevin Coughlin        << "' was ";
570ad9f53e9SDevin Coughlin 
571ad9f53e9SDevin Coughlin     if (PropDecl->getSetterKind() == ObjCPropertyDecl::Retain)
572ad9f53e9SDevin Coughlin       OS << "retained";
573ad9f53e9SDevin Coughlin     else
574ad9f53e9SDevin Coughlin       OS << "copied";
575ad9f53e9SDevin Coughlin 
576ad9f53e9SDevin Coughlin     OS << " by a synthesized property but not released"
577ad9f53e9SDevin Coughlin           " before '[super dealloc]'";
578ad9f53e9SDevin Coughlin 
5792f169e7cSArtem Dergachev     auto BR = std::make_unique<PathSensitiveBugReport>(*MissingReleaseBugType,
5802f169e7cSArtem Dergachev                                                        OS.str(), ErrNode);
581ad9f53e9SDevin Coughlin     C.emitReport(std::move(BR));
582ad9f53e9SDevin Coughlin   }
583ad9f53e9SDevin Coughlin 
584ad9f53e9SDevin Coughlin   if (NewUnreleased.isEmpty()) {
585ad9f53e9SDevin Coughlin     State = State->remove<UnreleasedIvarMap>(SelfSym);
586ad9f53e9SDevin Coughlin   } else {
587ad9f53e9SDevin Coughlin     State = State->set<UnreleasedIvarMap>(SelfSym, NewUnreleased);
588ad9f53e9SDevin Coughlin   }
589ad9f53e9SDevin Coughlin 
590ad9f53e9SDevin Coughlin   if (ErrNode) {
591ad9f53e9SDevin Coughlin     C.addTransition(State, ErrNode);
592ad9f53e9SDevin Coughlin   } else if (State != InitialState) {
593ad9f53e9SDevin Coughlin     C.addTransition(State);
594ad9f53e9SDevin Coughlin   }
595ad9f53e9SDevin Coughlin 
596ad9f53e9SDevin Coughlin   // Make sure that after checking in the top-most frame the list of
597ad9f53e9SDevin Coughlin   // tracked ivars is empty. This is intended to detect accidental leaks in
598ad9f53e9SDevin Coughlin   // the UnreleasedIvarMap program state.
599ad9f53e9SDevin Coughlin   assert(!LCtx->inTopFrame() || State->get<UnreleasedIvarMap>().isEmpty());
600ad9f53e9SDevin Coughlin }
601ad9f53e9SDevin Coughlin 
602a6046798SDevin Coughlin /// Given a symbol, determine whether the symbol refers to an ivar on
603a6046798SDevin Coughlin /// the top-most deallocating instance. If so, find the property for that
604a6046798SDevin Coughlin /// ivar, if one exists. Otherwise return null.
605a6046798SDevin Coughlin const ObjCPropertyImplDecl *
findPropertyOnDeallocatingInstance(SymbolRef IvarSym,CheckerContext & C) const606a6046798SDevin Coughlin ObjCDeallocChecker::findPropertyOnDeallocatingInstance(
607a6046798SDevin Coughlin     SymbolRef IvarSym, CheckerContext &C) const {
608a6046798SDevin Coughlin   SVal DeallocedInstance;
609a6046798SDevin Coughlin   if (!isInInstanceDealloc(C, DeallocedInstance))
610a6046798SDevin Coughlin     return nullptr;
611a6046798SDevin Coughlin 
612a6046798SDevin Coughlin   // Try to get the region from which the ivar value was loaded.
613a6046798SDevin Coughlin   auto *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
614a6046798SDevin Coughlin   if (!IvarRegion)
615a6046798SDevin Coughlin     return nullptr;
616a6046798SDevin Coughlin 
617a6046798SDevin Coughlin   // Don't try to find the property if the ivar was not loaded from the
618a6046798SDevin Coughlin   // given instance.
619a6046798SDevin Coughlin   if (DeallocedInstance.castAs<loc::MemRegionVal>().getRegion() !=
620a6046798SDevin Coughlin       IvarRegion->getSuperRegion())
621a6046798SDevin Coughlin     return nullptr;
622a6046798SDevin Coughlin 
623a6046798SDevin Coughlin   const LocationContext *LCtx = C.getLocationContext();
624a6046798SDevin Coughlin   const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
625a6046798SDevin Coughlin 
626a6046798SDevin Coughlin   const ObjCImplDecl *Container = getContainingObjCImpl(LCtx);
627a6046798SDevin Coughlin   const ObjCPropertyImplDecl *PropImpl =
628a6046798SDevin Coughlin       Container->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
629a6046798SDevin Coughlin   return PropImpl;
630a6046798SDevin Coughlin }
631a6046798SDevin Coughlin 
632ec6f61ccSDevin Coughlin /// Emits a warning if the current context is -dealloc and ReleasedValue
633ad9f53e9SDevin Coughlin /// must not be directly released in a -dealloc. Returns true if a diagnostic
634ad9f53e9SDevin Coughlin /// was emitted.
diagnoseExtraRelease(SymbolRef ReleasedValue,const ObjCMethodCall & M,CheckerContext & C) const635ad9f53e9SDevin Coughlin bool ObjCDeallocChecker::diagnoseExtraRelease(SymbolRef ReleasedValue,
636ad9f53e9SDevin Coughlin                                               const ObjCMethodCall &M,
637ad9f53e9SDevin Coughlin                                               CheckerContext &C) const {
63856939f7eSHiroshi Inoue   // Try to get the region from which the released value was loaded.
639ad9f53e9SDevin Coughlin   // Note that, unlike diagnosing for missing releases, here we don't track
640ad9f53e9SDevin Coughlin   // values that must not be released in the state. This is because even if
641ad9f53e9SDevin Coughlin   // these values escape, it is still an error under the rules of MRR to
642ad9f53e9SDevin Coughlin   // release them in -dealloc.
643ad9f53e9SDevin Coughlin   const ObjCPropertyImplDecl *PropImpl =
644a6046798SDevin Coughlin       findPropertyOnDeallocatingInstance(ReleasedValue, C);
645a6046798SDevin Coughlin 
646ad9f53e9SDevin Coughlin   if (!PropImpl)
647ad9f53e9SDevin Coughlin     return false;
648ad9f53e9SDevin Coughlin 
649a6046798SDevin Coughlin   // If the ivar belongs to a property that must not be released directly
650a6046798SDevin Coughlin   // in dealloc, emit a warning.
651ad9f53e9SDevin Coughlin   if (getDeallocReleaseRequirement(PropImpl) !=
652ad9f53e9SDevin Coughlin       ReleaseRequirement::MustNotReleaseDirectly) {
653ad9f53e9SDevin Coughlin     return false;
654ad9f53e9SDevin Coughlin   }
655ad9f53e9SDevin Coughlin 
656ad9f53e9SDevin Coughlin   // If the property is readwrite but it shadows a read-only property in its
657ad9f53e9SDevin Coughlin   // external interface, treat the property a read-only. If the outside
658ad9f53e9SDevin Coughlin   // world cannot write to a property then the internal implementation is free
659ad9f53e9SDevin Coughlin   // to make its own convention about whether the value is stored retained
660ad9f53e9SDevin Coughlin   // or not. We look up the shadow here rather than in
661ad9f53e9SDevin Coughlin   // getDeallocReleaseRequirement() because doing so can be expensive.
662ad9f53e9SDevin Coughlin   const ObjCPropertyDecl *PropDecl = findShadowedPropertyDecl(PropImpl);
663ad9f53e9SDevin Coughlin   if (PropDecl) {
664ad9f53e9SDevin Coughlin     if (PropDecl->isReadOnly())
665ad9f53e9SDevin Coughlin       return false;
666ad9f53e9SDevin Coughlin   } else {
667ad9f53e9SDevin Coughlin     PropDecl = PropImpl->getPropertyDecl();
668ad9f53e9SDevin Coughlin   }
669ad9f53e9SDevin Coughlin 
670ad9f53e9SDevin Coughlin   ExplodedNode *ErrNode = C.generateNonFatalErrorNode();
671ad9f53e9SDevin Coughlin   if (!ErrNode)
672ad9f53e9SDevin Coughlin     return false;
673ad9f53e9SDevin Coughlin 
674ad9f53e9SDevin Coughlin   std::string Buf;
675ad9f53e9SDevin Coughlin   llvm::raw_string_ostream OS(Buf);
676ad9f53e9SDevin Coughlin 
677ad9f53e9SDevin Coughlin   assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Weak ||
678ad9f53e9SDevin Coughlin          (PropDecl->getSetterKind() == ObjCPropertyDecl::Assign &&
679b8076292SDevin Coughlin           !PropDecl->isReadOnly()) ||
680b8076292SDevin Coughlin          isReleasedByCIFilterDealloc(PropImpl)
681b8076292SDevin Coughlin          );
682ad9f53e9SDevin Coughlin 
683a6046798SDevin Coughlin   const ObjCImplDecl *Container = getContainingObjCImpl(C.getLocationContext());
6844fba10c3SDevin Coughlin   OS << "The '" << *PropImpl->getPropertyIvarDecl()
6854fba10c3SDevin Coughlin      << "' ivar in '" << *Container;
686b8076292SDevin Coughlin 
687b8076292SDevin Coughlin 
6884fba10c3SDevin Coughlin   if (isReleasedByCIFilterDealloc(PropImpl)) {
689b8076292SDevin Coughlin     OS << "' will be released by '-[CIFilter dealloc]' but also released here";
690b8076292SDevin Coughlin   } else {
691b8076292SDevin Coughlin     OS << "' was synthesized for ";
692ad9f53e9SDevin Coughlin 
693ad9f53e9SDevin Coughlin     if (PropDecl->getSetterKind() == ObjCPropertyDecl::Weak)
694ad9f53e9SDevin Coughlin       OS << "a weak";
695ad9f53e9SDevin Coughlin     else
696ad9f53e9SDevin Coughlin       OS << "an assign, readwrite";
697ad9f53e9SDevin Coughlin 
698ad9f53e9SDevin Coughlin     OS <<  " property but was released in 'dealloc'";
699b8076292SDevin Coughlin   }
700ad9f53e9SDevin Coughlin 
7012f169e7cSArtem Dergachev   auto BR = std::make_unique<PathSensitiveBugReport>(*ExtraReleaseBugType,
7022f169e7cSArtem Dergachev                                                      OS.str(), ErrNode);
703ad9f53e9SDevin Coughlin   BR->addRange(M.getOriginExpr()->getSourceRange());
704ad9f53e9SDevin Coughlin 
705ad9f53e9SDevin Coughlin   C.emitReport(std::move(BR));
706ad9f53e9SDevin Coughlin 
707ad9f53e9SDevin Coughlin   return true;
708ad9f53e9SDevin Coughlin }
709ad9f53e9SDevin Coughlin 
710a6046798SDevin Coughlin /// Emits a warning if the current context is -dealloc and DeallocedValue
711a6046798SDevin Coughlin /// must not be directly dealloced in a -dealloc. Returns true if a diagnostic
712a6046798SDevin Coughlin /// was emitted.
diagnoseMistakenDealloc(SymbolRef DeallocedValue,const ObjCMethodCall & M,CheckerContext & C) const713a6046798SDevin Coughlin bool ObjCDeallocChecker::diagnoseMistakenDealloc(SymbolRef DeallocedValue,
714a6046798SDevin Coughlin                                                  const ObjCMethodCall &M,
715a6046798SDevin Coughlin                                                  CheckerContext &C) const {
7160ce45faeSArtem Dergachev   // TODO: Apart from unknown/undefined receivers, this may happen when
7170ce45faeSArtem Dergachev   // dealloc is called as a class method. Should we warn?
7180ce45faeSArtem Dergachev   if (!DeallocedValue)
7190ce45faeSArtem Dergachev     return false;
720a6046798SDevin Coughlin 
721a6046798SDevin Coughlin   // Find the property backing the instance variable that M
722a6046798SDevin Coughlin   // is dealloc'ing.
723a6046798SDevin Coughlin   const ObjCPropertyImplDecl *PropImpl =
724a6046798SDevin Coughlin       findPropertyOnDeallocatingInstance(DeallocedValue, C);
725a6046798SDevin Coughlin   if (!PropImpl)
726a6046798SDevin Coughlin     return false;
727a6046798SDevin Coughlin 
728a6046798SDevin Coughlin   if (getDeallocReleaseRequirement(PropImpl) !=
729a6046798SDevin Coughlin       ReleaseRequirement::MustRelease) {
730a6046798SDevin Coughlin     return false;
731a6046798SDevin Coughlin   }
732a6046798SDevin Coughlin 
733a6046798SDevin Coughlin   ExplodedNode *ErrNode = C.generateErrorNode();
734a6046798SDevin Coughlin   if (!ErrNode)
735a6046798SDevin Coughlin     return false;
736a6046798SDevin Coughlin 
737a6046798SDevin Coughlin   std::string Buf;
738a6046798SDevin Coughlin   llvm::raw_string_ostream OS(Buf);
739a6046798SDevin Coughlin 
740a6046798SDevin Coughlin   OS << "'" << *PropImpl->getPropertyIvarDecl()
741a6046798SDevin Coughlin      << "' should be released rather than deallocated";
742a6046798SDevin Coughlin 
7432f169e7cSArtem Dergachev   auto BR = std::make_unique<PathSensitiveBugReport>(*MistakenDeallocBugType,
7442f169e7cSArtem Dergachev                                                      OS.str(), ErrNode);
745a6046798SDevin Coughlin   BR->addRange(M.getOriginExpr()->getSourceRange());
746a6046798SDevin Coughlin 
747a6046798SDevin Coughlin   C.emitReport(std::move(BR));
748a6046798SDevin Coughlin 
749a6046798SDevin Coughlin   return true;
750a6046798SDevin Coughlin }
751ad9f53e9SDevin Coughlin 
ObjCDeallocChecker()7529d5057ccSDevin Coughlin ObjCDeallocChecker::ObjCDeallocChecker()
7539d5057ccSDevin Coughlin     : NSObjectII(nullptr), SenTestCaseII(nullptr), XCTestCaseII(nullptr),
7549d5057ccSDevin Coughlin       CIFilterII(nullptr) {
755ad9f53e9SDevin Coughlin 
756ad9f53e9SDevin Coughlin   MissingReleaseBugType.reset(
757ad9f53e9SDevin Coughlin       new BugType(this, "Missing ivar release (leak)",
7580bb17c46SGeorge Karpenkov                   categories::MemoryRefCount));
759ad9f53e9SDevin Coughlin 
760ad9f53e9SDevin Coughlin   ExtraReleaseBugType.reset(
761ad9f53e9SDevin Coughlin       new BugType(this, "Extra ivar release",
7620bb17c46SGeorge Karpenkov                   categories::MemoryRefCount));
763a6046798SDevin Coughlin 
764a6046798SDevin Coughlin   MistakenDeallocBugType.reset(
765a6046798SDevin Coughlin       new BugType(this, "Mistaken dealloc",
7660bb17c46SGeorge Karpenkov                   categories::MemoryRefCount));
767ad9f53e9SDevin Coughlin }
768ad9f53e9SDevin Coughlin 
initIdentifierInfoAndSelectors(ASTContext & Ctx) const769ad9f53e9SDevin Coughlin void ObjCDeallocChecker::initIdentifierInfoAndSelectors(
770ad9f53e9SDevin Coughlin     ASTContext &Ctx) const {
771ad9f53e9SDevin Coughlin   if (NSObjectII)
772ad9f53e9SDevin Coughlin     return;
773ad9f53e9SDevin Coughlin 
774ad9f53e9SDevin Coughlin   NSObjectII = &Ctx.Idents.get("NSObject");
775ad9f53e9SDevin Coughlin   SenTestCaseII = &Ctx.Idents.get("SenTestCase");
7769d5057ccSDevin Coughlin   XCTestCaseII = &Ctx.Idents.get("XCTestCase");
77709359493SDevin Coughlin   Block_releaseII = &Ctx.Idents.get("_Block_release");
778b8076292SDevin Coughlin   CIFilterII = &Ctx.Idents.get("CIFilter");
779ad9f53e9SDevin Coughlin 
780ad9f53e9SDevin Coughlin   IdentifierInfo *DeallocII = &Ctx.Idents.get("dealloc");
781ad9f53e9SDevin Coughlin   IdentifierInfo *ReleaseII = &Ctx.Idents.get("release");
782ad9f53e9SDevin Coughlin   DeallocSel = Ctx.Selectors.getSelector(0, &DeallocII);
783ad9f53e9SDevin Coughlin   ReleaseSel = Ctx.Selectors.getSelector(0, &ReleaseII);
784ad9f53e9SDevin Coughlin }
785ad9f53e9SDevin Coughlin 
786ec6f61ccSDevin Coughlin /// Returns true if M is a call to '[super dealloc]'.
isSuperDeallocMessage(const ObjCMethodCall & M) const787ad9f53e9SDevin Coughlin bool ObjCDeallocChecker::isSuperDeallocMessage(
788ad9f53e9SDevin Coughlin     const ObjCMethodCall &M) const {
789ad9f53e9SDevin Coughlin   if (M.getOriginExpr()->getReceiverKind() != ObjCMessageExpr::SuperInstance)
790ad9f53e9SDevin Coughlin     return false;
791ad9f53e9SDevin Coughlin 
792ad9f53e9SDevin Coughlin   return M.getSelector() == DeallocSel;
793ad9f53e9SDevin Coughlin }
794ad9f53e9SDevin Coughlin 
795a8aa5f0aSNAKAMURA Takumi /// Returns the ObjCImplDecl containing the method declaration in LCtx.
796ad9f53e9SDevin Coughlin const ObjCImplDecl *
getContainingObjCImpl(const LocationContext * LCtx) const797ad9f53e9SDevin Coughlin ObjCDeallocChecker::getContainingObjCImpl(const LocationContext *LCtx) const {
798ad9f53e9SDevin Coughlin   auto *MD = cast<ObjCMethodDecl>(LCtx->getDecl());
799ad9f53e9SDevin Coughlin   return cast<ObjCImplDecl>(MD->getDeclContext());
800ad9f53e9SDevin Coughlin }
801ad9f53e9SDevin Coughlin 
802ec6f61ccSDevin Coughlin /// Returns the property that shadowed by PropImpl if one exists and
803ad9f53e9SDevin Coughlin /// nullptr otherwise.
findShadowedPropertyDecl(const ObjCPropertyImplDecl * PropImpl) const804ad9f53e9SDevin Coughlin const ObjCPropertyDecl *ObjCDeallocChecker::findShadowedPropertyDecl(
805ad9f53e9SDevin Coughlin     const ObjCPropertyImplDecl *PropImpl) const {
806ad9f53e9SDevin Coughlin   const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
807ad9f53e9SDevin Coughlin 
808ad9f53e9SDevin Coughlin   // Only readwrite properties can shadow.
809ad9f53e9SDevin Coughlin   if (PropDecl->isReadOnly())
810ad9f53e9SDevin Coughlin     return nullptr;
811ad9f53e9SDevin Coughlin 
812ad9f53e9SDevin Coughlin   auto *CatDecl = dyn_cast<ObjCCategoryDecl>(PropDecl->getDeclContext());
813ad9f53e9SDevin Coughlin 
814ad9f53e9SDevin Coughlin   // Only class extensions can contain shadowing properties.
815ad9f53e9SDevin Coughlin   if (!CatDecl || !CatDecl->IsClassExtension())
816ad9f53e9SDevin Coughlin     return nullptr;
817ad9f53e9SDevin Coughlin 
818ad9f53e9SDevin Coughlin   IdentifierInfo *ID = PropDecl->getIdentifier();
819ad9f53e9SDevin Coughlin   DeclContext::lookup_result R = CatDecl->getClassInterface()->lookup(ID);
820ad9f53e9SDevin Coughlin   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
821ad9f53e9SDevin Coughlin     auto *ShadowedPropDecl = dyn_cast<ObjCPropertyDecl>(*I);
822ad9f53e9SDevin Coughlin     if (!ShadowedPropDecl)
823ad9f53e9SDevin Coughlin       continue;
824ad9f53e9SDevin Coughlin 
825ad9f53e9SDevin Coughlin     if (ShadowedPropDecl->isInstanceProperty()) {
826ad9f53e9SDevin Coughlin       assert(ShadowedPropDecl->isReadOnly());
827ad9f53e9SDevin Coughlin       return ShadowedPropDecl;
828ad9f53e9SDevin Coughlin     }
829ad9f53e9SDevin Coughlin   }
830ad9f53e9SDevin Coughlin 
831ad9f53e9SDevin Coughlin   return nullptr;
832ad9f53e9SDevin Coughlin }
833ad9f53e9SDevin Coughlin 
83409359493SDevin Coughlin /// Add a transition noting the release of the given value.
transitionToReleaseValue(CheckerContext & C,SymbolRef Value) const83509359493SDevin Coughlin void ObjCDeallocChecker::transitionToReleaseValue(CheckerContext &C,
83609359493SDevin Coughlin                                                   SymbolRef Value) const {
83709359493SDevin Coughlin   assert(Value);
83809359493SDevin Coughlin   SymbolRef InstanceSym = getInstanceSymbolFromIvarSymbol(Value);
83909359493SDevin Coughlin   if (!InstanceSym)
84009359493SDevin Coughlin     return;
84109359493SDevin Coughlin   ProgramStateRef InitialState = C.getState();
84209359493SDevin Coughlin 
84309359493SDevin Coughlin   ProgramStateRef ReleasedState =
84409359493SDevin Coughlin       removeValueRequiringRelease(InitialState, InstanceSym, Value);
84509359493SDevin Coughlin 
84609359493SDevin Coughlin   if (ReleasedState != InitialState) {
84709359493SDevin Coughlin     C.addTransition(ReleasedState);
84809359493SDevin Coughlin   }
84909359493SDevin Coughlin }
85009359493SDevin Coughlin 
851ec6f61ccSDevin Coughlin /// Remove the Value requiring a release from the tracked set for
852ec6f61ccSDevin Coughlin /// Instance and return the resultant state.
removeValueRequiringRelease(ProgramStateRef State,SymbolRef Instance,SymbolRef Value) const853ad9f53e9SDevin Coughlin ProgramStateRef ObjCDeallocChecker::removeValueRequiringRelease(
854ad9f53e9SDevin Coughlin     ProgramStateRef State, SymbolRef Instance, SymbolRef Value) const {
855ad9f53e9SDevin Coughlin   assert(Instance);
856ad9f53e9SDevin Coughlin   assert(Value);
8573fc67e47SDevin Coughlin   const ObjCIvarRegion *RemovedRegion = getIvarRegionForIvarSymbol(Value);
8583fc67e47SDevin Coughlin   if (!RemovedRegion)
8593fc67e47SDevin Coughlin     return State;
860ad9f53e9SDevin Coughlin 
861ad9f53e9SDevin Coughlin   const SymbolSet *Unreleased = State->get<UnreleasedIvarMap>(Instance);
862ad9f53e9SDevin Coughlin   if (!Unreleased)
863ad9f53e9SDevin Coughlin     return State;
864ad9f53e9SDevin Coughlin 
865ad9f53e9SDevin Coughlin   // Mark the value as no longer requiring a release.
866ad9f53e9SDevin Coughlin   SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
8673fc67e47SDevin Coughlin   SymbolSet NewUnreleased = *Unreleased;
8683fc67e47SDevin Coughlin   for (auto &Sym : *Unreleased) {
8693fc67e47SDevin Coughlin     const ObjCIvarRegion *UnreleasedRegion = getIvarRegionForIvarSymbol(Sym);
8703fc67e47SDevin Coughlin     assert(UnreleasedRegion);
8713fc67e47SDevin Coughlin     if (RemovedRegion->getDecl() == UnreleasedRegion->getDecl()) {
8723fc67e47SDevin Coughlin       NewUnreleased = F.remove(NewUnreleased, Sym);
8733fc67e47SDevin Coughlin     }
8743fc67e47SDevin Coughlin   }
875ad9f53e9SDevin Coughlin 
876ad9f53e9SDevin Coughlin   if (NewUnreleased.isEmpty()) {
877ad9f53e9SDevin Coughlin     return State->remove<UnreleasedIvarMap>(Instance);
878ad9f53e9SDevin Coughlin   }
879ad9f53e9SDevin Coughlin 
880ad9f53e9SDevin Coughlin   return State->set<UnreleasedIvarMap>(Instance, NewUnreleased);
881ad9f53e9SDevin Coughlin }
882ad9f53e9SDevin Coughlin 
883ad9f53e9SDevin Coughlin /// Determines whether the instance variable for \p PropImpl must or must not be
884ad9f53e9SDevin Coughlin /// released in -dealloc or whether it cannot be determined.
getDeallocReleaseRequirement(const ObjCPropertyImplDecl * PropImpl) const885ad9f53e9SDevin Coughlin ReleaseRequirement ObjCDeallocChecker::getDeallocReleaseRequirement(
886ad9f53e9SDevin Coughlin     const ObjCPropertyImplDecl *PropImpl) const {
887ad9f53e9SDevin Coughlin   const ObjCIvarDecl *IvarDecl;
888ad9f53e9SDevin Coughlin   const ObjCPropertyDecl *PropDecl;
889ad9f53e9SDevin Coughlin   if (!isSynthesizedRetainableProperty(PropImpl, &IvarDecl, &PropDecl))
890ad9f53e9SDevin Coughlin     return ReleaseRequirement::Unknown;
891ad9f53e9SDevin Coughlin 
892ad9f53e9SDevin Coughlin   ObjCPropertyDecl::SetterKind SK = PropDecl->getSetterKind();
893ad9f53e9SDevin Coughlin 
894ad9f53e9SDevin Coughlin   switch (SK) {
895ad9f53e9SDevin Coughlin   // Retain and copy setters retain/copy their values before storing and so
896ad9f53e9SDevin Coughlin   // the value in their instance variables must be released in -dealloc.
897ad9f53e9SDevin Coughlin   case ObjCPropertyDecl::Retain:
898ad9f53e9SDevin Coughlin   case ObjCPropertyDecl::Copy:
899b8076292SDevin Coughlin     if (isReleasedByCIFilterDealloc(PropImpl))
900b8076292SDevin Coughlin       return ReleaseRequirement::MustNotReleaseDirectly;
901b8076292SDevin Coughlin 
9020bd37a1aSDevin Coughlin     if (isNibLoadedIvarWithoutRetain(PropImpl))
9030bd37a1aSDevin Coughlin       return ReleaseRequirement::Unknown;
9040bd37a1aSDevin Coughlin 
905ad9f53e9SDevin Coughlin     return ReleaseRequirement::MustRelease;
906ad9f53e9SDevin Coughlin 
907ad9f53e9SDevin Coughlin   case ObjCPropertyDecl::Weak:
908ad9f53e9SDevin Coughlin     return ReleaseRequirement::MustNotReleaseDirectly;
909ad9f53e9SDevin Coughlin 
910ad9f53e9SDevin Coughlin   case ObjCPropertyDecl::Assign:
911ad9f53e9SDevin Coughlin     // It is common for the ivars for read-only assign properties to
912ad9f53e9SDevin Coughlin     // always be stored retained, so their release requirement cannot be
913ad9f53e9SDevin Coughlin     // be determined.
914ad9f53e9SDevin Coughlin     if (PropDecl->isReadOnly())
915ad9f53e9SDevin Coughlin       return ReleaseRequirement::Unknown;
916ad9f53e9SDevin Coughlin 
917ad9f53e9SDevin Coughlin     return ReleaseRequirement::MustNotReleaseDirectly;
918ad9f53e9SDevin Coughlin   }
919ad9f53e9SDevin Coughlin   llvm_unreachable("Unrecognized setter kind");
920ad9f53e9SDevin Coughlin }
921ad9f53e9SDevin Coughlin 
922ec6f61ccSDevin Coughlin /// Returns the released value if M is a call a setter that releases
923ad9f53e9SDevin Coughlin /// and nils out its underlying instance variable.
924ad9f53e9SDevin Coughlin SymbolRef
getValueReleasedByNillingOut(const ObjCMethodCall & M,CheckerContext & C) const925ad9f53e9SDevin Coughlin ObjCDeallocChecker::getValueReleasedByNillingOut(const ObjCMethodCall &M,
926ad9f53e9SDevin Coughlin                                                  CheckerContext &C) const {
927ad9f53e9SDevin Coughlin   SVal ReceiverVal = M.getReceiverSVal();
928ad9f53e9SDevin Coughlin   if (!ReceiverVal.isValid())
929ad9f53e9SDevin Coughlin     return nullptr;
930ad9f53e9SDevin Coughlin 
931ad9f53e9SDevin Coughlin   if (M.getNumArgs() == 0)
932ad9f53e9SDevin Coughlin     return nullptr;
933578a20a8SDevin Coughlin 
934578a20a8SDevin Coughlin   if (!M.getArgExpr(0)->getType()->isObjCRetainableType())
935578a20a8SDevin Coughlin     return nullptr;
936578a20a8SDevin Coughlin 
937578a20a8SDevin Coughlin   // Is the first argument nil?
938ad9f53e9SDevin Coughlin   SVal Arg = M.getArgSVal(0);
939ad9f53e9SDevin Coughlin   ProgramStateRef notNilState, nilState;
940ad9f53e9SDevin Coughlin   std::tie(notNilState, nilState) =
941ad9f53e9SDevin Coughlin       M.getState()->assume(Arg.castAs<DefinedOrUnknownSVal>());
942ad9f53e9SDevin Coughlin   if (!(nilState && !notNilState))
943ad9f53e9SDevin Coughlin     return nullptr;
944ad9f53e9SDevin Coughlin 
945ad9f53e9SDevin Coughlin   const ObjCPropertyDecl *Prop = M.getAccessedProperty();
946ad9f53e9SDevin Coughlin   if (!Prop)
947ad9f53e9SDevin Coughlin     return nullptr;
948ad9f53e9SDevin Coughlin 
949ad9f53e9SDevin Coughlin   ObjCIvarDecl *PropIvarDecl = Prop->getPropertyIvarDecl();
950ad9f53e9SDevin Coughlin   if (!PropIvarDecl)
951ad9f53e9SDevin Coughlin     return nullptr;
952ad9f53e9SDevin Coughlin 
953ad9f53e9SDevin Coughlin   ProgramStateRef State = C.getState();
954ad9f53e9SDevin Coughlin 
955ad9f53e9SDevin Coughlin   SVal LVal = State->getLValue(PropIvarDecl, ReceiverVal);
956ad9f53e9SDevin Coughlin   Optional<Loc> LValLoc = LVal.getAs<Loc>();
957ad9f53e9SDevin Coughlin   if (!LValLoc)
958ad9f53e9SDevin Coughlin     return nullptr;
959ad9f53e9SDevin Coughlin 
960*ca4af13eSKazu Hirata   SVal CurrentValInIvar = State->getSVal(*LValLoc);
961ad9f53e9SDevin Coughlin   return CurrentValInIvar.getAsSymbol();
962ad9f53e9SDevin Coughlin }
963ad9f53e9SDevin Coughlin 
964ad9f53e9SDevin Coughlin /// Returns true if the current context is a call to -dealloc and false
965ec6f61ccSDevin Coughlin /// otherwise. If true, it also sets SelfValOut to the value of
966ad9f53e9SDevin Coughlin /// 'self'.
isInInstanceDealloc(const CheckerContext & C,SVal & SelfValOut) const967ad9f53e9SDevin Coughlin bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
968ad9f53e9SDevin Coughlin                                              SVal &SelfValOut) const {
969ad9f53e9SDevin Coughlin   return isInInstanceDealloc(C, C.getLocationContext(), SelfValOut);
970ad9f53e9SDevin Coughlin }
971ad9f53e9SDevin Coughlin 
972ec6f61ccSDevin Coughlin /// Returns true if LCtx is a call to -dealloc and false
973ec6f61ccSDevin Coughlin /// otherwise. If true, it also sets SelfValOut to the value of
974ad9f53e9SDevin Coughlin /// 'self'.
isInInstanceDealloc(const CheckerContext & C,const LocationContext * LCtx,SVal & SelfValOut) const975ad9f53e9SDevin Coughlin bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
976ad9f53e9SDevin Coughlin                                              const LocationContext *LCtx,
977ad9f53e9SDevin Coughlin                                              SVal &SelfValOut) const {
978ad9f53e9SDevin Coughlin   auto *MD = dyn_cast<ObjCMethodDecl>(LCtx->getDecl());
979ad9f53e9SDevin Coughlin   if (!MD || !MD->isInstanceMethod() || MD->getSelector() != DeallocSel)
980ad9f53e9SDevin Coughlin     return false;
981ad9f53e9SDevin Coughlin 
982ad9f53e9SDevin Coughlin   const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
983ad9f53e9SDevin Coughlin   assert(SelfDecl && "No self in -dealloc?");
984ad9f53e9SDevin Coughlin 
985ad9f53e9SDevin Coughlin   ProgramStateRef State = C.getState();
986ad9f53e9SDevin Coughlin   SelfValOut = State->getSVal(State->getRegion(SelfDecl, LCtx));
987ad9f53e9SDevin Coughlin   return true;
988ad9f53e9SDevin Coughlin }
989ad9f53e9SDevin Coughlin 
990ad9f53e9SDevin Coughlin /// Returns true if there is a call to -dealloc anywhere on the stack and false
991ec6f61ccSDevin Coughlin /// otherwise. If true, it also sets InstanceValOut to the value of
992ad9f53e9SDevin Coughlin /// 'self' in the frame for -dealloc.
instanceDeallocIsOnStack(const CheckerContext & C,SVal & InstanceValOut) const993ad9f53e9SDevin Coughlin bool ObjCDeallocChecker::instanceDeallocIsOnStack(const CheckerContext &C,
994ad9f53e9SDevin Coughlin                                                   SVal &InstanceValOut) const {
995ad9f53e9SDevin Coughlin   const LocationContext *LCtx = C.getLocationContext();
996ad9f53e9SDevin Coughlin 
997ad9f53e9SDevin Coughlin   while (LCtx) {
998ad9f53e9SDevin Coughlin     if (isInInstanceDealloc(C, LCtx, InstanceValOut))
999ad9f53e9SDevin Coughlin       return true;
1000ad9f53e9SDevin Coughlin 
1001ad9f53e9SDevin Coughlin     LCtx = LCtx->getParent();
1002ad9f53e9SDevin Coughlin   }
1003ad9f53e9SDevin Coughlin 
1004ad9f53e9SDevin Coughlin   return false;
1005ad9f53e9SDevin Coughlin }
1006ad9f53e9SDevin Coughlin 
1007ec6f61ccSDevin Coughlin /// Returns true if the ID is a class in which which is known to have
1008ad9f53e9SDevin Coughlin /// a separate teardown lifecycle. In this case, -dealloc warnings
1009ad9f53e9SDevin Coughlin /// about missing releases should be suppressed.
classHasSeparateTeardown(const ObjCInterfaceDecl * ID) const1010ad9f53e9SDevin Coughlin bool ObjCDeallocChecker::classHasSeparateTeardown(
1011ad9f53e9SDevin Coughlin     const ObjCInterfaceDecl *ID) const {
1012ad9f53e9SDevin Coughlin   // Suppress if the class is not a subclass of NSObject.
1013ad9f53e9SDevin Coughlin   for ( ; ID ; ID = ID->getSuperClass()) {
1014ad9f53e9SDevin Coughlin     IdentifierInfo *II = ID->getIdentifier();
1015ad9f53e9SDevin Coughlin 
1016ad9f53e9SDevin Coughlin     if (II == NSObjectII)
1017ad9f53e9SDevin Coughlin       return false;
1018ad9f53e9SDevin Coughlin 
10199d5057ccSDevin Coughlin     // FIXME: For now, ignore classes that subclass SenTestCase and XCTestCase,
10209d5057ccSDevin Coughlin     // as these don't need to implement -dealloc.  They implement tear down in
10219d5057ccSDevin Coughlin     // another way, which we should try and catch later.
1022ad9f53e9SDevin Coughlin     //  http://llvm.org/bugs/show_bug.cgi?id=3187
10239d5057ccSDevin Coughlin     if (II == XCTestCaseII || II == SenTestCaseII)
1024ad9f53e9SDevin Coughlin       return true;
1025ad9f53e9SDevin Coughlin   }
1026ad9f53e9SDevin Coughlin 
1027ad9f53e9SDevin Coughlin   return true;
1028ad9f53e9SDevin Coughlin }
1029ad9f53e9SDevin Coughlin 
1030b8076292SDevin Coughlin /// The -dealloc method in CIFilter highly unusual in that is will release
1031b8076292SDevin Coughlin /// instance variables belonging to its *subclasses* if the variable name
1032b8076292SDevin Coughlin /// starts with "input" or backs a property whose name starts with "input".
1033b8076292SDevin Coughlin /// Subclasses should not release these ivars in their own -dealloc method --
1034b8076292SDevin Coughlin /// doing so could result in an over release.
1035b8076292SDevin Coughlin ///
1036b8076292SDevin Coughlin /// This method returns true if the property will be released by
1037b8076292SDevin Coughlin /// -[CIFilter dealloc].
isReleasedByCIFilterDealloc(const ObjCPropertyImplDecl * PropImpl) const1038b8076292SDevin Coughlin bool ObjCDeallocChecker::isReleasedByCIFilterDealloc(
1039b8076292SDevin Coughlin     const ObjCPropertyImplDecl *PropImpl) const {
1040b8076292SDevin Coughlin   assert(PropImpl->getPropertyIvarDecl());
1041b8076292SDevin Coughlin   StringRef PropName = PropImpl->getPropertyDecl()->getName();
1042b8076292SDevin Coughlin   StringRef IvarName = PropImpl->getPropertyIvarDecl()->getName();
1043b8076292SDevin Coughlin 
1044b8076292SDevin Coughlin   const char *ReleasePrefix = "input";
1045b8076292SDevin Coughlin   if (!(PropName.startswith(ReleasePrefix) ||
1046b8076292SDevin Coughlin         IvarName.startswith(ReleasePrefix))) {
1047b8076292SDevin Coughlin     return false;
1048b8076292SDevin Coughlin   }
1049b8076292SDevin Coughlin 
1050b8076292SDevin Coughlin   const ObjCInterfaceDecl *ID =
1051b8076292SDevin Coughlin       PropImpl->getPropertyIvarDecl()->getContainingInterface();
1052b8076292SDevin Coughlin   for ( ; ID ; ID = ID->getSuperClass()) {
1053b8076292SDevin Coughlin     IdentifierInfo *II = ID->getIdentifier();
1054b8076292SDevin Coughlin     if (II == CIFilterII)
1055b8076292SDevin Coughlin       return true;
1056b8076292SDevin Coughlin   }
1057b8076292SDevin Coughlin 
1058b8076292SDevin Coughlin   return false;
1059b8076292SDevin Coughlin }
1060b8076292SDevin Coughlin 
10610bd37a1aSDevin Coughlin /// Returns whether the ivar backing the property is an IBOutlet that
10620bd37a1aSDevin Coughlin /// has its value set by nib loading code without retaining the value.
10630bd37a1aSDevin Coughlin ///
10640bd37a1aSDevin Coughlin /// On macOS, if there is no setter, the nib-loading code sets the ivar
10650bd37a1aSDevin Coughlin /// directly, without retaining the value,
10660bd37a1aSDevin Coughlin ///
10670bd37a1aSDevin Coughlin /// On iOS and its derivatives, the nib-loading code will call
10680bd37a1aSDevin Coughlin /// -setValue:forKey:, which retains the value before directly setting the ivar.
isNibLoadedIvarWithoutRetain(const ObjCPropertyImplDecl * PropImpl) const10690bd37a1aSDevin Coughlin bool ObjCDeallocChecker::isNibLoadedIvarWithoutRetain(
10700bd37a1aSDevin Coughlin     const ObjCPropertyImplDecl *PropImpl) const {
10710bd37a1aSDevin Coughlin   const ObjCIvarDecl *IvarDecl = PropImpl->getPropertyIvarDecl();
10720bd37a1aSDevin Coughlin   if (!IvarDecl->hasAttr<IBOutletAttr>())
10730bd37a1aSDevin Coughlin     return false;
10740bd37a1aSDevin Coughlin 
10750bd37a1aSDevin Coughlin   const llvm::Triple &Target =
10760bd37a1aSDevin Coughlin       IvarDecl->getASTContext().getTargetInfo().getTriple();
10770bd37a1aSDevin Coughlin 
10780bd37a1aSDevin Coughlin   if (!Target.isMacOSX())
10790bd37a1aSDevin Coughlin     return false;
10800bd37a1aSDevin Coughlin 
10810bd37a1aSDevin Coughlin   if (PropImpl->getPropertyDecl()->getSetterMethodDecl())
10820bd37a1aSDevin Coughlin     return false;
10830bd37a1aSDevin Coughlin 
10840bd37a1aSDevin Coughlin   return true;
10850bd37a1aSDevin Coughlin }
10860bd37a1aSDevin Coughlin 
registerObjCDeallocChecker(CheckerManager & Mgr)1087ad9f53e9SDevin Coughlin void ento::registerObjCDeallocChecker(CheckerManager &Mgr) {
1088ad9f53e9SDevin Coughlin   Mgr.registerChecker<ObjCDeallocChecker>();
1089af45aca6SArgyrios Kyrtzidis }
1090058a7a45SKristof Umann 
shouldRegisterObjCDeallocChecker(const CheckerManager & mgr)1091bda3dd0dSKirstóf Umann bool ento::shouldRegisterObjCDeallocChecker(const CheckerManager &mgr) {
1092748c139aSKristof Umann   // These checker only makes sense under MRR.
1093bda3dd0dSKirstóf Umann   const LangOptions &LO = mgr.getLangOpts();
1094748c139aSKristof Umann   return LO.getGC() != LangOptions::GCOnly && !LO.ObjCAutoRefCount;
1095058a7a45SKristof Umann }
1096