1 //==- CheckObjCDealloc.cpp - Check ObjC -dealloc implementation --*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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'.
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.
29 //===----------------------------------------------------------------------===//
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/Basic/TargetInfo.h"
38 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
39 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
40 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
41 #include "clang/StaticAnalyzer/Core/Checker.h"
42 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
43 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
44 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
45 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
46 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
47 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
48 #include "llvm/Support/raw_ostream.h"
50 using namespace clang;
53 /// Indicates whether an instance variable is required to be released in
55 enum class ReleaseRequirement {
56 /// The instance variable must be released, either by calling
57 /// -release on it directly or by nilling it out with a property setter.
60 /// The instance variable must not be directly released with -release.
61 MustNotReleaseDirectly,
63 /// The requirement for the instance variable could not be determined.
67 /// Returns true if the property implementation is synthesized and the
68 /// type of the property is retainable.
69 static bool isSynthesizedRetainableProperty(const ObjCPropertyImplDecl *I,
70 const ObjCIvarDecl **ID,
71 const ObjCPropertyDecl **PD) {
73 if (I->getPropertyImplementation() != ObjCPropertyImplDecl::Synthesize)
76 (*ID) = I->getPropertyIvarDecl();
80 QualType T = (*ID)->getType();
81 if (!T->isObjCRetainableType())
84 (*PD) = I->getPropertyDecl();
85 // Shouldn't be able to synthesize a property that doesn't exist.
93 class ObjCDeallocChecker
94 : public Checker<check::ASTDecl<ObjCImplementationDecl>,
95 check::PreObjCMessage, check::PostObjCMessage,
97 check::BeginFunction, check::EndFunction,
100 check::PreStmt<ReturnStmt>> {
102 mutable IdentifierInfo *NSObjectII, *SenTestCaseII, *XCTestCaseII,
103 *Block_releaseII, *CIFilterII;
105 mutable Selector DeallocSel, ReleaseSel;
107 std::unique_ptr<BugType> MissingReleaseBugType;
108 std::unique_ptr<BugType> ExtraReleaseBugType;
109 std::unique_ptr<BugType> MistakenDeallocBugType;
112 ObjCDeallocChecker();
114 void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
115 BugReporter &BR) const;
116 void checkBeginFunction(CheckerContext &Ctx) const;
117 void checkPreObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
118 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
119 void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
121 ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
122 bool Assumption) const;
124 ProgramStateRef checkPointerEscape(ProgramStateRef State,
125 const InvalidatedSymbols &Escaped,
126 const CallEvent *Call,
127 PointerEscapeKind Kind) const;
128 void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
129 void checkEndFunction(CheckerContext &Ctx) const;
132 void diagnoseMissingReleases(CheckerContext &C) const;
134 bool diagnoseExtraRelease(SymbolRef ReleasedValue, const ObjCMethodCall &M,
135 CheckerContext &C) const;
137 bool diagnoseMistakenDealloc(SymbolRef DeallocedValue,
138 const ObjCMethodCall &M,
139 CheckerContext &C) const;
141 SymbolRef getValueReleasedByNillingOut(const ObjCMethodCall &M,
142 CheckerContext &C) const;
144 const ObjCIvarRegion *getIvarRegionForIvarSymbol(SymbolRef IvarSym) const;
145 SymbolRef getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const;
147 const ObjCPropertyImplDecl*
148 findPropertyOnDeallocatingInstance(SymbolRef IvarSym,
149 CheckerContext &C) const;
152 getDeallocReleaseRequirement(const ObjCPropertyImplDecl *PropImpl) const;
154 bool isInInstanceDealloc(const CheckerContext &C, SVal &SelfValOut) const;
155 bool isInInstanceDealloc(const CheckerContext &C, const LocationContext *LCtx,
156 SVal &SelfValOut) const;
157 bool instanceDeallocIsOnStack(const CheckerContext &C,
158 SVal &InstanceValOut) const;
160 bool isSuperDeallocMessage(const ObjCMethodCall &M) const;
162 const ObjCImplDecl *getContainingObjCImpl(const LocationContext *LCtx) const;
164 const ObjCPropertyDecl *
165 findShadowedPropertyDecl(const ObjCPropertyImplDecl *PropImpl) const;
167 void transitionToReleaseValue(CheckerContext &C, SymbolRef Value) const;
168 ProgramStateRef removeValueRequiringRelease(ProgramStateRef State,
169 SymbolRef InstanceSym,
170 SymbolRef ValueSym) const;
172 void initIdentifierInfoAndSelectors(ASTContext &Ctx) const;
174 bool classHasSeparateTeardown(const ObjCInterfaceDecl *ID) const;
176 bool isReleasedByCIFilterDealloc(const ObjCPropertyImplDecl *PropImpl) const;
177 bool isNibLoadedIvarWithoutRetain(const ObjCPropertyImplDecl *PropImpl) const;
179 } // End anonymous namespace.
181 typedef llvm::ImmutableSet<SymbolRef> SymbolSet;
183 /// Maps from the symbol for a class instance to the set of
184 /// symbols remaining that must be released in -dealloc.
185 REGISTER_MAP_WITH_PROGRAMSTATE(UnreleasedIvarMap, SymbolRef, SymbolSet)
189 template<> struct ProgramStateTrait<SymbolSet>
190 : public ProgramStatePartialTrait<SymbolSet> {
191 static void *GDMIndex() { static int index = 0; return &index; }
196 /// An AST check that diagnose when the class requires a -dealloc method and
198 void ObjCDeallocChecker::checkASTDecl(const ObjCImplementationDecl *D,
199 AnalysisManager &Mgr,
200 BugReporter &BR) const {
201 assert(Mgr.getLangOpts().getGC() != LangOptions::GCOnly);
202 assert(!Mgr.getLangOpts().ObjCAutoRefCount);
203 initIdentifierInfoAndSelectors(Mgr.getASTContext());
205 const ObjCInterfaceDecl *ID = D->getClassInterface();
206 // If the class is known to have a lifecycle with a separate teardown method
207 // then it may not require a -dealloc method.
208 if (classHasSeparateTeardown(ID))
211 // Does the class contain any synthesized properties that are retainable?
212 // If not, skip the check entirely.
213 const ObjCPropertyImplDecl *PropImplRequiringRelease = nullptr;
214 bool HasOthers = false;
215 for (const auto *I : D->property_impls()) {
216 if (getDeallocReleaseRequirement(I) == ReleaseRequirement::MustRelease) {
217 if (!PropImplRequiringRelease)
218 PropImplRequiringRelease = I;
226 if (!PropImplRequiringRelease)
229 const ObjCMethodDecl *MD = nullptr;
231 // Scan the instance methods for "dealloc".
232 for (const auto *I : D->instance_methods()) {
233 if (I->getSelector() == DeallocSel) {
239 if (!MD) { // No dealloc found.
240 const char* Name = "Missing -dealloc";
243 llvm::raw_string_ostream OS(Buf);
244 OS << "'" << *D << "' lacks a 'dealloc' instance method but "
245 << "must release '" << *PropImplRequiringRelease->getPropertyIvarDecl()
250 PathDiagnosticLocation DLoc =
251 PathDiagnosticLocation::createBegin(D, BR.getSourceManager());
253 BR.EmitBasicReport(D, this, Name, categories::CoreFoundationObjectiveC,
259 /// If this is the beginning of -dealloc, mark the values initially stored in
260 /// instance variables that must be released by the end of -dealloc
261 /// as unreleased in the state.
262 void ObjCDeallocChecker::checkBeginFunction(
263 CheckerContext &C) const {
264 initIdentifierInfoAndSelectors(C.getASTContext());
266 // Only do this if the current method is -dealloc.
268 if (!isInInstanceDealloc(C, SelfVal))
271 SymbolRef SelfSymbol = SelfVal.getAsSymbol();
273 const LocationContext *LCtx = C.getLocationContext();
274 ProgramStateRef InitialState = C.getState();
276 ProgramStateRef State = InitialState;
278 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
280 // Symbols that must be released by the end of the -dealloc;
281 SymbolSet RequiredReleases = F.getEmptySet();
283 // If we're an inlined -dealloc, we should add our symbols to the existing
284 // set from our subclass.
285 if (const SymbolSet *CurrSet = State->get<UnreleasedIvarMap>(SelfSymbol))
286 RequiredReleases = *CurrSet;
288 for (auto *PropImpl : getContainingObjCImpl(LCtx)->property_impls()) {
289 ReleaseRequirement Requirement = getDeallocReleaseRequirement(PropImpl);
290 if (Requirement != ReleaseRequirement::MustRelease)
293 SVal LVal = State->getLValue(PropImpl->getPropertyIvarDecl(), SelfVal);
294 Optional<Loc> LValLoc = LVal.getAs<Loc>();
298 SVal InitialVal = State->getSVal(LValLoc.getValue());
299 SymbolRef Symbol = InitialVal.getAsSymbol();
300 if (!Symbol || !isa<SymbolRegionValue>(Symbol))
303 // Mark the value as requiring a release.
304 RequiredReleases = F.add(RequiredReleases, Symbol);
307 if (!RequiredReleases.isEmpty()) {
308 State = State->set<UnreleasedIvarMap>(SelfSymbol, RequiredReleases);
311 if (State != InitialState) {
312 C.addTransition(State);
316 /// Given a symbol for an ivar, return the ivar region it was loaded from.
317 /// Returns nullptr if the instance symbol cannot be found.
318 const ObjCIvarRegion *
319 ObjCDeallocChecker::getIvarRegionForIvarSymbol(SymbolRef IvarSym) const {
320 return dyn_cast_or_null<ObjCIvarRegion>(IvarSym->getOriginRegion());
323 /// Given a symbol for an ivar, return a symbol for the instance containing
324 /// the ivar. Returns nullptr if the instance symbol cannot be found.
326 ObjCDeallocChecker::getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const {
328 const ObjCIvarRegion *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
332 return IvarRegion->getSymbolicBase()->getSymbol();
335 /// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
336 /// a release or a nilling-out property setter.
337 void ObjCDeallocChecker::checkPreObjCMessage(
338 const ObjCMethodCall &M, CheckerContext &C) const {
339 // Only run if -dealloc is on the stack.
340 SVal DeallocedInstance;
341 if (!instanceDeallocIsOnStack(C, DeallocedInstance))
344 SymbolRef ReleasedValue = nullptr;
346 if (M.getSelector() == ReleaseSel) {
347 ReleasedValue = M.getReceiverSVal().getAsSymbol();
348 } else if (M.getSelector() == DeallocSel && !M.isReceiverSelfOrSuper()) {
349 if (diagnoseMistakenDealloc(M.getReceiverSVal().getAsSymbol(), M, C))
354 // An instance variable symbol was released with -release:
355 // [_property release];
356 if (diagnoseExtraRelease(ReleasedValue,M, C))
359 // An instance variable symbol was released nilling out its property:
360 // self.property = nil;
361 ReleasedValue = getValueReleasedByNillingOut(M, C);
367 transitionToReleaseValue(C, ReleasedValue);
370 /// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
371 /// call to Block_release().
372 void ObjCDeallocChecker::checkPreCall(const CallEvent &Call,
373 CheckerContext &C) const {
374 const IdentifierInfo *II = Call.getCalleeIdentifier();
375 if (II != Block_releaseII)
378 if (Call.getNumArgs() != 1)
381 SymbolRef ReleasedValue = Call.getArgSVal(0).getAsSymbol();
385 transitionToReleaseValue(C, ReleasedValue);
387 /// If the message was a call to '[super dealloc]', diagnose any missing
389 void ObjCDeallocChecker::checkPostObjCMessage(
390 const ObjCMethodCall &M, CheckerContext &C) const {
391 // We perform this check post-message so that if the super -dealloc
392 // calls a helper method and that this class overrides, any ivars released in
393 // the helper method will be recorded before checking.
394 if (isSuperDeallocMessage(M))
395 diagnoseMissingReleases(C);
398 /// Check for missing releases even when -dealloc does not call
399 /// '[super dealloc]'.
400 void ObjCDeallocChecker::checkEndFunction(
401 CheckerContext &C) const {
402 diagnoseMissingReleases(C);
405 /// Check for missing releases on early return.
406 void ObjCDeallocChecker::checkPreStmt(
407 const ReturnStmt *RS, CheckerContext &C) const {
408 diagnoseMissingReleases(C);
411 /// When a symbol is assumed to be nil, remove it from the set of symbols
412 /// require to be nil.
413 ProgramStateRef ObjCDeallocChecker::evalAssume(ProgramStateRef State, SVal Cond,
414 bool Assumption) const {
415 if (State->get<UnreleasedIvarMap>().isEmpty())
418 auto *CondBSE = dyn_cast_or_null<BinarySymExpr>(Cond.getAsSymExpr());
422 BinaryOperator::Opcode OpCode = CondBSE->getOpcode();
431 SymbolRef NullSymbol = nullptr;
432 if (auto *SIE = dyn_cast<SymIntExpr>(CondBSE)) {
433 const llvm::APInt &RHS = SIE->getRHS();
436 NullSymbol = SIE->getLHS();
437 } else if (auto *SIE = dyn_cast<IntSymExpr>(CondBSE)) {
438 const llvm::APInt &LHS = SIE->getLHS();
441 NullSymbol = SIE->getRHS();
446 SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(NullSymbol);
450 State = removeValueRequiringRelease(State, InstanceSymbol, NullSymbol);
455 /// If a symbol escapes conservatively assume unseen code released it.
456 ProgramStateRef ObjCDeallocChecker::checkPointerEscape(
457 ProgramStateRef State, const InvalidatedSymbols &Escaped,
458 const CallEvent *Call, PointerEscapeKind Kind) const {
460 if (State->get<UnreleasedIvarMap>().isEmpty())
463 // Don't treat calls to '[super dealloc]' as escaping for the purposes
464 // of this checker. Because the checker diagnoses missing releases in the
465 // post-message handler for '[super dealloc], escaping here would cause
466 // the checker to never warn.
467 auto *OMC = dyn_cast_or_null<ObjCMethodCall>(Call);
468 if (OMC && isSuperDeallocMessage(*OMC))
471 for (const auto &Sym : Escaped) {
472 if (!Call || (Call && !Call->isInSystemHeader())) {
473 // If Sym is a symbol for an object with instance variables that
474 // must be released, remove these obligations when the object escapes
475 // unless via a call to a system function. System functions are
476 // very unlikely to release instance variables on objects passed to them,
477 // and are frequently called on 'self' in -dealloc (e.g., to remove
478 // observers) -- we want to avoid false negatives from escaping on
480 State = State->remove<UnreleasedIvarMap>(Sym);
484 SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(Sym);
488 State = removeValueRequiringRelease(State, InstanceSymbol, Sym);
494 /// Report any unreleased instance variables for the current instance being
496 void ObjCDeallocChecker::diagnoseMissingReleases(CheckerContext &C) const {
497 ProgramStateRef State = C.getState();
500 if (!isInInstanceDealloc(C, SelfVal))
503 const MemRegion *SelfRegion = SelfVal.castAs<loc::MemRegionVal>().getRegion();
504 const LocationContext *LCtx = C.getLocationContext();
506 ExplodedNode *ErrNode = nullptr;
508 SymbolRef SelfSym = SelfVal.getAsSymbol();
512 const SymbolSet *OldUnreleased = State->get<UnreleasedIvarMap>(SelfSym);
516 SymbolSet NewUnreleased = *OldUnreleased;
517 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
519 ProgramStateRef InitialState = State;
521 for (auto *IvarSymbol : *OldUnreleased) {
522 const TypedValueRegion *TVR =
523 cast<SymbolRegionValue>(IvarSymbol)->getRegion();
524 const ObjCIvarRegion *IvarRegion = cast<ObjCIvarRegion>(TVR);
526 // Don't warn if the ivar is not for this instance.
527 if (SelfRegion != IvarRegion->getSuperRegion())
530 const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
531 // Prevent an inlined call to -dealloc in a super class from warning
532 // about the values the subclass's -dealloc should release.
533 if (IvarDecl->getContainingInterface() !=
534 cast<ObjCMethodDecl>(LCtx->getDecl())->getClassInterface())
537 // Prevents diagnosing multiple times for the same instance variable
538 // at, for example, both a return and at the end of of the function.
539 NewUnreleased = F.remove(NewUnreleased, IvarSymbol);
541 if (State->getStateManager()
542 .getConstraintManager()
543 .isNull(State, IvarSymbol)
544 .isConstrainedTrue()) {
548 // A missing release manifests as a leak, so treat as a non-fatal error.
550 ErrNode = C.generateNonFatalErrorNode();
551 // If we've already reached this node on another path, return without
557 llvm::raw_string_ostream OS(Buf);
559 const ObjCInterfaceDecl *Interface = IvarDecl->getContainingInterface();
560 // If the class is known to have a lifecycle with teardown that is
561 // separate from -dealloc, do not warn about missing releases. We
562 // suppress here (rather than not tracking for instance variables in
563 // such classes) because these classes are rare.
564 if (classHasSeparateTeardown(Interface))
567 ObjCImplDecl *ImplDecl = Interface->getImplementation();
569 const ObjCPropertyImplDecl *PropImpl =
570 ImplDecl->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
572 const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
574 assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Copy ||
575 PropDecl->getSetterKind() == ObjCPropertyDecl::Retain);
577 OS << "The '" << *IvarDecl << "' ivar in '" << *ImplDecl
580 if (PropDecl->getSetterKind() == ObjCPropertyDecl::Retain)
585 OS << " by a synthesized property but not released"
586 " before '[super dealloc]'";
588 std::unique_ptr<BugReport> BR(
589 new BugReport(*MissingReleaseBugType, OS.str(), ErrNode));
591 C.emitReport(std::move(BR));
594 if (NewUnreleased.isEmpty()) {
595 State = State->remove<UnreleasedIvarMap>(SelfSym);
597 State = State->set<UnreleasedIvarMap>(SelfSym, NewUnreleased);
601 C.addTransition(State, ErrNode);
602 } else if (State != InitialState) {
603 C.addTransition(State);
606 // Make sure that after checking in the top-most frame the list of
607 // tracked ivars is empty. This is intended to detect accidental leaks in
608 // the UnreleasedIvarMap program state.
609 assert(!LCtx->inTopFrame() || State->get<UnreleasedIvarMap>().isEmpty());
612 /// Given a symbol, determine whether the symbol refers to an ivar on
613 /// the top-most deallocating instance. If so, find the property for that
614 /// ivar, if one exists. Otherwise return null.
615 const ObjCPropertyImplDecl *
616 ObjCDeallocChecker::findPropertyOnDeallocatingInstance(
617 SymbolRef IvarSym, CheckerContext &C) const {
618 SVal DeallocedInstance;
619 if (!isInInstanceDealloc(C, DeallocedInstance))
622 // Try to get the region from which the ivar value was loaded.
623 auto *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
627 // Don't try to find the property if the ivar was not loaded from the
629 if (DeallocedInstance.castAs<loc::MemRegionVal>().getRegion() !=
630 IvarRegion->getSuperRegion())
633 const LocationContext *LCtx = C.getLocationContext();
634 const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
636 const ObjCImplDecl *Container = getContainingObjCImpl(LCtx);
637 const ObjCPropertyImplDecl *PropImpl =
638 Container->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
642 /// Emits a warning if the current context is -dealloc and ReleasedValue
643 /// must not be directly released in a -dealloc. Returns true if a diagnostic
645 bool ObjCDeallocChecker::diagnoseExtraRelease(SymbolRef ReleasedValue,
646 const ObjCMethodCall &M,
647 CheckerContext &C) const {
648 // Try to get the region from which the the released value was loaded.
649 // Note that, unlike diagnosing for missing releases, here we don't track
650 // values that must not be released in the state. This is because even if
651 // these values escape, it is still an error under the rules of MRR to
652 // release them in -dealloc.
653 const ObjCPropertyImplDecl *PropImpl =
654 findPropertyOnDeallocatingInstance(ReleasedValue, C);
659 // If the ivar belongs to a property that must not be released directly
660 // in dealloc, emit a warning.
661 if (getDeallocReleaseRequirement(PropImpl) !=
662 ReleaseRequirement::MustNotReleaseDirectly) {
666 // If the property is readwrite but it shadows a read-only property in its
667 // external interface, treat the property a read-only. If the outside
668 // world cannot write to a property then the internal implementation is free
669 // to make its own convention about whether the value is stored retained
670 // or not. We look up the shadow here rather than in
671 // getDeallocReleaseRequirement() because doing so can be expensive.
672 const ObjCPropertyDecl *PropDecl = findShadowedPropertyDecl(PropImpl);
674 if (PropDecl->isReadOnly())
677 PropDecl = PropImpl->getPropertyDecl();
680 ExplodedNode *ErrNode = C.generateNonFatalErrorNode();
685 llvm::raw_string_ostream OS(Buf);
687 assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Weak ||
688 (PropDecl->getSetterKind() == ObjCPropertyDecl::Assign &&
689 !PropDecl->isReadOnly()) ||
690 isReleasedByCIFilterDealloc(PropImpl)
693 const ObjCImplDecl *Container = getContainingObjCImpl(C.getLocationContext());
694 OS << "The '" << *PropImpl->getPropertyIvarDecl()
695 << "' ivar in '" << *Container;
698 if (isReleasedByCIFilterDealloc(PropImpl)) {
699 OS << "' will be released by '-[CIFilter dealloc]' but also released here";
701 OS << "' was synthesized for ";
703 if (PropDecl->getSetterKind() == ObjCPropertyDecl::Weak)
706 OS << "an assign, readwrite";
708 OS << " property but was released in 'dealloc'";
711 std::unique_ptr<BugReport> BR(
712 new BugReport(*ExtraReleaseBugType, OS.str(), ErrNode));
713 BR->addRange(M.getOriginExpr()->getSourceRange());
715 C.emitReport(std::move(BR));
720 /// Emits a warning if the current context is -dealloc and DeallocedValue
721 /// must not be directly dealloced in a -dealloc. Returns true if a diagnostic
723 bool ObjCDeallocChecker::diagnoseMistakenDealloc(SymbolRef DeallocedValue,
724 const ObjCMethodCall &M,
725 CheckerContext &C) const {
727 // Find the property backing the instance variable that M
729 const ObjCPropertyImplDecl *PropImpl =
730 findPropertyOnDeallocatingInstance(DeallocedValue, C);
734 if (getDeallocReleaseRequirement(PropImpl) !=
735 ReleaseRequirement::MustRelease) {
739 ExplodedNode *ErrNode = C.generateErrorNode();
744 llvm::raw_string_ostream OS(Buf);
746 OS << "'" << *PropImpl->getPropertyIvarDecl()
747 << "' should be released rather than deallocated";
749 std::unique_ptr<BugReport> BR(
750 new BugReport(*MistakenDeallocBugType, OS.str(), ErrNode));
751 BR->addRange(M.getOriginExpr()->getSourceRange());
753 C.emitReport(std::move(BR));
758 ObjCDeallocChecker::ObjCDeallocChecker()
759 : NSObjectII(nullptr), SenTestCaseII(nullptr), XCTestCaseII(nullptr),
760 CIFilterII(nullptr) {
762 MissingReleaseBugType.reset(
763 new BugType(this, "Missing ivar release (leak)",
764 categories::MemoryCoreFoundationObjectiveC));
766 ExtraReleaseBugType.reset(
767 new BugType(this, "Extra ivar release",
768 categories::MemoryCoreFoundationObjectiveC));
770 MistakenDeallocBugType.reset(
771 new BugType(this, "Mistaken dealloc",
772 categories::MemoryCoreFoundationObjectiveC));
775 void ObjCDeallocChecker::initIdentifierInfoAndSelectors(
776 ASTContext &Ctx) const {
780 NSObjectII = &Ctx.Idents.get("NSObject");
781 SenTestCaseII = &Ctx.Idents.get("SenTestCase");
782 XCTestCaseII = &Ctx.Idents.get("XCTestCase");
783 Block_releaseII = &Ctx.Idents.get("_Block_release");
784 CIFilterII = &Ctx.Idents.get("CIFilter");
786 IdentifierInfo *DeallocII = &Ctx.Idents.get("dealloc");
787 IdentifierInfo *ReleaseII = &Ctx.Idents.get("release");
788 DeallocSel = Ctx.Selectors.getSelector(0, &DeallocII);
789 ReleaseSel = Ctx.Selectors.getSelector(0, &ReleaseII);
792 /// Returns true if M is a call to '[super dealloc]'.
793 bool ObjCDeallocChecker::isSuperDeallocMessage(
794 const ObjCMethodCall &M) const {
795 if (M.getOriginExpr()->getReceiverKind() != ObjCMessageExpr::SuperInstance)
798 return M.getSelector() == DeallocSel;
801 /// Returns the ObjCImplDecl containing the method declaration in LCtx.
803 ObjCDeallocChecker::getContainingObjCImpl(const LocationContext *LCtx) const {
804 auto *MD = cast<ObjCMethodDecl>(LCtx->getDecl());
805 return cast<ObjCImplDecl>(MD->getDeclContext());
808 /// Returns the property that shadowed by PropImpl if one exists and
809 /// nullptr otherwise.
810 const ObjCPropertyDecl *ObjCDeallocChecker::findShadowedPropertyDecl(
811 const ObjCPropertyImplDecl *PropImpl) const {
812 const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
814 // Only readwrite properties can shadow.
815 if (PropDecl->isReadOnly())
818 auto *CatDecl = dyn_cast<ObjCCategoryDecl>(PropDecl->getDeclContext());
820 // Only class extensions can contain shadowing properties.
821 if (!CatDecl || !CatDecl->IsClassExtension())
824 IdentifierInfo *ID = PropDecl->getIdentifier();
825 DeclContext::lookup_result R = CatDecl->getClassInterface()->lookup(ID);
826 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
827 auto *ShadowedPropDecl = dyn_cast<ObjCPropertyDecl>(*I);
828 if (!ShadowedPropDecl)
831 if (ShadowedPropDecl->isInstanceProperty()) {
832 assert(ShadowedPropDecl->isReadOnly());
833 return ShadowedPropDecl;
840 /// Add a transition noting the release of the given value.
841 void ObjCDeallocChecker::transitionToReleaseValue(CheckerContext &C,
842 SymbolRef Value) const {
844 SymbolRef InstanceSym = getInstanceSymbolFromIvarSymbol(Value);
847 ProgramStateRef InitialState = C.getState();
849 ProgramStateRef ReleasedState =
850 removeValueRequiringRelease(InitialState, InstanceSym, Value);
852 if (ReleasedState != InitialState) {
853 C.addTransition(ReleasedState);
857 /// Remove the Value requiring a release from the tracked set for
858 /// Instance and return the resultant state.
859 ProgramStateRef ObjCDeallocChecker::removeValueRequiringRelease(
860 ProgramStateRef State, SymbolRef Instance, SymbolRef Value) const {
863 const ObjCIvarRegion *RemovedRegion = getIvarRegionForIvarSymbol(Value);
867 const SymbolSet *Unreleased = State->get<UnreleasedIvarMap>(Instance);
871 // Mark the value as no longer requiring a release.
872 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
873 SymbolSet NewUnreleased = *Unreleased;
874 for (auto &Sym : *Unreleased) {
875 const ObjCIvarRegion *UnreleasedRegion = getIvarRegionForIvarSymbol(Sym);
876 assert(UnreleasedRegion);
877 if (RemovedRegion->getDecl() == UnreleasedRegion->getDecl()) {
878 NewUnreleased = F.remove(NewUnreleased, Sym);
882 if (NewUnreleased.isEmpty()) {
883 return State->remove<UnreleasedIvarMap>(Instance);
886 return State->set<UnreleasedIvarMap>(Instance, NewUnreleased);
889 /// Determines whether the instance variable for \p PropImpl must or must not be
890 /// released in -dealloc or whether it cannot be determined.
891 ReleaseRequirement ObjCDeallocChecker::getDeallocReleaseRequirement(
892 const ObjCPropertyImplDecl *PropImpl) const {
893 const ObjCIvarDecl *IvarDecl;
894 const ObjCPropertyDecl *PropDecl;
895 if (!isSynthesizedRetainableProperty(PropImpl, &IvarDecl, &PropDecl))
896 return ReleaseRequirement::Unknown;
898 ObjCPropertyDecl::SetterKind SK = PropDecl->getSetterKind();
901 // Retain and copy setters retain/copy their values before storing and so
902 // the value in their instance variables must be released in -dealloc.
903 case ObjCPropertyDecl::Retain:
904 case ObjCPropertyDecl::Copy:
905 if (isReleasedByCIFilterDealloc(PropImpl))
906 return ReleaseRequirement::MustNotReleaseDirectly;
908 if (isNibLoadedIvarWithoutRetain(PropImpl))
909 return ReleaseRequirement::Unknown;
911 return ReleaseRequirement::MustRelease;
913 case ObjCPropertyDecl::Weak:
914 return ReleaseRequirement::MustNotReleaseDirectly;
916 case ObjCPropertyDecl::Assign:
917 // It is common for the ivars for read-only assign properties to
918 // always be stored retained, so their release requirement cannot be
920 if (PropDecl->isReadOnly())
921 return ReleaseRequirement::Unknown;
923 return ReleaseRequirement::MustNotReleaseDirectly;
925 llvm_unreachable("Unrecognized setter kind");
928 /// Returns the released value if M is a call a setter that releases
929 /// and nils out its underlying instance variable.
931 ObjCDeallocChecker::getValueReleasedByNillingOut(const ObjCMethodCall &M,
932 CheckerContext &C) const {
933 SVal ReceiverVal = M.getReceiverSVal();
934 if (!ReceiverVal.isValid())
937 if (M.getNumArgs() == 0)
940 if (!M.getArgExpr(0)->getType()->isObjCRetainableType())
943 // Is the first argument nil?
944 SVal Arg = M.getArgSVal(0);
945 ProgramStateRef notNilState, nilState;
946 std::tie(notNilState, nilState) =
947 M.getState()->assume(Arg.castAs<DefinedOrUnknownSVal>());
948 if (!(nilState && !notNilState))
951 const ObjCPropertyDecl *Prop = M.getAccessedProperty();
955 ObjCIvarDecl *PropIvarDecl = Prop->getPropertyIvarDecl();
959 ProgramStateRef State = C.getState();
961 SVal LVal = State->getLValue(PropIvarDecl, ReceiverVal);
962 Optional<Loc> LValLoc = LVal.getAs<Loc>();
966 SVal CurrentValInIvar = State->getSVal(LValLoc.getValue());
967 return CurrentValInIvar.getAsSymbol();
970 /// Returns true if the current context is a call to -dealloc and false
971 /// otherwise. If true, it also sets SelfValOut to the value of
973 bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
974 SVal &SelfValOut) const {
975 return isInInstanceDealloc(C, C.getLocationContext(), SelfValOut);
978 /// Returns true if LCtx is a call to -dealloc and false
979 /// otherwise. If true, it also sets SelfValOut to the value of
981 bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
982 const LocationContext *LCtx,
983 SVal &SelfValOut) const {
984 auto *MD = dyn_cast<ObjCMethodDecl>(LCtx->getDecl());
985 if (!MD || !MD->isInstanceMethod() || MD->getSelector() != DeallocSel)
988 const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
989 assert(SelfDecl && "No self in -dealloc?");
991 ProgramStateRef State = C.getState();
992 SelfValOut = State->getSVal(State->getRegion(SelfDecl, LCtx));
996 /// Returns true if there is a call to -dealloc anywhere on the stack and false
997 /// otherwise. If true, it also sets InstanceValOut to the value of
998 /// 'self' in the frame for -dealloc.
999 bool ObjCDeallocChecker::instanceDeallocIsOnStack(const CheckerContext &C,
1000 SVal &InstanceValOut) const {
1001 const LocationContext *LCtx = C.getLocationContext();
1004 if (isInInstanceDealloc(C, LCtx, InstanceValOut))
1007 LCtx = LCtx->getParent();
1013 /// Returns true if the ID is a class in which which is known to have
1014 /// a separate teardown lifecycle. In this case, -dealloc warnings
1015 /// about missing releases should be suppressed.
1016 bool ObjCDeallocChecker::classHasSeparateTeardown(
1017 const ObjCInterfaceDecl *ID) const {
1018 // Suppress if the class is not a subclass of NSObject.
1019 for ( ; ID ; ID = ID->getSuperClass()) {
1020 IdentifierInfo *II = ID->getIdentifier();
1022 if (II == NSObjectII)
1025 // FIXME: For now, ignore classes that subclass SenTestCase and XCTestCase,
1026 // as these don't need to implement -dealloc. They implement tear down in
1027 // another way, which we should try and catch later.
1028 // http://llvm.org/bugs/show_bug.cgi?id=3187
1029 if (II == XCTestCaseII || II == SenTestCaseII)
1036 /// The -dealloc method in CIFilter highly unusual in that is will release
1037 /// instance variables belonging to its *subclasses* if the variable name
1038 /// starts with "input" or backs a property whose name starts with "input".
1039 /// Subclasses should not release these ivars in their own -dealloc method --
1040 /// doing so could result in an over release.
1042 /// This method returns true if the property will be released by
1043 /// -[CIFilter dealloc].
1044 bool ObjCDeallocChecker::isReleasedByCIFilterDealloc(
1045 const ObjCPropertyImplDecl *PropImpl) const {
1046 assert(PropImpl->getPropertyIvarDecl());
1047 StringRef PropName = PropImpl->getPropertyDecl()->getName();
1048 StringRef IvarName = PropImpl->getPropertyIvarDecl()->getName();
1050 const char *ReleasePrefix = "input";
1051 if (!(PropName.startswith(ReleasePrefix) ||
1052 IvarName.startswith(ReleasePrefix))) {
1056 const ObjCInterfaceDecl *ID =
1057 PropImpl->getPropertyIvarDecl()->getContainingInterface();
1058 for ( ; ID ; ID = ID->getSuperClass()) {
1059 IdentifierInfo *II = ID->getIdentifier();
1060 if (II == CIFilterII)
1067 /// Returns whether the ivar backing the property is an IBOutlet that
1068 /// has its value set by nib loading code without retaining the value.
1070 /// On macOS, if there is no setter, the nib-loading code sets the ivar
1071 /// directly, without retaining the value,
1073 /// On iOS and its derivatives, the nib-loading code will call
1074 /// -setValue:forKey:, which retains the value before directly setting the ivar.
1075 bool ObjCDeallocChecker::isNibLoadedIvarWithoutRetain(
1076 const ObjCPropertyImplDecl *PropImpl) const {
1077 const ObjCIvarDecl *IvarDecl = PropImpl->getPropertyIvarDecl();
1078 if (!IvarDecl->hasAttr<IBOutletAttr>())
1081 const llvm::Triple &Target =
1082 IvarDecl->getASTContext().getTargetInfo().getTriple();
1084 if (!Target.isMacOSX())
1087 if (PropImpl->getPropertyDecl()->getSetterMethodDecl())
1093 void ento::registerObjCDeallocChecker(CheckerManager &Mgr) {
1094 const LangOptions &LangOpts = Mgr.getLangOpts();
1095 // These checker only makes sense under MRR.
1096 if (LangOpts.getGC() == LangOptions::GCOnly || LangOpts.ObjCAutoRefCount)
1099 Mgr.registerChecker<ObjCDeallocChecker>();