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