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