#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
#include "clang/Analysis/PathDiagnostic.h"
#include "clang/AST/Attr.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprObjC.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
using namespace ento;
enum class ReleaseRequirement {
MustRelease,
MustNotReleaseDirectly,
Unknown
};
static bool isSynthesizedRetainableProperty(const ObjCPropertyImplDecl *I,
const ObjCIvarDecl **ID,
const ObjCPropertyDecl **PD) {
if (I->getPropertyImplementation() != ObjCPropertyImplDecl::Synthesize)
return false;
(*ID) = I->getPropertyIvarDecl();
if (!(*ID))
return false;
QualType T = (*ID)->getType();
if (!T->isObjCRetainableType())
return false;
(*PD) = I->getPropertyDecl();
assert(*PD);
return true;
}
namespace {
class ObjCDeallocChecker
: public Checker<check::ASTDecl<ObjCImplementationDecl>,
check::PreObjCMessage, check::PostObjCMessage,
check::PreCall,
check::BeginFunction, check::EndFunction,
eval::Assume,
check::PointerEscape,
check::PreStmt<ReturnStmt>> {
mutable IdentifierInfo *NSObjectII, *SenTestCaseII, *XCTestCaseII,
*Block_releaseII, *CIFilterII;
mutable Selector DeallocSel, ReleaseSel;
std::unique_ptr<BugType> MissingReleaseBugType;
std::unique_ptr<BugType> ExtraReleaseBugType;
std::unique_ptr<BugType> MistakenDeallocBugType;
public:
ObjCDeallocChecker();
void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
BugReporter &BR) const;
void checkBeginFunction(CheckerContext &Ctx) const;
void checkPreObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
bool Assumption) const;
ProgramStateRef checkPointerEscape(ProgramStateRef State,
const InvalidatedSymbols &Escaped,
const CallEvent *Call,
PointerEscapeKind Kind) const;
void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
void checkEndFunction(const ReturnStmt *RS, CheckerContext &Ctx) const;
private:
void diagnoseMissingReleases(CheckerContext &C) const;
bool diagnoseExtraRelease(SymbolRef ReleasedValue, const ObjCMethodCall &M,
CheckerContext &C) const;
bool diagnoseMistakenDealloc(SymbolRef DeallocedValue,
const ObjCMethodCall &M,
CheckerContext &C) const;
SymbolRef getValueReleasedByNillingOut(const ObjCMethodCall &M,
CheckerContext &C) const;
const ObjCIvarRegion *getIvarRegionForIvarSymbol(SymbolRef IvarSym) const;
SymbolRef getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const;
const ObjCPropertyImplDecl*
findPropertyOnDeallocatingInstance(SymbolRef IvarSym,
CheckerContext &C) const;
ReleaseRequirement
getDeallocReleaseRequirement(const ObjCPropertyImplDecl *PropImpl) const;
bool isInInstanceDealloc(const CheckerContext &C, SVal &SelfValOut) const;
bool isInInstanceDealloc(const CheckerContext &C, const LocationContext *LCtx,
SVal &SelfValOut) const;
bool instanceDeallocIsOnStack(const CheckerContext &C,
SVal &InstanceValOut) const;
bool isSuperDeallocMessage(const ObjCMethodCall &M) const;
const ObjCImplDecl *getContainingObjCImpl(const LocationContext *LCtx) const;
const ObjCPropertyDecl *
findShadowedPropertyDecl(const ObjCPropertyImplDecl *PropImpl) const;
void transitionToReleaseValue(CheckerContext &C, SymbolRef Value) const;
ProgramStateRef removeValueRequiringRelease(ProgramStateRef State,
SymbolRef InstanceSym,
SymbolRef ValueSym) const;
void initIdentifierInfoAndSelectors(ASTContext &Ctx) const;
bool classHasSeparateTeardown(const ObjCInterfaceDecl *ID) const;
bool isReleasedByCIFilterDealloc(const ObjCPropertyImplDecl *PropImpl) const;
bool isNibLoadedIvarWithoutRetain(const ObjCPropertyImplDecl *PropImpl) const;
};
}
REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(SymbolSet, SymbolRef)
REGISTER_MAP_WITH_PROGRAMSTATE(UnreleasedIvarMap, SymbolRef, SymbolSet)
void ObjCDeallocChecker::checkASTDecl(const ObjCImplementationDecl *D,
AnalysisManager &Mgr,
BugReporter &BR) const {
assert(Mgr.getLangOpts().getGC() != LangOptions::GCOnly);
assert(!Mgr.getLangOpts().ObjCAutoRefCount);
initIdentifierInfoAndSelectors(Mgr.getASTContext());
const ObjCInterfaceDecl *ID = D->getClassInterface();
if (classHasSeparateTeardown(ID))
return;
const ObjCPropertyImplDecl *PropImplRequiringRelease = nullptr;
bool HasOthers = false;
for (const auto *I : D->property_impls()) {
if (getDeallocReleaseRequirement(I) == ReleaseRequirement::MustRelease) {
if (!PropImplRequiringRelease)
PropImplRequiringRelease = I;
else {
HasOthers = true;
break;
}
}
}
if (!PropImplRequiringRelease)
return;
const ObjCMethodDecl *MD = nullptr;
for (const auto *I : D->instance_methods()) {
if (I->getSelector() == DeallocSel) {
MD = I;
break;
}
}
if (!MD) { const char* Name = "Missing -dealloc";
std::string Buf;
llvm::raw_string_ostream OS(Buf);
OS << "'" << *D << "' lacks a 'dealloc' instance method but "
<< "must release '" << *PropImplRequiringRelease->getPropertyIvarDecl()
<< "'";
if (HasOthers)
OS << " and others";
PathDiagnosticLocation DLoc =
PathDiagnosticLocation::createBegin(D, BR.getSourceManager());
BR.EmitBasicReport(D, this, Name, categories::CoreFoundationObjectiveC,
OS.str(), DLoc);
return;
}
}
void ObjCDeallocChecker::checkBeginFunction(
CheckerContext &C) const {
initIdentifierInfoAndSelectors(C.getASTContext());
SVal SelfVal;
if (!isInInstanceDealloc(C, SelfVal))
return;
SymbolRef SelfSymbol = SelfVal.getAsSymbol();
const LocationContext *LCtx = C.getLocationContext();
ProgramStateRef InitialState = C.getState();
ProgramStateRef State = InitialState;
SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
SymbolSet RequiredReleases = F.getEmptySet();
if (const SymbolSet *CurrSet = State->get<UnreleasedIvarMap>(SelfSymbol))
RequiredReleases = *CurrSet;
for (auto *PropImpl : getContainingObjCImpl(LCtx)->property_impls()) {
ReleaseRequirement Requirement = getDeallocReleaseRequirement(PropImpl);
if (Requirement != ReleaseRequirement::MustRelease)
continue;
SVal LVal = State->getLValue(PropImpl->getPropertyIvarDecl(), SelfVal);
Optional<Loc> LValLoc = LVal.getAs<Loc>();
if (!LValLoc)
continue;
SVal InitialVal = State->getSVal(*LValLoc);
SymbolRef Symbol = InitialVal.getAsSymbol();
if (!Symbol || !isa<SymbolRegionValue>(Symbol))
continue;
RequiredReleases = F.add(RequiredReleases, Symbol);
}
if (!RequiredReleases.isEmpty()) {
State = State->set<UnreleasedIvarMap>(SelfSymbol, RequiredReleases);
}
if (State != InitialState) {
C.addTransition(State);
}
}
const ObjCIvarRegion *
ObjCDeallocChecker::getIvarRegionForIvarSymbol(SymbolRef IvarSym) const {
return dyn_cast_or_null<ObjCIvarRegion>(IvarSym->getOriginRegion());
}
SymbolRef
ObjCDeallocChecker::getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const {
const ObjCIvarRegion *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
if (!IvarRegion)
return nullptr;
return IvarRegion->getSymbolicBase()->getSymbol();
}
void ObjCDeallocChecker::checkPreObjCMessage(
const ObjCMethodCall &M, CheckerContext &C) const {
SVal DeallocedInstance;
if (!instanceDeallocIsOnStack(C, DeallocedInstance))
return;
SymbolRef ReleasedValue = nullptr;
if (M.getSelector() == ReleaseSel) {
ReleasedValue = M.getReceiverSVal().getAsSymbol();
} else if (M.getSelector() == DeallocSel && !M.isReceiverSelfOrSuper()) {
if (diagnoseMistakenDealloc(M.getReceiverSVal().getAsSymbol(), M, C))
return;
}
if (ReleasedValue) {
if (diagnoseExtraRelease(ReleasedValue,M, C))
return;
} else {
ReleasedValue = getValueReleasedByNillingOut(M, C);
}
if (!ReleasedValue)
return;
transitionToReleaseValue(C, ReleasedValue);
}
void ObjCDeallocChecker::checkPreCall(const CallEvent &Call,
CheckerContext &C) const {
const IdentifierInfo *II = Call.getCalleeIdentifier();
if (II != Block_releaseII)
return;
if (Call.getNumArgs() != 1)
return;
SymbolRef ReleasedValue = Call.getArgSVal(0).getAsSymbol();
if (!ReleasedValue)
return;
transitionToReleaseValue(C, ReleasedValue);
}
void ObjCDeallocChecker::checkPostObjCMessage(
const ObjCMethodCall &M, CheckerContext &C) const {
if (isSuperDeallocMessage(M))
diagnoseMissingReleases(C);
}
void ObjCDeallocChecker::checkEndFunction(
const ReturnStmt *RS, CheckerContext &C) const {
diagnoseMissingReleases(C);
}
void ObjCDeallocChecker::checkPreStmt(
const ReturnStmt *RS, CheckerContext &C) const {
diagnoseMissingReleases(C);
}
ProgramStateRef ObjCDeallocChecker::evalAssume(ProgramStateRef State, SVal Cond,
bool Assumption) const {
if (State->get<UnreleasedIvarMap>().isEmpty())
return State;
auto *CondBSE = dyn_cast_or_null<BinarySymExpr>(Cond.getAsSymbol());
if (!CondBSE)
return State;
BinaryOperator::Opcode OpCode = CondBSE->getOpcode();
if (Assumption) {
if (OpCode != BO_EQ)
return State;
} else {
if (OpCode != BO_NE)
return State;
}
SymbolRef NullSymbol = nullptr;
if (auto *SIE = dyn_cast<SymIntExpr>(CondBSE)) {
const llvm::APInt &RHS = SIE->getRHS();
if (RHS != 0)
return State;
NullSymbol = SIE->getLHS();
} else if (auto *SIE = dyn_cast<IntSymExpr>(CondBSE)) {
const llvm::APInt &LHS = SIE->getLHS();
if (LHS != 0)
return State;
NullSymbol = SIE->getRHS();
} else {
return State;
}
SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(NullSymbol);
if (!InstanceSymbol)
return State;
State = removeValueRequiringRelease(State, InstanceSymbol, NullSymbol);
return State;
}
ProgramStateRef ObjCDeallocChecker::checkPointerEscape(
ProgramStateRef State, const InvalidatedSymbols &Escaped,
const CallEvent *Call, PointerEscapeKind Kind) const {
if (State->get<UnreleasedIvarMap>().isEmpty())
return State;
auto *OMC = dyn_cast_or_null<ObjCMethodCall>(Call);
if (OMC && isSuperDeallocMessage(*OMC))
return State;
for (const auto &Sym : Escaped) {
if (!Call || (Call && !Call->isInSystemHeader())) {
State = State->remove<UnreleasedIvarMap>(Sym);
}
SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(Sym);
if (!InstanceSymbol)
continue;
State = removeValueRequiringRelease(State, InstanceSymbol, Sym);
}
return State;
}
void ObjCDeallocChecker::diagnoseMissingReleases(CheckerContext &C) const {
ProgramStateRef State = C.getState();
SVal SelfVal;
if (!isInInstanceDealloc(C, SelfVal))
return;
const MemRegion *SelfRegion = SelfVal.castAs<loc::MemRegionVal>().getRegion();
const LocationContext *LCtx = C.getLocationContext();
ExplodedNode *ErrNode = nullptr;
SymbolRef SelfSym = SelfVal.getAsSymbol();
if (!SelfSym)
return;
const SymbolSet *OldUnreleased = State->get<UnreleasedIvarMap>(SelfSym);
if (!OldUnreleased)
return;
SymbolSet NewUnreleased = *OldUnreleased;
SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
ProgramStateRef InitialState = State;
for (auto *IvarSymbol : *OldUnreleased) {
const TypedValueRegion *TVR =
cast<SymbolRegionValue>(IvarSymbol)->getRegion();
const ObjCIvarRegion *IvarRegion = cast<ObjCIvarRegion>(TVR);
if (SelfRegion != IvarRegion->getSuperRegion())
continue;
const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
if (IvarDecl->getContainingInterface() !=
cast<ObjCMethodDecl>(LCtx->getDecl())->getClassInterface())
continue;
NewUnreleased = F.remove(NewUnreleased, IvarSymbol);
if (State->getStateManager()
.getConstraintManager()
.isNull(State, IvarSymbol)
.isConstrainedTrue()) {
continue;
}
if (!ErrNode)
ErrNode = C.generateNonFatalErrorNode();
if (!ErrNode)
return;
std::string Buf;
llvm::raw_string_ostream OS(Buf);
const ObjCInterfaceDecl *Interface = IvarDecl->getContainingInterface();
if (classHasSeparateTeardown(Interface))
return;
ObjCImplDecl *ImplDecl = Interface->getImplementation();
const ObjCPropertyImplDecl *PropImpl =
ImplDecl->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Copy ||
PropDecl->getSetterKind() == ObjCPropertyDecl::Retain);
OS << "The '" << *IvarDecl << "' ivar in '" << *ImplDecl
<< "' was ";
if (PropDecl->getSetterKind() == ObjCPropertyDecl::Retain)
OS << "retained";
else
OS << "copied";
OS << " by a synthesized property but not released"
" before '[super dealloc]'";
auto BR = std::make_unique<PathSensitiveBugReport>(*MissingReleaseBugType,
OS.str(), ErrNode);
C.emitReport(std::move(BR));
}
if (NewUnreleased.isEmpty()) {
State = State->remove<UnreleasedIvarMap>(SelfSym);
} else {
State = State->set<UnreleasedIvarMap>(SelfSym, NewUnreleased);
}
if (ErrNode) {
C.addTransition(State, ErrNode);
} else if (State != InitialState) {
C.addTransition(State);
}
assert(!LCtx->inTopFrame() || State->get<UnreleasedIvarMap>().isEmpty());
}
const ObjCPropertyImplDecl *
ObjCDeallocChecker::findPropertyOnDeallocatingInstance(
SymbolRef IvarSym, CheckerContext &C) const {
SVal DeallocedInstance;
if (!isInInstanceDealloc(C, DeallocedInstance))
return nullptr;
auto *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
if (!IvarRegion)
return nullptr;
if (DeallocedInstance.castAs<loc::MemRegionVal>().getRegion() !=
IvarRegion->getSuperRegion())
return nullptr;
const LocationContext *LCtx = C.getLocationContext();
const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
const ObjCImplDecl *Container = getContainingObjCImpl(LCtx);
const ObjCPropertyImplDecl *PropImpl =
Container->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
return PropImpl;
}
bool ObjCDeallocChecker::diagnoseExtraRelease(SymbolRef ReleasedValue,
const ObjCMethodCall &M,
CheckerContext &C) const {
const ObjCPropertyImplDecl *PropImpl =
findPropertyOnDeallocatingInstance(ReleasedValue, C);
if (!PropImpl)
return false;
if (getDeallocReleaseRequirement(PropImpl) !=
ReleaseRequirement::MustNotReleaseDirectly) {
return false;
}
const ObjCPropertyDecl *PropDecl = findShadowedPropertyDecl(PropImpl);
if (PropDecl) {
if (PropDecl->isReadOnly())
return false;
} else {
PropDecl = PropImpl->getPropertyDecl();
}
ExplodedNode *ErrNode = C.generateNonFatalErrorNode();
if (!ErrNode)
return false;
std::string Buf;
llvm::raw_string_ostream OS(Buf);
assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Weak ||
(PropDecl->getSetterKind() == ObjCPropertyDecl::Assign &&
!PropDecl->isReadOnly()) ||
isReleasedByCIFilterDealloc(PropImpl)
);
const ObjCImplDecl *Container = getContainingObjCImpl(C.getLocationContext());
OS << "The '" << *PropImpl->getPropertyIvarDecl()
<< "' ivar in '" << *Container;
if (isReleasedByCIFilterDealloc(PropImpl)) {
OS << "' will be released by '-[CIFilter dealloc]' but also released here";
} else {
OS << "' was synthesized for ";
if (PropDecl->getSetterKind() == ObjCPropertyDecl::Weak)
OS << "a weak";
else
OS << "an assign, readwrite";
OS << " property but was released in 'dealloc'";
}
auto BR = std::make_unique<PathSensitiveBugReport>(*ExtraReleaseBugType,
OS.str(), ErrNode);
BR->addRange(M.getOriginExpr()->getSourceRange());
C.emitReport(std::move(BR));
return true;
}
bool ObjCDeallocChecker::diagnoseMistakenDealloc(SymbolRef DeallocedValue,
const ObjCMethodCall &M,
CheckerContext &C) const {
if (!DeallocedValue)
return false;
const ObjCPropertyImplDecl *PropImpl =
findPropertyOnDeallocatingInstance(DeallocedValue, C);
if (!PropImpl)
return false;
if (getDeallocReleaseRequirement(PropImpl) !=
ReleaseRequirement::MustRelease) {
return false;
}
ExplodedNode *ErrNode = C.generateErrorNode();
if (!ErrNode)
return false;
std::string Buf;
llvm::raw_string_ostream OS(Buf);
OS << "'" << *PropImpl->getPropertyIvarDecl()
<< "' should be released rather than deallocated";
auto BR = std::make_unique<PathSensitiveBugReport>(*MistakenDeallocBugType,
OS.str(), ErrNode);
BR->addRange(M.getOriginExpr()->getSourceRange());
C.emitReport(std::move(BR));
return true;
}
ObjCDeallocChecker::ObjCDeallocChecker()
: NSObjectII(nullptr), SenTestCaseII(nullptr), XCTestCaseII(nullptr),
CIFilterII(nullptr) {
MissingReleaseBugType.reset(
new BugType(this, "Missing ivar release (leak)",
categories::MemoryRefCount));
ExtraReleaseBugType.reset(
new BugType(this, "Extra ivar release",
categories::MemoryRefCount));
MistakenDeallocBugType.reset(
new BugType(this, "Mistaken dealloc",
categories::MemoryRefCount));
}
void ObjCDeallocChecker::initIdentifierInfoAndSelectors(
ASTContext &Ctx) const {
if (NSObjectII)
return;
NSObjectII = &Ctx.Idents.get("NSObject");
SenTestCaseII = &Ctx.Idents.get("SenTestCase");
XCTestCaseII = &Ctx.Idents.get("XCTestCase");
Block_releaseII = &Ctx.Idents.get("_Block_release");
CIFilterII = &Ctx.Idents.get("CIFilter");
IdentifierInfo *DeallocII = &Ctx.Idents.get("dealloc");
IdentifierInfo *ReleaseII = &Ctx.Idents.get("release");
DeallocSel = Ctx.Selectors.getSelector(0, &DeallocII);
ReleaseSel = Ctx.Selectors.getSelector(0, &ReleaseII);
}
bool ObjCDeallocChecker::isSuperDeallocMessage(
const ObjCMethodCall &M) const {
if (M.getOriginExpr()->getReceiverKind() != ObjCMessageExpr::SuperInstance)
return false;
return M.getSelector() == DeallocSel;
}
const ObjCImplDecl *
ObjCDeallocChecker::getContainingObjCImpl(const LocationContext *LCtx) const {
auto *MD = cast<ObjCMethodDecl>(LCtx->getDecl());
return cast<ObjCImplDecl>(MD->getDeclContext());
}
const ObjCPropertyDecl *ObjCDeallocChecker::findShadowedPropertyDecl(
const ObjCPropertyImplDecl *PropImpl) const {
const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
if (PropDecl->isReadOnly())
return nullptr;
auto *CatDecl = dyn_cast<ObjCCategoryDecl>(PropDecl->getDeclContext());
if (!CatDecl || !CatDecl->IsClassExtension())
return nullptr;
IdentifierInfo *ID = PropDecl->getIdentifier();
DeclContext::lookup_result R = CatDecl->getClassInterface()->lookup(ID);
for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
auto *ShadowedPropDecl = dyn_cast<ObjCPropertyDecl>(*I);
if (!ShadowedPropDecl)
continue;
if (ShadowedPropDecl->isInstanceProperty()) {
assert(ShadowedPropDecl->isReadOnly());
return ShadowedPropDecl;
}
}
return nullptr;
}
void ObjCDeallocChecker::transitionToReleaseValue(CheckerContext &C,
SymbolRef Value) const {
assert(Value);
SymbolRef InstanceSym = getInstanceSymbolFromIvarSymbol(Value);
if (!InstanceSym)
return;
ProgramStateRef InitialState = C.getState();
ProgramStateRef ReleasedState =
removeValueRequiringRelease(InitialState, InstanceSym, Value);
if (ReleasedState != InitialState) {
C.addTransition(ReleasedState);
}
}
ProgramStateRef ObjCDeallocChecker::removeValueRequiringRelease(
ProgramStateRef State, SymbolRef Instance, SymbolRef Value) const {
assert(Instance);
assert(Value);
const ObjCIvarRegion *RemovedRegion = getIvarRegionForIvarSymbol(Value);
if (!RemovedRegion)
return State;
const SymbolSet *Unreleased = State->get<UnreleasedIvarMap>(Instance);
if (!Unreleased)
return State;
SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
SymbolSet NewUnreleased = *Unreleased;
for (auto &Sym : *Unreleased) {
const ObjCIvarRegion *UnreleasedRegion = getIvarRegionForIvarSymbol(Sym);
assert(UnreleasedRegion);
if (RemovedRegion->getDecl() == UnreleasedRegion->getDecl()) {
NewUnreleased = F.remove(NewUnreleased, Sym);
}
}
if (NewUnreleased.isEmpty()) {
return State->remove<UnreleasedIvarMap>(Instance);
}
return State->set<UnreleasedIvarMap>(Instance, NewUnreleased);
}
ReleaseRequirement ObjCDeallocChecker::getDeallocReleaseRequirement(
const ObjCPropertyImplDecl *PropImpl) const {
const ObjCIvarDecl *IvarDecl;
const ObjCPropertyDecl *PropDecl;
if (!isSynthesizedRetainableProperty(PropImpl, &IvarDecl, &PropDecl))
return ReleaseRequirement::Unknown;
ObjCPropertyDecl::SetterKind SK = PropDecl->getSetterKind();
switch (SK) {
case ObjCPropertyDecl::Retain:
case ObjCPropertyDecl::Copy:
if (isReleasedByCIFilterDealloc(PropImpl))
return ReleaseRequirement::MustNotReleaseDirectly;
if (isNibLoadedIvarWithoutRetain(PropImpl))
return ReleaseRequirement::Unknown;
return ReleaseRequirement::MustRelease;
case ObjCPropertyDecl::Weak:
return ReleaseRequirement::MustNotReleaseDirectly;
case ObjCPropertyDecl::Assign:
if (PropDecl->isReadOnly())
return ReleaseRequirement::Unknown;
return ReleaseRequirement::MustNotReleaseDirectly;
}
llvm_unreachable("Unrecognized setter kind");
}
SymbolRef
ObjCDeallocChecker::getValueReleasedByNillingOut(const ObjCMethodCall &M,
CheckerContext &C) const {
SVal ReceiverVal = M.getReceiverSVal();
if (!ReceiverVal.isValid())
return nullptr;
if (M.getNumArgs() == 0)
return nullptr;
if (!M.getArgExpr(0)->getType()->isObjCRetainableType())
return nullptr;
SVal Arg = M.getArgSVal(0);
ProgramStateRef notNilState, nilState;
std::tie(notNilState, nilState) =
M.getState()->assume(Arg.castAs<DefinedOrUnknownSVal>());
if (!(nilState && !notNilState))
return nullptr;
const ObjCPropertyDecl *Prop = M.getAccessedProperty();
if (!Prop)
return nullptr;
ObjCIvarDecl *PropIvarDecl = Prop->getPropertyIvarDecl();
if (!PropIvarDecl)
return nullptr;
ProgramStateRef State = C.getState();
SVal LVal = State->getLValue(PropIvarDecl, ReceiverVal);
Optional<Loc> LValLoc = LVal.getAs<Loc>();
if (!LValLoc)
return nullptr;
SVal CurrentValInIvar = State->getSVal(*LValLoc);
return CurrentValInIvar.getAsSymbol();
}
bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
SVal &SelfValOut) const {
return isInInstanceDealloc(C, C.getLocationContext(), SelfValOut);
}
bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
const LocationContext *LCtx,
SVal &SelfValOut) const {
auto *MD = dyn_cast<ObjCMethodDecl>(LCtx->getDecl());
if (!MD || !MD->isInstanceMethod() || MD->getSelector() != DeallocSel)
return false;
const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
assert(SelfDecl && "No self in -dealloc?");
ProgramStateRef State = C.getState();
SelfValOut = State->getSVal(State->getRegion(SelfDecl, LCtx));
return true;
}
bool ObjCDeallocChecker::instanceDeallocIsOnStack(const CheckerContext &C,
SVal &InstanceValOut) const {
const LocationContext *LCtx = C.getLocationContext();
while (LCtx) {
if (isInInstanceDealloc(C, LCtx, InstanceValOut))
return true;
LCtx = LCtx->getParent();
}
return false;
}
bool ObjCDeallocChecker::classHasSeparateTeardown(
const ObjCInterfaceDecl *ID) const {
for ( ; ID ; ID = ID->getSuperClass()) {
IdentifierInfo *II = ID->getIdentifier();
if (II == NSObjectII)
return false;
if (II == XCTestCaseII || II == SenTestCaseII)
return true;
}
return true;
}
bool ObjCDeallocChecker::isReleasedByCIFilterDealloc(
const ObjCPropertyImplDecl *PropImpl) const {
assert(PropImpl->getPropertyIvarDecl());
StringRef PropName = PropImpl->getPropertyDecl()->getName();
StringRef IvarName = PropImpl->getPropertyIvarDecl()->getName();
const char *ReleasePrefix = "input";
if (!(PropName.startswith(ReleasePrefix) ||
IvarName.startswith(ReleasePrefix))) {
return false;
}
const ObjCInterfaceDecl *ID =
PropImpl->getPropertyIvarDecl()->getContainingInterface();
for ( ; ID ; ID = ID->getSuperClass()) {
IdentifierInfo *II = ID->getIdentifier();
if (II == CIFilterII)
return true;
}
return false;
}
bool ObjCDeallocChecker::isNibLoadedIvarWithoutRetain(
const ObjCPropertyImplDecl *PropImpl) const {
const ObjCIvarDecl *IvarDecl = PropImpl->getPropertyIvarDecl();
if (!IvarDecl->hasAttr<IBOutletAttr>())
return false;
const llvm::Triple &Target =
IvarDecl->getASTContext().getTargetInfo().getTriple();
if (!Target.isMacOSX())
return false;
if (PropImpl->getPropertyDecl()->getSetterMethodDecl())
return false;
return true;
}
void ento::registerObjCDeallocChecker(CheckerManager &Mgr) {
Mgr.registerChecker<ObjCDeallocChecker>();
}
bool ento::shouldRegisterObjCDeallocChecker(const CheckerManager &mgr) {
const LangOptions &LO = mgr.getLangOpts();
return LO.getGC() != LangOptions::GCOnly && !LO.ObjCAutoRefCount;
}