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