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