xref: /freebsd/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp (revision f126890ac5386406dadf7c4cfa9566cbb56537c5)
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 #include <optional>
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     std::optional<Loc> LValLoc = LVal.getAs<Loc>();
287     if (!LValLoc)
288       continue;
289 
290     SVal InitialVal = State->getSVal(*LValLoc);
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   const SymbolicRegion *SR = IvarRegion->getSymbolicBase();
325   assert(SR && "Symbolic base should not be nullptr");
326   return SR->getSymbol();
327 }
328 
329 /// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
330 /// a release or a nilling-out property setter.
331 void ObjCDeallocChecker::checkPreObjCMessage(
332     const ObjCMethodCall &M, CheckerContext &C) const {
333   // Only run if -dealloc is on the stack.
334   SVal DeallocedInstance;
335   if (!instanceDeallocIsOnStack(C, DeallocedInstance))
336     return;
337 
338   SymbolRef ReleasedValue = nullptr;
339 
340   if (M.getSelector() == ReleaseSel) {
341     ReleasedValue = M.getReceiverSVal().getAsSymbol();
342   } else if (M.getSelector() == DeallocSel && !M.isReceiverSelfOrSuper()) {
343     if (diagnoseMistakenDealloc(M.getReceiverSVal().getAsSymbol(), M, C))
344       return;
345   }
346 
347   if (ReleasedValue) {
348     // An instance variable symbol was released with -release:
349     //    [_property release];
350     if (diagnoseExtraRelease(ReleasedValue,M, C))
351       return;
352   } else {
353     // An instance variable symbol was released nilling out its property:
354     //    self.property = nil;
355     ReleasedValue = getValueReleasedByNillingOut(M, C);
356   }
357 
358   if (!ReleasedValue)
359     return;
360 
361   transitionToReleaseValue(C, ReleasedValue);
362 }
363 
364 /// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
365 /// call to Block_release().
366 void ObjCDeallocChecker::checkPreCall(const CallEvent &Call,
367                                       CheckerContext &C) const {
368   const IdentifierInfo *II = Call.getCalleeIdentifier();
369   if (II != Block_releaseII)
370     return;
371 
372   if (Call.getNumArgs() != 1)
373     return;
374 
375   SymbolRef ReleasedValue = Call.getArgSVal(0).getAsSymbol();
376   if (!ReleasedValue)
377     return;
378 
379   transitionToReleaseValue(C, ReleasedValue);
380 }
381 /// If the message was a call to '[super dealloc]', diagnose any missing
382 /// releases.
383 void ObjCDeallocChecker::checkPostObjCMessage(
384     const ObjCMethodCall &M, CheckerContext &C) const {
385   // We perform this check post-message so that if the super -dealloc
386   // calls a helper method and that this class overrides, any ivars released in
387   // the helper method will be recorded before checking.
388   if (isSuperDeallocMessage(M))
389     diagnoseMissingReleases(C);
390 }
391 
392 /// Check for missing releases even when -dealloc does not call
393 /// '[super dealloc]'.
394 void ObjCDeallocChecker::checkEndFunction(
395     const ReturnStmt *RS, CheckerContext &C) const {
396   diagnoseMissingReleases(C);
397 }
398 
399 /// Check for missing releases on early return.
400 void ObjCDeallocChecker::checkPreStmt(
401     const ReturnStmt *RS, CheckerContext &C) const {
402   diagnoseMissingReleases(C);
403 }
404 
405 /// When a symbol is assumed to be nil, remove it from the set of symbols
406 /// require to be nil.
407 ProgramStateRef ObjCDeallocChecker::evalAssume(ProgramStateRef State, SVal Cond,
408                                                bool Assumption) const {
409   if (State->get<UnreleasedIvarMap>().isEmpty())
410     return State;
411 
412   auto *CondBSE = dyn_cast_or_null<BinarySymExpr>(Cond.getAsSymbol());
413   if (!CondBSE)
414     return State;
415 
416   BinaryOperator::Opcode OpCode = CondBSE->getOpcode();
417   if (Assumption) {
418     if (OpCode != BO_EQ)
419       return State;
420   } else {
421     if (OpCode != BO_NE)
422       return State;
423   }
424 
425   SymbolRef NullSymbol = nullptr;
426   if (auto *SIE = dyn_cast<SymIntExpr>(CondBSE)) {
427     const llvm::APInt &RHS = SIE->getRHS();
428     if (RHS != 0)
429       return State;
430     NullSymbol = SIE->getLHS();
431   } else if (auto *SIE = dyn_cast<IntSymExpr>(CondBSE)) {
432     const llvm::APInt &LHS = SIE->getLHS();
433     if (LHS != 0)
434       return State;
435     NullSymbol = SIE->getRHS();
436   } else {
437     return State;
438   }
439 
440   SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(NullSymbol);
441   if (!InstanceSymbol)
442     return State;
443 
444   State = removeValueRequiringRelease(State, InstanceSymbol, NullSymbol);
445 
446   return State;
447 }
448 
449 /// If a symbol escapes conservatively assume unseen code released it.
450 ProgramStateRef ObjCDeallocChecker::checkPointerEscape(
451     ProgramStateRef State, const InvalidatedSymbols &Escaped,
452     const CallEvent *Call, PointerEscapeKind Kind) const {
453 
454   if (State->get<UnreleasedIvarMap>().isEmpty())
455     return State;
456 
457   // Don't treat calls to '[super dealloc]' as escaping for the purposes
458   // of this checker. Because the checker diagnoses missing releases in the
459   // post-message handler for '[super dealloc], escaping here would cause
460   // the checker to never warn.
461   auto *OMC = dyn_cast_or_null<ObjCMethodCall>(Call);
462   if (OMC && isSuperDeallocMessage(*OMC))
463     return State;
464 
465   for (const auto &Sym : Escaped) {
466     if (!Call || (Call && !Call->isInSystemHeader())) {
467       // If Sym is a symbol for an object with instance variables that
468       // must be released, remove these obligations when the object escapes
469       // unless via a call to a system function. System functions are
470       // very unlikely to release instance variables on objects passed to them,
471       // and are frequently called on 'self' in -dealloc (e.g., to remove
472       // observers) -- we want to avoid false negatives from escaping on
473       // them.
474       State = State->remove<UnreleasedIvarMap>(Sym);
475     }
476 
477 
478     SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(Sym);
479     if (!InstanceSymbol)
480       continue;
481 
482     State = removeValueRequiringRelease(State, InstanceSymbol, Sym);
483   }
484 
485   return State;
486 }
487 
488 /// Report any unreleased instance variables for the current instance being
489 /// dealloced.
490 void ObjCDeallocChecker::diagnoseMissingReleases(CheckerContext &C) const {
491   ProgramStateRef State = C.getState();
492 
493   SVal SelfVal;
494   if (!isInInstanceDealloc(C, SelfVal))
495     return;
496 
497   const MemRegion *SelfRegion = SelfVal.castAs<loc::MemRegionVal>().getRegion();
498   const LocationContext *LCtx = C.getLocationContext();
499 
500   ExplodedNode *ErrNode = nullptr;
501 
502   SymbolRef SelfSym = SelfVal.getAsSymbol();
503   if (!SelfSym)
504     return;
505 
506   const SymbolSet *OldUnreleased = State->get<UnreleasedIvarMap>(SelfSym);
507   if (!OldUnreleased)
508     return;
509 
510   SymbolSet NewUnreleased = *OldUnreleased;
511   SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
512 
513   ProgramStateRef InitialState = State;
514 
515   for (auto *IvarSymbol : *OldUnreleased) {
516     const TypedValueRegion *TVR =
517         cast<SymbolRegionValue>(IvarSymbol)->getRegion();
518     const ObjCIvarRegion *IvarRegion = cast<ObjCIvarRegion>(TVR);
519 
520     // Don't warn if the ivar is not for this instance.
521     if (SelfRegion != IvarRegion->getSuperRegion())
522       continue;
523 
524     const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
525     // Prevent an inlined call to -dealloc in a super class from warning
526     // about the values the subclass's -dealloc should release.
527     if (IvarDecl->getContainingInterface() !=
528         cast<ObjCMethodDecl>(LCtx->getDecl())->getClassInterface())
529       continue;
530 
531     // Prevents diagnosing multiple times for the same instance variable
532     // at, for example, both a return and at the end of the function.
533     NewUnreleased = F.remove(NewUnreleased, IvarSymbol);
534 
535     if (State->getStateManager()
536             .getConstraintManager()
537             .isNull(State, IvarSymbol)
538             .isConstrainedTrue()) {
539       continue;
540     }
541 
542     // A missing release manifests as a leak, so treat as a non-fatal error.
543     if (!ErrNode)
544       ErrNode = C.generateNonFatalErrorNode();
545     // If we've already reached this node on another path, return without
546     // diagnosing.
547     if (!ErrNode)
548       return;
549 
550     std::string Buf;
551     llvm::raw_string_ostream OS(Buf);
552 
553     const ObjCInterfaceDecl *Interface = IvarDecl->getContainingInterface();
554     // If the class is known to have a lifecycle with teardown that is
555     // separate from -dealloc, do not warn about missing releases. We
556     // suppress here (rather than not tracking for instance variables in
557     // such classes) because these classes are rare.
558     if (classHasSeparateTeardown(Interface))
559       return;
560 
561     ObjCImplDecl *ImplDecl = Interface->getImplementation();
562 
563     const ObjCPropertyImplDecl *PropImpl =
564         ImplDecl->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
565 
566     const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
567 
568     assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Copy ||
569            PropDecl->getSetterKind() == ObjCPropertyDecl::Retain);
570 
571     OS << "The '" << *IvarDecl << "' ivar in '" << *ImplDecl
572        << "' was ";
573 
574     if (PropDecl->getSetterKind() == ObjCPropertyDecl::Retain)
575       OS << "retained";
576     else
577       OS << "copied";
578 
579     OS << " by a synthesized property but not released"
580           " before '[super dealloc]'";
581 
582     auto BR = std::make_unique<PathSensitiveBugReport>(*MissingReleaseBugType,
583                                                        OS.str(), ErrNode);
584     C.emitReport(std::move(BR));
585   }
586 
587   if (NewUnreleased.isEmpty()) {
588     State = State->remove<UnreleasedIvarMap>(SelfSym);
589   } else {
590     State = State->set<UnreleasedIvarMap>(SelfSym, NewUnreleased);
591   }
592 
593   if (ErrNode) {
594     C.addTransition(State, ErrNode);
595   } else if (State != InitialState) {
596     C.addTransition(State);
597   }
598 
599   // Make sure that after checking in the top-most frame the list of
600   // tracked ivars is empty. This is intended to detect accidental leaks in
601   // the UnreleasedIvarMap program state.
602   assert(!LCtx->inTopFrame() || State->get<UnreleasedIvarMap>().isEmpty());
603 }
604 
605 /// Given a symbol, determine whether the symbol refers to an ivar on
606 /// the top-most deallocating instance. If so, find the property for that
607 /// ivar, if one exists. Otherwise return null.
608 const ObjCPropertyImplDecl *
609 ObjCDeallocChecker::findPropertyOnDeallocatingInstance(
610     SymbolRef IvarSym, CheckerContext &C) const {
611   SVal DeallocedInstance;
612   if (!isInInstanceDealloc(C, DeallocedInstance))
613     return nullptr;
614 
615   // Try to get the region from which the ivar value was loaded.
616   auto *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
617   if (!IvarRegion)
618     return nullptr;
619 
620   // Don't try to find the property if the ivar was not loaded from the
621   // given instance.
622   if (DeallocedInstance.castAs<loc::MemRegionVal>().getRegion() !=
623       IvarRegion->getSuperRegion())
624     return nullptr;
625 
626   const LocationContext *LCtx = C.getLocationContext();
627   const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
628 
629   const ObjCImplDecl *Container = getContainingObjCImpl(LCtx);
630   const ObjCPropertyImplDecl *PropImpl =
631       Container->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
632   return PropImpl;
633 }
634 
635 /// Emits a warning if the current context is -dealloc and ReleasedValue
636 /// must not be directly released in a -dealloc. Returns true if a diagnostic
637 /// was emitted.
638 bool ObjCDeallocChecker::diagnoseExtraRelease(SymbolRef ReleasedValue,
639                                               const ObjCMethodCall &M,
640                                               CheckerContext &C) const {
641   // Try to get the region from which the released value was loaded.
642   // Note that, unlike diagnosing for missing releases, here we don't track
643   // values that must not be released in the state. This is because even if
644   // these values escape, it is still an error under the rules of MRR to
645   // release them in -dealloc.
646   const ObjCPropertyImplDecl *PropImpl =
647       findPropertyOnDeallocatingInstance(ReleasedValue, C);
648 
649   if (!PropImpl)
650     return false;
651 
652   // If the ivar belongs to a property that must not be released directly
653   // in dealloc, emit a warning.
654   if (getDeallocReleaseRequirement(PropImpl) !=
655       ReleaseRequirement::MustNotReleaseDirectly) {
656     return false;
657   }
658 
659   // If the property is readwrite but it shadows a read-only property in its
660   // external interface, treat the property a read-only. If the outside
661   // world cannot write to a property then the internal implementation is free
662   // to make its own convention about whether the value is stored retained
663   // or not. We look up the shadow here rather than in
664   // getDeallocReleaseRequirement() because doing so can be expensive.
665   const ObjCPropertyDecl *PropDecl = findShadowedPropertyDecl(PropImpl);
666   if (PropDecl) {
667     if (PropDecl->isReadOnly())
668       return false;
669   } else {
670     PropDecl = PropImpl->getPropertyDecl();
671   }
672 
673   ExplodedNode *ErrNode = C.generateNonFatalErrorNode();
674   if (!ErrNode)
675     return false;
676 
677   std::string Buf;
678   llvm::raw_string_ostream OS(Buf);
679 
680   assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Weak ||
681          (PropDecl->getSetterKind() == ObjCPropertyDecl::Assign &&
682           !PropDecl->isReadOnly()) ||
683          isReleasedByCIFilterDealloc(PropImpl)
684          );
685 
686   const ObjCImplDecl *Container = getContainingObjCImpl(C.getLocationContext());
687   OS << "The '" << *PropImpl->getPropertyIvarDecl()
688      << "' ivar in '" << *Container;
689 
690 
691   if (isReleasedByCIFilterDealloc(PropImpl)) {
692     OS << "' will be released by '-[CIFilter dealloc]' but also released here";
693   } else {
694     OS << "' was synthesized for ";
695 
696     if (PropDecl->getSetterKind() == ObjCPropertyDecl::Weak)
697       OS << "a weak";
698     else
699       OS << "an assign, readwrite";
700 
701     OS <<  " property but was released in 'dealloc'";
702   }
703 
704   auto BR = std::make_unique<PathSensitiveBugReport>(*ExtraReleaseBugType,
705                                                      OS.str(), ErrNode);
706   BR->addRange(M.getOriginExpr()->getSourceRange());
707 
708   C.emitReport(std::move(BR));
709 
710   return true;
711 }
712 
713 /// Emits a warning if the current context is -dealloc and DeallocedValue
714 /// must not be directly dealloced in a -dealloc. Returns true if a diagnostic
715 /// was emitted.
716 bool ObjCDeallocChecker::diagnoseMistakenDealloc(SymbolRef DeallocedValue,
717                                                  const ObjCMethodCall &M,
718                                                  CheckerContext &C) const {
719   // TODO: Apart from unknown/undefined receivers, this may happen when
720   // dealloc is called as a class method. Should we warn?
721   if (!DeallocedValue)
722     return false;
723 
724   // Find the property backing the instance variable that M
725   // is dealloc'ing.
726   const ObjCPropertyImplDecl *PropImpl =
727       findPropertyOnDeallocatingInstance(DeallocedValue, C);
728   if (!PropImpl)
729     return false;
730 
731   if (getDeallocReleaseRequirement(PropImpl) !=
732       ReleaseRequirement::MustRelease) {
733     return false;
734   }
735 
736   ExplodedNode *ErrNode = C.generateErrorNode();
737   if (!ErrNode)
738     return false;
739 
740   std::string Buf;
741   llvm::raw_string_ostream OS(Buf);
742 
743   OS << "'" << *PropImpl->getPropertyIvarDecl()
744      << "' should be released rather than deallocated";
745 
746   auto BR = std::make_unique<PathSensitiveBugReport>(*MistakenDeallocBugType,
747                                                      OS.str(), ErrNode);
748   BR->addRange(M.getOriginExpr()->getSourceRange());
749 
750   C.emitReport(std::move(BR));
751 
752   return true;
753 }
754 
755 ObjCDeallocChecker::ObjCDeallocChecker()
756     : NSObjectII(nullptr), SenTestCaseII(nullptr), XCTestCaseII(nullptr),
757       Block_releaseII(nullptr), CIFilterII(nullptr) {
758 
759   MissingReleaseBugType.reset(
760       new BugType(this, "Missing ivar release (leak)",
761                   categories::MemoryRefCount));
762 
763   ExtraReleaseBugType.reset(
764       new BugType(this, "Extra ivar release",
765                   categories::MemoryRefCount));
766 
767   MistakenDeallocBugType.reset(
768       new BugType(this, "Mistaken dealloc",
769                   categories::MemoryRefCount));
770 }
771 
772 void ObjCDeallocChecker::initIdentifierInfoAndSelectors(
773     ASTContext &Ctx) const {
774   if (NSObjectII)
775     return;
776 
777   NSObjectII = &Ctx.Idents.get("NSObject");
778   SenTestCaseII = &Ctx.Idents.get("SenTestCase");
779   XCTestCaseII = &Ctx.Idents.get("XCTestCase");
780   Block_releaseII = &Ctx.Idents.get("_Block_release");
781   CIFilterII = &Ctx.Idents.get("CIFilter");
782 
783   IdentifierInfo *DeallocII = &Ctx.Idents.get("dealloc");
784   IdentifierInfo *ReleaseII = &Ctx.Idents.get("release");
785   DeallocSel = Ctx.Selectors.getSelector(0, &DeallocII);
786   ReleaseSel = Ctx.Selectors.getSelector(0, &ReleaseII);
787 }
788 
789 /// Returns true if M is a call to '[super dealloc]'.
790 bool ObjCDeallocChecker::isSuperDeallocMessage(
791     const ObjCMethodCall &M) const {
792   if (M.getOriginExpr()->getReceiverKind() != ObjCMessageExpr::SuperInstance)
793     return false;
794 
795   return M.getSelector() == DeallocSel;
796 }
797 
798 /// Returns the ObjCImplDecl containing the method declaration in LCtx.
799 const ObjCImplDecl *
800 ObjCDeallocChecker::getContainingObjCImpl(const LocationContext *LCtx) const {
801   auto *MD = cast<ObjCMethodDecl>(LCtx->getDecl());
802   return cast<ObjCImplDecl>(MD->getDeclContext());
803 }
804 
805 /// Returns the property that shadowed by PropImpl if one exists and
806 /// nullptr otherwise.
807 const ObjCPropertyDecl *ObjCDeallocChecker::findShadowedPropertyDecl(
808     const ObjCPropertyImplDecl *PropImpl) const {
809   const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
810 
811   // Only readwrite properties can shadow.
812   if (PropDecl->isReadOnly())
813     return nullptr;
814 
815   auto *CatDecl = dyn_cast<ObjCCategoryDecl>(PropDecl->getDeclContext());
816 
817   // Only class extensions can contain shadowing properties.
818   if (!CatDecl || !CatDecl->IsClassExtension())
819     return nullptr;
820 
821   IdentifierInfo *ID = PropDecl->getIdentifier();
822   DeclContext::lookup_result R = CatDecl->getClassInterface()->lookup(ID);
823   for (const NamedDecl *D : R) {
824     auto *ShadowedPropDecl = dyn_cast<ObjCPropertyDecl>(D);
825     if (!ShadowedPropDecl)
826       continue;
827 
828     if (ShadowedPropDecl->isInstanceProperty()) {
829       assert(ShadowedPropDecl->isReadOnly());
830       return ShadowedPropDecl;
831     }
832   }
833 
834   return nullptr;
835 }
836 
837 /// Add a transition noting the release of the given value.
838 void ObjCDeallocChecker::transitionToReleaseValue(CheckerContext &C,
839                                                   SymbolRef Value) const {
840   assert(Value);
841   SymbolRef InstanceSym = getInstanceSymbolFromIvarSymbol(Value);
842   if (!InstanceSym)
843     return;
844   ProgramStateRef InitialState = C.getState();
845 
846   ProgramStateRef ReleasedState =
847       removeValueRequiringRelease(InitialState, InstanceSym, Value);
848 
849   if (ReleasedState != InitialState) {
850     C.addTransition(ReleasedState);
851   }
852 }
853 
854 /// Remove the Value requiring a release from the tracked set for
855 /// Instance and return the resultant state.
856 ProgramStateRef ObjCDeallocChecker::removeValueRequiringRelease(
857     ProgramStateRef State, SymbolRef Instance, SymbolRef Value) const {
858   assert(Instance);
859   assert(Value);
860   const ObjCIvarRegion *RemovedRegion = getIvarRegionForIvarSymbol(Value);
861   if (!RemovedRegion)
862     return State;
863 
864   const SymbolSet *Unreleased = State->get<UnreleasedIvarMap>(Instance);
865   if (!Unreleased)
866     return State;
867 
868   // Mark the value as no longer requiring a release.
869   SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
870   SymbolSet NewUnreleased = *Unreleased;
871   for (auto &Sym : *Unreleased) {
872     const ObjCIvarRegion *UnreleasedRegion = getIvarRegionForIvarSymbol(Sym);
873     assert(UnreleasedRegion);
874     if (RemovedRegion->getDecl() == UnreleasedRegion->getDecl()) {
875       NewUnreleased = F.remove(NewUnreleased, Sym);
876     }
877   }
878 
879   if (NewUnreleased.isEmpty()) {
880     return State->remove<UnreleasedIvarMap>(Instance);
881   }
882 
883   return State->set<UnreleasedIvarMap>(Instance, NewUnreleased);
884 }
885 
886 /// Determines whether the instance variable for \p PropImpl must or must not be
887 /// released in -dealloc or whether it cannot be determined.
888 ReleaseRequirement ObjCDeallocChecker::getDeallocReleaseRequirement(
889     const ObjCPropertyImplDecl *PropImpl) const {
890   const ObjCIvarDecl *IvarDecl;
891   const ObjCPropertyDecl *PropDecl;
892   if (!isSynthesizedRetainableProperty(PropImpl, &IvarDecl, &PropDecl))
893     return ReleaseRequirement::Unknown;
894 
895   ObjCPropertyDecl::SetterKind SK = PropDecl->getSetterKind();
896 
897   switch (SK) {
898   // Retain and copy setters retain/copy their values before storing and so
899   // the value in their instance variables must be released in -dealloc.
900   case ObjCPropertyDecl::Retain:
901   case ObjCPropertyDecl::Copy:
902     if (isReleasedByCIFilterDealloc(PropImpl))
903       return ReleaseRequirement::MustNotReleaseDirectly;
904 
905     if (isNibLoadedIvarWithoutRetain(PropImpl))
906       return ReleaseRequirement::Unknown;
907 
908     return ReleaseRequirement::MustRelease;
909 
910   case ObjCPropertyDecl::Weak:
911     return ReleaseRequirement::MustNotReleaseDirectly;
912 
913   case ObjCPropertyDecl::Assign:
914     // It is common for the ivars for read-only assign properties to
915     // always be stored retained, so their release requirement cannot be
916     // be determined.
917     if (PropDecl->isReadOnly())
918       return ReleaseRequirement::Unknown;
919 
920     return ReleaseRequirement::MustNotReleaseDirectly;
921   }
922   llvm_unreachable("Unrecognized setter kind");
923 }
924 
925 /// Returns the released value if M is a call a setter that releases
926 /// and nils out its underlying instance variable.
927 SymbolRef
928 ObjCDeallocChecker::getValueReleasedByNillingOut(const ObjCMethodCall &M,
929                                                  CheckerContext &C) const {
930   SVal ReceiverVal = M.getReceiverSVal();
931   if (!ReceiverVal.isValid())
932     return nullptr;
933 
934   if (M.getNumArgs() == 0)
935     return nullptr;
936 
937   if (!M.getArgExpr(0)->getType()->isObjCRetainableType())
938     return nullptr;
939 
940   // Is the first argument nil?
941   SVal Arg = M.getArgSVal(0);
942   ProgramStateRef notNilState, nilState;
943   std::tie(notNilState, nilState) =
944       M.getState()->assume(Arg.castAs<DefinedOrUnknownSVal>());
945   if (!(nilState && !notNilState))
946     return nullptr;
947 
948   const ObjCPropertyDecl *Prop = M.getAccessedProperty();
949   if (!Prop)
950     return nullptr;
951 
952   ObjCIvarDecl *PropIvarDecl = Prop->getPropertyIvarDecl();
953   if (!PropIvarDecl)
954     return nullptr;
955 
956   ProgramStateRef State = C.getState();
957 
958   SVal LVal = State->getLValue(PropIvarDecl, ReceiverVal);
959   std::optional<Loc> LValLoc = LVal.getAs<Loc>();
960   if (!LValLoc)
961     return nullptr;
962 
963   SVal CurrentValInIvar = State->getSVal(*LValLoc);
964   return CurrentValInIvar.getAsSymbol();
965 }
966 
967 /// Returns true if the current context is a call to -dealloc and false
968 /// otherwise. If true, it also sets SelfValOut to the value of
969 /// 'self'.
970 bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
971                                              SVal &SelfValOut) const {
972   return isInInstanceDealloc(C, C.getLocationContext(), SelfValOut);
973 }
974 
975 /// Returns true if LCtx is a call to -dealloc and false
976 /// otherwise. If true, it also sets SelfValOut to the value of
977 /// 'self'.
978 bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
979                                              const LocationContext *LCtx,
980                                              SVal &SelfValOut) const {
981   auto *MD = dyn_cast<ObjCMethodDecl>(LCtx->getDecl());
982   if (!MD || !MD->isInstanceMethod() || MD->getSelector() != DeallocSel)
983     return false;
984 
985   const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
986   assert(SelfDecl && "No self in -dealloc?");
987 
988   ProgramStateRef State = C.getState();
989   SelfValOut = State->getSVal(State->getRegion(SelfDecl, LCtx));
990   return true;
991 }
992 
993 /// Returns true if there is a call to -dealloc anywhere on the stack and false
994 /// otherwise. If true, it also sets InstanceValOut to the value of
995 /// 'self' in the frame for -dealloc.
996 bool ObjCDeallocChecker::instanceDeallocIsOnStack(const CheckerContext &C,
997                                                   SVal &InstanceValOut) const {
998   const LocationContext *LCtx = C.getLocationContext();
999 
1000   while (LCtx) {
1001     if (isInInstanceDealloc(C, LCtx, InstanceValOut))
1002       return true;
1003 
1004     LCtx = LCtx->getParent();
1005   }
1006 
1007   return false;
1008 }
1009 
1010 /// Returns true if the ID is a class in which is known to have
1011 /// a separate teardown lifecycle. In this case, -dealloc warnings
1012 /// about missing releases should be suppressed.
1013 bool ObjCDeallocChecker::classHasSeparateTeardown(
1014     const ObjCInterfaceDecl *ID) const {
1015   // Suppress if the class is not a subclass of NSObject.
1016   for ( ; ID ; ID = ID->getSuperClass()) {
1017     IdentifierInfo *II = ID->getIdentifier();
1018 
1019     if (II == NSObjectII)
1020       return false;
1021 
1022     // FIXME: For now, ignore classes that subclass SenTestCase and XCTestCase,
1023     // as these don't need to implement -dealloc.  They implement tear down in
1024     // another way, which we should try and catch later.
1025     //  http://llvm.org/bugs/show_bug.cgi?id=3187
1026     if (II == XCTestCaseII || II == SenTestCaseII)
1027       return true;
1028   }
1029 
1030   return true;
1031 }
1032 
1033 /// The -dealloc method in CIFilter highly unusual in that is will release
1034 /// instance variables belonging to its *subclasses* if the variable name
1035 /// starts with "input" or backs a property whose name starts with "input".
1036 /// Subclasses should not release these ivars in their own -dealloc method --
1037 /// doing so could result in an over release.
1038 ///
1039 /// This method returns true if the property will be released by
1040 /// -[CIFilter dealloc].
1041 bool ObjCDeallocChecker::isReleasedByCIFilterDealloc(
1042     const ObjCPropertyImplDecl *PropImpl) const {
1043   assert(PropImpl->getPropertyIvarDecl());
1044   StringRef PropName = PropImpl->getPropertyDecl()->getName();
1045   StringRef IvarName = PropImpl->getPropertyIvarDecl()->getName();
1046 
1047   const char *ReleasePrefix = "input";
1048   if (!(PropName.startswith(ReleasePrefix) ||
1049         IvarName.startswith(ReleasePrefix))) {
1050     return false;
1051   }
1052 
1053   const ObjCInterfaceDecl *ID =
1054       PropImpl->getPropertyIvarDecl()->getContainingInterface();
1055   for ( ; ID ; ID = ID->getSuperClass()) {
1056     IdentifierInfo *II = ID->getIdentifier();
1057     if (II == CIFilterII)
1058       return true;
1059   }
1060 
1061   return false;
1062 }
1063 
1064 /// Returns whether the ivar backing the property is an IBOutlet that
1065 /// has its value set by nib loading code without retaining the value.
1066 ///
1067 /// On macOS, if there is no setter, the nib-loading code sets the ivar
1068 /// directly, without retaining the value,
1069 ///
1070 /// On iOS and its derivatives, the nib-loading code will call
1071 /// -setValue:forKey:, which retains the value before directly setting the ivar.
1072 bool ObjCDeallocChecker::isNibLoadedIvarWithoutRetain(
1073     const ObjCPropertyImplDecl *PropImpl) const {
1074   const ObjCIvarDecl *IvarDecl = PropImpl->getPropertyIvarDecl();
1075   if (!IvarDecl->hasAttr<IBOutletAttr>())
1076     return false;
1077 
1078   const llvm::Triple &Target =
1079       IvarDecl->getASTContext().getTargetInfo().getTriple();
1080 
1081   if (!Target.isMacOSX())
1082     return false;
1083 
1084   if (PropImpl->getPropertyDecl()->getSetterMethodDecl())
1085     return false;
1086 
1087   return true;
1088 }
1089 
1090 void ento::registerObjCDeallocChecker(CheckerManager &Mgr) {
1091   Mgr.registerChecker<ObjCDeallocChecker>();
1092 }
1093 
1094 bool ento::shouldRegisterObjCDeallocChecker(const CheckerManager &mgr) {
1095   // These checker only makes sense under MRR.
1096   const LangOptions &LO = mgr.getLangOpts();
1097   return LO.getGC() != LangOptions::GCOnly && !LO.ObjCAutoRefCount;
1098 }
1099