#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
#include "clang/Analysis/RetainSummaryManager.h"
#include "clang/AST/Attr.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/ParentMap.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
using namespace clang;
using namespace ento;
template <class T>
constexpr static bool isOneOf() {
return false;
}
template <class T, class P, class... ToCompare>
constexpr static bool isOneOf() {
return std::is_same<T, P>::value || isOneOf<T, ToCompare...>();
}
namespace {
struct GeneralizedReturnsRetainedAttr {
static bool classof(const Attr *A) {
if (auto AA = dyn_cast<AnnotateAttr>(A))
return AA->getAnnotation() == "rc_ownership_returns_retained";
return false;
}
};
struct GeneralizedReturnsNotRetainedAttr {
static bool classof(const Attr *A) {
if (auto AA = dyn_cast<AnnotateAttr>(A))
return AA->getAnnotation() == "rc_ownership_returns_not_retained";
return false;
}
};
struct GeneralizedConsumedAttr {
static bool classof(const Attr *A) {
if (auto AA = dyn_cast<AnnotateAttr>(A))
return AA->getAnnotation() == "rc_ownership_consumed";
return false;
}
};
}
template <class T>
Optional<ObjKind> RetainSummaryManager::hasAnyEnabledAttrOf(const Decl *D,
QualType QT) {
ObjKind K;
if (isOneOf<T, CFConsumedAttr, CFReturnsRetainedAttr,
CFReturnsNotRetainedAttr>()) {
if (!TrackObjCAndCFObjects)
return None;
K = ObjKind::CF;
} else if (isOneOf<T, NSConsumedAttr, NSConsumesSelfAttr,
NSReturnsAutoreleasedAttr, NSReturnsRetainedAttr,
NSReturnsNotRetainedAttr, NSConsumesSelfAttr>()) {
if (!TrackObjCAndCFObjects)
return None;
if (isOneOf<T, NSReturnsRetainedAttr, NSReturnsAutoreleasedAttr,
NSReturnsNotRetainedAttr>() &&
!cocoa::isCocoaObjectRef(QT))
return None;
K = ObjKind::ObjC;
} else if (isOneOf<T, OSConsumedAttr, OSConsumesThisAttr,
OSReturnsNotRetainedAttr, OSReturnsRetainedAttr,
OSReturnsRetainedOnZeroAttr,
OSReturnsRetainedOnNonZeroAttr>()) {
if (!TrackOSObjects)
return None;
K = ObjKind::OS;
} else if (isOneOf<T, GeneralizedReturnsNotRetainedAttr,
GeneralizedReturnsRetainedAttr,
GeneralizedConsumedAttr>()) {
K = ObjKind::Generalized;
} else {
llvm_unreachable("Unexpected attribute");
}
if (D->hasAttr<T>())
return K;
return None;
}
template <class T1, class T2, class... Others>
Optional<ObjKind> RetainSummaryManager::hasAnyEnabledAttrOf(const Decl *D,
QualType QT) {
if (auto Out = hasAnyEnabledAttrOf<T1>(D, QT))
return Out;
return hasAnyEnabledAttrOf<T2, Others...>(D, QT);
}
const RetainSummary *
RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
if (OldSumm.isSimple()) {
::llvm::FoldingSetNodeID ID;
OldSumm.Profile(ID);
void *Pos;
CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
if (!N) {
N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
new (N) CachedSummaryNode(OldSumm);
SimpleSummaries.InsertNode(N, Pos);
}
return &N->getValue();
}
RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
new (Summ) RetainSummary(OldSumm);
return Summ;
}
static bool isSubclass(const Decl *D,
StringRef ClassName) {
using namespace ast_matchers;
DeclarationMatcher SubclassM =
cxxRecordDecl(isSameOrDerivedFrom(std::string(ClassName)));
return !(match(SubclassM, *D, D->getASTContext()).empty());
}
static bool isExactClass(const Decl *D, StringRef ClassName) {
using namespace ast_matchers;
DeclarationMatcher sameClassM =
cxxRecordDecl(hasName(std::string(ClassName)));
return !(match(sameClassM, *D, D->getASTContext()).empty());
}
static bool isOSObjectSubclass(const Decl *D) {
return D && isSubclass(D, "OSMetaClassBase") &&
!isExactClass(D, "OSMetaClass");
}
static bool isOSObjectDynamicCast(StringRef S) { return S == "safeMetaCast"; }
static bool isOSObjectRequiredCast(StringRef S) {
return S == "requiredMetaCast";
}
static bool isOSObjectThisCast(StringRef S) {
return S == "metaCast";
}
static bool isOSObjectPtr(QualType QT) {
return isOSObjectSubclass(QT->getPointeeCXXRecordDecl());
}
static bool isISLObjectRef(QualType Ty) {
return StringRef(Ty.getAsString()).startswith("isl_");
}
static bool isOSIteratorSubclass(const Decl *D) {
return isSubclass(D, "OSIterator");
}
static bool hasRCAnnotation(const Decl *D, StringRef rcAnnotation) {
for (const auto *Ann : D->specific_attrs<AnnotateAttr>()) {
if (Ann->getAnnotation() == rcAnnotation)
return true;
}
return false;
}
static bool isRetain(const FunctionDecl *FD, StringRef FName) {
return FName.startswith_insensitive("retain") ||
FName.endswith_insensitive("retain");
}
static bool isRelease(const FunctionDecl *FD, StringRef FName) {
return FName.startswith_insensitive("release") ||
FName.endswith_insensitive("release");
}
static bool isAutorelease(const FunctionDecl *FD, StringRef FName) {
return FName.startswith_insensitive("autorelease") ||
FName.endswith_insensitive("autorelease");
}
static bool isMakeCollectable(StringRef FName) {
return FName.contains_insensitive("MakeCollectable");
}
static bool isOSObjectRelated(const CXXMethodDecl *MD) {
if (isOSObjectSubclass(MD->getParent()))
return true;
for (ParmVarDecl *Param : MD->parameters()) {
QualType PT = Param->getType()->getPointeeType();
if (!PT.isNull())
if (CXXRecordDecl *RD = PT->getAsCXXRecordDecl())
if (isOSObjectSubclass(RD))
return true;
}
return false;
}
bool
RetainSummaryManager::isKnownSmartPointer(QualType QT) {
QT = QT.getCanonicalType();
const auto *RD = QT->getAsCXXRecordDecl();
if (!RD)
return false;
const IdentifierInfo *II = RD->getIdentifier();
if (II && II->getName() == "smart_ptr")
if (const auto *ND = dyn_cast<NamespaceDecl>(RD->getDeclContext()))
if (ND->getNameAsString() == "os")
return true;
return false;
}
const RetainSummary *
RetainSummaryManager::getSummaryForOSObject(const FunctionDecl *FD,
StringRef FName, QualType RetTy) {
assert(TrackOSObjects &&
"Requesting a summary for an OSObject but OSObjects are not tracked");
if (RetTy->isPointerType()) {
const CXXRecordDecl *PD = RetTy->getPointeeType()->getAsCXXRecordDecl();
if (PD && isOSObjectSubclass(PD)) {
if (isOSObjectDynamicCast(FName) || isOSObjectRequiredCast(FName) ||
isOSObjectThisCast(FName))
return getDefaultSummary();
if (FName.endswith("Matching")) {
return getPersistentStopSummary();
}
if ((!FName.startswith("get") && !FName.startswith("Get")) ||
isOSIteratorSubclass(PD)) {
return getOSSummaryCreateRule(FD);
} else {
return getOSSummaryGetRule(FD);
}
}
}
if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
const CXXRecordDecl *Parent = MD->getParent();
if (Parent && isOSObjectSubclass(Parent)) {
if (FName == "release" || FName == "taggedRelease")
return getOSSummaryReleaseRule(FD);
if (FName == "retain" || FName == "taggedRetain")
return getOSSummaryRetainRule(FD);
if (FName == "free")
return getOSSummaryFreeRule(FD);
if (MD->getOverloadedOperator() == OO_New)
return getOSSummaryCreateRule(MD);
}
}
return nullptr;
}
const RetainSummary *RetainSummaryManager::getSummaryForObjCOrCFObject(
const FunctionDecl *FD,
StringRef FName,
QualType RetTy,
const FunctionType *FT,
bool &AllowAnnotations) {
ArgEffects ScratchArgs(AF.getEmptyMap());
std::string RetTyName = RetTy.getAsString();
if (FName == "pthread_create" || FName == "pthread_setspecific") {
return getPersistentStopSummary();
} else if(FName == "NSMakeCollectable") {
AllowAnnotations = false;
return RetTy->isObjCIdType() ? getUnarySummary(FT, DoNothing)
: getPersistentStopSummary();
} else if (FName == "CMBufferQueueDequeueAndRetain" ||
FName == "CMBufferQueueDequeueIfDataReadyAndRetain") {
return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF),
ScratchArgs,
ArgEffect(DoNothing),
ArgEffect(DoNothing));
} else if (FName == "CFPlugInInstanceCreate") {
return getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs);
} else if (FName == "IORegistryEntrySearchCFProperty" ||
(RetTyName == "CFMutableDictionaryRef" &&
(FName == "IOBSDNameMatching" || FName == "IOServiceMatching" ||
FName == "IOServiceNameMatching" ||
FName == "IORegistryEntryIDMatching" ||
FName == "IOOpenFirmwarePathMatching"))) {
return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs,
ArgEffect(DoNothing), ArgEffect(DoNothing));
} else if (FName == "IOServiceGetMatchingService" ||
FName == "IOServiceGetMatchingServices") {
ScratchArgs = AF.add(ScratchArgs, 1, ArgEffect(DecRef, ObjKind::CF));
return getPersistentSummary(RetEffect::MakeNoRet(),
ScratchArgs,
ArgEffect(DoNothing), ArgEffect(DoNothing));
} else if (FName == "IOServiceAddNotification" ||
FName == "IOServiceAddMatchingNotification") {
ScratchArgs = AF.add(ScratchArgs, 2, ArgEffect(DecRef, ObjKind::CF));
return getPersistentSummary(RetEffect::MakeNoRet(),
ScratchArgs,
ArgEffect(DoNothing), ArgEffect(DoNothing));
} else if (FName == "CVPixelBufferCreateWithBytes") {
ScratchArgs = AF.add(ScratchArgs, 7, ArgEffect(StopTracking));
return getPersistentSummary(RetEffect::MakeNoRet(),
ScratchArgs,
ArgEffect(DoNothing), ArgEffect(DoNothing));
} else if (FName == "CGBitmapContextCreateWithData") {
ScratchArgs = AF.add(ScratchArgs, 8, ArgEffect(ArgEffect(StopTracking)));
return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs,
ArgEffect(DoNothing), ArgEffect(DoNothing));
} else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
ScratchArgs = AF.add(ScratchArgs, 12, ArgEffect(StopTracking));
return getPersistentSummary(RetEffect::MakeNoRet(),
ScratchArgs,
ArgEffect(DoNothing), ArgEffect(DoNothing));
} else if (FName == "VTCompressionSessionEncodeFrame") {
ScratchArgs = AF.add(ScratchArgs, 5, ArgEffect(StopTracking));
return getPersistentSummary(RetEffect::MakeNoRet(),
ScratchArgs,
ArgEffect(DoNothing), ArgEffect(DoNothing));
} else if (FName == "dispatch_set_context" ||
FName == "xpc_connection_set_context") {
ScratchArgs = AF.add(ScratchArgs, 1, ArgEffect(StopTracking));
return getPersistentSummary(RetEffect::MakeNoRet(),
ScratchArgs,
ArgEffect(DoNothing), ArgEffect(DoNothing));
} else if (FName.startswith("NSLog")) {
return getDoNothingSummary();
} else if (FName.startswith("NS") && FName.contains("Insert")) {
ScratchArgs = AF.add(ScratchArgs, 1, ArgEffect(StopTracking));
ScratchArgs = AF.add(ScratchArgs, 2, ArgEffect(StopTracking));
return getPersistentSummary(RetEffect::MakeNoRet(),
ScratchArgs, ArgEffect(DoNothing),
ArgEffect(DoNothing));
}
if (RetTy->isPointerType()) {
if (cocoa::isRefType(RetTy, "CF", FName)) {
if (isRetain(FD, FName)) {
AllowAnnotations = false;
return getUnarySummary(FT, IncRef);
} else if (isAutorelease(FD, FName)) {
AllowAnnotations = false;
return getUnarySummary(FT, Autorelease);
} else if (isMakeCollectable(FName)) {
AllowAnnotations = false;
return getUnarySummary(FT, DoNothing);
} else {
return getCFCreateGetRuleSummary(FD);
}
}
if (cocoa::isRefType(RetTy, "CG", FName) ||
cocoa::isRefType(RetTy, "CV", FName)) {
if (isRetain(FD, FName))
return getUnarySummary(FT, IncRef);
else
return getCFCreateGetRuleSummary(FD);
}
if (coreFoundation::isCFObjectRef(RetTy)) {
return getCFCreateGetRuleSummary(FD);
}
if (FD->hasAttr<CFAuditedTransferAttr>()) {
return getCFCreateGetRuleSummary(FD);
}
}
if (FName.startswith("CG") || FName.startswith("CF")) {
FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
if (isRelease(FD, FName))
return getUnarySummary(FT, DecRef);
else {
assert(ScratchArgs.isEmpty());
ArgEffectKind E =
(StrInStrNoCase(FName, "InsertValue") != StringRef::npos ||
StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
StrInStrNoCase(FName, "AppendValue") != StringRef::npos ||
StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
? MayEscape
: DoNothing;
return getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs,
ArgEffect(DoNothing), ArgEffect(E, ObjKind::CF));
}
}
return nullptr;
}
const RetainSummary *
RetainSummaryManager::generateSummary(const FunctionDecl *FD,
bool &AllowAnnotations) {
if (FD->isImplicit())
return getPersistentStopSummary();
const IdentifierInfo *II = FD->getIdentifier();
StringRef FName = II ? II->getName() : "";
FName = FName.substr(FName.find_first_not_of('_'));
const auto *FT = FD->getType()->castAs<FunctionType>();
QualType RetTy = FT->getReturnType();
if (TrackOSObjects)
if (const RetainSummary *S = getSummaryForOSObject(FD, FName, RetTy))
return S;
if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
if (!isOSObjectRelated(MD))
return getPersistentSummary(RetEffect::MakeNoRet(),
ArgEffects(AF.getEmptyMap()),
ArgEffect(DoNothing),
ArgEffect(StopTracking),
ArgEffect(DoNothing));
if (TrackObjCAndCFObjects)
if (const RetainSummary *S =
getSummaryForObjCOrCFObject(FD, FName, RetTy, FT, AllowAnnotations))
return S;
return getDefaultSummary();
}
const RetainSummary *
RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
if (!FD)
return getDefaultSummary();
FuncSummariesTy::iterator I = FuncSummaries.find(FD);
if (I != FuncSummaries.end())
return I->second;
bool AllowAnnotations = true;
const RetainSummary *S = generateSummary(FD, AllowAnnotations);
if (AllowAnnotations)
updateSummaryFromAnnotations(S, FD);
FuncSummaries[FD] = S;
return S;
}
static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
switch (E.getKind()) {
case DoNothing:
case Autorelease:
case DecRefBridgedTransferred:
case IncRef:
case UnretainedOutParameter:
case RetainedOutParameter:
case RetainedOutParameterOnZero:
case RetainedOutParameterOnNonZero:
case MayEscape:
case StopTracking:
case StopTrackingHard:
return E.withKind(StopTrackingHard);
case DecRef:
case DecRefAndStopTrackingHard:
return E.withKind(DecRefAndStopTrackingHard);
case Dealloc:
return E.withKind(Dealloc);
}
llvm_unreachable("Unknown ArgEffect kind");
}
const RetainSummary *
RetainSummaryManager::updateSummaryForNonZeroCallbackArg(const RetainSummary *S,
AnyCall &C) {
ArgEffect RecEffect = getStopTrackingHardEquivalent(S->getReceiverEffect());
ArgEffect DefEffect = getStopTrackingHardEquivalent(S->getDefaultArgEffect());
ArgEffects ScratchArgs(AF.getEmptyMap());
ArgEffects CustomArgEffects = S->getArgEffects();
for (ArgEffects::iterator I = CustomArgEffects.begin(),
E = CustomArgEffects.end();
I != E; ++I) {
ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
if (Translated.getKind() != DefEffect.getKind())
ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
}
RetEffect RE = RetEffect::MakeNoRetHard();
if (const IdentifierInfo *Name = C.getIdentifier()) {
if (Name->isStr("CGBitmapContextCreateWithData") ||
Name->isStr("dispatch_data_create"))
RE = S->getRetEffect();
}
return getPersistentSummary(RE, ScratchArgs, RecEffect, DefEffect);
}
void RetainSummaryManager::updateSummaryForReceiverUnconsumedSelf(
const RetainSummary *&S) {
RetainSummaryTemplate Template(S, *this);
Template->setReceiverEffect(ArgEffect(DoNothing));
Template->setRetEffect(RetEffect::MakeNoRet());
}
void RetainSummaryManager::updateSummaryForArgumentTypes(
const AnyCall &C, const RetainSummary *&RS) {
RetainSummaryTemplate Template(RS, *this);
unsigned parm_idx = 0;
for (auto pi = C.param_begin(), pe = C.param_end(); pi != pe;
++pi, ++parm_idx) {
QualType QT = (*pi)->getType();
if (RS->getArgEffects().contains(parm_idx))
continue;
ObjKind K = ObjKind::AnyObj;
if (isISLObjectRef(QT)) {
K = ObjKind::Generalized;
} else if (isOSObjectPtr(QT)) {
K = ObjKind::OS;
} else if (cocoa::isCocoaObjectRef(QT)) {
K = ObjKind::ObjC;
} else if (coreFoundation::isCFObjectRef(QT)) {
K = ObjKind::CF;
}
if (K != ObjKind::AnyObj)
Template->addArg(AF, parm_idx,
ArgEffect(RS->getDefaultArgEffect().getKind(), K));
}
}
const RetainSummary *
RetainSummaryManager::getSummary(AnyCall C,
bool HasNonZeroCallbackArg,
bool IsReceiverUnconsumedSelf,
QualType ReceiverType) {
const RetainSummary *Summ;
switch (C.getKind()) {
case AnyCall::Function:
case AnyCall::Constructor:
case AnyCall::InheritedConstructor:
case AnyCall::Allocator:
case AnyCall::Deallocator:
Summ = getFunctionSummary(cast_or_null<FunctionDecl>(C.getDecl()));
break;
case AnyCall::Block:
case AnyCall::Destructor:
return getPersistentStopSummary();
case AnyCall::ObjCMethod: {
const auto *ME = cast_or_null<ObjCMessageExpr>(C.getExpr());
if (!ME) {
Summ = getMethodSummary(cast<ObjCMethodDecl>(C.getDecl()));
} else if (ME->isInstanceMessage()) {
Summ = getInstanceMethodSummary(ME, ReceiverType);
} else {
Summ = getClassMethodSummary(ME);
}
break;
}
}
if (HasNonZeroCallbackArg)
Summ = updateSummaryForNonZeroCallbackArg(Summ, C);
if (IsReceiverUnconsumedSelf)
updateSummaryForReceiverUnconsumedSelf(Summ);
updateSummaryForArgumentTypes(C, Summ);
assert(Summ && "Unknown call type?");
return Summ;
}
const RetainSummary *
RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
if (coreFoundation::followsCreateRule(FD))
return getCFSummaryCreateRule(FD);
return getCFSummaryGetRule(FD);
}
bool RetainSummaryManager::isTrustedReferenceCountImplementation(
const Decl *FD) {
return hasRCAnnotation(FD, "rc_ownership_trusted_implementation");
}
Optional<RetainSummaryManager::BehaviorSummary>
RetainSummaryManager::canEval(const CallExpr *CE, const FunctionDecl *FD,
bool &hasTrustedImplementationAnnotation) {
IdentifierInfo *II = FD->getIdentifier();
if (!II)
return None;
StringRef FName = II->getName();
FName = FName.substr(FName.find_first_not_of('_'));
QualType ResultTy = CE->getCallReturnType(Ctx);
if (ResultTy->isObjCIdType()) {
if (II->isStr("NSMakeCollectable"))
return BehaviorSummary::Identity;
} else if (ResultTy->isPointerType()) {
if (FName == "CMBufferQueueDequeueAndRetain" ||
FName == "CMBufferQueueDequeueIfDataReadyAndRetain") {
return None;
}
if (CE->getNumArgs() == 1 &&
(cocoa::isRefType(ResultTy, "CF", FName) ||
cocoa::isRefType(ResultTy, "CG", FName) ||
cocoa::isRefType(ResultTy, "CV", FName)) &&
(isRetain(FD, FName) || isAutorelease(FD, FName) ||
isMakeCollectable(FName)))
return BehaviorSummary::Identity;
if (TrackOSObjects) {
if (isOSObjectDynamicCast(FName) && FD->param_size() >= 1) {
return BehaviorSummary::IdentityOrZero;
} else if (isOSObjectRequiredCast(FName) && FD->param_size() >= 1) {
return BehaviorSummary::Identity;
} else if (isOSObjectThisCast(FName) && isa<CXXMethodDecl>(FD) &&
!cast<CXXMethodDecl>(FD)->isStatic()) {
return BehaviorSummary::IdentityThis;
}
}
const FunctionDecl* FDD = FD->getDefinition();
if (FDD && isTrustedReferenceCountImplementation(FDD)) {
hasTrustedImplementationAnnotation = true;
return BehaviorSummary::Identity;
}
}
if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
const CXXRecordDecl *Parent = MD->getParent();
if (TrackOSObjects && Parent && isOSObjectSubclass(Parent))
if (FName == "release" || FName == "retain")
return BehaviorSummary::NoOp;
}
return None;
}
const RetainSummary *
RetainSummaryManager::getUnarySummary(const FunctionType* FT,
ArgEffectKind AE) {
ArgEffects ScratchArgs(AF.getEmptyMap());
const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
if (!FTP || FTP->getNumParams() != 1)
return getPersistentStopSummary();
ArgEffect Effect(AE, ObjKind::CF);
ScratchArgs = AF.add(ScratchArgs, 0, Effect);
return getPersistentSummary(RetEffect::MakeNoRet(),
ScratchArgs,
ArgEffect(DoNothing), ArgEffect(DoNothing));
}
const RetainSummary *
RetainSummaryManager::getOSSummaryRetainRule(const FunctionDecl *FD) {
return getPersistentSummary(RetEffect::MakeNoRet(),
AF.getEmptyMap(),
ArgEffect(DoNothing),
ArgEffect(DoNothing),
ArgEffect(IncRef, ObjKind::OS));
}
const RetainSummary *
RetainSummaryManager::getOSSummaryReleaseRule(const FunctionDecl *FD) {
return getPersistentSummary(RetEffect::MakeNoRet(),
AF.getEmptyMap(),
ArgEffect(DoNothing),
ArgEffect(DoNothing),
ArgEffect(DecRef, ObjKind::OS));
}
const RetainSummary *
RetainSummaryManager::getOSSummaryFreeRule(const FunctionDecl *FD) {
return getPersistentSummary(RetEffect::MakeNoRet(),
AF.getEmptyMap(),
ArgEffect(DoNothing),
ArgEffect(DoNothing),
ArgEffect(Dealloc, ObjKind::OS));
}
const RetainSummary *
RetainSummaryManager::getOSSummaryCreateRule(const FunctionDecl *FD) {
return getPersistentSummary(RetEffect::MakeOwned(ObjKind::OS),
AF.getEmptyMap());
}
const RetainSummary *
RetainSummaryManager::getOSSummaryGetRule(const FunctionDecl *FD) {
return getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::OS),
AF.getEmptyMap());
}
const RetainSummary *
RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF),
ArgEffects(AF.getEmptyMap()));
}
const RetainSummary *
RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
return getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::CF),
ArgEffects(AF.getEmptyMap()),
ArgEffect(DoNothing), ArgEffect(DoNothing));
}
Optional<RetEffect>
RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
const Decl *D) {
if (hasAnyEnabledAttrOf<NSReturnsRetainedAttr>(D, RetTy))
return ObjCAllocRetE;
if (auto K = hasAnyEnabledAttrOf<CFReturnsRetainedAttr, OSReturnsRetainedAttr,
GeneralizedReturnsRetainedAttr>(D, RetTy))
return RetEffect::MakeOwned(*K);
if (auto K = hasAnyEnabledAttrOf<
CFReturnsNotRetainedAttr, OSReturnsNotRetainedAttr,
GeneralizedReturnsNotRetainedAttr, NSReturnsNotRetainedAttr,
NSReturnsAutoreleasedAttr>(D, RetTy))
return RetEffect::MakeNotOwned(*K);
if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
for (const auto *PD : MD->overridden_methods())
if (auto RE = getRetEffectFromAnnotations(RetTy, PD))
return RE;
return None;
}
static bool hasTypedefNamed(QualType QT,
StringRef Name) {
while (auto *T = dyn_cast<TypedefType>(QT)) {
const auto &Context = T->getDecl()->getASTContext();
if (T->getDecl()->getIdentifier() == &Context.Idents.get(Name))
return true;
QT = T->getDecl()->getUnderlyingType();
}
return false;
}
static QualType getCallableReturnType(const NamedDecl *ND) {
if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
return FD->getReturnType();
} else if (const auto *MD = dyn_cast<ObjCMethodDecl>(ND)) {
return MD->getReturnType();
} else {
llvm_unreachable("Unexpected decl");
}
}
bool RetainSummaryManager::applyParamAnnotationEffect(
const ParmVarDecl *pd, unsigned parm_idx, const NamedDecl *FD,
RetainSummaryTemplate &Template) {
QualType QT = pd->getType();
if (auto K =
hasAnyEnabledAttrOf<NSConsumedAttr, CFConsumedAttr, OSConsumedAttr,
GeneralizedConsumedAttr>(pd, QT)) {
Template->addArg(AF, parm_idx, ArgEffect(DecRef, *K));
return true;
} else if (auto K = hasAnyEnabledAttrOf<
CFReturnsRetainedAttr, OSReturnsRetainedAttr,
OSReturnsRetainedOnNonZeroAttr, OSReturnsRetainedOnZeroAttr,
GeneralizedReturnsRetainedAttr>(pd, QT)) {
if (K == ObjKind::OS) {
QualType QT = getCallableReturnType(FD);
bool HasRetainedOnZero = pd->hasAttr<OSReturnsRetainedOnZeroAttr>();
bool HasRetainedOnNonZero = pd->hasAttr<OSReturnsRetainedOnNonZeroAttr>();
bool SuccessOnZero =
HasRetainedOnZero ||
(hasTypedefNamed(QT, "kern_return_t") && !HasRetainedOnNonZero);
bool ShouldSplit = !QT.isNull() && !QT->isVoidType();
ArgEffectKind AK = RetainedOutParameter;
if (ShouldSplit && SuccessOnZero) {
AK = RetainedOutParameterOnZero;
} else if (ShouldSplit && (!SuccessOnZero || HasRetainedOnNonZero)) {
AK = RetainedOutParameterOnNonZero;
}
Template->addArg(AF, parm_idx, ArgEffect(AK, ObjKind::OS));
}
return true;
} else if (auto K = hasAnyEnabledAttrOf<CFReturnsNotRetainedAttr,
OSReturnsNotRetainedAttr,
GeneralizedReturnsNotRetainedAttr>(
pd, QT)) {
Template->addArg(AF, parm_idx, ArgEffect(UnretainedOutParameter, *K));
return true;
}
if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
for (const auto *OD : MD->overridden_methods()) {
const ParmVarDecl *OP = OD->parameters()[parm_idx];
if (applyParamAnnotationEffect(OP, parm_idx, OD, Template))
return true;
}
}
return false;
}
void
RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
const FunctionDecl *FD) {
if (!FD)
return;
assert(Summ && "Must have a summary to add annotations to.");
RetainSummaryTemplate Template(Summ, *this);
unsigned parm_idx = 0;
for (auto pi = FD->param_begin(),
pe = FD->param_end(); pi != pe; ++pi, ++parm_idx)
applyParamAnnotationEffect(*pi, parm_idx, FD, Template);
QualType RetTy = FD->getReturnType();
if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
Template->setRetEffect(*RetE);
if (hasAnyEnabledAttrOf<OSConsumesThisAttr>(FD, RetTy))
Template->setThisEffect(ArgEffect(DecRef, ObjKind::OS));
}
void
RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
const ObjCMethodDecl *MD) {
if (!MD)
return;
assert(Summ && "Must have a valid summary to add annotations to");
RetainSummaryTemplate Template(Summ, *this);
if (hasAnyEnabledAttrOf<NSConsumesSelfAttr>(MD, MD->getReturnType()))
Template->setReceiverEffect(ArgEffect(DecRef, ObjKind::ObjC));
unsigned parm_idx = 0;
for (auto pi = MD->param_begin(), pe = MD->param_end(); pi != pe;
++pi, ++parm_idx)
applyParamAnnotationEffect(*pi, parm_idx, MD, Template);
QualType RetTy = MD->getReturnType();
if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
Template->setRetEffect(*RetE);
}
const RetainSummary *
RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
Selector S, QualType RetTy) {
ArgEffect ReceiverEff = ArgEffect(DoNothing, ObjKind::ObjC);
RetEffect ResultEff = RetEffect::MakeNoRet();
switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
case OMF_None:
case OMF_initialize:
case OMF_performSelector:
if (cocoa::isCocoaObjectRef(RetTy))
ResultEff = RetEffect::MakeNotOwned(ObjKind::ObjC);
else if (coreFoundation::isCFObjectRef(RetTy)) {
if (MD) {
switch (S.getMethodFamily()) {
case OMF_alloc:
case OMF_new:
case OMF_copy:
case OMF_mutableCopy:
ResultEff = RetEffect::MakeOwned(ObjKind::CF);
break;
default:
ResultEff = RetEffect::MakeNotOwned(ObjKind::CF);
break;
}
} else {
ResultEff = RetEffect::MakeNotOwned(ObjKind::CF);
}
}
break;
case OMF_init:
ResultEff = ObjCInitRetE;
ReceiverEff = ArgEffect(DecRef, ObjKind::ObjC);
break;
case OMF_alloc:
case OMF_new:
case OMF_copy:
case OMF_mutableCopy:
if (cocoa::isCocoaObjectRef(RetTy))
ResultEff = ObjCAllocRetE;
else if (coreFoundation::isCFObjectRef(RetTy))
ResultEff = RetEffect::MakeOwned(ObjKind::CF);
break;
case OMF_autorelease:
ReceiverEff = ArgEffect(Autorelease, ObjKind::ObjC);
break;
case OMF_retain:
ReceiverEff = ArgEffect(IncRef, ObjKind::ObjC);
break;
case OMF_release:
ReceiverEff = ArgEffect(DecRef, ObjKind::ObjC);
break;
case OMF_dealloc:
ReceiverEff = ArgEffect(Dealloc, ObjKind::ObjC);
break;
case OMF_self:
break;
case OMF_retainCount:
case OMF_finalize:
break;
}
if (S.isKeywordSelector()) {
for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
StringRef Slot = S.getNameForSlot(i);
if (Slot.substr(Slot.size() - 8).equals_insensitive("delegate")) {
if (ResultEff == ObjCInitRetE)
ResultEff = RetEffect::MakeNoRetHard();
else
ReceiverEff = ArgEffect(StopTrackingHard, ObjKind::ObjC);
}
}
}
if (ReceiverEff.getKind() == DoNothing &&
ResultEff.getKind() == RetEffect::NoRet)
return getDefaultSummary();
return getPersistentSummary(ResultEff, ArgEffects(AF.getEmptyMap()),
ArgEffect(ReceiverEff), ArgEffect(MayEscape));
}
const RetainSummary *
RetainSummaryManager::getClassMethodSummary(const ObjCMessageExpr *ME) {
assert(!ME->isInstanceMessage());
const ObjCInterfaceDecl *Class = ME->getReceiverInterface();
return getMethodSummary(ME->getSelector(), Class, ME->getMethodDecl(),
ME->getType(), ObjCClassMethodSummaries);
}
const RetainSummary *RetainSummaryManager::getInstanceMethodSummary(
const ObjCMessageExpr *ME,
QualType ReceiverType) {
const ObjCInterfaceDecl *ReceiverClass = nullptr;
if (!ReceiverType.isNull())
if (const auto *PT = ReceiverType->getAs<ObjCObjectPointerType>())
ReceiverClass = PT->getInterfaceDecl();
if (!ReceiverClass)
ReceiverClass = ME->getReceiverInterface();
Selector S = ME->getSelector();
const ObjCMethodDecl *Method = ME->getMethodDecl();
if (!Method && ReceiverClass)
Method = ReceiverClass->getInstanceMethod(S);
return getMethodSummary(S, ReceiverClass, Method, ME->getType(),
ObjCMethodSummaries);
}
const RetainSummary *
RetainSummaryManager::getMethodSummary(Selector S,
const ObjCInterfaceDecl *ID,
const ObjCMethodDecl *MD, QualType RetTy,
ObjCMethodSummariesTy &CachedSummaries) {
if (!TrackObjCAndCFObjects)
return getDefaultSummary();
const RetainSummary *Summ = CachedSummaries.find(ID, S);
if (!Summ) {
Summ = getStandardMethodSummary(MD, S, RetTy);
updateSummaryFromAnnotations(Summ, MD);
CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
}
return Summ;
}
void RetainSummaryManager::InitializeClassMethodSummaries() {
ArgEffects ScratchArgs = AF.getEmptyMap();
addClassMethSummary("NSAssertionHandler", "currentHandler",
getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::ObjC),
ScratchArgs));
ScratchArgs = AF.add(ScratchArgs, 0, ArgEffect(Autorelease));
addClassMethSummary("NSAutoreleasePool", "addObject",
getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs,
ArgEffect(DoNothing),
ArgEffect(Autorelease)));
}
void RetainSummaryManager::InitializeMethodSummaries() {
ArgEffects ScratchArgs = AF.getEmptyMap();
const RetainSummary *InitSumm = getPersistentSummary(
ObjCInitRetE, ScratchArgs, ArgEffect(DecRef, ObjKind::ObjC));
addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
InitSumm);
const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE,
ScratchArgs);
const RetainSummary *CFAllocSumm =
getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs);
RetEffect NoRet = RetEffect::MakeNoRet();
const RetainSummary *Summ = getPersistentSummary(
NoRet, ScratchArgs, ArgEffect(IncRef, ObjKind::ObjC));
addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Summ = getPersistentSummary(NoRet, ScratchArgs,
ArgEffect(DecRef, ObjKind::ObjC));
addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Summ = getPersistentSummary(NoRet, ScratchArgs, ArgEffect(Dealloc,
ObjKind::ObjC));
addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Summ = getPersistentSummary(NoRet, ScratchArgs, ArgEffect(Autorelease,
ObjKind::ObjC));
addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
const RetainSummary *NoTrackYet =
getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs,
ArgEffect(StopTracking), ArgEffect(StopTracking));
addClassMethSummary("NSWindow", "alloc", NoTrackYet);
addClassMethSummary("NSPanel", "alloc", NoTrackYet);
addClassMethSummary("NSNull", "null", NoTrackYet);
addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
addInstMethSummary("QCRenderer", AllocSumm, "createSnapshotImageOfType");
addInstMethSummary("QCView", AllocSumm, "createSnapshotImageOfType");
addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect");
addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect",
"format", "colorSpace");
addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", "info");
}
const RetainSummary *
RetainSummaryManager::getMethodSummary(const ObjCMethodDecl *MD) {
const ObjCInterfaceDecl *ID = MD->getClassInterface();
Selector S = MD->getSelector();
QualType ResultTy = MD->getReturnType();
ObjCMethodSummariesTy *CachedSummaries;
if (MD->isInstanceMethod())
CachedSummaries = &ObjCMethodSummaries;
else
CachedSummaries = &ObjCClassMethodSummaries;
return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
}