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