#include "clang/AST/ParentMap.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/Builtins.h"
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
using namespace clang;
using namespace ento;
REGISTER_MAP_WITH_PROGRAMSTATE(MostSpecializedTypeArgsMap, SymbolRef,
const ObjCObjectPointerType *)
namespace {
class DynamicTypePropagation:
public Checker< check::PreCall,
check::PostCall,
check::DeadSymbols,
check::PostStmt<CastExpr>,
check::PostStmt<CXXNewExpr>,
check::PreObjCMessage,
check::PostObjCMessage > {
const ObjCObjectPointerType *getBetterObjCType(const Expr *CastE,
CheckerContext &C) const;
ExplodedNode *dynamicTypePropagationOnCasts(const CastExpr *CE,
ProgramStateRef &State,
CheckerContext &C) const;
mutable std::unique_ptr<BugType> ObjCGenericsBugType;
void initBugType() const {
if (!ObjCGenericsBugType)
ObjCGenericsBugType.reset(new BugType(
GenericCheckName, "Generics", categories::CoreFoundationObjectiveC));
}
class GenericsBugVisitor : public BugReporterVisitor {
public:
GenericsBugVisitor(SymbolRef S) : Sym(S) {}
void Profile(llvm::FoldingSetNodeID &ID) const override {
static int X = 0;
ID.AddPointer(&X);
ID.AddPointer(Sym);
}
PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
BugReporterContext &BRC,
PathSensitiveBugReport &BR) override;
private:
SymbolRef Sym;
};
void reportGenericsBug(const ObjCObjectPointerType *From,
const ObjCObjectPointerType *To, ExplodedNode *N,
SymbolRef Sym, CheckerContext &C,
const Stmt *ReportedNode = nullptr) const;
public:
void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
void checkPostStmt(const CastExpr *CastE, CheckerContext &C) const;
void checkPostStmt(const CXXNewExpr *NewE, CheckerContext &C) const;
void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
void checkPreObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
bool CheckGenerics = false;
CheckerNameRef GenericCheckName;
};
bool isObjCClassType(QualType Type) {
if (const auto *PointerType = dyn_cast<ObjCObjectPointerType>(Type)) {
return PointerType->getObjectType()->isObjCClass();
}
return false;
}
struct RuntimeType {
const ObjCObjectType *Type = nullptr;
bool Precise = false;
operator bool() const { return Type != nullptr; }
};
RuntimeType inferReceiverType(const ObjCMethodCall &Message,
CheckerContext &C) {
const ObjCMessageExpr *MessageExpr = Message.getOriginExpr();
if (MessageExpr->getReceiverKind() == ObjCMessageExpr::Class) {
return {MessageExpr->getClassReceiver()->getAs<ObjCObjectType>(),
true};
}
if (MessageExpr->getReceiverKind() == ObjCMessageExpr::SuperClass) {
return {MessageExpr->getSuperType()->getAs<ObjCObjectType>(),
true};
}
if (MessageExpr->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
if (const auto *ObjTy =
MessageExpr->getSuperType()->getAs<ObjCObjectPointerType>())
return {ObjTy->getObjectType(), true};
}
const Expr *RecE = MessageExpr->getInstanceReceiver();
if (!RecE)
return {};
QualType InferredType;
SVal ReceiverSVal = C.getSVal(RecE);
ProgramStateRef State = C.getState();
if (const MemRegion *ReceiverRegion = ReceiverSVal.getAsRegion()) {
if (DynamicTypeInfo DTI = getDynamicTypeInfo(State, ReceiverRegion)) {
InferredType = DTI.getType().getCanonicalType();
}
}
if (SymbolRef ReceiverSymbol = ReceiverSVal.getAsSymbol()) {
if (InferredType.isNull()) {
InferredType = ReceiverSymbol->getType();
}
if (isObjCClassType(InferredType)) {
if (DynamicTypeInfo DTI =
getClassObjectDynamicTypeInfo(State, ReceiverSymbol)) {
return {cast<ObjCObjectType>(DTI.getType()), !DTI.canBeASubClass()};
}
SVal SelfSVal = State->getSelfSVal(C.getLocationContext());
if (ReceiverSVal == SelfSVal) {
if (const ObjCMethodDecl *MD =
dyn_cast<ObjCMethodDecl>(C.getStackFrame()->getDecl()))
if (const ObjCObjectType *ObjTy = dyn_cast<ObjCObjectType>(
MD->getClassInterface()->getTypeForDecl()))
return {ObjTy};
}
}
}
if (InferredType.isNull()) {
return {};
}
if (const auto *ReceiverInferredType =
dyn_cast<ObjCObjectPointerType>(InferredType)) {
return {ReceiverInferredType->getObjectType()};
}
return {};
}
}
void DynamicTypePropagation::checkDeadSymbols(SymbolReaper &SR,
CheckerContext &C) const {
ProgramStateRef State = removeDeadTypes(C.getState(), SR);
State = removeDeadClassObjectTypes(State, SR);
MostSpecializedTypeArgsMapTy TyArgMap =
State->get<MostSpecializedTypeArgsMap>();
for (MostSpecializedTypeArgsMapTy::iterator I = TyArgMap.begin(),
E = TyArgMap.end();
I != E; ++I) {
if (SR.isDead(I->first)) {
State = State->remove<MostSpecializedTypeArgsMap>(I->first);
}
}
C.addTransition(State);
}
static void recordFixedType(const MemRegion *Region, const CXXMethodDecl *MD,
CheckerContext &C) {
assert(Region);
assert(MD);
ASTContext &Ctx = C.getASTContext();
QualType Ty = Ctx.getPointerType(Ctx.getRecordType(MD->getParent()));
ProgramStateRef State = C.getState();
State = setDynamicTypeInfo(State, Region, Ty, false);
C.addTransition(State);
}
void DynamicTypePropagation::checkPreCall(const CallEvent &Call,
CheckerContext &C) const {
if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(&Call)) {
switch (Ctor->getOriginExpr()->getConstructionKind()) {
case CXXConstructExpr::CK_Complete:
case CXXConstructExpr::CK_Delegating:
return;
case CXXConstructExpr::CK_NonVirtualBase:
case CXXConstructExpr::CK_VirtualBase:
if (const MemRegion *Target = Ctor->getCXXThisVal().getAsRegion())
recordFixedType(Target, Ctor->getDecl(), C);
return;
}
return;
}
if (const CXXDestructorCall *Dtor = dyn_cast<CXXDestructorCall>(&Call)) {
if (!Dtor->isBaseDestructor())
return;
const MemRegion *Target = Dtor->getCXXThisVal().getAsRegion();
if (!Target)
return;
const Decl *D = Dtor->getDecl();
if (!D)
return;
recordFixedType(Target, cast<CXXDestructorDecl>(D), C);
return;
}
}
void DynamicTypePropagation::checkPostCall(const CallEvent &Call,
CheckerContext &C) const {
if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(&Call)) {
const MemRegion *RetReg = Call.getReturnValue().getAsRegion();
if (!RetReg)
return;
ProgramStateRef State = C.getState();
const ObjCMethodDecl *D = Msg->getDecl();
if (D && D->hasRelatedResultType()) {
switch (Msg->getMethodFamily()) {
default:
break;
case OMF_alloc:
case OMF_new: {
RuntimeType ObjTy = inferReceiverType(*Msg, C);
if (!ObjTy)
return;
QualType DynResTy =
C.getASTContext().getObjCObjectPointerType(QualType(ObjTy.Type, 0));
C.addTransition(setDynamicTypeInfo(State, RetReg, DynResTy, false));
break;
}
case OMF_init: {
const MemRegion *RecReg = Msg->getReceiverSVal().getAsRegion();
if (!RecReg)
return;
DynamicTypeInfo RecDynType = getDynamicTypeInfo(State, RecReg);
C.addTransition(setDynamicTypeInfo(State, RetReg, RecDynType));
break;
}
}
}
return;
}
if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(&Call)) {
switch (Ctor->getOriginExpr()->getConstructionKind()) {
case CXXConstructExpr::CK_Complete:
case CXXConstructExpr::CK_Delegating:
return;
case CXXConstructExpr::CK_NonVirtualBase:
case CXXConstructExpr::CK_VirtualBase:
if (const MemRegion *Target = Ctor->getCXXThisVal().getAsRegion()) {
const LocationContext *LCtx = C.getLocationContext();
if (isa_and_nonnull<InitListExpr>(
LCtx->getParentMap().getParent(Ctor->getOriginExpr())))
return;
recordFixedType(Target, cast<CXXConstructorDecl>(LCtx->getDecl()), C);
}
return;
}
}
}
ExplodedNode *DynamicTypePropagation::dynamicTypePropagationOnCasts(
const CastExpr *CE, ProgramStateRef &State, CheckerContext &C) const {
const MemRegion *ToR = C.getSVal(CE).getAsRegion();
if (!ToR)
return C.getPredecessor();
if (isa<ExplicitCastExpr>(CE))
return C.getPredecessor();
if (const Type *NewTy = getBetterObjCType(CE, C)) {
State = setDynamicTypeInfo(State, ToR, QualType(NewTy, 0));
return C.addTransition(State);
}
return C.getPredecessor();
}
void DynamicTypePropagation::checkPostStmt(const CXXNewExpr *NewE,
CheckerContext &C) const {
if (NewE->isArray())
return;
const MemRegion *MR = C.getSVal(NewE).getAsRegion();
if (!MR)
return;
C.addTransition(setDynamicTypeInfo(C.getState(), MR, NewE->getType(),
false));
}
const ObjCObjectPointerType *
DynamicTypePropagation::getBetterObjCType(const Expr *CastE,
CheckerContext &C) const {
const MemRegion *ToR = C.getSVal(CastE).getAsRegion();
assert(ToR);
const ObjCObjectPointerType *NewTy =
CastE->getType()->getAs<ObjCObjectPointerType>();
if (!NewTy)
return nullptr;
QualType OldDTy = getDynamicTypeInfo(C.getState(), ToR).getType();
if (OldDTy.isNull()) {
return NewTy;
}
const ObjCObjectPointerType *OldTy =
OldDTy->getAs<ObjCObjectPointerType>();
if (!OldTy)
return nullptr;
if (OldTy->isObjCIdType() && !NewTy->isObjCIdType())
return NewTy;
const ObjCInterfaceDecl *ToI = NewTy->getInterfaceDecl();
const ObjCInterfaceDecl *FromI = OldTy->getInterfaceDecl();
if (ToI && FromI && FromI->isSuperClassOf(ToI))
return NewTy;
return nullptr;
}
static const ObjCObjectPointerType *getMostInformativeDerivedClassImpl(
const ObjCObjectPointerType *From, const ObjCObjectPointerType *To,
const ObjCObjectPointerType *MostInformativeCandidate, ASTContext &C) {
if (From->getInterfaceDecl()->getCanonicalDecl() ==
To->getInterfaceDecl()->getCanonicalDecl()) {
if (To->isSpecialized()) {
assert(MostInformativeCandidate->isSpecialized());
return MostInformativeCandidate;
}
return From;
}
if (To->getObjectType()->getSuperClassType().isNull()) {
return From;
}
const auto *SuperOfTo =
To->getObjectType()->getSuperClassType()->castAs<ObjCObjectType>();
assert(SuperOfTo);
QualType SuperPtrOfToQual =
C.getObjCObjectPointerType(QualType(SuperOfTo, 0));
const auto *SuperPtrOfTo = SuperPtrOfToQual->castAs<ObjCObjectPointerType>();
if (To->isUnspecialized())
return getMostInformativeDerivedClassImpl(From, SuperPtrOfTo, SuperPtrOfTo,
C);
else
return getMostInformativeDerivedClassImpl(From, SuperPtrOfTo,
MostInformativeCandidate, C);
}
static const ObjCObjectPointerType *
getMostInformativeDerivedClass(const ObjCObjectPointerType *From,
const ObjCObjectPointerType *To, ASTContext &C) {
return getMostInformativeDerivedClassImpl(From, To, To, C);
}
static bool
storeWhenMoreInformative(ProgramStateRef &State, SymbolRef Sym,
const ObjCObjectPointerType *const *Current,
const ObjCObjectPointerType *StaticLowerBound,
const ObjCObjectPointerType *StaticUpperBound,
ASTContext &C) {
assert(StaticUpperBound->isSpecialized() ||
StaticLowerBound->isSpecialized());
assert(!Current || (*Current)->isSpecialized());
if (!Current) {
if (StaticUpperBound->isUnspecialized()) {
State = State->set<MostSpecializedTypeArgsMap>(Sym, StaticLowerBound);
return true;
}
const ObjCObjectPointerType *WithMostInfo =
getMostInformativeDerivedClass(StaticUpperBound, StaticLowerBound, C);
State = State->set<MostSpecializedTypeArgsMap>(Sym, WithMostInfo);
return true;
}
if (C.canAssignObjCInterfaces(StaticLowerBound, *Current)) {
return false;
}
if (C.canAssignObjCInterfaces(*Current, StaticUpperBound)) {
const ObjCObjectPointerType *WithMostInfo =
getMostInformativeDerivedClass(*Current, StaticUpperBound, C);
WithMostInfo =
getMostInformativeDerivedClass(WithMostInfo, StaticLowerBound, C);
if (WithMostInfo == *Current)
return false;
State = State->set<MostSpecializedTypeArgsMap>(Sym, WithMostInfo);
return true;
}
const ObjCObjectPointerType *WithMostInfo =
getMostInformativeDerivedClass(*Current, StaticLowerBound, C);
if (WithMostInfo != *Current) {
State = State->set<MostSpecializedTypeArgsMap>(Sym, WithMostInfo);
return true;
}
return false;
}
void DynamicTypePropagation::checkPostStmt(const CastExpr *CE,
CheckerContext &C) const {
if (CE->getCastKind() != CK_BitCast)
return;
QualType OriginType = CE->getSubExpr()->getType();
QualType DestType = CE->getType();
const auto *OrigObjectPtrType = OriginType->getAs<ObjCObjectPointerType>();
const auto *DestObjectPtrType = DestType->getAs<ObjCObjectPointerType>();
if (!OrigObjectPtrType || !DestObjectPtrType)
return;
ProgramStateRef State = C.getState();
ExplodedNode *AfterTypeProp = dynamicTypePropagationOnCasts(CE, State, C);
ASTContext &ASTCtxt = C.getASTContext();
OrigObjectPtrType = OrigObjectPtrType->stripObjCKindOfTypeAndQuals(ASTCtxt);
DestObjectPtrType = DestObjectPtrType->stripObjCKindOfTypeAndQuals(ASTCtxt);
if (OrigObjectPtrType->isUnspecialized() &&
DestObjectPtrType->isUnspecialized())
return;
SymbolRef Sym = C.getSVal(CE).getAsSymbol();
if (!Sym)
return;
const ObjCObjectPointerType *const *TrackedType =
State->get<MostSpecializedTypeArgsMap>(Sym);
if (isa<ExplicitCastExpr>(CE)) {
if (TrackedType) {
State = State->remove<MostSpecializedTypeArgsMap>(Sym);
C.addTransition(State, AfterTypeProp);
}
return;
}
bool OrigToDest =
ASTCtxt.canAssignObjCInterfaces(DestObjectPtrType, OrigObjectPtrType);
bool DestToOrig =
ASTCtxt.canAssignObjCInterfaces(OrigObjectPtrType, DestObjectPtrType);
if (TrackedType &&
!ASTCtxt.canAssignObjCInterfaces(DestObjectPtrType, *TrackedType) &&
!ASTCtxt.canAssignObjCInterfaces(*TrackedType, DestObjectPtrType)) {
static CheckerProgramPointTag IllegalConv(this, "IllegalConversion");
ExplodedNode *N = C.addTransition(State, AfterTypeProp, &IllegalConv);
reportGenericsBug(*TrackedType, DestObjectPtrType, N, Sym, C);
return;
}
const ObjCObjectPointerType *LowerBound = DestObjectPtrType;
const ObjCObjectPointerType *UpperBound = OrigObjectPtrType;
if (OrigToDest && !DestToOrig)
std::swap(LowerBound, UpperBound);
LowerBound = LowerBound->isObjCIdType() ? UpperBound : LowerBound;
UpperBound = UpperBound->isObjCIdType() ? LowerBound : UpperBound;
if (storeWhenMoreInformative(State, Sym, TrackedType, LowerBound, UpperBound,
ASTCtxt)) {
C.addTransition(State, AfterTypeProp);
}
}
static const Expr *stripCastsAndSugar(const Expr *E) {
E = E->IgnoreParenImpCasts();
if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
E = POE->getSyntacticForm()->IgnoreParenImpCasts();
if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
E = OVE->getSourceExpr()->IgnoreParenImpCasts();
return E;
}
static bool isObjCTypeParamDependent(QualType Type) {
class IsObjCTypeParamDependentTypeVisitor
: public RecursiveASTVisitor<IsObjCTypeParamDependentTypeVisitor> {
public:
IsObjCTypeParamDependentTypeVisitor() : Result(false) {}
bool VisitObjCTypeParamType(const ObjCTypeParamType *Type) {
if (isa<ObjCTypeParamDecl>(Type->getDecl())) {
Result = true;
return false;
}
return true;
}
bool Result;
};
IsObjCTypeParamDependentTypeVisitor Visitor;
Visitor.TraverseType(Type);
return Visitor.Result;
}
static const ObjCMethodDecl *
findMethodDecl(const ObjCMessageExpr *MessageExpr,
const ObjCObjectPointerType *TrackedType, ASTContext &ASTCtxt) {
const ObjCMethodDecl *Method = nullptr;
QualType ReceiverType = MessageExpr->getReceiverType();
const auto *ReceiverObjectPtrType =
ReceiverType->getAs<ObjCObjectPointerType>();
if (MessageExpr->getReceiverKind() == ObjCMessageExpr::Instance ||
MessageExpr->getReceiverKind() == ObjCMessageExpr::Class) {
if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType() ||
ASTCtxt.canAssignObjCInterfaces(ReceiverObjectPtrType, TrackedType)) {
const ObjCInterfaceDecl *InterfaceDecl = TrackedType->getInterfaceDecl();
Selector Sel = MessageExpr->getSelector();
Method = InterfaceDecl->lookupInstanceMethod(Sel);
if (!Method)
Method = InterfaceDecl->lookupClassMethod(Sel);
}
}
return Method ? Method : MessageExpr->getMethodDecl();
}
static QualType getReturnTypeForMethod(
const ObjCMethodDecl *Method, ArrayRef<QualType> TypeArgs,
const ObjCObjectPointerType *SelfType, ASTContext &C) {
QualType StaticResultType = Method->getReturnType();
if (StaticResultType == C.getObjCInstanceType())
return QualType(SelfType, 0);
if (!isObjCTypeParamDependent(StaticResultType))
return QualType();
QualType ResultType = StaticResultType.substObjCTypeArgs(
C, TypeArgs, ObjCSubstitutionContext::Result);
return ResultType;
}
void DynamicTypePropagation::checkPreObjCMessage(const ObjCMethodCall &M,
CheckerContext &C) const {
ProgramStateRef State = C.getState();
SymbolRef Sym = M.getReceiverSVal().getAsSymbol();
if (!Sym)
return;
const ObjCObjectPointerType *const *TrackedType =
State->get<MostSpecializedTypeArgsMap>(Sym);
if (!TrackedType)
return;
ASTContext &ASTCtxt = C.getASTContext();
const ObjCMessageExpr *MessageExpr = M.getOriginExpr();
const ObjCMethodDecl *Method =
findMethodDecl(MessageExpr, *TrackedType, ASTCtxt);
if (!Method)
return;
const ObjCInterfaceDecl *Interface = Method->getClassInterface();
if (!Interface)
return;
ObjCTypeParamList *TypeParams = Interface->getTypeParamList();
if (!TypeParams)
return;
for (ObjCTypeParamDecl *TypeParam : *TypeParams) {
if (TypeParam->getVariance() != ObjCTypeParamVariance::Invariant)
return;
}
Optional<ArrayRef<QualType>> TypeArgs =
(*TrackedType)->getObjCSubstitutions(Method->getDeclContext());
if (!TypeArgs)
return;
for (unsigned i = 0; i < Method->param_size(); i++) {
const Expr *Arg = MessageExpr->getArg(i);
const ParmVarDecl *Param = Method->parameters()[i];
QualType OrigParamType = Param->getType();
if (!isObjCTypeParamDependent(OrigParamType))
continue;
QualType ParamType = OrigParamType.substObjCTypeArgs(
ASTCtxt, *TypeArgs, ObjCSubstitutionContext::Parameter);
const auto *ParamObjectPtrType = ParamType->getAs<ObjCObjectPointerType>();
const auto *ArgObjectPtrType =
stripCastsAndSugar(Arg)->getType()->getAs<ObjCObjectPointerType>();
if (!ParamObjectPtrType || !ArgObjectPtrType)
continue;
SVal ArgSVal = M.getArgSVal(i);
SymbolRef ArgSym = ArgSVal.getAsSymbol();
if (ArgSym) {
const ObjCObjectPointerType *const *TrackedArgType =
State->get<MostSpecializedTypeArgsMap>(ArgSym);
if (TrackedArgType &&
ASTCtxt.canAssignObjCInterfaces(ArgObjectPtrType, *TrackedArgType)) {
ArgObjectPtrType = *TrackedArgType;
}
}
if (!ASTCtxt.canAssignObjCInterfaces(ParamObjectPtrType,
ArgObjectPtrType)) {
static CheckerProgramPointTag Tag(this, "ArgTypeMismatch");
ExplodedNode *N = C.addTransition(State, &Tag);
reportGenericsBug(ArgObjectPtrType, ParamObjectPtrType, N, Sym, C, Arg);
return;
}
}
}
void DynamicTypePropagation::checkPostObjCMessage(const ObjCMethodCall &M,
CheckerContext &C) const {
const ObjCMessageExpr *MessageExpr = M.getOriginExpr();
SymbolRef RetSym = M.getReturnValue().getAsSymbol();
if (!RetSym)
return;
Selector Sel = MessageExpr->getSelector();
ProgramStateRef State = C.getState();
if (Sel.getAsString() == "class") {
if (RuntimeType ReceiverRuntimeType = inferReceiverType(M, C)) {
ReceiverRuntimeType.Type->getSuperClassType();
QualType ReceiverClassType(ReceiverRuntimeType.Type, 0);
if (ReceiverRuntimeType.Type->isSpecialized() &&
ReceiverRuntimeType.Precise) {
QualType ReceiverClassPointerType =
C.getASTContext().getObjCObjectPointerType(ReceiverClassType);
const auto *InferredType =
ReceiverClassPointerType->castAs<ObjCObjectPointerType>();
State = State->set<MostSpecializedTypeArgsMap>(RetSym, InferredType);
}
State = setClassObjectDynamicTypeInfo(State, RetSym, ReceiverClassType,
!ReceiverRuntimeType.Precise);
C.addTransition(State);
return;
}
}
if (Sel.getAsString() == "superclass") {
if (RuntimeType ReceiverRuntimeType = inferReceiverType(M, C)) {
QualType ReceiversSuperClass =
ReceiverRuntimeType.Type->getSuperClassType();
if (!ReceiversSuperClass.isNull()) {
State = setClassObjectDynamicTypeInfo(
State, RetSym, ReceiversSuperClass, !ReceiverRuntimeType.Precise);
C.addTransition(State);
}
return;
}
}
SymbolRef RecSym = M.getReceiverSVal().getAsSymbol();
if (!RecSym)
return;
const ObjCObjectPointerType *const *TrackedType =
State->get<MostSpecializedTypeArgsMap>(RecSym);
if (!TrackedType)
return;
ASTContext &ASTCtxt = C.getASTContext();
const ObjCMethodDecl *Method =
findMethodDecl(MessageExpr, *TrackedType, ASTCtxt);
if (!Method)
return;
Optional<ArrayRef<QualType>> TypeArgs =
(*TrackedType)->getObjCSubstitutions(Method->getDeclContext());
if (!TypeArgs)
return;
QualType ResultType =
getReturnTypeForMethod(Method, *TypeArgs, *TrackedType, ASTCtxt);
if (ResultType.isNull())
return;
const MemRegion *RetRegion = M.getReturnValue().getAsRegion();
ExplodedNode *Pred = C.getPredecessor();
if (RetRegion && !getRawDynamicTypeInfo(State, RetRegion)) {
State = setDynamicTypeInfo(State, RetRegion, ResultType,
true);
Pred = C.addTransition(State);
}
const auto *ResultPtrType = ResultType->getAs<ObjCObjectPointerType>();
if (!ResultPtrType || ResultPtrType->isUnspecialized())
return;
if (!State->get<MostSpecializedTypeArgsMap>(RetSym)) {
State = State->set<MostSpecializedTypeArgsMap>(RetSym, ResultPtrType);
C.addTransition(State, Pred);
}
}
void DynamicTypePropagation::reportGenericsBug(
const ObjCObjectPointerType *From, const ObjCObjectPointerType *To,
ExplodedNode *N, SymbolRef Sym, CheckerContext &C,
const Stmt *ReportedNode) const {
if (!CheckGenerics)
return;
initBugType();
SmallString<192> Buf;
llvm::raw_svector_ostream OS(Buf);
OS << "Conversion from value of type '";
QualType::print(From, Qualifiers(), OS, C.getLangOpts(), llvm::Twine());
OS << "' to incompatible type '";
QualType::print(To, Qualifiers(), OS, C.getLangOpts(), llvm::Twine());
OS << "'";
auto R = std::make_unique<PathSensitiveBugReport>(*ObjCGenericsBugType,
OS.str(), N);
R->markInteresting(Sym);
R->addVisitor(std::make_unique<GenericsBugVisitor>(Sym));
if (ReportedNode)
R->addRange(ReportedNode->getSourceRange());
C.emitReport(std::move(R));
}
PathDiagnosticPieceRef DynamicTypePropagation::GenericsBugVisitor::VisitNode(
const ExplodedNode *N, BugReporterContext &BRC,
PathSensitiveBugReport &BR) {
ProgramStateRef state = N->getState();
ProgramStateRef statePrev = N->getFirstPred()->getState();
const ObjCObjectPointerType *const *TrackedType =
state->get<MostSpecializedTypeArgsMap>(Sym);
const ObjCObjectPointerType *const *TrackedTypePrev =
statePrev->get<MostSpecializedTypeArgsMap>(Sym);
if (!TrackedType)
return nullptr;
if (TrackedTypePrev && *TrackedTypePrev == *TrackedType)
return nullptr;
const Stmt *S = N->getStmtForDiagnostics();
if (!S)
return nullptr;
const LangOptions &LangOpts = BRC.getASTContext().getLangOpts();
SmallString<256> Buf;
llvm::raw_svector_ostream OS(Buf);
OS << "Type '";
QualType::print(*TrackedType, Qualifiers(), OS, LangOpts, llvm::Twine());
OS << "' is inferred from ";
if (const auto *ExplicitCast = dyn_cast<ExplicitCastExpr>(S)) {
OS << "explicit cast (from '";
QualType::print(ExplicitCast->getSubExpr()->getType().getTypePtr(),
Qualifiers(), OS, LangOpts, llvm::Twine());
OS << "' to '";
QualType::print(ExplicitCast->getType().getTypePtr(), Qualifiers(), OS,
LangOpts, llvm::Twine());
OS << "')";
} else if (const auto *ImplicitCast = dyn_cast<ImplicitCastExpr>(S)) {
OS << "implicit cast (from '";
QualType::print(ImplicitCast->getSubExpr()->getType().getTypePtr(),
Qualifiers(), OS, LangOpts, llvm::Twine());
OS << "' to '";
QualType::print(ImplicitCast->getType().getTypePtr(), Qualifiers(), OS,
LangOpts, llvm::Twine());
OS << "')";
} else {
OS << "this context";
}
PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
N->getLocationContext());
return std::make_shared<PathDiagnosticEventPiece>(Pos, OS.str(), true);
}
void ento::registerObjCGenericsChecker(CheckerManager &mgr) {
DynamicTypePropagation *checker = mgr.getChecker<DynamicTypePropagation>();
checker->CheckGenerics = true;
checker->GenericCheckName = mgr.getCurrentCheckerName();
}
bool ento::shouldRegisterObjCGenericsChecker(const CheckerManager &mgr) {
return true;
}
void ento::registerDynamicTypePropagation(CheckerManager &mgr) {
mgr.registerChecker<DynamicTypePropagation>();
}
bool ento::shouldRegisterDynamicTypePropagation(const CheckerManager &mgr) {
return true;
}