1 //==- CheckObjCDealloc.cpp - Check ObjC -dealloc implementation --*- C++ -*-==//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This checker analyzes Objective-C -dealloc methods and their callees
10 // to warn about improper releasing of instance variables that back synthesized
11 // properties. It warns about missing releases in the following cases:
12 // - When a class has a synthesized instance variable for a 'retain' or 'copy'
13 // property and lacks a -dealloc method in its implementation.
14 // - When a class has a synthesized instance variable for a 'retain'/'copy'
15 // property but the ivar is not released in -dealloc by either -release
16 // or by nilling out the property.
18 // It warns about extra releases in -dealloc (but not in callees) when a
19 // synthesized instance variable is released in the following cases:
20 // - When the property is 'assign' and is not 'readonly'.
21 // - When the property is 'weak'.
23 // This checker only warns for instance variables synthesized to back
24 // properties. Handling the more general case would require inferring whether
25 // an instance variable is stored retained or not. For synthesized properties,
26 // this is specified in the property declaration itself.
28 //===----------------------------------------------------------------------===//
30 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
31 #include "clang/Analysis/PathDiagnostic.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/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(const ReturnStmt *RS, 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;
176 bool isNibLoadedIvarWithoutRetain(const ObjCPropertyImplDecl *PropImpl) const;
178 } // End anonymous namespace.
181 /// Maps from the symbol for a class instance to the set of
182 /// symbols remaining that must be released in -dealloc.
183 REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(SymbolSet, SymbolRef)
184 REGISTER_MAP_WITH_PROGRAMSTATE(UnreleasedIvarMap, SymbolRef, SymbolSet)
187 /// An AST check that diagnose when the class requires a -dealloc method and
189 void ObjCDeallocChecker::checkASTDecl(const ObjCImplementationDecl *D,
190 AnalysisManager &Mgr,
191 BugReporter &BR) const {
192 assert(Mgr.getLangOpts().getGC() != LangOptions::GCOnly);
193 assert(!Mgr.getLangOpts().ObjCAutoRefCount);
194 initIdentifierInfoAndSelectors(Mgr.getASTContext());
196 const ObjCInterfaceDecl *ID = D->getClassInterface();
197 // If the class is known to have a lifecycle with a separate teardown method
198 // then it may not require a -dealloc method.
199 if (classHasSeparateTeardown(ID))
202 // Does the class contain any synthesized properties that are retainable?
203 // If not, skip the check entirely.
204 const ObjCPropertyImplDecl *PropImplRequiringRelease = nullptr;
205 bool HasOthers = false;
206 for (const auto *I : D->property_impls()) {
207 if (getDeallocReleaseRequirement(I) == ReleaseRequirement::MustRelease) {
208 if (!PropImplRequiringRelease)
209 PropImplRequiringRelease = I;
217 if (!PropImplRequiringRelease)
220 const ObjCMethodDecl *MD = nullptr;
222 // Scan the instance methods for "dealloc".
223 for (const auto *I : D->instance_methods()) {
224 if (I->getSelector() == DeallocSel) {
230 if (!MD) { // No dealloc found.
231 const char* Name = "Missing -dealloc";
234 llvm::raw_string_ostream OS(Buf);
235 OS << "'" << *D << "' lacks a 'dealloc' instance method but "
236 << "must release '" << *PropImplRequiringRelease->getPropertyIvarDecl()
241 PathDiagnosticLocation DLoc =
242 PathDiagnosticLocation::createBegin(D, BR.getSourceManager());
244 BR.EmitBasicReport(D, this, Name, categories::CoreFoundationObjectiveC,
250 /// If this is the beginning of -dealloc, mark the values initially stored in
251 /// instance variables that must be released by the end of -dealloc
252 /// as unreleased in the state.
253 void ObjCDeallocChecker::checkBeginFunction(
254 CheckerContext &C) const {
255 initIdentifierInfoAndSelectors(C.getASTContext());
257 // Only do this if the current method is -dealloc.
259 if (!isInInstanceDealloc(C, SelfVal))
262 SymbolRef SelfSymbol = SelfVal.getAsSymbol();
264 const LocationContext *LCtx = C.getLocationContext();
265 ProgramStateRef InitialState = C.getState();
267 ProgramStateRef State = InitialState;
269 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
271 // Symbols that must be released by the end of the -dealloc;
272 SymbolSet RequiredReleases = F.getEmptySet();
274 // If we're an inlined -dealloc, we should add our symbols to the existing
275 // set from our subclass.
276 if (const SymbolSet *CurrSet = State->get<UnreleasedIvarMap>(SelfSymbol))
277 RequiredReleases = *CurrSet;
279 for (auto *PropImpl : getContainingObjCImpl(LCtx)->property_impls()) {
280 ReleaseRequirement Requirement = getDeallocReleaseRequirement(PropImpl);
281 if (Requirement != ReleaseRequirement::MustRelease)
284 SVal LVal = State->getLValue(PropImpl->getPropertyIvarDecl(), SelfVal);
285 Optional<Loc> LValLoc = LVal.getAs<Loc>();
289 SVal InitialVal = State->getSVal(LValLoc.getValue());
290 SymbolRef Symbol = InitialVal.getAsSymbol();
291 if (!Symbol || !isa<SymbolRegionValue>(Symbol))
294 // Mark the value as requiring a release.
295 RequiredReleases = F.add(RequiredReleases, Symbol);
298 if (!RequiredReleases.isEmpty()) {
299 State = State->set<UnreleasedIvarMap>(SelfSymbol, RequiredReleases);
302 if (State != InitialState) {
303 C.addTransition(State);
307 /// Given a symbol for an ivar, return the ivar region it was loaded from.
308 /// Returns nullptr if the instance symbol cannot be found.
309 const ObjCIvarRegion *
310 ObjCDeallocChecker::getIvarRegionForIvarSymbol(SymbolRef IvarSym) const {
311 return dyn_cast_or_null<ObjCIvarRegion>(IvarSym->getOriginRegion());
314 /// Given a symbol for an ivar, return a symbol for the instance containing
315 /// the ivar. Returns nullptr if the instance symbol cannot be found.
317 ObjCDeallocChecker::getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const {
319 const ObjCIvarRegion *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
323 return IvarRegion->getSymbolicBase()->getSymbol();
326 /// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
327 /// a release or a nilling-out property setter.
328 void ObjCDeallocChecker::checkPreObjCMessage(
329 const ObjCMethodCall &M, CheckerContext &C) const {
330 // Only run if -dealloc is on the stack.
331 SVal DeallocedInstance;
332 if (!instanceDeallocIsOnStack(C, DeallocedInstance))
335 SymbolRef ReleasedValue = nullptr;
337 if (M.getSelector() == ReleaseSel) {
338 ReleasedValue = M.getReceiverSVal().getAsSymbol();
339 } else if (M.getSelector() == DeallocSel && !M.isReceiverSelfOrSuper()) {
340 if (diagnoseMistakenDealloc(M.getReceiverSVal().getAsSymbol(), M, C))
345 // An instance variable symbol was released with -release:
346 // [_property release];
347 if (diagnoseExtraRelease(ReleasedValue,M, C))
350 // An instance variable symbol was released nilling out its property:
351 // self.property = nil;
352 ReleasedValue = getValueReleasedByNillingOut(M, C);
358 transitionToReleaseValue(C, ReleasedValue);
361 /// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
362 /// call to Block_release().
363 void ObjCDeallocChecker::checkPreCall(const CallEvent &Call,
364 CheckerContext &C) const {
365 const IdentifierInfo *II = Call.getCalleeIdentifier();
366 if (II != Block_releaseII)
369 if (Call.getNumArgs() != 1)
372 SymbolRef ReleasedValue = Call.getArgSVal(0).getAsSymbol();
376 transitionToReleaseValue(C, ReleasedValue);
378 /// If the message was a call to '[super dealloc]', diagnose any missing
380 void ObjCDeallocChecker::checkPostObjCMessage(
381 const ObjCMethodCall &M, CheckerContext &C) const {
382 // We perform this check post-message so that if the super -dealloc
383 // calls a helper method and that this class overrides, any ivars released in
384 // the helper method will be recorded before checking.
385 if (isSuperDeallocMessage(M))
386 diagnoseMissingReleases(C);
389 /// Check for missing releases even when -dealloc does not call
390 /// '[super dealloc]'.
391 void ObjCDeallocChecker::checkEndFunction(
392 const ReturnStmt *RS, CheckerContext &C) const {
393 diagnoseMissingReleases(C);
396 /// Check for missing releases on early return.
397 void ObjCDeallocChecker::checkPreStmt(
398 const ReturnStmt *RS, CheckerContext &C) const {
399 diagnoseMissingReleases(C);
402 /// When a symbol is assumed to be nil, remove it from the set of symbols
403 /// require to be nil.
404 ProgramStateRef ObjCDeallocChecker::evalAssume(ProgramStateRef State, SVal Cond,
405 bool Assumption) const {
406 if (State->get<UnreleasedIvarMap>().isEmpty())
409 auto *CondBSE = dyn_cast_or_null<BinarySymExpr>(Cond.getAsSymExpr());
413 BinaryOperator::Opcode OpCode = CondBSE->getOpcode();
422 SymbolRef NullSymbol = nullptr;
423 if (auto *SIE = dyn_cast<SymIntExpr>(CondBSE)) {
424 const llvm::APInt &RHS = SIE->getRHS();
427 NullSymbol = SIE->getLHS();
428 } else if (auto *SIE = dyn_cast<IntSymExpr>(CondBSE)) {
429 const llvm::APInt &LHS = SIE->getLHS();
432 NullSymbol = SIE->getRHS();
437 SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(NullSymbol);
441 State = removeValueRequiringRelease(State, InstanceSymbol, NullSymbol);
446 /// If a symbol escapes conservatively assume unseen code released it.
447 ProgramStateRef ObjCDeallocChecker::checkPointerEscape(
448 ProgramStateRef State, const InvalidatedSymbols &Escaped,
449 const CallEvent *Call, PointerEscapeKind Kind) const {
451 if (State->get<UnreleasedIvarMap>().isEmpty())
454 // Don't treat calls to '[super dealloc]' as escaping for the purposes
455 // of this checker. Because the checker diagnoses missing releases in the
456 // post-message handler for '[super dealloc], escaping here would cause
457 // the checker to never warn.
458 auto *OMC = dyn_cast_or_null<ObjCMethodCall>(Call);
459 if (OMC && isSuperDeallocMessage(*OMC))
462 for (const auto &Sym : Escaped) {
463 if (!Call || (Call && !Call->isInSystemHeader())) {
464 // If Sym is a symbol for an object with instance variables that
465 // must be released, remove these obligations when the object escapes
466 // unless via a call to a system function. System functions are
467 // very unlikely to release instance variables on objects passed to them,
468 // and are frequently called on 'self' in -dealloc (e.g., to remove
469 // observers) -- we want to avoid false negatives from escaping on
471 State = State->remove<UnreleasedIvarMap>(Sym);
475 SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(Sym);
479 State = removeValueRequiringRelease(State, InstanceSymbol, Sym);
485 /// Report any unreleased instance variables for the current instance being
487 void ObjCDeallocChecker::diagnoseMissingReleases(CheckerContext &C) const {
488 ProgramStateRef State = C.getState();
491 if (!isInInstanceDealloc(C, SelfVal))
494 const MemRegion *SelfRegion = SelfVal.castAs<loc::MemRegionVal>().getRegion();
495 const LocationContext *LCtx = C.getLocationContext();
497 ExplodedNode *ErrNode = nullptr;
499 SymbolRef SelfSym = SelfVal.getAsSymbol();
503 const SymbolSet *OldUnreleased = State->get<UnreleasedIvarMap>(SelfSym);
507 SymbolSet NewUnreleased = *OldUnreleased;
508 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
510 ProgramStateRef InitialState = State;
512 for (auto *IvarSymbol : *OldUnreleased) {
513 const TypedValueRegion *TVR =
514 cast<SymbolRegionValue>(IvarSymbol)->getRegion();
515 const ObjCIvarRegion *IvarRegion = cast<ObjCIvarRegion>(TVR);
517 // Don't warn if the ivar is not for this instance.
518 if (SelfRegion != IvarRegion->getSuperRegion())
521 const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
522 // Prevent an inlined call to -dealloc in a super class from warning
523 // about the values the subclass's -dealloc should release.
524 if (IvarDecl->getContainingInterface() !=
525 cast<ObjCMethodDecl>(LCtx->getDecl())->getClassInterface())
528 // Prevents diagnosing multiple times for the same instance variable
529 // at, for example, both a return and at the end of the function.
530 NewUnreleased = F.remove(NewUnreleased, IvarSymbol);
532 if (State->getStateManager()
533 .getConstraintManager()
534 .isNull(State, IvarSymbol)
535 .isConstrainedTrue()) {
539 // A missing release manifests as a leak, so treat as a non-fatal error.
541 ErrNode = C.generateNonFatalErrorNode();
542 // If we've already reached this node on another path, return without
548 llvm::raw_string_ostream OS(Buf);
550 const ObjCInterfaceDecl *Interface = IvarDecl->getContainingInterface();
551 // If the class is known to have a lifecycle with teardown that is
552 // separate from -dealloc, do not warn about missing releases. We
553 // suppress here (rather than not tracking for instance variables in
554 // such classes) because these classes are rare.
555 if (classHasSeparateTeardown(Interface))
558 ObjCImplDecl *ImplDecl = Interface->getImplementation();
560 const ObjCPropertyImplDecl *PropImpl =
561 ImplDecl->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
563 const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
565 assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Copy ||
566 PropDecl->getSetterKind() == ObjCPropertyDecl::Retain);
568 OS << "The '" << *IvarDecl << "' ivar in '" << *ImplDecl
571 if (PropDecl->getSetterKind() == ObjCPropertyDecl::Retain)
576 OS << " by a synthesized property but not released"
577 " before '[super dealloc]'";
579 auto BR = std::make_unique<PathSensitiveBugReport>(*MissingReleaseBugType,
581 C.emitReport(std::move(BR));
584 if (NewUnreleased.isEmpty()) {
585 State = State->remove<UnreleasedIvarMap>(SelfSym);
587 State = State->set<UnreleasedIvarMap>(SelfSym, NewUnreleased);
591 C.addTransition(State, ErrNode);
592 } else if (State != InitialState) {
593 C.addTransition(State);
596 // Make sure that after checking in the top-most frame the list of
597 // tracked ivars is empty. This is intended to detect accidental leaks in
598 // the UnreleasedIvarMap program state.
599 assert(!LCtx->inTopFrame() || State->get<UnreleasedIvarMap>().isEmpty());
602 /// Given a symbol, determine whether the symbol refers to an ivar on
603 /// the top-most deallocating instance. If so, find the property for that
604 /// ivar, if one exists. Otherwise return null.
605 const ObjCPropertyImplDecl *
606 ObjCDeallocChecker::findPropertyOnDeallocatingInstance(
607 SymbolRef IvarSym, CheckerContext &C) const {
608 SVal DeallocedInstance;
609 if (!isInInstanceDealloc(C, DeallocedInstance))
612 // Try to get the region from which the ivar value was loaded.
613 auto *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
617 // Don't try to find the property if the ivar was not loaded from the
619 if (DeallocedInstance.castAs<loc::MemRegionVal>().getRegion() !=
620 IvarRegion->getSuperRegion())
623 const LocationContext *LCtx = C.getLocationContext();
624 const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
626 const ObjCImplDecl *Container = getContainingObjCImpl(LCtx);
627 const ObjCPropertyImplDecl *PropImpl =
628 Container->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
632 /// Emits a warning if the current context is -dealloc and ReleasedValue
633 /// must not be directly released in a -dealloc. Returns true if a diagnostic
635 bool ObjCDeallocChecker::diagnoseExtraRelease(SymbolRef ReleasedValue,
636 const ObjCMethodCall &M,
637 CheckerContext &C) const {
638 // Try to get the region from which the released value was loaded.
639 // Note that, unlike diagnosing for missing releases, here we don't track
640 // values that must not be released in the state. This is because even if
641 // these values escape, it is still an error under the rules of MRR to
642 // release them in -dealloc.
643 const ObjCPropertyImplDecl *PropImpl =
644 findPropertyOnDeallocatingInstance(ReleasedValue, C);
649 // If the ivar belongs to a property that must not be released directly
650 // in dealloc, emit a warning.
651 if (getDeallocReleaseRequirement(PropImpl) !=
652 ReleaseRequirement::MustNotReleaseDirectly) {
656 // If the property is readwrite but it shadows a read-only property in its
657 // external interface, treat the property a read-only. If the outside
658 // world cannot write to a property then the internal implementation is free
659 // to make its own convention about whether the value is stored retained
660 // or not. We look up the shadow here rather than in
661 // getDeallocReleaseRequirement() because doing so can be expensive.
662 const ObjCPropertyDecl *PropDecl = findShadowedPropertyDecl(PropImpl);
664 if (PropDecl->isReadOnly())
667 PropDecl = PropImpl->getPropertyDecl();
670 ExplodedNode *ErrNode = C.generateNonFatalErrorNode();
675 llvm::raw_string_ostream OS(Buf);
677 assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Weak ||
678 (PropDecl->getSetterKind() == ObjCPropertyDecl::Assign &&
679 !PropDecl->isReadOnly()) ||
680 isReleasedByCIFilterDealloc(PropImpl)
683 const ObjCImplDecl *Container = getContainingObjCImpl(C.getLocationContext());
684 OS << "The '" << *PropImpl->getPropertyIvarDecl()
685 << "' ivar in '" << *Container;
688 if (isReleasedByCIFilterDealloc(PropImpl)) {
689 OS << "' will be released by '-[CIFilter dealloc]' but also released here";
691 OS << "' was synthesized for ";
693 if (PropDecl->getSetterKind() == ObjCPropertyDecl::Weak)
696 OS << "an assign, readwrite";
698 OS << " property but was released in 'dealloc'";
701 auto BR = std::make_unique<PathSensitiveBugReport>(*ExtraReleaseBugType,
703 BR->addRange(M.getOriginExpr()->getSourceRange());
705 C.emitReport(std::move(BR));
710 /// Emits a warning if the current context is -dealloc and DeallocedValue
711 /// must not be directly dealloced in a -dealloc. Returns true if a diagnostic
713 bool ObjCDeallocChecker::diagnoseMistakenDealloc(SymbolRef DeallocedValue,
714 const ObjCMethodCall &M,
715 CheckerContext &C) const {
716 // TODO: Apart from unknown/undefined receivers, this may happen when
717 // dealloc is called as a class method. Should we warn?
721 // Find the property backing the instance variable that M
723 const ObjCPropertyImplDecl *PropImpl =
724 findPropertyOnDeallocatingInstance(DeallocedValue, C);
728 if (getDeallocReleaseRequirement(PropImpl) !=
729 ReleaseRequirement::MustRelease) {
733 ExplodedNode *ErrNode = C.generateErrorNode();
738 llvm::raw_string_ostream OS(Buf);
740 OS << "'" << *PropImpl->getPropertyIvarDecl()
741 << "' should be released rather than deallocated";
743 auto BR = std::make_unique<PathSensitiveBugReport>(*MistakenDeallocBugType,
745 BR->addRange(M.getOriginExpr()->getSourceRange());
747 C.emitReport(std::move(BR));
752 ObjCDeallocChecker::ObjCDeallocChecker()
753 : NSObjectII(nullptr), SenTestCaseII(nullptr), XCTestCaseII(nullptr),
754 CIFilterII(nullptr) {
756 MissingReleaseBugType.reset(
757 new BugType(this, "Missing ivar release (leak)",
758 categories::MemoryRefCount));
760 ExtraReleaseBugType.reset(
761 new BugType(this, "Extra ivar release",
762 categories::MemoryRefCount));
764 MistakenDeallocBugType.reset(
765 new BugType(this, "Mistaken dealloc",
766 categories::MemoryRefCount));
769 void ObjCDeallocChecker::initIdentifierInfoAndSelectors(
770 ASTContext &Ctx) const {
774 NSObjectII = &Ctx.Idents.get("NSObject");
775 SenTestCaseII = &Ctx.Idents.get("SenTestCase");
776 XCTestCaseII = &Ctx.Idents.get("XCTestCase");
777 Block_releaseII = &Ctx.Idents.get("_Block_release");
778 CIFilterII = &Ctx.Idents.get("CIFilter");
780 IdentifierInfo *DeallocII = &Ctx.Idents.get("dealloc");
781 IdentifierInfo *ReleaseII = &Ctx.Idents.get("release");
782 DeallocSel = Ctx.Selectors.getSelector(0, &DeallocII);
783 ReleaseSel = Ctx.Selectors.getSelector(0, &ReleaseII);
786 /// Returns true if M is a call to '[super dealloc]'.
787 bool ObjCDeallocChecker::isSuperDeallocMessage(
788 const ObjCMethodCall &M) const {
789 if (M.getOriginExpr()->getReceiverKind() != ObjCMessageExpr::SuperInstance)
792 return M.getSelector() == DeallocSel;
795 /// Returns the ObjCImplDecl containing the method declaration in LCtx.
797 ObjCDeallocChecker::getContainingObjCImpl(const LocationContext *LCtx) const {
798 auto *MD = cast<ObjCMethodDecl>(LCtx->getDecl());
799 return cast<ObjCImplDecl>(MD->getDeclContext());
802 /// Returns the property that shadowed by PropImpl if one exists and
803 /// nullptr otherwise.
804 const ObjCPropertyDecl *ObjCDeallocChecker::findShadowedPropertyDecl(
805 const ObjCPropertyImplDecl *PropImpl) const {
806 const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
808 // Only readwrite properties can shadow.
809 if (PropDecl->isReadOnly())
812 auto *CatDecl = dyn_cast<ObjCCategoryDecl>(PropDecl->getDeclContext());
814 // Only class extensions can contain shadowing properties.
815 if (!CatDecl || !CatDecl->IsClassExtension())
818 IdentifierInfo *ID = PropDecl->getIdentifier();
819 DeclContext::lookup_result R = CatDecl->getClassInterface()->lookup(ID);
820 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
821 auto *ShadowedPropDecl = dyn_cast<ObjCPropertyDecl>(*I);
822 if (!ShadowedPropDecl)
825 if (ShadowedPropDecl->isInstanceProperty()) {
826 assert(ShadowedPropDecl->isReadOnly());
827 return ShadowedPropDecl;
834 /// Add a transition noting the release of the given value.
835 void ObjCDeallocChecker::transitionToReleaseValue(CheckerContext &C,
836 SymbolRef Value) const {
838 SymbolRef InstanceSym = getInstanceSymbolFromIvarSymbol(Value);
841 ProgramStateRef InitialState = C.getState();
843 ProgramStateRef ReleasedState =
844 removeValueRequiringRelease(InitialState, InstanceSym, Value);
846 if (ReleasedState != InitialState) {
847 C.addTransition(ReleasedState);
851 /// Remove the Value requiring a release from the tracked set for
852 /// Instance and return the resultant state.
853 ProgramStateRef ObjCDeallocChecker::removeValueRequiringRelease(
854 ProgramStateRef State, SymbolRef Instance, SymbolRef Value) const {
857 const ObjCIvarRegion *RemovedRegion = getIvarRegionForIvarSymbol(Value);
861 const SymbolSet *Unreleased = State->get<UnreleasedIvarMap>(Instance);
865 // Mark the value as no longer requiring a release.
866 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
867 SymbolSet NewUnreleased = *Unreleased;
868 for (auto &Sym : *Unreleased) {
869 const ObjCIvarRegion *UnreleasedRegion = getIvarRegionForIvarSymbol(Sym);
870 assert(UnreleasedRegion);
871 if (RemovedRegion->getDecl() == UnreleasedRegion->getDecl()) {
872 NewUnreleased = F.remove(NewUnreleased, Sym);
876 if (NewUnreleased.isEmpty()) {
877 return State->remove<UnreleasedIvarMap>(Instance);
880 return State->set<UnreleasedIvarMap>(Instance, NewUnreleased);
883 /// Determines whether the instance variable for \p PropImpl must or must not be
884 /// released in -dealloc or whether it cannot be determined.
885 ReleaseRequirement ObjCDeallocChecker::getDeallocReleaseRequirement(
886 const ObjCPropertyImplDecl *PropImpl) const {
887 const ObjCIvarDecl *IvarDecl;
888 const ObjCPropertyDecl *PropDecl;
889 if (!isSynthesizedRetainableProperty(PropImpl, &IvarDecl, &PropDecl))
890 return ReleaseRequirement::Unknown;
892 ObjCPropertyDecl::SetterKind SK = PropDecl->getSetterKind();
895 // Retain and copy setters retain/copy their values before storing and so
896 // the value in their instance variables must be released in -dealloc.
897 case ObjCPropertyDecl::Retain:
898 case ObjCPropertyDecl::Copy:
899 if (isReleasedByCIFilterDealloc(PropImpl))
900 return ReleaseRequirement::MustNotReleaseDirectly;
902 if (isNibLoadedIvarWithoutRetain(PropImpl))
903 return ReleaseRequirement::Unknown;
905 return ReleaseRequirement::MustRelease;
907 case ObjCPropertyDecl::Weak:
908 return ReleaseRequirement::MustNotReleaseDirectly;
910 case ObjCPropertyDecl::Assign:
911 // It is common for the ivars for read-only assign properties to
912 // always be stored retained, so their release requirement cannot be
914 if (PropDecl->isReadOnly())
915 return ReleaseRequirement::Unknown;
917 return ReleaseRequirement::MustNotReleaseDirectly;
919 llvm_unreachable("Unrecognized setter kind");
922 /// Returns the released value if M is a call a setter that releases
923 /// and nils out its underlying instance variable.
925 ObjCDeallocChecker::getValueReleasedByNillingOut(const ObjCMethodCall &M,
926 CheckerContext &C) const {
927 SVal ReceiverVal = M.getReceiverSVal();
928 if (!ReceiverVal.isValid())
931 if (M.getNumArgs() == 0)
934 if (!M.getArgExpr(0)->getType()->isObjCRetainableType())
937 // Is the first argument nil?
938 SVal Arg = M.getArgSVal(0);
939 ProgramStateRef notNilState, nilState;
940 std::tie(notNilState, nilState) =
941 M.getState()->assume(Arg.castAs<DefinedOrUnknownSVal>());
942 if (!(nilState && !notNilState))
945 const ObjCPropertyDecl *Prop = M.getAccessedProperty();
949 ObjCIvarDecl *PropIvarDecl = Prop->getPropertyIvarDecl();
953 ProgramStateRef State = C.getState();
955 SVal LVal = State->getLValue(PropIvarDecl, ReceiverVal);
956 Optional<Loc> LValLoc = LVal.getAs<Loc>();
960 SVal CurrentValInIvar = State->getSVal(LValLoc.getValue());
961 return CurrentValInIvar.getAsSymbol();
964 /// Returns true if the current context is a call to -dealloc and false
965 /// otherwise. If true, it also sets SelfValOut to the value of
967 bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
968 SVal &SelfValOut) const {
969 return isInInstanceDealloc(C, C.getLocationContext(), SelfValOut);
972 /// Returns true if LCtx is a call to -dealloc and false
973 /// otherwise. If true, it also sets SelfValOut to the value of
975 bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
976 const LocationContext *LCtx,
977 SVal &SelfValOut) const {
978 auto *MD = dyn_cast<ObjCMethodDecl>(LCtx->getDecl());
979 if (!MD || !MD->isInstanceMethod() || MD->getSelector() != DeallocSel)
982 const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
983 assert(SelfDecl && "No self in -dealloc?");
985 ProgramStateRef State = C.getState();
986 SelfValOut = State->getSVal(State->getRegion(SelfDecl, LCtx));
990 /// Returns true if there is a call to -dealloc anywhere on the stack and false
991 /// otherwise. If true, it also sets InstanceValOut to the value of
992 /// 'self' in the frame for -dealloc.
993 bool ObjCDeallocChecker::instanceDeallocIsOnStack(const CheckerContext &C,
994 SVal &InstanceValOut) const {
995 const LocationContext *LCtx = C.getLocationContext();
998 if (isInInstanceDealloc(C, LCtx, InstanceValOut))
1001 LCtx = LCtx->getParent();
1007 /// Returns true if the ID is a class in which which is known to have
1008 /// a separate teardown lifecycle. In this case, -dealloc warnings
1009 /// about missing releases should be suppressed.
1010 bool ObjCDeallocChecker::classHasSeparateTeardown(
1011 const ObjCInterfaceDecl *ID) const {
1012 // Suppress if the class is not a subclass of NSObject.
1013 for ( ; ID ; ID = ID->getSuperClass()) {
1014 IdentifierInfo *II = ID->getIdentifier();
1016 if (II == NSObjectII)
1019 // FIXME: For now, ignore classes that subclass SenTestCase and XCTestCase,
1020 // as these don't need to implement -dealloc. They implement tear down in
1021 // another way, which we should try and catch later.
1022 // http://llvm.org/bugs/show_bug.cgi?id=3187
1023 if (II == XCTestCaseII || II == SenTestCaseII)
1030 /// The -dealloc method in CIFilter highly unusual in that is will release
1031 /// instance variables belonging to its *subclasses* if the variable name
1032 /// starts with "input" or backs a property whose name starts with "input".
1033 /// Subclasses should not release these ivars in their own -dealloc method --
1034 /// doing so could result in an over release.
1036 /// This method returns true if the property will be released by
1037 /// -[CIFilter dealloc].
1038 bool ObjCDeallocChecker::isReleasedByCIFilterDealloc(
1039 const ObjCPropertyImplDecl *PropImpl) const {
1040 assert(PropImpl->getPropertyIvarDecl());
1041 StringRef PropName = PropImpl->getPropertyDecl()->getName();
1042 StringRef IvarName = PropImpl->getPropertyIvarDecl()->getName();
1044 const char *ReleasePrefix = "input";
1045 if (!(PropName.startswith(ReleasePrefix) ||
1046 IvarName.startswith(ReleasePrefix))) {
1050 const ObjCInterfaceDecl *ID =
1051 PropImpl->getPropertyIvarDecl()->getContainingInterface();
1052 for ( ; ID ; ID = ID->getSuperClass()) {
1053 IdentifierInfo *II = ID->getIdentifier();
1054 if (II == CIFilterII)
1061 /// Returns whether the ivar backing the property is an IBOutlet that
1062 /// has its value set by nib loading code without retaining the value.
1064 /// On macOS, if there is no setter, the nib-loading code sets the ivar
1065 /// directly, without retaining the value,
1067 /// On iOS and its derivatives, the nib-loading code will call
1068 /// -setValue:forKey:, which retains the value before directly setting the ivar.
1069 bool ObjCDeallocChecker::isNibLoadedIvarWithoutRetain(
1070 const ObjCPropertyImplDecl *PropImpl) const {
1071 const ObjCIvarDecl *IvarDecl = PropImpl->getPropertyIvarDecl();
1072 if (!IvarDecl->hasAttr<IBOutletAttr>())
1075 const llvm::Triple &Target =
1076 IvarDecl->getASTContext().getTargetInfo().getTriple();
1078 if (!Target.isMacOSX())
1081 if (PropImpl->getPropertyDecl()->getSetterMethodDecl())
1087 void ento::registerObjCDeallocChecker(CheckerManager &Mgr) {
1088 Mgr.registerChecker<ObjCDeallocChecker>();
1091 bool ento::shouldRegisterObjCDeallocChecker(const LangOptions &LO) {
1092 // These checker only makes sense under MRR.
1093 return LO.getGC() != LangOptions::GCOnly && !LO.ObjCAutoRefCount;