#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
#include "clang/AST/Attr.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallString.h"
using namespace clang;
using namespace ento;
namespace {
struct ChecksFilter {
bool check_MissingInvalidationMethod = false;
bool check_InstanceVariableInvalidation = false;
CheckerNameRef checkName_MissingInvalidationMethod;
CheckerNameRef checkName_InstanceVariableInvalidation;
};
class IvarInvalidationCheckerImpl {
typedef llvm::SmallSetVector<const ObjCMethodDecl*, 2> MethodSet;
typedef llvm::DenseMap<const ObjCMethodDecl*,
const ObjCIvarDecl*> MethToIvarMapTy;
typedef llvm::DenseMap<const ObjCPropertyDecl*,
const ObjCIvarDecl*> PropToIvarMapTy;
typedef llvm::DenseMap<const ObjCIvarDecl*,
const ObjCPropertyDecl*> IvarToPropMapTy;
struct InvalidationInfo {
bool IsInvalidated;
MethodSet InvalidationMethods;
InvalidationInfo() : IsInvalidated(false) {}
void addInvalidationMethod(const ObjCMethodDecl *MD) {
InvalidationMethods.insert(MD);
}
bool needsInvalidation() const {
return !InvalidationMethods.empty();
}
bool hasMethod(const ObjCMethodDecl *MD) {
if (IsInvalidated)
return true;
for (MethodSet::iterator I = InvalidationMethods.begin(),
E = InvalidationMethods.end(); I != E; ++I) {
if (*I == MD) {
IsInvalidated = true;
return true;
}
}
return false;
}
};
typedef llvm::DenseMap<const ObjCIvarDecl*, InvalidationInfo> IvarSet;
class MethodCrawler : public ConstStmtVisitor<MethodCrawler> {
IvarSet &IVars;
bool &CalledAnotherInvalidationMethod;
const MethToIvarMapTy &PropertySetterToIvarMap;
const MethToIvarMapTy &PropertyGetterToIvarMap;
const PropToIvarMapTy &PropertyToIvarMap;
const ObjCMethodDecl *InvalidationMethod;
ASTContext &Ctx;
const Expr *peel(const Expr *E) const;
bool isZero(const Expr *E) const;
void markInvalidated(const ObjCIvarDecl *Iv);
void checkObjCIvarRefExpr(const ObjCIvarRefExpr *IvarRef);
void checkObjCPropertyRefExpr(const ObjCPropertyRefExpr *PA);
void checkObjCMessageExpr(const ObjCMessageExpr *ME);
void check(const Expr *E);
public:
MethodCrawler(IvarSet &InIVars,
bool &InCalledAnotherInvalidationMethod,
const MethToIvarMapTy &InPropertySetterToIvarMap,
const MethToIvarMapTy &InPropertyGetterToIvarMap,
const PropToIvarMapTy &InPropertyToIvarMap,
ASTContext &InCtx)
: IVars(InIVars),
CalledAnotherInvalidationMethod(InCalledAnotherInvalidationMethod),
PropertySetterToIvarMap(InPropertySetterToIvarMap),
PropertyGetterToIvarMap(InPropertyGetterToIvarMap),
PropertyToIvarMap(InPropertyToIvarMap),
InvalidationMethod(nullptr),
Ctx(InCtx) {}
void VisitStmt(const Stmt *S) { VisitChildren(S); }
void VisitBinaryOperator(const BinaryOperator *BO);
void VisitObjCMessageExpr(const ObjCMessageExpr *ME);
void VisitChildren(const Stmt *S) {
for (const auto *Child : S->children()) {
if (Child)
this->Visit(Child);
if (CalledAnotherInvalidationMethod)
return;
}
}
};
static void containsInvalidationMethod(const ObjCContainerDecl *D,
InvalidationInfo &Out,
bool LookForPartial);
static bool trackIvar(const ObjCIvarDecl *Iv, IvarSet &TrackedIvars,
const ObjCIvarDecl **FirstIvarDecl);
static const ObjCIvarDecl *findPropertyBackingIvar(
const ObjCPropertyDecl *Prop,
const ObjCInterfaceDecl *InterfaceD,
IvarSet &TrackedIvars,
const ObjCIvarDecl **FirstIvarDecl);
static void printIvar(llvm::raw_svector_ostream &os,
const ObjCIvarDecl *IvarDecl,
const IvarToPropMapTy &IvarToPopertyMap);
void reportNoInvalidationMethod(CheckerNameRef CheckName,
const ObjCIvarDecl *FirstIvarDecl,
const IvarToPropMapTy &IvarToPopertyMap,
const ObjCInterfaceDecl *InterfaceD,
bool MissingDeclaration) const;
void reportIvarNeedsInvalidation(const ObjCIvarDecl *IvarD,
const IvarToPropMapTy &IvarToPopertyMap,
const ObjCMethodDecl *MethodD) const;
AnalysisManager& Mgr;
BugReporter &BR;
const ChecksFilter &Filter;
public:
IvarInvalidationCheckerImpl(AnalysisManager& InMgr,
BugReporter &InBR,
const ChecksFilter &InFilter) :
Mgr (InMgr), BR(InBR), Filter(InFilter) {}
void visit(const ObjCImplementationDecl *D) const;
};
static bool isInvalidationMethod(const ObjCMethodDecl *M, bool LookForPartial) {
for (const auto *Ann : M->specific_attrs<AnnotateAttr>()) {
if (!LookForPartial &&
Ann->getAnnotation() == "objc_instance_variable_invalidator")
return true;
if (LookForPartial &&
Ann->getAnnotation() == "objc_instance_variable_invalidator_partial")
return true;
}
return false;
}
void IvarInvalidationCheckerImpl::containsInvalidationMethod(
const ObjCContainerDecl *D, InvalidationInfo &OutInfo, bool Partial) {
if (!D)
return;
assert(!isa<ObjCImplementationDecl>(D));
for (const auto *MDI : D->methods())
if (isInvalidationMethod(MDI, Partial))
OutInfo.addInvalidationMethod(
cast<ObjCMethodDecl>(MDI->getCanonicalDecl()));
if (const ObjCInterfaceDecl *InterfD = dyn_cast<ObjCInterfaceDecl>(D)) {
for (const auto *I : InterfD->protocols())
containsInvalidationMethod(I->getDefinition(), OutInfo, Partial);
for (const auto *Ext : InterfD->visible_extensions())
containsInvalidationMethod(Ext, OutInfo, Partial);
containsInvalidationMethod(InterfD->getSuperClass(), OutInfo, Partial);
return;
}
if (const ObjCProtocolDecl *ProtD = dyn_cast<ObjCProtocolDecl>(D)) {
for (const auto *I : ProtD->protocols()) {
containsInvalidationMethod(I->getDefinition(), OutInfo, Partial);
}
return;
}
}
bool IvarInvalidationCheckerImpl::trackIvar(const ObjCIvarDecl *Iv,
IvarSet &TrackedIvars,
const ObjCIvarDecl **FirstIvarDecl) {
QualType IvQTy = Iv->getType();
const ObjCObjectPointerType *IvTy = IvQTy->getAs<ObjCObjectPointerType>();
if (!IvTy)
return false;
const ObjCInterfaceDecl *IvInterf = IvTy->getInterfaceDecl();
InvalidationInfo Info;
containsInvalidationMethod(IvInterf, Info, false);
if (Info.needsInvalidation()) {
const ObjCIvarDecl *I = cast<ObjCIvarDecl>(Iv->getCanonicalDecl());
TrackedIvars[I] = Info;
if (!*FirstIvarDecl)
*FirstIvarDecl = I;
return true;
}
return false;
}
const ObjCIvarDecl *IvarInvalidationCheckerImpl::findPropertyBackingIvar(
const ObjCPropertyDecl *Prop,
const ObjCInterfaceDecl *InterfaceD,
IvarSet &TrackedIvars,
const ObjCIvarDecl **FirstIvarDecl) {
const ObjCIvarDecl *IvarD = nullptr;
IvarD = Prop->getPropertyIvarDecl();
if (IvarD && IvarD->getContainingInterface() == InterfaceD) {
if (TrackedIvars.count(IvarD)) {
return IvarD;
}
if (trackIvar(IvarD, TrackedIvars, FirstIvarDecl))
return IvarD;
}
StringRef PropName = Prop->getIdentifier()->getName();
for (IvarSet::const_iterator I = TrackedIvars.begin(),
E = TrackedIvars.end(); I != E; ++I) {
const ObjCIvarDecl *Iv = I->first;
StringRef IvarName = Iv->getName();
if (IvarName == PropName)
return Iv;
SmallString<128> PropNameWithUnderscore;
{
llvm::raw_svector_ostream os(PropNameWithUnderscore);
os << '_' << PropName;
}
if (IvarName == PropNameWithUnderscore)
return Iv;
}
return nullptr;
}
void IvarInvalidationCheckerImpl::printIvar(llvm::raw_svector_ostream &os,
const ObjCIvarDecl *IvarDecl,
const IvarToPropMapTy &IvarToPopertyMap) {
if (IvarDecl->getSynthesize()) {
const ObjCPropertyDecl *PD = IvarToPopertyMap.lookup(IvarDecl);
assert(PD &&"Do we synthesize ivars for something other than properties?");
os << "Property "<< PD->getName() << " ";
} else {
os << "Instance variable "<< IvarDecl->getName() << " ";
}
}
void IvarInvalidationCheckerImpl::
visit(const ObjCImplementationDecl *ImplD) const {
IvarSet Ivars;
const ObjCIvarDecl *FirstIvarDecl = nullptr;
const ObjCInterfaceDecl *InterfaceD = ImplD->getClassInterface();
ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(InterfaceD);
for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Iv= Iv->getNextIvar())
trackIvar(Iv, Ivars, &FirstIvarDecl);
MethToIvarMapTy PropSetterToIvarMap;
MethToIvarMapTy PropGetterToIvarMap;
PropToIvarMapTy PropertyToIvarMap;
IvarToPropMapTy IvarToPopertyMap;
ObjCInterfaceDecl::PropertyMap PropMap;
ObjCInterfaceDecl::PropertyDeclOrder PropOrder;
InterfaceD->collectPropertiesToImplement(PropMap, PropOrder);
for (ObjCInterfaceDecl::PropertyMap::iterator
I = PropMap.begin(), E = PropMap.end(); I != E; ++I) {
const ObjCPropertyDecl *PD = I->second;
if (PD->isClassProperty())
continue;
const ObjCIvarDecl *ID = findPropertyBackingIvar(PD, InterfaceD, Ivars,
&FirstIvarDecl);
if (!ID)
continue;
PD = cast<ObjCPropertyDecl>(PD->getCanonicalDecl());
PropertyToIvarMap[PD] = ID;
IvarToPopertyMap[ID] = PD;
const ObjCMethodDecl *SetterD = PD->getSetterMethodDecl();
if (SetterD) {
SetterD = SetterD->getCanonicalDecl();
PropSetterToIvarMap[SetterD] = ID;
}
const ObjCMethodDecl *GetterD = PD->getGetterMethodDecl();
if (GetterD) {
GetterD = GetterD->getCanonicalDecl();
PropGetterToIvarMap[GetterD] = ID;
}
}
if (Ivars.empty())
return;
InvalidationInfo PartialInfo;
containsInvalidationMethod(InterfaceD, PartialInfo, true);
bool AtImplementationContainsAtLeastOnePartialInvalidationMethod = false;
for (MethodSet::iterator
I = PartialInfo.InvalidationMethods.begin(),
E = PartialInfo.InvalidationMethods.end(); I != E; ++I) {
const ObjCMethodDecl *InterfD = *I;
const ObjCMethodDecl *D = ImplD->getMethod(InterfD->getSelector(),
InterfD->isInstanceMethod());
if (D && D->hasBody()) {
AtImplementationContainsAtLeastOnePartialInvalidationMethod = true;
bool CalledAnotherInvalidationMethod = false;
MethodCrawler(Ivars,
CalledAnotherInvalidationMethod,
PropSetterToIvarMap,
PropGetterToIvarMap,
PropertyToIvarMap,
BR.getContext()).VisitStmt(D->getBody());
if (CalledAnotherInvalidationMethod)
Ivars.clear();
}
}
if (Ivars.empty())
return;
InvalidationInfo Info;
containsInvalidationMethod(InterfaceD, Info, false);
if (!Info.needsInvalidation() && !PartialInfo.needsInvalidation()) {
if (Filter.check_MissingInvalidationMethod)
reportNoInvalidationMethod(Filter.checkName_MissingInvalidationMethod,
FirstIvarDecl, IvarToPopertyMap, InterfaceD,
true);
return;
}
if (!Filter.check_InstanceVariableInvalidation)
return;
bool AtImplementationContainsAtLeastOneInvalidationMethod = false;
for (MethodSet::iterator I = Info.InvalidationMethods.begin(),
E = Info.InvalidationMethods.end(); I != E; ++I) {
const ObjCMethodDecl *InterfD = *I;
const ObjCMethodDecl *D = ImplD->getMethod(InterfD->getSelector(),
InterfD->isInstanceMethod());
if (D && D->hasBody()) {
AtImplementationContainsAtLeastOneInvalidationMethod = true;
IvarSet IvarsI = Ivars;
bool CalledAnotherInvalidationMethod = false;
MethodCrawler(IvarsI,
CalledAnotherInvalidationMethod,
PropSetterToIvarMap,
PropGetterToIvarMap,
PropertyToIvarMap,
BR.getContext()).VisitStmt(D->getBody());
if (CalledAnotherInvalidationMethod)
continue;
for (IvarSet::const_iterator
I = IvarsI.begin(), E = IvarsI.end(); I != E; ++I)
reportIvarNeedsInvalidation(I->first, IvarToPopertyMap, D);
}
}
if (!AtImplementationContainsAtLeastOneInvalidationMethod) {
if (AtImplementationContainsAtLeastOnePartialInvalidationMethod) {
for (IvarSet::const_iterator
I = Ivars.begin(), E = Ivars.end(); I != E; ++I)
reportIvarNeedsInvalidation(I->first, IvarToPopertyMap, nullptr);
} else {
reportNoInvalidationMethod(Filter.checkName_InstanceVariableInvalidation,
FirstIvarDecl, IvarToPopertyMap, InterfaceD,
false);
}
}
}
void IvarInvalidationCheckerImpl::reportNoInvalidationMethod(
CheckerNameRef CheckName, const ObjCIvarDecl *FirstIvarDecl,
const IvarToPropMapTy &IvarToPopertyMap,
const ObjCInterfaceDecl *InterfaceD, bool MissingDeclaration) const {
SmallString<128> sbuf;
llvm::raw_svector_ostream os(sbuf);
assert(FirstIvarDecl);
printIvar(os, FirstIvarDecl, IvarToPopertyMap);
os << "needs to be invalidated; ";
if (MissingDeclaration)
os << "no invalidation method is declared for ";
else
os << "no invalidation method is defined in the @implementation for ";
os << InterfaceD->getName();
PathDiagnosticLocation IvarDecLocation =
PathDiagnosticLocation::createBegin(FirstIvarDecl, BR.getSourceManager());
BR.EmitBasicReport(FirstIvarDecl, CheckName, "Incomplete invalidation",
categories::CoreFoundationObjectiveC, os.str(),
IvarDecLocation);
}
void IvarInvalidationCheckerImpl::
reportIvarNeedsInvalidation(const ObjCIvarDecl *IvarD,
const IvarToPropMapTy &IvarToPopertyMap,
const ObjCMethodDecl *MethodD) const {
SmallString<128> sbuf;
llvm::raw_svector_ostream os(sbuf);
printIvar(os, IvarD, IvarToPopertyMap);
os << "needs to be invalidated or set to nil";
if (MethodD) {
PathDiagnosticLocation MethodDecLocation =
PathDiagnosticLocation::createEnd(MethodD->getBody(),
BR.getSourceManager(),
Mgr.getAnalysisDeclContext(MethodD));
BR.EmitBasicReport(MethodD, Filter.checkName_InstanceVariableInvalidation,
"Incomplete invalidation",
categories::CoreFoundationObjectiveC, os.str(),
MethodDecLocation);
} else {
BR.EmitBasicReport(
IvarD, Filter.checkName_InstanceVariableInvalidation,
"Incomplete invalidation", categories::CoreFoundationObjectiveC,
os.str(),
PathDiagnosticLocation::createBegin(IvarD, BR.getSourceManager()));
}
}
void IvarInvalidationCheckerImpl::MethodCrawler::markInvalidated(
const ObjCIvarDecl *Iv) {
IvarSet::iterator I = IVars.find(Iv);
if (I != IVars.end()) {
if (!InvalidationMethod || I->second.hasMethod(InvalidationMethod))
IVars.erase(I);
}
}
const Expr *IvarInvalidationCheckerImpl::MethodCrawler::peel(const Expr *E) const {
E = E->IgnoreParenCasts();
if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
E = POE->getSyntacticForm()->IgnoreParenCasts();
if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
E = OVE->getSourceExpr()->IgnoreParenCasts();
return E;
}
void IvarInvalidationCheckerImpl::MethodCrawler::checkObjCIvarRefExpr(
const ObjCIvarRefExpr *IvarRef) {
if (const Decl *D = IvarRef->getDecl())
markInvalidated(cast<ObjCIvarDecl>(D->getCanonicalDecl()));
}
void IvarInvalidationCheckerImpl::MethodCrawler::checkObjCMessageExpr(
const ObjCMessageExpr *ME) {
const ObjCMethodDecl *MD = ME->getMethodDecl();
if (MD) {
MD = MD->getCanonicalDecl();
MethToIvarMapTy::const_iterator IvI = PropertyGetterToIvarMap.find(MD);
if (IvI != PropertyGetterToIvarMap.end())
markInvalidated(IvI->second);
}
}
void IvarInvalidationCheckerImpl::MethodCrawler::checkObjCPropertyRefExpr(
const ObjCPropertyRefExpr *PA) {
if (PA->isExplicitProperty()) {
const ObjCPropertyDecl *PD = PA->getExplicitProperty();
if (PD) {
PD = cast<ObjCPropertyDecl>(PD->getCanonicalDecl());
PropToIvarMapTy::const_iterator IvI = PropertyToIvarMap.find(PD);
if (IvI != PropertyToIvarMap.end())
markInvalidated(IvI->second);
return;
}
}
if (PA->isImplicitProperty()) {
const ObjCMethodDecl *MD = PA->getImplicitPropertySetter();
if (MD) {
MD = MD->getCanonicalDecl();
MethToIvarMapTy::const_iterator IvI =PropertyGetterToIvarMap.find(MD);
if (IvI != PropertyGetterToIvarMap.end())
markInvalidated(IvI->second);
return;
}
}
}
bool IvarInvalidationCheckerImpl::MethodCrawler::isZero(const Expr *E) const {
E = peel(E);
return (E->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull)
!= Expr::NPCK_NotNull);
}
void IvarInvalidationCheckerImpl::MethodCrawler::check(const Expr *E) {
E = peel(E);
if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
checkObjCIvarRefExpr(IvarRef);
return;
}
if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E)) {
checkObjCPropertyRefExpr(PropRef);
return;
}
if (const ObjCMessageExpr *MsgExpr = dyn_cast<ObjCMessageExpr>(E)) {
checkObjCMessageExpr(MsgExpr);
return;
}
}
void IvarInvalidationCheckerImpl::MethodCrawler::VisitBinaryOperator(
const BinaryOperator *BO) {
VisitStmt(BO);
BinaryOperatorKind Opcode = BO->getOpcode();
if (Opcode != BO_Assign &&
Opcode != BO_EQ &&
Opcode != BO_NE)
return;
if (isZero(BO->getRHS())) {
check(BO->getLHS());
return;
}
if (Opcode != BO_Assign && isZero(BO->getLHS())) {
check(BO->getRHS());
return;
}
}
void IvarInvalidationCheckerImpl::MethodCrawler::VisitObjCMessageExpr(
const ObjCMessageExpr *ME) {
const ObjCMethodDecl *MD = ME->getMethodDecl();
const Expr *Receiver = ME->getInstanceReceiver();
if (Receiver && isInvalidationMethod(MD, false))
if (Receiver->isObjCSelfExpr()) {
CalledAnotherInvalidationMethod = true;
return;
}
if (MD && (ME->getNumArgs() == 1) && isZero(ME->getArg(0))) {
MD = MD->getCanonicalDecl();
MethToIvarMapTy::const_iterator IvI = PropertySetterToIvarMap.find(MD);
if (IvI != PropertySetterToIvarMap.end()) {
markInvalidated(IvI->second);
return;
}
}
if (Receiver) {
InvalidationMethod = MD;
check(Receiver->IgnoreParenCasts());
InvalidationMethod = nullptr;
}
VisitStmt(ME);
}
}
namespace {
class IvarInvalidationChecker :
public Checker<check::ASTDecl<ObjCImplementationDecl> > {
public:
ChecksFilter Filter;
public:
void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
BugReporter &BR) const {
IvarInvalidationCheckerImpl Walker(Mgr, BR, Filter);
Walker.visit(D);
}
};
}
void ento::registerIvarInvalidationModeling(CheckerManager &mgr) {
mgr.registerChecker<IvarInvalidationChecker>();
}
bool ento::shouldRegisterIvarInvalidationModeling(const CheckerManager &mgr) {
return true;
}
#define REGISTER_CHECKER(name) \
void ento::register##name(CheckerManager &mgr) { \
IvarInvalidationChecker *checker = \
mgr.getChecker<IvarInvalidationChecker>(); \
checker->Filter.check_##name = true; \
checker->Filter.checkName_##name = mgr.getCurrentCheckerName(); \
} \
\
bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; }
REGISTER_CHECKER(InstanceVariableInvalidation)
REGISTER_CHECKER(MissingInvalidationMethod)