1 //== RetainSummaryManager.cpp - Summaries for reference counting --*- C++ -*--//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines summaries implementation for retain counting, which
11 // implements a reference count checker for Core Foundation, Cocoa
12 // and OSObject (on Mac OS X).
14 //===----------------------------------------------------------------------===//
16 #include "clang/StaticAnalyzer/Core/RetainSummaryManager.h"
17 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/ParentMap.h"
22 #include "clang/ASTMatchers/ASTMatchFinder.h"
24 using namespace clang;
28 constexpr static bool isOneOf() {
32 /// Helper function to check whether the class is one of the
34 template <class T, class P, class... ToCompare>
35 constexpr static bool isOneOf() {
36 return std::is_same<T, P>::value || isOneOf<T, ToCompare...>();
41 /// Fake attribute class for RC* attributes.
42 struct GeneralizedReturnsRetainedAttr {
43 static bool classof(const Attr *A) {
44 if (auto AA = dyn_cast<AnnotateAttr>(A))
45 return AA->getAnnotation() == "rc_ownership_returns_retained";
50 struct GeneralizedReturnsNotRetainedAttr {
51 static bool classof(const Attr *A) {
52 if (auto AA = dyn_cast<AnnotateAttr>(A))
53 return AA->getAnnotation() == "rc_ownership_returns_not_retained";
58 struct GeneralizedConsumedAttr {
59 static bool classof(const Attr *A) {
60 if (auto AA = dyn_cast<AnnotateAttr>(A))
61 return AA->getAnnotation() == "rc_ownership_consumed";
69 Optional<ObjKind> RetainSummaryManager::hasAnyEnabledAttrOf(const Decl *D,
72 if (isOneOf<T, CFConsumedAttr, CFReturnsRetainedAttr,
73 CFReturnsNotRetainedAttr>()) {
74 if (!TrackObjCAndCFObjects)
78 } else if (isOneOf<T, NSConsumedAttr, NSConsumesSelfAttr,
79 NSReturnsAutoreleasedAttr, NSReturnsRetainedAttr,
80 NSReturnsNotRetainedAttr, NSConsumesSelfAttr>()) {
82 if (!TrackObjCAndCFObjects)
85 if (isOneOf<T, NSReturnsRetainedAttr, NSReturnsAutoreleasedAttr,
86 NSReturnsNotRetainedAttr>() &&
87 !cocoa::isCocoaObjectRef(QT))
90 } else if (isOneOf<T, OSConsumedAttr, OSConsumesThisAttr,
91 OSReturnsNotRetainedAttr, OSReturnsRetainedAttr,
92 OSReturnsRetainedOnZeroAttr,
93 OSReturnsRetainedOnNonZeroAttr>()) {
97 } else if (isOneOf<T, GeneralizedReturnsNotRetainedAttr,
98 GeneralizedReturnsRetainedAttr,
99 GeneralizedConsumedAttr>()) {
100 K = ObjKind::Generalized;
102 llvm_unreachable("Unexpected attribute");
109 template <class T1, class T2, class... Others>
110 Optional<ObjKind> RetainSummaryManager::hasAnyEnabledAttrOf(const Decl *D,
112 if (auto Out = hasAnyEnabledAttrOf<T1>(D, QT))
114 return hasAnyEnabledAttrOf<T2, Others...>(D, QT);
117 const RetainSummary *
118 RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
119 // Unique "simple" summaries -- those without ArgEffects.
120 if (OldSumm.isSimple()) {
121 ::llvm::FoldingSetNodeID ID;
125 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
128 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
129 new (N) CachedSummaryNode(OldSumm);
130 SimpleSummaries.InsertNode(N, Pos);
133 return &N->getValue();
136 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
137 new (Summ) RetainSummary(OldSumm);
141 static bool isSubclass(const Decl *D,
142 StringRef ClassName) {
143 using namespace ast_matchers;
144 DeclarationMatcher SubclassM = cxxRecordDecl(isSameOrDerivedFrom(ClassName));
145 return !(match(SubclassM, *D, D->getASTContext()).empty());
148 static bool isOSObjectSubclass(const Decl *D) {
149 return isSubclass(D, "OSObject");
152 static bool isOSObjectDynamicCast(StringRef S) {
153 return S == "safeMetaCast";
156 static bool isOSIteratorSubclass(const Decl *D) {
157 return isSubclass(D, "OSIterator");
160 static bool hasRCAnnotation(const Decl *D, StringRef rcAnnotation) {
161 for (const auto *Ann : D->specific_attrs<AnnotateAttr>()) {
162 if (Ann->getAnnotation() == rcAnnotation)
168 static bool isRetain(const FunctionDecl *FD, StringRef FName) {
169 return FName.startswith_lower("retain") || FName.endswith_lower("retain");
172 static bool isRelease(const FunctionDecl *FD, StringRef FName) {
173 return FName.startswith_lower("release") || FName.endswith_lower("release");
176 static bool isAutorelease(const FunctionDecl *FD, StringRef FName) {
177 return FName.startswith_lower("autorelease") ||
178 FName.endswith_lower("autorelease");
181 static bool isMakeCollectable(StringRef FName) {
182 return FName.contains_lower("MakeCollectable");
185 /// A function is OSObject related if it is declared on a subclass
186 /// of OSObject, or any of the parameters is a subclass of an OSObject.
187 static bool isOSObjectRelated(const CXXMethodDecl *MD) {
188 if (isOSObjectSubclass(MD->getParent()))
191 for (ParmVarDecl *Param : MD->parameters()) {
192 QualType PT = Param->getType()->getPointeeType();
194 if (CXXRecordDecl *RD = PT->getAsCXXRecordDecl())
195 if (isOSObjectSubclass(RD))
202 const RetainSummary *
203 RetainSummaryManager::getSummaryForOSObject(const FunctionDecl *FD,
204 StringRef FName, QualType RetTy) {
205 if (RetTy->isPointerType()) {
206 const CXXRecordDecl *PD = RetTy->getPointeeType()->getAsCXXRecordDecl();
207 if (PD && isOSObjectSubclass(PD)) {
208 if (const IdentifierInfo *II = FD->getIdentifier()) {
209 if (isOSObjectDynamicCast(II->getName()))
210 return getDefaultSummary();
212 // All objects returned with functions *not* starting with
213 // get, or iterators, are returned at +1.
214 if ((!II->getName().startswith("get") &&
215 !II->getName().startswith("Get")) ||
216 isOSIteratorSubclass(PD)) {
217 return getOSSummaryCreateRule(FD);
219 return getOSSummaryGetRule(FD);
225 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
226 const CXXRecordDecl *Parent = MD->getParent();
227 if (TrackOSObjects && Parent && isOSObjectSubclass(Parent)) {
228 if (FName == "release")
229 return getOSSummaryReleaseRule(FD);
231 if (FName == "retain")
232 return getOSSummaryRetainRule(FD);
235 return getOSSummaryFreeRule(FD);
237 if (MD->getOverloadedOperator() == OO_New)
238 return getOSSummaryCreateRule(MD);
245 const RetainSummary *RetainSummaryManager::getSummaryForObjCOrCFObject(
246 const FunctionDecl *FD,
249 const FunctionType *FT,
250 bool &AllowAnnotations) {
252 ArgEffects ScratchArgs(AF.getEmptyMap());
254 std::string RetTyName = RetTy.getAsString();
255 if (FName == "pthread_create" || FName == "pthread_setspecific") {
256 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
257 // This will be addressed better with IPA.
258 return getPersistentStopSummary();
259 } else if(FName == "NSMakeCollectable") {
260 // Handle: id NSMakeCollectable(CFTypeRef)
261 AllowAnnotations = false;
262 return RetTy->isObjCIdType() ? getUnarySummary(FT, DoNothing)
263 : getPersistentStopSummary();
264 } else if (FName == "CMBufferQueueDequeueAndRetain" ||
265 FName == "CMBufferQueueDequeueIfDataReadyAndRetain") {
266 // Part of: <rdar://problem/39390714>.
267 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF),
269 ArgEffect(DoNothing),
270 ArgEffect(DoNothing));
271 } else if (FName == "CFPlugInInstanceCreate") {
272 return getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs);
273 } else if (FName == "IORegistryEntrySearchCFProperty" ||
274 (RetTyName == "CFMutableDictionaryRef" &&
275 (FName == "IOBSDNameMatching" || FName == "IOServiceMatching" ||
276 FName == "IOServiceNameMatching" ||
277 FName == "IORegistryEntryIDMatching" ||
278 FName == "IOOpenFirmwarePathMatching"))) {
279 // Part of <rdar://problem/6961230>. (IOKit)
280 // This should be addressed using a API table.
281 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs,
282 ArgEffect(DoNothing), ArgEffect(DoNothing));
283 } else if (FName == "IOServiceGetMatchingService" ||
284 FName == "IOServiceGetMatchingServices") {
285 // FIXES: <rdar://problem/6326900>
286 // This should be addressed using a API table. This strcmp is also
287 // a little gross, but there is no need to super optimize here.
288 ScratchArgs = AF.add(ScratchArgs, 1, ArgEffect(DecRef, ObjKind::CF));
289 return getPersistentSummary(RetEffect::MakeNoRet(),
291 ArgEffect(DoNothing), ArgEffect(DoNothing));
292 } else if (FName == "IOServiceAddNotification" ||
293 FName == "IOServiceAddMatchingNotification") {
294 // Part of <rdar://problem/6961230>. (IOKit)
295 // This should be addressed using a API table.
296 ScratchArgs = AF.add(ScratchArgs, 2, ArgEffect(DecRef, ObjKind::CF));
297 return getPersistentSummary(RetEffect::MakeNoRet(),
299 ArgEffect(DoNothing), ArgEffect(DoNothing));
300 } else if (FName == "CVPixelBufferCreateWithBytes") {
301 // FIXES: <rdar://problem/7283567>
302 // Eventually this can be improved by recognizing that the pixel
303 // buffer passed to CVPixelBufferCreateWithBytes is released via
304 // a callback and doing full IPA to make sure this is done correctly.
305 // FIXME: This function has an out parameter that returns an
307 ScratchArgs = AF.add(ScratchArgs, 7, ArgEffect(StopTracking));
308 return getPersistentSummary(RetEffect::MakeNoRet(),
310 ArgEffect(DoNothing), ArgEffect(DoNothing));
311 } else if (FName == "CGBitmapContextCreateWithData") {
312 // FIXES: <rdar://problem/7358899>
313 // Eventually this can be improved by recognizing that 'releaseInfo'
314 // passed to CGBitmapContextCreateWithData is released via
315 // a callback and doing full IPA to make sure this is done correctly.
316 ScratchArgs = AF.add(ScratchArgs, 8, ArgEffect(ArgEffect(StopTracking)));
317 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs,
318 ArgEffect(DoNothing), ArgEffect(DoNothing));
319 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
320 // FIXES: <rdar://problem/7283567>
321 // Eventually this can be improved by recognizing that the pixel
322 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
323 // via a callback and doing full IPA to make sure this is done
325 ScratchArgs = AF.add(ScratchArgs, 12, ArgEffect(StopTracking));
326 return getPersistentSummary(RetEffect::MakeNoRet(),
328 ArgEffect(DoNothing), ArgEffect(DoNothing));
329 } else if (FName == "VTCompressionSessionEncodeFrame") {
330 // The context argument passed to VTCompressionSessionEncodeFrame()
331 // is passed to the callback specified when creating the session
332 // (e.g. with VTCompressionSessionCreate()) which can release it.
333 // To account for this possibility, conservatively stop tracking
335 ScratchArgs = AF.add(ScratchArgs, 5, ArgEffect(StopTracking));
336 return getPersistentSummary(RetEffect::MakeNoRet(),
338 ArgEffect(DoNothing), ArgEffect(DoNothing));
339 } else if (FName == "dispatch_set_context" ||
340 FName == "xpc_connection_set_context") {
341 // <rdar://problem/11059275> - The analyzer currently doesn't have
342 // a good way to reason about the finalizer function for libdispatch.
343 // If we pass a context object that is memory managed, stop tracking it.
344 // <rdar://problem/13783514> - Same problem, but for XPC.
345 // FIXME: this hack should possibly go away once we can handle
346 // libdispatch and XPC finalizers.
347 ScratchArgs = AF.add(ScratchArgs, 1, ArgEffect(StopTracking));
348 return getPersistentSummary(RetEffect::MakeNoRet(),
350 ArgEffect(DoNothing), ArgEffect(DoNothing));
351 } else if (FName.startswith("NSLog")) {
352 return getDoNothingSummary();
353 } else if (FName.startswith("NS") &&
354 (FName.find("Insert") != StringRef::npos)) {
355 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
356 // be deallocated by NSMapRemove. (radar://11152419)
357 ScratchArgs = AF.add(ScratchArgs, 1, ArgEffect(StopTracking));
358 ScratchArgs = AF.add(ScratchArgs, 2, ArgEffect(StopTracking));
359 return getPersistentSummary(RetEffect::MakeNoRet(),
360 ScratchArgs, ArgEffect(DoNothing),
361 ArgEffect(DoNothing));
364 if (RetTy->isPointerType()) {
366 // For CoreFoundation ('CF') types.
367 if (cocoa::isRefType(RetTy, "CF", FName)) {
368 if (isRetain(FD, FName)) {
369 // CFRetain isn't supposed to be annotated. However, this may as
370 // well be a user-made "safe" CFRetain function that is incorrectly
371 // annotated as cf_returns_retained due to lack of better options.
372 // We want to ignore such annotation.
373 AllowAnnotations = false;
375 return getUnarySummary(FT, IncRef);
376 } else if (isAutorelease(FD, FName)) {
377 // The headers use cf_consumed, but we can fully model CFAutorelease
379 AllowAnnotations = false;
381 return getUnarySummary(FT, Autorelease);
382 } else if (isMakeCollectable(FName)) {
383 AllowAnnotations = false;
384 return getUnarySummary(FT, DoNothing);
386 return getCFCreateGetRuleSummary(FD);
390 // For CoreGraphics ('CG') and CoreVideo ('CV') types.
391 if (cocoa::isRefType(RetTy, "CG", FName) ||
392 cocoa::isRefType(RetTy, "CV", FName)) {
393 if (isRetain(FD, FName))
394 return getUnarySummary(FT, IncRef);
396 return getCFCreateGetRuleSummary(FD);
399 // For all other CF-style types, use the Create/Get
400 // rule for summaries but don't support Retain functions
401 // with framework-specific prefixes.
402 if (coreFoundation::isCFObjectRef(RetTy)) {
403 return getCFCreateGetRuleSummary(FD);
406 if (FD->hasAttr<CFAuditedTransferAttr>()) {
407 return getCFCreateGetRuleSummary(FD);
411 // Check for release functions, the only kind of functions that we care
412 // about that don't return a pointer type.
413 if (FName.startswith("CG") || FName.startswith("CF")) {
415 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
417 if (isRelease(FD, FName))
418 return getUnarySummary(FT, DecRef);
420 assert(ScratchArgs.isEmpty());
421 // Remaining CoreFoundation and CoreGraphics functions.
422 // We use to assume that they all strictly followed the ownership idiom
423 // and that ownership cannot be transferred. While this is technically
424 // correct, many methods allow a tracked object to escape. For example:
426 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
427 // CFDictionaryAddValue(y, key, x);
429 // ... it is okay to use 'x' since 'y' has a reference to it
431 // We handle this and similar cases with the follow heuristic. If the
432 // function name contains "InsertValue", "SetValue", "AddValue",
433 // "AppendValue", or "SetAttribute", then we assume that arguments may
434 // "escape." This means that something else holds on to the object,
435 // allowing it be used even after its local retain count drops to 0.
437 (StrInStrNoCase(FName, "InsertValue") != StringRef::npos ||
438 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
439 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
440 StrInStrNoCase(FName, "AppendValue") != StringRef::npos ||
441 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
445 return getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs,
446 ArgEffect(DoNothing), ArgEffect(E, ObjKind::CF));
453 const RetainSummary *
454 RetainSummaryManager::generateSummary(const FunctionDecl *FD,
455 bool &AllowAnnotations) {
456 // We generate "stop" summaries for implicitly defined functions.
457 if (FD->isImplicit())
458 return getPersistentStopSummary();
460 const IdentifierInfo *II = FD->getIdentifier();
462 StringRef FName = II ? II->getName() : "";
464 // Strip away preceding '_'. Doing this here will effect all the checks
466 FName = FName.substr(FName.find_first_not_of('_'));
468 // Inspect the result type. Strip away any typedefs.
469 const auto *FT = FD->getType()->getAs<FunctionType>();
470 QualType RetTy = FT->getReturnType();
473 if (const RetainSummary *S = getSummaryForOSObject(FD, FName, RetTy))
476 if (TrackObjCAndCFObjects)
477 if (const RetainSummary *S =
478 getSummaryForObjCOrCFObject(FD, FName, RetTy, FT, AllowAnnotations))
481 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
482 if (!(TrackOSObjects && isOSObjectRelated(MD)))
483 return getPersistentSummary(RetEffect::MakeNoRet(),
484 ArgEffects(AF.getEmptyMap()),
485 ArgEffect(DoNothing),
486 ArgEffect(StopTracking),
487 ArgEffect(DoNothing));
489 return getDefaultSummary();
492 const RetainSummary *
493 RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
494 // If we don't know what function we're calling, use our default summary.
496 return getDefaultSummary();
498 // Look up a summary in our cache of FunctionDecls -> Summaries.
499 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
500 if (I != FuncSummaries.end())
503 // No summary? Generate one.
504 bool AllowAnnotations = true;
505 const RetainSummary *S = generateSummary(FD, AllowAnnotations);
507 // Annotations override defaults.
508 if (AllowAnnotations)
509 updateSummaryFromAnnotations(S, FD);
511 FuncSummaries[FD] = S;
515 //===----------------------------------------------------------------------===//
516 // Summary creation for functions (largely uses of Core Foundation).
517 //===----------------------------------------------------------------------===//
519 static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
520 switch (E.getKind()) {
523 case DecRefBridgedTransferred:
525 case UnretainedOutParameter:
526 case RetainedOutParameter:
527 case RetainedOutParameterOnZero:
528 case RetainedOutParameterOnNonZero:
531 case StopTrackingHard:
532 return E.withKind(StopTrackingHard);
534 case DecRefAndStopTrackingHard:
535 return E.withKind(DecRefAndStopTrackingHard);
537 return E.withKind(Dealloc);
540 llvm_unreachable("Unknown ArgEffect kind");
543 void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
544 const CallEvent &Call) {
545 if (Call.hasNonZeroCallbackArg()) {
546 ArgEffect RecEffect =
547 getStopTrackingHardEquivalent(S->getReceiverEffect());
548 ArgEffect DefEffect =
549 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
551 ArgEffects ScratchArgs(AF.getEmptyMap());
552 ArgEffects CustomArgEffects = S->getArgEffects();
553 for (ArgEffects::iterator I = CustomArgEffects.begin(),
554 E = CustomArgEffects.end();
556 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
557 if (Translated.getKind() != DefEffect.getKind())
558 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
561 RetEffect RE = RetEffect::MakeNoRetHard();
563 // Special cases where the callback argument CANNOT free the return value.
564 // This can generally only happen if we know that the callback will only be
565 // called when the return value is already being deallocated.
566 if (const SimpleFunctionCall *FC = dyn_cast<SimpleFunctionCall>(&Call)) {
567 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
568 // When the CGBitmapContext is deallocated, the callback here will free
569 // the associated data buffer.
570 // The callback in dispatch_data_create frees the buffer, but not
572 if (Name->isStr("CGBitmapContextCreateWithData") ||
573 Name->isStr("dispatch_data_create"))
574 RE = S->getRetEffect();
578 S = getPersistentSummary(RE, ScratchArgs, RecEffect, DefEffect);
581 // Special case '[super init];' and '[self init];'
583 // Even though calling '[super init]' without assigning the result to self
584 // and checking if the parent returns 'nil' is a bad pattern, it is common.
585 // Additionally, our Self Init checker already warns about it. To avoid
586 // overwhelming the user with messages from both checkers, we model the case
587 // of '[super init]' in cases when it is not consumed by another expression
588 // as if the call preserves the value of 'self'; essentially, assuming it can
589 // never fail and return 'nil'.
590 // Note, we don't want to just stop tracking the value since we want the
591 // RetainCount checker to report leaks and use-after-free if SelfInit checker
593 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
594 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
596 // Check if the message is not consumed, we know it will not be used in
597 // an assignment, ex: "self = [super init]".
598 const Expr *ME = MC->getOriginExpr();
599 const LocationContext *LCtx = MC->getLocationContext();
600 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
601 if (!PM.isConsumedExpr(ME)) {
602 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
603 ModifiableSummaryTemplate->setReceiverEffect(ArgEffect(DoNothing));
604 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
610 const RetainSummary *
611 RetainSummaryManager::getSummary(const CallEvent &Call,
612 QualType ReceiverType) {
613 const RetainSummary *Summ;
614 switch (Call.getKind()) {
617 case CE_CXXMemberOperator:
618 case CE_CXXConstructor:
619 case CE_CXXAllocator:
620 Summ = getFunctionSummary(cast_or_null<FunctionDecl>(Call.getDecl()));
623 case CE_CXXDestructor:
624 // FIXME: These calls are currently unsupported.
625 return getPersistentStopSummary();
626 case CE_ObjCMessage: {
627 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
628 if (Msg.isInstanceMessage())
629 Summ = getInstanceMethodSummary(Msg, ReceiverType);
631 Summ = getClassMethodSummary(Msg);
636 updateSummaryForCall(Summ, Call);
638 assert(Summ && "Unknown call type?");
643 const RetainSummary *
644 RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
645 if (coreFoundation::followsCreateRule(FD))
646 return getCFSummaryCreateRule(FD);
648 return getCFSummaryGetRule(FD);
651 bool RetainSummaryManager::isTrustedReferenceCountImplementation(
652 const FunctionDecl *FD) {
653 return hasRCAnnotation(FD, "rc_ownership_trusted_implementation");
656 Optional<RetainSummaryManager::BehaviorSummary>
657 RetainSummaryManager::canEval(const CallExpr *CE, const FunctionDecl *FD,
658 bool &hasTrustedImplementationAnnotation) {
660 IdentifierInfo *II = FD->getIdentifier();
664 StringRef FName = II->getName();
665 FName = FName.substr(FName.find_first_not_of('_'));
667 QualType ResultTy = CE->getCallReturnType(Ctx);
668 if (ResultTy->isObjCIdType()) {
669 if (II->isStr("NSMakeCollectable"))
670 return BehaviorSummary::Identity;
671 } else if (ResultTy->isPointerType()) {
672 // Handle: (CF|CG|CV)Retain
674 // It's okay to be a little sloppy here.
675 if (FName == "CMBufferQueueDequeueAndRetain" ||
676 FName == "CMBufferQueueDequeueIfDataReadyAndRetain") {
677 // Part of: <rdar://problem/39390714>.
678 // These are not retain. They just return something and retain it.
681 if (cocoa::isRefType(ResultTy, "CF", FName) ||
682 cocoa::isRefType(ResultTy, "CG", FName) ||
683 cocoa::isRefType(ResultTy, "CV", FName))
684 if (isRetain(FD, FName) || isAutorelease(FD, FName) ||
685 isMakeCollectable(FName))
686 return BehaviorSummary::Identity;
688 // safeMetaCast is called by OSDynamicCast.
689 // We assume that OSDynamicCast is either an identity (cast is OK,
690 // the input was non-zero),
691 // or that it returns zero (when the cast failed, or the input
693 if (TrackOSObjects && isOSObjectDynamicCast(FName)) {
694 return BehaviorSummary::IdentityOrZero;
697 const FunctionDecl* FDD = FD->getDefinition();
698 if (FDD && isTrustedReferenceCountImplementation(FDD)) {
699 hasTrustedImplementationAnnotation = true;
700 return BehaviorSummary::Identity;
704 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
705 const CXXRecordDecl *Parent = MD->getParent();
706 if (TrackOSObjects && Parent && isOSObjectSubclass(Parent))
707 if (FName == "release" || FName == "retain")
708 return BehaviorSummary::NoOp;
714 const RetainSummary *
715 RetainSummaryManager::getUnarySummary(const FunctionType* FT,
718 // Unary functions have no arg effects by definition.
719 ArgEffects ScratchArgs(AF.getEmptyMap());
721 // Sanity check that this is *really* a unary function. This can
722 // happen if people do weird things.
723 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
724 if (!FTP || FTP->getNumParams() != 1)
725 return getPersistentStopSummary();
727 ArgEffect Effect(AE, ObjKind::CF);
729 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
730 return getPersistentSummary(RetEffect::MakeNoRet(),
732 ArgEffect(DoNothing), ArgEffect(DoNothing));
735 const RetainSummary *
736 RetainSummaryManager::getOSSummaryRetainRule(const FunctionDecl *FD) {
737 return getPersistentSummary(RetEffect::MakeNoRet(),
739 /*ReceiverEff=*/ArgEffect(DoNothing),
740 /*DefaultEff=*/ArgEffect(DoNothing),
741 /*ThisEff=*/ArgEffect(IncRef, ObjKind::OS));
744 const RetainSummary *
745 RetainSummaryManager::getOSSummaryReleaseRule(const FunctionDecl *FD) {
746 return getPersistentSummary(RetEffect::MakeNoRet(),
748 /*ReceiverEff=*/ArgEffect(DoNothing),
749 /*DefaultEff=*/ArgEffect(DoNothing),
750 /*ThisEff=*/ArgEffect(DecRef, ObjKind::OS));
753 const RetainSummary *
754 RetainSummaryManager::getOSSummaryFreeRule(const FunctionDecl *FD) {
755 return getPersistentSummary(RetEffect::MakeNoRet(),
757 /*ReceiverEff=*/ArgEffect(DoNothing),
758 /*DefaultEff=*/ArgEffect(DoNothing),
759 /*ThisEff=*/ArgEffect(Dealloc, ObjKind::OS));
762 const RetainSummary *
763 RetainSummaryManager::getOSSummaryCreateRule(const FunctionDecl *FD) {
764 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::OS),
768 const RetainSummary *
769 RetainSummaryManager::getOSSummaryGetRule(const FunctionDecl *FD) {
770 return getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::OS),
774 const RetainSummary *
775 RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
776 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF),
777 ArgEffects(AF.getEmptyMap()));
780 const RetainSummary *
781 RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
782 return getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::CF),
783 ArgEffects(AF.getEmptyMap()),
784 ArgEffect(DoNothing), ArgEffect(DoNothing));
790 //===----------------------------------------------------------------------===//
791 // Summary creation for Selectors.
792 //===----------------------------------------------------------------------===//
795 RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
797 if (hasAnyEnabledAttrOf<NSReturnsRetainedAttr>(D, RetTy))
798 return ObjCAllocRetE;
800 if (auto K = hasAnyEnabledAttrOf<CFReturnsRetainedAttr, OSReturnsRetainedAttr,
801 GeneralizedReturnsRetainedAttr>(D, RetTy))
802 return RetEffect::MakeOwned(*K);
804 if (auto K = hasAnyEnabledAttrOf<
805 CFReturnsNotRetainedAttr, OSReturnsNotRetainedAttr,
806 GeneralizedReturnsNotRetainedAttr, NSReturnsNotRetainedAttr,
807 NSReturnsAutoreleasedAttr>(D, RetTy))
808 return RetEffect::MakeNotOwned(*K);
810 if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
811 for (const auto *PD : MD->overridden_methods())
812 if (auto RE = getRetEffectFromAnnotations(RetTy, PD))
818 /// \return Whether the chain of typedefs starting from {@code QT}
819 /// has a typedef with a given name {@code Name}.
820 static bool hasTypedefNamed(QualType QT,
822 while (auto *T = dyn_cast<TypedefType>(QT)) {
823 const auto &Context = T->getDecl()->getASTContext();
824 if (T->getDecl()->getIdentifier() == &Context.Idents.get(Name))
826 QT = T->getDecl()->getUnderlyingType();
831 static QualType getCallableReturnType(const NamedDecl *ND) {
832 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
833 return FD->getReturnType();
834 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(ND)) {
835 return MD->getReturnType();
837 llvm_unreachable("Unexpected decl");
841 bool RetainSummaryManager::applyParamAnnotationEffect(
842 const ParmVarDecl *pd, unsigned parm_idx, const NamedDecl *FD,
843 RetainSummaryTemplate &Template) {
844 QualType QT = pd->getType();
846 hasAnyEnabledAttrOf<NSConsumedAttr, CFConsumedAttr, OSConsumedAttr,
847 GeneralizedConsumedAttr>(pd, QT)) {
848 Template->addArg(AF, parm_idx, ArgEffect(DecRef, *K));
850 } else if (auto K = hasAnyEnabledAttrOf<
851 CFReturnsRetainedAttr, OSReturnsRetainedAttr,
852 OSReturnsRetainedOnNonZeroAttr, OSReturnsRetainedOnZeroAttr,
853 GeneralizedReturnsRetainedAttr>(pd, QT)) {
855 // For OSObjects, we try to guess whether the object is created based
856 // on the return value.
857 if (K == ObjKind::OS) {
858 QualType QT = getCallableReturnType(FD);
860 bool HasRetainedOnZero = pd->hasAttr<OSReturnsRetainedOnZeroAttr>();
861 bool HasRetainedOnNonZero = pd->hasAttr<OSReturnsRetainedOnNonZeroAttr>();
863 // The usual convention is to create an object on non-zero return, but
864 // it's reverted if the typedef chain has a typedef kern_return_t,
865 // because kReturnSuccess constant is defined as zero.
866 // The convention can be overwritten by custom attributes.
869 (hasTypedefNamed(QT, "kern_return_t") && !HasRetainedOnNonZero);
870 bool ShouldSplit = !QT.isNull() && !QT->isVoidType();
871 ArgEffectKind AK = RetainedOutParameter;
872 if (ShouldSplit && SuccessOnZero) {
873 AK = RetainedOutParameterOnZero;
874 } else if (ShouldSplit && (!SuccessOnZero || HasRetainedOnNonZero)) {
875 AK = RetainedOutParameterOnNonZero;
877 Template->addArg(AF, parm_idx, ArgEffect(AK, ObjKind::OS));
881 // Do nothing. Retained out parameters will either point to a +1 reference
882 // or NULL, but the way you check for failure differs depending on the
883 // API. Consequently, we don't have a good way to track them yet.
885 } else if (auto K = hasAnyEnabledAttrOf<CFReturnsNotRetainedAttr,
886 OSReturnsNotRetainedAttr,
887 GeneralizedReturnsNotRetainedAttr>(
889 Template->addArg(AF, parm_idx, ArgEffect(UnretainedOutParameter, *K));
893 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
894 for (const auto *OD : MD->overridden_methods()) {
895 const ParmVarDecl *OP = OD->parameters()[parm_idx];
896 if (applyParamAnnotationEffect(OP, parm_idx, OD, Template))
905 RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
906 const FunctionDecl *FD) {
910 assert(Summ && "Must have a summary to add annotations to.");
911 RetainSummaryTemplate Template(Summ, *this);
913 // Effects on the parameters.
914 unsigned parm_idx = 0;
915 for (auto pi = FD->param_begin(),
916 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx)
917 applyParamAnnotationEffect(*pi, parm_idx, FD, Template);
919 QualType RetTy = FD->getReturnType();
920 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
921 Template->setRetEffect(*RetE);
923 if (hasAnyEnabledAttrOf<OSConsumesThisAttr>(FD, RetTy))
924 Template->setThisEffect(ArgEffect(DecRef, ObjKind::OS));
928 RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
929 const ObjCMethodDecl *MD) {
933 assert(Summ && "Must have a valid summary to add annotations to");
934 RetainSummaryTemplate Template(Summ, *this);
936 // Effects on the receiver.
937 if (hasAnyEnabledAttrOf<NSConsumesSelfAttr>(MD, MD->getReturnType()))
938 Template->setReceiverEffect(ArgEffect(DecRef, ObjKind::ObjC));
940 // Effects on the parameters.
941 unsigned parm_idx = 0;
942 for (auto pi = MD->param_begin(), pe = MD->param_end(); pi != pe;
944 applyParamAnnotationEffect(*pi, parm_idx, MD, Template);
946 QualType RetTy = MD->getReturnType();
947 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
948 Template->setRetEffect(*RetE);
951 const RetainSummary *
952 RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
953 Selector S, QualType RetTy) {
954 // Any special effects?
955 ArgEffect ReceiverEff = ArgEffect(DoNothing, ObjKind::ObjC);
956 RetEffect ResultEff = RetEffect::MakeNoRet();
958 // Check the method family, and apply any default annotations.
959 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
962 case OMF_performSelector:
963 // Assume all Objective-C methods follow Cocoa Memory Management rules.
964 // FIXME: Does the non-threaded performSelector family really belong here?
965 // The selector could be, say, @selector(copy).
966 if (cocoa::isCocoaObjectRef(RetTy))
967 ResultEff = RetEffect::MakeNotOwned(ObjKind::ObjC);
968 else if (coreFoundation::isCFObjectRef(RetTy)) {
969 // ObjCMethodDecl currently doesn't consider CF objects as valid return
970 // values for alloc, new, copy, or mutableCopy, so we have to
971 // double-check with the selector. This is ugly, but there aren't that
972 // many Objective-C methods that return CF objects, right?
974 switch (S.getMethodFamily()) {
978 case OMF_mutableCopy:
979 ResultEff = RetEffect::MakeOwned(ObjKind::CF);
982 ResultEff = RetEffect::MakeNotOwned(ObjKind::CF);
986 ResultEff = RetEffect::MakeNotOwned(ObjKind::CF);
991 ResultEff = ObjCInitRetE;
992 ReceiverEff = ArgEffect(DecRef, ObjKind::ObjC);
997 case OMF_mutableCopy:
998 if (cocoa::isCocoaObjectRef(RetTy))
999 ResultEff = ObjCAllocRetE;
1000 else if (coreFoundation::isCFObjectRef(RetTy))
1001 ResultEff = RetEffect::MakeOwned(ObjKind::CF);
1003 case OMF_autorelease:
1004 ReceiverEff = ArgEffect(Autorelease, ObjKind::ObjC);
1007 ReceiverEff = ArgEffect(IncRef, ObjKind::ObjC);
1010 ReceiverEff = ArgEffect(DecRef, ObjKind::ObjC);
1013 ReceiverEff = ArgEffect(Dealloc, ObjKind::ObjC);
1016 // -self is handled specially by the ExprEngine to propagate the receiver.
1018 case OMF_retainCount:
1020 // These methods don't return objects.
1024 // If one of the arguments in the selector has the keyword 'delegate' we
1025 // should stop tracking the reference count for the receiver. This is
1026 // because the reference count is quite possibly handled by a delegate
1028 if (S.isKeywordSelector()) {
1029 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1030 StringRef Slot = S.getNameForSlot(i);
1031 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1032 if (ResultEff == ObjCInitRetE)
1033 ResultEff = RetEffect::MakeNoRetHard();
1035 ReceiverEff = ArgEffect(StopTrackingHard, ObjKind::ObjC);
1040 if (ReceiverEff.getKind() == DoNothing &&
1041 ResultEff.getKind() == RetEffect::NoRet)
1042 return getDefaultSummary();
1044 return getPersistentSummary(ResultEff, ArgEffects(AF.getEmptyMap()),
1045 ArgEffect(ReceiverEff), ArgEffect(MayEscape));
1048 const RetainSummary *RetainSummaryManager::getInstanceMethodSummary(
1049 const ObjCMethodCall &Msg,
1050 QualType ReceiverType) {
1051 const ObjCInterfaceDecl *ReceiverClass = nullptr;
1053 // We do better tracking of the type of the object than the core ExprEngine.
1054 // See if we have its type in our private state.
1055 if (!ReceiverType.isNull())
1056 if (const auto *PT = ReceiverType->getAs<ObjCObjectPointerType>())
1057 ReceiverClass = PT->getInterfaceDecl();
1059 // If we don't know what kind of object this is, fall back to its static type.
1061 ReceiverClass = Msg.getReceiverInterface();
1063 // FIXME: The receiver could be a reference to a class, meaning that
1064 // we should use the class method.
1065 // id x = [NSObject class];
1066 // [x performSelector:... withObject:... afterDelay:...];
1067 Selector S = Msg.getSelector();
1068 const ObjCMethodDecl *Method = Msg.getDecl();
1069 if (!Method && ReceiverClass)
1070 Method = ReceiverClass->getInstanceMethod(S);
1072 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1073 ObjCMethodSummaries);
1076 const RetainSummary *
1077 RetainSummaryManager::getMethodSummary(Selector S,
1078 const ObjCInterfaceDecl *ID,
1079 const ObjCMethodDecl *MD, QualType RetTy,
1080 ObjCMethodSummariesTy &CachedSummaries) {
1082 // Objective-C method summaries are only applicable to ObjC and CF objects.
1083 if (!TrackObjCAndCFObjects)
1084 return getDefaultSummary();
1086 // Look up a summary in our summary cache.
1087 const RetainSummary *Summ = CachedSummaries.find(ID, S);
1090 Summ = getStandardMethodSummary(MD, S, RetTy);
1092 // Annotations override defaults.
1093 updateSummaryFromAnnotations(Summ, MD);
1095 // Memoize the summary.
1096 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
1102 void RetainSummaryManager::InitializeClassMethodSummaries() {
1103 ArgEffects ScratchArgs = AF.getEmptyMap();
1105 // Create the [NSAssertionHandler currentHander] summary.
1106 addClassMethSummary("NSAssertionHandler", "currentHandler",
1107 getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::ObjC),
1110 // Create the [NSAutoreleasePool addObject:] summary.
1111 ScratchArgs = AF.add(ScratchArgs, 0, ArgEffect(Autorelease));
1112 addClassMethSummary("NSAutoreleasePool", "addObject",
1113 getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs,
1114 ArgEffect(DoNothing),
1115 ArgEffect(Autorelease)));
1118 void RetainSummaryManager::InitializeMethodSummaries() {
1120 ArgEffects ScratchArgs = AF.getEmptyMap();
1121 // Create the "init" selector. It just acts as a pass-through for the
1123 const RetainSummary *InitSumm = getPersistentSummary(
1124 ObjCInitRetE, ScratchArgs, ArgEffect(DecRef, ObjKind::ObjC));
1125 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1127 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1128 // claims the receiver and returns a retained object.
1129 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1132 // The next methods are allocators.
1133 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE,
1135 const RetainSummary *CFAllocSumm =
1136 getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs);
1138 // Create the "retain" selector.
1139 RetEffect NoRet = RetEffect::MakeNoRet();
1140 const RetainSummary *Summ = getPersistentSummary(
1141 NoRet, ScratchArgs, ArgEffect(IncRef, ObjKind::ObjC));
1142 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
1144 // Create the "release" selector.
1145 Summ = getPersistentSummary(NoRet, ScratchArgs,
1146 ArgEffect(DecRef, ObjKind::ObjC));
1147 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
1149 // Create the -dealloc summary.
1150 Summ = getPersistentSummary(NoRet, ScratchArgs, ArgEffect(Dealloc,
1152 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
1154 // Create the "autorelease" selector.
1155 Summ = getPersistentSummary(NoRet, ScratchArgs, ArgEffect(Autorelease,
1157 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
1159 // For NSWindow, allocated objects are (initially) self-owned.
1160 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1161 // self-own themselves. However, they only do this once they are displayed.
1162 // Thus, we need to track an NSWindow's display status.
1163 // This is tracked in <rdar://problem/6062711>.
1164 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
1165 const RetainSummary *NoTrackYet =
1166 getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs,
1167 ArgEffect(StopTracking), ArgEffect(StopTracking));
1169 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1171 // For NSPanel (which subclasses NSWindow), allocated objects are not
1173 // FIXME: For now we don't track NSPanels. object for the same reason
1174 // as for NSWindow objects.
1175 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1177 // For NSNull, objects returned by +null are singletons that ignore
1178 // retain/release semantics. Just don't track them.
1179 // <rdar://problem/12858915>
1180 addClassMethSummary("NSNull", "null", NoTrackYet);
1182 // Don't track allocated autorelease pools, as it is okay to prematurely
1184 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
1185 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
1186 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
1188 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1189 addInstMethSummary("QCRenderer", AllocSumm, "createSnapshotImageOfType");
1190 addInstMethSummary("QCView", AllocSumm, "createSnapshotImageOfType");
1192 // Create summaries for CIContext, 'createCGImage' and
1193 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1194 // automatically garbage collected.
1195 addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect");
1196 addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect",
1197 "format", "colorSpace");
1198 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", "info");
1201 CallEffects CallEffects::getEffect(const ObjCMethodDecl *MD) {
1202 ASTContext &Ctx = MD->getASTContext();
1203 LangOptions L = Ctx.getLangOpts();
1204 RetainSummaryManager M(Ctx, L.ObjCAutoRefCount,
1205 /*TrackNSAndCFObjects=*/true,
1206 /*TrackOSObjects=*/false);
1207 const RetainSummary *S = M.getMethodSummary(MD);
1208 CallEffects CE(S->getRetEffect(), S->getReceiverEffect());
1209 unsigned N = MD->param_size();
1210 for (unsigned i = 0; i < N; ++i) {
1211 CE.Args.push_back(S->getArg(i));
1216 CallEffects CallEffects::getEffect(const FunctionDecl *FD) {
1217 ASTContext &Ctx = FD->getASTContext();
1218 LangOptions L = Ctx.getLangOpts();
1219 RetainSummaryManager M(Ctx, L.ObjCAutoRefCount,
1220 /*TrackNSAndCFObjects=*/true,
1221 /*TrackOSObjects=*/false);
1222 const RetainSummary *S = M.getFunctionSummary(FD);
1223 CallEffects CE(S->getRetEffect());
1224 unsigned N = FD->param_size();
1225 for (unsigned i = 0; i < N; ++i) {
1226 CE.Args.push_back(S->getArg(i));