"git@repo.hca.bsc.es:rferrer/llvm-epi.git" did not exist on "f22f34f0cc3d9b3768c58f8fb4e823e994d76b0b"
Newer
Older
Argyrios Kyrtzidis
committed
//== ObjCSelfInitChecker.cpp - Checker for 'self' initialization -*- C++ -*--=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This defines ObjCSelfInitChecker, a builtin check that checks for uses of
// 'self' before proper initialization.
//
//===----------------------------------------------------------------------===//
// This checks initialization methods to verify that they assign 'self' to the
// result of an initialization call (e.g. [super init], or [self initWith..])
// before using 'self' or any instance variable.
//
// To perform the required checking, values are tagged with flags that indicate
Argyrios Kyrtzidis
committed
// 1) if the object is the one pointed to by 'self', and 2) if the object
// is the result of an initializer (e.g. [super init]).
//
// Uses of an object that is true for 1) but not 2) trigger a diagnostic.
// The uses that are currently checked are:
// - Using instance variables.
// - Returning the object.
//
// Note that we don't check for an invalid 'self' that is the receiver of an
// obj-c message expression to cut down false positives where logging functions
// get information from self (like its class) or doing "invalidation" on self
// when the initialization fails.
//
// Because the object that 'self' points to gets invalidated when a call
// receives a reference to 'self', the checker keeps track and passes the flags
// for 1) and 2) to the new object that 'self' points to after the call.
//
//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis
committed
#include "ClangSACheckers.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek
committed
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
Ted Kremenek
committed
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidis
committed
#include "clang/AST/ParentMap.h"
using namespace clang;
using namespace ento;
static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND);
static bool isInitializationMethod(const ObjCMethodDecl *MD);
Argyrios Kyrtzidis
committed
static bool isInitMessage(const ObjCMessage &msg);
Argyrios Kyrtzidis
committed
static bool isSelfVar(SVal location, CheckerContext &C);
namespace {
class ObjCSelfInitChecker : public Checker< check::PreObjCMessage,
check::PostObjCMessage,
check::PostStmt<ObjCIvarRefExpr>,
check::PreStmt<ReturnStmt>,
check::PreStmt<CallExpr>,
check::PostStmt<CallExpr>,
check::Location > {
Argyrios Kyrtzidis
committed
public:
void checkPreObjCMessage(ObjCMessage msg, CheckerContext &C) const;
void checkPostObjCMessage(ObjCMessage msg, CheckerContext &C) const;
void checkPostStmt(const ObjCIvarRefExpr *E, CheckerContext &C) const;
void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anna Zaks
committed
void checkLocation(SVal location, bool isLoad, const Stmt *S,
CheckerContext &C) const;
void checkPreStmt(const CallOrObjCMessage &CE, CheckerContext &C) const;
void checkPostStmt(const CallOrObjCMessage &CE, CheckerContext &C) const;
Argyrios Kyrtzidis
committed
};
} // end anonymous namespace
namespace {
class InitSelfBug : public BugType {
const std::string desc;
public:
InitSelfBug() : BugType("Missing \"self = [(super or self) init...]\"",
"Core Foundation/Objective-C") {}
Argyrios Kyrtzidis
committed
};
} // end anonymous namespace
namespace {
enum SelfFlagEnum {
/// \brief No flag set.
SelfFlag_None = 0x0,
/// \brief Value came from 'self'.
SelfFlag_Self = 0x1,
/// \brief Value came from the result of an initializer (e.g. [super init]).
SelfFlag_InitRes = 0x2
};
}
Argyrios Kyrtzidis
committed
typedef llvm::ImmutableMap<SymbolRef, unsigned> SelfFlag;
Ted Kremenek
committed
namespace { struct CalledInit {}; }
namespace { struct PreCallSelfFlags {}; }
Argyrios Kyrtzidis
committed
namespace clang {
namespace ento {
template<>
Ted Kremenek
committed
struct ProgramStateTrait<SelfFlag> : public ProgramStatePartialTrait<SelfFlag> {
Ted Kremenek
committed
static void *GDMIndex() { static int index = 0; return &index; }
Argyrios Kyrtzidis
committed
};
Ted Kremenek
committed
template <>
Ted Kremenek
committed
struct ProgramStateTrait<CalledInit> : public ProgramStatePartialTrait<bool> {
Ted Kremenek
committed
static void *GDMIndex() { static int index = 0; return &index; }
};
/// \brief A call receiving a reference to 'self' invalidates the object that
/// 'self' contains. This keeps the "self flags" assigned to the 'self'
/// object before the call so we can assign them to the new object that 'self'
/// points to after the call.
template <>
Ted Kremenek
committed
struct ProgramStateTrait<PreCallSelfFlags> : public ProgramStatePartialTrait<unsigned> {
static void *GDMIndex() { static int index = 0; return &index; }
};
Argyrios Kyrtzidis
committed
}
}
static SelfFlagEnum getSelfFlags(SVal val, ProgramStateRef state) {
Argyrios Kyrtzidis
committed
if (SymbolRef sym = val.getAsSymbol())
if (const unsigned *attachedFlags = state->get<SelfFlag>(sym))
return (SelfFlagEnum)*attachedFlags;
return SelfFlag_None;
}
static SelfFlagEnum getSelfFlags(SVal val, CheckerContext &C) {
return getSelfFlags(val, C.getState());
}
static void addSelfFlag(ProgramStateRef state, SVal val,
Ted Kremenek
committed
SelfFlagEnum flag, CheckerContext &C) {
// We tag the symbol that the SVal wraps.
Argyrios Kyrtzidis
committed
if (SymbolRef sym = val.getAsSymbol())
C.addTransition(state->set<SelfFlag>(sym, getSelfFlags(val, C) | flag));
Argyrios Kyrtzidis
committed
}
static bool hasSelfFlag(SVal val, SelfFlagEnum flag, CheckerContext &C) {
return getSelfFlags(val, C) & flag;
}
/// \brief Returns true of the value of the expression is the object that 'self'
/// points to and is an object that did not come from the result of calling
/// an initializer.
static bool isInvalidSelf(const Expr *E, CheckerContext &C) {
Ted Kremenek
committed
SVal exprVal = C.getState()->getSVal(E, C.getLocationContext());
Argyrios Kyrtzidis
committed
if (!hasSelfFlag(exprVal, SelfFlag_Self, C))
return false; // value did not come from 'self'.
if (hasSelfFlag(exprVal, SelfFlag_InitRes, C))
return false; // 'self' is properly initialized.
return true;
}
static void checkForInvalidSelf(const Expr *E, CheckerContext &C,
const char *errorStr) {
if (!E)
return;
Ted Kremenek
committed
if (!C.getState()->get<CalledInit>())
return;
Argyrios Kyrtzidis
committed
if (!isInvalidSelf(E, C))
return;
Ted Kremenek
committed
Argyrios Kyrtzidis
committed
// Generate an error node.
ExplodedNode *N = C.generateSink();
if (!N)
return;
BugReport *report =
new BugReport(*new InitSelfBug(), errorStr, N);
Argyrios Kyrtzidis
committed
C.EmitReport(report);
}
void ObjCSelfInitChecker::checkPostObjCMessage(ObjCMessage msg,
CheckerContext &C) const {
CallOrObjCMessage MsgWrapper(msg, C.getState(), C.getLocationContext());
checkPostStmt(MsgWrapper, C);
Argyrios Kyrtzidis
committed
// When encountering a message that does initialization (init rule),
// tag the return value so that we know later on that if self has this value
// then it is properly initialized.
// FIXME: A callback should disable checkers at the start of functions.
if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
C.getCurrentAnalysisDeclContext()->getDecl())))
Argyrios Kyrtzidis
committed
return;
Argyrios Kyrtzidis
committed
if (isInitMessage(msg)) {
Argyrios Kyrtzidis
committed
// Tag the return value as the result of an initializer.
ProgramStateRef state = C.getState();
Ted Kremenek
committed
// FIXME this really should be context sensitive, where we record
// the current stack frame (for IPA). Also, we need to clean this
// value out when we return from this method.
state = state->set<CalledInit>(true);
Ted Kremenek
committed
SVal V = state->getSVal(msg.getMessageExpr(), C.getLocationContext());
Ted Kremenek
committed
addSelfFlag(state, V, SelfFlag_InitRes, C);
Argyrios Kyrtzidis
committed
return;
}
// We don't check for an invalid 'self' in an obj-c message expression to cut
// down false positives where logging functions get information from self
// (like its class) or doing "invalidation" on self when the initialization
// fails.
}
void ObjCSelfInitChecker::checkPostStmt(const ObjCIvarRefExpr *E,
CheckerContext &C) const {
Argyrios Kyrtzidis
committed
// FIXME: A callback should disable checkers at the start of functions.
if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
C.getCurrentAnalysisDeclContext()->getDecl())))
Argyrios Kyrtzidis
committed
return;
checkForInvalidSelf(E->getBase(), C,
Argyrios Kyrtzidis
committed
"Instance variable used while 'self' is not set to the result of "
Argyrios Kyrtzidis
committed
"'[(super or self) init...]'");
Argyrios Kyrtzidis
committed
}
void ObjCSelfInitChecker::checkPreStmt(const ReturnStmt *S,
CheckerContext &C) const {
Argyrios Kyrtzidis
committed
// FIXME: A callback should disable checkers at the start of functions.
if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
C.getCurrentAnalysisDeclContext()->getDecl())))
Argyrios Kyrtzidis
committed
return;
checkForInvalidSelf(S->getRetValue(), C,
"Returning 'self' while it is not set to the result of "
Argyrios Kyrtzidis
committed
"'[(super or self) init...]'");
Argyrios Kyrtzidis
committed
}
// When a call receives a reference to 'self', [Pre/Post]VisitGenericCall pass
// the SelfFlags from the object 'self' point to before the call, to the new
// object after the call. This is to avoid invalidation of 'self' by logging
// functions.
// Another common pattern in classes with multiple initializers is to put the
// subclass's common initialization bits into a static function that receives
// the value of 'self', e.g:
// @code
// if (!(self = [super init]))
// return nil;
// if (!(self = _commonInit(self)))
// return nil;
// @endcode
// Until we can use inter-procedural analysis, in such a call, transfer the
// SelfFlags to the result of the call.
Argyrios Kyrtzidis
committed
void ObjCSelfInitChecker::checkPreStmt(const CallExpr *CE,
CheckerContext &C) const {
CallOrObjCMessage CEWrapper(CE, C.getState(), C.getLocationContext());
checkPreStmt(CEWrapper, C);
}
void ObjCSelfInitChecker::checkPostStmt(const CallExpr *CE,
CheckerContext &C) const {
CallOrObjCMessage CEWrapper(CE, C.getState(), C.getLocationContext());
checkPostStmt(CEWrapper, C);
}
void ObjCSelfInitChecker::checkPreObjCMessage(ObjCMessage Msg,
CheckerContext &C) const {
CallOrObjCMessage MsgWrapper(Msg, C.getState(), C.getLocationContext());
checkPreStmt(MsgWrapper, C);
}
void ObjCSelfInitChecker::checkPreStmt(const CallOrObjCMessage &CE,
CheckerContext &C) const {
ProgramStateRef state = C.getState();
unsigned NumArgs = CE.getNumArgs();
for (unsigned i = 0; i < NumArgs; ++i) {
SVal argV = CE.getArgSVal(i);
Argyrios Kyrtzidis
committed
if (isSelfVar(argV, C)) {
unsigned selfFlags = getSelfFlags(state->getSVal(cast<Loc>(argV)), C);
C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
Argyrios Kyrtzidis
committed
return;
} else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
unsigned selfFlags = getSelfFlags(argV, C);
C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
return;
Argyrios Kyrtzidis
committed
}
}
}
void ObjCSelfInitChecker::checkPostStmt(const CallOrObjCMessage &CE,
CheckerContext &C) const {
ProgramStateRef state = C.getState();
unsigned NumArgs = CE.getNumArgs();
for (unsigned i = 0; i < NumArgs; ++i) {
SVal argV = CE.getArgSVal(i);
Argyrios Kyrtzidis
committed
if (isSelfVar(argV, C)) {
SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>();
state = state->remove<PreCallSelfFlags>();
addSelfFlag(state, state->getSVal(cast<Loc>(argV)), prevFlags, C);
Argyrios Kyrtzidis
committed
return;
} else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>();
state = state->remove<PreCallSelfFlags>();
addSelfFlag(state, state->getSVal(cast<Loc>(argV)), prevFlags, C);
return;
Argyrios Kyrtzidis
committed
}
}
}
void ObjCSelfInitChecker::checkLocation(SVal location, bool isLoad,
Anna Zaks
committed
const Stmt *S,
CheckerContext &C) const {
Argyrios Kyrtzidis
committed
// Tag the result of a load from 'self' so that we can easily know that the
// value is the object that 'self' points to.
ProgramStateRef state = C.getState();
Argyrios Kyrtzidis
committed
if (isSelfVar(location, C))
Ted Kremenek
committed
addSelfFlag(state, state->getSVal(cast<Loc>(location)), SelfFlag_Self, C);
Argyrios Kyrtzidis
committed
}
// FIXME: A callback should disable checkers at the start of functions.
static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND) {
if (!ND)
return false;
const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND);
if (!MD)
return false;
if (!isInitializationMethod(MD))
return false;
Argyrios Kyrtzidis
committed
// self = [super init] applies only to NSObject subclasses.
// For instance, NSProxy doesn't implement -init.
Ted Kremenek
committed
ASTContext &Ctx = MD->getASTContext();
Argyrios Kyrtzidis
committed
IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
Ted Kremenek
committed
ObjCInterfaceDecl *ID = MD->getClassInterface()->getSuperClass();
Argyrios Kyrtzidis
committed
for ( ; ID ; ID = ID->getSuperClass()) {
IdentifierInfo *II = ID->getIdentifier();
if (II == NSObjectII)
break;
}
if (!ID)
return false;
Argyrios Kyrtzidis
committed
return true;
}
/// \brief Returns true if the location is 'self'.
static bool isSelfVar(SVal location, CheckerContext &C) {
AnalysisDeclContext *analCtx = C.getCurrentAnalysisDeclContext();
Argyrios Kyrtzidis
committed
if (!analCtx->getSelfDecl())
return false;
if (!isa<loc::MemRegionVal>(location))
return false;
loc::MemRegionVal MRV = cast<loc::MemRegionVal>(location);
if (const DeclRegion *DR = dyn_cast<DeclRegion>(MRV.getRegion()))
return (DR->getDecl() == analCtx->getSelfDecl());
return false;
}
static bool isInitializationMethod(const ObjCMethodDecl *MD) {
return MD->getMethodFamily() == OMF_init;
Argyrios Kyrtzidis
committed
}
Argyrios Kyrtzidis
committed
static bool isInitMessage(const ObjCMessage &msg) {
return msg.getMethodFamily() == OMF_init;
Argyrios Kyrtzidis
committed
}
//===----------------------------------------------------------------------===//
// Registration.
//===----------------------------------------------------------------------===//
void ento::registerObjCSelfInitChecker(CheckerManager &mgr) {
mgr.registerChecker<ObjCSelfInitChecker>();
}