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/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"
49 using namespace clang;
52 /// Indicates whether an instance variable is required to be released in
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.
59 /// The instance variable must not be directly released with -release.
60 MustNotReleaseDirectly,
62 /// The requirement for the instance variable could not be determined.
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) {
72 if (I->getPropertyImplementation() != ObjCPropertyImplDecl::Synthesize)
75 (*ID) = I->getPropertyIvarDecl();
79 QualType T = (*ID)->getType();
80 if (!T->isObjCRetainableType())
83 (*PD) = I->getPropertyDecl();
84 // Shouldn't be able to synthesize a property that doesn't exist.
92 class ObjCDeallocChecker
93 : public Checker<check::ASTDecl<ObjCImplementationDecl>,
94 check::PreObjCMessage, check::PostObjCMessage,
96 check::BeginFunction, check::EndFunction,
99 check::PreStmt<ReturnStmt>> {
101 mutable IdentifierInfo *NSObjectII, *SenTestCaseII, *XCTestCaseII,
102 *Block_releaseII, *CIFilterII;
104 mutable Selector DeallocSel, ReleaseSel;
106 std::unique_ptr<BugType> MissingReleaseBugType;
107 std::unique_ptr<BugType> ExtraReleaseBugType;
108 std::unique_ptr<BugType> MistakenDeallocBugType;
111 ObjCDeallocChecker();
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;
120 ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
121 bool Assumption) const;
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;
131 void diagnoseMissingReleases(CheckerContext &C) const;
133 bool diagnoseExtraRelease(SymbolRef ReleasedValue, const ObjCMethodCall &M,
134 CheckerContext &C) const;
136 bool diagnoseMistakenDealloc(SymbolRef DeallocedValue,
137 const ObjCMethodCall &M,
138 CheckerContext &C) const;
140 SymbolRef getValueReleasedByNillingOut(const ObjCMethodCall &M,
141 CheckerContext &C) const;
143 const ObjCIvarRegion *getIvarRegionForIvarSymbol(SymbolRef IvarSym) const;
144 SymbolRef getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const;
146 const ObjCPropertyImplDecl*
147 findPropertyOnDeallocatingInstance(SymbolRef IvarSym,
148 CheckerContext &C) const;
151 getDeallocReleaseRequirement(const ObjCPropertyImplDecl *PropImpl) const;
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;
159 bool isSuperDeallocMessage(const ObjCMethodCall &M) const;
161 const ObjCImplDecl *getContainingObjCImpl(const LocationContext *LCtx) const;
163 const ObjCPropertyDecl *
164 findShadowedPropertyDecl(const ObjCPropertyImplDecl *PropImpl) const;
166 void transitionToReleaseValue(CheckerContext &C, SymbolRef Value) const;
167 ProgramStateRef removeValueRequiringRelease(ProgramStateRef State,
168 SymbolRef InstanceSym,
169 SymbolRef ValueSym) const;
171 void initIdentifierInfoAndSelectors(ASTContext &Ctx) const;
173 bool classHasSeparateTeardown(const ObjCInterfaceDecl *ID) const;
175 bool isReleasedByCIFilterDealloc(const ObjCPropertyImplDecl *PropImpl) const;
177 } // End anonymous namespace.
179 typedef llvm::ImmutableSet<SymbolRef> SymbolSet;
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)
187 template<> struct ProgramStateTrait<SymbolSet>
188 : public ProgramStatePartialTrait<SymbolSet> {
189 static void *GDMIndex() { static int index = 0; return &index; }
194 /// An AST check that diagnose when the class requires a -dealloc method and
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());
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))
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;
224 if (!PropImplRequiringRelease)
227 const ObjCMethodDecl *MD = nullptr;
229 // Scan the instance methods for "dealloc".
230 for (const auto *I : D->instance_methods()) {
231 if (I->getSelector() == DeallocSel) {
237 if (!MD) { // No dealloc found.
238 const char* Name = "Missing -dealloc";
241 llvm::raw_string_ostream OS(Buf);
242 OS << "'" << *D << "' lacks a 'dealloc' instance method but "
243 << "must release '" << *PropImplRequiringRelease->getPropertyIvarDecl()
248 PathDiagnosticLocation DLoc =
249 PathDiagnosticLocation::createBegin(D, BR.getSourceManager());
251 BR.EmitBasicReport(D, this, Name, categories::CoreFoundationObjectiveC,
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());
264 // Only do this if the current method is -dealloc.
266 if (!isInInstanceDealloc(C, SelfVal))
269 SymbolRef SelfSymbol = SelfVal.getAsSymbol();
271 const LocationContext *LCtx = C.getLocationContext();
272 ProgramStateRef InitialState = C.getState();
274 ProgramStateRef State = InitialState;
276 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
278 // Symbols that must be released by the end of the -dealloc;
279 SymbolSet RequiredReleases = F.getEmptySet();
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;
286 for (auto *PropImpl : getContainingObjCImpl(LCtx)->property_impls()) {
287 ReleaseRequirement Requirement = getDeallocReleaseRequirement(PropImpl);
288 if (Requirement != ReleaseRequirement::MustRelease)
291 SVal LVal = State->getLValue(PropImpl->getPropertyIvarDecl(), SelfVal);
292 Optional<Loc> LValLoc = LVal.getAs<Loc>();
296 SVal InitialVal = State->getSVal(LValLoc.getValue());
297 SymbolRef Symbol = InitialVal.getAsSymbol();
298 if (!Symbol || !isa<SymbolRegionValue>(Symbol))
301 // Mark the value as requiring a release.
302 RequiredReleases = F.add(RequiredReleases, Symbol);
305 if (!RequiredReleases.isEmpty()) {
306 State = State->set<UnreleasedIvarMap>(SelfSymbol, RequiredReleases);
309 if (State != InitialState) {
310 C.addTransition(State);
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 return dyn_cast_or_null<ObjCIvarRegion>(IvarSym->getOriginRegion());
321 /// Given a symbol for an ivar, return a symbol for the instance containing
322 /// the ivar. Returns nullptr if the instance symbol cannot be found.
324 ObjCDeallocChecker::getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const {
326 const ObjCIvarRegion *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
330 return IvarRegion->getSymbolicBase()->getSymbol();
333 /// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
334 /// a release or a nilling-out property setter.
335 void ObjCDeallocChecker::checkPreObjCMessage(
336 const ObjCMethodCall &M, CheckerContext &C) const {
337 // Only run if -dealloc is on the stack.
338 SVal DeallocedInstance;
339 if (!instanceDeallocIsOnStack(C, DeallocedInstance))
342 SymbolRef ReleasedValue = nullptr;
344 if (M.getSelector() == ReleaseSel) {
345 ReleasedValue = M.getReceiverSVal().getAsSymbol();
346 } else if (M.getSelector() == DeallocSel && !M.isReceiverSelfOrSuper()) {
347 if (diagnoseMistakenDealloc(M.getReceiverSVal().getAsSymbol(), M, C))
352 // An instance variable symbol was released with -release:
353 // [_property release];
354 if (diagnoseExtraRelease(ReleasedValue,M, C))
357 // An instance variable symbol was released nilling out its property:
358 // self.property = nil;
359 ReleasedValue = getValueReleasedByNillingOut(M, C);
365 transitionToReleaseValue(C, ReleasedValue);
368 /// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
369 /// call to Block_release().
370 void ObjCDeallocChecker::checkPreCall(const CallEvent &Call,
371 CheckerContext &C) const {
372 const IdentifierInfo *II = Call.getCalleeIdentifier();
373 if (II != Block_releaseII)
376 if (Call.getNumArgs() != 1)
379 SymbolRef ReleasedValue = Call.getArgSVal(0).getAsSymbol();
383 transitionToReleaseValue(C, ReleasedValue);
385 /// If the message was a call to '[super dealloc]', diagnose any missing
387 void ObjCDeallocChecker::checkPostObjCMessage(
388 const ObjCMethodCall &M, CheckerContext &C) const {
389 // We perform this check post-message so that if the super -dealloc
390 // calls a helper method and that this class overrides, any ivars released in
391 // the helper method will be recorded before checking.
392 if (isSuperDeallocMessage(M))
393 diagnoseMissingReleases(C);
396 /// Check for missing releases even when -dealloc does not call
397 /// '[super dealloc]'.
398 void ObjCDeallocChecker::checkEndFunction(
399 CheckerContext &C) const {
400 diagnoseMissingReleases(C);
403 /// Check for missing releases on early return.
404 void ObjCDeallocChecker::checkPreStmt(
405 const ReturnStmt *RS, CheckerContext &C) const {
406 diagnoseMissingReleases(C);
409 /// When a symbol is assumed to be nil, remove it from the set of symbols
410 /// require to be nil.
411 ProgramStateRef ObjCDeallocChecker::evalAssume(ProgramStateRef State, SVal Cond,
412 bool Assumption) const {
413 if (State->get<UnreleasedIvarMap>().isEmpty())
416 auto *CondBSE = dyn_cast_or_null<BinarySymExpr>(Cond.getAsSymExpr());
420 BinaryOperator::Opcode OpCode = CondBSE->getOpcode();
429 SymbolRef NullSymbol = nullptr;
430 if (auto *SIE = dyn_cast<SymIntExpr>(CondBSE)) {
431 const llvm::APInt &RHS = SIE->getRHS();
434 NullSymbol = SIE->getLHS();
435 } else if (auto *SIE = dyn_cast<IntSymExpr>(CondBSE)) {
436 const llvm::APInt &LHS = SIE->getLHS();
439 NullSymbol = SIE->getRHS();
444 SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(NullSymbol);
448 State = removeValueRequiringRelease(State, InstanceSymbol, NullSymbol);
453 /// If a symbol escapes conservatively assume unseen code released it.
454 ProgramStateRef ObjCDeallocChecker::checkPointerEscape(
455 ProgramStateRef State, const InvalidatedSymbols &Escaped,
456 const CallEvent *Call, PointerEscapeKind Kind) const {
458 if (State->get<UnreleasedIvarMap>().isEmpty())
461 // Don't treat calls to '[super dealloc]' as escaping for the purposes
462 // of this checker. Because the checker diagnoses missing releases in the
463 // post-message handler for '[super dealloc], escaping here would cause
464 // the checker to never warn.
465 auto *OMC = dyn_cast_or_null<ObjCMethodCall>(Call);
466 if (OMC && isSuperDeallocMessage(*OMC))
469 for (const auto &Sym : Escaped) {
470 if (!Call || (Call && !Call->isInSystemHeader())) {
471 // If Sym is a symbol for an object with instance variables that
472 // must be released, remove these obligations when the object escapes
473 // unless via a call to a system function. System functions are
474 // very unlikely to release instance variables on objects passed to them,
475 // and are frequently called on 'self' in -dealloc (e.g., to remove
476 // observers) -- we want to avoid false negatives from escaping on
478 State = State->remove<UnreleasedIvarMap>(Sym);
482 SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(Sym);
486 State = removeValueRequiringRelease(State, InstanceSymbol, Sym);
492 /// Report any unreleased instance variables for the current instance being
494 void ObjCDeallocChecker::diagnoseMissingReleases(CheckerContext &C) const {
495 ProgramStateRef State = C.getState();
498 if (!isInInstanceDealloc(C, SelfVal))
501 const MemRegion *SelfRegion = SelfVal.castAs<loc::MemRegionVal>().getRegion();
502 const LocationContext *LCtx = C.getLocationContext();
504 ExplodedNode *ErrNode = nullptr;
506 SymbolRef SelfSym = SelfVal.getAsSymbol();
510 const SymbolSet *OldUnreleased = State->get<UnreleasedIvarMap>(SelfSym);
514 SymbolSet NewUnreleased = *OldUnreleased;
515 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
517 ProgramStateRef InitialState = State;
519 for (auto *IvarSymbol : *OldUnreleased) {
520 const TypedValueRegion *TVR =
521 cast<SymbolRegionValue>(IvarSymbol)->getRegion();
522 const ObjCIvarRegion *IvarRegion = cast<ObjCIvarRegion>(TVR);
524 // Don't warn if the ivar is not for this instance.
525 if (SelfRegion != IvarRegion->getSuperRegion())
528 const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
529 // Prevent an inlined call to -dealloc in a super class from warning
530 // about the values the subclass's -dealloc should release.
531 if (IvarDecl->getContainingInterface() !=
532 cast<ObjCMethodDecl>(LCtx->getDecl())->getClassInterface())
535 // Prevents diagnosing multiple times for the same instance variable
536 // at, for example, both a return and at the end of of the function.
537 NewUnreleased = F.remove(NewUnreleased, IvarSymbol);
539 if (State->getStateManager()
540 .getConstraintManager()
541 .isNull(State, IvarSymbol)
542 .isConstrainedTrue()) {
546 // A missing release manifests as a leak, so treat as a non-fatal error.
548 ErrNode = C.generateNonFatalErrorNode();
549 // If we've already reached this node on another path, return without
555 llvm::raw_string_ostream OS(Buf);
557 const ObjCInterfaceDecl *Interface = IvarDecl->getContainingInterface();
558 // If the class is known to have a lifecycle with teardown that is
559 // separate from -dealloc, do not warn about missing releases. We
560 // suppress here (rather than not tracking for instance variables in
561 // such classes) because these classes are rare.
562 if (classHasSeparateTeardown(Interface))
565 ObjCImplDecl *ImplDecl = Interface->getImplementation();
567 const ObjCPropertyImplDecl *PropImpl =
568 ImplDecl->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
570 const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
572 assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Copy ||
573 PropDecl->getSetterKind() == ObjCPropertyDecl::Retain);
575 OS << "The '" << *IvarDecl << "' ivar in '" << *ImplDecl
578 if (PropDecl->getSetterKind() == ObjCPropertyDecl::Retain)
583 OS << " by a synthesized property but not released"
584 " before '[super dealloc]'";
586 std::unique_ptr<BugReport> BR(
587 new BugReport(*MissingReleaseBugType, OS.str(), ErrNode));
589 C.emitReport(std::move(BR));
592 if (NewUnreleased.isEmpty()) {
593 State = State->remove<UnreleasedIvarMap>(SelfSym);
595 State = State->set<UnreleasedIvarMap>(SelfSym, NewUnreleased);
599 C.addTransition(State, ErrNode);
600 } else if (State != InitialState) {
601 C.addTransition(State);
604 // Make sure that after checking in the top-most frame the list of
605 // tracked ivars is empty. This is intended to detect accidental leaks in
606 // the UnreleasedIvarMap program state.
607 assert(!LCtx->inTopFrame() || State->get<UnreleasedIvarMap>().isEmpty());
610 /// Given a symbol, determine whether the symbol refers to an ivar on
611 /// the top-most deallocating instance. If so, find the property for that
612 /// ivar, if one exists. Otherwise return null.
613 const ObjCPropertyImplDecl *
614 ObjCDeallocChecker::findPropertyOnDeallocatingInstance(
615 SymbolRef IvarSym, CheckerContext &C) const {
616 SVal DeallocedInstance;
617 if (!isInInstanceDealloc(C, DeallocedInstance))
620 // Try to get the region from which the ivar value was loaded.
621 auto *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
625 // Don't try to find the property if the ivar was not loaded from the
627 if (DeallocedInstance.castAs<loc::MemRegionVal>().getRegion() !=
628 IvarRegion->getSuperRegion())
631 const LocationContext *LCtx = C.getLocationContext();
632 const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
634 const ObjCImplDecl *Container = getContainingObjCImpl(LCtx);
635 const ObjCPropertyImplDecl *PropImpl =
636 Container->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
640 /// Emits a warning if the current context is -dealloc and ReleasedValue
641 /// must not be directly released in a -dealloc. Returns true if a diagnostic
643 bool ObjCDeallocChecker::diagnoseExtraRelease(SymbolRef ReleasedValue,
644 const ObjCMethodCall &M,
645 CheckerContext &C) const {
646 // Try to get the region from which the the released value was loaded.
647 // Note that, unlike diagnosing for missing releases, here we don't track
648 // values that must not be released in the state. This is because even if
649 // these values escape, it is still an error under the rules of MRR to
650 // release them in -dealloc.
651 const ObjCPropertyImplDecl *PropImpl =
652 findPropertyOnDeallocatingInstance(ReleasedValue, C);
657 // If the ivar belongs to a property that must not be released directly
658 // in dealloc, emit a warning.
659 if (getDeallocReleaseRequirement(PropImpl) !=
660 ReleaseRequirement::MustNotReleaseDirectly) {
664 // If the property is readwrite but it shadows a read-only property in its
665 // external interface, treat the property a read-only. If the outside
666 // world cannot write to a property then the internal implementation is free
667 // to make its own convention about whether the value is stored retained
668 // or not. We look up the shadow here rather than in
669 // getDeallocReleaseRequirement() because doing so can be expensive.
670 const ObjCPropertyDecl *PropDecl = findShadowedPropertyDecl(PropImpl);
672 if (PropDecl->isReadOnly())
675 PropDecl = PropImpl->getPropertyDecl();
678 ExplodedNode *ErrNode = C.generateNonFatalErrorNode();
683 llvm::raw_string_ostream OS(Buf);
685 assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Weak ||
686 (PropDecl->getSetterKind() == ObjCPropertyDecl::Assign &&
687 !PropDecl->isReadOnly()) ||
688 isReleasedByCIFilterDealloc(PropImpl)
691 const ObjCImplDecl *Container = getContainingObjCImpl(C.getLocationContext());
692 OS << "The '" << *PropImpl->getPropertyIvarDecl()
693 << "' ivar in '" << *Container;
696 if (isReleasedByCIFilterDealloc(PropImpl)) {
697 OS << "' will be released by '-[CIFilter dealloc]' but also released here";
699 OS << "' was synthesized for ";
701 if (PropDecl->getSetterKind() == ObjCPropertyDecl::Weak)
704 OS << "an assign, readwrite";
706 OS << " property but was released in 'dealloc'";
709 std::unique_ptr<BugReport> BR(
710 new BugReport(*ExtraReleaseBugType, OS.str(), ErrNode));
711 BR->addRange(M.getOriginExpr()->getSourceRange());
713 C.emitReport(std::move(BR));
718 /// Emits a warning if the current context is -dealloc and DeallocedValue
719 /// must not be directly dealloced in a -dealloc. Returns true if a diagnostic
721 bool ObjCDeallocChecker::diagnoseMistakenDealloc(SymbolRef DeallocedValue,
722 const ObjCMethodCall &M,
723 CheckerContext &C) const {
725 // Find the property backing the instance variable that M
727 const ObjCPropertyImplDecl *PropImpl =
728 findPropertyOnDeallocatingInstance(DeallocedValue, C);
732 if (getDeallocReleaseRequirement(PropImpl) !=
733 ReleaseRequirement::MustRelease) {
737 ExplodedNode *ErrNode = C.generateErrorNode();
742 llvm::raw_string_ostream OS(Buf);
744 OS << "'" << *PropImpl->getPropertyIvarDecl()
745 << "' should be released rather than deallocated";
747 std::unique_ptr<BugReport> BR(
748 new BugReport(*MistakenDeallocBugType, OS.str(), ErrNode));
749 BR->addRange(M.getOriginExpr()->getSourceRange());
751 C.emitReport(std::move(BR));
756 ObjCDeallocChecker::ObjCDeallocChecker()
757 : NSObjectII(nullptr), SenTestCaseII(nullptr), XCTestCaseII(nullptr),
758 CIFilterII(nullptr) {
760 MissingReleaseBugType.reset(
761 new BugType(this, "Missing ivar release (leak)",
762 categories::MemoryCoreFoundationObjectiveC));
764 ExtraReleaseBugType.reset(
765 new BugType(this, "Extra ivar release",
766 categories::MemoryCoreFoundationObjectiveC));
768 MistakenDeallocBugType.reset(
769 new BugType(this, "Mistaken dealloc",
770 categories::MemoryCoreFoundationObjectiveC));
773 void ObjCDeallocChecker::initIdentifierInfoAndSelectors(
774 ASTContext &Ctx) const {
778 NSObjectII = &Ctx.Idents.get("NSObject");
779 SenTestCaseII = &Ctx.Idents.get("SenTestCase");
780 XCTestCaseII = &Ctx.Idents.get("XCTestCase");
781 Block_releaseII = &Ctx.Idents.get("_Block_release");
782 CIFilterII = &Ctx.Idents.get("CIFilter");
784 IdentifierInfo *DeallocII = &Ctx.Idents.get("dealloc");
785 IdentifierInfo *ReleaseII = &Ctx.Idents.get("release");
786 DeallocSel = Ctx.Selectors.getSelector(0, &DeallocII);
787 ReleaseSel = Ctx.Selectors.getSelector(0, &ReleaseII);
790 /// Returns true if M is a call to '[super dealloc]'.
791 bool ObjCDeallocChecker::isSuperDeallocMessage(
792 const ObjCMethodCall &M) const {
793 if (M.getOriginExpr()->getReceiverKind() != ObjCMessageExpr::SuperInstance)
796 return M.getSelector() == DeallocSel;
799 /// Returns the ObjCImplDecl containing the method declaration in LCtx.
801 ObjCDeallocChecker::getContainingObjCImpl(const LocationContext *LCtx) const {
802 auto *MD = cast<ObjCMethodDecl>(LCtx->getDecl());
803 return cast<ObjCImplDecl>(MD->getDeclContext());
806 /// Returns the property that shadowed by PropImpl if one exists and
807 /// nullptr otherwise.
808 const ObjCPropertyDecl *ObjCDeallocChecker::findShadowedPropertyDecl(
809 const ObjCPropertyImplDecl *PropImpl) const {
810 const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
812 // Only readwrite properties can shadow.
813 if (PropDecl->isReadOnly())
816 auto *CatDecl = dyn_cast<ObjCCategoryDecl>(PropDecl->getDeclContext());
818 // Only class extensions can contain shadowing properties.
819 if (!CatDecl || !CatDecl->IsClassExtension())
822 IdentifierInfo *ID = PropDecl->getIdentifier();
823 DeclContext::lookup_result R = CatDecl->getClassInterface()->lookup(ID);
824 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
825 auto *ShadowedPropDecl = dyn_cast<ObjCPropertyDecl>(*I);
826 if (!ShadowedPropDecl)
829 if (ShadowedPropDecl->isInstanceProperty()) {
830 assert(ShadowedPropDecl->isReadOnly());
831 return ShadowedPropDecl;
838 /// Add a transition noting the release of the given value.
839 void ObjCDeallocChecker::transitionToReleaseValue(CheckerContext &C,
840 SymbolRef Value) const {
842 SymbolRef InstanceSym = getInstanceSymbolFromIvarSymbol(Value);
845 ProgramStateRef InitialState = C.getState();
847 ProgramStateRef ReleasedState =
848 removeValueRequiringRelease(InitialState, InstanceSym, Value);
850 if (ReleasedState != InitialState) {
851 C.addTransition(ReleasedState);
855 /// Remove the Value requiring a release from the tracked set for
856 /// Instance and return the resultant state.
857 ProgramStateRef ObjCDeallocChecker::removeValueRequiringRelease(
858 ProgramStateRef State, SymbolRef Instance, SymbolRef Value) const {
861 const ObjCIvarRegion *RemovedRegion = getIvarRegionForIvarSymbol(Value);
865 const SymbolSet *Unreleased = State->get<UnreleasedIvarMap>(Instance);
869 // Mark the value as no longer requiring a release.
870 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
871 SymbolSet NewUnreleased = *Unreleased;
872 for (auto &Sym : *Unreleased) {
873 const ObjCIvarRegion *UnreleasedRegion = getIvarRegionForIvarSymbol(Sym);
874 assert(UnreleasedRegion);
875 if (RemovedRegion->getDecl() == UnreleasedRegion->getDecl()) {
876 NewUnreleased = F.remove(NewUnreleased, Sym);
880 if (NewUnreleased.isEmpty()) {
881 return State->remove<UnreleasedIvarMap>(Instance);
884 return State->set<UnreleasedIvarMap>(Instance, NewUnreleased);
887 /// Determines whether the instance variable for \p PropImpl must or must not be
888 /// released in -dealloc or whether it cannot be determined.
889 ReleaseRequirement ObjCDeallocChecker::getDeallocReleaseRequirement(
890 const ObjCPropertyImplDecl *PropImpl) const {
891 const ObjCIvarDecl *IvarDecl;
892 const ObjCPropertyDecl *PropDecl;
893 if (!isSynthesizedRetainableProperty(PropImpl, &IvarDecl, &PropDecl))
894 return ReleaseRequirement::Unknown;
896 ObjCPropertyDecl::SetterKind SK = PropDecl->getSetterKind();
899 // Retain and copy setters retain/copy their values before storing and so
900 // the value in their instance variables must be released in -dealloc.
901 case ObjCPropertyDecl::Retain:
902 case ObjCPropertyDecl::Copy:
903 if (isReleasedByCIFilterDealloc(PropImpl))
904 return ReleaseRequirement::MustNotReleaseDirectly;
906 return ReleaseRequirement::MustRelease;
908 case ObjCPropertyDecl::Weak:
909 return ReleaseRequirement::MustNotReleaseDirectly;
911 case ObjCPropertyDecl::Assign:
912 // It is common for the ivars for read-only assign properties to
913 // always be stored retained, so their release requirement cannot be
915 if (PropDecl->isReadOnly())
916 return ReleaseRequirement::Unknown;
918 return ReleaseRequirement::MustNotReleaseDirectly;
920 llvm_unreachable("Unrecognized setter kind");
923 /// Returns the released value if M is a call a setter that releases
924 /// and nils out its underlying instance variable.
926 ObjCDeallocChecker::getValueReleasedByNillingOut(const ObjCMethodCall &M,
927 CheckerContext &C) const {
928 SVal ReceiverVal = M.getReceiverSVal();
929 if (!ReceiverVal.isValid())
932 if (M.getNumArgs() == 0)
935 if (!M.getArgExpr(0)->getType()->isObjCRetainableType())
938 // Is the first argument nil?
939 SVal Arg = M.getArgSVal(0);
940 ProgramStateRef notNilState, nilState;
941 std::tie(notNilState, nilState) =
942 M.getState()->assume(Arg.castAs<DefinedOrUnknownSVal>());
943 if (!(nilState && !notNilState))
946 const ObjCPropertyDecl *Prop = M.getAccessedProperty();
950 ObjCIvarDecl *PropIvarDecl = Prop->getPropertyIvarDecl();
954 ProgramStateRef State = C.getState();
956 SVal LVal = State->getLValue(PropIvarDecl, ReceiverVal);
957 Optional<Loc> LValLoc = LVal.getAs<Loc>();
961 SVal CurrentValInIvar = State->getSVal(LValLoc.getValue());
962 return CurrentValInIvar.getAsSymbol();
965 /// Returns true if the current context is a call to -dealloc and false
966 /// otherwise. If true, it also sets SelfValOut to the value of
968 bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
969 SVal &SelfValOut) const {
970 return isInInstanceDealloc(C, C.getLocationContext(), SelfValOut);
973 /// Returns true if LCtx is a call to -dealloc and false
974 /// otherwise. If true, it also sets SelfValOut to the value of
976 bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
977 const LocationContext *LCtx,
978 SVal &SelfValOut) const {
979 auto *MD = dyn_cast<ObjCMethodDecl>(LCtx->getDecl());
980 if (!MD || !MD->isInstanceMethod() || MD->getSelector() != DeallocSel)
983 const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
984 assert(SelfDecl && "No self in -dealloc?");
986 ProgramStateRef State = C.getState();
987 SelfValOut = State->getSVal(State->getRegion(SelfDecl, LCtx));
991 /// Returns true if there is a call to -dealloc anywhere on the stack and false
992 /// otherwise. If true, it also sets InstanceValOut to the value of
993 /// 'self' in the frame for -dealloc.
994 bool ObjCDeallocChecker::instanceDeallocIsOnStack(const CheckerContext &C,
995 SVal &InstanceValOut) const {
996 const LocationContext *LCtx = C.getLocationContext();
999 if (isInInstanceDealloc(C, LCtx, InstanceValOut))
1002 LCtx = LCtx->getParent();
1008 /// Returns true if the ID is a class in which which is known to have
1009 /// a separate teardown lifecycle. In this case, -dealloc warnings
1010 /// about missing releases should be suppressed.
1011 bool ObjCDeallocChecker::classHasSeparateTeardown(
1012 const ObjCInterfaceDecl *ID) const {
1013 // Suppress if the class is not a subclass of NSObject.
1014 for ( ; ID ; ID = ID->getSuperClass()) {
1015 IdentifierInfo *II = ID->getIdentifier();
1017 if (II == NSObjectII)
1020 // FIXME: For now, ignore classes that subclass SenTestCase and XCTestCase,
1021 // as these don't need to implement -dealloc. They implement tear down in
1022 // another way, which we should try and catch later.
1023 // http://llvm.org/bugs/show_bug.cgi?id=3187
1024 if (II == XCTestCaseII || II == SenTestCaseII)
1031 /// The -dealloc method in CIFilter highly unusual in that is will release
1032 /// instance variables belonging to its *subclasses* if the variable name
1033 /// starts with "input" or backs a property whose name starts with "input".
1034 /// Subclasses should not release these ivars in their own -dealloc method --
1035 /// doing so could result in an over release.
1037 /// This method returns true if the property will be released by
1038 /// -[CIFilter dealloc].
1039 bool ObjCDeallocChecker::isReleasedByCIFilterDealloc(
1040 const ObjCPropertyImplDecl *PropImpl) const {
1041 assert(PropImpl->getPropertyIvarDecl());
1042 StringRef PropName = PropImpl->getPropertyDecl()->getName();
1043 StringRef IvarName = PropImpl->getPropertyIvarDecl()->getName();
1045 const char *ReleasePrefix = "input";
1046 if (!(PropName.startswith(ReleasePrefix) ||
1047 IvarName.startswith(ReleasePrefix))) {
1051 const ObjCInterfaceDecl *ID =
1052 PropImpl->getPropertyIvarDecl()->getContainingInterface();
1053 for ( ; ID ; ID = ID->getSuperClass()) {
1054 IdentifierInfo *II = ID->getIdentifier();
1055 if (II == CIFilterII)
1062 void ento::registerObjCDeallocChecker(CheckerManager &Mgr) {
1063 const LangOptions &LangOpts = Mgr.getLangOpts();
1064 // These checker only makes sense under MRR.
1065 if (LangOpts.getGC() == LangOptions::GCOnly || LangOpts.ObjCAutoRefCount)
1068 Mgr.registerChecker<ObjCDeallocChecker>();