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